kifaru 1.0.193 → 1.0.194

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.
@@ -57,40 +57,40 @@ import{i as e,n as t,o as n,r,t as i}from"./react-dom.B--7n7g5.js";import{_ as a
57
57
  newResult[${r}] = ${n}.value;
58
58
  }
59
59
 
60
- `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Mp,s=!_p.jitless,c=s&&Np.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?tg([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function ig(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Jp(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Zp(e,r,vp())))}),t)}var ag=I(`$ZodUnion`,(e,t)=>{gh.init(e,t),Ep(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),Ep(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Ep(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Ep(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Cp(e.source)).join(`|`)})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);if(t instanceof Promise)s.push(t),o=!0;else{if(t.issues.length===0)return t;s.push(t)}}return o?Promise.all(s).then(t=>ig(t,i,e,a)):ig(s,i,e,a)}}),og=I(`$ZodIntersection`,(e,t)=>{gh.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>cg(e,t,n)):cg(e,i,a)}});function sg(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Pp(e)&&Pp(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=sg(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=sg(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function cg(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Jp(e))return e;let r=sg(t.value,n.value);if(!r.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}var lg=I(`$ZodRecord`,(e,t)=>{gh.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Pp(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...Yp(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...Yp(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Zp(e,r,vp())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Yp(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Yp(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),ug=I(`$ZodEnum`,(e,t)=>{gh.init(e,t);let n=yp(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Ip.has(typeof e)).map(e=>typeof e==`string`?Lp(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),dg=I(`$ZodLiteral`,(e,t)=>{if(gh.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?Lp(e):e?Lp(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),fg=I(`$ZodTransform`,(e,t)=>{gh.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new gp(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new hp;return n.value=i,n}});function pg(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var mg=I(`$ZodOptional`,(e,t)=>{gh.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,Ep(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ep(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Cp(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>pg(t,e.value)):pg(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),hg=I(`$ZodNullable`,(e,t)=>{gh.init(e,t),Ep(e._zod,`optin`,()=>t.innerType._zod.optin),Ep(e._zod,`optout`,()=>t.innerType._zod.optout),Ep(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Cp(e.source)}|null)$`):void 0}),Ep(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),gg=I(`$ZodDefault`,(e,t)=>{gh.init(e,t),e._zod.optin=`optional`,Ep(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>_g(e,t)):_g(r,t)}});function _g(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var vg=I(`$ZodPrefault`,(e,t)=>{gh.init(e,t),e._zod.optin=`optional`,Ep(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),yg=I(`$ZodNonOptional`,(e,t)=>{gh.init(e,t),Ep(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>bg(t,e)):bg(i,e)}});function bg(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var xg=I(`$ZodCatch`,(e,t)=>{gh.init(e,t),Ep(e._zod,`optin`,()=>t.innerType._zod.optin),Ep(e._zod,`optout`,()=>t.innerType._zod.optout),Ep(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Zp(e,n,vp()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Zp(e,n,vp()))},input:e.value}),e.issues=[]),e)}}),Sg=I(`$ZodPipe`,(e,t)=>{gh.init(e,t),Ep(e._zod,`values`,()=>t.in._zod.values),Ep(e._zod,`optin`,()=>t.in._zod.optin),Ep(e._zod,`optout`,()=>t.out._zod.optout),Ep(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Cg(e,t.in,n)):Cg(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Cg(e,t.out,n)):Cg(r,t.out,n)}});function Cg(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var wg=I(`$ZodReadonly`,(e,t)=>{gh.init(e,t),Ep(e._zod,`propValues`,()=>t.innerType._zod.propValues),Ep(e._zod,`values`,()=>t.innerType._zod.values),Ep(e._zod,`optin`,()=>t.innerType._zod.optin),Ep(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Tg):Tg(r)}});function Tg(e){return e.value=Object.freeze(e.value),e}var Eg=I(`$ZodLazy`,(e,t)=>{gh.init(e,t),Ep(e._zod,`innerType`,()=>t.getter()),Ep(e._zod,`pattern`,()=>e._zod.innerType._zod.pattern),Ep(e._zod,`propValues`,()=>e._zod.innerType._zod.propValues),Ep(e._zod,`optin`,()=>e._zod.innerType._zod.optin??void 0),Ep(e._zod,`optout`,()=>e._zod.innerType._zod.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Dg=I(`$ZodCustom`,(e,t)=>{Zm.init(e,t),gh.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Og(t,n,r,e));Og(i,n,r,e)}});function Og(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push($p(e))}}var kg=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ag(){return new kg}var jg=Ag();function Mg(e,t){return new e({type:`string`,...L(t)})}function Ng(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...L(t)})}function Pg(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...L(t)})}function Fg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...L(t)})}function Ig(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...L(t)})}function Lg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...L(t)})}function Rg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...L(t)})}function zg(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...L(t)})}function Bg(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...L(t)})}function Vg(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...L(t)})}function Hg(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...L(t)})}function Ug(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...L(t)})}function Wg(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...L(t)})}function Gg(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...L(t)})}function Kg(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...L(t)})}function qg(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...L(t)})}function Jg(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...L(t)})}function Yg(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...L(t)})}function Xg(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...L(t)})}function Zg(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...L(t)})}function Qg(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...L(t)})}function $g(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...L(t)})}function e_(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...L(t)})}function t_(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...L(t)})}function n_(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...L(t)})}function r_(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...L(t)})}function i_(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...L(t)})}function a_(e,t){return new e({type:`number`,checks:[],...L(t)})}function o_(e,t){return new e({type:`number`,coerce:!0,checks:[],...L(t)})}function s_(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...L(t)})}function c_(e,t){return new e({type:`boolean`,...L(t)})}function l_(e,t){return new e({type:`null`,...L(t)})}function u_(e){return new e({type:`unknown`})}function d_(e,t){return new e({type:`never`,...L(t)})}function f_(e,t){return new $m({check:`less_than`,...L(t),value:e,inclusive:!1})}function p_(e,t){return new $m({check:`less_than`,...L(t),value:e,inclusive:!0})}function m_(e,t){return new eh({check:`greater_than`,...L(t),value:e,inclusive:!1})}function h_(e,t){return new eh({check:`greater_than`,...L(t),value:e,inclusive:!0})}function g_(e,t){return new th({check:`multiple_of`,...L(t),value:e})}function __(e,t){return new rh({check:`max_length`,...L(t),maximum:e})}function v_(e,t){return new ih({check:`min_length`,...L(t),minimum:e})}function y_(e,t){return new ah({check:`length_equals`,...L(t),length:e})}function b_(e,t){return new sh({check:`string_format`,format:`regex`,...L(t),pattern:e})}function x_(e){return new ch({check:`string_format`,format:`lowercase`,...L(e)})}function S_(e){return new lh({check:`string_format`,format:`uppercase`,...L(e)})}function C_(e,t){return new uh({check:`string_format`,format:`includes`,...L(t),includes:e})}function w_(e,t){return new dh({check:`string_format`,format:`starts_with`,...L(t),prefix:e})}function T_(e,t){return new fh({check:`string_format`,format:`ends_with`,...L(t),suffix:e})}function E_(e){return new ph({check:`overwrite`,tx:e})}function D_(e){return E_(t=>t.normalize(e))}function O_(){return E_(e=>e.trim())}function k_(){return E_(e=>e.toLowerCase())}function A_(){return E_(e=>e.toUpperCase())}function j_(e,t,n){return new e({type:`array`,element:t,...L(n)})}function M_(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...L(n)})}function N_(e){let t=P_(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push($p(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push($p(r))}},e(n.value,n)));return t}function P_(e,t){let n=new Zm({check:`custom`,...L(t)});return n._zod.check=e,n}var F_=I(`ZodISODateTime`,(e,t)=>{Ah.init(e,t),ov.init(e,t)});function I_(e){return t_(F_,e)}var L_=I(`ZodISODate`,(e,t)=>{jh.init(e,t),ov.init(e,t)});function R_(e){return n_(L_,e)}var z_=I(`ZodISOTime`,(e,t)=>{Mh.init(e,t),ov.init(e,t)});function B_(e){return r_(z_,e)}var V_=I(`ZodISODuration`,(e,t)=>{Nh.init(e,t),ov.init(e,t)});function H_(e){return i_(V_,e)}var U_=(e,t)=>{tm.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>im(e,t)},flatten:{value:t=>rm(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,bp,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,bp,2)}},isEmpty:{get(){return e.issues.length===0}}})};I(`ZodError`,U_);var W_=I(`ZodError`,U_,{Parent:Error}),G_=am(W_),K_=om(W_),q_=sm(W_),J_=lm(W_),Y_=dm(W_),X_=fm(W_),Z_=pm(W_),Q_=mm(W_),$_=hm(W_),ev=gm(W_),tv=_m(W_),nv=vm(W_),rv=I(`ZodType`,(e,t)=>(gh.init(e,t),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>Rp(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>G_(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>q_(e,t,n),e.parseAsync=async(t,n)=>K_(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>J_(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Y_(e,t,n),e.decode=(t,n)=>X_(e,t,n),e.encodeAsync=async(t,n)=>Z_(e,t,n),e.decodeAsync=async(t,n)=>Q_(e,t,n),e.safeEncode=(t,n)=>$_(e,t,n),e.safeDecode=(t,n)=>ev(e,t,n),e.safeEncodeAsync=async(t,n)=>tv(e,t,n),e.safeDecodeAsync=async(t,n)=>nv(e,t,n),e.refine=(t,n)=>e.check(hy(t,n)),e.superRefine=t=>e.check(gy(t)),e.overwrite=t=>e.check(E_(t)),e.optional=()=>Zv(e),e.nullable=()=>$v(e),e.nullish=()=>Zv($v(e)),e.nonoptional=t=>ay(e,t),e.array=()=>B(e),e.or=t=>Bv([e,t]),e.and=t=>Hv(e,t),e.transform=t=>ly(e,Yv(t)),e.default=t=>ty(e,t),e.prefault=t=>ry(e,t),e.catch=t=>sy(e,t),e.pipe=t=>ly(e,t),e.readonly=()=>dy(e),e.describe=t=>{let n=e.clone();return jg.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return jg.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return jg.get(e);let n=e.clone();return jg.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),iv=I(`_ZodString`,(e,t)=>{_h.init(e,t),rv.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(b_(...t)),e.includes=(...t)=>e.check(C_(...t)),e.startsWith=(...t)=>e.check(w_(...t)),e.endsWith=(...t)=>e.check(T_(...t)),e.min=(...t)=>e.check(v_(...t)),e.max=(...t)=>e.check(__(...t)),e.length=(...t)=>e.check(y_(...t)),e.nonempty=(...t)=>e.check(v_(1,...t)),e.lowercase=t=>e.check(x_(t)),e.uppercase=t=>e.check(S_(t)),e.trim=()=>e.check(O_()),e.normalize=(...t)=>e.check(D_(...t)),e.toLowerCase=()=>e.check(k_()),e.toUpperCase=()=>e.check(A_())}),av=I(`ZodString`,(e,t)=>{_h.init(e,t),iv.init(e,t),e.email=t=>e.check(Ng(sv,t)),e.url=t=>e.check(zg(uv,t)),e.jwt=t=>e.check(e_(Tv,t)),e.emoji=t=>e.check(Bg(dv,t)),e.guid=t=>e.check(Pg(cv,t)),e.uuid=t=>e.check(Fg(lv,t)),e.uuidv4=t=>e.check(Ig(lv,t)),e.uuidv6=t=>e.check(Lg(lv,t)),e.uuidv7=t=>e.check(Rg(lv,t)),e.nanoid=t=>e.check(Vg(fv,t)),e.guid=t=>e.check(Pg(cv,t)),e.cuid=t=>e.check(Hg(pv,t)),e.cuid2=t=>e.check(Ug(mv,t)),e.ulid=t=>e.check(Wg(hv,t)),e.base64=t=>e.check(Zg(Sv,t)),e.base64url=t=>e.check(Qg(Cv,t)),e.xid=t=>e.check(Gg(gv,t)),e.ksuid=t=>e.check(Kg(_v,t)),e.ipv4=t=>e.check(qg(vv,t)),e.ipv6=t=>e.check(Jg(yv,t)),e.cidrv4=t=>e.check(Yg(bv,t)),e.cidrv6=t=>e.check(Xg(xv,t)),e.e164=t=>e.check($g(wv,t)),e.datetime=t=>e.check(I_(t)),e.date=t=>e.check(R_(t)),e.time=t=>e.check(B_(t)),e.duration=t=>e.check(H_(t))});function R(e){return Mg(av,e)}var ov=I(`ZodStringFormat`,(e,t)=>{vh.init(e,t),iv.init(e,t)}),sv=I(`ZodEmail`,(e,t)=>{xh.init(e,t),ov.init(e,t)}),cv=I(`ZodGUID`,(e,t)=>{yh.init(e,t),ov.init(e,t)}),lv=I(`ZodUUID`,(e,t)=>{bh.init(e,t),ov.init(e,t)}),uv=I(`ZodURL`,(e,t)=>{Sh.init(e,t),ov.init(e,t)}),dv=I(`ZodEmoji`,(e,t)=>{Ch.init(e,t),ov.init(e,t)}),fv=I(`ZodNanoID`,(e,t)=>{wh.init(e,t),ov.init(e,t)}),pv=I(`ZodCUID`,(e,t)=>{Th.init(e,t),ov.init(e,t)}),mv=I(`ZodCUID2`,(e,t)=>{Eh.init(e,t),ov.init(e,t)}),hv=I(`ZodULID`,(e,t)=>{Dh.init(e,t),ov.init(e,t)}),gv=I(`ZodXID`,(e,t)=>{Oh.init(e,t),ov.init(e,t)}),_v=I(`ZodKSUID`,(e,t)=>{kh.init(e,t),ov.init(e,t)}),vv=I(`ZodIPv4`,(e,t)=>{Ph.init(e,t),ov.init(e,t)}),yv=I(`ZodIPv6`,(e,t)=>{Fh.init(e,t),ov.init(e,t)}),bv=I(`ZodCIDRv4`,(e,t)=>{Ih.init(e,t),ov.init(e,t)}),xv=I(`ZodCIDRv6`,(e,t)=>{Lh.init(e,t),ov.init(e,t)}),Sv=I(`ZodBase64`,(e,t)=>{zh.init(e,t),ov.init(e,t)}),Cv=I(`ZodBase64URL`,(e,t)=>{Vh.init(e,t),ov.init(e,t)}),wv=I(`ZodE164`,(e,t)=>{Hh.init(e,t),ov.init(e,t)}),Tv=I(`ZodJWT`,(e,t)=>{Wh.init(e,t),ov.init(e,t)}),Ev=I(`ZodNumber`,(e,t)=>{Gh.init(e,t),rv.init(e,t),e.gt=(t,n)=>e.check(m_(t,n)),e.gte=(t,n)=>e.check(h_(t,n)),e.min=(t,n)=>e.check(h_(t,n)),e.lt=(t,n)=>e.check(f_(t,n)),e.lte=(t,n)=>e.check(p_(t,n)),e.max=(t,n)=>e.check(p_(t,n)),e.int=t=>e.check(Ov(t)),e.safe=t=>e.check(Ov(t)),e.positive=t=>e.check(m_(0,t)),e.nonnegative=t=>e.check(h_(0,t)),e.negative=t=>e.check(f_(0,t)),e.nonpositive=t=>e.check(p_(0,t)),e.multipleOf=(t,n)=>e.check(g_(t,n)),e.step=(t,n)=>e.check(g_(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function z(e){return a_(Ev,e)}var Dv=I(`ZodNumberFormat`,(e,t)=>{Kh.init(e,t),Ev.init(e,t)});function Ov(e){return s_(Dv,e)}var kv=I(`ZodBoolean`,(e,t)=>{qh.init(e,t),rv.init(e,t)});function Av(e){return c_(kv,e)}var jv=I(`ZodNull`,(e,t)=>{Jh.init(e,t),rv.init(e,t)});function Mv(e){return l_(jv,e)}var Nv=I(`ZodUnknown`,(e,t)=>{Yh.init(e,t),rv.init(e,t)});function Pv(){return u_(Nv)}var Fv=I(`ZodNever`,(e,t)=>{Xh.init(e,t),rv.init(e,t)});function Iv(e){return d_(Fv,e)}var Lv=I(`ZodArray`,(e,t)=>{Qh.init(e,t),rv.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(v_(t,n)),e.nonempty=t=>e.check(v_(1,t)),e.max=(t,n)=>e.check(__(t,n)),e.length=(t,n)=>e.check(y_(t,n)),e.unwrap=()=>e.element});function B(e,t){return j_(Lv,e,t)}var Rv=I(`ZodObject`,(e,t)=>{rg.init(e,t),rv.init(e,t),Ep(e,`shape`,()=>t.shape),e.keyof=()=>H(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Pv()}),e.loose=()=>e.clone({...e._zod.def,catchall:Pv()}),e.strict=()=>e.clone({...e._zod.def,catchall:Iv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Up(e,t),e.safeExtend=t=>Wp(e,t),e.merge=t=>Gp(e,t),e.pick=t=>Vp(e,t),e.omit=t=>Hp(e,t),e.partial=(...t)=>Kp(Xv,e,t[0]),e.required=(...t)=>qp(iy,e,t[0])});function V(e,t){return new Rv({type:`object`,get shape(){return Op(this,`shape`,e?Dp(e):{}),this.shape},...L(t)})}var zv=I(`ZodUnion`,(e,t)=>{ag.init(e,t),rv.init(e,t),e.options=t.options});function Bv(e,t){return new zv({type:`union`,options:e,...L(t)})}var Vv=I(`ZodIntersection`,(e,t)=>{og.init(e,t),rv.init(e,t)});function Hv(e,t){return new Vv({type:`intersection`,left:e,right:t})}var Uv=I(`ZodRecord`,(e,t)=>{lg.init(e,t),rv.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Wv(e,t,n){return new Uv({type:`record`,keyType:e,valueType:t,...L(n)})}var Gv=I(`ZodEnum`,(e,t)=>{ug.init(e,t),rv.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Gv({...t,checks:[],...L(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Gv({...t,checks:[],...L(r),entries:i})}});function H(e,t){return new Gv({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...L(t)})}var Kv=I(`ZodLiteral`,(e,t)=>{dg.init(e,t),rv.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function qv(e,t){return new Kv({type:`literal`,values:Array.isArray(e)?e:[e],...L(t)})}var Jv=I(`ZodTransform`,(e,t)=>{fg.init(e,t),rv.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new gp(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push($p(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push($p(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Yv(e){return new Jv({type:`transform`,transform:e})}var Xv=I(`ZodOptional`,(e,t)=>{mg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Zv(e){return new Xv({type:`optional`,innerType:e})}var Qv=I(`ZodNullable`,(e,t)=>{hg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function $v(e){return new Qv({type:`nullable`,innerType:e})}var ey=I(`ZodDefault`,(e,t)=>{gg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ty(e,t){return new ey({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Fp(t)}})}var ny=I(`ZodPrefault`,(e,t)=>{vg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ry(e,t){return new ny({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Fp(t)}})}var iy=I(`ZodNonOptional`,(e,t)=>{yg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ay(e,t){return new iy({type:`nonoptional`,innerType:e,...L(t)})}var oy=I(`ZodCatch`,(e,t)=>{xg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function sy(e,t){return new oy({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var cy=I(`ZodPipe`,(e,t)=>{Sg.init(e,t),rv.init(e,t),e.in=t.in,e.out=t.out});function ly(e,t){return new cy({type:`pipe`,in:e,out:t})}var uy=I(`ZodReadonly`,(e,t)=>{wg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function dy(e){return new uy({type:`readonly`,innerType:e})}var fy=I(`ZodLazy`,(e,t)=>{Eg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.getter()});function py(e){return new fy({type:`lazy`,getter:e})}var my=I(`ZodCustom`,(e,t)=>{Dg.init(e,t),rv.init(e,t)});function hy(e,t={}){return M_(my,e,t)}function gy(e){return N_(e)}function _y(e){let t=py(()=>Bv([R(e),z(),Av(),Mv(),B(t),Wv(R(),t)]));return t}function vy(e){return o_(Ev,e)}var U=R().uuid(),W=R().datetime({offset:!0}),yy=R().regex(/^[a-f0-9]{64}$/);R().trim().min(1);var by=H([`owner`,`admin`,`security_manager`,`operator`,`viewer`,`auditor`]),xy=H([`R0`,`R1`,`R2`]),Sy=H([`public`,`internal`,`confidential`,`restricted`]);V({cursor:R().min(1).optional(),limit:vy().int().min(1).max(200).default(50)}),V({nextCursor:R().min(1).optional(),hasMore:Av()}),V({idempotencyKey:R().trim().min(8).max(200),expectedVersion:z().int().nonnegative().optional()}),V({type:R().default(`about:blank`),title:R(),status:z().int().min(400).max(599),detail:R().optional(),instance:R().optional(),code:R().regex(/^[a-z0-9_]+$/),requestId:R(),errors:B(V({path:R(),message:R(),code:R().optional()})).optional()});var Cy=V({providerId:R().nullable(),modelId:R().nullable(),inputTokens:z().int().nonnegative(),outputTokens:z().int().nonnegative(),reasoningTokens:z().int().nonnegative(),cacheReadTokens:z().int().nonnegative(),cacheWriteTokens:z().int().nonnegative(),estimatedCostUsd:z().nonnegative(),pricingSource:R().nullable(),pricingAsOf:R().nullable()}),wy=V({id:U,organizationId:U,workspaceId:U,projectId:U,runId:U.nullable(),externalSessionId:R().nullable(),createdBy:U,status:H([`active`,`waiting`,`completed`,`failed`,`cancelled`]),mode:H([`autonomous`,`guided`]),model:R().nullable(),costUsd:z().nonnegative(),usage:Cy,sensitive:Av(),createdAt:W,lastActivityAt:W}),Ty=V({id:U,sessionId:U,role:H([`user`,`assistant`,`system`,`tool`]),redactedPreview:R(),sensitivePayloadArtifactId:U.nullable(),createdAt:W}),Ey=V({id:U,sessionId:U,runId:U.nullable(),stageId:U.nullable(),externalToolCallId:R().nullable(),toolName:R().min(1),status:H([`running`,`completed`,`failed`,`cancelled`]),inputHash:yy,outputArtifactId:U.nullable(),startedAt:W,completedAt:W.nullable()});V({session:wy,messages:B(Ty),toolActivities:B(Ey)}),V({expectedRunVersion:z().int().nonnegative(),reason:R().trim().min(1).max(1e3)});var Dy=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Oy=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ky=(e,t)=>e>>>t|e<<32-t,Ay=e=>ky(e,7)^ky(e,18)^e>>>3,jy=e=>ky(e,17)^ky(e,19)^e>>>10,My=e=>ky(e,2)^ky(e,13)^ky(e,22),Ny=e=>ky(e,6)^ky(e,11)^ky(e,25),Py=(e,t,n)=>e&t^~e&n,Fy=(e,t,n)=>e&t^e&n^t&n;function Iy(e){let t=new TextEncoder().encode(e),n=Math.floor(t.length*8/4294967296),r=t.length*8>>>0,i=new Uint8Array(((t.length+8>>6)+1)*64);i.set(t),i[t.length]=128;let a=new DataView(i.buffer);a.setUint32(i.length-8,n),a.setUint32(i.length-4,r);let o=new Uint32Array(Oy),s=new Uint32Array(64);for(let e=0;e<i.length;e+=64){for(let t=0;t<16;t++)s[t]=a.getUint32(e+t*4);for(let e=16;e<64;e++){let t=s[e-15],n=s[e-2];s[e]=jy(n)+s[e-7]+Ay(t)+s[e-16]>>>0}let t=o[0],n=o[1],r=o[2],i=o[3],c=o[4],l=o[5],u=o[6],d=o[7];for(let e=0;e<64;e++){let a=d+Ny(c)+Py(c,l,u)+Dy[e]+s[e]>>>0,o=My(t)+Fy(t,n,r)>>>0;d=u,u=l,l=c,c=i+a>>>0,i=r,r=n,n=t,t=a+o>>>0}o[0]=o[0]+t>>>0,o[1]=o[1]+n>>>0,o[2]=o[2]+r>>>0,o[3]=o[3]+i>>>0,o[4]=o[4]+c>>>0,o[5]=o[5]+l>>>0,o[6]=o[6]+u>>>0,o[7]=o[7]+d>>>0}let c=``;for(let e=0;e<8;e++)c+=o[e].toString(16).padStart(8,`0`);return c}var Ly=H([`informational`,`low`,`medium`,`high`,`critical`]),Ry=H([`clean`,`informational`,`actionable`,`critical`]),zy=V({fingerprint:yy.optional(),title:R().min(1),severity:H([`info`,`low`,`medium`,`high`,`critical`]),details:R().default(``),targetUrl:R().optional(),cvss:R().default(``),cweId:R().default(``),invariant:R().default(``),rootCause:R().default(``),impact:R().default(``),reproduction:B(R().min(1)).default([]),remediation:R().default(``),disposition:H([`candidate`,`confirmed`,`refuted`,`inconclusive`]).default(`candidate`),evidenceRefs:B(yy).default([])}),By=V({description:R().min(1),artifactType:R().min(1),data:_y().refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=65536,{message:`Evidence metadata must not exceed 64 KiB.`}).default(null),timestamp:z().int().nonnegative(),stageId:U.optional(),agentSessionId:U.optional()}),Vy=H([`observation`,`artifact`,`control_result`,`manual_confirmation`,`report`]),Hy=V({fingerprint:yy,title:R().min(1),description:R().default(``),severity:Ly,cvss:R().default(``),cweId:R().default(``),invariant:R().default(``),rootCause:R().default(``),impact:R().default(``),reproduction:B(R()).default([]),remediation:R().default(``),targetUrl:R().optional(),disposition:H([`candidate`,`confirmed`,`refuted`,`inconclusive`]),evidenceRefs:B(yy).default([]),status:H([`open`]).default(`open`)}).strict(),Uy=V({fingerprint:yy,kind:Vy,title:R().min(1),summary:R().default(``),artifactType:R(),sha256:yy,timestamp:z().int().nonnegative(),stageId:U.optional(),agentSessionId:U.optional(),classification:Sy.default(`confidential`)}).strict(),Wy=V({satisfied:Av(),missing:B(R())}).strict(),Gy=V({id:U,runId:U,projectId:U,workflowKey:R().min(1),workflowVersionId:U,version:z().int().nonnegative(),contentHash:yy,target:R().min(1),scopeOrigins:B(R()).default([]),summary:R().default(``),posture:Ry,findings:B(Hy).default([]),unverifiedLeads:B(Hy).default([]),evidence:B(Uy).default([]),negativeControls:B(R()).default([]),classification:Sy.default(`confidential`),publicationState:H([`draft`,`blocked`,`published`]).default(`draft`),gate:Wy,parentContentHash:yy.nullable().default(null),editorialMarkdownHash:yy.nullable().default(null),publishedAt:W.optional(),createdAt:W}).strict();V({agentSessionId:R().min(1),runId:U.optional(),stageId:U.optional(),stageKey:R().min(1),target:R().min(1),model:R().min(1)}),V({agentSessionId:R().min(1),runId:U.optional(),stageId:U.optional(),stageKey:R().min(1),description:R().min(1),artifactType:R().min(1),data:_y().refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=65536,{message:`Evidence metadata must not exceed 64 KiB.`}).default(null),timestamp:z().int().nonnegative()}),V({agentSessionId:R().min(1),runId:U.optional(),stageId:U.optional(),stageKey:R().min(1),workflowKey:R().min(1),status:H([`succeeded`,`blocked`,`inconclusive`,`failed`]),terminationReason:R().max(300).optional(),findings:z().int().nonnegative(),evidence:z().int().nonnegative(),findingItems:B(zy).default([]),evidenceItems:B(By).default([]),negativeControls:B(R().min(1).max(4e3)).max(500).default([]),toolAttempts:z().int().nonnegative(),toolsExecuted:z().int().nonnegative(),toolsErrored:z().int().nonnegative(),pricingUnknown:Av().optional()}),V({runId:U.optional(),stageId:U.optional(),stageKey:R().min(1),kind:H([`finding`,`evidence`]),index:z().int().nonnegative(),issues:B(R().max(120)).min(1).max(20)}),V({id:U,organizationId:U,name:R().trim().min(1).max(120),slug:R().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),version:z().int().nonnegative(),createdAt:W,updatedAt:W}),V({id:U,organizationId:U,workspaceId:U,name:R().trim().min(1).max(160),slug:R().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),archivedAt:W.nullable(),version:z().int().nonnegative(),createdAt:W,updatedAt:W}),V({name:R().trim().min(1).max(160),slug:R().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)});var Ky=V({id:U,kind:H([`domain`,`ip`,`cidr`,`url`,`repository`,`api`,`android`,`ios`,`custom`]),locator:R().trim().min(1).max(2048),displayName:R().trim().min(1).max(240)}),qy=V({id:U,owner:R().trim().min(1),documentArtifactId:U,validFrom:W,validUntil:W,allowedActions:B(R().min(1)).min(1),prohibitedActions:B(R().min(1)),sha256:yy}),Jy=V({requestsPerSecond:z().positive().optional(),concurrency:z().int().positive().optional(),durationSeconds:z().int().positive(),costUsd:z().nonnegative().optional(),modelTokens:z().int().nonnegative().optional()}),Yy=V({projectId:U,name:R().trim().min(1).max(160),targets:B(Ky).min(1),exclusions:B(R().trim().min(1)),authorization:qy.optional(),allowedRisk:xy,allowedActions:B(R().min(1)),prohibitedActions:B(R().min(1)),limits:Jy,requiredWorkerClass:R().trim().min(1),requiredCapabilities:B(R().trim().min(1)),credentialReferences:B(R().trim().min(1)),dataClassification:Sy,retentionPolicyId:U.optional(),notificationChannels:B(R().trim().min(1))}).extend({id:U,organizationId:U,workspaceId:U,revision:z().int().positive(),inputHash:yy,createdAt:W,createdBy:U}),Xy=H([`open`,`in_progress`,`accepted_risk`,`false_positive`,`remediated`,`verified`]);V({id:U,organizationId:U,workspaceId:U,projectId:U,title:R().min(1),description:R(),severity:H([`informational`,`low`,`medium`,`high`,`critical`]),status:Xy,fingerprint:yy,version:z().int().nonnegative(),firstSeenAt:W,lastSeenAt:W}),V({id:U,organizationId:U,workspaceId:U,projectId:U,runId:U.nullable(),stageId:U.nullable(),agentSessionId:U.nullable(),toolCallId:U.nullable(),kind:H([`observation`,`artifact`,`report`,`manual_confirmation`,`control_result`]),title:R().min(1),summary:R(),classification:Sy,artifactId:U.nullable(),sha256:yy,createdAt:W});var Zy=V({id:U,organizationId:U,workspaceId:U,projectId:U,runId:U,objectKey:R().min(1),sha256:yy,mimeType:R().min(1),size:z().int().nonnegative(),classification:Sy,createdBy:U,createdAt:W}),Qy=H([`internal-infrastructure`,`external-infrastructure`,`web-application`,`api-security`,`mobile-application`,`red-team-campaign`,`purple-team-validation`,`nist-csf-2`,`cis-controls-8-1`,`advanced-security-testing`,`remediation-validation`,`network-security-audit`]),$y=V({key:R().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),name:R().min(1),description:R().min(1),risk:xy,optional:Av().default(!1),requiredCapabilities:B(R().min(1)),skillRefs:B(R().min(1).max(80)).max(64).default([]),retrySafe:Av(),approvalCheckpoint:Av(),timeoutSeconds:z().int().positive()}),eb=V({id:U,key:Qy,version:R().regex(/^\d+\.\d+\.\d+$/),name:R().min(1),description:R().min(1),inputSchema:Wv(R(),Pv()),requiredCapabilities:B(R().min(1)),requiredIntegrations:B(R().min(1)),stages:B($y).min(1),evidenceRequirements:B(R().min(1)).min(1),completionCriteria:B(R().min(1)).min(1),publishedAt:W,contentHash:yy}),tb=V({code:H([`authorization_missing`,`authorization_expired`,`capability_missing`,`worker_missing`,`integration_missing`,`credential_missing`,`scope_invalid`,`approval_required`]),message:R().min(1),stageKey:R().optional(),capability:R().optional()}),nb=V({ready:Av(),launchState:H([`ready`,`blocked`,`awaiting_approval`]),highestRisk:xy,reasons:B(tb),matchingWorkerIds:B(U),inputHash:yy}),rb=H([`draft`,`blocked`,`awaiting_approval`,`queued`,`leased`,`running`,`cancel_requested`,`succeeded`,`failed`,`cancelled`,`expired`]),ib=H([`pending`,`blocked`,`awaiting_approval`,`queued`,`leased`,`running`,`paused`,`succeeded`,`failed`,`cancel_requested`,`cancelled`,`expired`,`skipped`]);V({projectId:U,assessmentProfileId:U,workflowKey:Qy,workflowVersionId:U,selectedStageKeys:B(R().min(1)).min(1).optional(),inputs:Wv(R(),Pv()),workerClass:R().min(1),mode:H([`autonomous`,`guided`]).default(`autonomous`)});var ab=V({id:U,organizationId:U,workspaceId:U,projectId:U,assessmentId:U,assessmentProfileId:U,workflowVersionId:U,workflowKey:Qy,requestedBy:U,state:rb,risk:xy,inputHash:yy,workerClass:R(),mode:H([`autonomous`,`guided`]),attempt:z().int().positive(),retryOfRunId:U.nullable(),agentSessionId:U.nullable(),usage:Cy,version:z().int().nonnegative(),createdAt:W,startedAt:W.nullable(),completedAt:W.nullable()}),ob=V({id:U,runId:U,key:R().min(1),position:z().int().nonnegative(),risk:xy,state:ib,workerId:U.nullable(),version:z().int().nonnegative(),startedAt:W.nullable(),completedAt:W.nullable()});V({id:z().int().positive(),runId:U,stageId:U.nullable(),type:R().min(1),payload:Wv(R(),Pv()),occurredAt:W}),V({after:z().int().nonnegative().default(0)});var sb=H([`internal-infrastructure`,`external-infrastructure`,`web-application`,`api-security`,`network-security-audit`]);V({target:R().trim().min(1).max(2048),workflowKey:sb,workflowVersionId:U,selectedStageKeys:B(R().min(1)).min(1).optional(),inputs:Wv(R(),Pv()).default({})}).extend({mode:H([`autonomous`,`guided`]).default(`autonomous`)}),V({owner:R().trim().min(2).max(200),statement:R().trim().min(20).max(2e3),validUntil:W});var cb=V({profile:Yy,authorization:qy,artifact:Zy}),lb=V({projectId:U,target:Ky,dossierKey:R().min(1),profileId:U,profileName:R().min(1),reusedProfile:Av()}),ub=V({binding:lb,readiness:nb}),db=V({binding:lb,run:ab,stages:B(ob),agentSession:wy}),fb=H([`pending`,`approved`,`rejected`,`expired`,`invalidated`]);V({id:U,organizationId:U,workspaceId:U,projectId:U,runId:U,stageId:U.nullable(),risk:xy,state:fb,requestedBy:U,requiredRole:H([`security_manager`,`owner_or_admin`]),decidedBy:U.nullable(),decisionRole:H([`owner`,`admin`,`security_manager`]).nullable(),workflowVersionId:U,inputHash:yy,scopeHash:yy,targetSetHash:yy,workerClass:R().min(1),actionSetHash:yy,expiresAt:W,decidedAt:W.nullable(),reason:R().nullable()}),V({decision:H([`approve`,`reject`]),reason:R().trim().min(1).max(2e3),passwordConfirmation:R().min(1),totpCode:R().regex(/^\d{6}$/).optional()}),V({id:U,sequence:z().int().positive(),organizationId:U,workspaceId:U,projectId:U.nullable(),actorId:U.nullable(),authSessionId:U.nullable(),action:R().min(1),resourceType:R().min(1),resourceId:R().min(1),requestId:R().min(1),correlationId:R().nullable(),ip:R().nullable(),userAgent:R().nullable(),outcome:H([`succeeded`,`denied`,`failed`]),reason:R().nullable(),beforeHash:yy.nullable(),afterHash:yy.nullable(),previousEventHash:yy.nullable(),eventHash:yy,occurredAt:W}),V({id:U,workspaceId:U,governanceDays:z().int().min(2555),assessmentDaysAfterClosure:z().int().min(1095),rawSessionDays:z().int().min(180),authSessionInvestigationDays:z().int().min(30),version:z().int().nonnegative()}),V({id:U,workspaceId:U,name:R().min(1),reason:R().min(1),resourceType:H([`assessment`,`run`,`agent_session`,`finding`,`artifact`]),resourceId:U,releasedAt:W.nullable(),createdAt:W});var pb=H([`workspace:admin`,`project:write`,`workflow:configure`,`run:launch`,`run:approve:r1`,`run:approve:r2`,`finding:write`,`session:read`,`session:read_sensitive`,`evidence:read`,`evidence:read_sensitive`,`governance:read`,`governance:write`]);V({user:V({id:U,email:R().email(),displayName:R().min(1),mfaEnrolled:Av(),createdAt:W}),organizationId:U,memberships:B(V({workspaceId:U,workspaceName:R().min(1),role:by,permissions:B(pb)})),activeWorkspaceId:U}),V({id:U,userId:U,createdAt:W,lastSeenAt:W,expiresAt:W,ip:R().nullable(),userAgent:R().nullable(),current:Av()}),V({password:R().min(1),totpCode:R().regex(/^\d{6}$/).optional()}),V({id:U,workspaceId:U,email:R().email(),role:by,expiresAt:W,acceptedAt:W.nullable(),createdAt:W});var mb=z().int().nonnegative(),hb=R().min(1),gb=H([`info`,`low`,`medium`,`high`,`critical`]),_b=H([`open`,`unverified`,`confirmed`,`remediating`,`remediated`,`verified`,`false_positive`,`accepted_risk`,`suppressed`]),vb=H([`cli`,`tui`,`web`,`github`,`system`]),yb=H([`scan`,`hunt`,`verify`,`import`]),bb=H([`queued`,`running`,`completed`,`failed`,`cancelled`]),xb=Wv(R(),Pv()),Sb=V({id:hb,workspaceID:hb,projectID:hb.nullable(),repositoryID:hb.nullable(),engagementID:hb.nullable(),targetID:hb.nullable(),parentRunID:hb.nullable(),sessionID:hb.nullable(),source:vb,kind:yb,status:bb,title:R(),requestedBy:R().nullable(),baseRevision:R().nullable(),headRevision:R().nullable(),promptRevision:R().nullable(),promptFingerprint:R().nullable(),configuration:xb.nullable(),summary:xb.nullable(),error:xb.nullable(),idempotencyKey:R().nullable(),createdAt:mb,startedAt:mb.nullable(),completedAt:mb.nullable(),updatedAt:mb}),Cb=V({runs:B(Sb),nextCursor:R().optional()}),wb=V({id:hb,fingerprint:R().min(1),title:R(),description:R().nullable(),severity:gb,status:_b,path:R().nullable(),line:z().int().nullable(),category:R().nullable(),firstSeenAt:mb,lastSeenAt:mb,updatedAt:mb}),Tb=V({findings:B(wb),total:z().int().nonnegative()}),Eb=V({id:hb,runID:hb.nullable(),operationID:hb.nullable(),kind:R(),verdict:R(),reason:R().nullable(),payload:xb.nullable(),createdAt:mb}),Db=V({finding:wb.extend({cwe:R().nullable(),cve:R().nullable(),cvssScore:z().nullable(),cvssVector:R().nullable(),remediation:R().nullable(),assignee:R().nullable(),resolvedAt:mb.nullable(),evidence:B(Eb)})}),Ob=V({id:hb,runID:hb,tool:R(),runtime:R(),status:R(),outcome:R(),title:R().nullable(),input:xb.nullable(),outputPreview:R().nullable(),error:xb.nullable(),startedAt:mb,completedAt:mb.nullable()}),kb=V({run:Sb,operations:B(Ob.omit({runID:!0})),findings:B(wb)}),Ab=V({id:hb,title:R(),kind:R(),source:R(),status:H([`running`,`failed`,`completed`]),runCount:z().int().nonnegative(),operationCount:z().int().nonnegative(),findingCount:z().int().nonnegative(),startedAt:mb,lastActivityAt:mb}),jb=V({session:Ab,runs:B(Sb),operations:B(Ob),findings:B(wb)}),Mb=V({id:hb,sequence:z().int().positive(),actorID:R().nullable(),action:R().min(1),objectType:R().min(1),objectID:R().min(1),outcome:H([`succeeded`,`denied`,`failed`]),details:xb.nullable(),createdAt:mb}),Nb=V({id:hb,workspaceId:hb,name:R(),slug:R(),archivedAt:mb.nullable(),createdAt:mb,updatedAt:mb}),Pb=V({id:hb,name:R(),role:R(),createdAt:mb,updatedAt:mb}),Fb=V({id:hb,name:R(),status:R(),capabilities:B(R()).default([]),lastSeenAt:mb.nullable()}),Ib=V({sessionId:R().nullable().optional(),runs:Wv(R(),z()),findings:V({total:z().int().nonnegative(),bySeverity:Wv(R(),z()),byStatus:Wv(R(),z())}),recentRuns:B(Sb),recentFindings:B(wb)}),Lb=V({count:z().int().nonnegative(),limit:z().int().positive(),hasMore:Av()});function Rb(e){return V({items:B(e),page:Lb})}V({workspaceId:U,clientId:U,batchId:U,records:B(V({id:U,kind:H([`agent_session`,`evidence`,`finding`,`governance_event`]),localSequence:z().int().positive(),payload:Wv(R(),Pv()),payloadHash:yy,occurredAt:W})).min(1).max(500)}),V({batchId:U,accepted:B(U),rejected:B(V({id:U,code:R(),detail:R()})),centralizedApproval:qv(!1)});var zb=H([`command_execution`,`read_files`,`write_files`,`http_request`,`run_exploit`,`dns_recon`,`state_mutation`,`skill_load`]);V({stageId:R().uuid(),workflowVersionId:R().uuid(),stageKey:R().min(1),requiredCapabilities:B(R().min(1)),allowedToolCategories:B(zb),allowedSkills:B(R().min(1).max(80)).max(64).default([]),retrySafe:Av(),timeoutMs:z().int().positive()});var Bb=V({workerClass:H([`network`,`web-api`,`mobile-lab`,`advanced-analysis`,`passive`]),capabilities:B(R().min(1)),tools:Wv(R(),R()),networkLocation:R().nullable(),devices:B(V({id:R(),platform:H([`android`,`ios`]),version:R()})),limits:V({concurrency:z().int().positive(),memoryMb:z().int().positive(),cpuMillis:z().int().positive(),durationSeconds:z().int().positive()})});V({token:R().min(32),name:R().trim().min(1).max(160),publicKey:R().min(32),capabilities:Bb}),V({expiresAt:W}),V({token:R().min(32),expiresAt:W}),V({worker:V({id:U,organizationId:U,workspaceId:U,name:R(),publicKey:R(),capabilities:Bb,status:H([`enrolling`,`online`,`offline`,`revoked`]),lastHeartbeatAt:W.nullable(),createdAt:W}),accessToken:R().min(32),expiresAt:W}),V({capabilities:Bb.optional(),runningJobIds:B(U)}),V({id:U,runId:U,stageId:U,workerId:U,leaseToken:R().min(32),leaseExpiresAt:W,attempt:z().int().positive(),payload:Wv(R(),Pv())}),V({leaseToken:R().min(32),events:B(V({idempotencyKey:R().min(8),type:R().min(1),occurredAt:W,payload:Wv(R(),Pv())})).min(1).max(500)});var Vb=V({leaseToken:R().min(32)});Vb.extend({extendSeconds:z().int().min(10).max(300).default(60)}),Vb.extend({outcome:H([`succeeded`,`failed`,`cancelled`]),summary:Wv(R(),Pv()).default({}),error:R().max(2e4).optional(),retrySafe:Av().default(!1)});function Hb(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Hb).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Hb(t[e])}`).join(`,`)}}`}function Ub(e){return Iy(typeof e==`string`?e:Hb(e))}function Wb(e){return`kifaru-workflow-${e}`}var G=(e,t,n,r,i={})=>({key:e,name:t,description:i.description??t,risk:n,optional:i.optional??!1,requiredCapabilities:r,skillRefs:i.skillRefs??(r.includes(`reporting`)?[`kifaru-vulnerability-report`]:r.some(e=>[`web-testing`,`authenticated-browser`,`api-client`,`api-security-testing`].includes(e))?[`kifaru-web-app-review`]:r.some(e=>[`mobile-static`,`mobile-device`,`mobile-proxy`].includes(e))?[`kifaru-mobile-app-review`]:[]),retrySafe:i.retrySafe??n!==`R2`,approvalCheckpoint:i.approvalCheckpoint??n!==`R0`,timeoutSeconds:i.timeoutSeconds??3600}),Gb=[{id:`10000000-0000-4000-8000-000000000101`,key:`internal-infrastructure`,name:`Internal Infrastructure Assessment`,description:`Customer-network discovery, configuration review, bounded validation, evidence capture, and reporting.`,requiredCapabilities:[`network-discovery`,`vulnerability-scanner`,`reporting`],stages:[G(`discovery`,`Discovery and inventory`,`R1`,[`network-discovery`]),G(`configuration-review`,`Configuration review`,`R1`,[`configuration-review`]),G(`vulnerability-checks`,`Vulnerability checks`,`R1`,[`vulnerability-scanner`]),G(`bounded-validation`,`Bounded validation`,`R1`,[`safe-validation`]),G(`exploitation`,`Approved exploitation`,`R2`,[`exploit-runner`],{retrySafe:!1,optional:!0}),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`host and service inventory`,`tool output with provenance`,`validation evidence`],completionCriteria:[`authorized targets accounted for`,`all executed checks have outcomes`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000102`,key:`external-infrastructure`,name:`External Infrastructure Assessment`,description:`Internet-facing inventory, DNS, TLS, exposed-service, and known-vulnerability assessment with run comparison.`,requiredCapabilities:[`dns`,`tls`,`network-discovery`,`vulnerability-scanner`,`reporting`],stages:[G(`inventory`,`Domain and IP inventory`,`R1`,[`dns`]),G(`service-discovery`,`Exposed service discovery`,`R1`,[`network-discovery`,`tls`]),G(`vulnerability-checks`,`Known-vulnerability checks`,`R1`,[`vulnerability-scanner`]),G(`comparison`,`Previous-run comparison`,`R0`,[`run-comparison`],{approvalCheckpoint:!1}),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`resolved inventory`,`service fingerprints`,`comparison baseline`],completionCriteria:[`all in-scope assets classified`,`material changes recorded`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000103`,key:`web-application`,name:`Web Application Assessment`,description:`Authenticated surface discovery, client analysis, focused testing, evidence gating, and reporting.`,requiredCapabilities:[`web-testing`,`reporting`],stages:[G(`surface-discovery`,`Surface discovery`,`R1`,[`web-testing`]),G(`authenticated-flows`,`Authenticated flow capture`,`R1`,[`authenticated-browser`],{optional:!0}),G(`client-analysis`,`Client-side analysis`,`R0`,[`source-analysis`],{approvalCheckpoint:!1}),G(`focused-testing`,`Focused vulnerability testing`,`R1`,[`web-testing`]),G(`destructive-payloads`,`Approved destructive payloads`,`R2`,[`exploit-runner`],{retrySafe:!1,optional:!0}),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`request and response provenance`,`reproduction evidence`,`negative controls`],completionCriteria:[`authenticated roles exercised`,`findings pass evidence gate`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000104`,key:`api-security`,name:`API Security Assessment`,description:`Schema import, authorization mapping, object-access and state-machine testing, and differential probes.`,requiredCapabilities:[`api-client`,`api-security-testing`,`reporting`],stages:[G(`schema-import`,`API schema and request import`,`R0`,[`openapi`],{approvalCheckpoint:!1}),G(`auth-mapping`,`Authentication and authorization mapping`,`R1`,[`api-client`]),G(`object-access`,`Object access tests`,`R1`,[`api-security-testing`]),G(`state-machine`,`State-machine checks`,`R1`,[`api-security-testing`]),G(`differential-probes`,`Differential probes`,`R1`,[`api-security-testing`]),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`imported request source`,`identity and object matrix`,`differential responses`],completionCriteria:[`declared operations accounted for`,`authorization hypotheses resolved`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000105`,key:`mobile-application`,name:`Android and iOS Assessment`,description:`Static artifact analysis with optional dynamic mobile-lab execution on registered devices.`,requiredCapabilities:[`mobile-static`,`reporting`],stages:[G(`static-analysis`,`Static artifact analysis`,`R0`,[`mobile-static`],{approvalCheckpoint:!1}),G(`dynamic-analysis`,`Dynamic device analysis`,`R1`,[`mobile-device`,`mobile-proxy`],{optional:!0}),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`artifact checksum`,`static analyzer output`,`device provenance for dynamic results`],completionCriteria:[`selected static or dynamic coverage is explicit`,`report artifact produced`],inputSchema:{coverage:{enum:[`static-only`,`full-dynamic`]}}},{id:`10000000-0000-4000-8000-000000000106`,key:`red-team-campaign`,name:`Red Team Campaign`,description:`Rules-of-engagement validation, reconnaissance, hypothesis execution, verification, and reporting.`,requiredCapabilities:[`red-team`,`reporting`],stages:[G(`roe-validation`,`Rules-of-engagement validation`,`R0`,[`authorization-review`],{approvalCheckpoint:!1}),G(`reconnaissance`,`Reconnaissance`,`R1`,[`network-discovery`]),G(`hypothesis-planning`,`Hypothesis planning`,`R0`,[`red-team`],{approvalCheckpoint:!1}),G(`execution`,`Approved campaign execution`,`R2`,[`red-team`],{retrySafe:!1}),G(`verification`,`Outcome verification`,`R1`,[`safe-validation`]),G(`reporting`,`Campaign reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`rules-of-engagement snapshot`,`action provenance`,`verification evidence`],completionCriteria:[`no persistence beyond authorization`,`all actions reconciled`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000107`,key:`purple-team-validation`,name:`Purple Team Validation`,description:`Vendor-neutral ATT&CK-aligned detection validation using signed, uploaded, or manually confirmed evidence.`,requiredCapabilities:[`detection-emulation`,`evidence-ingest`,`reporting`],stages:[G(`expectations`,`Detection expectation mapping`,`R0`,[`attack-mapping`],{approvalCheckpoint:!1}),G(`emulation`,`Controlled detection emulation`,`R1`,[`detection-emulation`]),G(`evidence-ingest`,`SIEM and EDR evidence ingest`,`R0`,[`evidence-ingest`],{approvalCheckpoint:!1}),G(`outcomes`,`Detection outcome classification`,`R0`,[`attack-mapping`],{approvalCheckpoint:!1}),G(`reporting`,`Validation reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`ATT&CK technique identifier`,`detection expectation`,`signed or attributable result`],completionCriteria:[`every expectation has a four-state outcome`,`all outcomes link evidence`]},{id:`10000000-0000-4000-8000-000000000108`,key:`nist-csf-2`,name:`NIST CSF 2.0 Assessment`,description:`Versioned CSF evidence requests, observations, gaps, applicability decisions, and maturity notes.`,requiredCapabilities:[`compliance-nist`,`evidence-ingest`,`reporting`],stages:[G(`scope`,`Framework scope and applicability`,`R0`,[`compliance-nist`],{approvalCheckpoint:!1}),G(`evidence`,`Evidence collection`,`R0`,[`evidence-ingest`],{approvalCheckpoint:!1}),G(`assessment`,`Requirement assessment`,`R0`,[`compliance-nist`],{approvalCheckpoint:!1}),G(`reporting`,`Assessment reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`pinned framework requirement`,`applicability decision`,`evidence or explicit gap`],completionCriteria:[`all applicable requirements assessed`,`output states assessment not certification`]},{id:`10000000-0000-4000-8000-000000000109`,key:`cis-controls-8-1`,name:`CIS Controls v8.1 Assessment`,description:`Implementation-group-aware evidence and test results mapped to versioned CIS safeguards.`,requiredCapabilities:[`compliance-cis`,`evidence-ingest`,`reporting`],stages:[G(`implementation-group`,`Implementation group selection`,`R0`,[`compliance-cis`],{approvalCheckpoint:!1}),G(`evidence`,`Safeguard evidence collection`,`R0`,[`evidence-ingest`],{approvalCheckpoint:!1}),G(`assessment`,`Safeguard assessment`,`R0`,[`compliance-cis`],{approvalCheckpoint:!1}),G(`reporting`,`Assessment reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`pinned safeguard`,`implementation group`,`evidence or explicit gap`],completionCriteria:[`all selected safeguards assessed`,`output states assessment not certification`]},{id:`10000000-0000-4000-8000-00000000010a`,key:`advanced-security-testing`,name:`Advanced Security Testing`,description:`Curated source, binary, firmware, protocol, smart-contract, and bounded custom testing.`,requiredCapabilities:[`advanced-analysis`,`reporting`],stages:[G(`analysis`,`Selected advanced analysis`,`R0`,[`advanced-analysis`],{approvalCheckpoint:!1}),G(`bounded-fuzzing`,`Bounded protocol fuzzing`,`R2`,[`protocol-fuzzing`],{retrySafe:!1,optional:!0}),G(`validation`,`Result validation`,`R1`,[`safe-validation`]),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`selected subtype`,`toolchain versions`,`reproducible evidence`],completionCriteria:[`unsupported stages blocked before launch`,`report artifact produced`],inputSchema:{subtype:{enum:[`source-review`,`binary-firmware`,`protocol-fuzzing`,`smart-contract`,`custom`]}}},{id:`10000000-0000-4000-8000-00000000010b`,key:`remediation-validation`,name:`Remediation Validation`,description:`Finding-led validation that reuses original scope, evidence contracts, and safe reproduction steps.`,requiredCapabilities:[`safe-validation`,`reporting`],stages:[G(`baseline`,`Original evidence baseline`,`R0`,[`evidence-ingest`],{approvalCheckpoint:!1}),G(`reproduction`,`Safe reproduction`,`R1`,[`safe-validation`]),G(`comparison`,`Before and after comparison`,`R0`,[`run-comparison`],{approvalCheckpoint:!1}),G(`finding-transition`,`Verified finding transition`,`R0`,[`finding-write`],{approvalCheckpoint:!1})],evidenceRequirements:[`original finding`,`before evidence`,`after evidence`],completionCriteria:[`only conclusive success marks verified`,`failed or inconclusive validation leaves finding open`],inputSchema:{findingIds:{type:`array`,minItems:1}}},{id:`10000000-0000-4000-8000-00000000010c`,key:`network-security-audit`,name:`Network Security Audit`,description:`Composite assessment that selects applicable child workflows and consolidates coverage and evidence.`,requiredCapabilities:[`workflow-orchestration`,`reporting`],stages:[G(`selection`,`Child workflow selection`,`R0`,[`workflow-orchestration`],{approvalCheckpoint:!1}),G(`combined-readiness`,`Combined readiness check`,`R0`,[`workflow-orchestration`],{approvalCheckpoint:!1}),G(`child-runs`,`Approved child runs`,`R1`,[`workflow-orchestration`]),G(`consolidation`,`Coverage and finding consolidation`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`child workflow versions`,`combined readiness decision`,`child run provenance`],completionCriteria:[`all selected children terminal`,`consolidated coverage identifies blocked work`],inputSchema:{childWorkflowKeys:{type:`array`,minItems:1}}}],Kb=`2026-09-06T00:00:00.000Z`;Gb.map(e=>{let t=Wb(e.key),n=e.stages.map(e=>({...e,timeoutSeconds:e.timeoutSeconds??3600,skillRefs:e.skillRefs.includes(t)?e.skillRefs:[...e.skillRefs,t]})),r={id:e.id,key:e.key,version:`1.1.0`,name:e.name,description:e.description,inputSchema:e.inputSchema??{},requiredCapabilities:e.requiredCapabilities,requiredIntegrations:e.requiredIntegrations??[],stages:n,evidenceRequirements:e.evidenceRequirements,completionCriteria:e.completionCriteria,publishedAt:Kb,contentHash:Ub({...e,stages:n})};return eb.parse(r)});var qb=V({items:B(eb)}),Jb=V({runId:R(),workflowKey:R(),target:R(),permissionMode:H([`scoped`,`yolo`]),status:R(),dbPath:R(),reportPath:R()}),Yb=V({runId:R(),workflowKey:R(),target:R(),permissionMode:H([`scoped`,`yolo`]),status:H([`queued`,`running`,`completed`,`partial`,`failed`,`cancelled`]),startedAt:z(),finishedAt:z().nullable(),error:R().nullable(),reportAvailable:Av(),stages:B(V({key:R(),name:R(),status:R(),summary:R()}))}),Xb=V({items:B(Yb)}),Zb=V({items:B(V({runId:R(),workflowKey:R(),target:R(),posture:R(),findings:z(),unverifiedLeads:z().default(0),createdAt:R()}))}),Qb=Rb(Pb),$b=Rb(Nb),ex=V({items:B(Yy)}),tx=Rb(Ab),nx=Rb(Mb),rx=Rb(Fb),ix=V({id:R(),label:R(),prefix:R().optional().default(``),tokenPrefix:R().optional(),role:R().optional().default(`admin`),workspaceId:R().optional().default(`default`),createdAt:R(),expiresAt:R().nullable().optional(),lastUsedAt:R().nullable().optional()}),ax=ix.extend({token:R()}),ox=V({items:B(ix)}),sx=V({items:B(V({version:z().int().nonnegative(),posture:R(),target:R(),contentHash:R(),classification:R(),publicationState:H([`draft`,`blocked`,`published`]),gate:V({satisfied:Av(),missing:B(R())}),publishedAt:R().nullable(),createdAt:R()}))}),cx=V({ext:R(),mimeType:R(),url:R().nullable(),rendered:Av()}),lx=V({version:z().int().nonnegative(),contentHash:R(),posture:R(),target:R(),classification:R(),record:Gy,renditions:B(cx)}),ux=V({artifacts:B(V({artifactId:R(),mimeType:R(),size:z(),sha256:R()}))}),dx=V({version:z().int().nonnegative(),contentHash:R(),posture:R()}),fx=class extends Error{status;code;constructor(e,t,n){super(n),this.status=e,this.code=t}};function px(e=fetch){async function t(t,n,r){let i=document.querySelector(`meta[name="csrf-token"]`)?.content||sessionStorage.getItem(`kifaru-csrf`)||document.cookie.split(`;`).map(e=>e.trim()).find(e=>e.startsWith(`kifaru_csrf=`))?.slice(12),a=r?.method?.toUpperCase()??`GET`,o=await e(t,{credentials:`same-origin`,...r,headers:{accept:`application/json`,...a!==`GET`&&a!==`HEAD`&&i?{"x-csrf-token":i}:{},...r?.headers}});if(!o.ok&&o.status===401&&typeof window<`u`&&!window.location.pathname.startsWith(`/login`))throw window.location.href=`/login?redirect=${encodeURIComponent(window.location.pathname+window.location.search)}`,new fx(401,`unauthorized`,`Session expired. Redirecting to login.`);let s=await o.json().catch(()=>void 0);if(!o.ok){let e=s;throw new fx(o.status,e?.code??`request_failed`,e?.detail??`Request failed.`)}return n.parse(s)}return{workflows:()=>t(`/api/v1/workflows`,qb),runs:e=>{let n=e&&typeof e==`object`&&(`limit`in e||`sessionId`in e)?e:void 0,r=new URLSearchParams;return r.set(`limit`,String(n?.limit??20)),n?.sessionId&&r.set(`sessionId`,n.sessionId),t(`/api/v1/runs?${r.toString()}`,Cb)},runDetail:e=>t(`/api/v1/runs/${encodeURIComponent(e)}`,kb),workspaces:()=>t(`/api/v1/workspaces`,Qb),projects:()=>t(`/api/v1/projects`,$b),assessmentProfiles:()=>t(`/api/v1/assessment-profiles`,ex),authorizeAssessmentProfile:(e,n)=>t(`/api/v1/assessment-profiles/${encodeURIComponent(e)}/authorization-attestations`,cb,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify(n)}),findings:e=>{let n=e&&typeof e==`object`&&(`limit`in e||`sessionId`in e||`runId`in e)?e:void 0,r=new URLSearchParams;return r.set(`limit`,String(n?.limit??50)),n?.sessionId&&r.set(`sessionId`,n.sessionId),n?.runId&&r.set(`runId`,n.runId),t(`/api/v1/findings?${r.toString()}`,Tb)},finding:e=>t(`/api/v1/findings/${encodeURIComponent(e)}`,Db),updateFindingStatus:(e,n,r)=>t(`/api/v1/findings/${encodeURIComponent(e)}/status`,Db,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({status:n,...r?{note:r}:{}})}),agentSessions:()=>t(`/api/v1/agent/sessions?limit=50`,tx),agentSession:e=>t(`/api/v1/agent/sessions/${encodeURIComponent(e)}`,jb),governanceEvents:()=>t(`/api/v1/governance/audit-events?limit=50`,nx),workers:()=>t(`/api/v1/workers`,rx),overview:e=>{let n;return typeof e==`string`?n=e:e&&typeof e==`object`&&`sessionId`in e&&typeof e.sessionId==`string`&&(n=e.sessionId),t(n?`/api/v1/overview?sessionId=${encodeURIComponent(n)}`:`/api/v1/overview`,Ib)},tokens:()=>t(`/api/v1/tokens`,ox),mintToken:e=>t(`/api/v1/tokens`,ax,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),revokeToken:e=>t(`/api/v1/tokens/${encodeURIComponent(e)}`,V({ok:Av()}),{method:`DELETE`}),targetAssessmentReadiness:e=>t(`/api/v1/assessments/readiness`,ub,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify(e)}),startTargetAssessment:e=>t(`/api/v1/assessments`,db,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify(e)}),startLocalRun:e=>t(`/api/v1/local-runs`,Jb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),localRuns:()=>t(`/api/v1/local-runs`,Xb),localRun:e=>t(`/api/v1/local-runs/${encodeURIComponent(e)}`,V({item:Yb})),localReports:()=>t(`/api/v1/local-reports`,Zb),reportVersions:e=>t(`/api/v1/runs/${encodeURIComponent(e)}/reports`,sx),reportVersion:(e,n)=>t(`/api/v1/runs/${encodeURIComponent(e)}/reports/${n}`,lx),renderReportRenditions:(e,n)=>t(`/api/v1/runs/${encodeURIComponent(e)}/reports/${n}/renditions`,ux,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify({})}),publishEditedMarkdown:(e,n,r)=>t(`/api/v1/runs/${encodeURIComponent(e)}/reports/${n}/editor`,dx,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify({markdown:r})})}}var mx=px(),hx=new Rd({defaultOptions:{queries:{staleTime:1e4,retry:2,refetchOnWindowFocus:!0}}}),gx=[{n:1,name:`Collection & Onboarding`,v:`--s1`},{n:2,name:`Storage & Security`,v:`--s2`},{n:3,name:`Use & Processing`,v:`--s3`},{n:4,name:`Sharing & Disclosure`,v:`--s4`},{n:5,name:`Retention`,v:`--s5`},{n:6,name:`Disposal & Erasure`,v:`--s6`}];function _x(e){return gx[Math.min(Math.max(e,1),gx.length)-1]}function vx(e){return e.name.split(` `)[0]}var yx=[`Governance`,`Technical`,`People & 3rd-party`,`Assurance`],bx=[`critical`,`high`,`medium`,`low`,`info`],xx={critical:0,high:1,medium:2,low:3,info:4},Sx={critical:`--crit`,high:`--high`,medium:`--med`,low:`--low`,info:`--info`},Cx={critical:`Critical`,high:`High`,medium:`Medium`,low:`Low`,info:`Info`};function wx(e){return e===`informational`?`info`:bx.includes(e)?e:`info`}function Tx(e){return e.length?[...e].sort((e,t)=>xx[e.severity]-xx[t.severity])[0].severity:null}function Ex(e){return[...e].sort((e,t)=>xx[e.severity]-xx[t.severity])}function Dx(e){return e.status!==`remediated`&&e.status!==`verified`}var Ox=/^(?:L|stage )([1-6])\s*·\s*P([0-3])\s*·\s*(.+)$/i;function kx(e,t){let n=(e??``).trim(),r=Ox.exec(n);if(r)return{stage:Number(r[1]),pillar:Number(r[2]),category:r[3],inferred:!1};let i=`${n} ${t??``}`.toLowerCase();return{stage:/sharing|disclos|transfer|cross-border|offshore|sftp|export|feed|webhook|api partner|integration/.test(i)?4:/retention|purge|backup|archive|dr site|snapshot|data lake/.test(i)?5:/eras|disposal|destroy|delete|decommission|shred/.test(i)?6:/consent|intake|onboarding|collection|telematics|form capture|survey/.test(i)?1:/encrypt|at rest|bucket|object store|database exposure|unencrypted|storage|nas|s3/.test(i)?2:3,pillar:/governance|dpia|retention schedule|policy|register|oversight|audit/.test(i)?0:/shared credential|third-party|tpa|vendor|partner|outsourc|staff|insider/.test(i)?2:1,category:n||`Agent finding`,inferred:!0}}function Ax(e){return e.map(e=>{let t=kx(e.category,e.title);return{...e,severity:wx(e.severity),stage:t.stage,pillar:t.pillar,displayCategory:t.inferred?`${t.category} (stage inferred)`:t.category,inferred:t.inferred}})}function jx(e){return Tx(e.filter(e=>e.status===`confirmed`||e.status===`verified`))}function Mx({title:e,sub:t,surface:n=!0,children:r}){return(0,b.jsxs)(`section`,{className:n?`bg-card rounded-xl border p-5`:void 0,children:[(0,b.jsxs)(`div`,{className:`mb-4 flex items-baseline justify-between gap-3`,children:[(0,b.jsx)(`h2`,{children:e}),t?(0,b.jsx)(`span`,{className:`text-muted-foreground shrink-0 text-xs`,children:t}):null]}),r]})}function Nx({children:e}){return(0,b.jsx)(`div`,{className:`kpis`,children:e})}function Px({label:e,value:t,meta:n,hero:r,tone:i}){return(0,b.jsxs)(`div`,{className:r?`kpi hero`:`kpi`,children:[(0,b.jsx)(`div`,{className:`lab`,children:e}),r?(0,b.jsxs)(`div`,{className:`posture-pill val`,style:i?{color:`var(${Sx[i]})`}:void 0,children:[(0,b.jsx)(`span`,{className:`sq`}),t]}):(0,b.jsx)(`div`,{className:`val`,children:t}),n?(0,b.jsx)(`div`,{className:`meta`,children:n}):null]})}function Fx({counts:e}){let t=Math.max(...bx.map(t=>e[t]),1);return(0,b.jsx)(`div`,{children:bx.map(n=>(0,b.jsxs)(`div`,{className:`sevrow`,children:[(0,b.jsxs)(`span`,{className:`name`,children:[(0,b.jsx)(`span`,{className:`chip`,style:{background:`var(${Sx[n]})`}}),Cx[n]]}),(0,b.jsx)(`div`,{className:`track`,children:(0,b.jsx)(`div`,{className:`fill`,"data-empty":e[n]===0,style:{width:`${e[n]/t*100}%`,background:`var(${Sx[n]})`}})}),(0,b.jsx)(`span`,{className:`n`,children:e[n]})]},n))})}function Ix({findings:e}){let t=gx.map(t=>e.filter(e=>e.stage===t.n).length),n=Math.max(...t,1);return(0,b.jsx)(`div`,{className:`stagebars`,children:gx.map((e,r)=>{let i=t[r];return(0,b.jsxs)(`div`,{className:`sbar`,children:[(0,b.jsx)(`span`,{className:`cnt`,children:i}),(0,b.jsx)(`div`,{className:`col`,style:{height:`${Math.max(i/n*112,i?10:2)}px`,background:`var(${e.v})`}}),(0,b.jsx)(`span`,{className:`idx`,children:e.n}),(0,b.jsx)(`span`,{className:`lb`,children:vx(e)})]},e.n)})})}function Lx({findings:e,onSelect:t,emptyLabel:n=`No findings.`}){return e.length?(0,b.jsx)(`div`,{className:`flist`,children:e.map(e=>{let n=_x(e.stage);return(0,b.jsxs)(`button`,{className:`frow`,type:`button`,onClick:t?()=>t(e):void 0,children:[(0,b.jsx)(`span`,{className:`sevtag sev-${e.severity}`,children:Cx[e.severity]}),(0,b.jsxs)(`span`,{children:[(0,b.jsx)(`span`,{className:`ftitle`,children:e.title}),(0,b.jsxs)(`span`,{className:`fmeta`,children:[(0,b.jsxs)(`span`,{className:`stagetag`,children:[(0,b.jsx)(`span`,{className:`d`,style:{background:`var(${n.v})`}}),`Stage `,n.n,` · `,vx(n)]}),(0,b.jsx)(`span`,{children:e.displayCategory}),e.path?(0,b.jsx)(`span`,{className:`font-mono`,children:e.path}):null]})]}),(0,b.jsx)(`span`,{className:`fright`,children:(0,b.jsx)(`span`,{className:`inline-flex shrink-0 self-start rounded-full border px-2.5 py-[3px] text-2xs font-semibold tracking-wide uppercase whitespace-nowrap text-muted-foreground`,children:e.status.replaceAll(`_`,` `)})})]},e.id)})}):(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs`,children:n})}function Rx({findings:e,selected:t,onSelect:n}){return(0,b.jsx)(`div`,{className:`chain`,children:gx.map(r=>{let i=e.filter(e=>e.stage===r.n),a=Tx(i);return(0,b.jsxs)(`button`,{className:`stagenode`,type:`button`,"aria-pressed":r.n===t,onClick:()=>n(r.n),children:[(0,b.jsx)(`div`,{className:`top`,style:{background:`var(${r.v})`}}),a?(0,b.jsx)(`span`,{className:`worst`,style:{background:`var(${Sx[a]})`}}):null,(0,b.jsxs)(`div`,{className:`sn`,children:[`STAGE `,r.n]}),(0,b.jsx)(`div`,{className:`st`,children:r.name}),(0,b.jsxs)(`div`,{className:`sc`,style:{color:`var(${r.v})`},children:[i.length,(0,b.jsxs)(`small`,{children:[`finding`,i.length===1?``:`s`]})]})]},r.n)})})}function zx({findings:e,onSelectStage:t}){return(0,b.jsx)(`div`,{style:{overflowX:`auto`},children:(0,b.jsxs)(`table`,{className:`matrix`,children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{className:`rh`}),gx.map(e=>(0,b.jsxs)(`th`,{children:[(0,b.jsx)(`span`,{className:`flex flex-wrap gap-4 text-xs font-medium`,children:(0,b.jsx)(`i`,{className:`mcap`,style:{background:`var(${e.v})`}})}),(0,b.jsx)(`br`,{}),e.n]},e.n))]})}),(0,b.jsx)(`tbody`,{children:yx.map((n,r)=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{className:`rh`,children:n}),gx.map(i=>{let a=e.filter(e=>e.pillar===r&&e.stage===i.n),o=Tx(a);return o?(0,b.jsx)(`td`,{className:`has`,style:{background:`var(${Sx[o]})`,cursor:`pointer`},title:`${a.length} open at ${n} · stage ${i.n}`,onClick:()=>t(i.n),children:a.length},i.n):(0,b.jsx)(`td`,{children:`·`},i.n)})]},n))})]})})}function Bx({items:e}){return(0,b.jsx)(`div`,{className:`my-3.5 grid grid-cols-2 gap-3 sm:grid-cols-4`,children:e.map(e=>(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`div`,{className:`k`,children:e.k}),(0,b.jsx)(`div`,{className:e.mono?`v mono`:`v`,children:e.v})]},e.k))})}function Vx({title:e,children:t}){return(0,b.jsxs)(`div`,{className:`border-[var(--hair)] mt-4 border-t pt-3.5 [&>h3]:text-muted-foreground [&>h3]:mb-2 [&>h3]:text-[11px] [&>h3]:font-semibold [&>h3]:tracking-[0.1em] [&>h3]:uppercase`,children:[(0,b.jsx)(`h3`,{children:e}),t]})}function Hx({title:e,detail:t,verdict:n}){return(0,b.jsxs)(`div`,{className:`evi`,children:[(0,b.jsxs)(`svg`,{className:`ei`,width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,b.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,b.jsx)(`path`,{d:`M14 2v6h6`})]}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`div`,{className:`et`,children:e}),(0,b.jsx)(`div`,{className:`ed`,children:t})]}),(0,b.jsx)(`span`,{className:`verdict`,children:n})]})}var Ux=v(`inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3`,{variants:{variant:{default:`bg-primary text-primary-foreground [a&]:hover:bg-primary/90`,secondary:`bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90`,destructive:`bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90`,outline:`border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,ghost:`[a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,link:`text-primary underline-offset-4 [a&]:hover:underline`,critical:`border-[color-mix(in_srgb,var(--crit)_35%,transparent)] bg-[var(--crit-bg)] text-[var(--crit)]`,high:`border-[color-mix(in_srgb,var(--high)_35%,transparent)] bg-[var(--high-bg)] text-[var(--high)]`,medium:`border-[color-mix(in_srgb,var(--med)_35%,transparent)] bg-[var(--med-bg)] text-[var(--med)]`,low:`border-[color-mix(in_srgb,var(--low)_35%,transparent)] bg-[var(--low-bg)] text-[var(--low)]`,success:`border-[color-mix(in_srgb,var(--good)_35%,transparent)] bg-[var(--good-bg)] text-[var(--good)]`,info:`bg-[var(--info-bg)] text-[var(--info)]`}},defaultVariants:{variant:`default`}}),Wx={critical:`critical`,failed:`critical`,blocked:`critical`,R2:`critical`,high:`high`,awaiting_approval:`high`,cancel_requested:`high`,R1:`high`,medium:`medium`,queued:`medium`,low:`low`,running:`low`,R0:`low`,succeeded:`success`,completed:`success`,confirmed:`success`,ok:`success`,verified:`success`,remediated:`success`,info:`info`,informational:`info`};function Gx(e){return e?Wx[e]??`secondary`:`secondary`}function Kx({className:e,variant:t=`default`,asChild:n=!1,...r}){let i=n?s:`span`;return(0,b.jsx)(i,{"data-slot":`badge`,"data-variant":t,className:a(Ux({variant:t}),e),...r})}function qx(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var Jx=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Yx=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Xx={};function Zx(e,t){return((t||Xx).jsx?Yx:Jx).test(e)}var Qx=/[ \t\n\f\r]/g;function $x(e){return typeof e==`object`?e.type===`text`&&eS(e.value):eS(e)}function eS(e){return e.replace(Qx,``)===``}var tS=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};tS.prototype.normal={},tS.prototype.property={},tS.prototype.space=void 0;function nS(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new tS(n,r,t)}function rS(e){return e.toLowerCase()}var iS=class{constructor(e,t){this.attribute=t,this.property=e}};iS.prototype.attribute=``,iS.prototype.booleanish=!1,iS.prototype.boolean=!1,iS.prototype.commaOrSpaceSeparated=!1,iS.prototype.commaSeparated=!1,iS.prototype.defined=!1,iS.prototype.mustUseProperty=!1,iS.prototype.number=!1,iS.prototype.overloadedBoolean=!1,iS.prototype.property=``,iS.prototype.spaceSeparated=!1,iS.prototype.space=void 0;var aS=e({boolean:()=>sS,booleanish:()=>cS,commaOrSpaceSeparated:()=>fS,commaSeparated:()=>dS,number:()=>K,overloadedBoolean:()=>lS,spaceSeparated:()=>uS}),oS=0,sS=pS(),cS=pS(),lS=pS(),K=pS(),uS=pS(),dS=pS(),fS=pS();function pS(){return 2**++oS}var mS=Object.keys(aS),hS=class extends iS{constructor(e,t,n,r){let i=-1;if(super(e,t),gS(this,`space`,r),typeof n==`number`)for(;++i<mS.length;){let e=mS[i];gS(this,mS[i],(n&aS[e])===aS[e])}}};hS.prototype.defined=!0;function gS(e,t,n){n&&(e[t]=n)}function _S(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new hS(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[rS(r)]=r,n[rS(a.attribute)]=r}return new tS(t,n,e.space)}var vS=_S({properties:{ariaActiveDescendant:null,ariaAtomic:cS,ariaAutoComplete:null,ariaBusy:cS,ariaChecked:cS,ariaColCount:K,ariaColIndex:K,ariaColSpan:K,ariaControls:uS,ariaCurrent:null,ariaDescribedBy:uS,ariaDetails:null,ariaDisabled:cS,ariaDropEffect:uS,ariaErrorMessage:null,ariaExpanded:cS,ariaFlowTo:uS,ariaGrabbed:cS,ariaHasPopup:null,ariaHidden:cS,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:uS,ariaLevel:K,ariaLive:null,ariaModal:cS,ariaMultiLine:cS,ariaMultiSelectable:cS,ariaOrientation:null,ariaOwns:uS,ariaPlaceholder:null,ariaPosInSet:K,ariaPressed:cS,ariaReadOnly:cS,ariaRelevant:null,ariaRequired:cS,ariaRoleDescription:uS,ariaRowCount:K,ariaRowIndex:K,ariaRowSpan:K,ariaSelected:cS,ariaSetSize:K,ariaSort:null,ariaValueMax:K,ariaValueMin:K,ariaValueNow:K,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function yS(e,t){return t in e?e[t]:t}function bS(e,t){return yS(e,t.toLowerCase())}var xS=_S({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:dS,acceptCharset:uS,accessKey:uS,action:null,allow:null,allowFullScreen:sS,allowPaymentRequest:sS,allowUserMedia:sS,alpha:sS,alt:null,as:null,async:sS,autoCapitalize:null,autoComplete:uS,autoFocus:sS,autoPlay:sS,blocking:uS,capture:null,charSet:null,checked:sS,cite:null,className:uS,closedBy:null,colorSpace:null,cols:K,colSpan:K,command:null,commandFor:null,content:null,contentEditable:cS,controls:sS,controlsList:uS,coords:K|dS,crossOrigin:null,data:null,dateTime:null,decoding:null,default:sS,defer:sS,dir:null,dirName:null,disabled:sS,download:lS,draggable:cS,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:sS,formTarget:null,headers:uS,height:K,hidden:lS,high:K,href:null,hrefLang:null,htmlFor:uS,httpEquiv:uS,id:null,imageSizes:null,imageSrcSet:null,inert:sS,inputMode:null,integrity:null,is:null,isMap:sS,itemId:null,itemProp:uS,itemRef:uS,itemScope:sS,itemType:uS,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:sS,low:K,manifest:null,max:null,maxLength:K,media:null,method:null,min:null,minLength:K,multiple:sS,muted:sS,name:null,nonce:null,noModule:sS,noValidate:sS,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:sS,optimum:K,pattern:null,ping:uS,placeholder:null,playsInline:sS,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:sS,referrerPolicy:null,rel:uS,required:sS,reversed:sS,rows:K,rowSpan:K,sandbox:uS,scope:null,scoped:sS,seamless:sS,selected:sS,shadowRootClonable:sS,shadowRootCustomElementRegistry:sS,shadowRootDelegatesFocus:sS,shadowRootMode:null,shadowRootSerializable:sS,shape:null,size:K,sizes:null,slot:null,span:K,spellCheck:cS,src:null,srcDoc:null,srcLang:null,srcSet:null,start:K,step:null,style:null,tabIndex:K,target:null,title:null,translate:null,type:null,typeMustMatch:sS,useMap:null,value:cS,width:K,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:uS,axis:null,background:null,bgColor:null,border:K,borderColor:null,bottomMargin:K,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:sS,declare:sS,event:null,face:null,frame:null,frameBorder:null,hSpace:K,leftMargin:K,link:null,longDesc:null,lowSrc:null,marginHeight:K,marginWidth:K,noResize:sS,noHref:sS,noShade:sS,noWrap:sS,object:null,profile:null,prompt:null,rev:null,rightMargin:K,rules:null,scheme:null,scrolling:cS,standby:null,summary:null,text:null,topMargin:K,valueType:null,version:null,vAlign:null,vLink:null,vSpace:K,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:sS,disablePictureInPicture:sS,disableRemotePlayback:sS,exportParts:dS,part:uS,prefix:null,property:null,results:K,security:null,unselectable:null},space:`html`,transform:bS}),SS=_S({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,maskType:`mask-type`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:fS,accentHeight:K,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:K,amplitude:K,arabicForm:null,ascent:K,attributeName:null,attributeType:null,azimuth:K,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:K,by:null,calcMode:null,capHeight:K,className:uS,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:K,diffuseConstant:K,direction:null,display:null,dur:null,divisor:K,dominantBaseline:null,download:sS,dx:null,dy:null,edgeMode:null,editable:null,elevation:K,enableBackground:null,end:null,event:null,exponent:K,externalResourcesRequired:null,fill:null,fillOpacity:K,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:dS,g2:dS,glyphName:dS,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:K,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:K,horizOriginX:K,horizOriginY:K,id:null,ideographic:K,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:K,k:K,k1:K,k2:K,k3:K,k4:K,kernelMatrix:fS,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:K,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:K,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:K,overlineThickness:K,paintOrder:null,panose1:null,path:null,pathLength:K,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:uS,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:K,pointsAtY:K,pointsAtZ:K,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:fS,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:fS,rev:fS,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:fS,requiredFeatures:fS,requiredFonts:fS,requiredFormats:fS,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:K,specularExponent:K,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:K,strikethroughThickness:K,string:null,stroke:null,strokeDashArray:fS,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:K,strokeOpacity:K,strokeWidth:null,style:null,surfaceScale:K,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:fS,tabIndex:K,tableValues:null,target:null,targetX:K,targetY:K,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:fS,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:K,underlineThickness:K,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:K,values:null,vAlphabetic:K,vMathematical:K,vectorEffect:null,vHanging:K,vIdeographic:K,version:null,vertAdvY:K,vertOriginX:K,vertOriginY:K,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:K,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:yS}),CS=_S({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),wS=_S({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:bS}),TS=_S({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),ES={classId:`classID`,dataType:`datatype`,itemId:`itemID`,strokeDashArray:`strokeDasharray`,strokeDashOffset:`strokeDashoffset`,strokeLineCap:`strokeLinecap`,strokeLineJoin:`strokeLinejoin`,strokeMiterLimit:`strokeMiterlimit`,typeOf:`typeof`,xLinkActuate:`xlinkActuate`,xLinkArcRole:`xlinkArcrole`,xLinkHref:`xlinkHref`,xLinkRole:`xlinkRole`,xLinkShow:`xlinkShow`,xLinkTitle:`xlinkTitle`,xLinkType:`xlinkType`,xmlnsXLink:`xmlnsXlink`},DS=/[A-Z]/g,OS=/-[a-z]/g,kS=/^data[-\w.:]+$/i;function AS(e,t){let n=rS(t),r=t,i=iS;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&kS.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(OS,MS);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!OS.test(e)){let n=e.replace(DS,jS);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=hS}return new i(r,t)}function jS(e){return`-`+e.toLowerCase()}function MS(e){return e.charAt(1).toUpperCase()}var NS=nS([vS,xS,CS,wS,TS],`html`),PS=nS([vS,SS,CS,wS,TS],`svg`);function FS(e){return e.join(` `).trim()}var IS=r(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g;function u(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,u=1;function f(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(`
61
- `);u=~n?e.length-n:u+e.length}function p(){var e={line:l,column:u};return function(t){return t.position=new m(e),_(),t}}function m(e){this.start=e,this.end={line:l,column:u},this.source=t.source}m.prototype.content=e;function h(n){var r=Error(t.source+`:`+l+`:`+u+`: `+n);if(r.reason=n,r.filename=t.source,r.line=l,r.column=u,r.source=e,!t.silent)throw r}function g(t){var n=t.exec(e);if(n){var r=n[0];return f(r),e=e.slice(r.length),n}}function _(){g(i)}function v(e){var t;for(e||=[];t=y();)t!==!1&&e.push(t);return e}function y(){var t=p();if(e.charAt(0)==`/`&&e.charAt(1)==`*`){for(var n=2;e.charAt(n)!=``&&(e.charAt(n)!=`*`||e.charAt(n+1)!=`/`);)++n;if(n+=2,e.charAt(n-1)===``)return h(`End of comment missing`);var r=e.slice(2,n-2);return u+=2,f(r),e=e.slice(n),u+=2,t({type:`comment`,comment:r})}}function b(){var e=p(),t=g(a);if(t){if(y(),!g(o))return h(`property missing ':'`);var r=g(s),i=e({type:`declaration`,property:d(t[0].replace(n,``)),value:r?d(r[0].replace(n,``)):``});return g(c),i}}function x(){var e=[];v(e);for(var t;t=b();)t!==!1&&(e.push(t),v(e));return e}return _(),x()}function d(e){return e?e.replace(l,``):``}t.exports=u})),LS=r((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.default=r;var n=t(IS());function r(e,t){let r=null;if(!e||typeof e!=`string`)return r;let i=(0,n.default)(e),a=typeof t==`function`;return i.forEach(e=>{if(e.type!==`declaration`)return;let{property:n,value:i}=e;a?t(n,i,e):i&&(r||={},r[n]=i)}),r}})),RS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(e){return!e||r.test(e)||t.test(e)},s=function(e,t){return t.toUpperCase()},c=function(e,t){return`${t}-`};e.camelCase=function(e,t){return t===void 0&&(t={}),o(e)?e:(e=e.toLowerCase(),e=t.reactCompat?e.replace(a,c):e.replace(i,c),e.replace(n,s))}})),zS=r(((e,t)=>{var n=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(LS()),r=RS();function i(e,t){var i={};return!e||typeof e!=`string`||(0,n.default)(e,function(e,n){e&&n&&(i[(0,r.camelCase)(e,t)]=n)}),i}i.default=i,t.exports=i})),BS=HS(`end`),VS=HS(`start`);function HS(e){return t;function t(t){let n=t&&t.position&&t.position[e]||{};if(typeof n.line==`number`&&n.line>0&&typeof n.column==`number`&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset==`number`&&n.offset>-1?n.offset:void 0}}}function US(e){let t=VS(e),n=BS(e);if(t&&n)return{start:t,end:n}}function WS(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?KS(e.position):`start`in e||`end`in e?KS(e):`line`in e||`column`in e?GS(e):``}function GS(e){return qS(e&&e.line)+`:`+qS(e&&e.column)}function KS(e){return GS(e&&e.start)+`-`+GS(e&&e.end)}function qS(e){return e&&typeof e==`number`?e:1}var JS=class extends Error{constructor(e,t,n){super(),typeof t==`string`&&(n=t,t=void 0);let r=``,i={},a=!1;if(t&&(i=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?r=e:!i.cause&&e&&(a=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n==`string`){let e=n.indexOf(`:`);e===-1?i.ruleId=n:(i.source=n.slice(0,e),i.ruleId=n.slice(e+1))}if(!i.place&&i.ancestors&&i.ancestors){let e=i.ancestors[i.ancestors.length-1];e&&(i.place=e.position)}let o=i.place&&`start`in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file=``,this.message=r,this.line=o?o.line:void 0,this.name=WS(i.place)||`1:1`,this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack==`string`?i.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};JS.prototype.file=``,JS.prototype.name=``,JS.prototype.reason=``,JS.prototype.message=``,JS.prototype.stack=``,JS.prototype.column=void 0,JS.prototype.line=void 0,JS.prototype.ancestors=void 0,JS.prototype.cause=void 0,JS.prototype.fatal=void 0,JS.prototype.place=void 0,JS.prototype.ruleId=void 0,JS.prototype.source=void 0;var YS=n(zS(),1),XS={}.hasOwnProperty,ZS=new Map,QS=/[A-Z]/g,$S=new Set([`table`,`tbody`,`thead`,`tfoot`,`tr`]),eC=new Set([`td`,`th`]),tC=`https://github.com/syntax-tree/hast-util-to-jsx-runtime`;function nC(e,t){if(!t||t.Fragment===void 0)throw TypeError("Expected `Fragment` in options");let n=t.filePath||void 0,r;if(t.development){if(typeof t.jsxDEV!=`function`)throw TypeError("Expected `jsxDEV` in options when `development: true`");r=pC(n,t.jsxDEV)}else{if(typeof t.jsx!=`function`)throw TypeError("Expected `jsx` in production options");if(typeof t.jsxs!=`function`)throw TypeError("Expected `jsxs` in production options");r=fC(n,t.jsx,t.jsxs)}let i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||`react`,evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space===`svg`?PS:NS,stylePropertyNameCase:t.stylePropertyNameCase||`dom`,tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=rC(i,e,void 0);return a&&typeof a!=`string`?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function rC(e,t,n){if(t.type===`element`)return iC(e,t,n);if(t.type===`mdxFlowExpression`||t.type===`mdxTextExpression`)return aC(e,t);if(t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)return sC(e,t,n);if(t.type===`mdxjsEsm`)return oC(e,t);if(t.type===`root`)return cC(e,t,n);if(t.type===`text`)return lC(e,t)}function iC(e,t,n){let r=e.schema,i=r;t.tagName.toLowerCase()===`svg`&&r.space===`html`&&(i=PS,e.schema=i),e.ancestors.push(t);let a=yC(e,t.tagName,!1),o=mC(e,t),s=gC(e,t);return $S.has(t.tagName)&&(s=s.filter(function(e){return typeof e!=`string`||!$x(e)})),uC(e,o,a,t),dC(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function aC(e,t){if(t.data&&t.data.estree&&e.evaluater){let n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}bC(e,t.position)}function oC(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);bC(e,t.position)}function sC(e,t,n){let r=e.schema,i=r;t.name===`svg`&&r.space===`html`&&(i=PS,e.schema=i),e.ancestors.push(t);let a=t.name===null?e.Fragment:yC(e,t.name,!0),o=hC(e,t),s=gC(e,t);return uC(e,o,a,t),dC(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function cC(e,t,n){let r={};return dC(r,gC(e,t)),e.create(t,e.Fragment,r,n)}function lC(e,t){return t.value}function uC(e,t,n,r){typeof n!=`string`&&n!==e.Fragment&&e.passNode&&(t.node=r)}function dC(e,t){if(t.length>0){let n=t.length>1?t:t[0];n&&(e.children=n)}}function fC(e,t,n){return r;function r(e,r,i,a){let o=Array.isArray(i.children)?n:t;return a?o(r,i,a):o(r,i)}}function pC(e,t){return n;function n(n,r,i,a){let o=Array.isArray(i.children),s=VS(n);return t(r,i,a,o,{columnNumber:s?s.column-1:void 0,fileName:e,lineNumber:s?s.line:void 0},void 0)}}function mC(e,t){let n={},r,i;for(i in t.properties)if(i!==`children`&&XS.call(t.properties,i)){let a=_C(e,i,t.properties[i]);if(a){let[i,o]=a;e.tableCellAlignToStyle&&i===`align`&&typeof o==`string`&&eC.has(t.tagName)?r=o:n[i]=o}}if(r){let t=n.style||={};t[e.stylePropertyNameCase===`css`?`text-align`:`textAlign`]=r}return n}function hC(e,t){let n={};for(let r of t.attributes)if(r.type===`mdxJsxExpressionAttribute`){if(r.data&&r.data.estree&&e.evaluater){let t=r.data.estree.body[0];t.type;let i=t.expression;i.type;let a=i.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else bC(e,t.position)}else{let i=r.name,a;if(r.value&&typeof r.value==`object`){if(r.value.data&&r.value.data.estree&&e.evaluater){let t=r.value.data.estree.body[0];t.type,a=e.evaluater.evaluateExpression(t.expression)}else bC(e,t.position)}else a=r.value===null||r.value;n[i]=a}return n}function gC(e,t){let n=[],r=-1,i=e.passKeys?new Map:ZS;for(;++r<t.children.length;){let a=t.children[r],o;if(e.passKeys){let e=a.type===`element`?a.tagName:a.type===`mdxJsxFlowElement`||a.type===`mdxJsxTextElement`?a.name:void 0;if(e){let t=i.get(e)||0;o=e+`-`+t,i.set(e,t+1)}}let s=rC(e,a,o);s!==void 0&&n.push(s)}return n}function _C(e,t,n){let r=AS(e.schema,t);if(!(n==null||typeof n==`number`&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?qx(n):FS(n)),r.property===`style`){let t=typeof n==`object`?n:vC(e,String(n));return e.stylePropertyNameCase===`css`&&(t=xC(t)),[`style`,t]}return[e.elementAttributeNameCase===`react`&&r.space?ES[r.property]||r.property:r.attribute,n]}}function vC(e,t){try{return(0,YS.default)(t,{reactCompat:!0})}catch(t){if(e.ignoreInvalidStyle)return{};let n=t,r=new JS("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:`style`,source:`hast-util-to-jsx-runtime`});throw r.file=e.filePath||void 0,r.url=tC+`#cannot-parse-style-attribute`,r}}function yC(e,t,n){let r;if(!n)r={type:`Literal`,value:t};else if(t.includes(`.`)){let e=t.split(`.`),n=-1,i;for(;++n<e.length;){let t=Zx(e[n])?{type:`Identifier`,name:e[n]}:{type:`Literal`,value:e[n]};i=i?{type:`MemberExpression`,object:i,property:t,computed:!!(n&&t.type===`Literal`),optional:!1}:t}r=i}else r=Zx(t)&&!/^[a-z]/.test(t)?{type:`Identifier`,name:t}:{type:`Literal`,value:t};if(r.type===`Literal`){let t=r.value;return XS.call(e.components,t)?e.components[t]:t}if(e.evaluater)return e.evaluater.evaluateExpression(r);bC(e)}function bC(e,t){let n=new JS("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:`mdx-estree`,source:`hast-util-to-jsx-runtime`});throw n.file=e.filePath||void 0,n.url=tC+`#cannot-handle-mdx-estrees-without-createevaluater`,n}function xC(e){let t={},n;for(n in e)XS.call(e,n)&&(t[SC(n)]=e[n]);return t}function SC(e){let t=e.replace(QS,CC);return t.slice(0,3)===`ms-`&&(t=`-`+t),t}function CC(e){return`-`+e.toLowerCase()}var wC={action:[`form`],cite:[`blockquote`,`del`,`ins`,`q`],data:[`object`],formAction:[`button`,`input`],href:[`a`,`area`,`base`,`link`],icon:[`menuitem`],itemId:null,manifest:[`html`],ping:[`a`,`area`],poster:[`video`],src:[`audio`,`embed`,`iframe`,`img`,`input`,`script`,`source`,`track`,`video`]},TC={};function EC(e,t){let n=t||TC;return DC(e,typeof n.includeImageAlt!=`boolean`||n.includeImageAlt,typeof n.includeHtml!=`boolean`||n.includeHtml)}function DC(e,t,n){if(kC(e)){if(`value`in e)return e.type===`html`&&!n?``:e.value;if(t&&`alt`in e&&e.alt)return e.alt;if(`children`in e)return OC(e.children,t,n)}return Array.isArray(e)?OC(e,t,n):``}function OC(e,t,n){let r=[],i=-1;for(;++i<e.length;)r[i]=DC(e[i],t,n);return r.join(``)}function kC(e){return!!(e&&typeof e==`object`)}var AC=document.createElement(`i`);function jC(e){let t=`&`+e+`;`;AC.innerHTML=t;let n=AC.textContent;return n.charCodeAt(n.length-1)===59&&e!==`semi`?!1:n!==t&&n}function MC(e,t,n,r){let i=e.length,a=0,o;if(t=t<0?-t>i?0:i+t:t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);a<r.length;)o=r.slice(a,a+1e4),o.unshift(t,0),e.splice(...o),a+=1e4,t+=1e4}function NC(e,t){return e.length>0?(MC(e,e.length,0,t),e):t}var PC={}.hasOwnProperty;function FC(e){let t={},n=-1;for(;++n<e.length;)IC(t,e[n]);return t}function IC(e,t){let n;for(n in t){let r=(PC.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n],a;if(i)for(a in i){PC.call(r,a)||(r[a]=[]);let e=i[a];LC(r[a],Array.isArray(e)?e:e?[e]:[])}}}function LC(e,t){let n=-1,r=[];for(;++n<t.length;)(t[n].add===`after`?e:r).push(t[n]);MC(e,0,0,r)}function RC(e,t){let n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)==65535||(n&65535)==65534||n>1114111?`�`:String.fromCodePoint(n)}function zC(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}var BC=ZC(/[A-Za-z]/),VC=ZC(/[\dA-Za-z]/),HC=ZC(/[#-'*+\--9=?A-Z^-~]/);function UC(e){return e!==null&&(e<32||e===127)}var WC=ZC(/\d/),GC=ZC(/[\dA-Fa-f]/),KC=ZC(/[!-/:-@[-`{-~]/);function q(e){return e!==null&&e<-2}function qC(e){return e!==null&&(e<0||e===32)}function JC(e){return e===-2||e===-1||e===32}var YC=ZC(/\p{P}|\p{S}/u),XC=ZC(/\s/);function ZC(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function QC(e){let t=[],n=-1,r=0,i=0;for(;++n<e.length;){let a=e.charCodeAt(n),o=``;if(a===37&&VC(e.charCodeAt(n+1))&&VC(e.charCodeAt(n+2)))i=2;else if(a<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(a))||(o=String.fromCharCode(a));else if(a>55295&&a<57344){let t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(o=String.fromCharCode(a,t),i=1):o=`�`}else o=String.fromCharCode(a);o&&=(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,``),i&&=(n+=i,0)}return t.join(``)+e.slice(r)}function $C(e,t,n,r){let i=r?r-1:1/0,a=0;return o;function o(r){return JC(r)?(e.enter(n),s(r)):t(r)}function s(r){return JC(r)&&a++<i?(e.consume(r),s):(e.exit(n),t(r))}}var ew={tokenize:tw};function tw(e){let t=e.attempt(this.parser.constructs.contentInitial,r,i),n;return t;function r(n){if(n===null){e.consume(n);return}return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),$C(e,t,`linePrefix`)}function i(t){return e.enter(`paragraph`),a(t)}function a(t){let r=e.enter(`chunkText`,{contentType:`text`,previous:n});return n&&(n.next=r),n=r,o(t)}function o(t){if(t===null){e.exit(`chunkText`),e.exit(`paragraph`),e.consume(t);return}return q(t)?(e.consume(t),e.exit(`chunkText`),a):(e.consume(t),o)}}var nw={tokenize:iw},rw={tokenize:aw};function iw(e){let t=this,n=[],r=0,i,a,o;return s;function s(i){if(r<n.length){let a=n[r];return t.containerState=a[1],e.attempt(a[0].continuation,c,l)(i)}return l(i)}function c(e){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&v();let n=t.events.length,a=n,o;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){o=t.events[a][1].end;break}_(r);let s=n;for(;s<t.events.length;)t.events[s][1].end={...o},s++;return MC(t.events,a+1,0,t.events.slice(n)),t.events.length=s,l(e)}return s(e)}function l(a){if(r===n.length){if(!i)return f(a);if(i.currentConstruct&&i.currentConstruct.concrete)return m(a);t.interrupt=!(!i.currentConstruct||i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(rw,u,d)(a)}function u(e){return i&&v(),_(r),f(e)}function d(e){return t.parser.lazy[t.now().line]=r!==n.length,o=t.now().offset,m(e)}function f(n){return t.containerState={},e.attempt(rw,p,m)(n)}function p(e){return r++,n.push([t.currentConstruct,t.containerState]),f(e)}function m(n){if(n===null){i&&v(),_(0),e.consume(n);return}return i||=t.parser.flow(t.now()),e.enter(`chunkFlow`,{_tokenizer:i,contentType:`flow`,previous:a}),h(n)}function h(n){if(n===null){g(e.exit(`chunkFlow`),!0),_(0),e.consume(n);return}return q(n)?(e.consume(n),g(e.exit(`chunkFlow`)),r=0,t.interrupt=void 0,s):(e.consume(n),h)}function g(e,n){let s=t.sliceStream(e);if(n&&s.push(null),e.previous=a,a&&(a.next=e),a=e,i.defineSkip(e.start),i.write(s),t.parser.lazy[e.start.line]){let e=i.events.length;for(;e--;)if(i.events[e][1].start.offset<o&&(!i.events[e][1].end||i.events[e][1].end.offset>o))return;let n=t.events.length,a=n,s,c;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){if(s){c=t.events[a][1].end;break}s=!0}for(_(r),e=n;e<t.events.length;)t.events[e][1].end={...c},e++;MC(t.events,a+1,0,t.events.slice(n)),t.events.length=e}}function _(r){let i=n.length;for(;i-->r;){let r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function v(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function aw(e,t,n){return $C(e,e.attempt(this.parser.constructs.document,t,n),`linePrefix`,this.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)}function ow(e){if(e===null||qC(e)||XC(e))return 1;if(YC(e))return 2}function sw(e,t,n){let r=[],i=-1;for(;++i<e.length;){let a=e[i].resolveAll;a&&!r.includes(a)&&(t=a(t,n),r.push(a))}return t}var cw={name:`attention`,resolveAll:lw,tokenize:uw};function lw(e,t){let n=-1,r,i,a,o,s,c,l,u;for(;++n<e.length;)if(e[n][0]===`enter`&&e[n][1].type===`attentionSequence`&&e[n][1]._close){for(r=n;r--;)if(e[r][0]===`exit`&&e[r][1].type===`attentionSequence`&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;let d={...e[r][1].end},f={...e[n][1].start};dw(d,-c),dw(f,c),o={type:c>1?`strongSequence`:`emphasisSequence`,start:d,end:{...e[r][1].end}},s={type:c>1?`strongSequence`:`emphasisSequence`,start:{...e[n][1].start},end:f},a={type:c>1?`strongText`:`emphasisText`,start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?`strong`:`emphasis`,start:{...o.start},end:{...s.end}},e[r][1].end={...o.start},e[n][1].start={...s.end},l=[],e[r][1].end.offset-e[r][1].start.offset&&(l=NC(l,[[`enter`,e[r][1],t],[`exit`,e[r][1],t]])),l=NC(l,[[`enter`,i,t],[`enter`,o,t],[`exit`,o,t],[`enter`,a,t]]),l=NC(l,sw(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),l=NC(l,[[`exit`,a,t],[`enter`,s,t],[`exit`,s,t],[`exit`,i,t]]),e[n][1].end.offset-e[n][1].start.offset?(u=2,l=NC(l,[[`enter`,e[n][1],t],[`exit`,e[n][1],t]])):u=0,MC(e,r-1,n-r+3,l),n=r+l.length-u-2;break}}for(n=-1;++n<e.length;)e[n][1].type===`attentionSequence`&&(e[n][1].type=`data`);return e}function uw(e,t){let n=this.parser.constructs.attentionMarkers.null,r=this.previous,i=ow(r),a;return o;function o(t){return a=t,e.enter(`attentionSequence`),s(t)}function s(o){if(o===a)return e.consume(o),s;let c=e.exit(`attentionSequence`),l=ow(o),u=!l||l===2&&i||n.includes(o),d=!i||i===2&&l||n.includes(r);return c._open=!!(a===42?u:u&&(i||!d)),c._close=!!(a===42?d:d&&(l||!u)),t(o)}}function dw(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}var fw={name:`autolink`,tokenize:pw};function pw(e,t,n){let r=0;return i;function i(t){return e.enter(`autolink`),e.enter(`autolinkMarker`),e.consume(t),e.exit(`autolinkMarker`),e.enter(`autolinkProtocol`),a}function a(t){return BC(t)?(e.consume(t),o):t===64?n(t):l(t)}function o(e){return e===43||e===45||e===46||VC(e)?(r=1,s(e)):l(e)}function s(t){return t===58?(e.consume(t),r=0,c):(t===43||t===45||t===46||VC(t))&&r++<32?(e.consume(t),s):(r=0,l(t))}function c(r){return r===62?(e.exit(`autolinkProtocol`),e.enter(`autolinkMarker`),e.consume(r),e.exit(`autolinkMarker`),e.exit(`autolink`),t):r===null||r===32||r===60||UC(r)?n(r):(e.consume(r),c)}function l(t){return t===64?(e.consume(t),u):HC(t)?(e.consume(t),l):n(t)}function u(e){return VC(e)?d(e):n(e)}function d(n){return n===46?(e.consume(n),r=0,u):n===62?(e.exit(`autolinkProtocol`).type=`autolinkEmail`,e.enter(`autolinkMarker`),e.consume(n),e.exit(`autolinkMarker`),e.exit(`autolink`),t):f(n)}function f(t){if((t===45||VC(t))&&r++<63){let n=t===45?f:d;return e.consume(t),n}return n(t)}}var mw={partial:!0,tokenize:hw};function hw(e,t,n){return r;function r(t){return JC(t)?$C(e,i,`linePrefix`)(t):i(t)}function i(e){return e===null||q(e)?t(e):n(e)}}var gw={continuation:{tokenize:vw},exit:yw,name:`blockQuote`,tokenize:_w};function _w(e,t,n){let r=this;return i;function i(t){if(t===62){let n=r.containerState;return n.open||=(e.enter(`blockQuote`,{_container:!0}),!0),e.enter(`blockQuotePrefix`),e.enter(`blockQuoteMarker`),e.consume(t),e.exit(`blockQuoteMarker`),a}return n(t)}function a(n){return JC(n)?(e.enter(`blockQuotePrefixWhitespace`),e.consume(n),e.exit(`blockQuotePrefixWhitespace`),e.exit(`blockQuotePrefix`),t):(e.exit(`blockQuotePrefix`),t(n))}}function vw(e,t,n){let r=this;return i;function i(t){return JC(t)?$C(e,a,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):a(t)}function a(r){return e.attempt(gw,t,n)(r)}}function yw(e){e.exit(`blockQuote`)}var bw={name:`characterEscape`,tokenize:xw};function xw(e,t,n){return r;function r(t){return e.enter(`characterEscape`),e.enter(`escapeMarker`),e.consume(t),e.exit(`escapeMarker`),i}function i(r){return KC(r)?(e.enter(`characterEscapeValue`),e.consume(r),e.exit(`characterEscapeValue`),e.exit(`characterEscape`),t):n(r)}}var Sw={name:`characterReference`,tokenize:Cw};function Cw(e,t,n){let r=this,i=0,a,o;return s;function s(t){return e.enter(`characterReference`),e.enter(`characterReferenceMarker`),e.consume(t),e.exit(`characterReferenceMarker`),c}function c(t){return t===35?(e.enter(`characterReferenceMarkerNumeric`),e.consume(t),e.exit(`characterReferenceMarkerNumeric`),l):(e.enter(`characterReferenceValue`),a=31,o=VC,u(t))}function l(t){return t===88||t===120?(e.enter(`characterReferenceMarkerHexadecimal`),e.consume(t),e.exit(`characterReferenceMarkerHexadecimal`),e.enter(`characterReferenceValue`),a=6,o=GC,u):(e.enter(`characterReferenceValue`),a=7,o=WC,u(t))}function u(s){if(s===59&&i){let i=e.exit(`characterReferenceValue`);return o===VC&&!jC(r.sliceSerialize(i))?n(s):(e.enter(`characterReferenceMarker`),e.consume(s),e.exit(`characterReferenceMarker`),e.exit(`characterReference`),t)}return o(s)&&i++<a?(e.consume(s),u):n(s)}}var ww={partial:!0,tokenize:Dw},Tw={concrete:!0,name:`codeFenced`,tokenize:Ew};function Ew(e,t,n){let r=this,i={partial:!0,tokenize:x},a=0,o=0,s;return c;function c(e){return l(e)}function l(t){let n=r.events[r.events.length-1];return a=n&&n[1].type===`linePrefix`?n[2].sliceSerialize(n[1],!0).length:0,s=t,e.enter(`codeFenced`),e.enter(`codeFencedFence`),e.enter(`codeFencedFenceSequence`),u(t)}function u(t){return t===s?(o++,e.consume(t),u):o<3?n(t):(e.exit(`codeFencedFenceSequence`),JC(t)?$C(e,d,`whitespace`)(t):d(t))}function d(n){return n===null||q(n)?(e.exit(`codeFencedFence`),r.interrupt?t(n):e.check(ww,h,b)(n)):(e.enter(`codeFencedFenceInfo`),e.enter(`chunkString`,{contentType:`string`}),f(n))}function f(t){return t===null||q(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceInfo`),d(t)):JC(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceInfo`),$C(e,p,`whitespace`)(t)):t===96&&t===s?n(t):(e.consume(t),f)}function p(t){return t===null||q(t)?d(t):(e.enter(`codeFencedFenceMeta`),e.enter(`chunkString`,{contentType:`string`}),m(t))}function m(t){return t===null||q(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceMeta`),d(t)):t===96&&t===s?n(t):(e.consume(t),m)}function h(t){return e.attempt(i,b,g)(t)}function g(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),_}function _(t){return a>0&&JC(t)?$C(e,v,`linePrefix`,a+1)(t):v(t)}function v(t){return t===null||q(t)?e.check(ww,h,b)(t):(e.enter(`codeFlowValue`),y(t))}function y(t){return t===null||q(t)?(e.exit(`codeFlowValue`),v(t)):(e.consume(t),y)}function b(n){return e.exit(`codeFenced`),t(n)}function x(e,t,n){let i=0;return a;function a(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c}function c(t){return e.enter(`codeFencedFence`),JC(t)?$C(e,l,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):l(t)}function l(t){return t===s?(e.enter(`codeFencedFenceSequence`),u(t)):n(t)}function u(t){return t===s?(i++,e.consume(t),u):i>=o?(e.exit(`codeFencedFenceSequence`),JC(t)?$C(e,d,`whitespace`)(t):d(t)):n(t)}function d(r){return r===null||q(r)?(e.exit(`codeFencedFence`),t(r)):n(r)}}}function Dw(e,t,n){let r=this;return i;function i(t){return t===null?n(t):(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}var Ow={name:`codeIndented`,tokenize:Aw},kw={partial:!0,tokenize:jw};function Aw(e,t,n){let r=this;return i;function i(t){return e.enter(`codeIndented`),$C(e,a,`linePrefix`,5)(t)}function a(e){let t=r.events[r.events.length-1];return t&&t[1].type===`linePrefix`&&t[2].sliceSerialize(t[1],!0).length>=4?o(e):n(e)}function o(t){return t===null?c(t):q(t)?e.attempt(kw,o,c)(t):(e.enter(`codeFlowValue`),s(t))}function s(t){return t===null||q(t)?(e.exit(`codeFlowValue`),o(t)):(e.consume(t),s)}function c(n){return e.exit(`codeIndented`),t(n)}}function jw(e,t,n){let r=this;return i;function i(t){return r.parser.lazy[r.now().line]?n(t):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),i):$C(e,a,`linePrefix`,5)(t)}function a(e){let a=r.events[r.events.length-1];return a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(e):q(e)?i(e):n(e)}}var Mw={name:`codeText`,previous:Pw,resolve:Nw,tokenize:Fw};function Nw(e){let t=e.length-4,n=3,r,i;if((e[n][1].type===`lineEnding`||e[n][1].type===`space`)&&(e[t][1].type===`lineEnding`||e[t][1].type===`space`)){for(r=n;++r<t;)if(e[r][1].type===`codeTextData`){e[n][1].type=`codeTextPadding`,e[t][1].type=`codeTextPadding`,n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!==`lineEnding`&&(i=r):(r===t||e[r][1].type===`lineEnding`)&&(e[i][1].type=`codeTextData`,r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function Pw(e){return e!==96||this.events[this.events.length-1][1].type===`characterEscape`}function Fw(e,t,n){let r=0,i,a;return o;function o(t){return e.enter(`codeText`),e.enter(`codeTextSequence`),s(t)}function s(t){return t===96?(e.consume(t),r++,s):(e.exit(`codeTextSequence`),c(t))}function c(t){return t===null?n(t):t===32?(e.enter(`space`),e.consume(t),e.exit(`space`),c):t===96?(a=e.enter(`codeTextSequence`),i=0,u(t)):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c):(e.enter(`codeTextData`),l(t))}function l(t){return t===null||t===32||t===96||q(t)?(e.exit(`codeTextData`),c(t)):(e.consume(t),l)}function u(n){return n===96?(e.consume(n),i++,u):i===r?(e.exit(`codeTextSequence`),e.exit(`codeText`),t(n)):(a.type=`codeTextData`,l(n))}}var Iw=class{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,t){let n=t??1/0;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){let r=t||0;this.setCursor(Math.trunc(e));let i=this.right.splice(this.right.length-r,1/0);return n&&Lw(this.left,n),i.reverse()}pop(){return this.setCursor(1/0),this.left.pop()}push(e){this.setCursor(1/0),this.left.push(e)}pushMany(e){this.setCursor(1/0),Lw(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),Lw(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0)){if(e<this.left.length){let t=this.left.splice(e,1/0);Lw(this.right,t.reverse())}else{let t=this.right.splice(this.left.length+this.right.length-e,1/0);Lw(this.left,t.reverse())}}}};function Lw(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function Rw(e){let t={},n=-1,r,i,a,o,s,c,l,u=new Iw(e);for(;++n<u.length;){for(;n in t;)n=t[n];if(r=u.get(n),n&&r[1].type===`chunkFlow`&&u.get(n-1)[1].type===`listItemPrefix`&&(c=r[1]._tokenizer.events,a=0,a<c.length&&c[a][1].type===`lineEndingBlank`&&(a+=2),a<c.length&&c[a][1].type===`content`))for(;++a<c.length&&c[a][1].type!==`content`;)c[a][1].type===`chunkText`&&(c[a][1]._isInFirstContentOfListItem=!0,a++);if(r[0]===`enter`)r[1].contentType&&(Object.assign(t,zw(u,n)),n=t[n],l=!0);else if(r[1]._container){for(a=n,i=void 0;a--;)if(o=u.get(a),o[1].type===`lineEnding`||o[1].type===`lineEndingBlank`)o[0]===`enter`&&(i&&(u.get(i)[1].type=`lineEndingBlank`),o[1].type=`lineEnding`,i=a);else if(o[1].type!==`linePrefix`&&o[1].type!==`listItemIndent`)break;i&&(r[1].end={...u.get(i)[1].start},s=u.slice(i,n),s.unshift(r),u.splice(i,n-i+1,s))}}return MC(e,0,1/0,u.slice(0)),!l}function zw(e,t){let n=e.get(t)[1],r=e.get(t)[2],i=t-1,a=[],o=n._tokenizer;o||(o=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));let s=o.events,c=[],l={},u,d,f=-1,p=n,m=0,h=0,g=[h];for(;p;){for(;e.get(++i)[1]!==p;);a.push(i),p._tokenizer||(u=r.sliceStream(p),p.next||u.push(null),d&&o.defineSkip(p.start),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(u),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=n;++f<s.length;)s[f][0]===`exit`&&s[f-1][0]===`enter`&&s[f][1].type===s[f-1][1].type&&s[f][1].start.line!==s[f][1].end.line&&(h=f+1,g.push(h),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(o.events=[],p?(p._tokenizer=void 0,p.previous=void 0):g.pop(),f=g.length;f--;){let t=s.slice(g[f],g[f+1]),n=a.pop();c.push([n,n+t.length-1]),e.splice(n,2,t)}for(c.reverse(),f=-1;++f<c.length;)l[m+c[f][0]]=m+c[f][1],m+=c[f][1]-c[f][0]-1;return l}var Bw={resolve:Hw,tokenize:Uw},Vw={partial:!0,tokenize:Ww};function Hw(e){return Rw(e),e}function Uw(e,t){let n;return r;function r(t){return e.enter(`content`),n=e.enter(`chunkContent`,{contentType:`content`}),i(t)}function i(t){return t===null?a(t):q(t)?e.check(Vw,o,a)(t):(e.consume(t),i)}function a(n){return e.exit(`chunkContent`),e.exit(`content`),t(n)}function o(t){return e.consume(t),e.exit(`chunkContent`),n.next=e.enter(`chunkContent`,{contentType:`content`,previous:n}),n=n.next,i}}function Ww(e,t,n){let r=this;return i;function i(t){return e.exit(`chunkContent`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),$C(e,a,`linePrefix`)}function a(i){if(i===null||q(i))return n(i);let a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes(`codeIndented`)&&a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function Gw(e,t,n,r,i,a,o,s,c){let l=c||1/0,u=0;return d;function d(t){return t===60?(e.enter(r),e.enter(i),e.enter(a),e.consume(t),e.exit(a),f):t===null||t===32||t===41||UC(t)?n(t):(e.enter(r),e.enter(o),e.enter(s),e.enter(`chunkString`,{contentType:`string`}),h(t))}function f(n){return n===62?(e.enter(a),e.consume(n),e.exit(a),e.exit(i),e.exit(r),t):(e.enter(s),e.enter(`chunkString`,{contentType:`string`}),p(n))}function p(t){return t===62?(e.exit(`chunkString`),e.exit(s),f(t)):t===null||t===60||q(t)?n(t):(e.consume(t),t===92?m:p)}function m(t){return t===60||t===62||t===92?(e.consume(t),p):p(t)}function h(i){return!u&&(i===null||i===41||qC(i))?(e.exit(`chunkString`),e.exit(s),e.exit(o),e.exit(r),t(i)):u<l&&i===40?(e.consume(i),u++,h):i===41?(e.consume(i),u--,h):i===null||i===32||i===40||UC(i)?n(i):(e.consume(i),i===92?g:h)}function g(t){return t===40||t===41||t===92?(e.consume(t),h):h(t)}}function Kw(e,t,n,r,i,a){let o=this,s=0,c;return l;function l(t){return e.enter(r),e.enter(i),e.consume(t),e.exit(i),e.enter(a),u}function u(l){return s>999||l===null||l===91||l===93&&!c||l===94&&!s&&`_hiddenFootnoteSupport`in o.parser.constructs?n(l):l===93?(e.exit(a),e.enter(i),e.consume(l),e.exit(i),e.exit(r),t):q(l)?(e.enter(`lineEnding`),e.consume(l),e.exit(`lineEnding`),u):(e.enter(`chunkString`,{contentType:`string`}),d(l))}function d(t){return t===null||t===91||t===93||q(t)||s++>999?(e.exit(`chunkString`),u(t)):(e.consume(t),c||=!JC(t),t===92?f:d)}function f(t){return t===91||t===92||t===93?(e.consume(t),s++,d):d(t)}}function qw(e,t,n,r,i,a){let o;return s;function s(t){return t===34||t===39||t===40?(e.enter(r),e.enter(i),e.consume(t),e.exit(i),o=t===40?41:t,c):n(t)}function c(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(a),l(n))}function l(t){return t===o?(e.exit(a),c(o)):t===null?n(t):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),$C(e,l,`linePrefix`)):(e.enter(`chunkString`,{contentType:`string`}),u(t))}function u(t){return t===o||t===null||q(t)?(e.exit(`chunkString`),l(t)):(e.consume(t),t===92?d:u)}function d(t){return t===o||t===92?(e.consume(t),u):u(t)}}function Jw(e,t){let n;return r;function r(i){return q(i)?(e.enter(`lineEnding`),e.consume(i),e.exit(`lineEnding`),n=!0,r):JC(i)?$C(e,r,n?`linePrefix`:`lineSuffix`)(i):t(i)}}var Yw={name:`definition`,tokenize:Zw},Xw={partial:!0,tokenize:Qw};function Zw(e,t,n){let r=this,i;return a;function a(t){return e.enter(`definition`),o(t)}function o(t){return Kw.call(r,e,s,n,`definitionLabel`,`definitionLabelMarker`,`definitionLabelString`)(t)}function s(t){return i=zC(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),c):n(t)}function c(t){return qC(t)?Jw(e,l)(t):l(t)}function l(t){return Gw(e,u,n,`definitionDestination`,`definitionDestinationLiteral`,`definitionDestinationLiteralMarker`,`definitionDestinationRaw`,`definitionDestinationString`)(t)}function u(t){return e.attempt(Xw,d,d)(t)}function d(t){return JC(t)?$C(e,f,`whitespace`)(t):f(t)}function f(a){return a===null||q(a)?(e.exit(`definition`),r.parser.defined.push(i),t(a)):n(a)}}function Qw(e,t,n){return r;function r(t){return qC(t)?Jw(e,i)(t):n(t)}function i(t){return qw(e,a,n,`definitionTitle`,`definitionTitleMarker`,`definitionTitleString`)(t)}function a(t){return JC(t)?$C(e,o,`whitespace`)(t):o(t)}function o(e){return e===null||q(e)?t(e):n(e)}}var $w={name:`hardBreakEscape`,tokenize:eT};function eT(e,t,n){return r;function r(t){return e.enter(`hardBreakEscape`),e.consume(t),i}function i(r){return q(r)?(e.exit(`hardBreakEscape`),t(r)):n(r)}}var tT={name:`headingAtx`,resolve:nT,tokenize:rT};function nT(e,t){let n=e.length-2,r=3,i,a;return e[r][1].type===`whitespace`&&(r+=2),n-2>r&&e[n][1].type===`whitespace`&&(n-=2),e[n][1].type===`atxHeadingSequence`&&(r===n-1||n-4>r&&e[n-2][1].type===`whitespace`)&&(n-=r+1===n?2:4),n>r&&(i={type:`atxHeadingText`,start:e[r][1].start,end:e[n][1].end},a={type:`chunkText`,start:e[r][1].start,end:e[n][1].end,contentType:`text`},MC(e,r,n-r+1,[[`enter`,i,t],[`enter`,a,t],[`exit`,a,t],[`exit`,i,t]])),e}function rT(e,t,n){let r=0;return i;function i(t){return e.enter(`atxHeading`),a(t)}function a(t){return e.enter(`atxHeadingSequence`),o(t)}function o(t){return t===35&&r++<6?(e.consume(t),o):t===null||qC(t)?(e.exit(`atxHeadingSequence`),s(t)):n(t)}function s(n){return n===35?(e.enter(`atxHeadingSequence`),c(n)):n===null||q(n)?(e.exit(`atxHeading`),t(n)):JC(n)?$C(e,s,`whitespace`)(n):(e.enter(`atxHeadingText`),l(n))}function c(t){return t===35?(e.consume(t),c):(e.exit(`atxHeadingSequence`),s(t))}function l(t){return t===null||t===35||qC(t)?(e.exit(`atxHeadingText`),s(t)):(e.consume(t),l)}}var iT=`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.h1.h2.h3.h4.h5.h6.head.header.hr.html.iframe.legend.li.link.main.menu.menuitem.nav.noframes.ol.optgroup.option.p.param.search.section.summary.table.tbody.td.tfoot.th.thead.title.tr.track.ul`.split(`.`),aT=[`pre`,`script`,`style`,`textarea`],oT={concrete:!0,name:`htmlFlow`,resolveTo:lT,tokenize:uT},sT={partial:!0,tokenize:fT},cT={partial:!0,tokenize:dT};function lT(e){let t=e.length;for(;t--&&(e[t][0]!==`enter`||e[t][1].type!==`htmlFlow`););return t>1&&e[t-2][1].type===`linePrefix`&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function uT(e,t,n){let r=this,i,a,o,s,c;return l;function l(e){return u(e)}function u(t){return e.enter(`htmlFlow`),e.enter(`htmlFlowData`),e.consume(t),d}function d(s){return s===33?(e.consume(s),f):s===47?(e.consume(s),a=!0,h):s===63?(e.consume(s),i=3,r.interrupt?t:ne):BC(s)?(e.consume(s),o=String.fromCharCode(s),g):n(s)}function f(a){return a===45?(e.consume(a),i=2,p):a===91?(e.consume(a),i=5,s=0,m):BC(a)?(e.consume(a),i=4,r.interrupt?t:ne):n(a)}function p(i){return i===45?(e.consume(i),r.interrupt?t:ne):n(i)}function m(i){return i===`CDATA[`.charCodeAt(s++)?(e.consume(i),s===6?r.interrupt?t:O:m):n(i)}function h(t){return BC(t)?(e.consume(t),o=String.fromCharCode(t),g):n(t)}function g(s){if(s===null||s===47||s===62||qC(s)){let c=s===47,l=o.toLowerCase();return!c&&!a&&aT.includes(l)?(i=1,r.interrupt?t(s):O(s)):iT.includes(o.toLowerCase())?(i=6,c?(e.consume(s),_):r.interrupt?t(s):O(s)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(s):a?v(s):y(s))}return s===45||VC(s)?(e.consume(s),o+=String.fromCharCode(s),g):n(s)}function _(i){return i===62?(e.consume(i),r.interrupt?t:O):n(i)}function v(t){return JC(t)?(e.consume(t),v):E(t)}function y(t){return t===47?(e.consume(t),E):t===58||t===95||BC(t)?(e.consume(t),b):JC(t)?(e.consume(t),y):E(t)}function b(t){return t===45||t===46||t===58||t===95||VC(t)?(e.consume(t),b):x(t)}function x(t){return t===61?(e.consume(t),S):JC(t)?(e.consume(t),x):y(t)}function S(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),c=t,C):JC(t)?(e.consume(t),S):w(t)}function C(t){return t===c?(e.consume(t),c=null,T):t===null||q(t)?n(t):(e.consume(t),C)}function w(t){return t===null||t===34||t===39||t===47||t===60||t===61||t===62||t===96||qC(t)?x(t):(e.consume(t),w)}function T(e){return e===47||e===62||JC(e)?y(e):n(e)}function E(t){return t===62?(e.consume(t),D):n(t)}function D(t){return t===null||q(t)?O(t):JC(t)?(e.consume(t),D):n(t)}function O(t){return t===45&&i===2?(e.consume(t),M):t===60&&i===1?(e.consume(t),N):t===62&&i===4?(e.consume(t),re):t===63&&i===3?(e.consume(t),ne):t===93&&i===5?(e.consume(t),te):q(t)&&(i===6||i===7)?(e.exit(`htmlFlowData`),e.check(sT,ie,k)(t)):t===null||q(t)?(e.exit(`htmlFlowData`),k(t)):(e.consume(t),O)}function k(t){return e.check(cT,A,ie)(t)}function A(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),j}function j(t){return t===null||q(t)?k(t):(e.enter(`htmlFlowData`),O(t))}function M(t){return t===45?(e.consume(t),ne):O(t)}function N(t){return t===47?(e.consume(t),o=``,ee):O(t)}function ee(t){if(t===62){let n=o.toLowerCase();return aT.includes(n)?(e.consume(t),re):O(t)}return BC(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),ee):O(t)}function te(t){return t===93?(e.consume(t),ne):O(t)}function ne(t){return t===62?(e.consume(t),re):t===45&&i===2?(e.consume(t),ne):O(t)}function re(t){return t===null||q(t)?(e.exit(`htmlFlowData`),ie(t)):(e.consume(t),re)}function ie(n){return e.exit(`htmlFlow`),t(n)}}function dT(e,t,n){let r=this;return i;function i(t){return q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a):n(t)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}function fT(e,t,n){return r;function r(r){return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),e.attempt(mw,t,n)}}var pT={name:`htmlText`,tokenize:mT};function mT(e,t,n){let r=this,i,a,o;return s;function s(t){return e.enter(`htmlText`),e.enter(`htmlTextData`),e.consume(t),c}function c(t){return t===33?(e.consume(t),l):t===47?(e.consume(t),x):t===63?(e.consume(t),y):BC(t)?(e.consume(t),w):n(t)}function l(t){return t===45?(e.consume(t),u):t===91?(e.consume(t),a=0,m):BC(t)?(e.consume(t),v):n(t)}function u(t){return t===45?(e.consume(t),p):n(t)}function d(t){return t===null?n(t):t===45?(e.consume(t),f):q(t)?(o=d,N(t)):(e.consume(t),d)}function f(t){return t===45?(e.consume(t),p):d(t)}function p(e){return e===62?M(e):e===45?f(e):d(e)}function m(t){return t===`CDATA[`.charCodeAt(a++)?(e.consume(t),a===6?h:m):n(t)}function h(t){return t===null?n(t):t===93?(e.consume(t),g):q(t)?(o=h,N(t)):(e.consume(t),h)}function g(t){return t===93?(e.consume(t),_):h(t)}function _(t){return t===62?M(t):t===93?(e.consume(t),_):h(t)}function v(t){return t===null||t===62?M(t):q(t)?(o=v,N(t)):(e.consume(t),v)}function y(t){return t===null?n(t):t===63?(e.consume(t),b):q(t)?(o=y,N(t)):(e.consume(t),y)}function b(e){return e===62?M(e):y(e)}function x(t){return BC(t)?(e.consume(t),S):n(t)}function S(t){return t===45||VC(t)?(e.consume(t),S):C(t)}function C(t){return q(t)?(o=C,N(t)):JC(t)?(e.consume(t),C):M(t)}function w(t){return t===45||VC(t)?(e.consume(t),w):t===47||t===62||qC(t)?T(t):n(t)}function T(t){return t===47?(e.consume(t),M):t===58||t===95||BC(t)?(e.consume(t),E):q(t)?(o=T,N(t)):JC(t)?(e.consume(t),T):M(t)}function E(t){return t===45||t===46||t===58||t===95||VC(t)?(e.consume(t),E):D(t)}function D(t){return t===61?(e.consume(t),O):q(t)?(o=D,N(t)):JC(t)?(e.consume(t),D):T(t)}function O(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),i=t,k):q(t)?(o=O,N(t)):JC(t)?(e.consume(t),O):(e.consume(t),A)}function k(t){return t===i?(e.consume(t),i=void 0,j):t===null?n(t):q(t)?(o=k,N(t)):(e.consume(t),k)}function A(t){return t===null||t===34||t===39||t===60||t===61||t===96?n(t):t===47||t===62||qC(t)?T(t):(e.consume(t),A)}function j(e){return e===47||e===62||qC(e)?T(e):n(e)}function M(r){return r===62?(e.consume(r),e.exit(`htmlTextData`),e.exit(`htmlText`),t):n(r)}function N(t){return e.exit(`htmlTextData`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),ee}function ee(t){return JC(t)?$C(e,te,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):te(t)}function te(t){return e.enter(`htmlTextData`),o(t)}}var hT={name:`labelEnd`,resolveAll:yT,resolveTo:bT,tokenize:xT},gT={tokenize:ST},_T={tokenize:CT},vT={tokenize:wT};function yT(e){let t=-1,n=[];for(;++t<e.length;){let r=e[t][1];if(n.push(e[t]),r.type===`labelImage`||r.type===`labelLink`||r.type===`labelEnd`){let e=r.type===`labelImage`?4:2;r.type=`data`,t+=e}}return e.length!==n.length&&MC(e,0,e.length,n),e}function bT(e,t){let n=e.length,r=0,i,a,o,s;for(;n--;)if(i=e[n][1],a){if(i.type===`link`||i.type===`labelLink`&&i._inactive)break;e[n][0]===`enter`&&i.type===`labelLink`&&(i._inactive=!0)}else if(o){if(e[n][0]===`enter`&&(i.type===`labelImage`||i.type===`labelLink`)&&!i._balanced&&(a=n,i.type!==`labelLink`)){r=2;break}}else i.type===`labelEnd`&&(o=n);let c={type:e[a][1].type===`labelLink`?`link`:`image`,start:{...e[a][1].start},end:{...e[e.length-1][1].end}},l={type:`label`,start:{...e[a][1].start},end:{...e[o][1].end}},u={type:`labelText`,start:{...e[a+r+2][1].end},end:{...e[o-2][1].start}};return s=[[`enter`,c,t],[`enter`,l,t]],s=NC(s,e.slice(a+1,a+r+3)),s=NC(s,[[`enter`,u,t]]),s=NC(s,sw(t.parser.constructs.insideSpan.null,e.slice(a+r+4,o-3),t)),s=NC(s,[[`exit`,u,t],e[o-2],e[o-1],[`exit`,l,t]]),s=NC(s,e.slice(o+1)),s=NC(s,[[`exit`,c,t]]),MC(e,a,e.length,s),e}function xT(e,t,n){let r=this,i=r.events.length,a,o;for(;i--;)if((r.events[i][1].type===`labelImage`||r.events[i][1].type===`labelLink`)&&!r.events[i][1]._balanced){a=r.events[i][1];break}return s;function s(t){return a?a._inactive?d(t):(o=r.parser.defined.includes(zC(r.sliceSerialize({start:a.end,end:r.now()}))),e.enter(`labelEnd`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelEnd`),c):n(t)}function c(t){return t===40?e.attempt(gT,u,o?u:d)(t):t===91?e.attempt(_T,u,o?l:d)(t):o?u(t):d(t)}function l(t){return e.attempt(vT,u,d)(t)}function u(e){return t(e)}function d(e){return a._balanced=!0,n(e)}}function ST(e,t,n){return r;function r(t){return e.enter(`resource`),e.enter(`resourceMarker`),e.consume(t),e.exit(`resourceMarker`),i}function i(t){return qC(t)?Jw(e,a)(t):a(t)}function a(t){return t===41?u(t):Gw(e,o,s,`resourceDestination`,`resourceDestinationLiteral`,`resourceDestinationLiteralMarker`,`resourceDestinationRaw`,`resourceDestinationString`,32)(t)}function o(t){return qC(t)?Jw(e,c)(t):u(t)}function s(e){return n(e)}function c(t){return t===34||t===39||t===40?qw(e,l,n,`resourceTitle`,`resourceTitleMarker`,`resourceTitleString`)(t):u(t)}function l(t){return qC(t)?Jw(e,u)(t):u(t)}function u(r){return r===41?(e.enter(`resourceMarker`),e.consume(r),e.exit(`resourceMarker`),e.exit(`resource`),t):n(r)}}function CT(e,t,n){let r=this;return i;function i(t){return Kw.call(r,e,a,o,`reference`,`referenceMarker`,`referenceString`)(t)}function a(e){return r.parser.defined.includes(zC(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function o(e){return n(e)}}function wT(e,t,n){return r;function r(t){return e.enter(`reference`),e.enter(`referenceMarker`),e.consume(t),e.exit(`referenceMarker`),i}function i(r){return r===93?(e.enter(`referenceMarker`),e.consume(r),e.exit(`referenceMarker`),e.exit(`reference`),t):n(r)}}var TT={name:`labelStartImage`,resolveAll:hT.resolveAll,tokenize:ET};function ET(e,t,n){let r=this;return i;function i(t){return e.enter(`labelImage`),e.enter(`labelImageMarker`),e.consume(t),e.exit(`labelImageMarker`),a}function a(t){return t===91?(e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelImage`),o):n(t)}function o(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):t(e)}}var DT={name:`labelStartLink`,resolveAll:hT.resolveAll,tokenize:OT};function OT(e,t,n){let r=this;return i;function i(t){return e.enter(`labelLink`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelLink`),a}function a(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):t(e)}}var kT={name:`lineEnding`,tokenize:AT};function AT(e,t){return n;function n(n){return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),$C(e,t,`linePrefix`)}}var jT={name:`thematicBreak`,tokenize:MT};function MT(e,t,n){let r=0,i;return a;function a(t){return e.enter(`thematicBreak`),o(t)}function o(e){return i=e,s(e)}function s(a){return a===i?(e.enter(`thematicBreakSequence`),c(a)):r>=3&&(a===null||q(a))?(e.exit(`thematicBreak`),t(a)):n(a)}function c(t){return t===i?(e.consume(t),r++,c):(e.exit(`thematicBreakSequence`),JC(t)?$C(e,s,`whitespace`)(t):s(t))}}var NT={continuation:{tokenize:LT},exit:zT,name:`list`,tokenize:IT},PT={partial:!0,tokenize:BT},FT={partial:!0,tokenize:RT};function IT(e,t,n){let r=this,i=r.events[r.events.length-1],a=i&&i[1].type===`linePrefix`?i[2].sliceSerialize(i[1],!0).length:0,o=0;return s;function s(t){let i=r.containerState.type||(t===42||t===43||t===45?`listUnordered`:`listOrdered`);if(i===`listUnordered`?!r.containerState.marker||t===r.containerState.marker:WC(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),i===`listUnordered`)return e.enter(`listItemPrefix`),t===42||t===45?e.check(jT,n,l)(t):l(t);if(!r.interrupt||t===49)return e.enter(`listItemPrefix`),e.enter(`listItemValue`),c(t)}return n(t)}function c(t){return WC(t)&&++o<10?(e.consume(t),c):(!r.interrupt||o<2)&&(r.containerState.marker?t===r.containerState.marker:t===41||t===46)?(e.exit(`listItemValue`),l(t)):n(t)}function l(t){return e.enter(`listItemMarker`),e.consume(t),e.exit(`listItemMarker`),r.containerState.marker=r.containerState.marker||t,e.check(mw,r.interrupt?n:u,e.attempt(PT,f,d))}function u(e){return r.containerState.initialBlankLine=!0,a++,f(e)}function d(t){return JC(t)?(e.enter(`listItemPrefixWhitespace`),e.consume(t),e.exit(`listItemPrefixWhitespace`),f):n(t)}function f(n){return r.containerState.size=a+r.sliceSerialize(e.exit(`listItemPrefix`),!0).length,t(n)}}function LT(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(mw,i,a);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,$C(e,t,`listItemIndent`,r.containerState.size+1)(n)}function a(n){return r.containerState.furtherBlankLines||!JC(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(FT,t,o)(n))}function o(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,$C(e,e.attempt(NT,t,n),`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(i)}}function RT(e,t,n){let r=this;return $C(e,i,`listItemIndent`,r.containerState.size+1);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`listItemIndent`&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)}}function zT(e){e.exit(this.containerState.type)}function BT(e,t,n){let r=this;return $C(e,i,`listItemPrefixWhitespace`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:5);function i(e){let i=r.events[r.events.length-1];return!JC(e)&&i&&i[1].type===`listItemPrefixWhitespace`?t(e):n(e)}}var VT={name:`setextUnderline`,resolveTo:HT,tokenize:UT};function HT(e,t){let n=e.length,r,i,a;for(;n--;)if(e[n][0]===`enter`){if(e[n][1].type===`content`){r=n;break}e[n][1].type===`paragraph`&&(i=n)}else e[n][1].type===`content`&&e.splice(n,1),!a&&e[n][1].type===`definition`&&(a=n);let o={type:`setextHeading`,start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type=`setextHeadingText`,a?(e.splice(i,0,[`enter`,o,t]),e.splice(a+1,0,[`exit`,e[r][1],t]),e[r][1].end={...e[a][1].end}):e[r][1]=o,e.push([`exit`,o,t]),e}function UT(e,t,n){let r=this,i;return a;function a(t){let a=r.events.length,s;for(;a--;)if(r.events[a][1].type!==`lineEnding`&&r.events[a][1].type!==`linePrefix`&&r.events[a][1].type!==`content`){s=r.events[a][1].type===`paragraph`;break}return!r.parser.lazy[r.now().line]&&(r.interrupt||s)?(e.enter(`setextHeadingLine`),i=t,o(t)):n(t)}function o(t){return e.enter(`setextHeadingLineSequence`),s(t)}function s(t){return t===i?(e.consume(t),s):(e.exit(`setextHeadingLineSequence`),JC(t)?$C(e,c,`lineSuffix`)(t):c(t))}function c(r){return r===null||q(r)?(e.exit(`setextHeadingLine`),t(r)):n(r)}}var WT={tokenize:GT};function GT(e){let t=this,n=e.attempt(mw,r,e.attempt(this.parser.constructs.flowInitial,i,$C(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Bw,i)),`linePrefix`)));return n;function r(r){if(r===null){e.consume(r);return}return e.enter(`lineEndingBlank`),e.consume(r),e.exit(`lineEndingBlank`),t.currentConstruct=void 0,n}function i(r){if(r===null){e.consume(r);return}return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),t.currentConstruct=void 0,n}}var KT={resolveAll:XT()},qT=YT(`string`),JT=YT(`text`);function YT(e){return{resolveAll:XT(e===`text`?ZT:void 0),tokenize:t};function t(t){let n=this,r=this.parser.constructs[e],i=t.attempt(r,a,o);return a;function a(e){return c(e)?i(e):o(e)}function o(e){if(e===null){t.consume(e);return}return t.enter(`data`),t.consume(e),s}function s(e){return c(e)?(t.exit(`data`),i(e)):(t.consume(e),s)}function c(e){if(e===null)return!0;let t=r[e],i=-1;if(t)for(;++i<t.length;){let e=t[i];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}}}function XT(e){return t;function t(t,n){let r=-1,i;for(;++r<=t.length;)i===void 0?t[r]&&t[r][1].type===`data`&&(i=r,r++):(!t[r]||t[r][1].type!==`data`)&&(r!==i+2&&(t[i][1].end=t[r-1][1].end,t.splice(i+2,r-i-2),r=i+2),i=void 0);return e?e(t,n):t}}function ZT(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type===`lineEnding`)&&e[n-1][1].type===`data`){let r=e[n-1][1],i=t.sliceStream(r),a=i.length,o=-1,s=0,c;for(;a--;){let e=i[a];if(typeof e==`string`){for(o=e.length;e.charCodeAt(o-1)===32;)s++,o--;if(o)break;o=-1}else if(e===-2)c=!0,s++;else if(e!==-1){a++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(s=0),s){let i={type:n===e.length||c||s<2?`lineSuffix`:`hardBreakTrailing`,start:{_bufferIndex:a?o:r.start._bufferIndex+o,_index:r.start._index+a,line:r.end.line,column:r.end.column-s,offset:r.end.offset-s},end:{...r.end}};r.end={...i.start},r.start.offset===r.end.offset?Object.assign(r,i):(e.splice(n,0,[`enter`,i,t],[`exit`,i,t]),n+=2)}n++}return e}var QT=e({attentionMarkers:()=>oE,contentInitial:()=>eE,disable:()=>sE,document:()=>$T,flow:()=>nE,flowInitial:()=>tE,insideSpan:()=>aE,string:()=>rE,text:()=>iE}),$T={42:NT,43:NT,45:NT,48:NT,49:NT,50:NT,51:NT,52:NT,53:NT,54:NT,55:NT,56:NT,57:NT,62:gw},eE={91:Yw},tE={[-2]:Ow,[-1]:Ow,32:Ow},nE={35:tT,42:jT,45:[VT,jT],60:oT,61:VT,95:jT,96:Tw,126:Tw},rE={38:Sw,92:bw},iE={[-5]:kT,[-4]:kT,[-3]:kT,33:TT,38:Sw,42:cw,60:[fw,pT],91:DT,92:[$w,bw],93:hT,95:cw,96:Mw},aE={null:[cw,KT]},oE={null:[42,95]},sE={null:[]};function cE(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},a=[],o=[],s=[],c={attempt:C(x),check:C(S),consume:v,enter:y,exit:b,interrupt:C(S,{interrupt:!0})},l={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d},u=t.tokenize.call(l,c);return t.resolveAll&&a.push(t),l;function d(e){return o=NC(o,e),g(),o[o.length-1]===null?(w(t,0),l.events=sw(a,l.events,l),l.events):[]}function f(e,t){return uE(p(e),t)}function p(e){return lE(o,e)}function m(){let{_bufferIndex:e,_index:t,line:n,column:i,offset:a}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:a}}function h(e){i[e.line]=e.column,E()}function g(){let e;for(;r._index<o.length;){let t=o[r._index];if(typeof t==`string`)for(e=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===e&&r._bufferIndex<t.length;)_(t.charCodeAt(r._bufferIndex));else _(t)}}function _(e){u=u(e)}function v(e){q(e)?(r.line++,r.column=1,r.offset+=e===-3?2:1,E()):e!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),l.previous=e}function y(e,t){let n=t||{};return n.type=e,n.start=m(),l.events.push([`enter`,n,l]),s.push(n),n}function b(e){let t=s.pop();return t.end=m(),l.events.push([`exit`,t,l]),t}function x(e,t){w(e,t.from)}function S(e,t){t.restore()}function C(e,t){return n;function n(n,r,i){let a,o,s,u;return Array.isArray(n)?f(n):`tokenize`in n?f([n]):d(n);function d(e){return t;function t(t){let n=t!==null&&e[t],r=t!==null&&e.null;return f([...Array.isArray(n)?n:n?[n]:[],...Array.isArray(r)?r:r?[r]:[]])(t)}}function f(e){return a=e,o=0,e.length===0?i:p(e[o])}function p(e){return n;function n(n){return u=T(),s=e,e.partial||(l.currentConstruct=e),e.name&&l.parser.constructs.disable.null.includes(e.name)?h(n):e.tokenize.call(t?Object.assign(Object.create(l),t):l,c,m,h)(n)}}function m(t){return e(s,u),r}function h(e){return u.restore(),++o<a.length?p(a[o]):i}}}function w(e,t){e.resolveAll&&!a.includes(e)&&a.push(e),e.resolve&&MC(l.events,t,l.events.length-t,e.resolve(l.events.slice(t),l)),e.resolveTo&&(l.events=e.resolveTo(l.events,l))}function T(){let e=m(),t=l.previous,n=l.currentConstruct,i=l.events.length,a=Array.from(s);return{from:i,restore:o};function o(){r=e,l.previous=t,l.currentConstruct=n,l.events.length=i,s=a,E()}}function E(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function lE(e,t){let n=t.start._index,r=t.start._bufferIndex,i=t.end._index,a=t.end._bufferIndex,o;if(n===i)o=[e[n].slice(r,a)];else{if(o=e.slice(n,i),r>-1){let e=o[0];typeof e==`string`?o[0]=e.slice(r):o.shift()}a>0&&o.push(e[i].slice(0,a))}return o}function uE(e,t){let n=-1,r=[],i;for(;++n<e.length;){let a=e[n],o;if(typeof a==`string`)o=a;else switch(a){case-5:o=`\r`;break;case-4:o=`
60
+ `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Mp,s=!_p.jitless,c=s&&Np.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?tg([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function ig(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Jp(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Zp(e,r,vp())))}),t)}var ag=I(`$ZodUnion`,(e,t)=>{gh.init(e,t),Ep(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),Ep(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Ep(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Ep(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Cp(e.source)).join(`|`)})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);if(t instanceof Promise)s.push(t),o=!0;else{if(t.issues.length===0)return t;s.push(t)}}return o?Promise.all(s).then(t=>ig(t,i,e,a)):ig(s,i,e,a)}}),og=I(`$ZodIntersection`,(e,t)=>{gh.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>cg(e,t,n)):cg(e,i,a)}});function sg(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Pp(e)&&Pp(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=sg(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=sg(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function cg(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),Jp(e))return e;let r=sg(t.value,n.value);if(!r.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}var lg=I(`$ZodRecord`,(e,t)=>{gh.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Pp(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...Yp(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...Yp(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Zp(e,r,vp())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Yp(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Yp(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),ug=I(`$ZodEnum`,(e,t)=>{gh.init(e,t);let n=yp(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Ip.has(typeof e)).map(e=>typeof e==`string`?Lp(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),dg=I(`$ZodLiteral`,(e,t)=>{if(gh.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?Lp(e):e?Lp(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),fg=I(`$ZodTransform`,(e,t)=>{gh.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new gp(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new hp;return n.value=i,n}});function pg(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var mg=I(`$ZodOptional`,(e,t)=>{gh.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,Ep(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ep(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Cp(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>pg(t,e.value)):pg(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),hg=I(`$ZodNullable`,(e,t)=>{gh.init(e,t),Ep(e._zod,`optin`,()=>t.innerType._zod.optin),Ep(e._zod,`optout`,()=>t.innerType._zod.optout),Ep(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Cp(e.source)}|null)$`):void 0}),Ep(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),gg=I(`$ZodDefault`,(e,t)=>{gh.init(e,t),e._zod.optin=`optional`,Ep(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>_g(e,t)):_g(r,t)}});function _g(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var vg=I(`$ZodPrefault`,(e,t)=>{gh.init(e,t),e._zod.optin=`optional`,Ep(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),yg=I(`$ZodNonOptional`,(e,t)=>{gh.init(e,t),Ep(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>bg(t,e)):bg(i,e)}});function bg(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var xg=I(`$ZodCatch`,(e,t)=>{gh.init(e,t),Ep(e._zod,`optin`,()=>t.innerType._zod.optin),Ep(e._zod,`optout`,()=>t.innerType._zod.optout),Ep(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Zp(e,n,vp()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Zp(e,n,vp()))},input:e.value}),e.issues=[]),e)}}),Sg=I(`$ZodPipe`,(e,t)=>{gh.init(e,t),Ep(e._zod,`values`,()=>t.in._zod.values),Ep(e._zod,`optin`,()=>t.in._zod.optin),Ep(e._zod,`optout`,()=>t.out._zod.optout),Ep(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Cg(e,t.in,n)):Cg(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Cg(e,t.out,n)):Cg(r,t.out,n)}});function Cg(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var wg=I(`$ZodReadonly`,(e,t)=>{gh.init(e,t),Ep(e._zod,`propValues`,()=>t.innerType._zod.propValues),Ep(e._zod,`values`,()=>t.innerType._zod.values),Ep(e._zod,`optin`,()=>t.innerType._zod.optin),Ep(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Tg):Tg(r)}});function Tg(e){return e.value=Object.freeze(e.value),e}var Eg=I(`$ZodLazy`,(e,t)=>{gh.init(e,t),Ep(e._zod,`innerType`,()=>t.getter()),Ep(e._zod,`pattern`,()=>e._zod.innerType._zod.pattern),Ep(e._zod,`propValues`,()=>e._zod.innerType._zod.propValues),Ep(e._zod,`optin`,()=>e._zod.innerType._zod.optin??void 0),Ep(e._zod,`optout`,()=>e._zod.innerType._zod.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Dg=I(`$ZodCustom`,(e,t)=>{Zm.init(e,t),gh.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Og(t,n,r,e));Og(i,n,r,e)}});function Og(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push($p(e))}}var kg=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ag(){return new kg}var jg=Ag();function Mg(e,t){return new e({type:`string`,...L(t)})}function Ng(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...L(t)})}function Pg(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...L(t)})}function Fg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...L(t)})}function Ig(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...L(t)})}function Lg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...L(t)})}function Rg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...L(t)})}function zg(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...L(t)})}function Bg(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...L(t)})}function Vg(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...L(t)})}function Hg(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...L(t)})}function Ug(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...L(t)})}function Wg(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...L(t)})}function Gg(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...L(t)})}function Kg(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...L(t)})}function qg(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...L(t)})}function Jg(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...L(t)})}function Yg(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...L(t)})}function Xg(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...L(t)})}function Zg(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...L(t)})}function Qg(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...L(t)})}function $g(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...L(t)})}function e_(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...L(t)})}function t_(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...L(t)})}function n_(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...L(t)})}function r_(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...L(t)})}function i_(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...L(t)})}function a_(e,t){return new e({type:`number`,checks:[],...L(t)})}function o_(e,t){return new e({type:`number`,coerce:!0,checks:[],...L(t)})}function s_(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...L(t)})}function c_(e,t){return new e({type:`boolean`,...L(t)})}function l_(e,t){return new e({type:`null`,...L(t)})}function u_(e){return new e({type:`unknown`})}function d_(e,t){return new e({type:`never`,...L(t)})}function f_(e,t){return new $m({check:`less_than`,...L(t),value:e,inclusive:!1})}function p_(e,t){return new $m({check:`less_than`,...L(t),value:e,inclusive:!0})}function m_(e,t){return new eh({check:`greater_than`,...L(t),value:e,inclusive:!1})}function h_(e,t){return new eh({check:`greater_than`,...L(t),value:e,inclusive:!0})}function g_(e,t){return new th({check:`multiple_of`,...L(t),value:e})}function __(e,t){return new rh({check:`max_length`,...L(t),maximum:e})}function v_(e,t){return new ih({check:`min_length`,...L(t),minimum:e})}function y_(e,t){return new ah({check:`length_equals`,...L(t),length:e})}function b_(e,t){return new sh({check:`string_format`,format:`regex`,...L(t),pattern:e})}function x_(e){return new ch({check:`string_format`,format:`lowercase`,...L(e)})}function S_(e){return new lh({check:`string_format`,format:`uppercase`,...L(e)})}function C_(e,t){return new uh({check:`string_format`,format:`includes`,...L(t),includes:e})}function w_(e,t){return new dh({check:`string_format`,format:`starts_with`,...L(t),prefix:e})}function T_(e,t){return new fh({check:`string_format`,format:`ends_with`,...L(t),suffix:e})}function E_(e){return new ph({check:`overwrite`,tx:e})}function D_(e){return E_(t=>t.normalize(e))}function O_(){return E_(e=>e.trim())}function k_(){return E_(e=>e.toLowerCase())}function A_(){return E_(e=>e.toUpperCase())}function j_(e,t,n){return new e({type:`array`,element:t,...L(n)})}function M_(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...L(n)})}function N_(e){let t=P_(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push($p(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push($p(r))}},e(n.value,n)));return t}function P_(e,t){let n=new Zm({check:`custom`,...L(t)});return n._zod.check=e,n}var F_=I(`ZodISODateTime`,(e,t)=>{Ah.init(e,t),ov.init(e,t)});function I_(e){return t_(F_,e)}var L_=I(`ZodISODate`,(e,t)=>{jh.init(e,t),ov.init(e,t)});function R_(e){return n_(L_,e)}var z_=I(`ZodISOTime`,(e,t)=>{Mh.init(e,t),ov.init(e,t)});function B_(e){return r_(z_,e)}var V_=I(`ZodISODuration`,(e,t)=>{Nh.init(e,t),ov.init(e,t)});function H_(e){return i_(V_,e)}var U_=(e,t)=>{tm.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>im(e,t)},flatten:{value:t=>rm(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,bp,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,bp,2)}},isEmpty:{get(){return e.issues.length===0}}})};I(`ZodError`,U_);var W_=I(`ZodError`,U_,{Parent:Error}),G_=am(W_),K_=om(W_),q_=sm(W_),J_=lm(W_),Y_=dm(W_),X_=fm(W_),Z_=pm(W_),Q_=mm(W_),$_=hm(W_),ev=gm(W_),tv=_m(W_),nv=vm(W_),rv=I(`ZodType`,(e,t)=>(gh.init(e,t),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>Rp(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>G_(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>q_(e,t,n),e.parseAsync=async(t,n)=>K_(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>J_(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Y_(e,t,n),e.decode=(t,n)=>X_(e,t,n),e.encodeAsync=async(t,n)=>Z_(e,t,n),e.decodeAsync=async(t,n)=>Q_(e,t,n),e.safeEncode=(t,n)=>$_(e,t,n),e.safeDecode=(t,n)=>ev(e,t,n),e.safeEncodeAsync=async(t,n)=>tv(e,t,n),e.safeDecodeAsync=async(t,n)=>nv(e,t,n),e.refine=(t,n)=>e.check(hy(t,n)),e.superRefine=t=>e.check(gy(t)),e.overwrite=t=>e.check(E_(t)),e.optional=()=>Zv(e),e.nullable=()=>$v(e),e.nullish=()=>Zv($v(e)),e.nonoptional=t=>ay(e,t),e.array=()=>B(e),e.or=t=>Bv([e,t]),e.and=t=>Hv(e,t),e.transform=t=>ly(e,Yv(t)),e.default=t=>ty(e,t),e.prefault=t=>ry(e,t),e.catch=t=>sy(e,t),e.pipe=t=>ly(e,t),e.readonly=()=>dy(e),e.describe=t=>{let n=e.clone();return jg.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return jg.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return jg.get(e);let n=e.clone();return jg.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),iv=I(`_ZodString`,(e,t)=>{_h.init(e,t),rv.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(b_(...t)),e.includes=(...t)=>e.check(C_(...t)),e.startsWith=(...t)=>e.check(w_(...t)),e.endsWith=(...t)=>e.check(T_(...t)),e.min=(...t)=>e.check(v_(...t)),e.max=(...t)=>e.check(__(...t)),e.length=(...t)=>e.check(y_(...t)),e.nonempty=(...t)=>e.check(v_(1,...t)),e.lowercase=t=>e.check(x_(t)),e.uppercase=t=>e.check(S_(t)),e.trim=()=>e.check(O_()),e.normalize=(...t)=>e.check(D_(...t)),e.toLowerCase=()=>e.check(k_()),e.toUpperCase=()=>e.check(A_())}),av=I(`ZodString`,(e,t)=>{_h.init(e,t),iv.init(e,t),e.email=t=>e.check(Ng(sv,t)),e.url=t=>e.check(zg(uv,t)),e.jwt=t=>e.check(e_(Tv,t)),e.emoji=t=>e.check(Bg(dv,t)),e.guid=t=>e.check(Pg(cv,t)),e.uuid=t=>e.check(Fg(lv,t)),e.uuidv4=t=>e.check(Ig(lv,t)),e.uuidv6=t=>e.check(Lg(lv,t)),e.uuidv7=t=>e.check(Rg(lv,t)),e.nanoid=t=>e.check(Vg(fv,t)),e.guid=t=>e.check(Pg(cv,t)),e.cuid=t=>e.check(Hg(pv,t)),e.cuid2=t=>e.check(Ug(mv,t)),e.ulid=t=>e.check(Wg(hv,t)),e.base64=t=>e.check(Zg(Sv,t)),e.base64url=t=>e.check(Qg(Cv,t)),e.xid=t=>e.check(Gg(gv,t)),e.ksuid=t=>e.check(Kg(_v,t)),e.ipv4=t=>e.check(qg(vv,t)),e.ipv6=t=>e.check(Jg(yv,t)),e.cidrv4=t=>e.check(Yg(bv,t)),e.cidrv6=t=>e.check(Xg(xv,t)),e.e164=t=>e.check($g(wv,t)),e.datetime=t=>e.check(I_(t)),e.date=t=>e.check(R_(t)),e.time=t=>e.check(B_(t)),e.duration=t=>e.check(H_(t))});function R(e){return Mg(av,e)}var ov=I(`ZodStringFormat`,(e,t)=>{vh.init(e,t),iv.init(e,t)}),sv=I(`ZodEmail`,(e,t)=>{xh.init(e,t),ov.init(e,t)}),cv=I(`ZodGUID`,(e,t)=>{yh.init(e,t),ov.init(e,t)}),lv=I(`ZodUUID`,(e,t)=>{bh.init(e,t),ov.init(e,t)}),uv=I(`ZodURL`,(e,t)=>{Sh.init(e,t),ov.init(e,t)}),dv=I(`ZodEmoji`,(e,t)=>{Ch.init(e,t),ov.init(e,t)}),fv=I(`ZodNanoID`,(e,t)=>{wh.init(e,t),ov.init(e,t)}),pv=I(`ZodCUID`,(e,t)=>{Th.init(e,t),ov.init(e,t)}),mv=I(`ZodCUID2`,(e,t)=>{Eh.init(e,t),ov.init(e,t)}),hv=I(`ZodULID`,(e,t)=>{Dh.init(e,t),ov.init(e,t)}),gv=I(`ZodXID`,(e,t)=>{Oh.init(e,t),ov.init(e,t)}),_v=I(`ZodKSUID`,(e,t)=>{kh.init(e,t),ov.init(e,t)}),vv=I(`ZodIPv4`,(e,t)=>{Ph.init(e,t),ov.init(e,t)}),yv=I(`ZodIPv6`,(e,t)=>{Fh.init(e,t),ov.init(e,t)}),bv=I(`ZodCIDRv4`,(e,t)=>{Ih.init(e,t),ov.init(e,t)}),xv=I(`ZodCIDRv6`,(e,t)=>{Lh.init(e,t),ov.init(e,t)}),Sv=I(`ZodBase64`,(e,t)=>{zh.init(e,t),ov.init(e,t)}),Cv=I(`ZodBase64URL`,(e,t)=>{Vh.init(e,t),ov.init(e,t)}),wv=I(`ZodE164`,(e,t)=>{Hh.init(e,t),ov.init(e,t)}),Tv=I(`ZodJWT`,(e,t)=>{Wh.init(e,t),ov.init(e,t)}),Ev=I(`ZodNumber`,(e,t)=>{Gh.init(e,t),rv.init(e,t),e.gt=(t,n)=>e.check(m_(t,n)),e.gte=(t,n)=>e.check(h_(t,n)),e.min=(t,n)=>e.check(h_(t,n)),e.lt=(t,n)=>e.check(f_(t,n)),e.lte=(t,n)=>e.check(p_(t,n)),e.max=(t,n)=>e.check(p_(t,n)),e.int=t=>e.check(Ov(t)),e.safe=t=>e.check(Ov(t)),e.positive=t=>e.check(m_(0,t)),e.nonnegative=t=>e.check(h_(0,t)),e.negative=t=>e.check(f_(0,t)),e.nonpositive=t=>e.check(p_(0,t)),e.multipleOf=(t,n)=>e.check(g_(t,n)),e.step=(t,n)=>e.check(g_(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function z(e){return a_(Ev,e)}var Dv=I(`ZodNumberFormat`,(e,t)=>{Kh.init(e,t),Ev.init(e,t)});function Ov(e){return s_(Dv,e)}var kv=I(`ZodBoolean`,(e,t)=>{qh.init(e,t),rv.init(e,t)});function Av(e){return c_(kv,e)}var jv=I(`ZodNull`,(e,t)=>{Jh.init(e,t),rv.init(e,t)});function Mv(e){return l_(jv,e)}var Nv=I(`ZodUnknown`,(e,t)=>{Yh.init(e,t),rv.init(e,t)});function Pv(){return u_(Nv)}var Fv=I(`ZodNever`,(e,t)=>{Xh.init(e,t),rv.init(e,t)});function Iv(e){return d_(Fv,e)}var Lv=I(`ZodArray`,(e,t)=>{Qh.init(e,t),rv.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(v_(t,n)),e.nonempty=t=>e.check(v_(1,t)),e.max=(t,n)=>e.check(__(t,n)),e.length=(t,n)=>e.check(y_(t,n)),e.unwrap=()=>e.element});function B(e,t){return j_(Lv,e,t)}var Rv=I(`ZodObject`,(e,t)=>{rg.init(e,t),rv.init(e,t),Ep(e,`shape`,()=>t.shape),e.keyof=()=>H(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Pv()}),e.loose=()=>e.clone({...e._zod.def,catchall:Pv()}),e.strict=()=>e.clone({...e._zod.def,catchall:Iv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Up(e,t),e.safeExtend=t=>Wp(e,t),e.merge=t=>Gp(e,t),e.pick=t=>Vp(e,t),e.omit=t=>Hp(e,t),e.partial=(...t)=>Kp(Xv,e,t[0]),e.required=(...t)=>qp(iy,e,t[0])});function V(e,t){return new Rv({type:`object`,get shape(){return Op(this,`shape`,e?Dp(e):{}),this.shape},...L(t)})}var zv=I(`ZodUnion`,(e,t)=>{ag.init(e,t),rv.init(e,t),e.options=t.options});function Bv(e,t){return new zv({type:`union`,options:e,...L(t)})}var Vv=I(`ZodIntersection`,(e,t)=>{og.init(e,t),rv.init(e,t)});function Hv(e,t){return new Vv({type:`intersection`,left:e,right:t})}var Uv=I(`ZodRecord`,(e,t)=>{lg.init(e,t),rv.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Wv(e,t,n){return new Uv({type:`record`,keyType:e,valueType:t,...L(n)})}var Gv=I(`ZodEnum`,(e,t)=>{ug.init(e,t),rv.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Gv({...t,checks:[],...L(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Gv({...t,checks:[],...L(r),entries:i})}});function H(e,t){return new Gv({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...L(t)})}var Kv=I(`ZodLiteral`,(e,t)=>{dg.init(e,t),rv.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function qv(e,t){return new Kv({type:`literal`,values:Array.isArray(e)?e:[e],...L(t)})}var Jv=I(`ZodTransform`,(e,t)=>{fg.init(e,t),rv.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new gp(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push($p(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push($p(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Yv(e){return new Jv({type:`transform`,transform:e})}var Xv=I(`ZodOptional`,(e,t)=>{mg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Zv(e){return new Xv({type:`optional`,innerType:e})}var Qv=I(`ZodNullable`,(e,t)=>{hg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function $v(e){return new Qv({type:`nullable`,innerType:e})}var ey=I(`ZodDefault`,(e,t)=>{gg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ty(e,t){return new ey({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Fp(t)}})}var ny=I(`ZodPrefault`,(e,t)=>{vg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ry(e,t){return new ny({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Fp(t)}})}var iy=I(`ZodNonOptional`,(e,t)=>{yg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ay(e,t){return new iy({type:`nonoptional`,innerType:e,...L(t)})}var oy=I(`ZodCatch`,(e,t)=>{xg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function sy(e,t){return new oy({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var cy=I(`ZodPipe`,(e,t)=>{Sg.init(e,t),rv.init(e,t),e.in=t.in,e.out=t.out});function ly(e,t){return new cy({type:`pipe`,in:e,out:t})}var uy=I(`ZodReadonly`,(e,t)=>{wg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.innerType});function dy(e){return new uy({type:`readonly`,innerType:e})}var fy=I(`ZodLazy`,(e,t)=>{Eg.init(e,t),rv.init(e,t),e.unwrap=()=>e._zod.def.getter()});function py(e){return new fy({type:`lazy`,getter:e})}var my=I(`ZodCustom`,(e,t)=>{Dg.init(e,t),rv.init(e,t)});function hy(e,t={}){return M_(my,e,t)}function gy(e){return N_(e)}function _y(e){let t=py(()=>Bv([R(e),z(),Av(),Mv(),B(t),Wv(R(),t)]));return t}function vy(e){return o_(Ev,e)}var U=R().uuid(),W=R().datetime({offset:!0}),yy=R().regex(/^[a-f0-9]{64}$/);R().trim().min(1);var by=H([`owner`,`admin`,`security_manager`,`operator`,`viewer`,`auditor`]),xy=H([`R0`,`R1`,`R2`]),Sy=H([`public`,`internal`,`confidential`,`restricted`]);V({cursor:R().min(1).optional(),limit:vy().int().min(1).max(200).default(50)}),V({nextCursor:R().min(1).optional(),hasMore:Av()}),V({idempotencyKey:R().trim().min(8).max(200),expectedVersion:z().int().nonnegative().optional()}),V({type:R().default(`about:blank`),title:R(),status:z().int().min(400).max(599),detail:R().optional(),instance:R().optional(),code:R().regex(/^[a-z0-9_]+$/),requestId:R(),errors:B(V({path:R(),message:R(),code:R().optional()})).optional()});var Cy=V({providerId:R().nullable(),modelId:R().nullable(),inputTokens:z().int().nonnegative(),outputTokens:z().int().nonnegative(),reasoningTokens:z().int().nonnegative(),cacheReadTokens:z().int().nonnegative(),cacheWriteTokens:z().int().nonnegative(),estimatedCostUsd:z().nonnegative(),pricingSource:R().nullable(),pricingAsOf:R().nullable()}),wy=V({id:U,organizationId:U,workspaceId:U,projectId:U,runId:U.nullable(),externalSessionId:R().nullable(),createdBy:U,status:H([`active`,`waiting`,`completed`,`failed`,`cancelled`]),mode:H([`autonomous`,`guided`]),model:R().nullable(),costUsd:z().nonnegative(),usage:Cy,sensitive:Av(),createdAt:W,lastActivityAt:W}),Ty=V({id:U,sessionId:U,role:H([`user`,`assistant`,`system`,`tool`]),redactedPreview:R(),sensitivePayloadArtifactId:U.nullable(),createdAt:W}),Ey=V({id:U,sessionId:U,runId:U.nullable(),stageId:U.nullable(),externalToolCallId:R().nullable(),toolName:R().min(1),status:H([`running`,`completed`,`failed`,`cancelled`]),inputHash:yy,outputArtifactId:U.nullable(),startedAt:W,completedAt:W.nullable()});V({session:wy,messages:B(Ty),toolActivities:B(Ey)}),V({expectedRunVersion:z().int().nonnegative(),reason:R().trim().min(1).max(1e3)});var Dy=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Oy=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ky=(e,t)=>e>>>t|e<<32-t,Ay=e=>ky(e,7)^ky(e,18)^e>>>3,jy=e=>ky(e,17)^ky(e,19)^e>>>10,My=e=>ky(e,2)^ky(e,13)^ky(e,22),Ny=e=>ky(e,6)^ky(e,11)^ky(e,25),Py=(e,t,n)=>e&t^~e&n,Fy=(e,t,n)=>e&t^e&n^t&n;function Iy(e){let t=new TextEncoder().encode(e),n=Math.floor(t.length*8/4294967296),r=t.length*8>>>0,i=new Uint8Array(((t.length+8>>6)+1)*64);i.set(t),i[t.length]=128;let a=new DataView(i.buffer);a.setUint32(i.length-8,n),a.setUint32(i.length-4,r);let o=new Uint32Array(Oy),s=new Uint32Array(64);for(let e=0;e<i.length;e+=64){for(let t=0;t<16;t++)s[t]=a.getUint32(e+t*4);for(let e=16;e<64;e++){let t=s[e-15],n=s[e-2];s[e]=jy(n)+s[e-7]+Ay(t)+s[e-16]>>>0}let t=o[0],n=o[1],r=o[2],i=o[3],c=o[4],l=o[5],u=o[6],d=o[7];for(let e=0;e<64;e++){let a=d+Ny(c)+Py(c,l,u)+Dy[e]+s[e]>>>0,o=My(t)+Fy(t,n,r)>>>0;d=u,u=l,l=c,c=i+a>>>0,i=r,r=n,n=t,t=a+o>>>0}o[0]=o[0]+t>>>0,o[1]=o[1]+n>>>0,o[2]=o[2]+r>>>0,o[3]=o[3]+i>>>0,o[4]=o[4]+c>>>0,o[5]=o[5]+l>>>0,o[6]=o[6]+u>>>0,o[7]=o[7]+d>>>0}let c=``;for(let e=0;e<8;e++)c+=o[e].toString(16).padStart(8,`0`);return c}var Ly=H([`informational`,`low`,`medium`,`high`,`critical`]),Ry=H([`clean`,`informational`,`actionable`,`critical`]),zy=V({fingerprint:yy.optional(),title:R().min(1),severity:H([`info`,`low`,`medium`,`high`,`critical`]),details:R().default(``),targetUrl:R().optional(),cvss:R().default(``),cweId:R().default(``),invariant:R().default(``),rootCause:R().default(``),impact:R().default(``),reproduction:B(R().min(1)).default([]),remediation:R().default(``),disposition:H([`candidate`,`confirmed`,`refuted`,`inconclusive`]).default(`candidate`),evidenceRefs:B(yy).default([])}),By=V({description:R().min(1),artifactType:R().min(1),data:_y().refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=65536,{message:`Evidence metadata must not exceed 64 KiB.`}).default(null),timestamp:z().int().nonnegative(),stageId:U.optional(),agentSessionId:U.optional()}),Vy=H([`observation`,`artifact`,`control_result`,`manual_confirmation`,`report`]),Hy=V({fingerprint:yy,title:R().min(1),description:R().default(``),severity:Ly,cvss:R().default(``),cweId:R().default(``),invariant:R().default(``),rootCause:R().default(``),impact:R().default(``),reproduction:B(R()).default([]),remediation:R().default(``),targetUrl:R().optional(),disposition:H([`candidate`,`confirmed`,`refuted`,`inconclusive`]),evidenceRefs:B(yy).default([]),status:H([`open`]).default(`open`)}).strict(),Uy=V({fingerprint:yy,kind:Vy,title:R().min(1),summary:R().default(``),artifactType:R(),sha256:yy,timestamp:z().int().nonnegative(),stageId:U.optional(),agentSessionId:U.optional(),classification:Sy.default(`confidential`)}).strict(),Wy=V({satisfied:Av(),missing:B(R())}).strict(),Gy=V({id:U,runId:U,projectId:U,workflowKey:R().min(1),workflowVersionId:U,version:z().int().nonnegative(),contentHash:yy,target:R().min(1),scopeOrigins:B(R()).default([]),summary:R().default(``),posture:Ry,findings:B(Hy).default([]),unverifiedLeads:B(Hy).default([]),evidence:B(Uy).default([]),negativeControls:B(R()).default([]),classification:Sy.default(`confidential`),publicationState:H([`draft`,`blocked`,`published`]).default(`draft`),gate:Wy,parentContentHash:yy.nullable().default(null),editorialMarkdownHash:yy.nullable().default(null),publishedAt:W.optional(),createdAt:W}).strict();V({agentSessionId:R().min(1),runId:U.optional(),stageId:U.optional(),stageKey:R().min(1),target:R().min(1),model:R().min(1)}),V({agentSessionId:R().min(1),runId:U.optional(),stageId:U.optional(),stageKey:R().min(1),description:R().min(1),artifactType:R().min(1),data:_y().refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=65536,{message:`Evidence metadata must not exceed 64 KiB.`}).default(null),timestamp:z().int().nonnegative()}),V({agentSessionId:R().min(1),runId:U.optional(),stageId:U.optional(),stageKey:R().min(1),workflowKey:R().min(1),status:H([`succeeded`,`blocked`,`inconclusive`,`failed`]),terminationReason:R().max(300).optional(),findings:z().int().nonnegative(),evidence:z().int().nonnegative(),findingItems:B(zy).default([]),evidenceItems:B(By).default([]),negativeControls:B(R().min(1).max(4e3)).max(500).default([]),toolAttempts:z().int().nonnegative(),toolsExecuted:z().int().nonnegative(),toolsErrored:z().int().nonnegative(),pricingUnknown:Av().optional()}),V({runId:U.optional(),stageId:U.optional(),stageKey:R().min(1),kind:H([`finding`,`evidence`]),index:z().int().nonnegative(),issues:B(R().max(120)).min(1).max(20)}),V({id:U,organizationId:U,name:R().trim().min(1).max(120),slug:R().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),version:z().int().nonnegative(),createdAt:W,updatedAt:W}),V({id:U,organizationId:U,workspaceId:U,name:R().trim().min(1).max(160),slug:R().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),archivedAt:W.nullable(),version:z().int().nonnegative(),createdAt:W,updatedAt:W}),V({name:R().trim().min(1).max(160),slug:R().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)});var Ky=V({id:U,kind:H([`domain`,`ip`,`cidr`,`url`,`repository`,`api`,`android`,`ios`,`custom`]),locator:R().trim().min(1).max(2048),displayName:R().trim().min(1).max(240)}),qy=V({id:U,owner:R().trim().min(1),documentArtifactId:U,validFrom:W,validUntil:W,allowedActions:B(R().min(1)).min(1),prohibitedActions:B(R().min(1)),sha256:yy}),Jy=V({requestsPerSecond:z().positive().optional(),concurrency:z().int().positive().optional(),durationSeconds:z().int().positive(),costUsd:z().nonnegative().optional(),modelTokens:z().int().nonnegative().optional()}),Yy=V({projectId:U,name:R().trim().min(1).max(160),targets:B(Ky).min(1),exclusions:B(R().trim().min(1)),authorization:qy.optional(),allowedRisk:xy,allowedActions:B(R().min(1)),prohibitedActions:B(R().min(1)),limits:Jy,requiredWorkerClass:R().trim().min(1),requiredCapabilities:B(R().trim().min(1)),credentialReferences:B(R().trim().min(1)),dataClassification:Sy,retentionPolicyId:U.optional(),notificationChannels:B(R().trim().min(1))}).extend({id:U,organizationId:U,workspaceId:U,revision:z().int().positive(),inputHash:yy,createdAt:W,createdBy:U}),Xy=H([`open`,`in_progress`,`accepted_risk`,`false_positive`,`remediated`,`verified`]);V({id:U,organizationId:U,workspaceId:U,projectId:U,title:R().min(1),description:R(),severity:H([`informational`,`low`,`medium`,`high`,`critical`]),status:Xy,fingerprint:yy,version:z().int().nonnegative(),firstSeenAt:W,lastSeenAt:W}),V({id:U,organizationId:U,workspaceId:U,projectId:U,runId:U.nullable(),stageId:U.nullable(),agentSessionId:U.nullable(),toolCallId:U.nullable(),kind:H([`observation`,`artifact`,`report`,`manual_confirmation`,`control_result`]),title:R().min(1),summary:R(),classification:Sy,artifactId:U.nullable(),sha256:yy,createdAt:W});var Zy=V({id:U,organizationId:U,workspaceId:U,projectId:U,runId:U,objectKey:R().min(1),sha256:yy,mimeType:R().min(1),size:z().int().nonnegative(),classification:Sy,createdBy:U,createdAt:W}),Qy=H([`internal-infrastructure`,`external-infrastructure`,`web-application`,`api-security`,`mobile-application`,`red-team-campaign`,`purple-team-validation`,`nist-csf-2`,`cis-controls-8-1`,`advanced-security-testing`,`remediation-validation`,`network-security-audit`]),$y=V({key:R().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),name:R().min(1),description:R().min(1),risk:xy,optional:Av().default(!1),requiredCapabilities:B(R().min(1)),skillRefs:B(R().min(1).max(80)).max(64).default([]),retrySafe:Av(),approvalCheckpoint:Av(),timeoutSeconds:z().int().positive()}),eb=V({id:U,key:Qy,version:R().regex(/^\d+\.\d+\.\d+$/),name:R().min(1),description:R().min(1),inputSchema:Wv(R(),Pv()),requiredCapabilities:B(R().min(1)),requiredIntegrations:B(R().min(1)),stages:B($y).min(1),evidenceRequirements:B(R().min(1)).min(1),completionCriteria:B(R().min(1)).min(1),publishedAt:W,contentHash:yy}),tb=V({code:H([`authorization_missing`,`authorization_expired`,`capability_missing`,`worker_missing`,`integration_missing`,`credential_missing`,`scope_invalid`,`approval_required`]),message:R().min(1),stageKey:R().optional(),capability:R().optional()}),nb=V({ready:Av(),launchState:H([`ready`,`blocked`,`awaiting_approval`]),highestRisk:xy,reasons:B(tb),matchingWorkerIds:B(U),inputHash:yy}),rb=H([`draft`,`blocked`,`awaiting_approval`,`queued`,`leased`,`running`,`cancel_requested`,`succeeded`,`failed`,`cancelled`,`expired`]),ib=H([`pending`,`blocked`,`awaiting_approval`,`queued`,`leased`,`running`,`paused`,`succeeded`,`failed`,`cancel_requested`,`cancelled`,`expired`,`skipped`]);V({projectId:U,assessmentProfileId:U,workflowKey:Qy,workflowVersionId:U,selectedStageKeys:B(R().min(1)).min(1).optional(),inputs:Wv(R(),Pv()),workerClass:R().min(1),mode:H([`autonomous`,`guided`]).default(`autonomous`)});var ab=V({id:U,organizationId:U,workspaceId:U,projectId:U,assessmentId:U,assessmentProfileId:U,workflowVersionId:U,workflowKey:Qy,requestedBy:U,state:rb,risk:xy,inputHash:yy,workerClass:R(),mode:H([`autonomous`,`guided`]),attempt:z().int().positive(),retryOfRunId:U.nullable(),agentSessionId:U.nullable(),usage:Cy,version:z().int().nonnegative(),createdAt:W,startedAt:W.nullable(),completedAt:W.nullable()}),ob=V({id:U,runId:U,key:R().min(1),position:z().int().nonnegative(),risk:xy,state:ib,workerId:U.nullable(),version:z().int().nonnegative(),startedAt:W.nullable(),completedAt:W.nullable()});V({id:z().int().positive(),runId:U,stageId:U.nullable(),type:R().min(1),payload:Wv(R(),Pv()),occurredAt:W}),V({after:z().int().nonnegative().default(0)});var sb=H([`internal-infrastructure`,`external-infrastructure`,`web-application`,`api-security`,`network-security-audit`]);V({target:R().trim().min(1).max(2048),workflowKey:sb,workflowVersionId:U,selectedStageKeys:B(R().min(1)).min(1).optional(),inputs:Wv(R(),Pv()).default({})}).extend({mode:H([`autonomous`,`guided`]).default(`autonomous`)}),V({owner:R().trim().min(2).max(200),statement:R().trim().min(20).max(2e3),validUntil:W});var cb=V({profile:Yy,authorization:qy,artifact:Zy}),lb=V({projectId:U,target:Ky,dossierKey:R().min(1),profileId:U,profileName:R().min(1),reusedProfile:Av()}),ub=V({binding:lb,readiness:nb}),db=V({binding:lb,run:ab,stages:B(ob),agentSession:wy}),fb=H([`pending`,`approved`,`rejected`,`expired`,`invalidated`]);V({id:U,organizationId:U,workspaceId:U,projectId:U,runId:U,stageId:U.nullable(),risk:xy,state:fb,requestedBy:U,requiredRole:H([`security_manager`,`owner_or_admin`]),decidedBy:U.nullable(),decisionRole:H([`owner`,`admin`,`security_manager`]).nullable(),workflowVersionId:U,inputHash:yy,scopeHash:yy,targetSetHash:yy,workerClass:R().min(1),actionSetHash:yy,expiresAt:W,decidedAt:W.nullable(),reason:R().nullable()}),V({decision:H([`approve`,`reject`]),reason:R().trim().min(1).max(2e3),passwordConfirmation:R().min(1),totpCode:R().regex(/^\d{6}$/).optional()}),V({id:U,sequence:z().int().positive(),organizationId:U,workspaceId:U,projectId:U.nullable(),actorId:U.nullable(),authSessionId:U.nullable(),action:R().min(1),resourceType:R().min(1),resourceId:R().min(1),requestId:R().min(1),correlationId:R().nullable(),ip:R().nullable(),userAgent:R().nullable(),outcome:H([`succeeded`,`denied`,`failed`]),reason:R().nullable(),beforeHash:yy.nullable(),afterHash:yy.nullable(),previousEventHash:yy.nullable(),eventHash:yy,occurredAt:W}),V({id:U,workspaceId:U,governanceDays:z().int().min(2555),assessmentDaysAfterClosure:z().int().min(1095),rawSessionDays:z().int().min(180),authSessionInvestigationDays:z().int().min(30),version:z().int().nonnegative()}),V({id:U,workspaceId:U,name:R().min(1),reason:R().min(1),resourceType:H([`assessment`,`run`,`agent_session`,`finding`,`artifact`]),resourceId:U,releasedAt:W.nullable(),createdAt:W});var pb=H([`workspace:admin`,`project:write`,`workflow:configure`,`run:launch`,`run:approve:r1`,`run:approve:r2`,`finding:write`,`session:read`,`session:read_sensitive`,`evidence:read`,`evidence:read_sensitive`,`governance:read`,`governance:write`]);V({user:V({id:U,email:R().email(),displayName:R().min(1),mfaEnrolled:Av(),createdAt:W}),organizationId:U,memberships:B(V({workspaceId:U,workspaceName:R().min(1),role:by,permissions:B(pb)})),activeWorkspaceId:U}),V({id:U,userId:U,createdAt:W,lastSeenAt:W,expiresAt:W,ip:R().nullable(),userAgent:R().nullable(),current:Av()}),V({password:R().min(1),totpCode:R().regex(/^\d{6}$/).optional()}),V({id:U,workspaceId:U,email:R().email(),role:by,expiresAt:W,acceptedAt:W.nullable(),createdAt:W});var mb=z().int().nonnegative(),hb=R().min(1),gb=H([`info`,`low`,`medium`,`high`,`critical`]),_b=H([`open`,`unverified`,`confirmed`,`remediating`,`remediated`,`verified`,`false_positive`,`accepted_risk`,`suppressed`]),vb=H([`cli`,`tui`,`web`,`github`,`system`]),yb=H([`scan`,`hunt`,`verify`,`import`]),bb=H([`queued`,`running`,`completed`,`failed`,`cancelled`]),xb=Wv(R(),Pv()),Sb=V({id:hb,workspaceID:hb,projectID:hb.nullable(),repositoryID:hb.nullable(),engagementID:hb.nullable(),targetID:hb.nullable(),parentRunID:hb.nullable(),sessionID:hb.nullable(),source:vb,kind:yb,status:bb,title:R(),requestedBy:R().nullable(),baseRevision:R().nullable(),headRevision:R().nullable(),promptRevision:R().nullable(),promptFingerprint:R().nullable(),configuration:xb.nullable(),summary:xb.nullable(),error:xb.nullable(),idempotencyKey:R().nullable(),createdAt:mb,startedAt:mb.nullable(),completedAt:mb.nullable(),updatedAt:mb}),Cb=V({runs:B(Sb),nextCursor:R().optional()}),wb=V({id:hb,fingerprint:R().min(1),title:R(),description:R().nullable(),severity:gb,status:_b,path:R().nullable(),line:z().int().nullable(),category:R().nullable(),firstSeenAt:mb,lastSeenAt:mb,updatedAt:mb}),Tb=V({findings:B(wb),total:z().int().nonnegative()}),Eb=V({id:hb,runID:hb.nullable(),operationID:hb.nullable(),kind:R(),verdict:R(),reason:R().nullable(),payload:xb.nullable(),createdAt:mb}),Db=V({finding:wb.extend({cwe:R().nullable(),cve:R().nullable(),cvssScore:z().nullable(),cvssVector:R().nullable(),remediation:R().nullable(),assignee:R().nullable(),resolvedAt:mb.nullable(),evidence:B(Eb)})}),Ob=V({id:hb,runID:hb,tool:R(),runtime:R(),status:R(),outcome:R(),title:R().nullable(),input:xb.nullable(),outputPreview:R().nullable(),error:xb.nullable(),startedAt:mb,completedAt:mb.nullable()}),kb=V({run:Sb,operations:B(Ob.omit({runID:!0})),findings:B(wb)}),Ab=V({id:hb,title:R(),kind:R(),source:R(),status:H([`running`,`failed`,`completed`]),runCount:z().int().nonnegative(),operationCount:z().int().nonnegative(),findingCount:z().int().nonnegative(),startedAt:mb,lastActivityAt:mb}),jb=V({session:Ab,runs:B(Sb),operations:B(Ob),findings:B(wb)}),Mb=V({id:hb,sequence:z().int().positive(),actorID:R().nullable(),action:R().min(1),objectType:R().min(1),objectID:R().min(1),outcome:H([`succeeded`,`denied`,`failed`]),details:xb.nullable(),createdAt:mb}),Nb=V({id:hb,workspaceId:hb,name:R(),slug:R(),archivedAt:mb.nullable(),createdAt:mb,updatedAt:mb}),Pb=V({id:hb,name:R(),role:R(),createdAt:mb,updatedAt:mb}),Fb=V({id:hb,name:R(),status:R(),capabilities:B(R()).default([]),lastSeenAt:mb.nullable()}),Ib=V({sessionId:R().nullable().optional(),runs:Wv(R(),z()),findings:V({total:z().int().nonnegative(),bySeverity:Wv(R(),z()),byStatus:Wv(R(),z())}),recentRuns:B(Sb),recentFindings:B(wb)}),Lb=V({count:z().int().nonnegative(),limit:z().int().positive(),hasMore:Av()});function Rb(e){return V({items:B(e),page:Lb})}V({workspaceId:U,clientId:U,batchId:U,records:B(V({id:U,kind:H([`agent_session`,`evidence`,`finding`,`governance_event`]),localSequence:z().int().positive(),payload:Wv(R(),Pv()),payloadHash:yy,occurredAt:W})).min(1).max(500)}),V({batchId:U,accepted:B(U),rejected:B(V({id:U,code:R(),detail:R()})),centralizedApproval:qv(!1)});var zb=H([`command_execution`,`read_files`,`write_files`,`http_request`,`run_exploit`,`dns_recon`,`state_mutation`,`skill_load`]);V({stageId:R().uuid(),workflowVersionId:R().uuid(),stageKey:R().min(1),requiredCapabilities:B(R().min(1)),allowedToolCategories:B(zb),allowedSkills:B(R().min(1).max(80)).max(64).default([]),retrySafe:Av(),timeoutMs:z().int().positive()});var Bb=V({workerClass:H([`network`,`web-api`,`mobile-lab`,`advanced-analysis`,`passive`]),capabilities:B(R().min(1)),tools:Wv(R(),R()),networkLocation:R().nullable(),devices:B(V({id:R(),platform:H([`android`,`ios`]),version:R()})),limits:V({concurrency:z().int().positive(),memoryMb:z().int().positive(),cpuMillis:z().int().positive(),durationSeconds:z().int().positive()})});V({token:R().min(32),name:R().trim().min(1).max(160),publicKey:R().min(32),capabilities:Bb}),V({expiresAt:W}),V({token:R().min(32),expiresAt:W}),V({worker:V({id:U,organizationId:U,workspaceId:U,name:R(),publicKey:R(),capabilities:Bb,status:H([`enrolling`,`online`,`offline`,`revoked`]),lastHeartbeatAt:W.nullable(),createdAt:W}),accessToken:R().min(32),expiresAt:W}),V({capabilities:Bb.optional(),runningJobIds:B(U)}),V({id:U,runId:U,stageId:U,workerId:U,leaseToken:R().min(32),leaseExpiresAt:W,attempt:z().int().positive(),payload:Wv(R(),Pv())}),V({leaseToken:R().min(32),events:B(V({idempotencyKey:R().min(8),type:R().min(1),occurredAt:W,payload:Wv(R(),Pv())})).min(1).max(500)});var Vb=V({leaseToken:R().min(32)});Vb.extend({extendSeconds:z().int().min(10).max(300).default(60)}),Vb.extend({outcome:H([`succeeded`,`failed`,`cancelled`]),summary:Wv(R(),Pv()).default({}),error:R().max(2e4).optional(),retrySafe:Av().default(!1)});function Hb(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Hb).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Hb(t[e])}`).join(`,`)}}`}function Ub(e){return Iy(typeof e==`string`?e:Hb(e))}function Wb(e){return`kifaru-workflow-${e}`}var G=(e,t,n,r,i={})=>({key:e,name:t,description:i.description??t,risk:n,optional:i.optional??!1,requiredCapabilities:r,skillRefs:i.skillRefs??(r.includes(`reporting`)?[`kifaru-vulnerability-report`]:r.some(e=>[`web-testing`,`authenticated-browser`,`api-client`,`api-security-testing`].includes(e))?[`kifaru-web-app-review`]:r.some(e=>[`mobile-static`,`mobile-device`,`mobile-proxy`].includes(e))?[`kifaru-mobile-app-review`]:[]),retrySafe:i.retrySafe??n!==`R2`,approvalCheckpoint:i.approvalCheckpoint??n!==`R0`,timeoutSeconds:i.timeoutSeconds??3600}),Gb=[{id:`10000000-0000-4000-8000-000000000101`,key:`internal-infrastructure`,name:`Internal Infrastructure Assessment`,description:`Customer-network discovery, configuration review, bounded validation, evidence capture, and reporting.`,requiredCapabilities:[`network-discovery`,`vulnerability-scanner`,`reporting`],stages:[G(`discovery`,`Discovery and inventory`,`R1`,[`network-discovery`]),G(`configuration-review`,`Configuration review`,`R1`,[`configuration-review`]),G(`vulnerability-checks`,`Vulnerability checks`,`R1`,[`vulnerability-scanner`]),G(`bounded-validation`,`Bounded validation`,`R1`,[`safe-validation`]),G(`exploitation`,`Approved exploitation`,`R2`,[`exploit-runner`],{retrySafe:!1,optional:!0}),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`host and service inventory`,`tool output with provenance`,`validation evidence`],completionCriteria:[`authorized targets accounted for`,`all executed checks have outcomes`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000102`,key:`external-infrastructure`,name:`External Infrastructure Assessment`,description:`Internet-facing inventory, DNS, TLS, exposed-service, and known-vulnerability assessment with run comparison.`,requiredCapabilities:[`dns`,`tls`,`network-discovery`,`vulnerability-scanner`,`reporting`],stages:[G(`inventory`,`Domain and IP inventory`,`R1`,[`dns`]),G(`service-discovery`,`Exposed service discovery`,`R1`,[`network-discovery`,`tls`]),G(`vulnerability-checks`,`Known-vulnerability checks`,`R1`,[`vulnerability-scanner`]),G(`comparison`,`Previous-run comparison`,`R0`,[`run-comparison`],{approvalCheckpoint:!1}),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`resolved inventory`,`service fingerprints`,`comparison baseline`],completionCriteria:[`all in-scope assets classified`,`material changes recorded`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000103`,key:`web-application`,name:`Web Application Assessment`,description:`Authenticated surface discovery, client analysis, focused testing, evidence gating, and reporting.`,requiredCapabilities:[`web-testing`,`reporting`],stages:[G(`surface-discovery`,`Surface discovery`,`R1`,[`web-testing`]),G(`authenticated-flows`,`Authenticated flow capture`,`R1`,[`authenticated-browser`],{optional:!0}),G(`client-analysis`,`Client-side analysis`,`R0`,[`source-analysis`],{approvalCheckpoint:!1}),G(`focused-testing`,`Focused vulnerability testing`,`R1`,[`web-testing`]),G(`destructive-payloads`,`Approved destructive payloads`,`R2`,[`exploit-runner`],{retrySafe:!1,optional:!0}),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`request and response provenance`,`reproduction evidence`,`negative controls`],completionCriteria:[`authenticated roles exercised`,`findings pass evidence gate`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000104`,key:`api-security`,name:`API Security Assessment`,description:`Schema import, authorization mapping, object-access and state-machine testing, and differential probes.`,requiredCapabilities:[`api-client`,`api-security-testing`,`reporting`],stages:[G(`schema-import`,`API schema and request import`,`R0`,[`openapi`],{approvalCheckpoint:!1}),G(`auth-mapping`,`Authentication and authorization mapping`,`R1`,[`api-client`]),G(`object-access`,`Object access tests`,`R1`,[`api-security-testing`]),G(`state-machine`,`State-machine checks`,`R1`,[`api-security-testing`]),G(`differential-probes`,`Differential probes`,`R1`,[`api-security-testing`]),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`imported request source`,`identity and object matrix`,`differential responses`],completionCriteria:[`declared operations accounted for`,`authorization hypotheses resolved`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000105`,key:`mobile-application`,name:`Android and iOS Assessment`,description:`Static artifact analysis with optional dynamic mobile-lab execution on registered devices.`,requiredCapabilities:[`mobile-static`,`reporting`],stages:[G(`static-analysis`,`Static artifact analysis`,`R0`,[`mobile-static`],{approvalCheckpoint:!1}),G(`dynamic-analysis`,`Dynamic device analysis`,`R1`,[`mobile-device`,`mobile-proxy`],{optional:!0}),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`artifact checksum`,`static analyzer output`,`device provenance for dynamic results`],completionCriteria:[`selected static or dynamic coverage is explicit`,`report artifact produced`],inputSchema:{coverage:{enum:[`static-only`,`full-dynamic`]}}},{id:`10000000-0000-4000-8000-000000000106`,key:`red-team-campaign`,name:`Red Team Campaign`,description:`Rules-of-engagement validation, reconnaissance, hypothesis execution, verification, and reporting.`,requiredCapabilities:[`red-team`,`reporting`],stages:[G(`roe-validation`,`Rules-of-engagement validation`,`R0`,[`authorization-review`],{approvalCheckpoint:!1}),G(`reconnaissance`,`Reconnaissance`,`R1`,[`network-discovery`]),G(`hypothesis-planning`,`Hypothesis planning`,`R0`,[`red-team`],{approvalCheckpoint:!1}),G(`execution`,`Approved campaign execution`,`R2`,[`red-team`],{retrySafe:!1}),G(`verification`,`Outcome verification`,`R1`,[`safe-validation`]),G(`reporting`,`Campaign reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`rules-of-engagement snapshot`,`action provenance`,`verification evidence`],completionCriteria:[`no persistence beyond authorization`,`all actions reconciled`,`report artifact produced`]},{id:`10000000-0000-4000-8000-000000000107`,key:`purple-team-validation`,name:`Purple Team Validation`,description:`Vendor-neutral ATT&CK-aligned detection validation using signed, uploaded, or manually confirmed evidence.`,requiredCapabilities:[`detection-emulation`,`evidence-ingest`,`reporting`],stages:[G(`expectations`,`Detection expectation mapping`,`R0`,[`attack-mapping`],{approvalCheckpoint:!1}),G(`emulation`,`Controlled detection emulation`,`R1`,[`detection-emulation`]),G(`evidence-ingest`,`SIEM and EDR evidence ingest`,`R0`,[`evidence-ingest`],{approvalCheckpoint:!1}),G(`outcomes`,`Detection outcome classification`,`R0`,[`attack-mapping`],{approvalCheckpoint:!1}),G(`reporting`,`Validation reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`ATT&CK technique identifier`,`detection expectation`,`signed or attributable result`],completionCriteria:[`every expectation has a four-state outcome`,`all outcomes link evidence`]},{id:`10000000-0000-4000-8000-000000000108`,key:`nist-csf-2`,name:`NIST CSF 2.0 Assessment`,description:`Versioned CSF evidence requests, observations, gaps, applicability decisions, and maturity notes.`,requiredCapabilities:[`compliance-nist`,`evidence-ingest`,`reporting`],stages:[G(`scope`,`Framework scope and applicability`,`R0`,[`compliance-nist`],{approvalCheckpoint:!1}),G(`evidence`,`Evidence collection`,`R0`,[`evidence-ingest`],{approvalCheckpoint:!1}),G(`assessment`,`Requirement assessment`,`R0`,[`compliance-nist`],{approvalCheckpoint:!1}),G(`reporting`,`Assessment reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`pinned framework requirement`,`applicability decision`,`evidence or explicit gap`],completionCriteria:[`all applicable requirements assessed`,`output states assessment not certification`]},{id:`10000000-0000-4000-8000-000000000109`,key:`cis-controls-8-1`,name:`CIS Controls v8.1 Assessment`,description:`Implementation-group-aware evidence and test results mapped to versioned CIS safeguards.`,requiredCapabilities:[`compliance-cis`,`evidence-ingest`,`reporting`],stages:[G(`implementation-group`,`Implementation group selection`,`R0`,[`compliance-cis`],{approvalCheckpoint:!1}),G(`evidence`,`Safeguard evidence collection`,`R0`,[`evidence-ingest`],{approvalCheckpoint:!1}),G(`assessment`,`Safeguard assessment`,`R0`,[`compliance-cis`],{approvalCheckpoint:!1}),G(`reporting`,`Assessment reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`pinned safeguard`,`implementation group`,`evidence or explicit gap`],completionCriteria:[`all selected safeguards assessed`,`output states assessment not certification`]},{id:`10000000-0000-4000-8000-00000000010a`,key:`advanced-security-testing`,name:`Advanced Security Testing`,description:`Curated source, binary, firmware, protocol, smart-contract, and bounded custom testing.`,requiredCapabilities:[`advanced-analysis`,`reporting`],stages:[G(`analysis`,`Selected advanced analysis`,`R0`,[`advanced-analysis`],{approvalCheckpoint:!1}),G(`bounded-fuzzing`,`Bounded protocol fuzzing`,`R2`,[`protocol-fuzzing`],{retrySafe:!1,optional:!0}),G(`validation`,`Result validation`,`R1`,[`safe-validation`]),G(`reporting`,`Evidence-backed reporting`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`selected subtype`,`toolchain versions`,`reproducible evidence`],completionCriteria:[`unsupported stages blocked before launch`,`report artifact produced`],inputSchema:{subtype:{enum:[`source-review`,`binary-firmware`,`protocol-fuzzing`,`smart-contract`,`custom`]}}},{id:`10000000-0000-4000-8000-00000000010b`,key:`remediation-validation`,name:`Remediation Validation`,description:`Finding-led validation that reuses original scope, evidence contracts, and safe reproduction steps.`,requiredCapabilities:[`safe-validation`,`reporting`],stages:[G(`baseline`,`Original evidence baseline`,`R0`,[`evidence-ingest`],{approvalCheckpoint:!1}),G(`reproduction`,`Safe reproduction`,`R1`,[`safe-validation`]),G(`comparison`,`Before and after comparison`,`R0`,[`run-comparison`],{approvalCheckpoint:!1}),G(`finding-transition`,`Verified finding transition`,`R0`,[`finding-write`],{approvalCheckpoint:!1})],evidenceRequirements:[`original finding`,`before evidence`,`after evidence`],completionCriteria:[`only conclusive success marks verified`,`failed or inconclusive validation leaves finding open`],inputSchema:{findingIds:{type:`array`,minItems:1}}},{id:`10000000-0000-4000-8000-00000000010c`,key:`network-security-audit`,name:`Network Security Audit`,description:`Composite assessment that selects applicable child workflows and consolidates coverage and evidence.`,requiredCapabilities:[`workflow-orchestration`,`reporting`],stages:[G(`selection`,`Child workflow selection`,`R0`,[`workflow-orchestration`],{approvalCheckpoint:!1}),G(`combined-readiness`,`Combined readiness check`,`R0`,[`workflow-orchestration`],{approvalCheckpoint:!1}),G(`child-runs`,`Approved child runs`,`R1`,[`workflow-orchestration`]),G(`consolidation`,`Coverage and finding consolidation`,`R0`,[`reporting`],{approvalCheckpoint:!1})],evidenceRequirements:[`child workflow versions`,`combined readiness decision`,`child run provenance`],completionCriteria:[`all selected children terminal`,`consolidated coverage identifies blocked work`],inputSchema:{childWorkflowKeys:{type:`array`,minItems:1}}}],Kb=`2026-09-06T00:00:00.000Z`;Gb.map(e=>{let t=Wb(e.key),n=e.stages.map(e=>({...e,timeoutSeconds:e.timeoutSeconds??3600,skillRefs:e.skillRefs.includes(t)?e.skillRefs:[...e.skillRefs,t]})),r={id:e.id,key:e.key,version:`1.1.0`,name:e.name,description:e.description,inputSchema:e.inputSchema??{},requiredCapabilities:e.requiredCapabilities,requiredIntegrations:e.requiredIntegrations??[],stages:n,evidenceRequirements:e.evidenceRequirements,completionCriteria:e.completionCriteria,publishedAt:Kb,contentHash:Ub({...e,stages:n})};return eb.parse(r)});var qb=V({items:B(eb)}),Jb=V({workflowKey:R(),skillName:R(),markdown:R(),revision:R(),customized:Av()}),Yb=V({runId:R(),workflowKey:R(),target:R(),permissionMode:H([`scoped`,`yolo`]),status:R(),dbPath:R(),reportPath:R()}),Xb=V({runId:R(),workflowKey:R(),target:R(),permissionMode:H([`scoped`,`yolo`]),status:H([`queued`,`running`,`completed`,`partial`,`failed`,`cancelled`]),startedAt:z(),finishedAt:z().nullable(),error:R().nullable(),reportAvailable:Av(),stages:B(V({key:R(),name:R(),status:R(),summary:R()}))}),Zb=V({items:B(Xb)}),Qb=V({items:B(V({runId:R(),workflowKey:R(),target:R(),posture:R(),findings:z(),unverifiedLeads:z().default(0),createdAt:R()}))}),$b=Rb(Pb),ex=Rb(Nb),tx=V({items:B(Yy)}),nx=Rb(Ab),rx=Rb(Mb),ix=Rb(Fb),ax=V({id:R(),label:R(),prefix:R().optional().default(``),tokenPrefix:R().optional(),role:R().optional().default(`admin`),workspaceId:R().optional().default(`default`),createdAt:R(),expiresAt:R().nullable().optional(),lastUsedAt:R().nullable().optional()}),ox=ax.extend({token:R()}),sx=V({items:B(ax)}),cx=V({items:B(V({version:z().int().nonnegative(),posture:R(),target:R(),contentHash:R(),classification:R(),publicationState:H([`draft`,`blocked`,`published`]),gate:V({satisfied:Av(),missing:B(R())}),publishedAt:R().nullable(),createdAt:R()}))}),lx=V({ext:R(),mimeType:R(),url:R().nullable(),rendered:Av()}),ux=V({version:z().int().nonnegative(),contentHash:R(),posture:R(),target:R(),classification:R(),record:Gy,renditions:B(lx)}),dx=V({artifacts:B(V({artifactId:R(),mimeType:R(),size:z(),sha256:R()}))}),fx=V({version:z().int().nonnegative(),contentHash:R(),posture:R()}),px=class extends Error{status;code;constructor(e,t,n){super(n),this.status=e,this.code=t}};function mx(e=fetch){async function t(t,n,r){let i=document.querySelector(`meta[name="csrf-token"]`)?.content||sessionStorage.getItem(`kifaru-csrf`)||document.cookie.split(`;`).map(e=>e.trim()).find(e=>e.startsWith(`kifaru_csrf=`))?.slice(12),a=r?.method?.toUpperCase()??`GET`,o=await e(t,{credentials:`same-origin`,...r,headers:{accept:`application/json`,...a!==`GET`&&a!==`HEAD`&&i?{"x-csrf-token":i}:{},...r?.headers}});if(!o.ok&&o.status===401&&typeof window<`u`&&!window.location.pathname.startsWith(`/login`))throw window.location.href=`/login?redirect=${encodeURIComponent(window.location.pathname+window.location.search)}`,new px(401,`unauthorized`,`Session expired. Redirecting to login.`);let s=await o.json().catch(()=>void 0);if(!o.ok){let e=s;throw new px(o.status,e?.code??`request_failed`,e?.detail??`Request failed.`)}return n.parse(s)}return{workflows:()=>t(`/api/v1/workflows`,qb),workflowSkill:e=>t(`/api/v1/workflows/${encodeURIComponent(e)}/skill`,V({item:Jb})),saveWorkflowSkill:(e,n,r)=>t(`/api/v1/workflows/${encodeURIComponent(e)}/skill`,V({item:Jb}),{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({markdown:n,expectedRevision:r})}),runs:e=>{let n=e&&typeof e==`object`&&(`limit`in e||`sessionId`in e)?e:void 0,r=new URLSearchParams;return r.set(`limit`,String(n?.limit??20)),n?.sessionId&&r.set(`sessionId`,n.sessionId),t(`/api/v1/runs?${r.toString()}`,Cb)},runDetail:e=>t(`/api/v1/runs/${encodeURIComponent(e)}`,kb),workspaces:()=>t(`/api/v1/workspaces`,$b),projects:()=>t(`/api/v1/projects`,ex),assessmentProfiles:()=>t(`/api/v1/assessment-profiles`,tx),authorizeAssessmentProfile:(e,n)=>t(`/api/v1/assessment-profiles/${encodeURIComponent(e)}/authorization-attestations`,cb,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify(n)}),findings:e=>{let n=e&&typeof e==`object`&&(`limit`in e||`sessionId`in e||`runId`in e)?e:void 0,r=new URLSearchParams;return r.set(`limit`,String(n?.limit??50)),n?.sessionId&&r.set(`sessionId`,n.sessionId),n?.runId&&r.set(`runId`,n.runId),t(`/api/v1/findings?${r.toString()}`,Tb)},finding:e=>t(`/api/v1/findings/${encodeURIComponent(e)}`,Db),updateFindingStatus:(e,n,r)=>t(`/api/v1/findings/${encodeURIComponent(e)}/status`,Db,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({status:n,...r?{note:r}:{}})}),agentSessions:()=>t(`/api/v1/agent/sessions?limit=50`,nx),agentSession:e=>t(`/api/v1/agent/sessions/${encodeURIComponent(e)}`,jb),governanceEvents:()=>t(`/api/v1/governance/audit-events?limit=50`,rx),workers:()=>t(`/api/v1/workers`,ix),overview:e=>{let n;return typeof e==`string`?n=e:e&&typeof e==`object`&&`sessionId`in e&&typeof e.sessionId==`string`&&(n=e.sessionId),t(n?`/api/v1/overview?sessionId=${encodeURIComponent(n)}`:`/api/v1/overview`,Ib)},tokens:()=>t(`/api/v1/tokens`,sx),mintToken:e=>t(`/api/v1/tokens`,ox,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),revokeToken:e=>t(`/api/v1/tokens/${encodeURIComponent(e)}`,V({ok:Av()}),{method:`DELETE`}),targetAssessmentReadiness:e=>t(`/api/v1/assessments/readiness`,ub,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify(e)}),startTargetAssessment:e=>t(`/api/v1/assessments`,db,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify(e)}),startLocalRun:e=>t(`/api/v1/local-runs`,Yb,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),localRuns:()=>t(`/api/v1/local-runs`,Zb),localRun:e=>t(`/api/v1/local-runs/${encodeURIComponent(e)}`,V({item:Xb})),localReports:()=>t(`/api/v1/local-reports`,Qb),reportVersions:e=>t(`/api/v1/runs/${encodeURIComponent(e)}/reports`,cx),reportVersion:(e,n)=>t(`/api/v1/runs/${encodeURIComponent(e)}/reports/${n}`,ux),renderReportRenditions:(e,n)=>t(`/api/v1/runs/${encodeURIComponent(e)}/reports/${n}/renditions`,dx,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify({})}),publishEditedMarkdown:(e,n,r)=>t(`/api/v1/runs/${encodeURIComponent(e)}/reports/${n}/editor`,fx,{method:`POST`,headers:{"content-type":`application/json`,"idempotency-key":crypto.randomUUID()},body:JSON.stringify({markdown:r})})}}var hx=mx(),gx=new Rd({defaultOptions:{queries:{staleTime:1e4,retry:2,refetchOnWindowFocus:!0}}}),_x=[{n:1,name:`Collection & Onboarding`,v:`--s1`},{n:2,name:`Storage & Security`,v:`--s2`},{n:3,name:`Use & Processing`,v:`--s3`},{n:4,name:`Sharing & Disclosure`,v:`--s4`},{n:5,name:`Retention`,v:`--s5`},{n:6,name:`Disposal & Erasure`,v:`--s6`}];function vx(e){return _x[Math.min(Math.max(e,1),_x.length)-1]}function yx(e){return e.name.split(` `)[0]}var bx=[`Governance`,`Technical`,`People & 3rd-party`,`Assurance`],xx=[`critical`,`high`,`medium`,`low`,`info`],Sx={critical:0,high:1,medium:2,low:3,info:4},Cx={critical:`--crit`,high:`--high`,medium:`--med`,low:`--low`,info:`--info`},wx={critical:`Critical`,high:`High`,medium:`Medium`,low:`Low`,info:`Info`};function Tx(e){return e===`informational`?`info`:xx.includes(e)?e:`info`}function Ex(e){return e.length?[...e].sort((e,t)=>Sx[e.severity]-Sx[t.severity])[0].severity:null}function Dx(e){return[...e].sort((e,t)=>Sx[e.severity]-Sx[t.severity])}function Ox(e){return e.status!==`remediated`&&e.status!==`verified`}var kx=/^(?:L|stage )([1-6])\s*·\s*P([0-3])\s*·\s*(.+)$/i;function Ax(e,t){let n=(e??``).trim(),r=kx.exec(n);if(r)return{stage:Number(r[1]),pillar:Number(r[2]),category:r[3],inferred:!1};let i=`${n} ${t??``}`.toLowerCase();return{stage:/sharing|disclos|transfer|cross-border|offshore|sftp|export|feed|webhook|api partner|integration/.test(i)?4:/retention|purge|backup|archive|dr site|snapshot|data lake/.test(i)?5:/eras|disposal|destroy|delete|decommission|shred/.test(i)?6:/consent|intake|onboarding|collection|telematics|form capture|survey/.test(i)?1:/encrypt|at rest|bucket|object store|database exposure|unencrypted|storage|nas|s3/.test(i)?2:3,pillar:/governance|dpia|retention schedule|policy|register|oversight|audit/.test(i)?0:/shared credential|third-party|tpa|vendor|partner|outsourc|staff|insider/.test(i)?2:1,category:n||`Agent finding`,inferred:!0}}function jx(e){return e.map(e=>{let t=Ax(e.category,e.title);return{...e,severity:Tx(e.severity),stage:t.stage,pillar:t.pillar,displayCategory:t.inferred?`${t.category} (stage inferred)`:t.category,inferred:t.inferred}})}function Mx(e){return Ex(e.filter(e=>e.status===`confirmed`||e.status===`verified`))}function Nx({title:e,sub:t,surface:n=!0,children:r}){return(0,b.jsxs)(`section`,{className:n?`bg-card rounded-xl border p-5`:void 0,children:[(0,b.jsxs)(`div`,{className:`mb-4 flex items-baseline justify-between gap-3`,children:[(0,b.jsx)(`h2`,{children:e}),t?(0,b.jsx)(`span`,{className:`text-muted-foreground shrink-0 text-xs`,children:t}):null]}),r]})}function Px({children:e}){return(0,b.jsx)(`div`,{className:`kpis`,children:e})}function Fx({label:e,value:t,meta:n,hero:r,tone:i}){return(0,b.jsxs)(`div`,{className:r?`kpi hero`:`kpi`,children:[(0,b.jsx)(`div`,{className:`lab`,children:e}),r?(0,b.jsxs)(`div`,{className:`posture-pill val`,style:i?{color:`var(${Cx[i]})`}:void 0,children:[(0,b.jsx)(`span`,{className:`sq`}),t]}):(0,b.jsx)(`div`,{className:`val`,children:t}),n?(0,b.jsx)(`div`,{className:`meta`,children:n}):null]})}function Ix({counts:e}){let t=Math.max(...xx.map(t=>e[t]),1);return(0,b.jsx)(`div`,{children:xx.map(n=>(0,b.jsxs)(`div`,{className:`sevrow`,children:[(0,b.jsxs)(`span`,{className:`name`,children:[(0,b.jsx)(`span`,{className:`chip`,style:{background:`var(${Cx[n]})`}}),wx[n]]}),(0,b.jsx)(`div`,{className:`track`,children:(0,b.jsx)(`div`,{className:`fill`,"data-empty":e[n]===0,style:{width:`${e[n]/t*100}%`,background:`var(${Cx[n]})`}})}),(0,b.jsx)(`span`,{className:`n`,children:e[n]})]},n))})}function Lx({findings:e}){let t=_x.map(t=>e.filter(e=>e.stage===t.n).length),n=Math.max(...t,1);return(0,b.jsx)(`div`,{className:`stagebars`,children:_x.map((e,r)=>{let i=t[r];return(0,b.jsxs)(`div`,{className:`sbar`,children:[(0,b.jsx)(`span`,{className:`cnt`,children:i}),(0,b.jsx)(`div`,{className:`col`,style:{height:`${Math.max(i/n*112,i?10:2)}px`,background:`var(${e.v})`}}),(0,b.jsx)(`span`,{className:`idx`,children:e.n}),(0,b.jsx)(`span`,{className:`lb`,children:yx(e)})]},e.n)})})}function Rx({findings:e,onSelect:t,emptyLabel:n=`No findings.`}){return e.length?(0,b.jsx)(`div`,{className:`flist`,children:e.map(e=>{let n=vx(e.stage);return(0,b.jsxs)(`button`,{className:`frow`,type:`button`,onClick:t?()=>t(e):void 0,children:[(0,b.jsx)(`span`,{className:`sevtag sev-${e.severity}`,children:wx[e.severity]}),(0,b.jsxs)(`span`,{children:[(0,b.jsx)(`span`,{className:`ftitle`,children:e.title}),(0,b.jsxs)(`span`,{className:`fmeta`,children:[(0,b.jsxs)(`span`,{className:`stagetag`,children:[(0,b.jsx)(`span`,{className:`d`,style:{background:`var(${n.v})`}}),`Stage `,n.n,` · `,yx(n)]}),(0,b.jsx)(`span`,{children:e.displayCategory}),e.path?(0,b.jsx)(`span`,{className:`font-mono`,children:e.path}):null]})]}),(0,b.jsx)(`span`,{className:`fright`,children:(0,b.jsx)(`span`,{className:`inline-flex shrink-0 self-start rounded-full border px-2.5 py-[3px] text-2xs font-semibold tracking-wide uppercase whitespace-nowrap text-muted-foreground`,children:e.status.replaceAll(`_`,` `)})})]},e.id)})}):(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs`,children:n})}function zx({findings:e,selected:t,onSelect:n}){return(0,b.jsx)(`div`,{className:`chain`,children:_x.map(r=>{let i=e.filter(e=>e.stage===r.n),a=Ex(i);return(0,b.jsxs)(`button`,{className:`stagenode`,type:`button`,"aria-pressed":r.n===t,onClick:()=>n(r.n),children:[(0,b.jsx)(`div`,{className:`top`,style:{background:`var(${r.v})`}}),a?(0,b.jsx)(`span`,{className:`worst`,style:{background:`var(${Cx[a]})`}}):null,(0,b.jsxs)(`div`,{className:`sn`,children:[`STAGE `,r.n]}),(0,b.jsx)(`div`,{className:`st`,children:r.name}),(0,b.jsxs)(`div`,{className:`sc`,style:{color:`var(${r.v})`},children:[i.length,(0,b.jsxs)(`small`,{children:[`finding`,i.length===1?``:`s`]})]})]},r.n)})})}function Bx({findings:e,onSelectStage:t}){return(0,b.jsx)(`div`,{style:{overflowX:`auto`},children:(0,b.jsxs)(`table`,{className:`matrix`,children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{className:`rh`}),_x.map(e=>(0,b.jsxs)(`th`,{children:[(0,b.jsx)(`span`,{className:`flex flex-wrap gap-4 text-xs font-medium`,children:(0,b.jsx)(`i`,{className:`mcap`,style:{background:`var(${e.v})`}})}),(0,b.jsx)(`br`,{}),e.n]},e.n))]})}),(0,b.jsx)(`tbody`,{children:bx.map((n,r)=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{className:`rh`,children:n}),_x.map(i=>{let a=e.filter(e=>e.pillar===r&&e.stage===i.n),o=Ex(a);return o?(0,b.jsx)(`td`,{className:`has`,style:{background:`var(${Cx[o]})`,cursor:`pointer`},title:`${a.length} open at ${n} · stage ${i.n}`,onClick:()=>t(i.n),children:a.length},i.n):(0,b.jsx)(`td`,{children:`·`},i.n)})]},n))})]})})}function Vx({items:e}){return(0,b.jsx)(`div`,{className:`my-3.5 grid grid-cols-2 gap-3 sm:grid-cols-4`,children:e.map(e=>(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`div`,{className:`k`,children:e.k}),(0,b.jsx)(`div`,{className:e.mono?`v mono`:`v`,children:e.v})]},e.k))})}function Hx({title:e,children:t}){return(0,b.jsxs)(`div`,{className:`border-[var(--hair)] mt-4 border-t pt-3.5 [&>h3]:text-muted-foreground [&>h3]:mb-2 [&>h3]:text-[11px] [&>h3]:font-semibold [&>h3]:tracking-[0.1em] [&>h3]:uppercase`,children:[(0,b.jsx)(`h3`,{children:e}),t]})}function Ux({title:e,detail:t,verdict:n}){return(0,b.jsxs)(`div`,{className:`evi`,children:[(0,b.jsxs)(`svg`,{className:`ei`,width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:[(0,b.jsx)(`path`,{d:`M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z`}),(0,b.jsx)(`path`,{d:`M14 2v6h6`})]}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`div`,{className:`et`,children:e}),(0,b.jsx)(`div`,{className:`ed`,children:t})]}),(0,b.jsx)(`span`,{className:`verdict`,children:n})]})}var Wx=v(`inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3`,{variants:{variant:{default:`bg-primary text-primary-foreground [a&]:hover:bg-primary/90`,secondary:`bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90`,destructive:`bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90`,outline:`border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,ghost:`[a&]:hover:bg-accent [a&]:hover:text-accent-foreground`,link:`text-primary underline-offset-4 [a&]:hover:underline`,critical:`border-[color-mix(in_srgb,var(--crit)_35%,transparent)] bg-[var(--crit-bg)] text-[var(--crit)]`,high:`border-[color-mix(in_srgb,var(--high)_35%,transparent)] bg-[var(--high-bg)] text-[var(--high)]`,medium:`border-[color-mix(in_srgb,var(--med)_35%,transparent)] bg-[var(--med-bg)] text-[var(--med)]`,low:`border-[color-mix(in_srgb,var(--low)_35%,transparent)] bg-[var(--low-bg)] text-[var(--low)]`,success:`border-[color-mix(in_srgb,var(--good)_35%,transparent)] bg-[var(--good-bg)] text-[var(--good)]`,info:`bg-[var(--info-bg)] text-[var(--info)]`}},defaultVariants:{variant:`default`}}),Gx={critical:`critical`,failed:`critical`,blocked:`critical`,R2:`critical`,high:`high`,awaiting_approval:`high`,cancel_requested:`high`,R1:`high`,medium:`medium`,queued:`medium`,low:`low`,running:`low`,R0:`low`,succeeded:`success`,completed:`success`,confirmed:`success`,ok:`success`,verified:`success`,remediated:`success`,info:`info`,informational:`info`};function Kx(e){return e?Gx[e]??`secondary`:`secondary`}function qx({className:e,variant:t=`default`,asChild:n=!1,...r}){let i=n?s:`span`;return(0,b.jsx)(i,{"data-slot":`badge`,"data-variant":t,className:a(Wx({variant:t}),e),...r})}function Jx(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var Yx=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Xx=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Zx={};function Qx(e,t){return((t||Zx).jsx?Xx:Yx).test(e)}var $x=/[ \t\n\f\r]/g;function eS(e){return typeof e==`object`?e.type===`text`&&tS(e.value):tS(e)}function tS(e){return e.replace($x,``)===``}var nS=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};nS.prototype.normal={},nS.prototype.property={},nS.prototype.space=void 0;function rS(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new nS(n,r,t)}function iS(e){return e.toLowerCase()}var aS=class{constructor(e,t){this.attribute=t,this.property=e}};aS.prototype.attribute=``,aS.prototype.booleanish=!1,aS.prototype.boolean=!1,aS.prototype.commaOrSpaceSeparated=!1,aS.prototype.commaSeparated=!1,aS.prototype.defined=!1,aS.prototype.mustUseProperty=!1,aS.prototype.number=!1,aS.prototype.overloadedBoolean=!1,aS.prototype.property=``,aS.prototype.spaceSeparated=!1,aS.prototype.space=void 0;var oS=e({boolean:()=>cS,booleanish:()=>lS,commaOrSpaceSeparated:()=>pS,commaSeparated:()=>fS,number:()=>K,overloadedBoolean:()=>uS,spaceSeparated:()=>dS}),sS=0,cS=mS(),lS=mS(),uS=mS(),K=mS(),dS=mS(),fS=mS(),pS=mS();function mS(){return 2**++sS}var hS=Object.keys(oS),gS=class extends aS{constructor(e,t,n,r){let i=-1;if(super(e,t),_S(this,`space`,r),typeof n==`number`)for(;++i<hS.length;){let e=hS[i];_S(this,hS[i],(n&oS[e])===oS[e])}}};gS.prototype.defined=!0;function _S(e,t,n){n&&(e[t]=n)}function vS(e){let t={},n={};for(let[r,i]of Object.entries(e.properties)){let a=new gS(r,e.transform(e.attributes||{},r),i,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(a.mustUseProperty=!0),t[r]=a,n[iS(r)]=r,n[iS(a.attribute)]=r}return new nS(t,n,e.space)}var yS=vS({properties:{ariaActiveDescendant:null,ariaAtomic:lS,ariaAutoComplete:null,ariaBusy:lS,ariaChecked:lS,ariaColCount:K,ariaColIndex:K,ariaColSpan:K,ariaControls:dS,ariaCurrent:null,ariaDescribedBy:dS,ariaDetails:null,ariaDisabled:lS,ariaDropEffect:dS,ariaErrorMessage:null,ariaExpanded:lS,ariaFlowTo:dS,ariaGrabbed:lS,ariaHasPopup:null,ariaHidden:lS,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:dS,ariaLevel:K,ariaLive:null,ariaModal:lS,ariaMultiLine:lS,ariaMultiSelectable:lS,ariaOrientation:null,ariaOwns:dS,ariaPlaceholder:null,ariaPosInSet:K,ariaPressed:lS,ariaReadOnly:lS,ariaRelevant:null,ariaRequired:lS,ariaRoleDescription:dS,ariaRowCount:K,ariaRowIndex:K,ariaRowSpan:K,ariaSelected:lS,ariaSetSize:K,ariaSort:null,ariaValueMax:K,ariaValueMin:K,ariaValueNow:K,ariaValueText:null,role:null},transform(e,t){return t===`role`?t:`aria-`+t.slice(4).toLowerCase()}});function bS(e,t){return t in e?e[t]:t}function xS(e,t){return bS(e,t.toLowerCase())}var SS=vS({attributes:{acceptcharset:`accept-charset`,classname:`class`,htmlfor:`for`,httpequiv:`http-equiv`},mustUseProperty:[`checked`,`multiple`,`muted`,`selected`],properties:{abbr:null,accept:fS,acceptCharset:dS,accessKey:dS,action:null,allow:null,allowFullScreen:cS,allowPaymentRequest:cS,allowUserMedia:cS,alpha:cS,alt:null,as:null,async:cS,autoCapitalize:null,autoComplete:dS,autoFocus:cS,autoPlay:cS,blocking:dS,capture:null,charSet:null,checked:cS,cite:null,className:dS,closedBy:null,colorSpace:null,cols:K,colSpan:K,command:null,commandFor:null,content:null,contentEditable:lS,controls:cS,controlsList:dS,coords:K|fS,crossOrigin:null,data:null,dateTime:null,decoding:null,default:cS,defer:cS,dir:null,dirName:null,disabled:cS,download:uS,draggable:lS,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:cS,formTarget:null,headers:dS,height:K,hidden:uS,high:K,href:null,hrefLang:null,htmlFor:dS,httpEquiv:dS,id:null,imageSizes:null,imageSrcSet:null,inert:cS,inputMode:null,integrity:null,is:null,isMap:cS,itemId:null,itemProp:dS,itemRef:dS,itemScope:cS,itemType:dS,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:cS,low:K,manifest:null,max:null,maxLength:K,media:null,method:null,min:null,minLength:K,multiple:cS,muted:cS,name:null,nonce:null,noModule:cS,noValidate:cS,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:cS,optimum:K,pattern:null,ping:dS,placeholder:null,playsInline:cS,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:cS,referrerPolicy:null,rel:dS,required:cS,reversed:cS,rows:K,rowSpan:K,sandbox:dS,scope:null,scoped:cS,seamless:cS,selected:cS,shadowRootClonable:cS,shadowRootCustomElementRegistry:cS,shadowRootDelegatesFocus:cS,shadowRootMode:null,shadowRootSerializable:cS,shape:null,size:K,sizes:null,slot:null,span:K,spellCheck:lS,src:null,srcDoc:null,srcLang:null,srcSet:null,start:K,step:null,style:null,tabIndex:K,target:null,title:null,translate:null,type:null,typeMustMatch:cS,useMap:null,value:lS,width:K,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:dS,axis:null,background:null,bgColor:null,border:K,borderColor:null,bottomMargin:K,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:cS,declare:cS,event:null,face:null,frame:null,frameBorder:null,hSpace:K,leftMargin:K,link:null,longDesc:null,lowSrc:null,marginHeight:K,marginWidth:K,noResize:cS,noHref:cS,noShade:cS,noWrap:cS,object:null,profile:null,prompt:null,rev:null,rightMargin:K,rules:null,scheme:null,scrolling:lS,standby:null,summary:null,text:null,topMargin:K,valueType:null,version:null,vAlign:null,vLink:null,vSpace:K,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:cS,disablePictureInPicture:cS,disableRemotePlayback:cS,exportParts:fS,part:dS,prefix:null,property:null,results:K,security:null,unselectable:null},space:`html`,transform:xS}),CS=vS({attributes:{accentHeight:`accent-height`,alignmentBaseline:`alignment-baseline`,arabicForm:`arabic-form`,baselineShift:`baseline-shift`,capHeight:`cap-height`,className:`class`,clipPath:`clip-path`,clipRule:`clip-rule`,colorInterpolation:`color-interpolation`,colorInterpolationFilters:`color-interpolation-filters`,colorProfile:`color-profile`,colorRendering:`color-rendering`,crossOrigin:`crossorigin`,dataType:`datatype`,dominantBaseline:`dominant-baseline`,enableBackground:`enable-background`,fillOpacity:`fill-opacity`,fillRule:`fill-rule`,floodColor:`flood-color`,floodOpacity:`flood-opacity`,fontFamily:`font-family`,fontSize:`font-size`,fontSizeAdjust:`font-size-adjust`,fontStretch:`font-stretch`,fontStyle:`font-style`,fontVariant:`font-variant`,fontWeight:`font-weight`,glyphName:`glyph-name`,glyphOrientationHorizontal:`glyph-orientation-horizontal`,glyphOrientationVertical:`glyph-orientation-vertical`,hrefLang:`hreflang`,horizAdvX:`horiz-adv-x`,horizOriginX:`horiz-origin-x`,horizOriginY:`horiz-origin-y`,imageRendering:`image-rendering`,letterSpacing:`letter-spacing`,lightingColor:`lighting-color`,markerEnd:`marker-end`,markerMid:`marker-mid`,markerStart:`marker-start`,maskType:`mask-type`,navDown:`nav-down`,navDownLeft:`nav-down-left`,navDownRight:`nav-down-right`,navLeft:`nav-left`,navNext:`nav-next`,navPrev:`nav-prev`,navRight:`nav-right`,navUp:`nav-up`,navUpLeft:`nav-up-left`,navUpRight:`nav-up-right`,onAbort:`onabort`,onActivate:`onactivate`,onAfterPrint:`onafterprint`,onBeforePrint:`onbeforeprint`,onBegin:`onbegin`,onCancel:`oncancel`,onCanPlay:`oncanplay`,onCanPlayThrough:`oncanplaythrough`,onChange:`onchange`,onClick:`onclick`,onClose:`onclose`,onCopy:`oncopy`,onCueChange:`oncuechange`,onCut:`oncut`,onDblClick:`ondblclick`,onDrag:`ondrag`,onDragEnd:`ondragend`,onDragEnter:`ondragenter`,onDragExit:`ondragexit`,onDragLeave:`ondragleave`,onDragOver:`ondragover`,onDragStart:`ondragstart`,onDrop:`ondrop`,onDurationChange:`ondurationchange`,onEmptied:`onemptied`,onEnd:`onend`,onEnded:`onended`,onError:`onerror`,onFocus:`onfocus`,onFocusIn:`onfocusin`,onFocusOut:`onfocusout`,onHashChange:`onhashchange`,onInput:`oninput`,onInvalid:`oninvalid`,onKeyDown:`onkeydown`,onKeyPress:`onkeypress`,onKeyUp:`onkeyup`,onLoad:`onload`,onLoadedData:`onloadeddata`,onLoadedMetadata:`onloadedmetadata`,onLoadStart:`onloadstart`,onMessage:`onmessage`,onMouseDown:`onmousedown`,onMouseEnter:`onmouseenter`,onMouseLeave:`onmouseleave`,onMouseMove:`onmousemove`,onMouseOut:`onmouseout`,onMouseOver:`onmouseover`,onMouseUp:`onmouseup`,onMouseWheel:`onmousewheel`,onOffline:`onoffline`,onOnline:`ononline`,onPageHide:`onpagehide`,onPageShow:`onpageshow`,onPaste:`onpaste`,onPause:`onpause`,onPlay:`onplay`,onPlaying:`onplaying`,onPopState:`onpopstate`,onProgress:`onprogress`,onRateChange:`onratechange`,onRepeat:`onrepeat`,onReset:`onreset`,onResize:`onresize`,onScroll:`onscroll`,onSeeked:`onseeked`,onSeeking:`onseeking`,onSelect:`onselect`,onShow:`onshow`,onStalled:`onstalled`,onStorage:`onstorage`,onSubmit:`onsubmit`,onSuspend:`onsuspend`,onTimeUpdate:`ontimeupdate`,onToggle:`ontoggle`,onUnload:`onunload`,onVolumeChange:`onvolumechange`,onWaiting:`onwaiting`,onZoom:`onzoom`,overlinePosition:`overline-position`,overlineThickness:`overline-thickness`,paintOrder:`paint-order`,panose1:`panose-1`,pointerEvents:`pointer-events`,referrerPolicy:`referrerpolicy`,renderingIntent:`rendering-intent`,shapeRendering:`shape-rendering`,stopColor:`stop-color`,stopOpacity:`stop-opacity`,strikethroughPosition:`strikethrough-position`,strikethroughThickness:`strikethrough-thickness`,strokeDashArray:`stroke-dasharray`,strokeDashOffset:`stroke-dashoffset`,strokeLineCap:`stroke-linecap`,strokeLineJoin:`stroke-linejoin`,strokeMiterLimit:`stroke-miterlimit`,strokeOpacity:`stroke-opacity`,strokeWidth:`stroke-width`,tabIndex:`tabindex`,textAnchor:`text-anchor`,textDecoration:`text-decoration`,textRendering:`text-rendering`,transformOrigin:`transform-origin`,typeOf:`typeof`,underlinePosition:`underline-position`,underlineThickness:`underline-thickness`,unicodeBidi:`unicode-bidi`,unicodeRange:`unicode-range`,unitsPerEm:`units-per-em`,vAlphabetic:`v-alphabetic`,vHanging:`v-hanging`,vIdeographic:`v-ideographic`,vMathematical:`v-mathematical`,vectorEffect:`vector-effect`,vertAdvY:`vert-adv-y`,vertOriginX:`vert-origin-x`,vertOriginY:`vert-origin-y`,wordSpacing:`word-spacing`,writingMode:`writing-mode`,xHeight:`x-height`,playbackOrder:`playbackorder`,timelineBegin:`timelinebegin`},properties:{about:pS,accentHeight:K,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:K,amplitude:K,arabicForm:null,ascent:K,attributeName:null,attributeType:null,azimuth:K,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:K,by:null,calcMode:null,capHeight:K,className:dS,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:K,diffuseConstant:K,direction:null,display:null,dur:null,divisor:K,dominantBaseline:null,download:cS,dx:null,dy:null,edgeMode:null,editable:null,elevation:K,enableBackground:null,end:null,event:null,exponent:K,externalResourcesRequired:null,fill:null,fillOpacity:K,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:fS,g2:fS,glyphName:fS,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:K,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:K,horizOriginX:K,horizOriginY:K,id:null,ideographic:K,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:K,k:K,k1:K,k2:K,k3:K,k4:K,kernelMatrix:pS,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:K,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:K,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:K,overlineThickness:K,paintOrder:null,panose1:null,path:null,pathLength:K,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:dS,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:K,pointsAtY:K,pointsAtZ:K,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:pS,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:pS,rev:pS,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:pS,requiredFeatures:pS,requiredFonts:pS,requiredFormats:pS,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:K,specularExponent:K,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:K,strikethroughThickness:K,string:null,stroke:null,strokeDashArray:pS,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:K,strokeOpacity:K,strokeWidth:null,style:null,surfaceScale:K,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:pS,tabIndex:K,tableValues:null,target:null,targetX:K,targetY:K,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:pS,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:K,underlineThickness:K,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:K,values:null,vAlphabetic:K,vMathematical:K,vectorEffect:null,vHanging:K,vIdeographic:K,version:null,vertAdvY:K,vertOriginX:K,vertOriginY:K,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:K,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:`svg`,transform:bS}),wS=vS({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:`xlink`,transform(e,t){return`xlink:`+t.slice(5).toLowerCase()}}),TS=vS({attributes:{xmlnsxlink:`xmlns:xlink`},properties:{xmlnsXLink:null,xmlns:null},space:`xmlns`,transform:xS}),ES=vS({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:`xml`,transform(e,t){return`xml:`+t.slice(3).toLowerCase()}}),DS={classId:`classID`,dataType:`datatype`,itemId:`itemID`,strokeDashArray:`strokeDasharray`,strokeDashOffset:`strokeDashoffset`,strokeLineCap:`strokeLinecap`,strokeLineJoin:`strokeLinejoin`,strokeMiterLimit:`strokeMiterlimit`,typeOf:`typeof`,xLinkActuate:`xlinkActuate`,xLinkArcRole:`xlinkArcrole`,xLinkHref:`xlinkHref`,xLinkRole:`xlinkRole`,xLinkShow:`xlinkShow`,xLinkTitle:`xlinkTitle`,xLinkType:`xlinkType`,xmlnsXLink:`xmlnsXlink`},OS=/[A-Z]/g,kS=/-[a-z]/g,AS=/^data[-\w.:]+$/i;function jS(e,t){let n=iS(t),r=t,i=aS;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)===`data`&&AS.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(kS,NS);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!kS.test(e)){let n=e.replace(OS,MS);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=gS}return new i(r,t)}function MS(e){return`-`+e.toLowerCase()}function NS(e){return e.charAt(1).toUpperCase()}var PS=rS([yS,SS,wS,TS,ES],`html`),FS=rS([yS,CS,wS,TS,ES],`svg`);function IS(e){return e.join(` `).trim()}var LS=r(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g;function u(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,u=1;function f(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(`
61
+ `);u=~n?e.length-n:u+e.length}function p(){var e={line:l,column:u};return function(t){return t.position=new m(e),_(),t}}function m(e){this.start=e,this.end={line:l,column:u},this.source=t.source}m.prototype.content=e;function h(n){var r=Error(t.source+`:`+l+`:`+u+`: `+n);if(r.reason=n,r.filename=t.source,r.line=l,r.column=u,r.source=e,!t.silent)throw r}function g(t){var n=t.exec(e);if(n){var r=n[0];return f(r),e=e.slice(r.length),n}}function _(){g(i)}function v(e){var t;for(e||=[];t=y();)t!==!1&&e.push(t);return e}function y(){var t=p();if(e.charAt(0)==`/`&&e.charAt(1)==`*`){for(var n=2;e.charAt(n)!=``&&(e.charAt(n)!=`*`||e.charAt(n+1)!=`/`);)++n;if(n+=2,e.charAt(n-1)===``)return h(`End of comment missing`);var r=e.slice(2,n-2);return u+=2,f(r),e=e.slice(n),u+=2,t({type:`comment`,comment:r})}}function b(){var e=p(),t=g(a);if(t){if(y(),!g(o))return h(`property missing ':'`);var r=g(s),i=e({type:`declaration`,property:d(t[0].replace(n,``)),value:r?d(r[0].replace(n,``)):``});return g(c),i}}function x(){var e=[];v(e);for(var t;t=b();)t!==!1&&(e.push(t),v(e));return e}return _(),x()}function d(e){return e?e.replace(l,``):``}t.exports=u})),RS=r((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.default=r;var n=t(LS());function r(e,t){let r=null;if(!e||typeof e!=`string`)return r;let i=(0,n.default)(e),a=typeof t==`function`;return i.forEach(e=>{if(e.type!==`declaration`)return;let{property:n,value:i}=e;a?t(n,i,e):i&&(r||={},r[n]=i)}),r}})),zS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(e){return!e||r.test(e)||t.test(e)},s=function(e,t){return t.toUpperCase()},c=function(e,t){return`${t}-`};e.camelCase=function(e,t){return t===void 0&&(t={}),o(e)?e:(e=e.toLowerCase(),e=t.reactCompat?e.replace(a,c):e.replace(i,c),e.replace(n,s))}})),BS=r(((e,t)=>{var n=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(RS()),r=zS();function i(e,t){var i={};return!e||typeof e!=`string`||(0,n.default)(e,function(e,n){e&&n&&(i[(0,r.camelCase)(e,t)]=n)}),i}i.default=i,t.exports=i})),VS=US(`end`),HS=US(`start`);function US(e){return t;function t(t){let n=t&&t.position&&t.position[e]||{};if(typeof n.line==`number`&&n.line>0&&typeof n.column==`number`&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset==`number`&&n.offset>-1?n.offset:void 0}}}function WS(e){let t=HS(e),n=VS(e);if(t&&n)return{start:t,end:n}}function GS(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?qS(e.position):`start`in e||`end`in e?qS(e):`line`in e||`column`in e?KS(e):``}function KS(e){return JS(e&&e.line)+`:`+JS(e&&e.column)}function qS(e){return KS(e&&e.start)+`-`+KS(e&&e.end)}function JS(e){return e&&typeof e==`number`?e:1}var YS=class extends Error{constructor(e,t,n){super(),typeof t==`string`&&(n=t,t=void 0);let r=``,i={},a=!1;if(t&&(i=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?r=e:!i.cause&&e&&(a=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n==`string`){let e=n.indexOf(`:`);e===-1?i.ruleId=n:(i.source=n.slice(0,e),i.ruleId=n.slice(e+1))}if(!i.place&&i.ancestors&&i.ancestors){let e=i.ancestors[i.ancestors.length-1];e&&(i.place=e.position)}let o=i.place&&`start`in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file=``,this.message=r,this.line=o?o.line:void 0,this.name=GS(i.place)||`1:1`,this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack==`string`?i.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};YS.prototype.file=``,YS.prototype.name=``,YS.prototype.reason=``,YS.prototype.message=``,YS.prototype.stack=``,YS.prototype.column=void 0,YS.prototype.line=void 0,YS.prototype.ancestors=void 0,YS.prototype.cause=void 0,YS.prototype.fatal=void 0,YS.prototype.place=void 0,YS.prototype.ruleId=void 0,YS.prototype.source=void 0;var XS=n(BS(),1),ZS={}.hasOwnProperty,QS=new Map,$S=/[A-Z]/g,eC=new Set([`table`,`tbody`,`thead`,`tfoot`,`tr`]),tC=new Set([`td`,`th`]),nC=`https://github.com/syntax-tree/hast-util-to-jsx-runtime`;function rC(e,t){if(!t||t.Fragment===void 0)throw TypeError("Expected `Fragment` in options");let n=t.filePath||void 0,r;if(t.development){if(typeof t.jsxDEV!=`function`)throw TypeError("Expected `jsxDEV` in options when `development: true`");r=mC(n,t.jsxDEV)}else{if(typeof t.jsx!=`function`)throw TypeError("Expected `jsx` in production options");if(typeof t.jsxs!=`function`)throw TypeError("Expected `jsxs` in production options");r=pC(n,t.jsx,t.jsxs)}let i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||`react`,evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space===`svg`?FS:PS,stylePropertyNameCase:t.stylePropertyNameCase||`dom`,tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=iC(i,e,void 0);return a&&typeof a!=`string`?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function iC(e,t,n){if(t.type===`element`)return aC(e,t,n);if(t.type===`mdxFlowExpression`||t.type===`mdxTextExpression`)return oC(e,t);if(t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)return cC(e,t,n);if(t.type===`mdxjsEsm`)return sC(e,t);if(t.type===`root`)return lC(e,t,n);if(t.type===`text`)return uC(e,t)}function aC(e,t,n){let r=e.schema,i=r;t.tagName.toLowerCase()===`svg`&&r.space===`html`&&(i=FS,e.schema=i),e.ancestors.push(t);let a=bC(e,t.tagName,!1),o=hC(e,t),s=_C(e,t);return eC.has(t.tagName)&&(s=s.filter(function(e){return typeof e!=`string`||!eS(e)})),dC(e,o,a,t),fC(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function oC(e,t){if(t.data&&t.data.estree&&e.evaluater){let n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}xC(e,t.position)}function sC(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);xC(e,t.position)}function cC(e,t,n){let r=e.schema,i=r;t.name===`svg`&&r.space===`html`&&(i=FS,e.schema=i),e.ancestors.push(t);let a=t.name===null?e.Fragment:bC(e,t.name,!0),o=gC(e,t),s=_C(e,t);return dC(e,o,a,t),fC(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function lC(e,t,n){let r={};return fC(r,_C(e,t)),e.create(t,e.Fragment,r,n)}function uC(e,t){return t.value}function dC(e,t,n,r){typeof n!=`string`&&n!==e.Fragment&&e.passNode&&(t.node=r)}function fC(e,t){if(t.length>0){let n=t.length>1?t:t[0];n&&(e.children=n)}}function pC(e,t,n){return r;function r(e,r,i,a){let o=Array.isArray(i.children)?n:t;return a?o(r,i,a):o(r,i)}}function mC(e,t){return n;function n(n,r,i,a){let o=Array.isArray(i.children),s=HS(n);return t(r,i,a,o,{columnNumber:s?s.column-1:void 0,fileName:e,lineNumber:s?s.line:void 0},void 0)}}function hC(e,t){let n={},r,i;for(i in t.properties)if(i!==`children`&&ZS.call(t.properties,i)){let a=vC(e,i,t.properties[i]);if(a){let[i,o]=a;e.tableCellAlignToStyle&&i===`align`&&typeof o==`string`&&tC.has(t.tagName)?r=o:n[i]=o}}if(r){let t=n.style||={};t[e.stylePropertyNameCase===`css`?`text-align`:`textAlign`]=r}return n}function gC(e,t){let n={};for(let r of t.attributes)if(r.type===`mdxJsxExpressionAttribute`){if(r.data&&r.data.estree&&e.evaluater){let t=r.data.estree.body[0];t.type;let i=t.expression;i.type;let a=i.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else xC(e,t.position)}else{let i=r.name,a;if(r.value&&typeof r.value==`object`){if(r.value.data&&r.value.data.estree&&e.evaluater){let t=r.value.data.estree.body[0];t.type,a=e.evaluater.evaluateExpression(t.expression)}else xC(e,t.position)}else a=r.value===null||r.value;n[i]=a}return n}function _C(e,t){let n=[],r=-1,i=e.passKeys?new Map:QS;for(;++r<t.children.length;){let a=t.children[r],o;if(e.passKeys){let e=a.type===`element`?a.tagName:a.type===`mdxJsxFlowElement`||a.type===`mdxJsxTextElement`?a.name:void 0;if(e){let t=i.get(e)||0;o=e+`-`+t,i.set(e,t+1)}}let s=iC(e,a,o);s!==void 0&&n.push(s)}return n}function vC(e,t,n){let r=jS(e.schema,t);if(!(n==null||typeof n==`number`&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?Jx(n):IS(n)),r.property===`style`){let t=typeof n==`object`?n:yC(e,String(n));return e.stylePropertyNameCase===`css`&&(t=SC(t)),[`style`,t]}return[e.elementAttributeNameCase===`react`&&r.space?DS[r.property]||r.property:r.attribute,n]}}function yC(e,t){try{return(0,XS.default)(t,{reactCompat:!0})}catch(t){if(e.ignoreInvalidStyle)return{};let n=t,r=new YS("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:`style`,source:`hast-util-to-jsx-runtime`});throw r.file=e.filePath||void 0,r.url=nC+`#cannot-parse-style-attribute`,r}}function bC(e,t,n){let r;if(!n)r={type:`Literal`,value:t};else if(t.includes(`.`)){let e=t.split(`.`),n=-1,i;for(;++n<e.length;){let t=Qx(e[n])?{type:`Identifier`,name:e[n]}:{type:`Literal`,value:e[n]};i=i?{type:`MemberExpression`,object:i,property:t,computed:!!(n&&t.type===`Literal`),optional:!1}:t}r=i}else r=Qx(t)&&!/^[a-z]/.test(t)?{type:`Identifier`,name:t}:{type:`Literal`,value:t};if(r.type===`Literal`){let t=r.value;return ZS.call(e.components,t)?e.components[t]:t}if(e.evaluater)return e.evaluater.evaluateExpression(r);xC(e)}function xC(e,t){let n=new YS("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:`mdx-estree`,source:`hast-util-to-jsx-runtime`});throw n.file=e.filePath||void 0,n.url=nC+`#cannot-handle-mdx-estrees-without-createevaluater`,n}function SC(e){let t={},n;for(n in e)ZS.call(e,n)&&(t[CC(n)]=e[n]);return t}function CC(e){let t=e.replace($S,wC);return t.slice(0,3)===`ms-`&&(t=`-`+t),t}function wC(e){return`-`+e.toLowerCase()}var TC={action:[`form`],cite:[`blockquote`,`del`,`ins`,`q`],data:[`object`],formAction:[`button`,`input`],href:[`a`,`area`,`base`,`link`],icon:[`menuitem`],itemId:null,manifest:[`html`],ping:[`a`,`area`],poster:[`video`],src:[`audio`,`embed`,`iframe`,`img`,`input`,`script`,`source`,`track`,`video`]},EC={};function DC(e,t){let n=t||EC;return OC(e,typeof n.includeImageAlt!=`boolean`||n.includeImageAlt,typeof n.includeHtml!=`boolean`||n.includeHtml)}function OC(e,t,n){if(AC(e)){if(`value`in e)return e.type===`html`&&!n?``:e.value;if(t&&`alt`in e&&e.alt)return e.alt;if(`children`in e)return kC(e.children,t,n)}return Array.isArray(e)?kC(e,t,n):``}function kC(e,t,n){let r=[],i=-1;for(;++i<e.length;)r[i]=OC(e[i],t,n);return r.join(``)}function AC(e){return!!(e&&typeof e==`object`)}var jC=document.createElement(`i`);function MC(e){let t=`&`+e+`;`;jC.innerHTML=t;let n=jC.textContent;return n.charCodeAt(n.length-1)===59&&e!==`semi`?!1:n!==t&&n}function NC(e,t,n,r){let i=e.length,a=0,o;if(t=t<0?-t>i?0:i+t:t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);a<r.length;)o=r.slice(a,a+1e4),o.unshift(t,0),e.splice(...o),a+=1e4,t+=1e4}function PC(e,t){return e.length>0?(NC(e,e.length,0,t),e):t}var FC={}.hasOwnProperty;function IC(e){let t={},n=-1;for(;++n<e.length;)LC(t,e[n]);return t}function LC(e,t){let n;for(n in t){let r=(FC.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n],a;if(i)for(a in i){FC.call(r,a)||(r[a]=[]);let e=i[a];RC(r[a],Array.isArray(e)?e:e?[e]:[])}}}function RC(e,t){let n=-1,r=[];for(;++n<t.length;)(t[n].add===`after`?e:r).push(t[n]);NC(e,0,0,r)}function zC(e,t){let n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)==65535||(n&65535)==65534||n>1114111?`�`:String.fromCodePoint(n)}function BC(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}var VC=QC(/[A-Za-z]/),HC=QC(/[\dA-Za-z]/),UC=QC(/[#-'*+\--9=?A-Z^-~]/);function WC(e){return e!==null&&(e<32||e===127)}var GC=QC(/\d/),KC=QC(/[\dA-Fa-f]/),qC=QC(/[!-/:-@[-`{-~]/);function q(e){return e!==null&&e<-2}function JC(e){return e!==null&&(e<0||e===32)}function YC(e){return e===-2||e===-1||e===32}var XC=QC(/\p{P}|\p{S}/u),ZC=QC(/\s/);function QC(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function $C(e){let t=[],n=-1,r=0,i=0;for(;++n<e.length;){let a=e.charCodeAt(n),o=``;if(a===37&&HC(e.charCodeAt(n+1))&&HC(e.charCodeAt(n+2)))i=2;else if(a<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(a))||(o=String.fromCharCode(a));else if(a>55295&&a<57344){let t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(o=String.fromCharCode(a,t),i=1):o=`�`}else o=String.fromCharCode(a);o&&=(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,``),i&&=(n+=i,0)}return t.join(``)+e.slice(r)}function ew(e,t,n,r){let i=r?r-1:1/0,a=0;return o;function o(r){return YC(r)?(e.enter(n),s(r)):t(r)}function s(r){return YC(r)&&a++<i?(e.consume(r),s):(e.exit(n),t(r))}}var tw={tokenize:nw};function nw(e){let t=e.attempt(this.parser.constructs.contentInitial,r,i),n;return t;function r(n){if(n===null){e.consume(n);return}return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),ew(e,t,`linePrefix`)}function i(t){return e.enter(`paragraph`),a(t)}function a(t){let r=e.enter(`chunkText`,{contentType:`text`,previous:n});return n&&(n.next=r),n=r,o(t)}function o(t){if(t===null){e.exit(`chunkText`),e.exit(`paragraph`),e.consume(t);return}return q(t)?(e.consume(t),e.exit(`chunkText`),a):(e.consume(t),o)}}var rw={tokenize:aw},iw={tokenize:ow};function aw(e){let t=this,n=[],r=0,i,a,o;return s;function s(i){if(r<n.length){let a=n[r];return t.containerState=a[1],e.attempt(a[0].continuation,c,l)(i)}return l(i)}function c(e){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,i&&v();let n=t.events.length,a=n,o;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){o=t.events[a][1].end;break}_(r);let s=n;for(;s<t.events.length;)t.events[s][1].end={...o},s++;return NC(t.events,a+1,0,t.events.slice(n)),t.events.length=s,l(e)}return s(e)}function l(a){if(r===n.length){if(!i)return f(a);if(i.currentConstruct&&i.currentConstruct.concrete)return m(a);t.interrupt=!(!i.currentConstruct||i._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(iw,u,d)(a)}function u(e){return i&&v(),_(r),f(e)}function d(e){return t.parser.lazy[t.now().line]=r!==n.length,o=t.now().offset,m(e)}function f(n){return t.containerState={},e.attempt(iw,p,m)(n)}function p(e){return r++,n.push([t.currentConstruct,t.containerState]),f(e)}function m(n){if(n===null){i&&v(),_(0),e.consume(n);return}return i||=t.parser.flow(t.now()),e.enter(`chunkFlow`,{_tokenizer:i,contentType:`flow`,previous:a}),h(n)}function h(n){if(n===null){g(e.exit(`chunkFlow`),!0),_(0),e.consume(n);return}return q(n)?(e.consume(n),g(e.exit(`chunkFlow`)),r=0,t.interrupt=void 0,s):(e.consume(n),h)}function g(e,n){let s=t.sliceStream(e);if(n&&s.push(null),e.previous=a,a&&(a.next=e),a=e,i.defineSkip(e.start),i.write(s),t.parser.lazy[e.start.line]){let e=i.events.length;for(;e--;)if(i.events[e][1].start.offset<o&&(!i.events[e][1].end||i.events[e][1].end.offset>o))return;let n=t.events.length,a=n,s,c;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){if(s){c=t.events[a][1].end;break}s=!0}for(_(r),e=n;e<t.events.length;)t.events[e][1].end={...c},e++;NC(t.events,a+1,0,t.events.slice(n)),t.events.length=e}}function _(r){let i=n.length;for(;i-->r;){let r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function v(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function ow(e,t,n){return ew(e,e.attempt(this.parser.constructs.document,t,n),`linePrefix`,this.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)}function sw(e){if(e===null||JC(e)||ZC(e))return 1;if(XC(e))return 2}function cw(e,t,n){let r=[],i=-1;for(;++i<e.length;){let a=e[i].resolveAll;a&&!r.includes(a)&&(t=a(t,n),r.push(a))}return t}var lw={name:`attention`,resolveAll:uw,tokenize:dw};function uw(e,t){let n=-1,r,i,a,o,s,c,l,u;for(;++n<e.length;)if(e[n][0]===`enter`&&e[n][1].type===`attentionSequence`&&e[n][1]._close){for(r=n;r--;)if(e[r][0]===`exit`&&e[r][1].type===`attentionSequence`&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;let d={...e[r][1].end},f={...e[n][1].start};fw(d,-c),fw(f,c),o={type:c>1?`strongSequence`:`emphasisSequence`,start:d,end:{...e[r][1].end}},s={type:c>1?`strongSequence`:`emphasisSequence`,start:{...e[n][1].start},end:f},a={type:c>1?`strongText`:`emphasisText`,start:{...e[r][1].end},end:{...e[n][1].start}},i={type:c>1?`strong`:`emphasis`,start:{...o.start},end:{...s.end}},e[r][1].end={...o.start},e[n][1].start={...s.end},l=[],e[r][1].end.offset-e[r][1].start.offset&&(l=PC(l,[[`enter`,e[r][1],t],[`exit`,e[r][1],t]])),l=PC(l,[[`enter`,i,t],[`enter`,o,t],[`exit`,o,t],[`enter`,a,t]]),l=PC(l,cw(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),l=PC(l,[[`exit`,a,t],[`enter`,s,t],[`exit`,s,t],[`exit`,i,t]]),e[n][1].end.offset-e[n][1].start.offset?(u=2,l=PC(l,[[`enter`,e[n][1],t],[`exit`,e[n][1],t]])):u=0,NC(e,r-1,n-r+3,l),n=r+l.length-u-2;break}}for(n=-1;++n<e.length;)e[n][1].type===`attentionSequence`&&(e[n][1].type=`data`);return e}function dw(e,t){let n=this.parser.constructs.attentionMarkers.null,r=this.previous,i=sw(r),a;return o;function o(t){return a=t,e.enter(`attentionSequence`),s(t)}function s(o){if(o===a)return e.consume(o),s;let c=e.exit(`attentionSequence`),l=sw(o),u=!l||l===2&&i||n.includes(o),d=!i||i===2&&l||n.includes(r);return c._open=!!(a===42?u:u&&(i||!d)),c._close=!!(a===42?d:d&&(l||!u)),t(o)}}function fw(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}var pw={name:`autolink`,tokenize:mw};function mw(e,t,n){let r=0;return i;function i(t){return e.enter(`autolink`),e.enter(`autolinkMarker`),e.consume(t),e.exit(`autolinkMarker`),e.enter(`autolinkProtocol`),a}function a(t){return VC(t)?(e.consume(t),o):t===64?n(t):l(t)}function o(e){return e===43||e===45||e===46||HC(e)?(r=1,s(e)):l(e)}function s(t){return t===58?(e.consume(t),r=0,c):(t===43||t===45||t===46||HC(t))&&r++<32?(e.consume(t),s):(r=0,l(t))}function c(r){return r===62?(e.exit(`autolinkProtocol`),e.enter(`autolinkMarker`),e.consume(r),e.exit(`autolinkMarker`),e.exit(`autolink`),t):r===null||r===32||r===60||WC(r)?n(r):(e.consume(r),c)}function l(t){return t===64?(e.consume(t),u):UC(t)?(e.consume(t),l):n(t)}function u(e){return HC(e)?d(e):n(e)}function d(n){return n===46?(e.consume(n),r=0,u):n===62?(e.exit(`autolinkProtocol`).type=`autolinkEmail`,e.enter(`autolinkMarker`),e.consume(n),e.exit(`autolinkMarker`),e.exit(`autolink`),t):f(n)}function f(t){if((t===45||HC(t))&&r++<63){let n=t===45?f:d;return e.consume(t),n}return n(t)}}var hw={partial:!0,tokenize:gw};function gw(e,t,n){return r;function r(t){return YC(t)?ew(e,i,`linePrefix`)(t):i(t)}function i(e){return e===null||q(e)?t(e):n(e)}}var _w={continuation:{tokenize:yw},exit:bw,name:`blockQuote`,tokenize:vw};function vw(e,t,n){let r=this;return i;function i(t){if(t===62){let n=r.containerState;return n.open||=(e.enter(`blockQuote`,{_container:!0}),!0),e.enter(`blockQuotePrefix`),e.enter(`blockQuoteMarker`),e.consume(t),e.exit(`blockQuoteMarker`),a}return n(t)}function a(n){return YC(n)?(e.enter(`blockQuotePrefixWhitespace`),e.consume(n),e.exit(`blockQuotePrefixWhitespace`),e.exit(`blockQuotePrefix`),t):(e.exit(`blockQuotePrefix`),t(n))}}function yw(e,t,n){let r=this;return i;function i(t){return YC(t)?ew(e,a,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):a(t)}function a(r){return e.attempt(_w,t,n)(r)}}function bw(e){e.exit(`blockQuote`)}var xw={name:`characterEscape`,tokenize:Sw};function Sw(e,t,n){return r;function r(t){return e.enter(`characterEscape`),e.enter(`escapeMarker`),e.consume(t),e.exit(`escapeMarker`),i}function i(r){return qC(r)?(e.enter(`characterEscapeValue`),e.consume(r),e.exit(`characterEscapeValue`),e.exit(`characterEscape`),t):n(r)}}var Cw={name:`characterReference`,tokenize:ww};function ww(e,t,n){let r=this,i=0,a,o;return s;function s(t){return e.enter(`characterReference`),e.enter(`characterReferenceMarker`),e.consume(t),e.exit(`characterReferenceMarker`),c}function c(t){return t===35?(e.enter(`characterReferenceMarkerNumeric`),e.consume(t),e.exit(`characterReferenceMarkerNumeric`),l):(e.enter(`characterReferenceValue`),a=31,o=HC,u(t))}function l(t){return t===88||t===120?(e.enter(`characterReferenceMarkerHexadecimal`),e.consume(t),e.exit(`characterReferenceMarkerHexadecimal`),e.enter(`characterReferenceValue`),a=6,o=KC,u):(e.enter(`characterReferenceValue`),a=7,o=GC,u(t))}function u(s){if(s===59&&i){let i=e.exit(`characterReferenceValue`);return o===HC&&!MC(r.sliceSerialize(i))?n(s):(e.enter(`characterReferenceMarker`),e.consume(s),e.exit(`characterReferenceMarker`),e.exit(`characterReference`),t)}return o(s)&&i++<a?(e.consume(s),u):n(s)}}var Tw={partial:!0,tokenize:Ow},Ew={concrete:!0,name:`codeFenced`,tokenize:Dw};function Dw(e,t,n){let r=this,i={partial:!0,tokenize:x},a=0,o=0,s;return c;function c(e){return l(e)}function l(t){let n=r.events[r.events.length-1];return a=n&&n[1].type===`linePrefix`?n[2].sliceSerialize(n[1],!0).length:0,s=t,e.enter(`codeFenced`),e.enter(`codeFencedFence`),e.enter(`codeFencedFenceSequence`),u(t)}function u(t){return t===s?(o++,e.consume(t),u):o<3?n(t):(e.exit(`codeFencedFenceSequence`),YC(t)?ew(e,d,`whitespace`)(t):d(t))}function d(n){return n===null||q(n)?(e.exit(`codeFencedFence`),r.interrupt?t(n):e.check(Tw,h,b)(n)):(e.enter(`codeFencedFenceInfo`),e.enter(`chunkString`,{contentType:`string`}),f(n))}function f(t){return t===null||q(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceInfo`),d(t)):YC(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceInfo`),ew(e,p,`whitespace`)(t)):t===96&&t===s?n(t):(e.consume(t),f)}function p(t){return t===null||q(t)?d(t):(e.enter(`codeFencedFenceMeta`),e.enter(`chunkString`,{contentType:`string`}),m(t))}function m(t){return t===null||q(t)?(e.exit(`chunkString`),e.exit(`codeFencedFenceMeta`),d(t)):t===96&&t===s?n(t):(e.consume(t),m)}function h(t){return e.attempt(i,b,g)(t)}function g(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),_}function _(t){return a>0&&YC(t)?ew(e,v,`linePrefix`,a+1)(t):v(t)}function v(t){return t===null||q(t)?e.check(Tw,h,b)(t):(e.enter(`codeFlowValue`),y(t))}function y(t){return t===null||q(t)?(e.exit(`codeFlowValue`),v(t)):(e.consume(t),y)}function b(n){return e.exit(`codeFenced`),t(n)}function x(e,t,n){let i=0;return a;function a(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c}function c(t){return e.enter(`codeFencedFence`),YC(t)?ew(e,l,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):l(t)}function l(t){return t===s?(e.enter(`codeFencedFenceSequence`),u(t)):n(t)}function u(t){return t===s?(i++,e.consume(t),u):i>=o?(e.exit(`codeFencedFenceSequence`),YC(t)?ew(e,d,`whitespace`)(t):d(t)):n(t)}function d(r){return r===null||q(r)?(e.exit(`codeFencedFence`),t(r)):n(r)}}}function Ow(e,t,n){let r=this;return i;function i(t){return t===null?n(t):(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}var kw={name:`codeIndented`,tokenize:jw},Aw={partial:!0,tokenize:Mw};function jw(e,t,n){let r=this;return i;function i(t){return e.enter(`codeIndented`),ew(e,a,`linePrefix`,5)(t)}function a(e){let t=r.events[r.events.length-1];return t&&t[1].type===`linePrefix`&&t[2].sliceSerialize(t[1],!0).length>=4?o(e):n(e)}function o(t){return t===null?c(t):q(t)?e.attempt(Aw,o,c)(t):(e.enter(`codeFlowValue`),s(t))}function s(t){return t===null||q(t)?(e.exit(`codeFlowValue`),o(t)):(e.consume(t),s)}function c(n){return e.exit(`codeIndented`),t(n)}}function Mw(e,t,n){let r=this;return i;function i(t){return r.parser.lazy[r.now().line]?n(t):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),i):ew(e,a,`linePrefix`,5)(t)}function a(e){let a=r.events[r.events.length-1];return a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(e):q(e)?i(e):n(e)}}var Nw={name:`codeText`,previous:Fw,resolve:Pw,tokenize:Iw};function Pw(e){let t=e.length-4,n=3,r,i;if((e[n][1].type===`lineEnding`||e[n][1].type===`space`)&&(e[t][1].type===`lineEnding`||e[t][1].type===`space`)){for(r=n;++r<t;)if(e[r][1].type===`codeTextData`){e[n][1].type=`codeTextPadding`,e[t][1].type=`codeTextPadding`,n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!==`lineEnding`&&(i=r):(r===t||e[r][1].type===`lineEnding`)&&(e[i][1].type=`codeTextData`,r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function Fw(e){return e!==96||this.events[this.events.length-1][1].type===`characterEscape`}function Iw(e,t,n){let r=0,i,a;return o;function o(t){return e.enter(`codeText`),e.enter(`codeTextSequence`),s(t)}function s(t){return t===96?(e.consume(t),r++,s):(e.exit(`codeTextSequence`),c(t))}function c(t){return t===null?n(t):t===32?(e.enter(`space`),e.consume(t),e.exit(`space`),c):t===96?(a=e.enter(`codeTextSequence`),i=0,u(t)):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c):(e.enter(`codeTextData`),l(t))}function l(t){return t===null||t===32||t===96||q(t)?(e.exit(`codeTextData`),c(t)):(e.consume(t),l)}function u(n){return n===96?(e.consume(n),i++,u):i===r?(e.exit(`codeTextSequence`),e.exit(`codeText`),t(n)):(a.type=`codeTextData`,l(n))}}var Lw=class{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,t){let n=t??1/0;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){let r=t||0;this.setCursor(Math.trunc(e));let i=this.right.splice(this.right.length-r,1/0);return n&&Rw(this.left,n),i.reverse()}pop(){return this.setCursor(1/0),this.left.pop()}push(e){this.setCursor(1/0),this.left.push(e)}pushMany(e){this.setCursor(1/0),Rw(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),Rw(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0)){if(e<this.left.length){let t=this.left.splice(e,1/0);Rw(this.right,t.reverse())}else{let t=this.right.splice(this.left.length+this.right.length-e,1/0);Rw(this.left,t.reverse())}}}};function Rw(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function zw(e){let t={},n=-1,r,i,a,o,s,c,l,u=new Lw(e);for(;++n<u.length;){for(;n in t;)n=t[n];if(r=u.get(n),n&&r[1].type===`chunkFlow`&&u.get(n-1)[1].type===`listItemPrefix`&&(c=r[1]._tokenizer.events,a=0,a<c.length&&c[a][1].type===`lineEndingBlank`&&(a+=2),a<c.length&&c[a][1].type===`content`))for(;++a<c.length&&c[a][1].type!==`content`;)c[a][1].type===`chunkText`&&(c[a][1]._isInFirstContentOfListItem=!0,a++);if(r[0]===`enter`)r[1].contentType&&(Object.assign(t,Bw(u,n)),n=t[n],l=!0);else if(r[1]._container){for(a=n,i=void 0;a--;)if(o=u.get(a),o[1].type===`lineEnding`||o[1].type===`lineEndingBlank`)o[0]===`enter`&&(i&&(u.get(i)[1].type=`lineEndingBlank`),o[1].type=`lineEnding`,i=a);else if(o[1].type!==`linePrefix`&&o[1].type!==`listItemIndent`)break;i&&(r[1].end={...u.get(i)[1].start},s=u.slice(i,n),s.unshift(r),u.splice(i,n-i+1,s))}}return NC(e,0,1/0,u.slice(0)),!l}function Bw(e,t){let n=e.get(t)[1],r=e.get(t)[2],i=t-1,a=[],o=n._tokenizer;o||(o=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));let s=o.events,c=[],l={},u,d,f=-1,p=n,m=0,h=0,g=[h];for(;p;){for(;e.get(++i)[1]!==p;);a.push(i),p._tokenizer||(u=r.sliceStream(p),p.next||u.push(null),d&&o.defineSkip(p.start),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(u),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=n;++f<s.length;)s[f][0]===`exit`&&s[f-1][0]===`enter`&&s[f][1].type===s[f-1][1].type&&s[f][1].start.line!==s[f][1].end.line&&(h=f+1,g.push(h),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(o.events=[],p?(p._tokenizer=void 0,p.previous=void 0):g.pop(),f=g.length;f--;){let t=s.slice(g[f],g[f+1]),n=a.pop();c.push([n,n+t.length-1]),e.splice(n,2,t)}for(c.reverse(),f=-1;++f<c.length;)l[m+c[f][0]]=m+c[f][1],m+=c[f][1]-c[f][0]-1;return l}var Vw={resolve:Uw,tokenize:Ww},Hw={partial:!0,tokenize:Gw};function Uw(e){return zw(e),e}function Ww(e,t){let n;return r;function r(t){return e.enter(`content`),n=e.enter(`chunkContent`,{contentType:`content`}),i(t)}function i(t){return t===null?a(t):q(t)?e.check(Hw,o,a)(t):(e.consume(t),i)}function a(n){return e.exit(`chunkContent`),e.exit(`content`),t(n)}function o(t){return e.consume(t),e.exit(`chunkContent`),n.next=e.enter(`chunkContent`,{contentType:`content`,previous:n}),n=n.next,i}}function Gw(e,t,n){let r=this;return i;function i(t){return e.exit(`chunkContent`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),ew(e,a,`linePrefix`)}function a(i){if(i===null||q(i))return n(i);let a=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes(`codeIndented`)&&a&&a[1].type===`linePrefix`&&a[2].sliceSerialize(a[1],!0).length>=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function Kw(e,t,n,r,i,a,o,s,c){let l=c||1/0,u=0;return d;function d(t){return t===60?(e.enter(r),e.enter(i),e.enter(a),e.consume(t),e.exit(a),f):t===null||t===32||t===41||WC(t)?n(t):(e.enter(r),e.enter(o),e.enter(s),e.enter(`chunkString`,{contentType:`string`}),h(t))}function f(n){return n===62?(e.enter(a),e.consume(n),e.exit(a),e.exit(i),e.exit(r),t):(e.enter(s),e.enter(`chunkString`,{contentType:`string`}),p(n))}function p(t){return t===62?(e.exit(`chunkString`),e.exit(s),f(t)):t===null||t===60||q(t)?n(t):(e.consume(t),t===92?m:p)}function m(t){return t===60||t===62||t===92?(e.consume(t),p):p(t)}function h(i){return!u&&(i===null||i===41||JC(i))?(e.exit(`chunkString`),e.exit(s),e.exit(o),e.exit(r),t(i)):u<l&&i===40?(e.consume(i),u++,h):i===41?(e.consume(i),u--,h):i===null||i===32||i===40||WC(i)?n(i):(e.consume(i),i===92?g:h)}function g(t){return t===40||t===41||t===92?(e.consume(t),h):h(t)}}function qw(e,t,n,r,i,a){let o=this,s=0,c;return l;function l(t){return e.enter(r),e.enter(i),e.consume(t),e.exit(i),e.enter(a),u}function u(l){return s>999||l===null||l===91||l===93&&!c||l===94&&!s&&`_hiddenFootnoteSupport`in o.parser.constructs?n(l):l===93?(e.exit(a),e.enter(i),e.consume(l),e.exit(i),e.exit(r),t):q(l)?(e.enter(`lineEnding`),e.consume(l),e.exit(`lineEnding`),u):(e.enter(`chunkString`,{contentType:`string`}),d(l))}function d(t){return t===null||t===91||t===93||q(t)||s++>999?(e.exit(`chunkString`),u(t)):(e.consume(t),c||=!YC(t),t===92?f:d)}function f(t){return t===91||t===92||t===93?(e.consume(t),s++,d):d(t)}}function Jw(e,t,n,r,i,a){let o;return s;function s(t){return t===34||t===39||t===40?(e.enter(r),e.enter(i),e.consume(t),e.exit(i),o=t===40?41:t,c):n(t)}function c(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(a),l(n))}function l(t){return t===o?(e.exit(a),c(o)):t===null?n(t):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),ew(e,l,`linePrefix`)):(e.enter(`chunkString`,{contentType:`string`}),u(t))}function u(t){return t===o||t===null||q(t)?(e.exit(`chunkString`),l(t)):(e.consume(t),t===92?d:u)}function d(t){return t===o||t===92?(e.consume(t),u):u(t)}}function Yw(e,t){let n;return r;function r(i){return q(i)?(e.enter(`lineEnding`),e.consume(i),e.exit(`lineEnding`),n=!0,r):YC(i)?ew(e,r,n?`linePrefix`:`lineSuffix`)(i):t(i)}}var Xw={name:`definition`,tokenize:Qw},Zw={partial:!0,tokenize:$w};function Qw(e,t,n){let r=this,i;return a;function a(t){return e.enter(`definition`),o(t)}function o(t){return qw.call(r,e,s,n,`definitionLabel`,`definitionLabelMarker`,`definitionLabelString`)(t)}function s(t){return i=BC(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),c):n(t)}function c(t){return JC(t)?Yw(e,l)(t):l(t)}function l(t){return Kw(e,u,n,`definitionDestination`,`definitionDestinationLiteral`,`definitionDestinationLiteralMarker`,`definitionDestinationRaw`,`definitionDestinationString`)(t)}function u(t){return e.attempt(Zw,d,d)(t)}function d(t){return YC(t)?ew(e,f,`whitespace`)(t):f(t)}function f(a){return a===null||q(a)?(e.exit(`definition`),r.parser.defined.push(i),t(a)):n(a)}}function $w(e,t,n){return r;function r(t){return JC(t)?Yw(e,i)(t):n(t)}function i(t){return Jw(e,a,n,`definitionTitle`,`definitionTitleMarker`,`definitionTitleString`)(t)}function a(t){return YC(t)?ew(e,o,`whitespace`)(t):o(t)}function o(e){return e===null||q(e)?t(e):n(e)}}var eT={name:`hardBreakEscape`,tokenize:tT};function tT(e,t,n){return r;function r(t){return e.enter(`hardBreakEscape`),e.consume(t),i}function i(r){return q(r)?(e.exit(`hardBreakEscape`),t(r)):n(r)}}var nT={name:`headingAtx`,resolve:rT,tokenize:iT};function rT(e,t){let n=e.length-2,r=3,i,a;return e[r][1].type===`whitespace`&&(r+=2),n-2>r&&e[n][1].type===`whitespace`&&(n-=2),e[n][1].type===`atxHeadingSequence`&&(r===n-1||n-4>r&&e[n-2][1].type===`whitespace`)&&(n-=r+1===n?2:4),n>r&&(i={type:`atxHeadingText`,start:e[r][1].start,end:e[n][1].end},a={type:`chunkText`,start:e[r][1].start,end:e[n][1].end,contentType:`text`},NC(e,r,n-r+1,[[`enter`,i,t],[`enter`,a,t],[`exit`,a,t],[`exit`,i,t]])),e}function iT(e,t,n){let r=0;return i;function i(t){return e.enter(`atxHeading`),a(t)}function a(t){return e.enter(`atxHeadingSequence`),o(t)}function o(t){return t===35&&r++<6?(e.consume(t),o):t===null||JC(t)?(e.exit(`atxHeadingSequence`),s(t)):n(t)}function s(n){return n===35?(e.enter(`atxHeadingSequence`),c(n)):n===null||q(n)?(e.exit(`atxHeading`),t(n)):YC(n)?ew(e,s,`whitespace`)(n):(e.enter(`atxHeadingText`),l(n))}function c(t){return t===35?(e.consume(t),c):(e.exit(`atxHeadingSequence`),s(t))}function l(t){return t===null||t===35||JC(t)?(e.exit(`atxHeadingText`),s(t)):(e.consume(t),l)}}var aT=`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.h1.h2.h3.h4.h5.h6.head.header.hr.html.iframe.legend.li.link.main.menu.menuitem.nav.noframes.ol.optgroup.option.p.param.search.section.summary.table.tbody.td.tfoot.th.thead.title.tr.track.ul`.split(`.`),oT=[`pre`,`script`,`style`,`textarea`],sT={concrete:!0,name:`htmlFlow`,resolveTo:uT,tokenize:dT},cT={partial:!0,tokenize:pT},lT={partial:!0,tokenize:fT};function uT(e){let t=e.length;for(;t--&&(e[t][0]!==`enter`||e[t][1].type!==`htmlFlow`););return t>1&&e[t-2][1].type===`linePrefix`&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function dT(e,t,n){let r=this,i,a,o,s,c;return l;function l(e){return u(e)}function u(t){return e.enter(`htmlFlow`),e.enter(`htmlFlowData`),e.consume(t),d}function d(s){return s===33?(e.consume(s),f):s===47?(e.consume(s),a=!0,h):s===63?(e.consume(s),i=3,r.interrupt?t:ne):VC(s)?(e.consume(s),o=String.fromCharCode(s),g):n(s)}function f(a){return a===45?(e.consume(a),i=2,p):a===91?(e.consume(a),i=5,s=0,m):VC(a)?(e.consume(a),i=4,r.interrupt?t:ne):n(a)}function p(i){return i===45?(e.consume(i),r.interrupt?t:ne):n(i)}function m(i){return i===`CDATA[`.charCodeAt(s++)?(e.consume(i),s===6?r.interrupt?t:O:m):n(i)}function h(t){return VC(t)?(e.consume(t),o=String.fromCharCode(t),g):n(t)}function g(s){if(s===null||s===47||s===62||JC(s)){let c=s===47,l=o.toLowerCase();return!c&&!a&&oT.includes(l)?(i=1,r.interrupt?t(s):O(s)):aT.includes(o.toLowerCase())?(i=6,c?(e.consume(s),_):r.interrupt?t(s):O(s)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(s):a?v(s):y(s))}return s===45||HC(s)?(e.consume(s),o+=String.fromCharCode(s),g):n(s)}function _(i){return i===62?(e.consume(i),r.interrupt?t:O):n(i)}function v(t){return YC(t)?(e.consume(t),v):E(t)}function y(t){return t===47?(e.consume(t),E):t===58||t===95||VC(t)?(e.consume(t),b):YC(t)?(e.consume(t),y):E(t)}function b(t){return t===45||t===46||t===58||t===95||HC(t)?(e.consume(t),b):x(t)}function x(t){return t===61?(e.consume(t),S):YC(t)?(e.consume(t),x):y(t)}function S(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),c=t,C):YC(t)?(e.consume(t),S):w(t)}function C(t){return t===c?(e.consume(t),c=null,T):t===null||q(t)?n(t):(e.consume(t),C)}function w(t){return t===null||t===34||t===39||t===47||t===60||t===61||t===62||t===96||JC(t)?x(t):(e.consume(t),w)}function T(e){return e===47||e===62||YC(e)?y(e):n(e)}function E(t){return t===62?(e.consume(t),D):n(t)}function D(t){return t===null||q(t)?O(t):YC(t)?(e.consume(t),D):n(t)}function O(t){return t===45&&i===2?(e.consume(t),M):t===60&&i===1?(e.consume(t),N):t===62&&i===4?(e.consume(t),re):t===63&&i===3?(e.consume(t),ne):t===93&&i===5?(e.consume(t),te):q(t)&&(i===6||i===7)?(e.exit(`htmlFlowData`),e.check(cT,ie,k)(t)):t===null||q(t)?(e.exit(`htmlFlowData`),k(t)):(e.consume(t),O)}function k(t){return e.check(lT,A,ie)(t)}function A(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),j}function j(t){return t===null||q(t)?k(t):(e.enter(`htmlFlowData`),O(t))}function M(t){return t===45?(e.consume(t),ne):O(t)}function N(t){return t===47?(e.consume(t),o=``,ee):O(t)}function ee(t){if(t===62){let n=o.toLowerCase();return oT.includes(n)?(e.consume(t),re):O(t)}return VC(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),ee):O(t)}function te(t){return t===93?(e.consume(t),ne):O(t)}function ne(t){return t===62?(e.consume(t),re):t===45&&i===2?(e.consume(t),ne):O(t)}function re(t){return t===null||q(t)?(e.exit(`htmlFlowData`),ie(t)):(e.consume(t),re)}function ie(n){return e.exit(`htmlFlow`),t(n)}}function fT(e,t,n){let r=this;return i;function i(t){return q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),a):n(t)}function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}function pT(e,t,n){return r;function r(r){return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),e.attempt(hw,t,n)}}var mT={name:`htmlText`,tokenize:hT};function hT(e,t,n){let r=this,i,a,o;return s;function s(t){return e.enter(`htmlText`),e.enter(`htmlTextData`),e.consume(t),c}function c(t){return t===33?(e.consume(t),l):t===47?(e.consume(t),x):t===63?(e.consume(t),y):VC(t)?(e.consume(t),w):n(t)}function l(t){return t===45?(e.consume(t),u):t===91?(e.consume(t),a=0,m):VC(t)?(e.consume(t),v):n(t)}function u(t){return t===45?(e.consume(t),p):n(t)}function d(t){return t===null?n(t):t===45?(e.consume(t),f):q(t)?(o=d,N(t)):(e.consume(t),d)}function f(t){return t===45?(e.consume(t),p):d(t)}function p(e){return e===62?M(e):e===45?f(e):d(e)}function m(t){return t===`CDATA[`.charCodeAt(a++)?(e.consume(t),a===6?h:m):n(t)}function h(t){return t===null?n(t):t===93?(e.consume(t),g):q(t)?(o=h,N(t)):(e.consume(t),h)}function g(t){return t===93?(e.consume(t),_):h(t)}function _(t){return t===62?M(t):t===93?(e.consume(t),_):h(t)}function v(t){return t===null||t===62?M(t):q(t)?(o=v,N(t)):(e.consume(t),v)}function y(t){return t===null?n(t):t===63?(e.consume(t),b):q(t)?(o=y,N(t)):(e.consume(t),y)}function b(e){return e===62?M(e):y(e)}function x(t){return VC(t)?(e.consume(t),S):n(t)}function S(t){return t===45||HC(t)?(e.consume(t),S):C(t)}function C(t){return q(t)?(o=C,N(t)):YC(t)?(e.consume(t),C):M(t)}function w(t){return t===45||HC(t)?(e.consume(t),w):t===47||t===62||JC(t)?T(t):n(t)}function T(t){return t===47?(e.consume(t),M):t===58||t===95||VC(t)?(e.consume(t),E):q(t)?(o=T,N(t)):YC(t)?(e.consume(t),T):M(t)}function E(t){return t===45||t===46||t===58||t===95||HC(t)?(e.consume(t),E):D(t)}function D(t){return t===61?(e.consume(t),O):q(t)?(o=D,N(t)):YC(t)?(e.consume(t),D):T(t)}function O(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),i=t,k):q(t)?(o=O,N(t)):YC(t)?(e.consume(t),O):(e.consume(t),A)}function k(t){return t===i?(e.consume(t),i=void 0,j):t===null?n(t):q(t)?(o=k,N(t)):(e.consume(t),k)}function A(t){return t===null||t===34||t===39||t===60||t===61||t===96?n(t):t===47||t===62||JC(t)?T(t):(e.consume(t),A)}function j(e){return e===47||e===62||JC(e)?T(e):n(e)}function M(r){return r===62?(e.consume(r),e.exit(`htmlTextData`),e.exit(`htmlText`),t):n(r)}function N(t){return e.exit(`htmlTextData`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),ee}function ee(t){return YC(t)?ew(e,te,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):te(t)}function te(t){return e.enter(`htmlTextData`),o(t)}}var gT={name:`labelEnd`,resolveAll:bT,resolveTo:xT,tokenize:ST},_T={tokenize:CT},vT={tokenize:wT},yT={tokenize:TT};function bT(e){let t=-1,n=[];for(;++t<e.length;){let r=e[t][1];if(n.push(e[t]),r.type===`labelImage`||r.type===`labelLink`||r.type===`labelEnd`){let e=r.type===`labelImage`?4:2;r.type=`data`,t+=e}}return e.length!==n.length&&NC(e,0,e.length,n),e}function xT(e,t){let n=e.length,r=0,i,a,o,s;for(;n--;)if(i=e[n][1],a){if(i.type===`link`||i.type===`labelLink`&&i._inactive)break;e[n][0]===`enter`&&i.type===`labelLink`&&(i._inactive=!0)}else if(o){if(e[n][0]===`enter`&&(i.type===`labelImage`||i.type===`labelLink`)&&!i._balanced&&(a=n,i.type!==`labelLink`)){r=2;break}}else i.type===`labelEnd`&&(o=n);let c={type:e[a][1].type===`labelLink`?`link`:`image`,start:{...e[a][1].start},end:{...e[e.length-1][1].end}},l={type:`label`,start:{...e[a][1].start},end:{...e[o][1].end}},u={type:`labelText`,start:{...e[a+r+2][1].end},end:{...e[o-2][1].start}};return s=[[`enter`,c,t],[`enter`,l,t]],s=PC(s,e.slice(a+1,a+r+3)),s=PC(s,[[`enter`,u,t]]),s=PC(s,cw(t.parser.constructs.insideSpan.null,e.slice(a+r+4,o-3),t)),s=PC(s,[[`exit`,u,t],e[o-2],e[o-1],[`exit`,l,t]]),s=PC(s,e.slice(o+1)),s=PC(s,[[`exit`,c,t]]),NC(e,a,e.length,s),e}function ST(e,t,n){let r=this,i=r.events.length,a,o;for(;i--;)if((r.events[i][1].type===`labelImage`||r.events[i][1].type===`labelLink`)&&!r.events[i][1]._balanced){a=r.events[i][1];break}return s;function s(t){return a?a._inactive?d(t):(o=r.parser.defined.includes(BC(r.sliceSerialize({start:a.end,end:r.now()}))),e.enter(`labelEnd`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelEnd`),c):n(t)}function c(t){return t===40?e.attempt(_T,u,o?u:d)(t):t===91?e.attempt(vT,u,o?l:d)(t):o?u(t):d(t)}function l(t){return e.attempt(yT,u,d)(t)}function u(e){return t(e)}function d(e){return a._balanced=!0,n(e)}}function CT(e,t,n){return r;function r(t){return e.enter(`resource`),e.enter(`resourceMarker`),e.consume(t),e.exit(`resourceMarker`),i}function i(t){return JC(t)?Yw(e,a)(t):a(t)}function a(t){return t===41?u(t):Kw(e,o,s,`resourceDestination`,`resourceDestinationLiteral`,`resourceDestinationLiteralMarker`,`resourceDestinationRaw`,`resourceDestinationString`,32)(t)}function o(t){return JC(t)?Yw(e,c)(t):u(t)}function s(e){return n(e)}function c(t){return t===34||t===39||t===40?Jw(e,l,n,`resourceTitle`,`resourceTitleMarker`,`resourceTitleString`)(t):u(t)}function l(t){return JC(t)?Yw(e,u)(t):u(t)}function u(r){return r===41?(e.enter(`resourceMarker`),e.consume(r),e.exit(`resourceMarker`),e.exit(`resource`),t):n(r)}}function wT(e,t,n){let r=this;return i;function i(t){return qw.call(r,e,a,o,`reference`,`referenceMarker`,`referenceString`)(t)}function a(e){return r.parser.defined.includes(BC(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function o(e){return n(e)}}function TT(e,t,n){return r;function r(t){return e.enter(`reference`),e.enter(`referenceMarker`),e.consume(t),e.exit(`referenceMarker`),i}function i(r){return r===93?(e.enter(`referenceMarker`),e.consume(r),e.exit(`referenceMarker`),e.exit(`reference`),t):n(r)}}var ET={name:`labelStartImage`,resolveAll:gT.resolveAll,tokenize:DT};function DT(e,t,n){let r=this;return i;function i(t){return e.enter(`labelImage`),e.enter(`labelImageMarker`),e.consume(t),e.exit(`labelImageMarker`),a}function a(t){return t===91?(e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelImage`),o):n(t)}function o(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):t(e)}}var OT={name:`labelStartLink`,resolveAll:gT.resolveAll,tokenize:kT};function kT(e,t,n){let r=this;return i;function i(t){return e.enter(`labelLink`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelLink`),a}function a(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):t(e)}}var AT={name:`lineEnding`,tokenize:jT};function jT(e,t){return n;function n(n){return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),ew(e,t,`linePrefix`)}}var MT={name:`thematicBreak`,tokenize:NT};function NT(e,t,n){let r=0,i;return a;function a(t){return e.enter(`thematicBreak`),o(t)}function o(e){return i=e,s(e)}function s(a){return a===i?(e.enter(`thematicBreakSequence`),c(a)):r>=3&&(a===null||q(a))?(e.exit(`thematicBreak`),t(a)):n(a)}function c(t){return t===i?(e.consume(t),r++,c):(e.exit(`thematicBreakSequence`),YC(t)?ew(e,s,`whitespace`)(t):s(t))}}var PT={continuation:{tokenize:RT},exit:BT,name:`list`,tokenize:LT},FT={partial:!0,tokenize:VT},IT={partial:!0,tokenize:zT};function LT(e,t,n){let r=this,i=r.events[r.events.length-1],a=i&&i[1].type===`linePrefix`?i[2].sliceSerialize(i[1],!0).length:0,o=0;return s;function s(t){let i=r.containerState.type||(t===42||t===43||t===45?`listUnordered`:`listOrdered`);if(i===`listUnordered`?!r.containerState.marker||t===r.containerState.marker:GC(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),i===`listUnordered`)return e.enter(`listItemPrefix`),t===42||t===45?e.check(MT,n,l)(t):l(t);if(!r.interrupt||t===49)return e.enter(`listItemPrefix`),e.enter(`listItemValue`),c(t)}return n(t)}function c(t){return GC(t)&&++o<10?(e.consume(t),c):(!r.interrupt||o<2)&&(r.containerState.marker?t===r.containerState.marker:t===41||t===46)?(e.exit(`listItemValue`),l(t)):n(t)}function l(t){return e.enter(`listItemMarker`),e.consume(t),e.exit(`listItemMarker`),r.containerState.marker=r.containerState.marker||t,e.check(hw,r.interrupt?n:u,e.attempt(FT,f,d))}function u(e){return r.containerState.initialBlankLine=!0,a++,f(e)}function d(t){return YC(t)?(e.enter(`listItemPrefixWhitespace`),e.consume(t),e.exit(`listItemPrefixWhitespace`),f):n(t)}function f(n){return r.containerState.size=a+r.sliceSerialize(e.exit(`listItemPrefix`),!0).length,t(n)}}function RT(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(hw,i,a);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,ew(e,t,`listItemIndent`,r.containerState.size+1)(n)}function a(n){return r.containerState.furtherBlankLines||!YC(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(IT,t,o)(n))}function o(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,ew(e,e.attempt(PT,t,n),`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(i)}}function zT(e,t,n){let r=this;return ew(e,i,`listItemIndent`,r.containerState.size+1);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`listItemIndent`&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)}}function BT(e){e.exit(this.containerState.type)}function VT(e,t,n){let r=this;return ew(e,i,`listItemPrefixWhitespace`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:5);function i(e){let i=r.events[r.events.length-1];return!YC(e)&&i&&i[1].type===`listItemPrefixWhitespace`?t(e):n(e)}}var HT={name:`setextUnderline`,resolveTo:UT,tokenize:WT};function UT(e,t){let n=e.length,r,i,a;for(;n--;)if(e[n][0]===`enter`){if(e[n][1].type===`content`){r=n;break}e[n][1].type===`paragraph`&&(i=n)}else e[n][1].type===`content`&&e.splice(n,1),!a&&e[n][1].type===`definition`&&(a=n);let o={type:`setextHeading`,start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[i][1].type=`setextHeadingText`,a?(e.splice(i,0,[`enter`,o,t]),e.splice(a+1,0,[`exit`,e[r][1],t]),e[r][1].end={...e[a][1].end}):e[r][1]=o,e.push([`exit`,o,t]),e}function WT(e,t,n){let r=this,i;return a;function a(t){let a=r.events.length,s;for(;a--;)if(r.events[a][1].type!==`lineEnding`&&r.events[a][1].type!==`linePrefix`&&r.events[a][1].type!==`content`){s=r.events[a][1].type===`paragraph`;break}return!r.parser.lazy[r.now().line]&&(r.interrupt||s)?(e.enter(`setextHeadingLine`),i=t,o(t)):n(t)}function o(t){return e.enter(`setextHeadingLineSequence`),s(t)}function s(t){return t===i?(e.consume(t),s):(e.exit(`setextHeadingLineSequence`),YC(t)?ew(e,c,`lineSuffix`)(t):c(t))}function c(r){return r===null||q(r)?(e.exit(`setextHeadingLine`),t(r)):n(r)}}var GT={tokenize:KT};function KT(e){let t=this,n=e.attempt(hw,r,e.attempt(this.parser.constructs.flowInitial,i,ew(e,e.attempt(this.parser.constructs.flow,i,e.attempt(Vw,i)),`linePrefix`)));return n;function r(r){if(r===null){e.consume(r);return}return e.enter(`lineEndingBlank`),e.consume(r),e.exit(`lineEndingBlank`),t.currentConstruct=void 0,n}function i(r){if(r===null){e.consume(r);return}return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),t.currentConstruct=void 0,n}}var qT={resolveAll:ZT()},JT=XT(`string`),YT=XT(`text`);function XT(e){return{resolveAll:ZT(e===`text`?QT:void 0),tokenize:t};function t(t){let n=this,r=this.parser.constructs[e],i=t.attempt(r,a,o);return a;function a(e){return c(e)?i(e):o(e)}function o(e){if(e===null){t.consume(e);return}return t.enter(`data`),t.consume(e),s}function s(e){return c(e)?(t.exit(`data`),i(e)):(t.consume(e),s)}function c(e){if(e===null)return!0;let t=r[e],i=-1;if(t)for(;++i<t.length;){let e=t[i];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}}}function ZT(e){return t;function t(t,n){let r=-1,i;for(;++r<=t.length;)i===void 0?t[r]&&t[r][1].type===`data`&&(i=r,r++):(!t[r]||t[r][1].type!==`data`)&&(r!==i+2&&(t[i][1].end=t[r-1][1].end,t.splice(i+2,r-i-2),r=i+2),i=void 0);return e?e(t,n):t}}function QT(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type===`lineEnding`)&&e[n-1][1].type===`data`){let r=e[n-1][1],i=t.sliceStream(r),a=i.length,o=-1,s=0,c;for(;a--;){let e=i[a];if(typeof e==`string`){for(o=e.length;e.charCodeAt(o-1)===32;)s++,o--;if(o)break;o=-1}else if(e===-2)c=!0,s++;else if(e!==-1){a++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(s=0),s){let i={type:n===e.length||c||s<2?`lineSuffix`:`hardBreakTrailing`,start:{_bufferIndex:a?o:r.start._bufferIndex+o,_index:r.start._index+a,line:r.end.line,column:r.end.column-s,offset:r.end.offset-s},end:{...r.end}};r.end={...i.start},r.start.offset===r.end.offset?Object.assign(r,i):(e.splice(n,0,[`enter`,i,t],[`exit`,i,t]),n+=2)}n++}return e}var $T=e({attentionMarkers:()=>sE,contentInitial:()=>tE,disable:()=>cE,document:()=>eE,flow:()=>rE,flowInitial:()=>nE,insideSpan:()=>oE,string:()=>iE,text:()=>aE}),eE={42:PT,43:PT,45:PT,48:PT,49:PT,50:PT,51:PT,52:PT,53:PT,54:PT,55:PT,56:PT,57:PT,62:_w},tE={91:Xw},nE={[-2]:kw,[-1]:kw,32:kw},rE={35:nT,42:MT,45:[HT,MT],60:sT,61:HT,95:MT,96:Ew,126:Ew},iE={38:Cw,92:xw},aE={[-5]:AT,[-4]:AT,[-3]:AT,33:ET,38:Cw,42:lw,60:[pw,mT],91:OT,92:[eT,xw],93:gT,95:lw,96:Nw},oE={null:[lw,qT]},sE={null:[42,95]},cE={null:[]};function lE(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},a=[],o=[],s=[],c={attempt:C(x),check:C(S),consume:v,enter:y,exit:b,interrupt:C(S,{interrupt:!0})},l={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d},u=t.tokenize.call(l,c);return t.resolveAll&&a.push(t),l;function d(e){return o=PC(o,e),g(),o[o.length-1]===null?(w(t,0),l.events=cw(a,l.events,l),l.events):[]}function f(e,t){return dE(p(e),t)}function p(e){return uE(o,e)}function m(){let{_bufferIndex:e,_index:t,line:n,column:i,offset:a}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:a}}function h(e){i[e.line]=e.column,E()}function g(){let e;for(;r._index<o.length;){let t=o[r._index];if(typeof t==`string`)for(e=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===e&&r._bufferIndex<t.length;)_(t.charCodeAt(r._bufferIndex));else _(t)}}function _(e){u=u(e)}function v(e){q(e)?(r.line++,r.column=1,r.offset+=e===-3?2:1,E()):e!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),l.previous=e}function y(e,t){let n=t||{};return n.type=e,n.start=m(),l.events.push([`enter`,n,l]),s.push(n),n}function b(e){let t=s.pop();return t.end=m(),l.events.push([`exit`,t,l]),t}function x(e,t){w(e,t.from)}function S(e,t){t.restore()}function C(e,t){return n;function n(n,r,i){let a,o,s,u;return Array.isArray(n)?f(n):`tokenize`in n?f([n]):d(n);function d(e){return t;function t(t){let n=t!==null&&e[t],r=t!==null&&e.null;return f([...Array.isArray(n)?n:n?[n]:[],...Array.isArray(r)?r:r?[r]:[]])(t)}}function f(e){return a=e,o=0,e.length===0?i:p(e[o])}function p(e){return n;function n(n){return u=T(),s=e,e.partial||(l.currentConstruct=e),e.name&&l.parser.constructs.disable.null.includes(e.name)?h(n):e.tokenize.call(t?Object.assign(Object.create(l),t):l,c,m,h)(n)}}function m(t){return e(s,u),r}function h(e){return u.restore(),++o<a.length?p(a[o]):i}}}function w(e,t){e.resolveAll&&!a.includes(e)&&a.push(e),e.resolve&&NC(l.events,t,l.events.length-t,e.resolve(l.events.slice(t),l)),e.resolveTo&&(l.events=e.resolveTo(l.events,l))}function T(){let e=m(),t=l.previous,n=l.currentConstruct,i=l.events.length,a=Array.from(s);return{from:i,restore:o};function o(){r=e,l.previous=t,l.currentConstruct=n,l.events.length=i,s=a,E()}}function E(){r.line in i&&r.column<2&&(r.column=i[r.line],r.offset+=i[r.line]-1)}}function uE(e,t){let n=t.start._index,r=t.start._bufferIndex,i=t.end._index,a=t.end._bufferIndex,o;if(n===i)o=[e[n].slice(r,a)];else{if(o=e.slice(n,i),r>-1){let e=o[0];typeof e==`string`?o[0]=e.slice(r):o.shift()}a>0&&o.push(e[i].slice(0,a))}return o}function dE(e,t){let n=-1,r=[],i;for(;++n<e.length;){let a=e[n],o;if(typeof a==`string`)o=a;else switch(a){case-5:o=`\r`;break;case-4:o=`
62
62
  `;break;case-3:o=`\r
63
- `;break;case-2:o=t?` `:` `;break;case-1:if(!t&&i)continue;o=` `;break;default:o=String.fromCharCode(a)}i=a===-2,r.push(o)}return r.join(``)}function dE(e){let t={constructs:FC([QT,...(e||{}).extensions||[]]),content:n(ew),defined:[],document:n(nw),flow:n(WT),lazy:{},string:n(qT),text:n(JT)};return t;function n(e){return n;function n(n){return cE(t,e,n)}}}function fE(e){for(;!Rw(e););return e}var pE=/[\0\t\n\r]/g;function mE(){let e=1,t=``,n=!0,r;return i;function i(i,a,o){let s=[],c,l,u,d,f;for(i=t+(typeof i==`string`?i.toString():new TextDecoder(a||void 0).decode(i)),u=0,t=``,n&&=(i.charCodeAt(0)===65279&&u++,void 0);u<i.length;){if(pE.lastIndex=u,c=pE.exec(i),d=c&&c.index!==void 0?c.index:i.length,f=i.charCodeAt(d),!c){t=i.slice(u);break}if(f===10&&u===d&&r)s.push(-3),r=void 0;else switch(r&&=(s.push(-5),void 0),u<d&&(s.push(i.slice(u,d)),e+=d-u),f){case 0:s.push(65533),e++;break;case 9:for(l=Math.ceil(e/4)*4,s.push(-2);e++<l;)s.push(-1);break;case 10:s.push(-4),e=1;break;default:r=!0,e=1}u=d+1}return o&&(r&&s.push(-5),t&&s.push(t),s.push(null)),s}}var hE=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function gE(e){return e.replace(hE,_E)}function _E(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){let e=n.charCodeAt(1),t=e===120||e===88;return RC(n.slice(t?2:1),t?16:10)}return jC(n)||e}var vE={}.hasOwnProperty;function yE(e,t,n){return t&&typeof t==`object`&&(n=t,t=void 0),bE(n)(fE(dE(n).document().write(mE()(e,t,!0))))}function bE(e){let t={transforms:[],canContainEols:[`emphasis`,`fragment`,`heading`,`paragraph`,`strong`],enter:{autolink:a(be),autolinkProtocol:T,autolinkEmail:T,atxHeading:a(ge),blockQuote:a(P),characterEscape:T,characterReference:T,codeFenced:a(fe),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:a(fe,o),codeText:a(pe,o),codeTextData:T,data:T,codeFlowValue:T,definition:a(me),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:a(he),hardBreakEscape:a(_e),hardBreakTrailing:a(_e),htmlFlow:a(ve,o),htmlFlowData:T,htmlText:a(ve,o),htmlTextData:T,image:a(ye),label:o,link:a(be),listItem:a(Se),listItemValue:f,listOrdered:a(xe,d),listUnordered:a(xe),paragraph:a(Ce),reference:ae,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:a(ge),strong:a(we),thematicBreak:a(Ee)},exit:{atxHeading:c(),atxHeadingSequence:x,autolink:c(),autolinkEmail:de,autolinkProtocol:ue,blockQuote:c(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:se,characterReferenceMarkerNumeric:se,characterReferenceValue:ce,characterReference:le,codeFenced:c(g),codeFencedFence:h,codeFencedFenceInfo:p,codeFencedFenceMeta:m,codeFlowValue:E,codeIndented:c(_),codeText:c(j),codeTextData:E,data:E,definition:c(),definitionDestinationString:b,definitionLabelString:v,definitionTitleString:y,emphasis:c(),hardBreakEscape:c(O),hardBreakTrailing:c(O),htmlFlow:c(k),htmlFlowData:E,htmlText:c(A),htmlTextData:E,image:c(N),label:te,labelText:ee,lineEnding:D,link:c(M),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:oe,resourceDestinationString:ne,resourceTitleString:re,resource:ie,setextHeading:c(w),setextHeadingLineSequence:C,setextHeadingText:S,strong:c(),thematicBreak:c()}};SE(t,(e||{}).mdastExtensions||[]);let n={};return r;function r(e){let r={type:`root`,children:[]},a={stack:[r],tokenStack:[],config:t,enter:s,exit:l,buffer:o,resume:u,data:n},c=[],d=-1;for(;++d<e.length;)(e[d][1].type===`listOrdered`||e[d][1].type===`listUnordered`)&&(e[d][0]===`enter`?c.push(d):d=i(e,c.pop(),d));for(d=-1;++d<e.length;){let n=t[e[d][0]];vE.call(n,e[d][1].type)&&n[e[d][1].type].call(Object.assign({sliceSerialize:e[d][2].sliceSerialize},a),e[d][1])}if(a.tokenStack.length>0){let e=a.tokenStack[a.tokenStack.length-1];(e[1]||wE).call(a,void 0,e[0])}for(r.position={start:xE(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:xE(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},d=-1;++d<t.transforms.length;)r=t.transforms[d](r)||r;return r}function i(e,t,n){let r=t-1,i=-1,a=!1,o,s,c,l;for(;++r<=n;){let t=e[r];switch(t[1].type){case`listUnordered`:case`listOrdered`:case`blockQuote`:t[0]===`enter`?i++:i--,l=void 0;break;case`lineEndingBlank`:t[0]===`enter`&&(o&&!l&&!i&&!c&&(c=r),l=void 0);break;case`linePrefix`:case`listItemValue`:case`listItemMarker`:case`listItemPrefix`:case`listItemPrefixWhitespace`:break;default:l=void 0}if(!i&&t[0]===`enter`&&t[1].type===`listItemPrefix`||i===-1&&t[0]===`exit`&&(t[1].type===`listUnordered`||t[1].type===`listOrdered`)){if(o){let i=r;for(s=void 0;i--;){let t=e[i];if(t[1].type===`lineEnding`||t[1].type===`lineEndingBlank`){if(t[0]===`exit`)continue;s&&(e[s][1].type=`lineEndingBlank`,a=!0),t[1].type=`lineEnding`,s=i}else if(t[1].type!==`linePrefix`&&t[1].type!==`blockQuotePrefix`&&t[1].type!==`blockQuotePrefixWhitespace`&&t[1].type!==`blockQuoteMarker`&&t[1].type!==`listItemIndent`)break}c&&(!s||c<s)&&(o._spread=!0),o.end=Object.assign({},s?e[s][1].start:t[1].end),e.splice(s||r,0,[`exit`,o,t[2]]),r++,n++}if(t[1].type===`listItemPrefix`){let i={type:`listItem`,_spread:!1,start:Object.assign({},t[1].start),end:void 0};o=i,e.splice(r,0,[`enter`,i,t[2]]),r++,n++,c=void 0,l=!0}}}return e[t][1]._spread=a,n}function a(e,t){return n;function n(n){s.call(this,e(n),n),t&&t.call(this,n)}}function o(){this.stack.push({type:`fragment`,children:[]})}function s(e,t,n){this.stack[this.stack.length-1].children.push(e),this.stack.push(e),this.tokenStack.push([t,n||void 0]),e.position={start:xE(t.start),end:void 0}}function c(e){return t;function t(t){e&&e.call(this,t),l.call(this,t)}}function l(e,t){let n=this.stack.pop(),r=this.tokenStack.pop();if(r)r[0].type!==e.type&&(t?t.call(this,e,r[0]):(r[1]||wE).call(this,e,r[0]));else throw Error("Cannot close `"+e.type+"` ("+WS({start:e.start,end:e.end})+`): it’s not open`);n.position.end=xE(e.end)}function u(){return EC(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function f(e){if(this.data.expectingFirstListItemValue){let t=this.stack[this.stack.length-2];t.start=Number.parseInt(this.sliceSerialize(e),10),this.data.expectingFirstListItemValue=void 0}}function p(){let e=this.resume(),t=this.stack[this.stack.length-1];t.lang=e}function m(){let e=this.resume(),t=this.stack[this.stack.length-1];t.meta=e}function h(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function g(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,``),this.data.flowCodeInside=void 0}function _(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e.replace(/(\r?\n|\r)$/g,``)}function v(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=zC(this.sliceSerialize(e)).toLowerCase()}function y(){let e=this.resume(),t=this.stack[this.stack.length-1];t.title=e}function b(){let e=this.resume(),t=this.stack[this.stack.length-1];t.url=e}function x(e){let t=this.stack[this.stack.length-1];t.depth||=this.sliceSerialize(e).length}function S(){this.data.setextHeadingSlurpLineEnding=!0}function C(e){let t=this.stack[this.stack.length-1];t.depth=this.sliceSerialize(e).codePointAt(0)===61?1:2}function w(){this.data.setextHeadingSlurpLineEnding=void 0}function T(e){let t=this.stack[this.stack.length-1].children,n=t[t.length-1];(!n||n.type!==`text`)&&(n=Te(),n.position={start:xE(e.start),end:void 0},t.push(n)),this.stack.push(n)}function E(e){let t=this.stack.pop();t.value+=this.sliceSerialize(e),t.position.end=xE(e.end)}function D(e){let n=this.stack[this.stack.length-1];if(this.data.atHardBreak){let t=n.children[n.children.length-1];t.position.end=xE(e.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(n.type)&&(T.call(this,e),E.call(this,e))}function O(){this.data.atHardBreak=!0}function k(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e}function A(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e}function j(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e}function M(){let e=this.stack[this.stack.length-1];if(this.data.inReference){let t=this.data.referenceType||`shortcut`;e.type+=`Reference`,e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}function N(){let e=this.stack[this.stack.length-1];if(this.data.inReference){let t=this.data.referenceType||`shortcut`;e.type+=`Reference`,e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}function ee(e){let t=this.sliceSerialize(e),n=this.stack[this.stack.length-2];n.label=gE(t),n.identifier=zC(t).toLowerCase()}function te(){let e=this.stack[this.stack.length-1],t=this.resume(),n=this.stack[this.stack.length-1];this.data.inReference=!0,n.type===`link`?n.children=e.children:n.alt=t}function ne(){let e=this.resume(),t=this.stack[this.stack.length-1];t.url=e}function re(){let e=this.resume(),t=this.stack[this.stack.length-1];t.title=e}function ie(){this.data.inReference=void 0}function ae(){this.data.referenceType=`collapsed`}function oe(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=zC(this.sliceSerialize(e)).toLowerCase(),this.data.referenceType=`full`}function se(e){this.data.characterReferenceType=e.type}function ce(e){let t=this.sliceSerialize(e),n=this.data.characterReferenceType,r;n?(r=RC(t,n===`characterReferenceMarkerNumeric`?10:16),this.data.characterReferenceType=void 0):r=jC(t);let i=this.stack[this.stack.length-1];i.value+=r}function le(e){let t=this.stack.pop();t.position.end=xE(e.end)}function ue(e){E.call(this,e);let t=this.stack[this.stack.length-1];t.url=this.sliceSerialize(e)}function de(e){E.call(this,e);let t=this.stack[this.stack.length-1];t.url=`mailto:`+this.sliceSerialize(e)}function P(){return{type:`blockquote`,children:[]}}function fe(){return{type:`code`,lang:null,meta:null,value:``}}function pe(){return{type:`inlineCode`,value:``}}function me(){return{type:`definition`,identifier:``,label:null,title:null,url:``}}function he(){return{type:`emphasis`,children:[]}}function ge(){return{type:`heading`,depth:0,children:[]}}function _e(){return{type:`break`}}function ve(){return{type:`html`,value:``}}function ye(){return{type:`image`,title:null,url:``,alt:null}}function be(){return{type:`link`,title:null,url:``,children:[]}}function xe(e){return{type:`list`,ordered:e.type===`listOrdered`,start:null,spread:e._spread,children:[]}}function Se(e){return{type:`listItem`,spread:e._spread,checked:null,children:[]}}function Ce(){return{type:`paragraph`,children:[]}}function we(){return{type:`strong`,children:[]}}function Te(){return{type:`text`,value:``}}function Ee(){return{type:`thematicBreak`}}}function xE(e){return{line:e.line,column:e.column,offset:e.offset}}function SE(e,t){let n=-1;for(;++n<t.length;){let r=t[n];Array.isArray(r)?SE(e,r):CE(e,r)}}function CE(e,t){let n;for(n in t)if(vE.call(t,n))switch(n){case`canContainEols`:{let r=t[n];r&&e[n].push(...r);break}case`transforms`:{let r=t[n];r&&e[n].push(...r);break}case`enter`:case`exit`:{let r=t[n];r&&Object.assign(e[n],r);break}}}function wE(e,t){throw Error(e?"Cannot close `"+e.type+"` ("+WS({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+WS({start:t.start,end:t.end})+`) is open`:"Cannot close document, a token (`"+t.type+"`, "+WS({start:t.start,end:t.end})+`) is still open`)}function TE(e){let t=this;t.parser=n;function n(n){return yE(n,{...t.data(`settings`),...e,extensions:t.data(`micromarkExtensions`)||[],mdastExtensions:t.data(`fromMarkdownExtensions`)||[]})}}function EE(e,t){let n={type:`element`,tagName:`blockquote`,properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function DE(e,t){let n={type:`element`,tagName:`br`,properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:`text`,value:`
64
- `}]}function OE(e,t){let n=t.value?t.value+`
65
- `:``,r={},i=t.lang?t.lang.split(/\s+/):[];i.length>0&&(r.className=[`language-`+i[0]]);let a={type:`element`,tagName:`code`,properties:r,children:[{type:`text`,value:n}]};return t.meta&&(a.data={meta:t.meta}),e.patch(t,a),a=e.applyData(t,a),a={type:`element`,tagName:`pre`,properties:{},children:[a]},e.patch(t,a),a}function kE(e,t){let n={type:`element`,tagName:`del`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function AE(e,t){let n={type:`element`,tagName:`em`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function jE(e,t){let n=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,r=String(t.identifier).toUpperCase(),i=QC(r.toLowerCase()),a=e.footnoteOrder.indexOf(r),o,s=e.footnoteCounts.get(r);s===void 0?(s=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=a+1,s+=1,e.footnoteCounts.set(r,s);let c={type:`element`,tagName:`a`,properties:{href:`#`+n+`fn-`+i,id:n+`fnref-`+i+(s>1?`-`+s:``),dataFootnoteRef:!0,ariaDescribedBy:[`footnote-label`]},children:[{type:`text`,value:String(o)}]};e.patch(t,c);let l={type:`element`,tagName:`sup`,properties:{},children:[c]};return e.patch(t,l),e.applyData(t,l)}function ME(e,t){let n={type:`element`,tagName:`h`+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function NE(e,t){if(e.options.allowDangerousHtml){let n={type:`raw`,value:t.value};return e.patch(t,n),e.applyData(t,n)}}function PE(e,t){let n=t.referenceType,r=`]`;if(n===`collapsed`?r+=`[]`:n===`full`&&(r+=`[`+(t.label||t.identifier)+`]`),t.type===`imageReference`)return[{type:`text`,value:`![`+t.alt+r}];let i=e.all(t),a=i[0];a&&a.type===`text`?a.value=`[`+a.value:i.unshift({type:`text`,value:`[`});let o=i[i.length-1];return o&&o.type===`text`?o.value+=r:i.push({type:`text`,value:r}),i}function FE(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return PE(e,t);let i={src:QC(r.url||``),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`img`,properties:i,children:[]};return e.patch(t,a),e.applyData(t,a)}function IE(e,t){let n={src:QC(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`img`,properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function LE(e,t){let n={type:`text`,value:t.value.replace(/\r?\n|\r/g,` `)};e.patch(t,n);let r={type:`element`,tagName:`code`,properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function RE(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return PE(e,t);let i={href:QC(r.url||``)};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`a`,properties:i,children:e.all(t)};return e.patch(t,a),e.applyData(t,a)}function zE(e,t){let n={href:QC(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`a`,properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function BE(e,t,n){let r=e.all(t),i=n?VE(n):HE(t),a={},o=[];if(typeof t.checked==`boolean`){let e=r[0],n;e&&e.type===`element`&&e.tagName===`p`?n=e:(n={type:`element`,tagName:`p`,properties:{},children:[]},r.unshift(n)),n.children.length>0&&n.children.unshift({type:`text`,value:` `}),n.children.unshift({type:`element`,tagName:`input`,properties:{type:`checkbox`,checked:t.checked,disabled:!0},children:[]}),a.className=[`task-list-item`]}let s=-1;for(;++s<r.length;){let e=r[s];(i||s!==0||e.type!==`element`||e.tagName!==`p`)&&o.push({type:`text`,value:`
63
+ `;break;case-2:o=t?` `:` `;break;case-1:if(!t&&i)continue;o=` `;break;default:o=String.fromCharCode(a)}i=a===-2,r.push(o)}return r.join(``)}function fE(e){let t={constructs:IC([$T,...(e||{}).extensions||[]]),content:n(tw),defined:[],document:n(rw),flow:n(GT),lazy:{},string:n(JT),text:n(YT)};return t;function n(e){return n;function n(n){return lE(t,e,n)}}}function pE(e){for(;!zw(e););return e}var mE=/[\0\t\n\r]/g;function hE(){let e=1,t=``,n=!0,r;return i;function i(i,a,o){let s=[],c,l,u,d,f;for(i=t+(typeof i==`string`?i.toString():new TextDecoder(a||void 0).decode(i)),u=0,t=``,n&&=(i.charCodeAt(0)===65279&&u++,void 0);u<i.length;){if(mE.lastIndex=u,c=mE.exec(i),d=c&&c.index!==void 0?c.index:i.length,f=i.charCodeAt(d),!c){t=i.slice(u);break}if(f===10&&u===d&&r)s.push(-3),r=void 0;else switch(r&&=(s.push(-5),void 0),u<d&&(s.push(i.slice(u,d)),e+=d-u),f){case 0:s.push(65533),e++;break;case 9:for(l=Math.ceil(e/4)*4,s.push(-2);e++<l;)s.push(-1);break;case 10:s.push(-4),e=1;break;default:r=!0,e=1}u=d+1}return o&&(r&&s.push(-5),t&&s.push(t),s.push(null)),s}}var gE=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function _E(e){return e.replace(gE,vE)}function vE(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){let e=n.charCodeAt(1),t=e===120||e===88;return zC(n.slice(t?2:1),t?16:10)}return MC(n)||e}var yE={}.hasOwnProperty;function bE(e,t,n){return t&&typeof t==`object`&&(n=t,t=void 0),xE(n)(pE(fE(n).document().write(hE()(e,t,!0))))}function xE(e){let t={transforms:[],canContainEols:[`emphasis`,`fragment`,`heading`,`paragraph`,`strong`],enter:{autolink:a(be),autolinkProtocol:T,autolinkEmail:T,atxHeading:a(ge),blockQuote:a(P),characterEscape:T,characterReference:T,codeFenced:a(fe),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:a(fe,o),codeText:a(pe,o),codeTextData:T,data:T,codeFlowValue:T,definition:a(me),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:a(he),hardBreakEscape:a(_e),hardBreakTrailing:a(_e),htmlFlow:a(ve,o),htmlFlowData:T,htmlText:a(ve,o),htmlTextData:T,image:a(ye),label:o,link:a(be),listItem:a(Se),listItemValue:f,listOrdered:a(xe,d),listUnordered:a(xe),paragraph:a(Ce),reference:ae,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:a(ge),strong:a(we),thematicBreak:a(Ee)},exit:{atxHeading:c(),atxHeadingSequence:x,autolink:c(),autolinkEmail:de,autolinkProtocol:ue,blockQuote:c(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:se,characterReferenceMarkerNumeric:se,characterReferenceValue:ce,characterReference:le,codeFenced:c(g),codeFencedFence:h,codeFencedFenceInfo:p,codeFencedFenceMeta:m,codeFlowValue:E,codeIndented:c(_),codeText:c(j),codeTextData:E,data:E,definition:c(),definitionDestinationString:b,definitionLabelString:v,definitionTitleString:y,emphasis:c(),hardBreakEscape:c(O),hardBreakTrailing:c(O),htmlFlow:c(k),htmlFlowData:E,htmlText:c(A),htmlTextData:E,image:c(N),label:te,labelText:ee,lineEnding:D,link:c(M),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:oe,resourceDestinationString:ne,resourceTitleString:re,resource:ie,setextHeading:c(w),setextHeadingLineSequence:C,setextHeadingText:S,strong:c(),thematicBreak:c()}};CE(t,(e||{}).mdastExtensions||[]);let n={};return r;function r(e){let r={type:`root`,children:[]},a={stack:[r],tokenStack:[],config:t,enter:s,exit:l,buffer:o,resume:u,data:n},c=[],d=-1;for(;++d<e.length;)(e[d][1].type===`listOrdered`||e[d][1].type===`listUnordered`)&&(e[d][0]===`enter`?c.push(d):d=i(e,c.pop(),d));for(d=-1;++d<e.length;){let n=t[e[d][0]];yE.call(n,e[d][1].type)&&n[e[d][1].type].call(Object.assign({sliceSerialize:e[d][2].sliceSerialize},a),e[d][1])}if(a.tokenStack.length>0){let e=a.tokenStack[a.tokenStack.length-1];(e[1]||TE).call(a,void 0,e[0])}for(r.position={start:SE(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:SE(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},d=-1;++d<t.transforms.length;)r=t.transforms[d](r)||r;return r}function i(e,t,n){let r=t-1,i=-1,a=!1,o,s,c,l;for(;++r<=n;){let t=e[r];switch(t[1].type){case`listUnordered`:case`listOrdered`:case`blockQuote`:t[0]===`enter`?i++:i--,l=void 0;break;case`lineEndingBlank`:t[0]===`enter`&&(o&&!l&&!i&&!c&&(c=r),l=void 0);break;case`linePrefix`:case`listItemValue`:case`listItemMarker`:case`listItemPrefix`:case`listItemPrefixWhitespace`:break;default:l=void 0}if(!i&&t[0]===`enter`&&t[1].type===`listItemPrefix`||i===-1&&t[0]===`exit`&&(t[1].type===`listUnordered`||t[1].type===`listOrdered`)){if(o){let i=r;for(s=void 0;i--;){let t=e[i];if(t[1].type===`lineEnding`||t[1].type===`lineEndingBlank`){if(t[0]===`exit`)continue;s&&(e[s][1].type=`lineEndingBlank`,a=!0),t[1].type=`lineEnding`,s=i}else if(t[1].type!==`linePrefix`&&t[1].type!==`blockQuotePrefix`&&t[1].type!==`blockQuotePrefixWhitespace`&&t[1].type!==`blockQuoteMarker`&&t[1].type!==`listItemIndent`)break}c&&(!s||c<s)&&(o._spread=!0),o.end=Object.assign({},s?e[s][1].start:t[1].end),e.splice(s||r,0,[`exit`,o,t[2]]),r++,n++}if(t[1].type===`listItemPrefix`){let i={type:`listItem`,_spread:!1,start:Object.assign({},t[1].start),end:void 0};o=i,e.splice(r,0,[`enter`,i,t[2]]),r++,n++,c=void 0,l=!0}}}return e[t][1]._spread=a,n}function a(e,t){return n;function n(n){s.call(this,e(n),n),t&&t.call(this,n)}}function o(){this.stack.push({type:`fragment`,children:[]})}function s(e,t,n){this.stack[this.stack.length-1].children.push(e),this.stack.push(e),this.tokenStack.push([t,n||void 0]),e.position={start:SE(t.start),end:void 0}}function c(e){return t;function t(t){e&&e.call(this,t),l.call(this,t)}}function l(e,t){let n=this.stack.pop(),r=this.tokenStack.pop();if(r)r[0].type!==e.type&&(t?t.call(this,e,r[0]):(r[1]||TE).call(this,e,r[0]));else throw Error("Cannot close `"+e.type+"` ("+GS({start:e.start,end:e.end})+`): it’s not open`);n.position.end=SE(e.end)}function u(){return DC(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function f(e){if(this.data.expectingFirstListItemValue){let t=this.stack[this.stack.length-2];t.start=Number.parseInt(this.sliceSerialize(e),10),this.data.expectingFirstListItemValue=void 0}}function p(){let e=this.resume(),t=this.stack[this.stack.length-1];t.lang=e}function m(){let e=this.resume(),t=this.stack[this.stack.length-1];t.meta=e}function h(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function g(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,``),this.data.flowCodeInside=void 0}function _(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e.replace(/(\r?\n|\r)$/g,``)}function v(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=BC(this.sliceSerialize(e)).toLowerCase()}function y(){let e=this.resume(),t=this.stack[this.stack.length-1];t.title=e}function b(){let e=this.resume(),t=this.stack[this.stack.length-1];t.url=e}function x(e){let t=this.stack[this.stack.length-1];t.depth||=this.sliceSerialize(e).length}function S(){this.data.setextHeadingSlurpLineEnding=!0}function C(e){let t=this.stack[this.stack.length-1];t.depth=this.sliceSerialize(e).codePointAt(0)===61?1:2}function w(){this.data.setextHeadingSlurpLineEnding=void 0}function T(e){let t=this.stack[this.stack.length-1].children,n=t[t.length-1];(!n||n.type!==`text`)&&(n=Te(),n.position={start:SE(e.start),end:void 0},t.push(n)),this.stack.push(n)}function E(e){let t=this.stack.pop();t.value+=this.sliceSerialize(e),t.position.end=SE(e.end)}function D(e){let n=this.stack[this.stack.length-1];if(this.data.atHardBreak){let t=n.children[n.children.length-1];t.position.end=SE(e.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(n.type)&&(T.call(this,e),E.call(this,e))}function O(){this.data.atHardBreak=!0}function k(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e}function A(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e}function j(){let e=this.resume(),t=this.stack[this.stack.length-1];t.value=e}function M(){let e=this.stack[this.stack.length-1];if(this.data.inReference){let t=this.data.referenceType||`shortcut`;e.type+=`Reference`,e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}function N(){let e=this.stack[this.stack.length-1];if(this.data.inReference){let t=this.data.referenceType||`shortcut`;e.type+=`Reference`,e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}function ee(e){let t=this.sliceSerialize(e),n=this.stack[this.stack.length-2];n.label=_E(t),n.identifier=BC(t).toLowerCase()}function te(){let e=this.stack[this.stack.length-1],t=this.resume(),n=this.stack[this.stack.length-1];this.data.inReference=!0,n.type===`link`?n.children=e.children:n.alt=t}function ne(){let e=this.resume(),t=this.stack[this.stack.length-1];t.url=e}function re(){let e=this.resume(),t=this.stack[this.stack.length-1];t.title=e}function ie(){this.data.inReference=void 0}function ae(){this.data.referenceType=`collapsed`}function oe(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=BC(this.sliceSerialize(e)).toLowerCase(),this.data.referenceType=`full`}function se(e){this.data.characterReferenceType=e.type}function ce(e){let t=this.sliceSerialize(e),n=this.data.characterReferenceType,r;n?(r=zC(t,n===`characterReferenceMarkerNumeric`?10:16),this.data.characterReferenceType=void 0):r=MC(t);let i=this.stack[this.stack.length-1];i.value+=r}function le(e){let t=this.stack.pop();t.position.end=SE(e.end)}function ue(e){E.call(this,e);let t=this.stack[this.stack.length-1];t.url=this.sliceSerialize(e)}function de(e){E.call(this,e);let t=this.stack[this.stack.length-1];t.url=`mailto:`+this.sliceSerialize(e)}function P(){return{type:`blockquote`,children:[]}}function fe(){return{type:`code`,lang:null,meta:null,value:``}}function pe(){return{type:`inlineCode`,value:``}}function me(){return{type:`definition`,identifier:``,label:null,title:null,url:``}}function he(){return{type:`emphasis`,children:[]}}function ge(){return{type:`heading`,depth:0,children:[]}}function _e(){return{type:`break`}}function ve(){return{type:`html`,value:``}}function ye(){return{type:`image`,title:null,url:``,alt:null}}function be(){return{type:`link`,title:null,url:``,children:[]}}function xe(e){return{type:`list`,ordered:e.type===`listOrdered`,start:null,spread:e._spread,children:[]}}function Se(e){return{type:`listItem`,spread:e._spread,checked:null,children:[]}}function Ce(){return{type:`paragraph`,children:[]}}function we(){return{type:`strong`,children:[]}}function Te(){return{type:`text`,value:``}}function Ee(){return{type:`thematicBreak`}}}function SE(e){return{line:e.line,column:e.column,offset:e.offset}}function CE(e,t){let n=-1;for(;++n<t.length;){let r=t[n];Array.isArray(r)?CE(e,r):wE(e,r)}}function wE(e,t){let n;for(n in t)if(yE.call(t,n))switch(n){case`canContainEols`:{let r=t[n];r&&e[n].push(...r);break}case`transforms`:{let r=t[n];r&&e[n].push(...r);break}case`enter`:case`exit`:{let r=t[n];r&&Object.assign(e[n],r);break}}}function TE(e,t){throw Error(e?"Cannot close `"+e.type+"` ("+GS({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+GS({start:t.start,end:t.end})+`) is open`:"Cannot close document, a token (`"+t.type+"`, "+GS({start:t.start,end:t.end})+`) is still open`)}function EE(e){let t=this;t.parser=n;function n(n){return bE(n,{...t.data(`settings`),...e,extensions:t.data(`micromarkExtensions`)||[],mdastExtensions:t.data(`fromMarkdownExtensions`)||[]})}}function DE(e,t){let n={type:`element`,tagName:`blockquote`,properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function OE(e,t){let n={type:`element`,tagName:`br`,properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:`text`,value:`
64
+ `}]}function kE(e,t){let n=t.value?t.value+`
65
+ `:``,r={},i=t.lang?t.lang.split(/\s+/):[];i.length>0&&(r.className=[`language-`+i[0]]);let a={type:`element`,tagName:`code`,properties:r,children:[{type:`text`,value:n}]};return t.meta&&(a.data={meta:t.meta}),e.patch(t,a),a=e.applyData(t,a),a={type:`element`,tagName:`pre`,properties:{},children:[a]},e.patch(t,a),a}function AE(e,t){let n={type:`element`,tagName:`del`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function jE(e,t){let n={type:`element`,tagName:`em`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ME(e,t){let n=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,r=String(t.identifier).toUpperCase(),i=$C(r.toLowerCase()),a=e.footnoteOrder.indexOf(r),o,s=e.footnoteCounts.get(r);s===void 0?(s=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=a+1,s+=1,e.footnoteCounts.set(r,s);let c={type:`element`,tagName:`a`,properties:{href:`#`+n+`fn-`+i,id:n+`fnref-`+i+(s>1?`-`+s:``),dataFootnoteRef:!0,ariaDescribedBy:[`footnote-label`]},children:[{type:`text`,value:String(o)}]};e.patch(t,c);let l={type:`element`,tagName:`sup`,properties:{},children:[c]};return e.patch(t,l),e.applyData(t,l)}function NE(e,t){let n={type:`element`,tagName:`h`+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function PE(e,t){if(e.options.allowDangerousHtml){let n={type:`raw`,value:t.value};return e.patch(t,n),e.applyData(t,n)}}function FE(e,t){let n=t.referenceType,r=`]`;if(n===`collapsed`?r+=`[]`:n===`full`&&(r+=`[`+(t.label||t.identifier)+`]`),t.type===`imageReference`)return[{type:`text`,value:`![`+t.alt+r}];let i=e.all(t),a=i[0];a&&a.type===`text`?a.value=`[`+a.value:i.unshift({type:`text`,value:`[`});let o=i[i.length-1];return o&&o.type===`text`?o.value+=r:i.push({type:`text`,value:r}),i}function IE(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return FE(e,t);let i={src:$C(r.url||``),alt:t.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`img`,properties:i,children:[]};return e.patch(t,a),e.applyData(t,a)}function LE(e,t){let n={src:$C(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`img`,properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function RE(e,t){let n={type:`text`,value:t.value.replace(/\r?\n|\r/g,` `)};e.patch(t,n);let r={type:`element`,tagName:`code`,properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function zE(e,t){let n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return FE(e,t);let i={href:$C(r.url||``)};r.title!==null&&r.title!==void 0&&(i.title=r.title);let a={type:`element`,tagName:`a`,properties:i,children:e.all(t)};return e.patch(t,a),e.applyData(t,a)}function BE(e,t){let n={href:$C(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);let r={type:`element`,tagName:`a`,properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function VE(e,t,n){let r=e.all(t),i=n?HE(n):UE(t),a={},o=[];if(typeof t.checked==`boolean`){let e=r[0],n;e&&e.type===`element`&&e.tagName===`p`?n=e:(n={type:`element`,tagName:`p`,properties:{},children:[]},r.unshift(n)),n.children.length>0&&n.children.unshift({type:`text`,value:` `}),n.children.unshift({type:`element`,tagName:`input`,properties:{type:`checkbox`,checked:t.checked,disabled:!0},children:[]}),a.className=[`task-list-item`]}let s=-1;for(;++s<r.length;){let e=r[s];(i||s!==0||e.type!==`element`||e.tagName!==`p`)&&o.push({type:`text`,value:`
66
66
  `}),e.type===`element`&&e.tagName===`p`&&!i?o.push(...e.children):o.push(e)}let c=r[r.length-1];c&&(i||c.type!==`element`||c.tagName!==`p`)&&o.push({type:`text`,value:`
67
- `});let l={type:`element`,tagName:`li`,properties:a,children:o};return e.patch(t,l),e.applyData(t,l)}function VE(e){let t=!1;if(e.type===`list`){t=e.spread||!1;let n=e.children,r=-1;for(;!t&&++r<n.length;)t=HE(n[r])}return t}function HE(e){return e.spread??e.children.length>1}function UE(e,t){let n={},r=e.all(t),i=-1;for(typeof t.start==`number`&&t.start!==1&&(n.start=t.start);++i<r.length;){let e=r[i];if(e.type===`element`&&e.tagName===`li`&&e.properties&&Array.isArray(e.properties.className)&&e.properties.className.includes(`task-list-item`)){n.className=[`contains-task-list`];break}}let a={type:`element`,tagName:t.ordered?`ol`:`ul`,properties:n,children:e.wrap(r,!0)};return e.patch(t,a),e.applyData(t,a)}function WE(e,t){let n={type:`element`,tagName:`p`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function GE(e,t){let n={type:`root`,children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function KE(e,t){let n={type:`element`,tagName:`strong`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function qE(e,t){let n=e.all(t),r=n.shift(),i=[];if(r){let n={type:`element`,tagName:`thead`,properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],n),i.push(n)}if(n.length>0){let r={type:`element`,tagName:`tbody`,properties:{},children:e.wrap(n,!0)},a=VS(t.children[1]),o=BS(t.children[t.children.length-1]);a&&o&&(r.position={start:a,end:o}),i.push(r)}let a={type:`element`,tagName:`table`,properties:{},children:e.wrap(i,!0)};return e.patch(t,a),e.applyData(t,a)}function JE(e,t,n){let r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?`th`:`td`,a=n&&n.type===`table`?n.align:void 0,o=a?a.length:t.children.length,s=-1,c=[];for(;++s<o;){let n=t.children[s],r={},o=a?a[s]:void 0;o&&(r.align=o);let l={type:`element`,tagName:i,properties:r,children:[]};n&&(l.children=e.all(n),e.patch(n,l),l=e.applyData(n,l)),c.push(l)}let l={type:`element`,tagName:`tr`,properties:{},children:e.wrap(c,!0)};return e.patch(t,l),e.applyData(t,l)}function YE(e,t){let n={type:`element`,tagName:`td`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}var XE=9,ZE=32;function QE(e){let t=String(e),n=/\r?\n|\r/g,r=n.exec(t),i=0,a=[];for(;r;)a.push($E(t.slice(i,r.index),i>0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return a.push($E(t.slice(i),i>0,!1)),a.join(``)}function $E(e,t,n){let r=0,i=e.length;if(t){let t=e.codePointAt(r);for(;t===XE||t===ZE;)r++,t=e.codePointAt(r)}if(n){let t=e.codePointAt(i-1);for(;t===XE||t===ZE;)i--,t=e.codePointAt(i-1)}return i>r?e.slice(r,i):``}function eD(e,t){let n={type:`text`,value:QE(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function tD(e,t){let n={type:`element`,tagName:`hr`,properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}var nD={blockquote:EE,break:DE,code:OE,delete:kE,emphasis:AE,footnoteReference:jE,heading:ME,html:NE,imageReference:FE,image:IE,inlineCode:LE,linkReference:RE,link:zE,listItem:BE,list:UE,paragraph:WE,root:GE,strong:KE,table:qE,tableCell:YE,tableRow:JE,text:eD,thematicBreak:tD,toml:rD,yaml:rD,definition:rD,footnoteDefinition:rD};function rD(){}var{defineProperty:iD}=Object,aD=typeof self==`object`?self:globalThis,oD=(e,t)=>{switch(e){case`Function`:case`SharedWorker`:case`Worker`:case`eval`:case`setInterval`:case`setTimeout`:throw TypeError(`unable to deserialize `+e)}return new aD[e](t)},sD=(e,t)=>{let n=(t,n)=>(e.set(n,t),t),r=i=>{if(e.has(i))return e.get(i);let[a,o]=t[i];switch(a){case 0:case-1:return n(o,i);case 1:{let e=n([],i);for(let t of o)e.push(r(t));return e}case 2:{let e=n({},i);for(let[t,n]of o){let i=r(t),a=r(n);i===`__proto__`?iD(e,i,{value:a,configurable:!0,enumerable:!0,writable:!0}):e[i]=a}return e}case 3:return n(new Date(o),i);case 4:{let{source:e,flags:t}=o;return n(new RegExp(e,t),i)}case 5:{let e=n(new Map,i);for(let[t,n]of o)e.set(r(t),r(n));return e}case 6:{let e=n(new Set,i);for(let t of o)e.add(r(t));return e}case 7:{let{name:e,message:t}=o;return n(typeof aD[e]==`function`?oD(e,t):Error(t),i)}case 8:return n(BigInt(o),i);case`BigInt`:return n(Object(BigInt(o)),i);case`ArrayBuffer`:return n(new Uint8Array(o).buffer,o);case`DataView`:{let{buffer:e}=new Uint8Array(o);return n(new DataView(e),o)}case`-0`:return-0}return n(oD(a,o),i)};return r},cD=e=>sD(new Map,e)(0),lD=``,{toString:uD}={},{keys:dD,is:fD}=Object,pD=e=>{let t=typeof e;if(t!==`object`||!e)return[0,t];let n=uD.call(e).slice(8,-1);switch(n){case`Array`:return[1,lD];case`Object`:return[2,lD];case`Date`:return[3,lD];case`RegExp`:return[4,lD];case`Map`:return[5,lD];case`Set`:return[6,lD];case`DataView`:return[1,n]}return n.includes(`Array`)?[1,n]:e instanceof Error?[7,e.name||`Error`]:[2,n]},mD=([e,t])=>e===0&&(t===`function`||t===`symbol`),hD=(e,t,n,r)=>{let i=(e,t)=>{let i=r.push(e)-1;return n.set(t,i),i},a=o=>{if(n.has(o))return n.get(o);let[s,c]=pD(o);switch(s){case 0:{let t=o;switch(c){case`bigint`:s=8,t=o.toString();break;case`number`:if(!o&&fD(o,-0))return r.push([`-0`])-1;break;case`function`:case`symbol`:if(e)throw TypeError(`unable to serialize `+c);t=null;break;case`undefined`:return i([-1],o)}return i([s,t],o)}case 1:{if(c){let e=o;return c===`DataView`?e=new Uint8Array(o.buffer):c===`ArrayBuffer`&&(e=new Uint8Array(o)),i([c,[...e]],o)}let e=[],t=i([s,e],o);for(let t of o)e.push(a(t));return t}case 2:{if(c)switch(c){case`BigInt`:return i([c,o.toString()],o);case`Boolean`:case`Number`:case`String`:return i([c,o.valueOf()],o)}if(t&&`toJSON`in o)return a(o.toJSON());let n=[],r=i([s,n],o);for(let t of dD(o))(e||!mD(pD(o[t])))&&n.push([a(t),a(o[t])]);return r}case 3:return i([s,isNaN(o.getTime())?lD:o.toISOString()],o);case 4:{let{source:e,flags:t}=o;return i([s,{source:e,flags:t}],o)}case 5:{let t=[],n=i([s,t],o);for(let[n,r]of o)(e||!(mD(pD(n))||mD(pD(r))))&&t.push([a(n),a(r)]);return n}case 6:{let t=[],n=i([s,t],o);for(let n of o)(e||!mD(pD(n)))&&t.push(a(n));return n}}let{message:l}=o;return i([s,{name:c,message:l}],o)};return a},gD=(e,{json:t,lossy:n}={})=>{let r=[];return hD(!(t||n),!!t,new Map,r)(e),r},_D=typeof structuredClone==`function`?(e,t)=>t&&(`json`in t||`lossy`in t)?cD(gD(e,t)):structuredClone(e):(e,t)=>cD(gD(e,t));function vD(e,t){let n=[{type:`text`,value:`↩`}];return t>1&&n.push({type:`element`,tagName:`sup`,properties:{},children:[{type:`text`,value:String(t)}]}),n}function yD(e,t){return`Back to reference `+(e+1)+(t>1?`-`+t:``)}function bD(e){let t=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,n=e.options.footnoteBackContent||vD,r=e.options.footnoteBackLabel||yD,i=e.options.footnoteLabel||`Footnotes`,a=e.options.footnoteLabelTagName||`h2`,o=e.options.footnoteLabelProperties||{className:[`sr-only`]},s=[],c=-1;for(;++c<e.footnoteOrder.length;){let i=e.footnoteById.get(e.footnoteOrder[c]);if(!i)continue;let a=e.all(i),o=String(i.identifier).toUpperCase(),l=QC(o.toLowerCase()),u=0,d=[],f=e.footnoteCounts.get(o);for(;f!==void 0&&++u<=f;){d.length>0&&d.push({type:`text`,value:` `});let e=typeof n==`string`?n:n(c,u);typeof e==`string`&&(e={type:`text`,value:e}),d.push({type:`element`,tagName:`a`,properties:{href:`#`+t+`fnref-`+l+(u>1?`-`+u:``),dataFootnoteBackref:``,ariaLabel:typeof r==`string`?r:r(c,u),className:[`data-footnote-backref`]},children:Array.isArray(e)?e:[e]})}let p=a[a.length-1];if(p&&p.type===`element`&&p.tagName===`p`){let e=p.children[p.children.length-1];e&&e.type===`text`?e.value+=` `:p.children.push({type:`text`,value:` `}),p.children.push(...d)}else a.push(...d);let m={type:`element`,tagName:`li`,properties:{id:t+`fn-`+l},children:e.wrap(a,!0)};e.patch(i,m),s.push(m)}if(s.length!==0)return{type:`element`,tagName:`section`,properties:{dataFootnotes:!0,className:[`footnotes`]},children:[{type:`element`,tagName:a,properties:{..._D(o),id:`footnote-label`},children:[{type:`text`,value:i}]},{type:`text`,value:`
67
+ `});let l={type:`element`,tagName:`li`,properties:a,children:o};return e.patch(t,l),e.applyData(t,l)}function HE(e){let t=!1;if(e.type===`list`){t=e.spread||!1;let n=e.children,r=-1;for(;!t&&++r<n.length;)t=UE(n[r])}return t}function UE(e){return e.spread??e.children.length>1}function WE(e,t){let n={},r=e.all(t),i=-1;for(typeof t.start==`number`&&t.start!==1&&(n.start=t.start);++i<r.length;){let e=r[i];if(e.type===`element`&&e.tagName===`li`&&e.properties&&Array.isArray(e.properties.className)&&e.properties.className.includes(`task-list-item`)){n.className=[`contains-task-list`];break}}let a={type:`element`,tagName:t.ordered?`ol`:`ul`,properties:n,children:e.wrap(r,!0)};return e.patch(t,a),e.applyData(t,a)}function GE(e,t){let n={type:`element`,tagName:`p`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function KE(e,t){let n={type:`root`,children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function qE(e,t){let n={type:`element`,tagName:`strong`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function JE(e,t){let n=e.all(t),r=n.shift(),i=[];if(r){let n={type:`element`,tagName:`thead`,properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],n),i.push(n)}if(n.length>0){let r={type:`element`,tagName:`tbody`,properties:{},children:e.wrap(n,!0)},a=HS(t.children[1]),o=VS(t.children[t.children.length-1]);a&&o&&(r.position={start:a,end:o}),i.push(r)}let a={type:`element`,tagName:`table`,properties:{},children:e.wrap(i,!0)};return e.patch(t,a),e.applyData(t,a)}function YE(e,t,n){let r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?`th`:`td`,a=n&&n.type===`table`?n.align:void 0,o=a?a.length:t.children.length,s=-1,c=[];for(;++s<o;){let n=t.children[s],r={},o=a?a[s]:void 0;o&&(r.align=o);let l={type:`element`,tagName:i,properties:r,children:[]};n&&(l.children=e.all(n),e.patch(n,l),l=e.applyData(n,l)),c.push(l)}let l={type:`element`,tagName:`tr`,properties:{},children:e.wrap(c,!0)};return e.patch(t,l),e.applyData(t,l)}function XE(e,t){let n={type:`element`,tagName:`td`,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}var ZE=9,QE=32;function $E(e){let t=String(e),n=/\r?\n|\r/g,r=n.exec(t),i=0,a=[];for(;r;)a.push(eD(t.slice(i,r.index),i>0,!0),r[0]),i=r.index+r[0].length,r=n.exec(t);return a.push(eD(t.slice(i),i>0,!1)),a.join(``)}function eD(e,t,n){let r=0,i=e.length;if(t){let t=e.codePointAt(r);for(;t===ZE||t===QE;)r++,t=e.codePointAt(r)}if(n){let t=e.codePointAt(i-1);for(;t===ZE||t===QE;)i--,t=e.codePointAt(i-1)}return i>r?e.slice(r,i):``}function tD(e,t){let n={type:`text`,value:$E(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function nD(e,t){let n={type:`element`,tagName:`hr`,properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}var rD={blockquote:DE,break:OE,code:kE,delete:AE,emphasis:jE,footnoteReference:ME,heading:NE,html:PE,imageReference:IE,image:LE,inlineCode:RE,linkReference:zE,link:BE,listItem:VE,list:WE,paragraph:GE,root:KE,strong:qE,table:JE,tableCell:XE,tableRow:YE,text:tD,thematicBreak:nD,toml:iD,yaml:iD,definition:iD,footnoteDefinition:iD};function iD(){}var{defineProperty:aD}=Object,oD=typeof self==`object`?self:globalThis,sD=(e,t)=>{switch(e){case`Function`:case`SharedWorker`:case`Worker`:case`eval`:case`setInterval`:case`setTimeout`:throw TypeError(`unable to deserialize `+e)}return new oD[e](t)},cD=(e,t)=>{let n=(t,n)=>(e.set(n,t),t),r=i=>{if(e.has(i))return e.get(i);let[a,o]=t[i];switch(a){case 0:case-1:return n(o,i);case 1:{let e=n([],i);for(let t of o)e.push(r(t));return e}case 2:{let e=n({},i);for(let[t,n]of o){let i=r(t),a=r(n);i===`__proto__`?aD(e,i,{value:a,configurable:!0,enumerable:!0,writable:!0}):e[i]=a}return e}case 3:return n(new Date(o),i);case 4:{let{source:e,flags:t}=o;return n(new RegExp(e,t),i)}case 5:{let e=n(new Map,i);for(let[t,n]of o)e.set(r(t),r(n));return e}case 6:{let e=n(new Set,i);for(let t of o)e.add(r(t));return e}case 7:{let{name:e,message:t}=o;return n(typeof oD[e]==`function`?sD(e,t):Error(t),i)}case 8:return n(BigInt(o),i);case`BigInt`:return n(Object(BigInt(o)),i);case`ArrayBuffer`:return n(new Uint8Array(o).buffer,o);case`DataView`:{let{buffer:e}=new Uint8Array(o);return n(new DataView(e),o)}case`-0`:return-0}return n(sD(a,o),i)};return r},lD=e=>cD(new Map,e)(0),uD=``,{toString:dD}={},{keys:fD,is:pD}=Object,mD=e=>{let t=typeof e;if(t!==`object`||!e)return[0,t];let n=dD.call(e).slice(8,-1);switch(n){case`Array`:return[1,uD];case`Object`:return[2,uD];case`Date`:return[3,uD];case`RegExp`:return[4,uD];case`Map`:return[5,uD];case`Set`:return[6,uD];case`DataView`:return[1,n]}return n.includes(`Array`)?[1,n]:e instanceof Error?[7,e.name||`Error`]:[2,n]},hD=([e,t])=>e===0&&(t===`function`||t===`symbol`),gD=(e,t,n,r)=>{let i=(e,t)=>{let i=r.push(e)-1;return n.set(t,i),i},a=o=>{if(n.has(o))return n.get(o);let[s,c]=mD(o);switch(s){case 0:{let t=o;switch(c){case`bigint`:s=8,t=o.toString();break;case`number`:if(!o&&pD(o,-0))return r.push([`-0`])-1;break;case`function`:case`symbol`:if(e)throw TypeError(`unable to serialize `+c);t=null;break;case`undefined`:return i([-1],o)}return i([s,t],o)}case 1:{if(c){let e=o;return c===`DataView`?e=new Uint8Array(o.buffer):c===`ArrayBuffer`&&(e=new Uint8Array(o)),i([c,[...e]],o)}let e=[],t=i([s,e],o);for(let t of o)e.push(a(t));return t}case 2:{if(c)switch(c){case`BigInt`:return i([c,o.toString()],o);case`Boolean`:case`Number`:case`String`:return i([c,o.valueOf()],o)}if(t&&`toJSON`in o)return a(o.toJSON());let n=[],r=i([s,n],o);for(let t of fD(o))(e||!hD(mD(o[t])))&&n.push([a(t),a(o[t])]);return r}case 3:return i([s,isNaN(o.getTime())?uD:o.toISOString()],o);case 4:{let{source:e,flags:t}=o;return i([s,{source:e,flags:t}],o)}case 5:{let t=[],n=i([s,t],o);for(let[n,r]of o)(e||!(hD(mD(n))||hD(mD(r))))&&t.push([a(n),a(r)]);return n}case 6:{let t=[],n=i([s,t],o);for(let n of o)(e||!hD(mD(n)))&&t.push(a(n));return n}}let{message:l}=o;return i([s,{name:c,message:l}],o)};return a},_D=(e,{json:t,lossy:n}={})=>{let r=[];return gD(!(t||n),!!t,new Map,r)(e),r},vD=typeof structuredClone==`function`?(e,t)=>t&&(`json`in t||`lossy`in t)?lD(_D(e,t)):structuredClone(e):(e,t)=>lD(_D(e,t));function yD(e,t){let n=[{type:`text`,value:`↩`}];return t>1&&n.push({type:`element`,tagName:`sup`,properties:{},children:[{type:`text`,value:String(t)}]}),n}function bD(e,t){return`Back to reference `+(e+1)+(t>1?`-`+t:``)}function xD(e){let t=typeof e.options.clobberPrefix==`string`?e.options.clobberPrefix:`user-content-`,n=e.options.footnoteBackContent||yD,r=e.options.footnoteBackLabel||bD,i=e.options.footnoteLabel||`Footnotes`,a=e.options.footnoteLabelTagName||`h2`,o=e.options.footnoteLabelProperties||{className:[`sr-only`]},s=[],c=-1;for(;++c<e.footnoteOrder.length;){let i=e.footnoteById.get(e.footnoteOrder[c]);if(!i)continue;let a=e.all(i),o=String(i.identifier).toUpperCase(),l=$C(o.toLowerCase()),u=0,d=[],f=e.footnoteCounts.get(o);for(;f!==void 0&&++u<=f;){d.length>0&&d.push({type:`text`,value:` `});let e=typeof n==`string`?n:n(c,u);typeof e==`string`&&(e={type:`text`,value:e}),d.push({type:`element`,tagName:`a`,properties:{href:`#`+t+`fnref-`+l+(u>1?`-`+u:``),dataFootnoteBackref:``,ariaLabel:typeof r==`string`?r:r(c,u),className:[`data-footnote-backref`]},children:Array.isArray(e)?e:[e]})}let p=a[a.length-1];if(p&&p.type===`element`&&p.tagName===`p`){let e=p.children[p.children.length-1];e&&e.type===`text`?e.value+=` `:p.children.push({type:`text`,value:` `}),p.children.push(...d)}else a.push(...d);let m={type:`element`,tagName:`li`,properties:{id:t+`fn-`+l},children:e.wrap(a,!0)};e.patch(i,m),s.push(m)}if(s.length!==0)return{type:`element`,tagName:`section`,properties:{dataFootnotes:!0,className:[`footnotes`]},children:[{type:`element`,tagName:a,properties:{...vD(o),id:`footnote-label`},children:[{type:`text`,value:i}]},{type:`text`,value:`
68
68
  `},{type:`element`,tagName:`ol`,properties:{},children:e.wrap(s,!0)},{type:`text`,value:`
69
- `}]}}var xD=(function(e){if(e==null)return ED;if(typeof e==`function`)return TD(e);if(typeof e==`object`)return Array.isArray(e)?SD(e):CD(e);if(typeof e==`string`)return wD(e);throw Error(`Expected function, string, or object as test`)});function SD(e){let t=[],n=-1;for(;++n<e.length;)t[n]=xD(e[n]);return TD(r);function r(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function CD(e){let t=e;return TD(n);function n(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function wD(e){return TD(t);function t(t){return t&&t.type===e}}function TD(e){return t;function t(t,n,r){return!!(DD(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function ED(){return!0}function DD(e){return typeof e==`object`&&!!e&&`type`in e}function OD(e){return e}var kD=[];function AD(e,t,n,r){let i;typeof t==`function`&&typeof n!=`function`?(r=n,n=t):i=t;let a=xD(i),o=r?-1:1;s(e,void 0,[])();function s(e,i,c){let l=e&&typeof e==`object`?e:{};if(typeof l.type==`string`){let t=typeof l.tagName==`string`?l.tagName:typeof l.name==`string`?l.name:void 0;Object.defineProperty(u,"name",{value:`node (`+OD(e.type+(t?`<`+t+`>`:``))+`)`})}return u;function u(){let l=kD,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=jD(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d<t.children.length;){let e=t.children[d];if(u=s(e,d,f)(),u[0]===!1)return u;d=typeof u[1]==`number`?u[1]:d+o}}return l}}}function jD(e){return Array.isArray(e)?e:typeof e==`number`?[!0,e]:e==null?kD:[e]}function MD(e,t,n,r){let i,a,o;typeof t==`function`&&typeof n!=`function`?(a=void 0,o=t,i=n):(a=t,o=n,i=r),AD(e,a,s,i);function s(e,t){let n=t[t.length-1],r=n?n.children.indexOf(e):void 0;return o(e,r,n)}}var ND={}.hasOwnProperty,PD={};function FD(e,t){let n=t||PD,r=new Map,i=new Map,a={all:s,applyData:LD,definitionById:r,footnoteById:i,footnoteCounts:new Map,footnoteOrder:[],handlers:{...nD,...n.handlers},one:o,options:n,patch:ID,wrap:zD};return MD(e,function(e){if(e.type===`definition`||e.type===`footnoteDefinition`){let t=e.type===`definition`?r:i,n=String(e.identifier).toUpperCase();t.has(n)||t.set(n,e)}}),a;function o(e,t){let n=e.type,r=a.handlers[n];if(ND.call(a.handlers,n)&&r)return r(a,e,t);if(a.options.passThrough&&a.options.passThrough.includes(n)){if(`children`in e){let{children:t,...n}=e,r=_D(n);return r.children=a.all(e),r}return _D(e)}return(a.options.unknownHandler||RD)(a,e,t)}function s(e){let t=[];if(`children`in e){let n=e.children,r=-1;for(;++r<n.length;){let i=a.one(n[r],e);if(i){if(r&&n[r-1].type===`break`&&(!Array.isArray(i)&&i.type===`text`&&(i.value=BD(i.value)),!Array.isArray(i)&&i.type===`element`)){let e=i.children[0];e&&e.type===`text`&&(e.value=BD(e.value))}Array.isArray(i)?t.push(...i):t.push(i)}}}return t}}function ID(e,t){e.position&&(t.position=US(e))}function LD(e,t){let n=t;if(e&&e.data){let t=e.data.hName,r=e.data.hChildren,i=e.data.hProperties;typeof t==`string`&&(n.type===`element`?n.tagName=t:n={type:`element`,tagName:t,properties:{},children:`children`in n?n.children:[n]}),n.type===`element`&&i&&Object.assign(n.properties,_D(i)),`children`in n&&n.children&&r!=null&&(n.children=r)}return n}function RD(e,t){let n=t.data||{},r=`value`in t&&!(ND.call(n,`hProperties`)||ND.call(n,`hChildren`))?{type:`text`,value:t.value}:{type:`element`,tagName:`div`,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function zD(e,t){let n=[],r=-1;for(t&&n.push({type:`text`,value:`
69
+ `}]}}var SD=(function(e){if(e==null)return DD;if(typeof e==`function`)return ED(e);if(typeof e==`object`)return Array.isArray(e)?CD(e):wD(e);if(typeof e==`string`)return TD(e);throw Error(`Expected function, string, or object as test`)});function CD(e){let t=[],n=-1;for(;++n<e.length;)t[n]=SD(e[n]);return ED(r);function r(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function wD(e){let t=e;return ED(n);function n(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function TD(e){return ED(t);function t(t){return t&&t.type===e}}function ED(e){return t;function t(t,n,r){return!!(OD(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function DD(){return!0}function OD(e){return typeof e==`object`&&!!e&&`type`in e}function kD(e){return e}var AD=[];function jD(e,t,n,r){let i;typeof t==`function`&&typeof n!=`function`?(r=n,n=t):i=t;let a=SD(i),o=r?-1:1;s(e,void 0,[])();function s(e,i,c){let l=e&&typeof e==`object`?e:{};if(typeof l.type==`string`){let t=typeof l.tagName==`string`?l.tagName:typeof l.name==`string`?l.name:void 0;Object.defineProperty(u,"name",{value:`node (`+kD(e.type+(t?`<`+t+`>`:``))+`)`})}return u;function u(){let l=AD,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=MD(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d<t.children.length;){let e=t.children[d];if(u=s(e,d,f)(),u[0]===!1)return u;d=typeof u[1]==`number`?u[1]:d+o}}return l}}}function MD(e){return Array.isArray(e)?e:typeof e==`number`?[!0,e]:e==null?AD:[e]}function ND(e,t,n,r){let i,a,o;typeof t==`function`&&typeof n!=`function`?(a=void 0,o=t,i=n):(a=t,o=n,i=r),jD(e,a,s,i);function s(e,t){let n=t[t.length-1],r=n?n.children.indexOf(e):void 0;return o(e,r,n)}}var PD={}.hasOwnProperty,FD={};function ID(e,t){let n=t||FD,r=new Map,i=new Map,a={all:s,applyData:RD,definitionById:r,footnoteById:i,footnoteCounts:new Map,footnoteOrder:[],handlers:{...rD,...n.handlers},one:o,options:n,patch:LD,wrap:BD};return ND(e,function(e){if(e.type===`definition`||e.type===`footnoteDefinition`){let t=e.type===`definition`?r:i,n=String(e.identifier).toUpperCase();t.has(n)||t.set(n,e)}}),a;function o(e,t){let n=e.type,r=a.handlers[n];if(PD.call(a.handlers,n)&&r)return r(a,e,t);if(a.options.passThrough&&a.options.passThrough.includes(n)){if(`children`in e){let{children:t,...n}=e,r=vD(n);return r.children=a.all(e),r}return vD(e)}return(a.options.unknownHandler||zD)(a,e,t)}function s(e){let t=[];if(`children`in e){let n=e.children,r=-1;for(;++r<n.length;){let i=a.one(n[r],e);if(i){if(r&&n[r-1].type===`break`&&(!Array.isArray(i)&&i.type===`text`&&(i.value=VD(i.value)),!Array.isArray(i)&&i.type===`element`)){let e=i.children[0];e&&e.type===`text`&&(e.value=VD(e.value))}Array.isArray(i)?t.push(...i):t.push(i)}}}return t}}function LD(e,t){e.position&&(t.position=WS(e))}function RD(e,t){let n=t;if(e&&e.data){let t=e.data.hName,r=e.data.hChildren,i=e.data.hProperties;typeof t==`string`&&(n.type===`element`?n.tagName=t:n={type:`element`,tagName:t,properties:{},children:`children`in n?n.children:[n]}),n.type===`element`&&i&&Object.assign(n.properties,vD(i)),`children`in n&&n.children&&r!=null&&(n.children=r)}return n}function zD(e,t){let n=t.data||{},r=`value`in t&&!(PD.call(n,`hProperties`)||PD.call(n,`hChildren`))?{type:`text`,value:t.value}:{type:`element`,tagName:`div`,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function BD(e,t){let n=[],r=-1;for(t&&n.push({type:`text`,value:`
70
70
  `});++r<e.length;)r&&n.push({type:`text`,value:`
71
71
  `}),n.push(e[r]);return t&&e.length>0&&n.push({type:`text`,value:`
72
- `}),n}function BD(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function VD(e,t){let n=FD(e,t),r=n.one(e,void 0),i=bD(n),a=Array.isArray(r)?{type:`root`,children:r}:r||{type:`root`,children:[]};return i&&(`children`in a,a.children.push({type:`text`,value:`
73
- `},i)),a}function HD(e,t){return e&&`run`in e?async function(n,r){let i=VD(n,{file:r,...t});await e.run(i,r)}:function(n,r){return VD(n,{file:r,...e||t})}}function UD(e){if(e)throw e}var WD=r(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});f<p;++f)if(t=arguments[f],t!=null)for(n in t)r=l(d,n),i=l(t,n),d!==i&&(m&&i&&(s(i)||(a=o(i)))?(a?(a=!1,u=r&&o(r)?r:[]):u=r&&s(r)?r:{},c(d,{name:n,newValue:e(m,u,i)})):i!==void 0&&c(d,{name:n,newValue:i}));return d}}));function GD(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function KD(){let e=[],t={run:n,use:r};return t;function n(...t){let n=-1,r=t.pop();if(typeof r!=`function`)throw TypeError(`Expected function as last argument, not `+r);i(null,...t);function i(a,...o){let s=e[++n],c=-1;if(a){r(a);return}for(;++c<t.length;)(o[c]===null||o[c]===void 0)&&(o[c]=t[c]);t=o,s?qD(s,i)(...o):r(null,...o)}}function r(n){if(typeof n!=`function`)throw TypeError("Expected `middelware` to be a function, not "+n);return e.push(n),t}}function qD(e,t){let n;return r;function r(...t){let r=e.length>t.length,o;r&&t.push(i);try{o=e.apply(this,t)}catch(e){let t=e;if(r&&n)throw t;return i(t)}r||(o&&o.then&&typeof o.then==`function`?o.then(a,i):o instanceof Error?i(o):a(o))}function i(e,...r){n||(n=!0,t(e,...r))}function a(e){i(null,e)}}var JD={basename:YD,dirname:XD,extname:ZD,join:QD,sep:`/`};function YD(e,t){if(t!==void 0&&typeof t!=`string`)throw TypeError(`"ext" argument must be a string`);tO(e);let n=0,r=-1,i=e.length,a;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else r<0&&(a=!0,r=i+1);return r<0?``:e.slice(n,r)}if(t===e)return``;let o=-1,s=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else o<0&&(a=!0,o=i+1),s>-1&&(e.codePointAt(i)===t.codePointAt(s--)?s<0&&(r=i):(s=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function XD(e){if(tO(e),e.length===0)return`.`;let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||=!0;return t<0?e.codePointAt(0)===47?`/`:`.`:t===1&&e.codePointAt(0)===47?`//`:e.slice(0,t)}function ZD(e){tO(e);let t=e.length,n=-1,r=0,i=-1,a=0,o;for(;t--;){let s=e.codePointAt(t);if(s===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),s===46?i<0?i=t:a!==1&&(a=1):i>-1&&(a=-1)}return i<0||n<0||a===0||a===1&&i===n-1&&i===r+1?``:e.slice(i,n)}function QD(...e){let t=-1,n;for(;++t<e.length;)tO(e[t]),e[t]&&(n=n===void 0?e[t]:n+`/`+e[t]);return n===void 0?`.`:$D(n)}function $D(e){tO(e);let t=e.codePointAt(0)===47,n=eO(e,!t);return n.length===0&&!t&&(n=`.`),n.length>0&&e.codePointAt(e.length-1)===47&&(n+=`/`),t?`/`+n:n}function eO(e,t){let n=``,r=0,i=-1,a=0,o=-1,s,c;for(;++o<=e.length;){if(o<e.length)s=e.codePointAt(o);else if(s===47)break;else s=47;if(s===47){if(i!==o-1&&a!==1){if(i!==o-1&&a===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf(`/`),c!==n.length-1){c<0?(n=``,r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf(`/`)),i=o,a=0;continue}}else if(n.length>0){n=``,r=0,i=o,a=0;continue}}t&&(n=n.length>0?n+`/..`:`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1}i=o,a=0}else s===46&&a>-1?a++:a=-1}return n}function tO(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received `+JSON.stringify(e))}var nO={cwd:rO};function rO(){return`/`}function iO(e){return!!(typeof e==`object`&&e&&`href`in e&&e.href&&`protocol`in e&&e.protocol&&e.auth===void 0)}function aO(e){if(typeof e==`string`)e=new URL(e);else if(!iO(e)){let t=TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code=`ERR_INVALID_ARG_TYPE`,t}if(e.protocol!==`file:`){let e=TypeError(`The URL must be of scheme file`);throw e.code=`ERR_INVALID_URL_SCHEME`,e}return oO(e)}function oO(e){if(e.hostname!==``){let e=TypeError(`File URL host must be "localhost" or empty on darwin`);throw e.code=`ERR_INVALID_FILE_URL_HOST`,e}let t=e.pathname,n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){let e=t.codePointAt(n+2);if(e===70||e===102){let e=TypeError(`File URL path must not include encoded / characters`);throw e.code=`ERR_INVALID_FILE_URL_PATH`,e}}return decodeURIComponent(t)}var sO=[`history`,`path`,`basename`,`stem`,`extname`,`dirname`],cO=class{constructor(e){let t;t=e?iO(e)?{path:e}:typeof e==`string`||fO(e)?{value:e}:e:{},this.cwd=`cwd`in t?``:nO.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<sO.length;){let e=sO[n];e in t&&t[e]!==void 0&&t[e]!==null&&(this[e]=e===`history`?[...t[e]]:t[e])}let r;for(r in t)sO.includes(r)||(this[r]=t[r])}get basename(){return typeof this.path==`string`?JD.basename(this.path):void 0}set basename(e){uO(e,`basename`),lO(e,`basename`),this.path=JD.join(this.dirname||``,e)}get dirname(){return typeof this.path==`string`?JD.dirname(this.path):void 0}set dirname(e){dO(this.basename,`dirname`),this.path=JD.join(e||``,this.basename)}get extname(){return typeof this.path==`string`?JD.extname(this.path):void 0}set extname(e){if(lO(e,`extname`),dO(this.dirname,`extname`),e){if(e.codePointAt(0)!==46)throw Error("`extname` must start with `.`");if(e.includes(`.`,1))throw Error("`extname` cannot contain multiple dots")}this.path=JD.join(this.dirname,this.stem+(e||``))}get path(){return this.history[this.history.length-1]}set path(e){iO(e)&&(e=aO(e)),uO(e,`path`),this.path!==e&&this.history.push(e)}get stem(){return typeof this.path==`string`?JD.basename(this.path,this.extname):void 0}set stem(e){uO(e,`stem`),lO(e,`stem`),this.path=JD.join(this.dirname||``,e+(this.extname||``))}fail(e,t,n){let r=this.message(e,t,n);throw r.fatal=!0,r}info(e,t,n){let r=this.message(e,t,n);return r.fatal=void 0,r}message(e,t,n){let r=new JS(e,t,n);return this.path&&(r.name=this.path+`:`+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(e){return this.value===void 0?``:typeof this.value==`string`?this.value:new TextDecoder(e||void 0).decode(this.value)}};function lO(e,t){if(e&&e.includes(JD.sep))throw Error("`"+t+"` cannot be a path: did not expect `"+JD.sep+"`")}function uO(e,t){if(!e)throw Error("`"+t+"` cannot be empty")}function dO(e,t){if(!e)throw Error("Setting `"+t+"` requires `path` to be set too")}function fO(e){return!!(e&&typeof e==`object`&&`byteLength`in e&&`byteOffset`in e)}var pO=(function(e){let t=this.constructor.prototype,n=t[e],r=function(){return n.apply(r,arguments)};return Object.setPrototypeOf(r,t),r}),mO=n(WD(),1),hO={}.hasOwnProperty,gO=new class e extends pO{constructor(){super(`copy`),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=KD()}copy(){let t=new e,n=-1;for(;++n<this.attachers.length;){let e=this.attachers[n];t.use(...e)}return t.data((0,mO.default)(!0,{},this.namespace)),t}data(e,t){return typeof e==`string`?arguments.length===2?(yO(`data`,this.frozen),this.namespace[e]=t,this):hO.call(this.namespace,e)&&this.namespace[e]||void 0:e?(yO(`data`,this.frozen),this.namespace=e,this):this.namespace}freeze(){if(this.frozen)return this;let e=this;for(;++this.freezeIndex<this.attachers.length;){let[t,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);let r=t.call(e,...n);typeof r==`function`&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=1/0,this}parse(e){this.freeze();let t=SO(e),n=this.parser||this.Parser;return _O(`parse`,n),n(String(t),t)}process(e,t){let n=this;return this.freeze(),_O(`process`,this.parser||this.Parser),vO(`process`,this.compiler||this.Compiler),t?r(void 0,t):new Promise(r);function r(r,i){let a=SO(e),o=n.parse(a);n.run(o,a,function(e,t,r){if(e||!t||!r)return s(e);let i=t,a=n.stringify(i,r);wO(a)?r.value=a:r.result=a,s(e,r)});function s(e,n){e||!n?i(e):r?r(n):t(void 0,n)}}}processSync(e){let t=!1,n;return this.freeze(),_O(`processSync`,this.parser||this.Parser),vO(`processSync`,this.compiler||this.Compiler),this.process(e,r),xO(`processSync`,`process`,t),n;function r(e,r){t=!0,UD(e),n=r}}run(e,t,n){bO(e),this.freeze();let r=this.transformers;return!n&&typeof t==`function`&&(n=t,t=void 0),n?i(void 0,n):new Promise(i);function i(i,a){let o=SO(t);r.run(e,o,s);function s(t,r,o){let s=r||e;t?a(t):i?i(s):n(void 0,s,o)}}}runSync(e,t){let n=!1,r;return this.run(e,t,i),xO(`runSync`,`run`,n),r;function i(e,t){UD(e),r=t,n=!0}}stringify(e,t){this.freeze();let n=SO(t),r=this.compiler||this.Compiler;return vO(`stringify`,r),bO(e),r(e,n)}use(e,...t){let n=this.attachers,r=this.namespace;if(yO(`use`,this.frozen),e!=null){if(typeof e==`function`)s(e,t);else if(typeof e==`object`)Array.isArray(e)?o(e):a(e);else throw TypeError("Expected usable value, not `"+e+"`")}return this;function i(e){if(typeof e==`function`)s(e,[]);else if(typeof e==`object`){if(Array.isArray(e)){let[t,...n]=e;s(t,n)}else a(e)}else throw TypeError("Expected usable value, not `"+e+"`")}function a(e){if(!(`plugins`in e)&&!(`settings`in e))throw Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(e.plugins),e.settings&&(r.settings=(0,mO.default)(!0,r.settings,e.settings))}function o(e){let t=-1;if(e!=null){if(Array.isArray(e))for(;++t<e.length;){let n=e[t];i(n)}else throw TypeError("Expected a list of plugins, not `"+e+"`")}}function s(e,t){let r=-1,i=-1;for(;++r<n.length;)if(n[r][0]===e){i=r;break}if(i===-1)n.push([e,...t]);else if(t.length>0){let[r,...a]=t,o=n[i][1];GD(o)&&GD(r)&&(r=(0,mO.default)(!0,o,r)),n[i]=[e,r,...a]}}}}().freeze();function _O(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `parser`")}function vO(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `compiler`")}function yO(e,t){if(t)throw Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function bO(e){if(!GD(e)||typeof e.type!=`string`)throw TypeError("Expected node, got `"+e+"`")}function xO(e,t,n){if(!n)throw Error("`"+e+"` finished async. Use `"+t+"` instead")}function SO(e){return CO(e)?e:new cO(e)}function CO(e){return!!(e&&typeof e==`object`&&`message`in e&&`messages`in e)}function wO(e){return typeof e==`string`||TO(e)}function TO(e){return!!(e&&typeof e==`object`&&`byteLength`in e&&`byteOffset`in e)}var EO=[],DO={allowDangerousHtml:!0},OO=/^(https?|ircs?|mailto|xmpp)$/i,kO=[{from:`astPlugins`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowDangerousHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowNode`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowElement`},{from:`allowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowedElements`},{from:`className`,id:`remove-classname`},{from:`disallowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`disallowedElements`},{from:`escapeHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`includeElementIndex`,id:`#remove-includeelementindex`},{from:`includeNodeIndex`,id:`change-includenodeindex-to-includeelementindex`},{from:`linkTarget`,id:`remove-linktarget`},{from:`plugins`,id:`change-plugins-to-remarkplugins`,to:`remarkPlugins`},{from:`rawSourcePos`,id:`#remove-rawsourcepos`},{from:`renderers`,id:`change-renderers-to-components`,to:`components`},{from:`source`,id:`change-source-to-children`,to:`children`},{from:`sourcePos`,id:`#remove-sourcepos`},{from:`transformImageUri`,id:`#add-urltransform`,to:`urlTransform`},{from:`transformLinkUri`,id:`#add-urltransform`,to:`urlTransform`}];function AO(e){let t=jO(e),n=MO(e);return NO(t.runSync(t.parse(n),n),e)}function jO(e){let t=e.rehypePlugins||EO,n=e.remarkPlugins||EO,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...DO}:DO;return gO().use(TE).use(n).use(HD,r).use(t)}function MO(e){let t=e.children||``,n=new cO;return typeof t==`string`?n.value=t:``+t,n}function NO(e,t){let n=t.allowedElements,r=t.allowElement,i=t.components,a=t.disallowedElements,o=t.skipHtml,s=t.unwrapDisallowed,c=t.urlTransform||PO;for(let e of kO)Object.hasOwn(t,e.from)&&``+e.from+(e.to?"use `"+e.to+"` instead":`remove it`)+e.id;return MD(e,l),nC(e,{Fragment:b.Fragment,components:i,ignoreInvalidStyle:!0,jsx:b.jsx,jsxs:b.jsxs,passKeys:!0,passNode:!0});function l(e,t,i){if(e.type===`raw`&&i&&typeof t==`number`)return o?i.children.splice(t,1):i.children[t]={type:`text`,value:e.value},t;if(e.type===`element`){let t;for(t in wC)if(Object.hasOwn(wC,t)&&Object.hasOwn(e.properties,t)){let n=e.properties[t],r=wC[t];(r===null||r.includes(e.tagName))&&(e.properties[t]=c(String(n||``),t,e))}}if(e.type===`element`){let o=n?!n.includes(e.tagName):a?a.includes(e.tagName):!1;if(!o&&r&&typeof t==`number`&&(o=!r(e,t,i)),o&&i&&typeof t==`number`)return s&&e.children?i.children.splice(t,1,...e.children):i.children.splice(t,1),t}}}function PO(e){let t=e.indexOf(`:`),n=e.indexOf(`?`),r=e.indexOf(`#`),i=e.indexOf(`/`);return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||OO.test(e.slice(0,t))?e:``}function FO(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function IO(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function LO(e,t,n){let r=xD((n||{}).ignore||[]),i=RO(t),a=-1;for(;++a<i.length;)AD(e,`text`,o);function o(e,t){let n=-1,i;for(;++n<t.length;){let e=t[n],a=i?i.children:void 0;if(r(e,a?a.indexOf(e):void 0,i))return;i=e}if(i)return s(e,t)}function s(e,t){let n=t[t.length-1],r=i[a][0],o=i[a][1],s=0,c=n.children.indexOf(e),l=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){let n=d.index,i={index:d.index,input:d.input,stack:[...t,e]},a=o(...d,i);if(typeof a==`string`&&(a=a.length>0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s<e.value.length&&u.push({type:`text`,value:e.value.slice(s)}),n.children.splice(c,1,...u)):u=[e],c+u.length}}function RO(e){let t=[];if(!Array.isArray(e))throw TypeError(`Expected find and replace tuple or list of tuples`);let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<n.length;){let e=n[r];t.push([zO(e[0]),BO(e[1])])}return t}function zO(e){return typeof e==`string`?new RegExp(IO(e),`g`):e}function BO(e){return typeof e==`function`?e:function(){return e}}var VO=`phrasing`,HO=[`autolink`,`link`,`image`,`label`];function UO(){return{transforms:[ZO],enter:{literalAutolink:GO,literalAutolinkEmail:KO,literalAutolinkHttp:KO,literalAutolinkWww:KO},exit:{literalAutolink:XO,literalAutolinkEmail:YO,literalAutolinkHttp:qO,literalAutolinkWww:JO}}}function WO(){return{unsafe:[{character:`@`,before:`[+\\-.\\w]`,after:`[\\-.\\w]`,inConstruct:VO,notInConstruct:HO},{character:`.`,before:`[Ww]`,after:`[\\-.\\w]`,inConstruct:VO,notInConstruct:HO},{character:`:`,before:`[ps]`,after:`\\/`,inConstruct:VO,notInConstruct:HO}]}}function GO(e){this.enter({type:`link`,title:null,url:``,children:[]},e)}function KO(e){this.config.enter.autolinkProtocol.call(this,e)}function qO(e){this.config.exit.autolinkProtocol.call(this,e)}function JO(e){this.config.exit.data.call(this,e);let t=this.stack[this.stack.length-1];t.type,t.url=`http://`+this.sliceSerialize(e)}function YO(e){this.config.exit.autolinkEmail.call(this,e)}function XO(e){this.exit(e)}function ZO(e){LO(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,QO],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,$O]],{ignore:[`link`,`linkReference`]})}function QO(e,t,n,r,i){let a=``;if(!nk(i)||(/^w/i.test(t)&&(n=t+n,t=``,a=`http://`),!ek(n)))return!1;let o=tk(n+r);if(!o[0])return!1;let s={type:`link`,title:null,url:a+t+o[0],children:[{type:`text`,value:t+o[0]}]};return o[1]?[s,{type:`text`,value:o[1]}]:s}function $O(e,t,n,r){return!nk(r,!0)||/[-\d_]$/.test(n)?!1:{type:`link`,title:null,url:`mailto:`+t+`@`+n,children:[{type:`text`,value:t+`@`+n}]}}function ek(e){let t=e.split(`.`);return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function tk(e){let t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=FO(e,`(`),a=FO(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function nk(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||XC(n)||YC(n))&&(!t||n!==47)}fk.peek=dk;function rk(){this.buffer()}function ik(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function ak(){this.buffer()}function ok(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function sk(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=zC(this.sliceSerialize(e)).toLowerCase(),n.label=t}function ck(e){this.exit(e)}function lk(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=zC(this.sliceSerialize(e)).toLowerCase(),n.label=t}function uk(e){this.exit(e)}function dk(){return`[`}function fk(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function pk(){return{enter:{gfmFootnoteCallString:rk,gfmFootnoteCall:ik,gfmFootnoteDefinitionLabelString:ak,gfmFootnoteDefinition:ok},exit:{gfmFootnoteCallString:sk,gfmFootnoteCall:ck,gfmFootnoteDefinitionLabelString:lk,gfmFootnoteDefinition:uk}}}function mk(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:fk},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?`
74
- `:` `)+r.indentLines(r.containerFlow(e,a.current()),t?gk:hk))),s(),o}}function hk(e,t,n){return t===0?e:gk(e,t,n)}function gk(e,t,n){return(n?``:` `)+e}var _k=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];Sk.peek=Ck;function vk(){return{canContainEols:[`delete`],enter:{strikethrough:bk},exit:{strikethrough:xk}}}function yk(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:_k}],handlers:{delete:Sk}}}function bk(e){this.enter({type:`delete`,children:[]},e)}function xk(e){this.exit(e)}function Sk(e,t,n,r){let i=n.createTracker(r),a=n.enter(`strikethrough`),o=i.move(`~~`);return o+=n.containerPhrasing(e,{...i.current(),before:o,after:`~`}),o+=i.move(`~~`),a(),o}function Ck(){return`~`}function wk(e){return e.length}function Tk(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||wk,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++u<e.length;){let t=[],r=[],a=-1;for(e[u].length>l&&(l=e[u].length);++a<e[u].length;){let o=Ek(e[u][a]);if(n.alignDelimiters!==!1){let e=i(o);r[a]=e,(c[a]===void 0||e>c[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++d<l;)a[d]=Dk(r[d]);else{let e=Dk(r);for(;++d<l;)a[d]=e}d=-1;let f=[],p=[];for(;++d<l;){let e=a[d],t=``,r=``;e===99?(t=`:`,r=`:`):e===108?t=`:`:e===114&&(r=`:`);let i=n.alignDelimiters===!1?1:Math.max(1,c[d]-t.length-r.length),o=t+`-`.repeat(i)+r;n.alignDelimiters!==!1&&(i=t.length+i+r.length,i>c[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u<o.length;){let e=o[u],t=s[u];d=-1;let r=[];for(;++d<l;){let i=e[d]||``,o=``,s=``;if(n.alignDelimiters!==!1){let e=c[d]-(t[d]||0),n=a[d];n===114?o=` `.repeat(e):n===99?e%2?(o=` `.repeat(e/2+.5),s=` `.repeat(e/2-.5)):(o=` `.repeat(e/2),s=o):s=` `.repeat(e)}n.delimiterStart!==!1&&!d&&r.push(`|`),n.padding!==!1&&(n.alignDelimiters!==!1||i!==``)&&(n.delimiterStart!==!1||d)&&r.push(` `),n.alignDelimiters!==!1&&r.push(o),r.push(i),n.alignDelimiters!==!1&&r.push(s),n.padding!==!1&&r.push(` `),(n.delimiterEnd!==!1||d!==l-1)&&r.push(`|`)}m.push(n.delimiterEnd===!1?r.join(``).replace(/ +$/,``):r.join(``))}return m.join(`
75
- `)}function Ek(e){return e==null?``:String(e)}function Dk(e){let t=typeof e==`string`?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function Ok(e,t,n,r){let i=n.enter(`blockquote`),a=n.createTracker(r);a.move(`> `),a.shift(2);let o=n.indentLines(n.containerFlow(e,a.current()),kk);return i(),o}function kk(e,t,n){return`>`+(n?``:` `)+e}function Ak(e,t){return jk(e,t.inConstruct,!0)&&!jk(e,t.notInConstruct,!1)}function jk(e,t,n){if(typeof t==`string`&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function Mk(e,t,n,r){let i=-1;for(;++i<n.unsafe.length;)if(n.unsafe[i].character===`
76
- `&&Ak(n.stack,n.unsafe[i]))return/[ \t]/.test(r.before)?``:` `;return`\\
77
- `}function Nk(e,t){let n=String(e),r=n.indexOf(t),i=r,a=0,o=0;if(typeof t!=`string`)throw TypeError(`Expected substring`);for(;r!==-1;)r===i?++a>o&&(o=a):a=1,i=r+t.length,r=n.indexOf(t,i);return o}function Pk(e,t){return!(t.options.fences!==!1||!e.value||e.lang||!/[^ \r\n]/.test(e.value)||/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Fk(e){let t=e.options.fence||"`";if(t!=="`"&&t!==`~`)throw Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function Ik(e,t,n,r){let i=Fk(n),a=e.value||``,o=i==="`"?`GraveAccent`:`Tilde`;if(Pk(e,n)){let e=n.enter(`codeIndented`),t=n.indentLines(a,Lk);return e(),t}let s=n.createTracker(r),c=i.repeat(Math.max(Nk(a,i)+1,3)),l=n.enter(`codeFenced`),u=s.move(c);if(e.lang){let t=n.enter(`codeFencedLang${o}`);u+=s.move(n.safe(e.lang,{before:u,after:` `,encode:["`"],...s.current()})),t()}if(e.lang&&e.meta){let t=n.enter(`codeFencedMeta${o}`);u+=s.move(` `),u+=s.move(n.safe(e.meta,{before:u,after:`
72
+ `}),n}function VD(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function HD(e,t){let n=ID(e,t),r=n.one(e,void 0),i=xD(n),a=Array.isArray(r)?{type:`root`,children:r}:r||{type:`root`,children:[]};return i&&(`children`in a,a.children.push({type:`text`,value:`
73
+ `},i)),a}function UD(e,t){return e&&`run`in e?async function(n,r){let i=HD(n,{file:r,...t});await e.run(i,r)}:function(n,r){return HD(n,{file:r,...e||t})}}function WD(e){if(e)throw e}var GD=r(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});f<p;++f)if(t=arguments[f],t!=null)for(n in t)r=l(d,n),i=l(t,n),d!==i&&(m&&i&&(s(i)||(a=o(i)))?(a?(a=!1,u=r&&o(r)?r:[]):u=r&&s(r)?r:{},c(d,{name:n,newValue:e(m,u,i)})):i!==void 0&&c(d,{name:n,newValue:i}));return d}}));function KD(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function qD(){let e=[],t={run:n,use:r};return t;function n(...t){let n=-1,r=t.pop();if(typeof r!=`function`)throw TypeError(`Expected function as last argument, not `+r);i(null,...t);function i(a,...o){let s=e[++n],c=-1;if(a){r(a);return}for(;++c<t.length;)(o[c]===null||o[c]===void 0)&&(o[c]=t[c]);t=o,s?JD(s,i)(...o):r(null,...o)}}function r(n){if(typeof n!=`function`)throw TypeError("Expected `middelware` to be a function, not "+n);return e.push(n),t}}function JD(e,t){let n;return r;function r(...t){let r=e.length>t.length,o;r&&t.push(i);try{o=e.apply(this,t)}catch(e){let t=e;if(r&&n)throw t;return i(t)}r||(o&&o.then&&typeof o.then==`function`?o.then(a,i):o instanceof Error?i(o):a(o))}function i(e,...r){n||(n=!0,t(e,...r))}function a(e){i(null,e)}}var YD={basename:XD,dirname:ZD,extname:QD,join:$D,sep:`/`};function XD(e,t){if(t!==void 0&&typeof t!=`string`)throw TypeError(`"ext" argument must be a string`);nO(e);let n=0,r=-1,i=e.length,a;if(t===void 0||t.length===0||t.length>e.length){for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else r<0&&(a=!0,r=i+1);return r<0?``:e.slice(n,r)}if(t===e)return``;let o=-1,s=t.length-1;for(;i--;)if(e.codePointAt(i)===47){if(a){n=i+1;break}}else o<0&&(a=!0,o=i+1),s>-1&&(e.codePointAt(i)===t.codePointAt(s--)?s<0&&(r=i):(s=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function ZD(e){if(nO(e),e.length===0)return`.`;let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||=!0;return t<0?e.codePointAt(0)===47?`/`:`.`:t===1&&e.codePointAt(0)===47?`//`:e.slice(0,t)}function QD(e){nO(e);let t=e.length,n=-1,r=0,i=-1,a=0,o;for(;t--;){let s=e.codePointAt(t);if(s===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),s===46?i<0?i=t:a!==1&&(a=1):i>-1&&(a=-1)}return i<0||n<0||a===0||a===1&&i===n-1&&i===r+1?``:e.slice(i,n)}function $D(...e){let t=-1,n;for(;++t<e.length;)nO(e[t]),e[t]&&(n=n===void 0?e[t]:n+`/`+e[t]);return n===void 0?`.`:eO(n)}function eO(e){nO(e);let t=e.codePointAt(0)===47,n=tO(e,!t);return n.length===0&&!t&&(n=`.`),n.length>0&&e.codePointAt(e.length-1)===47&&(n+=`/`),t?`/`+n:n}function tO(e,t){let n=``,r=0,i=-1,a=0,o=-1,s,c;for(;++o<=e.length;){if(o<e.length)s=e.codePointAt(o);else if(s===47)break;else s=47;if(s===47){if(i!==o-1&&a!==1){if(i!==o-1&&a===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf(`/`),c!==n.length-1){c<0?(n=``,r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf(`/`)),i=o,a=0;continue}}else if(n.length>0){n=``,r=0,i=o,a=0;continue}}t&&(n=n.length>0?n+`/..`:`..`,r=2)}else n.length>0?n+=`/`+e.slice(i+1,o):n=e.slice(i+1,o),r=o-i-1}i=o,a=0}else s===46&&a>-1?a++:a=-1}return n}function nO(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received `+JSON.stringify(e))}var rO={cwd:iO};function iO(){return`/`}function aO(e){return!!(typeof e==`object`&&e&&`href`in e&&e.href&&`protocol`in e&&e.protocol&&e.auth===void 0)}function oO(e){if(typeof e==`string`)e=new URL(e);else if(!aO(e)){let t=TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code=`ERR_INVALID_ARG_TYPE`,t}if(e.protocol!==`file:`){let e=TypeError(`The URL must be of scheme file`);throw e.code=`ERR_INVALID_URL_SCHEME`,e}return sO(e)}function sO(e){if(e.hostname!==``){let e=TypeError(`File URL host must be "localhost" or empty on darwin`);throw e.code=`ERR_INVALID_FILE_URL_HOST`,e}let t=e.pathname,n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){let e=t.codePointAt(n+2);if(e===70||e===102){let e=TypeError(`File URL path must not include encoded / characters`);throw e.code=`ERR_INVALID_FILE_URL_PATH`,e}}return decodeURIComponent(t)}var cO=[`history`,`path`,`basename`,`stem`,`extname`,`dirname`],lO=class{constructor(e){let t;t=e?aO(e)?{path:e}:typeof e==`string`||pO(e)?{value:e}:e:{},this.cwd=`cwd`in t?``:rO.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<cO.length;){let e=cO[n];e in t&&t[e]!==void 0&&t[e]!==null&&(this[e]=e===`history`?[...t[e]]:t[e])}let r;for(r in t)cO.includes(r)||(this[r]=t[r])}get basename(){return typeof this.path==`string`?YD.basename(this.path):void 0}set basename(e){dO(e,`basename`),uO(e,`basename`),this.path=YD.join(this.dirname||``,e)}get dirname(){return typeof this.path==`string`?YD.dirname(this.path):void 0}set dirname(e){fO(this.basename,`dirname`),this.path=YD.join(e||``,this.basename)}get extname(){return typeof this.path==`string`?YD.extname(this.path):void 0}set extname(e){if(uO(e,`extname`),fO(this.dirname,`extname`),e){if(e.codePointAt(0)!==46)throw Error("`extname` must start with `.`");if(e.includes(`.`,1))throw Error("`extname` cannot contain multiple dots")}this.path=YD.join(this.dirname,this.stem+(e||``))}get path(){return this.history[this.history.length-1]}set path(e){aO(e)&&(e=oO(e)),dO(e,`path`),this.path!==e&&this.history.push(e)}get stem(){return typeof this.path==`string`?YD.basename(this.path,this.extname):void 0}set stem(e){dO(e,`stem`),uO(e,`stem`),this.path=YD.join(this.dirname||``,e+(this.extname||``))}fail(e,t,n){let r=this.message(e,t,n);throw r.fatal=!0,r}info(e,t,n){let r=this.message(e,t,n);return r.fatal=void 0,r}message(e,t,n){let r=new YS(e,t,n);return this.path&&(r.name=this.path+`:`+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(e){return this.value===void 0?``:typeof this.value==`string`?this.value:new TextDecoder(e||void 0).decode(this.value)}};function uO(e,t){if(e&&e.includes(YD.sep))throw Error("`"+t+"` cannot be a path: did not expect `"+YD.sep+"`")}function dO(e,t){if(!e)throw Error("`"+t+"` cannot be empty")}function fO(e,t){if(!e)throw Error("Setting `"+t+"` requires `path` to be set too")}function pO(e){return!!(e&&typeof e==`object`&&`byteLength`in e&&`byteOffset`in e)}var mO=(function(e){let t=this.constructor.prototype,n=t[e],r=function(){return n.apply(r,arguments)};return Object.setPrototypeOf(r,t),r}),hO=n(GD(),1),gO={}.hasOwnProperty,_O=new class e extends mO{constructor(){super(`copy`),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=qD()}copy(){let t=new e,n=-1;for(;++n<this.attachers.length;){let e=this.attachers[n];t.use(...e)}return t.data((0,hO.default)(!0,{},this.namespace)),t}data(e,t){return typeof e==`string`?arguments.length===2?(bO(`data`,this.frozen),this.namespace[e]=t,this):gO.call(this.namespace,e)&&this.namespace[e]||void 0:e?(bO(`data`,this.frozen),this.namespace=e,this):this.namespace}freeze(){if(this.frozen)return this;let e=this;for(;++this.freezeIndex<this.attachers.length;){let[t,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);let r=t.call(e,...n);typeof r==`function`&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=1/0,this}parse(e){this.freeze();let t=CO(e),n=this.parser||this.Parser;return vO(`parse`,n),n(String(t),t)}process(e,t){let n=this;return this.freeze(),vO(`process`,this.parser||this.Parser),yO(`process`,this.compiler||this.Compiler),t?r(void 0,t):new Promise(r);function r(r,i){let a=CO(e),o=n.parse(a);n.run(o,a,function(e,t,r){if(e||!t||!r)return s(e);let i=t,a=n.stringify(i,r);TO(a)?r.value=a:r.result=a,s(e,r)});function s(e,n){e||!n?i(e):r?r(n):t(void 0,n)}}}processSync(e){let t=!1,n;return this.freeze(),vO(`processSync`,this.parser||this.Parser),yO(`processSync`,this.compiler||this.Compiler),this.process(e,r),SO(`processSync`,`process`,t),n;function r(e,r){t=!0,WD(e),n=r}}run(e,t,n){xO(e),this.freeze();let r=this.transformers;return!n&&typeof t==`function`&&(n=t,t=void 0),n?i(void 0,n):new Promise(i);function i(i,a){let o=CO(t);r.run(e,o,s);function s(t,r,o){let s=r||e;t?a(t):i?i(s):n(void 0,s,o)}}}runSync(e,t){let n=!1,r;return this.run(e,t,i),SO(`runSync`,`run`,n),r;function i(e,t){WD(e),r=t,n=!0}}stringify(e,t){this.freeze();let n=CO(t),r=this.compiler||this.Compiler;return yO(`stringify`,r),xO(e),r(e,n)}use(e,...t){let n=this.attachers,r=this.namespace;if(bO(`use`,this.frozen),e!=null){if(typeof e==`function`)s(e,t);else if(typeof e==`object`)Array.isArray(e)?o(e):a(e);else throw TypeError("Expected usable value, not `"+e+"`")}return this;function i(e){if(typeof e==`function`)s(e,[]);else if(typeof e==`object`){if(Array.isArray(e)){let[t,...n]=e;s(t,n)}else a(e)}else throw TypeError("Expected usable value, not `"+e+"`")}function a(e){if(!(`plugins`in e)&&!(`settings`in e))throw Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(e.plugins),e.settings&&(r.settings=(0,hO.default)(!0,r.settings,e.settings))}function o(e){let t=-1;if(e!=null){if(Array.isArray(e))for(;++t<e.length;){let n=e[t];i(n)}else throw TypeError("Expected a list of plugins, not `"+e+"`")}}function s(e,t){let r=-1,i=-1;for(;++r<n.length;)if(n[r][0]===e){i=r;break}if(i===-1)n.push([e,...t]);else if(t.length>0){let[r,...a]=t,o=n[i][1];KD(o)&&KD(r)&&(r=(0,hO.default)(!0,o,r)),n[i]=[e,r,...a]}}}}().freeze();function vO(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `parser`")}function yO(e,t){if(typeof t!=`function`)throw TypeError("Cannot `"+e+"` without `compiler`")}function bO(e,t){if(t)throw Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function xO(e){if(!KD(e)||typeof e.type!=`string`)throw TypeError("Expected node, got `"+e+"`")}function SO(e,t,n){if(!n)throw Error("`"+e+"` finished async. Use `"+t+"` instead")}function CO(e){return wO(e)?e:new lO(e)}function wO(e){return!!(e&&typeof e==`object`&&`message`in e&&`messages`in e)}function TO(e){return typeof e==`string`||EO(e)}function EO(e){return!!(e&&typeof e==`object`&&`byteLength`in e&&`byteOffset`in e)}var DO=[],OO={allowDangerousHtml:!0},kO=/^(https?|ircs?|mailto|xmpp)$/i,AO=[{from:`astPlugins`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowDangerousHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`allowNode`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowElement`},{from:`allowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`allowedElements`},{from:`className`,id:`remove-classname`},{from:`disallowedTypes`,id:`replace-allownode-allowedtypes-and-disallowedtypes`,to:`disallowedElements`},{from:`escapeHtml`,id:`remove-buggy-html-in-markdown-parser`},{from:`includeElementIndex`,id:`#remove-includeelementindex`},{from:`includeNodeIndex`,id:`change-includenodeindex-to-includeelementindex`},{from:`linkTarget`,id:`remove-linktarget`},{from:`plugins`,id:`change-plugins-to-remarkplugins`,to:`remarkPlugins`},{from:`rawSourcePos`,id:`#remove-rawsourcepos`},{from:`renderers`,id:`change-renderers-to-components`,to:`components`},{from:`source`,id:`change-source-to-children`,to:`children`},{from:`sourcePos`,id:`#remove-sourcepos`},{from:`transformImageUri`,id:`#add-urltransform`,to:`urlTransform`},{from:`transformLinkUri`,id:`#add-urltransform`,to:`urlTransform`}];function jO(e){let t=MO(e),n=NO(e);return PO(t.runSync(t.parse(n),n),e)}function MO(e){let t=e.rehypePlugins||DO,n=e.remarkPlugins||DO,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...OO}:OO;return _O().use(EE).use(n).use(UD,r).use(t)}function NO(e){let t=e.children||``,n=new lO;return typeof t==`string`?n.value=t:``+t,n}function PO(e,t){let n=t.allowedElements,r=t.allowElement,i=t.components,a=t.disallowedElements,o=t.skipHtml,s=t.unwrapDisallowed,c=t.urlTransform||FO;for(let e of AO)Object.hasOwn(t,e.from)&&``+e.from+(e.to?"use `"+e.to+"` instead":`remove it`)+e.id;return ND(e,l),rC(e,{Fragment:b.Fragment,components:i,ignoreInvalidStyle:!0,jsx:b.jsx,jsxs:b.jsxs,passKeys:!0,passNode:!0});function l(e,t,i){if(e.type===`raw`&&i&&typeof t==`number`)return o?i.children.splice(t,1):i.children[t]={type:`text`,value:e.value},t;if(e.type===`element`){let t;for(t in TC)if(Object.hasOwn(TC,t)&&Object.hasOwn(e.properties,t)){let n=e.properties[t],r=TC[t];(r===null||r.includes(e.tagName))&&(e.properties[t]=c(String(n||``),t,e))}}if(e.type===`element`){let o=n?!n.includes(e.tagName):a?a.includes(e.tagName):!1;if(!o&&r&&typeof t==`number`&&(o=!r(e,t,i)),o&&i&&typeof t==`number`)return s&&e.children?i.children.splice(t,1,...e.children):i.children.splice(t,1),t}}}function FO(e){let t=e.indexOf(`:`),n=e.indexOf(`?`),r=e.indexOf(`#`),i=e.indexOf(`/`);return t===-1||i!==-1&&t>i||n!==-1&&t>n||r!==-1&&t>r||kO.test(e.slice(0,t))?e:``}function IO(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}function LO(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function RO(e,t,n){let r=SD((n||{}).ignore||[]),i=zO(t),a=-1;for(;++a<i.length;)jD(e,`text`,o);function o(e,t){let n=-1,i;for(;++n<t.length;){let e=t[n],a=i?i.children:void 0;if(r(e,a?a.indexOf(e):void 0,i))return;i=e}if(i)return s(e,t)}function s(e,t){let n=t[t.length-1],r=i[a][0],o=i[a][1],s=0,c=n.children.indexOf(e),l=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){let n=d.index,i={index:d.index,input:d.input,stack:[...t,e]},a=o(...d,i);if(typeof a==`string`&&(a=a.length>0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s<e.value.length&&u.push({type:`text`,value:e.value.slice(s)}),n.children.splice(c,1,...u)):u=[e],c+u.length}}function zO(e){let t=[];if(!Array.isArray(e))throw TypeError(`Expected find and replace tuple or list of tuples`);let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<n.length;){let e=n[r];t.push([BO(e[0]),VO(e[1])])}return t}function BO(e){return typeof e==`string`?new RegExp(LO(e),`g`):e}function VO(e){return typeof e==`function`?e:function(){return e}}var HO=`phrasing`,UO=[`autolink`,`link`,`image`,`label`];function WO(){return{transforms:[QO],enter:{literalAutolink:KO,literalAutolinkEmail:qO,literalAutolinkHttp:qO,literalAutolinkWww:qO},exit:{literalAutolink:ZO,literalAutolinkEmail:XO,literalAutolinkHttp:JO,literalAutolinkWww:YO}}}function GO(){return{unsafe:[{character:`@`,before:`[+\\-.\\w]`,after:`[\\-.\\w]`,inConstruct:HO,notInConstruct:UO},{character:`.`,before:`[Ww]`,after:`[\\-.\\w]`,inConstruct:HO,notInConstruct:UO},{character:`:`,before:`[ps]`,after:`\\/`,inConstruct:HO,notInConstruct:UO}]}}function KO(e){this.enter({type:`link`,title:null,url:``,children:[]},e)}function qO(e){this.config.enter.autolinkProtocol.call(this,e)}function JO(e){this.config.exit.autolinkProtocol.call(this,e)}function YO(e){this.config.exit.data.call(this,e);let t=this.stack[this.stack.length-1];t.type,t.url=`http://`+this.sliceSerialize(e)}function XO(e){this.config.exit.autolinkEmail.call(this,e)}function ZO(e){this.exit(e)}function QO(e){RO(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,$O],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,ek]],{ignore:[`link`,`linkReference`]})}function $O(e,t,n,r,i){let a=``;if(!rk(i)||(/^w/i.test(t)&&(n=t+n,t=``,a=`http://`),!tk(n)))return!1;let o=nk(n+r);if(!o[0])return!1;let s={type:`link`,title:null,url:a+t+o[0],children:[{type:`text`,value:t+o[0]}]};return o[1]?[s,{type:`text`,value:o[1]}]:s}function ek(e,t,n,r){return!rk(r,!0)||/[-\d_]$/.test(n)?!1:{type:`link`,title:null,url:`mailto:`+t+`@`+n,children:[{type:`text`,value:t+`@`+n}]}}function tk(e){let t=e.split(`.`);return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function nk(e){let t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=IO(e,`(`),a=IO(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function rk(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||ZC(n)||XC(n))&&(!t||n!==47)}pk.peek=fk;function ik(){this.buffer()}function ak(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function ok(){this.buffer()}function sk(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function ck(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=BC(this.sliceSerialize(e)).toLowerCase(),n.label=t}function lk(e){this.exit(e)}function uk(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=BC(this.sliceSerialize(e)).toLowerCase(),n.label=t}function dk(e){this.exit(e)}function fk(){return`[`}function pk(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function mk(){return{enter:{gfmFootnoteCallString:ik,gfmFootnoteCall:ak,gfmFootnoteDefinitionLabelString:ok,gfmFootnoteDefinition:sk},exit:{gfmFootnoteCallString:ck,gfmFootnoteCall:lk,gfmFootnoteDefinitionLabelString:uk,gfmFootnoteDefinition:dk}}}function hk(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:pk},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?`
74
+ `:` `)+r.indentLines(r.containerFlow(e,a.current()),t?_k:gk))),s(),o}}function gk(e,t,n){return t===0?e:_k(e,t,n)}function _k(e,t,n){return(n?``:` `)+e}var vk=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];Ck.peek=wk;function yk(){return{canContainEols:[`delete`],enter:{strikethrough:xk},exit:{strikethrough:Sk}}}function bk(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:vk}],handlers:{delete:Ck}}}function xk(e){this.enter({type:`delete`,children:[]},e)}function Sk(e){this.exit(e)}function Ck(e,t,n,r){let i=n.createTracker(r),a=n.enter(`strikethrough`),o=i.move(`~~`);return o+=n.containerPhrasing(e,{...i.current(),before:o,after:`~`}),o+=i.move(`~~`),a(),o}function wk(){return`~`}function Tk(e){return e.length}function Ek(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||Tk,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++u<e.length;){let t=[],r=[],a=-1;for(e[u].length>l&&(l=e[u].length);++a<e[u].length;){let o=Dk(e[u][a]);if(n.alignDelimiters!==!1){let e=i(o);r[a]=e,(c[a]===void 0||e>c[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++d<l;)a[d]=Ok(r[d]);else{let e=Ok(r);for(;++d<l;)a[d]=e}d=-1;let f=[],p=[];for(;++d<l;){let e=a[d],t=``,r=``;e===99?(t=`:`,r=`:`):e===108?t=`:`:e===114&&(r=`:`);let i=n.alignDelimiters===!1?1:Math.max(1,c[d]-t.length-r.length),o=t+`-`.repeat(i)+r;n.alignDelimiters!==!1&&(i=t.length+i+r.length,i>c[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u<o.length;){let e=o[u],t=s[u];d=-1;let r=[];for(;++d<l;){let i=e[d]||``,o=``,s=``;if(n.alignDelimiters!==!1){let e=c[d]-(t[d]||0),n=a[d];n===114?o=` `.repeat(e):n===99?e%2?(o=` `.repeat(e/2+.5),s=` `.repeat(e/2-.5)):(o=` `.repeat(e/2),s=o):s=` `.repeat(e)}n.delimiterStart!==!1&&!d&&r.push(`|`),n.padding!==!1&&(n.alignDelimiters!==!1||i!==``)&&(n.delimiterStart!==!1||d)&&r.push(` `),n.alignDelimiters!==!1&&r.push(o),r.push(i),n.alignDelimiters!==!1&&r.push(s),n.padding!==!1&&r.push(` `),(n.delimiterEnd!==!1||d!==l-1)&&r.push(`|`)}m.push(n.delimiterEnd===!1?r.join(``).replace(/ +$/,``):r.join(``))}return m.join(`
75
+ `)}function Dk(e){return e==null?``:String(e)}function Ok(e){let t=typeof e==`string`?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function kk(e,t,n,r){let i=n.enter(`blockquote`),a=n.createTracker(r);a.move(`> `),a.shift(2);let o=n.indentLines(n.containerFlow(e,a.current()),Ak);return i(),o}function Ak(e,t,n){return`>`+(n?``:` `)+e}function jk(e,t){return Mk(e,t.inConstruct,!0)&&!Mk(e,t.notInConstruct,!1)}function Mk(e,t,n){if(typeof t==`string`&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function Nk(e,t,n,r){let i=-1;for(;++i<n.unsafe.length;)if(n.unsafe[i].character===`
76
+ `&&jk(n.stack,n.unsafe[i]))return/[ \t]/.test(r.before)?``:` `;return`\\
77
+ `}function Pk(e,t){let n=String(e),r=n.indexOf(t),i=r,a=0,o=0;if(typeof t!=`string`)throw TypeError(`Expected substring`);for(;r!==-1;)r===i?++a>o&&(o=a):a=1,i=r+t.length,r=n.indexOf(t,i);return o}function Fk(e,t){return!(t.options.fences!==!1||!e.value||e.lang||!/[^ \r\n]/.test(e.value)||/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Ik(e){let t=e.options.fence||"`";if(t!=="`"&&t!==`~`)throw Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function Lk(e,t,n,r){let i=Ik(n),a=e.value||``,o=i==="`"?`GraveAccent`:`Tilde`;if(Fk(e,n)){let e=n.enter(`codeIndented`),t=n.indentLines(a,Rk);return e(),t}let s=n.createTracker(r),c=i.repeat(Math.max(Pk(a,i)+1,3)),l=n.enter(`codeFenced`),u=s.move(c);if(e.lang){let t=n.enter(`codeFencedLang${o}`);u+=s.move(n.safe(e.lang,{before:u,after:` `,encode:["`"],...s.current()})),t()}if(e.lang&&e.meta){let t=n.enter(`codeFencedMeta${o}`);u+=s.move(` `),u+=s.move(n.safe(e.meta,{before:u,after:`
78
78
  `,encode:["`"],...s.current()})),t()}return u+=s.move(`
79
79
  `),a&&(u+=s.move(a+`
80
- `)),u+=s.move(c),l(),u}function Lk(e,t,n){return(n?``:` `)+e}function Rk(e){let t=e.options.quote||`"`;if(t!==`"`&&t!==`'`)throw Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function zk(e,t,n,r){let i=Rk(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`definition`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`[`);return l+=c.move(n.safe(n.associationId(e),{before:l,after:`]`,...c.current()})),l+=c.move(`]: `),s(),!e.url||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:`
81
- `,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),o(),l}function Bk(e){let t=e.options.emphasis||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Vk(e){return`&#x`+e.toString(16).toUpperCase()+`;`}function Hk(e,t,n){let r=ow(e),i=ow(t);return r===void 0?i===void 0?n===`_`?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Uk.peek=Wk;function Uk(e,t,n,r){let i=Bk(n),a=n.enter(`emphasis`),o=n.createTracker(r),s=o.move(i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=Hk(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=Vk(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=Hk(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+Vk(d));let p=o.move(i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function Wk(e,t,n){return n.options.emphasis||`*`}function Gk(e,t){let n=!1;return MD(e,function(e){if(`value`in e&&/\r?\n|\r/.test(e.value)||e.type===`break`)return n=!0,!1}),!!((!e.depth||e.depth<3)&&EC(e)&&(t.options.setext||n))}function Kk(e,t,n,r){let i=Math.max(Math.min(6,e.depth||1),1),a=n.createTracker(r);if(Gk(e,n)){let t=n.enter(`headingSetext`),r=n.enter(`phrasing`),o=n.containerPhrasing(e,{...a.current(),before:`
80
+ `)),u+=s.move(c),l(),u}function Rk(e,t,n){return(n?``:` `)+e}function zk(e){let t=e.options.quote||`"`;if(t!==`"`&&t!==`'`)throw Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function Bk(e,t,n,r){let i=zk(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`definition`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`[`);return l+=c.move(n.safe(n.associationId(e),{before:l,after:`]`,...c.current()})),l+=c.move(`]: `),s(),!e.url||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:`
81
+ `,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),o(),l}function Vk(e){let t=e.options.emphasis||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Hk(e){return`&#x`+e.toString(16).toUpperCase()+`;`}function Uk(e,t,n){let r=sw(e),i=sw(t);return r===void 0?i===void 0?n===`_`?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:i===void 0?{inside:!1,outside:!1}:i===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Wk.peek=Gk;function Wk(e,t,n,r){let i=Vk(n),a=n.enter(`emphasis`),o=n.createTracker(r),s=o.move(i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=Uk(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=Hk(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=Uk(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+Hk(d));let p=o.move(i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function Gk(e,t,n){return n.options.emphasis||`*`}function Kk(e,t){let n=!1;return ND(e,function(e){if(`value`in e&&/\r?\n|\r/.test(e.value)||e.type===`break`)return n=!0,!1}),!!((!e.depth||e.depth<3)&&DC(e)&&(t.options.setext||n))}function qk(e,t,n,r){let i=Math.max(Math.min(6,e.depth||1),1),a=n.createTracker(r);if(Kk(e,n)){let t=n.enter(`headingSetext`),r=n.enter(`phrasing`),o=n.containerPhrasing(e,{...a.current(),before:`
82
82
  `,after:`
83
83
  `});return r(),t(),o+`
84
84
  `+(i===1?`=`:`-`).repeat(o.length-(Math.max(o.lastIndexOf(`\r`),o.lastIndexOf(`
85
85
  `))+1))}let o=`#`.repeat(i),s=n.enter(`headingAtx`),c=n.enter(`phrasing`);a.move(o+` `);let l=n.containerPhrasing(e,{before:`# `,after:`
86
- `,...a.current()});return/^[\t ]/.test(l)&&(l=Vk(l.charCodeAt(0))+l.slice(1)),l=l?o+` `+l:o,n.options.closeAtx&&(l+=` `+o),c(),s(),l}qk.peek=Jk;function qk(e){return e.value||``}function Jk(){return`<`}Yk.peek=Xk;function Yk(e,t,n,r){let i=Rk(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`image`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`![`);return l+=c.move(n.safe(e.alt,{before:l,after:`]`,...c.current()})),l+=c.move(`](`),s(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),l+=c.move(`)`),o(),l}function Xk(){return`!`}Zk.peek=Qk;function Zk(e,t,n,r){let i=e.referenceType,a=n.enter(`imageReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`![`),l=n.safe(e.alt,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function Qk(){return`!`}$k.peek=eA;function $k(e,t,n){let r=e.value||``,i="`",a=-1;for(;RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=` `+r+` `);++a<n.unsafe.length;){let e=n.unsafe[a],t=n.compilePattern(e),i;if(e.atBreak)for(;i=t.exec(r);){let e=i.index;r.charCodeAt(e)===10&&r.charCodeAt(e-1)===13&&e--,r=r.slice(0,e)+` `+r.slice(i.index+1)}}return i+r+i}function eA(){return"`"}function tA(e,t){let n=EC(e);return!(t.options.resourceLink||!e.url||e.title||!e.children||e.children.length!==1||e.children[0].type!==`text`||n!==e.url&&`mailto:`+n!==e.url||!/^[a-z][a-z+.-]+:/i.test(e.url)||/[\0- <>\u007F]/.test(e.url))}nA.peek=rA;function nA(e,t,n,r){let i=Rk(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.createTracker(r),s,c;if(tA(e,n)){let t=n.stack;n.stack=[],s=n.enter(`autolink`);let r=o.move(`<`);return r+=o.move(n.containerPhrasing(e,{before:r,after:`>`,...o.current()})),r+=o.move(`>`),s(),n.stack=t,r}s=n.enter(`link`),c=n.enter(`label`);let l=o.move(`[`);return l+=o.move(n.containerPhrasing(e,{before:l,after:`](`,...o.current()})),l+=o.move(`](`),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter(`destinationLiteral`),l+=o.move(`<`),l+=o.move(n.safe(e.url,{before:l,after:`>`,...o.current()})),l+=o.move(`>`)):(c=n.enter(`destinationRaw`),l+=o.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...o.current()}))),c(),e.title&&(c=n.enter(`title${a}`),l+=o.move(` `+i),l+=o.move(n.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),l+=o.move(`)`),s(),l}function rA(e,t,n){return tA(e,n)?`<`:`[`}iA.peek=aA;function iA(e,t,n,r){let i=e.referenceType,a=n.enter(`linkReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`[`),l=n.containerPhrasing(e,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function aA(){return`[`}function oA(e){let t=e.options.bullet||`*`;if(t!==`*`&&t!==`+`&&t!==`-`)throw Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function sA(e){let t=oA(e),n=e.options.bulletOther;if(!n)return t===`*`?`-`:`*`;if(n!==`*`&&n!==`+`&&n!==`-`)throw Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function cA(e){let t=e.options.bulletOrdered||`.`;if(t!==`.`&&t!==`)`)throw Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function lA(e){let t=e.options.rule||`*`;if(t!==`*`&&t!==`-`&&t!==`_`)throw Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function uA(e,t,n,r){let i=n.enter(`list`),a=n.bulletCurrent,o=e.ordered?cA(n):oA(n),s=e.ordered?o===`.`?`)`:`.`:sA(n),c=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){let t=e.children?e.children[0]:void 0;if((o===`*`||o===`-`)&&t&&(!t.children||!t.children[0])&&n.stack[n.stack.length-1]===`list`&&n.stack[n.stack.length-2]===`listItem`&&n.stack[n.stack.length-3]===`list`&&n.stack[n.stack.length-4]===`listItem`&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),lA(n)===o&&t){let t=-1;for(;++t<e.children.length;){let n=e.children[t];if(n&&n.type===`listItem`&&n.children&&n.children[0]&&n.children[0].type===`thematicBreak`){c=!0;break}}}}c&&(o=s),n.bulletCurrent=o;let l=n.containerFlow(e,r);return n.bulletLastUsed=o,n.bulletCurrent=a,i(),l}function dA(e){let t=e.options.listItemIndent||`one`;if(t!==`tab`&&t!==`one`&&t!==`mixed`)throw Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function fA(e,t,n,r){let i=dA(n),a=n.bulletCurrent||oA(n);t&&t.type===`list`&&t.ordered&&(a=(typeof t.start==`number`&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+a);let o=a.length+1;(i===`tab`||i===`mixed`&&(t&&t.type===`list`&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);let s=n.createTracker(r);s.move(a+` `.repeat(o-a.length)),s.shift(o);let c=n.enter(`listItem`),l=n.indentLines(n.containerFlow(e,s.current()),u);return c(),l;function u(e,t,n){return t?(n?``:` `.repeat(o))+e:(n?a:a+` `.repeat(o-a.length))+e}}function pA(e,t,n,r){let i=n.enter(`paragraph`),a=n.enter(`phrasing`),o=n.containerPhrasing(e,r);return a(),i(),o}var mA=xD([`break`,`delete`,`emphasis`,`footnote`,`footnoteReference`,`image`,`imageReference`,`inlineCode`,`inlineMath`,`link`,`linkReference`,`mdxJsxTextElement`,`mdxTextExpression`,`strong`,`text`,`textDirective`]);function hA(e,t,n,r){return(e.children.some(function(e){return mA(e)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function gA(e){let t=e.options.strong||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}_A.peek=vA;function _A(e,t,n,r){let i=gA(n),a=n.enter(`strong`),o=n.createTracker(r),s=o.move(i+i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=Hk(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=Vk(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=Hk(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+Vk(d));let p=o.move(i+i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function vA(e,t,n){return n.options.strong||`*`}function yA(e,t,n,r){return n.safe(e.value,r)}function bA(e){let t=e.options.ruleRepetition||3;if(t<3)throw Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function xA(e,t,n){let r=(lA(n)+(n.options.ruleSpaces?` `:``)).repeat(bA(n));return n.options.ruleSpaces?r.slice(0,-1):r}var SA={blockquote:Ok,break:Mk,code:Ik,definition:zk,emphasis:Uk,hardBreak:Mk,heading:Kk,html:qk,image:Yk,imageReference:Zk,inlineCode:$k,link:nA,linkReference:iA,list:uA,listItem:fA,paragraph:pA,root:hA,strong:_A,text:yA,thematicBreak:xA};function CA(){return{enter:{table:wA,tableData:OA,tableHeader:OA,tableRow:EA},exit:{codeText:kA,table:TA,tableData:DA,tableHeader:DA,tableRow:DA}}}function wA(e){let t=e._align;this.enter({type:`table`,align:t.map(function(e){return e===`none`?null:e}),children:[]},e),this.data.inTable=!0}function TA(e){this.exit(e),this.data.inTable=void 0}function EA(e){this.enter({type:`tableRow`,children:[]},e)}function DA(e){this.exit(e)}function OA(e){this.enter({type:`tableCell`,children:[]},e)}function kA(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,AA));let n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function AA(e,t){return t===`|`?t:e}function jA(e){let t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,a=n?` `:`|`;return{unsafe:[{character:`\r`,inConstruct:`tableCell`},{character:`
86
+ `,...a.current()});return/^[\t ]/.test(l)&&(l=Hk(l.charCodeAt(0))+l.slice(1)),l=l?o+` `+l:o,n.options.closeAtx&&(l+=` `+o),c(),s(),l}Jk.peek=Yk;function Jk(e){return e.value||``}function Yk(){return`<`}Xk.peek=Zk;function Xk(e,t,n,r){let i=zk(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.enter(`image`),s=n.enter(`label`),c=n.createTracker(r),l=c.move(`![`);return l+=c.move(n.safe(e.alt,{before:l,after:`]`,...c.current()})),l+=c.move(`](`),s(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(s=n.enter(`destinationLiteral`),l+=c.move(`<`),l+=c.move(n.safe(e.url,{before:l,after:`>`,...c.current()})),l+=c.move(`>`)):(s=n.enter(`destinationRaw`),l+=c.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...c.current()}))),s(),e.title&&(s=n.enter(`title${a}`),l+=c.move(` `+i),l+=c.move(n.safe(e.title,{before:l,after:i,...c.current()})),l+=c.move(i),s()),l+=c.move(`)`),o(),l}function Zk(){return`!`}Qk.peek=$k;function Qk(e,t,n,r){let i=e.referenceType,a=n.enter(`imageReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`![`),l=n.safe(e.alt,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function $k(){return`!`}eA.peek=tA;function eA(e,t,n){let r=e.value||``,i="`",a=-1;for(;RegExp("(^|[^`])"+i+"([^`]|$)").test(r);)i+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=` `+r+` `);++a<n.unsafe.length;){let e=n.unsafe[a],t=n.compilePattern(e),i;if(e.atBreak)for(;i=t.exec(r);){let e=i.index;r.charCodeAt(e)===10&&r.charCodeAt(e-1)===13&&e--,r=r.slice(0,e)+` `+r.slice(i.index+1)}}return i+r+i}function tA(){return"`"}function nA(e,t){let n=DC(e);return!(t.options.resourceLink||!e.url||e.title||!e.children||e.children.length!==1||e.children[0].type!==`text`||n!==e.url&&`mailto:`+n!==e.url||!/^[a-z][a-z+.-]+:/i.test(e.url)||/[\0- <>\u007F]/.test(e.url))}rA.peek=iA;function rA(e,t,n,r){let i=zk(n),a=i===`"`?`Quote`:`Apostrophe`,o=n.createTracker(r),s,c;if(nA(e,n)){let t=n.stack;n.stack=[],s=n.enter(`autolink`);let r=o.move(`<`);return r+=o.move(n.containerPhrasing(e,{before:r,after:`>`,...o.current()})),r+=o.move(`>`),s(),n.stack=t,r}s=n.enter(`link`),c=n.enter(`label`);let l=o.move(`[`);return l+=o.move(n.containerPhrasing(e,{before:l,after:`](`,...o.current()})),l+=o.move(`](`),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter(`destinationLiteral`),l+=o.move(`<`),l+=o.move(n.safe(e.url,{before:l,after:`>`,...o.current()})),l+=o.move(`>`)):(c=n.enter(`destinationRaw`),l+=o.move(n.safe(e.url,{before:l,after:e.title?` `:`)`,...o.current()}))),c(),e.title&&(c=n.enter(`title${a}`),l+=o.move(` `+i),l+=o.move(n.safe(e.title,{before:l,after:i,...o.current()})),l+=o.move(i),c()),l+=o.move(`)`),s(),l}function iA(e,t,n){return nA(e,n)?`<`:`[`}aA.peek=oA;function aA(e,t,n,r){let i=e.referenceType,a=n.enter(`linkReference`),o=n.enter(`label`),s=n.createTracker(r),c=s.move(`[`),l=n.containerPhrasing(e,{before:c,after:`]`,...s.current()});c+=s.move(l+`][`),o();let u=n.stack;n.stack=[],o=n.enter(`reference`);let d=n.safe(n.associationId(e),{before:c,after:`]`,...s.current()});return o(),n.stack=u,a(),i===`full`||!l||l!==d?c+=s.move(d+`]`):i===`shortcut`?c=c.slice(0,-1):c+=s.move(`]`),c}function oA(){return`[`}function sA(e){let t=e.options.bullet||`*`;if(t!==`*`&&t!==`+`&&t!==`-`)throw Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function cA(e){let t=sA(e),n=e.options.bulletOther;if(!n)return t===`*`?`-`:`*`;if(n!==`*`&&n!==`+`&&n!==`-`)throw Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function lA(e){let t=e.options.bulletOrdered||`.`;if(t!==`.`&&t!==`)`)throw Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function uA(e){let t=e.options.rule||`*`;if(t!==`*`&&t!==`-`&&t!==`_`)throw Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function dA(e,t,n,r){let i=n.enter(`list`),a=n.bulletCurrent,o=e.ordered?lA(n):sA(n),s=e.ordered?o===`.`?`)`:`.`:cA(n),c=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){let t=e.children?e.children[0]:void 0;if((o===`*`||o===`-`)&&t&&(!t.children||!t.children[0])&&n.stack[n.stack.length-1]===`list`&&n.stack[n.stack.length-2]===`listItem`&&n.stack[n.stack.length-3]===`list`&&n.stack[n.stack.length-4]===`listItem`&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),uA(n)===o&&t){let t=-1;for(;++t<e.children.length;){let n=e.children[t];if(n&&n.type===`listItem`&&n.children&&n.children[0]&&n.children[0].type===`thematicBreak`){c=!0;break}}}}c&&(o=s),n.bulletCurrent=o;let l=n.containerFlow(e,r);return n.bulletLastUsed=o,n.bulletCurrent=a,i(),l}function fA(e){let t=e.options.listItemIndent||`one`;if(t!==`tab`&&t!==`one`&&t!==`mixed`)throw Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function pA(e,t,n,r){let i=fA(n),a=n.bulletCurrent||sA(n);t&&t.type===`list`&&t.ordered&&(a=(typeof t.start==`number`&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+a);let o=a.length+1;(i===`tab`||i===`mixed`&&(t&&t.type===`list`&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);let s=n.createTracker(r);s.move(a+` `.repeat(o-a.length)),s.shift(o);let c=n.enter(`listItem`),l=n.indentLines(n.containerFlow(e,s.current()),u);return c(),l;function u(e,t,n){return t?(n?``:` `.repeat(o))+e:(n?a:a+` `.repeat(o-a.length))+e}}function mA(e,t,n,r){let i=n.enter(`paragraph`),a=n.enter(`phrasing`),o=n.containerPhrasing(e,r);return a(),i(),o}var hA=SD([`break`,`delete`,`emphasis`,`footnote`,`footnoteReference`,`image`,`imageReference`,`inlineCode`,`inlineMath`,`link`,`linkReference`,`mdxJsxTextElement`,`mdxTextExpression`,`strong`,`text`,`textDirective`]);function gA(e,t,n,r){return(e.children.some(function(e){return hA(e)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function _A(e){let t=e.options.strong||`*`;if(t!==`*`&&t!==`_`)throw Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}vA.peek=yA;function vA(e,t,n,r){let i=_A(n),a=n.enter(`strong`),o=n.createTracker(r),s=o.move(i+i),c=o.move(n.containerPhrasing(e,{after:i,before:s,...o.current()})),l=c.charCodeAt(0),u=Uk(r.before.charCodeAt(r.before.length-1),l,i);u.inside&&(c=Hk(l)+c.slice(1));let d=c.charCodeAt(c.length-1),f=Uk(r.after.charCodeAt(0),d,i);f.inside&&(c=c.slice(0,-1)+Hk(d));let p=o.move(i+i);return a(),n.attentionEncodeSurroundingInfo={after:f.outside,before:u.outside},s+c+p}function yA(e,t,n){return n.options.strong||`*`}function bA(e,t,n,r){return n.safe(e.value,r)}function xA(e){let t=e.options.ruleRepetition||3;if(t<3)throw Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function SA(e,t,n){let r=(uA(n)+(n.options.ruleSpaces?` `:``)).repeat(xA(n));return n.options.ruleSpaces?r.slice(0,-1):r}var CA={blockquote:kk,break:Nk,code:Lk,definition:Bk,emphasis:Wk,hardBreak:Nk,heading:qk,html:Jk,image:Xk,imageReference:Qk,inlineCode:eA,link:rA,linkReference:aA,list:dA,listItem:pA,paragraph:mA,root:gA,strong:vA,text:bA,thematicBreak:SA};function wA(){return{enter:{table:TA,tableData:kA,tableHeader:kA,tableRow:DA},exit:{codeText:AA,table:EA,tableData:OA,tableHeader:OA,tableRow:OA}}}function TA(e){let t=e._align;this.enter({type:`table`,align:t.map(function(e){return e===`none`?null:e}),children:[]},e),this.data.inTable=!0}function EA(e){this.exit(e),this.data.inTable=void 0}function DA(e){this.enter({type:`tableRow`,children:[]},e)}function OA(e){this.exit(e)}function kA(e){this.enter({type:`tableCell`,children:[]},e)}function AA(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,jA));let n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function jA(e,t){return t===`|`?t:e}function MA(e){let t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,i=t.stringLength,a=n?` `:`|`;return{unsafe:[{character:`\r`,inConstruct:`tableCell`},{character:`
87
87
  `,inConstruct:`tableCell`},{atBreak:!0,character:`|`,after:`[ :-]`},{character:`|`,inConstruct:`tableCell`},{atBreak:!0,character:`:`,after:`-`},{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{inlineCode:f,table:o,tableCell:c,tableRow:s}};function o(e,t,n,r){return l(u(e,n,r),e.align)}function s(e,t,n,r){let i=l([d(e,n,r)]);return i.slice(0,i.indexOf(`
88
- `))}function c(e,t,n,r){let i=n.enter(`tableCell`),o=n.enter(`phrasing`),s=n.containerPhrasing(e,{...r,before:a,after:a});return o(),i(),s}function l(e,t){return Tk(e,{align:t,alignDelimiters:r,padding:n,stringLength:i})}function u(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`table`);for(;++i<r.length;)a[i]=d(r[i],t,n);return o(),a}function d(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`tableRow`);for(;++i<r.length;)a[i]=c(r[i],e,t,n);return o(),a}function f(e,t,n){let r=SA.inlineCode(e,t,n);return n.stack.includes(`tableCell`)&&(r=r.replace(/\|/g,`\\$&`)),r}}function MA(){return{exit:{taskListCheckValueChecked:PA,taskListCheckValueUnchecked:PA,paragraph:FA}}}function NA(){return{unsafe:[{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{listItem:IA}}}function PA(e){let t=this.stack[this.stack.length-2];t.type,t.checked=e.type===`taskListCheckValueChecked`}function FA(e){let t=this.stack[this.stack.length-2];if(t&&t.type===`listItem`&&typeof t.checked==`boolean`){let e=this.stack[this.stack.length-1];e.type;let n=e.children[0];if(n&&n.type===`text`){let r=t.children,i=-1,a;for(;++i<r.length;){let e=r[i];if(e.type===`paragraph`){a=e;break}}a===e&&(n.value=n.value.slice(1),n.value.length===0?e.children.shift():e.position&&n.position&&typeof n.position.start.offset==`number`&&(n.position.start.column++,n.position.start.offset++,e.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function IA(e,t,n,r){let i=e.children[0],a=typeof e.checked==`boolean`&&i&&i.type===`paragraph`,o=`[`+(e.checked?`x`:` `)+`] `,s=n.createTracker(r);a&&s.move(o);let c=SA.listItem(e,t,n,{...r,...s.current()});return a&&(c=c.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),c;function l(e){return e+o}}function LA(){return[UO(),pk(),vk(),CA(),MA()]}function RA(e){return{extensions:[WO(),mk(e),yk(),jA(e),NA()]}}var zA={tokenize:$A,partial:!0},BA={tokenize:ej,partial:!0},VA={tokenize:tj,partial:!0},HA={tokenize:nj,partial:!0},UA={tokenize:rj,partial:!0},WA={name:`wwwAutolink`,tokenize:ZA,previous:ij},GA={name:`protocolAutolink`,tokenize:QA,previous:aj},KA={name:`emailAutolink`,tokenize:XA,previous:oj},qA={};function JA(){return{text:qA}}for(var YA=48;YA<123;)qA[YA]=KA,YA++,YA===58?YA=65:YA===91&&(YA=97);qA[43]=KA,qA[45]=KA,qA[46]=KA,qA[95]=KA,qA[72]=[KA,GA],qA[104]=[KA,GA],qA[87]=[KA,WA],qA[119]=[KA,WA];function XA(e,t,n){let r=this,i,a;return o;function o(t){return!sj(t)||!oj.call(r,r.previous)||cj(r.events)?n(t):(e.enter(`literalAutolink`),e.enter(`literalAutolinkEmail`),s(t))}function s(t){return sj(t)?(e.consume(t),s):t===64?(e.consume(t),c):n(t)}function c(t){return t===46?e.check(UA,u,l)(t):t===45||t===95||VC(t)?(a=!0,e.consume(t),c):u(t)}function l(t){return e.consume(t),i=!0,c}function u(o){return a&&i&&BC(r.previous)?(e.exit(`literalAutolinkEmail`),e.exit(`literalAutolink`),t(o)):n(o)}}function ZA(e,t,n){let r=this;return i;function i(t){return t!==87&&t!==119||!ij.call(r,r.previous)||cj(r.events)?n(t):(e.enter(`literalAutolink`),e.enter(`literalAutolinkWww`),e.check(zA,e.attempt(BA,e.attempt(VA,a),n),n)(t))}function a(n){return e.exit(`literalAutolinkWww`),e.exit(`literalAutolink`),t(n)}}function QA(e,t,n){let r=this,i=``,a=!1;return o;function o(t){return(t===72||t===104)&&aj.call(r,r.previous)&&!cj(r.events)?(e.enter(`literalAutolink`),e.enter(`literalAutolinkHttp`),i+=String.fromCodePoint(t),e.consume(t),s):n(t)}function s(t){if(BC(t)&&i.length<5)return i+=String.fromCodePoint(t),e.consume(t),s;if(t===58){let n=i.toLowerCase();if(n===`http`||n===`https`)return e.consume(t),c}return n(t)}function c(t){return t===47?(e.consume(t),a?l:(a=!0,c)):n(t)}function l(t){return t===null||UC(t)||qC(t)||XC(t)||YC(t)?n(t):e.attempt(BA,e.attempt(VA,u),n)(t)}function u(n){return e.exit(`literalAutolinkHttp`),e.exit(`literalAutolink`),t(n)}}function $A(e,t,n){let r=0;return i;function i(t){return(t===87||t===119)&&r<3?(r++,e.consume(t),i):t===46&&r===3?(e.consume(t),a):n(t)}function a(e){return e===null?n(e):t(e)}}function ej(e,t,n){let r,i,a;return o;function o(t){return t===46||t===95?e.check(HA,c,s)(t):t===null||qC(t)||XC(t)||t!==45&&YC(t)?c(t):(a=!0,e.consume(t),o)}function s(t){return t===95?r=!0:(i=r,r=void 0),e.consume(t),o}function c(e){return i||r||!a?n(e):t(e)}}function tj(e,t){let n=0,r=0;return i;function i(o){return o===40?(n++,e.consume(o),i):o===41&&r<n?a(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(HA,t,a)(o):o===null||qC(o)||XC(o)?t(o):(e.consume(o),i)}function a(t){return t===41&&r++,e.consume(t),i}}function nj(e,t,n){return r;function r(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),r):o===38?(e.consume(o),a):o===93?(e.consume(o),i):o===60||o===null||qC(o)||XC(o)?t(o):n(o)}function i(e){return e===null||e===40||e===91||qC(e)||XC(e)?t(e):r(e)}function a(e){return BC(e)?o(e):n(e)}function o(t){return t===59?(e.consume(t),r):BC(t)?(e.consume(t),o):n(t)}}function rj(e,t,n){return r;function r(t){return e.consume(t),i}function i(e){return VC(e)?n(e):t(e)}}function ij(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||qC(e)}function aj(e){return!BC(e)}function oj(e){return!(e===47||sj(e))}function sj(e){return e===43||e===45||e===46||e===95||VC(e)}function cj(e){let t=e.length,n=!1;for(;t--;){let r=e[t][1];if((r.type===`labelLink`||r.type===`labelImage`)&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var lj={tokenize:_j,partial:!0};function uj(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:mj,continuation:{tokenize:hj},exit:gj}},text:{91:{name:`gfmFootnoteCall`,tokenize:pj},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:dj,resolveTo:fj}}}}function dj(e,t,n){let r=this,i=r.events.length,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o;for(;i--;){let e=r.events[i][1];if(e.type===`labelImage`){o=e;break}if(e.type===`gfmFootnoteCall`||e.type===`labelLink`||e.type===`label`||e.type===`image`||e.type===`link`)break}return s;function s(i){if(!o||!o._balanced)return n(i);let s=zC(r.sliceSerialize({start:o.end,end:r.now()}));return s.codePointAt(0)!==94||!a.includes(s.slice(1))?n(i):(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(i),e.exit(`gfmFootnoteCallLabelMarker`),t(i))}}function fj(e,t){let n=e.length;for(;n--;)if(e[n][1].type===`labelImage`&&e[n][0]===`enter`){e[n][1];break}e[n+1][1].type=`data`,e[n+3][1].type=`gfmFootnoteCallLabelMarker`;let r={type:`gfmFootnoteCall`,start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:`gfmFootnoteCallMarker`,start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let a={type:`gfmFootnoteCallString`,start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:`chunkString`,contentType:`string`,start:Object.assign({},a.start),end:Object.assign({},a.end)},s=[e[n+1],e[n+2],[`enter`,r,t],e[n+3],e[n+4],[`enter`,i,t],[`exit`,i,t],[`enter`,a,t],[`enter`,o,t],[`exit`,o,t],[`exit`,a,t],e[e.length-2],e[e.length-1],[`exit`,r,t]];return e.splice(n,e.length-n+1,...s),e}function pj(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a=0,o;return s;function s(t){return e.enter(`gfmFootnoteCall`),e.enter(`gfmFootnoteCallLabelMarker`),e.consume(t),e.exit(`gfmFootnoteCallLabelMarker`),c}function c(t){return t===94?(e.enter(`gfmFootnoteCallMarker`),e.consume(t),e.exit(`gfmFootnoteCallMarker`),e.enter(`gfmFootnoteCallString`),e.enter(`chunkString`).contentType=`string`,l):n(t)}function l(s){if(a>999||s===93&&!o||s===null||s===91||qC(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(zC(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return qC(s)||(o=!0),a++,e.consume(s),s===92?u:l}function u(t){return t===91||t===92||t===93?(e.consume(t),a++,l):l(t)}}function mj(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a,o=0,s;return c;function c(t){return e.enter(`gfmFootnoteDefinition`)._container=!0,e.enter(`gfmFootnoteDefinitionLabel`),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),l}function l(t){return t===94?(e.enter(`gfmFootnoteDefinitionMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionMarker`),e.enter(`gfmFootnoteDefinitionLabelString`),e.enter(`chunkString`).contentType=`string`,u):n(t)}function u(t){if(o>999||t===93&&!s||t===null||t===91||qC(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=zC(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return qC(t)||(s=!0),o++,e.consume(t),t===92?d:u}function d(t){return t===91||t===92||t===93?(e.consume(t),o++,u):u(t)}function f(t){return t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),i.includes(a)||i.push(a),$C(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function hj(e,t,n){return e.check(mw,t,e.attempt(lj,t,n))}function gj(e){e.exit(`gfmFootnoteDefinition`)}function _j(e,t,n){let r=this;return $C(e,i,`gfmFootnoteDefinitionIndent`,5);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`gfmFootnoteDefinitionIndent`&&i[2].sliceSerialize(i[1],!0).length===4?t(e):n(e)}}function vj(e){let t=(e||{}).singleTilde,n={name:`strikethrough`,tokenize:i,resolveAll:r};return t??=!0,{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(e,t){let n=-1;for(;++n<e.length;)if(e[n][0]===`enter`&&e[n][1].type===`strikethroughSequenceTemporary`&&e[n][1]._close){let r=n;for(;r--;)if(e[r][0]===`exit`&&e[r][1].type===`strikethroughSequenceTemporary`&&e[r][1]._open&&e[n][1].end.offset-e[n][1].start.offset===e[r][1].end.offset-e[r][1].start.offset){e[n][1].type=`strikethroughSequence`,e[r][1].type=`strikethroughSequence`;let i={type:`strikethrough`,start:Object.assign({},e[r][1].start),end:Object.assign({},e[n][1].end)},a={type:`strikethroughText`,start:Object.assign({},e[r][1].end),end:Object.assign({},e[n][1].start)},o=[[`enter`,i,t],[`enter`,e[r][1],t],[`exit`,e[r][1],t],[`enter`,a,t]],s=t.parser.constructs.insideSpan.null;s&&MC(o,o.length,0,sw(s,e.slice(r+1,n),t)),MC(o,o.length,0,[[`exit`,a,t],[`enter`,e[n][1],t],[`exit`,e[n][1],t],[`exit`,i,t]]),MC(e,r-1,n-r+3,o),n=r+o.length-2;break}}for(n=-1;++n<e.length;)e[n][1].type===`strikethroughSequenceTemporary`&&(e[n][1].type=`data`);return e}function i(e,n,r){let i=this.previous,a=this.events,o=0;return s;function s(t){return i===126&&a[a.length-1][1].type!==`characterEscape`?r(t):(e.enter(`strikethroughSequenceTemporary`),c(t))}function c(a){let s=ow(i);if(a===126)return o>1?r(a):(e.consume(a),o++,c);if(o<2&&!t)return r(a);let l=e.exit(`strikethroughSequenceTemporary`),u=ow(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var yj=class{constructor(){this.map=[],this.index=new Map}add(e,t,n){bj(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0,this.index.clear()}};function bj(e,t,n,r){if(n===0&&r.length===0)return;let i=e.index.get(t);if(i){i[1]+=n,i[2].push(...r);return}let a=[t,n,r];e.map.push(a),e.index.set(t,a)}function xj(e,t){let n=!1,r=[];for(;t<e.length;){let i=e[t];if(n){if(i[0]===`enter`)i[1].type===`tableContent`&&r.push(e[t+1][1].type===`tableDelimiterMarker`?`left`:`none`);else if(i[1].type===`tableContent`){if(e[t-1][1].type===`tableDelimiterMarker`){let e=r.length-1;r[e]=r[e]===`left`?`center`:`right`}}else if(i[1].type===`tableDelimiterRow`)break}else i[0]===`enter`&&i[1].type===`tableDelimiterRow`&&(n=!0);t+=1}return r}function Sj(){return{flow:{null:{name:`table`,tokenize:Cj,resolveAll:wj}}}}function Cj(e,t,n){let r=this,i=0,a=0,o;return s;function s(e){let t=r.events.length-1;for(;t>-1;){let{type:e}=r.events[t][1];if(e===`lineEnding`||e===`linePrefix`)t--;else break}let i=t>-1?r.events[t][1].type:null,a=i===`tableHead`||i===`tableRow`?S:c;return a===S&&r.parser.lazy[r.now().line]?n(e):a(e)}function c(t){return e.enter(`tableHead`),e.enter(`tableRow`),l(t)}function l(e){return e===124?u(e):(o=!0,a+=1,u(e))}function u(t){return t===null?n(t):q(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):JC(t)?$C(e,u,`whitespace`)(t):(a+=1,o&&(o=!1,i+=1),t===124?(e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),o=!0,u):(e.enter(`data`),d(t)))}function d(t){return t===null||t===124||qC(t)?(e.exit(`data`),u(t)):(e.consume(t),t===92?f:d)}function f(t){return t===92||t===124?(e.consume(t),d):d(t)}function p(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter(`tableDelimiterRow`),o=!1,JC(t)?$C(e,m,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):m(t))}function m(t){return t===45||t===58?g(t):t===124?(o=!0,e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),h):x(t)}function h(t){return JC(t)?$C(e,g,`whitespace`)(t):g(t)}function g(t){return t===58?(a+=1,o=!0,e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),_):t===45?(a+=1,_(t)):t===null||q(t)?b(t):x(t)}function _(t){return t===45?(e.enter(`tableDelimiterFiller`),v(t)):x(t)}function v(t){return t===45?(e.consume(t),v):t===58?(o=!0,e.exit(`tableDelimiterFiller`),e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),y):(e.exit(`tableDelimiterFiller`),y(t))}function y(t){return JC(t)?$C(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||q(n)?!o||i!==a?x(n):(e.exit(`tableDelimiterRow`),e.exit(`tableHead`),t(n)):x(n)}function x(e){return n(e)}function S(t){return e.enter(`tableRow`),C(t)}function C(n){return n===124?(e.enter(`tableCellDivider`),e.consume(n),e.exit(`tableCellDivider`),C):n===null||q(n)?(e.exit(`tableRow`),t(n)):JC(n)?$C(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||qC(t)?(e.exit(`data`),C(t)):(e.consume(t),t===92?T:w)}function T(t){return t===92||t===124?(e.consume(t),w):w(t)}}function wj(e,t){let n=-1,r=!0,i=0,a=[0,0,0,0],o=[0,0,0,0],s=!1,c=0,l,u,d,f=new yj;for(;++n<e.length;){let p=e[n],m=p[1];p[0]===`enter`?m.type===`tableHead`?(s=!1,c!==0&&(Ej(f,t,c,l,u),u=void 0,c=0),l={type:`table`,start:Object.assign({},m.start),end:Object.assign({},m.end)},f.add(n,0,[[`enter`,l,t]])):m.type===`tableRow`||m.type===`tableDelimiterRow`?(r=!0,d=void 0,a=[0,0,0,0],o=[0,n+1,0,0],s&&(s=!1,u={type:`tableBody`,start:Object.assign({},m.start),end:Object.assign({},m.end)},f.add(n,0,[[`enter`,u,t]])),i=m.type===`tableDelimiterRow`?2:u?3:1):i&&(m.type===`data`||m.type===`tableDelimiterMarker`||m.type===`tableDelimiterFiller`)?(r=!1,o[2]===0&&(a[1]!==0&&(o[0]=o[1],d=Tj(f,t,a,i,void 0,d),a=[0,0,0,0]),o[2]=n)):m.type===`tableCellDivider`&&(r?r=!1:(a[1]!==0&&(o[0]=o[1],d=Tj(f,t,a,i,void 0,d)),a=o,o=[a[1],n,0,0])):m.type===`tableHead`?(s=!0,c=n):m.type===`tableRow`||m.type===`tableDelimiterRow`?(c=n,a[1]===0?o[1]!==0&&(d=Tj(f,t,o,i,n,d)):(o[0]=o[1],d=Tj(f,t,a,i,n,d)),i=0):i&&(m.type===`data`||m.type===`tableDelimiterMarker`||m.type===`tableDelimiterFiller`)&&(o[3]=n)}for(c!==0&&Ej(f,t,c,l,u),f.consume(t.events),n=-1;++n<t.events.length;){let e=t.events[n];e[0]===`enter`&&e[1].type===`table`&&(e[1]._align=xj(t.events,n))}return e}function Tj(e,t,n,r,i,a){let o=r===1?`tableHeader`:r===2?`tableDelimiter`:`tableData`;n[0]!==0&&(a.end=Object.assign({},Dj(t.events,n[0])),e.add(n[0],0,[[`exit`,a,t]]));let s=Dj(t.events,n[1]);if(a={type:o,start:Object.assign({},s),end:Object.assign({},s)},e.add(n[1],0,[[`enter`,a,t]]),n[2]!==0){let i=Dj(t.events,n[2]),a=Dj(t.events,n[3]),o={type:`tableContent`,start:Object.assign({},i),end:Object.assign({},a)};if(e.add(n[2],0,[[`enter`,o,t]]),r!==2){let r=t.events[n[2]],i=t.events[n[3]];if(r[1].end=Object.assign({},i[1].end),r[1].type=`chunkText`,r[1].contentType=`text`,n[3]>n[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[[`exit`,o,t]])}return i!==void 0&&(a.end=Object.assign({},Dj(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function Ej(e,t,n,r,i){let a=[],o=Dj(t.events,n);i&&(i.end=Object.assign({},o),a.push([`exit`,i,t])),r.end=Object.assign({},o),a.push([`exit`,r,t]),e.add(n+1,0,a)}function Dj(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var Oj={name:`tasklistCheck`,tokenize:Aj};function kj(){return{text:{91:Oj}}}function Aj(e,t,n){let r=this;return i;function i(t){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(t):(e.enter(`taskListCheck`),e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),a)}function a(t){return qC(t)?(e.enter(`taskListCheckValueUnchecked`),e.consume(t),e.exit(`taskListCheckValueUnchecked`),o):t===88||t===120?(e.enter(`taskListCheckValueChecked`),e.consume(t),e.exit(`taskListCheckValueChecked`),o):n(t)}function o(t){return t===93?(e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),e.exit(`taskListCheck`),s):n(t)}function s(r){return q(r)?t(r):JC(r)?e.check({tokenize:jj},t,n)(r):n(r)}}function jj(e,t,n){return $C(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function Mj(e){return FC([JA(),uj(),vj(e),Sj(),kj()])}var Nj={};function Pj(e){let t=this,n=e||Nj,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(Mj(n)),a.push(LA()),o.push(RA(n))}var Fj={a:({children:e,...t})=>(0,b.jsx)(`a`,{...t,target:`_blank`,rel:`noreferrer`,className:`text-primary underline underline-offset-2`,children:e}),code:({className:e,children:t,...n})=>/language-/.test(e??``)?(0,b.jsx)(`code`,{...n,className:`block overflow-auto rounded-md border bg-[var(--plane)] p-3 font-mono text-xs whitespace-pre-wrap`,children:t}):(0,b.jsx)(`code`,{...n,className:`rounded-sm bg-[var(--plane)] px-1 py-0.5 font-mono text-[0.85em]`,children:t}),pre:({children:e,...t})=>(0,b.jsx)(`pre`,{...t,className:`my-1 overflow-auto`,children:e}),blockquote:({children:e,...t})=>(0,b.jsx)(`blockquote`,{...t,className:`border-l-2 border-border pl-3 text-muted-foreground`,children:e}),table:({children:e,...t})=>(0,b.jsx)(`div`,{className:`overflow-auto`,children:(0,b.jsx)(`table`,{...t,className:`w-full text-xs`,children:e})})};function Ij({children:e,className:t}){return(0,b.jsx)(`div`,{className:a(`md-body grid gap-2 text-sm leading-relaxed [&_h1]:mt-1 [&_h2]:mt-2 [&_h3]:mt-1`,t),children:(0,b.jsx)(AO,{remarkPlugins:[Pj],components:Fj,children:e})})}var Lj={clean:`success`,informational:`neutral`,actionable:`warning`,critical:`critical`},Rj={critical:`critical`,high:`error`,medium:`warning`,low:`neutral`,informational:`neutral`};function zj(){let e=Bd(),t=tf({queryKey:[`runs`],queryFn:()=>mx.runs()}),n=t.data?.runs??[],[r,i]=(0,y.useState)(null),a=tf({queryKey:[`report-versions`,r],queryFn:()=>mx.reportVersions(r),enabled:!!r}).data?.items??[],[s,c]=(0,y.useState)(null);(0,y.useEffect)(()=>{n.length>0&&!n.some(e=>e.id===r)&&i(n[0].id)},[n,r]),(0,y.useEffect)(()=>{if(a.length===0){c(null);return}a.some(e=>e.version===s)||c(a[0].version)},[r,a,s]);let l=tf({queryKey:[`report-version`,r,s],queryFn:()=>mx.reportVersion(r,s),enabled:!!r&&s!==null}),u=l.data?.record,d=l.data?.renditions.find(e=>e.ext===`md`)?.url??null,f=tf({queryKey:[`report-md`,r,s],queryFn:async()=>{let e=await fetch(d,{credentials:`same-origin`});if(!e.ok)throw Error(`Rendition fetch failed: ${e.status}`);return e.text()},enabled:d!==null}),[p,m]=(0,y.useState)(!1),[g,_]=(0,y.useState)(null),v=()=>{e.invalidateQueries({queryKey:[`report-versions`,r]}),e.invalidateQueries({queryKey:[`report-version`,r]}),e.invalidateQueries({queryKey:[`report-md`,r]})},x=nf({mutationFn:()=>mx.renderReportRenditions(r,s),onSuccess:()=>{m(!1),v()}}),S=nf({mutationFn:()=>mx.publishEditedMarkdown(r,s,g),onSuccess:e=>{_(null),m(!1),c(e.version),v()}});return t.isLoading?(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsx)(Bj,{}),(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`Loading hosted runs…`})})]}):n.length===0?(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsx)(Bj,{}),(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`No hosted runs yet. Launch an assessment and its report will appear here on completion.`})})]}):(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsx)(Bj,{}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{className:`mb-0`,children:`Generated report`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`The structured record is read-only; edits create new auditable versions.`})]}),(0,b.jsxs)(`div`,{className:`bg-card flex flex-wrap items-center gap-x-4 gap-y-2 rounded-xl border p-3`,children:[(0,b.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,b.jsx)(`span`,{className:`text-muted-foreground text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Run`}),(0,b.jsx)(`select`,{className:`rounded-md border bg-transparent px-2 py-1 text-sm`,value:r??``,onChange:e=>{i(e.target.value),c(null)},children:n.map(e=>(0,b.jsxs)(`option`,{value:e.id,children:[e.title,` — `,Hj(e.status)]},e.id))})]}),a.length>0?(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,b.jsx)(`span`,{className:`text-muted-foreground text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Version`}),a.map(e=>(0,b.jsxs)(o,{variant:e.version===s?`secondary`:`outline`,size:`sm`,className:`aria-pressed:border-primary`,"aria-pressed":e.version===s,onClick:()=>{c(e.version),m(!1)},children:[`v`,e.version,` · `,e.publicationState]},e.version))]}):null]}),a.length===0?(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`No report has been generated for this run yet. Reports are produced when a run reaches a terminal state.`})}):(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[u?(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(Kx,{variant:Gx(Lj[u.posture]??`neutral`),children:u.posture.toUpperCase()}),(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[`v`,l.data?.version,` · `,u.contentHash.slice(0,12),` · `,u.classification,` ·`,` `,u.publicationState]})]}),(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,b.jsx)(`h2`,{children:u.target}),(0,b.jsxs)(`span`,{className:`flex flex-wrap items-center gap-2`,children:[(0,b.jsx)(`span`,{className:`text-muted-foreground text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Export`}),l.data?.renditions.filter(e=>e.url).length?l.data.renditions.filter(e=>e.url).map(e=>(0,b.jsx)(o,{variant:`outline`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:e.url,download:!0,children:[(0,b.jsx)(Pf,{}),` `,e.ext.toUpperCase()]})},e.ext)):(0,b.jsx)(`span`,{className:`text-muted-foreground text-sm`,children:u.publicationState===`published`?`Use “Ensure renditions” below to generate files.`:`Publish to generate downloadable files.`})]})]}),(0,b.jsxs)(`p`,{className:`text-muted-foreground`,children:[u.workflowKey,` · `,u.findings.length,` finding(s) · `,u.evidence.length,` evidence row(s)`]}),u.gate.satisfied?null:(0,b.jsxs)(`p`,{className:`text-destructive text-sm`,children:[`Publication blocked: missing `,u.gate.missing.join(`, `),`.`]}),u.summary?(0,b.jsx)(`p`,{children:u.summary}):null,u.findings.length>0?(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Severity`}),(0,b.jsx)(`th`,{children:`Finding`}),(0,b.jsx)(`th`,{children:`Target`})]})}),(0,b.jsx)(`tbody`,{children:u.findings.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{children:(0,b.jsx)(Kx,{variant:Gx(Rj[e.severity]??`neutral`),children:e.severity})}),(0,b.jsx)(`td`,{children:e.title}),(0,b.jsx)(`td`,{className:`text-muted-foreground`,children:e.targetUrl??`—`})]},e.fingerprint))})]}):(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`No confirmed findings recorded — posture never claims a clean bill by default.`}),u.unverifiedLeads.length>0?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(`h3`,{children:`Unverified leads`}),(0,b.jsx)(`ul`,{children:u.unverifiedLeads.map(e=>(0,b.jsxs)(`li`,{children:[e.title,` `,(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[`(`,e.disposition,`)`]})]},e.fingerprint))})]}):null,u.negativeControls.length>0?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(`h3`,{children:`Negative controls`}),(0,b.jsx)(`ul`,{children:u.negativeControls.map(e=>(0,b.jsx)(`li`,{children:e},e))})]}):null]}):(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{children:`Select a run and version.`})}),l.data?(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(`h3`,{children:`Markdown rendition`}),(0,b.jsx)(`span`,{className:`flex flex-wrap items-center gap-2.5`,children:l.data.renditions.filter(e=>e.url).map(e=>(0,b.jsx)(o,{variant:`ghost`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:e.url,download:!0,children:[(0,b.jsx)(Pf,{}),` `,e.ext]})},e.ext))})]}),(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,style:{margin:`0.5rem 0`},children:[(0,b.jsxs)(o,{variant:`ghost`,onClick:()=>m(e=>!e),disabled:S.isPending,children:[p?(0,b.jsx)(If,{}):(0,b.jsx)(qf,{}),` `,p?`View`:`Edit`]}),(0,b.jsxs)(o,{variant:`ghost`,onClick:()=>x.mutate(),disabled:x.isPending||u?.publicationState!==`published`,title:`Create any missing immutable report renditions`,children:[(0,b.jsx)(Qf,{}),` Ensure renditions`]})]}),p?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(`textarea`,{className:`w-full resize-y rounded-lg border bg-[var(--surface-2)] p-3 font-mono text-[0.85rem] leading-normal`,value:g??f.data??``,onChange:e=>_(e.target.value),rows:24}),(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,style:{marginTop:`0.5rem`},children:[(0,b.jsxs)(o,{onClick:()=>S.mutate(),disabled:S.isPending||!g?.trim(),children:[(0,b.jsx)($f,{}),` Save as v`,(l.data?.version??0)+1]}),S.isError?(0,b.jsxs)(`span`,{className:`text-destructive text-sm`,children:[`Save failed: `,String(S.error)]}):null]})]}):f.isLoading?(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`Loading markdown…`}):f.isError||d===null?(0,b.jsxs)(`p`,{className:`text-muted-foreground`,children:[`No rendered markdown yet`,d===null?``:` (unavailable)`,` — regenerate to produce it.`]}):(0,b.jsx)(`div`,{className:`max-h-[32rem] overflow-auto rounded-lg border bg-[var(--plane)] p-4`,children:(0,b.jsx)(Ij,{children:f.data??``})})]}):null]})]})}function Bj(){let e=tf({queryKey:[`local-reports`],queryFn:()=>mx.localReports(),refetchInterval:5e3,retry:!1}),t=e.data?.items??[],[n,r]=(0,y.useState)(null),i=n&&t.some(e=>e.runId===n)?n:t[0]?.runId,a=i?`/api/v1/local-reports/${encodeURIComponent(i)}`:null,s=tf({queryKey:[`local-report-md`,i],queryFn:async()=>{let e=await fetch(`${a}/md`,{credentials:`same-origin`});if(!e.ok)throw Error(`Markdown fetch failed: ${e.status}`);return e.text()},enabled:!!a}),c=tf({queryKey:[`local-report-json`,i],queryFn:async()=>{let e=await fetch(`${a}/json`,{credentials:`same-origin`});if(!e.ok)throw Error(`Report fetch failed: ${e.status}`);return Gy.parse(await e.json())},enabled:!!a});if(e.isError)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Agent reports`}),(0,b.jsx)(`p`,{className:`text-destructive text-sm`,children:`Could not load local report files. Check that local reports are enabled and your session can access this workspace.`})]});if(e.isLoading)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Agent reports`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Checking completed report files…`})]});if(!t.length)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Agent reports`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`No completed report files are available for this workspace yet.`})]});let l=c.data;return(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{children:`Agent reports`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Rendered from the Markdown file written when an agent run completes.`})]}),(0,b.jsx)(`select`,{className:`rounded-md border bg-transparent px-2 py-1 text-sm`,value:i??``,onChange:e=>r(e.target.value),children:t.map(e=>(0,b.jsxs)(`option`,{value:e.runId,children:[e.workflowKey,` · `,e.target,` · `,e.findings+e.unverifiedLeads,` findings`]},e.runId))})]}),a?(0,b.jsx)(`div`,{className:`my-3 flex flex-wrap gap-2`,children:[`md`,`xlsx`,`pdf`,`json`].map(e=>(0,b.jsx)(o,{variant:`outline`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:`${a}/${e}`,download:`${i}.${e}`,children:[(0,b.jsx)(Pf,{}),` `,e.toUpperCase()]})},e))}):null,l?(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[l.findings.length,` confirmed findings · `,l.unverifiedLeads.length,` unverified leads · `,l.evidence.length,` evidence rows · `,l.posture,` posture`]}):null,l&&l.findings.length+l.unverifiedLeads.length>0?(0,b.jsx)(`div`,{className:`overflow-x-auto`,children:(0,b.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Severity`}),(0,b.jsx)(`th`,{children:`Finding`}),(0,b.jsx)(`th`,{children:`Status`}),(0,b.jsx)(`th`,{children:`Asset`}),(0,b.jsx)(`th`,{children:`Root cause`}),(0,b.jsx)(`th`,{children:`Impact`}),(0,b.jsx)(`th`,{children:`Corrective action`}),(0,b.jsx)(`th`,{children:`Evidence`})]})}),(0,b.jsx)(`tbody`,{children:[...l.findings,...l.unverifiedLeads].map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{children:e.severity}),(0,b.jsx)(`td`,{children:e.title}),(0,b.jsx)(`td`,{children:e.disposition}),(0,b.jsx)(`td`,{children:e.targetUrl??`—`}),(0,b.jsx)(`td`,{children:e.rootCause||`Not recorded`}),(0,b.jsx)(`td`,{children:e.impact||`Not recorded`}),(0,b.jsx)(`td`,{children:e.remediation||`Not recorded`}),(0,b.jsxs)(`td`,{children:[e.evidenceRefs.length,` ref(s)`]})]},e.fingerprint))})]})}):null,s.isLoading?(0,b.jsx)(`p`,{children:`Loading report file…`}):s.isError?(0,b.jsx)(`p`,{className:`text-destructive`,children:`Could not read the Markdown report file.`}):(0,b.jsx)(`div`,{className:`mt-4 max-h-[40rem] overflow-auto rounded-lg border p-4`,children:(0,b.jsx)(Ij,{children:s.data??``})})]})}function Vj(){let e=tf({queryKey:[`local-reports`],queryFn:()=>mx.localReports(),refetchInterval:5e3,retry:!1}).data?.items??[],[t,n]=(0,y.useState)(null),r=t&&e.some(e=>e.runId===t)?t:e[0]?.runId,i=r?`/api/v1/local-reports/${encodeURIComponent(r)}`:null,a=tf({queryKey:[`local-report-json`,r],queryFn:async()=>{let e=await fetch(`${i}/json`,{credentials:`same-origin`});if(!e.ok)throw Error(`Report fetch failed: ${e.status}`);return Gy.parse(await e.json())},enabled:!!i});if(!e.length)return null;let s=a.data;return(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{children:`Agent findings and root cause analysis`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Compiled from local run evidence. Unverified leads are labeled separately.`})]}),(0,b.jsx)(`select`,{className:`rounded-md border bg-transparent px-2 py-1 text-sm`,value:r??``,onChange:e=>n(e.target.value),children:e.map(e=>(0,b.jsxs)(`option`,{value:e.runId,children:[e.workflowKey,` · `,e.target]},e.runId))})]}),i?(0,b.jsxs)(`div`,{className:`my-3 flex gap-2`,children:[(0,b.jsx)(o,{variant:`outline`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:`${i}/xlsx`,download:!0,children:[(0,b.jsx)(Pf,{}),` Export Excel`]})}),(0,b.jsx)(o,{variant:`outline`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:`${i}/pdf`,download:!0,children:[(0,b.jsx)(Pf,{}),` Export PDF`]})})]}):null,s?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[s.findings.length,` confirmed · `,s.unverifiedLeads.length,` unverified · `,s.evidence.length,` evidence rows`]}),(0,b.jsx)(`div`,{className:`overflow-x-auto`,children:(0,b.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Severity`}),(0,b.jsx)(`th`,{children:`Finding and analysis`}),(0,b.jsx)(`th`,{children:`Asset`}),(0,b.jsx)(`th`,{children:`Root cause`}),(0,b.jsx)(`th`,{children:`Impact`}),(0,b.jsx)(`th`,{children:`Corrective action`}),(0,b.jsx)(`th`,{children:`Evidence`})]})}),(0,b.jsx)(`tbody`,{children:[...s.findings,...s.unverifiedLeads].map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[e.severity,(0,b.jsx)(`br`,{}),(0,b.jsx)(`span`,{className:`text-muted-foreground`,children:e.disposition})]}),(0,b.jsx)(`td`,{children:(0,b.jsxs)(`details`,{children:[(0,b.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:e.title}),(0,b.jsxs)(`div`,{className:`mt-2 grid gap-2`,children:[(0,b.jsx)(`p`,{children:e.description||`No description recorded.`}),e.invariant?(0,b.jsxs)(`p`,{children:[(0,b.jsx)(`strong`,{children:`Security invariant:`}),` `,e.invariant]}):null,e.reproduction.length?(0,b.jsx)(`ol`,{className:`list-decimal pl-5`,children:e.reproduction.map((e,t)=>(0,b.jsx)(`li`,{children:e},t))}):null]})]})}),(0,b.jsx)(`td`,{children:e.targetUrl??`—`}),(0,b.jsx)(`td`,{children:e.rootCause||`Not recorded`}),(0,b.jsx)(`td`,{children:e.impact||`Not recorded`}),(0,b.jsx)(`td`,{children:e.remediation||`Not recorded`}),(0,b.jsx)(`td`,{children:e.evidenceRefs.length?e.evidenceRefs.map(e=>(0,b.jsx)(`code`,{className:`block`,children:e.slice(0,12)},e)):`No linked refs`})]},e.fingerprint))})]})})]}):a.isError?(0,b.jsx)(`p`,{className:`text-destructive`,children:`Could not read the local finding record.`}):(0,b.jsx)(`p`,{children:`Loading findings…`})]})}function Hj(e){return e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var Uj=[`Reported`,`Confirmed`,`Remediating`,`Resolved`],Wj={open:0,unverified:0,confirmed:1,remediating:2,remediated:3,verified:3},Gj={false_positive:`Dismissed as a false positive`,accepted_risk:`Accepted as residual risk`,suppressed:`Suppressed`};function Kj(e){let t={label:`Confirm as risk`,status:`confirmed`,icon:(0,b.jsx)(tp,{size:14})},n={label:`Dismiss (false positive)`,status:`false_positive`,icon:(0,b.jsx)(Of,{size:14}),variant:`outline`},r={label:`Start remediation`,status:`remediating`,icon:(0,b.jsx)(pp,{size:14})},i={label:`Mark resolved`,status:`remediated`,icon:(0,b.jsx)(Sf,{size:14})},a={label:`Verify fix`,status:`verified`,icon:(0,b.jsx)(np,{size:14})},o={label:`Accept risk`,status:`accepted_risk`,icon:(0,b.jsx)(np,{size:14}),variant:`outline`},s={label:`Reopen`,status:`confirmed`,icon:(0,b.jsx)(gf,{size:14}),variant:`outline`};switch(e){case`open`:case`unverified`:return[t,n];case`confirmed`:return[r,i,o,n];case`remediating`:return[i,a,o];case`remediated`:return[a,s];case`verified`:return[s];default:return[{...s,label:`Reopen finding`}]}}function qj({findingId:e,onBack:t}){let n=Bd(),r=tf({queryKey:[`finding`,e],queryFn:()=>mx.finding(e)}),i=nf({mutationFn:t=>mx.updateFindingStatus(e,t),onSuccess:()=>{n.invalidateQueries({queryKey:[`finding`,e]}),n.invalidateQueries({queryKey:[`findings`]}),n.invalidateQueries({queryKey:[`overview`]})}});if(r.isLoading)return(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`Loading finding…`})});if(r.isError||!r.data)return(0,b.jsx)(h,{children:(0,b.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,b.jsx)(`p`,{className:`text-destructive`,children:`Could not load this finding.`}),t?(0,b.jsxs)(o,{variant:`outline`,size:`sm`,onClick:t,children:[(0,b.jsx)(gf,{size:14}),` Back`]}):null]})});let a=r.data.finding,s=wx(a.severity),c=kx(a.category,a.title),l=_x(c.stage),u=Wj[a.status],d=Gj[a.status],f=Kj(a.status);return(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsxs)(`div`,{className:`grid gap-2`,children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,b.jsx)(Kx,{variant:Gx(s),children:Cx[s]}),(0,b.jsx)(Kx,{variant:Gx(a.status),children:Yj(a.status)}),a.cvssScore==null?null:(0,b.jsxs)(Kx,{variant:`outline`,children:[`CVSS `,a.cvssScore]})]}),(0,b.jsx)(`h1`,{className:`text-xl font-semibold`,children:a.title}),(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[a.path??`unscoped asset`,a.line==null?``:`:${a.line}`,` · Stage `,c.stage,` `,vx(l),` · Pillar `,yx[c.pillar],c.inferred?` (inferred)`:``]})]}),t?(0,b.jsxs)(o,{variant:`outline`,size:`sm`,onClick:t,children:[(0,b.jsx)(gf,{size:14}),` Back`]}):null]}),(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Resolution`}),d?(0,b.jsx)(Kx,{variant:`secondary`,children:d}):null]}),d?(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`This finding is off the remediation track. Reopen it to return it to the queue.`}):(0,b.jsx)(`ol`,{className:`mt-1 grid grid-cols-4 gap-2`,"aria-label":`Resolution progress`,children:Uj.map((e,t)=>(0,b.jsxs)(`li`,{className:`grid gap-1.5`,children:[(0,b.jsx)(`span`,{className:`h-1.5 rounded-full`,style:{background:u!=null&&t<=u?`var(--good)`:`var(--border)`},"aria-hidden":`true`}),(0,b.jsx)(`span`,{className:u===t?`text-xs font-semibold`:`text-muted-foreground text-xs`,children:e})]},e))})]}),(0,b.jsxs)(h,{children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Verify & triage`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Move this finding through its lifecycle. Changes are audited.`}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:f.map(e=>(0,b.jsxs)(o,{size:`sm`,variant:e.variant??`default`,disabled:i.isPending,onClick:()=>i.mutate(e.status),children:[e.icon,` `,e.label]},`${e.label}:${e.status}`))}),i.isError?(0,b.jsxs)(`p`,{className:`text-destructive text-sm`,children:[`Update failed: `,String(i.error?.message??i.error)]}):null]}),a.description?(0,b.jsxs)(h,{children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Description`}),(0,b.jsx)(Ij,{children:a.description})]}):null,a.remediation?(0,b.jsxs)(h,{children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Remediation`}),(0,b.jsx)(Ij,{children:a.remediation})]}):null,(0,b.jsxs)(h,{children:[(0,b.jsxs)(`h3`,{className:`text-sm font-semibold`,children:[`Evidence (`,a.evidence.length,`)`]}),a.evidence.length?(0,b.jsx)(`div`,{className:`grid gap-2`,children:a.evidence.map(e=>(0,b.jsx)(Hx,{title:`${e.kind}${e.reason?` — ${e.reason}`:``}`,detail:(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[new Date(e.createdAt).toLocaleString(),e.runID?` · run ${e.runID.slice(0,12)}`:``]}),verdict:e.verdict},e.id))}):(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`No operation-level evidence linked yet. Source findings stay unverified until evidence confirms them.`})]}),(a.cwe||a.cve||a.cvssVector||a.assignee||a.resolvedAt)&&(0,b.jsxs)(h,{children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Metadata`}),(0,b.jsxs)(`dl`,{className:`grid gap-1.5 text-sm sm:grid-cols-2`,children:[a.cwe?(0,b.jsx)(Jj,{k:`CWE`,v:a.cwe}):null,a.cve?(0,b.jsx)(Jj,{k:`CVE`,v:a.cve}):null,a.cvssVector?(0,b.jsx)(Jj,{k:`CVSS vector`,v:a.cvssVector,mono:!0}):null,a.assignee?(0,b.jsx)(Jj,{k:`Assignee`,v:a.assignee}):null,a.resolvedAt?(0,b.jsx)(Jj,{k:`Resolved`,v:new Date(a.resolvedAt).toLocaleString()}):null,(0,b.jsx)(Jj,{k:`Fingerprint`,v:a.fingerprint,mono:!0})]})]})]})}function Jj({k:e,v:t,mono:n}){return(0,b.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,b.jsx)(`dt`,{className:`text-muted-foreground text-2xs w-28 shrink-0 font-semibold tracking-[0.08em] uppercase`,children:e}),(0,b.jsx)(`dd`,{className:n?`font-mono text-xs break-all`:``,children:t})]})}function Yj(e){return e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var Xj=null;function Zj(e,t){e.currentIndex=0,e.wipContextDeps=null,e.wipCommitCallbacks=[];let n=Xj;Xj=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{Xj=n}}function Qj(){if(!Xj)throw Error(`No resource fiber available`);return Xj}function $j(){return Xj}var eM=typeof process<`u`&&!1,tM=e=>({version:0,committedVersion:0,dispatchUpdate:e,changelog:[],committedLog:[],unsettledCount:0,rollbackCallbacks:[]}),nM=e=>{e.committedVersion=e.version;for(let t of e.changelog)t.logged=!1,t.settled||(t.settled=!0,e.unsettledCount--),e.committedLog.push(t);e.changelog.length=0,e.unsettledCount===0&&(e.committedLog.length=0),e.rollbackCallbacks.length=0},rM=(e,t)=>{let n=e.version>t;if(e.version=t,n){for(let t=0;t<e.rollbackCallbacks.length;t++)e.rollbackCallbacks[t]();if(e.rollbackCallbacks.length=0,t<=e.committedVersion){let n=[];for(;e.committedVersion-n.length>t;){let t=e.committedLog.pop();if(t===void 0){if(eM)throw Error(`tap: committed history is shorter than the replay base.`);break}sM(t.fiber,t.cell),t.cell.workInProgress=t.prevState,n.push({record:t,prevState:t.prevState,eagerState:t.eagerState,hasEagerState:t.hasEagerState})}if(n.length>0){let t=e.committedVersion;oM(e,()=>{for(let t=n.length-1;t>=0;t--){let r=n[t];r.record.prevState=r.prevState,r.record.eagerState=r.eagerState,r.record.hasEagerState=r.hasEagerState,e.committedLog.push(r.record)}e.committedVersion=t})}e.committedVersion=t;for(let t of e.changelog)t.logged=!1;e.changelog.length=0}else{for(;e.committedVersion+e.changelog.length>t;)e.changelog.pop().logged=!1;for(let t=0;t<e.changelog.length;t++)iM(e.changelog[t]);nM(e)}}},iM=e=>{sM(e.fiber,e.cell),e.queued||(e.queued=!0,(e.cell.queue??=[]).push(e))},aM=(e,t)=>{e.wipCommitCallbacks.push(t)},oM=(e,t)=>{e.rollbackCallbacks.push(t)},sM=(e,t)=>{t.isDirty||(t.isDirty=!0,e.markDirty?.(),oM(e.root,()=>{if(t.queue!==null){for(let e of t.queue)e.queued=!1;t.queue=null}t.workInProgress=t.current,t.isDirty=!1}))},cM=Symbol.for(`react.memo_cache_sentinel`),lM=e=>Array(e).fill(cM),uM=(e,t)=>{let n=e.memoCache,r=n.workInProgress;if(r===null){let t=n.current;r=t===null?[]:t.map(e=>e.slice()),n.workInProgress=r,oM(e.root,()=>{n.workInProgress=null})}let i=n.index++,a=r[i];return a===void 0?(a=lM(t),r[i]=a):eM&&a.length!==t&&console.error(`Expected a constant size argument for each invocation of c(). The previous cache was allocated with size ${a.length} but size ${t} was requested.`),a},dM=e=>uM(Qj(),e),fM=y.default.__COMPILER_RUNTIME?.c??(e=>(0,y.useMemo)(()=>{let t=lM(e);return t[cM]=!0,t},[])),pM=()=>$j()!==null,J=e=>pM()?dM(e):fM(e),mM=(e,...t)=>Object.assign(Object.create(null),e,...t),hM=()=>{throw Error(`Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.`)},gM=()=>{throw Error(`Hook order changed between renders`)},_M=()=>({type:`effect`,setup:void 0,setupDeps:void 0,cleanup:void 0,deps:null,generation:0});function vM(e,t){let n=Qj(),r=n.currentIndex++,i=n.cells[r],a=i===void 0?_M():i.type===`effect`?i:gM();if(i===void 0&&(n.isFirstRender||hM(),n.cells[r]=a,n.effectCells.push(a)),a.deps!==null&&!!t!=!!a.deps)throw Error(`useEffect called with and without dependencies across re-renders`);aM(n,()=>{a.setup=e,a.setupDeps=t,a.generation++})}var yM=(e,t)=>{eM&&e.length!==t.length&&console.error(`The final argument passed to a hook changed size between renders. The order and size of this array must remain constant.
88
+ `))}function c(e,t,n,r){let i=n.enter(`tableCell`),o=n.enter(`phrasing`),s=n.containerPhrasing(e,{...r,before:a,after:a});return o(),i(),s}function l(e,t){return Ek(e,{align:t,alignDelimiters:r,padding:n,stringLength:i})}function u(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`table`);for(;++i<r.length;)a[i]=d(r[i],t,n);return o(),a}function d(e,t,n){let r=e.children,i=-1,a=[],o=t.enter(`tableRow`);for(;++i<r.length;)a[i]=c(r[i],e,t,n);return o(),a}function f(e,t,n){let r=CA.inlineCode(e,t,n);return n.stack.includes(`tableCell`)&&(r=r.replace(/\|/g,`\\$&`)),r}}function NA(){return{exit:{taskListCheckValueChecked:FA,taskListCheckValueUnchecked:FA,paragraph:IA}}}function PA(){return{unsafe:[{atBreak:!0,character:`-`,after:`[:|-]`}],handlers:{listItem:LA}}}function FA(e){let t=this.stack[this.stack.length-2];t.type,t.checked=e.type===`taskListCheckValueChecked`}function IA(e){let t=this.stack[this.stack.length-2];if(t&&t.type===`listItem`&&typeof t.checked==`boolean`){let e=this.stack[this.stack.length-1];e.type;let n=e.children[0];if(n&&n.type===`text`){let r=t.children,i=-1,a;for(;++i<r.length;){let e=r[i];if(e.type===`paragraph`){a=e;break}}a===e&&(n.value=n.value.slice(1),n.value.length===0?e.children.shift():e.position&&n.position&&typeof n.position.start.offset==`number`&&(n.position.start.column++,n.position.start.offset++,e.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function LA(e,t,n,r){let i=e.children[0],a=typeof e.checked==`boolean`&&i&&i.type===`paragraph`,o=`[`+(e.checked?`x`:` `)+`] `,s=n.createTracker(r);a&&s.move(o);let c=CA.listItem(e,t,n,{...r,...s.current()});return a&&(c=c.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,l)),c;function l(e){return e+o}}function RA(){return[WO(),mk(),yk(),wA(),NA()]}function zA(e){return{extensions:[GO(),hk(e),bk(),MA(e),PA()]}}var BA={tokenize:ej,partial:!0},VA={tokenize:tj,partial:!0},HA={tokenize:nj,partial:!0},UA={tokenize:rj,partial:!0},WA={tokenize:ij,partial:!0},GA={name:`wwwAutolink`,tokenize:QA,previous:aj},KA={name:`protocolAutolink`,tokenize:$A,previous:oj},qA={name:`emailAutolink`,tokenize:ZA,previous:sj},JA={};function YA(){return{text:JA}}for(var XA=48;XA<123;)JA[XA]=qA,XA++,XA===58?XA=65:XA===91&&(XA=97);JA[43]=qA,JA[45]=qA,JA[46]=qA,JA[95]=qA,JA[72]=[qA,KA],JA[104]=[qA,KA],JA[87]=[qA,GA],JA[119]=[qA,GA];function ZA(e,t,n){let r=this,i,a;return o;function o(t){return!cj(t)||!sj.call(r,r.previous)||lj(r.events)?n(t):(e.enter(`literalAutolink`),e.enter(`literalAutolinkEmail`),s(t))}function s(t){return cj(t)?(e.consume(t),s):t===64?(e.consume(t),c):n(t)}function c(t){return t===46?e.check(WA,u,l)(t):t===45||t===95||HC(t)?(a=!0,e.consume(t),c):u(t)}function l(t){return e.consume(t),i=!0,c}function u(o){return a&&i&&VC(r.previous)?(e.exit(`literalAutolinkEmail`),e.exit(`literalAutolink`),t(o)):n(o)}}function QA(e,t,n){let r=this;return i;function i(t){return t!==87&&t!==119||!aj.call(r,r.previous)||lj(r.events)?n(t):(e.enter(`literalAutolink`),e.enter(`literalAutolinkWww`),e.check(BA,e.attempt(VA,e.attempt(HA,a),n),n)(t))}function a(n){return e.exit(`literalAutolinkWww`),e.exit(`literalAutolink`),t(n)}}function $A(e,t,n){let r=this,i=``,a=!1;return o;function o(t){return(t===72||t===104)&&oj.call(r,r.previous)&&!lj(r.events)?(e.enter(`literalAutolink`),e.enter(`literalAutolinkHttp`),i+=String.fromCodePoint(t),e.consume(t),s):n(t)}function s(t){if(VC(t)&&i.length<5)return i+=String.fromCodePoint(t),e.consume(t),s;if(t===58){let n=i.toLowerCase();if(n===`http`||n===`https`)return e.consume(t),c}return n(t)}function c(t){return t===47?(e.consume(t),a?l:(a=!0,c)):n(t)}function l(t){return t===null||WC(t)||JC(t)||ZC(t)||XC(t)?n(t):e.attempt(VA,e.attempt(HA,u),n)(t)}function u(n){return e.exit(`literalAutolinkHttp`),e.exit(`literalAutolink`),t(n)}}function ej(e,t,n){let r=0;return i;function i(t){return(t===87||t===119)&&r<3?(r++,e.consume(t),i):t===46&&r===3?(e.consume(t),a):n(t)}function a(e){return e===null?n(e):t(e)}}function tj(e,t,n){let r,i,a;return o;function o(t){return t===46||t===95?e.check(UA,c,s)(t):t===null||JC(t)||ZC(t)||t!==45&&XC(t)?c(t):(a=!0,e.consume(t),o)}function s(t){return t===95?r=!0:(i=r,r=void 0),e.consume(t),o}function c(e){return i||r||!a?n(e):t(e)}}function nj(e,t){let n=0,r=0;return i;function i(o){return o===40?(n++,e.consume(o),i):o===41&&r<n?a(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(UA,t,a)(o):o===null||JC(o)||ZC(o)?t(o):(e.consume(o),i)}function a(t){return t===41&&r++,e.consume(t),i}}function rj(e,t,n){return r;function r(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),r):o===38?(e.consume(o),a):o===93?(e.consume(o),i):o===60||o===null||JC(o)||ZC(o)?t(o):n(o)}function i(e){return e===null||e===40||e===91||JC(e)||ZC(e)?t(e):r(e)}function a(e){return VC(e)?o(e):n(e)}function o(t){return t===59?(e.consume(t),r):VC(t)?(e.consume(t),o):n(t)}}function ij(e,t,n){return r;function r(t){return e.consume(t),i}function i(e){return HC(e)?n(e):t(e)}}function aj(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||JC(e)}function oj(e){return!VC(e)}function sj(e){return!(e===47||cj(e))}function cj(e){return e===43||e===45||e===46||e===95||HC(e)}function lj(e){let t=e.length,n=!1;for(;t--;){let r=e[t][1];if((r.type===`labelLink`||r.type===`labelImage`)&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}var uj={tokenize:vj,partial:!0};function dj(){return{document:{91:{name:`gfmFootnoteDefinition`,tokenize:hj,continuation:{tokenize:gj},exit:_j}},text:{91:{name:`gfmFootnoteCall`,tokenize:mj},93:{name:`gfmPotentialFootnoteCall`,add:`after`,tokenize:fj,resolveTo:pj}}}}function fj(e,t,n){let r=this,i=r.events.length,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),o;for(;i--;){let e=r.events[i][1];if(e.type===`labelImage`){o=e;break}if(e.type===`gfmFootnoteCall`||e.type===`labelLink`||e.type===`label`||e.type===`image`||e.type===`link`)break}return s;function s(i){if(!o||!o._balanced)return n(i);let s=BC(r.sliceSerialize({start:o.end,end:r.now()}));return s.codePointAt(0)!==94||!a.includes(s.slice(1))?n(i):(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(i),e.exit(`gfmFootnoteCallLabelMarker`),t(i))}}function pj(e,t){let n=e.length;for(;n--;)if(e[n][1].type===`labelImage`&&e[n][0]===`enter`){e[n][1];break}e[n+1][1].type=`data`,e[n+3][1].type=`gfmFootnoteCallLabelMarker`;let r={type:`gfmFootnoteCall`,start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},i={type:`gfmFootnoteCallMarker`,start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};i.end.column++,i.end.offset++,i.end._bufferIndex++;let a={type:`gfmFootnoteCallString`,start:Object.assign({},i.end),end:Object.assign({},e[e.length-1][1].start)},o={type:`chunkString`,contentType:`string`,start:Object.assign({},a.start),end:Object.assign({},a.end)},s=[e[n+1],e[n+2],[`enter`,r,t],e[n+3],e[n+4],[`enter`,i,t],[`exit`,i,t],[`enter`,a,t],[`enter`,o,t],[`exit`,o,t],[`exit`,a,t],e[e.length-2],e[e.length-1],[`exit`,r,t]];return e.splice(n,e.length-n+1,...s),e}function mj(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a=0,o;return s;function s(t){return e.enter(`gfmFootnoteCall`),e.enter(`gfmFootnoteCallLabelMarker`),e.consume(t),e.exit(`gfmFootnoteCallLabelMarker`),c}function c(t){return t===94?(e.enter(`gfmFootnoteCallMarker`),e.consume(t),e.exit(`gfmFootnoteCallMarker`),e.enter(`gfmFootnoteCallString`),e.enter(`chunkString`).contentType=`string`,l):n(t)}function l(s){if(a>999||s===93&&!o||s===null||s===91||JC(s))return n(s);if(s===93){e.exit(`chunkString`);let a=e.exit(`gfmFootnoteCallString`);return i.includes(BC(r.sliceSerialize(a)))?(e.enter(`gfmFootnoteCallLabelMarker`),e.consume(s),e.exit(`gfmFootnoteCallLabelMarker`),e.exit(`gfmFootnoteCall`),t):n(s)}return JC(s)||(o=!0),a++,e.consume(s),s===92?u:l}function u(t){return t===91||t===92||t===93?(e.consume(t),a++,l):l(t)}}function hj(e,t,n){let r=this,i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]),a,o=0,s;return c;function c(t){return e.enter(`gfmFootnoteDefinition`)._container=!0,e.enter(`gfmFootnoteDefinitionLabel`),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),l}function l(t){return t===94?(e.enter(`gfmFootnoteDefinitionMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionMarker`),e.enter(`gfmFootnoteDefinitionLabelString`),e.enter(`chunkString`).contentType=`string`,u):n(t)}function u(t){if(o>999||t===93&&!s||t===null||t===91||JC(t))return n(t);if(t===93){e.exit(`chunkString`);let n=e.exit(`gfmFootnoteDefinitionLabelString`);return a=BC(r.sliceSerialize(n)),e.enter(`gfmFootnoteDefinitionLabelMarker`),e.consume(t),e.exit(`gfmFootnoteDefinitionLabelMarker`),e.exit(`gfmFootnoteDefinitionLabel`),f}return JC(t)||(s=!0),o++,e.consume(t),t===92?d:u}function d(t){return t===91||t===92||t===93?(e.consume(t),o++,u):u(t)}function f(t){return t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),i.includes(a)||i.push(a),ew(e,p,`gfmFootnoteDefinitionWhitespace`)):n(t)}function p(e){return t(e)}}function gj(e,t,n){return e.check(hw,t,e.attempt(uj,t,n))}function _j(e){e.exit(`gfmFootnoteDefinition`)}function vj(e,t,n){let r=this;return ew(e,i,`gfmFootnoteDefinitionIndent`,5);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`gfmFootnoteDefinitionIndent`&&i[2].sliceSerialize(i[1],!0).length===4?t(e):n(e)}}function yj(e){let t=(e||{}).singleTilde,n={name:`strikethrough`,tokenize:i,resolveAll:r};return t??=!0,{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function r(e,t){let n=-1;for(;++n<e.length;)if(e[n][0]===`enter`&&e[n][1].type===`strikethroughSequenceTemporary`&&e[n][1]._close){let r=n;for(;r--;)if(e[r][0]===`exit`&&e[r][1].type===`strikethroughSequenceTemporary`&&e[r][1]._open&&e[n][1].end.offset-e[n][1].start.offset===e[r][1].end.offset-e[r][1].start.offset){e[n][1].type=`strikethroughSequence`,e[r][1].type=`strikethroughSequence`;let i={type:`strikethrough`,start:Object.assign({},e[r][1].start),end:Object.assign({},e[n][1].end)},a={type:`strikethroughText`,start:Object.assign({},e[r][1].end),end:Object.assign({},e[n][1].start)},o=[[`enter`,i,t],[`enter`,e[r][1],t],[`exit`,e[r][1],t],[`enter`,a,t]],s=t.parser.constructs.insideSpan.null;s&&NC(o,o.length,0,cw(s,e.slice(r+1,n),t)),NC(o,o.length,0,[[`exit`,a,t],[`enter`,e[n][1],t],[`exit`,e[n][1],t],[`exit`,i,t]]),NC(e,r-1,n-r+3,o),n=r+o.length-2;break}}for(n=-1;++n<e.length;)e[n][1].type===`strikethroughSequenceTemporary`&&(e[n][1].type=`data`);return e}function i(e,n,r){let i=this.previous,a=this.events,o=0;return s;function s(t){return i===126&&a[a.length-1][1].type!==`characterEscape`?r(t):(e.enter(`strikethroughSequenceTemporary`),c(t))}function c(a){let s=sw(i);if(a===126)return o>1?r(a):(e.consume(a),o++,c);if(o<2&&!t)return r(a);let l=e.exit(`strikethroughSequenceTemporary`),u=sw(a);return l._open=!u||u===2&&!!s,l._close=!s||s===2&&!!u,n(a)}}}var bj=class{constructor(){this.map=[],this.index=new Map}add(e,t,n){xj(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0,this.index.clear()}};function xj(e,t,n,r){if(n===0&&r.length===0)return;let i=e.index.get(t);if(i){i[1]+=n,i[2].push(...r);return}let a=[t,n,r];e.map.push(a),e.index.set(t,a)}function Sj(e,t){let n=!1,r=[];for(;t<e.length;){let i=e[t];if(n){if(i[0]===`enter`)i[1].type===`tableContent`&&r.push(e[t+1][1].type===`tableDelimiterMarker`?`left`:`none`);else if(i[1].type===`tableContent`){if(e[t-1][1].type===`tableDelimiterMarker`){let e=r.length-1;r[e]=r[e]===`left`?`center`:`right`}}else if(i[1].type===`tableDelimiterRow`)break}else i[0]===`enter`&&i[1].type===`tableDelimiterRow`&&(n=!0);t+=1}return r}function Cj(){return{flow:{null:{name:`table`,tokenize:wj,resolveAll:Tj}}}}function wj(e,t,n){let r=this,i=0,a=0,o;return s;function s(e){let t=r.events.length-1;for(;t>-1;){let{type:e}=r.events[t][1];if(e===`lineEnding`||e===`linePrefix`)t--;else break}let i=t>-1?r.events[t][1].type:null,a=i===`tableHead`||i===`tableRow`?S:c;return a===S&&r.parser.lazy[r.now().line]?n(e):a(e)}function c(t){return e.enter(`tableHead`),e.enter(`tableRow`),l(t)}function l(e){return e===124?u(e):(o=!0,a+=1,u(e))}function u(t){return t===null?n(t):q(t)?a>1?(a=0,r.interrupt=!0,e.exit(`tableRow`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),p):n(t):YC(t)?ew(e,u,`whitespace`)(t):(a+=1,o&&(o=!1,i+=1),t===124?(e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),o=!0,u):(e.enter(`data`),d(t)))}function d(t){return t===null||t===124||JC(t)?(e.exit(`data`),u(t)):(e.consume(t),t===92?f:d)}function f(t){return t===92||t===124?(e.consume(t),d):d(t)}function p(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter(`tableDelimiterRow`),o=!1,YC(t)?ew(e,m,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):m(t))}function m(t){return t===45||t===58?g(t):t===124?(o=!0,e.enter(`tableCellDivider`),e.consume(t),e.exit(`tableCellDivider`),h):x(t)}function h(t){return YC(t)?ew(e,g,`whitespace`)(t):g(t)}function g(t){return t===58?(a+=1,o=!0,e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),_):t===45?(a+=1,_(t)):t===null||q(t)?b(t):x(t)}function _(t){return t===45?(e.enter(`tableDelimiterFiller`),v(t)):x(t)}function v(t){return t===45?(e.consume(t),v):t===58?(o=!0,e.exit(`tableDelimiterFiller`),e.enter(`tableDelimiterMarker`),e.consume(t),e.exit(`tableDelimiterMarker`),y):(e.exit(`tableDelimiterFiller`),y(t))}function y(t){return YC(t)?ew(e,b,`whitespace`)(t):b(t)}function b(n){return n===124?m(n):n===null||q(n)?!o||i!==a?x(n):(e.exit(`tableDelimiterRow`),e.exit(`tableHead`),t(n)):x(n)}function x(e){return n(e)}function S(t){return e.enter(`tableRow`),C(t)}function C(n){return n===124?(e.enter(`tableCellDivider`),e.consume(n),e.exit(`tableCellDivider`),C):n===null||q(n)?(e.exit(`tableRow`),t(n)):YC(n)?ew(e,C,`whitespace`)(n):(e.enter(`data`),w(n))}function w(t){return t===null||t===124||JC(t)?(e.exit(`data`),C(t)):(e.consume(t),t===92?T:w)}function T(t){return t===92||t===124?(e.consume(t),w):w(t)}}function Tj(e,t){let n=-1,r=!0,i=0,a=[0,0,0,0],o=[0,0,0,0],s=!1,c=0,l,u,d,f=new bj;for(;++n<e.length;){let p=e[n],m=p[1];p[0]===`enter`?m.type===`tableHead`?(s=!1,c!==0&&(Dj(f,t,c,l,u),u=void 0,c=0),l={type:`table`,start:Object.assign({},m.start),end:Object.assign({},m.end)},f.add(n,0,[[`enter`,l,t]])):m.type===`tableRow`||m.type===`tableDelimiterRow`?(r=!0,d=void 0,a=[0,0,0,0],o=[0,n+1,0,0],s&&(s=!1,u={type:`tableBody`,start:Object.assign({},m.start),end:Object.assign({},m.end)},f.add(n,0,[[`enter`,u,t]])),i=m.type===`tableDelimiterRow`?2:u?3:1):i&&(m.type===`data`||m.type===`tableDelimiterMarker`||m.type===`tableDelimiterFiller`)?(r=!1,o[2]===0&&(a[1]!==0&&(o[0]=o[1],d=Ej(f,t,a,i,void 0,d),a=[0,0,0,0]),o[2]=n)):m.type===`tableCellDivider`&&(r?r=!1:(a[1]!==0&&(o[0]=o[1],d=Ej(f,t,a,i,void 0,d)),a=o,o=[a[1],n,0,0])):m.type===`tableHead`?(s=!0,c=n):m.type===`tableRow`||m.type===`tableDelimiterRow`?(c=n,a[1]===0?o[1]!==0&&(d=Ej(f,t,o,i,n,d)):(o[0]=o[1],d=Ej(f,t,a,i,n,d)),i=0):i&&(m.type===`data`||m.type===`tableDelimiterMarker`||m.type===`tableDelimiterFiller`)&&(o[3]=n)}for(c!==0&&Dj(f,t,c,l,u),f.consume(t.events),n=-1;++n<t.events.length;){let e=t.events[n];e[0]===`enter`&&e[1].type===`table`&&(e[1]._align=Sj(t.events,n))}return e}function Ej(e,t,n,r,i,a){let o=r===1?`tableHeader`:r===2?`tableDelimiter`:`tableData`;n[0]!==0&&(a.end=Object.assign({},Oj(t.events,n[0])),e.add(n[0],0,[[`exit`,a,t]]));let s=Oj(t.events,n[1]);if(a={type:o,start:Object.assign({},s),end:Object.assign({},s)},e.add(n[1],0,[[`enter`,a,t]]),n[2]!==0){let i=Oj(t.events,n[2]),a=Oj(t.events,n[3]),o={type:`tableContent`,start:Object.assign({},i),end:Object.assign({},a)};if(e.add(n[2],0,[[`enter`,o,t]]),r!==2){let r=t.events[n[2]],i=t.events[n[3]];if(r[1].end=Object.assign({},i[1].end),r[1].type=`chunkText`,r[1].contentType=`text`,n[3]>n[2]+1){let t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[[`exit`,o,t]])}return i!==void 0&&(a.end=Object.assign({},Oj(t.events,i)),e.add(i,0,[[`exit`,a,t]]),a=void 0),a}function Dj(e,t,n,r,i){let a=[],o=Oj(t.events,n);i&&(i.end=Object.assign({},o),a.push([`exit`,i,t])),r.end=Object.assign({},o),a.push([`exit`,r,t]),e.add(n+1,0,a)}function Oj(e,t){let n=e[t],r=n[0]===`enter`?`start`:`end`;return n[1][r]}var kj={name:`tasklistCheck`,tokenize:jj};function Aj(){return{text:{91:kj}}}function jj(e,t,n){let r=this;return i;function i(t){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(t):(e.enter(`taskListCheck`),e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),a)}function a(t){return JC(t)?(e.enter(`taskListCheckValueUnchecked`),e.consume(t),e.exit(`taskListCheckValueUnchecked`),o):t===88||t===120?(e.enter(`taskListCheckValueChecked`),e.consume(t),e.exit(`taskListCheckValueChecked`),o):n(t)}function o(t){return t===93?(e.enter(`taskListCheckMarker`),e.consume(t),e.exit(`taskListCheckMarker`),e.exit(`taskListCheck`),s):n(t)}function s(r){return q(r)?t(r):YC(r)?e.check({tokenize:Mj},t,n)(r):n(r)}}function Mj(e,t,n){return ew(e,r,`whitespace`);function r(e){return e===null?n(e):t(e)}}function Nj(e){return IC([YA(),dj(),yj(e),Cj(),Aj()])}var Pj={};function Fj(e){let t=this,n=e||Pj,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(Nj(n)),a.push(RA()),o.push(zA(n))}var Ij={a:({children:e,...t})=>(0,b.jsx)(`a`,{...t,target:`_blank`,rel:`noreferrer`,className:`text-primary underline underline-offset-2`,children:e}),code:({className:e,children:t,...n})=>/language-/.test(e??``)?(0,b.jsx)(`code`,{...n,className:`block overflow-auto rounded-md border bg-[var(--plane)] p-3 font-mono text-xs whitespace-pre-wrap`,children:t}):(0,b.jsx)(`code`,{...n,className:`rounded-sm bg-[var(--plane)] px-1 py-0.5 font-mono text-[0.85em]`,children:t}),pre:({children:e,...t})=>(0,b.jsx)(`pre`,{...t,className:`my-1 overflow-auto`,children:e}),blockquote:({children:e,...t})=>(0,b.jsx)(`blockquote`,{...t,className:`border-l-2 border-border pl-3 text-muted-foreground`,children:e}),table:({children:e,...t})=>(0,b.jsx)(`div`,{className:`overflow-auto`,children:(0,b.jsx)(`table`,{...t,className:`w-full text-xs`,children:e})})};function Lj({children:e,className:t}){return(0,b.jsx)(`div`,{className:a(`md-body grid gap-2 text-sm leading-relaxed [&_h1]:mt-1 [&_h2]:mt-2 [&_h3]:mt-1`,t),children:(0,b.jsx)(jO,{remarkPlugins:[Fj],components:Ij,children:e})})}var Rj={clean:`success`,informational:`neutral`,actionable:`warning`,critical:`critical`},zj={critical:`critical`,high:`error`,medium:`warning`,low:`neutral`,informational:`neutral`};function Bj(){let e=Bd(),t=tf({queryKey:[`runs`],queryFn:()=>hx.runs()}),n=t.data?.runs??[],[r,i]=(0,y.useState)(null),a=tf({queryKey:[`report-versions`,r],queryFn:()=>hx.reportVersions(r),enabled:!!r}).data?.items??[],[s,c]=(0,y.useState)(null);(0,y.useEffect)(()=>{n.length>0&&!n.some(e=>e.id===r)&&i(n[0].id)},[n,r]),(0,y.useEffect)(()=>{if(a.length===0){c(null);return}a.some(e=>e.version===s)||c(a[0].version)},[r,a,s]);let l=tf({queryKey:[`report-version`,r,s],queryFn:()=>hx.reportVersion(r,s),enabled:!!r&&s!==null}),u=l.data?.record,d=l.data?.renditions.find(e=>e.ext===`md`)?.url??null,f=tf({queryKey:[`report-md`,r,s],queryFn:async()=>{let e=await fetch(d,{credentials:`same-origin`});if(!e.ok)throw Error(`Rendition fetch failed: ${e.status}`);return e.text()},enabled:d!==null}),[p,m]=(0,y.useState)(!1),[g,_]=(0,y.useState)(null),v=()=>{e.invalidateQueries({queryKey:[`report-versions`,r]}),e.invalidateQueries({queryKey:[`report-version`,r]}),e.invalidateQueries({queryKey:[`report-md`,r]})},x=nf({mutationFn:()=>hx.renderReportRenditions(r,s),onSuccess:()=>{m(!1),v()}}),S=nf({mutationFn:()=>hx.publishEditedMarkdown(r,s,g),onSuccess:e=>{_(null),m(!1),c(e.version),v()}});return t.isLoading?(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsx)(Vj,{}),(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`Loading hosted runs…`})})]}):n.length===0?(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsx)(Vj,{}),(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`No hosted runs yet. Launch an assessment and its report will appear here on completion.`})})]}):(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsx)(Vj,{}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{className:`mb-0`,children:`Generated report`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`The structured record is read-only; edits create new auditable versions.`})]}),(0,b.jsxs)(`div`,{className:`bg-card flex flex-wrap items-center gap-x-4 gap-y-2 rounded-xl border p-3`,children:[(0,b.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,b.jsx)(`span`,{className:`text-muted-foreground text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Run`}),(0,b.jsx)(`select`,{className:`rounded-md border bg-transparent px-2 py-1 text-sm`,value:r??``,onChange:e=>{i(e.target.value),c(null)},children:n.map(e=>(0,b.jsxs)(`option`,{value:e.id,children:[e.title,` — `,Uj(e.status)]},e.id))})]}),a.length>0?(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[(0,b.jsx)(`span`,{className:`text-muted-foreground text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Version`}),a.map(e=>(0,b.jsxs)(o,{variant:e.version===s?`secondary`:`outline`,size:`sm`,className:`aria-pressed:border-primary`,"aria-pressed":e.version===s,onClick:()=>{c(e.version),m(!1)},children:[`v`,e.version,` · `,e.publicationState]},e.version))]}):null]}),a.length===0?(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`No report has been generated for this run yet. Reports are produced when a run reaches a terminal state.`})}):(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[u?(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(qx,{variant:Kx(Rj[u.posture]??`neutral`),children:u.posture.toUpperCase()}),(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[`v`,l.data?.version,` · `,u.contentHash.slice(0,12),` · `,u.classification,` ·`,` `,u.publicationState]})]}),(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,b.jsx)(`h2`,{children:u.target}),(0,b.jsxs)(`span`,{className:`flex flex-wrap items-center gap-2`,children:[(0,b.jsx)(`span`,{className:`text-muted-foreground text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Export`}),l.data?.renditions.filter(e=>e.url).length?l.data.renditions.filter(e=>e.url).map(e=>(0,b.jsx)(o,{variant:`outline`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:e.url,download:!0,children:[(0,b.jsx)(Pf,{}),` `,e.ext.toUpperCase()]})},e.ext)):(0,b.jsx)(`span`,{className:`text-muted-foreground text-sm`,children:u.publicationState===`published`?`Use “Ensure renditions” below to generate files.`:`Publish to generate downloadable files.`})]})]}),(0,b.jsxs)(`p`,{className:`text-muted-foreground`,children:[u.workflowKey,` · `,u.findings.length,` finding(s) · `,u.evidence.length,` evidence row(s)`]}),u.gate.satisfied?null:(0,b.jsxs)(`p`,{className:`text-destructive text-sm`,children:[`Publication blocked: missing `,u.gate.missing.join(`, `),`.`]}),u.summary?(0,b.jsx)(`p`,{children:u.summary}):null,u.findings.length>0?(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Severity`}),(0,b.jsx)(`th`,{children:`Finding`}),(0,b.jsx)(`th`,{children:`Target`})]})}),(0,b.jsx)(`tbody`,{children:u.findings.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{children:(0,b.jsx)(qx,{variant:Kx(zj[e.severity]??`neutral`),children:e.severity})}),(0,b.jsx)(`td`,{children:e.title}),(0,b.jsx)(`td`,{className:`text-muted-foreground`,children:e.targetUrl??`—`})]},e.fingerprint))})]}):(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`No confirmed findings recorded — posture never claims a clean bill by default.`}),u.unverifiedLeads.length>0?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(`h3`,{children:`Unverified leads`}),(0,b.jsx)(`ul`,{children:u.unverifiedLeads.map(e=>(0,b.jsxs)(`li`,{children:[e.title,` `,(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[`(`,e.disposition,`)`]})]},e.fingerprint))})]}):null,u.negativeControls.length>0?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(`h3`,{children:`Negative controls`}),(0,b.jsx)(`ul`,{children:u.negativeControls.map(e=>(0,b.jsx)(`li`,{children:e},e))})]}):null]}):(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{children:`Select a run and version.`})}),l.data?(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(`h3`,{children:`Markdown rendition`}),(0,b.jsx)(`span`,{className:`flex flex-wrap items-center gap-2.5`,children:l.data.renditions.filter(e=>e.url).map(e=>(0,b.jsx)(o,{variant:`ghost`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:e.url,download:!0,children:[(0,b.jsx)(Pf,{}),` `,e.ext]})},e.ext))})]}),(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,style:{margin:`0.5rem 0`},children:[(0,b.jsxs)(o,{variant:`ghost`,onClick:()=>m(e=>!e),disabled:S.isPending,children:[p?(0,b.jsx)(If,{}):(0,b.jsx)(qf,{}),` `,p?`View`:`Edit`]}),(0,b.jsxs)(o,{variant:`ghost`,onClick:()=>x.mutate(),disabled:x.isPending||u?.publicationState!==`published`,title:`Create any missing immutable report renditions`,children:[(0,b.jsx)(Qf,{}),` Ensure renditions`]})]}),p?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(`textarea`,{className:`w-full resize-y rounded-lg border bg-[var(--surface-2)] p-3 font-mono text-[0.85rem] leading-normal`,value:g??f.data??``,onChange:e=>_(e.target.value),rows:24}),(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,style:{marginTop:`0.5rem`},children:[(0,b.jsxs)(o,{onClick:()=>S.mutate(),disabled:S.isPending||!g?.trim(),children:[(0,b.jsx)($f,{}),` Save as v`,(l.data?.version??0)+1]}),S.isError?(0,b.jsxs)(`span`,{className:`text-destructive text-sm`,children:[`Save failed: `,String(S.error)]}):null]})]}):f.isLoading?(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`Loading markdown…`}):f.isError||d===null?(0,b.jsxs)(`p`,{className:`text-muted-foreground`,children:[`No rendered markdown yet`,d===null?``:` (unavailable)`,` — regenerate to produce it.`]}):(0,b.jsx)(`div`,{className:`max-h-[32rem] overflow-auto rounded-lg border bg-[var(--plane)] p-4`,children:(0,b.jsx)(Lj,{children:f.data??``})})]}):null]})]})}function Vj(){let e=tf({queryKey:[`local-reports`],queryFn:()=>hx.localReports(),refetchInterval:5e3,retry:!1}),t=e.data?.items??[],[n,r]=(0,y.useState)(null),i=n&&t.some(e=>e.runId===n)?n:t[0]?.runId,a=i?`/api/v1/local-reports/${encodeURIComponent(i)}`:null,s=tf({queryKey:[`local-report-md`,i],queryFn:async()=>{let e=await fetch(`${a}/md`,{credentials:`same-origin`});if(!e.ok)throw Error(`Markdown fetch failed: ${e.status}`);return e.text()},enabled:!!a}),c=tf({queryKey:[`local-report-json`,i],queryFn:async()=>{let e=await fetch(`${a}/json`,{credentials:`same-origin`});if(!e.ok)throw Error(`Report fetch failed: ${e.status}`);return Gy.parse(await e.json())},enabled:!!a});if(e.isError)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Agent reports`}),(0,b.jsx)(`p`,{className:`text-destructive text-sm`,children:`Could not load local report files. Check that local reports are enabled and your session can access this workspace.`})]});if(e.isLoading)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Agent reports`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Checking completed report files…`})]});if(!t.length)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Agent reports`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`No completed report files are available for this workspace yet.`})]});let l=c.data;return(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{children:`Agent reports`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Rendered from the Markdown file written when an agent run completes.`})]}),(0,b.jsx)(`select`,{className:`rounded-md border bg-transparent px-2 py-1 text-sm`,value:i??``,onChange:e=>r(e.target.value),children:t.map(e=>(0,b.jsxs)(`option`,{value:e.runId,children:[e.workflowKey,` · `,e.target,` · `,e.findings+e.unverifiedLeads,` findings`]},e.runId))})]}),a?(0,b.jsx)(`div`,{className:`my-3 flex flex-wrap gap-2`,children:[`md`,`xlsx`,`pdf`,`json`].map(e=>(0,b.jsx)(o,{variant:`outline`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:`${a}/${e}`,download:`${i}.${e}`,children:[(0,b.jsx)(Pf,{}),` `,e.toUpperCase()]})},e))}):null,l?(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[l.findings.length,` confirmed findings · `,l.unverifiedLeads.length,` unverified leads · `,l.evidence.length,` evidence rows · `,l.posture,` posture`]}):null,l&&l.findings.length+l.unverifiedLeads.length>0?(0,b.jsx)(`div`,{className:`overflow-x-auto`,children:(0,b.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Severity`}),(0,b.jsx)(`th`,{children:`Finding`}),(0,b.jsx)(`th`,{children:`Status`}),(0,b.jsx)(`th`,{children:`Asset`}),(0,b.jsx)(`th`,{children:`Root cause`}),(0,b.jsx)(`th`,{children:`Impact`}),(0,b.jsx)(`th`,{children:`Corrective action`}),(0,b.jsx)(`th`,{children:`Evidence`})]})}),(0,b.jsx)(`tbody`,{children:[...l.findings,...l.unverifiedLeads].map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{children:e.severity}),(0,b.jsx)(`td`,{children:e.title}),(0,b.jsx)(`td`,{children:e.disposition}),(0,b.jsx)(`td`,{children:e.targetUrl??`—`}),(0,b.jsx)(`td`,{children:e.rootCause||`Not recorded`}),(0,b.jsx)(`td`,{children:e.impact||`Not recorded`}),(0,b.jsx)(`td`,{children:e.remediation||`Not recorded`}),(0,b.jsxs)(`td`,{children:[e.evidenceRefs.length,` ref(s)`]})]},e.fingerprint))})]})}):null,s.isLoading?(0,b.jsx)(`p`,{children:`Loading report file…`}):s.isError?(0,b.jsx)(`p`,{className:`text-destructive`,children:`Could not read the Markdown report file.`}):(0,b.jsx)(`div`,{className:`mt-4 max-h-[40rem] overflow-auto rounded-lg border p-4`,children:(0,b.jsx)(Lj,{children:s.data??``})})]})}function Hj(){let e=tf({queryKey:[`local-reports`],queryFn:()=>hx.localReports(),refetchInterval:5e3,retry:!1}).data?.items??[],[t,n]=(0,y.useState)(null),[r,i]=(0,y.useState)(!1),[a,s]=(0,y.useState)(!1),c=t&&e.some(e=>e.runId===t)?t:e[0]?.runId,l=c?`/api/v1/local-reports/${encodeURIComponent(c)}`:null,u=tf({queryKey:[`local-report-json`,c],queryFn:async()=>{let e=await fetch(`${l}/json`,{credentials:`same-origin`});if(!e.ok)throw Error(`Report fetch failed: ${e.status}`);return Gy.parse(await e.json())},enabled:!!l&&r});if(!e.length)return null;let d=u.data;return(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{children:`Local headless runs`}),(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[e.length,` report`,e.length===1?``:`s`,` · separate from the agent session selected above.`]})]}),(0,b.jsx)(o,{variant:`outline`,size:`sm`,"aria-expanded":r,onClick:()=>i(e=>!e),children:r?`Hide local runs`:`Browse local runs`})]}),r?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(`label`,{className:`mt-3 flex flex-wrap items-center gap-2 text-sm`,children:[`Run`,(0,b.jsx)(`select`,{className:`rounded-md border bg-transparent px-2 py-1 text-sm`,value:c??``,onChange:e=>{n(e.target.value),s(!1)},children:e.map(e=>(0,b.jsxs)(`option`,{value:e.runId,children:[e.workflowKey,` · `,e.target]},e.runId))})]}),l?(0,b.jsxs)(`div`,{className:`my-3 flex gap-2`,children:[(0,b.jsx)(o,{variant:`outline`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:`${l}/xlsx`,download:!0,children:[(0,b.jsx)(Pf,{}),` Export Excel`]})}),(0,b.jsx)(o,{variant:`outline`,size:`sm`,asChild:!0,children:(0,b.jsxs)(`a`,{href:`${l}/pdf`,download:!0,children:[(0,b.jsx)(Pf,{}),` Export PDF`]})})]}):null,d?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[d.findings.length,` confirmed · `,d.unverifiedLeads.length,` unverified · `,d.evidence.length,` evidence rows`]}),(0,b.jsx)(o,{variant:`outline`,size:`sm`,className:`mt-2`,"aria-expanded":a,onClick:()=>s(e=>!e),children:a?`Hide RCA table`:`Show RCA table`}),a?(0,b.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,b.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Severity`}),(0,b.jsx)(`th`,{children:`Finding and analysis`}),(0,b.jsx)(`th`,{children:`Asset`}),(0,b.jsx)(`th`,{children:`Root cause`}),(0,b.jsx)(`th`,{children:`Impact`}),(0,b.jsx)(`th`,{children:`Corrective action`}),(0,b.jsx)(`th`,{children:`Evidence`})]})}),(0,b.jsx)(`tbody`,{children:[...d.findings,...d.unverifiedLeads].map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[e.severity,(0,b.jsx)(`br`,{}),(0,b.jsx)(`span`,{className:`text-muted-foreground`,children:e.disposition})]}),(0,b.jsx)(`td`,{children:(0,b.jsxs)(`details`,{children:[(0,b.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:e.title}),(0,b.jsxs)(`div`,{className:`mt-2 grid gap-2`,children:[(0,b.jsx)(`p`,{children:e.description||`No description recorded.`}),e.invariant?(0,b.jsxs)(`p`,{children:[(0,b.jsx)(`strong`,{children:`Security invariant:`}),` `,e.invariant]}):null,e.reproduction.length?(0,b.jsx)(`ol`,{className:`list-decimal pl-5`,children:e.reproduction.map((e,t)=>(0,b.jsx)(`li`,{children:e},t))}):null]})]})}),(0,b.jsx)(`td`,{children:e.targetUrl??`—`}),(0,b.jsx)(`td`,{children:e.rootCause||`Not recorded`}),(0,b.jsx)(`td`,{children:e.impact||`Not recorded`}),(0,b.jsx)(`td`,{children:e.remediation||`Not recorded`}),(0,b.jsx)(`td`,{children:e.evidenceRefs.length?e.evidenceRefs.map(e=>(0,b.jsx)(`code`,{className:`block`,children:e.slice(0,12)},e)):`No linked refs`})]},e.fingerprint))})]})}):null]}):u.isError?(0,b.jsx)(`p`,{className:`text-destructive`,children:`Could not read the local finding record.`}):(0,b.jsx)(`p`,{children:`Loading findings…`})]}):null]})}function Uj(e){return e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var Wj=[`Reported`,`Confirmed`,`Remediating`,`Resolved`],Gj={open:0,unverified:0,confirmed:1,remediating:2,remediated:3,verified:3},Kj={false_positive:`Dismissed as a false positive`,accepted_risk:`Accepted as residual risk`,suppressed:`Suppressed`};function qj(e){let t={label:`Confirm as risk`,status:`confirmed`,icon:(0,b.jsx)(tp,{size:14})},n={label:`Dismiss (false positive)`,status:`false_positive`,icon:(0,b.jsx)(Of,{size:14}),variant:`outline`},r={label:`Start remediation`,status:`remediating`,icon:(0,b.jsx)(pp,{size:14})},i={label:`Mark resolved`,status:`remediated`,icon:(0,b.jsx)(Sf,{size:14})},a={label:`Verify fix`,status:`verified`,icon:(0,b.jsx)(np,{size:14})},o={label:`Accept risk`,status:`accepted_risk`,icon:(0,b.jsx)(np,{size:14}),variant:`outline`},s={label:`Reopen`,status:`confirmed`,icon:(0,b.jsx)(gf,{size:14}),variant:`outline`};switch(e){case`open`:case`unverified`:return[t,n];case`confirmed`:return[r,i,o,n];case`remediating`:return[i,a,o];case`remediated`:return[a,s];case`verified`:return[s];default:return[{...s,label:`Reopen finding`}]}}function Jj({findingId:e,onBack:t}){let n=Bd(),r=tf({queryKey:[`finding`,e],queryFn:()=>hx.finding(e)}),i=nf({mutationFn:t=>hx.updateFindingStatus(e,t),onSuccess:()=>{n.invalidateQueries({queryKey:[`finding`,e]}),n.invalidateQueries({queryKey:[`findings`]}),n.invalidateQueries({queryKey:[`overview`]})}});if(r.isLoading)return(0,b.jsx)(h,{children:(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`Loading finding…`})});if(r.isError||!r.data)return(0,b.jsx)(h,{children:(0,b.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,b.jsx)(`p`,{className:`text-destructive`,children:`Could not load this finding.`}),t?(0,b.jsxs)(o,{variant:`outline`,size:`sm`,onClick:t,children:[(0,b.jsx)(gf,{size:14}),` Back`]}):null]})});let a=r.data.finding,s=Tx(a.severity),c=Ax(a.category,a.title),l=vx(c.stage),u=Gj[a.status],d=Kj[a.status],f=qj(a.status);return(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsxs)(`div`,{className:`grid gap-2`,children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,b.jsx)(qx,{variant:Kx(s),children:wx[s]}),(0,b.jsx)(qx,{variant:Kx(a.status),children:Xj(a.status)}),a.cvssScore==null?null:(0,b.jsxs)(qx,{variant:`outline`,children:[`CVSS `,a.cvssScore]})]}),(0,b.jsx)(`h1`,{className:`text-xl font-semibold`,children:a.title}),(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[a.path??`unscoped asset`,a.line==null?``:`:${a.line}`,` · Stage `,c.stage,` `,yx(l),` · Pillar `,bx[c.pillar],c.inferred?` (inferred)`:``]})]}),t?(0,b.jsxs)(o,{variant:`outline`,size:`sm`,onClick:t,children:[(0,b.jsx)(gf,{size:14}),` Back`]}):null]}),(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Resolution`}),d?(0,b.jsx)(qx,{variant:`secondary`,children:d}):null]}),d?(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`This finding is off the remediation track. Reopen it to return it to the queue.`}):(0,b.jsx)(`ol`,{className:`mt-1 grid grid-cols-4 gap-2`,"aria-label":`Resolution progress`,children:Wj.map((e,t)=>(0,b.jsxs)(`li`,{className:`grid gap-1.5`,children:[(0,b.jsx)(`span`,{className:`h-1.5 rounded-full`,style:{background:u!=null&&t<=u?`var(--good)`:`var(--border)`},"aria-hidden":`true`}),(0,b.jsx)(`span`,{className:u===t?`text-xs font-semibold`:`text-muted-foreground text-xs`,children:e})]},e))})]}),(0,b.jsxs)(h,{children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Verify & triage`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Move this finding through its lifecycle. Changes are audited.`}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:f.map(e=>(0,b.jsxs)(o,{size:`sm`,variant:e.variant??`default`,disabled:i.isPending,onClick:()=>i.mutate(e.status),children:[e.icon,` `,e.label]},`${e.label}:${e.status}`))}),i.isError?(0,b.jsxs)(`p`,{className:`text-destructive text-sm`,children:[`Update failed: `,String(i.error?.message??i.error)]}):null]}),a.description?(0,b.jsxs)(h,{children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Description`}),(0,b.jsx)(Lj,{children:a.description})]}):null,a.remediation?(0,b.jsxs)(h,{children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Remediation`}),(0,b.jsx)(Lj,{children:a.remediation})]}):null,(0,b.jsxs)(h,{children:[(0,b.jsxs)(`h3`,{className:`text-sm font-semibold`,children:[`Evidence (`,a.evidence.length,`)`]}),a.evidence.length?(0,b.jsx)(`div`,{className:`grid gap-2`,children:a.evidence.map(e=>(0,b.jsx)(Ux,{title:`${e.kind}${e.reason?` — ${e.reason}`:``}`,detail:(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[new Date(e.createdAt).toLocaleString(),e.runID?` · run ${e.runID.slice(0,12)}`:``]}),verdict:e.verdict},e.id))}):(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`No operation-level evidence linked yet. Source findings stay unverified until evidence confirms them.`})]}),(a.cwe||a.cve||a.cvssVector||a.assignee||a.resolvedAt)&&(0,b.jsxs)(h,{children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold`,children:`Metadata`}),(0,b.jsxs)(`dl`,{className:`grid gap-1.5 text-sm sm:grid-cols-2`,children:[a.cwe?(0,b.jsx)(Yj,{k:`CWE`,v:a.cwe}):null,a.cve?(0,b.jsx)(Yj,{k:`CVE`,v:a.cve}):null,a.cvssVector?(0,b.jsx)(Yj,{k:`CVSS vector`,v:a.cvssVector,mono:!0}):null,a.assignee?(0,b.jsx)(Yj,{k:`Assignee`,v:a.assignee}):null,a.resolvedAt?(0,b.jsx)(Yj,{k:`Resolved`,v:new Date(a.resolvedAt).toLocaleString()}):null,(0,b.jsx)(Yj,{k:`Fingerprint`,v:a.fingerprint,mono:!0})]})]})]})}function Yj({k:e,v:t,mono:n}){return(0,b.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,b.jsx)(`dt`,{className:`text-muted-foreground text-2xs w-28 shrink-0 font-semibold tracking-[0.08em] uppercase`,children:e}),(0,b.jsx)(`dd`,{className:n?`font-mono text-xs break-all`:``,children:t})]})}function Xj(e){return e.replace(/[-_]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var Zj=null;function Qj(e,t){e.currentIndex=0,e.wipContextDeps=null,e.wipCommitCallbacks=[];let n=Zj;Zj=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{Zj=n}}function $j(){if(!Zj)throw Error(`No resource fiber available`);return Zj}function eM(){return Zj}var tM=typeof process<`u`&&!1,nM=e=>({version:0,committedVersion:0,dispatchUpdate:e,changelog:[],committedLog:[],unsettledCount:0,rollbackCallbacks:[]}),rM=e=>{e.committedVersion=e.version;for(let t of e.changelog)t.logged=!1,t.settled||(t.settled=!0,e.unsettledCount--),e.committedLog.push(t);e.changelog.length=0,e.unsettledCount===0&&(e.committedLog.length=0),e.rollbackCallbacks.length=0},iM=(e,t)=>{let n=e.version>t;if(e.version=t,n){for(let t=0;t<e.rollbackCallbacks.length;t++)e.rollbackCallbacks[t]();if(e.rollbackCallbacks.length=0,t<=e.committedVersion){let n=[];for(;e.committedVersion-n.length>t;){let t=e.committedLog.pop();if(t===void 0){if(tM)throw Error(`tap: committed history is shorter than the replay base.`);break}cM(t.fiber,t.cell),t.cell.workInProgress=t.prevState,n.push({record:t,prevState:t.prevState,eagerState:t.eagerState,hasEagerState:t.hasEagerState})}if(n.length>0){let t=e.committedVersion;sM(e,()=>{for(let t=n.length-1;t>=0;t--){let r=n[t];r.record.prevState=r.prevState,r.record.eagerState=r.eagerState,r.record.hasEagerState=r.hasEagerState,e.committedLog.push(r.record)}e.committedVersion=t})}e.committedVersion=t;for(let t of e.changelog)t.logged=!1;e.changelog.length=0}else{for(;e.committedVersion+e.changelog.length>t;)e.changelog.pop().logged=!1;for(let t=0;t<e.changelog.length;t++)aM(e.changelog[t]);rM(e)}}},aM=e=>{cM(e.fiber,e.cell),e.queued||(e.queued=!0,(e.cell.queue??=[]).push(e))},oM=(e,t)=>{e.wipCommitCallbacks.push(t)},sM=(e,t)=>{e.rollbackCallbacks.push(t)},cM=(e,t)=>{t.isDirty||(t.isDirty=!0,e.markDirty?.(),sM(e.root,()=>{if(t.queue!==null){for(let e of t.queue)e.queued=!1;t.queue=null}t.workInProgress=t.current,t.isDirty=!1}))},lM=Symbol.for(`react.memo_cache_sentinel`),uM=e=>Array(e).fill(lM),dM=(e,t)=>{let n=e.memoCache,r=n.workInProgress;if(r===null){let t=n.current;r=t===null?[]:t.map(e=>e.slice()),n.workInProgress=r,sM(e.root,()=>{n.workInProgress=null})}let i=n.index++,a=r[i];return a===void 0?(a=uM(t),r[i]=a):tM&&a.length!==t&&console.error(`Expected a constant size argument for each invocation of c(). The previous cache was allocated with size ${a.length} but size ${t} was requested.`),a},fM=e=>dM($j(),e),pM=y.default.__COMPILER_RUNTIME?.c??(e=>(0,y.useMemo)(()=>{let t=uM(e);return t[lM]=!0,t},[])),mM=()=>eM()!==null,J=e=>mM()?fM(e):pM(e),hM=(e,...t)=>Object.assign(Object.create(null),e,...t),gM=()=>{throw Error(`Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.`)},_M=()=>{throw Error(`Hook order changed between renders`)},vM=()=>({type:`effect`,setup:void 0,setupDeps:void 0,cleanup:void 0,deps:null,generation:0});function yM(e,t){let n=$j(),r=n.currentIndex++,i=n.cells[r],a=i===void 0?vM():i.type===`effect`?i:_M();if(i===void 0&&(n.isFirstRender||gM(),n.cells[r]=a,n.effectCells.push(a)),a.deps!==null&&!!t!=!!a.deps)throw Error(`useEffect called with and without dependencies across re-renders`);oM(n,()=>{a.setup=e,a.setupDeps=t,a.generation++})}var bM=(e,t)=>{tM&&e.length!==t.length&&console.error(`The final argument passed to a hook changed size between renders. The order and size of this array must remain constant.
89
89
 
90
- Previous: [${e.join(`, `)}]\nIncoming: [${t.join(`, `)}]`);for(let n=0;n<e.length&&n<t.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0},bM=(e,t)=>{aM(e,()=>{t.current=t.wip,t.currentDeps=t.wipDeps,t.isDirty=!1})},xM=(e,t)=>{let n=Qj(),r=n.currentIndex++,i=n.cells[r];if(i===void 0){n.isFirstRender||hM();let a=e();return eM&&n.devStrictMode&&e(),i={type:`memo`,current:a,currentDeps:t,wip:a,wipDeps:t,isDirty:!1},n.cells[r]=i,a}i.type!==`memo`&&gM();let a=i;if(yM(a.wipDeps,t))return a.isDirty&&bM(n,a),a.wip;let o=e();return eM&&n.devStrictMode&&e(),a.wip=o,a.wipDeps=t,a.isDirty||(a.isDirty=!0,oM(n.root,()=>{a.wip=a.current,a.wipDeps=a.currentDeps,a.isDirty=!1})),bM(n,a),o};function SM(e){return xM(()=>({current:e}),[])}var CM=Symbol(`tap.Context.defaultValue`),wM=e=>e,TM=new Map,EM=new Set,DM=()=>new Map(TM),OM=(e,t)=>{let n=TM;TM=e;try{return t()}finally{TM=n}},kM=(e,t)=>{e[CM]=t},AM=e=>typeof e==`object`&&!!e&&CM in e,jM=e=>typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===Symbol.for(`react.context`),MM=e=>AM(e)||jM(e),NM=e=>{if(!AM(e)){if(jM(e)){kM(e,e._currentValue??e._currentValue2);return}throw Error("A tap resource's `use()` only accepts a tap context.")}},PM=(e,t,n)=>{if(typeof e!=`object`||!e)throw Error(`useContextProvider only accepts a React context.`);NM(e);let r=e,i=Qj(),a=SM(void 0),o=a.current===void 0||!Object.is(a.current.value,t);vM(()=>{a.current={value:t}},[t]);let s=TM.get(r),c=s!==void 0||TM.has(r);TM.set(r,{value:t,source:i});try{return FM(r,o,n)}finally{c?TM.set(r,s):TM.delete(r)}},FM=(e,t,n)=>{let r=EM.has(e);t?EM.add(e):EM.delete(e);try{return n()}finally{r?EM.add(e):EM.delete(e)}},IM=e=>{NM(e);let t=e,n=LM(t,e),r=Qj();return(r.wipContextDeps??=new Map).set(t,n.source),n.value},LM=(e,t)=>TM.get(e)??{value:wM(t)[CM],source:null},RM=(e,t,n,r)=>{if(!r)return n;let i=n;for(let[n,a]of r)a!==t&&a!==e&&(i??=new Map).set(n,a);return i},zM=(e,t=e.wipContextDeps)=>{let n=$j();n&&t&&(n.wipContextDeps=RM(n,e,n.wipContextDeps,t))},BM=()=>EM.size>0,VM=e=>{if(!e.contextDeps||!BM())return!1;for(let t of EM.keys())if(e.contextDeps.has(t))return!0;return!1},HM=(e,t,n)=>{if(e.isNeverMounted)throw Error(`Resource updated before mount`);let r=!1,i=!0;e.root.unsettledCount++,e.root.dispatchUpdate(()=>r?i:(r=!0,n&&e.root.changelog.length===0&&!t.cell.isDirty&&!t.hasEagerState&&(t.prevState=t.cell.workInProgress,t.eagerState=n(t.cell.workInProgress,t.action),t.hasEagerState=!0,i=!Object.is(t.cell.current,t.eagerState),!i&&!t.settled&&(t.settled=!0,e.root.unsettledCount--)),i),()=>(r=!0,i=!0,iM(t),t.logged||(t.logged=!0,e.root.changelog.push(t)),!0))},UM=(e,t,n,r,i)=>{let a=r?r(n):n;eM&&e.devStrictMode&&r&&r(n);let o={type:`reducer`,workInProgress:a,current:a,isDirty:!1,queue:null,renderQueue:null,reducer:t,dispatch:n=>{let r=$j();if(r!==null){if(r!==e)throw Error(`Cannot update a resource while rendering a different resource.`);(e.renderPendingCells??=new Set).add(o),(o.renderQueue??=[]).push(n)}else HM(e,{fiber:e,cell:o,action:n,hasEagerState:!1,eagerState:void 0,prevState:o.current,settled:!1,queued:!1,logged:!1},i?t:void 0)}};return o};function WM(e,t,n,r){let i=Qj(),a=i.currentIndex++,o=i.cells[a],s=(()=>{if(o!==void 0)return o.type===`reducer`?o:gM();i.isFirstRender||hM();let s=UM(i,e,t,n,r);return i.cells[a]=s,s})(),c=s.queue;if(c!==null){let t=e===s.reducer;for(let n=0;n<c.length;n++){let r=c[n];!r.hasEagerState||!t||!Object.is(r.prevState,s.workInProgress)?(r.prevState=s.workInProgress,r.eagerState=e(s.workInProgress,r.action),r.hasEagerState=!0,eM&&i.devStrictMode&&(r.eagerState=e(s.workInProgress,r.action))):eM&&i.devStrictMode&&e(s.workInProgress,r.action),r.queued=!1,s.workInProgress=r.eagerState}s.queue=null}if(s.reducer=e,s.renderQueue!==null){let t=s.workInProgress;for(let n of s.renderQueue)t=e(t,n);s.renderQueue=null,i.renderPendingCells?.delete(s),Object.is(t,s.workInProgress)||(sM(i,s),s.workInProgress=t)}return s.isDirty&&aM(i,()=>{s.current=s.workInProgress,s.isDirty=!1}),[s.workInProgress,s.dispatch]}function GM(e,t,n){return WM(e,t,n,!1)}var KM=(e,t)=>typeof t==`function`?t(e):t,qM=e=>e===void 0?void 0:typeof e==`function`?e():e;function JM(e){return WM(KM,e,qM,!0)}var YM=(e,t)=>xM(()=>e,t);function XM(e){let t=Qj(),n=SM(e);return n.current!==e&&aM(t,()=>{n.current=e}),YM(((...e)=>{if(eM&&$j())throw Error(`useEffectEvent cannot be called during render`);return n.current(...e)}),[])}var ZM=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,QM=()=>{},$M=e=>{let t=e;switch(typeof t.status==`string`?t.status!==`fulfilled`&&t.status!==`rejected`&&e.then(QM,QM):(t.status=`pending`,e.then(e=>{t.status===`pending`&&(t.status=`fulfilled`,t.value=e)},e=>{t.status===`pending`&&(t.status=`rejected`,t.reason=e)})),t.status){case`fulfilled`:return t.value;case`rejected`:throw t.reason;default:throw e}},eN=e=>ZM(e)?$M(e):IM(e),tN=!1,nN=(e,t,n=t)=>{let r=Qj().isNeverMounted,i=r?n():t();eM&&!tN&&(!r||n===t)&&(Object.is(i,t())||(tN=!0,console.error(`The result of getSnapshot should be cached to avoid an infinite loop`)));let[,a]=GM(e=>e+1,0),o=SM(0),s=XM(()=>{try{if(Object.is(i,t()))return o.current=0,!1}catch{}return!0});return vM(()=>e(()=>{s()&&a()}),[e]),vM(()=>{if(s()){if(++o.current>50)throw o.current=0,Error(`Maximum update depth exceeded. The result of getSnapshot should be cached to avoid an infinite loop.`);a()}},[e,i,t]),i},rN=(e,t)=>{},iN=0,aN=()=>{let e=SM(null);return e.current??=`:tap${iN++}:`,e.current},oN=(e,t,n)=>{let r=()=>{if(!e)return;let n=t();if(typeof e==`function`){let t=e(n);return typeof t==`function`?t:()=>e(null)}return e.current=n,()=>{e.current=null}};n==null?vM(r):vM(r,[...n,e])},sN=y.default;function cN(e){let t=(0,y.useRef)(e);return(0,y.useInsertionEffect)(()=>{t.current=e}),(0,y.useCallback)(((...e)=>t.current(...e)),[])}var lN=sN.useEffectEvent??cN,uN=()=>$j()!==null,dN=y.default,fN=e=>uN()?JM(e):dN.useState(e),pN=(e,t,n)=>uN()?GM(e,t,n):dN.useReducer(e,t,n),Y=e=>uN()?SM(e):dN.useRef(e),mN=(e,t)=>uN()?xM(e,t):dN.useMemo(e,t),hN=(e,t)=>uN()?YM(e,t):dN.useCallback(e,t),X=(e,t)=>uN()?vM(e,t):dN.useEffect(e,t),gN=(e,t)=>uN()?vM(e,t):dN.useLayoutEffect(e,t),_N=e=>uN()?XM(e):lN(e),vN=(e,t,n)=>uN()?nN(e,t,n):dN.useSyncExternalStore(e,t,n),yN=(e,t)=>uN()?void 0:dN.useDebugValue(e,t),bN=(e,t)=>uN()?vM(e,t):dN.useInsertionEffect(e,t),xN=()=>uN()?aN():dN.useId(),SN=(e,t,n)=>uN()?oN(e,t,n):dN.useImperativeHandle(e,t,n),Z=e=>dN.forwardRef(e),CN=(e,t)=>dN.memo(e,t),wN=dN.Fragment,TN=(...e)=>dN.createElement(...e),EN=(...e)=>dN.cloneElement(...e),DN=e=>dN.isValidElement(e);dN.Children,dN.Suspense;var ON=e=>{let t=dN.createContext(e);return kM(t,e),t},kN=e=>uN()&&MM(e)?eN(e):dN.use(e),AN=e=>uN()&&MM(e)?eN(e):dN.useContext(e);function jN(e){return(...t)=>({hook:e,args:t})}function MN(e,t,n){return typeof t==`function`?(...n)=>MN(e,t(...n)):n?{...t,key:e,deps:n}:{...t,key:e}}var NN=(e,t)=>{if(e.length!==0){if(e.length===1)throw e[0];for(let t of e)console.error(t);throw AggregateError(e,t)}},PN=50,FN={schedulers:new Set,isScheduled:!1},IN=null,LN=[],RN=class{_isDirty=!1;_task;constructor(e){this._task=e}get isDirty(){return this._isDirty}markDirty(){if(IN&&(IN.get(this)??0)>=PN)throw Error(`Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside useEffect.`);this._isDirty=!0,FN.schedulers.add(this),VN()}runTask(){IN?.set(this,(IN.get(this)??0)+1),this._isDirty=!1,this._task()}settle(){this._isDirty=!1}},zN=[];new RN(()=>{let e=zN.splice(0),t=[];for(let n of e)try{n()}catch(e){t.push(e)}NN(t,`Errors occurred while running scheduled tasks`)});var BN=e=>{if(IN!==null){LN.push(e);return}e()},VN=()=>{FN.isScheduled||(FN.isScheduled=!0,UN())},HN=()=>{let e=IN;IN=new Map;let t=[];try{for(let e of FN.schedulers)if(FN.schedulers.delete(e),e.isDirty)try{e.runTask()}catch(e){t.push(e)}}finally{if(IN=e,FN.schedulers.clear(),FN.isScheduled=!1,IN===null)for(;LN.length>0;)try{LN.shift()()}catch(e){t.push(e)}}NN(t,`Errors occurred during flushSync`)},UN=(()=>{if(typeof MessageChannel<`u`){let e=null,t;return()=>{if(!e){let n=new MessageChannel;n.port1.onmessage=()=>{e?.unref?.(),HN()},e=n.port1,t=n.port2}e.ref?.(),t.postMessage(null)}}return()=>setTimeout(HN,0)})(),WN=e=>{if(IN!==null)return eM&&console.warn(`flushTapSync was called from inside a render or commit. The flush is deferred until the current pass completes.`),e();let t=FN;FN={schedulers:new Set,isScheduled:!0};try{let t=e();return HN(),t}finally{let e=FN.schedulers;if(FN=t,e.size>0){for(let t of e)FN.schedulers.add(t);VN()}}};function GN(e){let t=[];for(let n=0;n<e.length;n++)try{e[n]()}catch(e){t.push(e)}NN(t,`Errors during commit`)}function KN(e){let t=e.setup,n=e.setupDeps,r=e.generation,i;try{let e=t();if(e!==void 0&&typeof e!=`function`)throw Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof e}`);i=e}finally{e.generation===r?(e.cleanup=i,e.deps=n):i?.()}}var qN=e=>e.setup===void 0?!1:e.deps===null||e.setupDeps===void 0||!yM(e.deps,e.setupDeps);function JN(e){let t=[],n=[];for(let t of e.effectCells)qN(t)&&n.push(t);for(let e of n)if(e.deps=null,e.cleanup!==void 0)try{e.cleanup()}catch(e){t.push(e)}finally{e.cleanup=void 0}for(let e of n)try{KN(e)}catch(e){t.push(e)}NN(t,`Errors during commit`)}function YN(e){let t=[];for(let n of e.effectCells)if(n.deps=null,n.cleanup)try{n.cleanup?.()}catch(e){t.push(e)}finally{n.cleanup=void 0}NN(t,`Errors during cleanup`)}var XN={useState:JM,useReducer:GM,useRef:SM,useMemo:xM,useCallback:YM,useEffect:vM,useLayoutEffect:vM,useInsertionEffect:vM,useEffectEvent:XM,useContext:IM,use:eN,useSyncExternalStore:nN,useDebugValue:rN,useId:aN,useImperativeHandle:oN,useMemoCache:dM},ZN=y.default,QN=ZN.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE??ZN.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,$N=QN==null?null:`H`in QN?{get current(){return QN.H},set current(e){QN.H=e}}:`ReactCurrentDispatcher`in QN?{get current(){return QN.ReactCurrentDispatcher.current},set current(e){QN.ReactCurrentDispatcher.current=e}}:null;function eP(e){if(!$N)return e();let t=$N.current;$N.current=XN;try{return e()}finally{$N.current=t}}function tP(e,t,n=void 0,r){return{hook:e,root:t,markDirty:n,devStrictMode:r,cells:[],effectCells:[],contextDeps:null,wipContextDeps:null,wipCommitCallbacks:null,memoCache:{current:null,workInProgress:null,index:0},renderPendingCells:null,currentIndex:0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function nP(e){e.wipCommitCallbacks=null,e.wipContextDeps=null,e.memoCache.workInProgress=null}function rP(e){e.isMounted&&(e.isMounted=!1,YN(e))}function iP(e,t){if(e.renderPendingCells!==null){for(let t of e.renderPendingCells)t.renderQueue=null;e.renderPendingCells.clear()}let n=0,r;try{do{if(++n>25)throw Error(`Too many re-renders. tap limits the number of renders to prevent an infinite loop.`);e.memoCache.index=0,Zj(e,()=>{r=eP(()=>e.hook(...t))})}while((e.renderPendingCells?.size??0)>0)}catch(t){throw nP(e),t}return zM(e),r}function aP(e){let t=e.wipCommitCallbacks;e.wipCommitCallbacks=null;let n=eM&&!e.isMounted&&e.devStrictMode===`root`;e.isMounted=!0,e.isNeverMounted=!1,t!==null&&(e.contextDeps=e.wipContextDeps,nM(e.root),e.memoCache.workInProgress!==null&&(e.memoCache.current=e.memoCache.workInProgress,e.memoCache.workInProgress=null),GN(t)),n&&(JN(e),YN(e)),JN(e)}var oP=()=>{let e=Qj();return e.devStrictMode?e.isFirstRender?`child`:`root`:null},sP=()=>`child`,cP=()=>null,lP=()=>{if(!eM)return cP;let e=Y(0);return fN(()=>e.current++),e.current===2?sP:cP},uP=()=>$j()?oP:lP(),dP=e=>e(),fP=e=>{let t=[];for(let n of e)try{n()}catch(e){t.push(e)}NN(t,`Errors occurred while notifying Tap root subscribers`)},pP=(e,t,n)=>{let r=new RN(()=>s.handleUpdate()),i=[],a=tM((e,t)=>{(i.length!==0||e())&&(i.push(t),r.markDirty())}),o=tP(dP,a,void 0,t),s={scheduler:r,queue:i,fiber:o,subscribers:new Set,pendingHostRender:!1,isMounted:!1,hasRendered:!1,committedRender:e,context:new Map,value:void 0,applyQueue:()=>{rM(a,a.committedVersion);for(let e of i)eM&&o.devStrictMode&&e(),e();return rM(a,a.committedVersion+a.changelog.length),i.length},publish:(e,t)=>{r.isDirty||a.committedVersion!==t||s.value===e||(s.value=e,BN(()=>fP(s.subscribers)))},finishFlush:(e,t,n)=>{nM(a),i.splice(0,n),s.pendingHostRender=!1,i.length===0&&r.settle(),s.isMounted&&aP(o),s.publish(e,t)},handleUpdate:()=>{let e=s.applyQueue(),t;try{eM&&o.devStrictMode&&OM(s.context,()=>iP(o,[s.committedRender])),t=OM(s.context,()=>iP(o,[s.committedRender]))}catch(e){if(rM(a,a.committedVersion),ZM(e)){let t=()=>{s.isMounted&&r.markDirty()};e.then(t,t);return}if(s.isMounted){s.pendingHostRender=!0,n(e=>e+1);return}throw e}if(r.isDirty)throw Error(`Scheduler is dirty, this should never happen`);s.finishFlush(t,a.version,e)}};return s},mP=e=>{let[,t]=fN(0),n=uP(),r=Y(null),i=r.current??=pP(e,n(),t),a=DM(),o=i.scheduler.isDirty||i.pendingHostRender?i.applyQueue():0,s=OM(a,()=>iP(i.fiber,[e])),c={render:e,context:a,value:s,drained:o,wip:i.fiber.wipCommitCallbacks,version:i.fiber.root.version,processed:!1};return i.hasRendered||(i.hasRendered=!0,i.committedRender=e,i.context=a,i.value=s),X(()=>(i.isMounted=!0,()=>{i.isMounted=!1,rP(i.fiber)}),[i]),X(()=>{if(c.processed){i.fiber.isMounted||(aP(i.fiber),i.queue.length&&!i.scheduler.isDirty&&i.scheduler.markDirty());return}if(c.processed=!0,i.committedRender=c.render,i.context=c.context,i.fiber.wipCommitCallbacks!==c.wip){i.scheduler.isDirty||i.handleUpdate();return}if(c.drained>0&&i.fiber.root.version===c.version){i.finishFlush(c.value,c.version,c.drained);return}aP(i.fiber),i.publish(c.value,c.version)}),mN(()=>({getValue:()=>i.value,subscribe:e=>(i.subscribers.add(e),()=>i.subscribers.delete(e))}),[i])},hP=()=>{let e=Y(0),t=e.current,n=Qj();return{version:t,markDirty:mN(()=>()=>{e.current++,n.markDirty?.()},[n]),root:n.root}},gP=()=>{let[e]=fN(()=>tM((e,t)=>{let i=!1;r(t=>(i=!e(),i?t:t+1)),i||n(t)})),[t,n]=pN((t,n)=>(rM(e,t),t+ +!!n()),0),[,r]=fN(0);return rM(e,t),{root:e,version:t,markDirty:void 0}},_P=()=>{let e=uP(),{root:t,version:n,markDirty:r}=$j()?hP():gP();return{version:n,createFiber:hN((n,i,a)=>tP(n,t,a?()=>{a(),r?.()}:r,e()),[])}},vP=(e,t,n)=>{let r=Y(null),i=r.current??={wipDeps:null,wip:null,currentDeps:null,current:null};return i.wipDeps=i.currentDeps,i.wip=i.current,X(()=>{i.currentDeps=i.wipDeps,i.current=i.wip}),!n&&i.currentDeps&&yM(i.currentDeps,t)?i.current:(i.wipDeps=t,i.wip=e(),i.wip)};function yP(e){let{version:t,createFiber:n}=_P(),r=mN(()=>n(e.hook,e.key),[e.hook,e.key,n]),i=vP(()=>({value:iP(r,e.args)}),[r,t,e.args],VM(r));return X(()=>()=>rP(r),[r]),X(()=>{aP(r)},[r,i]),i.value}var bP=(e,t)=>{let n=e.get(t);n&&(n.isDirty=!0)},xP=(e,t)=>!e.isDirty&&!VM(e.fiber)&&t!==void 0&&e.committedDeps!==void 0&&yM(e.committedDeps,t),SP=e=>{if(!BM())return!1;for(let{fiber:t}of e.values())if(VM(t))return!0;return!1};function CP(e){let[t]=fN(()=>new Map),{version:n,createFiber:r}=_P(),i=SP(t),a=vP(()=>{let n=new Set,i=[],a=0;for(let o=0;o<e.length;o++){let s=e[o],c=s.key;if(c===void 0)throw Error(`useResources did not provide a key for array at index ${o}`);if(n.has(c))throw Error(`Duplicate key ${c} in useResources`);n.add(c);let l=t.get(c);if(!l){let e=r(s.hook,s.key,()=>bP(t,c));l={fiber:e,next:{value:iP(e,s.args),deps:s.deps},isDirty:!1,committedDeps:void 0,committedValue:void 0},a++,t.set(c,l)}else if(l.fiber.hook!==s.hook){let e=r(s.hook,s.key,()=>bP(t,c)),n=iP(e,s.args);l.next={value:n,deps:s.deps,remount:e}}else if(xP(l,s.deps))typeof l.next==`object`&&nP(l.fiber),l.fiber.contextDeps&&zM(l.fiber,l.fiber.contextDeps),l.next=`skip`;else{let e=iP(l.fiber,s.args);l.next={value:e,deps:s.deps}}i.push(typeof l.next==`object`?l.next.value:l.committedValue)}if(t.size>i.length-a)for(let e of t.keys())n.has(e)||(t.get(e).next=`delete`);return i},[e,t,r,n],i);return X(()=>()=>{for(let e of t.keys())rP(t.get(e).fiber)},[t]),X(()=>{for(let[e,n]of t.entries()){let r=n.next;r===`delete`?(rP(n.fiber),t.delete(e)):r===`skip`?!n.fiber.isNeverMounted&&!n.fiber.isMounted&&aP(n.fiber):(r.remount&&(rP(n.fiber),n.fiber=r.remount),aP(n.fiber),n.committedDeps=r.deps,n.committedValue=r.value,n.isDirty=!1,n.next=`skip`)}},[a,t]),a}var wP=e=>e(),TP=e=>{let{createFiber:t}=_P(),n=mN(()=>t(wP,void 0),[t]),r=iP(n,[e]);X(()=>()=>{rP(n)},[n]);let i=!1,a=()=>{i&&n.isMounted||(i=!0,aP(n))};return X(a),{value:r,effects:a}},EP=jN(()=>{let e=J(4),[t,n]=fN(DP),r;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(e,t)=>(n(n=>{let r=mM(n.renderers);return r[e]=[...r[e]??[],t],{...n,renderers:r}}),()=>{n(n=>{let r=mM(n.renderers),i=r[e]?.filter(e=>e!==t)??[];return i.length>0?r[e]=i:delete r[e],{...n,renderers:r}})}),e[0]=r):r=e[0];let i=r,a;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=e=>(n(t=>({...t,fallbacks:[...t.fallbacks,e]})),()=>{n(t=>({...t,fallbacks:t.fallbacks.filter(t=>t!==e)}))}),e[1]=a):a=e[1];let o=a,s;return e[2]===t?s=e[3]:(s={getState:()=>t,setDataUI:i,setFallbackDataUI:o},e[2]=t,e[3]=s),s});function DP(){return{renderers:mM(),fallbacks:[]}}var OP=e=>{if(!e.overwrite)return e;let{overwrite:t,...n}=e;return n},kP=e=>{let t=Array.from(e).map(e=>e.getModelContext()).sort((e,t)=>(t.priority??0)-(e.priority??0)),n=mM();return t.reduce((e,t)=>{let r=t.priority??0;if(t.system&&(e.system?e.system+=`\n\n${t.system}`:e.system=t.system),t.tools)for(let[i,a]of Object.entries(t.tools)){let t=e.tools!==void 0&&Object.hasOwn(e.tools,i)?e.tools[i]:void 0;if(t&&t!==a){let o=n[i];if(o===r){if(!a.overwrite)throw Error(`You tried to define a tool with the name ${i}, but it already exists.`);e.tools[i]=OP(a);continue}let s=o>r?t:a,c=o>r?a:t;e.tools[i]=OP({...c,...s}),n[i]=Math.max(o,r);continue}e.tools||=mM(),e.tools[i]=OP(a),Object.hasOwn(n,i)||(n[i]=r)}return t.config&&(e.config={...e.config,...t.config}),t.callSettings&&(e.callSettings={...e.callSettings,...t.callSettings}),t.unstable_composerMetadata&&(e.unstable_composerMetadata={...e.unstable_composerMetadata,...t.unstable_composerMetadata}),e},{})},AP=(e,t,n)=>{let r=e=>{console.error(`[assistant-ui] ${n} listener threw an error`,e)};for(let n of e)try{let e=n(typeof t==`function`?t():t);e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`&&Promise.resolve(e).catch(r)}catch(e){r(e)}},jP=e=>e,MP=new Set([`$$typeof`,`nodeType`,`then`,`__v_raw`,`__v_isRef`,`__v_isReactive`,`__v_isReadonly`,`__v_isShallow`,`__v_skip`]),NP=(e,t)=>{if(e===Symbol.toStringTag)return t;if(typeof e!=`symbol`){if(e===`toJSON`)return()=>t;if(!MP.has(e))return!1}},PP=class{getOwnPropertyDescriptor(e,t){let n=this.get(e,t);if(n!==void 0)return{value:n,writable:!1,enumerable:!0,configurable:!0}}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}},FP=Symbol(`assistant-ui.store.clientId`),IP=Symbol(`assistant-ui.store.instanceTag`),LP=(e,t)=>{let n=new Proxy((()=>{}),{apply:()=>(t(),n),get:(n,r)=>r===`source`?e.source:r===`query`?e.query:r===`name`?e.name:r===FP?VP(t()):t()[r],has:(e,n)=>n===`source`||n===`query`||n===`name`||n===FP||n in t(),ownKeys:()=>Reflect.ownKeys(t()),getOwnPropertyDescriptor:(e,n)=>{if(typeof n!=`symbol`&&n in t())return{value:t()[n],writable:!1,enumerable:!0,configurable:!0}}});return n},RP=(e,t)=>{let n=()=>{throw Error(e)};return new Proxy((()=>{}),{apply:n,get:(e,r)=>{if(r===`source`||r===`query`)return null;if(r===`name`)return t;if(r===FP)return n();let i=NP(r,`AssistantClientAccessor`);return i===!1?n():i},has:(e,t)=>t===`source`||t===`query`||t===`name`,ownKeys:()=>[],getOwnPropertyDescriptor:()=>void 0})},zP=e=>e?.source!=null,BP=e=>e?.source===null,VP=e=>e[FP]??e,HP=e=>e[IP]??VP(e),UP=e=>e===`optional`||e===`subscribe`||e===`on`||e===`__proto__`||typeof e==`symbol`,WP=e=>{let t=[];for(let n in e)UP(n)||t.push(n);return t},GP=class extends PP{#e;constructor(e){super(),this.#e=e}get(e,t){let n=NP(t,`OptionalAssistantClient`);if(n!==!1)return n;if(UP(t))return;let r=this.#e[t];return zP(r)?r:void 0}ownKeys(){return WP(this.#e)}has(e,t){return!UP(t)&&t in this.#e}},KP=e=>new Proxy({},new GP(e)),qP=()=>()=>{},JP=`You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.`,YP=class extends PP{#e;#t;#n;#r;constructor(e,t,n){super(),this.#e=e,this.#t=t,this.#n=n}get(e,t){if(t===`subscribe`||t===`on`)return qP;if(t===`optional`)return this.#r??=KP(this.#n());let n=NP(t,this.#e);return n===!1?RP(this.#t(String(t)),String(t)):n}ownKeys(){return[`subscribe`,`on`,`optional`]}getOwnPropertyDescriptor(e,t){if(t!==`optional`)return super.getOwnPropertyDescriptor(e,t);let n=this.get(e,t);if(n!==void 0)return{value:n,writable:!1,enumerable:!1,configurable:!0}}has(e,t){return t===`subscribe`||t===`on`||t===`optional`}},XP=((e,t)=>{let n=new Proxy({},new YP(e,t,()=>n));return n})(`DefaultAssistantClient`,()=>JP),ZP=()=>new Proxy({},{get(e,t){let n=NP(t,`AssistantClient`);return n===!1?RP(`The current scope does not have a "${String(t)}" property.`,String(t)):n}}),QP=ON(XP),$P=()=>{},eF=new WeakMap,tF=e=>eF.get(e)??$P,nF=(e,t)=>{eF.set(e,t)},rF=()=>AN(QP),iF=(e,t)=>PM(QP,e,t),aF=Symbol(`assistant-ui.transform-scopes`);function oF(e,t){let n=e;if(n[aF])throw Error(`transformScopes is already attached to this resource`);n[aF]=t}function sF(e){return e[aF]}var cF=e=>typeof e==`string`?{scope:e.split(`.`)[0],event:e}:{scope:e.scope,event:e.event},lF=e=>{console.error(`NotificationManager: event listener error`,e)},uF=(e,t,n)=>{try{let r=e(t,n);r!==null&&(typeof r==`object`||typeof r==`function`)&&typeof r.then==`function`&&Promise.resolve(r).catch(lF)}catch(e){lF(e)}},dF=()=>{let e=new Map,t=new Set,n=new Set;return{on(n,r){let i=r;if(n===`*`)return t.add(i),()=>t.delete(i);let a=e.get(n);return a||(a=new Set,e.set(n,a)),a.add(i),()=>{a.delete(i),a.size===0&&e.get(n)===a&&e.delete(n)}},emit(n,r,i){(e.has(n)||t.size!==0)&&queueMicrotask(()=>{let a=e.get(n);if(a)for(let e of a)uF(e,r,i);if(t.size>0){let e={event:n,payload:r};for(let n of t)uF(n,e,i)}})},subscribe(e){return n.add(e),()=>n.delete(e)},notifySubscribers(){for(let e of n)try{e()}catch(e){console.error(`NotificationManager: subscriber callback error`,e)}}}},fF=()=>fN(dF)[0],pF=Symbol(`assistant-ui.store.clientIndex`),mF=e=>e[pF],hF=ON([]),gF=()=>kN(hF),_F=(e,t)=>{let n=J(3),r=gF(),i;return n[0]!==e||n[1]!==r?(i=[...r,e],n[0]=e,n[1]=r,n[2]=i):i=n[2],PM(hF,i,t)},vF=ON(null),yF=Symbol(`aui.scope-effect-unapplied`),bF=(e,t)=>PM(vF,e,t),xF=()=>{let e=kN(vF);if(!e)throw Error(`AssistantTapContext is not available`);return e},SF=()=>xF().clientRef,CF=(e,t,n)=>{let r=J(8),{clientRef:i}=xF(),a;r[0]!==i||r[1]!==t||r[2]!==e?(a=()=>{let n=i.current;if(n===null)throw Error(`useAssistantScopeEffect ran before the client was committed. This is likely an internal bug in assistant-ui.`);let r=()=>{let t=i.current?.[e];return t!==void 0&&zP(t)?HP(t):void 0},a=yF,o,s=e=>{if(o?.(),o=void 0,a=yF,e!==void 0){let e=t();o=typeof e==`function`?e:void 0}a=e};s(r());let c=n.subscribe(()=>{let e=r();e!==a&&s(e)});return()=>{c(),o?.()}},r[0]=i,r[1]=t,r[2]=e,r[3]=a):a=r[3];let o;r[4]!==i||r[5]!==n||r[6]!==e?(o=[i,e,...n],r[4]=i,r[5]=n,r[6]=e,r[7]=o):o=r[7],X(a,o)},wF=()=>{let e=J(3),{emit:t}=xF(),n=gF(),r;return e[0]!==n||e[1]!==t?(r=(e,r)=>{t(e,r,n)},e[0]=n,e[1]=t,e[2]=r):r=e[2],_N(r)},TF=ON(void 0),EF=(e,t)=>{let n=kN(TF);return PM(TF,e??n,t)},DF=()=>{let e=J(3),[t]=fN(OF),n,r;return e[0]===t?(n=e[1],r=e[2]):(n=()=>()=>queueMicrotask(()=>t.abort()),r=[t],e[0]=t,e[1]=n,e[2]=r),bN(n,r),t.signal};function OF(){return new AbortController}var kF=Symbol(`assistant-ui.store.getValue`),AF=e=>{let t=e[kF];if(!t)throw Error(`Client scope contains a non-client resource. Ensure your Derived get() returns a client created with useClientResource(), not a plain resource.`);return t.getState?.()},jF=new Map;function MF(e){let t=jF.get(e);return t||(t=function(...t){if(!this||typeof this!=`object`)throw Error(`Method "${String(e)}" called without proper context. This may indicate the function was called incorrectly.`);let n=this[kF];if(!n)throw Error(`Method "${String(e)}" called on invalid client proxy. Ensure you are calling this method on a valid client instance.`);let r=n[e];if(!r)throw Error(`Method "${String(e)}" is not implemented.`);if(typeof r!=`function`)throw Error(`"${String(e)}" is not a function.`);return r(...t)},jF.set(e,t)),t}var NF=class extends PP{boundFns;cachedReceiver;outputRef;tagRef;index;constructor(e,t,n){super(),this.outputRef=e,this.tagRef=t,this.index=n}get(e,t,n){if(t===kF)return this.outputRef.current;if(t===pF)return this.index;if(t===IP)return this.tagRef.current;let r=NP(t,`ClientProxy`);if(r!==!1)return r;let i=this.outputRef.current[t];if(typeof i==`function`){if(n===void 0)return i;(!this.boundFns||this.cachedReceiver!==n)&&(this.boundFns=new Map,this.cachedReceiver=n);let e=this.boundFns.get(t);return e||(e=MF(t).bind(n),this.boundFns.set(t,e)),e}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(e,t){return t===kF||t===pF||t===IP||t in this.outputRef.current}},PF=e=>{let t=Y(null),n=Y(null),r=mN(()=>({}),[e.hook,e.key]),i=gF().length,a=mN(()=>new Proxy({},new NF(t,n,i)),[i]),o=_F(a,function(){return yP(e)});return t.current||(t.current=o,n.current=r),X(()=>{t.current=o,n.current=r}),{methods:a,state:o.getState?.(),key:e.key}},FF=jN(PF),IF=(e,t)=>{if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0}let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&Object.is(e[n],t[n]))},LF=e=>{let t=mN(()=>({}),[]);return t.v!==void 0&&IF(t.v,e)?t.v:(t.v=e,e)},RF=e=>{let t=J(2),n=Y(void 0),r;return t[0]===e?r=t[1]:(r=t=>{let r=e(t);return n.current!==void 0&&IF(n.current,r)?n.current:(n.current=r,r)},t[0]=e,t[1]=r),r},zF=(()=>{try{return!1}catch{return!1}})(),BF=(e,t)=>{let n={...e},r=new Set,i=!0;for(;i;){i=!1;for(let e of Object.values(n)){if(r.has(e.hook))continue;r.add(e.hook);let a=sF(e.hook);if(a){a(n,t),i=!0;break}}}return n},VF=e=>e.hook===uI,HF=e=>{if(!VF(e))return{source:`root`,query:{}};let t=e.args[0];return{source:t.source,query:t.query??{}}},UF=Symbol.for(`aui.event-receiver-ref`),WF=(e,t)=>{let n=e===XP?ZP():e,r=Object.create(n);Object.assign(r,t);let i;return Object.defineProperty(r,"optional",{get:()=>i??=KP(r),enumerable:!1}),r},GF=({notifications:e,clientRef:t})=>mN(()=>({subscribe:e.subscribe,on:function(n,r){if(!this)throw Error(`const { on } = useAui() is not supported. Use aui.on() instead.`);let{scope:i,event:a}=cF(n),o=n[UF];if(i!==`*`&&!o&&BP(this[i]))throw Error(`Scope "${i}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);let s=e.on(a,(e,n)=>{if(i===`*`)return r(e);let a=((o??t).current??this)[i];if(!zP(a))return;let s=VP(a);if(s===n[mF(s)])return r(e)});if(i!==`*`){if(o){if(t.parent===XP)return s}else if(BP(t.parent[i]))return s}let c=t.parent.on(n,r);return()=>{s(),c()}}}),[e,t]),KF=e=>{let t=J(5),n;t[0]===e?n=t[1]:(n=HF(e),t[0]=e,t[1]=n);let{source:r,query:i}=n,a=LF(i),o;return t[2]!==r||t[3]!==a?(o={source:r,query:a},t[2]=r,t[3]=a,t[4]=o):o=t[4],LF(o)},qF=(e,t)=>{let n=J(3),r;return n[0]!==t||n[1]!==e?(r=t?e:FF(e),n[0]=t,n[1]=e,n[2]=r):r=n[2],yP(r)},JF=jN((e,t)=>{let n=rF(),r=VF(t),i=qF(t,r),a=r?i:i.methods,o=KF(t),s=mN(()=>LP({name:e,...o},()=>a),[e,o,a]);return n[e]=s,s}),YF=e=>{let t=J(2),n;return t[0]===e?n=t[1]:(n=e.map(aI),t[0]=e,t[1]=n),CP(n)},XF=(e,t)=>{let n=LF(t),r=mN(()=>({}),[]);return r.deps!==n&&(r.deps=n,r.client=e),r.client},ZF=({parent:e,entries:t,clientRef:n,notifications:r})=>{let i=WF(e,GF({notifications:r,clientRef:n}));return{client:XF(i,[e,...bF({clientRef:n,emit:r.emit},function(){return iF(i,function(){return YF(t)})})])}},QF=({parent:e,entries:t,destroySignal:n})=>{let r=Y({parent:e,current:null}).current,{value:i,effects:a}=TP(function(){let i=fF(),{client:a}=EF(n,function(){return ZF({parent:e,entries:t,clientRef:r,notifications:i})});return X(()=>e.subscribe(i.notifySubscribers),[e,i]),X(()=>i.notifySubscribers()),a});return bN(()=>{r.parent=e,r.current=i},[i,e,r]),{client:i,effects:a}},$F=({parent:e,entries:t,destroySignal:n})=>{let r=Y({parent:e,current:null}).current,{value:i,effects:a}=TP(function(){let i=fF(),a=mP(function(){return EF(n,function(){return ZF({parent:e,entries:t,clientRef:r,notifications:i})})}),o=vN(a.subscribe,()=>a.getValue().client,()=>a.getValue().client);return X(()=>{let t=()=>WN(()=>{r.current=a.getValue().client,i.notifySubscribers()}),n=a.subscribe(t),o=e.subscribe(t);return()=>{n(),o()}},[a,e,i]),o});return bN(()=>{r.parent=e,r.current=i},[i,e,r]),{client:i,effects:a}},eI=(e,t,n,r)=>{let{get:i}=r.args[0],a=vN(e.subscribe,()=>i(e),()=>i(e)),o=KF(r),s=mN(()=>LP({name:n,...o},()=>a),[n,o,a]);return t[n]=s,s},tI=(e,t)=>{if(zF){let[e]=fN(()=>t.map(([e])=>e).join(`,`)),n=t.find(([,e])=>!VF(e));if(n)throw Error(`Scope "${n[0]}" is a root scope but this useAui mounted derived-only; remount with a new key to change scope kinds.`);let r=t.map(([e])=>e).join(`,`);if(r!==e)throw Error(`A derived-only config mounted scopes [${e}] but now has [${r}]; remount with a new key to change the scope set.`)}let n=Y({parent:e,current:null}).current,r=WF(e,{subscribe:e.subscribe,on:function(t,r){if(!this)throw Error(`const { on } = useAui() is not supported. Use aui.on() instead.`);let{scope:i,event:a}=cF(t);if(i===`*`)return e.on(t,r);let o=t[UF];if(!o&&BP(this[i]))throw Error(`Scope "${i}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);return e.on({scope:i,event:a,[UF]:o??n},r)}}),i=XF(r,[e,...t.map(([t,n])=>eI(e,r,t,n))]);return bN(()=>{n.parent=e,n.current=i},[i,e,n]),i},nI=(e,t)=>{let n=J(8),r;n[0]!==t||n[1]!==e?(r=Object.entries(BF(t,e)),n[0]=t,n[1]=e,n[2]=r):r=n[2];let i=r,a;n[3]===i?a=n[4]:(a=()=>i.length===0||i.some(oI),n[3]=i,n[4]=a);let[o]=fN(a),s;return n[5]!==i||n[6]!==o?(s={entries:i,rooted:o},n[5]=i,n[6]=o,n[7]=s):s=n[7],s},rI=(e,t,n,r)=>{let{entries:i,rooted:a}=nI(e,t);return a?n({parent:e,entries:i,destroySignal:r}):{client:tI(e,i)}},iI=(e,t,n)=>rI(e,t,QF,n);function Q(e){let t=rF();if(e){let{client:n,effects:r}=rI(t,e,$F,DF());return r&&nF(n,r),n}return t}function aI(e){let[t,n]=e;return MN(t,JF(t,n))}function oI(e){let[,t]=e;return!VF(t)}var sI=e=>{let t;class n extends PP{get(t,n){let r=NP(n,`OptionalAssistantState`);if(r!==!1)return r;let i=n;if(!UP(i)&&zP(e[i]))return AF(e[i]())}ownKeys(){return WP(e)}has(t,n){return!UP(n)&&n in e}}class r extends PP{get(r,i){let a=NP(i,`AssistantState`);if(a!==!1)return a;if(i===`optional`)return t??=new Proxy({},new n);let o=i;if(!UP(o))return AF(e[o]())}ownKeys(){return[...WP(e),`optional`]}has(t,n){return n===`optional`||!UP(n)&&n in e}}return new Proxy({},new r)},cI=new WeakMap,lI=e=>{let t=cI.get(e);return t||(t=sI(e),cI.set(e,t)),t},$=e=>{let t=J(6),n=Q(),r;t[0]===n?r=t[1]:(r=lI(n),t[0]=n,t[1]=r);let i=r,a,o;t[2]!==i||t[3]!==e?(a=()=>e(i),o=()=>e(i),t[2]=i,t[3]=e,t[4]=a,t[5]=o):(a=t[4],o=t[5]);let s=vN(n.subscribe,a,o);if(typeof s==`object`&&s&&(s===i||s===i.optional))throw Error(`You tried to return the entire AssistantState. This is not supported due to technical limitations.`);return yN(s),s},uI=e=>{let t=J(3),{get:n}=e,r=Q(),i;return t[0]!==r||t[1]!==n?(i=()=>n(r),t[0]=r,t[1]=n,t[2]=i):i=t[2],$(i)},dI=jN(uI),fI=e=>{if(e.key===void 0)throw Error(`useClientLookup: Element has no key`);return e.key};function pI(e){let t=J(12),n;t[0]===e?n=t[1]:(n=e.map(gI),t[0]=e,t[1]=n);let r=CP(n),i;t[2]===e?i=t[3]:(i=e.reduce(hI,Object.create(null)),t[2]=e,t[3]=i);let a=i,o;t[4]===r?o=t[5]:(o=r.map(mI),t[4]=r,t[5]=o);let s=o,c;t[6]!==a||t[7]!==r?(c=e=>{if(`index`in e){if(e.index<0||e.index>=r.length)throw Error(`useClientLookup: index ${e.index} out of bounds (length: ${r.length}) (ignore if recovered)`);return r[e.index].methods}let t=a[e.key];if(t===void 0)throw Error(`useClientLookup: key "${e.key}" not found (ignore if recovered)`);return r[t].methods},t[6]=a,t[7]=r,t[8]=c):c=t[8];let l;return t[9]!==s||t[10]!==c?(l={state:s,get:c},t[9]=s,t[10]=c,t[11]=l):l=t[11],l}function mI(e){return e.state}function hI(e,t,n){return e[fI(t)]=n,e}function gI(e){return MN(fI(e),FF(e),e.deps)}var _I=(e,t=0)=>t===0?Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight)<=1||e.scrollHeight<=e.clientHeight:e.scrollHeight-t-e.scrollTop-e.clientHeight<=1||e.scrollHeight-t<=e.clientHeight,vI=(e,t=0)=>t===0?e.scrollHeight>e.clientHeight+1:e.scrollHeight-t>e.clientHeight+1,yI=(e,t)=>e.scrollTop>t.scrollTop&&e.scrollHeight===t.scrollHeight,bI=Symbol(`skip-update`),xI=(e,...t)=>{let n=[];for(let r of e)try{r(...t)}catch(e){n.push(e)}if(n.length===1)throw n[0];if(n.length>1){for(let e of n)console.error(e);throw AggregateError(n)}},SI=e=>{xI(e)},CI=(e,t)=>e===void 0||t===void 0?e===t:IF(e,t),wI=class{_subscribers=new Set;subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{let t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){xI(this._subscribers)}},TI=class extends wI{_state;constructor(e){super(),this._state=e,this.subscribe=this.subscribe.bind(this),this.getState=this.getState.bind(this),this.getServerSnapshot=()=>e}getState(){return this._state}getServerSnapshot;setState(e){Object.is(e,this._state)||(this._state=e,this._notifySubscribers())}},EI=class{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(e,t){if(t){AP(this._subscriptions,e,t);return}xI(this._subscriptions,e)}_updateConnection(){if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else{let e=this._connection;this._connection=void 0,e?.()}}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},DI=class extends EI{get path(){return this.binding.path}binding;constructor(e){super(),this.binding=e;let t=e.getState();if(t===bI)throw Error(`Entry not available in the store`);this._previousState=t}_previousState;getState=()=>(this.isConnected||this._syncState(),this._previousState);_syncState(){let e=this.binding.getState();return e===bI||CI(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){let e=this.binding.subscribe(()=>{this._syncState()&&this.notifySubscribers()});return this._syncState(),e}},OI=class extends EI{get path(){return this.binding.path}binding;constructor(e){super(),this.binding=e}_previousStateDirty=!0;_previousState;getState=()=>{if(!this.isConnected||this._previousStateDirty){let e=this.binding.getState();e!==bI&&(this._previousState===void 0||!CI(e,this._previousState))&&(this._previousState=e),this._previousStateDirty=!1}if(this._previousState===void 0)throw Error(`Entry not available in the store`);return this._previousState};_connect(){let e=this.binding.subscribe(()=>{this._previousStateDirty=!0,this.notifySubscribers()});return this._previousStateDirty=!0,e}},kI=class extends EI{get path(){return this.binding.path}binding;constructor(e){super(),this.binding=e}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){let e=()=>{this.notifySubscribers()},t=this.binding.getState(),n=t?.subscribe(e),r=this.outerSubscribe(()=>{let r=this.binding.getState();if(r===t)return;t=r;let i=n;n=void 0;try{i?.()}finally{n=r?.subscribe(e),e()}});return()=>SI([()=>r?.(),()=>n?.()])}},AI=class extends EI{config;constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){let e=`Runtime event "${this.config.event}"`,t=t=>{this.notifySubscribers(t,e)},n=this.config.binding.getState(),r=n?.unstable_on(this.config.event,t),i=this.outerSubscribe(()=>{let e=this.config.binding.getState();if(e===n)return;n=e;let i=r;r=void 0;try{i?.()}finally{r=e?.unstable_on(this.config.event,t)}});return()=>SI([()=>i?.(),()=>r?.()])}},jI=class{_providers=new Map;_providerUnsubscribes=new Map;getModelContext(){return kP(new Set(this._providers.values()))}registerModelContextProvider(e){let t=Symbol();this._providers.set(t,e);let n;try{n=e.subscribe?.(()=>{this.notifySubscribers()})}catch(e){this._providers.delete(t);try{this.notifySubscribers()}catch(e){console.error(e)}throw e}this._providerUnsubscribes.set(t,n),this.notifySubscribers();let r=!1;return()=>{if(r)return;r=!0,this._providers.delete(t);let e=this._providerUnsubscribes.get(t);this._providerUnsubscribes.delete(t);let n=!1,i,a=e=>{try{e()}catch(e){n?console.error(e):(n=!0,i=e)}};if(e&&a(e),a(()=>this.notifySubscribers()),n)throw i}}_subscribers=new Set;notifySubscribers(){xI(this._subscribers)}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}},MI=[],NI={modelName:void 0,toolNames:MI},PI=(e,t)=>e===t||IF(e,t),FI=(e,t)=>{let n=e.getModelContext(),r=n.config?.modelName,i=n.tools?Object.keys(n.tools).sort():MI,a=i.length?i:MI;return r===t.modelName&&PI(a,t.toolNames)?t:{modelName:r,toolNames:a}},II=jN(()=>{let e=J(11),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=new jI,e[0]=t):t=e[0];let n=t,r;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>FI(n,NI),e[1]=r):r=e[1];let[i,a]=fN(r),o,s;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=()=>(a(e=>FI(n,e)),n.subscribe(()=>{a(e=>FI(n,e))})),s=[n],e[2]=o,e[3]=s):(o=e[2],s=e[3]),X(o,s);let c;e[4]===i?c=e[5]:(c=()=>FI(n,i),e[4]=i,e[5]=c);let l,u,d;e[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=()=>n.getModelContext(),u=e=>n.subscribe(e),d=e=>n.registerModelContextProvider(e),e[6]=l,e[7]=u,e[8]=d):(l=e[6],u=e[7],d=e[8]);let f;return e[9]===c?f=e[10]:(f={getState:c,getModelContext:l,subscribe:u,register:d},e[9]=c,e[10]=f),f}),LI=(e,t)=>{if(t.status?.type!==`running`&&t.status?.type!==`requires-action`){let n=e.complete;return typeof n==`function`?n({args:t.args,result:t.result}):n??null}let n=e.running;return typeof n==`function`?n({args:t.args}):n??null},RI=e=>e.display===void 0?e.type===`human`:e.display===`standalone`,zI=e=>function(t){return LI(e,t)},BI=e=>{let t=J(16),{toolkit:n,mcpApp:r}=e,i;t[0]===r?i=t[1]:(i=r?[MN(`mcpApp`,r)]:[],t[0]=r,t[1]=i);let a=CP(i)[0],[o,s]=fN(HI),c;t[2]!==a||t[3]!==o?(c={toolUIs:o,mcpApp:a},t[2]=a,t[3]=o,t[4]=c):c=t[4];let l=c,u=SF(),d;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(d=(e,t,n)=>{let r={render:t,renderText:n?.renderText,standalone:n?.standalone??!1};return s(t=>{let n=mM(t);return n[e]=[...n[e]??[],r],n}),()=>{s(t=>{let n=t[e]?.filter(e=>e!==r)??[],i=mM(t);return n.length>0?(i[e]=n,i):(delete i[e],i)})}},t[5]=d):d=t[5];let f=d,p,m;t[6]===n?(p=t[7],m=t[8]):(p=()=>{if(!n)return;let e=[];for(let[t,r]of Object.entries(n)){let n=`render`in r?r.render:void 0,i=`renderText`in r?r.renderText:void 0,a=n??(i?zI(i):void 0);a&&e.push(f(t,a,{standalone:RI(r),renderText:i}))}return()=>{e.forEach(UI)}},m=[n,f],t[6]=n,t[7]=p,t[8]=m),X(p,m);let h;t[9]!==u||t[10]!==n?(h=()=>{if(!n)return;let e=Object.entries(n).reduce(WI,mM());return u.current.modelContext().register({getModelContext:()=>({tools:e})})},t[9]=u,t[10]=n,t[11]=h):h=t[11];let g;t[12]===n?g=t[13]:(g=[n],t[12]=n,t[13]=g),CF(`modelContext`,h,g);let _;return t[14]===l?_=t[15]:(_={getState:()=>l,setToolUI:f},t[14]=l,t[15]=_),_},VI=jN(BI);oF(BI,(e,t)=>{!e.modelContext&&t.modelContext.source===null&&(e.modelContext=II())});function HI(){return mM()}function UI(e){return e()}function WI(e,t){let[n,r]=t;if(r.type===`mcp`)return e;let{display:i,render:a,renderText:o,...s}=r;return e[n]=s,e}var GI=e=>vN(e.subscribe,e.getState,e.getServerSnapshot),KI=Symbol.for(`assistant-ui.silent-runtime-action`),qI=e=>typeof e==`object`&&!!e&&KI in e,JI=(e,t)=>{let n=t();return n.catch(t=>{qI(t)||console.error(`[assistant-ui] ${e} failed:`,t)}),n},YI=jN(e=>{let t=J(9),{runtime:n}=e,r=GI(n),i;t[0]===r?i=t[1]:(i=()=>r,t[0]=r,t[1]=i);let a,o;t[2]===n?(a=t[3],o=t[4]):(a=()=>JI(`attachment remove`,n.remove),o=()=>n,t[2]=n,t[3]=a,t[4]=o);let s;return t[5]!==i||t[6]!==a||t[7]!==o?(s={getState:i,remove:a,__internal_getRuntime:o},t[5]=i,t[6]=a,t[7]=o,t[8]=s):s=t[8],s}),XI=jN(e=>{let t=J(5),{runtime:n,index:r}=e,i;t[0]!==r||t[1]!==n?(i=n.getAttachmentByIndex(r),t[0]=r,t[1]=n,t[2]=i):i=t[2];let a=i,o;return t[3]===a?o=t[4]:(o=YI({runtime:a}),t[3]=a,t[4]=o),yP(o)}),ZI=jN(({item:e,onMove:t,onRemove:n})=>({getState:()=>e,steer:()=>t({lane:`steer`,insertAfter:null}),move:t,remove:n})),QI=jN(e=>{let t=J(63),{threadIdRef:n,messageIdRef:r,runtime:i,isSuggestion:a}=e,o=GI(i),s=wF(),c=Y(!1),l,u;t[0]!==s||t[1]!==r||t[2]!==i||t[3]!==n?(l=()=>{let e=[],t=i.unstable_on(`send`,e=>{let t=c.current;c.current=!1,s(`composer.send`,{threadId:n.current,...r&&{messageId:r.current},chars:e.chars,attachments:e.attachments,...t?{suggestion:!0}:void 0})});e.push(t);let a=i.unstable_on(`attachmentAdd`,e=>{s(`composer.attachmentAdd`,{threadId:n.current,...r&&{messageId:r.current},...e.contentType?{contentType:e.contentType}:void 0})});return e.push(a),e.push(i.unstable_on(`attachmentAddError`,e=>{s(`composer.attachmentAddError`,{threadId:n.current,...r&&{messageId:r.current},...e.attachmentId&&{attachmentId:e.attachmentId},reason:e.reason,message:e.message,...e.contentType?{contentType:e.contentType}:void 0})})),()=>{for(let t of e)t()}},u=[i,s,n,r],t[0]=s,t[1]=r,t[2]=i,t[3]=n,t[4]=l,t[5]=u):(l=t[4],u=t[5]),X(l,u);let d;if(t[6]!==i||t[7]!==o.attachments){let e;t[9]===i?e=t[10]:(e=(e,t)=>MN(e.id,XI({runtime:i,index:t}),[i,t]),t[9]=i,t[10]=e),d=o.attachments.map(e),t[6]=i,t[7]=o.attachments,t[8]=d}else d=t[8];let f=pI(d),p=o.queue,m;if(t[11]!==p||t[12]!==i){let e;t[14]===i?e=t[15]:(e=e=>MN(e.id,ZI({item:e,onMove:t=>i.moveQueueItem(e.id,t),onRemove:()=>i.removeQueueItem(e.id)})),t[14]=i,t[15]=e),m=p.map(e),t[11]=p,t[12]=i,t[13]=m}else m=t[13];let h=pI(m),g=o.type??`thread`,_;t[16]!==f.state||t[17]!==p||t[18]!==o.attachmentAccept||t[19]!==o.canCancel||t[20]!==o.canSend||t[21]!==o.dictation||t[22]!==o.isEditing||t[23]!==o.isEmpty||t[24]!==o.quote||t[25]!==o.role||t[26]!==o.runConfig||t[27]!==o.text||t[28]!==g?(_={text:o.text,role:o.role,attachments:f.state,runConfig:o.runConfig,isEditing:o.isEditing,canCancel:o.canCancel,canSend:o.canSend,attachmentAccept:o.attachmentAccept,isEmpty:o.isEmpty,type:g,dictation:o.dictation,quote:o.quote,queue:p},t[16]=f.state,t[17]=p,t[18]=o.attachmentAccept,t[19]=o.canCancel,t[20]=o.canSend,t[21]=o.dictation,t[22]=o.isEditing,t[23]=o.isEmpty,t[24]=o.quote,t[25]=o.role,t[26]=o.runConfig,t[27]=o.text,t[28]=g,t[29]=_):_=t[29];let v=_,y;t[30]===v?y=t[31]:(y=()=>v,t[30]=v,t[31]=y);let b;t[32]!==a||t[33]!==i?(b=e=>{let t=i.getState();c.current=t.canSend&&(a?.(t.text)??!1),i.send(e)},t[32]=a,t[33]=i,t[34]=b):b=t[34];let x;t[35]!==s||t[36]!==r||t[37]!==i||t[38]!==n?(x=()=>{!r&&i.getState().canCancel&&s(`composer.cancel`,{threadId:n.current}),i.cancel()},t[35]=s,t[36]=r,t[37]=i,t[38]=n,t[39]=x):x=t[39];let S=i.beginEdit??$I,C;t[40]===f?C=t[41]:(C=e=>`id`in e?f.get({key:e.id}):f.get(e),t[40]=f,t[41]=C);let w;t[42]===h?w=t[43]:(w=e=>`id`in e?h.get({key:e.id}):h.get(e),t[42]=h,t[43]=w);let T;t[44]===i?T=t[45]:(T=()=>i,t[44]=i,t[45]=T);let E;return t[46]!==i.addAttachment||t[47]!==i.clearAttachments||t[48]!==i.reset||t[49]!==i.setQuote||t[50]!==i.setRole||t[51]!==i.setRunConfig||t[52]!==i.setText||t[53]!==i.startDictation||t[54]!==i.stopDictation||t[55]!==S||t[56]!==C||t[57]!==w||t[58]!==T||t[59]!==y||t[60]!==b||t[61]!==x?(E={getState:y,setText:i.setText,setRole:i.setRole,setRunConfig:i.setRunConfig,addAttachment:i.addAttachment,reset:i.reset,clearAttachments:i.clearAttachments,send:b,cancel:x,beginEdit:S,startDictation:i.startDictation,stopDictation:i.stopDictation,setQuote:i.setQuote,attachment:C,queueItem:w,__internal_getRuntime:T},t[46]=i.addAttachment,t[47]=i.clearAttachments,t[48]=i.reset,t[49]=i.setQuote,t[50]=i.setRole,t[51]=i.setRunConfig,t[52]=i.setText,t[53]=i.startDictation,t[54]=i.stopDictation,t[55]=S,t[56]=C,t[57]=w,t[58]=T,t[59]=y,t[60]=b,t[61]=x,t[62]=E):E=t[62],E});function $I(){throw Error(`beginEdit is not supported in this runtime`)}var eL=e=>({get current(){return e()}}),tL=jN(e=>{let t=J(13),{runtime:n}=e,r=GI(n),i;t[0]===r?i=t[1]:(i=()=>r,t[0]=r,t[1]=i);let a,o,s,c;t[2]===n?(a=t[3],o=t[4],s=t[5],c=t[6]):(a=e=>n.addToolResult(e),o=e=>n.resumeToolCall(e),s=e=>n.respondToToolApproval(e),c=()=>n,t[2]=n,t[3]=a,t[4]=o,t[5]=s,t[6]=c);let l;return t[7]!==i||t[8]!==a||t[9]!==o||t[10]!==s||t[11]!==c?(l={getState:i,addToolResult:a,resumeToolCall:o,respondToToolApproval:s,__internal_getRuntime:c},t[7]=i,t[8]=a,t[9]=o,t[10]=s,t[11]=c,t[12]=l):l=t[12],l}),nL=jN(e=>{let t=J(5),{runtime:n,index:r}=e,i;t[0]!==r||t[1]!==n?(i=n.getAttachmentByIndex(r),t[0]=r,t[1]=n,t[2]=i):i=t[2];let a=i,o;return t[3]===a?o=t[4]:(o=YI({runtime:a}),t[3]=a,t[4]=o),yP(o)}),rL=jN(e=>{let t=J(5),{runtime:n,index:r}=e,i;t[0]!==r||t[1]!==n?(i=n.getMessagePartByIndex(r),t[0]=r,t[1]=n,t[2]=i):i=t[2];let a=i,o;return t[3]===a?o=t[4]:(o=tL({runtime:a}),t[3]=a,t[4]=o),yP(o)}),iL=jN(e=>{let t=J(74),{runtime:n,threadIdRef:r,threadId:i}=e,a=GI(n),o=wF(),[s,c]=fN(!1),[l,u]=fN(!1),d;t[0]===n?d=t[1]:(d=eL(()=>n.getState().id),t[0]=n,t[1]=d);let f=d,p=Y(a.status),m;t[2]!==o||t[3]!==n||t[4]!==i?(m=e=>{o(e,{threadId:i,messageId:n.getState().id})},t[2]=o,t[3]=n,t[4]=i,t[5]=m):m=t[5];let h=m,g,_;t[6]!==o||t[7]!==a.id||t[8]!==a.status||t[9]!==i?(g=()=>{let e=a.status,t=p.current;p.current=e,e?.type===`incomplete`&&e.reason===`error`&&(t?.type!==`incomplete`||t.reason!==`error`)&&o(`message.error`,{threadId:i,messageId:a.id,reason:`error`})},_=[a.status,a.id,o,i],t[6]=o,t[7]=a.id,t[8]=a.status,t[9]=i,t[10]=g,t[11]=_):(g=t[10],_=t[11]),X(g,_);let v;t[12]!==f||t[13]!==n.composer||t[14]!==r?(v=QI({runtime:n.composer,threadIdRef:r,messageIdRef:f}),t[12]=f,t[13]=n.composer,t[14]=r,t[15]=v):v=t[15];let y=PF(v),b;if(t[16]!==n||t[17]!==a.content){let e;t[19]===n?e=t[20]:(e=(e,t)=>MN(`toolCallId`in e&&e.toolCallId!=null?`toolCallId-${e.toolCallId}`:`index-${t}`,rL({runtime:n,index:t}),[n,t]),t[19]=n,t[20]=e),b=a.content.map(e),t[16]=n,t[17]=a.content,t[18]=b}else b=t[18];let x=pI(b),S;t[21]===a.attachments?S=t[22]:(S=a.attachments??[],t[21]=a.attachments,t[22]=S);let C;if(t[23]!==n||t[24]!==S){let e;t[26]===n?e=t[27]:(e=(e,t)=>MN(e.id,nL({runtime:n,index:t}),[n,t]),t[26]=n,t[27]=e),C=S.map(e),t[23]=n,t[24]=S,t[25]=C}else C=t[25];let w=pI(C),T=a,E;t[28]!==y.state||t[29]!==s||t[30]!==l||t[31]!==x.state||t[32]!==T?(E={...T,parts:x.state,composer:y.state,isCopied:s,isHovering:l},t[28]=y.state,t[29]=s,t[30]=l,t[31]=x.state,t[32]=T,t[33]=E):E=t[33];let D=E,O;t[34]===D?O=t[35]:(O=()=>D,t[34]=D,t[35]=O);let k;t[36]===y.methods?k=t[37]:(k=()=>y.methods,t[36]=y.methods,t[37]=k);let A;t[38]===n?A=t[39]:(A=()=>n.delete(),t[38]=n,t[39]=A);let j,M;t[40]!==h||t[41]!==n?(j=e=>(h(`message.reload`),n.reload(e)),M=()=>(h(`message.speak`),n.speak()),t[40]=h,t[41]=n,t[42]=j,t[43]=M):(j=t[42],M=t[43]);let N,ee;t[44]===n?(N=t[45],ee=t[46]):(N=()=>n.stopSpeaking(),ee=e=>n.submitFeedback(e),t[44]=n,t[45]=N,t[46]=ee);let te;t[47]!==h||t[48]!==n?(te=e=>(h(`message.branchSwitched`),n.switchToBranch(e)),t[47]=h,t[48]=n,t[49]=te):te=t[49];let ne;t[50]===n?ne=t[51]:(ne=()=>n.unstable_getCopyText(),t[50]=n,t[51]=ne);let re;t[52]===x?re=t[53]:(re=e=>`index`in e?x.get({index:e.index}):x.get({key:`toolCallId-${e.toolCallId}`}),t[52]=x,t[53]=re);let ie;t[54]===w?ie=t[55]:(ie=e=>`id`in e?w.get({key:e.id}):w.get(e),t[54]=w,t[55]=ie);let ae;t[56]===h?ae=t[57]:(ae=e=>{e&&h(`message.copied`),c(e)},t[56]=h,t[57]=ae);let oe;t[58]===n?oe=t[59]:(oe=()=>n,t[58]=n,t[59]=oe);let se;return t[60]!==O||t[61]!==k||t[62]!==A||t[63]!==j||t[64]!==M||t[65]!==N||t[66]!==ee||t[67]!==te||t[68]!==ne||t[69]!==re||t[70]!==ie||t[71]!==ae||t[72]!==oe?(se={getState:O,composer:k,delete:A,reload:j,speak:M,stopSpeaking:N,submitFeedback:ee,switchToBranch:te,getCopyText:ne,part:re,attachment:ie,setIsCopied:ae,setIsHovering:u,__internal_getRuntime:oe},t[60]=O,t[61]=k,t[62]=A,t[63]=j,t[64]=M,t[65]=N,t[66]=ee,t[67]=te,t[68]=ne,t[69]=re,t[70]=ie,t[71]=ae,t[72]=oe,t[73]=se):se=t[73],se}),aL=e=>{let t=mN(()=>({}),[]),n=t.state,r=[];e.suggestions.forEach(e=>{let t=n?.suggestions[r.length];r.push(t&&IF(t,e)?t:e)});let i=n&&IF(r,n.suggestions)?n:{suggestions:r};return t.state=i,i},oL=jN(e=>({getState:()=>e})),sL=e=>{let t=J(9),n=aL(e),r;t[0]===n.suggestions?r=t[1]:(r=n.suggestions.map(lL),t[0]=n.suggestions,t[1]=r);let i=pI(r),a;t[2]===n?a=t[3]:(a=()=>n,t[2]=n,t[3]=a);let o;t[4]===i?o=t[5]:(o=e=>{let{index:t}=e;return i.get({index:t})},t[4]=i,t[5]=o);let s;return t[6]!==a||t[7]!==o?(s={getState:a,suggestion:o},t[6]=a,t[7]=o,t[8]=s):s=t[8],s},cL=jN(e=>{let t=J(4),n;t[0]===e?n=t[1]:(n=e.map(uL),t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r={suggestions:n},t[2]=n,t[3]=r),sL(r)});function lL(e,t){return MN(t,oL(e),[e])}function uL(e){return{title:e.title??e.prompt,label:e.label??``,prompt:e.prompt}}var dL=Object.freeze({type:`complete`}),fL=Object.freeze({type:`running`}),pL=Object.freeze({cancelled:Object.freeze({type:`incomplete`,reason:`cancelled`}),length:Object.freeze({type:`incomplete`,reason:`length`}),"content-filter":Object.freeze({type:`incomplete`,reason:`content-filter`}),other:Object.freeze({type:`incomplete`,reason:`other`}),error:Object.freeze({type:`incomplete`,reason:`error`})}),mL=e=>{let t=e.status;if(!t||typeof t!=`object`)return;let{type:n}=t;if(n===`running`)return fL;if(n===`complete`)return dL;if(n!==`incomplete`)return;let{reason:r}=t;return pL[r===`cancelled`||r===`length`||r===`content-filter`||r===`other`||r===`error`?r:`other`]},hL=(e,t,n)=>{if(e.role!==`assistant`)return dL;if(n.type===`tool-call`)return n.result===void 0?e.status:dL;if(e.status.type===`running`){let e=mL(n);if(e)return e}let r=t===Math.max(0,e.content.length-1);return e.status.type===`requires-action`?dL:r?e.status:dL},gL=e=>`reason`in e?e.reason:void 0,_L=e=>`error`in e?e.error:void 0,vL=32,yL=new WeakMap,bL=e=>yL.get(e)??e.id,xL=(e,t,n)=>`status`in e&&e.status?hL(e,t,n):dL,SL=()=>{let e=[],t=new Map;return n=>{let r=[],i=new Map,a=!0,o=(e,n,s,c)=>{if(!(s>vL))for(let[l,u]of e.entries())for(let[e,d]of u.content.entries()){if(d.type!==`tool-call`||d.messages===void 0)continue;let f=d.messages,p=xL(u,e,d),m=gL(p),h=_L(p),g=`${c}${l}.${e}`,_=t.get(g),v=_?.part===d&&_.statusType===p.type&&_.statusReason===m&&Object.is(_.statusError,h)&&_.messages===f&&_.task.messageId===u.id&&_.task.parentTaskId===n&&_.task.depth===s?_.task:{id:d.toolCallId,toolName:d.toolName,args:d.args,result:d.result,...d.isError===void 0?void 0:{isError:d.isError},status:p,timing:d.timing,messageId:u.id,parentTaskId:n,depth:s,messages:f};v!==_?.task&&(a=!1,yL.set(v,g)),r.push(v),i.set(g,{task:v,part:d,statusType:p.type,statusReason:m,statusError:h,messages:f}),o(f,v.id,s+1,`${g}.`)}};o(n,null,0,``);let s=a&&r.length===e.length&&r.every((t,n)=>t===e[n])?e:r;return e=s,t=i,s}},CL=jN(({task:e})=>({getState:()=>e})),wL=jN(e=>{let t=J(7),{runtime:n,id:r,threadIdRef:i,threadId:a}=e,o;t[0]!==r||t[1]!==n?(o=n.getMessageById(r),t[0]=r,t[1]=n,t[2]=o):o=t[2];let s=o,c;return t[3]!==s||t[4]!==a||t[5]!==i?(c=iL({runtime:s,threadIdRef:i,threadId:a}),t[3]=s,t[4]=a,t[5]=i,t[6]=c):c=t[6],yP(c)}),TL=jN(e=>{let t=J(93),{runtime:n}=e,r=GI(n),i=wF(),a,o;t[0]!==i||t[1]!==n?(a=()=>{let e=[];for(let t of[`runStart`,`runEnd`,`initialize`,`modelContextUpdate`]){let r=n.unstable_on(t,()=>{let e=n.getState()?.threadId||`unknown`;i(`thread.${t}`,{threadId:e})});e.push(r)}return e.push(n.unstable_on(`toolApprovalAnswered`,e=>{let t=n.getState()?.threadId||`unknown`;i(`thread.toolApprovalAnswered`,{threadId:t,...e})})),()=>{for(let t of e)t()}},o=[n,i],t[0]=i,t[1]=n,t[2]=a,t[3]=o):(a=t[2],o=t[3]),X(a,o);let s;t[4]===n?s=t[5]:(s=eL(()=>n.getState().threadId),t[4]=n,t[5]=s);let c=s,l;t[6]!==i||t[7]!==n?(l=e=>{i(e,{threadId:n.getState().threadId})},t[6]=i,t[7]=n,t[8]=l):l=t[8];let u=l,d;t[9]===n?d=t[10]:(d=e=>n.getState().suggestions.some(t=>t.prompt===e),t[9]=n,t[10]=d);let f=d,p;t[11]!==f||t[12]!==n.composer||t[13]!==c?(p=QI({runtime:n.composer,threadIdRef:c,isSuggestion:f}),t[11]=f,t[12]=n.composer,t[13]=c,t[14]=p):p=t[14];let m=PF(p),h;t[15]===r.suggestions?h=t[16]:(h=cL(r.suggestions),t[15]=r.suggestions,t[16]=h);let g=PF(h),_;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(_=SL(),t[17]=_):_=t[17];let v=_,y;t[18]===r.messages?y=t[19]:(y=v(r.messages),t[18]=r.messages,t[19]=y);let b=y,x;t[20]===b?x=t[21]:(x=b.map(EL),t[20]=b,t[21]=x);let S=pI(x),C;if(t[22]!==n||t[23]!==r.messages||t[24]!==r.threadId||t[25]!==c){let e;t[27]!==n||t[28]!==r.threadId||t[29]!==c?(e=e=>MN(e.id,wL({runtime:n,id:e.id,threadIdRef:c,threadId:r.threadId}),[n,e.id,c,r.threadId]),t[27]=n,t[28]=r.threadId,t[29]=c,t[30]=e):e=t[30],C=r.messages.map(e),t[22]=n,t[23]=r.messages,t[24]=r.threadId,t[25]=c,t[26]=C}else C=t[26];let w=pI(C),T=w.state.length===0&&!r.isLoading,E;t[31]!==m.state||t[32]!==w.state||t[33]!==r.capabilities||t[34]!==r.extras||t[35]!==r.isDisabled||t[36]!==r.isLoading||t[37]!==r.isRunning||t[38]!==r.speech||t[39]!==r.state||t[40]!==r.suggestions||t[41]!==r.voice||t[42]!==T||t[43]!==b?(E={isEmpty:T,isDisabled:r.isDisabled,isLoading:r.isLoading,isRunning:r.isRunning,capabilities:r.capabilities,state:r.state,suggestions:r.suggestions,extras:r.extras,speech:r.speech,voice:r.voice,composer:m.state,messages:w.state,tasks:b},t[31]=m.state,t[32]=w.state,t[33]=r.capabilities,t[34]=r.extras,t[35]=r.isDisabled,t[36]=r.isLoading,t[37]=r.isRunning,t[38]=r.speech,t[39]=r.state,t[40]=r.suggestions,t[41]=r.voice,t[42]=T,t[43]=b,t[44]=E):E=t[44];let D=E,O;t[45]===D?O=t[46]:(O=()=>D,t[45]=D,t[46]=O);let k;t[47]===m.methods?k=t[48]:(k=()=>m.methods,t[47]=m.methods,t[48]=k);let A;t[49]===g?A=t[50]:(A=()=>g.methods,t[49]=g,t[50]=A);let j;t[51]!==S||t[52]!==b?(j=e=>{if(`id`in e){let t=b.find(t=>t.id===e.id);return S.get({key:t?bL(t):e.id})}return S.get(e)},t[51]=S,t[52]=b,t[53]=j):j=t[53];let M;t[54]!==i||t[55]!==f||t[56]!==n?(M=e=>{let t=typeof e==`string`?{content:[{type:`text`,text:e}]}:e;if((t.role??`user`)===`user`){let e=t.content.map(DL).join(``);i(`composer.send`,{threadId:n.getState().threadId,chars:e.length,attachments:t.attachments?.length??0,...f(e)?{suggestion:!0}:void 0})}n.append(e)},t[54]=i,t[55]=f,t[56]=n,t[57]=M):M=t[57];let N;t[58]!==u||t[59]!==n||t[60]!==r.isRunning?(N=()=>{r.isRunning&&u(`thread.cancelRun`),n.cancelRun()},t[58]=u,t[59]=n,t[60]=r.isRunning,t[61]=N):N=t[61];let ee;t[62]!==u||t[63]!==n?(ee=()=>{n.connectVoice(),u(`thread.voiceStarted`)},t[62]=u,t[63]=n,t[64]=ee):ee=t[64];let te;t[65]===w?te=t[66]:(te=e=>`id`in e?w.get({key:e.id}):w.get(e),t[65]=w,t[66]=te);let ne;t[67]===n?ne=t[68]:(ne=()=>n,t[67]=n,t[68]=ne);let re;return t[69]!==n.deleteMessage||t[70]!==n.disconnectVoice||t[71]!==n.export||t[72]!==n.getModelContext||t[73]!==n.getVoiceVolume||t[74]!==n.import||t[75]!==n.importExternalState||t[76]!==n.muteVoice||t[77]!==n.reset||t[78]!==n.resumeRun||t[79]!==n.startRun||t[80]!==n.stopSpeaking||t[81]!==n.subscribeVoiceVolume||t[82]!==n.unmuteVoice||t[83]!==O||t[84]!==k||t[85]!==A||t[86]!==j||t[87]!==M||t[88]!==N||t[89]!==ee||t[90]!==te||t[91]!==ne?(re={getState:O,composer:k,suggestions:A,task:j,append:M,deleteMessage:n.deleteMessage,startRun:n.startRun,resumeRun:n.resumeRun,importExternalState:n.importExternalState,cancelRun:N,getModelContext:n.getModelContext,export:n.export,import:n.import,reset:n.reset,stopSpeaking:n.stopSpeaking,connectVoice:ee,disconnectVoice:n.disconnectVoice,getVoiceVolume:n.getVoiceVolume,subscribeVoiceVolume:n.subscribeVoiceVolume,muteVoice:n.muteVoice,unmuteVoice:n.unmuteVoice,message:te,__internal_getRuntime:ne},t[69]=n.deleteMessage,t[70]=n.disconnectVoice,t[71]=n.export,t[72]=n.getModelContext,t[73]=n.getVoiceVolume,t[74]=n.import,t[75]=n.importExternalState,t[76]=n.muteVoice,t[77]=n.reset,t[78]=n.resumeRun,t[79]=n.startRun,t[80]=n.stopSpeaking,t[81]=n.subscribeVoiceVolume,t[82]=n.unmuteVoice,t[83]=O,t[84]=k,t[85]=A,t[86]=j,t[87]=M,t[88]=N,t[89]=ee,t[90]=te,t[91]=ne,t[92]=re):re=t[92],re});function EL(e){return MN(bL(e),CL({task:e}),[e])}function DL(e){return e.type===`text`?e.text:``}var OL=(e,t)=>JI(`thread list ${e}`,t),kL=jN(e=>{let t=J(35),{runtime:n,mainThreadIsRunning:r}=e,i=r!==void 0&&r,a=GI(n),o;bb0:{let e=a.isRunning||a.isMain&&i;if(e===a.isRunning){o=a;break bb0}let n;t[0]!==e||t[1]!==a?(n={...a,isRunning:e},t[0]=e,t[1]=a,t[2]=n):n=t[2],o=n}let s=o,c=wF(),{isMain:l,id:u}=a,d;t[3]!==l||t[4]!==u?(d={isMain:l,threadId:u},t[3]=l,t[4]=u,t[5]=d):d=t[5];let f=Y(d),p,m;t[6]!==c||t[7]!==l||t[8]!==u?(p=()=>{let e=f.current;(e.isMain!==l||e.threadId!==u)&&(f.current={isMain:l,threadId:u},c(l?`threadListItem.switchedTo`:`threadListItem.switchedAway`,{threadId:u}))},m=[l,u,c],t[6]=c,t[7]=l,t[8]=u,t[9]=p,t[10]=m):(p=t[9],m=t[10]),X(p,m);let h;t[11]===s?h=t[12]:(h=()=>s,t[11]=s,t[12]=h);let g,_,v,y,b,x,S;t[13]===n?(g=t[14],_=t[15],v=t[16],y=t[17],b=t[18],x=t[19],S=t[20]):(b=e=>OL(`switch`,()=>n.switchTo(e)),x=e=>OL(`rename`,()=>n.rename(e)),S=e=>OL(`update custom metadata`,()=>n.updateCustom(e)),g=()=>OL(`archive`,()=>n.archive()),_=()=>OL(`unarchive`,()=>n.unarchive()),v=()=>OL(`delete`,()=>n.delete()),y=e=>OL(`generate title`,()=>n.generateTitle(e)),t[13]=n,t[14]=g,t[15]=_,t[16]=v,t[17]=y,t[18]=b,t[19]=x,t[20]=S);let C;t[21]===n?C=t[22]:(C=()=>n,t[21]=n,t[22]=C);let w;return t[23]!==n.detach||t[24]!==n.initialize||t[25]!==g||t[26]!==_||t[27]!==v||t[28]!==y||t[29]!==C||t[30]!==h||t[31]!==b||t[32]!==x||t[33]!==S?(w={getState:h,switchTo:b,rename:x,updateCustom:S,archive:g,unarchive:_,delete:v,generateTitle:y,initialize:n.initialize,detach:n.detach,__internal_getRuntime:C},t[23]=n.detach,t[24]=n.initialize,t[25]=g,t[26]=_,t[27]=v,t[28]=y,t[29]=C,t[30]=h,t[31]=b,t[32]=x,t[33]=S,t[34]=w):w=t[34],w}),AL=e=>{let t=J(4),n=wF(),r=Y(e),i,a;t[0]!==n||t[1]!==e?(i=()=>{let t=r.current;t!==e&&(r.current=e,n(`threads.selectionChanged`,{threadId:e,previousThreadId:t}))},a=[e,n],t[0]=n,t[1]=e,t[2]=i,t[3]=a):(i=t[2],a=t[3]),X(i,a)},jL=jN(e=>{let t=J(6),{runtime:n,id:r,mainThreadIsRunning:i}=e,a;t[0]!==r||t[1]!==n?(a=n.getItemById(r),t[0]=r,t[1]=n,t[2]=a):a=t[2];let o=a,s;return t[3]!==i||t[4]!==o?(s=kL({runtime:o,mainThreadIsRunning:i}),t[3]=i,t[4]=o,t[5]=s):s=t[5],yP(s)}),ML=jN(e=>{let t=J(48),{runtime:n,__internal_assistantRuntime:r}=e,i=GI(n);AL(i.mainThreadId);let a=wF(),o,s;t[0]!==a||t[1]!==n?(o=()=>n.unstable_subscribeThreadEvents(e=>{let{threadId:t,type:r}=e;t!==n.getState().mainThreadId&&a(`thread.${r}`,{threadId:t})}),s=[n,a],t[0]=a,t[1]=n,t[2]=o,t[3]=s):(o=t[2],s=t[3]),X(o,s);let c;t[4]===n.main?c=t[5]:(c=TL({runtime:n.main}),t[4]=n.main,t[5]=c);let l=PF(c),u;t[6]!==l.state||t[7]!==n||t[8]!==i.threadItems?(u=Object.keys(i.threadItems).map(e=>MN(e,jL({runtime:n,id:e,mainThreadIsRunning:l.state.isRunning}),[n,e,l.state.isRunning])),t[6]=l.state,t[7]=n,t[8]=i.threadItems,t[9]=u):u=t[9];let d=pI(u),f=i.newThreadId??null,p;t[10]!==l.state||t[11]!==i.archivedThreadIds||t[12]!==i.hasMore||t[13]!==i.isLoading||t[14]!==i.isLoadingMore||t[15]!==i.loadError||t[16]!==i.mainThreadId||t[17]!==i.threadIds||t[18]!==f||t[19]!==d.state?(p={mainThreadId:i.mainThreadId,newThreadId:f,isLoading:i.isLoading,loadError:i.loadError,isLoadingMore:i.isLoadingMore,hasMore:i.hasMore,threadIds:i.threadIds,archivedThreadIds:i.archivedThreadIds,threadItems:d.state,main:l.state},t[10]=l.state,t[11]=i.archivedThreadIds,t[12]=i.hasMore,t[13]=i.isLoading,t[14]=i.isLoadingMore,t[15]=i.loadError,t[16]=i.mainThreadId,t[17]=i.threadIds,t[18]=f,t[19]=d.state,t[20]=p):p=t[20];let m=p,h;t[21]===m?h=t[22]:(h=()=>m,t[21]=m,t[22]=h);let g;t[23]===l.methods?g=t[24]:(g=()=>l.methods,t[23]=l.methods,t[24]=g);let _;t[25]!==m||t[26]!==d?(_=e=>{if(e===`main`)return d.get({key:m.mainThreadId});if(`id`in e)return d.get({key:e.id});let{index:t,archived:n}=e,r=n!==void 0&&n?m.archivedThreadIds[t]:m.threadIds[t];return d.get({key:r})},t[25]=m,t[26]=d,t[27]=_):_=t[27];let v,y,b,x,S,C;t[28]===n?(v=t[29],y=t[30],b=t[31],x=t[32],S=t[33],C=t[34]):(v=(e,t)=>OL(`switch`,()=>n.switchToThread(e,t)),y=()=>OL(`create`,()=>n.switchToNewThread()),b=()=>n.getLoadThreadsPromise(),x=()=>n.reload(),S=()=>n.reloadMainThread(),C=()=>n.loadMore(),t[28]=n,t[29]=v,t[30]=y,t[31]=b,t[32]=x,t[33]=S,t[34]=C);let w;t[35]===r?w=t[36]:(w=()=>r,t[35]=r,t[36]=w);let T;return t[37]!==v||t[38]!==y||t[39]!==b||t[40]!==x||t[41]!==S||t[42]!==C||t[43]!==w||t[44]!==h||t[45]!==g||t[46]!==_?(T={getState:h,thread:g,item:_,switchToThread:v,switchToNewThread:y,getLoadThreadsPromise:b,reload:x,reloadMainThread:S,loadMore:C,__internal_getAssistantRuntime:w},t[37]=v,t[38]=y,t[39]=b,t[40]=x,t[41]=S,t[42]=C,t[43]=w,t[44]=h,t[45]=g,t[46]=_,t[47]=T):T=t[47],T}),NL=(e,t)=>{e.thread??=dI({source:`threads`,query:{type:`main`},get:e=>e.threads.thread(`main`)}),e.threadListItem??=dI({source:`threads`,query:{type:`main`},get:e=>e.threads.item(`main`)}),e.composer??=dI({source:`thread`,query:{},get:e=>e.threads.thread(`main`).composer()}),!e.modelContext&&t.modelContext.source===null&&(e.modelContext=II()),!e.suggestions&&t.suggestions.source===null&&(e.suggestions=dI({source:`thread`,query:{},get:e=>e.thread.suggestions()}))},PL=e=>{let t=J(7),n=SF(),r;t[0]!==n||t[1]!==e?(r=()=>e.registerModelContextProvider(n.current.modelContext()),t[0]=n,t[1]=e,t[2]=r):r=t[2];let i;t[3]===e?i=t[4]:(i=[e],t[3]=e,t[4]=i),CF(`modelContext`,r,i);let a;return t[5]===e?a=t[6]:(a=ML({runtime:e.threads,__internal_assistantRuntime:e}),t[5]=e,t[6]=a),yP(a)},FL=jN(PL);oF(PL,(e,t)=>{NL(e,t),!e.tools&&t.tools.source===null&&(e.tools=VI({})),!e.dataRenderers&&t.dataRenderers.source===null&&(e.dataRenderers=EP())});var IL=e=>{let{children:t,condition:n}=e;return $(n)?t:null};IL.displayName=`AuiIf`;var LL=jP({}),RL=({effects:e})=>{"use no memo";return gN(e),null},zL=Z(function(e,t){"use no memo";let{config:n,children:r}=e,i=`extends`in e,a=`value`in e,o=rF();if(zF){if(i&&a)throw Error("AuiProvider: pass either `extends` or `value`, not both.");if(i&&e.extends===void 0)throw Error("AuiProvider: `extends` must be a client or null, not undefined.");if(i&&!n)throw Error("AuiProvider: `extends` requires a `config`.");if(a&&n)throw Error("AuiProvider: pass either `value` or `config`, not both.");if(!a&&!n)throw Error("AuiProvider: a `config` is required.");if(!i&&!a&&o!==XP)throw Error(`A parent AuiProvider exists — pass extends={aui} to inherit it or extends={null} to isolate.`)}let s=i?e.extends??XP:a?e.value??XP:o,c=DF(),{client:l,effects:u}=iI(s,n??LL,c);return SN(t,()=>l,[l]),(0,b.jsx)(TF.Provider,{value:c,children:(0,b.jsxs)(QP.Provider,{value:l,children:[(0,b.jsx)(RL,{effects:tF(s)}),u&&(0,b.jsx)(RL,{effects:u}),r]})})}),BL=e=>{let t=Q(),n=Y(!1),r=n.current?null:e(t);return $(()=>n.current?e(t):r),()=>(n.current=!0,e(t))},VL=Object.freeze({});function HL(e){let t=J(3),{getItemState:n,children:r}=e,i=BL(n),a;return t[0]!==r||t[1]!==i?(a=r(i),t[0]=r,t[1]=i,t[2]=a):a=t[2],UL(a)}var UL=e=>{let t=typeof e==`object`&&e&&`type`in e?e:null,n=t?.type,r=t?.key;return mN(()=>t,[n,r,typeof t?.props==`object`&&t.props!=null&&Object.entries(t.props).length===0?VL:t?.props])??e},WL=(e,t)=>{let n=J(11),r=Q(),i=_N(t),a;n[0]===e?a=n[1]:(a=cF(e),n[0]=e,n[1]=a);let{scope:o,event:s}=a,c;n[2]!==r||n[3]!==i||n[4]!==s||n[5]!==o?(c=()=>r.on({scope:o,event:s},i),n[2]=r,n[3]=i,n[4]=s,n[5]=o,n[6]=c):c=n[6];let l;n[7]!==r||n[8]!==s||n[9]!==o?(l=[r,o,s],n[7]=r,n[8]=s,n[9]=o,n[10]=l):l=n[10],X(c,l)},GL=e=>e._core?.RenderComponent,KL=({runtime:e,aui:t,config:n,children:r})=>{"use no memo";let i=GL(e),a=jP({...n,threads:FL(e)});return(0,b.jsxs)(zL,{extends:t,config:a,children:[i&&(0,b.jsx)(i,{}),r]})},qL=CN(e=>{let t=J(5),{runtime:n,aui:r,config:i,children:a}=e,o=r===void 0?null:r,s;return t[0]!==o||t[1]!==a||t[2]!==i||t[3]!==n?(s=(0,b.jsx)(KL,{runtime:n,aui:o,config:i,children:a}),t[0]=o,t[1]=a,t[2]=i,t[3]=n,t[4]=s):s=t[4],s});function JL(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function YL(e,t=0){return t>100?!1:e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(e=>YL(e,t+1)):JL(e)?Object.entries(e).every(([e,n])=>typeof e==`string`&&YL(n,t+1)):!1}var XL=100,ZL=(e,t,n)=>{if(e===t)return!0;if(n>XL||e==null||t==null)return!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((e,r)=>ZL(e,t[r],n+1));if(Array.isArray(t)||!JL(e)||!JL(t))return!1;let r=Object.keys(e),i=Object.keys(t);return r.length===i.length&&r.every(r=>Object.hasOwn(t,r)&&ZL(e[r],t[r],n+1))},QL=(e,t)=>!YL(e)||!YL(t)?!1:ZL(e,t,0);function $L(e){let t=Y(e);return t.current!==e&&!QL(t.current,e)&&(t.current=e),t.current}function eR(e){let t=J(2),n=Y(void 0),r;return t[0]===e?r=t[1]:(r=t=>{let r=e(t);return n.current!==void 0&&QL(n.current,r)?n.current:(n.current=r,r)},t[0]=e,t[1]=r),r}var tR=Symbol.for(`aui.tool-response`),nR=`<no result>`,rR=class e{get[tR](){return!0}artifact;result;isError;modelContent;messages;constructor(e){e.artifact!==void 0&&(this.artifact=e.artifact);let t=e.result;this.result=t===void 0?nR:t,this.isError=e.isError??!1,e.modelContent!==void 0&&(this.modelContent=e.modelContent),e.messages!==void 0&&(this.messages=e.messages)}static[Symbol.hasInstance](e){return typeof e==`object`&&!!e&&tR in e}static toResponse(t){return t instanceof e?t:new e({result:t===void 0?nR:t})}},iR=()=>{let e,t,n=new Promise((n,r)=>{e=n,t=r});if(!e||!t)throw Error(`Failed to create promise`);return{promise:n,resolve:e,reject:t}},aR=()=>{let e=[],t=!1,n=!1,r=!1,i,a,o=0,s,c,l=()=>(a=void 0,c??=Promise.all(e.splice(0).map(async e=>{try{await e.reader.cancel().catch(()=>void 0),await e.pipeTask}finally{e.reader.releaseLock()}})).then(()=>void 0),c),u=e=>{n||r||(r=!0,console.error(e),l(),i.error(e),s?.reject(e),s=void 0)},d=a=>{a.promise||=a.reader.read().then(({done:c,value:l})=>{a.promise=void 0,!(n||r)&&(c?(e.splice(e.indexOf(a),1),a.reader.releaseLock(),t&&e.length===0&&o===0&&i.close()):i.enqueue(l),s?.resolve(),s=void 0)}).catch(u)},f=new ReadableStream({start(e){i=e},pull(){return s=iR(),e.forEach(e=>{d(e)}),s.promise},async cancel(){n=!0;let e=l();s?.resolve(),s=void 0,await e}}),p=c=>{if(e.length>0&&(a=void 0),!a){let c=[];a=c,o++,Promise.resolve().then(()=>{if(o--,a===c&&(a=void 0),!(n||r)){for(let e of c)i.enqueue(e);t&&e.length===0&&o===0&&i.close(),s?.resolve(),s=void 0}}).catch(u)}a.push(c)};return{readable:f,isSealed(){return t},isCancelled(){return n},isErrored(){return r},seal(){t||n||r||(t=!0,e.length===0&&o===0&&i.close())},addStream:(i,o)=>{let s=o?.catch(()=>void 0);if(n||r){i.cancel().catch(()=>void 0);return}if(t)throw i.cancel().catch(()=>void 0),Error(`Cannot add streams after the run callback has settled.`);a=void 0;let c={reader:i.getReader(),pipeTask:s};e.push(c),d(c)},enqueue(e){if(!(n||r)){if(t)throw Error(`Cannot add streams after the run callback has settled.`);p(e)}}}},oR=e=>e instanceof TypeError,sR=(e,t,n)=>{try{e.enqueue(t)}catch(e){if(!oR(e))throw e;n?.(e)}},cR=e=>{try{e.close()}catch(e){if(!oR(e))throw e}},lR=(e,t)=>new ReadableStream({start(n){return e.start?.(t(n))},pull(n){return e.pull?.(t(n))},cancel(t){return e.cancel?.(t)}}),uR=(e,t)=>{let n;return[lR({start(e){n=e},cancel(e){return t?.(n,e)}},e),n]},dR=class{_controller;_strict;_isClosed=!1;_warnedDropped=!1;constructor(e,t={}){this._controller=e,this._strict=t.strict??!0}append(e){let t={type:`text-delta`,path:[],textDelta:e};if(this._isClosed){if(this._strict)throw TypeError(`Cannot append to a closed TextStreamController`);return sR(this._controller,t,this._warnDroppedAfterClose),this}return sR(this._controller,t),this}_warnDroppedAfterClose=e=>{this._warnedDropped||(this._warnedDropped=!0,console.error(`Dropped text delta for closed stream: ${String(e)}`))};close(){this._isClosed||(this._isClosed=!0,sR(this._controller,{type:`part-finish`,path:[]}),cR(this._controller))}},fR=(e,t={})=>lR(e,e=>new dR(e,t)),pR=(e={})=>uR(t=>new dR(t,e)),mR=class{_isClosed=!1;_mergeTask;_controller;constructor(e,t={}){this._controller=e;let n=fR({start:e=>{this._argsTextController=e}},t),r=!1;this._mergeTask=n.pipeTo(new WritableStream({write:e=>{switch(e.type){case`text-delta`:r=!0,sR(this._controller,e);break;case`part-finish`:r||sR(this._controller,{type:`text-delta`,textDelta:`{}`,path:[]}),sR(this._controller,{type:`tool-call-args-text-finish`,path:[]});break;default:throw Error(`Unexpected chunk type: ${e.type}`)}}}))}get argsText(){return this._argsTextController}_argsTextController;async setResponse(e){if(this._isClosed)return;let t=e.result;sR(this._controller,{type:`result`,path:[],...e.artifact===void 0?{}:{artifact:e.artifact},result:t===void 0?nR:t,isError:e.isError??!1,...e.modelContent===void 0?{}:{modelContent:e.modelContent},...e.messages===void 0?{}:{messages:e.messages}}),await this.close()}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,sR(this._controller,{type:`part-finish`,path:[]}),cR(this._controller))}},hR=(e={})=>uR(t=>new mR(t,e)),gR=class{value=-1;up(){return++this.value}},_R=class extends TransformStream{constructor(e){super({transform(t,n){n.enqueue({...t,path:[e,...t.path]})}})}};TransformStream;var vR=class extends TransformStream{constructor(e){let t=new gR,n=new Map;super({transform(r,i){r.type===`part-start`&&r.path.length===0&&n.set(t.up(),e.up());let[a,...o]=r.path;if(a===void 0){i.enqueue(r);return}let s=n.get(a);if(s===void 0)throw Error(`Path not found`);i.enqueue({...r,path:[s,...o]})}})}},yR=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i-->0;)r+=e[Math.random()*e.length|0];return r},bR=yR(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7),xR=class e{_state;_parentId;constructor(e,t={}){this._state=e||{strict:t.strict??!0,merger:aR(),contentCounter:new gR}}get __internal_isClosed(){return this._state.merger.isSealed()||this._state.merger.isCancelled()||this._state.merger.isErrored()}get __internal_isCancelled(){return this._state.merger.isCancelled()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(e){this._state.closeSubscriber=e}_addTransformedStream(e,t){if(e.locked)throw TypeError(`Cannot merge a stream that is already locked to a reader.`);let n=e.pipeTo(t.writable).catch(async e=>{throw await t.writable.abort(e).catch(()=>void 0),e});this._state.merger.addStream(t.readable,n)}_addPart(e,t){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:`part-start`,part:e,path:[]}),this._addTransformedStream(t,new _R(this._state.contentCounter.value))}merge(e){this._addTransformedStream(e,new vR(this._state.contentCounter))}appendText(e){(this._state.append?.kind!==`text`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`text`,parentId:this._parentId,controller:this.addTextPart()}),this._state.append.controller.append(e)}appendReasoning(e,t){(t!==void 0||this._state.append?.kind!==`reasoning`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`reasoning`,parentId:this._parentId,controller:this.addReasoningPart(t)}),(t===void 0||e.length!==0)&&this._state.append.controller.append(e)}addTextPart(){let[e,t]=pR({strict:this._state.strict});return this._addPart(this._withParentIdOption({type:`text`}),e),t}addReasoningPart(e){let[t,n]=pR({strict:this._state.strict});return this._addPart(this._withParentIdOption({type:`reasoning`,...e}),t),n}addToolCallPart(e){let t=typeof e==`string`?{toolName:e}:e,n=t.toolName,r=t.toolCallId??bR(),[i,a]=hR({strict:this._state.strict});return this._addPart({type:`tool-call`,toolName:n,toolCallId:r,...this._parentId&&{parentId:this._parentId}},i),t.argsText!==void 0&&(a.argsText.append(t.argsText),a.argsText.close()),t.args!==void 0&&(a.argsText.append(JSON.stringify(t.args)),a.argsText.close()),t.response!==void 0&&a.setResponse(t.response),a}_finishedPartStream(){return new ReadableStream({start(e){e.enqueue({type:`part-finish`,path:[]}),e.close()}})}_withParentIdOption(e){return this._parentId?{...e,parentId:this._parentId}:e}appendSource(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}appendFile(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}appendData(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}enqueue(e){this._state.merger.enqueue(e),e.type===`part-start`&&e.path.length===0&&this._state.contentCounter.up()}withParentId(t){let n=new e(this._state);return n._parentId=t,n}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function SR(e,t={}){let n=new xR(void 0,t);return(async()=>{try{await e(n)}catch(e){n.__internal_isClosed?n.__internal_isCancelled||console.error(e):n.enqueue({type:`error`,path:[],error:String(e)})}finally{n.__internal_isClosed||n.close()}})(),n.__internal_getReadable()}function CR(e={}){let{resolve:t,promise:n}=iR(),r;return[SR(e=>(r=e,r.__internal_subscribeToClose(t),n),e),r]}var wR=class extends TransformStream{constructor(e){super();let t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},TR=r(((e,t)=>{var n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o})),ER=class extends TransformStream{constructor(){let e=[];super({transform(t,n){if(t.type===`part-start`){if(t.path.length!==0){n.error(Error(`Nested parts are not supported`));return}e.push(t.part),n.enqueue(t);return}if(t.type===`text-delta`||t.type===`result`||t.type===`part-finish`||t.type===`tool-call-args-text-finish`){if(t.path.length!==1){n.error(Error(`${t.type} chunks must have a path of length 1`));return}let r=t.path[0];if(r<0||r>=e.length){n.error(Error(`Invalid path index: ${r}`));return}let i=e[r];n.enqueue({...t,meta:i});return}n.enqueue(t)}})}},DR=/[0-9a-fA-F]/;function OR(e){let t=[`ROOT`],n=-1,r=null,i=0,a=[],o;function s(){o!==void 0&&(a.push(JSON.parse(`"${o}"`)),o=void 0)}function c(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`),s();break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),s();break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),s();break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`),s();break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`),s()}}function l(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop(),o=a.pop()}}function u(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),o=(Number(o)+1).toString();break;case`]`:n=r,t.pop(),o=a.pop()}}for(let s=0;s<e.length;s++){let d=e[s];switch(t[t.length-1]){case`ROOT`:c(d,s,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(d){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`),o=``;break;case`}`:n=s,t.pop(),o=a.pop()}break;case`INSIDE_OBJECT_AFTER_COMMA`:d===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_KEY`),o=``);break;case`INSIDE_OBJECT_KEY`:switch(d){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`),o+=d;break;default:o+=d}break;case`INSIDE_OBJECT_AFTER_KEY`:d===`:`&&(t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`));break;case`INSIDE_OBJECT_BEFORE_VALUE`:c(d,s,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:l(d,s);break;case`INSIDE_STRING`:switch(d){case`"`:t.pop(),n=s,o=a.pop();break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=s}break;case`INSIDE_ARRAY_START`:switch(d){case`]`:n=s,t.pop(),o=a.pop();break;default:o=`0`,c(d,s,`INSIDE_ARRAY_AFTER_VALUE`)}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(d){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),o=(Number(o)+1).toString();break;case`]`:n=s,t.pop(),o=a.pop();break;default:n=s}break;case`INSIDE_ARRAY_AFTER_COMMA`:c(d,s,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:{t.pop();let e=t[t.length-1];d===`u`?(t.push(`INSIDE_STRING_UNICODE_ESCAPE`),i=0):e===`INSIDE_STRING`&&(n=s),e===`INSIDE_OBJECT_KEY`&&(o+=d);break}case`INSIDE_STRING_UNICODE_ESCAPE`:{let e=t[t.length-2];if(!DR.test(d)){t.pop(),s--;break}i++,i===4&&(t.pop(),e===`INSIDE_STRING`&&(n=s)),e===`INSIDE_OBJECT_KEY`&&(o+=d);break}case`INSIDE_NUMBER`:switch(d){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=s;break;case`e`:case`E`:case`-`:case`+`:case`.`:break;case`,`:t.pop(),o=a.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&u(d,s),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&l(d,s);break;case`}`:t.pop(),o=a.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&l(d,s);break;case`]`:t.pop(),o=a.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&u(d,s);break;default:t.pop(),o=a.pop()}break;case`INSIDE_LITERAL`:{let i=e.substring(r,s+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?l(d,s):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&u(d,s)):n=s;break}}}let d=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:d+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:d+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:d+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?d+=`true`.slice(t.length):`false`.startsWith(t)?d+=`false`.slice(t.length):`null`.startsWith(t)&&(d+=`null`.slice(t.length))}}return[d,a]}var kR=n(TR(),1),AR=Symbol(`aui.parse-partial-json-object.meta`),jR=e=>e?.[AR],MR=e=>{if(e.length===0)return{[AR]:{state:`partial`,partialPath:[]}};try{let t=kR.default.parse(e);if(typeof t!=`object`||!t)throw Error(`argsText is expected to be an object`);return t[AR]={state:`complete`,partialPath:[]},t}catch{try{let[t,n]=OR(e),r=kR.default.parse(t);if(typeof r!=`object`||!r)throw Error(`argsText is expected to be an object`);return r[AR]={state:`partial`,partialPath:n},r}catch{return}}},NR=(e,t,n)=>{if(typeof e!=`object`||!e)return t.state;if(t.state===`complete`)return`complete`;if(n.length===0)return t.state;let[r,...i]=n;if(!Object.hasOwn(e,r))return`partial`;let[a,...o]=t.partialPath;if(r!==a)return`complete`;let s=e[r];return NR(s,{state:`partial`,partialPath:o},i)},PR=(e,t)=>{let n=jR(e);if(!n)throw Error(`unable to determine object state`);return NR(e,n,t.map(String))},FR=new Set([`__proto__`,`constructor`,`prototype`]);function IR(e){if(FR.has(e))throw Error(`Unsafe gorp path segment: ${e}`)}var LR=class{_state;_strict;_logged=new Set;_warnedClamp=!1;constructor(e=null,t={}){this._state=e,this._strict=t.strict??!0}get state(){return this._state}logOnce(e,t){this._logged.has(e)||this._logged.size>=20||(this._logged.add(e),t())}append(e){this._state=e.reduce((e,t)=>{if(this._strict)return this.apply(e,t);try{return this.apply(e,t)}catch(n){return this.logOnce(`skip:${String(n)}`,()=>console.error(`Skipped unappliable gorp operation: ${String(n)}`,t)),e}},this._state)}apply(e,t){let n=t.type;switch(n){case`set`:return this.updatePath(e,t.path,()=>t.value);case`append-text`:return this.updatePath(e,t.path,e=>{if(typeof e!=`string`)throw Error(`Expected string at path [${t.path.join(`, `)}]`);return e+t.value});default:throw Error(`Invalid operation type: ${n}`)}}updatePath(e,t,n){if(t.length===0)return n(e);let r=[],i=e;for(let e=0;e<t.length;e++){if(i??={},typeof i!=`object`)throw Error(`Invalid path: [${t.slice(e).join(`, `)}]`);let n=t[e];if(IR(n),Array.isArray(i)){let a=Number(n);if(!Number.isInteger(a)||String(a)!==String(n))throw Error(`Expected array index at [${t.slice(e).join(`, `)}]`);if(a<0)throw Error(`Insert array index out of bounds`);if(a>i.length){if(this._strict)throw Error(`Insert array index out of bounds`);this._warnedClamp||(this._warnedClamp=!0,console.warn(`Clamped out-of-bounds gorp array index ${a} to ${i.length}`)),a=i.length}r.push({kind:`array`,state:i,key:a}),i=Object.hasOwn(i,a)?i[a]:void 0}else{let e=i;r.push({kind:`object`,state:e,key:n}),i=Object.hasOwn(e,n)?e[n]:void 0}}let a=n(i);for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.kind===`array`){let e=[...t.state];e[t.key]=a,a=e}else{let e={...t.state};e[t.key]=a,a=e}}return a}},RR=class{_streamStartTime;_firstTokenTime;_totalChunks=0;_toolCallIds=new Set;constructor(){this._streamStartTime=Date.now()}recordChunk(){this._totalChunks++}recordFirstToken(){this._firstTokenTime===void 0&&(this._firstTokenTime=Date.now())}recordToolCallStart(e){this._toolCallIds.add(e)}getTiming(e,t){let n=Date.now()-this._streamStartTime,r=e&&e>0?e:t?Math.ceil(t.length/4):void 0,i=r&&n>0?r/n*1e3:void 0;return{streamStartTime:this._streamStartTime,...this._firstTokenTime===void 0?void 0:{firstTokenTime:this._firstTokenTime-this._streamStartTime},totalStreamTime:n,...r===void 0?void 0:{tokenCount:r},...i===void 0?void 0:{tokensPerSecond:i},totalChunks:this._totalChunks,toolCallCount:this._toolCallIds.size}}},zR=(e,t)=>({...e,parts:t,get content(){return this.parts}}),BR=(e,t)=>zR(e,[...e.parts,t]),VR=({unstable_state:e=null}={})=>({role:`assistant`,status:{type:`running`},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),HR=16,UR=(e,t,n,r)=>{let i=t.path.length===1?e.parts[t.path[0]]:void 0;if(i===void 0)return n(`no-part:${t.type}`,`Dropped ${t.type} chunk: no part at path [${t.path.join(`, `)}]`),e;let a=t.path[0],o=r(i);return o===i?e:zR(e,[...e.parts.slice(0,a),o,...e.parts.slice(a+1)])},WR=(e,t,n)=>{let r=t.part;if(r.type===`text`||r.type===`reasoning`)return BR(e,{type:r.type,text:``,status:{type:`running`},...r.type===`reasoning`&&r.unstable_summary!==void 0?{unstable_summary:r.unstable_summary}:void 0,...r.parentId&&{parentId:r.parentId}});if(r.type===`tool-call`)return BR(e,{type:`tool-call`,state:`partial-call`,status:{type:`running`,isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:``,args:{},timing:{startedAt:Date.now()},...r.parentId&&{parentId:r.parentId}});if(r.type===`source`)return BR(e,{type:`source`,sourceType:r.sourceType,id:r.id,url:r.url,...r.title?{title:r.title}:void 0,...r.parentId&&{parentId:r.parentId}});if(r.type===`file`)return BR(e,{type:`file`,mimeType:r.mimeType,data:r.data,...r.parentId&&{parentId:r.parentId}});if(r.type===`data`)return BR(e,{type:`data`,name:r.name,data:r.data,...r.parentId&&{parentId:r.parentId}});{let t=String(r.type);return n(`unsupported-part-start:${t}`,`Unsupported part-start type ${t}: inserting an empty reasoning part to preserve part indices`),BR(e,{type:`reasoning`,text:``,status:{type:`running`}})}},GR=(e,t,n)=>UR(e,t,n,e=>e.type===`tool-call`?e.state===`partial-call`?{...e,state:`call`,status:e.status.type===`running`?{type:`running`,isArgsComplete:!0}:e.status}:e:(n(`wrong-part:tool-call-args-text-finish`,`Dropped tool-call-args-text-finish chunk: part is not a tool-call`),e)),KR=(e,t,n)=>UR(e,t,n,e=>({...e,status:{type:`complete`,reason:`unknown`}})),qR=(e,t,n)=>UR(e,t,n,e=>{if(e.type===`text`||e.type===`reasoning`)return{...e,text:e.text+t.textDelta};if(e.type===`tool-call`){let n=e.argsText+t.textDelta,r=MR(n)??e.args;return{...e,argsText:n,args:r}}return n(`wrong-part:text-delta`,`Dropped text-delta chunk: part is neither text nor tool-call`),e}),JR=(e,t,n)=>UR(e,t,n,e=>e.type===`tool-call`?{...e,state:`result`,...e.timing===void 0?{}:{timing:{...e.timing,completedAt:e.timing.completedAt??Date.now()}},...t.artifact===void 0?{}:{artifact:t.artifact},result:t.result,isError:t.isError??!1,...t.modelContent===void 0?{}:{modelContent:t.modelContent},...t.messages===void 0?{}:{messages:t.messages},status:{type:`complete`,reason:`stop`}}:(n(`wrong-part:result`,`Dropped result chunk: part is not a tool-call`),e)),YR=(e,t)=>{if(e.status?.type===`incomplete`&&e.status?.reason===`error`)return e;let n=XR(t);return{...e,status:n}},XR=e=>e.finishReason===`tool-calls`?{type:`requires-action`,reason:`tool-calls`}:e.finishReason===`stop`||e.finishReason===`unknown`?{type:`complete`,reason:e.finishReason}:{type:`incomplete`,reason:e.finishReason},ZR=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),QR=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),$R=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:`started`,messageId:t.messageId}]}}),ez=(e,t)=>{let n=e.metadata.steps.slice(),r=n.length-1;return n.length>0&&n[r]?.state===`started`?n[r]={...n[r],state:`finished`,finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}:n.push({state:`finished`,messageId:bR(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:n}}},tz=(e,t)=>{let n=t.severity===`critical`||t.severity===`warning`||t.severity===`info`?t.severity:void 0;return{...e,status:{type:`incomplete`,reason:`error`,error:{code:t.code??`unknown`,message:t.error??`unknown error`,...n!==void 0&&{severity:n}}}}},nz=(e,t,n)=>(n.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:n.state}}),rz=e=>{let t=0;for(let n of e.metadata.steps)n.state===`finished`&&n.usage&&(t+=n.usage.outputTokens);return t},iz=(e,t,n=0)=>{let r=n>0?n:rz(t);if(r>0)return e.getTiming(r);let i=``;for(let e of t.parts)(e.type===`text`||e.type===`reasoning`)&&(i+=e.text);return e.getTiming(void 0,i||void 0)},az=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},oz=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:n,strict:r=!0}={}){let i=e??VR(),a,o,s=new RR,c=new Set,l=(e,t)=>{c.has(e)||c.size>=HR||(c.add(e),console.warn(t))},u,d=t?az(()=>{u?.enqueue(i)}):()=>{u?.enqueue(i)};super({start(e){u=e},transform(e){s.recordChunk();let t=e.type;switch(t){case`part-start`:i=WR(i,e,l),e.part.type===`tool-call`&&s.recordToolCallStart(e.part.toolCallId);break;case`tool-call-args-text-finish`:i=GR(i,e,l);break;case`part-finish`:i=KR(i,e,l);break;case`text-delta`:{let t=qR(i,e,l);t!==i&&s.recordFirstToken(),i=t;break}case`result`:i=JR(i,e,l);break;case`message-finish`:o=e.usage?.outputTokens,i=YR(i,e);break;case`annotations`:i=ZR(i,e);break;case`data`:i=QR(i,e);break;case`step-start`:i=$R(i,e);break;case`step-finish`:i=ez(i,e);break;case`error`:i=tz(i,e),n?.(e.error);break;case`update-state`:a??=new LR(i.metadata.unstable_state,{strict:r}),i=nz(i,e,a);break;default:throw Error(`Unsupported chunk type: ${t}`)}i.status.type!==`running`&&(i={...i,metadata:{...i.metadata,timing:iz(s,i,o)}}),d()},flush(e){if(i.status?.type===`running`){let t=i.parts?.some(e=>e.type===`tool-call`&&(e.state===`call`||e.state===`partial-call`)&&e.result===void 0)??!1;i=YR(i,{type:`message-finish`,path:[],finishReason:t?`tool-calls`:`unknown`,usage:{inputTokens:0,outputTokens:0}}),i={...i,metadata:{...i.metadata,timing:iz(s,i,o)}},e.enqueue(i)}}})}};async function*sz(){let e=this.getReader(),t=!0;try{for(;;){let n;try{n=await e.read()}catch(e){throw t=!1,e}if(n.done){t=!1;break}let{value:r}=n;yield r}}finally{try{t&&await e.cancel()}finally{e.releaseLock()}}}function cz(e){return e[Symbol.asyncIterator]??=sz,e}var lz=class e{readable;constructor(e){this.readable=e}static fromAssistantStream(t){return new e(t.pipeThrough(new oz))}async unstable_result(){let e;for await(let t of this)e=t;return e||{role:`assistant`,status:{type:`complete`,reason:`unknown`},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}}[Symbol.asyncIterator](){return cz(this.readable)[Symbol.asyncIterator]()}tee(){let[t,n]=this.readable.tee();return[new e(t),new e(n)]}};function uz(e,t,n){try{let r=e();if(typeof r==`object`&&r&&`then`in r)return r.then(t,n);t(r)}catch(e){n(e)}}function dz(e,t){let n=e;for(let e of t){if(n==null||!Object.hasOwn(n,e))return;n=n[e]}return n}var fz=class{resolve;reject;disposed=!1;fieldPath;get isDisposed(){return this.disposed}constructor(e,t,n){this.resolve=e,this.reject=t,this.fieldPath=n}update(e){if(!this.disposed)try{if(PR(e,this.fieldPath)===`complete`){let t=dz(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(e){this.reject(e),this.dispose()}}end(e){if(!this.disposed)try{let t=dz(e,this.fieldPath);this.resolve(t)}catch(e){this.reject(e)}finally{this.dispose()}}dispose(){this.disposed=!0}},pz=class{controller;disposed=!1;fieldPath;get isDisposed(){return this.disposed}constructor(e,t){this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{let t=dz(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),PR(e,this.fieldPath)===`complete`&&(this.controller.close(),this.dispose())}catch(e){this.controller.error(e),this.dispose()}}end(){this.disposed||(this.controller.close(),this.dispose())}dispose(){this.disposed=!0}},mz=class{controller;disposed=!1;fieldPath;lastValue=void 0;get isDisposed(){return this.disposed}constructor(e,t){this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{let t=dz(e,this.fieldPath);if(t!==void 0&&typeof t==`string`){let e=t.substring(this.lastValue?.length||0);this.lastValue=t,this.controller.enqueue(e)}PR(e,this.fieldPath)===`complete`&&(this.controller.close(),this.dispose())}catch(e){this.controller.error(e),this.dispose()}}end(){this.disposed||(this.controller.close(),this.dispose())}dispose(){this.disposed=!0}},hz=class{controller;disposed=!1;fieldPath;nextIndex=0;get isDisposed(){return this.disposed}constructor(e,t){this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{let t=dz(e,this.fieldPath);if(!Array.isArray(t))return;for(;this.nextIndex<t.length&&PR(e,[...this.fieldPath,this.nextIndex])===`complete`;this.nextIndex++)this.controller.enqueue(t[this.nextIndex]);PR(e,this.fieldPath)===`complete`&&(this.controller.close(),this.dispose())}catch(e){this.controller.error(e),this.dispose()}}end(){this.disposed||(this.controller.close(),this.dispose())}dispose(){this.disposed=!0}},gz=class{argTextDeltas;handles=new Set;accumulatedText=``;parsedTextLength=-1;args=void 0;finished=!1;constructor(e){this.argTextDeltas=e,this.processStream()}async processStream(){try{let e=this.argTextDeltas.getReader();for(;;){let{value:t,done:n}=await e.read();if(n)break;this.accumulatedText+=t,this.handles.size!==0&&this.parseCurrentArgs()&&this.updateHandles()}}catch(e){console.error(`Error processing argument stream:`,e)}finally{this.finished=!0;for(let e of this.handles)e.end(this.args);this.handles.clear()}}parseCurrentArgs(){if(this.parsedTextLength===this.accumulatedText.length)return!1;let e=MR(this.accumulatedText);return this.parsedTextLength=this.accumulatedText.length,e===void 0?(this.args??=MR(``),!1):(this.args=e,!0)}updateHandles(){for(let e of this.handles)e.update(this.args),e.isDisposed&&this.handles.delete(e)}activateHandle(e){if(this.parseCurrentArgs(),e.update(this.args),!e.isDisposed){if(this.finished){e.end(this.args);return}this.handles.add(e)}}get(...e){return new Promise((t,n)=>{let r=new fz(t,n,e);this.activateHandle(r)})}streamValues(...e){let t=e,n;return cz(new ReadableStream({start:e=>{n=new pz(e,t),this.activateHandle(n)},cancel:()=>{n&&(n.dispose(),this.handles.delete(n))}}))}streamText(...e){let t=e,n;return cz(new ReadableStream({start:e=>{n=new mz(e,t),this.activateHandle(n)},cancel:()=>{n&&(n.dispose(),this.handles.delete(n))}}))}forEach(...e){let t=e,n;return cz(new ReadableStream({start:e=>{n=new hz(e,t),this.activateHandle(n)},cancel:()=>{n&&(n.dispose(),this.handles.delete(n))}}))}},_z=class{promise;constructor(e){this.promise=e}get(){return this.promise}},vz=class{args;response;writable;resolve;argsText=``;constructor(){let e=new TransformStream;this.writable=e.writable,this.args=new gz(e.readable);let{promise:t,resolve:n}=iR();this.resolve=n,this.response=new _z(t)}async appendArgsTextDelta(e){let t=this.writable.getWriter();try{await t.write(e)}catch(e){console.warn(e)}finally{t.releaseLock()}this.argsText+=e}async finishArgsText(){let e=this.writable.getWriter();try{await e.close()}catch(e){console.warn(e)}finally{e.releaseLock()}}setResponse(e){this.resolve(e)}result={get:async()=>(await this.response.get()).result}},yz=Symbol.for(`assistant-stream.tool-execution-id`),bz=(e,t,n,r,i)=>{try{let a=t?.(n,r,i);Promise.resolve(a).catch(t=>{console.error(`[assistant-stream] ${e} callback threw an error`,t)})}catch(t){console.error(`[assistant-stream] ${e} callback threw an error`,t)}},xz=e=>e.join(`,`),Sz=(e,t)=>{let n={...e};return Object.defineProperty(n,yz,{value:t,enumerable:!0}),n},Cz=class extends wR{constructor(e){let t=e,n=new Map,r=new Map,i=new Set,a=new Map,o=0;super(e=>{let s=new TransformStream({async transform(e,s){let c=a.get(xz(e.path));switch((e.type!==`part-finish`||e.meta.type!==`tool-call`)&&s.enqueue(c?Sz(e,c):e),e.type){case`part-start`:{let n=o;if(o+=1,e.part.type===`tool-call`){let i=new vz,o=Symbol();a.set(String(n),o),r.set(o,i),t.streamCall({reader:i,toolCallId:e.part.toolCallId,toolName:e.part.toolName,executionId:o})}break}case`text-delta`:if(e.meta.type===`tool-call`){let t=a.get(xz(e.path)),n=t?r.get(t):void 0;if(!n)throw Error(`No controller found for tool call`);await n.appendArgsTextDelta(e.textDelta)}break;case`result`:{if(e.meta.type!==`tool-call`)break;let t=a.get(xz(e.path)),n=t?r.get(t):void 0;if(!n)throw Error(`No controller found for tool call`);n.setResponse(new rR({result:e.result,artifact:e.artifact,isError:e.isError,modelContent:e.modelContent,messages:e.messages})),i.add(t);break}case`tool-call-args-text-finish`:{if(e.meta.type!==`tool-call`)break;let{toolCallId:o,toolName:c}=e.meta,l=a.get(xz(e.path)),u=l?r.get(l):void 0;if(!u)throw Error(`No controller found for tool call`);if(await u.finishArgsText(),i.has(l))break;let d=!1,f=uz(()=>{let e;try{e=kR.default.parse(u.argsText)}catch(e){throw Error(`Function parameter parsing failed. ${JSON.stringify(e.message)}`)}let n=t.execute({toolCallId:o,toolName:c,args:e,executionId:l});return n!==void 0&&(d=!0,bz(`onExecutionStart`,t.onExecutionStart,o,c,l)),n},n=>{if(d&&bz(`onExecutionEnd`,t.onExecutionEnd,o,c,l),n===void 0)return;let r=new rR({artifact:n.artifact,result:n.result,isError:n.isError,messages:n.messages,modelContent:n.modelContent});u.setResponse(r),sR(s,Sz({type:`result`,path:e.path,...r},l))},n=>{d&&bz(`onExecutionEnd`,t.onExecutionEnd,o,c,l);let r=new rR({result:String(n),isError:!0});u.setResponse(r),sR(s,Sz({type:`result`,path:e.path,...r},l))});f&&n.set(l,f);break}case`part-finish`:{if(e.meta.type!==`tool-call`)break;let t=a.get(xz(e.path)),o=t?n.get(t):void 0,c=()=>{t&&(n.delete(t),r.delete(t),i.delete(t),a.delete(xz(e.path)))};o?o.then(()=>{c(),sR(s,e)}):(c(),s.enqueue(e))}}},async flush(){await Promise.all(n.values())}});return e.pipeThrough(new ER).pipeThrough(s)})}},wz=Symbol.for(`assistant-stream.tool-execution-id`),Tz=Symbol(`assistant-stream.tool-aborted`),Ez=e=>typeof e==`object`&&!!e&&`~standard`in e&&e[`~standard`].version===1,Dz=e=>typeof e?.then==`function`,Oz=async(e,t,n=!1)=>{let r,i=new Promise(e=>{r=()=>{n?queueMicrotask(()=>queueMicrotask(()=>e(Tz))):e(Tz)},t.aborted?r():t.addEventListener(`abort`,r,{once:!0})});try{return await Promise.race([e,i])}finally{t.removeEventListener(`abort`,r)}},kz=()=>new rR({result:`Tool execution was cancelled.`,isError:!0});function Az(e,t,n,r){let i=e?.[n.toolName];return i?.execute?(async e=>{if(t.aborted)return kz();let a=e;if(Ez(i.parameters)){let e=i.parameters[`~standard`].validate(n.args),r=Dz(e)?await Oz(e,t):e;if(r===Tz)return kz();r.issues&&(a=i.experimental_onSchemaValidationError??(()=>{throw Error(`Function parameter validation failed. ${JSON.stringify(r.issues)}`)}))}if(t.aborted)return kz();let o=await Oz((async()=>{let e={toolCallId:n.toolCallId,abortSignal:t,human:e=>r(n.toolCallId,e,n.executionId),[wz]:n.executionId},o=await a(n.args,e),s=rR.toResponse(o);if(i.toModelOutput&&!s.isError&&s.modelContent===void 0)try{let e=await i.toModelOutput({toolCallId:n.toolCallId,input:n.args,output:s.result});return new rR({result:s.result,artifact:s.artifact,isError:s.isError,messages:s.messages,modelContent:e})}catch(e){console.warn(`[assistant-stream] tool "${n.toolName}" toModelOutput threw; falling back to default projection.`,e)}return s})(),t,!0);return o===Tz?kz():o})(i.execute):void 0}function jz(e,t,n,r,i){let a={toolCallId:r.toolCallId,abortSignal:t,human:e=>i(r.toolCallId,e,r.executionId),[wz]:r.executionId};e?.[r.toolName]?.streamCall?.(n,a)}function Mz(e,t,n,r){let i=typeof e==`function`?e:()=>e,a=typeof t==`function`?t:()=>t,o=r,s=n;return new Cz({execute:e=>Az(i(),a(),e,s),streamCall:({reader:e,...t})=>jz(i(),a(),e,t,s),onExecutionStart:o?.onExecutionStart,onExecutionEnd:o?.onExecutionEnd})}var Nz=new Set([`http://json-schema.org/draft-07/schema`,`https://json-schema.org/draft-07/schema`]);function Pz(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}function Fz(e){return typeof e==`object`&&!!e&&`toJSONSchema`in e&&typeof e.toJSONSchema==`function`}function Iz(e){return typeof e==`object`&&!!e&&`toJSON`in e&&typeof e.toJSON==`function`}function Lz(e){if(typeof e==`object`&&e){let t=e.$schema;if(typeof t==`string`&&!Nz.has(t.replace(/#$/,``)))throw Error(`The schema library was asked for a draft-07 JSON Schema and returned "${t}". Upgrade the library, or pass a plain JSON Schema object instead.`)}return e}function Rz(e){if(Pz(e)){let t=e[`~standard`].jsonSchema;if(typeof t==`object`&&t&&typeof t.input==`function`)return Lz(t.input({target:`draft-07`}))}if(Fz(e))return e.toJSONSchema({target:`draft-07`});if(Iz(e))return e.toJSON();if(Pz(e)){let{vendor:t}=e[`~standard`],n=t===`zod`?`convert it with z.toJSONSchema(schema)`:`wrap the schema with ${t}'s Standard JSON Schema helper`;throw Error(`Could not convert the "${t}" schema to JSON Schema: it has no "~standard.jsonSchema" converter. Upgrade ${t} to a release that implements Standard JSON Schema, ${n}, or pass a plain JSON Schema object instead.`)}return e}function zz(e){let{required:t,...n}=e;return n.properties&&=Object.fromEntries(Object.entries(n.properties).map(([e,t])=>typeof t==`object`&&t&&!Array.isArray(t)?[e,zz(t)]:[e,t])),n}function Bz(e){return $L(mN(()=>{try{let t=Rz(e);return YL(t)?t:null}catch{return null}},[e]))}var Vz=e=>{let t=J(17),n=Q(),r;t[0]===e?r=t[1]:(r=t=>t.unstable_interactables.definitions[e]?.state,t[0]=e,t[1]=r);let i=$(r),a;t[2]===e?a=t[3]:(a=t=>t.unstable_interactables.persistence[e],t[2]=e,t[3]=a);let o=$(a),s;t[4]!==n||t[5]!==e?(s=t=>{n.unstable_interactables.setState(e,e=>typeof t==`function`?t(e):t)},t[4]=n,t[5]=e,t[6]=s):s=t[6];let c=s,l;t[7]===n?l=t[8]:(l=()=>n.unstable_interactables.flush(),t[7]=n,t[8]=l);let u=l,d=o?.isPending??!1,f=o?.error,p;t[9]!==u||t[10]!==c||t[11]!==d||t[12]!==f?(p={setState:c,isPending:d,error:f,flush:u},t[9]=u,t[10]=c,t[11]=d,t[12]=f,t[13]=p):p=t[13];let m;return t[14]!==i||t[15]!==p?(m=[i,p],t[14]=i,t[15]=p,t[16]=m):m=t[16],m};function Hz(e){let t=e.metadata;if(!t||typeof t!=`object`)return;let n=t.custom;if(!n||typeof n!=`object`)return;let r=n.interactables;return Array.isArray(r)?r:void 0}function Uz(e){return`update_${e.replace(/[^a-zA-Z0-9_-]/g,`_`)}`}var Wz=e=>{if(!JL(e))return;let t=e.id;return typeof t==`string`||typeof t==`number`?t:void 0};function Gz(e,t,n){let r=Array.isArray(t.set)?[...t.set]:[...e];if(t.clear===!0&&(r=[]),Array.isArray(t.remove)&&t.remove.length>0){let e=new Set(t.remove);r=r.filter(t=>{let n=Wz(t);return n===void 0?!e.has(t):!e.has(n)})}let i=t.update;if(Array.isArray(i)&&i.length>0){let e=new Map;for(let t of i){let n=Wz(t);n!==void 0&&!Number.isNaN(n)&&!e.has(n)&&e.set(n,t)}r=r.map(t=>{let n=Wz(t);if(n===void 0||!JL(t))return t;let r=e.get(n);return r?{...t,...r}:t})}if(Array.isArray(t.add)&&t.add.length>0){let e=n?t.add.map(e=>{if(!JL(e)||e.id!==void 0)return e;let t=n();return t===void 0?e:{...e,id:t}}):t.add;r=[...r,...e]}return r}function Kz(e,t,n){if(!JL(e)||!JL(t))return t;let r=JL(n?.arrayBaseline)?n.arrayBaseline:e,i=Object.entries(e);for(let[e,a]of Object.entries(t)){let t=r[e];if(Array.isArray(t)&&JL(a)){let r=n?.idFactory&&(n.idKeyedFields===void 0||n.idKeyedFields.has(e))?()=>n.idFactory?.(e):void 0;i.push([e,Gz(t,a,r)])}else i.push([e,a])}return Object.fromEntries(i)}function qz(e,t){if(!JL(e)||!JL(t))return;for(let n of Object.keys(e))if(!Object.hasOwn(t,n))return;let n=[];for(let[r,i]of Object.entries(t))(!Object.hasOwn(e,r)||!QL(e[r],i))&&n.push([r,i]);let r=n.length;if(r!==0&&r!==Object.keys(t).length)return Object.fromEntries(n)}var Jz=e=>{if(!e||typeof e!=`object`)return;let t=e;return t.type===`tool-call`?t:void 0},Yz=(e,t)=>{if(!e.args||typeof e.args!=`object`)return!1;let n=JL(e.result)?e.result:void 0;if(n?.success===!1)return!1;if(typeof n?.id==`string`)return n.id===t;let r=e.args.id;return r===t||r===void 0},Xz=e=>{let t=JL(e)?e.addedItemIds:void 0;if(!JL(t))return;let n=new Map;for(let[e,r]of Object.entries(t)){if(!Array.isArray(r))continue;let t=r.filter(e=>typeof e==`string`);t.length>0&&n.set(e,t)}if(n.size!==0)return e=>n.get(e)?.shift()},Zz=new WeakMap;function Qz(e,t,n){let r=Zz.get(e);r||(r=new Map,Zz.set(e,r));let i=r.get(n);i||(i=new Map,r.set(n,i));let a=i.get(t);if(a)return a;let o=Uz(n),s=[],c=()=>s[s.length-1];for(let r of e){if(r.role===`user`){let e=Hz(r)?.find(e=>e.id===t);if(!e)continue;if(e.partial){let t=c();t&&s.push({state:Kz(t.state,e.state),origin:`user-edit`})}else s.push({state:e.state,origin:`user-edit`});continue}if(r.role===`assistant`)for(let e of r.content??[]){let r=Jz(e);if(r){if(r.toolCallId===t&&r.toolName===n)r.args&&typeof r.args==`object`&&s.push({state:r.args,origin:`create`,toolCallId:t});else if(r.toolName===o&&Yz(r,t)){let e=c();if(e){let{id:t,...n}=r.args,i=Xz(r.result);s.push({state:i?Kz(e.state,n,{idFactory:i}):Kz(e.state,n),origin:`update`,toolCallId:r.toolCallId})}}}}}return i.set(t,s),s}function $z(e,t,n){let r=Qz(e,t,n),i=r[r.length-1];return i?{state:i.state}:void 0}function eB(e,t){if(!e)return;let{interactables:n,...r}=e,i={...r};if(Array.isArray(n)){let e=[];for(let r of n){let n=$z(t,r.id,r.name);if(!n){e.push({id:r.id,name:r.name,state:r.state});continue}if(QL(r.state,n.state))continue;let i=qz(n.state,r.state);e.push(i?{id:r.id,name:r.name,state:i,partial:!0}:{id:r.id,name:r.name,state:r.state})}e.length&&(i.interactables=e)}return Object.keys(i).length?i:void 0}var tB=(e,t)=>{let n=Q(),r=xN().replace(/[^a-zA-Z0-9]/g,``),i=Uz(e),a=$(e=>{let t=e.optional.part;return t?.type===`tool-call`?t:void 0}),o;if(a?.toolName===i){let e=a.result,t=a.args;e?.success!==!1&&(typeof e?.id==`string`?o=e.id:typeof t?.id==`string`&&(o=t.id))}let s=t.id??o??r,c=a?.toolName===e||a?.toolName===i?`thread`:void 0,l=Y(t.stateSchema);l.current=t.stateSchema;let u=Bz(t.stateSchema),d=Y(t.initialState);d.current=t.initialState;let f=$(()=>n.unstable_interactables);X(()=>f.register({id:s,name:e,description:t.description,stateSchema:l.current,initialState:d.current,updateRender:t.updateRender,...c?{scope:c}:{}}),[f,s,e,t.description,u,c,t.updateRender]);let p=a?.toolCallId,[m,h]=Vz(s),{setState:g}=h,_=$(eR(t=>{if(!c||!p)return;let n=Qz(t.thread.messages,s,e);if(!n.some(e=>e.origin===`create`&&e.toolCallId===s))return;let r=n.find(e=>e.toolCallId===p);if(!r)return;let i=n.findLast(e=>e.toolCallId!==void 0)?.toolCallId;return{state:r.state,isLatest:i===p}})),v=mN(()=>_&&{state:_.state,isLatest:_.isLatest,restore:()=>g(_.state)},[_,g]);return[m===void 0?t.initialState:m,{id:s,version:v,...h}]},nB=ON(null),rB=(e,t)=>PM(nB,e,t),iB=()=>AN(nB),aB={},oB=e=>{let t=LF(e??aB);return e==null?null:t},sB=Symbol(`innerMessage`),cB=Symbol(`innerMessages`),lB=[],uB=(e,t)=>{sB in e||(e[sB]=t)},dB=e=>{let t=`messages`in e?e.messages:e,n=t[cB]||t[sB];return n?Array.isArray(n)?n:(t[cB]=[n],t[cB]):lB},fB=`__external_store_fallback_`,pB=yR(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7);function mB(e){let t=e.match(/^data:([^;,]+)(?:;[^;,]+)*;base64,(.*)$/i);return t?{mimeType:t[1].toLowerCase(),data:t[2]}:null}var hB=(e,t)=>{if(e.startsWith(`data-`))return{type:`data`,name:e.substring(5),data:t}},gB=(e,t,n)=>{let{role:r,id:i,createdAt:a,attachments:o,status:s,metadata:c}=e,l={id:i??t,createdAt:a??new Date},u=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content,d=({image:e,...t})=>typeof e==`string`?mB(e)?.mimeType.startsWith(`image/`)||/^(https:\/\/|blob:)/i.test(e)?{...t,image:e}:(console.warn(`Invalid image data format detected`),null):null;if(r!==`user`&&o?.length)throw Error(`attachments are only supported for user messages`);if(r!==`assistant`&&s)throw Error(`status is only supported for assistant messages`);if(r!==`assistant`&&c?.steps)throw Error(`metadata.steps is only supported for assistant messages`);switch(r){case`assistant`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:return e.text?.trim()?e:null;case`reasoning`:return!e.text?.trim()&&!e.unstable_summary?.trim()?null:e;case`file`:case`source`:return e;case`image`:return d(e);case`data`:return e;case`generative-ui`:return e;case`tool-call`:{let{parentId:t,messages:n,...r}=e,i={...r,toolCallId:e.toolCallId||`tool-${pB()}`,...t!==void 0&&{parentId:t},...n!==void 0&&{messages:n}};return e.args?{...i,args:e.args,argsText:e.argsText??JSON.stringify(e.args)}:{...i,args:MR(e.argsText??``)??{},argsText:e.argsText??``}}default:{let n=hB(t,e.data);if(n)return n;throw Error(`Unsupported assistant message part type: ${t}`)}}}).filter(e=>!!e),status:s??n,metadata:{unstable_state:c?.unstable_state??null,unstable_annotations:c?.unstable_annotations??[],unstable_data:c?.unstable_data??[],custom:c?.custom??{},steps:c?.steps??[],...c?.timing&&{timing:c.timing},...c?.submittedFeedback&&{submittedFeedback:c.submittedFeedback},...c?.isOptimistic&&{isOptimistic:!0},...c?.modality&&{modality:c.modality}}};case`user`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:case`image`:case`audio`:case`file`:case`data`:return e;default:{let n=hB(t,e.data);if(n)return n;throw Error(`Unsupported user message part type: ${t}`)}}}),attachments:(o??[]).map(e=>({...e,content:e.content.map(e=>hB(e.type,e.data)??e)})),metadata:{custom:c?.custom??{},...c?.isOptimistic&&{isOptimistic:!0},...c?.modality&&{modality:c.modality}}};case`system`:if(u.length!==1||u[0].type!==`text`)throw Error(`System messages must have exactly one text message part.`);return{...l,role:r,content:u,metadata:{custom:c?.custom??{}}};default:throw Error(`Unknown message role: ${r}`)}},_B=e=>e.type===`tool-call`&&e.result===void 0,vB=e=>{if(e.type!==`tool-call`||e.result!==void 0)return!1;let t=e.messages?.at(-1);return t?.role===`assistant`&&t.status.type===`running`},yB=e=>e.type!==`tool-call`||e.result!==void 0?!1:e.interrupt!=null||e.approval!=null&&e.approval.approved===void 0&&e.approval.resolution===void 0,bB=Symbol(`autoStatus`),xB=Object.freeze(Object.assign({type:`running`},{[bB]:!0})),SB=Object.freeze(Object.assign({type:`complete`,reason:`unknown`},{[bB]:!0})),CB=Object.freeze(Object.assign({type:`incomplete`,reason:`cancelled`},{[bB]:!0})),wB=Object.freeze(Object.assign({type:`requires-action`,reason:`tool-calls`},{[bB]:!0})),TB=Object.freeze(Object.assign({type:`requires-action`,reason:`interrupt`},{[bB]:!0})),EB=e=>e[bB]===!0,DB=(e,t,n,r,i,a,o)=>e&&i?Object.assign({type:`incomplete`,reason:`error`,error:i},{[bB]:!0}):e&&t?xB:n?TB:o&&!a?xB:r?wB:a?CB:SB,OB=e=>DB(!1,!1,typeof e!=`string`&&e.some(yB),typeof e!=`string`&&e.some(_B)),kB=(e,t,n)=>DB(t,n,typeof e!=`string`&&e.some(yB),typeof e!=`string`&&e.some(_B),void 0,void 0,typeof e!=`string`&&e.some(vB)),AB=class{cache=new WeakMap;convertMessages(e,t){return e.map((e,n)=>{let r=t(this.cache.get(e),e,n);return this.cache.set(e,r),r})}},jB=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},MB=500,NB=({adapterRef:e,snapshot:t,updatePersistenceStatus:n})=>{let r=Y(void 0),i=Y(0),a=Y(new Map),o=Y(0),s=Y([]),c=Y(new Set),l=Y([]),u=Y(()=>{}),d=hN(e=>{if(c.current.size===0)return;let n=new Set(c.current);c.current.clear();let r=++i.current;for(let e of n)a.current.set(e,r);return{adapter:e,payload:t(),dirtyIds:n,seq:r}},[t]),f=hN(e=>{let t=d(e);t&&(o.current===0?u.current(t):l.current.push(t))},[d]),p=hN(async t=>{let i=t??(e.current?d(e.current):void 0);if(!i){if(o.current===0){for(let e of s.current)e();s.current=[]}return}let{adapter:f,payload:p,dirtyIds:m,seq:h}=i;o.current+=1,n(e=>{let t=mM(e);for(let e of m)t[e]={isPending:!0,error:void 0};return t});let g=e=>{let t=[];for(let e of m)a.current.get(e)!==h||c.current.has(e)||(a.current.delete(e),t.push(e));t.length!==0&&n(n=>{let r=!1,i=mM(n);for(let a of t)n[a]!==void 0&&(e===void 0?delete i[a]:i[a]=e,r=!0);return r?i:n})};try{await f.save(p),g(void 0)}catch(e){g({isPending:!1,error:e})}finally{--o.current;let t=l.current.shift()??(e.current&&c.current.size>0?d(e.current):void 0);if(t)r.current!==void 0&&(clearTimeout(r.current),r.current=void 0),u.current(t);else if(o.current===0){for(let e of s.current)e();s.current=[]}}},[e,d,n]);return u.current=e=>{p(e)},{flushIfPending:hN(()=>{r.current!==void 0&&(clearTimeout(r.current),r.current=void 0),e.current&&f(e.current)},[e,f]),schedulePersistence:hN(t=>{e.current&&(c.current.add(t),r.current!==void 0&&clearTimeout(r.current),r.current=setTimeout(()=>{r.current=void 0,o.current===0&&e.current?f(e.current):r.current=setTimeout(()=>{r.current=void 0,e.current&&f(e.current)},MB)},MB))},[e,f]),flush:hN(async()=>{if(r.current!==void 0&&(clearTimeout(r.current),r.current=void 0),!(o.current>0||c.current.size>0||l.current.length>0))return;let t=new Promise(e=>{s.current.push(e)});return e.current&&f(e.current),t},[e,f])}},PB={type:`string`,description:`The id of the instance to update, as shown in its state snapshot in the conversation.`},FB={type:`string`,description:`The id of an item currently in this list.`},IB=e=>{let t=e.properties;return JL(t)&&t.id!==void 0},LB=e=>({...e,required:[`id`]}),RB=e=>{let{id:t,...n}=JL(e.properties)?e.properties:{},r=Array.isArray(e.required)?e.required.filter(e=>e!==`id`):e.required;return{...e,properties:n,required:r}},zB=(e,t)=>{if(!JL(e)||e.type!==`array`)return e;let n=e.items;if(Array.isArray(n)||!JL(n))return e;let r=IB(n),i={add:{type:`array`,items:r?RB(n):n},remove:{type:`array`,items:r?FB:n},clear:{type:`boolean`}};return r&&(i.update={type:`array`,items:LB(n)}),{type:`object`,description:`Operations for array field "${t}". To change one item use update with its id; add new items (their ids are assigned for you), remove items by id, or clear to empty. Change only the items you mean to — never resend the whole array to edit one item.`,properties:i,additionalProperties:!1}},BB=e=>{let t=new Set;for(let[n,r]of Object.entries(e))JL(r)&&r.type===`array`&&JL(r.items)&&IB(r.items)&&t.add(n);return t},VB=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,zB(t,e)]));function HB(e){if(!e||typeof e!=`object`||e.type!==`object`)return{type:`object`,properties:{id:PB},required:[`id`],additionalProperties:!0};let{id:t,...n}=e.properties??{};return{...e,properties:{id:PB,...VB(n)},required:[`id`]}}function UB(e,t,n,r=new Map){let i=Object.values(e);if(i.length===0)return;let a=new Map;for(let e of i){let t=a.get(e.name)??[];t.push(e),a.set(e.name,t)}let o={};for(let[i,s]of a){let a=Uz(i);if(o[a])continue;let c=s[0],l=t.get(c.id),u=l&&JL(l.properties)?BB(l.properties):new Set,d=t=>{if(typeof t==`string`){let n=e[t];return n?.name===i?n:void 0}return s.length===1?c:void 0};o[a]={type:`frontend`,description:`Update the state of interactable component "${i}". ${c.description} Pass the id of the instance to update — instance ids and current state appear in the conversation as state snapshots. Only include the fields you want to change; omitted fields keep their current values.`,parameters:HB(l),streamCall:async(e,{toolCallId:t})=>{try{for await(let i of e.args.streamValues()){if(!i||typeof i!=`object`)continue;let e=i,a=Object.keys(e);if(a.indexOf(`id`)===a.length-1)continue;let{id:o,...s}=e;if(Object.keys(s).length===0)continue;let c=d(o);if(!c)continue;let l=r.get(t),u=l?.targetId===c.id?l.state:c.state;(!l||l.targetId!==c.id)&&r.set(t,{targetId:c.id,state:c.state}),n(c.id,e=>Kz(e,s,{arrayBaseline:u}))}}catch{}},execute:async(e,{toolCallId:t})=>{let{id:a,...o}=e??{},c=d(a);if(!c){let e=s.map(e=>e.id);return{success:!1,error:`Unknown id ${JSON.stringify(a)} for interactable "${i}". Valid ids: ${e.join(`, `)}`}}let l=r.get(t);r.delete(t);let f=mM();n(c.id,e=>Kz(e,o,{arrayBaseline:l?.targetId===c.id?l.state:void 0,idFactory:e=>{let t=pB();return(f[e]??=[]).push(t),t},idKeyedFields:u}));let p={success:!0,id:c.id};return Object.keys(f).length>0&&(p.addedItemIds={...f}),p}}}return{tools:o,unstable_composerMetadata:{interactables:i.map(e=>({id:e.id,name:e.name,state:e.state}))}}}var WB=(e,t,n)=>e.some(e=>e.role===`assistant`&&e.content?.some(e=>{if(!e||typeof e!=`object`)return!1;let r=e;return r.type===`tool-call`&&r.toolCallId===t&&r.toolName===n})),GB=({persistence:e}={})=>{let[t,n]=fN(()=>({definitions:mM(),persistence:mM()})),r=SF(),i=Y(t),a=Y(new Set),o=Y(new Map),s=Y(new Map),c=Y(new Map),l=Y(new Map),u=Y(new Map),d=Y(new Map),f=Y(new Map),p=Y(new Map),m=Y(new Set),h=Y(void 0),g=hN(e=>{let t=e(i.current);i.current=t,n(t)},[]),_=hN(()=>{let e=mM();for(let[t,n]of Object.entries(i.current.definitions))n.scope!==`thread`&&(e[t]={name:n.name,state:n.state});return e},[]),{flushIfPending:v,schedulePersistence:y,flush:b}=NB({adapterRef:h,snapshot:_,updatePersistenceStatus:hN(e=>{g(t=>{let n=e(t.persistence);return n===t.persistence?t:{...t,persistence:n}})},[g])}),x=hN((e,t)=>{let n=t.shouldStash??(()=>!0),r=t.shouldApply??(()=>!0);for(let[r,i]of Object.entries(e))n(r)&&t.stash.set(r,i.state);g(t=>{let n=!1,i=mM(t.definitions);for(let[t,a]of Object.entries(e)){let e=i[t];e&&r(t,e)&&(i[t]={...e,state:a.state},n=!0)}return n?{...t,definitions:i}:t})},[g]),S=hN(e=>{x(e,{stash:l.current})},[x]),C=hN(e=>{x(e,{stash:p.current,shouldStash:e=>!m.current.has(e),shouldApply:(e,t)=>!m.current.has(e)&&t.scope!==`thread`})},[x]),w=hN(async e=>{if(e.load)try{let t=await e.load();if(!t||h.current!==e)return;C(t)}catch(e){console.warn(`[Interactables] Persistence load failed.`,e)}},[C]),T=hN(e=>{h.current!==e&&v(),h.current=e,e&&w(e)},[v,w]),E=hN(()=>{let e=r.current;if(!e)return;let t=e.threadListItem;if(t.source!=null)return t().getState().id;let n=e.threads;if(n.source!=null)return n().getState().mainThreadId},[r]);X(()=>{if(e)return T(e),()=>{h.current===e&&T(void 0)}},[e,T]);let D=hN((e,t)=>{m.current.add(e),g(n=>{let r=n.definitions[e];return r?{...n,definitions:mM(n.definitions,{[e]:{...r,state:t(r.state)}})}:n}),i.current.definitions[e]?.scope!==`thread`&&y(e)},[y,g]),O=mN(()=>({getModelContext:()=>{let e=i.current.definitions;return UB(e,o.current,D,c.current)??{}},subscribe:e=>(a.current.add(e),()=>{a.current.delete(e)})}),[D]);X(()=>{xI(a.current)},[t]),CF(`modelContext`,()=>r.current.modelContext().register(O),[O]);let k=hN((e,t)=>{let n=r.current?.tools;return!n||n.source==null?!1:(t.unsubscribe=n().setToolUI(Uz(e),t.render,{standalone:!0}),!0)},[r]);return CF(`tools`,()=>{for(let[e,t]of f.current)t.unsubscribe?.(),t.unsubscribe=void 0,k(e,t);return()=>{for(let e of f.current.values())e.unsubscribe?.(),e.unsubscribe=void 0}},[k]),{getState:()=>i.current,register:hN(e=>{let t=r.current?.thread,n=t&&t.source!=null?t().getState().messages??[]:[],i=e.scope??(WB(n,e.id,e.name)?`thread`:`app`);d.current.set(e.id,(d.current.get(e.id)??0)+1);let a;if(e.updateRender){let t=f.current.get(e.name),n=t??{count:0,render:e.updateRender,unsubscribe:void 0};n.count++,t||f.current.set(e.name,n),!n.unsubscribe&&k(e.name,n),a=()=>{let t=f.current.get(e.name);t&&--t.count===0&&(f.current.delete(e.name),t.unsubscribe?.(),t.unsubscribe=void 0)}}if(s.current.get(e.id)!==e.stateSchema){s.current.set(e.id,e.stateSchema),o.current.delete(e.id);try{let t=Rz(e.stateSchema);o.current.set(e.id,zz(t))}catch(t){console.warn(`[Interactables] Failed to create partial schema for "${e.name}". The update tool will accept arbitrary fields without validation.`,t)}}let c=i===`thread`?E():void 0,m=i===`thread`?c?u.current.get(c)?.get(e.id):void 0:l.current.get(e.id);i===`thread`?c&&u.current.get(c)?.delete(e.id):l.current.delete(e.id);let h=i===`thread`?void 0:p.current.get(e.id),_=i===`thread`?$z(n,e.id,e.name):void 0;return g(t=>({...t,definitions:mM(t.definitions,{[e.id]:{id:e.id,name:e.name,description:e.description,stateSchema:e.stateSchema,initialState:e.initialState,scope:i,state:t.definitions[e.id]?.state??m??_?.state??h??e.initialState}})})),()=>{a?.();let t=(d.current.get(e.id)??1)-1;if(t>0){d.current.set(e.id,t);return}d.current.delete(e.id),v(),g(t=>{let n=t.definitions[e.id];if(n){if(n.scope===`thread`){let t=E();if(t){let r=u.current.get(t);r||(r=new Map,u.current.set(t,r)),r.set(e.id,n.state)}}else l.current.set(e.id,n.state)}s.current.delete(e.id),o.current.delete(e.id);let r=mM(t.definitions),i=mM(t.persistence);return delete r[e.id],delete i[e.id],{...t,definitions:r,persistence:i}})}},[v,r,E,k,g]),setState:D,exportState:_,importState:S,setPersistenceAdapter:T,flush:b}},KB=jN(GB);oF(GB,(e,t)=>{!e.modelContext&&t.modelContext.source===null&&(e.modelContext=II())});var qB=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=jP({attachment:dI({source:`message`,query:{type:`index`,index:n},get:e=>e.message.attachment({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(zL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},JB=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=jP({attachment:dI({source:`composer`,query:{type:`index`,index:n},get:e=>e.composer.attachment({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(zL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},YB=e=>{let t=J(6),{runtime:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=jP({threadListItem:kL({runtime:n})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(zL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},XB=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=jP({message:dI({source:`thread`,query:{type:`index`,index:n},get:e=>e.thread.message({index:n})}),composer:dI({source:`message`,query:{},get:e=>e.thread.message({index:n}).composer()})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(zL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},ZB=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=jP({part:dI({source:`message`,query:{type:`index`,index:n},get:e=>e.message.part({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(zL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},QB=jN(e=>{let t=J(7),{text:n,isRunning:r}=e,i;t[0]===r?i=t[1]:(i=r?{type:`running`}:{type:`complete`},t[0]=r,t[1]=i);let a;t[2]!==i||t[3]!==n?(a={type:`text`,text:n,status:i},t[2]=i,t[3]=n,t[4]=a):a=t[4];let o=a,s;return t[5]===o?s=t[6]:(s={getState:()=>o,addToolResult:eV,resumeToolCall:tV,respondToToolApproval:nV},t[5]=o,t[6]=s),s}),$B=e=>{let t=J(7),{text:n,isRunning:r,children:i}=e,a=r!==void 0&&r,o=Q(),s;t[0]!==a||t[1]!==n?(s=jP({part:QB({text:n,isRunning:a})}),t[0]=a,t[1]=n,t[2]=s):s=t[2];let c=s,l;return t[3]!==o||t[4]!==i||t[5]!==c?(l=(0,b.jsx)(zL,{extends:o,config:c,children:i}),t[3]=o,t[4]=i,t[5]=c,t[6]=l):l=t[6],l};function eV(){throw Error(`Not supported`)}function tV(){throw Error(`Not supported`)}function nV(){throw Error(`Not supported`)}var rV=e=>{for(let t of e)if(t?.status.type===`running`)return fL;return e.at(-1)?.status??dL},iV=(e,t)=>{let n={running:0,complete:0,incomplete:0,requiresAction:0},r=dL,i=!1;for(let a of t)switch(r=e[a]?.status??dL,r.type){case`running`:n.running++,i=!0;break;case`complete`:n.complete++;break;case`incomplete`:n.incomplete++;break;case`requires-action`:n.requiresAction++}return{status:i?fL:r,counts:n}},aV=jN(e=>{let t=J(11),{parts:n,getMessagePart:r}=e,[i,a]=fN(!0),o;t[0]===n?o=t[1]:(o=rV(n),t[0]=n,t[1]=o);let s=o,c;t[2]!==i||t[3]!==n||t[4]!==s?(c={parts:n,collapsed:i,status:s},t[2]=i,t[3]=n,t[4]=s,t[5]=c):c=t[5];let l=c,u;t[6]===l?u=t[7]:(u=()=>l,t[6]=l,t[7]=u);let d;return t[8]!==r||t[9]!==u?(d={getState:u,setCollapsed:a,part:r},t[8]=r,t[9]=u,t[10]=d):d=t[10],d}),oV=e=>{let t=J(4),{startIndex:n,endIndex:r,children:i}=e,a=$(sV).slice(n,r+1),o=Q(),s=jP({chainOfThought:aV({parts:a,getMessagePart:e=>{let{index:t}=e;if(t<0||t>=a.length)throw Error(`ChainOfThought part index ${t} is out of bounds (0..${a.length-1})`);return o.message.part({index:n+t})}})}),c;return t[0]!==i||t[1]!==s||t[2]!==o?(c=(0,b.jsx)(zL,{extends:o,config:s,children:i}),t[0]=i,t[1]=s,t[2]=o,t[3]=c):c=t[3],c};function sV(e){return e.message.parts}var cV=e=>{let t=J(7),{index:n,archived:r,children:i}=e,a=Q(),o;t[0]!==r||t[1]!==n?(o=jP({threadListItem:dI({source:`threads`,query:{type:`index`,index:n,archived:r},get:e=>e.threads.item({index:n,archived:r})})}),t[0]=r,t[1]=n,t[2]=o):o=t[2];let s=o,c;return t[3]!==a||t[4]!==i||t[5]!==s?(c=(0,b.jsx)(zL,{extends:a,config:s,children:i}),t[3]=a,t[4]=i,t[5]=s,t[6]=c):c=t[6],c},lV=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=jP({suggestion:dI({source:`suggestions`,query:{index:n},get:e=>e.suggestions.suggestion({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(zL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},uV=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=jP({queueItem:dI({source:`composer`,query:{type:`index`,index:n},get:e=>e.composer.queueItem({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(zL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},dV=Symbol.for(`assistant-ui.message-not-sent`),fV=e=>typeof e==`object`&&!!e&&dV in e,pV=class{get path(){return this._core.path}_core;constructor(e){this._core=e,this.__internal_bindMethods()}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},mV=class extends pV{_composerApi;constructor(e,t){super(e),this._composerApi=t}remove(){let e=this._composerApi.getState();if(!e)throw Error(`Composer is not available`);return e.removeAttachment(this.getState().id)}},hV=class extends mV{get source(){return`thread-composer`}},gV=class extends mV{get source(){return`edit-composer`}},_V=class extends pV{get source(){return`message`}remove(){throw Error(`Message attachments cannot be removed`)}},vV=Object.freeze([]),yV=Object.freeze({}),bV=e=>Object.freeze({type:`thread`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??vV,text:e?.text??``,role:e?.role??`user`,runConfig:e?.runConfig??yV,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??vV,value:e?.text??``}),xV=e=>Object.freeze({type:`edit`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,text:e?.text??``,role:e?.role??`user`,attachments:e?.attachments??vV,runConfig:e?.runConfig??yV,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??vV,parentId:e?.parentId??null,sourceId:e?.sourceId??null,value:e?.text??``}),SV=class{get path(){return this._core.path}_core;constructor(e){this._core=e}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.steerQueueItem=this.steerQueueItem.bind(this),this.moveQueueItem=this.moveQueueItem.bind(this),this.removeQueueItem=this.removeQueueItem.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.startDictation=this.startDictation.bind(this),this.stopDictation=this.stopDictation.bind(this),this.setQuote=this.setQuote.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setText(e)}setRunConfig(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRunConfig(e)}addAttachment(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);return t.addAttachment(e)}reset(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.reset()}clearAttachments(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.clearAttachments()}send(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.send(e)}cancel(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.cancel()}steerQueueItem(e){this.moveQueueItem(e,{lane:`steer`,insertAfter:null})}moveQueueItem(e,t){let n=this._core.getState();if(!n)throw Error(`Composer is not available`);n.moveQueueItem(e,t)}removeQueueItem(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.removeQueueItem(e)}setRole(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRole(e)}startDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.startDictation()}stopDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.stopDictation()}setQuote(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setQuote(e)}subscribe(e){return this._core.subscribe(e)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new AI({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},CV=class extends SV{get path(){return this._core.path}get type(){return`thread`}_getState;constructor(e){let t=new OI({path:e.path,getState:()=>bV(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>t.subscribe(e)}),this._getState=t.getState.bind(t),this.__internal_bindMethods()}getState(){return this._getState()}getAttachmentByIndex(e){return new hV(new DI({path:{...this.path,attachmentSource:`thread-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`thread-composer`}:bI},subscribe:e=>this._core.subscribe(e)}),this._core)}},wV=class extends SV{get path(){return this._core.path}get type(){return`edit`}_getState;_beginEdit;constructor(e,t){let n=new OI({path:e.path,getState:()=>xV(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>n.subscribe(e)}),this._beginEdit=t,this._getState=n.getState.bind(n),this.__internal_bindMethods()}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new gV(new DI({path:{...this.path,attachmentSource:`edit-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`edit-composer`}:bI},subscribe:e=>this._core.subscribe(e)}),this._core)}},TV=e=>e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
90
+ Previous: [${e.join(`, `)}]\nIncoming: [${t.join(`, `)}]`);for(let n=0;n<e.length&&n<t.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0},xM=(e,t)=>{oM(e,()=>{t.current=t.wip,t.currentDeps=t.wipDeps,t.isDirty=!1})},SM=(e,t)=>{let n=$j(),r=n.currentIndex++,i=n.cells[r];if(i===void 0){n.isFirstRender||gM();let a=e();return tM&&n.devStrictMode&&e(),i={type:`memo`,current:a,currentDeps:t,wip:a,wipDeps:t,isDirty:!1},n.cells[r]=i,a}i.type!==`memo`&&_M();let a=i;if(bM(a.wipDeps,t))return a.isDirty&&xM(n,a),a.wip;let o=e();return tM&&n.devStrictMode&&e(),a.wip=o,a.wipDeps=t,a.isDirty||(a.isDirty=!0,sM(n.root,()=>{a.wip=a.current,a.wipDeps=a.currentDeps,a.isDirty=!1})),xM(n,a),o};function CM(e){return SM(()=>({current:e}),[])}var wM=Symbol(`tap.Context.defaultValue`),TM=e=>e,EM=new Map,DM=new Set,OM=()=>new Map(EM),kM=(e,t)=>{let n=EM;EM=e;try{return t()}finally{EM=n}},AM=(e,t)=>{e[wM]=t},jM=e=>typeof e==`object`&&!!e&&wM in e,MM=e=>typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===Symbol.for(`react.context`),NM=e=>jM(e)||MM(e),PM=e=>{if(!jM(e)){if(MM(e)){AM(e,e._currentValue??e._currentValue2);return}throw Error("A tap resource's `use()` only accepts a tap context.")}},FM=(e,t,n)=>{if(typeof e!=`object`||!e)throw Error(`useContextProvider only accepts a React context.`);PM(e);let r=e,i=$j(),a=CM(void 0),o=a.current===void 0||!Object.is(a.current.value,t);yM(()=>{a.current={value:t}},[t]);let s=EM.get(r),c=s!==void 0||EM.has(r);EM.set(r,{value:t,source:i});try{return IM(r,o,n)}finally{c?EM.set(r,s):EM.delete(r)}},IM=(e,t,n)=>{let r=DM.has(e);t?DM.add(e):DM.delete(e);try{return n()}finally{r?DM.add(e):DM.delete(e)}},LM=e=>{PM(e);let t=e,n=RM(t,e),r=$j();return(r.wipContextDeps??=new Map).set(t,n.source),n.value},RM=(e,t)=>EM.get(e)??{value:TM(t)[wM],source:null},zM=(e,t,n,r)=>{if(!r)return n;let i=n;for(let[n,a]of r)a!==t&&a!==e&&(i??=new Map).set(n,a);return i},BM=(e,t=e.wipContextDeps)=>{let n=eM();n&&t&&(n.wipContextDeps=zM(n,e,n.wipContextDeps,t))},VM=()=>DM.size>0,HM=e=>{if(!e.contextDeps||!VM())return!1;for(let t of DM.keys())if(e.contextDeps.has(t))return!0;return!1},UM=(e,t,n)=>{if(e.isNeverMounted)throw Error(`Resource updated before mount`);let r=!1,i=!0;e.root.unsettledCount++,e.root.dispatchUpdate(()=>r?i:(r=!0,n&&e.root.changelog.length===0&&!t.cell.isDirty&&!t.hasEagerState&&(t.prevState=t.cell.workInProgress,t.eagerState=n(t.cell.workInProgress,t.action),t.hasEagerState=!0,i=!Object.is(t.cell.current,t.eagerState),!i&&!t.settled&&(t.settled=!0,e.root.unsettledCount--)),i),()=>(r=!0,i=!0,aM(t),t.logged||(t.logged=!0,e.root.changelog.push(t)),!0))},WM=(e,t,n,r,i)=>{let a=r?r(n):n;tM&&e.devStrictMode&&r&&r(n);let o={type:`reducer`,workInProgress:a,current:a,isDirty:!1,queue:null,renderQueue:null,reducer:t,dispatch:n=>{let r=eM();if(r!==null){if(r!==e)throw Error(`Cannot update a resource while rendering a different resource.`);(e.renderPendingCells??=new Set).add(o),(o.renderQueue??=[]).push(n)}else UM(e,{fiber:e,cell:o,action:n,hasEagerState:!1,eagerState:void 0,prevState:o.current,settled:!1,queued:!1,logged:!1},i?t:void 0)}};return o};function GM(e,t,n,r){let i=$j(),a=i.currentIndex++,o=i.cells[a],s=(()=>{if(o!==void 0)return o.type===`reducer`?o:_M();i.isFirstRender||gM();let s=WM(i,e,t,n,r);return i.cells[a]=s,s})(),c=s.queue;if(c!==null){let t=e===s.reducer;for(let n=0;n<c.length;n++){let r=c[n];!r.hasEagerState||!t||!Object.is(r.prevState,s.workInProgress)?(r.prevState=s.workInProgress,r.eagerState=e(s.workInProgress,r.action),r.hasEagerState=!0,tM&&i.devStrictMode&&(r.eagerState=e(s.workInProgress,r.action))):tM&&i.devStrictMode&&e(s.workInProgress,r.action),r.queued=!1,s.workInProgress=r.eagerState}s.queue=null}if(s.reducer=e,s.renderQueue!==null){let t=s.workInProgress;for(let n of s.renderQueue)t=e(t,n);s.renderQueue=null,i.renderPendingCells?.delete(s),Object.is(t,s.workInProgress)||(cM(i,s),s.workInProgress=t)}return s.isDirty&&oM(i,()=>{s.current=s.workInProgress,s.isDirty=!1}),[s.workInProgress,s.dispatch]}function KM(e,t,n){return GM(e,t,n,!1)}var qM=(e,t)=>typeof t==`function`?t(e):t,JM=e=>e===void 0?void 0:typeof e==`function`?e():e;function YM(e){return GM(qM,e,JM,!0)}var XM=(e,t)=>SM(()=>e,t);function ZM(e){let t=$j(),n=CM(e);return n.current!==e&&oM(t,()=>{n.current=e}),XM(((...e)=>{if(tM&&eM())throw Error(`useEffectEvent cannot be called during render`);return n.current(...e)}),[])}var QM=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,$M=()=>{},eN=e=>{let t=e;switch(typeof t.status==`string`?t.status!==`fulfilled`&&t.status!==`rejected`&&e.then($M,$M):(t.status=`pending`,e.then(e=>{t.status===`pending`&&(t.status=`fulfilled`,t.value=e)},e=>{t.status===`pending`&&(t.status=`rejected`,t.reason=e)})),t.status){case`fulfilled`:return t.value;case`rejected`:throw t.reason;default:throw e}},tN=e=>QM(e)?eN(e):LM(e),nN=!1,rN=(e,t,n=t)=>{let r=$j().isNeverMounted,i=r?n():t();tM&&!nN&&(!r||n===t)&&(Object.is(i,t())||(nN=!0,console.error(`The result of getSnapshot should be cached to avoid an infinite loop`)));let[,a]=KM(e=>e+1,0),o=CM(0),s=ZM(()=>{try{if(Object.is(i,t()))return o.current=0,!1}catch{}return!0});return yM(()=>e(()=>{s()&&a()}),[e]),yM(()=>{if(s()){if(++o.current>50)throw o.current=0,Error(`Maximum update depth exceeded. The result of getSnapshot should be cached to avoid an infinite loop.`);a()}},[e,i,t]),i},iN=(e,t)=>{},aN=0,oN=()=>{let e=CM(null);return e.current??=`:tap${aN++}:`,e.current},sN=(e,t,n)=>{let r=()=>{if(!e)return;let n=t();if(typeof e==`function`){let t=e(n);return typeof t==`function`?t:()=>e(null)}return e.current=n,()=>{e.current=null}};n==null?yM(r):yM(r,[...n,e])},cN=y.default;function lN(e){let t=(0,y.useRef)(e);return(0,y.useInsertionEffect)(()=>{t.current=e}),(0,y.useCallback)(((...e)=>t.current(...e)),[])}var uN=cN.useEffectEvent??lN,dN=()=>eM()!==null,fN=y.default,pN=e=>dN()?YM(e):fN.useState(e),mN=(e,t,n)=>dN()?KM(e,t,n):fN.useReducer(e,t,n),Y=e=>dN()?CM(e):fN.useRef(e),hN=(e,t)=>dN()?SM(e,t):fN.useMemo(e,t),gN=(e,t)=>dN()?XM(e,t):fN.useCallback(e,t),X=(e,t)=>dN()?yM(e,t):fN.useEffect(e,t),_N=(e,t)=>dN()?yM(e,t):fN.useLayoutEffect(e,t),vN=e=>dN()?ZM(e):uN(e),yN=(e,t,n)=>dN()?rN(e,t,n):fN.useSyncExternalStore(e,t,n),bN=(e,t)=>dN()?void 0:fN.useDebugValue(e,t),xN=(e,t)=>dN()?yM(e,t):fN.useInsertionEffect(e,t),SN=()=>dN()?oN():fN.useId(),CN=(e,t,n)=>dN()?sN(e,t,n):fN.useImperativeHandle(e,t,n),Z=e=>fN.forwardRef(e),wN=(e,t)=>fN.memo(e,t),TN=fN.Fragment,EN=(...e)=>fN.createElement(...e),DN=(...e)=>fN.cloneElement(...e),ON=e=>fN.isValidElement(e);fN.Children,fN.Suspense;var kN=e=>{let t=fN.createContext(e);return AM(t,e),t},AN=e=>dN()&&NM(e)?tN(e):fN.use(e),jN=e=>dN()&&NM(e)?tN(e):fN.useContext(e);function MN(e){return(...t)=>({hook:e,args:t})}function NN(e,t,n){return typeof t==`function`?(...n)=>NN(e,t(...n)):n?{...t,key:e,deps:n}:{...t,key:e}}var PN=(e,t)=>{if(e.length!==0){if(e.length===1)throw e[0];for(let t of e)console.error(t);throw AggregateError(e,t)}},FN=50,IN={schedulers:new Set,isScheduled:!1},LN=null,RN=[],zN=class{_isDirty=!1;_task;constructor(e){this._task=e}get isDirty(){return this._isDirty}markDirty(){if(LN&&(LN.get(this)??0)>=FN)throw Error(`Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside useEffect.`);this._isDirty=!0,IN.schedulers.add(this),HN()}runTask(){LN?.set(this,(LN.get(this)??0)+1),this._isDirty=!1,this._task()}settle(){this._isDirty=!1}},BN=[];new zN(()=>{let e=BN.splice(0),t=[];for(let n of e)try{n()}catch(e){t.push(e)}PN(t,`Errors occurred while running scheduled tasks`)});var VN=e=>{if(LN!==null){RN.push(e);return}e()},HN=()=>{IN.isScheduled||(IN.isScheduled=!0,WN())},UN=()=>{let e=LN;LN=new Map;let t=[];try{for(let e of IN.schedulers)if(IN.schedulers.delete(e),e.isDirty)try{e.runTask()}catch(e){t.push(e)}}finally{if(LN=e,IN.schedulers.clear(),IN.isScheduled=!1,LN===null)for(;RN.length>0;)try{RN.shift()()}catch(e){t.push(e)}}PN(t,`Errors occurred during flushSync`)},WN=(()=>{if(typeof MessageChannel<`u`){let e=null,t;return()=>{if(!e){let n=new MessageChannel;n.port1.onmessage=()=>{e?.unref?.(),UN()},e=n.port1,t=n.port2}e.ref?.(),t.postMessage(null)}}return()=>setTimeout(UN,0)})(),GN=e=>{if(LN!==null)return tM&&console.warn(`flushTapSync was called from inside a render or commit. The flush is deferred until the current pass completes.`),e();let t=IN;IN={schedulers:new Set,isScheduled:!0};try{let t=e();return UN(),t}finally{let e=IN.schedulers;if(IN=t,e.size>0){for(let t of e)IN.schedulers.add(t);HN()}}};function KN(e){let t=[];for(let n=0;n<e.length;n++)try{e[n]()}catch(e){t.push(e)}PN(t,`Errors during commit`)}function qN(e){let t=e.setup,n=e.setupDeps,r=e.generation,i;try{let e=t();if(e!==void 0&&typeof e!=`function`)throw Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof e}`);i=e}finally{e.generation===r?(e.cleanup=i,e.deps=n):i?.()}}var JN=e=>e.setup===void 0?!1:e.deps===null||e.setupDeps===void 0||!bM(e.deps,e.setupDeps);function YN(e){let t=[],n=[];for(let t of e.effectCells)JN(t)&&n.push(t);for(let e of n)if(e.deps=null,e.cleanup!==void 0)try{e.cleanup()}catch(e){t.push(e)}finally{e.cleanup=void 0}for(let e of n)try{qN(e)}catch(e){t.push(e)}PN(t,`Errors during commit`)}function XN(e){let t=[];for(let n of e.effectCells)if(n.deps=null,n.cleanup)try{n.cleanup?.()}catch(e){t.push(e)}finally{n.cleanup=void 0}PN(t,`Errors during cleanup`)}var ZN={useState:YM,useReducer:KM,useRef:CM,useMemo:SM,useCallback:XM,useEffect:yM,useLayoutEffect:yM,useInsertionEffect:yM,useEffectEvent:ZM,useContext:LM,use:tN,useSyncExternalStore:rN,useDebugValue:iN,useId:oN,useImperativeHandle:sN,useMemoCache:fM},QN=y.default,$N=QN.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE??QN.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,eP=$N==null?null:`H`in $N?{get current(){return $N.H},set current(e){$N.H=e}}:`ReactCurrentDispatcher`in $N?{get current(){return $N.ReactCurrentDispatcher.current},set current(e){$N.ReactCurrentDispatcher.current=e}}:null;function tP(e){if(!eP)return e();let t=eP.current;eP.current=ZN;try{return e()}finally{eP.current=t}}function nP(e,t,n=void 0,r){return{hook:e,root:t,markDirty:n,devStrictMode:r,cells:[],effectCells:[],contextDeps:null,wipContextDeps:null,wipCommitCallbacks:null,memoCache:{current:null,workInProgress:null,index:0},renderPendingCells:null,currentIndex:0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function rP(e){e.wipCommitCallbacks=null,e.wipContextDeps=null,e.memoCache.workInProgress=null}function iP(e){e.isMounted&&(e.isMounted=!1,XN(e))}function aP(e,t){if(e.renderPendingCells!==null){for(let t of e.renderPendingCells)t.renderQueue=null;e.renderPendingCells.clear()}let n=0,r;try{do{if(++n>25)throw Error(`Too many re-renders. tap limits the number of renders to prevent an infinite loop.`);e.memoCache.index=0,Qj(e,()=>{r=tP(()=>e.hook(...t))})}while((e.renderPendingCells?.size??0)>0)}catch(t){throw rP(e),t}return BM(e),r}function oP(e){let t=e.wipCommitCallbacks;e.wipCommitCallbacks=null;let n=tM&&!e.isMounted&&e.devStrictMode===`root`;e.isMounted=!0,e.isNeverMounted=!1,t!==null&&(e.contextDeps=e.wipContextDeps,rM(e.root),e.memoCache.workInProgress!==null&&(e.memoCache.current=e.memoCache.workInProgress,e.memoCache.workInProgress=null),KN(t)),n&&(YN(e),XN(e)),YN(e)}var sP=()=>{let e=$j();return e.devStrictMode?e.isFirstRender?`child`:`root`:null},cP=()=>`child`,lP=()=>null,uP=()=>{if(!tM)return lP;let e=Y(0);return pN(()=>e.current++),e.current===2?cP:lP},dP=()=>eM()?sP:uP(),fP=e=>e(),pP=e=>{let t=[];for(let n of e)try{n()}catch(e){t.push(e)}PN(t,`Errors occurred while notifying Tap root subscribers`)},mP=(e,t,n)=>{let r=new zN(()=>s.handleUpdate()),i=[],a=nM((e,t)=>{(i.length!==0||e())&&(i.push(t),r.markDirty())}),o=nP(fP,a,void 0,t),s={scheduler:r,queue:i,fiber:o,subscribers:new Set,pendingHostRender:!1,isMounted:!1,hasRendered:!1,committedRender:e,context:new Map,value:void 0,applyQueue:()=>{iM(a,a.committedVersion);for(let e of i)tM&&o.devStrictMode&&e(),e();return iM(a,a.committedVersion+a.changelog.length),i.length},publish:(e,t)=>{r.isDirty||a.committedVersion!==t||s.value===e||(s.value=e,VN(()=>pP(s.subscribers)))},finishFlush:(e,t,n)=>{rM(a),i.splice(0,n),s.pendingHostRender=!1,i.length===0&&r.settle(),s.isMounted&&oP(o),s.publish(e,t)},handleUpdate:()=>{let e=s.applyQueue(),t;try{tM&&o.devStrictMode&&kM(s.context,()=>aP(o,[s.committedRender])),t=kM(s.context,()=>aP(o,[s.committedRender]))}catch(e){if(iM(a,a.committedVersion),QM(e)){let t=()=>{s.isMounted&&r.markDirty()};e.then(t,t);return}if(s.isMounted){s.pendingHostRender=!0,n(e=>e+1);return}throw e}if(r.isDirty)throw Error(`Scheduler is dirty, this should never happen`);s.finishFlush(t,a.version,e)}};return s},hP=e=>{let[,t]=pN(0),n=dP(),r=Y(null),i=r.current??=mP(e,n(),t),a=OM(),o=i.scheduler.isDirty||i.pendingHostRender?i.applyQueue():0,s=kM(a,()=>aP(i.fiber,[e])),c={render:e,context:a,value:s,drained:o,wip:i.fiber.wipCommitCallbacks,version:i.fiber.root.version,processed:!1};return i.hasRendered||(i.hasRendered=!0,i.committedRender=e,i.context=a,i.value=s),X(()=>(i.isMounted=!0,()=>{i.isMounted=!1,iP(i.fiber)}),[i]),X(()=>{if(c.processed){i.fiber.isMounted||(oP(i.fiber),i.queue.length&&!i.scheduler.isDirty&&i.scheduler.markDirty());return}if(c.processed=!0,i.committedRender=c.render,i.context=c.context,i.fiber.wipCommitCallbacks!==c.wip){i.scheduler.isDirty||i.handleUpdate();return}if(c.drained>0&&i.fiber.root.version===c.version){i.finishFlush(c.value,c.version,c.drained);return}oP(i.fiber),i.publish(c.value,c.version)}),hN(()=>({getValue:()=>i.value,subscribe:e=>(i.subscribers.add(e),()=>i.subscribers.delete(e))}),[i])},gP=()=>{let e=Y(0),t=e.current,n=$j();return{version:t,markDirty:hN(()=>()=>{e.current++,n.markDirty?.()},[n]),root:n.root}},_P=()=>{let[e]=pN(()=>nM((e,t)=>{let i=!1;r(t=>(i=!e(),i?t:t+1)),i||n(t)})),[t,n]=mN((t,n)=>(iM(e,t),t+ +!!n()),0),[,r]=pN(0);return iM(e,t),{root:e,version:t,markDirty:void 0}},vP=()=>{let e=dP(),{root:t,version:n,markDirty:r}=eM()?gP():_P();return{version:n,createFiber:gN((n,i,a)=>nP(n,t,a?()=>{a(),r?.()}:r,e()),[])}},yP=(e,t,n)=>{let r=Y(null),i=r.current??={wipDeps:null,wip:null,currentDeps:null,current:null};return i.wipDeps=i.currentDeps,i.wip=i.current,X(()=>{i.currentDeps=i.wipDeps,i.current=i.wip}),!n&&i.currentDeps&&bM(i.currentDeps,t)?i.current:(i.wipDeps=t,i.wip=e(),i.wip)};function bP(e){let{version:t,createFiber:n}=vP(),r=hN(()=>n(e.hook,e.key),[e.hook,e.key,n]),i=yP(()=>({value:aP(r,e.args)}),[r,t,e.args],HM(r));return X(()=>()=>iP(r),[r]),X(()=>{oP(r)},[r,i]),i.value}var xP=(e,t)=>{let n=e.get(t);n&&(n.isDirty=!0)},SP=(e,t)=>!e.isDirty&&!HM(e.fiber)&&t!==void 0&&e.committedDeps!==void 0&&bM(e.committedDeps,t),CP=e=>{if(!VM())return!1;for(let{fiber:t}of e.values())if(HM(t))return!0;return!1};function wP(e){let[t]=pN(()=>new Map),{version:n,createFiber:r}=vP(),i=CP(t),a=yP(()=>{let n=new Set,i=[],a=0;for(let o=0;o<e.length;o++){let s=e[o],c=s.key;if(c===void 0)throw Error(`useResources did not provide a key for array at index ${o}`);if(n.has(c))throw Error(`Duplicate key ${c} in useResources`);n.add(c);let l=t.get(c);if(!l){let e=r(s.hook,s.key,()=>xP(t,c));l={fiber:e,next:{value:aP(e,s.args),deps:s.deps},isDirty:!1,committedDeps:void 0,committedValue:void 0},a++,t.set(c,l)}else if(l.fiber.hook!==s.hook){let e=r(s.hook,s.key,()=>xP(t,c)),n=aP(e,s.args);l.next={value:n,deps:s.deps,remount:e}}else if(SP(l,s.deps))typeof l.next==`object`&&rP(l.fiber),l.fiber.contextDeps&&BM(l.fiber,l.fiber.contextDeps),l.next=`skip`;else{let e=aP(l.fiber,s.args);l.next={value:e,deps:s.deps}}i.push(typeof l.next==`object`?l.next.value:l.committedValue)}if(t.size>i.length-a)for(let e of t.keys())n.has(e)||(t.get(e).next=`delete`);return i},[e,t,r,n],i);return X(()=>()=>{for(let e of t.keys())iP(t.get(e).fiber)},[t]),X(()=>{for(let[e,n]of t.entries()){let r=n.next;r===`delete`?(iP(n.fiber),t.delete(e)):r===`skip`?!n.fiber.isNeverMounted&&!n.fiber.isMounted&&oP(n.fiber):(r.remount&&(iP(n.fiber),n.fiber=r.remount),oP(n.fiber),n.committedDeps=r.deps,n.committedValue=r.value,n.isDirty=!1,n.next=`skip`)}},[a,t]),a}var TP=e=>e(),EP=e=>{let{createFiber:t}=vP(),n=hN(()=>t(TP,void 0),[t]),r=aP(n,[e]);X(()=>()=>{iP(n)},[n]);let i=!1,a=()=>{i&&n.isMounted||(i=!0,oP(n))};return X(a),{value:r,effects:a}},DP=MN(()=>{let e=J(4),[t,n]=pN(OP),r;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=(e,t)=>(n(n=>{let r=hM(n.renderers);return r[e]=[...r[e]??[],t],{...n,renderers:r}}),()=>{n(n=>{let r=hM(n.renderers),i=r[e]?.filter(e=>e!==t)??[];return i.length>0?r[e]=i:delete r[e],{...n,renderers:r}})}),e[0]=r):r=e[0];let i=r,a;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=e=>(n(t=>({...t,fallbacks:[...t.fallbacks,e]})),()=>{n(t=>({...t,fallbacks:t.fallbacks.filter(t=>t!==e)}))}),e[1]=a):a=e[1];let o=a,s;return e[2]===t?s=e[3]:(s={getState:()=>t,setDataUI:i,setFallbackDataUI:o},e[2]=t,e[3]=s),s});function OP(){return{renderers:hM(),fallbacks:[]}}var kP=e=>{if(!e.overwrite)return e;let{overwrite:t,...n}=e;return n},AP=e=>{let t=Array.from(e).map(e=>e.getModelContext()).sort((e,t)=>(t.priority??0)-(e.priority??0)),n=hM();return t.reduce((e,t)=>{let r=t.priority??0;if(t.system&&(e.system?e.system+=`\n\n${t.system}`:e.system=t.system),t.tools)for(let[i,a]of Object.entries(t.tools)){let t=e.tools!==void 0&&Object.hasOwn(e.tools,i)?e.tools[i]:void 0;if(t&&t!==a){let o=n[i];if(o===r){if(!a.overwrite)throw Error(`You tried to define a tool with the name ${i}, but it already exists.`);e.tools[i]=kP(a);continue}let s=o>r?t:a,c=o>r?a:t;e.tools[i]=kP({...c,...s}),n[i]=Math.max(o,r);continue}e.tools||=hM(),e.tools[i]=kP(a),Object.hasOwn(n,i)||(n[i]=r)}return t.config&&(e.config={...e.config,...t.config}),t.callSettings&&(e.callSettings={...e.callSettings,...t.callSettings}),t.unstable_composerMetadata&&(e.unstable_composerMetadata={...e.unstable_composerMetadata,...t.unstable_composerMetadata}),e},{})},jP=(e,t,n)=>{let r=e=>{console.error(`[assistant-ui] ${n} listener threw an error`,e)};for(let n of e)try{let e=n(typeof t==`function`?t():t);e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`&&Promise.resolve(e).catch(r)}catch(e){r(e)}},MP=e=>e,NP=new Set([`$$typeof`,`nodeType`,`then`,`__v_raw`,`__v_isRef`,`__v_isReactive`,`__v_isReadonly`,`__v_isShallow`,`__v_skip`]),PP=(e,t)=>{if(e===Symbol.toStringTag)return t;if(typeof e!=`symbol`){if(e===`toJSON`)return()=>t;if(!NP.has(e))return!1}},FP=class{getOwnPropertyDescriptor(e,t){let n=this.get(e,t);if(n!==void 0)return{value:n,writable:!1,enumerable:!0,configurable:!0}}set(){return!1}setPrototypeOf(){return!1}defineProperty(){return!1}deleteProperty(){return!1}preventExtensions(){return!1}},IP=Symbol(`assistant-ui.store.clientId`),LP=Symbol(`assistant-ui.store.instanceTag`),RP=(e,t)=>{let n=new Proxy((()=>{}),{apply:()=>(t(),n),get:(n,r)=>r===`source`?e.source:r===`query`?e.query:r===`name`?e.name:r===IP?HP(t()):t()[r],has:(e,n)=>n===`source`||n===`query`||n===`name`||n===IP||n in t(),ownKeys:()=>Reflect.ownKeys(t()),getOwnPropertyDescriptor:(e,n)=>{if(typeof n!=`symbol`&&n in t())return{value:t()[n],writable:!1,enumerable:!0,configurable:!0}}});return n},zP=(e,t)=>{let n=()=>{throw Error(e)};return new Proxy((()=>{}),{apply:n,get:(e,r)=>{if(r===`source`||r===`query`)return null;if(r===`name`)return t;if(r===IP)return n();let i=PP(r,`AssistantClientAccessor`);return i===!1?n():i},has:(e,t)=>t===`source`||t===`query`||t===`name`,ownKeys:()=>[],getOwnPropertyDescriptor:()=>void 0})},BP=e=>e?.source!=null,VP=e=>e?.source===null,HP=e=>e[IP]??e,UP=e=>e[LP]??HP(e),WP=e=>e===`optional`||e===`subscribe`||e===`on`||e===`__proto__`||typeof e==`symbol`,GP=e=>{let t=[];for(let n in e)WP(n)||t.push(n);return t},KP=class extends FP{#e;constructor(e){super(),this.#e=e}get(e,t){let n=PP(t,`OptionalAssistantClient`);if(n!==!1)return n;if(WP(t))return;let r=this.#e[t];return BP(r)?r:void 0}ownKeys(){return GP(this.#e)}has(e,t){return!WP(t)&&t in this.#e}},qP=e=>new Proxy({},new KP(e)),JP=()=>()=>{},YP=`You are using a component or hook that requires an AuiProvider. Wrap your component in an <AuiProvider> component.`,XP=class extends FP{#e;#t;#n;#r;constructor(e,t,n){super(),this.#e=e,this.#t=t,this.#n=n}get(e,t){if(t===`subscribe`||t===`on`)return JP;if(t===`optional`)return this.#r??=qP(this.#n());let n=PP(t,this.#e);return n===!1?zP(this.#t(String(t)),String(t)):n}ownKeys(){return[`subscribe`,`on`,`optional`]}getOwnPropertyDescriptor(e,t){if(t!==`optional`)return super.getOwnPropertyDescriptor(e,t);let n=this.get(e,t);if(n!==void 0)return{value:n,writable:!1,enumerable:!1,configurable:!0}}has(e,t){return t===`subscribe`||t===`on`||t===`optional`}},ZP=((e,t)=>{let n=new Proxy({},new XP(e,t,()=>n));return n})(`DefaultAssistantClient`,()=>YP),QP=()=>new Proxy({},{get(e,t){let n=PP(t,`AssistantClient`);return n===!1?zP(`The current scope does not have a "${String(t)}" property.`,String(t)):n}}),$P=kN(ZP),eF=()=>{},tF=new WeakMap,nF=e=>tF.get(e)??eF,rF=(e,t)=>{tF.set(e,t)},iF=()=>jN($P),aF=(e,t)=>FM($P,e,t),oF=Symbol(`assistant-ui.transform-scopes`);function sF(e,t){let n=e;if(n[oF])throw Error(`transformScopes is already attached to this resource`);n[oF]=t}function cF(e){return e[oF]}var lF=e=>typeof e==`string`?{scope:e.split(`.`)[0],event:e}:{scope:e.scope,event:e.event},uF=e=>{console.error(`NotificationManager: event listener error`,e)},dF=(e,t,n)=>{try{let r=e(t,n);r!==null&&(typeof r==`object`||typeof r==`function`)&&typeof r.then==`function`&&Promise.resolve(r).catch(uF)}catch(e){uF(e)}},fF=()=>{let e=new Map,t=new Set,n=new Set;return{on(n,r){let i=r;if(n===`*`)return t.add(i),()=>t.delete(i);let a=e.get(n);return a||(a=new Set,e.set(n,a)),a.add(i),()=>{a.delete(i),a.size===0&&e.get(n)===a&&e.delete(n)}},emit(n,r,i){(e.has(n)||t.size!==0)&&queueMicrotask(()=>{let a=e.get(n);if(a)for(let e of a)dF(e,r,i);if(t.size>0){let e={event:n,payload:r};for(let n of t)dF(n,e,i)}})},subscribe(e){return n.add(e),()=>n.delete(e)},notifySubscribers(){for(let e of n)try{e()}catch(e){console.error(`NotificationManager: subscriber callback error`,e)}}}},pF=()=>pN(fF)[0],mF=Symbol(`assistant-ui.store.clientIndex`),hF=e=>e[mF],gF=kN([]),_F=()=>AN(gF),vF=(e,t)=>{let n=J(3),r=_F(),i;return n[0]!==e||n[1]!==r?(i=[...r,e],n[0]=e,n[1]=r,n[2]=i):i=n[2],FM(gF,i,t)},yF=kN(null),bF=Symbol(`aui.scope-effect-unapplied`),xF=(e,t)=>FM(yF,e,t),SF=()=>{let e=AN(yF);if(!e)throw Error(`AssistantTapContext is not available`);return e},CF=()=>SF().clientRef,wF=(e,t,n)=>{let r=J(8),{clientRef:i}=SF(),a;r[0]!==i||r[1]!==t||r[2]!==e?(a=()=>{let n=i.current;if(n===null)throw Error(`useAssistantScopeEffect ran before the client was committed. This is likely an internal bug in assistant-ui.`);let r=()=>{let t=i.current?.[e];return t!==void 0&&BP(t)?UP(t):void 0},a=bF,o,s=e=>{if(o?.(),o=void 0,a=bF,e!==void 0){let e=t();o=typeof e==`function`?e:void 0}a=e};s(r());let c=n.subscribe(()=>{let e=r();e!==a&&s(e)});return()=>{c(),o?.()}},r[0]=i,r[1]=t,r[2]=e,r[3]=a):a=r[3];let o;r[4]!==i||r[5]!==n||r[6]!==e?(o=[i,e,...n],r[4]=i,r[5]=n,r[6]=e,r[7]=o):o=r[7],X(a,o)},TF=()=>{let e=J(3),{emit:t}=SF(),n=_F(),r;return e[0]!==n||e[1]!==t?(r=(e,r)=>{t(e,r,n)},e[0]=n,e[1]=t,e[2]=r):r=e[2],vN(r)},EF=kN(void 0),DF=(e,t)=>{let n=AN(EF);return FM(EF,e??n,t)},OF=()=>{let e=J(3),[t]=pN(kF),n,r;return e[0]===t?(n=e[1],r=e[2]):(n=()=>()=>queueMicrotask(()=>t.abort()),r=[t],e[0]=t,e[1]=n,e[2]=r),xN(n,r),t.signal};function kF(){return new AbortController}var AF=Symbol(`assistant-ui.store.getValue`),jF=e=>{let t=e[AF];if(!t)throw Error(`Client scope contains a non-client resource. Ensure your Derived get() returns a client created with useClientResource(), not a plain resource.`);return t.getState?.()},MF=new Map;function NF(e){let t=MF.get(e);return t||(t=function(...t){if(!this||typeof this!=`object`)throw Error(`Method "${String(e)}" called without proper context. This may indicate the function was called incorrectly.`);let n=this[AF];if(!n)throw Error(`Method "${String(e)}" called on invalid client proxy. Ensure you are calling this method on a valid client instance.`);let r=n[e];if(!r)throw Error(`Method "${String(e)}" is not implemented.`);if(typeof r!=`function`)throw Error(`"${String(e)}" is not a function.`);return r(...t)},MF.set(e,t)),t}var PF=class extends FP{boundFns;cachedReceiver;outputRef;tagRef;index;constructor(e,t,n){super(),this.outputRef=e,this.tagRef=t,this.index=n}get(e,t,n){if(t===AF)return this.outputRef.current;if(t===mF)return this.index;if(t===LP)return this.tagRef.current;let r=PP(t,`ClientProxy`);if(r!==!1)return r;let i=this.outputRef.current[t];if(typeof i==`function`){if(n===void 0)return i;(!this.boundFns||this.cachedReceiver!==n)&&(this.boundFns=new Map,this.cachedReceiver=n);let e=this.boundFns.get(t);return e||(e=NF(t).bind(n),this.boundFns.set(t,e)),e}return i}ownKeys(){return Object.keys(this.outputRef.current)}has(e,t){return t===AF||t===mF||t===LP||t in this.outputRef.current}},FF=e=>{let t=Y(null),n=Y(null),r=hN(()=>({}),[e.hook,e.key]),i=_F().length,a=hN(()=>new Proxy({},new PF(t,n,i)),[i]),o=vF(a,function(){return bP(e)});return t.current||(t.current=o,n.current=r),X(()=>{t.current=o,n.current=r}),{methods:a,state:o.getState?.(),key:e.key}},IF=MN(FF),LF=(e,t)=>{if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0}let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&Object.is(e[n],t[n]))},RF=e=>{let t=hN(()=>({}),[]);return t.v!==void 0&&LF(t.v,e)?t.v:(t.v=e,e)},zF=e=>{let t=J(2),n=Y(void 0),r;return t[0]===e?r=t[1]:(r=t=>{let r=e(t);return n.current!==void 0&&LF(n.current,r)?n.current:(n.current=r,r)},t[0]=e,t[1]=r),r},BF=(()=>{try{return!1}catch{return!1}})(),VF=(e,t)=>{let n={...e},r=new Set,i=!0;for(;i;){i=!1;for(let e of Object.values(n)){if(r.has(e.hook))continue;r.add(e.hook);let a=cF(e.hook);if(a){a(n,t),i=!0;break}}}return n},HF=e=>e.hook===dI,UF=e=>{if(!HF(e))return{source:`root`,query:{}};let t=e.args[0];return{source:t.source,query:t.query??{}}},WF=Symbol.for(`aui.event-receiver-ref`),GF=(e,t)=>{let n=e===ZP?QP():e,r=Object.create(n);Object.assign(r,t);let i;return Object.defineProperty(r,"optional",{get:()=>i??=qP(r),enumerable:!1}),r},KF=({notifications:e,clientRef:t})=>hN(()=>({subscribe:e.subscribe,on:function(n,r){if(!this)throw Error(`const { on } = useAui() is not supported. Use aui.on() instead.`);let{scope:i,event:a}=lF(n),o=n[WF];if(i!==`*`&&!o&&VP(this[i]))throw Error(`Scope "${i}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);let s=e.on(a,(e,n)=>{if(i===`*`)return r(e);let a=((o??t).current??this)[i];if(!BP(a))return;let s=HP(a);if(s===n[hF(s)])return r(e)});if(i!==`*`){if(o){if(t.parent===ZP)return s}else if(VP(t.parent[i]))return s}let c=t.parent.on(n,r);return()=>{s(),c()}}}),[e,t]),qF=e=>{let t=J(5),n;t[0]===e?n=t[1]:(n=UF(e),t[0]=e,t[1]=n);let{source:r,query:i}=n,a=RF(i),o;return t[2]!==r||t[3]!==a?(o={source:r,query:a},t[2]=r,t[3]=a,t[4]=o):o=t[4],RF(o)},JF=(e,t)=>{let n=J(3),r;return n[0]!==t||n[1]!==e?(r=t?e:IF(e),n[0]=t,n[1]=e,n[2]=r):r=n[2],bP(r)},YF=MN((e,t)=>{let n=iF(),r=HF(t),i=JF(t,r),a=r?i:i.methods,o=qF(t),s=hN(()=>RP({name:e,...o},()=>a),[e,o,a]);return n[e]=s,s}),XF=e=>{let t=J(2),n;return t[0]===e?n=t[1]:(n=e.map(oI),t[0]=e,t[1]=n),wP(n)},ZF=(e,t)=>{let n=RF(t),r=hN(()=>({}),[]);return r.deps!==n&&(r.deps=n,r.client=e),r.client},QF=({parent:e,entries:t,clientRef:n,notifications:r})=>{let i=GF(e,KF({notifications:r,clientRef:n}));return{client:ZF(i,[e,...xF({clientRef:n,emit:r.emit},function(){return aF(i,function(){return XF(t)})})])}},$F=({parent:e,entries:t,destroySignal:n})=>{let r=Y({parent:e,current:null}).current,{value:i,effects:a}=EP(function(){let i=pF(),{client:a}=DF(n,function(){return QF({parent:e,entries:t,clientRef:r,notifications:i})});return X(()=>e.subscribe(i.notifySubscribers),[e,i]),X(()=>i.notifySubscribers()),a});return xN(()=>{r.parent=e,r.current=i},[i,e,r]),{client:i,effects:a}},eI=({parent:e,entries:t,destroySignal:n})=>{let r=Y({parent:e,current:null}).current,{value:i,effects:a}=EP(function(){let i=pF(),a=hP(function(){return DF(n,function(){return QF({parent:e,entries:t,clientRef:r,notifications:i})})}),o=yN(a.subscribe,()=>a.getValue().client,()=>a.getValue().client);return X(()=>{let t=()=>GN(()=>{r.current=a.getValue().client,i.notifySubscribers()}),n=a.subscribe(t),o=e.subscribe(t);return()=>{n(),o()}},[a,e,i]),o});return xN(()=>{r.parent=e,r.current=i},[i,e,r]),{client:i,effects:a}},tI=(e,t,n,r)=>{let{get:i}=r.args[0],a=yN(e.subscribe,()=>i(e),()=>i(e)),o=qF(r),s=hN(()=>RP({name:n,...o},()=>a),[n,o,a]);return t[n]=s,s},nI=(e,t)=>{if(BF){let[e]=pN(()=>t.map(([e])=>e).join(`,`)),n=t.find(([,e])=>!HF(e));if(n)throw Error(`Scope "${n[0]}" is a root scope but this useAui mounted derived-only; remount with a new key to change scope kinds.`);let r=t.map(([e])=>e).join(`,`);if(r!==e)throw Error(`A derived-only config mounted scopes [${e}] but now has [${r}]; remount with a new key to change the scope set.`)}let n=Y({parent:e,current:null}).current,r=GF(e,{subscribe:e.subscribe,on:function(t,r){if(!this)throw Error(`const { on } = useAui() is not supported. Use aui.on() instead.`);let{scope:i,event:a}=lF(t);if(i===`*`)return e.on(t,r);let o=t[WF];if(!o&&VP(this[i]))throw Error(`Scope "${i}" is not available. Use { scope: "*", event: "${a}" } to listen globally.`);return e.on({scope:i,event:a,[WF]:o??n},r)}}),i=ZF(r,[e,...t.map(([t,n])=>tI(e,r,t,n))]);return xN(()=>{n.parent=e,n.current=i},[i,e,n]),i},rI=(e,t)=>{let n=J(8),r;n[0]!==t||n[1]!==e?(r=Object.entries(VF(t,e)),n[0]=t,n[1]=e,n[2]=r):r=n[2];let i=r,a;n[3]===i?a=n[4]:(a=()=>i.length===0||i.some(sI),n[3]=i,n[4]=a);let[o]=pN(a),s;return n[5]!==i||n[6]!==o?(s={entries:i,rooted:o},n[5]=i,n[6]=o,n[7]=s):s=n[7],s},iI=(e,t,n,r)=>{let{entries:i,rooted:a}=rI(e,t);return a?n({parent:e,entries:i,destroySignal:r}):{client:nI(e,i)}},aI=(e,t,n)=>iI(e,t,$F,n);function Q(e){let t=iF();if(e){let{client:n,effects:r}=iI(t,e,eI,OF());return r&&rF(n,r),n}return t}function oI(e){let[t,n]=e;return NN(t,YF(t,n))}function sI(e){let[,t]=e;return!HF(t)}var cI=e=>{let t;class n extends FP{get(t,n){let r=PP(n,`OptionalAssistantState`);if(r!==!1)return r;let i=n;if(!WP(i)&&BP(e[i]))return jF(e[i]())}ownKeys(){return GP(e)}has(t,n){return!WP(n)&&n in e}}class r extends FP{get(r,i){let a=PP(i,`AssistantState`);if(a!==!1)return a;if(i===`optional`)return t??=new Proxy({},new n);let o=i;if(!WP(o))return jF(e[o]())}ownKeys(){return[...GP(e),`optional`]}has(t,n){return n===`optional`||!WP(n)&&n in e}}return new Proxy({},new r)},lI=new WeakMap,uI=e=>{let t=lI.get(e);return t||(t=cI(e),lI.set(e,t)),t},$=e=>{let t=J(6),n=Q(),r;t[0]===n?r=t[1]:(r=uI(n),t[0]=n,t[1]=r);let i=r,a,o;t[2]!==i||t[3]!==e?(a=()=>e(i),o=()=>e(i),t[2]=i,t[3]=e,t[4]=a,t[5]=o):(a=t[4],o=t[5]);let s=yN(n.subscribe,a,o);if(typeof s==`object`&&s&&(s===i||s===i.optional))throw Error(`You tried to return the entire AssistantState. This is not supported due to technical limitations.`);return bN(s),s},dI=e=>{let t=J(3),{get:n}=e,r=Q(),i;return t[0]!==r||t[1]!==n?(i=()=>n(r),t[0]=r,t[1]=n,t[2]=i):i=t[2],$(i)},fI=MN(dI),pI=e=>{if(e.key===void 0)throw Error(`useClientLookup: Element has no key`);return e.key};function mI(e){let t=J(12),n;t[0]===e?n=t[1]:(n=e.map(_I),t[0]=e,t[1]=n);let r=wP(n),i;t[2]===e?i=t[3]:(i=e.reduce(gI,Object.create(null)),t[2]=e,t[3]=i);let a=i,o;t[4]===r?o=t[5]:(o=r.map(hI),t[4]=r,t[5]=o);let s=o,c;t[6]!==a||t[7]!==r?(c=e=>{if(`index`in e){if(e.index<0||e.index>=r.length)throw Error(`useClientLookup: index ${e.index} out of bounds (length: ${r.length}) (ignore if recovered)`);return r[e.index].methods}let t=a[e.key];if(t===void 0)throw Error(`useClientLookup: key "${e.key}" not found (ignore if recovered)`);return r[t].methods},t[6]=a,t[7]=r,t[8]=c):c=t[8];let l;return t[9]!==s||t[10]!==c?(l={state:s,get:c},t[9]=s,t[10]=c,t[11]=l):l=t[11],l}function hI(e){return e.state}function gI(e,t,n){return e[pI(t)]=n,e}function _I(e){return NN(pI(e),IF(e),e.deps)}var vI=(e,t=0)=>t===0?Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight)<=1||e.scrollHeight<=e.clientHeight:e.scrollHeight-t-e.scrollTop-e.clientHeight<=1||e.scrollHeight-t<=e.clientHeight,yI=(e,t=0)=>t===0?e.scrollHeight>e.clientHeight+1:e.scrollHeight-t>e.clientHeight+1,bI=(e,t)=>e.scrollTop>t.scrollTop&&e.scrollHeight===t.scrollHeight,xI=Symbol(`skip-update`),SI=(e,...t)=>{let n=[];for(let r of e)try{r(...t)}catch(e){n.push(e)}if(n.length===1)throw n[0];if(n.length>1){for(let e of n)console.error(e);throw AggregateError(n)}},CI=e=>{SI(e)},wI=(e,t)=>e===void 0||t===void 0?e===t:LF(e,t),TI=class{_subscribers=new Set;subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{let t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){SI(this._subscribers)}},EI=class extends TI{_state;constructor(e){super(),this._state=e,this.subscribe=this.subscribe.bind(this),this.getState=this.getState.bind(this),this.getServerSnapshot=()=>e}getState(){return this._state}getServerSnapshot;setState(e){Object.is(e,this._state)||(this._state=e,this._notifySubscribers())}},DI=class{_subscriptions=new Set;_connection;get isConnected(){return!!this._connection}notifySubscribers(e,t){if(t){jP(this._subscriptions,e,t);return}SI(this._subscriptions,e)}_updateConnection(){if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else{let e=this._connection;this._connection=void 0,e?.()}}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},OI=class extends DI{get path(){return this.binding.path}binding;constructor(e){super(),this.binding=e;let t=e.getState();if(t===xI)throw Error(`Entry not available in the store`);this._previousState=t}_previousState;getState=()=>(this.isConnected||this._syncState(),this._previousState);_syncState(){let e=this.binding.getState();return e===xI||wI(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){let e=this.binding.subscribe(()=>{this._syncState()&&this.notifySubscribers()});return this._syncState(),e}},kI=class extends DI{get path(){return this.binding.path}binding;constructor(e){super(),this.binding=e}_previousStateDirty=!0;_previousState;getState=()=>{if(!this.isConnected||this._previousStateDirty){let e=this.binding.getState();e!==xI&&(this._previousState===void 0||!wI(e,this._previousState))&&(this._previousState=e),this._previousStateDirty=!1}if(this._previousState===void 0)throw Error(`Entry not available in the store`);return this._previousState};_connect(){let e=this.binding.subscribe(()=>{this._previousStateDirty=!0,this.notifySubscribers()});return this._previousStateDirty=!0,e}},AI=class extends DI{get path(){return this.binding.path}binding;constructor(e){super(),this.binding=e}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){let e=()=>{this.notifySubscribers()},t=this.binding.getState(),n=t?.subscribe(e),r=this.outerSubscribe(()=>{let r=this.binding.getState();if(r===t)return;t=r;let i=n;n=void 0;try{i?.()}finally{n=r?.subscribe(e),e()}});return()=>CI([()=>r?.(),()=>n?.()])}},jI=class extends DI{config;constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){let e=`Runtime event "${this.config.event}"`,t=t=>{this.notifySubscribers(t,e)},n=this.config.binding.getState(),r=n?.unstable_on(this.config.event,t),i=this.outerSubscribe(()=>{let e=this.config.binding.getState();if(e===n)return;n=e;let i=r;r=void 0;try{i?.()}finally{r=e?.unstable_on(this.config.event,t)}});return()=>CI([()=>i?.(),()=>r?.()])}},MI=class{_providers=new Map;_providerUnsubscribes=new Map;getModelContext(){return AP(new Set(this._providers.values()))}registerModelContextProvider(e){let t=Symbol();this._providers.set(t,e);let n;try{n=e.subscribe?.(()=>{this.notifySubscribers()})}catch(e){this._providers.delete(t);try{this.notifySubscribers()}catch(e){console.error(e)}throw e}this._providerUnsubscribes.set(t,n),this.notifySubscribers();let r=!1;return()=>{if(r)return;r=!0,this._providers.delete(t);let e=this._providerUnsubscribes.get(t);this._providerUnsubscribes.delete(t);let n=!1,i,a=e=>{try{e()}catch(e){n?console.error(e):(n=!0,i=e)}};if(e&&a(e),a(()=>this.notifySubscribers()),n)throw i}}_subscribers=new Set;notifySubscribers(){SI(this._subscribers)}subscribe(e){return this._subscribers.add(e),()=>{this._subscribers.delete(e)}}},NI=[],PI={modelName:void 0,toolNames:NI},FI=(e,t)=>e===t||LF(e,t),II=(e,t)=>{let n=e.getModelContext(),r=n.config?.modelName,i=n.tools?Object.keys(n.tools).sort():NI,a=i.length?i:NI;return r===t.modelName&&FI(a,t.toolNames)?t:{modelName:r,toolNames:a}},LI=MN(()=>{let e=J(11),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=new MI,e[0]=t):t=e[0];let n=t,r;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>II(n,PI),e[1]=r):r=e[1];let[i,a]=pN(r),o,s;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(o=()=>(a(e=>II(n,e)),n.subscribe(()=>{a(e=>II(n,e))})),s=[n],e[2]=o,e[3]=s):(o=e[2],s=e[3]),X(o,s);let c;e[4]===i?c=e[5]:(c=()=>II(n,i),e[4]=i,e[5]=c);let l,u,d;e[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=()=>n.getModelContext(),u=e=>n.subscribe(e),d=e=>n.registerModelContextProvider(e),e[6]=l,e[7]=u,e[8]=d):(l=e[6],u=e[7],d=e[8]);let f;return e[9]===c?f=e[10]:(f={getState:c,getModelContext:l,subscribe:u,register:d},e[9]=c,e[10]=f),f}),RI=(e,t)=>{if(t.status?.type!==`running`&&t.status?.type!==`requires-action`){let n=e.complete;return typeof n==`function`?n({args:t.args,result:t.result}):n??null}let n=e.running;return typeof n==`function`?n({args:t.args}):n??null},zI=e=>e.display===void 0?e.type===`human`:e.display===`standalone`,BI=e=>function(t){return RI(e,t)},VI=e=>{let t=J(16),{toolkit:n,mcpApp:r}=e,i;t[0]===r?i=t[1]:(i=r?[NN(`mcpApp`,r)]:[],t[0]=r,t[1]=i);let a=wP(i)[0],[o,s]=pN(UI),c;t[2]!==a||t[3]!==o?(c={toolUIs:o,mcpApp:a},t[2]=a,t[3]=o,t[4]=c):c=t[4];let l=c,u=CF(),d;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(d=(e,t,n)=>{let r={render:t,renderText:n?.renderText,standalone:n?.standalone??!1};return s(t=>{let n=hM(t);return n[e]=[...n[e]??[],r],n}),()=>{s(t=>{let n=t[e]?.filter(e=>e!==r)??[],i=hM(t);return n.length>0?(i[e]=n,i):(delete i[e],i)})}},t[5]=d):d=t[5];let f=d,p,m;t[6]===n?(p=t[7],m=t[8]):(p=()=>{if(!n)return;let e=[];for(let[t,r]of Object.entries(n)){let n=`render`in r?r.render:void 0,i=`renderText`in r?r.renderText:void 0,a=n??(i?BI(i):void 0);a&&e.push(f(t,a,{standalone:zI(r),renderText:i}))}return()=>{e.forEach(WI)}},m=[n,f],t[6]=n,t[7]=p,t[8]=m),X(p,m);let h;t[9]!==u||t[10]!==n?(h=()=>{if(!n)return;let e=Object.entries(n).reduce(GI,hM());return u.current.modelContext().register({getModelContext:()=>({tools:e})})},t[9]=u,t[10]=n,t[11]=h):h=t[11];let g;t[12]===n?g=t[13]:(g=[n],t[12]=n,t[13]=g),wF(`modelContext`,h,g);let _;return t[14]===l?_=t[15]:(_={getState:()=>l,setToolUI:f},t[14]=l,t[15]=_),_},HI=MN(VI);sF(VI,(e,t)=>{!e.modelContext&&t.modelContext.source===null&&(e.modelContext=LI())});function UI(){return hM()}function WI(e){return e()}function GI(e,t){let[n,r]=t;if(r.type===`mcp`)return e;let{display:i,render:a,renderText:o,...s}=r;return e[n]=s,e}var KI=e=>yN(e.subscribe,e.getState,e.getServerSnapshot),qI=Symbol.for(`assistant-ui.silent-runtime-action`),JI=e=>typeof e==`object`&&!!e&&qI in e,YI=(e,t)=>{let n=t();return n.catch(t=>{JI(t)||console.error(`[assistant-ui] ${e} failed:`,t)}),n},XI=MN(e=>{let t=J(9),{runtime:n}=e,r=KI(n),i;t[0]===r?i=t[1]:(i=()=>r,t[0]=r,t[1]=i);let a,o;t[2]===n?(a=t[3],o=t[4]):(a=()=>YI(`attachment remove`,n.remove),o=()=>n,t[2]=n,t[3]=a,t[4]=o);let s;return t[5]!==i||t[6]!==a||t[7]!==o?(s={getState:i,remove:a,__internal_getRuntime:o},t[5]=i,t[6]=a,t[7]=o,t[8]=s):s=t[8],s}),ZI=MN(e=>{let t=J(5),{runtime:n,index:r}=e,i;t[0]!==r||t[1]!==n?(i=n.getAttachmentByIndex(r),t[0]=r,t[1]=n,t[2]=i):i=t[2];let a=i,o;return t[3]===a?o=t[4]:(o=XI({runtime:a}),t[3]=a,t[4]=o),bP(o)}),QI=MN(({item:e,onMove:t,onRemove:n})=>({getState:()=>e,steer:()=>t({lane:`steer`,insertAfter:null}),move:t,remove:n})),$I=MN(e=>{let t=J(63),{threadIdRef:n,messageIdRef:r,runtime:i,isSuggestion:a}=e,o=KI(i),s=TF(),c=Y(!1),l,u;t[0]!==s||t[1]!==r||t[2]!==i||t[3]!==n?(l=()=>{let e=[],t=i.unstable_on(`send`,e=>{let t=c.current;c.current=!1,s(`composer.send`,{threadId:n.current,...r&&{messageId:r.current},chars:e.chars,attachments:e.attachments,...t?{suggestion:!0}:void 0})});e.push(t);let a=i.unstable_on(`attachmentAdd`,e=>{s(`composer.attachmentAdd`,{threadId:n.current,...r&&{messageId:r.current},...e.contentType?{contentType:e.contentType}:void 0})});return e.push(a),e.push(i.unstable_on(`attachmentAddError`,e=>{s(`composer.attachmentAddError`,{threadId:n.current,...r&&{messageId:r.current},...e.attachmentId&&{attachmentId:e.attachmentId},reason:e.reason,message:e.message,...e.contentType?{contentType:e.contentType}:void 0})})),()=>{for(let t of e)t()}},u=[i,s,n,r],t[0]=s,t[1]=r,t[2]=i,t[3]=n,t[4]=l,t[5]=u):(l=t[4],u=t[5]),X(l,u);let d;if(t[6]!==i||t[7]!==o.attachments){let e;t[9]===i?e=t[10]:(e=(e,t)=>NN(e.id,ZI({runtime:i,index:t}),[i,t]),t[9]=i,t[10]=e),d=o.attachments.map(e),t[6]=i,t[7]=o.attachments,t[8]=d}else d=t[8];let f=mI(d),p=o.queue,m;if(t[11]!==p||t[12]!==i){let e;t[14]===i?e=t[15]:(e=e=>NN(e.id,QI({item:e,onMove:t=>i.moveQueueItem(e.id,t),onRemove:()=>i.removeQueueItem(e.id)})),t[14]=i,t[15]=e),m=p.map(e),t[11]=p,t[12]=i,t[13]=m}else m=t[13];let h=mI(m),g=o.type??`thread`,_;t[16]!==f.state||t[17]!==p||t[18]!==o.attachmentAccept||t[19]!==o.canCancel||t[20]!==o.canSend||t[21]!==o.dictation||t[22]!==o.isEditing||t[23]!==o.isEmpty||t[24]!==o.quote||t[25]!==o.role||t[26]!==o.runConfig||t[27]!==o.text||t[28]!==g?(_={text:o.text,role:o.role,attachments:f.state,runConfig:o.runConfig,isEditing:o.isEditing,canCancel:o.canCancel,canSend:o.canSend,attachmentAccept:o.attachmentAccept,isEmpty:o.isEmpty,type:g,dictation:o.dictation,quote:o.quote,queue:p},t[16]=f.state,t[17]=p,t[18]=o.attachmentAccept,t[19]=o.canCancel,t[20]=o.canSend,t[21]=o.dictation,t[22]=o.isEditing,t[23]=o.isEmpty,t[24]=o.quote,t[25]=o.role,t[26]=o.runConfig,t[27]=o.text,t[28]=g,t[29]=_):_=t[29];let v=_,y;t[30]===v?y=t[31]:(y=()=>v,t[30]=v,t[31]=y);let b;t[32]!==a||t[33]!==i?(b=e=>{let t=i.getState();c.current=t.canSend&&(a?.(t.text)??!1),i.send(e)},t[32]=a,t[33]=i,t[34]=b):b=t[34];let x;t[35]!==s||t[36]!==r||t[37]!==i||t[38]!==n?(x=()=>{!r&&i.getState().canCancel&&s(`composer.cancel`,{threadId:n.current}),i.cancel()},t[35]=s,t[36]=r,t[37]=i,t[38]=n,t[39]=x):x=t[39];let S=i.beginEdit??eL,C;t[40]===f?C=t[41]:(C=e=>`id`in e?f.get({key:e.id}):f.get(e),t[40]=f,t[41]=C);let w;t[42]===h?w=t[43]:(w=e=>`id`in e?h.get({key:e.id}):h.get(e),t[42]=h,t[43]=w);let T;t[44]===i?T=t[45]:(T=()=>i,t[44]=i,t[45]=T);let E;return t[46]!==i.addAttachment||t[47]!==i.clearAttachments||t[48]!==i.reset||t[49]!==i.setQuote||t[50]!==i.setRole||t[51]!==i.setRunConfig||t[52]!==i.setText||t[53]!==i.startDictation||t[54]!==i.stopDictation||t[55]!==S||t[56]!==C||t[57]!==w||t[58]!==T||t[59]!==y||t[60]!==b||t[61]!==x?(E={getState:y,setText:i.setText,setRole:i.setRole,setRunConfig:i.setRunConfig,addAttachment:i.addAttachment,reset:i.reset,clearAttachments:i.clearAttachments,send:b,cancel:x,beginEdit:S,startDictation:i.startDictation,stopDictation:i.stopDictation,setQuote:i.setQuote,attachment:C,queueItem:w,__internal_getRuntime:T},t[46]=i.addAttachment,t[47]=i.clearAttachments,t[48]=i.reset,t[49]=i.setQuote,t[50]=i.setRole,t[51]=i.setRunConfig,t[52]=i.setText,t[53]=i.startDictation,t[54]=i.stopDictation,t[55]=S,t[56]=C,t[57]=w,t[58]=T,t[59]=y,t[60]=b,t[61]=x,t[62]=E):E=t[62],E});function eL(){throw Error(`beginEdit is not supported in this runtime`)}var tL=e=>({get current(){return e()}}),nL=MN(e=>{let t=J(13),{runtime:n}=e,r=KI(n),i;t[0]===r?i=t[1]:(i=()=>r,t[0]=r,t[1]=i);let a,o,s,c;t[2]===n?(a=t[3],o=t[4],s=t[5],c=t[6]):(a=e=>n.addToolResult(e),o=e=>n.resumeToolCall(e),s=e=>n.respondToToolApproval(e),c=()=>n,t[2]=n,t[3]=a,t[4]=o,t[5]=s,t[6]=c);let l;return t[7]!==i||t[8]!==a||t[9]!==o||t[10]!==s||t[11]!==c?(l={getState:i,addToolResult:a,resumeToolCall:o,respondToToolApproval:s,__internal_getRuntime:c},t[7]=i,t[8]=a,t[9]=o,t[10]=s,t[11]=c,t[12]=l):l=t[12],l}),rL=MN(e=>{let t=J(5),{runtime:n,index:r}=e,i;t[0]!==r||t[1]!==n?(i=n.getAttachmentByIndex(r),t[0]=r,t[1]=n,t[2]=i):i=t[2];let a=i,o;return t[3]===a?o=t[4]:(o=XI({runtime:a}),t[3]=a,t[4]=o),bP(o)}),iL=MN(e=>{let t=J(5),{runtime:n,index:r}=e,i;t[0]!==r||t[1]!==n?(i=n.getMessagePartByIndex(r),t[0]=r,t[1]=n,t[2]=i):i=t[2];let a=i,o;return t[3]===a?o=t[4]:(o=nL({runtime:a}),t[3]=a,t[4]=o),bP(o)}),aL=MN(e=>{let t=J(74),{runtime:n,threadIdRef:r,threadId:i}=e,a=KI(n),o=TF(),[s,c]=pN(!1),[l,u]=pN(!1),d;t[0]===n?d=t[1]:(d=tL(()=>n.getState().id),t[0]=n,t[1]=d);let f=d,p=Y(a.status),m;t[2]!==o||t[3]!==n||t[4]!==i?(m=e=>{o(e,{threadId:i,messageId:n.getState().id})},t[2]=o,t[3]=n,t[4]=i,t[5]=m):m=t[5];let h=m,g,_;t[6]!==o||t[7]!==a.id||t[8]!==a.status||t[9]!==i?(g=()=>{let e=a.status,t=p.current;p.current=e,e?.type===`incomplete`&&e.reason===`error`&&(t?.type!==`incomplete`||t.reason!==`error`)&&o(`message.error`,{threadId:i,messageId:a.id,reason:`error`})},_=[a.status,a.id,o,i],t[6]=o,t[7]=a.id,t[8]=a.status,t[9]=i,t[10]=g,t[11]=_):(g=t[10],_=t[11]),X(g,_);let v;t[12]!==f||t[13]!==n.composer||t[14]!==r?(v=$I({runtime:n.composer,threadIdRef:r,messageIdRef:f}),t[12]=f,t[13]=n.composer,t[14]=r,t[15]=v):v=t[15];let y=FF(v),b;if(t[16]!==n||t[17]!==a.content){let e;t[19]===n?e=t[20]:(e=(e,t)=>NN(`toolCallId`in e&&e.toolCallId!=null?`toolCallId-${e.toolCallId}`:`index-${t}`,iL({runtime:n,index:t}),[n,t]),t[19]=n,t[20]=e),b=a.content.map(e),t[16]=n,t[17]=a.content,t[18]=b}else b=t[18];let x=mI(b),S;t[21]===a.attachments?S=t[22]:(S=a.attachments??[],t[21]=a.attachments,t[22]=S);let C;if(t[23]!==n||t[24]!==S){let e;t[26]===n?e=t[27]:(e=(e,t)=>NN(e.id,rL({runtime:n,index:t}),[n,t]),t[26]=n,t[27]=e),C=S.map(e),t[23]=n,t[24]=S,t[25]=C}else C=t[25];let w=mI(C),T=a,E;t[28]!==y.state||t[29]!==s||t[30]!==l||t[31]!==x.state||t[32]!==T?(E={...T,parts:x.state,composer:y.state,isCopied:s,isHovering:l},t[28]=y.state,t[29]=s,t[30]=l,t[31]=x.state,t[32]=T,t[33]=E):E=t[33];let D=E,O;t[34]===D?O=t[35]:(O=()=>D,t[34]=D,t[35]=O);let k;t[36]===y.methods?k=t[37]:(k=()=>y.methods,t[36]=y.methods,t[37]=k);let A;t[38]===n?A=t[39]:(A=()=>n.delete(),t[38]=n,t[39]=A);let j,M;t[40]!==h||t[41]!==n?(j=e=>(h(`message.reload`),n.reload(e)),M=()=>(h(`message.speak`),n.speak()),t[40]=h,t[41]=n,t[42]=j,t[43]=M):(j=t[42],M=t[43]);let N,ee;t[44]===n?(N=t[45],ee=t[46]):(N=()=>n.stopSpeaking(),ee=e=>n.submitFeedback(e),t[44]=n,t[45]=N,t[46]=ee);let te;t[47]!==h||t[48]!==n?(te=e=>(h(`message.branchSwitched`),n.switchToBranch(e)),t[47]=h,t[48]=n,t[49]=te):te=t[49];let ne;t[50]===n?ne=t[51]:(ne=()=>n.unstable_getCopyText(),t[50]=n,t[51]=ne);let re;t[52]===x?re=t[53]:(re=e=>`index`in e?x.get({index:e.index}):x.get({key:`toolCallId-${e.toolCallId}`}),t[52]=x,t[53]=re);let ie;t[54]===w?ie=t[55]:(ie=e=>`id`in e?w.get({key:e.id}):w.get(e),t[54]=w,t[55]=ie);let ae;t[56]===h?ae=t[57]:(ae=e=>{e&&h(`message.copied`),c(e)},t[56]=h,t[57]=ae);let oe;t[58]===n?oe=t[59]:(oe=()=>n,t[58]=n,t[59]=oe);let se;return t[60]!==O||t[61]!==k||t[62]!==A||t[63]!==j||t[64]!==M||t[65]!==N||t[66]!==ee||t[67]!==te||t[68]!==ne||t[69]!==re||t[70]!==ie||t[71]!==ae||t[72]!==oe?(se={getState:O,composer:k,delete:A,reload:j,speak:M,stopSpeaking:N,submitFeedback:ee,switchToBranch:te,getCopyText:ne,part:re,attachment:ie,setIsCopied:ae,setIsHovering:u,__internal_getRuntime:oe},t[60]=O,t[61]=k,t[62]=A,t[63]=j,t[64]=M,t[65]=N,t[66]=ee,t[67]=te,t[68]=ne,t[69]=re,t[70]=ie,t[71]=ae,t[72]=oe,t[73]=se):se=t[73],se}),oL=e=>{let t=hN(()=>({}),[]),n=t.state,r=[];e.suggestions.forEach(e=>{let t=n?.suggestions[r.length];r.push(t&&LF(t,e)?t:e)});let i=n&&LF(r,n.suggestions)?n:{suggestions:r};return t.state=i,i},sL=MN(e=>({getState:()=>e})),cL=e=>{let t=J(9),n=oL(e),r;t[0]===n.suggestions?r=t[1]:(r=n.suggestions.map(uL),t[0]=n.suggestions,t[1]=r);let i=mI(r),a;t[2]===n?a=t[3]:(a=()=>n,t[2]=n,t[3]=a);let o;t[4]===i?o=t[5]:(o=e=>{let{index:t}=e;return i.get({index:t})},t[4]=i,t[5]=o);let s;return t[6]!==a||t[7]!==o?(s={getState:a,suggestion:o},t[6]=a,t[7]=o,t[8]=s):s=t[8],s},lL=MN(e=>{let t=J(4),n;t[0]===e?n=t[1]:(n=e.map(dL),t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r={suggestions:n},t[2]=n,t[3]=r),cL(r)});function uL(e,t){return NN(t,sL(e),[e])}function dL(e){return{title:e.title??e.prompt,label:e.label??``,prompt:e.prompt}}var fL=Object.freeze({type:`complete`}),pL=Object.freeze({type:`running`}),mL=Object.freeze({cancelled:Object.freeze({type:`incomplete`,reason:`cancelled`}),length:Object.freeze({type:`incomplete`,reason:`length`}),"content-filter":Object.freeze({type:`incomplete`,reason:`content-filter`}),other:Object.freeze({type:`incomplete`,reason:`other`}),error:Object.freeze({type:`incomplete`,reason:`error`})}),hL=e=>{let t=e.status;if(!t||typeof t!=`object`)return;let{type:n}=t;if(n===`running`)return pL;if(n===`complete`)return fL;if(n!==`incomplete`)return;let{reason:r}=t;return mL[r===`cancelled`||r===`length`||r===`content-filter`||r===`other`||r===`error`?r:`other`]},gL=(e,t,n)=>{if(e.role!==`assistant`)return fL;if(n.type===`tool-call`)return n.result===void 0?e.status:fL;if(e.status.type===`running`){let e=hL(n);if(e)return e}let r=t===Math.max(0,e.content.length-1);return e.status.type===`requires-action`?fL:r?e.status:fL},_L=e=>`reason`in e?e.reason:void 0,vL=e=>`error`in e?e.error:void 0,yL=32,bL=new WeakMap,xL=e=>bL.get(e)??e.id,SL=(e,t,n)=>`status`in e&&e.status?gL(e,t,n):fL,CL=()=>{let e=[],t=new Map;return n=>{let r=[],i=new Map,a=!0,o=(e,n,s,c)=>{if(!(s>yL))for(let[l,u]of e.entries())for(let[e,d]of u.content.entries()){if(d.type!==`tool-call`||d.messages===void 0)continue;let f=d.messages,p=SL(u,e,d),m=_L(p),h=vL(p),g=`${c}${l}.${e}`,_=t.get(g),v=_?.part===d&&_.statusType===p.type&&_.statusReason===m&&Object.is(_.statusError,h)&&_.messages===f&&_.task.messageId===u.id&&_.task.parentTaskId===n&&_.task.depth===s?_.task:{id:d.toolCallId,toolName:d.toolName,args:d.args,result:d.result,...d.isError===void 0?void 0:{isError:d.isError},status:p,timing:d.timing,messageId:u.id,parentTaskId:n,depth:s,messages:f};v!==_?.task&&(a=!1,bL.set(v,g)),r.push(v),i.set(g,{task:v,part:d,statusType:p.type,statusReason:m,statusError:h,messages:f}),o(f,v.id,s+1,`${g}.`)}};o(n,null,0,``);let s=a&&r.length===e.length&&r.every((t,n)=>t===e[n])?e:r;return e=s,t=i,s}},wL=MN(({task:e})=>({getState:()=>e})),TL=MN(e=>{let t=J(7),{runtime:n,id:r,threadIdRef:i,threadId:a}=e,o;t[0]!==r||t[1]!==n?(o=n.getMessageById(r),t[0]=r,t[1]=n,t[2]=o):o=t[2];let s=o,c;return t[3]!==s||t[4]!==a||t[5]!==i?(c=aL({runtime:s,threadIdRef:i,threadId:a}),t[3]=s,t[4]=a,t[5]=i,t[6]=c):c=t[6],bP(c)}),EL=MN(e=>{let t=J(93),{runtime:n}=e,r=KI(n),i=TF(),a,o;t[0]!==i||t[1]!==n?(a=()=>{let e=[];for(let t of[`runStart`,`runEnd`,`initialize`,`modelContextUpdate`]){let r=n.unstable_on(t,()=>{let e=n.getState()?.threadId||`unknown`;i(`thread.${t}`,{threadId:e})});e.push(r)}return e.push(n.unstable_on(`toolApprovalAnswered`,e=>{let t=n.getState()?.threadId||`unknown`;i(`thread.toolApprovalAnswered`,{threadId:t,...e})})),()=>{for(let t of e)t()}},o=[n,i],t[0]=i,t[1]=n,t[2]=a,t[3]=o):(a=t[2],o=t[3]),X(a,o);let s;t[4]===n?s=t[5]:(s=tL(()=>n.getState().threadId),t[4]=n,t[5]=s);let c=s,l;t[6]!==i||t[7]!==n?(l=e=>{i(e,{threadId:n.getState().threadId})},t[6]=i,t[7]=n,t[8]=l):l=t[8];let u=l,d;t[9]===n?d=t[10]:(d=e=>n.getState().suggestions.some(t=>t.prompt===e),t[9]=n,t[10]=d);let f=d,p;t[11]!==f||t[12]!==n.composer||t[13]!==c?(p=$I({runtime:n.composer,threadIdRef:c,isSuggestion:f}),t[11]=f,t[12]=n.composer,t[13]=c,t[14]=p):p=t[14];let m=FF(p),h;t[15]===r.suggestions?h=t[16]:(h=lL(r.suggestions),t[15]=r.suggestions,t[16]=h);let g=FF(h),_;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(_=CL(),t[17]=_):_=t[17];let v=_,y;t[18]===r.messages?y=t[19]:(y=v(r.messages),t[18]=r.messages,t[19]=y);let b=y,x;t[20]===b?x=t[21]:(x=b.map(DL),t[20]=b,t[21]=x);let S=mI(x),C;if(t[22]!==n||t[23]!==r.messages||t[24]!==r.threadId||t[25]!==c){let e;t[27]!==n||t[28]!==r.threadId||t[29]!==c?(e=e=>NN(e.id,TL({runtime:n,id:e.id,threadIdRef:c,threadId:r.threadId}),[n,e.id,c,r.threadId]),t[27]=n,t[28]=r.threadId,t[29]=c,t[30]=e):e=t[30],C=r.messages.map(e),t[22]=n,t[23]=r.messages,t[24]=r.threadId,t[25]=c,t[26]=C}else C=t[26];let w=mI(C),T=w.state.length===0&&!r.isLoading,E;t[31]!==m.state||t[32]!==w.state||t[33]!==r.capabilities||t[34]!==r.extras||t[35]!==r.isDisabled||t[36]!==r.isLoading||t[37]!==r.isRunning||t[38]!==r.speech||t[39]!==r.state||t[40]!==r.suggestions||t[41]!==r.voice||t[42]!==T||t[43]!==b?(E={isEmpty:T,isDisabled:r.isDisabled,isLoading:r.isLoading,isRunning:r.isRunning,capabilities:r.capabilities,state:r.state,suggestions:r.suggestions,extras:r.extras,speech:r.speech,voice:r.voice,composer:m.state,messages:w.state,tasks:b},t[31]=m.state,t[32]=w.state,t[33]=r.capabilities,t[34]=r.extras,t[35]=r.isDisabled,t[36]=r.isLoading,t[37]=r.isRunning,t[38]=r.speech,t[39]=r.state,t[40]=r.suggestions,t[41]=r.voice,t[42]=T,t[43]=b,t[44]=E):E=t[44];let D=E,O;t[45]===D?O=t[46]:(O=()=>D,t[45]=D,t[46]=O);let k;t[47]===m.methods?k=t[48]:(k=()=>m.methods,t[47]=m.methods,t[48]=k);let A;t[49]===g?A=t[50]:(A=()=>g.methods,t[49]=g,t[50]=A);let j;t[51]!==S||t[52]!==b?(j=e=>{if(`id`in e){let t=b.find(t=>t.id===e.id);return S.get({key:t?xL(t):e.id})}return S.get(e)},t[51]=S,t[52]=b,t[53]=j):j=t[53];let M;t[54]!==i||t[55]!==f||t[56]!==n?(M=e=>{let t=typeof e==`string`?{content:[{type:`text`,text:e}]}:e;if((t.role??`user`)===`user`){let e=t.content.map(OL).join(``);i(`composer.send`,{threadId:n.getState().threadId,chars:e.length,attachments:t.attachments?.length??0,...f(e)?{suggestion:!0}:void 0})}n.append(e)},t[54]=i,t[55]=f,t[56]=n,t[57]=M):M=t[57];let N;t[58]!==u||t[59]!==n||t[60]!==r.isRunning?(N=()=>{r.isRunning&&u(`thread.cancelRun`),n.cancelRun()},t[58]=u,t[59]=n,t[60]=r.isRunning,t[61]=N):N=t[61];let ee;t[62]!==u||t[63]!==n?(ee=()=>{n.connectVoice(),u(`thread.voiceStarted`)},t[62]=u,t[63]=n,t[64]=ee):ee=t[64];let te;t[65]===w?te=t[66]:(te=e=>`id`in e?w.get({key:e.id}):w.get(e),t[65]=w,t[66]=te);let ne;t[67]===n?ne=t[68]:(ne=()=>n,t[67]=n,t[68]=ne);let re;return t[69]!==n.deleteMessage||t[70]!==n.disconnectVoice||t[71]!==n.export||t[72]!==n.getModelContext||t[73]!==n.getVoiceVolume||t[74]!==n.import||t[75]!==n.importExternalState||t[76]!==n.muteVoice||t[77]!==n.reset||t[78]!==n.resumeRun||t[79]!==n.startRun||t[80]!==n.stopSpeaking||t[81]!==n.subscribeVoiceVolume||t[82]!==n.unmuteVoice||t[83]!==O||t[84]!==k||t[85]!==A||t[86]!==j||t[87]!==M||t[88]!==N||t[89]!==ee||t[90]!==te||t[91]!==ne?(re={getState:O,composer:k,suggestions:A,task:j,append:M,deleteMessage:n.deleteMessage,startRun:n.startRun,resumeRun:n.resumeRun,importExternalState:n.importExternalState,cancelRun:N,getModelContext:n.getModelContext,export:n.export,import:n.import,reset:n.reset,stopSpeaking:n.stopSpeaking,connectVoice:ee,disconnectVoice:n.disconnectVoice,getVoiceVolume:n.getVoiceVolume,subscribeVoiceVolume:n.subscribeVoiceVolume,muteVoice:n.muteVoice,unmuteVoice:n.unmuteVoice,message:te,__internal_getRuntime:ne},t[69]=n.deleteMessage,t[70]=n.disconnectVoice,t[71]=n.export,t[72]=n.getModelContext,t[73]=n.getVoiceVolume,t[74]=n.import,t[75]=n.importExternalState,t[76]=n.muteVoice,t[77]=n.reset,t[78]=n.resumeRun,t[79]=n.startRun,t[80]=n.stopSpeaking,t[81]=n.subscribeVoiceVolume,t[82]=n.unmuteVoice,t[83]=O,t[84]=k,t[85]=A,t[86]=j,t[87]=M,t[88]=N,t[89]=ee,t[90]=te,t[91]=ne,t[92]=re):re=t[92],re});function DL(e){return NN(xL(e),wL({task:e}),[e])}function OL(e){return e.type===`text`?e.text:``}var kL=(e,t)=>YI(`thread list ${e}`,t),AL=MN(e=>{let t=J(35),{runtime:n,mainThreadIsRunning:r}=e,i=r!==void 0&&r,a=KI(n),o;bb0:{let e=a.isRunning||a.isMain&&i;if(e===a.isRunning){o=a;break bb0}let n;t[0]!==e||t[1]!==a?(n={...a,isRunning:e},t[0]=e,t[1]=a,t[2]=n):n=t[2],o=n}let s=o,c=TF(),{isMain:l,id:u}=a,d;t[3]!==l||t[4]!==u?(d={isMain:l,threadId:u},t[3]=l,t[4]=u,t[5]=d):d=t[5];let f=Y(d),p,m;t[6]!==c||t[7]!==l||t[8]!==u?(p=()=>{let e=f.current;(e.isMain!==l||e.threadId!==u)&&(f.current={isMain:l,threadId:u},c(l?`threadListItem.switchedTo`:`threadListItem.switchedAway`,{threadId:u}))},m=[l,u,c],t[6]=c,t[7]=l,t[8]=u,t[9]=p,t[10]=m):(p=t[9],m=t[10]),X(p,m);let h;t[11]===s?h=t[12]:(h=()=>s,t[11]=s,t[12]=h);let g,_,v,y,b,x,S;t[13]===n?(g=t[14],_=t[15],v=t[16],y=t[17],b=t[18],x=t[19],S=t[20]):(b=e=>kL(`switch`,()=>n.switchTo(e)),x=e=>kL(`rename`,()=>n.rename(e)),S=e=>kL(`update custom metadata`,()=>n.updateCustom(e)),g=()=>kL(`archive`,()=>n.archive()),_=()=>kL(`unarchive`,()=>n.unarchive()),v=()=>kL(`delete`,()=>n.delete()),y=e=>kL(`generate title`,()=>n.generateTitle(e)),t[13]=n,t[14]=g,t[15]=_,t[16]=v,t[17]=y,t[18]=b,t[19]=x,t[20]=S);let C;t[21]===n?C=t[22]:(C=()=>n,t[21]=n,t[22]=C);let w;return t[23]!==n.detach||t[24]!==n.initialize||t[25]!==g||t[26]!==_||t[27]!==v||t[28]!==y||t[29]!==C||t[30]!==h||t[31]!==b||t[32]!==x||t[33]!==S?(w={getState:h,switchTo:b,rename:x,updateCustom:S,archive:g,unarchive:_,delete:v,generateTitle:y,initialize:n.initialize,detach:n.detach,__internal_getRuntime:C},t[23]=n.detach,t[24]=n.initialize,t[25]=g,t[26]=_,t[27]=v,t[28]=y,t[29]=C,t[30]=h,t[31]=b,t[32]=x,t[33]=S,t[34]=w):w=t[34],w}),jL=e=>{let t=J(4),n=TF(),r=Y(e),i,a;t[0]!==n||t[1]!==e?(i=()=>{let t=r.current;t!==e&&(r.current=e,n(`threads.selectionChanged`,{threadId:e,previousThreadId:t}))},a=[e,n],t[0]=n,t[1]=e,t[2]=i,t[3]=a):(i=t[2],a=t[3]),X(i,a)},ML=MN(e=>{let t=J(6),{runtime:n,id:r,mainThreadIsRunning:i}=e,a;t[0]!==r||t[1]!==n?(a=n.getItemById(r),t[0]=r,t[1]=n,t[2]=a):a=t[2];let o=a,s;return t[3]!==i||t[4]!==o?(s=AL({runtime:o,mainThreadIsRunning:i}),t[3]=i,t[4]=o,t[5]=s):s=t[5],bP(s)}),NL=MN(e=>{let t=J(48),{runtime:n,__internal_assistantRuntime:r}=e,i=KI(n);jL(i.mainThreadId);let a=TF(),o,s;t[0]!==a||t[1]!==n?(o=()=>n.unstable_subscribeThreadEvents(e=>{let{threadId:t,type:r}=e;t!==n.getState().mainThreadId&&a(`thread.${r}`,{threadId:t})}),s=[n,a],t[0]=a,t[1]=n,t[2]=o,t[3]=s):(o=t[2],s=t[3]),X(o,s);let c;t[4]===n.main?c=t[5]:(c=EL({runtime:n.main}),t[4]=n.main,t[5]=c);let l=FF(c),u;t[6]!==l.state||t[7]!==n||t[8]!==i.threadItems?(u=Object.keys(i.threadItems).map(e=>NN(e,ML({runtime:n,id:e,mainThreadIsRunning:l.state.isRunning}),[n,e,l.state.isRunning])),t[6]=l.state,t[7]=n,t[8]=i.threadItems,t[9]=u):u=t[9];let d=mI(u),f=i.newThreadId??null,p;t[10]!==l.state||t[11]!==i.archivedThreadIds||t[12]!==i.hasMore||t[13]!==i.isLoading||t[14]!==i.isLoadingMore||t[15]!==i.loadError||t[16]!==i.mainThreadId||t[17]!==i.threadIds||t[18]!==f||t[19]!==d.state?(p={mainThreadId:i.mainThreadId,newThreadId:f,isLoading:i.isLoading,loadError:i.loadError,isLoadingMore:i.isLoadingMore,hasMore:i.hasMore,threadIds:i.threadIds,archivedThreadIds:i.archivedThreadIds,threadItems:d.state,main:l.state},t[10]=l.state,t[11]=i.archivedThreadIds,t[12]=i.hasMore,t[13]=i.isLoading,t[14]=i.isLoadingMore,t[15]=i.loadError,t[16]=i.mainThreadId,t[17]=i.threadIds,t[18]=f,t[19]=d.state,t[20]=p):p=t[20];let m=p,h;t[21]===m?h=t[22]:(h=()=>m,t[21]=m,t[22]=h);let g;t[23]===l.methods?g=t[24]:(g=()=>l.methods,t[23]=l.methods,t[24]=g);let _;t[25]!==m||t[26]!==d?(_=e=>{if(e===`main`)return d.get({key:m.mainThreadId});if(`id`in e)return d.get({key:e.id});let{index:t,archived:n}=e,r=n!==void 0&&n?m.archivedThreadIds[t]:m.threadIds[t];return d.get({key:r})},t[25]=m,t[26]=d,t[27]=_):_=t[27];let v,y,b,x,S,C;t[28]===n?(v=t[29],y=t[30],b=t[31],x=t[32],S=t[33],C=t[34]):(v=(e,t)=>kL(`switch`,()=>n.switchToThread(e,t)),y=()=>kL(`create`,()=>n.switchToNewThread()),b=()=>n.getLoadThreadsPromise(),x=()=>n.reload(),S=()=>n.reloadMainThread(),C=()=>n.loadMore(),t[28]=n,t[29]=v,t[30]=y,t[31]=b,t[32]=x,t[33]=S,t[34]=C);let w;t[35]===r?w=t[36]:(w=()=>r,t[35]=r,t[36]=w);let T;return t[37]!==v||t[38]!==y||t[39]!==b||t[40]!==x||t[41]!==S||t[42]!==C||t[43]!==w||t[44]!==h||t[45]!==g||t[46]!==_?(T={getState:h,thread:g,item:_,switchToThread:v,switchToNewThread:y,getLoadThreadsPromise:b,reload:x,reloadMainThread:S,loadMore:C,__internal_getAssistantRuntime:w},t[37]=v,t[38]=y,t[39]=b,t[40]=x,t[41]=S,t[42]=C,t[43]=w,t[44]=h,t[45]=g,t[46]=_,t[47]=T):T=t[47],T}),PL=(e,t)=>{e.thread??=fI({source:`threads`,query:{type:`main`},get:e=>e.threads.thread(`main`)}),e.threadListItem??=fI({source:`threads`,query:{type:`main`},get:e=>e.threads.item(`main`)}),e.composer??=fI({source:`thread`,query:{},get:e=>e.threads.thread(`main`).composer()}),!e.modelContext&&t.modelContext.source===null&&(e.modelContext=LI()),!e.suggestions&&t.suggestions.source===null&&(e.suggestions=fI({source:`thread`,query:{},get:e=>e.thread.suggestions()}))},FL=e=>{let t=J(7),n=CF(),r;t[0]!==n||t[1]!==e?(r=()=>e.registerModelContextProvider(n.current.modelContext()),t[0]=n,t[1]=e,t[2]=r):r=t[2];let i;t[3]===e?i=t[4]:(i=[e],t[3]=e,t[4]=i),wF(`modelContext`,r,i);let a;return t[5]===e?a=t[6]:(a=NL({runtime:e.threads,__internal_assistantRuntime:e}),t[5]=e,t[6]=a),bP(a)},IL=MN(FL);sF(FL,(e,t)=>{PL(e,t),!e.tools&&t.tools.source===null&&(e.tools=HI({})),!e.dataRenderers&&t.dataRenderers.source===null&&(e.dataRenderers=DP())});var LL=e=>{let{children:t,condition:n}=e;return $(n)?t:null};LL.displayName=`AuiIf`;var RL=MP({}),zL=({effects:e})=>{"use no memo";return _N(e),null},BL=Z(function(e,t){"use no memo";let{config:n,children:r}=e,i=`extends`in e,a=`value`in e,o=iF();if(BF){if(i&&a)throw Error("AuiProvider: pass either `extends` or `value`, not both.");if(i&&e.extends===void 0)throw Error("AuiProvider: `extends` must be a client or null, not undefined.");if(i&&!n)throw Error("AuiProvider: `extends` requires a `config`.");if(a&&n)throw Error("AuiProvider: pass either `value` or `config`, not both.");if(!a&&!n)throw Error("AuiProvider: a `config` is required.");if(!i&&!a&&o!==ZP)throw Error(`A parent AuiProvider exists — pass extends={aui} to inherit it or extends={null} to isolate.`)}let s=i?e.extends??ZP:a?e.value??ZP:o,c=OF(),{client:l,effects:u}=aI(s,n??RL,c);return CN(t,()=>l,[l]),(0,b.jsx)(EF.Provider,{value:c,children:(0,b.jsxs)($P.Provider,{value:l,children:[(0,b.jsx)(zL,{effects:nF(s)}),u&&(0,b.jsx)(zL,{effects:u}),r]})})}),VL=e=>{let t=Q(),n=Y(!1),r=n.current?null:e(t);return $(()=>n.current?e(t):r),()=>(n.current=!0,e(t))},HL=Object.freeze({});function UL(e){let t=J(3),{getItemState:n,children:r}=e,i=VL(n),a;return t[0]!==r||t[1]!==i?(a=r(i),t[0]=r,t[1]=i,t[2]=a):a=t[2],WL(a)}var WL=e=>{let t=typeof e==`object`&&e&&`type`in e?e:null,n=t?.type,r=t?.key;return hN(()=>t,[n,r,typeof t?.props==`object`&&t.props!=null&&Object.entries(t.props).length===0?HL:t?.props])??e},GL=(e,t)=>{let n=J(11),r=Q(),i=vN(t),a;n[0]===e?a=n[1]:(a=lF(e),n[0]=e,n[1]=a);let{scope:o,event:s}=a,c;n[2]!==r||n[3]!==i||n[4]!==s||n[5]!==o?(c=()=>r.on({scope:o,event:s},i),n[2]=r,n[3]=i,n[4]=s,n[5]=o,n[6]=c):c=n[6];let l;n[7]!==r||n[8]!==s||n[9]!==o?(l=[r,o,s],n[7]=r,n[8]=s,n[9]=o,n[10]=l):l=n[10],X(c,l)},KL=e=>e._core?.RenderComponent,qL=({runtime:e,aui:t,config:n,children:r})=>{"use no memo";let i=KL(e),a=MP({...n,threads:IL(e)});return(0,b.jsxs)(BL,{extends:t,config:a,children:[i&&(0,b.jsx)(i,{}),r]})},JL=wN(e=>{let t=J(5),{runtime:n,aui:r,config:i,children:a}=e,o=r===void 0?null:r,s;return t[0]!==o||t[1]!==a||t[2]!==i||t[3]!==n?(s=(0,b.jsx)(qL,{runtime:n,aui:o,config:i,children:a}),t[0]=o,t[1]=a,t[2]=i,t[3]=n,t[4]=s):s=t[4],s});function YL(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function XL(e,t=0){return t>100?!1:e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(e=>XL(e,t+1)):YL(e)?Object.entries(e).every(([e,n])=>typeof e==`string`&&XL(n,t+1)):!1}var ZL=100,QL=(e,t,n)=>{if(e===t)return!0;if(n>ZL||e==null||t==null)return!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((e,r)=>QL(e,t[r],n+1));if(Array.isArray(t)||!YL(e)||!YL(t))return!1;let r=Object.keys(e),i=Object.keys(t);return r.length===i.length&&r.every(r=>Object.hasOwn(t,r)&&QL(e[r],t[r],n+1))},$L=(e,t)=>!XL(e)||!XL(t)?!1:QL(e,t,0);function eR(e){let t=Y(e);return t.current!==e&&!$L(t.current,e)&&(t.current=e),t.current}function tR(e){let t=J(2),n=Y(void 0),r;return t[0]===e?r=t[1]:(r=t=>{let r=e(t);return n.current!==void 0&&$L(n.current,r)?n.current:(n.current=r,r)},t[0]=e,t[1]=r),r}var nR=Symbol.for(`aui.tool-response`),rR=`<no result>`,iR=class e{get[nR](){return!0}artifact;result;isError;modelContent;messages;constructor(e){e.artifact!==void 0&&(this.artifact=e.artifact);let t=e.result;this.result=t===void 0?rR:t,this.isError=e.isError??!1,e.modelContent!==void 0&&(this.modelContent=e.modelContent),e.messages!==void 0&&(this.messages=e.messages)}static[Symbol.hasInstance](e){return typeof e==`object`&&!!e&&nR in e}static toResponse(t){return t instanceof e?t:new e({result:t===void 0?rR:t})}},aR=()=>{let e,t,n=new Promise((n,r)=>{e=n,t=r});if(!e||!t)throw Error(`Failed to create promise`);return{promise:n,resolve:e,reject:t}},oR=()=>{let e=[],t=!1,n=!1,r=!1,i,a,o=0,s,c,l=()=>(a=void 0,c??=Promise.all(e.splice(0).map(async e=>{try{await e.reader.cancel().catch(()=>void 0),await e.pipeTask}finally{e.reader.releaseLock()}})).then(()=>void 0),c),u=e=>{n||r||(r=!0,console.error(e),l(),i.error(e),s?.reject(e),s=void 0)},d=a=>{a.promise||=a.reader.read().then(({done:c,value:l})=>{a.promise=void 0,!(n||r)&&(c?(e.splice(e.indexOf(a),1),a.reader.releaseLock(),t&&e.length===0&&o===0&&i.close()):i.enqueue(l),s?.resolve(),s=void 0)}).catch(u)},f=new ReadableStream({start(e){i=e},pull(){return s=aR(),e.forEach(e=>{d(e)}),s.promise},async cancel(){n=!0;let e=l();s?.resolve(),s=void 0,await e}}),p=c=>{if(e.length>0&&(a=void 0),!a){let c=[];a=c,o++,Promise.resolve().then(()=>{if(o--,a===c&&(a=void 0),!(n||r)){for(let e of c)i.enqueue(e);t&&e.length===0&&o===0&&i.close(),s?.resolve(),s=void 0}}).catch(u)}a.push(c)};return{readable:f,isSealed(){return t},isCancelled(){return n},isErrored(){return r},seal(){t||n||r||(t=!0,e.length===0&&o===0&&i.close())},addStream:(i,o)=>{let s=o?.catch(()=>void 0);if(n||r){i.cancel().catch(()=>void 0);return}if(t)throw i.cancel().catch(()=>void 0),Error(`Cannot add streams after the run callback has settled.`);a=void 0;let c={reader:i.getReader(),pipeTask:s};e.push(c),d(c)},enqueue(e){if(!(n||r)){if(t)throw Error(`Cannot add streams after the run callback has settled.`);p(e)}}}},sR=e=>e instanceof TypeError,cR=(e,t,n)=>{try{e.enqueue(t)}catch(e){if(!sR(e))throw e;n?.(e)}},lR=e=>{try{e.close()}catch(e){if(!sR(e))throw e}},uR=(e,t)=>new ReadableStream({start(n){return e.start?.(t(n))},pull(n){return e.pull?.(t(n))},cancel(t){return e.cancel?.(t)}}),dR=(e,t)=>{let n;return[uR({start(e){n=e},cancel(e){return t?.(n,e)}},e),n]},fR=class{_controller;_strict;_isClosed=!1;_warnedDropped=!1;constructor(e,t={}){this._controller=e,this._strict=t.strict??!0}append(e){let t={type:`text-delta`,path:[],textDelta:e};if(this._isClosed){if(this._strict)throw TypeError(`Cannot append to a closed TextStreamController`);return cR(this._controller,t,this._warnDroppedAfterClose),this}return cR(this._controller,t),this}_warnDroppedAfterClose=e=>{this._warnedDropped||(this._warnedDropped=!0,console.error(`Dropped text delta for closed stream: ${String(e)}`))};close(){this._isClosed||(this._isClosed=!0,cR(this._controller,{type:`part-finish`,path:[]}),lR(this._controller))}},pR=(e,t={})=>uR(e,e=>new fR(e,t)),mR=(e={})=>dR(t=>new fR(t,e)),hR=class{_isClosed=!1;_mergeTask;_controller;constructor(e,t={}){this._controller=e;let n=pR({start:e=>{this._argsTextController=e}},t),r=!1;this._mergeTask=n.pipeTo(new WritableStream({write:e=>{switch(e.type){case`text-delta`:r=!0,cR(this._controller,e);break;case`part-finish`:r||cR(this._controller,{type:`text-delta`,textDelta:`{}`,path:[]}),cR(this._controller,{type:`tool-call-args-text-finish`,path:[]});break;default:throw Error(`Unexpected chunk type: ${e.type}`)}}}))}get argsText(){return this._argsTextController}_argsTextController;async setResponse(e){if(this._isClosed)return;let t=e.result;cR(this._controller,{type:`result`,path:[],...e.artifact===void 0?{}:{artifact:e.artifact},result:t===void 0?rR:t,isError:e.isError??!1,...e.modelContent===void 0?{}:{modelContent:e.modelContent},...e.messages===void 0?{}:{messages:e.messages}}),await this.close()}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,cR(this._controller,{type:`part-finish`,path:[]}),lR(this._controller))}},gR=(e={})=>dR(t=>new hR(t,e)),_R=class{value=-1;up(){return++this.value}},vR=class extends TransformStream{constructor(e){super({transform(t,n){n.enqueue({...t,path:[e,...t.path]})}})}};TransformStream;var yR=class extends TransformStream{constructor(e){let t=new _R,n=new Map;super({transform(r,i){r.type===`part-start`&&r.path.length===0&&n.set(t.up(),e.up());let[a,...o]=r.path;if(a===void 0){i.enqueue(r);return}let s=n.get(a);if(s===void 0)throw Error(`Path not found`);i.enqueue({...r,path:[s,...o]})}})}},bR=(e,t=21)=>(n=t)=>{let r=``,i=n|0;for(;i-->0;)r+=e[Math.random()*e.length|0];return r},xR=bR(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7),SR=class e{_state;_parentId;constructor(e,t={}){this._state=e||{strict:t.strict??!0,merger:oR(),contentCounter:new _R}}get __internal_isClosed(){return this._state.merger.isSealed()||this._state.merger.isCancelled()||this._state.merger.isErrored()}get __internal_isCancelled(){return this._state.merger.isCancelled()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(e){this._state.closeSubscriber=e}_addTransformedStream(e,t){if(e.locked)throw TypeError(`Cannot merge a stream that is already locked to a reader.`);let n=e.pipeTo(t.writable).catch(async e=>{throw await t.writable.abort(e).catch(()=>void 0),e});this._state.merger.addStream(t.readable,n)}_addPart(e,t){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:`part-start`,part:e,path:[]}),this._addTransformedStream(t,new vR(this._state.contentCounter.value))}merge(e){this._addTransformedStream(e,new yR(this._state.contentCounter))}appendText(e){(this._state.append?.kind!==`text`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`text`,parentId:this._parentId,controller:this.addTextPart()}),this._state.append.controller.append(e)}appendReasoning(e,t){(t!==void 0||this._state.append?.kind!==`reasoning`||this._state.append.parentId!==this._parentId)&&(this._state.append={kind:`reasoning`,parentId:this._parentId,controller:this.addReasoningPart(t)}),(t===void 0||e.length!==0)&&this._state.append.controller.append(e)}addTextPart(){let[e,t]=mR({strict:this._state.strict});return this._addPart(this._withParentIdOption({type:`text`}),e),t}addReasoningPart(e){let[t,n]=mR({strict:this._state.strict});return this._addPart(this._withParentIdOption({type:`reasoning`,...e}),t),n}addToolCallPart(e){let t=typeof e==`string`?{toolName:e}:e,n=t.toolName,r=t.toolCallId??xR(),[i,a]=gR({strict:this._state.strict});return this._addPart({type:`tool-call`,toolName:n,toolCallId:r,...this._parentId&&{parentId:this._parentId}},i),t.argsText!==void 0&&(a.argsText.append(t.argsText),a.argsText.close()),t.args!==void 0&&(a.argsText.append(JSON.stringify(t.args)),a.argsText.close()),t.response!==void 0&&a.setResponse(t.response),a}_finishedPartStream(){return new ReadableStream({start(e){e.enqueue({type:`part-finish`,path:[]}),e.close()}})}_withParentIdOption(e){return this._parentId?{...e,parentId:this._parentId}:e}appendSource(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}appendFile(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}appendData(e){this._addPart(this._withParentIdOption(e),this._finishedPartStream())}enqueue(e){this._state.merger.enqueue(e),e.type===`part-start`&&e.path.length===0&&this._state.contentCounter.up()}withParentId(t){let n=new e(this._state);return n._parentId=t,n}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}};function CR(e,t={}){let n=new SR(void 0,t);return(async()=>{try{await e(n)}catch(e){n.__internal_isClosed?n.__internal_isCancelled||console.error(e):n.enqueue({type:`error`,path:[],error:String(e)})}finally{n.__internal_isClosed||n.close()}})(),n.__internal_getReadable()}function wR(e={}){let{resolve:t,promise:n}=aR(),r;return[CR(e=>(r=e,r.__internal_subscribeToClose(t),n),e),r]}var TR=class extends TransformStream{constructor(e){super();let t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},ER=r(((e,t)=>{var n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o})),DR=class extends TransformStream{constructor(){let e=[];super({transform(t,n){if(t.type===`part-start`){if(t.path.length!==0){n.error(Error(`Nested parts are not supported`));return}e.push(t.part),n.enqueue(t);return}if(t.type===`text-delta`||t.type===`result`||t.type===`part-finish`||t.type===`tool-call-args-text-finish`){if(t.path.length!==1){n.error(Error(`${t.type} chunks must have a path of length 1`));return}let r=t.path[0];if(r<0||r>=e.length){n.error(Error(`Invalid path index: ${r}`));return}let i=e[r];n.enqueue({...t,meta:i});return}n.enqueue(t)}})}},OR=/[0-9a-fA-F]/;function kR(e){let t=[`ROOT`],n=-1,r=null,i=0,a=[],o;function s(){o!==void 0&&(a.push(JSON.parse(`"${o}"`)),o=void 0)}function c(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`),s();break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),s();break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`),s();break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`),s();break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`),s()}}function l(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop(),o=a.pop()}}function u(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),o=(Number(o)+1).toString();break;case`]`:n=r,t.pop(),o=a.pop()}}for(let s=0;s<e.length;s++){let d=e[s];switch(t[t.length-1]){case`ROOT`:c(d,s,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(d){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`),o=``;break;case`}`:n=s,t.pop(),o=a.pop()}break;case`INSIDE_OBJECT_AFTER_COMMA`:d===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_KEY`),o=``);break;case`INSIDE_OBJECT_KEY`:switch(d){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`),o+=d;break;default:o+=d}break;case`INSIDE_OBJECT_AFTER_KEY`:d===`:`&&(t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`));break;case`INSIDE_OBJECT_BEFORE_VALUE`:c(d,s,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:l(d,s);break;case`INSIDE_STRING`:switch(d){case`"`:t.pop(),n=s,o=a.pop();break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=s}break;case`INSIDE_ARRAY_START`:switch(d){case`]`:n=s,t.pop(),o=a.pop();break;default:o=`0`,c(d,s,`INSIDE_ARRAY_AFTER_VALUE`)}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(d){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`),o=(Number(o)+1).toString();break;case`]`:n=s,t.pop(),o=a.pop();break;default:n=s}break;case`INSIDE_ARRAY_AFTER_COMMA`:c(d,s,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:{t.pop();let e=t[t.length-1];d===`u`?(t.push(`INSIDE_STRING_UNICODE_ESCAPE`),i=0):e===`INSIDE_STRING`&&(n=s),e===`INSIDE_OBJECT_KEY`&&(o+=d);break}case`INSIDE_STRING_UNICODE_ESCAPE`:{let e=t[t.length-2];if(!OR.test(d)){t.pop(),s--;break}i++,i===4&&(t.pop(),e===`INSIDE_STRING`&&(n=s)),e===`INSIDE_OBJECT_KEY`&&(o+=d);break}case`INSIDE_NUMBER`:switch(d){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=s;break;case`e`:case`E`:case`-`:case`+`:case`.`:break;case`,`:t.pop(),o=a.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&u(d,s),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&l(d,s);break;case`}`:t.pop(),o=a.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&l(d,s);break;case`]`:t.pop(),o=a.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&u(d,s);break;default:t.pop(),o=a.pop()}break;case`INSIDE_LITERAL`:{let i=e.substring(r,s+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?l(d,s):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&u(d,s)):n=s;break}}}let d=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:d+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:d+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:d+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?d+=`true`.slice(t.length):`false`.startsWith(t)?d+=`false`.slice(t.length):`null`.startsWith(t)&&(d+=`null`.slice(t.length))}}return[d,a]}var AR=n(ER(),1),jR=Symbol(`aui.parse-partial-json-object.meta`),MR=e=>e?.[jR],NR=e=>{if(e.length===0)return{[jR]:{state:`partial`,partialPath:[]}};try{let t=AR.default.parse(e);if(typeof t!=`object`||!t)throw Error(`argsText is expected to be an object`);return t[jR]={state:`complete`,partialPath:[]},t}catch{try{let[t,n]=kR(e),r=AR.default.parse(t);if(typeof r!=`object`||!r)throw Error(`argsText is expected to be an object`);return r[jR]={state:`partial`,partialPath:n},r}catch{return}}},PR=(e,t,n)=>{if(typeof e!=`object`||!e)return t.state;if(t.state===`complete`)return`complete`;if(n.length===0)return t.state;let[r,...i]=n;if(!Object.hasOwn(e,r))return`partial`;let[a,...o]=t.partialPath;if(r!==a)return`complete`;let s=e[r];return PR(s,{state:`partial`,partialPath:o},i)},FR=(e,t)=>{let n=MR(e);if(!n)throw Error(`unable to determine object state`);return PR(e,n,t.map(String))},IR=new Set([`__proto__`,`constructor`,`prototype`]);function LR(e){if(IR.has(e))throw Error(`Unsafe gorp path segment: ${e}`)}var RR=class{_state;_strict;_logged=new Set;_warnedClamp=!1;constructor(e=null,t={}){this._state=e,this._strict=t.strict??!0}get state(){return this._state}logOnce(e,t){this._logged.has(e)||this._logged.size>=20||(this._logged.add(e),t())}append(e){this._state=e.reduce((e,t)=>{if(this._strict)return this.apply(e,t);try{return this.apply(e,t)}catch(n){return this.logOnce(`skip:${String(n)}`,()=>console.error(`Skipped unappliable gorp operation: ${String(n)}`,t)),e}},this._state)}apply(e,t){let n=t.type;switch(n){case`set`:return this.updatePath(e,t.path,()=>t.value);case`append-text`:return this.updatePath(e,t.path,e=>{if(typeof e!=`string`)throw Error(`Expected string at path [${t.path.join(`, `)}]`);return e+t.value});default:throw Error(`Invalid operation type: ${n}`)}}updatePath(e,t,n){if(t.length===0)return n(e);let r=[],i=e;for(let e=0;e<t.length;e++){if(i??={},typeof i!=`object`)throw Error(`Invalid path: [${t.slice(e).join(`, `)}]`);let n=t[e];if(LR(n),Array.isArray(i)){let a=Number(n);if(!Number.isInteger(a)||String(a)!==String(n))throw Error(`Expected array index at [${t.slice(e).join(`, `)}]`);if(a<0)throw Error(`Insert array index out of bounds`);if(a>i.length){if(this._strict)throw Error(`Insert array index out of bounds`);this._warnedClamp||(this._warnedClamp=!0,console.warn(`Clamped out-of-bounds gorp array index ${a} to ${i.length}`)),a=i.length}r.push({kind:`array`,state:i,key:a}),i=Object.hasOwn(i,a)?i[a]:void 0}else{let e=i;r.push({kind:`object`,state:e,key:n}),i=Object.hasOwn(e,n)?e[n]:void 0}}let a=n(i);for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.kind===`array`){let e=[...t.state];e[t.key]=a,a=e}else{let e={...t.state};e[t.key]=a,a=e}}return a}},zR=class{_streamStartTime;_firstTokenTime;_totalChunks=0;_toolCallIds=new Set;constructor(){this._streamStartTime=Date.now()}recordChunk(){this._totalChunks++}recordFirstToken(){this._firstTokenTime===void 0&&(this._firstTokenTime=Date.now())}recordToolCallStart(e){this._toolCallIds.add(e)}getTiming(e,t){let n=Date.now()-this._streamStartTime,r=e&&e>0?e:t?Math.ceil(t.length/4):void 0,i=r&&n>0?r/n*1e3:void 0;return{streamStartTime:this._streamStartTime,...this._firstTokenTime===void 0?void 0:{firstTokenTime:this._firstTokenTime-this._streamStartTime},totalStreamTime:n,...r===void 0?void 0:{tokenCount:r},...i===void 0?void 0:{tokensPerSecond:i},totalChunks:this._totalChunks,toolCallCount:this._toolCallIds.size}}},BR=(e,t)=>({...e,parts:t,get content(){return this.parts}}),VR=(e,t)=>BR(e,[...e.parts,t]),HR=({unstable_state:e=null}={})=>({role:`assistant`,status:{type:`running`},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),UR=16,WR=(e,t,n,r)=>{let i=t.path.length===1?e.parts[t.path[0]]:void 0;if(i===void 0)return n(`no-part:${t.type}`,`Dropped ${t.type} chunk: no part at path [${t.path.join(`, `)}]`),e;let a=t.path[0],o=r(i);return o===i?e:BR(e,[...e.parts.slice(0,a),o,...e.parts.slice(a+1)])},GR=(e,t,n)=>{let r=t.part;if(r.type===`text`||r.type===`reasoning`)return VR(e,{type:r.type,text:``,status:{type:`running`},...r.type===`reasoning`&&r.unstable_summary!==void 0?{unstable_summary:r.unstable_summary}:void 0,...r.parentId&&{parentId:r.parentId}});if(r.type===`tool-call`)return VR(e,{type:`tool-call`,state:`partial-call`,status:{type:`running`,isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:``,args:{},timing:{startedAt:Date.now()},...r.parentId&&{parentId:r.parentId}});if(r.type===`source`)return VR(e,{type:`source`,sourceType:r.sourceType,id:r.id,url:r.url,...r.title?{title:r.title}:void 0,...r.parentId&&{parentId:r.parentId}});if(r.type===`file`)return VR(e,{type:`file`,mimeType:r.mimeType,data:r.data,...r.parentId&&{parentId:r.parentId}});if(r.type===`data`)return VR(e,{type:`data`,name:r.name,data:r.data,...r.parentId&&{parentId:r.parentId}});{let t=String(r.type);return n(`unsupported-part-start:${t}`,`Unsupported part-start type ${t}: inserting an empty reasoning part to preserve part indices`),VR(e,{type:`reasoning`,text:``,status:{type:`running`}})}},KR=(e,t,n)=>WR(e,t,n,e=>e.type===`tool-call`?e.state===`partial-call`?{...e,state:`call`,status:e.status.type===`running`?{type:`running`,isArgsComplete:!0}:e.status}:e:(n(`wrong-part:tool-call-args-text-finish`,`Dropped tool-call-args-text-finish chunk: part is not a tool-call`),e)),qR=(e,t,n)=>WR(e,t,n,e=>({...e,status:{type:`complete`,reason:`unknown`}})),JR=(e,t,n)=>WR(e,t,n,e=>{if(e.type===`text`||e.type===`reasoning`)return{...e,text:e.text+t.textDelta};if(e.type===`tool-call`){let n=e.argsText+t.textDelta,r=NR(n)??e.args;return{...e,argsText:n,args:r}}return n(`wrong-part:text-delta`,`Dropped text-delta chunk: part is neither text nor tool-call`),e}),YR=(e,t,n)=>WR(e,t,n,e=>e.type===`tool-call`?{...e,state:`result`,...e.timing===void 0?{}:{timing:{...e.timing,completedAt:e.timing.completedAt??Date.now()}},...t.artifact===void 0?{}:{artifact:t.artifact},result:t.result,isError:t.isError??!1,...t.modelContent===void 0?{}:{modelContent:t.modelContent},...t.messages===void 0?{}:{messages:t.messages},status:{type:`complete`,reason:`stop`}}:(n(`wrong-part:result`,`Dropped result chunk: part is not a tool-call`),e)),XR=(e,t)=>{if(e.status?.type===`incomplete`&&e.status?.reason===`error`)return e;let n=ZR(t);return{...e,status:n}},ZR=e=>e.finishReason===`tool-calls`?{type:`requires-action`,reason:`tool-calls`}:e.finishReason===`stop`||e.finishReason===`unknown`?{type:`complete`,reason:e.finishReason}:{type:`incomplete`,reason:e.finishReason},QR=(e,t)=>({...e,metadata:{...e.metadata,unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]}}),$R=(e,t)=>({...e,metadata:{...e.metadata,unstable_data:[...e.metadata.unstable_data,...t.data]}}),ez=(e,t)=>({...e,metadata:{...e.metadata,steps:[...e.metadata.steps,{state:`started`,messageId:t.messageId}]}}),tz=(e,t)=>{let n=e.metadata.steps.slice(),r=n.length-1;return n.length>0&&n[r]?.state===`started`?n[r]={...n[r],state:`finished`,finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}:n.push({state:`finished`,messageId:xR(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),{...e,metadata:{...e.metadata,steps:n}}},nz=(e,t)=>{let n=t.severity===`critical`||t.severity===`warning`||t.severity===`info`?t.severity:void 0;return{...e,status:{type:`incomplete`,reason:`error`,error:{code:t.code??`unknown`,message:t.error??`unknown error`,...n!==void 0&&{severity:n}}}}},rz=(e,t,n)=>(n.append(t.operations),{...e,metadata:{...e.metadata,unstable_state:n.state}}),iz=e=>{let t=0;for(let n of e.metadata.steps)n.state===`finished`&&n.usage&&(t+=n.usage.outputTokens);return t},az=(e,t,n=0)=>{let r=n>0?n:iz(t);if(r>0)return e.getTiming(r);let i=``;for(let e of t.parts)(e.type===`text`||e.type===`reasoning`)&&(i+=e.text);return e.getTiming(void 0,i||void 0)},oz=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},sz=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:n,strict:r=!0}={}){let i=e??HR(),a,o,s=new zR,c=new Set,l=(e,t)=>{c.has(e)||c.size>=UR||(c.add(e),console.warn(t))},u,d=t?oz(()=>{u?.enqueue(i)}):()=>{u?.enqueue(i)};super({start(e){u=e},transform(e){s.recordChunk();let t=e.type;switch(t){case`part-start`:i=GR(i,e,l),e.part.type===`tool-call`&&s.recordToolCallStart(e.part.toolCallId);break;case`tool-call-args-text-finish`:i=KR(i,e,l);break;case`part-finish`:i=qR(i,e,l);break;case`text-delta`:{let t=JR(i,e,l);t!==i&&s.recordFirstToken(),i=t;break}case`result`:i=YR(i,e,l);break;case`message-finish`:o=e.usage?.outputTokens,i=XR(i,e);break;case`annotations`:i=QR(i,e);break;case`data`:i=$R(i,e);break;case`step-start`:i=ez(i,e);break;case`step-finish`:i=tz(i,e);break;case`error`:i=nz(i,e),n?.(e.error);break;case`update-state`:a??=new RR(i.metadata.unstable_state,{strict:r}),i=rz(i,e,a);break;default:throw Error(`Unsupported chunk type: ${t}`)}i.status.type!==`running`&&(i={...i,metadata:{...i.metadata,timing:az(s,i,o)}}),d()},flush(e){if(i.status?.type===`running`){let t=i.parts?.some(e=>e.type===`tool-call`&&(e.state===`call`||e.state===`partial-call`)&&e.result===void 0)??!1;i=XR(i,{type:`message-finish`,path:[],finishReason:t?`tool-calls`:`unknown`,usage:{inputTokens:0,outputTokens:0}}),i={...i,metadata:{...i.metadata,timing:az(s,i,o)}},e.enqueue(i)}}})}};async function*cz(){let e=this.getReader(),t=!0;try{for(;;){let n;try{n=await e.read()}catch(e){throw t=!1,e}if(n.done){t=!1;break}let{value:r}=n;yield r}}finally{try{t&&await e.cancel()}finally{e.releaseLock()}}}function lz(e){return e[Symbol.asyncIterator]??=cz,e}var uz=class e{readable;constructor(e){this.readable=e}static fromAssistantStream(t){return new e(t.pipeThrough(new sz))}async unstable_result(){let e;for await(let t of this)e=t;return e||{role:`assistant`,status:{type:`complete`,reason:`unknown`},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}}[Symbol.asyncIterator](){return lz(this.readable)[Symbol.asyncIterator]()}tee(){let[t,n]=this.readable.tee();return[new e(t),new e(n)]}};function dz(e,t,n){try{let r=e();if(typeof r==`object`&&r&&`then`in r)return r.then(t,n);t(r)}catch(e){n(e)}}function fz(e,t){let n=e;for(let e of t){if(n==null||!Object.hasOwn(n,e))return;n=n[e]}return n}var pz=class{resolve;reject;disposed=!1;fieldPath;get isDisposed(){return this.disposed}constructor(e,t,n){this.resolve=e,this.reject=t,this.fieldPath=n}update(e){if(!this.disposed)try{if(FR(e,this.fieldPath)===`complete`){let t=fz(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(e){this.reject(e),this.dispose()}}end(e){if(!this.disposed)try{let t=fz(e,this.fieldPath);this.resolve(t)}catch(e){this.reject(e)}finally{this.dispose()}}dispose(){this.disposed=!0}},mz=class{controller;disposed=!1;fieldPath;get isDisposed(){return this.disposed}constructor(e,t){this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{let t=fz(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),FR(e,this.fieldPath)===`complete`&&(this.controller.close(),this.dispose())}catch(e){this.controller.error(e),this.dispose()}}end(){this.disposed||(this.controller.close(),this.dispose())}dispose(){this.disposed=!0}},hz=class{controller;disposed=!1;fieldPath;lastValue=void 0;get isDisposed(){return this.disposed}constructor(e,t){this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{let t=fz(e,this.fieldPath);if(t!==void 0&&typeof t==`string`){let e=t.substring(this.lastValue?.length||0);this.lastValue=t,this.controller.enqueue(e)}FR(e,this.fieldPath)===`complete`&&(this.controller.close(),this.dispose())}catch(e){this.controller.error(e),this.dispose()}}end(){this.disposed||(this.controller.close(),this.dispose())}dispose(){this.disposed=!0}},gz=class{controller;disposed=!1;fieldPath;nextIndex=0;get isDisposed(){return this.disposed}constructor(e,t){this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{let t=fz(e,this.fieldPath);if(!Array.isArray(t))return;for(;this.nextIndex<t.length&&FR(e,[...this.fieldPath,this.nextIndex])===`complete`;this.nextIndex++)this.controller.enqueue(t[this.nextIndex]);FR(e,this.fieldPath)===`complete`&&(this.controller.close(),this.dispose())}catch(e){this.controller.error(e),this.dispose()}}end(){this.disposed||(this.controller.close(),this.dispose())}dispose(){this.disposed=!0}},_z=class{argTextDeltas;handles=new Set;accumulatedText=``;parsedTextLength=-1;args=void 0;finished=!1;constructor(e){this.argTextDeltas=e,this.processStream()}async processStream(){try{let e=this.argTextDeltas.getReader();for(;;){let{value:t,done:n}=await e.read();if(n)break;this.accumulatedText+=t,this.handles.size!==0&&this.parseCurrentArgs()&&this.updateHandles()}}catch(e){console.error(`Error processing argument stream:`,e)}finally{this.finished=!0;for(let e of this.handles)e.end(this.args);this.handles.clear()}}parseCurrentArgs(){if(this.parsedTextLength===this.accumulatedText.length)return!1;let e=NR(this.accumulatedText);return this.parsedTextLength=this.accumulatedText.length,e===void 0?(this.args??=NR(``),!1):(this.args=e,!0)}updateHandles(){for(let e of this.handles)e.update(this.args),e.isDisposed&&this.handles.delete(e)}activateHandle(e){if(this.parseCurrentArgs(),e.update(this.args),!e.isDisposed){if(this.finished){e.end(this.args);return}this.handles.add(e)}}get(...e){return new Promise((t,n)=>{let r=new pz(t,n,e);this.activateHandle(r)})}streamValues(...e){let t=e,n;return lz(new ReadableStream({start:e=>{n=new mz(e,t),this.activateHandle(n)},cancel:()=>{n&&(n.dispose(),this.handles.delete(n))}}))}streamText(...e){let t=e,n;return lz(new ReadableStream({start:e=>{n=new hz(e,t),this.activateHandle(n)},cancel:()=>{n&&(n.dispose(),this.handles.delete(n))}}))}forEach(...e){let t=e,n;return lz(new ReadableStream({start:e=>{n=new gz(e,t),this.activateHandle(n)},cancel:()=>{n&&(n.dispose(),this.handles.delete(n))}}))}},vz=class{promise;constructor(e){this.promise=e}get(){return this.promise}},yz=class{args;response;writable;resolve;argsText=``;constructor(){let e=new TransformStream;this.writable=e.writable,this.args=new _z(e.readable);let{promise:t,resolve:n}=aR();this.resolve=n,this.response=new vz(t)}async appendArgsTextDelta(e){let t=this.writable.getWriter();try{await t.write(e)}catch(e){console.warn(e)}finally{t.releaseLock()}this.argsText+=e}async finishArgsText(){let e=this.writable.getWriter();try{await e.close()}catch(e){console.warn(e)}finally{e.releaseLock()}}setResponse(e){this.resolve(e)}result={get:async()=>(await this.response.get()).result}},bz=Symbol.for(`assistant-stream.tool-execution-id`),xz=(e,t,n,r,i)=>{try{let a=t?.(n,r,i);Promise.resolve(a).catch(t=>{console.error(`[assistant-stream] ${e} callback threw an error`,t)})}catch(t){console.error(`[assistant-stream] ${e} callback threw an error`,t)}},Sz=e=>e.join(`,`),Cz=(e,t)=>{let n={...e};return Object.defineProperty(n,bz,{value:t,enumerable:!0}),n},wz=class extends TR{constructor(e){let t=e,n=new Map,r=new Map,i=new Set,a=new Map,o=0;super(e=>{let s=new TransformStream({async transform(e,s){let c=a.get(Sz(e.path));switch((e.type!==`part-finish`||e.meta.type!==`tool-call`)&&s.enqueue(c?Cz(e,c):e),e.type){case`part-start`:{let n=o;if(o+=1,e.part.type===`tool-call`){let i=new yz,o=Symbol();a.set(String(n),o),r.set(o,i),t.streamCall({reader:i,toolCallId:e.part.toolCallId,toolName:e.part.toolName,executionId:o})}break}case`text-delta`:if(e.meta.type===`tool-call`){let t=a.get(Sz(e.path)),n=t?r.get(t):void 0;if(!n)throw Error(`No controller found for tool call`);await n.appendArgsTextDelta(e.textDelta)}break;case`result`:{if(e.meta.type!==`tool-call`)break;let t=a.get(Sz(e.path)),n=t?r.get(t):void 0;if(!n)throw Error(`No controller found for tool call`);n.setResponse(new iR({result:e.result,artifact:e.artifact,isError:e.isError,modelContent:e.modelContent,messages:e.messages})),i.add(t);break}case`tool-call-args-text-finish`:{if(e.meta.type!==`tool-call`)break;let{toolCallId:o,toolName:c}=e.meta,l=a.get(Sz(e.path)),u=l?r.get(l):void 0;if(!u)throw Error(`No controller found for tool call`);if(await u.finishArgsText(),i.has(l))break;let d=!1,f=dz(()=>{let e;try{e=AR.default.parse(u.argsText)}catch(e){throw Error(`Function parameter parsing failed. ${JSON.stringify(e.message)}`)}let n=t.execute({toolCallId:o,toolName:c,args:e,executionId:l});return n!==void 0&&(d=!0,xz(`onExecutionStart`,t.onExecutionStart,o,c,l)),n},n=>{if(d&&xz(`onExecutionEnd`,t.onExecutionEnd,o,c,l),n===void 0)return;let r=new iR({artifact:n.artifact,result:n.result,isError:n.isError,messages:n.messages,modelContent:n.modelContent});u.setResponse(r),cR(s,Cz({type:`result`,path:e.path,...r},l))},n=>{d&&xz(`onExecutionEnd`,t.onExecutionEnd,o,c,l);let r=new iR({result:String(n),isError:!0});u.setResponse(r),cR(s,Cz({type:`result`,path:e.path,...r},l))});f&&n.set(l,f);break}case`part-finish`:{if(e.meta.type!==`tool-call`)break;let t=a.get(Sz(e.path)),o=t?n.get(t):void 0,c=()=>{t&&(n.delete(t),r.delete(t),i.delete(t),a.delete(Sz(e.path)))};o?o.then(()=>{c(),cR(s,e)}):(c(),s.enqueue(e))}}},async flush(){await Promise.all(n.values())}});return e.pipeThrough(new DR).pipeThrough(s)})}},Tz=Symbol.for(`assistant-stream.tool-execution-id`),Ez=Symbol(`assistant-stream.tool-aborted`),Dz=e=>typeof e==`object`&&!!e&&`~standard`in e&&e[`~standard`].version===1,Oz=e=>typeof e?.then==`function`,kz=async(e,t,n=!1)=>{let r,i=new Promise(e=>{r=()=>{n?queueMicrotask(()=>queueMicrotask(()=>e(Ez))):e(Ez)},t.aborted?r():t.addEventListener(`abort`,r,{once:!0})});try{return await Promise.race([e,i])}finally{t.removeEventListener(`abort`,r)}},Az=()=>new iR({result:`Tool execution was cancelled.`,isError:!0});function jz(e,t,n,r){let i=e?.[n.toolName];return i?.execute?(async e=>{if(t.aborted)return Az();let a=e;if(Dz(i.parameters)){let e=i.parameters[`~standard`].validate(n.args),r=Oz(e)?await kz(e,t):e;if(r===Ez)return Az();r.issues&&(a=i.experimental_onSchemaValidationError??(()=>{throw Error(`Function parameter validation failed. ${JSON.stringify(r.issues)}`)}))}if(t.aborted)return Az();let o=await kz((async()=>{let e={toolCallId:n.toolCallId,abortSignal:t,human:e=>r(n.toolCallId,e,n.executionId),[Tz]:n.executionId},o=await a(n.args,e),s=iR.toResponse(o);if(i.toModelOutput&&!s.isError&&s.modelContent===void 0)try{let e=await i.toModelOutput({toolCallId:n.toolCallId,input:n.args,output:s.result});return new iR({result:s.result,artifact:s.artifact,isError:s.isError,messages:s.messages,modelContent:e})}catch(e){console.warn(`[assistant-stream] tool "${n.toolName}" toModelOutput threw; falling back to default projection.`,e)}return s})(),t,!0);return o===Ez?Az():o})(i.execute):void 0}function Mz(e,t,n,r,i){let a={toolCallId:r.toolCallId,abortSignal:t,human:e=>i(r.toolCallId,e,r.executionId),[Tz]:r.executionId};e?.[r.toolName]?.streamCall?.(n,a)}function Nz(e,t,n,r){let i=typeof e==`function`?e:()=>e,a=typeof t==`function`?t:()=>t,o=r,s=n;return new wz({execute:e=>jz(i(),a(),e,s),streamCall:({reader:e,...t})=>Mz(i(),a(),e,t,s),onExecutionStart:o?.onExecutionStart,onExecutionEnd:o?.onExecutionEnd})}var Pz=new Set([`http://json-schema.org/draft-07/schema`,`https://json-schema.org/draft-07/schema`]);function Fz(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}function Iz(e){return typeof e==`object`&&!!e&&`toJSONSchema`in e&&typeof e.toJSONSchema==`function`}function Lz(e){return typeof e==`object`&&!!e&&`toJSON`in e&&typeof e.toJSON==`function`}function Rz(e){if(typeof e==`object`&&e){let t=e.$schema;if(typeof t==`string`&&!Pz.has(t.replace(/#$/,``)))throw Error(`The schema library was asked for a draft-07 JSON Schema and returned "${t}". Upgrade the library, or pass a plain JSON Schema object instead.`)}return e}function zz(e){if(Fz(e)){let t=e[`~standard`].jsonSchema;if(typeof t==`object`&&t&&typeof t.input==`function`)return Rz(t.input({target:`draft-07`}))}if(Iz(e))return e.toJSONSchema({target:`draft-07`});if(Lz(e))return e.toJSON();if(Fz(e)){let{vendor:t}=e[`~standard`],n=t===`zod`?`convert it with z.toJSONSchema(schema)`:`wrap the schema with ${t}'s Standard JSON Schema helper`;throw Error(`Could not convert the "${t}" schema to JSON Schema: it has no "~standard.jsonSchema" converter. Upgrade ${t} to a release that implements Standard JSON Schema, ${n}, or pass a plain JSON Schema object instead.`)}return e}function Bz(e){let{required:t,...n}=e;return n.properties&&=Object.fromEntries(Object.entries(n.properties).map(([e,t])=>typeof t==`object`&&t&&!Array.isArray(t)?[e,Bz(t)]:[e,t])),n}function Vz(e){return eR(hN(()=>{try{let t=zz(e);return XL(t)?t:null}catch{return null}},[e]))}var Hz=e=>{let t=J(17),n=Q(),r;t[0]===e?r=t[1]:(r=t=>t.unstable_interactables.definitions[e]?.state,t[0]=e,t[1]=r);let i=$(r),a;t[2]===e?a=t[3]:(a=t=>t.unstable_interactables.persistence[e],t[2]=e,t[3]=a);let o=$(a),s;t[4]!==n||t[5]!==e?(s=t=>{n.unstable_interactables.setState(e,e=>typeof t==`function`?t(e):t)},t[4]=n,t[5]=e,t[6]=s):s=t[6];let c=s,l;t[7]===n?l=t[8]:(l=()=>n.unstable_interactables.flush(),t[7]=n,t[8]=l);let u=l,d=o?.isPending??!1,f=o?.error,p;t[9]!==u||t[10]!==c||t[11]!==d||t[12]!==f?(p={setState:c,isPending:d,error:f,flush:u},t[9]=u,t[10]=c,t[11]=d,t[12]=f,t[13]=p):p=t[13];let m;return t[14]!==i||t[15]!==p?(m=[i,p],t[14]=i,t[15]=p,t[16]=m):m=t[16],m};function Uz(e){let t=e.metadata;if(!t||typeof t!=`object`)return;let n=t.custom;if(!n||typeof n!=`object`)return;let r=n.interactables;return Array.isArray(r)?r:void 0}function Wz(e){return`update_${e.replace(/[^a-zA-Z0-9_-]/g,`_`)}`}var Gz=e=>{if(!YL(e))return;let t=e.id;return typeof t==`string`||typeof t==`number`?t:void 0};function Kz(e,t,n){let r=Array.isArray(t.set)?[...t.set]:[...e];if(t.clear===!0&&(r=[]),Array.isArray(t.remove)&&t.remove.length>0){let e=new Set(t.remove);r=r.filter(t=>{let n=Gz(t);return n===void 0?!e.has(t):!e.has(n)})}let i=t.update;if(Array.isArray(i)&&i.length>0){let e=new Map;for(let t of i){let n=Gz(t);n!==void 0&&!Number.isNaN(n)&&!e.has(n)&&e.set(n,t)}r=r.map(t=>{let n=Gz(t);if(n===void 0||!YL(t))return t;let r=e.get(n);return r?{...t,...r}:t})}if(Array.isArray(t.add)&&t.add.length>0){let e=n?t.add.map(e=>{if(!YL(e)||e.id!==void 0)return e;let t=n();return t===void 0?e:{...e,id:t}}):t.add;r=[...r,...e]}return r}function qz(e,t,n){if(!YL(e)||!YL(t))return t;let r=YL(n?.arrayBaseline)?n.arrayBaseline:e,i=Object.entries(e);for(let[e,a]of Object.entries(t)){let t=r[e];if(Array.isArray(t)&&YL(a)){let r=n?.idFactory&&(n.idKeyedFields===void 0||n.idKeyedFields.has(e))?()=>n.idFactory?.(e):void 0;i.push([e,Kz(t,a,r)])}else i.push([e,a])}return Object.fromEntries(i)}function Jz(e,t){if(!YL(e)||!YL(t))return;for(let n of Object.keys(e))if(!Object.hasOwn(t,n))return;let n=[];for(let[r,i]of Object.entries(t))(!Object.hasOwn(e,r)||!$L(e[r],i))&&n.push([r,i]);let r=n.length;if(r!==0&&r!==Object.keys(t).length)return Object.fromEntries(n)}var Yz=e=>{if(!e||typeof e!=`object`)return;let t=e;return t.type===`tool-call`?t:void 0},Xz=(e,t)=>{if(!e.args||typeof e.args!=`object`)return!1;let n=YL(e.result)?e.result:void 0;if(n?.success===!1)return!1;if(typeof n?.id==`string`)return n.id===t;let r=e.args.id;return r===t||r===void 0},Zz=e=>{let t=YL(e)?e.addedItemIds:void 0;if(!YL(t))return;let n=new Map;for(let[e,r]of Object.entries(t)){if(!Array.isArray(r))continue;let t=r.filter(e=>typeof e==`string`);t.length>0&&n.set(e,t)}if(n.size!==0)return e=>n.get(e)?.shift()},Qz=new WeakMap;function $z(e,t,n){let r=Qz.get(e);r||(r=new Map,Qz.set(e,r));let i=r.get(n);i||(i=new Map,r.set(n,i));let a=i.get(t);if(a)return a;let o=Wz(n),s=[],c=()=>s[s.length-1];for(let r of e){if(r.role===`user`){let e=Uz(r)?.find(e=>e.id===t);if(!e)continue;if(e.partial){let t=c();t&&s.push({state:qz(t.state,e.state),origin:`user-edit`})}else s.push({state:e.state,origin:`user-edit`});continue}if(r.role===`assistant`)for(let e of r.content??[]){let r=Yz(e);if(r){if(r.toolCallId===t&&r.toolName===n)r.args&&typeof r.args==`object`&&s.push({state:r.args,origin:`create`,toolCallId:t});else if(r.toolName===o&&Xz(r,t)){let e=c();if(e){let{id:t,...n}=r.args,i=Zz(r.result);s.push({state:i?qz(e.state,n,{idFactory:i}):qz(e.state,n),origin:`update`,toolCallId:r.toolCallId})}}}}}return i.set(t,s),s}function eB(e,t,n){let r=$z(e,t,n),i=r[r.length-1];return i?{state:i.state}:void 0}function tB(e,t){if(!e)return;let{interactables:n,...r}=e,i={...r};if(Array.isArray(n)){let e=[];for(let r of n){let n=eB(t,r.id,r.name);if(!n){e.push({id:r.id,name:r.name,state:r.state});continue}if($L(r.state,n.state))continue;let i=Jz(n.state,r.state);e.push(i?{id:r.id,name:r.name,state:i,partial:!0}:{id:r.id,name:r.name,state:r.state})}e.length&&(i.interactables=e)}return Object.keys(i).length?i:void 0}var nB=(e,t)=>{let n=Q(),r=SN().replace(/[^a-zA-Z0-9]/g,``),i=Wz(e),a=$(e=>{let t=e.optional.part;return t?.type===`tool-call`?t:void 0}),o;if(a?.toolName===i){let e=a.result,t=a.args;e?.success!==!1&&(typeof e?.id==`string`?o=e.id:typeof t?.id==`string`&&(o=t.id))}let s=t.id??o??r,c=a?.toolName===e||a?.toolName===i?`thread`:void 0,l=Y(t.stateSchema);l.current=t.stateSchema;let u=Vz(t.stateSchema),d=Y(t.initialState);d.current=t.initialState;let f=$(()=>n.unstable_interactables);X(()=>f.register({id:s,name:e,description:t.description,stateSchema:l.current,initialState:d.current,updateRender:t.updateRender,...c?{scope:c}:{}}),[f,s,e,t.description,u,c,t.updateRender]);let p=a?.toolCallId,[m,h]=Hz(s),{setState:g}=h,_=$(tR(t=>{if(!c||!p)return;let n=$z(t.thread.messages,s,e);if(!n.some(e=>e.origin===`create`&&e.toolCallId===s))return;let r=n.find(e=>e.toolCallId===p);if(!r)return;let i=n.findLast(e=>e.toolCallId!==void 0)?.toolCallId;return{state:r.state,isLatest:i===p}})),v=hN(()=>_&&{state:_.state,isLatest:_.isLatest,restore:()=>g(_.state)},[_,g]);return[m===void 0?t.initialState:m,{id:s,version:v,...h}]},rB=kN(null),iB=(e,t)=>FM(rB,e,t),aB=()=>jN(rB),oB={},sB=e=>{let t=RF(e??oB);return e==null?null:t},cB=Symbol(`innerMessage`),lB=Symbol(`innerMessages`),uB=[],dB=(e,t)=>{cB in e||(e[cB]=t)},fB=e=>{let t=`messages`in e?e.messages:e,n=t[lB]||t[cB];return n?Array.isArray(n)?n:(t[lB]=[n],t[lB]):uB},pB=`__external_store_fallback_`,mB=bR(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,7);function hB(e){let t=e.match(/^data:([^;,]+)(?:;[^;,]+)*;base64,(.*)$/i);return t?{mimeType:t[1].toLowerCase(),data:t[2]}:null}var gB=(e,t)=>{if(e.startsWith(`data-`))return{type:`data`,name:e.substring(5),data:t}},_B=(e,t,n)=>{let{role:r,id:i,createdAt:a,attachments:o,status:s,metadata:c}=e,l={id:i??t,createdAt:a??new Date},u=typeof e.content==`string`?[{type:`text`,text:e.content}]:e.content,d=({image:e,...t})=>typeof e==`string`?hB(e)?.mimeType.startsWith(`image/`)||/^(https:\/\/|blob:)/i.test(e)?{...t,image:e}:(console.warn(`Invalid image data format detected`),null):null;if(r!==`user`&&o?.length)throw Error(`attachments are only supported for user messages`);if(r!==`assistant`&&s)throw Error(`status is only supported for assistant messages`);if(r!==`assistant`&&c?.steps)throw Error(`metadata.steps is only supported for assistant messages`);switch(r){case`assistant`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:return e.text?.trim()?e:null;case`reasoning`:return!e.text?.trim()&&!e.unstable_summary?.trim()?null:e;case`file`:case`source`:return e;case`image`:return d(e);case`data`:return e;case`generative-ui`:return e;case`tool-call`:{let{parentId:t,messages:n,...r}=e,i={...r,toolCallId:e.toolCallId||`tool-${mB()}`,...t!==void 0&&{parentId:t},...n!==void 0&&{messages:n}};return e.args?{...i,args:e.args,argsText:e.argsText??JSON.stringify(e.args)}:{...i,args:NR(e.argsText??``)??{},argsText:e.argsText??``}}default:{let n=gB(t,e.data);if(n)return n;throw Error(`Unsupported assistant message part type: ${t}`)}}}).filter(e=>!!e),status:s??n,metadata:{unstable_state:c?.unstable_state??null,unstable_annotations:c?.unstable_annotations??[],unstable_data:c?.unstable_data??[],custom:c?.custom??{},steps:c?.steps??[],...c?.timing&&{timing:c.timing},...c?.submittedFeedback&&{submittedFeedback:c.submittedFeedback},...c?.isOptimistic&&{isOptimistic:!0},...c?.modality&&{modality:c.modality}}};case`user`:return{...l,role:r,content:u.map(e=>{let t=e.type;switch(t){case`text`:case`image`:case`audio`:case`file`:case`data`:return e;default:{let n=gB(t,e.data);if(n)return n;throw Error(`Unsupported user message part type: ${t}`)}}}),attachments:(o??[]).map(e=>({...e,content:e.content.map(e=>gB(e.type,e.data)??e)})),metadata:{custom:c?.custom??{},...c?.isOptimistic&&{isOptimistic:!0},...c?.modality&&{modality:c.modality}}};case`system`:if(u.length!==1||u[0].type!==`text`)throw Error(`System messages must have exactly one text message part.`);return{...l,role:r,content:u,metadata:{custom:c?.custom??{}}};default:throw Error(`Unknown message role: ${r}`)}},vB=e=>e.type===`tool-call`&&e.result===void 0,yB=e=>{if(e.type!==`tool-call`||e.result!==void 0)return!1;let t=e.messages?.at(-1);return t?.role===`assistant`&&t.status.type===`running`},bB=e=>e.type!==`tool-call`||e.result!==void 0?!1:e.interrupt!=null||e.approval!=null&&e.approval.approved===void 0&&e.approval.resolution===void 0,xB=Symbol(`autoStatus`),SB=Object.freeze(Object.assign({type:`running`},{[xB]:!0})),CB=Object.freeze(Object.assign({type:`complete`,reason:`unknown`},{[xB]:!0})),wB=Object.freeze(Object.assign({type:`incomplete`,reason:`cancelled`},{[xB]:!0})),TB=Object.freeze(Object.assign({type:`requires-action`,reason:`tool-calls`},{[xB]:!0})),EB=Object.freeze(Object.assign({type:`requires-action`,reason:`interrupt`},{[xB]:!0})),DB=e=>e[xB]===!0,OB=(e,t,n,r,i,a,o)=>e&&i?Object.assign({type:`incomplete`,reason:`error`,error:i},{[xB]:!0}):e&&t?SB:n?EB:o&&!a?SB:r?TB:a?wB:CB,kB=e=>OB(!1,!1,typeof e!=`string`&&e.some(bB),typeof e!=`string`&&e.some(vB)),AB=(e,t,n)=>OB(t,n,typeof e!=`string`&&e.some(bB),typeof e!=`string`&&e.some(vB),void 0,void 0,typeof e!=`string`&&e.some(yB)),jB=class{cache=new WeakMap;convertMessages(e,t){return e.map((e,n)=>{let r=t(this.cache.get(e),e,n);return this.cache.set(e,r),r})}},MB=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},NB=500,PB=({adapterRef:e,snapshot:t,updatePersistenceStatus:n})=>{let r=Y(void 0),i=Y(0),a=Y(new Map),o=Y(0),s=Y([]),c=Y(new Set),l=Y([]),u=Y(()=>{}),d=gN(e=>{if(c.current.size===0)return;let n=new Set(c.current);c.current.clear();let r=++i.current;for(let e of n)a.current.set(e,r);return{adapter:e,payload:t(),dirtyIds:n,seq:r}},[t]),f=gN(e=>{let t=d(e);t&&(o.current===0?u.current(t):l.current.push(t))},[d]),p=gN(async t=>{let i=t??(e.current?d(e.current):void 0);if(!i){if(o.current===0){for(let e of s.current)e();s.current=[]}return}let{adapter:f,payload:p,dirtyIds:m,seq:h}=i;o.current+=1,n(e=>{let t=hM(e);for(let e of m)t[e]={isPending:!0,error:void 0};return t});let g=e=>{let t=[];for(let e of m)a.current.get(e)!==h||c.current.has(e)||(a.current.delete(e),t.push(e));t.length!==0&&n(n=>{let r=!1,i=hM(n);for(let a of t)n[a]!==void 0&&(e===void 0?delete i[a]:i[a]=e,r=!0);return r?i:n})};try{await f.save(p),g(void 0)}catch(e){g({isPending:!1,error:e})}finally{--o.current;let t=l.current.shift()??(e.current&&c.current.size>0?d(e.current):void 0);if(t)r.current!==void 0&&(clearTimeout(r.current),r.current=void 0),u.current(t);else if(o.current===0){for(let e of s.current)e();s.current=[]}}},[e,d,n]);return u.current=e=>{p(e)},{flushIfPending:gN(()=>{r.current!==void 0&&(clearTimeout(r.current),r.current=void 0),e.current&&f(e.current)},[e,f]),schedulePersistence:gN(t=>{e.current&&(c.current.add(t),r.current!==void 0&&clearTimeout(r.current),r.current=setTimeout(()=>{r.current=void 0,o.current===0&&e.current?f(e.current):r.current=setTimeout(()=>{r.current=void 0,e.current&&f(e.current)},NB)},NB))},[e,f]),flush:gN(async()=>{if(r.current!==void 0&&(clearTimeout(r.current),r.current=void 0),!(o.current>0||c.current.size>0||l.current.length>0))return;let t=new Promise(e=>{s.current.push(e)});return e.current&&f(e.current),t},[e,f])}},FB={type:`string`,description:`The id of the instance to update, as shown in its state snapshot in the conversation.`},IB={type:`string`,description:`The id of an item currently in this list.`},LB=e=>{let t=e.properties;return YL(t)&&t.id!==void 0},RB=e=>({...e,required:[`id`]}),zB=e=>{let{id:t,...n}=YL(e.properties)?e.properties:{},r=Array.isArray(e.required)?e.required.filter(e=>e!==`id`):e.required;return{...e,properties:n,required:r}},BB=(e,t)=>{if(!YL(e)||e.type!==`array`)return e;let n=e.items;if(Array.isArray(n)||!YL(n))return e;let r=LB(n),i={add:{type:`array`,items:r?zB(n):n},remove:{type:`array`,items:r?IB:n},clear:{type:`boolean`}};return r&&(i.update={type:`array`,items:RB(n)}),{type:`object`,description:`Operations for array field "${t}". To change one item use update with its id; add new items (their ids are assigned for you), remove items by id, or clear to empty. Change only the items you mean to — never resend the whole array to edit one item.`,properties:i,additionalProperties:!1}},VB=e=>{let t=new Set;for(let[n,r]of Object.entries(e))YL(r)&&r.type===`array`&&YL(r.items)&&LB(r.items)&&t.add(n);return t},HB=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,BB(t,e)]));function UB(e){if(!e||typeof e!=`object`||e.type!==`object`)return{type:`object`,properties:{id:FB},required:[`id`],additionalProperties:!0};let{id:t,...n}=e.properties??{};return{...e,properties:{id:FB,...HB(n)},required:[`id`]}}function WB(e,t,n,r=new Map){let i=Object.values(e);if(i.length===0)return;let a=new Map;for(let e of i){let t=a.get(e.name)??[];t.push(e),a.set(e.name,t)}let o={};for(let[i,s]of a){let a=Wz(i);if(o[a])continue;let c=s[0],l=t.get(c.id),u=l&&YL(l.properties)?VB(l.properties):new Set,d=t=>{if(typeof t==`string`){let n=e[t];return n?.name===i?n:void 0}return s.length===1?c:void 0};o[a]={type:`frontend`,description:`Update the state of interactable component "${i}". ${c.description} Pass the id of the instance to update — instance ids and current state appear in the conversation as state snapshots. Only include the fields you want to change; omitted fields keep their current values.`,parameters:UB(l),streamCall:async(e,{toolCallId:t})=>{try{for await(let i of e.args.streamValues()){if(!i||typeof i!=`object`)continue;let e=i,a=Object.keys(e);if(a.indexOf(`id`)===a.length-1)continue;let{id:o,...s}=e;if(Object.keys(s).length===0)continue;let c=d(o);if(!c)continue;let l=r.get(t),u=l?.targetId===c.id?l.state:c.state;(!l||l.targetId!==c.id)&&r.set(t,{targetId:c.id,state:c.state}),n(c.id,e=>qz(e,s,{arrayBaseline:u}))}}catch{}},execute:async(e,{toolCallId:t})=>{let{id:a,...o}=e??{},c=d(a);if(!c){let e=s.map(e=>e.id);return{success:!1,error:`Unknown id ${JSON.stringify(a)} for interactable "${i}". Valid ids: ${e.join(`, `)}`}}let l=r.get(t);r.delete(t);let f=hM();n(c.id,e=>qz(e,o,{arrayBaseline:l?.targetId===c.id?l.state:void 0,idFactory:e=>{let t=mB();return(f[e]??=[]).push(t),t},idKeyedFields:u}));let p={success:!0,id:c.id};return Object.keys(f).length>0&&(p.addedItemIds={...f}),p}}}return{tools:o,unstable_composerMetadata:{interactables:i.map(e=>({id:e.id,name:e.name,state:e.state}))}}}var GB=(e,t,n)=>e.some(e=>e.role===`assistant`&&e.content?.some(e=>{if(!e||typeof e!=`object`)return!1;let r=e;return r.type===`tool-call`&&r.toolCallId===t&&r.toolName===n})),KB=({persistence:e}={})=>{let[t,n]=pN(()=>({definitions:hM(),persistence:hM()})),r=CF(),i=Y(t),a=Y(new Set),o=Y(new Map),s=Y(new Map),c=Y(new Map),l=Y(new Map),u=Y(new Map),d=Y(new Map),f=Y(new Map),p=Y(new Map),m=Y(new Set),h=Y(void 0),g=gN(e=>{let t=e(i.current);i.current=t,n(t)},[]),_=gN(()=>{let e=hM();for(let[t,n]of Object.entries(i.current.definitions))n.scope!==`thread`&&(e[t]={name:n.name,state:n.state});return e},[]),{flushIfPending:v,schedulePersistence:y,flush:b}=PB({adapterRef:h,snapshot:_,updatePersistenceStatus:gN(e=>{g(t=>{let n=e(t.persistence);return n===t.persistence?t:{...t,persistence:n}})},[g])}),x=gN((e,t)=>{let n=t.shouldStash??(()=>!0),r=t.shouldApply??(()=>!0);for(let[r,i]of Object.entries(e))n(r)&&t.stash.set(r,i.state);g(t=>{let n=!1,i=hM(t.definitions);for(let[t,a]of Object.entries(e)){let e=i[t];e&&r(t,e)&&(i[t]={...e,state:a.state},n=!0)}return n?{...t,definitions:i}:t})},[g]),S=gN(e=>{x(e,{stash:l.current})},[x]),C=gN(e=>{x(e,{stash:p.current,shouldStash:e=>!m.current.has(e),shouldApply:(e,t)=>!m.current.has(e)&&t.scope!==`thread`})},[x]),w=gN(async e=>{if(e.load)try{let t=await e.load();if(!t||h.current!==e)return;C(t)}catch(e){console.warn(`[Interactables] Persistence load failed.`,e)}},[C]),T=gN(e=>{h.current!==e&&v(),h.current=e,e&&w(e)},[v,w]),E=gN(()=>{let e=r.current;if(!e)return;let t=e.threadListItem;if(t.source!=null)return t().getState().id;let n=e.threads;if(n.source!=null)return n().getState().mainThreadId},[r]);X(()=>{if(e)return T(e),()=>{h.current===e&&T(void 0)}},[e,T]);let D=gN((e,t)=>{m.current.add(e),g(n=>{let r=n.definitions[e];return r?{...n,definitions:hM(n.definitions,{[e]:{...r,state:t(r.state)}})}:n}),i.current.definitions[e]?.scope!==`thread`&&y(e)},[y,g]),O=hN(()=>({getModelContext:()=>{let e=i.current.definitions;return WB(e,o.current,D,c.current)??{}},subscribe:e=>(a.current.add(e),()=>{a.current.delete(e)})}),[D]);X(()=>{SI(a.current)},[t]),wF(`modelContext`,()=>r.current.modelContext().register(O),[O]);let k=gN((e,t)=>{let n=r.current?.tools;return!n||n.source==null?!1:(t.unsubscribe=n().setToolUI(Wz(e),t.render,{standalone:!0}),!0)},[r]);return wF(`tools`,()=>{for(let[e,t]of f.current)t.unsubscribe?.(),t.unsubscribe=void 0,k(e,t);return()=>{for(let e of f.current.values())e.unsubscribe?.(),e.unsubscribe=void 0}},[k]),{getState:()=>i.current,register:gN(e=>{let t=r.current?.thread,n=t&&t.source!=null?t().getState().messages??[]:[],i=e.scope??(GB(n,e.id,e.name)?`thread`:`app`);d.current.set(e.id,(d.current.get(e.id)??0)+1);let a;if(e.updateRender){let t=f.current.get(e.name),n=t??{count:0,render:e.updateRender,unsubscribe:void 0};n.count++,t||f.current.set(e.name,n),!n.unsubscribe&&k(e.name,n),a=()=>{let t=f.current.get(e.name);t&&--t.count===0&&(f.current.delete(e.name),t.unsubscribe?.(),t.unsubscribe=void 0)}}if(s.current.get(e.id)!==e.stateSchema){s.current.set(e.id,e.stateSchema),o.current.delete(e.id);try{let t=zz(e.stateSchema);o.current.set(e.id,Bz(t))}catch(t){console.warn(`[Interactables] Failed to create partial schema for "${e.name}". The update tool will accept arbitrary fields without validation.`,t)}}let c=i===`thread`?E():void 0,m=i===`thread`?c?u.current.get(c)?.get(e.id):void 0:l.current.get(e.id);i===`thread`?c&&u.current.get(c)?.delete(e.id):l.current.delete(e.id);let h=i===`thread`?void 0:p.current.get(e.id),_=i===`thread`?eB(n,e.id,e.name):void 0;return g(t=>({...t,definitions:hM(t.definitions,{[e.id]:{id:e.id,name:e.name,description:e.description,stateSchema:e.stateSchema,initialState:e.initialState,scope:i,state:t.definitions[e.id]?.state??m??_?.state??h??e.initialState}})})),()=>{a?.();let t=(d.current.get(e.id)??1)-1;if(t>0){d.current.set(e.id,t);return}d.current.delete(e.id),v(),g(t=>{let n=t.definitions[e.id];if(n){if(n.scope===`thread`){let t=E();if(t){let r=u.current.get(t);r||(r=new Map,u.current.set(t,r)),r.set(e.id,n.state)}}else l.current.set(e.id,n.state)}s.current.delete(e.id),o.current.delete(e.id);let r=hM(t.definitions),i=hM(t.persistence);return delete r[e.id],delete i[e.id],{...t,definitions:r,persistence:i}})}},[v,r,E,k,g]),setState:D,exportState:_,importState:S,setPersistenceAdapter:T,flush:b}},qB=MN(KB);sF(KB,(e,t)=>{!e.modelContext&&t.modelContext.source===null&&(e.modelContext=LI())});var JB=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=MP({attachment:fI({source:`message`,query:{type:`index`,index:n},get:e=>e.message.attachment({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(BL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},YB=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=MP({attachment:fI({source:`composer`,query:{type:`index`,index:n},get:e=>e.composer.attachment({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(BL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},XB=e=>{let t=J(6),{runtime:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=MP({threadListItem:AL({runtime:n})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(BL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},ZB=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=MP({message:fI({source:`thread`,query:{type:`index`,index:n},get:e=>e.thread.message({index:n})}),composer:fI({source:`message`,query:{},get:e=>e.thread.message({index:n}).composer()})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(BL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},QB=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=MP({part:fI({source:`message`,query:{type:`index`,index:n},get:e=>e.message.part({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(BL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},$B=MN(e=>{let t=J(7),{text:n,isRunning:r}=e,i;t[0]===r?i=t[1]:(i=r?{type:`running`}:{type:`complete`},t[0]=r,t[1]=i);let a;t[2]!==i||t[3]!==n?(a={type:`text`,text:n,status:i},t[2]=i,t[3]=n,t[4]=a):a=t[4];let o=a,s;return t[5]===o?s=t[6]:(s={getState:()=>o,addToolResult:tV,resumeToolCall:nV,respondToToolApproval:rV},t[5]=o,t[6]=s),s}),eV=e=>{let t=J(7),{text:n,isRunning:r,children:i}=e,a=r!==void 0&&r,o=Q(),s;t[0]!==a||t[1]!==n?(s=MP({part:$B({text:n,isRunning:a})}),t[0]=a,t[1]=n,t[2]=s):s=t[2];let c=s,l;return t[3]!==o||t[4]!==i||t[5]!==c?(l=(0,b.jsx)(BL,{extends:o,config:c,children:i}),t[3]=o,t[4]=i,t[5]=c,t[6]=l):l=t[6],l};function tV(){throw Error(`Not supported`)}function nV(){throw Error(`Not supported`)}function rV(){throw Error(`Not supported`)}var iV=e=>{for(let t of e)if(t?.status.type===`running`)return pL;return e.at(-1)?.status??fL},aV=(e,t)=>{let n={running:0,complete:0,incomplete:0,requiresAction:0},r=fL,i=!1;for(let a of t)switch(r=e[a]?.status??fL,r.type){case`running`:n.running++,i=!0;break;case`complete`:n.complete++;break;case`incomplete`:n.incomplete++;break;case`requires-action`:n.requiresAction++}return{status:i?pL:r,counts:n}},oV=MN(e=>{let t=J(11),{parts:n,getMessagePart:r}=e,[i,a]=pN(!0),o;t[0]===n?o=t[1]:(o=iV(n),t[0]=n,t[1]=o);let s=o,c;t[2]!==i||t[3]!==n||t[4]!==s?(c={parts:n,collapsed:i,status:s},t[2]=i,t[3]=n,t[4]=s,t[5]=c):c=t[5];let l=c,u;t[6]===l?u=t[7]:(u=()=>l,t[6]=l,t[7]=u);let d;return t[8]!==r||t[9]!==u?(d={getState:u,setCollapsed:a,part:r},t[8]=r,t[9]=u,t[10]=d):d=t[10],d}),sV=e=>{let t=J(4),{startIndex:n,endIndex:r,children:i}=e,a=$(cV).slice(n,r+1),o=Q(),s=MP({chainOfThought:oV({parts:a,getMessagePart:e=>{let{index:t}=e;if(t<0||t>=a.length)throw Error(`ChainOfThought part index ${t} is out of bounds (0..${a.length-1})`);return o.message.part({index:n+t})}})}),c;return t[0]!==i||t[1]!==s||t[2]!==o?(c=(0,b.jsx)(BL,{extends:o,config:s,children:i}),t[0]=i,t[1]=s,t[2]=o,t[3]=c):c=t[3],c};function cV(e){return e.message.parts}var lV=e=>{let t=J(7),{index:n,archived:r,children:i}=e,a=Q(),o;t[0]!==r||t[1]!==n?(o=MP({threadListItem:fI({source:`threads`,query:{type:`index`,index:n,archived:r},get:e=>e.threads.item({index:n,archived:r})})}),t[0]=r,t[1]=n,t[2]=o):o=t[2];let s=o,c;return t[3]!==a||t[4]!==i||t[5]!==s?(c=(0,b.jsx)(BL,{extends:a,config:s,children:i}),t[3]=a,t[4]=i,t[5]=s,t[6]=c):c=t[6],c},uV=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=MP({suggestion:fI({source:`suggestions`,query:{index:n},get:e=>e.suggestions.suggestion({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(BL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},dV=e=>{let t=J(6),{index:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=MP({queueItem:fI({source:`composer`,query:{type:`index`,index:n},get:e=>e.composer.queueItem({index:n})})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(BL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},fV=Symbol.for(`assistant-ui.message-not-sent`),pV=e=>typeof e==`object`&&!!e&&fV in e,mV=class{get path(){return this._core.path}_core;constructor(e){this._core=e,this.__internal_bindMethods()}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},hV=class extends mV{_composerApi;constructor(e,t){super(e),this._composerApi=t}remove(){let e=this._composerApi.getState();if(!e)throw Error(`Composer is not available`);return e.removeAttachment(this.getState().id)}},gV=class extends hV{get source(){return`thread-composer`}},_V=class extends hV{get source(){return`edit-composer`}},vV=class extends mV{get source(){return`message`}remove(){throw Error(`Message attachments cannot be removed`)}},yV=Object.freeze([]),bV=Object.freeze({}),xV=e=>Object.freeze({type:`thread`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,attachments:e?.attachments??yV,text:e?.text??``,role:e?.role??`user`,runConfig:e?.runConfig??bV,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??yV,value:e?.text??``}),SV=e=>Object.freeze({type:`edit`,isEditing:e?.isEditing??!1,canCancel:e?.canCancel??!1,canSend:e?.canSend??!1,isEmpty:e?.isEmpty??!0,text:e?.text??``,role:e?.role??`user`,attachments:e?.attachments??yV,runConfig:e?.runConfig??bV,attachmentAccept:e?.attachmentAccept??``,dictation:e?.dictation,quote:e?.quote,queue:e?.queue??yV,parentId:e?.parentId??null,sourceId:e?.sourceId??null,value:e?.text??``}),CV=class{get path(){return this._core.path}_core;constructor(e){this._core=e}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.steerQueueItem=this.steerQueueItem.bind(this),this.moveQueueItem=this.moveQueueItem.bind(this),this.removeQueueItem=this.removeQueueItem.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.startDictation=this.startDictation.bind(this),this.stopDictation=this.stopDictation.bind(this),this.setQuote=this.setQuote.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setText(e)}setRunConfig(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRunConfig(e)}addAttachment(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);return t.addAttachment(e)}reset(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.reset()}clearAttachments(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);return e.clearAttachments()}send(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.send(e)}cancel(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.cancel()}steerQueueItem(e){this.moveQueueItem(e,{lane:`steer`,insertAfter:null})}moveQueueItem(e,t){let n=this._core.getState();if(!n)throw Error(`Composer is not available`);n.moveQueueItem(e,t)}removeQueueItem(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.removeQueueItem(e)}setRole(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setRole(e)}startDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.startDictation()}stopDictation(){let e=this._core.getState();if(!e)throw Error(`Composer is not available`);e.stopDictation()}setQuote(e){let t=this._core.getState();if(!t)throw Error(`Composer is not available`);t.setQuote(e)}subscribe(e){return this._core.subscribe(e)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new jI({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},wV=class extends CV{get path(){return this._core.path}get type(){return`thread`}_getState;constructor(e){let t=new kI({path:e.path,getState:()=>xV(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>t.subscribe(e)}),this._getState=t.getState.bind(t),this.__internal_bindMethods()}getState(){return this._getState()}getAttachmentByIndex(e){return new gV(new OI({path:{...this.path,attachmentSource:`thread-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`thread-composer`}:xI},subscribe:e=>this._core.subscribe(e)}),this._core)}},TV=class extends CV{get path(){return this._core.path}get type(){return`edit`}_getState;_beginEdit;constructor(e,t){let n=new kI({path:e.path,getState:()=>SV(e.getState()),subscribe:t=>e.subscribe(t)});super({path:e.path,getState:()=>e.getState(),subscribe:e=>n.subscribe(e)}),this._beginEdit=t,this._getState=n.getState.bind(n),this.__internal_bindMethods()}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new _V(new OI({path:{...this.path,attachmentSource:`edit-composer`,attachmentSelector:{type:`index`,index:e},ref:`${this.path.ref}.attachments[${e}]`},getState:()=>{let t=this.getState().attachments[e];return t?{...t,source:`edit-composer`}:xI},subscribe:e=>this._core.subscribe(e)}),this._core)}},EV=e=>e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
91
91
 
92
- `),EV=`ui://`,DV=e=>!!e?.startsWith(EV),OV=e=>e.display===`text`||e.allowFreeform===!0,kV={"allow-once":!0,"allow-always":!0,"reject-once":!1,"reject-always":!1},AV=(e,t)=>{let n=t.text;if(n!==void 0&&!OV(e))throw Error(`Tool approval "${e.id}" does not accept a free-form answer; the request must declare display "text" or allowFreeform`);let r,i;if(`optionId`in t){let n=e.options?.find(e=>e.id===t.optionId);if(!n)throw Error(`Tool approval has no option with id "${t.optionId}"`);if(`approved`in t)r=t.approved;else{if(!Object.hasOwn(kV,n.kind))throw Error(`Tool approval option "${n.id}" has a custom kind "${n.kind}"; respond with an explicit approved value instead`);r=kV[n.kind]}i=n.id}else if(`approved`in t)r=t.approved;else{if(e.display!==`text`&&e.display!==`select`)throw Error(`Tool approval "${e.id}" is a decision, not a question; respond with an explicit approved value, optionally alongside the answer`);r=!0}return{approvalId:e.id,approved:r,...i!==void 0&&{optionId:i},...n!==void 0&&{text:n},...t.reason!=null&&{reason:t.reason}}},jV=class{get path(){return this.contentBinding.path}contentBinding;messageApi;threadApi;constructor(e,t,n){this.contentBinding=e,this.messageApi=t,this.threadApi=n,this.__internal_bindMethods()}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.respondToToolApproval=this.respondToToolApproval.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to add tool result to non-tool message part`);if(!this.messageApi)throw Error(`Message API is not available. This is likely a bug in assistant-ui.`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=this.messageApi.getState();if(!n)throw Error(`Message is not available`);let r=t.toolName,i=t.toolCallId,a=rR.toResponse(e);this.threadApi.getState().addToolResult({messageId:n.id,toolName:r,toolCallId:i,result:a.result,isError:a.isError,...a.artifact!==void 0&&{artifact:a.artifact},...a.modelContent!==void 0&&{modelContent:a.modelContent}})}resumeToolCall(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to resume tool call on non-tool message part`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:n,payload:e})}respondToToolApproval(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to respond to tool approval on non-tool message part`);if(!t.approval||t.approval.approved!==void 0||t.approval.resolution!==void 0)throw Error(`Tool call has no pending approval`);if(!this.threadApi)throw Error(`Thread API is not available`);return this.threadApi.getState().respondToToolApproval(AV(t.approval,e))}subscribe(e){return this.contentBinding.subscribe(e)}},MV=(e,t)=>{let n=e.content[t];if(!n)return bI;let r=hL(e,t,n);return Object.freeze({...n,[sB]:n[sB],status:r})},NV=class{get path(){return this._core.path}_core;_threadBinding;constructor(e,t){this._core=e,this._threadBinding=t,this.composer=new wV(new kI({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:`edit`},getState:this._getEditComposerRuntimeCore,subscribe:e=>this._threadBinding.subscribe(e)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}__internal_bindMethods(){this.reload=this.reload.bind(this),this.delete=this.delete.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}composer;_getEditComposerRuntimeCore=()=>this._threadBinding.getState().getEditComposer(this._core.getState().id);getState(){return this._core.getState()}delete(){let e=this._core.getState();return this._threadBinding.getState().deleteMessage(e.id)}reload(e={}){let t=this._getEditComposerRuntimeCore(),n=t??this._threadBinding.getState().composer,r=t??n,{runConfig:i=r.runConfig}=e,a=this._core.getState();if(a.role!==`assistant`)throw Error(`Can only reload assistant messages`);this._threadBinding.getState().startRun({parentId:a.parentId,sourceId:a.id,runConfig:i})}speak(){let e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){let e=this._core.getState();if(this._threadBinding.getState().speech?.messageId===e.id)this._threadBinding.getState().stopSpeaking();else throw Error(`Message is not being spoken`)}submitFeedback({type:e,comment:t}){let n=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:n.id,type:e,...t===void 0?void 0:{comment:t}})}switchToBranch({position:e,branchId:t}){let n=this._core.getState();if(t&&e)throw Error(`May not specify both branchId and position`);if(!t&&!e)throw Error(`Must specify either branchId or position`);let r=this._threadBinding.getState().getBranches(n.id),i=t;if(e===`previous`?i=r[n.branchNumber-2]:e===`next`&&(i=r[n.branchNumber]),!i)throw Error(`Branch not found`);this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return TV(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw Error(`Message part index must be >= 0`);return new jV(new DI({path:{...this.path,ref:`${this.path.ref}.content[${e}]`,messagePartSelector:{type:`index`,index:e}},getState:()=>MV(this.getState(),e),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new jV(new DI({path:{...this.path,ref:`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:`toolCallId`,toolCallId:e}},getState:()=>{let t=this._core.getState(),n=t.content.findIndex(t=>t.type===`tool-call`&&t.toolCallId===e);return n===-1?bI:MV(t,n)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new _V(new DI({path:{...this.path,ref:`${this.path.ref}.attachments[${e}]`,attachmentSource:`message`,attachmentSelector:{type:`index`,index:e}},getState:()=>{let t=this.getState().attachments?.[e];return t?{...t,source:`message`}:bI},subscribe:e=>this._core.subscribe(e)}))}},PV=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),FV=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),IV=(e,t)=>typeof t==`string`?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:`user`,content:[{type:`text`,text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId===void 0?e.at(-1)?.id??null:t.parentId,sourceId:t.sourceId??null,role:t.role??`user`,content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},LV=e=>{if(e.isRunning!==void 0)return e.isRunning;let t=e.messages.at(-1);return t?.role===`assistant`&&t.status.type===`running`},RV=(e,t)=>Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:LV(e),messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech,voice:e.voice}),zV=class{get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;_stateBinding;constructor(e,t){let n=new DI({path:e.path,getState:()=>RV(e.getState(),t.getState()),subscribe:n=>{let r=e.subscribe(n),i=t.subscribe(n);return()=>SI([r,i])}});this._stateBinding=n,this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>n.getState(),outerSubscribe:t=>e.outerSubscribe(t),subscribe:t=>e.subscribe(t)},this.composer=new CV(new kI({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:`thread`},getState:()=>this._threadBinding.getState().composer,subscribe:e=>this._threadBinding.subscribe(e)})),this.__internal_bindMethods()}__internal_bindMethods(){this.append=this.append.bind(this),this.deleteMessage=this.deleteMessage.bind(this),this.resumeRun=this.resumeRun.bind(this),this.importExternalState=this.importExternalState.bind(this),this.exportExternalState=this.exportExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.unstable_notifySessionReset=this.unstable_notifySessionReset.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.connectVoice=this.connectVoice.bind(this),this.disconnectVoice=this.disconnectVoice.bind(this),this.muteVoice=this.muteVoice.bind(this),this.unmuteVoice=this.unmuteVoice.bind(this),this.getVoiceVolume=this.getVoiceVolume.bind(this),this.subscribeVoiceVolume=this.subscribeVoiceVolume.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getState=this.getState.bind(this)}composer;getState(){return this._threadBinding.getStateState()}append(e){let t=this._threadBinding.getState().append(IV(this._threadBinding.getState().messages,e));Promise.resolve(t).catch(e=>{if(!fV(e))throw e})}deleteMessage(e){return this._threadBinding.getState().deleteMessage(e)}subscribe(e){return this._stateBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}startRun(e){return this._threadBinding.getState().startRun(FV(e))}resumeRun(e){return this._threadBinding.getState().resumeRun(PV(e))}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}unstable_notifySessionReset(){this._threadBinding.getState().unstable_notifySessionReset()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}connectVoice(){this._threadBinding.getState().connectVoice()}disconnectVoice(){this._threadBinding.getState().disconnectVoice()}getVoiceVolume(){return this._threadBinding.getState().getVoiceVolume()}subscribeVoiceVolume(e){return this._threadBinding.getState().subscribeVoiceVolume(e)}muteVoice(){this._threadBinding.getState().muteVoice()}unmuteVoice(){this._threadBinding.getState().unmuteVoice()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw Error(`Message index must be >= 0`);return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[${e}]`,messageSelector:{type:`index`,index:e}},()=>{let t=this._threadBinding.getState().messages,n=t[e];if(n)return{message:n,parentId:t[e-1]?.id??null,index:e}})}getMessageById(e){return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:`messageId`,messageId:e}},()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new NV(new DI({path:e,getState:()=>{let{message:e,parentId:n,index:r}=t()??{},{messages:i,speech:a}=this._threadBinding.getState();if(!e||n===void 0||r===void 0)return bI;let o=this._threadBinding.getState().getBranches(e.id);return{...e,[sB]:e[sB],index:r,isLast:i.at(-1)?.id===e.id,parentId:n,branchNumber:o.indexOf(e.id)+1,branchCount:o.length,speech:a?.messageId===e.id?a:void 0}},subscribe:e=>this._threadBinding.subscribe(e)}),this._threadBinding)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new AI({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},BV=(e,t)=>({attachments:[],attachmentAccept:`*`,async addAttachment(){throw e},async removeAttachment(){throw e},isEditing:t,canCancel:!1,canSend:!1,isEmpty:!0,text:``,setText(){throw e},role:`user`,setRole(){throw e},runConfig:{},setRunConfig(){throw e},async reset(){},async clearAttachments(){},send(){throw e},cancel(){},queue:[],moveQueueItem(){},removeQueueItem(){},dictation:void 0,startDictation(){throw e},stopDictation(){},quote:void 0,setQuote(){throw e},subscribe(){return()=>{}},unstable_on(){return()=>{}}}),VV=class extends wI{switchToBranch(){throw this.error}append(){throw this.error}deleteMessage(){throw this.error}startRun(){throw this.error}resumeRun(){throw this.error}cancelRun(){throw this.error}unstable_notifySessionReset(){throw this.error}addToolResult(){throw this.error}resumeToolCall(){throw this.error}respondToToolApproval(){throw this.error}speak(){throw this.error}stopSpeaking(){throw this.error}connectVoice(){throw this.error}disconnectVoice(){throw this.error}muteVoice(){throw this.error}unmuteVoice(){throw this.error}submitFeedback(){throw this.error}exportExternalState(){throw this.error}importExternalState(){throw this.error}beginEdit(){throw this.error}import(){throw this.error}reset(){throw this.error}getModelContext(){return{}}getEditComposer(){}getVoiceVolume=()=>0;subscribeVoiceVolume=()=>()=>{};speech=void 0;voice=void 0;capabilities={switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,delete:!1,reload:!1,refetchThread:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1};isDisabled=!1;isSendDisabled=!1;state=null;suggestions=[];extras=void 0;unstable_on(){return()=>{}}},HV=e=>{let t=J(6),{adapters:n,children:r}=e,i=AN(nB),a;t[0]!==n||t[1]!==i?(a={...i,...n},t[0]=n,t[1]=i,t[2]=a):a=t[2];let o=a,s;return t[3]!==r||t[4]!==o?(s=(0,b.jsx)(nB.Provider,{value:o,children:r}),t[3]=r,t[4]=o,t[5]=s):s=t[5],s},UV=class{get path(){return this._core.path}_core;_threadListBinding;constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.updateCustom=this.updateCustom.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(e){let t=this._core.getState();return this._threadListBinding.switchToThread(t.id,e)}rename(e){let t=this._core.getState();return this._threadListBinding.rename(t.id,e)}updateCustom(e){let t=this._core.getState();if(!this._threadListBinding.updateCustom)throw Error(`Thread list runtime does not support updating custom metadata`);return this._threadListBinding.updateCustom(t.id,e)}archive(){let e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){let e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){let e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){let e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(e){let t=this._core.getState();return this._threadListBinding.generateTitle(t.id,e)}unstable_on(e,t){let n=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{let i=this._core.getState(),a=i.isMain,o=i.id;(n!==a||r!==o)&&(n=a,r=o,(e!==`switchedTo`||a)&&(e===`switchedAway`&&a||AP([t],{},`Thread list item "${e}"`)))})}subscribe(e){return this._core.subscribe(e)}detach(){let e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}},WV=Promise.resolve(),GV=()=>{},KV=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,loadError:e.loadError,isLoadingMore:e.isLoadingMore??!1,hasMore:e.hasMore??!1,threadItems:e.threadItems}),qV=(e,t)=>{if(t===void 0)return bI;let n=e.getItemById(t);return n?{id:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,lastMessageAt:n.lastMessageAt,custom:n.custom,isMain:n.id===e.mainThreadId,isRunning:e.unstable_isThreadRunning?.(n.id)??!1}:bI},JV=class{_getState;_stateBinding;_core;_runtimeFactory;constructor(e,t=zV){this._core=e,this._runtimeFactory=t;let n=new OI({path:{},getState:()=>KV(e),subscribe:t=>e.subscribe(t)});this._getState=n.getState.bind(n),this._stateBinding=n,this._mainThreadListItemRuntime=new UV(new DI({path:{ref:`threadItems[main]`,threadSelector:{type:`main`}},getState:()=>qV(this._core,this._core.mainThreadId),subscribe:e=>this._core.subscribe(e)}),this._core),this.main=new t(new kI({path:{ref:`threads.main`,threadSelector:{type:`main`}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:t=>e.subscribe(t)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.unstable_subscribeThreadEvents=this.unstable_subscribeThreadEvents.bind(this),this.getLoadThreadsPromise=this.getLoadThreadsPromise.bind(this),this.reload=this.reload.bind(this),this.reloadMainThread=this.reloadMainThread.bind(this),this.loadMore=this.loadMore.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e,t){return this._core.switchToThread(e,t)}switchToNewThread(){return this._core.switchToNewThread()}unstable_subscribeThreadEvents(e){return this._core.unstable_subscribeThreadEvents?.(e)??GV}getLoadThreadsPromise(){return this._core.getLoadThreadsPromise()}reload(){return this._core.reload?.()??WV}reloadMainThread(){return this._core.reloadMainThread?.()??WV}loadMore(){return this._core.loadMore?.()??WV}getState(){return this._getState()}subscribe(e){return this._stateBinding.subscribe(e)}_mainThreadListItemRuntime;main;get mainItem(){return this._mainThreadListItemRuntime}_createItemStateBinding(e){return new DI({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>qV(this._core,e),subscribe:e=>this._core.subscribe(e)})}getById(e){return new this._runtimeFactory(new kI({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:e=>this._core.subscribe(e)}),this._createItemStateBinding(e))}getItemByIndex(e){return new UV(new DI({path:{ref:`threadItems[${e}]`,threadSelector:{type:`index`,index:e}},getState:()=>qV(this._core,this._core.threadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(e){return new UV(new DI({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:`archiveIndex`,index:e}},getState:()=>qV(this._core,this._core.archivedThreadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(e){return new UV(this._createItemStateBinding(e),this._core)}},YV=class{threads;_thread;_core;constructor(e){this._core=e,this.threads=new JV(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.registerModelContextProvider=this.registerModelContextProvider.bind(this)}get thread(){return this._thread}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}},XV=new WeakMap,ZV=e=>XV.get(e)??0,QV=(e,t)=>ZV(e)===t,$V=e=>{XV.set(e,ZV(e)+1)},eH=class{_contextProvider=new jI;registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},tH=Object.freeze([]),nH=`DEFAULT_THREAD_ID`,rH=Object.freeze([nH]),iH=Object.freeze({id:nH,remoteId:void 0,externalId:void 0,status:`regular`}),aH=Promise.resolve(),oH=Object.freeze(mM({[nH]:iH})),sH=class extends wI{_mainThreadId=nH;_threads=rH;_archivedThreads=tH;_threadData=oH;adapter={};get isLoading(){return this.adapter.isLoading??!1}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}get threadItems(){return this._threadData}getLoadThreadsPromise(){return aH}_mainThread;get mainThreadId(){return this._mainThreadId}threadFactory;constructor(e={},t){super(),this.threadFactory=t,this.__internal_setAdapter(e,!0)}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw Error(`Method not implemented.`)}getItemById(e){return Object.hasOwn(this._threadData,e)?this._threadData[e]:void 0}__internal_setAdapter(e,t=!1){let n=this.adapter;this.adapter=e;let r=e.threadId??nH,i=e.threads??tH,a=e.archivedThreads??tH,o=n.threadId??nH,s=n.threads??tH,c=n.archivedThreads??tH;(t||(n.isLoading??!1)!==(e.isLoading??!1)||o!==r||s!==i||c!==a)&&((s!==i||c!==a||o!==r)&&(this._threadData=mM(oH,Object.fromEntries(e.threads?.map(e=>[e.id,{...e,remoteId:e.remoteId,externalId:e.externalId,status:`regular`}])??[]),Object.fromEntries(e.archivedThreads?.map(e=>[e.id,{...e,remoteId:e.remoteId,externalId:e.externalId,status:`archived`}])??[]))),s!==i&&(this._threads=this.adapter.threads?.map(e=>e.id)??tH),c!==a&&(this._archivedThreads=this.adapter.archivedThreads?.map(e=>e.id)??tH),(t||o!==r)&&(t||$V(this._mainThread),this._mainThreadId=r,this._mainThread=this.threadFactory()),Object.hasOwn(this._threadData,this._mainThreadId)||(this._threadData=mM(this._threadData,{[this._mainThreadId]:{id:this._mainThreadId,remoteId:void 0,externalId:void 0,status:`regular`}})),this._notifySubscribers())}async reloadMainThread(){this._mainThread.unstable_refetchThread&&await this._mainThread.unstable_refetchThread()}async switchToThread(e,t){if(this._mainThreadId===e)return;let n=this.adapter.onSwitchToThread;if(!n)throw Error(`External store adapter does not support switching to thread`);await n(e)}async switchToNewThread(){let e=this.adapter.onSwitchToNewThread;if(!e)throw Error(`External store adapter does not support switching to new thread`);await e()}async rename(e,t){let n=this.adapter.onRename;if(!n)throw Error(`External store adapter does not support renaming`);await n(e,t)}async updateCustom(e,t){let n=this.adapter.onUpdateCustom;if(!n)throw Error(`External store adapter does not support updating custom metadata`);await n(e,t)}async detach(){}async archive(e){let t=this.adapter.onArchive;if(!t)throw Error(`External store adapter does not support archiving`);await t(e)}async unarchive(e){let t=this.adapter.onUnarchive;if(!t)throw Error(`External store adapter does not support unarchiving`);await t(e)}async delete(e){let t=this.adapter.onDelete;if(!t)throw Error(`External store adapter does not support deleting`);await t(e)}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){throw Error(`Method not implemented.`)}},cH={fromArray:e=>{let t=e.map(e=>gB(e,pB(),OB(e.content)));return{messages:t.map((e,n)=>({parentId:n>0?t[n-1].id:null,message:e}))}},fromBranchableArray:(e,t)=>({...t?.headId===void 0?void 0:{headId:t.headId},messages:e.map(({message:e,parentId:t})=>{if(!e.id)throw Error(`ExportedMessageRepository.fromBranchableArray: Each message must have an 'id' field set.`);return{parentId:t,message:gB(e,e.id,OB(e.content))}})})},lH=e=>{let t=e;for(;t.next;)t=t.next;return`current`in t?t:null},uH=class{_value=null;func;constructor(e){this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},dH=class{messages=new Map;head=null;root={children:[],next:null};updateLevels(e,t){let n=[{message:e,level:t}];for(;n.length>0;){let e=n.pop();e.message.level=e.level;for(let t of e.message.children){let r=this.messages.get(t);r&&n.push({message:r,level:e.level+1})}}}selectPathTo(e){for(let t=e;t;t=t.prev)(t.prev??this.root).next=t}performOp(e,t,n){let r=t.prev??this.root,i=e??this.root;if(n!==`relink`||r!==i){if(n===`relink`){for(let n=e;n;n=n.prev)if(n.current.id===t.current.id)throw Error(`MessageRepository(performOp/relink): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.`)}if(n!==`link`&&(r.children=r.children.filter(e=>e!==t.current.id),r.next===t)){let e=r.children.at(-1),t=e?this.messages.get(e):null;if(t===void 0)throw Error(`MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.`);r.next=t}if(n!==`cut`){i.children=[...i.children,t.current.id],t.prev=e,lH(t)===this.head?this.selectPathTo(t):i.next===null&&(i.next=t,this.head===i&&(this.head=lH(t)));let n=e?e.level+1:0;this.updateLevels(t,n)}}}_messages=new uH(()=>{let e=Array((this.head?.level??-1)+1);for(let t=this.head;t;t=t.prev)e[t.level]=t.current;return e});get headId(){return this.head?.current.id??null}get canonicalHeadId(){let e=this.head;for(;e?.current.metadata?.isOptimistic;)e=e.prev;return e?.current.id??null}getMessages(e){if(e===void 0||e===this.head?.current.id)return this._messages.value;let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.`);let n=Array(t.level+1);for(let e=t;e;e=e.prev)n[e.level]=e.current;return n}addOrUpdateMessage(e,t){let n=this.messages.get(t.id),r=e?this.messages.get(e):null;if(r===void 0)throw Error(`MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.`);if(n){n.current=t,this.performOp(r,n,`relink`),this._messages.dirty();return}let i={prev:r,current:t,next:null,children:[],level:r?r.level+1:0};this.messages.set(t.id,i),this.performOp(r,i,`link`),this.head===r&&(this.head=i),this._messages.dirty()}getMessage(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.`);return{parentId:t.prev?.current.id??null,message:t.current,index:t.level}}deleteMessage(e,t){let n=this.messages.get(e);if(!n)throw Error(`MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.`);let r=t===void 0?n.prev:t===null?null:this.messages.get(t);if(r===void 0)throw Error(`MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.`);for(let e of n.children){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.`);this.performOp(r,t,`relink`)}this.performOp(null,n,`cut`),this.messages.delete(e),this.head===n&&(this.head=lH(r??this.root)),this._messages.dirty()}getBranches(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.`);let{children:n}=t.prev??this.root;return n}evictOffBranchOptimisticMessages(e,t){if(!e)return;let n=new Set;for(let e=t;e;e=e.prev)n.add(e.current.id);let r=[];for(let t=e;t&&!n.has(t.current.id);t=t.prev)t.current.metadata?.isOptimistic&&r.push(t.current.id);for(let e of r)this.messages.has(e)&&this.deleteMessage(e)}switchToBranch(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.`);let n=this.head;this.selectPathTo(t),this.head=lH(t),this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.`);let n=this.head;if(t.children.length>0){let e=[...t.children];for(;e.length>0;){let t=e.pop(),n=this.messages.get(t);if(n){for(let t of n.children)e.push(t);this.messages.delete(t)}}t.children=[],t.next=null}this.head=t,this.selectPathTo(t),this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){let e=[],t=[...this.root.children].reverse();for(;t.length>0;){let n=this.messages.get(t.pop());if(!n)continue;for(let e=n.children.length-1;e>=0;e--)t.push(n.children[e]);if(n.current.metadata?.isOptimistic)continue;let r=n.prev;for(;r&&r.current.metadata?.isOptimistic;)r=r.prev;e.push({message:n.current,parentId:r?.current.id??null})}return{headId:this.canonicalHeadId,messages:e}}import({headId:e,messages:t}){for(let{message:e,parentId:n}of t)this.addOrUpdateMessage(n,e);this.resetHead(e??t.at(-1)?.message.id??null)}},fH=Object.freeze([]);function*pH(e){for(let t of e)if(t?.role===`assistant`&&Array.isArray(t.content))for(let e of t.content)e&&e.type===`tool-call`&&(yield{part:e,messageId:t.id},e.messages?.length&&(yield*pH(e.messages)))}function mH(e,t){if(t===`*`)return!0;let n=t.split(`,`).map(e=>e.trim().toLowerCase()),r=e.name.toLowerCase(),i=e.type.split(`;`,1)[0].trim().toLowerCase();for(let e of n){if(e.startsWith(`.`)&&r.endsWith(e)||e.includes(`/`)&&e===i)return!0;if(e.endsWith(`/*`)){let t=e.split(`/`)[0];if(i.startsWith(`${t}/`))return!0}}return!1}function hH(e){let t=pB();return e.type===`image`?{id:t,type:`image`,name:e.filename??`image`,content:[e],status:{type:`complete`}}:e.type===`file`?{id:t,type:`document`,name:e.filename??`document`,contentType:e.mimeType,content:[e],status:{type:`complete`}}:e.type===`audio`?{id:t,type:`audio`,name:`audio.${e.audio.format}`,contentType:`audio/${e.audio.format}`,content:[e],status:{type:`complete`}}:{id:t,type:`data`,name:e.name,content:[e],status:{type:`complete`}}}function gH(e){let t=[];for(let n of e)n.type!==`text`&&t.push(hH(n));return t}var _H=e=>`content`in e&&!(`lastModified`in e),vH=e=>e.status.type===`complete`,yH=class{operations=new Set;start(){let e={cancelled:!1,attachmentIds:new Set};return this.operations.add(e),e}accept(e,t){return!e.cancelled&&(e.attachmentIds.add(t),!0)}finish(e){this.operations.delete(e)}isCancelled(e){return e.cancelled}cancel(e){for(let t of[...this.operations])t.attachmentIds.has(e)&&(t.cancelled=!0,this.operations.delete(t))}cancelAll(){for(let e of this.operations)e.cancelled=!0;this.operations.clear()}},bH=async(e,t)=>{if(Symbol.asyncIterator in e){for await(let n of e)if(!t(n))break}else t(await e)},xH=class extends wI{isEditing=!0;enrichWithComposerMetadata(e,t){return t?{...e,metadata:{...e.metadata,custom:{...e.metadata?.custom,...t}}}:e}get attachmentAccept(){return this.getAttachmentAdapter()?.accept??`*`}_attachments=[];get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}_text=``;get text(){return this._text}_role=`user`;get role(){return this._role}_runConfig={};get runConfig(){return this._runConfig}_quote=void 0;get quote(){return this._quote}setQuote(e){this._quote!==e&&(this._quote=e,this._notifySubscribers())}setText(e){this._text!==e&&(this._text=e,this._rebaseDictation(e),this._notifySubscribers())}_rebaseDictation(e){if(!this._dictation)return;this._dictationBaseText=e,this._currentInterimText=``;let{status:t,inputDisabled:n}=this._dictation;this._dictation=n?{status:t,inputDisabled:n}:{status:t}}setRole(e){this._role!==e&&(this._role=e,this._notifySubscribers())}setRunConfig(e){this._runConfig!==e&&(this._runConfig=e,this._notifySubscribers())}_isSending=!1;_removedDuringSend=new Set;_sendGeneration=0;_attachmentAddOperations=new yH;_cancelAttachmentAdd(e){this._attachmentAddOperations.cancel(e)}_cancelAllAttachmentAdds(){this._attachmentAddOperations.cancelAll()}_emptyTextAndAttachments(){this._attachments=[],this._text=``,this._rebaseDictation(``),this._notifySubscribers()}async _onClearAttachments(){let e=this.getAttachmentAdapter();if(e){let t=this._attachments.filter(e=>!vH(e));await Promise.all(t.map(async t=>e.remove(t)))}}async reset(){if(this._cancelAllAttachmentAdds(),this._sendGeneration++,this._isSending=!1,this._removedDuringSend.clear(),this._attachments.length===0&&this._text===``&&this._role===`user`&&Object.keys(this._runConfig).length===0&&this._quote===void 0)return;this._role=`user`,this._runConfig={},this._quote=void 0;let e=this._onClearAttachments();this._emptyTextAndAttachments(),await e}async clearAttachments(){if(this._cancelAllAttachmentAdds(),this._isSending)for(let e of this._attachments)this._removedDuringSend.add(e.id);let e=this._onClearAttachments();this.setAttachments([]),await e}async send(e){if(!this.canSend||this._isSending)return;if(this._dictationSession)try{this._dictationSession.cancel()}catch(e){console.error(`[assistant-ui] Dictation session cancel threw`,e)}finally{this._cleanupDictation()}let t=this.getAttachmentAdapter(),n=this.attachments.map(async e=>{if(vH(e))return e;if(!t)throw Error(`Attachments are not supported`);return await t.send(e)}),r=this.attachments,i=this.text,a=this._quote,o=this.role,s=this.runConfig;this._quote=void 0,this._text=``,this._isSending=!0;let c=++this._sendGeneration;this._notifySubscribers();let l;try{l=await Promise.all(n)}catch(e){throw c===this._sendGeneration&&(!this.text.trim()&&this._quote===void 0&&(this._text=i,this._rebaseDictation(i),this._quote=a,this._notifySubscribers()),Promise.allSettled(n).then(()=>{c===this._sendGeneration&&(this._removedDuringSend.clear(),this._isSending=!1,this._notifySubscribers())})),e}if(c!==this._sendGeneration)return;let u=new Set(r.map(e=>e.id));this._attachments=this._attachments.filter(e=>!u.has(e.id)),this._isSending=!1,this._notifySubscribers();let d=l.filter(e=>!this._removedDuringSend.has(e.id));this._removedDuringSend.clear();let f={createdAt:new Date,role:o,content:i?[{type:`text`,text:i}]:[],attachments:d,runConfig:s,metadata:{custom:{...a?{quote:a}:{}}}},p={text:i,quote:a,attachments:d},m;try{m=this.handleSend(f,e)}catch(e){throw this._restoreUnsentDraft(e,c,p),e}m&&m.catch(e=>{this._restoreUnsentDraft(e,c,p)}),this._notifyEventSubscribers(`send`,{chars:i.length,attachments:d.length})}restoreDraft(e){return this._text.trim()||this._quote!==void 0||this._attachments.length>0?!1:(this._text=e.text,this._rebaseDictation(e.text),this._quote=e.quote,this._attachments=e.attachments??[],this._notifySubscribers(),!0)}retractDraft(e){let t=e.attachments===void 0?this._attachments.length===0:this._attachments===e.attachments;this._text===e.text&&this._quote===e.quote&&t&&(this._text=``,this._rebaseDictation(``),this._quote=void 0,this._attachments=[],this._notifySubscribers())}_restoreUnsentDraft(e,t,n){fV(e)&&t===this._sendGeneration&&this.restoreDraft(n)}cancel(){this.handleCancel()}get queue(){return fH}moveQueueItem(e,t){}removeQueueItem(e){}async addAttachment(e){if(_H(e)){let t=this.getAttachmentAdapter();if(t&&!mH({name:e.name,type:e.contentType??``},t.accept)){let n=`File type ${e.contentType||`unknown`} is not accepted. Accepted types: ${t.accept}`,r=Error(n);throw this._safeEmitAttachmentAddError(`not-accepted`,n,void 0,r,e.contentType),r}let n={id:e.id??pB(),type:e.type??`document`,name:e.name,contentType:e.contentType,content:e.content,status:{type:`complete`}};this._attachments=[...this._attachments,n],this._notifySubscribers(),this._notifyEventSubscribers(`attachmentAdd`,{...n.contentType?{contentType:n.contentType}:void 0});return}let t=this.getAttachmentAdapter();if(!t){let t=`Attachments are not supported`,n=Error(t);throw this._safeEmitAttachmentAddError(`no-adapter`,t,void 0,n,e.type),n}if(!mH({name:e.name,type:e.type},t.accept)){let n=`File type ${e.type||`unknown`} is not accepted. Accepted types: ${t.accept}`,r=Error(n);throw this._safeEmitAttachmentAddError(`not-accepted`,n,void 0,r,e.type),r}let n=this._attachmentAddOperations.start(),r=e=>{if(!this._attachmentAddOperations.accept(n,e.id))return!1;let t=this._attachments.findIndex(t=>t.id===e.id);return this._attachments=t===-1?[...this._attachments,e]:[...this._attachments.slice(0,t),e,...this._attachments.slice(t+1)],this._notifySubscribers(),!0},i;try{await bH(t.add({file:e}),e=>(i=e,r(e)))}catch(t){if(this._attachmentAddOperations.isCancelled(n))return;throw i&&r({...i,status:{type:`incomplete`,reason:`error`,message:t instanceof Error?t.message:String(t)}}),this._safeEmitAttachmentAddError(`adapter-error`,t instanceof Error?t.message:String(t),i?.id,t instanceof Error?t:void 0,i?.contentType||e.type),t}finally{this._attachmentAddOperations.finish(n)}this._attachmentAddOperations.isCancelled(n)||(i?.status.type===`incomplete`&&i.status.reason===`error`?this._safeEmitAttachmentAddError(`adapter-error`,i.status.message??`Attachment upload did not complete successfully.`,i.id,void 0,i.contentType||e.type):this._notifyEventSubscribers(`attachmentAdd`,{...i?.contentType?{contentType:i.contentType}:e.type?{contentType:e.type}:void 0}))}_safeEmitAttachmentAddError(e,t,n,r,i){try{this._notifyEventSubscribers(`attachmentAddError`,{reason:e,message:t,...n!==void 0&&{attachmentId:n},...r!==void 0&&{error:r},...i?{contentType:i}:void 0})}catch(e){console.error(`[assistant-ui] attachmentAddError subscriber threw:`,e)}}async removeAttachment(e){let t=this._attachments.findIndex(t=>t.id===e);if(t===-1)throw Error(`Attachment not found`);let n=this._attachments[t];if(this._cancelAttachmentAdd(e),this._isSending&&this._removedDuringSend.add(e),!vH(n)){let t=this.getAttachmentAdapter();if(!t)throw Error(`Attachments are not supported`);try{await t.remove(n)}catch(t){let n=t instanceof Error?t.message:String(t);throw this._attachments=this._attachments.map(t=>t.id===e&&!vH(t)?{...t,status:{type:`incomplete`,reason:`error`,message:n}}:t),this._notifySubscribers(),t}}this._attachments=this._attachments.filter(t=>t.id!==e),this._notifySubscribers()}_dictation;_dictationSession;_dictationUnsubscribes=[];_dictationBaseText=``;_currentInterimText=``;_dictationSessionIdCounter=0;_activeDictationSessionId;_isCleaningDictation=!1;get dictation(){return this._dictation}_isActiveSession(e,t){return this._activeDictationSessionId===e&&this._dictationSession===t}startDictation(){let e=this.getDictationAdapter();if(!e)throw Error(`Dictation adapter not configured`);let t=this._dictationSession!==void 0;if(this._dictationSession){let e=this._dictationSession;this._cleanupDictation({notify:!1}),this._stopDictationSession(e)}let n=e.disableInputDuringDictation??!1;this._dictationBaseText=this._text,this._currentInterimText=``;let r;try{r=e.listen()}catch(e){if(t)try{this._notifySubscribers()}catch(e){console.error(`[assistant-ui] Dictation replacement rollback notification threw`,e)}throw e}this._dictationSession=r;let i=++this._dictationSessionIdCounter;this._activeDictationSessionId=i,this._dictation={status:r.status,inputDisabled:n},this._notifySubscribers();let a=r.onSpeech(e=>{if(!this._isActiveSession(i,r))return;let t=e.isFinal!==!1,n=this._dictationBaseText&&!this._dictationBaseText.endsWith(` `)&&e.transcript?` `:``;if(t){if(this._dictationBaseText=this._dictationBaseText+n+e.transcript,this._currentInterimText=``,this._text=this._dictationBaseText,this._dictation){let{transcript:e,...t}=this._dictation;this._dictation=t}this._notifySubscribers()}else this._currentInterimText=n+e.transcript,this._text=this._dictationBaseText+this._currentInterimText,this._dictation&&={...this._dictation,transcript:e.transcript},this._notifySubscribers()});this._dictationUnsubscribes.push(a);let o=r.onSpeechStart(()=>{this._isActiveSession(i,r)&&(this._dictation={status:{type:`running`},inputDisabled:n,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._notifySubscribers())});this._dictationUnsubscribes.push(o);let s=r.onSpeechEnd(()=>{this._cleanupDictation({sessionId:i})});this._dictationUnsubscribes.push(s);let c=setInterval(()=>{this._isActiveSession(i,r)&&r.status.type===`ended`&&this._cleanupDictation({sessionId:i})},100);this._dictationUnsubscribes.push(()=>clearInterval(c))}stopDictation(){if(!this._dictationSession)return;let e=this._dictationSession,t=this._activeDictationSessionId;this._stopDictationSession(e,()=>this._cleanupDictation({sessionId:t}))}_stopDictationSession(e,t=()=>{}){let n;try{n=e.stop()}catch(e){console.error(`[assistant-ui] Dictation session stop threw`,e),t();return}n.then(t,e=>{console.error(`[assistant-ui] Dictation session stop rejected`,e),t()})}_cleanupDictation(e){if(e?.sessionId!==void 0&&e.sessionId!==this._activeDictationSessionId||this._isCleaningDictation)return;this._isCleaningDictation=!0;let t=e=>{try{e()}catch(e){console.error(`[assistant-ui] Dictation cleanup threw`,e)}};try{let n=this._dictationUnsubscribes;this._dictationUnsubscribes=[],this._dictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText=``,this._currentInterimText=``;for(let e of n)t(e);e?.notify!==!1&&t(()=>this._notifySubscribers())}finally{this._isCleaningDictation=!1}}_eventSubscribers=new Map;_notifyEventSubscribers(e,t){let n=this._eventSubscribers.get(e);n&&AP(n,t,`Composer runtime "${e}"`)}unstable_on(e,t){let n=t,r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),()=>{this._eventSubscribers.get(e)?.delete(n)}}},SH=e=>e.capabilities?.cancel?LV(e):!1,CH=class extends xH{get canCancel(){return SH(this.runtime)}get canSend(){return!this.isEmpty&&!this.runtime.isSendDisabled&&!this.runtime.voice&&!this._isSending}_queueCache;get queue(){let e=this.runtime.getSteerQueueItems?.()??fH,t=this.runtime.getQueueItems?.()??fH,n=this._queueCache;if(n&&n.steer===e&&n.queue===t)return n.flat;let r=e.length===0?t:t.length===0?e:[...e,...t];return this._queueCache={steer:e,queue:t,flat:r},r}moveQueueItem(e,t){this.runtime.moveQueueItem?.(e,t)}removeQueueItem(e){this.runtime.removeQueueItem?.(e)}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}runtime;constructor(e){super(),this.runtime=e,this.connect()}connect(){let e=!1,t=this.runtime.isSendDisabled,n=this.runtime.voice!==void 0,r=this.queue;return this.runtime.subscribe(()=>{let i=!1,a=this.canCancel;e!==a&&(e=a,i=!0),t!==this.runtime.isSendDisabled&&(t=this.runtime.isSendDisabled,i=!0);let o=this.runtime.voice!==void 0;n!==o&&(n=o,i=!0),r!==this.queue&&(r=this.queue,i=!0),i&&this._notifySubscribers()})}async handleSend(e,t){return this.runtime.append({...e,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null,startRun:t?.startRun,steer:t?.steer})}async handleCancel(){this.runtime.cancelRun()}},wH=class extends xH{get canCancel(){return!0}get canSend(){return!this.isEmpty&&!this.runtime.voice&&!this._isSending}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}_nonTextPassthrough;_parentId;_sourceId;runtime;endEditCallback;constructor(e,t,{parentId:n,message:r}){super(),this.runtime=e;let i=e.voice!==void 0,a=e.subscribe(()=>{let t=e.voice!==void 0;t!==i&&(i=t,this._notifySubscribers())});this.endEditCallback=()=>{a(),t()},this._parentId=n,this._sourceId=r.id,this.setText(TV(r)),this.setRole(r.role);let o;r.role===`user`?(o=[...r.attachments??[],...gH(r.content)],this._nonTextPassthrough=[]):(o=r.attachments??[],this._nonTextPassthrough=r.content.filter(e=>e.type!==`text`)),this.setAttachments(o),this.setRunConfig({...e.composer.runConfig})}get parentId(){return this._parentId}get sourceId(){return this._sourceId}async handleSend(e,t){let n=this._nonTextPassthrough.length>0?[...e.content,...this._nonTextPassthrough]:e.content,r=this.runtime.append({...e,content:n,parentId:this._parentId,sourceId:this._sourceId,startRun:t?.startRun});return this.handleCancel(),r}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},TH=class extends wI{_isInitialized=!1;repository=new dH;_voiceMessages=[];_voiceGeneration=0;_cachedMergedMessages=null;_cachedVoiceGeneration=-1;_cachedMergedBase=null;_markVoiceMessagesDirty(){this._voiceGeneration++,this._cachedMergedMessages=null}_getBaseMessages(){return this.repository.getMessages()}_commitVoiceMessage(e){}get messages(){if(this._voiceMessages.length===0)return this._getBaseMessages();let e=this._getBaseMessages();if(this._cachedVoiceGeneration!==this._voiceGeneration||this._cachedMergedBase!==e){let t=new Set(e.map(e=>e.id));this._cachedMergedMessages=[...e,...this._voiceMessages.filter(e=>!t.has(e.id))],this._cachedVoiceGeneration=this._voiceGeneration,this._cachedMergedBase=e}return this._cachedMergedMessages}get state(){let e;for(let t of this.messages)t.role===`assistant`&&(e=t);return e?.metadata.unstable_state??null}composer=new CH(this);_contextProvider;constructor(e){super(),this._contextProvider=e}getModelContext(){return this._contextProvider.getModelContext()}enrichAppendMetadata(e,t=e.parentId){if(e.role!==`user`)return e;let n=this.messages,r=t===null?-1:n.findIndex(e=>e.id===t),i=eB(this.getModelContext().unstable_composerMetadata,n.slice(0,r+1));return i?{...e,metadata:{...e.metadata,custom:{...e.metadata?.custom,...i}}}:e}_editComposers=new Map;getEditComposer(e){return this._editComposers.get(e)}_isVoiceMessage(e){return e!==null&&this._voiceMessages.some(t=>t.id===e)}_resolveAppendParent(e){return this._isVoiceMessage(e)?this._getBaseMessages().at(-1)?.id??null:e}beginEdit(e){if(this.voice)throw Error(`Cannot edit a message while a voice session is connected`);if(this._isVoiceMessage(e))throw Error(`Voice transcript messages cannot be edited`);if(this._editComposers.has(e))throw Error(`Edit already in progress`);this._editComposers.set(e,new wH(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch{let t=this.repository.getMessages(),n=this._voiceMessages.findIndex(t=>t.id===e);return n===-1?void 0:{parentId:n>0?this._voiceMessages[n-1].id:t.at(-1)?.id??null,message:this._voiceMessages[n],index:t.length+n}}}getBranches(e){return this._voiceMessages.some(t=>t.id===e)?[]:this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifyEventSubscribers(e,t){let n=this._eventSubscribers.get(e);n&&AP(n,t,`Thread runtime "${e}"`)}_notifyToolApprovalAnswered(e,t,n,r){this._notifyEventSubscribers(`toolApprovalAnswered`,{messageId:e,toolCallId:t,toolName:n,approved:r})}submitFeedback({messageId:e,type:t,comment:n}){let r=this.adapters?.feedback,i=this.getMessageById(e);if(!i)throw Error(`Message not found: ${e}`);let{message:a,parentId:o}=i,s=n?.trim(),c={type:t,...s?{comment:s}:void 0};if(r?.submit({message:a,...c}),a.role===`assistant`){let t={...a,metadata:{...a.metadata,submittedFeedback:c}},n=this._voiceMessages.findIndex(t=>t.id===e);n===-1?this.repository.addOrUpdateMessage(o,t):(this._voiceMessages[n]=t,this._currentAssistantMsg===a&&(this._currentAssistantMsg=t),this._markVoiceMessagesDirty())}this._notifySubscribers()}_stopSpeaking;speech;speak(e){let t=this.adapters?.speech;if(!t)throw Error(`Speech adapter not configured`);let n=this.getMessageById(e);if(!n)throw Error(`Message not found: ${e}`);let{message:r}=n,i=this._stopSpeaking,a;try{i?.(),a=t.speak(TV(r))}catch(e){if(i&&!this._stopSpeaking)try{this._notifySubscribers()}catch(e){console.error(`[assistant-ui] Speech rollback notification threw`,e)}throw e}let o,s=()=>{this._stopSpeaking=void 0,this.speech=void 0;let e=o;o=void 0,e?.()},c=()=>{if(this._stopSpeaking===c)try{s()}finally{a.cancel()}},l=()=>{this._stopSpeaking===c&&(a.status.type===`ended`?xI([s,()=>this._notifySubscribers()]):(this.speech={messageId:e,status:a.status},this._notifySubscribers()))};this._stopSpeaking=c;try{if(o=a.subscribe(l),this._stopSpeaking!==c){o();return}l()}catch(e){if(this._stopSpeaking===c)try{xI([c,()=>this._notifySubscribers()])}catch(e){console.error(`[assistant-ui] Speech rollback cleanup threw`,e)}throw e}}stopSpeaking(){if(!this._stopSpeaking)throw Error(`No message is being spoken`);xI([this._stopSpeaking,()=>this._notifySubscribers()])}_voiceSession;_voiceUnsubs=[];voice;_voiceVolume=0;_voiceVolumeSubscribers=new Set;getVoiceVolume=()=>this._voiceVolume;subscribeVoiceVolume=e=>(this._voiceVolumeSubscribers.add(e),()=>this._voiceVolumeSubscribers.delete(e));_onVoiceConnected(){}_onVoiceDisconnected(){}_isRunActive(){if(this.isRunning)return!0;let e=this._getBaseMessages().at(-1);return e?.role===`assistant`&&(e.status.type===`running`||e.status.type===`requires-action`)}connectVoice(){let e=this.adapters?.voice;if(!e)throw Error(`Voice adapter not configured`);if(this._isRunActive())throw Error(`Cannot start a voice session while a run is in progress or paused on a pending tool action`);let t=this._voiceSession!==void 0;try{this._disconnectVoice(!1)}catch(e){console.error(`[assistant-ui] Voice cleanup threw before reconnect`,e)}let n;try{n=e.connect({})}catch(e){throw t&&this._voiceSession===void 0&&this._onVoiceDisconnected(),e}this._voiceSession=n;let r=[];this._voiceUnsubs=r;let i=()=>{if(this._voiceSession===n&&this._voiceUnsubs===r)return!1;try{xI(r.splice(0))}catch(e){console.error(`[assistant-ui] Detached voice setup cleanup threw`,e)}return!0};try{let e=`listening`;if(this.voice={status:n.status,isMuted:n.isMuted,mode:e},this._voiceVolume=0,this._notifySubscribers(),i()||(r.push(n.onStatusChange(t=>{this._voiceSession===n&&(t.type===`ended`?(this._finishVoiceAssistantMessage(),this._voiceSession=void 0,this.voice=void 0,this._onVoiceDisconnected()):this.voice={status:t,isMuted:n.isMuted,mode:e},this._notifySubscribers())})),i())||(r.push(n.onModeChange(t=>{e=t,this.voice&&(this.voice={...this.voice,mode:t},this._notifySubscribers())})),i())||(r.push(n.onVolumeChange(e=>{this._voiceVolume=e,AP(this._voiceVolumeSubscribers,void 0,`Voice volume`)})),i()))return;r.push(n.onTranscript(e=>{this._handleVoiceTranscript(e)})),i()||this._onVoiceConnected()}catch(e){if(this._voiceSession===n&&this._voiceUnsubs===r){try{this._disconnectVoice(!1)}catch(e){console.error(`[assistant-ui] Voice rollback cleanup threw`,e)}t&&this._voiceSession===void 0&&this._onVoiceDisconnected()}else i();throw e}}_currentAssistantMsg=null;_handleVoiceTranscript(e){if(this.ensureInitialized(),e.role===`user`){if(this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null,e.isFinal){let t={id:pB(),role:`user`,content:[{type:`text`,text:e.text}],metadata:{modality:`voice`,custom:{}},createdAt:new Date,status:{type:`complete`,reason:`unknown`},attachments:[]};this._voiceMessages.push(t),this._commitVoiceMessage(t),this._markVoiceMessagesDirty(),this._notifySubscribers()}}else{let t=e.isFinal?{type:`complete`,reason:`stop`}:{type:`running`};if(!this._currentAssistantMsg)this._currentAssistantMsg={id:pB(),role:`assistant`,content:[{type:`text`,text:e.text}],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],modality:`voice`,custom:{}},status:t,createdAt:new Date},this._voiceMessages.push(this._currentAssistantMsg);else{let n=this._voiceMessages.indexOf(this._currentAssistantMsg);if(n===-1)return;let r={...this._currentAssistantMsg,content:[{type:`text`,text:e.text}],status:t};this._voiceMessages[n]=r,this._currentAssistantMsg=r}e.isFinal&&(this._commitVoiceMessage(this._currentAssistantMsg),this._currentAssistantMsg=null),this._markVoiceMessagesDirty(),this._notifySubscribers()}}_finishVoiceAssistantMessage(e=!0){let t=this._voiceMessages.at(-1);if(t?.role===`assistant`&&t.status.type===`running`){let n=this._voiceMessages.length-1;this._voiceMessages[n]={...t,status:{type:`complete`,reason:`stop`}},this._commitVoiceMessage(this._voiceMessages[n]),this._currentAssistantMsg=null,this._markVoiceMessagesDirty(),e&&this._notifySubscribers()}}disconnectVoice(){this._disconnectVoice(!0)}_disconnectVoice(e){this._finishVoiceAssistantMessage(!1),this._currentAssistantMsg=null;let t=this._voiceUnsubs.splice(0);this._voiceUnsubs=[];let n=this._voiceSession;this._voiceSession=void 0,this.voice=void 0,this._voiceVolume=0;let r=this.speech&&this._isVoiceMessage(this.speech.messageId)?this._stopSpeaking:void 0;this._voiceMessages=[],this._markVoiceMessagesDirty();try{xI([...t,...r?[r]:[],...n?[()=>n.disconnect()]:[],()=>AP(this._voiceVolumeSubscribers,void 0,`Voice volume`),()=>this._notifySubscribers()])}finally{e&&n&&this._voiceSession===void 0&&this._onVoiceDisconnected()}}muteVoice(){if(!this._voiceSession)throw Error(`No active voice session`);this._voiceSession.mute(),this.voice={...this.voice,isMuted:!0},this._notifySubscribers()}unmuteVoice(){if(!this._voiceSession)throw Error(`No active voice session`);this._voiceSession.unmute(),this.voice={...this.voice,isMuted:!1},this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers(`initialize`,{}))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(cH.fromArray(e??[]))}_eventSubscribers=new Map;unstable_on(e,t){let n=t;if(e===`modelContextUpdate`)return this._contextProvider.subscribe?.(()=>AP([n],{},`Thread runtime "${e}"`))??(()=>{});let r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),e===`initialize`&&this._isInitialized&&queueMicrotask(()=>{r.has(n)&&AP([n],{},`Thread runtime "${e}"`)}),()=>{this._eventSubscribers.get(e)?.delete(n)}}},EH=Symbol.for(`assistant-stream.tool-execution-id`),DH=e=>{try{return JSON.parse(e),!0}catch{return!1}},OH=e=>{try{return JSON.parse(e)}catch{return}},kH=(e,t)=>{let n=OH(e),r=OH(t);return n===void 0||r===void 0?!1:QL(n,r)},AH=e=>e[EH],jH=class{_getTools;_callbacks;_isClientToolCall;_entries=new Map;_humanInput=new Map;_executing=new Set;_discardedToolCallIds=new Set;_settledResolvers=[];_statuses=new Map;_ac=new AbortController;_pendingRestore=!0;_lastSnapshot=null;_isRunning=!1;_controller;_pipelineDead=!1;_pipelineRestartUsed=!1;constructor(e,t,n){this._getTools=e,this._callbacks=t,this._isClientToolCall=n,this._initPipeline()}_initPipeline(){let[e,t]=CR();this._controller=t;let n=Mz(()=>this._getWrappedTools(),()=>this._ac.signal,(e,t,n)=>this._onHumanInput(e,t,n),{onExecutionStart:(e,t,n)=>this._onExecutionStart(e,n),onExecutionEnd:(e,t,n)=>this._onExecutionEnd(e,n)});e.pipeThrough(n).pipeThrough(new ER).pipeTo(new WritableStream({write:e=>{try{if(e.type!==`result`)return;this._handleResultChunk(e)}catch(e){console.error(`[ToolInvocationTracker] result chunk handling failed`,e)}}})).catch(e=>{console.error(`[ToolInvocationTracker] stream pipeline failed; will attempt single restart on next setState`,e),this._pipelineDead=!0})}setState(e){try{if(this._pipelineDead){if(this._pipelineRestartUsed)return;this._pipelineRestartUsed=!0,this._pipelineDead=!1,this._demoteEntriesToRestored(),this._executing.clear(),this._ac=new AbortController,this._initPipeline()}if(this._lastSnapshot&&this._lastSnapshot.messages===e.messages&&this._lastSnapshot.isRunning===e.isRunning&&this._lastSnapshot.isLoading===e.isLoading)return;e.isLoading===!0&&(this._pendingRestore=!0);let t=this._isRunning;this._isRunning=e.isRunning;try{this._processMessages(e.messages)}catch(e){throw this._isRunning=t,e}this._lastSnapshot=e,this._pendingRestore=!1}catch(e){console.error(`[ToolInvocationTracker] setState failed; snapshot dropped`,e)}}reset(){try{this._pendingRestore=!0,this._entries.clear(),this._discardedToolCallIds.clear(),this._lastSnapshot=null,this.abort(),this._statuses.size>0&&(this._statuses=new Map,this._invokeOnStatusesChange())}catch(e){console.error(`[ToolInvocationTracker] reset failed`,e)}}abort(e){try{if(this._humanInput.forEach(({reject:e})=>{try{e(Error(`Tool execution aborted`))}catch{}}),this._humanInput.clear(),e?.discardPending)for(let[e,t]of this._entries)t.controller&&(t.argsComplete||t.hasResult||(this._discardedToolCallIds.add(e),t.skipExecute=!0));if(this._ac.abort(),this._ac=new AbortController,this._executing.size===0)return Promise.resolve();let t=new Set(this._executing);return new Promise(e=>{this._settledResolvers.push({executionIds:t,resolve:e})})}catch(e){return console.error(`[ToolInvocationTracker] abort failed`,e),Promise.resolve()}}resume(e,t){try{let n=this._humanInput.get(e);return n?(this._humanInput.delete(e),this._setStatus(e,{type:`executing`}),n.resolve(t),!0):!1}catch(e){return console.error(`[ToolInvocationTracker] resume failed`,e),!1}}getStatuses(){return this._statuses}_getWrappedTools(){let e=this._getTools();if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=t.execute,r=t.streamCall;return n===void 0&&r===void 0?[e,t]:[e,{...t,...n!==void 0&&{execute:(...[e,t])=>{let r=AH(t),i=this._captureExecution(t.toolCallId,r);return!i||i.skipExecute?new Promise(()=>{}):n(e,t)}},...r!==void 0&&{streamCall:(...[e,t])=>{let n=AH(t);if(this._captureExecution(t.toolCallId,n))return r(e,t)}}}]}))}_captureExecution(e,t){if(t===void 0)return;let n=this._entries.get(e);if(n?.controller)return n.executionId===void 0&&(n.executionId=t),n.executionId===t?n:void 0}_onHumanInput(e,t,n){return new Promise((r,i)=>{let a=this._entries.get(e);if(!a?.controller||a.executionId!==n){i(Error(`Tool execution aborted`));return}let o=this._humanInput.get(e);if(o)try{o.reject(Error(`Human input request was superseded by a new request`))}catch{}this._humanInput.set(e,{executionId:n,resolve:r,reject:i}),this._setStatus(e,{type:`interrupt`,payload:{type:`human`,payload:t}})})}_onExecutionStart(e,t){this._captureExecution(e,t)&&(this._entries.get(e).skipExecute||(this._executing.add(t),this._humanInput.get(e)?.executionId!==t&&this._setStatus(e,{type:`executing`})))}_onExecutionEnd(e,t){if(t===void 0||!this._executing.delete(t))return;this._entries.get(e)?.executionId===t&&this._deleteStatus(e);let n=[];this._settledResolvers.forEach(({executionIds:e,resolve:t})=>{if([...e].some(e=>this._executing.has(e))){n.push({executionIds:e,resolve:t});return}try{t()}catch{}}),this._settledResolvers.length=0,this._settledResolvers.push(...n)}_handleResultChunk(e){let t=e.meta.toolCallId,n=AH(e),r=this._entries.get(t);r&&r.executionId===n&&(r?.hasResult||r.skipExecute||this._invokeOnResult({type:`add-tool-result`,toolCallId:t,toolName:e.meta.toolName,result:e.result,isError:e.isError,...e.artifact!==void 0&&{artifact:e.artifact},...e.modelContent!==void 0&&{modelContent:e.modelContent}}))}_invokeOnResult(e){try{this._callbacks.onResult(e)}catch(e){console.error(`[ToolInvocationTracker] onResult callback threw; result dropped`,e)}}_invokeOnStatusesChange(){try{this._callbacks.onStatusesChange(this._statuses)}catch(e){console.error(`[ToolInvocationTracker] onStatusesChange callback threw; status change not propagated`,e)}}_setStatus(e,t){let n=new Map(this._statuses);n.set(e,t),this._statuses=n,this._invokeOnStatusesChange()}_deleteStatus(e){if(!this._statuses.has(e))return;let t=new Map(this._statuses);t.delete(e),this._statuses=t,this._invokeOnStatusesChange()}_warnProviderOwnedSkip(e,t){}_shouldCloseArgsStream({argsText:e,hasResult:t,clientOwned:n}){return t?!0:DH(e)?n||!this._isRunning:!1}_startActiveEntry(e,t,n,r){let i={toolName:t,controller:this._controller.addToolCallPart({toolName:t,toolCallId:e}),argsText:``,hasResult:!1,skipExecute:n,argsComplete:!1,clientOwned:r};return this._entries.set(e,i),i}_demoteEntriesToRestored(){for(let[e,t]of this._entries)if(t.controller){if(!t.argsComplete&&!t.hasResult){this._entries.delete(e);continue}this._entries.set(e,{toolName:t.toolName,argsText:t.argsText,hasResult:t.hasResult})}}_processArgsText(e,t){if(!e.controller)return;let n=t.result!==void 0;if(t.argsText!==e.argsText){let r=!0;if(e.argsComplete)kH(e.argsText,t.argsText)&&(e.argsText=t.argsText),r=!1;else if(!t.argsText.startsWith(e.argsText)){if(DH(e.argsText)&&DH(t.argsText)&&kH(e.argsText,t.argsText)){let i=this._shouldCloseArgsStream({argsText:t.argsText,hasResult:n,clientOwned:e.clientOwned});i&&e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=i,r=!1}else r=!1}if(r&&e.controller){let r=t.argsText.slice(e.argsText.length);e.controller.argsText.append(r);let i=this._shouldCloseArgsStream({argsText:t.argsText,hasResult:n,clientOwned:e.clientOwned});i&&e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=i}}!e.argsComplete&&e.controller&&this._shouldCloseArgsStream({argsText:e.argsText,hasResult:n,clientOwned:e.clientOwned})&&(e.controller.argsText.close(),e.argsComplete=!0)}_processMessages(e){let t=this._pendingRestore;for(let{part:n}of pH(e)){let e=this._entries.get(n.toolCallId);if(t){e?.controller||this._entries.set(n.toolCallId,{toolName:n.toolName,argsText:n.argsText,hasResult:n.result!==void 0});continue}let r=e;if(n.result!==void 0&&this._discardedToolCallIds.delete(n.toolCallId),r&&!r.controller){if(r.hasResult||(n.argsText===r.argsText||DH(r.argsText)&&DH(n.argsText)&&kH(r.argsText,n.argsText))&&n.result===void 0)continue;this._entries.delete(n.toolCallId),r=void 0}if(!r){let e=this._isClientToolCall?.(n),t=n.result===void 0&&e===!1;t&&this._warnProviderOwnedSkip(n.toolName,n.toolCallId),r=this._startActiveEntry(n.toolCallId,n.toolName,n.result!==void 0||t||this._discardedToolCallIds.has(n.toolCallId),e===!0)}if(n.approval!==void 0&&(r.skipExecute=!0),this._processArgsText(r,n),n.result!==void 0&&!r.hasResult){let{controller:e}=r;if(!e)continue;r.hasResult=!0,r.argsComplete=!0,e.setResponse(new rR({result:n.result,artifact:n.artifact,isError:n.isError,...n.modelContent===void 0?{}:{modelContent:n.modelContent}})),e.close()}}}},MH=Object.freeze([]),NH=(e,t)=>{Promise.resolve(t).catch(t=>{console.error(`[ExternalStoreThreadRuntimeCore] ${e} callback rejected`,t)})},PH=(e,t)=>e&&t[t.length-1]?.role!==`assistant`,FH=class extends TH{_capabilities={switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,delete:!1,reload:!1,refetchThread:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1};get capabilities(){return this._capabilities}_messages;isDisabled;isSendDisabled;get isLoading(){return this._store.isLoading??!1}get isRunning(){return this._hasExecutingTools(this._store)?!0:this._store.isRunning}_getBaseMessages(){return this._messages}get state(){return this._store.state??super.state}get adapters(){return this._store.adapters}get unstable_refetchThread(){if(this._store.onRefetchThread)return()=>this._store.onRefetchThread()}suggestions=[];extras=void 0;_converter=new AB;_pendingDeleteEvictions=new Set;_optimistic=null;_store;_getInitializePromise;__internal_setGetInitializePromise(e){this._getInitializePromise=e}_transformedQueue;_toolInvocations=null;_toolStatuses=new Map;_effectiveIsRunning=!1;_inTrackerUpdate=!1;_pendingRunningRefresh=!1;_runTrackerUpdate(e){this._inTrackerUpdate=!0;try{e()}finally{this._inTrackerUpdate=!1}this._pendingRunningRefresh&&(this._pendingRunningRefresh=!1,this._refreshEffectiveIsRunning())}_refreshEffectiveIsRunning(){let e=this._getEffectiveIsRunning(this._store);this._effectiveIsRunning!==e&&(this._effectiveIsRunning=e,this._notifyEventSubscribers(e?`runStart`:`runEnd`,{}),this._notifySubscribers())}_hasExecutingTools(e){if(e.unstable_enableToolInvocations!==!0||this._toolInvocations===null)return!1;for(let e of this._toolStatuses.values())if(e.type===`executing`)return!0;return!1}_getEffectiveIsRunning(e){return(e.isRunning??!1)||this._hasExecutingTools(e)}beginEdit(e){if(!this._store.onEdit)throw Error(`Runtime does not support editing.`);super.beginEdit(e)}constructor(e,t){super(e),this.__internal_setAdapter(t)}__internal_setAdapter(e){this._store!==e&&this._updateStoreSnapshot(e)}_updateStoreSnapshot(e){let t=this._effectiveIsRunning;this.isDisabled=e.isDisabled??!1,this.isSendDisabled=e.isSendDisabled??!1;let n=this._store;this._store=e;let r=this._getEffectiveIsRunning(e),i=e.unstable_messageRepositoryInstance,a=i!==void 0&&i!==this.repository;a&&(this.repository=i,this._pendingDeleteEvictions.clear()),n?.queue!==e.queue&&(this._transformedQueue=void 0,e.queue?.__internal_setDispatchTransform?.(e=>{let t=this.messages.at(-1)?.id??null;return this.enrichAppendMetadata({...e,parentId:t},t)}),e.queue?.__internal_setDispatchTransform&&(this._transformedQueue=e.queue)),this.extras!==e.extras&&(this.extras=e.extras);let o=e.suggestions??MH;IF(this.suggestions,o)||(this.suggestions=o);let s={switchToBranch:this._store.setMessages!==void 0,switchBranchDuringRun:!1,edit:this._store.onEdit!==void 0,delete:this._store.onDelete!==void 0||this._store.setMessages!==void 0,reload:this._store.onReload!==void 0,refetchThread:this._store.onRefetchThread!==void 0,cancel:this._store.onCancel!==void 0,speech:this._store.adapters?.speech!==void 0,dictation:this._store.adapters?.dictation!==void 0,voice:this._store.adapters?.voice!==void 0,unstable_copy:this._store.unstable_capabilities?.copy!==!1,attachments:!!this._store.adapters?.attachments,feedback:!!this._store.adapters?.feedback,queue:this._store.queue!==void 0};IF(this._capabilities,s)||(this._capabilities=s);let c;if(e.messageRepository){if(n&&!a&&n.isRunning===e.isRunning&&n.messageRepository===e.messageRepository&&t===r){this._notifySubscribers();return}let i=e.messageRepository.messages,o=e.messageRepository.headId??i.at(-1)?.message.id??null;if(n&&!a&&n.messageRepository===e.messageRepository)this.repository.resetHead(o),c=this.repository.getMessages();else{let e=new Set(i.map(({message:e})=>e.id));for(let{message:e,parentId:t}of i)this.repository.addOrUpdateMessage(t,e);for(let{message:t}of this.repository.export().messages)e.has(t.id)||this.repository.deleteMessage(t.id);this._pendingDeleteEvictions.clear(),this.repository.resetHead(o),c=this.repository.getMessages()}}else if(e.messages){if(n){if(n.convertMessage!==e.convertMessage)this._converter=new AB;else if(!a&&n.isRunning===e.isRunning&&n.messages===e.messages&&t===r){this._notifySubscribers();return}}c=e.convertMessage?this._converter.convertMessages(e.messages,(t,n,i)=>{if(!e.convertMessage)return n;let a=i===(e.messages?.length??0)-1,o=`${fB}${i}`;if(t&&(t.role!==`assistant`||!EB(t.status)||t.status===kB(t.content,a,r))){if(t.id.startsWith(`__external_store_fallback_`)&&t.id!==o){let e={...t,id:o};return uB(e,n),e}return t}let s=e.convertMessage(n,i),c=gB(s,o,kB(s.content,a,r));return uB(c,n),c}):e.messages;let i=new Set,o=[];for(let e=c.length-1;e>=0;e--){let t=c[e];if(i.has(t.id)){console.warn(`ExternalStoreThreadRuntimeCore: duplicate message id "${t.id}" in the provided messages array; keeping the last occurrence.`);continue}i.add(t.id),o.push(t)}o.length!==c.length&&(c=o.reverse());for(let e=0;e<c.length;e++){let t=c[e],n=c[e-1];this.repository.addOrUpdateMessage(n?.id??null,t)}if(this._pendingDeleteEvictions.size>0){let e=new Set(c.map(e=>e.id));for(let t of this._pendingDeleteEvictions)if(this._pendingDeleteEvictions.delete(t),!e.has(t)){try{this.repository.getMessage(t)}catch{continue}this.repository.deleteMessage(t)}}}else throw Error(`ExternalStoreAdapter must provide either 'messages' or 'messageRepository'`);c.length>0&&this.ensureInitialized(),this._effectiveIsRunning=r,t!==r&&(r?this._notifyEventSubscribers(`runStart`,{}):this._notifyEventSubscribers(`runEnd`,{}));let l=null;if(PH(r,c)){let e=c.at(-1)?.id??null;this._optimistic?.parentId!==e&&(this._optimistic={id:pB(),parentId:e}),l=this._optimistic.id,this.repository.addOrUpdateMessage(e,gB({role:`assistant`,content:[],metadata:{isOptimistic:!0}},l,{type:`running`}))}l===null&&(this._optimistic=null),this.repository.resetHead(l??c.at(-1)?.id??null);let u=this.repository.getMessages();if((!this._messages||!jB(this._messages,u))&&(this._messages=u),this._voiceMessages.length>0){let e=new Set(this._messages.map(e=>e.id)),t=this._voiceMessages.filter(t=>!e.has(t.id));t.length!==this._voiceMessages.length&&(this._voiceMessages=t,this._markVoiceMessagesDirty())}a&&this._runTrackerUpdate(()=>this._toolInvocations?.reset()),this._runTrackerUpdate(()=>this._driveToolInvocations()),this._notifySubscribers()}_driveToolInvocations(){if(!this._store.unstable_enableToolInvocations){this._toolInvocations&&(this._toolInvocations.reset(),this._toolInvocations=null,this._toolStatuses=new Map,this._store.setToolStatuses?.({}));return}this._toolInvocations||=new jH(()=>this.getModelContext().tools,{onResult:e=>{try{let t=this._findMessageIdForToolCall(e.toolCallId);if(t===void 0)return;NH(`onAddToolResult`,this._store.onAddToolResult?.({messageId:t,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError,...e.artifact!==void 0&&{artifact:e.artifact},...e.modelContent!==void 0&&{modelContent:e.modelContent}}))}catch(e){console.error(`[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed`,e)}},onStatusesChange:e=>{let t=this._hasExecutingTools(this._store);this._toolStatuses=e;try{this._store.setToolStatuses?.(Object.fromEntries(e))}finally{t!==this._hasExecutingTools(this._store)&&(this._inTrackerUpdate?this._pendingRunningRefresh=!0:this._updateStoreSnapshot(this._store))}}},e=>this._store.unstable_isClientToolCall?.(e)),this._toolInvocations.setState({messages:this._messages,isRunning:this._getEffectiveIsRunning(this._store),...this._store.isLoading!==void 0&&{isLoading:this._store.isLoading}})}_toolCallToMessageId=new Map;_messagesForToolCallIndex=null;_findMessageIdForToolCall(e){if(this._messagesForToolCallIndex!==this._messages){this._toolCallToMessageId.clear();for(let{part:e,messageId:t}of pH(this._messages))this._toolCallToMessageId.set(e.toolCallId,t);this._messagesForToolCallIndex=this._messages}return this._toolCallToMessageId.get(e)}switchToBranch(e){if(!this._store.setMessages)throw Error(`Runtime does not support switching branches.`);if(this._getEffectiveIsRunning(this._store))return;let t=this._store.unstable_onBranchChange,n=t?this.repository.canonicalHeadId:null;this.repository.switchToBranch(e),this._pendingDeleteEvictions.clear(),this.updateMessages(this.repository.getMessages()),t&&this._notifyBranchChange(n,t)}_notifyBranchChange(e,t){let n=this.repository.canonicalHeadId;n!==e&&t({headId:n,visibleMessageIds:this.repository.getMessages().map(e=>e.id)})}async append(e){let t={...e,parentId:this._resolveAppendParent(e.parentId)};if(this.voice)throw Error(`Cannot send a text message while a voice session is connected`);if(this._isVoiceMessage(t.sourceId))throw Error(`Voice transcript messages cannot be edited`);let n=t.sourceId!=null||t.parentId!==(this._getBaseMessages().at(-1)?.id??null);t=!n&&this._store.queue&&this._store.queue===this._transformedQueue?t:this.enrichAppendMetadata(t);let r=ZV(this);this.ensureInitialized();let i=this._getInitializePromise?.();if(!n&&this._store.queue){if(i&&await i,!QV(this,r))return;t.steer??this._getEffectiveIsRunning(this._store)?this._store.queue.steer(t):this._store.queue.enqueue(t);return}if(i?.catch(()=>{}),(t.startRun??t.role===`user`)&&await this._toolInvocations?.abort({discardPending:!0}),QV(this,r)){if(n){if(!this._store.onEdit)throw Error(`Runtime does not support editing messages.`);this._pendingDeleteEvictions.clear(),await this._store.onEdit(t)}else await this._store.onNew(t)}}_commitVoiceMessage(e){this._store.onVoiceTranscript?.(e)}async deleteMessage(e){if(this._store.onDelete){this.repository.getMessages().some(t=>t.id===e)&&this._pendingDeleteEvictions.add(e);try{await this._store.onDelete(e)}catch(t){throw this._pendingDeleteEvictions.delete(e),t}return}if(!this._store.setMessages)throw Error(`Runtime does not support deleting messages.`);this._getEffectiveIsRunning(this._store)&&await this._toolInvocations?.abort();let t=this.repository.getMessages();if(t.findIndex(t=>t.id===e)===-1)throw Error(`Message not found.`);this._pendingDeleteEvictions.clear(),this.updateMessages(t.filter(t=>t.id!==e)),this._evictDeletedMessage(e)}_evictDeletedMessage(e){if(!e.startsWith(`__external_store_fallback_`)){try{this.repository.getMessage(e)}catch{return}this.repository.deleteMessage(e),this._publishRepositoryMessages()}}_publishRepositoryMessages(){let e=this.repository.getMessages();jB(this._messages,e)||(this._messages=e),this._notifySubscribers()}getQueueItems(){return this._store?.queue?.items??fH}getSteerQueueItems(){return this._store?.queue?.steerItems??fH}moveQueueItem(e,t){this._store?.queue?.move(e,t)}removeQueueItem(e){this._store?.queue?.remove(e)}async startRun(e){if(!this._store.onReload)throw Error(`Runtime does not support reloading messages.`);if(this.voice)throw Error(`Cannot start a run while a voice session is connected`);if(this._isVoiceMessage(e.sourceId))throw Error(`Voice transcript messages cannot be reloaded`);this._pendingDeleteEvictions.clear(),await this._toolInvocations?.abort({discardPending:!0}),await this._store.onReload(e.parentId,e)}async resumeRun(e){if(!this._store.onResume)throw Error(`Runtime does not support resuming runs.`);if(this.voice)throw Error(`Cannot start a run while a voice session is connected`);if(this._isVoiceMessage(e.sourceId))throw Error(`Voice transcript messages cannot be reloaded`);await this._store.onResume(e)}exportExternalState(){if(!this._store.onExportExternalState)throw Error(`Runtime does not support exporting external states.`);return this._store.onExportExternalState()}importExternalState(e){if(!this._store.onLoadExternalState)throw Error(`Runtime does not support importing external states.`);this._runTrackerUpdate(()=>this._toolInvocations?.reset()),this._store.onLoadExternalState(e)}unstable_notifySessionReset(){this._runTrackerUpdate(()=>this._toolInvocations?.reset()),this._store.queue?.__internal_notifyCancelled?.()}cancelRun(){if(!this._store.onCancel)throw Error(`Runtime does not support cancelling runs.`);let e=ZV(this);this._toolInvocations?.abort({discardPending:!0}),this._store.queue?.__internal_notifyCancelled?.(),NH(`onCancel`,this._store.onCancel()),this.dropEmptyOptimisticHead();let t=this.repository.getMessages(),n=t[t.length-1],r=this._store.setMessages!==void 0&&n?.role===`user`&&n.id===t.at(-1)?.id&&n.content.every(e=>e.type===`text`)?n:void 0,i;if(r){let e={text:TV(r),attachments:r.attachments,quote:r.metadata.custom.quote};this.composer.restoreDraft(e)&&(this.repository.deleteMessage(r.id),i={id:r.id,draft:e})}this._publishRepositoryMessages(),setTimeout(()=>{if(QV(this,e)){if(this.dropEmptyOptimisticHead(),i){let e=this.repository.getMessages();e.at(-1)?.id===i.id?this.repository.deleteMessage(i.id):e.some(e=>e.id===i.id)&&this.composer.retractDraft(i.draft)}this._publishRepositoryMessages(),this.updateMessages(this._messages)}},0)}dropEmptyOptimisticHead(){let e=this.repository.getMessages().at(-1);e&&e.metadata.isOptimistic&&e.content.length===0&&this.repository.deleteMessage(e.id)}addToolResult(e){if(!this._store.onAddToolResult)throw Error(`Runtime does not support tool results.`);NH(`onAddToolResult`,this._store.onAddToolResult(e))}resumeToolCall(e){if(!(this._toolInvocations?.resume(e.toolCallId,e.payload)??!1)){if(this._store.onResumeToolCall){this._store.onResumeToolCall(e);return}throw Error(`Tool call ${e.toolCallId} is not waiting for resume.`)}}respondToToolApproval(e){if(!this._store.onRespondToToolApproval)throw Error(`Runtime does not support tool approvals.`);let t=this.messages.findLast(t=>t.role===`assistant`&&t.content.some(t=>t.type===`tool-call`&&t.approval?.id===e.approvalId)),n=t?.content.find(t=>t.type===`tool-call`&&t.approval?.id===e.approvalId);try{return Promise.resolve(this._store.onRespondToToolApproval(e)).then(()=>{t&&n?.type===`tool-call`&&this._notifyToolApprovalAnswered(t.id,n.toolCallId,n.toolName,e.approved)})}catch(e){return Promise.reject(e)}}reset(e){let t=new dH;t.import(cH.fromArray(e??[])),this.updateMessages(t.getMessages())}import(e){super.import(e),this._store.onImport&&this._store.onImport(this.repository.getMessages())}updateMessages=e=>{this._store.convertMessage===void 0?this._store.setMessages?.(e):this._store.setMessages?.(e.flatMap(dB))}},IH=e=>e.adapters?.threadList??{},LH=class extends eH{threads;constructor(e){super(),this.threads=new sH(IH(e),()=>new FH(this._contextProvider,e))}setAdapter(e){this.threads.__internal_setAdapter(IH(e)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(e)}},RH=e=>{let t=J(21),{modelContext:n,feedback:r}=iB()??{},i;bb0:{if(!r||e.adapters?.feedback){i=e;break bb0}let n;t[0]!==r||t[1]!==e.adapters?(n={...e.adapters,feedback:r},t[0]=r,t[1]=e.adapters,t[2]=n):n=t[2];let a;t[3]!==e||t[4]!==n?(a={...e,adapters:n},t[3]=e,t[4]=n,t[5]=a):a=t[5],i=a}let a=i,o;t[6]===a?o=t[7]:(o=()=>new LH(a),t[6]=a,t[7]=o);let[s]=fN(o),c;t[8]===s.threads?c=t[9]:(c=()=>()=>{$V(s.threads.getMainThreadRuntimeCore())},t[8]=s.threads,t[9]=c);let l;t[10]===s?l=t[11]:(l=[s],t[10]=s,t[11]=l),X(c,l);let u;t[12]!==a||t[13]!==s?(u=()=>{s.setAdapter(a)},t[12]=a,t[13]=s,t[14]=u):u=t[14],X(u);let d,f;t[15]!==n||t[16]!==s?(d=()=>{if(n)return s.registerModelContextProvider(n)},f=[n,s],t[15]=n,t[16]=s,t[17]=d,t[18]=f):(d=t[17],f=t[18]),X(d,f);let p;return t[19]===s?p=t[20]:(p=new YV(s),t[19]=s,t[20]=p),p},zH=e=>e.status?.type!==`running`,BH=async(e,t)=>{let n=lz.fromAssistantStream(e);for await(let e of n){let n=e.parts.filter(e=>e.type===`text`)[0]?.text;n?.trim()&&await t(n)}},VH=(e,t)=>{let n=()=>void t.generateTitle({automatic:!0}).catch(e=>{qI(e)||console.error(`[assistant-ui] Thread title generation failed`,e)}),r=()=>e.getState().messages.some(zH);if(r())return n(),()=>{};let i=e.subscribe(()=>{r()&&(i(),n())});return i},HH=({threadId:e,generation:t,runtimeHook:n,publish:r,itemRuntime:i})=>{let a=n(),o=a?.thread?.__internal_threadBinding,s=hN(()=>{o&&r(e,o.getState(),t)},[e,t,o,r]),c=Y(!1);c.current||s(),X(()=>{if(o)return c.current=!0,s(),o.outerSubscribe(s)},[o,s]);let l=Y(void 0),u=Y(!1),d=Y(void 0),f=Y(!1),p=_N(()=>{if(u.current||i.getState().status!==`new`)return;u.current=!0;let e=i.initialize();l.current=e,e.then(()=>{f.current&&(d.current?.(),d.current=VH(a.thread,i))},()=>{l.current===e&&(l.current=void 0,u.current=!1)})}),m=_N(()=>(p(),l.current));return X(()=>{if(!o)return;let e=o.getState(),t=e.__internal_setGetInitializePromise;typeof t==`function`&&t.call(e,m)},[o]),X(()=>{if(!a?.threads?.main)return;u.current=!1,f.current=!0;let e=a.threads.main.unstable_on(`initialize`,p);return()=>{f.current=!1,e(),d.current?.(),d.current=void 0}},[a]),a},UH=jN(({threadId:e,generation:t,parentList:n,runtimeHook:r,parentClient:i,adapters:a,publish:o,destroySignal:s})=>{let c=mN(()=>new UV(new DI({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>{let t=n.getItemById(e);return t?{id:t.id,remoteId:t.remoteId,externalId:t.externalId,title:t.title,lastMessageAt:t.lastMessageAt,custom:t.custom,status:t.status,isMain:t.id===n.mainThreadId,isRunning:n.unstable_isThreadRunning?.(t.id)??!1}:bI},subscribe:e=>n.subscribe(e)}),n),[n,e]),{client:l}=iI(i,{threadListItem:kL({runtime:c})});return EF(s,function(){return iF(l,function(){return rB(a,function(){return HH({threadId:e,generation:t,runtimeHook:r,publish:o,itemRuntime:c})})})})}),WH=[`runStart`,`runEnd`,`initialize`,`modelContextUpdate`],GH=e=>{let t=J(3),{detectorRef:n}=e,r,i;return t[0]===n?(r=t[1],i=t[2]):(r=()=>{n.current=!0},i=[n],t[0]=n,t[1]=r,t[2]=i),gN(r,i),null},KH=class extends wI{runtimeHook;adapterStore=new TI({defaultAdapters:null,threadAdapters:new Map});hostStore=new TI({threads:[],hookEpoch:0});pendingThreadAdapters=new Map;instances=new Map;nextGeneration=0;parent;constructor(e,t){super(),this.parent=t,this.runtimeHook=e}_whenRuntimeAttached(e){return new Promise((t,n)=>{let r=()=>{let r=this.instances.get(e);if(!r)i(),n(Error(`Thread was deleted before runtime was started`));else if(!r.runtime||r.publishedGeneration!==r.generation)return;else i(),t(r.runtime)},i=this.subscribe(r);r()})}startThreadRuntime(e){if(!this.instances.has(e)){let t=this.nextGeneration++;this.instances.set(e,{generation:t,isRunning:!1,destroy:new AbortController}),this._syncHostThreads()}return this._whenRuntimeAttached(e)}__internal_restartThreadRuntime(e){let t=this.instances.get(e);return t?(t.runtime&&$V(t.runtime),t.unsubscribeRunning?.(),t.unsubscribeRunning=void 0,t.destroy.abort(),t.destroy=new AbortController,t.generation=this.nextGeneration++,this._syncHostThreads(),this._notifySubscribers(),this._whenRuntimeAttached(e)):this.startThreadRuntime(e)}getThreadRuntimeCore(e){let t=this.instances.get(e);if(t)return t.runtime}__internal_isThreadRunning(e){return this.instances.get(e)?.isRunning??!1}runningSubscribers=new Set;__internal_subscribeRunningChanged(e){return this.runningSubscribers.add(e),()=>this.runningSubscribers.delete(e)}threadEventSubscribers=new Set;__internal_subscribeThreadEvents(e){return this.threadEventSubscribers.add(e),()=>this.threadEventSubscribers.delete(e)}_publish=(e,t,n)=>{this._publishThreadRuntime(e,t,n)};_publishThreadRuntime(e,t,n){let r=this.instances.get(e);if(!r||r.generation!==n)return;let i=r.runtime;r.runtime=t,r.publishedGeneration=n,i!==t&&this._trackRunning(e,r),this._notifySubscribers(),i!==void 0&&i!==t&&xI(this.replacedSubscribers)}replacedSubscribers=new Set;__internal_subscribeRuntimeReplaced(e){return this.replacedSubscribers.add(e),()=>this.replacedSubscribers.delete(e)}_trackRunning(e,t){t.unsubscribeRunning?.();let n=t.runtime;if(!n){t.unsubscribeRunning=void 0,this._setRunning(t,!1);return}this._setRunning(t,LV(n));let r=[n.subscribe(()=>{this._setRunning(t,LV(n))}),...WH.map(t=>n.unstable_on(t,()=>{AP(this.threadEventSubscribers,{threadId:e,type:t},`Thread event "${t}"`)}))];t.unsubscribeRunning=()=>{for(let e of r)e()}}_setRunning(e,t){e.isRunning!==t&&(e.isRunning=t,xI(this.runningSubscribers))}stopThreadRuntime(e){let t=this.instances.get(e);t?.runtime&&$V(t.runtime),t?.unsubscribeRunning?.(),t?.destroy.abort(),this.instances.delete(e),this.pendingThreadAdapters.delete(e),this._syncHostThreads(),this._notifySubscribers()}setRuntimeHook(e){if(this.runtimeHook===e)return;this.runtimeHook=e;let t=this.hostStore.getState();this.hostStore.setState({...t,hookEpoch:t.hookEpoch+1})}__internal_setDefaultAdapters(e){let t=this.adapterStore.getState();t.defaultAdapters!==e&&this.adapterStore.setState({...t,defaultAdapters:e})}__internal_setThreadAdapters(e,t){let n=this.adapterStore.getState(),r=new Map(n.threadAdapters);t===null?r.delete(e):r.set(e,t),this.adapterStore.setState({...n,threadAdapters:r})}__internal_dispose(){for(let e of[...this.instances.keys()])this.stopThreadRuntime(e)}_syncHostThreads(){let e=this.hostStore.getState();this.hostStore.setState({...e,threads:Array.from(this.instances.entries()).map(([e,{generation:t,destroy:n}])=>({id:e,generation:t,destroySignal:n.signal}))})}_threadElements(e,{threads:t,hookEpoch:n},r){let i=this.runtimeHook;return t.map(({id:t,generation:a,destroySignal:o})=>{let s=this.pendingThreadAdapters.has(t)?this.pendingThreadAdapters.get(t):r.threadAdapters.get(t)??r.defaultAdapters;return MN(`${t}:${a}:${n}`,UH({threadId:t,generation:a,parentList:this.parent,runtimeHook:i,parentClient:e,adapters:s,publish:this._publish,destroySignal:o}))})}__internal_useHost(e){let t=GI(this.hostStore),n=GI(this.adapterStore);return CP(this._threadElements(e,t,n))}__internal_RenderThreadRuntimes=({provider:e})=>(GI(this.hostStore),Array.from(this.instances.entries()).map(([t,{generation:n}])=>(0,b.jsx)(this._OuterActiveThreadProvider,{threadId:t,provider:e},`${t}:${n}`)));__internal_Host=({parentClient:e})=>{let t=GI(this.hostStore),n=GI(this.adapterStore),r=this._threadElements(e,t,n),{effects:i}=TP(function(){return CP(r)});return gN(i),null};_OuterActiveThreadProvider=CN(({threadId:e,provider:t})=>{let n=mN(()=>new JV(this.parent).getItemById(e),[e]),r=Y(!1);return X(()=>{},[t]),(0,b.jsx)(YB,{runtime:n,children:(0,b.jsx)(t,{children:(0,b.jsx)(this._AdapterSink,{threadId:e,detectorRef:r})})})});_AdapterSink=({threadId:e,detectorRef:t})=>{let n=iB();return this.pendingThreadAdapters.set(e,n),gN(()=>(this.__internal_setThreadAdapters(e,n),()=>{this.pendingThreadAdapters.get(e)===n&&this.pendingThreadAdapters.delete(e),this.__internal_setThreadAdapters(e,null)}),[e,n]),(0,b.jsx)(GH,{detectorRef:t})}};function qH(e,t,n,...r){if(!n)return;let i=n=>{try{console.error(`[${e}] ${t} callback threw an error`,n)}catch{}};try{let e=n(...r);if(e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`)return Promise.resolve(e).then(()=>void 0,e=>i(e))}catch(e){i(e)}}var JH=(e,t,n)=>n.reduce((e,n)=>n?.(e,t)??e,e),YH=class extends wI{_pendingTransforms=[];_completedOptimistics=[];_nextTransformOrder=0;_epoch=0;_baseValue;_cachedValue;constructor(e){super(),this._baseValue=e,this._cachedValue=e}_updateState(){let e=[...this._pendingTransforms.map(e=>({order:e.order,apply:t=>JH(t,e.task,[e.loading,e.optimistic])})),...this._completedOptimistics.map(({order:e,optimistic:t})=>({order:e,apply:t}))].sort((e,t)=>e.order-t.order);this._cachedValue=e.reduce((e,t)=>t.apply(e),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(e){this._baseValue=e,this._updateState()}reset(e){this._epoch++,this._pendingTransforms.length=0,this._completedOptimistics.length=0,this._baseValue=e,this._cachedValue=e,this._notifySubscribers()}async optimisticUpdate(e){let t=this._epoch,n=this._nextTransformOrder++,r=e.execute(),i={...e,order:n,task:r};try{this._pendingTransforms.push(i),this._updateState();let n=await r;if(t!==this._epoch)return n;this._baseValue=JH(this._baseValue,n,[e.optimistic,e.then]);for(let t of this._completedOptimistics)(e.then||t.order>i.order)&&(this._baseValue=t.optimistic(this._baseValue));return e.optimistic&&(this._completedOptimistics.push({order:i.order,optimistic:e.optimistic}),this._completedOptimistics.sort((e,t)=>e.order-t.order)),n}finally{let e=this._pendingTransforms.indexOf(i);e>-1&&this._pendingTransforms.splice(e,1),this._pendingTransforms.length===0&&(this._completedOptimistics.length=0),this._updateState()}}},XH=Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),ZH=new class extends VV{get error(){return XH}messages=[];composer=BV(XH,!0);isLoading=!0;getMessageById(){}getBranches(){return[]}export(){return{messages:[]}}subscribe(){return()=>{}}waitForUpdate(){return Promise.reject(XH)}};function QH(e){return e}var $H=`__LOCALID_`,eU=e=>e||void 0,tU=(e,t)=>{let n=[...t.threadIds],r=[...t.archivedThreadIds],i=mM(t.threadIdMap),a=mM(t.threadData),o=new Set([...n,...r]);for(let t of e){switch(t.status){case`regular`:case`archived`:break;default:{let e=t.status;throw Error(`Unsupported state: ${e}`)}}let e=i[t.remoteId],s=e===void 0?void 0:a[e],c=s?.id??t.remoteId,l=e??QH(c),u=s!==void 0&&s.status!==`new`?s.initializeTask:void 0;o.has(c)?s!==void 0&&s.status!==t.status&&(t.status===`regular`?(r=r.filter(e=>e!==c),n.push(c)):(n=n.filter(e=>e!==c),r.push(c))):(o.add(c),t.status===`regular`?n.push(c):r.push(c)),i[c]=l,i[t.remoteId]=l,a[l]={...s?.localOrigin===!0?{localOrigin:!0}:{},id:c,remoteId:t.remoteId,externalId:t.externalId,status:t.status,title:t.title,lastMessageAt:t.lastMessageAt,custom:t.custom,initializeTask:u??Promise.resolve({remoteId:t.remoteId,externalId:t.externalId})}}return{threadIds:n,archivedThreadIds:r,threadIdMap:i,threadData:a}},nU=()=>({isLoading:!0,loadError:void 0,isLoadingMore:!1,cursor:void 0,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:mM(),threadData:mM()}),rU=e=>{let t;do t=`${$H}${pB()}`;while(e.threadIdMap[t]);let n=QH(t);return{id:t,state:{...e,newThreadId:t,threadIdMap:mM(e.threadIdMap,{[t]:n}),threadData:mM(e.threadData,{[n]:{status:`new`,id:t,remoteId:void 0,externalId:void 0,title:void 0,custom:void 0,localOrigin:!0}})}}},iU=(e,t,n)=>{let r=new Set(e.threadIds),i=new Set(e.archivedThreadIds),a=[],o=[],s=(e,t)=>e.has(t.id)||t.remoteId!==void 0&&e.has(t.remoteId);for(let t of Object.values(e.threadData)){let e=n.get(t.id);(e===void 0||e===`new`)&&(e!==void 0||t.localOrigin===!0)&&(t.status===`regular`&&!s(r,t)?(a.push(t),r.add(t.id)):t.status===`archived`&&!s(i,t)&&(o.push(t),i.add(t.id)))}if(a.length===0&&o.length===0)return e;let c=(e,t)=>{let n=e.indexOf(t.id);if(n!==-1)return n;let r=t.remoteId===void 0?-1:e.indexOf(t.remoteId);return r===-1?2**53-1:r};return a.sort((e,n)=>c(t.threadIds,e)-c(t.threadIds,n)),o.sort((e,n)=>c(t.archivedThreadIds,e)-c(t.archivedThreadIds,n)),{...e,threadIds:[...a.map(e=>e.id),...e.threadIds],archivedThreadIds:[...o.map(e=>e.id),...e.archivedThreadIds]}},aU=e=>new Map(Object.values(e.threadData).map(e=>[e.id,e.status])),oU=(e,t)=>{let n=Object.hasOwn(e.threadIdMap,t)?e.threadIdMap[t]:void 0;if(n!==void 0)return Object.hasOwn(e.threadData,n)?e.threadData[n]:void 0},sU=(e,t,n,r,i)=>{let a=QH(t),o=Object.hasOwn(e.threadData,a)?e.threadData[a]:void 0;if(!o)return{state:e,removedMappingId:void 0,survivorMappingId:a};let s=Object.hasOwn(e.threadIdMap,n)?e.threadIdMap[n]:void 0,c=s!==void 0&&s!==a&&Object.hasOwn(e.threadData,s)?e.threadData[s]:void 0,l=s!==void 0&&c!==void 0?{mappingId:s,data:c}:void 0,u=i!==void 0&&Object.hasOwn(e.threadIdMap,i)?e.threadIdMap[i]:void 0,d=l!==void 0&&u===l.mappingId?l.mappingId:a,f=l===void 0?void 0:d===a?l.mappingId:a,p=r??l?.data.externalId,m=mM(e.threadData);f!==void 0&&delete m[f];let h={...o,id:d,initializeTask:Promise.resolve({remoteId:n,externalId:p}),remoteId:n,externalId:p};m[d]={...l?.data,...h,title:o.title??l?.data.title,lastMessageAt:(`lastMessageAt`in o?o.lastMessageAt:void 0)??(l&&`lastMessageAt`in l.data?l.data.lastMessageAt:void 0),custom:o.custom??l?.data.custom};let g=mM(e.threadIdMap);if(f!==void 0)for(let[e,t]of Object.entries(g))t===f&&(g[e]=d);g[t]=d,g[n]=d;let _=e=>l===void 0?e:e.filter(e=>e!==l.data.id).map(e=>e===o.id?d:e);return{state:{...e,threadIds:_(e.threadIds),archivedThreadIds:_(e.archivedThreadIds),threadIdMap:g,threadData:m},removedMappingId:f,survivorMappingId:d}},cU=(e,t,n,r)=>{let i=oU(e,t);if(!i)return e;let{id:a,status:o}=i;if(o===n)return e;let s;if(n!==`deleted`){if(i.status===`new`){if(r===void 0)return e;s={...i,initializeTask:r,status:n}}else s={...i,status:n}}let c={...e};switch(o){case`new`:c.newThreadId=void 0;break;case`regular`:c.threadIds=c.threadIds.filter(e=>e!==a);break;case`archived`:c.archivedThreadIds=c.archivedThreadIds.filter(e=>e!==a);break;default:throw Error(`Unsupported state: ${o}`)}switch(n){case`regular`:c.threadIds=[a,...c.threadIds];break;case`archived`:c.archivedThreadIds=[a,...c.archivedThreadIds];break;case`deleted`:{let n=e.threadIdMap[t],r=mM(c.threadData);delete r[n],c.threadData=r;let i=mM(c.threadIdMap);for(let[e,t]of Object.entries(i))t===n&&delete i[e];c.threadIdMap=i;break}default:throw Error(`Unsupported state: ${n}`)}return s!==void 0&&(c.threadData={...c.threadData,[a]:s}),c},lU=(e,t,n)=>cU(e,t,n,void 0),uU=(e,t,n)=>cU(e,t,`regular`,n),dU=class extends Error{[KI]=!0;constructor(){super(`Thread list adapter changed while an operation was pending.`),this.name=`ThreadListAdapterChangedError`}};function fU(e,t){let n=e.get(t);return n===void 0&&(n={generations:new Set,pendingClaim:null,inFlightClaims:new Set,manualTitle:void 0,latestExplicit:null,nextOrder:0},e.set(t,n)),n}function pU(e,t,n){n.generations.size===0&&n.pendingClaim===null&&n.inFlightClaims.size===0&&n.manualTitle===void 0&&e.get(t)===n&&e.delete(t)}function mU(e,t){return!t.superseded&&(e.latestExplicit?.order??0)<=t.order}function hU(e,t){return(e.latestExplicit?.order??0)<t.order}function gU(e,t,n){let r=fU(e,t),i,a=new Promise(e=>{i=e}),o={title:n,order:++r.nextOrder,settled:a,settle:i};r.pendingClaim=o,r.inFlightClaims.add(o);for(let e of r.generations)e.order<o.order&&(e.claim=o);return o}function _U(e,t,n,r){n.settle(r);let i=e.get(t);i!==void 0&&(i.inFlightClaims.delete(n),i.pendingClaim===n&&(i.pendingClaim=null,r&&(i.manualTitle=n.title)),pU(e,t,i))}function vU(e,t,n){let r=n.manualTitle;if(r!==void 0)return n.manualTitle=void 0,pU(e,t,n),r}function yU(e,t){e.delete(t)}function bU(e,t,n){let r=fU(e,t);if(n&&r.pendingClaim===null&&vU(e,t,r)!==void 0)return null;let i,a=new Promise(e=>{i=e}),o={automatic:n,order:++r.nextOrder,claim:n?r.pendingClaim:null,beforeGenerationClaims:n?[]:[...r.inFlightClaims],superseded:!1,persisted:a,settlePersisted:i};if(!n){r.pendingClaim=null,r.manualTitle=void 0,r.latestExplicit=o;for(let e of r.generations)e.automatic&&(e.superseded=!0)}return r.generations.add(o),o}async function xU({states:e,threadId:t,automatic:n,generate:r,rename:i,applyTitle:a}){let o=fU(e,t),s=bU(e,t,n);if(s===null)return;let c,l=s.order,u=async e=>{let t=await e.settled;if(s.claim===e)return t||(s.claim=null,o.pendingClaim===e&&(o.pendingClaim=null)),t},d=()=>n&&vU(e,t,o)!==void 0,f=async()=>{if(c!==void 0)for(;;){let e=s.claim;if(e!==null&&e.order>l&&hU(o,e)){await u(e)===!0&&(c=e.title,l=e.order,await i(e.title));continue}let t=o.latestExplicit;if(t===null||t.order<=l)return;let n=await t.persisted;if(o.latestExplicit===t){if(l=t.order,n===void 0||n===c)return;c=n,await i(n)}}},p=async()=>{if(s.beforeGenerationClaims.length>0&&await Promise.all(s.beforeGenerationClaims.map(e=>e.settled)),s.claim!==null){let e=await u(s.claim);if(e===!0){s.superseded=!0;return}if(e===!1&&d())return}if(!mU(o,s))return;let e=!1,t;for(await r(async n=>{e=!0,t=n,n!==void 0&&(c=n);let r=s.claim;if(r!==null){if(await u(r)!==!1)return;if(d()){s.superseded=!0;return}}mU(o,s)&&await a(t)});;){let n=s.claim;if(n===null)return;let r=await u(n);if(r!==void 0){if(r===!1){if(d())return;e&&mU(o,s)&&await a(t);return}if(!hU(o,n))return;if(await i(n.title),c=n.title,l=n.order,s.claim===n){if(!mU(o,s))return;await a(n.title),s.superseded=!0;return}}}};try{await p(),await f()}finally{s.settlePersisted(c),o.generations.delete(s),pU(e,t,o)}}var SU=(e,t)=>Error(`Thread "${e}" not found while ${t}.`),CU=(e,t,n)=>Error(`Thread "${e}" has status "${t}", so it cannot ${n}.`),wU=nU(),TU=class extends wI{_options;_hookManager;_runtimeAdapters;_loadThreadsPromise;_loadMorePromise;_loadGeneration=0;_adapterGeneration=0;_replaceListOnNextLoad=!1;_staleThreadIdsOnReplace;_switchGeneration=0;_switchTask;_titleStates=new Map;_mainThreadId;_state=new YH(wU);_useAdaptersProvider=({children:e})=>{let t=this._options.adapter.unstable_useAdapters;return t===void 0?e:(0,b.jsx)(this._SynthesizedAdapters,{useAdapters:t,children:e})};_SynthesizedAdapters=({useAdapters:e,children:t})=>{let n=oB(e());return n==null?t:(0,b.jsx)(HV,{adapters:n,children:t})};resolveProvider(e){return e.unstable_Provider===void 0?e.unstable_useAdapters===void 0?wN:this._useAdaptersProvider:e.unstable_Provider}get threadItems(){return this._state.value.threadData}getLoadThreadsPromise(){if(!this._loadThreadsPromise){let e=this._loadGeneration,t=!1,n=aU(this._state.baseValue);this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>e===this._loadGeneration?{...t,isLoading:!0,loadError:void 0}:t,then:(r,i)=>{if(e!==this._loadGeneration)return r;if(this._replaceListOnNextLoad)return this._replaceListOnNextLoad=!1,t=!0,this._replaceWithThreads({...r,loadError:void 0},i.threads,eU(i.nextCursor));let a=tU(i.threads,{threadIds:[],archivedThreadIds:[],threadIdMap:{...r.threadIdMap},threadData:{...r.threadData}});return iU({...r,isLoading:!1,loadError:void 0,cursor:eU(i.nextCursor),threadIds:a.threadIds,archivedThreadIds:a.archivedThreadIds,threadIdMap:a.threadIdMap,threadData:a.threadData},r,n)}}).catch(n=>{if(e===this._loadGeneration){if(console.error(`[assistant-ui] thread list load failed:`,n),this._loadThreadsPromise=void 0,!this._replaceListOnNextLoad){this._state.update({...this._state.baseValue,isLoading:!1,loadError:n});return}this._replaceListOnNextLoad=!1,t=!0,this._state.update(this._replaceWithThreads({...this._state.baseValue,loadError:n},[],void 0))}}).then(()=>{if(!t)return;let e=this._options.threadId;e!==void 0&&this.getItemById(e)?.id!==this._mainThreadId&&this._switchToThreadFromProp(e).catch(()=>{})})}return this._loadThreadsPromise}loadMore(){if(this._loadMorePromise)return this._loadMorePromise;let e=this._state.value;if(e.cursor===void 0||e.isLoading)return Promise.resolve();let t=this._loadGeneration,n=this._options.adapter,r=e.cursor,i=this._state.optimisticUpdate({execute:()=>n.list({after:r}),loading:e=>t===this._loadGeneration?{...e,isLoadingMore:!0}:e,then:(e,r)=>{if(t!==this._loadGeneration||n!==this._options.adapter)return e;let i=tU(r.threads,{threadIds:[...e.threadIds],archivedThreadIds:[...e.archivedThreadIds],threadIdMap:{...e.threadIdMap},threadData:{...e.threadData}});return{...e,isLoadingMore:!1,cursor:eU(r.nextCursor),threadIds:i.threadIds,archivedThreadIds:i.archivedThreadIds,threadIdMap:i.threadIdMap,threadData:i.threadData}}}).catch(e=>{t===this._loadGeneration&&console.error(`[assistant-ui] thread list loadMore failed:`,e)}).then(()=>{this._loadMorePromise===i&&(this._loadMorePromise=void 0)});return this._loadMorePromise=i,i}constructor(e,t){super(),this._state.subscribe(()=>{this._notifySubscribers(),this._notifyThreadIdChange()}),this._runtimeAdapters={modelContext:t},this._hookManager=new KH(e.runtimeHook,this),this._hookManager.__internal_setDefaultAdapters(this._runtimeAdapters),this._hookManager.__internal_subscribeRunningChanged(()=>this._notifySubscribers()),this._hookManager.__internal_subscribeRuntimeReplaced(()=>{queueMicrotask(()=>this._notifySubscribers())}),this.providerStore=new TI(this.resolveProvider(e.adapter)),this.__internal_setOptions(e),this.switchToNewThread()}_initialThreadLoaded=!1;providerStore;__internal_setOptions(e){if(this._options===e)return;let t=this._options!==void 0&&this._options.adapter!==e.adapter,n=this._initialThreadLoaded&&this._options!==void 0&&this._options.threadId!==e.threadId;this._options=e,this.providerStore.setState(this.resolveProvider(e.adapter)),this._hookManager.setRuntimeHook(e.runtimeHook),t&&(this._loadGeneration++,this._adapterGeneration++,this._switchGeneration++,this._switchTask=void 0,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._replaceListOnNextLoad=!0,this._staleThreadIdsOnReplace=new Set(Object.values(this._state.baseValue.threadData).filter(e=>e.status!==`new`).map(e=>e.id)),this._state.update({...this._state.baseValue,cursor:void 0,loadError:void 0}),this._titleStates.clear()),n&&this._switchToThreadFromProp(e.threadId).catch(()=>{})}_requireAdapterGeneration(e){if(e!==this._adapterGeneration)throw new dU}_requireAdapterSettled(){if(this._replaceListOnNextLoad)throw new dU}_replaceWithThreads(e,t,n){let r=[];if(e.newThreadId){let t=Object.hasOwn(e.threadIdMap,e.newThreadId)?e.threadIdMap[e.newThreadId]:void 0,n=t&&Object.hasOwn(e.threadData,t)?e.threadData[t]:void 0;n?.status===`new`&&r.push(n)}let i=this._staleThreadIdsOnReplace;if(i)for(let t of Object.values(e.threadData))i.has(t.id)||(t.status===`new`||t.remoteId!==void 0)&&r.push(t);this._staleThreadIdsOnReplace=void 0;let a={threadIds:[],archivedThreadIds:[],threadIdMap:mM(),threadData:mM()};for(let e of r){let t=QH(e.id);Object.hasOwn(a.threadData,t)||(a.threadIdMap[e.id]=t,e.remoteId!==void 0&&(a.threadIdMap[e.remoteId]=t),a.threadData[t]=e)}let{threadIds:o,archivedThreadIds:s,threadIdMap:c,threadData:l}=tU(t,a);for(let e of r){if(e.remoteId===void 0)continue;let t=QH(e.id),n=Object.hasOwn(l,t)?l[t]:void 0;n!==void 0&&(n.status===`regular`&&!o.includes(n.id)?o.push(n.id):n.status===`archived`&&!s.includes(n.id)&&s.push(n.id))}let u={...e,isLoading:!1,cursor:n,threadIds:o,archivedThreadIds:s,threadIdMap:c,threadData:l,newThreadId:e.newThreadId!==void 0&&!Object.hasOwn(c,e.newThreadId)?void 0:e.newThreadId};if(oU(u,this._mainThreadId)===void 0){let e=u.newThreadId;if(e!==void 0)this._mainThreadId=e;else{let e=rU(u);this._mainThreadId=e.id,u=e.state}this._options.threadId===void 0?this._notifyThreadIdChange():this._lastNotifiedThreadId=void 0}let d=new Set(Object.values(u.threadData).map(e=>e.id));for(let t of Object.values(e.threadData))d.has(t.id)||this._hookManager.stopThreadRuntime(t.id);return this._hookManager.startThreadRuntime(this._mainThreadId).then(()=>this._notifySubscribers(),()=>void 0),u}__internal_load(){if(this.getLoadThreadsPromise(),this._initialThreadLoaded)return;this._initialThreadLoaded=!0;let e=this._options.threadId??this._options.initialThreadId;e!==void 0&&(this._options.threadId===void 0?this.switchToThread(e):this._switchToThreadFromProp(e)).catch(()=>{})}async reloadMainThread(){let e=this._mainThreadId;if(e===void 0||this.getItemById(e)?.status===`new`)return;let t=this._hookManager.getThreadRuntimeCore(e);try{t?.unstable_refetchThread?await t.unstable_refetchThread():await this._hookManager.__internal_restartThreadRuntime(e)}catch(t){if(e!==this._mainThreadId)return;throw t}e===this._mainThreadId&&this._notifySubscribers()}reload(){return this._loadGeneration++,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._state.update({...this._state.baseValue,cursor:void 0}),this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get loadError(){return this._state.value.loadError}get isLoadingMore(){return this._state.value.isLoadingMore}get hasMore(){return this._state.value.cursor!==void 0}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}get _mainThreadRemoteId(){if(this._mainThreadId!==void 0)return oU(this._state.value,this._mainThreadId)?.remoteId}_lastNotifiedThreadId=void 0;_notifyThreadIdChange(e=!0){let t=this._mainThreadRemoteId;this._lastNotifiedThreadId!==t&&(this._lastNotifiedThreadId=t,e&&qH(`assistant-ui`,`onThreadIdChange`,this._options.onThreadIdChange,t))}getMainThreadRuntimeCore(){return this._hookManager.getThreadRuntimeCore(this._mainThreadId)||ZH}getThreadRuntimeCore(e){let t=this.getItemById(e);if(!t)throw SU(e,`getting its runtime`);let n=this._hookManager.getThreadRuntimeCore(t.id);if(!n)throw Error(`Runtime for thread "${e}" not found while getting its runtime.`);return n}unstable_isThreadRunning(e){let t=this.getItemById(e);return t?this._hookManager.__internal_isThreadRunning(t.id):!1}unstable_subscribeThreadEvents(e){return this._hookManager.__internal_subscribeThreadEvents(e)}getItemById(e){return oU(this._state.value,e)}switchToThread(e,t){return this._startSwitchToThread(e,t,!0)}_startSwitchToThread(e,t,n){let r=++this._switchGeneration,i=this._switchToThread(e,t,r,n);return this._switchTask=i,i}async _switchToThread(e,t,n,r){if(this._replaceListOnNextLoad&&e!==this._state.value.newThreadId)throw new dU;let i=this.getItemById(e);if(!i){let t=await this._options.adapter.fetch(e);if(n!==this._switchGeneration)return;let r=this._state.value,a=QH(t.remoteId),o={...r.threadData,[a]:{id:a,initializeTask:Promise.resolve({remoteId:t.remoteId,externalId:t.externalId}),remoteId:t.remoteId,externalId:t.externalId,status:t.status,title:t.title,lastMessageAt:t.lastMessageAt,custom:t.custom}},s={...r.threadIdMap,[t.remoteId]:a},c=t.remoteId,l=t.status===`regular`?r.threadIds.includes(c):r.archivedThreadIds.includes(c),u=r.threadIds.filter(e=>e!==c),d=r.archivedThreadIds.filter(e=>e!==c),f=t.status===`regular`?l?r.threadIds:[...u,c]:u,p=t.status===`archived`?l?r.archivedThreadIds:[...d,c]:d;this._state.update({...r,threadIds:f,archivedThreadIds:p,threadIdMap:s,threadData:o}),i=this.getItemById(e)}if(!i)throw SU(e,`switching to it`);if(this._mainThreadId===i.id)return;let a=this._hookManager.startThreadRuntime(i.id);if(this.mainThreadId===void 0?a.then(()=>this._notifySubscribers(),()=>void 0):await a,n!==this._switchGeneration)return;let o=this.getItemById(i.id);o?.id===i.id&&(o.status===`archived`&&t?.unarchive!==!1&&(await o.initializeTask,n!==this._switchGeneration||(o=this.getItemById(i.id),o?.id!==i.id)||o.status===`archived`&&(await this.unarchive(o.id),n!==this._switchGeneration||(o=this.getItemById(i.id),o?.id!==i.id)))||(this._mainThreadId=o.id,this._notifySubscribers(),this._notifyThreadIdChange(r)))}switchToNewThread(){return this._startSwitchToNewThread(!0)}_switchToThreadFromProp(e){return e===void 0?this._startSwitchToNewThread(!1):this._startSwitchToThread(e,void 0,!1)}_startSwitchToNewThread(e){let t=++this._switchGeneration,n=this._switchToNewThread(t,e);return this._switchTask=n,n}async _switchToNewThread(e,t){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)if(await this._state.waitForUpdate(),e!==this._switchGeneration)return;let n=this._state.baseValue,r=this._state.value.newThreadId;if(r===void 0){let e=rU(n);r=e.id,this._state.update(e.state)}return this._switchToThread(r,void 0,e,t)}initialize=async e=>{let t=this._options.adapter,n=this._adapterGeneration;if(this._state.value.newThreadId!==e){this._requireAdapterSettled();let t=this.getItemById(e);if(!t)throw SU(e,`initializing it`);if(t.status===`new`)throw CU(e,t.status,`be initialized here`);let{remoteId:r,externalId:i}=await t.initializeTask;return this._requireAdapterGeneration(n),{remoteId:r,externalId:i}}this._requireAdapterGeneration(n);let r=t.initialize(e),i,{remoteId:a,externalId:o}=await this._state.optimisticUpdate({execute:()=>r,optimistic:t=>uU(t,e,r),then:(t,{remoteId:r,externalId:a})=>{if(n!==this._adapterGeneration)return t;let o=sU(t,e,r,a,e);return i=o.removedMappingId,i===this._mainThreadId&&(this._mainThreadId=o.survivorMappingId),o.state}});return this._requireAdapterGeneration(n),i!==void 0&&this._hookManager.stopThreadRuntime(i),{remoteId:a,externalId:o}};generateTitle=async(e,t)=>{this._requireAdapterSettled();let n=this._options.adapter,r=this._adapterGeneration,i=this.getItemById(e);if(!i)throw SU(e,`generating its title`);if(i.status===`new`)throw CU(e,i.status,`generate a title`);let{remoteId:a}=await i.initializeTask;this._requireAdapterGeneration(r);let o=this._hookManager.getThreadRuntimeCore(i.id);if(!o)return;let s=o.messages.filter(zH);await xU({states:this._titleStates,threadId:i.id,automatic:t?.automatic===!0,generate:async e=>{let t=await n.generateTitle(a,s);this._requireAdapterGeneration(r),await BH(t,e)},rename:async e=>{this._requireAdapterGeneration(r),await n.rename(a,e)},applyTitle:async e=>{await this._state.optimisticUpdate({execute:async()=>{},optimistic:t=>{if(r!==this._adapterGeneration)return t;let n=oU(t,i.id);return n?{...t,threadData:{...t.threadData,[n.id]:{...n,title:e}}}:t}})}})};async rename(e,t){this._requireAdapterSettled();let n=this._options.adapter,r=this._adapterGeneration,i=this.getItemById(e);if(!i)throw SU(e,`renaming it`);if(i.status===`new`)throw CU(e,i.status,`be renamed`);let a=gU(this._titleStates,i.id,t);try{let o=await this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await i.initializeTask;return this._requireAdapterGeneration(r),n.rename(e,t)},optimistic:n=>{let r=oU(n,e);return r?{...n,threadData:{...n.threadData,[r.id]:{...r,title:t}}}:n}});return _U(this._titleStates,i.id,a,!0),o}catch(e){throw _U(this._titleStates,i.id,a,!1),e}}async updateCustom(e,t){this._requireAdapterSettled();let n=this._options.adapter,r=this._adapterGeneration,i=this.getItemById(e);if(!i)throw SU(e,`updating its custom metadata`);if(i.status===`new`)throw CU(e,i.status,`update custom metadata`);if(!n.updateCustom)throw Error(`Remote thread list adapter does not support updating custom metadata`);return this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await i.initializeTask;if(this._requireAdapterGeneration(r),!n.updateCustom)throw Error(`Remote thread list adapter does not support updating custom metadata`);return n.updateCustom(e,t)},optimistic:n=>{let r=oU(n,e);return r?{...n,threadData:{...n.threadData,[r.id]:{...r,custom:t}}}:n}})}async _ensureThreadIsNotMain(e){if(e===this.newThreadId)throw Error(`Cannot ensure new thread is not main`);let t;for(;e===this._mainThreadId;){let e=this._switchTask,n=!e||e===t;n&&(e=this.switchToNewThread()),t=e;try{await e}catch(t){if(n&&this._switchTask===e)throw t}}}async archive(e){this._requireAdapterSettled();let t=this._options.adapter,n=this._adapterGeneration,r=this.getItemById(e);if(!r)throw SU(e,`archiving it`);if(r.status!==`regular`)throw CU(e,r.status,`be archived`);return await this._ensureThreadIsNotMain(r.id),this._requireAdapterGeneration(n),this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await r.initializeTask;return this._requireAdapterGeneration(n),t.archive(e)},optimistic:e=>lU(e,r.id,`archived`)})}async unarchive(e){this._requireAdapterSettled();let t=this._options.adapter,n=this._adapterGeneration,r=this.getItemById(e);if(!r)throw SU(e,`unarchiving it`);if(r.status!==`archived`)throw CU(e,r.status,`be unarchived`);return this._state.optimisticUpdate({execute:async()=>{try{let{remoteId:e}=await r.initializeTask;return this._requireAdapterGeneration(n),await t.unarchive(e)}catch(e){throw n===this._adapterGeneration&&await this._ensureThreadIsNotMain(r.id),e}},optimistic:e=>lU(e,r.id,`regular`)})}async delete(e){this._requireAdapterSettled();let t=this._options.adapter,n=this._adapterGeneration,r=this.getItemById(e);if(!r)throw SU(e,`deleting it`);if(r.status!==`regular`&&r.status!==`archived`)throw CU(e,r.status,`be deleted`);await this._ensureThreadIsNotMain(r.id),this._requireAdapterGeneration(n);let i=await this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await r.initializeTask;return this._requireAdapterGeneration(n),await t.delete(e)},optimistic:e=>lU(e,r.id,`deleted`)});return this._hookManager.stopThreadRuntime(r.id),yU(this._titleStates,r.id),i}__internal_dispose(){this._hookManager.__internal_dispose()}async detach(e){let t=this._adapterGeneration,n=this.getItemById(e);if(!n)throw SU(e,`detaching it`);if(n.status!==`regular`&&n.status!==`archived`)throw CU(e,n.status,`be detached`);await this._ensureThreadIsNotMain(n.id),this._requireAdapterGeneration(t),this._hookManager.stopThreadRuntime(n.id)}boundIdsStore=new TI([]);__internal_RenderComponent=()=>{let e=xN();X(()=>(this.boundIdsStore.setState([...this.boundIdsStore.getState(),e]),()=>{this.boundIdsStore.setState(this.boundIdsStore.getState().filter(t=>t!==e))}),[e]);let t=GI(this.boundIdsStore),n=GI(this.providerStore),r=Q();return(t.length===0||t[0]===e)&&(0,b.jsxs)(HV,{adapters:this._runtimeAdapters,children:[(0,b.jsx)(this._hookManager.__internal_RenderThreadRuntimes,{provider:n}),(0,b.jsx)(this._hookManager.__internal_Host,{parentClient:r})]})}},EU=class extends eH{threads;constructor(e){super(),this.threads=new TU(e,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},DU=e=>{let t=J(18),n;t[0]===e?n=t[1]:(n=()=>new EU(e),t[0]=e,t[1]=n);let[r]=fN(n),i;t[2]===r.threads?i=t[3]:(i=()=>()=>queueMicrotask(()=>r.threads.__internal_dispose()),t[2]=r.threads,t[3]=i);let a;t[4]===r?a=t[5]:(a=[r],t[4]=r,t[5]=a),bN(i,a);let o;t[6]!==e||t[7]!==r.threads?(o=()=>{r.threads.__internal_setOptions(e),r.threads.__internal_load()},t[6]=e,t[7]=r.threads,t[8]=o):o=t[8];let s;t[9]!==e||t[10]!==r?(s=[r,e],t[9]=e,t[10]=r,t[11]=s):s=t[11],X(o,s);let c;t[12]===r.threads?c=t[13]:(c=()=>{if(typeof window>`u`||typeof document>`u`)return;let e=()=>{r.threads.loadError!==void 0&&r.threads.reload()},t=()=>{document.visibilityState===`visible`&&e()};return window.addEventListener(`online`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`online`,e),document.removeEventListener(`visibilitychange`,t)}},t[12]=r.threads,t[13]=c);let l;t[14]===r?l=t[15]:(l=[r],t[14]=r,t[15]=l),X(c,l);let u;return t[16]===r?u=t[17]:(u=new YV(r),t[16]=r,t[17]=u),u},OU=e=>{let[t]=fN(()=>new TI(e.runtimeHook));gN(()=>{t.setState(e.runtimeHook)},[t,e.runtimeHook]);let n=Y(e.initialThreadId),r=hN(function(){return GI({subscribe:t.subscribe,getState:t.getState,getServerSnapshot:t.getState})()},[t]),i=_N(t=>e.onThreadIdChange?.(t)),a=mN(()=>({adapter:e.adapter,allowNesting:e.allowNesting,threadId:e.threadId,initialThreadId:n.current,runtimeHook:r,onThreadIdChange:i}),[e.adapter,e.allowNesting,e.threadId,r]);if(Q().threadListItem.source!==null){if(!a.allowNesting)throw Error(`useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).`);return e.runtimeHook()}return DU(a)},kU=e=>{let t=J(6),{id:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=jP({message:dI({source:`thread`,query:{type:`id`,id:n},get:e=>e.thread.message({id:n})}),composer:dI({source:`message`,query:{},get:e=>e.thread.message({id:n}).composer()})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(zL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},AU=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,jU=()=>null,MU=new WeakMap,NU=(e,t)=>{let n=MU.get(e);return n||(n=new Set(e.map(e=>e.id)),MU.set(e,n)),n.has(t)},PU=(e,t,n)=>{switch(t){case`user`:return n?e.UserEditComposer??e.EditComposer??e.UserMessage??e.Message:e.UserMessage??e.Message;case`assistant`:return n?e.AssistantEditComposer??e.EditComposer??e.AssistantMessage??e.Message:e.AssistantMessage??e.Message;case`system`:return n?e.SystemEditComposer??e.EditComposer??e.SystemMessage??e.Message??jU:e.SystemMessage??e.Message??jU;default:throw Error(`Unknown message role: ${t}`)}},FU=e=>{let t=J(6),{components:n}=e,r=$(VU),i=$(HU),a;t[0]!==n||t[1]!==i||t[2]!==r?(a=PU(n,r,i),t[0]=n,t[1]=i,t[2]=r,t[3]=a):a=t[3];let o=a,s;return t[4]===o?s=t[5]:(s=(0,b.jsx)(o,{}),t[4]=o,t[5]=s),s},IU=CN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(FU,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(XB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&AU(e.components,t.components));IU.displayName=`ThreadPrimitive.MessageByIndex`;var LU=CN(e=>{let t=J(7),{messageId:n,components:r}=e,i;if(t[0]===n?i=t[1]:(i=e=>NU(e.thread.messages,n),t[0]=n,t[1]=i),!$(i))return null;let a;t[2]===r?a=t[3]:(a=(0,b.jsx)(FU,{components:r}),t[2]=r,t[3]=a);let o;return t[4]!==n||t[5]!==a?(o=(0,b.jsx)(kU,{id:n,children:a}),t[4]=n,t[5]=a,t[6]=o):o=t[6],o},(e,t)=>e.messageId===t.messageId&&AU(e.components,t.components));LU.displayName=`ThreadPrimitive.Unstable_MessageById`;var RU=({children:e})=>{let t=$(RF(e=>e.thread.messages.map(e=>e.id)));return mN(()=>t.length===0?null:t.map((t,n)=>(0,b.jsx)(XB,{index:n,children:(0,b.jsx)(HL,{getItemState:e=>e.thread.message({index:n}).getState(),children:t=>e({get message(){return t()}})})},t)),[t,e])},zU=e=>{let t=J(4),{components:n,children:r}=e;if(n){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(RU,{children:()=>(0,b.jsx)(FU,{components:n})}),t[0]=n,t[1]=e),e}let i;return t[2]===r?i=t[3]:(i=(0,b.jsx)(RU,{children:r}),t[2]=r,t[3]=i),i};zU.displayName=`ThreadPrimitive.Messages`;var BU=CN(zU,(e,t)=>e.children||t.children?e.children===t.children:AU(e.components,t.components));function VU(e){return e.message.role}function HU(e){return e.message.composer.isEditing}var UU=e=>{let t=e.message.metadata;if(t&&typeof t==`object`)return t.custom?.quote},WU=class extends Error{componentName;constructor(e,t=`Component "${e}" is not in the generative-ui allowlist.`){super(t),this.name=`GenerativeUIRenderError`,this.componentName=e}},GU=e=>typeof e==`object`&&!!e,KU=e=>e==null?[]:Array.isArray(e)?e:[e],qU=(e,t,n,r)=>{if(e==null)return null;if(typeof e==`string`)return e;if(!GU(e)||!(`component`in e)||typeof e.component!=`string`)return null;let{component:i,props:a,children:o,key:s}=e,c=t[i];if(!c){if(n)return(0,b.jsx)(n,{component:i,props:a},s??r);throw new WU(i)}return TN(c,{...a??{},key:s??r},...KU(o).map((e,i)=>qU(e,t,n,`${r}/${i}`)))},JU=e=>{let t=J(11),{spec:n,components:r,Fallback:i}=e,a=n?.root,o;t[0]===a?o=t[1]:(o=KU(a),t[0]=a,t[1]=o);let s=o,c;if(t[2]!==i||t[3]!==r||t[4]!==s){let e;t[6]!==i||t[7]!==r?(e=(e,t)=>qU(e,r,i,`${t}`),t[6]=i,t[7]=r,t[8]=e):e=t[8],c=s.map(e),t[2]=i,t[3]=r,t[4]=s,t[5]=c}else c=t[5];let l;return t[9]===c?l=t[10]:(l=(0,b.jsx)(b.Fragment,{children:c}),t[9]=c,t[10]=l),l};JU.displayName=`GenerativeUIRender`;var YU=e=>{let t=J(4),{components:n,spec:r,Fallback:i}=e,a=$(XU),o=r??a;if(!o)return null;let s;return t[0]!==i||t[1]!==n||t[2]!==o?(s=(0,b.jsx)(JU,{spec:o,components:n,Fallback:i}),t[0]=i,t[1]=n,t[2]=o,t[3]=s):s=t[3],s};YU.displayName=`MessagePrimitive.GenerativeUI`;function XU(e){let t=e.part;return t?.type===`generative-ui`?t.spec:void 0}var ZU=e=>{let t=-1;return{startGroup:e=>{t===-1&&(t=e)},endGroup:(n,r)=>{t!==-1&&(r.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,r)=>{t!==-1&&r.push({type:e,startIndex:t,endIndex:n})}}},QU=(e,t,n)=>{let r=[];if(t){let t=ZU(`chainOfThoughtGroup`);for(let n=0;n<e.length;n++){let i=e[n];i===`tool-call`||i===`reasoning`?t.startGroup(n):(t.endGroup(n-1,r),r.push({type:`single`,index:n}))}t.finalize(e.length-1,r)}else{let t=ZU(`toolGroup`),n=ZU(`reasoningGroup`);for(let i=0;i<e.length;i++){let a=e[i];a===`tool-call`?(n.endGroup(i-1,r),t.startGroup(i)):a===`reasoning`?(t.endGroup(i-1,r),n.startGroup(i)):(t.endGroup(i-1,r),n.endGroup(i-1,r),r.push({type:`single`,index:i}))}t.finalize(e.length-1,r),n.finalize(e.length-1,r)}if(n){let e=new Set;for(let t of r){if(t.type===`single`)continue;let r=n[t.startIndex];r!==void 0&&!e.has(r)&&(e.add(r),t.idKey=`id:${r}`)}}return r},$U=e=>{let t=J(10),n=$(RF(CW)),r=$(RF(TW)),i;bb0:{if(n.length===0){let e;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[0]=e):e=t[0];let n;t[1]===r?n=t[2]:(n={ranges:e,partIds:r},t[1]=r,t[2]=n),i=n;break bb0}let a;t[3]!==n||t[4]!==r||t[5]!==e?(a=QU(n,e,r),t[3]=n,t[4]=r,t[5]=e,t[6]=a):a=t[6];let o;t[7]!==r||t[8]!==a?(o={ranges:a,partIds:r},t[7]=r,t[8]=a,t[9]=o):o=t[9],i=o}return i},eW=e=>{let t=J(9),n,r;t[0]===e?(n=t[1],r=t[2]):({Fallback:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]!==n||t[4]!==r.toolName?(i=e=>e.tools.toolUIs[r.toolName]?.[0]?.render??n,t[3]=n,t[4]=r.toolName,t[5]=i):i=t[5];let a=$(i);if(!a)return null;let o;return t[6]!==a||t[7]!==r?(o=(0,b.jsx)(a,{...r}),t[6]=a,t[7]=r,t[8]=o):o=t[8],o},tW=(e,t,n)=>e.renderers[t]?.[0]||(e.fallbacks[0]??n),nW=e=>{let t=J(9),n,r;t[0]===e?(n=t[1],r=t[2]):({Fallback:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]!==n||t[4]!==r.name?(i=e=>tW(e.dataRenderers,r.name,n),t[3]=n,t[4]=r.name,t[5]=i):i=t[5];let a=$(i);if(!a)return null;let o;return t[6]!==a||t[7]!==r?(o=(0,b.jsx)(a,{...r}),t[6]=a,t[7]=r,t[8]=o):o=t[8],o},rW={Text:()=>null,Reasoning:()=>null,Source:()=>null,Image:()=>null,File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},iW=e=>{let t=J(41),{components:n}=e,r;t[0]===n?r=t[1]:(r=n===void 0?{}:n,t[0]=n,t[1]=r);let{Text:i,Reasoning:a,Image:o,Source:s,File:c,Unstable_Audio:l,tools:u,data:d,generativeUI:f}=r,p=i===void 0?rW.Text:i,m=a===void 0?rW.Reasoning:a,h=o===void 0?rW.Image:o,g=s===void 0?rW.Source:s,_=c===void 0?rW.File:c,v=l===void 0?rW.Unstable_Audio:l,y;t[2]===u?y=t[3]:(y=u===void 0?{}:u,t[2]=u,t[3]=y);let x=y,S=Q(),C=$(EW),w=C.type;if(w===`tool-call`){let e=S.part.addToolResult,n=S.part.resumeToolCall,r=S.part.respondToToolApproval;if(`Override`in x){let i;return t[4]!==e||t[5]!==C||t[6]!==r||t[7]!==n||t[8]!==x.Override?(i=(0,b.jsx)(x.Override,{...C,addResult:e,resume:n,respondToApproval:r}),t[4]=e,t[5]=C,t[6]=r,t[7]=n,t[8]=x.Override,t[9]=i):i=t[9],i}let i=x.by_name?.[C.toolName]??x.Fallback,a;return t[10]!==i||t[11]!==e||t[12]!==C||t[13]!==r||t[14]!==n?(a=(0,b.jsx)(eW,{...C,Fallback:i,addResult:e,resume:n,respondToApproval:r}),t[10]=i,t[11]=e,t[12]=C,t[13]=r,t[14]=n,t[15]=a):a=t[15],a}if(C.status?.type===`requires-action`)throw Error(`Encountered unexpected requires-action status`);switch(w){case`text`:{let e;return t[16]!==p||t[17]!==C?(e=(0,b.jsx)(p,{...C}),t[16]=p,t[17]=C,t[18]=e):e=t[18],e}case`reasoning`:{let e;return t[19]!==m||t[20]!==C?(e=(0,b.jsx)(m,{...C}),t[19]=m,t[20]=C,t[21]=e):e=t[21],e}case`source`:{let e;return t[22]!==g||t[23]!==C?(e=(0,b.jsx)(g,{...C}),t[22]=g,t[23]=C,t[24]=e):e=t[24],e}case`image`:{let e;return t[25]!==h||t[26]!==C?(e=(0,b.jsx)(h,{...C}),t[25]=h,t[26]=C,t[27]=e):e=t[27],e}case`file`:{let e;return t[28]!==_||t[29]!==C?(e=(0,b.jsx)(_,{...C}),t[28]=_,t[29]=C,t[30]=e):e=t[30],e}case`audio`:{let e;return t[31]!==v||t[32]!==C?(e=(0,b.jsx)(v,{...C}),t[31]=v,t[32]=C,t[33]=e):e=t[33],e}case`data`:{let e=d?.by_name?.[C.name]??d?.Fallback,n;return t[34]!==e||t[35]!==C?(n=(0,b.jsx)(nW,{...C,Fallback:e}),t[34]=e,t[35]=C,t[36]=n):n=t[36],n}case`generative-ui`:{if(!f?.components)return null;let e=C,n;return t[37]!==f.Fallback||t[38]!==f.components||t[39]!==e.spec?(n=(0,b.jsx)(JU,{spec:e.spec,components:f.components,Fallback:f.Fallback}),t[37]=f.Fallback,t[38]=f.components,t[39]=e.spec,t[40]=n):n=t[40],n}default:return console.warn(`Unknown message part type: ${w}`),null}},aW=CN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(iW,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(ZB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.generativeUI===t.components?.generativeUI&&e.components?.ToolGroup===t.components?.ToolGroup&&e.components?.ReasoningGroup===t.components?.ReasoningGroup);aW.displayName=`MessagePrimitive.PartByIndex`;var oW=e=>{let t=J(6),{status:n,component:r}=e,i=n.type===`running`,a;t[0]!==r||t[1]!==n?(a=(0,b.jsx)(r,{type:`text`,text:``,status:n}),t[0]=r,t[1]=n,t[2]=a):a=t[2];let o;return t[3]!==i||t[4]!==a?(o=(0,b.jsx)($B,{text:``,isRunning:i,children:a}),t[3]=i,t[4]=a,t[5]=o):o=t[5],o},sW=Object.freeze({type:`complete`}),cW=Object.freeze({type:`running`}),lW=CN(e=>{let t=J(6),{components:n}=e,r=$(DW);if(n?.Empty){let e;return t[0]!==n.Empty||t[1]!==r?(e=(0,b.jsx)(n.Empty,{status:r}),t[0]=n.Empty,t[1]=r,t[2]=e):e=t[2],e}if(r.type!==`running`)return null;let i=n?.Text??rW.Text,a;return t[3]!==r||t[4]!==i?(a=(0,b.jsx)(oW,{status:r,component:i}),t[3]=r,t[4]=i,t[5]=a):a=t[5],a},(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),uW=CN(e=>{let t=J(4),{components:n,enabled:r}=e,i;if(t[0]===r?i=t[1]:(i=e=>{if(!r||e.message.parts.length===0)return!1;let t=e.message.parts[e.message.parts.length-1];return t?.type!==`text`&&t?.type!==`reasoning`},t[0]=r,t[1]=i),!$(i))return null;let a;return t[2]===n?a=t[3]:(a=(0,b.jsx)(lW,{components:n}),t[2]=n,t[3]=a),a},(e,t)=>e.enabled===t.enabled&&e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),dW=CN(e=>{let t=J(4),{Quote:n}=e,r=$(UU);if(!r)return null;let i;return t[0]!==n||t[1]!==r.messageId||t[2]!==r.text?(i=(0,b.jsx)(n,{text:r.text,messageId:r.messageId}),t[0]=n,t[1]=r.messageId,t[2]=r.text,t[3]=i):i=t[3],i});function fW(e,t){return(e.toolUIs[t.toolName]?.[0]?.render??null)||(DV(t.mcp?.app?.resourceUri)&&e.mcpApp?e.mcpApp.render:null)}var pW=()=>{let e=J(6),t=Q(),n=$(OW),r=$(kW);if(!r||n.type!==`tool-call`)return null;let i;return e[0]!==r||e[1]!==t.part.addToolResult||e[2]!==t.part.respondToToolApproval||e[3]!==t.part.resumeToolCall||e[4]!==n?(i=(0,b.jsx)(r,{...n,addResult:t.part.addToolResult,resume:t.part.resumeToolCall,respondToApproval:t.part.respondToToolApproval}),e[0]=r,e[1]=t.part.addToolResult,e[2]=t.part.respondToToolApproval,e[3]=t.part.resumeToolCall,e[4]=n,e[5]=i):i=e[5],i},mW=()=>{let e=J(3),t=$(AW),n=$(jW);if(!n||t.type!==`data`)return null;let r=t,i;return e[0]!==n||e[1]!==r?(i=(0,b.jsx)(n,{...r}),e[0]=n,e[1]=r,e[2]=i):i=e[2],i},hW=()=>{let e=J(2),t=$(MW);if(t===`tool-call`){let t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,b.jsx)(pW,{}),e[0]=t):t=e[0],t}if(t===`data`){let t;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,b.jsx)(mW,{}),e[1]=t):t=e[1],t}return null},gW=Object.freeze({type:`text`,text:``,status:cW}),_W=({children:e})=>{let t=Q(),n=$(e=>e.dataRenderers);return(0,b.jsx)(HL,{getItemState:e=>e.part.getState(),children:r=>e({get part(){let e=r();if(e.type===`tool-call`){let n=fW(t.tools.getState(),e)!==null,r=t.part;return{...e,toolUI:n?(0,b.jsx)(pW,{}):null,addResult:r.addToolResult,resume:r.resumeToolCall,respondToApproval:r.respondToToolApproval}}if(e.type===`data`){let t=tW(n,e.name,void 0)!==void 0;return{...e,dataRendererUI:t?(0,b.jsx)(mW,{}):null}}return e}})})},vW=e=>{let t=J(5),{index:n,children:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(_W,{children:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(ZB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},yW=e=>{let t=J(9),{children:n}=e,r=$(NW),i=$(PW),a=r===0&&i;if(r===0){if(!a)return null;let e;t[0]===n?e=t[1]:(e=n({part:gW}),t[0]=n,t[1]=e);let r;return t[2]===e?r=t[3]:(r=(0,b.jsx)($B,{text:``,isRunning:!0,children:e}),t[2]=e,t[3]=r),r}let o;if(t[4]!==n||t[5]!==r){let e;t[7]===n?e=t[8]:(e=(e,t)=>(0,b.jsx)(vW,{index:t,children:e=>n(e)??(0,b.jsx)(hW,{})},t),t[7]=n,t[8]=e),o=(0,b.jsx)(b.Fragment,{children:Array.from({length:r},e)}),t[4]=n,t[5]=r,t[6]=o}else o=t[6];return o},bW=e=>{let t=J(5),{components:n,unstable_showEmptyOnNonTextEnd:r,children:i}=e,a=r===void 0||r;if(i){let e;return t[0]===i?e=t[1]:(e=(0,b.jsx)(yW,{children:i}),t[0]=i,t[1]=e),e}let o;return t[2]!==n||t[3]!==a?(o=(0,b.jsx)(xW,{components:n,unstable_showEmptyOnNonTextEnd:a}),t[2]=n,t[3]=a,t[4]=o):o=t[4],o};bW.displayName=`MessagePrimitive.Parts`;var xW=e=>{let t=J(15),{components:n,unstable_showEmptyOnNonTextEnd:r}=e,i=$(FW),{ranges:a,partIds:o}=$U(!!n?.ChainOfThought),s;bb0:{if(i===0){let e;t[0]===n?e=t[1]:(e=(0,b.jsx)(lW,{components:n}),t[0]=n,t[1]=e),s=e;break bb0}let e;if(t[2]!==n||t[3]!==a||t[4]!==o){let r=new Set,i=e=>{let t=o[e];return t!==void 0&&!r.has(t)?(r.add(t),`part-id:${t}`):`part-${e}`};e=a.map(e=>{if(e.type===`single`)return(0,b.jsx)(aW,{index:e.index,components:n},e.index);if(e.type===`chainOfThoughtGroup`){let t=n?.ChainOfThought;return t?(0,b.jsx)(oV,{startIndex:e.startIndex,endIndex:e.endIndex,children:(0,b.jsx)(t,{})},`chainOfThought-${e.idKey??e.startIndex}`):null}if(e.type===`toolGroup`){let t=n?.ToolGroup??rW.ToolGroup;return(0,b.jsx)(t,{startIndex:e.startIndex,endIndex:e.endIndex,children:Array.from({length:e.endIndex-e.startIndex+1},(t,r)=>{let a=e.startIndex+r;return(0,b.jsx)(aW,{index:a,components:n},i(a))})},`tool-${e.idKey??e.startIndex}`)}{let t=n?.ReasoningGroup??rW.ReasoningGroup;return(0,b.jsx)(t,{startIndex:e.startIndex,endIndex:e.endIndex,children:Array.from({length:e.endIndex-e.startIndex+1},(t,r)=>{let i=e.startIndex+r;return(0,b.jsx)(aW,{index:i,components:n},`part-${i}`)})},`reasoning-${e.startIndex}`)}}),t[2]=n,t[3]=a,t[4]=o,t[5]=e}else e=t[5];s=e}let c=s,l;t[6]===n?l=t[7]:(l=n?.Quote&&(0,b.jsx)(dW,{Quote:n.Quote}),t[6]=n,t[7]=l);let u;t[8]!==n||t[9]!==r?(u=(0,b.jsx)(uW,{components:n,enabled:r}),t[8]=n,t[9]=r,t[10]=u):u=t[10];let d;return t[11]!==c||t[12]!==l||t[13]!==u?(d=(0,b.jsxs)(b.Fragment,{children:[l,c,u]}),t[11]=c,t[12]=l,t[13]=u,t[14]=d):d=t[14],d};function SW(e){return e.type}function CW(e){return e.message.parts.map(SW)}function wW(e){return e.type===`tool-call`?e.toolCallId:void 0}function TW(e){return e.message.parts.map(wW)}function EW(e){return e.part}function DW(e){return e.message.status??sW}function OW(e){return e.part}function kW(e){return e.part.type===`tool-call`?fW(e.tools,e.part):null}function AW(e){return e.part}function jW(e){return e.part.type===`data`?tW(e.dataRenderers,e.part.name,void 0)??null:null}function MW(e){return e.part.type}function NW(e){return e.message.parts.length}function PW(e){return(e.message.status?.type??`complete`)===`running`}function FW(e){return e.message.parts.length}var IW=Symbol.for(`@assistant-ui/groupBy.memoKey`),LW=e=>{let t=e,n=((e,n)=>{if(e.type===`tool-call`){if((DV(e.mcp?.app?.resourceUri)||(n?.toolUIs?.[e.toolName]?.[0]?.standalone??!1))&&t[`standalone-tool-call`]!==void 0)return t[`standalone-tool-call`];let r=t[`tool-call:${e.toolName}`];return r===void 0?t[`tool-call`]??[]:r}return t[e.type]??[]}),r=Object.keys(e).sort().map(t=>[t,e[t]]);return n[IW]=`groupPartByType:${JSON.stringify(r)}`,n},RW=e=>{let t=e.nextChildIdx++;return e.nodeKey===``?String(t):`${e.nodeKey}.${t}`},zW=(e,t)=>{if(!(t===void 0||e.claimed.has(t)))return e.claimed.add(t),`id:${t}`},BW=(e,t)=>{let n={key:``,nodeKey:``,indices:[],children:[],nextChildIdx:0,claimed:new Set},r=[n],i=()=>{let e=r.pop(),n=r[r.length-1];n.children.push({type:`group`,key:e.key,nodeKey:e.nodeKey,idKey:zW(n,t?.[e.indices[0]]),indices:e.indices,children:e.children})};for(let n=0;n<e.length;n++){let a=e[n],o=0;for(;o<r.length-1&&o<a.length&&r[o+1].key===a[o];)o++;for(;r.length-1>o;)i();for(;r.length-1<a.length;){let e=r[r.length-1];r.push({key:a[r.length-1],nodeKey:RW(e),indices:[],children:[],nextChildIdx:0,claimed:new Set})}let s=r[r.length-1];s.children.push({type:`part`,index:n,nodeKey:RW(s),idKey:zW(s,t?.[n])});for(let e=1;e<r.length;e++)r[e].indices.push(n)}for(;r.length>1;)i();return n.children},VW=(e,t,n)=>{if(!n)return!1;switch(e){case`never`:return!1;case`always`:return!0;case`empty`:return t.length===0;case`no-text`:{let e=t[t.length-1];return e===void 0||e.type!==`text`&&e.type!==`reasoning`}}},HW=()=>{throw Error("MessagePrimitive.GroupedParts: rendered `children` under a leaf part. `children` is only meaningful for `group-…` cases — add a matching case for the part type or return `null` to skip it.")},UW=(e,t,n)=>{if(e.type===`part`)return(0,b.jsx)(vW,{index:e.index,children:({part:e})=>n({part:e,children:(0,b.jsx)(HW,{})})},e.idKey?`part-${e.idKey}`:`part-${e.index}`);let{status:r,counts:i}=iV(t,e.indices),a={type:e.key,status:r,counts:i,indices:e.indices};return(0,b.jsx)(wN,{children:n({part:a,children:(0,b.jsx)(b.Fragment,{children:e.children.map(e=>UW(e,t,n))})})},e.idKey??e.nodeKey)},WW=({groupBy:e,indicator:t=`no-text`,children:n})=>{let r=$(RF(e=>e.message.parts)),i=$(e=>e.tools.toolUIs),a=$(e=>t!==`never`&&e.message.status?.type===`running`),o=mN(()=>{let t={toolUIs:i};return BW(r.map(n=>e(n,t)??[]),r.map(e=>e.type===`tool-call`?e.toolCallId:void 0))},[r,e[IW]??e,i]);return(0,b.jsxs)(b.Fragment,{children:[o.map(e=>UW(e,r,n)),VW(t,r,a)&&n({part:{type:`indicator`},children:(0,b.jsx)(HW,{})})]})};WW.displayName=`MessagePrimitive.GroupedParts`;var GW=CN(e=>{let t=J(5),{children:n}=e,r=$(UU);if(!r)return null;let i;t[0]!==n||t[1]!==r?(i=n(r),t[0]=n,t[1]=r,t[2]=i):i=t[2];let a;return t[3]===i?a=t[4]:(a=(0,b.jsx)(b.Fragment,{children:i}),t[3]=i,t[4]=a),a});GW.displayName=`MessagePrimitive.Quote`;var KW=(e,t)=>{switch(t.type){case`image`:return e?.Image??e?.Attachment;case`document`:return e?.Document??e?.Attachment;case`file`:return e?.File??e?.Attachment;default:return e?.Attachment}},qW=e=>{let t=J(5),{components:n}=e,r=$(ZW);if(!r)return null;let i=r,a;t[0]!==n||t[1]!==i?(a=KW(n,i),t[0]=n,t[1]=i,t[2]=a):a=t[2];let o=a;if(!o)return null;let s;return t[3]===o?s=t[4]:(s=(0,b.jsx)(o,{}),t[3]=o,t[4]=s),s},JW=CN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(qW,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(qB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);JW.displayName=`MessagePrimitive.AttachmentByIndex`;var YW=({children:e})=>{let t=$(RF(e=>e.message.role===`user`?(e.message.attachments??[]).map(e=>e.id):[]));return mN(()=>t.map((t,n)=>(0,b.jsx)(qB,{index:n,children:(0,b.jsx)(HL,{getItemState:e=>e.message.attachment({index:n}).getState(),children:t=>e({get attachment(){return t()}})})},t)),[t,e])},XW=e=>{let t=J(4),{components:n,children:r}=e;if(n){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(YW,{children:e=>{let{attachment:t}=e,r=KW(n,t);return r?(0,b.jsx)(r,{}):null}}),t[0]=n,t[1]=e),e}let i;return t[2]===r?i=t[3]:(i=(0,b.jsx)(YW,{children:r}),t[2]=r,t[3]=i),i};XW.displayName=`MessagePrimitive.Attachments`;function ZW(e){return e.attachment}var QW=(e,t)=>{switch(t.type){case`image`:return e?.Image??e?.Attachment;case`document`:return e?.Document??e?.Attachment;case`file`:return e?.File??e?.Attachment;default:return e?.Attachment}},$W=e=>{let t=J(5),{components:n}=e,r=$(rG);if(!r)return null;let i;t[0]!==r||t[1]!==n?(i=QW(n,r),t[0]=r,t[1]=n,t[2]=i):i=t[2];let a=i;if(!a)return null;let o;return t[3]===a?o=t[4]:(o=(0,b.jsx)(a,{}),t[3]=a,t[4]=o),o},eG=CN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)($W,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(JB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);eG.displayName=`ComposerPrimitive.AttachmentByIndex`;var tG=({children:e})=>{let t=$(RF(e=>e.composer.attachments.map(e=>e.id)));return mN(()=>t.map((t,n)=>(0,b.jsx)(JB,{index:n,children:(0,b.jsx)(HL,{getItemState:e=>e.composer.attachment({index:n}).getState(),children:t=>e({get attachment(){return t()}})})},t)),[t,e])},nG=e=>{let t=J(4),{components:n,children:r}=e;if(n){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(tG,{children:e=>{let{attachment:t}=e,r=QW(n,t);return r?(0,b.jsx)(r,{}):null}}),t[0]=n,t[1]=e),e}let i;return t[2]===r?i=t[3]:(i=(0,b.jsx)(tG,{children:r}),t[2]=r,t[3]=i),i};nG.displayName=`ComposerPrimitive.Attachments`;function rG(e){return e.attachment}var iG=CN(({children:e})=>{let t=$(RF(e=>e.composer.queue.map(e=>e.id)));return mN(()=>t.map((t,n)=>(0,b.jsx)(uV,{index:n,children:(0,b.jsx)(HL,{getItemState:e=>e.composer.queueItem({index:n}).getState(),children:t=>e({get queueItem(){return t()}})})},t)),[t,e])});iG.displayName=`ComposerPrimitive.Queue`;var aG=CN(e=>{let t=J(6),{index:n,archived:r,components:i}=e,a=r!==void 0&&r,o=i.ThreadListItem,s;t[0]===o?s=t[1]:(s=(0,b.jsx)(o,{}),t[0]=o,t[1]=s);let c;return t[2]!==a||t[3]!==n||t[4]!==s?(c=(0,b.jsx)(cV,{index:n,archived:a,children:s}),t[2]=a,t[3]=n,t[4]=s,t[5]=c):c=t[5],c},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);aG.displayName=`ThreadListPrimitive.ItemByIndex`;var oG=({archived:e,children:t})=>{let n=$(RF(t=>e?t.threads.archivedThreadIds:t.threads.threadIds));return mN(()=>n.map((n,r)=>(0,b.jsx)(cV,{index:r,archived:e,children:(0,b.jsx)(HL,{getItemState:t=>t.threads.item({index:r,archived:e}).getState(),children:e=>t({get threadListItem(){return e()}})})},n)),[n,e,t])},sG=e=>{let t=J(8),{archived:n,components:r,children:i}=e,a=n!==void 0&&n;if(r){let e=r.ThreadListItem,n;t[0]===e?n=t[1]:(n=()=>(0,b.jsx)(e,{}),t[0]=e,t[1]=n);let i;return t[2]!==a||t[3]!==n?(i=(0,b.jsx)(oG,{archived:a,children:n}),t[2]=a,t[3]=n,t[4]=i):i=t[4],i}let o;return t[5]!==a||t[6]!==i?(o=(0,b.jsx)(oG,{archived:a,children:i}),t[5]=a,t[6]=i,t[7]=o):o=t[7],o};sG.displayName=`ThreadListPrimitive.Items`;var cG=e=>{let{children:t}=e;return $(lG)?t:null};cG.displayName=`MessagePartPrimitive.InProgress`;function lG(e){return e.part.status.type===`running`}var uG=e=>{let t=J(2),{fallback:n}=e,r=$(dG)||n,i;return t[0]===r?i=t[1]:(i=(0,b.jsx)(b.Fragment,{children:r}),t[0]=r,t[1]=i),i};uG.displayName=`ThreadListItemPrimitive.Title`;function dG(e){return e.threadListItem.title}var fG=e=>{let t=J(2),{components:n}=e,r=n.Suggestion,i;return t[0]===r?i=t[1]:(i=(0,b.jsx)(r,{}),t[0]=r,t[1]=i),i},pG=CN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(fG,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(lV,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&e.components.Suggestion===t.components.Suggestion);pG.displayName=`ThreadPrimitive.SuggestionByIndex`;var mG=({children:e})=>{let t=$(e=>e.suggestions.suggestions.length);return mN(()=>t===0?null:Array.from({length:t},(t,n)=>(0,b.jsx)(lV,{index:n,children:(0,b.jsx)(HL,{getItemState:e=>e.suggestions.suggestion({index:n}).getState(),children:t=>e({get suggestion(){return t()}})})},n)),[t,e])},hG=e=>{let t=J(4),{components:n,children:r}=e;if(n){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(mG,{children:()=>(0,b.jsx)(fG,{components:n})}),t[0]=n,t[1]=e),e}let i;return t[2]===r?i=t[3]:(i=(0,b.jsx)(mG,{children:r}),t[2]=r,t[3]=i),i};hG.displayName=`ThreadPrimitive.Suggestions`;var gG=CN(hG,(e,t)=>e.children||t.children?e.children===t.children:e.components.Suggestion===t.components.Suggestion),_G=e=>{let t=J(3),n;return t[0]!==e.dictation||t[1]!==e.editing?(n=t=>{if(e.editing===!0&&!t.composer.isEditing||e.editing===!1&&t.composer.isEditing)return!1;let n=t.composer.dictation!=null;return!(e.dictation===!0&&!n||e.dictation===!1&&n)},t[0]=e.dictation,t[1]=e.editing,t[2]=n):n=t[2],$(n)},vG=e=>{let t=J(3),n,r;return t[0]===e?(n=t[1],r=t[2]):({children:n,...r}=e,t[0]=e,t[1]=n,t[2]=r),_G(r)?n:null};vG.displayName=`ComposerPrimitive.If`;var yG=e=>!e.composer.canSend||e.thread.isRunning&&!e.thread.capabilities.queue,bG=e=>!e.composer.canCancel,xG=e=>e.composer.isEditing||e.optional.thread?.voice!==void 0||e.optional.thread?.capabilities.edit===!1,SG=e=>e.thread.isRunning||e.thread.isDisabled||e.thread.voice!==void 0||e.message.role!==`assistant`||!e.thread.capabilities.reload,CG=e=>e.message.role===`assistant`&&e.message.status?.type===`running`||!e.message.parts.some(e=>e.type===`text`&&e.text.length>0),wG=e=>e.message.branchNumber<=1||!e.thread.capabilities.switchToBranch||e.thread.isRunning&&!e.thread.capabilities.switchBranchDuringRun,TG=e=>e.message.branchNumber>=e.message.branchCount||!e.thread.capabilities.switchToBranch||e.thread.isRunning&&!e.thread.capabilities.switchBranchDuringRun,EG=(e,t)=>e.thread.isDisabled||t&&e.thread.isRunning&&!e.thread.capabilities.queue,DG=e=>{if(e.message.status?.type!==`incomplete`||e.message.status.reason!==`error`)return;let t=e.message.status.error;return typeof t==`string`?t:typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`?t.message:t??`An error occurred`},OG=e=>!e.threads.hasMore||e.threads.isLoading||e.threads.isLoadingMore,kG=()=>{let e=J(5),t=Q(),n=$(yG),r;e[0]===t?r=e[1]:(r=e=>{t.composer.send(e)},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={send:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},AG=()=>{let e=J(5),t=Q(),n=$(bG),r;e[0]===t?r=e[1]:(r=()=>{t.composer.cancel()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==i||e[3]!==n?(a={cancel:i,disabled:n},e[2]=i,e[3]=n,e[4]=a):a=e[4],a},jG=()=>{let e=J(5),t=Q(),n=$(MG),r;e[0]===t?r=e[1]:(r=()=>{t.composer.startDictation()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={startDictation:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a};function MG(e){return e.composer.dictation!=null||!e.thread.capabilities.dictation||!e.composer.isEditing}var NG=()=>{let e=J(5),t=Q(),n=$(PG),r;e[0]===t?r=e[1]:(r=e=>t.composer.addAttachment(e),e[0]=t,e[1]=r);let i=r,a;return e[2]!==i||e[3]!==n?(a={addAttachment:i,disabled:n},e[2]=i,e[3]=n,e[4]=a):a=e[4],a};function PG(e){return!e.composer.isEditing}var FG=e=>{let t=J(15),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{copiedDuration:r,copyToClipboard:i}=n,a=r===void 0?3e3:r,o=Q(),s=$(CG),c=$(IG),l=$(LG),u=$(RG),d=Y(void 0),f=Y(0),p,m;t[2]===o?(p=t[3],m=t[4]):(p=()=>()=>{f.current+=1,d.current!==void 0&&(clearTimeout(d.current),d.current=void 0,o.message.setIsCopied(!1))},m=[o],t[2]=o,t[3]=p,t[4]=m),X(p,m);let h;t[5]!==o||t[6]!==u||t[7]!==a||t[8]!==i||t[9]!==l?(h=()=>{if(!i)return;let e=l?u:o.message.getCopyText();if(!e)return;let t=f.current,n;try{n=i(e)}catch{return}Promise.resolve(n).then(()=>{t===f.current&&(d.current!==void 0&&clearTimeout(d.current),o.message.setIsCopied(!0),d.current=setTimeout(()=>{d.current=void 0,o.message.setIsCopied(!1)},a))},zG)},t[5]=o,t[6]=u,t[7]=a,t[8]=i,t[9]=l,t[10]=h):h=t[10];let g=h,_=s||!i,v;return t[11]!==g||t[12]!==c||t[13]!==_?(v={copy:g,disabled:_,isCopied:c},t[11]=g,t[12]=c,t[13]=_,t[14]=v):v=t[14],v};function IG(e){return e.message.isCopied}function LG(e){return e.composer.isEditing}function RG(e){return e.composer.text}function zG(){}var BG=()=>{let e=J(5),t=Q(),n=$(xG),r;e[0]===t?r=e[1]:(r=()=>{t.composer.beginEdit()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={edit:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},VG=()=>{let e=J(5),t=Q(),n=$(SG),r;e[0]===t?r=e[1]:(r=()=>{t.message.reload()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={reload:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},HG=()=>{let e=J(5),t=Q(),n=$(WG),r;e[0]===t?r=e[1]:(r=()=>{t.message.submitFeedback({type:`positive`})},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={submit:i,isSubmitted:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},UG=()=>{let e=J(5),t=Q(),n=$(GG),r;e[0]===t?r=e[1]:(r=()=>{t.message.submitFeedback({type:`negative`})},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={submit:i,isSubmitted:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a};function WG(e){return e.message.metadata.submittedFeedback?.type===`positive`}function GG(e){return e.message.metadata.submittedFeedback?.type===`negative`}var KG=()=>{let e=J(5),t=Q(),n=$(JG),r;e[0]===t?r=e[1]:(r=async()=>{t.message.speak()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={speak:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a};function qG(e){return e.type===`text`&&e.text.length>0}function JG(e){return e.message.role===`assistant`&&e.message.status?.type===`running`||!e.message.parts.some(qG)}var YG=()=>{let e=J(5),t=Q(),n=$(XG),r;e[0]===t?r=e[1]:(r=()=>{t.message.stopSpeaking()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={stopSpeaking:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a};function XG(e){return e.message.speech==null}var ZG=()=>{let e=J(5),t=Q(),n=$(TG),r;e[0]===t?r=e[1]:(r=()=>{t.message.switchToBranch({position:`next`})},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={next:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},QG=()=>{let e=J(5),t=Q(),n=$(wG),r;e[0]===t?r=e[1]:(r=()=>{t.message.switchToBranch({position:`previous`})},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={previous:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},$G=e=>{let t=J(10),{prompt:n,send:r,clearComposer:i}=e,a=i===void 0||i,o=Q(),s=r??!1,c;t[0]===s?c=t[1]:(c=e=>EG(e,s),t[0]=s,t[1]=c);let l=$(c),u;t[2]!==o||t[3]!==a||t[4]!==n||t[5]!==s?(u=()=>{if(s){let{isRunning:e,capabilities:t}=o.thread.getState();if(e&&!t.queue)return;o.thread.append({content:[{type:`text`,text:n}],runConfig:o.composer.getState().runConfig}),a&&!e&&o.composer.setText(``)}else if(a)o.composer.setText(n);else{let e=o.composer.getState().text;o.composer.setText([e,n].filter(eK).join(` `))}},t[2]=o,t[3]=a,t[4]=n,t[5]=s,t[6]=u):u=t[6];let d=u,f;return t[7]!==l||t[8]!==d?(f={trigger:d,disabled:l},t[7]=l,t[8]=d,t[9]=f):f=t[9],f};function eK(e){return e.trim()}var tK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threadListItem.archive()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={archive:r},e[2]=r,e[3]=i),i},nK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threadListItem.delete()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={delete:r},e[2]=r,e[3]=i),i},rK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threadListItem.unarchive()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={unarchive:r},e[2]=r,e[3]=i),i},iK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threadListItem.switchTo()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={switchTo:r},e[2]=r,e[3]=i),i},aK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threads.switchToNewThread()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={switchToNewThread:r},e[2]=r,e[3]=i),i},oK=()=>{let e=J(5),t=Q(),n=$(OG),r;e[0]===t?r=e[1]:(r=()=>{t.threads.loadMore()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={loadMore:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},sK=()=>$(DG),cK=e=>{let{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:a,unstable_enableMessageQueue:o,unstable_queueClearOnRewind:s,unstable_queueClearOnCancel:c,...l}=e;return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:a,unstable_enableMessageQueue:o,unstable_queueClearOnRewind:s,unstable_queueClearOnCancel:c},otherOptions:l}};function lK(e,t){function n(n){let r=AN(e);if(!n?.optional&&!r)throw Error(`This component must be used within ${t}.`);return r}return n}function uK(e,t){function n(n){let r=e(n);return r?r[t]:null}function r(e){let t=!1,r;typeof e==`function`?r=e:e&&typeof e==`object`&&(t=!!e.optional,r=e.selector);let i=n({optional:t});return i?r?i(r):i():null}return{[t]:r,[`${t}Store`]:n}}var dK=ON(null),{useThreadViewport:fK,useThreadViewportStore:pK}=uK(lK(dK,`ThreadPrimitive.Viewport`),`useThreadViewport`),mK=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},hK=(e=>e?mK(e):mK),gK=e=>e;function _K(e,t=gK){let n=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(n),n}var vK=e=>{let t=hK(e),n=e=>_K(t,e);return Object.assign(n,t),n},yK=(e=>e?vK(e):vK),bK=e=>{let t=new Map,n=()=>{let n=0;for(let e of t.values())n+=e;e(n)};return{register:()=>{let e=Symbol();return t.set(e,0),{setHeight:r=>{t.get(e)!==r&&(t.set(e,r),n())},unregister:()=>{t.delete(e),n()}}}}},xK=(e={})=>{let t=new Set,n=bK(e=>{a.setState({height:{...a.getState().height,viewport:e}})}),r=bK(e=>{a.setState({height:{...a.getState().height,inset:e}})}),i=(e,t)=>(a.setState({element:{...a.getState().element,[e]:t}}),()=>{a.getState().element[e]===t&&a.setState({element:{...a.getState().element,[e]:null}})}),a=yK(()=>({isAtBottom:!0,scrollToBottom:({behavior:e=`auto`}={})=>{AP(t,()=>({behavior:e}),`Thread viewport`)},onScrollToBottom:e=>(t.add(e),()=>{t.delete(e)}),turnAnchor:e.turnAnchor??`bottom`,topAnchorMessageClamp:{tallerThan:e.topAnchorMessageClamp?.tallerThan??`10em`,visibleHeight:e.topAnchorMessageClamp?.visibleHeight??`6em`},height:{viewport:0,inset:0},element:{viewport:null,anchor:null,target:null},targetConfig:null,topAnchorTurn:null,registerViewport:n.register,registerContentInset:r.register,registerViewportElement:e=>i(`viewport`,e),registerAnchorElement:e=>i(`anchor`,e),registerAnchorTargetElement:(e,t)=>(a.setState({element:{...a.getState().element,target:e},targetConfig:e&&t?t:null}),()=>{a.getState().element.target===e&&a.setState({element:{...a.getState().element,target:null},targetConfig:null})}),setTopAnchorTurn:e=>{a.setState({topAnchorTurn:e})}}));return a},SK=e=>e,CK=e=>{let t=J(11),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n={optional:!0},t[0]=n):n=t[0];let r=pK(n),i;t[1]===e?i=t[2]:(i=()=>xK(e),t[1]=e,t[2]=i);let[a]=fN(i),o,s;t[3]!==r||t[4]!==a?(o=()=>r?.getState().onScrollToBottom(e=>{a.getState().scrollToBottom(e)}),s=[r,a],t[3]=r,t[4]=a,t[5]=o,t[6]=s):(o=t[5],s=t[6]),X(o,s);let c,l;return t[7]!==r||t[8]!==a?(c=()=>{if(r)return a.subscribe(e=>{r.getState().isAtBottom!==e.isAtBottom&&SK(r).setState({isAtBottom:e.isAtBottom})})},l=[a,r],t[7]=r,t[8]=a,t[9]=c,t[10]=l):(c=t[9],l=t[10]),X(c,l),a},wK=e=>{let t=J(7),{children:n,options:r}=e,i;t[0]===r?i=t[1]:(i=r===void 0?{}:r,t[0]=r,t[1]=i);let a=CK(i),o;t[2]===a?o=t[3]:(o=()=>({useThreadViewport:a}),t[2]=a,t[3]=o);let[s]=fN(o),c;return t[4]!==n||t[5]!==s?(c=(0,b.jsx)(dK.Provider,{value:s,children:n}),t[4]=n,t[5]=s,t[6]=c):c=t[6],c},TK=()=>{let e=J(3),t=Q(),n,r;return e[0]===t?(n=e[1],r=e[2]):(n=()=>{},r=[t],e[0]=t,e[1]=n,e[2]=r),X(n,r),null},EK=CN(e=>{let t=J(8),{children:n,aui:r,config:i,runtime:a}=e,o=r??null,s;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,b.jsx)(TK,{}),t[0]=s):s=t[0];let c;t[1]===n?c=t[2]:(c=(0,b.jsx)(wK,{children:n}),t[1]=n,t[2]=c);let l;return t[3]!==i||t[4]!==a||t[5]!==o||t[6]!==c?(l=(0,b.jsxs)(qL,{runtime:a,aui:o,config:i,children:[s,c]}),t[3]=i,t[4]=a,t[5]=o,t[6]=c,t[7]=l):l=t[7],l}),DK=/:([\w-]{1,64})\[([^\]\n]{1,1024})\](?:\{name=([^}\n]{1,1024})\})?/gu,OK={serialize(e){let t=e.id===e.label?``:`{name=${e.id}}`;return`:${e.type}[${e.label}]${t}`},parse(e){let t=[],n=0;for(let r of e.matchAll(DK)){r.index>n&&t.push({kind:`text`,text:e.slice(n,r.index)});let i=r[2];t.push({kind:`mention`,type:r[1],label:i,id:r[3]??i}),n=r.index+r[0].length}return n<e.length&&t.push({kind:`text`,text:e.slice(n)}),t}},kK=Object.defineProperty,AK=(e,t)=>kK(e,`name`,{value:t,configurable:!0});function jK(e,t=globalThis?.document){let n=dt(e);y.useEffect(()=>{let e=AK(e=>{e.key===`Escape`&&n(e)},`handleKeyDown`);return t.addEventListener(`keydown`,e,{capture:!0}),()=>t.removeEventListener(`keydown`,e,{capture:!0})},[n,t])}AK(jK,`useEscapeKeydown`);var MK=d;MK.dispatchDiscreteCustomEvent=_,MK.Root=d;var NK=Object.defineProperty,PK=(e,t)=>{let n={};for(var r in e)NK(n,r,{get:e[r],enumerable:!0});return t||NK(n,Symbol.toStringTag,{value:`Module`}),n},FK=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`];function IK(e,t){return EN(e,void 0,t===void 0?e.props.children:t)}function LK(e,t,n){return(0,b.jsx)(s,{...n,children:IK(e,t)})}function RK(e){let t=Z((t,n)=>{let r=J(17),i,a,o,s;r[0]===t?(i=r[1],a=r[2],o=r[3],s=r[4]):({render:o,asChild:i,children:a,...s}=t,r[0]=t,r[1]=i,r[2]=a,r[3]=o,r[4]=s);let c=e;if(o&&DN(o)){let e=s,t;r[5]!==a||r[6]!==o?(t=IK(o,a),r[5]=a,r[6]=o,r[7]=t):t=r[7];let i;return r[8]!==n||r[9]!==e||r[10]!==t?(i=(0,b.jsx)(c,{...e,asChild:!0,ref:n,children:t}),r[8]=n,r[9]=e,r[10]=t,r[11]=i):i=r[11],i}let l=s,u;return r[12]!==i||r[13]!==a||r[14]!==n||r[15]!==l?(u=(0,b.jsx)(c,{...l,asChild:i,ref:n,children:a}),r[12]=i,r[13]=a,r[14]=n,r[15]=l,r[16]=u):u=r[16],u});return t.displayName=typeof e==`string`?e:e.displayName??e.name??`Component`,t}function zK(e){let t=MK[e],n=RK(t);return n.displayName=`Primitive.${e}`,n}var BK=FK.reduce((e,t)=>(e[t]=zK(t),e),{}),VK={Hidden:`hidden`,Floating:`floating`,Normal:`normal`},HK=e=>{let t=J(5),{hideWhenRunning:n,autohide:r,autohideFloat:i,forceVisible:a}=e,o;return t[0]!==r||t[1]!==i||t[2]!==a||t[3]!==n?(o=e=>{if(n&&e.thread.isRunning)return VK.Hidden;let t=r===`always`||r===`not-last`&&!e.message.isLast,o=a||e.message.isHovering;return t?o?i===`always`||i===`single-branch`&&e.message.branchCount<=1?VK.Floating:VK.Normal:VK.Hidden:VK.Normal},t[0]=r,t[1]=i,t[2]=a,t[3]=n,t[4]=o):o=t[4],$(o)},UK=ON(null),WK=()=>AN(UK),GK=Z((e,t)=>{let n=J(18),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({hideWhenRunning:a,autohide:r,autohideFloat:i,...o}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let[s,c]=fN(0),l;n[5]===Symbol.for(`react.memo_cache_sentinel`)?(l=()=>{let e=!1;return c(KK),()=>{e||(e=!0,c(qK))}},n[5]=l):l=n[5];let u=l,d;n[6]===Symbol.for(`react.memo_cache_sentinel`)?(d={acquireInteractionLock:u},n[6]=d):d=n[6];let f=d,p=s>0,m;n[7]!==r||n[8]!==i||n[9]!==a||n[10]!==p?(m={hideWhenRunning:a,autohide:r,autohideFloat:i,forceVisible:p},n[7]=r,n[8]=i,n[9]=a,n[10]=p,n[11]=m):m=n[11];let h=HK(m);if(h===VK.Hidden)return null;let g;n[12]===h?g=n[13]:(g=h===VK.Floating?{"data-floating":`true`}:null,n[12]=h,n[13]=g);let _;return n[14]!==t||n[15]!==o||n[16]!==g?(_=(0,b.jsx)(UK.Provider,{value:f,children:(0,b.jsx)(BK.div,{...g,...o,ref:t})}),n[14]=t,n[15]=o,n[16]=g,n[17]=_):_=n[17],_});GK.displayName=`ActionBarPrimitive.Root`;function KK(e){return e+1}function qK(e){return Math.max(0,e-1)}var JK=e=>{let t=J(4),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{copiedDuration:r}=n,i=r===void 0?3e3:r,a;t[2]===i?a=t[3]:(a={copiedDuration:i,copyToClipboard:XK},t[2]=i,t[3]=a);let{copy:o,disabled:s}=FG(a);return s?null:o},YK=Z((e,t)=>{let n=J(20),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({copiedDuration:r,onClick:a,disabled:i,...o}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let s=$(ZK),c;n[5]===r?c=n[6]:(c={copiedDuration:r},n[5]=r,n[6]=c);let l=JK(c),u;n[7]===s?u=n[8]:(u=s?{"data-copied":`true`}:{},n[7]=s,n[8]=u);let d=i||!l,f;n[9]===l?f=n[10]:(f=()=>{l?.()},n[9]=l,n[10]=f);let p;n[11]!==a||n[12]!==f?(p=P(a,f),n[11]=a,n[12]=f,n[13]=p):p=n[13];let m;return n[14]!==t||n[15]!==o||n[16]!==u||n[17]!==d||n[18]!==p?(m=(0,b.jsx)(BK.button,{type:`button`,...u,...o,ref:t,disabled:d,onClick:p}),n[14]=t,n[15]=o,n[16]=u,n[17]=d,n[18]=p,n[19]=m):m=n[19],m});YK.displayName=`ActionBarPrimitive.Copy`;function XK(e){return typeof navigator>`u`||!navigator.clipboard?Promise.reject(Error(`Clipboard API is unavailable`)):navigator.clipboard.writeText(e)}function ZK(e){return e.message.isCopied}var QK=(e,t,n=[])=>{let r=Z((e,r)=>{let i=J(6),a={},o={};Object.keys(e).forEach(t=>{n.includes(t)?a[t]=e[t]:o[t]=e[t]});let s=t(a)??void 0,c=BK,l=o.disabled||!s,u=P(o.onClick,s),d;return i[0]!==r||i[1]!==o||i[2]!==c.button||i[3]!==l||i[4]!==u?(d=(0,b.jsx)(c.button,{type:`button`,...o,ref:r,disabled:l,onClick:u}),i[0]=r,i[1]=o,i[2]=c.button,i[3]=l,i[4]=u,i[5]=d):d=i[5],d});return r.displayName=e,r},$K=QK(`ActionBarPrimitive.Reload`,()=>{let{disabled:e,reload:t}=VG();return e?null:t}),eq=QK(`ActionBarPrimitive.Edit`,()=>{let{disabled:e,edit:t}=BG();return e?null:t}),tq=QK(`ActionBarPrimitive.Speak`,()=>{let{disabled:e,speak:t}=KG();return e?null:t}),nq=()=>{let{disabled:e,stopSpeaking:t}=YG();return e?null:t},rq=Z((e,t)=>{let n=J(10),r=nq(),i=!r,a;n[0]===r?a=n[1]:(a=()=>{r?.()},n[0]=r,n[1]=a);let o;n[2]!==e.onClick||n[3]!==a?(o=P(e.onClick,a),n[2]=e.onClick,n[3]=a,n[4]=o):o=n[4];let s;return n[5]!==e||n[6]!==t||n[7]!==i||n[8]!==o?(s=(0,b.jsx)(BK.button,{type:`button`,disabled:i,...e,ref:t,onClick:o}),n[5]=e,n[6]=t,n[7]=i,n[8]=o,n[9]=s):s=n[9],s});rq.displayName=`ActionBarPrimitive.StopSpeaking`;var iq=()=>{let{submit:e}=HG();return e},aq=Z((e,t)=>{let n=J(17),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({onClick:i,disabled:r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let o=$(oq),s=iq(),c;n[4]===o?c=n[5]:(c=o?{"data-submitted":`true`}:{},n[4]=o,n[5]=c);let l=r||!s,u;n[6]===s?u=n[7]:(u=()=>{s?.()},n[6]=s,n[7]=u);let d;n[8]!==i||n[9]!==u?(d=P(i,u),n[8]=i,n[9]=u,n[10]=d):d=n[10];let f;return n[11]!==t||n[12]!==a||n[13]!==c||n[14]!==l||n[15]!==d?(f=(0,b.jsx)(BK.button,{type:`button`,...c,...a,ref:t,disabled:l,onClick:d}),n[11]=t,n[12]=a,n[13]=c,n[14]=l,n[15]=d,n[16]=f):f=n[16],f});aq.displayName=`ActionBarPrimitive.FeedbackPositive`;function oq(e){return e.message.metadata.submittedFeedback?.type===`positive`}var sq=()=>{let{submit:e}=UG();return e},cq=Z((e,t)=>{let n=J(17),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({onClick:i,disabled:r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let o=$(lq),s=sq(),c;n[4]===o?c=n[5]:(c=o?{"data-submitted":`true`}:{},n[4]=o,n[5]=c);let l=r||!s,u;n[6]===s?u=n[7]:(u=()=>{s?.()},n[6]=s,n[7]=u);let d;n[8]!==i||n[9]!==u?(d=P(i,u),n[8]=i,n[9]=u,n[10]=d):d=n[10];let f;return n[11]!==t||n[12]!==a||n[13]!==c||n[14]!==l||n[15]!==d?(f=(0,b.jsx)(BK.button,{type:`button`,...c,...a,ref:t,disabled:l,onClick:d}),n[11]=t,n[12]=a,n[13]=c,n[14]=l,n[15]=d,n[16]=f):f=n[16],f});cq.displayName=`ActionBarPrimitive.FeedbackNegative`;function lq(e){return e.message.metadata.submittedFeedback?.type===`negative`}var uq=e=>{let t=J(6),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{filename:r,onExport:i}=n,a=Q(),o=$(pq),s;return t[2]!==a.message||t[3]!==r||t[4]!==i?(s=async()=>{let e=a.message.getCopyText();if(!e)return;if(i){await i(e);return}let t=new Blob([e],{type:`text/markdown`}),n=URL.createObjectURL(t),o=document.createElement(`a`);o.href=n,o.download=r??`message-${Date.now()}.md`,o.click(),setTimeout(()=>URL.revokeObjectURL(n),4e4)},t[2]=a.message,t[3]=r,t[4]=i,t[5]=s):s=t[5],o?s:null},dq=Z((e,t)=>{let n=J(19),r,i,a,o,s;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],s=n[5]):({filename:i,onExport:o,onClick:a,disabled:r,...s}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=s);let c;n[6]!==i||n[7]!==o?(c={filename:i,onExport:o},n[6]=i,n[7]=o,n[8]=c):c=n[8];let l=uq(c),u=r||!l,d;n[9]===l?d=n[10]:(d=()=>{l?.().catch(mq)},n[9]=l,n[10]=d);let f;n[11]!==a||n[12]!==d?(f=P(a,d),n[11]=a,n[12]=d,n[13]=f):f=n[13];let p;return n[14]!==t||n[15]!==s||n[16]!==u||n[17]!==f?(p=(0,b.jsx)(BK.button,{type:`button`,...s,ref:t,disabled:u,onClick:f}),n[14]=t,n[15]=s,n[16]=u,n[17]=f,n[18]=p):p=n[18],p});dq.displayName=`ActionBarPrimitive.ExportMarkdown`;function fq(e){return e.type===`text`&&e.text.length>0}function pq(e){return(e.message.role!==`assistant`||e.message.status?.type!==`running`)&&e.message.parts.some(fq)}function mq(e){console.error(`[assistant-ui] markdown export failed:`,e)}var hq=PK({Copy:()=>YK,Edit:()=>eq,ExportMarkdown:()=>dq,FeedbackNegative:()=>cq,FeedbackPositive:()=>aq,Reload:()=>$K,Root:()=>GK,Speak:()=>tq,StopSpeaking:()=>rq}),gq=ul(),_q=e=>{let t=J(25),n,r,i,a;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4]):({__scopeActionBarMore:n,open:i,onOpenChange:r,...a}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a);let o=gq(n),s=WK(),c=Y(null),l=i!==void 0,u;t[5]===s?u=t[6]:(u=e=>{if(e){if(c.current)return;c.current=s?.acquireInteractionLock()??null;return}c.current?.(),c.current=null},t[5]=s,t[6]=u);let d=u,f;t[7]!==l||t[8]!==r||t[9]!==d?(f=e=>{l||d(e),r?.(e)},t[7]=l,t[8]=r,t[9]=d,t[10]=f):f=t[10];let p=f,m,h;t[11]!==l||t[12]!==i||t[13]!==d?(m=()=>{l&&d(!!i)},h=[l,i,d],t[11]=l,t[12]=i,t[13]=d,t[14]=m,t[15]=h):(m=t[14],h=t[15]),X(m,h);let g,_;t[16]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>()=>{c.current?.(),c.current=null},_=[],t[16]=g,t[17]=_):(g=t[16],_=t[17]),X(g,_);let v;t[18]===i?v=t[19]:(v=i===void 0?null:{open:i},t[18]=i,t[19]=v);let y;return t[20]!==p||t[21]!==a||t[22]!==o||t[23]!==v?(y=(0,b.jsx)(Ml,{...o,...a,...v,onOpenChange:p}),t[20]=p,t[21]=a,t[22]=o,t[23]=v,t[24]=y):y=t[24],y};_q.displayName=`ActionBarMorePrimitive.Root`;var vq=RK(Nl),yq=RK(Fl),bq=RK(Rl),xq=RK(Ul),Sq=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeActionBarMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=gq(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(vq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});Sq.displayName=`ActionBarMorePrimitive.Trigger`;var Cq=Z((e,t)=>{let n=J(14),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({__scopeActionBarMore:r,portalProps:i,sideOffset:o,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let s=o===void 0?4:o,c=gq(r),l;n[5]!==t||n[6]!==a||n[7]!==c||n[8]!==s?(l=(0,b.jsx)(yq,{...c,...a,ref:t,sideOffset:s}),n[5]=t,n[6]=a,n[7]=c,n[8]=s,n[9]=l):l=n[9];let u;return n[10]!==i||n[11]!==c||n[12]!==l?(u=(0,b.jsx)(Pl,{...c,...i,children:l}),n[10]=i,n[11]=c,n[12]=l,n[13]=u):u=n[13],u});Cq.displayName=`ActionBarMorePrimitive.Content`;var wq=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeActionBarMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=gq(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(bq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});wq.displayName=`ActionBarMorePrimitive.Item`;var Tq=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeActionBarMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=gq(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(xq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});Tq.displayName=`ActionBarMorePrimitive.Separator`;var Eq=PK({Content:()=>Cq,Item:()=>wq,Root:()=>_q,Separator:()=>Tq,Trigger:()=>Sq}),Dq=Z((e,t)=>{let n=J(3),r;return n[0]!==e||n[1]!==t?(r=(0,b.jsx)(BK.div,{...e,ref:t}),n[0]=e,n[1]=t,n[2]=r):r=n[2],r});Dq.displayName=`AttachmentPrimitive.Root`;var Oq=Z((e,t)=>{let n=J(4),r=$(kq),i=e.children??r,a;return n[0]!==e||n[1]!==t||n[2]!==i?(a=(0,b.jsx)(BK.div,{...e,ref:t,children:i}),n[0]=e,n[1]=t,n[2]=i,n[3]=a):a=n[3],a});Oq.displayName=`AttachmentPrimitive.unstable_Thumb`;function kq(e){let t=e.attachment.name,n=t.lastIndexOf(`.`);return n>0&&n<t.length-1?`.${t.slice(n+1)}`:e.attachment.type}var Aq=()=>{let e=J(2),t=$(jq),n;return e[0]===t?n=e[1]:(n=(0,b.jsx)(b.Fragment,{children:t}),e[0]=t,e[1]=n),n};Aq.displayName=`AttachmentPrimitive.Name`;function jq(e){return e.attachment.name}var Mq=QK(`AttachmentPrimitive.Remove`,()=>{let e=J(2),t=Q(),n;return e[0]===t.attachment?n=e[1]:(n=()=>{t.attachment.remove()},e[0]=t.attachment,e[1]=n),n}),Nq=PK({Name:()=>Aq,Remove:()=>Mq,Root:()=>Dq,unstable_Thumb:()=>Oq}),Pq=QK(`BranchPickerPrimitive.Next`,()=>{let{disabled:e,next:t}=ZG();return e?null:t}),Fq=QK(`BranchPickerPrimitive.Previous`,()=>{let{disabled:e,previous:t}=QG();return e?null:t}),Iq=()=>$(Rq),Lq=()=>{let e=J(2),t=Iq(),n;return e[0]===t?n=e[1]:(n=(0,b.jsx)(b.Fragment,{children:t}),e[0]=t,e[1]=n),n};Lq.displayName=`BranchPickerPrimitive.Count`;function Rq(e){return e.message.branchCount}var zq=()=>$(Vq),Bq=()=>{let e=J(2),t=zq(),n;return e[0]===t?n=e[1]:(n=(0,b.jsx)(b.Fragment,{children:t}),e[0]=t,e[1]=n),n};Bq.displayName=`BranchPickerPrimitive.Number`;function Vq(e){return e.message.branchNumber}var Hq=Z((e,t)=>{let n=J(11),r,i;n[0]===e?(r=n[1],i=n[2]):({hideWhenSingleBranch:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===r?a=n[4]:(a=e=>!r||e.message.branchCount>=2,n[3]=r,n[4]=a);let o;n[5]!==t||n[6]!==i?(o=(0,b.jsx)(BK.div,{...i,ref:t}),n[5]=t,n[6]=i,n[7]=o):o=n[7];let s;return n[8]!==a||n[9]!==o?(s=(0,b.jsx)(IL,{condition:a,children:o}),n[8]=a,n[9]=o,n[10]=s):s=n[10],s});Hq.displayName=`BranchPickerPrimitive.Root`;var Uq=PK({Count:()=>Lq,Next:()=>Pq,Number:()=>Bq,Previous:()=>Fq,Root:()=>Hq}),Wq=ON(null),Gq=()=>AN(Wq),Kq=e=>{let t=J(8),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=new Map,t[0]=r):r=t[0];let i=Y(r),a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=[],t[1]=a):a=t[1];let o=Y(a),s;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(s=()=>{let e=Array.from(i.current.entries());e.sort(qq),o.current=e.map(Jq)},t[2]=s):s=t[2];let c=s,l;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(l=(e,t)=>{let n=t?.priority??0;return i.current.set(e,n),c(),()=>{i.current.delete(e),c()}},t[3]=l):l=t[3];let u=l,d;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(d=()=>o.current,t[4]=d):d=t[4];let f=d,p;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(p={register:u,getPlugins:f},t[5]=p):p=t[5];let m=p,h;return t[6]===n?h=t[7]:(h=(0,b.jsx)(Wq.Provider,{value:m,children:n}),t[6]=n,t[7]=h),h};function qq(e,t){return t[1]-e[1]}function Jq(e){let[t]=e;return t}var Yq=ON(null),Xq=ON(null),Zq=()=>{let e=AN(Yq);if(!e)throw Error(`useTriggerPopoverRootContext must be used within ComposerPrimitive.TriggerPopoverRoot`);return e},Qq=()=>AN(Yq),$q=()=>{let e=AN(Xq);if(!e)throw Error(`useTriggerPopoverAriaPublish must be used within ComposerPrimitive.TriggerPopoverRoot`);return e},eJ=()=>{let e=Zq();return vN(e.subscribe,e.getTriggers,e.getTriggers)},tJ=new Map,nJ=()=>()=>{},rJ=()=>tJ,iJ=()=>{let e=Qq();return vN(e?e.subscribe:nJ,e?e.getTriggers:rJ,e?e.getTriggers:rJ)},aJ=()=>null,oJ=()=>{let e=Qq();return vN(e?e.subscribeAria:nJ,e?e.getActiveAria:aJ,e?e.getActiveAria:aJ)};function sJ(){let e=J(4),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=new Set,e[0]=t):t=e[0];let n=Y(t),r;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{for(let e of n.current)e()},e[1]=r):r=e[1];let i=r,a;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(a=e=>(n.current.add(e),()=>{n.current.delete(e)}),e[2]=a):a=e[2];let o=a,s;return e[3]===Symbol.for(`react.memo_cache_sentinel`)?(s={notify:i,subscribe:o},e[3]=s):s=e[3],s}var cJ=e=>{let t=J(21),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=new Map,t[0]=r):r=t[0];let i=Y(r),a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=new Set,t[1]=a):a=t[1];let o=Y(a),{notify:s,subscribe:c}=sJ(),l;t[2]===s?l=t[3]:(l=e=>{let{char:t}=e;if(i.current.has(t))return uJ;let n=new Map(i.current);n.set(t,e),i.current=n,s();for(let t of o.current)t.added(e);return()=>{let e=new Map(i.current);e.delete(t),i.current=e,s();for(let e of o.current)e.removed(t)}},t[2]=s,t[3]=l);let u=l,d;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(d=()=>i.current,t[4]=d):d=t[4];let f=d,p;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(p=e=>(o.current.add(e),()=>{o.current.delete(e)}),t[5]=p):p=t[5];let m=p,h=Y(null),g=Y(null),{notify:_,subscribe:v}=sJ(),y;t[6]===_?y=t[7]:(y=(e,t)=>{if(t===null){if(g.current!==e)return;h.current=null,g.current=null,_();return}let n=h.current;(g.current!==e||n===null||n.popoverId!==t.popoverId||n.highlightedItemId!==t.highlightedItemId)&&(h.current=t,g.current=e,_())},t[6]=_,t[7]=y);let x=y,S;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(S=()=>h.current,t[8]=S):S=t[8];let C=S,w;t[9]!==u||t[10]!==c||t[11]!==v?(w={register:u,getTriggers:f,subscribe:c,subscribeLifecycle:m,getActiveAria:C,subscribeAria:v},t[9]=u,t[10]=c,t[11]=v,t[12]=w):w=t[12];let T=w,E;t[13]===x?E=t[14]:(E={setActiveAria:x},t[13]=x,t[14]=E);let D=E,O;t[15]!==D||t[16]!==n?(O=(0,b.jsx)(Xq.Provider,{value:D,children:n}),t[15]=D,t[16]=n,t[17]=O):O=t[17];let k;return t[18]!==O||t[19]!==T?(k=(0,b.jsx)(Yq.Provider,{value:T,children:O}),t[18]=O,t[19]=T,t[20]=k):k=t[20],k},lJ=e=>{let t=J(4),{children:n}=e;if(Gq()){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(cJ,{children:n}),t[0]=n,t[1]=e),e}let r;return t[2]===n?r=t[3]:(r=(0,b.jsx)(Kq,{children:(0,b.jsx)(cJ,{children:n})}),t[2]=n,t[3]=r),r};lJ.displayName=`ComposerPrimitive.TriggerPopoverRoot`;function uJ(){}var dJ=/\s/u;function fJ(e,t,n,r){if(r===null)return null;let{query:i,offset:a,endOffset:o}=r;return a<0||a+t.length>n||!e.startsWith(t,a)||o<a+t.length||o>e.length?null:{query:i,offset:a,endOffset:o}}function pJ(e,t,n,r){if(r)return fJ(e,t,n,r(e,t,n));let i=e.slice(0,n);for(let e=i.length-1;e>=0;e--){let r=i[e];if(dJ.test(r))return null;if(i.startsWith(t,e)){if(e>0&&!dJ.test(i[e-1]))continue;return{query:i.slice(e+t.length),offset:e,endOffset:n}}}return null}var mJ=jN(e=>{let t=J(8),{text:n,triggerChar:r,matcher:i}=e,[a,o]=fN(n.length),s=Math.min(a,n.length),c;t[0]!==i||t[1]!==s||t[2]!==n||t[3]!==r?(c=pJ(n,r,s,i),t[0]=i,t[1]=s,t[2]=n,t[3]=r,t[4]=c):c=t[4];let l=c,u=l?.query??``,d;return t[5]!==u||t[6]!==l?(d={trigger:l,query:u,setCursorPosition:o},t[5]=u,t[6]=l,t[7]=d):d=t[7],d});function hJ(e){return`type`in e}var gJ=jN(e=>{let t=J(22),{navigableList:n,isSearchMode:r,activeCategoryId:i,query:a,popoverId:o,open:s,selectItem:c,selectCategory:l,goBack:u,close:d}=e,[f,p]=fN(0),m;t[0]!==i||t[1]!==r||t[2]!==n?(m={navigableList:n,isSearchMode:r,activeCategoryId:i},t[0]=i,t[1]=r,t[2]=n,t[3]=m):m=t[3];let[h,g]=fN(m);(h.navigableList!==n||h.isSearchMode!==r||h.activeCategoryId!==i)&&(g({navigableList:n,isSearchMode:r,activeCategoryId:i}),p(0));let _;t[4]!==f||t[5]!==n.length?(_=e=>{e<0||e>=n.length||e!==f&&p(e)},t[4]=f,t[5]=n.length,t[6]=_):_=t[6];let v=_N(_),y;t[7]!==i||t[8]!==d||t[9]!==u||t[10]!==f||t[11]!==n||t[12]!==s||t[13]!==a||t[14]!==l||t[15]!==c?(y=e=>{if(!s)return!1;switch(e.key){case`ArrowDown`:return e.preventDefault(),p(e=>{let t=n.length;return t===0?0:e<t-1?e+1:0}),!0;case`ArrowUp`:return e.preventDefault(),p(e=>{let t=n.length;return t===0?0:e>0?e-1:t-1}),!0;case`Enter`:case`Tab`:{if(e.shiftKey)return!1;e.preventDefault();let t=n[f];return t&&(hJ(t)?c(t):l(t.id)),!0}case`Escape`:return e.preventDefault(),d(),!0;case`Backspace`:return i&&a===``?(e.preventDefault(),u(),!0):!1;default:return!1}},t[7]=i,t[8]=d,t[9]=u,t[10]=f,t[11]=n,t[12]=s,t[13]=a,t[14]=l,t[15]=c,t[16]=y):y=t[16];let b=_N(y),x=n[f],S=s&&x?`${o}-option-${x.id}`:void 0,C;return t[17]!==b||t[18]!==v||t[19]!==f||t[20]!==S?(C={highlightedIndex:f,highlightedItemId:S,highlightIndex:v,handleKeyDown:b},t[17]=b,t[18]=v,t[19]=f,t[20]=S,t[21]=C):C=t[21],C});function _J(e,t){return!t||e.id.toLowerCase().includes(t)||e.label.toLowerCase().includes(t)||(e.description?.toLowerCase().includes(t)??!1)}var vJ=jN(e=>{let t=J(35),{adapter:n,query:r,open:i}=e,[a,o]=fN(null),[s,c]=fN(i);s!==i&&(c(i),i||o(null));let l;bb0:{if(!i||!n){let e;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[0]=e):e=t[0],l=e;break bb0}let e;t[1]===n?e=t[2]:(e=n.categories(),t[1]=n,t[2]=e),l=e}let u=l,d=i?a:null,f;bb1:{if(!d||!n){let e;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[3]=e):e=t[3],f=e;break bb1}let e;t[4]!==n||t[5]!==d?(e=n.categoryItems(d),t[4]=n,t[5]=d,t[6]=e):e=t[6],f=e}let p=f,m;bb2:{if(!i||!n||d){m=null;break bb2}if(!r&&u.length>0){m=null;break bb2}if(n.search){let e;t[7]!==n||t[8]!==r?(e=n.search(r),t[7]=n,t[8]=r,t[9]=e):e=t[9],m=e;break bb2}let e;if(t[10]!==n||t[11]!==u||t[12]!==r){e=[];let i=r.toLowerCase();for(let t of u)for(let r of n.categoryItems(t.id))_J(r,i)&&e.push(r);t[10]=n,t[11]=u,t[12]=r,t[13]=e}else e=t[13];m=e}let h=m,g=h!==null,_;bb3:{if(g){let e;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[14]=e):e=t[14],_=e;break bb3}if(!r){_=u;break bb3}let e;if(t[15]!==u||t[16]!==r){let n=r.toLowerCase();e=u.filter(e=>e.label.toLowerCase().includes(n)),t[15]=u,t[16]=r,t[17]=e}else e=t[17];_=e}let v=_,y;bb4:{if(g){let e;t[18]===h?e=t[19]:(e=h??[],t[18]=h,t[19]=e),y=e;break bb4}if(!r){y=p;break bb4}let e;if(t[20]!==p||t[21]!==r){let n=r.toLowerCase();e=p.filter(e=>_J(e,n)),t[20]=p,t[21]=r,t[22]=e}else e=t[22];y=e}let b=y,x;bb5:{if(g){let e;t[23]===h?e=t[24]:(e=h??[],t[23]=h,t[24]=e),x=e;break bb5}if(d){x=b;break bb5}x=v}let S=x,C;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(C=e=>{o(e)},t[25]=C):C=t[25];let w=_N(C),T;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(T=()=>{o(null)},t[26]=T):T=t[26];let E=_N(T),D;return t[27]!==d||t[28]!==v||t[29]!==b||t[30]!==E||t[31]!==g||t[32]!==S||t[33]!==w?(D={categories:v,items:b,isSearchMode:g,activeCategoryId:d,navigableList:S,selectCategory:w,goBack:E},t[27]=d,t[28]=v,t[29]=b,t[30]=E,t[31]=g,t[32]=S,t[33]=w,t[34]=D):D=t[34],D}),yJ=jN(e=>{let t=J(15),{behavior:n,trigger:r,aui:i,setCursorPosition:a,onSelected:o}=e,s=Y(null),c;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(c=e=>(s.current=e,()=>{s.current===e&&(s.current=null)}),t[0]=c):c=t[0];let l=_N(c),u;t[1]!==i||t[2]!==n||t[3]!==o||t[4]!==a||t[5]!==r?(u=e=>{if(!r||!n)return;if(s.current?.(e)){o();return}let t=i.composer.getState().text,c=t.slice(0,r.offset),l=t.slice(r.endOffset),u=()=>{let t=n.formatter.serialize(e);i.composer.setText(c+t+(l.startsWith(` `)?l:` ${l}`)),a(c.length+t.length+1)};n.kind===`directive`?(u(),n.onInserted?.(e)):(n.removeOnExecute?(i.composer.setText(c+(l.startsWith(` `)?l.slice(1):l)),a(c.length)):u(),n.onExecute(e)),o()},t[1]=i,t[2]=n,t[3]=o,t[4]=a,t[5]=r,t[6]=u):u=t[6];let d=_N(u),f;t[7]!==o||t[8]!==a||t[9]!==r?(f=()=>{o(),r&&a(r.offset)},t[7]=o,t[8]=a,t[9]=r,t[10]=f):f=t[10];let p=_N(f),m;return t[11]!==p||t[12]!==l||t[13]!==d?(m={selectItem:d,close:p,registerSelectItemOverride:l},t[11]=p,t[12]=l,t[13]=d,t[14]=m):m=t[14],m}),bJ=jN(e=>{let t=J(47),{adapter:n,text:r,triggerChar:i,matcher:a,behavior:o,aui:s,popoverId:c,isLoading:l}=e,u;t[0]!==a||t[1]!==r||t[2]!==i?(u=mJ({text:r,triggerChar:i,matcher:a}),t[0]=a,t[1]=r,t[2]=i,t[3]=u):u=t[3];let d=yP(u),f=d.trigger!==null&&n!==void 0&&o!==void 0,p;t[4]!==n||t[5]!==d.query||t[6]!==f?(p=vJ({adapter:n,query:d.query,open:f}),t[4]=n,t[5]=d.query,t[6]=f,t[7]=p):p=t[7];let m=yP(p),h;t[8]===m?h=t[9]:(h=()=>{m.goBack()},t[8]=m,t[9]=h);let g=_N(h),_;t[10]!==s||t[11]!==o||t[12]!==d.setCursorPosition||t[13]!==d.trigger||t[14]!==g||t[15]!==i?(_=yJ({behavior:o,trigger:d.trigger,aui:s,triggerChar:i,setCursorPosition:d.setCursorPosition,onSelected:g}),t[10]=s,t[11]=o,t[12]=d.setCursorPosition,t[13]=d.trigger,t[14]=g,t[15]=i,t[16]=_):_=t[16];let v=yP(_),y;t[17]!==d.query||t[18]!==m.activeCategoryId||t[19]!==m.goBack||t[20]!==m.isSearchMode||t[21]!==m.navigableList||t[22]!==m.selectCategory||t[23]!==f||t[24]!==c||t[25]!==v.close||t[26]!==v.selectItem?(y=gJ({navigableList:m.navigableList,isSearchMode:m.isSearchMode,activeCategoryId:m.activeCategoryId,query:d.query,popoverId:c,open:f,selectItem:v.selectItem,selectCategory:m.selectCategory,goBack:m.goBack,close:v.close}),t[17]=d.query,t[18]=m.activeCategoryId,t[19]=m.goBack,t[20]=m.isSearchMode,t[21]=m.navigableList,t[22]=m.selectCategory,t[23]=f,t[24]=c,t[25]=v.close,t[26]=v.selectItem,t[27]=y):y=t[27];let b=yP(y),x;return t[28]!==d.query||t[29]!==d.setCursorPosition||t[30]!==l||t[31]!==b.handleKeyDown||t[32]!==b.highlightIndex||t[33]!==b.highlightedIndex||t[34]!==b.highlightedItemId||t[35]!==m.activeCategoryId||t[36]!==m.categories||t[37]!==m.goBack||t[38]!==m.isSearchMode||t[39]!==m.items||t[40]!==m.selectCategory||t[41]!==f||t[42]!==c||t[43]!==v.close||t[44]!==v.registerSelectItemOverride||t[45]!==v.selectItem?(x={open:f,query:d.query,activeCategoryId:m.activeCategoryId,categories:m.categories,items:m.items,highlightedIndex:b.highlightedIndex,isSearchMode:m.isSearchMode,isLoading:l,popoverId:c,highlightedItemId:b.highlightedItemId,selectCategory:m.selectCategory,goBack:m.goBack,selectItem:v.selectItem,close:v.close,highlightIndex:b.highlightIndex,handleKeyDown:b.handleKeyDown,setCursorPosition:d.setCursorPosition,registerSelectItemOverride:v.registerSelectItemOverride},t[28]=d.query,t[29]=d.setCursorPosition,t[30]=l,t[31]=b.handleKeyDown,t[32]=b.highlightIndex,t[33]=b.highlightedIndex,t[34]=b.highlightedItemId,t[35]=m.activeCategoryId,t[36]=m.categories,t[37]=m.goBack,t[38]=m.isSearchMode,t[39]=m.items,t[40]=m.selectCategory,t[41]=f,t[42]=c,t[43]=v.close,t[44]=v.registerSelectItemOverride,t[45]=v.selectItem,t[46]=x):x=t[46],x}),xJ=ON(null),SJ=()=>{let e=AN(xJ);if(!e)throw Error(`useTriggerPopoverScopeContext must be used within ComposerPrimitive.TriggerPopover`);return e},CJ=()=>AN(xJ),wJ=ON(null),TJ=()=>{let e=AN(wJ);if(!e)throw Error(`TriggerPopover.Directive / TriggerPopover.Action must be rendered inside ComposerPrimitive.TriggerPopover`);return e},EJ=Z((e,t)=>{let n=J(69),r,i,a,o,s,c,l;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],s=n[5],c=n[6],l=n[7]):({char:a,matcher:s,adapter:r,isLoading:l,"aria-label":i,children:o,...c}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=s,n[6]=c,n[7]=l);let u=l!==void 0&&l,d=Q(),f=$(DJ),p=xN(),m=Y(s),h;n[8]===s?h=n[9]:(h=()=>{m.current=s},n[8]=s,n[9]=h),X(h);let g;n[10]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>(e,t,n)=>m.current(e,t,n),n[10]=g):g=n[10];let[_]=fN(g),v=s!==void 0,y=Y(null),[x,S]=fN(null),C=Y(0),w;n[11]===a?w=n[12]:(w=e=>(C.current+=1,y.current=e,S(e),()=>{C.current=Math.max(0,C.current-1),y.current===e&&(y.current=null,S(null))}),n[11]=a,n[12]=w);let T=w,E;n[13]===T?E=n[14]:(E={register:T},n[13]=T,n[14]=E);let D=E,O=x??void 0,k;n[15]!==r||n[16]!==d||n[17]!==a||n[18]!==u||n[19]!==s||n[20]!==p||n[21]!==O||n[22]!==f?(k=bJ({adapter:r,text:f,triggerChar:a,matcher:s,behavior:O,aui:d,popoverId:p,isLoading:u}),n[15]=r,n[16]=d,n[17]=a,n[18]=u,n[19]=s,n[20]=p,n[21]=O,n[22]=f,n[23]=k):k=n[23];let A=yP(k),j;n[24]===A?j=n[25]:(j=()=>A,n[24]=A,n[25]=j);let M=_N(j),N=Zq(),ee;n[26]!==x||n[27]!==a||n[28]!==M||n[29]!==v||n[30]!==_||n[31]!==N?(ee=()=>N.register({char:a,...v?{matcher:_}:{},...x?{behavior:x}:{},resource:M()}),n[26]=x,n[27]=a,n[28]=M,n[29]=v,n[30]=_,n[31]=N,n[32]=ee):ee=n[32];let te;n[33]!==x||n[34]!==a||n[35]!==v||n[36]!==N?(te=[N,a,v,x],n[33]=x,n[34]=a,n[35]=v,n[36]=N,n[37]=te):te=n[37],X(ee,te);let ne=Gq(),re;n[38]!==M||n[39]!==ne?(re=()=>{if(ne)return ne.register(M())},n[38]=M,n[39]=ne,n[40]=re):re=n[40];let ie;n[41]===ne?ie=n[42]:(ie=[ne],n[41]=ne,n[42]=ie),X(re,ie);let ae=x!==null&&A.open,oe=$q(),se,ce;n[43]!==oe||n[44]!==a||n[45]!==ae?(se=()=>{if(ae)return()=>{oe.setActiveAria(a,null)}},ce=[oe,a,ae],n[43]=oe,n[44]=a,n[45]=ae,n[46]=se,n[47]=ce):(se=n[46],ce=n[47]),X(se,ce);let le,ue;n[48]!==oe||n[49]!==a||n[50]!==ae||n[51]!==p||n[52]!==A.highlightedItemId?(le=()=>{ae&&oe.setActiveAria(a,{popoverId:p,highlightedItemId:A.highlightedItemId})},ue=[oe,a,p,ae,A.highlightedItemId],n[48]=oe,n[49]=a,n[50]=ae,n[51]=p,n[52]=A.highlightedItemId,n[53]=le,n[54]=ue):(le=n[53],ue=n[54]),X(le,ue);let de;n[55]!==i||n[56]!==o||n[57]!==t||n[58]!==ae||n[59]!==p||n[60]!==c||n[61]!==A.highlightedItemId?(de=ae?(0,b.jsx)(BK.div,{role:`listbox`,id:p,"aria-label":i??`Suggestions`,"aria-activedescendant":A.highlightedItemId,"data-state":`open`,...c,ref:t,children:o}):o,n[55]=i,n[56]=o,n[57]=t,n[58]=ae,n[59]=p,n[60]=c,n[61]=A.highlightedItemId,n[62]=de):de=n[62];let P;n[63]!==A||n[64]!==de?(P=(0,b.jsx)(xJ.Provider,{value:A,children:de}),n[63]=A,n[64]=de,n[65]=P):P=n[65];let fe;return n[66]!==D||n[67]!==P?(fe=(0,b.jsx)(wJ.Provider,{value:D,children:P}),n[66]=D,n[67]=P,n[68]=fe):fe=n[68],fe});EJ.displayName=`ComposerPrimitive.TriggerPopover`;function DJ(e){return e.composer.text}var OJ=()=>{let e=J(2),{disabled:t,send:n}=kG(),r;return e[0]===n?r=e[1]:(r=()=>n(),e[0]=n,e[1]=r),t?null:r},kJ=QK(`ComposerPrimitive.Send`,OJ),AJ=ON(null),jJ=()=>AN(AJ),MJ=`[contenteditable]:not([contenteditable='false'])`,NJ=`textarea:not(:disabled), ${MJ}`,PJ=[`a`,`audio[controls]`,`button`,`details`,`embed`,`iframe`,`input`,`label`,`select`,`summary`,`textarea`,`video[controls]`,MJ,`[tabindex]`].join(`, `),FJ=Z((e,t)=>{let n=J(24),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({onSubmit:a,onMouseDown:i,compact:r,...o}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let s=OJ(),[c,l]=fN(!1),u;n[5]===Symbol.for(`react.memo_cache_sentinel`)?(u={setMultiline:l},n[5]=u):u=n[5];let d=u,f;n[6]===r?f=n[7]:(f=e=>r?e.composer.attachments.length===0&&e.composer.quote==null&&e.composer.queue.length===0&&e.composer.dictation==null&&!e.composer.text.includes(`
93
- `):!1,n[6]=r,n[7]=f);let p=$(f)&&!c,m;n[8]===s?m=n[9]:(m=e=>{e.preventDefault(),s&&s()},n[8]=s,n[9]=m);let h=m,g=IJ,_=r?d:null,v=p?``:void 0,y;n[10]!==h||n[11]!==a?(y=P(a,h),n[10]=h,n[11]=a,n[12]=y):y=n[12];let x;n[13]===i?x=n[14]:(x=P(i,g),n[13]=i,n[14]=x);let S;n[15]!==t||n[16]!==o||n[17]!==v||n[18]!==y||n[19]!==x?(S=(0,b.jsx)(BK.form,{...o,"data-compact":v,ref:t,onSubmit:y,onMouseDown:x}),n[15]=t,n[16]=o,n[17]=v,n[18]=y,n[19]=x,n[20]=S):S=n[20];let C;return n[21]!==_||n[22]!==S?(C=(0,b.jsx)(AJ.Provider,{value:_,children:S}),n[21]=_,n[22]=S,n[23]=C):C=n[23],C});FJ.displayName=`ComposerPrimitive.Root`;function IJ(e){if(e.button!==0)return;let t=e.target;if(!(t instanceof Element)||!e.currentTarget.contains(t))return;let n=t.closest(PJ);if(n&&e.currentTarget.contains(n))return;let r=e.currentTarget.querySelector(NJ);r&&(e.preventDefault(),r.focus())}var LJ=e=>{let t=J(4),n=dt(e),r=fK(RJ),i,a;t[0]!==n||t[1]!==r?(i=()=>r(n),a=[r,n],t[0]=n,t[1]=r,t[2]=i,t[3]=a):(i=t[2],a=t[3]),X(i,a)};function RJ(e){return e.onScrollToBottom}var zJ=()=>!1,BJ=()=>{},VJ=e=>{let t=J(4),n;t[0]===e?n=t[1]:(n=t=>{if(typeof window>`u`||e===null||!window.matchMedia)return BJ;let n=window.matchMedia(e);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)},t[0]=e,t[1]=n);let r=n,i;return t[2]===e?i=t[3]:(i=()=>typeof window>`u`||e===null||!window.matchMedia?!1:window.matchMedia(e).matches,t[2]=e,t[3]=i),vN(r,i,zJ)};function HJ(){return $(UJ)}function UJ(e){return e.composer.isEditing?e.composer.text:``}function WJ(e){return!!$(GJ)||!!e}function GJ(e){return e.thread.isDisabled||e.composer.dictation?.inputDisabled}function KJ(){let e=J(4),t=oJ();if(!t){let t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t={},e[0]=t):t=e[0],t}let n;return e[1]!==t.highlightedItemId||e[2]!==t.popoverId?(n={"aria-controls":t.popoverId,"aria-expanded":!0,"aria-haspopup":`listbox`,"aria-activedescendant":t.highlightedItemId},e[1]=t.highlightedItemId,e[2]=t.popoverId,e[3]=n):n=e[3],n}function qJ(){return qJ=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},qJ.apply(null,arguments)}function JJ(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var YJ=y.useLayoutEffect,XJ=function(e){var t=y.useRef(e);return YJ(function(){t.current=e}),t},ZJ=function(e,t){if(typeof e==`function`){e(t);return}e.current=t},QJ=function(e,t){var n=y.useRef();return y.useCallback(function(r){e.current=r,n.current&&ZJ(n.current,null),n.current=t,t&&ZJ(t,r)},[t])},$J={"min-height":`0`,"max-height":`none`,height:`0`,visibility:`hidden`,overflow:`hidden`,position:`absolute`,"z-index":`-1000`,top:`0`,right:`0`,display:`block`},eY=function(e){Object.keys($J).forEach(function(t){e.style.setProperty(t,$J[t],`important`)})},tY=null,nY=function(e,t){var n=e.scrollHeight;return t.sizingStyle.boxSizing===`border-box`?n+t.borderSize:n-t.paddingSize};function rY(e,t,n,r){n===void 0&&(n=1),r===void 0&&(r=1/0),tY||(tY=document.createElement(`textarea`),tY.setAttribute(`tabindex`,`-1`),tY.setAttribute(`aria-hidden`,`true`),eY(tY)),tY.parentNode===null&&document.body.appendChild(tY);var i=e.paddingSize,a=e.borderSize,o=e.sizingStyle,s=o.boxSizing;Object.keys(o).forEach(function(e){var t=e;tY.style[t]=o[t]}),eY(tY),tY.value=t;var c=nY(tY,e);tY.value=t,c=nY(tY,e),tY.value=`x`;var l=tY.scrollHeight-i,u=l*n;s===`border-box`&&(u=u+i+a),c=Math.max(u,c);var d=l*r;return s===`border-box`&&(d=d+i+a),c=Math.min(d,c),[c,l]}var iY=function(){},aY=function(e,t){return e.reduce(function(e,n){return e[n]=t[n],e},{})},oY=[`borderBottomWidth`,`borderLeftWidth`,`borderRightWidth`,`borderTopWidth`,`boxSizing`,`fontFamily`,`fontSize`,`fontStyle`,`fontWeight`,`letterSpacing`,`lineHeight`,`paddingBottom`,`paddingLeft`,`paddingRight`,`paddingTop`,`tabSize`,`textIndent`,`textRendering`,`textTransform`,`width`,`wordBreak`,`wordSpacing`,`scrollbarGutter`],sY=!!document.documentElement.currentStyle,cY=function(e){var t=window.getComputedStyle(e);if(t===null)return null;var n=aY(oY,t),r=n.boxSizing;return r===``?null:(sY&&r===`border-box`&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+`px`),{sizingStyle:n,paddingSize:parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),borderSize:parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth)})};function lY(e,t,n){var r=XJ(n);y.useLayoutEffect(function(){var n=function(e){return r.current(e)};if(e)return e.addEventListener(t,n),function(){return e.removeEventListener(t,n)}},[])}var uY=function(e,t){lY(document.body,`reset`,function(n){e.current.form===n.target&&t(n)})},dY=function(e){lY(window,`resize`,e)},fY=function(e){lY(document.fonts,`loadingdone`,e)},pY=[`cacheMeasurements`,`maxRows`,`minRows`,`onChange`,`onHeightChange`],mY=y.forwardRef(function(e,t){var n=e.cacheMeasurements,r=e.maxRows,i=e.minRows,a=e.onChange,o=a===void 0?iY:a,s=e.onHeightChange,c=s===void 0?iY:s,l=JJ(e,pY),u=l.value!==void 0,d=y.useRef(null),f=QJ(d,t),p=y.useRef(0),m=y.useRef(),h=function(){var e=d.current,t=n&&m.current?m.current:cY(e);if(t){m.current=t;var a=rY(t,e.value||e.placeholder||`x`,i,r),o=a[0],s=a[1];p.current!==o&&(p.current=o,e.style.setProperty(`height`,o+`px`,`important`),c(o,{rowHeight:s}))}};return y.useLayoutEffect(h),uY(d,function(){if(!u){var e=d.current.value;requestAnimationFrame(function(){var t=d.current;t&&e!==t.value&&h()})}}),dY(h),fY(h),y.createElement(`textarea`,qJ({},l,{onChange:function(e){u||h(),o(e)},ref:f}))}),hY=`(pointer: coarse) and (not (any-pointer: fine))`,gY=Z(({autoFocus:e=!1,asChild:t,render:n,disabled:r,onChange:i,onKeyDown:a,onPaste:o,onSelect:c,submitOnEnter:l,submitMode:d,cancelOnEscape:f=!0,unstable_focusOnRunStart:p=!0,unstable_focusOnScrollToBottom:m=!0,unstable_focusOnThreadSwitched:h=!0,unstable_insertNewlineOnTouchEnter:g=!1,addAttachmentOnPaste:_=!0,onHeightChange:v,...y},x)=>{let S=Q(),C=Gq(),w=jJ(),T=d??(l===!1?`none`:`enter`),E=VJ(g?hY:null),D=g&&E&&T===`enter`?`none`:T,O=HJ(),k=WJ(r),A=Y(null),j=u(x,A),M=Y(!1);jK(e=>{if(!A.current?.contains(e.target)||e.isComposing)return;if(C){for(let t of C.getPlugins())if(t.handleKeyDown(e))return}if(!f)return;let t=S.composer;t.getState().canCancel&&(t.cancel(),e.preventDefault())});let N=e=>{if(!k&&!e.nativeEvent.isComposing){if(C){for(let t of C.getPlugins())if(t.handleKeyDown(e))return}if(e.key===`Enter`){let t=S.thread.getState(),n=t.capabilities.queue;if(e.shiftKey&&(e.ctrlKey||e.metaKey)&&n&&T!==`none`&&S.composer.getState().canSend){e.preventDefault(),S.composer.send({steer:!0});return}if(e.shiftKey||t.isRunning&&!n)return;let r=!1;D===`ctrlEnter`?r=e.ctrlKey||e.metaKey:D===`enter`&&(r=!0),r&&(e.preventDefault(),A.current?.closest(`form`)?.requestSubmit())}}},ee=async e=>{if(!_)return;let t=S.thread.getState().capabilities,n=Array.from(e.clipboardData?.files||[]);t.attachments&&n.length>0&&(e.preventDefault(),await Promise.all(n.map(async e=>{try{await S.composer.addAttachment(e)}catch{}})))},te=(e,t)=>{if(v?.(e,t),!w)return;let n=A.current;if(!n||n.value===``)return;let r=getComputedStyle(n),i=r.boxSizing===`border-box`?e-parseFloat(r.paddingTop)-parseFloat(r.paddingBottom)-parseFloat(r.borderTopWidth)-parseFloat(r.borderBottomWidth):e;Math.round(i/t.rowHeight)>1&&w.setMultiline(!0)},ne=e&&!k,re=hN(()=>{let e=A.current;e&&ne&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[ne]);X(()=>re(),[re]),LJ(()=>{S.composer.getState().type===`thread`&&m&&re()}),X(()=>{if(S.composer.getState().type===`thread`&&p)return S.on(`thread.runStart`,re)},[p,re,S]),X(()=>{if(S.composer.getState().type===`thread`&&h)return S.on(`threads.selectionChanged`,re)},[h,re,S]),X(()=>{O===``&&w?.setMultiline(!1)},[O,w]);let ie=KJ(),ae={name:`input`,value:O,...y,...ie,ref:j,disabled:k,onChange:P(i,e=>{if(!S.composer.getState().isEditing)return;let t=e.nativeEvent.isComposing===!0;M.current&&!t&&(M.current=!1);let n=t||M.current;if(WN(()=>{S.composer.setText(e.target.value)}),n)return;let r=e.target.selectionStart??e.target.value.length;if(C)for(let e of C.getPlugins())e.setCursorPosition(r)}),onKeyDown:P(a,N),onCompositionStart:P(y.onCompositionStart,()=>{M.current=!0}),onCompositionEnd:P(y.onCompositionEnd,e=>{if(M.current=!1,!S.composer.getState().isEditing)return;let t=e.target;WN(()=>{S.composer.setText(t.value)});let n=t.selectionStart??t.value.length;if(C)for(let e of C.getPlugins())e.setCursorPosition(n)}),onSelect:P(c,e=>{if(M.current)return;let t=e.target,n=t.selectionStart??t.value.length;if(C)for(let e of C.getPlugins())e.setCursorPosition(n)}),onPaste:P(o,ee),...w?{onHeightChange:te}:v===void 0?{}:{onHeightChange:v}};if(n&&DN(n))return LK(n,y.children,ae);let oe=t?s:mY;return(0,b.jsx)(oe,{...ae})});gY.displayName=`ComposerPrimitive.Input`;var _Y=QK(`ComposerPrimitive.Cancel`,()=>{let{disabled:e,cancel:t}=AG();return e?null:t}),vY=QK(`ComposerPrimitive.AddAttachment`,e=>{let t=J(6),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{multiple:r}=n,i=r===void 0||r,{disabled:a,addAttachment:o}=NG(),s=Q(),c;return t[2]!==o||t[3]!==s.composer||t[4]!==i?(c=()=>{let e=document.createElement(`input`);e.type=`file`,e.multiple=i,e.hidden=!0;let t=s.composer.getState().attachmentAccept;t!==`*`&&(e.accept=t),document.body.appendChild(e),e.onchange=async t=>{let n=t.target.files;if(!n)return;let r=Array.from(n,async e=>{try{await o(e)}catch{}});document.body.removeChild(e),await Promise.all(r)},e.oncancel=()=>{(!e.files||e.files.length===0)&&document.body.removeChild(e)},e.click()},t[2]=o,t[3]=s.composer,t[4]=i,t[5]=c):c=t[5],a?null:c},[`multiple`]),yY=Z(({disabled:e,asChild:t=!1,render:n,children:r,...i},a)=>{let[o,c]=fN(!1),l=Q(),u=hN(t=>{if(!e&&t.dataTransfer.types.includes(`Files`)){if(t.preventDefault(),!l.thread.getState().capabilities.attachments){t.dataTransfer.dropEffect=`none`;return}c(!0)}},[e,l]),d=hN(t=>{if(!e&&t.dataTransfer.types.includes(`Files`)){if(t.preventDefault(),!l.thread.getState().capabilities.attachments){t.dataTransfer.dropEffect=`none`;return}o||c(!0)}},[e,o,l]),f=hN(t=>{if(e)return;t.preventDefault();let n=t.relatedTarget;n&&t.currentTarget.contains(n)||c(!1)},[e]),p=hN(async t=>{if(e||(c(!1),!t.dataTransfer.types.includes(`Files`)))return;t.preventDefault();let n=Array.from(t.dataTransfer.files);l.thread.getState().capabilities.attachments&&n.length!==0&&await Promise.all(n.map(async e=>{try{await l.composer.addAttachment(e)}catch{}}))},[e,l]),m={...o?{"data-dragging":`true`}:null,...i,onDragEnterCapture:P(i.onDragEnterCapture,u),onDragOverCapture:P(i.onDragOverCapture,d),onDragLeaveCapture:P(i.onDragLeaveCapture,f),onDropCapture:P(i.onDropCapture,p),ref:a};if(n&&DN(n))return LK(n,r,m);let h=t?s:`div`;return(0,b.jsx)(h,{...m,children:r})});yY.displayName=`ComposerPrimitive.AttachmentDropzone`;var bY=QK(`ComposerPrimitive.Dictate`,()=>{let{disabled:e,startDictation:t}=jG();return e?null:t}),xY=QK(`ComposerPrimitive.StopDictation`,()=>{let e=J(2),t=Q(),n=$(SY),r;return e[0]===t.composer?r=e[1]:(r=()=>{t.composer.stopDictation()},e[0]=t.composer,e[1]=r),n?r:null});function SY(e){return e.composer.dictation!=null}var CY=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({children:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=$(wY);if(!a)return null;let o=r??a,s;return n[3]!==t||n[4]!==i||n[5]!==o?(s=(0,b.jsx)(BK.span,{...i,ref:t,children:o}),n[3]=t,n[4]=i,n[5]=o,n[6]=s):s=n[6],s});CY.displayName=`ComposerPrimitive.DictationTranscript`;function wY(e){return e.composer.dictation?.transcript}var TY=Z((e,t)=>{let n=J(3);if(!$(OY))return null;let r;return n[0]!==t||n[1]!==e?(r=(0,b.jsx)(BK.div,{...e,ref:t}),n[0]=t,n[1]=e,n[2]=r):r=n[2],r});TY.displayName=`ComposerPrimitive.Quote`;var EY=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({children:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=$(kY);if(!a)return null;let o=r??a,s;return n[3]!==t||n[4]!==i||n[5]!==o?(s=(0,b.jsx)(BK.span,{...i,ref:t,children:o}),n[3]=t,n[4]=i,n[5]=o,n[6]=s):s=n[6],s});EY.displayName=`ComposerPrimitive.QuoteText`;var DY=Z((e,t)=>{let n=J(12),r,i;n[0]===e?(r=n[1],i=n[2]):({onClick:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=Q(),o;n[3]===a?o=n[4]:(o=()=>{a.composer.setQuote(void 0)},n[3]=a,n[4]=o);let s=o,c;n[5]!==s||n[6]!==r?(c=P(r,s),n[5]=s,n[6]=r,n[7]=c):c=n[7];let l;return n[8]!==t||n[9]!==i||n[10]!==c?(l=(0,b.jsx)(BK.button,{type:`button`,...i,ref:t,onClick:c}),n[8]=t,n[9]=i,n[10]=c,n[11]=l):l=n[11],l});DY.displayName=`ComposerPrimitive.QuoteDismiss`;function OY(e){return e.composer.quote}function kY(e){return e.composer.quote?.text}var AY=Z((e,t)=>{let n=J(12),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({children:i,"aria-label":r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let{categories:o,activeCategoryId:s,isSearchMode:c,open:l}=SJ();if(!l||s||c)return null;let u=r??`Categories`,d;n[4]!==o||n[5]!==i?(d=i(o),n[4]=o,n[5]=i,n[6]=d):d=n[6];let f;return n[7]!==t||n[8]!==a||n[9]!==u||n[10]!==d?(f=(0,b.jsx)(BK.div,{role:`group`,"aria-label":u,...a,ref:t,children:d}),n[7]=t,n[8]=a,n[9]=u,n[10]=d,n[11]=f):f=n[11],f});AY.displayName=`ComposerPrimitive.TriggerPopoverCategories`;var jY=Z((e,t)=>{let n=J(30),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({categoryId:r,onClick:i,onMouseMove:a,...o}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let{selectCategory:s,highlightIndex:c,categories:l,highlightedIndex:u,activeCategoryId:d,isSearchMode:f,popoverId:p}=SJ(),m;n[5]!==r||n[6]!==s?(m=()=>{s(r)},n[5]=r,n[6]=s,n[7]=m):m=n[7];let h=m,g;if(n[8]!==l||n[9]!==r){let e;n[11]===r?e=n[12]:(e=e=>e.id===r,n[11]=r,n[12]=e),g=l.findIndex(e),n[8]=l,n[9]=r,n[10]=g}else g=n[10];let _=g,v=!d&&!f&&_===u,y;n[13]!==_||n[14]!==c?(y=()=>{c(_)},n[13]=_,n[14]=c,n[15]=y):y=n[15];let x=y,S=`${p}-option-${r}`,C=v?``:void 0,w;n[16]!==h||n[17]!==i?(w=P(i,h),n[16]=h,n[17]=i,n[18]=w):w=n[18];let T;n[19]!==x||n[20]!==a?(T=P(a,x),n[19]=x,n[20]=a,n[21]=T):T=n[21];let E;return n[22]!==t||n[23]!==v||n[24]!==o||n[25]!==S||n[26]!==C||n[27]!==w||n[28]!==T?(E=(0,b.jsx)(BK.button,{type:`button`,role:`option`,id:S,"aria-selected":v,"data-highlighted":C,...o,ref:t,onClick:w,onMouseMove:T}),n[22]=t,n[23]=v,n[24]=o,n[25]=S,n[26]=C,n[27]=w,n[28]=T,n[29]=E):E=n[29],E});jY.displayName=`ComposerPrimitive.TriggerPopoverCategoryItem`;var MY=Z((e,t)=>{let n=J(12),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({children:i,"aria-label":r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let{items:o,activeCategoryId:s,isSearchMode:c,open:l}=SJ();if(!l||!s&&!c)return null;let u=r??`Items`,d;n[4]!==i||n[5]!==o?(d=i(o),n[4]=i,n[5]=o,n[6]=d):d=n[6];let f;return n[7]!==t||n[8]!==a||n[9]!==u||n[10]!==d?(f=(0,b.jsx)(BK.div,{role:`group`,"aria-label":u,...a,ref:t,children:d}),n[7]=t,n[8]=a,n[9]=u,n[10]=d,n[11]=f):f=n[11],f});MY.displayName=`ComposerPrimitive.TriggerPopoverItems`;var NY=Z((e,t)=>{let n=J(30),r,i,a,o,s;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],s=n[5]):({item:i,index:r,onClick:a,onMouseMove:o,...s}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=s);let{selectItem:c,highlightIndex:l,items:u,highlightedIndex:d,activeCategoryId:f,isSearchMode:p,popoverId:m}=SJ(),h;n[6]!==i||n[7]!==c?(h=()=>{c(i)},n[6]=i,n[7]=c,n[8]=h):h=n[8];let g=h,_;n[9]!==r||n[10]!==i.id||n[11]!==u?(_=r??u.findIndex(e=>e.id===i.id),n[9]=r,n[10]=i.id,n[11]=u,n[12]=_):_=n[12];let v=_,y=(p||f!==null)&&v===d,x;n[13]!==l||n[14]!==v?(x=()=>{l(v)},n[13]=l,n[14]=v,n[15]=x):x=n[15];let S=x,C=`${m}-option-${i.id}`,w=y?``:void 0,T;n[16]!==g||n[17]!==a?(T=P(a,g),n[16]=g,n[17]=a,n[18]=T):T=n[18];let E;n[19]!==S||n[20]!==o?(E=P(o,S),n[19]=S,n[20]=o,n[21]=E):E=n[21];let D;return n[22]!==t||n[23]!==y||n[24]!==s||n[25]!==C||n[26]!==w||n[27]!==T||n[28]!==E?(D=(0,b.jsx)(BK.button,{type:`button`,role:`option`,id:C,"aria-selected":y,"data-highlighted":w,...s,ref:t,onClick:T,onMouseMove:E}),n[22]=t,n[23]=y,n[24]=s,n[25]=C,n[26]=w,n[27]=T,n[28]=E,n[29]=D):D=n[29],D});NY.displayName=`ComposerPrimitive.TriggerPopoverItem`;var PY=Z((e,t)=>{let n=J(10),r,i;n[0]===e?(r=n[1],i=n[2]):({onClick:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let{activeCategoryId:a,isSearchMode:o,goBack:s,open:c}=SJ();if(!c||!a||o)return null;let l;n[3]!==s||n[4]!==r?(l=P(r,s),n[3]=s,n[4]=r,n[5]=l):l=n[5];let u;return n[6]!==t||n[7]!==i||n[8]!==l?(u=(0,b.jsx)(BK.button,{type:`button`,...i,ref:t,onClick:l}),n[6]=t,n[7]=i,n[8]=l,n[9]=u):u=n[9],u});PY.displayName=`ComposerPrimitive.TriggerPopoverBack`;var FY=e=>{let t=J(8),{formatter:n,onExecute:r,removeOnExecute:i}=e,{register:a}=TJ(),o=Y(r),s,c;t[0]===r?(s=t[1],c=t[2]):(s=()=>{o.current=r},c=[r],t[0]=r,t[1]=s,t[2]=c),bN(s,c);let l,u;return t[3]!==n||t[4]!==a||t[5]!==i?(l=()=>{let e={kind:`action`,formatter:n??OK,onExecute:e=>o.current(e),...i===void 0?{}:{removeOnExecute:i}};return a(e)},u=[a,n,i],t[3]=n,t[4]=a,t[5]=i,t[6]=l,t[7]=u):(l=t[6],u=t[7]),X(l,u),null};FY.displayName=`ComposerPrimitive.TriggerPopoverAction`;var IY=e=>{let t=J(7),{formatter:n,onInserted:r}=e,{register:i}=TJ(),a=Y(r),o,s;t[0]===r?(o=t[1],s=t[2]):(o=()=>{a.current=r},s=[r],t[0]=r,t[1]=o,t[2]=s),bN(o,s);let c,l;return t[3]!==n||t[4]!==i?(c=()=>i({kind:`directive`,formatter:n??OK,onInserted:e=>a.current?.(e)}),l=[i,n],t[3]=n,t[4]=i,t[5]=c,t[6]=l):(c=t[5],l=t[6]),X(c,l),null};IY.displayName=`ComposerPrimitive.TriggerPopoverDirective`;var LY=Object.assign(EJ,{Directive:IY,Action:FY}),RY=PK({AddAttachment:()=>vY,AttachmentByIndex:()=>eG,AttachmentDropzone:()=>yY,Attachments:()=>nG,Cancel:()=>_Y,Dictate:()=>bY,DictationTranscript:()=>CY,If:()=>vG,Input:()=>gY,Queue:()=>iG,Quote:()=>TY,QuoteDismiss:()=>DY,QuoteText:()=>EY,Root:()=>FJ,Send:()=>kJ,StopDictation:()=>xY,Unstable_TriggerPopover:()=>LY,Unstable_TriggerPopoverBack:()=>PY,Unstable_TriggerPopoverCategories:()=>AY,Unstable_TriggerPopoverCategoryItem:()=>jY,Unstable_TriggerPopoverItem:()=>NY,Unstable_TriggerPopoverItems:()=>MY,Unstable_TriggerPopoverRoot:()=>lJ,unstable_useTriggerPopoverRootContext:()=>Zq,unstable_useTriggerPopoverRootContextOptional:()=>Qq,unstable_useTriggerPopoverScopeContext:()=>SJ,unstable_useTriggerPopoverScopeContextOptional:()=>CJ,unstable_useTriggerPopoverTriggers:()=>eJ,unstable_useTriggerPopoverTriggersOptional:()=>iJ}),zY=Object.freeze({type:`complete`}),BY=Object.freeze({type:`text`,text:``,status:zY}),VY=()=>$(HY);function HY(e){return e.part.type!==`text`&&e.part.type!==`reasoning`?BY:e.part}var UY=ON(null),WY=e=>({useSmoothStatus:yK(()=>e)}),GY=e=>{let t=J(6),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r={optional:!0},t[0]=r):r=t[0];let i=qY(r),a=Q(),o;t[1]===a.part?o=t[2]:(o=()=>WY(a.part.getState().status),t[1]=a.part,t[2]=o);let[s]=fN(o);if(i)return n;let c;return t[3]!==n||t[4]!==s?(c=(0,b.jsx)(UY.Provider,{value:s,children:n}),t[3]=n,t[4]=s,t[5]=c):c=t[5],c},KY=e=>{let t=Z((t,n)=>{let r=J(3),i=t,a;return r[0]!==n||r[1]!==i?(a=(0,b.jsx)(GY,{children:(0,b.jsx)(e,{...i,ref:n})}),r[0]=n,r[1]=i,r[2]=a):a=r[2],a});return t.displayName=e.displayName,t};function qY(e){let t=AN(UY);if(!e?.optional&&!t)throw Error(`This component must be used within a SmoothContextProvider.`);return t}var{useSmoothStatus:JY,useSmoothStatusStore:YY}=uK(qY,`useSmoothStatus`),XY=250,ZY=5,QY=class{animationFrameId=null;lastUpdateTime=Date.now();lastCommitTime=0;targetText=``;drainMs=XY;maxCharIntervalMs=ZY;maxCharsPerFrame=1/0;minCommitMs=0;currentText;setText;constructor(e,t){this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate=()=>{let e=Date.now(),t=e-this.lastUpdateTime,n=this.targetText.length-this.currentText.length,r=Math.min(this.maxCharIntervalMs,this.drainMs/n),i=Math.min(n,this.maxCharsPerFrame),a=0;for(;t>=r&&a<i;)a++,t-=r;a===i&&i===this.maxCharsPerFrame&&(t=0),this.animationFrameId=a===n?null:requestAnimationFrame(this.animate),a!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+a),this.lastUpdateTime=e-t,(a===n||e-this.lastCommitTime>=this.minCommitMs)&&(this.lastCommitTime=e,this.setText(this.currentText)))}},$Y=Object.freeze({type:`running`}),eX=(e,t)=>e!==void 0&&e>0?e:t,tX=(e,t=!1)=>{let{text:n}=e,r=VJ(`(prefers-reduced-motion: reduce)`),i=typeof t==`object`&&t?t:void 0,a=t!==!1&&t!==null&&!r,o=eX(i?.drainMs,XY),s=eX(i?.maxCharIntervalMs,ZY),c=eX(i?.maxCharsPerFrame,1/0),l=eX(i?.minCommitMs,0),[u,d]=fN(e.status.type===`running`?``:n),f=Q(),p=$(()=>f.part),[m,h]=fN(p);(p!==m||!n.startsWith(u))&&(h(p),d(e.status.type===`running`?``:n));let g=YY({optional:!0}),_=dt(t=>{if(d(t),g){let n=u!==t||e.status.type===`running`?$Y:e.status;SK(g).setState(n,!0)}});X(()=>{if(g){let t=a&&(u!==n||e.status.type===`running`)?$Y:e.status;SK(g).setState(t,!0)}},[g,a,n,u,e.status]);let[v]=fN(new QY(u,_));X(()=>{v.drainMs=o,v.maxCharIntervalMs=s,v.maxCharsPerFrame=c,v.minCommitMs=l},[v,o,s,c,l]);let y=Y(p);return X(()=>{if(!a){v.stop();return}let t=y.current!==p;if(y.current=p,t||!n.startsWith(v.targetText)){e.status.type===`running`?(v.currentText=``,v.targetText=n,v.lastCommitTime=0,v.start()):(v.currentText=n,v.targetText=n,v.stop(),_(n));return}if(v.targetText=n,e.status.type!==`running`){if(v.currentText===``){v.currentText=n,v.stop(),_(n);return}v.start();return}v.start()},[v,a,n,e.status.type,p,_]),X(()=>()=>{v.stop()},[v]),mN(()=>a?{...e,text:u,status:n===u?e.status:$Y}:e,[a,u,e,n])},nX=Object.freeze({type:`complete`}),rX=Object.freeze({type:`image`,image:``,status:nX}),iX=()=>$(aX);function aX(e){return e.part.type===`image`?e.part:rX}var oX=Z(({smooth:e=!0,component:t=BK.span,render:n,...r},i)=>{let{text:a,status:o}=tX(VY(),e),s={"data-status":o.type,...r,ref:i};return n&&DN(n)?LK(n,a,s):(0,b.jsx)(t,{...s,children:a})});oX.displayName=`MessagePartPrimitive.Text`;var sX=Z((e,t)=>{let n=J(4),{image:r}=iX(),i;return n[0]!==t||n[1]!==r||n[2]!==e?(i=(0,b.jsx)(BK.img,{src:r,...e,ref:t}),n[0]=t,n[1]=r,n[2]=e,n[3]=i):i=n[3],i});sX.displayName=`MessagePartPrimitive.Image`;var cX=Z((e,t)=>{let n=J(3),r;return n[0]!==t||n[1]!==e?(r=(0,b.jsx)(BK.div,{role:`alert`,...e,ref:t}),n[0]=t,n[1]=e,n[2]=r):r=n[2],r});cX.displayName=`ErrorPrimitive.Root`;var lX=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({children:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=sK();if(a===void 0)return null;let o=r??String(a),s;return n[3]!==t||n[4]!==i||n[5]!==o?(s=(0,b.jsx)(BK.span,{...i,ref:t,children:o}),n[3]=t,n[4]=i,n[5]=o,n[6]=s):s=n[6],s});lX.displayName=`ErrorPrimitive.Message`;var uX=PK({Message:()=>lX,Root:()=>cX}),dX=e=>{let t=J(2),n=Y(void 0),r;return t[0]===e?r=t[1]:(r=t=>{n.current&&=(n.current(),void 0),t&&(n.current=e(t))},t[0]=e,t[1]=r),r},fX=(e,t)=>{let n=e.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(em|px|rem)$/);if(!n)return 1/0;let r=Number(n[1]),i=n[2];return i===`px`?r:i===`em`?r*(parseFloat(getComputedStyle(t).fontSize)||16):i===`rem`?r*(parseFloat(getComputedStyle(document.documentElement).fontSize)||16):1/0},pX=e=>e.dataset.messageId,mX=()=>{let e=document.createElement(`div`);return e.dataset.auiTopAnchorReserve=``,e.style.height=`0px`,e.style.flexShrink=`0`,e.style.pointerEvents=`none`,e.setAttribute(`aria-hidden`,`true`),e},hX=(e,t)=>{let n=`${t}px`;return e.style.height!==n&&(e.style.height=n,!0)},gX=e=>{let t=window.devicePixelRatio||1;return Math.round(e*t)/t},_X=()=>{let e=J(4),t=Q(),n;e[0]===t.message?n=e[1]:(n=()=>t.message,e[0]=t.message,e[1]=n);let r=$(n),i;return e[2]===r?i=e[3]:(i=e=>{let t=()=>{r.setIsHovering(!0)},n=()=>{r.setIsHovering(!1)};return e.addEventListener(`mouseenter`,t),e.addEventListener(`mouseleave`,n),e.matches(`:hover`)&&queueMicrotask(()=>r.setIsHovering(!0)),()=>{e.removeEventListener(`mouseenter`,t),e.removeEventListener(`mouseleave`,n),r.setIsHovering(!1)}},e[2]=r,e[3]=i),dX(i)},vX=()=>{let e=J(2),t=fK(TX),n;return e[0]===t?n=e[1]:(n=e=>e.message.role===`user`&&e.message.index>0&&e.message.index===e.thread.messages.length-2&&e.thread.messages.at(-1)?.role===`assistant`&&(e.message.id===t||e.thread.isRunning),e[0]=t,e[1]=n),$(n)},yX=()=>{let e=J(2),t=fK(EX),n;return e[0]===t?n=e[1]:(n=e=>e.message.isLast&&e.message.role===`assistant`&&e.message.index>=1&&e.thread.messages.at(e.message.index-1)?.role===`user`&&(e.message.id===t||e.thread.isRunning),e[0]=t,e[1]=n),$(n)},bX=(e,t)=>{let n=J(3),r;return n[0]!==e||n[1]!==t?(r=n=>{if(e)return t.getState().registerAnchorElement(n)},n[0]=e,n[1]=t,n[2]=r):r=n[2],dX(r)},xX=e=>{let t=J(3),{active:n,threadViewportStore:r}=e,i;return t[0]!==n||t[1]!==r?(i=e=>{if(!n)return;let t=r.getState(),i=t.topAnchorMessageClamp;return t.registerAnchorTargetElement(e,{tallerThan:fX(i.tallerThan,e),visibleHeight:fX(i.visibleHeight,e)})},t[0]=n,t[1]=r,t[2]=i):i=t[2],dX(i)},SX=e=>{let t=J(7),n,r;t[0]===e?(n=t[1],r=t[2]):({forwardedRef:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i=_X(),a=u(n,i),o=$(DX),s;return t[3]!==o||t[4]!==r||t[5]!==a?(s=(0,b.jsx)(BK.div,{...r,ref:a,"data-message-id":o}),t[3]=o,t[4]=r,t[5]=a,t[6]=s):s=t[6],s},CX=e=>{let t=J(13),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({forwardedRef:n,threadViewportStore:i,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a=_X(),o=vX(),s=yX(),c=bX(o,i),l;t[4]!==s||t[5]!==i?(l={active:s,threadViewportStore:i},t[4]=s,t[5]=i,t[6]=l):l=t[6];let d=xX(l),f=u(n,a,c,d),p=$(OX),m=o?``:void 0,h=s?``:void 0,g;return t[7]!==p||t[8]!==r||t[9]!==f||t[10]!==m||t[11]!==h?(g=(0,b.jsx)(BK.div,{...r,ref:f,"data-message-id":p,"data-aui-top-anchor-user":m,"data-aui-top-anchor-target":h}),t[7]=p,t[8]=r,t[9]=f,t[10]=m,t[11]=h,t[12]=g):g=t[12],g},wX=Z((e,t)=>{let n=J(7),r=pK();if(r.getState().turnAnchor===`top`){let i;return n[0]!==t||n[1]!==e||n[2]!==r?(i=(0,b.jsx)(CX,{...e,forwardedRef:t,threadViewportStore:r}),n[0]=t,n[1]=e,n[2]=r,n[3]=i):i=n[3],i}let i;return n[4]!==t||n[5]!==e?(i=(0,b.jsx)(SX,{...e,forwardedRef:t}),n[4]=t,n[5]=e,n[6]=i):i=n[6],i});wX.displayName=`MessagePrimitive.Root`;function TX(e){return e.topAnchorTurn?.anchorId}function EX(e){return e.topAnchorTurn?.targetId}function DX(e){return e.message.id}function OX(e){return e.message.id}var kX={...rW,Text:()=>(0,b.jsxs)(`p`,{style:{whiteSpace:`pre-line`},children:[(0,b.jsx)(oX,{}),(0,b.jsx)(cG,{children:(0,b.jsx)(`span`,{style:{fontFamily:`revert`},children:` ●`})})]}),Image:()=>(0,b.jsx)(sX,{})},AX=e=>{let t=J(10);if(`children`in e){let n;return t[0]===e.children?n=t[1]:(n=(0,b.jsx)(bW,{children:e.children}),t[0]=e.children,t[1]=n),n}let n,r;t[2]===e?(n=t[3],r=t[4]):({components:n,...r}=e,t[2]=e,t[3]=n,t[4]=r);let i;t[5]===n?i=t[6]:(i=n?{...n,Text:n.Text??kX.Text,Image:n.Image??kX.Image}:kX,t[5]=n,t[6]=i);let a=i,o;return t[7]!==r||t[8]!==a?(o=(0,b.jsx)(bW,{components:a,...r}),t[7]=r,t[8]=a,t[9]=o):o=t[9],o};AX.displayName=`MessagePrimitive.Parts`;var jX=e=>{let t=J(12),n;return t[0]!==e.assistant||t[1]!==e.copied||t[2]!==e.hasAttachments||t[3]!==e.hasBranches||t[4]!==e.hasContent||t[5]!==e.last||t[6]!==e.lastOrHover||t[7]!==e.speaking||t[8]!==e.submittedFeedback||t[9]!==e.system||t[10]!==e.user?(n=t=>{let{role:n,attachments:r,parts:i,branchCount:a,isLast:o,speech:s,isCopied:c,isHovering:l}=t.message;return!(e.hasBranches===!0&&a<2||e.user&&n!==`user`||e.assistant&&n!==`assistant`||e.system&&n!==`system`||e.lastOrHover===!0&&!l&&!o||e.last!==void 0&&e.last!==o||e.copied===!0&&!c||e.copied===!1&&c||e.speaking===!0&&s==null||e.speaking===!1&&s!=null||e.hasAttachments===!0&&(n!==`user`||!r?.length)||e.hasAttachments===!1&&n===`user`&&r?.length||e.hasContent===!0&&i.length===0||e.hasContent===!1&&i.length>0||e.submittedFeedback!==void 0&&(t.message.metadata.submittedFeedback?.type??null)!==e.submittedFeedback)},t[0]=e.assistant,t[1]=e.copied,t[2]=e.hasAttachments,t[3]=e.hasBranches,t[4]=e.hasContent,t[5]=e.last,t[6]=e.lastOrHover,t[7]=e.speaking,t[8]=e.submittedFeedback,t[9]=e.system,t[10]=e.user,t[11]=n):n=t[11],$(n)},MX=e=>{let t=J(3),n,r;return t[0]===e?(n=t[1],r=t[2]):({children:n,...r}=e,t[0]=e,t[1]=n,t[2]=r),jX(r)?n:null};MX.displayName=`MessagePrimitive.If`;var NX=e=>{let{children:t}=e;return sK()===void 0?null:t};NX.displayName=`MessagePrimitive.Error`;var PX=e=>{let t=new Map;for(let n=0;n<e.length;n++){let r=e[n]?.parentId??n,i=t.get(r)??[];i.push(n),t.set(r,i)}let n=[];for(let[e,r]of t){let t=typeof e==`string`?e:void 0;n.push({groupKey:t,indices:r})}return n},FX=e=>{let t=J(4),n=$(KX),r;bb0:{if(n.length===0){let e;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[0]=e):e=t[0],r=e;break bb0}let i;t[1]!==e||t[2]!==n?(i=e(n),t[1]=e,t[2]=n,t[3]=i):i=t[3],r=i}return r},IX=e=>{let t=J(9),n,r;t[0]===e?(n=t[1],r=t[2]):({Fallback:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]!==n||t[4]!==r.toolName?(i=e=>e.tools.toolUIs[r.toolName]?.[0]?.render??n,t[3]=n,t[4]=r.toolName,t[5]=i):i=t[5];let a=$(i);if(!a)return null;let o;return t[6]!==a||t[7]!==r?(o=(0,b.jsx)(a,{...r}),t[6]=a,t[7]=r,t[8]=o):o=t[8],o},LX=e=>{let t=J(9),n,r;t[0]===e?(n=t[1],r=t[2]):({Fallback:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]!==n||t[4]!==r.name?(i=e=>{let t=e.dataRenderers.renderers[r.name]??n;return Array.isArray(t)?t[0]??n:t},t[3]=n,t[4]=r.name,t[5]=i):i=t[5];let a=$(i);if(!a)return null;let o;return t[6]!==a||t[7]!==r?(o=(0,b.jsx)(a,{...r}),t[6]=a,t[7]=r,t[8]=o):o=t[8],o},RX={Text:()=>(0,b.jsxs)(`p`,{style:{whiteSpace:`pre-line`},children:[(0,b.jsx)(oX,{}),(0,b.jsx)(cG,{children:(0,b.jsx)(`span`,{style:{fontFamily:`revert`},children:` ●`})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>(0,b.jsx)(sX,{}),File:()=>null,Unstable_Audio:()=>null,Group:({children:e})=>e},zX=e=>{let t=J(37),{components:n}=e,r;t[0]===n?r=t[1]:(r=n===void 0?{}:n,t[0]=n,t[1]=r);let{Text:i,Reasoning:a,Image:o,Source:s,File:c,Unstable_Audio:l,tools:u,data:d}=r,f=i===void 0?RX.Text:i,p=a===void 0?RX.Reasoning:a,m=o===void 0?RX.Image:o,h=s===void 0?RX.Source:s,g=c===void 0?RX.File:c,_=l===void 0?RX.Unstable_Audio:l,v;t[2]===u?v=t[3]:(v=u===void 0?{}:u,t[2]=u,t[3]=v);let y=v,x=Q(),S=$(qX),C=S.type;if(C===`tool-call`){let e=x.part.addToolResult,n=x.part.resumeToolCall,r=x.part.respondToToolApproval;if(`Override`in y){let i;return t[4]!==e||t[5]!==S||t[6]!==r||t[7]!==n||t[8]!==y.Override?(i=(0,b.jsx)(y.Override,{...S,addResult:e,resume:n,respondToApproval:r}),t[4]=e,t[5]=S,t[6]=r,t[7]=n,t[8]=y.Override,t[9]=i):i=t[9],i}let i=y.by_name?.[S.toolName]??y.Fallback,a;return t[10]!==i||t[11]!==e||t[12]!==S||t[13]!==r||t[14]!==n?(a=(0,b.jsx)(IX,{...S,Fallback:i,addResult:e,resume:n,respondToApproval:r}),t[10]=i,t[11]=e,t[12]=S,t[13]=r,t[14]=n,t[15]=a):a=t[15],a}if(S.status?.type===`requires-action`)throw Error(`Encountered unexpected requires-action status`);switch(C){case`text`:{let e;return t[16]!==f||t[17]!==S?(e=(0,b.jsx)(f,{...S}),t[16]=f,t[17]=S,t[18]=e):e=t[18],e}case`reasoning`:{let e;return t[19]!==p||t[20]!==S?(e=(0,b.jsx)(p,{...S}),t[19]=p,t[20]=S,t[21]=e):e=t[21],e}case`source`:{let e;return t[22]!==h||t[23]!==S?(e=(0,b.jsx)(h,{...S}),t[22]=h,t[23]=S,t[24]=e):e=t[24],e}case`image`:{let e;return t[25]!==m||t[26]!==S?(e=(0,b.jsx)(m,{...S}),t[25]=m,t[26]=S,t[27]=e):e=t[27],e}case`file`:{let e;return t[28]!==g||t[29]!==S?(e=(0,b.jsx)(g,{...S}),t[28]=g,t[29]=S,t[30]=e):e=t[30],e}case`audio`:{let e;return t[31]!==_||t[32]!==S?(e=(0,b.jsx)(_,{...S}),t[31]=_,t[32]=S,t[33]=e):e=t[33],e}case`data`:{let e=d?.by_name?.[S.name]??d?.Fallback,n;return t[34]!==e||t[35]!==S?(n=(0,b.jsx)(LX,{...S,Fallback:e}),t[34]=e,t[35]=S,t[36]=n):n=t[36],n}default:return console.warn(`Unknown message part type: ${C}`),null}},BX=CN(e=>{let t=J(5),{partIndex:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(zX,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(ZB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.partIndex===t.partIndex&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.Group===t.components?.Group),VX=e=>{let t=J(6),{status:n,component:r}=e,i=n.type===`running`,a;t[0]!==r||t[1]!==n?(a=(0,b.jsx)(r,{type:`text`,text:``,status:n}),t[0]=r,t[1]=n,t[2]=a):a=t[2];let o;return t[3]!==i||t[4]!==a?(o=(0,b.jsx)($B,{text:``,isRunning:i,children:a}),t[3]=i,t[4]=a,t[5]=o):o=t[5],o},HX=Object.freeze({type:`complete`}),UX=CN(e=>{let t=J(6),{components:n}=e,r=$(JX);if(n?.Empty){let e;return t[0]!==n.Empty||t[1]!==r?(e=(0,b.jsx)(n.Empty,{status:r}),t[0]=n.Empty,t[1]=r,t[2]=e):e=t[2],e}let i=n?.Text??RX.Text,a;return t[3]!==r||t[4]!==i?(a=(0,b.jsx)(VX,{status:r,component:i}),t[3]=r,t[4]=i,t[5]=a):a=t[5],a},(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),WX=e=>{let t=J(9),{groupingFunction:n,components:r}=e,i=$(YX),a=FX(n),o;bb0:{if(i===0){let e;t[0]===r?e=t[1]:(e=(0,b.jsx)(UX,{components:r}),t[0]=r,t[1]=e),o=e;break bb0}let e;if(t[2]!==r||t[3]!==a){let n;t[5]===r?n=t[6]:(n=(e,t)=>{let n=r?.Group??RX.Group;return(0,b.jsx)(n,{groupKey:e.groupKey,indices:e.indices,children:e.indices.map(e=>(0,b.jsx)(BX,{partIndex:e,components:r},e))},`group-${t}-${e.groupKey??`ungrouped`}`)},t[5]=r,t[6]=n),e=a.map(n),t[2]=r,t[3]=a,t[4]=e}else e=t[4];o=e}let s=o,c;return t[7]===s?c=t[8]:(c=(0,b.jsx)(b.Fragment,{children:s}),t[7]=s,t[8]=c),c};WX.displayName=`MessagePrimitive.Unstable_PartsGrouped`;var GX=e=>{let t=J(6),n,r;t[0]===e?(n=t[1],r=t[2]):({components:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;return t[3]!==n||t[4]!==r?(i=(0,b.jsx)(WX,{...r,components:n,groupingFunction:PX}),t[3]=n,t[4]=r,t[5]=i):i=t[5],i};GX.displayName=`MessagePrimitive.Unstable_PartsGroupedByParentId`;function KX(e){return e.message.parts}function qX(e){return e.part}function JX(e){return e.message.status??HX}function YX(e){return e.message.parts.length}var XX=PK({AttachmentByIndex:()=>JW,Attachments:()=>XW,Content:()=>AX,Error:()=>NX,GenerativeUI:()=>YU,GroupedParts:()=>WW,If:()=>MX,PartByIndex:()=>aW,Parts:()=>AX,Quote:()=>GW,Root:()=>wX,Unstable_PartsGrouped:()=>WX,Unstable_PartsGroupedByParentId:()=>GX}),ZX=e=>{let t=J(2),n=dt(e),r;return t[0]===n?r=t[1]:(r=e=>{let t=new ResizeObserver(()=>{n()}),r=new MutationObserver(e=>{e.some(QX)&&n()});return t.observe(e),r.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{t.disconnect(),r.disconnect()}},t[0]=n,t[1]=r),dX(r)};function QX(e){return e.type!==`attributes`||e.attributeName!==`style`}var $X=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:r=!0})=>{let i=Y(null),a=$(e=>e.thread.messages.length>0),o=$(e=>e.thread.isRunning),s=Y(!1),c=Y(null),l=pK();e===void 0&&(e=l.getState().turnAnchor!==`top`);let d=Y(0),f=Y(0),p=Y(0),m=Y(0),h=Y(null),g=Y(e),_=Y(e);gN(()=>{let t=_.current;if(_.current=e,t||!e)return;let n=i.current;g.current=n!==null&&_I(n)},[e]);let v=hN(e=>{let t=i.current;t&&(g.current=!0,h.current=e,t.scrollTo({top:t.scrollHeight,behavior:e}))},[]),y=hN(()=>{c.current!==null&&(cancelAnimationFrame(c.current),c.current=null)},[]),b=hN(e=>{h.current=e,y(),c.current=requestAnimationFrame(()=>{c.current=null,v(e)})},[y,v]);gN(()=>()=>y(),[y]);let x=hN(()=>{let e=l.getState();return e.turnAnchor===`top`&&e.element.viewport===i.current&&e.element.anchor!==null},[l]),S=()=>{let t=i.current;if(!t)return;let n=l.getState().isAtBottom,r=_I(t);if(!(!r&&d.current<t.scrollTop)){let i=yI({scrollTop:d.current,scrollHeight:f.current},t);r?(vI(t)&&(h.current=null),e&&(g.current=!0)):i&&(y(),h.current=null,g.current=!1),(r||h.current===null)&&r!==n&&SK(l).setState({isAtBottom:r})}d.current=t.scrollTop,f.current=t.scrollHeight},C=ZX(()=>{let t=i.current;if(!t)return;let{scrollHeight:n,clientHeight:r}=t;if(n===p.current&&r===m.current)return;p.current=n,m.current=r;let a=h.current;a&&x()?h.current=null:a?v(a):e&&!(o&&x())&&g.current&&v(`instant`),S()}),w=dX(e=>{let t=()=>{h.current=null};return e.addEventListener(`scroll`,S),e.addEventListener(`pointerdown`,t),()=>{e.removeEventListener(`scroll`,S),e.removeEventListener(`pointerdown`,t)}});return gN(()=>{if(n){if(!a){s.current=!1;return}s.current||(s.current=!0,h.current===null&&b(`instant`))}},[a,b,n]),LJ(({behavior:e})=>{v(e)}),WL(`thread.runStart`,()=>{t&&l.getState().turnAnchor!==`top`&&b(`auto`)}),WL(`threads.selectionChanged`,()=>{r&&b(`instant`)}),u(C,w,i)},eZ=Z((e,t)=>{let n=J(6),r=Q(),i,a;n[0]===r?(i=n[1],a=n[2]):(i=()=>{let e=e=>{if(e.key===`Escape`&&!(e.defaultPrevented||r.thread.source===null)&&r.thread.getState().speech!=null){e.preventDefault();try{r.thread.stopSpeaking()}catch(e){let t=e;if(!(t instanceof Error)||t.message!==`No message is being spoken`)throw t}}};return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},a=[r],n[0]=r,n[1]=i,n[2]=a),X(i,a);let o;return n[3]!==e||n[4]!==t?(o=(0,b.jsx)(BK.div,{...e,ref:t}),n[3]=e,n[4]=t,n[5]=o):o=n[5],o});eZ.displayName=`ThreadPrimitive.Root`;var tZ=e=>{let{children:t}=e;return $(nZ)?t:null};tZ.displayName=`ThreadPrimitive.Empty`;function nZ(e){return e.thread.isEmpty}var rZ=e=>{let t=J(4),n;return t[0]!==e.disabled||t[1]!==e.empty||t[2]!==e.running?(n=t=>!(e.empty===!0&&!t.thread.isEmpty||e.empty===!1&&t.thread.isEmpty||e.running===!0&&!t.thread.isRunning||e.running===!1&&t.thread.isRunning||e.disabled===!0&&!t.thread.isDisabled||e.disabled===!1&&t.thread.isDisabled),t[0]=e.disabled,t[1]=e.empty,t[2]=e.running,t[3]=n):n=t[3],$(n)},iZ=e=>{let t=J(3),n,r;return t[0]===e?(n=t[1],r=t[2]):({children:n,...r}=e,t[0]=e,t[1]=n,t[2]=r),rZ(r)?n:null};iZ.displayName=`ThreadPrimitive.If`;var aZ=(e,t)=>{let n=J(3),r;return n[0]!==t||n[1]!==e?(r=n=>{if(!e)return;let r=e(),i=()=>{let e=t?t(n):n.offsetHeight;r.setHeight(e)},a=new ResizeObserver(i);return a.observe(n),i(),()=>{a.disconnect(),r.unregister()}},n[0]=t,n[1]=e,n[2]=r):r=n[2],dX(r)},oZ=e=>{let t=0,n=e;for(;n;)t+=n.offsetTop,n=n.offsetParent;return t},sZ=(e,t)=>{let n=0,r=e;for(;r&&r!==t;)n+=r.offsetTop,r=r.offsetParent;return r===t?n:oZ(e)-oZ(t)},cZ=({viewport:e,anchor:t,tallerThan:n,visibleHeight:r})=>{let i=sZ(t,e),a=t.offsetHeight;return i+Math.max(0,a-(a<=n?a:r))},lZ=({scrollHeight:e,...t})=>{let{viewport:n}=t,r=cZ(t)+n.clientHeight;return Math.max(0,r-e)},uZ=({viewport:e,reserve:t,...n})=>lZ({viewport:e,...n,scrollHeight:e.scrollHeight-t.offsetHeight}),dZ=e=>{let t=new ResizeObserver(e),n=new MutationObserver(e),r=null,i=null,a=null,o=()=>{t.disconnect(),n.disconnect(),r=null,i=null,a=null};return{target:(e,s,c)=>{(r!==e||i!==s||a!==c)&&(o(),t.observe(e),t.observe(s),t.observe(c),n.observe(c,{childList:!0,subtree:!0,characterData:!0}),r=e,i=s,a=c)},disconnect:o}},fZ=e=>{let t=null;return{schedule:()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))},cancel:()=>{t!==null&&(cancelAnimationFrame(t),t=null)}}},pZ=e=>{let t=null,n;function r(){let r=e.getState(),{viewport:o,anchor:s,target:c}=r.element,l=r.targetConfig;if(r.turnAnchor!==`top`||!o){a.disconnect(),t&&(hX(t,0),t.remove());return}if(!s&&!c&&!l&&r.topAnchorTurn){a.disconnect(),t?.parentElement&&t.parentElement.lastElementChild!==t&&t.parentElement.append(t);return}if(!s||!c||!l){a.disconnect(),t&&(hX(t,0),t.remove());return}if(t??=mX(),(t.parentElement!==c.parentElement||t.previousElementSibling!==c)&&c.after(t),a.target(o,s,c),hX(t,uZ({viewport:o,anchor:s,reserve:t,...l}))){i.schedule();return}let u=pX(s);if(u!==void 0&&n===u)return;let d=gX(cZ({viewport:o,anchor:s,...l}));Math.abs(o.scrollTop-d)>1&&o.scrollTo({top:d,behavior:`smooth`}),u!==void 0&&(n=u)}let i=fZ(r),a=dZ(i.schedule);i.schedule();let o=e.subscribe(i.schedule);return()=>{i.cancel(),o(),a.disconnect(),t?.remove()}},mZ=e=>{let t=J(4),n=pK(),r,i;t[0]!==e||t[1]!==n?(r=()=>{if(e)return pZ(n)},i=[e,n],t[0]=e,t[1]=n,t[2]=r,t[3]=i):(r=t[2],i=t[3]),gN(r,i)},hZ=(e,t)=>{if(!e)return!1;let n=t.findIndex(t=>t.id===e.targetId);return n<1?!1:t[n-1]?.id===e.anchorId&&t.slice(n+1).every(e=>e.role===`user`)},gZ=({isRunning:e,messages:t})=>{if(!e)return null;let n=t.at(-1),r=t.at(-2);return r?.role!==`user`||n?.role!==`assistant`?null:{anchorId:r.id,targetId:n.id}},_Z=e=>gZ(e)?.anchorId,vZ=e=>gZ(e)?.targetId,yZ=()=>aZ(fK(wZ),TZ),bZ=()=>dX(fK(EZ)),xZ=e=>{let t=J(19),n=pK(),r;t[0]===e?r=t[1]:(r=t=>{if(e)return _Z(t.thread)},t[0]=e,t[1]=r);let i=$(r),a;t[2]===e?a=t[3]:(a=t=>{if(e)return vZ(t.thread)},t[2]=e,t[3]=a);let o=$(a),s=fK(DZ),c;bb0:{if(!i||!o){c=null;break bb0}let e;t[4]!==i||t[5]!==o?(e={anchorId:i,targetId:o},t[4]=i,t[5]=o,t[6]=e):e=t[6],c=e}let l=c,u;t[7]!==e||t[8]!==s?(u=t=>e&&!!s&&hZ(s,t.thread.messages),t[7]=e,t[8]=s,t[9]=u):u=t[9];let d=$(u),f,p;t[10]!==n||t[11]!==s||t[12]!==d?(f=()=>{s&&!d&&n.getState().setTopAnchorTurn(null)},p=[n,s,d],t[10]=n,t[11]=s,t[12]=d,t[13]=f,t[14]=p):(f=t[13],p=t[14]),gN(f,p);let m,h;t[15]!==l||t[16]!==n?(m=()=>{if(!l)return;let e=n.getState(),t=e.topAnchorTurn;(t?.anchorId!==l.anchorId||t.targetId!==l.targetId)&&e.setTopAnchorTurn(l)},h=[l,n],t[15]=l,t[16]=n,t[17]=m,t[18]=h):(m=t[17],h=t[18]),gN(m,h)},SZ=Z((e,t)=>{let n=J(18),r,i,a,o,s,c;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],s=n[5],c=n[6]):({autoScroll:r,scrollToBottomOnRunStart:s,scrollToBottomOnInitialize:o,scrollToBottomOnThreadSwitch:c,children:i,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=s,n[6]=c);let l;n[7]!==r||n[8]!==o||n[9]!==s||n[10]!==c?(l={autoScroll:r,scrollToBottomOnRunStart:s,scrollToBottomOnInitialize:o,scrollToBottomOnThreadSwitch:c},n[7]=r,n[8]=o,n[9]=s,n[10]=c,n[11]=l):l=n[11];let d=$X(l),f=yZ(),p=bZ(),m=pK(),h;n[12]===m?h=n[13]:(h=m.getState(),n[12]=m,n[13]=h);let g=h.turnAnchor===`top`;xZ(g),mZ(g);let _=u(t,d,f,p),v;return n[14]!==i||n[15]!==_||n[16]!==a?(v=(0,b.jsx)(BK.div,{...a,ref:_,children:i}),n[14]=i,n[15]=_,n[16]=a,n[17]=v):v=n[17],v});SZ.displayName=`ThreadPrimitive.ViewportScrollable`;var CZ=Z((e,t)=>{let n=J(13),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({turnAnchor:a,topAnchorMessageClamp:i,...r}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let o;n[4]!==i||n[5]!==a?(o={turnAnchor:a,topAnchorMessageClamp:i},n[4]=i,n[5]=a,n[6]=o):o=n[6];let s;n[7]!==r||n[8]!==t?(s=(0,b.jsx)(SZ,{...r,ref:t}),n[7]=r,n[8]=t,n[9]=s):s=n[9];let c;return n[10]!==o||n[11]!==s?(c=(0,b.jsx)(wK,{options:o,children:s}),n[10]=o,n[11]=s,n[12]=c):c=n[12],c});CZ.displayName=`ThreadPrimitive.Viewport`;function wZ(e){return e.registerViewport}function TZ(e){return e.clientHeight}function EZ(e){return e.registerViewportElement}function DZ(e){return e.topAnchorTurn}var OZ=Z((e,t)=>{let n=J(3),r=aZ(fK(kZ),AZ),i=u(t,r),a;return n[0]!==e||n[1]!==i?(a=(0,b.jsx)(BK.div,{...e,ref:i}),n[0]=e,n[1]=i,n[2]=a):a=n[2],a});OZ.displayName=`ThreadPrimitive.ViewportFooter`;function kZ(e){return e.registerContentInset}function AZ(e){let t=parseFloat(getComputedStyle(e).marginTop)||0;return e.offsetHeight+t}var jZ=QK(`ThreadPrimitive.ScrollToBottom`,e=>{let t=J(5),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{behavior:r}=n,i=fK(MZ),a=pK(),o;return t[2]!==r||t[3]!==a?(o=()=>{a.getState().scrollToBottom({behavior:r})},t[2]=r,t[3]=a,t[4]=o):o=t[4],i?null:o},[`behavior`]);function MZ(e){return e.isAtBottom}var NZ=QK(`ThreadPrimitive.Suggestion`,e=>{let t=J(4),{prompt:n,send:r,clearComposer:i,autoSend:a}=e,o=r??a??!1,s;t[0]!==i||t[1]!==n||t[2]!==o?(s={prompt:n,send:o,clearComposer:i},t[0]=i,t[1]=n,t[2]=o,t[3]=s):s=t[3];let{disabled:c,trigger:l}=$G(s);return c?null:l},[`prompt`,`send`,`clearComposer`,`autoSend`,`method`]),PZ=PK({Empty:()=>tZ,If:()=>iZ,MessageByIndex:()=>IU,Messages:()=>BU,Root:()=>eZ,ScrollToBottom:()=>jZ,Suggestion:()=>NZ,SuggestionByIndex:()=>pG,Suggestions:()=>gG,Unstable_MessageById:()=>LU,Viewport:()=>CZ,ViewportFooter:()=>OZ,ViewportProvider:()=>wK}),FZ=Z((e,t)=>{let n=J(4),r=$(IZ),i=e.children??r,a;return n[0]!==e||n[1]!==t||n[2]!==i?(a=(0,b.jsx)(BK.span,{...e,ref:t,children:i}),n[0]=e,n[1]=t,n[2]=i,n[3]=a):a=n[3],a});FZ.displayName=`SuggestionPrimitive.Title`;function IZ(e){return e.suggestion.title}var LZ=Z((e,t)=>{let n=J(4),r=$(RZ),i=e.children??r,a;return n[0]!==e||n[1]!==t||n[2]!==i?(a=(0,b.jsx)(BK.span,{...e,ref:t,children:i}),n[0]=e,n[1]=t,n[2]=i,n[3]=a):a=n[3],a});LZ.displayName=`SuggestionPrimitive.Description`;function RZ(e){return e.suggestion.label}var zZ=QK(`SuggestionPrimitive.Trigger`,e=>{let t=J(4),{send:n,clearComposer:r}=e,i=$(BZ),a;t[0]!==r||t[1]!==i||t[2]!==n?(a={prompt:i,send:n,clearComposer:r},t[0]=r,t[1]=i,t[2]=n,t[3]=a):a=t[3];let{trigger:o,disabled:s}=$G(a);return s?null:o},[`send`,`clearComposer`]);function BZ(e){return e.suggestion.prompt}var VZ=PK({Description:()=>LZ,Title:()=>FZ,Trigger:()=>zZ}),HZ=Z((e,t)=>{let n=J(15),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({onClick:i,disabled:r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let o=$(UZ),{switchToNewThread:s}=aK(),c;n[4]===o?c=n[5]:(c=o?{"data-active":`true`,"aria-current":`true`}:null,n[4]=o,n[5]=c);let l;n[6]!==i||n[7]!==s?(l=P(i,s),n[6]=i,n[7]=s,n[8]=l):l=n[8];let u;return n[9]!==r||n[10]!==t||n[11]!==a||n[12]!==c||n[13]!==l?(u=(0,b.jsx)(BK.button,{type:`button`,...c,...a,ref:t,disabled:r,onClick:l}),n[9]=r,n[10]=t,n[11]=a,n[12]=c,n[13]=l,n[14]=u):u=n[14],u});HZ.displayName=`ThreadListPrimitive.New`;function UZ(e){return e.threads.newThreadId===e.threads.mainThreadId}var WZ=QK(`ThreadListPrimitive.LoadMore`,()=>{let{loadMore:e,disabled:t}=oK();return t?null:e}),[GZ,KZ]=M(`ThreadList`),qZ=GZ,JZ=ON(null),YZ=JZ.Provider,XZ=()=>AN(JZ),ZZ=Z((e,t)=>{let n=J(3),r;return n[0]!==e||n[1]!==t?(r=(0,b.jsx)(qZ.Provider,{scope:void 0,children:(0,b.jsx)(qZ.Slot,{scope:void 0,children:(0,b.jsx)(BK.div,{...e,ref:t})})}),n[0]=e,n[1]=t,n[2]=r):r=n[2],r});ZZ.displayName=`ThreadListPrimitive.Root`;var QZ=PK({ItemByIndex:()=>aG,Items:()=>sG,LoadMore:()=>WZ,New:()=>HZ,Root:()=>ZZ}),$Z=Z((e,t)=>{let n=$(e=>e.threads.mainThreadId===e.threadListItem.id),r=Y(null),i=Y(null),a=mN(()=>({triggerRef:r,moreRef:i}),[]),o=KZ(void 0),s=ct(),c=e=>{let t=s===`rtl`?`ArrowLeft`:`ArrowRight`,n=s===`rtl`?`ArrowRight`:`ArrowLeft`,a=r.current,c=i.current;if(a&&e.target===a){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=o().map(e=>e.ref.current).filter(e=>e!==null),n=t[t.indexOf(a)+(e.key===`ArrowDown`?1:-1)];n&&(n.focus(),e.preventDefault())}else e.key===t&&c&&(c.focus(),e.preventDefault())}else c&&e.target===c&&e.key===n&&(a?.focus(),e.preventDefault())};return(0,b.jsx)(YZ,{value:a,children:(0,b.jsx)(BK.div,{...n?{"data-active":`true`,"aria-current":`true`}:null,...e,onKeyDown:P(e.onKeyDown,c),ref:t})})});$Z.displayName=`ThreadListItemPrimitive.Root`;var eQ=QK(`ThreadListItemPrimitive.Archive`,()=>{let{archive:e}=tK();return e}),tQ=QK(`ThreadListItemPrimitive.Unarchive`,()=>{let{unarchive:e}=rK();return e}),nQ=QK(`ThreadListItemPrimitive.Delete`,()=>{let{delete:e}=nK();return e}),rQ=QK(`ThreadListItemPrimitive.Trigger`,()=>{let{switchTo:e}=iK();return e}),iQ=Z((e,t)=>{let n=J(3),r=XZ(),i=u(t,r?.triggerRef),a;return n[0]!==e||n[1]!==i?(a=(0,b.jsx)(qZ.ItemSlot,{scope:void 0,children:(0,b.jsx)(rQ,{...e,ref:i})}),n[0]=e,n[1]=i,n[2]=a):a=n[2],a});iQ.displayName=`ThreadListItemPrimitive.Trigger`;var aQ=PK({Archive:()=>eQ,Delete:()=>nQ,Root:()=>$Z,Title:()=>uG,Trigger:()=>iQ,Unarchive:()=>tQ}),oQ=ul(),sQ=ON(()=>{}),cQ=()=>AN(sQ),lQ=ON(!1),uQ=()=>AN(lQ),dQ=e=>{let t=J(26),n,r,i,a,o,s,c;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5],s=t[6],c=t[7]):({__scopeThreadListItemMore:n,open:o,defaultOpen:r,onOpenChange:a,sharedFocusGroup:c,modal:i,...s}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o,t[6]=s,t[7]=c);let l=c!==void 0&&c,u=l?!1:i??!0,d=oQ(n),f=r??!1,p;t[8]===a?p=t[9]:(p=a?{onChange:a}:{},t[8]=a,t[9]=p);let m;t[10]!==o||t[11]!==f||t[12]!==p?(m={prop:o,defaultProp:f,caller:`ThreadListItemMorePrimitive.Root`,...p},t[10]=o,t[11]=f,t[12]=p,t[13]=m):m=t[13];let[h,g]=Te(m),_;t[14]!==u||t[15]!==h||t[16]!==s||t[17]!==d||t[18]!==g?(_=(0,b.jsx)(Ml,{...d,...s,modal:u,open:h,onOpenChange:g}),t[14]=u,t[15]=h,t[16]=s,t[17]=d,t[18]=g,t[19]=_):_=t[19];let v;t[20]!==g||t[21]!==_?(v=(0,b.jsx)(sQ.Provider,{value:g,children:_}),t[20]=g,t[21]=_,t[22]=v):v=t[22];let y;return t[23]!==l||t[24]!==v?(y=(0,b.jsx)(lQ.Provider,{value:l,children:v}),t[23]=l,t[24]=v,t[25]=y):y=t[25],y};dQ.displayName=`ThreadListItemMorePrimitive.Root`;var fQ=Z((e,t)=>{let n=J(10),{__scopeThreadListItemMore:r,...i}=e,a=oQ(r),o=XZ(),s=cQ(),c=uQ(),l=u(t,o?.moreRef),d=ct()===`rtl`?`ArrowLeft`:`ArrowRight`,f=vq,p;n[0]!==d||n[1]!==s||n[2]!==c?(p=e=>{c&&e.key===d&&(e.preventDefault(),s(!0))},n[0]=d,n[1]=s,n[2]=c,n[3]=p):p=n[3];let m=P(i.onKeyDown,p),h;return n[4]!==f||n[5]!==l||n[6]!==i||n[7]!==a||n[8]!==m?(h=(0,b.jsx)(f,{...a,...i,onKeyDown:m,ref:l}),n[4]=f,n[5]=l,n[6]=i,n[7]=a,n[8]=m,n[9]=h):h=n[9],h});fQ.displayName=`ThreadListItemMorePrimitive.Trigger`;var pQ=Z((e,t)=>{let n=J(21),{__scopeThreadListItemMore:r,portalProps:i,sideOffset:a,...o}=e,s=a===void 0?4:a,c=oQ(r),l=cQ(),u=XZ(),d=uQ(),f=ct()===`rtl`?`ArrowRight`:`ArrowLeft`,p=al,m=yq,h;n[0]!==f||n[1]!==u?.moreRef||n[2]!==l||n[3]!==d?(h=e=>{d&&e.key===f&&(e.preventDefault(),l(!1),u?.moreRef.current?.focus())},n[0]=f,n[1]=u?.moreRef,n[2]=l,n[3]=d,n[4]=h):h=n[4];let g=P(o.onKeyDown,h),_;n[5]!==u?.moreRef||n[6]!==d?(_=()=>{d&&u?.moreRef.current?.focus()},n[5]=u?.moreRef,n[6]=d,n[7]=_):_=n[7];let v=P(o.onEscapeKeyDown,_),y;n[8]!==m||n[9]!==t||n[10]!==o||n[11]!==c||n[12]!==s||n[13]!==g||n[14]!==v?(y=(0,b.jsx)(m,{...c,...o,onKeyDown:g,onEscapeKeyDown:v,ref:t,sideOffset:s}),n[8]=m,n[9]=t,n[10]=o,n[11]=c,n[12]=s,n[13]=g,n[14]=v,n[15]=y):y=n[15];let x;return n[16]!==i||n[17]!==c||n[18]!==p.Portal||n[19]!==y?(x=(0,b.jsx)(p.Portal,{...c,...i,children:y}),n[16]=i,n[17]=c,n[18]=p.Portal,n[19]=y,n[20]=x):x=n[20],x});pQ.displayName=`ThreadListItemMorePrimitive.Content`;var mQ=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeThreadListItemMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=oQ(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(bq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});mQ.displayName=`ThreadListItemMorePrimitive.Item`;var hQ=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeThreadListItemMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=oQ(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(xq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});hQ.displayName=`ThreadListItemMorePrimitive.Separator`;var gQ=PK({Content:()=>pQ,Item:()=>mQ,Root:()=>dQ,Separator:()=>hQ,Trigger:()=>fQ}),_Q=(e,t)=>{let n=J(5),r=Y(null),i=Y(null),a,o;n[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=()=>()=>{i.current?.()},o=[],n[0]=a,n[1]=o):(a=n[0],o=n[1]),X(a,o);let s;return n[2]!==e||n[3]!==t?(s=()=>{i.current?.(),(function(){if(r.current||!e.current)return;let t=e.current;for(;t;){let{overflowY:e}=getComputedStyle(t);if(e===`scroll`||e===`auto`){r.current=t;break}t=t.parentElement}})();let n=r.current;if(!n)return;let a=n.scrollTop,o=n.style.scrollbarWidth,s=getComputedStyle(n),c=s.direction===`rtl`?`paddingLeft`:`paddingRight`,l=n.style[c],u=n.offsetWidth-n.clientWidth-parseFloat(s.borderLeftWidth)-parseFloat(s.borderRightWidth),d=n.ownerDocument,f=(n===d.documentElement||n===d.body)&&u<=0?(d.defaultView?.innerWidth??0)-d.documentElement.clientWidth:u;n.style.scrollbarWidth=`none`,f>0&&(n.style[c]=`${parseFloat(s[c])+f}px`);let p=()=>{n.style.scrollbarWidth=o,n.style[c]=l},m=()=>n.scrollTop=a;n.addEventListener(`scroll`,m);let h=setTimeout(()=>{n.removeEventListener(`scroll`,m),p(),i.current=null},t);i.current=()=>{clearTimeout(h),n.removeEventListener(`scroll`,m),p()}},n[2]=e,n[3]=t,n[4]=s):s=n[4],s},vQ=()=>{let e=J(3),t=$(yQ),n=$(bQ),r=t!==void 0&&t.completedAt===void 0&&n,[i,a]=fN(xQ),o,s;if(e[0]===r?(o=e[1],s=e[2]):(o=()=>{if(!r)return;a(Date.now());let e=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(e)},s=[r],e[0]=r,e[1]=o,e[2]=s),X(o,s),t!==void 0){if(t.completedAt!==void 0)return Math.max(0,t.completedAt-t.startedAt);if(r)return Math.max(0,i-t.startedAt)}};function yQ(e){let t=e.optional.part;return t?.type===`tool-call`?t.timing:void 0}function bQ(e){let t=e.optional.part;return t?.type===`tool-call`&&t.status.type===`running`}function xQ(){return Date.now()}var SQ=PK({AssistantRuntimeImpl:()=>YV,BaseAssistantRuntimeCore:()=>eH,CompositeContextProvider:()=>jI,DefaultThreadComposerRuntimeCore:()=>CH,MessageRepository:()=>dH,ThreadRuntimeImpl:()=>zV,getAutoStatus:()=>DB,splitLocalRuntimeOptions:()=>cK,useComposerInputPluginRegistryOptional:()=>Gq,useSmooth:()=>tX,useSmoothStatus:()=>JY,withSmoothContextProvider:()=>KY}),CQ=(e,t)=>`${e}:${t}`,wQ=e=>({id:e,status:`idle`}),TQ=e=>({threadId:e,metadata:wQ(e),messages:[],streamingMessageIndex:void 0,toolExecutions:{},runStatus:`idle`,queue:{steering:[],followUp:[]},contextUsage:void 0,compaction:{active:!1},retry:{active:!1,attempt:0},hostUiRequests:[],readiness:void 0,lastError:void 0,loadState:`pending`,lastSeq:0}),EQ=e=>e?.role===`assistant`,DQ=(e,t)=>e.status===t?e:{...e,status:t},OQ=(e,t,n)=>e.compactionActive===t.active&&e.retryActive===n.active&&e.retryAttempt===n.attempt?e:{...e,compactionActive:t.active,retryActive:n.active,retryAttempt:n.attempt},kQ=(e,t)=>{let n=t.metadata.status===`running`?`running`:t.metadata.status===`failed`?`failed`:`idle`,r=n!==`running`,i=t.seq!==void 0&&t.seq<e.lastSeq,a=t.metadata.compactionActive??(!r&&e.compaction.active),o=t.metadata.retryActive??(!r&&e.retry.active),s=i?e.compaction:a?{...e.compaction,active:!0}:{active:!1},c=i?e.retry:o?{active:!0,attempt:t.metadata.retryAttempt??e.retry.attempt}:{active:!1,attempt:0};return{...e,metadata:OQ(t.metadata,s,c),messages:t.messages,streamingMessageIndex:void 0,toolExecutions:{},runStatus:n,compaction:s,retry:c,queue:{steering:(t.metadata.queuedMessages??[]).filter(e=>e.mode===`steer`).map(e=>e.content),followUp:(t.metadata.queuedMessages??[]).filter(e=>e.mode===`followUp`).map(e=>e.content)},contextUsage:t.metadata.contextUsage??e.contextUsage,hostUiRequests:t.hostUiRequests??[],readiness:t.readiness??e.readiness,lastError:t.lastError,loadState:`loaded`}},AQ=(e,t,n)=>{let r=e.slice();return r[t]=n,r},jQ=(e,t,n)=>({...e,toolExecutions:{...e.toolExecutions,[t]:{toolCallId:t,status:`running`,...e.toolExecutions[t],...n}}}),MQ=(e,t)=>e.hostUiRequests.some(e=>e.id===t)?{...e,hostUiRequests:e.hostUiRequests.filter(e=>e.id!==t)}:e,NQ=(e,t)=>{if(t.type!==`snapshot`&&t.type!==`error`&&t.seq<=e.lastSeq)return e;let n=n=>n===e&&t.seq<=e.lastSeq?n:{...n,lastSeq:Math.max(e.lastSeq,t.seq)};switch(t.type){case`snapshot`:return n(kQ(e,t.snapshot));case`agent_start`:return n({...e,runStatus:`running`,lastError:void 0,metadata:DQ(e.metadata,`running`)});case`agent_end`:{let r=t.willRetry===!0;return n({...e,runStatus:r?`running`:`idle`,streamingMessageIndex:void 0,metadata:DQ(e.metadata,r?`running`:`idle`)})}case`message_start`:{let r=[...e.messages,t.message];return n({...e,messages:r,streamingMessageIndex:EQ(t.message)?r.length-1:e.streamingMessageIndex})}case`message_update`:{if(e.streamingMessageIndex!==void 0&&e.streamingMessageIndex<e.messages.length)return n({...e,messages:AQ(e.messages,e.streamingMessageIndex,t.message)});let r=[...e.messages,t.message];return n({...e,messages:r,streamingMessageIndex:r.length-1})}case`message_end`:return e.streamingMessageIndex!==void 0&&e.streamingMessageIndex<e.messages.length?n({...e,messages:AQ(e.messages,e.streamingMessageIndex,t.message),streamingMessageIndex:void 0}):n({...e,streamingMessageIndex:void 0});case`tool_execution_start`:return n(jQ(e,t.toolCallId,{toolName:t.toolName,args:t.args,status:`running`}));case`tool_execution_update`:return n(jQ(e,t.toolCallId,{...t.toolName===void 0?{}:{toolName:t.toolName},partialResult:t.partialResult,status:`running`}));case`tool_execution_end`:return n(jQ(e,t.toolCallId,{partialResult:t.result,status:t.isError?`error`:`complete`}));case`queue_update`:return n({...e,queue:{steering:t.steering,followUp:t.followUp}});case`compaction_start`:{let r={active:!0,reason:t.reason};return n({...e,compaction:r,metadata:OQ(e.metadata,r,e.retry)})}case`compaction_end`:{let t={active:!1};return n({...e,compaction:t,metadata:OQ(e.metadata,t,e.retry)})}case`auto_retry_start`:{let r={active:!0,attempt:t.attempt};return n({...e,retry:r,metadata:OQ(e.metadata,e.compaction,r)})}case`auto_retry_end`:{let t={active:!1,attempt:0};return n({...e,retry:t,metadata:OQ(e.metadata,e.compaction,t)})}case`context_usage`:return n({...e,contextUsage:t.contextUsage});case`session_info_changed`:{let r={...e.metadata};return t.name===void 0?delete r.title:r.title=t.name,n({...e,metadata:r})}case`thinking_level_changed`:return n({...e,metadata:{...e.metadata,config:{...e.metadata.config,thinkingLevel:t.level}}});case`extension_ui_request`:return e.hostUiRequests.some(e=>e.id===t.request.id)?n(e):n({...e,hostUiRequests:[...e.hostUiRequests,t.request]});case`extension_ui_resolved`:return n(MQ(e,t.requestId));case`error`:return n({...e,lastError:t.error,runStatus:`failed`,metadata:DQ(e.metadata,`failed`)});case`agent_settled`:case`entry_appended`:return n(e);default:return n(e)}},PQ=e=>{let t=new Map,n=[];for(let r of e)r.toolCallId!==void 0&&IQ(r)?t.has(r.toolCallId)?n.push(r):t.set(r.toolCallId,r):n.push(r);return{toolAssociated:t,freeStanding:n}},FQ=(e,t)=>({requestId:e,confirmed:t}),IQ=e=>{switch(e.kind){case`confirm`:return{id:e.id,prompt:`${e.title}\n${e.message}`};case`select`:return e.options.length===0?void 0:{id:e.id,prompt:e.title,display:`select`,options:e.options.map((e,t)=>({id:String(t),kind:`_${t}`,label:e}))};case`input`:case`editor`:return{id:e.id,prompt:e.title,display:`text`}}},LQ=(e,t)=>{if(e.kind===`confirm`)return FQ(e.id,t.approved);if(!t.approved)return{requestId:e.id,dismissed:!0};let n=e.kind===`select`?e.options.find((e,n)=>String(n)===t.optionId):t.text;if(n===void 0)throw Error(`Pi ${e.kind} request "${e.id}" was not answered with ${e.kind===`select`?`one of its options`:`text`}`);return{requestId:e.id,value:n}},RQ=e=>{if(typeof e==`string`)return e;if(typeof e==`object`&&e){if(e.dismissed)return;if(typeof e.value==`string`)return e.value}},zQ=(e,t)=>{let n=RQ(t);return n===void 0?{requestId:e,dismissed:!0}:{requestId:e,value:n}};function BQ(e){let t=e.match(/^data:([^;,]+)(?:;[^;,]+)*;base64,(.*)$/i);return t?{mimeType:t[1].toLowerCase(),data:t[2]}:null}function VQ(e,t,n,...r){if(!n)return;let i=n=>{try{console.error(`[${e}] ${t} callback threw an error`,n)}catch{}};try{let e=n(...r);if(e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`)return Promise.resolve(e).then(()=>void 0,e=>i(e))}catch(e){i(e)}}var HQ=e=>`pi-msg:${e}`,UQ=e=>`pi-step:${e}`,WQ=(e,t)=>/^data:/i.test(e)?e:`data:${t};base64,${e}`,GQ=e=>new Date(typeof e.timestamp==`number`?e.timestamp:0),KQ=e=>{if(!e)return{};let t=e.filter(e=>e.type===`text`).map(e=>e.text).join(``);return e.every(e=>e.type===`text`)?{result:t}:{result:t,modelContent:e.flatMap(e=>{if(e.type===`text`)return[{type:`text`,text:e.text}];let t=BQ(e.data);return[{type:`file`,data:t?.data??e.data,mediaType:t?.mimeType??e.mimeType}]})}},qQ=e=>{if(e==null)return;let t=e.content;if(Array.isArray(t))return t.filter(e=>typeof e==`object`&&!!e&&(e.type===`text`&&typeof e.text==`string`||e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`))},JQ=e=>typeof e==`string`?[{type:`text`,text:e}]:e.map(e=>e.type===`image`?{type:`image`,image:WQ(e.data,e.mimeType)}:{type:`text`,text:e.text}),YQ=(e,t)=>({type:`data`,name:e,data:t}),XQ=e=>{let t=new Map;for(let n of e){if(n.role!==`toolResult`)continue;let e=n;t.set(e.toolCallId,{...KQ(qQ({content:e.content})),isError:e.isError,details:e.details})}return t},ZQ=(e,t,n,r,i,a)=>{let o=UQ(n);e.lastAssistant=t,e.steps.push({messageId:o,usage:{inputTokens:t.usage?.input??0,outputTokens:t.usage?.output??0}});for(let n of t.content)if(n.type===`text`)e.parts.push({type:`text`,text:n.text,parentId:o});else if(n.type===`thinking`){let t=n.thinking||(n.redacted?`[reasoning redacted]`:``);e.parts.push({type:`reasoning`,text:t,parentId:o})}else if(n.type===`toolCall`){let t=i.get(n.id),s=r.toolExecutions[n.id],c=t??KQ(qQ(s?.partialResult)),l=t?.isError??s?.status===`error`,u=a.get(n.id),d=u&&IQ(u),f={type:`tool-call`,toolCallId:n.id,toolName:n.name,args:n.arguments??{},argsText:JSON.stringify(n.arguments??{}),parentId:o,...c.result===void 0?{}:{result:c.result},...c.modelContent===void 0?{}:{modelContent:c.modelContent},...l?{isError:!0}:{},...d?{approval:d}:{}};d&&(e.hasPendingHostUi=!0),e.parts.push(f)}},QQ=(e,t,n)=>{let r=e.lastAssistant,i=$Q(e,t,n);return{id:HQ(e.firstIndex),role:`assistant`,createdAt:GQ(r),content:e.parts,...i?{status:i}:{},metadata:{steps:e.steps,custom:{pi:{provider:r.provider,model:r.model,api:r.api,usage:r.usage,stopReason:r.stopReason,...r.errorMessage?{errorMessage:r.errorMessage}:{}}}}}},$Q=(e,t,n)=>{if(e.hasPendingHostUi)return{type:`requires-action`,reason:`interrupt`};let r=e.lastAssistant;return t.runStatus===`running`&&n&&r.stopReason!==`error`&&r.stopReason!==`aborted`?{type:`running`}:r.stopReason===`error`?{type:`incomplete`,reason:`error`,...r.errorMessage?{error:r.errorMessage}:{}}:r.stopReason===`aborted`?{type:`incomplete`,reason:`cancelled`}:r.stopReason===`length`?{type:`incomplete`,reason:`length`}:{type:`complete`,reason:`stop`}},e$=e=>{let{messages:t}=e,n=XQ(t),r=PQ(e.hostUiRequests).toolAssociated,i=[],a=null,o=t=>{a&&=(i.push(QQ(a,e,t)),null)};return t.forEach((s,c)=>{let l=c===t.length-1;switch(s.role){case`assistant`:a||={firstIndex:c,parts:[],steps:[],lastAssistant:s,hasPendingHostUi:!1},ZQ(a,s,c,e,n,r),l&&o(!0);break;case`toolResult`:break;case`user`:o(!1),i.push({id:HQ(c),role:`user`,createdAt:GQ(s),content:JQ(s.content)});break;case`bashExecution`:{o(!1);let e=s;i.push(t$(c,e,`pi-bash-execution`,{command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath}));break}case`custom`:{o(!1);let e=s;if(!e.display)break;i.push({id:HQ(c),role:`assistant`,createdAt:GQ(e),content:[YQ(`pi-custom-message`,{customType:e.customType,details:e.details}),...JQ(e.content)]});break}case`branchSummary`:{o(!1);let e=s;i.push(t$(c,e,`pi-branch-summary`,{summary:e.summary,fromId:e.fromId}));break}case`compactionSummary`:{o(!1);let e=s;i.push(t$(c,e,`pi-compaction-summary`,{summary:e.summary,tokensBefore:e.tokensBefore}));break}default:o(!1),i.push(t$(c,s,`pi-unsupported-message`,{role:s.role,message:s}))}}),o(!0),i},t$=(e,t,n,r)=>({id:HQ(e),role:`assistant`,createdAt:GQ(t),content:[YQ(n,r)]}),n$=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()===t.getTime():void 0,r$=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype,i$=(e,t)=>{if(e===t)return!0;let n=n$(e,t);if(n!==void 0)return n;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!i$(e[n],t[n]))return!1;return!0}if(r$(e)||r$(t)){if(!r$(e)||!r$(t))return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!i$(e[r],t[r]))return!1;return!0}return!1},a$=(e,t)=>e.id===t.id&&e.role===t.role&&i$(e.createdAt,t.createdAt)&&i$(e.content,t.content)&&i$(e.status,t.status)&&i$(e.metadata,t.metadata),o$=(e,t)=>{let n=e.length!==t.length,r=e.map((e,r)=>{let i=t[r];return i&&a$(e,i)?i:(n=!0,e)});return n?r:t},s$=(e,t)=>o$(e$(e),t),c$={snapshot:!0,agent_start:!0,agent_end:!0,agent_settled:!0,turn_start:!0,turn_end:!0,message_start:!0,message_update:!0,message_end:!0,tool_execution_start:!0,tool_execution_update:!0,tool_execution_end:!0,queue_update:!0,compaction_start:!0,compaction_end:!0,entry_appended:!0,auto_retry_start:!0,auto_retry_end:!0,session_info_changed:!0,thinking_level_changed:!0,context_usage:!0,extension_ui_request:!0,extension_ui_resolved:!0,error:!0},l$=e=>Object.prototype.hasOwnProperty.call(c$,e),u$=e=>e instanceof Error?e.message:String(e),d$=e=>{if(typeof globalThis.requestAnimationFrame==`function`){globalThis.requestAnimationFrame(()=>e());return}setTimeout(e,16)},f$=e=>{for(let t of e)try{t()}catch(e){console.error(`[react-pi] Listener threw an error`,e)}},p$=new Set([`snapshot`,`agent_start`,`agent_end`,`message_start`,`message_update`,`message_end`,`tool_execution_update`,`tool_execution_end`,`extension_ui_request`,`extension_ui_resolved`]),m$=new Set([`message_update`,`tool_execution_update`]),h$=new Set([`snapshot`,`agent_start`,`agent_end`,`queue_update`,`compaction_start`,`compaction_end`,`auto_retry_start`,`auto_retry_end`,`session_info_changed`,`thinking_level_changed`,`context_usage`,`extension_ui_request`,`extension_ui_resolved`,`error`]),g$=e=>{let t=/^data:([^;,]+)(?:;base64)?,(.*)$/is.exec(e);return t?{type:`image`,mimeType:t[1].toLowerCase(),data:t[2]}:{type:`image`,mimeType:`image/png`,data:e}},_$=e=>[...e.content,...e.attachments?.flatMap(e=>e.content??[])??[]],v$=(e,t)=>{let n=_$(e),r=[],i=[];for(let e of n)e.type===`text`?r.push(e.text):e.type===`image`&&i.push(g$(e.image));return{content:r.join(`
92
+ `),DV=`ui://`,OV=e=>!!e?.startsWith(DV),kV=e=>e.display===`text`||e.allowFreeform===!0,AV={"allow-once":!0,"allow-always":!0,"reject-once":!1,"reject-always":!1},jV=(e,t)=>{let n=t.text;if(n!==void 0&&!kV(e))throw Error(`Tool approval "${e.id}" does not accept a free-form answer; the request must declare display "text" or allowFreeform`);let r,i;if(`optionId`in t){let n=e.options?.find(e=>e.id===t.optionId);if(!n)throw Error(`Tool approval has no option with id "${t.optionId}"`);if(`approved`in t)r=t.approved;else{if(!Object.hasOwn(AV,n.kind))throw Error(`Tool approval option "${n.id}" has a custom kind "${n.kind}"; respond with an explicit approved value instead`);r=AV[n.kind]}i=n.id}else if(`approved`in t)r=t.approved;else{if(e.display!==`text`&&e.display!==`select`)throw Error(`Tool approval "${e.id}" is a decision, not a question; respond with an explicit approved value, optionally alongside the answer`);r=!0}return{approvalId:e.id,approved:r,...i!==void 0&&{optionId:i},...n!==void 0&&{text:n},...t.reason!=null&&{reason:t.reason}}},MV=class{get path(){return this.contentBinding.path}contentBinding;messageApi;threadApi;constructor(e,t,n){this.contentBinding=e,this.messageApi=t,this.threadApi=n,this.__internal_bindMethods()}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.respondToToolApproval=this.respondToToolApproval.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to add tool result to non-tool message part`);if(!this.messageApi)throw Error(`Message API is not available. This is likely a bug in assistant-ui.`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=this.messageApi.getState();if(!n)throw Error(`Message is not available`);let r=t.toolName,i=t.toolCallId,a=iR.toResponse(e);this.threadApi.getState().addToolResult({messageId:n.id,toolName:r,toolCallId:i,result:a.result,isError:a.isError,...a.artifact!==void 0&&{artifact:a.artifact},...a.modelContent!==void 0&&{modelContent:a.modelContent}})}resumeToolCall(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to resume tool call on non-tool message part`);if(!this.threadApi)throw Error(`Thread API is not available`);let n=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:n,payload:e})}respondToToolApproval(e){let t=this.contentBinding.getState();if(!t)throw Error(`Message part is not available`);if(t.type!==`tool-call`)throw Error(`Tried to respond to tool approval on non-tool message part`);if(!t.approval||t.approval.approved!==void 0||t.approval.resolution!==void 0)throw Error(`Tool call has no pending approval`);if(!this.threadApi)throw Error(`Thread API is not available`);return this.threadApi.getState().respondToToolApproval(jV(t.approval,e))}subscribe(e){return this.contentBinding.subscribe(e)}},NV=(e,t)=>{let n=e.content[t];if(!n)return xI;let r=gL(e,t,n);return Object.freeze({...n,[cB]:n[cB],status:r})},PV=class{get path(){return this._core.path}_core;_threadBinding;constructor(e,t){this._core=e,this._threadBinding=t,this.composer=new TV(new AI({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:`edit`},getState:this._getEditComposerRuntimeCore,subscribe:e=>this._threadBinding.subscribe(e)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}__internal_bindMethods(){this.reload=this.reload.bind(this),this.delete=this.delete.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}composer;_getEditComposerRuntimeCore=()=>this._threadBinding.getState().getEditComposer(this._core.getState().id);getState(){return this._core.getState()}delete(){let e=this._core.getState();return this._threadBinding.getState().deleteMessage(e.id)}reload(e={}){let t=this._getEditComposerRuntimeCore(),n=t??this._threadBinding.getState().composer,r=t??n,{runConfig:i=r.runConfig}=e,a=this._core.getState();if(a.role!==`assistant`)throw Error(`Can only reload assistant messages`);this._threadBinding.getState().startRun({parentId:a.parentId,sourceId:a.id,runConfig:i})}speak(){let e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){let e=this._core.getState();if(this._threadBinding.getState().speech?.messageId===e.id)this._threadBinding.getState().stopSpeaking();else throw Error(`Message is not being spoken`)}submitFeedback({type:e,comment:t}){let n=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:n.id,type:e,...t===void 0?void 0:{comment:t}})}switchToBranch({position:e,branchId:t}){let n=this._core.getState();if(t&&e)throw Error(`May not specify both branchId and position`);if(!t&&!e)throw Error(`Must specify either branchId or position`);let r=this._threadBinding.getState().getBranches(n.id),i=t;if(e===`previous`?i=r[n.branchNumber-2]:e===`next`&&(i=r[n.branchNumber]),!i)throw Error(`Branch not found`);this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return EV(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw Error(`Message part index must be >= 0`);return new MV(new OI({path:{...this.path,ref:`${this.path.ref}.content[${e}]`,messagePartSelector:{type:`index`,index:e}},getState:()=>NV(this.getState(),e),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new MV(new OI({path:{...this.path,ref:`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:`toolCallId`,toolCallId:e}},getState:()=>{let t=this._core.getState(),n=t.content.findIndex(t=>t.type===`tool-call`&&t.toolCallId===e);return n===-1?xI:NV(t,n)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new vV(new OI({path:{...this.path,ref:`${this.path.ref}.attachments[${e}]`,attachmentSource:`message`,attachmentSelector:{type:`index`,index:e}},getState:()=>{let t=this.getState().attachments?.[e];return t?{...t,source:`message`}:xI},subscribe:e=>this._core.subscribe(e)}))}},FV=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{},...e.stream?{stream:e.stream}:{}}),IV=e=>({parentId:e.parentId??null,sourceId:e.sourceId??null,runConfig:e.runConfig??{}}),LV=(e,t)=>typeof t==`string`?{createdAt:new Date,parentId:e.at(-1)?.id??null,sourceId:null,runConfig:{},role:`user`,content:[{type:`text`,text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:t.createdAt??new Date,parentId:t.parentId===void 0?e.at(-1)?.id??null:t.parentId,sourceId:t.sourceId??null,role:t.role??`user`,content:t.content,attachments:t.attachments??[],metadata:t.metadata??{custom:{}},runConfig:t.runConfig??{},startRun:t.startRun},RV=e=>{if(e.isRunning!==void 0)return e.isRunning;let t=e.messages.at(-1);return t?.role===`assistant`&&t.status.type===`running`},zV=(e,t)=>Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:RV(e),messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech,voice:e.voice}),BV=class{get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}_threadBinding;_stateBinding;constructor(e,t){let n=new OI({path:e.path,getState:()=>zV(e.getState(),t.getState()),subscribe:n=>{let r=e.subscribe(n),i=t.subscribe(n);return()=>CI([r,i])}});this._stateBinding=n,this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>n.getState(),outerSubscribe:t=>e.outerSubscribe(t),subscribe:t=>e.subscribe(t)},this.composer=new wV(new AI({path:{...this.path,ref:`${this.path.ref}.composer`,composerSource:`thread`},getState:()=>this._threadBinding.getState().composer,subscribe:e=>this._threadBinding.subscribe(e)})),this.__internal_bindMethods()}__internal_bindMethods(){this.append=this.append.bind(this),this.deleteMessage=this.deleteMessage.bind(this),this.resumeRun=this.resumeRun.bind(this),this.importExternalState=this.importExternalState.bind(this),this.exportExternalState=this.exportExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.unstable_notifySessionReset=this.unstable_notifySessionReset.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.connectVoice=this.connectVoice.bind(this),this.disconnectVoice=this.disconnectVoice.bind(this),this.muteVoice=this.muteVoice.bind(this),this.unmuteVoice=this.unmuteVoice.bind(this),this.getVoiceVolume=this.getVoiceVolume.bind(this),this.subscribeVoiceVolume=this.subscribeVoiceVolume.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getState=this.getState.bind(this)}composer;getState(){return this._threadBinding.getStateState()}append(e){let t=this._threadBinding.getState().append(LV(this._threadBinding.getState().messages,e));Promise.resolve(t).catch(e=>{if(!pV(e))throw e})}deleteMessage(e){return this._threadBinding.getState().deleteMessage(e)}subscribe(e){return this._stateBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}startRun(e){return this._threadBinding.getState().startRun(IV(e))}resumeRun(e){return this._threadBinding.getState().resumeRun(FV(e))}exportExternalState(){return this._threadBinding.getState().exportExternalState()}importExternalState(e){this._threadBinding.getState().importExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}unstable_notifySessionReset(){this._threadBinding.getState().unstable_notifySessionReset()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}connectVoice(){this._threadBinding.getState().connectVoice()}disconnectVoice(){this._threadBinding.getState().disconnectVoice()}getVoiceVolume(){return this._threadBinding.getState().getVoiceVolume()}subscribeVoiceVolume(e){return this._threadBinding.getState().subscribeVoiceVolume(e)}muteVoice(){this._threadBinding.getState().muteVoice()}unmuteVoice(){this._threadBinding.getState().unmuteVoice()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw Error(`Message index must be >= 0`);return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[${e}]`,messageSelector:{type:`index`,index:e}},()=>{let t=this._threadBinding.getState().messages,n=t[e];if(n)return{message:n,parentId:t[e-1]?.id??null,index:e}})}getMessageById(e){return this._getMessageRuntime({...this.path,ref:`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:`messageId`,messageId:e}},()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new PV(new OI({path:e,getState:()=>{let{message:e,parentId:n,index:r}=t()??{},{messages:i,speech:a}=this._threadBinding.getState();if(!e||n===void 0||r===void 0)return xI;let o=this._threadBinding.getState().getBranches(e.id);return{...e,[cB]:e[cB],index:r,isLast:i.at(-1)?.id===e.id,parentId:n,branchNumber:o.indexOf(e.id)+1,branchCount:o.length,speech:a?.messageId===e.id?a:void 0}},subscribe:e=>this._threadBinding.subscribe(e)}),this._threadBinding)}_eventSubscriptionSubjects=new Map;unstable_on(e,t){let n=this._eventSubscriptionSubjects.get(e);return n||(n=new jI({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,n)),n.subscribe(t)}},VV=(e,t)=>({attachments:[],attachmentAccept:`*`,async addAttachment(){throw e},async removeAttachment(){throw e},isEditing:t,canCancel:!1,canSend:!1,isEmpty:!0,text:``,setText(){throw e},role:`user`,setRole(){throw e},runConfig:{},setRunConfig(){throw e},async reset(){},async clearAttachments(){},send(){throw e},cancel(){},queue:[],moveQueueItem(){},removeQueueItem(){},dictation:void 0,startDictation(){throw e},stopDictation(){},quote:void 0,setQuote(){throw e},subscribe(){return()=>{}},unstable_on(){return()=>{}}}),HV=class extends TI{switchToBranch(){throw this.error}append(){throw this.error}deleteMessage(){throw this.error}startRun(){throw this.error}resumeRun(){throw this.error}cancelRun(){throw this.error}unstable_notifySessionReset(){throw this.error}addToolResult(){throw this.error}resumeToolCall(){throw this.error}respondToToolApproval(){throw this.error}speak(){throw this.error}stopSpeaking(){throw this.error}connectVoice(){throw this.error}disconnectVoice(){throw this.error}muteVoice(){throw this.error}unmuteVoice(){throw this.error}submitFeedback(){throw this.error}exportExternalState(){throw this.error}importExternalState(){throw this.error}beginEdit(){throw this.error}import(){throw this.error}reset(){throw this.error}getModelContext(){return{}}getEditComposer(){}getVoiceVolume=()=>0;subscribeVoiceVolume=()=>()=>{};speech=void 0;voice=void 0;capabilities={switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,delete:!1,reload:!1,refetchThread:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1};isDisabled=!1;isSendDisabled=!1;state=null;suggestions=[];extras=void 0;unstable_on(){return()=>{}}},UV=e=>{let t=J(6),{adapters:n,children:r}=e,i=jN(rB),a;t[0]!==n||t[1]!==i?(a={...i,...n},t[0]=n,t[1]=i,t[2]=a):a=t[2];let o=a,s;return t[3]!==r||t[4]!==o?(s=(0,b.jsx)(rB.Provider,{value:o,children:r}),t[3]=r,t[4]=o,t[5]=s):s=t[5],s},WV=class{get path(){return this._core.path}_core;_threadListBinding;constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.updateCustom=this.updateCustom.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(e){let t=this._core.getState();return this._threadListBinding.switchToThread(t.id,e)}rename(e){let t=this._core.getState();return this._threadListBinding.rename(t.id,e)}updateCustom(e){let t=this._core.getState();if(!this._threadListBinding.updateCustom)throw Error(`Thread list runtime does not support updating custom metadata`);return this._threadListBinding.updateCustom(t.id,e)}archive(){let e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){let e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){let e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){let e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(e){let t=this._core.getState();return this._threadListBinding.generateTitle(t.id,e)}unstable_on(e,t){let n=this._core.getState().isMain,r=this._core.getState().id;return this.subscribe(()=>{let i=this._core.getState(),a=i.isMain,o=i.id;(n!==a||r!==o)&&(n=a,r=o,(e!==`switchedTo`||a)&&(e===`switchedAway`&&a||jP([t],{},`Thread list item "${e}"`)))})}subscribe(e){return this._core.subscribe(e)}detach(){let e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}},GV=Promise.resolve(),KV=()=>{},qV=e=>({mainThreadId:e.mainThreadId,newThreadId:e.newThreadId,threadIds:e.threadIds,archivedThreadIds:e.archivedThreadIds,isLoading:e.isLoading,loadError:e.loadError,isLoadingMore:e.isLoadingMore??!1,hasMore:e.hasMore??!1,threadItems:e.threadItems}),JV=(e,t)=>{if(t===void 0)return xI;let n=e.getItemById(t);return n?{id:n.id,remoteId:n.remoteId,externalId:n.externalId,title:n.title,status:n.status,lastMessageAt:n.lastMessageAt,custom:n.custom,isMain:n.id===e.mainThreadId,isRunning:e.unstable_isThreadRunning?.(n.id)??!1}:xI},YV=class{_getState;_stateBinding;_core;_runtimeFactory;constructor(e,t=BV){this._core=e,this._runtimeFactory=t;let n=new kI({path:{},getState:()=>qV(e),subscribe:t=>e.subscribe(t)});this._getState=n.getState.bind(n),this._stateBinding=n,this._mainThreadListItemRuntime=new WV(new OI({path:{ref:`threadItems[main]`,threadSelector:{type:`main`}},getState:()=>JV(this._core,this._core.mainThreadId),subscribe:e=>this._core.subscribe(e)}),this._core),this.main=new t(new AI({path:{ref:`threads.main`,threadSelector:{type:`main`}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:t=>e.subscribe(t)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.unstable_subscribeThreadEvents=this.unstable_subscribeThreadEvents.bind(this),this.getLoadThreadsPromise=this.getLoadThreadsPromise.bind(this),this.reload=this.reload.bind(this),this.reloadMainThread=this.reloadMainThread.bind(this),this.loadMore=this.loadMore.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e,t){return this._core.switchToThread(e,t)}switchToNewThread(){return this._core.switchToNewThread()}unstable_subscribeThreadEvents(e){return this._core.unstable_subscribeThreadEvents?.(e)??KV}getLoadThreadsPromise(){return this._core.getLoadThreadsPromise()}reload(){return this._core.reload?.()??GV}reloadMainThread(){return this._core.reloadMainThread?.()??GV}loadMore(){return this._core.loadMore?.()??GV}getState(){return this._getState()}subscribe(e){return this._stateBinding.subscribe(e)}_mainThreadListItemRuntime;main;get mainItem(){return this._mainThreadListItemRuntime}_createItemStateBinding(e){return new OI({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>JV(this._core,e),subscribe:e=>this._core.subscribe(e)})}getById(e){return new this._runtimeFactory(new AI({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:e=>this._core.subscribe(e)}),this._createItemStateBinding(e))}getItemByIndex(e){return new WV(new OI({path:{ref:`threadItems[${e}]`,threadSelector:{type:`index`,index:e}},getState:()=>JV(this._core,this._core.threadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(e){return new WV(new OI({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:`archiveIndex`,index:e}},getState:()=>JV(this._core,this._core.archivedThreadIds[e]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(e){return new WV(this._createItemStateBinding(e),this._core)}},XV=class{threads;_thread;_core;constructor(e){this._core=e,this.threads=new YV(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}__internal_bindMethods(){this.registerModelContextProvider=this.registerModelContextProvider.bind(this)}get thread(){return this._thread}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}},ZV=new WeakMap,QV=e=>ZV.get(e)??0,$V=(e,t)=>QV(e)===t,eH=e=>{ZV.set(e,QV(e)+1)},tH=class{_contextProvider=new MI;registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},nH=Object.freeze([]),rH=`DEFAULT_THREAD_ID`,iH=Object.freeze([rH]),aH=Object.freeze({id:rH,remoteId:void 0,externalId:void 0,status:`regular`}),oH=Promise.resolve(),sH=Object.freeze(hM({[rH]:aH})),cH=class extends TI{_mainThreadId=rH;_threads=iH;_archivedThreads=nH;_threadData=sH;adapter={};get isLoading(){return this.adapter.isLoading??!1}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}get threadItems(){return this._threadData}getLoadThreadsPromise(){return oH}_mainThread;get mainThreadId(){return this._mainThreadId}threadFactory;constructor(e={},t){super(),this.threadFactory=t,this.__internal_setAdapter(e,!0)}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw Error(`Method not implemented.`)}getItemById(e){return Object.hasOwn(this._threadData,e)?this._threadData[e]:void 0}__internal_setAdapter(e,t=!1){let n=this.adapter;this.adapter=e;let r=e.threadId??rH,i=e.threads??nH,a=e.archivedThreads??nH,o=n.threadId??rH,s=n.threads??nH,c=n.archivedThreads??nH;(t||(n.isLoading??!1)!==(e.isLoading??!1)||o!==r||s!==i||c!==a)&&((s!==i||c!==a||o!==r)&&(this._threadData=hM(sH,Object.fromEntries(e.threads?.map(e=>[e.id,{...e,remoteId:e.remoteId,externalId:e.externalId,status:`regular`}])??[]),Object.fromEntries(e.archivedThreads?.map(e=>[e.id,{...e,remoteId:e.remoteId,externalId:e.externalId,status:`archived`}])??[]))),s!==i&&(this._threads=this.adapter.threads?.map(e=>e.id)??nH),c!==a&&(this._archivedThreads=this.adapter.archivedThreads?.map(e=>e.id)??nH),(t||o!==r)&&(t||eH(this._mainThread),this._mainThreadId=r,this._mainThread=this.threadFactory()),Object.hasOwn(this._threadData,this._mainThreadId)||(this._threadData=hM(this._threadData,{[this._mainThreadId]:{id:this._mainThreadId,remoteId:void 0,externalId:void 0,status:`regular`}})),this._notifySubscribers())}async reloadMainThread(){this._mainThread.unstable_refetchThread&&await this._mainThread.unstable_refetchThread()}async switchToThread(e,t){if(this._mainThreadId===e)return;let n=this.adapter.onSwitchToThread;if(!n)throw Error(`External store adapter does not support switching to thread`);await n(e)}async switchToNewThread(){let e=this.adapter.onSwitchToNewThread;if(!e)throw Error(`External store adapter does not support switching to new thread`);await e()}async rename(e,t){let n=this.adapter.onRename;if(!n)throw Error(`External store adapter does not support renaming`);await n(e,t)}async updateCustom(e,t){let n=this.adapter.onUpdateCustom;if(!n)throw Error(`External store adapter does not support updating custom metadata`);await n(e,t)}async detach(){}async archive(e){let t=this.adapter.onArchive;if(!t)throw Error(`External store adapter does not support archiving`);await t(e)}async unarchive(e){let t=this.adapter.onUnarchive;if(!t)throw Error(`External store adapter does not support unarchiving`);await t(e)}async delete(e){let t=this.adapter.onDelete;if(!t)throw Error(`External store adapter does not support deleting`);await t(e)}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){throw Error(`Method not implemented.`)}},lH={fromArray:e=>{let t=e.map(e=>_B(e,mB(),kB(e.content)));return{messages:t.map((e,n)=>({parentId:n>0?t[n-1].id:null,message:e}))}},fromBranchableArray:(e,t)=>({...t?.headId===void 0?void 0:{headId:t.headId},messages:e.map(({message:e,parentId:t})=>{if(!e.id)throw Error(`ExportedMessageRepository.fromBranchableArray: Each message must have an 'id' field set.`);return{parentId:t,message:_B(e,e.id,kB(e.content))}})})},uH=e=>{let t=e;for(;t.next;)t=t.next;return`current`in t?t:null},dH=class{_value=null;func;constructor(e){this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},fH=class{messages=new Map;head=null;root={children:[],next:null};updateLevels(e,t){let n=[{message:e,level:t}];for(;n.length>0;){let e=n.pop();e.message.level=e.level;for(let t of e.message.children){let r=this.messages.get(t);r&&n.push({message:r,level:e.level+1})}}}selectPathTo(e){for(let t=e;t;t=t.prev)(t.prev??this.root).next=t}performOp(e,t,n){let r=t.prev??this.root,i=e??this.root;if(n!==`relink`||r!==i){if(n===`relink`){for(let n=e;n;n=n.prev)if(n.current.id===t.current.id)throw Error(`MessageRepository(performOp/relink): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.`)}if(n!==`link`&&(r.children=r.children.filter(e=>e!==t.current.id),r.next===t)){let e=r.children.at(-1),t=e?this.messages.get(e):null;if(t===void 0)throw Error(`MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.`);r.next=t}if(n!==`cut`){i.children=[...i.children,t.current.id],t.prev=e,uH(t)===this.head?this.selectPathTo(t):i.next===null&&(i.next=t,this.head===i&&(this.head=uH(t)));let n=e?e.level+1:0;this.updateLevels(t,n)}}}_messages=new dH(()=>{let e=Array((this.head?.level??-1)+1);for(let t=this.head;t;t=t.prev)e[t.level]=t.current;return e});get headId(){return this.head?.current.id??null}get canonicalHeadId(){let e=this.head;for(;e?.current.metadata?.isOptimistic;)e=e.prev;return e?.current.id??null}getMessages(e){if(e===void 0||e===this.head?.current.id)return this._messages.value;let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.`);let n=Array(t.level+1);for(let e=t;e;e=e.prev)n[e.level]=e.current;return n}addOrUpdateMessage(e,t){let n=this.messages.get(t.id),r=e?this.messages.get(e):null;if(r===void 0)throw Error(`MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.`);if(n){n.current=t,this.performOp(r,n,`relink`),this._messages.dirty();return}let i={prev:r,current:t,next:null,children:[],level:r?r.level+1:0};this.messages.set(t.id,i),this.performOp(r,i,`link`),this.head===r&&(this.head=i),this._messages.dirty()}getMessage(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.`);return{parentId:t.prev?.current.id??null,message:t.current,index:t.level}}deleteMessage(e,t){let n=this.messages.get(e);if(!n)throw Error(`MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.`);let r=t===void 0?n.prev:t===null?null:this.messages.get(t);if(r===void 0)throw Error(`MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.`);for(let e of n.children){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.`);this.performOp(r,t,`relink`)}this.performOp(null,n,`cut`),this.messages.delete(e),this.head===n&&(this.head=uH(r??this.root)),this._messages.dirty()}getBranches(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.`);let{children:n}=t.prev??this.root;return n}evictOffBranchOptimisticMessages(e,t){if(!e)return;let n=new Set;for(let e=t;e;e=e.prev)n.add(e.current.id);let r=[];for(let t=e;t&&!n.has(t.current.id);t=t.prev)t.current.metadata?.isOptimistic&&r.push(t.current.id);for(let e of r)this.messages.has(e)&&this.deleteMessage(e)}switchToBranch(e){let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.`);let n=this.head;this.selectPathTo(t),this.head=uH(t),this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}let t=this.messages.get(e);if(!t)throw Error(`MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.`);let n=this.head;if(t.children.length>0){let e=[...t.children];for(;e.length>0;){let t=e.pop(),n=this.messages.get(t);if(n){for(let t of n.children)e.push(t);this.messages.delete(t)}}t.children=[],t.next=null}this.head=t,this.selectPathTo(t),this.evictOffBranchOptimisticMessages(n,this.head),this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){let e=[],t=[...this.root.children].reverse();for(;t.length>0;){let n=this.messages.get(t.pop());if(!n)continue;for(let e=n.children.length-1;e>=0;e--)t.push(n.children[e]);if(n.current.metadata?.isOptimistic)continue;let r=n.prev;for(;r&&r.current.metadata?.isOptimistic;)r=r.prev;e.push({message:n.current,parentId:r?.current.id??null})}return{headId:this.canonicalHeadId,messages:e}}import({headId:e,messages:t}){for(let{message:e,parentId:n}of t)this.addOrUpdateMessage(n,e);this.resetHead(e??t.at(-1)?.message.id??null)}},pH=Object.freeze([]);function*mH(e){for(let t of e)if(t?.role===`assistant`&&Array.isArray(t.content))for(let e of t.content)e&&e.type===`tool-call`&&(yield{part:e,messageId:t.id},e.messages?.length&&(yield*mH(e.messages)))}function hH(e,t){if(t===`*`)return!0;let n=t.split(`,`).map(e=>e.trim().toLowerCase()),r=e.name.toLowerCase(),i=e.type.split(`;`,1)[0].trim().toLowerCase();for(let e of n){if(e.startsWith(`.`)&&r.endsWith(e)||e.includes(`/`)&&e===i)return!0;if(e.endsWith(`/*`)){let t=e.split(`/`)[0];if(i.startsWith(`${t}/`))return!0}}return!1}function gH(e){let t=mB();return e.type===`image`?{id:t,type:`image`,name:e.filename??`image`,content:[e],status:{type:`complete`}}:e.type===`file`?{id:t,type:`document`,name:e.filename??`document`,contentType:e.mimeType,content:[e],status:{type:`complete`}}:e.type===`audio`?{id:t,type:`audio`,name:`audio.${e.audio.format}`,contentType:`audio/${e.audio.format}`,content:[e],status:{type:`complete`}}:{id:t,type:`data`,name:e.name,content:[e],status:{type:`complete`}}}function _H(e){let t=[];for(let n of e)n.type!==`text`&&t.push(gH(n));return t}var vH=e=>`content`in e&&!(`lastModified`in e),yH=e=>e.status.type===`complete`,bH=class{operations=new Set;start(){let e={cancelled:!1,attachmentIds:new Set};return this.operations.add(e),e}accept(e,t){return!e.cancelled&&(e.attachmentIds.add(t),!0)}finish(e){this.operations.delete(e)}isCancelled(e){return e.cancelled}cancel(e){for(let t of[...this.operations])t.attachmentIds.has(e)&&(t.cancelled=!0,this.operations.delete(t))}cancelAll(){for(let e of this.operations)e.cancelled=!0;this.operations.clear()}},xH=async(e,t)=>{if(Symbol.asyncIterator in e){for await(let n of e)if(!t(n))break}else t(await e)},SH=class extends TI{isEditing=!0;enrichWithComposerMetadata(e,t){return t?{...e,metadata:{...e.metadata,custom:{...e.metadata?.custom,...t}}}:e}get attachmentAccept(){return this.getAttachmentAdapter()?.accept??`*`}_attachments=[];get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}_text=``;get text(){return this._text}_role=`user`;get role(){return this._role}_runConfig={};get runConfig(){return this._runConfig}_quote=void 0;get quote(){return this._quote}setQuote(e){this._quote!==e&&(this._quote=e,this._notifySubscribers())}setText(e){this._text!==e&&(this._text=e,this._rebaseDictation(e),this._notifySubscribers())}_rebaseDictation(e){if(!this._dictation)return;this._dictationBaseText=e,this._currentInterimText=``;let{status:t,inputDisabled:n}=this._dictation;this._dictation=n?{status:t,inputDisabled:n}:{status:t}}setRole(e){this._role!==e&&(this._role=e,this._notifySubscribers())}setRunConfig(e){this._runConfig!==e&&(this._runConfig=e,this._notifySubscribers())}_isSending=!1;_removedDuringSend=new Set;_sendGeneration=0;_attachmentAddOperations=new bH;_cancelAttachmentAdd(e){this._attachmentAddOperations.cancel(e)}_cancelAllAttachmentAdds(){this._attachmentAddOperations.cancelAll()}_emptyTextAndAttachments(){this._attachments=[],this._text=``,this._rebaseDictation(``),this._notifySubscribers()}async _onClearAttachments(){let e=this.getAttachmentAdapter();if(e){let t=this._attachments.filter(e=>!yH(e));await Promise.all(t.map(async t=>e.remove(t)))}}async reset(){if(this._cancelAllAttachmentAdds(),this._sendGeneration++,this._isSending=!1,this._removedDuringSend.clear(),this._attachments.length===0&&this._text===``&&this._role===`user`&&Object.keys(this._runConfig).length===0&&this._quote===void 0)return;this._role=`user`,this._runConfig={},this._quote=void 0;let e=this._onClearAttachments();this._emptyTextAndAttachments(),await e}async clearAttachments(){if(this._cancelAllAttachmentAdds(),this._isSending)for(let e of this._attachments)this._removedDuringSend.add(e.id);let e=this._onClearAttachments();this.setAttachments([]),await e}async send(e){if(!this.canSend||this._isSending)return;if(this._dictationSession)try{this._dictationSession.cancel()}catch(e){console.error(`[assistant-ui] Dictation session cancel threw`,e)}finally{this._cleanupDictation()}let t=this.getAttachmentAdapter(),n=this.attachments.map(async e=>{if(yH(e))return e;if(!t)throw Error(`Attachments are not supported`);return await t.send(e)}),r=this.attachments,i=this.text,a=this._quote,o=this.role,s=this.runConfig;this._quote=void 0,this._text=``,this._isSending=!0;let c=++this._sendGeneration;this._notifySubscribers();let l;try{l=await Promise.all(n)}catch(e){throw c===this._sendGeneration&&(!this.text.trim()&&this._quote===void 0&&(this._text=i,this._rebaseDictation(i),this._quote=a,this._notifySubscribers()),Promise.allSettled(n).then(()=>{c===this._sendGeneration&&(this._removedDuringSend.clear(),this._isSending=!1,this._notifySubscribers())})),e}if(c!==this._sendGeneration)return;let u=new Set(r.map(e=>e.id));this._attachments=this._attachments.filter(e=>!u.has(e.id)),this._isSending=!1,this._notifySubscribers();let d=l.filter(e=>!this._removedDuringSend.has(e.id));this._removedDuringSend.clear();let f={createdAt:new Date,role:o,content:i?[{type:`text`,text:i}]:[],attachments:d,runConfig:s,metadata:{custom:{...a?{quote:a}:{}}}},p={text:i,quote:a,attachments:d},m;try{m=this.handleSend(f,e)}catch(e){throw this._restoreUnsentDraft(e,c,p),e}m&&m.catch(e=>{this._restoreUnsentDraft(e,c,p)}),this._notifyEventSubscribers(`send`,{chars:i.length,attachments:d.length})}restoreDraft(e){return this._text.trim()||this._quote!==void 0||this._attachments.length>0?!1:(this._text=e.text,this._rebaseDictation(e.text),this._quote=e.quote,this._attachments=e.attachments??[],this._notifySubscribers(),!0)}retractDraft(e){let t=e.attachments===void 0?this._attachments.length===0:this._attachments===e.attachments;this._text===e.text&&this._quote===e.quote&&t&&(this._text=``,this._rebaseDictation(``),this._quote=void 0,this._attachments=[],this._notifySubscribers())}_restoreUnsentDraft(e,t,n){pV(e)&&t===this._sendGeneration&&this.restoreDraft(n)}cancel(){this.handleCancel()}get queue(){return pH}moveQueueItem(e,t){}removeQueueItem(e){}async addAttachment(e){if(vH(e)){let t=this.getAttachmentAdapter();if(t&&!hH({name:e.name,type:e.contentType??``},t.accept)){let n=`File type ${e.contentType||`unknown`} is not accepted. Accepted types: ${t.accept}`,r=Error(n);throw this._safeEmitAttachmentAddError(`not-accepted`,n,void 0,r,e.contentType),r}let n={id:e.id??mB(),type:e.type??`document`,name:e.name,contentType:e.contentType,content:e.content,status:{type:`complete`}};this._attachments=[...this._attachments,n],this._notifySubscribers(),this._notifyEventSubscribers(`attachmentAdd`,{...n.contentType?{contentType:n.contentType}:void 0});return}let t=this.getAttachmentAdapter();if(!t){let t=`Attachments are not supported`,n=Error(t);throw this._safeEmitAttachmentAddError(`no-adapter`,t,void 0,n,e.type),n}if(!hH({name:e.name,type:e.type},t.accept)){let n=`File type ${e.type||`unknown`} is not accepted. Accepted types: ${t.accept}`,r=Error(n);throw this._safeEmitAttachmentAddError(`not-accepted`,n,void 0,r,e.type),r}let n=this._attachmentAddOperations.start(),r=e=>{if(!this._attachmentAddOperations.accept(n,e.id))return!1;let t=this._attachments.findIndex(t=>t.id===e.id);return this._attachments=t===-1?[...this._attachments,e]:[...this._attachments.slice(0,t),e,...this._attachments.slice(t+1)],this._notifySubscribers(),!0},i;try{await xH(t.add({file:e}),e=>(i=e,r(e)))}catch(t){if(this._attachmentAddOperations.isCancelled(n))return;throw i&&r({...i,status:{type:`incomplete`,reason:`error`,message:t instanceof Error?t.message:String(t)}}),this._safeEmitAttachmentAddError(`adapter-error`,t instanceof Error?t.message:String(t),i?.id,t instanceof Error?t:void 0,i?.contentType||e.type),t}finally{this._attachmentAddOperations.finish(n)}this._attachmentAddOperations.isCancelled(n)||(i?.status.type===`incomplete`&&i.status.reason===`error`?this._safeEmitAttachmentAddError(`adapter-error`,i.status.message??`Attachment upload did not complete successfully.`,i.id,void 0,i.contentType||e.type):this._notifyEventSubscribers(`attachmentAdd`,{...i?.contentType?{contentType:i.contentType}:e.type?{contentType:e.type}:void 0}))}_safeEmitAttachmentAddError(e,t,n,r,i){try{this._notifyEventSubscribers(`attachmentAddError`,{reason:e,message:t,...n!==void 0&&{attachmentId:n},...r!==void 0&&{error:r},...i?{contentType:i}:void 0})}catch(e){console.error(`[assistant-ui] attachmentAddError subscriber threw:`,e)}}async removeAttachment(e){let t=this._attachments.findIndex(t=>t.id===e);if(t===-1)throw Error(`Attachment not found`);let n=this._attachments[t];if(this._cancelAttachmentAdd(e),this._isSending&&this._removedDuringSend.add(e),!yH(n)){let t=this.getAttachmentAdapter();if(!t)throw Error(`Attachments are not supported`);try{await t.remove(n)}catch(t){let n=t instanceof Error?t.message:String(t);throw this._attachments=this._attachments.map(t=>t.id===e&&!yH(t)?{...t,status:{type:`incomplete`,reason:`error`,message:n}}:t),this._notifySubscribers(),t}}this._attachments=this._attachments.filter(t=>t.id!==e),this._notifySubscribers()}_dictation;_dictationSession;_dictationUnsubscribes=[];_dictationBaseText=``;_currentInterimText=``;_dictationSessionIdCounter=0;_activeDictationSessionId;_isCleaningDictation=!1;get dictation(){return this._dictation}_isActiveSession(e,t){return this._activeDictationSessionId===e&&this._dictationSession===t}startDictation(){let e=this.getDictationAdapter();if(!e)throw Error(`Dictation adapter not configured`);let t=this._dictationSession!==void 0;if(this._dictationSession){let e=this._dictationSession;this._cleanupDictation({notify:!1}),this._stopDictationSession(e)}let n=e.disableInputDuringDictation??!1;this._dictationBaseText=this._text,this._currentInterimText=``;let r;try{r=e.listen()}catch(e){if(t)try{this._notifySubscribers()}catch(e){console.error(`[assistant-ui] Dictation replacement rollback notification threw`,e)}throw e}this._dictationSession=r;let i=++this._dictationSessionIdCounter;this._activeDictationSessionId=i,this._dictation={status:r.status,inputDisabled:n},this._notifySubscribers();let a=r.onSpeech(e=>{if(!this._isActiveSession(i,r))return;let t=e.isFinal!==!1,n=this._dictationBaseText&&!this._dictationBaseText.endsWith(` `)&&e.transcript?` `:``;if(t){if(this._dictationBaseText=this._dictationBaseText+n+e.transcript,this._currentInterimText=``,this._text=this._dictationBaseText,this._dictation){let{transcript:e,...t}=this._dictation;this._dictation=t}this._notifySubscribers()}else this._currentInterimText=n+e.transcript,this._text=this._dictationBaseText+this._currentInterimText,this._dictation&&={...this._dictation,transcript:e.transcript},this._notifySubscribers()});this._dictationUnsubscribes.push(a);let o=r.onSpeechStart(()=>{this._isActiveSession(i,r)&&(this._dictation={status:{type:`running`},inputDisabled:n,...this._dictation?.transcript&&{transcript:this._dictation.transcript}},this._notifySubscribers())});this._dictationUnsubscribes.push(o);let s=r.onSpeechEnd(()=>{this._cleanupDictation({sessionId:i})});this._dictationUnsubscribes.push(s);let c=setInterval(()=>{this._isActiveSession(i,r)&&r.status.type===`ended`&&this._cleanupDictation({sessionId:i})},100);this._dictationUnsubscribes.push(()=>clearInterval(c))}stopDictation(){if(!this._dictationSession)return;let e=this._dictationSession,t=this._activeDictationSessionId;this._stopDictationSession(e,()=>this._cleanupDictation({sessionId:t}))}_stopDictationSession(e,t=()=>{}){let n;try{n=e.stop()}catch(e){console.error(`[assistant-ui] Dictation session stop threw`,e),t();return}n.then(t,e=>{console.error(`[assistant-ui] Dictation session stop rejected`,e),t()})}_cleanupDictation(e){if(e?.sessionId!==void 0&&e.sessionId!==this._activeDictationSessionId||this._isCleaningDictation)return;this._isCleaningDictation=!0;let t=e=>{try{e()}catch(e){console.error(`[assistant-ui] Dictation cleanup threw`,e)}};try{let n=this._dictationUnsubscribes;this._dictationUnsubscribes=[],this._dictationSession=void 0,this._activeDictationSessionId=void 0,this._dictation=void 0,this._dictationBaseText=``,this._currentInterimText=``;for(let e of n)t(e);e?.notify!==!1&&t(()=>this._notifySubscribers())}finally{this._isCleaningDictation=!1}}_eventSubscribers=new Map;_notifyEventSubscribers(e,t){let n=this._eventSubscribers.get(e);n&&jP(n,t,`Composer runtime "${e}"`)}unstable_on(e,t){let n=t,r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),()=>{this._eventSubscribers.get(e)?.delete(n)}}},CH=e=>e.capabilities?.cancel?RV(e):!1,wH=class extends SH{get canCancel(){return CH(this.runtime)}get canSend(){return!this.isEmpty&&!this.runtime.isSendDisabled&&!this.runtime.voice&&!this._isSending}_queueCache;get queue(){let e=this.runtime.getSteerQueueItems?.()??pH,t=this.runtime.getQueueItems?.()??pH,n=this._queueCache;if(n&&n.steer===e&&n.queue===t)return n.flat;let r=e.length===0?t:t.length===0?e:[...e,...t];return this._queueCache={steer:e,queue:t,flat:r},r}moveQueueItem(e,t){this.runtime.moveQueueItem?.(e,t)}removeQueueItem(e){this.runtime.removeQueueItem?.(e)}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}runtime;constructor(e){super(),this.runtime=e,this.connect()}connect(){let e=!1,t=this.runtime.isSendDisabled,n=this.runtime.voice!==void 0,r=this.queue;return this.runtime.subscribe(()=>{let i=!1,a=this.canCancel;e!==a&&(e=a,i=!0),t!==this.runtime.isSendDisabled&&(t=this.runtime.isSendDisabled,i=!0);let o=this.runtime.voice!==void 0;n!==o&&(n=o,i=!0),r!==this.queue&&(r=this.queue,i=!0),i&&this._notifySubscribers()})}async handleSend(e,t){return this.runtime.append({...e,parentId:this.runtime.messages.at(-1)?.id??null,sourceId:null,startRun:t?.startRun,steer:t?.steer})}async handleCancel(){this.runtime.cancelRun()}},TH=class extends SH{get canCancel(){return!0}get canSend(){return!this.isEmpty&&!this.runtime.voice&&!this._isSending}getAttachmentAdapter(){return this.runtime.adapters?.attachments}getDictationAdapter(){return this.runtime.adapters?.dictation}_nonTextPassthrough;_parentId;_sourceId;runtime;endEditCallback;constructor(e,t,{parentId:n,message:r}){super(),this.runtime=e;let i=e.voice!==void 0,a=e.subscribe(()=>{let t=e.voice!==void 0;t!==i&&(i=t,this._notifySubscribers())});this.endEditCallback=()=>{a(),t()},this._parentId=n,this._sourceId=r.id,this.setText(EV(r)),this.setRole(r.role);let o;r.role===`user`?(o=[...r.attachments??[],..._H(r.content)],this._nonTextPassthrough=[]):(o=r.attachments??[],this._nonTextPassthrough=r.content.filter(e=>e.type!==`text`)),this.setAttachments(o),this.setRunConfig({...e.composer.runConfig})}get parentId(){return this._parentId}get sourceId(){return this._sourceId}async handleSend(e,t){let n=this._nonTextPassthrough.length>0?[...e.content,...this._nonTextPassthrough]:e.content,r=this.runtime.append({...e,content:n,parentId:this._parentId,sourceId:this._sourceId,startRun:t?.startRun});return this.handleCancel(),r}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},EH=class extends TI{_isInitialized=!1;repository=new fH;_voiceMessages=[];_voiceGeneration=0;_cachedMergedMessages=null;_cachedVoiceGeneration=-1;_cachedMergedBase=null;_markVoiceMessagesDirty(){this._voiceGeneration++,this._cachedMergedMessages=null}_getBaseMessages(){return this.repository.getMessages()}_commitVoiceMessage(e){}get messages(){if(this._voiceMessages.length===0)return this._getBaseMessages();let e=this._getBaseMessages();if(this._cachedVoiceGeneration!==this._voiceGeneration||this._cachedMergedBase!==e){let t=new Set(e.map(e=>e.id));this._cachedMergedMessages=[...e,...this._voiceMessages.filter(e=>!t.has(e.id))],this._cachedVoiceGeneration=this._voiceGeneration,this._cachedMergedBase=e}return this._cachedMergedMessages}get state(){let e;for(let t of this.messages)t.role===`assistant`&&(e=t);return e?.metadata.unstable_state??null}composer=new wH(this);_contextProvider;constructor(e){super(),this._contextProvider=e}getModelContext(){return this._contextProvider.getModelContext()}enrichAppendMetadata(e,t=e.parentId){if(e.role!==`user`)return e;let n=this.messages,r=t===null?-1:n.findIndex(e=>e.id===t),i=tB(this.getModelContext().unstable_composerMetadata,n.slice(0,r+1));return i?{...e,metadata:{...e.metadata,custom:{...e.metadata?.custom,...i}}}:e}_editComposers=new Map;getEditComposer(e){return this._editComposers.get(e)}_isVoiceMessage(e){return e!==null&&this._voiceMessages.some(t=>t.id===e)}_resolveAppendParent(e){return this._isVoiceMessage(e)?this._getBaseMessages().at(-1)?.id??null:e}beginEdit(e){if(this.voice)throw Error(`Cannot edit a message while a voice session is connected`);if(this._isVoiceMessage(e))throw Error(`Voice transcript messages cannot be edited`);if(this._editComposers.has(e))throw Error(`Edit already in progress`);this._editComposers.set(e,new TH(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch{let t=this.repository.getMessages(),n=this._voiceMessages.findIndex(t=>t.id===e);return n===-1?void 0:{parentId:n>0?this._voiceMessages[n-1].id:t.at(-1)?.id??null,message:this._voiceMessages[n],index:t.length+n}}}getBranches(e){return this._voiceMessages.some(t=>t.id===e)?[]:this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifyEventSubscribers(e,t){let n=this._eventSubscribers.get(e);n&&jP(n,t,`Thread runtime "${e}"`)}_notifyToolApprovalAnswered(e,t,n,r){this._notifyEventSubscribers(`toolApprovalAnswered`,{messageId:e,toolCallId:t,toolName:n,approved:r})}submitFeedback({messageId:e,type:t,comment:n}){let r=this.adapters?.feedback,i=this.getMessageById(e);if(!i)throw Error(`Message not found: ${e}`);let{message:a,parentId:o}=i,s=n?.trim(),c={type:t,...s?{comment:s}:void 0};if(r?.submit({message:a,...c}),a.role===`assistant`){let t={...a,metadata:{...a.metadata,submittedFeedback:c}},n=this._voiceMessages.findIndex(t=>t.id===e);n===-1?this.repository.addOrUpdateMessage(o,t):(this._voiceMessages[n]=t,this._currentAssistantMsg===a&&(this._currentAssistantMsg=t),this._markVoiceMessagesDirty())}this._notifySubscribers()}_stopSpeaking;speech;speak(e){let t=this.adapters?.speech;if(!t)throw Error(`Speech adapter not configured`);let n=this.getMessageById(e);if(!n)throw Error(`Message not found: ${e}`);let{message:r}=n,i=this._stopSpeaking,a;try{i?.(),a=t.speak(EV(r))}catch(e){if(i&&!this._stopSpeaking)try{this._notifySubscribers()}catch(e){console.error(`[assistant-ui] Speech rollback notification threw`,e)}throw e}let o,s=()=>{this._stopSpeaking=void 0,this.speech=void 0;let e=o;o=void 0,e?.()},c=()=>{if(this._stopSpeaking===c)try{s()}finally{a.cancel()}},l=()=>{this._stopSpeaking===c&&(a.status.type===`ended`?SI([s,()=>this._notifySubscribers()]):(this.speech={messageId:e,status:a.status},this._notifySubscribers()))};this._stopSpeaking=c;try{if(o=a.subscribe(l),this._stopSpeaking!==c){o();return}l()}catch(e){if(this._stopSpeaking===c)try{SI([c,()=>this._notifySubscribers()])}catch(e){console.error(`[assistant-ui] Speech rollback cleanup threw`,e)}throw e}}stopSpeaking(){if(!this._stopSpeaking)throw Error(`No message is being spoken`);SI([this._stopSpeaking,()=>this._notifySubscribers()])}_voiceSession;_voiceUnsubs=[];voice;_voiceVolume=0;_voiceVolumeSubscribers=new Set;getVoiceVolume=()=>this._voiceVolume;subscribeVoiceVolume=e=>(this._voiceVolumeSubscribers.add(e),()=>this._voiceVolumeSubscribers.delete(e));_onVoiceConnected(){}_onVoiceDisconnected(){}_isRunActive(){if(this.isRunning)return!0;let e=this._getBaseMessages().at(-1);return e?.role===`assistant`&&(e.status.type===`running`||e.status.type===`requires-action`)}connectVoice(){let e=this.adapters?.voice;if(!e)throw Error(`Voice adapter not configured`);if(this._isRunActive())throw Error(`Cannot start a voice session while a run is in progress or paused on a pending tool action`);let t=this._voiceSession!==void 0;try{this._disconnectVoice(!1)}catch(e){console.error(`[assistant-ui] Voice cleanup threw before reconnect`,e)}let n;try{n=e.connect({})}catch(e){throw t&&this._voiceSession===void 0&&this._onVoiceDisconnected(),e}this._voiceSession=n;let r=[];this._voiceUnsubs=r;let i=()=>{if(this._voiceSession===n&&this._voiceUnsubs===r)return!1;try{SI(r.splice(0))}catch(e){console.error(`[assistant-ui] Detached voice setup cleanup threw`,e)}return!0};try{let e=`listening`;if(this.voice={status:n.status,isMuted:n.isMuted,mode:e},this._voiceVolume=0,this._notifySubscribers(),i()||(r.push(n.onStatusChange(t=>{this._voiceSession===n&&(t.type===`ended`?(this._finishVoiceAssistantMessage(),this._voiceSession=void 0,this.voice=void 0,this._onVoiceDisconnected()):this.voice={status:t,isMuted:n.isMuted,mode:e},this._notifySubscribers())})),i())||(r.push(n.onModeChange(t=>{e=t,this.voice&&(this.voice={...this.voice,mode:t},this._notifySubscribers())})),i())||(r.push(n.onVolumeChange(e=>{this._voiceVolume=e,jP(this._voiceVolumeSubscribers,void 0,`Voice volume`)})),i()))return;r.push(n.onTranscript(e=>{this._handleVoiceTranscript(e)})),i()||this._onVoiceConnected()}catch(e){if(this._voiceSession===n&&this._voiceUnsubs===r){try{this._disconnectVoice(!1)}catch(e){console.error(`[assistant-ui] Voice rollback cleanup threw`,e)}t&&this._voiceSession===void 0&&this._onVoiceDisconnected()}else i();throw e}}_currentAssistantMsg=null;_handleVoiceTranscript(e){if(this.ensureInitialized(),e.role===`user`){if(this._finishVoiceAssistantMessage(),this._currentAssistantMsg=null,e.isFinal){let t={id:mB(),role:`user`,content:[{type:`text`,text:e.text}],metadata:{modality:`voice`,custom:{}},createdAt:new Date,status:{type:`complete`,reason:`unknown`},attachments:[]};this._voiceMessages.push(t),this._commitVoiceMessage(t),this._markVoiceMessagesDirty(),this._notifySubscribers()}}else{let t=e.isFinal?{type:`complete`,reason:`stop`}:{type:`running`};if(!this._currentAssistantMsg)this._currentAssistantMsg={id:mB(),role:`assistant`,content:[{type:`text`,text:e.text}],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],modality:`voice`,custom:{}},status:t,createdAt:new Date},this._voiceMessages.push(this._currentAssistantMsg);else{let n=this._voiceMessages.indexOf(this._currentAssistantMsg);if(n===-1)return;let r={...this._currentAssistantMsg,content:[{type:`text`,text:e.text}],status:t};this._voiceMessages[n]=r,this._currentAssistantMsg=r}e.isFinal&&(this._commitVoiceMessage(this._currentAssistantMsg),this._currentAssistantMsg=null),this._markVoiceMessagesDirty(),this._notifySubscribers()}}_finishVoiceAssistantMessage(e=!0){let t=this._voiceMessages.at(-1);if(t?.role===`assistant`&&t.status.type===`running`){let n=this._voiceMessages.length-1;this._voiceMessages[n]={...t,status:{type:`complete`,reason:`stop`}},this._commitVoiceMessage(this._voiceMessages[n]),this._currentAssistantMsg=null,this._markVoiceMessagesDirty(),e&&this._notifySubscribers()}}disconnectVoice(){this._disconnectVoice(!0)}_disconnectVoice(e){this._finishVoiceAssistantMessage(!1),this._currentAssistantMsg=null;let t=this._voiceUnsubs.splice(0);this._voiceUnsubs=[];let n=this._voiceSession;this._voiceSession=void 0,this.voice=void 0,this._voiceVolume=0;let r=this.speech&&this._isVoiceMessage(this.speech.messageId)?this._stopSpeaking:void 0;this._voiceMessages=[],this._markVoiceMessagesDirty();try{SI([...t,...r?[r]:[],...n?[()=>n.disconnect()]:[],()=>jP(this._voiceVolumeSubscribers,void 0,`Voice volume`),()=>this._notifySubscribers()])}finally{e&&n&&this._voiceSession===void 0&&this._onVoiceDisconnected()}}muteVoice(){if(!this._voiceSession)throw Error(`No active voice session`);this._voiceSession.mute(),this.voice={...this.voice,isMuted:!0},this._notifySubscribers()}unmuteVoice(){if(!this._voiceSession)throw Error(`No active voice session`);this._voiceSession.unmute(),this.voice={...this.voice,isMuted:!1},this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers(`initialize`,{}))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(lH.fromArray(e??[]))}_eventSubscribers=new Map;unstable_on(e,t){let n=t;if(e===`modelContextUpdate`)return this._contextProvider.subscribe?.(()=>jP([n],{},`Thread runtime "${e}"`))??(()=>{});let r=this._eventSubscribers.get(e);return r||(r=new Set,this._eventSubscribers.set(e,r)),r.add(n),e===`initialize`&&this._isInitialized&&queueMicrotask(()=>{r.has(n)&&jP([n],{},`Thread runtime "${e}"`)}),()=>{this._eventSubscribers.get(e)?.delete(n)}}},DH=Symbol.for(`assistant-stream.tool-execution-id`),OH=e=>{try{return JSON.parse(e),!0}catch{return!1}},kH=e=>{try{return JSON.parse(e)}catch{return}},AH=(e,t)=>{let n=kH(e),r=kH(t);return n===void 0||r===void 0?!1:$L(n,r)},jH=e=>e[DH],MH=class{_getTools;_callbacks;_isClientToolCall;_entries=new Map;_humanInput=new Map;_executing=new Set;_discardedToolCallIds=new Set;_settledResolvers=[];_statuses=new Map;_ac=new AbortController;_pendingRestore=!0;_lastSnapshot=null;_isRunning=!1;_controller;_pipelineDead=!1;_pipelineRestartUsed=!1;constructor(e,t,n){this._getTools=e,this._callbacks=t,this._isClientToolCall=n,this._initPipeline()}_initPipeline(){let[e,t]=wR();this._controller=t;let n=Nz(()=>this._getWrappedTools(),()=>this._ac.signal,(e,t,n)=>this._onHumanInput(e,t,n),{onExecutionStart:(e,t,n)=>this._onExecutionStart(e,n),onExecutionEnd:(e,t,n)=>this._onExecutionEnd(e,n)});e.pipeThrough(n).pipeThrough(new DR).pipeTo(new WritableStream({write:e=>{try{if(e.type!==`result`)return;this._handleResultChunk(e)}catch(e){console.error(`[ToolInvocationTracker] result chunk handling failed`,e)}}})).catch(e=>{console.error(`[ToolInvocationTracker] stream pipeline failed; will attempt single restart on next setState`,e),this._pipelineDead=!0})}setState(e){try{if(this._pipelineDead){if(this._pipelineRestartUsed)return;this._pipelineRestartUsed=!0,this._pipelineDead=!1,this._demoteEntriesToRestored(),this._executing.clear(),this._ac=new AbortController,this._initPipeline()}if(this._lastSnapshot&&this._lastSnapshot.messages===e.messages&&this._lastSnapshot.isRunning===e.isRunning&&this._lastSnapshot.isLoading===e.isLoading)return;e.isLoading===!0&&(this._pendingRestore=!0);let t=this._isRunning;this._isRunning=e.isRunning;try{this._processMessages(e.messages)}catch(e){throw this._isRunning=t,e}this._lastSnapshot=e,this._pendingRestore=!1}catch(e){console.error(`[ToolInvocationTracker] setState failed; snapshot dropped`,e)}}reset(){try{this._pendingRestore=!0,this._entries.clear(),this._discardedToolCallIds.clear(),this._lastSnapshot=null,this.abort(),this._statuses.size>0&&(this._statuses=new Map,this._invokeOnStatusesChange())}catch(e){console.error(`[ToolInvocationTracker] reset failed`,e)}}abort(e){try{if(this._humanInput.forEach(({reject:e})=>{try{e(Error(`Tool execution aborted`))}catch{}}),this._humanInput.clear(),e?.discardPending)for(let[e,t]of this._entries)t.controller&&(t.argsComplete||t.hasResult||(this._discardedToolCallIds.add(e),t.skipExecute=!0));if(this._ac.abort(),this._ac=new AbortController,this._executing.size===0)return Promise.resolve();let t=new Set(this._executing);return new Promise(e=>{this._settledResolvers.push({executionIds:t,resolve:e})})}catch(e){return console.error(`[ToolInvocationTracker] abort failed`,e),Promise.resolve()}}resume(e,t){try{let n=this._humanInput.get(e);return n?(this._humanInput.delete(e),this._setStatus(e,{type:`executing`}),n.resolve(t),!0):!1}catch(e){return console.error(`[ToolInvocationTracker] resume failed`,e),!1}}getStatuses(){return this._statuses}_getWrappedTools(){let e=this._getTools();if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=t.execute,r=t.streamCall;return n===void 0&&r===void 0?[e,t]:[e,{...t,...n!==void 0&&{execute:(...[e,t])=>{let r=jH(t),i=this._captureExecution(t.toolCallId,r);return!i||i.skipExecute?new Promise(()=>{}):n(e,t)}},...r!==void 0&&{streamCall:(...[e,t])=>{let n=jH(t);if(this._captureExecution(t.toolCallId,n))return r(e,t)}}}]}))}_captureExecution(e,t){if(t===void 0)return;let n=this._entries.get(e);if(n?.controller)return n.executionId===void 0&&(n.executionId=t),n.executionId===t?n:void 0}_onHumanInput(e,t,n){return new Promise((r,i)=>{let a=this._entries.get(e);if(!a?.controller||a.executionId!==n){i(Error(`Tool execution aborted`));return}let o=this._humanInput.get(e);if(o)try{o.reject(Error(`Human input request was superseded by a new request`))}catch{}this._humanInput.set(e,{executionId:n,resolve:r,reject:i}),this._setStatus(e,{type:`interrupt`,payload:{type:`human`,payload:t}})})}_onExecutionStart(e,t){this._captureExecution(e,t)&&(this._entries.get(e).skipExecute||(this._executing.add(t),this._humanInput.get(e)?.executionId!==t&&this._setStatus(e,{type:`executing`})))}_onExecutionEnd(e,t){if(t===void 0||!this._executing.delete(t))return;this._entries.get(e)?.executionId===t&&this._deleteStatus(e);let n=[];this._settledResolvers.forEach(({executionIds:e,resolve:t})=>{if([...e].some(e=>this._executing.has(e))){n.push({executionIds:e,resolve:t});return}try{t()}catch{}}),this._settledResolvers.length=0,this._settledResolvers.push(...n)}_handleResultChunk(e){let t=e.meta.toolCallId,n=jH(e),r=this._entries.get(t);r&&r.executionId===n&&(r?.hasResult||r.skipExecute||this._invokeOnResult({type:`add-tool-result`,toolCallId:t,toolName:e.meta.toolName,result:e.result,isError:e.isError,...e.artifact!==void 0&&{artifact:e.artifact},...e.modelContent!==void 0&&{modelContent:e.modelContent}}))}_invokeOnResult(e){try{this._callbacks.onResult(e)}catch(e){console.error(`[ToolInvocationTracker] onResult callback threw; result dropped`,e)}}_invokeOnStatusesChange(){try{this._callbacks.onStatusesChange(this._statuses)}catch(e){console.error(`[ToolInvocationTracker] onStatusesChange callback threw; status change not propagated`,e)}}_setStatus(e,t){let n=new Map(this._statuses);n.set(e,t),this._statuses=n,this._invokeOnStatusesChange()}_deleteStatus(e){if(!this._statuses.has(e))return;let t=new Map(this._statuses);t.delete(e),this._statuses=t,this._invokeOnStatusesChange()}_warnProviderOwnedSkip(e,t){}_shouldCloseArgsStream({argsText:e,hasResult:t,clientOwned:n}){return t?!0:OH(e)?n||!this._isRunning:!1}_startActiveEntry(e,t,n,r){let i={toolName:t,controller:this._controller.addToolCallPart({toolName:t,toolCallId:e}),argsText:``,hasResult:!1,skipExecute:n,argsComplete:!1,clientOwned:r};return this._entries.set(e,i),i}_demoteEntriesToRestored(){for(let[e,t]of this._entries)if(t.controller){if(!t.argsComplete&&!t.hasResult){this._entries.delete(e);continue}this._entries.set(e,{toolName:t.toolName,argsText:t.argsText,hasResult:t.hasResult})}}_processArgsText(e,t){if(!e.controller)return;let n=t.result!==void 0;if(t.argsText!==e.argsText){let r=!0;if(e.argsComplete)AH(e.argsText,t.argsText)&&(e.argsText=t.argsText),r=!1;else if(!t.argsText.startsWith(e.argsText)){if(OH(e.argsText)&&OH(t.argsText)&&AH(e.argsText,t.argsText)){let i=this._shouldCloseArgsStream({argsText:t.argsText,hasResult:n,clientOwned:e.clientOwned});i&&e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=i,r=!1}else r=!1}if(r&&e.controller){let r=t.argsText.slice(e.argsText.length);e.controller.argsText.append(r);let i=this._shouldCloseArgsStream({argsText:t.argsText,hasResult:n,clientOwned:e.clientOwned});i&&e.controller.argsText.close(),e.argsText=t.argsText,e.argsComplete=i}}!e.argsComplete&&e.controller&&this._shouldCloseArgsStream({argsText:e.argsText,hasResult:n,clientOwned:e.clientOwned})&&(e.controller.argsText.close(),e.argsComplete=!0)}_processMessages(e){let t=this._pendingRestore;for(let{part:n}of mH(e)){let e=this._entries.get(n.toolCallId);if(t){e?.controller||this._entries.set(n.toolCallId,{toolName:n.toolName,argsText:n.argsText,hasResult:n.result!==void 0});continue}let r=e;if(n.result!==void 0&&this._discardedToolCallIds.delete(n.toolCallId),r&&!r.controller){if(r.hasResult||(n.argsText===r.argsText||OH(r.argsText)&&OH(n.argsText)&&AH(r.argsText,n.argsText))&&n.result===void 0)continue;this._entries.delete(n.toolCallId),r=void 0}if(!r){let e=this._isClientToolCall?.(n),t=n.result===void 0&&e===!1;t&&this._warnProviderOwnedSkip(n.toolName,n.toolCallId),r=this._startActiveEntry(n.toolCallId,n.toolName,n.result!==void 0||t||this._discardedToolCallIds.has(n.toolCallId),e===!0)}if(n.approval!==void 0&&(r.skipExecute=!0),this._processArgsText(r,n),n.result!==void 0&&!r.hasResult){let{controller:e}=r;if(!e)continue;r.hasResult=!0,r.argsComplete=!0,e.setResponse(new iR({result:n.result,artifact:n.artifact,isError:n.isError,...n.modelContent===void 0?{}:{modelContent:n.modelContent}})),e.close()}}}},NH=Object.freeze([]),PH=(e,t)=>{Promise.resolve(t).catch(t=>{console.error(`[ExternalStoreThreadRuntimeCore] ${e} callback rejected`,t)})},FH=(e,t)=>e&&t[t.length-1]?.role!==`assistant`,IH=class extends EH{_capabilities={switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,delete:!1,reload:!1,refetchThread:!1,cancel:!1,unstable_copy:!1,speech:!1,dictation:!1,voice:!1,attachments:!1,feedback:!1,queue:!1};get capabilities(){return this._capabilities}_messages;isDisabled;isSendDisabled;get isLoading(){return this._store.isLoading??!1}get isRunning(){return this._hasExecutingTools(this._store)?!0:this._store.isRunning}_getBaseMessages(){return this._messages}get state(){return this._store.state??super.state}get adapters(){return this._store.adapters}get unstable_refetchThread(){if(this._store.onRefetchThread)return()=>this._store.onRefetchThread()}suggestions=[];extras=void 0;_converter=new jB;_pendingDeleteEvictions=new Set;_optimistic=null;_store;_getInitializePromise;__internal_setGetInitializePromise(e){this._getInitializePromise=e}_transformedQueue;_toolInvocations=null;_toolStatuses=new Map;_effectiveIsRunning=!1;_inTrackerUpdate=!1;_pendingRunningRefresh=!1;_runTrackerUpdate(e){this._inTrackerUpdate=!0;try{e()}finally{this._inTrackerUpdate=!1}this._pendingRunningRefresh&&(this._pendingRunningRefresh=!1,this._refreshEffectiveIsRunning())}_refreshEffectiveIsRunning(){let e=this._getEffectiveIsRunning(this._store);this._effectiveIsRunning!==e&&(this._effectiveIsRunning=e,this._notifyEventSubscribers(e?`runStart`:`runEnd`,{}),this._notifySubscribers())}_hasExecutingTools(e){if(e.unstable_enableToolInvocations!==!0||this._toolInvocations===null)return!1;for(let e of this._toolStatuses.values())if(e.type===`executing`)return!0;return!1}_getEffectiveIsRunning(e){return(e.isRunning??!1)||this._hasExecutingTools(e)}beginEdit(e){if(!this._store.onEdit)throw Error(`Runtime does not support editing.`);super.beginEdit(e)}constructor(e,t){super(e),this.__internal_setAdapter(t)}__internal_setAdapter(e){this._store!==e&&this._updateStoreSnapshot(e)}_updateStoreSnapshot(e){let t=this._effectiveIsRunning;this.isDisabled=e.isDisabled??!1,this.isSendDisabled=e.isSendDisabled??!1;let n=this._store;this._store=e;let r=this._getEffectiveIsRunning(e),i=e.unstable_messageRepositoryInstance,a=i!==void 0&&i!==this.repository;a&&(this.repository=i,this._pendingDeleteEvictions.clear()),n?.queue!==e.queue&&(this._transformedQueue=void 0,e.queue?.__internal_setDispatchTransform?.(e=>{let t=this.messages.at(-1)?.id??null;return this.enrichAppendMetadata({...e,parentId:t},t)}),e.queue?.__internal_setDispatchTransform&&(this._transformedQueue=e.queue)),this.extras!==e.extras&&(this.extras=e.extras);let o=e.suggestions??NH;LF(this.suggestions,o)||(this.suggestions=o);let s={switchToBranch:this._store.setMessages!==void 0,switchBranchDuringRun:!1,edit:this._store.onEdit!==void 0,delete:this._store.onDelete!==void 0||this._store.setMessages!==void 0,reload:this._store.onReload!==void 0,refetchThread:this._store.onRefetchThread!==void 0,cancel:this._store.onCancel!==void 0,speech:this._store.adapters?.speech!==void 0,dictation:this._store.adapters?.dictation!==void 0,voice:this._store.adapters?.voice!==void 0,unstable_copy:this._store.unstable_capabilities?.copy!==!1,attachments:!!this._store.adapters?.attachments,feedback:!!this._store.adapters?.feedback,queue:this._store.queue!==void 0};LF(this._capabilities,s)||(this._capabilities=s);let c;if(e.messageRepository){if(n&&!a&&n.isRunning===e.isRunning&&n.messageRepository===e.messageRepository&&t===r){this._notifySubscribers();return}let i=e.messageRepository.messages,o=e.messageRepository.headId??i.at(-1)?.message.id??null;if(n&&!a&&n.messageRepository===e.messageRepository)this.repository.resetHead(o),c=this.repository.getMessages();else{let e=new Set(i.map(({message:e})=>e.id));for(let{message:e,parentId:t}of i)this.repository.addOrUpdateMessage(t,e);for(let{message:t}of this.repository.export().messages)e.has(t.id)||this.repository.deleteMessage(t.id);this._pendingDeleteEvictions.clear(),this.repository.resetHead(o),c=this.repository.getMessages()}}else if(e.messages){if(n){if(n.convertMessage!==e.convertMessage)this._converter=new jB;else if(!a&&n.isRunning===e.isRunning&&n.messages===e.messages&&t===r){this._notifySubscribers();return}}c=e.convertMessage?this._converter.convertMessages(e.messages,(t,n,i)=>{if(!e.convertMessage)return n;let a=i===(e.messages?.length??0)-1,o=`${pB}${i}`;if(t&&(t.role!==`assistant`||!DB(t.status)||t.status===AB(t.content,a,r))){if(t.id.startsWith(`__external_store_fallback_`)&&t.id!==o){let e={...t,id:o};return dB(e,n),e}return t}let s=e.convertMessage(n,i),c=_B(s,o,AB(s.content,a,r));return dB(c,n),c}):e.messages;let i=new Set,o=[];for(let e=c.length-1;e>=0;e--){let t=c[e];if(i.has(t.id)){console.warn(`ExternalStoreThreadRuntimeCore: duplicate message id "${t.id}" in the provided messages array; keeping the last occurrence.`);continue}i.add(t.id),o.push(t)}o.length!==c.length&&(c=o.reverse());for(let e=0;e<c.length;e++){let t=c[e],n=c[e-1];this.repository.addOrUpdateMessage(n?.id??null,t)}if(this._pendingDeleteEvictions.size>0){let e=new Set(c.map(e=>e.id));for(let t of this._pendingDeleteEvictions)if(this._pendingDeleteEvictions.delete(t),!e.has(t)){try{this.repository.getMessage(t)}catch{continue}this.repository.deleteMessage(t)}}}else throw Error(`ExternalStoreAdapter must provide either 'messages' or 'messageRepository'`);c.length>0&&this.ensureInitialized(),this._effectiveIsRunning=r,t!==r&&(r?this._notifyEventSubscribers(`runStart`,{}):this._notifyEventSubscribers(`runEnd`,{}));let l=null;if(FH(r,c)){let e=c.at(-1)?.id??null;this._optimistic?.parentId!==e&&(this._optimistic={id:mB(),parentId:e}),l=this._optimistic.id,this.repository.addOrUpdateMessage(e,_B({role:`assistant`,content:[],metadata:{isOptimistic:!0}},l,{type:`running`}))}l===null&&(this._optimistic=null),this.repository.resetHead(l??c.at(-1)?.id??null);let u=this.repository.getMessages();if((!this._messages||!MB(this._messages,u))&&(this._messages=u),this._voiceMessages.length>0){let e=new Set(this._messages.map(e=>e.id)),t=this._voiceMessages.filter(t=>!e.has(t.id));t.length!==this._voiceMessages.length&&(this._voiceMessages=t,this._markVoiceMessagesDirty())}a&&this._runTrackerUpdate(()=>this._toolInvocations?.reset()),this._runTrackerUpdate(()=>this._driveToolInvocations()),this._notifySubscribers()}_driveToolInvocations(){if(!this._store.unstable_enableToolInvocations){this._toolInvocations&&(this._toolInvocations.reset(),this._toolInvocations=null,this._toolStatuses=new Map,this._store.setToolStatuses?.({}));return}this._toolInvocations||=new MH(()=>this.getModelContext().tools,{onResult:e=>{try{let t=this._findMessageIdForToolCall(e.toolCallId);if(t===void 0)return;PH(`onAddToolResult`,this._store.onAddToolResult?.({messageId:t,toolCallId:e.toolCallId,toolName:e.toolName,result:e.result,isError:e.isError,...e.artifact!==void 0&&{artifact:e.artifact},...e.modelContent!==void 0&&{modelContent:e.modelContent}}))}catch(e){console.error(`[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed`,e)}},onStatusesChange:e=>{let t=this._hasExecutingTools(this._store);this._toolStatuses=e;try{this._store.setToolStatuses?.(Object.fromEntries(e))}finally{t!==this._hasExecutingTools(this._store)&&(this._inTrackerUpdate?this._pendingRunningRefresh=!0:this._updateStoreSnapshot(this._store))}}},e=>this._store.unstable_isClientToolCall?.(e)),this._toolInvocations.setState({messages:this._messages,isRunning:this._getEffectiveIsRunning(this._store),...this._store.isLoading!==void 0&&{isLoading:this._store.isLoading}})}_toolCallToMessageId=new Map;_messagesForToolCallIndex=null;_findMessageIdForToolCall(e){if(this._messagesForToolCallIndex!==this._messages){this._toolCallToMessageId.clear();for(let{part:e,messageId:t}of mH(this._messages))this._toolCallToMessageId.set(e.toolCallId,t);this._messagesForToolCallIndex=this._messages}return this._toolCallToMessageId.get(e)}switchToBranch(e){if(!this._store.setMessages)throw Error(`Runtime does not support switching branches.`);if(this._getEffectiveIsRunning(this._store))return;let t=this._store.unstable_onBranchChange,n=t?this.repository.canonicalHeadId:null;this.repository.switchToBranch(e),this._pendingDeleteEvictions.clear(),this.updateMessages(this.repository.getMessages()),t&&this._notifyBranchChange(n,t)}_notifyBranchChange(e,t){let n=this.repository.canonicalHeadId;n!==e&&t({headId:n,visibleMessageIds:this.repository.getMessages().map(e=>e.id)})}async append(e){let t={...e,parentId:this._resolveAppendParent(e.parentId)};if(this.voice)throw Error(`Cannot send a text message while a voice session is connected`);if(this._isVoiceMessage(t.sourceId))throw Error(`Voice transcript messages cannot be edited`);let n=t.sourceId!=null||t.parentId!==(this._getBaseMessages().at(-1)?.id??null);t=!n&&this._store.queue&&this._store.queue===this._transformedQueue?t:this.enrichAppendMetadata(t);let r=QV(this);this.ensureInitialized();let i=this._getInitializePromise?.();if(!n&&this._store.queue){if(i&&await i,!$V(this,r))return;t.steer??this._getEffectiveIsRunning(this._store)?this._store.queue.steer(t):this._store.queue.enqueue(t);return}if(i?.catch(()=>{}),(t.startRun??t.role===`user`)&&await this._toolInvocations?.abort({discardPending:!0}),$V(this,r)){if(n){if(!this._store.onEdit)throw Error(`Runtime does not support editing messages.`);this._pendingDeleteEvictions.clear(),await this._store.onEdit(t)}else await this._store.onNew(t)}}_commitVoiceMessage(e){this._store.onVoiceTranscript?.(e)}async deleteMessage(e){if(this._store.onDelete){this.repository.getMessages().some(t=>t.id===e)&&this._pendingDeleteEvictions.add(e);try{await this._store.onDelete(e)}catch(t){throw this._pendingDeleteEvictions.delete(e),t}return}if(!this._store.setMessages)throw Error(`Runtime does not support deleting messages.`);this._getEffectiveIsRunning(this._store)&&await this._toolInvocations?.abort();let t=this.repository.getMessages();if(t.findIndex(t=>t.id===e)===-1)throw Error(`Message not found.`);this._pendingDeleteEvictions.clear(),this.updateMessages(t.filter(t=>t.id!==e)),this._evictDeletedMessage(e)}_evictDeletedMessage(e){if(!e.startsWith(`__external_store_fallback_`)){try{this.repository.getMessage(e)}catch{return}this.repository.deleteMessage(e),this._publishRepositoryMessages()}}_publishRepositoryMessages(){let e=this.repository.getMessages();MB(this._messages,e)||(this._messages=e),this._notifySubscribers()}getQueueItems(){return this._store?.queue?.items??pH}getSteerQueueItems(){return this._store?.queue?.steerItems??pH}moveQueueItem(e,t){this._store?.queue?.move(e,t)}removeQueueItem(e){this._store?.queue?.remove(e)}async startRun(e){if(!this._store.onReload)throw Error(`Runtime does not support reloading messages.`);if(this.voice)throw Error(`Cannot start a run while a voice session is connected`);if(this._isVoiceMessage(e.sourceId))throw Error(`Voice transcript messages cannot be reloaded`);this._pendingDeleteEvictions.clear(),await this._toolInvocations?.abort({discardPending:!0}),await this._store.onReload(e.parentId,e)}async resumeRun(e){if(!this._store.onResume)throw Error(`Runtime does not support resuming runs.`);if(this.voice)throw Error(`Cannot start a run while a voice session is connected`);if(this._isVoiceMessage(e.sourceId))throw Error(`Voice transcript messages cannot be reloaded`);await this._store.onResume(e)}exportExternalState(){if(!this._store.onExportExternalState)throw Error(`Runtime does not support exporting external states.`);return this._store.onExportExternalState()}importExternalState(e){if(!this._store.onLoadExternalState)throw Error(`Runtime does not support importing external states.`);this._runTrackerUpdate(()=>this._toolInvocations?.reset()),this._store.onLoadExternalState(e)}unstable_notifySessionReset(){this._runTrackerUpdate(()=>this._toolInvocations?.reset()),this._store.queue?.__internal_notifyCancelled?.()}cancelRun(){if(!this._store.onCancel)throw Error(`Runtime does not support cancelling runs.`);let e=QV(this);this._toolInvocations?.abort({discardPending:!0}),this._store.queue?.__internal_notifyCancelled?.(),PH(`onCancel`,this._store.onCancel()),this.dropEmptyOptimisticHead();let t=this.repository.getMessages(),n=t[t.length-1],r=this._store.setMessages!==void 0&&n?.role===`user`&&n.id===t.at(-1)?.id&&n.content.every(e=>e.type===`text`)?n:void 0,i;if(r){let e={text:EV(r),attachments:r.attachments,quote:r.metadata.custom.quote};this.composer.restoreDraft(e)&&(this.repository.deleteMessage(r.id),i={id:r.id,draft:e})}this._publishRepositoryMessages(),setTimeout(()=>{if($V(this,e)){if(this.dropEmptyOptimisticHead(),i){let e=this.repository.getMessages();e.at(-1)?.id===i.id?this.repository.deleteMessage(i.id):e.some(e=>e.id===i.id)&&this.composer.retractDraft(i.draft)}this._publishRepositoryMessages(),this.updateMessages(this._messages)}},0)}dropEmptyOptimisticHead(){let e=this.repository.getMessages().at(-1);e&&e.metadata.isOptimistic&&e.content.length===0&&this.repository.deleteMessage(e.id)}addToolResult(e){if(!this._store.onAddToolResult)throw Error(`Runtime does not support tool results.`);PH(`onAddToolResult`,this._store.onAddToolResult(e))}resumeToolCall(e){if(!(this._toolInvocations?.resume(e.toolCallId,e.payload)??!1)){if(this._store.onResumeToolCall){this._store.onResumeToolCall(e);return}throw Error(`Tool call ${e.toolCallId} is not waiting for resume.`)}}respondToToolApproval(e){if(!this._store.onRespondToToolApproval)throw Error(`Runtime does not support tool approvals.`);let t=this.messages.findLast(t=>t.role===`assistant`&&t.content.some(t=>t.type===`tool-call`&&t.approval?.id===e.approvalId)),n=t?.content.find(t=>t.type===`tool-call`&&t.approval?.id===e.approvalId);try{return Promise.resolve(this._store.onRespondToToolApproval(e)).then(()=>{t&&n?.type===`tool-call`&&this._notifyToolApprovalAnswered(t.id,n.toolCallId,n.toolName,e.approved)})}catch(e){return Promise.reject(e)}}reset(e){let t=new fH;t.import(lH.fromArray(e??[])),this.updateMessages(t.getMessages())}import(e){super.import(e),this._store.onImport&&this._store.onImport(this.repository.getMessages())}updateMessages=e=>{this._store.convertMessage===void 0?this._store.setMessages?.(e):this._store.setMessages?.(e.flatMap(fB))}},LH=e=>e.adapters?.threadList??{},RH=class extends tH{threads;constructor(e){super(),this.threads=new cH(LH(e),()=>new IH(this._contextProvider,e))}setAdapter(e){this.threads.__internal_setAdapter(LH(e)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(e)}},zH=e=>{let t=J(21),{modelContext:n,feedback:r}=aB()??{},i;bb0:{if(!r||e.adapters?.feedback){i=e;break bb0}let n;t[0]!==r||t[1]!==e.adapters?(n={...e.adapters,feedback:r},t[0]=r,t[1]=e.adapters,t[2]=n):n=t[2];let a;t[3]!==e||t[4]!==n?(a={...e,adapters:n},t[3]=e,t[4]=n,t[5]=a):a=t[5],i=a}let a=i,o;t[6]===a?o=t[7]:(o=()=>new RH(a),t[6]=a,t[7]=o);let[s]=pN(o),c;t[8]===s.threads?c=t[9]:(c=()=>()=>{eH(s.threads.getMainThreadRuntimeCore())},t[8]=s.threads,t[9]=c);let l;t[10]===s?l=t[11]:(l=[s],t[10]=s,t[11]=l),X(c,l);let u;t[12]!==a||t[13]!==s?(u=()=>{s.setAdapter(a)},t[12]=a,t[13]=s,t[14]=u):u=t[14],X(u);let d,f;t[15]!==n||t[16]!==s?(d=()=>{if(n)return s.registerModelContextProvider(n)},f=[n,s],t[15]=n,t[16]=s,t[17]=d,t[18]=f):(d=t[17],f=t[18]),X(d,f);let p;return t[19]===s?p=t[20]:(p=new XV(s),t[19]=s,t[20]=p),p},BH=e=>e.status?.type!==`running`,VH=async(e,t)=>{let n=uz.fromAssistantStream(e);for await(let e of n){let n=e.parts.filter(e=>e.type===`text`)[0]?.text;n?.trim()&&await t(n)}},HH=(e,t)=>{let n=()=>void t.generateTitle({automatic:!0}).catch(e=>{JI(e)||console.error(`[assistant-ui] Thread title generation failed`,e)}),r=()=>e.getState().messages.some(BH);if(r())return n(),()=>{};let i=e.subscribe(()=>{r()&&(i(),n())});return i},UH=({threadId:e,generation:t,runtimeHook:n,publish:r,itemRuntime:i})=>{let a=n(),o=a?.thread?.__internal_threadBinding,s=gN(()=>{o&&r(e,o.getState(),t)},[e,t,o,r]),c=Y(!1);c.current||s(),X(()=>{if(o)return c.current=!0,s(),o.outerSubscribe(s)},[o,s]);let l=Y(void 0),u=Y(!1),d=Y(void 0),f=Y(!1),p=vN(()=>{if(u.current||i.getState().status!==`new`)return;u.current=!0;let e=i.initialize();l.current=e,e.then(()=>{f.current&&(d.current?.(),d.current=HH(a.thread,i))},()=>{l.current===e&&(l.current=void 0,u.current=!1)})}),m=vN(()=>(p(),l.current));return X(()=>{if(!o)return;let e=o.getState(),t=e.__internal_setGetInitializePromise;typeof t==`function`&&t.call(e,m)},[o]),X(()=>{if(!a?.threads?.main)return;u.current=!1,f.current=!0;let e=a.threads.main.unstable_on(`initialize`,p);return()=>{f.current=!1,e(),d.current?.(),d.current=void 0}},[a]),a},WH=MN(({threadId:e,generation:t,parentList:n,runtimeHook:r,parentClient:i,adapters:a,publish:o,destroySignal:s})=>{let c=hN(()=>new WV(new OI({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:`threadId`,threadId:e}},getState:()=>{let t=n.getItemById(e);return t?{id:t.id,remoteId:t.remoteId,externalId:t.externalId,title:t.title,lastMessageAt:t.lastMessageAt,custom:t.custom,status:t.status,isMain:t.id===n.mainThreadId,isRunning:n.unstable_isThreadRunning?.(t.id)??!1}:xI},subscribe:e=>n.subscribe(e)}),n),[n,e]),{client:l}=aI(i,{threadListItem:AL({runtime:c})});return DF(s,function(){return aF(l,function(){return iB(a,function(){return UH({threadId:e,generation:t,runtimeHook:r,publish:o,itemRuntime:c})})})})}),GH=[`runStart`,`runEnd`,`initialize`,`modelContextUpdate`],KH=e=>{let t=J(3),{detectorRef:n}=e,r,i;return t[0]===n?(r=t[1],i=t[2]):(r=()=>{n.current=!0},i=[n],t[0]=n,t[1]=r,t[2]=i),_N(r,i),null},qH=class extends TI{runtimeHook;adapterStore=new EI({defaultAdapters:null,threadAdapters:new Map});hostStore=new EI({threads:[],hookEpoch:0});pendingThreadAdapters=new Map;instances=new Map;nextGeneration=0;parent;constructor(e,t){super(),this.parent=t,this.runtimeHook=e}_whenRuntimeAttached(e){return new Promise((t,n)=>{let r=()=>{let r=this.instances.get(e);if(!r)i(),n(Error(`Thread was deleted before runtime was started`));else if(!r.runtime||r.publishedGeneration!==r.generation)return;else i(),t(r.runtime)},i=this.subscribe(r);r()})}startThreadRuntime(e){if(!this.instances.has(e)){let t=this.nextGeneration++;this.instances.set(e,{generation:t,isRunning:!1,destroy:new AbortController}),this._syncHostThreads()}return this._whenRuntimeAttached(e)}__internal_restartThreadRuntime(e){let t=this.instances.get(e);return t?(t.runtime&&eH(t.runtime),t.unsubscribeRunning?.(),t.unsubscribeRunning=void 0,t.destroy.abort(),t.destroy=new AbortController,t.generation=this.nextGeneration++,this._syncHostThreads(),this._notifySubscribers(),this._whenRuntimeAttached(e)):this.startThreadRuntime(e)}getThreadRuntimeCore(e){let t=this.instances.get(e);if(t)return t.runtime}__internal_isThreadRunning(e){return this.instances.get(e)?.isRunning??!1}runningSubscribers=new Set;__internal_subscribeRunningChanged(e){return this.runningSubscribers.add(e),()=>this.runningSubscribers.delete(e)}threadEventSubscribers=new Set;__internal_subscribeThreadEvents(e){return this.threadEventSubscribers.add(e),()=>this.threadEventSubscribers.delete(e)}_publish=(e,t,n)=>{this._publishThreadRuntime(e,t,n)};_publishThreadRuntime(e,t,n){let r=this.instances.get(e);if(!r||r.generation!==n)return;let i=r.runtime;r.runtime=t,r.publishedGeneration=n,i!==t&&this._trackRunning(e,r),this._notifySubscribers(),i!==void 0&&i!==t&&SI(this.replacedSubscribers)}replacedSubscribers=new Set;__internal_subscribeRuntimeReplaced(e){return this.replacedSubscribers.add(e),()=>this.replacedSubscribers.delete(e)}_trackRunning(e,t){t.unsubscribeRunning?.();let n=t.runtime;if(!n){t.unsubscribeRunning=void 0,this._setRunning(t,!1);return}this._setRunning(t,RV(n));let r=[n.subscribe(()=>{this._setRunning(t,RV(n))}),...GH.map(t=>n.unstable_on(t,()=>{jP(this.threadEventSubscribers,{threadId:e,type:t},`Thread event "${t}"`)}))];t.unsubscribeRunning=()=>{for(let e of r)e()}}_setRunning(e,t){e.isRunning!==t&&(e.isRunning=t,SI(this.runningSubscribers))}stopThreadRuntime(e){let t=this.instances.get(e);t?.runtime&&eH(t.runtime),t?.unsubscribeRunning?.(),t?.destroy.abort(),this.instances.delete(e),this.pendingThreadAdapters.delete(e),this._syncHostThreads(),this._notifySubscribers()}setRuntimeHook(e){if(this.runtimeHook===e)return;this.runtimeHook=e;let t=this.hostStore.getState();this.hostStore.setState({...t,hookEpoch:t.hookEpoch+1})}__internal_setDefaultAdapters(e){let t=this.adapterStore.getState();t.defaultAdapters!==e&&this.adapterStore.setState({...t,defaultAdapters:e})}__internal_setThreadAdapters(e,t){let n=this.adapterStore.getState(),r=new Map(n.threadAdapters);t===null?r.delete(e):r.set(e,t),this.adapterStore.setState({...n,threadAdapters:r})}__internal_dispose(){for(let e of[...this.instances.keys()])this.stopThreadRuntime(e)}_syncHostThreads(){let e=this.hostStore.getState();this.hostStore.setState({...e,threads:Array.from(this.instances.entries()).map(([e,{generation:t,destroy:n}])=>({id:e,generation:t,destroySignal:n.signal}))})}_threadElements(e,{threads:t,hookEpoch:n},r){let i=this.runtimeHook;return t.map(({id:t,generation:a,destroySignal:o})=>{let s=this.pendingThreadAdapters.has(t)?this.pendingThreadAdapters.get(t):r.threadAdapters.get(t)??r.defaultAdapters;return NN(`${t}:${a}:${n}`,WH({threadId:t,generation:a,parentList:this.parent,runtimeHook:i,parentClient:e,adapters:s,publish:this._publish,destroySignal:o}))})}__internal_useHost(e){let t=KI(this.hostStore),n=KI(this.adapterStore);return wP(this._threadElements(e,t,n))}__internal_RenderThreadRuntimes=({provider:e})=>(KI(this.hostStore),Array.from(this.instances.entries()).map(([t,{generation:n}])=>(0,b.jsx)(this._OuterActiveThreadProvider,{threadId:t,provider:e},`${t}:${n}`)));__internal_Host=({parentClient:e})=>{let t=KI(this.hostStore),n=KI(this.adapterStore),r=this._threadElements(e,t,n),{effects:i}=EP(function(){return wP(r)});return _N(i),null};_OuterActiveThreadProvider=wN(({threadId:e,provider:t})=>{let n=hN(()=>new YV(this.parent).getItemById(e),[e]),r=Y(!1);return X(()=>{},[t]),(0,b.jsx)(XB,{runtime:n,children:(0,b.jsx)(t,{children:(0,b.jsx)(this._AdapterSink,{threadId:e,detectorRef:r})})})});_AdapterSink=({threadId:e,detectorRef:t})=>{let n=aB();return this.pendingThreadAdapters.set(e,n),_N(()=>(this.__internal_setThreadAdapters(e,n),()=>{this.pendingThreadAdapters.get(e)===n&&this.pendingThreadAdapters.delete(e),this.__internal_setThreadAdapters(e,null)}),[e,n]),(0,b.jsx)(KH,{detectorRef:t})}};function JH(e,t,n,...r){if(!n)return;let i=n=>{try{console.error(`[${e}] ${t} callback threw an error`,n)}catch{}};try{let e=n(...r);if(e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`)return Promise.resolve(e).then(()=>void 0,e=>i(e))}catch(e){i(e)}}var YH=(e,t,n)=>n.reduce((e,n)=>n?.(e,t)??e,e),XH=class extends TI{_pendingTransforms=[];_completedOptimistics=[];_nextTransformOrder=0;_epoch=0;_baseValue;_cachedValue;constructor(e){super(),this._baseValue=e,this._cachedValue=e}_updateState(){let e=[...this._pendingTransforms.map(e=>({order:e.order,apply:t=>YH(t,e.task,[e.loading,e.optimistic])})),...this._completedOptimistics.map(({order:e,optimistic:t})=>({order:e,apply:t}))].sort((e,t)=>e.order-t.order);this._cachedValue=e.reduce((e,t)=>t.apply(e),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(e){this._baseValue=e,this._updateState()}reset(e){this._epoch++,this._pendingTransforms.length=0,this._completedOptimistics.length=0,this._baseValue=e,this._cachedValue=e,this._notifySubscribers()}async optimisticUpdate(e){let t=this._epoch,n=this._nextTransformOrder++,r=e.execute(),i={...e,order:n,task:r};try{this._pendingTransforms.push(i),this._updateState();let n=await r;if(t!==this._epoch)return n;this._baseValue=YH(this._baseValue,n,[e.optimistic,e.then]);for(let t of this._completedOptimistics)(e.then||t.order>i.order)&&(this._baseValue=t.optimistic(this._baseValue));return e.optimistic&&(this._completedOptimistics.push({order:i.order,optimistic:e.optimistic}),this._completedOptimistics.sort((e,t)=>e.order-t.order)),n}finally{let e=this._pendingTransforms.indexOf(i);e>-1&&this._pendingTransforms.splice(e,1),this._pendingTransforms.length===0&&(this._completedOptimistics.length=0),this._updateState()}}},ZH=Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),QH=new class extends HV{get error(){return ZH}messages=[];composer=VV(ZH,!0);isLoading=!0;getMessageById(){}getBranches(){return[]}export(){return{messages:[]}}subscribe(){return()=>{}}waitForUpdate(){return Promise.reject(ZH)}};function $H(e){return e}var eU=`__LOCALID_`,tU=e=>e||void 0,nU=(e,t)=>{let n=[...t.threadIds],r=[...t.archivedThreadIds],i=hM(t.threadIdMap),a=hM(t.threadData),o=new Set([...n,...r]);for(let t of e){switch(t.status){case`regular`:case`archived`:break;default:{let e=t.status;throw Error(`Unsupported state: ${e}`)}}let e=i[t.remoteId],s=e===void 0?void 0:a[e],c=s?.id??t.remoteId,l=e??$H(c),u=s!==void 0&&s.status!==`new`?s.initializeTask:void 0;o.has(c)?s!==void 0&&s.status!==t.status&&(t.status===`regular`?(r=r.filter(e=>e!==c),n.push(c)):(n=n.filter(e=>e!==c),r.push(c))):(o.add(c),t.status===`regular`?n.push(c):r.push(c)),i[c]=l,i[t.remoteId]=l,a[l]={...s?.localOrigin===!0?{localOrigin:!0}:{},id:c,remoteId:t.remoteId,externalId:t.externalId,status:t.status,title:t.title,lastMessageAt:t.lastMessageAt,custom:t.custom,initializeTask:u??Promise.resolve({remoteId:t.remoteId,externalId:t.externalId})}}return{threadIds:n,archivedThreadIds:r,threadIdMap:i,threadData:a}},rU=()=>({isLoading:!0,loadError:void 0,isLoadingMore:!1,cursor:void 0,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:hM(),threadData:hM()}),iU=e=>{let t;do t=`${eU}${mB()}`;while(e.threadIdMap[t]);let n=$H(t);return{id:t,state:{...e,newThreadId:t,threadIdMap:hM(e.threadIdMap,{[t]:n}),threadData:hM(e.threadData,{[n]:{status:`new`,id:t,remoteId:void 0,externalId:void 0,title:void 0,custom:void 0,localOrigin:!0}})}}},aU=(e,t,n)=>{let r=new Set(e.threadIds),i=new Set(e.archivedThreadIds),a=[],o=[],s=(e,t)=>e.has(t.id)||t.remoteId!==void 0&&e.has(t.remoteId);for(let t of Object.values(e.threadData)){let e=n.get(t.id);(e===void 0||e===`new`)&&(e!==void 0||t.localOrigin===!0)&&(t.status===`regular`&&!s(r,t)?(a.push(t),r.add(t.id)):t.status===`archived`&&!s(i,t)&&(o.push(t),i.add(t.id)))}if(a.length===0&&o.length===0)return e;let c=(e,t)=>{let n=e.indexOf(t.id);if(n!==-1)return n;let r=t.remoteId===void 0?-1:e.indexOf(t.remoteId);return r===-1?2**53-1:r};return a.sort((e,n)=>c(t.threadIds,e)-c(t.threadIds,n)),o.sort((e,n)=>c(t.archivedThreadIds,e)-c(t.archivedThreadIds,n)),{...e,threadIds:[...a.map(e=>e.id),...e.threadIds],archivedThreadIds:[...o.map(e=>e.id),...e.archivedThreadIds]}},oU=e=>new Map(Object.values(e.threadData).map(e=>[e.id,e.status])),sU=(e,t)=>{let n=Object.hasOwn(e.threadIdMap,t)?e.threadIdMap[t]:void 0;if(n!==void 0)return Object.hasOwn(e.threadData,n)?e.threadData[n]:void 0},cU=(e,t,n,r,i)=>{let a=$H(t),o=Object.hasOwn(e.threadData,a)?e.threadData[a]:void 0;if(!o)return{state:e,removedMappingId:void 0,survivorMappingId:a};let s=Object.hasOwn(e.threadIdMap,n)?e.threadIdMap[n]:void 0,c=s!==void 0&&s!==a&&Object.hasOwn(e.threadData,s)?e.threadData[s]:void 0,l=s!==void 0&&c!==void 0?{mappingId:s,data:c}:void 0,u=i!==void 0&&Object.hasOwn(e.threadIdMap,i)?e.threadIdMap[i]:void 0,d=l!==void 0&&u===l.mappingId?l.mappingId:a,f=l===void 0?void 0:d===a?l.mappingId:a,p=r??l?.data.externalId,m=hM(e.threadData);f!==void 0&&delete m[f];let h={...o,id:d,initializeTask:Promise.resolve({remoteId:n,externalId:p}),remoteId:n,externalId:p};m[d]={...l?.data,...h,title:o.title??l?.data.title,lastMessageAt:(`lastMessageAt`in o?o.lastMessageAt:void 0)??(l&&`lastMessageAt`in l.data?l.data.lastMessageAt:void 0),custom:o.custom??l?.data.custom};let g=hM(e.threadIdMap);if(f!==void 0)for(let[e,t]of Object.entries(g))t===f&&(g[e]=d);g[t]=d,g[n]=d;let _=e=>l===void 0?e:e.filter(e=>e!==l.data.id).map(e=>e===o.id?d:e);return{state:{...e,threadIds:_(e.threadIds),archivedThreadIds:_(e.archivedThreadIds),threadIdMap:g,threadData:m},removedMappingId:f,survivorMappingId:d}},lU=(e,t,n,r)=>{let i=sU(e,t);if(!i)return e;let{id:a,status:o}=i;if(o===n)return e;let s;if(n!==`deleted`){if(i.status===`new`){if(r===void 0)return e;s={...i,initializeTask:r,status:n}}else s={...i,status:n}}let c={...e};switch(o){case`new`:c.newThreadId=void 0;break;case`regular`:c.threadIds=c.threadIds.filter(e=>e!==a);break;case`archived`:c.archivedThreadIds=c.archivedThreadIds.filter(e=>e!==a);break;default:throw Error(`Unsupported state: ${o}`)}switch(n){case`regular`:c.threadIds=[a,...c.threadIds];break;case`archived`:c.archivedThreadIds=[a,...c.archivedThreadIds];break;case`deleted`:{let n=e.threadIdMap[t],r=hM(c.threadData);delete r[n],c.threadData=r;let i=hM(c.threadIdMap);for(let[e,t]of Object.entries(i))t===n&&delete i[e];c.threadIdMap=i;break}default:throw Error(`Unsupported state: ${n}`)}return s!==void 0&&(c.threadData={...c.threadData,[a]:s}),c},uU=(e,t,n)=>lU(e,t,n,void 0),dU=(e,t,n)=>lU(e,t,`regular`,n),fU=class extends Error{[qI]=!0;constructor(){super(`Thread list adapter changed while an operation was pending.`),this.name=`ThreadListAdapterChangedError`}};function pU(e,t){let n=e.get(t);return n===void 0&&(n={generations:new Set,pendingClaim:null,inFlightClaims:new Set,manualTitle:void 0,latestExplicit:null,nextOrder:0},e.set(t,n)),n}function mU(e,t,n){n.generations.size===0&&n.pendingClaim===null&&n.inFlightClaims.size===0&&n.manualTitle===void 0&&e.get(t)===n&&e.delete(t)}function hU(e,t){return!t.superseded&&(e.latestExplicit?.order??0)<=t.order}function gU(e,t){return(e.latestExplicit?.order??0)<t.order}function _U(e,t,n){let r=pU(e,t),i,a=new Promise(e=>{i=e}),o={title:n,order:++r.nextOrder,settled:a,settle:i};r.pendingClaim=o,r.inFlightClaims.add(o);for(let e of r.generations)e.order<o.order&&(e.claim=o);return o}function vU(e,t,n,r){n.settle(r);let i=e.get(t);i!==void 0&&(i.inFlightClaims.delete(n),i.pendingClaim===n&&(i.pendingClaim=null,r&&(i.manualTitle=n.title)),mU(e,t,i))}function yU(e,t,n){let r=n.manualTitle;if(r!==void 0)return n.manualTitle=void 0,mU(e,t,n),r}function bU(e,t){e.delete(t)}function xU(e,t,n){let r=pU(e,t);if(n&&r.pendingClaim===null&&yU(e,t,r)!==void 0)return null;let i,a=new Promise(e=>{i=e}),o={automatic:n,order:++r.nextOrder,claim:n?r.pendingClaim:null,beforeGenerationClaims:n?[]:[...r.inFlightClaims],superseded:!1,persisted:a,settlePersisted:i};if(!n){r.pendingClaim=null,r.manualTitle=void 0,r.latestExplicit=o;for(let e of r.generations)e.automatic&&(e.superseded=!0)}return r.generations.add(o),o}async function SU({states:e,threadId:t,automatic:n,generate:r,rename:i,applyTitle:a}){let o=pU(e,t),s=xU(e,t,n);if(s===null)return;let c,l=s.order,u=async e=>{let t=await e.settled;if(s.claim===e)return t||(s.claim=null,o.pendingClaim===e&&(o.pendingClaim=null)),t},d=()=>n&&yU(e,t,o)!==void 0,f=async()=>{if(c!==void 0)for(;;){let e=s.claim;if(e!==null&&e.order>l&&gU(o,e)){await u(e)===!0&&(c=e.title,l=e.order,await i(e.title));continue}let t=o.latestExplicit;if(t===null||t.order<=l)return;let n=await t.persisted;if(o.latestExplicit===t){if(l=t.order,n===void 0||n===c)return;c=n,await i(n)}}},p=async()=>{if(s.beforeGenerationClaims.length>0&&await Promise.all(s.beforeGenerationClaims.map(e=>e.settled)),s.claim!==null){let e=await u(s.claim);if(e===!0){s.superseded=!0;return}if(e===!1&&d())return}if(!hU(o,s))return;let e=!1,t;for(await r(async n=>{e=!0,t=n,n!==void 0&&(c=n);let r=s.claim;if(r!==null){if(await u(r)!==!1)return;if(d()){s.superseded=!0;return}}hU(o,s)&&await a(t)});;){let n=s.claim;if(n===null)return;let r=await u(n);if(r!==void 0){if(r===!1){if(d())return;e&&hU(o,s)&&await a(t);return}if(!gU(o,n))return;if(await i(n.title),c=n.title,l=n.order,s.claim===n){if(!hU(o,s))return;await a(n.title),s.superseded=!0;return}}}};try{await p(),await f()}finally{s.settlePersisted(c),o.generations.delete(s),mU(e,t,o)}}var CU=(e,t)=>Error(`Thread "${e}" not found while ${t}.`),wU=(e,t,n)=>Error(`Thread "${e}" has status "${t}", so it cannot ${n}.`),TU=rU(),EU=class extends TI{_options;_hookManager;_runtimeAdapters;_loadThreadsPromise;_loadMorePromise;_loadGeneration=0;_adapterGeneration=0;_replaceListOnNextLoad=!1;_staleThreadIdsOnReplace;_switchGeneration=0;_switchTask;_titleStates=new Map;_mainThreadId;_state=new XH(TU);_useAdaptersProvider=({children:e})=>{let t=this._options.adapter.unstable_useAdapters;return t===void 0?e:(0,b.jsx)(this._SynthesizedAdapters,{useAdapters:t,children:e})};_SynthesizedAdapters=({useAdapters:e,children:t})=>{let n=sB(e());return n==null?t:(0,b.jsx)(UV,{adapters:n,children:t})};resolveProvider(e){return e.unstable_Provider===void 0?e.unstable_useAdapters===void 0?TN:this._useAdaptersProvider:e.unstable_Provider}get threadItems(){return this._state.value.threadData}getLoadThreadsPromise(){if(!this._loadThreadsPromise){let e=this._loadGeneration,t=!1,n=oU(this._state.baseValue);this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>e===this._loadGeneration?{...t,isLoading:!0,loadError:void 0}:t,then:(r,i)=>{if(e!==this._loadGeneration)return r;if(this._replaceListOnNextLoad)return this._replaceListOnNextLoad=!1,t=!0,this._replaceWithThreads({...r,loadError:void 0},i.threads,tU(i.nextCursor));let a=nU(i.threads,{threadIds:[],archivedThreadIds:[],threadIdMap:{...r.threadIdMap},threadData:{...r.threadData}});return aU({...r,isLoading:!1,loadError:void 0,cursor:tU(i.nextCursor),threadIds:a.threadIds,archivedThreadIds:a.archivedThreadIds,threadIdMap:a.threadIdMap,threadData:a.threadData},r,n)}}).catch(n=>{if(e===this._loadGeneration){if(console.error(`[assistant-ui] thread list load failed:`,n),this._loadThreadsPromise=void 0,!this._replaceListOnNextLoad){this._state.update({...this._state.baseValue,isLoading:!1,loadError:n});return}this._replaceListOnNextLoad=!1,t=!0,this._state.update(this._replaceWithThreads({...this._state.baseValue,loadError:n},[],void 0))}}).then(()=>{if(!t)return;let e=this._options.threadId;e!==void 0&&this.getItemById(e)?.id!==this._mainThreadId&&this._switchToThreadFromProp(e).catch(()=>{})})}return this._loadThreadsPromise}loadMore(){if(this._loadMorePromise)return this._loadMorePromise;let e=this._state.value;if(e.cursor===void 0||e.isLoading)return Promise.resolve();let t=this._loadGeneration,n=this._options.adapter,r=e.cursor,i=this._state.optimisticUpdate({execute:()=>n.list({after:r}),loading:e=>t===this._loadGeneration?{...e,isLoadingMore:!0}:e,then:(e,r)=>{if(t!==this._loadGeneration||n!==this._options.adapter)return e;let i=nU(r.threads,{threadIds:[...e.threadIds],archivedThreadIds:[...e.archivedThreadIds],threadIdMap:{...e.threadIdMap},threadData:{...e.threadData}});return{...e,isLoadingMore:!1,cursor:tU(r.nextCursor),threadIds:i.threadIds,archivedThreadIds:i.archivedThreadIds,threadIdMap:i.threadIdMap,threadData:i.threadData}}}).catch(e=>{t===this._loadGeneration&&console.error(`[assistant-ui] thread list loadMore failed:`,e)}).then(()=>{this._loadMorePromise===i&&(this._loadMorePromise=void 0)});return this._loadMorePromise=i,i}constructor(e,t){super(),this._state.subscribe(()=>{this._notifySubscribers(),this._notifyThreadIdChange()}),this._runtimeAdapters={modelContext:t},this._hookManager=new qH(e.runtimeHook,this),this._hookManager.__internal_setDefaultAdapters(this._runtimeAdapters),this._hookManager.__internal_subscribeRunningChanged(()=>this._notifySubscribers()),this._hookManager.__internal_subscribeRuntimeReplaced(()=>{queueMicrotask(()=>this._notifySubscribers())}),this.providerStore=new EI(this.resolveProvider(e.adapter)),this.__internal_setOptions(e),this.switchToNewThread()}_initialThreadLoaded=!1;providerStore;__internal_setOptions(e){if(this._options===e)return;let t=this._options!==void 0&&this._options.adapter!==e.adapter,n=this._initialThreadLoaded&&this._options!==void 0&&this._options.threadId!==e.threadId;this._options=e,this.providerStore.setState(this.resolveProvider(e.adapter)),this._hookManager.setRuntimeHook(e.runtimeHook),t&&(this._loadGeneration++,this._adapterGeneration++,this._switchGeneration++,this._switchTask=void 0,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._replaceListOnNextLoad=!0,this._staleThreadIdsOnReplace=new Set(Object.values(this._state.baseValue.threadData).filter(e=>e.status!==`new`).map(e=>e.id)),this._state.update({...this._state.baseValue,cursor:void 0,loadError:void 0}),this._titleStates.clear()),n&&this._switchToThreadFromProp(e.threadId).catch(()=>{})}_requireAdapterGeneration(e){if(e!==this._adapterGeneration)throw new fU}_requireAdapterSettled(){if(this._replaceListOnNextLoad)throw new fU}_replaceWithThreads(e,t,n){let r=[];if(e.newThreadId){let t=Object.hasOwn(e.threadIdMap,e.newThreadId)?e.threadIdMap[e.newThreadId]:void 0,n=t&&Object.hasOwn(e.threadData,t)?e.threadData[t]:void 0;n?.status===`new`&&r.push(n)}let i=this._staleThreadIdsOnReplace;if(i)for(let t of Object.values(e.threadData))i.has(t.id)||(t.status===`new`||t.remoteId!==void 0)&&r.push(t);this._staleThreadIdsOnReplace=void 0;let a={threadIds:[],archivedThreadIds:[],threadIdMap:hM(),threadData:hM()};for(let e of r){let t=$H(e.id);Object.hasOwn(a.threadData,t)||(a.threadIdMap[e.id]=t,e.remoteId!==void 0&&(a.threadIdMap[e.remoteId]=t),a.threadData[t]=e)}let{threadIds:o,archivedThreadIds:s,threadIdMap:c,threadData:l}=nU(t,a);for(let e of r){if(e.remoteId===void 0)continue;let t=$H(e.id),n=Object.hasOwn(l,t)?l[t]:void 0;n!==void 0&&(n.status===`regular`&&!o.includes(n.id)?o.push(n.id):n.status===`archived`&&!s.includes(n.id)&&s.push(n.id))}let u={...e,isLoading:!1,cursor:n,threadIds:o,archivedThreadIds:s,threadIdMap:c,threadData:l,newThreadId:e.newThreadId!==void 0&&!Object.hasOwn(c,e.newThreadId)?void 0:e.newThreadId};if(sU(u,this._mainThreadId)===void 0){let e=u.newThreadId;if(e!==void 0)this._mainThreadId=e;else{let e=iU(u);this._mainThreadId=e.id,u=e.state}this._options.threadId===void 0?this._notifyThreadIdChange():this._lastNotifiedThreadId=void 0}let d=new Set(Object.values(u.threadData).map(e=>e.id));for(let t of Object.values(e.threadData))d.has(t.id)||this._hookManager.stopThreadRuntime(t.id);return this._hookManager.startThreadRuntime(this._mainThreadId).then(()=>this._notifySubscribers(),()=>void 0),u}__internal_load(){if(this.getLoadThreadsPromise(),this._initialThreadLoaded)return;this._initialThreadLoaded=!0;let e=this._options.threadId??this._options.initialThreadId;e!==void 0&&(this._options.threadId===void 0?this.switchToThread(e):this._switchToThreadFromProp(e)).catch(()=>{})}async reloadMainThread(){let e=this._mainThreadId;if(e===void 0||this.getItemById(e)?.status===`new`)return;let t=this._hookManager.getThreadRuntimeCore(e);try{t?.unstable_refetchThread?await t.unstable_refetchThread():await this._hookManager.__internal_restartThreadRuntime(e)}catch(t){if(e!==this._mainThreadId)return;throw t}e===this._mainThreadId&&this._notifySubscribers()}reload(){return this._loadGeneration++,this._loadThreadsPromise=void 0,this._loadMorePromise=void 0,this._state.update({...this._state.baseValue,cursor:void 0}),this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get loadError(){return this._state.value.loadError}get isLoadingMore(){return this._state.value.isLoadingMore}get hasMore(){return this._state.value.cursor!==void 0}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}get _mainThreadRemoteId(){if(this._mainThreadId!==void 0)return sU(this._state.value,this._mainThreadId)?.remoteId}_lastNotifiedThreadId=void 0;_notifyThreadIdChange(e=!0){let t=this._mainThreadRemoteId;this._lastNotifiedThreadId!==t&&(this._lastNotifiedThreadId=t,e&&JH(`assistant-ui`,`onThreadIdChange`,this._options.onThreadIdChange,t))}getMainThreadRuntimeCore(){return this._hookManager.getThreadRuntimeCore(this._mainThreadId)||QH}getThreadRuntimeCore(e){let t=this.getItemById(e);if(!t)throw CU(e,`getting its runtime`);let n=this._hookManager.getThreadRuntimeCore(t.id);if(!n)throw Error(`Runtime for thread "${e}" not found while getting its runtime.`);return n}unstable_isThreadRunning(e){let t=this.getItemById(e);return t?this._hookManager.__internal_isThreadRunning(t.id):!1}unstable_subscribeThreadEvents(e){return this._hookManager.__internal_subscribeThreadEvents(e)}getItemById(e){return sU(this._state.value,e)}switchToThread(e,t){return this._startSwitchToThread(e,t,!0)}_startSwitchToThread(e,t,n){let r=++this._switchGeneration,i=this._switchToThread(e,t,r,n);return this._switchTask=i,i}async _switchToThread(e,t,n,r){if(this._replaceListOnNextLoad&&e!==this._state.value.newThreadId)throw new fU;let i=this.getItemById(e);if(!i){let t=await this._options.adapter.fetch(e);if(n!==this._switchGeneration)return;let r=this._state.value,a=$H(t.remoteId),o={...r.threadData,[a]:{id:a,initializeTask:Promise.resolve({remoteId:t.remoteId,externalId:t.externalId}),remoteId:t.remoteId,externalId:t.externalId,status:t.status,title:t.title,lastMessageAt:t.lastMessageAt,custom:t.custom}},s={...r.threadIdMap,[t.remoteId]:a},c=t.remoteId,l=t.status===`regular`?r.threadIds.includes(c):r.archivedThreadIds.includes(c),u=r.threadIds.filter(e=>e!==c),d=r.archivedThreadIds.filter(e=>e!==c),f=t.status===`regular`?l?r.threadIds:[...u,c]:u,p=t.status===`archived`?l?r.archivedThreadIds:[...d,c]:d;this._state.update({...r,threadIds:f,archivedThreadIds:p,threadIdMap:s,threadData:o}),i=this.getItemById(e)}if(!i)throw CU(e,`switching to it`);if(this._mainThreadId===i.id)return;let a=this._hookManager.startThreadRuntime(i.id);if(this.mainThreadId===void 0?a.then(()=>this._notifySubscribers(),()=>void 0):await a,n!==this._switchGeneration)return;let o=this.getItemById(i.id);o?.id===i.id&&(o.status===`archived`&&t?.unarchive!==!1&&(await o.initializeTask,n!==this._switchGeneration||(o=this.getItemById(i.id),o?.id!==i.id)||o.status===`archived`&&(await this.unarchive(o.id),n!==this._switchGeneration||(o=this.getItemById(i.id),o?.id!==i.id)))||(this._mainThreadId=o.id,this._notifySubscribers(),this._notifyThreadIdChange(r)))}switchToNewThread(){return this._startSwitchToNewThread(!0)}_switchToThreadFromProp(e){return e===void 0?this._startSwitchToNewThread(!1):this._startSwitchToThread(e,void 0,!1)}_startSwitchToNewThread(e){let t=++this._switchGeneration,n=this._switchToNewThread(t,e);return this._switchTask=n,n}async _switchToNewThread(e,t){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)if(await this._state.waitForUpdate(),e!==this._switchGeneration)return;let n=this._state.baseValue,r=this._state.value.newThreadId;if(r===void 0){let e=iU(n);r=e.id,this._state.update(e.state)}return this._switchToThread(r,void 0,e,t)}initialize=async e=>{let t=this._options.adapter,n=this._adapterGeneration;if(this._state.value.newThreadId!==e){this._requireAdapterSettled();let t=this.getItemById(e);if(!t)throw CU(e,`initializing it`);if(t.status===`new`)throw wU(e,t.status,`be initialized here`);let{remoteId:r,externalId:i}=await t.initializeTask;return this._requireAdapterGeneration(n),{remoteId:r,externalId:i}}this._requireAdapterGeneration(n);let r=t.initialize(e),i,{remoteId:a,externalId:o}=await this._state.optimisticUpdate({execute:()=>r,optimistic:t=>dU(t,e,r),then:(t,{remoteId:r,externalId:a})=>{if(n!==this._adapterGeneration)return t;let o=cU(t,e,r,a,e);return i=o.removedMappingId,i===this._mainThreadId&&(this._mainThreadId=o.survivorMappingId),o.state}});return this._requireAdapterGeneration(n),i!==void 0&&this._hookManager.stopThreadRuntime(i),{remoteId:a,externalId:o}};generateTitle=async(e,t)=>{this._requireAdapterSettled();let n=this._options.adapter,r=this._adapterGeneration,i=this.getItemById(e);if(!i)throw CU(e,`generating its title`);if(i.status===`new`)throw wU(e,i.status,`generate a title`);let{remoteId:a}=await i.initializeTask;this._requireAdapterGeneration(r);let o=this._hookManager.getThreadRuntimeCore(i.id);if(!o)return;let s=o.messages.filter(BH);await SU({states:this._titleStates,threadId:i.id,automatic:t?.automatic===!0,generate:async e=>{let t=await n.generateTitle(a,s);this._requireAdapterGeneration(r),await VH(t,e)},rename:async e=>{this._requireAdapterGeneration(r),await n.rename(a,e)},applyTitle:async e=>{await this._state.optimisticUpdate({execute:async()=>{},optimistic:t=>{if(r!==this._adapterGeneration)return t;let n=sU(t,i.id);return n?{...t,threadData:{...t.threadData,[n.id]:{...n,title:e}}}:t}})}})};async rename(e,t){this._requireAdapterSettled();let n=this._options.adapter,r=this._adapterGeneration,i=this.getItemById(e);if(!i)throw CU(e,`renaming it`);if(i.status===`new`)throw wU(e,i.status,`be renamed`);let a=_U(this._titleStates,i.id,t);try{let o=await this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await i.initializeTask;return this._requireAdapterGeneration(r),n.rename(e,t)},optimistic:n=>{let r=sU(n,e);return r?{...n,threadData:{...n.threadData,[r.id]:{...r,title:t}}}:n}});return vU(this._titleStates,i.id,a,!0),o}catch(e){throw vU(this._titleStates,i.id,a,!1),e}}async updateCustom(e,t){this._requireAdapterSettled();let n=this._options.adapter,r=this._adapterGeneration,i=this.getItemById(e);if(!i)throw CU(e,`updating its custom metadata`);if(i.status===`new`)throw wU(e,i.status,`update custom metadata`);if(!n.updateCustom)throw Error(`Remote thread list adapter does not support updating custom metadata`);return this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await i.initializeTask;if(this._requireAdapterGeneration(r),!n.updateCustom)throw Error(`Remote thread list adapter does not support updating custom metadata`);return n.updateCustom(e,t)},optimistic:n=>{let r=sU(n,e);return r?{...n,threadData:{...n.threadData,[r.id]:{...r,custom:t}}}:n}})}async _ensureThreadIsNotMain(e){if(e===this.newThreadId)throw Error(`Cannot ensure new thread is not main`);let t;for(;e===this._mainThreadId;){let e=this._switchTask,n=!e||e===t;n&&(e=this.switchToNewThread()),t=e;try{await e}catch(t){if(n&&this._switchTask===e)throw t}}}async archive(e){this._requireAdapterSettled();let t=this._options.adapter,n=this._adapterGeneration,r=this.getItemById(e);if(!r)throw CU(e,`archiving it`);if(r.status!==`regular`)throw wU(e,r.status,`be archived`);return await this._ensureThreadIsNotMain(r.id),this._requireAdapterGeneration(n),this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await r.initializeTask;return this._requireAdapterGeneration(n),t.archive(e)},optimistic:e=>uU(e,r.id,`archived`)})}async unarchive(e){this._requireAdapterSettled();let t=this._options.adapter,n=this._adapterGeneration,r=this.getItemById(e);if(!r)throw CU(e,`unarchiving it`);if(r.status!==`archived`)throw wU(e,r.status,`be unarchived`);return this._state.optimisticUpdate({execute:async()=>{try{let{remoteId:e}=await r.initializeTask;return this._requireAdapterGeneration(n),await t.unarchive(e)}catch(e){throw n===this._adapterGeneration&&await this._ensureThreadIsNotMain(r.id),e}},optimistic:e=>uU(e,r.id,`regular`)})}async delete(e){this._requireAdapterSettled();let t=this._options.adapter,n=this._adapterGeneration,r=this.getItemById(e);if(!r)throw CU(e,`deleting it`);if(r.status!==`regular`&&r.status!==`archived`)throw wU(e,r.status,`be deleted`);await this._ensureThreadIsNotMain(r.id),this._requireAdapterGeneration(n);let i=await this._state.optimisticUpdate({execute:async()=>{let{remoteId:e}=await r.initializeTask;return this._requireAdapterGeneration(n),await t.delete(e)},optimistic:e=>uU(e,r.id,`deleted`)});return this._hookManager.stopThreadRuntime(r.id),bU(this._titleStates,r.id),i}__internal_dispose(){this._hookManager.__internal_dispose()}async detach(e){let t=this._adapterGeneration,n=this.getItemById(e);if(!n)throw CU(e,`detaching it`);if(n.status!==`regular`&&n.status!==`archived`)throw wU(e,n.status,`be detached`);await this._ensureThreadIsNotMain(n.id),this._requireAdapterGeneration(t),this._hookManager.stopThreadRuntime(n.id)}boundIdsStore=new EI([]);__internal_RenderComponent=()=>{let e=SN();X(()=>(this.boundIdsStore.setState([...this.boundIdsStore.getState(),e]),()=>{this.boundIdsStore.setState(this.boundIdsStore.getState().filter(t=>t!==e))}),[e]);let t=KI(this.boundIdsStore),n=KI(this.providerStore),r=Q();return(t.length===0||t[0]===e)&&(0,b.jsxs)(UV,{adapters:this._runtimeAdapters,children:[(0,b.jsx)(this._hookManager.__internal_RenderThreadRuntimes,{provider:n}),(0,b.jsx)(this._hookManager.__internal_Host,{parentClient:r})]})}},DU=class extends tH{threads;constructor(e){super(),this.threads=new EU(e,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},OU=e=>{let t=J(18),n;t[0]===e?n=t[1]:(n=()=>new DU(e),t[0]=e,t[1]=n);let[r]=pN(n),i;t[2]===r.threads?i=t[3]:(i=()=>()=>queueMicrotask(()=>r.threads.__internal_dispose()),t[2]=r.threads,t[3]=i);let a;t[4]===r?a=t[5]:(a=[r],t[4]=r,t[5]=a),xN(i,a);let o;t[6]!==e||t[7]!==r.threads?(o=()=>{r.threads.__internal_setOptions(e),r.threads.__internal_load()},t[6]=e,t[7]=r.threads,t[8]=o):o=t[8];let s;t[9]!==e||t[10]!==r?(s=[r,e],t[9]=e,t[10]=r,t[11]=s):s=t[11],X(o,s);let c;t[12]===r.threads?c=t[13]:(c=()=>{if(typeof window>`u`||typeof document>`u`)return;let e=()=>{r.threads.loadError!==void 0&&r.threads.reload()},t=()=>{document.visibilityState===`visible`&&e()};return window.addEventListener(`online`,e),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`online`,e),document.removeEventListener(`visibilitychange`,t)}},t[12]=r.threads,t[13]=c);let l;t[14]===r?l=t[15]:(l=[r],t[14]=r,t[15]=l),X(c,l);let u;return t[16]===r?u=t[17]:(u=new XV(r),t[16]=r,t[17]=u),u},kU=e=>{let[t]=pN(()=>new EI(e.runtimeHook));_N(()=>{t.setState(e.runtimeHook)},[t,e.runtimeHook]);let n=Y(e.initialThreadId),r=gN(function(){return KI({subscribe:t.subscribe,getState:t.getState,getServerSnapshot:t.getState})()},[t]),i=vN(t=>e.onThreadIdChange?.(t)),a=hN(()=>({adapter:e.adapter,allowNesting:e.allowNesting,threadId:e.threadId,initialThreadId:n.current,runtimeHook:r,onThreadIdChange:i}),[e.adapter,e.allowNesting,e.threadId,r]);if(Q().threadListItem.source!==null){if(!a.allowNesting)throw Error(`useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).`);return e.runtimeHook()}return OU(a)},AU=e=>{let t=J(6),{id:n,children:r}=e,i=Q(),a;t[0]===n?a=t[1]:(a=MP({message:fI({source:`thread`,query:{type:`id`,id:n},get:e=>e.thread.message({id:n})}),composer:fI({source:`message`,query:{},get:e=>e.thread.message({id:n}).composer()})}),t[0]=n,t[1]=a);let o=a,s;return t[2]!==i||t[3]!==r||t[4]!==o?(s=(0,b.jsx)(BL,{extends:i,config:o,children:r}),t[2]=i,t[3]=r,t[4]=o,t[5]=s):s=t[5],s},jU=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,MU=()=>null,NU=new WeakMap,PU=(e,t)=>{let n=NU.get(e);return n||(n=new Set(e.map(e=>e.id)),NU.set(e,n)),n.has(t)},FU=(e,t,n)=>{switch(t){case`user`:return n?e.UserEditComposer??e.EditComposer??e.UserMessage??e.Message:e.UserMessage??e.Message;case`assistant`:return n?e.AssistantEditComposer??e.EditComposer??e.AssistantMessage??e.Message:e.AssistantMessage??e.Message;case`system`:return n?e.SystemEditComposer??e.EditComposer??e.SystemMessage??e.Message??MU:e.SystemMessage??e.Message??MU;default:throw Error(`Unknown message role: ${t}`)}},IU=e=>{let t=J(6),{components:n}=e,r=$(HU),i=$(UU),a;t[0]!==n||t[1]!==i||t[2]!==r?(a=FU(n,r,i),t[0]=n,t[1]=i,t[2]=r,t[3]=a):a=t[3];let o=a,s;return t[4]===o?s=t[5]:(s=(0,b.jsx)(o,{}),t[4]=o,t[5]=s),s},LU=wN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(IU,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(ZB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&jU(e.components,t.components));LU.displayName=`ThreadPrimitive.MessageByIndex`;var RU=wN(e=>{let t=J(7),{messageId:n,components:r}=e,i;if(t[0]===n?i=t[1]:(i=e=>PU(e.thread.messages,n),t[0]=n,t[1]=i),!$(i))return null;let a;t[2]===r?a=t[3]:(a=(0,b.jsx)(IU,{components:r}),t[2]=r,t[3]=a);let o;return t[4]!==n||t[5]!==a?(o=(0,b.jsx)(AU,{id:n,children:a}),t[4]=n,t[5]=a,t[6]=o):o=t[6],o},(e,t)=>e.messageId===t.messageId&&jU(e.components,t.components));RU.displayName=`ThreadPrimitive.Unstable_MessageById`;var zU=({children:e})=>{let t=$(zF(e=>e.thread.messages.map(e=>e.id)));return hN(()=>t.length===0?null:t.map((t,n)=>(0,b.jsx)(ZB,{index:n,children:(0,b.jsx)(UL,{getItemState:e=>e.thread.message({index:n}).getState(),children:t=>e({get message(){return t()}})})},t)),[t,e])},BU=e=>{let t=J(4),{components:n,children:r}=e;if(n){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(zU,{children:()=>(0,b.jsx)(IU,{components:n})}),t[0]=n,t[1]=e),e}let i;return t[2]===r?i=t[3]:(i=(0,b.jsx)(zU,{children:r}),t[2]=r,t[3]=i),i};BU.displayName=`ThreadPrimitive.Messages`;var VU=wN(BU,(e,t)=>e.children||t.children?e.children===t.children:jU(e.components,t.components));function HU(e){return e.message.role}function UU(e){return e.message.composer.isEditing}var WU=e=>{let t=e.message.metadata;if(t&&typeof t==`object`)return t.custom?.quote},GU=class extends Error{componentName;constructor(e,t=`Component "${e}" is not in the generative-ui allowlist.`){super(t),this.name=`GenerativeUIRenderError`,this.componentName=e}},KU=e=>typeof e==`object`&&!!e,qU=e=>e==null?[]:Array.isArray(e)?e:[e],JU=(e,t,n,r)=>{if(e==null)return null;if(typeof e==`string`)return e;if(!KU(e)||!(`component`in e)||typeof e.component!=`string`)return null;let{component:i,props:a,children:o,key:s}=e,c=t[i];if(!c){if(n)return(0,b.jsx)(n,{component:i,props:a},s??r);throw new GU(i)}return EN(c,{...a??{},key:s??r},...qU(o).map((e,i)=>JU(e,t,n,`${r}/${i}`)))},YU=e=>{let t=J(11),{spec:n,components:r,Fallback:i}=e,a=n?.root,o;t[0]===a?o=t[1]:(o=qU(a),t[0]=a,t[1]=o);let s=o,c;if(t[2]!==i||t[3]!==r||t[4]!==s){let e;t[6]!==i||t[7]!==r?(e=(e,t)=>JU(e,r,i,`${t}`),t[6]=i,t[7]=r,t[8]=e):e=t[8],c=s.map(e),t[2]=i,t[3]=r,t[4]=s,t[5]=c}else c=t[5];let l;return t[9]===c?l=t[10]:(l=(0,b.jsx)(b.Fragment,{children:c}),t[9]=c,t[10]=l),l};YU.displayName=`GenerativeUIRender`;var XU=e=>{let t=J(4),{components:n,spec:r,Fallback:i}=e,a=$(ZU),o=r??a;if(!o)return null;let s;return t[0]!==i||t[1]!==n||t[2]!==o?(s=(0,b.jsx)(YU,{spec:o,components:n,Fallback:i}),t[0]=i,t[1]=n,t[2]=o,t[3]=s):s=t[3],s};XU.displayName=`MessagePrimitive.GenerativeUI`;function ZU(e){let t=e.part;return t?.type===`generative-ui`?t.spec:void 0}var QU=e=>{let t=-1;return{startGroup:e=>{t===-1&&(t=e)},endGroup:(n,r)=>{t!==-1&&(r.push({type:e,startIndex:t,endIndex:n}),t=-1)},finalize:(n,r)=>{t!==-1&&r.push({type:e,startIndex:t,endIndex:n})}}},$U=(e,t,n)=>{let r=[];if(t){let t=QU(`chainOfThoughtGroup`);for(let n=0;n<e.length;n++){let i=e[n];i===`tool-call`||i===`reasoning`?t.startGroup(n):(t.endGroup(n-1,r),r.push({type:`single`,index:n}))}t.finalize(e.length-1,r)}else{let t=QU(`toolGroup`),n=QU(`reasoningGroup`);for(let i=0;i<e.length;i++){let a=e[i];a===`tool-call`?(n.endGroup(i-1,r),t.startGroup(i)):a===`reasoning`?(t.endGroup(i-1,r),n.startGroup(i)):(t.endGroup(i-1,r),n.endGroup(i-1,r),r.push({type:`single`,index:i}))}t.finalize(e.length-1,r),n.finalize(e.length-1,r)}if(n){let e=new Set;for(let t of r){if(t.type===`single`)continue;let r=n[t.startIndex];r!==void 0&&!e.has(r)&&(e.add(r),t.idKey=`id:${r}`)}}return r},eW=e=>{let t=J(10),n=$(zF(wW)),r=$(zF(EW)),i;bb0:{if(n.length===0){let e;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[0]=e):e=t[0];let n;t[1]===r?n=t[2]:(n={ranges:e,partIds:r},t[1]=r,t[2]=n),i=n;break bb0}let a;t[3]!==n||t[4]!==r||t[5]!==e?(a=$U(n,e,r),t[3]=n,t[4]=r,t[5]=e,t[6]=a):a=t[6];let o;t[7]!==r||t[8]!==a?(o={ranges:a,partIds:r},t[7]=r,t[8]=a,t[9]=o):o=t[9],i=o}return i},tW=e=>{let t=J(9),n,r;t[0]===e?(n=t[1],r=t[2]):({Fallback:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]!==n||t[4]!==r.toolName?(i=e=>e.tools.toolUIs[r.toolName]?.[0]?.render??n,t[3]=n,t[4]=r.toolName,t[5]=i):i=t[5];let a=$(i);if(!a)return null;let o;return t[6]!==a||t[7]!==r?(o=(0,b.jsx)(a,{...r}),t[6]=a,t[7]=r,t[8]=o):o=t[8],o},nW=(e,t,n)=>e.renderers[t]?.[0]||(e.fallbacks[0]??n),rW=e=>{let t=J(9),n,r;t[0]===e?(n=t[1],r=t[2]):({Fallback:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]!==n||t[4]!==r.name?(i=e=>nW(e.dataRenderers,r.name,n),t[3]=n,t[4]=r.name,t[5]=i):i=t[5];let a=$(i);if(!a)return null;let o;return t[6]!==a||t[7]!==r?(o=(0,b.jsx)(a,{...r}),t[6]=a,t[7]=r,t[8]=o):o=t[8],o},iW={Text:()=>null,Reasoning:()=>null,Source:()=>null,Image:()=>null,File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},aW=e=>{let t=J(41),{components:n}=e,r;t[0]===n?r=t[1]:(r=n===void 0?{}:n,t[0]=n,t[1]=r);let{Text:i,Reasoning:a,Image:o,Source:s,File:c,Unstable_Audio:l,tools:u,data:d,generativeUI:f}=r,p=i===void 0?iW.Text:i,m=a===void 0?iW.Reasoning:a,h=o===void 0?iW.Image:o,g=s===void 0?iW.Source:s,_=c===void 0?iW.File:c,v=l===void 0?iW.Unstable_Audio:l,y;t[2]===u?y=t[3]:(y=u===void 0?{}:u,t[2]=u,t[3]=y);let x=y,S=Q(),C=$(DW),w=C.type;if(w===`tool-call`){let e=S.part.addToolResult,n=S.part.resumeToolCall,r=S.part.respondToToolApproval;if(`Override`in x){let i;return t[4]!==e||t[5]!==C||t[6]!==r||t[7]!==n||t[8]!==x.Override?(i=(0,b.jsx)(x.Override,{...C,addResult:e,resume:n,respondToApproval:r}),t[4]=e,t[5]=C,t[6]=r,t[7]=n,t[8]=x.Override,t[9]=i):i=t[9],i}let i=x.by_name?.[C.toolName]??x.Fallback,a;return t[10]!==i||t[11]!==e||t[12]!==C||t[13]!==r||t[14]!==n?(a=(0,b.jsx)(tW,{...C,Fallback:i,addResult:e,resume:n,respondToApproval:r}),t[10]=i,t[11]=e,t[12]=C,t[13]=r,t[14]=n,t[15]=a):a=t[15],a}if(C.status?.type===`requires-action`)throw Error(`Encountered unexpected requires-action status`);switch(w){case`text`:{let e;return t[16]!==p||t[17]!==C?(e=(0,b.jsx)(p,{...C}),t[16]=p,t[17]=C,t[18]=e):e=t[18],e}case`reasoning`:{let e;return t[19]!==m||t[20]!==C?(e=(0,b.jsx)(m,{...C}),t[19]=m,t[20]=C,t[21]=e):e=t[21],e}case`source`:{let e;return t[22]!==g||t[23]!==C?(e=(0,b.jsx)(g,{...C}),t[22]=g,t[23]=C,t[24]=e):e=t[24],e}case`image`:{let e;return t[25]!==h||t[26]!==C?(e=(0,b.jsx)(h,{...C}),t[25]=h,t[26]=C,t[27]=e):e=t[27],e}case`file`:{let e;return t[28]!==_||t[29]!==C?(e=(0,b.jsx)(_,{...C}),t[28]=_,t[29]=C,t[30]=e):e=t[30],e}case`audio`:{let e;return t[31]!==v||t[32]!==C?(e=(0,b.jsx)(v,{...C}),t[31]=v,t[32]=C,t[33]=e):e=t[33],e}case`data`:{let e=d?.by_name?.[C.name]??d?.Fallback,n;return t[34]!==e||t[35]!==C?(n=(0,b.jsx)(rW,{...C,Fallback:e}),t[34]=e,t[35]=C,t[36]=n):n=t[36],n}case`generative-ui`:{if(!f?.components)return null;let e=C,n;return t[37]!==f.Fallback||t[38]!==f.components||t[39]!==e.spec?(n=(0,b.jsx)(YU,{spec:e.spec,components:f.components,Fallback:f.Fallback}),t[37]=f.Fallback,t[38]=f.components,t[39]=e.spec,t[40]=n):n=t[40],n}default:return console.warn(`Unknown message part type: ${w}`),null}},oW=wN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(aW,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(QB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.generativeUI===t.components?.generativeUI&&e.components?.ToolGroup===t.components?.ToolGroup&&e.components?.ReasoningGroup===t.components?.ReasoningGroup);oW.displayName=`MessagePrimitive.PartByIndex`;var sW=e=>{let t=J(6),{status:n,component:r}=e,i=n.type===`running`,a;t[0]!==r||t[1]!==n?(a=(0,b.jsx)(r,{type:`text`,text:``,status:n}),t[0]=r,t[1]=n,t[2]=a):a=t[2];let o;return t[3]!==i||t[4]!==a?(o=(0,b.jsx)(eV,{text:``,isRunning:i,children:a}),t[3]=i,t[4]=a,t[5]=o):o=t[5],o},cW=Object.freeze({type:`complete`}),lW=Object.freeze({type:`running`}),uW=wN(e=>{let t=J(6),{components:n}=e,r=$(OW);if(n?.Empty){let e;return t[0]!==n.Empty||t[1]!==r?(e=(0,b.jsx)(n.Empty,{status:r}),t[0]=n.Empty,t[1]=r,t[2]=e):e=t[2],e}if(r.type!==`running`)return null;let i=n?.Text??iW.Text,a;return t[3]!==r||t[4]!==i?(a=(0,b.jsx)(sW,{status:r,component:i}),t[3]=r,t[4]=i,t[5]=a):a=t[5],a},(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),dW=wN(e=>{let t=J(4),{components:n,enabled:r}=e,i;if(t[0]===r?i=t[1]:(i=e=>{if(!r||e.message.parts.length===0)return!1;let t=e.message.parts[e.message.parts.length-1];return t?.type!==`text`&&t?.type!==`reasoning`},t[0]=r,t[1]=i),!$(i))return null;let a;return t[2]===n?a=t[3]:(a=(0,b.jsx)(uW,{components:n}),t[2]=n,t[3]=a),a},(e,t)=>e.enabled===t.enabled&&e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),fW=wN(e=>{let t=J(4),{Quote:n}=e,r=$(WU);if(!r)return null;let i;return t[0]!==n||t[1]!==r.messageId||t[2]!==r.text?(i=(0,b.jsx)(n,{text:r.text,messageId:r.messageId}),t[0]=n,t[1]=r.messageId,t[2]=r.text,t[3]=i):i=t[3],i});function pW(e,t){return(e.toolUIs[t.toolName]?.[0]?.render??null)||(OV(t.mcp?.app?.resourceUri)&&e.mcpApp?e.mcpApp.render:null)}var mW=()=>{let e=J(6),t=Q(),n=$(kW),r=$(AW);if(!r||n.type!==`tool-call`)return null;let i;return e[0]!==r||e[1]!==t.part.addToolResult||e[2]!==t.part.respondToToolApproval||e[3]!==t.part.resumeToolCall||e[4]!==n?(i=(0,b.jsx)(r,{...n,addResult:t.part.addToolResult,resume:t.part.resumeToolCall,respondToApproval:t.part.respondToToolApproval}),e[0]=r,e[1]=t.part.addToolResult,e[2]=t.part.respondToToolApproval,e[3]=t.part.resumeToolCall,e[4]=n,e[5]=i):i=e[5],i},hW=()=>{let e=J(3),t=$(jW),n=$(MW);if(!n||t.type!==`data`)return null;let r=t,i;return e[0]!==n||e[1]!==r?(i=(0,b.jsx)(n,{...r}),e[0]=n,e[1]=r,e[2]=i):i=e[2],i},gW=()=>{let e=J(2),t=$(NW);if(t===`tool-call`){let t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,b.jsx)(mW,{}),e[0]=t):t=e[0],t}if(t===`data`){let t;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,b.jsx)(hW,{}),e[1]=t):t=e[1],t}return null},_W=Object.freeze({type:`text`,text:``,status:lW}),vW=({children:e})=>{let t=Q(),n=$(e=>e.dataRenderers);return(0,b.jsx)(UL,{getItemState:e=>e.part.getState(),children:r=>e({get part(){let e=r();if(e.type===`tool-call`){let n=pW(t.tools.getState(),e)!==null,r=t.part;return{...e,toolUI:n?(0,b.jsx)(mW,{}):null,addResult:r.addToolResult,resume:r.resumeToolCall,respondToApproval:r.respondToToolApproval}}if(e.type===`data`){let t=nW(n,e.name,void 0)!==void 0;return{...e,dataRendererUI:t?(0,b.jsx)(hW,{}):null}}return e}})})},yW=e=>{let t=J(5),{index:n,children:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(vW,{children:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(QB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},bW=e=>{let t=J(9),{children:n}=e,r=$(PW),i=$(FW),a=r===0&&i;if(r===0){if(!a)return null;let e;t[0]===n?e=t[1]:(e=n({part:_W}),t[0]=n,t[1]=e);let r;return t[2]===e?r=t[3]:(r=(0,b.jsx)(eV,{text:``,isRunning:!0,children:e}),t[2]=e,t[3]=r),r}let o;if(t[4]!==n||t[5]!==r){let e;t[7]===n?e=t[8]:(e=(e,t)=>(0,b.jsx)(yW,{index:t,children:e=>n(e)??(0,b.jsx)(gW,{})},t),t[7]=n,t[8]=e),o=(0,b.jsx)(b.Fragment,{children:Array.from({length:r},e)}),t[4]=n,t[5]=r,t[6]=o}else o=t[6];return o},xW=e=>{let t=J(5),{components:n,unstable_showEmptyOnNonTextEnd:r,children:i}=e,a=r===void 0||r;if(i){let e;return t[0]===i?e=t[1]:(e=(0,b.jsx)(bW,{children:i}),t[0]=i,t[1]=e),e}let o;return t[2]!==n||t[3]!==a?(o=(0,b.jsx)(SW,{components:n,unstable_showEmptyOnNonTextEnd:a}),t[2]=n,t[3]=a,t[4]=o):o=t[4],o};xW.displayName=`MessagePrimitive.Parts`;var SW=e=>{let t=J(15),{components:n,unstable_showEmptyOnNonTextEnd:r}=e,i=$(IW),{ranges:a,partIds:o}=eW(!!n?.ChainOfThought),s;bb0:{if(i===0){let e;t[0]===n?e=t[1]:(e=(0,b.jsx)(uW,{components:n}),t[0]=n,t[1]=e),s=e;break bb0}let e;if(t[2]!==n||t[3]!==a||t[4]!==o){let r=new Set,i=e=>{let t=o[e];return t!==void 0&&!r.has(t)?(r.add(t),`part-id:${t}`):`part-${e}`};e=a.map(e=>{if(e.type===`single`)return(0,b.jsx)(oW,{index:e.index,components:n},e.index);if(e.type===`chainOfThoughtGroup`){let t=n?.ChainOfThought;return t?(0,b.jsx)(sV,{startIndex:e.startIndex,endIndex:e.endIndex,children:(0,b.jsx)(t,{})},`chainOfThought-${e.idKey??e.startIndex}`):null}if(e.type===`toolGroup`){let t=n?.ToolGroup??iW.ToolGroup;return(0,b.jsx)(t,{startIndex:e.startIndex,endIndex:e.endIndex,children:Array.from({length:e.endIndex-e.startIndex+1},(t,r)=>{let a=e.startIndex+r;return(0,b.jsx)(oW,{index:a,components:n},i(a))})},`tool-${e.idKey??e.startIndex}`)}{let t=n?.ReasoningGroup??iW.ReasoningGroup;return(0,b.jsx)(t,{startIndex:e.startIndex,endIndex:e.endIndex,children:Array.from({length:e.endIndex-e.startIndex+1},(t,r)=>{let i=e.startIndex+r;return(0,b.jsx)(oW,{index:i,components:n},`part-${i}`)})},`reasoning-${e.startIndex}`)}}),t[2]=n,t[3]=a,t[4]=o,t[5]=e}else e=t[5];s=e}let c=s,l;t[6]===n?l=t[7]:(l=n?.Quote&&(0,b.jsx)(fW,{Quote:n.Quote}),t[6]=n,t[7]=l);let u;t[8]!==n||t[9]!==r?(u=(0,b.jsx)(dW,{components:n,enabled:r}),t[8]=n,t[9]=r,t[10]=u):u=t[10];let d;return t[11]!==c||t[12]!==l||t[13]!==u?(d=(0,b.jsxs)(b.Fragment,{children:[l,c,u]}),t[11]=c,t[12]=l,t[13]=u,t[14]=d):d=t[14],d};function CW(e){return e.type}function wW(e){return e.message.parts.map(CW)}function TW(e){return e.type===`tool-call`?e.toolCallId:void 0}function EW(e){return e.message.parts.map(TW)}function DW(e){return e.part}function OW(e){return e.message.status??cW}function kW(e){return e.part}function AW(e){return e.part.type===`tool-call`?pW(e.tools,e.part):null}function jW(e){return e.part}function MW(e){return e.part.type===`data`?nW(e.dataRenderers,e.part.name,void 0)??null:null}function NW(e){return e.part.type}function PW(e){return e.message.parts.length}function FW(e){return(e.message.status?.type??`complete`)===`running`}function IW(e){return e.message.parts.length}var LW=Symbol.for(`@assistant-ui/groupBy.memoKey`),RW=e=>{let t=e,n=((e,n)=>{if(e.type===`tool-call`){if((OV(e.mcp?.app?.resourceUri)||(n?.toolUIs?.[e.toolName]?.[0]?.standalone??!1))&&t[`standalone-tool-call`]!==void 0)return t[`standalone-tool-call`];let r=t[`tool-call:${e.toolName}`];return r===void 0?t[`tool-call`]??[]:r}return t[e.type]??[]}),r=Object.keys(e).sort().map(t=>[t,e[t]]);return n[LW]=`groupPartByType:${JSON.stringify(r)}`,n},zW=e=>{let t=e.nextChildIdx++;return e.nodeKey===``?String(t):`${e.nodeKey}.${t}`},BW=(e,t)=>{if(!(t===void 0||e.claimed.has(t)))return e.claimed.add(t),`id:${t}`},VW=(e,t)=>{let n={key:``,nodeKey:``,indices:[],children:[],nextChildIdx:0,claimed:new Set},r=[n],i=()=>{let e=r.pop(),n=r[r.length-1];n.children.push({type:`group`,key:e.key,nodeKey:e.nodeKey,idKey:BW(n,t?.[e.indices[0]]),indices:e.indices,children:e.children})};for(let n=0;n<e.length;n++){let a=e[n],o=0;for(;o<r.length-1&&o<a.length&&r[o+1].key===a[o];)o++;for(;r.length-1>o;)i();for(;r.length-1<a.length;){let e=r[r.length-1];r.push({key:a[r.length-1],nodeKey:zW(e),indices:[],children:[],nextChildIdx:0,claimed:new Set})}let s=r[r.length-1];s.children.push({type:`part`,index:n,nodeKey:zW(s),idKey:BW(s,t?.[n])});for(let e=1;e<r.length;e++)r[e].indices.push(n)}for(;r.length>1;)i();return n.children},HW=(e,t,n)=>{if(!n)return!1;switch(e){case`never`:return!1;case`always`:return!0;case`empty`:return t.length===0;case`no-text`:{let e=t[t.length-1];return e===void 0||e.type!==`text`&&e.type!==`reasoning`}}},UW=()=>{throw Error("MessagePrimitive.GroupedParts: rendered `children` under a leaf part. `children` is only meaningful for `group-…` cases — add a matching case for the part type or return `null` to skip it.")},WW=(e,t,n)=>{if(e.type===`part`)return(0,b.jsx)(yW,{index:e.index,children:({part:e})=>n({part:e,children:(0,b.jsx)(UW,{})})},e.idKey?`part-${e.idKey}`:`part-${e.index}`);let{status:r,counts:i}=aV(t,e.indices),a={type:e.key,status:r,counts:i,indices:e.indices};return(0,b.jsx)(TN,{children:n({part:a,children:(0,b.jsx)(b.Fragment,{children:e.children.map(e=>WW(e,t,n))})})},e.idKey??e.nodeKey)},GW=({groupBy:e,indicator:t=`no-text`,children:n})=>{let r=$(zF(e=>e.message.parts)),i=$(e=>e.tools.toolUIs),a=$(e=>t!==`never`&&e.message.status?.type===`running`),o=hN(()=>{let t={toolUIs:i};return VW(r.map(n=>e(n,t)??[]),r.map(e=>e.type===`tool-call`?e.toolCallId:void 0))},[r,e[LW]??e,i]);return(0,b.jsxs)(b.Fragment,{children:[o.map(e=>WW(e,r,n)),HW(t,r,a)&&n({part:{type:`indicator`},children:(0,b.jsx)(UW,{})})]})};GW.displayName=`MessagePrimitive.GroupedParts`;var KW=wN(e=>{let t=J(5),{children:n}=e,r=$(WU);if(!r)return null;let i;t[0]!==n||t[1]!==r?(i=n(r),t[0]=n,t[1]=r,t[2]=i):i=t[2];let a;return t[3]===i?a=t[4]:(a=(0,b.jsx)(b.Fragment,{children:i}),t[3]=i,t[4]=a),a});KW.displayName=`MessagePrimitive.Quote`;var qW=(e,t)=>{switch(t.type){case`image`:return e?.Image??e?.Attachment;case`document`:return e?.Document??e?.Attachment;case`file`:return e?.File??e?.Attachment;default:return e?.Attachment}},JW=e=>{let t=J(5),{components:n}=e,r=$(QW);if(!r)return null;let i=r,a;t[0]!==n||t[1]!==i?(a=qW(n,i),t[0]=n,t[1]=i,t[2]=a):a=t[2];let o=a;if(!o)return null;let s;return t[3]===o?s=t[4]:(s=(0,b.jsx)(o,{}),t[3]=o,t[4]=s),s},YW=wN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(JW,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(JB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);YW.displayName=`MessagePrimitive.AttachmentByIndex`;var XW=({children:e})=>{let t=$(zF(e=>e.message.role===`user`?(e.message.attachments??[]).map(e=>e.id):[]));return hN(()=>t.map((t,n)=>(0,b.jsx)(JB,{index:n,children:(0,b.jsx)(UL,{getItemState:e=>e.message.attachment({index:n}).getState(),children:t=>e({get attachment(){return t()}})})},t)),[t,e])},ZW=e=>{let t=J(4),{components:n,children:r}=e;if(n){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(XW,{children:e=>{let{attachment:t}=e,r=qW(n,t);return r?(0,b.jsx)(r,{}):null}}),t[0]=n,t[1]=e),e}let i;return t[2]===r?i=t[3]:(i=(0,b.jsx)(XW,{children:r}),t[2]=r,t[3]=i),i};ZW.displayName=`MessagePrimitive.Attachments`;function QW(e){return e.attachment}var $W=(e,t)=>{switch(t.type){case`image`:return e?.Image??e?.Attachment;case`document`:return e?.Document??e?.Attachment;case`file`:return e?.File??e?.Attachment;default:return e?.Attachment}},eG=e=>{let t=J(5),{components:n}=e,r=$(iG);if(!r)return null;let i;t[0]!==r||t[1]!==n?(i=$W(n,r),t[0]=r,t[1]=n,t[2]=i):i=t[2];let a=i;if(!a)return null;let o;return t[3]===a?o=t[4]:(o=(0,b.jsx)(a,{}),t[3]=a,t[4]=o),o},tG=wN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(eG,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(YB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&e.components?.Image===t.components?.Image&&e.components?.Document===t.components?.Document&&e.components?.File===t.components?.File&&e.components?.Attachment===t.components?.Attachment);tG.displayName=`ComposerPrimitive.AttachmentByIndex`;var nG=({children:e})=>{let t=$(zF(e=>e.composer.attachments.map(e=>e.id)));return hN(()=>t.map((t,n)=>(0,b.jsx)(YB,{index:n,children:(0,b.jsx)(UL,{getItemState:e=>e.composer.attachment({index:n}).getState(),children:t=>e({get attachment(){return t()}})})},t)),[t,e])},rG=e=>{let t=J(4),{components:n,children:r}=e;if(n){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(nG,{children:e=>{let{attachment:t}=e,r=$W(n,t);return r?(0,b.jsx)(r,{}):null}}),t[0]=n,t[1]=e),e}let i;return t[2]===r?i=t[3]:(i=(0,b.jsx)(nG,{children:r}),t[2]=r,t[3]=i),i};rG.displayName=`ComposerPrimitive.Attachments`;function iG(e){return e.attachment}var aG=wN(({children:e})=>{let t=$(zF(e=>e.composer.queue.map(e=>e.id)));return hN(()=>t.map((t,n)=>(0,b.jsx)(dV,{index:n,children:(0,b.jsx)(UL,{getItemState:e=>e.composer.queueItem({index:n}).getState(),children:t=>e({get queueItem(){return t()}})})},t)),[t,e])});aG.displayName=`ComposerPrimitive.Queue`;var oG=wN(e=>{let t=J(6),{index:n,archived:r,components:i}=e,a=r!==void 0&&r,o=i.ThreadListItem,s;t[0]===o?s=t[1]:(s=(0,b.jsx)(o,{}),t[0]=o,t[1]=s);let c;return t[2]!==a||t[3]!==n||t[4]!==s?(c=(0,b.jsx)(lV,{index:n,archived:a,children:s}),t[2]=a,t[3]=n,t[4]=s,t[5]=c):c=t[5],c},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);oG.displayName=`ThreadListPrimitive.ItemByIndex`;var sG=({archived:e,children:t})=>{let n=$(zF(t=>e?t.threads.archivedThreadIds:t.threads.threadIds));return hN(()=>n.map((n,r)=>(0,b.jsx)(lV,{index:r,archived:e,children:(0,b.jsx)(UL,{getItemState:t=>t.threads.item({index:r,archived:e}).getState(),children:e=>t({get threadListItem(){return e()}})})},n)),[n,e,t])},cG=e=>{let t=J(8),{archived:n,components:r,children:i}=e,a=n!==void 0&&n;if(r){let e=r.ThreadListItem,n;t[0]===e?n=t[1]:(n=()=>(0,b.jsx)(e,{}),t[0]=e,t[1]=n);let i;return t[2]!==a||t[3]!==n?(i=(0,b.jsx)(sG,{archived:a,children:n}),t[2]=a,t[3]=n,t[4]=i):i=t[4],i}let o;return t[5]!==a||t[6]!==i?(o=(0,b.jsx)(sG,{archived:a,children:i}),t[5]=a,t[6]=i,t[7]=o):o=t[7],o};cG.displayName=`ThreadListPrimitive.Items`;var lG=e=>{let{children:t}=e;return $(uG)?t:null};lG.displayName=`MessagePartPrimitive.InProgress`;function uG(e){return e.part.status.type===`running`}var dG=e=>{let t=J(2),{fallback:n}=e,r=$(fG)||n,i;return t[0]===r?i=t[1]:(i=(0,b.jsx)(b.Fragment,{children:r}),t[0]=r,t[1]=i),i};dG.displayName=`ThreadListItemPrimitive.Title`;function fG(e){return e.threadListItem.title}var pG=e=>{let t=J(2),{components:n}=e,r=n.Suggestion,i;return t[0]===r?i=t[1]:(i=(0,b.jsx)(r,{}),t[0]=r,t[1]=i),i},mG=wN(e=>{let t=J(5),{index:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(pG,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(uV,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.index===t.index&&e.components.Suggestion===t.components.Suggestion);mG.displayName=`ThreadPrimitive.SuggestionByIndex`;var hG=({children:e})=>{let t=$(e=>e.suggestions.suggestions.length);return hN(()=>t===0?null:Array.from({length:t},(t,n)=>(0,b.jsx)(uV,{index:n,children:(0,b.jsx)(UL,{getItemState:e=>e.suggestions.suggestion({index:n}).getState(),children:t=>e({get suggestion(){return t()}})})},n)),[t,e])},gG=e=>{let t=J(4),{components:n,children:r}=e;if(n){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(hG,{children:()=>(0,b.jsx)(pG,{components:n})}),t[0]=n,t[1]=e),e}let i;return t[2]===r?i=t[3]:(i=(0,b.jsx)(hG,{children:r}),t[2]=r,t[3]=i),i};gG.displayName=`ThreadPrimitive.Suggestions`;var _G=wN(gG,(e,t)=>e.children||t.children?e.children===t.children:e.components.Suggestion===t.components.Suggestion),vG=e=>{let t=J(3),n;return t[0]!==e.dictation||t[1]!==e.editing?(n=t=>{if(e.editing===!0&&!t.composer.isEditing||e.editing===!1&&t.composer.isEditing)return!1;let n=t.composer.dictation!=null;return!(e.dictation===!0&&!n||e.dictation===!1&&n)},t[0]=e.dictation,t[1]=e.editing,t[2]=n):n=t[2],$(n)},yG=e=>{let t=J(3),n,r;return t[0]===e?(n=t[1],r=t[2]):({children:n,...r}=e,t[0]=e,t[1]=n,t[2]=r),vG(r)?n:null};yG.displayName=`ComposerPrimitive.If`;var bG=e=>!e.composer.canSend||e.thread.isRunning&&!e.thread.capabilities.queue,xG=e=>!e.composer.canCancel,SG=e=>e.composer.isEditing||e.optional.thread?.voice!==void 0||e.optional.thread?.capabilities.edit===!1,CG=e=>e.thread.isRunning||e.thread.isDisabled||e.thread.voice!==void 0||e.message.role!==`assistant`||!e.thread.capabilities.reload,wG=e=>e.message.role===`assistant`&&e.message.status?.type===`running`||!e.message.parts.some(e=>e.type===`text`&&e.text.length>0),TG=e=>e.message.branchNumber<=1||!e.thread.capabilities.switchToBranch||e.thread.isRunning&&!e.thread.capabilities.switchBranchDuringRun,EG=e=>e.message.branchNumber>=e.message.branchCount||!e.thread.capabilities.switchToBranch||e.thread.isRunning&&!e.thread.capabilities.switchBranchDuringRun,DG=(e,t)=>e.thread.isDisabled||t&&e.thread.isRunning&&!e.thread.capabilities.queue,OG=e=>{if(e.message.status?.type!==`incomplete`||e.message.status.reason!==`error`)return;let t=e.message.status.error;return typeof t==`string`?t:typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`?t.message:t??`An error occurred`},kG=e=>!e.threads.hasMore||e.threads.isLoading||e.threads.isLoadingMore,AG=()=>{let e=J(5),t=Q(),n=$(bG),r;e[0]===t?r=e[1]:(r=e=>{t.composer.send(e)},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={send:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},jG=()=>{let e=J(5),t=Q(),n=$(xG),r;e[0]===t?r=e[1]:(r=()=>{t.composer.cancel()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==i||e[3]!==n?(a={cancel:i,disabled:n},e[2]=i,e[3]=n,e[4]=a):a=e[4],a},MG=()=>{let e=J(5),t=Q(),n=$(NG),r;e[0]===t?r=e[1]:(r=()=>{t.composer.startDictation()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={startDictation:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a};function NG(e){return e.composer.dictation!=null||!e.thread.capabilities.dictation||!e.composer.isEditing}var PG=()=>{let e=J(5),t=Q(),n=$(FG),r;e[0]===t?r=e[1]:(r=e=>t.composer.addAttachment(e),e[0]=t,e[1]=r);let i=r,a;return e[2]!==i||e[3]!==n?(a={addAttachment:i,disabled:n},e[2]=i,e[3]=n,e[4]=a):a=e[4],a};function FG(e){return!e.composer.isEditing}var IG=e=>{let t=J(15),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{copiedDuration:r,copyToClipboard:i}=n,a=r===void 0?3e3:r,o=Q(),s=$(wG),c=$(LG),l=$(RG),u=$(zG),d=Y(void 0),f=Y(0),p,m;t[2]===o?(p=t[3],m=t[4]):(p=()=>()=>{f.current+=1,d.current!==void 0&&(clearTimeout(d.current),d.current=void 0,o.message.setIsCopied(!1))},m=[o],t[2]=o,t[3]=p,t[4]=m),X(p,m);let h;t[5]!==o||t[6]!==u||t[7]!==a||t[8]!==i||t[9]!==l?(h=()=>{if(!i)return;let e=l?u:o.message.getCopyText();if(!e)return;let t=f.current,n;try{n=i(e)}catch{return}Promise.resolve(n).then(()=>{t===f.current&&(d.current!==void 0&&clearTimeout(d.current),o.message.setIsCopied(!0),d.current=setTimeout(()=>{d.current=void 0,o.message.setIsCopied(!1)},a))},BG)},t[5]=o,t[6]=u,t[7]=a,t[8]=i,t[9]=l,t[10]=h):h=t[10];let g=h,_=s||!i,v;return t[11]!==g||t[12]!==c||t[13]!==_?(v={copy:g,disabled:_,isCopied:c},t[11]=g,t[12]=c,t[13]=_,t[14]=v):v=t[14],v};function LG(e){return e.message.isCopied}function RG(e){return e.composer.isEditing}function zG(e){return e.composer.text}function BG(){}var VG=()=>{let e=J(5),t=Q(),n=$(SG),r;e[0]===t?r=e[1]:(r=()=>{t.composer.beginEdit()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={edit:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},HG=()=>{let e=J(5),t=Q(),n=$(CG),r;e[0]===t?r=e[1]:(r=()=>{t.message.reload()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={reload:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},UG=()=>{let e=J(5),t=Q(),n=$(GG),r;e[0]===t?r=e[1]:(r=()=>{t.message.submitFeedback({type:`positive`})},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={submit:i,isSubmitted:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},WG=()=>{let e=J(5),t=Q(),n=$(KG),r;e[0]===t?r=e[1]:(r=()=>{t.message.submitFeedback({type:`negative`})},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={submit:i,isSubmitted:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a};function GG(e){return e.message.metadata.submittedFeedback?.type===`positive`}function KG(e){return e.message.metadata.submittedFeedback?.type===`negative`}var qG=()=>{let e=J(5),t=Q(),n=$(YG),r;e[0]===t?r=e[1]:(r=async()=>{t.message.speak()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={speak:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a};function JG(e){return e.type===`text`&&e.text.length>0}function YG(e){return e.message.role===`assistant`&&e.message.status?.type===`running`||!e.message.parts.some(JG)}var XG=()=>{let e=J(5),t=Q(),n=$(ZG),r;e[0]===t?r=e[1]:(r=()=>{t.message.stopSpeaking()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={stopSpeaking:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a};function ZG(e){return e.message.speech==null}var QG=()=>{let e=J(5),t=Q(),n=$(EG),r;e[0]===t?r=e[1]:(r=()=>{t.message.switchToBranch({position:`next`})},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={next:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},$G=()=>{let e=J(5),t=Q(),n=$(TG),r;e[0]===t?r=e[1]:(r=()=>{t.message.switchToBranch({position:`previous`})},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={previous:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},eK=e=>{let t=J(10),{prompt:n,send:r,clearComposer:i}=e,a=i===void 0||i,o=Q(),s=r??!1,c;t[0]===s?c=t[1]:(c=e=>DG(e,s),t[0]=s,t[1]=c);let l=$(c),u;t[2]!==o||t[3]!==a||t[4]!==n||t[5]!==s?(u=()=>{if(s){let{isRunning:e,capabilities:t}=o.thread.getState();if(e&&!t.queue)return;o.thread.append({content:[{type:`text`,text:n}],runConfig:o.composer.getState().runConfig}),a&&!e&&o.composer.setText(``)}else if(a)o.composer.setText(n);else{let e=o.composer.getState().text;o.composer.setText([e,n].filter(tK).join(` `))}},t[2]=o,t[3]=a,t[4]=n,t[5]=s,t[6]=u):u=t[6];let d=u,f;return t[7]!==l||t[8]!==d?(f={trigger:d,disabled:l},t[7]=l,t[8]=d,t[9]=f):f=t[9],f};function tK(e){return e.trim()}var nK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threadListItem.archive()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={archive:r},e[2]=r,e[3]=i),i},rK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threadListItem.delete()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={delete:r},e[2]=r,e[3]=i),i},iK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threadListItem.unarchive()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={unarchive:r},e[2]=r,e[3]=i),i},aK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threadListItem.switchTo()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={switchTo:r},e[2]=r,e[3]=i),i},oK=()=>{let e=J(4),t=Q(),n;e[0]===t?n=e[1]:(n=()=>{t.threads.switchToNewThread()},e[0]=t,e[1]=n);let r=n,i;return e[2]===r?i=e[3]:(i={switchToNewThread:r},e[2]=r,e[3]=i),i},sK=()=>{let e=J(5),t=Q(),n=$(kG),r;e[0]===t?r=e[1]:(r=()=>{t.threads.loadMore()},e[0]=t,e[1]=r);let i=r,a;return e[2]!==n||e[3]!==i?(a={loadMore:i,disabled:n},e[2]=n,e[3]=i,e[4]=a):a=e[4],a},cK=()=>$(OG),lK=e=>{let{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:a,unstable_enableMessageQueue:o,unstable_queueClearOnRewind:s,unstable_queueClearOnCancel:c,...l}=e;return{localRuntimeOptions:{cloud:t,initialMessages:n,maxSteps:r,adapters:i,unstable_humanToolNames:a,unstable_enableMessageQueue:o,unstable_queueClearOnRewind:s,unstable_queueClearOnCancel:c},otherOptions:l}};function uK(e,t){function n(n){let r=jN(e);if(!n?.optional&&!r)throw Error(`This component must be used within ${t}.`);return r}return n}function dK(e,t){function n(n){let r=e(n);return r?r[t]:null}function r(e){let t=!1,r;typeof e==`function`?r=e:e&&typeof e==`object`&&(t=!!e.optional,r=e.selector);let i=n({optional:t});return i?r?i(r):i():null}return{[t]:r,[`${t}Store`]:n}}var fK=kN(null),{useThreadViewport:pK,useThreadViewportStore:mK}=dK(uK(fK,`ThreadPrimitive.Viewport`),`useThreadViewport`),hK=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},gK=(e=>e?hK(e):hK),_K=e=>e;function vK(e,t=_K){let n=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(n),n}var yK=e=>{let t=gK(e),n=e=>vK(t,e);return Object.assign(n,t),n},bK=(e=>e?yK(e):yK),xK=e=>{let t=new Map,n=()=>{let n=0;for(let e of t.values())n+=e;e(n)};return{register:()=>{let e=Symbol();return t.set(e,0),{setHeight:r=>{t.get(e)!==r&&(t.set(e,r),n())},unregister:()=>{t.delete(e),n()}}}}},SK=(e={})=>{let t=new Set,n=xK(e=>{a.setState({height:{...a.getState().height,viewport:e}})}),r=xK(e=>{a.setState({height:{...a.getState().height,inset:e}})}),i=(e,t)=>(a.setState({element:{...a.getState().element,[e]:t}}),()=>{a.getState().element[e]===t&&a.setState({element:{...a.getState().element,[e]:null}})}),a=bK(()=>({isAtBottom:!0,scrollToBottom:({behavior:e=`auto`}={})=>{jP(t,()=>({behavior:e}),`Thread viewport`)},onScrollToBottom:e=>(t.add(e),()=>{t.delete(e)}),turnAnchor:e.turnAnchor??`bottom`,topAnchorMessageClamp:{tallerThan:e.topAnchorMessageClamp?.tallerThan??`10em`,visibleHeight:e.topAnchorMessageClamp?.visibleHeight??`6em`},height:{viewport:0,inset:0},element:{viewport:null,anchor:null,target:null},targetConfig:null,topAnchorTurn:null,registerViewport:n.register,registerContentInset:r.register,registerViewportElement:e=>i(`viewport`,e),registerAnchorElement:e=>i(`anchor`,e),registerAnchorTargetElement:(e,t)=>(a.setState({element:{...a.getState().element,target:e},targetConfig:e&&t?t:null}),()=>{a.getState().element.target===e&&a.setState({element:{...a.getState().element,target:null},targetConfig:null})}),setTopAnchorTurn:e=>{a.setState({topAnchorTurn:e})}}));return a},CK=e=>e,wK=e=>{let t=J(11),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n={optional:!0},t[0]=n):n=t[0];let r=mK(n),i;t[1]===e?i=t[2]:(i=()=>SK(e),t[1]=e,t[2]=i);let[a]=pN(i),o,s;t[3]!==r||t[4]!==a?(o=()=>r?.getState().onScrollToBottom(e=>{a.getState().scrollToBottom(e)}),s=[r,a],t[3]=r,t[4]=a,t[5]=o,t[6]=s):(o=t[5],s=t[6]),X(o,s);let c,l;return t[7]!==r||t[8]!==a?(c=()=>{if(r)return a.subscribe(e=>{r.getState().isAtBottom!==e.isAtBottom&&CK(r).setState({isAtBottom:e.isAtBottom})})},l=[a,r],t[7]=r,t[8]=a,t[9]=c,t[10]=l):(c=t[9],l=t[10]),X(c,l),a},TK=e=>{let t=J(7),{children:n,options:r}=e,i;t[0]===r?i=t[1]:(i=r===void 0?{}:r,t[0]=r,t[1]=i);let a=wK(i),o;t[2]===a?o=t[3]:(o=()=>({useThreadViewport:a}),t[2]=a,t[3]=o);let[s]=pN(o),c;return t[4]!==n||t[5]!==s?(c=(0,b.jsx)(fK.Provider,{value:s,children:n}),t[4]=n,t[5]=s,t[6]=c):c=t[6],c},EK=()=>{let e=J(3),t=Q(),n,r;return e[0]===t?(n=e[1],r=e[2]):(n=()=>{},r=[t],e[0]=t,e[1]=n,e[2]=r),X(n,r),null},DK=wN(e=>{let t=J(8),{children:n,aui:r,config:i,runtime:a}=e,o=r??null,s;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,b.jsx)(EK,{}),t[0]=s):s=t[0];let c;t[1]===n?c=t[2]:(c=(0,b.jsx)(TK,{children:n}),t[1]=n,t[2]=c);let l;return t[3]!==i||t[4]!==a||t[5]!==o||t[6]!==c?(l=(0,b.jsxs)(JL,{runtime:a,aui:o,config:i,children:[s,c]}),t[3]=i,t[4]=a,t[5]=o,t[6]=c,t[7]=l):l=t[7],l}),OK=/:([\w-]{1,64})\[([^\]\n]{1,1024})\](?:\{name=([^}\n]{1,1024})\})?/gu,kK={serialize(e){let t=e.id===e.label?``:`{name=${e.id}}`;return`:${e.type}[${e.label}]${t}`},parse(e){let t=[],n=0;for(let r of e.matchAll(OK)){r.index>n&&t.push({kind:`text`,text:e.slice(n,r.index)});let i=r[2];t.push({kind:`mention`,type:r[1],label:i,id:r[3]??i}),n=r.index+r[0].length}return n<e.length&&t.push({kind:`text`,text:e.slice(n)}),t}},AK=Object.defineProperty,jK=(e,t)=>AK(e,`name`,{value:t,configurable:!0});function MK(e,t=globalThis?.document){let n=dt(e);y.useEffect(()=>{let e=jK(e=>{e.key===`Escape`&&n(e)},`handleKeyDown`);return t.addEventListener(`keydown`,e,{capture:!0}),()=>t.removeEventListener(`keydown`,e,{capture:!0})},[n,t])}jK(MK,`useEscapeKeydown`);var NK=d;NK.dispatchDiscreteCustomEvent=_,NK.Root=d;var PK=Object.defineProperty,FK=(e,t)=>{let n={};for(var r in e)PK(n,r,{get:e[r],enumerable:!0});return t||PK(n,Symbol.toStringTag,{value:`Module`}),n},IK=[`a`,`button`,`div`,`form`,`h2`,`h3`,`img`,`input`,`label`,`li`,`nav`,`ol`,`p`,`select`,`span`,`svg`,`ul`];function LK(e,t){return DN(e,void 0,t===void 0?e.props.children:t)}function RK(e,t,n){return(0,b.jsx)(s,{...n,children:LK(e,t)})}function zK(e){let t=Z((t,n)=>{let r=J(17),i,a,o,s;r[0]===t?(i=r[1],a=r[2],o=r[3],s=r[4]):({render:o,asChild:i,children:a,...s}=t,r[0]=t,r[1]=i,r[2]=a,r[3]=o,r[4]=s);let c=e;if(o&&ON(o)){let e=s,t;r[5]!==a||r[6]!==o?(t=LK(o,a),r[5]=a,r[6]=o,r[7]=t):t=r[7];let i;return r[8]!==n||r[9]!==e||r[10]!==t?(i=(0,b.jsx)(c,{...e,asChild:!0,ref:n,children:t}),r[8]=n,r[9]=e,r[10]=t,r[11]=i):i=r[11],i}let l=s,u;return r[12]!==i||r[13]!==a||r[14]!==n||r[15]!==l?(u=(0,b.jsx)(c,{...l,asChild:i,ref:n,children:a}),r[12]=i,r[13]=a,r[14]=n,r[15]=l,r[16]=u):u=r[16],u});return t.displayName=typeof e==`string`?e:e.displayName??e.name??`Component`,t}function BK(e){let t=NK[e],n=zK(t);return n.displayName=`Primitive.${e}`,n}var VK=IK.reduce((e,t)=>(e[t]=BK(t),e),{}),HK={Hidden:`hidden`,Floating:`floating`,Normal:`normal`},UK=e=>{let t=J(5),{hideWhenRunning:n,autohide:r,autohideFloat:i,forceVisible:a}=e,o;return t[0]!==r||t[1]!==i||t[2]!==a||t[3]!==n?(o=e=>{if(n&&e.thread.isRunning)return HK.Hidden;let t=r===`always`||r===`not-last`&&!e.message.isLast,o=a||e.message.isHovering;return t?o?i===`always`||i===`single-branch`&&e.message.branchCount<=1?HK.Floating:HK.Normal:HK.Hidden:HK.Normal},t[0]=r,t[1]=i,t[2]=a,t[3]=n,t[4]=o):o=t[4],$(o)},WK=kN(null),GK=()=>jN(WK),KK=Z((e,t)=>{let n=J(18),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({hideWhenRunning:a,autohide:r,autohideFloat:i,...o}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let[s,c]=pN(0),l;n[5]===Symbol.for(`react.memo_cache_sentinel`)?(l=()=>{let e=!1;return c(qK),()=>{e||(e=!0,c(JK))}},n[5]=l):l=n[5];let u=l,d;n[6]===Symbol.for(`react.memo_cache_sentinel`)?(d={acquireInteractionLock:u},n[6]=d):d=n[6];let f=d,p=s>0,m;n[7]!==r||n[8]!==i||n[9]!==a||n[10]!==p?(m={hideWhenRunning:a,autohide:r,autohideFloat:i,forceVisible:p},n[7]=r,n[8]=i,n[9]=a,n[10]=p,n[11]=m):m=n[11];let h=UK(m);if(h===HK.Hidden)return null;let g;n[12]===h?g=n[13]:(g=h===HK.Floating?{"data-floating":`true`}:null,n[12]=h,n[13]=g);let _;return n[14]!==t||n[15]!==o||n[16]!==g?(_=(0,b.jsx)(WK.Provider,{value:f,children:(0,b.jsx)(VK.div,{...g,...o,ref:t})}),n[14]=t,n[15]=o,n[16]=g,n[17]=_):_=n[17],_});KK.displayName=`ActionBarPrimitive.Root`;function qK(e){return e+1}function JK(e){return Math.max(0,e-1)}var YK=e=>{let t=J(4),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{copiedDuration:r}=n,i=r===void 0?3e3:r,a;t[2]===i?a=t[3]:(a={copiedDuration:i,copyToClipboard:ZK},t[2]=i,t[3]=a);let{copy:o,disabled:s}=IG(a);return s?null:o},XK=Z((e,t)=>{let n=J(20),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({copiedDuration:r,onClick:a,disabled:i,...o}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let s=$(QK),c;n[5]===r?c=n[6]:(c={copiedDuration:r},n[5]=r,n[6]=c);let l=YK(c),u;n[7]===s?u=n[8]:(u=s?{"data-copied":`true`}:{},n[7]=s,n[8]=u);let d=i||!l,f;n[9]===l?f=n[10]:(f=()=>{l?.()},n[9]=l,n[10]=f);let p;n[11]!==a||n[12]!==f?(p=P(a,f),n[11]=a,n[12]=f,n[13]=p):p=n[13];let m;return n[14]!==t||n[15]!==o||n[16]!==u||n[17]!==d||n[18]!==p?(m=(0,b.jsx)(VK.button,{type:`button`,...u,...o,ref:t,disabled:d,onClick:p}),n[14]=t,n[15]=o,n[16]=u,n[17]=d,n[18]=p,n[19]=m):m=n[19],m});XK.displayName=`ActionBarPrimitive.Copy`;function ZK(e){return typeof navigator>`u`||!navigator.clipboard?Promise.reject(Error(`Clipboard API is unavailable`)):navigator.clipboard.writeText(e)}function QK(e){return e.message.isCopied}var $K=(e,t,n=[])=>{let r=Z((e,r)=>{let i=J(6),a={},o={};Object.keys(e).forEach(t=>{n.includes(t)?a[t]=e[t]:o[t]=e[t]});let s=t(a)??void 0,c=VK,l=o.disabled||!s,u=P(o.onClick,s),d;return i[0]!==r||i[1]!==o||i[2]!==c.button||i[3]!==l||i[4]!==u?(d=(0,b.jsx)(c.button,{type:`button`,...o,ref:r,disabled:l,onClick:u}),i[0]=r,i[1]=o,i[2]=c.button,i[3]=l,i[4]=u,i[5]=d):d=i[5],d});return r.displayName=e,r},eq=$K(`ActionBarPrimitive.Reload`,()=>{let{disabled:e,reload:t}=HG();return e?null:t}),tq=$K(`ActionBarPrimitive.Edit`,()=>{let{disabled:e,edit:t}=VG();return e?null:t}),nq=$K(`ActionBarPrimitive.Speak`,()=>{let{disabled:e,speak:t}=qG();return e?null:t}),rq=()=>{let{disabled:e,stopSpeaking:t}=XG();return e?null:t},iq=Z((e,t)=>{let n=J(10),r=rq(),i=!r,a;n[0]===r?a=n[1]:(a=()=>{r?.()},n[0]=r,n[1]=a);let o;n[2]!==e.onClick||n[3]!==a?(o=P(e.onClick,a),n[2]=e.onClick,n[3]=a,n[4]=o):o=n[4];let s;return n[5]!==e||n[6]!==t||n[7]!==i||n[8]!==o?(s=(0,b.jsx)(VK.button,{type:`button`,disabled:i,...e,ref:t,onClick:o}),n[5]=e,n[6]=t,n[7]=i,n[8]=o,n[9]=s):s=n[9],s});iq.displayName=`ActionBarPrimitive.StopSpeaking`;var aq=()=>{let{submit:e}=UG();return e},oq=Z((e,t)=>{let n=J(17),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({onClick:i,disabled:r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let o=$(sq),s=aq(),c;n[4]===o?c=n[5]:(c=o?{"data-submitted":`true`}:{},n[4]=o,n[5]=c);let l=r||!s,u;n[6]===s?u=n[7]:(u=()=>{s?.()},n[6]=s,n[7]=u);let d;n[8]!==i||n[9]!==u?(d=P(i,u),n[8]=i,n[9]=u,n[10]=d):d=n[10];let f;return n[11]!==t||n[12]!==a||n[13]!==c||n[14]!==l||n[15]!==d?(f=(0,b.jsx)(VK.button,{type:`button`,...c,...a,ref:t,disabled:l,onClick:d}),n[11]=t,n[12]=a,n[13]=c,n[14]=l,n[15]=d,n[16]=f):f=n[16],f});oq.displayName=`ActionBarPrimitive.FeedbackPositive`;function sq(e){return e.message.metadata.submittedFeedback?.type===`positive`}var cq=()=>{let{submit:e}=WG();return e},lq=Z((e,t)=>{let n=J(17),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({onClick:i,disabled:r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let o=$(uq),s=cq(),c;n[4]===o?c=n[5]:(c=o?{"data-submitted":`true`}:{},n[4]=o,n[5]=c);let l=r||!s,u;n[6]===s?u=n[7]:(u=()=>{s?.()},n[6]=s,n[7]=u);let d;n[8]!==i||n[9]!==u?(d=P(i,u),n[8]=i,n[9]=u,n[10]=d):d=n[10];let f;return n[11]!==t||n[12]!==a||n[13]!==c||n[14]!==l||n[15]!==d?(f=(0,b.jsx)(VK.button,{type:`button`,...c,...a,ref:t,disabled:l,onClick:d}),n[11]=t,n[12]=a,n[13]=c,n[14]=l,n[15]=d,n[16]=f):f=n[16],f});lq.displayName=`ActionBarPrimitive.FeedbackNegative`;function uq(e){return e.message.metadata.submittedFeedback?.type===`negative`}var dq=e=>{let t=J(6),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{filename:r,onExport:i}=n,a=Q(),o=$(mq),s;return t[2]!==a.message||t[3]!==r||t[4]!==i?(s=async()=>{let e=a.message.getCopyText();if(!e)return;if(i){await i(e);return}let t=new Blob([e],{type:`text/markdown`}),n=URL.createObjectURL(t),o=document.createElement(`a`);o.href=n,o.download=r??`message-${Date.now()}.md`,o.click(),setTimeout(()=>URL.revokeObjectURL(n),4e4)},t[2]=a.message,t[3]=r,t[4]=i,t[5]=s):s=t[5],o?s:null},fq=Z((e,t)=>{let n=J(19),r,i,a,o,s;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],s=n[5]):({filename:i,onExport:o,onClick:a,disabled:r,...s}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=s);let c;n[6]!==i||n[7]!==o?(c={filename:i,onExport:o},n[6]=i,n[7]=o,n[8]=c):c=n[8];let l=dq(c),u=r||!l,d;n[9]===l?d=n[10]:(d=()=>{l?.().catch(hq)},n[9]=l,n[10]=d);let f;n[11]!==a||n[12]!==d?(f=P(a,d),n[11]=a,n[12]=d,n[13]=f):f=n[13];let p;return n[14]!==t||n[15]!==s||n[16]!==u||n[17]!==f?(p=(0,b.jsx)(VK.button,{type:`button`,...s,ref:t,disabled:u,onClick:f}),n[14]=t,n[15]=s,n[16]=u,n[17]=f,n[18]=p):p=n[18],p});fq.displayName=`ActionBarPrimitive.ExportMarkdown`;function pq(e){return e.type===`text`&&e.text.length>0}function mq(e){return(e.message.role!==`assistant`||e.message.status?.type!==`running`)&&e.message.parts.some(pq)}function hq(e){console.error(`[assistant-ui] markdown export failed:`,e)}var gq=FK({Copy:()=>XK,Edit:()=>tq,ExportMarkdown:()=>fq,FeedbackNegative:()=>lq,FeedbackPositive:()=>oq,Reload:()=>eq,Root:()=>KK,Speak:()=>nq,StopSpeaking:()=>iq}),_q=ul(),vq=e=>{let t=J(25),n,r,i,a;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4]):({__scopeActionBarMore:n,open:i,onOpenChange:r,...a}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a);let o=_q(n),s=GK(),c=Y(null),l=i!==void 0,u;t[5]===s?u=t[6]:(u=e=>{if(e){if(c.current)return;c.current=s?.acquireInteractionLock()??null;return}c.current?.(),c.current=null},t[5]=s,t[6]=u);let d=u,f;t[7]!==l||t[8]!==r||t[9]!==d?(f=e=>{l||d(e),r?.(e)},t[7]=l,t[8]=r,t[9]=d,t[10]=f):f=t[10];let p=f,m,h;t[11]!==l||t[12]!==i||t[13]!==d?(m=()=>{l&&d(!!i)},h=[l,i,d],t[11]=l,t[12]=i,t[13]=d,t[14]=m,t[15]=h):(m=t[14],h=t[15]),X(m,h);let g,_;t[16]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>()=>{c.current?.(),c.current=null},_=[],t[16]=g,t[17]=_):(g=t[16],_=t[17]),X(g,_);let v;t[18]===i?v=t[19]:(v=i===void 0?null:{open:i},t[18]=i,t[19]=v);let y;return t[20]!==p||t[21]!==a||t[22]!==o||t[23]!==v?(y=(0,b.jsx)(Ml,{...o,...a,...v,onOpenChange:p}),t[20]=p,t[21]=a,t[22]=o,t[23]=v,t[24]=y):y=t[24],y};vq.displayName=`ActionBarMorePrimitive.Root`;var yq=zK(Nl),bq=zK(Fl),xq=zK(Rl),Sq=zK(Ul),Cq=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeActionBarMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=_q(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(yq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});Cq.displayName=`ActionBarMorePrimitive.Trigger`;var wq=Z((e,t)=>{let n=J(14),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({__scopeActionBarMore:r,portalProps:i,sideOffset:o,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let s=o===void 0?4:o,c=_q(r),l;n[5]!==t||n[6]!==a||n[7]!==c||n[8]!==s?(l=(0,b.jsx)(bq,{...c,...a,ref:t,sideOffset:s}),n[5]=t,n[6]=a,n[7]=c,n[8]=s,n[9]=l):l=n[9];let u;return n[10]!==i||n[11]!==c||n[12]!==l?(u=(0,b.jsx)(Pl,{...c,...i,children:l}),n[10]=i,n[11]=c,n[12]=l,n[13]=u):u=n[13],u});wq.displayName=`ActionBarMorePrimitive.Content`;var Tq=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeActionBarMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=_q(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(xq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});Tq.displayName=`ActionBarMorePrimitive.Item`;var Eq=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeActionBarMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=_q(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(Sq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});Eq.displayName=`ActionBarMorePrimitive.Separator`;var Dq=FK({Content:()=>wq,Item:()=>Tq,Root:()=>vq,Separator:()=>Eq,Trigger:()=>Cq}),Oq=Z((e,t)=>{let n=J(3),r;return n[0]!==e||n[1]!==t?(r=(0,b.jsx)(VK.div,{...e,ref:t}),n[0]=e,n[1]=t,n[2]=r):r=n[2],r});Oq.displayName=`AttachmentPrimitive.Root`;var kq=Z((e,t)=>{let n=J(4),r=$(Aq),i=e.children??r,a;return n[0]!==e||n[1]!==t||n[2]!==i?(a=(0,b.jsx)(VK.div,{...e,ref:t,children:i}),n[0]=e,n[1]=t,n[2]=i,n[3]=a):a=n[3],a});kq.displayName=`AttachmentPrimitive.unstable_Thumb`;function Aq(e){let t=e.attachment.name,n=t.lastIndexOf(`.`);return n>0&&n<t.length-1?`.${t.slice(n+1)}`:e.attachment.type}var jq=()=>{let e=J(2),t=$(Mq),n;return e[0]===t?n=e[1]:(n=(0,b.jsx)(b.Fragment,{children:t}),e[0]=t,e[1]=n),n};jq.displayName=`AttachmentPrimitive.Name`;function Mq(e){return e.attachment.name}var Nq=$K(`AttachmentPrimitive.Remove`,()=>{let e=J(2),t=Q(),n;return e[0]===t.attachment?n=e[1]:(n=()=>{t.attachment.remove()},e[0]=t.attachment,e[1]=n),n}),Pq=FK({Name:()=>jq,Remove:()=>Nq,Root:()=>Oq,unstable_Thumb:()=>kq}),Fq=$K(`BranchPickerPrimitive.Next`,()=>{let{disabled:e,next:t}=QG();return e?null:t}),Iq=$K(`BranchPickerPrimitive.Previous`,()=>{let{disabled:e,previous:t}=$G();return e?null:t}),Lq=()=>$(zq),Rq=()=>{let e=J(2),t=Lq(),n;return e[0]===t?n=e[1]:(n=(0,b.jsx)(b.Fragment,{children:t}),e[0]=t,e[1]=n),n};Rq.displayName=`BranchPickerPrimitive.Count`;function zq(e){return e.message.branchCount}var Bq=()=>$(Hq),Vq=()=>{let e=J(2),t=Bq(),n;return e[0]===t?n=e[1]:(n=(0,b.jsx)(b.Fragment,{children:t}),e[0]=t,e[1]=n),n};Vq.displayName=`BranchPickerPrimitive.Number`;function Hq(e){return e.message.branchNumber}var Uq=Z((e,t)=>{let n=J(11),r,i;n[0]===e?(r=n[1],i=n[2]):({hideWhenSingleBranch:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a;n[3]===r?a=n[4]:(a=e=>!r||e.message.branchCount>=2,n[3]=r,n[4]=a);let o;n[5]!==t||n[6]!==i?(o=(0,b.jsx)(VK.div,{...i,ref:t}),n[5]=t,n[6]=i,n[7]=o):o=n[7];let s;return n[8]!==a||n[9]!==o?(s=(0,b.jsx)(LL,{condition:a,children:o}),n[8]=a,n[9]=o,n[10]=s):s=n[10],s});Uq.displayName=`BranchPickerPrimitive.Root`;var Wq=FK({Count:()=>Rq,Next:()=>Fq,Number:()=>Vq,Previous:()=>Iq,Root:()=>Uq}),Gq=kN(null),Kq=()=>jN(Gq),qq=e=>{let t=J(8),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=new Map,t[0]=r):r=t[0];let i=Y(r),a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=[],t[1]=a):a=t[1];let o=Y(a),s;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(s=()=>{let e=Array.from(i.current.entries());e.sort(Jq),o.current=e.map(Yq)},t[2]=s):s=t[2];let c=s,l;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(l=(e,t)=>{let n=t?.priority??0;return i.current.set(e,n),c(),()=>{i.current.delete(e),c()}},t[3]=l):l=t[3];let u=l,d;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(d=()=>o.current,t[4]=d):d=t[4];let f=d,p;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(p={register:u,getPlugins:f},t[5]=p):p=t[5];let m=p,h;return t[6]===n?h=t[7]:(h=(0,b.jsx)(Gq.Provider,{value:m,children:n}),t[6]=n,t[7]=h),h};function Jq(e,t){return t[1]-e[1]}function Yq(e){let[t]=e;return t}var Xq=kN(null),Zq=kN(null),Qq=()=>{let e=jN(Xq);if(!e)throw Error(`useTriggerPopoverRootContext must be used within ComposerPrimitive.TriggerPopoverRoot`);return e},$q=()=>jN(Xq),eJ=()=>{let e=jN(Zq);if(!e)throw Error(`useTriggerPopoverAriaPublish must be used within ComposerPrimitive.TriggerPopoverRoot`);return e},tJ=()=>{let e=Qq();return yN(e.subscribe,e.getTriggers,e.getTriggers)},nJ=new Map,rJ=()=>()=>{},iJ=()=>nJ,aJ=()=>{let e=$q();return yN(e?e.subscribe:rJ,e?e.getTriggers:iJ,e?e.getTriggers:iJ)},oJ=()=>null,sJ=()=>{let e=$q();return yN(e?e.subscribeAria:rJ,e?e.getActiveAria:oJ,e?e.getActiveAria:oJ)};function cJ(){let e=J(4),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=new Set,e[0]=t):t=e[0];let n=Y(t),r;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=()=>{for(let e of n.current)e()},e[1]=r):r=e[1];let i=r,a;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(a=e=>(n.current.add(e),()=>{n.current.delete(e)}),e[2]=a):a=e[2];let o=a,s;return e[3]===Symbol.for(`react.memo_cache_sentinel`)?(s={notify:i,subscribe:o},e[3]=s):s=e[3],s}var lJ=e=>{let t=J(21),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=new Map,t[0]=r):r=t[0];let i=Y(r),a;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a=new Set,t[1]=a):a=t[1];let o=Y(a),{notify:s,subscribe:c}=cJ(),l;t[2]===s?l=t[3]:(l=e=>{let{char:t}=e;if(i.current.has(t))return dJ;let n=new Map(i.current);n.set(t,e),i.current=n,s();for(let t of o.current)t.added(e);return()=>{let e=new Map(i.current);e.delete(t),i.current=e,s();for(let e of o.current)e.removed(t)}},t[2]=s,t[3]=l);let u=l,d;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(d=()=>i.current,t[4]=d):d=t[4];let f=d,p;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(p=e=>(o.current.add(e),()=>{o.current.delete(e)}),t[5]=p):p=t[5];let m=p,h=Y(null),g=Y(null),{notify:_,subscribe:v}=cJ(),y;t[6]===_?y=t[7]:(y=(e,t)=>{if(t===null){if(g.current!==e)return;h.current=null,g.current=null,_();return}let n=h.current;(g.current!==e||n===null||n.popoverId!==t.popoverId||n.highlightedItemId!==t.highlightedItemId)&&(h.current=t,g.current=e,_())},t[6]=_,t[7]=y);let x=y,S;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(S=()=>h.current,t[8]=S):S=t[8];let C=S,w;t[9]!==u||t[10]!==c||t[11]!==v?(w={register:u,getTriggers:f,subscribe:c,subscribeLifecycle:m,getActiveAria:C,subscribeAria:v},t[9]=u,t[10]=c,t[11]=v,t[12]=w):w=t[12];let T=w,E;t[13]===x?E=t[14]:(E={setActiveAria:x},t[13]=x,t[14]=E);let D=E,O;t[15]!==D||t[16]!==n?(O=(0,b.jsx)(Zq.Provider,{value:D,children:n}),t[15]=D,t[16]=n,t[17]=O):O=t[17];let k;return t[18]!==O||t[19]!==T?(k=(0,b.jsx)(Xq.Provider,{value:T,children:O}),t[18]=O,t[19]=T,t[20]=k):k=t[20],k},uJ=e=>{let t=J(4),{children:n}=e;if(Kq()){let e;return t[0]===n?e=t[1]:(e=(0,b.jsx)(lJ,{children:n}),t[0]=n,t[1]=e),e}let r;return t[2]===n?r=t[3]:(r=(0,b.jsx)(qq,{children:(0,b.jsx)(lJ,{children:n})}),t[2]=n,t[3]=r),r};uJ.displayName=`ComposerPrimitive.TriggerPopoverRoot`;function dJ(){}var fJ=/\s/u;function pJ(e,t,n,r){if(r===null)return null;let{query:i,offset:a,endOffset:o}=r;return a<0||a+t.length>n||!e.startsWith(t,a)||o<a+t.length||o>e.length?null:{query:i,offset:a,endOffset:o}}function mJ(e,t,n,r){if(r)return pJ(e,t,n,r(e,t,n));let i=e.slice(0,n);for(let e=i.length-1;e>=0;e--){let r=i[e];if(fJ.test(r))return null;if(i.startsWith(t,e)){if(e>0&&!fJ.test(i[e-1]))continue;return{query:i.slice(e+t.length),offset:e,endOffset:n}}}return null}var hJ=MN(e=>{let t=J(8),{text:n,triggerChar:r,matcher:i}=e,[a,o]=pN(n.length),s=Math.min(a,n.length),c;t[0]!==i||t[1]!==s||t[2]!==n||t[3]!==r?(c=mJ(n,r,s,i),t[0]=i,t[1]=s,t[2]=n,t[3]=r,t[4]=c):c=t[4];let l=c,u=l?.query??``,d;return t[5]!==u||t[6]!==l?(d={trigger:l,query:u,setCursorPosition:o},t[5]=u,t[6]=l,t[7]=d):d=t[7],d});function gJ(e){return`type`in e}var _J=MN(e=>{let t=J(22),{navigableList:n,isSearchMode:r,activeCategoryId:i,query:a,popoverId:o,open:s,selectItem:c,selectCategory:l,goBack:u,close:d}=e,[f,p]=pN(0),m;t[0]!==i||t[1]!==r||t[2]!==n?(m={navigableList:n,isSearchMode:r,activeCategoryId:i},t[0]=i,t[1]=r,t[2]=n,t[3]=m):m=t[3];let[h,g]=pN(m);(h.navigableList!==n||h.isSearchMode!==r||h.activeCategoryId!==i)&&(g({navigableList:n,isSearchMode:r,activeCategoryId:i}),p(0));let _;t[4]!==f||t[5]!==n.length?(_=e=>{e<0||e>=n.length||e!==f&&p(e)},t[4]=f,t[5]=n.length,t[6]=_):_=t[6];let v=vN(_),y;t[7]!==i||t[8]!==d||t[9]!==u||t[10]!==f||t[11]!==n||t[12]!==s||t[13]!==a||t[14]!==l||t[15]!==c?(y=e=>{if(!s)return!1;switch(e.key){case`ArrowDown`:return e.preventDefault(),p(e=>{let t=n.length;return t===0?0:e<t-1?e+1:0}),!0;case`ArrowUp`:return e.preventDefault(),p(e=>{let t=n.length;return t===0?0:e>0?e-1:t-1}),!0;case`Enter`:case`Tab`:{if(e.shiftKey)return!1;e.preventDefault();let t=n[f];return t&&(gJ(t)?c(t):l(t.id)),!0}case`Escape`:return e.preventDefault(),d(),!0;case`Backspace`:return i&&a===``?(e.preventDefault(),u(),!0):!1;default:return!1}},t[7]=i,t[8]=d,t[9]=u,t[10]=f,t[11]=n,t[12]=s,t[13]=a,t[14]=l,t[15]=c,t[16]=y):y=t[16];let b=vN(y),x=n[f],S=s&&x?`${o}-option-${x.id}`:void 0,C;return t[17]!==b||t[18]!==v||t[19]!==f||t[20]!==S?(C={highlightedIndex:f,highlightedItemId:S,highlightIndex:v,handleKeyDown:b},t[17]=b,t[18]=v,t[19]=f,t[20]=S,t[21]=C):C=t[21],C});function vJ(e,t){return!t||e.id.toLowerCase().includes(t)||e.label.toLowerCase().includes(t)||(e.description?.toLowerCase().includes(t)??!1)}var yJ=MN(e=>{let t=J(35),{adapter:n,query:r,open:i}=e,[a,o]=pN(null),[s,c]=pN(i);s!==i&&(c(i),i||o(null));let l;bb0:{if(!i||!n){let e;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[0]=e):e=t[0],l=e;break bb0}let e;t[1]===n?e=t[2]:(e=n.categories(),t[1]=n,t[2]=e),l=e}let u=l,d=i?a:null,f;bb1:{if(!d||!n){let e;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[3]=e):e=t[3],f=e;break bb1}let e;t[4]!==n||t[5]!==d?(e=n.categoryItems(d),t[4]=n,t[5]=d,t[6]=e):e=t[6],f=e}let p=f,m;bb2:{if(!i||!n||d){m=null;break bb2}if(!r&&u.length>0){m=null;break bb2}if(n.search){let e;t[7]!==n||t[8]!==r?(e=n.search(r),t[7]=n,t[8]=r,t[9]=e):e=t[9],m=e;break bb2}let e;if(t[10]!==n||t[11]!==u||t[12]!==r){e=[];let i=r.toLowerCase();for(let t of u)for(let r of n.categoryItems(t.id))vJ(r,i)&&e.push(r);t[10]=n,t[11]=u,t[12]=r,t[13]=e}else e=t[13];m=e}let h=m,g=h!==null,_;bb3:{if(g){let e;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[14]=e):e=t[14],_=e;break bb3}if(!r){_=u;break bb3}let e;if(t[15]!==u||t[16]!==r){let n=r.toLowerCase();e=u.filter(e=>e.label.toLowerCase().includes(n)),t[15]=u,t[16]=r,t[17]=e}else e=t[17];_=e}let v=_,y;bb4:{if(g){let e;t[18]===h?e=t[19]:(e=h??[],t[18]=h,t[19]=e),y=e;break bb4}if(!r){y=p;break bb4}let e;if(t[20]!==p||t[21]!==r){let n=r.toLowerCase();e=p.filter(e=>vJ(e,n)),t[20]=p,t[21]=r,t[22]=e}else e=t[22];y=e}let b=y,x;bb5:{if(g){let e;t[23]===h?e=t[24]:(e=h??[],t[23]=h,t[24]=e),x=e;break bb5}if(d){x=b;break bb5}x=v}let S=x,C;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(C=e=>{o(e)},t[25]=C):C=t[25];let w=vN(C),T;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(T=()=>{o(null)},t[26]=T):T=t[26];let E=vN(T),D;return t[27]!==d||t[28]!==v||t[29]!==b||t[30]!==E||t[31]!==g||t[32]!==S||t[33]!==w?(D={categories:v,items:b,isSearchMode:g,activeCategoryId:d,navigableList:S,selectCategory:w,goBack:E},t[27]=d,t[28]=v,t[29]=b,t[30]=E,t[31]=g,t[32]=S,t[33]=w,t[34]=D):D=t[34],D}),bJ=MN(e=>{let t=J(15),{behavior:n,trigger:r,aui:i,setCursorPosition:a,onSelected:o}=e,s=Y(null),c;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(c=e=>(s.current=e,()=>{s.current===e&&(s.current=null)}),t[0]=c):c=t[0];let l=vN(c),u;t[1]!==i||t[2]!==n||t[3]!==o||t[4]!==a||t[5]!==r?(u=e=>{if(!r||!n)return;if(s.current?.(e)){o();return}let t=i.composer.getState().text,c=t.slice(0,r.offset),l=t.slice(r.endOffset),u=()=>{let t=n.formatter.serialize(e);i.composer.setText(c+t+(l.startsWith(` `)?l:` ${l}`)),a(c.length+t.length+1)};n.kind===`directive`?(u(),n.onInserted?.(e)):(n.removeOnExecute?(i.composer.setText(c+(l.startsWith(` `)?l.slice(1):l)),a(c.length)):u(),n.onExecute(e)),o()},t[1]=i,t[2]=n,t[3]=o,t[4]=a,t[5]=r,t[6]=u):u=t[6];let d=vN(u),f;t[7]!==o||t[8]!==a||t[9]!==r?(f=()=>{o(),r&&a(r.offset)},t[7]=o,t[8]=a,t[9]=r,t[10]=f):f=t[10];let p=vN(f),m;return t[11]!==p||t[12]!==l||t[13]!==d?(m={selectItem:d,close:p,registerSelectItemOverride:l},t[11]=p,t[12]=l,t[13]=d,t[14]=m):m=t[14],m}),xJ=MN(e=>{let t=J(47),{adapter:n,text:r,triggerChar:i,matcher:a,behavior:o,aui:s,popoverId:c,isLoading:l}=e,u;t[0]!==a||t[1]!==r||t[2]!==i?(u=hJ({text:r,triggerChar:i,matcher:a}),t[0]=a,t[1]=r,t[2]=i,t[3]=u):u=t[3];let d=bP(u),f=d.trigger!==null&&n!==void 0&&o!==void 0,p;t[4]!==n||t[5]!==d.query||t[6]!==f?(p=yJ({adapter:n,query:d.query,open:f}),t[4]=n,t[5]=d.query,t[6]=f,t[7]=p):p=t[7];let m=bP(p),h;t[8]===m?h=t[9]:(h=()=>{m.goBack()},t[8]=m,t[9]=h);let g=vN(h),_;t[10]!==s||t[11]!==o||t[12]!==d.setCursorPosition||t[13]!==d.trigger||t[14]!==g||t[15]!==i?(_=bJ({behavior:o,trigger:d.trigger,aui:s,triggerChar:i,setCursorPosition:d.setCursorPosition,onSelected:g}),t[10]=s,t[11]=o,t[12]=d.setCursorPosition,t[13]=d.trigger,t[14]=g,t[15]=i,t[16]=_):_=t[16];let v=bP(_),y;t[17]!==d.query||t[18]!==m.activeCategoryId||t[19]!==m.goBack||t[20]!==m.isSearchMode||t[21]!==m.navigableList||t[22]!==m.selectCategory||t[23]!==f||t[24]!==c||t[25]!==v.close||t[26]!==v.selectItem?(y=_J({navigableList:m.navigableList,isSearchMode:m.isSearchMode,activeCategoryId:m.activeCategoryId,query:d.query,popoverId:c,open:f,selectItem:v.selectItem,selectCategory:m.selectCategory,goBack:m.goBack,close:v.close}),t[17]=d.query,t[18]=m.activeCategoryId,t[19]=m.goBack,t[20]=m.isSearchMode,t[21]=m.navigableList,t[22]=m.selectCategory,t[23]=f,t[24]=c,t[25]=v.close,t[26]=v.selectItem,t[27]=y):y=t[27];let b=bP(y),x;return t[28]!==d.query||t[29]!==d.setCursorPosition||t[30]!==l||t[31]!==b.handleKeyDown||t[32]!==b.highlightIndex||t[33]!==b.highlightedIndex||t[34]!==b.highlightedItemId||t[35]!==m.activeCategoryId||t[36]!==m.categories||t[37]!==m.goBack||t[38]!==m.isSearchMode||t[39]!==m.items||t[40]!==m.selectCategory||t[41]!==f||t[42]!==c||t[43]!==v.close||t[44]!==v.registerSelectItemOverride||t[45]!==v.selectItem?(x={open:f,query:d.query,activeCategoryId:m.activeCategoryId,categories:m.categories,items:m.items,highlightedIndex:b.highlightedIndex,isSearchMode:m.isSearchMode,isLoading:l,popoverId:c,highlightedItemId:b.highlightedItemId,selectCategory:m.selectCategory,goBack:m.goBack,selectItem:v.selectItem,close:v.close,highlightIndex:b.highlightIndex,handleKeyDown:b.handleKeyDown,setCursorPosition:d.setCursorPosition,registerSelectItemOverride:v.registerSelectItemOverride},t[28]=d.query,t[29]=d.setCursorPosition,t[30]=l,t[31]=b.handleKeyDown,t[32]=b.highlightIndex,t[33]=b.highlightedIndex,t[34]=b.highlightedItemId,t[35]=m.activeCategoryId,t[36]=m.categories,t[37]=m.goBack,t[38]=m.isSearchMode,t[39]=m.items,t[40]=m.selectCategory,t[41]=f,t[42]=c,t[43]=v.close,t[44]=v.registerSelectItemOverride,t[45]=v.selectItem,t[46]=x):x=t[46],x}),SJ=kN(null),CJ=()=>{let e=jN(SJ);if(!e)throw Error(`useTriggerPopoverScopeContext must be used within ComposerPrimitive.TriggerPopover`);return e},wJ=()=>jN(SJ),TJ=kN(null),EJ=()=>{let e=jN(TJ);if(!e)throw Error(`TriggerPopover.Directive / TriggerPopover.Action must be rendered inside ComposerPrimitive.TriggerPopover`);return e},DJ=Z((e,t)=>{let n=J(69),r,i,a,o,s,c,l;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],s=n[5],c=n[6],l=n[7]):({char:a,matcher:s,adapter:r,isLoading:l,"aria-label":i,children:o,...c}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=s,n[6]=c,n[7]=l);let u=l!==void 0&&l,d=Q(),f=$(OJ),p=SN(),m=Y(s),h;n[8]===s?h=n[9]:(h=()=>{m.current=s},n[8]=s,n[9]=h),X(h);let g;n[10]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>(e,t,n)=>m.current(e,t,n),n[10]=g):g=n[10];let[_]=pN(g),v=s!==void 0,y=Y(null),[x,S]=pN(null),C=Y(0),w;n[11]===a?w=n[12]:(w=e=>(C.current+=1,y.current=e,S(e),()=>{C.current=Math.max(0,C.current-1),y.current===e&&(y.current=null,S(null))}),n[11]=a,n[12]=w);let T=w,E;n[13]===T?E=n[14]:(E={register:T},n[13]=T,n[14]=E);let D=E,O=x??void 0,k;n[15]!==r||n[16]!==d||n[17]!==a||n[18]!==u||n[19]!==s||n[20]!==p||n[21]!==O||n[22]!==f?(k=xJ({adapter:r,text:f,triggerChar:a,matcher:s,behavior:O,aui:d,popoverId:p,isLoading:u}),n[15]=r,n[16]=d,n[17]=a,n[18]=u,n[19]=s,n[20]=p,n[21]=O,n[22]=f,n[23]=k):k=n[23];let A=bP(k),j;n[24]===A?j=n[25]:(j=()=>A,n[24]=A,n[25]=j);let M=vN(j),N=Qq(),ee;n[26]!==x||n[27]!==a||n[28]!==M||n[29]!==v||n[30]!==_||n[31]!==N?(ee=()=>N.register({char:a,...v?{matcher:_}:{},...x?{behavior:x}:{},resource:M()}),n[26]=x,n[27]=a,n[28]=M,n[29]=v,n[30]=_,n[31]=N,n[32]=ee):ee=n[32];let te;n[33]!==x||n[34]!==a||n[35]!==v||n[36]!==N?(te=[N,a,v,x],n[33]=x,n[34]=a,n[35]=v,n[36]=N,n[37]=te):te=n[37],X(ee,te);let ne=Kq(),re;n[38]!==M||n[39]!==ne?(re=()=>{if(ne)return ne.register(M())},n[38]=M,n[39]=ne,n[40]=re):re=n[40];let ie;n[41]===ne?ie=n[42]:(ie=[ne],n[41]=ne,n[42]=ie),X(re,ie);let ae=x!==null&&A.open,oe=eJ(),se,ce;n[43]!==oe||n[44]!==a||n[45]!==ae?(se=()=>{if(ae)return()=>{oe.setActiveAria(a,null)}},ce=[oe,a,ae],n[43]=oe,n[44]=a,n[45]=ae,n[46]=se,n[47]=ce):(se=n[46],ce=n[47]),X(se,ce);let le,ue;n[48]!==oe||n[49]!==a||n[50]!==ae||n[51]!==p||n[52]!==A.highlightedItemId?(le=()=>{ae&&oe.setActiveAria(a,{popoverId:p,highlightedItemId:A.highlightedItemId})},ue=[oe,a,p,ae,A.highlightedItemId],n[48]=oe,n[49]=a,n[50]=ae,n[51]=p,n[52]=A.highlightedItemId,n[53]=le,n[54]=ue):(le=n[53],ue=n[54]),X(le,ue);let de;n[55]!==i||n[56]!==o||n[57]!==t||n[58]!==ae||n[59]!==p||n[60]!==c||n[61]!==A.highlightedItemId?(de=ae?(0,b.jsx)(VK.div,{role:`listbox`,id:p,"aria-label":i??`Suggestions`,"aria-activedescendant":A.highlightedItemId,"data-state":`open`,...c,ref:t,children:o}):o,n[55]=i,n[56]=o,n[57]=t,n[58]=ae,n[59]=p,n[60]=c,n[61]=A.highlightedItemId,n[62]=de):de=n[62];let P;n[63]!==A||n[64]!==de?(P=(0,b.jsx)(SJ.Provider,{value:A,children:de}),n[63]=A,n[64]=de,n[65]=P):P=n[65];let fe;return n[66]!==D||n[67]!==P?(fe=(0,b.jsx)(TJ.Provider,{value:D,children:P}),n[66]=D,n[67]=P,n[68]=fe):fe=n[68],fe});DJ.displayName=`ComposerPrimitive.TriggerPopover`;function OJ(e){return e.composer.text}var kJ=()=>{let e=J(2),{disabled:t,send:n}=AG(),r;return e[0]===n?r=e[1]:(r=()=>n(),e[0]=n,e[1]=r),t?null:r},AJ=$K(`ComposerPrimitive.Send`,kJ),jJ=kN(null),MJ=()=>jN(jJ),NJ=`[contenteditable]:not([contenteditable='false'])`,PJ=`textarea:not(:disabled), ${NJ}`,FJ=[`a`,`audio[controls]`,`button`,`details`,`embed`,`iframe`,`input`,`label`,`select`,`summary`,`textarea`,`video[controls]`,NJ,`[tabindex]`].join(`, `),IJ=Z((e,t)=>{let n=J(24),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({onSubmit:a,onMouseDown:i,compact:r,...o}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let s=kJ(),[c,l]=pN(!1),u;n[5]===Symbol.for(`react.memo_cache_sentinel`)?(u={setMultiline:l},n[5]=u):u=n[5];let d=u,f;n[6]===r?f=n[7]:(f=e=>r?e.composer.attachments.length===0&&e.composer.quote==null&&e.composer.queue.length===0&&e.composer.dictation==null&&!e.composer.text.includes(`
93
+ `):!1,n[6]=r,n[7]=f);let p=$(f)&&!c,m;n[8]===s?m=n[9]:(m=e=>{e.preventDefault(),s&&s()},n[8]=s,n[9]=m);let h=m,g=LJ,_=r?d:null,v=p?``:void 0,y;n[10]!==h||n[11]!==a?(y=P(a,h),n[10]=h,n[11]=a,n[12]=y):y=n[12];let x;n[13]===i?x=n[14]:(x=P(i,g),n[13]=i,n[14]=x);let S;n[15]!==t||n[16]!==o||n[17]!==v||n[18]!==y||n[19]!==x?(S=(0,b.jsx)(VK.form,{...o,"data-compact":v,ref:t,onSubmit:y,onMouseDown:x}),n[15]=t,n[16]=o,n[17]=v,n[18]=y,n[19]=x,n[20]=S):S=n[20];let C;return n[21]!==_||n[22]!==S?(C=(0,b.jsx)(jJ.Provider,{value:_,children:S}),n[21]=_,n[22]=S,n[23]=C):C=n[23],C});IJ.displayName=`ComposerPrimitive.Root`;function LJ(e){if(e.button!==0)return;let t=e.target;if(!(t instanceof Element)||!e.currentTarget.contains(t))return;let n=t.closest(FJ);if(n&&e.currentTarget.contains(n))return;let r=e.currentTarget.querySelector(PJ);r&&(e.preventDefault(),r.focus())}var RJ=e=>{let t=J(4),n=dt(e),r=pK(zJ),i,a;t[0]!==n||t[1]!==r?(i=()=>r(n),a=[r,n],t[0]=n,t[1]=r,t[2]=i,t[3]=a):(i=t[2],a=t[3]),X(i,a)};function zJ(e){return e.onScrollToBottom}var BJ=()=>!1,VJ=()=>{},HJ=e=>{let t=J(4),n;t[0]===e?n=t[1]:(n=t=>{if(typeof window>`u`||e===null||!window.matchMedia)return VJ;let n=window.matchMedia(e);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)},t[0]=e,t[1]=n);let r=n,i;return t[2]===e?i=t[3]:(i=()=>typeof window>`u`||e===null||!window.matchMedia?!1:window.matchMedia(e).matches,t[2]=e,t[3]=i),yN(r,i,BJ)};function UJ(){return $(WJ)}function WJ(e){return e.composer.isEditing?e.composer.text:``}function GJ(e){return!!$(KJ)||!!e}function KJ(e){return e.thread.isDisabled||e.composer.dictation?.inputDisabled}function qJ(){let e=J(4),t=sJ();if(!t){let t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t={},e[0]=t):t=e[0],t}let n;return e[1]!==t.highlightedItemId||e[2]!==t.popoverId?(n={"aria-controls":t.popoverId,"aria-expanded":!0,"aria-haspopup":`listbox`,"aria-activedescendant":t.highlightedItemId},e[1]=t.highlightedItemId,e[2]=t.popoverId,e[3]=n):n=e[3],n}function JJ(){return JJ=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},JJ.apply(null,arguments)}function YJ(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var XJ=y.useLayoutEffect,ZJ=function(e){var t=y.useRef(e);return XJ(function(){t.current=e}),t},QJ=function(e,t){if(typeof e==`function`){e(t);return}e.current=t},$J=function(e,t){var n=y.useRef();return y.useCallback(function(r){e.current=r,n.current&&QJ(n.current,null),n.current=t,t&&QJ(t,r)},[t])},eY={"min-height":`0`,"max-height":`none`,height:`0`,visibility:`hidden`,overflow:`hidden`,position:`absolute`,"z-index":`-1000`,top:`0`,right:`0`,display:`block`},tY=function(e){Object.keys(eY).forEach(function(t){e.style.setProperty(t,eY[t],`important`)})},nY=null,rY=function(e,t){var n=e.scrollHeight;return t.sizingStyle.boxSizing===`border-box`?n+t.borderSize:n-t.paddingSize};function iY(e,t,n,r){n===void 0&&(n=1),r===void 0&&(r=1/0),nY||(nY=document.createElement(`textarea`),nY.setAttribute(`tabindex`,`-1`),nY.setAttribute(`aria-hidden`,`true`),tY(nY)),nY.parentNode===null&&document.body.appendChild(nY);var i=e.paddingSize,a=e.borderSize,o=e.sizingStyle,s=o.boxSizing;Object.keys(o).forEach(function(e){var t=e;nY.style[t]=o[t]}),tY(nY),nY.value=t;var c=rY(nY,e);nY.value=t,c=rY(nY,e),nY.value=`x`;var l=nY.scrollHeight-i,u=l*n;s===`border-box`&&(u=u+i+a),c=Math.max(u,c);var d=l*r;return s===`border-box`&&(d=d+i+a),c=Math.min(d,c),[c,l]}var aY=function(){},oY=function(e,t){return e.reduce(function(e,n){return e[n]=t[n],e},{})},sY=[`borderBottomWidth`,`borderLeftWidth`,`borderRightWidth`,`borderTopWidth`,`boxSizing`,`fontFamily`,`fontSize`,`fontStyle`,`fontWeight`,`letterSpacing`,`lineHeight`,`paddingBottom`,`paddingLeft`,`paddingRight`,`paddingTop`,`tabSize`,`textIndent`,`textRendering`,`textTransform`,`width`,`wordBreak`,`wordSpacing`,`scrollbarGutter`],cY=!!document.documentElement.currentStyle,lY=function(e){var t=window.getComputedStyle(e);if(t===null)return null;var n=oY(sY,t),r=n.boxSizing;return r===``?null:(cY&&r===`border-box`&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+`px`),{sizingStyle:n,paddingSize:parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),borderSize:parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth)})};function uY(e,t,n){var r=ZJ(n);y.useLayoutEffect(function(){var n=function(e){return r.current(e)};if(e)return e.addEventListener(t,n),function(){return e.removeEventListener(t,n)}},[])}var dY=function(e,t){uY(document.body,`reset`,function(n){e.current.form===n.target&&t(n)})},fY=function(e){uY(window,`resize`,e)},pY=function(e){uY(document.fonts,`loadingdone`,e)},mY=[`cacheMeasurements`,`maxRows`,`minRows`,`onChange`,`onHeightChange`],hY=y.forwardRef(function(e,t){var n=e.cacheMeasurements,r=e.maxRows,i=e.minRows,a=e.onChange,o=a===void 0?aY:a,s=e.onHeightChange,c=s===void 0?aY:s,l=YJ(e,mY),u=l.value!==void 0,d=y.useRef(null),f=$J(d,t),p=y.useRef(0),m=y.useRef(),h=function(){var e=d.current,t=n&&m.current?m.current:lY(e);if(t){m.current=t;var a=iY(t,e.value||e.placeholder||`x`,i,r),o=a[0],s=a[1];p.current!==o&&(p.current=o,e.style.setProperty(`height`,o+`px`,`important`),c(o,{rowHeight:s}))}};return y.useLayoutEffect(h),dY(d,function(){if(!u){var e=d.current.value;requestAnimationFrame(function(){var t=d.current;t&&e!==t.value&&h()})}}),fY(h),pY(h),y.createElement(`textarea`,JJ({},l,{onChange:function(e){u||h(),o(e)},ref:f}))}),gY=`(pointer: coarse) and (not (any-pointer: fine))`,_Y=Z(({autoFocus:e=!1,asChild:t,render:n,disabled:r,onChange:i,onKeyDown:a,onPaste:o,onSelect:c,submitOnEnter:l,submitMode:d,cancelOnEscape:f=!0,unstable_focusOnRunStart:p=!0,unstable_focusOnScrollToBottom:m=!0,unstable_focusOnThreadSwitched:h=!0,unstable_insertNewlineOnTouchEnter:g=!1,addAttachmentOnPaste:_=!0,onHeightChange:v,...y},x)=>{let S=Q(),C=Kq(),w=MJ(),T=d??(l===!1?`none`:`enter`),E=HJ(g?gY:null),D=g&&E&&T===`enter`?`none`:T,O=UJ(),k=GJ(r),A=Y(null),j=u(x,A),M=Y(!1);MK(e=>{if(!A.current?.contains(e.target)||e.isComposing)return;if(C){for(let t of C.getPlugins())if(t.handleKeyDown(e))return}if(!f)return;let t=S.composer;t.getState().canCancel&&(t.cancel(),e.preventDefault())});let N=e=>{if(!k&&!e.nativeEvent.isComposing){if(C){for(let t of C.getPlugins())if(t.handleKeyDown(e))return}if(e.key===`Enter`){let t=S.thread.getState(),n=t.capabilities.queue;if(e.shiftKey&&(e.ctrlKey||e.metaKey)&&n&&T!==`none`&&S.composer.getState().canSend){e.preventDefault(),S.composer.send({steer:!0});return}if(e.shiftKey||t.isRunning&&!n)return;let r=!1;D===`ctrlEnter`?r=e.ctrlKey||e.metaKey:D===`enter`&&(r=!0),r&&(e.preventDefault(),A.current?.closest(`form`)?.requestSubmit())}}},ee=async e=>{if(!_)return;let t=S.thread.getState().capabilities,n=Array.from(e.clipboardData?.files||[]);t.attachments&&n.length>0&&(e.preventDefault(),await Promise.all(n.map(async e=>{try{await S.composer.addAttachment(e)}catch{}})))},te=(e,t)=>{if(v?.(e,t),!w)return;let n=A.current;if(!n||n.value===``)return;let r=getComputedStyle(n),i=r.boxSizing===`border-box`?e-parseFloat(r.paddingTop)-parseFloat(r.paddingBottom)-parseFloat(r.borderTopWidth)-parseFloat(r.borderBottomWidth):e;Math.round(i/t.rowHeight)>1&&w.setMultiline(!0)},ne=e&&!k,re=gN(()=>{let e=A.current;e&&ne&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[ne]);X(()=>re(),[re]),RJ(()=>{S.composer.getState().type===`thread`&&m&&re()}),X(()=>{if(S.composer.getState().type===`thread`&&p)return S.on(`thread.runStart`,re)},[p,re,S]),X(()=>{if(S.composer.getState().type===`thread`&&h)return S.on(`threads.selectionChanged`,re)},[h,re,S]),X(()=>{O===``&&w?.setMultiline(!1)},[O,w]);let ie=qJ(),ae={name:`input`,value:O,...y,...ie,ref:j,disabled:k,onChange:P(i,e=>{if(!S.composer.getState().isEditing)return;let t=e.nativeEvent.isComposing===!0;M.current&&!t&&(M.current=!1);let n=t||M.current;if(GN(()=>{S.composer.setText(e.target.value)}),n)return;let r=e.target.selectionStart??e.target.value.length;if(C)for(let e of C.getPlugins())e.setCursorPosition(r)}),onKeyDown:P(a,N),onCompositionStart:P(y.onCompositionStart,()=>{M.current=!0}),onCompositionEnd:P(y.onCompositionEnd,e=>{if(M.current=!1,!S.composer.getState().isEditing)return;let t=e.target;GN(()=>{S.composer.setText(t.value)});let n=t.selectionStart??t.value.length;if(C)for(let e of C.getPlugins())e.setCursorPosition(n)}),onSelect:P(c,e=>{if(M.current)return;let t=e.target,n=t.selectionStart??t.value.length;if(C)for(let e of C.getPlugins())e.setCursorPosition(n)}),onPaste:P(o,ee),...w?{onHeightChange:te}:v===void 0?{}:{onHeightChange:v}};if(n&&ON(n))return RK(n,y.children,ae);let oe=t?s:hY;return(0,b.jsx)(oe,{...ae})});_Y.displayName=`ComposerPrimitive.Input`;var vY=$K(`ComposerPrimitive.Cancel`,()=>{let{disabled:e,cancel:t}=jG();return e?null:t}),yY=$K(`ComposerPrimitive.AddAttachment`,e=>{let t=J(6),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{multiple:r}=n,i=r===void 0||r,{disabled:a,addAttachment:o}=PG(),s=Q(),c;return t[2]!==o||t[3]!==s.composer||t[4]!==i?(c=()=>{let e=document.createElement(`input`);e.type=`file`,e.multiple=i,e.hidden=!0;let t=s.composer.getState().attachmentAccept;t!==`*`&&(e.accept=t),document.body.appendChild(e),e.onchange=async t=>{let n=t.target.files;if(!n)return;let r=Array.from(n,async e=>{try{await o(e)}catch{}});document.body.removeChild(e),await Promise.all(r)},e.oncancel=()=>{(!e.files||e.files.length===0)&&document.body.removeChild(e)},e.click()},t[2]=o,t[3]=s.composer,t[4]=i,t[5]=c):c=t[5],a?null:c},[`multiple`]),bY=Z(({disabled:e,asChild:t=!1,render:n,children:r,...i},a)=>{let[o,c]=pN(!1),l=Q(),u=gN(t=>{if(!e&&t.dataTransfer.types.includes(`Files`)){if(t.preventDefault(),!l.thread.getState().capabilities.attachments){t.dataTransfer.dropEffect=`none`;return}c(!0)}},[e,l]),d=gN(t=>{if(!e&&t.dataTransfer.types.includes(`Files`)){if(t.preventDefault(),!l.thread.getState().capabilities.attachments){t.dataTransfer.dropEffect=`none`;return}o||c(!0)}},[e,o,l]),f=gN(t=>{if(e)return;t.preventDefault();let n=t.relatedTarget;n&&t.currentTarget.contains(n)||c(!1)},[e]),p=gN(async t=>{if(e||(c(!1),!t.dataTransfer.types.includes(`Files`)))return;t.preventDefault();let n=Array.from(t.dataTransfer.files);l.thread.getState().capabilities.attachments&&n.length!==0&&await Promise.all(n.map(async e=>{try{await l.composer.addAttachment(e)}catch{}}))},[e,l]),m={...o?{"data-dragging":`true`}:null,...i,onDragEnterCapture:P(i.onDragEnterCapture,u),onDragOverCapture:P(i.onDragOverCapture,d),onDragLeaveCapture:P(i.onDragLeaveCapture,f),onDropCapture:P(i.onDropCapture,p),ref:a};if(n&&ON(n))return RK(n,r,m);let h=t?s:`div`;return(0,b.jsx)(h,{...m,children:r})});bY.displayName=`ComposerPrimitive.AttachmentDropzone`;var xY=$K(`ComposerPrimitive.Dictate`,()=>{let{disabled:e,startDictation:t}=MG();return e?null:t}),SY=$K(`ComposerPrimitive.StopDictation`,()=>{let e=J(2),t=Q(),n=$(CY),r;return e[0]===t.composer?r=e[1]:(r=()=>{t.composer.stopDictation()},e[0]=t.composer,e[1]=r),n?r:null});function CY(e){return e.composer.dictation!=null}var wY=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({children:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=$(TY);if(!a)return null;let o=r??a,s;return n[3]!==t||n[4]!==i||n[5]!==o?(s=(0,b.jsx)(VK.span,{...i,ref:t,children:o}),n[3]=t,n[4]=i,n[5]=o,n[6]=s):s=n[6],s});wY.displayName=`ComposerPrimitive.DictationTranscript`;function TY(e){return e.composer.dictation?.transcript}var EY=Z((e,t)=>{let n=J(3);if(!$(kY))return null;let r;return n[0]!==t||n[1]!==e?(r=(0,b.jsx)(VK.div,{...e,ref:t}),n[0]=t,n[1]=e,n[2]=r):r=n[2],r});EY.displayName=`ComposerPrimitive.Quote`;var DY=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({children:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=$(AY);if(!a)return null;let o=r??a,s;return n[3]!==t||n[4]!==i||n[5]!==o?(s=(0,b.jsx)(VK.span,{...i,ref:t,children:o}),n[3]=t,n[4]=i,n[5]=o,n[6]=s):s=n[6],s});DY.displayName=`ComposerPrimitive.QuoteText`;var OY=Z((e,t)=>{let n=J(12),r,i;n[0]===e?(r=n[1],i=n[2]):({onClick:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=Q(),o;n[3]===a?o=n[4]:(o=()=>{a.composer.setQuote(void 0)},n[3]=a,n[4]=o);let s=o,c;n[5]!==s||n[6]!==r?(c=P(r,s),n[5]=s,n[6]=r,n[7]=c):c=n[7];let l;return n[8]!==t||n[9]!==i||n[10]!==c?(l=(0,b.jsx)(VK.button,{type:`button`,...i,ref:t,onClick:c}),n[8]=t,n[9]=i,n[10]=c,n[11]=l):l=n[11],l});OY.displayName=`ComposerPrimitive.QuoteDismiss`;function kY(e){return e.composer.quote}function AY(e){return e.composer.quote?.text}var jY=Z((e,t)=>{let n=J(12),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({children:i,"aria-label":r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let{categories:o,activeCategoryId:s,isSearchMode:c,open:l}=CJ();if(!l||s||c)return null;let u=r??`Categories`,d;n[4]!==o||n[5]!==i?(d=i(o),n[4]=o,n[5]=i,n[6]=d):d=n[6];let f;return n[7]!==t||n[8]!==a||n[9]!==u||n[10]!==d?(f=(0,b.jsx)(VK.div,{role:`group`,"aria-label":u,...a,ref:t,children:d}),n[7]=t,n[8]=a,n[9]=u,n[10]=d,n[11]=f):f=n[11],f});jY.displayName=`ComposerPrimitive.TriggerPopoverCategories`;var MY=Z((e,t)=>{let n=J(30),r,i,a,o;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4]):({categoryId:r,onClick:i,onMouseMove:a,...o}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o);let{selectCategory:s,highlightIndex:c,categories:l,highlightedIndex:u,activeCategoryId:d,isSearchMode:f,popoverId:p}=CJ(),m;n[5]!==r||n[6]!==s?(m=()=>{s(r)},n[5]=r,n[6]=s,n[7]=m):m=n[7];let h=m,g;if(n[8]!==l||n[9]!==r){let e;n[11]===r?e=n[12]:(e=e=>e.id===r,n[11]=r,n[12]=e),g=l.findIndex(e),n[8]=l,n[9]=r,n[10]=g}else g=n[10];let _=g,v=!d&&!f&&_===u,y;n[13]!==_||n[14]!==c?(y=()=>{c(_)},n[13]=_,n[14]=c,n[15]=y):y=n[15];let x=y,S=`${p}-option-${r}`,C=v?``:void 0,w;n[16]!==h||n[17]!==i?(w=P(i,h),n[16]=h,n[17]=i,n[18]=w):w=n[18];let T;n[19]!==x||n[20]!==a?(T=P(a,x),n[19]=x,n[20]=a,n[21]=T):T=n[21];let E;return n[22]!==t||n[23]!==v||n[24]!==o||n[25]!==S||n[26]!==C||n[27]!==w||n[28]!==T?(E=(0,b.jsx)(VK.button,{type:`button`,role:`option`,id:S,"aria-selected":v,"data-highlighted":C,...o,ref:t,onClick:w,onMouseMove:T}),n[22]=t,n[23]=v,n[24]=o,n[25]=S,n[26]=C,n[27]=w,n[28]=T,n[29]=E):E=n[29],E});MY.displayName=`ComposerPrimitive.TriggerPopoverCategoryItem`;var NY=Z((e,t)=>{let n=J(12),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({children:i,"aria-label":r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let{items:o,activeCategoryId:s,isSearchMode:c,open:l}=CJ();if(!l||!s&&!c)return null;let u=r??`Items`,d;n[4]!==i||n[5]!==o?(d=i(o),n[4]=i,n[5]=o,n[6]=d):d=n[6];let f;return n[7]!==t||n[8]!==a||n[9]!==u||n[10]!==d?(f=(0,b.jsx)(VK.div,{role:`group`,"aria-label":u,...a,ref:t,children:d}),n[7]=t,n[8]=a,n[9]=u,n[10]=d,n[11]=f):f=n[11],f});NY.displayName=`ComposerPrimitive.TriggerPopoverItems`;var PY=Z((e,t)=>{let n=J(30),r,i,a,o,s;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],s=n[5]):({item:i,index:r,onClick:a,onMouseMove:o,...s}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=s);let{selectItem:c,highlightIndex:l,items:u,highlightedIndex:d,activeCategoryId:f,isSearchMode:p,popoverId:m}=CJ(),h;n[6]!==i||n[7]!==c?(h=()=>{c(i)},n[6]=i,n[7]=c,n[8]=h):h=n[8];let g=h,_;n[9]!==r||n[10]!==i.id||n[11]!==u?(_=r??u.findIndex(e=>e.id===i.id),n[9]=r,n[10]=i.id,n[11]=u,n[12]=_):_=n[12];let v=_,y=(p||f!==null)&&v===d,x;n[13]!==l||n[14]!==v?(x=()=>{l(v)},n[13]=l,n[14]=v,n[15]=x):x=n[15];let S=x,C=`${m}-option-${i.id}`,w=y?``:void 0,T;n[16]!==g||n[17]!==a?(T=P(a,g),n[16]=g,n[17]=a,n[18]=T):T=n[18];let E;n[19]!==S||n[20]!==o?(E=P(o,S),n[19]=S,n[20]=o,n[21]=E):E=n[21];let D;return n[22]!==t||n[23]!==y||n[24]!==s||n[25]!==C||n[26]!==w||n[27]!==T||n[28]!==E?(D=(0,b.jsx)(VK.button,{type:`button`,role:`option`,id:C,"aria-selected":y,"data-highlighted":w,...s,ref:t,onClick:T,onMouseMove:E}),n[22]=t,n[23]=y,n[24]=s,n[25]=C,n[26]=w,n[27]=T,n[28]=E,n[29]=D):D=n[29],D});PY.displayName=`ComposerPrimitive.TriggerPopoverItem`;var FY=Z((e,t)=>{let n=J(10),r,i;n[0]===e?(r=n[1],i=n[2]):({onClick:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let{activeCategoryId:a,isSearchMode:o,goBack:s,open:c}=CJ();if(!c||!a||o)return null;let l;n[3]!==s||n[4]!==r?(l=P(r,s),n[3]=s,n[4]=r,n[5]=l):l=n[5];let u;return n[6]!==t||n[7]!==i||n[8]!==l?(u=(0,b.jsx)(VK.button,{type:`button`,...i,ref:t,onClick:l}),n[6]=t,n[7]=i,n[8]=l,n[9]=u):u=n[9],u});FY.displayName=`ComposerPrimitive.TriggerPopoverBack`;var IY=e=>{let t=J(8),{formatter:n,onExecute:r,removeOnExecute:i}=e,{register:a}=EJ(),o=Y(r),s,c;t[0]===r?(s=t[1],c=t[2]):(s=()=>{o.current=r},c=[r],t[0]=r,t[1]=s,t[2]=c),xN(s,c);let l,u;return t[3]!==n||t[4]!==a||t[5]!==i?(l=()=>{let e={kind:`action`,formatter:n??kK,onExecute:e=>o.current(e),...i===void 0?{}:{removeOnExecute:i}};return a(e)},u=[a,n,i],t[3]=n,t[4]=a,t[5]=i,t[6]=l,t[7]=u):(l=t[6],u=t[7]),X(l,u),null};IY.displayName=`ComposerPrimitive.TriggerPopoverAction`;var LY=e=>{let t=J(7),{formatter:n,onInserted:r}=e,{register:i}=EJ(),a=Y(r),o,s;t[0]===r?(o=t[1],s=t[2]):(o=()=>{a.current=r},s=[r],t[0]=r,t[1]=o,t[2]=s),xN(o,s);let c,l;return t[3]!==n||t[4]!==i?(c=()=>i({kind:`directive`,formatter:n??kK,onInserted:e=>a.current?.(e)}),l=[i,n],t[3]=n,t[4]=i,t[5]=c,t[6]=l):(c=t[5],l=t[6]),X(c,l),null};LY.displayName=`ComposerPrimitive.TriggerPopoverDirective`;var RY=Object.assign(DJ,{Directive:LY,Action:IY}),zY=FK({AddAttachment:()=>yY,AttachmentByIndex:()=>tG,AttachmentDropzone:()=>bY,Attachments:()=>rG,Cancel:()=>vY,Dictate:()=>xY,DictationTranscript:()=>wY,If:()=>yG,Input:()=>_Y,Queue:()=>aG,Quote:()=>EY,QuoteDismiss:()=>OY,QuoteText:()=>DY,Root:()=>IJ,Send:()=>AJ,StopDictation:()=>SY,Unstable_TriggerPopover:()=>RY,Unstable_TriggerPopoverBack:()=>FY,Unstable_TriggerPopoverCategories:()=>jY,Unstable_TriggerPopoverCategoryItem:()=>MY,Unstable_TriggerPopoverItem:()=>PY,Unstable_TriggerPopoverItems:()=>NY,Unstable_TriggerPopoverRoot:()=>uJ,unstable_useTriggerPopoverRootContext:()=>Qq,unstable_useTriggerPopoverRootContextOptional:()=>$q,unstable_useTriggerPopoverScopeContext:()=>CJ,unstable_useTriggerPopoverScopeContextOptional:()=>wJ,unstable_useTriggerPopoverTriggers:()=>tJ,unstable_useTriggerPopoverTriggersOptional:()=>aJ}),BY=Object.freeze({type:`complete`}),VY=Object.freeze({type:`text`,text:``,status:BY}),HY=()=>$(UY);function UY(e){return e.part.type!==`text`&&e.part.type!==`reasoning`?VY:e.part}var WY=kN(null),GY=e=>({useSmoothStatus:bK(()=>e)}),KY=e=>{let t=J(6),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r={optional:!0},t[0]=r):r=t[0];let i=JY(r),a=Q(),o;t[1]===a.part?o=t[2]:(o=()=>GY(a.part.getState().status),t[1]=a.part,t[2]=o);let[s]=pN(o);if(i)return n;let c;return t[3]!==n||t[4]!==s?(c=(0,b.jsx)(WY.Provider,{value:s,children:n}),t[3]=n,t[4]=s,t[5]=c):c=t[5],c},qY=e=>{let t=Z((t,n)=>{let r=J(3),i=t,a;return r[0]!==n||r[1]!==i?(a=(0,b.jsx)(KY,{children:(0,b.jsx)(e,{...i,ref:n})}),r[0]=n,r[1]=i,r[2]=a):a=r[2],a});return t.displayName=e.displayName,t};function JY(e){let t=jN(WY);if(!e?.optional&&!t)throw Error(`This component must be used within a SmoothContextProvider.`);return t}var{useSmoothStatus:YY,useSmoothStatusStore:XY}=dK(JY,`useSmoothStatus`),ZY=250,QY=5,$Y=class{animationFrameId=null;lastUpdateTime=Date.now();lastCommitTime=0;targetText=``;drainMs=ZY;maxCharIntervalMs=QY;maxCharsPerFrame=1/0;minCommitMs=0;currentText;setText;constructor(e,t){this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}animate=()=>{let e=Date.now(),t=e-this.lastUpdateTime,n=this.targetText.length-this.currentText.length,r=Math.min(this.maxCharIntervalMs,this.drainMs/n),i=Math.min(n,this.maxCharsPerFrame),a=0;for(;t>=r&&a<i;)a++,t-=r;a===i&&i===this.maxCharsPerFrame&&(t=0),this.animationFrameId=a===n?null:requestAnimationFrame(this.animate),a!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+a),this.lastUpdateTime=e-t,(a===n||e-this.lastCommitTime>=this.minCommitMs)&&(this.lastCommitTime=e,this.setText(this.currentText)))}},eX=Object.freeze({type:`running`}),tX=(e,t)=>e!==void 0&&e>0?e:t,nX=(e,t=!1)=>{let{text:n}=e,r=HJ(`(prefers-reduced-motion: reduce)`),i=typeof t==`object`&&t?t:void 0,a=t!==!1&&t!==null&&!r,o=tX(i?.drainMs,ZY),s=tX(i?.maxCharIntervalMs,QY),c=tX(i?.maxCharsPerFrame,1/0),l=tX(i?.minCommitMs,0),[u,d]=pN(e.status.type===`running`?``:n),f=Q(),p=$(()=>f.part),[m,h]=pN(p);(p!==m||!n.startsWith(u))&&(h(p),d(e.status.type===`running`?``:n));let g=XY({optional:!0}),_=dt(t=>{if(d(t),g){let n=u!==t||e.status.type===`running`?eX:e.status;CK(g).setState(n,!0)}});X(()=>{if(g){let t=a&&(u!==n||e.status.type===`running`)?eX:e.status;CK(g).setState(t,!0)}},[g,a,n,u,e.status]);let[v]=pN(new $Y(u,_));X(()=>{v.drainMs=o,v.maxCharIntervalMs=s,v.maxCharsPerFrame=c,v.minCommitMs=l},[v,o,s,c,l]);let y=Y(p);return X(()=>{if(!a){v.stop();return}let t=y.current!==p;if(y.current=p,t||!n.startsWith(v.targetText)){e.status.type===`running`?(v.currentText=``,v.targetText=n,v.lastCommitTime=0,v.start()):(v.currentText=n,v.targetText=n,v.stop(),_(n));return}if(v.targetText=n,e.status.type!==`running`){if(v.currentText===``){v.currentText=n,v.stop(),_(n);return}v.start();return}v.start()},[v,a,n,e.status.type,p,_]),X(()=>()=>{v.stop()},[v]),hN(()=>a?{...e,text:u,status:n===u?e.status:eX}:e,[a,u,e,n])},rX=Object.freeze({type:`complete`}),iX=Object.freeze({type:`image`,image:``,status:rX}),aX=()=>$(oX);function oX(e){return e.part.type===`image`?e.part:iX}var sX=Z(({smooth:e=!0,component:t=VK.span,render:n,...r},i)=>{let{text:a,status:o}=nX(HY(),e),s={"data-status":o.type,...r,ref:i};return n&&ON(n)?RK(n,a,s):(0,b.jsx)(t,{...s,children:a})});sX.displayName=`MessagePartPrimitive.Text`;var cX=Z((e,t)=>{let n=J(4),{image:r}=aX(),i;return n[0]!==t||n[1]!==r||n[2]!==e?(i=(0,b.jsx)(VK.img,{src:r,...e,ref:t}),n[0]=t,n[1]=r,n[2]=e,n[3]=i):i=n[3],i});cX.displayName=`MessagePartPrimitive.Image`;var lX=Z((e,t)=>{let n=J(3),r;return n[0]!==t||n[1]!==e?(r=(0,b.jsx)(VK.div,{role:`alert`,...e,ref:t}),n[0]=t,n[1]=e,n[2]=r):r=n[2],r});lX.displayName=`ErrorPrimitive.Root`;var uX=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({children:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=cK();if(a===void 0)return null;let o=r??String(a),s;return n[3]!==t||n[4]!==i||n[5]!==o?(s=(0,b.jsx)(VK.span,{...i,ref:t,children:o}),n[3]=t,n[4]=i,n[5]=o,n[6]=s):s=n[6],s});uX.displayName=`ErrorPrimitive.Message`;var dX=FK({Message:()=>uX,Root:()=>lX}),fX=e=>{let t=J(2),n=Y(void 0),r;return t[0]===e?r=t[1]:(r=t=>{n.current&&=(n.current(),void 0),t&&(n.current=e(t))},t[0]=e,t[1]=r),r},pX=(e,t)=>{let n=e.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(em|px|rem)$/);if(!n)return 1/0;let r=Number(n[1]),i=n[2];return i===`px`?r:i===`em`?r*(parseFloat(getComputedStyle(t).fontSize)||16):i===`rem`?r*(parseFloat(getComputedStyle(document.documentElement).fontSize)||16):1/0},mX=e=>e.dataset.messageId,hX=()=>{let e=document.createElement(`div`);return e.dataset.auiTopAnchorReserve=``,e.style.height=`0px`,e.style.flexShrink=`0`,e.style.pointerEvents=`none`,e.setAttribute(`aria-hidden`,`true`),e},gX=(e,t)=>{let n=`${t}px`;return e.style.height!==n&&(e.style.height=n,!0)},_X=e=>{let t=window.devicePixelRatio||1;return Math.round(e*t)/t},vX=()=>{let e=J(4),t=Q(),n;e[0]===t.message?n=e[1]:(n=()=>t.message,e[0]=t.message,e[1]=n);let r=$(n),i;return e[2]===r?i=e[3]:(i=e=>{let t=()=>{r.setIsHovering(!0)},n=()=>{r.setIsHovering(!1)};return e.addEventListener(`mouseenter`,t),e.addEventListener(`mouseleave`,n),e.matches(`:hover`)&&queueMicrotask(()=>r.setIsHovering(!0)),()=>{e.removeEventListener(`mouseenter`,t),e.removeEventListener(`mouseleave`,n),r.setIsHovering(!1)}},e[2]=r,e[3]=i),fX(i)},yX=()=>{let e=J(2),t=pK(EX),n;return e[0]===t?n=e[1]:(n=e=>e.message.role===`user`&&e.message.index>0&&e.message.index===e.thread.messages.length-2&&e.thread.messages.at(-1)?.role===`assistant`&&(e.message.id===t||e.thread.isRunning),e[0]=t,e[1]=n),$(n)},bX=()=>{let e=J(2),t=pK(DX),n;return e[0]===t?n=e[1]:(n=e=>e.message.isLast&&e.message.role===`assistant`&&e.message.index>=1&&e.thread.messages.at(e.message.index-1)?.role===`user`&&(e.message.id===t||e.thread.isRunning),e[0]=t,e[1]=n),$(n)},xX=(e,t)=>{let n=J(3),r;return n[0]!==e||n[1]!==t?(r=n=>{if(e)return t.getState().registerAnchorElement(n)},n[0]=e,n[1]=t,n[2]=r):r=n[2],fX(r)},SX=e=>{let t=J(3),{active:n,threadViewportStore:r}=e,i;return t[0]!==n||t[1]!==r?(i=e=>{if(!n)return;let t=r.getState(),i=t.topAnchorMessageClamp;return t.registerAnchorTargetElement(e,{tallerThan:pX(i.tallerThan,e),visibleHeight:pX(i.visibleHeight,e)})},t[0]=n,t[1]=r,t[2]=i):i=t[2],fX(i)},CX=e=>{let t=J(7),n,r;t[0]===e?(n=t[1],r=t[2]):({forwardedRef:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i=vX(),a=u(n,i),o=$(OX),s;return t[3]!==o||t[4]!==r||t[5]!==a?(s=(0,b.jsx)(VK.div,{...r,ref:a,"data-message-id":o}),t[3]=o,t[4]=r,t[5]=a,t[6]=s):s=t[6],s},wX=e=>{let t=J(13),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({forwardedRef:n,threadViewportStore:i,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a=vX(),o=yX(),s=bX(),c=xX(o,i),l;t[4]!==s||t[5]!==i?(l={active:s,threadViewportStore:i},t[4]=s,t[5]=i,t[6]=l):l=t[6];let d=SX(l),f=u(n,a,c,d),p=$(kX),m=o?``:void 0,h=s?``:void 0,g;return t[7]!==p||t[8]!==r||t[9]!==f||t[10]!==m||t[11]!==h?(g=(0,b.jsx)(VK.div,{...r,ref:f,"data-message-id":p,"data-aui-top-anchor-user":m,"data-aui-top-anchor-target":h}),t[7]=p,t[8]=r,t[9]=f,t[10]=m,t[11]=h,t[12]=g):g=t[12],g},TX=Z((e,t)=>{let n=J(7),r=mK();if(r.getState().turnAnchor===`top`){let i;return n[0]!==t||n[1]!==e||n[2]!==r?(i=(0,b.jsx)(wX,{...e,forwardedRef:t,threadViewportStore:r}),n[0]=t,n[1]=e,n[2]=r,n[3]=i):i=n[3],i}let i;return n[4]!==t||n[5]!==e?(i=(0,b.jsx)(CX,{...e,forwardedRef:t}),n[4]=t,n[5]=e,n[6]=i):i=n[6],i});TX.displayName=`MessagePrimitive.Root`;function EX(e){return e.topAnchorTurn?.anchorId}function DX(e){return e.topAnchorTurn?.targetId}function OX(e){return e.message.id}function kX(e){return e.message.id}var AX={...iW,Text:()=>(0,b.jsxs)(`p`,{style:{whiteSpace:`pre-line`},children:[(0,b.jsx)(sX,{}),(0,b.jsx)(lG,{children:(0,b.jsx)(`span`,{style:{fontFamily:`revert`},children:` ●`})})]}),Image:()=>(0,b.jsx)(cX,{})},jX=e=>{let t=J(10);if(`children`in e){let n;return t[0]===e.children?n=t[1]:(n=(0,b.jsx)(xW,{children:e.children}),t[0]=e.children,t[1]=n),n}let n,r;t[2]===e?(n=t[3],r=t[4]):({components:n,...r}=e,t[2]=e,t[3]=n,t[4]=r);let i;t[5]===n?i=t[6]:(i=n?{...n,Text:n.Text??AX.Text,Image:n.Image??AX.Image}:AX,t[5]=n,t[6]=i);let a=i,o;return t[7]!==r||t[8]!==a?(o=(0,b.jsx)(xW,{components:a,...r}),t[7]=r,t[8]=a,t[9]=o):o=t[9],o};jX.displayName=`MessagePrimitive.Parts`;var MX=e=>{let t=J(12),n;return t[0]!==e.assistant||t[1]!==e.copied||t[2]!==e.hasAttachments||t[3]!==e.hasBranches||t[4]!==e.hasContent||t[5]!==e.last||t[6]!==e.lastOrHover||t[7]!==e.speaking||t[8]!==e.submittedFeedback||t[9]!==e.system||t[10]!==e.user?(n=t=>{let{role:n,attachments:r,parts:i,branchCount:a,isLast:o,speech:s,isCopied:c,isHovering:l}=t.message;return!(e.hasBranches===!0&&a<2||e.user&&n!==`user`||e.assistant&&n!==`assistant`||e.system&&n!==`system`||e.lastOrHover===!0&&!l&&!o||e.last!==void 0&&e.last!==o||e.copied===!0&&!c||e.copied===!1&&c||e.speaking===!0&&s==null||e.speaking===!1&&s!=null||e.hasAttachments===!0&&(n!==`user`||!r?.length)||e.hasAttachments===!1&&n===`user`&&r?.length||e.hasContent===!0&&i.length===0||e.hasContent===!1&&i.length>0||e.submittedFeedback!==void 0&&(t.message.metadata.submittedFeedback?.type??null)!==e.submittedFeedback)},t[0]=e.assistant,t[1]=e.copied,t[2]=e.hasAttachments,t[3]=e.hasBranches,t[4]=e.hasContent,t[5]=e.last,t[6]=e.lastOrHover,t[7]=e.speaking,t[8]=e.submittedFeedback,t[9]=e.system,t[10]=e.user,t[11]=n):n=t[11],$(n)},NX=e=>{let t=J(3),n,r;return t[0]===e?(n=t[1],r=t[2]):({children:n,...r}=e,t[0]=e,t[1]=n,t[2]=r),MX(r)?n:null};NX.displayName=`MessagePrimitive.If`;var PX=e=>{let{children:t}=e;return cK()===void 0?null:t};PX.displayName=`MessagePrimitive.Error`;var FX=e=>{let t=new Map;for(let n=0;n<e.length;n++){let r=e[n]?.parentId??n,i=t.get(r)??[];i.push(n),t.set(r,i)}let n=[];for(let[e,r]of t){let t=typeof e==`string`?e:void 0;n.push({groupKey:t,indices:r})}return n},IX=e=>{let t=J(4),n=$(qX),r;bb0:{if(n.length===0){let e;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[0]=e):e=t[0],r=e;break bb0}let i;t[1]!==e||t[2]!==n?(i=e(n),t[1]=e,t[2]=n,t[3]=i):i=t[3],r=i}return r},LX=e=>{let t=J(9),n,r;t[0]===e?(n=t[1],r=t[2]):({Fallback:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]!==n||t[4]!==r.toolName?(i=e=>e.tools.toolUIs[r.toolName]?.[0]?.render??n,t[3]=n,t[4]=r.toolName,t[5]=i):i=t[5];let a=$(i);if(!a)return null;let o;return t[6]!==a||t[7]!==r?(o=(0,b.jsx)(a,{...r}),t[6]=a,t[7]=r,t[8]=o):o=t[8],o},RX=e=>{let t=J(9),n,r;t[0]===e?(n=t[1],r=t[2]):({Fallback:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]!==n||t[4]!==r.name?(i=e=>{let t=e.dataRenderers.renderers[r.name]??n;return Array.isArray(t)?t[0]??n:t},t[3]=n,t[4]=r.name,t[5]=i):i=t[5];let a=$(i);if(!a)return null;let o;return t[6]!==a||t[7]!==r?(o=(0,b.jsx)(a,{...r}),t[6]=a,t[7]=r,t[8]=o):o=t[8],o},zX={Text:()=>(0,b.jsxs)(`p`,{style:{whiteSpace:`pre-line`},children:[(0,b.jsx)(sX,{}),(0,b.jsx)(lG,{children:(0,b.jsx)(`span`,{style:{fontFamily:`revert`},children:` ●`})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>(0,b.jsx)(cX,{}),File:()=>null,Unstable_Audio:()=>null,Group:({children:e})=>e},BX=e=>{let t=J(37),{components:n}=e,r;t[0]===n?r=t[1]:(r=n===void 0?{}:n,t[0]=n,t[1]=r);let{Text:i,Reasoning:a,Image:o,Source:s,File:c,Unstable_Audio:l,tools:u,data:d}=r,f=i===void 0?zX.Text:i,p=a===void 0?zX.Reasoning:a,m=o===void 0?zX.Image:o,h=s===void 0?zX.Source:s,g=c===void 0?zX.File:c,_=l===void 0?zX.Unstable_Audio:l,v;t[2]===u?v=t[3]:(v=u===void 0?{}:u,t[2]=u,t[3]=v);let y=v,x=Q(),S=$(JX),C=S.type;if(C===`tool-call`){let e=x.part.addToolResult,n=x.part.resumeToolCall,r=x.part.respondToToolApproval;if(`Override`in y){let i;return t[4]!==e||t[5]!==S||t[6]!==r||t[7]!==n||t[8]!==y.Override?(i=(0,b.jsx)(y.Override,{...S,addResult:e,resume:n,respondToApproval:r}),t[4]=e,t[5]=S,t[6]=r,t[7]=n,t[8]=y.Override,t[9]=i):i=t[9],i}let i=y.by_name?.[S.toolName]??y.Fallback,a;return t[10]!==i||t[11]!==e||t[12]!==S||t[13]!==r||t[14]!==n?(a=(0,b.jsx)(LX,{...S,Fallback:i,addResult:e,resume:n,respondToApproval:r}),t[10]=i,t[11]=e,t[12]=S,t[13]=r,t[14]=n,t[15]=a):a=t[15],a}if(S.status?.type===`requires-action`)throw Error(`Encountered unexpected requires-action status`);switch(C){case`text`:{let e;return t[16]!==f||t[17]!==S?(e=(0,b.jsx)(f,{...S}),t[16]=f,t[17]=S,t[18]=e):e=t[18],e}case`reasoning`:{let e;return t[19]!==p||t[20]!==S?(e=(0,b.jsx)(p,{...S}),t[19]=p,t[20]=S,t[21]=e):e=t[21],e}case`source`:{let e;return t[22]!==h||t[23]!==S?(e=(0,b.jsx)(h,{...S}),t[22]=h,t[23]=S,t[24]=e):e=t[24],e}case`image`:{let e;return t[25]!==m||t[26]!==S?(e=(0,b.jsx)(m,{...S}),t[25]=m,t[26]=S,t[27]=e):e=t[27],e}case`file`:{let e;return t[28]!==g||t[29]!==S?(e=(0,b.jsx)(g,{...S}),t[28]=g,t[29]=S,t[30]=e):e=t[30],e}case`audio`:{let e;return t[31]!==_||t[32]!==S?(e=(0,b.jsx)(_,{...S}),t[31]=_,t[32]=S,t[33]=e):e=t[33],e}case`data`:{let e=d?.by_name?.[S.name]??d?.Fallback,n;return t[34]!==e||t[35]!==S?(n=(0,b.jsx)(RX,{...S,Fallback:e}),t[34]=e,t[35]=S,t[36]=n):n=t[36],n}default:return console.warn(`Unknown message part type: ${C}`),null}},VX=wN(e=>{let t=J(5),{partIndex:n,components:r}=e,i;t[0]===r?i=t[1]:(i=(0,b.jsx)(BX,{components:r}),t[0]=r,t[1]=i);let a;return t[2]!==n||t[3]!==i?(a=(0,b.jsx)(QB,{index:n,children:i}),t[2]=n,t[3]=i,t[4]=a):a=t[4],a},(e,t)=>e.partIndex===t.partIndex&&e.components?.Text===t.components?.Text&&e.components?.Reasoning===t.components?.Reasoning&&e.components?.Source===t.components?.Source&&e.components?.Image===t.components?.Image&&e.components?.File===t.components?.File&&e.components?.Unstable_Audio===t.components?.Unstable_Audio&&e.components?.tools===t.components?.tools&&e.components?.data===t.components?.data&&e.components?.Group===t.components?.Group),HX=e=>{let t=J(6),{status:n,component:r}=e,i=n.type===`running`,a;t[0]!==r||t[1]!==n?(a=(0,b.jsx)(r,{type:`text`,text:``,status:n}),t[0]=r,t[1]=n,t[2]=a):a=t[2];let o;return t[3]!==i||t[4]!==a?(o=(0,b.jsx)(eV,{text:``,isRunning:i,children:a}),t[3]=i,t[4]=a,t[5]=o):o=t[5],o},UX=Object.freeze({type:`complete`}),WX=wN(e=>{let t=J(6),{components:n}=e,r=$(YX);if(n?.Empty){let e;return t[0]!==n.Empty||t[1]!==r?(e=(0,b.jsx)(n.Empty,{status:r}),t[0]=n.Empty,t[1]=r,t[2]=e):e=t[2],e}let i=n?.Text??zX.Text,a;return t[3]!==r||t[4]!==i?(a=(0,b.jsx)(HX,{status:r,component:i}),t[3]=r,t[4]=i,t[5]=a):a=t[5],a},(e,t)=>e.components?.Empty===t.components?.Empty&&e.components?.Text===t.components?.Text),GX=e=>{let t=J(9),{groupingFunction:n,components:r}=e,i=$(XX),a=IX(n),o;bb0:{if(i===0){let e;t[0]===r?e=t[1]:(e=(0,b.jsx)(WX,{components:r}),t[0]=r,t[1]=e),o=e;break bb0}let e;if(t[2]!==r||t[3]!==a){let n;t[5]===r?n=t[6]:(n=(e,t)=>{let n=r?.Group??zX.Group;return(0,b.jsx)(n,{groupKey:e.groupKey,indices:e.indices,children:e.indices.map(e=>(0,b.jsx)(VX,{partIndex:e,components:r},e))},`group-${t}-${e.groupKey??`ungrouped`}`)},t[5]=r,t[6]=n),e=a.map(n),t[2]=r,t[3]=a,t[4]=e}else e=t[4];o=e}let s=o,c;return t[7]===s?c=t[8]:(c=(0,b.jsx)(b.Fragment,{children:s}),t[7]=s,t[8]=c),c};GX.displayName=`MessagePrimitive.Unstable_PartsGrouped`;var KX=e=>{let t=J(6),n,r;t[0]===e?(n=t[1],r=t[2]):({components:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;return t[3]!==n||t[4]!==r?(i=(0,b.jsx)(GX,{...r,components:n,groupingFunction:FX}),t[3]=n,t[4]=r,t[5]=i):i=t[5],i};KX.displayName=`MessagePrimitive.Unstable_PartsGroupedByParentId`;function qX(e){return e.message.parts}function JX(e){return e.part}function YX(e){return e.message.status??UX}function XX(e){return e.message.parts.length}var ZX=FK({AttachmentByIndex:()=>YW,Attachments:()=>ZW,Content:()=>jX,Error:()=>PX,GenerativeUI:()=>XU,GroupedParts:()=>GW,If:()=>NX,PartByIndex:()=>oW,Parts:()=>jX,Quote:()=>KW,Root:()=>TX,Unstable_PartsGrouped:()=>GX,Unstable_PartsGroupedByParentId:()=>KX}),QX=e=>{let t=J(2),n=dt(e),r;return t[0]===n?r=t[1]:(r=e=>{let t=new ResizeObserver(()=>{n()}),r=new MutationObserver(e=>{e.some($X)&&n()});return t.observe(e),r.observe(e,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{t.disconnect(),r.disconnect()}},t[0]=n,t[1]=r),fX(r)};function $X(e){return e.type!==`attributes`||e.attributeName!==`style`}var eZ=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:n=!0,scrollToBottomOnThreadSwitch:r=!0})=>{let i=Y(null),a=$(e=>e.thread.messages.length>0),o=$(e=>e.thread.isRunning),s=Y(!1),c=Y(null),l=mK();e===void 0&&(e=l.getState().turnAnchor!==`top`);let d=Y(0),f=Y(0),p=Y(0),m=Y(0),h=Y(null),g=Y(e),_=Y(e);_N(()=>{let t=_.current;if(_.current=e,t||!e)return;let n=i.current;g.current=n!==null&&vI(n)},[e]);let v=gN(e=>{let t=i.current;t&&(g.current=!0,h.current=e,t.scrollTo({top:t.scrollHeight,behavior:e}))},[]),y=gN(()=>{c.current!==null&&(cancelAnimationFrame(c.current),c.current=null)},[]),b=gN(e=>{h.current=e,y(),c.current=requestAnimationFrame(()=>{c.current=null,v(e)})},[y,v]);_N(()=>()=>y(),[y]);let x=gN(()=>{let e=l.getState();return e.turnAnchor===`top`&&e.element.viewport===i.current&&e.element.anchor!==null},[l]),S=()=>{let t=i.current;if(!t)return;let n=l.getState().isAtBottom,r=vI(t);if(!(!r&&d.current<t.scrollTop)){let i=bI({scrollTop:d.current,scrollHeight:f.current},t);r?(yI(t)&&(h.current=null),e&&(g.current=!0)):i&&(y(),h.current=null,g.current=!1),(r||h.current===null)&&r!==n&&CK(l).setState({isAtBottom:r})}d.current=t.scrollTop,f.current=t.scrollHeight},C=QX(()=>{let t=i.current;if(!t)return;let{scrollHeight:n,clientHeight:r}=t;if(n===p.current&&r===m.current)return;p.current=n,m.current=r;let a=h.current;a&&x()?h.current=null:a?v(a):e&&!(o&&x())&&g.current&&v(`instant`),S()}),w=fX(e=>{let t=()=>{h.current=null};return e.addEventListener(`scroll`,S),e.addEventListener(`pointerdown`,t),()=>{e.removeEventListener(`scroll`,S),e.removeEventListener(`pointerdown`,t)}});return _N(()=>{if(n){if(!a){s.current=!1;return}s.current||(s.current=!0,h.current===null&&b(`instant`))}},[a,b,n]),RJ(({behavior:e})=>{v(e)}),GL(`thread.runStart`,()=>{t&&l.getState().turnAnchor!==`top`&&b(`auto`)}),GL(`threads.selectionChanged`,()=>{r&&b(`instant`)}),u(C,w,i)},tZ=Z((e,t)=>{let n=J(6),r=Q(),i,a;n[0]===r?(i=n[1],a=n[2]):(i=()=>{let e=e=>{if(e.key===`Escape`&&!(e.defaultPrevented||r.thread.source===null)&&r.thread.getState().speech!=null){e.preventDefault();try{r.thread.stopSpeaking()}catch(e){let t=e;if(!(t instanceof Error)||t.message!==`No message is being spoken`)throw t}}};return document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`keydown`,e)}},a=[r],n[0]=r,n[1]=i,n[2]=a),X(i,a);let o;return n[3]!==e||n[4]!==t?(o=(0,b.jsx)(VK.div,{...e,ref:t}),n[3]=e,n[4]=t,n[5]=o):o=n[5],o});tZ.displayName=`ThreadPrimitive.Root`;var nZ=e=>{let{children:t}=e;return $(rZ)?t:null};nZ.displayName=`ThreadPrimitive.Empty`;function rZ(e){return e.thread.isEmpty}var iZ=e=>{let t=J(4),n;return t[0]!==e.disabled||t[1]!==e.empty||t[2]!==e.running?(n=t=>!(e.empty===!0&&!t.thread.isEmpty||e.empty===!1&&t.thread.isEmpty||e.running===!0&&!t.thread.isRunning||e.running===!1&&t.thread.isRunning||e.disabled===!0&&!t.thread.isDisabled||e.disabled===!1&&t.thread.isDisabled),t[0]=e.disabled,t[1]=e.empty,t[2]=e.running,t[3]=n):n=t[3],$(n)},aZ=e=>{let t=J(3),n,r;return t[0]===e?(n=t[1],r=t[2]):({children:n,...r}=e,t[0]=e,t[1]=n,t[2]=r),iZ(r)?n:null};aZ.displayName=`ThreadPrimitive.If`;var oZ=(e,t)=>{let n=J(3),r;return n[0]!==t||n[1]!==e?(r=n=>{if(!e)return;let r=e(),i=()=>{let e=t?t(n):n.offsetHeight;r.setHeight(e)},a=new ResizeObserver(i);return a.observe(n),i(),()=>{a.disconnect(),r.unregister()}},n[0]=t,n[1]=e,n[2]=r):r=n[2],fX(r)},sZ=e=>{let t=0,n=e;for(;n;)t+=n.offsetTop,n=n.offsetParent;return t},cZ=(e,t)=>{let n=0,r=e;for(;r&&r!==t;)n+=r.offsetTop,r=r.offsetParent;return r===t?n:sZ(e)-sZ(t)},lZ=({viewport:e,anchor:t,tallerThan:n,visibleHeight:r})=>{let i=cZ(t,e),a=t.offsetHeight;return i+Math.max(0,a-(a<=n?a:r))},uZ=({scrollHeight:e,...t})=>{let{viewport:n}=t,r=lZ(t)+n.clientHeight;return Math.max(0,r-e)},dZ=({viewport:e,reserve:t,...n})=>uZ({viewport:e,...n,scrollHeight:e.scrollHeight-t.offsetHeight}),fZ=e=>{let t=new ResizeObserver(e),n=new MutationObserver(e),r=null,i=null,a=null,o=()=>{t.disconnect(),n.disconnect(),r=null,i=null,a=null};return{target:(e,s,c)=>{(r!==e||i!==s||a!==c)&&(o(),t.observe(e),t.observe(s),t.observe(c),n.observe(c,{childList:!0,subtree:!0,characterData:!0}),r=e,i=s,a=c)},disconnect:o}},pZ=e=>{let t=null;return{schedule:()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,e()}))},cancel:()=>{t!==null&&(cancelAnimationFrame(t),t=null)}}},mZ=e=>{let t=null,n;function r(){let r=e.getState(),{viewport:o,anchor:s,target:c}=r.element,l=r.targetConfig;if(r.turnAnchor!==`top`||!o){a.disconnect(),t&&(gX(t,0),t.remove());return}if(!s&&!c&&!l&&r.topAnchorTurn){a.disconnect(),t?.parentElement&&t.parentElement.lastElementChild!==t&&t.parentElement.append(t);return}if(!s||!c||!l){a.disconnect(),t&&(gX(t,0),t.remove());return}if(t??=hX(),(t.parentElement!==c.parentElement||t.previousElementSibling!==c)&&c.after(t),a.target(o,s,c),gX(t,dZ({viewport:o,anchor:s,reserve:t,...l}))){i.schedule();return}let u=mX(s);if(u!==void 0&&n===u)return;let d=_X(lZ({viewport:o,anchor:s,...l}));Math.abs(o.scrollTop-d)>1&&o.scrollTo({top:d,behavior:`smooth`}),u!==void 0&&(n=u)}let i=pZ(r),a=fZ(i.schedule);i.schedule();let o=e.subscribe(i.schedule);return()=>{i.cancel(),o(),a.disconnect(),t?.remove()}},hZ=e=>{let t=J(4),n=mK(),r,i;t[0]!==e||t[1]!==n?(r=()=>{if(e)return mZ(n)},i=[e,n],t[0]=e,t[1]=n,t[2]=r,t[3]=i):(r=t[2],i=t[3]),_N(r,i)},gZ=(e,t)=>{if(!e)return!1;let n=t.findIndex(t=>t.id===e.targetId);return n<1?!1:t[n-1]?.id===e.anchorId&&t.slice(n+1).every(e=>e.role===`user`)},_Z=({isRunning:e,messages:t})=>{if(!e)return null;let n=t.at(-1),r=t.at(-2);return r?.role!==`user`||n?.role!==`assistant`?null:{anchorId:r.id,targetId:n.id}},vZ=e=>_Z(e)?.anchorId,yZ=e=>_Z(e)?.targetId,bZ=()=>oZ(pK(TZ),EZ),xZ=()=>fX(pK(DZ)),SZ=e=>{let t=J(19),n=mK(),r;t[0]===e?r=t[1]:(r=t=>{if(e)return vZ(t.thread)},t[0]=e,t[1]=r);let i=$(r),a;t[2]===e?a=t[3]:(a=t=>{if(e)return yZ(t.thread)},t[2]=e,t[3]=a);let o=$(a),s=pK(OZ),c;bb0:{if(!i||!o){c=null;break bb0}let e;t[4]!==i||t[5]!==o?(e={anchorId:i,targetId:o},t[4]=i,t[5]=o,t[6]=e):e=t[6],c=e}let l=c,u;t[7]!==e||t[8]!==s?(u=t=>e&&!!s&&gZ(s,t.thread.messages),t[7]=e,t[8]=s,t[9]=u):u=t[9];let d=$(u),f,p;t[10]!==n||t[11]!==s||t[12]!==d?(f=()=>{s&&!d&&n.getState().setTopAnchorTurn(null)},p=[n,s,d],t[10]=n,t[11]=s,t[12]=d,t[13]=f,t[14]=p):(f=t[13],p=t[14]),_N(f,p);let m,h;t[15]!==l||t[16]!==n?(m=()=>{if(!l)return;let e=n.getState(),t=e.topAnchorTurn;(t?.anchorId!==l.anchorId||t.targetId!==l.targetId)&&e.setTopAnchorTurn(l)},h=[l,n],t[15]=l,t[16]=n,t[17]=m,t[18]=h):(m=t[17],h=t[18]),_N(m,h)},CZ=Z((e,t)=>{let n=J(18),r,i,a,o,s,c;n[0]===e?(r=n[1],i=n[2],a=n[3],o=n[4],s=n[5],c=n[6]):({autoScroll:r,scrollToBottomOnRunStart:s,scrollToBottomOnInitialize:o,scrollToBottomOnThreadSwitch:c,children:i,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a,n[4]=o,n[5]=s,n[6]=c);let l;n[7]!==r||n[8]!==o||n[9]!==s||n[10]!==c?(l={autoScroll:r,scrollToBottomOnRunStart:s,scrollToBottomOnInitialize:o,scrollToBottomOnThreadSwitch:c},n[7]=r,n[8]=o,n[9]=s,n[10]=c,n[11]=l):l=n[11];let d=eZ(l),f=bZ(),p=xZ(),m=mK(),h;n[12]===m?h=n[13]:(h=m.getState(),n[12]=m,n[13]=h);let g=h.turnAnchor===`top`;SZ(g),hZ(g);let _=u(t,d,f,p),v;return n[14]!==i||n[15]!==_||n[16]!==a?(v=(0,b.jsx)(VK.div,{...a,ref:_,children:i}),n[14]=i,n[15]=_,n[16]=a,n[17]=v):v=n[17],v});CZ.displayName=`ThreadPrimitive.ViewportScrollable`;var wZ=Z((e,t)=>{let n=J(13),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({turnAnchor:a,topAnchorMessageClamp:i,...r}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let o;n[4]!==i||n[5]!==a?(o={turnAnchor:a,topAnchorMessageClamp:i},n[4]=i,n[5]=a,n[6]=o):o=n[6];let s;n[7]!==r||n[8]!==t?(s=(0,b.jsx)(CZ,{...r,ref:t}),n[7]=r,n[8]=t,n[9]=s):s=n[9];let c;return n[10]!==o||n[11]!==s?(c=(0,b.jsx)(TK,{options:o,children:s}),n[10]=o,n[11]=s,n[12]=c):c=n[12],c});wZ.displayName=`ThreadPrimitive.Viewport`;function TZ(e){return e.registerViewport}function EZ(e){return e.clientHeight}function DZ(e){return e.registerViewportElement}function OZ(e){return e.topAnchorTurn}var kZ=Z((e,t)=>{let n=J(3),r=oZ(pK(AZ),jZ),i=u(t,r),a;return n[0]!==e||n[1]!==i?(a=(0,b.jsx)(VK.div,{...e,ref:i}),n[0]=e,n[1]=i,n[2]=a):a=n[2],a});kZ.displayName=`ThreadPrimitive.ViewportFooter`;function AZ(e){return e.registerContentInset}function jZ(e){let t=parseFloat(getComputedStyle(e).marginTop)||0;return e.offsetHeight+t}var MZ=$K(`ThreadPrimitive.ScrollToBottom`,e=>{let t=J(5),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{behavior:r}=n,i=pK(NZ),a=mK(),o;return t[2]!==r||t[3]!==a?(o=()=>{a.getState().scrollToBottom({behavior:r})},t[2]=r,t[3]=a,t[4]=o):o=t[4],i?null:o},[`behavior`]);function NZ(e){return e.isAtBottom}var PZ=$K(`ThreadPrimitive.Suggestion`,e=>{let t=J(4),{prompt:n,send:r,clearComposer:i,autoSend:a}=e,o=r??a??!1,s;t[0]!==i||t[1]!==n||t[2]!==o?(s={prompt:n,send:o,clearComposer:i},t[0]=i,t[1]=n,t[2]=o,t[3]=s):s=t[3];let{disabled:c,trigger:l}=eK(s);return c?null:l},[`prompt`,`send`,`clearComposer`,`autoSend`,`method`]),FZ=FK({Empty:()=>nZ,If:()=>aZ,MessageByIndex:()=>LU,Messages:()=>VU,Root:()=>tZ,ScrollToBottom:()=>MZ,Suggestion:()=>PZ,SuggestionByIndex:()=>mG,Suggestions:()=>_G,Unstable_MessageById:()=>RU,Viewport:()=>wZ,ViewportFooter:()=>kZ,ViewportProvider:()=>TK}),IZ=Z((e,t)=>{let n=J(4),r=$(LZ),i=e.children??r,a;return n[0]!==e||n[1]!==t||n[2]!==i?(a=(0,b.jsx)(VK.span,{...e,ref:t,children:i}),n[0]=e,n[1]=t,n[2]=i,n[3]=a):a=n[3],a});IZ.displayName=`SuggestionPrimitive.Title`;function LZ(e){return e.suggestion.title}var RZ=Z((e,t)=>{let n=J(4),r=$(zZ),i=e.children??r,a;return n[0]!==e||n[1]!==t||n[2]!==i?(a=(0,b.jsx)(VK.span,{...e,ref:t,children:i}),n[0]=e,n[1]=t,n[2]=i,n[3]=a):a=n[3],a});RZ.displayName=`SuggestionPrimitive.Description`;function zZ(e){return e.suggestion.label}var BZ=$K(`SuggestionPrimitive.Trigger`,e=>{let t=J(4),{send:n,clearComposer:r}=e,i=$(VZ),a;t[0]!==r||t[1]!==i||t[2]!==n?(a={prompt:i,send:n,clearComposer:r},t[0]=r,t[1]=i,t[2]=n,t[3]=a):a=t[3];let{trigger:o,disabled:s}=eK(a);return s?null:o},[`send`,`clearComposer`]);function VZ(e){return e.suggestion.prompt}var HZ=FK({Description:()=>RZ,Title:()=>IZ,Trigger:()=>BZ}),UZ=Z((e,t)=>{let n=J(15),r,i,a;n[0]===e?(r=n[1],i=n[2],a=n[3]):({onClick:i,disabled:r,...a}=e,n[0]=e,n[1]=r,n[2]=i,n[3]=a);let o=$(WZ),{switchToNewThread:s}=oK(),c;n[4]===o?c=n[5]:(c=o?{"data-active":`true`,"aria-current":`true`}:null,n[4]=o,n[5]=c);let l;n[6]!==i||n[7]!==s?(l=P(i,s),n[6]=i,n[7]=s,n[8]=l):l=n[8];let u;return n[9]!==r||n[10]!==t||n[11]!==a||n[12]!==c||n[13]!==l?(u=(0,b.jsx)(VK.button,{type:`button`,...c,...a,ref:t,disabled:r,onClick:l}),n[9]=r,n[10]=t,n[11]=a,n[12]=c,n[13]=l,n[14]=u):u=n[14],u});UZ.displayName=`ThreadListPrimitive.New`;function WZ(e){return e.threads.newThreadId===e.threads.mainThreadId}var GZ=$K(`ThreadListPrimitive.LoadMore`,()=>{let{loadMore:e,disabled:t}=sK();return t?null:e}),[KZ,qZ]=M(`ThreadList`),JZ=KZ,YZ=kN(null),XZ=YZ.Provider,ZZ=()=>jN(YZ),QZ=Z((e,t)=>{let n=J(3),r;return n[0]!==e||n[1]!==t?(r=(0,b.jsx)(JZ.Provider,{scope:void 0,children:(0,b.jsx)(JZ.Slot,{scope:void 0,children:(0,b.jsx)(VK.div,{...e,ref:t})})}),n[0]=e,n[1]=t,n[2]=r):r=n[2],r});QZ.displayName=`ThreadListPrimitive.Root`;var $Z=FK({ItemByIndex:()=>oG,Items:()=>cG,LoadMore:()=>GZ,New:()=>UZ,Root:()=>QZ}),eQ=Z((e,t)=>{let n=$(e=>e.threads.mainThreadId===e.threadListItem.id),r=Y(null),i=Y(null),a=hN(()=>({triggerRef:r,moreRef:i}),[]),o=qZ(void 0),s=ct(),c=e=>{let t=s===`rtl`?`ArrowLeft`:`ArrowRight`,n=s===`rtl`?`ArrowRight`:`ArrowLeft`,a=r.current,c=i.current;if(a&&e.target===a){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=o().map(e=>e.ref.current).filter(e=>e!==null),n=t[t.indexOf(a)+(e.key===`ArrowDown`?1:-1)];n&&(n.focus(),e.preventDefault())}else e.key===t&&c&&(c.focus(),e.preventDefault())}else c&&e.target===c&&e.key===n&&(a?.focus(),e.preventDefault())};return(0,b.jsx)(XZ,{value:a,children:(0,b.jsx)(VK.div,{...n?{"data-active":`true`,"aria-current":`true`}:null,...e,onKeyDown:P(e.onKeyDown,c),ref:t})})});eQ.displayName=`ThreadListItemPrimitive.Root`;var tQ=$K(`ThreadListItemPrimitive.Archive`,()=>{let{archive:e}=nK();return e}),nQ=$K(`ThreadListItemPrimitive.Unarchive`,()=>{let{unarchive:e}=iK();return e}),rQ=$K(`ThreadListItemPrimitive.Delete`,()=>{let{delete:e}=rK();return e}),iQ=$K(`ThreadListItemPrimitive.Trigger`,()=>{let{switchTo:e}=aK();return e}),aQ=Z((e,t)=>{let n=J(3),r=ZZ(),i=u(t,r?.triggerRef),a;return n[0]!==e||n[1]!==i?(a=(0,b.jsx)(JZ.ItemSlot,{scope:void 0,children:(0,b.jsx)(iQ,{...e,ref:i})}),n[0]=e,n[1]=i,n[2]=a):a=n[2],a});aQ.displayName=`ThreadListItemPrimitive.Trigger`;var oQ=FK({Archive:()=>tQ,Delete:()=>rQ,Root:()=>eQ,Title:()=>dG,Trigger:()=>aQ,Unarchive:()=>nQ}),sQ=ul(),cQ=kN(()=>{}),lQ=()=>jN(cQ),uQ=kN(!1),dQ=()=>jN(uQ),fQ=e=>{let t=J(26),n,r,i,a,o,s,c;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5],s=t[6],c=t[7]):({__scopeThreadListItemMore:n,open:o,defaultOpen:r,onOpenChange:a,sharedFocusGroup:c,modal:i,...s}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o,t[6]=s,t[7]=c);let l=c!==void 0&&c,u=l?!1:i??!0,d=sQ(n),f=r??!1,p;t[8]===a?p=t[9]:(p=a?{onChange:a}:{},t[8]=a,t[9]=p);let m;t[10]!==o||t[11]!==f||t[12]!==p?(m={prop:o,defaultProp:f,caller:`ThreadListItemMorePrimitive.Root`,...p},t[10]=o,t[11]=f,t[12]=p,t[13]=m):m=t[13];let[h,g]=Te(m),_;t[14]!==u||t[15]!==h||t[16]!==s||t[17]!==d||t[18]!==g?(_=(0,b.jsx)(Ml,{...d,...s,modal:u,open:h,onOpenChange:g}),t[14]=u,t[15]=h,t[16]=s,t[17]=d,t[18]=g,t[19]=_):_=t[19];let v;t[20]!==g||t[21]!==_?(v=(0,b.jsx)(cQ.Provider,{value:g,children:_}),t[20]=g,t[21]=_,t[22]=v):v=t[22];let y;return t[23]!==l||t[24]!==v?(y=(0,b.jsx)(uQ.Provider,{value:l,children:v}),t[23]=l,t[24]=v,t[25]=y):y=t[25],y};fQ.displayName=`ThreadListItemMorePrimitive.Root`;var pQ=Z((e,t)=>{let n=J(10),{__scopeThreadListItemMore:r,...i}=e,a=sQ(r),o=ZZ(),s=lQ(),c=dQ(),l=u(t,o?.moreRef),d=ct()===`rtl`?`ArrowLeft`:`ArrowRight`,f=yq,p;n[0]!==d||n[1]!==s||n[2]!==c?(p=e=>{c&&e.key===d&&(e.preventDefault(),s(!0))},n[0]=d,n[1]=s,n[2]=c,n[3]=p):p=n[3];let m=P(i.onKeyDown,p),h;return n[4]!==f||n[5]!==l||n[6]!==i||n[7]!==a||n[8]!==m?(h=(0,b.jsx)(f,{...a,...i,onKeyDown:m,ref:l}),n[4]=f,n[5]=l,n[6]=i,n[7]=a,n[8]=m,n[9]=h):h=n[9],h});pQ.displayName=`ThreadListItemMorePrimitive.Trigger`;var mQ=Z((e,t)=>{let n=J(21),{__scopeThreadListItemMore:r,portalProps:i,sideOffset:a,...o}=e,s=a===void 0?4:a,c=sQ(r),l=lQ(),u=ZZ(),d=dQ(),f=ct()===`rtl`?`ArrowRight`:`ArrowLeft`,p=al,m=bq,h;n[0]!==f||n[1]!==u?.moreRef||n[2]!==l||n[3]!==d?(h=e=>{d&&e.key===f&&(e.preventDefault(),l(!1),u?.moreRef.current?.focus())},n[0]=f,n[1]=u?.moreRef,n[2]=l,n[3]=d,n[4]=h):h=n[4];let g=P(o.onKeyDown,h),_;n[5]!==u?.moreRef||n[6]!==d?(_=()=>{d&&u?.moreRef.current?.focus()},n[5]=u?.moreRef,n[6]=d,n[7]=_):_=n[7];let v=P(o.onEscapeKeyDown,_),y;n[8]!==m||n[9]!==t||n[10]!==o||n[11]!==c||n[12]!==s||n[13]!==g||n[14]!==v?(y=(0,b.jsx)(m,{...c,...o,onKeyDown:g,onEscapeKeyDown:v,ref:t,sideOffset:s}),n[8]=m,n[9]=t,n[10]=o,n[11]=c,n[12]=s,n[13]=g,n[14]=v,n[15]=y):y=n[15];let x;return n[16]!==i||n[17]!==c||n[18]!==p.Portal||n[19]!==y?(x=(0,b.jsx)(p.Portal,{...c,...i,children:y}),n[16]=i,n[17]=c,n[18]=p.Portal,n[19]=y,n[20]=x):x=n[20],x});mQ.displayName=`ThreadListItemMorePrimitive.Content`;var hQ=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeThreadListItemMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=sQ(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(xq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});hQ.displayName=`ThreadListItemMorePrimitive.Item`;var gQ=Z((e,t)=>{let n=J(7),r,i;n[0]===e?(r=n[1],i=n[2]):({__scopeThreadListItemMore:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a=sQ(r),o;return n[3]!==t||n[4]!==i||n[5]!==a?(o=(0,b.jsx)(Sq,{...a,...i,ref:t}),n[3]=t,n[4]=i,n[5]=a,n[6]=o):o=n[6],o});gQ.displayName=`ThreadListItemMorePrimitive.Separator`;var _Q=FK({Content:()=>mQ,Item:()=>hQ,Root:()=>fQ,Separator:()=>gQ,Trigger:()=>pQ}),vQ=(e,t)=>{let n=J(5),r=Y(null),i=Y(null),a,o;n[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=()=>()=>{i.current?.()},o=[],n[0]=a,n[1]=o):(a=n[0],o=n[1]),X(a,o);let s;return n[2]!==e||n[3]!==t?(s=()=>{i.current?.(),(function(){if(r.current||!e.current)return;let t=e.current;for(;t;){let{overflowY:e}=getComputedStyle(t);if(e===`scroll`||e===`auto`){r.current=t;break}t=t.parentElement}})();let n=r.current;if(!n)return;let a=n.scrollTop,o=n.style.scrollbarWidth,s=getComputedStyle(n),c=s.direction===`rtl`?`paddingLeft`:`paddingRight`,l=n.style[c],u=n.offsetWidth-n.clientWidth-parseFloat(s.borderLeftWidth)-parseFloat(s.borderRightWidth),d=n.ownerDocument,f=(n===d.documentElement||n===d.body)&&u<=0?(d.defaultView?.innerWidth??0)-d.documentElement.clientWidth:u;n.style.scrollbarWidth=`none`,f>0&&(n.style[c]=`${parseFloat(s[c])+f}px`);let p=()=>{n.style.scrollbarWidth=o,n.style[c]=l},m=()=>n.scrollTop=a;n.addEventListener(`scroll`,m);let h=setTimeout(()=>{n.removeEventListener(`scroll`,m),p(),i.current=null},t);i.current=()=>{clearTimeout(h),n.removeEventListener(`scroll`,m),p()}},n[2]=e,n[3]=t,n[4]=s):s=n[4],s},yQ=()=>{let e=J(3),t=$(bQ),n=$(xQ),r=t!==void 0&&t.completedAt===void 0&&n,[i,a]=pN(SQ),o,s;if(e[0]===r?(o=e[1],s=e[2]):(o=()=>{if(!r)return;a(Date.now());let e=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(e)},s=[r],e[0]=r,e[1]=o,e[2]=s),X(o,s),t!==void 0){if(t.completedAt!==void 0)return Math.max(0,t.completedAt-t.startedAt);if(r)return Math.max(0,i-t.startedAt)}};function bQ(e){let t=e.optional.part;return t?.type===`tool-call`?t.timing:void 0}function xQ(e){let t=e.optional.part;return t?.type===`tool-call`&&t.status.type===`running`}function SQ(){return Date.now()}var CQ=FK({AssistantRuntimeImpl:()=>XV,BaseAssistantRuntimeCore:()=>tH,CompositeContextProvider:()=>MI,DefaultThreadComposerRuntimeCore:()=>wH,MessageRepository:()=>fH,ThreadRuntimeImpl:()=>BV,getAutoStatus:()=>OB,splitLocalRuntimeOptions:()=>lK,useComposerInputPluginRegistryOptional:()=>Kq,useSmooth:()=>nX,useSmoothStatus:()=>YY,withSmoothContextProvider:()=>qY}),wQ=(e,t)=>`${e}:${t}`,TQ=e=>({id:e,status:`idle`}),EQ=e=>({threadId:e,metadata:TQ(e),messages:[],streamingMessageIndex:void 0,toolExecutions:{},runStatus:`idle`,queue:{steering:[],followUp:[]},contextUsage:void 0,compaction:{active:!1},retry:{active:!1,attempt:0},hostUiRequests:[],readiness:void 0,lastError:void 0,loadState:`pending`,lastSeq:0}),DQ=e=>e?.role===`assistant`,OQ=(e,t)=>e.status===t?e:{...e,status:t},kQ=(e,t,n)=>e.compactionActive===t.active&&e.retryActive===n.active&&e.retryAttempt===n.attempt?e:{...e,compactionActive:t.active,retryActive:n.active,retryAttempt:n.attempt},AQ=(e,t)=>{let n=t.metadata.status===`running`?`running`:t.metadata.status===`failed`?`failed`:`idle`,r=n!==`running`,i=t.seq!==void 0&&t.seq<e.lastSeq,a=t.metadata.compactionActive??(!r&&e.compaction.active),o=t.metadata.retryActive??(!r&&e.retry.active),s=i?e.compaction:a?{...e.compaction,active:!0}:{active:!1},c=i?e.retry:o?{active:!0,attempt:t.metadata.retryAttempt??e.retry.attempt}:{active:!1,attempt:0};return{...e,metadata:kQ(t.metadata,s,c),messages:t.messages,streamingMessageIndex:void 0,toolExecutions:{},runStatus:n,compaction:s,retry:c,queue:{steering:(t.metadata.queuedMessages??[]).filter(e=>e.mode===`steer`).map(e=>e.content),followUp:(t.metadata.queuedMessages??[]).filter(e=>e.mode===`followUp`).map(e=>e.content)},contextUsage:t.metadata.contextUsage??e.contextUsage,hostUiRequests:t.hostUiRequests??[],readiness:t.readiness??e.readiness,lastError:t.lastError,loadState:`loaded`}},jQ=(e,t,n)=>{let r=e.slice();return r[t]=n,r},MQ=(e,t,n)=>({...e,toolExecutions:{...e.toolExecutions,[t]:{toolCallId:t,status:`running`,...e.toolExecutions[t],...n}}}),NQ=(e,t)=>e.hostUiRequests.some(e=>e.id===t)?{...e,hostUiRequests:e.hostUiRequests.filter(e=>e.id!==t)}:e,PQ=(e,t)=>{if(t.type!==`snapshot`&&t.type!==`error`&&t.seq<=e.lastSeq)return e;let n=n=>n===e&&t.seq<=e.lastSeq?n:{...n,lastSeq:Math.max(e.lastSeq,t.seq)};switch(t.type){case`snapshot`:return n(AQ(e,t.snapshot));case`agent_start`:return n({...e,runStatus:`running`,lastError:void 0,metadata:OQ(e.metadata,`running`)});case`agent_end`:{let r=t.willRetry===!0;return n({...e,runStatus:r?`running`:`idle`,streamingMessageIndex:void 0,metadata:OQ(e.metadata,r?`running`:`idle`)})}case`message_start`:{let r=[...e.messages,t.message];return n({...e,messages:r,streamingMessageIndex:DQ(t.message)?r.length-1:e.streamingMessageIndex})}case`message_update`:{if(e.streamingMessageIndex!==void 0&&e.streamingMessageIndex<e.messages.length)return n({...e,messages:jQ(e.messages,e.streamingMessageIndex,t.message)});let r=[...e.messages,t.message];return n({...e,messages:r,streamingMessageIndex:r.length-1})}case`message_end`:return e.streamingMessageIndex!==void 0&&e.streamingMessageIndex<e.messages.length?n({...e,messages:jQ(e.messages,e.streamingMessageIndex,t.message),streamingMessageIndex:void 0}):n({...e,streamingMessageIndex:void 0});case`tool_execution_start`:return n(MQ(e,t.toolCallId,{toolName:t.toolName,args:t.args,status:`running`}));case`tool_execution_update`:return n(MQ(e,t.toolCallId,{...t.toolName===void 0?{}:{toolName:t.toolName},partialResult:t.partialResult,status:`running`}));case`tool_execution_end`:return n(MQ(e,t.toolCallId,{partialResult:t.result,status:t.isError?`error`:`complete`}));case`queue_update`:return n({...e,queue:{steering:t.steering,followUp:t.followUp}});case`compaction_start`:{let r={active:!0,reason:t.reason};return n({...e,compaction:r,metadata:kQ(e.metadata,r,e.retry)})}case`compaction_end`:{let t={active:!1};return n({...e,compaction:t,metadata:kQ(e.metadata,t,e.retry)})}case`auto_retry_start`:{let r={active:!0,attempt:t.attempt};return n({...e,retry:r,metadata:kQ(e.metadata,e.compaction,r)})}case`auto_retry_end`:{let t={active:!1,attempt:0};return n({...e,retry:t,metadata:kQ(e.metadata,e.compaction,t)})}case`context_usage`:return n({...e,contextUsage:t.contextUsage});case`session_info_changed`:{let r={...e.metadata};return t.name===void 0?delete r.title:r.title=t.name,n({...e,metadata:r})}case`thinking_level_changed`:return n({...e,metadata:{...e.metadata,config:{...e.metadata.config,thinkingLevel:t.level}}});case`extension_ui_request`:return e.hostUiRequests.some(e=>e.id===t.request.id)?n(e):n({...e,hostUiRequests:[...e.hostUiRequests,t.request]});case`extension_ui_resolved`:return n(NQ(e,t.requestId));case`error`:return n({...e,lastError:t.error,runStatus:`failed`,metadata:OQ(e.metadata,`failed`)});case`agent_settled`:case`entry_appended`:return n(e);default:return n(e)}},FQ=e=>{let t=new Map,n=[];for(let r of e)r.toolCallId!==void 0&&LQ(r)?t.has(r.toolCallId)?n.push(r):t.set(r.toolCallId,r):n.push(r);return{toolAssociated:t,freeStanding:n}},IQ=(e,t)=>({requestId:e,confirmed:t}),LQ=e=>{switch(e.kind){case`confirm`:return{id:e.id,prompt:`${e.title}\n${e.message}`};case`select`:return e.options.length===0?void 0:{id:e.id,prompt:e.title,display:`select`,options:e.options.map((e,t)=>({id:String(t),kind:`_${t}`,label:e}))};case`input`:case`editor`:return{id:e.id,prompt:e.title,display:`text`}}},RQ=(e,t)=>{if(e.kind===`confirm`)return IQ(e.id,t.approved);if(!t.approved)return{requestId:e.id,dismissed:!0};let n=e.kind===`select`?e.options.find((e,n)=>String(n)===t.optionId):t.text;if(n===void 0)throw Error(`Pi ${e.kind} request "${e.id}" was not answered with ${e.kind===`select`?`one of its options`:`text`}`);return{requestId:e.id,value:n}},zQ=e=>{if(typeof e==`string`)return e;if(typeof e==`object`&&e){if(e.dismissed)return;if(typeof e.value==`string`)return e.value}},BQ=(e,t)=>{let n=zQ(t);return n===void 0?{requestId:e,dismissed:!0}:{requestId:e,value:n}};function VQ(e){let t=e.match(/^data:([^;,]+)(?:;[^;,]+)*;base64,(.*)$/i);return t?{mimeType:t[1].toLowerCase(),data:t[2]}:null}function HQ(e,t,n,...r){if(!n)return;let i=n=>{try{console.error(`[${e}] ${t} callback threw an error`,n)}catch{}};try{let e=n(...r);if(e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`)return Promise.resolve(e).then(()=>void 0,e=>i(e))}catch(e){i(e)}}var UQ=e=>`pi-msg:${e}`,WQ=e=>`pi-step:${e}`,GQ=(e,t)=>/^data:/i.test(e)?e:`data:${t};base64,${e}`,KQ=e=>new Date(typeof e.timestamp==`number`?e.timestamp:0),qQ=e=>{if(!e)return{};let t=e.filter(e=>e.type===`text`).map(e=>e.text).join(``);return e.every(e=>e.type===`text`)?{result:t}:{result:t,modelContent:e.flatMap(e=>{if(e.type===`text`)return[{type:`text`,text:e.text}];let t=VQ(e.data);return[{type:`file`,data:t?.data??e.data,mediaType:t?.mimeType??e.mimeType}]})}},JQ=e=>{if(e==null)return;let t=e.content;if(Array.isArray(t))return t.filter(e=>typeof e==`object`&&!!e&&(e.type===`text`&&typeof e.text==`string`||e.type===`image`&&typeof e.data==`string`&&typeof e.mimeType==`string`))},YQ=e=>typeof e==`string`?[{type:`text`,text:e}]:e.map(e=>e.type===`image`?{type:`image`,image:GQ(e.data,e.mimeType)}:{type:`text`,text:e.text}),XQ=(e,t)=>({type:`data`,name:e,data:t}),ZQ=e=>{let t=new Map;for(let n of e){if(n.role!==`toolResult`)continue;let e=n;t.set(e.toolCallId,{...qQ(JQ({content:e.content})),isError:e.isError,details:e.details})}return t},QQ=(e,t,n,r,i,a)=>{let o=WQ(n);e.lastAssistant=t,e.steps.push({messageId:o,usage:{inputTokens:t.usage?.input??0,outputTokens:t.usage?.output??0}});for(let n of t.content)if(n.type===`text`)e.parts.push({type:`text`,text:n.text,parentId:o});else if(n.type===`thinking`){let t=n.thinking||(n.redacted?`[reasoning redacted]`:``);e.parts.push({type:`reasoning`,text:t,parentId:o})}else if(n.type===`toolCall`){let t=i.get(n.id),s=r.toolExecutions[n.id],c=t??qQ(JQ(s?.partialResult)),l=t?.isError??s?.status===`error`,u=a.get(n.id),d=u&&LQ(u),f={type:`tool-call`,toolCallId:n.id,toolName:n.name,args:n.arguments??{},argsText:JSON.stringify(n.arguments??{}),parentId:o,...c.result===void 0?{}:{result:c.result},...c.modelContent===void 0?{}:{modelContent:c.modelContent},...l?{isError:!0}:{},...d?{approval:d}:{}};d&&(e.hasPendingHostUi=!0),e.parts.push(f)}},$Q=(e,t,n)=>{let r=e.lastAssistant,i=e$(e,t,n);return{id:UQ(e.firstIndex),role:`assistant`,createdAt:KQ(r),content:e.parts,...i?{status:i}:{},metadata:{steps:e.steps,custom:{pi:{provider:r.provider,model:r.model,api:r.api,usage:r.usage,stopReason:r.stopReason,...r.errorMessage?{errorMessage:r.errorMessage}:{}}}}}},e$=(e,t,n)=>{if(e.hasPendingHostUi)return{type:`requires-action`,reason:`interrupt`};let r=e.lastAssistant;return t.runStatus===`running`&&n&&r.stopReason!==`error`&&r.stopReason!==`aborted`?{type:`running`}:r.stopReason===`error`?{type:`incomplete`,reason:`error`,...r.errorMessage?{error:r.errorMessage}:{}}:r.stopReason===`aborted`?{type:`incomplete`,reason:`cancelled`}:r.stopReason===`length`?{type:`incomplete`,reason:`length`}:{type:`complete`,reason:`stop`}},t$=e=>{let{messages:t}=e,n=ZQ(t),r=FQ(e.hostUiRequests).toolAssociated,i=[],a=null,o=t=>{a&&=(i.push($Q(a,e,t)),null)};return t.forEach((s,c)=>{let l=c===t.length-1;switch(s.role){case`assistant`:a||={firstIndex:c,parts:[],steps:[],lastAssistant:s,hasPendingHostUi:!1},QQ(a,s,c,e,n,r),l&&o(!0);break;case`toolResult`:break;case`user`:o(!1),i.push({id:UQ(c),role:`user`,createdAt:KQ(s),content:YQ(s.content)});break;case`bashExecution`:{o(!1);let e=s;i.push(n$(c,e,`pi-bash-execution`,{command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath}));break}case`custom`:{o(!1);let e=s;if(!e.display)break;i.push({id:UQ(c),role:`assistant`,createdAt:KQ(e),content:[XQ(`pi-custom-message`,{customType:e.customType,details:e.details}),...YQ(e.content)]});break}case`branchSummary`:{o(!1);let e=s;i.push(n$(c,e,`pi-branch-summary`,{summary:e.summary,fromId:e.fromId}));break}case`compactionSummary`:{o(!1);let e=s;i.push(n$(c,e,`pi-compaction-summary`,{summary:e.summary,tokensBefore:e.tokensBefore}));break}default:o(!1),i.push(n$(c,s,`pi-unsupported-message`,{role:s.role,message:s}))}}),o(!0),i},n$=(e,t,n,r)=>({id:UQ(e),role:`assistant`,createdAt:KQ(t),content:[XQ(n,r)]}),r$=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()===t.getTime():void 0,i$=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype,a$=(e,t)=>{if(e===t)return!0;let n=r$(e,t);if(n!==void 0)return n;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!a$(e[n],t[n]))return!1;return!0}if(i$(e)||i$(t)){if(!i$(e)||!i$(t))return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!a$(e[r],t[r]))return!1;return!0}return!1},o$=(e,t)=>e.id===t.id&&e.role===t.role&&a$(e.createdAt,t.createdAt)&&a$(e.content,t.content)&&a$(e.status,t.status)&&a$(e.metadata,t.metadata),s$=(e,t)=>{let n=e.length!==t.length,r=e.map((e,r)=>{let i=t[r];return i&&o$(e,i)?i:(n=!0,e)});return n?r:t},c$=(e,t)=>s$(t$(e),t),l$={snapshot:!0,agent_start:!0,agent_end:!0,agent_settled:!0,turn_start:!0,turn_end:!0,message_start:!0,message_update:!0,message_end:!0,tool_execution_start:!0,tool_execution_update:!0,tool_execution_end:!0,queue_update:!0,compaction_start:!0,compaction_end:!0,entry_appended:!0,auto_retry_start:!0,auto_retry_end:!0,session_info_changed:!0,thinking_level_changed:!0,context_usage:!0,extension_ui_request:!0,extension_ui_resolved:!0,error:!0},u$=e=>Object.prototype.hasOwnProperty.call(l$,e),d$=e=>e instanceof Error?e.message:String(e),f$=e=>{if(typeof globalThis.requestAnimationFrame==`function`){globalThis.requestAnimationFrame(()=>e());return}setTimeout(e,16)},p$=e=>{for(let t of e)try{t()}catch(e){console.error(`[react-pi] Listener threw an error`,e)}},m$=new Set([`snapshot`,`agent_start`,`agent_end`,`message_start`,`message_update`,`message_end`,`tool_execution_update`,`tool_execution_end`,`extension_ui_request`,`extension_ui_resolved`]),h$=new Set([`message_update`,`tool_execution_update`]),g$=new Set([`snapshot`,`agent_start`,`agent_end`,`queue_update`,`compaction_start`,`compaction_end`,`auto_retry_start`,`auto_retry_end`,`session_info_changed`,`thinking_level_changed`,`context_usage`,`extension_ui_request`,`extension_ui_resolved`,`error`]),_$=e=>{let t=/^data:([^;,]+)(?:;base64)?,(.*)$/is.exec(e);return t?{type:`image`,mimeType:t[1].toLowerCase(),data:t[2]}:{type:`image`,mimeType:`image/png`,data:e}},v$=e=>[...e.content,...e.attachments?.flatMap(e=>e.content??[])??[]],y$=(e,t)=>{let n=v$(e),r=[],i=[];for(let e of n)e.type===`text`?r.push(e.text):e.type===`image`&&i.push(_$(e.image));return{content:r.join(`
94
94
 
95
- `),...i.length>0?{attachments:i}:{},...t?{streamingBehavior:t}:{}}},y$=e=>{let t=e.runConfig?.custom?.streamingBehavior;return t===`followUp`||t===`steer`?t:void 0},b$=e=>({role:`user`,content:e.attachments&&e.attachments.length>0?[{type:`text`,text:e.content},...e.attachments]:e.content,timestamp:Date.now()}),x$=e=>{if(e.role!==`user`)return null;let t=e.content;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
96
- `):null},S$=e=>e.runStatus===`running`&&e.metadata.status===`running`?e:{...e,runStatus:`running`,lastError:void 0,metadata:e.metadata.status===`running`?e.metadata:{...e.metadata,status:`running`}},C$=class{state;stateSnapshot;projectedMessages=[];messageRepository=cH.fromArray([]);version=0;allListeners=new Set;metadataListeners=new Set;messageListeners=new Set;connectionRetainers=0;optimisticUserMessages=[];unsubscribeFromEvents=null;disconnectTimer=null;loadPromise=null;messageFlushScheduled=!1;localSnapshotSeq=0;client;threadId;options;constructor(e,t,n={}){this.client=e,this.threadId=t,this.options=n,this.state=TQ(t),this.stateSnapshot=this.state}getState(){return this.state}getStateSnapshot(){return this.stateSnapshot}getProjectedMessages(){return this.projectedMessages}getMessageRepository(){return this.messageRepository}getVersion(){return this.version}connect(){return this.connectionRetainers+=1,this.ensureEventSubscription({includeSnapshot:this.state.loadState!==`loaded`}),()=>{this.connectionRetainers=Math.max(0,this.connectionRetainers-1),this.maybeDisconnectFromEvents()}}subscribe(e){return this.allListeners.add(e),()=>{this.allListeners.delete(e),this.maybeDisconnectFromEvents()}}subscribeMetadata(e){return this.metadataListeners.add(e),()=>{this.metadataListeners.delete(e),this.maybeDisconnectFromEvents()}}subscribeMessages(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e),this.maybeDisconnectFromEvents()}}dispose(){this.clearDisconnectTimer(),this.unsubscribeFromEvents?.(),this.unsubscribeFromEvents=null,this.allListeners.clear(),this.metadataListeners.clear(),this.messageListeners.clear()}ensureEventSubscription(e){this.clearDisconnectTimer(),!this.unsubscribeFromEvents&&(this.unsubscribeFromEvents=this.client.subscribe(this.threadId,e=>{e.threadId===this.threadId&&this.dispatch(e)},e))}hasConsumers(){return this.connectionRetainers>0||this.allListeners.size>0||this.metadataListeners.size>0||this.messageListeners.size>0}maybeDisconnectFromEvents(){this.hasConsumers()||(this.disconnectTimer||=setTimeout(()=>{this.disconnectTimer=null,!this.hasConsumers()&&(this.unsubscribeFromEvents?.(),this.unsubscribeFromEvents=null)},3e4))}clearDisconnectTimer(){this.disconnectTimer&&=(clearTimeout(this.disconnectTimer),null)}async load(e=!1){if(this.loadPromise&&!e)return this.loadPromise;this.setState({...this.state,loadState:`loading`});let t=this.client.getThread(this.threadId).then(e=>{this.loadPromise===t&&this.applySnapshot(e)}).catch(e=>{throw this.loadPromise===t&&this.setState({...this.state,loadState:`loaded`,lastError:u$(e)}),e}).finally(()=>{this.loadPromise===t&&(this.loadPromise=null)});return this.loadPromise=t,t}refresh(){return this.load(!0)}refreshInBackground(){this.loadPromise||this.refresh().catch(()=>{})}async sendMessage(e,t){if(e.role!==`user`)throw Error(`Pi only supports sending user messages`);let n=this.state.runStatus===`running`,r=t?.streamingBehavior??y$(e)??(n?`followUp`:void 0),i=v$(e,r);if(this.ensureEventSubscription({includeSnapshot:!1}),n)return this.sendQueued(i,r??`followUp`);let a=b$(i);this.optimisticUserMessages.push({message:a,baseMessageCount:this.state.messages.length}),this.setState(S$(this.state)),this.recomputeProjectedMessagesAndNotify();try{await this.client.sendMessage(this.threadId,i)}catch(e){let t=this.optimisticUserMessages.findIndex(e=>e.message===a);throw t!==-1&&this.optimisticUserMessages.splice(t,1),this.recomputeProjectedMessagesAndNotify(),this.setState({...this.state,lastError:u$(e),runStatus:`failed`,metadata:{...this.state.metadata,status:`failed`}}),e}}async sendQueued(e,t){let n=t===`steer`?`steering`:`followUp`,r={...this.state.queue,[n]:[...this.state.queue[n],e.content]};this.setState({...this.state,queue:r});try{await this.client.sendMessage(this.threadId,e)}catch(t){let i=this.state.queue!==r,a=this.state.queue[n],o=i?-1:a.lastIndexOf(e.content);throw this.setState({...this.state,lastError:u$(t),...o===-1?{}:{queue:{...this.state.queue,[n]:a.filter((e,t)=>t!==o)}}}),t}}async clearQueue(){let e=this.state.queue,t=await this.client.clearQueue(this.threadId);return this.state.queue===e&&(e.steering.length>0||e.followUp.length>0)&&this.setState({...this.state,queue:{steering:[],followUp:[]}}),t}async cancel(){try{await this.client.cancelRun(this.threadId)}catch(e){throw this.setState({...this.state,lastError:u$(e)}),e}}async setModel(e){try{await this.client.setModel(this.threadId,e)}catch(e){throw this.setState({...this.state,lastError:u$(e)}),e}await this.refresh()}async setThinkingLevel(e){try{await this.client.setThinkingLevel(this.threadId,e)}catch(e){throw this.setState({...this.state,lastError:u$(e)}),e}await this.refresh()}async respondToToolApproval(e,t){let n=this.state.hostUiRequests.find(t=>t.id===e);await this.respond(n?LQ(n,{approvalId:e,approved:t}):FQ(e,t))}async resumeToolCall(e,t){let n=this.state.hostUiRequests.find(t=>t.toolCallId===e);if(!n)throw Error(`No pending host-UI request for tool call "${e}"`);n.kind===`confirm`?await this.respond(FQ(n.id,t===!0)):await this.respond(zQ(n.id,t))}async respondToHostUiRequest(e){await this.respond(e)}async respond(e){try{await this.client.respondToHostUiRequest(this.threadId,e)}catch(e){throw this.setState({...this.state,lastError:u$(e)}),e}let t=MQ(this.state,e.requestId);t!==this.state&&(this.setState(t),this.recomputeProjectedMessagesAndNotify())}applySnapshot(e){this.dispatch({type:`snapshot`,snapshot:e,threadId:this.threadId,seq:this.localSnapshotSeq})}dispatch(e){let t=NQ(this.state,e),n=t!==this.state;n&&(this.state=t),this.reconcileOptimisticUserMessages(),n&&h$.has(e.type)&&this.notifyMetadataListeners(),n&&p$.has(e.type)&&(m$.has(e.type)?this.scheduleProjectedMessageFlush():this.recomputeProjectedMessagesAndNotify()),(!l$(e.type)||e.type===`entry_appended`&&e.entry?.type!==`custom`)&&this.refreshInBackground()}setState(e){e!==this.state&&(this.state=e,this.notifyMetadataListeners())}projectedInputMessages(){return[...this.state.messages,...this.optimisticUserMessages.map(e=>e.message)]}reconcileOptimisticUserMessages(){if(this.optimisticUserMessages.length===0)return;let e=[];for(let t of this.optimisticUserMessages){let n=x$(t.message);this.state.messages.slice(t.baseMessageCount).some(e=>x$(e)===n)||e.push(t)}e.length!==this.optimisticUserMessages.length&&(this.optimisticUserMessages.length=0,this.optimisticUserMessages.push(...e))}projectMessages(){return s$({messages:this.projectedInputMessages(),toolExecutions:this.state.toolExecutions,runStatus:this.state.runStatus,hostUiRequests:this.state.hostUiRequests},this.projectedMessages)}recomputeProjectedMessagesAndNotify(){let e=this.projectMessages();if(e===this.projectedMessages){this.state!==this.stateSnapshot&&this.publishState();return}this.projectedMessages=e,this.messageRepository=cH.fromArray(e),this.notifyMessageListeners()}scheduleProjectedMessageFlush(){this.messageFlushScheduled||(this.messageFlushScheduled=!0,(this.options.scheduleNotify??d$)(()=>{this.messageFlushScheduled=!1,this.recomputeProjectedMessagesAndNotify()}))}bumpVersion(){this.version+=1}publishState(){this.stateSnapshot=this.state,this.bumpVersion(),f$(this.allListeners)}notifyMetadataListeners(){this.stateSnapshot=this.state,this.bumpVersion(),f$(this.metadataListeners),f$(this.allListeners)}notifyMessageListeners(){this.stateSnapshot=this.state,this.bumpVersion(),f$(this.messageListeners),f$(this.allListeners)}},w$=e=>{let t=Symbol(`${e} extras`),n=e=>typeof e==`object`&&!!e&&t in e;return{provide:e=>(Object.defineProperty(e,t,{value:!0,enumerable:!1,configurable:!0}),e),is:n,tryGet:e=>n(e)?e:void 0,assert:t=>{if(!n(t))throw Error(`The current thread is not backed by the ${e} runtime.`);return t}}},T$=e=>{let{provide:t,is:n,tryGet:r,assert:i}=e,a=e=>i(e.thread.getState().extras);function o(e,...t){let r=t.length>0,a=t[0];return $(t=>{let o=t.thread.extras;return n(o)?e?e(o):o:r?a:i(o)})}return{provide:t,is:n,tryGet:r,get:a,use:o}},E$=(e=>T$(w$(e)))(`usePiRuntime`),D$=TQ(`__pending__`),O$=[],k$=cH.fromArray([]),A$=e=>{let t=new Map,n=!1;return{client:e,controllers:t,get disposed(){return n},activate(){n=!1},dispose(){n=!0;for(let e of t.values())e.dispose()}}},j$=(e,t)=>{let n=e.controllers.get(t);if(n)return n;let r=new C$(e.client,t);return e.controllers.set(t,r),r},M$={getState:()=>D$,getProjectedMessages:()=>O$,getMessageRepository:()=>k$,getVersion:()=>0,subscribe:()=>()=>{},subscribeMetadata:()=>()=>{},subscribeMessages:()=>()=>{},connect:()=>()=>{},load:async()=>{},refresh:async()=>{},sendMessage:async()=>{},cancel:async()=>{},clearQueue:async()=>({steering:[],followUp:[]}),setModel:async()=>{},setThinkingLevel:async()=>{},respondToToolApproval:async()=>{},resumeToolCall:async()=>{},respondToHostUiRequest:async()=>{},dispose:()=>{}},N$=(e,t)=>{VQ(`react-pi`,`onError`,e,t)},P$=(e,t)=>{let{freeStanding:n}=PQ(t.hostUiRequests);return E$.provide({controller:e,state:t,metadata:t.metadata,status:t.runStatus===`failed`?`failed`:t.runStatus,readiness:t.readiness,contextUsage:t.contextUsage,hostUiRequests:n,allHostUiRequests:t.hostUiRequests,queue:t.queue,compaction:t.compaction,retry:t.retry,lastError:t.lastError,cancel:()=>e.cancel(),refresh:()=>e.refresh(),clearQueue:()=>e.clearQueue(),setModel:t=>e.setModel(t),setThinkingLevel:t=>e.setThinkingLevel(t),respondToHostUiRequest:t=>e.respondToHostUiRequest(t),respondToToolApproval:(t,n)=>e.respondToToolApproval(t,n),resumeToolCall:(t,n)=>e.resumeToolCall(t,n)})},F$=P$(M$,D$),I$=e=>e.getStateSnapshot?.()??e.getState(),L$=e=>{let t=(0,y.useCallback)(()=>I$(e),[e]);return(0,y.useSyncExternalStore)((0,y.useCallback)(t=>e.subscribe(t),[e]),t,t)},R$=e=>{let t=(0,y.useCallback)(()=>e.getMessageRepository(),[e]);return(0,y.useSyncExternalStore)((0,y.useCallback)(t=>e.subscribeMessages(t),[e]),t,t)},z$=(e,t)=>{let n=(0,y.useMemo)(()=>{let n;return()=>{let r=I$(e);return(!n||n.state!==r)&&(n={state:r,selection:t(r)}),n.selection}},[e,t]);return(0,y.useSyncExternalStore)((0,y.useCallback)(t=>e.subscribe(t),[e]),n,n)},B$=e=>e.runStatus===`running`||e.compaction.active||e.retry.active,V$=(e,t)=>{let n=L$(e),r=R$(e),{adapters:i,isDisabled:a,isSendDisabled:o,onError:s,suggestions:c,unstable_capabilities:l}=t,u=n.loadState===`loading`,d=B$(n),f=(0,y.useEffectEvent)(e=>{N$(s,e)});(0,y.useEffect)(()=>{e!==M$&&e.load().catch(f)},[e]),(0,y.useEffect)(()=>{if(e!==M$&&d)return e.connect()},[e,d]);let p=(0,y.useMemo)(()=>P$(e,n),[e,n]),m=(0,y.useMemo)(()=>({items:n.queue.followUp.map((e,t)=>({id:CQ(`followUp`,t),prompt:e,parts:[{type:`text`,text:e}]})),steerItems:n.queue.steering.map((e,t)=>({id:CQ(`steer`,t),prompt:e,parts:[{type:`text`,text:e}]})),enqueue:t=>{e.sendMessage(t).catch(e=>N$(s,e))},steer:t=>{e.sendMessage(t,{streamingBehavior:`steer`}).catch(e=>N$(s,e))},move:()=>{},edit:()=>{},remove:()=>{}}),[e,n.queue,s]);return(0,y.useMemo)(()=>({isDisabled:a,isSendDisabled:o,unstable_capabilities:l,suggestions:c,isLoading:u,isRunning:d,messageRepository:r,extras:p,queue:m,...i?{adapters:i}:{},onNew:async t=>{try{await e.sendMessage(t)}catch(e){throw N$(s,e),e}},onCancel:async()=>{try{try{await e.clearQueue()}finally{await e.cancel()}}catch(e){throw N$(s,e),e}},onRespondToToolApproval:async t=>{try{let n=e.getState().hostUiRequests.find(e=>e.id===t.approvalId);if(!n)throw Error(`No pending host-UI request "${t.approvalId}"`);await e.respondToHostUiRequest(LQ(n,t))}catch(e){throw N$(s,e),e}},onResumeToolCall:({toolCallId:t,payload:n})=>{e.resumeToolCall(t,n).catch(e=>N$(s,e))}}),[e,p,r,m,i,a,u,d,o,s,c,l])},H$=(e,t)=>({id:`pi-new-user:${t}`,role:`user`,createdAt:new Date,content:_$(e)}),U$=(e,t)=>{let n=Q(),{adapters:r,isDisabled:i,isSendDisabled:a,onError:o,suggestions:s,unstable_capabilities:c}=t,[l,u]=(0,y.useState)([]),d=(0,y.useRef)(0),f=(0,y.useMemo)(()=>cH.fromArray(l),[l]);return(0,y.useMemo)(()=>({isDisabled:i??!1,isSendDisabled:a,unstable_capabilities:c,suggestions:s,isLoading:!1,isRunning:!1,messageRepository:f,extras:F$,...r?{adapters:r}:{},onNew:async t=>{let r=H$(t,d.current++);u(e=>[...e,r]);let i=()=>{u(e=>e.filter(e=>e!==r))};try{let{remoteId:r,externalId:a}=await n.threadListItem.initialize();if(e.disposed){i();return}await j$(e,a??r).sendMessage(t),i()}catch(e){throw i(),N$(o,e),e}}}),[n,f,e,r,i,a,o,s,c])},W$=(e,t)=>{let n=$(e=>e.threadListItem),r=$(e=>e.threads.mainThreadId===e.threadListItem.id),i=n.externalId??n.remoteId,a=i?j$(e,i):M$,o=V$(r?a:M$,t),s=U$(e,t);return RH(i?o:s)},G$=e=>({status:e.archived?`archived`:`regular`,remoteId:e.id,externalId:e.id,...e.title===void 0?{}:{title:e.title},custom:{status:e.status,...e.workspacePath===void 0?{}:{workspacePath:e.workspacePath},...e.sessionFile===void 0?{}:{sessionFile:e.sessionFile},...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath}}}),K$=e=>{let{client:t}=e,n=(0,y.useMemo)(()=>A$(t),[t]);return(0,y.useEffect)(()=>(n.activate(),()=>n.dispose()),[n]),OU({allowNesting:!0,adapter:(0,y.useMemo)(()=>({list:async()=>({threads:(await t.listThreads({...e.workspacePath===void 0?{}:{workspacePath:e.workspacePath},...e.includeArchived===void 0?{}:{includeArchived:e.includeArchived}})).map(G$)}),rename:async(e,n)=>{await t.renameThread(e,n)},archive:async e=>{await t.archiveThread?.(e)},unarchive:async e=>{await t.unarchiveThread?.(e)},delete:async e=>{await t.deleteThread?.(e)},initialize:async()=>{let n=await t.createThread({...e.workspacePath===void 0?{}:{workspacePath:e.workspacePath}});return{remoteId:n.metadata.id,externalId:n.metadata.id}},generateTitle:async()=>new ReadableStream({start(e){e.close()}}),fetch:async e=>G$((await t.getThread(e)).metadata)}),[t,e.workspacePath,e.includeArchived]),...e.initialThreadId===void 0?{}:{initialThreadId:e.initialThreadId},...e.threadId===void 0?{}:{threadId:e.threadId},...e.onThreadIdChange===void 0?{}:{onThreadIdChange:e.onThreadIdChange},runtimeHook:()=>W$(n,e)})},q$=()=>E$.use(e=>e,F$),J$=()=>E$.use(e=>e.metadata,null);function Y$(e){return z$(E$.use(e=>e.controller,M$),e??(e=>e))}var X$=()=>{let e=E$.use(e=>e,void 0);return(0,y.useMemo)(()=>({requests:e?.hostUiRequests??[],respond:e?.respondToHostUiRequest??(async()=>{throw Error(`Pi runtime is not ready yet`)})}),[e])};function Z$({delayDuration:e=0,...t}){return(0,b.jsx)(Du,{"data-slot":`tooltip-provider`,delayDuration:e,...t})}function Q$({...e}){return(0,b.jsx)(Ou,{"data-slot":`tooltip`,...e})}function $$({...e}){return(0,b.jsx)(ku,{"data-slot":`tooltip-trigger`,...e})}function e1({className:e,sideOffset:t=0,children:n,...r}){return(0,b.jsx)(Au,{children:(0,b.jsxs)(ju,{"data-slot":`tooltip-content`,sideOffset:t,className:a(`z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95`,e),...r,children:[n,(0,b.jsx)(Mu,{className:`z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground`})]})})}function t1({...e}){return(0,b.jsx)(wr,{"data-slot":`dialog`,...e})}function n1({...e}){return(0,b.jsx)(Er,{"data-slot":`dialog-trigger`,...e})}function r1({...e}){return(0,b.jsx)(Ar,{"data-slot":`dialog-portal`,...e})}function i1({className:e,...t}){return(0,b.jsx)(Mr,{"data-slot":`dialog-overlay`,className:a(`fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0`,e),...t})}function a1({className:e,children:t,showCloseButton:n=!0,...r}){return(0,b.jsxs)(r1,{"data-slot":`dialog-portal`,children:[(0,b.jsx)(i1,{}),(0,b.jsxs)(Ir,{"data-slot":`dialog-content`,className:a(`fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg`,e),...r,children:[t,n&&(0,b.jsxs)(Gr,{"data-slot":`dialog-close`,className:`absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,children:[(0,b.jsx)(mp,{}),(0,b.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function o1({className:e,...t}){return(0,b.jsx)(`div`,{"data-slot":`dialog-header`,className:a(`flex flex-col gap-2 text-center sm:text-left`,e),...t})}function s1({className:e,showCloseButton:t=!1,children:n,...r}){return(0,b.jsxs)(`div`,{"data-slot":`dialog-footer`,className:a(`flex flex-col-reverse gap-2 sm:flex-row sm:justify-end`,e),...r,children:[n,t&&(0,b.jsx)(Gr,{asChild:!0,children:(0,b.jsx)(o,{variant:`outline`,children:`Close`})})]})}function c1({className:e,...t}){return(0,b.jsx)(Vr,{"data-slot":`dialog-title`,className:a(`text-lg leading-none font-semibold`,e),...t})}function l1({className:e,...t}){return(0,b.jsx)(Ur,{"data-slot":`dialog-description`,className:a(`text-sm text-muted-foreground`,e),...t})}function u1({className:e,size:t=`default`,...n}){return(0,b.jsx)(ti,{"data-slot":`avatar`,"data-size":t,className:a(`group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6`,e),...n})}function d1({className:e,...t}){return(0,b.jsx)(ri,{"data-slot":`avatar-image`,className:a(`aspect-square size-full`,e),...t})}function f1({className:e,...t}){return(0,b.jsx)(ai,{"data-slot":`avatar-fallback`,className:a(`flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs`,e),...t})}var p1=(0,y.forwardRef)(({children:e,tooltip:t,side:n=`bottom`,className:r,...i},s)=>(0,b.jsx)(Z$,{delayDuration:0,children:(0,b.jsxs)(Q$,{children:[(0,b.jsx)($$,{asChild:!0,children:(0,b.jsxs)(o,{variant:`ghost`,size:`icon`,...i,className:a(`aui-button-icon size-6 p-1 active:scale-90`,r),ref:s,children:[(0,b.jsx)(c,{children:e}),(0,b.jsx)(`span`,{className:`aui-sr-only sr-only`,children:t})]})}),(0,b.jsx)(e1,{side:n,children:t})]})}));p1.displayName=`TooltipIconButton`;var m1=e=>Symbol.iterator in e,h1=e=>`entries`in e,g1=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},_1=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function v1(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:m1(e)&&m1(t)?h1(e)&&h1(t)?g1(e,t):_1(e,t):g1({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function y1(e){let t=y.useRef(void 0);return n=>{let r=e(n);return v1(t.current,r)?t.current:t.current=r}}var b1=e=>{let[t,n]=(0,y.useState)(void 0);return(0,y.useEffect)(()=>{if(!e){n(void 0);return}let t=URL.createObjectURL(e);return n({file:e,url:t}),()=>{URL.revokeObjectURL(t)}},[e]),t!==void 0&&t.file===e?t.url:void 0},x1=()=>{let{file:e,src:t}=$(y1(e=>{if(e.attachment.type!==`image`)return{};if(e.attachment.file)return{file:e.attachment.file};let t=e.attachment.content?.filter(e=>e.type===`image`)[0]?.image;return t?{src:t}:{}}));return b1(e)??t},S1=({src:e})=>{let[t,n]=(0,y.useState)(!1);return(0,b.jsx)(`img`,{src:e,alt:`Attachment preview`,className:a(`block h-auto max-h-[80vh] w-auto max-w-full rounded-sm object-contain transition-opacity duration-300 motion-reduce:transition-none`,t?`aui-attachment-preview-image-loaded opacity-100`:`aui-attachment-preview-image-loading opacity-0`),onLoad:()=>n(!0)})},C1=({children:e})=>{let t=x1();return t?(0,b.jsxs)(t1,{children:[(0,b.jsx)(n1,{className:`aui-attachment-preview-trigger cursor-zoom-in`,asChild:!0,children:(0,y.isValidElement)(e)?e:(0,b.jsx)(`button`,{type:`button`,children:e})}),(0,b.jsxs)(a1,{className:`aui-attachment-preview-dialog-content [&>button]:bg-foreground/60 [&>button]:hover:bg-foreground/80 [&_svg]:text-background p-2 sm:max-w-3xl [&>button]:rounded-full [&>button]:p-1 [&>button]:opacity-100 [&>button]:ring-0!`,children:[(0,b.jsx)(c1,{className:`aui-sr-only sr-only`,children:`Image Attachment Preview`}),(0,b.jsx)(`div`,{className:`aui-attachment-preview bg-background relative mx-auto flex max-h-[80dvh] w-full items-center justify-center overflow-hidden rounded-sm`,children:(0,b.jsx)(S1,{src:t})})]})]}):e},w1=()=>{let e=x1();return(0,b.jsxs)(u1,{className:`aui-attachment-tile-avatar h-full w-full rounded-none`,children:[(0,b.jsx)(d1,{src:e,alt:`Attachment preview`,className:`aui-attachment-tile-image rounded-none object-cover`}),(0,b.jsx)(f1,{children:(0,b.jsx)(Lf,{className:`aui-attachment-tile-fallback-icon text-muted-foreground/80 size-6 stroke-[1.5]`})})]})},T1=()=>{let e=Q().attachment.source!==`message`,t=$(e=>e.attachment.type===`image`),n=$(e=>{let t=e.attachment.type;switch(t){case`image`:return`Image`;case`document`:return`Document`;case`file`:return`File`;default:return t}}),r=$(e=>e.attachment.status.type===`running`?`uploading`:e.attachment.status.type===`incomplete`&&e.attachment.status.reason===`error`?`error`:void 0),i=r===`uploading`,o=r===`error`,s=$(e=>e.attachment.status.type===`incomplete`&&e.attachment.status.reason===`error`?e.attachment.status.message??`Upload failed`:void 0);return(0,b.jsx)(Z$,{children:(0,b.jsxs)(Q$,{children:[(0,b.jsxs)(Nq.Root,{className:a(`aui-attachment-root relative`,e&&`animate-in fade-in-0 zoom-in-95 duration-200 motion-reduce:animate-none`,t&&!e&&`aui-attachment-root-message only:*:first:size-24`),children:[(0,b.jsx)(C1,{children:(0,b.jsx)($$,{asChild:!0,children:(0,b.jsxs)(`div`,{className:a(`aui-attachment-tile bg-muted hover:after:bg-foreground/10 focus-visible:ring-ring/50 relative size-14 cursor-pointer overflow-hidden rounded-[calc(var(--composer-radius,1rem)-var(--composer-padding,8px))] transition-transform outline-none after:pointer-events-none after:absolute after:inset-0 after:rounded-[inherit] after:ring-1 after:ring-black/10 after:transition-colors after:ring-inset focus-visible:ring-1 active:scale-[0.96] motion-reduce:transition-none dark:after:ring-white/10`,o&&`after:ring-destructive/60 dark:after:ring-destructive/60`),role:`button`,tabIndex:0,onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),e.currentTarget.click()):e.key===` `&&e.preventDefault()},onKeyUp:e=>{e.key===` `&&e.currentTarget.click()},"aria-label":`${n} attachment${o?`, upload failed`:i?`, uploading`:``}`,children:[(0,b.jsx)(w1,{}),i&&(0,b.jsx)(`div`,{"aria-hidden":`true`,className:`aui-attachment-tile-uploading bg-background/60 animate-in fade-in-0 absolute inset-0 flex items-center justify-center backdrop-blur-[2px] motion-reduce:animate-none`,children:(0,b.jsx)(Uf,{className:`text-muted-foreground size-4 animate-spin`})}),o&&(0,b.jsx)(`div`,{"aria-hidden":`true`,className:`aui-attachment-tile-error bg-background/70 animate-in fade-in-0 absolute inset-0 flex items-center justify-center backdrop-blur-[2px] motion-reduce:animate-none`,children:(0,b.jsx)(Ef,{className:`text-destructive size-4`})})]})})}),e&&(0,b.jsx)(E1,{})]}),(0,b.jsxs)(e1,{side:`top`,children:[(0,b.jsx)(Nq.Name,{}),s&&(0,b.jsx)(`p`,{className:`aui-attachment-error-message`,children:s})]})]})})},E1=()=>(0,b.jsx)(Nq.Remove,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Remove file`,className:`aui-attachment-tile-remove absolute end-1 top-1 size-5 rounded-full bg-black/50! text-white after:absolute after:-inset-1.5 hover:bg-black/70! hover:text-white! active:scale-[0.96] motion-reduce:transition-none`,side:`top`,children:(0,b.jsx)(mp,{className:`aui-attachment-remove-icon size-3 stroke-[2.5]`})})}),D1=()=>(0,b.jsx)(`div`,{className:`aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2 empty:hidden`,children:(0,b.jsx)(XX.Attachments,{children:()=>(0,b.jsx)(T1,{})})}),O1=()=>(0,b.jsx)(`div`,{className:`aui-composer-attachments flex w-full flex-row items-center gap-2 overflow-x-auto empty:hidden`,children:(0,b.jsx)(RY.Attachments,{children:()=>(0,b.jsx)(T1,{})})}),k1=()=>(0,b.jsx)(RY.AddAttachment,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Add Attachment`,side:`bottom`,variant:`ghost`,size:`icon`,className:`aui-composer-add-attachment text-muted-foreground hover:text-foreground hover:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 size-7 rounded-full active:scale-[0.96] motion-reduce:transition-none`,"aria-label":`Add Attachment`,children:(0,b.jsx)(Zf,{className:`aui-attachment-add-icon size-4`})})}),A1=v(`aui-file-root inline-flex items-center gap-3 rounded-lg transition-colors`,{variants:{variant:{outline:`border-border hover:bg-muted/50 border`,ghost:`hover:bg-muted/50`,muted:`bg-muted/50 hover:bg-muted/70`},size:{sm:`px-2.5 py-1.5 text-xs`,default:`px-3 py-2 text-sm`,lg:`px-4 py-3 text-base`}},defaultVariants:{variant:`outline`,size:`default`}});function j1(e){let t=e.toLowerCase();return t.startsWith(`image/`)?Bf:t===`application/pdf`?Lf:t===`application/json`?bf:t.startsWith(`text/`)?Lf:t.startsWith(`audio/`)?Kf:t.startsWith(`video/`)?fp:Rf}function M1(e,t){return t===`url`&&/^data:/i.test(e)?`data-uri`:t||(/^data:/i.test(e)?`data-uri`:/^https?:\/\//i.test(e)?`url`:`base64`)}function N1(e){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`),n=e.search(/[^A-Za-z\d+/]/);return n!==-1&&n!==e.length-t||e.length%4==1||t>0&&e.length%4!=0?0:Math.floor(e.length*3/4)-t}function P1(e){return N1(/[\t\n\f\r ]/.test(e)?e.replace(/[\t\n\f\r ]/g,``):e)}function F1(e){let t=e.indexOf(`#`),n=t<0?e.length:t,r=e.indexOf(`,`);if(r<0||r>=n)return 0;let i=e.slice(r+1,n);return/;base64$/i.test(e.slice(0,r))?(/[%\t\n\f\r ]/.test(i)&&(i=i.replace(/%([\da-f]{2})/gi,(e,t)=>String.fromCharCode(Number.parseInt(t,16))).replace(/[\t\n\f\r ]/g,``)),N1(i)):new TextEncoder().encode(i.replace(/%[\da-f]{2}/gi,`_`)).byteLength}function I1(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function L1({className:e,variant:t,size:n,children:r,...i}){return(0,b.jsx)(`div`,{"data-slot":`file-root`,"data-variant":t,"data-size":n,className:a(A1({variant:t,size:n,className:e})),...i,children:r})}function R1({mimeType:e,className:t,children:n,...r}){let i=e?j1(e):Rf;return(0,b.jsx)(`span`,{"data-slot":`file-icon`,className:a(`text-muted-foreground shrink-0`,t),...r,children:n??(0,b.jsx)(i,{className:`size-5`})})}function z1({className:e,children:t,...n}){return(0,b.jsx)(`span`,{"data-slot":`file-name`,className:a(`min-w-0 flex-1 truncate font-medium`,e),...n,children:t||`Unnamed file`})}function B1({bytes:e,className:t,...n}){return(0,b.jsx)(`span`,{"data-slot":`file-size`,className:a(`text-muted-foreground shrink-0`,t),...n,children:I1(e)})}function V1({data:e,mimeType:t,filename:n,sourceType:r,className:i,children:o,...s}){if(typeof e!=`string`)return null;let c=M1(e,r);if(c===`id`||c===`url`&&!/^(https?:\/\/|blob:)/i.test(e))return null;let l=c===`base64`?`data:${t};base64,${e}`:e;return(0,b.jsx)(`a`,{"data-slot":`file-download`,href:l,download:n||`download`,...c===`url`&&{target:`_blank`,rel:`noopener noreferrer`},className:a(`text-muted-foreground hover:bg-accent hover:text-accent-foreground shrink-0 rounded-md p-1 transition-colors`,i),"aria-label":o?void 0:`Download ${n||`file`}`,...s,children:o||(0,b.jsx)(Pf,{className:`size-4`})})}var H1=(0,y.memo)(({filename:e,data:t,mimeType:n,sourceType:r})=>{let i=M1(t,r);return(0,b.jsxs)(L1,{children:[(0,b.jsx)(R1,{mimeType:n}),(0,b.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,b.jsx)(z1,{children:e}),typeof t==`string`&&(i===`base64`||i===`data-uri`)&&(0,b.jsx)(B1,{bytes:i===`data-uri`?F1(t):P1(t),className:`text-xs`})]}),(0,b.jsx)(V1,{data:t,mimeType:n,...e!==void 0&&{filename:e},...r!==void 0&&{sourceType:r}})]})});H1.displayName=`File`,H1.Root=L1,H1.Icon=R1,H1.Name=z1,H1.Size=B1,H1.Download=V1;var U1=()=>{let e=$(e=>e.thread.suggestions),t=(0,y.useRef)(null),n=(0,y.useRef)(null),[r,i]=(0,y.useState)({left:!1,right:!1}),a=(0,y.useCallback)(()=>{let e=t.current;if(!e)return;let r=e.scrollWidth-e.clientWidth,a=Math.abs(e.scrollLeft),[o,s]=(n.current??=getComputedStyle(e).direction===`rtl`)?[r-a,a]:[a,r-a];i(e=>{let t={left:o>1,right:s>1};return e.left===t.left&&e.right===t.right?e:t})},[]);(0,y.useEffect)(()=>{a();let e=t.current;if(!e?.firstElementChild)return;let n=new ResizeObserver(a);return n.observe(e),n.observe(e.firstElementChild),()=>n.disconnect()},[a]);let o=`linear-gradient(to right, ${r.left?`transparent, black 2rem`:`black`}, ${r.right?`black calc(100% - 2rem), transparent`:`black`})`;return(0,b.jsx)(`div`,{ref:t,onScroll:a,className:`aui-thread-followup-suggestions -my-1 w-full [scrollbar-width:none] overflow-x-auto py-1 [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden`,style:{maskImage:o,WebkitMaskImage:o},children:(0,b.jsx)(`div`,{className:`mx-auto flex min-h-8 w-max items-center gap-2 px-0.5`,children:e.map((e,t)=>(0,b.jsxs)(PZ.Suggestion,{className:`aui-thread-followup-suggestion border-foreground/10 hover:bg-foreground/[0.03] hover:border-foreground/25 rounded-md border px-2.5 py-1 text-sm whitespace-nowrap transition-colors ease-in motion-reduce:transition-none`,prompt:e.prompt,send:!0,children:[e.title??e.prompt,e.label&&(0,b.jsx)(`span`,{className:`aui-thread-followup-suggestion-label text-muted-foreground ms-1`,children:e.label})]},t))})})},W1=()=>(0,b.jsx)(IL,{condition:e=>!e.thread.isEmpty&&!e.thread.isRunning&&e.thread.suggestions.length>0,children:(0,b.jsx)(U1,{})}),G1=e=>{switch(e){case`image/png`:return`png`;case`image/jpeg`:case`image/jpg`:return`jpg`;case`image/webp`:return`webp`;case`image/gif`:return`gif`;case`image/svg+xml`:return`svg`;default:return`png`}},K1=e=>{let t=e.indexOf(`,`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):``,i=n.match(/data:([^;]+)/i)?.[1]?.toLowerCase()??`application/octet-stream`;if(!/;base64/i.test(n)){let e=r.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return decodeURIComponent(e)}catch{return e}});return new Blob([e],{type:i})}let a;try{let e=r.replace(/%([\da-f]{2})/gi,(e,t)=>String.fromCharCode(Number.parseInt(t,16)));a=atob(e)}catch{return null}let o=new Uint8Array(a.length);for(let e=0;e<a.length;e++)o[e]=a.charCodeAt(e);return new Blob([o],{type:i})},q1=e=>e.match(/^data:([^;,]+)/i)?.[1]?.toLowerCase(),J1=e=>{if(typeof document>`u`)return;let t=G1(q1(e.image)),n=e.filename??`image.${t}`,r=/^data:/i.test(e.image),i=r?K1(e.image):null;if(r&&!i)return;let a=i?URL.createObjectURL(i):null,o=a??e.image,s=document.createElement(`a`);s.href=o,s.download=n,s.rel=`noopener`,document.body.appendChild(s),s.click(),document.body.removeChild(s),a&&setTimeout(()=>URL.revokeObjectURL(a),4e4)},Y1=async e=>{if(typeof navigator>`u`||!navigator.clipboard||typeof ClipboardItem>`u`)throw Error(`Clipboard API is not available in this environment.`);let t=/^data:/i.test(e.image)?K1(e.image):await fetch(e.image).then(e=>e.blob());if(!t)return;let n=q1(e.image)??t.type??`image/png`;await navigator.clipboard.write([new ClipboardItem({[n]:t})])},X1=v(`aui-image-root relative overflow-hidden rounded-lg`,{variants:{variant:{outline:`border-border border`,ghost:``,muted:`bg-muted/50`},size:{sm:`max-w-64`,default:`max-w-96`,lg:`max-w-[512px]`,full:`w-full`}},defaultVariants:{variant:`outline`,size:`default`}});function Z1({className:e,variant:t,size:n,children:r,...i}){return(0,b.jsx)(`div`,{"data-slot":`image-root`,"data-variant":t,"data-size":n,className:a(X1({variant:t,size:n,className:e})),...i,children:r})}function Q1({className:e,containerClassName:t,onLoad:n,onError:r,alt:i=`Image content`,src:o,...s}){let c=(0,y.useRef)(null),[l,u]=(0,y.useState)(void 0),[d,f]=(0,y.useState)(void 0),p=l===o,m=d===o;return(0,y.useEffect)(()=>{let e=c.current;typeof o==`string`&&e?.complete&&(e.naturalWidth>0?u(o):f(o))},[o]),(0,b.jsxs)(`div`,{"data-slot":`image-preview`,className:a(`relative min-h-32`,t),children:[!p&&!m&&(0,b.jsx)(`div`,{"data-slot":`image-preview-loading`,className:`bg-muted/50 absolute inset-0 flex items-center justify-center`,children:(0,b.jsx)(Bf,{className:`text-muted-foreground size-8 animate-pulse`})}),m?(0,b.jsx)(`div`,{"data-slot":`image-preview-error`,className:`bg-muted/50 flex min-h-32 items-center justify-center p-4`,children:(0,b.jsx)(zf,{className:`text-muted-foreground size-8`})}):(0,b.jsx)(`img`,{ref:c,src:o,alt:i,className:a(`block h-auto w-full object-contain`,!p&&`invisible`,e),onLoad:e=>{typeof o==`string`&&u(o),n?.(e)},onError:e=>{typeof o==`string`&&f(o),r?.(e)},...s})]})}function $1({className:e,children:t,...n}){return t?(0,b.jsx)(`span`,{"data-slot":`image-filename`,className:a(`text-muted-foreground block truncate px-2 py-1.5 text-xs`,e),...n,children:t}):null}function e0({src:e,alt:t=`Image preview`,children:n}){let[r,i]=(0,y.useState)(!1),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(null),c=(0,y.useCallback)(()=>i(!0),[]),l=(0,y.useCallback)(()=>{i(!1),a.current?.focus()},[]);return(0,y.useEffect)(()=>{if(!r)return;let e=e=>{if(e.key===`Escape`){l();return}if(e.key!==`Tab`)return;let t=s.current?.querySelectorAll(`a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])`),n=t?.[0],r=t?.[t.length-1];n&&r&&(e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus()))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[r,l]),(0,y.useEffect)(()=>{if(!r)return;let e=document.body.style.overflow;return document.body.style.overflow=`hidden`,()=>{document.body.style.overflow=e}},[r]),(0,y.useEffect)(()=>{r&&o.current?.focus()},[r]),(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(`div`,{ref:a,onClick:c,onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),e.currentTarget.click()):e.key===` `&&e.preventDefault()},onKeyUp:e=>{e.key===` `&&e.currentTarget.click()},role:`button`,tabIndex:0,className:`aui-image-zoom-trigger cursor-zoom-in`,"aria-label":`Click to zoom image`,children:n}),r&&(0,Ut.createPortal)((0,b.jsxs)(`div`,{ref:s,"data-slot":`image-zoom-overlay`,role:`dialog`,"aria-modal":`true`,className:`aui-image-zoom-overlay fade-in animate-in fixed inset-0 z-50 flex items-center justify-center bg-black/80 duration-200`,onClick:l,"aria-label":`Zoomed image`,children:[(0,b.jsx)(`img`,{"data-slot":`image-zoom-content`,src:e,alt:t,className:`aui-image-zoom-content fade-in zoom-in-95 animate-in max-h-[90vh] max-w-[90vw] cursor-zoom-out object-contain duration-200`,onClick:e=>{e.stopPropagation(),l()}}),(0,b.jsx)(`button`,{ref:o,type:`button`,"aria-label":`Close zoomed image`,onClick:e=>{e.stopPropagation(),l()},className:`text-muted-foreground hover:text-foreground bg-background/80 absolute end-4 top-4 cursor-pointer rounded-md p-2`,children:(0,b.jsx)(mp,{className:`size-5`})})]}),document.body)]})}function t0({className:e}){return(0,b.jsxs)(`div`,{"data-slot":`image-generating`,className:a(`bg-muted/50 flex min-h-32 items-center justify-center p-4`,e),children:[(0,b.jsx)(Uf,{className:`text-muted-foreground size-8 animate-spin`}),(0,b.jsx)(`span`,{className:`sr-only`,children:`Generating image…`})]})}function n0({className:e,reason:t}){return(0,b.jsxs)(`div`,{"data-slot":`image-content-filter-error`,className:a(`bg-muted/50 flex min-h-32 flex-col items-center justify-center gap-2 p-4 text-center`,e),children:[(0,b.jsx)(tp,{className:`text-muted-foreground size-8`}),(0,b.jsx)(`p`,{className:`text-sm font-medium`,children:`Image could not be generated`}),t&&(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs`,children:t})]})}function r0({onRegenerate:e}){let[t,n]=(0,y.useState)(!1);return(0,b.jsx)(`button`,{type:`button`,onClick:async()=>{n(!0);try{await e()}catch{}finally{n(!1)}},disabled:t,"data-slot":`image-regenerate`,"aria-label":`Regenerate image`,className:`hover:bg-muted inline-flex size-7 items-center justify-center rounded disabled:opacity-50`,children:(0,b.jsx)(Qf,{className:a(`size-4`,t&&`animate-spin`)})})}function i0({part:e,onRegenerate:t,className:n}){return(0,b.jsxs)(`div`,{"data-slot":`image-actions`,className:a(`flex items-center gap-1 p-1`,n),children:[(0,b.jsx)(`button`,{type:`button`,onClick:()=>J1(e),"data-slot":`image-download`,"aria-label":`Download image`,className:`hover:bg-muted inline-flex size-7 items-center justify-center rounded`,children:(0,b.jsx)(Pf,{className:`size-4`})}),(0,b.jsx)(`button`,{type:`button`,onClick:()=>{Y1(e).catch(()=>{})},"data-slot":`image-copy`,"aria-label":`Copy image`,className:`hover:bg-muted inline-flex size-7 items-center justify-center rounded`,children:(0,b.jsx)(Mf,{className:`size-4`})}),t&&(0,b.jsx)(r0,{onRegenerate:t})]})}var a0=(0,y.memo)(e=>{let{image:t,filename:n,status:r}=e;return r?.type===`running`?(0,b.jsxs)(Z1,{children:[(0,b.jsx)(t0,{}),(0,b.jsx)($1,{children:n})]}):r?.type===`incomplete`&&r.reason===`content-filter`?(0,b.jsx)(Z1,{children:(0,b.jsx)(n0,{reason:`The provider blocked this image.`})}):(0,b.jsxs)(Z1,{children:[(0,b.jsx)(e0,{src:t,alt:n||`Image content`,children:(0,b.jsx)(Q1,{src:t,alt:n||`Image content`})}),(0,b.jsx)($1,{children:n})]})});a0.displayName=`Image`,a0.Root=Z1,a0.Preview=Q1,a0.Filename=$1,a0.Zoom=e0,a0.Actions=i0,a0.Generating=t0,a0.ContentFilterError=n0;var o0=(e,t)=>typeof e==`string`?e===t:JSON.stringify(e)===JSON.stringify(t),s0=(e,t)=>{if(!e||!t)return!1;let n=e=>{let{position:t,data:n,...r}=e||{};return r};return JSON.stringify(n(e.properties))===JSON.stringify(n(t.properties))&&o0(e.children,t.children)},c0=(e,t)=>s0(e.node,t.node),l0=(e={})=>Object.fromEntries(Object.entries(e??{}).map(([e,t])=>{if(!t)return[e,t];let n=t;return[e,(0,y.memo)(({node:e,...t})=>(0,b.jsx)(n,{...t}),c0)]})),u0=(0,y.createContext)(null),d0=()=>(0,y.useContext)(u0)!==null,f0=(0,y.memo)(({children:e,fallbackPre:t,...n})=>n.node?.children.some(e=>e.type===`element`&&e.tagName===`code`)??!0?(0,b.jsx)(u0.Provider,{value:n,children:e}):(0,b.jsx)(t,{...n,children:e}),(e,t)=>e.fallbackPre===t.fallbackPre&&c0(e,t)),p0=({node:e,...t})=>(0,b.jsx)(`pre`,{...t}),m0=({node:e,...t})=>(0,b.jsx)(`code`,{...t}),h0=({node:e,components:{Pre:t,Code:n},code:r})=>(0,b.jsx)(t,{children:(0,b.jsx)(n,{node:e,children:r})}),g0=()=>null,_0=e=>/language-([^\s]+)/.exec(e??``)?.[1]??``,v0=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:r,CodeHeader:i},language:a,code:o})=>{let s=(0,y.useMemo)(()=>({Pre:t,Code:n}),[t,n]);return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(i,{node:e,language:a,code:o}),(0,b.jsx)(r,{node:e,components:s,language:a,code:o})]})},y0=n(r(((e,t)=>{(function(){var e={}.hasOwnProperty;function n(){for(var e=``,t=0;t<arguments.length;t++){var n=arguments[t];n&&(e=i(e,r(n)))}return e}function r(t){if(typeof t==`string`||typeof t==`number`)return t;if(typeof t!=`object`)return``;if(Array.isArray(t))return n.apply(null,t);if(t.toString!==Object.prototype.toString&&!t.toString.toString().includes(`[native code]`))return t.toString();var r=``;for(var a in t)e.call(t,a)&&t[a]&&(r=i(r,a));return r}function i(e,t){return t?e?e+` `+t:e+t:e}t!==void 0&&t.exports?(n.default=n,t.exports=n):typeof define==`function`&&typeof define.amd==`object`&&define.amd?define(`classnames`,[],function(){return n}):window.classNames=n})()}))(),1),b0=({className:e,...t})=>({className:n,...r})=>({className:(0,y0.default)(e,n),...t,...r});function x0(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=``;for(let n of e)t+=x0(n);return t}return(0,y.isValidElement)(e)?x0(e.props.children):``}var S0=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:r,CodeHeader:i},componentsByLanguage:a={},children:o,...s})=>{let c=b0((0,y.useContext)(u0)),l=dt(e=>(0,b.jsx)(t,{...c(e)})),u=b0(s),d=dt(e=>(0,b.jsx)(n,{...u(e)})),f=_0(s.className),p=a[f]?.SyntaxHighlighter??r,m=a[f]?.CodeHeader??i;return o!=null&&typeof o!=`string`?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(m,{node:e,language:f,code:x0(o)}),(0,b.jsx)(h0,{node:e,components:{Pre:l,Code:d},code:o})]}):(0,b.jsx)(v0,{node:e,components:{Pre:l,Code:d,SyntaxHighlighter:p,CodeHeader:m},language:f,code:o??``})},C0=({node:e,components:t,componentsByLanguage:n,...r})=>d0()?(0,b.jsx)(S0,{node:e,components:t,componentsByLanguage:n,...r}):(0,b.jsx)(t.Code,{...r}),w0=(e,t)=>{if(e===t)return!0;if(!e||!t)return!1;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n){if(!Object.hasOwn(t,r))return!1;let n=e[r],i=t[r];if(n!==i&&(!n||!i||n.SyntaxHighlighter!==i.SyntaxHighlighter||n.CodeHeader!==i.CodeHeader))return!1}return!0},T0=(0,y.memo)(C0,(e,t)=>e.components===t.components&&w0(e.componentsByLanguage,t.componentsByLanguage)&&c0(e,t)),{useSmooth:E0,useSmoothStatus:D0,withSmoothContextProvider:O0}=SQ,k0=(0,y.memo)(({text:e,overrideVersion:t,...n})=>(0,b.jsx)(AO,{...n,children:e}));k0.displayName=`MarkdownRenderer`;var A0=({text:e,...t})=>{let n=(0,y.useDeferredValue)(e);return(0,b.jsx)(k0,{text:n,...t})},j0=e=>typeof e==`object`&&!!e&&!Array.isArray(e),M0=(e,t,n=1)=>{if(Object.is(e,t))return!0;if(n<=0)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!M0(e[r],t[r],n-1))return!1;return!0}if(j0(e)&&j0(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(r=>Object.hasOwn(t,r)&&M0(e[r],t[r],n-1))}return!1};function N0(e,t){let n=(0,y.useRef)(e);return M0(e,n.current,t)||(n.current=e),n.current}function P0(e){let t=(0,y.useRef)(e),n=(e,t)=>e[t],r=Object.keys(e),i=Object.keys(t.current);return r.length===i.length&&r.every(r=>Object.hasOwn(t.current,r)&&M0(n(e,r),n(t.current,r)))||(t.current=e),t.current}var F0=({components:e,componentsByLanguage:t,smooth:n=!0,defer:r=!1,preprocess:i,...a})=>{let{text:o}=E0(VY(),n),s=(0,y.useMemo)(()=>i?i(o):o,[i,o]),{pre:c=p0,code:l=m0,SyntaxHighlighter:u=h0,CodeHeader:d=g0}=e??{},f=(0,y.useMemo)(()=>({Pre:c,Code:l,SyntaxHighlighter:u,CodeHeader:d}),[c,l,u,d]),p=dt(e=>(0,b.jsx)(T0,{components:f,componentsByLanguage:t,...e})),m=dt(e=>(0,b.jsx)(f0,{fallbackPre:c,...e})),h=P0((0,y.useMemo)(()=>{let{pre:t,code:n,SyntaxHighlighter:r,CodeHeader:i,...a}=e??{};return{...a,pre:m,code:p}},[p,m,e])),g=N0((0,y.useMemo)(()=>({components:f,componentsByLanguage:t}),[f,t]),3),_=r?A0:k0,v=P0(a);return(0,b.jsx)(_,{text:s,components:h,overrideVersion:g,...v})},I0=(0,y.forwardRef)(({className:e,containerProps:t,containerComponent:n=`div`,...r},i)=>{let a=D0();return(0,b.jsx)(n,{"data-status":a.type,...t,className:(0,y0.default)(e,t?.className),ref:i,children:(0,b.jsx)(F0,{...r})})});I0.displayName=`MarkdownTextPrimitive`;var L0=O0(I0),R0=({copiedDuration:e=3e3}={})=>{let[t,n]=(0,y.useState)(!1),r=(0,y.useRef)(void 0),i=(0,y.useRef)(0);return(0,y.useEffect)(()=>()=>{i.current+=1,r.current!==void 0&&(clearTimeout(r.current),r.current=void 0,n(!1))},[]),{isCopied:t,copyToClipboard:t=>{if(!t||typeof navigator>`u`||!navigator.clipboard)return;let a=i.current;navigator.clipboard.writeText(t).then(()=>{a===i.current&&(r.current!==void 0&&clearTimeout(r.current),n(!0),r.current=setTimeout(()=>{r.current=void 0,n(!1)},e))},()=>{})}}},z0=e=>{let t=(0,y.useRef)(e);if(e!==t.current){let n=t.current;e!==void 0&&n!==void 0&&Object.keys(n).length===Object.keys(e).length&&Object.keys(e).every(t=>n[t]===e[t])||(t.current=e)}return t.current},B0=(0,y.memo)(({components:e})=>{let t=z0(e),n=(0,y.useMemo)(()=>t?{...V0,...l0(t)}:V0,[t]);return(0,b.jsx)(L0,{remarkPlugins:[Pj],className:`aui-md`,components:n,defer:!0})}),V0=l0({h1:({className:e,...t})=>(0,b.jsx)(`h1`,{className:a(`aui-md-h1 mt-5 mb-2 scroll-m-20 text-xl font-semibold first:mt-0 last:mb-0`,e),...t}),h2:({className:e,...t})=>(0,b.jsx)(`h2`,{className:a(`aui-md-h2 mt-5 mb-2 scroll-m-20 text-lg font-semibold first:mt-0 last:mb-0`,e),...t}),h3:({className:e,...t})=>(0,b.jsx)(`h3`,{className:a(`aui-md-h3 mt-4 mb-1.5 scroll-m-20 text-base font-semibold first:mt-0 last:mb-0`,e),...t}),h4:({className:e,...t})=>(0,b.jsx)(`h4`,{className:a(`aui-md-h4 mt-3.5 mb-1 scroll-m-20 text-base font-medium first:mt-0 last:mb-0`,e),...t}),h5:({className:e,...t})=>(0,b.jsx)(`h5`,{className:a(`aui-md-h5 mt-3 mb-1 text-sm font-semibold first:mt-0 last:mb-0`,e),...t}),h6:({className:e,...t})=>(0,b.jsx)(`h6`,{className:a(`aui-md-h6 mt-3 mb-1 text-sm font-medium first:mt-0 last:mb-0`,e),...t}),p:({className:e,...t})=>(0,b.jsx)(`p`,{className:a(`aui-md-p my-3 leading-relaxed first:mt-0 last:mb-0`,e),...t}),a:({className:e,...t})=>(0,b.jsx)(`a`,{className:a(`aui-md-a text-primary hover:text-primary/80 underline underline-offset-2`,e),...t}),blockquote:({className:e,...t})=>(0,b.jsx)(`blockquote`,{className:a(`aui-md-blockquote border-muted-foreground/30 text-muted-foreground my-3 border-s-2 ps-4`,e),...t}),ul:({className:e,...t})=>(0,b.jsx)(`ul`,{className:a(`aui-md-ul marker:text-muted-foreground my-3 ms-5 list-disc [&>li]:mt-1`,e),...t}),ol:({className:e,...t})=>(0,b.jsx)(`ol`,{className:a(`aui-md-ol marker:text-muted-foreground my-3 ms-5 list-decimal [&>li]:mt-1`,e),...t}),hr:({className:e,...t})=>(0,b.jsx)(`hr`,{className:a(`aui-md-hr border-muted-foreground/20 my-3`,e),...t}),table:({className:e,...t})=>(0,b.jsx)(`div`,{className:`aui-md-table-wrapper my-3 overflow-x-auto`,children:(0,b.jsx)(`table`,{className:a(`aui-md-table w-full border-separate border-spacing-0`,e),...t})}),th:({className:e,...t})=>(0,b.jsx)(`th`,{className:a(`aui-md-th bg-muted px-3 py-1.5 text-start font-medium first:rounded-ss-lg last:rounded-se-lg [[align=center]]:text-center [[align=right]]:text-right`,e),...t}),td:({className:e,...t})=>(0,b.jsx)(`td`,{className:a(`aui-md-td border-muted-foreground/20 border-s border-b px-3 py-1.5 text-start last:border-e [[align=center]]:text-center [[align=right]]:text-right`,e),...t}),tr:({className:e,...t})=>(0,b.jsx)(`tr`,{className:a(`aui-md-tr m-0 border-b p-0 first:border-t [&:last-child>td:first-child]:rounded-es-lg [&:last-child>td:last-child]:rounded-ee-lg`,e),...t}),li:({className:e,...t})=>(0,b.jsx)(`li`,{className:a(`aui-md-li leading-relaxed`,e),...t}),strong:({className:e,...t})=>(0,b.jsx)(`strong`,{className:a(`aui-md-strong font-semibold`,e),...t}),sup:({className:e,...t})=>(0,b.jsx)(`sup`,{className:a(`aui-md-sup [&>a]:text-xs [&>a]:no-underline`,e),...t}),pre:({className:e,...t})=>(0,b.jsx)(`pre`,{className:a(`aui-md-pre border-border/50 bg-muted/30 overflow-x-auto rounded-t-none rounded-b-xl border border-t-0 p-3.5 text-[13px] leading-relaxed`,e),...t}),code:function({className:e,...t}){let n=d0();return(0,b.jsx)(`code`,{className:a(!n&&`aui-md-inline-code bg-muted rounded-md px-1.5 py-0.5 font-mono text-[0.85em]`,e),...t})},CodeHeader:({language:e,code:t})=>{let{isCopied:n,copyToClipboard:r}=R0();return(0,b.jsxs)(`div`,{className:`aui-code-header-root border-border/50 bg-muted/50 mt-3 flex items-center justify-between rounded-t-xl border border-b-0 px-3.5 py-1.5 text-xs`,children:[(0,b.jsx)(`span`,{className:`aui-code-header-language text-muted-foreground font-medium lowercase`,children:e}),(0,b.jsxs)(p1,{tooltip:`Copy`,onClick:()=>{t&&!n&&r(t)},children:[!n&&(0,b.jsx)(Mf,{className:`animate-in zoom-in-75 fade-in duration-150`}),n&&(0,b.jsx)(Sf,{className:`animate-in zoom-in-50 fade-in duration-200 ease-out`})]})]})}});function H0({...e}){return(0,b.jsx)(it,{"data-slot":`collapsible`,...e})}function U0({...e}){return(0,b.jsx)($e,{"data-slot":`collapsible-trigger`,...e})}function W0({...e}){return(0,b.jsx)(tt,{"data-slot":`collapsible-content`,...e})}var G0=(0,y.createContext)(!1),K0=v(`aui-reasoning-root mb-4 w-full`,{variants:{variant:{outline:`rounded-lg border px-3 py-2`,ghost:``,muted:`bg-muted/50 rounded-lg px-3 py-2`}},defaultVariants:{variant:`outline`}});function q0({className:e,variant:t,open:n,onOpenChange:r,defaultOpen:i=!1,streaming:o,onAnimationStart:s,children:c,...l}){let[u]=(0,y.useState)(i),[d,f]=(0,y.useState)(null),p=n!==void 0,m=p?n:d??(o||u),h=o===!0&&m,g=(0,y.useRef)(o);(0,y.useLayoutEffect)(()=>{g.current!==o&&(g.current=o,!p&&d===null&&!u&&s?.())},[o,p,d,u,s]);let _=(0,y.useCallback)(e=>{s?.(),p||f(e),r?.(e)},[s,p,r]);return(0,b.jsx)(H0,{"data-slot":`reasoning-root`,"data-variant":t,open:m,onOpenChange:_,className:a(`group/reasoning-root`,K0({variant:t,className:e})),style:{"--animation-duration":`200ms`},...l,children:(0,b.jsx)(G0.Provider,{value:h,children:c})})}function J0({side:e=`bottom`,className:t,...n}){return e===`top`?(0,b.jsx)(`div`,{"data-slot":`reasoning-fade`,className:a(`aui-reasoning-fade pointer-events-none absolute inset-x-0 top-0 z-10 h-8`,`bg-[linear-gradient(to_bottom,var(--color-background),transparent)]`,`group-data-[variant=muted]/reasoning-root:bg-[linear-gradient(to_bottom,color-mix(in_oklab,var(--color-muted)_50%,var(--color-background)),transparent)]`,`fade-in-0 animate-in`,`animation-duration-(--animation-duration)`,t),...n}):(0,b.jsx)(`div`,{"data-slot":`reasoning-fade`,className:a(`aui-reasoning-fade pointer-events-none absolute inset-x-0 bottom-0 z-10 h-8`,`bg-[linear-gradient(to_top,var(--color-background),transparent)]`,`group-data-[variant=muted]/reasoning-root:bg-[linear-gradient(to_top,color-mix(in_oklab,var(--color-muted)_50%,var(--color-background)),transparent)]`,`fade-in-0 animate-in`,`animation-duration-(--animation-duration)`,t),...n})}function Y0({active:e,duration:t,className:n,...r}){let i=t?` (${t}s)`:``;return(0,b.jsxs)(U0,{"data-slot":`reasoning-trigger`,className:a(`aui-reasoning-trigger group/trigger text-muted-foreground hover:text-foreground flex max-w-[75%] origin-left items-center gap-2 py-1.5 text-sm transition-[color,scale] active:scale-[0.98]`,n),...r,children:[(0,b.jsx)(xf,{"data-slot":`reasoning-trigger-icon`,className:`aui-reasoning-trigger-icon size-4 shrink-0`}),(0,b.jsxs)(`span`,{"data-slot":`reasoning-trigger-label`,className:a(`aui-reasoning-trigger-label-wrapper inline-block leading-none tabular-nums`,e&&`shimmer motion-reduce:animate-none`),children:[`Reasoning`,i]}),(0,b.jsx)(Cf,{"data-slot":`reasoning-trigger-chevron`,className:a(`aui-reasoning-trigger-chevron mt-0.5 size-4 shrink-0`,`transition-transform duration-(--animation-duration) ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none`,`-rotate-90`,`group-data-open/trigger:rotate-0`,`group-data-panel-open/trigger:rotate-0`)})]})}function X0({className:e,children:t,...n}){let r=(0,y.useContext)(G0);return(0,b.jsxs)(W0,{"data-slot":`reasoning-content`,className:a(`aui-reasoning-content text-muted-foreground relative overflow-hidden text-sm outline-none`,`group/collapsible-content ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none`,`data-closed:animate-collapsible-up`,`data-open:animate-collapsible-down`,`data-closed:fill-mode-forwards`,`data-closed:pointer-events-none`,`[--tw-duration:var(--animation-duration)]`,e),...n,children:[(0,b.jsx)(J0,{side:`top`}),t,r?(0,b.jsx)(J0,{}):null]})}function Z0({className:e,children:t,...n}){let r=(0,y.useContext)(G0),i=(0,y.useRef)(null),o=(0,y.useRef)(null);return(0,y.useEffect)(()=>{if(!r)return;let e=i.current,t=o.current;if(!e||!t)return;let n=!0,a=e.scrollTop,s=e.scrollHeight,c=()=>Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight)<=1||e.scrollHeight<=e.clientHeight,l=()=>{n&&(e.scrollTop=e.scrollHeight)},u=()=>{c()?n=!0:e.scrollTop<a&&e.scrollHeight===s&&(n=!1),a=e.scrollTop,s=e.scrollHeight};l(),e.addEventListener(`scroll`,u);let d=new ResizeObserver(l);return d.observe(t),()=>{e.removeEventListener(`scroll`,u),d.disconnect()}},[r]),(0,b.jsx)(`div`,{ref:i,"data-slot":`reasoning-text`,className:a(`aui-reasoning-text relative z-0 max-h-64 overflow-y-auto ps-6 pt-2 pb-2 leading-relaxed text-pretty`,`transform-gpu transition-[transform,opacity] ease-[cubic-bezier(0.32,0.72,0,1)]`,`motion-reduce:animate-none`,`group-data-open/collapsible-content:animate-in`,`group-data-closed/collapsible-content:animate-out`,`group-data-open/collapsible-content:fade-in-0`,`group-data-closed/collapsible-content:fade-out-0`,`group-data-open/collapsible-content:slide-in-from-top-4`,`group-data-closed/collapsible-content:slide-out-to-top-4`,`group-data-open/collapsible-content:blur-in-[2px]`,`group-data-closed/collapsible-content:blur-out-[2px]`,`group-data-open/collapsible-content:animation-duration-(--animation-duration)`,`group-data-closed/collapsible-content:animation-duration-(--animation-duration)`,e),...n,children:(0,b.jsx)(`div`,{ref:o,className:`aui-reasoning-text-content space-y-4`,children:t})})}function Q0({ref:e,onAnimationStart:t,...n}){let r=(0,y.useRef)(null),i=_Q(r,200),a=(0,y.useCallback)(()=>{i(),t?.()},[i,t]),o=(0,y.useCallback)(t=>{r.current=t,typeof e==`function`?e(t):e&&(e.current=t)},[e]);return(0,b.jsx)(q0,{ref:o,onAnimationStart:a,...n})}var $0=()=>(0,b.jsx)(B0,{}),e2=({children:e,startIndex:t,endIndex:n})=>{let r=$(e=>{if(e.message.status?.type!==`running`)return!1;for(let r=t;r<=n;r++)if(e.message.parts[r]?.status.type===`running`)return!0;return!1});return(0,b.jsxs)(Q0,{streaming:r,children:[(0,b.jsx)(Y0,{active:r}),(0,b.jsx)(X0,{"aria-busy":r,children:(0,b.jsx)(Z0,{children:e})})]})},t2=(0,y.memo)($0);t2.displayName=`Reasoning`,t2.Root=Q0,t2.Trigger=Y0,t2.Content=X0,t2.Text=Z0,t2.Fade=J0;var n2=(0,y.memo)(e2);n2.displayName=`ReasoningGroup`;function r2({className:e,...t}){return(0,b.jsx)(`textarea`,{"data-slot":`textarea`,className:a(`flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40`,e),...t})}var i2=200,a2=`active:scale-[0.98]`;function o2({className:e,open:t,onOpenChange:n,defaultOpen:r=!1,children:i,...o}){let s=(0,y.useRef)(null),[c,l]=(0,y.useState)(r),u=_Q(s,i2),d=t!==void 0,f=d?t:c,p=(0,y.useCallback)(e=>{u(),d||l(e),n?.(e)},[u,d,n]);return(0,b.jsx)(H0,{ref:s,"data-slot":`tool-fallback-root`,open:f,onOpenChange:p,className:a(`aui-tool-fallback-root group/tool-fallback-root w-full`,e),style:{"--animation-duration":`${i2}ms`},...o,children:i})}var s2={running:Wf,complete:Sf,incomplete:Of,"requires-action":Ef},c2=e=>{if(e<1e3)return`<1s`;let t=e/1e3;return t<10?`${(Math.floor(t*10)/10).toFixed(1)}s`:t<60?`${Math.floor(t)}s`:`${Math.floor(t/60)}m ${Math.floor(t%60)}s`};function l2({className:e,...t}){let n=vQ();return n===void 0?null:(0,b.jsx)(`span`,{"data-slot":`tool-fallback-duration`,className:a(`aui-tool-fallback-duration text-muted-foreground text-xs tabular-nums`,e),...t,children:c2(n)})}function u2({toolName:e,status:t,className:n,...r}){let i=t?.type??`complete`,o=i===`running`,s=t?.type===`incomplete`&&t.reason===`cancelled`,c=s2[i],l=s?`Cancelled tool`:`Used tool`;return(0,b.jsxs)(U0,{"data-slot":`tool-fallback-trigger`,className:a(`aui-tool-fallback-trigger group/trigger text-muted-foreground hover:text-foreground flex w-fit origin-left items-center gap-2 py-1.5 text-sm transition-[color,scale] active:scale-[0.98]`,n),...r,children:[(0,b.jsx)(c,{"data-slot":`tool-fallback-trigger-icon`,className:a(`aui-tool-fallback-trigger-icon size-4 shrink-0`,s&&`text-muted-foreground`,o&&`animate-spin [animation-duration:0.6s]`)}),(0,b.jsxs)(`span`,{"data-slot":`tool-fallback-trigger-label`,className:a(`aui-tool-fallback-trigger-label-wrapper inline-block text-start leading-none`,s&&`text-muted-foreground line-through`,o&&`shimmer motion-reduce:animate-none`),children:[l,`: `,(0,b.jsx)(`b`,{children:e})]}),(0,b.jsx)(l2,{}),(0,b.jsx)(Cf,{"data-slot":`tool-fallback-trigger-chevron`,className:a(`aui-tool-fallback-trigger-chevron size-4 shrink-0`,`transition-transform duration-(--animation-duration) ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none`,`-rotate-90`,`group-data-open/trigger:rotate-0`,`group-data-panel-open/trigger:rotate-0`)})]})}function d2({className:e,children:t,...n}){return(0,b.jsx)(W0,{"data-slot":`tool-fallback-content`,className:a(`aui-tool-fallback-content relative overflow-hidden text-sm outline-none`,`group/collapsible-content ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none`,`data-closed:animate-collapsible-up`,`data-open:animate-collapsible-down`,`data-closed:fill-mode-forwards`,`data-closed:pointer-events-none`,`[--tw-duration:var(--animation-duration)]`,e),...n,children:(0,b.jsx)(`div`,{className:a(`flex flex-col gap-2 ps-6 pt-1 pb-2 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none`,`group-data-open/collapsible-content:animate-in group-data-open/collapsible-content:fade-in-0 group-data-open/collapsible-content:blur-in-[2px] group-data-open/collapsible-content:slide-in-from-top-1`,`group-data-closed/collapsible-content:animate-out group-data-closed/collapsible-content:fade-out-0 group-data-closed/collapsible-content:blur-out-[2px] group-data-closed/collapsible-content:slide-out-to-top-1`,`group-data-closed/collapsible-content:animation-duration-(--animation-duration) group-data-open/collapsible-content:animation-duration-(--animation-duration)`),children:t})})}function f2({argsText:e,className:t,...n}){return e?(0,b.jsx)(`div`,{"data-slot":`tool-fallback-args`,className:a(`aui-tool-fallback-args`,t),...n,children:(0,b.jsx)(`pre`,{className:`aui-tool-fallback-args-value bg-muted/50 text-foreground/90 rounded-md p-2.5 text-xs whitespace-pre-wrap`,children:e})}):null}var p2=(e,t)=>{if(typeof e==`string`)return e;try{if(e instanceof Error)return String(e);let n=JSON.stringify(e,null,t);if(n!==void 0)return n}catch{}try{return String(e)}catch{return`[Unserializable value]`}};function m2({result:e,className:t,...n}){return e===void 0?null:(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-result`,className:a(`aui-tool-fallback-result`,t),...n,children:[(0,b.jsx)(`p`,{className:`aui-tool-fallback-result-header text-muted-foreground text-xs font-medium`,children:`Result:`}),(0,b.jsx)(`pre`,{className:`aui-tool-fallback-result-content bg-muted/50 text-foreground/90 mt-1 rounded-md p-2.5 text-xs whitespace-pre-wrap`,children:p2(e,2)})]})}function h2({status:e,className:t,...n}){if(e?.type!==`incomplete`)return null;let r=e.error,i=r==null?null:p2(r);if(!i)return null;let o=e.reason===`cancelled`?`Cancelled reason:`:`Error:`;return(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-error`,className:a(`aui-tool-fallback-error`,t),...n,children:[(0,b.jsx)(`p`,{className:`aui-tool-fallback-error-header text-muted-foreground font-semibold`,children:o}),(0,b.jsx)(`p`,{className:`aui-tool-fallback-error-reason text-muted-foreground whitespace-pre-line`,children:i})]})}var g2=`Approved by user`,_2=`User denied tool execution`,v2={"allow-once":`Allow`,"allow-always":`Always allow`,"reject-once":`Deny`,"reject-always":`Always deny`},y2=e=>Object.hasOwn(v2,e),b2=e=>e===`allow-once`||e===`allow-always`,x2=e=>e.label??(y2(e.kind)?v2[e.kind]:void 0)??e.id,S2=e=>e?.display===`select`||e?.display===`text`,C2=(e,t,n)=>e?.type!==`requires-action`||e.reason!==`interrupt`||t!=null||n!=null;function w2({className:e,addResult:t,resume:n,interrupt:r,approval:i,respondToApproval:s,status:c,...l}){let[u,d]=(0,y.useState)(!1),f=$(e=>e.thread.voice!==void 0),p=u||f,[m,h]=(0,y.useState)(null),[g,_]=(0,y.useState)(``),[v,x]=(0,y.useState)(null);if(i!=null&&(i.approved!==void 0||i.resolution!==void 0)||!C2(c,i,r))return null;let S=s?i?.options:void 0,C=i!=null&&s!=null&&OV(i),w=e=>{d(!0),x(null),(async()=>{try{await e()}catch(e){d(!1),x(e instanceof Error?e.message:String(e))}})()},T=e=>{if(!p){if(i!=null&&i.approved===void 0&&s)w(()=>s({approved:e,...D()}));else if(r)w(()=>n?.({approved:e}));else if(c?.type===`requires-action`&&c.reason===`interrupt`)return;else w(()=>t?.(e?g2:_2))}},E=e=>{p||(h(null),w(()=>s?.(y2(e.kind)?{optionId:e.id,...D()}:{optionId:e.id,approved:!0,...D()})))},D=()=>g.trim()?{text:g}:{},O=()=>{p||w(()=>s?.({text:g}))},k=()=>{p||w(()=>s?.({approved:!1}))},A=e=>{e.confirm?h(e.id):E(e)},j=m==null?void 0:S?.find(e=>e.id===m),M=S2(i),N=M&&s!=null&&i?.dismissible===!0?(0,b.jsx)(o,{size:`sm`,variant:`outline`,className:a2,onClick:k,disabled:p,children:`Dismiss`}):null,ee=i?.prompt?(0,b.jsx)(`p`,{className:`aui-tool-fallback-approval-prompt text-foreground whitespace-pre-line`,children:i.prompt}):null,te=v?(0,b.jsx)(`p`,{role:`alert`,className:`aui-tool-fallback-approval-error text-destructive text-xs whitespace-pre-line`,children:v}):null,ne=C?(0,b.jsxs)(`div`,{className:`aui-tool-fallback-approval-answer flex flex-col items-start gap-2`,children:[(0,b.jsx)(r2,{value:g,onChange:e=>_(e.target.value),disabled:p,"aria-label":M?i?.prompt??`Answer`:`Note`,placeholder:M?`Type your answer`:`Add a note to your decision`}),M&&(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsx)(o,{size:`sm`,className:a2,onClick:O,disabled:p,children:`Send`}),N]})]}):null;if(j){let t=typeof j.confirm==`object`?j.confirm:void 0,n=t?.description??j.description;return(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-approval-confirm`,className:a(`aui-tool-fallback-approval-confirm flex flex-col gap-2 pt-1`,e),...l,children:[(0,b.jsx)(`p`,{className:`aui-tool-fallback-approval-confirm-title font-semibold`,children:t?.title??`${x2(j)}?`}),n&&(0,b.jsx)(`p`,{className:`aui-tool-fallback-approval-confirm-description text-muted-foreground whitespace-pre-line`,children:n}),j.grants&&j.grants.length>0&&(0,b.jsx)(`ul`,{className:`aui-tool-fallback-approval-confirm-grants flex flex-col gap-1`,children:j.grants.map(e=>(0,b.jsx)(`li`,{children:(0,b.jsx)(`code`,{className:`aui-tool-fallback-approval-confirm-grant bg-muted rounded px-1.5 py-0.5 text-xs`,children:e})},e))}),(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsx)(o,{size:`sm`,className:a2,onClick:()=>E(j),disabled:p,children:`Confirm`}),(0,b.jsx)(o,{size:`sm`,variant:`outline`,className:a2,onClick:()=>h(null),disabled:p,children:`Back`})]})]})}if(S&&S.length>0){let t=S.filter(e=>b2(e.kind)),n=S.filter(e=>!y2(e.kind)),r=S.filter(e=>y2(e.kind)&&!b2(e.kind));return(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-approval`,className:a(`aui-tool-fallback-approval flex flex-col gap-2 pt-1`,e),...l,children:[ee,(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[[...t,...n,...r].map(e=>(0,b.jsx)(o,{size:`sm`,variant:e===t[0]?`default`:`outline`,className:a2,onClick:()=>A(e),disabled:p,children:x2(e)},e.id)),r.length===0&&!M&&(0,b.jsx)(o,{size:`sm`,variant:`outline`,className:a2,onClick:()=>T(!1),disabled:p,children:`Deny`}),!C&&N]}),ne,te]})}return M?(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-approval`,className:a(`aui-tool-fallback-approval flex flex-col gap-2 pt-1`,e),...l,children:[ee,ne,!C&&N&&(0,b.jsx)(`div`,{className:`flex items-center gap-2`,children:N}),te]}):(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-approval`,className:a(`aui-tool-fallback-approval flex flex-col gap-2 pt-1`,e),...l,children:[ee,(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsx)(o,{size:`sm`,className:a2,onClick:()=>T(!0),disabled:p,children:`Allow`}),(0,b.jsx)(o,{size:`sm`,variant:`outline`,className:a2,onClick:()=>T(!1),disabled:p,children:`Deny`})]}),ne,te]})}var T2=(0,y.memo)(({toolName:e,argsText:t,result:n,status:r,addResult:i,resume:o,interrupt:s,approval:c,respondToApproval:l})=>{let u=r?.type===`incomplete`&&r.reason===`cancelled`,d=r?.type===`requires-action`,f=d&&C2(r,c,s),[p,m]=(0,y.useState)(d),[h,g]=(0,y.useState)(d);return d!==h&&(g(d),d&&m(!0)),(0,b.jsxs)(o2,{open:p,onOpenChange:m,children:[(0,b.jsx)(u2,{toolName:e,status:r}),(0,b.jsxs)(d2,{children:[(0,b.jsx)(h2,{status:r}),(0,b.jsx)(f2,{argsText:t,className:a(u&&`opacity-60`)}),f&&(0,b.jsx)(w2,{addResult:i,resume:o,interrupt:s,approval:c,respondToApproval:l,status:r}),(0,b.jsx)(m2,{result:n})]})]})});T2.displayName=`ToolFallback`,T2.Root=o2,T2.Trigger=u2,T2.Content=d2,T2.Args=f2,T2.Result=m2,T2.Error=h2,T2.Approval=w2;var E2=200,D2=v(`aui-tool-group-root group/tool-group w-full`,{variants:{variant:{outline:`rounded-lg border py-3`,ghost:``,muted:`border-muted-foreground/30 bg-muted/30 rounded-lg border py-3`}},defaultVariants:{variant:`outline`}});function O2({className:e,variant:t,open:n,onOpenChange:r,defaultOpen:i=!1,children:o,...s}){let c=(0,y.useRef)(null),[l,u]=(0,y.useState)(i),d=_Q(c,E2),f=n!==void 0,p=f?n:l,m=(0,y.useCallback)(e=>{d(),f||u(e),r?.(e)},[d,f,r]);return(0,b.jsx)(H0,{ref:c,"data-slot":`tool-group-root`,"data-variant":t??`outline`,open:p,onOpenChange:m,className:a(D2({variant:t}),`group/tool-group-root`,e),style:{"--animation-duration":`${E2}ms`},...s,children:o})}function k2({count:e,active:t=!1,className:n,...r}){let i=`${e} tool ${e===1?`call`:`calls`}`;return(0,b.jsxs)(U0,{"data-slot":`tool-group-trigger`,className:a(`aui-tool-group-trigger group/trigger flex origin-left items-center gap-2 text-sm transition-[color,scale] active:scale-[0.98]`,`group-data-[variant=ghost]/tool-group-root:text-muted-foreground group-data-[variant=ghost]/tool-group-root:hover:text-foreground group-data-[variant=ghost]/tool-group-root:py-1.5`,`group-data-[variant=outline]/tool-group-root:w-full group-data-[variant=outline]/tool-group-root:px-4`,`group-data-[variant=muted]/tool-group-root:w-full group-data-[variant=muted]/tool-group-root:px-4`,n),...r,children:[t&&(0,b.jsx)(Wf,{"data-slot":`tool-group-trigger-loader`,className:`aui-tool-group-trigger-loader size-3 shrink-0 animate-spin [animation-duration:0.6s]`}),(0,b.jsx)(`span`,{"data-slot":`tool-group-trigger-label`,className:a(`aui-tool-group-trigger-label-wrapper inline-block text-start text-xs leading-none font-medium`,`group-data-[variant=ghost]/tool-group-root:font-normal`,`group-data-[variant=outline]/tool-group-root:grow`,`group-data-[variant=muted]/tool-group-root:grow`,t&&`shimmer motion-reduce:animate-none`),children:i}),(0,b.jsx)(Cf,{"data-slot":`tool-group-trigger-chevron`,className:a(`aui-tool-group-trigger-chevron size-3 shrink-0`,`transition-transform duration-(--animation-duration) ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none`,`-rotate-90`,`group-data-open/trigger:rotate-0`,`group-data-panel-open/trigger:rotate-0`)})]})}function A2({className:e,children:t,...n}){return(0,b.jsx)(W0,{"data-slot":`tool-group-content`,className:a(`aui-tool-group-content relative overflow-hidden text-sm outline-none`,`group/collapsible-content ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none`,`data-closed:animate-collapsible-up`,`data-open:animate-collapsible-down`,`data-closed:fill-mode-forwards`,`data-closed:pointer-events-none`,`[--tw-duration:var(--animation-duration)]`,e),...n,children:(0,b.jsx)(`div`,{className:a(`mt-2 flex flex-col gap-2`,`group-data-[variant=ghost]/tool-group-root:mt-1 group-data-[variant=ghost]/tool-group-root:gap-1`,`group-data-[variant=outline]/tool-group-root:mt-3 group-data-[variant=outline]/tool-group-root:border-t group-data-[variant=outline]/tool-group-root:px-4 group-data-[variant=outline]/tool-group-root:pt-3`,`group-data-[variant=muted]/tool-group-root:mt-3 group-data-[variant=muted]/tool-group-root:border-t group-data-[variant=muted]/tool-group-root:px-4 group-data-[variant=muted]/tool-group-root:pt-3`,`[&>*]:animate-in [&>*]:fade-in-0 [&>*]:blur-in-[2px] [&>*]:slide-in-from-top-1 [&>*]:animation-duration-(--animation-duration) [&>*]:ease-[cubic-bezier(0.32,0.72,0,1)]`,`[&>*]:motion-reduce:animate-none`,`[&>*:nth-child(2)]:[animation-delay:40ms]`,`[&>*:nth-child(3)]:[animation-delay:80ms]`,`[&>*:nth-child(4)]:[animation-delay:120ms]`,`[&>*:nth-child(n+5)]:[animation-delay:160ms]`),children:t})})}var j2=(0,y.memo)(({children:e,startIndex:t,endIndex:n})=>{let r=n-t+1;return(0,b.jsxs)(O2,{children:[(0,b.jsx)(k2,{count:r}),(0,b.jsx)(A2,{children:e})]})});j2.displayName=`ToolGroup`,j2.Root=O2,j2.Trigger=k2,j2.Content=A2;function M2({className:e,...t}){return(0,b.jsx)(`div`,{"data-slot":`skeleton`,className:a(`animate-pulse rounded-md bg-accent`,e),...t})}var N2=LW({reasoning:[`group-chainOfThought`,`group-reasoning`],"tool-call":[`group-chainOfThought`,`group-tool`],"standalone-tool-call":[]}),P2=[`group-chainOfThought`,`group-task`],F2=(e,t)=>{let n=N2(e,t);return e.type===`tool-call`&&e.messages!==void 0&&n.length>0&&!t?.toolUIs?.[e.toolName]?.length?P2:n},I2={},L2=(0,y.createContext)(I2),R2=e=>e.thread.messages.length===0&&(!e.thread.isLoading||e.threads.isLoading),z2=e=>e.thread.messages.length===0&&e.thread.isLoading&&!e.thread.isDisabled&&!e.threads.isLoading,B2=()=>(0,b.jsxs)(`div`,{"data-slot":`aui_thread-history-skeleton`,role:`status`,className:`animate-in fade-in fill-mode-both flex flex-col gap-y-6 [animation-delay:150ms] [animation-duration:200ms]`,children:[(0,b.jsx)(`span`,{className:`sr-only`,children:`Loading conversation`}),(0,b.jsx)(M2,{className:`ml-auto h-9 w-2/5 rounded-xl motion-reduce:animate-none`}),(0,b.jsxs)(`div`,{className:`flex flex-col gap-y-2`,children:[(0,b.jsx)(M2,{className:`h-4 w-11/12 motion-reduce:animate-none`}),(0,b.jsx)(M2,{className:`h-4 w-4/5 motion-reduce:animate-none`}),(0,b.jsx)(M2,{className:`h-4 w-3/5 motion-reduce:animate-none`})]}),(0,b.jsx)(M2,{className:`ml-auto h-9 w-1/3 rounded-xl motion-reduce:animate-none`}),(0,b.jsxs)(`div`,{className:`flex flex-col gap-y-2`,children:[(0,b.jsx)(M2,{className:`h-4 w-10/12 motion-reduce:animate-none`}),(0,b.jsx)(M2,{className:`h-4 w-2/3 motion-reduce:animate-none`})]})]}),V2=({components:e=I2,autoFocus:t=!0})=>{let n=$(R2);return(0,b.jsx)(L2.Provider,{value:e,children:(0,b.jsx)(H2,{isEmpty:n,autoFocus:t})})},H2=({isEmpty:e,autoFocus:t})=>{let{Welcome:n=Y2}=(0,y.useContext)(L2);return(0,b.jsx)(PZ.Root,{className:`aui-root aui-thread-root bg-background @container flex h-full flex-col`,style:{"--thread-max-width":`44rem`,"--composer-bg":`color-mix(in oklab, var(--color-muted) 30%, transparent)`,"--composer-radius":`var(--radius-2xl)`,"--composer-padding":`8px`},children:(0,b.jsx)(PZ.Viewport,{turnAnchor:`top`,"data-slot":`aui_thread-viewport`,className:`relative flex flex-1 flex-col overflow-x-auto overflow-y-scroll scroll-smooth`,children:(0,b.jsxs)(`div`,{className:a(`mx-auto flex w-full max-w-(--thread-max-width) flex-1 flex-col px-4 pt-4`,e&&`justify-center`),children:[(0,b.jsx)(IL,{condition:R2,children:(0,b.jsx)(n,{})}),(0,b.jsx)(IL,{condition:z2,children:(0,b.jsx)(B2,{})}),(0,b.jsx)(`div`,{"data-slot":`aui_message-group`,className:`mb-14 flex flex-col gap-y-6 empty:hidden`,children:(0,b.jsx)(PZ.Messages,{children:()=>(0,b.jsx)(U2,{})})}),(0,b.jsxs)(PZ.ViewportFooter,{className:a(`aui-thread-viewport-footer bg-background flex flex-col gap-4 overflow-visible pb-4 md:pb-6`,!e&&`sticky bottom-0 mt-auto rounded-t-(--composer-radius)`),children:[(0,b.jsx)(J2,{}),(0,b.jsx)(W1,{}),(0,b.jsx)(Q2,{autoFocus:t}),(0,b.jsx)(IL,{condition:e=>R2(e)&&e.composer.isEmpty,children:(0,b.jsx)(X2,{})})]})]})})})},U2=()=>{let{AssistantMessage:e=t4}=(0,y.useContext)(L2),t=$(e=>e.message.role),n=$(e=>e.message.composer.isEditing),r=$(e=>e.message.metadata.modality===`voice`);return n?(0,b.jsx)(s4,{}):r?(0,b.jsx)(K2,{}):t===`user`?(0,b.jsx)(a4,{}):(0,b.jsx)(e,{})},W2=()=>$(e=>{let t=e.thread.messages[e.message.index-1]?.metadata.modality===`voice`,n=e.thread.messages[e.message.index+1]?.metadata.modality===`voice`;return t?n?`middle`:`end`:n?`start`:`single`}),G2=({text:e})=>(0,b.jsx)(`p`,{className:`aui-spoken-message-text m-0`,children:e}),K2=()=>{let e=$(e=>e.message.role),t=W2(),n=$(e=>e.message.role===`assistant`&&e.message.status?.type===`running`),r=t===`start`||t===`single`;return(0,b.jsxs)(XX.Root,{"data-slot":`aui_spoken-message-root`,"data-role":e,"data-voice-run":t,className:a(`aui-spoken-message bg-muted/40 mx-2 px-3 py-1.5 [contain-intrinsic-size:auto_48px] [content-visibility:auto]`,t===`single`&&`rounded-xl py-2`,t===`start`&&`rounded-t-xl pt-2`,t===`middle`&&`-mt-6`,t===`end`&&`-mt-6 rounded-b-xl pb-2`),children:[r&&(0,b.jsxs)(`div`,{"data-slot":`aui_spoken-exchange-header`,className:`text-muted-foreground mb-1.5 flex items-center gap-1.5 text-xs`,children:[(0,b.jsx)(Yf,{className:`size-3`,"aria-hidden":!0}),(0,b.jsx)(`span`,{children:`Voice conversation`})]}),(0,b.jsxs)(`div`,{"data-slot":`aui_spoken-message-content`,className:`text-foreground flex items-start gap-2 text-sm leading-relaxed`,children:[(0,b.jsx)(`span`,{className:`text-muted-foreground mt-1 shrink-0`,"aria-hidden":!0,children:e===`user`?(0,b.jsx)(Gf,{className:`size-3.5`}):(0,b.jsx)(yf,{className:`size-3.5`})}),(0,b.jsx)(`span`,{className:`sr-only`,children:e===`user`?`You said`:`Assistant said`}),(0,b.jsxs)(`div`,{className:`min-w-0 flex-1 wrap-break-word`,children:[(0,b.jsx)(XX.Parts,{components:{Text:G2}}),n&&(0,b.jsx)(`span`,{"data-slot":`aui_spoken-message-indicator`,role:`status`,className:`text-muted-foreground ms-1 animate-pulse font-sans`,"aria-label":`Assistant is speaking`,children:`●`})]}),(0,b.jsx)(q2,{})]})]})},q2=()=>(0,b.jsx)(hq.Root,{hideWhenRunning:!0,autohide:`always`,className:`aui-spoken-action-bar text-muted-foreground flex shrink-0 gap-1`,children:(0,b.jsx)(hq.Copy,{asChild:!0,children:(0,b.jsxs)(p1,{tooltip:`Copy`,className:`size-6`,children:[(0,b.jsx)(IL,{condition:e=>e.message.isCopied,children:(0,b.jsx)(Sf,{className:`animate-in zoom-in-50 fade-in duration-200 ease-out`})}),(0,b.jsx)(IL,{condition:e=>!e.message.isCopied,children:(0,b.jsx)(Mf,{className:`animate-in zoom-in-75 fade-in duration-150`})})]})})}),J2=()=>(0,b.jsx)(PZ.ScrollToBottom,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Scroll to bottom`,variant:`outline`,className:`aui-thread-scroll-to-bottom dark:border-border dark:bg-background dark:hover:bg-accent absolute -top-12 z-10 self-center rounded-full p-4 disabled:invisible`,children:(0,b.jsx)(hf,{})})}),Y2=()=>(0,b.jsx)(`div`,{className:`aui-thread-welcome-root mb-6 flex flex-col px-2`,children:(0,b.jsx)(`p`,{className:`aui-thread-welcome-message-inner fade-in slide-in-from-bottom-1 animate-in fill-mode-both text-2xl font-medium tracking-tight duration-200`,children:`How can I help you today?`})}),X2=()=>(0,b.jsx)(`div`,{className:`aui-thread-welcome-suggestions flex w-full flex-col`,children:(0,b.jsx)(PZ.Suggestions,{children:()=>(0,b.jsx)(Z2,{})})}),Z2=()=>(0,b.jsx)(`div`,{className:`aui-thread-welcome-suggestion-display fade-in slide-in-from-bottom-2 animate-in fill-mode-both duration-200`,children:(0,b.jsx)(VZ.Trigger,{send:!0,asChild:!0,children:(0,b.jsxs)(`button`,{type:`button`,className:`aui-thread-welcome-suggestion group hover:bg-foreground/[0.03] focus-visible:ring-ring/50 flex w-full items-baseline gap-2.5 rounded-md px-2 py-2 text-start text-sm transition-colors outline-none focus-visible:ring-1 motion-reduce:transition-none`,children:[(0,b.jsx)(`span`,{"aria-hidden":!0,className:`text-muted-foreground/60 group-hover:text-foreground font-mono text-xs transition-colors motion-reduce:transition-none`,children:`>`}),(0,b.jsxs)(`span`,{className:`min-w-0 flex-1 truncate`,children:[(0,b.jsx)(VZ.Title,{className:`aui-thread-welcome-suggestion-text-1 text-foreground`}),` `,(0,b.jsx)(VZ.Description,{className:`aui-thread-welcome-suggestion-text-2 text-muted-foreground empty:hidden`})]})]})})}),Q2=({autoFocus:e})=>(0,b.jsx)(RY.Root,{className:`aui-composer-root relative flex w-full flex-col`,children:(0,b.jsx)(RY.AttachmentDropzone,{asChild:!0,children:(0,b.jsxs)(`div`,{"data-slot":`aui_composer-shell`,className:`border-foreground/10 focus-within:border-foreground/25 data-[dragging=true]:border-ring flex w-full cursor-text flex-col gap-2 rounded-(--composer-radius) border bg-(--composer-bg) p-(--composer-padding) transition-[border-color] data-[dragging=true]:border-dashed data-[dragging=true]:bg-[color-mix(in_oklab,var(--color-accent)_50%,var(--color-background))]`,children:[(0,b.jsx)(O1,{}),(0,b.jsx)(RY.Input,{placeholder:`Send a message...`,className:`aui-composer-input caret-primary placeholder:text-muted-foreground/60 max-h-48 min-h-10 w-full resize-none bg-transparent px-2.5 py-1 text-base leading-6 outline-none`,rows:1,autoFocus:e,enterKeyHint:`send`,"aria-label":`Message input`}),(0,b.jsx)($2,{})]})})}),$2=()=>(0,b.jsxs)(`div`,{className:`aui-composer-action-wrapper relative flex items-center justify-between`,children:[(0,b.jsx)(k1,{}),(0,b.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,b.jsxs)(IL,{condition:e=>e.thread.capabilities.dictation,children:[(0,b.jsx)(IL,{condition:e=>e.composer.dictation==null,children:(0,b.jsx)(RY.Dictate,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Voice input`,side:`bottom`,type:`button`,variant:`ghost`,size:`icon`,className:`aui-composer-dictate text-muted-foreground hover:text-foreground size-7 rounded-full`,"aria-label":`Start voice input`,children:(0,b.jsx)(Gf,{className:`aui-composer-dictate-icon size-4`})})})}),(0,b.jsx)(IL,{condition:e=>e.composer.dictation!=null,children:(0,b.jsx)(RY.StopDictation,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Stop dictation`,side:`bottom`,type:`button`,variant:`ghost`,size:`icon`,className:`aui-composer-stop-dictation text-destructive size-7 rounded-full`,"aria-label":`Stop voice input`,children:(0,b.jsx)(ip,{className:`aui-composer-stop-dictation-icon size-3.5 animate-pulse fill-current`})})})})]}),(0,b.jsx)(IL,{condition:e=>!e.thread.isRunning||e.thread.voice!==void 0,children:(0,b.jsx)(RY.Send,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Send message`,side:`bottom`,type:`button`,variant:`default`,size:`icon`,className:`aui-composer-send size-7 rounded-full`,"aria-label":`Send message`,children:(0,b.jsx)(vf,{className:`aui-composer-send-icon size-4`})})})}),(0,b.jsx)(IL,{condition:e=>e.thread.isRunning&&e.thread.voice===void 0,children:(0,b.jsx)(RY.Cancel,{asChild:!0,children:(0,b.jsx)(o,{type:`button`,variant:`default`,size:`icon`,className:`aui-composer-cancel size-7 rounded-full`,"aria-label":`Stop generating`,children:(0,b.jsx)(ip,{className:`aui-composer-cancel-icon size-3.5 fill-current`})})})})]})]}),e4=()=>(0,b.jsx)(XX.Error,{children:(0,b.jsx)(uX.Root,{className:`aui-message-error-root border-destructive bg-destructive/10 text-destructive dark:bg-destructive/5 mt-2 rounded-md border p-3 text-sm dark:text-red-200`,children:(0,b.jsx)(uX.Message,{className:`aui-message-error-message line-clamp-2`})})}),t4=()=>{let{ToolFallback:e=T2,ToolGroup:t,ReasoningGroup:n,TaskGroup:r}=(0,y.useContext)(L2),i=r?F2:N2;return(0,b.jsxs)(XX.Root,{"data-slot":`aui_assistant-message-root`,"data-role":`assistant`,className:`fade-in slide-in-from-bottom-1 animate-in relative -mb-7.5 pb-7.5 duration-150 [contain-intrinsic-size:auto_200px] [content-visibility:auto]`,children:[(0,b.jsxs)(`div`,{"data-slot":`aui_assistant-message-content`,className:`text-foreground px-2 leading-relaxed wrap-break-word`,children:[(0,b.jsx)(XX.GroupedParts,{groupBy:i,children:({part:i,children:a})=>{switch(i.type){case`group-chainOfThought`:return(0,b.jsx)(`div`,{"data-slot":`aui_chain-of-thought`,children:a});case`group-task`:return r?(0,b.jsx)(r,{group:i}):null;case`group-tool`:return t?(0,b.jsx)(t,{group:i,children:a}):(0,b.jsxs)(O2,{variant:`ghost`,children:[(0,b.jsx)(k2,{count:i.indices.length,active:i.status.type===`running`}),(0,b.jsx)(A2,{children:a})]});case`group-reasoning`:{if(n)return(0,b.jsx)(n,{group:i,children:a});let e=i.status.type===`running`;return(0,b.jsxs)(Q0,{streaming:e,children:[(0,b.jsx)(Y0,{active:e}),(0,b.jsx)(X0,{"aria-busy":e,children:(0,b.jsx)(Z0,{children:a})})]})}case`text`:return(0,b.jsx)(B0,{});case`reasoning`:return(0,b.jsx)(t2,{...i});case`tool-call`:return i.toolUI??(0,b.jsx)(e,{...i});case`data`:return i.dataRendererUI;case`file`:return(0,b.jsx)(`div`,{"data-slot":`aui_assistant-message-file`,className:`py-1`,children:(0,b.jsx)(H1,{...i})});case`image`:return(0,b.jsx)(`div`,{"data-slot":`aui_assistant-message-image`,className:`py-1`,children:(0,b.jsx)(a0,{...i})});case`indicator`:return(0,b.jsx)(`span`,{"data-slot":`aui_assistant-message-indicator`,className:`animate-pulse font-sans`,"aria-label":`Assistant is working`,children:`●`});default:return null}}}),(0,b.jsx)(e4,{})]}),(0,b.jsxs)(`div`,{"data-slot":`aui_assistant-message-footer`,className:a(`ms-2 flex items-center`,`min-h-7.5 pt-1.5`),children:[(0,b.jsx)(c4,{}),(0,b.jsx)(n4,{})]})]})},n4=()=>(0,b.jsxs)(hq.Root,{hideWhenRunning:!0,autohide:`not-last`,className:`aui-assistant-action-bar-root text-muted-foreground animate-in fade-in col-start-3 row-start-2 -ms-1 flex gap-1 duration-200`,children:[(0,b.jsx)(hq.Copy,{asChild:!0,children:(0,b.jsxs)(p1,{tooltip:`Copy`,children:[(0,b.jsx)(IL,{condition:e=>e.message.isCopied,children:(0,b.jsx)(Sf,{className:`animate-in zoom-in-50 fade-in duration-200 ease-out`})}),(0,b.jsx)(IL,{condition:e=>!e.message.isCopied,children:(0,b.jsx)(Mf,{className:`animate-in zoom-in-75 fade-in duration-150`})})]})}),(0,b.jsxs)(IL,{condition:e=>e.thread.capabilities.feedback,children:[(0,b.jsx)(hq.FeedbackPositive,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Helpful`,className:`data-[submitted=true]:bg-accent data-[submitted=true]:text-accent-foreground`,children:(0,b.jsx)(cp,{})})}),(0,b.jsx)(hq.FeedbackNegative,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Not helpful`,className:`data-[submitted=true]:bg-accent data-[submitted=true]:text-accent-foreground`,children:(0,b.jsx)(sp,{})})})]}),(0,b.jsx)(hq.Reload,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Refresh`,children:(0,b.jsx)(Qf,{})})}),(0,b.jsxs)(Eq.Root,{children:[(0,b.jsx)(Eq.Trigger,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`More`,className:`data-[state=open]:bg-accent`,children:(0,b.jsx)(Ff,{})})}),(0,b.jsx)(Eq.Content,{side:`bottom`,align:`start`,sideOffset:6,className:`aui-action-bar-more-content bg-popover text-popover-foreground data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=closed]:animate-out data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] overflow-hidden rounded-xl border p-1.5`,children:(0,b.jsx)(hq.ExportMarkdown,{asChild:!0,children:(0,b.jsxs)(Eq.Item,{className:`aui-action-bar-more-item hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,children:[(0,b.jsx)(Pf,{className:`size-4`}),`Export as Markdown`]})})})]})]}),r4=e=>(0,b.jsx)(`div`,{"data-slot":`aui_user-message-file`,className:`py-1`,children:(0,b.jsx)(H1,{...e})}),i4=e=>(0,b.jsx)(`div`,{"data-slot":`aui_user-message-image`,className:`py-1`,children:(0,b.jsx)(a0,{...e})}),a4=()=>(0,b.jsxs)(XX.Root,{"data-slot":`aui_user-message-root`,className:`fade-in slide-in-from-bottom-1 animate-in grid auto-rows-auto grid-cols-[minmax(72px,1fr)_auto] content-start gap-y-2 px-2 duration-150 [contain-intrinsic-size:auto_200px] [content-visibility:auto] [&:where(>*)]:col-start-2`,"data-role":`user`,children:[(0,b.jsx)(D1,{}),(0,b.jsxs)(`div`,{className:`aui-user-message-content-wrapper relative col-start-2 min-w-0`,children:[(0,b.jsx)(`div`,{className:`aui-user-message-content peer bg-muted text-foreground rounded-(--composer-radius) px-4 py-2 wrap-break-word empty:hidden`,children:(0,b.jsx)(XX.Parts,{components:{File:r4,Image:i4}})}),(0,b.jsx)(`div`,{className:`aui-user-action-bar-wrapper absolute start-0 top-1/2 -translate-x-full -translate-y-1/2 pe-2 peer-empty:hidden rtl:translate-x-full`,children:(0,b.jsx)(o4,{})})]}),(0,b.jsx)(c4,{"data-slot":`aui_user-branch-picker`,className:`col-span-full col-start-1 -me-1 justify-end`})]}),o4=()=>(0,b.jsx)(hq.Root,{hideWhenRunning:!0,autohide:`not-last`,className:`aui-user-action-bar-root flex flex-col items-end`,children:(0,b.jsx)(hq.Edit,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Edit`,className:`aui-user-action-edit`,children:(0,b.jsx)(Jf,{})})})}),s4=()=>(0,b.jsx)(XX.Root,{"data-slot":`aui_edit-composer-wrapper`,className:`flex flex-col px-2 [contain-intrinsic-size:auto_200px] [content-visibility:auto]`,children:(0,b.jsxs)(RY.Root,{className:`aui-edit-composer-root border-foreground/10 focus-within:border-foreground/25 ms-auto flex w-full max-w-[85%] cursor-text flex-col rounded-(--composer-radius) border bg-(--composer-bg) transition-[border-color]`,children:[(0,b.jsx)(RY.Input,{className:`aui-edit-composer-input text-foreground min-h-14 w-full resize-none bg-transparent px-4 pt-3 pb-1 text-base outline-none`,autoFocus:!0}),(0,b.jsxs)(`div`,{className:`aui-edit-composer-footer mx-2.5 mb-2.5 flex items-center gap-1.5 self-end`,children:[(0,b.jsx)(RY.Cancel,{asChild:!0,children:(0,b.jsx)(o,{variant:`ghost`,size:`sm`,className:`h-8 px-3`,children:`Cancel`})}),(0,b.jsx)(RY.Send,{asChild:!0,children:(0,b.jsx)(o,{size:`sm`,className:`h-8 px-3`,children:`Update`})})]})]})}),c4=({className:e,...t})=>(0,b.jsxs)(Uq.Root,{hideWhenSingleBranch:!0,className:a(`aui-branch-picker-root text-muted-foreground -ms-2 me-2 inline-flex items-center text-xs`,e),...t,children:[(0,b.jsx)(Uq.Previous,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Previous`,children:(0,b.jsx)(wf,{})})}),(0,b.jsxs)(`span`,{className:`aui-branch-picker-state font-medium`,children:[(0,b.jsx)(Uq.Number,{}),` / `,(0,b.jsx)(Uq.Count,{})]}),(0,b.jsx)(Uq.Next,{asChild:!0,children:(0,b.jsx)(p1,{tooltip:`Next`,children:(0,b.jsx)(Tf,{})})})]}),l4=()=>{let[e,t]=(0,y.useState)(``),n=$(e=>e.threads.threadIds.length>0);return(0,b.jsxs)(d4,{children:[(0,b.jsx)(v4,{}),n&&(0,b.jsx)(u4,{value:e,onValueChange:t}),(0,b.jsx)(f4,{searchQuery:n?e:``})]})},u4=(0,y.forwardRef)(({className:e,value:t,onValueChange:n,...r},i)=>(0,b.jsxs)(`div`,{"data-slot":`aui_thread-list-search`,className:`relative px-0.5 py-1`,children:[(0,b.jsx)(ep,{"data-slot":`aui_thread-list-search-icon`,className:`text-muted-foreground pointer-events-none absolute start-3 top-1/2 size-4 -translate-y-1/2`}),(0,b.jsx)(p,{ref:i,type:`search`,value:t,onChange:e=>n(e.target.value),"aria-label":`Search threads`,placeholder:`Search threads`,className:a(`h-8 ps-8 text-sm`,e),...r})]}));u4.displayName=`ThreadListSearch`;var d4=({className:e,...t})=>(0,b.jsx)(QZ.Root,{"data-slot":`aui_thread-list-root`,className:a(`flex flex-col gap-0.5`,e),...t}),f4=({className:e,searchQuery:t=``,...n})=>(0,b.jsxs)(`div`,{"data-slot":`aui_thread-list-items`,className:a(`flex flex-col gap-0.5`,e),...n,children:[(0,b.jsx)(IL,{condition:e=>e.threads.isLoading,children:(0,b.jsx)(y4,{})}),(0,b.jsx)(IL,{condition:e=>!e.threads.isLoading,children:(0,b.jsx)(g4,{searchQuery:t})})]}),p4=864e5,m4=(e,t)=>!e||e.getTime()>=t?`Today`:e.getTime()>=t-p4?`Yesterday`:`Earlier`,h4=(e=``)=>{let t=$(e=>e.threads.threadIds),n=$(e=>e.threads.threadItems),r=e.trim().toLowerCase();return(0,y.useMemo)(()=>{let e=new Map(n.map(e=>[e.id,e])),i=t=>!r||(e.get(t)?.title||`New Chat`).toLowerCase().includes(r),a=t=>e.get(t)?.status===`archived`,o=t.map(t=>e.get(t)?.lastMessageAt),s=t.map((e,t)=>({id:e,index:t})).filter(({id:e})=>i(e)&&!a(e)).map(({index:e})=>e),c=t.map((e,t)=>({id:e,index:t})).filter(({id:e})=>i(e)&&a(e)).map(({index:e})=>e);if(!s.some(e=>o[e]))return{threadIds:t,filteredIndices:s,archivedIndices:c,groups:null};let l=new Date,u=new Date(l.getFullYear(),l.getMonth(),l.getDate()).getTime(),d=e=>o[e]?.getTime()??2**53-1,f=[...s].sort((e,t)=>d(t)-d(e)),p=[];for(let e of f){let t=m4(o[e],u),n=p[p.length-1];n?.label===t?n.indices.push(e):p.push({label:t,indices:[e]})}return{threadIds:t,filteredIndices:s,archivedIndices:c,groups:p}},[t,n,r])},g4=({searchQuery:e=``})=>{let{threadIds:t,filteredIndices:n,archivedIndices:r,groups:i}=h4(e);return e.trim()&&n.length===0&&r.length===0?(0,b.jsx)(`div`,{"data-slot":`aui_thread-list-empty`,className:`text-muted-foreground px-2.5 py-4 text-sm`,children:`No threads found`}):i?(0,b.jsxs)(b.Fragment,{children:[i.map(e=>(0,b.jsxs)(y.Fragment,{children:[(0,b.jsx)(`div`,{"data-slot":`aui_thread-list-group-label`,className:`text-muted-foreground px-2.5 pt-3 pb-1 text-xs font-medium`,children:e.label}),e.indices.map(e=>(0,b.jsx)(QZ.ItemByIndex,{index:e,components:{ThreadListItem:b4}},t[e]))]},e.label)),(0,b.jsx)(_4,{threadIds:t,indices:r})]}):(0,b.jsxs)(b.Fragment,{children:[n.map(e=>(0,b.jsx)(QZ.ItemByIndex,{index:e,components:{ThreadListItem:b4}},t[e])),(0,b.jsx)(_4,{threadIds:t,indices:r})]})},_4=({threadIds:e,indices:t})=>t.length?(0,b.jsxs)(y.Fragment,{children:[(0,b.jsx)(`div`,{"data-slot":`aui_thread-list-group-label`,className:`text-muted-foreground px-2.5 pt-3 pb-1 text-xs font-medium`,children:`Archived`}),t.map(t=>(0,b.jsx)(QZ.ItemByIndex,{index:t,components:{ThreadListItem:b4}},e[t]))]}):null,v4=(0,y.forwardRef)(({className:e,labelClassName:t,children:n,...r},i)=>(0,b.jsx)(QZ.New,{asChild:!0,children:(0,b.jsx)(o,{ref:i,variant:`ghost`,"data-slot":`aui_thread-list-new`,className:a(`hover:bg-muted data-active:bg-muted h-8 justify-start gap-2 rounded-md px-2.5 text-sm font-normal`,e),...r,children:n??(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(Zf,{"data-slot":`aui_thread-list-new-icon`,className:`size-4 shrink-0`}),(0,b.jsx)(`span`,{"data-slot":`aui_thread-list-new-label`,className:a(`whitespace-nowrap`,t),children:`New Thread`})]})})}));v4.displayName=`ThreadListNew`;var y4=()=>(0,b.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:Array.from({length:5},(e,t)=>(0,b.jsx)(`div`,{role:`status`,"aria-label":`Loading threads`,"data-slot":`aui_thread-list-skeleton-wrapper`,className:`flex h-8 items-center px-2.5`,children:(0,b.jsx)(M2,{"data-slot":`aui_thread-list-skeleton`,className:`h-3.5 w-full`})},t))}),b4=()=>{let e=$(e=>e.threadListItem.isRunning),t=$(e=>e.threadListItem.status)===`archived`,[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(null),o=(0,y.useRef)(!1);return(0,y.useEffect)(()=>{!n&&o.current&&(o.current=!1,i.current?.focus())},[n]),(0,b.jsxs)(aQ.Root,{"data-slot":`aui_thread-list-item`,"data-archived":t||void 0,className:a(`group hover:bg-muted focus-visible:bg-muted data-active:bg-muted has-focus-visible:bg-muted has-data-[state=open]:bg-muted relative flex h-8 items-center rounded-md transition-colors focus-visible:outline-none`,t&&`opacity-60`),children:[n?(0,b.jsx)(x4,{onDone:e=>{o.current=e,r(!1)}}):(0,b.jsxs)(aQ.Trigger,{ref:i,"data-slot":`aui_thread-list-item-trigger`,className:`focus-visible:ring-ring/50 flex h-full min-w-0 flex-1 items-center rounded-md px-2.5 text-start text-sm outline-none group-hover:pe-9 group-has-focus-visible:pe-9 group-has-data-[state=open]:pe-9 group-data-active:pe-9 focus-visible:ring-1`,children:[e&&(0,b.jsx)(Uf,{"aria-hidden":!0,"data-slot":`aui_thread-list-item-running`,className:`text-muted-foreground me-1.5 size-3.5 shrink-0 animate-spin`}),(0,b.jsx)(`span`,{"data-slot":`aui_thread-list-item-title`,className:`min-w-0 flex-1 truncate`,children:(0,b.jsx)(aQ.Title,{fallback:`New Chat`})}),e&&(0,b.jsx)(`span`,{className:`sr-only`,children:`Running`})]}),(0,b.jsx)(S4,{archived:t,onRename:()=>r(!0)})]})},x4=({onDone:e})=>{let t=Q(),n=$(e=>e.threadListItem.title)??``,[r,i]=(0,y.useState)(n),a=(0,y.useRef)(null),o=(0,y.useRef)(!1);(0,y.useEffect)(()=>{a.current?.select()},[]);let s=i=>{if(o.current)return;o.current=!0;let s=r.trim();if(!s||s===n){e(i);return}Promise.resolve().then(()=>t.threadListItem.rename(s)).then(()=>e(i),()=>{o.current=!1,i&&a.current?.focus()})},c=()=>{o.current||(o.current=!0,e(!0))};return(0,b.jsx)(p,{ref:a,autoFocus:!0,"data-slot":`aui_thread-list-item-rename`,"aria-label":`Rename thread`,value:r,className:`h-7 min-w-0 flex-1 ps-2.5 pe-9 text-sm`,onChange:e=>i(e.target.value),onBlur:()=>s(!1),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),s(!0)):e.key===`Escape`&&(e.preventDefault(),c())}})},S4=({archived:e,onRename:t})=>(0,b.jsxs)(gQ.Root,{sharedFocusGroup:!0,children:[(0,b.jsx)(gQ.Trigger,{asChild:!0,children:(0,b.jsxs)(o,{variant:`ghost`,size:`icon`,"data-slot":`aui_thread-list-item-more`,className:`data-[state=open]:bg-accent absolute end-1.5 top-1/2 size-6 -translate-y-1/2 p-0 opacity-0 group-hover:opacity-100 group-has-focus-visible:opacity-100 group-data-active:opacity-100 data-[state=open]:opacity-100`,children:[(0,b.jsx)(Ff,{className:`size-3.5`}),(0,b.jsx)(`span`,{className:`sr-only`,children:`More options`})]})}),(0,b.jsxs)(gQ.Content,{side:`right`,align:`start`,sideOffset:6,"data-slot":`aui_thread-list-item-more-content`,className:`bg-popover text-popover-foreground data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=closed]:animate-out data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 overflow-hidden rounded-xl border p-1.5`,children:[(0,b.jsxs)(gQ.Item,{"data-slot":`aui_thread-list-item-more-item`,className:`hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,onSelect:t,children:[(0,b.jsx)(Jf,{className:`size-4`}),`Rename`]}),e?(0,b.jsx)(aQ.Unarchive,{asChild:!0,children:(0,b.jsxs)(gQ.Item,{"data-slot":`aui_thread-list-item-more-item`,className:`hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,children:[(0,b.jsx)(pf,{className:`size-4`}),`Unarchive`]})}):(0,b.jsx)(aQ.Archive,{asChild:!0,children:(0,b.jsxs)(gQ.Item,{"data-slot":`aui_thread-list-item-more-item`,className:`hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,children:[(0,b.jsx)(mf,{className:`size-4`}),`Archive`]})}),(0,b.jsx)(aQ.Delete,{asChild:!0,children:(0,b.jsxs)(gQ.Item,{"data-slot":`aui_thread-list-item-more-item`,className:`text-destructive hover:bg-destructive/10 hover:text-destructive focus:bg-destructive/10 focus:text-destructive flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,children:[(0,b.jsx)(lp,{className:`size-4`}),`Delete`]})})]})]}),C4=`bg-background border border-border/60 dark:bg-popover`;function w4({phase:e,attempt:t,resumedTokens:n,onRetry:r,className:i,...o}){return e===`online`?null:(0,b.jsxs)(`div`,{"data-slot":`connection-state`,className:a(C4,`fade-in slide-in-from-top-1 animate-in flex w-full max-w-sm items-center gap-2.5 rounded-2xl px-3.5 py-2.5 duration-300`,i),...o,children:[e===`dropped`&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(jf,{className:`size-3.5 shrink-0 text-amber-600 dark:text-amber-400`}),(0,b.jsx)(`span`,{className:`min-w-0 flex-1 text-[13px]`,children:`Connection lost. The run kept going on the server.`}),(0,b.jsx)(`button`,{type:`button`,onClick:r,className:`text-foreground/70 hover:bg-foreground/[0.06] hover:text-foreground/95 shrink-0 rounded-full px-2.5 py-1 text-xs font-medium transition-[background-color,color,scale] duration-150 active:scale-[0.96]`,children:`Reconnect`})]}),e===`reconnecting`&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(Uf,{className:`text-foreground/40 size-3.5 shrink-0 animate-spin motion-reduce:animate-none`}),(0,b.jsx)(`span`,{className:`min-w-0 flex-1 text-[13px]`,children:`Reconnecting`}),t!==void 0&&(0,b.jsxs)(`span`,{className:a(`font-mono text-[11px] tracking-tight`,`text-foreground/30 shrink-0 tabular-nums`),children:[`attempt `,t]})]}),e===`resumed`&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(Sf,{className:`size-3.5 shrink-0 text-emerald-500`}),(0,b.jsx)(`span`,{className:`min-w-0 flex-1 text-[13px]`,children:`Picked the stream back up.`}),n!==void 0&&(0,b.jsxs)(`span`,{className:a(`font-mono text-[11px] tracking-tight`,`text-foreground/30 shrink-0 tabular-nums`),children:[`+`,n,` tokens`]})]})]})}var T4=[`pending`,`testing`,`confirmed`,`rejected`,`blocked`],E4=H(T4),D4=V({tasks:B(V({id:R(),title:R(),status:E4.default(`pending`),note:R().optional()})),target:R().optional(),phase:R().optional()}),O4={tasks:[]};function k4(e){return typeof e==`string`&&T4.includes(e)}function A4(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase().replace(/[^a-z_-]/g,``);if(t===`pending`||t===`todo`||t===`hypothesis`||t===`planned`||t===`open`)return`pending`;if(t===`testing`||t===`in_progress`||t===`inprogress`||t===`active`||t===`probing`)return`testing`;if(t===`confirmed`||t===`verified`||t===`exploited`||t===`vulnerable`||t===`success`)return`confirmed`;if(t===`rejected`||t===`tested_safe`||t===`testedsafe`||t===`safe`||t===`clean`||t===`not_vulnerable`||t===`notvulnerable`||t===`invalid`)return`rejected`;if(t===`blocked`||t===`justified_blocked`||t===`justifiedblocked`||t===`needs_auth`||t===`needsauth`||t===`untestable`)return`blocked`}var j4=/https?:\/\/[^\s<>")']+/i,M4=/\b(?:[a-z0-9-]+\.)+[a-z]{2,}\b/i;function N4(e){if(!e||typeof e!=`string`)return null;let t=e.match(j4);if(t?.[0]){let e=t[0].trim().replace(/[),.!?;:]$/,``);if(e.length>0&&e.length<512)return e}let n=e.match(M4);if(n?.[0]){let e=n[0].trim().replace(/[),.!?;:]$/,``);if(e.length>0&&e.length<256&&!e.endsWith(`.ts`)&&!e.endsWith(`.js`)&&!e.endsWith(`.json`)&&!e.endsWith(`.md`)&&!e.endsWith(`.html`)&&!e.endsWith(`.txt`))return e}return null}function P4(e){let t=0;for(let n of e){let e=n.id.match(/^T-(\d+)$/i);e&&(t=Math.max(t,Number.parseInt(e[1],10)))}return`T-${t+1}`}function F4(e,t){let n=new Map;for(let t of e)n.set(t.id,{...t});for(let e of t){let t=n.get(e.id);t?n.set(e.id,{id:e.id,title:e.title||t.title,status:e.status||t.status,note:e.note===void 0?t.note:e.note}):n.set(e.id,{...e})}return Array.from(n.values())}var I4=/-\s*\[(pending|testing|confirmed|rejected|blocked)\]\s*([A-Za-z0-9_-]+):\s*([^—\n\r]+?)(?:\s*—\s*([^\n\r]+))?$/gim,L4=/Task\s+([A-Za-z0-9_-]+)\s+(?:added|updated):\s*\[(pending|testing|confirmed|rejected|blocked)\]\s*([^—\n\r]+?)(?:\s*—\s*([^\n\r]+))?$/gim,R4=/<kifaru_dossier\s+target="([^"]+)"(?:\s+phase="([^"]+)")?/i;function z4(e,t=[]){let n=[...t],r=new Map;for(let e of n)r.set(e.title.trim().toLowerCase(),e);let i=e.split(/\r?\n/);for(let e of i){let t=e.trim();if(!t.startsWith(`|`)||!t.endsWith(`|`))continue;let i=t.split(`|`).map(e=>e.trim()),a=i.filter((e,t)=>t>0&&t<i.length-1);if(a.length<2||a.every(e=>/^[-:=|\s]+$/.test(e)))continue;let o=A4(a[1]),s=a[0],c=a[2];if(o||(o=A4(a[0]),o&&(s=a[1],c=a[2])),!o||!s||(s=s.replace(/^[`*_\s]+|[`*_\s]+$/g,``).trim(),!s||s.toLowerCase()===`cell`||s.toLowerCase()===`task`))continue;let l,u=s.match(/^(T-\d+)[:\s—-]+(.*)$/i);u?.[1]&&(l=u[1].toUpperCase(),s=u[2].trim());let d=s.toLowerCase(),f=r.get(d);if(f)f.status=o,c&&(f.note=c.trim());else{let e={id:l||P4(n),title:s,status:o,note:c?c.trim():void 0};n.push(e),r.set(d,e)}}return n}function B4(e,t=[]){let n=[...t],r=new Map;for(let e of n)r.set(e.title.trim().toLowerCase(),e);let i=/^\s*[-*]\s*\[([ xX/!?-])\]\s*(?:([A-Za-z0-9_-]+):)?\s*([^—\n\r]+?)(?:\s*—\s*([^\n\r]+))?$/gm,a;for(;(a=i.exec(e))!==null;){let[,e,t,i,o]=a;if(!i)continue;let s=`pending`;e===`x`||e===`X`?s=`confirmed`:e===`/`?s=`testing`:e===`!`?s=`blocked`:(e===`-`||e===`?`)&&(s=`rejected`);let c=i.trim(),l=c.toLowerCase(),u=r.get(l);if(u)u.status=s,o&&(u.note=o.trim());else{let e={id:t?.startsWith(`T-`)?t.toUpperCase():P4(n),title:c,status:s,note:o?o.trim():void 0};n.push(e),r.set(l,e)}}return n}function V4(e,t=[]){let n=[...t],r=new Map;for(let e of n)r.set(e.title.trim().toLowerCase(),e);for(let t of e){let e=typeof t==`string`?t:typeof t==`object`&&t&&`note`in t?String(t.note??``):``;if(!e)continue;let i,a,o;if(/^CONFIRMED(\([^)]+\))?:/i.test(e)){i=`confirmed`;let t=e.replace(/^CONFIRMED(\([^)]+\))?:\s*/i,``).trim(),n=t.indexOf(`.`);a=(n>0&&n<120?t.slice(0,n):t.slice(0,120)).trim(),o=n>0?t.slice(n+1).trim():void 0}else if(/BLOCKED/i.test(e)&&(/coverage gap/i.test(e)||/needs auth/i.test(e))){i=`blocked`;let t=e.replace(/^Coverage gap(\s*\([^)]+\))?:\s*/i,``).trim(),n=t.indexOf(`—`);a=(n>0&&n<120?t.slice(0,n):t.slice(0,120)).trim(),o=n>0?t.slice(n+1).trim():t}if(i&&a){let e=a.toLowerCase(),t=r.get(e);if(t)t.status=i,o&&(t.note=o);else{let t={id:P4(n),title:a,status:i,note:o};n.push(t),r.set(e,t)}}}return n}function H4(e){let t=[],n,r;for(let i of e){if(i.role===`user`){let e=``;if(typeof i.content==`string`)e=i.content;else if(Array.isArray(i.content))for(let t of i.content)typeof t==`object`&&t&&`type`in t&&t.type===`text`&&(e+=` ${t.text??``}`);let t=N4(e);t&&(n=t)}if(i.role===`custom`&&i.customType===`kifaru-dossier`){let e=typeof i.content==`string`?i.content:``,a=e.match(/Bound target:\s*([^\n\r]+)/i)||e.match(/Session bound to target\s*([^\n\r.]+)/i);a?.[1]&&(n=a[1].trim());let o=e.match(/Phase:\s*([a-zA-Z0-9_-]+)/i);o?.[1]&&(r=o[1].trim());let s;for(I4.lastIndex=0;(s=I4.exec(e))!==null;){let[,e,n,r,i]=s;n&&r&&k4(e)&&(t=F4(t,[{id:n.trim(),title:r.trim(),status:e,note:i?i.trim():void 0}]))}}if(i.role===`assistant`&&Array.isArray(i.content)){for(let e of i.content)if(typeof e==`object`&&e&&`type`in e){if(e.type===`text`&&typeof e.text==`string`){let i=e.text,a=N4(i);a&&!n&&(n=a);let o=i.match(R4);o?.[1]&&(n=o[1].trim()),o?.[2]&&(r=o[2].trim()),t=z4(i,t),t=B4(i,t)}if(e.type===`tool-call`||e.type===`toolCall`){let i=e,a=i.name??i.toolName,o=i.args??i.arguments;if(a===`kifaru_dossier`&&o&&(typeof o.target==`string`&&o.target.trim()&&(n=o.target.trim()),typeof o.phase==`string`&&o.phase.trim()&&(r=o.phase.trim()),o.action===`task`)){let e=typeof o.taskId==`string`?o.taskId.trim():void 0,n=typeof o.title==`string`?o.title.trim():void 0,r=typeof o.note==`string`?o.note.trim():void 0;e&&(t=F4(t,[{id:e,title:n||e,status:k4(o.status)?o.status:`pending`,note:r}]))}}}}if(i.role===`toolResult`){let e=i;for(let i of e.content??[])if(i.type===`text`&&i.text){let e=i.text.trim();if(e.startsWith(`{`)&&e.endsWith(`}`))try{let i=JSON.parse(e);if(typeof i.target==`string`&&(n=i.target),typeof i.phase==`string`&&(r=i.phase),Array.isArray(i.tasks)){let e=[];for(let t of i.tasks)typeof t.id==`string`&&typeof t.title==`string`&&e.push({id:t.id,title:t.title,status:k4(t.status)?t.status:`pending`,note:typeof t.note==`string`?t.note:void 0});t=F4(t,e)}Array.isArray(i.observations)&&(t=V4(i.observations,t))}catch{}t=z4(e,t),t=B4(e,t);let a;for(L4.lastIndex=0;(a=L4.exec(e))!==null;){let[,e,n,r,i]=a;e&&r&&k4(n)&&(t=F4(t,[{id:e.trim(),title:r.trim(),status:n,note:i?i.trim():void 0}]))}let o=e.match(R4);for(o?.[1]&&(n=o[1].trim()),o?.[2]&&(r=o[2].trim()),I4.lastIndex=0;(a=I4.exec(e))!==null;){let[,e,n,r,i]=a;n&&r&&k4(e)&&(t=F4(t,[{id:n.trim(),title:r.trim(),status:e,note:i?i.trim():void 0}]))}}}}return{tasks:t,target:n,phase:r}}var U4={pending:Af,testing:Uf,confirmed:Sf,rejected:Of,blocked:Ef},W4={pending:{badge:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,text:`text-muted-foreground`,ring:`border-border`},testing:{badge:`bg-blue-500/10 text-blue-500 border-blue-500/30 hover:bg-blue-500/20`,text:`text-blue-500`,ring:`border-blue-500/40 bg-blue-500/10`},confirmed:{badge:`bg-emerald-500/10 text-emerald-500 border-emerald-500/30 hover:bg-emerald-500/20`,text:`text-emerald-500`,ring:`border-emerald-500/50 bg-emerald-500/20`},rejected:{badge:`bg-rose-500/10 text-rose-500 border-rose-500/30 hover:bg-rose-500/20`,text:`text-rose-500`,ring:`border-rose-500/40 bg-rose-500/10`},blocked:{badge:`bg-amber-500/10 text-amber-500 border-amber-500/30 hover:bg-amber-500/20`,text:`text-amber-500`,ring:`border-amber-500/40 bg-amber-500/10`}};function G4({className:e=``,onClose:t}){let[n,{setState:r}]=tB(`taskBoard`,{description:`A task board panel for the target dossier tracking hunt theses, tests, and findings. Use update_taskBoard with tasks.add/update/remove/clear to manage tasks. Tasks have id (e.g. T-1), title, status (pending|testing|confirmed|rejected|blocked), and optional note.`,stateSchema:D4,initialState:O4}),i=Y$(e=>e.messages),[a,s]=(0,y.useState)(``),[c,l]=(0,y.useState)(`all`),[u,d]=(0,y.useState)(!1);(0,y.useEffect)(()=>{if(!i||i.length===0)return;let e=H4(i);(e.tasks.length!==0||e.target||e.phase)&&r(t=>{let n=F4(t?.tasks??[],e.tasks),r=e.target&&e.target!==t?.target,i=e.phase&&e.phase!==t?.phase,a=n.length!==(t?.tasks?.length??0)||n.some((e,n)=>{let r=t?.tasks?.[n];return!r||r.id!==e.id||r.status!==e.status||r.title!==e.title||r.note!==e.note});return!r&&!i&&!a?t:{...t,tasks:n,target:e.target??t?.target,phase:e.phase??t?.phase}})},[i,r]);let f=n?.target;(0,y.useEffect)(()=>{if(!f)return;let e=!1;return fetch(`/api/v1/workbench/dossier?target=${encodeURIComponent(f)}`).then(e=>e.ok?e.json():null).then(t=>{!e&&t&&Array.isArray(t.tasks)&&t.tasks.length!==0&&r(e=>{let n=F4(e?.tasks??[],t.tasks??[]),r=t.target&&!e?.target,i=t.phase&&!e?.phase,a=n.length!==(e?.tasks?.length??0)||n.some((t,n)=>{let r=e?.tasks?.[n];return!r||r.id!==t.id||r.status!==t.status||r.title!==t.title});return!r&&!i&&!a?e:{...e,tasks:n,target:e?.target??t.target,phase:e?.phase??t.phase}})}).catch(()=>{}),()=>{e=!0}},[f,r]);let m=n?.tasks??[],h=n?.target,g=n?.phase,_=(0,y.useMemo)(()=>{let e={all:m.length};for(let t of T4)e[t]=0;for(let t of m)e[t.status]=(e[t.status]??0)+1;return e},[m]),v=(0,y.useMemo)(()=>c===`all`?m:m.filter(e=>e.status===c),[m,c]),x=(e,t,n)=>{let r=t||h;r&&fetch(`/api/v1/workbench/dossier`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({target:r,tasks:e,phase:n||g})}).catch(()=>{})},S=e=>{let t=`pending`;e.status===`pending`?t=`testing`:e.status===`testing`?t=`confirmed`:e.status===`confirmed`?t=`pending`:e.status===`blocked`?t=`testing`:e.status===`rejected`&&(t=`pending`);let n=m.map(n=>n.id===e.id?{...n,status:t}:n);r(e=>({...e,tasks:n})),x(n)},C=(e,t)=>{let n=m.map(n=>n.id===e?{...n,status:t}:n);r(e=>({...e,tasks:n})),x(n)},w=e=>{let t=m.filter(t=>t.id!==e);r(e=>({...e,tasks:t})),x(t)},T=()=>{let e=a.trim();if(!e)return;let t={id:P4(m),title:e,status:`pending`},n=[...m,t];r(e=>({...e,tasks:n})),x(n),s(``),d(!1)};return(0,b.jsxs)(`div`,{className:`flex h-full flex-col bg-card text-card-foreground ${e}`,children:[(0,b.jsxs)(`header`,{className:`flex items-center justify-between border-b border-border px-3.5 py-2.5`,children:[(0,b.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,b.jsx)(Hf,{className:`size-4.5 text-muted-foreground shrink-0`,"aria-hidden":`true`}),(0,b.jsx)(`h2`,{className:`text-sm font-semibold tracking-tight text-foreground truncate`,children:`Task Board`}),m.length>0?(0,b.jsx)(Kx,{variant:`secondary`,className:`px-1.5 py-0 text-[11px] font-mono font-medium`,children:m.length}):null]}),(0,b.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[h?(0,b.jsxs)(`div`,{className:`flex items-center gap-1 text-[11px] text-muted-foreground bg-muted/60 px-2 py-0.5 rounded-md font-mono truncate max-w-32`,title:`Bound target: ${h}`,children:[(0,b.jsx)(ap,{className:`size-3 text-primary shrink-0`}),(0,b.jsx)(`span`,{className:`truncate`,children:h})]}):null,g?(0,b.jsx)(Kx,{variant:`outline`,className:`text-[10px] uppercase font-mono tracking-wider px-1.5 py-0`,children:g}):null,(0,b.jsxs)(o,{variant:`ghost`,size:`icon`,className:`size-7 text-muted-foreground hover:text-foreground`,onClick:()=>d(e=>!e),title:`Add task`,children:[(0,b.jsx)(Zf,{className:`size-4`}),(0,b.jsx)(`span`,{className:`sr-only`,children:`Add task`})]}),t?(0,b.jsxs)(o,{variant:`ghost`,size:`icon`,className:`size-7 text-muted-foreground hover:text-foreground md:hidden`,onClick:t,title:`Close panel`,children:[(0,b.jsx)(Of,{className:`size-4`}),(0,b.jsx)(`span`,{className:`sr-only`,children:`Close panel`})]}):null]})]}),m.length>0?(0,b.jsxs)(`div`,{className:`flex items-center gap-1 overflow-x-auto border-b border-border/60 px-3 py-1.5 text-xs`,children:[(0,b.jsxs)(`button`,{type:`button`,onClick:()=>l(`all`),className:`rounded-md px-2 py-0.5 text-xs font-medium transition-colors ${c===`all`?`bg-accent text-accent-foreground`:`text-muted-foreground hover:text-foreground`}`,children:[`All (`,_.all,`)`]}),T4.map(e=>{let t=_[e]??0;return t===0&&c!==e?null:(0,b.jsxs)(`button`,{type:`button`,onClick:()=>l(e),className:`flex items-center gap-1 rounded-md px-2 py-0.5 text-xs capitalize font-medium transition-colors ${c===e?`bg-accent text-accent-foreground`:`text-muted-foreground hover:text-foreground`}`,children:[(0,b.jsx)(`span`,{children:e}),(0,b.jsxs)(`span`,{className:`font-mono text-[10px] opacity-70`,children:[`(`,t,`)`]})]},e)})]}):null,u?(0,b.jsxs)(`div`,{className:`border-b border-border/80 bg-muted/30 p-2.5 flex items-center gap-2`,children:[(0,b.jsx)(p,{autoFocus:!0,value:a,onChange:e=>s(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),T()):e.key===`Escape`&&d(!1)},placeholder:`New task thesis (e.g. Test IDOR on /api/user)...`,className:`h-8 text-xs bg-background`}),(0,b.jsx)(o,{size:`sm`,className:`h-8 px-2.5 text-xs shrink-0`,onClick:T,children:`Add`})]}):null,(0,b.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-3`,children:m.length===0?(0,b.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center text-center px-4`,children:[(0,b.jsx)(`div`,{className:`flex size-14 items-center justify-center rounded-2xl bg-muted/40 mb-3 border border-border/40`,children:(0,b.jsx)(Hf,{className:`size-8 text-muted-foreground/50`,"aria-hidden":`true`})}),(0,b.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:h?`No tasks yet for ${h}`:`No tasks yet.`}),(0,b.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground max-w-56 leading-relaxed`,children:h?`Analyzing target surface and recording hunt theses...`:`Ask the assistant to add some!`}),(0,b.jsxs)(o,{variant:`outline`,size:`sm`,className:`mt-4 h-7 text-xs gap-1.5 text-muted-foreground hover:text-foreground`,onClick:()=>d(!0),children:[(0,b.jsx)(Zf,{className:`size-3.5`}),`Add task`]})]}):v.length===0?(0,b.jsxs)(`div`,{className:`flex h-full min-h-36 flex-col items-center justify-center text-center text-muted-foreground text-xs py-8`,children:[(0,b.jsxs)(`p`,{children:[`No tasks with status "`,c,`".`]}),(0,b.jsx)(o,{variant:`link`,size:`sm`,className:`text-xs mt-1`,onClick:()=>l(`all`),children:`Show all tasks`})]}):(0,b.jsx)(`ul`,{className:`flex flex-col gap-2`,children:v.map(e=>{let t=U4[e.status]??Af,n=W4[e.status]??W4.pending,r=e.status===`confirmed`;return(0,b.jsx)(`li`,{className:`group relative flex flex-col gap-1.5 rounded-lg border border-border/70 bg-card p-2.5 transition-all hover:border-border hover:shadow-xs`,children:(0,b.jsxs)(`div`,{className:`flex items-start gap-2.5`,children:[(0,b.jsx)(`button`,{type:`button`,onClick:()=>S(e),title:`Status: ${e.status}. Click to cycle.`,"aria-label":`Toggle task status for ${e.title}`,className:`mt-0.5 flex size-4.5 shrink-0 items-center justify-center rounded-md border transition-all ${r?`border-emerald-500 bg-emerald-500 text-white dark:text-black`:n.ring}`,children:r?(0,b.jsx)(Sf,{className:`size-3 stroke-[3]`}):e.status===`testing`?(0,b.jsx)(Uf,{className:`size-2.5 animate-spin text-blue-500`}):(0,b.jsx)(`span`,{className:`size-1.5 rounded-full bg-transparent group-hover:bg-muted-foreground/30`})}),(0,b.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,b.jsxs)(`div`,{className:`flex items-center gap-1.5 mb-1`,children:[(0,b.jsx)(`span`,{className:`font-mono text-[10px] font-semibold text-muted-foreground/80 tracking-wider`,children:e.id}),(0,b.jsxs)(`div`,{className:`relative inline-flex items-center`,children:[(0,b.jsx)(t,{className:`pointer-events-none absolute left-1.5 size-2.5 opacity-70`}),(0,b.jsx)(`select`,{value:e.status,onChange:t=>C(e.id,t.target.value),"aria-label":`Change status for task ${e.id}`,className:`h-4.5 appearance-none rounded border pl-4.5 pr-4 text-[10px] font-medium transition-colors cursor-pointer outline-none ${n.badge}`,children:T4.map(e=>(0,b.jsx)(`option`,{value:e,children:e},e))}),(0,b.jsx)(Cf,{className:`pointer-events-none absolute right-1 size-2.5 opacity-60`})]})]}),(0,b.jsx)(`p`,{className:`text-xs leading-snug break-words ${r?`text-muted-foreground line-through`:`text-foreground`}`,children:e.title}),e.note?(0,b.jsx)(`p`,{className:`mt-1 text-[11px] text-muted-foreground/90 bg-muted/40 rounded px-1.5 py-0.5 border border-border/40 font-mono`,children:e.note}):null]}),(0,b.jsx)(`button`,{type:`button`,onClick:()=>w(e.id),className:`opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive p-1 rounded-sm`,title:`Delete task`,"aria-label":`Delete task`,children:(0,b.jsx)(up,{className:`size-3.5`})})]})},e.id)})})}),m.length>0?(0,b.jsxs)(`footer`,{className:`border-t border-border px-3 py-2 flex items-center justify-between text-[11px] text-muted-foreground bg-muted/20`,children:[(0,b.jsxs)(`span`,{children:[_.confirmed??0,` of `,m.length,` confirmed`]}),(0,b.jsx)(o,{variant:`ghost`,size:`sm`,className:`h-6 px-1.5 text-[11px] text-muted-foreground hover:text-destructive`,onClick:()=>r(e=>({...e,tasks:[]})),children:`Clear all`})]}):null]})}function K4({request:e,respond:t}){let[n,r]=(0,y.useState)(e.kind===`editor`?e.prefill??``:``),i=e=>void t(e);return(0,b.jsxs)(`div`,{className:`bg-card grid gap-2 rounded-md border border-l-[3px] border-l-primary p-3`,role:`group`,"aria-label":`The agent is asking for approval`,children:[(0,b.jsxs)(`p`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,b.jsx)(rp,{className:`size-4 shrink-0 text-primary`,"aria-hidden":`true`}),e.title]}),e.kind===`confirm`?(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs break-words whitespace-pre-wrap`,children:e.message}):null,e.timeoutMs?(0,b.jsxs)(`p`,{className:`text-muted-foreground text-[0.7rem] tabular-nums`,children:[`Auto-dismisses after `,Math.round(e.timeoutMs/1e3),`s`]}):null,e.kind===`confirm`?(0,b.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,b.jsx)(o,{size:`sm`,onClick:()=>i({requestId:e.id,confirmed:!0}),children:`Allow`}),(0,b.jsx)(o,{size:`sm`,variant:`outline`,onClick:()=>i({requestId:e.id,confirmed:!1}),children:`Deny`})]}):null,e.kind===`select`?(0,b.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[e.options.map(t=>(0,b.jsx)(o,{size:`sm`,variant:`outline`,onClick:()=>i({requestId:e.id,value:t}),children:t},t)),(0,b.jsx)(o,{size:`sm`,variant:`ghost`,onClick:()=>i({requestId:e.id,dismissed:!0}),children:`Dismiss`})]}):null,e.kind===`input`||e.kind===`editor`?(0,b.jsxs)(`form`,{className:`grid gap-2`,onSubmit:t=>{t.preventDefault(),i({requestId:e.id,value:n})},children:[e.kind===`editor`?(0,b.jsx)(r2,{rows:6,value:n,onChange:e=>r(e.target.value)}):(0,b.jsx)(p,{value:n,placeholder:e.placeholder??``,onChange:e=>r(e.target.value)}),(0,b.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,b.jsx)(o,{size:`sm`,type:`submit`,children:`Submit`}),(0,b.jsx)(o,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i({requestId:e.id,dismissed:!0}),children:`Dismiss`})]})]}):null]})}function q4(){let{requests:e,respond:t}=X$();return e.length===0?null:(0,b.jsx)(`div`,{className:`grid gap-2 border-b px-3 py-2`,children:e.map(e=>(0,b.jsx)(K4,{request:e,respond:t},e.id))})}function J4({className:e,...t}){return(0,b.jsx)(`select`,{"data-slot":`native-select`,className:a(`border-input bg-background text-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:border-destructive h-9 w-full min-w-0 cursor-pointer rounded-md border px-3 py-1 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50`,e),...t})}function Y4({title:e,detail:t,action:n,compact:r}){return(0,b.jsxs)(h,{className:`state ${r?`state-compact`:``}`,"aria-live":`polite`,children:[(0,b.jsx)(`div`,{className:`mb-1 grid size-9 place-items-center rounded-full border bg-[var(--accent-soft)] text-primary [&_svg]:size-[18px]`,children:(0,b.jsx)(np,{"aria-hidden":`true`})}),(0,b.jsx)(`h2`,{children:e}),(0,b.jsx)(`p`,{children:t}),n]})}var X4=`session`,Z4=`kifaru:session`,Q4={kind:`latest`},$4={kind:`all`};function e3(e){return e.kind===`pinned`?e.id:e.kind===`all`?`all`:null}function t3(e){return e?e===`all`?$4:e===`latest`?Q4:{kind:`pinned`,id:e}:Q4}function n3(e,t){return t3(new URLSearchParams(e).get(X4)||t)}function r3(e,t){if(e.kind!==`all`)return e.kind===`pinned`?e.id:t?.[0]?.id}function i3(e,t){if(e.kind!==`latest`)return null;let n=t?.[0]?.id;return n?{kind:`pinned`,id:n}:null}function a3(e){return e?.source===`web`}function o3(e,t){if(e.kind===`all`)return{kind:`fresh`};if(e.kind===`pinned`){let n=t?.find(t=>t.id===e.id);return n&&!a3(n)?{kind:`external`,session:n}:{kind:`thread`,threadId:e.id}}if(!t)return{kind:`loading`};let n=t[0];return n?a3(n)?{kind:`thread`,threadId:n.id}:{kind:`external`,session:n}:{kind:`fresh`}}function s3(e,t){return!(!t||e.kind===`all`||e.kind===`pinned`&&e.id===t)}function c3(){if(typeof window>`u`)return Q4;let e=null;try{e=window.localStorage.getItem(Z4)}catch{}return n3(window.location.search,e)}function l3(e){if(typeof window>`u`)return;let t=e3(e);try{t?window.localStorage.setItem(Z4,t):window.localStorage.removeItem(Z4)}catch{}let n=new URL(window.location.href);t?n.searchParams.set(X4,t):n.searchParams.delete(X4),n.toString()!==window.location.href&&window.history.replaceState({},``,n.toString())}var u3=yK((e,t)=>({selection:c3(),select:t=>{l3(t),e({selection:t})},resolveLatest:n=>{let r=i3(t().selection,n);r&&(l3(r),e({selection:r}))}}));if(typeof window<`u`){let e=()=>l3(u3.getState().selection);e(),document.addEventListener(`astro:page-load`,e)}var d3=6e4,f3=500,p3=1e4,m3=100,h3=new Set([`listThreads`,`getThread`,`getAvailableModels`]),g3=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`WorkbenchTransportError`}},_3=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`WorkbenchRpcError`}};function v3(){return`${location.protocol===`https:`?`wss:`:`ws:`}//${location.host}/api/v1/workbench/ws`}function y3(e={}){let t=e.url??v3(),n=new Map,r=new Map,i=null,a=0,o,s=!1,c=!1,l=0;function u(t){e.onStatusChange?.(t)}function d(t){e.onError?.(t instanceof Error?t:Error(String(t)))}function f(e,t){let r=n.get(e);r&&(n.delete(e),clearTimeout(r.timer),r.reject(t))}function p(e,t=!1){return e.phase===`sent`?new g3(`OUTCOME_UNKNOWN`,`Confirmation for ${e.frame.method} was lost. The request may have been accepted. Reconnect and check the thread before retrying.`):new g3(t?`TIMEOUT_NOT_SENT`:`NOT_CONNECTED`,`The connection is unavailable. The request was not sent.`)}function m(e){if(i&&i.readyState===WebSocket.OPEN&&n.has(e.frame.id))try{i.send(JSON.stringify(e.frame)),e.phase=`sent`}catch{f(e.frame.id,new g3(`SEND_FAILED`,`The request could not be sent.`))}}function h(e){if(i&&i.readyState===WebSocket.OPEN)try{i.send(JSON.stringify(e))}catch(e){d(e),i.close()}}function g(){if(s||o!==void 0)return;let t=Math.min((e.reconnectBaseMs??f3)*2**a,p3);a+=1,o=setTimeout(()=>{o=void 0,_()},t)}function _(){if(s||i)return;u(`connecting`);let o;try{o=e.createSocket?.(t)??new WebSocket(t)}catch(e){d(e),u(`closed`),g();return}i=o,o.onopen=()=>{if(!(s||i!==o)){a=0;for(let[e,t]of r)h({kind:`subscribe`,threadId:e,includeSnapshot:c||t.includeSnapshot});c=!0;for(let e of n.values())e.phase===`queued`&&m(e);u(`open`)}},o.onmessage=e=>{if(s||i!==o)return;let t;try{t=C3(JSON.parse(String(e.data)))}catch{d(new g3(`INVALID_SERVER_FRAME`,`The workspace sent an invalid response. Reconnecting.`)),o.close();return}if(t.kind===`event`){let e=t.event,n=r.get(e.threadId)?.listeners;for(let t of[...n??[]])try{t(e)}catch(e){d(e)}return}let a=n.get(t.id);if(a){if(t.kind===`rpc_error`){f(t.id,new _3(t.code,t.message));return}if(!w3(a.frame.method,t.result)){f(t.id,new g3(`INVALID_SERVER_FRAME`,`The workspace returned an invalid result.`));return}n.delete(t.id),clearTimeout(a.timer),a.resolve(t.result===null?void 0:t.result)}},o.onerror=()=>{},o.onclose=()=>{if(!(s||i!==o)){i=null;for(let[e,t]of n)f(e,p(t));u(`closed`),g()}}}function v(t,r){if(s)return Promise.reject(new g3(`DISPOSED`,`The workspace connection was closed.`));if(!h3.has(t)&&i?.readyState!==WebSocket.OPEN)return Promise.reject(new g3(`NOT_CONNECTED`,`The connection is unavailable. The request was not sent.`));if(n.size>=m3)return Promise.reject(new g3(`TOO_MANY_REQUESTS`,`Too many workspace requests are pending.`));let a=`rpc-${l++}`;return new Promise((i,o)=>{let s=setTimeout(()=>{let e=n.get(a);e&&f(a,p(e,!0))},e.requestTimeoutMs??d3),c={frame:{kind:`rpc`,id:a,method:t,params:r},phase:`queued`,resolve:i,reject:o,timer:s};n.set(a,c),m(c)})}return _(),{dispose(){if(!s){s=!0,o&&clearTimeout(o),o=void 0,r.clear();for(let e of n.keys())f(e,new g3(`DISPOSED`,`The workspace connection was closed.`));i&&(i.onopen=null,i.onmessage=null,i.onclose=null,i.onerror=null,i.close()),i=null}},listThreads:e=>v(`listThreads`,e?[e]:[]),createThread:e=>v(`createThread`,e?[e]:[]),getThread:e=>v(`getThread`,[e]),sendMessage:(e,t)=>v(`sendMessage`,[e,t]),cancelRun:e=>v(`cancelRun`,[e]),clearQueue:e=>v(`clearQueue`,[e]),getAvailableModels:e=>v(`getAvailableModels`,e?[e]:[]),setModel:(e,t)=>v(`setModel`,[e,t]),setThinkingLevel:(e,t)=>v(`setThinkingLevel`,[e,t]),renameThread:(e,t)=>v(`renameThread`,[e,t]),archiveThread:e=>v(`archiveThread`,[e]),unarchiveThread:e=>v(`unarchiveThread`,[e]),deleteThread:e=>v(`deleteThread`,[e]),respondToHostUiRequest:(e,t)=>v(`respondToHostUiRequest`,[e,t]),subscribe(e,t,n){if(s)return()=>{};let a=e=>t(e),o=r.get(e);return o?(o.listeners.add(a),n?.includeSnapshot!==!1&&(o.includeSnapshot=!0,i?.readyState===WebSocket.OPEN&&h({kind:`subscribe`,threadId:e,includeSnapshot:!0}))):(o={listeners:new Set,includeSnapshot:n?.includeSnapshot!==!1},r.set(e,o),o.listeners.add(a),h({kind:`subscribe`,threadId:e,includeSnapshot:o.includeSnapshot})),()=>{let t=r.get(e);t&&t.listeners.delete(a)&&t.listeners.size===0&&(r.delete(e),h({kind:`unsubscribe`,threadId:e}))}}}}function b3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x3(e){return b3(e)&&typeof e.id==`string`&&[`idle`,`running`,`failed`].includes(String(e.status))}function S3(e){return b3(e)&&x3(e.metadata)&&Array.isArray(e.messages)}function C3(e){if(!b3(e))throw Error(`Invalid frame`);if(e.kind===`event`){let t=e.event;if(b3(t)&&typeof t.type==`string`&&typeof t.threadId==`string`&&Number.isSafeInteger(t.seq)&&Number(t.seq)>=0&&(t.type!==`snapshot`||S3(t.snapshot)))return e}else if(typeof e.id==`string`&&(e.kind===`rpc_ok`&&`result`in e||e.kind===`rpc_error`&&typeof e.message==`string`&&typeof e.code==`string`))return e;throw Error(`Invalid frame`)}function w3(e,t){switch(e){case`listThreads`:return Array.isArray(t)&&t.every(x3);case`getThread`:case`createThread`:return S3(t);case`getAvailableModels`:return Array.isArray(t)&&t.every(e=>b3(e)&&typeof e.provider==`string`&&typeof e.modelId==`string`);case`clearQueue`:return b3(t)&&Array.isArray(t.steering)&&t.steering.every(e=>typeof e==`string`)&&Array.isArray(t.followUp)&&t.followUp.every(e=>typeof e==`string`);default:return t===null}}async function T3(){try{let e=await fetch(`/api/v1/workbench/status`,{credentials:`same-origin`});return e.status===401||e.status===403?`unauthenticated`:e.ok?(await e.json()).enabled?`up`:`unconfigured`:`down`}catch{return`down`}}var E3={connecting:`reconnecting`,open:`online`,closed:`dropped`};function D3(){let{compaction:e,retry:t,contextUsage:n,readiness:r}=q$(),i=r&&r.state!==`ready`?r:null;return(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i?(0,b.jsx)(Kx,{variant:`high`,children:i.message}):null,e.active?(0,b.jsx)(Kx,{variant:`secondary`,children:`Compacting context…`}):null,t.active?(0,b.jsxs)(Kx,{variant:`high`,children:[`Retrying (attempt `,t.attempt,`)`]}):null,n?.percent==null?null:(0,b.jsxs)(`span`,{className:`text-muted-foreground text-xs tabular-nums`,title:`${n.tokens??`?`} / ${n.contextWindow} tokens`,children:[Math.round(n.percent),`% context`]})]})}var O3=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function k3({client:e}){let t=J$(),n=$(e=>e.threadListItem),r=n?n.externalId??n.remoteId??n.id:null,[i,a]=(0,y.useState)([]),[o,s]=(0,y.useState)(null);(0,y.useEffect)(()=>{let t=!1;return e.getAvailableModels().then(e=>{t||a(e)},()=>{}),()=>{t=!0}},[e]);let c=t?.status===`running`,l=t?.config,u=l?.provider&&l.modelId?`${l.provider}/${l.modelId}`:``,d=l?.thinkingLevel??``,f=async e=>{s(null);try{await e()}catch(e){s(e instanceof Error?e.message:String(e))}};return r?(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>0?(0,b.jsxs)(J4,{"aria-label":`Model`,title:`Model for this conversation`,value:u,disabled:c,onChange:t=>{let[n,...i]=t.target.value.split(`/`),a=i.join(`/`);n&&a&&f(()=>e.setModel(r,{provider:n,modelId:a}))},className:`h-7 w-auto max-w-44 text-xs`,children:[!u||i.every(e=>`${e.provider}/${e.modelId}`!==u)?(0,b.jsx)(`option`,{value:u,children:u||`Select a model`}):null,i.map(e=>(0,b.jsx)(`option`,{value:`${e.provider}/${e.modelId}`,children:e.name},`${e.provider}/${e.modelId}`))]}):null,(0,b.jsxs)(J4,{"aria-label":`Thinking level`,title:`Thinking level for this conversation`,value:d,disabled:c,onChange:t=>{let n=t.target.value;f(()=>e.setThinkingLevel(r,n))},className:`h-7 w-auto text-xs`,children:[(0,b.jsx)(`option`,{value:``,children:`Thinking…`}),O3.map(e=>(0,b.jsx)(`option`,{value:e,children:e},e))]}),o?(0,b.jsx)(`span`,{className:`text-destructive max-w-64 truncate text-xs`,title:o,children:o}):null]}):null}function A3({status:e,client:t,showTaskBoard:n,onToggleTaskBoard:r}){let i=J$();return(0,b.jsxs)(`header`,{className:`flex flex-wrap items-center justify-between gap-2 border-b px-3 py-2`,children:[(0,b.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,b.jsx)(`strong`,{className:`truncate text-sm font-semibold`,children:i?.title??`Live Workspace`}),i?.status===`running`?(0,b.jsx)(Kx,{variant:`low`,children:`streaming`}):null]}),(0,b.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,b.jsx)(D3,{}),(0,b.jsx)(k3,{client:t}),e===`open`?null:(0,b.jsx)(w4,{phase:E3[e]}),(0,b.jsxs)(o,{variant:n?`secondary`:`ghost`,size:`sm`,className:`h-7 gap-1.5 px-2 text-xs`,onClick:r,title:`Toggle Dossier Task Board`,"aria-label":`Toggle Dossier Task Board`,children:[(0,b.jsx)(Hf,{className:`size-3.5`}),(0,b.jsx)(`span`,{className:`hidden sm:inline`,children:`Tasks`})]})]})]})}function j3({initialThreadId:e}){let[t,n]=(0,y.useState)(`connecting`),[r,i]=(0,y.useState)(!0),o=(0,y.useMemo)(()=>y3({onStatusChange:n}),[]);(0,y.useEffect)(()=>()=>o.dispose(),[o]);let s=K$({client:o,includeArchived:!0,...e===void 0?{}:{initialThreadId:e},onThreadIdChange:e=>{let{selection:t,select:n}=u3.getState();e&&s3(t,e)&&n({kind:`pinned`,id:e})}}),c=(0,y.useMemo)(()=>jP({unstable_interactables:KB()}),[]);return(0,b.jsx)(EK,{runtime:s,config:c,children:(0,b.jsxs)(`div`,{className:a(`grid h-[var(--workspace-height)] min-h-120 grid-cols-1 gap-4`,r?`xl:grid-cols-[minmax(0,16rem)_minmax(0,1fr)_minmax(0,21rem)] md:grid-cols-[minmax(0,1fr)_minmax(0,20rem)]`:`md:grid-cols-[minmax(0,17rem)_minmax(0,1fr)]`),children:[(0,b.jsx)(h,{className:a(`min-h-0 overflow-hidden p-0`,r?`hidden xl:flex`:`hidden md:flex`),children:(0,b.jsx)(l4,{})}),(0,b.jsxs)(h,{className:`flex min-h-0 flex-col overflow-hidden p-0`,children:[(0,b.jsx)(A3,{status:t,client:o,showTaskBoard:r,onToggleTaskBoard:()=>i(e=>!e)}),(0,b.jsx)(q4,{}),(0,b.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,b.jsx)(V2,{})})]}),r?(0,b.jsx)(h,{className:`flex min-h-0 flex-col overflow-hidden p-0`,children:(0,b.jsx)(G4,{onClose:()=>i(!1)})}):null]})})}function M3({session:e,onStartChat:t}){return(0,b.jsxs)(h,{className:`mx-auto max-w-lg items-start gap-3 p-6`,children:[(0,b.jsx)(`h2`,{className:`text-base font-semibold`,children:`This session ran outside the live workspace`}),(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[`Session `,(0,b.jsx)(`span`,{className:`font-mono text-xs`,children:e.id}),` came from`,` `,(0,b.jsx)(`span`,{className:`font-mono text-xs`,children:e.source}),`. Its findings, runs and evidence are all here — the transcript is not, because the conversation happened in the TUI rather than over the workbench socket.`]}),(0,b.jsx)(o,{onClick:t,children:`Start a chat for this session`})]})}function N3(){let e=u3(e=>e.selection),t=tf({queryKey:[`agent-sessions`],queryFn:mx.agentSessions}),[n,r]=(0,y.useState)(null),i=o3(e,t.data?.items),a=i.kind===`external`&&n===i.session.id;if(i.kind===`loading`)return(0,b.jsx)(Y4,{compact:!0,title:`Opening the live workspace…`,detail:`Resolving the current session.`});if(i.kind===`external`&&!a)return(0,b.jsx)(M3,{session:i.session,onStartChat:()=>r(i.session.id)});let o=i.kind===`thread`?i.threadId:void 0;return(0,b.jsx)(j3,{initialThreadId:o},o??`new`)}function P3({state:e}){return(0,b.jsxs)(h,{className:`mx-auto max-w-lg items-start gap-3 p-6`,children:[(0,b.jsx)(`h2`,{className:`text-base font-semibold`,children:e===`unauthenticated`?`Sign in required`:e===`unconfigured`?`Live workspace not configured`:`Live workspace unreachable`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:e===`unauthenticated`?`The live workspace is available to authenticated platform users.`:e===`unconfigured`?`Set WORKBENCH_CWD on the platform server to enable the hosted agent runtime (see docs/infra/workbench-integration.md).`:`The platform server did not answer. Check that it is running.`}),e===`unauthenticated`?(0,b.jsx)(o,{variant:`outline`,asChild:!0,children:(0,b.jsx)(`a`,{href:`/login`,children:`Sign in`})}):null]})}function F3({workflow:e}){let t=Bd(),[n,r]=(0,y.useState)(!1),[i,a]=(0,y.useState)(``),[s,c]=(0,y.useState)(!1),[l,u]=(0,y.useState)(!1),[d,f]=(0,y.useState)([]),m=[...new Set(e.stages.flatMap(e=>e.skillRefs))],_=e.stages.filter(e=>e.optional),v=nf({mutationFn:()=>mx.startLocalRun({workflowKey:e.key,target:i.trim(),permissionMode:l?`yolo`:`scoped`,selectedStageKeys:d,allowedActions:[`read_files`,`command_execution`]}),onSuccess:()=>void t.invalidateQueries({queryKey:[`local-runs`]})});return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(h,{className:`cursor-pointer transition-colors hover:border-primary focus-visible:outline-2 focus-visible:outline-primary`,role:`button`,tabIndex:0,onClick:()=>r(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r(!0))},"aria-label":`Run ${e.name} headlessly`,children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsxs)(Kx,{variant:Gx(B3(e)),children:[`Highest risk `,B3(e)]}),(0,b.jsxs)(`span`,{className:`font-mono`,children:[`v`,e.version]})]}),(0,b.jsx)(`h2`,{children:e.name}),(0,b.jsx)(`p`,{children:e.description}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.requiredCapabilities.map(e=>(0,b.jsx)(`span`,{children:e},e))}),(0,b.jsxs)(`span`,{className:`mt-4 inline-flex items-center gap-2 text-sm font-medium text-primary`,children:[`Run headless `,(0,b.jsx)(_f,{size:16})]})]}),(0,b.jsx)(t1,{open:n,onOpenChange:e=>{r(e),e||(a(``),c(!1),u(!1),f([]),v.reset())},children:(0,b.jsxs)(a1,{className:`max-h-[90vh] overflow-y-auto`,children:[(0,b.jsxs)(o1,{children:[(0,b.jsxs)(c1,{children:[`Run `,e.name]}),(0,b.jsx)(l1,{children:`Start a local headless run. Each stage loads its workflow skill pack and the report appears under Audits and Reports when the run completes.`})]}),v.data?(0,b.jsx)(`div`,{className:`grid gap-3 text-sm`,children:(0,b.jsx)(L3,{runId:v.data.runId})}):(0,b.jsxs)(`form`,{className:`grid gap-4`,onSubmit:e=>{e.preventDefault(),i.trim()&&s&&!v.isPending&&v.mutate()},children:[(0,b.jsxs)(`div`,{className:`grid gap-2`,children:[(0,b.jsx)(g,{htmlFor:`workflow-target-${e.key}`,children:`Target or scope`}),(0,b.jsx)(p,{id:`workflow-target-${e.key}`,value:i,onChange:e=>a(e.target.value),placeholder:`https://example.com or an authorized asset`,required:!0})]}),(0,b.jsxs)(`div`,{className:`grid gap-1 text-sm`,children:[(0,b.jsx)(`span`,{className:`font-medium`,children:`Skill pack`}),(0,b.jsx)(`span`,{className:`text-muted-foreground`,children:m.length?m.join(`, `):`No skill refs configured`})]}),_.length>0?(0,b.jsxs)(`fieldset`,{className:`grid gap-2 text-sm`,children:[(0,b.jsx)(`legend`,{className:`font-medium`,children:`Optional stages`}),_.map(e=>(0,b.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,b.jsx)(`input`,{type:`checkbox`,checked:d.includes(e.key),onChange:t=>f(n=>t.target.checked?[...n,e.key]:n.filter(t=>t!==e.key))}),(0,b.jsxs)(`span`,{children:[e.name,` `,(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[`(`,e.risk,` risk)`]})]})]},e.key))]}):null,(0,b.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,b.jsx)(`input`,{type:`checkbox`,checked:s,onChange:e=>c(e.target.checked),required:!0}),(0,b.jsx)(`span`,{children:`I am authorized to assess this target. The local agent may execute commands on the gateway host.`})]}),(0,b.jsxs)(`label`,{className:`flex items-start gap-3 rounded-lg border border-destructive/50 bg-destructive/5 p-3 text-sm`,children:[(0,b.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked)}),(0,b.jsxs)(`span`,{children:[(0,b.jsx)(`strong`,{children:`YOLO mode — no per-command approval.`}),` The agent can run arbitrary shell commands and read or change local files on the gateway host until the run ends. Commands are not sandboxed; only use this on a trusted local machine and an authorized target. Explicit prohibitions and run time/cost limits still apply.`]})]}),v.isError?(0,b.jsx)(`p`,{role:`alert`,className:`text-destructive text-sm`,children:v.error.message}):null,(0,b.jsx)(s1,{children:(0,b.jsxs)(o,{type:`submit`,disabled:!i.trim()||!s||v.isPending,children:[(0,b.jsx)(Xf,{size:16}),` `,v.isPending?`Starting…`:`Start headless run`]})})]})]})})]})}function I3(){let e=tf({queryKey:[`local-runs`],queryFn:mx.localRuns,refetchInterval:2e3,retry:!1}),[t,n]=(0,y.useState)(null);if(e.isLoading)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Headless run activity`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Loading run history…`})]});if(e.isError)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Headless run activity`}),(0,b.jsx)(`p`,{className:`text-destructive text-sm`,children:`Could not load local run status. Local runs require an admin session on this gateway.`})]});let r=e.data?.items??[];if(!r.length)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Headless run activity`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`No headless runs yet. Select a workflow above to start one.`})]});let i=r.find(e=>e.runId===t)??r[0];return(0,b.jsxs)(h,{className:`grid gap-4`,children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{children:`Headless run activity`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Live stage progress, retained after you close the launch dialog.`})]}),(0,b.jsx)(`select`,{className:`max-w-full rounded-md border bg-transparent px-2 py-1 text-sm`,value:i.runId,onChange:e=>n(e.target.value),children:r.map(e=>(0,b.jsxs)(`option`,{value:e.runId,children:[e.workflowKey,` · `,e.target,` · `,e.status]},e.runId))})]}),(0,b.jsx)(R3,{run:i})]})}function L3({runId:e}){let t=tf({queryKey:[`local-run`,e],queryFn:()=>mx.localRun(e),refetchInterval:e=>![`completed`,`partial`,`failed`,`cancelled`].includes(e.state.data?.item.status??``)&&2e3,retry:2});return t.isError?(0,b.jsx)(`p`,{role:`alert`,className:`text-destructive`,children:`Could not load run progress.`}):t.data?(0,b.jsx)(R3,{run:t.data.item}):(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`Starting run and loading its stages…`})}function R3({run:e}){let t=e.stages.filter(e=>![`pending`,`running`].includes(e.status)).length;return(0,b.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,b.jsx)(z3,{status:e.status}),(0,b.jsx)(`strong`,{children:e.workflowKey}),e.permissionMode===`yolo`?(0,b.jsx)(Kx,{variant:`high`,children:`YOLO mode`}):null,(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[e.status,` · `,t,`/`,e.stages.length,` stages · `,e.runId.slice(0,8)]})]}),(0,b.jsxs)(`p`,{className:`break-all text-muted-foreground`,children:[`Target: `,e.target]}),(0,b.jsx)(`div`,{className:`h-2 overflow-hidden rounded-full bg-muted`,role:`progressbar`,"aria-valuenow":t,"aria-valuemin":0,"aria-valuemax":e.stages.length,children:(0,b.jsx)(`div`,{className:`h-full bg-primary transition-all`,style:{width:`${e.stages.length?t/e.stages.length*100:0}%`}})}),(0,b.jsx)(`ol`,{className:`grid gap-0 border-l pl-4`,children:e.stages.map(e=>(0,b.jsxs)(`li`,{className:`relative flex items-start gap-3 border-b py-2 last:border-b-0`,children:[(0,b.jsx)(`span`,{className:`absolute -left-[1.43rem] bg-card`,children:(0,b.jsx)(z3,{status:e.status})}),(0,b.jsxs)(`span`,{className:`min-w-0`,children:[(0,b.jsx)(`strong`,{children:e.name}),(0,b.jsx)(`span`,{className:`ml-2 text-muted-foreground`,children:e.status}),e.summary?(0,b.jsx)(`span`,{className:`mt-1 block text-muted-foreground`,children:e.summary}):null]})]},e.key))}),e.error?(0,b.jsx)(`p`,{role:`alert`,className:`text-destructive`,children:e.error}):null,e.reportAvailable?(0,b.jsx)(o,{asChild:!0,size:`sm`,variant:`outline`,children:(0,b.jsxs)(`a`,{href:`/reports`,children:[`View report `,(0,b.jsx)(_f,{size:16})]})}):e.status===`running`?(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`This view updates every two seconds. The report appears after completion.`}):null]})}function z3({status:e}){return e===`running`?(0,b.jsx)(Uf,{size:17,className:`animate-spin text-primary`,"aria-label":`Running`}):e===`completed`||e===`succeeded`?(0,b.jsx)(Df,{size:17,className:`text-green-600`,"aria-label":`Succeeded`}):[`failed`,`blocked`,`interrupted`,`partial`,`cancelled`].includes(e)?(0,b.jsx)(Of,{size:17,className:`text-destructive`,"aria-label":e}):(0,b.jsx)(kf,{size:17,className:`text-muted-foreground`,"aria-label":e})}function B3(e){return e.stages.some(e=>e.risk===`R2`)?`R2`:e.stages.some(e=>e.risk===`R1`)?`R1`:`R0`}function V3({eyebrow:e,title:t,description:n,actions:r,className:i}){return(0,b.jsxs)(`header`,{className:a(`flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between`,i),children:[(0,b.jsxs)(`div`,{className:`min-w-0`,children:[e?(0,b.jsx)(`p`,{className:`text-muted-foreground mt-0 mb-2 text-2xs font-semibold tracking-[0.12em] uppercase`,children:e}):null,t?(0,b.jsx)(`h1`,{children:t}):null,n?(0,b.jsx)(`p`,{className:`mt-2 mb-0 max-w-[72ch]`,children:n}):null]}),r?(0,b.jsx)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:r}):null]})}function H3({sessions:e,value:t,onChange:n,className:r,id:i=`agent-session`}){let o=e[0];return(0,b.jsxs)(`div`,{className:a(`flex min-w-0 items-center gap-2`,r),children:[(0,b.jsx)(`label`,{className:`text-muted-foreground shrink-0 text-[13px]`,htmlFor:i,children:`Session`}),(0,b.jsxs)(J4,{"aria-label":`Agent session`,className:`w-auto min-w-0 max-w-[22rem] text-[13px]`,id:i,onChange:e=>n(e.target.value),value:t??`latest`,children:[(0,b.jsx)(`option`,{value:`latest`,children:o?`Latest — ${o.title||`Session`}`:`Latest session`}),(0,b.jsx)(`option`,{value:`all`,children:`All workspace sessions`}),e.map(e=>(0,b.jsxs)(`option`,{value:e.id,children:[e.title||`Session`,` · `,e.findingCount??0,` findings · `,e.runCount??0,` runs`]},e.id))]})]})}function U3({section:e}){return(0,b.jsx)(Vd,{client:hx,children:(0,b.jsx)(K3,{section:e})})}function W3(){let e=tf({queryKey:[`workbench-status`],queryFn:T3,retry:1,staleTime:15e3});return e.isLoading?(0,b.jsx)(Y4,{compact:!0,title:`Connecting to the live workspace…`,detail:`Checking the platform agent runtime.`}):e.data&&e.data!==`up`?(0,b.jsx)(P3,{state:e.data}):(0,b.jsx)(N3,{})}function G3(){return(0,b.jsx)(Vd,{client:hx,children:(0,b.jsx)(W3,{})})}function K3({section:e}){let t=u3(e=>e.selection),n=u3(e=>e.select),r=u3(e=>e.resolveLatest),i=e3(t),a=e=>n(t3(e)),[s,c]=(0,y.useState)(()=>typeof window<`u`?new URLSearchParams(window.location.search).get(`finding`):null),l=e=>{if(c(e),typeof window<`u`){let t=new URL(window.location.href);e?t.searchParams.set(`finding`,e):t.searchParams.delete(`finding`),window.history.replaceState({},``,t.toString())}},u=tf({queryKey:[`agent-sessions`],queryFn:mx.agentSessions,enabled:e===`runs`||e===`agent`||e===`findings`||e===`dashboard`||e===`lifecycle`,refetchInterval:2e3});(0,y.useEffect)(()=>{u.data?.items&&r(u.data.items)},[u.data?.items,r]);let d=r3(t,u.data?.items),f=tf({queryKey:[`workflows`],queryFn:mx.workflows,enabled:e===`workflows`||e===`assessments`}),m=tf({queryKey:[`overview`,d],queryFn:()=>mx.overview(d),enabled:e===`dashboard`||e===`assessments`||e===`lifecycle`,refetchInterval:2e3}),_=tf({queryKey:[`runs`,d],queryFn:()=>mx.runs({sessionId:d}),enabled:e===`runs`,refetchInterval:2e3}),v=tf({queryKey:[`projects`],queryFn:mx.projects,enabled:e===`assessments`}),x=tf({queryKey:[`assessment-profiles`],queryFn:mx.assessmentProfiles,enabled:e===`assessments`}),S=tf({queryKey:[`findings`,d],queryFn:()=>mx.findings({sessionId:d}),enabled:e===`findings`||e===`dashboard`||e===`lifecycle`||e===`reports`,refetchInterval:6e3}),C=tf({queryKey:[`agent-session`,d],queryFn:()=>mx.agentSession(d),enabled:e===`runs`&&!!d,refetchInterval:2e3}),w=tf({queryKey:[`governance-events`],queryFn:mx.governanceEvents,enabled:e===`reports`}),T=tf({queryKey:[`workers`],queryFn:mx.workers,enabled:e===`administration`}),E=tf({queryKey:[`tokens`],queryFn:mx.tokens,enabled:e===`administration`}),[D,O]=(0,y.useState)(``),[k,A]=(0,y.useState)(30),[j,M]=(0,y.useState)(!1),[N,ee]=(0,y.useState)(null),[te,ne]=(0,y.useState)(!1),[re,ie]=(0,y.useState)(!1),[ae,oe]=(0,y.useState)(null),[se,ce]=(0,y.useState)(null);async function le(e){e.preventDefault(),M(!0),oe(null);try{let e=await mx.mintToken({label:D.trim()||`CLI Token`,expiresInDays:k});ee(e),O(``),hx.invalidateQueries({queryKey:[`tokens`]})}catch(e){oe(e instanceof Error?e.message:`Failed to mint token`)}finally{M(!1)}}async function ue(e){if(confirm(`Are you sure you want to revoke this token? Any CLI session or automation using it will immediately lose access.`)){ce(e);try{await mx.revokeToken(e),hx.invalidateQueries({queryKey:[`tokens`]})}catch(e){alert(e instanceof Error?e.message:`Failed to revoke token`)}finally{ce(null)}}}let de=[...e===`workflows`||e===`assessments`?[f]:[],...e===`dashboard`?[m,S]:[],...e===`lifecycle`?[m,S]:[],...e===`runs`?[_,u]:[],...e===`runs`&&d?[C]:[],...e===`assessments`?[m,v,x]:[],...e===`findings`?[S]:[],...e===`reports`?[w,S]:[],...e===`administration`?[T,E]:[]];if(de.some(e=>e.isLoading))return(0,b.jsx)(Y4,{title:`Loading workspace`,detail:`Reading durable platform state…`});let P=de.find(e=>e.isError);if(P){let e=P.error,t=e&&typeof e==`object`&&`status`in e&&e.status===401;return(0,b.jsx)(Y4,{title:`Platform unavailable`,detail:e instanceof Error?e.message:`The platform could not be reached.`,action:t?(0,b.jsx)(o,{asChild:!0,children:(0,b.jsx)(`a`,{href:`/login`,children:`Sign in`})}):(0,b.jsxs)(o,{onClick:()=>void P.refetch(),children:[(0,b.jsx)(Qf,{}),` Retry`]})})}let fe=Ax(S.data?.findings??[]),pe=fe.filter(Dx);if(e===`dashboard`){let e=Object.fromEntries(bx.map(e=>[e,pe.filter(t=>t.severity===e).length])),t=m.data?.runs??{},n=Object.values(t).reduce((e,t)=>e+t,0),r=(t.queued??0)+(t.running??0),s=jx(fe),c=fe.filter(e=>e.status===`confirmed`||e.status===`verified`);return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(V3,{actions:(0,b.jsx)(H3,{onChange:a,sessions:u.data?.items??[],value:i})}),(0,b.jsxs)(Nx,{children:[(0,b.jsx)(Px,{hero:!0,tone:s??void 0,label:`Client posture`,value:s?Cx[s].toUpperCase():`NO CONFIRMED RISK`,meta:s?`Worst confirmed finding across ${c.length} confirmed finding${c.length===1?``:`s`}.`:`No finding has been confirmed yet.`}),(0,b.jsx)(Px,{label:`Open findings`,value:pe.length,meta:`${fe.length-pe.length} resolved`}),(0,b.jsx)(Px,{label:`Critical / High`,value:`${e.critical} / ${e.high}`,meta:`${c.length} confirmed overall`}),(0,b.jsx)(Px,{label:`Assessments`,value:n,meta:`${r} in flight`})]}),(0,b.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[1.35fr_1fr]`,children:[(0,b.jsx)(Mx,{title:`Open findings by severity`,sub:`${pe.length} active`,children:(0,b.jsx)(Fx,{counts:e})}),(0,b.jsx)(Mx,{title:`Findings by data-lifecycle stage`,sub:`where the risk lives`,children:(0,b.jsx)(Ix,{findings:pe})})]}),(0,b.jsx)(Mx,{title:`Highest-priority open findings`,sub:(0,b.jsx)(`a`,{className:`link-more`,href:`/findings`,children:`View all`}),children:(0,b.jsx)(Lx,{findings:Ex(pe).slice(0,5),onSelect:e=>{window.location.href=`/findings?finding=${encodeURIComponent(e.id)}`},emptyLabel:`No open findings. Agent runs report findings through the report_finding tool; none have been ingested yet.`})}),(0,b.jsxs)(`section`,{"aria-labelledby":`active-runs`,children:[(0,b.jsxs)(`div`,{className:`mb-4 flex items-baseline justify-between gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`p`,{className:`text-muted-foreground mt-0 mb-1 text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Operations`}),(0,b.jsx)(`h2`,{id:`active-runs`,children:`Active runs`})]}),(0,b.jsxs)(`a`,{className:`link-more`,href:`/runs`,children:[`View all `,(0,b.jsx)(_f,{"aria-hidden":`true`})]})]}),m.data?.recentRuns.filter(e=>e.status===`queued`||e.status===`running`).length?(0,b.jsx)(Q3,{runs:m.data.recentRuns.filter(e=>e.status===`queued`||e.status===`running`)}):(0,b.jsx)(Y4,{compact:!0,title:`No active runs`,detail:`Select a target endpoint to initialize a governed assessment.`,action:(0,b.jsx)(o,{asChild:!0,children:(0,b.jsx)(`a`,{href:`/assessments`,children:`New assessment`})})})]})]})}if(e===`lifecycle`)return(0,b.jsx)(X3,{findings:pe});if(e===`workflows`)return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(V3,{title:`Workflows`}),(0,b.jsx)(I3,{}),(0,b.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:f.data?.items.map(e=>(0,b.jsx)(F3,{workflow:e},e.key))})]});if(e===`runs`){if(d&&C.data){let e=C.data,t=e.operations.filter(e=>e.status!==`completed`).length;return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsxs)(`header`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`p`,{className:`text-2xs font-semibold tracking-[0.12em] uppercase text-muted-foreground`,children:`Session`}),(0,b.jsx)(`h1`,{children:e.session.title}),(0,b.jsx)(`p`,{children:`Recorded tool calls and findings for this agent session, newest run last.`})]}),(0,b.jsx)(o,{variant:`outline`,onClick:()=>n($4),children:`All sessions`})]}),(0,b.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,b.jsx)(Y3,{label:`Status`,value:t6(e.session.status),detail:`${e.session.runCount} run${e.session.runCount===1?``:`s`} in this session`}),(0,b.jsx)(Y3,{label:`Tool calls`,value:String(e.session.operationCount),detail:t?`${t} did not complete`:`All completed`}),(0,b.jsx)(Y3,{label:`Findings`,value:String(e.session.findingCount),detail:e.session.findingCount?`Ingested through report_finding`:`None reported in this session`})]}),(0,b.jsxs)(`div`,{className:`grid items-start gap-5 lg:grid-cols-[minmax(0,1.35fr)_minmax(280px,0.65fr)]`,"aria-live":`polite`,children:[(0,b.jsxs)(`section`,{"aria-labelledby":`agent-transcript`,children:[(0,b.jsx)(`h2`,{id:`agent-transcript`,children:`Transcript`}),e.operations.length?(0,b.jsx)(`div`,{className:`grid gap-2.5`,children:e.operations.map(e=>(0,b.jsxs)(`article`,{className:`bg-card rounded-lg border p-4 [&_p]:mt-2 [&_p]:mb-0 [&_p]:text-[13px] [&_p]:leading-relaxed [&_p]:break-words [&_p]:text-muted-foreground [&_p.font-mono]:max-h-28 [&_p.font-mono]:overflow-auto [&_p.font-mono]:rounded-sm [&_p.font-mono]:bg-[var(--plane)] [&_p.font-mono]:px-2.5 [&_p.font-mono]:py-2 [&_p.font-mono]:text-xs [&_p.font-mono]:whitespace-pre-wrap`,children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(`strong`,{children:e.tool}),(0,b.jsx)(Kx,{variant:Gx(e.status),children:t6(e.outcome)})]}),(0,b.jsxs)(`p`,{children:[e.runtime,` · `,new Date(e.startedAt).toLocaleTimeString(),e.completedAt?` · ${e.completedAt-e.startedAt}ms`:``]}),e.outputPreview?(0,b.jsx)(`p`,{className:`font-mono`,children:e.outputPreview.slice(0,400)}):null]},e.id))}):(0,b.jsx)(Y4,{compact:!0,title:`Waiting for agent output`,detail:`Tool calls appear here as the runtime records them.`})]}),(0,b.jsxs)(`section`,{"aria-labelledby":`agent-runs`,children:[(0,b.jsx)(`h2`,{id:`agent-runs`,children:`Runs`}),(0,b.jsx)(`div`,{className:`grid gap-2.5`,children:e.runs.map(e=>(0,b.jsxs)(`article`,{className:`bg-card rounded-lg border p-4 [&_p]:mt-2 [&_p]:mb-0 [&_p]:text-[13px] [&_p]:leading-relaxed [&_p]:break-words [&_p]:text-muted-foreground`,children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(Kx,{variant:Gx(e.status),children:t6(e.status)}),(0,b.jsx)(`span`,{className:`font-mono`,children:e.id.slice(0,12)})]}),(0,b.jsxs)(`p`,{children:[e.kind,` · `,new Date(e.createdAt).toLocaleString()]})]},e.id))})]})]}),e.findings.length?(0,b.jsxs)(`section`,{"aria-labelledby":`agent-findings`,children:[(0,b.jsx)(`h2`,{id:`agent-findings`,children:`Findings from this session`}),(0,b.jsx)($3,{findings:e.findings})]}):null]})}return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(V3,{title:`Runs`}),(0,b.jsxs)(`section`,{"aria-labelledby":`all-runs`,children:[(0,b.jsx)(`h2`,{id:`all-runs`,className:`mb-3`,children:`Runs`}),_.data?.runs.length?(0,b.jsx)(Q3,{runs:_.data.runs}):(0,b.jsx)(Y4,{compact:!0,title:`No runs yet`,detail:`Initialize an assessment to start the first governed run.`})]}),(0,b.jsxs)(`section`,{"aria-labelledby":`all-sessions`,children:[(0,b.jsx)(`h2`,{id:`all-sessions`,className:`mb-3`,children:`Sessions`}),u.data?.items.length?(0,b.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:u.data.items.map(e=>(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(Kx,{variant:Gx(e.status),children:t6(e.status)}),(0,b.jsx)(`span`,{className:`font-mono`,children:e.source})]}),(0,b.jsx)(`h2`,{children:e.title}),(0,b.jsxs)(`p`,{children:[e.runCount,` run`,e.runCount===1?``:`s`,` · `,e.operationCount,` tool call`,e.operationCount===1?``:`s`,` · `,e.findingCount,` finding`,e.findingCount===1?``:`s`]}),(0,b.jsxs)(`p`,{children:[`Last active `,new Date(e.lastActivityAt).toLocaleString()]}),(0,b.jsx)(o,{variant:`outline`,onClick:()=>n({kind:`pinned`,id:e.id}),children:`Open session`})]},e.id))}):(0,b.jsx)(Y4,{compact:!0,title:`No agent sessions`,detail:`Sessions appear here once an agent run reaches the platform.`})]})]})}if(e===`assessments`)return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(V3,{title:`Assessments`}),(0,b.jsx)(Bj,{}),(0,b.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,b.jsx)(Y3,{label:`Projects`,value:String(v.data?.items.length??0),detail:`Active workspace project boundaries`}),(0,b.jsx)(Y3,{label:`Target bindings`,value:String(x.data?.items.length??0),detail:`Bound endpoints and infrastructure`}),(0,b.jsx)(Y3,{label:`Recent runs`,value:String(m.data?.recentRuns.length??0),detail:`Assessment runs recorded in this workspace`})]}),x.data?.items.length?(0,b.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:x.data.items.map(e=>(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(Kx,{variant:Gx(e.allowedRisk),children:e.allowedRisk}),(0,b.jsxs)(`span`,{className:`font-mono`,children:[`rev `,e.revision]})]}),(0,b.jsx)(`h2`,{children:e.targets[0]?.displayName??e.targets[0]?.locator??`Bound target`}),(0,b.jsxs)(`p`,{children:[e.requiredWorkerClass,` worker · immutable launch policy`]}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.requiredCapabilities.map(e=>(0,b.jsx)(`span`,{children:e},e))})]},e.id))}):(0,b.jsx)(Y4,{compact:!0,title:`No targets yet`,detail:`Configure a new target endpoint from the dashboard to initialize assessment tracking.`})]});if(e===`findings`){if(s)return(0,b.jsx)(`div`,{className:`grid gap-6`,children:(0,b.jsx)(qj,{findingId:s,onBack:()=>l(null)})});let e=Object.fromEntries(bx.map(e=>[e,pe.filter(t=>t.severity===e).length])),t=e6(fe);return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(V3,{actions:(0,b.jsx)(H3,{id:`findings-session`,onChange:a,sessions:u.data?.items??[],value:i}),title:`Findings & assets`}),(0,b.jsx)(Vj,{}),fe.length?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[1.35fr_1fr]`,children:[(0,b.jsx)(Mx,{title:`Open findings by severity`,sub:`${pe.length} active`,children:(0,b.jsx)(Fx,{counts:e})}),(0,b.jsx)(Mx,{title:`Findings by data-lifecycle stage`,sub:`where the risk lives`,children:(0,b.jsx)(Ix,{findings:pe})})]}),(0,b.jsx)(Mx,{title:`Control coverage`,sub:`pillar × lifecycle stage — worst open severity per cell`,children:(0,b.jsx)(zx,{findings:pe,onSelectStage:()=>{}})}),t.map(({asset:e,items:t})=>(0,b.jsx)(Mx,{title:e,sub:`${t.length} finding${t.length===1?``:`s`}`,children:(0,b.jsx)(Lx,{findings:Ex(t),onSelect:e=>l(e.id)})},e))]}):(0,b.jsx)(Y4,{compact:!0,title:`No findings`,detail:`Discovered findings will appear here as agent runs report them. Source findings stay unverified until operation-level evidence confirms them.`})]})}return e===`agent`?(0,b.jsx)(V3,{actions:(0,b.jsx)(H3,{id:`console-session`,onChange:a,sessions:u.data?.items??[],value:i}),title:`Console`}):e===`reports`?(0,b.jsxs)(`div`,{className:`grid gap-8`,children:[(0,b.jsx)(V3,{title:`Reports`}),(0,b.jsx)(zj,{}),(0,b.jsx)(Z3,{events:w.data?.items??[],findings:fe})]}):e===`administration`?(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(V3,{title:`Administration & Access`}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`div`,{className:`flex items-start justify-between gap-4`,children:(0,b.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`0.5rem`},children:[(0,b.jsx)(Vf,{size:18}),(0,b.jsx)(`h2`,{children:`Personal Access Tokens & CLI Sign-In`})]})}),(0,b.jsx)(`p`,{style:{marginTop:`0.25rem`,marginBottom:`1rem`},children:`Mint tokens to authenticate the Kifaru CLI or automated CI/CD pipelines without passwords.`}),N&&(0,b.jsxs)(`div`,{style:{background:`rgba(16, 185, 129, 0.12)`,border:`1px solid rgba(16, 185, 129, 0.4)`,borderRadius:`var(--radius-xl)`,padding:`1rem`,marginBottom:`1.25rem`},children:[(0,b.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,marginBottom:`0.5rem`},children:[(0,b.jsxs)(`strong`,{style:{color:`var(--good)`,display:`flex`,alignItems:`center`,gap:`0.4rem`},children:[(0,b.jsx)(Sf,{size:16}),` Token Minted: `,N.label]}),(0,b.jsx)(o,{variant:`ghost`,size:`sm`,onClick:()=>ee(null),children:`Dismiss`})]}),(0,b.jsx)(`p`,{style:{fontSize:`0.85rem`,color:`var(--ink-2)`,marginBottom:`0.75rem`},children:`Make sure to copy your Personal Access Token now. You will not be able to see it again!`}),(0,b.jsxs)(`div`,{style:{display:`grid`,gap:`0.75rem`},children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(g,{className:`text-muted-foreground mb-1 block text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Token Value`}),(0,b.jsxs)(`div`,{style:{display:`flex`,gap:`0.5rem`,alignItems:`center`},children:[(0,b.jsx)(p,{type:`text`,readOnly:!0,value:N.token,className:`flex-1 font-mono`}),(0,b.jsxs)(o,{variant:`outline`,size:`sm`,onClick:()=>{navigator.clipboard.writeText(N.token),ne(!0),setTimeout(()=>ne(!1),2e3)},children:[te?(0,b.jsx)(Sf,{size:14}):(0,b.jsx)(Mf,{size:14}),te?`Copied`:`Copy Token`]})]})]}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`label`,{className:`text-2xs font-semibold tracking-[0.12em] uppercase text-muted-foreground`,style:{display:`block`,marginBottom:`0.25rem`},children:`CLI Sign-In Command`}),(0,b.jsxs)(`div`,{style:{display:`flex`,gap:`0.5rem`,alignItems:`center`},children:[(0,b.jsxs)(`code`,{className:`font-mono`,style:{flex:1,borderRadius:`var(--radius-lg)`,padding:`0.45rem 0.65rem`,fontSize:`0.82rem`,color:`var(--primary)`},children:[`kifaru session login --token `,N.token]}),(0,b.jsxs)(o,{variant:`outline`,size:`sm`,onClick:()=>{navigator.clipboard.writeText(`kifaru session login --token `+N.token),ie(!0),setTimeout(()=>ie(!1),2e3)},children:[re?(0,b.jsx)(Sf,{size:14}):(0,b.jsx)(Mf,{size:14}),re?`Copied`:`Copy Command`]})]})]})]})]}),(0,b.jsxs)(`form`,{onSubmit:le,style:{display:`flex`,flexWrap:`wrap`,alignItems:`flex-end`,gap:`0.75rem`,background:`var(--surface-2)`,border:`1px solid var(--border)`,borderRadius:`var(--radius-xl)`,padding:`0.85rem`,marginBottom:`1.25rem`},children:[(0,b.jsxs)(`div`,{style:{flex:`1 1 220px`},children:[(0,b.jsx)(g,{htmlFor:`mint-label`,className:`mb-1.5 block text-sm`,children:`Token Label`}),(0,b.jsx)(p,{id:`mint-label`,type:`text`,placeholder:`e.g. Workstation CLI, CI Runner`,value:D,onChange:e=>O(e.target.value)})]}),(0,b.jsxs)(`div`,{style:{width:`160px`},children:[(0,b.jsx)(g,{htmlFor:`mint-expiry`,className:`mb-1.5 block text-sm`,children:`Expiration`}),(0,b.jsxs)(J4,{id:`mint-expiry`,value:k,onChange:e=>A(Number(e.target.value)),children:[(0,b.jsx)(`option`,{value:30,children:`30 days`}),(0,b.jsx)(`option`,{value:60,children:`60 days`}),(0,b.jsx)(`option`,{value:90,children:`90 days`}),(0,b.jsx)(`option`,{value:365,children:`1 year`}),(0,b.jsx)(`option`,{value:0,children:`Never expires`})]})]}),(0,b.jsxs)(o,{type:`submit`,disabled:j,size:`sm`,children:[(0,b.jsx)(Zf,{size:15}),j?`Minting…`:`Mint Token`]})]}),ae&&(0,b.jsx)(`p`,{className:`text-destructive text-sm`,style:{marginBottom:`1rem`},children:ae}),(0,b.jsxs)(`div`,{style:{marginTop:`0.5rem`},children:[(0,b.jsx)(`h3`,{style:{fontSize:`0.95rem`,fontWeight:600,marginBottom:`0.5rem`},children:`Active Tokens`}),E.data?.items.length?(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Label`}),(0,b.jsx)(`th`,{children:`Token Prefix`}),(0,b.jsx)(`th`,{children:`Role`}),(0,b.jsx)(`th`,{children:`Created`}),(0,b.jsx)(`th`,{children:`Expires`}),(0,b.jsx)(`th`,{children:`Action`})]})}),(0,b.jsx)(`tbody`,{children:E.data.items.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{style:{fontWeight:600,color:`var(--ink)`},children:e.label}),(0,b.jsxs)(`td`,{className:`font-mono`,children:[e.prefix,`…`]}),(0,b.jsx)(`td`,{children:(0,b.jsx)(Kx,{variant:Gx(`confirmed`),children:e.role})}),(0,b.jsx)(`td`,{children:new Date(e.createdAt).toLocaleDateString()}),(0,b.jsx)(`td`,{children:e.expiresAt?new Date(e.expiresAt).toLocaleDateString():`Never`}),(0,b.jsx)(`td`,{children:(0,b.jsxs)(o,{variant:`destructive`,size:`sm`,disabled:se===e.id,onClick:()=>ue(e.id),children:[(0,b.jsx)(up,{size:13}),se===e.id?`Revoking…`:`Revoke`]})})]},e.id))})]})}):(0,b.jsx)(`p`,{style:{color:`var(--ink-3)`,fontSize:`0.85rem`,fontStyle:`italic`},children:`No personal access tokens minted yet. Use the form above to create one.`})]}),(0,b.jsxs)(`div`,{style:{marginTop:`1.25rem`,background:`var(--surface-2)`,border:`1px dashed var(--border)`,borderRadius:`var(--radius-xl)`,padding:`0.85rem 1rem`,display:`flex`,alignItems:`center`,gap:`0.75rem`},children:[(0,b.jsx)(op,{size:20}),(0,b.jsxs)(`div`,{style:{fontSize:`0.82rem`,color:`var(--ink-3)`},children:[(0,b.jsx)(`strong`,{style:{color:`var(--ink)`},children:`Interactive Browser Sign-in:`}),` You can also run`,` `,(0,b.jsx)(`code`,{className:`font-mono`,style:{color:`var(--primary)`},children:`kifaru session login`}),` `,`in your terminal to authenticate interactively through your browser.`]})]})]}),(0,b.jsxs)(`div`,{style:{marginTop:`1rem`},children:[(0,b.jsx)(`h2`,{style:{fontSize:`1.15rem`,marginBottom:`0.75rem`},children:`Execution Workers`}),T.data?.items.length?(0,b.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:T.data.items.map(e=>(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(Kx,{variant:Gx(e.status),children:t6(e.status)}),(0,b.jsx)(`span`,{className:`font-mono`,children:e.status})]}),(0,b.jsx)(`h2`,{children:e.name}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.capabilities.map(e=>(0,b.jsx)(`span`,{children:e},e))})]},e.id))}):(0,b.jsx)(Y4,{compact:!0,title:`No workers registered`,detail:`Connect an execution worker before launching capability-bound workflows.`})]})]}):e===`billing`?(0,b.jsx)(q3,{}):e===`team`?(0,b.jsx)(J3,{}):(0,b.jsx)(Y4,{title:`Not found`,detail:`This view does not exist.`})}function q3(){return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(V3,{title:`Billing & Subscription`}),(0,b.jsxs)(`div`,{className:`grid gap-6 md:grid-cols-2`,children:[(0,b.jsxs)(h,{className:`p-6`,children:[(0,b.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,b.jsxs)(`span`,{className:`text-2xs font-semibold uppercase tracking-[0.12em] text-muted-foreground flex items-center gap-1.5`,children:[(0,b.jsx)(Nf,{className:`size-3.5`}),` Current Plan`]}),(0,b.jsx)(Kx,{variant:`success`,children:`Active`})]}),(0,b.jsx)(`div`,{className:`text-2xl font-bold mb-1`,children:`Developer Pro`}),(0,b.jsx)(`p`,{className:`text-sm text-muted-foreground mb-6`,children:`Continuous assurance scans with dedicated runtime concurrency.`}),(0,b.jsxs)(`div`,{className:`space-y-2 border-t pt-4 text-xs text-muted-foreground`,children:[(0,b.jsxs)(`div`,{className:`flex justify-between`,children:[(0,b.jsx)(`span`,{children:`Parallel agent jobs`}),(0,b.jsx)(`span`,{className:`font-semibold text-foreground`,children:`8 concurrent`})]}),(0,b.jsxs)(`div`,{className:`flex justify-between`,children:[(0,b.jsx)(`span`,{children:`Finding retention`}),(0,b.jsx)(`span`,{className:`font-semibold text-foreground`,children:`365 days`})]}),(0,b.jsxs)(`div`,{className:`flex justify-between`,children:[(0,b.jsx)(`span`,{children:`Next renewal`}),(0,b.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Oct 1, 2026`})]})]})]}),(0,b.jsxs)(h,{className:`p-6 flex flex-col justify-between`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,b.jsx)(`span`,{className:`text-2xs font-semibold uppercase tracking-[0.12em] text-muted-foreground`,children:`Scan Credits`}),(0,b.jsx)(`span`,{className:`text-xs font-mono text-[var(--good)] font-semibold`,children:`Active Balance`})]}),(0,b.jsx)(`div`,{className:`text-2xl font-bold font-mono mb-1`,children:`$240.00`}),(0,b.jsx)(`p`,{className:`text-sm text-muted-foreground mb-4`,children:`Prepaid compute balance for high-concurrency automated audits.`})]}),(0,b.jsxs)(`div`,{className:`flex gap-2`,children:[(0,b.jsx)(o,{size:`sm`,className:`flex-1`,children:`Add Balance`}),(0,b.jsx)(o,{size:`sm`,variant:`outline`,children:`Change Plan`})]})]})]}),(0,b.jsxs)(h,{className:`p-6`,children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold mb-4`,children:`Recent Invoices`}),(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-lg border`,children:(0,b.jsxs)(`table`,{className:`w-full text-left text-xs`,children:[(0,b.jsx)(`thead`,{className:`bg-muted/50 border-b`,children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{className:`p-3`,children:`Invoice`}),(0,b.jsx)(`th`,{className:`p-3`,children:`Date`}),(0,b.jsx)(`th`,{className:`p-3`,children:`Amount`}),(0,b.jsx)(`th`,{className:`p-3`,children:`Status`}),(0,b.jsx)(`th`,{className:`p-3 text-right`,children:`Receipt`})]})}),(0,b.jsxs)(`tbody`,{className:`divide-y`,children:[(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{className:`p-3 font-mono font-medium`,children:`INV-2026-009`}),(0,b.jsx)(`td`,{className:`p-3 text-muted-foreground`,children:`Sep 1, 2026`}),(0,b.jsx)(`td`,{className:`p-3 font-mono`,children:`$120.00`}),(0,b.jsx)(`td`,{className:`p-3`,children:(0,b.jsx)(Kx,{variant:`success`,children:`Paid`})}),(0,b.jsx)(`td`,{className:`p-3 text-right`,children:(0,b.jsx)(`span`,{className:`text-primary hover:underline cursor-pointer`,children:`PDF`})})]}),(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{className:`p-3 font-mono font-medium`,children:`INV-2026-008`}),(0,b.jsx)(`td`,{className:`p-3 text-muted-foreground`,children:`Aug 1, 2026`}),(0,b.jsx)(`td`,{className:`p-3 font-mono`,children:`$120.00`}),(0,b.jsx)(`td`,{className:`p-3`,children:(0,b.jsx)(Kx,{variant:`success`,children:`Paid`})}),(0,b.jsx)(`td`,{className:`p-3 text-right`,children:(0,b.jsx)(`span`,{className:`text-primary hover:underline cursor-pointer`,children:`PDF`})})]})]})]})})]})]})}function J3(){return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(V3,{title:`Team & Permissions`}),(0,b.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsxs)(`h2`,{className:`text-base font-semibold flex items-center gap-2`,children:[(0,b.jsx)(dp,{size:18}),` Workspace Members`]}),(0,b.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Manage organization access and security verification roles.`})]}),(0,b.jsxs)(o,{size:`sm`,children:[(0,b.jsx)(Zf,{size:14}),` Invite Member`]})]}),(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Member`}),(0,b.jsx)(`th`,{children:`Role`}),(0,b.jsx)(`th`,{children:`Status`}),(0,b.jsx)(`th`,{children:`Last Active`})]})}),(0,b.jsxs)(`tbody`,{children:[(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[(0,b.jsx)(`div`,{className:`font-semibold text-foreground`,children:`Daniel Bast`}),(0,b.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`daniel@bastsec.com`})]}),(0,b.jsx)(`td`,{children:(0,b.jsx)(Kx,{variant:`default`,children:`Owner / Admin`})}),(0,b.jsx)(`td`,{children:(0,b.jsx)(`span`,{className:`text-xs text-[var(--good)] font-medium`,children:`Active`})}),(0,b.jsx)(`td`,{className:`text-xs text-muted-foreground`,children:`Just now`})]}),(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[(0,b.jsx)(`div`,{className:`font-semibold text-foreground`,children:`Kifaru Security Bot`}),(0,b.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`bot@kifaru.internal`})]}),(0,b.jsx)(`td`,{children:(0,b.jsx)(Kx,{variant:`secondary`,children:`Automated Worker`})}),(0,b.jsx)(`td`,{children:(0,b.jsx)(`span`,{className:`text-xs text-[var(--good)] font-medium`,children:`Active`})}),(0,b.jsx)(`td`,{className:`text-xs text-muted-foreground`,children:`Running scans`})]})]})]})})]})}function Y3({label:e,value:t,detail:n}){return(0,b.jsxs)(h,{children:[(0,b.jsx)(`p`,{className:`text-2xs font-semibold tracking-[0.12em] uppercase text-muted-foreground`,children:e}),(0,b.jsx)(`strong`,{className:`my-1 block text-[28px] font-bold tracking-[-0.02em]`,children:t}),(0,b.jsx)(`p`,{children:n})]})}function X3({findings:e}){let[t,n]=(0,y.useState)(4),r=_x(t),i=Ex(e.filter(e=>e.stage===t));return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(V3,{title:`Finding → data-lifecycle stage`}),(0,b.jsx)(Rx,{findings:e,selected:t,onSelect:n}),(0,b.jsxs)(`div`,{className:`grid items-start gap-4 lg:grid-cols-[1.35fr_1fr]`,children:[(0,b.jsx)(Mx,{title:`Stage ${r.n} · ${r.name}`,sub:`${i.length} finding${i.length===1?``:`s`}`,children:(0,b.jsx)(Lx,{findings:i,emptyLabel:`No open findings at this stage.`})}),(0,b.jsxs)(Mx,{title:`Control pillar × lifecycle stage`,sub:`cell = open findings`,children:[(0,b.jsx)(zx,{findings:e,onSelectStage:n}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-4 text-xs font-medium`,style:{marginTop:12},children:[`critical`,`high`,`medium`,`low`].map(e=>(0,b.jsxs)(`span`,{children:[(0,b.jsx)(`i`,{className:`mcap`,style:{background:`var(${Sx[e]})`}}),`worst: `,Cx[e]]},e))})]})]})]})}function Z3({events:e,findings:t}){let n=Ex(t.filter(e=>e.status===`confirmed`||e.status===`unverified`)),[r,i]=(0,y.useState)(null),a=n.find(e=>e.id===r)??n[0]??null,o=tf({queryKey:[`finding`,a?.id],queryFn:()=>mx.finding(a.id),enabled:!!a});return(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{className:`mb-0`,children:`Findings & evidence`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Every finding carries the evidence chain that produced it; every platform mutation is recorded below.`})]}),(0,b.jsxs)(`div`,{className:`grid items-start gap-4 md:grid-cols-[300px_minmax(0,1fr)]`,children:[(0,b.jsxs)(`div`,{className:`bg-card overflow-hidden rounded-xl border [&_.ph]:text-muted-foreground [&_.ph]:border-b [&_.ph]:border-[var(--hair)] [&_.ph]:px-3.5 [&_.ph]:py-3 [&_.ph]:text-xs [&_.ph]:font-semibold`,children:[(0,b.jsx)(`div`,{className:`ph`,children:`Findings with evidence`}),n.length?n.map(e=>(0,b.jsxs)(`button`,{className:`block w-full border-0 border-b border-l-[3px] border-[var(--hair)] border-l-transparent bg-transparent px-3.5 py-2.5 text-left last:border-b-0 aria-pressed:border-l-primary aria-pressed:bg-[var(--accent-soft)] [&_.pt]:text-[13px] [&_.pt]:font-semibold`,type:`button`,"aria-pressed":e.id===a?.id,onClick:()=>i(e.id),children:[(0,b.jsx)(`span`,{className:`sevtag sev-${e.severity}`,children:Cx[e.severity]}),(0,b.jsx)(`div`,{className:`pt`,children:e.title})]},e.id)):(0,b.jsx)(`div`,{style:{padding:`14px`},children:(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs`,children:`No findings have been ingested yet, so there is no evidence to audit.`})})]}),(0,b.jsx)(`div`,{children:a?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(`div`,{className:`mb-4 flex justify-between gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`span`,{className:`sevtag sev-${a.severity}`,children:Cx[a.severity]}),(0,b.jsx)(`span`,{className:`font-mono text-muted-foreground text-xs`,style:{marginLeft:8},children:a.id}),(0,b.jsx)(`h2`,{style:{marginTop:9},children:a.title})]}),(0,b.jsx)(`span`,{className:`inline-flex shrink-0 self-start rounded-full border px-2.5 py-[3px] text-2xs font-semibold tracking-wide uppercase whitespace-nowrap text-muted-foreground`,children:a.status.replaceAll(`_`,` `)})]}),(0,b.jsx)(`p`,{children:a.description}),(0,b.jsx)(Bx,{items:[{k:`CVSS`,v:o.data?.finding.cvssScore??`—`},{k:`Weakness`,v:o.data?.finding.cwe??`—`,mono:!0},{k:`Category`,v:a.displayCategory},{k:`Lifecycle stage`,v:(0,b.jsxs)(`span`,{className:`inline-flex items-center gap-[5px] [&_.d]:size-2 [&_.d]:rounded-[2px]`,children:[(0,b.jsx)(`span`,{className:`d`,style:{background:`var(${_x(a.stage).v})`}}),a.stage,` · `,vx(_x(a.stage))]})}]}),(0,b.jsx)(Vx,{title:`Evidence chain — provenance`,children:o.data?.finding.evidence.length?o.data.finding.evidence.map(e=>(0,b.jsx)(Hx,{title:e.kind,detail:e.reason??`No reason recorded.`,verdict:e.verdict},e.id)):(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs`,children:`No evidence records attached to this finding.`})}),o.data?.finding.remediation?(0,b.jsx)(Vx,{title:`Remediation`,children:(0,b.jsx)(`p`,{children:o.data.finding.remediation})}):null]}):(0,b.jsx)(Y4,{compact:!0,title:`Nothing to audit yet`,detail:`Evidence appears once an agent reports a finding through report_finding.`})})]}),(0,b.jsx)(Mx,{surface:!1,title:`Governance ledger`,sub:`${e.length} recent event${e.length===1?``:`s`}`,children:e.length?(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`#`}),(0,b.jsx)(`th`,{children:`Action`}),(0,b.jsx)(`th`,{children:`Object`}),(0,b.jsx)(`th`,{children:`Actor`}),(0,b.jsx)(`th`,{children:`Outcome`}),(0,b.jsx)(`th`,{children:`Occurred`})]})}),(0,b.jsx)(`tbody`,{children:e.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{className:`font-mono`,children:e.sequence}),(0,b.jsx)(`td`,{children:e.action}),(0,b.jsxs)(`td`,{children:[e.objectType,` · `,(0,b.jsx)(`span`,{className:`font-mono`,children:e.objectID.slice(0,16)})]}),(0,b.jsx)(`td`,{className:`font-mono`,children:e.actorID??`—`}),(0,b.jsx)(`td`,{children:(0,b.jsx)(Kx,{variant:Gx(e.outcome),children:e.outcome})}),(0,b.jsx)(`td`,{children:new Date(e.createdAt).toLocaleString()})]},e.id))})]})}):(0,b.jsx)(Y4,{compact:!0,title:`No governance events`,detail:`Run creation, state transitions, tool calls and finding ingestion are all recorded here.`})})]})}function Q3({runs:e}){return(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Assessment`}),(0,b.jsx)(`th`,{children:`Kind`}),(0,b.jsx)(`th`,{children:`Status`}),(0,b.jsx)(`th`,{children:`Updated`})]})}),(0,b.jsx)(`tbody`,{children:e.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[(0,b.jsx)(`span`,{children:e.title}),(0,b.jsx)(`span`,{className:`font-mono block text-muted-foreground text-2xs`,children:e.id})]}),(0,b.jsx)(`td`,{children:t6(e.kind)}),(0,b.jsx)(`td`,{children:(0,b.jsx)(Kx,{variant:Gx(e.status),children:t6(e.status)})}),(0,b.jsx)(`td`,{children:new Date(e.updatedAt).toLocaleString()})]},e.id))})]})})}function $3({findings:e}){return(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Finding`}),(0,b.jsx)(`th`,{children:`Severity`}),(0,b.jsx)(`th`,{children:`Status`}),(0,b.jsx)(`th`,{children:`Asset`}),(0,b.jsx)(`th`,{children:`Updated`})]})}),(0,b.jsx)(`tbody`,{children:e.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[(0,b.jsx)(`a`,{href:`/findings`,children:e.title}),(0,b.jsx)(`span`,{className:`font-mono block text-muted-foreground text-2xs`,children:e.description??e.id})]}),(0,b.jsx)(`td`,{children:(0,b.jsx)(Kx,{variant:Gx(e.severity),children:t6(e.severity)})}),(0,b.jsx)(`td`,{children:(0,b.jsx)(Kx,{variant:Gx(e.status),children:t6(e.status)})}),(0,b.jsx)(`td`,{children:e.path??`—`}),(0,b.jsx)(`td`,{children:new Date(e.updatedAt).toLocaleString()})]},e.id))})]})})}function e6(e){let t=new Map;for(let n of e){let e=n.path?.trim()||`Unscoped`,r=t.get(e)??[];r.push(n),t.set(e,r)}return[...t.entries()].map(([e,t])=>({asset:e,items:t})).sort((e,t)=>t.items.length-e.items.length)}function t6(e){return e.replaceAll(`_`,` `).replaceAll(`-`,` `).replace(/\b\w/g,e=>e.toUpperCase())}export{G3 as LiveWorkspaceIsland,U3 as PlatformRoute};
95
+ `),...i.length>0?{attachments:i}:{},...t?{streamingBehavior:t}:{}}},b$=e=>{let t=e.runConfig?.custom?.streamingBehavior;return t===`followUp`||t===`steer`?t:void 0},x$=e=>({role:`user`,content:e.attachments&&e.attachments.length>0?[{type:`text`,text:e.content},...e.attachments]:e.content,timestamp:Date.now()}),S$=e=>{if(e.role!==`user`)return null;let t=e.content;return typeof t==`string`?t:Array.isArray(t)?t.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
96
+ `):null},C$=e=>e.runStatus===`running`&&e.metadata.status===`running`?e:{...e,runStatus:`running`,lastError:void 0,metadata:e.metadata.status===`running`?e.metadata:{...e.metadata,status:`running`}},w$=class{state;stateSnapshot;projectedMessages=[];messageRepository=lH.fromArray([]);version=0;allListeners=new Set;metadataListeners=new Set;messageListeners=new Set;connectionRetainers=0;optimisticUserMessages=[];unsubscribeFromEvents=null;disconnectTimer=null;loadPromise=null;messageFlushScheduled=!1;localSnapshotSeq=0;client;threadId;options;constructor(e,t,n={}){this.client=e,this.threadId=t,this.options=n,this.state=EQ(t),this.stateSnapshot=this.state}getState(){return this.state}getStateSnapshot(){return this.stateSnapshot}getProjectedMessages(){return this.projectedMessages}getMessageRepository(){return this.messageRepository}getVersion(){return this.version}connect(){return this.connectionRetainers+=1,this.ensureEventSubscription({includeSnapshot:this.state.loadState!==`loaded`}),()=>{this.connectionRetainers=Math.max(0,this.connectionRetainers-1),this.maybeDisconnectFromEvents()}}subscribe(e){return this.allListeners.add(e),()=>{this.allListeners.delete(e),this.maybeDisconnectFromEvents()}}subscribeMetadata(e){return this.metadataListeners.add(e),()=>{this.metadataListeners.delete(e),this.maybeDisconnectFromEvents()}}subscribeMessages(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e),this.maybeDisconnectFromEvents()}}dispose(){this.clearDisconnectTimer(),this.unsubscribeFromEvents?.(),this.unsubscribeFromEvents=null,this.allListeners.clear(),this.metadataListeners.clear(),this.messageListeners.clear()}ensureEventSubscription(e){this.clearDisconnectTimer(),!this.unsubscribeFromEvents&&(this.unsubscribeFromEvents=this.client.subscribe(this.threadId,e=>{e.threadId===this.threadId&&this.dispatch(e)},e))}hasConsumers(){return this.connectionRetainers>0||this.allListeners.size>0||this.metadataListeners.size>0||this.messageListeners.size>0}maybeDisconnectFromEvents(){this.hasConsumers()||(this.disconnectTimer||=setTimeout(()=>{this.disconnectTimer=null,!this.hasConsumers()&&(this.unsubscribeFromEvents?.(),this.unsubscribeFromEvents=null)},3e4))}clearDisconnectTimer(){this.disconnectTimer&&=(clearTimeout(this.disconnectTimer),null)}async load(e=!1){if(this.loadPromise&&!e)return this.loadPromise;this.setState({...this.state,loadState:`loading`});let t=this.client.getThread(this.threadId).then(e=>{this.loadPromise===t&&this.applySnapshot(e)}).catch(e=>{throw this.loadPromise===t&&this.setState({...this.state,loadState:`loaded`,lastError:d$(e)}),e}).finally(()=>{this.loadPromise===t&&(this.loadPromise=null)});return this.loadPromise=t,t}refresh(){return this.load(!0)}refreshInBackground(){this.loadPromise||this.refresh().catch(()=>{})}async sendMessage(e,t){if(e.role!==`user`)throw Error(`Pi only supports sending user messages`);let n=this.state.runStatus===`running`,r=t?.streamingBehavior??b$(e)??(n?`followUp`:void 0),i=y$(e,r);if(this.ensureEventSubscription({includeSnapshot:!1}),n)return this.sendQueued(i,r??`followUp`);let a=x$(i);this.optimisticUserMessages.push({message:a,baseMessageCount:this.state.messages.length}),this.setState(C$(this.state)),this.recomputeProjectedMessagesAndNotify();try{await this.client.sendMessage(this.threadId,i)}catch(e){let t=this.optimisticUserMessages.findIndex(e=>e.message===a);throw t!==-1&&this.optimisticUserMessages.splice(t,1),this.recomputeProjectedMessagesAndNotify(),this.setState({...this.state,lastError:d$(e),runStatus:`failed`,metadata:{...this.state.metadata,status:`failed`}}),e}}async sendQueued(e,t){let n=t===`steer`?`steering`:`followUp`,r={...this.state.queue,[n]:[...this.state.queue[n],e.content]};this.setState({...this.state,queue:r});try{await this.client.sendMessage(this.threadId,e)}catch(t){let i=this.state.queue!==r,a=this.state.queue[n],o=i?-1:a.lastIndexOf(e.content);throw this.setState({...this.state,lastError:d$(t),...o===-1?{}:{queue:{...this.state.queue,[n]:a.filter((e,t)=>t!==o)}}}),t}}async clearQueue(){let e=this.state.queue,t=await this.client.clearQueue(this.threadId);return this.state.queue===e&&(e.steering.length>0||e.followUp.length>0)&&this.setState({...this.state,queue:{steering:[],followUp:[]}}),t}async cancel(){try{await this.client.cancelRun(this.threadId)}catch(e){throw this.setState({...this.state,lastError:d$(e)}),e}}async setModel(e){try{await this.client.setModel(this.threadId,e)}catch(e){throw this.setState({...this.state,lastError:d$(e)}),e}await this.refresh()}async setThinkingLevel(e){try{await this.client.setThinkingLevel(this.threadId,e)}catch(e){throw this.setState({...this.state,lastError:d$(e)}),e}await this.refresh()}async respondToToolApproval(e,t){let n=this.state.hostUiRequests.find(t=>t.id===e);await this.respond(n?RQ(n,{approvalId:e,approved:t}):IQ(e,t))}async resumeToolCall(e,t){let n=this.state.hostUiRequests.find(t=>t.toolCallId===e);if(!n)throw Error(`No pending host-UI request for tool call "${e}"`);n.kind===`confirm`?await this.respond(IQ(n.id,t===!0)):await this.respond(BQ(n.id,t))}async respondToHostUiRequest(e){await this.respond(e)}async respond(e){try{await this.client.respondToHostUiRequest(this.threadId,e)}catch(e){throw this.setState({...this.state,lastError:d$(e)}),e}let t=NQ(this.state,e.requestId);t!==this.state&&(this.setState(t),this.recomputeProjectedMessagesAndNotify())}applySnapshot(e){this.dispatch({type:`snapshot`,snapshot:e,threadId:this.threadId,seq:this.localSnapshotSeq})}dispatch(e){let t=PQ(this.state,e),n=t!==this.state;n&&(this.state=t),this.reconcileOptimisticUserMessages(),n&&g$.has(e.type)&&this.notifyMetadataListeners(),n&&m$.has(e.type)&&(h$.has(e.type)?this.scheduleProjectedMessageFlush():this.recomputeProjectedMessagesAndNotify()),(!u$(e.type)||e.type===`entry_appended`&&e.entry?.type!==`custom`)&&this.refreshInBackground()}setState(e){e!==this.state&&(this.state=e,this.notifyMetadataListeners())}projectedInputMessages(){return[...this.state.messages,...this.optimisticUserMessages.map(e=>e.message)]}reconcileOptimisticUserMessages(){if(this.optimisticUserMessages.length===0)return;let e=[];for(let t of this.optimisticUserMessages){let n=S$(t.message);this.state.messages.slice(t.baseMessageCount).some(e=>S$(e)===n)||e.push(t)}e.length!==this.optimisticUserMessages.length&&(this.optimisticUserMessages.length=0,this.optimisticUserMessages.push(...e))}projectMessages(){return c$({messages:this.projectedInputMessages(),toolExecutions:this.state.toolExecutions,runStatus:this.state.runStatus,hostUiRequests:this.state.hostUiRequests},this.projectedMessages)}recomputeProjectedMessagesAndNotify(){let e=this.projectMessages();if(e===this.projectedMessages){this.state!==this.stateSnapshot&&this.publishState();return}this.projectedMessages=e,this.messageRepository=lH.fromArray(e),this.notifyMessageListeners()}scheduleProjectedMessageFlush(){this.messageFlushScheduled||(this.messageFlushScheduled=!0,(this.options.scheduleNotify??f$)(()=>{this.messageFlushScheduled=!1,this.recomputeProjectedMessagesAndNotify()}))}bumpVersion(){this.version+=1}publishState(){this.stateSnapshot=this.state,this.bumpVersion(),p$(this.allListeners)}notifyMetadataListeners(){this.stateSnapshot=this.state,this.bumpVersion(),p$(this.metadataListeners),p$(this.allListeners)}notifyMessageListeners(){this.stateSnapshot=this.state,this.bumpVersion(),p$(this.messageListeners),p$(this.allListeners)}},T$=e=>{let t=Symbol(`${e} extras`),n=e=>typeof e==`object`&&!!e&&t in e;return{provide:e=>(Object.defineProperty(e,t,{value:!0,enumerable:!1,configurable:!0}),e),is:n,tryGet:e=>n(e)?e:void 0,assert:t=>{if(!n(t))throw Error(`The current thread is not backed by the ${e} runtime.`);return t}}},E$=e=>{let{provide:t,is:n,tryGet:r,assert:i}=e,a=e=>i(e.thread.getState().extras);function o(e,...t){let r=t.length>0,a=t[0];return $(t=>{let o=t.thread.extras;return n(o)?e?e(o):o:r?a:i(o)})}return{provide:t,is:n,tryGet:r,get:a,use:o}},D$=(e=>E$(T$(e)))(`usePiRuntime`),O$=EQ(`__pending__`),k$=[],A$=lH.fromArray([]),j$=e=>{let t=new Map,n=!1;return{client:e,controllers:t,get disposed(){return n},activate(){n=!1},dispose(){n=!0;for(let e of t.values())e.dispose()}}},M$=(e,t)=>{let n=e.controllers.get(t);if(n)return n;let r=new w$(e.client,t);return e.controllers.set(t,r),r},N$={getState:()=>O$,getProjectedMessages:()=>k$,getMessageRepository:()=>A$,getVersion:()=>0,subscribe:()=>()=>{},subscribeMetadata:()=>()=>{},subscribeMessages:()=>()=>{},connect:()=>()=>{},load:async()=>{},refresh:async()=>{},sendMessage:async()=>{},cancel:async()=>{},clearQueue:async()=>({steering:[],followUp:[]}),setModel:async()=>{},setThinkingLevel:async()=>{},respondToToolApproval:async()=>{},resumeToolCall:async()=>{},respondToHostUiRequest:async()=>{},dispose:()=>{}},P$=(e,t)=>{HQ(`react-pi`,`onError`,e,t)},F$=(e,t)=>{let{freeStanding:n}=FQ(t.hostUiRequests);return D$.provide({controller:e,state:t,metadata:t.metadata,status:t.runStatus===`failed`?`failed`:t.runStatus,readiness:t.readiness,contextUsage:t.contextUsage,hostUiRequests:n,allHostUiRequests:t.hostUiRequests,queue:t.queue,compaction:t.compaction,retry:t.retry,lastError:t.lastError,cancel:()=>e.cancel(),refresh:()=>e.refresh(),clearQueue:()=>e.clearQueue(),setModel:t=>e.setModel(t),setThinkingLevel:t=>e.setThinkingLevel(t),respondToHostUiRequest:t=>e.respondToHostUiRequest(t),respondToToolApproval:(t,n)=>e.respondToToolApproval(t,n),resumeToolCall:(t,n)=>e.resumeToolCall(t,n)})},I$=F$(N$,O$),L$=e=>e.getStateSnapshot?.()??e.getState(),R$=e=>{let t=(0,y.useCallback)(()=>L$(e),[e]);return(0,y.useSyncExternalStore)((0,y.useCallback)(t=>e.subscribe(t),[e]),t,t)},z$=e=>{let t=(0,y.useCallback)(()=>e.getMessageRepository(),[e]);return(0,y.useSyncExternalStore)((0,y.useCallback)(t=>e.subscribeMessages(t),[e]),t,t)},B$=(e,t)=>{let n=(0,y.useMemo)(()=>{let n;return()=>{let r=L$(e);return(!n||n.state!==r)&&(n={state:r,selection:t(r)}),n.selection}},[e,t]);return(0,y.useSyncExternalStore)((0,y.useCallback)(t=>e.subscribe(t),[e]),n,n)},V$=e=>e.runStatus===`running`||e.compaction.active||e.retry.active,H$=(e,t)=>{let n=R$(e),r=z$(e),{adapters:i,isDisabled:a,isSendDisabled:o,onError:s,suggestions:c,unstable_capabilities:l}=t,u=n.loadState===`loading`,d=V$(n),f=(0,y.useEffectEvent)(e=>{P$(s,e)});(0,y.useEffect)(()=>{e!==N$&&e.load().catch(f)},[e]),(0,y.useEffect)(()=>{if(e!==N$&&d)return e.connect()},[e,d]);let p=(0,y.useMemo)(()=>F$(e,n),[e,n]),m=(0,y.useMemo)(()=>({items:n.queue.followUp.map((e,t)=>({id:wQ(`followUp`,t),prompt:e,parts:[{type:`text`,text:e}]})),steerItems:n.queue.steering.map((e,t)=>({id:wQ(`steer`,t),prompt:e,parts:[{type:`text`,text:e}]})),enqueue:t=>{e.sendMessage(t).catch(e=>P$(s,e))},steer:t=>{e.sendMessage(t,{streamingBehavior:`steer`}).catch(e=>P$(s,e))},move:()=>{},edit:()=>{},remove:()=>{}}),[e,n.queue,s]);return(0,y.useMemo)(()=>({isDisabled:a,isSendDisabled:o,unstable_capabilities:l,suggestions:c,isLoading:u,isRunning:d,messageRepository:r,extras:p,queue:m,...i?{adapters:i}:{},onNew:async t=>{try{await e.sendMessage(t)}catch(e){throw P$(s,e),e}},onCancel:async()=>{try{try{await e.clearQueue()}finally{await e.cancel()}}catch(e){throw P$(s,e),e}},onRespondToToolApproval:async t=>{try{let n=e.getState().hostUiRequests.find(e=>e.id===t.approvalId);if(!n)throw Error(`No pending host-UI request "${t.approvalId}"`);await e.respondToHostUiRequest(RQ(n,t))}catch(e){throw P$(s,e),e}},onResumeToolCall:({toolCallId:t,payload:n})=>{e.resumeToolCall(t,n).catch(e=>P$(s,e))}}),[e,p,r,m,i,a,u,d,o,s,c,l])},U$=(e,t)=>({id:`pi-new-user:${t}`,role:`user`,createdAt:new Date,content:v$(e)}),W$=(e,t)=>{let n=Q(),{adapters:r,isDisabled:i,isSendDisabled:a,onError:o,suggestions:s,unstable_capabilities:c}=t,[l,u]=(0,y.useState)([]),d=(0,y.useRef)(0),f=(0,y.useMemo)(()=>lH.fromArray(l),[l]);return(0,y.useMemo)(()=>({isDisabled:i??!1,isSendDisabled:a,unstable_capabilities:c,suggestions:s,isLoading:!1,isRunning:!1,messageRepository:f,extras:I$,...r?{adapters:r}:{},onNew:async t=>{let r=U$(t,d.current++);u(e=>[...e,r]);let i=()=>{u(e=>e.filter(e=>e!==r))};try{let{remoteId:r,externalId:a}=await n.threadListItem.initialize();if(e.disposed){i();return}await M$(e,a??r).sendMessage(t),i()}catch(e){throw i(),P$(o,e),e}}}),[n,f,e,r,i,a,o,s,c])},G$=(e,t)=>{let n=$(e=>e.threadListItem),r=$(e=>e.threads.mainThreadId===e.threadListItem.id),i=n.externalId??n.remoteId,a=i?M$(e,i):N$,o=H$(r?a:N$,t),s=W$(e,t);return zH(i?o:s)},K$=e=>({status:e.archived?`archived`:`regular`,remoteId:e.id,externalId:e.id,...e.title===void 0?{}:{title:e.title},custom:{status:e.status,...e.workspacePath===void 0?{}:{workspacePath:e.workspacePath},...e.sessionFile===void 0?{}:{sessionFile:e.sessionFile},...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath}}}),q$=e=>{let{client:t}=e,n=(0,y.useMemo)(()=>j$(t),[t]);return(0,y.useEffect)(()=>(n.activate(),()=>n.dispose()),[n]),kU({allowNesting:!0,adapter:(0,y.useMemo)(()=>({list:async()=>({threads:(await t.listThreads({...e.workspacePath===void 0?{}:{workspacePath:e.workspacePath},...e.includeArchived===void 0?{}:{includeArchived:e.includeArchived}})).map(K$)}),rename:async(e,n)=>{await t.renameThread(e,n)},archive:async e=>{await t.archiveThread?.(e)},unarchive:async e=>{await t.unarchiveThread?.(e)},delete:async e=>{await t.deleteThread?.(e)},initialize:async()=>{let n=await t.createThread({...e.workspacePath===void 0?{}:{workspacePath:e.workspacePath}});return{remoteId:n.metadata.id,externalId:n.metadata.id}},generateTitle:async()=>new ReadableStream({start(e){e.close()}}),fetch:async e=>K$((await t.getThread(e)).metadata)}),[t,e.workspacePath,e.includeArchived]),...e.initialThreadId===void 0?{}:{initialThreadId:e.initialThreadId},...e.threadId===void 0?{}:{threadId:e.threadId},...e.onThreadIdChange===void 0?{}:{onThreadIdChange:e.onThreadIdChange},runtimeHook:()=>G$(n,e)})},J$=()=>D$.use(e=>e,I$),Y$=()=>D$.use(e=>e.metadata,null);function X$(e){return B$(D$.use(e=>e.controller,N$),e??(e=>e))}var Z$=()=>{let e=D$.use(e=>e,void 0);return(0,y.useMemo)(()=>({requests:e?.hostUiRequests??[],respond:e?.respondToHostUiRequest??(async()=>{throw Error(`Pi runtime is not ready yet`)})}),[e])};function Q$({delayDuration:e=0,...t}){return(0,b.jsx)(Du,{"data-slot":`tooltip-provider`,delayDuration:e,...t})}function $$({...e}){return(0,b.jsx)(Ou,{"data-slot":`tooltip`,...e})}function e1({...e}){return(0,b.jsx)(ku,{"data-slot":`tooltip-trigger`,...e})}function t1({className:e,sideOffset:t=0,children:n,...r}){return(0,b.jsx)(Au,{children:(0,b.jsxs)(ju,{"data-slot":`tooltip-content`,sideOffset:t,className:a(`z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95`,e),...r,children:[n,(0,b.jsx)(Mu,{className:`z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground`})]})})}function n1({...e}){return(0,b.jsx)(wr,{"data-slot":`dialog`,...e})}function r1({...e}){return(0,b.jsx)(Er,{"data-slot":`dialog-trigger`,...e})}function i1({...e}){return(0,b.jsx)(Ar,{"data-slot":`dialog-portal`,...e})}function a1({className:e,...t}){return(0,b.jsx)(Mr,{"data-slot":`dialog-overlay`,className:a(`fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0`,e),...t})}function o1({className:e,children:t,showCloseButton:n=!0,...r}){return(0,b.jsxs)(i1,{"data-slot":`dialog-portal`,children:[(0,b.jsx)(a1,{}),(0,b.jsxs)(Ir,{"data-slot":`dialog-content`,className:a(`fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg`,e),...r,children:[t,n&&(0,b.jsxs)(Gr,{"data-slot":`dialog-close`,className:`absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,children:[(0,b.jsx)(mp,{}),(0,b.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function s1({className:e,...t}){return(0,b.jsx)(`div`,{"data-slot":`dialog-header`,className:a(`flex flex-col gap-2 text-center sm:text-left`,e),...t})}function c1({className:e,showCloseButton:t=!1,children:n,...r}){return(0,b.jsxs)(`div`,{"data-slot":`dialog-footer`,className:a(`flex flex-col-reverse gap-2 sm:flex-row sm:justify-end`,e),...r,children:[n,t&&(0,b.jsx)(Gr,{asChild:!0,children:(0,b.jsx)(o,{variant:`outline`,children:`Close`})})]})}function l1({className:e,...t}){return(0,b.jsx)(Vr,{"data-slot":`dialog-title`,className:a(`text-lg leading-none font-semibold`,e),...t})}function u1({className:e,...t}){return(0,b.jsx)(Ur,{"data-slot":`dialog-description`,className:a(`text-sm text-muted-foreground`,e),...t})}function d1({className:e,size:t=`default`,...n}){return(0,b.jsx)(ti,{"data-slot":`avatar`,"data-size":t,className:a(`group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6`,e),...n})}function f1({className:e,...t}){return(0,b.jsx)(ri,{"data-slot":`avatar-image`,className:a(`aspect-square size-full`,e),...t})}function p1({className:e,...t}){return(0,b.jsx)(ai,{"data-slot":`avatar-fallback`,className:a(`flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs`,e),...t})}var m1=(0,y.forwardRef)(({children:e,tooltip:t,side:n=`bottom`,className:r,...i},s)=>(0,b.jsx)(Q$,{delayDuration:0,children:(0,b.jsxs)($$,{children:[(0,b.jsx)(e1,{asChild:!0,children:(0,b.jsxs)(o,{variant:`ghost`,size:`icon`,...i,className:a(`aui-button-icon size-6 p-1 active:scale-90`,r),ref:s,children:[(0,b.jsx)(c,{children:e}),(0,b.jsx)(`span`,{className:`aui-sr-only sr-only`,children:t})]})}),(0,b.jsx)(t1,{side:n,children:t})]})}));m1.displayName=`TooltipIconButton`;var h1=e=>Symbol.iterator in e,g1=e=>`entries`in e,_1=(e,t)=>{let n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(let[e,t]of n)if(!r.has(e)||!Object.is(t,r.get(e)))return!1;return!0},v1=(e,t)=>{let n=e[Symbol.iterator](),r=t[Symbol.iterator](),i=n.next(),a=r.next();for(;!i.done&&!a.done;){if(!Object.is(i.value,a.value))return!1;i=n.next(),a=r.next()}return!!i.done&&!!a.done};function y1(e,t){return Object.is(e,t)?!0:typeof e!=`object`||!e||typeof t!=`object`||!t||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:h1(e)&&h1(t)?g1(e)&&g1(t)?_1(e,t):v1(e,t):_1({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function b1(e){let t=y.useRef(void 0);return n=>{let r=e(n);return y1(t.current,r)?t.current:t.current=r}}var x1=e=>{let[t,n]=(0,y.useState)(void 0);return(0,y.useEffect)(()=>{if(!e){n(void 0);return}let t=URL.createObjectURL(e);return n({file:e,url:t}),()=>{URL.revokeObjectURL(t)}},[e]),t!==void 0&&t.file===e?t.url:void 0},S1=()=>{let{file:e,src:t}=$(b1(e=>{if(e.attachment.type!==`image`)return{};if(e.attachment.file)return{file:e.attachment.file};let t=e.attachment.content?.filter(e=>e.type===`image`)[0]?.image;return t?{src:t}:{}}));return x1(e)??t},C1=({src:e})=>{let[t,n]=(0,y.useState)(!1);return(0,b.jsx)(`img`,{src:e,alt:`Attachment preview`,className:a(`block h-auto max-h-[80vh] w-auto max-w-full rounded-sm object-contain transition-opacity duration-300 motion-reduce:transition-none`,t?`aui-attachment-preview-image-loaded opacity-100`:`aui-attachment-preview-image-loading opacity-0`),onLoad:()=>n(!0)})},w1=({children:e})=>{let t=S1();return t?(0,b.jsxs)(n1,{children:[(0,b.jsx)(r1,{className:`aui-attachment-preview-trigger cursor-zoom-in`,asChild:!0,children:(0,y.isValidElement)(e)?e:(0,b.jsx)(`button`,{type:`button`,children:e})}),(0,b.jsxs)(o1,{className:`aui-attachment-preview-dialog-content [&>button]:bg-foreground/60 [&>button]:hover:bg-foreground/80 [&_svg]:text-background p-2 sm:max-w-3xl [&>button]:rounded-full [&>button]:p-1 [&>button]:opacity-100 [&>button]:ring-0!`,children:[(0,b.jsx)(l1,{className:`aui-sr-only sr-only`,children:`Image Attachment Preview`}),(0,b.jsx)(`div`,{className:`aui-attachment-preview bg-background relative mx-auto flex max-h-[80dvh] w-full items-center justify-center overflow-hidden rounded-sm`,children:(0,b.jsx)(C1,{src:t})})]})]}):e},T1=()=>{let e=S1();return(0,b.jsxs)(d1,{className:`aui-attachment-tile-avatar h-full w-full rounded-none`,children:[(0,b.jsx)(f1,{src:e,alt:`Attachment preview`,className:`aui-attachment-tile-image rounded-none object-cover`}),(0,b.jsx)(p1,{children:(0,b.jsx)(Lf,{className:`aui-attachment-tile-fallback-icon text-muted-foreground/80 size-6 stroke-[1.5]`})})]})},E1=()=>{let e=Q().attachment.source!==`message`,t=$(e=>e.attachment.type===`image`),n=$(e=>{let t=e.attachment.type;switch(t){case`image`:return`Image`;case`document`:return`Document`;case`file`:return`File`;default:return t}}),r=$(e=>e.attachment.status.type===`running`?`uploading`:e.attachment.status.type===`incomplete`&&e.attachment.status.reason===`error`?`error`:void 0),i=r===`uploading`,o=r===`error`,s=$(e=>e.attachment.status.type===`incomplete`&&e.attachment.status.reason===`error`?e.attachment.status.message??`Upload failed`:void 0);return(0,b.jsx)(Q$,{children:(0,b.jsxs)($$,{children:[(0,b.jsxs)(Pq.Root,{className:a(`aui-attachment-root relative`,e&&`animate-in fade-in-0 zoom-in-95 duration-200 motion-reduce:animate-none`,t&&!e&&`aui-attachment-root-message only:*:first:size-24`),children:[(0,b.jsx)(w1,{children:(0,b.jsx)(e1,{asChild:!0,children:(0,b.jsxs)(`div`,{className:a(`aui-attachment-tile bg-muted hover:after:bg-foreground/10 focus-visible:ring-ring/50 relative size-14 cursor-pointer overflow-hidden rounded-[calc(var(--composer-radius,1rem)-var(--composer-padding,8px))] transition-transform outline-none after:pointer-events-none after:absolute after:inset-0 after:rounded-[inherit] after:ring-1 after:ring-black/10 after:transition-colors after:ring-inset focus-visible:ring-1 active:scale-[0.96] motion-reduce:transition-none dark:after:ring-white/10`,o&&`after:ring-destructive/60 dark:after:ring-destructive/60`),role:`button`,tabIndex:0,onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),e.currentTarget.click()):e.key===` `&&e.preventDefault()},onKeyUp:e=>{e.key===` `&&e.currentTarget.click()},"aria-label":`${n} attachment${o?`, upload failed`:i?`, uploading`:``}`,children:[(0,b.jsx)(T1,{}),i&&(0,b.jsx)(`div`,{"aria-hidden":`true`,className:`aui-attachment-tile-uploading bg-background/60 animate-in fade-in-0 absolute inset-0 flex items-center justify-center backdrop-blur-[2px] motion-reduce:animate-none`,children:(0,b.jsx)(Uf,{className:`text-muted-foreground size-4 animate-spin`})}),o&&(0,b.jsx)(`div`,{"aria-hidden":`true`,className:`aui-attachment-tile-error bg-background/70 animate-in fade-in-0 absolute inset-0 flex items-center justify-center backdrop-blur-[2px] motion-reduce:animate-none`,children:(0,b.jsx)(Ef,{className:`text-destructive size-4`})})]})})}),e&&(0,b.jsx)(D1,{})]}),(0,b.jsxs)(t1,{side:`top`,children:[(0,b.jsx)(Pq.Name,{}),s&&(0,b.jsx)(`p`,{className:`aui-attachment-error-message`,children:s})]})]})})},D1=()=>(0,b.jsx)(Pq.Remove,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Remove file`,className:`aui-attachment-tile-remove absolute end-1 top-1 size-5 rounded-full bg-black/50! text-white after:absolute after:-inset-1.5 hover:bg-black/70! hover:text-white! active:scale-[0.96] motion-reduce:transition-none`,side:`top`,children:(0,b.jsx)(mp,{className:`aui-attachment-remove-icon size-3 stroke-[2.5]`})})}),O1=()=>(0,b.jsx)(`div`,{className:`aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2 empty:hidden`,children:(0,b.jsx)(ZX.Attachments,{children:()=>(0,b.jsx)(E1,{})})}),k1=()=>(0,b.jsx)(`div`,{className:`aui-composer-attachments flex w-full flex-row items-center gap-2 overflow-x-auto empty:hidden`,children:(0,b.jsx)(zY.Attachments,{children:()=>(0,b.jsx)(E1,{})})}),A1=()=>(0,b.jsx)(zY.AddAttachment,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Add Attachment`,side:`bottom`,variant:`ghost`,size:`icon`,className:`aui-composer-add-attachment text-muted-foreground hover:text-foreground hover:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30 size-7 rounded-full active:scale-[0.96] motion-reduce:transition-none`,"aria-label":`Add Attachment`,children:(0,b.jsx)(Zf,{className:`aui-attachment-add-icon size-4`})})}),j1=v(`aui-file-root inline-flex items-center gap-3 rounded-lg transition-colors`,{variants:{variant:{outline:`border-border hover:bg-muted/50 border`,ghost:`hover:bg-muted/50`,muted:`bg-muted/50 hover:bg-muted/70`},size:{sm:`px-2.5 py-1.5 text-xs`,default:`px-3 py-2 text-sm`,lg:`px-4 py-3 text-base`}},defaultVariants:{variant:`outline`,size:`default`}});function M1(e){let t=e.toLowerCase();return t.startsWith(`image/`)?Bf:t===`application/pdf`?Lf:t===`application/json`?bf:t.startsWith(`text/`)?Lf:t.startsWith(`audio/`)?Kf:t.startsWith(`video/`)?fp:Rf}function N1(e,t){return t===`url`&&/^data:/i.test(e)?`data-uri`:t||(/^data:/i.test(e)?`data-uri`:/^https?:\/\//i.test(e)?`url`:`base64`)}function P1(e){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`),n=e.search(/[^A-Za-z\d+/]/);return n!==-1&&n!==e.length-t||e.length%4==1||t>0&&e.length%4!=0?0:Math.floor(e.length*3/4)-t}function F1(e){return P1(/[\t\n\f\r ]/.test(e)?e.replace(/[\t\n\f\r ]/g,``):e)}function I1(e){let t=e.indexOf(`#`),n=t<0?e.length:t,r=e.indexOf(`,`);if(r<0||r>=n)return 0;let i=e.slice(r+1,n);return/;base64$/i.test(e.slice(0,r))?(/[%\t\n\f\r ]/.test(i)&&(i=i.replace(/%([\da-f]{2})/gi,(e,t)=>String.fromCharCode(Number.parseInt(t,16))).replace(/[\t\n\f\r ]/g,``)),P1(i)):new TextEncoder().encode(i.replace(/%[\da-f]{2}/gi,`_`)).byteLength}function L1(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function R1({className:e,variant:t,size:n,children:r,...i}){return(0,b.jsx)(`div`,{"data-slot":`file-root`,"data-variant":t,"data-size":n,className:a(j1({variant:t,size:n,className:e})),...i,children:r})}function z1({mimeType:e,className:t,children:n,...r}){let i=e?M1(e):Rf;return(0,b.jsx)(`span`,{"data-slot":`file-icon`,className:a(`text-muted-foreground shrink-0`,t),...r,children:n??(0,b.jsx)(i,{className:`size-5`})})}function B1({className:e,children:t,...n}){return(0,b.jsx)(`span`,{"data-slot":`file-name`,className:a(`min-w-0 flex-1 truncate font-medium`,e),...n,children:t||`Unnamed file`})}function V1({bytes:e,className:t,...n}){return(0,b.jsx)(`span`,{"data-slot":`file-size`,className:a(`text-muted-foreground shrink-0`,t),...n,children:L1(e)})}function H1({data:e,mimeType:t,filename:n,sourceType:r,className:i,children:o,...s}){if(typeof e!=`string`)return null;let c=N1(e,r);if(c===`id`||c===`url`&&!/^(https?:\/\/|blob:)/i.test(e))return null;let l=c===`base64`?`data:${t};base64,${e}`:e;return(0,b.jsx)(`a`,{"data-slot":`file-download`,href:l,download:n||`download`,...c===`url`&&{target:`_blank`,rel:`noopener noreferrer`},className:a(`text-muted-foreground hover:bg-accent hover:text-accent-foreground shrink-0 rounded-md p-1 transition-colors`,i),"aria-label":o?void 0:`Download ${n||`file`}`,...s,children:o||(0,b.jsx)(Pf,{className:`size-4`})})}var U1=(0,y.memo)(({filename:e,data:t,mimeType:n,sourceType:r})=>{let i=N1(t,r);return(0,b.jsxs)(R1,{children:[(0,b.jsx)(z1,{mimeType:n}),(0,b.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,b.jsx)(B1,{children:e}),typeof t==`string`&&(i===`base64`||i===`data-uri`)&&(0,b.jsx)(V1,{bytes:i===`data-uri`?I1(t):F1(t),className:`text-xs`})]}),(0,b.jsx)(H1,{data:t,mimeType:n,...e!==void 0&&{filename:e},...r!==void 0&&{sourceType:r}})]})});U1.displayName=`File`,U1.Root=R1,U1.Icon=z1,U1.Name=B1,U1.Size=V1,U1.Download=H1;var W1=()=>{let e=$(e=>e.thread.suggestions),t=(0,y.useRef)(null),n=(0,y.useRef)(null),[r,i]=(0,y.useState)({left:!1,right:!1}),a=(0,y.useCallback)(()=>{let e=t.current;if(!e)return;let r=e.scrollWidth-e.clientWidth,a=Math.abs(e.scrollLeft),[o,s]=(n.current??=getComputedStyle(e).direction===`rtl`)?[r-a,a]:[a,r-a];i(e=>{let t={left:o>1,right:s>1};return e.left===t.left&&e.right===t.right?e:t})},[]);(0,y.useEffect)(()=>{a();let e=t.current;if(!e?.firstElementChild)return;let n=new ResizeObserver(a);return n.observe(e),n.observe(e.firstElementChild),()=>n.disconnect()},[a]);let o=`linear-gradient(to right, ${r.left?`transparent, black 2rem`:`black`}, ${r.right?`black calc(100% - 2rem), transparent`:`black`})`;return(0,b.jsx)(`div`,{ref:t,onScroll:a,className:`aui-thread-followup-suggestions -my-1 w-full [scrollbar-width:none] overflow-x-auto py-1 [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden`,style:{maskImage:o,WebkitMaskImage:o},children:(0,b.jsx)(`div`,{className:`mx-auto flex min-h-8 w-max items-center gap-2 px-0.5`,children:e.map((e,t)=>(0,b.jsxs)(FZ.Suggestion,{className:`aui-thread-followup-suggestion border-foreground/10 hover:bg-foreground/[0.03] hover:border-foreground/25 rounded-md border px-2.5 py-1 text-sm whitespace-nowrap transition-colors ease-in motion-reduce:transition-none`,prompt:e.prompt,send:!0,children:[e.title??e.prompt,e.label&&(0,b.jsx)(`span`,{className:`aui-thread-followup-suggestion-label text-muted-foreground ms-1`,children:e.label})]},t))})})},G1=()=>(0,b.jsx)(LL,{condition:e=>!e.thread.isEmpty&&!e.thread.isRunning&&e.thread.suggestions.length>0,children:(0,b.jsx)(W1,{})}),K1=e=>{switch(e){case`image/png`:return`png`;case`image/jpeg`:case`image/jpg`:return`jpg`;case`image/webp`:return`webp`;case`image/gif`:return`gif`;case`image/svg+xml`:return`svg`;default:return`png`}},q1=e=>{let t=e.indexOf(`,`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):``,i=n.match(/data:([^;]+)/i)?.[1]?.toLowerCase()??`application/octet-stream`;if(!/;base64/i.test(n)){let e=r.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return decodeURIComponent(e)}catch{return e}});return new Blob([e],{type:i})}let a;try{let e=r.replace(/%([\da-f]{2})/gi,(e,t)=>String.fromCharCode(Number.parseInt(t,16)));a=atob(e)}catch{return null}let o=new Uint8Array(a.length);for(let e=0;e<a.length;e++)o[e]=a.charCodeAt(e);return new Blob([o],{type:i})},J1=e=>e.match(/^data:([^;,]+)/i)?.[1]?.toLowerCase(),Y1=e=>{if(typeof document>`u`)return;let t=K1(J1(e.image)),n=e.filename??`image.${t}`,r=/^data:/i.test(e.image),i=r?q1(e.image):null;if(r&&!i)return;let a=i?URL.createObjectURL(i):null,o=a??e.image,s=document.createElement(`a`);s.href=o,s.download=n,s.rel=`noopener`,document.body.appendChild(s),s.click(),document.body.removeChild(s),a&&setTimeout(()=>URL.revokeObjectURL(a),4e4)},X1=async e=>{if(typeof navigator>`u`||!navigator.clipboard||typeof ClipboardItem>`u`)throw Error(`Clipboard API is not available in this environment.`);let t=/^data:/i.test(e.image)?q1(e.image):await fetch(e.image).then(e=>e.blob());if(!t)return;let n=J1(e.image)??t.type??`image/png`;await navigator.clipboard.write([new ClipboardItem({[n]:t})])},Z1=v(`aui-image-root relative overflow-hidden rounded-lg`,{variants:{variant:{outline:`border-border border`,ghost:``,muted:`bg-muted/50`},size:{sm:`max-w-64`,default:`max-w-96`,lg:`max-w-[512px]`,full:`w-full`}},defaultVariants:{variant:`outline`,size:`default`}});function Q1({className:e,variant:t,size:n,children:r,...i}){return(0,b.jsx)(`div`,{"data-slot":`image-root`,"data-variant":t,"data-size":n,className:a(Z1({variant:t,size:n,className:e})),...i,children:r})}function $1({className:e,containerClassName:t,onLoad:n,onError:r,alt:i=`Image content`,src:o,...s}){let c=(0,y.useRef)(null),[l,u]=(0,y.useState)(void 0),[d,f]=(0,y.useState)(void 0),p=l===o,m=d===o;return(0,y.useEffect)(()=>{let e=c.current;typeof o==`string`&&e?.complete&&(e.naturalWidth>0?u(o):f(o))},[o]),(0,b.jsxs)(`div`,{"data-slot":`image-preview`,className:a(`relative min-h-32`,t),children:[!p&&!m&&(0,b.jsx)(`div`,{"data-slot":`image-preview-loading`,className:`bg-muted/50 absolute inset-0 flex items-center justify-center`,children:(0,b.jsx)(Bf,{className:`text-muted-foreground size-8 animate-pulse`})}),m?(0,b.jsx)(`div`,{"data-slot":`image-preview-error`,className:`bg-muted/50 flex min-h-32 items-center justify-center p-4`,children:(0,b.jsx)(zf,{className:`text-muted-foreground size-8`})}):(0,b.jsx)(`img`,{ref:c,src:o,alt:i,className:a(`block h-auto w-full object-contain`,!p&&`invisible`,e),onLoad:e=>{typeof o==`string`&&u(o),n?.(e)},onError:e=>{typeof o==`string`&&f(o),r?.(e)},...s})]})}function e0({className:e,children:t,...n}){return t?(0,b.jsx)(`span`,{"data-slot":`image-filename`,className:a(`text-muted-foreground block truncate px-2 py-1.5 text-xs`,e),...n,children:t}):null}function t0({src:e,alt:t=`Image preview`,children:n}){let[r,i]=(0,y.useState)(!1),a=(0,y.useRef)(null),o=(0,y.useRef)(null),s=(0,y.useRef)(null),c=(0,y.useCallback)(()=>i(!0),[]),l=(0,y.useCallback)(()=>{i(!1),a.current?.focus()},[]);return(0,y.useEffect)(()=>{if(!r)return;let e=e=>{if(e.key===`Escape`){l();return}if(e.key!==`Tab`)return;let t=s.current?.querySelectorAll(`a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])`),n=t?.[0],r=t?.[t.length-1];n&&r&&(e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus()))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[r,l]),(0,y.useEffect)(()=>{if(!r)return;let e=document.body.style.overflow;return document.body.style.overflow=`hidden`,()=>{document.body.style.overflow=e}},[r]),(0,y.useEffect)(()=>{r&&o.current?.focus()},[r]),(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(`div`,{ref:a,onClick:c,onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),e.currentTarget.click()):e.key===` `&&e.preventDefault()},onKeyUp:e=>{e.key===` `&&e.currentTarget.click()},role:`button`,tabIndex:0,className:`aui-image-zoom-trigger cursor-zoom-in`,"aria-label":`Click to zoom image`,children:n}),r&&(0,Ut.createPortal)((0,b.jsxs)(`div`,{ref:s,"data-slot":`image-zoom-overlay`,role:`dialog`,"aria-modal":`true`,className:`aui-image-zoom-overlay fade-in animate-in fixed inset-0 z-50 flex items-center justify-center bg-black/80 duration-200`,onClick:l,"aria-label":`Zoomed image`,children:[(0,b.jsx)(`img`,{"data-slot":`image-zoom-content`,src:e,alt:t,className:`aui-image-zoom-content fade-in zoom-in-95 animate-in max-h-[90vh] max-w-[90vw] cursor-zoom-out object-contain duration-200`,onClick:e=>{e.stopPropagation(),l()}}),(0,b.jsx)(`button`,{ref:o,type:`button`,"aria-label":`Close zoomed image`,onClick:e=>{e.stopPropagation(),l()},className:`text-muted-foreground hover:text-foreground bg-background/80 absolute end-4 top-4 cursor-pointer rounded-md p-2`,children:(0,b.jsx)(mp,{className:`size-5`})})]}),document.body)]})}function n0({className:e}){return(0,b.jsxs)(`div`,{"data-slot":`image-generating`,className:a(`bg-muted/50 flex min-h-32 items-center justify-center p-4`,e),children:[(0,b.jsx)(Uf,{className:`text-muted-foreground size-8 animate-spin`}),(0,b.jsx)(`span`,{className:`sr-only`,children:`Generating image…`})]})}function r0({className:e,reason:t}){return(0,b.jsxs)(`div`,{"data-slot":`image-content-filter-error`,className:a(`bg-muted/50 flex min-h-32 flex-col items-center justify-center gap-2 p-4 text-center`,e),children:[(0,b.jsx)(tp,{className:`text-muted-foreground size-8`}),(0,b.jsx)(`p`,{className:`text-sm font-medium`,children:`Image could not be generated`}),t&&(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs`,children:t})]})}function i0({onRegenerate:e}){let[t,n]=(0,y.useState)(!1);return(0,b.jsx)(`button`,{type:`button`,onClick:async()=>{n(!0);try{await e()}catch{}finally{n(!1)}},disabled:t,"data-slot":`image-regenerate`,"aria-label":`Regenerate image`,className:`hover:bg-muted inline-flex size-7 items-center justify-center rounded disabled:opacity-50`,children:(0,b.jsx)(Qf,{className:a(`size-4`,t&&`animate-spin`)})})}function a0({part:e,onRegenerate:t,className:n}){return(0,b.jsxs)(`div`,{"data-slot":`image-actions`,className:a(`flex items-center gap-1 p-1`,n),children:[(0,b.jsx)(`button`,{type:`button`,onClick:()=>Y1(e),"data-slot":`image-download`,"aria-label":`Download image`,className:`hover:bg-muted inline-flex size-7 items-center justify-center rounded`,children:(0,b.jsx)(Pf,{className:`size-4`})}),(0,b.jsx)(`button`,{type:`button`,onClick:()=>{X1(e).catch(()=>{})},"data-slot":`image-copy`,"aria-label":`Copy image`,className:`hover:bg-muted inline-flex size-7 items-center justify-center rounded`,children:(0,b.jsx)(Mf,{className:`size-4`})}),t&&(0,b.jsx)(i0,{onRegenerate:t})]})}var o0=(0,y.memo)(e=>{let{image:t,filename:n,status:r}=e;return r?.type===`running`?(0,b.jsxs)(Q1,{children:[(0,b.jsx)(n0,{}),(0,b.jsx)(e0,{children:n})]}):r?.type===`incomplete`&&r.reason===`content-filter`?(0,b.jsx)(Q1,{children:(0,b.jsx)(r0,{reason:`The provider blocked this image.`})}):(0,b.jsxs)(Q1,{children:[(0,b.jsx)(t0,{src:t,alt:n||`Image content`,children:(0,b.jsx)($1,{src:t,alt:n||`Image content`})}),(0,b.jsx)(e0,{children:n})]})});o0.displayName=`Image`,o0.Root=Q1,o0.Preview=$1,o0.Filename=e0,o0.Zoom=t0,o0.Actions=a0,o0.Generating=n0,o0.ContentFilterError=r0;var s0=(e,t)=>typeof e==`string`?e===t:JSON.stringify(e)===JSON.stringify(t),c0=(e,t)=>{if(!e||!t)return!1;let n=e=>{let{position:t,data:n,...r}=e||{};return r};return JSON.stringify(n(e.properties))===JSON.stringify(n(t.properties))&&s0(e.children,t.children)},l0=(e,t)=>c0(e.node,t.node),u0=(e={})=>Object.fromEntries(Object.entries(e??{}).map(([e,t])=>{if(!t)return[e,t];let n=t;return[e,(0,y.memo)(({node:e,...t})=>(0,b.jsx)(n,{...t}),l0)]})),d0=(0,y.createContext)(null),f0=()=>(0,y.useContext)(d0)!==null,p0=(0,y.memo)(({children:e,fallbackPre:t,...n})=>n.node?.children.some(e=>e.type===`element`&&e.tagName===`code`)??!0?(0,b.jsx)(d0.Provider,{value:n,children:e}):(0,b.jsx)(t,{...n,children:e}),(e,t)=>e.fallbackPre===t.fallbackPre&&l0(e,t)),m0=({node:e,...t})=>(0,b.jsx)(`pre`,{...t}),h0=({node:e,...t})=>(0,b.jsx)(`code`,{...t}),g0=({node:e,components:{Pre:t,Code:n},code:r})=>(0,b.jsx)(t,{children:(0,b.jsx)(n,{node:e,children:r})}),_0=()=>null,v0=e=>/language-([^\s]+)/.exec(e??``)?.[1]??``,y0=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:r,CodeHeader:i},language:a,code:o})=>{let s=(0,y.useMemo)(()=>({Pre:t,Code:n}),[t,n]);return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(i,{node:e,language:a,code:o}),(0,b.jsx)(r,{node:e,components:s,language:a,code:o})]})},b0=n(r(((e,t)=>{(function(){var e={}.hasOwnProperty;function n(){for(var e=``,t=0;t<arguments.length;t++){var n=arguments[t];n&&(e=i(e,r(n)))}return e}function r(t){if(typeof t==`string`||typeof t==`number`)return t;if(typeof t!=`object`)return``;if(Array.isArray(t))return n.apply(null,t);if(t.toString!==Object.prototype.toString&&!t.toString.toString().includes(`[native code]`))return t.toString();var r=``;for(var a in t)e.call(t,a)&&t[a]&&(r=i(r,a));return r}function i(e,t){return t?e?e+` `+t:e+t:e}t!==void 0&&t.exports?(n.default=n,t.exports=n):typeof define==`function`&&typeof define.amd==`object`&&define.amd?define(`classnames`,[],function(){return n}):window.classNames=n})()}))(),1),x0=({className:e,...t})=>({className:n,...r})=>({className:(0,b0.default)(e,n),...t,...r});function S0(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=``;for(let n of e)t+=S0(n);return t}return(0,y.isValidElement)(e)?S0(e.props.children):``}var C0=({node:e,components:{Pre:t,Code:n,SyntaxHighlighter:r,CodeHeader:i},componentsByLanguage:a={},children:o,...s})=>{let c=x0((0,y.useContext)(d0)),l=dt(e=>(0,b.jsx)(t,{...c(e)})),u=x0(s),d=dt(e=>(0,b.jsx)(n,{...u(e)})),f=v0(s.className),p=a[f]?.SyntaxHighlighter??r,m=a[f]?.CodeHeader??i;return o!=null&&typeof o!=`string`?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(m,{node:e,language:f,code:S0(o)}),(0,b.jsx)(g0,{node:e,components:{Pre:l,Code:d},code:o})]}):(0,b.jsx)(y0,{node:e,components:{Pre:l,Code:d,SyntaxHighlighter:p,CodeHeader:m},language:f,code:o??``})},w0=({node:e,components:t,componentsByLanguage:n,...r})=>f0()?(0,b.jsx)(C0,{node:e,components:t,componentsByLanguage:n,...r}):(0,b.jsx)(t.Code,{...r}),T0=(e,t)=>{if(e===t)return!0;if(!e||!t)return!1;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n){if(!Object.hasOwn(t,r))return!1;let n=e[r],i=t[r];if(n!==i&&(!n||!i||n.SyntaxHighlighter!==i.SyntaxHighlighter||n.CodeHeader!==i.CodeHeader))return!1}return!0},E0=(0,y.memo)(w0,(e,t)=>e.components===t.components&&T0(e.componentsByLanguage,t.componentsByLanguage)&&l0(e,t)),{useSmooth:D0,useSmoothStatus:O0,withSmoothContextProvider:k0}=CQ,A0=(0,y.memo)(({text:e,overrideVersion:t,...n})=>(0,b.jsx)(jO,{...n,children:e}));A0.displayName=`MarkdownRenderer`;var j0=({text:e,...t})=>{let n=(0,y.useDeferredValue)(e);return(0,b.jsx)(A0,{text:n,...t})},M0=e=>typeof e==`object`&&!!e&&!Array.isArray(e),N0=(e,t,n=1)=>{if(Object.is(e,t))return!0;if(n<=0)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!N0(e[r],t[r],n-1))return!1;return!0}if(M0(e)&&M0(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(r=>Object.hasOwn(t,r)&&N0(e[r],t[r],n-1))}return!1};function P0(e,t){let n=(0,y.useRef)(e);return N0(e,n.current,t)||(n.current=e),n.current}function F0(e){let t=(0,y.useRef)(e),n=(e,t)=>e[t],r=Object.keys(e),i=Object.keys(t.current);return r.length===i.length&&r.every(r=>Object.hasOwn(t.current,r)&&N0(n(e,r),n(t.current,r)))||(t.current=e),t.current}var I0=({components:e,componentsByLanguage:t,smooth:n=!0,defer:r=!1,preprocess:i,...a})=>{let{text:o}=D0(HY(),n),s=(0,y.useMemo)(()=>i?i(o):o,[i,o]),{pre:c=m0,code:l=h0,SyntaxHighlighter:u=g0,CodeHeader:d=_0}=e??{},f=(0,y.useMemo)(()=>({Pre:c,Code:l,SyntaxHighlighter:u,CodeHeader:d}),[c,l,u,d]),p=dt(e=>(0,b.jsx)(E0,{components:f,componentsByLanguage:t,...e})),m=dt(e=>(0,b.jsx)(p0,{fallbackPre:c,...e})),h=F0((0,y.useMemo)(()=>{let{pre:t,code:n,SyntaxHighlighter:r,CodeHeader:i,...a}=e??{};return{...a,pre:m,code:p}},[p,m,e])),g=P0((0,y.useMemo)(()=>({components:f,componentsByLanguage:t}),[f,t]),3),_=r?j0:A0,v=F0(a);return(0,b.jsx)(_,{text:s,components:h,overrideVersion:g,...v})},L0=(0,y.forwardRef)(({className:e,containerProps:t,containerComponent:n=`div`,...r},i)=>{let a=O0();return(0,b.jsx)(n,{"data-status":a.type,...t,className:(0,b0.default)(e,t?.className),ref:i,children:(0,b.jsx)(I0,{...r})})});L0.displayName=`MarkdownTextPrimitive`;var R0=k0(L0),z0=({copiedDuration:e=3e3}={})=>{let[t,n]=(0,y.useState)(!1),r=(0,y.useRef)(void 0),i=(0,y.useRef)(0);return(0,y.useEffect)(()=>()=>{i.current+=1,r.current!==void 0&&(clearTimeout(r.current),r.current=void 0,n(!1))},[]),{isCopied:t,copyToClipboard:t=>{if(!t||typeof navigator>`u`||!navigator.clipboard)return;let a=i.current;navigator.clipboard.writeText(t).then(()=>{a===i.current&&(r.current!==void 0&&clearTimeout(r.current),n(!0),r.current=setTimeout(()=>{r.current=void 0,n(!1)},e))},()=>{})}}},B0=e=>{let t=(0,y.useRef)(e);if(e!==t.current){let n=t.current;e!==void 0&&n!==void 0&&Object.keys(n).length===Object.keys(e).length&&Object.keys(e).every(t=>n[t]===e[t])||(t.current=e)}return t.current},V0=(0,y.memo)(({components:e})=>{let t=B0(e),n=(0,y.useMemo)(()=>t?{...H0,...u0(t)}:H0,[t]);return(0,b.jsx)(R0,{remarkPlugins:[Fj],className:`aui-md`,components:n,defer:!0})}),H0=u0({h1:({className:e,...t})=>(0,b.jsx)(`h1`,{className:a(`aui-md-h1 mt-5 mb-2 scroll-m-20 text-xl font-semibold first:mt-0 last:mb-0`,e),...t}),h2:({className:e,...t})=>(0,b.jsx)(`h2`,{className:a(`aui-md-h2 mt-5 mb-2 scroll-m-20 text-lg font-semibold first:mt-0 last:mb-0`,e),...t}),h3:({className:e,...t})=>(0,b.jsx)(`h3`,{className:a(`aui-md-h3 mt-4 mb-1.5 scroll-m-20 text-base font-semibold first:mt-0 last:mb-0`,e),...t}),h4:({className:e,...t})=>(0,b.jsx)(`h4`,{className:a(`aui-md-h4 mt-3.5 mb-1 scroll-m-20 text-base font-medium first:mt-0 last:mb-0`,e),...t}),h5:({className:e,...t})=>(0,b.jsx)(`h5`,{className:a(`aui-md-h5 mt-3 mb-1 text-sm font-semibold first:mt-0 last:mb-0`,e),...t}),h6:({className:e,...t})=>(0,b.jsx)(`h6`,{className:a(`aui-md-h6 mt-3 mb-1 text-sm font-medium first:mt-0 last:mb-0`,e),...t}),p:({className:e,...t})=>(0,b.jsx)(`p`,{className:a(`aui-md-p my-3 leading-relaxed first:mt-0 last:mb-0`,e),...t}),a:({className:e,...t})=>(0,b.jsx)(`a`,{className:a(`aui-md-a text-primary hover:text-primary/80 underline underline-offset-2`,e),...t}),blockquote:({className:e,...t})=>(0,b.jsx)(`blockquote`,{className:a(`aui-md-blockquote border-muted-foreground/30 text-muted-foreground my-3 border-s-2 ps-4`,e),...t}),ul:({className:e,...t})=>(0,b.jsx)(`ul`,{className:a(`aui-md-ul marker:text-muted-foreground my-3 ms-5 list-disc [&>li]:mt-1`,e),...t}),ol:({className:e,...t})=>(0,b.jsx)(`ol`,{className:a(`aui-md-ol marker:text-muted-foreground my-3 ms-5 list-decimal [&>li]:mt-1`,e),...t}),hr:({className:e,...t})=>(0,b.jsx)(`hr`,{className:a(`aui-md-hr border-muted-foreground/20 my-3`,e),...t}),table:({className:e,...t})=>(0,b.jsx)(`div`,{className:`aui-md-table-wrapper my-3 overflow-x-auto`,children:(0,b.jsx)(`table`,{className:a(`aui-md-table w-full border-separate border-spacing-0`,e),...t})}),th:({className:e,...t})=>(0,b.jsx)(`th`,{className:a(`aui-md-th bg-muted px-3 py-1.5 text-start font-medium first:rounded-ss-lg last:rounded-se-lg [[align=center]]:text-center [[align=right]]:text-right`,e),...t}),td:({className:e,...t})=>(0,b.jsx)(`td`,{className:a(`aui-md-td border-muted-foreground/20 border-s border-b px-3 py-1.5 text-start last:border-e [[align=center]]:text-center [[align=right]]:text-right`,e),...t}),tr:({className:e,...t})=>(0,b.jsx)(`tr`,{className:a(`aui-md-tr m-0 border-b p-0 first:border-t [&:last-child>td:first-child]:rounded-es-lg [&:last-child>td:last-child]:rounded-ee-lg`,e),...t}),li:({className:e,...t})=>(0,b.jsx)(`li`,{className:a(`aui-md-li leading-relaxed`,e),...t}),strong:({className:e,...t})=>(0,b.jsx)(`strong`,{className:a(`aui-md-strong font-semibold`,e),...t}),sup:({className:e,...t})=>(0,b.jsx)(`sup`,{className:a(`aui-md-sup [&>a]:text-xs [&>a]:no-underline`,e),...t}),pre:({className:e,...t})=>(0,b.jsx)(`pre`,{className:a(`aui-md-pre border-border/50 bg-muted/30 overflow-x-auto rounded-t-none rounded-b-xl border border-t-0 p-3.5 text-[13px] leading-relaxed`,e),...t}),code:function({className:e,...t}){let n=f0();return(0,b.jsx)(`code`,{className:a(!n&&`aui-md-inline-code bg-muted rounded-md px-1.5 py-0.5 font-mono text-[0.85em]`,e),...t})},CodeHeader:({language:e,code:t})=>{let{isCopied:n,copyToClipboard:r}=z0();return(0,b.jsxs)(`div`,{className:`aui-code-header-root border-border/50 bg-muted/50 mt-3 flex items-center justify-between rounded-t-xl border border-b-0 px-3.5 py-1.5 text-xs`,children:[(0,b.jsx)(`span`,{className:`aui-code-header-language text-muted-foreground font-medium lowercase`,children:e}),(0,b.jsxs)(m1,{tooltip:`Copy`,onClick:()=>{t&&!n&&r(t)},children:[!n&&(0,b.jsx)(Mf,{className:`animate-in zoom-in-75 fade-in duration-150`}),n&&(0,b.jsx)(Sf,{className:`animate-in zoom-in-50 fade-in duration-200 ease-out`})]})]})}});function U0({...e}){return(0,b.jsx)(it,{"data-slot":`collapsible`,...e})}function W0({...e}){return(0,b.jsx)($e,{"data-slot":`collapsible-trigger`,...e})}function G0({...e}){return(0,b.jsx)(tt,{"data-slot":`collapsible-content`,...e})}var K0=(0,y.createContext)(!1),q0=v(`aui-reasoning-root mb-4 w-full`,{variants:{variant:{outline:`rounded-lg border px-3 py-2`,ghost:``,muted:`bg-muted/50 rounded-lg px-3 py-2`}},defaultVariants:{variant:`outline`}});function J0({className:e,variant:t,open:n,onOpenChange:r,defaultOpen:i=!1,streaming:o,onAnimationStart:s,children:c,...l}){let[u]=(0,y.useState)(i),[d,f]=(0,y.useState)(null),p=n!==void 0,m=p?n:d??(o||u),h=o===!0&&m,g=(0,y.useRef)(o);(0,y.useLayoutEffect)(()=>{g.current!==o&&(g.current=o,!p&&d===null&&!u&&s?.())},[o,p,d,u,s]);let _=(0,y.useCallback)(e=>{s?.(),p||f(e),r?.(e)},[s,p,r]);return(0,b.jsx)(U0,{"data-slot":`reasoning-root`,"data-variant":t,open:m,onOpenChange:_,className:a(`group/reasoning-root`,q0({variant:t,className:e})),style:{"--animation-duration":`200ms`},...l,children:(0,b.jsx)(K0.Provider,{value:h,children:c})})}function Y0({side:e=`bottom`,className:t,...n}){return e===`top`?(0,b.jsx)(`div`,{"data-slot":`reasoning-fade`,className:a(`aui-reasoning-fade pointer-events-none absolute inset-x-0 top-0 z-10 h-8`,`bg-[linear-gradient(to_bottom,var(--color-background),transparent)]`,`group-data-[variant=muted]/reasoning-root:bg-[linear-gradient(to_bottom,color-mix(in_oklab,var(--color-muted)_50%,var(--color-background)),transparent)]`,`fade-in-0 animate-in`,`animation-duration-(--animation-duration)`,t),...n}):(0,b.jsx)(`div`,{"data-slot":`reasoning-fade`,className:a(`aui-reasoning-fade pointer-events-none absolute inset-x-0 bottom-0 z-10 h-8`,`bg-[linear-gradient(to_top,var(--color-background),transparent)]`,`group-data-[variant=muted]/reasoning-root:bg-[linear-gradient(to_top,color-mix(in_oklab,var(--color-muted)_50%,var(--color-background)),transparent)]`,`fade-in-0 animate-in`,`animation-duration-(--animation-duration)`,t),...n})}function X0({active:e,duration:t,className:n,...r}){let i=t?` (${t}s)`:``;return(0,b.jsxs)(W0,{"data-slot":`reasoning-trigger`,className:a(`aui-reasoning-trigger group/trigger text-muted-foreground hover:text-foreground flex max-w-[75%] origin-left items-center gap-2 py-1.5 text-sm transition-[color,scale] active:scale-[0.98]`,n),...r,children:[(0,b.jsx)(xf,{"data-slot":`reasoning-trigger-icon`,className:`aui-reasoning-trigger-icon size-4 shrink-0`}),(0,b.jsxs)(`span`,{"data-slot":`reasoning-trigger-label`,className:a(`aui-reasoning-trigger-label-wrapper inline-block leading-none tabular-nums`,e&&`shimmer motion-reduce:animate-none`),children:[`Reasoning`,i]}),(0,b.jsx)(Cf,{"data-slot":`reasoning-trigger-chevron`,className:a(`aui-reasoning-trigger-chevron mt-0.5 size-4 shrink-0`,`transition-transform duration-(--animation-duration) ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none`,`-rotate-90`,`group-data-open/trigger:rotate-0`,`group-data-panel-open/trigger:rotate-0`)})]})}function Z0({className:e,children:t,...n}){let r=(0,y.useContext)(K0);return(0,b.jsxs)(G0,{"data-slot":`reasoning-content`,className:a(`aui-reasoning-content text-muted-foreground relative overflow-hidden text-sm outline-none`,`group/collapsible-content ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none`,`data-closed:animate-collapsible-up`,`data-open:animate-collapsible-down`,`data-closed:fill-mode-forwards`,`data-closed:pointer-events-none`,`[--tw-duration:var(--animation-duration)]`,e),...n,children:[(0,b.jsx)(Y0,{side:`top`}),t,r?(0,b.jsx)(Y0,{}):null]})}function Q0({className:e,children:t,...n}){let r=(0,y.useContext)(K0),i=(0,y.useRef)(null),o=(0,y.useRef)(null);return(0,y.useEffect)(()=>{if(!r)return;let e=i.current,t=o.current;if(!e||!t)return;let n=!0,a=e.scrollTop,s=e.scrollHeight,c=()=>Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight)<=1||e.scrollHeight<=e.clientHeight,l=()=>{n&&(e.scrollTop=e.scrollHeight)},u=()=>{c()?n=!0:e.scrollTop<a&&e.scrollHeight===s&&(n=!1),a=e.scrollTop,s=e.scrollHeight};l(),e.addEventListener(`scroll`,u);let d=new ResizeObserver(l);return d.observe(t),()=>{e.removeEventListener(`scroll`,u),d.disconnect()}},[r]),(0,b.jsx)(`div`,{ref:i,"data-slot":`reasoning-text`,className:a(`aui-reasoning-text relative z-0 max-h-64 overflow-y-auto ps-6 pt-2 pb-2 leading-relaxed text-pretty`,`transform-gpu transition-[transform,opacity] ease-[cubic-bezier(0.32,0.72,0,1)]`,`motion-reduce:animate-none`,`group-data-open/collapsible-content:animate-in`,`group-data-closed/collapsible-content:animate-out`,`group-data-open/collapsible-content:fade-in-0`,`group-data-closed/collapsible-content:fade-out-0`,`group-data-open/collapsible-content:slide-in-from-top-4`,`group-data-closed/collapsible-content:slide-out-to-top-4`,`group-data-open/collapsible-content:blur-in-[2px]`,`group-data-closed/collapsible-content:blur-out-[2px]`,`group-data-open/collapsible-content:animation-duration-(--animation-duration)`,`group-data-closed/collapsible-content:animation-duration-(--animation-duration)`,e),...n,children:(0,b.jsx)(`div`,{ref:o,className:`aui-reasoning-text-content space-y-4`,children:t})})}function $0({ref:e,onAnimationStart:t,...n}){let r=(0,y.useRef)(null),i=vQ(r,200),a=(0,y.useCallback)(()=>{i(),t?.()},[i,t]),o=(0,y.useCallback)(t=>{r.current=t,typeof e==`function`?e(t):e&&(e.current=t)},[e]);return(0,b.jsx)(J0,{ref:o,onAnimationStart:a,...n})}var e2=()=>(0,b.jsx)(V0,{}),t2=({children:e,startIndex:t,endIndex:n})=>{let r=$(e=>{if(e.message.status?.type!==`running`)return!1;for(let r=t;r<=n;r++)if(e.message.parts[r]?.status.type===`running`)return!0;return!1});return(0,b.jsxs)($0,{streaming:r,children:[(0,b.jsx)(X0,{active:r}),(0,b.jsx)(Z0,{"aria-busy":r,children:(0,b.jsx)(Q0,{children:e})})]})},n2=(0,y.memo)(e2);n2.displayName=`Reasoning`,n2.Root=$0,n2.Trigger=X0,n2.Content=Z0,n2.Text=Q0,n2.Fade=Y0;var r2=(0,y.memo)(t2);r2.displayName=`ReasoningGroup`;function i2({className:e,...t}){return(0,b.jsx)(`textarea`,{"data-slot":`textarea`,className:a(`flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40`,e),...t})}var a2=200,o2=`active:scale-[0.98]`;function s2({className:e,open:t,onOpenChange:n,defaultOpen:r=!1,children:i,...o}){let s=(0,y.useRef)(null),[c,l]=(0,y.useState)(r),u=vQ(s,a2),d=t!==void 0,f=d?t:c,p=(0,y.useCallback)(e=>{u(),d||l(e),n?.(e)},[u,d,n]);return(0,b.jsx)(U0,{ref:s,"data-slot":`tool-fallback-root`,open:f,onOpenChange:p,className:a(`aui-tool-fallback-root group/tool-fallback-root w-full`,e),style:{"--animation-duration":`${a2}ms`},...o,children:i})}var c2={running:Wf,complete:Sf,incomplete:Of,"requires-action":Ef},l2=e=>{if(e<1e3)return`<1s`;let t=e/1e3;return t<10?`${(Math.floor(t*10)/10).toFixed(1)}s`:t<60?`${Math.floor(t)}s`:`${Math.floor(t/60)}m ${Math.floor(t%60)}s`};function u2({className:e,...t}){let n=yQ();return n===void 0?null:(0,b.jsx)(`span`,{"data-slot":`tool-fallback-duration`,className:a(`aui-tool-fallback-duration text-muted-foreground text-xs tabular-nums`,e),...t,children:l2(n)})}function d2({toolName:e,status:t,className:n,...r}){let i=t?.type??`complete`,o=i===`running`,s=t?.type===`incomplete`&&t.reason===`cancelled`,c=c2[i],l=s?`Cancelled tool`:`Used tool`;return(0,b.jsxs)(W0,{"data-slot":`tool-fallback-trigger`,className:a(`aui-tool-fallback-trigger group/trigger text-muted-foreground hover:text-foreground flex w-fit origin-left items-center gap-2 py-1.5 text-sm transition-[color,scale] active:scale-[0.98]`,n),...r,children:[(0,b.jsx)(c,{"data-slot":`tool-fallback-trigger-icon`,className:a(`aui-tool-fallback-trigger-icon size-4 shrink-0`,s&&`text-muted-foreground`,o&&`animate-spin [animation-duration:0.6s]`)}),(0,b.jsxs)(`span`,{"data-slot":`tool-fallback-trigger-label`,className:a(`aui-tool-fallback-trigger-label-wrapper inline-block text-start leading-none`,s&&`text-muted-foreground line-through`,o&&`shimmer motion-reduce:animate-none`),children:[l,`: `,(0,b.jsx)(`b`,{children:e})]}),(0,b.jsx)(u2,{}),(0,b.jsx)(Cf,{"data-slot":`tool-fallback-trigger-chevron`,className:a(`aui-tool-fallback-trigger-chevron size-4 shrink-0`,`transition-transform duration-(--animation-duration) ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none`,`-rotate-90`,`group-data-open/trigger:rotate-0`,`group-data-panel-open/trigger:rotate-0`)})]})}function f2({className:e,children:t,...n}){return(0,b.jsx)(G0,{"data-slot":`tool-fallback-content`,className:a(`aui-tool-fallback-content relative overflow-hidden text-sm outline-none`,`group/collapsible-content ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none`,`data-closed:animate-collapsible-up`,`data-open:animate-collapsible-down`,`data-closed:fill-mode-forwards`,`data-closed:pointer-events-none`,`[--tw-duration:var(--animation-duration)]`,e),...n,children:(0,b.jsx)(`div`,{className:a(`flex flex-col gap-2 ps-6 pt-1 pb-2 ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none`,`group-data-open/collapsible-content:animate-in group-data-open/collapsible-content:fade-in-0 group-data-open/collapsible-content:blur-in-[2px] group-data-open/collapsible-content:slide-in-from-top-1`,`group-data-closed/collapsible-content:animate-out group-data-closed/collapsible-content:fade-out-0 group-data-closed/collapsible-content:blur-out-[2px] group-data-closed/collapsible-content:slide-out-to-top-1`,`group-data-closed/collapsible-content:animation-duration-(--animation-duration) group-data-open/collapsible-content:animation-duration-(--animation-duration)`),children:t})})}function p2({argsText:e,className:t,...n}){return e?(0,b.jsx)(`div`,{"data-slot":`tool-fallback-args`,className:a(`aui-tool-fallback-args`,t),...n,children:(0,b.jsx)(`pre`,{className:`aui-tool-fallback-args-value bg-muted/50 text-foreground/90 rounded-md p-2.5 text-xs whitespace-pre-wrap`,children:e})}):null}var m2=(e,t)=>{if(typeof e==`string`)return e;try{if(e instanceof Error)return String(e);let n=JSON.stringify(e,null,t);if(n!==void 0)return n}catch{}try{return String(e)}catch{return`[Unserializable value]`}};function h2({result:e,className:t,...n}){return e===void 0?null:(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-result`,className:a(`aui-tool-fallback-result`,t),...n,children:[(0,b.jsx)(`p`,{className:`aui-tool-fallback-result-header text-muted-foreground text-xs font-medium`,children:`Result:`}),(0,b.jsx)(`pre`,{className:`aui-tool-fallback-result-content bg-muted/50 text-foreground/90 mt-1 rounded-md p-2.5 text-xs whitespace-pre-wrap`,children:m2(e,2)})]})}function g2({status:e,className:t,...n}){if(e?.type!==`incomplete`)return null;let r=e.error,i=r==null?null:m2(r);if(!i)return null;let o=e.reason===`cancelled`?`Cancelled reason:`:`Error:`;return(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-error`,className:a(`aui-tool-fallback-error`,t),...n,children:[(0,b.jsx)(`p`,{className:`aui-tool-fallback-error-header text-muted-foreground font-semibold`,children:o}),(0,b.jsx)(`p`,{className:`aui-tool-fallback-error-reason text-muted-foreground whitespace-pre-line`,children:i})]})}var _2=`Approved by user`,v2=`User denied tool execution`,y2={"allow-once":`Allow`,"allow-always":`Always allow`,"reject-once":`Deny`,"reject-always":`Always deny`},b2=e=>Object.hasOwn(y2,e),x2=e=>e===`allow-once`||e===`allow-always`,S2=e=>e.label??(b2(e.kind)?y2[e.kind]:void 0)??e.id,C2=e=>e?.display===`select`||e?.display===`text`,w2=(e,t,n)=>e?.type!==`requires-action`||e.reason!==`interrupt`||t!=null||n!=null;function T2({className:e,addResult:t,resume:n,interrupt:r,approval:i,respondToApproval:s,status:c,...l}){let[u,d]=(0,y.useState)(!1),f=$(e=>e.thread.voice!==void 0),p=u||f,[m,h]=(0,y.useState)(null),[g,_]=(0,y.useState)(``),[v,x]=(0,y.useState)(null);if(i!=null&&(i.approved!==void 0||i.resolution!==void 0)||!w2(c,i,r))return null;let S=s?i?.options:void 0,C=i!=null&&s!=null&&kV(i),w=e=>{d(!0),x(null),(async()=>{try{await e()}catch(e){d(!1),x(e instanceof Error?e.message:String(e))}})()},T=e=>{if(!p){if(i!=null&&i.approved===void 0&&s)w(()=>s({approved:e,...D()}));else if(r)w(()=>n?.({approved:e}));else if(c?.type===`requires-action`&&c.reason===`interrupt`)return;else w(()=>t?.(e?_2:v2))}},E=e=>{p||(h(null),w(()=>s?.(b2(e.kind)?{optionId:e.id,...D()}:{optionId:e.id,approved:!0,...D()})))},D=()=>g.trim()?{text:g}:{},O=()=>{p||w(()=>s?.({text:g}))},k=()=>{p||w(()=>s?.({approved:!1}))},A=e=>{e.confirm?h(e.id):E(e)},j=m==null?void 0:S?.find(e=>e.id===m),M=C2(i),N=M&&s!=null&&i?.dismissible===!0?(0,b.jsx)(o,{size:`sm`,variant:`outline`,className:o2,onClick:k,disabled:p,children:`Dismiss`}):null,ee=i?.prompt?(0,b.jsx)(`p`,{className:`aui-tool-fallback-approval-prompt text-foreground whitespace-pre-line`,children:i.prompt}):null,te=v?(0,b.jsx)(`p`,{role:`alert`,className:`aui-tool-fallback-approval-error text-destructive text-xs whitespace-pre-line`,children:v}):null,ne=C?(0,b.jsxs)(`div`,{className:`aui-tool-fallback-approval-answer flex flex-col items-start gap-2`,children:[(0,b.jsx)(i2,{value:g,onChange:e=>_(e.target.value),disabled:p,"aria-label":M?i?.prompt??`Answer`:`Note`,placeholder:M?`Type your answer`:`Add a note to your decision`}),M&&(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsx)(o,{size:`sm`,className:o2,onClick:O,disabled:p,children:`Send`}),N]})]}):null;if(j){let t=typeof j.confirm==`object`?j.confirm:void 0,n=t?.description??j.description;return(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-approval-confirm`,className:a(`aui-tool-fallback-approval-confirm flex flex-col gap-2 pt-1`,e),...l,children:[(0,b.jsx)(`p`,{className:`aui-tool-fallback-approval-confirm-title font-semibold`,children:t?.title??`${S2(j)}?`}),n&&(0,b.jsx)(`p`,{className:`aui-tool-fallback-approval-confirm-description text-muted-foreground whitespace-pre-line`,children:n}),j.grants&&j.grants.length>0&&(0,b.jsx)(`ul`,{className:`aui-tool-fallback-approval-confirm-grants flex flex-col gap-1`,children:j.grants.map(e=>(0,b.jsx)(`li`,{children:(0,b.jsx)(`code`,{className:`aui-tool-fallback-approval-confirm-grant bg-muted rounded px-1.5 py-0.5 text-xs`,children:e})},e))}),(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsx)(o,{size:`sm`,className:o2,onClick:()=>E(j),disabled:p,children:`Confirm`}),(0,b.jsx)(o,{size:`sm`,variant:`outline`,className:o2,onClick:()=>h(null),disabled:p,children:`Back`})]})]})}if(S&&S.length>0){let t=S.filter(e=>x2(e.kind)),n=S.filter(e=>!b2(e.kind)),r=S.filter(e=>b2(e.kind)&&!x2(e.kind));return(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-approval`,className:a(`aui-tool-fallback-approval flex flex-col gap-2 pt-1`,e),...l,children:[ee,(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[[...t,...n,...r].map(e=>(0,b.jsx)(o,{size:`sm`,variant:e===t[0]?`default`:`outline`,className:o2,onClick:()=>A(e),disabled:p,children:S2(e)},e.id)),r.length===0&&!M&&(0,b.jsx)(o,{size:`sm`,variant:`outline`,className:o2,onClick:()=>T(!1),disabled:p,children:`Deny`}),!C&&N]}),ne,te]})}return M?(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-approval`,className:a(`aui-tool-fallback-approval flex flex-col gap-2 pt-1`,e),...l,children:[ee,ne,!C&&N&&(0,b.jsx)(`div`,{className:`flex items-center gap-2`,children:N}),te]}):(0,b.jsxs)(`div`,{"data-slot":`tool-fallback-approval`,className:a(`aui-tool-fallback-approval flex flex-col gap-2 pt-1`,e),...l,children:[ee,(0,b.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,b.jsx)(o,{size:`sm`,className:o2,onClick:()=>T(!0),disabled:p,children:`Allow`}),(0,b.jsx)(o,{size:`sm`,variant:`outline`,className:o2,onClick:()=>T(!1),disabled:p,children:`Deny`})]}),ne,te]})}var E2=(0,y.memo)(({toolName:e,argsText:t,result:n,status:r,addResult:i,resume:o,interrupt:s,approval:c,respondToApproval:l})=>{let u=r?.type===`incomplete`&&r.reason===`cancelled`,d=r?.type===`requires-action`,f=d&&w2(r,c,s),[p,m]=(0,y.useState)(d),[h,g]=(0,y.useState)(d);return d!==h&&(g(d),d&&m(!0)),(0,b.jsxs)(s2,{open:p,onOpenChange:m,children:[(0,b.jsx)(d2,{toolName:e,status:r}),(0,b.jsxs)(f2,{children:[(0,b.jsx)(g2,{status:r}),(0,b.jsx)(p2,{argsText:t,className:a(u&&`opacity-60`)}),f&&(0,b.jsx)(T2,{addResult:i,resume:o,interrupt:s,approval:c,respondToApproval:l,status:r}),(0,b.jsx)(h2,{result:n})]})]})});E2.displayName=`ToolFallback`,E2.Root=s2,E2.Trigger=d2,E2.Content=f2,E2.Args=p2,E2.Result=h2,E2.Error=g2,E2.Approval=T2;var D2=200,O2=v(`aui-tool-group-root group/tool-group w-full`,{variants:{variant:{outline:`rounded-lg border py-3`,ghost:``,muted:`border-muted-foreground/30 bg-muted/30 rounded-lg border py-3`}},defaultVariants:{variant:`outline`}});function k2({className:e,variant:t,open:n,onOpenChange:r,defaultOpen:i=!1,children:o,...s}){let c=(0,y.useRef)(null),[l,u]=(0,y.useState)(i),d=vQ(c,D2),f=n!==void 0,p=f?n:l,m=(0,y.useCallback)(e=>{d(),f||u(e),r?.(e)},[d,f,r]);return(0,b.jsx)(U0,{ref:c,"data-slot":`tool-group-root`,"data-variant":t??`outline`,open:p,onOpenChange:m,className:a(O2({variant:t}),`group/tool-group-root`,e),style:{"--animation-duration":`${D2}ms`},...s,children:o})}function A2({count:e,active:t=!1,className:n,...r}){let i=`${e} tool ${e===1?`call`:`calls`}`;return(0,b.jsxs)(W0,{"data-slot":`tool-group-trigger`,className:a(`aui-tool-group-trigger group/trigger flex origin-left items-center gap-2 text-sm transition-[color,scale] active:scale-[0.98]`,`group-data-[variant=ghost]/tool-group-root:text-muted-foreground group-data-[variant=ghost]/tool-group-root:hover:text-foreground group-data-[variant=ghost]/tool-group-root:py-1.5`,`group-data-[variant=outline]/tool-group-root:w-full group-data-[variant=outline]/tool-group-root:px-4`,`group-data-[variant=muted]/tool-group-root:w-full group-data-[variant=muted]/tool-group-root:px-4`,n),...r,children:[t&&(0,b.jsx)(Wf,{"data-slot":`tool-group-trigger-loader`,className:`aui-tool-group-trigger-loader size-3 shrink-0 animate-spin [animation-duration:0.6s]`}),(0,b.jsx)(`span`,{"data-slot":`tool-group-trigger-label`,className:a(`aui-tool-group-trigger-label-wrapper inline-block text-start text-xs leading-none font-medium`,`group-data-[variant=ghost]/tool-group-root:font-normal`,`group-data-[variant=outline]/tool-group-root:grow`,`group-data-[variant=muted]/tool-group-root:grow`,t&&`shimmer motion-reduce:animate-none`),children:i}),(0,b.jsx)(Cf,{"data-slot":`tool-group-trigger-chevron`,className:a(`aui-tool-group-trigger-chevron size-3 shrink-0`,`transition-transform duration-(--animation-duration) ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none`,`-rotate-90`,`group-data-open/trigger:rotate-0`,`group-data-panel-open/trigger:rotate-0`)})]})}function j2({className:e,children:t,...n}){return(0,b.jsx)(G0,{"data-slot":`tool-group-content`,className:a(`aui-tool-group-content relative overflow-hidden text-sm outline-none`,`group/collapsible-content ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none`,`data-closed:animate-collapsible-up`,`data-open:animate-collapsible-down`,`data-closed:fill-mode-forwards`,`data-closed:pointer-events-none`,`[--tw-duration:var(--animation-duration)]`,e),...n,children:(0,b.jsx)(`div`,{className:a(`mt-2 flex flex-col gap-2`,`group-data-[variant=ghost]/tool-group-root:mt-1 group-data-[variant=ghost]/tool-group-root:gap-1`,`group-data-[variant=outline]/tool-group-root:mt-3 group-data-[variant=outline]/tool-group-root:border-t group-data-[variant=outline]/tool-group-root:px-4 group-data-[variant=outline]/tool-group-root:pt-3`,`group-data-[variant=muted]/tool-group-root:mt-3 group-data-[variant=muted]/tool-group-root:border-t group-data-[variant=muted]/tool-group-root:px-4 group-data-[variant=muted]/tool-group-root:pt-3`,`[&>*]:animate-in [&>*]:fade-in-0 [&>*]:blur-in-[2px] [&>*]:slide-in-from-top-1 [&>*]:animation-duration-(--animation-duration) [&>*]:ease-[cubic-bezier(0.32,0.72,0,1)]`,`[&>*]:motion-reduce:animate-none`,`[&>*:nth-child(2)]:[animation-delay:40ms]`,`[&>*:nth-child(3)]:[animation-delay:80ms]`,`[&>*:nth-child(4)]:[animation-delay:120ms]`,`[&>*:nth-child(n+5)]:[animation-delay:160ms]`),children:t})})}var M2=(0,y.memo)(({children:e,startIndex:t,endIndex:n})=>{let r=n-t+1;return(0,b.jsxs)(k2,{children:[(0,b.jsx)(A2,{count:r}),(0,b.jsx)(j2,{children:e})]})});M2.displayName=`ToolGroup`,M2.Root=k2,M2.Trigger=A2,M2.Content=j2;function N2({className:e,...t}){return(0,b.jsx)(`div`,{"data-slot":`skeleton`,className:a(`animate-pulse rounded-md bg-accent`,e),...t})}var P2=RW({reasoning:[`group-chainOfThought`,`group-reasoning`],"tool-call":[`group-chainOfThought`,`group-tool`],"standalone-tool-call":[]}),F2=[`group-chainOfThought`,`group-task`],I2=(e,t)=>{let n=P2(e,t);return e.type===`tool-call`&&e.messages!==void 0&&n.length>0&&!t?.toolUIs?.[e.toolName]?.length?F2:n},L2={},R2=(0,y.createContext)(L2),z2=e=>e.thread.messages.length===0&&(!e.thread.isLoading||e.threads.isLoading),B2=e=>e.thread.messages.length===0&&e.thread.isLoading&&!e.thread.isDisabled&&!e.threads.isLoading,V2=()=>(0,b.jsxs)(`div`,{"data-slot":`aui_thread-history-skeleton`,role:`status`,className:`animate-in fade-in fill-mode-both flex flex-col gap-y-6 [animation-delay:150ms] [animation-duration:200ms]`,children:[(0,b.jsx)(`span`,{className:`sr-only`,children:`Loading conversation`}),(0,b.jsx)(N2,{className:`ml-auto h-9 w-2/5 rounded-xl motion-reduce:animate-none`}),(0,b.jsxs)(`div`,{className:`flex flex-col gap-y-2`,children:[(0,b.jsx)(N2,{className:`h-4 w-11/12 motion-reduce:animate-none`}),(0,b.jsx)(N2,{className:`h-4 w-4/5 motion-reduce:animate-none`}),(0,b.jsx)(N2,{className:`h-4 w-3/5 motion-reduce:animate-none`})]}),(0,b.jsx)(N2,{className:`ml-auto h-9 w-1/3 rounded-xl motion-reduce:animate-none`}),(0,b.jsxs)(`div`,{className:`flex flex-col gap-y-2`,children:[(0,b.jsx)(N2,{className:`h-4 w-10/12 motion-reduce:animate-none`}),(0,b.jsx)(N2,{className:`h-4 w-2/3 motion-reduce:animate-none`})]})]}),H2=({components:e=L2,autoFocus:t=!0})=>{let n=$(z2);return(0,b.jsx)(R2.Provider,{value:e,children:(0,b.jsx)(U2,{isEmpty:n,autoFocus:t})})},U2=({isEmpty:e,autoFocus:t})=>{let{Welcome:n=X2}=(0,y.useContext)(R2);return(0,b.jsx)(FZ.Root,{className:`aui-root aui-thread-root bg-background @container flex h-full flex-col`,style:{"--thread-max-width":`44rem`,"--composer-bg":`color-mix(in oklab, var(--color-muted) 30%, transparent)`,"--composer-radius":`var(--radius-2xl)`,"--composer-padding":`8px`},children:(0,b.jsx)(FZ.Viewport,{turnAnchor:`top`,"data-slot":`aui_thread-viewport`,className:`relative flex flex-1 flex-col overflow-x-auto overflow-y-scroll scroll-smooth`,children:(0,b.jsxs)(`div`,{className:a(`mx-auto flex w-full max-w-(--thread-max-width) flex-1 flex-col px-4 pt-4`,e&&`justify-center`),children:[(0,b.jsx)(LL,{condition:z2,children:(0,b.jsx)(n,{})}),(0,b.jsx)(LL,{condition:B2,children:(0,b.jsx)(V2,{})}),(0,b.jsx)(`div`,{"data-slot":`aui_message-group`,className:`mb-14 flex flex-col gap-y-6 empty:hidden`,children:(0,b.jsx)(FZ.Messages,{children:()=>(0,b.jsx)(W2,{})})}),(0,b.jsxs)(FZ.ViewportFooter,{className:a(`aui-thread-viewport-footer bg-background flex flex-col gap-4 overflow-visible pb-4 md:pb-6`,!e&&`sticky bottom-0 mt-auto rounded-t-(--composer-radius)`),children:[(0,b.jsx)(Y2,{}),(0,b.jsx)(G1,{}),(0,b.jsx)($2,{autoFocus:t}),(0,b.jsx)(LL,{condition:e=>z2(e)&&e.composer.isEmpty,children:(0,b.jsx)(Z2,{})})]})]})})})},W2=()=>{let{AssistantMessage:e=n4}=(0,y.useContext)(R2),t=$(e=>e.message.role),n=$(e=>e.message.composer.isEditing),r=$(e=>e.message.metadata.modality===`voice`);return n?(0,b.jsx)(c4,{}):r?(0,b.jsx)(q2,{}):t===`user`?(0,b.jsx)(o4,{}):(0,b.jsx)(e,{})},G2=()=>$(e=>{let t=e.thread.messages[e.message.index-1]?.metadata.modality===`voice`,n=e.thread.messages[e.message.index+1]?.metadata.modality===`voice`;return t?n?`middle`:`end`:n?`start`:`single`}),K2=({text:e})=>(0,b.jsx)(`p`,{className:`aui-spoken-message-text m-0`,children:e}),q2=()=>{let e=$(e=>e.message.role),t=G2(),n=$(e=>e.message.role===`assistant`&&e.message.status?.type===`running`),r=t===`start`||t===`single`;return(0,b.jsxs)(ZX.Root,{"data-slot":`aui_spoken-message-root`,"data-role":e,"data-voice-run":t,className:a(`aui-spoken-message bg-muted/40 mx-2 px-3 py-1.5 [contain-intrinsic-size:auto_48px] [content-visibility:auto]`,t===`single`&&`rounded-xl py-2`,t===`start`&&`rounded-t-xl pt-2`,t===`middle`&&`-mt-6`,t===`end`&&`-mt-6 rounded-b-xl pb-2`),children:[r&&(0,b.jsxs)(`div`,{"data-slot":`aui_spoken-exchange-header`,className:`text-muted-foreground mb-1.5 flex items-center gap-1.5 text-xs`,children:[(0,b.jsx)(Yf,{className:`size-3`,"aria-hidden":!0}),(0,b.jsx)(`span`,{children:`Voice conversation`})]}),(0,b.jsxs)(`div`,{"data-slot":`aui_spoken-message-content`,className:`text-foreground flex items-start gap-2 text-sm leading-relaxed`,children:[(0,b.jsx)(`span`,{className:`text-muted-foreground mt-1 shrink-0`,"aria-hidden":!0,children:e===`user`?(0,b.jsx)(Gf,{className:`size-3.5`}):(0,b.jsx)(yf,{className:`size-3.5`})}),(0,b.jsx)(`span`,{className:`sr-only`,children:e===`user`?`You said`:`Assistant said`}),(0,b.jsxs)(`div`,{className:`min-w-0 flex-1 wrap-break-word`,children:[(0,b.jsx)(ZX.Parts,{components:{Text:K2}}),n&&(0,b.jsx)(`span`,{"data-slot":`aui_spoken-message-indicator`,role:`status`,className:`text-muted-foreground ms-1 animate-pulse font-sans`,"aria-label":`Assistant is speaking`,children:`●`})]}),(0,b.jsx)(J2,{})]})]})},J2=()=>(0,b.jsx)(gq.Root,{hideWhenRunning:!0,autohide:`always`,className:`aui-spoken-action-bar text-muted-foreground flex shrink-0 gap-1`,children:(0,b.jsx)(gq.Copy,{asChild:!0,children:(0,b.jsxs)(m1,{tooltip:`Copy`,className:`size-6`,children:[(0,b.jsx)(LL,{condition:e=>e.message.isCopied,children:(0,b.jsx)(Sf,{className:`animate-in zoom-in-50 fade-in duration-200 ease-out`})}),(0,b.jsx)(LL,{condition:e=>!e.message.isCopied,children:(0,b.jsx)(Mf,{className:`animate-in zoom-in-75 fade-in duration-150`})})]})})}),Y2=()=>(0,b.jsx)(FZ.ScrollToBottom,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Scroll to bottom`,variant:`outline`,className:`aui-thread-scroll-to-bottom dark:border-border dark:bg-background dark:hover:bg-accent absolute -top-12 z-10 self-center rounded-full p-4 disabled:invisible`,children:(0,b.jsx)(hf,{})})}),X2=()=>(0,b.jsx)(`div`,{className:`aui-thread-welcome-root mb-6 flex flex-col px-2`,children:(0,b.jsx)(`p`,{className:`aui-thread-welcome-message-inner fade-in slide-in-from-bottom-1 animate-in fill-mode-both text-2xl font-medium tracking-tight duration-200`,children:`How can I help you today?`})}),Z2=()=>(0,b.jsx)(`div`,{className:`aui-thread-welcome-suggestions flex w-full flex-col`,children:(0,b.jsx)(FZ.Suggestions,{children:()=>(0,b.jsx)(Q2,{})})}),Q2=()=>(0,b.jsx)(`div`,{className:`aui-thread-welcome-suggestion-display fade-in slide-in-from-bottom-2 animate-in fill-mode-both duration-200`,children:(0,b.jsx)(HZ.Trigger,{send:!0,asChild:!0,children:(0,b.jsxs)(`button`,{type:`button`,className:`aui-thread-welcome-suggestion group hover:bg-foreground/[0.03] focus-visible:ring-ring/50 flex w-full items-baseline gap-2.5 rounded-md px-2 py-2 text-start text-sm transition-colors outline-none focus-visible:ring-1 motion-reduce:transition-none`,children:[(0,b.jsx)(`span`,{"aria-hidden":!0,className:`text-muted-foreground/60 group-hover:text-foreground font-mono text-xs transition-colors motion-reduce:transition-none`,children:`>`}),(0,b.jsxs)(`span`,{className:`min-w-0 flex-1 truncate`,children:[(0,b.jsx)(HZ.Title,{className:`aui-thread-welcome-suggestion-text-1 text-foreground`}),` `,(0,b.jsx)(HZ.Description,{className:`aui-thread-welcome-suggestion-text-2 text-muted-foreground empty:hidden`})]})]})})}),$2=({autoFocus:e})=>(0,b.jsx)(zY.Root,{className:`aui-composer-root relative flex w-full flex-col`,children:(0,b.jsx)(zY.AttachmentDropzone,{asChild:!0,children:(0,b.jsxs)(`div`,{"data-slot":`aui_composer-shell`,className:`border-foreground/10 focus-within:border-foreground/25 data-[dragging=true]:border-ring flex w-full cursor-text flex-col gap-2 rounded-(--composer-radius) border bg-(--composer-bg) p-(--composer-padding) transition-[border-color] data-[dragging=true]:border-dashed data-[dragging=true]:bg-[color-mix(in_oklab,var(--color-accent)_50%,var(--color-background))]`,children:[(0,b.jsx)(k1,{}),(0,b.jsx)(zY.Input,{placeholder:`Send a message...`,className:`aui-composer-input caret-primary placeholder:text-muted-foreground/60 max-h-48 min-h-10 w-full resize-none bg-transparent px-2.5 py-1 text-base leading-6 outline-none`,rows:1,autoFocus:e,enterKeyHint:`send`,"aria-label":`Message input`}),(0,b.jsx)(e4,{})]})})}),e4=()=>(0,b.jsxs)(`div`,{className:`aui-composer-action-wrapper relative flex items-center justify-between`,children:[(0,b.jsx)(A1,{}),(0,b.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,b.jsxs)(LL,{condition:e=>e.thread.capabilities.dictation,children:[(0,b.jsx)(LL,{condition:e=>e.composer.dictation==null,children:(0,b.jsx)(zY.Dictate,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Voice input`,side:`bottom`,type:`button`,variant:`ghost`,size:`icon`,className:`aui-composer-dictate text-muted-foreground hover:text-foreground size-7 rounded-full`,"aria-label":`Start voice input`,children:(0,b.jsx)(Gf,{className:`aui-composer-dictate-icon size-4`})})})}),(0,b.jsx)(LL,{condition:e=>e.composer.dictation!=null,children:(0,b.jsx)(zY.StopDictation,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Stop dictation`,side:`bottom`,type:`button`,variant:`ghost`,size:`icon`,className:`aui-composer-stop-dictation text-destructive size-7 rounded-full`,"aria-label":`Stop voice input`,children:(0,b.jsx)(ip,{className:`aui-composer-stop-dictation-icon size-3.5 animate-pulse fill-current`})})})})]}),(0,b.jsx)(LL,{condition:e=>!e.thread.isRunning||e.thread.voice!==void 0,children:(0,b.jsx)(zY.Send,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Send message`,side:`bottom`,type:`button`,variant:`default`,size:`icon`,className:`aui-composer-send size-7 rounded-full`,"aria-label":`Send message`,children:(0,b.jsx)(vf,{className:`aui-composer-send-icon size-4`})})})}),(0,b.jsx)(LL,{condition:e=>e.thread.isRunning&&e.thread.voice===void 0,children:(0,b.jsx)(zY.Cancel,{asChild:!0,children:(0,b.jsx)(o,{type:`button`,variant:`default`,size:`icon`,className:`aui-composer-cancel size-7 rounded-full`,"aria-label":`Stop generating`,children:(0,b.jsx)(ip,{className:`aui-composer-cancel-icon size-3.5 fill-current`})})})})]})]}),t4=()=>(0,b.jsx)(ZX.Error,{children:(0,b.jsx)(dX.Root,{className:`aui-message-error-root border-destructive bg-destructive/10 text-destructive dark:bg-destructive/5 mt-2 rounded-md border p-3 text-sm dark:text-red-200`,children:(0,b.jsx)(dX.Message,{className:`aui-message-error-message line-clamp-2`})})}),n4=()=>{let{ToolFallback:e=E2,ToolGroup:t,ReasoningGroup:n,TaskGroup:r}=(0,y.useContext)(R2),i=r?I2:P2;return(0,b.jsxs)(ZX.Root,{"data-slot":`aui_assistant-message-root`,"data-role":`assistant`,className:`fade-in slide-in-from-bottom-1 animate-in relative -mb-7.5 pb-7.5 duration-150 [contain-intrinsic-size:auto_200px] [content-visibility:auto]`,children:[(0,b.jsxs)(`div`,{"data-slot":`aui_assistant-message-content`,className:`text-foreground px-2 leading-relaxed wrap-break-word`,children:[(0,b.jsx)(ZX.GroupedParts,{groupBy:i,children:({part:i,children:a})=>{switch(i.type){case`group-chainOfThought`:return(0,b.jsx)(`div`,{"data-slot":`aui_chain-of-thought`,children:a});case`group-task`:return r?(0,b.jsx)(r,{group:i}):null;case`group-tool`:return t?(0,b.jsx)(t,{group:i,children:a}):(0,b.jsxs)(k2,{variant:`ghost`,children:[(0,b.jsx)(A2,{count:i.indices.length,active:i.status.type===`running`}),(0,b.jsx)(j2,{children:a})]});case`group-reasoning`:{if(n)return(0,b.jsx)(n,{group:i,children:a});let e=i.status.type===`running`;return(0,b.jsxs)($0,{streaming:e,children:[(0,b.jsx)(X0,{active:e}),(0,b.jsx)(Z0,{"aria-busy":e,children:(0,b.jsx)(Q0,{children:a})})]})}case`text`:return(0,b.jsx)(V0,{});case`reasoning`:return(0,b.jsx)(n2,{...i});case`tool-call`:return i.toolUI??(0,b.jsx)(e,{...i});case`data`:return i.dataRendererUI;case`file`:return(0,b.jsx)(`div`,{"data-slot":`aui_assistant-message-file`,className:`py-1`,children:(0,b.jsx)(U1,{...i})});case`image`:return(0,b.jsx)(`div`,{"data-slot":`aui_assistant-message-image`,className:`py-1`,children:(0,b.jsx)(o0,{...i})});case`indicator`:return(0,b.jsx)(`span`,{"data-slot":`aui_assistant-message-indicator`,className:`animate-pulse font-sans`,"aria-label":`Assistant is working`,children:`●`});default:return null}}}),(0,b.jsx)(t4,{})]}),(0,b.jsxs)(`div`,{"data-slot":`aui_assistant-message-footer`,className:a(`ms-2 flex items-center`,`min-h-7.5 pt-1.5`),children:[(0,b.jsx)(l4,{}),(0,b.jsx)(r4,{})]})]})},r4=()=>(0,b.jsxs)(gq.Root,{hideWhenRunning:!0,autohide:`not-last`,className:`aui-assistant-action-bar-root text-muted-foreground animate-in fade-in col-start-3 row-start-2 -ms-1 flex gap-1 duration-200`,children:[(0,b.jsx)(gq.Copy,{asChild:!0,children:(0,b.jsxs)(m1,{tooltip:`Copy`,children:[(0,b.jsx)(LL,{condition:e=>e.message.isCopied,children:(0,b.jsx)(Sf,{className:`animate-in zoom-in-50 fade-in duration-200 ease-out`})}),(0,b.jsx)(LL,{condition:e=>!e.message.isCopied,children:(0,b.jsx)(Mf,{className:`animate-in zoom-in-75 fade-in duration-150`})})]})}),(0,b.jsxs)(LL,{condition:e=>e.thread.capabilities.feedback,children:[(0,b.jsx)(gq.FeedbackPositive,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Helpful`,className:`data-[submitted=true]:bg-accent data-[submitted=true]:text-accent-foreground`,children:(0,b.jsx)(cp,{})})}),(0,b.jsx)(gq.FeedbackNegative,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Not helpful`,className:`data-[submitted=true]:bg-accent data-[submitted=true]:text-accent-foreground`,children:(0,b.jsx)(sp,{})})})]}),(0,b.jsx)(gq.Reload,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Refresh`,children:(0,b.jsx)(Qf,{})})}),(0,b.jsxs)(Dq.Root,{children:[(0,b.jsx)(Dq.Trigger,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`More`,className:`data-[state=open]:bg-accent`,children:(0,b.jsx)(Ff,{})})}),(0,b.jsx)(Dq.Content,{side:`bottom`,align:`start`,sideOffset:6,className:`aui-action-bar-more-content bg-popover text-popover-foreground data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=closed]:animate-out data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] overflow-hidden rounded-xl border p-1.5`,children:(0,b.jsx)(gq.ExportMarkdown,{asChild:!0,children:(0,b.jsxs)(Dq.Item,{className:`aui-action-bar-more-item hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,children:[(0,b.jsx)(Pf,{className:`size-4`}),`Export as Markdown`]})})})]})]}),i4=e=>(0,b.jsx)(`div`,{"data-slot":`aui_user-message-file`,className:`py-1`,children:(0,b.jsx)(U1,{...e})}),a4=e=>(0,b.jsx)(`div`,{"data-slot":`aui_user-message-image`,className:`py-1`,children:(0,b.jsx)(o0,{...e})}),o4=()=>(0,b.jsxs)(ZX.Root,{"data-slot":`aui_user-message-root`,className:`fade-in slide-in-from-bottom-1 animate-in grid auto-rows-auto grid-cols-[minmax(72px,1fr)_auto] content-start gap-y-2 px-2 duration-150 [contain-intrinsic-size:auto_200px] [content-visibility:auto] [&:where(>*)]:col-start-2`,"data-role":`user`,children:[(0,b.jsx)(O1,{}),(0,b.jsxs)(`div`,{className:`aui-user-message-content-wrapper relative col-start-2 min-w-0`,children:[(0,b.jsx)(`div`,{className:`aui-user-message-content peer bg-muted text-foreground rounded-(--composer-radius) px-4 py-2 wrap-break-word empty:hidden`,children:(0,b.jsx)(ZX.Parts,{components:{File:i4,Image:a4}})}),(0,b.jsx)(`div`,{className:`aui-user-action-bar-wrapper absolute start-0 top-1/2 -translate-x-full -translate-y-1/2 pe-2 peer-empty:hidden rtl:translate-x-full`,children:(0,b.jsx)(s4,{})})]}),(0,b.jsx)(l4,{"data-slot":`aui_user-branch-picker`,className:`col-span-full col-start-1 -me-1 justify-end`})]}),s4=()=>(0,b.jsx)(gq.Root,{hideWhenRunning:!0,autohide:`not-last`,className:`aui-user-action-bar-root flex flex-col items-end`,children:(0,b.jsx)(gq.Edit,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Edit`,className:`aui-user-action-edit`,children:(0,b.jsx)(Jf,{})})})}),c4=()=>(0,b.jsx)(ZX.Root,{"data-slot":`aui_edit-composer-wrapper`,className:`flex flex-col px-2 [contain-intrinsic-size:auto_200px] [content-visibility:auto]`,children:(0,b.jsxs)(zY.Root,{className:`aui-edit-composer-root border-foreground/10 focus-within:border-foreground/25 ms-auto flex w-full max-w-[85%] cursor-text flex-col rounded-(--composer-radius) border bg-(--composer-bg) transition-[border-color]`,children:[(0,b.jsx)(zY.Input,{className:`aui-edit-composer-input text-foreground min-h-14 w-full resize-none bg-transparent px-4 pt-3 pb-1 text-base outline-none`,autoFocus:!0}),(0,b.jsxs)(`div`,{className:`aui-edit-composer-footer mx-2.5 mb-2.5 flex items-center gap-1.5 self-end`,children:[(0,b.jsx)(zY.Cancel,{asChild:!0,children:(0,b.jsx)(o,{variant:`ghost`,size:`sm`,className:`h-8 px-3`,children:`Cancel`})}),(0,b.jsx)(zY.Send,{asChild:!0,children:(0,b.jsx)(o,{size:`sm`,className:`h-8 px-3`,children:`Update`})})]})]})}),l4=({className:e,...t})=>(0,b.jsxs)(Wq.Root,{hideWhenSingleBranch:!0,className:a(`aui-branch-picker-root text-muted-foreground -ms-2 me-2 inline-flex items-center text-xs`,e),...t,children:[(0,b.jsx)(Wq.Previous,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Previous`,children:(0,b.jsx)(wf,{})})}),(0,b.jsxs)(`span`,{className:`aui-branch-picker-state font-medium`,children:[(0,b.jsx)(Wq.Number,{}),` / `,(0,b.jsx)(Wq.Count,{})]}),(0,b.jsx)(Wq.Next,{asChild:!0,children:(0,b.jsx)(m1,{tooltip:`Next`,children:(0,b.jsx)(Tf,{})})})]}),u4=()=>{let[e,t]=(0,y.useState)(``),n=$(e=>e.threads.threadIds.length>0);return(0,b.jsxs)(f4,{children:[(0,b.jsx)(y4,{}),n&&(0,b.jsx)(d4,{value:e,onValueChange:t}),(0,b.jsx)(p4,{searchQuery:n?e:``})]})},d4=(0,y.forwardRef)(({className:e,value:t,onValueChange:n,...r},i)=>(0,b.jsxs)(`div`,{"data-slot":`aui_thread-list-search`,className:`relative px-0.5 py-1`,children:[(0,b.jsx)(ep,{"data-slot":`aui_thread-list-search-icon`,className:`text-muted-foreground pointer-events-none absolute start-3 top-1/2 size-4 -translate-y-1/2`}),(0,b.jsx)(p,{ref:i,type:`search`,value:t,onChange:e=>n(e.target.value),"aria-label":`Search threads`,placeholder:`Search threads`,className:a(`h-8 ps-8 text-sm`,e),...r})]}));d4.displayName=`ThreadListSearch`;var f4=({className:e,...t})=>(0,b.jsx)($Z.Root,{"data-slot":`aui_thread-list-root`,className:a(`flex flex-col gap-0.5`,e),...t}),p4=({className:e,searchQuery:t=``,...n})=>(0,b.jsxs)(`div`,{"data-slot":`aui_thread-list-items`,className:a(`flex flex-col gap-0.5`,e),...n,children:[(0,b.jsx)(LL,{condition:e=>e.threads.isLoading,children:(0,b.jsx)(b4,{})}),(0,b.jsx)(LL,{condition:e=>!e.threads.isLoading,children:(0,b.jsx)(_4,{searchQuery:t})})]}),m4=864e5,h4=(e,t)=>!e||e.getTime()>=t?`Today`:e.getTime()>=t-m4?`Yesterday`:`Earlier`,g4=(e=``)=>{let t=$(e=>e.threads.threadIds),n=$(e=>e.threads.threadItems),r=e.trim().toLowerCase();return(0,y.useMemo)(()=>{let e=new Map(n.map(e=>[e.id,e])),i=t=>!r||(e.get(t)?.title||`New Chat`).toLowerCase().includes(r),a=t=>e.get(t)?.status===`archived`,o=t.map(t=>e.get(t)?.lastMessageAt),s=t.map((e,t)=>({id:e,index:t})).filter(({id:e})=>i(e)&&!a(e)).map(({index:e})=>e),c=t.map((e,t)=>({id:e,index:t})).filter(({id:e})=>i(e)&&a(e)).map(({index:e})=>e);if(!s.some(e=>o[e]))return{threadIds:t,filteredIndices:s,archivedIndices:c,groups:null};let l=new Date,u=new Date(l.getFullYear(),l.getMonth(),l.getDate()).getTime(),d=e=>o[e]?.getTime()??2**53-1,f=[...s].sort((e,t)=>d(t)-d(e)),p=[];for(let e of f){let t=h4(o[e],u),n=p[p.length-1];n?.label===t?n.indices.push(e):p.push({label:t,indices:[e]})}return{threadIds:t,filteredIndices:s,archivedIndices:c,groups:p}},[t,n,r])},_4=({searchQuery:e=``})=>{let{threadIds:t,filteredIndices:n,archivedIndices:r,groups:i}=g4(e);return e.trim()&&n.length===0&&r.length===0?(0,b.jsx)(`div`,{"data-slot":`aui_thread-list-empty`,className:`text-muted-foreground px-2.5 py-4 text-sm`,children:`No threads found`}):i?(0,b.jsxs)(b.Fragment,{children:[i.map(e=>(0,b.jsxs)(y.Fragment,{children:[(0,b.jsx)(`div`,{"data-slot":`aui_thread-list-group-label`,className:`text-muted-foreground px-2.5 pt-3 pb-1 text-xs font-medium`,children:e.label}),e.indices.map(e=>(0,b.jsx)($Z.ItemByIndex,{index:e,components:{ThreadListItem:x4}},t[e]))]},e.label)),(0,b.jsx)(v4,{threadIds:t,indices:r})]}):(0,b.jsxs)(b.Fragment,{children:[n.map(e=>(0,b.jsx)($Z.ItemByIndex,{index:e,components:{ThreadListItem:x4}},t[e])),(0,b.jsx)(v4,{threadIds:t,indices:r})]})},v4=({threadIds:e,indices:t})=>t.length?(0,b.jsxs)(y.Fragment,{children:[(0,b.jsx)(`div`,{"data-slot":`aui_thread-list-group-label`,className:`text-muted-foreground px-2.5 pt-3 pb-1 text-xs font-medium`,children:`Archived`}),t.map(t=>(0,b.jsx)($Z.ItemByIndex,{index:t,components:{ThreadListItem:x4}},e[t]))]}):null,y4=(0,y.forwardRef)(({className:e,labelClassName:t,children:n,...r},i)=>(0,b.jsx)($Z.New,{asChild:!0,children:(0,b.jsx)(o,{ref:i,variant:`ghost`,"data-slot":`aui_thread-list-new`,className:a(`hover:bg-muted data-active:bg-muted h-8 justify-start gap-2 rounded-md px-2.5 text-sm font-normal`,e),...r,children:n??(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(Zf,{"data-slot":`aui_thread-list-new-icon`,className:`size-4 shrink-0`}),(0,b.jsx)(`span`,{"data-slot":`aui_thread-list-new-label`,className:a(`whitespace-nowrap`,t),children:`New Thread`})]})})}));y4.displayName=`ThreadListNew`;var b4=()=>(0,b.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:Array.from({length:5},(e,t)=>(0,b.jsx)(`div`,{role:`status`,"aria-label":`Loading threads`,"data-slot":`aui_thread-list-skeleton-wrapper`,className:`flex h-8 items-center px-2.5`,children:(0,b.jsx)(N2,{"data-slot":`aui_thread-list-skeleton`,className:`h-3.5 w-full`})},t))}),x4=()=>{let e=$(e=>e.threadListItem.isRunning),t=$(e=>e.threadListItem.status)===`archived`,[n,r]=(0,y.useState)(!1),i=(0,y.useRef)(null),o=(0,y.useRef)(!1);return(0,y.useEffect)(()=>{!n&&o.current&&(o.current=!1,i.current?.focus())},[n]),(0,b.jsxs)(oQ.Root,{"data-slot":`aui_thread-list-item`,"data-archived":t||void 0,className:a(`group hover:bg-muted focus-visible:bg-muted data-active:bg-muted has-focus-visible:bg-muted has-data-[state=open]:bg-muted relative flex h-8 items-center rounded-md transition-colors focus-visible:outline-none`,t&&`opacity-60`),children:[n?(0,b.jsx)(S4,{onDone:e=>{o.current=e,r(!1)}}):(0,b.jsxs)(oQ.Trigger,{ref:i,"data-slot":`aui_thread-list-item-trigger`,className:`focus-visible:ring-ring/50 flex h-full min-w-0 flex-1 items-center rounded-md px-2.5 text-start text-sm outline-none group-hover:pe-9 group-has-focus-visible:pe-9 group-has-data-[state=open]:pe-9 group-data-active:pe-9 focus-visible:ring-1`,children:[e&&(0,b.jsx)(Uf,{"aria-hidden":!0,"data-slot":`aui_thread-list-item-running`,className:`text-muted-foreground me-1.5 size-3.5 shrink-0 animate-spin`}),(0,b.jsx)(`span`,{"data-slot":`aui_thread-list-item-title`,className:`min-w-0 flex-1 truncate`,children:(0,b.jsx)(oQ.Title,{fallback:`New Chat`})}),e&&(0,b.jsx)(`span`,{className:`sr-only`,children:`Running`})]}),(0,b.jsx)(C4,{archived:t,onRename:()=>r(!0)})]})},S4=({onDone:e})=>{let t=Q(),n=$(e=>e.threadListItem.title)??``,[r,i]=(0,y.useState)(n),a=(0,y.useRef)(null),o=(0,y.useRef)(!1);(0,y.useEffect)(()=>{a.current?.select()},[]);let s=i=>{if(o.current)return;o.current=!0;let s=r.trim();if(!s||s===n){e(i);return}Promise.resolve().then(()=>t.threadListItem.rename(s)).then(()=>e(i),()=>{o.current=!1,i&&a.current?.focus()})},c=()=>{o.current||(o.current=!0,e(!0))};return(0,b.jsx)(p,{ref:a,autoFocus:!0,"data-slot":`aui_thread-list-item-rename`,"aria-label":`Rename thread`,value:r,className:`h-7 min-w-0 flex-1 ps-2.5 pe-9 text-sm`,onChange:e=>i(e.target.value),onBlur:()=>s(!1),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),s(!0)):e.key===`Escape`&&(e.preventDefault(),c())}})},C4=({archived:e,onRename:t})=>(0,b.jsxs)(_Q.Root,{sharedFocusGroup:!0,children:[(0,b.jsx)(_Q.Trigger,{asChild:!0,children:(0,b.jsxs)(o,{variant:`ghost`,size:`icon`,"data-slot":`aui_thread-list-item-more`,className:`data-[state=open]:bg-accent absolute end-1.5 top-1/2 size-6 -translate-y-1/2 p-0 opacity-0 group-hover:opacity-100 group-has-focus-visible:opacity-100 group-data-active:opacity-100 data-[state=open]:opacity-100`,children:[(0,b.jsx)(Ff,{className:`size-3.5`}),(0,b.jsx)(`span`,{className:`sr-only`,children:`More options`})]})}),(0,b.jsxs)(_Q.Content,{side:`right`,align:`start`,sideOffset:6,"data-slot":`aui_thread-list-item-more-content`,className:`bg-popover text-popover-foreground data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=closed]:animate-out data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 overflow-hidden rounded-xl border p-1.5`,children:[(0,b.jsxs)(_Q.Item,{"data-slot":`aui_thread-list-item-more-item`,className:`hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,onSelect:t,children:[(0,b.jsx)(Jf,{className:`size-4`}),`Rename`]}),e?(0,b.jsx)(oQ.Unarchive,{asChild:!0,children:(0,b.jsxs)(_Q.Item,{"data-slot":`aui_thread-list-item-more-item`,className:`hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,children:[(0,b.jsx)(pf,{className:`size-4`}),`Unarchive`]})}):(0,b.jsx)(oQ.Archive,{asChild:!0,children:(0,b.jsxs)(_Q.Item,{"data-slot":`aui_thread-list-item-more-item`,className:`hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,children:[(0,b.jsx)(mf,{className:`size-4`}),`Archive`]})}),(0,b.jsx)(oQ.Delete,{asChild:!0,children:(0,b.jsxs)(_Q.Item,{"data-slot":`aui_thread-list-item-more-item`,className:`text-destructive hover:bg-destructive/10 hover:text-destructive focus:bg-destructive/10 focus:text-destructive flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none`,children:[(0,b.jsx)(lp,{className:`size-4`}),`Delete`]})})]})]}),w4=`bg-background border border-border/60 dark:bg-popover`;function T4({phase:e,attempt:t,resumedTokens:n,onRetry:r,className:i,...o}){return e===`online`?null:(0,b.jsxs)(`div`,{"data-slot":`connection-state`,className:a(w4,`fade-in slide-in-from-top-1 animate-in flex w-full max-w-sm items-center gap-2.5 rounded-2xl px-3.5 py-2.5 duration-300`,i),...o,children:[e===`dropped`&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(jf,{className:`size-3.5 shrink-0 text-amber-600 dark:text-amber-400`}),(0,b.jsx)(`span`,{className:`min-w-0 flex-1 text-[13px]`,children:`Connection lost. The run kept going on the server.`}),(0,b.jsx)(`button`,{type:`button`,onClick:r,className:`text-foreground/70 hover:bg-foreground/[0.06] hover:text-foreground/95 shrink-0 rounded-full px-2.5 py-1 text-xs font-medium transition-[background-color,color,scale] duration-150 active:scale-[0.96]`,children:`Reconnect`})]}),e===`reconnecting`&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(Uf,{className:`text-foreground/40 size-3.5 shrink-0 animate-spin motion-reduce:animate-none`}),(0,b.jsx)(`span`,{className:`min-w-0 flex-1 text-[13px]`,children:`Reconnecting`}),t!==void 0&&(0,b.jsxs)(`span`,{className:a(`font-mono text-[11px] tracking-tight`,`text-foreground/30 shrink-0 tabular-nums`),children:[`attempt `,t]})]}),e===`resumed`&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(Sf,{className:`size-3.5 shrink-0 text-emerald-500`}),(0,b.jsx)(`span`,{className:`min-w-0 flex-1 text-[13px]`,children:`Picked the stream back up.`}),n!==void 0&&(0,b.jsxs)(`span`,{className:a(`font-mono text-[11px] tracking-tight`,`text-foreground/30 shrink-0 tabular-nums`),children:[`+`,n,` tokens`]})]})]})}var E4=[`pending`,`testing`,`confirmed`,`rejected`,`blocked`],D4=H(E4),O4=V({tasks:B(V({id:R(),title:R(),status:D4.default(`pending`),note:R().optional()})),target:R().optional(),phase:R().optional()}),k4={tasks:[]};function A4(e){return typeof e==`string`&&E4.includes(e)}function j4(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase().replace(/[^a-z_-]/g,``);if(t===`pending`||t===`todo`||t===`hypothesis`||t===`planned`||t===`open`)return`pending`;if(t===`testing`||t===`in_progress`||t===`inprogress`||t===`active`||t===`probing`)return`testing`;if(t===`confirmed`||t===`verified`||t===`exploited`||t===`vulnerable`||t===`success`)return`confirmed`;if(t===`rejected`||t===`tested_safe`||t===`testedsafe`||t===`safe`||t===`clean`||t===`not_vulnerable`||t===`notvulnerable`||t===`invalid`)return`rejected`;if(t===`blocked`||t===`justified_blocked`||t===`justifiedblocked`||t===`needs_auth`||t===`needsauth`||t===`untestable`)return`blocked`}var M4=/https?:\/\/[^\s<>")']+/i,N4=/\b(?:[a-z0-9-]+\.)+[a-z]{2,}\b/i;function P4(e){if(!e||typeof e!=`string`)return null;let t=e.match(M4);if(t?.[0]){let e=t[0].trim().replace(/[),.!?;:]$/,``);if(e.length>0&&e.length<512)return e}let n=e.match(N4);if(n?.[0]){let e=n[0].trim().replace(/[),.!?;:]$/,``);if(e.length>0&&e.length<256&&!e.endsWith(`.ts`)&&!e.endsWith(`.js`)&&!e.endsWith(`.json`)&&!e.endsWith(`.md`)&&!e.endsWith(`.html`)&&!e.endsWith(`.txt`))return e}return null}function F4(e){let t=0;for(let n of e){let e=n.id.match(/^T-(\d+)$/i);e&&(t=Math.max(t,Number.parseInt(e[1],10)))}return`T-${t+1}`}function I4(e,t){let n=new Map;for(let t of e)n.set(t.id,{...t});for(let e of t){let t=n.get(e.id);t?n.set(e.id,{id:e.id,title:e.title||t.title,status:e.status||t.status,note:e.note===void 0?t.note:e.note}):n.set(e.id,{...e})}return Array.from(n.values())}var L4=/-\s*\[(pending|testing|confirmed|rejected|blocked)\]\s*([A-Za-z0-9_-]+):\s*([^—\n\r]+?)(?:\s*—\s*([^\n\r]+))?$/gim,R4=/Task\s+([A-Za-z0-9_-]+)\s+(?:added|updated):\s*\[(pending|testing|confirmed|rejected|blocked)\]\s*([^—\n\r]+?)(?:\s*—\s*([^\n\r]+))?$/gim,z4=/<kifaru_dossier\s+target="([^"]+)"(?:\s+phase="([^"]+)")?/i;function B4(e,t=[]){let n=[...t],r=new Map;for(let e of n)r.set(e.title.trim().toLowerCase(),e);let i=e.split(/\r?\n/);for(let e of i){let t=e.trim();if(!t.startsWith(`|`)||!t.endsWith(`|`))continue;let i=t.split(`|`).map(e=>e.trim()),a=i.filter((e,t)=>t>0&&t<i.length-1);if(a.length<2||a.every(e=>/^[-:=|\s]+$/.test(e)))continue;let o=j4(a[1]),s=a[0],c=a[2];if(o||(o=j4(a[0]),o&&(s=a[1],c=a[2])),!o||!s||(s=s.replace(/^[`*_\s]+|[`*_\s]+$/g,``).trim(),!s||s.toLowerCase()===`cell`||s.toLowerCase()===`task`))continue;let l,u=s.match(/^(T-\d+)[:\s—-]+(.*)$/i);u?.[1]&&(l=u[1].toUpperCase(),s=u[2].trim());let d=s.toLowerCase(),f=r.get(d);if(f)f.status=o,c&&(f.note=c.trim());else{let e={id:l||F4(n),title:s,status:o,note:c?c.trim():void 0};n.push(e),r.set(d,e)}}return n}function V4(e,t=[]){let n=[...t],r=new Map;for(let e of n)r.set(e.title.trim().toLowerCase(),e);let i=/^\s*[-*]\s*\[([ xX/!?-])\]\s*(?:([A-Za-z0-9_-]+):)?\s*([^—\n\r]+?)(?:\s*—\s*([^\n\r]+))?$/gm,a;for(;(a=i.exec(e))!==null;){let[,e,t,i,o]=a;if(!i)continue;let s=`pending`;e===`x`||e===`X`?s=`confirmed`:e===`/`?s=`testing`:e===`!`?s=`blocked`:(e===`-`||e===`?`)&&(s=`rejected`);let c=i.trim(),l=c.toLowerCase(),u=r.get(l);if(u)u.status=s,o&&(u.note=o.trim());else{let e={id:t?.startsWith(`T-`)?t.toUpperCase():F4(n),title:c,status:s,note:o?o.trim():void 0};n.push(e),r.set(l,e)}}return n}function H4(e,t=[]){let n=[...t],r=new Map;for(let e of n)r.set(e.title.trim().toLowerCase(),e);for(let t of e){let e=typeof t==`string`?t:typeof t==`object`&&t&&`note`in t?String(t.note??``):``;if(!e)continue;let i,a,o;if(/^CONFIRMED(\([^)]+\))?:/i.test(e)){i=`confirmed`;let t=e.replace(/^CONFIRMED(\([^)]+\))?:\s*/i,``).trim(),n=t.indexOf(`.`);a=(n>0&&n<120?t.slice(0,n):t.slice(0,120)).trim(),o=n>0?t.slice(n+1).trim():void 0}else if(/BLOCKED/i.test(e)&&(/coverage gap/i.test(e)||/needs auth/i.test(e))){i=`blocked`;let t=e.replace(/^Coverage gap(\s*\([^)]+\))?:\s*/i,``).trim(),n=t.indexOf(`—`);a=(n>0&&n<120?t.slice(0,n):t.slice(0,120)).trim(),o=n>0?t.slice(n+1).trim():t}if(i&&a){let e=a.toLowerCase(),t=r.get(e);if(t)t.status=i,o&&(t.note=o);else{let t={id:F4(n),title:a,status:i,note:o};n.push(t),r.set(e,t)}}}return n}function U4(e){let t=[],n,r;for(let i of e){if(i.role===`user`){let e=``;if(typeof i.content==`string`)e=i.content;else if(Array.isArray(i.content))for(let t of i.content)typeof t==`object`&&t&&`type`in t&&t.type===`text`&&(e+=` ${t.text??``}`);let t=P4(e);t&&(n=t)}if(i.role===`custom`&&i.customType===`kifaru-dossier`){let e=typeof i.content==`string`?i.content:``,a=e.match(/Bound target:\s*([^\n\r]+)/i)||e.match(/Session bound to target\s*([^\n\r.]+)/i);a?.[1]&&(n=a[1].trim());let o=e.match(/Phase:\s*([a-zA-Z0-9_-]+)/i);o?.[1]&&(r=o[1].trim());let s;for(L4.lastIndex=0;(s=L4.exec(e))!==null;){let[,e,n,r,i]=s;n&&r&&A4(e)&&(t=I4(t,[{id:n.trim(),title:r.trim(),status:e,note:i?i.trim():void 0}]))}}if(i.role===`assistant`&&Array.isArray(i.content)){for(let e of i.content)if(typeof e==`object`&&e&&`type`in e){if(e.type===`text`&&typeof e.text==`string`){let i=e.text,a=P4(i);a&&!n&&(n=a);let o=i.match(z4);o?.[1]&&(n=o[1].trim()),o?.[2]&&(r=o[2].trim()),t=B4(i,t),t=V4(i,t)}if(e.type===`tool-call`||e.type===`toolCall`){let i=e,a=i.name??i.toolName,o=i.args??i.arguments;if(a===`kifaru_dossier`&&o&&(typeof o.target==`string`&&o.target.trim()&&(n=o.target.trim()),typeof o.phase==`string`&&o.phase.trim()&&(r=o.phase.trim()),o.action===`task`)){let e=typeof o.taskId==`string`?o.taskId.trim():void 0,n=typeof o.title==`string`?o.title.trim():void 0,r=typeof o.note==`string`?o.note.trim():void 0;e&&(t=I4(t,[{id:e,title:n||e,status:A4(o.status)?o.status:`pending`,note:r}]))}}}}if(i.role===`toolResult`){let e=i;for(let i of e.content??[])if(i.type===`text`&&i.text){let e=i.text.trim();if(e.startsWith(`{`)&&e.endsWith(`}`))try{let i=JSON.parse(e);if(typeof i.target==`string`&&(n=i.target),typeof i.phase==`string`&&(r=i.phase),Array.isArray(i.tasks)){let e=[];for(let t of i.tasks)typeof t.id==`string`&&typeof t.title==`string`&&e.push({id:t.id,title:t.title,status:A4(t.status)?t.status:`pending`,note:typeof t.note==`string`?t.note:void 0});t=I4(t,e)}Array.isArray(i.observations)&&(t=H4(i.observations,t))}catch{}t=B4(e,t),t=V4(e,t);let a;for(R4.lastIndex=0;(a=R4.exec(e))!==null;){let[,e,n,r,i]=a;e&&r&&A4(n)&&(t=I4(t,[{id:e.trim(),title:r.trim(),status:n,note:i?i.trim():void 0}]))}let o=e.match(z4);for(o?.[1]&&(n=o[1].trim()),o?.[2]&&(r=o[2].trim()),L4.lastIndex=0;(a=L4.exec(e))!==null;){let[,e,n,r,i]=a;n&&r&&A4(e)&&(t=I4(t,[{id:n.trim(),title:r.trim(),status:e,note:i?i.trim():void 0}]))}}}}return{tasks:t,target:n,phase:r}}var W4={pending:Af,testing:Uf,confirmed:Sf,rejected:Of,blocked:Ef},G4={pending:{badge:`bg-secondary text-secondary-foreground hover:bg-secondary/80`,text:`text-muted-foreground`,ring:`border-border`},testing:{badge:`bg-blue-500/10 text-blue-500 border-blue-500/30 hover:bg-blue-500/20`,text:`text-blue-500`,ring:`border-blue-500/40 bg-blue-500/10`},confirmed:{badge:`bg-emerald-500/10 text-emerald-500 border-emerald-500/30 hover:bg-emerald-500/20`,text:`text-emerald-500`,ring:`border-emerald-500/50 bg-emerald-500/20`},rejected:{badge:`bg-rose-500/10 text-rose-500 border-rose-500/30 hover:bg-rose-500/20`,text:`text-rose-500`,ring:`border-rose-500/40 bg-rose-500/10`},blocked:{badge:`bg-amber-500/10 text-amber-500 border-amber-500/30 hover:bg-amber-500/20`,text:`text-amber-500`,ring:`border-amber-500/40 bg-amber-500/10`}};function K4({className:e=``,onClose:t}){let[n,{setState:r}]=nB(`taskBoard`,{description:`A task board panel for the target dossier tracking hunt theses, tests, and findings. Use update_taskBoard with tasks.add/update/remove/clear to manage tasks. Tasks have id (e.g. T-1), title, status (pending|testing|confirmed|rejected|blocked), and optional note.`,stateSchema:O4,initialState:k4}),i=X$(e=>e.messages),[a,s]=(0,y.useState)(``),[c,l]=(0,y.useState)(`all`),[u,d]=(0,y.useState)(!1);(0,y.useEffect)(()=>{if(!i||i.length===0)return;let e=U4(i);(e.tasks.length!==0||e.target||e.phase)&&r(t=>{let n=I4(t?.tasks??[],e.tasks),r=e.target&&e.target!==t?.target,i=e.phase&&e.phase!==t?.phase,a=n.length!==(t?.tasks?.length??0)||n.some((e,n)=>{let r=t?.tasks?.[n];return!r||r.id!==e.id||r.status!==e.status||r.title!==e.title||r.note!==e.note});return!r&&!i&&!a?t:{...t,tasks:n,target:e.target??t?.target,phase:e.phase??t?.phase}})},[i,r]);let f=n?.target;(0,y.useEffect)(()=>{if(!f)return;let e=!1;return fetch(`/api/v1/workbench/dossier?target=${encodeURIComponent(f)}`).then(e=>e.ok?e.json():null).then(t=>{!e&&t&&Array.isArray(t.tasks)&&t.tasks.length!==0&&r(e=>{let n=I4(e?.tasks??[],t.tasks??[]),r=t.target&&!e?.target,i=t.phase&&!e?.phase,a=n.length!==(e?.tasks?.length??0)||n.some((t,n)=>{let r=e?.tasks?.[n];return!r||r.id!==t.id||r.status!==t.status||r.title!==t.title});return!r&&!i&&!a?e:{...e,tasks:n,target:e?.target??t.target,phase:e?.phase??t.phase}})}).catch(()=>{}),()=>{e=!0}},[f,r]);let m=n?.tasks??[],h=n?.target,g=n?.phase,_=(0,y.useMemo)(()=>{let e={all:m.length};for(let t of E4)e[t]=0;for(let t of m)e[t.status]=(e[t.status]??0)+1;return e},[m]),v=(0,y.useMemo)(()=>c===`all`?m:m.filter(e=>e.status===c),[m,c]),x=(e,t,n)=>{let r=t||h;r&&fetch(`/api/v1/workbench/dossier`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({target:r,tasks:e,phase:n||g})}).catch(()=>{})},S=e=>{let t=`pending`;e.status===`pending`?t=`testing`:e.status===`testing`?t=`confirmed`:e.status===`confirmed`?t=`pending`:e.status===`blocked`?t=`testing`:e.status===`rejected`&&(t=`pending`);let n=m.map(n=>n.id===e.id?{...n,status:t}:n);r(e=>({...e,tasks:n})),x(n)},C=(e,t)=>{let n=m.map(n=>n.id===e?{...n,status:t}:n);r(e=>({...e,tasks:n})),x(n)},w=e=>{let t=m.filter(t=>t.id!==e);r(e=>({...e,tasks:t})),x(t)},T=()=>{let e=a.trim();if(!e)return;let t={id:F4(m),title:e,status:`pending`},n=[...m,t];r(e=>({...e,tasks:n})),x(n),s(``),d(!1)};return(0,b.jsxs)(`div`,{className:`flex h-full flex-col bg-card text-card-foreground ${e}`,children:[(0,b.jsxs)(`header`,{className:`flex items-center justify-between border-b border-border px-3.5 py-2.5`,children:[(0,b.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,b.jsx)(Hf,{className:`size-4.5 text-muted-foreground shrink-0`,"aria-hidden":`true`}),(0,b.jsx)(`h2`,{className:`text-sm font-semibold tracking-tight text-foreground truncate`,children:`Task Board`}),m.length>0?(0,b.jsx)(qx,{variant:`secondary`,className:`px-1.5 py-0 text-[11px] font-mono font-medium`,children:m.length}):null]}),(0,b.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[h?(0,b.jsxs)(`div`,{className:`flex items-center gap-1 text-[11px] text-muted-foreground bg-muted/60 px-2 py-0.5 rounded-md font-mono truncate max-w-32`,title:`Bound target: ${h}`,children:[(0,b.jsx)(ap,{className:`size-3 text-primary shrink-0`}),(0,b.jsx)(`span`,{className:`truncate`,children:h})]}):null,g?(0,b.jsx)(qx,{variant:`outline`,className:`text-[10px] uppercase font-mono tracking-wider px-1.5 py-0`,children:g}):null,(0,b.jsxs)(o,{variant:`ghost`,size:`icon`,className:`size-7 text-muted-foreground hover:text-foreground`,onClick:()=>d(e=>!e),title:`Add task`,children:[(0,b.jsx)(Zf,{className:`size-4`}),(0,b.jsx)(`span`,{className:`sr-only`,children:`Add task`})]}),t?(0,b.jsxs)(o,{variant:`ghost`,size:`icon`,className:`size-7 text-muted-foreground hover:text-foreground md:hidden`,onClick:t,title:`Close panel`,children:[(0,b.jsx)(Of,{className:`size-4`}),(0,b.jsx)(`span`,{className:`sr-only`,children:`Close panel`})]}):null]})]}),m.length>0?(0,b.jsxs)(`div`,{className:`flex items-center gap-1 overflow-x-auto border-b border-border/60 px-3 py-1.5 text-xs`,children:[(0,b.jsxs)(`button`,{type:`button`,onClick:()=>l(`all`),className:`rounded-md px-2 py-0.5 text-xs font-medium transition-colors ${c===`all`?`bg-accent text-accent-foreground`:`text-muted-foreground hover:text-foreground`}`,children:[`All (`,_.all,`)`]}),E4.map(e=>{let t=_[e]??0;return t===0&&c!==e?null:(0,b.jsxs)(`button`,{type:`button`,onClick:()=>l(e),className:`flex items-center gap-1 rounded-md px-2 py-0.5 text-xs capitalize font-medium transition-colors ${c===e?`bg-accent text-accent-foreground`:`text-muted-foreground hover:text-foreground`}`,children:[(0,b.jsx)(`span`,{children:e}),(0,b.jsxs)(`span`,{className:`font-mono text-[10px] opacity-70`,children:[`(`,t,`)`]})]},e)})]}):null,u?(0,b.jsxs)(`div`,{className:`border-b border-border/80 bg-muted/30 p-2.5 flex items-center gap-2`,children:[(0,b.jsx)(p,{autoFocus:!0,value:a,onChange:e=>s(e.target.value),onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),T()):e.key===`Escape`&&d(!1)},placeholder:`New task thesis (e.g. Test IDOR on /api/user)...`,className:`h-8 text-xs bg-background`}),(0,b.jsx)(o,{size:`sm`,className:`h-8 px-2.5 text-xs shrink-0`,onClick:T,children:`Add`})]}):null,(0,b.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-3`,children:m.length===0?(0,b.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center text-center px-4`,children:[(0,b.jsx)(`div`,{className:`flex size-14 items-center justify-center rounded-2xl bg-muted/40 mb-3 border border-border/40`,children:(0,b.jsx)(Hf,{className:`size-8 text-muted-foreground/50`,"aria-hidden":`true`})}),(0,b.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:h?`No tasks yet for ${h}`:`No tasks yet.`}),(0,b.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground max-w-56 leading-relaxed`,children:h?`Analyzing target surface and recording hunt theses...`:`Ask the assistant to add some!`}),(0,b.jsxs)(o,{variant:`outline`,size:`sm`,className:`mt-4 h-7 text-xs gap-1.5 text-muted-foreground hover:text-foreground`,onClick:()=>d(!0),children:[(0,b.jsx)(Zf,{className:`size-3.5`}),`Add task`]})]}):v.length===0?(0,b.jsxs)(`div`,{className:`flex h-full min-h-36 flex-col items-center justify-center text-center text-muted-foreground text-xs py-8`,children:[(0,b.jsxs)(`p`,{children:[`No tasks with status "`,c,`".`]}),(0,b.jsx)(o,{variant:`link`,size:`sm`,className:`text-xs mt-1`,onClick:()=>l(`all`),children:`Show all tasks`})]}):(0,b.jsx)(`ul`,{className:`flex flex-col gap-2`,children:v.map(e=>{let t=W4[e.status]??Af,n=G4[e.status]??G4.pending,r=e.status===`confirmed`;return(0,b.jsx)(`li`,{className:`group relative flex flex-col gap-1.5 rounded-lg border border-border/70 bg-card p-2.5 transition-all hover:border-border hover:shadow-xs`,children:(0,b.jsxs)(`div`,{className:`flex items-start gap-2.5`,children:[(0,b.jsx)(`button`,{type:`button`,onClick:()=>S(e),title:`Status: ${e.status}. Click to cycle.`,"aria-label":`Toggle task status for ${e.title}`,className:`mt-0.5 flex size-4.5 shrink-0 items-center justify-center rounded-md border transition-all ${r?`border-emerald-500 bg-emerald-500 text-white dark:text-black`:n.ring}`,children:r?(0,b.jsx)(Sf,{className:`size-3 stroke-[3]`}):e.status===`testing`?(0,b.jsx)(Uf,{className:`size-2.5 animate-spin text-blue-500`}):(0,b.jsx)(`span`,{className:`size-1.5 rounded-full bg-transparent group-hover:bg-muted-foreground/30`})}),(0,b.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,b.jsxs)(`div`,{className:`flex items-center gap-1.5 mb-1`,children:[(0,b.jsx)(`span`,{className:`font-mono text-[10px] font-semibold text-muted-foreground/80 tracking-wider`,children:e.id}),(0,b.jsxs)(`div`,{className:`relative inline-flex items-center`,children:[(0,b.jsx)(t,{className:`pointer-events-none absolute left-1.5 size-2.5 opacity-70`}),(0,b.jsx)(`select`,{value:e.status,onChange:t=>C(e.id,t.target.value),"aria-label":`Change status for task ${e.id}`,className:`h-4.5 appearance-none rounded border pl-4.5 pr-4 text-[10px] font-medium transition-colors cursor-pointer outline-none ${n.badge}`,children:E4.map(e=>(0,b.jsx)(`option`,{value:e,children:e},e))}),(0,b.jsx)(Cf,{className:`pointer-events-none absolute right-1 size-2.5 opacity-60`})]})]}),(0,b.jsx)(`p`,{className:`text-xs leading-snug break-words ${r?`text-muted-foreground line-through`:`text-foreground`}`,children:e.title}),e.note?(0,b.jsx)(`p`,{className:`mt-1 text-[11px] text-muted-foreground/90 bg-muted/40 rounded px-1.5 py-0.5 border border-border/40 font-mono`,children:e.note}):null]}),(0,b.jsx)(`button`,{type:`button`,onClick:()=>w(e.id),className:`opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive p-1 rounded-sm`,title:`Delete task`,"aria-label":`Delete task`,children:(0,b.jsx)(up,{className:`size-3.5`})})]})},e.id)})})}),m.length>0?(0,b.jsxs)(`footer`,{className:`border-t border-border px-3 py-2 flex items-center justify-between text-[11px] text-muted-foreground bg-muted/20`,children:[(0,b.jsxs)(`span`,{children:[_.confirmed??0,` of `,m.length,` confirmed`]}),(0,b.jsx)(o,{variant:`ghost`,size:`sm`,className:`h-6 px-1.5 text-[11px] text-muted-foreground hover:text-destructive`,onClick:()=>r(e=>({...e,tasks:[]})),children:`Clear all`})]}):null]})}function q4({request:e,respond:t}){let[n,r]=(0,y.useState)(e.kind===`editor`?e.prefill??``:``),i=e=>void t(e);return(0,b.jsxs)(`div`,{className:`bg-card grid gap-2 rounded-md border border-l-[3px] border-l-primary p-3`,role:`group`,"aria-label":`The agent is asking for approval`,children:[(0,b.jsxs)(`p`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,b.jsx)(rp,{className:`size-4 shrink-0 text-primary`,"aria-hidden":`true`}),e.title]}),e.kind===`confirm`?(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs break-words whitespace-pre-wrap`,children:e.message}):null,e.timeoutMs?(0,b.jsxs)(`p`,{className:`text-muted-foreground text-[0.7rem] tabular-nums`,children:[`Auto-dismisses after `,Math.round(e.timeoutMs/1e3),`s`]}):null,e.kind===`confirm`?(0,b.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,b.jsx)(o,{size:`sm`,onClick:()=>i({requestId:e.id,confirmed:!0}),children:`Allow`}),(0,b.jsx)(o,{size:`sm`,variant:`outline`,onClick:()=>i({requestId:e.id,confirmed:!1}),children:`Deny`})]}):null,e.kind===`select`?(0,b.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[e.options.map(t=>(0,b.jsx)(o,{size:`sm`,variant:`outline`,onClick:()=>i({requestId:e.id,value:t}),children:t},t)),(0,b.jsx)(o,{size:`sm`,variant:`ghost`,onClick:()=>i({requestId:e.id,dismissed:!0}),children:`Dismiss`})]}):null,e.kind===`input`||e.kind===`editor`?(0,b.jsxs)(`form`,{className:`grid gap-2`,onSubmit:t=>{t.preventDefault(),i({requestId:e.id,value:n})},children:[e.kind===`editor`?(0,b.jsx)(i2,{rows:6,value:n,onChange:e=>r(e.target.value)}):(0,b.jsx)(p,{value:n,placeholder:e.placeholder??``,onChange:e=>r(e.target.value)}),(0,b.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,b.jsx)(o,{size:`sm`,type:`submit`,children:`Submit`}),(0,b.jsx)(o,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i({requestId:e.id,dismissed:!0}),children:`Dismiss`})]})]}):null]})}function J4(){let{requests:e,respond:t}=Z$();return e.length===0?null:(0,b.jsx)(`div`,{className:`grid gap-2 border-b px-3 py-2`,children:e.map(e=>(0,b.jsx)(q4,{request:e,respond:t},e.id))})}function Y4({className:e,...t}){return(0,b.jsx)(`select`,{"data-slot":`native-select`,className:a(`border-input bg-background text-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:border-destructive h-9 w-full min-w-0 cursor-pointer rounded-md border px-3 py-1 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50`,e),...t})}function X4({title:e,detail:t,action:n,compact:r}){return(0,b.jsxs)(h,{className:`state ${r?`state-compact`:``}`,"aria-live":`polite`,children:[(0,b.jsx)(`div`,{className:`mb-1 grid size-9 place-items-center rounded-full border bg-[var(--accent-soft)] text-primary [&_svg]:size-[18px]`,children:(0,b.jsx)(np,{"aria-hidden":`true`})}),(0,b.jsx)(`h2`,{children:e}),(0,b.jsx)(`p`,{children:t}),n]})}var Z4=`session`,Q4=`kifaru:session`,$4={kind:`latest`},e3={kind:`all`};function t3(e){return e.kind===`pinned`?e.id:e.kind===`all`?`all`:null}function n3(e){return e?e===`all`?e3:e===`latest`?$4:{kind:`pinned`,id:e}:$4}function r3(e,t){return n3(new URLSearchParams(e).get(Z4)||t)}function i3(e,t){if(e.kind!==`all`)return e.kind===`pinned`?e.id:t?.[0]?.id}function a3(e,t){if(e.kind!==`latest`)return null;let n=t?.[0]?.id;return n?{kind:`pinned`,id:n}:null}function o3(e){return e?.source===`web`}function s3(e,t){if(e.kind===`all`)return{kind:`fresh`};if(e.kind===`pinned`){let n=t?.find(t=>t.id===e.id);return n&&!o3(n)?{kind:`external`,session:n}:{kind:`thread`,threadId:e.id}}if(!t)return{kind:`loading`};let n=t[0];return n?o3(n)?{kind:`thread`,threadId:n.id}:{kind:`external`,session:n}:{kind:`fresh`}}function c3(e,t){return!(!t||e.kind===`all`||e.kind===`pinned`&&e.id===t)}function l3(){if(typeof window>`u`)return $4;let e=null;try{e=window.localStorage.getItem(Q4)}catch{}return r3(window.location.search,e)}function u3(e){if(typeof window>`u`)return;let t=t3(e);try{t?window.localStorage.setItem(Q4,t):window.localStorage.removeItem(Q4)}catch{}let n=new URL(window.location.href);t?n.searchParams.set(Z4,t):n.searchParams.delete(Z4),n.toString()!==window.location.href&&window.history.replaceState({},``,n.toString())}var d3=bK((e,t)=>({selection:l3(),select:t=>{u3(t),e({selection:t})},resolveLatest:n=>{let r=a3(t().selection,n);r&&(u3(r),e({selection:r}))}}));if(typeof window<`u`){let e=()=>u3(d3.getState().selection);e(),document.addEventListener(`astro:page-load`,e)}var f3=6e4,p3=500,m3=1e4,h3=100,g3=new Set([`listThreads`,`getThread`,`getAvailableModels`]),_3=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`WorkbenchTransportError`}},v3=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`WorkbenchRpcError`}};function y3(){return`${location.protocol===`https:`?`wss:`:`ws:`}//${location.host}/api/v1/workbench/ws`}function b3(e={}){let t=e.url??y3(),n=new Map,r=new Map,i=null,a=0,o,s=!1,c=!1,l=0;function u(t){e.onStatusChange?.(t)}function d(t){e.onError?.(t instanceof Error?t:Error(String(t)))}function f(e,t){let r=n.get(e);r&&(n.delete(e),clearTimeout(r.timer),r.reject(t))}function p(e,t=!1){return e.phase===`sent`?new _3(`OUTCOME_UNKNOWN`,`Confirmation for ${e.frame.method} was lost. The request may have been accepted. Reconnect and check the thread before retrying.`):new _3(t?`TIMEOUT_NOT_SENT`:`NOT_CONNECTED`,`The connection is unavailable. The request was not sent.`)}function m(e){if(i&&i.readyState===WebSocket.OPEN&&n.has(e.frame.id))try{i.send(JSON.stringify(e.frame)),e.phase=`sent`}catch{f(e.frame.id,new _3(`SEND_FAILED`,`The request could not be sent.`))}}function h(e){if(i&&i.readyState===WebSocket.OPEN)try{i.send(JSON.stringify(e))}catch(e){d(e),i.close()}}function g(){if(s||o!==void 0)return;let t=Math.min((e.reconnectBaseMs??p3)*2**a,m3);a+=1,o=setTimeout(()=>{o=void 0,_()},t)}function _(){if(s||i)return;u(`connecting`);let o;try{o=e.createSocket?.(t)??new WebSocket(t)}catch(e){d(e),u(`closed`),g();return}i=o,o.onopen=()=>{if(!(s||i!==o)){a=0;for(let[e,t]of r)h({kind:`subscribe`,threadId:e,includeSnapshot:c||t.includeSnapshot});c=!0;for(let e of n.values())e.phase===`queued`&&m(e);u(`open`)}},o.onmessage=e=>{if(s||i!==o)return;let t;try{t=w3(JSON.parse(String(e.data)))}catch{d(new _3(`INVALID_SERVER_FRAME`,`The workspace sent an invalid response. Reconnecting.`)),o.close();return}if(t.kind===`event`){let e=t.event,n=r.get(e.threadId)?.listeners;for(let t of[...n??[]])try{t(e)}catch(e){d(e)}return}let a=n.get(t.id);if(a){if(t.kind===`rpc_error`){f(t.id,new v3(t.code,t.message));return}if(!T3(a.frame.method,t.result)){f(t.id,new _3(`INVALID_SERVER_FRAME`,`The workspace returned an invalid result.`));return}n.delete(t.id),clearTimeout(a.timer),a.resolve(t.result===null?void 0:t.result)}},o.onerror=()=>{},o.onclose=()=>{if(!(s||i!==o)){i=null;for(let[e,t]of n)f(e,p(t));u(`closed`),g()}}}function v(t,r){if(s)return Promise.reject(new _3(`DISPOSED`,`The workspace connection was closed.`));if(!g3.has(t)&&i?.readyState!==WebSocket.OPEN)return Promise.reject(new _3(`NOT_CONNECTED`,`The connection is unavailable. The request was not sent.`));if(n.size>=h3)return Promise.reject(new _3(`TOO_MANY_REQUESTS`,`Too many workspace requests are pending.`));let a=`rpc-${l++}`;return new Promise((i,o)=>{let s=setTimeout(()=>{let e=n.get(a);e&&f(a,p(e,!0))},e.requestTimeoutMs??f3),c={frame:{kind:`rpc`,id:a,method:t,params:r},phase:`queued`,resolve:i,reject:o,timer:s};n.set(a,c),m(c)})}return _(),{dispose(){if(!s){s=!0,o&&clearTimeout(o),o=void 0,r.clear();for(let e of n.keys())f(e,new _3(`DISPOSED`,`The workspace connection was closed.`));i&&(i.onopen=null,i.onmessage=null,i.onclose=null,i.onerror=null,i.close()),i=null}},listThreads:e=>v(`listThreads`,e?[e]:[]),createThread:e=>v(`createThread`,e?[e]:[]),getThread:e=>v(`getThread`,[e]),sendMessage:(e,t)=>v(`sendMessage`,[e,t]),cancelRun:e=>v(`cancelRun`,[e]),clearQueue:e=>v(`clearQueue`,[e]),getAvailableModels:e=>v(`getAvailableModels`,e?[e]:[]),setModel:(e,t)=>v(`setModel`,[e,t]),setThinkingLevel:(e,t)=>v(`setThinkingLevel`,[e,t]),renameThread:(e,t)=>v(`renameThread`,[e,t]),archiveThread:e=>v(`archiveThread`,[e]),unarchiveThread:e=>v(`unarchiveThread`,[e]),deleteThread:e=>v(`deleteThread`,[e]),respondToHostUiRequest:(e,t)=>v(`respondToHostUiRequest`,[e,t]),subscribe(e,t,n){if(s)return()=>{};let a=e=>t(e),o=r.get(e);return o?(o.listeners.add(a),n?.includeSnapshot!==!1&&(o.includeSnapshot=!0,i?.readyState===WebSocket.OPEN&&h({kind:`subscribe`,threadId:e,includeSnapshot:!0}))):(o={listeners:new Set,includeSnapshot:n?.includeSnapshot!==!1},r.set(e,o),o.listeners.add(a),h({kind:`subscribe`,threadId:e,includeSnapshot:o.includeSnapshot})),()=>{let t=r.get(e);t&&t.listeners.delete(a)&&t.listeners.size===0&&(r.delete(e),h({kind:`unsubscribe`,threadId:e}))}}}}function x3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function S3(e){return x3(e)&&typeof e.id==`string`&&[`idle`,`running`,`failed`].includes(String(e.status))}function C3(e){return x3(e)&&S3(e.metadata)&&Array.isArray(e.messages)}function w3(e){if(!x3(e))throw Error(`Invalid frame`);if(e.kind===`event`){let t=e.event;if(x3(t)&&typeof t.type==`string`&&typeof t.threadId==`string`&&Number.isSafeInteger(t.seq)&&Number(t.seq)>=0&&(t.type!==`snapshot`||C3(t.snapshot)))return e}else if(typeof e.id==`string`&&(e.kind===`rpc_ok`&&`result`in e||e.kind===`rpc_error`&&typeof e.message==`string`&&typeof e.code==`string`))return e;throw Error(`Invalid frame`)}function T3(e,t){switch(e){case`listThreads`:return Array.isArray(t)&&t.every(S3);case`getThread`:case`createThread`:return C3(t);case`getAvailableModels`:return Array.isArray(t)&&t.every(e=>x3(e)&&typeof e.provider==`string`&&typeof e.modelId==`string`);case`clearQueue`:return x3(t)&&Array.isArray(t.steering)&&t.steering.every(e=>typeof e==`string`)&&Array.isArray(t.followUp)&&t.followUp.every(e=>typeof e==`string`);default:return t===null}}async function E3(){try{let e=await fetch(`/api/v1/workbench/status`,{credentials:`same-origin`});return e.status===401||e.status===403?`unauthenticated`:e.ok?(await e.json()).enabled?`up`:`unconfigured`:`down`}catch{return`down`}}var D3={connecting:`reconnecting`,open:`online`,closed:`dropped`};function O3(){let{compaction:e,retry:t,contextUsage:n,readiness:r}=J$(),i=r&&r.state!==`ready`?r:null;return(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i?(0,b.jsx)(qx,{variant:`high`,children:i.message}):null,e.active?(0,b.jsx)(qx,{variant:`secondary`,children:`Compacting context…`}):null,t.active?(0,b.jsxs)(qx,{variant:`high`,children:[`Retrying (attempt `,t.attempt,`)`]}):null,n?.percent==null?null:(0,b.jsxs)(`span`,{className:`text-muted-foreground text-xs tabular-nums`,title:`${n.tokens??`?`} / ${n.contextWindow} tokens`,children:[Math.round(n.percent),`% context`]})]})}var k3=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function A3({client:e}){let t=Y$(),n=$(e=>e.threadListItem),r=n?n.externalId??n.remoteId??n.id:null,[i,a]=(0,y.useState)([]),[o,s]=(0,y.useState)(null);(0,y.useEffect)(()=>{let t=!1;return e.getAvailableModels().then(e=>{t||a(e)},()=>{}),()=>{t=!0}},[e]);let c=t?.status===`running`,l=t?.config,u=l?.provider&&l.modelId?`${l.provider}/${l.modelId}`:``,d=l?.thinkingLevel??``,f=async e=>{s(null);try{await e()}catch(e){s(e instanceof Error?e.message:String(e))}};return r?(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>0?(0,b.jsxs)(Y4,{"aria-label":`Model`,title:`Model for this conversation`,value:u,disabled:c,onChange:t=>{let[n,...i]=t.target.value.split(`/`),a=i.join(`/`);n&&a&&f(()=>e.setModel(r,{provider:n,modelId:a}))},className:`h-7 w-auto max-w-44 text-xs`,children:[!u||i.every(e=>`${e.provider}/${e.modelId}`!==u)?(0,b.jsx)(`option`,{value:u,children:u||`Select a model`}):null,i.map(e=>(0,b.jsx)(`option`,{value:`${e.provider}/${e.modelId}`,children:e.name},`${e.provider}/${e.modelId}`))]}):null,(0,b.jsxs)(Y4,{"aria-label":`Thinking level`,title:`Thinking level for this conversation`,value:d,disabled:c,onChange:t=>{let n=t.target.value;f(()=>e.setThinkingLevel(r,n))},className:`h-7 w-auto text-xs`,children:[(0,b.jsx)(`option`,{value:``,children:`Thinking…`}),k3.map(e=>(0,b.jsx)(`option`,{value:e,children:e},e))]}),o?(0,b.jsx)(`span`,{className:`text-destructive max-w-64 truncate text-xs`,title:o,children:o}):null]}):null}function j3({status:e,client:t,showTaskBoard:n,onToggleTaskBoard:r}){let i=Y$();return(0,b.jsxs)(`header`,{className:`flex flex-wrap items-center justify-between gap-2 border-b px-3 py-2`,children:[(0,b.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,b.jsx)(`strong`,{className:`truncate text-sm font-semibold`,children:i?.title??`Live Workspace`}),i?.status===`running`?(0,b.jsx)(qx,{variant:`low`,children:`streaming`}):null]}),(0,b.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,b.jsx)(O3,{}),(0,b.jsx)(A3,{client:t}),e===`open`?null:(0,b.jsx)(T4,{phase:D3[e]}),(0,b.jsxs)(o,{variant:n?`secondary`:`ghost`,size:`sm`,className:`h-7 gap-1.5 px-2 text-xs`,onClick:r,title:`Toggle Dossier Task Board`,"aria-label":`Toggle Dossier Task Board`,children:[(0,b.jsx)(Hf,{className:`size-3.5`}),(0,b.jsx)(`span`,{className:`hidden sm:inline`,children:`Tasks`})]})]})]})}function M3({initialThreadId:e}){let[t,n]=(0,y.useState)(`connecting`),[r,i]=(0,y.useState)(!0),o=(0,y.useMemo)(()=>b3({onStatusChange:n}),[]);(0,y.useEffect)(()=>()=>o.dispose(),[o]);let s=q$({client:o,includeArchived:!0,...e===void 0?{}:{initialThreadId:e},onThreadIdChange:e=>{let{selection:t,select:n}=d3.getState();e&&c3(t,e)&&n({kind:`pinned`,id:e})}}),c=(0,y.useMemo)(()=>MP({unstable_interactables:qB()}),[]);return(0,b.jsx)(DK,{runtime:s,config:c,children:(0,b.jsxs)(`div`,{className:a(`grid h-[var(--workspace-height)] min-h-120 grid-cols-1 gap-4`,r?`xl:grid-cols-[minmax(0,16rem)_minmax(0,1fr)_minmax(0,21rem)] md:grid-cols-[minmax(0,1fr)_minmax(0,20rem)]`:`md:grid-cols-[minmax(0,17rem)_minmax(0,1fr)]`),children:[(0,b.jsx)(h,{className:a(`min-h-0 overflow-hidden p-0`,r?`hidden xl:flex`:`hidden md:flex`),children:(0,b.jsx)(u4,{})}),(0,b.jsxs)(h,{className:`flex min-h-0 flex-col overflow-hidden p-0`,children:[(0,b.jsx)(j3,{status:t,client:o,showTaskBoard:r,onToggleTaskBoard:()=>i(e=>!e)}),(0,b.jsx)(J4,{}),(0,b.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,b.jsx)(H2,{})})]}),r?(0,b.jsx)(h,{className:`flex min-h-0 flex-col overflow-hidden p-0`,children:(0,b.jsx)(K4,{onClose:()=>i(!1)})}):null]})})}function N3({session:e,onStartChat:t}){return(0,b.jsxs)(h,{className:`mx-auto max-w-lg items-start gap-3 p-6`,children:[(0,b.jsx)(`h2`,{className:`text-base font-semibold`,children:`This session ran outside the live workspace`}),(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[`Session `,(0,b.jsx)(`span`,{className:`font-mono text-xs`,children:e.id}),` came from`,` `,(0,b.jsx)(`span`,{className:`font-mono text-xs`,children:e.source}),`. Its findings, runs and evidence are all here — the transcript is not, because the conversation happened in the TUI rather than over the workbench socket.`]}),(0,b.jsx)(o,{onClick:t,children:`Start a chat for this session`})]})}function P3(){let e=d3(e=>e.selection),t=tf({queryKey:[`agent-sessions`],queryFn:hx.agentSessions}),[n,r]=(0,y.useState)(null),i=s3(e,t.data?.items),a=i.kind===`external`&&n===i.session.id;if(i.kind===`loading`)return(0,b.jsx)(X4,{compact:!0,title:`Opening the live workspace…`,detail:`Resolving the current session.`});if(i.kind===`external`&&!a)return(0,b.jsx)(N3,{session:i.session,onStartChat:()=>r(i.session.id)});let o=i.kind===`thread`?i.threadId:void 0;return(0,b.jsx)(M3,{initialThreadId:o},o??`new`)}function F3({state:e}){return(0,b.jsxs)(h,{className:`mx-auto max-w-lg items-start gap-3 p-6`,children:[(0,b.jsx)(`h2`,{className:`text-base font-semibold`,children:e===`unauthenticated`?`Sign in required`:e===`unconfigured`?`Live workspace not configured`:`Live workspace unreachable`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:e===`unauthenticated`?`The live workspace is available to authenticated platform users.`:e===`unconfigured`?`Set WORKBENCH_CWD on the platform server to enable the hosted agent runtime (see docs/infra/workbench-integration.md).`:`The platform server did not answer. Check that it is running.`}),e===`unauthenticated`?(0,b.jsx)(o,{variant:`outline`,asChild:!0,children:(0,b.jsx)(`a`,{href:`/login`,children:`Sign in`})}):null]})}function I3({workflow:e}){let t=Bd(),[n,r]=(0,y.useState)(!1),[i,a]=(0,y.useState)(!1),[s,c]=(0,y.useState)(``),[l,u]=(0,y.useState)(!1),[d,f]=(0,y.useState)(!1),[m,_]=(0,y.useState)([]),v=[...new Set(e.stages.flatMap(e=>e.skillRefs))],x=e.stages.filter(e=>e.optional),S=nf({mutationFn:()=>hx.startLocalRun({workflowKey:e.key,target:s.trim(),permissionMode:d?`yolo`:`scoped`,selectedStageKeys:m,allowedActions:[`read_files`,`command_execution`]}),onSuccess:()=>void t.invalidateQueries({queryKey:[`local-runs`]})});return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(h,{className:`cursor-pointer transition-colors hover:border-primary focus-visible:outline-2 focus-visible:outline-primary`,role:`button`,tabIndex:0,onClick:()=>r(!0),onKeyDown:e=>{e.target===e.currentTarget&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),r(!0))},"aria-label":`Run ${e.name} headlessly`,children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsxs)(qx,{variant:Kx(H3(e)),children:[`Highest risk `,H3(e)]}),(0,b.jsxs)(`span`,{className:`font-mono`,children:[`v`,e.version]})]}),(0,b.jsx)(`h2`,{children:e.name}),(0,b.jsx)(`p`,{children:e.description}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.requiredCapabilities.map(e=>(0,b.jsx)(`span`,{children:e},e))}),(0,b.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3`,children:[(0,b.jsxs)(`span`,{className:`inline-flex items-center gap-2 text-sm font-medium text-primary`,children:[`Run headless `,(0,b.jsx)(_f,{size:16})]}),(0,b.jsxs)(o,{type:`button`,size:`sm`,variant:`outline`,onClick:e=>{e.stopPropagation(),a(!0)},children:[(0,b.jsx)(Jf,{size:14}),` Edit skill`]})]})]}),(0,b.jsx)(L3,{workflow:e,open:i,onOpenChange:a}),(0,b.jsx)(n1,{open:n,onOpenChange:e=>{r(e),e||(c(``),u(!1),f(!1),_([]),S.reset())},children:(0,b.jsxs)(o1,{className:`max-h-[90vh] overflow-y-auto`,children:[(0,b.jsxs)(s1,{children:[(0,b.jsxs)(l1,{children:[`Run `,e.name]}),(0,b.jsx)(u1,{children:`Start a local headless run. Each stage loads its workflow skill pack and the report appears under Audits and Reports when the run completes.`})]}),S.data?(0,b.jsx)(`div`,{className:`grid gap-3 text-sm`,children:(0,b.jsx)(z3,{runId:S.data.runId})}):(0,b.jsxs)(`form`,{className:`grid gap-4`,onSubmit:e=>{e.preventDefault(),s.trim()&&l&&!S.isPending&&S.mutate()},children:[(0,b.jsxs)(`div`,{className:`grid gap-2`,children:[(0,b.jsx)(g,{htmlFor:`workflow-target-${e.key}`,children:`Target or scope`}),(0,b.jsx)(p,{id:`workflow-target-${e.key}`,value:s,onChange:e=>c(e.target.value),placeholder:`https://example.com or an authorized asset`,required:!0})]}),(0,b.jsxs)(`div`,{className:`grid gap-1 text-sm`,children:[(0,b.jsx)(`span`,{className:`font-medium`,children:`Skill pack`}),(0,b.jsx)(`span`,{className:`text-muted-foreground`,children:v.length?v.join(`, `):`No skill refs configured`})]}),x.length>0?(0,b.jsxs)(`fieldset`,{className:`grid gap-2 text-sm`,children:[(0,b.jsx)(`legend`,{className:`font-medium`,children:`Optional stages`}),x.map(e=>(0,b.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,b.jsx)(`input`,{type:`checkbox`,checked:m.includes(e.key),onChange:t=>_(n=>t.target.checked?[...n,e.key]:n.filter(t=>t!==e.key))}),(0,b.jsxs)(`span`,{children:[e.name,` `,(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[`(`,e.risk,` risk)`]})]})]},e.key))]}):null,(0,b.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,b.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),required:!0}),(0,b.jsx)(`span`,{children:`I am authorized to assess this target. The local agent may execute commands on the gateway host.`})]}),(0,b.jsxs)(`label`,{className:`flex items-start gap-3 rounded-lg border border-destructive/50 bg-destructive/5 p-3 text-sm`,children:[(0,b.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),(0,b.jsxs)(`span`,{children:[(0,b.jsx)(`strong`,{children:`YOLO mode — no per-command approval.`}),` The agent can run arbitrary shell commands and read or change local files on the gateway host until the run ends. Commands are not sandboxed; only use this on a trusted local machine and an authorized target. Explicit prohibitions and run time/cost limits still apply.`]})]}),S.isError?(0,b.jsx)(`p`,{role:`alert`,className:`text-destructive text-sm`,children:S.error.message}):null,(0,b.jsx)(c1,{children:(0,b.jsxs)(o,{type:`submit`,disabled:!s.trim()||!l||S.isPending,children:[(0,b.jsx)(Xf,{size:16}),` `,S.isPending?`Starting…`:`Start headless run`]})})]})]})})]})}function L3({workflow:e,open:t,onOpenChange:n}){let r=tf({queryKey:[`workflow-skill`,e.key],queryFn:()=>hx.workflowSkill(e.key),enabled:t,staleTime:0}),i=r.error instanceof px?r.error.status===404?`The local gateway does not serve skill editing yet. Restart it and try again.`:r.error.status===403?`Skill editing requires an admin session with local runs enabled on this gateway.`:`Could not load this skill (${r.error.code}).`:`Could not load this skill. Check the gateway connection and try again.`,[a,s]=(0,y.useState)(``),[c,l]=(0,y.useState)(!1);(0,y.useEffect)(()=>{t&&r.data&&s(r.data.item.markdown)},[t,r.data?.item.revision]);let u=nf({mutationFn:()=>hx.saveWorkflowSkill(e.key,a,r.data.item.revision),onSuccess:e=>{l(!0),r.refetch(),s(e.item.markdown)}});return(0,b.jsx)(n1,{open:t,onOpenChange:e=>{n(e),e||(u.reset(),l(!1))},children:(0,b.jsxs)(o1,{className:`max-h-[90vh] max-w-4xl overflow-y-auto`,children:[(0,b.jsxs)(s1,{children:[(0,b.jsxs)(l1,{children:[`Edit `,e.name,` skill`]}),(0,b.jsx)(u1,{children:`Edit the Markdown instructions the agent loads during this workflow. Saved changes apply to runs when they start; runs already in progress keep their original copy.`})]}),r.isLoading?(0,b.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading skill…`}):r.isError?(0,b.jsxs)(`div`,{className:`grid gap-2`,children:[(0,b.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:i}),(0,b.jsx)(o,{type:`button`,variant:`outline`,onClick:()=>void r.refetch(),children:`Retry`})]}):r.data?(0,b.jsxs)(`div`,{className:`grid gap-3`,children:[(0,b.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[r.data.item.skillName,` · `,r.data.item.customized?`Local override`:`Bundled default`]}),(0,b.jsx)(g,{htmlFor:`workflow-skill-${e.key}`,children:`Markdown`}),(0,b.jsx)(i2,{id:`workflow-skill-${e.key}`,value:a,onChange:e=>{s(e.target.value),l(!1)},className:`min-h-[45vh] font-mono text-sm`,spellCheck:!1}),u.isError?(0,b.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:u.error.message}):null,c?(0,b.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Saved. The next run will use this version.`}):null,(0,b.jsxs)(c1,{children:[(0,b.jsx)(o,{type:`button`,variant:`outline`,onClick:()=>n(!1),children:`Close`}),(0,b.jsx)(o,{type:`button`,disabled:u.isPending||!a.trim()||a.trim()===r.data.item.markdown.trim(),onClick:()=>u.mutate(),children:u.isPending?`Saving…`:`Save skill`})]})]}):null]})})}function R3(){let e=tf({queryKey:[`local-runs`],queryFn:hx.localRuns,refetchInterval:2e3,retry:!1}),[t,n]=(0,y.useState)(null);if(e.isLoading)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Headless run activity`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Loading run history…`})]});if(e.isError)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Headless run activity`}),(0,b.jsx)(`p`,{className:`text-destructive text-sm`,children:`Could not load local run status. Local runs require an admin session on this gateway.`})]});let r=e.data?.items??[];if(!r.length)return(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:`Headless run activity`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`No headless runs yet. Select a workflow above to start one.`})]});let i=r.find(e=>e.runId===t)??r[0];return(0,b.jsxs)(h,{className:`grid gap-4`,children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{children:`Headless run activity`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Live stage progress, retained after you close the launch dialog.`})]}),(0,b.jsx)(`select`,{className:`max-w-full rounded-md border bg-transparent px-2 py-1 text-sm`,value:i.runId,onChange:e=>n(e.target.value),children:r.map(e=>(0,b.jsxs)(`option`,{value:e.runId,children:[e.workflowKey,` · `,e.target,` · `,e.status]},e.runId))})]}),(0,b.jsx)(B3,{run:i})]})}function z3({runId:e}){let t=tf({queryKey:[`local-run`,e],queryFn:()=>hx.localRun(e),refetchInterval:e=>![`completed`,`partial`,`failed`,`cancelled`].includes(e.state.data?.item.status??``)&&2e3,retry:2});return t.isError?(0,b.jsx)(`p`,{role:`alert`,className:`text-destructive`,children:`Could not load run progress.`}):t.data?(0,b.jsx)(B3,{run:t.data.item}):(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`Starting run and loading its stages…`})}function B3({run:e}){let t=e.stages.filter(e=>![`pending`,`running`].includes(e.status)).length;return(0,b.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,b.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,b.jsx)(V3,{status:e.status}),(0,b.jsx)(`strong`,{children:e.workflowKey}),e.permissionMode===`yolo`?(0,b.jsx)(qx,{variant:`high`,children:`YOLO mode`}):null,(0,b.jsxs)(`span`,{className:`text-muted-foreground`,children:[e.status,` · `,t,`/`,e.stages.length,` stages · `,e.runId.slice(0,8)]})]}),(0,b.jsxs)(`p`,{className:`break-all text-muted-foreground`,children:[`Target: `,e.target]}),(0,b.jsx)(`div`,{className:`h-2 overflow-hidden rounded-full bg-muted`,role:`progressbar`,"aria-valuenow":t,"aria-valuemin":0,"aria-valuemax":e.stages.length,children:(0,b.jsx)(`div`,{className:`h-full bg-primary transition-all`,style:{width:`${e.stages.length?t/e.stages.length*100:0}%`}})}),(0,b.jsx)(`ol`,{className:`grid gap-0 border-l pl-4`,children:e.stages.map(e=>(0,b.jsxs)(`li`,{className:`relative flex items-start gap-3 border-b py-2 last:border-b-0`,children:[(0,b.jsx)(`span`,{className:`absolute -left-[1.43rem] bg-card`,children:(0,b.jsx)(V3,{status:e.status})}),(0,b.jsxs)(`span`,{className:`min-w-0`,children:[(0,b.jsx)(`strong`,{children:e.name}),(0,b.jsx)(`span`,{className:`ml-2 text-muted-foreground`,children:e.status}),e.summary?(0,b.jsx)(`span`,{className:`mt-1 block text-muted-foreground`,children:e.summary}):null]})]},e.key))}),e.error?(0,b.jsx)(`p`,{role:`alert`,className:`text-destructive`,children:e.error}):null,e.reportAvailable?(0,b.jsx)(o,{asChild:!0,size:`sm`,variant:`outline`,children:(0,b.jsxs)(`a`,{href:`/reports`,children:[`View report `,(0,b.jsx)(_f,{size:16})]})}):e.status===`running`?(0,b.jsx)(`p`,{className:`text-muted-foreground`,children:`This view updates every two seconds. The report appears after completion.`}):null]})}function V3({status:e}){return e===`running`?(0,b.jsx)(Uf,{size:17,className:`animate-spin text-primary`,"aria-label":`Running`}):e===`completed`||e===`succeeded`?(0,b.jsx)(Df,{size:17,className:`text-green-600`,"aria-label":`Succeeded`}):[`failed`,`blocked`,`interrupted`,`partial`,`cancelled`].includes(e)?(0,b.jsx)(Of,{size:17,className:`text-destructive`,"aria-label":e}):(0,b.jsx)(kf,{size:17,className:`text-muted-foreground`,"aria-label":e})}function H3(e){return e.stages.some(e=>e.risk===`R2`)?`R2`:e.stages.some(e=>e.risk===`R1`)?`R1`:`R0`}function U3({eyebrow:e,title:t,description:n,actions:r,className:i}){return(0,b.jsxs)(`header`,{className:a(`flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between`,i),children:[(0,b.jsxs)(`div`,{className:`min-w-0`,children:[e?(0,b.jsx)(`p`,{className:`text-muted-foreground mt-0 mb-2 text-2xs font-semibold tracking-[0.12em] uppercase`,children:e}):null,t?(0,b.jsx)(`h1`,{children:t}):null,n?(0,b.jsx)(`p`,{className:`mt-2 mb-0 max-w-[72ch]`,children:n}):null]}),r?(0,b.jsx)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:r}):null]})}function W3({sessions:e,value:t,onChange:n,className:r,id:i=`agent-session`}){let o=e[0];return(0,b.jsxs)(`div`,{className:a(`flex min-w-0 items-center gap-2`,r),children:[(0,b.jsx)(`label`,{className:`text-muted-foreground shrink-0 text-[13px]`,htmlFor:i,children:`Session`}),(0,b.jsxs)(Y4,{"aria-label":`Agent session`,className:`w-auto min-w-0 max-w-[22rem] text-[13px]`,id:i,onChange:e=>n(e.target.value),value:t??`latest`,children:[(0,b.jsx)(`option`,{value:`latest`,children:o?`Latest — ${o.title||`Session`}`:`Latest session`}),(0,b.jsx)(`option`,{value:`all`,children:`All workspace sessions`}),e.map(e=>(0,b.jsxs)(`option`,{value:e.id,children:[e.title||`Session`,` · `,e.findingCount??0,` findings · `,e.runCount??0,` runs`]},e.id))]})]})}function G3({section:e}){return(0,b.jsx)(Vd,{client:gx,children:(0,b.jsx)(J3,{section:e})})}function K3(){let e=tf({queryKey:[`workbench-status`],queryFn:E3,retry:1,staleTime:15e3});return e.isLoading?(0,b.jsx)(X4,{compact:!0,title:`Connecting to the live workspace…`,detail:`Checking the platform agent runtime.`}):e.data&&e.data!==`up`?(0,b.jsx)(F3,{state:e.data}):(0,b.jsx)(P3,{})}function q3(){return(0,b.jsx)(Vd,{client:gx,children:(0,b.jsx)(K3,{})})}function J3({section:e}){let t=d3(e=>e.selection),n=d3(e=>e.select),r=d3(e=>e.resolveLatest),i=t3(t),a=e=>n(n3(e)),[s,c]=(0,y.useState)(()=>typeof window<`u`?new URLSearchParams(window.location.search).get(`finding`):null),l=e=>{if(c(e),typeof window<`u`){let t=new URL(window.location.href);e?t.searchParams.set(`finding`,e):t.searchParams.delete(`finding`),window.history.replaceState({},``,t.toString())}},u=tf({queryKey:[`agent-sessions`],queryFn:hx.agentSessions,enabled:e===`runs`||e===`agent`||e===`findings`||e===`dashboard`||e===`lifecycle`,refetchInterval:2e3});(0,y.useEffect)(()=>{u.data?.items&&r(u.data.items)},[u.data?.items,r]);let d=i3(t,u.data?.items),f=tf({queryKey:[`workflows`],queryFn:hx.workflows,enabled:e===`workflows`||e===`assessments`}),m=tf({queryKey:[`overview`,d],queryFn:()=>hx.overview(d),enabled:e===`dashboard`||e===`assessments`||e===`lifecycle`,refetchInterval:2e3}),_=tf({queryKey:[`runs`,d],queryFn:()=>hx.runs({sessionId:d}),enabled:e===`runs`,refetchInterval:2e3}),v=tf({queryKey:[`projects`],queryFn:hx.projects,enabled:e===`assessments`}),x=tf({queryKey:[`assessment-profiles`],queryFn:hx.assessmentProfiles,enabled:e===`assessments`}),S=tf({queryKey:[`findings`,d],queryFn:()=>hx.findings({sessionId:d}),enabled:e===`findings`||e===`dashboard`||e===`lifecycle`||e===`reports`,refetchInterval:6e3}),C=tf({queryKey:[`agent-session`,d],queryFn:()=>hx.agentSession(d),enabled:e===`runs`&&!!d,refetchInterval:2e3}),w=tf({queryKey:[`governance-events`],queryFn:hx.governanceEvents,enabled:e===`reports`}),T=tf({queryKey:[`workers`],queryFn:hx.workers,enabled:e===`administration`}),E=tf({queryKey:[`tokens`],queryFn:hx.tokens,enabled:e===`administration`}),[D,O]=(0,y.useState)(``),[k,A]=(0,y.useState)(30),[j,M]=(0,y.useState)(!1),[N,ee]=(0,y.useState)(null),[te,ne]=(0,y.useState)(!1),[re,ie]=(0,y.useState)(!1),[ae,oe]=(0,y.useState)(null),[se,ce]=(0,y.useState)(null);async function le(e){e.preventDefault(),M(!0),oe(null);try{let e=await hx.mintToken({label:D.trim()||`CLI Token`,expiresInDays:k});ee(e),O(``),gx.invalidateQueries({queryKey:[`tokens`]})}catch(e){oe(e instanceof Error?e.message:`Failed to mint token`)}finally{M(!1)}}async function ue(e){if(confirm(`Are you sure you want to revoke this token? Any CLI session or automation using it will immediately lose access.`)){ce(e);try{await hx.revokeToken(e),gx.invalidateQueries({queryKey:[`tokens`]})}catch(e){alert(e instanceof Error?e.message:`Failed to revoke token`)}finally{ce(null)}}}let de=[...e===`workflows`||e===`assessments`?[f]:[],...e===`dashboard`?[m,S]:[],...e===`lifecycle`?[m,S]:[],...e===`runs`?[_,u]:[],...e===`runs`&&d?[C]:[],...e===`assessments`?[m,v,x]:[],...e===`findings`?[S,u]:[],...e===`reports`?[w,S]:[],...e===`administration`?[T,E]:[]];if(de.some(e=>e.isLoading))return(0,b.jsx)(X4,{title:`Loading workspace`,detail:`Reading durable platform state…`});let P=de.find(e=>e.isError);if(P){let e=P.error,t=e&&typeof e==`object`&&`status`in e&&e.status===401;return(0,b.jsx)(X4,{title:`Platform unavailable`,detail:e instanceof Error?e.message:`The platform could not be reached.`,action:t?(0,b.jsx)(o,{asChild:!0,children:(0,b.jsx)(`a`,{href:`/login`,children:`Sign in`})}):(0,b.jsxs)(o,{onClick:()=>void P.refetch(),children:[(0,b.jsx)(Qf,{}),` Retry`]})})}let fe=jx(S.data?.findings??[]),pe=fe.filter(Ox);if(e===`dashboard`){let e=Object.fromEntries(xx.map(e=>[e,pe.filter(t=>t.severity===e).length])),t=m.data?.runs??{},n=Object.values(t).reduce((e,t)=>e+t,0),r=(t.queued??0)+(t.running??0),s=Mx(fe),c=fe.filter(e=>e.status===`confirmed`||e.status===`verified`);return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(U3,{actions:(0,b.jsx)(W3,{onChange:a,sessions:u.data?.items??[],value:i})}),(0,b.jsxs)(Px,{children:[(0,b.jsx)(Fx,{hero:!0,tone:s??void 0,label:`Client posture`,value:s?wx[s].toUpperCase():`NO CONFIRMED RISK`,meta:s?`Worst confirmed finding across ${c.length} confirmed finding${c.length===1?``:`s`}.`:`No finding has been confirmed yet.`}),(0,b.jsx)(Fx,{label:`Open findings`,value:pe.length,meta:`${fe.length-pe.length} resolved`}),(0,b.jsx)(Fx,{label:`Critical / High`,value:`${e.critical} / ${e.high}`,meta:`${c.length} confirmed overall`}),(0,b.jsx)(Fx,{label:`Assessments`,value:n,meta:`${r} in flight`})]}),(0,b.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[1.35fr_1fr]`,children:[(0,b.jsx)(Nx,{title:`Open findings by severity`,sub:`${pe.length} active`,children:(0,b.jsx)(Ix,{counts:e})}),(0,b.jsx)(Nx,{title:`Findings by data-lifecycle stage`,sub:`where the risk lives`,children:(0,b.jsx)(Lx,{findings:pe})})]}),(0,b.jsx)(Nx,{title:`Highest-priority open findings`,sub:(0,b.jsx)(`a`,{className:`link-more`,href:`/findings`,children:`View all`}),children:(0,b.jsx)(Rx,{findings:Dx(pe).slice(0,5),onSelect:e=>{window.location.href=`/findings?finding=${encodeURIComponent(e.id)}`},emptyLabel:`No open findings. Agent runs report findings through the report_finding tool; none have been ingested yet.`})}),(0,b.jsxs)(`section`,{"aria-labelledby":`active-runs`,children:[(0,b.jsxs)(`div`,{className:`mb-4 flex items-baseline justify-between gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`p`,{className:`text-muted-foreground mt-0 mb-1 text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Operations`}),(0,b.jsx)(`h2`,{id:`active-runs`,children:`Active runs`})]}),(0,b.jsxs)(`a`,{className:`link-more`,href:`/runs`,children:[`View all `,(0,b.jsx)(_f,{"aria-hidden":`true`})]})]}),m.data?.recentRuns.filter(e=>e.status===`queued`||e.status===`running`).length?(0,b.jsx)(e6,{runs:m.data.recentRuns.filter(e=>e.status===`queued`||e.status===`running`)}):(0,b.jsx)(X4,{compact:!0,title:`No active runs`,detail:`Select a target endpoint to initialize a governed assessment.`,action:(0,b.jsx)(o,{asChild:!0,children:(0,b.jsx)(`a`,{href:`/assessments`,children:`New assessment`})})})]})]})}if(e===`lifecycle`)return(0,b.jsx)(Q3,{findings:pe});if(e===`workflows`)return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(U3,{title:`Workflows`}),(0,b.jsx)(R3,{}),(0,b.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:f.data?.items.map(e=>(0,b.jsx)(I3,{workflow:e},e.key))})]});if(e===`runs`){if(d&&C.data){let e=C.data,t=e.operations.filter(e=>e.status!==`completed`).length;return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsxs)(`header`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`p`,{className:`text-2xs font-semibold tracking-[0.12em] uppercase text-muted-foreground`,children:`Session`}),(0,b.jsx)(`h1`,{children:e.session.title}),(0,b.jsx)(`p`,{children:`Recorded tool calls and findings for this agent session, newest run last.`})]}),(0,b.jsx)(o,{variant:`outline`,onClick:()=>n(e3),children:`All sessions`})]}),(0,b.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,b.jsx)(Z3,{label:`Status`,value:r6(e.session.status),detail:`${e.session.runCount} run${e.session.runCount===1?``:`s`} in this session`}),(0,b.jsx)(Z3,{label:`Tool calls`,value:String(e.session.operationCount),detail:t?`${t} did not complete`:`All completed`}),(0,b.jsx)(Z3,{label:`Findings`,value:String(e.session.findingCount),detail:e.session.findingCount?`Ingested through report_finding`:`None reported in this session`})]}),(0,b.jsxs)(`div`,{className:`grid items-start gap-5 lg:grid-cols-[minmax(0,1.35fr)_minmax(280px,0.65fr)]`,"aria-live":`polite`,children:[(0,b.jsxs)(`section`,{"aria-labelledby":`agent-transcript`,children:[(0,b.jsx)(`h2`,{id:`agent-transcript`,children:`Transcript`}),e.operations.length?(0,b.jsx)(`div`,{className:`grid gap-2.5`,children:e.operations.map(e=>(0,b.jsxs)(`article`,{className:`bg-card rounded-lg border p-4 [&_p]:mt-2 [&_p]:mb-0 [&_p]:text-[13px] [&_p]:leading-relaxed [&_p]:break-words [&_p]:text-muted-foreground [&_p.font-mono]:max-h-28 [&_p.font-mono]:overflow-auto [&_p.font-mono]:rounded-sm [&_p.font-mono]:bg-[var(--plane)] [&_p.font-mono]:px-2.5 [&_p.font-mono]:py-2 [&_p.font-mono]:text-xs [&_p.font-mono]:whitespace-pre-wrap`,children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(`strong`,{children:e.tool}),(0,b.jsx)(qx,{variant:Kx(e.status),children:r6(e.outcome)})]}),(0,b.jsxs)(`p`,{children:[e.runtime,` · `,new Date(e.startedAt).toLocaleTimeString(),e.completedAt?` · ${e.completedAt-e.startedAt}ms`:``]}),e.outputPreview?(0,b.jsx)(`p`,{className:`font-mono`,children:e.outputPreview.slice(0,400)}):null]},e.id))}):(0,b.jsx)(X4,{compact:!0,title:`Waiting for agent output`,detail:`Tool calls appear here as the runtime records them.`})]}),(0,b.jsxs)(`section`,{"aria-labelledby":`agent-runs`,children:[(0,b.jsx)(`h2`,{id:`agent-runs`,children:`Runs`}),(0,b.jsx)(`div`,{className:`grid gap-2.5`,children:e.runs.map(e=>(0,b.jsxs)(`article`,{className:`bg-card rounded-lg border p-4 [&_p]:mt-2 [&_p]:mb-0 [&_p]:text-[13px] [&_p]:leading-relaxed [&_p]:break-words [&_p]:text-muted-foreground`,children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(qx,{variant:Kx(e.status),children:r6(e.status)}),(0,b.jsx)(`span`,{className:`font-mono`,children:e.id.slice(0,12)})]}),(0,b.jsxs)(`p`,{children:[e.kind,` · `,new Date(e.createdAt).toLocaleString()]})]},e.id))})]})]}),e.findings.length?(0,b.jsxs)(`section`,{"aria-labelledby":`agent-findings`,children:[(0,b.jsx)(`h2`,{id:`agent-findings`,children:`Findings from this session`}),(0,b.jsx)(t6,{findings:e.findings})]}):null]})}return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(U3,{title:`Runs`}),(0,b.jsxs)(`section`,{"aria-labelledby":`all-runs`,children:[(0,b.jsx)(`h2`,{id:`all-runs`,className:`mb-3`,children:`Runs`}),_.data?.runs.length?(0,b.jsx)(e6,{runs:_.data.runs}):(0,b.jsx)(X4,{compact:!0,title:`No runs yet`,detail:`Initialize an assessment to start the first governed run.`})]}),(0,b.jsxs)(`section`,{"aria-labelledby":`all-sessions`,children:[(0,b.jsx)(`h2`,{id:`all-sessions`,className:`mb-3`,children:`Sessions`}),u.data?.items.length?(0,b.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:u.data.items.map(e=>(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(qx,{variant:Kx(e.status),children:r6(e.status)}),(0,b.jsx)(`span`,{className:`font-mono`,children:e.source})]}),(0,b.jsx)(`h2`,{children:e.title}),(0,b.jsxs)(`p`,{children:[e.runCount,` run`,e.runCount===1?``:`s`,` · `,e.operationCount,` tool call`,e.operationCount===1?``:`s`,` · `,e.findingCount,` finding`,e.findingCount===1?``:`s`]}),(0,b.jsxs)(`p`,{children:[`Last active `,new Date(e.lastActivityAt).toLocaleString()]}),(0,b.jsx)(o,{variant:`outline`,onClick:()=>n({kind:`pinned`,id:e.id}),children:`Open session`})]},e.id))}):(0,b.jsx)(X4,{compact:!0,title:`No agent sessions`,detail:`Sessions appear here once an agent run reaches the platform.`})]})]})}if(e===`assessments`)return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(U3,{title:`Assessments`}),(0,b.jsx)(Vj,{}),(0,b.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[(0,b.jsx)(Z3,{label:`Projects`,value:String(v.data?.items.length??0),detail:`Active workspace project boundaries`}),(0,b.jsx)(Z3,{label:`Target bindings`,value:String(x.data?.items.length??0),detail:`Bound endpoints and infrastructure`}),(0,b.jsx)(Z3,{label:`Recent runs`,value:String(m.data?.recentRuns.length??0),detail:`Assessment runs recorded in this workspace`})]}),x.data?.items.length?(0,b.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:x.data.items.map(e=>(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(qx,{variant:Kx(e.allowedRisk),children:e.allowedRisk}),(0,b.jsxs)(`span`,{className:`font-mono`,children:[`rev `,e.revision]})]}),(0,b.jsx)(`h2`,{children:e.targets[0]?.displayName??e.targets[0]?.locator??`Bound target`}),(0,b.jsxs)(`p`,{children:[e.requiredWorkerClass,` worker · immutable launch policy`]}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.requiredCapabilities.map(e=>(0,b.jsx)(`span`,{children:e},e))})]},e.id))}):(0,b.jsx)(X4,{compact:!0,title:`No targets yet`,detail:`Configure a new target endpoint from the dashboard to initialize assessment tracking.`})]});if(e===`findings`){if(s)return(0,b.jsx)(`div`,{className:`grid gap-6`,children:(0,b.jsx)(Jj,{findingId:s,onBack:()=>l(null)})});let e=Object.fromEntries(xx.map(e=>[e,pe.filter(t=>t.severity===e).length])),r=n6(pe),c=fe.filter(e=>!Ox(e)),f=u.data?.items??[],p=f.find(e=>e.id===d),m=t.kind===`all`&&f.length>0;return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(U3,{actions:(0,b.jsx)(W3,{id:`findings-session`,onChange:a,sessions:u.data?.items??[],value:i}),title:`Findings`}),m?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Choose an agent session to review its findings. Local headless runs are listed separately below.`}),(0,b.jsx)(`div`,{className:`grid gap-3 md:grid-cols-2`,children:f.map(e=>(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{children:e.title||`Agent session`}),(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[e.findingCount,` finding`,e.findingCount===1?``:`s`,` · `,e.runCount,` run`,e.runCount===1?``:`s`,` · `,e.source]})]}),(0,b.jsx)(qx,{variant:Kx(e.status),children:r6(e.status)})]}),(0,b.jsx)(o,{variant:`outline`,size:`sm`,onClick:()=>n({kind:`pinned`,id:e.id}),children:`View session findings`})]},e.id))}),fe.length?(0,b.jsxs)(`details`,{className:`rounded-xl border bg-card p-4`,children:[(0,b.jsxs)(`summary`,{className:`cursor-pointer font-medium`,children:[`Workspace-wide findings · `,fe.length,` total`]}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`This combined view can include findings associated with more than one session.`}),(0,b.jsx)(Rx,{findings:Dx(fe),onSelect:e=>l(e.id)})]}):null]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(h,{children:[(0,b.jsx)(`h2`,{children:p?.title||(d?`Selected agent session`:`Workspace findings`)}),(0,b.jsxs)(`p`,{className:`text-muted-foreground text-sm`,children:[fe.length,` total · `,pe.length,` open · `,c.length,` resolved`,p?` · ${p.runCount} run${p.runCount===1?``:`s`}`:null]})]}),pe.length?(0,b.jsx)(b.Fragment,{children:r.map(({asset:e,items:t})=>(0,b.jsx)(Nx,{title:e,sub:`${t.length} finding${t.length===1?``:`s`}`,children:(0,b.jsx)(Rx,{findings:Dx(t),onSelect:e=>l(e.id)})},e))}):(0,b.jsx)(X4,{compact:!0,title:c.length?`No open findings`:`No findings in this session`,detail:c.length?`Resolved findings are available below.`:`Findings reported by this agent session will appear here. Local headless runs are listed separately below.`}),c.length?(0,b.jsxs)(`details`,{className:`rounded-xl border bg-card p-4`,children:[(0,b.jsxs)(`summary`,{className:`cursor-pointer font-medium`,children:[`Resolved findings · `,c.length]}),(0,b.jsx)(Rx,{findings:Dx(c),onSelect:e=>l(e.id)})]}):null,fe.length?(0,b.jsxs)(`details`,{className:`rounded-xl border bg-card p-4`,children:[(0,b.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:`Analysis views · severity, lifecycle and control matrix`}),(0,b.jsxs)(`div`,{className:`mt-4 grid gap-4 lg:grid-cols-[1.35fr_1fr]`,children:[(0,b.jsx)(Nx,{title:`Open findings by severity`,sub:`${pe.length} active`,children:(0,b.jsx)(Ix,{counts:e})}),(0,b.jsx)(Nx,{title:`Findings by data-lifecycle stage`,sub:`where the risk lives`,children:(0,b.jsx)(Lx,{findings:pe})})]}),(0,b.jsx)(`div`,{className:`mt-4`,children:(0,b.jsx)(Nx,{title:`Control coverage`,sub:`pillar × lifecycle stage — worst open severity per cell`,children:(0,b.jsx)(Bx,{findings:pe,onSelectStage:()=>{}})})})]}):null]}),(0,b.jsx)(Hj,{})]})}return e===`agent`?(0,b.jsx)(U3,{actions:(0,b.jsx)(W3,{id:`console-session`,onChange:a,sessions:u.data?.items??[],value:i}),title:`Console`}):e===`reports`?(0,b.jsxs)(`div`,{className:`grid gap-8`,children:[(0,b.jsx)(U3,{title:`Reports`}),(0,b.jsx)(Bj,{}),(0,b.jsx)($3,{events:w.data?.items??[],findings:fe})]}):e===`administration`?(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(U3,{title:`Administration & Access`}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`div`,{className:`flex items-start justify-between gap-4`,children:(0,b.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`0.5rem`},children:[(0,b.jsx)(Vf,{size:18}),(0,b.jsx)(`h2`,{children:`Personal Access Tokens & CLI Sign-In`})]})}),(0,b.jsx)(`p`,{style:{marginTop:`0.25rem`,marginBottom:`1rem`},children:`Mint tokens to authenticate the Kifaru CLI or automated CI/CD pipelines without passwords.`}),N&&(0,b.jsxs)(`div`,{style:{background:`rgba(16, 185, 129, 0.12)`,border:`1px solid rgba(16, 185, 129, 0.4)`,borderRadius:`var(--radius-xl)`,padding:`1rem`,marginBottom:`1.25rem`},children:[(0,b.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,marginBottom:`0.5rem`},children:[(0,b.jsxs)(`strong`,{style:{color:`var(--good)`,display:`flex`,alignItems:`center`,gap:`0.4rem`},children:[(0,b.jsx)(Sf,{size:16}),` Token Minted: `,N.label]}),(0,b.jsx)(o,{variant:`ghost`,size:`sm`,onClick:()=>ee(null),children:`Dismiss`})]}),(0,b.jsx)(`p`,{style:{fontSize:`0.85rem`,color:`var(--ink-2)`,marginBottom:`0.75rem`},children:`Make sure to copy your Personal Access Token now. You will not be able to see it again!`}),(0,b.jsxs)(`div`,{style:{display:`grid`,gap:`0.75rem`},children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(g,{className:`text-muted-foreground mb-1 block text-2xs font-semibold tracking-[0.12em] uppercase`,children:`Token Value`}),(0,b.jsxs)(`div`,{style:{display:`flex`,gap:`0.5rem`,alignItems:`center`},children:[(0,b.jsx)(p,{type:`text`,readOnly:!0,value:N.token,className:`flex-1 font-mono`}),(0,b.jsxs)(o,{variant:`outline`,size:`sm`,onClick:()=>{navigator.clipboard.writeText(N.token),ne(!0),setTimeout(()=>ne(!1),2e3)},children:[te?(0,b.jsx)(Sf,{size:14}):(0,b.jsx)(Mf,{size:14}),te?`Copied`:`Copy Token`]})]})]}),(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`label`,{className:`text-2xs font-semibold tracking-[0.12em] uppercase text-muted-foreground`,style:{display:`block`,marginBottom:`0.25rem`},children:`CLI Sign-In Command`}),(0,b.jsxs)(`div`,{style:{display:`flex`,gap:`0.5rem`,alignItems:`center`},children:[(0,b.jsxs)(`code`,{className:`font-mono`,style:{flex:1,borderRadius:`var(--radius-lg)`,padding:`0.45rem 0.65rem`,fontSize:`0.82rem`,color:`var(--primary)`},children:[`kifaru session login --token `,N.token]}),(0,b.jsxs)(o,{variant:`outline`,size:`sm`,onClick:()=>{navigator.clipboard.writeText(`kifaru session login --token `+N.token),ie(!0),setTimeout(()=>ie(!1),2e3)},children:[re?(0,b.jsx)(Sf,{size:14}):(0,b.jsx)(Mf,{size:14}),re?`Copied`:`Copy Command`]})]})]})]})]}),(0,b.jsxs)(`form`,{onSubmit:le,style:{display:`flex`,flexWrap:`wrap`,alignItems:`flex-end`,gap:`0.75rem`,background:`var(--surface-2)`,border:`1px solid var(--border)`,borderRadius:`var(--radius-xl)`,padding:`0.85rem`,marginBottom:`1.25rem`},children:[(0,b.jsxs)(`div`,{style:{flex:`1 1 220px`},children:[(0,b.jsx)(g,{htmlFor:`mint-label`,className:`mb-1.5 block text-sm`,children:`Token Label`}),(0,b.jsx)(p,{id:`mint-label`,type:`text`,placeholder:`e.g. Workstation CLI, CI Runner`,value:D,onChange:e=>O(e.target.value)})]}),(0,b.jsxs)(`div`,{style:{width:`160px`},children:[(0,b.jsx)(g,{htmlFor:`mint-expiry`,className:`mb-1.5 block text-sm`,children:`Expiration`}),(0,b.jsxs)(Y4,{id:`mint-expiry`,value:k,onChange:e=>A(Number(e.target.value)),children:[(0,b.jsx)(`option`,{value:30,children:`30 days`}),(0,b.jsx)(`option`,{value:60,children:`60 days`}),(0,b.jsx)(`option`,{value:90,children:`90 days`}),(0,b.jsx)(`option`,{value:365,children:`1 year`}),(0,b.jsx)(`option`,{value:0,children:`Never expires`})]})]}),(0,b.jsxs)(o,{type:`submit`,disabled:j,size:`sm`,children:[(0,b.jsx)(Zf,{size:15}),j?`Minting…`:`Mint Token`]})]}),ae&&(0,b.jsx)(`p`,{className:`text-destructive text-sm`,style:{marginBottom:`1rem`},children:ae}),(0,b.jsxs)(`div`,{style:{marginTop:`0.5rem`},children:[(0,b.jsx)(`h3`,{style:{fontSize:`0.95rem`,fontWeight:600,marginBottom:`0.5rem`},children:`Active Tokens`}),E.data?.items.length?(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Label`}),(0,b.jsx)(`th`,{children:`Token Prefix`}),(0,b.jsx)(`th`,{children:`Role`}),(0,b.jsx)(`th`,{children:`Created`}),(0,b.jsx)(`th`,{children:`Expires`}),(0,b.jsx)(`th`,{children:`Action`})]})}),(0,b.jsx)(`tbody`,{children:E.data.items.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{style:{fontWeight:600,color:`var(--ink)`},children:e.label}),(0,b.jsxs)(`td`,{className:`font-mono`,children:[e.prefix,`…`]}),(0,b.jsx)(`td`,{children:(0,b.jsx)(qx,{variant:Kx(`confirmed`),children:e.role})}),(0,b.jsx)(`td`,{children:new Date(e.createdAt).toLocaleDateString()}),(0,b.jsx)(`td`,{children:e.expiresAt?new Date(e.expiresAt).toLocaleDateString():`Never`}),(0,b.jsx)(`td`,{children:(0,b.jsxs)(o,{variant:`destructive`,size:`sm`,disabled:se===e.id,onClick:()=>ue(e.id),children:[(0,b.jsx)(up,{size:13}),se===e.id?`Revoking…`:`Revoke`]})})]},e.id))})]})}):(0,b.jsx)(`p`,{style:{color:`var(--ink-3)`,fontSize:`0.85rem`,fontStyle:`italic`},children:`No personal access tokens minted yet. Use the form above to create one.`})]}),(0,b.jsxs)(`div`,{style:{marginTop:`1.25rem`,background:`var(--surface-2)`,border:`1px dashed var(--border)`,borderRadius:`var(--radius-xl)`,padding:`0.85rem 1rem`,display:`flex`,alignItems:`center`,gap:`0.75rem`},children:[(0,b.jsx)(op,{size:20}),(0,b.jsxs)(`div`,{style:{fontSize:`0.82rem`,color:`var(--ink-3)`},children:[(0,b.jsx)(`strong`,{style:{color:`var(--ink)`},children:`Interactive Browser Sign-in:`}),` You can also run`,` `,(0,b.jsx)(`code`,{className:`font-mono`,style:{color:`var(--primary)`},children:`kifaru session login`}),` `,`in your terminal to authenticate interactively through your browser.`]})]})]}),(0,b.jsxs)(`div`,{style:{marginTop:`1rem`},children:[(0,b.jsx)(`h2`,{style:{fontSize:`1.15rem`,marginBottom:`0.75rem`},children:`Execution Workers`}),T.data?.items.length?(0,b.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:T.data.items.map(e=>(0,b.jsxs)(h,{children:[(0,b.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,b.jsx)(qx,{variant:Kx(e.status),children:r6(e.status)}),(0,b.jsx)(`span`,{className:`font-mono`,children:e.status})]}),(0,b.jsx)(`h2`,{children:e.name}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.capabilities.map(e=>(0,b.jsx)(`span`,{children:e},e))})]},e.id))}):(0,b.jsx)(X4,{compact:!0,title:`No workers registered`,detail:`Connect an execution worker before launching capability-bound workflows.`})]})]}):e===`billing`?(0,b.jsx)(Y3,{}):e===`team`?(0,b.jsx)(X3,{}):(0,b.jsx)(X4,{title:`Not found`,detail:`This view does not exist.`})}function Y3(){return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(U3,{title:`Billing & Subscription`}),(0,b.jsxs)(`div`,{className:`grid gap-6 md:grid-cols-2`,children:[(0,b.jsxs)(h,{className:`p-6`,children:[(0,b.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,b.jsxs)(`span`,{className:`text-2xs font-semibold uppercase tracking-[0.12em] text-muted-foreground flex items-center gap-1.5`,children:[(0,b.jsx)(Nf,{className:`size-3.5`}),` Current Plan`]}),(0,b.jsx)(qx,{variant:`success`,children:`Active`})]}),(0,b.jsx)(`div`,{className:`text-2xl font-bold mb-1`,children:`Developer Pro`}),(0,b.jsx)(`p`,{className:`text-sm text-muted-foreground mb-6`,children:`Continuous assurance scans with dedicated runtime concurrency.`}),(0,b.jsxs)(`div`,{className:`space-y-2 border-t pt-4 text-xs text-muted-foreground`,children:[(0,b.jsxs)(`div`,{className:`flex justify-between`,children:[(0,b.jsx)(`span`,{children:`Parallel agent jobs`}),(0,b.jsx)(`span`,{className:`font-semibold text-foreground`,children:`8 concurrent`})]}),(0,b.jsxs)(`div`,{className:`flex justify-between`,children:[(0,b.jsx)(`span`,{children:`Finding retention`}),(0,b.jsx)(`span`,{className:`font-semibold text-foreground`,children:`365 days`})]}),(0,b.jsxs)(`div`,{className:`flex justify-between`,children:[(0,b.jsx)(`span`,{children:`Next renewal`}),(0,b.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Oct 1, 2026`})]})]})]}),(0,b.jsxs)(h,{className:`p-6 flex flex-col justify-between`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsxs)(`div`,{className:`flex items-center justify-between mb-4`,children:[(0,b.jsx)(`span`,{className:`text-2xs font-semibold uppercase tracking-[0.12em] text-muted-foreground`,children:`Scan Credits`}),(0,b.jsx)(`span`,{className:`text-xs font-mono text-[var(--good)] font-semibold`,children:`Active Balance`})]}),(0,b.jsx)(`div`,{className:`text-2xl font-bold font-mono mb-1`,children:`$240.00`}),(0,b.jsx)(`p`,{className:`text-sm text-muted-foreground mb-4`,children:`Prepaid compute balance for high-concurrency automated audits.`})]}),(0,b.jsxs)(`div`,{className:`flex gap-2`,children:[(0,b.jsx)(o,{size:`sm`,className:`flex-1`,children:`Add Balance`}),(0,b.jsx)(o,{size:`sm`,variant:`outline`,children:`Change Plan`})]})]})]}),(0,b.jsxs)(h,{className:`p-6`,children:[(0,b.jsx)(`h3`,{className:`text-sm font-semibold mb-4`,children:`Recent Invoices`}),(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-lg border`,children:(0,b.jsxs)(`table`,{className:`w-full text-left text-xs`,children:[(0,b.jsx)(`thead`,{className:`bg-muted/50 border-b`,children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{className:`p-3`,children:`Invoice`}),(0,b.jsx)(`th`,{className:`p-3`,children:`Date`}),(0,b.jsx)(`th`,{className:`p-3`,children:`Amount`}),(0,b.jsx)(`th`,{className:`p-3`,children:`Status`}),(0,b.jsx)(`th`,{className:`p-3 text-right`,children:`Receipt`})]})}),(0,b.jsxs)(`tbody`,{className:`divide-y`,children:[(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{className:`p-3 font-mono font-medium`,children:`INV-2026-009`}),(0,b.jsx)(`td`,{className:`p-3 text-muted-foreground`,children:`Sep 1, 2026`}),(0,b.jsx)(`td`,{className:`p-3 font-mono`,children:`$120.00`}),(0,b.jsx)(`td`,{className:`p-3`,children:(0,b.jsx)(qx,{variant:`success`,children:`Paid`})}),(0,b.jsx)(`td`,{className:`p-3 text-right`,children:(0,b.jsx)(`span`,{className:`text-primary hover:underline cursor-pointer`,children:`PDF`})})]}),(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{className:`p-3 font-mono font-medium`,children:`INV-2026-008`}),(0,b.jsx)(`td`,{className:`p-3 text-muted-foreground`,children:`Aug 1, 2026`}),(0,b.jsx)(`td`,{className:`p-3 font-mono`,children:`$120.00`}),(0,b.jsx)(`td`,{className:`p-3`,children:(0,b.jsx)(qx,{variant:`success`,children:`Paid`})}),(0,b.jsx)(`td`,{className:`p-3 text-right`,children:(0,b.jsx)(`span`,{className:`text-primary hover:underline cursor-pointer`,children:`PDF`})})]})]})]})})]})]})}function X3(){return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(U3,{title:`Team & Permissions`}),(0,b.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsxs)(`h2`,{className:`text-base font-semibold flex items-center gap-2`,children:[(0,b.jsx)(dp,{size:18}),` Workspace Members`]}),(0,b.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Manage organization access and security verification roles.`})]}),(0,b.jsxs)(o,{size:`sm`,children:[(0,b.jsx)(Zf,{size:14}),` Invite Member`]})]}),(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Member`}),(0,b.jsx)(`th`,{children:`Role`}),(0,b.jsx)(`th`,{children:`Status`}),(0,b.jsx)(`th`,{children:`Last Active`})]})}),(0,b.jsxs)(`tbody`,{children:[(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[(0,b.jsx)(`div`,{className:`font-semibold text-foreground`,children:`Daniel Bast`}),(0,b.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`daniel@bastsec.com`})]}),(0,b.jsx)(`td`,{children:(0,b.jsx)(qx,{variant:`default`,children:`Owner / Admin`})}),(0,b.jsx)(`td`,{children:(0,b.jsx)(`span`,{className:`text-xs text-[var(--good)] font-medium`,children:`Active`})}),(0,b.jsx)(`td`,{className:`text-xs text-muted-foreground`,children:`Just now`})]}),(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[(0,b.jsx)(`div`,{className:`font-semibold text-foreground`,children:`Kifaru Security Bot`}),(0,b.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`bot@kifaru.internal`})]}),(0,b.jsx)(`td`,{children:(0,b.jsx)(qx,{variant:`secondary`,children:`Automated Worker`})}),(0,b.jsx)(`td`,{children:(0,b.jsx)(`span`,{className:`text-xs text-[var(--good)] font-medium`,children:`Active`})}),(0,b.jsx)(`td`,{className:`text-xs text-muted-foreground`,children:`Running scans`})]})]})]})})]})}function Z3({label:e,value:t,detail:n}){return(0,b.jsxs)(h,{children:[(0,b.jsx)(`p`,{className:`text-2xs font-semibold tracking-[0.12em] uppercase text-muted-foreground`,children:e}),(0,b.jsx)(`strong`,{className:`my-1 block text-[28px] font-bold tracking-[-0.02em]`,children:t}),(0,b.jsx)(`p`,{children:n})]})}function Q3({findings:e}){let[t,n]=(0,y.useState)(4),r=vx(t),i=Dx(e.filter(e=>e.stage===t));return(0,b.jsxs)(`div`,{className:`grid gap-6`,children:[(0,b.jsx)(U3,{title:`Finding → data-lifecycle stage`}),(0,b.jsx)(zx,{findings:e,selected:t,onSelect:n}),(0,b.jsxs)(`div`,{className:`grid items-start gap-4 lg:grid-cols-[1.35fr_1fr]`,children:[(0,b.jsx)(Nx,{title:`Stage ${r.n} · ${r.name}`,sub:`${i.length} finding${i.length===1?``:`s`}`,children:(0,b.jsx)(Rx,{findings:i,emptyLabel:`No open findings at this stage.`})}),(0,b.jsxs)(Nx,{title:`Control pillar × lifecycle stage`,sub:`cell = open findings`,children:[(0,b.jsx)(Bx,{findings:e,onSelectStage:n}),(0,b.jsx)(`div`,{className:`flex flex-wrap gap-4 text-xs font-medium`,style:{marginTop:12},children:[`critical`,`high`,`medium`,`low`].map(e=>(0,b.jsxs)(`span`,{children:[(0,b.jsx)(`i`,{className:`mcap`,style:{background:`var(${Cx[e]})`}}),`worst: `,wx[e]]},e))})]})]})]})}function $3({events:e,findings:t}){let n=Dx(t.filter(e=>e.status===`confirmed`||e.status===`unverified`)),[r,i]=(0,y.useState)(null),a=n.find(e=>e.id===r)??n[0]??null,o=tf({queryKey:[`finding`,a?.id],queryFn:()=>hx.finding(a.id),enabled:!!a});return(0,b.jsxs)(`div`,{className:`grid gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`h2`,{className:`mb-0`,children:`Findings & evidence`}),(0,b.jsx)(`p`,{className:`text-muted-foreground text-sm`,children:`Every finding carries the evidence chain that produced it; every platform mutation is recorded below.`})]}),(0,b.jsxs)(`div`,{className:`grid items-start gap-4 md:grid-cols-[300px_minmax(0,1fr)]`,children:[(0,b.jsxs)(`div`,{className:`bg-card overflow-hidden rounded-xl border [&_.ph]:text-muted-foreground [&_.ph]:border-b [&_.ph]:border-[var(--hair)] [&_.ph]:px-3.5 [&_.ph]:py-3 [&_.ph]:text-xs [&_.ph]:font-semibold`,children:[(0,b.jsx)(`div`,{className:`ph`,children:`Findings with evidence`}),n.length?n.map(e=>(0,b.jsxs)(`button`,{className:`block w-full border-0 border-b border-l-[3px] border-[var(--hair)] border-l-transparent bg-transparent px-3.5 py-2.5 text-left last:border-b-0 aria-pressed:border-l-primary aria-pressed:bg-[var(--accent-soft)] [&_.pt]:text-[13px] [&_.pt]:font-semibold`,type:`button`,"aria-pressed":e.id===a?.id,onClick:()=>i(e.id),children:[(0,b.jsx)(`span`,{className:`sevtag sev-${e.severity}`,children:wx[e.severity]}),(0,b.jsx)(`div`,{className:`pt`,children:e.title})]},e.id)):(0,b.jsx)(`div`,{style:{padding:`14px`},children:(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs`,children:`No findings have been ingested yet, so there is no evidence to audit.`})})]}),(0,b.jsx)(`div`,{children:a?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)(`div`,{className:`mb-4 flex justify-between gap-4`,children:[(0,b.jsxs)(`div`,{children:[(0,b.jsx)(`span`,{className:`sevtag sev-${a.severity}`,children:wx[a.severity]}),(0,b.jsx)(`span`,{className:`font-mono text-muted-foreground text-xs`,style:{marginLeft:8},children:a.id}),(0,b.jsx)(`h2`,{style:{marginTop:9},children:a.title})]}),(0,b.jsx)(`span`,{className:`inline-flex shrink-0 self-start rounded-full border px-2.5 py-[3px] text-2xs font-semibold tracking-wide uppercase whitespace-nowrap text-muted-foreground`,children:a.status.replaceAll(`_`,` `)})]}),(0,b.jsx)(`p`,{children:a.description}),(0,b.jsx)(Vx,{items:[{k:`CVSS`,v:o.data?.finding.cvssScore??`—`},{k:`Weakness`,v:o.data?.finding.cwe??`—`,mono:!0},{k:`Category`,v:a.displayCategory},{k:`Lifecycle stage`,v:(0,b.jsxs)(`span`,{className:`inline-flex items-center gap-[5px] [&_.d]:size-2 [&_.d]:rounded-[2px]`,children:[(0,b.jsx)(`span`,{className:`d`,style:{background:`var(${vx(a.stage).v})`}}),a.stage,` · `,yx(vx(a.stage))]})}]}),(0,b.jsx)(Hx,{title:`Evidence chain — provenance`,children:o.data?.finding.evidence.length?o.data.finding.evidence.map(e=>(0,b.jsx)(Ux,{title:e.kind,detail:e.reason??`No reason recorded.`,verdict:e.verdict},e.id)):(0,b.jsx)(`p`,{className:`text-muted-foreground text-xs`,children:`No evidence records attached to this finding.`})}),o.data?.finding.remediation?(0,b.jsx)(Hx,{title:`Remediation`,children:(0,b.jsx)(`p`,{children:o.data.finding.remediation})}):null]}):(0,b.jsx)(X4,{compact:!0,title:`Nothing to audit yet`,detail:`Evidence appears once an agent reports a finding through report_finding.`})})]}),(0,b.jsx)(Nx,{surface:!1,title:`Governance ledger`,sub:`${e.length} recent event${e.length===1?``:`s`}`,children:e.length?(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`#`}),(0,b.jsx)(`th`,{children:`Action`}),(0,b.jsx)(`th`,{children:`Object`}),(0,b.jsx)(`th`,{children:`Actor`}),(0,b.jsx)(`th`,{children:`Outcome`}),(0,b.jsx)(`th`,{children:`Occurred`})]})}),(0,b.jsx)(`tbody`,{children:e.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`td`,{className:`font-mono`,children:e.sequence}),(0,b.jsx)(`td`,{children:e.action}),(0,b.jsxs)(`td`,{children:[e.objectType,` · `,(0,b.jsx)(`span`,{className:`font-mono`,children:e.objectID.slice(0,16)})]}),(0,b.jsx)(`td`,{className:`font-mono`,children:e.actorID??`—`}),(0,b.jsx)(`td`,{children:(0,b.jsx)(qx,{variant:Kx(e.outcome),children:e.outcome})}),(0,b.jsx)(`td`,{children:new Date(e.createdAt).toLocaleString()})]},e.id))})]})}):(0,b.jsx)(X4,{compact:!0,title:`No governance events`,detail:`Run creation, state transitions, tool calls and finding ingestion are all recorded here.`})})]})}function e6({runs:e}){return(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Assessment`}),(0,b.jsx)(`th`,{children:`Kind`}),(0,b.jsx)(`th`,{children:`Status`}),(0,b.jsx)(`th`,{children:`Updated`})]})}),(0,b.jsx)(`tbody`,{children:e.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[(0,b.jsx)(`span`,{children:e.title}),(0,b.jsx)(`span`,{className:`font-mono block text-muted-foreground text-2xs`,children:e.id})]}),(0,b.jsx)(`td`,{children:r6(e.kind)}),(0,b.jsx)(`td`,{children:(0,b.jsx)(qx,{variant:Kx(e.status),children:r6(e.status)})}),(0,b.jsx)(`td`,{children:new Date(e.updatedAt).toLocaleString()})]},e.id))})]})})}function t6({findings:e}){return(0,b.jsx)(`div`,{className:`overflow-x-auto rounded-xl border bg-card`,children:(0,b.jsxs)(`table`,{children:[(0,b.jsx)(`thead`,{children:(0,b.jsxs)(`tr`,{children:[(0,b.jsx)(`th`,{children:`Finding`}),(0,b.jsx)(`th`,{children:`Severity`}),(0,b.jsx)(`th`,{children:`Status`}),(0,b.jsx)(`th`,{children:`Asset`}),(0,b.jsx)(`th`,{children:`Updated`})]})}),(0,b.jsx)(`tbody`,{children:e.map(e=>(0,b.jsxs)(`tr`,{children:[(0,b.jsxs)(`td`,{children:[(0,b.jsx)(`a`,{href:`/findings`,children:e.title}),(0,b.jsx)(`span`,{className:`font-mono block text-muted-foreground text-2xs`,children:e.description??e.id})]}),(0,b.jsx)(`td`,{children:(0,b.jsx)(qx,{variant:Kx(e.severity),children:r6(e.severity)})}),(0,b.jsx)(`td`,{children:(0,b.jsx)(qx,{variant:Kx(e.status),children:r6(e.status)})}),(0,b.jsx)(`td`,{children:e.path??`—`}),(0,b.jsx)(`td`,{children:new Date(e.updatedAt).toLocaleString()})]},e.id))})]})})}function n6(e){let t=new Map;for(let n of e){let e=n.path?.trim()||`Unscoped`,r=t.get(e)??[];r.push(n),t.set(e,r)}return[...t.entries()].map(([e,t])=>({asset:e,items:t})).sort((e,t)=>t.items.length-e.items.length)}function r6(e){return e.replaceAll(`_`,` `).replaceAll(`-`,` `).replace(/\b\w/g,e=>e.toUpperCase())}export{q3 as LiveWorkspaceIsland,G3 as PlatformRoute};