webui: MCP Diagnostics improvements (#21803)

* Add MCP Connection diagnostics and CORS hint to web-ui

* tidy up test

* webui: Refactor and improve MCP diagnostic logging

---------

Co-authored-by: evalstate <1936278+evalstate@users.noreply.github.com>
This commit is contained in:
Aleksander Grygier 2026-04-13 07:58:38 +02:00 committed by GitHub
parent bafae27654
commit 227ed28e12
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 1329 additions and 308 deletions

File diff suppressed because one or more lines are too long

View File

@ -847,14 +847,14 @@ $$props,"trapFocus",3,!0),isValidEvent2=prop($$props,"isValidEvent",3,()=>!1),cu
onStrategy","strategy","dir","preventScroll","wrapperId","style","onPlaced","onInteractOutside","onCloseAutoFocus","onOpenAutoFocus","onFocusOutside","interactOutsideBehavior","loop","trapFocus","isValidEvent","customAnchor","isStatic","enabled"]);Popper_layer_inner($$anchor,spread_props({get popper(){return $$props.popper},get onEscapeKeydown(){return $$props.onEscapeKeydown},get escapeKeydownBehavior(){return $$props.escapeKeydownBehavior},get preventOverflowTextSelection(){return $$props.preventOverflowTextSelection},
get id(){return $$props.id},get onPointerDown(){return $$props.onPointerDown},get onPointerUp(){return $$props.onPointerUp},get side(){return $$props.side},get sideOffset(){return $$props.sideOffset},get align(){return $$props.align},get alignOffset(){return $$props.alignOffset},get arrowPadding(){return $$props.arrowPadding},get avoidCollisions(){return $$props.avoidCollisions},get collisionBoundary(){return $$props.collisionBoundary},get collisionPadding(){return $$props.collisionPadding},get sticky(){
return $$props.sticky},get hideWhenDetached(){return $$props.hideWhenDetached},get updatePositionStrategy(){return $$props.updatePositionStrategy},get strategy(){return $$props.strategy},get dir(){return $$props.dir},get preventScroll(){return $$props.preventScroll},get wrapperId(){return $$props.wrapperId},get style(){return $$props.style},get onPlaced(){return $$props.onPlaced},get customAnchor(){return customAnchor()},get isStatic(){return isStatic()},get enabled(){return $$props.enabled},get onInteractOutside(){
return $$props.onInteractOutside},get onCloseAutoFocus(){return $$props.onCloseAutoFocus},get onOpenAutoFocus(){return $$props.onOpenAutoFocus},get interactOutsideBehavior(){return interactOutsideBehavior()},get loop(){return $$props.loop},get trapFocus(){return trapFocus()},get isValidEvent(){return isValidEvent2()},get onFocusOutside(){return $$props.onFocusOutside}},()=>restProps,{forceMount:!0}))}var root_4$E=from_html("<div><div><!></div></div>"),root_9$r=from_html("<div><div><!></div></div\
return $$props.onInteractOutside},get onCloseAutoFocus(){return $$props.onCloseAutoFocus},get onOpenAutoFocus(){return $$props.onOpenAutoFocus},get interactOutsideBehavior(){return interactOutsideBehavior()},get loop(){return $$props.loop},get trapFocus(){return trapFocus()},get isValidEvent(){return isValidEvent2()},get onFocusOutside(){return $$props.onFocusOutside}},()=>restProps,{forceMount:!0}))}var root_4$E=from_html("<div><div><!></div></div>"),root_9$s=from_html("<div><div><!></div></div\
>");function Select_content$1($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),ref2=prop($$props,"ref",15,null),forceMount=prop($$props,"forceMount",3,!1),side=prop($$props,"side",3,"bottom"),onInteractOutside=prop($$props,"onInteractOutside",3,noop$1),onEscapeKeydown=prop($$props,"onEscapeKeydown",3,noop$1),preventScroll=prop($$props,"preventScroll",3,!1),restProps=rest_props($$props,["$$slots","$$events","$$legacy","id","ref","forceMount",
"side","onInteractOutside","onEscapeKeydown","children","child","preventScroll","style"]);const contentState=SelectContentState.create({id:boxWith$1(()=>id2()),ref:boxWith$1(()=>ref2(),v=>ref2(v)),onInteractOutside:boxWith$1(()=>onInteractOutside()),onEscapeKeydown:boxWith$1(()=>onEscapeKeydown())}),mergedProps=user_derived(()=>mergeProps(restProps,contentState.props));var fragment=comment$2(),node2=first_child(fragment);{var consequent_1=$$anchor2=>{Popper_layer_force_mount($$anchor2,spread_props(
()=>get$4(mergedProps),()=>contentState.popperProps,{get ref(){return contentState.opts.ref},get side(){return side()},get enabled(){return contentState.root.opts.open.current},get id(){return id2()},get preventScroll(){return preventScroll()},forceMount:!0,get shouldRender(){return contentState.shouldRender},popper:($$anchor3,$$arg0)=>{let props=()=>$$arg0?.().props,wrapperProps=()=>$$arg0?.().wrapperProps;const finalProps=user_derived(()=>mergeProps(props(),{style:contentState.props.style},{style:$$props.
style}));var fragment_2=comment$2(),node_1=first_child(fragment_2);{var consequent=$$anchor4=>{var fragment_3=comment$2(),node_2=first_child(fragment_3);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_2,()=>$$props.child,()=>get$4($0))}append($$anchor4,fragment_3)},alternate=$$anchor4=>{var div=root_4$E();attribute_effect(div,()=>({...wrapperProps()}));var div_1=child(div);attribute_effect(div_1,()=>({...get$4(finalProps)}));
var node_3=child(div_1);snippet(node_3,()=>$$props.children??noop$3),reset(div_1),reset(div),append($$anchor4,div)};if_block(node_1,$$render=>{$$props.child?$$render(consequent):$$render(alternate,!1)})}append($$anchor3,fragment_2)},$$slots:{popper:!0}}))},alternate_2=$$anchor2=>{var fragment_4=comment$2(),node_4=first_child(fragment_4);{var consequent_3=$$anchor3=>{Popper_layer($$anchor3,spread_props(()=>get$4(mergedProps),()=>contentState.popperProps,{get ref(){return contentState.opts.ref},get side(){
return side()},get open(){return contentState.root.opts.open.current},get id(){return id2()},get preventScroll(){return preventScroll()},forceMount:!1,get shouldRender(){return contentState.shouldRender},popper:($$anchor4,$$arg0)=>{let props=()=>$$arg0?.().props,wrapperProps=()=>$$arg0?.().wrapperProps;const finalProps=user_derived(()=>mergeProps(props(),{style:contentState.props.style},{style:$$props.style}));var fragment_6=comment$2(),node_5=first_child(fragment_6);{var consequent_2=$$anchor5=>{
var fragment_7=comment$2(),node_6=first_child(fragment_7);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($0))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$r();attribute_effect(div_2,()=>({...wrapperProps()}));var div_3=child(div_2);attribute_effect(div_3,()=>({...get$4(finalProps)}));var node_7=child(div_3);snippet(node_7,()=>$$props.children??noop$3),reset(div_3),
var fragment_7=comment$2(),node_6=first_child(fragment_7);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($0))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$s();attribute_effect(div_2,()=>({...wrapperProps()}));var div_3=child(div_2);attribute_effect(div_3,()=>({...get$4(finalProps)}));var node_7=child(div_3);snippet(node_7,()=>$$props.children??noop$3),reset(div_3),
reset(div_2),append($$anchor5,div_2)};if_block(node_5,$$render=>{$$props.child?$$render(consequent_2):$$render(alternate_1,!1)})}append($$anchor4,fragment_6)},$$slots:{popper:!0}}))};if_block(node_4,$$render=>{forceMount()||$$render(consequent_3)},!0)}append($$anchor2,fragment_4)};if_block(node2,$$render=>{forceMount()?$$render(consequent_1):$$render(alternate_2,!1)})}append($$anchor,fragment),pop()}function Mounted($$anchor,$$props){push$1($$props,!0);let mounted=prop($$props,"mounted",15,!1),onMountedChange=prop(
$$props,"onMountedChange",3,noop$1);onMountEffect(()=>(mounted(!0),onMountedChange()(!0),()=>{mounted(!1),onMountedChange()(!1)})),pop()}var root_2$1k=from_html("<div><!></div>"),root$1K=from_html("<!> <!>",1);function Select_item$1($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),ref2=prop($$props,"ref",15,null),label=prop($$props,"label",19,()=>$$props.value),disabled=prop($$props,"disabled",3,!1),onHighlight=prop($$props,"onHighlight",3,
noop$1),onUnhighlight=prop($$props,"onUnhighlight",3,noop$1),restProps=rest_props($$props,["$$slots","$$events","$$legacy","id","ref","value","label","disabled","children","child","onHighlight","onUnhighlight"]);const itemState=SelectItemState.create({id:boxWith$1(()=>id2()),ref:boxWith$1(()=>ref2(),v=>ref2(v)),value:boxWith$1(()=>$$props.value),disabled:boxWith$1(()=>disabled()),label:boxWith$1(()=>label()),onHighlight:boxWith$1(()=>onHighlight()),onUnhighlight:boxWith$1(()=>onUnhighlight())}),
@ -873,7 +873,7 @@ function Menu_item($$anchor,$$props){const uid=props_id();push$1($$props,!0);let
()=>disabled()),onSelect:boxWith$1(()=>onSelect()),ref:boxWith$1(()=>ref2(),v=>ref2(v)),closeOnSelect:boxWith$1(()=>closeOnSelect())}),mergedProps=user_derived(()=>mergeProps(restProps,itemState.props));var fragment=comment$2(),node2=first_child(fragment);{var consequent=$$anchor2=>{var fragment_1=comment$2(),node_1=first_child(fragment_1);snippet(node_1,()=>$$props.child,()=>({props:get$4(mergedProps)})),append($$anchor2,fragment_1)},alternate=$$anchor2=>{var div=root_2$1i();attribute_effect(div,
()=>({...get$4(mergedProps)}));var node_2=child(div);snippet(node_2,()=>$$props.children??noop$3),reset(div),append($$anchor2,div)};if_block(node2,$$render=>{$$props.child?$$render(consequent):$$render(alternate,!1)})}append($$anchor,fragment),pop()}var root_2$1h=from_html("<div><!></div>");function Menu_separator($$anchor,$$props){const uid=props_id();push$1($$props,!0);let ref2=prop($$props,"ref",15,null),id2=prop($$props,"id",19,()=>createId(uid)),restProps=rest_props($$props,["$$slots","$$ev\
ents","$$legacy","ref","id","child","children"]);const separatorState=MenuSeparatorState.create({id:boxWith$1(()=>id2()),ref:boxWith$1(()=>ref2(),v=>ref2(v))}),mergedProps=user_derived(()=>mergeProps(restProps,separatorState.props));var fragment=comment$2(),node2=first_child(fragment);{var consequent=$$anchor2=>{var fragment_1=comment$2(),node_1=first_child(fragment_1);snippet(node_1,()=>$$props.child,()=>({props:get$4(mergedProps)})),append($$anchor2,fragment_1)},alternate=$$anchor2=>{var div=root_2$1h();
attribute_effect(div,()=>({...get$4(mergedProps)}));var node_2=child(div);snippet(node_2,()=>$$props.children??noop$3),reset(div),append($$anchor2,div)};if_block(node2,$$render=>{$$props.child?$$render(consequent):$$render(alternate,!1)})}append($$anchor,fragment),pop()}var root_4$D=from_html("<div><div><!></div></div>"),root_9$q=from_html("<div><div><!></div></div>");function Menu_sub_content($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),
attribute_effect(div,()=>({...get$4(mergedProps)}));var node_2=child(div);snippet(node_2,()=>$$props.children??noop$3),reset(div),append($$anchor2,div)};if_block(node2,$$render=>{$$props.child?$$render(consequent):$$render(alternate,!1)})}append($$anchor,fragment),pop()}var root_4$D=from_html("<div><div><!></div></div>"),root_9$r=from_html("<div><div><!></div></div>");function Menu_sub_content($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),
ref2=prop($$props,"ref",15,null),loop2=prop($$props,"loop",3,!0),onInteractOutside=prop($$props,"onInteractOutside",3,noop$1),forceMount=prop($$props,"forceMount",3,!1),onEscapeKeydown=prop($$props,"onEscapeKeydown",3,noop$1),interactOutsideBehavior=prop($$props,"interactOutsideBehavior",3,"defer-otherwise-close"),escapeKeydownBehavior=prop($$props,"escapeKeydownBehavior",3,"defer-otherwise-close"),onOpenAutoFocusProp=prop($$props,"onOpenAutoFocus",3,noop$1),onCloseAutoFocusProp=prop($$props,"on\
CloseAutoFocus",3,noop$1),onFocusOutside=prop($$props,"onFocusOutside",3,noop$1),side=prop($$props,"side",3,"right"),trapFocus=prop($$props,"trapFocus",3,!1),restProps=rest_props($$props,["$$slots","$$events","$$legacy","id","ref","children","child","loop","onInteractOutside","forceMount","onEscapeKeydown","interactOutsideBehavior","escapeKeydownBehavior","onOpenAutoFocus","onCloseAutoFocus","onFocusOutside","side","trapFocus","style"]);const subContentState=MenuContentState.create({id:boxWith$1(
()=>id2()),loop:boxWith$1(()=>loop2()),ref:boxWith$1(()=>ref2(),v=>ref2(v)),isSub:!0,onCloseAutoFocus:boxWith$1(()=>handleCloseAutoFocus)});function onkeydown(e){const isKeyDownInside=e.currentTarget.contains(e.target),isCloseKey=SUB_CLOSE_KEYS[subContentState.parentMenu.root.opts.dir.current].includes(e.key);isKeyDownInside&&isCloseKey&&(subContentState.parentMenu.onClose(),subContentState.parentMenu.triggerNode?.focus(),e.preventDefault())}const dataAttr=user_derived(()=>subContentState.parentMenu.
@ -884,7 +884,7 @@ return trapFocus()},get shouldRender(){return subContentState.shouldRender},popp
wrapperProps:wrapperProps(),...subContentState.snippetProps}));snippet(node_2,()=>$$props.child,()=>get$4($0))}append($$anchor4,fragment_3)},alternate=$$anchor4=>{var div=root_4$D();attribute_effect(div,()=>({...wrapperProps()}));var div_1=child(div);attribute_effect(div_1,()=>({...get$4(finalProps)}));var node_3=child(div_1);snippet(node_3,()=>$$props.children??noop$3),reset(div_1),reset(div),append($$anchor4,div)};if_block(node_1,$$render=>{$$props.child?$$render(consequent):$$render(alternate,
!1)})}append($$anchor3,fragment_2)},$$slots:{popper:!0}}))},alternate_2=$$anchor2=>{var fragment_4=comment$2(),node_4=first_child(fragment_4);{var consequent_3=$$anchor3=>{Popper_layer($$anchor3,spread_props(()=>get$4(mergedProps),{get ref(){return subContentState.opts.ref},get interactOutsideBehavior(){return interactOutsideBehavior()},get escapeKeydownBehavior(){return escapeKeydownBehavior()},onCloseAutoFocus:handleCloseAutoFocus,onOpenAutoFocus:handleOpenAutoFocus,get open(){return subContentState.
parentMenu.opts.open.current},onInteractOutside:handleInteractOutside,onEscapeKeydown:handleEscapeKeydown,onFocusOutside:handleOnFocusOutside,preventScroll:!1,get loop(){return loop2()},get trapFocus(){return trapFocus()},get shouldRender(){return subContentState.shouldRender},popper:($$anchor4,$$arg0)=>{let props=()=>$$arg0?.().props,wrapperProps=()=>$$arg0?.().wrapperProps;const finalProps=user_derived(()=>mergeProps(props(),get$4(mergedProps),{style:getFloatingContentCSSVars("menu")},{style:$$props.
style}));var fragment_6=comment$2(),node_5=first_child(fragment_6);{var consequent_2=$$anchor5=>{var fragment_7=comment$2(),node_6=first_child(fragment_7);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...subContentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($0))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$q();attribute_effect(div_2,()=>({...wrapperProps()}));var div_3=child(div_2);attribute_effect(div_3,()=>({...get$4(
style}));var fragment_6=comment$2(),node_5=first_child(fragment_6);{var consequent_2=$$anchor5=>{var fragment_7=comment$2(),node_6=first_child(fragment_7);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...subContentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($0))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$r();attribute_effect(div_2,()=>({...wrapperProps()}));var div_3=child(div_2);attribute_effect(div_3,()=>({...get$4(
finalProps)}));var node_7=child(div_3);snippet(node_7,()=>$$props.children??noop$3),reset(div_3),reset(div_2),append($$anchor5,div_2)};if_block(node_5,$$render=>{$$props.child?$$render(consequent_2):$$render(alternate_1,!1)})}append($$anchor4,fragment_6)},$$slots:{popper:!0}}))};if_block(node_4,$$render=>{forceMount()||$$render(consequent_3)},!0)}append($$anchor2,fragment_4)};if_block(node2,$$render=>{forceMount()?$$render(consequent_1):$$render(alternate_2,!1)})}append($$anchor,fragment),pop()}
var root_3$Z=from_html("<div><!></div>");function Menu_sub_trigger($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),disabled=prop($$props,"disabled",3,!1),ref2=prop($$props,"ref",15,null),onSelect=prop($$props,"onSelect",3,noop$1),openDelay=prop($$props,"openDelay",3,100),restProps=rest_props($$props,["$$slots","$$events","$$legacy","id","disabled","ref","children","child","onSelect","openDelay"]);const subTriggerState=MenuSubTriggerState.
create({disabled:boxWith$1(()=>disabled()),onSelect:boxWith$1(()=>onSelect()),id:boxWith$1(()=>id2()),ref:boxWith$1(()=>ref2(),v=>ref2(v)),openDelay:boxWith$1(()=>openDelay())}),mergedProps=user_derived(()=>mergeProps(restProps,subTriggerState.props));Floating_layer_anchor($$anchor,{get id(){return id2()},get ref(){return subTriggerState.opts.ref},children:($$anchor2,$$slotProps)=>{var fragment_1=comment$2(),node2=first_child(fragment_1);{var consequent=$$anchor3=>{var fragment_2=comment$2(),node_1=first_child(
@ -915,7 +915,7 @@ opts,PopoverRootContext.get())}opts;root;attachment;constructor(opts,root2){this
this.root.openedViaHover&&!this.root.hasInteractedWithContent,onPointerExit:()=>{this.root.handleDelayedHoverClose()}})}onpointerdown(_){this.root.markInteraction()}onfocusin(e){const target2=e.target;isElement$1(target2)&&isTabbable(target2)&&this.root.markInteraction()}onpointerenter(e){isTouch(e)||this.root.cancelDelayedClose()}onpointerleave(e){isTouch(e)}onInteractOutside=e=>{if(this.opts.onInteractOutside.current(e),e.defaultPrevented||!isElement$1(e.target))return;const closestTrigger=e.target.
closest(popoverAttrs.selector("trigger"));if(!(closestTrigger&&closestTrigger===this.root.triggerNode)){if(this.opts.customAnchor.current){if(isElement$1(this.opts.customAnchor.current)){if(this.opts.customAnchor.current.contains(e.target))return}else if(typeof this.opts.customAnchor.current=="string"){const el=document.querySelector(this.opts.customAnchor.current);if(el&&el.contains(e.target))return}}this.root.handleClose()}};onEscapeKeydown=e=>{this.opts.onEscapeKeydown.current(e),!e.defaultPrevented&&
this.root.handleClose()};get shouldRender(){return this.root.contentPresence.shouldRender}get shouldTrapFocus(){return!(this.root.openedViaHover&&!this.root.hasInteractedWithContent)}#snippetProps=user_derived(()=>({open:this.root.opts.open.current}));get snippetProps(){return get$4(this.#snippetProps)}set snippetProps(value){set$1(this.#snippetProps,value)}#props=user_derived(()=>({id:this.opts.id.current,tabindex:-1,"data-state":getDataOpenClosed(this.root.opts.open.current),[popoverAttrs.content]:"",
style:{pointerEvents:"auto",contain:"layout style paint"},onpointerdown:this.onpointerdown,onfocusin:this.onfocusin,onpointerenter:this.onpointerenter,onpointerleave:this.onpointerleave,...this.attachment}));get props(){return get$4(this.#props)}set props(value){set$1(this.#props,value)}popperProps={onInteractOutside:this.onInteractOutside,onEscapeKeydown:this.onEscapeKeydown}}var root_4$C=from_html("<div><div><!></div></div>"),root_9$p=from_html("<div><div><!></div></div>");function Popover_content$1($$anchor,$$props){
style:{pointerEvents:"auto",contain:"layout style paint"},onpointerdown:this.onpointerdown,onfocusin:this.onfocusin,onpointerenter:this.onpointerenter,onpointerleave:this.onpointerleave,...this.attachment}));get props(){return get$4(this.#props)}set props(value){set$1(this.#props,value)}popperProps={onInteractOutside:this.onInteractOutside,onEscapeKeydown:this.onEscapeKeydown}}var root_4$C=from_html("<div><div><!></div></div>"),root_9$q=from_html("<div><div><!></div></div>");function Popover_content$1($$anchor,$$props){
const uid=props_id();push$1($$props,!0);let ref2=prop($$props,"ref",15,null),id2=prop($$props,"id",19,()=>createId(uid)),forceMount=prop($$props,"forceMount",3,!1),onOpenAutoFocus=prop($$props,"onOpenAutoFocus",3,noop$1),onCloseAutoFocus=prop($$props,"onCloseAutoFocus",3,noop$1),onEscapeKeydown=prop($$props,"onEscapeKeydown",3,noop$1),onInteractOutside=prop($$props,"onInteractOutside",3,noop$1),trapFocus=prop($$props,"trapFocus",3,!0),preventScroll=prop($$props,"preventScroll",3,!1),customAnchor=prop(
$$props,"customAnchor",3,null),restProps=rest_props($$props,["$$slots","$$events","$$legacy","child","children","ref","id","forceMount","onOpenAutoFocus","onCloseAutoFocus","onEscapeKeydown","onInteractOutside","trapFocus","preventScroll","customAnchor","style"]);const contentState=PopoverContentState.create({id:boxWith$1(()=>id2()),ref:boxWith$1(()=>ref2(),v=>ref2(v)),onInteractOutside:boxWith$1(()=>onInteractOutside()),onEscapeKeydown:boxWith$1(()=>onEscapeKeydown()),customAnchor:boxWith$1(()=>customAnchor())}),
mergedProps=user_derived(()=>mergeProps(restProps,contentState.props)),effectiveTrapFocus=user_derived(()=>trapFocus()&&contentState.shouldTrapFocus);function handleOpenAutoFocus(e){contentState.shouldTrapFocus||e.preventDefault(),onOpenAutoFocus()(e)}var fragment=comment$2(),node2=first_child(fragment);{var consequent_1=$$anchor2=>{Popper_layer_force_mount($$anchor2,spread_props(()=>get$4(mergedProps),()=>contentState.popperProps,{get ref(){return contentState.opts.ref},get enabled(){return contentState.
@ -923,7 +923,7 @@ root.opts.open.current},get id(){return id2()},get trapFocus(){return get$4(effe
"popover")},{style:$$props.style}));var fragment_2=comment$2(),node_1=first_child(fragment_2);{var consequent=$$anchor4=>{var fragment_3=comment$2(),node_2=first_child(fragment_3);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_2,()=>$$props.child,()=>get$4($0))}append($$anchor4,fragment_3)},alternate=$$anchor4=>{var div=root_4$C();attribute_effect(div,()=>({...wrapperProps()}));var div_1=child(div);attribute_effect(div_1,
()=>({...get$4(finalProps)}));var node_3=child(div_1);snippet(node_3,()=>$$props.children??noop$3),reset(div_1),reset(div),append($$anchor4,div)};if_block(node_1,$$render=>{$$props.child?$$render(consequent):$$render(alternate,!1)})}append($$anchor3,fragment_2)},$$slots:{popper:!0}}))},alternate_2=$$anchor2=>{var fragment_4=comment$2(),node_4=first_child(fragment_4);{var consequent_3=$$anchor3=>{Popper_layer($$anchor3,spread_props(()=>get$4(mergedProps),()=>contentState.popperProps,{get ref(){return contentState.
opts.ref},get open(){return contentState.root.opts.open.current},get id(){return id2()},get trapFocus(){return get$4(effectiveTrapFocus)},get preventScroll(){return preventScroll()},loop:!0,forceMount:!1,get customAnchor(){return customAnchor()},onOpenAutoFocus:handleOpenAutoFocus,get onCloseAutoFocus(){return onCloseAutoFocus()},get shouldRender(){return contentState.shouldRender},popper:($$anchor4,$$arg0)=>{let props=()=>$$arg0?.().props,wrapperProps=()=>$$arg0?.().wrapperProps;const finalProps=user_derived(
()=>mergeProps(props(),{style:getFloatingContentCSSVars("popover")},{style:$$props.style}));var fragment_6=comment$2(),node_5=first_child(fragment_6);{var consequent_2=$$anchor5=>{var fragment_7=comment$2(),node_6=first_child(fragment_7);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($0))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$p();attribute_effect(div_2,()=>({
()=>mergeProps(props(),{style:getFloatingContentCSSVars("popover")},{style:$$props.style}));var fragment_6=comment$2(),node_5=first_child(fragment_6);{var consequent_2=$$anchor5=>{var fragment_7=comment$2(),node_6=first_child(fragment_7);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($0))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$q();attribute_effect(div_2,()=>({
...wrapperProps()}));var div_3=child(div_2);attribute_effect(div_3,()=>({...get$4(finalProps)}));var node_7=child(div_3);snippet(node_7,()=>$$props.children??noop$3),reset(div_3),reset(div_2),append($$anchor5,div_2)};if_block(node_5,$$render=>{$$props.child?$$render(consequent_2):$$render(alternate_1,!1)})}append($$anchor4,fragment_6)},$$slots:{popper:!0}}))};if_block(node_4,$$render=>{forceMount()||$$render(consequent_3)},!0)}append($$anchor2,fragment_4)};if_block(node2,$$render=>{forceMount()?
$$render(consequent_1):$$render(alternate_2,!1)})}append($$anchor,fragment),pop()}var root_3$Y=from_html("<button><!></button>");function Popover_trigger$1($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),ref2=prop($$props,"ref",15,null),type2=prop($$props,"type",3,"button"),disabled=prop($$props,"disabled",3,!1),openOnHover=prop($$props,"openOnHover",3,!1),openDelay=prop($$props,"openDelay",3,700),closeDelay=prop($$props,"closeDelay",3,300),
restProps=rest_props($$props,["$$slots","$$events","$$legacy","children","child","id","ref","type","disabled","openOnHover","openDelay","closeDelay"]);const triggerState=PopoverTriggerState.create({id:boxWith$1(()=>id2()),ref:boxWith$1(()=>ref2(),v=>ref2(v)),disabled:boxWith$1(()=>!!disabled()),openOnHover:boxWith$1(()=>openOnHover()),openDelay:boxWith$1(()=>openDelay()),closeDelay:boxWith$1(()=>closeDelay())}),mergedProps=user_derived(()=>mergeProps(restProps,triggerState.props,{type:type2()}));
@ -940,7 +940,7 @@ opts.ref},onEscapeKeydown:e=>{onEscapeKeydown()(e),!e.defaultPrevented&&contentS
consequent)})}var node_3=sibling(node_2,2);{let $0=user_derived(()=>({props:mergeProps(get$4(mergedProps),focusScopeProps()),...contentState.snippetProps}));snippet(node_3,()=>$$props.child,()=>get$4($0))}append($$anchor7,fragment_6)},alternate=$$anchor7=>{var fragment_8=root_8$q(),node_4=first_child(fragment_8);Scroll_lock(node_4,{get preventScroll(){return preventScroll()}});var div=sibling(node_4,2);attribute_effect(div,$0=>({...$0}),[()=>mergeProps(get$4(mergedProps),focusScopeProps())]);var node_5=child(
div);snippet(node_5,()=>$$props.children??noop$3),reset(div),append($$anchor7,fragment_8)};if_block(node_1,$$render=>{$$props.child?$$render(consequent_1):$$render(alternate,!1)})}append($$anchor6,fragment_5)},$$slots:{default:!0}}))},$$slots:{default:!0}}))},$$slots:{default:!0}}))},$$slots:{focusScope:!0}})};if_block(node2,$$render=>{(contentState.shouldRender||forceMount())&&$$render(consequent_2)})}append($$anchor,fragment),pop()}function Menu($$anchor,$$props){push$1($$props,!0);let open2=prop(
$$props,"open",15,!1),dir=prop($$props,"dir",3,"ltr"),onOpenChange=prop($$props,"onOpenChange",3,noop$1),onOpenChangeComplete=prop($$props,"onOpenChangeComplete",3,noop$1),variant=prop($$props,"_internal_variant",3,"dropdown-menu");const root2=MenuRootState.create({variant:boxWith$1(()=>variant()),dir:boxWith$1(()=>dir()),onClose:()=>{open2(!1),onOpenChange()(!1)}});MenuMenuState.create({open:boxWith$1(()=>open2(),v=>{open2(v),onOpenChange()(v)}),onOpenChangeComplete:boxWith$1(()=>onOpenChangeComplete())},
root2),Floating_layer($$anchor,{children:($$anchor2,$$slotProps)=>{var fragment_1=comment$2(),node2=first_child(fragment_1);snippet(node2,()=>$$props.children??noop$3),append($$anchor2,fragment_1)},$$slots:{default:!0}}),pop()}var root_4$B=from_html("<div><div><!></div></div>"),root_9$o=from_html("<div><div><!></div></div>");function Dropdown_menu_content$1($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),ref2=prop($$props,"ref",15,null),loop2=prop(
root2),Floating_layer($$anchor,{children:($$anchor2,$$slotProps)=>{var fragment_1=comment$2(),node2=first_child(fragment_1);snippet(node2,()=>$$props.children??noop$3),append($$anchor2,fragment_1)},$$slots:{default:!0}}),pop()}var root_4$B=from_html("<div><div><!></div></div>"),root_9$p=from_html("<div><div><!></div></div>");function Dropdown_menu_content$1($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),ref2=prop($$props,"ref",15,null),loop2=prop(
$$props,"loop",3,!0),onInteractOutside=prop($$props,"onInteractOutside",3,noop$1),onEscapeKeydown=prop($$props,"onEscapeKeydown",3,noop$1),onCloseAutoFocus=prop($$props,"onCloseAutoFocus",3,noop$1),forceMount=prop($$props,"forceMount",3,!1),trapFocus=prop($$props,"trapFocus",3,!1),restProps=rest_props($$props,["$$slots","$$events","$$legacy","id","child","children","ref","loop","onInteractOutside","onEscapeKeydown","onCloseAutoFocus","forceMount","trapFocus","style"]);const contentState=MenuContentState.
create({id:boxWith$1(()=>id2()),loop:boxWith$1(()=>loop2()),ref:boxWith$1(()=>ref2(),v=>ref2(v)),onCloseAutoFocus:boxWith$1(()=>onCloseAutoFocus())}),mergedProps=user_derived(()=>mergeProps(restProps,contentState.props));function handleInteractOutside(e){if(contentState.handleInteractOutside(e),!e.defaultPrevented&&(onInteractOutside()(e),!e.defaultPrevented)){if(e.target&&e.target instanceof Element){const subContentSelector=`[${contentState.parentMenu.root.getBitsAttr("sub-content")}]`;if(e.target.
closest(subContentSelector))return}contentState.parentMenu.onClose()}}function handleEscapeKeydown(e){onEscapeKeydown()(e),!e.defaultPrevented&&contentState.parentMenu.onClose()}var fragment=comment$2(),node2=first_child(fragment);{var consequent_1=$$anchor2=>{Popper_layer_force_mount($$anchor2,spread_props(()=>get$4(mergedProps),()=>contentState.popperProps,{get ref(){return contentState.opts.ref},get enabled(){return contentState.parentMenu.opts.open.current},onInteractOutside:handleInteractOutside,
@ -948,7 +948,7 @@ onEscapeKeydown:handleEscapeKeydown,get trapFocus(){return trapFocus()},get loop
var fragment_3=comment$2(),node_2=first_child(fragment_3);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_2,()=>$$props.child,()=>get$4($0))}append($$anchor4,fragment_3)},alternate=$$anchor4=>{var div=root_4$B();attribute_effect(div,()=>({...wrapperProps()}));var div_1=child(div);attribute_effect(div_1,()=>({...get$4(finalProps)}));var node_3=child(div_1);snippet(node_3,()=>$$props.children??noop$3),reset(div_1),reset(div),
append($$anchor4,div)};if_block(node_1,$$render=>{$$props.child?$$render(consequent):$$render(alternate,!1)})}append($$anchor3,fragment_2)},$$slots:{popper:!0}}))},alternate_2=$$anchor2=>{var fragment_4=comment$2(),node_4=first_child(fragment_4);{var consequent_3=$$anchor3=>{Popper_layer($$anchor3,spread_props(()=>get$4(mergedProps),()=>contentState.popperProps,{get ref(){return contentState.opts.ref},get open(){return contentState.parentMenu.opts.open.current},onInteractOutside:handleInteractOutside,
onEscapeKeydown:handleEscapeKeydown,get trapFocus(){return trapFocus()},get loop(){return loop2()},forceMount:!1,get id(){return id2()},get shouldRender(){return contentState.shouldRender},popper:($$anchor4,$$arg0)=>{let props=()=>$$arg0?.().props,wrapperProps=()=>$$arg0?.().wrapperProps;const finalProps=user_derived(()=>mergeProps(props(),{style:getFloatingContentCSSVars("dropdown-menu")},{style:$$props.style}));var fragment_6=comment$2(),node_5=first_child(fragment_6);{var consequent_2=$$anchor5=>{
var fragment_7=comment$2(),node_6=first_child(fragment_7);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($0))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$o();attribute_effect(div_2,()=>({...wrapperProps()}));var div_3=child(div_2);attribute_effect(div_3,()=>({...get$4(finalProps)}));var node_7=child(div_3);snippet(node_7,()=>$$props.children??noop$3),reset(div_3),
var fragment_7=comment$2(),node_6=first_child(fragment_7);{let $0=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($0))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$p();attribute_effect(div_2,()=>({...wrapperProps()}));var div_3=child(div_2);attribute_effect(div_3,()=>({...get$4(finalProps)}));var node_7=child(div_3);snippet(node_7,()=>$$props.children??noop$3),reset(div_3),
reset(div_2),append($$anchor5,div_2)};if_block(node_5,$$render=>{$$props.child?$$render(consequent_2):$$render(alternate_1,!1)})}append($$anchor4,fragment_6)},$$slots:{popper:!0}}))};if_block(node_4,$$render=>{forceMount()||$$render(consequent_3)},!0)}append($$anchor2,fragment_4)};if_block(node2,$$render=>{forceMount()?$$render(consequent_1):$$render(alternate_2,!1)})}append($$anchor,fragment),pop()}var root_3$X=from_html("<button><!></button>");function Menu_trigger($$anchor,$$props){const uid=props_id();
push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),ref2=prop($$props,"ref",15,null),disabled=prop($$props,"disabled",3,!1),type2=prop($$props,"type",3,"button"),restProps=rest_props($$props,["$$slots","$$events","$$legacy","id","ref","child","children","disabled","type"]);const triggerState=DropdownMenuTriggerState.create({id:boxWith$1(()=>id2()),disabled:boxWith$1(()=>disabled()??!1),ref:boxWith$1(()=>ref2(),v=>ref2(v))}),mergedProps=user_derived(()=>mergeProps(restProps,triggerState.
props,{type:type2()}));Floating_layer_anchor($$anchor,{get id(){return id2()},get ref(){return triggerState.opts.ref},children:($$anchor2,$$slotProps)=>{var fragment_1=comment$2(),node2=first_child(fragment_1);{var consequent=$$anchor3=>{var fragment_2=comment$2(),node_1=first_child(fragment_2);snippet(node_1,()=>$$props.child,()=>({props:get$4(mergedProps)})),append($$anchor3,fragment_2)},alternate=$$anchor3=>{var button=root_3$X();attribute_effect(button,()=>({...get$4(mergedProps)}));var node_2=child(
@ -1078,7 +1078,7 @@ attachRef(this.opts.ref,v=>this.root.contentNode=v),new SafePolygon({triggerNode
this.root.triggerNode?.contains(e.target)&&this.root.disableCloseOnTriggerClick){e.preventDefault();return}this.opts.onInteractOutside.current(e),!e.defaultPrevented&&this.root.handleClose()};onEscapeKeydown=e=>{this.opts.onEscapeKeydown.current?.(e),!e.defaultPrevented&&this.root.handleClose()};onOpenAutoFocus=e=>{e.preventDefault()};onCloseAutoFocus=e=>{e.preventDefault()};get shouldRender(){return this.root.contentPresence.shouldRender}#snippetProps=user_derived(()=>({open:this.root.opts.open.
current}));get snippetProps(){return get$4(this.#snippetProps)}set snippetProps(value){set$1(this.#snippetProps,value)}#props=user_derived(()=>({id:this.opts.id.current,"data-state":this.root.stateAttr,"data-disabled":boolToEmptyStrOrUndef(this.root.disabled),style:{outline:"none"},[tooltipAttrs.content]:"",...this.attachment}));get props(){return get$4(this.#props)}set props(value){set$1(this.#props,value)}popperProps={onInteractOutside:this.onInteractOutside,onEscapeKeydown:this.onEscapeKeydown,
onOpenAutoFocus:this.onOpenAutoFocus,onCloseAutoFocus:this.onCloseAutoFocus}}function Tooltip($$anchor,$$props){push$1($$props,!0);let open2=prop($$props,"open",15,!1),onOpenChange=prop($$props,"onOpenChange",3,noop$1),onOpenChangeComplete=prop($$props,"onOpenChangeComplete",3,noop$1);TooltipRootState.create({open:boxWith$1(()=>open2(),v=>{open2(v),onOpenChange()(v)}),delayDuration:boxWith$1(()=>$$props.delayDuration),disableCloseOnTriggerClick:boxWith$1(()=>$$props.disableCloseOnTriggerClick),disableHoverableContent:boxWith$1(
()=>$$props.disableHoverableContent),ignoreNonKeyboardFocus:boxWith$1(()=>$$props.ignoreNonKeyboardFocus),disabled:boxWith$1(()=>$$props.disabled),onOpenChangeComplete:boxWith$1(()=>onOpenChangeComplete())}),Floating_layer($$anchor,{tooltip:!0,children:($$anchor2,$$slotProps)=>{var fragment_1=comment$2(),node2=first_child(fragment_1);snippet(node2,()=>$$props.children??noop$3),append($$anchor2,fragment_1)},$$slots:{default:!0}}),pop()}var root_4$A=from_html("<div><div><!></div></div>"),root_9$n=from_html(
()=>$$props.disableHoverableContent),ignoreNonKeyboardFocus:boxWith$1(()=>$$props.ignoreNonKeyboardFocus),disabled:boxWith$1(()=>$$props.disabled),onOpenChangeComplete:boxWith$1(()=>onOpenChangeComplete())}),Floating_layer($$anchor,{tooltip:!0,children:($$anchor2,$$slotProps)=>{var fragment_1=comment$2(),node2=first_child(fragment_1);snippet(node2,()=>$$props.children??noop$3),append($$anchor2,fragment_1)},$$slots:{default:!0}}),pop()}var root_4$A=from_html("<div><div><!></div></div>"),root_9$o=from_html(
"<div><div><!></div></div>");function Tooltip_content$1($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),ref2=prop($$props,"ref",15,null),side=prop($$props,"side",3,"top"),sideOffset=prop($$props,"sideOffset",3,0),align=prop($$props,"align",3,"center"),avoidCollisions=prop($$props,"avoidCollisions",3,!0),arrowPadding=prop($$props,"arrowPadding",3,0),sticky=prop($$props,"sticky",3,"partial"),hideWhenDetached=prop($$props,"hideWhenDetached",
3,!1),collisionPadding=prop($$props,"collisionPadding",3,0),onInteractOutside=prop($$props,"onInteractOutside",3,noop$1),onEscapeKeydown=prop($$props,"onEscapeKeydown",3,noop$1),forceMount=prop($$props,"forceMount",3,!1),restProps=rest_props($$props,["$$slots","$$events","$$legacy","children","child","id","ref","side","sideOffset","align","avoidCollisions","arrowPadding","sticky","strategy","hideWhenDetached","collisionPadding","onInteractOutside","onEscapeKeydown","forceMount","style"]);const contentState=TooltipContentState.
create({id:boxWith$1(()=>id2()),ref:boxWith$1(()=>ref2(),v=>ref2(v)),onInteractOutside:boxWith$1(()=>onInteractOutside()),onEscapeKeydown:boxWith$1(()=>onEscapeKeydown())}),floatingProps=user_derived(()=>({side:side(),sideOffset:sideOffset(),align:align(),avoidCollisions:avoidCollisions(),arrowPadding:arrowPadding(),sticky:sticky(),hideWhenDetached:hideWhenDetached(),collisionPadding:collisionPadding(),strategy:$$props.strategy})),mergedProps=user_derived(()=>mergeProps(restProps,get$4(floatingProps),
@ -1086,7 +1086,7 @@ contentState.props));var fragment=comment$2(),node2=first_child(fragment);{var c
props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_2,()=>$$props.child,()=>get$4($02))}append($$anchor4,fragment_3)},alternate=$$anchor4=>{var div=root_4$A();attribute_effect(div,()=>({...wrapperProps()}));var div_1=child(div);attribute_effect(div_1,()=>({...get$4(finalProps)}));var node_3=child(div_1);snippet(node_3,()=>$$props.children??noop$3),reset(div_1),reset(div),append($$anchor4,div)};if_block(node_1,$$render=>{$$props.child?$$render(consequent):
$$render(alternate,!1)})}append($$anchor3,fragment_2)};let $0=user_derived(()=>contentState.root.disableHoverableContent?"none":"auto");Popper_layer_force_mount($$anchor2,spread_props(()=>get$4(mergedProps),()=>contentState.popperProps,{get enabled(){return contentState.root.opts.open.current},get id(){return id2()},trapFocus:!1,loop:!1,preventScroll:!1,forceMount:!0,get ref(){return contentState.opts.ref},tooltip:!0,get shouldRender(){return contentState.shouldRender},get contentPointerEvents(){
return get$4($0)},popper,$$slots:{popper:!0}}))}},alternate_2=$$anchor2=>{var fragment_4=comment$2(),node_4=first_child(fragment_4);{var consequent_3=$$anchor3=>{{const popper=($$anchor4,$$arg0)=>{let props=()=>$$arg0?.().props,wrapperProps=()=>$$arg0?.().wrapperProps;const finalProps=user_derived(()=>mergeProps(props(),{style:getFloatingContentCSSVars("tooltip")},{style:$$props.style}));var fragment_6=comment$2(),node_5=first_child(fragment_6);{var consequent_2=$$anchor5=>{var fragment_7=comment$2(),
node_6=first_child(fragment_7);{let $02=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($02))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$n();attribute_effect(div_2,()=>({...wrapperProps()}));var div_3=child(div_2);attribute_effect(div_3,()=>({...get$4(finalProps)}));var node_7=child(div_3);snippet(node_7,()=>$$props.children??noop$3),reset(div_3),reset(div_2),append($$anchor5,
node_6=first_child(fragment_7);{let $02=user_derived(()=>({props:get$4(finalProps),wrapperProps:wrapperProps(),...contentState.snippetProps}));snippet(node_6,()=>$$props.child,()=>get$4($02))}append($$anchor5,fragment_7)},alternate_1=$$anchor5=>{var div_2=root_9$o();attribute_effect(div_2,()=>({...wrapperProps()}));var div_3=child(div_2);attribute_effect(div_3,()=>({...get$4(finalProps)}));var node_7=child(div_3);snippet(node_7,()=>$$props.children??noop$3),reset(div_3),reset(div_2),append($$anchor5,
div_2)};if_block(node_5,$$render=>{$$props.child?$$render(consequent_2):$$render(alternate_1,!1)})}append($$anchor4,fragment_6)};let $0=user_derived(()=>contentState.root.disableHoverableContent?"none":"auto");Popper_layer($$anchor3,spread_props(()=>get$4(mergedProps),()=>contentState.popperProps,{get open(){return contentState.root.opts.open.current},get id(){return id2()},trapFocus:!1,loop:!1,preventScroll:!1,forceMount:!1,get ref(){return contentState.opts.ref},tooltip:!0,get shouldRender(){return contentState.
shouldRender},get contentPointerEvents(){return get$4($0)},popper,$$slots:{popper:!0}}))}};if_block(node_4,$$render=>{forceMount()||$$render(consequent_3)},!0)}append($$anchor2,fragment_4)};if_block(node2,$$render=>{forceMount()?$$render(consequent_1):$$render(alternate_2,!1)})}append($$anchor,fragment),pop()}var root_3$V=from_html("<button><!></button>");function Tooltip_trigger$1($$anchor,$$props){const uid=props_id();push$1($$props,!0);let id2=prop($$props,"id",19,()=>createId(uid)),disabled=prop(
$$props,"disabled",3,!1),type2=prop($$props,"type",3,"button"),tabindex=prop($$props,"tabindex",3,0),ref2=prop($$props,"ref",15,null),restProps=rest_props($$props,["$$slots","$$events","$$legacy","children","child","id","disabled","type","tabindex","ref"]);const triggerState=TooltipTriggerState.create({id:boxWith$1(()=>id2()),disabled:boxWith$1(()=>disabled()??!1),tabindex:boxWith$1(()=>tabindex()??0),ref:boxWith$1(()=>ref2(),v=>ref2(v))}),mergedProps=user_derived(()=>mergeProps(restProps,triggerState.
@ -1238,9 +1238,9 @@ prefixLength:1024*10,suspiciousCharThresholdRatio:.15,maxAbsoluteNullBytes:2},DE
FILE_TYPE_ICONS={[FileTypeCategory.IMAGE]:Image$1,[FileTypeCategory.AUDIO]:Mic,[FileTypeCategory.TEXT]:File_text,[FileTypeCategory.PDF]:File$1},MODALITY_ICONS={[ModelModality.VISION]:Eye,[ModelModality.AUDIO]:Mic},MODALITY_LABELS={[ModelModality.VISION]:"Vision",[ModelModality.AUDIO]:"Audio"},CODE_BLOCK_REGEXP=/(```[\s\S]*?```|`[^`\n]+`)/g,LATEX_MATH_AND_CODE_PATTERN=new RegExp("(```[\\S\\s]*?```|`.*?`)|(?<!\\\\)\\\\\\[([\\S\\s]*?[^\\\\])\\\\]|(?<!\\\\)\\\\\\((.*?)\\\\\\)","g"),LATEX_LINEBREAK_REGEXP=/\$\$([\s\S]*?\\\\[\s\S]*?)\$\$/,
LINE_BREAK=/\r?\n/,PHRASE_PARENTS=new Set(["paragraph","heading","emphasis","strong","delete","link","linkReference","tableCell"]),NBSP=" ",TAB_AS_SPACES=NBSP.repeat(4),CONFIG_LOCALSTORAGE_KEY="LlamaCppWebui.config",USER_OVERRIDES_LOCALSTORAGE_KEY="LlamaCppWebui.userOverrides",FAVORITE_MODELS_LOCALSTORAGE_KEY="LlamaCppWebui.favoriteModels",MCP_DEFAULT_ENABLED_LOCALSTORAGE_KEY="LlamaCppWebui.mcpDefaultEnabled",IMAGE_NOT_ERROR_BOUND_SELECTOR="img:not([data-error-bound])",DATA_ERROR_BOUND_ATTR="er\
rorBound",DATA_ERROR_HANDLED_ATTR="errorHandled",BOOL_TRUE_STRING="true",DEFAULT_CLIENT_VERSION="1.0.0",DEFAULT_IMAGE_MIME_TYPE=MimeTypeImage.PNG,MCP_ALLOWED_ICON_MIME_TYPES=new Set([MimeTypeImage.PNG,MimeTypeImage.JPEG,MimeTypeImage.JPG,MimeTypeImage.SVG,MimeTypeImage.WEBP]),MCP_PROTOCOL_VERSION="2025-06-18",DEFAULT_MCP_CONFIG={protocolVersion:MCP_PROTOCOL_VERSION,capabilities:{tools:{listChanged:!0}},clientInfo:{name:"llama-webui-mcp",version:DEFAULT_CLIENT_VERSION},requestTimeoutSeconds:300,connectionTimeoutMs:1e4},
MCP_SERVER_ID_PREFIX="LlamaCpp-WebUI-MCP-Server",MCP_RECONNECT_INITIAL_DELAY=1e3,MCP_RECONNECT_BACKOFF_MULTIPLIER=2,MCP_RECONNECT_MAX_DELAY=3e4,MCP_RECONNECT_ATTEMPT_TIMEOUT_MS=15e3,MAX_DISPLAYED_MCP_AVATARS=3,EXPECTED_THEMED_ICON_PAIR_COUNT=2,CORS_PROXY_URL_PARAM="url",MCP_TRANSPORT_LABELS={[MCPTransportType.WEBSOCKET]:"WebSocket",[MCPTransportType.STREAMABLE_HTTP]:"HTTP",[MCPTransportType.SSE]:"SSE"},MCP_TRANSPORT_ICONS={[MCPTransportType.WEBSOCKET]:Zap,[MCPTransportType.STREAMABLE_HTTP]:Globe,
[MCPTransportType.SSE]:Radio},MCP_SERVER_URL_PLACEHOLDER="https://mcp.example.com/sse",MIN_AUTOCOMPLETE_INPUT_LENGTH=1,IMAGE_FILE_EXTENSION_REGEX=/\.(png|jpg|jpeg|gif|svg|webp)$/i,CODE_FILE_EXTENSION_REGEX=/\.(js|ts|json|yaml|yml|xml|html|css|py|rs|go|java|cpp|c|h|rb|sh|toml)$/i,TEXT_FILE_EXTENSION_REGEX=/\.(txt|md|log)$/i,PROTOCOL_PREFIX_REGEX=/^[a-z]+:\/\//,FILE_EXTENSION_REGEX=/\.[^.]+$/,DISPLAY_NAME_SEPARATOR_REGEX=/[-_]/,DATA_URI_BASE64_REGEX=/^data:([^;]+);base64,([A-Za-z0-9+/]+=*)$/,MCP_ATTACHMENT_NAME_PREFIX="\
mcp-attachment",MCP_RESOURCE_ATTACHMENT_ID_PREFIX="res",DEFAULT_IMAGE_EXTENSION="img",DEFAULT_RESOURCE_FILENAME="resource.txt",PATH_SEPARATOR="/",RESOURCE_TEXT_CONTENT_SEPARATOR=`
MCP_SERVER_ID_PREFIX="LlamaCpp-WebUI-MCP-Server",MCP_RECONNECT_INITIAL_DELAY=1e3,MCP_RECONNECT_BACKOFF_MULTIPLIER=2,MCP_RECONNECT_MAX_DELAY=3e4,MCP_RECONNECT_ATTEMPT_TIMEOUT_MS=15e3,MAX_DISPLAYED_MCP_AVATARS=3,EXPECTED_THEMED_ICON_PAIR_COUNT=2,CORS_PROXY_URL_PARAM="url",MCP_SESSION_ID_VISIBLE_CHARS=5,MCP_PARTIAL_REDACT_HEADERS=new Map([["mcp-session-id",MCP_SESSION_ID_VISIBLE_CHARS]]),REDACTED_HEADERS=new Set(["authorization","api-key","cookie","mcp-session-id","proxy-authorization","set-cookie",
"x-auth-token","x-api-key"]),MCP_TRANSPORT_LABELS={[MCPTransportType.WEBSOCKET]:"WebSocket",[MCPTransportType.STREAMABLE_HTTP]:"HTTP",[MCPTransportType.SSE]:"SSE"},MCP_TRANSPORT_ICONS={[MCPTransportType.WEBSOCKET]:Zap,[MCPTransportType.STREAMABLE_HTTP]:Globe,[MCPTransportType.SSE]:Radio},MCP_SERVER_URL_PLACEHOLDER="https://mcp.example.com/sse",MIN_AUTOCOMPLETE_INPUT_LENGTH=1,IMAGE_FILE_EXTENSION_REGEX=/\.(png|jpg|jpeg|gif|svg|webp)$/i,CODE_FILE_EXTENSION_REGEX=/\.(js|ts|json|yaml|yml|xml|html|css|py|rs|go|java|cpp|c|h|rb|sh|toml)$/i,
TEXT_FILE_EXTENSION_REGEX=/\.(txt|md|log)$/i,PROTOCOL_PREFIX_REGEX=/^[a-z]+:\/\//,FILE_EXTENSION_REGEX=/\.[^.]+$/,DISPLAY_NAME_SEPARATOR_REGEX=/[-_]/,DATA_URI_BASE64_REGEX=/^data:([^;]+);base64,([A-Za-z0-9+/]+=*)$/,MCP_ATTACHMENT_NAME_PREFIX="mcp-attachment",MCP_RESOURCE_ATTACHMENT_ID_PREFIX="res",DEFAULT_IMAGE_EXTENSION="img",DEFAULT_RESOURCE_FILENAME="resource.txt",PATH_SEPARATOR="/",RESOURCE_TEXT_CONTENT_SEPARATOR=`
`,RESOURCE_UNKNOWN_TYPE="unknown type",BINARY_CONTENT_LABEL="Binary content",IMAGE_MIME_TO_EXTENSION={[MimeTypeImage.JPEG]:"jpg",[MimeTypeImage.JPG]:"jpg",[MimeTypeImage.PNG]:"png",[MimeTypeImage.GIF]:"gif",[MimeTypeImage.WEBP]:"webp"},EXPORT_CONV_ID_TRIM_LENGTH=8,EXPORT_CONV_NAME_SUFFIX_MAX_LENGTH=20,ISO_TIMESTAMP_SLICE_LENGTH=19,NON_ALPHANUMERIC_REGEX=/[^a-z0-9]/gi,EXPORT_CONV_NONALNUM_REPLACEMENT="_",MULTIPLE_UNDERSCORE_REGEX=/_+/g,ISO_DATE_TIME_SEPARATOR="T",ISO_DATE_TIME_SEPARATOR_REPLACEMENT="\
_",ISO_TIME_SEPARATOR=":",ISO_TIME_SEPARATOR_REPLACEMENT="-",MODEL_ID_NOT_FOUND=-1,MODEL_ID_ORG_SEPARATOR="/",MODEL_ID_SEGMENT_SEPARATOR="-",MODEL_ID_QUANTIZATION_SEPARATOR=":",MODEL_QUANTIZATION_SEGMENT_RE=/^(I?Q\d+(_[A-Z0-9]+)*|F\d+|BF\d+|MXFP\d+(_[A-Z0-9]+)*)$/i,MODEL_CUSTOM_QUANTIZATION_PREFIX_RE=/^UD$/i,MODEL_PARAMS_RE=/^\d+(\.\d+)?[BbMmKkTt]$/,MODEL_ACTIVATED_PARAMS_RE=/^[Aa]\d+(\.\d+)?[BbMmKkTt]$/,MODEL_IGNORED_SEGMENTS=new Set(["GGUF","GGML"]),PRECISION_MULTIPLIER=1e6,PROCESSING_INFO_TIMEOUT=2e3,
@ -1302,55 +1302,56 @@ this.userOverrides.delete(key2),this.saveConfig()}syncWithServerDefaults(){const
if(webuiSettings)for(const[key2,value]of Object.entries(webuiSettings))!this.userOverrides.has(key2)&&value!==void 0&&setConfigValue(this.config,key2,value);this.saveConfig(),console.log("User overrides after sync:",Array.from(this.userOverrides))}forceSyncWithServerDefaults(){const propsDefaults=this.getServerDefaults(),webuiSettings=serverStore.webuiSettings;for(const key2 of ParameterSyncService.getSyncableParameterKeys())webuiSettings&&key2 in webuiSettings?setConfigValue(this.config,key2,webuiSettings[key2]):
propsDefaults[key2]!==void 0?setConfigValue(this.config,key2,""):key2 in SETTING_CONFIG_DEFAULT&&setConfigValue(this.config,key2,getConfigValue(SETTING_CONFIG_DEFAULT,key2)),this.userOverrides.delete(key2);this.saveConfig()}getConfig(key2){return this.config[key2]}getAllConfig(){return{...this.config}}canSyncParameter(key2){return ParameterSyncService.canSyncParameter(key2)}getParameterInfo(key2){const propsDefaults=this.getServerDefaults(),currentValue=getConfigValue(this.config,key2);return ParameterSyncService.
getParameterInfo(key2,currentValue??"",propsDefaults,this.userOverrides)}getParameterDiff(){const serverDefaults=this.getServerDefaults();if(Object.keys(serverDefaults).length===0)return{};const configAsRecord=configToParameterRecord(this.config,ParameterSyncService.getSyncableParameterKeys());return ParameterSyncService.createParameterDiff(configAsRecord,serverDefaults)}clearAllUserOverrides(){this.userOverrides.clear(),this.saveConfig(),console.log("Cleared all user overrides")}}const settingsStore=new SettingsStore,
config$1=()=>settingsStore.config;function getAuthHeaders(){const apiKey=config$1().apiKey?.toString().trim();return apiKey?{Authorization:`Bearer ${apiKey}`}:{}}function getJsonHeaders(){return{"Content-Type":"application/json",...getAuthHeaders()}}async function apiFetch(path2,options={}){const{authOnly=!1,headers:customHeaders,...fetchOptions}=options,headers={...authOnly?getAuthHeaders():getJsonHeaders(),...customHeaders},url2=path2.startsWith(UrlProtocol.HTTP)||path2.startsWith(UrlProtocol.
HTTPS)?path2:`${base}${path2}`,response=await fetch(url2,{...fetchOptions,headers});if(!response.ok){const errorMessage=await parseErrorMessage(response);throw new Error(errorMessage)}return response.json()}async function apiFetchWithParams(basePath,params,options={}){const url2=new URL(basePath,window.location.href);for(const[key2,value]of Object.entries(params))value!=null&&url2.searchParams.set(key2,value);const{authOnly=!1,headers:customHeaders,...fetchOptions}=options,headers={...authOnly?getAuthHeaders():
getJsonHeaders(),...customHeaders},response=await fetch(url2.toString(),{...fetchOptions,headers});if(!response.ok){const errorMessage=await parseErrorMessage(response);throw new Error(errorMessage)}return response.json()}async function apiPost(path2,body2,options={}){return apiFetch(path2,{method:"POST",body:JSON.stringify(body2),...options})}async function parseErrorMessage(response){try{const errorData=await response.json();if(errorData?.error?.message)return errorData.error.message;if(errorData?.
error&&typeof errorData.error=="string")return errorData.error;if(errorData?.message)return errorData.message}catch{}return`Request failed: ${response.status} ${response.statusText}`}function error(status,body2){throw new HttpError(status,body2)}async function validateApiKey(fetch2){try{const apiKey=config$1().apiKey,headers={"Content-Type":"application/json"};apiKey&&(headers.Authorization=`Bearer ${apiKey}`);const response=await fetch2(`${base}/props`,{headers});if(!response.ok){if(response.status===
401||response.status===403)throw error(401,"Access denied");console.warn(`Server responded with status ${response.status} during API key validation`);return}}catch(err){if(err&&typeof err=="object"&&"status"in err)throw err;console.warn("Cannot connect to server for API key validation:",err)}}function isMcpPromptUpload(file){return file.type===SpecialFileType.MCP_PROMPT&&!!file.mcpPrompt}function isMcpPromptAttachment(attachment){return attachment.type===AttachmentType.MCP_PROMPT}function isMcpResourceAttachment(attachment){
return attachment.type===AttachmentType.MCP_RESOURCE}function getUploadedFileCategory$1(file){const categoryByMime=getFileTypeCategory(file.type);return categoryByMime||getFileTypeCategoryByExtension(file.name)}function getAttachmentDisplayItems(options){const{uploadedFiles=[],attachments=[]}=options,items2=[];for(const file of uploadedFiles)items2.push({id:file.id,name:file.name,size:file.size,preview:file.preview,isImage:getUploadedFileCategory$1(file)===FileTypeCategory.IMAGE,isMcpPrompt:isMcpPromptUpload(
file),isLoading:file.isLoading,loadError:file.loadError,uploadedFile:file,textContent:file.textContent});for(const[index2,attachment]of attachments.entries()){const isImage2=isImageFile(attachment),isMcpPrompt=isMcpPromptAttachment(attachment),isMcpResource=isMcpResourceAttachment(attachment);items2.push({id:`attachment-${index2}`,name:attachment.name,preview:isImage2&&"base64Url"in attachment?attachment.base64Url:void 0,isImage:isImage2,isMcpPrompt,isMcpResource,attachment,attachmentIndex:index2,
textContent:"content"in attachment?attachment.content:void 0})}return items2.reverse()}function getUploadedFileCategory(uploadedFile){const categoryByMime=getFileTypeCategory(uploadedFile.type);return categoryByMime||getFileTypeCategoryByExtension(uploadedFile.name)}function isTextFile(attachment,uploadedFile){return uploadedFile?getUploadedFileCategory(uploadedFile)===FileTypeCategory.TEXT:attachment?attachment.type===AttachmentType.TEXT||attachment.type===AttachmentType.LEGACY_CONTEXT:!1}function isImageFile(attachment,uploadedFile){
return uploadedFile?getUploadedFileCategory(uploadedFile)===FileTypeCategory.IMAGE:attachment?attachment.type===AttachmentType.IMAGE:!1}function isPdfFile$1(attachment,uploadedFile){return uploadedFile?getUploadedFileCategory(uploadedFile)===FileTypeCategory.PDF:attachment?attachment.type===AttachmentType.PDF:!1}function isAudioFile(attachment,uploadedFile){return uploadedFile?getUploadedFileCategory(uploadedFile)===FileTypeCategory.AUDIO:attachment?attachment.type===AttachmentType.AUDIO:!1}function autoResizeTextarea(textareaElement){
textareaElement&&(textareaElement.style.height="1rem",textareaElement.style.height=textareaElement.scrollHeight+"px")}function findMessageById(messages,id2){if(id2)return messages.find(m=>m.id===id2)}function filterByLeafNodeId(messages,leafNodeId,includeRoot=!1){const result=[],nodeMap=new Map;for(const msg of messages)nodeMap.set(msg.id,msg);let startNode=nodeMap.get(leafNodeId);if(!startNode){let latestTime=-1;for(const msg of messages)msg.timestamp>latestTime&&(startNode=msg,latestTime=msg.timestamp)}
let currentNode=startNode;for(;currentNode&&((currentNode.type!=="root"||includeRoot)&&result.push(currentNode),currentNode.parent!==null);)currentNode=nodeMap.get(currentNode.parent);return result.sort((a,b)=>a.role===MessageRole.SYSTEM&&b.role!==MessageRole.SYSTEM?-1:a.role!==MessageRole.SYSTEM&&b.role===MessageRole.SYSTEM?1:a.timestamp-b.timestamp),result}function findLeafNode(messages,messageId){const nodeMap=new Map;for(const msg of messages)nodeMap.set(msg.id,msg);let currentNode=nodeMap.get(
messageId);for(;currentNode&&currentNode.children.length>0;){const lastChildId=currentNode.children[currentNode.children.length-1];currentNode=nodeMap.get(lastChildId)}return currentNode?.id??messageId}function findDescendantMessages(messages,messageId){const nodeMap=new Map;for(const msg of messages)nodeMap.set(msg.id,msg);const descendants=[],queue=[messageId];for(;queue.length>0;){const currentId=queue.shift(),currentNode=nodeMap.get(currentId);if(currentNode)for(const childId of currentNode.
children)descendants.push(childId),queue.push(childId)}return descendants}function getMessageSiblings(messages,messageId){const nodeMap=new Map;for(const msg of messages)nodeMap.set(msg.id,msg);const message=nodeMap.get(messageId);if(!message)return null;if(message.parent===null)return{message,siblingIds:[messageId],currentIndex:0,totalSiblings:1};const parentNode=nodeMap.get(message.parent);if(!parentNode)return{message,siblingIds:[messageId],currentIndex:0,totalSiblings:1};const siblingIds=parentNode.
children,siblingLeafIds=siblingIds.map(siblingId=>findLeafNode(messages,siblingId)),currentIndex=siblingIds.indexOf(messageId);return{message,siblingIds:siblingLeafIds,currentIndex,totalSiblings:siblingIds.length}}var core$5,hasRequiredCore$4;function requireCore$4(){if(hasRequiredCore$4)return core$5;hasRequiredCore$4=1;function deepFreeze(obj){return obj instanceof Map?obj.clear=obj.delete=obj.set=function(){throw new Error("map is read-only")}:obj instanceof Set&&(obj.add=obj.clear=obj.delete=
function(){throw new Error("set is read-only")}),Object.freeze(obj),Object.getOwnPropertyNames(obj).forEach(name=>{const prop2=obj[name],type2=typeof prop2;(type2==="object"||type2==="function")&&!Object.isFrozen(prop2)&&deepFreeze(prop2)}),obj}class Response2{constructor(mode){mode.data===void 0&&(mode.data={}),this.data=mode.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function escapeHTML(value){return value.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(
/"/g,"&quot;").replace(/'/g,"&#x27;")}function inherit$1(original,...objects){const result=Object.create(null);for(const key2 in original)result[key2]=original[key2];return objects.forEach(function(obj){for(const key2 in obj)result[key2]=obj[key2]}),result}const SPAN_CLOSE="</span>",emitsWrappingTags=node2=>!!node2.scope,scopeToCSSClass=(name,{prefix})=>{if(name.startsWith("language:"))return name.replace("language:","language-");if(name.includes(".")){const pieces=name.split(".");return[`${prefix}${pieces.
shift()}`,...pieces.map((x,i)=>`${x}${"_".repeat(i+1)}`)].join(" ")}return`${prefix}${name}`};class HTMLRenderer{constructor(parseTree3,options){this.buffer="",this.classPrefix=options.classPrefix,parseTree3.walk(this)}addText(text2){this.buffer+=escapeHTML(text2)}openNode(node2){if(!emitsWrappingTags(node2))return;const className=scopeToCSSClass(node2.scope,{prefix:this.classPrefix});this.span(className)}closeNode(node2){emitsWrappingTags(node2)&&(this.buffer+=SPAN_CLOSE)}value(){return this.buffer}span(className){
this.buffer+=`<span class="${className}">`}}const newNode=(opts={})=>{const result={children:[]};return Object.assign(result,opts),result};class TokenTree{constructor(){this.rootNode=newNode(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(node2){this.top.children.push(node2)}openNode(scope2){const node2=newNode({scope:scope2});this.add(node2),this.stack.push(node2)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){
for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(builder){return this.constructor._walk(builder,this.rootNode)}static _walk(builder,node2){return typeof node2=="string"?builder.addText(node2):node2.children&&(builder.openNode(node2),node2.children.forEach(child2=>this._walk(builder,child2)),builder.closeNode(node2)),builder}static _collapse(node2){typeof node2!="string"&&node2.children&&(node2.children.every(el=>typeof el=="string")?node2.children=[node2.children.
join("")]:node2.children.forEach(child2=>{TokenTree._collapse(child2)}))}}class TokenTreeEmitter extends TokenTree{constructor(options){super(),this.options=options}addText(text2){text2!==""&&this.add(text2)}startScope(scope2){this.openNode(scope2)}endScope(){this.closeNode()}__addSublanguage(emitter,name){const node2=emitter.root;name&&(node2.scope=`language:${name}`),this.add(node2)}toHTML(){return new HTMLRenderer(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function source2(re2){
return re2?typeof re2=="string"?re2:re2.source:null}function lookahead2(re2){return concat2("(?=",re2,")")}function anyNumberOfTimes(re2){return concat2("(?:",re2,")*")}function optional2(re2){return concat2("(?:",re2,")?")}function concat2(...args){return args.map(x=>source2(x)).join("")}function stripOptionsFromArgs2(args){const opts=args[args.length-1];return typeof opts=="object"&&opts.constructor===Object?(args.splice(args.length-1,1),opts):{}}function either2(...args){return"("+(stripOptionsFromArgs2(
args).capture?"":"?:")+args.map(x=>source2(x)).join("|")+")"}function countMatchGroups(re2){return new RegExp(re2.toString()+"|").exec("").length-1}function startsWith(re2,lexeme){const match=re2&&re2.exec(lexeme);return match&&match.index===0}const BACKREF_RE=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function _rewriteBackreferences(regexps,{joinWith}){let numCaptures=0;return regexps.map(regex=>{numCaptures+=1;const offset2=numCaptures;let re2=source2(regex),out="";for(;re2.length>0;){const match=BACKREF_RE.
exec(re2);if(!match){out+=re2;break}out+=re2.substring(0,match.index),re2=re2.substring(match.index+match[0].length),match[0][0]==="\\"&&match[1]?out+="\\"+String(Number(match[1])+offset2):(out+=match[0],match[0]==="("&&numCaptures++)}return out}).map(re2=>`(${re2})`).join(joinWith)}const MATCH_NOTHING_RE=/\b\B/,IDENT_RE2="[a-zA-Z]\\w*",UNDERSCORE_IDENT_RE="[a-zA-Z_]\\w*",NUMBER_RE="\\b\\d+(\\.\\d+)?",C_NUMBER_RE="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",BINARY_NUMBER_RE="\
\\b(0b[01]+)",RE_STARTERS_RE="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG=(opts={})=>{const beginShebang=/^#![ ]*\//;return opts.binary&&(opts.begin=concat2(beginShebang,/.*\b/,opts.binary,/\b.*/)),inherit$1({scope:"meta",begin:beginShebang,end:/$/,relevance:0,"on:begin":(m,resp)=>{m.index!==0&&resp.ignoreMatch()}},opts)},BACKSLASH_ESCAPE={begin:"\\\\[\\s\\S]",relevance:0},APOS_STRING_MODE={
scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[BACKSLASH_ESCAPE]},QUOTE_STRING_MODE={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[BACKSLASH_ESCAPE]},PHRASAL_WORDS_MODE={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},COMMENT=function(begin,end,modeOptions={}){const mode=inherit$1({scope:"comment",begin,end,contains:[]},modeOptions);mode.contains.push({scope:"doctag",begin:"[ \
]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const ENGLISH_WORD=either2("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return mode.contains.push({begin:concat2(/[ ]+/,"(",ENGLISH_WORD,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),mode},C_LINE_COMMENT_MODE=COMMENT("//","$"),C_BLOCK_COMMENT_MODE=COMMENT("/\\*","\\*/"),HASH_COMMENT_MODE=COMMENT("#","$"),
NUMBER_MODE={scope:"number",begin:NUMBER_RE,relevance:0},C_NUMBER_MODE={scope:"number",begin:C_NUMBER_RE,relevance:0},BINARY_NUMBER_MODE={scope:"number",begin:BINARY_NUMBER_RE,relevance:0},REGEXP_MODE={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[BACKSLASH_ESCAPE]}]},TITLE_MODE={scope:"title",begin:IDENT_RE2,relevance:0},UNDERSCORE_TITLE_MODE={scope:"title",begin:UNDERSCORE_IDENT_RE,relevance:0},METHOD_GUARD={begin:"\
\\.\\s*"+UNDERSCORE_IDENT_RE,relevance:0};var MODES2=Object.freeze({__proto__:null,APOS_STRING_MODE,BACKSLASH_ESCAPE,BINARY_NUMBER_MODE,BINARY_NUMBER_RE,COMMENT,C_BLOCK_COMMENT_MODE,C_LINE_COMMENT_MODE,C_NUMBER_MODE,C_NUMBER_RE,END_SAME_AS_BEGIN:function(mode){return Object.assign(mode,{"on:begin":(m,resp)=>{resp.data._beginMatch=m[1]},"on:end":(m,resp)=>{resp.data._beginMatch!==m[1]&&resp.ignoreMatch()}})},HASH_COMMENT_MODE,IDENT_RE:IDENT_RE2,MATCH_NOTHING_RE,METHOD_GUARD,NUMBER_MODE,NUMBER_RE,
PHRASAL_WORDS_MODE,QUOTE_STRING_MODE,REGEXP_MODE,RE_STARTERS_RE,SHEBANG,TITLE_MODE,UNDERSCORE_IDENT_RE,UNDERSCORE_TITLE_MODE});function skipIfHasPrecedingDot(match,response){match.input[match.index-1]==="."&&response.ignoreMatch()}function scopeClassName(mode,_parent){mode.className!==void 0&&(mode.scope=mode.className,delete mode.className)}function beginKeywords(mode,parent){parent&&mode.beginKeywords&&(mode.begin="\\b("+mode.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",mode.__beforeBegin=
skipIfHasPrecedingDot,mode.keywords=mode.keywords||mode.beginKeywords,delete mode.beginKeywords,mode.relevance===void 0&&(mode.relevance=0))}function compileIllegal(mode,_parent){Array.isArray(mode.illegal)&&(mode.illegal=either2(...mode.illegal))}function compileMatch(mode,_parent){if(mode.match){if(mode.begin||mode.end)throw new Error("begin & end are not supported with match");mode.begin=mode.match,delete mode.match}}function compileRelevance(mode,_parent){mode.relevance===void 0&&(mode.relevance=
1)}const beforeMatchExt=(mode,parent)=>{if(!mode.beforeMatch)return;if(mode.starts)throw new Error("beforeMatch cannot be used with starts");const originalMode=Object.assign({},mode);Object.keys(mode).forEach(key2=>{delete mode[key2]}),mode.keywords=originalMode.keywords,mode.begin=concat2(originalMode.beforeMatch,lookahead2(originalMode.begin)),mode.starts={relevance:0,contains:[Object.assign(originalMode,{endsParent:!0})]},mode.relevance=0,delete originalMode.beforeMatch},COMMON_KEYWORDS=["of",
"and","for","in","not","or","if","then","parent","list","value"],DEFAULT_KEYWORD_SCOPE="keyword";function compileKeywords(rawKeywords,caseInsensitive,scopeName=DEFAULT_KEYWORD_SCOPE){const compiledKeywords=Object.create(null);return typeof rawKeywords=="string"?compileList(scopeName,rawKeywords.split(" ")):Array.isArray(rawKeywords)?compileList(scopeName,rawKeywords):Object.keys(rawKeywords).forEach(function(scopeName2){Object.assign(compiledKeywords,compileKeywords(rawKeywords[scopeName2],caseInsensitive,
scopeName2))}),compiledKeywords;function compileList(scopeName2,keywordList){caseInsensitive&&(keywordList=keywordList.map(x=>x.toLowerCase())),keywordList.forEach(function(keyword2){const pair=keyword2.split("|");compiledKeywords[pair[0]]=[scopeName2,scoreForKeyword(pair[0],pair[1])]})}}function scoreForKeyword(keyword2,providedScore){return providedScore?Number(providedScore):commonKeyword(keyword2)?0:1}function commonKeyword(keyword2){return COMMON_KEYWORDS.includes(keyword2.toLowerCase())}const seenDeprecations={},
error2=message=>{console.error(message)},warn2=(message,...args)=>{console.log(`WARN: ${message}`,...args)},deprecated2=(version3,message)=>{seenDeprecations[`${version3}/${message}`]||(console.log(`Deprecated as of ${version3}. ${message}`),seenDeprecations[`${version3}/${message}`]=!0)},MultiClassError=new Error;function remapScopeNames(mode,regexes,{key:key2}){let offset2=0;const scopeNames=mode[key2],emit={},positions={};for(let i=1;i<=regexes.length;i++)positions[i+offset2]=scopeNames[i],emit[i+
offset2]=!0,offset2+=countMatchGroups(regexes[i-1]);mode[key2]=positions,mode[key2]._emit=emit,mode[key2]._multi=!0}function beginMultiClass(mode){if(Array.isArray(mode.begin)){if(mode.skip||mode.excludeBegin||mode.returnBegin)throw error2("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),MultiClassError;if(typeof mode.beginScope!="object"||mode.beginScope===null)throw error2("beginScope must be object"),MultiClassError;remapScopeNames(mode,mode.begin,{key:"beginScope"}),mode.
begin=_rewriteBackreferences(mode.begin,{joinWith:""})}}function endMultiClass(mode){if(Array.isArray(mode.end)){if(mode.skip||mode.excludeEnd||mode.returnEnd)throw error2("skip, excludeEnd, returnEnd not compatible with endScope: {}"),MultiClassError;if(typeof mode.endScope!="object"||mode.endScope===null)throw error2("endScope must be object"),MultiClassError;remapScopeNames(mode,mode.end,{key:"endScope"}),mode.end=_rewriteBackreferences(mode.end,{joinWith:""})}}function scopeSugar(mode){mode.
scope&&typeof mode.scope=="object"&&mode.scope!==null&&(mode.beginScope=mode.scope,delete mode.scope)}function MultiClass(mode){scopeSugar(mode),typeof mode.beginScope=="string"&&(mode.beginScope={_wrap:mode.beginScope}),typeof mode.endScope=="string"&&(mode.endScope={_wrap:mode.endScope}),beginMultiClass(mode),endMultiClass(mode)}function compileLanguage(language2){function langRe(value,global2){return new RegExp(source2(value),"m"+(language2.case_insensitive?"i":"")+(language2.unicodeRegex?"u":
"")+(global2?"g":""))}class MultiRegex{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(re2,opts){opts.position=this.position++,this.matchIndexes[this.matchAt]=opts,this.regexes.push([opts,re2]),this.matchAt+=countMatchGroups(re2)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);const terminators=this.regexes.map(el=>el[1]);this.matcherRe=langRe(_rewriteBackreferences(terminators,{joinWith:"|"}),!0),this.lastIndex=0}exec(s2){this.matcherRe.lastIndex=
this.lastIndex;const match=this.matcherRe.exec(s2);if(!match)return null;const i=match.findIndex((el,i2)=>i2>0&&el!==void 0),matchData=this.matchIndexes[i];return match.splice(0,i),Object.assign(match,matchData)}}class ResumableMultiRegex{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(index2){if(this.multiRegexes[index2])return this.multiRegexes[index2];const matcher=new MultiRegex;return this.rules.slice(index2).forEach(([re2,opts])=>matcher.
addRule(re2,opts)),matcher.compile(),this.multiRegexes[index2]=matcher,matcher}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(re2,opts){this.rules.push([re2,opts]),opts.type==="begin"&&this.count++}exec(s2){const m=this.getMatcher(this.regexIndex);m.lastIndex=this.lastIndex;let result=m.exec(s2);if(this.resumingScanAtSamePosition()&&!(result&&result.index===this.lastIndex)){const m2=this.getMatcher(0);m2.lastIndex=this.lastIndex+1,result=m2.exec(s2)}
return result&&(this.regexIndex+=result.position+1,this.regexIndex===this.count&&this.considerAll()),result}}function buildModeRegex(mode){const mm=new ResumableMultiRegex;return mode.contains.forEach(term=>mm.addRule(term.begin,{rule:term,type:"begin"})),mode.terminatorEnd&&mm.addRule(mode.terminatorEnd,{type:"end"}),mode.illegal&&mm.addRule(mode.illegal,{type:"illegal"}),mm}function compileMode(mode,parent){const cmode=mode;if(mode.isCompiled)return cmode;[scopeClassName,compileMatch,MultiClass,
beforeMatchExt].forEach(ext=>ext(mode,parent)),language2.compilerExtensions.forEach(ext=>ext(mode,parent)),mode.__beforeBegin=null,[beginKeywords,compileIllegal,compileRelevance].forEach(ext=>ext(mode,parent)),mode.isCompiled=!0;let keywordPattern=null;return typeof mode.keywords=="object"&&mode.keywords.$pattern&&(mode.keywords=Object.assign({},mode.keywords),keywordPattern=mode.keywords.$pattern,delete mode.keywords.$pattern),keywordPattern=keywordPattern||/\w+/,mode.keywords&&(mode.keywords=compileKeywords(
mode.keywords,language2.case_insensitive)),cmode.keywordPatternRe=langRe(keywordPattern,!0),parent&&(mode.begin||(mode.begin=/\B|\b/),cmode.beginRe=langRe(cmode.begin),!mode.end&&!mode.endsWithParent&&(mode.end=/\B|\b/),mode.end&&(cmode.endRe=langRe(cmode.end)),cmode.terminatorEnd=source2(cmode.end)||"",mode.endsWithParent&&parent.terminatorEnd&&(cmode.terminatorEnd+=(mode.end?"|":"")+parent.terminatorEnd)),mode.illegal&&(cmode.illegalRe=langRe(mode.illegal)),mode.contains||(mode.contains=[]),mode.
contains=[].concat(...mode.contains.map(function(c2){return expandOrCloneMode(c2==="self"?mode:c2)})),mode.contains.forEach(function(c2){compileMode(c2,cmode)}),mode.starts&&compileMode(mode.starts,parent),cmode.matcher=buildModeRegex(cmode),cmode}if(language2.compilerExtensions||(language2.compilerExtensions=[]),language2.contains&&language2.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return language2.classNameAliases=
inherit$1(language2.classNameAliases||{}),compileMode(language2)}function dependencyOnParent(mode){return mode?mode.endsWithParent||dependencyOnParent(mode.starts):!1}function expandOrCloneMode(mode){return mode.variants&&!mode.cachedVariants&&(mode.cachedVariants=mode.variants.map(function(variant){return inherit$1(mode,{variants:null},variant)})),mode.cachedVariants?mode.cachedVariants:dependencyOnParent(mode)?inherit$1(mode,{starts:mode.starts?inherit$1(mode.starts):null}):Object.isFrozen(mode)?
inherit$1(mode):mode}var version2="11.11.1";class HTMLInjectionError extends Error{constructor(reason,html2){super(reason),this.name="HTMLInjectionError",this.html=html2}}const escape2=escapeHTML,inherit=inherit$1,NO_MATCH=Symbol("nomatch"),MAX_KEYWORD_HITS=7,HLJS=function(hljs){const languages=Object.create(null),aliases=Object.create(null),plugins=[];let SAFE_MODE=!0;const LANGUAGE_NOT_FOUND="Could not find the language '{}', did you forget to load/include a language module?",PLAINTEXT_LANGUAGE={
disableAutodetect:!0,name:"Plain text",contains:[]};let options={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:TokenTreeEmitter};function shouldNotHighlight(languageName){return options.noHighlightRe.test(languageName)}function blockLanguage(block2){let classes=block2.className+" ";classes+=block2.parentNode?block2.parentNode.className:"";const match=options.
languageDetectRe.exec(classes);if(match){const language2=getLanguage(match[1]);return language2||(warn2(LANGUAGE_NOT_FOUND.replace("{}",match[1])),warn2("Falling back to no-highlight mode for this block.",block2)),language2?match[1]:"no-highlight"}return classes.split(/\s+/).find(_class=>shouldNotHighlight(_class)||getLanguage(_class))}function highlight2(codeOrLanguageName,optionsOrCode,ignoreIllegals){let code2="",languageName="";typeof optionsOrCode=="object"?(code2=codeOrLanguageName,ignoreIllegals=
optionsOrCode.ignoreIllegals,languageName=optionsOrCode.language):(deprecated2("10.7.0","highlight(lang, code, ...args) has been deprecated."),deprecated2("10.7.0",`Please use highlight(code, options) instead.
config$1=()=>settingsStore.config;function redactValue(value,showLastChars){return showLastChars?`....${value.slice(-showLastChars)}`:"[redacted]"}function getAuthHeaders(){const apiKey=config$1().apiKey?.toString().trim();return apiKey?{Authorization:`Bearer ${apiKey}`}:{}}function getJsonHeaders(){return{"Content-Type":"application/json",...getAuthHeaders()}}function sanitizeHeaders(headers,extraRedactedHeaders,partialRedactHeaders){if(!headers)return{};const normalized=new Headers(headers),sanitized={},
redactedHeaders=new Set(Array.from(extraRedactedHeaders??[],header=>header.toLowerCase()));for(const[key2,value]of normalized.entries()){const normalizedKey=key2.toLowerCase(),partialChars=partialRedactHeaders?.get(normalizedKey);partialChars!==void 0?sanitized[key2]=redactValue(value,partialChars):REDACTED_HEADERS.has(normalizedKey)||redactedHeaders.has(normalizedKey)?sanitized[key2]=redactValue(value):sanitized[key2]=value}return sanitized}async function apiFetch(path2,options={}){const{authOnly=!1,
headers:customHeaders,...fetchOptions}=options,headers={...authOnly?getAuthHeaders():getJsonHeaders(),...customHeaders},url2=path2.startsWith(UrlProtocol.HTTP)||path2.startsWith(UrlProtocol.HTTPS)?path2:`${base}${path2}`,response=await fetch(url2,{...fetchOptions,headers});if(!response.ok){const errorMessage=await parseErrorMessage(response);throw new Error(errorMessage)}return response.json()}async function apiFetchWithParams(basePath,params,options={}){const url2=new URL(basePath,window.location.
href);for(const[key2,value]of Object.entries(params))value!=null&&url2.searchParams.set(key2,value);const{authOnly=!1,headers:customHeaders,...fetchOptions}=options,headers={...authOnly?getAuthHeaders():getJsonHeaders(),...customHeaders},response=await fetch(url2.toString(),{...fetchOptions,headers});if(!response.ok){const errorMessage=await parseErrorMessage(response);throw new Error(errorMessage)}return response.json()}async function apiPost(path2,body2,options={}){return apiFetch(path2,{method:"\
POST",body:JSON.stringify(body2),...options})}async function parseErrorMessage(response){try{const errorData=await response.json();if(errorData?.error?.message)return errorData.error.message;if(errorData?.error&&typeof errorData.error=="string")return errorData.error;if(errorData?.message)return errorData.message}catch{}return`Request failed: ${response.status} ${response.statusText}`}function error(status,body2){throw new HttpError(status,body2)}async function validateApiKey(fetch2){try{const apiKey=config$1().
apiKey,headers={"Content-Type":"application/json"};apiKey&&(headers.Authorization=`Bearer ${apiKey}`);const response=await fetch2(`${base}/props`,{headers});if(!response.ok){if(response.status===401||response.status===403)throw error(401,"Access denied");console.warn(`Server responded with status ${response.status} during API key validation`);return}}catch(err){if(err&&typeof err=="object"&&"status"in err)throw err;console.warn("Cannot connect to server for API key validation:",err)}}function isMcpPromptUpload(file){
return file.type===SpecialFileType.MCP_PROMPT&&!!file.mcpPrompt}function isMcpPromptAttachment(attachment){return attachment.type===AttachmentType.MCP_PROMPT}function isMcpResourceAttachment(attachment){return attachment.type===AttachmentType.MCP_RESOURCE}function getUploadedFileCategory$1(file){const categoryByMime=getFileTypeCategory(file.type);return categoryByMime||getFileTypeCategoryByExtension(file.name)}function getAttachmentDisplayItems(options){const{uploadedFiles=[],attachments=[]}=options,
items2=[];for(const file of uploadedFiles)items2.push({id:file.id,name:file.name,size:file.size,preview:file.preview,isImage:getUploadedFileCategory$1(file)===FileTypeCategory.IMAGE,isMcpPrompt:isMcpPromptUpload(file),isLoading:file.isLoading,loadError:file.loadError,uploadedFile:file,textContent:file.textContent});for(const[index2,attachment]of attachments.entries()){const isImage2=isImageFile(attachment),isMcpPrompt=isMcpPromptAttachment(attachment),isMcpResource=isMcpResourceAttachment(attachment);
items2.push({id:`attachment-${index2}`,name:attachment.name,preview:isImage2&&"base64Url"in attachment?attachment.base64Url:void 0,isImage:isImage2,isMcpPrompt,isMcpResource,attachment,attachmentIndex:index2,textContent:"content"in attachment?attachment.content:void 0})}return items2.reverse()}function getUploadedFileCategory(uploadedFile){const categoryByMime=getFileTypeCategory(uploadedFile.type);return categoryByMime||getFileTypeCategoryByExtension(uploadedFile.name)}function isTextFile(attachment,uploadedFile){
return uploadedFile?getUploadedFileCategory(uploadedFile)===FileTypeCategory.TEXT:attachment?attachment.type===AttachmentType.TEXT||attachment.type===AttachmentType.LEGACY_CONTEXT:!1}function isImageFile(attachment,uploadedFile){return uploadedFile?getUploadedFileCategory(uploadedFile)===FileTypeCategory.IMAGE:attachment?attachment.type===AttachmentType.IMAGE:!1}function isPdfFile$1(attachment,uploadedFile){return uploadedFile?getUploadedFileCategory(uploadedFile)===FileTypeCategory.PDF:attachment?
attachment.type===AttachmentType.PDF:!1}function isAudioFile(attachment,uploadedFile){return uploadedFile?getUploadedFileCategory(uploadedFile)===FileTypeCategory.AUDIO:attachment?attachment.type===AttachmentType.AUDIO:!1}function autoResizeTextarea(textareaElement){textareaElement&&(textareaElement.style.height="1rem",textareaElement.style.height=textareaElement.scrollHeight+"px")}function findMessageById(messages,id2){if(id2)return messages.find(m=>m.id===id2)}function filterByLeafNodeId(messages,leafNodeId,includeRoot=!1){
const result=[],nodeMap=new Map;for(const msg of messages)nodeMap.set(msg.id,msg);let startNode=nodeMap.get(leafNodeId);if(!startNode){let latestTime=-1;for(const msg of messages)msg.timestamp>latestTime&&(startNode=msg,latestTime=msg.timestamp)}let currentNode=startNode;for(;currentNode&&((currentNode.type!=="root"||includeRoot)&&result.push(currentNode),currentNode.parent!==null);)currentNode=nodeMap.get(currentNode.parent);return result.sort((a,b)=>a.role===MessageRole.SYSTEM&&b.role!==MessageRole.
SYSTEM?-1:a.role!==MessageRole.SYSTEM&&b.role===MessageRole.SYSTEM?1:a.timestamp-b.timestamp),result}function findLeafNode(messages,messageId){const nodeMap=new Map;for(const msg of messages)nodeMap.set(msg.id,msg);let currentNode=nodeMap.get(messageId);for(;currentNode&&currentNode.children.length>0;){const lastChildId=currentNode.children[currentNode.children.length-1];currentNode=nodeMap.get(lastChildId)}return currentNode?.id??messageId}function findDescendantMessages(messages,messageId){const nodeMap=new Map;
for(const msg of messages)nodeMap.set(msg.id,msg);const descendants=[],queue=[messageId];for(;queue.length>0;){const currentId=queue.shift(),currentNode=nodeMap.get(currentId);if(currentNode)for(const childId of currentNode.children)descendants.push(childId),queue.push(childId)}return descendants}function getMessageSiblings(messages,messageId){const nodeMap=new Map;for(const msg of messages)nodeMap.set(msg.id,msg);const message=nodeMap.get(messageId);if(!message)return null;if(message.parent===null)
return{message,siblingIds:[messageId],currentIndex:0,totalSiblings:1};const parentNode=nodeMap.get(message.parent);if(!parentNode)return{message,siblingIds:[messageId],currentIndex:0,totalSiblings:1};const siblingIds=parentNode.children,siblingLeafIds=siblingIds.map(siblingId=>findLeafNode(messages,siblingId)),currentIndex=siblingIds.indexOf(messageId);return{message,siblingIds:siblingLeafIds,currentIndex,totalSiblings:siblingIds.length}}var core$5,hasRequiredCore$4;function requireCore$4(){if(hasRequiredCore$4)
return core$5;hasRequiredCore$4=1;function deepFreeze(obj){return obj instanceof Map?obj.clear=obj.delete=obj.set=function(){throw new Error("map is read-only")}:obj instanceof Set&&(obj.add=obj.clear=obj.delete=function(){throw new Error("set is read-only")}),Object.freeze(obj),Object.getOwnPropertyNames(obj).forEach(name=>{const prop2=obj[name],type2=typeof prop2;(type2==="object"||type2==="function")&&!Object.isFrozen(prop2)&&deepFreeze(prop2)}),obj}class Response2{constructor(mode){mode.data===
void 0&&(mode.data={}),this.data=mode.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function escapeHTML(value){return value.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}function inherit$1(original,...objects){const result=Object.create(null);for(const key2 in original)result[key2]=original[key2];return objects.forEach(function(obj){for(const key2 in obj)result[key2]=obj[key2]}),result}const SPAN_CLOSE="</span>",
emitsWrappingTags=node2=>!!node2.scope,scopeToCSSClass=(name,{prefix})=>{if(name.startsWith("language:"))return name.replace("language:","language-");if(name.includes(".")){const pieces=name.split(".");return[`${prefix}${pieces.shift()}`,...pieces.map((x,i)=>`${x}${"_".repeat(i+1)}`)].join(" ")}return`${prefix}${name}`};class HTMLRenderer{constructor(parseTree3,options){this.buffer="",this.classPrefix=options.classPrefix,parseTree3.walk(this)}addText(text2){this.buffer+=escapeHTML(text2)}openNode(node2){
if(!emitsWrappingTags(node2))return;const className=scopeToCSSClass(node2.scope,{prefix:this.classPrefix});this.span(className)}closeNode(node2){emitsWrappingTags(node2)&&(this.buffer+=SPAN_CLOSE)}value(){return this.buffer}span(className){this.buffer+=`<span class="${className}">`}}const newNode=(opts={})=>{const result={children:[]};return Object.assign(result,opts),result};class TokenTree{constructor(){this.rootNode=newNode(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-
1]}get root(){return this.rootNode}add(node2){this.top.children.push(node2)}openNode(scope2){const node2=newNode({scope:scope2});this.add(node2),this.stack.push(node2)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(builder){return this.constructor._walk(builder,this.rootNode)}static _walk(builder,node2){return typeof node2=="string"?builder.addText(node2):node2.children&&(builder.openNode(
node2),node2.children.forEach(child2=>this._walk(builder,child2)),builder.closeNode(node2)),builder}static _collapse(node2){typeof node2!="string"&&node2.children&&(node2.children.every(el=>typeof el=="string")?node2.children=[node2.children.join("")]:node2.children.forEach(child2=>{TokenTree._collapse(child2)}))}}class TokenTreeEmitter extends TokenTree{constructor(options){super(),this.options=options}addText(text2){text2!==""&&this.add(text2)}startScope(scope2){this.openNode(scope2)}endScope(){
this.closeNode()}__addSublanguage(emitter,name){const node2=emitter.root;name&&(node2.scope=`language:${name}`),this.add(node2)}toHTML(){return new HTMLRenderer(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function source2(re2){return re2?typeof re2=="string"?re2:re2.source:null}function lookahead2(re2){return concat2("(?=",re2,")")}function anyNumberOfTimes(re2){return concat2("(?:",re2,")*")}function optional2(re2){return concat2("(?:",re2,")?")}function concat2(...args){
return args.map(x=>source2(x)).join("")}function stripOptionsFromArgs2(args){const opts=args[args.length-1];return typeof opts=="object"&&opts.constructor===Object?(args.splice(args.length-1,1),opts):{}}function either2(...args){return"("+(stripOptionsFromArgs2(args).capture?"":"?:")+args.map(x=>source2(x)).join("|")+")"}function countMatchGroups(re2){return new RegExp(re2.toString()+"|").exec("").length-1}function startsWith(re2,lexeme){const match=re2&&re2.exec(lexeme);return match&&match.index===
0}const BACKREF_RE=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function _rewriteBackreferences(regexps,{joinWith}){let numCaptures=0;return regexps.map(regex=>{numCaptures+=1;const offset2=numCaptures;let re2=source2(regex),out="";for(;re2.length>0;){const match=BACKREF_RE.exec(re2);if(!match){out+=re2;break}out+=re2.substring(0,match.index),re2=re2.substring(match.index+match[0].length),match[0][0]==="\\"&&match[1]?out+="\\"+String(Number(match[1])+offset2):(out+=match[0],match[0]==="("&&numCaptures++)}
return out}).map(re2=>`(${re2})`).join(joinWith)}const MATCH_NOTHING_RE=/\b\B/,IDENT_RE2="[a-zA-Z]\\w*",UNDERSCORE_IDENT_RE="[a-zA-Z_]\\w*",NUMBER_RE="\\b\\d+(\\.\\d+)?",C_NUMBER_RE="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",BINARY_NUMBER_RE="\\b(0b[01]+)",RE_STARTERS_RE="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG=(opts={})=>{const beginShebang=/^#![ ]*\//;return opts.
binary&&(opts.begin=concat2(beginShebang,/.*\b/,opts.binary,/\b.*/)),inherit$1({scope:"meta",begin:beginShebang,end:/$/,relevance:0,"on:begin":(m,resp)=>{m.index!==0&&resp.ignoreMatch()}},opts)},BACKSLASH_ESCAPE={begin:"\\\\[\\s\\S]",relevance:0},APOS_STRING_MODE={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[BACKSLASH_ESCAPE]},QUOTE_STRING_MODE={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[BACKSLASH_ESCAPE]},PHRASAL_WORDS_MODE={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},
COMMENT=function(begin,end,modeOptions={}){const mode=inherit$1({scope:"comment",begin,end,contains:[]},modeOptions);mode.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const ENGLISH_WORD=either2("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return mode.contains.push({begin:concat2(/[ ]+/,"(",ENGLISH_WORD,
/[.]?[:]?([.][ ]|[ ])/,"){3}")}),mode},C_LINE_COMMENT_MODE=COMMENT("//","$"),C_BLOCK_COMMENT_MODE=COMMENT("/\\*","\\*/"),HASH_COMMENT_MODE=COMMENT("#","$"),NUMBER_MODE={scope:"number",begin:NUMBER_RE,relevance:0},C_NUMBER_MODE={scope:"number",begin:C_NUMBER_RE,relevance:0},BINARY_NUMBER_MODE={scope:"number",begin:BINARY_NUMBER_RE,relevance:0},REGEXP_MODE={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[BACKSLASH_ESCAPE]}]},
TITLE_MODE={scope:"title",begin:IDENT_RE2,relevance:0},UNDERSCORE_TITLE_MODE={scope:"title",begin:UNDERSCORE_IDENT_RE,relevance:0},METHOD_GUARD={begin:"\\.\\s*"+UNDERSCORE_IDENT_RE,relevance:0};var MODES2=Object.freeze({__proto__:null,APOS_STRING_MODE,BACKSLASH_ESCAPE,BINARY_NUMBER_MODE,BINARY_NUMBER_RE,COMMENT,C_BLOCK_COMMENT_MODE,C_LINE_COMMENT_MODE,C_NUMBER_MODE,C_NUMBER_RE,END_SAME_AS_BEGIN:function(mode){return Object.assign(mode,{"on:begin":(m,resp)=>{resp.data._beginMatch=m[1]},"on:end":(m,resp)=>{
resp.data._beginMatch!==m[1]&&resp.ignoreMatch()}})},HASH_COMMENT_MODE,IDENT_RE:IDENT_RE2,MATCH_NOTHING_RE,METHOD_GUARD,NUMBER_MODE,NUMBER_RE,PHRASAL_WORDS_MODE,QUOTE_STRING_MODE,REGEXP_MODE,RE_STARTERS_RE,SHEBANG,TITLE_MODE,UNDERSCORE_IDENT_RE,UNDERSCORE_TITLE_MODE});function skipIfHasPrecedingDot(match,response){match.input[match.index-1]==="."&&response.ignoreMatch()}function scopeClassName(mode,_parent){mode.className!==void 0&&(mode.scope=mode.className,delete mode.className)}function beginKeywords(mode,parent){
parent&&mode.beginKeywords&&(mode.begin="\\b("+mode.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",mode.__beforeBegin=skipIfHasPrecedingDot,mode.keywords=mode.keywords||mode.beginKeywords,delete mode.beginKeywords,mode.relevance===void 0&&(mode.relevance=0))}function compileIllegal(mode,_parent){Array.isArray(mode.illegal)&&(mode.illegal=either2(...mode.illegal))}function compileMatch(mode,_parent){if(mode.match){if(mode.begin||mode.end)throw new Error("begin & end are not supported wi\
th match");mode.begin=mode.match,delete mode.match}}function compileRelevance(mode,_parent){mode.relevance===void 0&&(mode.relevance=1)}const beforeMatchExt=(mode,parent)=>{if(!mode.beforeMatch)return;if(mode.starts)throw new Error("beforeMatch cannot be used with starts");const originalMode=Object.assign({},mode);Object.keys(mode).forEach(key2=>{delete mode[key2]}),mode.keywords=originalMode.keywords,mode.begin=concat2(originalMode.beforeMatch,lookahead2(originalMode.begin)),mode.starts={relevance:0,
contains:[Object.assign(originalMode,{endsParent:!0})]},mode.relevance=0,delete originalMode.beforeMatch},COMMON_KEYWORDS=["of","and","for","in","not","or","if","then","parent","list","value"],DEFAULT_KEYWORD_SCOPE="keyword";function compileKeywords(rawKeywords,caseInsensitive,scopeName=DEFAULT_KEYWORD_SCOPE){const compiledKeywords=Object.create(null);return typeof rawKeywords=="string"?compileList(scopeName,rawKeywords.split(" ")):Array.isArray(rawKeywords)?compileList(scopeName,rawKeywords):Object.
keys(rawKeywords).forEach(function(scopeName2){Object.assign(compiledKeywords,compileKeywords(rawKeywords[scopeName2],caseInsensitive,scopeName2))}),compiledKeywords;function compileList(scopeName2,keywordList){caseInsensitive&&(keywordList=keywordList.map(x=>x.toLowerCase())),keywordList.forEach(function(keyword2){const pair=keyword2.split("|");compiledKeywords[pair[0]]=[scopeName2,scoreForKeyword(pair[0],pair[1])]})}}function scoreForKeyword(keyword2,providedScore){return providedScore?Number(
providedScore):commonKeyword(keyword2)?0:1}function commonKeyword(keyword2){return COMMON_KEYWORDS.includes(keyword2.toLowerCase())}const seenDeprecations={},error2=message=>{console.error(message)},warn2=(message,...args)=>{console.log(`WARN: ${message}`,...args)},deprecated2=(version3,message)=>{seenDeprecations[`${version3}/${message}`]||(console.log(`Deprecated as of ${version3}. ${message}`),seenDeprecations[`${version3}/${message}`]=!0)},MultiClassError=new Error;function remapScopeNames(mode,regexes,{
key:key2}){let offset2=0;const scopeNames=mode[key2],emit={},positions={};for(let i=1;i<=regexes.length;i++)positions[i+offset2]=scopeNames[i],emit[i+offset2]=!0,offset2+=countMatchGroups(regexes[i-1]);mode[key2]=positions,mode[key2]._emit=emit,mode[key2]._multi=!0}function beginMultiClass(mode){if(Array.isArray(mode.begin)){if(mode.skip||mode.excludeBegin||mode.returnBegin)throw error2("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),MultiClassError;if(typeof mode.beginScope!=
"object"||mode.beginScope===null)throw error2("beginScope must be object"),MultiClassError;remapScopeNames(mode,mode.begin,{key:"beginScope"}),mode.begin=_rewriteBackreferences(mode.begin,{joinWith:""})}}function endMultiClass(mode){if(Array.isArray(mode.end)){if(mode.skip||mode.excludeEnd||mode.returnEnd)throw error2("skip, excludeEnd, returnEnd not compatible with endScope: {}"),MultiClassError;if(typeof mode.endScope!="object"||mode.endScope===null)throw error2("endScope must be object"),MultiClassError;
remapScopeNames(mode,mode.end,{key:"endScope"}),mode.end=_rewriteBackreferences(mode.end,{joinWith:""})}}function scopeSugar(mode){mode.scope&&typeof mode.scope=="object"&&mode.scope!==null&&(mode.beginScope=mode.scope,delete mode.scope)}function MultiClass(mode){scopeSugar(mode),typeof mode.beginScope=="string"&&(mode.beginScope={_wrap:mode.beginScope}),typeof mode.endScope=="string"&&(mode.endScope={_wrap:mode.endScope}),beginMultiClass(mode),endMultiClass(mode)}function compileLanguage(language2){
function langRe(value,global2){return new RegExp(source2(value),"m"+(language2.case_insensitive?"i":"")+(language2.unicodeRegex?"u":"")+(global2?"g":""))}class MultiRegex{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(re2,opts){opts.position=this.position++,this.matchIndexes[this.matchAt]=opts,this.regexes.push([opts,re2]),this.matchAt+=countMatchGroups(re2)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);const terminators=this.regexes.map(el=>el[1]);
this.matcherRe=langRe(_rewriteBackreferences(terminators,{joinWith:"|"}),!0),this.lastIndex=0}exec(s2){this.matcherRe.lastIndex=this.lastIndex;const match=this.matcherRe.exec(s2);if(!match)return null;const i=match.findIndex((el,i2)=>i2>0&&el!==void 0),matchData=this.matchIndexes[i];return match.splice(0,i),Object.assign(match,matchData)}}class ResumableMultiRegex{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(index2){if(this.multiRegexes[index2])
return this.multiRegexes[index2];const matcher=new MultiRegex;return this.rules.slice(index2).forEach(([re2,opts])=>matcher.addRule(re2,opts)),matcher.compile(),this.multiRegexes[index2]=matcher,matcher}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(re2,opts){this.rules.push([re2,opts]),opts.type==="begin"&&this.count++}exec(s2){const m=this.getMatcher(this.regexIndex);m.lastIndex=this.lastIndex;let result=m.exec(s2);if(this.resumingScanAtSamePosition()&&
!(result&&result.index===this.lastIndex)){const m2=this.getMatcher(0);m2.lastIndex=this.lastIndex+1,result=m2.exec(s2)}return result&&(this.regexIndex+=result.position+1,this.regexIndex===this.count&&this.considerAll()),result}}function buildModeRegex(mode){const mm=new ResumableMultiRegex;return mode.contains.forEach(term=>mm.addRule(term.begin,{rule:term,type:"begin"})),mode.terminatorEnd&&mm.addRule(mode.terminatorEnd,{type:"end"}),mode.illegal&&mm.addRule(mode.illegal,{type:"illegal"}),mm}function compileMode(mode,parent){
const cmode=mode;if(mode.isCompiled)return cmode;[scopeClassName,compileMatch,MultiClass,beforeMatchExt].forEach(ext=>ext(mode,parent)),language2.compilerExtensions.forEach(ext=>ext(mode,parent)),mode.__beforeBegin=null,[beginKeywords,compileIllegal,compileRelevance].forEach(ext=>ext(mode,parent)),mode.isCompiled=!0;let keywordPattern=null;return typeof mode.keywords=="object"&&mode.keywords.$pattern&&(mode.keywords=Object.assign({},mode.keywords),keywordPattern=mode.keywords.$pattern,delete mode.
keywords.$pattern),keywordPattern=keywordPattern||/\w+/,mode.keywords&&(mode.keywords=compileKeywords(mode.keywords,language2.case_insensitive)),cmode.keywordPatternRe=langRe(keywordPattern,!0),parent&&(mode.begin||(mode.begin=/\B|\b/),cmode.beginRe=langRe(cmode.begin),!mode.end&&!mode.endsWithParent&&(mode.end=/\B|\b/),mode.end&&(cmode.endRe=langRe(cmode.end)),cmode.terminatorEnd=source2(cmode.end)||"",mode.endsWithParent&&parent.terminatorEnd&&(cmode.terminatorEnd+=(mode.end?"|":"")+parent.terminatorEnd)),
mode.illegal&&(cmode.illegalRe=langRe(mode.illegal)),mode.contains||(mode.contains=[]),mode.contains=[].concat(...mode.contains.map(function(c2){return expandOrCloneMode(c2==="self"?mode:c2)})),mode.contains.forEach(function(c2){compileMode(c2,cmode)}),mode.starts&&compileMode(mode.starts,parent),cmode.matcher=buildModeRegex(cmode),cmode}if(language2.compilerExtensions||(language2.compilerExtensions=[]),language2.contains&&language2.contains.includes("self"))throw new Error("ERR: contains `self`\
is not supported at the top-level of a language. See documentation.");return language2.classNameAliases=inherit$1(language2.classNameAliases||{}),compileMode(language2)}function dependencyOnParent(mode){return mode?mode.endsWithParent||dependencyOnParent(mode.starts):!1}function expandOrCloneMode(mode){return mode.variants&&!mode.cachedVariants&&(mode.cachedVariants=mode.variants.map(function(variant){return inherit$1(mode,{variants:null},variant)})),mode.cachedVariants?mode.cachedVariants:dependencyOnParent(
mode)?inherit$1(mode,{starts:mode.starts?inherit$1(mode.starts):null}):Object.isFrozen(mode)?inherit$1(mode):mode}var version2="11.11.1";class HTMLInjectionError extends Error{constructor(reason,html2){super(reason),this.name="HTMLInjectionError",this.html=html2}}const escape2=escapeHTML,inherit=inherit$1,NO_MATCH=Symbol("nomatch"),MAX_KEYWORD_HITS=7,HLJS=function(hljs){const languages=Object.create(null),aliases=Object.create(null),plugins=[];let SAFE_MODE=!0;const LANGUAGE_NOT_FOUND="Could not\
find the language '{}', did you forget to load/include a language module?",PLAINTEXT_LANGUAGE={disableAutodetect:!0,name:"Plain text",contains:[]};let options={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:TokenTreeEmitter};function shouldNotHighlight(languageName){return options.noHighlightRe.test(languageName)}function blockLanguage(block2){let classes=block2.
className+" ";classes+=block2.parentNode?block2.parentNode.className:"";const match=options.languageDetectRe.exec(classes);if(match){const language2=getLanguage(match[1]);return language2||(warn2(LANGUAGE_NOT_FOUND.replace("{}",match[1])),warn2("Falling back to no-highlight mode for this block.",block2)),language2?match[1]:"no-highlight"}return classes.split(/\s+/).find(_class=>shouldNotHighlight(_class)||getLanguage(_class))}function highlight2(codeOrLanguageName,optionsOrCode,ignoreIllegals){let code2="",
languageName="";typeof optionsOrCode=="object"?(code2=codeOrLanguageName,ignoreIllegals=optionsOrCode.ignoreIllegals,languageName=optionsOrCode.language):(deprecated2("10.7.0","highlight(lang, code, ...args) has been deprecated."),deprecated2("10.7.0",`Please use highlight(code, options) instead.
https://github.com/highlightjs/highlight.js/issues/2277`),languageName=codeOrLanguageName,code2=optionsOrCode),ignoreIllegals===void 0&&(ignoreIllegals=!0);const context={code:code2,language:languageName};fire("before:highlight",context);const result=context.result?context.result:_highlight(context.language,context.code,ignoreIllegals);return result.code=context.code,fire("after:highlight",result),result}function _highlight(languageName,codeToHighlight,ignoreIllegals,continuation){const keywordHits=Object.
create(null);function keywordData(mode,matchText){return mode.keywords[matchText]}function processKeywords(){if(!top.keywords){emitter.addText(modeBuffer);return}let lastIndex=0;top.keywordPatternRe.lastIndex=0;let match=top.keywordPatternRe.exec(modeBuffer),buf="";for(;match;){buf+=modeBuffer.substring(lastIndex,match.index);const word=language2.case_insensitive?match[0].toLowerCase():match[0],data=keywordData(top,word);if(data){const[kind,keywordRelevance]=data;if(emitter.addText(buf),buf="",keywordHits[word]=
(keywordHits[word]||0)+1,keywordHits[word]<=MAX_KEYWORD_HITS&&(relevance+=keywordRelevance),kind.startsWith("_"))buf+=match[0];else{const cssClass=language2.classNameAliases[kind]||kind;emitKeyword(match[0],cssClass)}}else buf+=match[0];lastIndex=top.keywordPatternRe.lastIndex,match=top.keywordPatternRe.exec(modeBuffer)}buf+=modeBuffer.substring(lastIndex),emitter.addText(buf)}function processSubLanguage(){if(modeBuffer==="")return;let result2=null;if(typeof top.subLanguage=="string"){if(!languages[top.
@ -3738,69 +3739,72 @@ updateMessage(message.id,{children:[]})}migratedCount++}return migratedCount}asy
conversations`):console.log("[Migration] No legacy messages found, marking as done"),markMigrationDone()}catch(error2){console.error("[Migration] Failed to migrate legacy messages:",error2),markMigrationDone()}}}class TTLCache{cache=new Map;ttlMs;maxEntries;onEvict;constructor(options={}){this.ttlMs=options.ttlMs??DEFAULT_CACHE_TTL_MS,this.maxEntries=options.maxEntries??DEFAULT_CACHE_MAX_ENTRIES,this.onEvict=options.onEvict}get(key2){const entry=this.cache.get(key2);return entry?Date.now()>entry.
expiresAt?(this.delete(key2),null):(entry.lastAccessed=Date.now(),entry.value):null}set(key2,value,customTtlMs){this.cache.size>=this.maxEntries&&!this.cache.has(key2)&&this.evictOldest();const ttl=customTtlMs??this.ttlMs,now2=Date.now();this.cache.set(key2,{value,expiresAt:now2+ttl,lastAccessed:now2})}has(key2){const entry=this.cache.get(key2);return entry?Date.now()>entry.expiresAt?(this.delete(key2),!1):!0:!1}delete(key2){const entry=this.cache.get(key2);return entry&&this.onEvict&&this.onEvict(
key2,entry.value),this.cache.delete(key2)}clear(){if(this.onEvict)for(const[key2,entry]of this.cache)this.onEvict(key2,entry.value);this.cache.clear()}get size(){return this.cache.size}prune(){const now2=Date.now();let pruned=0;for(const[key2,entry]of this.cache)now2>entry.expiresAt&&(this.delete(key2),pruned++);return pruned}keys(){const now2=Date.now(),validKeys=[];for(const[key2,entry]of this.cache)now2<=entry.expiresAt&&validKeys.push(key2);return validKeys}evictOldest(){let oldestKey=null,oldestTime=1/0;
for(const[key2,entry]of this.cache)entry.lastAccessed<oldestTime&&(oldestTime=entry.lastAccessed,oldestKey=key2);oldestKey!==null&&this.delete(oldestKey)}touch(key2){const entry=this.cache.get(key2);if(!entry)return!1;const now2=Date.now();return now2>entry.expiresAt?(this.delete(key2),!1):(entry.expiresAt=now2+this.ttlMs,entry.lastAccessed=now2,!0)}}function throwIfAborted(signal){if(signal?.aborted)throw new DOMException("Operation was aborted","AbortError")}function isAbortError(error2){return error2 instanceof
DOMException&&error2.name==="AbortError"||error2 instanceof Error&&error2.name==="AbortError"}function uuid$1(){return globalThis.crypto?.randomUUID?.()??Math.random().toString(36).substring(2)}function ActionIconCopyToClipboard($$anchor,$$props){push$1($$props,!0);let ariaLabel=prop($$props,"ariaLabel",3,"Copy to clipboard"),canCopy=prop($$props,"canCopy",3,!0);{let $0=user_derived(()=>canCopy()?"pointer":"not-allowed");Copy($$anchor,{get class(){return`h-3 w-3 flex-shrink-0 cursor-${get$4($0)??
""}`},get"aria-label"(){return ariaLabel()},onclick:()=>canCopy()&&copyToClipboard($$props.text)})}pop()}function ActionIconRemove($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),iconSize=prop($$props,"iconSize",3,3);Button($$anchor,{type:"button",variant:"ghost",size:"icon-sm",get class(){return`bg-white/20 p-0 hover:bg-white/30 ${className()??""}`},onclick:e=>{e.stopPropagation(),$$props.onRemove?.($$props.id)},"aria-label":"Remove file",children:($$anchor2,$$slotProps)=>{
X($$anchor2,{get class(){return`h-${iconSize()??""} w-${iconSize()??""}`}})},$$slots:{default:!0}}),pop()}var root_6$z=from_html("<p> </p>"),root_2$15=from_html("<!> <!>",1);function BadgeChatStatistic($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,"");function handleClick(){copyToClipboard(String($$props.value))}var fragment=comment$2(),node2=first_child(fragment);{var consequent=$$anchor2=>{var fragment_1=comment$2(),node_1=first_child(fragment_1);component(node_1,()=>Root$5,
($$anchor3,Tooltip_Root)=>{Tooltip_Root($$anchor3,{children:($$anchor4,$$slotProps)=>{var fragment_2=root_2$15(),node_2=first_child(fragment_2);component(node_2,()=>Tooltip_trigger,($$anchor5,Tooltip_Trigger)=>{Tooltip_Trigger($$anchor5,{children:($$anchor6,$$slotProps2)=>{BadgeInfo($$anchor6,{get class(){return className()},onclick:handleClick,icon:$$anchor7=>{var fragment_4=comment$2(),node_3=first_child(fragment_4);component(node_3,()=>$$props.icon,($$anchor8,Icon_1)=>{Icon_1($$anchor8,{class:"\
h-3 w-3"})}),append($$anchor7,fragment_4)},children:($$anchor7,$$slotProps3)=>{next$1();var text2=text$8();template_effect(()=>set_text(text2,$$props.value)),append($$anchor7,text2)},$$slots:{icon:!0,default:!0}})},$$slots:{default:!0}})});var node_4=sibling(node_2,2);component(node_4,()=>Tooltip_content,($$anchor5,Tooltip_Content)=>{Tooltip_Content($$anchor5,{children:($$anchor6,$$slotProps2)=>{var p2=root_6$z(),text_1=child(p2,!0);reset(p2),template_effect(()=>set_text(text_1,$$props.tooltipLabel)),
append($$anchor6,p2)},$$slots:{default:!0}})}),append($$anchor4,fragment_2)},$$slots:{default:!0}})}),append($$anchor2,fragment_1)},alternate=$$anchor2=>{BadgeInfo($$anchor2,{get class(){return className()},onclick:handleClick,icon:$$anchor3=>{var fragment_7=comment$2(),node_5=first_child(fragment_7);component(node_5,()=>$$props.icon,($$anchor4,Icon_2)=>{Icon_2($$anchor4,{class:"h-3 w-3"})}),append($$anchor3,fragment_7)},children:($$anchor3,$$slotProps)=>{next$1();var text_2=text$8();template_effect(
()=>set_text(text_2,$$props.value)),append($$anchor3,text_2)},$$slots:{icon:!0,default:!0}})};if_block(node2,$$render=>{$$props.tooltipLabel?$$render(consequent):$$render(alternate,!1)})}append($$anchor,fragment),pop()}var root$1w=from_html("<button><!> <!></button>");function BadgeInfo($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,"");var button=root$1w();button.__click=function(...$$args){$$props.onclick?.apply(this,$$args)};var node2=child(button);{var consequent=$$anchor2=>{
var fragment=comment$2(),node_1=first_child(fragment);snippet(node_1,()=>$$props.icon),append($$anchor2,fragment)};if_block(node2,$$render=>{$$props.icon&&$$render(consequent)})}var node_2=sibling(node2,2);snippet(node_2,()=>$$props.children),reset(button),template_effect($0=>set_class(button,1,$0),[()=>clsx(cn$1("inline-flex cursor-pointer items-center gap-1 rounded-sm bg-muted-foreground/15 px-1.5 py-0.75",className()))]),append($$anchor,button),pop()}delegate(["click"]);var root_1$$=from_html(
"<span><!> </span>");function BadgeModality($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,"");const displayableModalities=user_derived(()=>$$props.modalities.filter(m=>m===ModelModality.VISION||m===ModelModality.AUDIO));var fragment=comment$2(),node2=first_child(fragment);each(node2,17,()=>get$4(displayableModalities),index$2,($$anchor2,modality)=>{const IconComponent=user_derived(()=>MODALITY_ICONS[get$4(modality)]),label=user_derived(()=>MODALITY_LABELS[get$4(modality)]);
var span=root_1$$(),node_1=child(span);{var consequent=$$anchor3=>{var fragment_1=comment$2(),node_2=first_child(fragment_1);component(node_2,()=>get$4(IconComponent),($$anchor4,IconComponent_1)=>{IconComponent_1($$anchor4,{class:"h-3 w-3"})}),append($$anchor3,fragment_1)};if_block(node_1,$$render=>{get$4(IconComponent)&&$$render(consequent)})}var text2=sibling(node_1);reset(span),template_effect($0=>{set_class(span,1,$0),set_text(text2,` ${get$4(label)??""}`)},[()=>clsx(cn$1("inline-flex items-\
center gap-1 rounded-md bg-muted px-2 py-1 text-xs font-medium",className()))]),append($$anchor2,span)}),append($$anchor,fragment),pop()}var root_12$a=from_html('<div class="mt-2 -mr-2 flex justify-end px-4"><!></div>'),root_2$14=from_html("<!> <!>",1),root_14$9=from_html('<div class="flex flex-wrap items-start justify-end gap-3"></div>'),root_1$_=from_html("<div><!></div>"),root$1v=from_html("<!> <!> <!> <!>",1);function ChatAttachmentsList($$anchor,$$props){push$1($$props,!0);let className=prop(
$$props,"class",3,""),style2=prop($$props,"style",3,""),attachments=prop($$props,"attachments",19,()=>[]),readonly2=prop($$props,"readonly",3,!1),uploadedFiles=prop($$props,"uploadedFiles",27,()=>proxy([])),imageClass=prop($$props,"imageClass",3,""),imageHeight=prop($$props,"imageHeight",3,"h-24"),imageWidth=prop($$props,"imageWidth",3,"w-auto"),limitToSingleRow=prop($$props,"limitToSingleRow",3,!1),displayItems=user_derived(()=>getAttachmentDisplayItems({uploadedFiles:uploadedFiles(),attachments:attachments()})),
carouselRef=state$1(void 0),isScrollable=state$1(!1),previewDialogOpen=state$1(!1),previewItem=state$1(null),mcpResourcePreviewOpen=state$1(!1),mcpResourcePreviewExtra=state$1(null),showViewAll=user_derived(()=>limitToSingleRow()&&get$4(displayItems).length>0&&get$4(isScrollable)),viewAllDialogOpen=state$1(!1);function openPreview(item,event2){event2?.stopPropagation(),event2?.preventDefault(),set$1(previewItem,{uploadedFile:item.uploadedFile,attachment:item.attachment,preview:item.preview,name:item.
name,size:item.size,textContent:item.textContent},!0),set$1(previewDialogOpen,!0)}function openMcpResourcePreview(extra){set$1(mcpResourcePreviewExtra,extra,!0),set$1(mcpResourcePreviewOpen,!0)}function toMcpResourceAttachment(extra,id2){return{id:id2,resource:{uri:extra.uri,name:extra.name,title:extra.name,serverName:extra.serverName}}}user_effect(()=>{get$4(carouselRef)&&get$4(displayItems).length&&get$4(carouselRef).resetScroll()});var fragment=root$1v(),node2=first_child(fragment);{var consequent_10=$$anchor2=>{
var div=root_1$_(),node_1=child(div);{var consequent_5=$$anchor3=>{var fragment_1=root_2$14(),node_2=first_child(fragment_1);bind_this(HorizontalScrollCarousel(node_2,{onScrollableChange:scrollable=>set$1(isScrollable,scrollable,!0),children:($$anchor4,$$slotProps)=>{var fragment_2=comment$2(),node_3=first_child(fragment_2);each(node_3,17,()=>get$4(displayItems),item=>item.id,($$anchor5,item)=>{var fragment_3=comment$2(),node_4=first_child(fragment_3);{var consequent_1=$$anchor6=>{const mcpPrompt=user_derived(
()=>get$4(item).attachment?.type===AttachmentType.MCP_PROMPT?get$4(item).attachment:get$4(item).uploadedFile?.mcpPrompt?{type:AttachmentType.MCP_PROMPT,name:get$4(item).name,serverName:get$4(item).uploadedFile.mcpPrompt.serverName,promptName:get$4(item).uploadedFile.mcpPrompt.promptName,content:get$4(item).textContent??"",arguments:get$4(item).uploadedFile.mcpPrompt.arguments}:null);var fragment_4=comment$2(),node_5=first_child(fragment_4);{var consequent=$$anchor7=>{{let $0=user_derived(()=>limitToSingleRow()?
"first:ml-4 last:mr-4":""),$1=user_derived(()=>$$props.onFileRemove?()=>$$props.onFileRemove(get$4(item).id):void 0);ChatAttachmentMcpPrompt($$anchor7,{get class(){return`max-w-[300px] min-w-[200px] flex-shrink-0 ${get$4($0)??""}`},get prompt(){return get$4(mcpPrompt)},get readonly(){return readonly2()},get isLoading(){return get$4(item).isLoading},get loadError(){return get$4(item).loadError},get onRemove(){return get$4($1)}})}};if_block(node_5,$$render=>{get$4(mcpPrompt)&&$$render(consequent)})}
append($$anchor6,fragment_4)},alternate_2=$$anchor6=>{var fragment_6=comment$2(),node_6=first_child(fragment_6);{var consequent_2=$$anchor7=>{const mcpResource=user_derived(()=>get$4(item).attachment);{let $0=user_derived(()=>limitToSingleRow()?"first:ml-4 last:mr-4":""),$1=user_derived(()=>toMcpResourceAttachment(get$4(mcpResource),get$4(item).id));ChatAttachmentMcpResource($$anchor7,{get class(){return`flex-shrink-0 ${get$4($0)??""}`},get attachment(){return get$4($1)},onClick:()=>openMcpResourcePreview(
get$4(mcpResource))})}},alternate_1=$$anchor7=>{var fragment_8=comment$2(),node_7=first_child(fragment_8);{var consequent_3=$$anchor8=>{{let $0=user_derived(()=>limitToSingleRow()?"first:ml-4 last:mr-4":"");ChatAttachmentThumbnailImage($$anchor8,{get class(){return`flex-shrink-0 cursor-pointer ${get$4($0)??""}`},get id(){return get$4(item).id},get name(){return get$4(item).name},get preview(){return get$4(item).preview},get readonly(){return readonly2()},get onRemove(){return $$props.onFileRemove},
get height(){return imageHeight()},get width(){return imageWidth()},get imageClass(){return imageClass()},onClick:event2=>openPreview(get$4(item),event2)})}},alternate=$$anchor8=>{{let $0=user_derived(()=>limitToSingleRow()?"first:ml-4 last:mr-4":"");ChatAttachmentThumbnailFile($$anchor8,{get class(){return`flex-shrink-0 cursor-pointer ${get$4($0)??""}`},get id(){return get$4(item).id},get name(){return get$4(item).name},get size(){return get$4(item).size},get readonly(){return readonly2()},get onRemove(){
return $$props.onFileRemove},get textContent(){return get$4(item).textContent},get attachment(){return get$4(item).attachment},get uploadedFile(){return get$4(item).uploadedFile},onClick:event2=>openPreview(get$4(item),event2)})}};if_block(node_7,$$render=>{get$4(item).isImage&&get$4(item).preview?$$render(consequent_3):$$render(alternate,!1)},!0)}append($$anchor7,fragment_8)};if_block(node_6,$$render=>{get$4(item).isMcpResource&&get$4(item).attachment?.type===AttachmentType.MCP_RESOURCE?$$render(
consequent_2):$$render(alternate_1,!1)},!0)}append($$anchor6,fragment_6)};if_block(node_4,$$render=>{get$4(item).isMcpPrompt?$$render(consequent_1):$$render(alternate_2,!1)})}append($$anchor5,fragment_3)}),append($$anchor4,fragment_2)},$$slots:{default:!0}}),$$value=>set$1(carouselRef,$$value,!0),()=>get$4(carouselRef));var node_8=sibling(node_2,2);{var consequent_4=$$anchor4=>{var div_1=root_12$a(),node_9=child(div_1);Button(node_9,{type:"button",variant:"ghost",size:"sm",class:"h-6 text-xs tex\
t-muted-foreground hover:text-foreground",onclick:()=>set$1(viewAllDialogOpen,!0),children:($$anchor5,$$slotProps)=>{next$1();var text2=text$8();template_effect(()=>set_text(text2,`View all (${get$4(displayItems).length??""})`)),append($$anchor5,text2)},$$slots:{default:!0}}),reset(div_1),append($$anchor4,div_1)};if_block(node_8,$$render=>{get$4(showViewAll)&&$$render(consequent_4)})}append($$anchor3,fragment_1)},alternate_6=$$anchor3=>{var div_2=root_14$9();each(div_2,21,()=>get$4(displayItems),
item=>item.id,($$anchor4,item)=>{var fragment_12=comment$2(),node_10=first_child(fragment_12);{var consequent_7=$$anchor5=>{const mcpPrompt=user_derived(()=>get$4(item).attachment?.type===AttachmentType.MCP_PROMPT?get$4(item).attachment:get$4(item).uploadedFile?.mcpPrompt?{type:AttachmentType.MCP_PROMPT,name:get$4(item).name,serverName:get$4(item).uploadedFile.mcpPrompt.serverName,promptName:get$4(item).uploadedFile.mcpPrompt.promptName,content:get$4(item).textContent??"",arguments:get$4(item).uploadedFile.
mcpPrompt.arguments}:null);var fragment_13=comment$2(),node_11=first_child(fragment_13);{var consequent_6=$$anchor6=>{{let $0=user_derived(()=>$$props.onFileRemove?()=>$$props.onFileRemove(get$4(item).id):void 0);ChatAttachmentMcpPrompt($$anchor6,{class:"max-w-[300px] min-w-[200px]",get prompt(){return get$4(mcpPrompt)},get readonly(){return readonly2()},get isLoading(){return get$4(item).isLoading},get loadError(){return get$4(item).loadError},get onRemove(){return get$4($0)}})}};if_block(node_11,
$$render=>{get$4(mcpPrompt)&&$$render(consequent_6)})}append($$anchor5,fragment_13)},alternate_5=$$anchor5=>{var fragment_15=comment$2(),node_12=first_child(fragment_15);{var consequent_8=$$anchor6=>{const mcpResource=user_derived(()=>get$4(item).attachment);{let $0=user_derived(()=>toMcpResourceAttachment(get$4(mcpResource),get$4(item).id));ChatAttachmentMcpResource($$anchor6,{get attachment(){return get$4($0)},onClick:()=>openMcpResourcePreview(get$4(mcpResource))})}},alternate_4=$$anchor6=>{var fragment_17=comment$2(),
node_13=first_child(fragment_17);{var consequent_9=$$anchor7=>{ChatAttachmentThumbnailImage($$anchor7,{class:"cursor-pointer",get id(){return get$4(item).id},get name(){return get$4(item).name},get preview(){return get$4(item).preview},get readonly(){return readonly2()},get onRemove(){return $$props.onFileRemove},get height(){return imageHeight()},get width(){return imageWidth()},get imageClass(){return imageClass()},onClick:event2=>openPreview(get$4(item),event2)})},alternate_3=$$anchor7=>{ChatAttachmentThumbnailFile(
$$anchor7,{class:"cursor-pointer",get id(){return get$4(item).id},get name(){return get$4(item).name},get size(){return get$4(item).size},get readonly(){return readonly2()},get onRemove(){return $$props.onFileRemove},get textContent(){return get$4(item).textContent},get attachment(){return get$4(item).attachment},get uploadedFile(){return get$4(item).uploadedFile},onClick:event2=>openPreview(get$4(item),event2)})};if_block(node_13,$$render=>{get$4(item).isImage&&get$4(item).preview?$$render(consequent_9):
$$render(alternate_3,!1)},!0)}append($$anchor6,fragment_17)};if_block(node_12,$$render=>{get$4(item).isMcpResource&&get$4(item).attachment?.type===AttachmentType.MCP_RESOURCE?$$render(consequent_8):$$render(alternate_4,!1)},!0)}append($$anchor5,fragment_15)};if_block(node_10,$$render=>{get$4(item).isMcpPrompt?$$render(consequent_7):$$render(alternate_5,!1)})}append($$anchor4,fragment_12)}),reset(div_2),append($$anchor3,div_2)};if_block(node_1,$$render=>{limitToSingleRow()?$$render(consequent_5):
$$render(alternate_6,!1)})}reset(div),template_effect(()=>{set_class(div,1,clsx(className())),set_style(div,style2())}),append($$anchor2,div)};if_block(node2,$$render=>{get$4(displayItems).length>0&&$$render(consequent_10)})}var node_14=sibling(node2,2);{var consequent_11=$$anchor2=>{DialogChatAttachmentPreview($$anchor2,{get uploadedFile(){return get$4(previewItem).uploadedFile},get attachment(){return get$4(previewItem).attachment},get preview(){return get$4(previewItem).preview},get name(){return get$4(
previewItem).name},get size(){return get$4(previewItem).size},get textContent(){return get$4(previewItem).textContent},get activeModelId(){return $$props.activeModelId},get open(){return get$4(previewDialogOpen)},set open($$value){set$1(previewDialogOpen,$$value,!0)}})};if_block(node_14,$$render=>{get$4(previewItem)&&$$render(consequent_11)})}var node_15=sibling(node_14,2);DialogChatAttachmentsViewAll(node_15,{get uploadedFiles(){return uploadedFiles()},get attachments(){return attachments()},get readonly(){
return readonly2()},get onFileRemove(){return $$props.onFileRemove},imageHeight:"h-64",get imageClass(){return imageClass()},get activeModelId(){return $$props.activeModelId},get open(){return get$4(viewAllDialogOpen)},set open($$value){set$1(viewAllDialogOpen,$$value,!0)}});var node_16=sibling(node_15,2);{var consequent_12=$$anchor2=>{DialogMcpResourcePreview($$anchor2,{get extra(){return get$4(mcpResourcePreviewExtra)},get open(){return get$4(mcpResourcePreviewOpen)},set open($$value){set$1(mcpResourcePreviewOpen,
$$value,!0)}})};if_block(node_16,$$render=>{get$4(mcpResourcePreviewExtra)&&$$render(consequent_12)})}append($$anchor,fragment),pop()}var root_1$Z=from_html('<div class="absolute top-10 right-2 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100"><!></div>'),root$1u=from_html("<div><!> <!></div>");function ChatAttachmentMcpPrompt($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),readonly2=prop($$props,"readonly",3,!1),isLoading2=prop(
$$props,"isLoading",3,!1);var div=root$1u(),node2=child(div);ChatMessageMcpPromptContent(node2,{get prompt(){return $$props.prompt},get variant(){return McpPromptVariant.ATTACHMENT},get isLoading(){return isLoading2()},get loadError(){return $$props.loadError}});var node_1=sibling(node2,2);{var consequent=$$anchor2=>{var div_1=root_1$Z(),node_2=child(div_1);ActionIconRemove(node_2,{get id(){return $$props.prompt.name},onRemove:()=>$$props.onRemove?.()}),reset(div_1),append($$anchor2,div_1)};if_block(
node_1,$$render=>{!readonly2()&&$$props.onRemove&&$$render(consequent)})}reset(div),template_effect(()=>set_class(div,1,`group relative ${className()??""}`)),append($$anchor,div),pop()}const NEVER=Object.freeze({status:"aborted"});function $constructor(name,initializer2,params){function init2(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer2(inst,def);const proto=_.
prototype,keys2=Object.keys(proto);for(let i=0;i<keys2.length;i++){const k=keys2[i];k in inst||(inst[k]=proto[k].bind(inst))}}const Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a2;const inst=params?.Parent?new Definition:this;init2(inst,def),(_a2=inst._zod).deferred??(_a2.deferred=[]);for(const fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_,"init",{value:init2}),Object.defineProperty(
_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),_}class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $ZodEncodeError extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}}const globalConfig={};function config(newConfig){return globalConfig}
function getEnumValues(entries){const numericValues=Object.values(entries).filter(v=>typeof v=="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function jsonStringifyReplacer(_,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return{get value(){{const value=getter();return Object.defineProperty(this,"value",{value}),value}}}}function nullish(input){return input==null}function cleanRegex(source2){const start2=source2.
startsWith("^")?1:0,end=source2.endsWith("$")?source2.length-1:source2.length;return source2.slice(start2,end)}function floatSafeRemainder(val,step){const valDecCount=(val.toString().split(".")[1]||"").length,stepString=step.toString();let stepDecCount=(stepString.split(".")[1]||"").length;if(stepDecCount===0&&/\d?e-\d?/.test(stepString)){const match=stepString.match(/\d?e-(\d?)/);match?.[1]&&(stepDecCount=Number.parseInt(match[1]))}const decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,
valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}const EVALUATING=Symbol("evaluating");function defineLazy(object2,key2,getter){let value;Object.defineProperty(object2,key2,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v){Object.defineProperty(object2,key2,{value:v})},configurable:!0})}function assignProp(target2,prop2,value){Object.defineProperty(
target2,prop2,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){const mergedDescriptors={};for(const def of defs){const descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const captureStackTrace="capt\
ureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};function isObject$1(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}const allowsEval=cached(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const F=Function;return new F(""),!0}catch{return!1}});function isPlainObject$2(o){if(isObject$1(o)===!1)return!1;const ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;const prot=ctor.prototype;return!(isObject$1(prot)===
!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject$2(o)?{...o}:Array.isArray(o)?[...o]:o}const propertyKeyTypes=new Set(["string","number","symbol"]);function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){const cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){const params=_params;if(!params)return{};
if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function optionalKeys(shape){return Object.keys(shape).filter(k=>shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional")}const NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.
MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pick(schema,mask){const currDef=schema._zod.def,def=mergeDefs(schema._zod.def,{get shape(){const newShape={};for(const key2 in mask){if(!(key2 in currDef.shape))throw new Error(`Unrecognized key: "${key2}"`);mask[key2]&&(newShape[key2]=currDef.shape[key2])}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(
schema,def)}function omit(schema,mask){const currDef=schema._zod.def,def=mergeDefs(schema._zod.def,{get shape(){const newShape={...schema._zod.def.shape};for(const key2 in mask){if(!(key2 in currDef.shape))throw new Error(`Unrecognized key: "${key2}"`);mask[key2]&&delete newShape[key2]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function extend$2(schema,shape){if(!isPlainObject$2(shape))throw new Error("Invalid input to extend: expected a plain object");
const checks2=schema._zod.def.checks;if(checks2&&checks2.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const def=mergeDefs(schema._zod.def,{get shape(){const _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape},checks:[]});return clone(schema,def)}function safeExtend(schema,shape){if(!isPlainObject$2(shape))throw new Error("Invalid input to safeExtend: expected a plain object");const def={...schema.
_zod.def,get shape(){const _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape},checks:schema._zod.def.checks};return clone(schema,def)}function merge$1(a,b){const def=mergeDefs(a._zod.def,{get shape(){const _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:[]});return clone(a,def)}function partial(Class,schema,mask){const def=mergeDefs(schema._zod.def,{get shape(){
const oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(const key2 in mask){if(!(key2 in oldShape))throw new Error(`Unrecognized key: "${key2}"`);mask[key2]&&(shape[key2]=Class?new Class({type:"optional",innerType:oldShape[key2]}):oldShape[key2])}else for(const key2 in oldShape)shape[key2]=Class?new Class({type:"optional",innerType:oldShape[key2]}):oldShape[key2];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema,def)}function required$4(Class,schema,mask){
const def=mergeDefs(schema._zod.def,{get shape(){const oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(const key2 in mask){if(!(key2 in shape))throw new Error(`Unrecognized key: "${key2}"`);mask[key2]&&(shape[key2]=new Class({type:"nonoptional",innerType:oldShape[key2]}))}else for(const key2 in oldShape)shape[key2]=new Class({type:"nonoptional",innerType:oldShape[key2]});return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema,def)}function aborted(x,startIndex=0){
if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function prefixIssues(path2,issues){return issues.map(iss=>{var _a2;return(_a2=iss).path??(_a2.path=[]),iss.path.unshift(path2),iss})}function unwrapMessage(message){return typeof message=="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){const full={...iss,path:iss.path??[]};if(!iss.message){const message=unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(
ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input";full.message=message}return delete full.inst,delete full.continue,ctx?.reportInput||delete full.input,full}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function issue(...args){const[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}const initializer$1=(inst,def)=>{
inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer$1),$ZodRealError=$constructor("$ZodError",initializer$1,{Parent:Error});function flattenError$1(error2,mapper=issue2=>issue2.message){const fieldErrors={},formErrors=[];
for(const sub2 of error2.issues)sub2.path.length>0?(fieldErrors[sub2.path[0]]=fieldErrors[sub2.path[0]]||[],fieldErrors[sub2.path[0]].push(mapper(sub2))):formErrors.push(mapper(sub2));return{formErrors,fieldErrors}}function formatError(error2,mapper=issue2=>issue2.message){const fieldErrors={_errors:[]},processError=error3=>{for(const issue2 of error3.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues}));else if(issue2.code==="invalid_key")
processError({issues:issue2.issues});else if(issue2.code==="invalid_element")processError({issues:issue2.issues});else if(issue2.path.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;for(;i<issue2.path.length;){const el=issue2.path[i];i===issue2.path.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}};return processError(error2),fieldErrors}const _parse=_Err=>(schema,value,_ctx,_params)=>{
const ctx=_ctx?Object.assign(_ctx,{async:!1}):{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){const e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},_parseAsync=_Err=>async(schema,value,_ctx,params)=>{const ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0};let result=schema._zod.run({value,issues:[]},ctx);if(result instanceof
Promise&&(result=await result),result.issues.length){const e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee),e}return result.value},_safeParse=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,
config())))}:{success:!0,data:result.value}},safeParse$2=_safeParse($ZodRealError),_safeParseAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0};let result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?{success:!1,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),_encode=_Err=>(schema,value,_ctx)=>{
const ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parse(_Err)(schema,value,ctx)},_decode=_Err=>(schema,value,_ctx)=>_parse(_Err)(schema,value,_ctx),_encodeAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parseAsync(_Err)(schema,value,ctx)},_decodeAsync=_Err=>async(schema,value,_ctx)=>_parseAsync(_Err)(schema,value,_ctx),_safeEncode=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?Object.
assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)},_safeDecode=_Err=>(schema,value,_ctx)=>_safeParse(_Err)(schema,value,_ctx),_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)},_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>_safeParseAsync(_Err)(schema,value,_ctx),cuid=/^[cC][^\s-]{8,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,
xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version2=>version2?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,
email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji$1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function emoji(){return new RegExp(_emoji$1,"u")}const ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,
for(const[key2,entry]of this.cache)entry.lastAccessed<oldestTime&&(oldestTime=entry.lastAccessed,oldestKey=key2);oldestKey!==null&&this.delete(oldestKey)}touch(key2){const entry=this.cache.get(key2);if(!entry)return!1;const now2=Date.now();return now2>entry.expiresAt?(this.delete(key2),!1):(entry.expiresAt=now2+this.ttlMs,entry.lastAccessed=now2,!0)}}function getRequestUrl(input){return typeof input=="string"?input:input instanceof URL?input.href:input.url}function getRequestMethod(input,init2,baseInit){
return init2?.method?init2.method:typeof Request<"u"&&input instanceof Request?input.method:baseInit?.method??"GET"}function getRequestBody(input,init2){if(init2?.body!==void 0)return init2.body;if(typeof Request<"u"&&input instanceof Request)return input.body}function summarizeRequestBody(body2){return body2==null?{kind:"empty"}:typeof body2=="string"?{kind:"string",size:body2.length}:body2 instanceof Blob?{kind:"blob",size:body2.size}:body2 instanceof URLSearchParams?{kind:"urlsearchparams",size:body2.
toString().length}:body2 instanceof FormData?{kind:"formdata"}:body2 instanceof ArrayBuffer?{kind:"arraybuffer",size:body2.byteLength}:ArrayBuffer.isView(body2)?{kind:body2.constructor.name,size:body2.byteLength}:{kind:typeof body2}}function formatDiagnosticErrorMessage(error2){const message=error2 instanceof Error?error2.message:String(error2);return message.includes("Failed to fetch")?`${message} (check CORS?)`:message}function extractJsonRpcMethods(body2){if(typeof body2=="string")try{const parsed=JSON.
parse(body2),methods=(Array.isArray(parsed)?parsed:[parsed]).map(message=>typeof message?.method=="string"?message.method:void 0).filter(method=>!!method);return methods.length>0?methods:void 0}catch{return}}function throwIfAborted(signal){if(signal?.aborted)throw new DOMException("Operation was aborted","AbortError")}function isAbortError(error2){return error2 instanceof DOMException&&error2.name==="AbortError"||error2 instanceof Error&&error2.name==="AbortError"}function uuid$1(){return globalThis.
crypto?.randomUUID?.()??Math.random().toString(36).substring(2)}function ActionIconCopyToClipboard($$anchor,$$props){push$1($$props,!0);let ariaLabel=prop($$props,"ariaLabel",3,"Copy to clipboard"),canCopy=prop($$props,"canCopy",3,!0);{let $0=user_derived(()=>canCopy()?"pointer":"not-allowed");Copy($$anchor,{get class(){return`h-3 w-3 flex-shrink-0 cursor-${get$4($0)??""}`},get"aria-label"(){return ariaLabel()},onclick:()=>canCopy()&&copyToClipboard($$props.text)})}pop()}function ActionIconRemove($$anchor,$$props){
push$1($$props,!0);let className=prop($$props,"class",3,""),iconSize=prop($$props,"iconSize",3,3);Button($$anchor,{type:"button",variant:"ghost",size:"icon-sm",get class(){return`bg-white/20 p-0 hover:bg-white/30 ${className()??""}`},onclick:e=>{e.stopPropagation(),$$props.onRemove?.($$props.id)},"aria-label":"Remove file",children:($$anchor2,$$slotProps)=>{X($$anchor2,{get class(){return`h-${iconSize()??""} w-${iconSize()??""}`}})},$$slots:{default:!0}}),pop()}var root_6$z=from_html("<p> </p>"),
root_2$15=from_html("<!> <!>",1);function BadgeChatStatistic($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,"");function handleClick(){copyToClipboard(String($$props.value))}var fragment=comment$2(),node2=first_child(fragment);{var consequent=$$anchor2=>{var fragment_1=comment$2(),node_1=first_child(fragment_1);component(node_1,()=>Root$5,($$anchor3,Tooltip_Root)=>{Tooltip_Root($$anchor3,{children:($$anchor4,$$slotProps)=>{var fragment_2=root_2$15(),node_2=first_child(
fragment_2);component(node_2,()=>Tooltip_trigger,($$anchor5,Tooltip_Trigger)=>{Tooltip_Trigger($$anchor5,{children:($$anchor6,$$slotProps2)=>{BadgeInfo($$anchor6,{get class(){return className()},onclick:handleClick,icon:$$anchor7=>{var fragment_4=comment$2(),node_3=first_child(fragment_4);component(node_3,()=>$$props.icon,($$anchor8,Icon_1)=>{Icon_1($$anchor8,{class:"h-3 w-3"})}),append($$anchor7,fragment_4)},children:($$anchor7,$$slotProps3)=>{next$1();var text2=text$8();template_effect(()=>set_text(
text2,$$props.value)),append($$anchor7,text2)},$$slots:{icon:!0,default:!0}})},$$slots:{default:!0}})});var node_4=sibling(node_2,2);component(node_4,()=>Tooltip_content,($$anchor5,Tooltip_Content)=>{Tooltip_Content($$anchor5,{children:($$anchor6,$$slotProps2)=>{var p2=root_6$z(),text_1=child(p2,!0);reset(p2),template_effect(()=>set_text(text_1,$$props.tooltipLabel)),append($$anchor6,p2)},$$slots:{default:!0}})}),append($$anchor4,fragment_2)},$$slots:{default:!0}})}),append($$anchor2,fragment_1)},
alternate=$$anchor2=>{BadgeInfo($$anchor2,{get class(){return className()},onclick:handleClick,icon:$$anchor3=>{var fragment_7=comment$2(),node_5=first_child(fragment_7);component(node_5,()=>$$props.icon,($$anchor4,Icon_2)=>{Icon_2($$anchor4,{class:"h-3 w-3"})}),append($$anchor3,fragment_7)},children:($$anchor3,$$slotProps)=>{next$1();var text_2=text$8();template_effect(()=>set_text(text_2,$$props.value)),append($$anchor3,text_2)},$$slots:{icon:!0,default:!0}})};if_block(node2,$$render=>{$$props.
tooltipLabel?$$render(consequent):$$render(alternate,!1)})}append($$anchor,fragment),pop()}var root$1w=from_html("<button><!> <!></button>");function BadgeInfo($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,"");var button=root$1w();button.__click=function(...$$args){$$props.onclick?.apply(this,$$args)};var node2=child(button);{var consequent=$$anchor2=>{var fragment=comment$2(),node_1=first_child(fragment);snippet(node_1,()=>$$props.icon),append($$anchor2,fragment)};if_block(
node2,$$render=>{$$props.icon&&$$render(consequent)})}var node_2=sibling(node2,2);snippet(node_2,()=>$$props.children),reset(button),template_effect($0=>set_class(button,1,$0),[()=>clsx(cn$1("inline-flex cursor-pointer items-center gap-1 rounded-sm bg-muted-foreground/15 px-1.5 py-0.75",className()))]),append($$anchor,button),pop()}delegate(["click"]);var root_1$$=from_html("<span><!> </span>");function BadgeModality($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,"");const displayableModalities=user_derived(
()=>$$props.modalities.filter(m=>m===ModelModality.VISION||m===ModelModality.AUDIO));var fragment=comment$2(),node2=first_child(fragment);each(node2,17,()=>get$4(displayableModalities),index$2,($$anchor2,modality)=>{const IconComponent=user_derived(()=>MODALITY_ICONS[get$4(modality)]),label=user_derived(()=>MODALITY_LABELS[get$4(modality)]);var span=root_1$$(),node_1=child(span);{var consequent=$$anchor3=>{var fragment_1=comment$2(),node_2=first_child(fragment_1);component(node_2,()=>get$4(IconComponent),
($$anchor4,IconComponent_1)=>{IconComponent_1($$anchor4,{class:"h-3 w-3"})}),append($$anchor3,fragment_1)};if_block(node_1,$$render=>{get$4(IconComponent)&&$$render(consequent)})}var text2=sibling(node_1);reset(span),template_effect($0=>{set_class(span,1,$0),set_text(text2,` ${get$4(label)??""}`)},[()=>clsx(cn$1("inline-flex items-center gap-1 rounded-md bg-muted px-2 py-1 text-xs font-medium",className()))]),append($$anchor2,span)}),append($$anchor,fragment),pop()}var root_12$a=from_html('<div \
class="mt-2 -mr-2 flex justify-end px-4"><!></div>'),root_2$14=from_html("<!> <!>",1),root_14$9=from_html('<div class="flex flex-wrap items-start justify-end gap-3"></div>'),root_1$_=from_html("<div><!></div>"),root$1v=from_html("<!> <!> <!> <!>",1);function ChatAttachmentsList($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),style2=prop($$props,"style",3,""),attachments=prop($$props,"attachments",19,()=>[]),readonly2=prop($$props,"readonly",3,!1),uploadedFiles=prop(
$$props,"uploadedFiles",27,()=>proxy([])),imageClass=prop($$props,"imageClass",3,""),imageHeight=prop($$props,"imageHeight",3,"h-24"),imageWidth=prop($$props,"imageWidth",3,"w-auto"),limitToSingleRow=prop($$props,"limitToSingleRow",3,!1),displayItems=user_derived(()=>getAttachmentDisplayItems({uploadedFiles:uploadedFiles(),attachments:attachments()})),carouselRef=state$1(void 0),isScrollable=state$1(!1),previewDialogOpen=state$1(!1),previewItem=state$1(null),mcpResourcePreviewOpen=state$1(!1),mcpResourcePreviewExtra=state$1(
null),showViewAll=user_derived(()=>limitToSingleRow()&&get$4(displayItems).length>0&&get$4(isScrollable)),viewAllDialogOpen=state$1(!1);function openPreview(item,event2){event2?.stopPropagation(),event2?.preventDefault(),set$1(previewItem,{uploadedFile:item.uploadedFile,attachment:item.attachment,preview:item.preview,name:item.name,size:item.size,textContent:item.textContent},!0),set$1(previewDialogOpen,!0)}function openMcpResourcePreview(extra){set$1(mcpResourcePreviewExtra,extra,!0),set$1(mcpResourcePreviewOpen,
!0)}function toMcpResourceAttachment(extra,id2){return{id:id2,resource:{uri:extra.uri,name:extra.name,title:extra.name,serverName:extra.serverName}}}user_effect(()=>{get$4(carouselRef)&&get$4(displayItems).length&&get$4(carouselRef).resetScroll()});var fragment=root$1v(),node2=first_child(fragment);{var consequent_10=$$anchor2=>{var div=root_1$_(),node_1=child(div);{var consequent_5=$$anchor3=>{var fragment_1=root_2$14(),node_2=first_child(fragment_1);bind_this(HorizontalScrollCarousel(node_2,{onScrollableChange:scrollable=>set$1(
isScrollable,scrollable,!0),children:($$anchor4,$$slotProps)=>{var fragment_2=comment$2(),node_3=first_child(fragment_2);each(node_3,17,()=>get$4(displayItems),item=>item.id,($$anchor5,item)=>{var fragment_3=comment$2(),node_4=first_child(fragment_3);{var consequent_1=$$anchor6=>{const mcpPrompt=user_derived(()=>get$4(item).attachment?.type===AttachmentType.MCP_PROMPT?get$4(item).attachment:get$4(item).uploadedFile?.mcpPrompt?{type:AttachmentType.MCP_PROMPT,name:get$4(item).name,serverName:get$4(
item).uploadedFile.mcpPrompt.serverName,promptName:get$4(item).uploadedFile.mcpPrompt.promptName,content:get$4(item).textContent??"",arguments:get$4(item).uploadedFile.mcpPrompt.arguments}:null);var fragment_4=comment$2(),node_5=first_child(fragment_4);{var consequent=$$anchor7=>{{let $0=user_derived(()=>limitToSingleRow()?"first:ml-4 last:mr-4":""),$1=user_derived(()=>$$props.onFileRemove?()=>$$props.onFileRemove(get$4(item).id):void 0);ChatAttachmentMcpPrompt($$anchor7,{get class(){return`max-\
w-[300px] min-w-[200px] flex-shrink-0 ${get$4($0)??""}`},get prompt(){return get$4(mcpPrompt)},get readonly(){return readonly2()},get isLoading(){return get$4(item).isLoading},get loadError(){return get$4(item).loadError},get onRemove(){return get$4($1)}})}};if_block(node_5,$$render=>{get$4(mcpPrompt)&&$$render(consequent)})}append($$anchor6,fragment_4)},alternate_2=$$anchor6=>{var fragment_6=comment$2(),node_6=first_child(fragment_6);{var consequent_2=$$anchor7=>{const mcpResource=user_derived(
()=>get$4(item).attachment);{let $0=user_derived(()=>limitToSingleRow()?"first:ml-4 last:mr-4":""),$1=user_derived(()=>toMcpResourceAttachment(get$4(mcpResource),get$4(item).id));ChatAttachmentMcpResource($$anchor7,{get class(){return`flex-shrink-0 ${get$4($0)??""}`},get attachment(){return get$4($1)},onClick:()=>openMcpResourcePreview(get$4(mcpResource))})}},alternate_1=$$anchor7=>{var fragment_8=comment$2(),node_7=first_child(fragment_8);{var consequent_3=$$anchor8=>{{let $0=user_derived(()=>limitToSingleRow()?
"first:ml-4 last:mr-4":"");ChatAttachmentThumbnailImage($$anchor8,{get class(){return`flex-shrink-0 cursor-pointer ${get$4($0)??""}`},get id(){return get$4(item).id},get name(){return get$4(item).name},get preview(){return get$4(item).preview},get readonly(){return readonly2()},get onRemove(){return $$props.onFileRemove},get height(){return imageHeight()},get width(){return imageWidth()},get imageClass(){return imageClass()},onClick:event2=>openPreview(get$4(item),event2)})}},alternate=$$anchor8=>{
{let $0=user_derived(()=>limitToSingleRow()?"first:ml-4 last:mr-4":"");ChatAttachmentThumbnailFile($$anchor8,{get class(){return`flex-shrink-0 cursor-pointer ${get$4($0)??""}`},get id(){return get$4(item).id},get name(){return get$4(item).name},get size(){return get$4(item).size},get readonly(){return readonly2()},get onRemove(){return $$props.onFileRemove},get textContent(){return get$4(item).textContent},get attachment(){return get$4(item).attachment},get uploadedFile(){return get$4(item).uploadedFile},
onClick:event2=>openPreview(get$4(item),event2)})}};if_block(node_7,$$render=>{get$4(item).isImage&&get$4(item).preview?$$render(consequent_3):$$render(alternate,!1)},!0)}append($$anchor7,fragment_8)};if_block(node_6,$$render=>{get$4(item).isMcpResource&&get$4(item).attachment?.type===AttachmentType.MCP_RESOURCE?$$render(consequent_2):$$render(alternate_1,!1)},!0)}append($$anchor6,fragment_6)};if_block(node_4,$$render=>{get$4(item).isMcpPrompt?$$render(consequent_1):$$render(alternate_2,!1)})}append(
$$anchor5,fragment_3)}),append($$anchor4,fragment_2)},$$slots:{default:!0}}),$$value=>set$1(carouselRef,$$value,!0),()=>get$4(carouselRef));var node_8=sibling(node_2,2);{var consequent_4=$$anchor4=>{var div_1=root_12$a(),node_9=child(div_1);Button(node_9,{type:"button",variant:"ghost",size:"sm",class:"h-6 text-xs text-muted-foreground hover:text-foreground",onclick:()=>set$1(viewAllDialogOpen,!0),children:($$anchor5,$$slotProps)=>{next$1();var text2=text$8();template_effect(()=>set_text(text2,`V\
iew all (${get$4(displayItems).length??""})`)),append($$anchor5,text2)},$$slots:{default:!0}}),reset(div_1),append($$anchor4,div_1)};if_block(node_8,$$render=>{get$4(showViewAll)&&$$render(consequent_4)})}append($$anchor3,fragment_1)},alternate_6=$$anchor3=>{var div_2=root_14$9();each(div_2,21,()=>get$4(displayItems),item=>item.id,($$anchor4,item)=>{var fragment_12=comment$2(),node_10=first_child(fragment_12);{var consequent_7=$$anchor5=>{const mcpPrompt=user_derived(()=>get$4(item).attachment?.
type===AttachmentType.MCP_PROMPT?get$4(item).attachment:get$4(item).uploadedFile?.mcpPrompt?{type:AttachmentType.MCP_PROMPT,name:get$4(item).name,serverName:get$4(item).uploadedFile.mcpPrompt.serverName,promptName:get$4(item).uploadedFile.mcpPrompt.promptName,content:get$4(item).textContent??"",arguments:get$4(item).uploadedFile.mcpPrompt.arguments}:null);var fragment_13=comment$2(),node_11=first_child(fragment_13);{var consequent_6=$$anchor6=>{{let $0=user_derived(()=>$$props.onFileRemove?()=>$$props.
onFileRemove(get$4(item).id):void 0);ChatAttachmentMcpPrompt($$anchor6,{class:"max-w-[300px] min-w-[200px]",get prompt(){return get$4(mcpPrompt)},get readonly(){return readonly2()},get isLoading(){return get$4(item).isLoading},get loadError(){return get$4(item).loadError},get onRemove(){return get$4($0)}})}};if_block(node_11,$$render=>{get$4(mcpPrompt)&&$$render(consequent_6)})}append($$anchor5,fragment_13)},alternate_5=$$anchor5=>{var fragment_15=comment$2(),node_12=first_child(fragment_15);{var consequent_8=$$anchor6=>{
const mcpResource=user_derived(()=>get$4(item).attachment);{let $0=user_derived(()=>toMcpResourceAttachment(get$4(mcpResource),get$4(item).id));ChatAttachmentMcpResource($$anchor6,{get attachment(){return get$4($0)},onClick:()=>openMcpResourcePreview(get$4(mcpResource))})}},alternate_4=$$anchor6=>{var fragment_17=comment$2(),node_13=first_child(fragment_17);{var consequent_9=$$anchor7=>{ChatAttachmentThumbnailImage($$anchor7,{class:"cursor-pointer",get id(){return get$4(item).id},get name(){return get$4(
item).name},get preview(){return get$4(item).preview},get readonly(){return readonly2()},get onRemove(){return $$props.onFileRemove},get height(){return imageHeight()},get width(){return imageWidth()},get imageClass(){return imageClass()},onClick:event2=>openPreview(get$4(item),event2)})},alternate_3=$$anchor7=>{ChatAttachmentThumbnailFile($$anchor7,{class:"cursor-pointer",get id(){return get$4(item).id},get name(){return get$4(item).name},get size(){return get$4(item).size},get readonly(){return readonly2()},
get onRemove(){return $$props.onFileRemove},get textContent(){return get$4(item).textContent},get attachment(){return get$4(item).attachment},get uploadedFile(){return get$4(item).uploadedFile},onClick:event2=>openPreview(get$4(item),event2)})};if_block(node_13,$$render=>{get$4(item).isImage&&get$4(item).preview?$$render(consequent_9):$$render(alternate_3,!1)},!0)}append($$anchor6,fragment_17)};if_block(node_12,$$render=>{get$4(item).isMcpResource&&get$4(item).attachment?.type===AttachmentType.MCP_RESOURCE?
$$render(consequent_8):$$render(alternate_4,!1)},!0)}append($$anchor5,fragment_15)};if_block(node_10,$$render=>{get$4(item).isMcpPrompt?$$render(consequent_7):$$render(alternate_5,!1)})}append($$anchor4,fragment_12)}),reset(div_2),append($$anchor3,div_2)};if_block(node_1,$$render=>{limitToSingleRow()?$$render(consequent_5):$$render(alternate_6,!1)})}reset(div),template_effect(()=>{set_class(div,1,clsx(className())),set_style(div,style2())}),append($$anchor2,div)};if_block(node2,$$render=>{get$4(
displayItems).length>0&&$$render(consequent_10)})}var node_14=sibling(node2,2);{var consequent_11=$$anchor2=>{DialogChatAttachmentPreview($$anchor2,{get uploadedFile(){return get$4(previewItem).uploadedFile},get attachment(){return get$4(previewItem).attachment},get preview(){return get$4(previewItem).preview},get name(){return get$4(previewItem).name},get size(){return get$4(previewItem).size},get textContent(){return get$4(previewItem).textContent},get activeModelId(){return $$props.activeModelId},
get open(){return get$4(previewDialogOpen)},set open($$value){set$1(previewDialogOpen,$$value,!0)}})};if_block(node_14,$$render=>{get$4(previewItem)&&$$render(consequent_11)})}var node_15=sibling(node_14,2);DialogChatAttachmentsViewAll(node_15,{get uploadedFiles(){return uploadedFiles()},get attachments(){return attachments()},get readonly(){return readonly2()},get onFileRemove(){return $$props.onFileRemove},imageHeight:"h-64",get imageClass(){return imageClass()},get activeModelId(){return $$props.
activeModelId},get open(){return get$4(viewAllDialogOpen)},set open($$value){set$1(viewAllDialogOpen,$$value,!0)}});var node_16=sibling(node_15,2);{var consequent_12=$$anchor2=>{DialogMcpResourcePreview($$anchor2,{get extra(){return get$4(mcpResourcePreviewExtra)},get open(){return get$4(mcpResourcePreviewOpen)},set open($$value){set$1(mcpResourcePreviewOpen,$$value,!0)}})};if_block(node_16,$$render=>{get$4(mcpResourcePreviewExtra)&&$$render(consequent_12)})}append($$anchor,fragment),pop()}var root_1$Z=from_html(
'<div class="absolute top-10 right-2 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100"><!></div>'),root$1u=from_html("<div><!> <!></div>");function ChatAttachmentMcpPrompt($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),readonly2=prop($$props,"readonly",3,!1),isLoading2=prop($$props,"isLoading",3,!1);var div=root$1u(),node2=child(div);ChatMessageMcpPromptContent(node2,{get prompt(){return $$props.prompt},get variant(){return McpPromptVariant.
ATTACHMENT},get isLoading(){return isLoading2()},get loadError(){return $$props.loadError}});var node_1=sibling(node2,2);{var consequent=$$anchor2=>{var div_1=root_1$Z(),node_2=child(div_1);ActionIconRemove(node_2,{get id(){return $$props.prompt.name},onRemove:()=>$$props.onRemove?.()}),reset(div_1),append($$anchor2,div_1)};if_block(node_1,$$render=>{!readonly2()&&$$props.onRemove&&$$render(consequent)})}reset(div),template_effect(()=>set_class(div,1,`group relative ${className()??""}`)),append(
$$anchor,div),pop()}const NEVER=Object.freeze({status:"aborted"});function $constructor(name,initializer2,params){function init2(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer2(inst,def);const proto=_.prototype,keys2=Object.keys(proto);for(let i=0;i<keys2.length;i++){const k=keys2[i];k in inst||(inst[k]=proto[k].bind(inst))}}const Parent=params?.Parent??Object;
class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a2;const inst=params?.Parent?new Definition:this;init2(inst,def),(_a2=inst._zod).deferred??(_a2.deferred=[]);for(const fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_,"init",{value:init2}),Object.defineProperty(_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),
_}class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $ZodEncodeError extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}}const globalConfig={};function config(newConfig){return globalConfig}function getEnumValues(entries){const numericValues=Object.values(entries).filter(v=>typeof v=="number");return Object.entries(entries).filter(([k,
_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function jsonStringifyReplacer(_,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return{get value(){{const value=getter();return Object.defineProperty(this,"value",{value}),value}}}}function nullish(input){return input==null}function cleanRegex(source2){const start2=source2.startsWith("^")?1:0,end=source2.endsWith("$")?source2.length-1:source2.length;return source2.slice(start2,end)}function floatSafeRemainder(val,step){
const valDecCount=(val.toString().split(".")[1]||"").length,stepString=step.toString();let stepDecCount=(stepString.split(".")[1]||"").length;if(stepDecCount===0&&/\d?e-\d?/.test(stepString)){const match=stepString.match(/\d?e-(\d?)/);match?.[1]&&(stepDecCount=Number.parseInt(match[1]))}const decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/
10**decCount}const EVALUATING=Symbol("evaluating");function defineLazy(object2,key2,getter){let value;Object.defineProperty(object2,key2,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v){Object.defineProperty(object2,key2,{value:v})},configurable:!0})}function assignProp(target2,prop2,value){Object.defineProperty(target2,prop2,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...defs){const mergedDescriptors={};for(const def of defs){
const descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};function isObject$1(data){return typeof data=="object"&&data!==null&&!Array.isArray(
data)}const allowsEval=cached(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const F=Function;return new F(""),!0}catch{return!1}});function isPlainObject$2(o){if(isObject$1(o)===!1)return!1;const ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;const prot=ctor.prototype;return!(isObject$1(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject$2(o)?{...o}:Array.isArray(
o)?[...o]:o}const propertyKeyTypes=new Set(["string","number","symbol"]);function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){const cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){const params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify b\
oth `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function optionalKeys(shape){return Object.keys(shape).filter(k=>shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional")}const NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.
MAX_VALUE,Number.MAX_VALUE]};function pick(schema,mask){const currDef=schema._zod.def,def=mergeDefs(schema._zod.def,{get shape(){const newShape={};for(const key2 in mask){if(!(key2 in currDef.shape))throw new Error(`Unrecognized key: "${key2}"`);mask[key2]&&(newShape[key2]=currDef.shape[key2])}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function omit(schema,mask){const currDef=schema._zod.def,def=mergeDefs(schema._zod.def,{get shape(){const newShape={...schema.
_zod.def.shape};for(const key2 in mask){if(!(key2 in currDef.shape))throw new Error(`Unrecognized key: "${key2}"`);mask[key2]&&delete newShape[key2]}return assignProp(this,"shape",newShape),newShape},checks:[]});return clone(schema,def)}function extend$2(schema,shape){if(!isPlainObject$2(shape))throw new Error("Invalid input to extend: expected a plain object");const checks2=schema._zod.def.checks;if(checks2&&checks2.length>0)throw new Error("Object schemas containing refinements cannot be exten\
ded. Use `.safeExtend()` instead.");const def=mergeDefs(schema._zod.def,{get shape(){const _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape},checks:[]});return clone(schema,def)}function safeExtend(schema,shape){if(!isPlainObject$2(shape))throw new Error("Invalid input to safeExtend: expected a plain object");const def={...schema._zod.def,get shape(){const _shape={...schema._zod.def.shape,...shape};return assignProp(this,"shape",_shape),_shape},checks:schema.
_zod.def.checks};return clone(schema,def)}function merge$1(a,b){const def=mergeDefs(a._zod.def,{get shape(){const _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:[]});return clone(a,def)}function partial(Class,schema,mask){const def=mergeDefs(schema._zod.def,{get shape(){const oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(const key2 in mask){if(!(key2 in oldShape))throw new Error(`U\
nrecognized key: "${key2}"`);mask[key2]&&(shape[key2]=Class?new Class({type:"optional",innerType:oldShape[key2]}):oldShape[key2])}else for(const key2 in oldShape)shape[key2]=Class?new Class({type:"optional",innerType:oldShape[key2]}):oldShape[key2];return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema,def)}function required$4(Class,schema,mask){const def=mergeDefs(schema._zod.def,{get shape(){const oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(const key2 in mask){
if(!(key2 in shape))throw new Error(`Unrecognized key: "${key2}"`);mask[key2]&&(shape[key2]=new Class({type:"nonoptional",innerType:oldShape[key2]}))}else for(const key2 in oldShape)shape[key2]=new Class({type:"nonoptional",innerType:oldShape[key2]});return assignProp(this,"shape",shape),shape},checks:[]});return clone(schema,def)}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function prefixIssues(path2,issues){
return issues.map(iss=>{var _a2;return(_a2=iss).path??(_a2.path=[]),iss.path.unshift(path2),iss})}function unwrapMessage(message){return typeof message=="string"?message:message?.message}function finalizeIssue(iss,ctx,config2){const full={...iss,path:iss.path??[]};if(!iss.message){const message=unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input";full.message=message}
return delete full.inst,delete full.continue,ctx?.reportInput||delete full.input,full}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function issue(...args){const[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}const initializer$1=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),
inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer$1),$ZodRealError=$constructor("$ZodError",initializer$1,{Parent:Error});function flattenError$1(error2,mapper=issue2=>issue2.message){const fieldErrors={},formErrors=[];for(const sub2 of error2.issues)sub2.path.length>0?(fieldErrors[sub2.path[0]]=fieldErrors[sub2.path[0]]||[],fieldErrors[sub2.path[0]].push(mapper(sub2))):
formErrors.push(mapper(sub2));return{formErrors,fieldErrors}}function formatError(error2,mapper=issue2=>issue2.message){const fieldErrors={_errors:[]},processError=error3=>{for(const issue2 of error3.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues}));else if(issue2.code==="invalid_key")processError({issues:issue2.issues});else if(issue2.code==="invalid_element")processError({issues:issue2.issues});else if(issue2.path.length===0)fieldErrors.
_errors.push(mapper(issue2));else{let curr=fieldErrors,i=0;for(;i<issue2.path.length;){const el=issue2.path[i];i===issue2.path.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue2))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}};return processError(error2),fieldErrors}const _parse=_Err=>(schema,value,_ctx,_params)=>{const ctx=_ctx?Object.assign(_ctx,{async:!1}):{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;
if(result.issues.length){const e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},_parseAsync=_Err=>async(schema,value,_ctx,params)=>{const ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0};let result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){const e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));
throw captureStackTrace(e,params?.callee),e}return result.value},_safeParse=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParse$2=_safeParse($ZodRealError),_safeParseAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?
Object.assign(_ctx,{async:!0}):{async:!0};let result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?{success:!1,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),_encode=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parse(_Err)(schema,value,ctx)},_decode=_Err=>(schema,value,_ctx)=>_parse(
_Err)(schema,value,_ctx),_encodeAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parseAsync(_Err)(schema,value,ctx)},_decodeAsync=_Err=>async(schema,value,_ctx)=>_parseAsync(_Err)(schema,value,_ctx),_safeEncode=_Err=>(schema,value,_ctx)=>{const ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)},_safeDecode=_Err=>(schema,value,_ctx)=>_safeParse(_Err)(schema,
value,_ctx),_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{const ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)},_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>_safeParseAsync(_Err)(schema,value,_ctx),cuid=/^[cC][^\s-]{8,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,
guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version2=>version2?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji$1="\
^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function emoji(){return new RegExp(_emoji$1,"u")}const ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,
cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,e164=/^\+(?:[0-9]){6,14}[0-9]$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]\
00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date$1=new RegExp(`^${dateSource}$`);function timeSource(args){const hhmm="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof args.precision=="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time$1(args){return new RegExp(`^${timeSource(args)}$`)}
function datetime$1(args){const time2=timeSource({precision:args.precision}),opts=["Z"];args.local&&opts.push(""),args.offset&&opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const timeRegex=`${time2}(?:${opts.join("|")})`;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}const string$3=params=>{const regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},integer=/^-?\d+$/,number$3=/^-?\d+(?:\.\d+)?/,boolean$2=/^(?:true|false)$/i,_null$2=/^null$/i,
@ -4890,19 +4894,31 @@ abort(),this._eventSource?.close(),this.onclose?.()}async send(message){if(!this
const{resourceMetadataUrl,scope:scope2}=extractWWWAuthenticateParams(response);if(this._resourceMetadataUrl=resourceMetadataUrl,this._scope=scope2,await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new UnauthorizedError;return this.send(message)}throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text2}`)}await response.body?.cancel()}catch(error2){throw this.onerror?.(
error2),error2}}setProtocolVersion(version2){this._protocolVersion=version2}}const SUBPROTOCOL="mcp";class WebSocketClientTransport{constructor(url2){this._url=url2}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((resolve2,reject)=>{this._socket=new WebSocket(this._url,SUBPROTOCOL),this._socket.onerror=event2=>{const error2="error"in event2?event2.error:new Error(`WebSo\
cket error: ${JSON.stringify(event2)}`);reject(error2),this.onerror?.(error2)},this._socket.onopen=()=>{resolve2()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=event2=>{let message;try{message=JSONRPCMessageSchema.parse(JSON.parse(event2.data))}catch(error2){this.onerror?.(error2);return}this.onmessage?.(message)}})}async close(){this._socket?.close()}send(message){return new Promise((resolve2,reject)=>{if(!this._socket){reject(new Error("Not connected"));return}this._socket?.
send(JSON.stringify(message)),resolve2()})}}class MCPService{static createLog(phase,message,level=MCPLogLevel.INFO,details){return{timestamp:new Date,phase,message,level,details}}static isSessionExpiredError(error2){return error2 instanceof StreamableHTTPError&&error2.code===404}static createTransport(config2){if(!config2.url)throw new Error("MCP server configuration is missing url");const useProxy=config2.useProxy??!1,requestInit={};if(config2.headers&&(requestInit.headers=config2.useProxy?buildProxiedHeaders(
config2.headers):config2.headers),useProxy&&(requestInit.headers={...getAuthHeaders(),...requestInit.headers}),config2.credentials&&(requestInit.credentials=config2.credentials),config2.transport===MCPTransportType.WEBSOCKET){if(useProxy)throw new Error("WebSocket transport is not supported when using CORS proxy. Use HTTP transport instead.");const url22=new URL(config2.url);return{transport:new WebSocketClientTransport(url22),type:MCPTransportType.WEBSOCKET}}const url2=useProxy?buildProxiedUrl(
config2.url):new URL(config2.url);try{return{transport:new StreamableHTTPClientTransport(url2,{requestInit}),type:MCPTransportType.STREAMABLE_HTTP}}catch(httpError){console.warn("[MCPService] StreamableHTTP failed, trying SSE transport...",httpError);try{return{transport:new SSEClientTransport(url2,{requestInit}),type:MCPTransportType.SSE}}catch(sseError){const httpMsg=httpError instanceof Error?httpError.message:String(httpError),sseMsg=sseError instanceof Error?sseError.message:String(sseError);
throw new Error(`Failed to create transport. StreamableHTTP: ${httpMsg}; SSE: ${sseMsg}`)}}}static extractServerInfo(impl){if(impl)return{name:impl.name,version:impl.version,title:impl.title,description:impl.description,websiteUrl:impl.websiteUrl,icons:impl.icons?.map(icon=>({src:icon.src,mimeType:icon.mimeType,sizes:icon.sizes}))}}static async connect(serverName,serverConfig,clientInfo,capabilities,onPhase,listChangedHandlers){const startTime=performance.now(),effectiveClientInfo=clientInfo??DEFAULT_MCP_CONFIG.
clientInfo,effectiveCapabilities=capabilities??DEFAULT_MCP_CONFIG.capabilities;onPhase?.(MCPConnectionPhase.TRANSPORT_CREATING,this.createLog(MCPConnectionPhase.TRANSPORT_CREATING,`Creating transport for ${serverConfig.url}`));const{transport,type:transportType}=this.createTransport(serverConfig);transportType===MCPTransportType.WEBSOCKET&&(transport.onclose=()=>{console.log(`[MCPService][${serverName}] WebSocket closed, notifying for reconnection`),onPhase?.(MCPConnectionPhase.DISCONNECTED,this.
createLog(MCPConnectionPhase.DISCONNECTED,"WebSocket connection closed"))}),onPhase?.(MCPConnectionPhase.TRANSPORT_READY,this.createLog(MCPConnectionPhase.TRANSPORT_READY,`Transport ready (${transportType})`),{transportType});const client=new Client({name:effectiveClientInfo.name,version:effectiveClientInfo.version??DEFAULT_CLIENT_VERSION},{capabilities:effectiveCapabilities,listChanged:listChangedHandlers});onPhase?.(MCPConnectionPhase.INITIALIZING,this.createLog(MCPConnectionPhase.INITIALIZING,
"Sending initialize request...")),console.log(`[MCPService][${serverName}] Connecting to server...`),await client.connect(transport);const serverVersion=client.getServerVersion(),serverCapabilities=client.getServerCapabilities(),instructions=client.getInstructions(),serverInfo=this.extractServerInfo(serverVersion);onPhase?.(MCPConnectionPhase.CAPABILITIES_EXCHANGED,this.createLog(MCPConnectionPhase.CAPABILITIES_EXCHANGED,"Capabilities exchanged successfully",MCPLogLevel.INFO,{serverCapabilities,
serverInfo}),{serverInfo,serverCapabilities,clientCapabilities:effectiveCapabilities,instructions}),onPhase?.(MCPConnectionPhase.LISTING_TOOLS,this.createLog(MCPConnectionPhase.LISTING_TOOLS,"Listing available tools...")),console.log(`[MCPService][${serverName}] Connected, listing tools...`);const tools=await this.listTools({client,transport,tools:[],serverName,transportType,connectionTimeMs:0}),connectionTimeMs=Math.round(performance.now()-startTime);return onPhase?.(MCPConnectionPhase.CONNECTED,
this.createLog(MCPConnectionPhase.CONNECTED,`Connection established with ${tools.length} tools (${connectionTimeMs}ms)`)),console.log(`[MCPService][${serverName}] Initialization complete with ${tools.length} tools in ${connectionTimeMs}ms`),{client,transport,tools,serverName,transportType,serverInfo,serverCapabilities,clientCapabilities:effectiveCapabilities,protocolVersion:DEFAULT_MCP_CONFIG.protocolVersion,instructions,connectionTimeMs}}static async disconnect(connection){console.log(`[MCPServ\
ice][${connection.serverName}] Disconnecting...`);try{connection.transport.onclose&&(connection.transport.onclose=void 0),await connection.client.close()}catch(error2){console.warn(`[MCPService][${connection.serverName}] Error during disconnect:`,error2)}}static async listTools(connection){try{return(await connection.client.listTools()).tools??[]}catch(error2){if(this.isSessionExpiredError(error2))throw error2;return console.warn(`[MCPService][${connection.serverName}] Failed to list tools:`,error2),
[]}}static async listPrompts(connection){try{return(await connection.client.listPrompts()).prompts??[]}catch(error2){if(this.isSessionExpiredError(error2))throw error2;return console.warn(`[MCPService][${connection.serverName}] Failed to list prompts:`,error2),[]}}static async getPrompt(connection,name,args){try{return await connection.client.getPrompt({name,arguments:args})}catch(error2){throw console.error(`[MCPService][${connection.serverName}] Failed to get prompt:`,error2),error2}}static async callTool(connection,params,signal){
throwIfAborted(signal);try{const result=await connection.client.callTool({name:params.name,arguments:params.arguments},void 0,{signal});return{content:this.formatToolResult(result),isError:result.isError??!1}}catch(error2){if(isAbortError(error2)||this.isSessionExpiredError(error2))throw error2;const message=error2 instanceof Error?error2.message:String(error2);throw new Error(`Tool "${params.name}" execution failed on server "${connection.serverName}": ${message}`,{cause:error2 instanceof Error?
error2:void 0})}}static formatToolResult(result){const content2=result.content;return Array.isArray(content2)?content2.map(item=>this.formatSingleContent(item)).filter(Boolean).join(`
send(JSON.stringify(message)),resolve2()})}}class MCPService{static createLog(phase,message,level=MCPLogLevel.INFO,details){return{timestamp:new Date,phase,message,level,details}}static createDiagnosticRequestDetails(input,init2,baseInit,requestHeaders,extraRedactedHeaders){const body2=getRequestBody(input,init2),details={url:getRequestUrl(input),method:getRequestMethod(input,init2,baseInit).toUpperCase(),credentials:init2?.credentials??baseInit.credentials,mode:init2?.mode??baseInit.mode,headers:sanitizeHeaders(
requestHeaders,extraRedactedHeaders,MCP_PARTIAL_REDACT_HEADERS),body:summarizeRequestBody(body2)},jsonRpcMethods=extractJsonRpcMethods(body2);return jsonRpcMethods&&(details.jsonRpcMethods=jsonRpcMethods),details}static summarizeError(error2){return error2 instanceof Error?{name:error2.name,message:error2.message,cause:error2.cause instanceof Error?{name:error2.cause.name,message:error2.cause.message}:error2.cause,stack:error2.stack?.split(`
`).slice(0,6).join(`
`)}:{value:String(error2)}}static getBrowserContext(targetUrl,useProxy){if(!(typeof window>"u"))return{location:window.location.href,origin:window.location.origin,protocol:window.location.protocol,isSecureContext:window.isSecureContext,targetOrigin:targetUrl.origin,targetProtocol:targetUrl.protocol,sameOrigin:window.location.origin===targetUrl.origin,useProxy}}static getConnectionHints(targetUrl,config2,error2){const hints=[],message=error2 instanceof Error?error2.message:String(error2),headerNames=Object.
keys(config2.headers??{});return typeof window<"u"&&(window.location.protocol==="https:"&&targetUrl.protocol==="http:"&&!config2.useProxy&&hints.push("The page is running over HTTPS but the MCP server is HTTP. Browsers often block this as mixed content; enable the proxy or use HTTPS/WSS for the MCP server."),window.location.origin!==targetUrl.origin&&!config2.useProxy&&hints.push("This is a cross-origin browser request. If the server is reachable from curl or Node but not from the browser, missi\
ng CORS headers are the most likely cause.")),headerNames.length>0&&hints.push(`Custom request headers are configured (${headerNames.join(", ")}). That triggers a CORS preflight, so the server must allow OPTIONS and include the matching Access-Control-Allow-Headers response.`),config2.credentials&&config2.credentials!=="omit"&&hints.push("Credentials are enabled for this connection. Cross-origin credentialed requests need Access-Control-Allow-Credentials: true and cannot use a wildcard Access-Co\
ntrol-Allow-Origin."),message.includes("Failed to fetch")&&hints.push('"Failed to fetch" is a browser-level network failure. Common causes are CORS rejection, mixed-content blocking, certificate/TLS errors, DNS failures, or nothing listening on the target port.'),hints}static createDiagnosticFetch(serverName,config2,baseInit,targetUrl,useProxy,onLog){let enabled=!0;const logIfEnabled=log=>{enabled&&onLog?.(log)};return{fetch:async(input,init2)=>{const startedAt=performance.now(),requestHeaders=new Headers(
baseInit.headers);if(typeof Request<"u"&&input instanceof Request)for(const[key2,value]of input.headers.entries())requestHeaders.set(key2,value);if(init2?.headers)for(const[key2,value]of new Headers(init2.headers).entries())requestHeaders.set(key2,value);const request=this.createDiagnosticRequestDetails(input,init2,baseInit,requestHeaders,Object.keys(config2.headers??{})),{method,url:url2}=request;logIfEnabled(this.createLog(MCPConnectionPhase.INITIALIZING,`HTTP ${method} ${url2}`,MCPLogLevel.INFO,
{serverName,request}));try{const response=await fetch(input,{...baseInit,...init2,headers:requestHeaders}),durationMs=Math.round(performance.now()-startedAt);return logIfEnabled(this.createLog(MCPConnectionPhase.INITIALIZING,`HTTP ${response.status} ${method} ${url2} (${durationMs}ms)`,response.ok?MCPLogLevel.INFO:MCPLogLevel.WARN,{response:{url:url2,status:response.status,statusText:response.statusText,headers:sanitizeHeaders(response.headers,void 0,MCP_PARTIAL_REDACT_HEADERS),durationMs}})),response}catch(error2){
const durationMs=Math.round(performance.now()-startedAt);throw logIfEnabled(this.createLog(MCPConnectionPhase.ERROR,`HTTP ${method} ${url2} failed: ${formatDiagnosticErrorMessage(error2)}`,MCPLogLevel.ERROR,{serverName,request,error:this.summarizeError(error2),browser:this.getBrowserContext(targetUrl,useProxy),hints:this.getConnectionHints(targetUrl,config2,error2),durationMs})),error2}},disable:()=>{enabled=!1}}}static isSessionExpiredError(error2){return error2 instanceof StreamableHTTPError&&
error2.code===404}static createTransport(serverName,config2,onLog){if(!config2.url)throw new Error("MCP server configuration is missing url");const useProxy=config2.useProxy??!1,requestInit={};if(config2.headers&&(requestInit.headers=config2.useProxy?buildProxiedHeaders(config2.headers):config2.headers),useProxy&&(requestInit.headers={...getAuthHeaders(),...requestInit.headers}),config2.credentials&&(requestInit.credentials=config2.credentials),config2.transport===MCPTransportType.WEBSOCKET){if(useProxy)
throw new Error("WebSocket transport is not supported when using CORS proxy. Use HTTP transport instead.");const url22=new URL(config2.url);return{transport:new WebSocketClientTransport(url22),type:MCPTransportType.WEBSOCKET,stopPhaseLogging:()=>{}}}const url2=useProxy?buildProxiedUrl(config2.url):new URL(config2.url),{fetch:diagnosticFetch,disable:stopPhaseLogging}=this.createDiagnosticFetch(serverName,config2,requestInit,url2,useProxy,onLog);try{return{transport:new StreamableHTTPClientTransport(
url2,{requestInit,fetch:diagnosticFetch}),type:MCPTransportType.STREAMABLE_HTTP,stopPhaseLogging}}catch(httpError){console.warn("[MCPService] StreamableHTTP failed, trying SSE transport...",httpError);try{return{transport:new SSEClientTransport(url2,{requestInit,fetch:diagnosticFetch,eventSourceInit:{fetch:diagnosticFetch}}),type:MCPTransportType.SSE,stopPhaseLogging}}catch(sseError){const httpMsg=httpError instanceof Error?httpError.message:String(httpError),sseMsg=sseError instanceof Error?sseError.
message:String(sseError);throw new Error(`Failed to create transport. StreamableHTTP: ${httpMsg}; SSE: ${sseMsg}`)}}}static extractServerInfo(impl){if(impl)return{name:impl.name,version:impl.version,title:impl.title,description:impl.description,websiteUrl:impl.websiteUrl,icons:impl.icons?.map(icon=>({src:icon.src,mimeType:icon.mimeType,sizes:icon.sizes}))}}static async connect(serverName,serverConfig,clientInfo,capabilities,onPhase,listChangedHandlers){const startTime=performance.now(),effectiveClientInfo=clientInfo??
DEFAULT_MCP_CONFIG.clientInfo,effectiveCapabilities=capabilities??DEFAULT_MCP_CONFIG.capabilities;onPhase?.(MCPConnectionPhase.TRANSPORT_CREATING,this.createLog(MCPConnectionPhase.TRANSPORT_CREATING,`Creating transport for ${serverConfig.url}`));const{transport,type:transportType,stopPhaseLogging}=this.createTransport(serverName,serverConfig,log=>onPhase?.(log.phase,log));transportType===MCPTransportType.WEBSOCKET&&(transport.onclose=()=>{console.log(`[MCPService][${serverName}] WebSocket closed\
, notifying for reconnection`),onPhase?.(MCPConnectionPhase.DISCONNECTED,this.createLog(MCPConnectionPhase.DISCONNECTED,"WebSocket connection closed"))}),onPhase?.(MCPConnectionPhase.TRANSPORT_READY,this.createLog(MCPConnectionPhase.TRANSPORT_READY,`Transport ready (${transportType})`),{transportType});const client=new Client({name:effectiveClientInfo.name,version:effectiveClientInfo.version??DEFAULT_CLIENT_VERSION},{capabilities:effectiveCapabilities,listChanged:listChangedHandlers}),runtimeErrorHandler=error2=>{
console.error(`[MCPService][${serverName}] Protocol error after initialize:`,error2)};client.onerror=error2=>{onPhase?.(MCPConnectionPhase.ERROR,this.createLog(MCPConnectionPhase.ERROR,`Protocol error: ${error2.message}`,MCPLogLevel.ERROR,{error:this.summarizeError(error2)}))},onPhase?.(MCPConnectionPhase.INITIALIZING,this.createLog(MCPConnectionPhase.INITIALIZING,"Sending initialize request...")),console.log(`[MCPService][${serverName}] Connecting to server...`);try{await client.connect(transport),
stopPhaseLogging(),client.onerror=runtimeErrorHandler}catch(error2){client.onerror=runtimeErrorHandler;const url2=serverConfig.useProxy??!1?buildProxiedUrl(serverConfig.url):new URL(serverConfig.url);throw onPhase?.(MCPConnectionPhase.ERROR,this.createLog(MCPConnectionPhase.ERROR,`Connection failed during initialize: ${error2 instanceof Error?error2.message:String(error2)}`,MCPLogLevel.ERROR,{error:this.summarizeError(error2),config:{serverName,configuredUrl:serverConfig.url,effectiveUrl:url2.href,
transportType,useProxy:serverConfig.useProxy??!1,headers:sanitizeHeaders(serverConfig.headers,Object.keys(serverConfig.headers??{}),MCP_PARTIAL_REDACT_HEADERS),credentials:serverConfig.credentials},browser:this.getBrowserContext(url2,serverConfig.useProxy??!1),hints:this.getConnectionHints(url2,serverConfig,error2)})),error2}const serverVersion=client.getServerVersion(),serverCapabilities=client.getServerCapabilities(),instructions=client.getInstructions(),serverInfo=this.extractServerInfo(serverVersion);
onPhase?.(MCPConnectionPhase.CAPABILITIES_EXCHANGED,this.createLog(MCPConnectionPhase.CAPABILITIES_EXCHANGED,"Capabilities exchanged successfully",MCPLogLevel.INFO,{serverCapabilities,serverInfo}),{serverInfo,serverCapabilities,clientCapabilities:effectiveCapabilities,instructions}),onPhase?.(MCPConnectionPhase.LISTING_TOOLS,this.createLog(MCPConnectionPhase.LISTING_TOOLS,"Listing available tools...")),console.log(`[MCPService][${serverName}] Connected, listing tools...`);const tools=await this.
listTools({client,transport,tools:[],serverName,transportType,connectionTimeMs:0}),connectionTimeMs=Math.round(performance.now()-startTime);return onPhase?.(MCPConnectionPhase.CONNECTED,this.createLog(MCPConnectionPhase.CONNECTED,`Connection established with ${tools.length} tools (${connectionTimeMs}ms)`)),console.log(`[MCPService][${serverName}] Initialization complete with ${tools.length} tools in ${connectionTimeMs}ms`),{client,transport,tools,serverName,transportType,serverInfo,serverCapabilities,
clientCapabilities:effectiveCapabilities,protocolVersion:DEFAULT_MCP_CONFIG.protocolVersion,instructions,connectionTimeMs}}static async disconnect(connection){console.log(`[MCPService][${connection.serverName}] Disconnecting...`);try{connection.transport.onclose&&(connection.transport.onclose=void 0),await connection.client.close()}catch(error2){console.warn(`[MCPService][${connection.serverName}] Error during disconnect:`,error2)}}static async listTools(connection){try{return(await connection.client.
listTools()).tools??[]}catch(error2){if(this.isSessionExpiredError(error2))throw error2;return console.warn(`[MCPService][${connection.serverName}] Failed to list tools:`,error2),[]}}static async listPrompts(connection){try{return(await connection.client.listPrompts()).prompts??[]}catch(error2){if(this.isSessionExpiredError(error2))throw error2;return console.warn(`[MCPService][${connection.serverName}] Failed to list prompts:`,error2),[]}}static async getPrompt(connection,name,args){try{return await connection.
client.getPrompt({name,arguments:args})}catch(error2){throw console.error(`[MCPService][${connection.serverName}] Failed to get prompt:`,error2),error2}}static async callTool(connection,params,signal){throwIfAborted(signal);try{const result=await connection.client.callTool({name:params.name,arguments:params.arguments},void 0,{signal});return{content:this.formatToolResult(result),isError:result.isError??!1}}catch(error2){if(isAbortError(error2)||this.isSessionExpiredError(error2))throw error2;const message=error2 instanceof
Error?error2.message:String(error2);throw new Error(`Tool "${params.name}" execution failed on server "${connection.serverName}": ${message}`,{cause:error2 instanceof Error?error2:void 0})}}static formatToolResult(result){const content2=result.content;return Array.isArray(content2)?content2.map(item=>this.formatSingleContent(item)).filter(Boolean).join(`
`):""}static formatSingleContent(content2){if(content2.type===MCPContentType.TEXT&&content2.text)return content2.text;if(content2.type===MCPContentType.IMAGE&&content2.data)return createBase64DataUrl(content2.mimeType??DEFAULT_IMAGE_MIME_TYPE,content2.data);if(content2.type===MCPContentType.RESOURCE&&content2.resource){const resource=content2.resource;return resource.text?resource.text:resource.blob?resource.blob:JSON.stringify(resource)}return content2.data&&content2.mimeType?createBase64DataUrl(
content2.mimeType,content2.data):JSON.stringify(content2)}static async complete(connection,ref2,argument){try{return(await connection.client.complete({ref:ref2,argument})).completion}catch(error2){return console.error("[MCPService] Failed to get completions:",error2),null}}static async listResources(connection,cursor){try{const result=await connection.client.listResources(cursor?{cursor}:void 0);return{resources:result.resources??[],nextCursor:result.nextCursor}}catch(error2){if(this.isSessionExpiredError(
error2))throw error2;return console.warn(`[MCPService][${connection.serverName}] Failed to list resources:`,error2),{resources:[]}}}static async listAllResources(connection){const allResources=[];let cursor;do{const result=await this.listResources(connection,cursor);allResources.push(...result.resources),cursor=result.nextCursor}while(cursor);return allResources}static async listResourceTemplates(connection,cursor){try{const result=await connection.client.listResourceTemplates(cursor?{cursor}:void 0);
@ -5023,67 +5039,68 @@ serverInfo:existingConnection.serverInfo,capabilities,transportType:existingConn
this.updateHealthCheck(server.id,{status:HealthCheckStatus.ERROR,message:"Please enter a server URL first.",logs:[]});return}this.updateHealthCheck(server.id,{status:HealthCheckStatus.CONNECTING,phase:MCPConnectionPhase.TRANSPORT_CREATING,logs:[]});const timeoutMs=Math.round(server.requestTimeoutSeconds*1e3),headers=this.parseHeaders(server.headers);try{const serverConfig={url:trimmedUrl,transport:detectMcpTransportFromUrl(trimmedUrl),handshakeTimeoutMs:DEFAULT_MCP_CONFIG.connectionTimeoutMs,requestTimeoutMs:timeoutMs,
headers,useProxy:server.useProxy};this.serverConfigs.set(server.id,serverConfig);const connection=await MCPService.connect(server.id,serverConfig,DEFAULT_MCP_CONFIG.clientInfo,DEFAULT_MCP_CONFIG.capabilities,(phase,log)=>{currentPhase=phase,logs.push(log),this.updateHealthCheck(server.id,{status:HealthCheckStatus.CONNECTING,phase,logs:[...logs]}),phase===MCPConnectionPhase.DISCONNECTED&&promoteToActive&&(console.log(`[MCPStore][${server.id}] Connection lost during health check, starting auto-rec\
onnect`),this.autoReconnect(server.id))}),tools=connection.tools.map(tool=>({name:tool.name,description:tool.description,title:tool.title})),capabilities=this.#buildCapabilitiesInfo(connection.serverCapabilities,connection.clientCapabilities);this.updateHealthCheck(server.id,{status:HealthCheckStatus.SUCCESS,tools,serverInfo:connection.serverInfo,capabilities,transportType:connection.transportType,protocolVersion:connection.protocolVersion,instructions:connection.instructions,connectionTimeMs:connection.
connectionTimeMs,logs}),promoteToActive&&server.enabled?this.promoteHealthCheckToConnection(server.id,connection):await MCPService.disconnect(connection)}catch(error2){const message=error2 instanceof Error?error2.message:"Unknown error occurred";logs.push({timestamp:new Date,phase:MCPConnectionPhase.ERROR,message:`Connection failed: ${message}`,level:MCPLogLevel.ERROR}),this.updateHealthCheck(server.id,{status:HealthCheckStatus.ERROR,message,phase:currentPhase,logs})}}promoteHealthCheckToConnection(serverId,connection){
for(const tool of connection.tools)this.toolsIndex.has(tool.name)&&console.warn(`[MCPStore] Tool name conflict during promotion: "${tool.name}" exists in "${this.toolsIndex.get(tool.name)}" and "${serverId}". Using tool from "${serverId}".`),this.toolsIndex.set(tool.name,serverId);this.connections.set(serverId,connection),this.updateState({toolCount:this.toolsIndex.size,connectedServers:Array.from(this.connections.keys())})}getServersStatus(){const statuses=[];for(const[name,connection]of this.connections)
statuses.push({name,isConnected:!0,toolCount:connection.tools.length,error:void 0});return statuses}getServerInstructions(){const results=[];for(const[serverName,connection]of this.connections)connection.instructions&&results.push({serverName,serverTitle:connection.serverInfo?.title||connection.serverInfo?.name,instructions:connection.instructions});return results}getHealthCheckInstructions(){const results=[];for(const[serverId,state2]of Object.entries(this._healthChecks))state2.status===HealthCheckStatus.
SUCCESS&&state2.instructions&&results.push({serverId,serverTitle:state2.serverInfo?.title||state2.serverInfo?.name,instructions:state2.instructions});return results}hasServerInstructions(){for(const connection of this.connections.values())if(connection.instructions)return!0;return!1}hasResourcesCapability(perChatOverrides){if(perChatOverrides!==void 0){const enabledServerIds=new Set(perChatOverrides.filter(o=>o.enabled).map(o=>o.serverId));if(enabledServerIds.size===0)return!1;for(const[serverId,
state2]of Object.entries(this._healthChecks))if(enabledServerIds.has(serverId)&&state2.status===HealthCheckStatus.SUCCESS&&state2.capabilities?.server?.resources!==void 0)return!0;for(const[serverName,connection]of this.connections)if(enabledServerIds.has(serverName)&&MCPService.supportsResources(connection))return!0;return!1}for(const state2 of Object.values(this._healthChecks))if(state2.status===HealthCheckStatus.SUCCESS&&state2.capabilities?.server?.resources!==void 0)return!0;for(const connection of this.
connections.values())if(MCPService.supportsResources(connection))return!0;return!1}getServersWithResources(){const servers=[];for(const[name,connection]of this.connections)MCPService.supportsResources(connection)&&!servers.includes(name)&&servers.push(name);for(const[serverId,state2]of Object.entries(this._healthChecks))!servers.includes(serverId)&&state2.status===HealthCheckStatus.SUCCESS&&state2.capabilities?.server?.resources!==void 0&&servers.push(serverId);return servers}async fetchAllResources(forceRefresh=!1){
const serversWithResources=this.getServersWithResources();if(serversWithResources.length!==0){if(!forceRefresh&&serversWithResources.every(serverName=>{const serverRes=mcpResourceStore.getServerResources(serverName);return!serverRes||!serverRes.lastFetched?!1:Date.now()-serverRes.lastFetched.getTime()<DEFAULT_CACHE_TTL_MS})){console.log("[MCPStore] Using cached resources");return}mcpResourceStore.setLoading(!0);try{await Promise.all(serversWithResources.map(serverName=>this.fetchServerResources(
serverName)))}finally{mcpResourceStore.setLoading(!1)}}}async fetchServerResources(serverName){const connection=this.connections.get(serverName);if(!connection){console.warn(`[MCPStore] No connection found for server: ${serverName}`);return}if(MCPService.supportsResources(connection)){mcpResourceStore.setServerLoading(serverName,!0);try{const[resources,templates]=await Promise.all([MCPService.listAllResources(connection),MCPService.listAllResourceTemplates(connection)]);mcpResourceStore.setServerResources(
serverName,resources,templates)}catch(error2){const message=error2 instanceof Error?error2.message:String(error2);mcpResourceStore.setServerError(serverName,message),console.error(`[MCPStore][${serverName}] Failed to fetch resources:`,error2)}}}async readResource(uri2){const cached2=mcpResourceStore.getCachedContent(uri2);if(cached2)return cached2.content;const serverName=mcpResourceStore.findServerForUri(uri2);if(!serverName)return console.error(`[MCPStore] No server found for resource URI: ${uri2}`),
null;const connection=this.connections.get(serverName);if(!connection)return console.error(`[MCPStore] No connection found for server: ${serverName}`),null;try{const result=await MCPService.readResource(connection,uri2),resourceInfo=mcpResourceStore.findResourceByUri(uri2);return resourceInfo&&mcpResourceStore.cacheResourceContent(resourceInfo,result.contents),result.contents}catch(error2){return console.error(`[MCPStore] Failed to read resource ${uri2}:`,error2),null}}async subscribeToResource(uri2){
const serverName=mcpResourceStore.findServerForUri(uri2);if(!serverName)return console.error(`[MCPStore] No server found for resource URI: ${uri2}`),!1;const connection=this.connections.get(serverName);if(!connection)return console.error(`[MCPStore] No connection found for server: ${serverName}`),!1;if(!MCPService.supportsResourceSubscriptions(connection))return!1;try{return await MCPService.subscribeResource(connection,uri2),mcpResourceStore.addSubscription(uri2,serverName),!0}catch(error2){return console.
error(`[MCPStore] Failed to subscribe to resource ${uri2}:`,error2),!1}}async unsubscribeFromResource(uri2){const serverName=mcpResourceStore.findServerForUri(uri2);if(!serverName)return console.error(`[MCPStore] No server found for resource URI: ${uri2}`),!1;const connection=this.connections.get(serverName);if(!connection)return console.error(`[MCPStore] No connection found for server: ${serverName}`),!1;try{return await MCPService.unsubscribeResource(connection,uri2),mcpResourceStore.removeSubscription(
uri2),!0}catch(error2){return console.error(`[MCPStore] Failed to unsubscribe from resource ${uri2}:`,error2),!1}}async attachResource(uri2){const resourceInfo=mcpResourceStore.findResourceByUri(uri2);if(!resourceInfo)return console.error(`[MCPStore] Resource not found: ${uri2}`),null;if(mcpResourceStore.isAttached(uri2))return null;const attachment=mcpResourceStore.addAttachment(resourceInfo);try{const content2=await this.readResource(uri2);content2?mcpResourceStore.updateAttachmentContent(attachment.
id,content2):mcpResourceStore.updateAttachmentError(attachment.id,"Failed to read resource")}catch(error2){const message=error2 instanceof Error?error2.message:String(error2);mcpResourceStore.updateAttachmentError(attachment.id,message)}return mcpResourceStore.getAttachment(attachment.id)??null}removeResourceAttachment(attachmentId){mcpResourceStore.removeAttachment(attachmentId)}clearResourceAttachments(){mcpResourceStore.clearAttachments()}getResourceContextForChat(){return mcpResourceStore.formatAttachmentsForContext()}consumeResourceAttachmentsAsExtras(){
const extras=mcpResourceStore.toMessageExtras();return extras.length>0&&mcpResourceStore.clearAttachments(),extras}}const mcpStore=new MCPStore;var root_2$12=from_html('<button type="button"><!> <span class="max-w-[150px] truncate text-xs"> </span> <!></button>'),root_9$m=from_html('<img alt="" class="h-3 w-3 shrink-0 rounded-sm"/>'),root_8$p=from_html('<div class="flex items-center gap-1 text-xs"><!> <span class="truncate"> </span></div>'),root_1$W=from_html("<!> <!>",1);function ChatAttachmentMcpResource($$anchor,$$props){
push$1($$props,!0);function getStatusClass(attachment){return attachment.error?"border-red-500/50 bg-red-500/10":(attachment.loading,"border-border/50 bg-muted/30")}const ResourceIcon=user_derived(()=>getResourceIcon($$props.attachment.resource.mimeType,$$props.attachment.resource.uri)),serverName=user_derived(()=>mcpStore.getServerDisplayName($$props.attachment.resource.serverName)),favicon=user_derived(()=>mcpStore.getServerFavicon($$props.attachment.resource.serverName));var fragment=comment$2(),
node2=first_child(fragment);component(node2,()=>Root$5,($$anchor2,Tooltip_Root)=>{Tooltip_Root($$anchor2,{children:($$anchor3,$$slotProps)=>{var fragment_1=root_1$W(),node_1=first_child(fragment_1);component(node_1,()=>Tooltip_trigger,($$anchor4,Tooltip_Trigger)=>{Tooltip_Trigger($$anchor4,{children:($$anchor5,$$slotProps2)=>{var button=root_2$12();button.__click=function(...$$args){$$props.onClick?.apply(this,$$args)};var node_2=child(button);{var consequent=$$anchor6=>{Loader_circle($$anchor6,
{class:"h-3 w-3 animate-spin text-muted-foreground"})},alternate_1=$$anchor6=>{var fragment_3=comment$2(),node_3=first_child(fragment_3);{var consequent_1=$$anchor7=>{Circle_alert($$anchor7,{class:"h-3 w-3 text-red-500"})},alternate=$$anchor7=>{var fragment_5=comment$2(),node_4=first_child(fragment_5);component(node_4,()=>get$4(ResourceIcon),($$anchor8,ResourceIcon_1)=>{ResourceIcon_1($$anchor8,{class:"h-3 w-3 text-muted-foreground"})}),append($$anchor7,fragment_5)};if_block(node_3,$$render=>{$$props.
attachment.error?$$render(consequent_1):$$render(alternate,!1)},!0)}append($$anchor6,fragment_3)};if_block(node_2,$$render=>{$$props.attachment.loading?$$render(consequent):$$render(alternate_1,!1)})}var span=sibling(node_2,2),text2=child(span,!0);reset(span);var node_5=sibling(span,2);{var consequent_2=$$anchor6=>{ActionIconRemove($$anchor6,{class:"-my-2 -mr-1.5 bg-transparent",iconSize:2,get id(){return $$props.attachment.id},get onRemove(){return $$props.onRemove}})};if_block(node_5,$$render=>{
$$props.onRemove&&$$render(consequent_2)})}reset(button),template_effect(($0,$1)=>{set_class(button,1,$0),button.disabled=!$$props.onClick,set_text(text2,$1)},[()=>clsx(cn$1("flex flex-shrink-0 items-center gap-1.5 rounded-md border px-2 py-0.75 text-sm transition-colors",getStatusClass($$props.attachment),$$props.onClick&&"cursor-pointer hover:bg-muted/50",$$props.class)),()=>getResourceDisplayName($$props.attachment.resource)]),append($$anchor5,button)},$$slots:{default:!0}})});var node_6=sibling(
node_1,2);component(node_6,()=>Tooltip_content,($$anchor4,Tooltip_Content)=>{Tooltip_Content($$anchor4,{children:($$anchor5,$$slotProps2)=>{var div=root_8$p(),node_7=child(div);{var consequent_3=$$anchor6=>{var img=root_9$m();template_effect(()=>set_attribute(img,"src",get$4(favicon))),event("error",img,e=>{e.currentTarget.style.display="none"}),replay_events(img),append($$anchor6,img)};if_block(node_7,$$render=>{get$4(favicon)&&$$render(consequent_3)})}var span_1=sibling(node_7,2),text_1=child(
span_1,!0);reset(span_1),reset(div),template_effect(()=>set_text(text_1,get$4(serverName))),append($$anchor5,div)},$$slots:{default:!0}})}),append($$anchor3,fragment_1)},$$slots:{default:!0}})}),append($$anchor,fragment),pop()}delegate(["click"]);const alertVariants=tv({base:"relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-curre\
nt",variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current"}},defaultVariants:{variant:"default"}});var root$1t=from_html("<div><!></div>");function Alert($$anchor,$$props){push$1($$props,!0);let ref2=prop($$props,"ref",15,null),variant=prop($$props,"variant",3,"default"),restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","class","variant","children"]);var div=root$1t();
attribute_effect(div,$0=>({"data-slot":"alert",class:$0,...restProps,role:"alert"}),[()=>cn$1(alertVariants({variant:variant()}),$$props.class)]);var node2=child(div);snippet(node2,()=>$$props.children??noop$3),reset(div),bind_this(div,$$value=>ref2($$value),()=>ref2()),append($$anchor,div),pop()}var root$1s=from_html("<div><!></div>");function Alert_description($$anchor,$$props){push$1($$props,!0);let ref2=prop($$props,"ref",15,null),restProps=rest_props($$props,["$$slots","$$events","$$legacy",
"ref","class","children"]);var div=root$1s();attribute_effect(div,$0=>({"data-slot":"alert-description",class:$0,...restProps}),[()=>cn$1("col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",$$props.class)]);var node2=child(div);snippet(node2,()=>$$props.children??noop$3),reset(div),bind_this(div,$$value=>ref2($$value),()=>ref2()),append($$anchor,div),pop()}var root$1r=from_html("<div><!></div>");function Alert_title($$anchor,$$props){push$1($$props,!0);
let ref2=prop($$props,"ref",15,null),restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","class","children"]);var div=root$1r();attribute_effect(div,$0=>({"data-slot":"alert-title",class:$0,...restProps}),[()=>cn$1("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",$$props.class)]);var node2=child(div);snippet(node2,()=>$$props.children??noop$3),reset(div),bind_this(div,$$value=>ref2($$value),()=>ref2()),append($$anchor,div),pop()}class AudioRecorder{mediaRecorder=null;audioChunks=[];stream=null;recordingState=!1;async startRecording(){
try{this.stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),this.initializeRecorder(this.stream),this.audioChunks=[],this.mediaRecorder.start(100),this.recordingState=!0}catch(error2){throw console.error("Failed to start recording:",error2),new Error("Failed to access microphone. Please check permissions.")}}async stopRecording(){return new Promise((resolve2,reject)=>{if(!this.mediaRecorder||this.mediaRecorder.state==="inactive"){
reject(new Error("No active recording to stop"));return}this.mediaRecorder.onstop=()=>{const mimeType=this.mediaRecorder?.mimeType||MimeTypeAudio.WAV,audioBlob=new Blob(this.audioChunks,{type:mimeType});this.cleanup(),resolve2(audioBlob)},this.mediaRecorder.onerror=event2=>{console.error("Recording error:",event2),this.cleanup(),reject(new Error("Recording failed"))},this.mediaRecorder.stop()})}isRecording(){return this.recordingState}cancelRecording(){this.mediaRecorder&&this.mediaRecorder.state!==
"inactive"&&this.mediaRecorder.stop(),this.cleanup()}initializeRecorder(stream){const options={};MediaRecorder.isTypeSupported(MimeTypeAudio.WAV)?options.mimeType=MimeTypeAudio.WAV:MediaRecorder.isTypeSupported(MimeTypeAudio.WEBM_OPUS)?options.mimeType=MimeTypeAudio.WEBM_OPUS:MediaRecorder.isTypeSupported(MimeTypeAudio.WEBM)?options.mimeType=MimeTypeAudio.WEBM:MediaRecorder.isTypeSupported(MimeTypeAudio.MP4)?options.mimeType=MimeTypeAudio.MP4:console.warn("No preferred audio format supported, us\
ing default"),this.mediaRecorder=new MediaRecorder(stream,options),this.mediaRecorder.ondataavailable=event2=>{event2.data.size>0&&this.audioChunks.push(event2.data)},this.mediaRecorder.onstop=()=>{this.recordingState=!1},this.mediaRecorder.onerror=event2=>{console.error("MediaRecorder error:",event2),this.recordingState=!1}}cleanup(){if(this.stream){for(const track2 of this.stream.getTracks())track2.stop();this.stream=null}this.mediaRecorder=null,this.audioChunks=[],this.recordingState=!1}}async function convertToWav(audioBlob){
try{if(audioBlob.type.includes("wav"))return audioBlob;const arrayBuffer=await audioBlob.arrayBuffer(),audioContext=new(window.AudioContext||window.webkitAudioContext),audioBuffer=await audioContext.decodeAudioData(arrayBuffer),wavBlob=audioBufferToWav(audioBuffer);return audioContext.close(),wavBlob}catch(error2){return console.error("Failed to convert audio to WAV:",error2),audioBlob}}function audioBufferToWav(buffer){const length=buffer.length,numberOfChannels=buffer.numberOfChannels,sampleRate=buffer.
sampleRate,blockAlign=numberOfChannels*2,byteRate=sampleRate*blockAlign,dataSize=length*blockAlign,bufferSize=44+dataSize,arrayBuffer=new ArrayBuffer(bufferSize),view=new DataView(arrayBuffer),writeString=(offset22,string2)=>{for(let i=0;i<string2.length;i++)view.setUint8(offset22+i,string2.charCodeAt(i))};writeString(0,"RIFF"),view.setUint32(4,bufferSize-8,!0),writeString(8,"WAVE"),writeString(12,"fmt "),view.setUint32(16,16,!0),view.setUint16(20,1,!0),view.setUint16(22,numberOfChannels,!0),view.
setUint32(24,sampleRate,!0),view.setUint32(28,byteRate,!0),view.setUint16(32,blockAlign,!0),view.setUint16(34,16,!0),writeString(36,"data"),view.setUint32(40,dataSize,!0);let offset2=44;for(let i=0;i<length;i++)for(let channel=0;channel<numberOfChannels;channel++){const sample=Math.max(-1,Math.min(1,buffer.getChannelData(channel)[i]));view.setInt16(offset2,sample*32767,!0),offset2+=2}return new Blob([arrayBuffer],{type:MimeTypeAudio.WAV})}function createAudioFile(audioBlob,filename){const timestamp=new Date().
toISOString().replace(/[:.]/g,"-"),extension2=audioBlob.type.includes("wav")?"wav":"mp3",defaultFilename=`recording-${timestamp}.${extension2}`;return new File([audioBlob],defaultFilename,{type:audioBlob.type,lastModified:Date.now()})}function isAudioRecordingSupported(){return!!(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.getUserMedia=="function"&&typeof window<"u"&&window.MediaRecorder)}const isNodeJS=typeof process=="object"&&process+""=="[object process]"&&!process.
versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),FONT_IDENTITY_MATRIX=[.001,0,0,.001,0,0],LINE_FACTOR=1.35,RenderingIntentFlag={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},AnnotationMode={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},AnnotationEditorPrefix="pdfjs_internal_editor_",AnnotationEditorType={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,SIGNATURE:101,COMMENT:102},
AnnotationEditorParamsType={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},PermissionFlag={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},TextRenderingMode={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},
util_ImageKind={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},AnnotationType={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},AnnotationBorderStyleType={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},VerbosityLevel={ERRORS:0,WARNINGS:1,INFOS:5},OPS={dependency:1,setLineWidth:2,setLineCap:3,
setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,
setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,
beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},DrawOPS={moveTo:0,
lineTo:1,curveTo:2,closePath:3},PasswordResponses={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let verbosity=VerbosityLevel.WARNINGS;function setVerbosityLevel(level){Number.isInteger(level)&&(verbosity=level)}function getVerbosityLevel(){return verbosity}function info(msg){verbosity>=VerbosityLevel.INFOS&&console.log(`Info: ${msg}`)}function warn(msg){verbosity>=VerbosityLevel.WARNINGS&&console.log(`Warning: ${msg}`)}function unreachable(msg){throw new Error(msg)}function assert$1(cond,msg){cond||unreachable(
msg)}function _isValidProtocol(url2){switch(url2?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function createValidAbsoluteUrl(url2,baseUrl=null,options=null){if(!url2)return null;if(options&&typeof url2=="string"&&(options.addDefaultProtocol&&url2.startsWith("www.")&&url2.match(/\./g)?.length>=2&&(url2=`http://${url2}`),options.tryConvertEncoding))try{url2=stringToUTF8String(url2)}catch{}const absoluteUrl=baseUrl?URL.parse(url2,baseUrl):URL.parse(
url2);return _isValidProtocol(absoluteUrl)?absoluteUrl:null}function updateUrlHash(url2,hash2,allowRel=!1){const res=URL.parse(url2);return res?(res.hash=hash2,res.href):allowRel&&createValidAbsoluteUrl(url2,"http://example.com")?url2.split("#",1)[0]+`${hash2?`#${hash2}`:""}`:""}function shadow(obj,prop2,value,nonSerializable=!1){return Object.defineProperty(obj,prop2,{value,enumerable:!nonSerializable,configurable:!0,writable:!1}),value}const BaseException=function(){function BaseException2(message,name){
this.message=message,this.name=name}return BaseException2.prototype=new Error,BaseException2.constructor=BaseException2,BaseException2}();class PasswordException extends BaseException{constructor(msg,code2){super(msg,"PasswordException"),this.code=code2}}class UnknownErrorException extends BaseException{constructor(msg,details){super(msg,"UnknownErrorException"),this.details=details}}class InvalidPDFException extends BaseException{constructor(msg){super(msg,"InvalidPDFException")}}class ResponseException extends BaseException{constructor(msg,status,missing){
super(msg,"ResponseException"),this.status=status,this.missing=missing}}class FormatError extends BaseException{constructor(msg){super(msg,"FormatError")}}class AbortException extends BaseException{constructor(msg){super(msg,"AbortException")}}function bytesToString(bytes){(typeof bytes!="object"||bytes?.length===void 0)&&unreachable("Invalid argument for bytesToString");const length=bytes.length,MAX_ARGUMENT_COUNT=8192;if(length<MAX_ARGUMENT_COUNT)return String.fromCharCode.apply(null,bytes);const strBuf=[];
for(let i=0;i<length;i+=MAX_ARGUMENT_COUNT){const chunkEnd=Math.min(i+MAX_ARGUMENT_COUNT,length),chunk=bytes.subarray(i,chunkEnd);strBuf.push(String.fromCharCode.apply(null,chunk))}return strBuf.join("")}function stringToBytes(str){typeof str!="string"&&unreachable("Invalid argument for stringToBytes");const length=str.length,bytes=new Uint8Array(length);for(let i=0;i<length;++i)bytes[i]=str.charCodeAt(i)&255;return bytes}function string32(value){return String.fromCharCode(value>>24&255,value>>16&
255,value>>8&255,value&255)}function isLittleEndian(){const buffer8=new Uint8Array(4);return buffer8[0]=1,new Uint32Array(buffer8.buffer,0,1)[0]===1}function isEvalSupported(){try{return new Function(""),!0}catch{return!1}}class util_FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",isLittleEndian())}static get isEvalSupported(){return shadow(this,"isEvalSupported",isEvalSupported())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported",
typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){const{platform:platform2,userAgent}=navigator;return shadow(this,"platform",{isAndroid:userAgent.includes("Android"),isLinux:platform2.includes("Linux"),isMac:platform2.includes("Mac"),isWindows:platform2.includes("Win"),isFirefox:userAgent.includes("Firefox")})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.
CSS?.supports?.("width: round(1.5px, 1px)"))}}const hexNumbers=Array.from(Array(256).keys(),n=>n.toString(16).padStart(2,"0"));class Util{static makeHexColor(r2,g,b){return`#${hexNumbers[r2]}${hexNumbers[g]}${hexNumbers[b]}`}static scaleMinMax(transform2,minMax){let temp;transform2[0]?(transform2[0]<0&&(temp=minMax[0],minMax[0]=minMax[2],minMax[2]=temp),minMax[0]*=transform2[0],minMax[2]*=transform2[0],transform2[3]<0&&(temp=minMax[1],minMax[1]=minMax[3],minMax[3]=temp),minMax[1]*=transform2[3],
minMax[3]*=transform2[3]):(temp=minMax[0],minMax[0]=minMax[1],minMax[1]=temp,temp=minMax[2],minMax[2]=minMax[3],minMax[3]=temp,transform2[1]<0&&(temp=minMax[1],minMax[1]=minMax[3],minMax[3]=temp),minMax[1]*=transform2[1],minMax[3]*=transform2[1],transform2[2]<0&&(temp=minMax[0],minMax[0]=minMax[2],minMax[2]=temp),minMax[0]*=transform2[2],minMax[2]*=transform2[2]),minMax[0]+=transform2[4],minMax[1]+=transform2[5],minMax[2]+=transform2[4],minMax[3]+=transform2[5]}static transform(m1,m2){return[m1[0]*
m2[0]+m1[2]*m2[1],m1[1]*m2[0]+m1[3]*m2[1],m1[0]*m2[2]+m1[2]*m2[3],m1[1]*m2[2]+m1[3]*m2[3],m1[0]*m2[4]+m1[2]*m2[5]+m1[4],m1[1]*m2[4]+m1[3]*m2[5]+m1[5]]}static applyTransform(p2,m,pos=0){const p0=p2[pos],p1=p2[pos+1];p2[pos]=p0*m[0]+p1*m[2]+m[4],p2[pos+1]=p0*m[1]+p1*m[3]+m[5]}static applyTransformToBezier(p2,transform2,pos=0){const m0=transform2[0],m1=transform2[1],m2=transform2[2],m3=transform2[3],m4=transform2[4],m5=transform2[5];for(let i=0;i<6;i+=2){const pI=p2[pos+i],pI1=p2[pos+i+1];p2[pos+i]=
pI*m0+pI1*m2+m4,p2[pos+i+1]=pI*m1+pI1*m3+m5}}static applyInverseTransform(p2,m){const p0=p2[0],p1=p2[1],d2=m[0]*m[3]-m[1]*m[2];p2[0]=(p0*m[3]-p1*m[2]+m[2]*m[5]-m[4]*m[3])/d2,p2[1]=(-p0*m[1]+p1*m[0]+m[4]*m[1]-m[5]*m[0])/d2}static axialAlignedBoundingBox(rect,transform2,output){const m0=transform2[0],m1=transform2[1],m2=transform2[2],m3=transform2[3],m4=transform2[4],m5=transform2[5],r0=rect[0],r1=rect[1],r2=rect[2],r3=rect[3];let a0=m0*r0+m4,a2=a0,a1=m0*r2+m4,a3=a1,b0=m3*r1+m5,b2=b0,b1=m3*r3+m5,b3=b1;
if(m1!==0||m2!==0){const m1r0=m1*r0,m1r2=m1*r2,m2r1=m2*r1,m2r3=m2*r3;a0+=m2r1,a3+=m2r1,a1+=m2r3,a2+=m2r3,b0+=m1r0,b3+=m1r0,b1+=m1r2,b2+=m1r2}output[0]=Math.min(output[0],a0,a1,a2,a3),output[1]=Math.min(output[1],b0,b1,b2,b3),output[2]=Math.max(output[2],a0,a1,a2,a3),output[3]=Math.max(output[3],b0,b1,b2,b3)}static inverseTransform(m){const d2=m[0]*m[3]-m[1]*m[2];return[m[3]/d2,-m[1]/d2,-m[2]/d2,m[0]/d2,(m[2]*m[5]-m[4]*m[3])/d2,(m[4]*m[1]-m[5]*m[0])/d2]}static singularValueDecompose2dScale(matrix,output){
const m0=matrix[0],m1=matrix[1],m2=matrix[2],m3=matrix[3],a=m0**2+m1**2,b=m0*m2+m1*m3,c2=m2**2+m3**2,first=(a+c2)/2,second=Math.sqrt(first**2-(a*c2-b**2));output[0]=Math.sqrt(first+second||1),output[1]=Math.sqrt(first-second||1)}static normalizeRect(rect){const r2=rect.slice(0);return rect[0]>rect[2]&&(r2[0]=rect[2],r2[2]=rect[0]),rect[1]>rect[3]&&(r2[1]=rect[3],r2[3]=rect[1]),r2}static intersect(rect1,rect2){const xLow=Math.max(Math.min(rect1[0],rect1[2]),Math.min(rect2[0],rect2[2])),xHigh=Math.
min(Math.max(rect1[0],rect1[2]),Math.max(rect2[0],rect2[2]));if(xLow>xHigh)return null;const yLow=Math.max(Math.min(rect1[1],rect1[3]),Math.min(rect2[1],rect2[3])),yHigh=Math.min(Math.max(rect1[1],rect1[3]),Math.max(rect2[1],rect2[3]));return yLow>yHigh?null:[xLow,yLow,xHigh,yHigh]}static pointBoundingBox(x,y,minMax){minMax[0]=Math.min(minMax[0],x),minMax[1]=Math.min(minMax[1],y),minMax[2]=Math.max(minMax[2],x),minMax[3]=Math.max(minMax[3],y)}static rectBoundingBox(x0,y0,x1,y1,minMax){minMax[0]=
Math.min(minMax[0],x0,x1),minMax[1]=Math.min(minMax[1],y0,y1),minMax[2]=Math.max(minMax[2],x0,x1),minMax[3]=Math.max(minMax[3],y0,y1)}static#getExtremumOnCurve(x0,x1,x2,x3,y0,y1,y2,y3,t,minMax){if(t<=0||t>=1)return;const mt=1-t,tt=t*t,ttt=tt*t,x=mt*(mt*(mt*x0+3*t*x1)+3*tt*x2)+ttt*x3,y=mt*(mt*(mt*y0+3*t*y1)+3*tt*y2)+ttt*y3;minMax[0]=Math.min(minMax[0],x),minMax[1]=Math.min(minMax[1],y),minMax[2]=Math.max(minMax[2],x),minMax[3]=Math.max(minMax[3],y)}static#getExtremum(x0,x1,x2,x3,y0,y1,y2,y3,a,b,c2,minMax){
if(Math.abs(a)<1e-12){Math.abs(b)>=1e-12&&this.#getExtremumOnCurve(x0,x1,x2,x3,y0,y1,y2,y3,-c2/b,minMax);return}const delta=b**2-4*c2*a;if(delta<0)return;const sqrtDelta=Math.sqrt(delta),a2=2*a;this.#getExtremumOnCurve(x0,x1,x2,x3,y0,y1,y2,y3,(-b+sqrtDelta)/a2,minMax),this.#getExtremumOnCurve(x0,x1,x2,x3,y0,y1,y2,y3,(-b-sqrtDelta)/a2,minMax)}static bezierBoundingBox(x0,y0,x1,y1,x2,y2,x3,y3,minMax){minMax[0]=Math.min(minMax[0],x0,x3),minMax[1]=Math.min(minMax[1],y0,y3),minMax[2]=Math.max(minMax[2],
x0,x3),minMax[3]=Math.max(minMax[3],y0,y3),this.#getExtremum(x0,x1,x2,x3,y0,y1,y2,y3,3*(-x0+3*(x1-x2)+x3),6*(x0-2*x1+x2),3*(x1-x0),minMax),this.#getExtremum(x0,x1,x2,x3,y0,y1,y2,y3,3*(-y0+3*(y1-y2)+y3),6*(y0-2*y1+y2),3*(y1-y0),minMax)}}function stringToUTF8String(str){return decodeURIComponent(escape(str))}let NormalizeRegex=null,NormalizationMap=null;function normalizeUnicode(str){return NormalizeRegex||(NormalizeRegex=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,
NormalizationMap=new Map([["ſt","ſt"]])),str.replaceAll(NormalizeRegex,(_,p1,p2)=>p1?p1.normalize("NFKC"):NormalizationMap.get(p2))}function getUuid(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const buf=new Uint8Array(32);return crypto.getRandomValues(buf),bytesToString(buf)}const AnnotationPrefix="pdfjs_internal_id_";function _isValidExplicitDest(validRef,validName,dest){if(!Array.isArray(dest)||dest.length<2)return!1;const[page2,zoom,...args]=dest;if(!validRef(page2)&&
!Number.isInteger(page2)||!validName(zoom))return!1;const argsLen=args.length;let allowNull=!0;switch(zoom.name){case"XYZ":if(argsLen<2||argsLen>3)return!1;break;case"Fit":case"FitB":return argsLen===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(argsLen>1)return!1;break;case"FitR":if(argsLen!==4)return!1;allowNull=!1;break;default:return!1}for(const arg of args)if(!(typeof arg=="number"||allowNull&&arg===null))return!1;return!0}function MathClamp(v,min2,max2){return Math.min(Math.max(v,min2),
max2)}function toBase64Util(arr){return Uint8Array.prototype.toBase64?arr.toBase64():btoa(bytesToString(arr))}function fromBase64Util(str){return Uint8Array.fromBase64?Uint8Array.fromBase64(str):stringToBytes(atob(str))}typeof Promise.try!="function"&&(Promise.try=function(fn,...args){return new Promise(resolve2=>{resolve2(fn(...args))})});typeof Math.sumPrecise!="function"&&(Math.sumPrecise=function(numbers){return numbers.reduce((a,b)=>a+b,0)});const SVG_NS="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.
connectionTimeMs,logs}),promoteToActive&&server.enabled?this.promoteHealthCheckToConnection(server.id,connection):await MCPService.disconnect(connection)}catch(error2){const message=error2 instanceof Error?error2.message:"Unknown error occurred";logs.at(-1)?.phase!==MCPConnectionPhase.ERROR&&logs.push({timestamp:new Date,phase:MCPConnectionPhase.ERROR,message:`Connection failed: ${message}`,level:MCPLogLevel.ERROR}),this.updateHealthCheck(server.id,{status:HealthCheckStatus.ERROR,message,phase:currentPhase,
logs})}}promoteHealthCheckToConnection(serverId,connection){for(const tool of connection.tools)this.toolsIndex.has(tool.name)&&console.warn(`[MCPStore] Tool name conflict during promotion: "${tool.name}" exists in "${this.toolsIndex.get(tool.name)}" and "${serverId}". Using tool from "${serverId}".`),this.toolsIndex.set(tool.name,serverId);this.connections.set(serverId,connection),this.updateState({toolCount:this.toolsIndex.size,connectedServers:Array.from(this.connections.keys())})}getServersStatus(){
const statuses=[];for(const[name,connection]of this.connections)statuses.push({name,isConnected:!0,toolCount:connection.tools.length,error:void 0});return statuses}getServerInstructions(){const results=[];for(const[serverName,connection]of this.connections)connection.instructions&&results.push({serverName,serverTitle:connection.serverInfo?.title||connection.serverInfo?.name,instructions:connection.instructions});return results}getHealthCheckInstructions(){const results=[];for(const[serverId,state2]of Object.
entries(this._healthChecks))state2.status===HealthCheckStatus.SUCCESS&&state2.instructions&&results.push({serverId,serverTitle:state2.serverInfo?.title||state2.serverInfo?.name,instructions:state2.instructions});return results}hasServerInstructions(){for(const connection of this.connections.values())if(connection.instructions)return!0;return!1}hasResourcesCapability(perChatOverrides){if(perChatOverrides!==void 0){const enabledServerIds=new Set(perChatOverrides.filter(o=>o.enabled).map(o=>o.serverId));
if(enabledServerIds.size===0)return!1;for(const[serverId,state2]of Object.entries(this._healthChecks))if(enabledServerIds.has(serverId)&&state2.status===HealthCheckStatus.SUCCESS&&state2.capabilities?.server?.resources!==void 0)return!0;for(const[serverName,connection]of this.connections)if(enabledServerIds.has(serverName)&&MCPService.supportsResources(connection))return!0;return!1}for(const state2 of Object.values(this._healthChecks))if(state2.status===HealthCheckStatus.SUCCESS&&state2.capabilities?.
server?.resources!==void 0)return!0;for(const connection of this.connections.values())if(MCPService.supportsResources(connection))return!0;return!1}getServersWithResources(){const servers=[];for(const[name,connection]of this.connections)MCPService.supportsResources(connection)&&!servers.includes(name)&&servers.push(name);for(const[serverId,state2]of Object.entries(this._healthChecks))!servers.includes(serverId)&&state2.status===HealthCheckStatus.SUCCESS&&state2.capabilities?.server?.resources!==
void 0&&servers.push(serverId);return servers}async fetchAllResources(forceRefresh=!1){const serversWithResources=this.getServersWithResources();if(serversWithResources.length!==0){if(!forceRefresh&&serversWithResources.every(serverName=>{const serverRes=mcpResourceStore.getServerResources(serverName);return!serverRes||!serverRes.lastFetched?!1:Date.now()-serverRes.lastFetched.getTime()<DEFAULT_CACHE_TTL_MS})){console.log("[MCPStore] Using cached resources");return}mcpResourceStore.setLoading(!0);
try{await Promise.all(serversWithResources.map(serverName=>this.fetchServerResources(serverName)))}finally{mcpResourceStore.setLoading(!1)}}}async fetchServerResources(serverName){const connection=this.connections.get(serverName);if(!connection){console.warn(`[MCPStore] No connection found for server: ${serverName}`);return}if(MCPService.supportsResources(connection)){mcpResourceStore.setServerLoading(serverName,!0);try{const[resources,templates]=await Promise.all([MCPService.listAllResources(connection),
MCPService.listAllResourceTemplates(connection)]);mcpResourceStore.setServerResources(serverName,resources,templates)}catch(error2){const message=error2 instanceof Error?error2.message:String(error2);mcpResourceStore.setServerError(serverName,message),console.error(`[MCPStore][${serverName}] Failed to fetch resources:`,error2)}}}async readResource(uri2){const cached2=mcpResourceStore.getCachedContent(uri2);if(cached2)return cached2.content;const serverName=mcpResourceStore.findServerForUri(uri2);
if(!serverName)return console.error(`[MCPStore] No server found for resource URI: ${uri2}`),null;const connection=this.connections.get(serverName);if(!connection)return console.error(`[MCPStore] No connection found for server: ${serverName}`),null;try{const result=await MCPService.readResource(connection,uri2),resourceInfo=mcpResourceStore.findResourceByUri(uri2);return resourceInfo&&mcpResourceStore.cacheResourceContent(resourceInfo,result.contents),result.contents}catch(error2){return console.
error(`[MCPStore] Failed to read resource ${uri2}:`,error2),null}}async subscribeToResource(uri2){const serverName=mcpResourceStore.findServerForUri(uri2);if(!serverName)return console.error(`[MCPStore] No server found for resource URI: ${uri2}`),!1;const connection=this.connections.get(serverName);if(!connection)return console.error(`[MCPStore] No connection found for server: ${serverName}`),!1;if(!MCPService.supportsResourceSubscriptions(connection))return!1;try{return await MCPService.subscribeResource(
connection,uri2),mcpResourceStore.addSubscription(uri2,serverName),!0}catch(error2){return console.error(`[MCPStore] Failed to subscribe to resource ${uri2}:`,error2),!1}}async unsubscribeFromResource(uri2){const serverName=mcpResourceStore.findServerForUri(uri2);if(!serverName)return console.error(`[MCPStore] No server found for resource URI: ${uri2}`),!1;const connection=this.connections.get(serverName);if(!connection)return console.error(`[MCPStore] No connection found for server: ${serverName}`),
!1;try{return await MCPService.unsubscribeResource(connection,uri2),mcpResourceStore.removeSubscription(uri2),!0}catch(error2){return console.error(`[MCPStore] Failed to unsubscribe from resource ${uri2}:`,error2),!1}}async attachResource(uri2){const resourceInfo=mcpResourceStore.findResourceByUri(uri2);if(!resourceInfo)return console.error(`[MCPStore] Resource not found: ${uri2}`),null;if(mcpResourceStore.isAttached(uri2))return null;const attachment=mcpResourceStore.addAttachment(resourceInfo);
try{const content2=await this.readResource(uri2);content2?mcpResourceStore.updateAttachmentContent(attachment.id,content2):mcpResourceStore.updateAttachmentError(attachment.id,"Failed to read resource")}catch(error2){const message=error2 instanceof Error?error2.message:String(error2);mcpResourceStore.updateAttachmentError(attachment.id,message)}return mcpResourceStore.getAttachment(attachment.id)??null}removeResourceAttachment(attachmentId){mcpResourceStore.removeAttachment(attachmentId)}clearResourceAttachments(){
mcpResourceStore.clearAttachments()}getResourceContextForChat(){return mcpResourceStore.formatAttachmentsForContext()}consumeResourceAttachmentsAsExtras(){const extras=mcpResourceStore.toMessageExtras();return extras.length>0&&mcpResourceStore.clearAttachments(),extras}}const mcpStore=new MCPStore;var root_2$12=from_html('<button type="button"><!> <span class="max-w-[150px] truncate text-xs"> </span> <!></button>'),root_9$n=from_html('<img alt="" class="h-3 w-3 shrink-0 rounded-sm"/>'),root_8$p=from_html(
'<div class="flex items-center gap-1 text-xs"><!> <span class="truncate"> </span></div>'),root_1$W=from_html("<!> <!>",1);function ChatAttachmentMcpResource($$anchor,$$props){push$1($$props,!0);function getStatusClass(attachment){return attachment.error?"border-red-500/50 bg-red-500/10":(attachment.loading,"border-border/50 bg-muted/30")}const ResourceIcon=user_derived(()=>getResourceIcon($$props.attachment.resource.mimeType,$$props.attachment.resource.uri)),serverName=user_derived(()=>mcpStore.
getServerDisplayName($$props.attachment.resource.serverName)),favicon=user_derived(()=>mcpStore.getServerFavicon($$props.attachment.resource.serverName));var fragment=comment$2(),node2=first_child(fragment);component(node2,()=>Root$5,($$anchor2,Tooltip_Root)=>{Tooltip_Root($$anchor2,{children:($$anchor3,$$slotProps)=>{var fragment_1=root_1$W(),node_1=first_child(fragment_1);component(node_1,()=>Tooltip_trigger,($$anchor4,Tooltip_Trigger)=>{Tooltip_Trigger($$anchor4,{children:($$anchor5,$$slotProps2)=>{
var button=root_2$12();button.__click=function(...$$args){$$props.onClick?.apply(this,$$args)};var node_2=child(button);{var consequent=$$anchor6=>{Loader_circle($$anchor6,{class:"h-3 w-3 animate-spin text-muted-foreground"})},alternate_1=$$anchor6=>{var fragment_3=comment$2(),node_3=first_child(fragment_3);{var consequent_1=$$anchor7=>{Circle_alert($$anchor7,{class:"h-3 w-3 text-red-500"})},alternate=$$anchor7=>{var fragment_5=comment$2(),node_4=first_child(fragment_5);component(node_4,()=>get$4(
ResourceIcon),($$anchor8,ResourceIcon_1)=>{ResourceIcon_1($$anchor8,{class:"h-3 w-3 text-muted-foreground"})}),append($$anchor7,fragment_5)};if_block(node_3,$$render=>{$$props.attachment.error?$$render(consequent_1):$$render(alternate,!1)},!0)}append($$anchor6,fragment_3)};if_block(node_2,$$render=>{$$props.attachment.loading?$$render(consequent):$$render(alternate_1,!1)})}var span=sibling(node_2,2),text2=child(span,!0);reset(span);var node_5=sibling(span,2);{var consequent_2=$$anchor6=>{ActionIconRemove(
$$anchor6,{class:"-my-2 -mr-1.5 bg-transparent",iconSize:2,get id(){return $$props.attachment.id},get onRemove(){return $$props.onRemove}})};if_block(node_5,$$render=>{$$props.onRemove&&$$render(consequent_2)})}reset(button),template_effect(($0,$1)=>{set_class(button,1,$0),button.disabled=!$$props.onClick,set_text(text2,$1)},[()=>clsx(cn$1("flex flex-shrink-0 items-center gap-1.5 rounded-md border px-2 py-0.75 text-sm transition-colors",getStatusClass($$props.attachment),$$props.onClick&&"cursor\
-pointer hover:bg-muted/50",$$props.class)),()=>getResourceDisplayName($$props.attachment.resource)]),append($$anchor5,button)},$$slots:{default:!0}})});var node_6=sibling(node_1,2);component(node_6,()=>Tooltip_content,($$anchor4,Tooltip_Content)=>{Tooltip_Content($$anchor4,{children:($$anchor5,$$slotProps2)=>{var div=root_8$p(),node_7=child(div);{var consequent_3=$$anchor6=>{var img=root_9$n();template_effect(()=>set_attribute(img,"src",get$4(favicon))),event("error",img,e=>{e.currentTarget.style.
display="none"}),replay_events(img),append($$anchor6,img)};if_block(node_7,$$render=>{get$4(favicon)&&$$render(consequent_3)})}var span_1=sibling(node_7,2),text_1=child(span_1,!0);reset(span_1),reset(div),template_effect(()=>set_text(text_1,get$4(serverName))),append($$anchor5,div)},$$slots:{default:!0}})}),append($$anchor3,fragment_1)},$$slots:{default:!0}})}),append($$anchor,fragment),pop()}delegate(["click"]);const alertVariants=tv({base:"relative grid w-full grid-cols-[0_1fr] items-start gap\
-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current"}},defaultVariants:{variant:"default"}});var root$1t=from_html("<div><!></div>");function Alert($$anchor,$$props){push$1($$props,!0);let ref2=prop($$props,"re\
f",15,null),variant=prop($$props,"variant",3,"default"),restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","class","variant","children"]);var div=root$1t();attribute_effect(div,$0=>({"data-slot":"alert",class:$0,...restProps,role:"alert"}),[()=>cn$1(alertVariants({variant:variant()}),$$props.class)]);var node2=child(div);snippet(node2,()=>$$props.children??noop$3),reset(div),bind_this(div,$$value=>ref2($$value),()=>ref2()),append($$anchor,div),pop()}var root$1s=from_html("<div><\
!></div>");function Alert_description($$anchor,$$props){push$1($$props,!0);let ref2=prop($$props,"ref",15,null),restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","class","children"]);var div=root$1s();attribute_effect(div,$0=>({"data-slot":"alert-description",class:$0,...restProps}),[()=>cn$1("col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",$$props.class)]);var node2=child(div);snippet(node2,()=>$$props.children??noop$3),reset(div),
bind_this(div,$$value=>ref2($$value),()=>ref2()),append($$anchor,div),pop()}var root$1r=from_html("<div><!></div>");function Alert_title($$anchor,$$props){push$1($$props,!0);let ref2=prop($$props,"ref",15,null),restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","class","children"]);var div=root$1r();attribute_effect(div,$0=>({"data-slot":"alert-title",class:$0,...restProps}),[()=>cn$1("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",$$props.class)]);var node2=child(
div);snippet(node2,()=>$$props.children??noop$3),reset(div),bind_this(div,$$value=>ref2($$value),()=>ref2()),append($$anchor,div),pop()}class AudioRecorder{mediaRecorder=null;audioChunks=[];stream=null;recordingState=!1;async startRecording(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),this.initializeRecorder(this.stream),this.audioChunks=[],this.mediaRecorder.start(100),this.recordingState=!0}catch(error2){throw console.
error("Failed to start recording:",error2),new Error("Failed to access microphone. Please check permissions.")}}async stopRecording(){return new Promise((resolve2,reject)=>{if(!this.mediaRecorder||this.mediaRecorder.state==="inactive"){reject(new Error("No active recording to stop"));return}this.mediaRecorder.onstop=()=>{const mimeType=this.mediaRecorder?.mimeType||MimeTypeAudio.WAV,audioBlob=new Blob(this.audioChunks,{type:mimeType});this.cleanup(),resolve2(audioBlob)},this.mediaRecorder.onerror=
event2=>{console.error("Recording error:",event2),this.cleanup(),reject(new Error("Recording failed"))},this.mediaRecorder.stop()})}isRecording(){return this.recordingState}cancelRecording(){this.mediaRecorder&&this.mediaRecorder.state!=="inactive"&&this.mediaRecorder.stop(),this.cleanup()}initializeRecorder(stream){const options={};MediaRecorder.isTypeSupported(MimeTypeAudio.WAV)?options.mimeType=MimeTypeAudio.WAV:MediaRecorder.isTypeSupported(MimeTypeAudio.WEBM_OPUS)?options.mimeType=MimeTypeAudio.
WEBM_OPUS:MediaRecorder.isTypeSupported(MimeTypeAudio.WEBM)?options.mimeType=MimeTypeAudio.WEBM:MediaRecorder.isTypeSupported(MimeTypeAudio.MP4)?options.mimeType=MimeTypeAudio.MP4:console.warn("No preferred audio format supported, using default"),this.mediaRecorder=new MediaRecorder(stream,options),this.mediaRecorder.ondataavailable=event2=>{event2.data.size>0&&this.audioChunks.push(event2.data)},this.mediaRecorder.onstop=()=>{this.recordingState=!1},this.mediaRecorder.onerror=event2=>{console.error(
"MediaRecorder error:",event2),this.recordingState=!1}}cleanup(){if(this.stream){for(const track2 of this.stream.getTracks())track2.stop();this.stream=null}this.mediaRecorder=null,this.audioChunks=[],this.recordingState=!1}}async function convertToWav(audioBlob){try{if(audioBlob.type.includes("wav"))return audioBlob;const arrayBuffer=await audioBlob.arrayBuffer(),audioContext=new(window.AudioContext||window.webkitAudioContext),audioBuffer=await audioContext.decodeAudioData(arrayBuffer),wavBlob=audioBufferToWav(
audioBuffer);return audioContext.close(),wavBlob}catch(error2){return console.error("Failed to convert audio to WAV:",error2),audioBlob}}function audioBufferToWav(buffer){const length=buffer.length,numberOfChannels=buffer.numberOfChannels,sampleRate=buffer.sampleRate,blockAlign=numberOfChannels*2,byteRate=sampleRate*blockAlign,dataSize=length*blockAlign,bufferSize=44+dataSize,arrayBuffer=new ArrayBuffer(bufferSize),view=new DataView(arrayBuffer),writeString=(offset22,string2)=>{for(let i=0;i<string2.
length;i++)view.setUint8(offset22+i,string2.charCodeAt(i))};writeString(0,"RIFF"),view.setUint32(4,bufferSize-8,!0),writeString(8,"WAVE"),writeString(12,"fmt "),view.setUint32(16,16,!0),view.setUint16(20,1,!0),view.setUint16(22,numberOfChannels,!0),view.setUint32(24,sampleRate,!0),view.setUint32(28,byteRate,!0),view.setUint16(32,blockAlign,!0),view.setUint16(34,16,!0),writeString(36,"data"),view.setUint32(40,dataSize,!0);let offset2=44;for(let i=0;i<length;i++)for(let channel=0;channel<numberOfChannels;channel++){
const sample=Math.max(-1,Math.min(1,buffer.getChannelData(channel)[i]));view.setInt16(offset2,sample*32767,!0),offset2+=2}return new Blob([arrayBuffer],{type:MimeTypeAudio.WAV})}function createAudioFile(audioBlob,filename){const timestamp=new Date().toISOString().replace(/[:.]/g,"-"),extension2=audioBlob.type.includes("wav")?"wav":"mp3",defaultFilename=`recording-${timestamp}.${extension2}`;return new File([audioBlob],defaultFilename,{type:audioBlob.type,lastModified:Date.now()})}function isAudioRecordingSupported(){
return!!(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.getUserMedia=="function"&&typeof window<"u"&&window.MediaRecorder)}const isNodeJS=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),FONT_IDENTITY_MATRIX=[.001,0,0,.001,0,0],LINE_FACTOR=1.35,RenderingIntentFlag={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,
OPLIST:256},AnnotationMode={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},AnnotationEditorPrefix="pdfjs_internal_editor_",AnnotationEditorType={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,SIGNATURE:101,COMMENT:102},AnnotationEditorParamsType={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},PermissionFlag={PRINT:4,
MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},TextRenderingMode={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},util_ImageKind={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},AnnotationType={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,
WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},AnnotationBorderStyleType={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},VerbosityLevel={ERRORS:0,WARNINGS:1,INFOS:5},OPS={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,
eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,
setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,
paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},DrawOPS={moveTo:0,lineTo:1,curveTo:2,closePath:3},PasswordResponses={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let verbosity=VerbosityLevel.WARNINGS;function setVerbosityLevel(level){Number.isInteger(level)&&(verbosity=level)}function getVerbosityLevel(){return verbosity}
function info(msg){verbosity>=VerbosityLevel.INFOS&&console.log(`Info: ${msg}`)}function warn(msg){verbosity>=VerbosityLevel.WARNINGS&&console.log(`Warning: ${msg}`)}function unreachable(msg){throw new Error(msg)}function assert$1(cond,msg){cond||unreachable(msg)}function _isValidProtocol(url2){switch(url2?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function createValidAbsoluteUrl(url2,baseUrl=null,options=null){if(!url2)return null;if(options&&
typeof url2=="string"&&(options.addDefaultProtocol&&url2.startsWith("www.")&&url2.match(/\./g)?.length>=2&&(url2=`http://${url2}`),options.tryConvertEncoding))try{url2=stringToUTF8String(url2)}catch{}const absoluteUrl=baseUrl?URL.parse(url2,baseUrl):URL.parse(url2);return _isValidProtocol(absoluteUrl)?absoluteUrl:null}function updateUrlHash(url2,hash2,allowRel=!1){const res=URL.parse(url2);return res?(res.hash=hash2,res.href):allowRel&&createValidAbsoluteUrl(url2,"http://example.com")?url2.split(
"#",1)[0]+`${hash2?`#${hash2}`:""}`:""}function shadow(obj,prop2,value,nonSerializable=!1){return Object.defineProperty(obj,prop2,{value,enumerable:!nonSerializable,configurable:!0,writable:!1}),value}const BaseException=function(){function BaseException2(message,name){this.message=message,this.name=name}return BaseException2.prototype=new Error,BaseException2.constructor=BaseException2,BaseException2}();class PasswordException extends BaseException{constructor(msg,code2){super(msg,"PasswordExce\
ption"),this.code=code2}}class UnknownErrorException extends BaseException{constructor(msg,details){super(msg,"UnknownErrorException"),this.details=details}}class InvalidPDFException extends BaseException{constructor(msg){super(msg,"InvalidPDFException")}}class ResponseException extends BaseException{constructor(msg,status,missing){super(msg,"ResponseException"),this.status=status,this.missing=missing}}class FormatError extends BaseException{constructor(msg){super(msg,"FormatError")}}class AbortException extends BaseException{constructor(msg){
super(msg,"AbortException")}}function bytesToString(bytes){(typeof bytes!="object"||bytes?.length===void 0)&&unreachable("Invalid argument for bytesToString");const length=bytes.length,MAX_ARGUMENT_COUNT=8192;if(length<MAX_ARGUMENT_COUNT)return String.fromCharCode.apply(null,bytes);const strBuf=[];for(let i=0;i<length;i+=MAX_ARGUMENT_COUNT){const chunkEnd=Math.min(i+MAX_ARGUMENT_COUNT,length),chunk=bytes.subarray(i,chunkEnd);strBuf.push(String.fromCharCode.apply(null,chunk))}return strBuf.join("")}
function stringToBytes(str){typeof str!="string"&&unreachable("Invalid argument for stringToBytes");const length=str.length,bytes=new Uint8Array(length);for(let i=0;i<length;++i)bytes[i]=str.charCodeAt(i)&255;return bytes}function string32(value){return String.fromCharCode(value>>24&255,value>>16&255,value>>8&255,value&255)}function isLittleEndian(){const buffer8=new Uint8Array(4);return buffer8[0]=1,new Uint32Array(buffer8.buffer,0,1)[0]===1}function isEvalSupported(){try{return new Function(""),
!0}catch{return!1}}class util_FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",isLittleEndian())}static get isEvalSupported(){return shadow(this,"isEvalSupported",isEvalSupported())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){const{platform:platform2,userAgent}=navigator;
return shadow(this,"platform",{isAndroid:userAgent.includes("Android"),isLinux:platform2.includes("Linux"),isMac:platform2.includes("Mac"),isWindows:platform2.includes("Win"),isFirefox:userAgent.includes("Firefox")})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const hexNumbers=Array.from(Array(256).keys(),n=>n.toString(16).padStart(2,"0"));class Util{static makeHexColor(r2,g,b){return`#${hexNumbers[r2]}${hexNumbers[g]}${hexNumbers[b]}`}static scaleMinMax(transform2,minMax){
let temp;transform2[0]?(transform2[0]<0&&(temp=minMax[0],minMax[0]=minMax[2],minMax[2]=temp),minMax[0]*=transform2[0],minMax[2]*=transform2[0],transform2[3]<0&&(temp=minMax[1],minMax[1]=minMax[3],minMax[3]=temp),minMax[1]*=transform2[3],minMax[3]*=transform2[3]):(temp=minMax[0],minMax[0]=minMax[1],minMax[1]=temp,temp=minMax[2],minMax[2]=minMax[3],minMax[3]=temp,transform2[1]<0&&(temp=minMax[1],minMax[1]=minMax[3],minMax[3]=temp),minMax[1]*=transform2[1],minMax[3]*=transform2[1],transform2[2]<0&&
(temp=minMax[0],minMax[0]=minMax[2],minMax[2]=temp),minMax[0]*=transform2[2],minMax[2]*=transform2[2]),minMax[0]+=transform2[4],minMax[1]+=transform2[5],minMax[2]+=transform2[4],minMax[3]+=transform2[5]}static transform(m1,m2){return[m1[0]*m2[0]+m1[2]*m2[1],m1[1]*m2[0]+m1[3]*m2[1],m1[0]*m2[2]+m1[2]*m2[3],m1[1]*m2[2]+m1[3]*m2[3],m1[0]*m2[4]+m1[2]*m2[5]+m1[4],m1[1]*m2[4]+m1[3]*m2[5]+m1[5]]}static applyTransform(p2,m,pos=0){const p0=p2[pos],p1=p2[pos+1];p2[pos]=p0*m[0]+p1*m[2]+m[4],p2[pos+1]=p0*m[1]+
p1*m[3]+m[5]}static applyTransformToBezier(p2,transform2,pos=0){const m0=transform2[0],m1=transform2[1],m2=transform2[2],m3=transform2[3],m4=transform2[4],m5=transform2[5];for(let i=0;i<6;i+=2){const pI=p2[pos+i],pI1=p2[pos+i+1];p2[pos+i]=pI*m0+pI1*m2+m4,p2[pos+i+1]=pI*m1+pI1*m3+m5}}static applyInverseTransform(p2,m){const p0=p2[0],p1=p2[1],d2=m[0]*m[3]-m[1]*m[2];p2[0]=(p0*m[3]-p1*m[2]+m[2]*m[5]-m[4]*m[3])/d2,p2[1]=(-p0*m[1]+p1*m[0]+m[4]*m[1]-m[5]*m[0])/d2}static axialAlignedBoundingBox(rect,transform2,output){
const m0=transform2[0],m1=transform2[1],m2=transform2[2],m3=transform2[3],m4=transform2[4],m5=transform2[5],r0=rect[0],r1=rect[1],r2=rect[2],r3=rect[3];let a0=m0*r0+m4,a2=a0,a1=m0*r2+m4,a3=a1,b0=m3*r1+m5,b2=b0,b1=m3*r3+m5,b3=b1;if(m1!==0||m2!==0){const m1r0=m1*r0,m1r2=m1*r2,m2r1=m2*r1,m2r3=m2*r3;a0+=m2r1,a3+=m2r1,a1+=m2r3,a2+=m2r3,b0+=m1r0,b3+=m1r0,b1+=m1r2,b2+=m1r2}output[0]=Math.min(output[0],a0,a1,a2,a3),output[1]=Math.min(output[1],b0,b1,b2,b3),output[2]=Math.max(output[2],a0,a1,a2,a3),output[3]=
Math.max(output[3],b0,b1,b2,b3)}static inverseTransform(m){const d2=m[0]*m[3]-m[1]*m[2];return[m[3]/d2,-m[1]/d2,-m[2]/d2,m[0]/d2,(m[2]*m[5]-m[4]*m[3])/d2,(m[4]*m[1]-m[5]*m[0])/d2]}static singularValueDecompose2dScale(matrix,output){const m0=matrix[0],m1=matrix[1],m2=matrix[2],m3=matrix[3],a=m0**2+m1**2,b=m0*m2+m1*m3,c2=m2**2+m3**2,first=(a+c2)/2,second=Math.sqrt(first**2-(a*c2-b**2));output[0]=Math.sqrt(first+second||1),output[1]=Math.sqrt(first-second||1)}static normalizeRect(rect){const r2=rect.
slice(0);return rect[0]>rect[2]&&(r2[0]=rect[2],r2[2]=rect[0]),rect[1]>rect[3]&&(r2[1]=rect[3],r2[3]=rect[1]),r2}static intersect(rect1,rect2){const xLow=Math.max(Math.min(rect1[0],rect1[2]),Math.min(rect2[0],rect2[2])),xHigh=Math.min(Math.max(rect1[0],rect1[2]),Math.max(rect2[0],rect2[2]));if(xLow>xHigh)return null;const yLow=Math.max(Math.min(rect1[1],rect1[3]),Math.min(rect2[1],rect2[3])),yHigh=Math.min(Math.max(rect1[1],rect1[3]),Math.max(rect2[1],rect2[3]));return yLow>yHigh?null:[xLow,yLow,
xHigh,yHigh]}static pointBoundingBox(x,y,minMax){minMax[0]=Math.min(minMax[0],x),minMax[1]=Math.min(minMax[1],y),minMax[2]=Math.max(minMax[2],x),minMax[3]=Math.max(minMax[3],y)}static rectBoundingBox(x0,y0,x1,y1,minMax){minMax[0]=Math.min(minMax[0],x0,x1),minMax[1]=Math.min(minMax[1],y0,y1),minMax[2]=Math.max(minMax[2],x0,x1),minMax[3]=Math.max(minMax[3],y0,y1)}static#getExtremumOnCurve(x0,x1,x2,x3,y0,y1,y2,y3,t,minMax){if(t<=0||t>=1)return;const mt=1-t,tt=t*t,ttt=tt*t,x=mt*(mt*(mt*x0+3*t*x1)+3*
tt*x2)+ttt*x3,y=mt*(mt*(mt*y0+3*t*y1)+3*tt*y2)+ttt*y3;minMax[0]=Math.min(minMax[0],x),minMax[1]=Math.min(minMax[1],y),minMax[2]=Math.max(minMax[2],x),minMax[3]=Math.max(minMax[3],y)}static#getExtremum(x0,x1,x2,x3,y0,y1,y2,y3,a,b,c2,minMax){if(Math.abs(a)<1e-12){Math.abs(b)>=1e-12&&this.#getExtremumOnCurve(x0,x1,x2,x3,y0,y1,y2,y3,-c2/b,minMax);return}const delta=b**2-4*c2*a;if(delta<0)return;const sqrtDelta=Math.sqrt(delta),a2=2*a;this.#getExtremumOnCurve(x0,x1,x2,x3,y0,y1,y2,y3,(-b+sqrtDelta)/a2,
minMax),this.#getExtremumOnCurve(x0,x1,x2,x3,y0,y1,y2,y3,(-b-sqrtDelta)/a2,minMax)}static bezierBoundingBox(x0,y0,x1,y1,x2,y2,x3,y3,minMax){minMax[0]=Math.min(minMax[0],x0,x3),minMax[1]=Math.min(minMax[1],y0,y3),minMax[2]=Math.max(minMax[2],x0,x3),minMax[3]=Math.max(minMax[3],y0,y3),this.#getExtremum(x0,x1,x2,x3,y0,y1,y2,y3,3*(-x0+3*(x1-x2)+x3),6*(x0-2*x1+x2),3*(x1-x0),minMax),this.#getExtremum(x0,x1,x2,x3,y0,y1,y2,y3,3*(-y0+3*(y1-y2)+y3),6*(y0-2*y1+y2),3*(y1-y0),minMax)}}function stringToUTF8String(str){
return decodeURIComponent(escape(str))}let NormalizeRegex=null,NormalizationMap=null;function normalizeUnicode(str){return NormalizeRegex||(NormalizeRegex=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,NormalizationMap=
new Map([["ſt","ſt"]])),str.replaceAll(NormalizeRegex,(_,p1,p2)=>p1?p1.normalize("NFKC"):NormalizationMap.get(p2))}function getUuid(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const buf=new Uint8Array(32);return crypto.getRandomValues(buf),bytesToString(buf)}const AnnotationPrefix="pdfjs_internal_id_";function _isValidExplicitDest(validRef,validName,dest){if(!Array.isArray(dest)||dest.length<2)return!1;const[page2,zoom,...args]=dest;if(!validRef(page2)&&!Number.isInteger(
page2)||!validName(zoom))return!1;const argsLen=args.length;let allowNull=!0;switch(zoom.name){case"XYZ":if(argsLen<2||argsLen>3)return!1;break;case"Fit":case"FitB":return argsLen===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(argsLen>1)return!1;break;case"FitR":if(argsLen!==4)return!1;allowNull=!1;break;default:return!1}for(const arg of args)if(!(typeof arg=="number"||allowNull&&arg===null))return!1;return!0}function MathClamp(v,min2,max2){return Math.min(Math.max(v,min2),max2)}function toBase64Util(arr){
return Uint8Array.prototype.toBase64?arr.toBase64():btoa(bytesToString(arr))}function fromBase64Util(str){return Uint8Array.fromBase64?Uint8Array.fromBase64(str):stringToBytes(atob(str))}typeof Promise.try!="function"&&(Promise.try=function(fn,...args){return new Promise(resolve2=>{resolve2(fn(...args))})});typeof Math.sumPrecise!="function"&&(Math.sumPrecise=function(numbers){return numbers.reduce((a,b)=>a+b,0)});const SVG_NS="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.
CSS/this.PDF}async function fetchData(url2,type2="text"){if(isValidFetchUrl(url2,document.baseURI)){const response=await fetch(url2);if(!response.ok)throw new Error(response.statusText);switch(type2){case"arraybuffer":return response.arrayBuffer();case"blob":return response.blob();case"json":return response.json()}return response.text()}return new Promise((resolve2,reject)=>{const request=new XMLHttpRequest;request.open("GET",url2,!0),request.responseType=type2,request.onreadystatechange=()=>{if(request.
readyState===XMLHttpRequest.DONE){if(request.status===200||request.status===0){switch(type2){case"arraybuffer":case"blob":case"json":resolve2(request.response);return}resolve2(request.responseText);return}reject(new Error(request.statusText))}},request.send(null)})}class PageViewport{constructor({viewBox,userUnit,scale:scale2,rotation,offsetX=0,offsetY=0,dontFlip=!1}){this.viewBox=viewBox,this.userUnit=userUnit,this.scale=scale2,this.rotation=rotation,this.offsetX=offsetX,this.offsetY=offsetY,scale2*=
userUnit;const centerX=(viewBox[2]+viewBox[0])/2,centerY=(viewBox[3]+viewBox[1])/2;let rotateA,rotateB,rotateC,rotateD;switch(rotation%=360,rotation<0&&(rotation+=360),rotation){case 180:rotateA=-1,rotateB=0,rotateC=0,rotateD=1;break;case 90:rotateA=0,rotateB=1,rotateC=1,rotateD=0;break;case 270:rotateA=0,rotateB=-1,rotateC=-1,rotateD=0;break;case 0:rotateA=1,rotateB=0,rotateC=0,rotateD=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}dontFlip&&
@ -6159,7 +6176,7 @@ $$props.onResourceClick?.(uri2)}var fragment=comment$2(),node2=first_child(fragm
return get$4(attachment)},onRemove:handleRemove,onClick:()=>handleResourceClick(get$4(attachment).resource.uri)})}}),append($$anchor3,fragment_1)},$$slots:{default:!0}}),reset(div),template_effect(()=>set_class(div,1,clsx($$props.class))),append($$anchor2,div)};if_block(node2,$$render=>{get$4(hasAttachments)&&$$render(consequent)})}append($$anchor,fragment),pop()}var root_3$S=from_html('<span class="text-xs text-muted-foreground"> </span>'),root_5$u=from_html('<div class="pointer-events-none abs\
olute right-0 bottom-0 left-0 h-6 bg-gradient-to-t from-muted to-transparent"></div>'),root_4$w=from_html('<div class="relative mt-2 w-full"><div class="overflow-hidden font-mono text-xs leading-relaxed break-words whitespace-pre-wrap text-muted-foreground"> </div> <!></div>'),root_2$10=from_html('<button type="button"><div class="flex items-start gap-3"><div class="flex min-w-0 flex-1 flex-col items-start text-left"><span class="w-full truncate text-sm font-medium text-foreground"> </span> <!> \
<!></div></div></button>'),root_8$n=from_html('<div class="pointer-events-none absolute right-0 bottom-0 left-0 h-4 bg-gradient-to-t from-muted to-transparent"></div>'),root_7$r=from_html('<div class="relative"><div class="overflow-hidden font-mono text-xs leading-relaxed break-words whitespace-pre-wrap text-muted-foreground" style="max-height: 3rem; line-height: 1.2em;"> </div> <!></div>'),root_6$x=from_html('<button><div class="absolute top-2 right-2 opacity-0 transition-opacity group-hover:op\
acity-100"><!></div> <div class="pr-8"><span class="mb-3 block truncate text-sm font-medium text-foreground"> </span> <!></div></button>'),root_10$h=from_html('<span class="text-left text-xs text-muted-foreground"> </span>'),root_12$8=from_html('<span class="text-left text-xs text-muted-foreground"> </span>'),root_13$c=from_html('<div class="absolute top-2 right-2 opacity-0 transition-opacity group-hover:opacity-100"><!></div>'),root_9$l=from_html('<button><div class="flex h-8 w-8 items-center j\
acity-100"><!></div> <div class="pr-8"><span class="mb-3 block truncate text-sm font-medium text-foreground"> </span> <!></div></button>'),root_10$h=from_html('<span class="text-left text-xs text-muted-foreground"> </span>'),root_12$8=from_html('<span class="text-left text-xs text-muted-foreground"> </span>'),root_13$c=from_html('<div class="absolute top-2 right-2 opacity-0 transition-opacity group-hover:opacity-100"><!></div>'),root_9$m=from_html('<button><div class="flex h-8 w-8 items-center j\
ustify-center rounded bg-primary/10 text-xs font-medium text-primary"> </div> <div class="flex flex-col gap-0.5"><span> </span> <!></div> <!></button>');function ChatAttachmentThumbnailFile($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),readonly2=prop($$props,"readonly",3,!1),isText=user_derived(()=>isTextFile($$props.attachment,$$props.uploadedFile)),fileTypeLabel=user_derived(()=>{if($$props.uploadedFile?.type)return getFileTypeLabel($$props.uploadedFile.type);if($$props.
attachment){if("mimeType"in $$props.attachment&&$$props.attachment.mimeType)return getFileTypeLabel($$props.attachment.mimeType);if($$props.attachment.type)return getFileTypeLabel($$props.attachment.type)}return getFileTypeLabel($$props.name)}),pdfProcessingMode=user_derived(()=>$$props.attachment?.type===AttachmentType.PDF?$$props.attachment.processedAsImages?"Sent as Image":"Sent as Text":null);var fragment=comment$2(),node2=first_child(fragment);{var consequent_6=$$anchor2=>{var fragment_1=comment$2(),
node_1=first_child(fragment_1);{var consequent_3=$$anchor3=>{var button=root_2$10();button.__click=function(...$$args){$$props.onClick?.apply(this,$$args)};var div=child(button),div_1=child(div),span=child(div_1),text2=child(span,!0);reset(span);var node_2=sibling(span,2);{var consequent=$$anchor4=>{var span_1=root_3$S(),text_1=child(span_1,!0);reset(span_1),template_effect($0=>set_text(text_1,$0),[()=>formatFileSize($$props.size)]),append($$anchor4,span_1)};if_block(node_2,$$render=>{$$props.size&&
@ -6167,7 +6184,7 @@ $$render(consequent)})}var node_3=sibling(node_2,2);{var consequent_2=$$anchor4=
textContent&&$$render(consequent_2)})}reset(div_1),reset(div),reset(button),template_effect(()=>{set_class(button,1,`cursor-pointer rounded-lg border border-border bg-muted p-3 transition-shadow hover:shadow-md ${className()??""} w-full max-w-2xl`),set_attribute(button,"aria-label",`Preview ${$$props.name}`),set_text(text2,$$props.name)}),append($$anchor3,button)},alternate=$$anchor3=>{var button_1=root_6$x();button_1.__click=function(...$$args){$$props.onClick?.apply(this,$$args)};var div_5=child(
button_1),node_5=child(div_5);ActionIconRemove(node_5,{get id(){return $$props.id},get onRemove(){return $$props.onRemove}}),reset(div_5);var div_6=sibling(div_5,2),span_2=child(div_6),text_3=child(span_2,!0);reset(span_2);var node_6=sibling(span_2,2);{var consequent_5=$$anchor4=>{var div_7=root_7$r(),div_8=child(div_7),text_4=child(div_8,!0);reset(div_8);var node_7=sibling(div_8,2);{var consequent_4=$$anchor5=>{var div_9=root_8$n();append($$anchor5,div_9)};if_block(node_7,$$render=>{$$props.textContent.
length>150&&$$render(consequent_4)})}reset(div_7),template_effect($0=>set_text(text_4,$0),[()=>getPreviewText($$props.textContent)]),append($$anchor4,div_7)};if_block(node_6,$$render=>{$$props.textContent&&$$render(consequent_5)})}reset(div_6),reset(button_1),template_effect(()=>{set_class(button_1,1,`group relative rounded-lg border border-border bg-muted p-3 ${className()??""} ${$$props.textContent?"max-h-24 max-w-72":"max-w-36"} cursor-pointer text-left`),set_text(text_3,$$props.name)}),append(
$$anchor3,button_1)};if_block(node_1,$$render=>{readonly2()?$$render(consequent_3):$$render(alternate,!1)})}append($$anchor2,fragment_1)},alternate_2=$$anchor2=>{var button_2=root_9$l();button_2.__click=function(...$$args){$$props.onClick?.apply(this,$$args)};var div_10=child(button_2),text_5=child(div_10,!0);reset(div_10);var div_11=sibling(div_10,2),span_3=child(div_11),text_6=child(span_3,!0);reset(span_3);var node_8=sibling(span_3,2);{var consequent_7=$$anchor3=>{var span_4=root_10$h(),text_7=child(
$$anchor3,button_1)};if_block(node_1,$$render=>{readonly2()?$$render(consequent_3):$$render(alternate,!1)})}append($$anchor2,fragment_1)},alternate_2=$$anchor2=>{var button_2=root_9$m();button_2.__click=function(...$$args){$$props.onClick?.apply(this,$$args)};var div_10=child(button_2),text_5=child(div_10,!0);reset(div_10);var div_11=sibling(div_10,2),span_3=child(div_11),text_6=child(span_3,!0);reset(span_3);var node_8=sibling(span_3,2);{var consequent_7=$$anchor3=>{var span_4=root_10$h(),text_7=child(
span_4,!0);reset(span_4),template_effect(()=>set_text(text_7,get$4(pdfProcessingMode))),append($$anchor3,span_4)},alternate_1=$$anchor3=>{var fragment_2=comment$2(),node_9=first_child(fragment_2);{var consequent_8=$$anchor4=>{var span_5=root_12$8(),text_8=child(span_5,!0);reset(span_5),template_effect($0=>set_text(text_8,$0),[()=>formatFileSize($$props.size)]),append($$anchor4,span_5)};if_block(node_9,$$render=>{$$props.size&&$$render(consequent_8)},!0)}append($$anchor3,fragment_2)};if_block(node_8,
$$render=>{get$4(pdfProcessingMode)?$$render(consequent_7):$$render(alternate_1,!1)})}reset(div_11);var node_10=sibling(div_11,2);{var consequent_9=$$anchor3=>{var div_12=root_13$c(),node_11=child(div_12);ActionIconRemove(node_11,{get id(){return $$props.id},get onRemove(){return $$props.onRemove}}),reset(div_12),append($$anchor3,div_12)};if_block(node_10,$$render=>{readonly2()||$$render(consequent_9)})}reset(button_2),template_effect(()=>{set_class(button_2,1,`group flex items-center gap-3 roun\
ded-lg border border-border bg-muted p-3 ${className()??""} relative`),set_text(text_5,get$4(fileTypeLabel)),set_class(span_3,1,`max-w-24 truncate text-sm font-medium text-foreground ${readonly2()?"":"group-hover:pr-6"} md:max-w-32`),set_text(text_6,$$props.name)}),append($$anchor2,button_2)};if_block(node2,$$render=>{get$4(isText)?$$render(consequent_6):$$render(alternate_2,!1)})}append($$anchor,fragment),pop()}delegate(["click"]);var root_1$T=from_html('<button type="button" class="block h-ful\
@ -6238,13 +6255,13 @@ $$props,"open",15,!1),uploadedFiles=prop($$props,"uploadedFiles",19,()=>[]),atta
Dialog_Content($$anchor6,{class:"flex !max-h-[90vh] !max-w-6xl flex-col",children:($$anchor7,$$slotProps3)=>{var fragment_3=root_3$L(),node_4=first_child(fragment_3);component(node_4,()=>Dialog_header,($$anchor8,Dialog_Header)=>{Dialog_Header($$anchor8,{children:($$anchor9,$$slotProps4)=>{var fragment_4=root_4$s(),node_5=first_child(fragment_4);component(node_5,()=>Dialog_title,($$anchor10,Dialog_Title)=>{Dialog_Title($$anchor10,{children:($$anchor11,$$slotProps5)=>{next$1();var text2=text$8();template_effect(
()=>set_text(text2,`All Attachments (${get$4(totalCount)??""})`)),append($$anchor11,text2)},$$slots:{default:!0}})});var node_6=sibling(node_5,2);component(node_6,()=>Dialog_description,($$anchor10,Dialog_Description)=>{Dialog_Description($$anchor10,{children:($$anchor11,$$slotProps5)=>{next$1();var text_1=text$8("View and manage all attached files");append($$anchor11,text_1)},$$slots:{default:!0}})}),append($$anchor9,fragment_4)},$$slots:{default:!0}})});var node_7=sibling(node_4,2);ChatAttachmentsViewAll(
node_7,{get uploadedFiles(){return uploadedFiles()},get attachments(){return attachments()},get readonly(){return readonly2()},get onFileRemove(){return $$props.onFileRemove},get imageHeight(){return imageHeight()},get imageWidth(){return imageWidth()},get imageClass(){return imageClass()},get activeModelId(){return $$props.activeModelId}}),append($$anchor7,fragment_3)},$$slots:{default:!0}})}),append($$anchor5,fragment_2)},$$slots:{default:!0}})}),append($$anchor3,fragment_1)},$$slots:{default:!0}})}),
append($$anchor,fragment),pop()}var root_4$r=from_html("<!> ",1),root_3$K=from_html("<!> <!>",1),root_9$k=from_html('<p><span class="font-medium">Context size:</span> </p>'),root_8$l=from_html('<div class="mt-2 space-y-1 text-xs opacity-80"><p><span class="font-medium">Prompt tokens:</span> </p> <!></div>'),root_2$U=from_html('<!> <div><p class="font-medium"> </p> <!></div> <!>',1);function DialogChatError($$anchor,$$props){push$1($$props,!0);let open2=prop($$props,"open",15);const isTimeout=user_derived(
append($$anchor,fragment),pop()}var root_4$r=from_html("<!> ",1),root_3$K=from_html("<!> <!>",1),root_9$l=from_html('<p><span class="font-medium">Context size:</span> </p>'),root_8$l=from_html('<div class="mt-2 space-y-1 text-xs opacity-80"><p><span class="font-medium">Prompt tokens:</span> </p> <!></div>'),root_2$U=from_html('<!> <div><p class="font-medium"> </p> <!></div> <!>',1);function DialogChatError($$anchor,$$props){push$1($$props,!0);let open2=prop($$props,"open",15);const isTimeout=user_derived(
()=>$$props.type===ErrorDialogType.TIMEOUT),title2=user_derived(()=>get$4(isTimeout)?"TCP Timeout":"Server Error"),description2=user_derived(()=>get$4(isTimeout)?"The request did not receive a response from the server before timing out.":"The server responded with an error message. Review the details below."),iconClass=user_derived(()=>get$4(isTimeout)?"text-destructive":"text-amber-500"),badgeClass=user_derived(()=>get$4(isTimeout)?"border-destructive/40 bg-destructive/10 text-destructive":"bor\
der-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400");function handleOpenChange(newOpen){open2(newOpen),$$props.onOpenChange?.(newOpen)}var fragment=comment$2(),node2=first_child(fragment);component(node2,()=>Root$3,($$anchor2,AlertDialog_Root)=>{AlertDialog_Root($$anchor2,{get open(){return open2()},onOpenChange:handleOpenChange,children:($$anchor3,$$slotProps)=>{var fragment_1=comment$2(),node_1=first_child(fragment_1);component(node_1,()=>Alert_dialog_content,($$anchor4,AlertDialog_Content)=>{
AlertDialog_Content($$anchor4,{children:($$anchor5,$$slotProps2)=>{var fragment_2=root_2$U(),node_2=first_child(fragment_2);component(node_2,()=>Alert_dialog_header,($$anchor6,AlertDialog_Header)=>{AlertDialog_Header($$anchor6,{children:($$anchor7,$$slotProps3)=>{var fragment_3=root_3$K(),node_3=first_child(fragment_3);component(node_3,()=>Alert_dialog_title,($$anchor8,AlertDialog_Title)=>{AlertDialog_Title($$anchor8,{class:"flex items-center gap-2",children:($$anchor9,$$slotProps4)=>{var fragment_4=root_4$r(),
node_4=first_child(fragment_4);{var consequent=$$anchor10=>{{let $0=user_derived(()=>`h-5 w-5 ${get$4(iconClass)}`);Timer_off($$anchor10,{get class(){return get$4($0)}})}},alternate=$$anchor10=>{{let $0=user_derived(()=>`h-5 w-5 ${get$4(iconClass)}`);Triangle_alert($$anchor10,{get class(){return get$4($0)}})}};if_block(node_4,$$render=>{get$4(isTimeout)?$$render(consequent):$$render(alternate,!1)})}var text2=sibling(node_4);template_effect(()=>set_text(text2,` ${get$4(title2)??""}`)),append($$anchor9,
fragment_4)},$$slots:{default:!0}})});var node_5=sibling(node_3,2);component(node_5,()=>Alert_dialog_description,($$anchor8,AlertDialog_Description)=>{AlertDialog_Description($$anchor8,{children:($$anchor9,$$slotProps4)=>{next$1();var text_1=text$8();template_effect(()=>set_text(text_1,get$4(description2))),append($$anchor9,text_1)},$$slots:{default:!0}})}),append($$anchor7,fragment_3)},$$slots:{default:!0}})});var div=sibling(node_2,2),p2=child(div),text_2=child(p2,!0);reset(p2);var node_6=sibling(
p2,2);{var consequent_2=$$anchor6=>{var div_1=root_8$l(),p_1=child(div_1),text_3=sibling(child(p_1));reset(p_1);var node_7=sibling(p_1,2);{var consequent_1=$$anchor7=>{var p_2=root_9$k(),text_4=sibling(child(p_2));reset(p_2),template_effect($0=>set_text(text_4,` ${$0??""}`),[()=>$$props.contextInfo.n_ctx.toLocaleString()]),append($$anchor7,p_2)};if_block(node_7,$$render=>{$$props.contextInfo.n_ctx&&$$render(consequent_1)})}reset(div_1),template_effect($0=>set_text(text_3,` ${$0??""}`),[()=>$$props.
p2,2);{var consequent_2=$$anchor6=>{var div_1=root_8$l(),p_1=child(div_1),text_3=sibling(child(p_1));reset(p_1);var node_7=sibling(p_1,2);{var consequent_1=$$anchor7=>{var p_2=root_9$l(),text_4=sibling(child(p_2));reset(p_2),template_effect($0=>set_text(text_4,` ${$0??""}`),[()=>$$props.contextInfo.n_ctx.toLocaleString()]),append($$anchor7,p_2)};if_block(node_7,$$render=>{$$props.contextInfo.n_ctx&&$$render(consequent_1)})}reset(div_1),template_effect($0=>set_text(text_3,` ${$0??""}`),[()=>$$props.
contextInfo.n_prompt_tokens.toLocaleString()]),append($$anchor6,div_1)};if_block(node_6,$$render=>{$$props.contextInfo&&$$render(consequent_2)})}reset(div);var node_8=sibling(div,2);component(node_8,()=>Alert_dialog_footer,($$anchor6,AlertDialog_Footer)=>{AlertDialog_Footer($$anchor6,{children:($$anchor7,$$slotProps3)=>{var fragment_8=comment$2(),node_9=first_child(fragment_8);component(node_9,()=>Alert_dialog_action,($$anchor8,AlertDialog_Action)=>{AlertDialog_Action($$anchor8,{onclick:()=>handleOpenChange(
!1),children:($$anchor9,$$slotProps4)=>{next$1();var text_5=text$8("Close");append($$anchor9,text_5)},$$slots:{default:!0}})}),append($$anchor7,fragment_8)},$$slots:{default:!0}})}),template_effect(()=>{set_class(div,1,`rounded-lg border px-4 py-3 text-sm ${get$4(badgeClass)}`),set_text(text_2,$$props.message)}),append($$anchor5,fragment_2)},$$slots:{default:!0}})}),append($$anchor3,fragment_1)},$$slots:{default:!0}})}),append($$anchor,fragment),pop()}var root_4$q=from_html("<!> Empty Files Dete\
cted",1),root_3$J=from_html("<!> <!>",1),root_6$v=from_html('<li class="font-mono text-sm"> </li>'),root_2$T=from_html('<!> <div class="space-y-3 text-sm"><div class="rounded-lg bg-muted p-3"><div class="mb-2 font-medium">Empty Files:</div> <ul class="list-inside list-disc space-y-1 text-muted-foreground"></ul></div> <div><div class="mb-2 font-medium">What happened:</div> <ul class="list-inside list-disc space-y-1 text-muted-foreground"><li>Empty files cannot be processed or sent to the AI model\
@ -6350,7 +6367,7 @@ a),URL.revokeObjectURL(url2)}async downloadConversation(convId){let conversation
importedData);toast.success(`Imported ${result.imported} conversation(s), skipped ${result.skipped}`),await this.loadConversations();const importedConversations=(Array.isArray(importedData)?importedData:[importedData]).map(item=>item.conv);resolve2(importedConversations)}catch(err){const message=err instanceof Error?err.message:"Unknown error";console.error("Failed to import conversations:",err),toast.error("Import failed",{description:message}),reject(new Error(`Import failed: ${message}`))}},input.
click()})}async importConversationsData(data){const result=await DatabaseService.importConversations(data);return await this.loadConversations(),result}}const conversationsStore=new ConversationsStore;conversationsStore.init();const conversations=()=>conversationsStore.conversations,activeConversation=()=>conversationsStore.activeConversation,activeMessages=()=>conversationsStore.activeMessages,isConversationsInitialized=()=>conversationsStore.isInitialized;function buildConversationTree(convs){
const childrenByParent=new SvelteMap,forkIds=new SvelteSet;for(const conv of convs)if(conv.forkedFromConversationId){forkIds.add(conv.id);const siblings2=childrenByParent.get(conv.forkedFromConversationId)||[];siblings2.push(conv),childrenByParent.set(conv.forkedFromConversationId,siblings2)}const result=[],visited=new SvelteSet;function walk(conv,depth){visited.add(conv.id),result.push({conversation:conv,depth});const children=childrenByParent.get(conv.id);if(children){children.sort((a,b)=>b.lastModified-
a.lastModified);for(const child2 of children)walk(child2,depth+1)}}const roots=convs.filter(c2=>!forkIds.has(c2.id));for(const root2 of roots)walk(root2,0);for(const conv of convs)visited.has(conv.id)||walk(conv,1);return result}var root_5$t=from_html('<span class="text-sm font-normal text-muted-foreground"> </span>'),root_4$n=from_html("<!> <span>MCP Resources</span> <!>",1),root_3$F=from_html("<!> <!>",1),root_8$k=from_html('<p class="mb-4 text-xs text-muted-foreground"> </p>'),root_9$j=from_html(
a.lastModified);for(const child2 of children)walk(child2,depth+1)}}const roots=convs.filter(c2=>!forkIds.has(c2.id));for(const root2 of roots)walk(root2,0);for(const conv of convs)visited.has(conv.id)||walk(conv,1);return result}var root_5$t=from_html('<span class="text-sm font-normal text-muted-foreground"> </span>'),root_4$n=from_html("<!> <span>MCP Resources</span> <!>",1),root_3$F=from_html("<!> <!>",1),root_8$k=from_html('<p class="mb-4 text-xs text-muted-foreground"> </p>'),root_9$k=from_html(
'<div class="flex flex-1 items-center justify-center"><!></div>'),root_11$b=from_html('<div class="flex flex-1 flex-col items-center justify-center gap-2 text-red-500"><span class="text-sm"> </span> <!></div>'),root_7$p=from_html('<div class="flex h-full flex-col"><div class="mb-3 flex items-center gap-2"><!> <span class="text-sm font-medium"> </span></div> <!> <div class="mb-4 rounded-md border border-border/50 bg-muted/30 px-3 py-2"><p class="font-mono text-xs break-all text-muted-foreground">\
</p></div> <!></div>'),root_19$2=from_html('<div class="flex flex-col gap-10"></div>'),root_22$6=from_html('<div class="flex h-full items-center justify-center text-sm text-muted-foreground">Select a resource to preview</div>'),root_26$4=from_html("<!> Attach Resource",1),root_30$2=from_html("<!> ",1),root_23$4=from_html("<!> <!>",1),root_2$P=from_html('<!> <div class="flex h-[500px] min-w-0"><div class="w-72 shrink-0 overflow-y-auto border-r border-border/30 p-4"><!></div> <div class="min-w-0 \
flex-1 overflow-auto p-4"><!></div></div> <!>',1);function DialogMcpResources($$anchor,$$props){push$1($$props,!0);let open2=prop($$props,"open",15,!1),selectedResources=new SvelteSet,lastSelectedUri=state$1(null),isAttaching=state$1(!1),selectedTemplate=state$1(null),templatePreviewUri=state$1(null),templatePreviewContent=state$1(null),templatePreviewLoading=state$1(!1),templatePreviewError=state$1(null);const totalCount=user_derived(mcpTotalResourceCount);user_effect(()=>{open2()&&(loadResources(),
@ -6368,7 +6385,7 @@ ow-hidden p-0",children:($$anchor5,$$slotProps2)=>{var fragment_2=root_2$P(),nod
node_4=first_child(fragment_4);Folder_open(node_4,{class:"h-5 w-5"});var node_5=sibling(node_4,4);{var consequent=$$anchor10=>{var span=root_5$t(),text2=child(span);reset(span),template_effect(()=>set_text(text2,`(${get$4(totalCount)??""})`)),append($$anchor10,span)};if_block(node_5,$$render=>{get$4(totalCount)>0&&$$render(consequent)})}append($$anchor9,fragment_4)},$$slots:{default:!0}})});var node_6=sibling(node_3,2);component(node_6,()=>Dialog_description,($$anchor8,Dialog_Description)=>{Dialog_Description(
$$anchor8,{children:($$anchor9,$$slotProps4)=>{next$1();var text_1=text$8("Browse and attach resources from connected MCP servers to your chat context.");append($$anchor9,text_1)},$$slots:{default:!0}})}),append($$anchor7,fragment_3)},$$slots:{default:!0}})});var div=sibling(node_2,2),div_1=child(div),node_7=child(div_1);McpResourceBrowser(node_7,{onSelect:handleResourceSelect,onToggle:handleResourceToggle,onTemplateSelect:handleTemplateSelect,get selectedUris(){return selectedResources},get selectedTemplateUri(){
return get$4(selectedTemplateUri)},get expandToUri(){return $$props.preSelectedUri}}),reset(div_1);var div_2=sibling(div_1,2),node_8=child(div_2);{var consequent_4=$$anchor6=>{var div_3=root_7$p(),div_4=child(div_3),node_9=child(div_4);Braces(node_9,{class:"h-4 w-4 text-muted-foreground"});var span_1=sibling(node_9,2),text_2=child(span_1,!0);reset(span_1),reset(div_4);var node_10=sibling(div_4,2);{var consequent_1=$$anchor7=>{var p2=root_8$k(),text_3=child(p2,!0);reset(p2),template_effect(()=>set_text(
text_3,get$4(selectedTemplate).description)),append($$anchor7,p2)};if_block(node_10,$$render=>{get$4(selectedTemplate).description&&$$render(consequent_1)})}var div_5=sibling(node_10,2),p_1=child(div_5),text_4=child(p_1,!0);reset(p_1),reset(div_5);var node_11=sibling(div_5,2);{var consequent_2=$$anchor7=>{var div_6=root_9$j(),node_12=child(div_6);Loader_circle(node_12,{class:"h-6 w-6 animate-spin text-muted-foreground"}),reset(div_6),append($$anchor7,div_6)},alternate_1=$$anchor7=>{var fragment_5=comment$2(),
text_3,get$4(selectedTemplate).description)),append($$anchor7,p2)};if_block(node_10,$$render=>{get$4(selectedTemplate).description&&$$render(consequent_1)})}var div_5=sibling(node_10,2),p_1=child(div_5),text_4=child(p_1,!0);reset(p_1),reset(div_5);var node_11=sibling(div_5,2);{var consequent_2=$$anchor7=>{var div_6=root_9$k(),node_12=child(div_6);Loader_circle(node_12,{class:"h-6 w-6 animate-spin text-muted-foreground"}),reset(div_6),append($$anchor7,div_6)},alternate_1=$$anchor7=>{var fragment_5=comment$2(),
node_13=first_child(fragment_5);{var consequent_3=$$anchor8=>{var div_7=root_11$b(),span_2=child(div_7),text_5=child(span_2,!0);reset(span_2);var node_14=sibling(span_2,2);Button(node_14,{size:"sm",variant:"outline",onclick:()=>{set$1(templatePreviewError,null)},children:($$anchor9,$$slotProps3)=>{next$1();var text_6=text$8("Try again");append($$anchor9,text_6)},$$slots:{default:!0}}),reset(div_7),template_effect(()=>set_text(text_5,get$4(templatePreviewError))),append($$anchor8,div_7)},alternate=$$anchor8=>{
McpResourceTemplateForm($$anchor8,{get template(){return get$4(selectedTemplate)},onResolve:handleTemplateResolve,onCancel:handleTemplateCancelForm})};if_block(node_13,$$render=>{get$4(templatePreviewError)?$$render(consequent_3):$$render(alternate,!1)},!0)}append($$anchor7,fragment_5)};if_block(node_11,$$render=>{get$4(templatePreviewLoading)?$$render(consequent_2):$$render(alternate_1,!1)})}reset(div_3),template_effect(()=>{set_text(text_2,get$4(selectedTemplate).title||get$4(selectedTemplate).
name),set_text(text_4,get$4(selectedTemplate).uriTemplate)}),append($$anchor6,div_3)},alternate_5=$$anchor6=>{var fragment_7=comment$2(),node_15=first_child(fragment_7);{var consequent_5=$$anchor7=>{{let $0=user_derived(()=>({uri:get$4(templatePreviewUri)??"",name:get$4(templatePreviewUri)?.split("/").pop()||(get$4(templatePreviewUri)??""),serverName:get$4(selectedTemplate)?.serverName||""}));McpResourcePreview($$anchor7,{get resource(){return get$4($0)},get preloadedContent(){return get$4(templatePreviewContent)}})}},
@ -6542,7 +6559,7 @@ ize-4 [&_svg:not([class*='text-'])]:text-muted-foreground",$$props.class));compo
()=>$$props.children??noop$3);var node_2=sibling(node_1,2);Chevron_right(node_2,{class:"ml-auto size-4"}),append($$anchor3,fragment_1)},$$slots:{default:!0}}))})}append($$anchor,fragment),pop()}const Sub=Menu_sub,Root$2=Menu;function Switch($$anchor,$$props){push$1($$props,!0);let ref2=prop($$props,"ref",15,null),checked=prop($$props,"checked",15,!1),restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","class","checked"]);var fragment=comment$2(),node2=first_child(fragment);{let $0=user_derived(
()=>cn$1("peer inline-flex h-[1.15rem] w-8 shrink-0 cursor-pointer items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80",$$props.class));component(node2,()=>Switch$1,($$anchor2,SwitchPrimitive_Root)=>{SwitchPrimitive_Root($$anchor2,spread_props(
{"data-slot":"switch",get class(){return get$4($0)}},()=>restProps,{get ref(){return ref2()},set ref($$value){ref2($$value)},get checked(){return checked()},set checked($$value){checked($$value)},children:($$anchor3,$$slotProps)=>{var fragment_1=comment$2(),node_1=first_child(fragment_1);{let $02=user_derived(()=>cn$1("pointer-events-none block size-4 rounded-full bg-background ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0 dark\
:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground"));component(node_1,()=>Switch_thumb,($$anchor4,SwitchPrimitive_Thumb)=>{SwitchPrimitive_Thumb($$anchor4,{"data-slot":"switch-thumb",get class(){return get$4($02)}})})}append($$anchor3,fragment_1)},$$slots:{default:!0}}))})}append($$anchor,fragment),pop()}var root_5$r=from_html('<span class="sr-only"></span> <!>',1),root_6$r=from_html("<p></p>"),root_3$D=from_html("<!> <!>",1),root_9$i=from_html("<!> <span>Imag\
:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground"));component(node_1,()=>Switch_thumb,($$anchor4,SwitchPrimitive_Thumb)=>{SwitchPrimitive_Thumb($$anchor4,{"data-slot":"switch-thumb",get class(){return get$4($02)}})})}append($$anchor3,fragment_1)},$$slots:{default:!0}}))})}append($$anchor,fragment),pop()}var root_5$r=from_html('<span class="sr-only"></span> <!>',1),root_6$r=from_html("<p></p>"),root_3$D=from_html("<!> <!>",1),root_9$j=from_html("<!> <span>Imag\
es</span>",1),root_13$b=from_html("<!> <span>Images</span>",1),root_14$6=from_html("<p>Image processing requires a vision model</p>"),root_11$a=from_html("<!> <!>",1),root_16$6=from_html("<!> <span>Audio Files</span>",1),root_20$8=from_html("<!> <span>Audio Files</span>",1),root_21$4=from_html("<p>Audio files processing requires an audio model</p>"),root_18$4=from_html("<!> <!>",1),root_22$5=from_html("<!> <span>Text Files</span>",1),root_24$1=from_html("<!> <span>PDF Files</span>",1),root_28$2=from_html(
"<!> <span>PDF Files</span>",1),root_29$1=from_html("<p>PDFs will be converted to text. Image-based PDFs may not work properly.</p>"),root_26$3=from_html("<!> <!>",1),root_32=from_html("<!> <span>System Message</span>",1),root_33$1=from_html("<p> </p>"),root_30$1=from_html("<!> <!>",1),root_35=from_html("<!> <span>MCP Servers</span>",1),root_38=from_html("<!> <span>Manage MCP Servers</span>",1),root_41=from_html('<img alt="" class="h-4 w-4 shrink-0 rounded-sm"/>'),root_42=from_html('<span class=\
"shrink-0 rounded bg-destructive/15 px-1.5 py-0.5 text-xs text-destructive">Error</span>'),root_40=from_html('<button type="button" class="flex w-full items-center justify-between gap-2 rounded-sm px-2 py-2 text-left transition-colors hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"><div class="flex min-w-0 flex-1 items-center gap-2"><!> <span class="truncate text-sm"> </span> <!></div> <!></button>'),root_39=from_html('<div class="max-h-64 overflow-y-auto"></div>'),root_34=from_html(
@ -6554,7 +6571,7 @@ var div=root$1c(),node2=child(div);component(node2,()=>Root$2,($$anchor2,Dropdow
var fragment_1=comment$2(),node_2=first_child(fragment_1);component(node_2,()=>Root$5,($$anchor6,Tooltip_Root)=>{Tooltip_Root($$anchor6,{children:($$anchor7,$$slotProps3)=>{var fragment_2=root_3$D(),node_3=first_child(fragment_2);component(node_3,()=>Tooltip_trigger,($$anchor8,Tooltip_Trigger)=>{Tooltip_Trigger($$anchor8,{class:"w-full",children:($$anchor9,$$slotProps4)=>{Button($$anchor9,{class:"file-upload-button h-8 w-8 rounded-full p-0",get disabled(){return disabled()},variant:"secondary",type:"\
button",children:($$anchor10,$$slotProps5)=>{var fragment_4=root_5$r(),span=first_child(fragment_4);span.textContent="Add files, system prompt or MCP Servers";var node_4=sibling(span,2);Plus(node_4,{class:"h-4 w-4"}),append($$anchor10,fragment_4)},$$slots:{default:!0}})},$$slots:{default:!0}})});var node_5=sibling(node_3,2);component(node_5,()=>Tooltip_content,($$anchor8,Tooltip_Content)=>{Tooltip_Content($$anchor8,{children:($$anchor9,$$slotProps4)=>{var p2=root_6$r();p2.textContent="Add files,\
system prompt or MCP Servers",append($$anchor9,p2)},$$slots:{default:!0}})}),append($$anchor7,fragment_2)},$$slots:{default:!0}})}),append($$anchor5,fragment_1)},$$slots:{default:!0}})});var node_6=sibling(node_1,2);component(node_6,()=>Dropdown_menu_content,($$anchor4,DropdownMenu_Content)=>{DropdownMenu_Content($$anchor4,{align:"start",class:"w-48",children:($$anchor5,$$slotProps2)=>{var fragment_5=root_7$n(),node_7=first_child(fragment_5);{var consequent=$$anchor6=>{var fragment_6=comment$2(),
node_8=first_child(fragment_6);component(node_8,()=>Dropdown_menu_item,($$anchor7,DropdownMenu_Item)=>{DropdownMenu_Item($$anchor7,{class:"images-button flex cursor-pointer items-center gap-2",onclick:()=>$$props.onFileUpload?.(),children:($$anchor8,$$slotProps3)=>{var fragment_7=root_9$i(),node_9=first_child(fragment_7);component(node_9,()=>FILE_TYPE_ICONS.image,($$anchor9,FILE_TYPE_ICONS_image)=>{FILE_TYPE_ICONS_image($$anchor9,{class:"h-4 w-4"})}),next$1(2),append($$anchor8,fragment_7)},$$slots:{
node_8=first_child(fragment_6);component(node_8,()=>Dropdown_menu_item,($$anchor7,DropdownMenu_Item)=>{DropdownMenu_Item($$anchor7,{class:"images-button flex cursor-pointer items-center gap-2",onclick:()=>$$props.onFileUpload?.(),children:($$anchor8,$$slotProps3)=>{var fragment_7=root_9$j(),node_9=first_child(fragment_7);component(node_9,()=>FILE_TYPE_ICONS.image,($$anchor9,FILE_TYPE_ICONS_image)=>{FILE_TYPE_ICONS_image($$anchor9,{class:"h-4 w-4"})}),next$1(2),append($$anchor8,fragment_7)},$$slots:{
default:!0}})}),append($$anchor6,fragment_6)},alternate=$$anchor6=>{var fragment_8=comment$2(),node_10=first_child(fragment_8);component(node_10,()=>Root$5,($$anchor7,Tooltip_Root_1)=>{Tooltip_Root_1($$anchor7,{get delayDuration(){return TOOLTIP_DELAY_DURATION},children:($$anchor8,$$slotProps3)=>{var fragment_9=root_11$a(),node_11=first_child(fragment_9);component(node_11,()=>Tooltip_trigger,($$anchor9,Tooltip_Trigger_1)=>{Tooltip_Trigger_1($$anchor9,{class:"w-full",children:($$anchor10,$$slotProps4)=>{
var fragment_10=comment$2(),node_12=first_child(fragment_10);component(node_12,()=>Dropdown_menu_item,($$anchor11,DropdownMenu_Item_1)=>{DropdownMenu_Item_1($$anchor11,{class:"images-button flex cursor-pointer items-center gap-2",disabled:!0,children:($$anchor12,$$slotProps5)=>{var fragment_11=root_13$b(),node_13=first_child(fragment_11);component(node_13,()=>FILE_TYPE_ICONS.image,($$anchor13,FILE_TYPE_ICONS_image_1)=>{FILE_TYPE_ICONS_image_1($$anchor13,{class:"h-4 w-4"})}),next$1(2),append($$anchor12,
fragment_11)},$$slots:{default:!0}})}),append($$anchor10,fragment_10)},$$slots:{default:!0}})});var node_14=sibling(node_11,2);component(node_14,()=>Tooltip_content,($$anchor9,Tooltip_Content_1)=>{Tooltip_Content_1($$anchor9,{side:"right",children:($$anchor10,$$slotProps4)=>{var p_1=root_14$6();append($$anchor10,p_1)},$$slots:{default:!0}})}),append($$anchor8,fragment_9)},$$slots:{default:!0}})}),append($$anchor6,fragment_8)};if_block(node_7,$$render=>{hasVisionModality()?$$render(consequent):$$render(
@ -6590,7 +6607,7 @@ abled:pointer-events-none",children:($$anchor7,$$slotProps3)=>{var fragment_3=ro
$$props,["$$slots","$$events","$$legacy","ref","class","children"]);var div=root$1b();attribute_effect(div,$0=>({"data-slot":"sheet-header",class:$0,...restProps}),[()=>cn$1("flex flex-col gap-1.5 p-4",$$props.class)]);var node2=child(div);snippet(node2,()=>$$props.children??noop$3),reset(div),bind_this(div,$$value=>ref2($$value),()=>ref2()),append($$anchor,div),pop()}function Sheet_title($$anchor,$$props){push$1($$props,!0);let ref2=prop($$props,"ref",15,null),restProps=rest_props($$props,["$$s\
lots","$$events","$$legacy","ref","class"]);var fragment=comment$2(),node2=first_child(fragment);{let $0=user_derived(()=>cn$1("font-semibold text-foreground",$$props.class));component(node2,()=>Dialog_title$1,($$anchor2,SheetPrimitive_Title)=>{SheetPrimitive_Title($$anchor2,spread_props({"data-slot":"sheet-title",get class(){return get$4($0)}},()=>restProps,{get ref(){return ref2()},set ref($$value){ref2($$value)}}))})}append($$anchor,fragment),pop()}function Sheet_description($$anchor,$$props){
push$1($$props,!0);let ref2=prop($$props,"ref",15,null),restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","class"]);var fragment=comment$2(),node2=first_child(fragment);{let $0=user_derived(()=>cn$1("text-sm text-muted-foreground",$$props.class));component(node2,()=>Dialog_description$1,($$anchor2,SheetPrimitive_Description)=>{SheetPrimitive_Description($$anchor2,spread_props({"data-slot":"sheet-description",get class(){return get$4($0)}},()=>restProps,{get ref(){return ref2()},
set ref($$value){ref2($$value)}}))})}append($$anchor,fragment),pop()}const Root$1=Dialog;var root_2$M=from_html('<span class="sr-only"></span> <!>',1),root_4$m=from_html("<!> <!>",1),root_7$m=from_html('<span class="ml-auto text-xs text-muted-foreground">Requires vision model</span>'),root_8$i=from_html('<span class="ml-auto text-xs text-muted-foreground">Requires audio model</span>'),root_9$h=from_html('<span class="ml-auto text-xs text-muted-foreground">Text-only</span>'),root_10$e=from_html('\
set ref($$value){ref2($$value)}}))})}append($$anchor,fragment),pop()}const Root$1=Dialog;var root_2$M=from_html('<span class="sr-only"></span> <!>',1),root_4$m=from_html("<!> <!>",1),root_7$m=from_html('<span class="ml-auto text-xs text-muted-foreground">Requires vision model</span>'),root_8$i=from_html('<span class="ml-auto text-xs text-muted-foreground">Requires audio model</span>'),root_9$i=from_html('<span class="ml-auto text-xs text-muted-foreground">Text-only</span>'),root_10$e=from_html('\
<button type="button"><!> <span>MCP Prompt</span></button>'),root_11$9=from_html('<button type="button"><!> <span>MCP Resources</span></button>'),root_3$B=from_html('<!> <div class="flex flex-col gap-1 overflow-y-auto px-1.5 pb-2"><button type="button"><!> <span>Images</span> <!></button> <button type="button"><!> <span>Audio Files</span> <!></button> <button type="button"><!> <span>Text Files</span></button> <button type="button"><!> <span>PDF Files</span> <!></button> <button type="button"><!>\
<span>System Message</span></button> <button type="button"><!> <span>MCP Servers</span></button> <!> <!></div>',1),root_1$M=from_html("<!> <!>",1),root$1a=from_html("<div><!></div>");function ChatFormActionAttachmentsSheet($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),disabled=prop($$props,"disabled",3,!1),hasAudioModality=prop($$props,"hasAudioModality",3,!1),hasVisionModality=prop($$props,"hasVisionModality",3,!1),hasMcpPromptsSupport=prop($$props,"hasMcpPrompt\
sSupport",3,!1),hasMcpResourcesSupport=prop($$props,"hasMcpResourcesSupport",3,!1),sheetOpen=state$1(!1);function handleMcpPromptClick(){set$1(sheetOpen,!1),$$props.onMcpPromptClick?.()}function handleMcpSettingsClick(){$$props.onMcpSettingsClick?.()}function handleMcpResourcesClick(){set$1(sheetOpen,!1),$$props.onMcpResourcesClick?.()}function handleSheetFileUpload(){set$1(sheetOpen,!1),$$props.onFileUpload?.()}function handleSheetSystemPromptClick(){set$1(sheetOpen,!1),$$props.onSystemPromptClick?.()}
@ -6600,7 +6617,7 @@ $$anchor4,{side:"bottom",class:"max-h-[85vh] gap-0",children:($$anchor5,$$slotPr
$$slots:{default:!0}})});var node_6=sibling(node_5,2);component(node_6,()=>Sheet_description,($$anchor8,Sheet_Description)=>{Sheet_Description($$anchor8,{class:"sr-only",children:($$anchor9,$$slotProps4)=>{next$1();var text_1=text$8("Add files, system prompt or configure MCP servers");append($$anchor9,text_1)},$$slots:{default:!0}})}),append($$anchor7,fragment_3)},$$slots:{default:!0}})});var div_1=sibling(node_4,2),button=child(div_1);set_class(button,1,clsx(sheetItemClass)),button.__click=handleSheetFileUpload;
var node_7=child(button);component(node_7,()=>FILE_TYPE_ICONS.image,($$anchor6,FILE_TYPE_ICONS_image)=>{FILE_TYPE_ICONS_image($$anchor6,{class:"h-4 w-4 shrink-0"})});var node_8=sibling(node_7,4);{var consequent=$$anchor6=>{var span_1=root_7$m();append($$anchor6,span_1)};if_block(node_8,$$render=>{hasVisionModality()||$$render(consequent)})}reset(button);var button_1=sibling(button,2);set_class(button_1,1,clsx(sheetItemClass)),button_1.__click=handleSheetFileUpload;var node_9=child(button_1);component(
node_9,()=>FILE_TYPE_ICONS.audio,($$anchor6,FILE_TYPE_ICONS_audio)=>{FILE_TYPE_ICONS_audio($$anchor6,{class:"h-4 w-4 shrink-0"})});var node_10=sibling(node_9,4);{var consequent_1=$$anchor6=>{var span_2=root_8$i();append($$anchor6,span_2)};if_block(node_10,$$render=>{hasAudioModality()||$$render(consequent_1)})}reset(button_1);var button_2=sibling(button_1,2);set_class(button_2,1,clsx(sheetItemClass)),button_2.__click=handleSheetFileUpload;var node_11=child(button_2);component(node_11,()=>FILE_TYPE_ICONS.
text,($$anchor6,FILE_TYPE_ICONS_text)=>{FILE_TYPE_ICONS_text($$anchor6,{class:"h-4 w-4 shrink-0"})}),next$1(2),reset(button_2);var button_3=sibling(button_2,2);set_class(button_3,1,clsx(sheetItemClass)),button_3.__click=handleSheetFileUpload;var node_12=child(button_3);component(node_12,()=>FILE_TYPE_ICONS.pdf,($$anchor6,FILE_TYPE_ICONS_pdf)=>{FILE_TYPE_ICONS_pdf($$anchor6,{class:"h-4 w-4 shrink-0"})});var node_13=sibling(node_12,4);{var consequent_2=$$anchor6=>{var span_3=root_9$h();append($$anchor6,
text,($$anchor6,FILE_TYPE_ICONS_text)=>{FILE_TYPE_ICONS_text($$anchor6,{class:"h-4 w-4 shrink-0"})}),next$1(2),reset(button_2);var button_3=sibling(button_2,2);set_class(button_3,1,clsx(sheetItemClass)),button_3.__click=handleSheetFileUpload;var node_12=child(button_3);component(node_12,()=>FILE_TYPE_ICONS.pdf,($$anchor6,FILE_TYPE_ICONS_pdf)=>{FILE_TYPE_ICONS_pdf($$anchor6,{class:"h-4 w-4 shrink-0"})});var node_13=sibling(node_12,4);{var consequent_2=$$anchor6=>{var span_3=root_9$i();append($$anchor6,
span_3)};if_block(node_13,$$render=>{hasVisionModality()||$$render(consequent_2)})}reset(button_3);var button_4=sibling(button_3,2);set_class(button_4,1,clsx(sheetItemClass)),button_4.__click=handleSheetSystemPromptClick;var node_14=child(button_4);Message_square(node_14,{class:"h-4 w-4 shrink-0"}),next$1(2),reset(button_4);var button_5=sibling(button_4,2);set_class(button_5,1,clsx(sheetItemClass)),button_5.__click=handleMcpSettingsClick;var node_15=child(button_5);McpLogo(node_15,{class:"h-4 w-\
4 shrink-0"}),next$1(2),reset(button_5);var node_16=sibling(button_5,2);{var consequent_3=$$anchor6=>{var button_6=root_10$e();set_class(button_6,1,clsx(sheetItemClass)),button_6.__click=handleMcpPromptClick;var node_17=child(button_6);Zap(node_17,{class:"h-4 w-4 shrink-0"}),next$1(2),reset(button_6),append($$anchor6,button_6)};if_block(node_16,$$render=>{hasMcpPromptsSupport()&&$$render(consequent_3)})}var node_18=sibling(node_16,2);{var consequent_4=$$anchor6=>{var button_7=root_11$9();set_class(
button_7,1,clsx(sheetItemClass)),button_7.__click=handleMcpResourcesClick;var node_19=child(button_7);Folder_open(node_19,{class:"h-4 w-4 shrink-0"}),next$1(2),reset(button_7),append($$anchor6,button_7)};if_block(node_18,$$render=>{hasMcpResourcesSupport()&&$$render(consequent_4)})}reset(div_1),template_effect(()=>{button.disabled=!hasVisionModality(),button_1.disabled=!hasAudioModality()}),append($$anchor5,fragment_2)},$$slots:{default:!0}})}),append($$anchor3,fragment)},$$slots:{default:!0}})}),
@ -6751,14 +6768,14 @@ return className()},get deletionInfo(){return get$4(deletionInfo)},get message()
get showDeleteDialog(){return get$4(showDeleteDialog)},get siblingInfo(){return siblingInfo()}})},alternate_1=$$anchor3=>{var fragment_4=comment$2(),node_2=first_child(fragment_4);{var consequent_2=$$anchor4=>{ChatMessageUser($$anchor4,{get class(){return className()},get deletionInfo(){return get$4(deletionInfo)},get message(){return $$props.message},onConfirmDelete:handleConfirmDelete,onCopy:handleCopy,onDelete:handleDelete2,onEdit:handleEdit,onForkConversation:handleForkConversation,onNavigateToSibling:handleNavigateToSibling,
onShowDeleteDialogChange:handleShowDeleteDialogChange,get showDeleteDialog(){return get$4(showDeleteDialog)},get siblingInfo(){return siblingInfo()}})},alternate=$$anchor4=>{ChatMessageAssistant($$anchor4,{get class(){return className()},get deletionInfo(){return get$4(deletionInfo)},get isLastAssistantMessage(){return isLastAssistantMessage()},get message(){return $$props.message},get toolMessages(){return toolMessages()},get messageContent(){return $$props.message.content},onConfirmDelete:handleConfirmDelete,
onContinue:handleContinue,onCopy:handleCopy,onDelete:handleDelete2,onEdit:handleEdit,onForkConversation:handleForkConversation,onNavigateToSibling:handleNavigateToSibling,onRegenerate:handleRegenerate,onShowDeleteDialogChange:handleShowDeleteDialogChange,get showDeleteDialog(){return get$4(showDeleteDialog)},get siblingInfo(){return siblingInfo()},get textareaElement(){return get$4(textareaElement)},set textareaElement($$value){set$1(textareaElement,$$value,!0)}})};if_block(node_2,$$render=>{$$props.
message.role===MessageRole.USER?$$render(consequent_2):$$render(alternate,!1)},!0)}append($$anchor3,fragment_4)};if_block(node_1,$$render=>{get$4(mcpPromptExtra)?$$render(consequent_1):$$render(alternate_1,!1)},!0)}append($$anchor2,fragment_2)};if_block(node2,$$render=>{$$props.message.role===MessageRole.SYSTEM?$$render(consequent):$$render(alternate_2,!1)})}append($$anchor,fragment),pop()}var root_2$D=from_html('<div class="agentic-text svelte-1uhcmx5"><!></div>'),root_9$g=from_html('<div class\
message.role===MessageRole.USER?$$render(consequent_2):$$render(alternate,!1)},!0)}append($$anchor3,fragment_4)};if_block(node_1,$$render=>{get$4(mcpPromptExtra)?$$render(consequent_1):$$render(alternate_1,!1)},!0)}append($$anchor2,fragment_2)};if_block(node2,$$render=>{$$props.message.role===MessageRole.SYSTEM?$$render(consequent):$$render(alternate_2,!1)})}append($$anchor,fragment),pop()}var root_2$D=from_html('<div class="agentic-text svelte-1uhcmx5"><!></div>'),root_9$h=from_html('<div class\
="rounded bg-muted/30 p-2 text-xs text-muted-foreground italic">Receiving arguments...</div>'),root_10$c=from_html('<div class="rounded bg-yellow-500/10 p-2 text-xs text-yellow-600 italic dark:text-yellow-400">Response was truncated</div>'),root_5$o=from_html('<div class="pt-3"><div class="my-3 flex items-center gap-2 text-xs text-muted-foreground"><span>Arguments:</span> <!></div> <!></div>'),root_14$5=from_html('<div class="pt-3"><div class="my-3 text-xs text-muted-foreground">Arguments:</div>\
<!></div>'),root_18$3=from_html('<img class="mt-2 mb-2 h-auto max-w-full rounded-lg" loading="lazy"/>'),root_17$4=from_html('<div class="font-mono text-xs leading-relaxed whitespace-pre-wrap"> </div> <!>',1),root_16$5=from_html('<div class="overflow-auto rounded-lg border border-border bg-muted p-4"></div>'),root_20$7=from_html('<div class="rounded bg-muted/30 p-2 text-xs text-muted-foreground italic">Waiting for result...</div>'),root_13$a=from_html('<!> <div class="pt-3"><div class="my-3 flex\
items-center gap-2 text-xs text-muted-foreground"><span>Result:</span> <!></div> <!></div>',1),root_23$3=from_html('<div class="pt-3"><div class="text-xs leading-relaxed break-words whitespace-pre-wrap"> </div></div>'),root_26$2=from_html('<div class="pt-3"><div class="text-xs leading-relaxed break-words whitespace-pre-wrap"> </div></div>'),root_30=from_html('<div class="turn-stats svelte-1uhcmx5"><!></div>'),root_28$1=from_html('<div class="agentic-turn my-2 hover:bg-muted/80 dark:hover:bg-mut\
ed/30 svelte-1uhcmx5"><span class="agentic-turn-label svelte-1uhcmx5"></span> <!> <!></div>'),root$$=from_html('<div class="agentic-content svelte-1uhcmx5"><!></div>');function ChatMessageAgenticContent($$anchor,$$props){push$1($$props,!0);const renderSection=($$anchor2,section=noop$3,index2=noop$3)=>{var fragment=comment$2(),node2=first_child(fragment);{var consequent=$$anchor3=>{var div=root_2$D(),node_1=child(div);{let $0=user_derived(()=>$$props.message?.extra);MarkdownContent(node_1,{get content(){
return section().content},get attachments(){return get$4($0)}})}reset(div),append($$anchor3,div)},alternate_6=$$anchor3=>{var fragment_1=comment$2(),node_2=first_child(fragment_1);{var consequent_4=$$anchor4=>{const streamingIcon=user_derived(()=>(isStreaming(),Loader_circle)),streamingIconClass=user_derived(()=>isStreaming()?"h-4 w-4 animate-spin":"h-4 w-4");{let $0=user_derived(()=>isExpanded(index2(),section())),$1=user_derived(()=>section().toolName||"Tool call"),$2=user_derived(()=>isStreaming()?
"":"incomplete");CollapsibleContentBlock($$anchor4,{get open(){return get$4($0)},class:"my-2",get icon(){return get$4(streamingIcon)},get iconClass(){return get$4(streamingIconClass)},get title(){return get$4($1)},get subtitle(){return get$4($2)},get isStreaming(){return isStreaming()},onToggle:()=>toggleExpanded(index2(),section()),children:($$anchor5,$$slotProps)=>{var div_1=root_5$o(),div_2=child(div_1),node_3=sibling(child(div_2),2);{var consequent_1=$$anchor6=>{Loader_circle($$anchor6,{class:"\
h-3 w-3 animate-spin"})};if_block(node_3,$$render=>{isStreaming()&&$$render(consequent_1)})}reset(div_2);var node_4=sibling(div_2,2);{var consequent_2=$$anchor6=>{{let $02=user_derived(()=>formatJsonPretty(section().toolArgs));SyntaxHighlightedCode($$anchor6,{get code(){return get$4($02)},get language(){return FileTypeText.JSON},maxHeight:"20rem",class:"text-xs"})}},alternate_1=$$anchor6=>{var fragment_5=comment$2(),node_5=first_child(fragment_5);{var consequent_3=$$anchor7=>{var div_3=root_9$g();
h-3 w-3 animate-spin"})};if_block(node_3,$$render=>{isStreaming()&&$$render(consequent_1)})}reset(div_2);var node_4=sibling(div_2,2);{var consequent_2=$$anchor6=>{{let $02=user_derived(()=>formatJsonPretty(section().toolArgs));SyntaxHighlightedCode($$anchor6,{get code(){return get$4($02)},get language(){return FileTypeText.JSON},maxHeight:"20rem",class:"text-xs"})}},alternate_1=$$anchor6=>{var fragment_5=comment$2(),node_5=first_child(fragment_5);{var consequent_3=$$anchor7=>{var div_3=root_9$h();
append($$anchor7,div_3)},alternate=$$anchor7=>{var div_4=root_10$c();append($$anchor7,div_4)};if_block(node_5,$$render=>{isStreaming()?$$render(consequent_3):$$render(alternate,!1)},!0)}append($$anchor6,fragment_5)};if_block(node_4,$$render=>{section().toolArgs?$$render(consequent_2):$$render(alternate_1,!1)})}reset(div_1),append($$anchor5,div_1)},$$slots:{default:!0}})}},alternate_5=$$anchor4=>{var fragment_6=comment$2(),node_6=first_child(fragment_6);{var consequent_10=$$anchor5=>{const isPending=user_derived(
()=>section().type===AgenticSectionType.TOOL_CALL_PENDING),toolIcon=user_derived(()=>get$4(isPending)?Loader_circle:Wrench),toolIconClass=user_derived(()=>get$4(isPending)?"h-4 w-4 animate-spin":"h-4 w-4");{let $0=user_derived(()=>isExpanded(index2(),section())),$1=user_derived(()=>section().toolName||""),$2=user_derived(()=>get$4(isPending)?"executing...":void 0);CollapsibleContentBlock($$anchor5,{get open(){return get$4($0)},class:"my-2",get icon(){return get$4(toolIcon)},get iconClass(){return get$4(
toolIconClass)},get title(){return get$4($1)},get subtitle(){return get$4($2)},get isStreaming(){return get$4(isPending)},onToggle:()=>toggleExpanded(index2(),section()),children:($$anchor6,$$slotProps)=>{var fragment_8=root_13$a(),node_7=first_child(fragment_8);{var consequent_5=$$anchor7=>{var div_5=root_14$5(),node_8=sibling(child(div_5),2);{let $02=user_derived(()=>formatJsonPretty(section().toolArgs));SyntaxHighlightedCode(node_8,{get code(){return get$4($02)},get language(){return FileTypeText.
@ -6793,15 +6810,15 @@ elete Message",get description(){return get$4($0)},get confirmText(){return get$
Cancel",get icon(){return Git_branch},onConfirm:handleConfirmFork,onCancel:()=>set$1(showForkDialog,!1),get open(){return get$4(showForkDialog)},set open($$value){set$1(showForkDialog,$$value,!0)},children:($$anchor2,$$slotProps)=>{var div_4=root_7$k(),div_5=child(div_4),node_11=child(div_5);Label(node_11,{for:"fork-name",children:($$anchor3,$$slotProps2)=>{next$1();var text2=text$8("Title");append($$anchor3,text2)},$$slots:{default:!0}});var node_12=sibling(node_11,2);Input(node_12,{id:"fork-na\
me",class:"text-foreground",placeholder:"Enter fork name",type:"text",get value(){return get$4(forkName)},set value($$value){set$1(forkName,$$value,!0)}}),reset(div_5);var div_6=sibling(div_5,2),node_13=child(div_6);Checkbox(node_13,{id:"fork-attachments",get checked(){return get$4(forkIncludeAttachments)},onCheckedChange:checked=>{set$1(forkIncludeAttachments,checked===!0)}});var node_14=sibling(node_13,2);Label(node_14,{for:"fork-attachments",class:"cursor-pointer text-sm font-normal",children:($$anchor3,$$slotProps2)=>{
next$1();var text_1=text$8("Include all attachments");append($$anchor3,text_1)},$$slots:{default:!0}}),reset(div_6),reset(div_4),append($$anchor2,div_4)},$$slots:{default:!0}}),template_effect(()=>{set_class(div,1,`relative ${$$props.justify==="start"?"mt-2":""} flex h-6 items-center justify-between`),set_class(div_1,1,`${$$props.actionsPosition==="left"?"left-0":"right-0"} flex items-center gap-2 opacity-100 transition-opacity`)}),append($$anchor,fragment),pop()}var root_5$n=from_html("<p>Previ\
ous version</p>"),root_2$C=from_html("<!> <!>",1),root_9$f=from_html("<p>Next version</p>"),root_6$l=from_html("<!> <!>",1),root_1$z=from_html('<div role="navigation"><!> <span class="px-1 font-mono text-xs"> </span> <!></div>');function ChatMessageBranchingControls($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),hasPrevious=user_derived(()=>$$props.siblingInfo&&$$props.siblingInfo.currentIndex>0),hasNext=user_derived(()=>$$props.siblingInfo&&$$props.siblingInfo.currentIndex<
ous version</p>"),root_2$C=from_html("<!> <!>",1),root_9$g=from_html("<p>Next version</p>"),root_6$l=from_html("<!> <!>",1),root_1$z=from_html('<div role="navigation"><!> <span class="px-1 font-mono text-xs"> </span> <!></div>');function ChatMessageBranchingControls($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),hasPrevious=user_derived(()=>$$props.siblingInfo&&$$props.siblingInfo.currentIndex>0),hasNext=user_derived(()=>$$props.siblingInfo&&$$props.siblingInfo.currentIndex<
$$props.siblingInfo.totalSiblings-1),nextSiblingId=user_derived(()=>get$4(hasNext)?$$props.siblingInfo.siblingIds[$$props.siblingInfo.currentIndex+1]:null),previousSiblingId=user_derived(()=>get$4(hasPrevious)?$$props.siblingInfo.siblingIds[$$props.siblingInfo.currentIndex-1]:null);function handleNext(){get$4(nextSiblingId)&&$$props.onNavigateToSibling?.(get$4(nextSiblingId))}function handlePrevious(){get$4(previousSiblingId)&&$$props.onNavigateToSibling?.(get$4(previousSiblingId))}var fragment=comment$2(),
node2=first_child(fragment);{var consequent=$$anchor2=>{var div=root_1$z(),node_1=child(div);component(node_1,()=>Root$5,($$anchor3,Tooltip_Root)=>{Tooltip_Root($$anchor3,{children:($$anchor4,$$slotProps)=>{var fragment_1=root_2$C(),node_2=first_child(fragment_1);component(node_2,()=>Tooltip_trigger,($$anchor5,Tooltip_Trigger)=>{Tooltip_Trigger($$anchor5,{children:($$anchor6,$$slotProps2)=>{{let $0=user_derived(()=>get$4(hasPrevious)?"":"cursor-not-allowed opacity-30"),$1=user_derived(()=>!get$4(
hasPrevious));Button($$anchor6,{"aria-label":"Previous message version",get class(){return`h-5 w-5 p-0 ${get$4($0)??""}`},get disabled(){return get$4($1)},onclick:handlePrevious,size:"sm",variant:"ghost",children:($$anchor7,$$slotProps3)=>{Chevron_left($$anchor7,{class:"h-3 w-3"})},$$slots:{default:!0}})}},$$slots:{default:!0}})});var node_3=sibling(node_2,2);component(node_3,()=>Tooltip_content,($$anchor5,Tooltip_Content)=>{Tooltip_Content($$anchor5,{children:($$anchor6,$$slotProps2)=>{var p2=root_5$n();
append($$anchor6,p2)},$$slots:{default:!0}})}),append($$anchor4,fragment_1)},$$slots:{default:!0}})});var span=sibling(node_1,2),text2=child(span);reset(span);var node_4=sibling(span,2);component(node_4,()=>Root$5,($$anchor3,Tooltip_Root_1)=>{Tooltip_Root_1($$anchor3,{children:($$anchor4,$$slotProps)=>{var fragment_4=root_6$l(),node_5=first_child(fragment_4);component(node_5,()=>Tooltip_trigger,($$anchor5,Tooltip_Trigger_1)=>{Tooltip_Trigger_1($$anchor5,{children:($$anchor6,$$slotProps2)=>{{let $0=user_derived(
()=>get$4(hasNext)?"":"cursor-not-allowed opacity-30"),$1=user_derived(()=>!get$4(hasNext));Button($$anchor6,{"aria-label":"Next message version",get class(){return`h-5 w-5 p-0 ${get$4($0)??""}`},get disabled(){return get$4($1)},onclick:handleNext,size:"sm",variant:"ghost",children:($$anchor7,$$slotProps3)=>{Chevron_right($$anchor7,{class:"h-3 w-3"})},$$slots:{default:!0}})}},$$slots:{default:!0}})});var node_6=sibling(node_5,2);component(node_6,()=>Tooltip_content,($$anchor5,Tooltip_Content_1)=>{
Tooltip_Content_1($$anchor5,{children:($$anchor6,$$slotProps2)=>{var p_1=root_9$f();append($$anchor6,p_1)},$$slots:{default:!0}})}),append($$anchor4,fragment_4)},$$slots:{default:!0}})}),reset(div),template_effect(()=>{set_attribute(div,"aria-label",`Message version ${$$props.siblingInfo.currentIndex+1} of ${$$props.siblingInfo.totalSiblings??""}`),set_class(div,1,`flex items-center gap-1 text-xs text-muted-foreground ${className()??""}`),set_text(text2,`${$$props.siblingInfo.currentIndex+1}/${$$props.
Tooltip_Content_1($$anchor5,{children:($$anchor6,$$slotProps2)=>{var p_1=root_9$g();append($$anchor6,p_1)},$$slots:{default:!0}})}),append($$anchor4,fragment_4)},$$slots:{default:!0}})}),reset(div),template_effect(()=>{set_attribute(div,"aria-label",`Message version ${$$props.siblingInfo.currentIndex+1} of ${$$props.siblingInfo.totalSiblings??""}`),set_class(div,1,`flex items-center gap-1 text-xs text-muted-foreground ${className()??""}`),set_text(text2,`${$$props.siblingInfo.currentIndex+1}/${$$props.
siblingInfo.totalSiblings??""}`)}),append($$anchor2,div)};if_block(node2,$$render=>{$$props.siblingInfo&&$$props.siblingInfo.totalSiblings>1&&$$render(consequent)})}append($$anchor,fragment),pop()}var root_3$w=from_html('<button type="button"><!> <span class="sr-only">Reading</span></button>'),root_4$j=from_html("<p>Reading (prompt processing)</p>"),root_2$B=from_html("<!> <!>",1),root_6$k=from_html('<button type="button"><!> <span class="sr-only">Generation</span></button>'),root_7$j=from_html(
"<p> </p>"),root_5$m=from_html("<!> <!>",1),root_10$b=from_html('<button type="button"><!> <span class="sr-only">Tools</span></button>'),root_11$8=from_html("<p>Tool calls</p>"),root_9$e=from_html("<!> <!>",1),root_14$4=from_html('<button type="button"><!> <span class="sr-only">Summary</span></button>'),root_15$3=from_html("<p>Agentic summary</p>"),root_13$9=from_html("<!> <!>",1),root_8$h=from_html("<!> <!>",1),root_16$4=from_html("<!> <!> <!>",1),root_18$2=from_html("<!> <!> <!>",1),root_20$6=from_html(
"<p> </p>"),root_5$m=from_html("<!> <!>",1),root_10$b=from_html('<button type="button"><!> <span class="sr-only">Tools</span></button>'),root_11$8=from_html("<p>Tool calls</p>"),root_9$f=from_html("<!> <!>",1),root_14$4=from_html('<button type="button"><!> <span class="sr-only">Summary</span></button>'),root_15$3=from_html("<p>Agentic summary</p>"),root_13$9=from_html("<!> <!>",1),root_8$h=from_html("<!> <!>",1),root_16$4=from_html("<!> <!> <!>",1),root_18$2=from_html("<!> <!> <!>",1),root_20$6=from_html(
"<!> <!> <!>",1),root_22$4=from_html("<!> <!> <!>",1),root$Z=from_html('<div class="inline-flex items-center text-xs text-muted-foreground"><div class="inline-flex items-center rounded-sm bg-muted-foreground/15 p-0.5"><!> <!> <!></div> <div class="flex items-center gap-1 px-2"><!></div></div>');function ChatMessageStatistics($$anchor,$$props){push$1($$props,!0);let isLive=prop($$props,"isLive",3,!1),isProcessingPrompt=prop($$props,"isProcessingPrompt",3,!1),initialView=prop($$props,"initialView",
19,()=>ChatMessageStatsView.GENERATION),hideSummary=prop($$props,"hideSummary",3,!1),activeView=user_derived(initialView),hasAutoSwitchedToGeneration=state$1(!1);user_effect(()=>{$$props.onActiveViewChange?.(get$4(activeView))}),user_effect(()=>{isLive()&&(!get$4(hasAutoSwitchedToGeneration)&&!isProcessingPrompt()&&$$props.predictedTokens&&$$props.predictedTokens>0?(set$1(activeView,ChatMessageStatsView.GENERATION),set$1(hasAutoSwitchedToGeneration,!0)):get$4(hasAutoSwitchedToGeneration)||set$1(
activeView,ChatMessageStatsView.READING))});let hasGenerationStats=user_derived(()=>$$props.predictedTokens!==void 0&&$$props.predictedTokens>0&&$$props.predictedMs!==void 0&&$$props.predictedMs>0),tokensPerSecond=user_derived(()=>get$4(hasGenerationStats)?$$props.predictedTokens/$$props.predictedMs*MS_PER_SECOND:0),formattedTime=user_derived(()=>$$props.predictedMs!==void 0?formatPerformanceTime($$props.predictedMs):DEFAULT_PERFORMANCE_TIME),promptTokensPerSecond=user_derived(()=>$$props.promptTokens!==
@ -6813,7 +6830,7 @@ $$slots:{default:!0}})});var node_4=sibling(node_2,2);component(node_4,()=>Toolt
Tooltip_Root_1($$anchor2,{children:($$anchor3,$$slotProps)=>{var fragment_2=root_5$m(),node_6=first_child(fragment_2);component(node_6,()=>Tooltip_trigger,($$anchor4,Tooltip_Trigger_1)=>{Tooltip_Trigger_1($$anchor4,{children:($$anchor5,$$slotProps2)=>{var button_1=root_6$k();button_1.__click=()=>!get$4(isGenerationDisabled)&&set$1(activeView,ChatMessageStatsView.GENERATION);var node_7=child(button_1);Sparkles(node_7,{class:"h-3 w-3"}),next$1(2),reset(button_1),template_effect(()=>{set_class(button_1,
1,`inline-flex h-5 w-5 items-center justify-center rounded-sm transition-colors ${get$4(activeView)===ChatMessageStatsView.GENERATION?"bg-background text-foreground shadow-sm":get$4(isGenerationDisabled)?"cursor-not-allowed opacity-40":"hover:text-foreground"}`),button_1.disabled=get$4(isGenerationDisabled)}),append($$anchor5,button_1)},$$slots:{default:!0}})});var node_8=sibling(node_6,2);component(node_8,()=>Tooltip_content,($$anchor4,Tooltip_Content_1)=>{Tooltip_Content_1($$anchor4,{children:($$anchor5,$$slotProps2)=>{
var p_1=root_7$j(),text2=child(p_1,!0);reset(p_1),template_effect(()=>set_text(text2,get$4(isGenerationDisabled)?"Generation (waiting for tokens...)":"Generation (token output)")),append($$anchor5,p_1)},$$slots:{default:!0}})}),append($$anchor3,fragment_2)},$$slots:{default:!0}})});var node_9=sibling(node_5,2);{var consequent_2=$$anchor2=>{var fragment_3=root_8$h(),node_10=first_child(fragment_3);component(node_10,()=>Root$5,($$anchor3,Tooltip_Root_2)=>{Tooltip_Root_2($$anchor3,{children:($$anchor4,$$slotProps)=>{
var fragment_4=root_9$e(),node_11=first_child(fragment_4);component(node_11,()=>Tooltip_trigger,($$anchor5,Tooltip_Trigger_2)=>{Tooltip_Trigger_2($$anchor5,{children:($$anchor6,$$slotProps2)=>{var button_2=root_10$b();button_2.__click=()=>set$1(activeView,ChatMessageStatsView.TOOLS);var node_12=child(button_2);Wrench(node_12,{class:"h-3 w-3"}),next$1(2),reset(button_2),template_effect(()=>set_class(button_2,1,`inline-flex h-5 w-5 items-center justify-center rounded-sm transition-colors ${get$4(activeView)===
var fragment_4=root_9$f(),node_11=first_child(fragment_4);component(node_11,()=>Tooltip_trigger,($$anchor5,Tooltip_Trigger_2)=>{Tooltip_Trigger_2($$anchor5,{children:($$anchor6,$$slotProps2)=>{var button_2=root_10$b();button_2.__click=()=>set$1(activeView,ChatMessageStatsView.TOOLS);var node_12=child(button_2);Wrench(node_12,{class:"h-3 w-3"}),next$1(2),reset(button_2),template_effect(()=>set_class(button_2,1,`inline-flex h-5 w-5 items-center justify-center rounded-sm transition-colors ${get$4(activeView)===
ChatMessageStatsView.TOOLS?"bg-background text-foreground shadow-sm":"hover:text-foreground"}`)),append($$anchor6,button_2)},$$slots:{default:!0}})});var node_13=sibling(node_11,2);component(node_13,()=>Tooltip_content,($$anchor5,Tooltip_Content_2)=>{Tooltip_Content_2($$anchor5,{children:($$anchor6,$$slotProps2)=>{var p_2=root_11$8();append($$anchor6,p_2)},$$slots:{default:!0}})}),append($$anchor4,fragment_4)},$$slots:{default:!0}})});var node_14=sibling(node_10,2);{var consequent_1=$$anchor3=>{
var fragment_5=comment$2(),node_15=first_child(fragment_5);component(node_15,()=>Root$5,($$anchor4,Tooltip_Root_3)=>{Tooltip_Root_3($$anchor4,{children:($$anchor5,$$slotProps)=>{var fragment_6=root_13$9(),node_16=first_child(fragment_6);component(node_16,()=>Tooltip_trigger,($$anchor6,Tooltip_Trigger_3)=>{Tooltip_Trigger_3($$anchor6,{children:($$anchor7,$$slotProps2)=>{var button_3=root_14$4();button_3.__click=()=>set$1(activeView,ChatMessageStatsView.SUMMARY);var node_17=child(button_3);Layers(
node_17,{class:"h-3 w-3"}),next$1(2),reset(button_3),template_effect(()=>set_class(button_3,1,`inline-flex h-5 w-5 items-center justify-center rounded-sm transition-colors ${get$4(activeView)===ChatMessageStatsView.SUMMARY?"bg-background text-foreground shadow-sm":"hover:text-foreground"}`)),append($$anchor7,button_3)},$$slots:{default:!0}})});var node_18=sibling(node_16,2);component(node_18,()=>Tooltip_content,($$anchor6,Tooltip_Content_3)=>{Tooltip_Content_3($$anchor6,{children:($$anchor7,$$slotProps2)=>{
@ -6858,7 +6875,7 @@ $$render(alternate,!1)})}append($$anchor,fragment),pop()}var root_4$g=from_html(
index$2,($$anchor2,key2,index2)=>{var fragment=root_1$x(),node2=first_child(fragment);{var consequent=$$anchor3=>{{let $0=user_derived(()=>variant()==="destructive"?"text-destructive":"");Arrow_big_up($$anchor3,{get class(){return`h-1 w-1 ${get$4($0)??""} -mr-1`}})}},alternate_1=$$anchor3=>{var fragment_2=comment$2(),node_1=first_child(fragment_2);{var consequent_1=$$anchor4=>{var span=root_4$g();template_effect(()=>set_class(span,1,clsx(variant()==="destructive"?"text-destructive":""))),append(
$$anchor4,span)},alternate=$$anchor4=>{var text2=text$8();template_effect($0=>set_text(text2,$0),[()=>get$4(key2).toUpperCase()]),append($$anchor4,text2)};if_block(node_1,$$render=>{get$4(key2)==="cmd"?$$render(consequent_1):$$render(alternate,!1)},!0)}append($$anchor3,fragment_2)};if_block(node2,$$render=>{get$4(key2)==="shift"?$$render(consequent):$$render(alternate_1,!1)})}var node_2=sibling(node2,2);{var consequent_2=$$anchor3=>{var span_1=root_6$j();append($$anchor3,span_1)};if_block(node_2,
$$render=>{index2<$$props.keys.length-1&&$$render(consequent_2)})}append($$anchor2,fragment)}),reset(kbd),template_effect(()=>set_class(kbd,1,`px-1 pointer-events-none inline-flex select-none items-center gap-0.5 font-sans text-md font-medium opacity-0 transition-opacity -my-1 ${get$4(variantClasses)??""} ${className()??""}`)),append($$anchor,kbd),pop()}var root_3$s=from_html('<img alt="" class="h-3.5 w-3.5 shrink-0 rounded-sm"/>'),root_4$f=from_html("<span> </span>"),root_1$w=from_html("<!> <!>",
1),root_8$f=from_html("<span> </span>"),root_9$d=from_html('<span class="max-w-xs break-all"> </span>'),root_7$i=from_html("<!> <!>",1),root_5$k=from_html('<div class="flex flex-wrap justify-end gap-1"></div>'),root_11$7=from_html("<div><span> </span></div>"),root_14$3=from_html('<div><div class="space-y-2"><div class="h-3 w-3/4 animate-pulse rounded bg-foreground/20"></div> <div class="h-3 w-full animate-pulse rounded bg-foreground/20"></div> <div class="h-3 w-5/6 animate-pulse rounded bg-foreg\
1),root_8$f=from_html("<span> </span>"),root_9$e=from_html('<span class="max-w-xs break-all"> </span>'),root_7$i=from_html("<!> <!>",1),root_5$k=from_html('<div class="flex flex-wrap justify-end gap-1"></div>'),root_11$7=from_html("<div><span> </span></div>"),root_14$3=from_html('<div><div class="space-y-2"><div class="h-3 w-3/4 animate-pulse rounded bg-foreground/20"></div> <div class="h-3 w-full animate-pulse rounded bg-foreground/20"></div> <div class="h-3 w-5/6 animate-pulse rounded bg-foreg\
round/20"></div></div></div>'),root_19$1=from_html("<span> </span>"),root_20$5=from_html("<span> </span>"),root_17$3=from_html("<div><span></span></div>"),root$T=from_html('<div><div class="flex items-center justify-between gap-2"><div class="inline-flex flex-wrap items-center gap-1.25 text-xs text-muted-foreground"><!> <!></div> <!></div> <!></div>');function ChatMessageMcpPromptContent($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),variant=prop($$props,"variant",
19,()=>McpPromptVariant.MESSAGE),isLoading2=prop($$props,"isLoading",3,!1),hoveredArgKey=state$1(null),argumentEntries=user_derived(()=>Object.entries($$props.prompt.arguments??{})),hasArguments=user_derived(()=>$$props.prompt.arguments&&Object.keys($$props.prompt.arguments).length>0),hasContent=user_derived(()=>$$props.prompt.content&&$$props.prompt.content.trim().length>0),contentParts=user_derived(()=>{if(!$$props.prompt.content||!get$4(hasArguments))return[{text:$$props.prompt.content||"",argKey:null}];
const parts=[];let remaining=$$props.prompt.content;const valueToKey=new SvelteMap;for(const[key2,value]of get$4(argumentEntries))value&&value.trim()&&valueToKey.set(value,key2);const sortedValues=[...valueToKey.keys()].sort((a,b)=>b.length-a.length);for(;remaining.length>0;){let earliestMatch=null;for(const value of sortedValues){const index2=remaining.indexOf(value);index2!==-1&&(earliestMatch===null||index2<earliestMatch.index)&&(earliestMatch={index:index2,value,key:valueToKey.get(value)})}if(earliestMatch)
@ -6868,7 +6885,7 @@ Tooltip_Root($$anchor2,{children:($$anchor3,$$slotProps)=>{var fragment=root_1$w
$$anchor6,img)};if_block(node_2,$$render=>{get$4(serverFavicon)&&$$render(consequent)})}append($$anchor5,fragment_1)},$$slots:{default:!0}})});var node_3=sibling(node_1,2);component(node_3,()=>Tooltip_content,($$anchor4,Tooltip_Content)=>{Tooltip_Content($$anchor4,{children:($$anchor5,$$slotProps2)=>{var span=root_4$f(),text2=child(span,!0);reset(span),template_effect(()=>set_text(text2,get$4(serverDisplayName))),append($$anchor5,span)},$$slots:{default:!0}})}),append($$anchor3,fragment)},$$slots:{
default:!0}})});var node_4=sibling(node2,2);TruncatedText(node_4,{get text(){return $$props.prompt.name}}),reset(div_2);var node_5=sibling(div_2,2);{var consequent_1=$$anchor2=>{var div_3=root_5$k();each(div_3,21,()=>get$4(argumentEntries),([key2,value])=>key2,($$anchor3,$$item)=>{var $$array=user_derived(()=>to_array(get$4($$item),2));let key2=()=>get$4($$array)[0],value=()=>get$4($$array)[1];var fragment_2=comment$2(),node_6=first_child(fragment_2);component(node_6,()=>Root$5,($$anchor4,Tooltip_Root_1)=>{
Tooltip_Root_1($$anchor4,{children:($$anchor5,$$slotProps)=>{var fragment_3=root_7$i(),node_7=first_child(fragment_3);component(node_7,()=>Tooltip_trigger,($$anchor6,Tooltip_Trigger_1)=>{Tooltip_Trigger_1($$anchor6,{children:($$anchor7,$$slotProps2)=>{var span_1=root_8$f(),text_1=child(span_1,!0);reset(span_1),template_effect(()=>{set_class(span_1,1,`rounded-sm bg-purple-200/60 px-1.5 py-0.5 text-[10px] leading-none text-purple-700 transition-opacity dark:bg-purple-800/40 dark:text-purple-300 ${get$4(
hoveredArgKey)&&get$4(hoveredArgKey)!==key2()?"opacity-30":""}`),set_text(text_1,key2())}),event("mouseenter",span_1,()=>set$1(hoveredArgKey,key2(),!0)),event("mouseleave",span_1,()=>set$1(hoveredArgKey,null)),append($$anchor7,span_1)},$$slots:{default:!0}})});var node_8=sibling(node_7,2);component(node_8,()=>Tooltip_content,($$anchor6,Tooltip_Content_1)=>{Tooltip_Content_1($$anchor6,{children:($$anchor7,$$slotProps2)=>{var span_2=root_9$d(),text_2=child(span_2,!0);reset(span_2),template_effect(
hoveredArgKey)&&get$4(hoveredArgKey)!==key2()?"opacity-30":""}`),set_text(text_1,key2())}),event("mouseenter",span_1,()=>set$1(hoveredArgKey,key2(),!0)),event("mouseleave",span_1,()=>set$1(hoveredArgKey,null)),append($$anchor7,span_1)},$$slots:{default:!0}})});var node_8=sibling(node_7,2);component(node_8,()=>Tooltip_content,($$anchor6,Tooltip_Content_1)=>{Tooltip_Content_1($$anchor6,{children:($$anchor7,$$slotProps2)=>{var span_2=root_9$e(),text_2=child(span_2,!0);reset(span_2),template_effect(
()=>set_text(text_2,value())),append($$anchor7,span_2)},$$slots:{default:!0}})}),append($$anchor5,fragment_3)},$$slots:{default:!0}})}),append($$anchor3,fragment_2)}),reset(div_3),append($$anchor2,div_3)};if_block(node_5,$$render=>{get$4(showArgBadges)&&$$render(consequent_1)})}reset(div_1);var node_9=sibling(div_1,2);{var consequent_2=$$anchor2=>{Card($$anchor2,{class:"relative overflow-hidden rounded-[1.125rem] border border-destructive/50 bg-destructive/10 backdrop-blur-md",children:($$anchor3,$$slotProps)=>{
var div_4=root_11$7(),span_3=child(div_4),text_3=child(span_3,!0);reset(span_3),reset(div_4),template_effect(()=>{set_class(div_4,1,`overflow-y-auto ${get$4(paddingClass)??""}`),set_style(div_4,`${get$4(maxHeightStyle)??""} overflow-wrap: anywhere; word-break: break-word;`),set_class(span_3,1,`${get$4(textSizeClass)??""} text-destructive`),set_text(text_3,$$props.loadError)}),append($$anchor3,div_4)},$$slots:{default:!0}})},alternate_2=$$anchor2=>{var fragment_5=comment$2(),node_10=first_child(fragment_5);
{var consequent_3=$$anchor3=>{Card($$anchor3,{class:"relative overflow-hidden rounded-[1.125rem] border border-purple-200 bg-purple-500/10 px-1 py-2 backdrop-blur-md dark:border-purple-800 dark:bg-purple-500/20",children:($$anchor4,$$slotProps)=>{var div_5=root_14$3();template_effect(()=>{set_class(div_5,1,`overflow-y-auto ${get$4(paddingClass)??""}`),set_style(div_5,`${get$4(maxHeightStyle)??""} overflow-wrap: anywhere; word-break: break-word;`)}),append($$anchor4,div_5)},$$slots:{default:!0}})},
@ -6876,7 +6893,7 @@ alternate_1=$$anchor3=>{var fragment_7=comment$2(),node_11=first_child(fragment_
{var consequent_4=$$anchor7=>{var span_5=root_19$1(),text_4=child(span_5,!0);reset(span_5),template_effect(()=>{set_class(span_5,1,`rounded-sm bg-purple-300/50 px-0.5 text-purple-900 transition-opacity dark:bg-purple-700/50 dark:text-purple-100 ${get$4(hoveredArgKey)&&get$4(hoveredArgKey)!==get$4(part).argKey?"opacity-30":""}`),set_text(text_4,get$4(part).text)}),event("mouseenter",span_5,()=>set$1(hoveredArgKey,get$4(part).argKey,!0)),event("mouseleave",span_5,()=>set$1(hoveredArgKey,null)),append(
$$anchor7,span_5)},alternate=$$anchor7=>{var span_6=root_20$5(),text_5=child(span_6,!0);reset(span_6),template_effect(()=>{set_class(span_6,1,`transition-opacity ${get$4(hoveredArgKey)?"opacity-30":""}`),set_text(text_5,get$4(part).text)}),append($$anchor7,span_6)};if_block(node_12,$$render=>{get$4(part).argKey?$$render(consequent_4):$$render(alternate,!1)})}append($$anchor6,fragment_9)}),reset(span_4),reset(div_6),template_effect(()=>{set_class(div_6,1,`overflow-y-auto ${get$4(paddingClass)??""}`),
set_style(div_6,`${get$4(maxHeightStyle)??""} overflow-wrap: anywhere; word-break: break-word;`),set_class(span_4,1,`${get$4(textSizeClass)??""} whitespace-pre-wrap`)}),append($$anchor5,div_6)},$$slots:{default:!0}})};if_block(node_11,$$render=>{get$4(hasContent)&&$$render(consequent_5)},!0)}append($$anchor3,fragment_7)};if_block(node_10,$$render=>{isLoading2()?$$render(consequent_3):$$render(alternate_1,!1)},!0)}append($$anchor2,fragment_5)};if_block(node_9,$$render=>{$$props.loadError?$$render(
consequent_2):$$render(alternate_2,!1)})}reset(div),template_effect(()=>set_class(div,1,`flex flex-col gap-2 ${className()??""}`)),append($$anchor,div),pop()}var root_2$y=from_html("<!> Cancel",1),root_3$r=from_html("<!> Save",1),root_1$v=from_html('<div class="w-full max-w-[80%]"><textarea placeholder="Edit system message..."></textarea> <div class="mt-2 flex justify-end gap-2"><!> <!></div></div>'),root_7$h=from_html("<div><!></div>"),root_8$e=from_html("<span> </span>"),root_9$c=from_html('<d\
consequent_2):$$render(alternate_2,!1)})}reset(div),template_effect(()=>set_class(div,1,`flex flex-col gap-2 ${className()??""}`)),append($$anchor,div),pop()}var root_2$y=from_html("<!> Cancel",1),root_3$r=from_html("<!> Save",1),root_1$v=from_html('<div class="w-full max-w-[80%]"><textarea placeholder="Edit system message..."></textarea> <div class="mt-2 flex justify-end gap-2"><!> <!></div></div>'),root_7$h=from_html("<div><!></div>"),root_8$e=from_html("<span> </span>"),root_9$d=from_html('<d\
iv class="pointer-events-none absolute right-0 bottom-0 left-0 h-48 bg-gradient-to-t from-muted to-transparent"></div> <div class="pointer-events-none absolute right-0 bottom-4 left-0 flex justify-center opacity-0 transition-opacity group-hover/expand:opacity-100"><!></div>',1),root_11$6=from_html('<div class="mb-2 flex justify-center"><!></div>'),root_6$i=from_html("<div><!> <!></div> <!>",1),root_5$j=from_html('<div class="relative max-w-[80%]"><button type="button"><!></button></div>'),root_13$8=from_html(
'<div class="max-w-[80%]"><!></div>'),root_4$e=from_html("<!> <!>",1),root$S=from_html('<div aria-label="System message with actions" role="group"><!></div>');function ChatMessageSystem($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),siblingInfo=prop($$props,"siblingInfo",3,null),textareaElement=prop($$props,"textareaElement",15);const editCtx=getMessageEditContext();function handleEditKeydown(event2){event2.key===KeyboardKey.ENTER&&!event2.shiftKey&&!isIMEComposing(
event2)?(event2.preventDefault(),editCtx.save()):event2.key===KeyboardKey.ESCAPE&&(event2.preventDefault(),editCtx.cancel())}let isMultiline=state$1(!1),messageElement=state$1(void 0),isExpanded=state$1(!1),contentHeight=state$1(0);const MAX_HEIGHT=200,currentConfig=config$1();let showExpandButton=user_derived(()=>get$4(contentHeight)>MAX_HEIGHT);user_effect(()=>{if(!get$4(messageElement)||!$$props.message.content.trim())return;$$props.message.content.includes(`
@ -6886,7 +6903,7 @@ var node_3=sibling(node_1,2);{let $0=user_derived(()=>!editCtx.editedContent.tri
-h-[60px] w-full resize-none rounded-2xl px-3 py-2 text-sm ${INPUT_CLASSES??""}`)}),append($$anchor2,div_1)},alternate_1=$$anchor2=>{var fragment_2=root_4$e(),node_5=first_child(fragment_2);{var consequent_4=$$anchor3=>{var div_3=root_5$j(),button=child(div_3);button.__click=function(...$$args){(get$4(showExpandButton)&&!get$4(isExpanded)?toggleExpand:void 0)?.apply(this,$$args)};var node_6=child(button);{let $0=user_derived(()=>get$4(isMultiline)?"":void 0);Card(node_6,{class:"overflow-y-auto r\
ounded-[1.125rem] !border-2 !border-dashed !border-border/50 bg-muted px-3.75 py-1.5 data-[multiline]:py-2.5",get"data-multiline"(){return get$4($0)},style:"border: 2px dashed hsl(var(--border)); max-height: var(--max-message-height); overflow-wrap: anywhere; word-break: break-word;",children:($$anchor4,$$slotProps)=>{var fragment_3=root_6$i(),div_4=first_child(fragment_3),node_7=child(div_4);{var consequent_1=$$anchor5=>{var div_5=root_7$h(),node_8=child(div_5);MarkdownContent(node_8,{class:"ma\
rkdown-system-content -my-4",get content(){return $$props.message.content}}),reset(div_5),bind_this(div_5,$$value=>set$1(messageElement,$$value),()=>get$4(messageElement)),template_effect(()=>set_class(div_5,1,clsx(get$4(isExpanded)?"cursor-text":""))),append($$anchor5,div_5)},alternate=$$anchor5=>{var span=root_8$e(),text2=child(span,!0);reset(span),bind_this(span,$$value=>set$1(messageElement,$$value),()=>get$4(messageElement)),template_effect(()=>{set_class(span,1,`text-md whitespace-pre-wrap\
${get$4(isExpanded)?"cursor-text":""}`),set_text(text2,$$props.message.content)}),append($$anchor5,span)};if_block(node_7,$$render=>{currentConfig.renderUserContentAsMarkdown?$$render(consequent_1):$$render(alternate,!1)})}var node_9=sibling(node_7,2);{var consequent_2=$$anchor5=>{var fragment_4=root_9$c(),div_6=sibling(first_child(fragment_4),2),node_10=child(div_6);Button(node_10,{class:"rounded-full px-4 py-1.5 text-xs shadow-md",size:"sm",variant:"outline",children:($$anchor6,$$slotProps2)=>{
${get$4(isExpanded)?"cursor-text":""}`),set_text(text2,$$props.message.content)}),append($$anchor5,span)};if_block(node_7,$$render=>{currentConfig.renderUserContentAsMarkdown?$$render(consequent_1):$$render(alternate,!1)})}var node_9=sibling(node_7,2);{var consequent_2=$$anchor5=>{var fragment_4=root_9$d(),div_6=sibling(first_child(fragment_4),2),node_10=child(div_6);Button(node_10,{class:"rounded-full px-4 py-1.5 text-xs shadow-md",size:"sm",variant:"outline",children:($$anchor6,$$slotProps2)=>{
next$1();var text_1=text$8("Show full system message");append($$anchor6,text_1)},$$slots:{default:!0}}),reset(div_6),append($$anchor5,fragment_4)};if_block(node_9,$$render=>{!get$4(isExpanded)&&get$4(showExpandButton)&&$$render(consequent_2)})}reset(div_4);var node_11=sibling(div_4,2);{var consequent_3=$$anchor5=>{var div_7=root_11$6(),node_12=child(div_7);Button(node_12,{class:"rounded-full px-4 py-1.5 text-xs",onclick:e=>{e.stopPropagation(),toggleExpand()},size:"sm",variant:"outline",children:($$anchor6,$$slotProps2)=>{
next$1();var text_2=text$8("Collapse System Message");append($$anchor6,text_2)},$$slots:{default:!0}}),reset(div_7),append($$anchor5,div_7)};if_block(node_11,$$render=>{get$4(isExpanded)&&get$4(showExpandButton)&&$$render(consequent_3)})}template_effect(()=>{set_class(div_4,1,`relative transition-all duration-300 ${get$4(isExpanded)?"cursor-text select-text":"select-none"}`),set_style(div_4,!get$4(isExpanded)&&get$4(showExpandButton)?`max-height: ${MAX_HEIGHT}px;`:"max-height: none;")}),append($$anchor4,
fragment_3)},$$slots:{default:!0}})}reset(button),reset(div_3),template_effect(()=>set_class(button,1,`group/expand w-full text-left ${!get$4(isExpanded)&&get$4(showExpandButton)?"cursor-pointer":"cursor-auto"}`)),append($$anchor3,div_3)};if_block(node_5,$$render=>{$$props.message.content.trim()&&$$render(consequent_4)})}var node_13=sibling(node_5,2);{var consequent_5=$$anchor3=>{var div_8=root_13$8(),node_14=child(div_8);ChatMessageActions(node_14,{actionsPosition:"right",get deletionInfo(){return $$props.
@ -6960,7 +6977,7 @@ startInterval():this.stopInterval()}destroy(){this.stopInterval(),this._doStopOb
return new AutoScrollController(options)}var root$O=from_html('<div class="pointer-events-none fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm"><div class="flex flex-col items-center justify-center rounded-2xl border-2 border-dashed border-border bg-background p-12 shadow-lg"><!> <p class="text-lg font-medium text-foreground">Attach a file</p> <p class="text-sm text-muted-foreground">Drop your files here to upload</p></div></div>');function ChatScreenDragOverlay($$anchor){
var div=root$O(),div_1=child(div),node2=child(div_1);Upload(node2,{class:"mb-4 h-12 w-12 text-muted-foreground"}),next$1(4),reset(div_1),reset(div),append($$anchor,div)}var root_5$h=from_html('<span>Server unavailable</span> <button class="flex items-center gap-1.5 rounded-lg bg-destructive/20 px-2 py-1 text-xs font-medium hover:bg-destructive/30 disabled:opacity-50"><!> </button>',1),root_4$c=from_html("<!> <!> <!>",1),root_3$o=from_html('<div class="pointer-events-auto mx-auto mb-4 max-w-[48re\
m] px-1"><!></div>'),root_2$u=from_html('<div aria-label="Chat interface with file drop zone" class="flex h-full flex-col-reverse overflow-y-auto px-4 md:px-6" role="main"><div class="flex flex-col"><!> <div class="pointer-events-none sticky right-0 bottom-4 left-0 mt-auto"><!> <!> <div class="conversation-chat-form pointer-events-auto rounded-t-3xl svelte-lwk0qk"><!></div></div></div></div>'),root_12$5=from_html('<span>Server unavailable</span> <button class="flex items-center gap-1.5 rounded-l\
g bg-destructive/20 px-2 py-1 text-xs font-medium hover:bg-destructive/30 disabled:opacity-50"><!> </button>',1),root_11$4=from_html("<!> <!> <!>",1),root_10$9=from_html('<div class="mb-4"><!></div>'),root_9$b=from_html('<div aria-label="Welcome screen with file drop zone" class="flex h-full items-center justify-center" role="main"><div class="w-full max-w-[48rem] px-4"><div class="mb-10 text-center"><h1 class="mb-2 text-2xl font-semibold tracking-tight md:text-3xl">llama.cpp</h1> <p class="text\
g bg-destructive/20 px-2 py-1 text-xs font-medium hover:bg-destructive/30 disabled:opacity-50"><!> </button>',1),root_11$4=from_html("<!> <!> <!>",1),root_10$9=from_html('<div class="mb-4"><!></div>'),root_9$c=from_html('<div aria-label="Welcome screen with file drop zone" class="flex h-full items-center justify-center" role="main"><div class="w-full max-w-[48rem] px-4"><div class="mb-10 text-center"><h1 class="mb-2 text-2xl font-semibold tracking-tight md:text-3xl">llama.cpp</h1> <p class="text\
-muted-foreground md:text-lg"> </p></div> <!> <div><!></div></div></div>'),root_17$2=from_html("<!> <!>",1),root_21$3=from_html('<div class="rounded-md bg-destructive/10 px-3 py-2"><p class="font-mono text-sm break-all text-destructive"> </p> <p class="mt-1 text-xs text-muted-foreground">File type not supported</p></div>'),root_20$4=from_html('<div class="space-y-2"><h4 class="text-sm font-medium text-destructive">Unsupported File Types</h4> <div class="space-y-1"></div></div>'),root_23$2=from_html(
'<div class="rounded-md bg-destructive/10 px-3 py-2"><p class="font-mono text-sm break-all text-destructive"> </p> <p class="mt-1 text-xs text-muted-foreground"> </p></div>'),root_22$3=from_html('<div class="space-y-2"><div class="space-y-1"></div></div>'),root_16$3=from_html('<!> <div class="!max-h-[50vh] min-h-0 flex-1 space-y-4 overflow-y-auto"><!> <!></div> <div class="rounded-md bg-muted/50 p-3"><h4 class="mb-2 text-sm font-medium">This model supports:</h4> <p class="text-sm text-muted-fore\
ground"> </p></div> <!>',1),root_15$2=from_html("<!> <!>",1),root$N=from_html("<!> <!> <!> <!> <!> <!> <!>",1);function ChatScreen($$anchor,$$props){push$1($$props,!0);let showCenteredEmpty=prop($$props,"showCenteredEmpty",3,!1),disableAutoScroll=user_derived(()=>!!config$1().disableAutoScroll),chatScrollContainer=state$1(void 0),dragCounter=state$1(0),isDragOver=state$1(!1),showFileErrorDialog=state$1(!1),uploadedFiles=state$1(proxy([]));const autoScroll=createAutoScrollController({isColumnReverse:!0});
@ -6980,7 +6997,7 @@ Alert_Title($$anchor6,{class:"flex items-center justify-between",children:($$anc
"Retrying...":"Retry"}`)}),append($$anchor7,fragment_3)},$$slots:{default:!0}})});var node_10=sibling(node_8,2);component(node_10,()=>Alert_description,($$anchor6,Alert_Description)=>{Alert_Description($$anchor6,{children:($$anchor7,$$slotProps2)=>{next$1();var text_1=text$8();template_effect($0=>set_text(text_1,$0),[serverError]),append($$anchor7,text_1)},$$slots:{default:!0}})}),append($$anchor5,fragment_2)},$$slots:{default:!0}})}),reset(div_3),transition(1,div_3,()=>fly,()=>({y:10,duration:250})),
append($$anchor3,div_3)};if_block(node_5,$$render=>{get$4(hasPropsError)&&$$render(consequent_1)})}var div_4=sibling(node_5,2),node_11=child(div_4);{let $0=user_derived(()=>get$4(hasPropsError)||isEditing());ChatScreenForm(node_11,{get disabled(){return get$4($0)},get initialMessage(){return get$4(initialMessage)},get isLoading(){return get$4(isCurrentConversationLoading)},onFileRemove:handleFileRemove,onFileUpload:handleFileUpload,onSend:handleSendMessage,onStop:()=>chatStore.stopGeneration(),onSystemPromptAdd:handleSystemPromptAdd,
showHelperText:!1,get uploadedFiles(){return get$4(uploadedFiles)},set uploadedFiles($$value){set$1(uploadedFiles,$$value,!0)}})}reset(div_4),reset(div_2),reset(div_1),reset(div),bind_this(div,$$value=>set$1(chatScrollContainer,$$value),()=>get$4(chatScrollContainer)),event("dragenter",div,handleDragEnter),event("dragleave",div,handleDragLeave),event("dragover",div,handleDragOver),event("drop",div,handleDrop),event("scroll",div,handleScroll),transition(1,div_2,()=>slide,()=>({duration:150,axis:"\
y"})),append($$anchor2,div)},alternate_1=$$anchor2=>{var fragment_5=comment$2(),node_12=first_child(fragment_5);{var consequent_3=$$anchor3=>{ServerLoadingSplash($$anchor3,{})},alternate=$$anchor3=>{var div_5=root_9$b(),div_6=child(div_5),div_7=child(div_6),p2=sibling(child(div_7),2),text_2=child(p2);reset(p2),reset(div_7);var node_13=sibling(div_7,2);{var consequent_4=$$anchor4=>{var div_8=root_10$9(),node_14=child(div_8);component(node_14,()=>Alert,($$anchor5,Alert_Root_1)=>{Alert_Root_1($$anchor5,
y"})),append($$anchor2,div)},alternate_1=$$anchor2=>{var fragment_5=comment$2(),node_12=first_child(fragment_5);{var consequent_3=$$anchor3=>{ServerLoadingSplash($$anchor3,{})},alternate=$$anchor3=>{var div_5=root_9$c(),div_6=child(div_5),div_7=child(div_6),p2=sibling(child(div_7),2),text_2=child(p2);reset(p2),reset(div_7);var node_13=sibling(div_7,2);{var consequent_4=$$anchor4=>{var div_8=root_10$9(),node_14=child(div_8);component(node_14,()=>Alert,($$anchor5,Alert_Root_1)=>{Alert_Root_1($$anchor5,
{variant:"destructive",children:($$anchor6,$$slotProps)=>{var fragment_7=root_11$4(),node_15=first_child(fragment_7);Triangle_alert(node_15,{class:"h-4 w-4"});var node_16=sibling(node_15,2);component(node_16,()=>Alert_title,($$anchor7,Alert_Title_1)=>{Alert_Title_1($$anchor7,{class:"flex items-center justify-between",children:($$anchor8,$$slotProps2)=>{var fragment_8=root_12$5(),button_1=sibling(first_child(fragment_8),2);button_1.__click=()=>serverStore.fetch();var node_17=child(button_1);{let $0=user_derived(
()=>get$4(isServerLoading)?"animate-spin":"");Refresh_cw(node_17,{get class(){return`h-3 w-3 ${get$4($0)??""}`}})}var text_3=sibling(node_17);reset(button_1),template_effect(()=>{button_1.disabled=get$4(isServerLoading),set_text(text_3,` ${get$4(isServerLoading)?"Retrying...":"Retry"}`)}),append($$anchor8,fragment_8)},$$slots:{default:!0}})});var node_18=sibling(node_16,2);component(node_18,()=>Alert_description,($$anchor7,Alert_Description_1)=>{Alert_Description_1($$anchor7,{children:($$anchor8,$$slotProps2)=>{
next$1();var text_4=text$8();template_effect($0=>set_text(text_4,$0),[serverError]),append($$anchor8,text_4)},$$slots:{default:!0}})}),append($$anchor6,fragment_7)},$$slots:{default:!0}})}),reset(div_8),transition(1,div_8,()=>fly,()=>({y:10,duration:250})),append($$anchor4,div_8)};if_block(node_13,$$render=>{get$4(hasPropsError)&&$$render(consequent_4)})}var div_9=sibling(node_13,2),node_19=child(div_9);ChatScreenForm(node_19,{get disabled(){return get$4(hasPropsError)},get initialMessage(){return get$4(
@ -7020,14 +7037,14 @@ $$props,["$$slots","$$events","$$legacy","ref","class","children"]);var ul=root$
$$props,"ref",15,null),open2=prop($$props,"open",15,!0),onOpenChange=prop($$props,"onOpenChange",3,()=>{}),restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","open","onOpenChange","class","style","children"]);const sidebar=setSidebar({open:()=>open2(),setOpen:value=>{open2(value),onOpenChange()(value),document.cookie=`${SIDEBAR_COOKIE_NAME}=${open2()}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`}});var div=root$E();event("keydown",$window,function(...$$args){sidebar.handleShortcutKeydown?.
apply(this,$$args)}),attribute_effect(div,$0=>({"data-slot":"sidebar-wrapper",style:`--sidebar-width: ${SIDEBAR_WIDTH}; --sidebar-width-icon: ${SIDEBAR_WIDTH_ICON}; ${$$props.style??""}`,class:$0,...restProps}),[()=>cn$1("group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",$$props.class)]);var node2=child(div);snippet(node2,()=>$$props.children??noop$3),reset(div),bind_this(div,$$value=>ref2($$value),()=>ref2()),append($$anchor,div),pop()}var root_1$s=from_html('<!> \
<span class="sr-only">Toggle Sidebar</span>',1);function Sidebar_trigger($$anchor,$$props){push$1($$props,!0),prop($$props,"ref",11,null);let restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","class","onclick"]);const sidebar=useSidebar();{let $0=user_derived(()=>$$props.class),$1=user_derived(()=>sidebar.open?"unset":"2");Button($$anchor,spread_props({"data-sidebar":"trigger","data-slot":"sidebar-trigger",variant:"ghost",size:"icon-lg",get class(){return`rounded-full backdrop-\
blur-lg ${get$4($0)??""} md:left-${get$4($1)??""} -top-2 -left-2 md:top-0`},type:"button",onclick:e=>{$$props.onclick?.(e),sidebar.toggle()}},()=>restProps,{children:($$anchor2,$$slotProps)=>{var fragment_1=root_1$s(),node2=first_child(fragment_1);Panel_left(node2,{}),next$1(2),append($$anchor2,fragment_1)},$$slots:{default:!0}}))}pop()}var root_1$r=from_html("<div><!></div>"),root_6$g=from_html("<!> <!>",1),root_5$g=from_html('<!> <div class="flex h-full w-full flex-col"><!></div>',1),root_9$a=from_html(
blur-lg ${get$4($0)??""} md:left-${get$4($1)??""} -top-2 -left-2 md:top-0`},type:"button",onclick:e=>{$$props.onclick?.(e),sidebar.toggle()}},()=>restProps,{children:($$anchor2,$$slotProps)=>{var fragment_1=root_1$s(),node2=first_child(fragment_1);Panel_left(node2,{}),next$1(2),append($$anchor2,fragment_1)},$$slots:{default:!0}}))}pop()}var root_1$r=from_html("<div><!></div>"),root_6$g=from_html("<!> <!>",1),root_5$g=from_html('<!> <div class="flex h-full w-full flex-col"><!></div>',1),root_9$b=from_html(
'<div class="group peer hidden text-sidebar-foreground md:block" data-slot="sidebar"><div data-slot="sidebar-gap"></div> <div><div data-sidebar="sidebar" data-slot="sidebar-inner" class="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm"><!></div></div></div>');function Sidebar($$anchor,$$props){push$1($$props,!0);let ref2=prop($$props,"re\
f",15,null),side=prop($$props,"side",3,"left"),variant=prop($$props,"variant",3,"sidebar"),collapsible=prop($$props,"collapsible",3,"offcanvas"),restProps=rest_props($$props,["$$slots","$$events","$$legacy","ref","side","variant","collapsible","class","children"]);const sidebar=useSidebar();var fragment=comment$2(),node2=first_child(fragment);{var consequent=$$anchor2=>{var div=root_1$r();attribute_effect(div,$0=>({class:$0,...restProps}),[()=>cn$1("flex h-full w-(--sidebar-width) flex-col bg-si\
debar text-sidebar-foreground",$$props.class)]);var node_1=child(div);snippet(node_1,()=>$$props.children??noop$3),reset(div),bind_this(div,$$value=>ref2($$value),()=>ref2()),append($$anchor2,div)},alternate_1=$$anchor2=>{var fragment_1=comment$2(),node_2=first_child(fragment_1);{var consequent_1=$$anchor3=>{var fragment_2=comment$2(),node_3=first_child(fragment_2),bind_get=()=>sidebar.openMobile,bind_set=v=>sidebar.setOpenMobile(v);component(node_3,()=>Root$1,($$anchor4,Sheet_Root)=>{Sheet_Root(
$$anchor4,spread_props({get open(){return bind_get()},set open($$value){bind_set($$value)}},()=>restProps,{children:($$anchor5,$$slotProps)=>{var fragment_3=comment$2(),node_4=first_child(fragment_3);component(node_4,()=>Sheet_content,($$anchor6,Sheet_Content)=>{Sheet_Content($$anchor6,{"data-sidebar":"sidebar","data-slot":"sidebar","data-mobile":"true",class:"z-99999 w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground sm:z-99 [&>button]:hidden",get style(){return`--sidebar-width: ${SIDEBAR_WIDTH_MOBILE}\
;`},get side(){return side()},children:($$anchor7,$$slotProps2)=>{var fragment_4=root_5$g(),node_5=first_child(fragment_4);component(node_5,()=>Sheet_header,($$anchor8,Sheet_Header)=>{Sheet_Header($$anchor8,{class:"sr-only",children:($$anchor9,$$slotProps3)=>{var fragment_5=root_6$g(),node_6=first_child(fragment_5);component(node_6,()=>Sheet_title,($$anchor10,Sheet_Title)=>{Sheet_Title($$anchor10,{children:($$anchor11,$$slotProps4)=>{next$1();var text2=text$8("Sidebar");append($$anchor11,text2)},
$$slots:{default:!0}})});var node_7=sibling(node_6,2);component(node_7,()=>Sheet_description,($$anchor10,Sheet_Description)=>{Sheet_Description($$anchor10,{children:($$anchor11,$$slotProps4)=>{next$1();var text_1=text$8("Displays the mobile sidebar.");append($$anchor11,text_1)},$$slots:{default:!0}})}),append($$anchor9,fragment_5)},$$slots:{default:!0}})});var div_1=sibling(node_5,2),node_8=child(div_1);snippet(node_8,()=>$$props.children??noop$3),reset(div_1),append($$anchor7,fragment_4)},$$slots:{
default:!0}})}),append($$anchor5,fragment_3)},$$slots:{default:!0}}))}),append($$anchor3,fragment_2)},alternate=$$anchor3=>{var div_2=root_9$a(),div_3=child(div_2),div_4=sibling(div_3,2);attribute_effect(div_4,$0=>({"data-slot":"sidebar-container",class:$0,...restProps}),[()=>cn$1("fixed inset-y-0 z-999 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:z-0 md:flex",side()==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*\
default:!0}})}),append($$anchor5,fragment_3)},$$slots:{default:!0}}))}),append($$anchor3,fragment_2)},alternate=$$anchor3=>{var div_2=root_9$b(),div_3=child(div_2),div_4=sibling(div_3,2);attribute_effect(div_4,$0=>({"data-slot":"sidebar-container",class:$0,...restProps}),[()=>cn$1("fixed inset-y-0 z-999 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:z-0 md:flex",side()==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*\
-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",variant()==="floating"||variant()==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)",$$props.class)]);var div_5=child(div_4),node_9=child(div_5);snippet(node_9,()=>$$props.children??noop$3),reset(div_5),reset(div_4),reset(div_2),bind_this(div_2,$$value=>ref2($$value),()=>ref2()),template_effect($0=>{set_attribute(
div_2,"data-state",sidebar.state),set_attribute(div_2,"data-collapsible",sidebar.state==="collapsed"?collapsible():""),set_attribute(div_2,"data-variant",variant()),set_attribute(div_2,"data-side",side()),set_class(div_3,1,$0)},[()=>clsx(cn$1("relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",variant()==="floating"||variant()==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--\
sidebar-width-icon)+(--spacing(4))+2px)]":"group-data-[collapsible=icon]:w-(--sidebar-width-icon)"))]),append($$anchor3,div_2)};if_block(node_2,$$render=>{sidebar.isMobile?$$render(consequent_1):$$render(alternate,!1)},!0)}append($$anchor2,fragment_1)};if_block(node2,$$render=>{collapsible()==="none"?$$render(consequent):$$render(alternate_1,!1)})}append($$anchor,fragment),pop()}var root$D=from_html('<header><div class="pointer-events-auto flex items-center space-x-2"><!></div></header>');function ChatScreenHeader($$anchor,$$props){
@ -7094,7 +7111,7 @@ transition-transform group-data-[state=open]:-rotate-180":"size-4 opacity-50");v
var fragment_1=root_1$m(),node_1=first_child(fragment_1);snippet(node_1,()=>$$props.children??noop$3);var node_2=sibling(node_1,2);Chevron_down(node_2,{get class(){return get$4(chevronClasses)}}),append($$anchor3,fragment_1)},$$slots:{default:!0}}))})}append($$anchor,fragment),pop()}const Root=Select;var root$z=from_html("<textarea></textarea>");function Textarea($$anchor,$$props){push$1($$props,!0);let ref2=prop($$props,"ref",15,null),value=prop($$props,"value",15),restProps=rest_props($$props,
["$$slots","$$events","$$legacy","ref","value","class"]);var textarea=root$z();remove_textarea_child(textarea),attribute_effect(textarea,$0=>({"data-slot":"textarea",class:$0,...restProps}),[()=>cn$1("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-allowe\
d 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",$$props.class)]),bind_this(textarea,$$value=>ref2($$value),()=>ref2()),bind_value(textarea,value),append($$anchor,textarea),pop()}var root_3$m=from_html(" <!>",1),root_6$e=from_html('<button type="button" class="absolute top-1/2 right-2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded transition-colors hover:bg-muted" ar\
ia-label="Reset to default" title="Reset to default"><!></button>'),root_7$e=from_html('<p class="mt-1 text-xs text-muted-foreground"><!></p>'),root_2$q=from_html('<div class="flex items-center gap-2"><!> <!></div> <div class="relative w-full md:max-w-md"><!> <!></div> <!>',1),root_10$8=from_html(" <!>",1),root_12$4=from_html('<p class="mt-1 text-xs text-muted-foreground"> </p>'),root_13$7=from_html('<div class="mt-3 flex items-center gap-2"><!> <!></div>'),root_9$9=from_html("<!> <!> <!> <!>",1),
ia-label="Reset to default" title="Reset to default"><!></button>'),root_7$e=from_html('<p class="mt-1 text-xs text-muted-foreground"><!></p>'),root_2$q=from_html('<div class="flex items-center gap-2"><!> <!></div> <div class="relative w-full md:max-w-md"><!> <!></div> <!>',1),root_10$8=from_html(" <!>",1),root_12$4=from_html('<p class="mt-1 text-xs text-muted-foreground"> </p>'),root_13$7=from_html('<div class="mt-3 flex items-center gap-2"><!> <!></div>'),root_9$a=from_html("<!> <!> <!> <!>",1),
root_17$1=from_html(" <!>",1),root_21$2=from_html('<div class="flex items-center gap-2"><!> </div>'),root_23$1=from_html('<button type="button" class="absolute top-1/2 right-8 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded transition-colors hover:bg-muted" aria-label="Reset to default" title="Reset to default"><!></button>'),root_27$1=from_html('<div class="flex items-center gap-2"><!> </div>'),root_20$3=from_html('<div class="relative w-full md:w-auto md:max-w-md"><!> \
<!></div> <!>',1),root_29=from_html('<p class="mt-1 text-xs text-muted-foreground"> </p>'),root_16$2=from_html('<div class="flex items-center gap-2"><!> <!></div> <!> <!>',1),root_33=from_html('<p class="text-xs text-muted-foreground"> </p>'),root_31=from_html('<div class="flex items-start space-x-3"><!> <div class="space-y-1"><label class="flex cursor-pointer items-center gap-1.5 pt-1 pb-0.5 text-sm leading-none font-medium"> <!></label> <!></div></div>'),root_1$l=from_html('<div class="space-y\
-2"><!></div>');function ChatSettingsFields($$anchor,$$props){push$1($$props,!0);let sp=user_derived(()=>{if(serverStore.isRouterMode){const m=selectedModelName();if(m)return modelsStore.getModelProps(m)?.default_generation_settings?.params??{}}return serverStore.defaultParams??{}});var fragment=comment$2(),node2=first_child(fragment);each(node2,17,()=>$$props.fields,field=>field.key,($$anchor2,field)=>{var div=root_1$l(),node_1=child(div);{var consequent_4=$$anchor3=>{const currentValue=user_derived(
@ -7103,7 +7120,7 @@ normalizedDefault})());var fragment_1=root_2$q(),div_1=first_child(fragment_1),n
template_effect(()=>set_text(text2,`${get$4(field).label??""} `)),append($$anchor4,fragment_2)},$$slots:{default:!0}});var node_4=sibling(node_2,2);{var consequent_1=$$anchor4=>{ChatSettingsParameterSourceIndicator($$anchor4,{})};if_block(node_4,$$render=>{get$4(isCustomRealTime)&&$$render(consequent_1)})}reset(div_1);var div_2=sibling(div_1,2),node_5=child(div_2);{let $0=user_derived(()=>get$4(sp)[get$4(field).key]!=null?`Default: ${normalizeFloatingPoint(get$4(sp)[get$4(field).key])}`:""),$1=user_derived(
()=>get$4(isCustomRealTime)?"pr-8":"");Input(node_5,{get id(){return get$4(field).key},get value(){return get$4(currentValue)},oninput:e=>{$$props.onConfigChange(get$4(field).key,e.currentTarget.value)},get placeholder(){return get$4($0)},get class(){return`w-full ${get$4($1)??""}`}})}var node_6=sibling(node_5,2);{var consequent_2=$$anchor4=>{var button=root_6$e();button.__click=()=>{settingsStore.resetParameterToServerDefault(get$4(field).key),$$props.onConfigChange(get$4(field).key,"")};var node_7=child(
button);Rotate_ccw(node_7,{class:"h-3 w-3"}),reset(button),append($$anchor4,button)};if_block(node_6,$$render=>{get$4(isCustomRealTime)&&$$render(consequent_2)})}reset(div_2);var node_8=sibling(div_2,2);{var consequent_3=$$anchor4=>{var p_1=root_7$e(),node_9=child(p_1);html$6(node_9,()=>get$4(field).help||SETTING_CONFIG_INFO[get$4(field).key]),reset(p_1),append($$anchor4,p_1)};if_block(node_8,$$render=>{(get$4(field).help||SETTING_CONFIG_INFO[get$4(field).key])&&$$render(consequent_3)})}append($$anchor3,
fragment_1)},alternate_2=$$anchor3=>{var fragment_5=comment$2(),node_10=first_child(fragment_5);{var consequent_8=$$anchor4=>{var fragment_6=root_9$9(),node_11=first_child(fragment_6);Label(node_11,{get for(){return get$4(field).key},class:"block flex items-center gap-1.5 text-sm font-medium",children:($$anchor5,$$slotProps)=>{next$1();var fragment_7=root_10$8(),text_1=first_child(fragment_7),node_12=sibling(text_1);{var consequent_5=$$anchor6=>{Flask_conical($$anchor6,{class:"h-3.5 w-3.5 text-m\
fragment_1)},alternate_2=$$anchor3=>{var fragment_5=comment$2(),node_10=first_child(fragment_5);{var consequent_8=$$anchor4=>{var fragment_6=root_9$a(),node_11=first_child(fragment_6);Label(node_11,{get for(){return get$4(field).key},class:"block flex items-center gap-1.5 text-sm font-medium",children:($$anchor5,$$slotProps)=>{next$1();var fragment_7=root_10$8(),text_1=first_child(fragment_7),node_12=sibling(text_1);{var consequent_5=$$anchor6=>{Flask_conical($$anchor6,{class:"h-3.5 w-3.5 text-m\
uted-foreground"})};if_block(node_12,$$render=>{get$4(field).isExperimental&&$$render(consequent_5)})}template_effect(()=>set_text(text_1,`${get$4(field).label??""} `)),append($$anchor5,fragment_7)},$$slots:{default:!0}});var node_13=sibling(node_11,2);{let $0=user_derived(()=>String($$props.localConfig[get$4(field).key]??""));Textarea(node_13,{get id(){return get$4(field).key},get value(){return get$4($0)},onchange:e=>$$props.onConfigChange(get$4(field).key,e.currentTarget.value),placeholder:"",
class:"min-h-[10rem] w-full md:max-w-2xl"})}var node_14=sibling(node_13,2);{var consequent_6=$$anchor5=>{var p_2=root_12$4(),text_2=child(p_2,!0);reset(p_2),template_effect(()=>set_text(text_2,get$4(field).help||SETTING_CONFIG_INFO[get$4(field).key])),append($$anchor5,p_2)};if_block(node_14,$$render=>{(get$4(field).help||SETTING_CONFIG_INFO[get$4(field).key])&&$$render(consequent_6)})}var node_15=sibling(node_14,2);{var consequent_7=$$anchor5=>{var div_3=root_13$7(),node_16=child(div_3);{let $0=user_derived(
()=>!!($$props.localConfig.showSystemMessage??!0));Checkbox(node_16,{id:"showSystemMessage",get checked(){return get$4($0)},onCheckedChange:checked=>$$props.onConfigChange("showSystemMessage",!!checked)})}var node_17=sibling(node_16,2);Label(node_17,{for:"showSystemMessage",class:"cursor-pointer text-sm font-normal",children:($$anchor6,$$slotProps)=>{next$1();var text_3=text$8("Show system message in conversations");append($$anchor6,text_3)},$$slots:{default:!0}}),reset(div_3),append($$anchor5,div_3)};
@ -7122,7 +7139,7 @@ node_35=first_child(fragment_20);{var consequent_19=$$anchor6=>{var div_8=root_3
template_effect(()=>{set_attribute(label,"for",get$4(field).key),set_text(text_8,`${get$4(field).label??""} `)}),append($$anchor6,div_8)};if_block(node_35,$$render=>{get$4(field).type===SettingsFieldType.CHECKBOX&&$$render(consequent_19)},!0)}append($$anchor5,fragment_20)};if_block(node_18,$$render=>{get$4(field).type===SettingsFieldType.SELECT?$$render(consequent_16):$$render(alternate,!1)},!0)}append($$anchor4,fragment_9)};if_block(node_10,$$render=>{get$4(field).type===SettingsFieldType.TEXTAREA?
$$render(consequent_8):$$render(alternate_1,!1)},!0)}append($$anchor3,fragment_5)};if_block(node_1,$$render=>{get$4(field).type===SettingsFieldType.INPUT?$$render(consequent_4):$$render(alternate_2,!1)})}reset(div),append($$anchor2,div)}),append($$anchor,fragment),pop()}delegate(["click"]);var root_1$k=from_html("<!> Export conversations",1),root_3$l=from_html('<li class="truncate"> </li>'),root_4$a=from_html('<li class="italic"> </li>'),root_2$p=from_html('<div class="mt-4 grid overflow-x-auto \
rounded-lg border border-border/50 bg-muted/30 p-4"><h5 class="mb-2 text-sm font-medium"> </h5> <ul class="space-y-1 text-sm text-muted-foreground"><!> <!></ul></div>'),root_5$e=from_html("<!> Import conversations",1),root_7$d=from_html('<li class="truncate"> </li>'),root_8$a=from_html('<li class="italic"> </li>'),root_6$d=from_html('<div class="mt-4 grid overflow-x-auto rounded-lg border border-border/50 bg-muted/30 p-4"><h5 class="mb-2 text-sm font-medium"> </h5> <ul class="space-y-1 text-sm t\
ext-muted-foreground"><!> <!></ul></div>'),root_9$8=from_html("<!> Delete all conversations",1),root$y=from_html(`<div class="space-y-6"><div class="space-y-4"><div class="grid"><h4 class="mb-2 text-sm font-medium">Export Conversations</h4> <p class="mb-4 text-sm text-muted-foreground">Download all your conversations as a JSON file. This includes all messages, attachments, and
ext-muted-foreground"><!> <!></ul></div>'),root_9$9=from_html("<!> Delete all conversations",1),root$y=from_html(`<div class="space-y-6"><div class="space-y-4"><div class="grid"><h4 class="mb-2 text-sm font-medium">Export Conversations</h4> <p class="mb-4 text-sm text-muted-foreground">Download all your conversations as a JSON file. This includes all messages, attachments, and
conversation history.</p> <!> <!></div> <div class="grid border-t border-border/30 pt-4"><h4 class="mb-2 text-sm font-medium">Import Conversations</h4> <p class="mb-4 text-sm text-muted-foreground">Import one or more conversations from a previously exported JSON file. This will merge with
your existing conversations.</p> <!> <!></div> <div class="grid border-t border-border/30 pt-4"><h4 class="mb-2 text-sm font-medium text-destructive">Delete All Conversations</h4> <p class="mb-4 text-sm text-muted-foreground">Permanently delete all conversations and their messages. This action cannot be undone.
Consider exporting your conversations first if you want to keep a backup.</p> <!></div></div></div> <!> <!> <!>`,1);function ChatSettingsImportExportTab($$anchor,$$props){push$1($$props,!0);let exportedConversations=state$1(proxy([])),importedConversations=state$1(proxy([])),showExportSummary=state$1(!1),showImportSummary=state$1(!1),showExportDialog=state$1(!1),showImportDialog=state$1(!1),availableConversations=state$1(proxy([])),messageCountMap=state$1(proxy(new Map)),fullImportData=state$1(
@ -7138,7 +7155,7 @@ conv).name||"Untitled conversation"}`)),append($$anchor3,li2)});var node_4=sibli
ation${get$4(exportedConversations).length===1?"":"s"}`)),append($$anchor2,div_3)};if_block(node_2,$$render=>{get$4(showExportSummary)&&get$4(exportedConversations).length>0&&$$render(consequent_1)})}reset(div_2);var div_4=sibling(div_2,2),node_5=sibling(child(div_4),4);Button(node_5,{class:"w-full justify-start justify-self-start md:w-auto",onclick:handleImportClick,variant:"outline",children:($$anchor2,$$slotProps)=>{var fragment_2=root_5$e(),node_6=first_child(fragment_2);Upload(node_6,{class:"\
mr-2 h-4 w-4"}),next$1(),append($$anchor2,fragment_2)},$$slots:{default:!0}});var node_7=sibling(node_5,2);{var consequent_3=$$anchor2=>{var div_5=root_6$d(),h5_1=child(div_5),text_4=child(h5_1);reset(h5_1);var ul_1=sibling(h5_1,2),node_8=child(ul_1);each(node_8,17,()=>get$4(importedConversations).slice(0,10),conv=>conv.id,($$anchor3,conv)=>{var li_2=root_7$d(),text_5=child(li_2);reset(li_2),template_effect(()=>set_text(text_5,`• ${get$4(conv).name||"Untitled conversation"}`)),append($$anchor3,
li_2)});var node_9=sibling(node_8,2);{var consequent_2=$$anchor3=>{var li_3=root_8$a(),text_6=child(li_3);reset(li_3),template_effect(()=>set_text(text_6,`... and ${get$4(importedConversations).length-10} more`)),append($$anchor3,li_3)};if_block(node_9,$$render=>{get$4(importedConversations).length>10&&$$render(consequent_2)})}reset(ul_1),reset(div_5),template_effect(()=>set_text(text_4,`Imported ${get$4(importedConversations).length??""} conversation${get$4(importedConversations).length===1?"":
"s"}`)),append($$anchor2,div_5)};if_block(node_7,$$render=>{get$4(showImportSummary)&&get$4(importedConversations).length>0&&$$render(consequent_3)})}reset(div_4);var div_6=sibling(div_4,2),node_10=sibling(child(div_6),4);Button(node_10,{class:"text-destructive-foreground w-full justify-start justify-self-start bg-destructive hover:bg-destructive/80 md:w-auto",onclick:handleDeleteAllClick,variant:"destructive",children:($$anchor2,$$slotProps)=>{var fragment_3=root_9$8(),node_11=first_child(fragment_3);
"s"}`)),append($$anchor2,div_5)};if_block(node_7,$$render=>{get$4(showImportSummary)&&get$4(importedConversations).length>0&&$$render(consequent_3)})}reset(div_4);var div_6=sibling(div_4,2),node_10=sibling(child(div_6),4);Button(node_10,{class:"text-destructive-foreground w-full justify-start justify-self-start bg-destructive hover:bg-destructive/80 md:w-auto",onclick:handleDeleteAllClick,variant:"destructive",children:($$anchor2,$$slotProps)=>{var fragment_3=root_9$9(),node_11=first_child(fragment_3);
Trash_2(node_11,{class:"mr-2 h-4 w-4"}),next$1(),append($$anchor2,fragment_3)},$$slots:{default:!0}}),reset(div_6),reset(div_1),reset(div);var node_12=sibling(div,2);DialogConversationSelection(node_12,{get conversations(){return get$4(availableConversations)},get messageCountMap(){return get$4(messageCountMap)},mode:"export",onCancel:()=>set$1(showExportDialog,!1),onConfirm:handleExportConfirm,get open(){return get$4(showExportDialog)},set open($$value){set$1(showExportDialog,$$value,!0)}});var node_13=sibling(
node_12,2);DialogConversationSelection(node_13,{get conversations(){return get$4(availableConversations)},get messageCountMap(){return get$4(messageCountMap)},mode:"import",onCancel:()=>set$1(showImportDialog,!1),onConfirm:handleImportConfirm,get open(){return get$4(showImportDialog)},set open($$value){set$1(showImportDialog,$$value,!0)}});var node_14=sibling(node_13,2);DialogConfirmation(node_14,{title:"Delete all conversations",description:"Are you sure you want to delete all conversations? Th\
is action cannot be undone and will permanently remove all your conversations and messages.",confirmText:"Delete All",cancelText:"Cancel",variant:"destructive",get icon(){return Trash_2},onConfirm:handleDeleteAllConfirm,onCancel:handleDeleteAllCancel,get open(){return get$4(showDeleteDialog)},set open($$value){set$1(showDeleteDialog,$$value,!0)}}),append($$anchor,fragment),pop()}var root_1$j=from_html("<!> Custom",1);function ChatSettingsParameterSourceIndicator($$anchor,$$props){let className=prop(
@ -7167,7 +7184,7 @@ e",cancelText:"Cancel",variant:"destructive",get icon(){return Trash_2},onConfir
deleteWithForks)},set checked($$value){set$1(deleteWithForks,$$value,!0)}});var node_14=sibling(node_13,2);Label(node_14,{for:"delete-with-forks",class:"text-sm",children:($$anchor4,$$slotProps2)=>{next$1();var text_2=text$8("Also delete all forked conversations");append($$anchor4,text_2)},$$slots:{default:!0}}),reset(div_1),append($$anchor3,div_1)};if_block(node_12,$$render=>{get$4(selectedConversationHasDescendants)&&$$render(consequent_2)})}append($$anchor2,fragment_10)},$$slots:{default:!0}})}
var node_15=sibling(node_11,2);return DialogConfirmation(node_15,{title:"Edit Conversation Name",description:"",confirmText:"Save",cancelText:"Cancel",get icon(){return Pencil},onConfirm:handleConfirmEdit,onCancel:()=>{set$1(showEditDialog,!1),set$1(selectedConversation,null)},onKeydown:e=>{e.key==="Enter"&&(e.preventDefault(),e.stopImmediatePropagation(),handleConfirmEdit())},get open(){return get$4(showEditDialog)},set open($$value){set$1(showEditDialog,$$value,!0)},children:($$anchor2,$$slotProps)=>{
Input($$anchor2,{class:"text-foreground",placeholder:"Enter a new name",type:"text",get value(){return get$4(editedName)},set value($$value){set$1(editedName,$$value,!0)}})},$$slots:{default:!0}}),append($$anchor,fragment),pop($$exports)}delegate(["click"]);var root_3$i=from_html('<a class="flex shrink-0 items-center text-muted-foreground transition-colors hover:text-foreground"><!></a>'),root_4$8=from_html("<p>See parent conversation</p>"),root_2$m=from_html("<!> <!>",1),root_7$b=from_html('<di\
v class="stop-button flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:text-foreground svelte-76ksb2" role="button" tabindex="0" aria-label="Stop generation"><!> <!></div>'),root_8$9=from_html("<p>Stop generation</p>"),root_6$c=from_html("<!> <!>",1),root_9$7=from_html('<div class="actions flex items-center"><!></div>'),root$v=from_html('<button><div class="flex min-w-0 flex-1 items-center gap-2"><!> <!> <span class="truncate \
v class="stop-button flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:text-foreground svelte-76ksb2" role="button" tabindex="0" aria-label="Stop generation"><!> <!></div>'),root_8$9=from_html("<p>Stop generation</p>"),root_6$c=from_html("<!> <!>",1),root_9$8=from_html('<div class="actions flex items-center"><!></div>'),root$v=from_html('<button><div class="flex min-w-0 flex-1 items-center gap-2"><!> <!> <span class="truncate \
text-sm font-medium"> </span></div> <!></button>');function ChatSidebarConversationItem($$anchor,$$props){push$1($$props,!0);let isActive=prop($$props,"isActive",3,!1),depth=prop($$props,"depth",3,0),renderActionsDropdown=state$1(!1),dropdownOpen=state$1(!1),isLoading2=user_derived(()=>getAllLoadingChats().includes($$props.conversation.id));function handleEdit(event2){event2.stopPropagation(),$$props.onEdit?.($$props.conversation.id)}function handleDelete2(event2){event2.stopPropagation(),$$props.
onDelete?.($$props.conversation.id)}function handleStop(event2){event2.stopPropagation(),$$props.onStop?.($$props.conversation.id)}function handleGlobalEditEvent(event2){event2.detail.conversationId===$$props.conversation.id&&isActive()&&handleEdit(event2)}function handleMouseLeave(){get$4(dropdownOpen)||set$1(renderActionsDropdown,!1)}function handleMouseOver(){set$1(renderActionsDropdown,!0)}function handleSelect(){$$props.onSelect?.($$props.conversation.id)}user_effect(()=>{get$4(dropdownOpen)||
set$1(renderActionsDropdown,!1)}),onMount$1(()=>(document.addEventListener("edit-active-conversation",handleGlobalEditEvent),()=>{document.removeEventListener("edit-active-conversation",handleGlobalEditEvent)}));var button=root$v();button.__click=handleSelect,button.__mouseover=handleMouseOver;var div=child(button);let styles2;var node2=child(div);{var consequent=$$anchor2=>{var fragment=comment$2(),node_1=first_child(fragment);component(node_1,()=>Root$5,($$anchor3,Tooltip_Root)=>{Tooltip_Root(
@ -7175,7 +7192,7 @@ $$anchor3,{children:($$anchor4,$$slotProps)=>{var fragment_1=root_2$m(),node_2=f
node_4,()=>Tooltip_content,($$anchor5,Tooltip_Content)=>{Tooltip_Content($$anchor5,{children:($$anchor6,$$slotProps2)=>{var p2=root_4$8();append($$anchor6,p2)},$$slots:{default:!0}})}),append($$anchor4,fragment_1)},$$slots:{default:!0}})}),append($$anchor2,fragment)};if_block(node2,$$render=>{depth()>0&&$$render(consequent)})}var node_5=sibling(node2,2);{var consequent_1=$$anchor2=>{var fragment_2=comment$2(),node_6=first_child(fragment_2);component(node_6,()=>Root$5,($$anchor3,Tooltip_Root_1)=>{
Tooltip_Root_1($$anchor3,{children:($$anchor4,$$slotProps)=>{var fragment_3=root_6$c(),node_7=first_child(fragment_3);component(node_7,()=>Tooltip_trigger,($$anchor5,Tooltip_Trigger_1)=>{Tooltip_Trigger_1($$anchor5,{children:($$anchor6,$$slotProps2)=>{var div_1=root_7$b();div_1.__click=handleStop,div_1.__keydown=e=>e.key==="Enter"&&handleStop(e);var node_8=child(div_1);Loader_circle(node_8,{class:"loading-icon h-3.5 w-3.5 animate-spin"});var node_9=sibling(node_8,2);Square(node_9,{class:"stop-ic\
on hidden h-3 w-3 fill-current text-destructive"}),reset(div_1),append($$anchor6,div_1)},$$slots:{default:!0}})});var node_10=sibling(node_7,2);component(node_10,()=>Tooltip_content,($$anchor5,Tooltip_Content_1)=>{Tooltip_Content_1($$anchor5,{children:($$anchor6,$$slotProps2)=>{var p_1=root_8$9();append($$anchor6,p_1)},$$slots:{default:!0}})}),append($$anchor4,fragment_3)},$$slots:{default:!0}})}),append($$anchor2,fragment_2)};if_block(node_5,$$render=>{get$4(isLoading2)&&$$render(consequent_1)})}
var span=sibling(node_5,2);span.__click=function(...$$args){$$props.handleMobileSidebarItemClick?.apply(this,$$args)};var text2=child(span,!0);reset(span),reset(div);var node_11=sibling(div,2);{var consequent_2=$$anchor2=>{var div_2=root_9$7(),node_12=child(div_2);{let $0=user_derived(()=>[{icon:Pencil,label:"Edit",onclick:handleEdit,shortcut:["shift","cmd","e"]},{icon:Download,label:"Export",onclick:e=>{e.stopPropagation(),conversationsStore.downloadConversation($$props.conversation.id)},shortcut:[
var span=sibling(node_5,2);span.__click=function(...$$args){$$props.handleMobileSidebarItemClick?.apply(this,$$args)};var text2=child(span,!0);reset(span),reset(div);var node_11=sibling(div,2);{var consequent_2=$$anchor2=>{var div_2=root_9$8(),node_12=child(div_2);{let $0=user_derived(()=>[{icon:Pencil,label:"Edit",onclick:handleEdit,shortcut:["shift","cmd","e"]},{icon:Download,label:"Export",onclick:e=>{e.stopPropagation(),conversationsStore.downloadConversation($$props.conversation.id)},shortcut:[
"shift","cmd","s"]},{icon:Trash_2,label:"Delete",onclick:handleDelete2,variant:"destructive",shortcut:["shift","cmd","d"],separator:!0}]);DropdownMenuActions(node_12,{get triggerIcon(){return Ellipsis},triggerTooltip:"More actions",get actions(){return get$4($0)},get open(){return get$4(dropdownOpen)},set open($$value){set$1(dropdownOpen,$$value,!0)}})}reset(div_2),append($$anchor2,div_2)};if_block(node_11,$$render=>{get$4(renderActionsDropdown)&&$$render(consequent_2)})}reset(button),template_effect(
()=>{set_class(button,1,`group flex min-h-9 w-full cursor-pointer items-center justify-between space-x-3 rounded-lg py-1.5 text-left transition-colors hover:bg-foreground/10 ${isActive()?"bg-foreground/5 text-accent-foreground":""} px-3`,"svelte-76ksb2"),styles2=set_style(div,"",styles2,{"padding-left":`${depth()*FORK_TREE_DEPTH_PADDING}px`}),set_text(text2,$$props.conversation.name)}),event("mouseleave",button,handleMouseLeave),append($$anchor,button),pop()}delegate(["click","mouseover","keydow\
n"]);const emptyOptions$7={};function toString$1(value,options){const settings=emptyOptions$7,includeImageAlt=typeof settings.includeImageAlt=="boolean"?settings.includeImageAlt:!0,includeHtml=typeof settings.includeHtml=="boolean"?settings.includeHtml:!0;return one$2(value,includeImageAlt,includeHtml)}function one$2(value,includeImageAlt,includeHtml){if(node(value)){if("value"in value)return value.type==="html"&&!includeHtml?"":value.value;if(includeImageAlt&&"alt"in value&&value.alt)return value.
@ -10681,7 +10698,7 @@ $$render=>{get$4(initialLoadComplete)?$$render(alternate,!1):$$render(consequent
id).status!==HealthCheckStatus.ERROR)),hasEnabledMcpServers=user_derived(()=>get$4(enabledMcpServersForChat).length>0),extraServersCount=user_derived(()=>Math.max(0,get$4(healthyEnabledMcpServers).length-MAX_DISPLAYED_MCP_AVATARS)),mcpFavicons=user_derived(()=>get$4(healthyEnabledMcpServers).slice(0,MAX_DISPLAYED_MCP_AVATARS).map(s2=>({id:s2.id,url:mcpStore.getServerFavicon(s2.id)})).filter(f=>f.url!==null));var fragment=comment$2(),node2=first_child(fragment);{var consequent_1=$$anchor2=>{var div=root_1$c(),
div_1=child(div);each(div_1,21,()=>get$4(mcpFavicons),favicon=>favicon.id,($$anchor3,favicon)=>{var div_2=root_2$g(),img=child(div_2);reset(div_2),template_effect(()=>set_attribute(img,"src",get$4(favicon).url)),event("error",img,e=>{e.currentTarget.style.display="none"}),replay_events(img),append($$anchor3,div_2)}),reset(div_1);var node_1=sibling(div_1,2);{var consequent=$$anchor3=>{var span=root_3$d(),text2=child(span);reset(span),template_effect(()=>set_text(text2,`+${get$4(extraServersCount)??
""}`)),append($$anchor3,span)};if_block(node_1,$$render=>{get$4(extraServersCount)>0&&$$render(consequent)})}reset(div),template_effect($0=>set_class(div,1,$0),[()=>clsx(cn$1("inline-flex items-center gap-1.5",className()))]),append($$anchor2,div)};if_block(node2,$$render=>{get$4(hasEnabledMcpServers)&&get$4(mcpFavicons).length>0&&$$render(consequent_1)})}append($$anchor,fragment),pop()}var root_3$c=from_html('<button type="button" class="inline-flex cursor-pointer items-center rounded-sm py-1 d\
isabled:cursor-not-allowed disabled:opacity-60" aria-label="MCP Servers"><!></button>'),root_6$a=from_html("<!> <span>Manage MCP Servers</span>",1),root_9$6=from_html('<img alt="" class="h-4 w-4 shrink-0 rounded-sm"/>'),root_10$6=from_html('<span class="shrink-0 rounded bg-destructive/15 px-1.5 py-0.5 text-xs text-destructive">Error</span>'),root_8$7=from_html('<button type="button" class="flex w-full items-center justify-between gap-2 px-2 py-2 text-left transition-colors hover:bg-accent disabl\
isabled:cursor-not-allowed disabled:opacity-60" aria-label="MCP Servers"><!></button>'),root_6$a=from_html("<!> <span>Manage MCP Servers</span>",1),root_9$7=from_html('<img alt="" class="h-4 w-4 shrink-0 rounded-sm"/>'),root_10$6=from_html('<span class="shrink-0 rounded bg-destructive/15 px-1.5 py-0.5 text-xs text-destructive">Error</span>'),root_8$7=from_html('<button type="button" class="flex w-full items-center justify-between gap-2 px-2 py-2 text-left transition-colors hover:bg-accent disabl\
ed:cursor-not-allowed disabled:opacity-50"><div class="flex min-w-0 flex-1 items-center gap-2"><!> <span class="truncate text-sm"> </span> <!></div> <!></button>'),root_7$9=from_html('<div class="max-h-64 overflow-y-auto"></div>'),root_2$f=from_html("<!> <!>",1);function McpServersSelector($$anchor,$$props){push$1($$props,!0);let className=prop($$props,"class",3,""),disabled=prop($$props,"disabled",3,!1),searchQuery=state$1(""),mcpServers=user_derived(()=>mcpStore.getServersSorted().filter(s2=>s2.
enabled)),hasMcpServers=user_derived(()=>get$4(mcpServers).length>0),enabledMcpServersForChat=user_derived(()=>get$4(mcpServers).filter(s2=>conversationsStore.isMcpServerEnabledForChat(s2.id)&&s2.url.trim())),healthyEnabledMcpServers=user_derived(()=>get$4(enabledMcpServersForChat).filter(s2=>mcpStore.getHealthCheckState(s2.id).status!==HealthCheckStatus.ERROR)),hasEnabledMcpServers=user_derived(()=>get$4(enabledMcpServersForChat).length>0),mcpFavicons=user_derived(()=>get$4(healthyEnabledMcpServers).
slice(0,3).map(s2=>({id:s2.id,url:mcpStore.getServerFavicon(s2.id)})).filter(f=>f.url!==null)),filteredMcpServers=user_derived(()=>{const query=get$4(searchQuery).toLowerCase().trim();return query?get$4(mcpServers).filter(s2=>{const name=getServerLabel(s2).toLowerCase(),url2=s2.url.toLowerCase();return name.includes(query)||url2.includes(query)}):get$4(mcpServers)});function getServerLabel(server){return mcpStore.getServerLabel(server)}function handleDropdownOpen(open2){open2&&mcpStore.runHealthChecksForServers(
@ -10690,72 +10707,74 @@ get$4(mcpServers))}function isServerEnabledForChat(serverId){return conversation
disabled=disabled()),append($$anchor6,button)},$$slots:{default:!0}})});var node_4=sibling(node_2,2);component(node_4,()=>Dropdown_menu_content,($$anchor5,DropdownMenu_Content)=>{DropdownMenu_Content($$anchor5,{align:"start",class:"w-72 pt-0",children:($$anchor6,$$slotProps2)=>{{const footer2=$$anchor7=>{var fragment_4=comment$2(),node_5=first_child(fragment_4);component(node_5,()=>Dropdown_menu_item,($$anchor8,DropdownMenu_Item)=>{DropdownMenu_Item($$anchor8,{class:"flex cursor-pointer items-ce\
nter gap-2",get onclick(){return $$props.onSettingsClick},children:($$anchor9,$$slotProps3)=>{var fragment_5=root_6$a(),node_6=first_child(fragment_5);Settings$1(node_6,{class:"h-4 w-4"}),next$1(2),append($$anchor9,fragment_5)},$$slots:{default:!0}})}),append($$anchor7,fragment_4)};let $0=user_derived(()=>get$4(filteredMcpServers).length===0);DropdownMenuSearchable($$anchor6,{placeholder:"Search servers...",emptyMessage:"No servers found",get isEmpty(){return get$4($0)},get searchValue(){return get$4(
searchQuery)},set searchValue($$value){set$1(searchQuery,$$value,!0)},footer:footer2,children:($$anchor7,$$slotProps3)=>{var div=root_7$9();each(div,21,()=>get$4(filteredMcpServers),server=>server.id,($$anchor8,server)=>{const healthState=user_derived(()=>mcpStore.getHealthCheckState(get$4(server).id)),hasError=user_derived(()=>get$4(healthState).status===HealthCheckStatus.ERROR),isEnabledForChat=user_derived(()=>isServerEnabledForChat(get$4(server).id));var button_1=root_8$7();button_1.__click=
()=>!get$4(hasError)&&toggleServerForChat(get$4(server).id);var div_1=child(button_1),node_7=child(div_1);{var consequent=$$anchor9=>{var img=root_9$6();template_effect($02=>set_attribute(img,"src",$02),[()=>mcpStore.getServerFavicon(get$4(server).id)]),event("error",img,e=>{e.currentTarget.style.display="none"}),replay_events(img),append($$anchor9,img)};if_block(node_7,$$render=>{mcpStore.getServerFavicon(get$4(server).id)&&$$render(consequent)})}var span=sibling(node_7,2),text2=child(span,!0);
()=>!get$4(hasError)&&toggleServerForChat(get$4(server).id);var div_1=child(button_1),node_7=child(div_1);{var consequent=$$anchor9=>{var img=root_9$7();template_effect($02=>set_attribute(img,"src",$02),[()=>mcpStore.getServerFavicon(get$4(server).id)]),event("error",img,e=>{e.currentTarget.style.display="none"}),replay_events(img),append($$anchor9,img)};if_block(node_7,$$render=>{mcpStore.getServerFavicon(get$4(server).id)&&$$render(consequent)})}var span=sibling(node_7,2),text2=child(span,!0);
reset(span);var node_8=sibling(span,2);{var consequent_1=$$anchor9=>{var span_1=root_10$6();append($$anchor9,span_1)};if_block(node_8,$$render=>{get$4(hasError)&&$$render(consequent_1)})}reset(div_1);var node_9=sibling(div_1,2);Switch(node_9,{get checked(){return get$4(isEnabledForChat)},get disabled(){return get$4(hasError)},onclick:e=>e.stopPropagation(),onCheckedChange:()=>toggleServerForChat(get$4(server).id)}),reset(button_1),template_effect($02=>{button_1.disabled=get$4(hasError),set_text(
text2,$02)},[()=>getServerLabel(get$4(server))]),append($$anchor8,button_1)}),reset(div),append($$anchor7,div)},$$slots:{footer:!0,default:!0}})}},$$slots:{default:!0}})}),append($$anchor4,fragment_2)},$$slots:{default:!0}})}),append($$anchor2,fragment_1)};if_block(node2,$$render=>{get$4(hasMcpServers)&&get$4(hasEnabledMcpServers)&&get$4(mcpFavicons).length>0&&$$render(consequent_2)})}append($$anchor,fragment),pop()}delegate(["click"]);var root_3$b=from_html("<!> Tools",1),root_5$a=from_html("<!\
> Resources",1),root_7$8=from_html("<!> Prompts",1),root_9$5=from_html("<!> Logging",1),root_11$3=from_html("<!> Completions",1),root_13$6=from_html("<!> Tasks",1),root_1$b=from_html("<!> <!> <!> <!> <!> <!>",1);function McpCapabilitiesBadges($$anchor,$$props){push$1($$props,!0);var fragment=comment$2(),node2=first_child(fragment);{var consequent_6=$$anchor2=>{var fragment_1=root_1$b(),node_1=first_child(fragment_1);{var consequent=$$anchor3=>{Badge($$anchor3,{variant:"outline",class:"h-5 gap-1 \
> Resources",1),root_7$8=from_html("<!> Prompts",1),root_9$6=from_html("<!> Logging",1),root_11$3=from_html("<!> Completions",1),root_13$6=from_html("<!> Tasks",1),root_1$b=from_html("<!> <!> <!> <!> <!> <!>",1);function McpCapabilitiesBadges($$anchor,$$props){push$1($$props,!0);var fragment=comment$2(),node2=first_child(fragment);{var consequent_6=$$anchor2=>{var fragment_1=root_1$b(),node_1=first_child(fragment_1);{var consequent=$$anchor3=>{Badge($$anchor3,{variant:"outline",class:"h-5 gap-1 \
bg-green-50 px-1.5 text-[10px] dark:bg-green-950",children:($$anchor4,$$slotProps)=>{var fragment_3=root_3$b(),node_2=first_child(fragment_3);Wrench(node_2,{class:"h-3 w-3 text-green-600 dark:text-green-400"}),next$1(),append($$anchor4,fragment_3)},$$slots:{default:!0}})};if_block(node_1,$$render=>{$$props.capabilities.server.tools&&$$render(consequent)})}var node_3=sibling(node_1,2);{var consequent_1=$$anchor3=>{Badge($$anchor3,{variant:"outline",class:"h-5 gap-1 bg-blue-50 px-1.5 text-[10px] d\
ark:bg-blue-950",children:($$anchor4,$$slotProps)=>{var fragment_5=root_5$a(),node_4=first_child(fragment_5);Database(node_4,{class:"h-3 w-3 text-blue-600 dark:text-blue-400"}),next$1(),append($$anchor4,fragment_5)},$$slots:{default:!0}})};if_block(node_3,$$render=>{$$props.capabilities.server.resources&&$$render(consequent_1)})}var node_5=sibling(node_3,2);{var consequent_2=$$anchor3=>{Badge($$anchor3,{variant:"outline",class:"h-5 gap-1 bg-purple-50 px-1.5 text-[10px] dark:bg-purple-950",children:($$anchor4,$$slotProps)=>{
var fragment_7=root_7$8(),node_6=first_child(fragment_7);Message_square(node_6,{class:"h-3 w-3 text-purple-600 dark:text-purple-400"}),next$1(),append($$anchor4,fragment_7)},$$slots:{default:!0}})};if_block(node_5,$$render=>{$$props.capabilities.server.prompts&&$$render(consequent_2)})}var node_7=sibling(node_5,2);{var consequent_3=$$anchor3=>{Badge($$anchor3,{variant:"outline",class:"h-5 gap-1 bg-orange-50 px-1.5 text-[10px] dark:bg-orange-950",children:($$anchor4,$$slotProps)=>{var fragment_9=root_9$5(),
var fragment_7=root_7$8(),node_6=first_child(fragment_7);Message_square(node_6,{class:"h-3 w-3 text-purple-600 dark:text-purple-400"}),next$1(),append($$anchor4,fragment_7)},$$slots:{default:!0}})};if_block(node_5,$$render=>{$$props.capabilities.server.prompts&&$$render(consequent_2)})}var node_7=sibling(node_5,2);{var consequent_3=$$anchor3=>{Badge($$anchor3,{variant:"outline",class:"h-5 gap-1 bg-orange-50 px-1.5 text-[10px] dark:bg-orange-950",children:($$anchor4,$$slotProps)=>{var fragment_9=root_9$6(),
node_8=first_child(fragment_9);File_text(node_8,{class:"h-3 w-3 text-orange-600 dark:text-orange-400"}),next$1(),append($$anchor4,fragment_9)},$$slots:{default:!0}})};if_block(node_7,$$render=>{$$props.capabilities.server.logging&&$$render(consequent_3)})}var node_9=sibling(node_7,2);{var consequent_4=$$anchor3=>{Badge($$anchor3,{variant:"outline",class:"h-5 gap-1 bg-cyan-50 px-1.5 text-[10px] dark:bg-cyan-950",children:($$anchor4,$$slotProps)=>{var fragment_11=root_11$3(),node_10=first_child(fragment_11);
Sparkles(node_10,{class:"h-3 w-3 text-cyan-600 dark:text-cyan-400"}),next$1(),append($$anchor4,fragment_11)},$$slots:{default:!0}})};if_block(node_9,$$render=>{$$props.capabilities.server.completions&&$$render(consequent_4)})}var node_11=sibling(node_9,2);{var consequent_5=$$anchor3=>{Badge($$anchor3,{variant:"outline",class:"h-5 gap-1 bg-pink-50 px-1.5 text-[10px] dark:bg-pink-950",children:($$anchor4,$$slotProps)=>{var fragment_13=root_13$6(),node_12=first_child(fragment_13);List_checks(node_12,
{class:"h-3 w-3 text-pink-600 dark:text-pink-400"}),next$1(),append($$anchor4,fragment_13)},$$slots:{default:!0}})};if_block(node_11,$$render=>{$$props.capabilities.server.tasks&&$$render(consequent_5)})}append($$anchor2,fragment_1)};if_block(node2,$$render=>{$$props.capabilities&&$$render(consequent_6)})}append($$anchor,fragment),pop()}var root_6$9=from_html('<span class="ml-1"> </span>'),root_3$a=from_html("<!> <span> </span> <!>",1),root_8$6=from_html('<div><span class="shrink-0 text-muted-fo\
reground"> </span> <!> <span class="break-all"> </span></div>'),root_7$7=from_html('<div class="max-h-64 space-y-0.5 overflow-y-auto rounded bg-muted/50 p-2 font-mono text-[10px]"></div>'),root_2$e=from_html('<div class="space-y-2"><!></div> <!>',1);function McpConnectionLogs($$anchor,$$props){push$1($$props,!0);let defaultExpanded=prop($$props,"defaultExpanded",3,!1),isExpanded=user_derived(defaultExpanded);var fragment=comment$2(),node2=first_child(fragment);{var consequent_2=$$anchor2=>{var fragment_1=comment$2(),
node_1=first_child(fragment_1);component(node_1,()=>Collapsible,($$anchor3,Collapsible_Root)=>{Collapsible_Root($$anchor3,{get class(){return $$props.class},get open(){return get$4(isExpanded)},set open($$value){set$1(isExpanded,$$value)},children:($$anchor4,$$slotProps)=>{var fragment_2=root_2$e(),div=first_child(fragment_2),node_2=child(div);component(node_2,()=>Collapsible_trigger,($$anchor5,Collapsible_Trigger)=>{Collapsible_Trigger($$anchor5,{class:"flex w-full items-center gap-1 text-xs te\
xt-muted-foreground hover:text-foreground",children:($$anchor6,$$slotProps2)=>{var fragment_3=root_3$a(),node_3=first_child(fragment_3);{var consequent=$$anchor7=>{Chevron_down($$anchor7,{class:"h-3.5 w-3.5"})},alternate=$$anchor7=>{Chevron_right($$anchor7,{class:"h-3.5 w-3.5"})};if_block(node_3,$$render=>{get$4(isExpanded)?$$render(consequent):$$render(alternate,!1)})}var span=sibling(node_3,2),text2=child(span);reset(span);var node_4=sibling(span,2);{var consequent_1=$$anchor7=>{var span_1=root_6$9(),
text_1=child(span_1);reset(span_1),template_effect(()=>set_text(text_1,`· Connected in ${$$props.connectionTimeMs??""}ms`)),append($$anchor7,span_1)};if_block(node_4,$$render=>{$$props.connectionTimeMs!==void 0&&$$render(consequent_1)})}template_effect(()=>set_text(text2,`Connection Log (${$$props.logs.length??""})`)),append($$anchor6,fragment_3)},$$slots:{default:!0}})}),reset(div);var node_5=sibling(div,2);component(node_5,()=>Collapsible_content,($$anchor5,Collapsible_Content)=>{Collapsible_Content(
$$anchor5,{class:"mt-2",children:($$anchor6,$$slotProps2)=>{var div_1=root_7$7();each(div_1,21,()=>$$props.logs,log=>log.timestamp.getTime()+log.message,($$anchor7,log)=>{const Icon2=user_derived(()=>getMcpLogLevelIcon(get$4(log).level));var div_2=root_8$6(),span_2=child(div_2),text_2=child(span_2,!0);reset(span_2);var node_6=sibling(span_2,2);component(node_6,()=>get$4(Icon2),($$anchor8,Icon_1)=>{Icon_1($$anchor8,{class:"mt-0.5 h-3 w-3 shrink-0"})});var span_3=sibling(node_6,2),text_3=child(span_3,
!0);reset(span_3),reset(div_2),template_effect(($0,$1)=>{set_class(div_2,1,$0),set_text(text_2,$1),set_text(text_3,get$4(log).message)},[()=>clsx(cn$1("flex items-start gap-1.5",getMcpLogLevelClass(get$4(log).level))),()=>formatTime(get$4(log).timestamp)]),append($$anchor7,div_2)}),reset(div_1),append($$anchor6,div_1)},$$slots:{default:!0}})}),append($$anchor4,fragment_2)},$$slots:{default:!0}})}),append($$anchor2,fragment_1)};if_block(node2,$$render=>{$$props.logs.length>0&&$$render(consequent_2)})}
append($$anchor,fragment),pop()}var root_1$a=from_html('<p class="mt-1.5 text-xs text-destructive"> </p>'),root_3$9=from_html('<span class="inline-flex gap-0.75 text-xs text-muted-foreground/60">(Run <pre>llama-server</pre> with <pre>--webui-mcp-proxy</pre> flag)</span>'),root_2$d=from_html('<label><!> <span><span class="text-xs text-muted-foreground">Use llama-server proxy</span> <br/> <!></span></label>'),root$k=from_html('<div class="grid gap-3"><div><label class="mb-2 block text-xs font-medi\
um">Server URL <span class="text-destructive">*</span></label> <!> <!> <!></div> <!></div>');function McpServerForm($$anchor,$$props){push$1($$props,!0);let useProxy=prop($$props,"useProxy",3,!1),urlError=prop($$props,"urlError",3,null),id2=prop($$props,"id",3,"server"),isWebSocket=user_derived(()=>$$props.url.toLowerCase().startsWith(UrlProtocol.WEBSOCKET)||$$props.url.toLowerCase().startsWith(UrlProtocol.WEBSOCKET_SECURE)),headerPairs=user_derived(()=>parseHeadersToArray($$props.headers));function updateHeaderPairs(newPairs){
set$1(headerPairs,newPairs),$$props.onHeadersChange(serializeHeaders(newPairs))}var div=root$k(),div_1=child(div),label=child(div_1),node2=sibling(label,2);{let $0=user_derived(()=>urlError()?"border-destructive":"");Input(node2,{get id(){return`server-url-${id2()??""}`},type:"url",get placeholder(){return MCP_SERVER_URL_PLACEHOLDER},get value(){return $$props.url},oninput:e=>$$props.onUrlChange(e.currentTarget.value),get class(){return get$4($0)}})}var node_1=sibling(node2,2);{var consequent=$$anchor2=>{
var p2=root_1$a(),text2=child(p2,!0);reset(p2),template_effect(()=>set_text(text2,urlError())),append($$anchor2,p2)};if_block(node_1,$$render=>{urlError()&&$$render(consequent)})}var node_2=sibling(node_1,2);{var consequent_2=$$anchor2=>{var label_1=root_2$d();let classes;var node_3=child(label_1);{let $0=user_derived(()=>!mcpStore.isProxyAvailable);Switch(node_3,{class:"mt-1",get id(){return`use-proxy-${id2()??""}`},get checked(){return useProxy()},get disabled(){return get$4($0)},onCheckedChange:checked=>$$props.
onUseProxyChange?.(checked)})}var span=sibling(node_3,2),node_4=sibling(child(span),4);{var consequent_1=$$anchor3=>{var span_1=root_3$9();append($$anchor3,span_1)};if_block(node_4,$$render=>{mcpStore.isProxyAvailable||$$render(consequent_1)})}reset(span),reset(label_1),template_effect(()=>classes=set_class(label_1,1,"mt-3 flex items-start gap-2",null,classes,{"cursor-pointer":mcpStore.isProxyAvailable,"opacity-80":!mcpStore.isProxyAvailable})),append($$anchor2,label_1)};if_block(node_2,$$render=>{
!get$4(isWebSocket)&&$$props.onUseProxyChange&&$$render(consequent_2)})}reset(div_1);var node_5=sibling(div_1,2);KeyValuePairs(node_5,{class:"mt-2",get pairs(){return get$4(headerPairs)},onPairsChange:updateHeaderPairs,keyPlaceholder:"Header name",valuePlaceholder:"Value",addButtonLabel:"Add",emptyMessage:"No custom headers configured.",sectionLabel:"Custom Headers",sectionLabelOptional:!0}),reset(div),template_effect(()=>set_attribute(label,"for",`server-url-${id2()??""}`)),append($$anchor,div),
pop()}var root$j=from_svg('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 174 174" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1"><g id="shape-320b5b95-d08d-8089-8007-585a8e498184"><defs><clipPath id="frame-clip-320b5b95-d08d-8089-8007-585a8e498184-render-1" class="frame-clip frame-clip-def"><rect rx="0" ry="0" x="0" y="0" width="174.00000000000045" height="174" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)"></rect></clipPath></defs><g \
class="frame-container-wrapper"><g class="frame-container-blur"><g class="frame-container-shadows"><g clip-path="url(#frame-clip-320b5b95-d08d-8089-8007-585a8e498184-render-1)" fill="none"><g class="fills" id="fills-320b5b95-d08d-8089-8007-585a8e498184"><rect rx="0" ry="0" x="0" y="0" width="174.00000000000045" height="174" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" class="frame-background"></rect></g><g class="frame-children"><g id="shape-320b5b95-d08d-8089-8\
007-585a974337b1"><g class="fills" id="fills-320b5b95-d08d-8089-8007-585a974337b1"><path d="M15.5587158203125,81.5927734375L83.44091796875,13.7105712890625C92.813720703125,4.3380126953125,108.0096435546875,4.3380126953125,117.3817138671875,13.7105712890625L117.3817138671875,13.7105712890625C126.7547607421875,23.08306884765625,126.7547607421875,38.27911376953125,117.3817138671875,47.65167236328125L66.1168212890625,98.9169921875" fill="none" stroke-linecap="round" style="fill: none;"></path></g><g\
fill="none" stroke-linecap="round" id="strokes-b954dcef-3e3e-8015-8007-585acd4382b6-320b5b95-d08d-8089-8007-585a974337b1" class="strokes"><g class="stroke-shape"><path d="M15.5587158203125,81.5927734375L83.44091796875,13.7105712890625C92.813720703125,4.3380126953125,108.0096435546875,4.3380126953125,117.3817138671875,13.7105712890625L117.3817138671875,13.7105712890625C126.7547607421875,23.08306884765625,126.7547607421875,38.27911376953125,117.3817138671875,47.65167236328125L66.1168212890625,98.\
9169921875" style="fill: none; stroke-width: 12; stroke: currentColor; stroke-opacity: 1;"></path></g></g></g><g id="shape-320b5b95-d08d-8089-8007-585a974337b2"><g class="fills" id="fills-320b5b95-d08d-8089-8007-585a974337b2"><path d="M66.5587158203125,98.26885986328125L117.1165771484375,47.7105712890625C126.489501953125,38.3380126953125,141.6854248046875,38.3380126953125,151.0584716796875,47.7105712890625L151.4114990234375,48.0640869140625C160.7845458984375,57.43670654296875,160.7845458984375,7\
2.6326904296875,151.4114990234375,82.00518798828125L90.018310546875,143.39886474609375C86.8941650390625,146.52288818359375,86.8941650390625,151.587890625,90.018310546875,154.71185302734375L102.62451171875,167.31890869140625" fill="none" stroke-linecap="round" style="fill: none;"></path></g><g fill="none" stroke-linecap="round" id="strokes-b954dcef-3e3e-8015-8007-585acd447743-320b5b95-d08d-8089-8007-585a974337b2" class="strokes"><g class="stroke-shape"><path d="M66.5587158203125,98.26885986328125\
L117.1165771484375,47.7105712890625C126.489501953125,38.3380126953125,141.6854248046875,38.3380126953125,151.0584716796875,47.7105712890625L151.4114990234375,48.0640869140625C160.7845458984375,57.43670654296875,160.7845458984375,72.6326904296875,151.4114990234375,82.00518798828125L90.018310546875,143.39886474609375C86.8941650390625,146.52288818359375,86.8941650390625,151.587890625,90.018310546875,154.71185302734375L102.62451171875,167.31890869140625" style="fill: none; stroke-width: 12; stroke: \
currentColor; stroke-opacity: 1;"></path></g></g></g><g id="shape-320b5b95-d08d-8089-8007-585a974337b3"><g class="fills" id="fills-320b5b95-d08d-8089-8007-585a974337b3"><path d="M99.79296875,30.68115234375L49.588134765625,80.8857421875C40.215576171875,90.258056640625,40.215576171875,105.45404052734375,49.588134765625,114.82708740234375L49.588134765625,114.82708740234375C58.9608154296875,124.19903564453125,74.1566162109375,124.19903564453125,83.529296875,114.82708740234375L133.7340087890625,64.62\
225341796875" fill="none" stroke-linecap="round" style="fill: none;"></path></g><g fill="none" stroke-linecap="round" id="strokes-b954dcef-3e3e-8015-8007-585acd44c5c9-320b5b95-d08d-8089-8007-585a974337b3" class="strokes"><g class="stroke-shape"><path d="M99.79296875,30.68115234375L49.588134765625,80.8857421875C40.215576171875,90.258056640625,40.215576171875,105.45404052734375,49.588134765625,114.82708740234375L49.588134765625,114.82708740234375C58.9608154296875,124.19903564453125,74.156616210937\
5,124.19903564453125,83.529296875,114.82708740234375L133.7340087890625,64.62225341796875" style="fill: none; stroke-width: 12; stroke: currentColor; stroke-opacity: 1;"></path></g></g></g></g></g></g></g></g></g></svg>');function McpLogo($$anchor,$$props){let className=prop($$props,"class",3,""),style2=prop($$props,"style",3,"");var svg2=root$j();template_effect(()=>{set_class(svg2,0,clsx(className())),set_style(svg2,style2())}),append($$anchor,svg2)}var root_4$4=from_html('<p class="text-xs tex\
t-destructive"> </p>'),root_5$9=from_html('<p class="line-clamp-2 text-xs text-muted-foreground"> </p>'),root_6$8=from_html('<div class="space-y-2"><div class="flex items-center gap-2"><!> <!></div> <div class="flex flex-wrap gap-1.5"><!> <!> <!></div></div> <div class="space-y-1.5"><div class="flex items-center gap-2"><!> <!></div></div>',1),root_7$6=from_html("<!> <!> <!>",1),root_13$5=from_html('<div class="flex flex-wrap items-center gap-1"><span class="text-[10px] text-muted-foreground"> </\
span></div>'),root_3$8=from_html('<!> <!> <!> <div class="grid gap-3"><!></div> <div class="flex justify-between gap-4"><!> <!></div>',1),root$i=from_html("<!> <!>",1);function McpServerCard($$anchor,$$props){push$1($$props,!0);let healthState=user_derived(()=>mcpStore.getHealthCheckState($$props.server.id)),displayName=user_derived(()=>mcpStore.getServerLabel($$props.server)),isIdle=user_derived(()=>get$4(healthState).status===HealthCheckStatus.IDLE),isHealthChecking=user_derived(()=>get$4(healthState).
status===HealthCheckStatus.CONNECTING),isConnected=user_derived(()=>get$4(healthState).status===HealthCheckStatus.SUCCESS),isError=user_derived(()=>get$4(healthState).status===HealthCheckStatus.ERROR),showSkeleton=user_derived(()=>get$4(isIdle)||get$4(isHealthChecking)),errorMessage=user_derived(()=>get$4(healthState).status===HealthCheckStatus.ERROR?get$4(healthState).message:void 0),tools=user_derived(()=>get$4(healthState).status===HealthCheckStatus.SUCCESS?get$4(healthState).tools:[]),connectionLogs=user_derived(
()=>get$4(healthState).status===HealthCheckStatus.CONNECTING||get$4(healthState).status===HealthCheckStatus.SUCCESS||get$4(healthState).status===HealthCheckStatus.ERROR?get$4(healthState).logs:[]),successState=user_derived(()=>get$4(healthState).status===HealthCheckStatus.SUCCESS?get$4(healthState):null),serverInfo=user_derived(()=>get$4(successState)?.serverInfo),capabilities=user_derived(()=>get$4(successState)?.capabilities),transportType=user_derived(()=>get$4(successState)?.transportType),protocolVersion=user_derived(
()=>get$4(successState)?.protocolVersion),connectionTimeMs=user_derived(()=>get$4(successState)?.connectionTimeMs),instructions=user_derived(()=>get$4(successState)?.instructions),isEditing2=user_derived(()=>!$$props.server.url.trim()),showDeleteDialog=state$1(!1),editFormRef=state$1(null);function handleHealthCheck(){mcpStore.runHealthCheck($$props.server)}async function startEditing(){set$1(isEditing2,!0),await tick(),get$4(editFormRef)?.setInitialValues($$props.server.url,$$props.server.headers||
"",$$props.server.useProxy||!1)}function cancelEditing(){$$props.server.url.trim()?set$1(isEditing2,!1):$$props.onDelete()}function saveEditing(url2,headers,useProxy){$$props.onUpdate({url:url2,headers:headers||void 0,useProxy}),set$1(isEditing2,!1),$$props.server.enabled&&url2&&setTimeout(()=>mcpStore.runHealthCheck({...$$props.server,url:url2,useProxy}),100)}function handleDeleteClick(){set$1(showDeleteDialog,!0)}var fragment=root$i(),node2=first_child(fragment);component(node2,()=>Card,($$anchor2,Card_Root)=>{
Card_Root($$anchor2,{class:"!gap-3 bg-muted/30 p-4",children:($$anchor3,$$slotProps)=>{var fragment_1=comment$2(),node_1=first_child(fragment_1);{var consequent=$$anchor4=>{bind_this(McpServerCardEditForm($$anchor4,{get serverId(){return $$props.server.id},get serverUrl(){return $$props.server.url},get serverUseProxy(){return $$props.server.useProxy},onSave:saveEditing,onCancel:cancelEditing}),$$value=>set$1(editFormRef,$$value,!0),()=>get$4(editFormRef))},alternate_2=$$anchor4=>{var fragment_3=root_3$8(),
node_2=first_child(fragment_3);{let $0=user_derived(()=>$$props.enabled??$$props.server.enabled);McpServerCardHeader(node_2,{get displayName(){return get$4(displayName)},get faviconUrl(){return $$props.faviconUrl},get enabled(){return get$4($0)},get disabled(){return get$4(isError)},get onToggle(){return $$props.onToggle},get serverInfo(){return get$4(serverInfo)},get capabilities(){return get$4(capabilities)},get transportType(){return get$4(transportType)}})}var node_3=sibling(node_2,2);{var consequent_1=$$anchor5=>{
var p2=root_4$4(),text2=child(p2,!0);reset(p2),template_effect(()=>set_text(text2,get$4(errorMessage))),append($$anchor5,p2)};if_block(node_3,$$render=>{get$4(isError)&&get$4(errorMessage)&&$$render(consequent_1)})}var node_4=sibling(node_3,2);{var consequent_2=$$anchor5=>{var p_1=root_5$9(),text_1=child(p_1,!0);reset(p_1),template_effect(()=>set_text(text_1,get$4(serverInfo).description)),append($$anchor5,p_1)};if_block(node_4,$$render=>{get$4(isConnected)&&get$4(serverInfo)?.description&&$$render(
consequent_2)})}var div=sibling(node_4,2),node_5=child(div);{var consequent_3=$$anchor5=>{var fragment_4=root_6$8(),div_1=first_child(fragment_4),div_2=child(div_1),node_6=child(div_2);Skeleton(node_6,{class:"h-4 w-4 rounded"});var node_7=sibling(node_6,2);Skeleton(node_7,{class:"h-3 w-24"}),reset(div_2);var div_3=sibling(div_2,2),node_8=child(div_3);Skeleton(node_8,{class:"h-5 w-16 rounded-full"});var node_9=sibling(node_8,2);Skeleton(node_9,{class:"h-5 w-20 rounded-full"});var node_10=sibling(
node_9,2);Skeleton(node_10,{class:"h-5 w-14 rounded-full"}),reset(div_3),reset(div_1);var div_4=sibling(div_1,2),div_5=child(div_4),node_11=child(div_5);Skeleton(node_11,{class:"h-4 w-4 rounded"});var node_12=sibling(node_11,2);Skeleton(node_12,{class:"h-3 w-32"}),reset(div_5),reset(div_4),append($$anchor5,fragment_4)},alternate=$$anchor5=>{var fragment_5=root_7$6(),node_13=first_child(fragment_5);{var consequent_4=$$anchor6=>{McpServerInfo($$anchor6,{get instructions(){return get$4(instructions)}})};
if_block(node_13,$$render=>{get$4(isConnected)&&get$4(instructions)&&$$render(consequent_4)})}var node_14=sibling(node_13,2);{var consequent_5=$$anchor6=>{McpServerCardToolsList($$anchor6,{get tools(){return get$4(tools)}})};if_block(node_14,$$render=>{get$4(tools).length>0&&$$render(consequent_5)})}var node_15=sibling(node_14,2);{var consequent_6=$$anchor6=>{McpConnectionLogs($$anchor6,{get logs(){return get$4(connectionLogs)},get connectionTimeMs(){return get$4(connectionTimeMs)}})};if_block(node_15,
$$render=>{get$4(connectionLogs).length>0&&$$render(consequent_6)})}append($$anchor5,fragment_5)};if_block(node_5,$$render=>{get$4(showSkeleton)?$$render(consequent_3):$$render(alternate,!1)})}reset(div);var div_6=sibling(div,2),node_16=child(div_6);{var consequent_7=$$anchor5=>{Skeleton($$anchor5,{class:"h-3 w-28"})},alternate_1=$$anchor5=>{var fragment_10=comment$2(),node_17=first_child(fragment_10);{var consequent_8=$$anchor6=>{var div_7=root_13$5(),span=child(div_7),text_2=child(span);reset(
span),reset(div_7),template_effect(()=>set_text(text_2,`Protocol version: ${get$4(protocolVersion)??""}`)),append($$anchor6,div_7)};if_block(node_17,$$render=>{get$4(protocolVersion)&&$$render(consequent_8)},!0)}append($$anchor5,fragment_10)};if_block(node_16,$$render=>{get$4(showSkeleton)?$$render(consequent_7):$$render(alternate_1,!1)})}var node_18=sibling(node_16,2);McpServerCardActions(node_18,{get isHealthChecking(){return get$4(isHealthChecking)},onEdit:startEditing,onRefresh:handleHealthCheck,
onDelete:handleDeleteClick}),reset(div_6),append($$anchor4,fragment_3)};if_block(node_1,$$render=>{get$4(isEditing2)?$$render(consequent):$$render(alternate_2,!1)})}append($$anchor3,fragment_1)},$$slots:{default:!0}})});var node_19=sibling(node2,2);McpServerCardDeleteDialog(node_19,{get displayName(){return get$4(displayName)},onOpenChange:open2=>set$1(showDeleteDialog,open2,!0),get onConfirm(){return $$props.onDelete},get open(){return get$4(showDeleteDialog)},set open($$value){set$1(showDeleteDialog,
$$value,!0)}}),append($$anchor,fragment),pop()}var root_1$9=from_html('<img alt="" class="h-5 w-5 shrink-0 rounded"/>'),root_2$c=from_html('<div class="flex h-5 w-5 shrink-0 items-center justify-center rounded bg-muted"><!></div>'),root_5$8=from_html('<a target="_blank" rel="noopener noreferrer" class="shrink-0 text-muted-foreground hover:text-foreground" aria-label="Open website"><!></a>'),root_8$5=from_html("<!> ",1),root_6$7=from_html('<div class="flex flex-wrap items-center gap-1"><!> <!></d\
iv>'),root$h=from_html('<div class="space-y-3"><div class="flex items-start justify-between gap-3"><div class="grid min-w-0 gap-3"><div class="flex items-center gap-2 overflow-hidden"><!> <p class="min-w-0 shrink-0 truncate leading-none font-medium"> </p> <!> <!></div> <!></div> <div class="flex shrink-0 items-center pl-2"><!></div></div></div>');function McpServerCardHeader($$anchor,$$props){push$1($$props,!0);let disabled=prop($$props,"disabled",3,!1);var div=root$h(),div_1=child(div),div_2=child(
div_1),div_3=child(div_2),node2=child(div_3);{var consequent=$$anchor2=>{var img=root_1$9();template_effect(()=>set_attribute(img,"src",$$props.faviconUrl)),event("error",img,e=>{e.currentTarget.style.display="none"}),replay_events(img),append($$anchor2,img)},alternate=$$anchor2=>{var div_4=root_2$c(),node_1=child(div_4);Cable(node_1,{class:"h-3 w-3 text-muted-foreground"}),reset(div_4),append($$anchor2,div_4)};if_block(node2,$$render=>{$$props.faviconUrl?$$render(consequent):$$render(alternate,
!1)})}var p2=sibling(node2,2),text2=child(p2,!0);reset(p2);var node_2=sibling(p2,2);{var consequent_1=$$anchor2=>{Badge($$anchor2,{variant:"secondary",class:"h-4 min-w-0 truncate px-1 text-[10px]",children:($$anchor3,$$slotProps)=>{next$1();var text_1=text$8();template_effect(()=>set_text(text_1,`v${$$props.serverInfo.version??""}`)),append($$anchor3,text_1)},$$slots:{default:!0}})};if_block(node_2,$$render=>{$$props.serverInfo?.version&&$$render(consequent_1)})}var node_3=sibling(node_2,2);{var consequent_2=$$anchor2=>{
var a=root_5$8(),node_4=child(a);External_link(node_4,{class:"h-3 w-3"}),reset(a),template_effect(()=>set_attribute(a,"href",$$props.serverInfo.websiteUrl)),append($$anchor2,a)};if_block(node_3,$$render=>{$$props.serverInfo?.websiteUrl&&$$render(consequent_2)})}reset(div_3);var node_5=sibling(div_3,2);{var consequent_6=$$anchor2=>{var div_5=root_6$7(),node_6=child(div_5);{var consequent_4=$$anchor3=>{const TransportIcon=user_derived(()=>MCP_TRANSPORT_ICONS[$$props.transportType]);Badge($$anchor3,
{variant:"outline",class:"h-5 gap-1 px-1.5 text-[10px]",children:($$anchor4,$$slotProps)=>{var fragment_3=root_8$5(),node_7=first_child(fragment_3);{var consequent_3=$$anchor5=>{var fragment_4=comment$2(),node_8=first_child(fragment_4);component(node_8,()=>get$4(TransportIcon),($$anchor6,TransportIcon_1)=>{TransportIcon_1($$anchor6,{class:"h-3 w-3"})}),append($$anchor5,fragment_4)};if_block(node_7,$$render=>{get$4(TransportIcon)&&$$render(consequent_3)})}var text_2=sibling(node_7);template_effect(
()=>set_text(text_2,` ${(MCP_TRANSPORT_LABELS[$$props.transportType]||$$props.transportType)??""}`)),append($$anchor4,fragment_3)},$$slots:{default:!0}})};if_block(node_6,$$render=>{$$props.transportType&&$$render(consequent_4)})}var node_9=sibling(node_6,2);{var consequent_5=$$anchor3=>{McpCapabilitiesBadges($$anchor3,{get capabilities(){return $$props.capabilities}})};if_block(node_9,$$render=>{$$props.capabilities&&$$render(consequent_5)})}reset(div_5),append($$anchor2,div_5)};if_block(node_5,
$$render=>{($$props.capabilities||$$props.transportType)&&$$render(consequent_6)})}reset(div_2);var div_6=sibling(div_2,2),node_10=child(div_6);Switch(node_10,{get checked(){return $$props.enabled},get disabled(){return disabled()},get onCheckedChange(){return $$props.onToggle}}),reset(div_6),reset(div_1),reset(div),template_effect(()=>set_text(text2,$$props.displayName)),append($$anchor,div),pop()}var root$g=from_html('<div class="flex shrink-0 items-center gap-1"><!> <!> <!></div>');function McpServerCardActions($$anchor,$$props){
var div=root$g(),node2=child(div);Button(node2,{variant:"ghost",size:"icon",class:"h-7 w-7",get onclick(){return $$props.onEdit},"aria-label":"Edit",children:($$anchor2,$$slotProps)=>{Pencil($$anchor2,{class:"h-3.5 w-3.5"})},$$slots:{default:!0}});var node_1=sibling(node2,2);Button(node_1,{variant:"ghost",size:"icon",class:"h-7 w-7",get onclick(){return $$props.onRefresh},get disabled(){return $$props.isHealthChecking},"aria-label":"Refresh",children:($$anchor2,$$slotProps)=>{Refresh_cw($$anchor2,
{class:"h-3.5 w-3.5"})},$$slots:{default:!0}});var node_2=sibling(node_1,2);Button(node_2,{variant:"ghost",size:"icon",class:"hover:text-destructive-foreground h-7 w-7 text-destructive hover:bg-destructive/10",get onclick(){return $$props.onDelete},"aria-label":"Delete",children:($$anchor2,$$slotProps)=>{Trash_2($$anchor2,{class:"h-3.5 w-3.5"})},$$slots:{default:!0}}),reset(div),append($$anchor,div)}var root_2$b=from_html("<!> <span> </span>",1),root_8$4=from_html('<p class="mt-1 text-xs text-mu\
ted-foreground"> </p>'),root_6$6=from_html("<div><!> <!></div>"),root_5$7=from_html('<div class="max-h-64 space-y-3 overflow-y-auto"></div>'),root_1$8=from_html("<!> <!>",1);function McpServerCardToolsList($$anchor,$$props){push$1($$props,!0);let isExpanded=state$1(!1),toolsCount=user_derived(()=>$$props.tools.length);var fragment=comment$2(),node2=first_child(fragment);component(node2,()=>Collapsible,($$anchor2,Collapsible_Root)=>{Collapsible_Root($$anchor2,{get open(){return get$4(isExpanded)},
set open($$value){set$1(isExpanded,$$value,!0)},children:($$anchor3,$$slotProps)=>{var fragment_1=root_1$8(),node_1=first_child(fragment_1);component(node_1,()=>Collapsible_trigger,($$anchor4,Collapsible_Trigger)=>{Collapsible_Trigger($$anchor4,{class:"flex w-full items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:($$anchor5,$$slotProps2)=>{var fragment_2=root_2$b(),node_2=first_child(fragment_2);{var consequent=$$anchor6=>{Chevron_down($$anchor6,{class:"h-3.5 w-3.5"})},
alternate=$$anchor6=>{Chevron_right($$anchor6,{class:"h-3.5 w-3.5"})};if_block(node_2,$$render=>{get$4(isExpanded)?$$render(consequent):$$render(alternate,!1)})}var span=sibling(node_2,2),text2=child(span);reset(span),template_effect(()=>set_text(text2,`${get$4(toolsCount)??""} tools available · Show details`)),append($$anchor5,fragment_2)},$$slots:{default:!0}})});var node_3=sibling(node_1,2);component(node_3,()=>Collapsible_content,($$anchor4,Collapsible_Content)=>{Collapsible_Content($$anchor4,
{class:"mt-2",children:($$anchor5,$$slotProps2)=>{var div=root_5$7();each(div,21,()=>$$props.tools,tool=>tool.name,($$anchor6,tool)=>{var div_1=root_6$6(),node_4=child(div_1);Badge(node_4,{variant:"secondary",children:($$anchor7,$$slotProps3)=>{next$1();var text_1=text$8();template_effect(()=>set_text(text_1,get$4(tool).name)),append($$anchor7,text_1)},$$slots:{default:!0}});var node_5=sibling(node_4,2);{var consequent_1=$$anchor7=>{var p2=root_8$4(),text_2=child(p2,!0);reset(p2),template_effect(
()=>set_text(text_2,get$4(tool).description)),append($$anchor7,p2)};if_block(node_5,$$render=>{get$4(tool).description&&$$render(consequent_1)})}reset(div_1),append($$anchor6,div_1)}),reset(div),append($$anchor5,div)},$$slots:{default:!0}})}),append($$anchor3,fragment_1)},$$slots:{default:!0}})}),append($$anchor,fragment),pop()}var root$f=from_html('<div class="space-y-4"><p class="font-medium">Configure Server</p> <!> <div class="flex items-center justify-end gap-2"><!> <!></div></div>');function McpServerCardEditForm($$anchor,$$props){
push$1($$props,!0);let serverUseProxy=prop($$props,"serverUseProxy",3,!1),editUrl=user_derived(()=>$$props.serverUrl),editHeaders=state$1(""),editUseProxy=user_derived(serverUseProxy),urlError=user_derived(()=>{if(!get$4(editUrl).trim())return"URL is required";try{return new URL(get$4(editUrl)),null}catch{return"Invalid URL format"}}),canSave=user_derived(()=>!get$4(urlError));function handleSave(){get$4(canSave)&&$$props.onSave(get$4(editUrl).trim(),get$4(editHeaders).trim(),get$4(editUseProxy))}
function setInitialValues(url2,headers,useProxy){set$1(editUrl,url2),set$1(editHeaders,headers,!0),set$1(editUseProxy,useProxy)}var $$exports={setInitialValues},div=root$f(),node2=sibling(child(div),2);{let $0=user_derived(()=>get$4(editUrl)?get$4(urlError):null);McpServerForm(node2,{get url(){return get$4(editUrl)},get headers(){return get$4(editHeaders)},get useProxy(){return get$4(editUseProxy)},onUrlChange:v=>set$1(editUrl,v),onHeadersChange:v=>set$1(editHeaders,v,!0),onUseProxyChange:v=>set$1(
editUseProxy,v),get urlError(){return get$4($0)},get id(){return $$props.serverId}})}var div_1=sibling(node2,2),node_1=child(div_1);Button(node_1,{variant:"secondary",size:"sm",get onclick(){return $$props.onCancel},children:($$anchor2,$$slotProps)=>{next$1();var text2=text$8("Cancel");append($$anchor2,text2)},$$slots:{default:!0}});var node_2=sibling(node_1,2);{let $0=user_derived(()=>!get$4(canSave));Button(node_2,{size:"sm",onclick:handleSave,get disabled(){return get$4($0)},children:($$anchor2,$$slotProps)=>{
next$1();var text_1=text$8();template_effect($02=>set_text(text_1,$02),[()=>$$props.serverUrl.trim()?"Update":"Add"]),append($$anchor2,text_1)},$$slots:{default:!0}})}return reset(div_1),reset(div),append($$anchor,div),pop($$exports)}var root_5$6=from_html(`Are you sure you want to delete <strong> </strong>? This action cannot be
{class:"h-3 w-3 text-pink-600 dark:text-pink-400"}),next$1(),append($$anchor4,fragment_13)},$$slots:{default:!0}})};if_block(node_11,$$render=>{$$props.capabilities.server.tasks&&$$render(consequent_5)})}append($$anchor2,fragment_1)};if_block(node2,$$render=>{$$props.capabilities&&$$render(consequent_6)})}append($$anchor,fragment),pop()}var root_6$9=from_html('<span class="ml-1"> </span>'),root_3$a=from_html("<!> <span> </span> <!>",1),root_9$5=from_html('<details class="ml-11"><summary class="c\
ursor-pointer text-[10px] text-muted-foreground">details</summary> <pre class="mt-1 overflow-x-auto rounded bg-background/70 p-2 text-[10px] break-all whitespace-pre-wrap text-foreground/80"> </pre></details>'),root_8$6=from_html('<div><span class="shrink-0 text-muted-foreground"> </span> <!> <span class="break-all"> </span></div> <!>',1),root_7$7=from_html('<div class="max-h-64 space-y-0.5 overflow-y-auto rounded bg-muted/50 p-2 font-mono text-[10px]"></div>'),root_2$e=from_html('<div class="sp\
ace-y-2"><!></div> <!>',1);function McpConnectionLogs($$anchor,$$props){push$1($$props,!0);let defaultExpanded=prop($$props,"defaultExpanded",3,!1),isExpanded=user_derived(defaultExpanded);function formatLogDetails(details){if(details==null)return"";try{return JSON.stringify(details,null,2)}catch{return String(details)}}var fragment=comment$2(),node2=first_child(fragment);{var consequent_3=$$anchor2=>{var fragment_1=comment$2(),node_1=first_child(fragment_1);component(node_1,()=>Collapsible,($$anchor3,Collapsible_Root)=>{
Collapsible_Root($$anchor3,{get class(){return $$props.class},get open(){return get$4(isExpanded)},set open($$value){set$1(isExpanded,$$value)},children:($$anchor4,$$slotProps)=>{var fragment_2=root_2$e(),div=first_child(fragment_2),node_2=child(div);component(node_2,()=>Collapsible_trigger,($$anchor5,Collapsible_Trigger)=>{Collapsible_Trigger($$anchor5,{class:"flex w-full items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:($$anchor6,$$slotProps2)=>{var fragment_3=root_3$a(),
node_3=first_child(fragment_3);{var consequent=$$anchor7=>{Chevron_down($$anchor7,{class:"h-3.5 w-3.5"})},alternate=$$anchor7=>{Chevron_right($$anchor7,{class:"h-3.5 w-3.5"})};if_block(node_3,$$render=>{get$4(isExpanded)?$$render(consequent):$$render(alternate,!1)})}var span=sibling(node_3,2),text2=child(span);reset(span);var node_4=sibling(span,2);{var consequent_1=$$anchor7=>{var span_1=root_6$9(),text_1=child(span_1);reset(span_1),template_effect(()=>set_text(text_1,`· Connected in ${$$props.
connectionTimeMs??""}ms`)),append($$anchor7,span_1)};if_block(node_4,$$render=>{$$props.connectionTimeMs!==void 0&&$$render(consequent_1)})}template_effect(()=>set_text(text2,`Connection Log (${$$props.logs.length??""})`)),append($$anchor6,fragment_3)},$$slots:{default:!0}})}),reset(div);var node_5=sibling(div,2);component(node_5,()=>Collapsible_content,($$anchor5,Collapsible_Content)=>{Collapsible_Content($$anchor5,{class:"mt-2",children:($$anchor6,$$slotProps2)=>{var div_1=root_7$7();each(div_1,
21,()=>$$props.logs,log=>log.timestamp.getTime()+log.message,($$anchor7,log)=>{const Icon2=user_derived(()=>getMcpLogLevelIcon(get$4(log).level));var fragment_6=root_8$6(),div_2=first_child(fragment_6),span_2=child(div_2),text_2=child(span_2,!0);reset(span_2);var node_6=sibling(span_2,2);component(node_6,()=>get$4(Icon2),($$anchor8,Icon_1)=>{Icon_1($$anchor8,{class:"mt-0.5 h-3 w-3 shrink-0"})});var span_3=sibling(node_6,2),text_3=child(span_3,!0);reset(span_3),reset(div_2);var node_7=sibling(div_2,
2);{var consequent_2=$$anchor8=>{var details_1=root_9$5(),pre=sibling(child(details_1),2),text_4=child(pre,!0);reset(pre),reset(details_1),template_effect($0=>set_text(text_4,$0),[()=>formatLogDetails(get$4(log).details)]),append($$anchor8,details_1)};if_block(node_7,$$render=>{get$4(log).details!==void 0&&$$render(consequent_2)})}template_effect(($0,$1)=>{set_class(div_2,1,$0),set_text(text_2,$1),set_text(text_3,get$4(log).message)},[()=>clsx(cn$1("flex items-start gap-1.5",getMcpLogLevelClass(
get$4(log).level))),()=>formatTime(get$4(log).timestamp)]),append($$anchor7,fragment_6)}),reset(div_1),append($$anchor6,div_1)},$$slots:{default:!0}})}),append($$anchor4,fragment_2)},$$slots:{default:!0}})}),append($$anchor2,fragment_1)};if_block(node2,$$render=>{$$props.logs.length>0&&$$render(consequent_3)})}append($$anchor,fragment),pop()}var root_1$a=from_html('<p class="mt-1.5 text-xs text-destructive"> </p>'),root_3$9=from_html('<span class="inline-flex gap-0.75 text-xs text-muted-foregrou\
nd/60">(Run <pre>llama-server</pre> with <pre>--webui-mcp-proxy</pre> flag)</span>'),root_2$d=from_html('<label><!> <span><span class="text-xs text-muted-foreground">Use llama-server proxy</span> <br/> <!></span></label>'),root$k=from_html('<div class="grid gap-3"><div><label class="mb-2 block text-xs font-medium">Server URL <span class="text-destructive">*</span></label> <!> <!> <!></div> <!></div>');function McpServerForm($$anchor,$$props){push$1($$props,!0);let useProxy=prop($$props,"useProxy",
3,!1),urlError=prop($$props,"urlError",3,null),id2=prop($$props,"id",3,"server"),isWebSocket=user_derived(()=>$$props.url.toLowerCase().startsWith(UrlProtocol.WEBSOCKET)||$$props.url.toLowerCase().startsWith(UrlProtocol.WEBSOCKET_SECURE)),headerPairs=user_derived(()=>parseHeadersToArray($$props.headers));function updateHeaderPairs(newPairs){set$1(headerPairs,newPairs),$$props.onHeadersChange(serializeHeaders(newPairs))}var div=root$k(),div_1=child(div),label=child(div_1),node2=sibling(label,2);{
let $0=user_derived(()=>urlError()?"border-destructive":"");Input(node2,{get id(){return`server-url-${id2()??""}`},type:"url",get placeholder(){return MCP_SERVER_URL_PLACEHOLDER},get value(){return $$props.url},oninput:e=>$$props.onUrlChange(e.currentTarget.value),get class(){return get$4($0)}})}var node_1=sibling(node2,2);{var consequent=$$anchor2=>{var p2=root_1$a(),text2=child(p2,!0);reset(p2),template_effect(()=>set_text(text2,urlError())),append($$anchor2,p2)};if_block(node_1,$$render=>{urlError()&&
$$render(consequent)})}var node_2=sibling(node_1,2);{var consequent_2=$$anchor2=>{var label_1=root_2$d();let classes;var node_3=child(label_1);{let $0=user_derived(()=>!mcpStore.isProxyAvailable);Switch(node_3,{class:"mt-1",get id(){return`use-proxy-${id2()??""}`},get checked(){return useProxy()},get disabled(){return get$4($0)},onCheckedChange:checked=>$$props.onUseProxyChange?.(checked)})}var span=sibling(node_3,2),node_4=sibling(child(span),4);{var consequent_1=$$anchor3=>{var span_1=root_3$9();
append($$anchor3,span_1)};if_block(node_4,$$render=>{mcpStore.isProxyAvailable||$$render(consequent_1)})}reset(span),reset(label_1),template_effect(()=>classes=set_class(label_1,1,"mt-3 flex items-start gap-2",null,classes,{"cursor-pointer":mcpStore.isProxyAvailable,"opacity-80":!mcpStore.isProxyAvailable})),append($$anchor2,label_1)};if_block(node_2,$$render=>{!get$4(isWebSocket)&&$$props.onUseProxyChange&&$$render(consequent_2)})}reset(div_1);var node_5=sibling(div_1,2);KeyValuePairs(node_5,{class:"\
mt-2",get pairs(){return get$4(headerPairs)},onPairsChange:updateHeaderPairs,keyPlaceholder:"Header name",valuePlaceholder:"Value",addButtonLabel:"Add",emptyMessage:"No custom headers configured.",sectionLabel:"Custom Headers",sectionLabelOptional:!0}),reset(div),template_effect(()=>set_attribute(label,"for",`server-url-${id2()??""}`)),append($$anchor,div),pop()}var root$j=from_svg('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 174 174" xmlns:xlink="http://www.w3.org/1999/xlink" fill="non\
e" version="1.1"><g id="shape-320b5b95-d08d-8089-8007-585a8e498184"><defs><clipPath id="frame-clip-320b5b95-d08d-8089-8007-585a8e498184-render-1" class="frame-clip frame-clip-def"><rect rx="0" ry="0" x="0" y="0" width="174.00000000000045" height="174" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)"></rect></clipPath></defs><g class="frame-container-wrapper"><g class="frame-container-blur"><g class="frame-container-shadows"><g clip-path="url(#frame-clip-320b5b95-d08\
d-8089-8007-585a8e498184-render-1)" fill="none"><g class="fills" id="fills-320b5b95-d08d-8089-8007-585a8e498184"><rect rx="0" ry="0" x="0" y="0" width="174.00000000000045" height="174" transform="matrix(1.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000)" class="frame-background"></rect></g><g class="frame-children"><g id="shape-320b5b95-d08d-8089-8007-585a974337b1"><g class="fills" id="fills-320b5b95-d08d-8089-8007-585a974337b1"><path d="M15.5587158203125,81.5927734375L83.44091796875,13\
.7105712890625C92.813720703125,4.3380126953125,108.0096435546875,4.3380126953125,117.3817138671875,13.7105712890625L117.3817138671875,13.7105712890625C126.7547607421875,23.08306884765625,126.7547607421875,38.27911376953125,117.3817138671875,47.65167236328125L66.1168212890625,98.9169921875" fill="none" stroke-linecap="round" style="fill: none;"></path></g><g fill="none" stroke-linecap="round" id="strokes-b954dcef-3e3e-8015-8007-585acd4382b6-320b5b95-d08d-8089-8007-585a974337b1" class="strokes"><g\
class="stroke-shape"><path d="M15.5587158203125,81.5927734375L83.44091796875,13.7105712890625C92.813720703125,4.3380126953125,108.0096435546875,4.3380126953125,117.3817138671875,13.7105712890625L117.3817138671875,13.7105712890625C126.7547607421875,23.08306884765625,126.7547607421875,38.27911376953125,117.3817138671875,47.65167236328125L66.1168212890625,98.9169921875" style="fill: none; stroke-width: 12; stroke: currentColor; stroke-opacity: 1;"></path></g></g></g><g id="shape-320b5b95-d08d-8089\
-8007-585a974337b2"><g class="fills" id="fills-320b5b95-d08d-8089-8007-585a974337b2"><path d="M66.5587158203125,98.26885986328125L117.1165771484375,47.7105712890625C126.489501953125,38.3380126953125,141.6854248046875,38.3380126953125,151.0584716796875,47.7105712890625L151.4114990234375,48.0640869140625C160.7845458984375,57.43670654296875,160.7845458984375,72.6326904296875,151.4114990234375,82.00518798828125L90.018310546875,143.39886474609375C86.8941650390625,146.52288818359375,86.8941650390625,1\
51.587890625,90.018310546875,154.71185302734375L102.62451171875,167.31890869140625" fill="none" stroke-linecap="round" style="fill: none;"></path></g><g fill="none" stroke-linecap="round" id="strokes-b954dcef-3e3e-8015-8007-585acd447743-320b5b95-d08d-8089-8007-585a974337b2" class="strokes"><g class="stroke-shape"><path d="M66.5587158203125,98.26885986328125L117.1165771484375,47.7105712890625C126.489501953125,38.3380126953125,141.6854248046875,38.3380126953125,151.0584716796875,47.7105712890625L1\
51.4114990234375,48.0640869140625C160.7845458984375,57.43670654296875,160.7845458984375,72.6326904296875,151.4114990234375,82.00518798828125L90.018310546875,143.39886474609375C86.8941650390625,146.52288818359375,86.8941650390625,151.587890625,90.018310546875,154.71185302734375L102.62451171875,167.31890869140625" style="fill: none; stroke-width: 12; stroke: currentColor; stroke-opacity: 1;"></path></g></g></g><g id="shape-320b5b95-d08d-8089-8007-585a974337b3"><g class="fills" id="fills-320b5b95-d\
08d-8089-8007-585a974337b3"><path d="M99.79296875,30.68115234375L49.588134765625,80.8857421875C40.215576171875,90.258056640625,40.215576171875,105.45404052734375,49.588134765625,114.82708740234375L49.588134765625,114.82708740234375C58.9608154296875,124.19903564453125,74.1566162109375,124.19903564453125,83.529296875,114.82708740234375L133.7340087890625,64.62225341796875" fill="none" stroke-linecap="round" style="fill: none;"></path></g><g fill="none" stroke-linecap="round" id="strokes-b954dcef-3e\
3e-8015-8007-585acd44c5c9-320b5b95-d08d-8089-8007-585a974337b3" class="strokes"><g class="stroke-shape"><path d="M99.79296875,30.68115234375L49.588134765625,80.8857421875C40.215576171875,90.258056640625,40.215576171875,105.45404052734375,49.588134765625,114.82708740234375L49.588134765625,114.82708740234375C58.9608154296875,124.19903564453125,74.1566162109375,124.19903564453125,83.529296875,114.82708740234375L133.7340087890625,64.62225341796875" style="fill: none; stroke-width: 12; stroke: curren\
tColor; stroke-opacity: 1;"></path></g></g></g></g></g></g></g></g></g></svg>');function McpLogo($$anchor,$$props){let className=prop($$props,"class",3,""),style2=prop($$props,"style",3,"");var svg2=root$j();template_effect(()=>{set_class(svg2,0,clsx(className())),set_style(svg2,style2())}),append($$anchor,svg2)}var root_4$4=from_html('<p class="text-xs text-destructive"> </p>'),root_5$9=from_html('<p class="line-clamp-2 text-xs text-muted-foreground"> </p>'),root_6$8=from_html('<div class="spac\
e-y-2"><div class="flex items-center gap-2"><!> <!></div> <div class="flex flex-wrap gap-1.5"><!> <!> <!></div></div> <div class="space-y-1.5"><div class="flex items-center gap-2"><!> <!></div></div>',1),root_7$6=from_html("<!> <!> <!>",1),root_13$5=from_html('<div class="flex flex-wrap items-center gap-1"><span class="text-[10px] text-muted-foreground"> </span></div>'),root_3$8=from_html('<!> <!> <!> <div class="grid gap-3"><!></div> <div class="flex justify-between gap-4"><!> <!></div>',1),root$i=from_html(
"<!> <!>",1);function McpServerCard($$anchor,$$props){push$1($$props,!0);let healthState=user_derived(()=>mcpStore.getHealthCheckState($$props.server.id)),displayName=user_derived(()=>mcpStore.getServerLabel($$props.server)),isIdle=user_derived(()=>get$4(healthState).status===HealthCheckStatus.IDLE),isHealthChecking=user_derived(()=>get$4(healthState).status===HealthCheckStatus.CONNECTING),isConnected=user_derived(()=>get$4(healthState).status===HealthCheckStatus.SUCCESS),isError=user_derived(()=>get$4(
healthState).status===HealthCheckStatus.ERROR),showSkeleton=user_derived(()=>get$4(isIdle)||get$4(isHealthChecking)),errorMessage=user_derived(()=>get$4(healthState).status===HealthCheckStatus.ERROR?get$4(healthState).message:void 0),tools=user_derived(()=>get$4(healthState).status===HealthCheckStatus.SUCCESS?get$4(healthState).tools:[]),connectionLogs=user_derived(()=>get$4(healthState).status===HealthCheckStatus.CONNECTING||get$4(healthState).status===HealthCheckStatus.SUCCESS||get$4(healthState).
status===HealthCheckStatus.ERROR?get$4(healthState).logs:[]),successState=user_derived(()=>get$4(healthState).status===HealthCheckStatus.SUCCESS?get$4(healthState):null),serverInfo=user_derived(()=>get$4(successState)?.serverInfo),capabilities=user_derived(()=>get$4(successState)?.capabilities),transportType=user_derived(()=>get$4(successState)?.transportType),protocolVersion=user_derived(()=>get$4(successState)?.protocolVersion),connectionTimeMs=user_derived(()=>get$4(successState)?.connectionTimeMs),
instructions=user_derived(()=>get$4(successState)?.instructions),isEditing2=user_derived(()=>!$$props.server.url.trim()),showDeleteDialog=state$1(!1),editFormRef=state$1(null);function handleHealthCheck(){mcpStore.runHealthCheck($$props.server)}async function startEditing(){set$1(isEditing2,!0),await tick(),get$4(editFormRef)?.setInitialValues($$props.server.url,$$props.server.headers||"",$$props.server.useProxy||!1)}function cancelEditing(){$$props.server.url.trim()?set$1(isEditing2,!1):$$props.
onDelete()}function saveEditing(url2,headers,useProxy){$$props.onUpdate({url:url2,headers:headers||void 0,useProxy}),set$1(isEditing2,!1),$$props.server.enabled&&url2&&setTimeout(()=>mcpStore.runHealthCheck({...$$props.server,url:url2,useProxy}),100)}function handleDeleteClick(){set$1(showDeleteDialog,!0)}var fragment=root$i(),node2=first_child(fragment);component(node2,()=>Card,($$anchor2,Card_Root)=>{Card_Root($$anchor2,{class:"!gap-3 bg-muted/30 p-4",children:($$anchor3,$$slotProps)=>{var fragment_1=comment$2(),
node_1=first_child(fragment_1);{var consequent=$$anchor4=>{bind_this(McpServerCardEditForm($$anchor4,{get serverId(){return $$props.server.id},get serverUrl(){return $$props.server.url},get serverUseProxy(){return $$props.server.useProxy},onSave:saveEditing,onCancel:cancelEditing}),$$value=>set$1(editFormRef,$$value,!0),()=>get$4(editFormRef))},alternate_2=$$anchor4=>{var fragment_3=root_3$8(),node_2=first_child(fragment_3);{let $0=user_derived(()=>$$props.enabled??$$props.server.enabled);McpServerCardHeader(
node_2,{get displayName(){return get$4(displayName)},get faviconUrl(){return $$props.faviconUrl},get enabled(){return get$4($0)},get disabled(){return get$4(isError)},get onToggle(){return $$props.onToggle},get serverInfo(){return get$4(serverInfo)},get capabilities(){return get$4(capabilities)},get transportType(){return get$4(transportType)}})}var node_3=sibling(node_2,2);{var consequent_1=$$anchor5=>{var p2=root_4$4(),text2=child(p2,!0);reset(p2),template_effect(()=>set_text(text2,get$4(errorMessage))),
append($$anchor5,p2)};if_block(node_3,$$render=>{get$4(isError)&&get$4(errorMessage)&&$$render(consequent_1)})}var node_4=sibling(node_3,2);{var consequent_2=$$anchor5=>{var p_1=root_5$9(),text_1=child(p_1,!0);reset(p_1),template_effect(()=>set_text(text_1,get$4(serverInfo).description)),append($$anchor5,p_1)};if_block(node_4,$$render=>{get$4(isConnected)&&get$4(serverInfo)?.description&&$$render(consequent_2)})}var div=sibling(node_4,2),node_5=child(div);{var consequent_3=$$anchor5=>{var fragment_4=root_6$8(),
div_1=first_child(fragment_4),div_2=child(div_1),node_6=child(div_2);Skeleton(node_6,{class:"h-4 w-4 rounded"});var node_7=sibling(node_6,2);Skeleton(node_7,{class:"h-3 w-24"}),reset(div_2);var div_3=sibling(div_2,2),node_8=child(div_3);Skeleton(node_8,{class:"h-5 w-16 rounded-full"});var node_9=sibling(node_8,2);Skeleton(node_9,{class:"h-5 w-20 rounded-full"});var node_10=sibling(node_9,2);Skeleton(node_10,{class:"h-5 w-14 rounded-full"}),reset(div_3),reset(div_1);var div_4=sibling(div_1,2),div_5=child(
div_4),node_11=child(div_5);Skeleton(node_11,{class:"h-4 w-4 rounded"});var node_12=sibling(node_11,2);Skeleton(node_12,{class:"h-3 w-32"}),reset(div_5),reset(div_4),append($$anchor5,fragment_4)},alternate=$$anchor5=>{var fragment_5=root_7$6(),node_13=first_child(fragment_5);{var consequent_4=$$anchor6=>{McpServerInfo($$anchor6,{get instructions(){return get$4(instructions)}})};if_block(node_13,$$render=>{get$4(isConnected)&&get$4(instructions)&&$$render(consequent_4)})}var node_14=sibling(node_13,
2);{var consequent_5=$$anchor6=>{McpServerCardToolsList($$anchor6,{get tools(){return get$4(tools)}})};if_block(node_14,$$render=>{get$4(tools).length>0&&$$render(consequent_5)})}var node_15=sibling(node_14,2);{var consequent_6=$$anchor6=>{McpConnectionLogs($$anchor6,{get logs(){return get$4(connectionLogs)},get connectionTimeMs(){return get$4(connectionTimeMs)}})};if_block(node_15,$$render=>{get$4(connectionLogs).length>0&&$$render(consequent_6)})}append($$anchor5,fragment_5)};if_block(node_5,$$render=>{
get$4(showSkeleton)?$$render(consequent_3):$$render(alternate,!1)})}reset(div);var div_6=sibling(div,2),node_16=child(div_6);{var consequent_7=$$anchor5=>{Skeleton($$anchor5,{class:"h-3 w-28"})},alternate_1=$$anchor5=>{var fragment_10=comment$2(),node_17=first_child(fragment_10);{var consequent_8=$$anchor6=>{var div_7=root_13$5(),span=child(div_7),text_2=child(span);reset(span),reset(div_7),template_effect(()=>set_text(text_2,`Protocol version: ${get$4(protocolVersion)??""}`)),append($$anchor6,div_7)};
if_block(node_17,$$render=>{get$4(protocolVersion)&&$$render(consequent_8)},!0)}append($$anchor5,fragment_10)};if_block(node_16,$$render=>{get$4(showSkeleton)?$$render(consequent_7):$$render(alternate_1,!1)})}var node_18=sibling(node_16,2);McpServerCardActions(node_18,{get isHealthChecking(){return get$4(isHealthChecking)},onEdit:startEditing,onRefresh:handleHealthCheck,onDelete:handleDeleteClick}),reset(div_6),append($$anchor4,fragment_3)};if_block(node_1,$$render=>{get$4(isEditing2)?$$render(consequent):
$$render(alternate_2,!1)})}append($$anchor3,fragment_1)},$$slots:{default:!0}})});var node_19=sibling(node2,2);McpServerCardDeleteDialog(node_19,{get displayName(){return get$4(displayName)},onOpenChange:open2=>set$1(showDeleteDialog,open2,!0),get onConfirm(){return $$props.onDelete},get open(){return get$4(showDeleteDialog)},set open($$value){set$1(showDeleteDialog,$$value,!0)}}),append($$anchor,fragment),pop()}var root_1$9=from_html('<img alt="" class="h-5 w-5 shrink-0 rounded"/>'),root_2$c=from_html(
'<div class="flex h-5 w-5 shrink-0 items-center justify-center rounded bg-muted"><!></div>'),root_5$8=from_html('<a target="_blank" rel="noopener noreferrer" class="shrink-0 text-muted-foreground hover:text-foreground" aria-label="Open website"><!></a>'),root_8$5=from_html("<!> ",1),root_6$7=from_html('<div class="flex flex-wrap items-center gap-1"><!> <!></div>'),root$h=from_html('<div class="space-y-3"><div class="flex items-start justify-between gap-3"><div class="grid min-w-0 gap-3"><div cla\
ss="flex items-center gap-2 overflow-hidden"><!> <p class="min-w-0 shrink-0 truncate leading-none font-medium"> </p> <!> <!></div> <!></div> <div class="flex shrink-0 items-center pl-2"><!></div></div></div>');function McpServerCardHeader($$anchor,$$props){push$1($$props,!0);let disabled=prop($$props,"disabled",3,!1);var div=root$h(),div_1=child(div),div_2=child(div_1),div_3=child(div_2),node2=child(div_3);{var consequent=$$anchor2=>{var img=root_1$9();template_effect(()=>set_attribute(img,"src",
$$props.faviconUrl)),event("error",img,e=>{e.currentTarget.style.display="none"}),replay_events(img),append($$anchor2,img)},alternate=$$anchor2=>{var div_4=root_2$c(),node_1=child(div_4);Cable(node_1,{class:"h-3 w-3 text-muted-foreground"}),reset(div_4),append($$anchor2,div_4)};if_block(node2,$$render=>{$$props.faviconUrl?$$render(consequent):$$render(alternate,!1)})}var p2=sibling(node2,2),text2=child(p2,!0);reset(p2);var node_2=sibling(p2,2);{var consequent_1=$$anchor2=>{Badge($$anchor2,{variant:"\
secondary",class:"h-4 min-w-0 truncate px-1 text-[10px]",children:($$anchor3,$$slotProps)=>{next$1();var text_1=text$8();template_effect(()=>set_text(text_1,`v${$$props.serverInfo.version??""}`)),append($$anchor3,text_1)},$$slots:{default:!0}})};if_block(node_2,$$render=>{$$props.serverInfo?.version&&$$render(consequent_1)})}var node_3=sibling(node_2,2);{var consequent_2=$$anchor2=>{var a=root_5$8(),node_4=child(a);External_link(node_4,{class:"h-3 w-3"}),reset(a),template_effect(()=>set_attribute(
a,"href",$$props.serverInfo.websiteUrl)),append($$anchor2,a)};if_block(node_3,$$render=>{$$props.serverInfo?.websiteUrl&&$$render(consequent_2)})}reset(div_3);var node_5=sibling(div_3,2);{var consequent_6=$$anchor2=>{var div_5=root_6$7(),node_6=child(div_5);{var consequent_4=$$anchor3=>{const TransportIcon=user_derived(()=>MCP_TRANSPORT_ICONS[$$props.transportType]);Badge($$anchor3,{variant:"outline",class:"h-5 gap-1 px-1.5 text-[10px]",children:($$anchor4,$$slotProps)=>{var fragment_3=root_8$5(),
node_7=first_child(fragment_3);{var consequent_3=$$anchor5=>{var fragment_4=comment$2(),node_8=first_child(fragment_4);component(node_8,()=>get$4(TransportIcon),($$anchor6,TransportIcon_1)=>{TransportIcon_1($$anchor6,{class:"h-3 w-3"})}),append($$anchor5,fragment_4)};if_block(node_7,$$render=>{get$4(TransportIcon)&&$$render(consequent_3)})}var text_2=sibling(node_7);template_effect(()=>set_text(text_2,` ${(MCP_TRANSPORT_LABELS[$$props.transportType]||$$props.transportType)??""}`)),append($$anchor4,
fragment_3)},$$slots:{default:!0}})};if_block(node_6,$$render=>{$$props.transportType&&$$render(consequent_4)})}var node_9=sibling(node_6,2);{var consequent_5=$$anchor3=>{McpCapabilitiesBadges($$anchor3,{get capabilities(){return $$props.capabilities}})};if_block(node_9,$$render=>{$$props.capabilities&&$$render(consequent_5)})}reset(div_5),append($$anchor2,div_5)};if_block(node_5,$$render=>{($$props.capabilities||$$props.transportType)&&$$render(consequent_6)})}reset(div_2);var div_6=sibling(div_2,
2),node_10=child(div_6);Switch(node_10,{get checked(){return $$props.enabled},get disabled(){return disabled()},get onCheckedChange(){return $$props.onToggle}}),reset(div_6),reset(div_1),reset(div),template_effect(()=>set_text(text2,$$props.displayName)),append($$anchor,div),pop()}var root$g=from_html('<div class="flex shrink-0 items-center gap-1"><!> <!> <!></div>');function McpServerCardActions($$anchor,$$props){var div=root$g(),node2=child(div);Button(node2,{variant:"ghost",size:"icon",class:"\
h-7 w-7",get onclick(){return $$props.onEdit},"aria-label":"Edit",children:($$anchor2,$$slotProps)=>{Pencil($$anchor2,{class:"h-3.5 w-3.5"})},$$slots:{default:!0}});var node_1=sibling(node2,2);Button(node_1,{variant:"ghost",size:"icon",class:"h-7 w-7",get onclick(){return $$props.onRefresh},get disabled(){return $$props.isHealthChecking},"aria-label":"Refresh",children:($$anchor2,$$slotProps)=>{Refresh_cw($$anchor2,{class:"h-3.5 w-3.5"})},$$slots:{default:!0}});var node_2=sibling(node_1,2);Button(
node_2,{variant:"ghost",size:"icon",class:"hover:text-destructive-foreground h-7 w-7 text-destructive hover:bg-destructive/10",get onclick(){return $$props.onDelete},"aria-label":"Delete",children:($$anchor2,$$slotProps)=>{Trash_2($$anchor2,{class:"h-3.5 w-3.5"})},$$slots:{default:!0}}),reset(div),append($$anchor,div)}var root_2$b=from_html("<!> <span> </span>",1),root_8$4=from_html('<p class="mt-1 text-xs text-muted-foreground"> </p>'),root_6$6=from_html("<div><!> <!></div>"),root_5$7=from_html(
'<div class="max-h-64 space-y-3 overflow-y-auto"></div>'),root_1$8=from_html("<!> <!>",1);function McpServerCardToolsList($$anchor,$$props){push$1($$props,!0);let isExpanded=state$1(!1),toolsCount=user_derived(()=>$$props.tools.length);var fragment=comment$2(),node2=first_child(fragment);component(node2,()=>Collapsible,($$anchor2,Collapsible_Root)=>{Collapsible_Root($$anchor2,{get open(){return get$4(isExpanded)},set open($$value){set$1(isExpanded,$$value,!0)},children:($$anchor3,$$slotProps)=>{
var fragment_1=root_1$8(),node_1=first_child(fragment_1);component(node_1,()=>Collapsible_trigger,($$anchor4,Collapsible_Trigger)=>{Collapsible_Trigger($$anchor4,{class:"flex w-full items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:($$anchor5,$$slotProps2)=>{var fragment_2=root_2$b(),node_2=first_child(fragment_2);{var consequent=$$anchor6=>{Chevron_down($$anchor6,{class:"h-3.5 w-3.5"})},alternate=$$anchor6=>{Chevron_right($$anchor6,{class:"h-3.5 w-3.5"})};if_block(
node_2,$$render=>{get$4(isExpanded)?$$render(consequent):$$render(alternate,!1)})}var span=sibling(node_2,2),text2=child(span);reset(span),template_effect(()=>set_text(text2,`${get$4(toolsCount)??""} tools available · Show details`)),append($$anchor5,fragment_2)},$$slots:{default:!0}})});var node_3=sibling(node_1,2);component(node_3,()=>Collapsible_content,($$anchor4,Collapsible_Content)=>{Collapsible_Content($$anchor4,{class:"mt-2",children:($$anchor5,$$slotProps2)=>{var div=root_5$7();each(div,
21,()=>$$props.tools,tool=>tool.name,($$anchor6,tool)=>{var div_1=root_6$6(),node_4=child(div_1);Badge(node_4,{variant:"secondary",children:($$anchor7,$$slotProps3)=>{next$1();var text_1=text$8();template_effect(()=>set_text(text_1,get$4(tool).name)),append($$anchor7,text_1)},$$slots:{default:!0}});var node_5=sibling(node_4,2);{var consequent_1=$$anchor7=>{var p2=root_8$4(),text_2=child(p2,!0);reset(p2),template_effect(()=>set_text(text_2,get$4(tool).description)),append($$anchor7,p2)};if_block(
node_5,$$render=>{get$4(tool).description&&$$render(consequent_1)})}reset(div_1),append($$anchor6,div_1)}),reset(div),append($$anchor5,div)},$$slots:{default:!0}})}),append($$anchor3,fragment_1)},$$slots:{default:!0}})}),append($$anchor,fragment),pop()}var root$f=from_html('<div class="space-y-4"><p class="font-medium">Configure Server</p> <!> <div class="flex items-center justify-end gap-2"><!> <!></div></div>');function McpServerCardEditForm($$anchor,$$props){push$1($$props,!0);let serverUseProxy=prop(
$$props,"serverUseProxy",3,!1),editUrl=user_derived(()=>$$props.serverUrl),editHeaders=state$1(""),editUseProxy=user_derived(serverUseProxy),urlError=user_derived(()=>{if(!get$4(editUrl).trim())return"URL is required";try{return new URL(get$4(editUrl)),null}catch{return"Invalid URL format"}}),canSave=user_derived(()=>!get$4(urlError));function handleSave(){get$4(canSave)&&$$props.onSave(get$4(editUrl).trim(),get$4(editHeaders).trim(),get$4(editUseProxy))}function setInitialValues(url2,headers,useProxy){
set$1(editUrl,url2),set$1(editHeaders,headers,!0),set$1(editUseProxy,useProxy)}var $$exports={setInitialValues},div=root$f(),node2=sibling(child(div),2);{let $0=user_derived(()=>get$4(editUrl)?get$4(urlError):null);McpServerForm(node2,{get url(){return get$4(editUrl)},get headers(){return get$4(editHeaders)},get useProxy(){return get$4(editUseProxy)},onUrlChange:v=>set$1(editUrl,v),onHeadersChange:v=>set$1(editHeaders,v,!0),onUseProxyChange:v=>set$1(editUseProxy,v),get urlError(){return get$4($0)},
get id(){return $$props.serverId}})}var div_1=sibling(node2,2),node_1=child(div_1);Button(node_1,{variant:"secondary",size:"sm",get onclick(){return $$props.onCancel},children:($$anchor2,$$slotProps)=>{next$1();var text2=text$8("Cancel");append($$anchor2,text2)},$$slots:{default:!0}});var node_2=sibling(node_1,2);{let $0=user_derived(()=>!get$4(canSave));Button(node_2,{size:"sm",onclick:handleSave,get disabled(){return get$4($0)},children:($$anchor2,$$slotProps)=>{next$1();var text_1=text$8();template_effect(
$02=>set_text(text_1,$02),[()=>$$props.serverUrl.trim()?"Update":"Add"]),append($$anchor2,text_1)},$$slots:{default:!0}})}return reset(div_1),reset(div),append($$anchor,div),pop($$exports)}var root_5$6=from_html(`Are you sure you want to delete <strong> </strong>? This action cannot be
undone.`,1),root_3$7=from_html("<!> <!>",1),root_6$5=from_html("<!> <!>",1),root_2$a=from_html("<!> <!>",1);function McpServerCardDeleteDialog($$anchor,$$props){push$1($$props,!0);let open2=prop($$props,"open",15);var fragment=comment$2(),node2=first_child(fragment);component(node2,()=>Root$3,($$anchor2,AlertDialog_Root)=>{AlertDialog_Root($$anchor2,{get onOpenChange(){return $$props.onOpenChange},get open(){return open2()},set open($$value){open2($$value)},children:($$anchor3,$$slotProps)=>{
var fragment_1=comment$2(),node_1=first_child(fragment_1);component(node_1,()=>Alert_dialog_content,($$anchor4,AlertDialog_Content)=>{AlertDialog_Content($$anchor4,{children:($$anchor5,$$slotProps2)=>{var fragment_2=root_2$a(),node_2=first_child(fragment_2);component(node_2,()=>Alert_dialog_header,($$anchor6,AlertDialog_Header)=>{AlertDialog_Header($$anchor6,{children:($$anchor7,$$slotProps3)=>{var fragment_3=root_3$7(),node_3=first_child(fragment_3);component(node_3,()=>Alert_dialog_title,($$anchor8,AlertDialog_Title)=>{
AlertDialog_Title($$anchor8,{children:($$anchor9,$$slotProps4)=>{next$1();var text2=text$8("Delete Server");append($$anchor9,text2)},$$slots:{default:!0}})});var node_4=sibling(node_3,2);component(node_4,()=>Alert_dialog_description,($$anchor8,AlertDialog_Description)=>{AlertDialog_Description($$anchor8,{children:($$anchor9,$$slotProps4)=>{next$1();var fragment_4=root_5$6(),strong2=sibling(first_child(fragment_4)),text_1=child(strong2,!0);reset(strong2),next$1(),template_effect(()=>set_text(text_1,

View File

@ -15,6 +15,18 @@
let { logs, connectionTimeMs, defaultExpanded = false, class: className }: Props = $props();
let isExpanded = $derived(defaultExpanded);
function formatLogDetails(details: unknown): string {
if (details == null) {
return '';
}
try {
return JSON.stringify(details, null, 2);
} catch {
return String(details);
}
}
</script>
{#if logs.length > 0}
@ -53,6 +65,16 @@
<span class="break-all">{log.message}</span>
</div>
{#if log.details !== undefined}
<details class="ml-11">
<summary class="cursor-pointer text-[10px] text-muted-foreground"> details </summary>
<pre
class="mt-1 overflow-x-auto rounded bg-background/70 p-2 text-[10px] break-all whitespace-pre-wrap text-foreground/80">
{formatLogDetails(log.details)}</pre>
</details>
{/if}
{/each}
</div>
</Collapsible.Content>

View File

@ -48,6 +48,26 @@ export const EXPECTED_THEMED_ICON_PAIR_COUNT = 2;
/** CORS proxy URL query parameter name */
export const CORS_PROXY_URL_PARAM = 'url';
/** Number of trailing characters to keep visible when partially redacting mcp-session-id */
export const MCP_SESSION_ID_VISIBLE_CHARS = 5;
/** Partial-redaction rules for MCP headers: header name -> visible trailing chars */
export const MCP_PARTIAL_REDACT_HEADERS = new Map<string, number>([
['mcp-session-id', MCP_SESSION_ID_VISIBLE_CHARS]
]);
/** Header names whose values should be redacted in diagnostic logs */
export const REDACTED_HEADERS = new Set([
'authorization',
'api-key',
'cookie',
'mcp-session-id',
'proxy-authorization',
'set-cookie',
'x-auth-token',
'x-api-key'
]);
/** Human-readable labels for MCP transport types */
export const MCP_TRANSPORT_LABELS: Record<MCPTransportType, string> = {
[MCPTransportType.WEBSOCKET]: 'WebSocket',

View File

@ -15,7 +15,8 @@ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
import {
DEFAULT_MCP_CONFIG,
DEFAULT_CLIENT_VERSION,
DEFAULT_IMAGE_MIME_TYPE
DEFAULT_IMAGE_MIME_TYPE,
MCP_PARTIAL_REDACT_HEADERS
} from '$lib/constants';
import {
MCPConnectionPhase,
@ -43,9 +44,17 @@ import {
buildProxiedUrl,
buildProxiedHeaders,
getAuthHeaders,
sanitizeHeaders,
throwIfAborted,
isAbortError,
createBase64DataUrl
createBase64DataUrl,
getRequestUrl,
getRequestMethod,
getRequestBody,
summarizeRequestBody,
formatDiagnosticErrorMessage,
extractJsonRpcMethods,
type RequestBodySummary
} from '$lib/utils';
interface ToolResultContentItem {
@ -62,6 +71,16 @@ interface ToolCallResult {
_meta?: Record<string, unknown>;
}
interface DiagnosticRequestDetails {
url: string;
method: string;
credentials?: RequestCredentials;
mode?: RequestMode;
headers: Record<string, string>;
body: RequestBodySummary;
jsonRpcMethods?: string[];
}
export class MCPService {
/**
* Create a connection log entry for phase tracking.
@ -87,6 +106,225 @@ export class MCPService {
};
}
private static createDiagnosticRequestDetails(
input: RequestInfo | URL,
init: RequestInit | undefined,
baseInit: RequestInit,
requestHeaders: Headers,
extraRedactedHeaders?: Iterable<string>
): DiagnosticRequestDetails {
const body = getRequestBody(input, init);
const details: DiagnosticRequestDetails = {
url: getRequestUrl(input),
method: getRequestMethod(input, init, baseInit).toUpperCase(),
credentials: init?.credentials ?? baseInit.credentials,
mode: init?.mode ?? baseInit.mode,
headers: sanitizeHeaders(requestHeaders, extraRedactedHeaders, MCP_PARTIAL_REDACT_HEADERS),
body: summarizeRequestBody(body)
};
const jsonRpcMethods = extractJsonRpcMethods(body);
if (jsonRpcMethods) {
details.jsonRpcMethods = jsonRpcMethods;
}
return details;
}
private static summarizeError(error: unknown): Record<string, unknown> {
if (error instanceof Error) {
return {
name: error.name,
message: error.message,
cause:
error.cause instanceof Error
? { name: error.cause.name, message: error.cause.message }
: error.cause,
stack: error.stack?.split('\n').slice(0, 6).join('\n')
};
}
return { value: String(error) };
}
private static getBrowserContext(
targetUrl: URL,
useProxy: boolean
): Record<string, unknown> | undefined {
if (typeof window === 'undefined') {
return undefined;
}
return {
location: window.location.href,
origin: window.location.origin,
protocol: window.location.protocol,
isSecureContext: window.isSecureContext,
targetOrigin: targetUrl.origin,
targetProtocol: targetUrl.protocol,
sameOrigin: window.location.origin === targetUrl.origin,
useProxy
};
}
private static getConnectionHints(
targetUrl: URL,
config: MCPServerConfig,
error: unknown
): string[] {
const hints: string[] = [];
const message = error instanceof Error ? error.message : String(error);
const headerNames = Object.keys(config.headers ?? {});
if (typeof window !== 'undefined') {
if (
window.location.protocol === 'https:' &&
targetUrl.protocol === 'http:' &&
!config.useProxy
) {
hints.push(
'The page is running over HTTPS but the MCP server is HTTP. Browsers often block this as mixed content; enable the proxy or use HTTPS/WSS for the MCP server.'
);
}
if (window.location.origin !== targetUrl.origin && !config.useProxy) {
hints.push(
'This is a cross-origin browser request. If the server is reachable from curl or Node but not from the browser, missing CORS headers are the most likely cause.'
);
}
}
if (headerNames.length > 0) {
hints.push(
`Custom request headers are configured (${headerNames.join(', ')}). That triggers a CORS preflight, so the server must allow OPTIONS and include the matching Access-Control-Allow-Headers response.`
);
}
if (config.credentials && config.credentials !== 'omit') {
hints.push(
'Credentials are enabled for this connection. Cross-origin credentialed requests need Access-Control-Allow-Credentials: true and cannot use a wildcard Access-Control-Allow-Origin.'
);
}
if (message.includes('Failed to fetch')) {
hints.push(
'"Failed to fetch" is a browser-level network failure. Common causes are CORS rejection, mixed-content blocking, certificate/TLS errors, DNS failures, or nothing listening on the target port.'
);
}
return hints;
}
private static createDiagnosticFetch(
serverName: string,
config: MCPServerConfig,
baseInit: RequestInit,
targetUrl: URL,
useProxy: boolean,
onLog?: (log: MCPConnectionLog) => void
): {
fetch: typeof fetch;
disable: () => void;
} {
let enabled = true;
const logIfEnabled = (log: MCPConnectionLog) => {
if (enabled) {
onLog?.(log);
}
};
return {
fetch: async (input, init) => {
const startedAt = performance.now();
const requestHeaders = new Headers(baseInit.headers);
if (typeof Request !== 'undefined' && input instanceof Request) {
for (const [key, value] of input.headers.entries()) {
requestHeaders.set(key, value);
}
}
if (init?.headers) {
for (const [key, value] of new Headers(init.headers).entries()) {
requestHeaders.set(key, value);
}
}
const request = this.createDiagnosticRequestDetails(
input,
init,
baseInit,
requestHeaders,
Object.keys(config.headers ?? {})
);
const { method, url } = request;
logIfEnabled(
this.createLog(
MCPConnectionPhase.INITIALIZING,
`HTTP ${method} ${url}`,
MCPLogLevel.INFO,
{
serverName,
request
}
)
);
try {
const response = await fetch(input, {
...baseInit,
...init,
headers: requestHeaders
});
const durationMs = Math.round(performance.now() - startedAt);
logIfEnabled(
this.createLog(
MCPConnectionPhase.INITIALIZING,
`HTTP ${response.status} ${method} ${url} (${durationMs}ms)`,
response.ok ? MCPLogLevel.INFO : MCPLogLevel.WARN,
{
response: {
url,
status: response.status,
statusText: response.statusText,
headers: sanitizeHeaders(response.headers, undefined, MCP_PARTIAL_REDACT_HEADERS),
durationMs
}
}
)
);
return response;
} catch (error) {
const durationMs = Math.round(performance.now() - startedAt);
logIfEnabled(
this.createLog(
MCPConnectionPhase.ERROR,
`HTTP ${method} ${url} failed: ${formatDiagnosticErrorMessage(error)}`,
MCPLogLevel.ERROR,
{
serverName,
request,
error: this.summarizeError(error),
browser: this.getBrowserContext(targetUrl, useProxy),
hints: this.getConnectionHints(targetUrl, config, error),
durationMs
}
)
);
throw error;
}
},
disable: () => {
enabled = false;
}
};
}
/**
* Detect if an error indicates an expired/invalidated MCP session.
* Per MCP spec 2025-11-25: HTTP 404 means session invalidated, client MUST
@ -113,9 +351,14 @@ export class MCPService {
* @returns Object containing the created transport and the transport type used
* @throws {Error} If url is missing, WebSocket + proxy combination, or all transports fail
*/
static createTransport(config: MCPServerConfig): {
static createTransport(
serverName: string,
config: MCPServerConfig,
onLog?: (log: MCPConnectionLog) => void
): {
transport: Transport;
type: MCPTransportType;
stopPhaseLogging: () => void;
} {
if (!config.url) {
throw new Error('MCP server configuration is missing url');
@ -154,11 +397,20 @@ export class MCPService {
return {
transport: new WebSocketClientTransport(url),
type: MCPTransportType.WEBSOCKET
type: MCPTransportType.WEBSOCKET,
stopPhaseLogging: () => {}
};
}
const url = useProxy ? buildProxiedUrl(config.url) : new URL(config.url);
const { fetch: diagnosticFetch, disable: stopPhaseLogging } = this.createDiagnosticFetch(
serverName,
config,
requestInit,
url,
useProxy,
onLog
);
if (useProxy && import.meta.env.DEV) {
console.log(`[MCPService] Using CORS proxy for ${config.url} -> ${url.href}`);
@ -171,17 +423,24 @@ export class MCPService {
return {
transport: new StreamableHTTPClientTransport(url, {
requestInit
requestInit,
fetch: diagnosticFetch
}),
type: MCPTransportType.STREAMABLE_HTTP
type: MCPTransportType.STREAMABLE_HTTP,
stopPhaseLogging
};
} catch (httpError) {
console.warn(`[MCPService] StreamableHTTP failed, trying SSE transport...`, httpError);
try {
return {
transport: new SSEClientTransport(url, { requestInit }),
type: MCPTransportType.SSE
transport: new SSEClientTransport(url, {
requestInit,
fetch: diagnosticFetch,
eventSourceInit: { fetch: diagnosticFetch }
}),
type: MCPTransportType.SSE,
stopPhaseLogging
};
} catch (sseError) {
const httpMsg = httpError instanceof Error ? httpError.message : String(httpError);
@ -263,7 +522,11 @@ export class MCPService {
console.log(`[MCPService][${serverName}] Creating transport...`);
}
const { transport, type: transportType } = this.createTransport(serverConfig);
const {
transport,
type: transportType,
stopPhaseLogging
} = this.createTransport(serverName, serverConfig, (log) => onPhase?.(log.phase, log));
// Setup WebSocket reconnection handler
if (transportType === MCPTransportType.WEBSOCKET) {
@ -294,6 +557,24 @@ export class MCPService {
}
);
const runtimeErrorHandler = (error: Error) => {
console.error(`[MCPService][${serverName}] Protocol error after initialize:`, error);
};
client.onerror = (error) => {
onPhase?.(
MCPConnectionPhase.ERROR,
this.createLog(
MCPConnectionPhase.ERROR,
`Protocol error: ${error.message}`,
MCPLogLevel.ERROR,
{
error: this.summarizeError(error)
}
)
);
};
// Phase: Initializing
onPhase?.(
MCPConnectionPhase.INITIALIZING,
@ -301,7 +582,49 @@ export class MCPService {
);
console.log(`[MCPService][${serverName}] Connecting to server...`);
await client.connect(transport);
try {
await client.connect(transport);
// Transport diagnostics are only for the initial handshake, not long-lived traffic.
stopPhaseLogging();
client.onerror = runtimeErrorHandler;
} catch (error) {
client.onerror = runtimeErrorHandler;
const url =
(serverConfig.useProxy ?? false)
? buildProxiedUrl(serverConfig.url)
: new URL(serverConfig.url);
onPhase?.(
MCPConnectionPhase.ERROR,
this.createLog(
MCPConnectionPhase.ERROR,
`Connection failed during initialize: ${
error instanceof Error ? error.message : String(error)
}`,
MCPLogLevel.ERROR,
{
error: this.summarizeError(error),
config: {
serverName,
configuredUrl: serverConfig.url,
effectiveUrl: url.href,
transportType,
useProxy: serverConfig.useProxy ?? false,
headers: sanitizeHeaders(
serverConfig.headers,
Object.keys(serverConfig.headers ?? {}),
MCP_PARTIAL_REDACT_HEADERS
),
credentials: serverConfig.credentials
},
browser: this.getBrowserContext(url, serverConfig.useProxy ?? false),
hints: this.getConnectionHints(url, serverConfig, error)
}
)
);
throw error;
}
const serverVersion = client.getServerVersion();
const serverCapabilities = client.getServerCapabilities();

View File

@ -1460,12 +1460,14 @@ class MCPStore {
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error occurred';
logs.push({
timestamp: new Date(),
phase: MCPConnectionPhase.ERROR,
message: `Connection failed: ${message}`,
level: MCPLogLevel.ERROR
});
if (logs.at(-1)?.phase !== MCPConnectionPhase.ERROR) {
logs.push({
timestamp: new Date(),
phase: MCPConnectionPhase.ERROR,
message: `Connection failed: ${message}`,
level: MCPLogLevel.ERROR
});
}
this.updateHealthCheck(server.id, {
status: HealthCheckStatus.ERROR,

View File

@ -1,4 +1,6 @@
import { config } from '$lib/stores/settings.svelte';
import { REDACTED_HEADERS } from '$lib/constants';
import { redactValue } from './redact';
/**
* Get authorization headers for API requests
@ -20,3 +22,46 @@ export function getJsonHeaders(): Record<string, string> {
...getAuthHeaders()
};
}
/**
* Sanitize HTTP headers by redacting sensitive values.
* Known sensitive headers (from REDACTED_HEADERS) and any extra headers
* specified by the caller are fully redacted. Headers listed in
* `partialRedactHeaders` are partially redacted, showing only the
* specified number of trailing characters.
*
* @param headers - Headers to sanitize
* @param extraRedactedHeaders - Additional header names to fully redact
* @param partialRedactHeaders - Map of header name -> number of trailing chars to keep visible
* @returns Object with header names as keys and (possibly redacted) values
*/
export function sanitizeHeaders(
headers?: HeadersInit,
extraRedactedHeaders?: Iterable<string>,
partialRedactHeaders?: Map<string, number>
): Record<string, string> {
if (!headers) {
return {};
}
const normalized = new Headers(headers);
const sanitized: Record<string, string> = {};
const redactedHeaders = new Set(
Array.from(extraRedactedHeaders ?? [], (header) => header.toLowerCase())
);
for (const [key, value] of normalized.entries()) {
const normalizedKey = key.toLowerCase();
const partialChars = partialRedactHeaders?.get(normalizedKey);
if (partialChars !== undefined) {
sanitized[key] = redactValue(value, partialChars);
} else if (REDACTED_HEADERS.has(normalizedKey) || redactedHeaders.has(normalizedKey)) {
sanitized[key] = redactValue(value);
} else {
sanitized[key] = value;
}
}
return sanitized;
}

View File

@ -8,7 +8,7 @@
*/
// API utilities
export { getAuthHeaders, getJsonHeaders } from './api-headers';
export { getAuthHeaders, getJsonHeaders, sanitizeHeaders } from './api-headers';
export { apiFetch, apiFetchWithParams, apiPost, type ApiFetchOptions } from './api-fetch';
export { validateApiKey } from './api-key-validation';
@ -164,6 +164,20 @@ export { runLegacyMigration, isMigrationNeeded } from './legacy-migration';
// Cache utilities
export { TTLCache, ReactiveTTLMap, type TTLCacheOptions } from './cache-ttl';
// Redaction utilities
export { redactValue } from './redact';
// Request inspection utilities
export {
getRequestUrl,
getRequestMethod,
getRequestBody,
summarizeRequestBody,
formatDiagnosticErrorMessage,
extractJsonRpcMethods,
type RequestBodySummary
} from './request-helpers';
// Abort signal utilities
export {
throwIfAborted,

View File

@ -0,0 +1,14 @@
/**
* Redacts a sensitive value, optionally showing the last N characters.
*
* @param value - The value to redact
* @param showLastChars - If provided, reveals the last N characters with a leading mask
* @returns The redacted string
*/
export function redactValue(value: string, showLastChars?: number): string {
if (showLastChars) {
return `....${value.slice(-showLastChars)}`;
}
return '[redacted]';
}

View File

@ -0,0 +1,111 @@
/**
* HTTP request inspection utilities for diagnostic logging.
* These helpers extract metadata from fetch-style request arguments
* without exposing sensitive payload data.
*/
export interface RequestBodySummary {
kind: string;
size?: number;
}
export function getRequestUrl(input: RequestInfo | URL): string {
if (typeof input === 'string') {
return input;
}
if (input instanceof URL) {
return input.href;
}
return input.url;
}
export function getRequestMethod(
input: RequestInfo | URL,
init?: RequestInit,
baseInit?: RequestInit
): string {
if (init?.method) {
return init.method;
}
if (typeof Request !== 'undefined' && input instanceof Request) {
return input.method;
}
return baseInit?.method ?? 'GET';
}
export function getRequestBody(
input: RequestInfo | URL,
init?: RequestInit
): BodyInit | null | undefined {
if (init?.body !== undefined) {
return init.body;
}
if (typeof Request !== 'undefined' && input instanceof Request) {
return input.body;
}
return undefined;
}
export function summarizeRequestBody(body: BodyInit | null | undefined): RequestBodySummary {
if (body == null) {
return { kind: 'empty' };
}
if (typeof body === 'string') {
return { kind: 'string', size: body.length };
}
if (body instanceof Blob) {
return { kind: 'blob', size: body.size };
}
if (body instanceof URLSearchParams) {
return { kind: 'urlsearchparams', size: body.toString().length };
}
if (body instanceof FormData) {
return { kind: 'formdata' };
}
if (body instanceof ArrayBuffer) {
return { kind: 'arraybuffer', size: body.byteLength };
}
if (ArrayBuffer.isView(body)) {
return { kind: body.constructor.name, size: body.byteLength };
}
return { kind: typeof body };
}
export function formatDiagnosticErrorMessage(error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
return message.includes('Failed to fetch') ? `${message} (check CORS?)` : message;
}
export function extractJsonRpcMethods(body: BodyInit | null | undefined): string[] | undefined {
if (typeof body !== 'string') {
return undefined;
}
try {
const parsed = JSON.parse(body);
const messages = Array.isArray(parsed) ? parsed : [parsed];
const methods = messages
.map((message: Record<string, unknown>) =>
typeof message?.method === 'string' ? (message.method as string) : undefined
)
.filter((method: string | undefined): method is string => Boolean(method));
return methods.length > 0 ? methods : undefined;
} catch {
return undefined;
}
}

View File

@ -0,0 +1,252 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Client } from '@modelcontextprotocol/sdk/client';
import { MCPService } from '$lib/services/mcp.service';
import { MCPConnectionPhase, MCPTransportType } from '$lib/enums';
import type { MCPConnectionLog, MCPServerConfig } from '$lib/types';
type DiagnosticFetchFactory = (
serverName: string,
config: MCPServerConfig,
baseInit: RequestInit,
targetUrl: URL,
useProxy: boolean,
onLog?: (log: MCPConnectionLog) => void
) => { fetch: typeof fetch; disable: () => void };
const createDiagnosticFetch = (
config: MCPServerConfig,
onLog?: (log: MCPConnectionLog) => void,
baseInit: RequestInit = {}
) =>
(
MCPService as unknown as { createDiagnosticFetch: DiagnosticFetchFactory }
).createDiagnosticFetch('test-server', config, baseInit, new URL(config.url), false, onLog);
describe('MCPService', () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('stops transport phase logging after handshake diagnostics are disabled', async () => {
const logs: MCPConnectionLog[] = [];
const response = new Response('{}', {
status: 200,
headers: { 'content-type': 'application/json' }
});
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
const config: MCPServerConfig = {
url: 'https://example.com/mcp',
transport: MCPTransportType.STREAMABLE_HTTP
};
const controller = createDiagnosticFetch(config, (log) => logs.push(log));
await controller.fetch(config.url, { method: 'POST', body: '{}' });
expect(logs).toHaveLength(2);
expect(logs.every((log) => log.message.includes('https://example.com/mcp'))).toBe(true);
controller.disable();
await controller.fetch(config.url, { method: 'POST', body: '{}' });
expect(logs).toHaveLength(2);
});
it('redacts all configured custom headers in diagnostic request logs', async () => {
const logs: MCPConnectionLog[] = [];
const response = new Response('{}', {
status: 200,
headers: { 'content-type': 'application/json' }
});
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
const config: MCPServerConfig = {
url: 'https://example.com/mcp',
transport: MCPTransportType.STREAMABLE_HTTP,
headers: {
'x-auth-token': 'secret-token',
'x-vendor-api-key': 'secret-key'
}
};
const controller = createDiagnosticFetch(config, (log) => logs.push(log), {
headers: config.headers
});
await controller.fetch(config.url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{}'
});
expect(logs).toHaveLength(2);
expect(logs[0].details).toMatchObject({
request: {
headers: {
'x-auth-token': '[redacted]',
'x-vendor-api-key': '[redacted]',
'content-type': 'application/json'
}
}
});
});
it('partially redacts mcp-session-id in diagnostic request and response logs', async () => {
const logs: MCPConnectionLog[] = [];
const response = new Response('{}', {
status: 200,
headers: {
'content-type': 'application/json',
'mcp-session-id': 'session-response-67890'
}
});
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
const config: MCPServerConfig = {
url: 'https://example.com/mcp',
transport: MCPTransportType.STREAMABLE_HTTP
};
const controller = createDiagnosticFetch(config, (log) => logs.push(log));
await controller.fetch(config.url, {
method: 'POST',
headers: {
'content-type': 'application/json',
'mcp-session-id': 'session-request-12345'
},
body: '{}'
});
expect(logs).toHaveLength(2);
expect(logs[0].details).toMatchObject({
request: {
headers: {
'content-type': 'application/json',
'mcp-session-id': '....12345'
}
}
});
expect(logs[1].details).toMatchObject({
response: {
headers: {
'content-type': 'application/json',
'mcp-session-id': '....67890'
}
}
});
});
it('extracts JSON-RPC methods without logging the raw request body', async () => {
const logs: MCPConnectionLog[] = [];
const response = new Response('{}', {
status: 200,
headers: { 'content-type': 'application/json' }
});
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
const config: MCPServerConfig = {
url: 'https://example.com/mcp',
transport: MCPTransportType.STREAMABLE_HTTP
};
const controller = createDiagnosticFetch(config, (log) => logs.push(log));
await controller.fetch(config.url, {
method: 'POST',
body: JSON.stringify([
{ jsonrpc: '2.0', id: 1, method: 'initialize' },
{ jsonrpc: '2.0', method: 'notifications/initialized' }
])
});
expect(logs[0].details).toMatchObject({
request: {
method: 'POST',
body: {
kind: 'string',
size: expect.any(Number)
},
jsonRpcMethods: ['initialize', 'notifications/initialized']
}
});
});
it('adds a CORS hint to Failed to fetch diagnostic log messages', async () => {
const logs: MCPConnectionLog[] = [];
const fetchError = new TypeError('Failed to fetch');
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(fetchError));
const config: MCPServerConfig = {
url: 'http://localhost:8000/mcp',
transport: MCPTransportType.STREAMABLE_HTTP
};
const controller = createDiagnosticFetch(config, (log) => logs.push(log));
await expect(controller.fetch(config.url, { method: 'POST', body: '{}' })).rejects.toThrow(
'Failed to fetch'
);
expect(logs).toHaveLength(2);
expect(logs[1].message).toBe(
'HTTP POST http://localhost:8000/mcp failed: Failed to fetch (check CORS?)'
);
});
it('detaches phase error logging after the initialize handshake completes', async () => {
const phaseLogs: Array<{ phase: MCPConnectionPhase; log: MCPConnectionLog }> = [];
const stopPhaseLogging = vi.fn();
let emitClientError: ((error: Error) => void) | undefined;
vi.spyOn(MCPService, 'createTransport').mockReturnValue({
transport: {} as never,
type: MCPTransportType.WEBSOCKET,
stopPhaseLogging
});
vi.spyOn(MCPService, 'listTools').mockResolvedValue([]);
vi.spyOn(Client.prototype, 'getServerVersion').mockReturnValue(undefined);
vi.spyOn(Client.prototype, 'getServerCapabilities').mockReturnValue(undefined);
vi.spyOn(Client.prototype, 'getInstructions').mockReturnValue(undefined);
vi.spyOn(Client.prototype, 'connect').mockImplementation(async function (this: Client) {
emitClientError = (error: Error) => this.onerror?.(error);
this.onerror?.(new Error('handshake protocol error'));
});
await MCPService.connect(
'test-server',
{
url: 'ws://example.com/mcp',
transport: MCPTransportType.WEBSOCKET
},
undefined,
undefined,
(phase, log) => phaseLogs.push({ phase, log })
);
expect(stopPhaseLogging).toHaveBeenCalledTimes(1);
expect(
phaseLogs.filter(
({ phase, log }) =>
phase === MCPConnectionPhase.ERROR &&
log.message === 'Protocol error: handshake protocol error'
)
).toHaveLength(1);
emitClientError?.(new Error('runtime protocol error'));
expect(
phaseLogs.filter(
({ phase, log }) =>
phase === MCPConnectionPhase.ERROR &&
log.message === 'Protocol error: runtime protocol error'
)
).toHaveLength(0);
});
});

View File

@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest';
import { redactValue } from '$lib/utils/redact';
describe('redactValue', () => {
it('returns [redacted] by default', () => {
expect(redactValue('secret-token')).toBe('[redacted]');
});
it('shows last N characters when showLastChars is provided', () => {
expect(redactValue('session-abc12', 5)).toBe('....abc12');
});
it('handles value shorter than showLastChars', () => {
expect(redactValue('ab', 5)).toBe('....ab');
});
it('returns [redacted] when showLastChars is 0', () => {
expect(redactValue('secret', 0)).toBe('[redacted]');
});
});

View File

@ -0,0 +1,124 @@
import { describe, expect, it } from 'vitest';
import {
getRequestUrl,
getRequestMethod,
getRequestBody,
summarizeRequestBody,
formatDiagnosticErrorMessage,
extractJsonRpcMethods
} from '$lib/utils/request-helpers';
describe('getRequestUrl', () => {
it('returns a plain string input as-is', () => {
expect(getRequestUrl('https://example.com/mcp')).toBe('https://example.com/mcp');
});
it('returns href from a URL object', () => {
expect(getRequestUrl(new URL('https://example.com/mcp'))).toBe('https://example.com/mcp');
});
it('returns url from a Request object', () => {
const req = new Request('https://example.com/mcp');
expect(getRequestUrl(req)).toBe('https://example.com/mcp');
});
});
describe('getRequestMethod', () => {
it('prefers method from init', () => {
expect(getRequestMethod('https://example.com', { method: 'POST' })).toBe('POST');
});
it('falls back to Request.method', () => {
const req = new Request('https://example.com', { method: 'PUT' });
expect(getRequestMethod(req)).toBe('PUT');
});
it('falls back to baseInit.method', () => {
expect(getRequestMethod('https://example.com', undefined, { method: 'DELETE' })).toBe('DELETE');
});
it('defaults to GET', () => {
expect(getRequestMethod('https://example.com')).toBe('GET');
});
});
describe('getRequestBody', () => {
it('returns body from init', () => {
expect(getRequestBody('https://example.com', { body: 'payload' })).toBe('payload');
});
it('returns undefined when no body is present', () => {
expect(getRequestBody('https://example.com')).toBeUndefined();
});
});
describe('summarizeRequestBody', () => {
it('returns empty for null', () => {
expect(summarizeRequestBody(null)).toEqual({ kind: 'empty' });
});
it('returns empty for undefined', () => {
expect(summarizeRequestBody(undefined)).toEqual({ kind: 'empty' });
});
it('returns string kind with size', () => {
expect(summarizeRequestBody('hello')).toEqual({ kind: 'string', size: 5 });
});
it('returns blob kind with size', () => {
const blob = new Blob(['abc']);
expect(summarizeRequestBody(blob)).toEqual({ kind: 'blob', size: 3 });
});
it('returns formdata kind', () => {
expect(summarizeRequestBody(new FormData())).toEqual({ kind: 'formdata' });
});
it('returns arraybuffer kind with size', () => {
expect(summarizeRequestBody(new ArrayBuffer(8))).toEqual({ kind: 'arraybuffer', size: 8 });
});
});
describe('formatDiagnosticErrorMessage', () => {
it('appends CORS hint for Failed to fetch', () => {
expect(formatDiagnosticErrorMessage(new TypeError('Failed to fetch'))).toBe(
'Failed to fetch (check CORS?)'
);
});
it('passes through other error messages unchanged', () => {
expect(formatDiagnosticErrorMessage(new Error('timeout'))).toBe('timeout');
});
it('handles non-Error values', () => {
expect(formatDiagnosticErrorMessage('some string')).toBe('some string');
});
});
describe('extractJsonRpcMethods', () => {
it('extracts methods from a JSON-RPC array', () => {
const body = JSON.stringify([
{ jsonrpc: '2.0', id: 1, method: 'initialize' },
{ jsonrpc: '2.0', method: 'notifications/initialized' }
]);
expect(extractJsonRpcMethods(body)).toEqual(['initialize', 'notifications/initialized']);
});
it('extracts method from a single JSON-RPC message', () => {
const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
expect(extractJsonRpcMethods(body)).toEqual(['tools/list']);
});
it('returns undefined for non-string body', () => {
expect(extractJsonRpcMethods(null)).toBeUndefined();
expect(extractJsonRpcMethods(undefined)).toBeUndefined();
});
it('returns undefined for invalid JSON', () => {
expect(extractJsonRpcMethods('not json')).toBeUndefined();
});
it('returns undefined when no methods found', () => {
expect(extractJsonRpcMethods(JSON.stringify({ foo: 'bar' }))).toBeUndefined();
});
});

View File

@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { sanitizeHeaders } from '$lib/utils/api-headers';
describe('sanitizeHeaders', () => {
it('returns empty object for undefined input', () => {
expect(sanitizeHeaders()).toEqual({});
});
it('passes through non-sensitive headers', () => {
const headers = new Headers({ 'content-type': 'application/json', accept: 'text/html' });
expect(sanitizeHeaders(headers)).toEqual({
'content-type': 'application/json',
accept: 'text/html'
});
});
it('redacts known sensitive headers', () => {
const headers = new Headers({
authorization: 'Bearer secret',
'x-api-key': 'key-123',
'content-type': 'application/json'
});
const result = sanitizeHeaders(headers);
expect(result.authorization).toBe('[redacted]');
expect(result['x-api-key']).toBe('[redacted]');
expect(result['content-type']).toBe('application/json');
});
it('partially redacts headers specified in partialRedactHeaders', () => {
const headers = new Headers({ 'mcp-session-id': 'session-12345' });
const partial = new Map([['mcp-session-id', 5]]);
expect(sanitizeHeaders(headers, undefined, partial)['mcp-session-id']).toBe('....12345');
});
it('fully redacts mcp-session-id when no partialRedactHeaders is given', () => {
const headers = new Headers({ 'mcp-session-id': 'session-12345' });
expect(sanitizeHeaders(headers)['mcp-session-id']).toBe('[redacted]');
});
it('redacts extra headers provided by the caller', () => {
const headers = new Headers({
'x-vendor-key': 'vendor-secret',
'content-type': 'application/json'
});
const result = sanitizeHeaders(headers, ['x-vendor-key']);
expect(result['x-vendor-key']).toBe('[redacted]');
expect(result['content-type']).toBe('application/json');
});
it('handles case-insensitive extra header names', () => {
const headers = new Headers({ 'X-Custom-Token': 'token-value' });
const result = sanitizeHeaders(headers, ['X-CUSTOM-TOKEN']);
expect(result['x-custom-token']).toBe('[redacted]');
});
});