diff --git a/README.md b/README.md index e82238f9..ec9bf30a 100644 --- a/README.md +++ b/README.md @@ -260,8 +260,8 @@ areno train \ ``` The tuner uses dummy-loaded model weights and synthetic token rows, respects -the configured sequence limits and tensor-parallel size, and enables -`--drop-rollout-state` for the tuned run. See `docs/cli/training.rst` for the +the configured sequence limits and tensor-parallel size, and uses the default +dropped rollout state for the tuned run. See `docs/cli/training.rst` for the full tuning rules. For Agentic RL, add `--agent-fn` to supply an agent function. The agent calls the local OpenAI-compatible endpoint, including `tools` and `tool_choice` when needed, and returns explicit `AgentTrajectoryTurn` objects. AReno converts those turns into trainable assistant outputs and masks tool results by default: diff --git a/areno/api/config.py b/areno/api/config.py index cfd5b27b..8aaa4654 100644 --- a/areno/api/config.py +++ b/areno/api/config.py @@ -68,7 +68,7 @@ class MlxConfig: prefill_step_size: int = 2048 max_kv_size: int | None = None decode_progress_interval_s: float = 10.0 - keep_rollout_state: bool = True + keep_rollout_state: bool = False logits_chunk_size: int = 4096 compile_train_step: bool = True gradient_checkpointing: bool = True diff --git a/areno/api/trainer_config.py b/areno/api/trainer_config.py index 7db26af3..00dd9bd2 100644 --- a/areno/api/trainer_config.py +++ b/areno/api/trainer_config.py @@ -69,7 +69,12 @@ class TrainerConfig: multimodal_projector_lr_decay_steps: int | None = None multimodal_projector_lr_decay_style: str | None = None activation_checkpointing: bool = True - keep_rollout_state: bool = True + fp8_checkpoint_activations: bool | None = None + fp8_checkpoint_group_size: int = 128 + fp8_checkpoint_stochastic: bool = False + fp8_checkpoint_warmup_steps: int = 0 + fp8_checkpoint_fallback_layers: tuple[int, ...] = () + keep_rollout_state: bool = False optimizer_state_offload: str | bool = "none" optimizer_state_offload_dir: str | None = None optimizer_state_offload_batch_size: int = 1 @@ -89,12 +94,25 @@ def __post_init__(self) -> None: self.backend = default_backend_type().value.lower() else: self.backend = self.backend.lower() + if self.fp8_checkpoint_activations is None: + self.fp8_checkpoint_activations = self.backend == "cuda" and self.activation_checkpointing + self.fp8_checkpoint_fallback_layers = tuple(self.fp8_checkpoint_fallback_layers) if self.backend not in {"cuda", "mlx"}: raise ValueError("backend must be one of: cuda, mlx") if self.adam_4bit and self.adam_8bit: raise ValueError("adam_4bit and adam_8bit are mutually exclusive") if self.adam_4bit and self.backend != "cuda": raise ValueError("adam_4bit is only supported by the CUDA backend") + if self.fp8_checkpoint_activations and self.backend != "cuda": + raise ValueError("fp8_checkpoint_activations is only supported by the CUDA backend") + if self.fp8_checkpoint_activations and not self.activation_checkpointing: + raise ValueError("fp8_checkpoint_activations requires activation_checkpointing") + if self.fp8_checkpoint_group_size not in {0, 128, 256}: + raise ValueError("fp8_checkpoint_group_size must be one of: 0, 128, 256") + if self.fp8_checkpoint_warmup_steps < 0: + raise ValueError("fp8_checkpoint_warmup_steps must be non-negative") + if any(layer < 0 for layer in self.fp8_checkpoint_fallback_layers): + raise ValueError("fp8_checkpoint_fallback_layers must contain non-negative indices") if self.attn_backend not in {"flash", "native"}: raise ValueError("attn_backend must be one of: flash, native") if self.model_hub not in {"hf", "modelscope"}: @@ -216,6 +234,11 @@ def cuda_config(self): optimizer=self.optimizer_config(), runtime={ "activation_checkpointing": self.activation_checkpointing, + "fp8_checkpoint_activations": self.fp8_checkpoint_activations, + "fp8_checkpoint_group_size": self.fp8_checkpoint_group_size, + "fp8_checkpoint_stochastic": self.fp8_checkpoint_stochastic, + "fp8_checkpoint_warmup_steps": self.fp8_checkpoint_warmup_steps, + "fp8_checkpoint_fallback_layers": self.fp8_checkpoint_fallback_layers, "keep_rollout_state": self.keep_rollout_state, "optimizer_state_offload": self.optimizer_state_offload, "optimizer_state_offload_dir": self.optimizer_state_offload_dir, @@ -266,6 +289,11 @@ def cuda_config(self): optimizer=self.optimizer_config(), runtime={ "activation_checkpointing": self.activation_checkpointing, + "fp8_checkpoint_activations": self.fp8_checkpoint_activations, + "fp8_checkpoint_group_size": self.fp8_checkpoint_group_size, + "fp8_checkpoint_stochastic": self.fp8_checkpoint_stochastic, + "fp8_checkpoint_warmup_steps": self.fp8_checkpoint_warmup_steps, + "fp8_checkpoint_fallback_layers": self.fp8_checkpoint_fallback_layers, "keep_rollout_state": self.keep_rollout_state, "optimizer_state_offload": self.optimizer_state_offload, "optimizer_state_offload_dir": self.optimizer_state_offload_dir, diff --git a/areno/cli/train.py b/areno/cli/train.py index 1de993a3..d09d42be 100644 --- a/areno/cli/train.py +++ b/areno/cli/train.py @@ -132,6 +132,7 @@ def flash_attention_unsupported_model_reason(model_config): "score_micro_bs", "gradient_accumulation_steps", "activation_checkpointing", + "fp8_checkpoint_activations", "lora_rank", "lora_alpha", "lora_dropout", @@ -240,6 +241,7 @@ def _trainer_config_from_options(**options) -> TrainerConfig: args.rollout_devices = getattr(args, "rollout_devices", None) args.policy_sync_bucket_mb = getattr(args, "policy_sync_bucket_mb", 64) args.adam_4bit = getattr(args, "adam_4bit", False) + args.fp8_checkpoint_activations = getattr(args, "fp8_checkpoint_activations", None) args.optimizer_state_offload = getattr(args, "optimizer_state_offload", "none") args.optimizer_state_offload_dir = getattr(args, "optimizer_state_offload_dir", None) args.optimizer_state_offload_batch_size = getattr(args, "optimizer_state_offload_batch_size", 1) @@ -525,6 +527,7 @@ def _format_training_config_summary( [ ("max_steps", _format_optional(config.max_steps)), ("sequence_parallel", _sequence_parallel_for_summary(config, model_config)), + ("fp8_ckpt_activations", _format_bool(config.fp8_checkpoint_activations)), ("mini_bs", str(config.mini_bs)), ("score_micro_bs", str(config.score_micro_bs)), ("gradient_accumulation_steps", _format_optional(config.gradient_accumulation_steps, default="auto")), @@ -848,6 +851,7 @@ def _trainer_config_from_args(args) -> TrainerConfig: args.rollout_devices = getattr(args, "rollout_devices", None) args.policy_sync_bucket_mb = getattr(args, "policy_sync_bucket_mb", 64) args.adam_4bit = getattr(args, "adam_4bit", False) + args.fp8_checkpoint_activations = getattr(args, "fp8_checkpoint_activations", None) args.unfreeze_multimodal_tower = getattr(args, "unfreeze_multimodal_tower", False) args.unfreeze_multimodal_projector = getattr(args, "unfreeze_multimodal_projector", False) args.multimodal_tower_lr = getattr(args, "multimodal_tower_lr", None) @@ -907,6 +911,7 @@ def _trainer_config_from_args(args) -> TrainerConfig: multimodal_projector_lr_decay_steps=args.multimodal_projector_lr_decay_steps, multimodal_projector_lr_decay_style=args.multimodal_projector_lr_decay_style, activation_checkpointing=args.activation_checkpointing, + fp8_checkpoint_activations=args.fp8_checkpoint_activations, keep_rollout_state=not args.drop_rollout_state, optimizer_state_offload=args.optimizer_state_offload, optimizer_state_offload_dir=args.optimizer_state_offload_dir, @@ -967,6 +972,7 @@ def _trainer_config_from_args(args) -> TrainerConfig: multimodal_projector_lr_decay_steps=args.multimodal_projector_lr_decay_steps, multimodal_projector_lr_decay_style=args.multimodal_projector_lr_decay_style, activation_checkpointing=args.activation_checkpointing, + fp8_checkpoint_activations=args.fp8_checkpoint_activations, keep_rollout_state=not args.drop_rollout_state, optimizer_state_offload=args.optimizer_state_offload, optimizer_state_offload_dir=args.optimizer_state_offload_dir, @@ -1035,6 +1041,7 @@ def _trainer_config_from_args(args) -> TrainerConfig: multimodal_projector_lr_decay_steps=args.multimodal_projector_lr_decay_steps, multimodal_projector_lr_decay_style=args.multimodal_projector_lr_decay_style, activation_checkpointing=args.activation_checkpointing, + fp8_checkpoint_activations=args.fp8_checkpoint_activations, keep_rollout_state=not args.drop_rollout_state, optimizer_state_offload=args.optimizer_state_offload, optimizer_state_offload_dir=args.optimizer_state_offload_dir, @@ -1104,6 +1111,7 @@ def _trainer_config_from_args(args) -> TrainerConfig: multimodal_projector_lr_decay_steps=args.multimodal_projector_lr_decay_steps, multimodal_projector_lr_decay_style=args.multimodal_projector_lr_decay_style, activation_checkpointing=args.activation_checkpointing, + fp8_checkpoint_activations=args.fp8_checkpoint_activations, keep_rollout_state=not args.drop_rollout_state, optimizer_state_offload=args.optimizer_state_offload, optimizer_state_offload_dir=args.optimizer_state_offload_dir, @@ -1232,6 +1240,7 @@ def section(title: str, names: list[str]) -> dict: "attn_backend", "eager_decode", "activation_checkpointing", + "fp8_checkpoint_activations", "keep_rollout_state", "optimizer_state_offload", "optimizer_state_offload_dir", @@ -1753,8 +1762,15 @@ def _dataset_builder_for_suffix(suffix: str) -> str: help="Enable decoder-layer activation recompute during training.", ) @click.option( - "--drop-rollout-state", - is_flag=True, + "--fp8-ckpt-activations/--no-fp8-ckpt-activations", + "fp8_checkpoint_activations", + default=None, + help="Store activation-checkpoint boundary tensors in FP8 E4M3 (enabled by default on CUDA).", +) +@click.option( + "--drop-rollout-state/--keep-rollout-state", + default=True, + show_default=True, help="Release completed rollout KV/cache state after each step.", ) @click.option( diff --git a/areno/dashboard/dist/assets/index-B4DqcGQ-.js b/areno/dashboard/dist/assets/index-CTi7Ypoy.js similarity index 84% rename from areno/dashboard/dist/assets/index-B4DqcGQ-.js rename to areno/dashboard/dist/assets/index-CTi7Ypoy.js index e0cdf8c2..998d7259 100644 --- a/areno/dashboard/dist/assets/index-B4DqcGQ-.js +++ b/areno/dashboard/dist/assets/index-CTi7Ypoy.js @@ -14,7 +14,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var np;function Yx(){if(np)return Ae;np=1;var n=Symbol.for("react.transitional.element"),i=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),u=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),f=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),x=Symbol.for("react.activity"),v=Symbol.iterator;function S(T){return T===null||typeof T!="object"?null:(T=v&&T[v]||T["@@iterator"],typeof T=="function"?T:null)}var w={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},j=Object.assign,q={};function N(T,G,k){this.props=T,this.context=G,this.refs=q,this.updater=k||w}N.prototype.isReactComponent={},N.prototype.setState=function(T,G){if(typeof T!="object"&&typeof T!="function"&&T!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,T,G,"setState")},N.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function K(){}K.prototype=N.prototype;function Y(T,G,k){this.props=T,this.context=G,this.refs=q,this.updater=k||w}var se=Y.prototype=new K;se.constructor=Y,j(se,N.prototype),se.isPureReactComponent=!0;var ae=Array.isArray;function U(){}var ne={H:null,A:null,T:null,S:null},ue=Object.prototype.hasOwnProperty;function ye(T,G,k){var le=k.ref;return{$$typeof:n,type:T,key:G,ref:le!==void 0?le:null,props:k}}function R(T,G){return ye(T.type,G,T.props)}function Q(T){return typeof T=="object"&&T!==null&&T.$$typeof===n}function W(T){var G={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(k){return G[k]})}var de=/\/+/g;function re(T,G){return typeof T=="object"&&T!==null&&T.key!=null?W(""+T.key):G.toString(36)}function I(T){switch(T.status){case"fulfilled":return T.value;case"rejected":throw T.reason;default:switch(typeof T.status=="string"?T.then(U,U):(T.status="pending",T.then(function(G){T.status==="pending"&&(T.status="fulfilled",T.value=G)},function(G){T.status==="pending"&&(T.status="rejected",T.reason=G)})),T.status){case"fulfilled":return T.value;case"rejected":throw T.reason}}throw T}function M(T,G,k,le,pe){var he=typeof T;(he==="undefined"||he==="boolean")&&(T=null);var je=!1;if(T===null)je=!0;else switch(he){case"bigint":case"string":case"number":je=!0;break;case"object":switch(T.$$typeof){case n:case i:je=!0;break;case y:return je=T._init,M(je(T._payload),G,k,le,pe)}}if(je)return pe=pe(T),je=le===""?"."+re(T,0):le,ae(pe)?(k="",je!=null&&(k=je.replace(de,"$&/")+"/"),M(pe,G,k,"",function(At){return At})):pe!=null&&(Q(pe)&&(pe=R(pe,k+(pe.key==null||T&&T.key===pe.key?"":(""+pe.key).replace(de,"$&/")+"/")+je)),G.push(pe)),1;je=0;var we=le===""?".":le+":";if(ae(T))for(var Ue=0;Ue>>1,A=M[xe];if(0>>1;xeo(k,P))leo(pe,k)?(M[xe]=pe,M[le]=P,xe=le):(M[xe]=k,M[G]=P,xe=G);else if(leo(pe,P))M[xe]=pe,M[le]=P,xe=le;else break e}}return J}function o(M,J){var P=M.sortIndex-J.sortIndex;return P!==0?P:M.id-J.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;n.unstable_now=function(){return c.now()}}else{var f=Date,h=f.now();n.unstable_now=function(){return f.now()-h}}var g=[],p=[],y=1,x=null,v=3,S=!1,w=!1,j=!1,q=!1,N=typeof setTimeout=="function"?setTimeout:null,K=typeof clearTimeout=="function"?clearTimeout:null,Y=typeof setImmediate<"u"?setImmediate:null;function se(M){for(var J=r(p);J!==null;){if(J.callback===null)u(p);else if(J.startTime<=M)u(p),J.sortIndex=J.expirationTime,i(g,J);else break;J=r(p)}}function ae(M){if(j=!1,se(M),!w)if(r(g)!==null)w=!0,U||(U=!0,W());else{var J=r(p);J!==null&&I(ae,J.startTime-M)}}var U=!1,ne=-1,ue=5,ye=-1;function R(){return q?!0:!(n.unstable_now()-yeM&&R());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,v=x.priorityLevel;var A=xe(x.expirationTime<=M);if(M=n.unstable_now(),typeof A=="function"){x.callback=A,se(M),J=!0;break t}x===r(g)&&u(g),se(M)}else u(g);x=r(g)}if(x!==null)J=!0;else{var T=r(p);T!==null&&I(ae,T.startTime-M),J=!1}}break e}finally{x=null,v=P,S=!1}J=void 0}}finally{J?W():U=!1}}}var W;if(typeof Y=="function")W=function(){Y(Q)};else if(typeof MessageChannel<"u"){var de=new MessageChannel,re=de.port2;de.port1.onmessage=Q,W=function(){re.postMessage(null)}}else W=function(){N(Q,0)};function I(M,J){ne=N(function(){M(n.unstable_now())},J)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(M){M.callback=null},n.unstable_forceFrameRate=function(M){0>M||125xe?(M.sortIndex=P,i(p,M),r(g)===null&&M===r(p)&&(j?(K(ne),ne=-1):j=!0,I(ae,P-xe))):(M.sortIndex=A,i(g,M),w||S||(w=!0,U||(U=!0,W()))),M},n.unstable_shouldYield=R,n.unstable_wrapCallback=function(M){var J=v;return function(){var P=v;v=J;try{return M.apply(this,arguments)}finally{v=P}}}})(sc)),sc}var ap;function Qx(){return ap||(ap=1,uc.exports=Vx()),uc.exports}var oc={exports:{}},Rt={};/** + */var ip;function Vx(){return ip||(ip=1,(function(n){function i(M,J){var P=M.length;M.push(J);e:for(;0>>1,A=M[xe];if(0>>1;xeo(k,P))leo(pe,k)?(M[xe]=pe,M[le]=P,xe=le):(M[xe]=k,M[G]=P,xe=G);else if(leo(pe,P))M[xe]=pe,M[le]=P,xe=le;else break e}}return J}function o(M,J){var P=M.sortIndex-J.sortIndex;return P!==0?P:M.id-J.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;n.unstable_now=function(){return c.now()}}else{var f=Date,h=f.now();n.unstable_now=function(){return f.now()-h}}var g=[],p=[],y=1,x=null,b=3,S=!1,w=!1,j=!1,q=!1,N=typeof setTimeout=="function"?setTimeout:null,K=typeof clearTimeout=="function"?clearTimeout:null,Y=typeof setImmediate<"u"?setImmediate:null;function se(M){for(var J=r(p);J!==null;){if(J.callback===null)u(p);else if(J.startTime<=M)u(p),J.sortIndex=J.expirationTime,i(g,J);else break;J=r(p)}}function ae(M){if(j=!1,se(M),!w)if(r(g)!==null)w=!0,U||(U=!0,W());else{var J=r(p);J!==null&&I(ae,J.startTime-M)}}var U=!1,ne=-1,ue=5,ye=-1;function R(){return q?!0:!(n.unstable_now()-yeM&&R());){var xe=x.callback;if(typeof xe=="function"){x.callback=null,b=x.priorityLevel;var A=xe(x.expirationTime<=M);if(M=n.unstable_now(),typeof A=="function"){x.callback=A,se(M),J=!0;break t}x===r(g)&&u(g),se(M)}else u(g);x=r(g)}if(x!==null)J=!0;else{var T=r(p);T!==null&&I(ae,T.startTime-M),J=!1}}break e}finally{x=null,b=P,S=!1}J=void 0}}finally{J?W():U=!1}}}var W;if(typeof Y=="function")W=function(){Y(Q)};else if(typeof MessageChannel<"u"){var de=new MessageChannel,re=de.port2;de.port1.onmessage=Q,W=function(){re.postMessage(null)}}else W=function(){N(Q,0)};function I(M,J){ne=N(function(){M(n.unstable_now())},J)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(M){M.callback=null},n.unstable_forceFrameRate=function(M){0>M||125xe?(M.sortIndex=P,i(p,M),r(g)===null&&M===r(p)&&(j?(K(ne),ne=-1):j=!0,I(ae,P-xe))):(M.sortIndex=A,i(g,M),w||S||(w=!0,U||(U=!0,W()))),M},n.unstable_shouldYield=R,n.unstable_wrapCallback=function(M){var J=b;return function(){var P=b;b=J;try{return M.apply(this,arguments)}finally{b=P}}}})(sc)),sc}var ap;function Qx(){return ap||(ap=1,uc.exports=Vx()),uc.exports}var oc={exports:{}},Rt={};/** * @license React * react-dom.production.js * @@ -30,7 +30,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var rp;function Xx(){if(rp)return Rt;rp=1;var n=Yc();function i(g){var p="https://react.dev/errors/"+g;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(i){console.error(i)}}return n(),oc.exports=Xx(),oc.exports}/** + */var rp;function Xx(){if(rp)return Rt;rp=1;var n=Yc();function i(g){var p="https://react.dev/errors/"+g;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(i){console.error(i)}}return n(),oc.exports=Xx(),oc.exports}/** * @license React * react-dom-client.production.js * @@ -38,48 +38,48 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var sp;function Fx(){if(sp)return Ia;sp=1;var n=Qx(),i=Yc(),r=Zx();function u(e){var t="https://react.dev/errors/"+e;if(1A||(e.current=xe[A],xe[A]=null,A--)}function k(e,t){A++,xe[A]=e.current,e.current=t}var le=T(null),pe=T(null),he=T(null),je=T(null);function we(e,t){switch(k(he,t),k(pe,e),k(le,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?km(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=km(t),e=Am(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}G(le),k(le,e)}function Ue(){G(le),G(pe),G(he)}function At(e){e.memoizedState!==null&&k(je,e);var t=le.current,l=Am(t,e.type);t!==l&&(k(pe,e),k(le,l))}function nt(e){pe.current===e&&(G(le),G(pe)),je.current===e&&(G(je),Za._currentValue=P)}var Dt,si;function Ut(e){if(Dt===void 0)try{throw Error()}catch(l){var t=l.stack.trim().match(/\n( *(at )?)/);Dt=t&&t[1]||"",si=-1A||(e.current=xe[A],xe[A]=null,A--)}function k(e,t){A++,xe[A]=e.current,e.current=t}var le=T(null),pe=T(null),he=T(null),je=T(null);function we(e,t){switch(k(he,t),k(pe,e),k(le,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?km(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=km(t),e=Am(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}G(le),k(le,e)}function Ue(){G(le),G(pe),G(he)}function At(e){e.memoizedState!==null&&k(je,e);var t=le.current,l=Am(t,e.type);t!==l&&(k(pe,e),k(le,l))}function nt(e){pe.current===e&&(G(le),G(pe)),je.current===e&&(G(je),Za._currentValue=P)}var Dt,si;function Ut(e){if(Dt===void 0)try{throw Error()}catch(l){var t=l.stack.trim().match(/\n( *(at )?)/);Dt=t&&t[1]||"",si=-1)":-1s||E[a]!==O[s]){var V=` `+E[a].replace(" at new "," at ");return e.displayName&&V.includes("")&&(V=V.replace("",e.displayName)),V}while(1<=a&&0<=s);break}}}finally{sl=!1,Error.prepareStackTrace=l}return(l=e?e.displayName||e.name:"")?Ut(l):""}function oi(e,t){switch(e.tag){case 26:case 27:case 5:return Ut(e.type);case 16:return Ut("Lazy");case 13:return e.child!==t&&t!==null?Ut("Suspense Fallback"):Ut("Suspense");case 19:return Ut("SuspenseList");case 0:case 15:return ol(e.type,!1);case 11:return ol(e.type.render,!1);case 1:return ol(e.type,!0);case 31:return Ut("Activity");default:return""}}function qn(e){try{var t="",l=null;do t+=oi(e,l),l=e,e=e.return;while(e);return t}catch(a){return` Error generating stack: `+a.message+` -`+a.stack}}var Ht=Object.prototype.hasOwnProperty,Yt=n.unstable_scheduleCallback,Wt=n.unstable_cancelCallback,Cn=n.unstable_shouldYield,kn=n.unstable_requestPaint,ut=n.unstable_now,ia=n.unstable_getCurrentPriorityLevel,B=n.unstable_ImmediatePriority,te=n.unstable_UserBlockingPriority,ve=n.unstable_NormalPriority,Ce=n.unstable_LowPriority,Oe=n.unstable_IdlePriority,St=n.log,fn=n.unstable_setDisableYieldValue,wt=null,ot=null;function Ot(e){if(typeof St=="function"&&fn(e),ot&&typeof ot.setStrictMode=="function")try{ot.setStrictMode(wt,e)}catch{}}var Qe=Math.clz32?Math.clz32:Ku,zn=Math.log,Vt=Math.LN2;function Ku(e){return e>>>=0,e===0?32:31-(zn(e)/Vt|0)|0}var ci=256,fi=262144,di=4194304;function en(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function hi(e,t,l){var a=e.pendingLanes;if(a===0)return 0;var s=0,d=e.suspendedLanes,b=e.pingedLanes;e=e.warmLanes;var _=a&134217727;return _!==0?(a=_&~d,a!==0?s=en(a):(b&=_,b!==0?s=en(b):l||(l=_&~e,l!==0&&(s=en(l))))):(_=a&~d,_!==0?s=en(_):b!==0?s=en(b):l||(l=a&~e,l!==0&&(s=en(l)))),s===0?0:t!==0&&t!==s&&(t&d)===0&&(d=s&-s,l=t&-t,d>=l||d===32&&(l&4194048)!==0)?t:s}function cl(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function fr(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function aa(){var e=di;return di<<=1,(di&62914560)===0&&(di=4194304),e}function ra(e){for(var t=[],l=0;31>l;l++)t.push(e);return t}function Gn(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Ju(e,t,l,a,s,d){var b=e.pendingLanes;e.pendingLanes=l,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=l,e.entangledLanes&=l,e.errorRecoveryDisabledLanes&=l,e.shellSuspendCounter=0;var _=e.entanglements,E=e.expirationTimes,O=e.hiddenUpdates;for(l=b&~l;0"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var Oy=/[\n"\\]/g;function hn(e){return e.replace(Oy,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function Iu(e,t,l,a,s,d,b,_){e.name="",b!=null&&typeof b!="function"&&typeof b!="symbol"&&typeof b!="boolean"?e.type=b:e.removeAttribute("type"),t!=null?b==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+dn(t)):e.value!==""+dn(t)&&(e.value=""+dn(t)):b!=="submit"&&b!=="reset"||e.removeAttribute("value"),t!=null?Pu(e,b,dn(t)):l!=null?Pu(e,b,dn(l)):a!=null&&e.removeAttribute("value"),s==null&&d!=null&&(e.defaultChecked=!!d),s!=null&&(e.checked=s&&typeof s!="function"&&typeof s!="symbol"),_!=null&&typeof _!="function"&&typeof _!="symbol"&&typeof _!="boolean"?e.name=""+dn(_):e.removeAttribute("name")}function yf(e,t,l,a,s,d,b,_){if(d!=null&&typeof d!="function"&&typeof d!="symbol"&&typeof d!="boolean"&&(e.type=d),t!=null||l!=null){if(!(d!=="submit"&&d!=="reset"||t!=null)){$u(e);return}l=l!=null?""+dn(l):"",t=t!=null?""+dn(t):l,_||t===e.value||(e.value=t),e.defaultValue=t}a=a??s,a=typeof a!="function"&&typeof a!="symbol"&&!!a,e.checked=_?e.checked:!!a,e.defaultChecked=!!a,b!=null&&typeof b!="function"&&typeof b!="symbol"&&typeof b!="boolean"&&(e.name=b),$u(e)}function Pu(e,t,l){t==="number"&&br(e.ownerDocument)===e||e.defaultValue===""+l||(e.defaultValue=""+l)}function xi(e,t,l,a){if(e=e.options,t){t={};for(var s=0;s"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ls=!1;if(Xn)try{var ca={};Object.defineProperty(ca,"passive",{get:function(){ls=!0}}),window.addEventListener("test",ca,ca),window.removeEventListener("test",ca,ca)}catch{ls=!1}var fl=null,is=null,Sr=null;function Af(){if(Sr)return Sr;var e,t=is,l=t.length,a,s="value"in fl?fl.value:fl.textContent,d=s.length;for(e=0;e=ha),zf=" ",Nf=!1;function Mf(e,t){switch(e){case"keyup":return s1.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Df(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var _i=!1;function c1(e,t){switch(e){case"compositionend":return Df(t);case"keypress":return t.which!==32?null:(Nf=!0,zf);case"textInput":return e=t.data,e===zf&&Nf?null:e;default:return null}}function f1(e,t){if(_i)return e==="compositionend"||!os&&Mf(e,t)?(e=Af(),Sr=is=fl=null,_i=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:l,offset:t-e};e=a}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Gf(l)}}function Vf(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Vf(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Qf(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=br(e.document);t instanceof e.HTMLIFrameElement;){try{var l=typeof t.contentWindow.location.href=="string"}catch{l=!1}if(l)e=t.contentWindow;else break;t=br(e.document)}return t}function ds(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var b1=Xn&&"documentMode"in document&&11>=document.documentMode,ki=null,hs=null,ya=null,ms=!1;function Xf(e,t,l){var a=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;ms||ki==null||ki!==br(a)||(a=ki,"selectionStart"in a&&ds(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),ya&&ga(ya,a)||(ya=a,a=mu(hs,"onSelect"),0>=b,s-=b,Dn=1<<32-Qe(t)+s|l<ze?(Le=me,me=null):Le=me.sibling;var Ge=L(z,me,D[ze],X);if(Ge===null){me===null&&(me=Le);break}e&&me&&Ge.alternate===null&&t(z,me),C=d(Ge,C,ze),qe===null?ge=Ge:qe.sibling=Ge,qe=Ge,me=Le}if(ze===D.length)return l(z,me),Be&&Fn(z,ze),ge;if(me===null){for(;zeze?(Le=me,me=null):Le=me.sibling;var Dl=L(z,me,Ge.value,X);if(Dl===null){me===null&&(me=Le);break}e&&me&&Dl.alternate===null&&t(z,me),C=d(Dl,C,ze),qe===null?ge=Dl:qe.sibling=Dl,qe=Dl,me=Le}if(Ge.done)return l(z,me),Be&&Fn(z,ze),ge;if(me===null){for(;!Ge.done;ze++,Ge=D.next())Ge=Z(z,Ge.value,X),Ge!==null&&(C=d(Ge,C,ze),qe===null?ge=Ge:qe.sibling=Ge,qe=Ge);return Be&&Fn(z,ze),ge}for(me=a(me);!Ge.done;ze++,Ge=D.next())Ge=H(me,z,ze,Ge.value,X),Ge!==null&&(e&&Ge.alternate!==null&&me.delete(Ge.key===null?ze:Ge.key),C=d(Ge,C,ze),qe===null?ge=Ge:qe.sibling=Ge,qe=Ge);return e&&me.forEach(function(Hx){return t(z,Hx)}),Be&&Fn(z,ze),ge}function Ie(z,C,D,X){if(typeof D=="object"&&D!==null&&D.type===j&&D.key===null&&(D=D.props.children),typeof D=="object"&&D!==null){switch(D.$$typeof){case S:e:{for(var ge=D.key;C!==null;){if(C.key===ge){if(ge=D.type,ge===j){if(C.tag===7){l(z,C.sibling),X=s(C,D.props.children),X.return=z,z=X;break e}}else if(C.elementType===ge||typeof ge=="object"&&ge!==null&&ge.$$typeof===ue&&Fl(ge)===C.type){l(z,C.sibling),X=s(C,D.props),ka(X,D),X.return=z,z=X;break e}l(z,C);break}else t(z,C);C=C.sibling}D.type===j?(X=Yl(D.props.children,z.mode,X,D.key),X.return=z,z=X):(X=Nr(D.type,D.key,D.props,null,z.mode,X),ka(X,D),X.return=z,z=X)}return b(z);case w:e:{for(ge=D.key;C!==null;){if(C.key===ge)if(C.tag===4&&C.stateNode.containerInfo===D.containerInfo&&C.stateNode.implementation===D.implementation){l(z,C.sibling),X=s(C,D.children||[]),X.return=z,z=X;break e}else{l(z,C);break}else t(z,C);C=C.sibling}X=Ss(D,z.mode,X),X.return=z,z=X}return b(z);case ue:return D=Fl(D),Ie(z,C,D,X)}if(I(D))return fe(z,C,D,X);if(W(D)){if(ge=W(D),typeof ge!="function")throw Error(u(150));return D=ge.call(D),Se(z,C,D,X)}if(typeof D.then=="function")return Ie(z,C,Ur(D),X);if(D.$$typeof===Y)return Ie(z,C,Or(z,D),X);Hr(z,D)}return typeof D=="string"&&D!==""||typeof D=="number"||typeof D=="bigint"?(D=""+D,C!==null&&C.tag===6?(l(z,C.sibling),X=s(C,D),X.return=z,z=X):(l(z,C),X=vs(D,z.mode,X),X.return=z,z=X),b(z)):l(z,C)}return function(z,C,D,X){try{_a=0;var ge=Ie(z,C,D,X);return Oi=null,ge}catch(me){if(me===Di||me===Lr)throw me;var qe=nn(29,me,null,z.mode);return qe.lanes=X,qe.return=z,qe}finally{}}}var Jl=md(!0),pd=md(!1),gl=!1;function Ds(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Os(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function yl(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function xl(e,t,l){var a=e.updateQueue;if(a===null)return null;if(a=a.shared,(Ye&2)!==0){var s=a.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),a.pending=t,t=zr(e),Pf(e,null,l),t}return Cr(e,a,t,l),zr(e)}function Aa(e,t,l){if(t=t.updateQueue,t!==null&&(t=t.shared,(l&4194048)!==0)){var a=t.lanes;a&=e.pendingLanes,l|=a,t.lanes=l,mi(e,l)}}function Rs(e,t){var l=e.updateQueue,a=e.alternate;if(a!==null&&(a=a.updateQueue,l===a)){var s=null,d=null;if(l=l.firstBaseUpdate,l!==null){do{var b={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};d===null?s=d=b:d=d.next=b,l=l.next}while(l!==null);d===null?s=d=t:d=d.next=t}else s=d=t;l={baseState:a.baseState,firstBaseUpdate:s,lastBaseUpdate:d,shared:a.shared,callbacks:a.callbacks},e.updateQueue=l;return}e=l.lastBaseUpdate,e===null?l.firstBaseUpdate=t:e.next=t,l.lastBaseUpdate=t}var Ls=!1;function wa(){if(Ls){var e=Mi;if(e!==null)throw e}}function Ea(e,t,l,a){Ls=!1;var s=e.updateQueue;gl=!1;var d=s.firstBaseUpdate,b=s.lastBaseUpdate,_=s.shared.pending;if(_!==null){s.shared.pending=null;var E=_,O=E.next;E.next=null,b===null?d=O:b.next=O,b=E;var V=e.alternate;V!==null&&(V=V.updateQueue,_=V.lastBaseUpdate,_!==b&&(_===null?V.firstBaseUpdate=O:_.next=O,V.lastBaseUpdate=E))}if(d!==null){var Z=s.baseState;b=0,V=O=E=null,_=d;do{var L=_.lane&-536870913,H=L!==_.lane;if(H?(Re&L)===L:(a&L)===L){L!==0&&L===Ni&&(Ls=!0),V!==null&&(V=V.next={lane:0,tag:_.tag,payload:_.payload,callback:null,next:null});e:{var fe=e,Se=_;L=t;var Ie=l;switch(Se.tag){case 1:if(fe=Se.payload,typeof fe=="function"){Z=fe.call(Ie,Z,L);break e}Z=fe;break e;case 3:fe.flags=fe.flags&-65537|128;case 0:if(fe=Se.payload,L=typeof fe=="function"?fe.call(Ie,Z,L):fe,L==null)break e;Z=x({},Z,L);break e;case 2:gl=!0}}L=_.callback,L!==null&&(e.flags|=64,H&&(e.flags|=8192),H=s.callbacks,H===null?s.callbacks=[L]:H.push(L))}else H={lane:L,tag:_.tag,payload:_.payload,callback:_.callback,next:null},V===null?(O=V=H,E=Z):V=V.next=H,b|=L;if(_=_.next,_===null){if(_=s.shared.pending,_===null)break;H=_,_=H.next,H.next=null,s.lastBaseUpdate=H,s.shared.pending=null}}while(!0);V===null&&(E=Z),s.baseState=E,s.firstBaseUpdate=O,s.lastBaseUpdate=V,d===null&&(s.shared.lanes=0),kl|=b,e.lanes=b,e.memoizedState=Z}}function gd(e,t){if(typeof e!="function")throw Error(u(191,e));e.call(t)}function yd(e,t){var l=e.callbacks;if(l!==null)for(e.callbacks=null,e=0;ed?d:8;var b=M.T,_={};M.T=_,to(e,!1,t,l);try{var E=s(),O=M.S;if(O!==null&&O(_,E),E!==null&&typeof E=="object"&&typeof E.then=="function"){var V=T1(E,a);Ca(e,t,V,sn(e))}else Ca(e,t,a,sn(e))}catch(Z){Ca(e,t,{then:function(){},status:"rejected",reason:Z},sn())}finally{J.p=d,b!==null&&_.types!==null&&(b.types=_.types),M.T=b}}function O1(){}function Ws(e,t,l,a){if(e.tag!==5)throw Error(u(476));var s=Jd(e).queue;Kd(e,s,t,P,l===null?O1:function(){return $d(e),l(a)})}function Jd(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:P,baseState:P,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:In,lastRenderedState:P},next:null};var l={};return t.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:In,lastRenderedState:l},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function $d(e){var t=Jd(e);t.next===null&&(t=e.alternate.memoizedState),Ca(e,t.next.queue,{},sn())}function eo(){return Ct(Za)}function Id(){return mt().memoizedState}function Pd(){return mt().memoizedState}function R1(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var l=sn();e=yl(l);var a=xl(t,e,l);a!==null&&($t(a,t,l),Aa(a,t,l)),t={cache:Cs()},e.payload=t;return}t=t.return}}function L1(e,t,l){var a=sn();l={lane:a,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Jr(e)?eh(t,l):(l=xs(e,t,l,a),l!==null&&($t(l,e,a),th(l,t,a)))}function Wd(e,t,l){var a=sn();Ca(e,t,l,a)}function Ca(e,t,l,a){var s={lane:a,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Jr(e))eh(t,s);else{var d=e.alternate;if(e.lanes===0&&(d===null||d.lanes===0)&&(d=t.lastRenderedReducer,d!==null))try{var b=t.lastRenderedState,_=d(b,l);if(s.hasEagerState=!0,s.eagerState=_,tn(_,b))return Cr(e,t,s,0),We===null&&Tr(),!1}catch{}finally{}if(l=xs(e,t,s,a),l!==null)return $t(l,e,a),th(l,t,a),!0}return!1}function to(e,t,l,a){if(a={lane:2,revertLane:Oo(),gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},Jr(e)){if(t)throw Error(u(479))}else t=xs(e,l,a,2),t!==null&&$t(t,e,2)}function Jr(e){var t=e.alternate;return e===Te||t!==null&&t===Te}function eh(e,t){Li=Yr=!0;var l=e.pending;l===null?t.next=t:(t.next=l.next,l.next=t),e.pending=t}function th(e,t,l){if((l&4194048)!==0){var a=t.lanes;a&=e.pendingLanes,l|=a,t.lanes=l,mi(e,l)}}var za={readContext:Ct,use:Xr,useCallback:ct,useContext:ct,useEffect:ct,useImperativeHandle:ct,useLayoutEffect:ct,useInsertionEffect:ct,useMemo:ct,useReducer:ct,useRef:ct,useState:ct,useDebugValue:ct,useDeferredValue:ct,useTransition:ct,useSyncExternalStore:ct,useId:ct,useHostTransitionStatus:ct,useFormState:ct,useActionState:ct,useOptimistic:ct,useMemoCache:ct,useCacheRefresh:ct};za.useEffectEvent=ct;var nh={readContext:Ct,use:Xr,useCallback:function(e,t){return qt().memoizedState=[e,t===void 0?null:t],e},useContext:Ct,useEffect:Hd,useImperativeHandle:function(e,t,l){l=l!=null?l.concat([e]):null,Fr(4194308,4,Vd.bind(null,t,e),l)},useLayoutEffect:function(e,t){return Fr(4194308,4,e,t)},useInsertionEffect:function(e,t){Fr(4,2,e,t)},useMemo:function(e,t){var l=qt();t=t===void 0?null:t;var a=e();if($l){Ot(!0);try{e()}finally{Ot(!1)}}return l.memoizedState=[a,t],a},useReducer:function(e,t,l){var a=qt();if(l!==void 0){var s=l(t);if($l){Ot(!0);try{l(t)}finally{Ot(!1)}}}else s=t;return a.memoizedState=a.baseState=s,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:s},a.queue=e,e=e.dispatch=L1.bind(null,Te,e),[a.memoizedState,e]},useRef:function(e){var t=qt();return e={current:e},t.memoizedState=e},useState:function(e){e=Ks(e);var t=e.queue,l=Wd.bind(null,Te,t);return t.dispatch=l,[e.memoizedState,l]},useDebugValue:Is,useDeferredValue:function(e,t){var l=qt();return Ps(l,e,t)},useTransition:function(){var e=Ks(!1);return e=Kd.bind(null,Te,e.queue,!0,!1),qt().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,l){var a=Te,s=qt();if(Be){if(l===void 0)throw Error(u(407));l=l()}else{if(l=t(),We===null)throw Error(u(349));(Re&127)!==0||kd(a,t,l)}s.memoizedState=l;var d={value:l,getSnapshot:t};return s.queue=d,Hd(wd.bind(null,a,d,e),[e]),a.flags|=2048,Ui(9,{destroy:void 0},Ad.bind(null,a,d,l,t),null),l},useId:function(){var e=qt(),t=We.identifierPrefix;if(Be){var l=On,a=Dn;l=(a&~(1<<32-Qe(a)-1)).toString(32)+l,t="_"+t+"R_"+l,l=Vr++,0<\/script>",d=d.removeChild(d.firstChild);break;case"select":d=typeof a.is=="string"?b.createElement("select",{is:a.is}):b.createElement("select"),a.multiple?d.multiple=!0:a.size&&(d.size=a.size);break;default:d=typeof a.is=="string"?b.createElement(s,{is:a.is}):b.createElement(s)}}d[_t]=t,d[jt]=a;e:for(b=t.child;b!==null;){if(b.tag===5||b.tag===6)d.appendChild(b.stateNode);else if(b.tag!==4&&b.tag!==27&&b.child!==null){b.child.return=b,b=b.child;continue}if(b===t)break e;for(;b.sibling===null;){if(b.return===null||b.return===t)break e;b=b.return}b.sibling.return=b.return,b=b.sibling}t.stateNode=d;e:switch(Nt(d,s,a),s){case"button":case"input":case"select":case"textarea":a=!!a.autoFocus;break e;case"img":a=!0;break e;default:a=!1}a&&Wn(t)}}return it(t),go(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,l),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==a&&Wn(t);else{if(typeof a!="string"&&t.stateNode===null)throw Error(u(166));if(e=he.current,Ci(t)){if(e=t.stateNode,l=t.memoizedProps,a=null,s=Tt,s!==null)switch(s.tag){case 27:case 5:a=s.memoizedProps}e[_t]=t,e=!!(e.nodeValue===l||a!==null&&a.suppressHydrationWarning===!0||Sm(e.nodeValue,l)),e||ml(t,!0)}else e=pu(e).createTextNode(a),e[_t]=t,t.stateNode=e}return it(t),null;case 31:if(l=t.memoizedState,e===null||e.memoizedState!==null){if(a=Ci(t),l!==null){if(e===null){if(!a)throw Error(u(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(u(557));e[_t]=t}else Vl(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;it(t),e=!1}else l=ws(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=l),e=!0;if(!e)return t.flags&256?(an(t),t):(an(t),null);if((t.flags&128)!==0)throw Error(u(558))}return it(t),null;case 13:if(a=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(s=Ci(t),a!==null&&a.dehydrated!==null){if(e===null){if(!s)throw Error(u(318));if(s=t.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(u(317));s[_t]=t}else Vl(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;it(t),s=!1}else s=ws(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),s=!0;if(!s)return t.flags&256?(an(t),t):(an(t),null)}return an(t),(t.flags&128)!==0?(t.lanes=l,t):(l=a!==null,e=e!==null&&e.memoizedState!==null,l&&(a=t.child,s=null,a.alternate!==null&&a.alternate.memoizedState!==null&&a.alternate.memoizedState.cachePool!==null&&(s=a.alternate.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==s&&(a.flags|=2048)),l!==e&&l&&(t.child.flags|=8192),eu(t,t.updateQueue),it(t),null);case 4:return Ue(),e===null&&Uo(t.stateNode.containerInfo),it(t),null;case 10:return Jn(t.type),it(t),null;case 19:if(G(ht),a=t.memoizedState,a===null)return it(t),null;if(s=(t.flags&128)!==0,d=a.rendering,d===null)if(s)Ma(a,!1);else{if(ft!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(d=Gr(e),d!==null){for(t.flags|=128,Ma(a,!1),e=d.updateQueue,t.updateQueue=e,eu(t,e),t.subtreeFlags=0,e=l,l=t.child;l!==null;)Wf(l,e),l=l.sibling;return k(ht,ht.current&1|2),Be&&Fn(t,a.treeForkCount),t.child}e=e.sibling}a.tail!==null&&ut()>au&&(t.flags|=128,s=!0,Ma(a,!1),t.lanes=4194304)}else{if(!s)if(e=Gr(d),e!==null){if(t.flags|=128,s=!0,e=e.updateQueue,t.updateQueue=e,eu(t,e),Ma(a,!0),a.tail===null&&a.tailMode==="hidden"&&!d.alternate&&!Be)return it(t),null}else 2*ut()-a.renderingStartTime>au&&l!==536870912&&(t.flags|=128,s=!0,Ma(a,!1),t.lanes=4194304);a.isBackwards?(d.sibling=t.child,t.child=d):(e=a.last,e!==null?e.sibling=d:t.child=d,a.last=d)}return a.tail!==null?(e=a.tail,a.rendering=e,a.tail=e.sibling,a.renderingStartTime=ut(),e.sibling=null,l=ht.current,k(ht,s?l&1|2:l&1),Be&&Fn(t,a.treeForkCount),e):(it(t),null);case 22:case 23:return an(t),Us(),a=t.memoizedState!==null,e!==null?e.memoizedState!==null!==a&&(t.flags|=8192):a&&(t.flags|=8192),a?(l&536870912)!==0&&(t.flags&128)===0&&(it(t),t.subtreeFlags&6&&(t.flags|=8192)):it(t),l=t.updateQueue,l!==null&&eu(t,l.retryQueue),l=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(l=e.memoizedState.cachePool.pool),a=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(a=t.memoizedState.cachePool.pool),a!==l&&(t.flags|=2048),e!==null&&G(Zl),null;case 24:return l=null,e!==null&&(l=e.memoizedState.cache),t.memoizedState.cache!==l&&(t.flags|=2048),Jn(gt),it(t),null;case 25:return null;case 30:return null}throw Error(u(156,t.tag))}function G1(e,t){switch(ks(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Jn(gt),Ue(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return nt(t),null;case 31:if(t.memoizedState!==null){if(an(t),t.alternate===null)throw Error(u(340));Vl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(an(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(u(340));Vl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return G(ht),null;case 4:return Ue(),null;case 10:return Jn(t.type),null;case 22:case 23:return an(t),Us(),e!==null&&G(Zl),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Jn(gt),null;case 25:return null;default:return null}}function Eh(e,t){switch(ks(t),t.tag){case 3:Jn(gt),Ue();break;case 26:case 27:case 5:nt(t);break;case 4:Ue();break;case 31:t.memoizedState!==null&&an(t);break;case 13:an(t);break;case 19:G(ht);break;case 10:Jn(t.type);break;case 22:case 23:an(t),Us(),e!==null&&G(Zl);break;case 24:Jn(gt)}}function Da(e,t){try{var l=t.updateQueue,a=l!==null?l.lastEffect:null;if(a!==null){var s=a.next;l=s;do{if((l.tag&e)===e){a=void 0;var d=l.create,b=l.inst;a=d(),b.destroy=a}l=l.next}while(l!==s)}}catch(_){Fe(t,t.return,_)}}function Sl(e,t,l){try{var a=t.updateQueue,s=a!==null?a.lastEffect:null;if(s!==null){var d=s.next;a=d;do{if((a.tag&e)===e){var b=a.inst,_=b.destroy;if(_!==void 0){b.destroy=void 0,s=t;var E=l,O=_;try{O()}catch(V){Fe(s,E,V)}}}a=a.next}while(a!==d)}}catch(V){Fe(t,t.return,V)}}function jh(e){var t=e.updateQueue;if(t!==null){var l=e.stateNode;try{yd(t,l)}catch(a){Fe(e,e.return,a)}}}function Th(e,t,l){l.props=Il(e.type,e.memoizedProps),l.state=e.memoizedState;try{l.componentWillUnmount()}catch(a){Fe(e,t,a)}}function Oa(e,t){try{var l=e.ref;if(l!==null){switch(e.tag){case 26:case 27:case 5:var a=e.stateNode;break;case 30:a=e.stateNode;break;default:a=e.stateNode}typeof l=="function"?e.refCleanup=l(a):l.current=a}}catch(s){Fe(e,t,s)}}function Rn(e,t){var l=e.ref,a=e.refCleanup;if(l!==null)if(typeof a=="function")try{a()}catch(s){Fe(e,t,s)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(s){Fe(e,t,s)}else l.current=null}function Ch(e){var t=e.type,l=e.memoizedProps,a=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":l.autoFocus&&a.focus();break e;case"img":l.src?a.src=l.src:l.srcSet&&(a.srcset=l.srcSet)}}catch(s){Fe(e,e.return,s)}}function yo(e,t,l){try{var a=e.stateNode;ox(a,e.type,l,t),a[jt]=t}catch(s){Fe(e,e.return,s)}}function zh(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Tl(e.type)||e.tag===4}function xo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||zh(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Tl(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function bo(e,t,l){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(e,t):(t=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,t.appendChild(e),l=l._reactRootContainer,l!=null||t.onclick!==null||(t.onclick=Qn));else if(a!==4&&(a===27&&Tl(e.type)&&(l=e.stateNode,t=null),e=e.child,e!==null))for(bo(e,t,l),e=e.sibling;e!==null;)bo(e,t,l),e=e.sibling}function tu(e,t,l){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?l.insertBefore(e,t):l.appendChild(e);else if(a!==4&&(a===27&&Tl(e.type)&&(l=e.stateNode),e=e.child,e!==null))for(tu(e,t,l),e=e.sibling;e!==null;)tu(e,t,l),e=e.sibling}function Nh(e){var t=e.stateNode,l=e.memoizedProps;try{for(var a=e.type,s=t.attributes;s.length;)t.removeAttributeNode(s[0]);Nt(t,a,l),t[_t]=e,t[jt]=l}catch(d){Fe(e,e.return,d)}}var el=!1,bt=!1,vo=!1,Mh=typeof WeakSet=="function"?WeakSet:Set,Et=null;function Y1(e,t){if(e=e.containerInfo,Go=_u,e=Qf(e),ds(e)){if("selectionStart"in e)var l={start:e.selectionStart,end:e.selectionEnd};else e:{l=(l=e.ownerDocument)&&l.defaultView||window;var a=l.getSelection&&l.getSelection();if(a&&a.rangeCount!==0){l=a.anchorNode;var s=a.anchorOffset,d=a.focusNode;a=a.focusOffset;try{l.nodeType,d.nodeType}catch{l=null;break e}var b=0,_=-1,E=-1,O=0,V=0,Z=e,L=null;t:for(;;){for(var H;Z!==l||s!==0&&Z.nodeType!==3||(_=b+s),Z!==d||a!==0&&Z.nodeType!==3||(E=b+a),Z.nodeType===3&&(b+=Z.nodeValue.length),(H=Z.firstChild)!==null;)L=Z,Z=H;for(;;){if(Z===e)break t;if(L===l&&++O===s&&(_=b),L===d&&++V===a&&(E=b),(H=Z.nextSibling)!==null)break;Z=L,L=Z.parentNode}Z=H}l=_===-1||E===-1?null:{start:_,end:E}}else l=null}l=l||{start:0,end:0}}else l=null;for(Yo={focusedElem:e,selectionRange:l},_u=!1,Et=t;Et!==null;)if(t=Et,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Et=e;else for(;Et!==null;){switch(t=Et,d=t.alternate,e=t.flags,t.tag){case 0:if((e&4)!==0&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(l=0;l title"))),Nt(d,a,l),d[_t]=e,Ke(d),a=d;break e;case"link":var b=Um("link","href",s).get(a+(l.href||""));if(b){for(var _=0;_Ie&&(b=Ie,Ie=Se,Se=b);var z=Yf(_,Se),C=Yf(_,Ie);if(z&&C&&(H.rangeCount!==1||H.anchorNode!==z.node||H.anchorOffset!==z.offset||H.focusNode!==C.node||H.focusOffset!==C.offset)){var D=Z.createRange();D.setStart(z.node,z.offset),H.removeAllRanges(),Se>Ie?(H.addRange(D),H.extend(C.node,C.offset)):(D.setEnd(C.node,C.offset),H.addRange(D))}}}}for(Z=[],H=_;H=H.parentNode;)H.nodeType===1&&Z.push({element:H,left:H.scrollLeft,top:H.scrollTop});for(typeof _.focus=="function"&&_.focus(),_=0;_l?32:l,M.T=null,l=jo,jo=null;var d=wl,b=al;if(kt=0,Vi=wl=null,al=0,(Ye&6)!==0)throw Error(u(331));var _=Ye;if(Ye|=4,Vh(d.current),qh(d,d.current,b,l),Ye=_,qa(0,!1),ot&&typeof ot.onPostCommitFiberRoot=="function")try{ot.onPostCommitFiberRoot(wt,d)}catch{}return!0}finally{J.p=s,M.T=a,um(e,t)}}function om(e,t,l){t=pn(l,t),t=ao(e.stateNode,t,2),e=xl(e,t,2),e!==null&&(Gn(e,2),Ln(e))}function Fe(e,t,l){if(e.tag===3)om(e,e,l);else for(;t!==null;){if(t.tag===3){om(t,e,l);break}else if(t.tag===1){var a=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof a.componentDidCatch=="function"&&(Al===null||!Al.has(a))){e=pn(l,e),l=ch(2),a=xl(t,l,2),a!==null&&(fh(l,a,t,e),Gn(a,2),Ln(a));break}}t=t.return}}function No(e,t,l){var a=e.pingCache;if(a===null){a=e.pingCache=new X1;var s=new Set;a.set(t,s)}else s=a.get(t),s===void 0&&(s=new Set,a.set(t,s));s.has(l)||(ko=!0,s.add(l),e=$1.bind(null,e,t,l),t.then(e,e))}function $1(e,t,l){var a=e.pingCache;a!==null&&a.delete(t),e.pingedLanes|=e.suspendedLanes&l,e.warmLanes&=~l,We===e&&(Re&l)===l&&(ft===4||ft===3&&(Re&62914560)===Re&&300>ut()-iu?(Ye&2)===0&&Qi(e,0):Ao|=l,Yi===Re&&(Yi=0)),Ln(e)}function cm(e,t){t===0&&(t=aa()),e=Gl(e,t),e!==null&&(Gn(e,t),Ln(e))}function I1(e){var t=e.memoizedState,l=0;t!==null&&(l=t.retryLane),cm(e,l)}function P1(e,t){var l=0;switch(e.tag){case 31:case 13:var a=e.stateNode,s=e.memoizedState;s!==null&&(l=s.retryLane);break;case 19:a=e.stateNode;break;case 22:a=e.stateNode._retryCache;break;default:throw Error(u(314))}a!==null&&a.delete(t),cm(e,l)}function W1(e,t){return Yt(e,t)}var fu=null,Zi=null,Mo=!1,du=!1,Do=!1,jl=0;function Ln(e){e!==Zi&&e.next===null&&(Zi===null?fu=Zi=e:Zi=Zi.next=e),du=!0,Mo||(Mo=!0,tx())}function qa(e,t){if(!Do&&du){Do=!0;do for(var l=!1,a=fu;a!==null;){if(e!==0){var s=a.pendingLanes;if(s===0)var d=0;else{var b=a.suspendedLanes,_=a.pingedLanes;d=(1<<31-Qe(42|e)+1)-1,d&=s&~(b&~_),d=d&201326741?d&201326741|1:d?d|2:0}d!==0&&(l=!0,mm(a,d))}else d=Re,d=hi(a,a===We?d:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),(d&3)===0||cl(a,d)||(l=!0,mm(a,d));a=a.next}while(l);Do=!1}}function ex(){fm()}function fm(){du=Mo=!1;var e=0;jl!==0&&fx()&&(e=jl);for(var t=ut(),l=null,a=fu;a!==null;){var s=a.next,d=dm(a,t);d===0?(a.next=null,l===null?fu=s:l.next=s,s===null&&(Zi=l)):(l=a,(e!==0||(d&3)!==0)&&(du=!0)),a=s}kt!==0&&kt!==5||qa(e),jl!==0&&(jl=0)}function dm(e,t){for(var l=e.suspendedLanes,a=e.pingedLanes,s=e.expirationTimes,d=e.pendingLanes&-62914561;0_)break;var V=E.transferSize,Z=E.initiatorType;V&&_m(Z)&&(E=E.responseEnd,b+=V*(E<_?1:(_-O)/(E-O)))}if(--a,t+=8*(d+b)/(s.duration/1e3),e++,10"u"?null:document;function Om(e,t,l){var a=Fi;if(a&&typeof t=="string"&&t){var s=hn(t);s='link[rel="'+e+'"][href="'+s+'"]',typeof l=="string"&&(s+='[crossorigin="'+l+'"]'),Dm.has(s)||(Dm.add(s),e={rel:e,crossOrigin:l,href:t},a.querySelector(s)===null&&(t=a.createElement("link"),Nt(t,"link",e),Ke(t),a.head.appendChild(t)))}}function vx(e){rl.D(e),Om("dns-prefetch",e,null)}function Sx(e,t){rl.C(e,t),Om("preconnect",e,t)}function _x(e,t,l){rl.L(e,t,l);var a=Fi;if(a&&e&&t){var s='link[rel="preload"][as="'+hn(t)+'"]';t==="image"&&l&&l.imageSrcSet?(s+='[imagesrcset="'+hn(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(s+='[imagesizes="'+hn(l.imageSizes)+'"]')):s+='[href="'+hn(e)+'"]';var d=s;switch(t){case"style":d=Ki(e);break;case"script":d=Ji(e)}Sn.has(d)||(e=x({rel:"preload",href:t==="image"&&l&&l.imageSrcSet?void 0:e,as:t},l),Sn.set(d,e),a.querySelector(s)!==null||t==="style"&&a.querySelector(Qa(d))||t==="script"&&a.querySelector(Xa(d))||(t=a.createElement("link"),Nt(t,"link",e),Ke(t),a.head.appendChild(t)))}}function kx(e,t){rl.m(e,t);var l=Fi;if(l&&e){var a=t&&typeof t.as=="string"?t.as:"script",s='link[rel="modulepreload"][as="'+hn(a)+'"][href="'+hn(e)+'"]',d=s;switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":d=Ji(e)}if(!Sn.has(d)&&(e=x({rel:"modulepreload",href:e},t),Sn.set(d,e),l.querySelector(s)===null)){switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(Xa(d)))return}a=l.createElement("link"),Nt(a,"link",e),Ke(a),l.head.appendChild(a)}}}function Ax(e,t,l){rl.S(e,t,l);var a=Fi;if(a&&e){var s=pt(a).hoistableStyles,d=Ki(e);t=t||"default";var b=s.get(d);if(!b){var _={loading:0,preload:null};if(b=a.querySelector(Qa(d)))_.loading=5;else{e=x({rel:"stylesheet",href:e,"data-precedence":t},l),(l=Sn.get(d))&&Jo(e,l);var E=b=a.createElement("link");Ke(E),Nt(E,"link",e),E._p=new Promise(function(O,V){E.onload=O,E.onerror=V}),E.addEventListener("load",function(){_.loading|=1}),E.addEventListener("error",function(){_.loading|=2}),_.loading|=4,yu(b,t,a)}b={type:"stylesheet",instance:b,count:1,state:_},s.set(d,b)}}}function wx(e,t){rl.X(e,t);var l=Fi;if(l&&e){var a=pt(l).hoistableScripts,s=Ji(e),d=a.get(s);d||(d=l.querySelector(Xa(s)),d||(e=x({src:e,async:!0},t),(t=Sn.get(s))&&$o(e,t),d=l.createElement("script"),Ke(d),Nt(d,"link",e),l.head.appendChild(d)),d={type:"script",instance:d,count:1,state:null},a.set(s,d))}}function Ex(e,t){rl.M(e,t);var l=Fi;if(l&&e){var a=pt(l).hoistableScripts,s=Ji(e),d=a.get(s);d||(d=l.querySelector(Xa(s)),d||(e=x({src:e,async:!0,type:"module"},t),(t=Sn.get(s))&&$o(e,t),d=l.createElement("script"),Ke(d),Nt(d,"link",e),l.head.appendChild(d)),d={type:"script",instance:d,count:1,state:null},a.set(s,d))}}function Rm(e,t,l,a){var s=(s=he.current)?gu(s):null;if(!s)throw Error(u(446));switch(e){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(t=Ki(l.href),l=pt(s).hoistableStyles,a=l.get(t),a||(a={type:"style",instance:null,count:0,state:null},l.set(t,a)),a):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){e=Ki(l.href);var d=pt(s).hoistableStyles,b=d.get(e);if(b||(s=s.ownerDocument||s,b={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},d.set(e,b),(d=s.querySelector(Qa(e)))&&!d._p&&(b.instance=d,b.state.loading=5),Sn.has(e)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},Sn.set(e,l),d||jx(s,e,l,b.state))),t&&a===null)throw Error(u(528,""));return b}if(t&&a!==null)throw Error(u(529,""));return null;case"script":return t=l.async,l=l.src,typeof l=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=Ji(l),l=pt(s).hoistableScripts,a=l.get(t),a||(a={type:"script",instance:null,count:0,state:null},l.set(t,a)),a):{type:"void",instance:null,count:0,state:null};default:throw Error(u(444,e))}}function Ki(e){return'href="'+hn(e)+'"'}function Qa(e){return'link[rel="stylesheet"]['+e+"]"}function Lm(e){return x({},e,{"data-precedence":e.precedence,precedence:null})}function jx(e,t,l,a){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?a.loading=1:(t=e.createElement("link"),a.preload=t,t.addEventListener("load",function(){return a.loading|=1}),t.addEventListener("error",function(){return a.loading|=2}),Nt(t,"link",l),Ke(t),e.head.appendChild(t))}function Ji(e){return'[src="'+hn(e)+'"]'}function Xa(e){return"script[async]"+e}function Bm(e,t,l){if(t.count++,t.instance===null)switch(t.type){case"style":var a=e.querySelector('style[data-href~="'+hn(l.href)+'"]');if(a)return t.instance=a,Ke(a),a;var s=x({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return a=(e.ownerDocument||e).createElement("style"),Ke(a),Nt(a,"style",s),yu(a,l.precedence,e),t.instance=a;case"stylesheet":s=Ki(l.href);var d=e.querySelector(Qa(s));if(d)return t.state.loading|=4,t.instance=d,Ke(d),d;a=Lm(l),(s=Sn.get(s))&&Jo(a,s),d=(e.ownerDocument||e).createElement("link"),Ke(d);var b=d;return b._p=new Promise(function(_,E){b.onload=_,b.onerror=E}),Nt(d,"link",a),t.state.loading|=4,yu(d,l.precedence,e),t.instance=d;case"script":return d=Ji(l.src),(s=e.querySelector(Xa(d)))?(t.instance=s,Ke(s),s):(a=l,(s=Sn.get(d))&&(a=x({},l),$o(a,s)),e=e.ownerDocument||e,s=e.createElement("script"),Ke(s),Nt(s,"link",a),e.head.appendChild(s),t.instance=s);case"void":return null;default:throw Error(u(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(a=t.instance,t.state.loading|=4,yu(a,l.precedence,e));return t.instance}function yu(e,t,l){for(var a=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),s=a.length?a[a.length-1]:null,d=s,b=0;b title"):null)}function Tx(e,t,l){if(l===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;switch(t.rel){case"stylesheet":return e=t.disabled,typeof t.precedence=="string"&&e==null;default:return!0}case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function qm(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function Cx(e,t,l,a){if(l.type==="stylesheet"&&(typeof a.media!="string"||matchMedia(a.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var s=Ki(a.href),d=t.querySelector(Qa(s));if(d){t=d._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=bu.bind(e),t.then(e,e)),l.state.loading|=4,l.instance=d,Ke(d);return}d=t.ownerDocument||t,a=Lm(a),(s=Sn.get(s))&&Jo(a,s),d=d.createElement("link"),Ke(d);var b=d;b._p=new Promise(function(_,E){b.onload=_,b.onerror=E}),Nt(d,"link",a),l.instance=d}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(l,t),(t=l.state.preload)&&(l.state.loading&3)===0&&(e.count++,l=bu.bind(e),t.addEventListener("load",l),t.addEventListener("error",l))}}var Io=0;function zx(e,t){return e.stylesheets&&e.count===0&&Su(e,e.stylesheets),0Io?50:800)+t);return e.unsuspend=l,function(){e.unsuspend=null,clearTimeout(a),clearTimeout(s)}}:null}function bu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Su(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var vu=null;function Su(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,vu=new Map,t.forEach(Nx,e),vu=null,bu.call(e))}function Nx(e,t){if(!(t.state.loading&4)){var l=vu.get(e);if(l)var a=l.get(null);else{l=new Map,vu.set(e,l);for(var s=e.querySelectorAll("link[data-precedence],style[data-precedence]"),d=0;d"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(i){console.error(i)}}return n(),rc.exports=Fx(),rc.exports}var Jx=Kx();function $x(n,i){const r={};return(n[n.length-1]===""?[...n,""]:n).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const Ix=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Px=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Wx={};function cp(n,i){return(Wx.jsx?Px:Ix).test(n)}const e0=/[ \t\n\f\r]/g;function t0(n){return typeof n=="object"?n.type==="text"?fp(n.value):!1:fp(n)}function fp(n){return n.replace(e0,"")===""}class sr{constructor(i,r,u){this.normal=r,this.property=i,u&&(this.space=u)}}sr.prototype.normal={};sr.prototype.property={};sr.prototype.space=void 0;function og(n,i){const r={},u={};for(const o of n)Object.assign(r,o.property),Object.assign(u,o.normal);return new sr(r,u,i)}function Cc(n){return n.toLowerCase()}class Pt{constructor(i,r){this.attribute=r,this.property=i}}Pt.prototype.attribute="";Pt.prototype.booleanish=!1;Pt.prototype.boolean=!1;Pt.prototype.commaOrSpaceSeparated=!1;Pt.prototype.commaSeparated=!1;Pt.prototype.defined=!1;Pt.prototype.mustUseProperty=!1;Pt.prototype.number=!1;Pt.prototype.overloadedBoolean=!1;Pt.prototype.property="";Pt.prototype.spaceSeparated=!1;Pt.prototype.space=void 0;let n0=0;const _e=ui(),vt=ui(),zc=ui(),ee=ui(),et=ui(),ii=ui(),on=ui();function ui(){return 2**++n0}const Nc=Object.freeze(Object.defineProperty({__proto__:null,boolean:_e,booleanish:vt,commaOrSpaceSeparated:on,commaSeparated:ii,number:ee,overloadedBoolean:zc,spaceSeparated:et},Symbol.toStringTag,{value:"Module"})),cc=Object.keys(Nc);class Vc extends Pt{constructor(i,r,u,o){let c=-1;if(super(i,r),dp(this,"space",o),typeof u=="number")for(;++c4&&r.slice(0,4)==="data"&&u0.test(i)){if(i.charAt(4)==="-"){const c=i.slice(5).replace(hp,c0);u="data"+c.charAt(0).toUpperCase()+c.slice(1)}else{const c=i.slice(4);if(!hp.test(c)){let f=c.replace(r0,o0);f.charAt(0)!=="-"&&(f="-"+f),i="data"+f}}o=Vc}return new o(u,i)}function o0(n){return"-"+n.toLowerCase()}function c0(n){return n.charAt(1).toUpperCase()}const f0=og([cg,l0,hg,mg,pg],"html"),Qc=og([cg,i0,hg,mg,pg],"svg");function d0(n){return n.join(" ").trim()}var Ii={},fc,mp;function h0(){if(mp)return fc;mp=1;var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,i=/\n/g,r=/^\s*/,u=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,c=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,f=/^[;\s]*/,h=/^\s+|\s+$/g,g=` -`,p="/",y="*",x="",v="comment",S="declaration";function w(q,N){if(typeof q!="string")throw new TypeError("First argument must be a string");if(!q)return[];N=N||{};var K=1,Y=1;function se(re){var I=re.match(i);I&&(K+=I.length);var M=re.lastIndexOf(g);Y=~M?re.length-M:Y+re.length}function ae(){var re={line:K,column:Y};return function(I){return I.position=new U(re),ye(),I}}function U(re){this.start=re,this.end={line:K,column:Y},this.source=N.source}U.prototype.content=q;function ne(re){var I=new Error(N.source+":"+K+":"+Y+": "+re);if(I.reason=re,I.filename=N.source,I.line=K,I.column=Y,I.source=q,!N.silent)throw I}function ue(re){var I=re.exec(q);if(I){var M=I[0];return se(M),q=q.slice(M.length),I}}function ye(){ue(r)}function R(re){var I;for(re=re||[];I=Q();)I!==!1&&re.push(I);return re}function Q(){var re=ae();if(!(p!=q.charAt(0)||y!=q.charAt(1))){for(var I=2;x!=q.charAt(I)&&(y!=q.charAt(I)||p!=q.charAt(I+1));)++I;if(I+=2,x===q.charAt(I-1))return ne("End of comment missing");var M=q.slice(2,I-2);return Y+=2,se(M),q=q.slice(I),Y+=2,re({type:v,comment:M})}}function W(){var re=ae(),I=ue(u);if(I){if(Q(),!ue(o))return ne("property missing ':'");var M=ue(c),J=re({type:S,property:j(I[0].replace(n,x)),value:M?j(M[0].replace(n,x)):x});return ue(f),J}}function de(){var re=[];R(re);for(var I;I=W();)I!==!1&&(re.push(I),R(re));return re}return ye(),de()}function j(q){return q?q.replace(h,x):x}return fc=w,fc}var pp;function m0(){if(pp)return Ii;pp=1;var n=Ii&&Ii.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.default=r;const i=n(h0());function r(u,o){let c=null;if(!u||typeof u!="string")return c;const f=(0,i.default)(u),h=typeof o=="function";return f.forEach(g=>{if(g.type!=="declaration")return;const{property:p,value:y}=g;h?o(p,y,g):y&&(c=c||{},c[p]=y)}),c}return Ii}var Pa={},gp;function p0(){if(gp)return Pa;gp=1,Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.camelCase=void 0;var n=/^--[a-zA-Z0-9_-]+$/,i=/-([a-z])/g,r=/^[^-]+$/,u=/^-(webkit|moz|ms|o|khtml)-/,o=/^-(ms)-/,c=function(p){return!p||r.test(p)||n.test(p)},f=function(p,y){return y.toUpperCase()},h=function(p,y){return"".concat(y,"-")},g=function(p,y){return y===void 0&&(y={}),c(p)?p:(p=p.toLowerCase(),y.reactCompat?p=p.replace(o,h):p=p.replace(u,h),p.replace(i,f))};return Pa.camelCase=g,Pa}var Wa,yp;function g0(){if(yp)return Wa;yp=1;var n=Wa&&Wa.__importDefault||function(o){return o&&o.__esModule?o:{default:o}},i=n(m0()),r=p0();function u(o,c){var f={};return!o||typeof o!="string"||(0,i.default)(o,function(h,g){h&&g&&(f[(0,r.camelCase)(h,c)]=g)}),f}return u.default=u,Wa=u,Wa}var y0=g0();const x0=sg(y0),gg=yg("end"),Xc=yg("start");function yg(n){return i;function i(r){const u=r&&r.position&&r.position[n]||{};if(typeof u.line=="number"&&u.line>0&&typeof u.column=="number"&&u.column>0)return{line:u.line,column:u.column,offset:typeof u.offset=="number"&&u.offset>-1?u.offset:void 0}}}function b0(n){const i=Xc(n),r=gg(n);if(i&&r)return{start:i,end:r}}function lr(n){return!n||typeof n!="object"?"":"position"in n||"type"in n?xp(n.position):"start"in n||"end"in n?xp(n):"line"in n||"column"in n?Mc(n):""}function Mc(n){return bp(n&&n.line)+":"+bp(n&&n.column)}function xp(n){return Mc(n&&n.start)+"-"+Mc(n&&n.end)}function bp(n){return n&&typeof n=="number"?n:1}class Bt extends Error{constructor(i,r,u){super(),typeof r=="string"&&(u=r,r=void 0);let o="",c={},f=!1;if(r&&("line"in r&&"column"in r?c={place:r}:"start"in r&&"end"in r?c={place:r}:"type"in r?c={ancestors:[r],place:r.position}:c={...r}),typeof i=="string"?o=i:!c.cause&&i&&(f=!0,o=i.message,c.cause=i),!c.ruleId&&!c.source&&typeof u=="string"){const g=u.indexOf(":");g===-1?c.ruleId=u:(c.source=u.slice(0,g),c.ruleId=u.slice(g+1))}if(!c.place&&c.ancestors&&c.ancestors){const g=c.ancestors[c.ancestors.length-1];g&&(c.place=g.position)}const h=c.place&&"start"in c.place?c.place.start:c.place;this.ancestors=c.ancestors||void 0,this.cause=c.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=o,this.line=h?h.line:void 0,this.name=lr(c.place)||"1:1",this.place=c.place||void 0,this.reason=this.message,this.ruleId=c.ruleId||void 0,this.source=c.source||void 0,this.stack=f&&c.cause&&typeof c.cause.stack=="string"?c.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Bt.prototype.file="";Bt.prototype.name="";Bt.prototype.reason="";Bt.prototype.message="";Bt.prototype.stack="";Bt.prototype.column=void 0;Bt.prototype.line=void 0;Bt.prototype.ancestors=void 0;Bt.prototype.cause=void 0;Bt.prototype.fatal=void 0;Bt.prototype.place=void 0;Bt.prototype.ruleId=void 0;Bt.prototype.source=void 0;const Zc={}.hasOwnProperty,v0=new Map,S0=/[A-Z]/g,_0=new Set(["table","tbody","thead","tfoot","tr"]),k0=new Set(["td","th"]),xg="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function A0(n,i){if(!i||i.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=i.filePath||void 0;let u;if(i.development){if(typeof i.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");u=M0(r,i.jsxDEV)}else{if(typeof i.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof i.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");u=N0(r,i.jsx,i.jsxs)}const o={Fragment:i.Fragment,ancestors:[],components:i.components||{},create:u,elementAttributeNameCase:i.elementAttributeNameCase||"react",evaluater:i.createEvaluater?i.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:i.ignoreInvalidStyle||!1,passKeys:i.passKeys!==!1,passNode:i.passNode||!1,schema:i.space==="svg"?Qc:f0,stylePropertyNameCase:i.stylePropertyNameCase||"dom",tableCellAlignToStyle:i.tableCellAlignToStyle!==!1},c=bg(o,n,void 0);return c&&typeof c!="string"?c:o.create(n,o.Fragment,{children:c||void 0},void 0)}function bg(n,i,r){if(i.type==="element")return w0(n,i,r);if(i.type==="mdxFlowExpression"||i.type==="mdxTextExpression")return E0(n,i);if(i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement")return T0(n,i,r);if(i.type==="mdxjsEsm")return j0(n,i);if(i.type==="root")return C0(n,i,r);if(i.type==="text")return z0(n,i)}function w0(n,i,r){const u=n.schema;let o=u;i.tagName.toLowerCase()==="svg"&&u.space==="html"&&(o=Qc,n.schema=o),n.ancestors.push(i);const c=Sg(n,i.tagName,!1),f=D0(n,i);let h=Kc(n,i);return _0.has(i.tagName)&&(h=h.filter(function(g){return typeof g=="string"?!t0(g):!0})),vg(n,f,c,i),Fc(f,h),n.ancestors.pop(),n.schema=u,n.create(i,c,f,r)}function E0(n,i){if(i.data&&i.data.estree&&n.evaluater){const u=i.data.estree.body[0];return u.type,n.evaluater.evaluateExpression(u.expression)}rr(n,i.position)}function j0(n,i){if(i.data&&i.data.estree&&n.evaluater)return n.evaluater.evaluateProgram(i.data.estree);rr(n,i.position)}function T0(n,i,r){const u=n.schema;let o=u;i.name==="svg"&&u.space==="html"&&(o=Qc,n.schema=o),n.ancestors.push(i);const c=i.name===null?n.Fragment:Sg(n,i.name,!0),f=O0(n,i),h=Kc(n,i);return vg(n,f,c,i),Fc(f,h),n.ancestors.pop(),n.schema=u,n.create(i,c,f,r)}function C0(n,i,r){const u={};return Fc(u,Kc(n,i)),n.create(i,n.Fragment,u,r)}function z0(n,i){return i.value}function vg(n,i,r,u){typeof r!="string"&&r!==n.Fragment&&n.passNode&&(i.node=u)}function Fc(n,i){if(i.length>0){const r=i.length>1?i:i[0];r&&(n.children=r)}}function N0(n,i,r){return u;function u(o,c,f,h){const p=Array.isArray(f.children)?r:i;return h?p(c,f,h):p(c,f)}}function M0(n,i){return r;function r(u,o,c,f){const h=Array.isArray(c.children),g=Xc(u);return i(o,c,f,h,{columnNumber:g?g.column-1:void 0,fileName:n,lineNumber:g?g.line:void 0},void 0)}}function D0(n,i){const r={};let u,o;for(o in i.properties)if(o!=="children"&&Zc.call(i.properties,o)){const c=R0(n,o,i.properties[o]);if(c){const[f,h]=c;n.tableCellAlignToStyle&&f==="align"&&typeof h=="string"&&k0.has(i.tagName)?u=h:r[f]=h}}if(u){const c=r.style||(r.style={});c[n.stylePropertyNameCase==="css"?"text-align":"textAlign"]=u}return r}function O0(n,i){const r={};for(const u of i.attributes)if(u.type==="mdxJsxExpressionAttribute")if(u.data&&u.data.estree&&n.evaluater){const c=u.data.estree.body[0];c.type;const f=c.expression;f.type;const h=f.properties[0];h.type,Object.assign(r,n.evaluater.evaluateExpression(h.argument))}else rr(n,i.position);else{const o=u.name;let c;if(u.value&&typeof u.value=="object")if(u.value.data&&u.value.data.estree&&n.evaluater){const h=u.value.data.estree.body[0];h.type,c=n.evaluater.evaluateExpression(h.expression)}else rr(n,i.position);else c=u.value===null?!0:u.value;r[o]=c}return r}function Kc(n,i){const r=[];let u=-1;const o=n.passKeys?new Map:v0;for(;++uo?0:o+i:i=i>o?o:i,r=r>0?r:0,u.length<1e4)f=Array.from(u),f.unshift(i,r),n.splice(...f);else for(r&&n.splice(i,r);c0?(cn(n,n.length,0,i),n):i}const _p={}.hasOwnProperty;function kg(n){const i={};let r=-1;for(;++r13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function Tn(n){return n.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Gt=Ll(/[A-Za-z]/),Lt=Ll(/[\dA-Za-z]/),Q0=Ll(/[#-'*+\--9=?A-Z^-~]/);function Ru(n){return n!==null&&(n<32||n===127)}const Dc=Ll(/\d/),X0=Ll(/[\dA-Fa-f]/),Z0=Ll(/[!-/:-@[-`{-~]/);function be(n){return n!==null&&n<-2}function tt(n){return n!==null&&(n<0||n===32)}function De(n){return n===-2||n===-1||n===32}const qu=Ll(new RegExp("\\p{P}|\\p{S}","u")),ri=Ll(/\s/);function Ll(n){return i;function i(r){return r!==null&&r>-1&&n.test(String.fromCharCode(r))}}function la(n){const i=[];let r=-1,u=0,o=0;for(;++r55295&&c<57344){const h=n.charCodeAt(r+1);c<56320&&h>56319&&h<57344?(f=String.fromCharCode(c,h),o=1):f="�"}else f=String.fromCharCode(c);f&&(i.push(n.slice(u,r),encodeURIComponent(f)),u=r+o+1,f=""),o&&(r+=o,o=0)}return i.join("")+n.slice(u)}function He(n,i,r,u){const o=u?u-1:Number.POSITIVE_INFINITY;let c=0;return f;function f(g){return De(g)?(n.enter(r),h(g)):i(g)}function h(g){return De(g)&&c++f))return;const ne=i.events.length;let ue=ne,ye,R;for(;ue--;)if(i.events[ue][0]==="exit"&&i.events[ue][1].type==="chunkFlow"){if(ye){R=i.events[ue][1].end;break}ye=!0}for(N(u),U=ne;UY;){const ae=r[se];i.containerState=ae[1],ae[0].exit.call(i,n)}r.length=Y}function K(){o.write([null]),c=void 0,o=void 0,i.containerState._closeFlow=void 0}}function I0(n,i,r){return He(n,n.attempt(this.parser.constructs.document,i,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ea(n){if(n===null||tt(n)||ri(n))return 1;if(qu(n))return 2}function Gu(n,i,r){const u=[];let o=-1;for(;++o1&&n[r][1].end.offset-n[r][1].start.offset>1?2:1;const x={...n[u][1].end},v={...n[r][1].start};Ap(x,-g),Ap(v,g),f={type:g>1?"strongSequence":"emphasisSequence",start:x,end:{...n[u][1].end}},h={type:g>1?"strongSequence":"emphasisSequence",start:{...n[r][1].start},end:v},c={type:g>1?"strongText":"emphasisText",start:{...n[u][1].end},end:{...n[r][1].start}},o={type:g>1?"strong":"emphasis",start:{...f.start},end:{...h.end}},n[u][1].end={...f.start},n[r][1].start={...h.end},p=[],n[u][1].end.offset-n[u][1].start.offset&&(p=_n(p,[["enter",n[u][1],i],["exit",n[u][1],i]])),p=_n(p,[["enter",o,i],["enter",f,i],["exit",f,i],["enter",c,i]]),p=_n(p,Gu(i.parser.constructs.insideSpan.null,n.slice(u+1,r),i)),p=_n(p,[["exit",c,i],["enter",h,i],["exit",h,i],["exit",o,i]]),n[r][1].end.offset-n[r][1].start.offset?(y=2,p=_n(p,[["enter",n[r][1],i],["exit",n[r][1],i]])):y=0,cn(n,u-1,r-u+3,p),r=u+p.length-y-2;break}}for(r=-1;++r0&&De(U)?He(n,K,"linePrefix",c+1)(U):K(U)}function K(U){return U===null||be(U)?n.check(wp,j,se)(U):(n.enter("codeFlowValue"),Y(U))}function Y(U){return U===null||be(U)?(n.exit("codeFlowValue"),K(U)):(n.consume(U),Y)}function se(U){return n.exit("codeFenced"),i(U)}function ae(U,ne,ue){let ye=0;return R;function R(I){return U.enter("lineEnding"),U.consume(I),U.exit("lineEnding"),Q}function Q(I){return U.enter("codeFencedFence"),De(I)?He(U,W,"linePrefix",u.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):W(I)}function W(I){return I===h?(U.enter("codeFencedFenceSequence"),de(I)):ue(I)}function de(I){return I===h?(ye++,U.consume(I),de):ye>=f?(U.exit("codeFencedFenceSequence"),De(I)?He(U,re,"whitespace")(I):re(I)):ue(I)}function re(I){return I===null||be(I)?(U.exit("codeFencedFence"),ne(I)):ue(I)}}}function ob(n,i,r){const u=this;return o;function o(f){return f===null?r(f):(n.enter("lineEnding"),n.consume(f),n.exit("lineEnding"),c)}function c(f){return u.parser.lazy[u.now().line]?r(f):i(f)}}const hc={name:"codeIndented",tokenize:fb},cb={partial:!0,tokenize:db};function fb(n,i,r){const u=this;return o;function o(p){return n.enter("codeIndented"),He(n,c,"linePrefix",5)(p)}function c(p){const y=u.events[u.events.length-1];return y&&y[1].type==="linePrefix"&&y[2].sliceSerialize(y[1],!0).length>=4?f(p):r(p)}function f(p){return p===null?g(p):be(p)?n.attempt(cb,f,g)(p):(n.enter("codeFlowValue"),h(p))}function h(p){return p===null||be(p)?(n.exit("codeFlowValue"),f(p)):(n.consume(p),h)}function g(p){return n.exit("codeIndented"),i(p)}}function db(n,i,r){const u=this;return o;function o(f){return u.parser.lazy[u.now().line]?r(f):be(f)?(n.enter("lineEnding"),n.consume(f),n.exit("lineEnding"),o):He(n,c,"linePrefix",5)(f)}function c(f){const h=u.events[u.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?i(f):be(f)?o(f):r(f)}}const hb={name:"codeText",previous:pb,resolve:mb,tokenize:gb};function mb(n){let i=n.length-4,r=3,u,o;if((n[r][1].type==="lineEnding"||n[r][1].type==="space")&&(n[i][1].type==="lineEnding"||n[i][1].type==="space")){for(u=r;++u=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+i+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ithis.left.length?this.right.slice(this.right.length-u+this.left.length,this.right.length-i+this.left.length).reverse():this.left.slice(i).concat(this.right.slice(this.right.length-u+this.left.length).reverse())}splice(i,r,u){const o=r||0;this.setCursor(Math.trunc(i));const c=this.right.splice(this.right.length-o,Number.POSITIVE_INFINITY);return u&&er(this.left,u),c.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(i){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(i)}pushMany(i){this.setCursor(Number.POSITIVE_INFINITY),er(this.left,i)}unshift(i){this.setCursor(0),this.right.push(i)}unshiftMany(i){this.setCursor(0),er(this.right,i.reverse())}setCursor(i){if(!(i===this.left.length||i>this.left.length&&this.right.length===0||i<0&&this.left.length===0))if(i=4?i(f):n.interrupt(u.parser.constructs.flow,r,i)(f)}}function Cg(n,i,r,u,o,c,f,h,g){const p=g||Number.POSITIVE_INFINITY;let y=0;return x;function x(N){return N===60?(n.enter(u),n.enter(o),n.enter(c),n.consume(N),n.exit(c),v):N===null||N===32||N===41||Ru(N)?r(N):(n.enter(u),n.enter(f),n.enter(h),n.enter("chunkString",{contentType:"string"}),j(N))}function v(N){return N===62?(n.enter(c),n.consume(N),n.exit(c),n.exit(o),n.exit(u),i):(n.enter(h),n.enter("chunkString",{contentType:"string"}),S(N))}function S(N){return N===62?(n.exit("chunkString"),n.exit(h),v(N)):N===null||N===60||be(N)?r(N):(n.consume(N),N===92?w:S)}function w(N){return N===60||N===62||N===92?(n.consume(N),S):S(N)}function j(N){return!y&&(N===null||N===41||tt(N))?(n.exit("chunkString"),n.exit(h),n.exit(f),n.exit(u),i(N)):y999||S===null||S===91||S===93&&!g||S===94&&!h&&"_hiddenFootnoteSupport"in f.parser.constructs?r(S):S===93?(n.exit(c),n.enter(o),n.consume(S),n.exit(o),n.exit(u),i):be(S)?(n.enter("lineEnding"),n.consume(S),n.exit("lineEnding"),y):(n.enter("chunkString",{contentType:"string"}),x(S))}function x(S){return S===null||S===91||S===93||be(S)||h++>999?(n.exit("chunkString"),y(S)):(n.consume(S),g||(g=!De(S)),S===92?v:x)}function v(S){return S===91||S===92||S===93?(n.consume(S),h++,x):x(S)}}function Ng(n,i,r,u,o,c){let f;return h;function h(v){return v===34||v===39||v===40?(n.enter(u),n.enter(o),n.consume(v),n.exit(o),f=v===40?41:v,g):r(v)}function g(v){return v===f?(n.enter(o),n.consume(v),n.exit(o),n.exit(u),i):(n.enter(c),p(v))}function p(v){return v===f?(n.exit(c),g(f)):v===null?r(v):be(v)?(n.enter("lineEnding"),n.consume(v),n.exit("lineEnding"),He(n,p,"linePrefix")):(n.enter("chunkString",{contentType:"string"}),y(v))}function y(v){return v===f||v===null||be(v)?(n.exit("chunkString"),p(v)):(n.consume(v),v===92?x:y)}function x(v){return v===f||v===92?(n.consume(v),y):y(v)}}function ir(n,i){let r;return u;function u(o){return be(o)?(n.enter("lineEnding"),n.consume(o),n.exit("lineEnding"),r=!0,u):De(o)?He(n,u,r?"linePrefix":"lineSuffix")(o):i(o)}}const Ab={name:"definition",tokenize:Eb},wb={partial:!0,tokenize:jb};function Eb(n,i,r){const u=this;let o;return c;function c(S){return n.enter("definition"),f(S)}function f(S){return zg.call(u,n,h,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(S)}function h(S){return o=Tn(u.sliceSerialize(u.events[u.events.length-1][1]).slice(1,-1)),S===58?(n.enter("definitionMarker"),n.consume(S),n.exit("definitionMarker"),g):r(S)}function g(S){return tt(S)?ir(n,p)(S):p(S)}function p(S){return Cg(n,y,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(S)}function y(S){return n.attempt(wb,x,x)(S)}function x(S){return De(S)?He(n,v,"whitespace")(S):v(S)}function v(S){return S===null||be(S)?(n.exit("definition"),u.parser.defined.push(o),i(S)):r(S)}}function jb(n,i,r){return u;function u(h){return tt(h)?ir(n,o)(h):r(h)}function o(h){return Ng(n,c,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function c(h){return De(h)?He(n,f,"whitespace")(h):f(h)}function f(h){return h===null||be(h)?i(h):r(h)}}const Tb={name:"hardBreakEscape",tokenize:Cb};function Cb(n,i,r){return u;function u(c){return n.enter("hardBreakEscape"),n.consume(c),o}function o(c){return be(c)?(n.exit("hardBreakEscape"),i(c)):r(c)}}const zb={name:"headingAtx",resolve:Nb,tokenize:Mb};function Nb(n,i){let r=n.length-2,u=3,o,c;return n[u][1].type==="whitespace"&&(u+=2),r-2>u&&n[r][1].type==="whitespace"&&(r-=2),n[r][1].type==="atxHeadingSequence"&&(u===r-1||r-4>u&&n[r-2][1].type==="whitespace")&&(r-=u+1===r?2:4),r>u&&(o={type:"atxHeadingText",start:n[u][1].start,end:n[r][1].end},c={type:"chunkText",start:n[u][1].start,end:n[r][1].end,contentType:"text"},cn(n,u,r-u+1,[["enter",o,i],["enter",c,i],["exit",c,i],["exit",o,i]])),n}function Mb(n,i,r){let u=0;return o;function o(y){return n.enter("atxHeading"),c(y)}function c(y){return n.enter("atxHeadingSequence"),f(y)}function f(y){return y===35&&u++<6?(n.consume(y),f):y===null||tt(y)?(n.exit("atxHeadingSequence"),h(y)):r(y)}function h(y){return y===35?(n.enter("atxHeadingSequence"),g(y)):y===null||be(y)?(n.exit("atxHeading"),i(y)):De(y)?He(n,h,"whitespace")(y):(n.enter("atxHeadingText"),p(y))}function g(y){return y===35?(n.consume(y),g):(n.exit("atxHeadingSequence"),h(y))}function p(y){return y===null||y===35||tt(y)?(n.exit("atxHeadingText"),h(y)):(n.consume(y),p)}}const Db=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],jp=["pre","script","style","textarea"],Ob={concrete:!0,name:"htmlFlow",resolveTo:Bb,tokenize:Ub},Rb={partial:!0,tokenize:qb},Lb={partial:!0,tokenize:Hb};function Bb(n){let i=n.length;for(;i--&&!(n[i][0]==="enter"&&n[i][1].type==="htmlFlow"););return i>1&&n[i-2][1].type==="linePrefix"&&(n[i][1].start=n[i-2][1].start,n[i+1][1].start=n[i-2][1].start,n.splice(i-2,2)),n}function Ub(n,i,r){const u=this;let o,c,f,h,g;return p;function p(k){return y(k)}function y(k){return n.enter("htmlFlow"),n.enter("htmlFlowData"),n.consume(k),x}function x(k){return k===33?(n.consume(k),v):k===47?(n.consume(k),c=!0,j):k===63?(n.consume(k),o=3,u.interrupt?i:A):Gt(k)?(n.consume(k),f=String.fromCharCode(k),q):r(k)}function v(k){return k===45?(n.consume(k),o=2,S):k===91?(n.consume(k),o=5,h=0,w):Gt(k)?(n.consume(k),o=4,u.interrupt?i:A):r(k)}function S(k){return k===45?(n.consume(k),u.interrupt?i:A):r(k)}function w(k){const le="CDATA[";return k===le.charCodeAt(h++)?(n.consume(k),h===le.length?u.interrupt?i:W:w):r(k)}function j(k){return Gt(k)?(n.consume(k),f=String.fromCharCode(k),q):r(k)}function q(k){if(k===null||k===47||k===62||tt(k)){const le=k===47,pe=f.toLowerCase();return!le&&!c&&jp.includes(pe)?(o=1,u.interrupt?i(k):W(k)):Db.includes(f.toLowerCase())?(o=6,le?(n.consume(k),N):u.interrupt?i(k):W(k)):(o=7,u.interrupt&&!u.parser.lazy[u.now().line]?r(k):c?K(k):Y(k))}return k===45||Lt(k)?(n.consume(k),f+=String.fromCharCode(k),q):r(k)}function N(k){return k===62?(n.consume(k),u.interrupt?i:W):r(k)}function K(k){return De(k)?(n.consume(k),K):R(k)}function Y(k){return k===47?(n.consume(k),R):k===58||k===95||Gt(k)?(n.consume(k),se):De(k)?(n.consume(k),Y):R(k)}function se(k){return k===45||k===46||k===58||k===95||Lt(k)?(n.consume(k),se):ae(k)}function ae(k){return k===61?(n.consume(k),U):De(k)?(n.consume(k),ae):Y(k)}function U(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(n.consume(k),g=k,ne):De(k)?(n.consume(k),U):ue(k)}function ne(k){return k===g?(n.consume(k),g=null,ye):k===null||be(k)?r(k):(n.consume(k),ne)}function ue(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||tt(k)?ae(k):(n.consume(k),ue)}function ye(k){return k===47||k===62||De(k)?Y(k):r(k)}function R(k){return k===62?(n.consume(k),Q):r(k)}function Q(k){return k===null||be(k)?W(k):De(k)?(n.consume(k),Q):r(k)}function W(k){return k===45&&o===2?(n.consume(k),M):k===60&&o===1?(n.consume(k),J):k===62&&o===4?(n.consume(k),T):k===63&&o===3?(n.consume(k),A):k===93&&o===5?(n.consume(k),xe):be(k)&&(o===6||o===7)?(n.exit("htmlFlowData"),n.check(Rb,G,de)(k)):k===null||be(k)?(n.exit("htmlFlowData"),de(k)):(n.consume(k),W)}function de(k){return n.check(Lb,re,G)(k)}function re(k){return n.enter("lineEnding"),n.consume(k),n.exit("lineEnding"),I}function I(k){return k===null||be(k)?de(k):(n.enter("htmlFlowData"),W(k))}function M(k){return k===45?(n.consume(k),A):W(k)}function J(k){return k===47?(n.consume(k),f="",P):W(k)}function P(k){if(k===62){const le=f.toLowerCase();return jp.includes(le)?(n.consume(k),T):W(k)}return Gt(k)&&f.length<8?(n.consume(k),f+=String.fromCharCode(k),P):W(k)}function xe(k){return k===93?(n.consume(k),A):W(k)}function A(k){return k===62?(n.consume(k),T):k===45&&o===2?(n.consume(k),A):W(k)}function T(k){return k===null||be(k)?(n.exit("htmlFlowData"),G(k)):(n.consume(k),T)}function G(k){return n.exit("htmlFlow"),i(k)}}function Hb(n,i,r){const u=this;return o;function o(f){return be(f)?(n.enter("lineEnding"),n.consume(f),n.exit("lineEnding"),c):r(f)}function c(f){return u.parser.lazy[u.now().line]?r(f):i(f)}}function qb(n,i,r){return u;function u(o){return n.enter("lineEnding"),n.consume(o),n.exit("lineEnding"),n.attempt(or,i,r)}}const Gb={name:"htmlText",tokenize:Yb};function Yb(n,i,r){const u=this;let o,c,f;return h;function h(A){return n.enter("htmlText"),n.enter("htmlTextData"),n.consume(A),g}function g(A){return A===33?(n.consume(A),p):A===47?(n.consume(A),ae):A===63?(n.consume(A),Y):Gt(A)?(n.consume(A),ue):r(A)}function p(A){return A===45?(n.consume(A),y):A===91?(n.consume(A),c=0,w):Gt(A)?(n.consume(A),K):r(A)}function y(A){return A===45?(n.consume(A),S):r(A)}function x(A){return A===null?r(A):A===45?(n.consume(A),v):be(A)?(f=x,J(A)):(n.consume(A),x)}function v(A){return A===45?(n.consume(A),S):x(A)}function S(A){return A===62?M(A):A===45?v(A):x(A)}function w(A){const T="CDATA[";return A===T.charCodeAt(c++)?(n.consume(A),c===T.length?j:w):r(A)}function j(A){return A===null?r(A):A===93?(n.consume(A),q):be(A)?(f=j,J(A)):(n.consume(A),j)}function q(A){return A===93?(n.consume(A),N):j(A)}function N(A){return A===62?M(A):A===93?(n.consume(A),N):j(A)}function K(A){return A===null||A===62?M(A):be(A)?(f=K,J(A)):(n.consume(A),K)}function Y(A){return A===null?r(A):A===63?(n.consume(A),se):be(A)?(f=Y,J(A)):(n.consume(A),Y)}function se(A){return A===62?M(A):Y(A)}function ae(A){return Gt(A)?(n.consume(A),U):r(A)}function U(A){return A===45||Lt(A)?(n.consume(A),U):ne(A)}function ne(A){return be(A)?(f=ne,J(A)):De(A)?(n.consume(A),ne):M(A)}function ue(A){return A===45||Lt(A)?(n.consume(A),ue):A===47||A===62||tt(A)?ye(A):r(A)}function ye(A){return A===47?(n.consume(A),M):A===58||A===95||Gt(A)?(n.consume(A),R):be(A)?(f=ye,J(A)):De(A)?(n.consume(A),ye):M(A)}function R(A){return A===45||A===46||A===58||A===95||Lt(A)?(n.consume(A),R):Q(A)}function Q(A){return A===61?(n.consume(A),W):be(A)?(f=Q,J(A)):De(A)?(n.consume(A),Q):ye(A)}function W(A){return A===null||A===60||A===61||A===62||A===96?r(A):A===34||A===39?(n.consume(A),o=A,de):be(A)?(f=W,J(A)):De(A)?(n.consume(A),W):(n.consume(A),re)}function de(A){return A===o?(n.consume(A),o=void 0,I):A===null?r(A):be(A)?(f=de,J(A)):(n.consume(A),de)}function re(A){return A===null||A===34||A===39||A===60||A===61||A===96?r(A):A===47||A===62||tt(A)?ye(A):(n.consume(A),re)}function I(A){return A===47||A===62||tt(A)?ye(A):r(A)}function M(A){return A===62?(n.consume(A),n.exit("htmlTextData"),n.exit("htmlText"),i):r(A)}function J(A){return n.exit("htmlTextData"),n.enter("lineEnding"),n.consume(A),n.exit("lineEnding"),P}function P(A){return De(A)?He(n,xe,"linePrefix",u.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):xe(A)}function xe(A){return n.enter("htmlTextData"),f(A)}}const Ic={name:"labelEnd",resolveAll:Zb,resolveTo:Fb,tokenize:Kb},Vb={tokenize:Jb},Qb={tokenize:$b},Xb={tokenize:Ib};function Zb(n){let i=-1;const r=[];for(;++i=3&&(p===null||be(p))?(n.exit("thematicBreak"),i(p)):r(p)}function g(p){return p===o?(n.consume(p),u++,g):(n.exit("thematicBreakSequence"),De(p)?He(n,h,"whitespace")(p):h(p))}}const It={continuation:{tokenize:uv},exit:ov,name:"list",tokenize:rv},iv={partial:!0,tokenize:cv},av={partial:!0,tokenize:sv};function rv(n,i,r){const u=this,o=u.events[u.events.length-1];let c=o&&o[1].type==="linePrefix"?o[2].sliceSerialize(o[1],!0).length:0,f=0;return h;function h(S){const w=u.containerState.type||(S===42||S===43||S===45?"listUnordered":"listOrdered");if(w==="listUnordered"?!u.containerState.marker||S===u.containerState.marker:Dc(S)){if(u.containerState.type||(u.containerState.type=w,n.enter(w,{_container:!0})),w==="listUnordered")return n.enter("listItemPrefix"),S===42||S===45?n.check(Du,r,p)(S):p(S);if(!u.interrupt||S===49)return n.enter("listItemPrefix"),n.enter("listItemValue"),g(S)}return r(S)}function g(S){return Dc(S)&&++f<10?(n.consume(S),g):(!u.interrupt||f<2)&&(u.containerState.marker?S===u.containerState.marker:S===41||S===46)?(n.exit("listItemValue"),p(S)):r(S)}function p(S){return n.enter("listItemMarker"),n.consume(S),n.exit("listItemMarker"),u.containerState.marker=u.containerState.marker||S,n.check(or,u.interrupt?r:y,n.attempt(iv,v,x))}function y(S){return u.containerState.initialBlankLine=!0,c++,v(S)}function x(S){return De(S)?(n.enter("listItemPrefixWhitespace"),n.consume(S),n.exit("listItemPrefixWhitespace"),v):r(S)}function v(S){return u.containerState.size=c+u.sliceSerialize(n.exit("listItemPrefix"),!0).length,i(S)}}function uv(n,i,r){const u=this;return u.containerState._closeFlow=void 0,n.check(or,o,c);function o(h){return u.containerState.furtherBlankLines=u.containerState.furtherBlankLines||u.containerState.initialBlankLine,He(n,i,"listItemIndent",u.containerState.size+1)(h)}function c(h){return u.containerState.furtherBlankLines||!De(h)?(u.containerState.furtherBlankLines=void 0,u.containerState.initialBlankLine=void 0,f(h)):(u.containerState.furtherBlankLines=void 0,u.containerState.initialBlankLine=void 0,n.attempt(av,i,f)(h))}function f(h){return u.containerState._closeFlow=!0,u.interrupt=void 0,He(n,n.attempt(It,i,r),"linePrefix",u.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function sv(n,i,r){const u=this;return He(n,o,"listItemIndent",u.containerState.size+1);function o(c){const f=u.events[u.events.length-1];return f&&f[1].type==="listItemIndent"&&f[2].sliceSerialize(f[1],!0).length===u.containerState.size?i(c):r(c)}}function ov(n){n.exit(this.containerState.type)}function cv(n,i,r){const u=this;return He(n,o,"listItemPrefixWhitespace",u.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function o(c){const f=u.events[u.events.length-1];return!De(c)&&f&&f[1].type==="listItemPrefixWhitespace"?i(c):r(c)}}const Tp={name:"setextUnderline",resolveTo:fv,tokenize:dv};function fv(n,i){let r=n.length,u,o,c;for(;r--;)if(n[r][0]==="enter"){if(n[r][1].type==="content"){u=r;break}n[r][1].type==="paragraph"&&(o=r)}else n[r][1].type==="content"&&n.splice(r,1),!c&&n[r][1].type==="definition"&&(c=r);const f={type:"setextHeading",start:{...n[u][1].start},end:{...n[n.length-1][1].end}};return n[o][1].type="setextHeadingText",c?(n.splice(o,0,["enter",f,i]),n.splice(c+1,0,["exit",n[u][1],i]),n[u][1].end={...n[c][1].end}):n[u][1]=f,n.push(["exit",f,i]),n}function dv(n,i,r){const u=this;let o;return c;function c(p){let y=u.events.length,x;for(;y--;)if(u.events[y][1].type!=="lineEnding"&&u.events[y][1].type!=="linePrefix"&&u.events[y][1].type!=="content"){x=u.events[y][1].type==="paragraph";break}return!u.parser.lazy[u.now().line]&&(u.interrupt||x)?(n.enter("setextHeadingLine"),o=p,f(p)):r(p)}function f(p){return n.enter("setextHeadingLineSequence"),h(p)}function h(p){return p===o?(n.consume(p),h):(n.exit("setextHeadingLineSequence"),De(p)?He(n,g,"lineSuffix")(p):g(p))}function g(p){return p===null||be(p)?(n.exit("setextHeadingLine"),i(p)):r(p)}}const hv={tokenize:mv};function mv(n){const i=this,r=n.attempt(or,u,n.attempt(this.parser.constructs.flowInitial,o,He(n,n.attempt(this.parser.constructs.flow,o,n.attempt(bb,o)),"linePrefix")));return r;function u(c){if(c===null){n.consume(c);return}return n.enter("lineEndingBlank"),n.consume(c),n.exit("lineEndingBlank"),i.currentConstruct=void 0,r}function o(c){if(c===null){n.consume(c);return}return n.enter("lineEnding"),n.consume(c),n.exit("lineEnding"),i.currentConstruct=void 0,r}}const pv={resolveAll:Dg()},gv=Mg("string"),yv=Mg("text");function Mg(n){return{resolveAll:Dg(n==="text"?xv:void 0),tokenize:i};function i(r){const u=this,o=this.parser.constructs[n],c=r.attempt(o,f,h);return f;function f(y){return p(y)?c(y):h(y)}function h(y){if(y===null){r.consume(y);return}return r.enter("data"),r.consume(y),g}function g(y){return p(y)?(r.exit("data"),c(y)):(r.consume(y),g)}function p(y){if(y===null)return!0;const x=o[y];let v=-1;if(x)for(;++v-1){const h=f[0];typeof h=="string"?f[0]=h.slice(u):f.shift()}c>0&&f.push(n[o].slice(0,c))}return f}function Nv(n,i){let r=-1;const u=[];let o;for(;++r>>=0,e===0?32:31-(zn(e)/Vt|0)|0}var ci=256,fi=262144,di=4194304;function en(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function hi(e,t,l){var a=e.pendingLanes;if(a===0)return 0;var s=0,d=e.suspendedLanes,v=e.pingedLanes;e=e.warmLanes;var _=a&134217727;return _!==0?(a=_&~d,a!==0?s=en(a):(v&=_,v!==0?s=en(v):l||(l=_&~e,l!==0&&(s=en(l))))):(_=a&~d,_!==0?s=en(_):v!==0?s=en(v):l||(l=a&~e,l!==0&&(s=en(l)))),s===0?0:t!==0&&t!==s&&(t&d)===0&&(d=s&-s,l=t&-t,d>=l||d===32&&(l&4194048)!==0)?t:s}function cl(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function fr(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function aa(){var e=di;return di<<=1,(di&62914560)===0&&(di=4194304),e}function ra(e){for(var t=[],l=0;31>l;l++)t.push(e);return t}function Gn(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Ju(e,t,l,a,s,d){var v=e.pendingLanes;e.pendingLanes=l,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=l,e.entangledLanes&=l,e.errorRecoveryDisabledLanes&=l,e.shellSuspendCounter=0;var _=e.entanglements,E=e.expirationTimes,O=e.hiddenUpdates;for(l=v&~l;0"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var Oy=/[\n"\\]/g;function hn(e){return e.replace(Oy,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function Iu(e,t,l,a,s,d,v,_){e.name="",v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"?e.type=v:e.removeAttribute("type"),t!=null?v==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+dn(t)):e.value!==""+dn(t)&&(e.value=""+dn(t)):v!=="submit"&&v!=="reset"||e.removeAttribute("value"),t!=null?Pu(e,v,dn(t)):l!=null?Pu(e,v,dn(l)):a!=null&&e.removeAttribute("value"),s==null&&d!=null&&(e.defaultChecked=!!d),s!=null&&(e.checked=s&&typeof s!="function"&&typeof s!="symbol"),_!=null&&typeof _!="function"&&typeof _!="symbol"&&typeof _!="boolean"?e.name=""+dn(_):e.removeAttribute("name")}function yf(e,t,l,a,s,d,v,_){if(d!=null&&typeof d!="function"&&typeof d!="symbol"&&typeof d!="boolean"&&(e.type=d),t!=null||l!=null){if(!(d!=="submit"&&d!=="reset"||t!=null)){$u(e);return}l=l!=null?""+dn(l):"",t=t!=null?""+dn(t):l,_||t===e.value||(e.value=t),e.defaultValue=t}a=a??s,a=typeof a!="function"&&typeof a!="symbol"&&!!a,e.checked=_?e.checked:!!a,e.defaultChecked=!!a,v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(e.name=v),$u(e)}function Pu(e,t,l){t==="number"&&vr(e.ownerDocument)===e||e.defaultValue===""+l||(e.defaultValue=""+l)}function xi(e,t,l,a){if(e=e.options,t){t={};for(var s=0;s"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ls=!1;if(Xn)try{var ca={};Object.defineProperty(ca,"passive",{get:function(){ls=!0}}),window.addEventListener("test",ca,ca),window.removeEventListener("test",ca,ca)}catch{ls=!1}var fl=null,is=null,Sr=null;function Af(){if(Sr)return Sr;var e,t=is,l=t.length,a,s="value"in fl?fl.value:fl.textContent,d=s.length;for(e=0;e=ha),zf=" ",Nf=!1;function Mf(e,t){switch(e){case"keyup":return s1.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Df(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var _i=!1;function c1(e,t){switch(e){case"compositionend":return Df(t);case"keypress":return t.which!==32?null:(Nf=!0,zf);case"textInput":return e=t.data,e===zf&&Nf?null:e;default:return null}}function f1(e,t){if(_i)return e==="compositionend"||!os&&Mf(e,t)?(e=Af(),Sr=is=fl=null,_i=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:l,offset:t-e};e=a}e:{for(;l;){if(l.nextSibling){l=l.nextSibling;break e}l=l.parentNode}l=void 0}l=Gf(l)}}function Vf(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Vf(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Qf(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=vr(e.document);t instanceof e.HTMLIFrameElement;){try{var l=typeof t.contentWindow.location.href=="string"}catch{l=!1}if(l)e=t.contentWindow;else break;t=vr(e.document)}return t}function ds(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var v1=Xn&&"documentMode"in document&&11>=document.documentMode,ki=null,hs=null,ya=null,ms=!1;function Xf(e,t,l){var a=l.window===l?l.document:l.nodeType===9?l:l.ownerDocument;ms||ki==null||ki!==vr(a)||(a=ki,"selectionStart"in a&&ds(a)?a={start:a.selectionStart,end:a.selectionEnd}:(a=(a.ownerDocument&&a.ownerDocument.defaultView||window).getSelection(),a={anchorNode:a.anchorNode,anchorOffset:a.anchorOffset,focusNode:a.focusNode,focusOffset:a.focusOffset}),ya&&ga(ya,a)||(ya=a,a=mu(hs,"onSelect"),0>=v,s-=v,Dn=1<<32-Qe(t)+s|l<ze?(Le=me,me=null):Le=me.sibling;var Ge=L(z,me,D[ze],X);if(Ge===null){me===null&&(me=Le);break}e&&me&&Ge.alternate===null&&t(z,me),C=d(Ge,C,ze),qe===null?ge=Ge:qe.sibling=Ge,qe=Ge,me=Le}if(ze===D.length)return l(z,me),Be&&Fn(z,ze),ge;if(me===null){for(;zeze?(Le=me,me=null):Le=me.sibling;var Dl=L(z,me,Ge.value,X);if(Dl===null){me===null&&(me=Le);break}e&&me&&Dl.alternate===null&&t(z,me),C=d(Dl,C,ze),qe===null?ge=Dl:qe.sibling=Dl,qe=Dl,me=Le}if(Ge.done)return l(z,me),Be&&Fn(z,ze),ge;if(me===null){for(;!Ge.done;ze++,Ge=D.next())Ge=Z(z,Ge.value,X),Ge!==null&&(C=d(Ge,C,ze),qe===null?ge=Ge:qe.sibling=Ge,qe=Ge);return Be&&Fn(z,ze),ge}for(me=a(me);!Ge.done;ze++,Ge=D.next())Ge=H(me,z,ze,Ge.value,X),Ge!==null&&(e&&Ge.alternate!==null&&me.delete(Ge.key===null?ze:Ge.key),C=d(Ge,C,ze),qe===null?ge=Ge:qe.sibling=Ge,qe=Ge);return e&&me.forEach(function(Hx){return t(z,Hx)}),Be&&Fn(z,ze),ge}function Ie(z,C,D,X){if(typeof D=="object"&&D!==null&&D.type===j&&D.key===null&&(D=D.props.children),typeof D=="object"&&D!==null){switch(D.$$typeof){case S:e:{for(var ge=D.key;C!==null;){if(C.key===ge){if(ge=D.type,ge===j){if(C.tag===7){l(z,C.sibling),X=s(C,D.props.children),X.return=z,z=X;break e}}else if(C.elementType===ge||typeof ge=="object"&&ge!==null&&ge.$$typeof===ue&&Fl(ge)===C.type){l(z,C.sibling),X=s(C,D.props),ka(X,D),X.return=z,z=X;break e}l(z,C);break}else t(z,C);C=C.sibling}D.type===j?(X=Yl(D.props.children,z.mode,X,D.key),X.return=z,z=X):(X=Nr(D.type,D.key,D.props,null,z.mode,X),ka(X,D),X.return=z,z=X)}return v(z);case w:e:{for(ge=D.key;C!==null;){if(C.key===ge)if(C.tag===4&&C.stateNode.containerInfo===D.containerInfo&&C.stateNode.implementation===D.implementation){l(z,C.sibling),X=s(C,D.children||[]),X.return=z,z=X;break e}else{l(z,C);break}else t(z,C);C=C.sibling}X=Ss(D,z.mode,X),X.return=z,z=X}return v(z);case ue:return D=Fl(D),Ie(z,C,D,X)}if(I(D))return fe(z,C,D,X);if(W(D)){if(ge=W(D),typeof ge!="function")throw Error(u(150));return D=ge.call(D),Se(z,C,D,X)}if(typeof D.then=="function")return Ie(z,C,Ur(D),X);if(D.$$typeof===Y)return Ie(z,C,Or(z,D),X);Hr(z,D)}return typeof D=="string"&&D!==""||typeof D=="number"||typeof D=="bigint"?(D=""+D,C!==null&&C.tag===6?(l(z,C.sibling),X=s(C,D),X.return=z,z=X):(l(z,C),X=bs(D,z.mode,X),X.return=z,z=X),v(z)):l(z,C)}return function(z,C,D,X){try{_a=0;var ge=Ie(z,C,D,X);return Oi=null,ge}catch(me){if(me===Di||me===Lr)throw me;var qe=nn(29,me,null,z.mode);return qe.lanes=X,qe.return=z,qe}finally{}}}var Jl=md(!0),pd=md(!1),gl=!1;function Ds(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Os(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function yl(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function xl(e,t,l){var a=e.updateQueue;if(a===null)return null;if(a=a.shared,(Ye&2)!==0){var s=a.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),a.pending=t,t=zr(e),Pf(e,null,l),t}return Cr(e,a,t,l),zr(e)}function Aa(e,t,l){if(t=t.updateQueue,t!==null&&(t=t.shared,(l&4194048)!==0)){var a=t.lanes;a&=e.pendingLanes,l|=a,t.lanes=l,mi(e,l)}}function Rs(e,t){var l=e.updateQueue,a=e.alternate;if(a!==null&&(a=a.updateQueue,l===a)){var s=null,d=null;if(l=l.firstBaseUpdate,l!==null){do{var v={lane:l.lane,tag:l.tag,payload:l.payload,callback:null,next:null};d===null?s=d=v:d=d.next=v,l=l.next}while(l!==null);d===null?s=d=t:d=d.next=t}else s=d=t;l={baseState:a.baseState,firstBaseUpdate:s,lastBaseUpdate:d,shared:a.shared,callbacks:a.callbacks},e.updateQueue=l;return}e=l.lastBaseUpdate,e===null?l.firstBaseUpdate=t:e.next=t,l.lastBaseUpdate=t}var Ls=!1;function wa(){if(Ls){var e=Mi;if(e!==null)throw e}}function Ea(e,t,l,a){Ls=!1;var s=e.updateQueue;gl=!1;var d=s.firstBaseUpdate,v=s.lastBaseUpdate,_=s.shared.pending;if(_!==null){s.shared.pending=null;var E=_,O=E.next;E.next=null,v===null?d=O:v.next=O,v=E;var V=e.alternate;V!==null&&(V=V.updateQueue,_=V.lastBaseUpdate,_!==v&&(_===null?V.firstBaseUpdate=O:_.next=O,V.lastBaseUpdate=E))}if(d!==null){var Z=s.baseState;v=0,V=O=E=null,_=d;do{var L=_.lane&-536870913,H=L!==_.lane;if(H?(Re&L)===L:(a&L)===L){L!==0&&L===Ni&&(Ls=!0),V!==null&&(V=V.next={lane:0,tag:_.tag,payload:_.payload,callback:null,next:null});e:{var fe=e,Se=_;L=t;var Ie=l;switch(Se.tag){case 1:if(fe=Se.payload,typeof fe=="function"){Z=fe.call(Ie,Z,L);break e}Z=fe;break e;case 3:fe.flags=fe.flags&-65537|128;case 0:if(fe=Se.payload,L=typeof fe=="function"?fe.call(Ie,Z,L):fe,L==null)break e;Z=x({},Z,L);break e;case 2:gl=!0}}L=_.callback,L!==null&&(e.flags|=64,H&&(e.flags|=8192),H=s.callbacks,H===null?s.callbacks=[L]:H.push(L))}else H={lane:L,tag:_.tag,payload:_.payload,callback:_.callback,next:null},V===null?(O=V=H,E=Z):V=V.next=H,v|=L;if(_=_.next,_===null){if(_=s.shared.pending,_===null)break;H=_,_=H.next,H.next=null,s.lastBaseUpdate=H,s.shared.pending=null}}while(!0);V===null&&(E=Z),s.baseState=E,s.firstBaseUpdate=O,s.lastBaseUpdate=V,d===null&&(s.shared.lanes=0),kl|=v,e.lanes=v,e.memoizedState=Z}}function gd(e,t){if(typeof e!="function")throw Error(u(191,e));e.call(t)}function yd(e,t){var l=e.callbacks;if(l!==null)for(e.callbacks=null,e=0;ed?d:8;var v=M.T,_={};M.T=_,to(e,!1,t,l);try{var E=s(),O=M.S;if(O!==null&&O(_,E),E!==null&&typeof E=="object"&&typeof E.then=="function"){var V=T1(E,a);Ca(e,t,V,sn(e))}else Ca(e,t,a,sn(e))}catch(Z){Ca(e,t,{then:function(){},status:"rejected",reason:Z},sn())}finally{J.p=d,v!==null&&_.types!==null&&(v.types=_.types),M.T=v}}function O1(){}function Ws(e,t,l,a){if(e.tag!==5)throw Error(u(476));var s=Jd(e).queue;Kd(e,s,t,P,l===null?O1:function(){return $d(e),l(a)})}function Jd(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:P,baseState:P,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:In,lastRenderedState:P},next:null};var l={};return t.next={memoizedState:l,baseState:l,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:In,lastRenderedState:l},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function $d(e){var t=Jd(e);t.next===null&&(t=e.alternate.memoizedState),Ca(e,t.next.queue,{},sn())}function eo(){return Ct(Za)}function Id(){return mt().memoizedState}function Pd(){return mt().memoizedState}function R1(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var l=sn();e=yl(l);var a=xl(t,e,l);a!==null&&($t(a,t,l),Aa(a,t,l)),t={cache:Cs()},e.payload=t;return}t=t.return}}function L1(e,t,l){var a=sn();l={lane:a,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Jr(e)?eh(t,l):(l=xs(e,t,l,a),l!==null&&($t(l,e,a),th(l,t,a)))}function Wd(e,t,l){var a=sn();Ca(e,t,l,a)}function Ca(e,t,l,a){var s={lane:a,revertLane:0,gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null};if(Jr(e))eh(t,s);else{var d=e.alternate;if(e.lanes===0&&(d===null||d.lanes===0)&&(d=t.lastRenderedReducer,d!==null))try{var v=t.lastRenderedState,_=d(v,l);if(s.hasEagerState=!0,s.eagerState=_,tn(_,v))return Cr(e,t,s,0),We===null&&Tr(),!1}catch{}finally{}if(l=xs(e,t,s,a),l!==null)return $t(l,e,a),th(l,t,a),!0}return!1}function to(e,t,l,a){if(a={lane:2,revertLane:Oo(),gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},Jr(e)){if(t)throw Error(u(479))}else t=xs(e,l,a,2),t!==null&&$t(t,e,2)}function Jr(e){var t=e.alternate;return e===Te||t!==null&&t===Te}function eh(e,t){Li=Yr=!0;var l=e.pending;l===null?t.next=t:(t.next=l.next,l.next=t),e.pending=t}function th(e,t,l){if((l&4194048)!==0){var a=t.lanes;a&=e.pendingLanes,l|=a,t.lanes=l,mi(e,l)}}var za={readContext:Ct,use:Xr,useCallback:ct,useContext:ct,useEffect:ct,useImperativeHandle:ct,useLayoutEffect:ct,useInsertionEffect:ct,useMemo:ct,useReducer:ct,useRef:ct,useState:ct,useDebugValue:ct,useDeferredValue:ct,useTransition:ct,useSyncExternalStore:ct,useId:ct,useHostTransitionStatus:ct,useFormState:ct,useActionState:ct,useOptimistic:ct,useMemoCache:ct,useCacheRefresh:ct};za.useEffectEvent=ct;var nh={readContext:Ct,use:Xr,useCallback:function(e,t){return qt().memoizedState=[e,t===void 0?null:t],e},useContext:Ct,useEffect:Hd,useImperativeHandle:function(e,t,l){l=l!=null?l.concat([e]):null,Fr(4194308,4,Vd.bind(null,t,e),l)},useLayoutEffect:function(e,t){return Fr(4194308,4,e,t)},useInsertionEffect:function(e,t){Fr(4,2,e,t)},useMemo:function(e,t){var l=qt();t=t===void 0?null:t;var a=e();if($l){Ot(!0);try{e()}finally{Ot(!1)}}return l.memoizedState=[a,t],a},useReducer:function(e,t,l){var a=qt();if(l!==void 0){var s=l(t);if($l){Ot(!0);try{l(t)}finally{Ot(!1)}}}else s=t;return a.memoizedState=a.baseState=s,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:s},a.queue=e,e=e.dispatch=L1.bind(null,Te,e),[a.memoizedState,e]},useRef:function(e){var t=qt();return e={current:e},t.memoizedState=e},useState:function(e){e=Ks(e);var t=e.queue,l=Wd.bind(null,Te,t);return t.dispatch=l,[e.memoizedState,l]},useDebugValue:Is,useDeferredValue:function(e,t){var l=qt();return Ps(l,e,t)},useTransition:function(){var e=Ks(!1);return e=Kd.bind(null,Te,e.queue,!0,!1),qt().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,l){var a=Te,s=qt();if(Be){if(l===void 0)throw Error(u(407));l=l()}else{if(l=t(),We===null)throw Error(u(349));(Re&127)!==0||kd(a,t,l)}s.memoizedState=l;var d={value:l,getSnapshot:t};return s.queue=d,Hd(wd.bind(null,a,d,e),[e]),a.flags|=2048,Ui(9,{destroy:void 0},Ad.bind(null,a,d,l,t),null),l},useId:function(){var e=qt(),t=We.identifierPrefix;if(Be){var l=On,a=Dn;l=(a&~(1<<32-Qe(a)-1)).toString(32)+l,t="_"+t+"R_"+l,l=Vr++,0<\/script>",d=d.removeChild(d.firstChild);break;case"select":d=typeof a.is=="string"?v.createElement("select",{is:a.is}):v.createElement("select"),a.multiple?d.multiple=!0:a.size&&(d.size=a.size);break;default:d=typeof a.is=="string"?v.createElement(s,{is:a.is}):v.createElement(s)}}d[_t]=t,d[jt]=a;e:for(v=t.child;v!==null;){if(v.tag===5||v.tag===6)d.appendChild(v.stateNode);else if(v.tag!==4&&v.tag!==27&&v.child!==null){v.child.return=v,v=v.child;continue}if(v===t)break e;for(;v.sibling===null;){if(v.return===null||v.return===t)break e;v=v.return}v.sibling.return=v.return,v=v.sibling}t.stateNode=d;e:switch(Nt(d,s,a),s){case"button":case"input":case"select":case"textarea":a=!!a.autoFocus;break e;case"img":a=!0;break e;default:a=!1}a&&Wn(t)}}return it(t),go(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,l),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==a&&Wn(t);else{if(typeof a!="string"&&t.stateNode===null)throw Error(u(166));if(e=he.current,Ci(t)){if(e=t.stateNode,l=t.memoizedProps,a=null,s=Tt,s!==null)switch(s.tag){case 27:case 5:a=s.memoizedProps}e[_t]=t,e=!!(e.nodeValue===l||a!==null&&a.suppressHydrationWarning===!0||Sm(e.nodeValue,l)),e||ml(t,!0)}else e=pu(e).createTextNode(a),e[_t]=t,t.stateNode=e}return it(t),null;case 31:if(l=t.memoizedState,e===null||e.memoizedState!==null){if(a=Ci(t),l!==null){if(e===null){if(!a)throw Error(u(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(u(557));e[_t]=t}else Vl(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;it(t),e=!1}else l=ws(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=l),e=!0;if(!e)return t.flags&256?(an(t),t):(an(t),null);if((t.flags&128)!==0)throw Error(u(558))}return it(t),null;case 13:if(a=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(s=Ci(t),a!==null&&a.dehydrated!==null){if(e===null){if(!s)throw Error(u(318));if(s=t.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(u(317));s[_t]=t}else Vl(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;it(t),s=!1}else s=ws(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),s=!0;if(!s)return t.flags&256?(an(t),t):(an(t),null)}return an(t),(t.flags&128)!==0?(t.lanes=l,t):(l=a!==null,e=e!==null&&e.memoizedState!==null,l&&(a=t.child,s=null,a.alternate!==null&&a.alternate.memoizedState!==null&&a.alternate.memoizedState.cachePool!==null&&(s=a.alternate.memoizedState.cachePool.pool),d=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(d=a.memoizedState.cachePool.pool),d!==s&&(a.flags|=2048)),l!==e&&l&&(t.child.flags|=8192),eu(t,t.updateQueue),it(t),null);case 4:return Ue(),e===null&&Uo(t.stateNode.containerInfo),it(t),null;case 10:return Jn(t.type),it(t),null;case 19:if(G(ht),a=t.memoizedState,a===null)return it(t),null;if(s=(t.flags&128)!==0,d=a.rendering,d===null)if(s)Ma(a,!1);else{if(ft!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(d=Gr(e),d!==null){for(t.flags|=128,Ma(a,!1),e=d.updateQueue,t.updateQueue=e,eu(t,e),t.subtreeFlags=0,e=l,l=t.child;l!==null;)Wf(l,e),l=l.sibling;return k(ht,ht.current&1|2),Be&&Fn(t,a.treeForkCount),t.child}e=e.sibling}a.tail!==null&&ut()>au&&(t.flags|=128,s=!0,Ma(a,!1),t.lanes=4194304)}else{if(!s)if(e=Gr(d),e!==null){if(t.flags|=128,s=!0,e=e.updateQueue,t.updateQueue=e,eu(t,e),Ma(a,!0),a.tail===null&&a.tailMode==="hidden"&&!d.alternate&&!Be)return it(t),null}else 2*ut()-a.renderingStartTime>au&&l!==536870912&&(t.flags|=128,s=!0,Ma(a,!1),t.lanes=4194304);a.isBackwards?(d.sibling=t.child,t.child=d):(e=a.last,e!==null?e.sibling=d:t.child=d,a.last=d)}return a.tail!==null?(e=a.tail,a.rendering=e,a.tail=e.sibling,a.renderingStartTime=ut(),e.sibling=null,l=ht.current,k(ht,s?l&1|2:l&1),Be&&Fn(t,a.treeForkCount),e):(it(t),null);case 22:case 23:return an(t),Us(),a=t.memoizedState!==null,e!==null?e.memoizedState!==null!==a&&(t.flags|=8192):a&&(t.flags|=8192),a?(l&536870912)!==0&&(t.flags&128)===0&&(it(t),t.subtreeFlags&6&&(t.flags|=8192)):it(t),l=t.updateQueue,l!==null&&eu(t,l.retryQueue),l=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(l=e.memoizedState.cachePool.pool),a=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(a=t.memoizedState.cachePool.pool),a!==l&&(t.flags|=2048),e!==null&&G(Zl),null;case 24:return l=null,e!==null&&(l=e.memoizedState.cache),t.memoizedState.cache!==l&&(t.flags|=2048),Jn(gt),it(t),null;case 25:return null;case 30:return null}throw Error(u(156,t.tag))}function G1(e,t){switch(ks(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Jn(gt),Ue(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return nt(t),null;case 31:if(t.memoizedState!==null){if(an(t),t.alternate===null)throw Error(u(340));Vl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(an(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(u(340));Vl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return G(ht),null;case 4:return Ue(),null;case 10:return Jn(t.type),null;case 22:case 23:return an(t),Us(),e!==null&&G(Zl),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Jn(gt),null;case 25:return null;default:return null}}function Eh(e,t){switch(ks(t),t.tag){case 3:Jn(gt),Ue();break;case 26:case 27:case 5:nt(t);break;case 4:Ue();break;case 31:t.memoizedState!==null&&an(t);break;case 13:an(t);break;case 19:G(ht);break;case 10:Jn(t.type);break;case 22:case 23:an(t),Us(),e!==null&&G(Zl);break;case 24:Jn(gt)}}function Da(e,t){try{var l=t.updateQueue,a=l!==null?l.lastEffect:null;if(a!==null){var s=a.next;l=s;do{if((l.tag&e)===e){a=void 0;var d=l.create,v=l.inst;a=d(),v.destroy=a}l=l.next}while(l!==s)}}catch(_){Fe(t,t.return,_)}}function Sl(e,t,l){try{var a=t.updateQueue,s=a!==null?a.lastEffect:null;if(s!==null){var d=s.next;a=d;do{if((a.tag&e)===e){var v=a.inst,_=v.destroy;if(_!==void 0){v.destroy=void 0,s=t;var E=l,O=_;try{O()}catch(V){Fe(s,E,V)}}}a=a.next}while(a!==d)}}catch(V){Fe(t,t.return,V)}}function jh(e){var t=e.updateQueue;if(t!==null){var l=e.stateNode;try{yd(t,l)}catch(a){Fe(e,e.return,a)}}}function Th(e,t,l){l.props=Il(e.type,e.memoizedProps),l.state=e.memoizedState;try{l.componentWillUnmount()}catch(a){Fe(e,t,a)}}function Oa(e,t){try{var l=e.ref;if(l!==null){switch(e.tag){case 26:case 27:case 5:var a=e.stateNode;break;case 30:a=e.stateNode;break;default:a=e.stateNode}typeof l=="function"?e.refCleanup=l(a):l.current=a}}catch(s){Fe(e,t,s)}}function Rn(e,t){var l=e.ref,a=e.refCleanup;if(l!==null)if(typeof a=="function")try{a()}catch(s){Fe(e,t,s)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof l=="function")try{l(null)}catch(s){Fe(e,t,s)}else l.current=null}function Ch(e){var t=e.type,l=e.memoizedProps,a=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":l.autoFocus&&a.focus();break e;case"img":l.src?a.src=l.src:l.srcSet&&(a.srcset=l.srcSet)}}catch(s){Fe(e,e.return,s)}}function yo(e,t,l){try{var a=e.stateNode;ox(a,e.type,l,t),a[jt]=t}catch(s){Fe(e,e.return,s)}}function zh(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Tl(e.type)||e.tag===4}function xo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||zh(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Tl(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function vo(e,t,l){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?(l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l).insertBefore(e,t):(t=l.nodeType===9?l.body:l.nodeName==="HTML"?l.ownerDocument.body:l,t.appendChild(e),l=l._reactRootContainer,l!=null||t.onclick!==null||(t.onclick=Qn));else if(a!==4&&(a===27&&Tl(e.type)&&(l=e.stateNode,t=null),e=e.child,e!==null))for(vo(e,t,l),e=e.sibling;e!==null;)vo(e,t,l),e=e.sibling}function tu(e,t,l){var a=e.tag;if(a===5||a===6)e=e.stateNode,t?l.insertBefore(e,t):l.appendChild(e);else if(a!==4&&(a===27&&Tl(e.type)&&(l=e.stateNode),e=e.child,e!==null))for(tu(e,t,l),e=e.sibling;e!==null;)tu(e,t,l),e=e.sibling}function Nh(e){var t=e.stateNode,l=e.memoizedProps;try{for(var a=e.type,s=t.attributes;s.length;)t.removeAttributeNode(s[0]);Nt(t,a,l),t[_t]=e,t[jt]=l}catch(d){Fe(e,e.return,d)}}var el=!1,vt=!1,bo=!1,Mh=typeof WeakSet=="function"?WeakSet:Set,Et=null;function Y1(e,t){if(e=e.containerInfo,Go=_u,e=Qf(e),ds(e)){if("selectionStart"in e)var l={start:e.selectionStart,end:e.selectionEnd};else e:{l=(l=e.ownerDocument)&&l.defaultView||window;var a=l.getSelection&&l.getSelection();if(a&&a.rangeCount!==0){l=a.anchorNode;var s=a.anchorOffset,d=a.focusNode;a=a.focusOffset;try{l.nodeType,d.nodeType}catch{l=null;break e}var v=0,_=-1,E=-1,O=0,V=0,Z=e,L=null;t:for(;;){for(var H;Z!==l||s!==0&&Z.nodeType!==3||(_=v+s),Z!==d||a!==0&&Z.nodeType!==3||(E=v+a),Z.nodeType===3&&(v+=Z.nodeValue.length),(H=Z.firstChild)!==null;)L=Z,Z=H;for(;;){if(Z===e)break t;if(L===l&&++O===s&&(_=v),L===d&&++V===a&&(E=v),(H=Z.nextSibling)!==null)break;Z=L,L=Z.parentNode}Z=H}l=_===-1||E===-1?null:{start:_,end:E}}else l=null}l=l||{start:0,end:0}}else l=null;for(Yo={focusedElem:e,selectionRange:l},_u=!1,Et=t;Et!==null;)if(t=Et,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Et=e;else for(;Et!==null;){switch(t=Et,d=t.alternate,e=t.flags,t.tag){case 0:if((e&4)!==0&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(l=0;l title"))),Nt(d,a,l),d[_t]=e,Ke(d),a=d;break e;case"link":var v=Um("link","href",s).get(a+(l.href||""));if(v){for(var _=0;_Ie&&(v=Ie,Ie=Se,Se=v);var z=Yf(_,Se),C=Yf(_,Ie);if(z&&C&&(H.rangeCount!==1||H.anchorNode!==z.node||H.anchorOffset!==z.offset||H.focusNode!==C.node||H.focusOffset!==C.offset)){var D=Z.createRange();D.setStart(z.node,z.offset),H.removeAllRanges(),Se>Ie?(H.addRange(D),H.extend(C.node,C.offset)):(D.setEnd(C.node,C.offset),H.addRange(D))}}}}for(Z=[],H=_;H=H.parentNode;)H.nodeType===1&&Z.push({element:H,left:H.scrollLeft,top:H.scrollTop});for(typeof _.focus=="function"&&_.focus(),_=0;_l?32:l,M.T=null,l=jo,jo=null;var d=wl,v=al;if(kt=0,Vi=wl=null,al=0,(Ye&6)!==0)throw Error(u(331));var _=Ye;if(Ye|=4,Vh(d.current),qh(d,d.current,v,l),Ye=_,qa(0,!1),ot&&typeof ot.onPostCommitFiberRoot=="function")try{ot.onPostCommitFiberRoot(wt,d)}catch{}return!0}finally{J.p=s,M.T=a,um(e,t)}}function om(e,t,l){t=pn(l,t),t=ao(e.stateNode,t,2),e=xl(e,t,2),e!==null&&(Gn(e,2),Ln(e))}function Fe(e,t,l){if(e.tag===3)om(e,e,l);else for(;t!==null;){if(t.tag===3){om(t,e,l);break}else if(t.tag===1){var a=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof a.componentDidCatch=="function"&&(Al===null||!Al.has(a))){e=pn(l,e),l=ch(2),a=xl(t,l,2),a!==null&&(fh(l,a,t,e),Gn(a,2),Ln(a));break}}t=t.return}}function No(e,t,l){var a=e.pingCache;if(a===null){a=e.pingCache=new X1;var s=new Set;a.set(t,s)}else s=a.get(t),s===void 0&&(s=new Set,a.set(t,s));s.has(l)||(ko=!0,s.add(l),e=$1.bind(null,e,t,l),t.then(e,e))}function $1(e,t,l){var a=e.pingCache;a!==null&&a.delete(t),e.pingedLanes|=e.suspendedLanes&l,e.warmLanes&=~l,We===e&&(Re&l)===l&&(ft===4||ft===3&&(Re&62914560)===Re&&300>ut()-iu?(Ye&2)===0&&Qi(e,0):Ao|=l,Yi===Re&&(Yi=0)),Ln(e)}function cm(e,t){t===0&&(t=aa()),e=Gl(e,t),e!==null&&(Gn(e,t),Ln(e))}function I1(e){var t=e.memoizedState,l=0;t!==null&&(l=t.retryLane),cm(e,l)}function P1(e,t){var l=0;switch(e.tag){case 31:case 13:var a=e.stateNode,s=e.memoizedState;s!==null&&(l=s.retryLane);break;case 19:a=e.stateNode;break;case 22:a=e.stateNode._retryCache;break;default:throw Error(u(314))}a!==null&&a.delete(t),cm(e,l)}function W1(e,t){return Yt(e,t)}var fu=null,Zi=null,Mo=!1,du=!1,Do=!1,jl=0;function Ln(e){e!==Zi&&e.next===null&&(Zi===null?fu=Zi=e:Zi=Zi.next=e),du=!0,Mo||(Mo=!0,tx())}function qa(e,t){if(!Do&&du){Do=!0;do for(var l=!1,a=fu;a!==null;){if(e!==0){var s=a.pendingLanes;if(s===0)var d=0;else{var v=a.suspendedLanes,_=a.pingedLanes;d=(1<<31-Qe(42|e)+1)-1,d&=s&~(v&~_),d=d&201326741?d&201326741|1:d?d|2:0}d!==0&&(l=!0,mm(a,d))}else d=Re,d=hi(a,a===We?d:0,a.cancelPendingCommit!==null||a.timeoutHandle!==-1),(d&3)===0||cl(a,d)||(l=!0,mm(a,d));a=a.next}while(l);Do=!1}}function ex(){fm()}function fm(){du=Mo=!1;var e=0;jl!==0&&fx()&&(e=jl);for(var t=ut(),l=null,a=fu;a!==null;){var s=a.next,d=dm(a,t);d===0?(a.next=null,l===null?fu=s:l.next=s,s===null&&(Zi=l)):(l=a,(e!==0||(d&3)!==0)&&(du=!0)),a=s}kt!==0&&kt!==5||qa(e),jl!==0&&(jl=0)}function dm(e,t){for(var l=e.suspendedLanes,a=e.pingedLanes,s=e.expirationTimes,d=e.pendingLanes&-62914561;0_)break;var V=E.transferSize,Z=E.initiatorType;V&&_m(Z)&&(E=E.responseEnd,v+=V*(E<_?1:(_-O)/(E-O)))}if(--a,t+=8*(d+v)/(s.duration/1e3),e++,10"u"?null:document;function Om(e,t,l){var a=Fi;if(a&&typeof t=="string"&&t){var s=hn(t);s='link[rel="'+e+'"][href="'+s+'"]',typeof l=="string"&&(s+='[crossorigin="'+l+'"]'),Dm.has(s)||(Dm.add(s),e={rel:e,crossOrigin:l,href:t},a.querySelector(s)===null&&(t=a.createElement("link"),Nt(t,"link",e),Ke(t),a.head.appendChild(t)))}}function bx(e){rl.D(e),Om("dns-prefetch",e,null)}function Sx(e,t){rl.C(e,t),Om("preconnect",e,t)}function _x(e,t,l){rl.L(e,t,l);var a=Fi;if(a&&e&&t){var s='link[rel="preload"][as="'+hn(t)+'"]';t==="image"&&l&&l.imageSrcSet?(s+='[imagesrcset="'+hn(l.imageSrcSet)+'"]',typeof l.imageSizes=="string"&&(s+='[imagesizes="'+hn(l.imageSizes)+'"]')):s+='[href="'+hn(e)+'"]';var d=s;switch(t){case"style":d=Ki(e);break;case"script":d=Ji(e)}Sn.has(d)||(e=x({rel:"preload",href:t==="image"&&l&&l.imageSrcSet?void 0:e,as:t},l),Sn.set(d,e),a.querySelector(s)!==null||t==="style"&&a.querySelector(Qa(d))||t==="script"&&a.querySelector(Xa(d))||(t=a.createElement("link"),Nt(t,"link",e),Ke(t),a.head.appendChild(t)))}}function kx(e,t){rl.m(e,t);var l=Fi;if(l&&e){var a=t&&typeof t.as=="string"?t.as:"script",s='link[rel="modulepreload"][as="'+hn(a)+'"][href="'+hn(e)+'"]',d=s;switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":d=Ji(e)}if(!Sn.has(d)&&(e=x({rel:"modulepreload",href:e},t),Sn.set(d,e),l.querySelector(s)===null)){switch(a){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(l.querySelector(Xa(d)))return}a=l.createElement("link"),Nt(a,"link",e),Ke(a),l.head.appendChild(a)}}}function Ax(e,t,l){rl.S(e,t,l);var a=Fi;if(a&&e){var s=pt(a).hoistableStyles,d=Ki(e);t=t||"default";var v=s.get(d);if(!v){var _={loading:0,preload:null};if(v=a.querySelector(Qa(d)))_.loading=5;else{e=x({rel:"stylesheet",href:e,"data-precedence":t},l),(l=Sn.get(d))&&Jo(e,l);var E=v=a.createElement("link");Ke(E),Nt(E,"link",e),E._p=new Promise(function(O,V){E.onload=O,E.onerror=V}),E.addEventListener("load",function(){_.loading|=1}),E.addEventListener("error",function(){_.loading|=2}),_.loading|=4,yu(v,t,a)}v={type:"stylesheet",instance:v,count:1,state:_},s.set(d,v)}}}function wx(e,t){rl.X(e,t);var l=Fi;if(l&&e){var a=pt(l).hoistableScripts,s=Ji(e),d=a.get(s);d||(d=l.querySelector(Xa(s)),d||(e=x({src:e,async:!0},t),(t=Sn.get(s))&&$o(e,t),d=l.createElement("script"),Ke(d),Nt(d,"link",e),l.head.appendChild(d)),d={type:"script",instance:d,count:1,state:null},a.set(s,d))}}function Ex(e,t){rl.M(e,t);var l=Fi;if(l&&e){var a=pt(l).hoistableScripts,s=Ji(e),d=a.get(s);d||(d=l.querySelector(Xa(s)),d||(e=x({src:e,async:!0,type:"module"},t),(t=Sn.get(s))&&$o(e,t),d=l.createElement("script"),Ke(d),Nt(d,"link",e),l.head.appendChild(d)),d={type:"script",instance:d,count:1,state:null},a.set(s,d))}}function Rm(e,t,l,a){var s=(s=he.current)?gu(s):null;if(!s)throw Error(u(446));switch(e){case"meta":case"title":return null;case"style":return typeof l.precedence=="string"&&typeof l.href=="string"?(t=Ki(l.href),l=pt(s).hoistableStyles,a=l.get(t),a||(a={type:"style",instance:null,count:0,state:null},l.set(t,a)),a):{type:"void",instance:null,count:0,state:null};case"link":if(l.rel==="stylesheet"&&typeof l.href=="string"&&typeof l.precedence=="string"){e=Ki(l.href);var d=pt(s).hoistableStyles,v=d.get(e);if(v||(s=s.ownerDocument||s,v={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},d.set(e,v),(d=s.querySelector(Qa(e)))&&!d._p&&(v.instance=d,v.state.loading=5),Sn.has(e)||(l={rel:"preload",as:"style",href:l.href,crossOrigin:l.crossOrigin,integrity:l.integrity,media:l.media,hrefLang:l.hrefLang,referrerPolicy:l.referrerPolicy},Sn.set(e,l),d||jx(s,e,l,v.state))),t&&a===null)throw Error(u(528,""));return v}if(t&&a!==null)throw Error(u(529,""));return null;case"script":return t=l.async,l=l.src,typeof l=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=Ji(l),l=pt(s).hoistableScripts,a=l.get(t),a||(a={type:"script",instance:null,count:0,state:null},l.set(t,a)),a):{type:"void",instance:null,count:0,state:null};default:throw Error(u(444,e))}}function Ki(e){return'href="'+hn(e)+'"'}function Qa(e){return'link[rel="stylesheet"]['+e+"]"}function Lm(e){return x({},e,{"data-precedence":e.precedence,precedence:null})}function jx(e,t,l,a){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?a.loading=1:(t=e.createElement("link"),a.preload=t,t.addEventListener("load",function(){return a.loading|=1}),t.addEventListener("error",function(){return a.loading|=2}),Nt(t,"link",l),Ke(t),e.head.appendChild(t))}function Ji(e){return'[src="'+hn(e)+'"]'}function Xa(e){return"script[async]"+e}function Bm(e,t,l){if(t.count++,t.instance===null)switch(t.type){case"style":var a=e.querySelector('style[data-href~="'+hn(l.href)+'"]');if(a)return t.instance=a,Ke(a),a;var s=x({},l,{"data-href":l.href,"data-precedence":l.precedence,href:null,precedence:null});return a=(e.ownerDocument||e).createElement("style"),Ke(a),Nt(a,"style",s),yu(a,l.precedence,e),t.instance=a;case"stylesheet":s=Ki(l.href);var d=e.querySelector(Qa(s));if(d)return t.state.loading|=4,t.instance=d,Ke(d),d;a=Lm(l),(s=Sn.get(s))&&Jo(a,s),d=(e.ownerDocument||e).createElement("link"),Ke(d);var v=d;return v._p=new Promise(function(_,E){v.onload=_,v.onerror=E}),Nt(d,"link",a),t.state.loading|=4,yu(d,l.precedence,e),t.instance=d;case"script":return d=Ji(l.src),(s=e.querySelector(Xa(d)))?(t.instance=s,Ke(s),s):(a=l,(s=Sn.get(d))&&(a=x({},l),$o(a,s)),e=e.ownerDocument||e,s=e.createElement("script"),Ke(s),Nt(s,"link",a),e.head.appendChild(s),t.instance=s);case"void":return null;default:throw Error(u(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(a=t.instance,t.state.loading|=4,yu(a,l.precedence,e));return t.instance}function yu(e,t,l){for(var a=l.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),s=a.length?a[a.length-1]:null,d=s,v=0;v title"):null)}function Tx(e,t,l){if(l===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;switch(t.rel){case"stylesheet":return e=t.disabled,typeof t.precedence=="string"&&e==null;default:return!0}case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function qm(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function Cx(e,t,l,a){if(l.type==="stylesheet"&&(typeof a.media!="string"||matchMedia(a.media).matches!==!1)&&(l.state.loading&4)===0){if(l.instance===null){var s=Ki(a.href),d=t.querySelector(Qa(s));if(d){t=d._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=vu.bind(e),t.then(e,e)),l.state.loading|=4,l.instance=d,Ke(d);return}d=t.ownerDocument||t,a=Lm(a),(s=Sn.get(s))&&Jo(a,s),d=d.createElement("link"),Ke(d);var v=d;v._p=new Promise(function(_,E){v.onload=_,v.onerror=E}),Nt(d,"link",a),l.instance=d}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(l,t),(t=l.state.preload)&&(l.state.loading&3)===0&&(e.count++,l=vu.bind(e),t.addEventListener("load",l),t.addEventListener("error",l))}}var Io=0;function zx(e,t){return e.stylesheets&&e.count===0&&Su(e,e.stylesheets),0Io?50:800)+t);return e.unsuspend=l,function(){e.unsuspend=null,clearTimeout(a),clearTimeout(s)}}:null}function vu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Su(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var bu=null;function Su(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,bu=new Map,t.forEach(Nx,e),bu=null,vu.call(e))}function Nx(e,t){if(!(t.state.loading&4)){var l=bu.get(e);if(l)var a=l.get(null);else{l=new Map,bu.set(e,l);for(var s=e.querySelectorAll("link[data-precedence],style[data-precedence]"),d=0;d"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(i){console.error(i)}}return n(),rc.exports=Fx(),rc.exports}var Jx=Kx();function $x(n,i){const r={};return(n[n.length-1]===""?[...n,""]:n).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const Ix=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Px=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Wx={};function cp(n,i){return(Wx.jsx?Px:Ix).test(n)}const e0=/[ \t\n\f\r]/g;function t0(n){return typeof n=="object"?n.type==="text"?fp(n.value):!1:fp(n)}function fp(n){return n.replace(e0,"")===""}class sr{constructor(i,r,u){this.normal=r,this.property=i,u&&(this.space=u)}}sr.prototype.normal={};sr.prototype.property={};sr.prototype.space=void 0;function og(n,i){const r={},u={};for(const o of n)Object.assign(r,o.property),Object.assign(u,o.normal);return new sr(r,u,i)}function Cc(n){return n.toLowerCase()}class Pt{constructor(i,r){this.attribute=r,this.property=i}}Pt.prototype.attribute="";Pt.prototype.booleanish=!1;Pt.prototype.boolean=!1;Pt.prototype.commaOrSpaceSeparated=!1;Pt.prototype.commaSeparated=!1;Pt.prototype.defined=!1;Pt.prototype.mustUseProperty=!1;Pt.prototype.number=!1;Pt.prototype.overloadedBoolean=!1;Pt.prototype.property="";Pt.prototype.spaceSeparated=!1;Pt.prototype.space=void 0;let n0=0;const _e=ui(),bt=ui(),zc=ui(),ee=ui(),et=ui(),ii=ui(),on=ui();function ui(){return 2**++n0}const Nc=Object.freeze(Object.defineProperty({__proto__:null,boolean:_e,booleanish:bt,commaOrSpaceSeparated:on,commaSeparated:ii,number:ee,overloadedBoolean:zc,spaceSeparated:et},Symbol.toStringTag,{value:"Module"})),cc=Object.keys(Nc);class Vc extends Pt{constructor(i,r,u,o){let c=-1;if(super(i,r),dp(this,"space",o),typeof u=="number")for(;++c4&&r.slice(0,4)==="data"&&u0.test(i)){if(i.charAt(4)==="-"){const c=i.slice(5).replace(hp,c0);u="data"+c.charAt(0).toUpperCase()+c.slice(1)}else{const c=i.slice(4);if(!hp.test(c)){let f=c.replace(r0,o0);f.charAt(0)!=="-"&&(f="-"+f),i="data"+f}}o=Vc}return new o(u,i)}function o0(n){return"-"+n.toLowerCase()}function c0(n){return n.charAt(1).toUpperCase()}const f0=og([cg,l0,hg,mg,pg],"html"),Qc=og([cg,i0,hg,mg,pg],"svg");function d0(n){return n.join(" ").trim()}var Ii={},fc,mp;function h0(){if(mp)return fc;mp=1;var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,i=/\n/g,r=/^\s*/,u=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,c=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,f=/^[;\s]*/,h=/^\s+|\s+$/g,g=` +`,p="/",y="*",x="",b="comment",S="declaration";function w(q,N){if(typeof q!="string")throw new TypeError("First argument must be a string");if(!q)return[];N=N||{};var K=1,Y=1;function se(re){var I=re.match(i);I&&(K+=I.length);var M=re.lastIndexOf(g);Y=~M?re.length-M:Y+re.length}function ae(){var re={line:K,column:Y};return function(I){return I.position=new U(re),ye(),I}}function U(re){this.start=re,this.end={line:K,column:Y},this.source=N.source}U.prototype.content=q;function ne(re){var I=new Error(N.source+":"+K+":"+Y+": "+re);if(I.reason=re,I.filename=N.source,I.line=K,I.column=Y,I.source=q,!N.silent)throw I}function ue(re){var I=re.exec(q);if(I){var M=I[0];return se(M),q=q.slice(M.length),I}}function ye(){ue(r)}function R(re){var I;for(re=re||[];I=Q();)I!==!1&&re.push(I);return re}function Q(){var re=ae();if(!(p!=q.charAt(0)||y!=q.charAt(1))){for(var I=2;x!=q.charAt(I)&&(y!=q.charAt(I)||p!=q.charAt(I+1));)++I;if(I+=2,x===q.charAt(I-1))return ne("End of comment missing");var M=q.slice(2,I-2);return Y+=2,se(M),q=q.slice(I),Y+=2,re({type:b,comment:M})}}function W(){var re=ae(),I=ue(u);if(I){if(Q(),!ue(o))return ne("property missing ':'");var M=ue(c),J=re({type:S,property:j(I[0].replace(n,x)),value:M?j(M[0].replace(n,x)):x});return ue(f),J}}function de(){var re=[];R(re);for(var I;I=W();)I!==!1&&(re.push(I),R(re));return re}return ye(),de()}function j(q){return q?q.replace(h,x):x}return fc=w,fc}var pp;function m0(){if(pp)return Ii;pp=1;var n=Ii&&Ii.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.default=r;const i=n(h0());function r(u,o){let c=null;if(!u||typeof u!="string")return c;const f=(0,i.default)(u),h=typeof o=="function";return f.forEach(g=>{if(g.type!=="declaration")return;const{property:p,value:y}=g;h?o(p,y,g):y&&(c=c||{},c[p]=y)}),c}return Ii}var Pa={},gp;function p0(){if(gp)return Pa;gp=1,Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.camelCase=void 0;var n=/^--[a-zA-Z0-9_-]+$/,i=/-([a-z])/g,r=/^[^-]+$/,u=/^-(webkit|moz|ms|o|khtml)-/,o=/^-(ms)-/,c=function(p){return!p||r.test(p)||n.test(p)},f=function(p,y){return y.toUpperCase()},h=function(p,y){return"".concat(y,"-")},g=function(p,y){return y===void 0&&(y={}),c(p)?p:(p=p.toLowerCase(),y.reactCompat?p=p.replace(o,h):p=p.replace(u,h),p.replace(i,f))};return Pa.camelCase=g,Pa}var Wa,yp;function g0(){if(yp)return Wa;yp=1;var n=Wa&&Wa.__importDefault||function(o){return o&&o.__esModule?o:{default:o}},i=n(m0()),r=p0();function u(o,c){var f={};return!o||typeof o!="string"||(0,i.default)(o,function(h,g){h&&g&&(f[(0,r.camelCase)(h,c)]=g)}),f}return u.default=u,Wa=u,Wa}var y0=g0();const x0=sg(y0),gg=yg("end"),Xc=yg("start");function yg(n){return i;function i(r){const u=r&&r.position&&r.position[n]||{};if(typeof u.line=="number"&&u.line>0&&typeof u.column=="number"&&u.column>0)return{line:u.line,column:u.column,offset:typeof u.offset=="number"&&u.offset>-1?u.offset:void 0}}}function v0(n){const i=Xc(n),r=gg(n);if(i&&r)return{start:i,end:r}}function lr(n){return!n||typeof n!="object"?"":"position"in n||"type"in n?xp(n.position):"start"in n||"end"in n?xp(n):"line"in n||"column"in n?Mc(n):""}function Mc(n){return vp(n&&n.line)+":"+vp(n&&n.column)}function xp(n){return Mc(n&&n.start)+"-"+Mc(n&&n.end)}function vp(n){return n&&typeof n=="number"?n:1}class Bt extends Error{constructor(i,r,u){super(),typeof r=="string"&&(u=r,r=void 0);let o="",c={},f=!1;if(r&&("line"in r&&"column"in r?c={place:r}:"start"in r&&"end"in r?c={place:r}:"type"in r?c={ancestors:[r],place:r.position}:c={...r}),typeof i=="string"?o=i:!c.cause&&i&&(f=!0,o=i.message,c.cause=i),!c.ruleId&&!c.source&&typeof u=="string"){const g=u.indexOf(":");g===-1?c.ruleId=u:(c.source=u.slice(0,g),c.ruleId=u.slice(g+1))}if(!c.place&&c.ancestors&&c.ancestors){const g=c.ancestors[c.ancestors.length-1];g&&(c.place=g.position)}const h=c.place&&"start"in c.place?c.place.start:c.place;this.ancestors=c.ancestors||void 0,this.cause=c.cause||void 0,this.column=h?h.column:void 0,this.fatal=void 0,this.file="",this.message=o,this.line=h?h.line:void 0,this.name=lr(c.place)||"1:1",this.place=c.place||void 0,this.reason=this.message,this.ruleId=c.ruleId||void 0,this.source=c.source||void 0,this.stack=f&&c.cause&&typeof c.cause.stack=="string"?c.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Bt.prototype.file="";Bt.prototype.name="";Bt.prototype.reason="";Bt.prototype.message="";Bt.prototype.stack="";Bt.prototype.column=void 0;Bt.prototype.line=void 0;Bt.prototype.ancestors=void 0;Bt.prototype.cause=void 0;Bt.prototype.fatal=void 0;Bt.prototype.place=void 0;Bt.prototype.ruleId=void 0;Bt.prototype.source=void 0;const Zc={}.hasOwnProperty,b0=new Map,S0=/[A-Z]/g,_0=new Set(["table","tbody","thead","tfoot","tr"]),k0=new Set(["td","th"]),xg="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function A0(n,i){if(!i||i.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=i.filePath||void 0;let u;if(i.development){if(typeof i.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");u=M0(r,i.jsxDEV)}else{if(typeof i.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof i.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");u=N0(r,i.jsx,i.jsxs)}const o={Fragment:i.Fragment,ancestors:[],components:i.components||{},create:u,elementAttributeNameCase:i.elementAttributeNameCase||"react",evaluater:i.createEvaluater?i.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:i.ignoreInvalidStyle||!1,passKeys:i.passKeys!==!1,passNode:i.passNode||!1,schema:i.space==="svg"?Qc:f0,stylePropertyNameCase:i.stylePropertyNameCase||"dom",tableCellAlignToStyle:i.tableCellAlignToStyle!==!1},c=vg(o,n,void 0);return c&&typeof c!="string"?c:o.create(n,o.Fragment,{children:c||void 0},void 0)}function vg(n,i,r){if(i.type==="element")return w0(n,i,r);if(i.type==="mdxFlowExpression"||i.type==="mdxTextExpression")return E0(n,i);if(i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement")return T0(n,i,r);if(i.type==="mdxjsEsm")return j0(n,i);if(i.type==="root")return C0(n,i,r);if(i.type==="text")return z0(n,i)}function w0(n,i,r){const u=n.schema;let o=u;i.tagName.toLowerCase()==="svg"&&u.space==="html"&&(o=Qc,n.schema=o),n.ancestors.push(i);const c=Sg(n,i.tagName,!1),f=D0(n,i);let h=Kc(n,i);return _0.has(i.tagName)&&(h=h.filter(function(g){return typeof g=="string"?!t0(g):!0})),bg(n,f,c,i),Fc(f,h),n.ancestors.pop(),n.schema=u,n.create(i,c,f,r)}function E0(n,i){if(i.data&&i.data.estree&&n.evaluater){const u=i.data.estree.body[0];return u.type,n.evaluater.evaluateExpression(u.expression)}rr(n,i.position)}function j0(n,i){if(i.data&&i.data.estree&&n.evaluater)return n.evaluater.evaluateProgram(i.data.estree);rr(n,i.position)}function T0(n,i,r){const u=n.schema;let o=u;i.name==="svg"&&u.space==="html"&&(o=Qc,n.schema=o),n.ancestors.push(i);const c=i.name===null?n.Fragment:Sg(n,i.name,!0),f=O0(n,i),h=Kc(n,i);return bg(n,f,c,i),Fc(f,h),n.ancestors.pop(),n.schema=u,n.create(i,c,f,r)}function C0(n,i,r){const u={};return Fc(u,Kc(n,i)),n.create(i,n.Fragment,u,r)}function z0(n,i){return i.value}function bg(n,i,r,u){typeof r!="string"&&r!==n.Fragment&&n.passNode&&(i.node=u)}function Fc(n,i){if(i.length>0){const r=i.length>1?i:i[0];r&&(n.children=r)}}function N0(n,i,r){return u;function u(o,c,f,h){const p=Array.isArray(f.children)?r:i;return h?p(c,f,h):p(c,f)}}function M0(n,i){return r;function r(u,o,c,f){const h=Array.isArray(c.children),g=Xc(u);return i(o,c,f,h,{columnNumber:g?g.column-1:void 0,fileName:n,lineNumber:g?g.line:void 0},void 0)}}function D0(n,i){const r={};let u,o;for(o in i.properties)if(o!=="children"&&Zc.call(i.properties,o)){const c=R0(n,o,i.properties[o]);if(c){const[f,h]=c;n.tableCellAlignToStyle&&f==="align"&&typeof h=="string"&&k0.has(i.tagName)?u=h:r[f]=h}}if(u){const c=r.style||(r.style={});c[n.stylePropertyNameCase==="css"?"text-align":"textAlign"]=u}return r}function O0(n,i){const r={};for(const u of i.attributes)if(u.type==="mdxJsxExpressionAttribute")if(u.data&&u.data.estree&&n.evaluater){const c=u.data.estree.body[0];c.type;const f=c.expression;f.type;const h=f.properties[0];h.type,Object.assign(r,n.evaluater.evaluateExpression(h.argument))}else rr(n,i.position);else{const o=u.name;let c;if(u.value&&typeof u.value=="object")if(u.value.data&&u.value.data.estree&&n.evaluater){const h=u.value.data.estree.body[0];h.type,c=n.evaluater.evaluateExpression(h.expression)}else rr(n,i.position);else c=u.value===null?!0:u.value;r[o]=c}return r}function Kc(n,i){const r=[];let u=-1;const o=n.passKeys?new Map:b0;for(;++uo?0:o+i:i=i>o?o:i,r=r>0?r:0,u.length<1e4)f=Array.from(u),f.unshift(i,r),n.splice(...f);else for(r&&n.splice(i,r);c0?(cn(n,n.length,0,i),n):i}const _p={}.hasOwnProperty;function kg(n){const i={};let r=-1;for(;++r13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function Tn(n){return n.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Gt=Ll(/[A-Za-z]/),Lt=Ll(/[\dA-Za-z]/),Q0=Ll(/[#-'*+\--9=?A-Z^-~]/);function Ru(n){return n!==null&&(n<32||n===127)}const Dc=Ll(/\d/),X0=Ll(/[\dA-Fa-f]/),Z0=Ll(/[!-/:-@[-`{-~]/);function ve(n){return n!==null&&n<-2}function tt(n){return n!==null&&(n<0||n===32)}function De(n){return n===-2||n===-1||n===32}const qu=Ll(new RegExp("\\p{P}|\\p{S}","u")),ri=Ll(/\s/);function Ll(n){return i;function i(r){return r!==null&&r>-1&&n.test(String.fromCharCode(r))}}function la(n){const i=[];let r=-1,u=0,o=0;for(;++r55295&&c<57344){const h=n.charCodeAt(r+1);c<56320&&h>56319&&h<57344?(f=String.fromCharCode(c,h),o=1):f="�"}else f=String.fromCharCode(c);f&&(i.push(n.slice(u,r),encodeURIComponent(f)),u=r+o+1,f=""),o&&(r+=o,o=0)}return i.join("")+n.slice(u)}function He(n,i,r,u){const o=u?u-1:Number.POSITIVE_INFINITY;let c=0;return f;function f(g){return De(g)?(n.enter(r),h(g)):i(g)}function h(g){return De(g)&&c++f))return;const ne=i.events.length;let ue=ne,ye,R;for(;ue--;)if(i.events[ue][0]==="exit"&&i.events[ue][1].type==="chunkFlow"){if(ye){R=i.events[ue][1].end;break}ye=!0}for(N(u),U=ne;UY;){const ae=r[se];i.containerState=ae[1],ae[0].exit.call(i,n)}r.length=Y}function K(){o.write([null]),c=void 0,o=void 0,i.containerState._closeFlow=void 0}}function I0(n,i,r){return He(n,n.attempt(this.parser.constructs.document,i,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ea(n){if(n===null||tt(n)||ri(n))return 1;if(qu(n))return 2}function Gu(n,i,r){const u=[];let o=-1;for(;++o1&&n[r][1].end.offset-n[r][1].start.offset>1?2:1;const x={...n[u][1].end},b={...n[r][1].start};Ap(x,-g),Ap(b,g),f={type:g>1?"strongSequence":"emphasisSequence",start:x,end:{...n[u][1].end}},h={type:g>1?"strongSequence":"emphasisSequence",start:{...n[r][1].start},end:b},c={type:g>1?"strongText":"emphasisText",start:{...n[u][1].end},end:{...n[r][1].start}},o={type:g>1?"strong":"emphasis",start:{...f.start},end:{...h.end}},n[u][1].end={...f.start},n[r][1].start={...h.end},p=[],n[u][1].end.offset-n[u][1].start.offset&&(p=kn(p,[["enter",n[u][1],i],["exit",n[u][1],i]])),p=kn(p,[["enter",o,i],["enter",f,i],["exit",f,i],["enter",c,i]]),p=kn(p,Gu(i.parser.constructs.insideSpan.null,n.slice(u+1,r),i)),p=kn(p,[["exit",c,i],["enter",h,i],["exit",h,i],["exit",o,i]]),n[r][1].end.offset-n[r][1].start.offset?(y=2,p=kn(p,[["enter",n[r][1],i],["exit",n[r][1],i]])):y=0,cn(n,u-1,r-u+3,p),r=u+p.length-y-2;break}}for(r=-1;++r0&&De(U)?He(n,K,"linePrefix",c+1)(U):K(U)}function K(U){return U===null||ve(U)?n.check(wp,j,se)(U):(n.enter("codeFlowValue"),Y(U))}function Y(U){return U===null||ve(U)?(n.exit("codeFlowValue"),K(U)):(n.consume(U),Y)}function se(U){return n.exit("codeFenced"),i(U)}function ae(U,ne,ue){let ye=0;return R;function R(I){return U.enter("lineEnding"),U.consume(I),U.exit("lineEnding"),Q}function Q(I){return U.enter("codeFencedFence"),De(I)?He(U,W,"linePrefix",u.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):W(I)}function W(I){return I===h?(U.enter("codeFencedFenceSequence"),de(I)):ue(I)}function de(I){return I===h?(ye++,U.consume(I),de):ye>=f?(U.exit("codeFencedFenceSequence"),De(I)?He(U,re,"whitespace")(I):re(I)):ue(I)}function re(I){return I===null||ve(I)?(U.exit("codeFencedFence"),ne(I)):ue(I)}}}function ov(n,i,r){const u=this;return o;function o(f){return f===null?r(f):(n.enter("lineEnding"),n.consume(f),n.exit("lineEnding"),c)}function c(f){return u.parser.lazy[u.now().line]?r(f):i(f)}}const hc={name:"codeIndented",tokenize:fv},cv={partial:!0,tokenize:dv};function fv(n,i,r){const u=this;return o;function o(p){return n.enter("codeIndented"),He(n,c,"linePrefix",5)(p)}function c(p){const y=u.events[u.events.length-1];return y&&y[1].type==="linePrefix"&&y[2].sliceSerialize(y[1],!0).length>=4?f(p):r(p)}function f(p){return p===null?g(p):ve(p)?n.attempt(cv,f,g)(p):(n.enter("codeFlowValue"),h(p))}function h(p){return p===null||ve(p)?(n.exit("codeFlowValue"),f(p)):(n.consume(p),h)}function g(p){return n.exit("codeIndented"),i(p)}}function dv(n,i,r){const u=this;return o;function o(f){return u.parser.lazy[u.now().line]?r(f):ve(f)?(n.enter("lineEnding"),n.consume(f),n.exit("lineEnding"),o):He(n,c,"linePrefix",5)(f)}function c(f){const h=u.events[u.events.length-1];return h&&h[1].type==="linePrefix"&&h[2].sliceSerialize(h[1],!0).length>=4?i(f):ve(f)?o(f):r(f)}}const hv={name:"codeText",previous:pv,resolve:mv,tokenize:gv};function mv(n){let i=n.length-4,r=3,u,o;if((n[r][1].type==="lineEnding"||n[r][1].type==="space")&&(n[i][1].type==="lineEnding"||n[i][1].type==="space")){for(u=r;++u=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+i+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ithis.left.length?this.right.slice(this.right.length-u+this.left.length,this.right.length-i+this.left.length).reverse():this.left.slice(i).concat(this.right.slice(this.right.length-u+this.left.length).reverse())}splice(i,r,u){const o=r||0;this.setCursor(Math.trunc(i));const c=this.right.splice(this.right.length-o,Number.POSITIVE_INFINITY);return u&&er(this.left,u),c.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(i){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(i)}pushMany(i){this.setCursor(Number.POSITIVE_INFINITY),er(this.left,i)}unshift(i){this.setCursor(0),this.right.push(i)}unshiftMany(i){this.setCursor(0),er(this.right,i.reverse())}setCursor(i){if(!(i===this.left.length||i>this.left.length&&this.right.length===0||i<0&&this.left.length===0))if(i=4?i(f):n.interrupt(u.parser.constructs.flow,r,i)(f)}}function Cg(n,i,r,u,o,c,f,h,g){const p=g||Number.POSITIVE_INFINITY;let y=0;return x;function x(N){return N===60?(n.enter(u),n.enter(o),n.enter(c),n.consume(N),n.exit(c),b):N===null||N===32||N===41||Ru(N)?r(N):(n.enter(u),n.enter(f),n.enter(h),n.enter("chunkString",{contentType:"string"}),j(N))}function b(N){return N===62?(n.enter(c),n.consume(N),n.exit(c),n.exit(o),n.exit(u),i):(n.enter(h),n.enter("chunkString",{contentType:"string"}),S(N))}function S(N){return N===62?(n.exit("chunkString"),n.exit(h),b(N)):N===null||N===60||ve(N)?r(N):(n.consume(N),N===92?w:S)}function w(N){return N===60||N===62||N===92?(n.consume(N),S):S(N)}function j(N){return!y&&(N===null||N===41||tt(N))?(n.exit("chunkString"),n.exit(h),n.exit(f),n.exit(u),i(N)):y999||S===null||S===91||S===93&&!g||S===94&&!h&&"_hiddenFootnoteSupport"in f.parser.constructs?r(S):S===93?(n.exit(c),n.enter(o),n.consume(S),n.exit(o),n.exit(u),i):ve(S)?(n.enter("lineEnding"),n.consume(S),n.exit("lineEnding"),y):(n.enter("chunkString",{contentType:"string"}),x(S))}function x(S){return S===null||S===91||S===93||ve(S)||h++>999?(n.exit("chunkString"),y(S)):(n.consume(S),g||(g=!De(S)),S===92?b:x)}function b(S){return S===91||S===92||S===93?(n.consume(S),h++,x):x(S)}}function Ng(n,i,r,u,o,c){let f;return h;function h(b){return b===34||b===39||b===40?(n.enter(u),n.enter(o),n.consume(b),n.exit(o),f=b===40?41:b,g):r(b)}function g(b){return b===f?(n.enter(o),n.consume(b),n.exit(o),n.exit(u),i):(n.enter(c),p(b))}function p(b){return b===f?(n.exit(c),g(f)):b===null?r(b):ve(b)?(n.enter("lineEnding"),n.consume(b),n.exit("lineEnding"),He(n,p,"linePrefix")):(n.enter("chunkString",{contentType:"string"}),y(b))}function y(b){return b===f||b===null||ve(b)?(n.exit("chunkString"),p(b)):(n.consume(b),b===92?x:y)}function x(b){return b===f||b===92?(n.consume(b),y):y(b)}}function ir(n,i){let r;return u;function u(o){return ve(o)?(n.enter("lineEnding"),n.consume(o),n.exit("lineEnding"),r=!0,u):De(o)?He(n,u,r?"linePrefix":"lineSuffix")(o):i(o)}}const Av={name:"definition",tokenize:Ev},wv={partial:!0,tokenize:jv};function Ev(n,i,r){const u=this;let o;return c;function c(S){return n.enter("definition"),f(S)}function f(S){return zg.call(u,n,h,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(S)}function h(S){return o=Tn(u.sliceSerialize(u.events[u.events.length-1][1]).slice(1,-1)),S===58?(n.enter("definitionMarker"),n.consume(S),n.exit("definitionMarker"),g):r(S)}function g(S){return tt(S)?ir(n,p)(S):p(S)}function p(S){return Cg(n,y,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(S)}function y(S){return n.attempt(wv,x,x)(S)}function x(S){return De(S)?He(n,b,"whitespace")(S):b(S)}function b(S){return S===null||ve(S)?(n.exit("definition"),u.parser.defined.push(o),i(S)):r(S)}}function jv(n,i,r){return u;function u(h){return tt(h)?ir(n,o)(h):r(h)}function o(h){return Ng(n,c,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(h)}function c(h){return De(h)?He(n,f,"whitespace")(h):f(h)}function f(h){return h===null||ve(h)?i(h):r(h)}}const Tv={name:"hardBreakEscape",tokenize:Cv};function Cv(n,i,r){return u;function u(c){return n.enter("hardBreakEscape"),n.consume(c),o}function o(c){return ve(c)?(n.exit("hardBreakEscape"),i(c)):r(c)}}const zv={name:"headingAtx",resolve:Nv,tokenize:Mv};function Nv(n,i){let r=n.length-2,u=3,o,c;return n[u][1].type==="whitespace"&&(u+=2),r-2>u&&n[r][1].type==="whitespace"&&(r-=2),n[r][1].type==="atxHeadingSequence"&&(u===r-1||r-4>u&&n[r-2][1].type==="whitespace")&&(r-=u+1===r?2:4),r>u&&(o={type:"atxHeadingText",start:n[u][1].start,end:n[r][1].end},c={type:"chunkText",start:n[u][1].start,end:n[r][1].end,contentType:"text"},cn(n,u,r-u+1,[["enter",o,i],["enter",c,i],["exit",c,i],["exit",o,i]])),n}function Mv(n,i,r){let u=0;return o;function o(y){return n.enter("atxHeading"),c(y)}function c(y){return n.enter("atxHeadingSequence"),f(y)}function f(y){return y===35&&u++<6?(n.consume(y),f):y===null||tt(y)?(n.exit("atxHeadingSequence"),h(y)):r(y)}function h(y){return y===35?(n.enter("atxHeadingSequence"),g(y)):y===null||ve(y)?(n.exit("atxHeading"),i(y)):De(y)?He(n,h,"whitespace")(y):(n.enter("atxHeadingText"),p(y))}function g(y){return y===35?(n.consume(y),g):(n.exit("atxHeadingSequence"),h(y))}function p(y){return y===null||y===35||tt(y)?(n.exit("atxHeadingText"),h(y)):(n.consume(y),p)}}const Dv=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],jp=["pre","script","style","textarea"],Ov={concrete:!0,name:"htmlFlow",resolveTo:Bv,tokenize:Uv},Rv={partial:!0,tokenize:qv},Lv={partial:!0,tokenize:Hv};function Bv(n){let i=n.length;for(;i--&&!(n[i][0]==="enter"&&n[i][1].type==="htmlFlow"););return i>1&&n[i-2][1].type==="linePrefix"&&(n[i][1].start=n[i-2][1].start,n[i+1][1].start=n[i-2][1].start,n.splice(i-2,2)),n}function Uv(n,i,r){const u=this;let o,c,f,h,g;return p;function p(k){return y(k)}function y(k){return n.enter("htmlFlow"),n.enter("htmlFlowData"),n.consume(k),x}function x(k){return k===33?(n.consume(k),b):k===47?(n.consume(k),c=!0,j):k===63?(n.consume(k),o=3,u.interrupt?i:A):Gt(k)?(n.consume(k),f=String.fromCharCode(k),q):r(k)}function b(k){return k===45?(n.consume(k),o=2,S):k===91?(n.consume(k),o=5,h=0,w):Gt(k)?(n.consume(k),o=4,u.interrupt?i:A):r(k)}function S(k){return k===45?(n.consume(k),u.interrupt?i:A):r(k)}function w(k){const le="CDATA[";return k===le.charCodeAt(h++)?(n.consume(k),h===le.length?u.interrupt?i:W:w):r(k)}function j(k){return Gt(k)?(n.consume(k),f=String.fromCharCode(k),q):r(k)}function q(k){if(k===null||k===47||k===62||tt(k)){const le=k===47,pe=f.toLowerCase();return!le&&!c&&jp.includes(pe)?(o=1,u.interrupt?i(k):W(k)):Dv.includes(f.toLowerCase())?(o=6,le?(n.consume(k),N):u.interrupt?i(k):W(k)):(o=7,u.interrupt&&!u.parser.lazy[u.now().line]?r(k):c?K(k):Y(k))}return k===45||Lt(k)?(n.consume(k),f+=String.fromCharCode(k),q):r(k)}function N(k){return k===62?(n.consume(k),u.interrupt?i:W):r(k)}function K(k){return De(k)?(n.consume(k),K):R(k)}function Y(k){return k===47?(n.consume(k),R):k===58||k===95||Gt(k)?(n.consume(k),se):De(k)?(n.consume(k),Y):R(k)}function se(k){return k===45||k===46||k===58||k===95||Lt(k)?(n.consume(k),se):ae(k)}function ae(k){return k===61?(n.consume(k),U):De(k)?(n.consume(k),ae):Y(k)}function U(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(n.consume(k),g=k,ne):De(k)?(n.consume(k),U):ue(k)}function ne(k){return k===g?(n.consume(k),g=null,ye):k===null||ve(k)?r(k):(n.consume(k),ne)}function ue(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||tt(k)?ae(k):(n.consume(k),ue)}function ye(k){return k===47||k===62||De(k)?Y(k):r(k)}function R(k){return k===62?(n.consume(k),Q):r(k)}function Q(k){return k===null||ve(k)?W(k):De(k)?(n.consume(k),Q):r(k)}function W(k){return k===45&&o===2?(n.consume(k),M):k===60&&o===1?(n.consume(k),J):k===62&&o===4?(n.consume(k),T):k===63&&o===3?(n.consume(k),A):k===93&&o===5?(n.consume(k),xe):ve(k)&&(o===6||o===7)?(n.exit("htmlFlowData"),n.check(Rv,G,de)(k)):k===null||ve(k)?(n.exit("htmlFlowData"),de(k)):(n.consume(k),W)}function de(k){return n.check(Lv,re,G)(k)}function re(k){return n.enter("lineEnding"),n.consume(k),n.exit("lineEnding"),I}function I(k){return k===null||ve(k)?de(k):(n.enter("htmlFlowData"),W(k))}function M(k){return k===45?(n.consume(k),A):W(k)}function J(k){return k===47?(n.consume(k),f="",P):W(k)}function P(k){if(k===62){const le=f.toLowerCase();return jp.includes(le)?(n.consume(k),T):W(k)}return Gt(k)&&f.length<8?(n.consume(k),f+=String.fromCharCode(k),P):W(k)}function xe(k){return k===93?(n.consume(k),A):W(k)}function A(k){return k===62?(n.consume(k),T):k===45&&o===2?(n.consume(k),A):W(k)}function T(k){return k===null||ve(k)?(n.exit("htmlFlowData"),G(k)):(n.consume(k),T)}function G(k){return n.exit("htmlFlow"),i(k)}}function Hv(n,i,r){const u=this;return o;function o(f){return ve(f)?(n.enter("lineEnding"),n.consume(f),n.exit("lineEnding"),c):r(f)}function c(f){return u.parser.lazy[u.now().line]?r(f):i(f)}}function qv(n,i,r){return u;function u(o){return n.enter("lineEnding"),n.consume(o),n.exit("lineEnding"),n.attempt(or,i,r)}}const Gv={name:"htmlText",tokenize:Yv};function Yv(n,i,r){const u=this;let o,c,f;return h;function h(A){return n.enter("htmlText"),n.enter("htmlTextData"),n.consume(A),g}function g(A){return A===33?(n.consume(A),p):A===47?(n.consume(A),ae):A===63?(n.consume(A),Y):Gt(A)?(n.consume(A),ue):r(A)}function p(A){return A===45?(n.consume(A),y):A===91?(n.consume(A),c=0,w):Gt(A)?(n.consume(A),K):r(A)}function y(A){return A===45?(n.consume(A),S):r(A)}function x(A){return A===null?r(A):A===45?(n.consume(A),b):ve(A)?(f=x,J(A)):(n.consume(A),x)}function b(A){return A===45?(n.consume(A),S):x(A)}function S(A){return A===62?M(A):A===45?b(A):x(A)}function w(A){const T="CDATA[";return A===T.charCodeAt(c++)?(n.consume(A),c===T.length?j:w):r(A)}function j(A){return A===null?r(A):A===93?(n.consume(A),q):ve(A)?(f=j,J(A)):(n.consume(A),j)}function q(A){return A===93?(n.consume(A),N):j(A)}function N(A){return A===62?M(A):A===93?(n.consume(A),N):j(A)}function K(A){return A===null||A===62?M(A):ve(A)?(f=K,J(A)):(n.consume(A),K)}function Y(A){return A===null?r(A):A===63?(n.consume(A),se):ve(A)?(f=Y,J(A)):(n.consume(A),Y)}function se(A){return A===62?M(A):Y(A)}function ae(A){return Gt(A)?(n.consume(A),U):r(A)}function U(A){return A===45||Lt(A)?(n.consume(A),U):ne(A)}function ne(A){return ve(A)?(f=ne,J(A)):De(A)?(n.consume(A),ne):M(A)}function ue(A){return A===45||Lt(A)?(n.consume(A),ue):A===47||A===62||tt(A)?ye(A):r(A)}function ye(A){return A===47?(n.consume(A),M):A===58||A===95||Gt(A)?(n.consume(A),R):ve(A)?(f=ye,J(A)):De(A)?(n.consume(A),ye):M(A)}function R(A){return A===45||A===46||A===58||A===95||Lt(A)?(n.consume(A),R):Q(A)}function Q(A){return A===61?(n.consume(A),W):ve(A)?(f=Q,J(A)):De(A)?(n.consume(A),Q):ye(A)}function W(A){return A===null||A===60||A===61||A===62||A===96?r(A):A===34||A===39?(n.consume(A),o=A,de):ve(A)?(f=W,J(A)):De(A)?(n.consume(A),W):(n.consume(A),re)}function de(A){return A===o?(n.consume(A),o=void 0,I):A===null?r(A):ve(A)?(f=de,J(A)):(n.consume(A),de)}function re(A){return A===null||A===34||A===39||A===60||A===61||A===96?r(A):A===47||A===62||tt(A)?ye(A):(n.consume(A),re)}function I(A){return A===47||A===62||tt(A)?ye(A):r(A)}function M(A){return A===62?(n.consume(A),n.exit("htmlTextData"),n.exit("htmlText"),i):r(A)}function J(A){return n.exit("htmlTextData"),n.enter("lineEnding"),n.consume(A),n.exit("lineEnding"),P}function P(A){return De(A)?He(n,xe,"linePrefix",u.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):xe(A)}function xe(A){return n.enter("htmlTextData"),f(A)}}const Ic={name:"labelEnd",resolveAll:Zv,resolveTo:Fv,tokenize:Kv},Vv={tokenize:Jv},Qv={tokenize:$v},Xv={tokenize:Iv};function Zv(n){let i=-1;const r=[];for(;++i=3&&(p===null||ve(p))?(n.exit("thematicBreak"),i(p)):r(p)}function g(p){return p===o?(n.consume(p),u++,g):(n.exit("thematicBreakSequence"),De(p)?He(n,h,"whitespace")(p):h(p))}}const It={continuation:{tokenize:ub},exit:ob,name:"list",tokenize:rb},ib={partial:!0,tokenize:cb},ab={partial:!0,tokenize:sb};function rb(n,i,r){const u=this,o=u.events[u.events.length-1];let c=o&&o[1].type==="linePrefix"?o[2].sliceSerialize(o[1],!0).length:0,f=0;return h;function h(S){const w=u.containerState.type||(S===42||S===43||S===45?"listUnordered":"listOrdered");if(w==="listUnordered"?!u.containerState.marker||S===u.containerState.marker:Dc(S)){if(u.containerState.type||(u.containerState.type=w,n.enter(w,{_container:!0})),w==="listUnordered")return n.enter("listItemPrefix"),S===42||S===45?n.check(Du,r,p)(S):p(S);if(!u.interrupt||S===49)return n.enter("listItemPrefix"),n.enter("listItemValue"),g(S)}return r(S)}function g(S){return Dc(S)&&++f<10?(n.consume(S),g):(!u.interrupt||f<2)&&(u.containerState.marker?S===u.containerState.marker:S===41||S===46)?(n.exit("listItemValue"),p(S)):r(S)}function p(S){return n.enter("listItemMarker"),n.consume(S),n.exit("listItemMarker"),u.containerState.marker=u.containerState.marker||S,n.check(or,u.interrupt?r:y,n.attempt(ib,b,x))}function y(S){return u.containerState.initialBlankLine=!0,c++,b(S)}function x(S){return De(S)?(n.enter("listItemPrefixWhitespace"),n.consume(S),n.exit("listItemPrefixWhitespace"),b):r(S)}function b(S){return u.containerState.size=c+u.sliceSerialize(n.exit("listItemPrefix"),!0).length,i(S)}}function ub(n,i,r){const u=this;return u.containerState._closeFlow=void 0,n.check(or,o,c);function o(h){return u.containerState.furtherBlankLines=u.containerState.furtherBlankLines||u.containerState.initialBlankLine,He(n,i,"listItemIndent",u.containerState.size+1)(h)}function c(h){return u.containerState.furtherBlankLines||!De(h)?(u.containerState.furtherBlankLines=void 0,u.containerState.initialBlankLine=void 0,f(h)):(u.containerState.furtherBlankLines=void 0,u.containerState.initialBlankLine=void 0,n.attempt(ab,i,f)(h))}function f(h){return u.containerState._closeFlow=!0,u.interrupt=void 0,He(n,n.attempt(It,i,r),"linePrefix",u.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(h)}}function sb(n,i,r){const u=this;return He(n,o,"listItemIndent",u.containerState.size+1);function o(c){const f=u.events[u.events.length-1];return f&&f[1].type==="listItemIndent"&&f[2].sliceSerialize(f[1],!0).length===u.containerState.size?i(c):r(c)}}function ob(n){n.exit(this.containerState.type)}function cb(n,i,r){const u=this;return He(n,o,"listItemPrefixWhitespace",u.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function o(c){const f=u.events[u.events.length-1];return!De(c)&&f&&f[1].type==="listItemPrefixWhitespace"?i(c):r(c)}}const Tp={name:"setextUnderline",resolveTo:fb,tokenize:db};function fb(n,i){let r=n.length,u,o,c;for(;r--;)if(n[r][0]==="enter"){if(n[r][1].type==="content"){u=r;break}n[r][1].type==="paragraph"&&(o=r)}else n[r][1].type==="content"&&n.splice(r,1),!c&&n[r][1].type==="definition"&&(c=r);const f={type:"setextHeading",start:{...n[u][1].start},end:{...n[n.length-1][1].end}};return n[o][1].type="setextHeadingText",c?(n.splice(o,0,["enter",f,i]),n.splice(c+1,0,["exit",n[u][1],i]),n[u][1].end={...n[c][1].end}):n[u][1]=f,n.push(["exit",f,i]),n}function db(n,i,r){const u=this;let o;return c;function c(p){let y=u.events.length,x;for(;y--;)if(u.events[y][1].type!=="lineEnding"&&u.events[y][1].type!=="linePrefix"&&u.events[y][1].type!=="content"){x=u.events[y][1].type==="paragraph";break}return!u.parser.lazy[u.now().line]&&(u.interrupt||x)?(n.enter("setextHeadingLine"),o=p,f(p)):r(p)}function f(p){return n.enter("setextHeadingLineSequence"),h(p)}function h(p){return p===o?(n.consume(p),h):(n.exit("setextHeadingLineSequence"),De(p)?He(n,g,"lineSuffix")(p):g(p))}function g(p){return p===null||ve(p)?(n.exit("setextHeadingLine"),i(p)):r(p)}}const hb={tokenize:mb};function mb(n){const i=this,r=n.attempt(or,u,n.attempt(this.parser.constructs.flowInitial,o,He(n,n.attempt(this.parser.constructs.flow,o,n.attempt(vv,o)),"linePrefix")));return r;function u(c){if(c===null){n.consume(c);return}return n.enter("lineEndingBlank"),n.consume(c),n.exit("lineEndingBlank"),i.currentConstruct=void 0,r}function o(c){if(c===null){n.consume(c);return}return n.enter("lineEnding"),n.consume(c),n.exit("lineEnding"),i.currentConstruct=void 0,r}}const pb={resolveAll:Dg()},gb=Mg("string"),yb=Mg("text");function Mg(n){return{resolveAll:Dg(n==="text"?xb:void 0),tokenize:i};function i(r){const u=this,o=this.parser.constructs[n],c=r.attempt(o,f,h);return f;function f(y){return p(y)?c(y):h(y)}function h(y){if(y===null){r.consume(y);return}return r.enter("data"),r.consume(y),g}function g(y){return p(y)?(r.exit("data"),c(y)):(r.consume(y),g)}function p(y){if(y===null)return!0;const x=o[y];let b=-1;if(x)for(;++b-1){const h=f[0];typeof h=="string"?f[0]=h.slice(u):f.shift()}c>0&&f.push(n[o].slice(0,c))}return f}function Nb(n,i){let r=-1;const u=[];let o;for(;++r0){const St=ve.tokenStack[ve.tokenStack.length-1];(St[1]||zp).call(ve,void 0,St[0])}for(te.position={start:Ol(B.length>0?B[0][1].start:{line:1,column:1,offset:0}),end:Ol(B.length>0?B[B.length-2][1].end:{line:1,column:1,offset:0})},Oe=-1;++Oe0&&(u.className=["language-"+o[0]]);let c={type:"element",tagName:"code",properties:u,children:[{type:"text",value:r}]};return i.meta&&(c.data={meta:i.meta}),n.patch(i,c),c=n.applyData(i,c),c={type:"element",tagName:"pre",properties:{},children:[c]},n.patch(i,c),c}function Xv(n,i){const r={type:"element",tagName:"del",properties:{},children:n.all(i)};return n.patch(i,r),n.applyData(i,r)}function Zv(n,i){const r={type:"element",tagName:"em",properties:{},children:n.all(i)};return n.patch(i,r),n.applyData(i,r)}function Fv(n,i){const r=typeof n.options.clobberPrefix=="string"?n.options.clobberPrefix:"user-content-",u=String(i.identifier).toUpperCase(),o=la(u.toLowerCase()),c=n.footnoteOrder.indexOf(u);let f,h=n.footnoteCounts.get(u);h===void 0?(h=0,n.footnoteOrder.push(u),f=n.footnoteOrder.length):f=c+1,h+=1,n.footnoteCounts.set(u,h);const g={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+o,id:r+"fnref-"+o+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(f)}]};n.patch(i,g);const p={type:"element",tagName:"sup",properties:{},children:[g]};return n.patch(i,p),n.applyData(i,p)}function Kv(n,i){const r={type:"element",tagName:"h"+i.depth,properties:{},children:n.all(i)};return n.patch(i,r),n.applyData(i,r)}function Jv(n,i){if(n.options.allowDangerousHtml){const r={type:"raw",value:i.value};return n.patch(i,r),n.applyData(i,r)}}function Lg(n,i){const r=i.referenceType;let u="]";if(r==="collapsed"?u+="[]":r==="full"&&(u+="["+(i.label||i.identifier)+"]"),i.type==="imageReference")return[{type:"text",value:"!["+i.alt+u}];const o=n.all(i),c=o[0];c&&c.type==="text"?c.value="["+c.value:o.unshift({type:"text",value:"["});const f=o[o.length-1];return f&&f.type==="text"?f.value+=u:o.push({type:"text",value:u}),o}function $v(n,i){const r=String(i.identifier).toUpperCase(),u=n.definitionById.get(r);if(!u)return Lg(n,i);const o={src:la(u.url||""),alt:i.alt};u.title!==null&&u.title!==void 0&&(o.title=u.title);const c={type:"element",tagName:"img",properties:o,children:[]};return n.patch(i,c),n.applyData(i,c)}function Iv(n,i){const r={src:la(i.url)};i.alt!==null&&i.alt!==void 0&&(r.alt=i.alt),i.title!==null&&i.title!==void 0&&(r.title=i.title);const u={type:"element",tagName:"img",properties:r,children:[]};return n.patch(i,u),n.applyData(i,u)}function Pv(n,i){const r={type:"text",value:i.value.replace(/\r?\n|\r/g," ")};n.patch(i,r);const u={type:"element",tagName:"code",properties:{},children:[r]};return n.patch(i,u),n.applyData(i,u)}function Wv(n,i){const r=String(i.identifier).toUpperCase(),u=n.definitionById.get(r);if(!u)return Lg(n,i);const o={href:la(u.url||"")};u.title!==null&&u.title!==void 0&&(o.title=u.title);const c={type:"element",tagName:"a",properties:o,children:n.all(i)};return n.patch(i,c),n.applyData(i,c)}function eS(n,i){const r={href:la(i.url)};i.title!==null&&i.title!==void 0&&(r.title=i.title);const u={type:"element",tagName:"a",properties:r,children:n.all(i)};return n.patch(i,u),n.applyData(i,u)}function tS(n,i,r){const u=n.all(i),o=r?nS(r):Bg(i),c={},f=[];if(typeof i.checked=="boolean"){const y=u[0];let x;y&&y.type==="element"&&y.tagName==="p"?x=y:(x={type:"element",tagName:"p",properties:{},children:[]},u.unshift(x)),x.children.length>0&&x.children.unshift({type:"text",value:" "}),x.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:i.checked,disabled:!0},children:[]}),c.className=["task-list-item"]}let h=-1;for(;++h0){const St=be.tokenStack[be.tokenStack.length-1];(St[1]||zp).call(be,void 0,St[0])}for(te.position={start:Ol(B.length>0?B[0][1].start:{line:1,column:1,offset:0}),end:Ol(B.length>0?B[B.length-2][1].end:{line:1,column:1,offset:0})},Oe=-1;++Oe0&&(u.className=["language-"+o[0]]);let c={type:"element",tagName:"code",properties:u,children:[{type:"text",value:r}]};return i.meta&&(c.data={meta:i.meta}),n.patch(i,c),c=n.applyData(i,c),c={type:"element",tagName:"pre",properties:{},children:[c]},n.patch(i,c),c}function Xb(n,i){const r={type:"element",tagName:"del",properties:{},children:n.all(i)};return n.patch(i,r),n.applyData(i,r)}function Zb(n,i){const r={type:"element",tagName:"em",properties:{},children:n.all(i)};return n.patch(i,r),n.applyData(i,r)}function Fb(n,i){const r=typeof n.options.clobberPrefix=="string"?n.options.clobberPrefix:"user-content-",u=String(i.identifier).toUpperCase(),o=la(u.toLowerCase()),c=n.footnoteOrder.indexOf(u);let f,h=n.footnoteCounts.get(u);h===void 0?(h=0,n.footnoteOrder.push(u),f=n.footnoteOrder.length):f=c+1,h+=1,n.footnoteCounts.set(u,h);const g={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+o,id:r+"fnref-"+o+(h>1?"-"+h:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(f)}]};n.patch(i,g);const p={type:"element",tagName:"sup",properties:{},children:[g]};return n.patch(i,p),n.applyData(i,p)}function Kb(n,i){const r={type:"element",tagName:"h"+i.depth,properties:{},children:n.all(i)};return n.patch(i,r),n.applyData(i,r)}function Jb(n,i){if(n.options.allowDangerousHtml){const r={type:"raw",value:i.value};return n.patch(i,r),n.applyData(i,r)}}function Lg(n,i){const r=i.referenceType;let u="]";if(r==="collapsed"?u+="[]":r==="full"&&(u+="["+(i.label||i.identifier)+"]"),i.type==="imageReference")return[{type:"text",value:"!["+i.alt+u}];const o=n.all(i),c=o[0];c&&c.type==="text"?c.value="["+c.value:o.unshift({type:"text",value:"["});const f=o[o.length-1];return f&&f.type==="text"?f.value+=u:o.push({type:"text",value:u}),o}function $b(n,i){const r=String(i.identifier).toUpperCase(),u=n.definitionById.get(r);if(!u)return Lg(n,i);const o={src:la(u.url||""),alt:i.alt};u.title!==null&&u.title!==void 0&&(o.title=u.title);const c={type:"element",tagName:"img",properties:o,children:[]};return n.patch(i,c),n.applyData(i,c)}function Ib(n,i){const r={src:la(i.url)};i.alt!==null&&i.alt!==void 0&&(r.alt=i.alt),i.title!==null&&i.title!==void 0&&(r.title=i.title);const u={type:"element",tagName:"img",properties:r,children:[]};return n.patch(i,u),n.applyData(i,u)}function Pb(n,i){const r={type:"text",value:i.value.replace(/\r?\n|\r/g," ")};n.patch(i,r);const u={type:"element",tagName:"code",properties:{},children:[r]};return n.patch(i,u),n.applyData(i,u)}function Wb(n,i){const r=String(i.identifier).toUpperCase(),u=n.definitionById.get(r);if(!u)return Lg(n,i);const o={href:la(u.url||"")};u.title!==null&&u.title!==void 0&&(o.title=u.title);const c={type:"element",tagName:"a",properties:o,children:n.all(i)};return n.patch(i,c),n.applyData(i,c)}function eS(n,i){const r={href:la(i.url)};i.title!==null&&i.title!==void 0&&(r.title=i.title);const u={type:"element",tagName:"a",properties:r,children:n.all(i)};return n.patch(i,u),n.applyData(i,u)}function tS(n,i,r){const u=n.all(i),o=r?nS(r):Bg(i),c={},f=[];if(typeof i.checked=="boolean"){const y=u[0];let x;y&&y.type==="element"&&y.tagName==="p"?x=y:(x={type:"element",tagName:"p",properties:{},children:[]},u.unshift(x)),x.children.length>0&&x.children.unshift({type:"text",value:" "}),x.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:i.checked,disabled:!0},children:[]}),c.className=["task-list-item"]}let h=-1;for(;++h1}function lS(n,i){const r={},u=n.all(i);let o=-1;for(typeof i.start=="number"&&i.start!==1&&(r.start=i.start);++o0){const f={type:"element",tagName:"tbody",properties:{},children:n.wrap(r,!0)},h=Xc(i.children[1]),g=gg(i.children[i.children.length-1]);h&&g&&(f.position={start:h,end:g}),o.push(f)}const c={type:"element",tagName:"table",properties:{},children:n.wrap(o,!0)};return n.patch(i,c),n.applyData(i,c)}function sS(n,i,r){const u=r?r.children:void 0,c=(u?u.indexOf(i):1)===0?"th":"td",f=r&&r.type==="table"?r.align:void 0,h=f?f.length:i.children.length;let g=-1;const p=[];for(;++g0,!0),u[0]),o=u.index+u[0].length,u=r.exec(i);return c.push(Dp(i.slice(o),o>0,!1)),c.join("")}function Dp(n,i,r){let u=0,o=n.length;if(i){let c=n.codePointAt(u);for(;c===Np||c===Mp;)u++,c=n.codePointAt(u)}if(r){let c=n.codePointAt(o-1);for(;c===Np||c===Mp;)o--,c=n.codePointAt(o-1)}return o>u?n.slice(u,o):""}function fS(n,i){const r={type:"text",value:cS(String(i.value))};return n.patch(i,r),n.applyData(i,r)}function dS(n,i){const r={type:"element",tagName:"hr",properties:{},children:[]};return n.patch(i,r),n.applyData(i,r)}const hS={blockquote:Yv,break:Vv,code:Qv,delete:Xv,emphasis:Zv,footnoteReference:Fv,heading:Kv,html:Jv,imageReference:$v,image:Iv,inlineCode:Pv,linkReference:Wv,link:eS,listItem:tS,list:lS,paragraph:iS,root:aS,strong:rS,table:uS,tableCell:oS,tableRow:sS,text:fS,thematicBreak:dS,toml:Cu,yaml:Cu,definition:Cu,footnoteDefinition:Cu};function Cu(){}const Ug=-1,Yu=0,ar=1,Lu=2,Pc=3,Wc=4,ef=5,tf=6,Hg=7,qg=8,Gg=typeof self=="object"?self:globalThis,Op=(n,i)=>{switch(n){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+n)}return new Gg[n](i)},mS=(n,i)=>{const r=(o,c)=>(n.set(c,o),o),u=o=>{if(n.has(o))return n.get(o);const[c,f]=i[o];switch(c){case Yu:case Ug:return r(f,o);case ar:{const h=r([],o);for(const g of f)h.push(u(g));return h}case Lu:{const h=r({},o);for(const[g,p]of f)h[u(g)]=u(p);return h}case Pc:return r(new Date(f),o);case Wc:{const{source:h,flags:g}=f;return r(new RegExp(h,g),o)}case ef:{const h=r(new Map,o);for(const[g,p]of f)h.set(u(g),u(p));return h}case tf:{const h=r(new Set,o);for(const g of f)h.add(u(g));return h}case Hg:{const{name:h,message:g}=f;return r(typeof Gg[h]=="function"?Op(h,g):new Error(g),o)}case qg:return r(BigInt(f),o);case"BigInt":return r(Object(BigInt(f)),o);case"ArrayBuffer":return r(new Uint8Array(f).buffer,f);case"DataView":{const{buffer:h}=new Uint8Array(f);return r(new DataView(h),f)}}return r(Op(c,f),o)};return u},Rp=n=>mS(new Map,n)(0),ti="",{toString:pS}={},{keys:gS}=Object,tr=n=>{const i=typeof n;if(i!=="object"||!n)return[Yu,i];const r=pS.call(n).slice(8,-1);switch(r){case"Array":return[ar,ti];case"Object":return[Lu,ti];case"Date":return[Pc,ti];case"RegExp":return[Wc,ti];case"Map":return[ef,ti];case"Set":return[tf,ti];case"DataView":return[ar,r]}return r.includes("Array")?[ar,r]:n instanceof Error?[Hg,n.name||"Error"]:[Lu,r]},zu=([n,i])=>n===Yu&&(i==="function"||i==="symbol"),yS=(n,i,r,u)=>{const o=(f,h)=>{const g=u.push(f)-1;return r.set(h,g),g},c=f=>{if(r.has(f))return r.get(f);let[h,g]=tr(f);switch(h){case Yu:{let y=f;switch(g){case"bigint":h=qg,y=f.toString();break;case"function":case"symbol":if(n)throw new TypeError("unable to serialize "+g);y=null;break;case"undefined":return o([Ug],f)}return o([h,y],f)}case ar:{if(g){let v=f;return g==="DataView"?v=new Uint8Array(f.buffer):g==="ArrayBuffer"&&(v=new Uint8Array(f)),o([g,[...v]],f)}const y=[],x=o([h,y],f);for(const v of f)y.push(c(v));return x}case Lu:{if(g)switch(g){case"BigInt":return o([g,f.toString()],f);case"Boolean":case"Number":case"String":return o([g,f.valueOf()],f)}if(i&&"toJSON"in f)return c(f.toJSON());const y=[],x=o([h,y],f);for(const v of gS(f))(n||!zu(tr(f[v])))&&y.push([c(v),c(f[v])]);return x}case Pc:return o([h,isNaN(f.getTime())?ti:f.toISOString()],f);case Wc:{const{source:y,flags:x}=f;return o([h,{source:y,flags:x}],f)}case ef:{const y=[],x=o([h,y],f);for(const[v,S]of f)(n||!(zu(tr(v))||zu(tr(S))))&&y.push([c(v),c(S)]);return x}case tf:{const y=[],x=o([h,y],f);for(const v of f)(n||!zu(tr(v)))&&y.push(c(v));return x}}const{message:p}=f;return o([h,{name:g,message:p}],f)};return c},Lp=(n,{json:i,lossy:r}={})=>{const u=[];return yS(!(i||r),!!i,new Map,u)(n),u},Bu=typeof structuredClone=="function"?(n,i)=>i&&("json"in i||"lossy"in i)?Rp(Lp(n,i)):structuredClone(n):(n,i)=>Rp(Lp(n,i));function xS(n,i){const r=[{type:"text",value:"↩"}];return i>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(i)}]}),r}function bS(n,i){return"Back to reference "+(n+1)+(i>1?"-"+i:"")}function vS(n){const i=typeof n.options.clobberPrefix=="string"?n.options.clobberPrefix:"user-content-",r=n.options.footnoteBackContent||xS,u=n.options.footnoteBackLabel||bS,o=n.options.footnoteLabel||"Footnotes",c=n.options.footnoteLabelTagName||"h2",f=n.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let g=-1;for(;++g0&&w.push({type:"text",value:" "});let K=typeof r=="string"?r:r(g,S);typeof K=="string"&&(K={type:"text",value:K}),w.push({type:"element",tagName:"a",properties:{href:"#"+i+"fnref-"+v+(S>1?"-"+S:""),dataFootnoteBackref:"",ariaLabel:typeof u=="string"?u:u(g,S),className:["data-footnote-backref"]},children:Array.isArray(K)?K:[K]})}const q=y[y.length-1];if(q&&q.type==="element"&&q.tagName==="p"){const K=q.children[q.children.length-1];K&&K.type==="text"?K.value+=" ":q.children.push({type:"text",value:" "}),q.children.push(...w)}else y.push(...w);const N={type:"element",tagName:"li",properties:{id:i+"fn-"+v},children:n.wrap(y,!0)};n.patch(p,N),h.push(N)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:c,properties:{...Bu(f),id:"footnote-label"},children:[{type:"text",value:o}]},{type:"text",value:` +`});const p={type:"element",tagName:"li",properties:c,children:f};return n.patch(i,p),n.applyData(i,p)}function nS(n){let i=!1;if(n.type==="list"){i=n.spread||!1;const r=n.children;let u=-1;for(;!i&&++u1}function lS(n,i){const r={},u=n.all(i);let o=-1;for(typeof i.start=="number"&&i.start!==1&&(r.start=i.start);++o0){const f={type:"element",tagName:"tbody",properties:{},children:n.wrap(r,!0)},h=Xc(i.children[1]),g=gg(i.children[i.children.length-1]);h&&g&&(f.position={start:h,end:g}),o.push(f)}const c={type:"element",tagName:"table",properties:{},children:n.wrap(o,!0)};return n.patch(i,c),n.applyData(i,c)}function sS(n,i,r){const u=r?r.children:void 0,c=(u?u.indexOf(i):1)===0?"th":"td",f=r&&r.type==="table"?r.align:void 0,h=f?f.length:i.children.length;let g=-1;const p=[];for(;++g0,!0),u[0]),o=u.index+u[0].length,u=r.exec(i);return c.push(Dp(i.slice(o),o>0,!1)),c.join("")}function Dp(n,i,r){let u=0,o=n.length;if(i){let c=n.codePointAt(u);for(;c===Np||c===Mp;)u++,c=n.codePointAt(u)}if(r){let c=n.codePointAt(o-1);for(;c===Np||c===Mp;)o--,c=n.codePointAt(o-1)}return o>u?n.slice(u,o):""}function fS(n,i){const r={type:"text",value:cS(String(i.value))};return n.patch(i,r),n.applyData(i,r)}function dS(n,i){const r={type:"element",tagName:"hr",properties:{},children:[]};return n.patch(i,r),n.applyData(i,r)}const hS={blockquote:Yb,break:Vb,code:Qb,delete:Xb,emphasis:Zb,footnoteReference:Fb,heading:Kb,html:Jb,imageReference:$b,image:Ib,inlineCode:Pb,linkReference:Wb,link:eS,listItem:tS,list:lS,paragraph:iS,root:aS,strong:rS,table:uS,tableCell:oS,tableRow:sS,text:fS,thematicBreak:dS,toml:Cu,yaml:Cu,definition:Cu,footnoteDefinition:Cu};function Cu(){}const Ug=-1,Yu=0,ar=1,Lu=2,Pc=3,Wc=4,ef=5,tf=6,Hg=7,qg=8,Gg=typeof self=="object"?self:globalThis,Op=(n,i)=>{switch(n){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+n)}return new Gg[n](i)},mS=(n,i)=>{const r=(o,c)=>(n.set(c,o),o),u=o=>{if(n.has(o))return n.get(o);const[c,f]=i[o];switch(c){case Yu:case Ug:return r(f,o);case ar:{const h=r([],o);for(const g of f)h.push(u(g));return h}case Lu:{const h=r({},o);for(const[g,p]of f)h[u(g)]=u(p);return h}case Pc:return r(new Date(f),o);case Wc:{const{source:h,flags:g}=f;return r(new RegExp(h,g),o)}case ef:{const h=r(new Map,o);for(const[g,p]of f)h.set(u(g),u(p));return h}case tf:{const h=r(new Set,o);for(const g of f)h.add(u(g));return h}case Hg:{const{name:h,message:g}=f;return r(typeof Gg[h]=="function"?Op(h,g):new Error(g),o)}case qg:return r(BigInt(f),o);case"BigInt":return r(Object(BigInt(f)),o);case"ArrayBuffer":return r(new Uint8Array(f).buffer,f);case"DataView":{const{buffer:h}=new Uint8Array(f);return r(new DataView(h),f)}}return r(Op(c,f),o)};return u},Rp=n=>mS(new Map,n)(0),ti="",{toString:pS}={},{keys:gS}=Object,tr=n=>{const i=typeof n;if(i!=="object"||!n)return[Yu,i];const r=pS.call(n).slice(8,-1);switch(r){case"Array":return[ar,ti];case"Object":return[Lu,ti];case"Date":return[Pc,ti];case"RegExp":return[Wc,ti];case"Map":return[ef,ti];case"Set":return[tf,ti];case"DataView":return[ar,r]}return r.includes("Array")?[ar,r]:n instanceof Error?[Hg,n.name||"Error"]:[Lu,r]},zu=([n,i])=>n===Yu&&(i==="function"||i==="symbol"),yS=(n,i,r,u)=>{const o=(f,h)=>{const g=u.push(f)-1;return r.set(h,g),g},c=f=>{if(r.has(f))return r.get(f);let[h,g]=tr(f);switch(h){case Yu:{let y=f;switch(g){case"bigint":h=qg,y=f.toString();break;case"function":case"symbol":if(n)throw new TypeError("unable to serialize "+g);y=null;break;case"undefined":return o([Ug],f)}return o([h,y],f)}case ar:{if(g){let b=f;return g==="DataView"?b=new Uint8Array(f.buffer):g==="ArrayBuffer"&&(b=new Uint8Array(f)),o([g,[...b]],f)}const y=[],x=o([h,y],f);for(const b of f)y.push(c(b));return x}case Lu:{if(g)switch(g){case"BigInt":return o([g,f.toString()],f);case"Boolean":case"Number":case"String":return o([g,f.valueOf()],f)}if(i&&"toJSON"in f)return c(f.toJSON());const y=[],x=o([h,y],f);for(const b of gS(f))(n||!zu(tr(f[b])))&&y.push([c(b),c(f[b])]);return x}case Pc:return o([h,isNaN(f.getTime())?ti:f.toISOString()],f);case Wc:{const{source:y,flags:x}=f;return o([h,{source:y,flags:x}],f)}case ef:{const y=[],x=o([h,y],f);for(const[b,S]of f)(n||!(zu(tr(b))||zu(tr(S))))&&y.push([c(b),c(S)]);return x}case tf:{const y=[],x=o([h,y],f);for(const b of f)(n||!zu(tr(b)))&&y.push(c(b));return x}}const{message:p}=f;return o([h,{name:g,message:p}],f)};return c},Lp=(n,{json:i,lossy:r}={})=>{const u=[];return yS(!(i||r),!!i,new Map,u)(n),u},Bu=typeof structuredClone=="function"?(n,i)=>i&&("json"in i||"lossy"in i)?Rp(Lp(n,i)):structuredClone(n):(n,i)=>Rp(Lp(n,i));function xS(n,i){const r=[{type:"text",value:"↩"}];return i>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(i)}]}),r}function vS(n,i){return"Back to reference "+(n+1)+(i>1?"-"+i:"")}function bS(n){const i=typeof n.options.clobberPrefix=="string"?n.options.clobberPrefix:"user-content-",r=n.options.footnoteBackContent||xS,u=n.options.footnoteBackLabel||vS,o=n.options.footnoteLabel||"Footnotes",c=n.options.footnoteLabelTagName||"h2",f=n.options.footnoteLabelProperties||{className:["sr-only"]},h=[];let g=-1;for(;++g0&&w.push({type:"text",value:" "});let K=typeof r=="string"?r:r(g,S);typeof K=="string"&&(K={type:"text",value:K}),w.push({type:"element",tagName:"a",properties:{href:"#"+i+"fnref-"+b+(S>1?"-"+S:""),dataFootnoteBackref:"",ariaLabel:typeof u=="string"?u:u(g,S),className:["data-footnote-backref"]},children:Array.isArray(K)?K:[K]})}const q=y[y.length-1];if(q&&q.type==="element"&&q.tagName==="p"){const K=q.children[q.children.length-1];K&&K.type==="text"?K.value+=" ":q.children.push({type:"text",value:" "}),q.children.push(...w)}else y.push(...w);const N={type:"element",tagName:"li",properties:{id:i+"fn-"+b},children:n.wrap(y,!0)};n.patch(p,N),h.push(N)}if(h.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:c,properties:{...Bu(f),id:"footnote-label"},children:[{type:"text",value:o}]},{type:"text",value:` `},{type:"element",tagName:"ol",properties:{},children:n.wrap(h,!0)},{type:"text",value:` -`}]}}const Vu=(function(n){if(n==null)return AS;if(typeof n=="function")return Qu(n);if(typeof n=="object")return Array.isArray(n)?SS(n):_S(n);if(typeof n=="string")return kS(n);throw new Error("Expected function, string, or object as test")});function SS(n){const i=[];let r=-1;for(;++r":""))+")"})}return v;function v(){let S=Yg,w,j,q;if((!i||c(g,p,y[y.length-1]||void 0))&&(S=TS(r(g,y)),S[0]===Rc))return S;if("children"in g&&g.children){const N=g;if(N.children&&S[0]!==jS)for(j=(u?N.children.length:-1)+f,q=y.concat(N);j>-1&&j":""))+")"})}return b;function b(){let S=Yg,w,j,q;if((!i||c(g,p,y[y.length-1]||void 0))&&(S=TS(r(g,y)),S[0]===Rc))return S;if("children"in g&&g.children){const N=g;if(N.children&&S[0]!==jS)for(j=(u?N.children.length:-1)+f,q=y.concat(N);j>-1&&j0&&r.push({type:"text",value:` -`}),r}function Bp(n){let i=0,r=n.charCodeAt(i);for(;r===9||r===32;)i++,r=n.charCodeAt(i);return n.slice(i)}function Up(n,i){const r=zS(n,i),u=r.one(n,void 0),o=vS(r),c=Array.isArray(u)?{type:"root",children:u}:u||{type:"root",children:[]};return o&&c.children.push({type:"text",value:` -`},o),c}function RS(n,i){return n&&"run"in n?async function(r,u){const o=Up(r,{file:u,...i});await n.run(o,u)}:function(r,u){return Up(r,{file:u,...n||i})}}function Hp(n){if(n)throw n}var pc,qp;function LS(){if(qp)return pc;qp=1;var n=Object.prototype.hasOwnProperty,i=Object.prototype.toString,r=Object.defineProperty,u=Object.getOwnPropertyDescriptor,o=function(p){return typeof Array.isArray=="function"?Array.isArray(p):i.call(p)==="[object Array]"},c=function(p){if(!p||i.call(p)!=="[object Object]")return!1;var y=n.call(p,"constructor"),x=p.constructor&&p.constructor.prototype&&n.call(p.constructor.prototype,"isPrototypeOf");if(p.constructor&&!y&&!x)return!1;var v;for(v in p);return typeof v>"u"||n.call(p,v)},f=function(p,y){r&&y.name==="__proto__"?r(p,y.name,{enumerable:!0,configurable:!0,value:y.newValue,writable:!0}):p[y.name]=y.newValue},h=function(p,y){if(y==="__proto__")if(n.call(p,y)){if(u)return u(p,y).value}else return;return p[y]};return pc=function g(){var p,y,x,v,S,w,j=arguments[0],q=1,N=arguments.length,K=!1;for(typeof j=="boolean"&&(K=j,j=arguments[1]||{},q=2),(j==null||typeof j!="object"&&typeof j!="function")&&(j={});qf.length;let g;h&&f.push(o);try{g=n.apply(this,f)}catch(p){const y=p;if(h&&r)throw y;return o(y)}h||(g&&g.then&&typeof g.then=="function"?g.then(c,o):g instanceof Error?o(g):c(g))}function o(f,...h){r||(r=!0,i(f,...h))}function c(f){o(null,f)}}const Un={basename:qS,dirname:GS,extname:YS,join:VS,sep:"/"};function qS(n,i){if(i!==void 0&&typeof i!="string")throw new TypeError('"ext" argument must be a string');cr(n);let r=0,u=-1,o=n.length,c;if(i===void 0||i.length===0||i.length>n.length){for(;o--;)if(n.codePointAt(o)===47){if(c){r=o+1;break}}else u<0&&(c=!0,u=o+1);return u<0?"":n.slice(r,u)}if(i===n)return"";let f=-1,h=i.length-1;for(;o--;)if(n.codePointAt(o)===47){if(c){r=o+1;break}}else f<0&&(c=!0,f=o+1),h>-1&&(n.codePointAt(o)===i.codePointAt(h--)?h<0&&(u=o):(h=-1,u=f));return r===u?u=f:u<0&&(u=n.length),n.slice(r,u)}function GS(n){if(cr(n),n.length===0)return".";let i=-1,r=n.length,u;for(;--r;)if(n.codePointAt(r)===47){if(u){i=r;break}}else u||(u=!0);return i<0?n.codePointAt(0)===47?"/":".":i===1&&n.codePointAt(0)===47?"//":n.slice(0,i)}function YS(n){cr(n);let i=n.length,r=-1,u=0,o=-1,c=0,f;for(;i--;){const h=n.codePointAt(i);if(h===47){if(f){u=i+1;break}continue}r<0&&(f=!0,r=i+1),h===46?o<0?o=i:c!==1&&(c=1):o>-1&&(c=-1)}return o<0||r<0||c===0||c===1&&o===r-1&&o===u+1?"":n.slice(o,r)}function VS(...n){let i=-1,r;for(;++i0&&n.codePointAt(n.length-1)===47&&(r+="/"),i?"/"+r:r}function XS(n,i){let r="",u=0,o=-1,c=0,f=-1,h,g;for(;++f<=n.length;){if(f2){if(g=r.lastIndexOf("/"),g!==r.length-1){g<0?(r="",u=0):(r=r.slice(0,g),u=r.length-1-r.lastIndexOf("/")),o=f,c=0;continue}}else if(r.length>0){r="",u=0,o=f,c=0;continue}}i&&(r=r.length>0?r+"/..":"..",u=2)}else r.length>0?r+="/"+n.slice(o+1,f):r=n.slice(o+1,f),u=f-o-1;o=f,c=0}else h===46&&c>-1?c++:c=-1}return r}function cr(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}const ZS={cwd:FS};function FS(){return"/"}function Uc(n){return!!(n!==null&&typeof n=="object"&&"href"in n&&n.href&&"protocol"in n&&n.protocol&&n.auth===void 0)}function KS(n){if(typeof n=="string")n=new URL(n);else if(!Uc(n)){const i=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+n+"`");throw i.code="ERR_INVALID_ARG_TYPE",i}if(n.protocol!=="file:"){const i=new TypeError("The URL must be of scheme file");throw i.code="ERR_INVALID_URL_SCHEME",i}return JS(n)}function JS(n){if(n.hostname!==""){const u=new TypeError('File URL host must be "localhost" or empty on darwin');throw u.code="ERR_INVALID_FILE_URL_HOST",u}const i=n.pathname;let r=-1;for(;++r0){let[S,...w]=y;const j=u[v][1];Bc(j)&&Bc(S)&&(S=gc(!0,j,S)),u[v]=[p,S,...w]}}}}const WS=new lf().freeze();function vc(n,i){if(typeof i!="function")throw new TypeError("Cannot `"+n+"` without `parser`")}function Sc(n,i){if(typeof i!="function")throw new TypeError("Cannot `"+n+"` without `compiler`")}function _c(n,i){if(i)throw new Error("Cannot call `"+n+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Yp(n){if(!Bc(n)||typeof n.type!="string")throw new TypeError("Expected node, got `"+n+"`")}function Vp(n,i,r){if(!r)throw new Error("`"+n+"` finished async. Use `"+i+"` instead")}function Nu(n){return e2(n)?n:new Qg(n)}function e2(n){return!!(n&&typeof n=="object"&&"message"in n&&"messages"in n)}function t2(n){return typeof n=="string"||n2(n)}function n2(n){return!!(n&&typeof n=="object"&&"byteLength"in n&&"byteOffset"in n)}const l2="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Qp=[],Xp={allowDangerousHtml:!0},i2=/^(https?|ircs?|mailto|xmpp)$/i,a2=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function r2(n){const i=u2(n),r=s2(n);return o2(i.runSync(i.parse(r),r),n)}function u2(n){const i=n.rehypePlugins||Qp,r=n.remarkPlugins||Qp,u=n.remarkRehypeOptions?{...n.remarkRehypeOptions,...Xp}:Xp;return WS().use(Gv).use(r).use(RS,u).use(i)}function s2(n){const i=n.children||"",r=new Qg;return typeof i=="string"&&(r.value=i),r}function o2(n,i){const r=i.allowedElements,u=i.allowElement,o=i.components,c=i.disallowedElements,f=i.skipHtml,h=i.unwrapDisallowed,g=i.urlTransform||c2;for(const y of a2)Object.hasOwn(i,y.from)&&(""+y.from+(y.to?"use `"+y.to+"` instead":"remove it")+l2+y.id,void 0);return nf(n,p),A0(n,{Fragment:m.Fragment,components:o,ignoreInvalidStyle:!0,jsx:m.jsx,jsxs:m.jsxs,passKeys:!0,passNode:!0});function p(y,x,v){if(y.type==="raw"&&v&&typeof x=="number")return f?v.children.splice(x,1):v.children[x]={type:"text",value:y.value},x;if(y.type==="element"){let S;for(S in dc)if(Object.hasOwn(dc,S)&&Object.hasOwn(y.properties,S)){const w=y.properties[S],j=dc[S];(j===null||j.includes(y.tagName))&&(y.properties[S]=g(String(w||""),S,y))}}if(y.type==="element"){let S=r?!r.includes(y.tagName):c?c.includes(y.tagName):!1;if(!S&&u&&typeof x=="number"&&(S=!u(y,x,v)),S&&v&&typeof x=="number")return h&&y.children?v.children.splice(x,1,...y.children):v.children.splice(x,1),x}}}function c2(n){const i=n.indexOf(":"),r=n.indexOf("?"),u=n.indexOf("#"),o=n.indexOf("/");return i===-1||o!==-1&&i>o||r!==-1&&i>r||u!==-1&&i>u||i2.test(n.slice(0,i))?n:""}function Zp(n,i){const r=String(n);if(typeof i!="string")throw new TypeError("Expected character");let u=0,o=r.indexOf(i);for(;o!==-1;)u++,o=r.indexOf(i,o+i.length);return u}function f2(n){if(typeof n!="string")throw new TypeError("Expected a string");return n.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function d2(n,i,r){const o=Vu((r||{}).ignore||[]),c=h2(i);let f=-1;for(;++f0?{type:"text",value:U}:void 0),U===!1?v.lastIndex=se+1:(w!==se&&K.push({type:"text",value:p.value.slice(w,se)}),Array.isArray(U)?K.push(...U):U&&K.push(U),w=se+Y[0].length,N=!0),!v.global)break;Y=v.exec(p.value)}return N?(w?\]}]+$/.exec(n);if(!i)return[n,void 0];n=n.slice(0,i.index);let r=i[0],u=r.indexOf(")");const o=Zp(n,"(");let c=Zp(n,")");for(;u!==-1&&o>c;)n+=r.slice(0,u+1),r=r.slice(u+1),u=r.indexOf(")"),c++;return[n,r]}function Xg(n,i){const r=n.input.charCodeAt(n.index-1);return(n.index===0||ri(r)||qu(r))&&(!i||r!==47)}Zg.peek=L2;function T2(){this.buffer()}function C2(n){this.enter({type:"footnoteReference",identifier:"",label:""},n)}function z2(){this.buffer()}function N2(n){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},n)}function M2(n){const i=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Tn(this.sliceSerialize(n)).toLowerCase(),r.label=i}function D2(n){this.exit(n)}function O2(n){const i=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Tn(this.sliceSerialize(n)).toLowerCase(),r.label=i}function R2(n){this.exit(n)}function L2(){return"["}function Zg(n,i,r,u){const o=r.createTracker(u);let c=o.move("[^");const f=r.enter("footnoteReference"),h=r.enter("reference");return c+=o.move(r.safe(r.associationId(n),{after:"]",before:c})),h(),f(),c+=o.move("]"),c}function B2(){return{enter:{gfmFootnoteCallString:T2,gfmFootnoteCall:C2,gfmFootnoteDefinitionLabelString:z2,gfmFootnoteDefinition:N2},exit:{gfmFootnoteCallString:M2,gfmFootnoteCall:D2,gfmFootnoteDefinitionLabelString:O2,gfmFootnoteDefinition:R2}}}function U2(n){let i=!1;return n&&n.firstLineBlank&&(i=!0),{handlers:{footnoteDefinition:r,footnoteReference:Zg},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(u,o,c,f){const h=c.createTracker(f);let g=h.move("[^");const p=c.enter("footnoteDefinition"),y=c.enter("label");return g+=h.move(c.safe(c.associationId(u),{before:g,after:"]"})),y(),g+=h.move("]:"),u.children&&u.children.length>0&&(h.shift(4),g+=h.move((i?` -`:" ")+c.indentLines(c.containerFlow(u,h.current()),i?Fg:H2))),p(),g}}function H2(n,i,r){return i===0?n:Fg(n,i,r)}function Fg(n,i,r){return(r?"":" ")+n}const q2=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Kg.peek=X2;function G2(){return{canContainEols:["delete"],enter:{strikethrough:V2},exit:{strikethrough:Q2}}}function Y2(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:q2}],handlers:{delete:Kg}}}function V2(n){this.enter({type:"delete",children:[]},n)}function Q2(n){this.exit(n)}function Kg(n,i,r,u){const o=r.createTracker(u),c=r.enter("strikethrough");let f=o.move("~~");return f+=r.containerPhrasing(n,{...o.current(),before:f,after:"~"}),f+=o.move("~~"),c(),f}function X2(){return"~"}function Z2(n){return n.length}function F2(n,i){const r=i||{},u=(r.align||[]).concat(),o=r.stringLength||Z2,c=[],f=[],h=[],g=[];let p=0,y=-1;for(;++yp&&(p=n[y].length);++Ng[N])&&(g[N]=Y)}j.push(K)}f[y]=j,h[y]=q}let x=-1;if(typeof u=="object"&&"length"in u)for(;++xg[x]&&(g[x]=K),S[x]=K),v[x]=Y}f.splice(1,0,v),h.splice(1,0,S),y=-1;const w=[];for(;++y"u"||n.call(p,b)},f=function(p,y){r&&y.name==="__proto__"?r(p,y.name,{enumerable:!0,configurable:!0,value:y.newValue,writable:!0}):p[y.name]=y.newValue},h=function(p,y){if(y==="__proto__")if(n.call(p,y)){if(u)return u(p,y).value}else return;return p[y]};return pc=function g(){var p,y,x,b,S,w,j=arguments[0],q=1,N=arguments.length,K=!1;for(typeof j=="boolean"&&(K=j,j=arguments[1]||{},q=2),(j==null||typeof j!="object"&&typeof j!="function")&&(j={});qf.length;let g;h&&f.push(o);try{g=n.apply(this,f)}catch(p){const y=p;if(h&&r)throw y;return o(y)}h||(g&&g.then&&typeof g.then=="function"?g.then(c,o):g instanceof Error?o(g):c(g))}function o(f,...h){r||(r=!0,i(f,...h))}function c(f){o(null,f)}}const Un={basename:qS,dirname:GS,extname:YS,join:VS,sep:"/"};function qS(n,i){if(i!==void 0&&typeof i!="string")throw new TypeError('"ext" argument must be a string');cr(n);let r=0,u=-1,o=n.length,c;if(i===void 0||i.length===0||i.length>n.length){for(;o--;)if(n.codePointAt(o)===47){if(c){r=o+1;break}}else u<0&&(c=!0,u=o+1);return u<0?"":n.slice(r,u)}if(i===n)return"";let f=-1,h=i.length-1;for(;o--;)if(n.codePointAt(o)===47){if(c){r=o+1;break}}else f<0&&(c=!0,f=o+1),h>-1&&(n.codePointAt(o)===i.codePointAt(h--)?h<0&&(u=o):(h=-1,u=f));return r===u?u=f:u<0&&(u=n.length),n.slice(r,u)}function GS(n){if(cr(n),n.length===0)return".";let i=-1,r=n.length,u;for(;--r;)if(n.codePointAt(r)===47){if(u){i=r;break}}else u||(u=!0);return i<0?n.codePointAt(0)===47?"/":".":i===1&&n.codePointAt(0)===47?"//":n.slice(0,i)}function YS(n){cr(n);let i=n.length,r=-1,u=0,o=-1,c=0,f;for(;i--;){const h=n.codePointAt(i);if(h===47){if(f){u=i+1;break}continue}r<0&&(f=!0,r=i+1),h===46?o<0?o=i:c!==1&&(c=1):o>-1&&(c=-1)}return o<0||r<0||c===0||c===1&&o===r-1&&o===u+1?"":n.slice(o,r)}function VS(...n){let i=-1,r;for(;++i0&&n.codePointAt(n.length-1)===47&&(r+="/"),i?"/"+r:r}function XS(n,i){let r="",u=0,o=-1,c=0,f=-1,h,g;for(;++f<=n.length;){if(f2){if(g=r.lastIndexOf("/"),g!==r.length-1){g<0?(r="",u=0):(r=r.slice(0,g),u=r.length-1-r.lastIndexOf("/")),o=f,c=0;continue}}else if(r.length>0){r="",u=0,o=f,c=0;continue}}i&&(r=r.length>0?r+"/..":"..",u=2)}else r.length>0?r+="/"+n.slice(o+1,f):r=n.slice(o+1,f),u=f-o-1;o=f,c=0}else h===46&&c>-1?c++:c=-1}return r}function cr(n){if(typeof n!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(n))}const ZS={cwd:FS};function FS(){return"/"}function Uc(n){return!!(n!==null&&typeof n=="object"&&"href"in n&&n.href&&"protocol"in n&&n.protocol&&n.auth===void 0)}function KS(n){if(typeof n=="string")n=new URL(n);else if(!Uc(n)){const i=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+n+"`");throw i.code="ERR_INVALID_ARG_TYPE",i}if(n.protocol!=="file:"){const i=new TypeError("The URL must be of scheme file");throw i.code="ERR_INVALID_URL_SCHEME",i}return JS(n)}function JS(n){if(n.hostname!==""){const u=new TypeError('File URL host must be "localhost" or empty on darwin');throw u.code="ERR_INVALID_FILE_URL_HOST",u}const i=n.pathname;let r=-1;for(;++r0){let[S,...w]=y;const j=u[b][1];Bc(j)&&Bc(S)&&(S=gc(!0,j,S)),u[b]=[p,S,...w]}}}}const WS=new lf().freeze();function bc(n,i){if(typeof i!="function")throw new TypeError("Cannot `"+n+"` without `parser`")}function Sc(n,i){if(typeof i!="function")throw new TypeError("Cannot `"+n+"` without `compiler`")}function _c(n,i){if(i)throw new Error("Cannot call `"+n+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Yp(n){if(!Bc(n)||typeof n.type!="string")throw new TypeError("Expected node, got `"+n+"`")}function Vp(n,i,r){if(!r)throw new Error("`"+n+"` finished async. Use `"+i+"` instead")}function Nu(n){return e2(n)?n:new Qg(n)}function e2(n){return!!(n&&typeof n=="object"&&"message"in n&&"messages"in n)}function t2(n){return typeof n=="string"||n2(n)}function n2(n){return!!(n&&typeof n=="object"&&"byteLength"in n&&"byteOffset"in n)}const l2="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Qp=[],Xp={allowDangerousHtml:!0},i2=/^(https?|ircs?|mailto|xmpp)$/i,a2=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function r2(n){const i=u2(n),r=s2(n);return o2(i.runSync(i.parse(r),r),n)}function u2(n){const i=n.rehypePlugins||Qp,r=n.remarkPlugins||Qp,u=n.remarkRehypeOptions?{...n.remarkRehypeOptions,...Xp}:Xp;return WS().use(Gb).use(r).use(RS,u).use(i)}function s2(n){const i=n.children||"",r=new Qg;return typeof i=="string"&&(r.value=i),r}function o2(n,i){const r=i.allowedElements,u=i.allowElement,o=i.components,c=i.disallowedElements,f=i.skipHtml,h=i.unwrapDisallowed,g=i.urlTransform||c2;for(const y of a2)Object.hasOwn(i,y.from)&&(""+y.from+(y.to?"use `"+y.to+"` instead":"remove it")+l2+y.id,void 0);return nf(n,p),A0(n,{Fragment:m.Fragment,components:o,ignoreInvalidStyle:!0,jsx:m.jsx,jsxs:m.jsxs,passKeys:!0,passNode:!0});function p(y,x,b){if(y.type==="raw"&&b&&typeof x=="number")return f?b.children.splice(x,1):b.children[x]={type:"text",value:y.value},x;if(y.type==="element"){let S;for(S in dc)if(Object.hasOwn(dc,S)&&Object.hasOwn(y.properties,S)){const w=y.properties[S],j=dc[S];(j===null||j.includes(y.tagName))&&(y.properties[S]=g(String(w||""),S,y))}}if(y.type==="element"){let S=r?!r.includes(y.tagName):c?c.includes(y.tagName):!1;if(!S&&u&&typeof x=="number"&&(S=!u(y,x,b)),S&&b&&typeof x=="number")return h&&y.children?b.children.splice(x,1,...y.children):b.children.splice(x,1),x}}}function c2(n){const i=n.indexOf(":"),r=n.indexOf("?"),u=n.indexOf("#"),o=n.indexOf("/");return i===-1||o!==-1&&i>o||r!==-1&&i>r||u!==-1&&i>u||i2.test(n.slice(0,i))?n:""}function Zp(n,i){const r=String(n);if(typeof i!="string")throw new TypeError("Expected character");let u=0,o=r.indexOf(i);for(;o!==-1;)u++,o=r.indexOf(i,o+i.length);return u}function f2(n){if(typeof n!="string")throw new TypeError("Expected a string");return n.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function d2(n,i,r){const o=Vu((r||{}).ignore||[]),c=h2(i);let f=-1;for(;++f0?{type:"text",value:U}:void 0),U===!1?b.lastIndex=se+1:(w!==se&&K.push({type:"text",value:p.value.slice(w,se)}),Array.isArray(U)?K.push(...U):U&&K.push(U),w=se+Y[0].length,N=!0),!b.global)break;Y=b.exec(p.value)}return N?(w?\]}]+$/.exec(n);if(!i)return[n,void 0];n=n.slice(0,i.index);let r=i[0],u=r.indexOf(")");const o=Zp(n,"(");let c=Zp(n,")");for(;u!==-1&&o>c;)n+=r.slice(0,u+1),r=r.slice(u+1),u=r.indexOf(")"),c++;return[n,r]}function Xg(n,i){const r=n.input.charCodeAt(n.index-1);return(n.index===0||ri(r)||qu(r))&&(!i||r!==47)}Zg.peek=L2;function T2(){this.buffer()}function C2(n){this.enter({type:"footnoteReference",identifier:"",label:""},n)}function z2(){this.buffer()}function N2(n){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},n)}function M2(n){const i=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Tn(this.sliceSerialize(n)).toLowerCase(),r.label=i}function D2(n){this.exit(n)}function O2(n){const i=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=Tn(this.sliceSerialize(n)).toLowerCase(),r.label=i}function R2(n){this.exit(n)}function L2(){return"["}function Zg(n,i,r,u){const o=r.createTracker(u);let c=o.move("[^");const f=r.enter("footnoteReference"),h=r.enter("reference");return c+=o.move(r.safe(r.associationId(n),{after:"]",before:c})),h(),f(),c+=o.move("]"),c}function B2(){return{enter:{gfmFootnoteCallString:T2,gfmFootnoteCall:C2,gfmFootnoteDefinitionLabelString:z2,gfmFootnoteDefinition:N2},exit:{gfmFootnoteCallString:M2,gfmFootnoteCall:D2,gfmFootnoteDefinitionLabelString:O2,gfmFootnoteDefinition:R2}}}function U2(n){let i=!1;return n&&n.firstLineBlank&&(i=!0),{handlers:{footnoteDefinition:r,footnoteReference:Zg},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(u,o,c,f){const h=c.createTracker(f);let g=h.move("[^");const p=c.enter("footnoteDefinition"),y=c.enter("label");return g+=h.move(c.safe(c.associationId(u),{before:g,after:"]"})),y(),g+=h.move("]:"),u.children&&u.children.length>0&&(h.shift(4),g+=h.move((i?` +`:" ")+c.indentLines(c.containerFlow(u,h.current()),i?Fg:H2))),p(),g}}function H2(n,i,r){return i===0?n:Fg(n,i,r)}function Fg(n,i,r){return(r?"":" ")+n}const q2=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Kg.peek=X2;function G2(){return{canContainEols:["delete"],enter:{strikethrough:V2},exit:{strikethrough:Q2}}}function Y2(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:q2}],handlers:{delete:Kg}}}function V2(n){this.enter({type:"delete",children:[]},n)}function Q2(n){this.exit(n)}function Kg(n,i,r,u){const o=r.createTracker(u),c=r.enter("strikethrough");let f=o.move("~~");return f+=r.containerPhrasing(n,{...o.current(),before:f,after:"~"}),f+=o.move("~~"),c(),f}function X2(){return"~"}function Z2(n){return n.length}function F2(n,i){const r=i||{},u=(r.align||[]).concat(),o=r.stringLength||Z2,c=[],f=[],h=[],g=[];let p=0,y=-1;for(;++yp&&(p=n[y].length);++Ng[N])&&(g[N]=Y)}j.push(K)}f[y]=j,h[y]=q}let x=-1;if(typeof u=="object"&&"length"in u)for(;++xg[x]&&(g[x]=K),S[x]=K),b[x]=Y}f.splice(1,0,b),h.splice(1,0,S),y=-1;const w=[];for(;++y "),c.shift(2);const f=r.indentLines(r.containerFlow(n,c.current()),$2);return o(),f}function $2(n,i,r){return">"+(r?"":" ")+n}function I2(n,i){return Kp(n,i.inConstruct,!0)&&!Kp(n,i.notInConstruct,!1)}function Kp(n,i,r){if(typeof i=="string"&&(i=[i]),!i||i.length===0)return r;let u=-1;for(;++uf&&(f=c):c=1,o=u+i.length,u=r.indexOf(i,o);return f}function W2(n,i){return!!(i.options.fences===!1&&n.value&&!n.lang&&/[^ \r\n]/.test(n.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(n.value))}function e_(n){const i=n.options.fence||"`";if(i!=="`"&&i!=="~")throw new Error("Cannot serialize code with `"+i+"` for `options.fence`, expected `` ` `` or `~`");return i}function t_(n,i,r,u){const o=e_(r),c=n.value||"",f=o==="`"?"GraveAccent":"Tilde";if(W2(n,r)){const x=r.enter("codeIndented"),v=r.indentLines(c,n_);return x(),v}const h=r.createTracker(u),g=o.repeat(Math.max(P2(c,o)+1,3)),p=r.enter("codeFenced");let y=h.move(g);if(n.lang){const x=r.enter(`codeFencedLang${f}`);y+=h.move(r.safe(n.lang,{before:y,after:" ",encode:["`"],...h.current()})),x()}if(n.lang&&n.meta){const x=r.enter(`codeFencedMeta${f}`);y+=h.move(" "),y+=h.move(r.safe(n.meta,{before:y,after:` +`}function P2(n,i){const r=String(n);let u=r.indexOf(i),o=u,c=0,f=0;if(typeof i!="string")throw new TypeError("Expected substring");for(;u!==-1;)u===o?++c>f&&(f=c):c=1,o=u+i.length,u=r.indexOf(i,o);return f}function W2(n,i){return!!(i.options.fences===!1&&n.value&&!n.lang&&/[^ \r\n]/.test(n.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(n.value))}function e_(n){const i=n.options.fence||"`";if(i!=="`"&&i!=="~")throw new Error("Cannot serialize code with `"+i+"` for `options.fence`, expected `` ` `` or `~`");return i}function t_(n,i,r,u){const o=e_(r),c=n.value||"",f=o==="`"?"GraveAccent":"Tilde";if(W2(n,r)){const x=r.enter("codeIndented"),b=r.indentLines(c,n_);return x(),b}const h=r.createTracker(u),g=o.repeat(Math.max(P2(c,o)+1,3)),p=r.enter("codeFenced");let y=h.move(g);if(n.lang){const x=r.enter(`codeFencedLang${f}`);y+=h.move(r.safe(n.lang,{before:y,after:" ",encode:["`"],...h.current()})),x()}if(n.lang&&n.meta){const x=r.enter(`codeFencedMeta${f}`);y+=h.move(" "),y+=h.move(r.safe(n.meta,{before:y,after:` `,encode:["`"],...h.current()})),x()}return y+=h.move(` `),c&&(y+=h.move(c+` `)),y+=h.move(g),p(),y}function n_(n,i,r){return(r?"":" ")+n}function af(n){const i=n.options.quote||'"';if(i!=='"'&&i!=="'")throw new Error("Cannot serialize title with `"+i+"` for `options.quote`, expected `\"`, or `'`");return i}function l_(n,i,r,u){const o=af(r),c=o==='"'?"Quote":"Apostrophe",f=r.enter("definition");let h=r.enter("label");const g=r.createTracker(u);let p=g.move("[");return p+=g.move(r.safe(r.associationId(n),{before:p,after:"]",...g.current()})),p+=g.move("]: "),h(),!n.url||/[\0- \u007F]/.test(n.url)?(h=r.enter("destinationLiteral"),p+=g.move("<"),p+=g.move(r.safe(n.url,{before:p,after:">",...g.current()})),p+=g.move(">")):(h=r.enter("destinationRaw"),p+=g.move(r.safe(n.url,{before:p,after:n.title?" ":` -`,...g.current()}))),h(),n.title&&(h=r.enter(`title${c}`),p+=g.move(" "+o),p+=g.move(r.safe(n.title,{before:p,after:o,...g.current()})),p+=g.move(o),h()),f(),p}function i_(n){const i=n.options.emphasis||"*";if(i!=="*"&&i!=="_")throw new Error("Cannot serialize emphasis with `"+i+"` for `options.emphasis`, expected `*`, or `_`");return i}function ur(n){return"&#x"+n.toString(16).toUpperCase()+";"}function Uu(n,i,r){const u=ea(n),o=ea(i);return u===void 0?o===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:o===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:u===1?o===void 0?{inside:!1,outside:!1}:o===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:o===void 0?{inside:!1,outside:!1}:o===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Jg.peek=a_;function Jg(n,i,r,u){const o=i_(r),c=r.enter("emphasis"),f=r.createTracker(u),h=f.move(o);let g=f.move(r.containerPhrasing(n,{after:o,before:h,...f.current()}));const p=g.charCodeAt(0),y=Uu(u.before.charCodeAt(u.before.length-1),p,o);y.inside&&(g=ur(p)+g.slice(1));const x=g.charCodeAt(g.length-1),v=Uu(u.after.charCodeAt(0),x,o);v.inside&&(g=g.slice(0,-1)+ur(x));const S=f.move(o);return c(),r.attentionEncodeSurroundingInfo={after:v.outside,before:y.outside},h+g+S}function a_(n,i,r){return r.options.emphasis||"*"}function r_(n,i){let r=!1;return nf(n,function(u){if("value"in u&&/\r?\n|\r/.test(u.value)||u.type==="break")return r=!0,Rc}),!!((!n.depth||n.depth<3)&&Jc(n)&&(i.options.setext||r))}function u_(n,i,r,u){const o=Math.max(Math.min(6,n.depth||1),1),c=r.createTracker(u);if(r_(n,r)){const y=r.enter("headingSetext"),x=r.enter("phrasing"),v=r.containerPhrasing(n,{...c.current(),before:` +`,...g.current()}))),h(),n.title&&(h=r.enter(`title${c}`),p+=g.move(" "+o),p+=g.move(r.safe(n.title,{before:p,after:o,...g.current()})),p+=g.move(o),h()),f(),p}function i_(n){const i=n.options.emphasis||"*";if(i!=="*"&&i!=="_")throw new Error("Cannot serialize emphasis with `"+i+"` for `options.emphasis`, expected `*`, or `_`");return i}function ur(n){return"&#x"+n.toString(16).toUpperCase()+";"}function Uu(n,i,r){const u=ea(n),o=ea(i);return u===void 0?o===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:o===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:u===1?o===void 0?{inside:!1,outside:!1}:o===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:o===void 0?{inside:!1,outside:!1}:o===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Jg.peek=a_;function Jg(n,i,r,u){const o=i_(r),c=r.enter("emphasis"),f=r.createTracker(u),h=f.move(o);let g=f.move(r.containerPhrasing(n,{after:o,before:h,...f.current()}));const p=g.charCodeAt(0),y=Uu(u.before.charCodeAt(u.before.length-1),p,o);y.inside&&(g=ur(p)+g.slice(1));const x=g.charCodeAt(g.length-1),b=Uu(u.after.charCodeAt(0),x,o);b.inside&&(g=g.slice(0,-1)+ur(x));const S=f.move(o);return c(),r.attentionEncodeSurroundingInfo={after:b.outside,before:y.outside},h+g+S}function a_(n,i,r){return r.options.emphasis||"*"}function r_(n,i){let r=!1;return nf(n,function(u){if("value"in u&&/\r?\n|\r/.test(u.value)||u.type==="break")return r=!0,Rc}),!!((!n.depth||n.depth<3)&&Jc(n)&&(i.options.setext||r))}function u_(n,i,r,u){const o=Math.max(Math.min(6,n.depth||1),1),c=r.createTracker(u);if(r_(n,r)){const y=r.enter("headingSetext"),x=r.enter("phrasing"),b=r.containerPhrasing(n,{...c.current(),before:` `,after:` -`});return x(),y(),v+` -`+(o===1?"=":"-").repeat(v.length-(Math.max(v.lastIndexOf("\r"),v.lastIndexOf(` +`});return x(),y(),b+` +`+(o===1?"=":"-").repeat(b.length-(Math.max(b.lastIndexOf("\r"),b.lastIndexOf(` `))+1))}const f="#".repeat(o),h=r.enter("headingAtx"),g=r.enter("phrasing");c.move(f+" ");let p=r.containerPhrasing(n,{before:"# ",after:` -`,...c.current()});return/^[\t ]/.test(p)&&(p=ur(p.charCodeAt(0))+p.slice(1)),p=p?f+" "+p:f,r.options.closeAtx&&(p+=" "+f),g(),h(),p}$g.peek=s_;function $g(n){return n.value||""}function s_(){return"<"}Ig.peek=o_;function Ig(n,i,r,u){const o=af(r),c=o==='"'?"Quote":"Apostrophe",f=r.enter("image");let h=r.enter("label");const g=r.createTracker(u);let p=g.move("![");return p+=g.move(r.safe(n.alt,{before:p,after:"]",...g.current()})),p+=g.move("]("),h(),!n.url&&n.title||/[\0- \u007F]/.test(n.url)?(h=r.enter("destinationLiteral"),p+=g.move("<"),p+=g.move(r.safe(n.url,{before:p,after:">",...g.current()})),p+=g.move(">")):(h=r.enter("destinationRaw"),p+=g.move(r.safe(n.url,{before:p,after:n.title?" ":")",...g.current()}))),h(),n.title&&(h=r.enter(`title${c}`),p+=g.move(" "+o),p+=g.move(r.safe(n.title,{before:p,after:o,...g.current()})),p+=g.move(o),h()),p+=g.move(")"),f(),p}function o_(){return"!"}Pg.peek=c_;function Pg(n,i,r,u){const o=n.referenceType,c=r.enter("imageReference");let f=r.enter("label");const h=r.createTracker(u);let g=h.move("![");const p=r.safe(n.alt,{before:g,after:"]",...h.current()});g+=h.move(p+"]["),f();const y=r.stack;r.stack=[],f=r.enter("reference");const x=r.safe(r.associationId(n),{before:g,after:"]",...h.current()});return f(),r.stack=y,c(),o==="full"||!p||p!==x?g+=h.move(x+"]"):o==="shortcut"?g=g.slice(0,-1):g+=h.move("]"),g}function c_(){return"!"}Wg.peek=f_;function Wg(n,i,r){let u=n.value||"",o="`",c=-1;for(;new RegExp("(^|[^`])"+o+"([^`]|$)").test(u);)o+="`";for(/[^ \r\n]/.test(u)&&(/^[ \r\n]/.test(u)&&/[ \r\n]$/.test(u)||/^`|`$/.test(u))&&(u=" "+u+" ");++c\u007F]/.test(n.url))}ty.peek=d_;function ty(n,i,r,u){const o=af(r),c=o==='"'?"Quote":"Apostrophe",f=r.createTracker(u);let h,g;if(ey(n,r)){const y=r.stack;r.stack=[],h=r.enter("autolink");let x=f.move("<");return x+=f.move(r.containerPhrasing(n,{before:x,after:">",...f.current()})),x+=f.move(">"),h(),r.stack=y,x}h=r.enter("link"),g=r.enter("label");let p=f.move("[");return p+=f.move(r.containerPhrasing(n,{before:p,after:"](",...f.current()})),p+=f.move("]("),g(),!n.url&&n.title||/[\0- \u007F]/.test(n.url)?(g=r.enter("destinationLiteral"),p+=f.move("<"),p+=f.move(r.safe(n.url,{before:p,after:">",...f.current()})),p+=f.move(">")):(g=r.enter("destinationRaw"),p+=f.move(r.safe(n.url,{before:p,after:n.title?" ":")",...f.current()}))),g(),n.title&&(g=r.enter(`title${c}`),p+=f.move(" "+o),p+=f.move(r.safe(n.title,{before:p,after:o,...f.current()})),p+=f.move(o),g()),p+=f.move(")"),h(),p}function d_(n,i,r){return ey(n,r)?"<":"["}ny.peek=h_;function ny(n,i,r,u){const o=n.referenceType,c=r.enter("linkReference");let f=r.enter("label");const h=r.createTracker(u);let g=h.move("[");const p=r.containerPhrasing(n,{before:g,after:"]",...h.current()});g+=h.move(p+"]["),f();const y=r.stack;r.stack=[],f=r.enter("reference");const x=r.safe(r.associationId(n),{before:g,after:"]",...h.current()});return f(),r.stack=y,c(),o==="full"||!p||p!==x?g+=h.move(x+"]"):o==="shortcut"?g=g.slice(0,-1):g+=h.move("]"),g}function h_(){return"["}function rf(n){const i=n.options.bullet||"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bullet`, expected `*`, `+`, or `-`");return i}function m_(n){const i=rf(n),r=n.options.bulletOther;if(!r)return i==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===i)throw new Error("Expected `bullet` (`"+i+"`) and `bulletOther` (`"+r+"`) to be different");return r}function p_(n){const i=n.options.bulletOrdered||".";if(i!=="."&&i!==")")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOrdered`, expected `.` or `)`");return i}function ly(n){const i=n.options.rule||"*";if(i!=="*"&&i!=="-"&&i!=="_")throw new Error("Cannot serialize rules with `"+i+"` for `options.rule`, expected `*`, `-`, or `_`");return i}function g_(n,i,r,u){const o=r.enter("list"),c=r.bulletCurrent;let f=n.ordered?p_(r):rf(r);const h=n.ordered?f==="."?")":".":m_(r);let g=i&&r.bulletLastUsed?f===r.bulletLastUsed:!1;if(!n.ordered){const y=n.children?n.children[0]:void 0;if((f==="*"||f==="-")&&y&&(!y.children||!y.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(g=!0),ly(r)===f&&y){let x=-1;for(;++x-1?i.start:1)+(r.options.incrementListMarker===!1?0:i.children.indexOf(n))+c);let f=c.length+1;(o==="tab"||o==="mixed"&&(i&&i.type==="list"&&i.spread||n.spread))&&(f=Math.ceil(f/4)*4);const h=r.createTracker(u);h.move(c+" ".repeat(f-c.length)),h.shift(f);const g=r.enter("listItem"),p=r.indentLines(r.containerFlow(n,h.current()),y);return g(),p;function y(x,v,S){return v?(S?"":" ".repeat(f))+x:(S?c:c+" ".repeat(f-c.length))+x}}function b_(n,i,r,u){const o=r.enter("paragraph"),c=r.enter("phrasing"),f=r.containerPhrasing(n,u);return c(),o(),f}const v_=Vu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function S_(n,i,r,u){return(n.children.some(function(f){return v_(f)})?r.containerPhrasing:r.containerFlow).call(r,n,u)}function __(n){const i=n.options.strong||"*";if(i!=="*"&&i!=="_")throw new Error("Cannot serialize strong with `"+i+"` for `options.strong`, expected `*`, or `_`");return i}iy.peek=k_;function iy(n,i,r,u){const o=__(r),c=r.enter("strong"),f=r.createTracker(u),h=f.move(o+o);let g=f.move(r.containerPhrasing(n,{after:o,before:h,...f.current()}));const p=g.charCodeAt(0),y=Uu(u.before.charCodeAt(u.before.length-1),p,o);y.inside&&(g=ur(p)+g.slice(1));const x=g.charCodeAt(g.length-1),v=Uu(u.after.charCodeAt(0),x,o);v.inside&&(g=g.slice(0,-1)+ur(x));const S=f.move(o+o);return c(),r.attentionEncodeSurroundingInfo={after:v.outside,before:y.outside},h+g+S}function k_(n,i,r){return r.options.strong||"*"}function A_(n,i,r,u){return r.safe(n.value,u)}function w_(n){const i=n.options.ruleRepetition||3;if(i<3)throw new Error("Cannot serialize rules with repetition `"+i+"` for `options.ruleRepetition`, expected `3` or more");return i}function E_(n,i,r){const u=(ly(r)+(r.options.ruleSpaces?" ":"")).repeat(w_(r));return r.options.ruleSpaces?u.slice(0,-1):u}const ay={blockquote:J2,break:Jp,code:t_,definition:l_,emphasis:Jg,hardBreak:Jp,heading:u_,html:$g,image:Ig,imageReference:Pg,inlineCode:Wg,link:ty,linkReference:ny,list:g_,listItem:x_,paragraph:b_,root:S_,strong:iy,text:A_,thematicBreak:E_};function j_(){return{enter:{table:T_,tableData:$p,tableHeader:$p,tableRow:z_},exit:{codeText:N_,table:C_,tableData:Ec,tableHeader:Ec,tableRow:Ec}}}function T_(n){const i=n._align;this.enter({type:"table",align:i.map(function(r){return r==="none"?null:r}),children:[]},n),this.data.inTable=!0}function C_(n){this.exit(n),this.data.inTable=void 0}function z_(n){this.enter({type:"tableRow",children:[]},n)}function Ec(n){this.exit(n)}function $p(n){this.enter({type:"tableCell",children:[]},n)}function N_(n){let i=this.resume();this.data.inTable&&(i=i.replace(/\\([\\|])/g,M_));const r=this.stack[this.stack.length-1];r.type,r.value=i,this.exit(n)}function M_(n,i){return i==="|"?i:n}function D_(n){const i=n||{},r=i.tableCellPadding,u=i.tablePipeAlign,o=i.stringLength,c=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` -`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:v,table:f,tableCell:g,tableRow:h}};function f(S,w,j,q){return p(y(S,j,q),S.align)}function h(S,w,j,q){const N=x(S,j,q),K=p([N]);return K.slice(0,K.indexOf(` -`))}function g(S,w,j,q){const N=j.enter("tableCell"),K=j.enter("phrasing"),Y=j.containerPhrasing(S,{...q,before:c,after:c});return K(),N(),Y}function p(S,w){return F2(S,{align:w,alignDelimiters:u,padding:r,stringLength:o})}function y(S,w,j){const q=S.children;let N=-1;const K=[],Y=w.enter("table");for(;++N0&&!r&&(n[n.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const I_={tokenize:ak,partial:!0};function P_(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:nk,continuation:{tokenize:lk},exit:ik}},text:{91:{name:"gfmFootnoteCall",tokenize:tk},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:W_,resolveTo:ek}}}}function W_(n,i,r){const u=this;let o=u.events.length;const c=u.parser.gfmFootnotes||(u.parser.gfmFootnotes=[]);let f;for(;o--;){const g=u.events[o][1];if(g.type==="labelImage"){f=g;break}if(g.type==="gfmFootnoteCall"||g.type==="labelLink"||g.type==="label"||g.type==="image"||g.type==="link")break}return h;function h(g){if(!f||!f._balanced)return r(g);const p=Tn(u.sliceSerialize({start:f.end,end:u.now()}));return p.codePointAt(0)!==94||!c.includes(p.slice(1))?r(g):(n.enter("gfmFootnoteCallLabelMarker"),n.consume(g),n.exit("gfmFootnoteCallLabelMarker"),i(g))}}function ek(n,i){let r=n.length;for(;r--;)if(n[r][1].type==="labelImage"&&n[r][0]==="enter"){n[r][1];break}n[r+1][1].type="data",n[r+3][1].type="gfmFootnoteCallLabelMarker";const u={type:"gfmFootnoteCall",start:Object.assign({},n[r+3][1].start),end:Object.assign({},n[n.length-1][1].end)},o={type:"gfmFootnoteCallMarker",start:Object.assign({},n[r+3][1].end),end:Object.assign({},n[r+3][1].end)};o.end.column++,o.end.offset++,o.end._bufferIndex++;const c={type:"gfmFootnoteCallString",start:Object.assign({},o.end),end:Object.assign({},n[n.length-1][1].start)},f={type:"chunkString",contentType:"string",start:Object.assign({},c.start),end:Object.assign({},c.end)},h=[n[r+1],n[r+2],["enter",u,i],n[r+3],n[r+4],["enter",o,i],["exit",o,i],["enter",c,i],["enter",f,i],["exit",f,i],["exit",c,i],n[n.length-2],n[n.length-1],["exit",u,i]];return n.splice(r,n.length-r+1,...h),n}function tk(n,i,r){const u=this,o=u.parser.gfmFootnotes||(u.parser.gfmFootnotes=[]);let c=0,f;return h;function h(x){return n.enter("gfmFootnoteCall"),n.enter("gfmFootnoteCallLabelMarker"),n.consume(x),n.exit("gfmFootnoteCallLabelMarker"),g}function g(x){return x!==94?r(x):(n.enter("gfmFootnoteCallMarker"),n.consume(x),n.exit("gfmFootnoteCallMarker"),n.enter("gfmFootnoteCallString"),n.enter("chunkString").contentType="string",p)}function p(x){if(c>999||x===93&&!f||x===null||x===91||tt(x))return r(x);if(x===93){n.exit("chunkString");const v=n.exit("gfmFootnoteCallString");return o.includes(Tn(u.sliceSerialize(v)))?(n.enter("gfmFootnoteCallLabelMarker"),n.consume(x),n.exit("gfmFootnoteCallLabelMarker"),n.exit("gfmFootnoteCall"),i):r(x)}return tt(x)||(f=!0),c++,n.consume(x),x===92?y:p}function y(x){return x===91||x===92||x===93?(n.consume(x),c++,p):p(x)}}function nk(n,i,r){const u=this,o=u.parser.gfmFootnotes||(u.parser.gfmFootnotes=[]);let c,f=0,h;return g;function g(w){return n.enter("gfmFootnoteDefinition")._container=!0,n.enter("gfmFootnoteDefinitionLabel"),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(w),n.exit("gfmFootnoteDefinitionLabelMarker"),p}function p(w){return w===94?(n.enter("gfmFootnoteDefinitionMarker"),n.consume(w),n.exit("gfmFootnoteDefinitionMarker"),n.enter("gfmFootnoteDefinitionLabelString"),n.enter("chunkString").contentType="string",y):r(w)}function y(w){if(f>999||w===93&&!h||w===null||w===91||tt(w))return r(w);if(w===93){n.exit("chunkString");const j=n.exit("gfmFootnoteDefinitionLabelString");return c=Tn(u.sliceSerialize(j)),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(w),n.exit("gfmFootnoteDefinitionLabelMarker"),n.exit("gfmFootnoteDefinitionLabel"),v}return tt(w)||(h=!0),f++,n.consume(w),w===92?x:y}function x(w){return w===91||w===92||w===93?(n.consume(w),f++,y):y(w)}function v(w){return w===58?(n.enter("definitionMarker"),n.consume(w),n.exit("definitionMarker"),o.includes(c)||o.push(c),He(n,S,"gfmFootnoteDefinitionWhitespace")):r(w)}function S(w){return i(w)}}function lk(n,i,r){return n.check(or,i,n.attempt(I_,i,r))}function ik(n){n.exit("gfmFootnoteDefinition")}function ak(n,i,r){const u=this;return He(n,o,"gfmFootnoteDefinitionIndent",5);function o(c){const f=u.events[u.events.length-1];return f&&f[1].type==="gfmFootnoteDefinitionIndent"&&f[2].sliceSerialize(f[1],!0).length===4?i(c):r(c)}}function rk(n){let r=(n||{}).singleTilde;const u={name:"strikethrough",tokenize:c,resolveAll:o};return r==null&&(r=!0),{text:{126:u},insideSpan:{null:[u]},attentionMarkers:{null:[126]}};function o(f,h){let g=-1;for(;++g1?g(w):(f.consume(w),x++,S);if(x<2&&!r)return g(w);const q=f.exit("strikethroughSequenceTemporary"),N=ea(w);return q._open=!N||N===2&&!!j,q._close=!j||j===2&&!!N,h(w)}}}class uk{constructor(){this.map=[]}add(i,r,u){sk(this,i,r,u)}consume(i){if(this.map.sort(function(c,f){return c[0]-f[0]}),this.map.length===0)return;let r=this.map.length;const u=[];for(;r>0;)r-=1,u.push(i.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),i.length=this.map[r][0];u.push(i.slice()),i.length=0;let o=u.pop();for(;o;){for(const c of o)i.push(c);o=u.pop()}this.map.length=0}}function sk(n,i,r,u){let o=0;if(!(r===0&&u.length===0)){for(;o-1;){const re=u.events[Q][1].type;if(re==="lineEnding"||re==="linePrefix")Q--;else break}const W=Q>-1?u.events[Q][1].type:null,de=W==="tableHead"||W==="tableRow"?U:g;return de===U&&u.parser.lazy[u.now().line]?r(R):de(R)}function g(R){return n.enter("tableHead"),n.enter("tableRow"),p(R)}function p(R){return R===124||(f=!0,c+=1),y(R)}function y(R){return R===null?r(R):be(R)?c>1?(c=0,u.interrupt=!0,n.exit("tableRow"),n.enter("lineEnding"),n.consume(R),n.exit("lineEnding"),S):r(R):De(R)?He(n,y,"whitespace")(R):(c+=1,f&&(f=!1,o+=1),R===124?(n.enter("tableCellDivider"),n.consume(R),n.exit("tableCellDivider"),f=!0,y):(n.enter("data"),x(R)))}function x(R){return R===null||R===124||tt(R)?(n.exit("data"),y(R)):(n.consume(R),R===92?v:x)}function v(R){return R===92||R===124?(n.consume(R),x):x(R)}function S(R){return u.interrupt=!1,u.parser.lazy[u.now().line]?r(R):(n.enter("tableDelimiterRow"),f=!1,De(R)?He(n,w,"linePrefix",u.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):w(R))}function w(R){return R===45||R===58?q(R):R===124?(f=!0,n.enter("tableCellDivider"),n.consume(R),n.exit("tableCellDivider"),j):ae(R)}function j(R){return De(R)?He(n,q,"whitespace")(R):q(R)}function q(R){return R===58?(c+=1,f=!0,n.enter("tableDelimiterMarker"),n.consume(R),n.exit("tableDelimiterMarker"),N):R===45?(c+=1,N(R)):R===null||be(R)?se(R):ae(R)}function N(R){return R===45?(n.enter("tableDelimiterFiller"),K(R)):ae(R)}function K(R){return R===45?(n.consume(R),K):R===58?(f=!0,n.exit("tableDelimiterFiller"),n.enter("tableDelimiterMarker"),n.consume(R),n.exit("tableDelimiterMarker"),Y):(n.exit("tableDelimiterFiller"),Y(R))}function Y(R){return De(R)?He(n,se,"whitespace")(R):se(R)}function se(R){return R===124?w(R):R===null||be(R)?!f||o!==c?ae(R):(n.exit("tableDelimiterRow"),n.exit("tableHead"),i(R)):ae(R)}function ae(R){return r(R)}function U(R){return n.enter("tableRow"),ne(R)}function ne(R){return R===124?(n.enter("tableCellDivider"),n.consume(R),n.exit("tableCellDivider"),ne):R===null||be(R)?(n.exit("tableRow"),i(R)):De(R)?He(n,ne,"whitespace")(R):(n.enter("data"),ue(R))}function ue(R){return R===null||R===124||tt(R)?(n.exit("data"),ne(R)):(n.consume(R),R===92?ye:ue)}function ye(R){return R===92||R===124?(n.consume(R),ue):ue(R)}}function dk(n,i){let r=-1,u=!0,o=0,c=[0,0,0,0],f=[0,0,0,0],h=!1,g=0,p,y,x;const v=new uk;for(;++rr[2]+1){const w=r[2]+1,j=r[3]-r[2]-1;n.add(w,j,[])}}n.add(r[3]+1,0,[["exit",x,i]])}return o!==void 0&&(c.end=Object.assign({},Pi(i.events,o)),n.add(o,0,[["exit",c,i]]),c=void 0),c}function Pp(n,i,r,u,o){const c=[],f=Pi(i.events,r);o&&(o.end=Object.assign({},f),c.push(["exit",o,i])),u.end=Object.assign({},f),c.push(["exit",u,i]),n.add(r+1,0,c)}function Pi(n,i){const r=n[i],u=r[0]==="enter"?"start":"end";return r[1][u]}const hk={name:"tasklistCheck",tokenize:pk};function mk(){return{text:{91:hk}}}function pk(n,i,r){const u=this;return o;function o(g){return u.previous!==null||!u._gfmTasklistFirstContentOfListItem?r(g):(n.enter("taskListCheck"),n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),c)}function c(g){return tt(g)?(n.enter("taskListCheckValueUnchecked"),n.consume(g),n.exit("taskListCheckValueUnchecked"),f):g===88||g===120?(n.enter("taskListCheckValueChecked"),n.consume(g),n.exit("taskListCheckValueChecked"),f):r(g)}function f(g){return g===93?(n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),n.exit("taskListCheck"),h):r(g)}function h(g){return be(g)?i(g):De(g)?n.check({tokenize:gk},i,r)(g):r(g)}}function gk(n,i,r){return He(n,u,"whitespace");function u(o){return o===null?r(o):i(o)}}function yk(n){return kg([Y_(),P_(),rk(n),ck(),mk()])}const xk={};function bk(n){const i=this,r=n||xk,u=i.data(),o=u.micromarkExtensions||(u.micromarkExtensions=[]),c=u.fromMarkdownExtensions||(u.fromMarkdownExtensions=[]),f=u.toMarkdownExtensions||(u.toMarkdownExtensions=[]);o.push(yk(r)),c.push(U_()),f.push(H_(r))}/** +`,...c.current()});return/^[\t ]/.test(p)&&(p=ur(p.charCodeAt(0))+p.slice(1)),p=p?f+" "+p:f,r.options.closeAtx&&(p+=" "+f),g(),h(),p}$g.peek=s_;function $g(n){return n.value||""}function s_(){return"<"}Ig.peek=o_;function Ig(n,i,r,u){const o=af(r),c=o==='"'?"Quote":"Apostrophe",f=r.enter("image");let h=r.enter("label");const g=r.createTracker(u);let p=g.move("![");return p+=g.move(r.safe(n.alt,{before:p,after:"]",...g.current()})),p+=g.move("]("),h(),!n.url&&n.title||/[\0- \u007F]/.test(n.url)?(h=r.enter("destinationLiteral"),p+=g.move("<"),p+=g.move(r.safe(n.url,{before:p,after:">",...g.current()})),p+=g.move(">")):(h=r.enter("destinationRaw"),p+=g.move(r.safe(n.url,{before:p,after:n.title?" ":")",...g.current()}))),h(),n.title&&(h=r.enter(`title${c}`),p+=g.move(" "+o),p+=g.move(r.safe(n.title,{before:p,after:o,...g.current()})),p+=g.move(o),h()),p+=g.move(")"),f(),p}function o_(){return"!"}Pg.peek=c_;function Pg(n,i,r,u){const o=n.referenceType,c=r.enter("imageReference");let f=r.enter("label");const h=r.createTracker(u);let g=h.move("![");const p=r.safe(n.alt,{before:g,after:"]",...h.current()});g+=h.move(p+"]["),f();const y=r.stack;r.stack=[],f=r.enter("reference");const x=r.safe(r.associationId(n),{before:g,after:"]",...h.current()});return f(),r.stack=y,c(),o==="full"||!p||p!==x?g+=h.move(x+"]"):o==="shortcut"?g=g.slice(0,-1):g+=h.move("]"),g}function c_(){return"!"}Wg.peek=f_;function Wg(n,i,r){let u=n.value||"",o="`",c=-1;for(;new RegExp("(^|[^`])"+o+"([^`]|$)").test(u);)o+="`";for(/[^ \r\n]/.test(u)&&(/^[ \r\n]/.test(u)&&/[ \r\n]$/.test(u)||/^`|`$/.test(u))&&(u=" "+u+" ");++c\u007F]/.test(n.url))}ty.peek=d_;function ty(n,i,r,u){const o=af(r),c=o==='"'?"Quote":"Apostrophe",f=r.createTracker(u);let h,g;if(ey(n,r)){const y=r.stack;r.stack=[],h=r.enter("autolink");let x=f.move("<");return x+=f.move(r.containerPhrasing(n,{before:x,after:">",...f.current()})),x+=f.move(">"),h(),r.stack=y,x}h=r.enter("link"),g=r.enter("label");let p=f.move("[");return p+=f.move(r.containerPhrasing(n,{before:p,after:"](",...f.current()})),p+=f.move("]("),g(),!n.url&&n.title||/[\0- \u007F]/.test(n.url)?(g=r.enter("destinationLiteral"),p+=f.move("<"),p+=f.move(r.safe(n.url,{before:p,after:">",...f.current()})),p+=f.move(">")):(g=r.enter("destinationRaw"),p+=f.move(r.safe(n.url,{before:p,after:n.title?" ":")",...f.current()}))),g(),n.title&&(g=r.enter(`title${c}`),p+=f.move(" "+o),p+=f.move(r.safe(n.title,{before:p,after:o,...f.current()})),p+=f.move(o),g()),p+=f.move(")"),h(),p}function d_(n,i,r){return ey(n,r)?"<":"["}ny.peek=h_;function ny(n,i,r,u){const o=n.referenceType,c=r.enter("linkReference");let f=r.enter("label");const h=r.createTracker(u);let g=h.move("[");const p=r.containerPhrasing(n,{before:g,after:"]",...h.current()});g+=h.move(p+"]["),f();const y=r.stack;r.stack=[],f=r.enter("reference");const x=r.safe(r.associationId(n),{before:g,after:"]",...h.current()});return f(),r.stack=y,c(),o==="full"||!p||p!==x?g+=h.move(x+"]"):o==="shortcut"?g=g.slice(0,-1):g+=h.move("]"),g}function h_(){return"["}function rf(n){const i=n.options.bullet||"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bullet`, expected `*`, `+`, or `-`");return i}function m_(n){const i=rf(n),r=n.options.bulletOther;if(!r)return i==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===i)throw new Error("Expected `bullet` (`"+i+"`) and `bulletOther` (`"+r+"`) to be different");return r}function p_(n){const i=n.options.bulletOrdered||".";if(i!=="."&&i!==")")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOrdered`, expected `.` or `)`");return i}function ly(n){const i=n.options.rule||"*";if(i!=="*"&&i!=="-"&&i!=="_")throw new Error("Cannot serialize rules with `"+i+"` for `options.rule`, expected `*`, `-`, or `_`");return i}function g_(n,i,r,u){const o=r.enter("list"),c=r.bulletCurrent;let f=n.ordered?p_(r):rf(r);const h=n.ordered?f==="."?")":".":m_(r);let g=i&&r.bulletLastUsed?f===r.bulletLastUsed:!1;if(!n.ordered){const y=n.children?n.children[0]:void 0;if((f==="*"||f==="-")&&y&&(!y.children||!y.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(g=!0),ly(r)===f&&y){let x=-1;for(;++x-1?i.start:1)+(r.options.incrementListMarker===!1?0:i.children.indexOf(n))+c);let f=c.length+1;(o==="tab"||o==="mixed"&&(i&&i.type==="list"&&i.spread||n.spread))&&(f=Math.ceil(f/4)*4);const h=r.createTracker(u);h.move(c+" ".repeat(f-c.length)),h.shift(f);const g=r.enter("listItem"),p=r.indentLines(r.containerFlow(n,h.current()),y);return g(),p;function y(x,b,S){return b?(S?"":" ".repeat(f))+x:(S?c:c+" ".repeat(f-c.length))+x}}function v_(n,i,r,u){const o=r.enter("paragraph"),c=r.enter("phrasing"),f=r.containerPhrasing(n,u);return c(),o(),f}const b_=Vu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function S_(n,i,r,u){return(n.children.some(function(f){return b_(f)})?r.containerPhrasing:r.containerFlow).call(r,n,u)}function __(n){const i=n.options.strong||"*";if(i!=="*"&&i!=="_")throw new Error("Cannot serialize strong with `"+i+"` for `options.strong`, expected `*`, or `_`");return i}iy.peek=k_;function iy(n,i,r,u){const o=__(r),c=r.enter("strong"),f=r.createTracker(u),h=f.move(o+o);let g=f.move(r.containerPhrasing(n,{after:o,before:h,...f.current()}));const p=g.charCodeAt(0),y=Uu(u.before.charCodeAt(u.before.length-1),p,o);y.inside&&(g=ur(p)+g.slice(1));const x=g.charCodeAt(g.length-1),b=Uu(u.after.charCodeAt(0),x,o);b.inside&&(g=g.slice(0,-1)+ur(x));const S=f.move(o+o);return c(),r.attentionEncodeSurroundingInfo={after:b.outside,before:y.outside},h+g+S}function k_(n,i,r){return r.options.strong||"*"}function A_(n,i,r,u){return r.safe(n.value,u)}function w_(n){const i=n.options.ruleRepetition||3;if(i<3)throw new Error("Cannot serialize rules with repetition `"+i+"` for `options.ruleRepetition`, expected `3` or more");return i}function E_(n,i,r){const u=(ly(r)+(r.options.ruleSpaces?" ":"")).repeat(w_(r));return r.options.ruleSpaces?u.slice(0,-1):u}const ay={blockquote:J2,break:Jp,code:t_,definition:l_,emphasis:Jg,hardBreak:Jp,heading:u_,html:$g,image:Ig,imageReference:Pg,inlineCode:Wg,link:ty,linkReference:ny,list:g_,listItem:x_,paragraph:v_,root:S_,strong:iy,text:A_,thematicBreak:E_};function j_(){return{enter:{table:T_,tableData:$p,tableHeader:$p,tableRow:z_},exit:{codeText:N_,table:C_,tableData:Ec,tableHeader:Ec,tableRow:Ec}}}function T_(n){const i=n._align;this.enter({type:"table",align:i.map(function(r){return r==="none"?null:r}),children:[]},n),this.data.inTable=!0}function C_(n){this.exit(n),this.data.inTable=void 0}function z_(n){this.enter({type:"tableRow",children:[]},n)}function Ec(n){this.exit(n)}function $p(n){this.enter({type:"tableCell",children:[]},n)}function N_(n){let i=this.resume();this.data.inTable&&(i=i.replace(/\\([\\|])/g,M_));const r=this.stack[this.stack.length-1];r.type,r.value=i,this.exit(n)}function M_(n,i){return i==="|"?i:n}function D_(n){const i=n||{},r=i.tableCellPadding,u=i.tablePipeAlign,o=i.stringLength,c=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` +`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:b,table:f,tableCell:g,tableRow:h}};function f(S,w,j,q){return p(y(S,j,q),S.align)}function h(S,w,j,q){const N=x(S,j,q),K=p([N]);return K.slice(0,K.indexOf(` +`))}function g(S,w,j,q){const N=j.enter("tableCell"),K=j.enter("phrasing"),Y=j.containerPhrasing(S,{...q,before:c,after:c});return K(),N(),Y}function p(S,w){return F2(S,{align:w,alignDelimiters:u,padding:r,stringLength:o})}function y(S,w,j){const q=S.children;let N=-1;const K=[],Y=w.enter("table");for(;++N0&&!r&&(n[n.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const I_={tokenize:ak,partial:!0};function P_(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:nk,continuation:{tokenize:lk},exit:ik}},text:{91:{name:"gfmFootnoteCall",tokenize:tk},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:W_,resolveTo:ek}}}}function W_(n,i,r){const u=this;let o=u.events.length;const c=u.parser.gfmFootnotes||(u.parser.gfmFootnotes=[]);let f;for(;o--;){const g=u.events[o][1];if(g.type==="labelImage"){f=g;break}if(g.type==="gfmFootnoteCall"||g.type==="labelLink"||g.type==="label"||g.type==="image"||g.type==="link")break}return h;function h(g){if(!f||!f._balanced)return r(g);const p=Tn(u.sliceSerialize({start:f.end,end:u.now()}));return p.codePointAt(0)!==94||!c.includes(p.slice(1))?r(g):(n.enter("gfmFootnoteCallLabelMarker"),n.consume(g),n.exit("gfmFootnoteCallLabelMarker"),i(g))}}function ek(n,i){let r=n.length;for(;r--;)if(n[r][1].type==="labelImage"&&n[r][0]==="enter"){n[r][1];break}n[r+1][1].type="data",n[r+3][1].type="gfmFootnoteCallLabelMarker";const u={type:"gfmFootnoteCall",start:Object.assign({},n[r+3][1].start),end:Object.assign({},n[n.length-1][1].end)},o={type:"gfmFootnoteCallMarker",start:Object.assign({},n[r+3][1].end),end:Object.assign({},n[r+3][1].end)};o.end.column++,o.end.offset++,o.end._bufferIndex++;const c={type:"gfmFootnoteCallString",start:Object.assign({},o.end),end:Object.assign({},n[n.length-1][1].start)},f={type:"chunkString",contentType:"string",start:Object.assign({},c.start),end:Object.assign({},c.end)},h=[n[r+1],n[r+2],["enter",u,i],n[r+3],n[r+4],["enter",o,i],["exit",o,i],["enter",c,i],["enter",f,i],["exit",f,i],["exit",c,i],n[n.length-2],n[n.length-1],["exit",u,i]];return n.splice(r,n.length-r+1,...h),n}function tk(n,i,r){const u=this,o=u.parser.gfmFootnotes||(u.parser.gfmFootnotes=[]);let c=0,f;return h;function h(x){return n.enter("gfmFootnoteCall"),n.enter("gfmFootnoteCallLabelMarker"),n.consume(x),n.exit("gfmFootnoteCallLabelMarker"),g}function g(x){return x!==94?r(x):(n.enter("gfmFootnoteCallMarker"),n.consume(x),n.exit("gfmFootnoteCallMarker"),n.enter("gfmFootnoteCallString"),n.enter("chunkString").contentType="string",p)}function p(x){if(c>999||x===93&&!f||x===null||x===91||tt(x))return r(x);if(x===93){n.exit("chunkString");const b=n.exit("gfmFootnoteCallString");return o.includes(Tn(u.sliceSerialize(b)))?(n.enter("gfmFootnoteCallLabelMarker"),n.consume(x),n.exit("gfmFootnoteCallLabelMarker"),n.exit("gfmFootnoteCall"),i):r(x)}return tt(x)||(f=!0),c++,n.consume(x),x===92?y:p}function y(x){return x===91||x===92||x===93?(n.consume(x),c++,p):p(x)}}function nk(n,i,r){const u=this,o=u.parser.gfmFootnotes||(u.parser.gfmFootnotes=[]);let c,f=0,h;return g;function g(w){return n.enter("gfmFootnoteDefinition")._container=!0,n.enter("gfmFootnoteDefinitionLabel"),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(w),n.exit("gfmFootnoteDefinitionLabelMarker"),p}function p(w){return w===94?(n.enter("gfmFootnoteDefinitionMarker"),n.consume(w),n.exit("gfmFootnoteDefinitionMarker"),n.enter("gfmFootnoteDefinitionLabelString"),n.enter("chunkString").contentType="string",y):r(w)}function y(w){if(f>999||w===93&&!h||w===null||w===91||tt(w))return r(w);if(w===93){n.exit("chunkString");const j=n.exit("gfmFootnoteDefinitionLabelString");return c=Tn(u.sliceSerialize(j)),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(w),n.exit("gfmFootnoteDefinitionLabelMarker"),n.exit("gfmFootnoteDefinitionLabel"),b}return tt(w)||(h=!0),f++,n.consume(w),w===92?x:y}function x(w){return w===91||w===92||w===93?(n.consume(w),f++,y):y(w)}function b(w){return w===58?(n.enter("definitionMarker"),n.consume(w),n.exit("definitionMarker"),o.includes(c)||o.push(c),He(n,S,"gfmFootnoteDefinitionWhitespace")):r(w)}function S(w){return i(w)}}function lk(n,i,r){return n.check(or,i,n.attempt(I_,i,r))}function ik(n){n.exit("gfmFootnoteDefinition")}function ak(n,i,r){const u=this;return He(n,o,"gfmFootnoteDefinitionIndent",5);function o(c){const f=u.events[u.events.length-1];return f&&f[1].type==="gfmFootnoteDefinitionIndent"&&f[2].sliceSerialize(f[1],!0).length===4?i(c):r(c)}}function rk(n){let r=(n||{}).singleTilde;const u={name:"strikethrough",tokenize:c,resolveAll:o};return r==null&&(r=!0),{text:{126:u},insideSpan:{null:[u]},attentionMarkers:{null:[126]}};function o(f,h){let g=-1;for(;++g1?g(w):(f.consume(w),x++,S);if(x<2&&!r)return g(w);const q=f.exit("strikethroughSequenceTemporary"),N=ea(w);return q._open=!N||N===2&&!!j,q._close=!j||j===2&&!!N,h(w)}}}class uk{constructor(){this.map=[]}add(i,r,u){sk(this,i,r,u)}consume(i){if(this.map.sort(function(c,f){return c[0]-f[0]}),this.map.length===0)return;let r=this.map.length;const u=[];for(;r>0;)r-=1,u.push(i.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),i.length=this.map[r][0];u.push(i.slice()),i.length=0;let o=u.pop();for(;o;){for(const c of o)i.push(c);o=u.pop()}this.map.length=0}}function sk(n,i,r,u){let o=0;if(!(r===0&&u.length===0)){for(;o-1;){const re=u.events[Q][1].type;if(re==="lineEnding"||re==="linePrefix")Q--;else break}const W=Q>-1?u.events[Q][1].type:null,de=W==="tableHead"||W==="tableRow"?U:g;return de===U&&u.parser.lazy[u.now().line]?r(R):de(R)}function g(R){return n.enter("tableHead"),n.enter("tableRow"),p(R)}function p(R){return R===124||(f=!0,c+=1),y(R)}function y(R){return R===null?r(R):ve(R)?c>1?(c=0,u.interrupt=!0,n.exit("tableRow"),n.enter("lineEnding"),n.consume(R),n.exit("lineEnding"),S):r(R):De(R)?He(n,y,"whitespace")(R):(c+=1,f&&(f=!1,o+=1),R===124?(n.enter("tableCellDivider"),n.consume(R),n.exit("tableCellDivider"),f=!0,y):(n.enter("data"),x(R)))}function x(R){return R===null||R===124||tt(R)?(n.exit("data"),y(R)):(n.consume(R),R===92?b:x)}function b(R){return R===92||R===124?(n.consume(R),x):x(R)}function S(R){return u.interrupt=!1,u.parser.lazy[u.now().line]?r(R):(n.enter("tableDelimiterRow"),f=!1,De(R)?He(n,w,"linePrefix",u.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):w(R))}function w(R){return R===45||R===58?q(R):R===124?(f=!0,n.enter("tableCellDivider"),n.consume(R),n.exit("tableCellDivider"),j):ae(R)}function j(R){return De(R)?He(n,q,"whitespace")(R):q(R)}function q(R){return R===58?(c+=1,f=!0,n.enter("tableDelimiterMarker"),n.consume(R),n.exit("tableDelimiterMarker"),N):R===45?(c+=1,N(R)):R===null||ve(R)?se(R):ae(R)}function N(R){return R===45?(n.enter("tableDelimiterFiller"),K(R)):ae(R)}function K(R){return R===45?(n.consume(R),K):R===58?(f=!0,n.exit("tableDelimiterFiller"),n.enter("tableDelimiterMarker"),n.consume(R),n.exit("tableDelimiterMarker"),Y):(n.exit("tableDelimiterFiller"),Y(R))}function Y(R){return De(R)?He(n,se,"whitespace")(R):se(R)}function se(R){return R===124?w(R):R===null||ve(R)?!f||o!==c?ae(R):(n.exit("tableDelimiterRow"),n.exit("tableHead"),i(R)):ae(R)}function ae(R){return r(R)}function U(R){return n.enter("tableRow"),ne(R)}function ne(R){return R===124?(n.enter("tableCellDivider"),n.consume(R),n.exit("tableCellDivider"),ne):R===null||ve(R)?(n.exit("tableRow"),i(R)):De(R)?He(n,ne,"whitespace")(R):(n.enter("data"),ue(R))}function ue(R){return R===null||R===124||tt(R)?(n.exit("data"),ne(R)):(n.consume(R),R===92?ye:ue)}function ye(R){return R===92||R===124?(n.consume(R),ue):ue(R)}}function dk(n,i){let r=-1,u=!0,o=0,c=[0,0,0,0],f=[0,0,0,0],h=!1,g=0,p,y,x;const b=new uk;for(;++rr[2]+1){const w=r[2]+1,j=r[3]-r[2]-1;n.add(w,j,[])}}n.add(r[3]+1,0,[["exit",x,i]])}return o!==void 0&&(c.end=Object.assign({},Pi(i.events,o)),n.add(o,0,[["exit",c,i]]),c=void 0),c}function Pp(n,i,r,u,o){const c=[],f=Pi(i.events,r);o&&(o.end=Object.assign({},f),c.push(["exit",o,i])),u.end=Object.assign({},f),c.push(["exit",u,i]),n.add(r+1,0,c)}function Pi(n,i){const r=n[i],u=r[0]==="enter"?"start":"end";return r[1][u]}const hk={name:"tasklistCheck",tokenize:pk};function mk(){return{text:{91:hk}}}function pk(n,i,r){const u=this;return o;function o(g){return u.previous!==null||!u._gfmTasklistFirstContentOfListItem?r(g):(n.enter("taskListCheck"),n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),c)}function c(g){return tt(g)?(n.enter("taskListCheckValueUnchecked"),n.consume(g),n.exit("taskListCheckValueUnchecked"),f):g===88||g===120?(n.enter("taskListCheckValueChecked"),n.consume(g),n.exit("taskListCheckValueChecked"),f):r(g)}function f(g){return g===93?(n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),n.exit("taskListCheck"),h):r(g)}function h(g){return ve(g)?i(g):De(g)?n.check({tokenize:gk},i,r)(g):r(g)}}function gk(n,i,r){return He(n,u,"whitespace");function u(o){return o===null?r(o):i(o)}}function yk(n){return kg([Y_(),P_(),rk(n),ck(),mk()])}const xk={};function vk(n){const i=this,r=n||xk,u=i.data(),o=u.micromarkExtensions||(u.micromarkExtensions=[]),c=u.fromMarkdownExtensions||(u.fromMarkdownExtensions=[]),f=u.toMarkdownExtensions||(u.toMarkdownExtensions=[]);o.push(yk(r)),c.push(U_()),f.push(H_(r))}/** * @license lucide-react v0.468.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const vk=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),my=(...n)=>n.filter((i,r,u)=>!!i&&i.trim()!==""&&u.indexOf(i)===r).join(" ").trim();/** + */const bk=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),my=(...n)=>n.filter((i,r,u)=>!!i&&i.trim()!==""&&u.indexOf(i)===r).join(" ").trim();/** * @license lucide-react v0.468.0 - ISC * * This source code is licensed under the ISC license. @@ -94,7 +94,7 @@ Error generating stack: `+a.message+` * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const at=(n,i)=>{const r=ie.forwardRef(({className:u,...o},c)=>ie.createElement(_k,{ref:c,iconNode:i,className:my(`lucide-${vk(n)}`,u),...o}));return r.displayName=`${n}`,r};/** + */const at=(n,i)=>{const r=ie.forwardRef(({className:u,...o},c)=>ie.createElement(_k,{ref:c,iconNode:i,className:my(`lucide-${bk(n)}`,u),...o}));return r.displayName=`${n}`,r};/** * @license lucide-react v0.468.0 - ISC * * This source code is licensed under the ISC license. @@ -194,7 +194,7 @@ Error generating stack: `+a.message+` * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const by=at("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** + */const vy=at("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** * @license lucide-react v0.468.0 - ISC * * This source code is licensed under the ISC license. @@ -219,17 +219,17 @@ Error generating stack: `+a.message+` * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Hk=at("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);function qk(){const n=document.querySelector('script[type="module"][src]');if(n!=null&&n.src)return new URL("../",n.src).pathname;const i=window.location.pathname;return i.endsWith("/")?i:`${i}/`}const of=qk(),eg="areno-dashboard-language",vy={Overview:"概览",Jobs:"任务",Runtime:"运行环境",Launcher:"任务启动",Agent:"智能助手","Operations Overview":"运行概览","Runtime health, active work, and the signals that need attention.":"查看运行环境、活跃任务和需要关注的信号。","Runtime Environment":"运行环境","Review areno check, areno env, dependencies, GPU state, and repository context.":"检查 AReno 环境、依赖、GPU 状态和仓库上下文。","Task Launcher":"任务启动","Start low-intrusion AReno train or serve subprocesses from explicit configs.":"通过明确配置启动 AReno 训练或服务进程。","Agent Console":"智能助手","Chat with an operations agent using the selected job context.":"基于所选任务上下文与运维助手对话。","Running Job Summary":"运行任务摘要","Current health, route, and stage progression for the latest job.":"最新任务的健康状态、运行路径和阶段进度。",Metrics:"指标","Switch between reward and loss for the latest job.":"切换查看最新任务的奖励、损失及训练指标。","Runtime attention":"运行环境提醒","Highest-priority environment finding.":"当前最高优先级的环境问题。","Quick actions":"快捷操作","Short paths into common workflows.":"快速执行常用工作流。","Latest health":"最新健康指标","Active jobs":"活跃任务","No signal":"暂无信号","Waiting for metrics":"等待指标上报",Reward:"奖励",Loss:"损失","Grad Norm":"梯度范数","Sequence Length":"序列长度","Job Detail: Overview":"任务详情:概览","Rollout Sample":"采样样例","Environment Checks":"环境检查","Runtime requirements, compatibility, and actionable diagnostics.":"运行要求、兼容性和可执行诊断。","GPU Cards":"GPU 状态","Memory pressure and utilization before launch.":"启动前的显存压力和利用率。",Details:"详情","Run Check":"运行检查",Fix:"修复","Starting...":"正在启动…","Installing...":"正在安装…",Installed:"已安装","Retry fix":"重试修复",Ready:"就绪","Needs attention":"需要关注",Checking:"检查中","Dependency Risk":"依赖风险","No checks reported":"暂无检查结果","No GPUs reported":"暂无 GPU 信息","No metrics available":"暂无指标","No rollout sample captured yet.":"尚未记录采样样例。","No TensorBoard scalar points loaded yet.":"尚未加载 TensorBoard 标量数据。","Loading selected metric...":"正在加载所选指标…",Open:"打开","Back to Jobs":"返回任务列表","Stop job":"停止任务",Stop:"停止",Prev:"上一页",Next:"下一页",All:"全部",Running:"运行中",Failed:"失败",Stopped:"已停止",Config:"配置",Logs:"日志","Command Preview":"命令预览",Preflight:"预检","Start Train":"启动训练","Start Serve":"启动服务",Send:"发送","New Chat":"新对话",Settings:"设置",Chat:"对话",History:"历史","Error Recovery":"错误恢复","Suggested Follow-ups":"建议追问",Done:"完成","Toggle theme":"切换主题","Translate to Chinese":"切换为中文","Translate to English":"切换为英文","Ask about this job, its metrics, or recent logs...":"询问此任务的指标、运行状态或最近日志…","Ask about the runtime or describe a task to launch...":"询问运行环境,或描述要启动的任务…","Message the operations agent":"向运维助手发送消息"},Gk=Object.fromEntries(Object.entries(vy).map(([n,i])=>[i,n]));async function Pe(n,i){const r=await fetch(`${of}${n.replace(/^\//,"")}`,{headers:{"Content-Type":"application/json",...(i==null?void 0:i.headers)||{}},...i}),u=await r.text(),o=u?JSON.parse(u):{};if(!r.ok)throw new Error(o.error||r.statusText);return o}function dt(...n){return n.filter(Boolean).join(" ")}function tg(n,i){if(!n)return;const r=i==="zh"?vy:Gk,u="pre, code, .mono, .chatMessages, .runtimeCommandResult, .commandPreview",o=document.createTreeWalker(n,NodeFilter.SHOW_TEXT);let c=o.nextNode();for(;c;){const f=c.parentElement;if(f&&!f.closest(u)){const h=c.nodeValue.trim(),g=r[h];g&&(c.nodeValue=c.nodeValue.replace(h,g))}c=o.nextNode()}for(const f of n.querySelectorAll("[title], [placeholder], [aria-label]"))if(!f.closest(u))for(const h of["title","placeholder","aria-label"]){const g=f.getAttribute(h);g&&r[g]&&f.setAttribute(h,r[g])}}function Bn(n,i=2500,r=[]){const[u,o]=ie.useState(null),c=async()=>{try{const f=await n();o(f)}catch{}};return ie.useEffect(()=>{c();const f=setInterval(c,i);return()=>clearInterval(f)},r),{data:u,refresh:c}}const Rl=[{role:"assistant",content:"Select a job, then ask about metrics, runtime, logs, or how to start the next AReno task."}],ng=[{role:"assistant",content:"选择一个任务,然后询问指标、运行环境、日志,或如何启动下一个 AReno 任务。"}],Yk="areno-dashboard-agent-chat",Sy="areno-dashboard-agent-chat-sessions",lg="areno-dashboard-agent-active-chat",ig="areno-dashboard-agent-draft",jc="areno-dashboard-agent-failure";function Vk(){try{const n=JSON.parse(localStorage.getItem(Yk)||"[]");return Array.isArray(n)&&n.length?n:Rl}catch{return Rl}}function Ou(n=Rl,i="New chat"){const r=Date.now();return{id:`chat-${r}-${Math.random().toString(16).slice(2)}`,title:i,createdAt:r,updatedAt:r,messages:n,followUps:[]}}function Qk(){try{const n=JSON.parse(localStorage.getItem(Sy)||"[]");if(Array.isArray(n)&&n.length)return n.map(i=>{var r;return{...i,messages:(r=i.messages)!=null&&r.length?i.messages:Rl,followUps:Array.isArray(i.followUps)?i.followUps:[]}})}catch{}return[Ou(Vk(),"Default chat")]}function Xk(n,i="New chat"){const r=n.find(o=>o.role==="user"&&o.content);if(!r)return i;const u=r.content.replace(/\s+/g," ").trim();return u.length>42?`${u.slice(0,42)}...`:u}const Zk={ckpt:"",dataset_path:"",dataset_loader_fn:"",reward_fn_path:"",ref_ckpt:"",reward_ckpt:"",critic_ckpt:"",agent_fn:"",algo:"sft",model_hub:"modelscope",epochs:10,max_steps:5,world_size:1,tp_size:1,attn_backend:"flash",activation_checkpointing:!0,drop_rollout_state:!1,eager_decode:!1,disable_thinking:!1,batch_size:8,n_samples:8,mini_bs:1,score_micro_bs:8,gradient_accumulation_steps:"",max_prompt_tokens:1024,max_context_len:2048,max_new_tokens:1024,max_running_prompts:"",temperature:1,top_k:-1,top_p:1,greedy:!1,train_tool_results:!1,lr:1e-6,min_lr:1e-7,lr_decay_steps:1e3,lr_decay_style:"cosine",adam_beta1:.9,adam_beta2:.999,adam_8bit:!1,unfreeze_multimodal_tower:!1,unfreeze_multimodal_projector:!1,multimodal_tower_lr:"",multimodal_tower_min_lr:"",multimodal_tower_lr_decay_steps:"",multimodal_tower_lr_decay_style:"",multimodal_projector_lr:"",multimodal_projector_min_lr:"",multimodal_projector_lr_decay_steps:"",multimodal_projector_lr_decay_style:"",weight_decay:.01,grad_clip_norm:1,gspo_clip_eps:3e-4,grpo_clip_eps:.2,dpo_beta:.1,critic_warmup_steps:20,critic_lr:1e-5,use_kl_loss:!0,kl_loss_coef:.001,kl_loss_type:"low_var_kl",clip_eps:.2,clip_ratio_c:3,value_clip_eps:.5,value_loss_coef:.5,gamma:1,lam:.95,tune_params:!1,mem_frac:.9,tune_max_samples:256,save_path:"outputs/dashboard-run",save_interval:100,metrics_dir:"outputs/dashboard-run/metrics",extra_args:""},Fk={model_path:"",model_hub:"modelscope",host:"0.0.0.0",port:8e3,world_size:1,tp_size:1,max_running_prompts:16,default_max_tokens:1024,decode_progress_interval_s:0,attn_backend:"flash",eager_decode:!1,disable_thinking:!1,extra_args:""};function Kk(){var jt,Yn,yi,pr,gr;const[n,i]=ie.useState(null),[r,u]=ie.useState(Zk),[o,c]=ie.useState(Fk),[f,h]=ie.useState(()=>localStorage.getItem(ig)||""),[g,p]=ie.useState(()=>Qk()),[y,x]=ie.useState(()=>localStorage.getItem(lg)||""),[v,S]=ie.useState("chat"),[w,j]=ie.useState(()=>{try{return JSON.parse(localStorage.getItem("areno-dashboard-agent-provider")||"{}")}catch{return{}}}),[q,N]=ie.useState("overview"),[K,Y]=ie.useState("all"),[se,ae]=ie.useState("train"),[U,ne]=ie.useState(()=>localStorage.getItem("areno-dashboard-theme-v2")||"light"),[ue,ye]=ie.useState(()=>localStorage.getItem(eg)||"en"),[R,Q]=ie.useState(""),[W,de]=ie.useState(!1),[re,I]=ie.useState(1),[M,J]=ie.useState(!1),[P,xe]=ie.useState(0),[A,T]=ie.useState(!1),[G,k]=ie.useState(()=>{try{return JSON.parse(localStorage.getItem(jc)||"null")}catch{return null}}),[le,pe]=ie.useState(!1),[he,je]=ie.useState(null),[we,Ue]=ie.useState(null),At=ie.useRef(null),nt=Bn(()=>Pe("/api/env"),5e3),Dt=Bn(()=>Pe("/api/jobs"),2e3),si=Bn(()=>n?Pe(`/api/jobs/${n}`):Promise.resolve(null),3e3,[n]),Ut=Bn(()=>Pe("/api/runtime/attention"),5e3),sl=Bn(()=>we!=null&&we.jobId?Pe(`/api/jobs/${we.jobId}`):Promise.resolve(null),1e3,[we==null?void 0:we.jobId]),ol=Bn(()=>Pe("/api/quick-actions"),3e4),oi=Bn(()=>Pe("/api/launcher/presets"),3e4),qn=Bn(()=>Pe(`/api/agent/recovery${n?`?job_id=${encodeURIComponent(n)}`:""}`),3e3,[n]),Ht=(((jt=Dt.data)==null?void 0:jt.jobs)||[]).filter(F=>F.kind!=="runtime-repair"),Yt=((Yn=sl.data)==null?void 0:Yn.job)||(we==null?void 0:we.job)||null,Wt=K==="all"?Ht:Ht.filter(F=>F.status===K),Cn=3,kn=Math.max(1,Math.ceil(Wt.length/Cn)),ut=Math.min(re,kn),ia=Wt.slice((ut-1)*Cn,ut*Cn),B=((yi=si.data)==null?void 0:yi.job)||(n?Ht.find(F=>F.id===n):null)||null,te=Ay(Ht),ve=Bn(()=>te?Pe(`/api/jobs/${te.id}`):Promise.resolve(null),3e3,[te==null?void 0:te.id]),Ce=te&&((gr=(pr=ve.data)==null?void 0:pr.job)==null?void 0:gr.id)===te.id?ve.data.job:te,Oe=ie.useMemo(()=>g.find(F=>F.id===y)||g[0]||Ou(),[g,y]),St=Oe.messages||Rl,fn=Oe.followUps||[];ie.useEffect(()=>{n&&Ht.length&&!Ht.some(F=>F.id===n)&&i(null)},[Ht.length,n]),ie.useEffect(()=>{re>kn&&I(kn)},[re,kn]),ie.useEffect(()=>{const F=String((Yt==null?void 0:Yt.status)||"").toLowerCase();!we||we.refreshed||!["succeeded","failed","stopped"].includes(F)||(Ue($=>$&&{...$,refreshed:!0}),(async()=>{try{await Pe("/api/runtime/refresh",{method:"POST",body:"{}"}),await Promise.all([nt.refresh(),Ut.refresh(),Dt.refresh()])}catch($){Q($.message||String($))}})())},[we,Yt==null?void 0:Yt.status]),ie.useEffect(()=>{document.documentElement.dataset.theme=U,localStorage.setItem("areno-dashboard-theme-v2",U)},[U]),ie.useEffect(()=>{const F=document.getElementById("root");document.documentElement.lang=ue==="zh"?"zh-CN":"en",localStorage.setItem(eg,ue),tg(F,ue);const $=new MutationObserver(()=>tg(F,ue));return F&&$.observe(F,{childList:!0,subtree:!0,characterData:!0}),()=>$.disconnect()},[ue]),ie.useEffect(()=>{localStorage.setItem("areno-dashboard-agent-provider",JSON.stringify(w))},[w]),ie.useEffect(()=>{localStorage.setItem(Sy,JSON.stringify(g.slice(-40)))},[g]),ie.useEffect(()=>{if(!g.length){const F=Ou(ue==="zh"?ng:Rl,ue==="zh"?"新对话":"New chat");p([F]),x(F.id);return}g.some(F=>F.id===y)||x(g[0].id)},[g,y,ue]),ie.useEffect(()=>{y&&localStorage.setItem(lg,y)},[y]),ie.useEffect(()=>{localStorage.setItem(ig,f)},[f]),ie.useEffect(()=>{G?localStorage.setItem(jc,JSON.stringify(G)):localStorage.removeItem(jc)},[G]),ie.useEffect(()=>{const F=At.current;F&&(F.scrollTop=F.scrollHeight)},[St,v]);const wt=[{id:"overview",label:"Overview",icon:m.jsx(zk,{size:17})},{id:"jobs",label:"Jobs",icon:m.jsx(py,{size:16})},{id:"runtime",label:"Runtime",icon:m.jsx(Ok,{size:16})},{id:"launcher",label:"Launcher",icon:m.jsx(Xu,{size:16})},{id:"agent",label:"Agent",icon:m.jsx(gy,{size:16})}],ot={overview:["Operations Overview","Runtime health, active work, and the signals that need attention."],jobs:M&&B?[B.name,`${B.kind} · ${B.status} · step ${B.step??0}`]:["Jobs","Open an AReno train or serve task to inspect metrics, samples, config, and logs."],runtime:["Runtime Environment","Review areno check, areno env, dependencies, GPU state, and repository context."],launcher:["Task Launcher","Start low-intrusion AReno train or serve subprocesses from explicit configs."],agent:["Agent Console","Chat with an operations agent using the selected job context."]};async function Ot(){Q("Starting train job...");try{const F=await Pe("/api/jobs/train",{method:"POST",body:JSON.stringify(r)});i(F.job.id),await Dt.refresh()}finally{Q("")}}async function Qe(){Q("Starting serve job...");try{const F=await Pe("/api/jobs/serve",{method:"POST",body:JSON.stringify(o)});i(F.job.id),await Dt.refresh()}finally{Q("")}}async function zn(F){var $;Q("Executing plan...");try{const ke=await Pe("/api/agent/tools/run",{method:"POST",body:JSON.stringify({tool:F.tool||Ey(F),parameters:F.parameters||{}})});return($=ke.job)!=null&&$.id&&(i(ke.job.id),await Dt.refresh()),ke}finally{Q("")}}async function Vt(F){Q("Stopping job...");try{await Pe(`/api/jobs/${F}/stop`,{method:"POST",body:"{}"}),await Dt.refresh()}finally{Q("")}}async function Ku(){Q("Running environment checks...");try{await Pe("/api/runtime/refresh",{method:"POST",body:"{}"}),await Promise.all([nt.refresh(),Ut.refresh()])}finally{Q("")}}async function ci(F){var $;Q(`Fixing ${F.package||"runtime dependency"}...`);try{const ke=await Pe("/api/runtime/repair",{method:"POST",body:JSON.stringify({action_id:F.id})});($=ke.job)!=null&&$.id&&(Ue({actionId:F.id,jobId:ke.job.id,job:ke.job,refreshed:!1}),await Dt.refresh()),await Ut.refresh(),Q("")}catch(ke){Q(ke.message||String(ke))}}async function fi(F,$=null){var ke;if(F.kind==="agent_prompt"){const ce=$?` + */const Hk=at("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);function qk(){const n=document.querySelector('script[type="module"][src]');if(n!=null&&n.src)return new URL("../",n.src).pathname;const i=window.location.pathname;return i.endsWith("/")?i:`${i}/`}const of=qk(),eg="areno-dashboard-language",by={Overview:"概览",Jobs:"任务",Runtime:"运行环境",Launcher:"任务启动",Agent:"智能助手","Operations Overview":"运行概览","Runtime health, active work, and the signals that need attention.":"查看运行环境、活跃任务和需要关注的信号。","Runtime Environment":"运行环境","Review areno check, areno env, dependencies, GPU state, and repository context.":"检查 AReno 环境、依赖、GPU 状态和仓库上下文。","Task Launcher":"任务启动","Start low-intrusion AReno train or serve subprocesses from explicit configs.":"通过明确配置启动 AReno 训练或服务进程。","Agent Console":"智能助手","Chat with an operations agent using the selected job context.":"基于所选任务上下文与运维助手对话。","Running Job Summary":"运行任务摘要","Current health, route, and stage progression for the latest job.":"最新任务的健康状态、运行路径和阶段进度。",Metrics:"指标","Switch between reward and loss for the latest job.":"切换查看最新任务的奖励、损失及训练指标。","Runtime attention":"运行环境提醒","Highest-priority environment finding.":"当前最高优先级的环境问题。","Quick actions":"快捷操作","Short paths into common workflows.":"快速执行常用工作流。","Latest health":"最新健康指标","Active jobs":"活跃任务","No signal":"暂无信号","Waiting for metrics":"等待指标上报",Reward:"奖励",Loss:"损失","Grad Norm":"梯度范数","Sequence Length":"序列长度","Job Detail: Overview":"任务详情:概览","Rollout Sample":"采样样例","Environment Checks":"环境检查","Runtime requirements, compatibility, and actionable diagnostics.":"运行要求、兼容性和可执行诊断。","GPU Cards":"GPU 状态","Memory pressure and utilization before launch.":"启动前的显存压力和利用率。",Details:"详情","Run Check":"运行检查",Fix:"修复","Starting...":"正在启动…","Installing...":"正在安装…",Installed:"已安装","Retry fix":"重试修复",Ready:"就绪","Needs attention":"需要关注",Checking:"检查中","Dependency Risk":"依赖风险","No checks reported":"暂无检查结果","No GPUs reported":"暂无 GPU 信息","No metrics available":"暂无指标","No rollout sample captured yet.":"尚未记录采样样例。","No TensorBoard scalar points loaded yet.":"尚未加载 TensorBoard 标量数据。","Loading selected metric...":"正在加载所选指标…",Open:"打开","Back to Jobs":"返回任务列表","Stop job":"停止任务",Stop:"停止",Prev:"上一页",Next:"下一页",All:"全部",Running:"运行中",Failed:"失败",Stopped:"已停止",Config:"配置",Logs:"日志","Command Preview":"命令预览",Preflight:"预检","Start Train":"启动训练","Start Serve":"启动服务",Send:"发送","New Chat":"新对话",Settings:"设置",Chat:"对话",History:"历史","Error Recovery":"错误恢复","Suggested Follow-ups":"建议追问",Done:"完成","Toggle theme":"切换主题","Translate to Chinese":"切换为中文","Translate to English":"切换为英文","Ask about this job, its metrics, or recent logs...":"询问此任务的指标、运行状态或最近日志…","Ask about the runtime or describe a task to launch...":"询问运行环境,或描述要启动的任务…","Message the operations agent":"向运维助手发送消息"},Gk=Object.fromEntries(Object.entries(by).map(([n,i])=>[i,n]));async function Pe(n,i){const r=await fetch(`${of}${n.replace(/^\//,"")}`,{headers:{"Content-Type":"application/json",...(i==null?void 0:i.headers)||{}},...i}),u=await r.text(),o=u?JSON.parse(u):{};if(!r.ok)throw new Error(o.error||r.statusText);return o}function dt(...n){return n.filter(Boolean).join(" ")}function tg(n,i){if(!n)return;const r=i==="zh"?by:Gk,u="pre, code, .mono, .chatMessages, .runtimeCommandResult, .commandPreview",o=document.createTreeWalker(n,NodeFilter.SHOW_TEXT);let c=o.nextNode();for(;c;){const f=c.parentElement;if(f&&!f.closest(u)){const h=c.nodeValue.trim(),g=r[h];g&&(c.nodeValue=c.nodeValue.replace(h,g))}c=o.nextNode()}for(const f of n.querySelectorAll("[title], [placeholder], [aria-label]"))if(!f.closest(u))for(const h of["title","placeholder","aria-label"]){const g=f.getAttribute(h);g&&r[g]&&f.setAttribute(h,r[g])}}function Bn(n,i=2500,r=[]){const[u,o]=ie.useState(null),c=async()=>{try{const f=await n();o(f)}catch{}};return ie.useEffect(()=>{c();const f=setInterval(c,i);return()=>clearInterval(f)},r),{data:u,refresh:c}}const Rl=[{role:"assistant",content:"Select a job, then ask about metrics, runtime, logs, or how to start the next AReno task."}],ng=[{role:"assistant",content:"选择一个任务,然后询问指标、运行环境、日志,或如何启动下一个 AReno 任务。"}],Yk="areno-dashboard-agent-chat",Sy="areno-dashboard-agent-chat-sessions",lg="areno-dashboard-agent-active-chat",ig="areno-dashboard-agent-draft",jc="areno-dashboard-agent-failure";function Vk(){try{const n=JSON.parse(localStorage.getItem(Yk)||"[]");return Array.isArray(n)&&n.length?n:Rl}catch{return Rl}}function Ou(n=Rl,i="New chat"){const r=Date.now();return{id:`chat-${r}-${Math.random().toString(16).slice(2)}`,title:i,createdAt:r,updatedAt:r,messages:n,followUps:[]}}function Qk(){try{const n=JSON.parse(localStorage.getItem(Sy)||"[]");if(Array.isArray(n)&&n.length)return n.map(i=>{var r;return{...i,messages:(r=i.messages)!=null&&r.length?i.messages:Rl,followUps:Array.isArray(i.followUps)?i.followUps:[]}})}catch{}return[Ou(Vk(),"Default chat")]}function Xk(n,i="New chat"){const r=n.find(o=>o.role==="user"&&o.content);if(!r)return i;const u=r.content.replace(/\s+/g," ").trim();return u.length>42?`${u.slice(0,42)}...`:u}const Zk={ckpt:"",dataset_path:"",dataset_loader_fn:"",reward_fn_path:"",ref_ckpt:"",reward_ckpt:"",critic_ckpt:"",agent_fn:"",algo:"sft",model_hub:"modelscope",epochs:10,max_steps:5,world_size:1,tp_size:1,attn_backend:"flash",activation_checkpointing:!0,fp8_checkpoint_activations:!0,drop_rollout_state:!0,eager_decode:!1,disable_thinking:!1,batch_size:8,n_samples:8,mini_bs:1,score_micro_bs:8,gradient_accumulation_steps:"",max_prompt_tokens:1024,max_context_len:2048,max_new_tokens:1024,max_running_prompts:"",temperature:1,top_k:-1,top_p:1,greedy:!1,train_tool_results:!1,lr:1e-6,min_lr:1e-7,lr_decay_steps:1e3,lr_decay_style:"cosine",adam_beta1:.9,adam_beta2:.999,adam_8bit:!1,unfreeze_multimodal_tower:!1,unfreeze_multimodal_projector:!1,multimodal_tower_lr:"",multimodal_tower_min_lr:"",multimodal_tower_lr_decay_steps:"",multimodal_tower_lr_decay_style:"",multimodal_projector_lr:"",multimodal_projector_min_lr:"",multimodal_projector_lr_decay_steps:"",multimodal_projector_lr_decay_style:"",weight_decay:.01,grad_clip_norm:1,gspo_clip_eps:3e-4,grpo_clip_eps:.2,dpo_beta:.1,critic_warmup_steps:20,critic_lr:1e-5,use_kl_loss:!0,kl_loss_coef:.001,kl_loss_type:"low_var_kl",clip_eps:.2,clip_ratio_c:3,value_clip_eps:.5,value_loss_coef:.5,gamma:1,lam:.95,tune_params:!1,mem_frac:.9,tune_max_samples:256,save_path:"outputs/dashboard-run",save_interval:100,metrics_dir:"outputs/dashboard-run/metrics",extra_args:""},Fk={model_path:"",model_hub:"modelscope",host:"0.0.0.0",port:8e3,world_size:1,tp_size:1,max_running_prompts:16,default_max_tokens:1024,decode_progress_interval_s:0,attn_backend:"flash",eager_decode:!1,disable_thinking:!1,extra_args:""};function Kk(){var jt,Yn,yi,pr,gr;const[n,i]=ie.useState(null),[r,u]=ie.useState(Zk),[o,c]=ie.useState(Fk),[f,h]=ie.useState(()=>localStorage.getItem(ig)||""),[g,p]=ie.useState(()=>Qk()),[y,x]=ie.useState(()=>localStorage.getItem(lg)||""),[b,S]=ie.useState("chat"),[w,j]=ie.useState(()=>{try{return JSON.parse(localStorage.getItem("areno-dashboard-agent-provider")||"{}")}catch{return{}}}),[q,N]=ie.useState("overview"),[K,Y]=ie.useState("all"),[se,ae]=ie.useState("train"),[U,ne]=ie.useState(()=>localStorage.getItem("areno-dashboard-theme-v2")||"light"),[ue,ye]=ie.useState(()=>localStorage.getItem(eg)||"en"),[R,Q]=ie.useState(""),[W,de]=ie.useState(!1),[re,I]=ie.useState(1),[M,J]=ie.useState(!1),[P,xe]=ie.useState(0),[A,T]=ie.useState(!1),[G,k]=ie.useState(()=>{try{return JSON.parse(localStorage.getItem(jc)||"null")}catch{return null}}),[le,pe]=ie.useState(!1),[he,je]=ie.useState(null),[we,Ue]=ie.useState(null),At=ie.useRef(null),nt=Bn(()=>Pe("/api/env"),5e3),Dt=Bn(()=>Pe("/api/jobs"),2e3),si=Bn(()=>n?Pe(`/api/jobs/${n}`):Promise.resolve(null),3e3,[n]),Ut=Bn(()=>Pe("/api/runtime/attention"),5e3),sl=Bn(()=>we!=null&&we.jobId?Pe(`/api/jobs/${we.jobId}`):Promise.resolve(null),1e3,[we==null?void 0:we.jobId]),ol=Bn(()=>Pe("/api/quick-actions"),3e4),oi=Bn(()=>Pe("/api/launcher/presets"),3e4),qn=Bn(()=>Pe(`/api/agent/recovery${n?`?job_id=${encodeURIComponent(n)}`:""}`),3e3,[n]),Ht=(((jt=Dt.data)==null?void 0:jt.jobs)||[]).filter(F=>F.kind!=="runtime-repair"),Yt=((Yn=sl.data)==null?void 0:Yn.job)||(we==null?void 0:we.job)||null,Wt=K==="all"?Ht:Ht.filter(F=>F.status===K),Cn=3,An=Math.max(1,Math.ceil(Wt.length/Cn)),ut=Math.min(re,An),ia=Wt.slice((ut-1)*Cn,ut*Cn),B=((yi=si.data)==null?void 0:yi.job)||(n?Ht.find(F=>F.id===n):null)||null,te=Ay(Ht),be=Bn(()=>te?Pe(`/api/jobs/${te.id}`):Promise.resolve(null),3e3,[te==null?void 0:te.id]),Ce=te&&((gr=(pr=be.data)==null?void 0:pr.job)==null?void 0:gr.id)===te.id?be.data.job:te,Oe=ie.useMemo(()=>g.find(F=>F.id===y)||g[0]||Ou(),[g,y]),St=Oe.messages||Rl,fn=Oe.followUps||[];ie.useEffect(()=>{n&&Ht.length&&!Ht.some(F=>F.id===n)&&i(null)},[Ht.length,n]),ie.useEffect(()=>{re>An&&I(An)},[re,An]),ie.useEffect(()=>{const F=String((Yt==null?void 0:Yt.status)||"").toLowerCase();!we||we.refreshed||!["succeeded","failed","stopped"].includes(F)||(Ue($=>$&&{...$,refreshed:!0}),(async()=>{try{await Pe("/api/runtime/refresh",{method:"POST",body:"{}"}),await Promise.all([nt.refresh(),Ut.refresh(),Dt.refresh()])}catch($){Q($.message||String($))}})())},[we,Yt==null?void 0:Yt.status]),ie.useEffect(()=>{document.documentElement.dataset.theme=U,localStorage.setItem("areno-dashboard-theme-v2",U)},[U]),ie.useEffect(()=>{const F=document.getElementById("root");document.documentElement.lang=ue==="zh"?"zh-CN":"en",localStorage.setItem(eg,ue),tg(F,ue);const $=new MutationObserver(()=>tg(F,ue));return F&&$.observe(F,{childList:!0,subtree:!0,characterData:!0}),()=>$.disconnect()},[ue]),ie.useEffect(()=>{localStorage.setItem("areno-dashboard-agent-provider",JSON.stringify(w))},[w]),ie.useEffect(()=>{localStorage.setItem(Sy,JSON.stringify(g.slice(-40)))},[g]),ie.useEffect(()=>{if(!g.length){const F=Ou(ue==="zh"?ng:Rl,ue==="zh"?"新对话":"New chat");p([F]),x(F.id);return}g.some(F=>F.id===y)||x(g[0].id)},[g,y,ue]),ie.useEffect(()=>{y&&localStorage.setItem(lg,y)},[y]),ie.useEffect(()=>{localStorage.setItem(ig,f)},[f]),ie.useEffect(()=>{G?localStorage.setItem(jc,JSON.stringify(G)):localStorage.removeItem(jc)},[G]),ie.useEffect(()=>{const F=At.current;F&&(F.scrollTop=F.scrollHeight)},[St,b]);const wt=[{id:"overview",label:"Overview",icon:m.jsx(zk,{size:17})},{id:"jobs",label:"Jobs",icon:m.jsx(py,{size:16})},{id:"runtime",label:"Runtime",icon:m.jsx(Ok,{size:16})},{id:"launcher",label:"Launcher",icon:m.jsx(Xu,{size:16})},{id:"agent",label:"Agent",icon:m.jsx(gy,{size:16})}],ot={overview:["Operations Overview","Runtime health, active work, and the signals that need attention."],jobs:M&&B?[B.name,`${B.kind} · ${B.status} · step ${B.step??0}`]:["Jobs","Open an AReno train or serve task to inspect metrics, samples, config, and logs."],runtime:["Runtime Environment","Review areno check, areno env, dependencies, GPU state, and repository context."],launcher:["Task Launcher","Start low-intrusion AReno train or serve subprocesses from explicit configs."],agent:["Agent Console","Chat with an operations agent using the selected job context."]};async function Ot(){Q("Starting train job...");try{const F=await Pe("/api/jobs/train",{method:"POST",body:JSON.stringify(r)});i(F.job.id),await Dt.refresh()}finally{Q("")}}async function Qe(){Q("Starting serve job...");try{const F=await Pe("/api/jobs/serve",{method:"POST",body:JSON.stringify(o)});i(F.job.id),await Dt.refresh()}finally{Q("")}}async function zn(F){var $;Q("Executing plan...");try{const ke=await Pe("/api/agent/tools/run",{method:"POST",body:JSON.stringify({tool:F.tool||Ey(F),parameters:F.parameters||{}})});return($=ke.job)!=null&&$.id&&(i(ke.job.id),await Dt.refresh()),ke}finally{Q("")}}async function Vt(F){Q("Stopping job...");try{await Pe(`/api/jobs/${F}/stop`,{method:"POST",body:"{}"}),await Dt.refresh()}finally{Q("")}}async function Ku(){Q("Running environment checks...");try{await Pe("/api/runtime/refresh",{method:"POST",body:"{}"}),await Promise.all([nt.refresh(),Ut.refresh()])}finally{Q("")}}async function ci(F){var $;Q(`Fixing ${F.package||"runtime dependency"}...`);try{const ke=await Pe("/api/runtime/repair",{method:"POST",body:JSON.stringify({action_id:F.id})});($=ke.job)!=null&&$.id&&(Ue({actionId:F.id,jobId:ke.job.id,job:ke.job,refreshed:!1}),await Dt.refresh()),await Ut.refresh(),Q("")}catch(ke){Q(ke.message||String(ke))}}async function fi(F,$=null){var ke;if(F.kind==="agent_prompt"){const ce=$?` Track this overview job: ${$.name} (${$.id}).`:"";i(($==null?void 0:$.id)||null),N("agent"),await en(`${F.prompt||"Track the latest job and summarize its health."}${ce}`,!1,($==null?void 0:$.id)||null);return}Q(`Running ${F.label}...`);try{const ce=await Pe("/api/quick-actions/run",{method:"POST",body:JSON.stringify({action_id:F.id,config:r})});(ke=ce.job)!=null&&ke.id?(i(ce.job.id),await Dt.refresh(),Q(`${ce.job.name||"Job"} started.`),window.setTimeout(()=>Q(""),2400)):ce.env&&(await Promise.all([nt.refresh(),Ut.refresh()]),je(ce),Q(""))}catch(ce){Q(ce.message||String(ce))}}async function di(F=null){T(!0);try{const $=await Pe("/api/agent/follow-ups",{method:"POST",body:JSON.stringify({job_id:(B==null?void 0:B.id)||null,provider:w,history:F||Gn(St),language:ue})});fr($.follow_ups||[])}catch($){Q($.message||String($))}finally{T(!1)}}async function en(F=null,$=!1,ke=null){const ce=String(F??f).trim();if(!ce)return;F==null&&h(""),fr([]),$&&pe(!0);const Ve=`assistant-${Date.now()}`;cl(Ee=>[...Ee,{role:"user",content:ce},{id:Ve,role:"assistant",content:"",events:[],streaming:!0}]),Q("Agent analyzing...");let st="",pt=!1,Ke="";try{await dr({prompt:ce,job_id:ke??(B==null?void 0:B.id)??null,provider:w,history:Gn(St),language:ue,onEvent:Ee=>{Ee.type==="content_delta"&&(st+=Ee.content||""),Ee.type==="error"&&(pt=!0,Ke=Ee.content||"The agent stream reported an error."),mi(Ve,Ee)}})}catch(Ee){pt=!0,Ke=Ee.message||String(Ee),mi(Ve,{type:"error",content:`Agent request failed: ${Ke}`})}finally{mi(Ve,{type:"done"}),Q(""),pe(!1),pt?(k(Ee=>({prompt:ce,error:Ke||"Agent request failed before producing a complete response.",jobId:ke??(B==null?void 0:B.id)??null,attempts:$?Number((Ee==null?void 0:Ee.attempts)||1)+1:1,failedAt:Date.now()})),qn.refresh()):(k(null),Pe("/api/agent/recovery/clear",{method:"POST",body:JSON.stringify({job_id:ke??(B==null?void 0:B.id)??null})}).catch(()=>{}),qn.refresh()),!pt&&st.trim()&&await di([...Gn(St),{role:"user",content:ce},{role:"assistant",content:st.trim()}])}}async function hi(){k(null),await Pe("/api/agent/recovery/clear",{method:"POST",body:JSON.stringify({job_id:(B==null?void 0:B.id)||null})}).catch(()=>{}),qn.refresh()}function cl(F){const $=Oe.id;p(ke=>ke.map(ce=>{if(ce.id!==$)return ce;const Ve=ce.messages||Rl,st=typeof F=="function"?F(Ve):F;return{...ce,messages:st,updatedAt:Date.now(),title:Xk(st,ce.title)}}))}function fr(F){const $=Oe.id;p(ke=>ke.map(ce=>{if(ce.id!==$)return ce;const Ve=ce.followUps||[];return{...ce,followUps:typeof F=="function"?F(Ve):F,updatedAt:Date.now()}}))}function aa(){const F=Ou(ue==="zh"?ng:Rl,ue==="zh"?"新对话":"New chat");p($=>[F,...$]),x(F.id),h(""),k(null),Pe("/api/agent/recovery/clear",{method:"POST",body:"{}"}).catch(()=>{}),S("chat")}function ra(F){x(F),S("chat")}function Gn(F){return F.filter($=>($.role==="user"||$.role==="assistant")&&!$.streaming).map($=>({role:$.role,content:Ju($)})).filter($=>$.content).slice(-10)}function Ju(F){return F.content?F.content:(F.events||[]).filter($=>$.type==="content"||$.type==="reasoning").map($=>$.text||"").join(` `).trim()}async function dr({prompt:F,job_id:$,provider:ke,history:ce,language:Ve,onEvent:st}){const pt=await fetch(`${of}api/agent/stream`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:F,job_id:$,provider:ke,history:ce,language:Ve})});if(!pt.ok||!pt.body){const Xe=await pt.text();throw new Error(Xe||pt.statusText)}const Ke=pt.body.getReader(),Ee=new TextDecoder;let Qt="";for(;;){const{value:Xe,done:Mn}=await Ke.read();if(Mn)break;Qt+=Ee.decode(Xe,{stream:!0});const Bl=Qt.split(` -`);Qt=Bl.pop()||"";for(const sa of Bl)sa.trim()&&st(JSON.parse(sa))}Qt.trim()&&st(JSON.parse(Qt))}function mi(F,$){cl(ke=>ke.map(ce=>ce.id!==F?ce:$.type==="content_delta"?pi(ce,"content",$.content||""):$.type==="reasoning_delta"?pi(ce,"reasoning",$.content||""):$.type==="tool_calls"?hr(ce,$.tool_calls||[]):$.type==="tool_call_delta"?gi(ce,$.tool_call,!0):$.type==="tool_result"?{...ce,events:[...ce.events||[],{type:"tool_result",result:$.tool_result}]}:$.type==="error"?{...pi(ce,"content",$.content||""),streaming:!1}:$.type==="done"?{...ce,streaming:!1}:ce))}function pi(F,$,ke){if(!ke)return F;const ce=[...F.events||[]],Ve=ce[ce.length-1];(Ve==null?void 0:Ve.type)===$?ce[ce.length-1]={...Ve,text:`${Ve.text||""}${ke}`}:ce.push({type:$,text:ke});const st=$==="content"?`${F.content||""}${ke}`:F.content;return{...F,content:st,events:ce}}function gi(F,$,ke=!1){if(!$)return F;const ce=[...F.events||[]],Ve=ce.findIndex(st=>st.type==="tool_call"&&ua(st.call,$));return Ve>=0?ce[Ve]={...ce[Ve],call:$,live:ke}:ce.push({type:"tool_call",call:$,live:ke}),{...F,events:ce}}function ua(F,$){return!F||!$?!1:!!(F.id&&$.id&&F.id===$.id||F.round!==void 0&&$.round!==void 0&&F.index!==void 0&&$.index!==void 0&&F.round===$.round&&F.index===$.index)}function hr(F,$){let ke=F;for(const ce of $)ke=gi(ke,ce,!1);return ke}function mr(){var F,$,ke,ce,Ve,st,pt,Ke;if(q==="overview")return m.jsx(Jk,{env:nt.data,jobs:Ht,runtimeAttention:Ut.data,quickActions:((F=ol.data)==null?void 0:F.actions)||[],onQuickAction:fi,onRuntimeRepair:ci,runtimeRepair:we?{...we,job:Yt}:null});if(q==="runtime")return m.jsx(dA,{env:nt.data,onRefresh:Ku});if(q==="launcher")return m.jsx($A,{mode:se,setMode:ae,trainConfig:r,setTrainConfig:u,serveConfig:o,setServeConfig:c,onStartTrain:Ot,onStartServe:Qe,env:nt.data,presets:(($=oi.data)==null?void 0:$.presets)||[]});if(q==="agent"){const Ee=((ke=qn.data)==null?void 0:ke.recovery)||{},Qt=G||(Ee.active?{error:Ee.error,attempts:1}:null);return m.jsxs("div",{className:"agentPrdLayout",children:[m.jsxs("section",{className:"panel chatPanel",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Agent Console"}),m.jsx("p",{children:"Natural-language operations with explicit runtime and job context."})]}),m.jsxs("div",{className:"agentHeaderActions",children:[m.jsx(Mt,{status:(ce=nt.data)!=null&&ce.ready?"ok":"warn"}),m.jsxs("button",{className:"secondaryButton",onClick:aa,children:[m.jsx(xy,{size:15})," New Chat"]}),m.jsxs("button",{className:"secondaryButton",onClick:()=>de(!0),children:[m.jsx(by,{size:15})," Settings"]})]})]}),m.jsxs("div",{className:"pillRow agentContextPills",children:[m.jsxs("span",{children:["repo: ",((st=(Ve=nt.data)==null?void 0:Ve.repo)==null?void 0:st.branch)||"unknown"]}),m.jsxs("span",{children:["job: ",(B==null?void 0:B.id)||"none selected"]}),m.jsxs("span",{children:["GPU: ",((Ke=(pt=nt.data)==null?void 0:pt.gpus)==null?void 0:Ke.length)||0," visible"]})]}),m.jsxs("div",{className:"agentTabs",children:[m.jsxs("button",{className:dt(v==="chat"&&"active"),onClick:()=>S("chat"),children:[m.jsx(Nk,{size:15})," Chat"]}),m.jsxs("button",{className:dt(v==="history"&&"active"),onClick:()=>S("history"),children:[m.jsx(jk,{size:15})," History"]})]}),v==="history"?m.jsx(yA,{sessions:g,activeId:Oe.id,onOpen:ra,onNew:aa}):m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"chatMessages",ref:At,children:St.map((Xe,Mn)=>{var Bl;return m.jsxs("div",{className:dt("chatBubble",Xe.role),children:[m.jsx("span",{children:Xe.role}),(Bl=Xe.events)!=null&&Bl.length?m.jsx(vA,{events:Xe.events,onPlanConfirm:zn}):m.jsx(ff,{text:Xe.content})]},`${Xe.id||Xe.role}-${Mn}`)})}),m.jsxs("div",{className:"chatComposer",children:[m.jsx("label",{className:"chatInputField",children:m.jsx("textarea",{"aria-label":"Message the operations agent",placeholder:B?"Ask about this job, its metrics, or recent logs...":"Ask about the runtime or describe a task to launch...",value:f,onChange:Xe=>h(Xe.target.value),onKeyDown:Xe=>{Xe.key==="Enter"&&!Xe.shiftKey&&(Xe.preventDefault(),en())}})}),m.jsxs("button",{className:"primaryButton chatSendButton",disabled:!f.trim(),onClick:()=>en(),children:[m.jsx(Dk,{size:16})," Send"]})]})]}),W&&m.jsx(Zu,{title:"Agent Settings",onClose:()=>de(!1),children:m.jsx(gA,{provider:w,setProvider:j})})]}),m.jsxs("aside",{className:"agentSideRail",children:[m.jsxs("section",{className:"panel agentRecoveryCard",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Error Recovery"}),m.jsx("p",{children:"Detect and retry failed agent requests."})]}),m.jsx(Mt,{status:Qt?"failed":"ok"})]}),Qt?m.jsxs("div",{className:"attentionItem",children:[m.jsx(Mt,{status:"failed"}),m.jsxs("div",{children:[m.jsx("strong",{children:"Agent request failed"}),m.jsx("p",{children:Qt.error}),Qt.attempts>1&&m.jsxs("small",{children:[Qt.attempts," recovery attempts"]})]})]}):m.jsxs("div",{className:"attentionItem",children:[m.jsx(Mt,{status:"ok"}),m.jsxs("div",{children:[m.jsx("strong",{children:"No active agent errors"}),m.jsx("p",{children:"The current conversation has no failed request."})]})]}),G&&m.jsxs("div",{className:"recoveryButtons",children:[m.jsx("button",{className:"primaryButton fullButton recoveryAction",disabled:le,onClick:()=>en(G.prompt,!0),children:le?"Recovering...":"Retry failed request"}),m.jsx("button",{className:"secondaryButton fullButton recoveryAction",disabled:le,onClick:hi,children:"Dismiss"})]})]}),m.jsxs("section",{className:"panel agentFollowupsCard",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Suggested Follow-ups"}),m.jsx("p",{children:"LLM-generated actions grounded in the current context."})]})}),A&&m.jsx("div",{className:"followupsLoading",children:"Generating follow-ups..."}),!A&&fn.length===0&&m.jsx("p",{children:"Follow-ups appear after the current response completes."}),fn.map(Xe=>m.jsx("button",{className:"secondaryButton",onClick:()=>{S("chat"),en(Xe.prompt)},children:Xe.label},Xe.id))]})]})]})}return M&&B?m.jsx(uA,{job:B,refreshNonce:P,onBack:()=>J(!1),onStop:()=>Vt(B.id)}):m.jsxs("div",{className:"jobsPageStack",children:[m.jsxs("section",{className:"panel jobListPage",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Jobs"}),m.jsx("p",{children:"Registered AReno train and serve processes. Open a job to inspect its full detail page."})]}),m.jsxs("div",{className:"jobsToolbar",children:[m.jsx("div",{className:"tabs compactTabs",children:["all","running","failed","stopped"].map(Ee=>m.jsx("button",{className:dt(K===Ee&&"active"),onClick:()=>{Y(Ee),I(1)},children:Ee[0].toUpperCase()+Ee.slice(1)},Ee))}),m.jsxs("div",{className:"pagerControls",children:[m.jsx("button",{className:"secondaryButton",disabled:ut<=1,onClick:()=>I(Ee=>Math.max(1,Ee-1)),children:"Prev"}),m.jsxs("span",{children:[ut," / ",kn]}),m.jsx("button",{className:"secondaryButton",disabled:ut>=kn,onClick:()=>I(Ee=>Math.min(kn,Ee+1)),children:"Next"})]})]})]}),m.jsxs("div",{className:"jobTableWrap",children:[Wt.length===0&&m.jsx(ai,{title:"No matching jobs",text:"Start a task from Launcher or select another status."}),Wt.length>0&&m.jsxs("table",{className:"jobTable",children:[m.jsx("thead",{children:m.jsxs("tr",{children:[m.jsx("th",{children:"Job"}),m.jsx("th",{children:"Status"}),m.jsx("th",{children:"Stage"}),m.jsx("th",{children:"Metric"}),m.jsx("th",{children:"Elapsed"}),m.jsx("th",{children:"Action"})]})}),m.jsx("tbody",{children:ia.map(Ee=>m.jsxs("tr",{children:[m.jsxs("td",{children:[m.jsx("strong",{children:Ee.name}),m.jsxs("span",{className:"mono subline",children:[Ee.id," · ",Ee.kind]})]}),m.jsx("td",{children:m.jsx(Mt,{status:Ee.status})}),m.jsxs("td",{children:[Ee.stage||"unknown"," · step ",Ee.step??0]}),m.jsx("td",{children:wy(Ee)}),m.jsx("td",{children:oA(Ee)}),m.jsx("td",{children:m.jsx("button",{className:"secondaryButton tableAction",onClick:()=>{i(Ee.id),J(!0)},children:"Open"})})]},Ee.id))})]})]}),Wt.length>Cn&&m.jsxs("div",{className:"listFooter",children:["Showing ",(ut-1)*Cn+1,"-",Math.min(ut*Cn,Wt.length)," of ",Wt.length," jobs"]})]}),Ce?m.jsx(rA,{job:Ce,env:nt.data,onStop:()=>Vt(Ce.id)}):m.jsxs("div",{className:"jobDetailPreviewGrid",children:[m.jsx("section",{className:"panel",children:m.jsx(ai,{title:"No job overview",text:"Launch a task to populate the job overview."})}),m.jsx("section",{className:"panel",children:m.jsx(ai,{title:"No rollout sample",text:"Samples appear after a rollout completes."})})]})]})}const[Nn,_t]=ot[q]||ot.jobs;return m.jsxs("div",{className:"shell",children:[m.jsxs("aside",{className:"rail",children:[m.jsxs("div",{className:"brand",children:[m.jsx("img",{className:"brandMark",src:"https://mdn.alipayobjects.com/huamei_fz8c8n/afts/img/6aFwRZclmL8AAAAAQyAAAAgADpuRAQJr/original",alt:"AReno logo"}),m.jsxs("div",{children:[m.jsx("div",{className:"brandName",children:"AReno Ops"}),m.jsx("div",{className:"brandMeta",children:"runtime workbench"})]})]}),m.jsx("nav",{className:"nav",children:wt.map(F=>m.jsxs("button",{className:dt("navItem",q===F.id&&"active"),onClick:()=>{F.id==="jobs"&&J(!1),N(F.id)},children:[F.icon," ",F.label]},F.id))})]}),m.jsxs("main",{className:"main",children:[m.jsxs("div",{className:"mobileNav",children:[m.jsx("strong",{children:"AReno Ops"}),m.jsx("select",{value:q,onChange:F=>{F.target.value==="jobs"&&J(!1),N(F.target.value)},children:wt.map(F=>m.jsx("option",{value:F.id,children:F.label},F.id))})]}),m.jsxs("header",{className:"topbar",children:[m.jsxs("div",{children:[m.jsx("h1",{children:Nn}),m.jsx("p",{children:_t})]}),m.jsxs("div",{className:"topActions",children:[m.jsx("button",{className:"iconButton",onClick:()=>ne(U==="dark"?"light":"dark"),title:"Toggle theme",children:U==="dark"?m.jsx(Lk,{size:16}):m.jsx(Mk,{size:16})}),m.jsxs("button",{className:"iconButton languageButton",onClick:()=>ye(ue==="en"?"zh":"en"),title:ue==="en"?"Translate to Chinese":"Translate to English",children:[m.jsx(Ck,{size:16}),m.jsx("span",{children:ue==="en"?"中文":"EN"})]})]})]}),R&&m.jsx("div",{className:"notice",children:R}),mr(),he&&m.jsx(xA,{result:he,onClose:()=>je(null)})]})]})}function Jk({env:n,jobs:i,runtimeAttention:r,quickActions:u,onQuickAction:o,onRuntimeRepair:c,runtimeRepair:f}){var U,ne,ue,ye,R,Q,W;const h=i.filter(iA),g=i.filter(de=>de.status==="failed"),p=Ay(h.length?h:i),x=(U=Bn(()=>p?Pe(`/api/jobs/${p.id}`):Promise.resolve(null),2e3,[p==null?void 0:p.id]).data)==null?void 0:U.job,v=(x==null?void 0:x.id)===(p==null?void 0:p.id)?x:p,S=(n==null?void 0:n.gpus)||[],w=(n==null?void 0:n.checks)||[],j=(r==null?void 0:r.attention)||w.find(de=>["warn","fail"].includes(String(de.status).toLowerCase())),q=((ne=j==null?void 0:j.repair)==null?void 0:ne.id)&&(f==null?void 0:f.actionId)===j.repair.id,N=q?String(((ue=f==null?void 0:f.job)==null?void 0:ue.status)||"created").toLowerCase():"",K=["created","running"].includes(N),Y=String(Fu(v,"algo")||"").toLowerCase(),se=["gspo","grpo","ppo"].includes(Y),ae=se?qc(v,["rollout/rewards_mean","reward_mean","reward"]):qc(v,["train/loss","loss","policy_loss"]);return m.jsxs("div",{className:"overviewPage",children:[m.jsxs("section",{className:"summaryGrid",children:[m.jsx(li,{label:"Runtime",value:n!=null&&n.ready?"Ready":n?"Needs attention":"Checking",detail:`${((ye=n==null?void 0:n.check_counts)==null?void 0:ye.ok)??0} OK · ${((R=n==null?void 0:n.check_counts)==null?void 0:R.warn)??0} WARN`,tone:n!=null&&n.ready?"ok":"warn"}),m.jsx(li,{label:"GPU",value:S.length?`${S.length} available`:"No GPU data",detail:((Q=S[0])==null?void 0:Q.name)||"Reported by runtime API"}),m.jsx(li,{label:"Active jobs",value:String(h.length),detail:g.length?`${g.length} failed job${g.length===1?"":"s"}`:"No failed jobs",tone:g.length?"warn":"info"}),m.jsx(li,{label:"Latest health",value:ae==null?"No signal":cf(ae),detail:ae==null?"Waiting for metrics":`Latest ${se?"reward":"loss"} signal`})]}),m.jsxs("div",{className:"overviewLayout",children:[m.jsxs("div",{className:"overviewPrimary",children:[v?m.jsx(lA,{job:v}):m.jsx("section",{className:"panel",children:m.jsx(ai,{title:"No jobs yet",text:"Launch a train or serve task to populate live operations data."})}),m.jsxs("section",{className:"panel overviewSignals",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Metrics"}),m.jsx("p",{children:"Switch between reward and loss for the latest job."})]}),m.jsx("span",{className:"sourceBadge",children:"Live API"})]}),v?m.jsx(Pk,{job:v}):m.jsx(ai,{title:"No metrics available",text:"Metrics appear after a job starts reporting scalar data."})]})]}),m.jsxs("aside",{className:"overviewAside",children:[m.jsxs("section",{className:"panel attentionCard",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Runtime attention"}),m.jsx("p",{children:"Highest-priority environment finding."})]})}),j?m.jsxs("div",{className:"attentionItem",children:[m.jsx(Mt,{status:j.status}),m.jsxs("div",{className:"attentionItemBody",children:[m.jsx("strong",{children:j.name||j.label||"Runtime warning"}),m.jsx("p",{children:j.detail||j.message||"Review the runtime check details."}),((W=j.repair)==null?void 0:W.kind)==="install_package"&&m.jsxs("div",{className:"runtimeRepairControl",children:[m.jsxs("button",{className:"secondaryButton runtimeFixButton",disabled:K||N==="succeeded",onClick:()=>c(j.repair),children:[K?m.jsx(sf,{className:"spinIcon",size:14}):m.jsx(Hk,{size:14}),N==="running"?"Installing...":N==="created"?"Starting...":N==="succeeded"?"Installed":N==="failed"?"Retry fix":j.repair.label||"Fix"]}),q&&m.jsx($k,{job:f.job})]})]})]}):m.jsxs("div",{className:"attentionItem",children:[m.jsx(Mt,{status:"ok"}),m.jsxs("div",{children:[m.jsx("strong",{children:"No blocking checks"}),m.jsx("p",{children:"The current runtime report has no warning or failure."})]})]})]}),m.jsxs("section",{className:"panel quickActions",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Quick actions"}),m.jsx("p",{children:"Short paths into common workflows."})]})}),u.map((de,re)=>m.jsxs("button",{className:re===0?"primaryButton":"secondaryButton",onClick:()=>o(de,v),children:[Ik(de.kind)," ",de.label]},de.id))]})]})]})]})}function $k({job:n}){if(!n)return null;const i=String(n.status||"created").toLowerCase(),r=n.logs||[],u=r.length?r[r.length-1]:"Preparing package installer...";return m.jsxs("div",{className:dt("runtimeRepairProgress",i),"aria-live":"polite",children:[["created","running"].includes(i)&&m.jsx("div",{className:"runtimeRepairTrack",children:m.jsx("i",{})}),m.jsx("small",{children:i==="failed"?"Installation failed":i==="succeeded"?"Installation complete":u})]})}function Ik(n){return n==="launcher_preset"?m.jsx(Xu,{size:15}):n==="runtime_refresh"?m.jsx(sf,{size:15}):m.jsx(gy,{size:15})}function Pk({job:n}){const i=String(Fu(n,"algo")||"").toLowerCase(),r=["gspo","grpo","ppo"].includes(i)?["reward","loss","gradnorm","seqlen"]:["loss","gradnorm","seqlen"],[u,o]=ie.useState({reward:[],loss:[],gradnorm:[],seqlen:[]}),[c,f]=ie.useState({reward:"",loss:"",gradnorm:"",seqlen:""}),[h,g]=ie.useState(r[0]),[p,y]=ie.useState(null);ie.useEffect(()=>{r.includes(h)||g(r[0])},[i,h]),ie.useEffect(()=>{let w=!1,j;const q=async()=>{try{const N=await Pe(`/api/jobs/${n.id}/metrics`),K=Cy(N.metrics||[]),Y=Object.fromEntries(r.map(ae=>[ae,Wk(K,ae)])),se=await Promise.all(r.map(ae=>Y[ae]?Pe(`/api/jobs/${n.id}/metric?name=${encodeURIComponent(Y[ae])}`):Promise.resolve({points:[]})));if(w)return;f(ae=>({...ae,...Y})),o(ae=>({...ae,...Object.fromEntries(r.map((U,ne)=>[U,eA(se[ne].points)]))}))}catch{w||o({reward:[],loss:[],gradnorm:[],seqlen:[]})}};return q(),j=window.setInterval(q,2500),()=>{w=!0,window.clearInterval(j)}},[n.id,i]);const x=u[h]||[],v=tA(x),S=x.length>0;return m.jsxs("div",{className:"overviewMetricChart",children:[m.jsxs("div",{className:"overviewMetricToolbar",children:[m.jsx("div",{className:"tabs compactTabs metricSwitch","aria-label":"Metric plot",children:r.map(w=>m.jsx("button",{className:dt(h===w&&"active"),onClick:()=>g(w),children:Tc(w)},w))}),m.jsx("div",{className:"metricLegend",children:m.jsxs("span",{className:`${h}Legend`,children:[m.jsx("i",{}),c[h]||Tc(h),m.jsx("b",{children:nA(x)})]})})]}),S?m.jsxs("div",{className:"metricPlotWrap",children:[m.jsxs("svg",{className:"metricPlot overviewPlot",viewBox:"0 0 720 220",role:"img","aria-label":`${h} metrics`,children:[m.jsx("g",{className:"plotGrid",children:[0,1,2,3].map(w=>m.jsx("line",{x1:"10",x2:"710",y1:35+w*52,y2:35+w*52},w))}),m.jsx("polyline",{className:`overviewMetricLine ${h}Line`,points:v.points}),x.map((w,j)=>{var q,N,K,Y;return m.jsxs("g",{children:[m.jsx("circle",{className:`metricDataPoint ${h}Point`,cx:((q=v.coords[j])==null?void 0:q.x)||0,cy:((N=v.coords[j])==null?void 0:N.y)||0,r:ky(x.length)}),m.jsx("circle",{className:"metricHoverTarget",cx:((K=v.coords[j])==null?void 0:K.x)||0,cy:((Y=v.coords[j])==null?void 0:Y.y)||0,r:"5",onMouseEnter:()=>y({point:w,coord:v.coords[j]}),onMouseLeave:()=>y(null)})]},`${w.step}-${j}`)})]}),p&&m.jsx(_y,{name:c[h]||Tc(h),point:p.point,coord:p.coord,width:720,height:220})]}):m.jsxs("div",{className:"plotEmpty",children:["No ",h," points reported yet."]}),m.jsxs("div",{className:"plotFooter",children:[m.jsxs("span",{children:["step ",v.stepMin," to ",v.stepMax]}),m.jsxs("span",{children:[v.minLabel," to ",v.maxLabel]})]})]})}function Wk(n,i){var c;const r=n.map(f=>({name:f,key:f.toLowerCase()})),u={reward:["rollout/rewards_mean"],loss:["train/loss","loss","train/policy_loss","policy_loss","actor_loss"],gradnorm:["train/grad_norm","grad_norm"],seqlen:["rollout/seq_len_mean"]}[i]||[];for(const f of u){const h=r.find(g=>g.key===f);if(h)return h.name}if(i==="reward"||i==="seqlen")return"";const o=i==="gradnorm"?"grad_norm":i;return((c=r.find(f=>f.key.includes(o)))==null?void 0:c.name)||""}function Tc(n){return{reward:"Reward",loss:"Loss",gradnorm:"Grad Norm",seqlen:"Sequence Length"}[n]||n}function eA(n=[]){return n.filter(i=>Number.isFinite(Number(i.value))).map(i=>({step:Number(i.step||0),value:Number(i.value),time:i.time}))}function tA(n){if(!n.length)return{points:"",coords:[],stepMin:0,stepMax:0,minLabel:"n/a",maxLabel:"n/a"};const{min:i,max:r}=Gc(n,p=>p.value),u=r===i,{min:o,max:c}=Gc(n,p=>p.step),f=Math.max(r-i,1e-9),h=Math.max(c-o,1),g=n.map(p=>{const y=(p.step-o)/h*680+20,x=u?113:200-(p.value-i)/f*174;return{x:y,y:x}});return{points:g.map(({x:p,y})=>`${p.toFixed(1)},${y.toFixed(1)}`).join(" "),coords:g,stepMin:o,stepMax:c,minLabel:ta(i),maxLabel:ta(r)}}function _y({name:n,point:i,coord:r,width:u,height:o}){const c=r.xu*.8?"end":"center";return m.jsxs("div",{className:`metricPointTooltip ${c}`,style:{left:`${r.x/u*100}%`,top:`${r.y/o*100}%`},children:[m.jsx("strong",{children:n||"metric"}),m.jsxs("span",{children:["Step ",m.jsx("b",{children:i.step})]}),m.jsxs("span",{children:["Value ",m.jsx("b",{children:ta(i.value)})]}),i.time&&m.jsx("small",{children:new Date(i.time).toLocaleString()})]})}function ky(n){return n<=12?2.75:n<=60?1.9:1.15}function nA(n){return n.length?ta(n[n.length-1].value):"—"}function lA({job:n}){const i=nr(n,"algo"),r=nr(n,"ckpt")||nr(n,"model_path"),u=nr(n,"dataset_path")||nr(n,"dataset"),o=(n.timeperf||[]).slice(-1)[0],c=Object.fromEntries(((o==null?void 0:o.segments)||[]).map(y=>[y.name,y.seconds])),f=df(n),h=Ty(n),g=Math.max(0,f.findIndex(y=>Wi(y,h,n))),p=(y,x)=>y.id==="rollout"&&Number.isFinite(Number(c.rollout))?`${Number(c.rollout).toFixed(1)}s`:["train","actor_train","critic_train"].includes(y.id)&&Number.isFinite(Number(c.train))?`${Number(c.train).toFixed(1)}s`:y.id==="created"&&n.created_at?"created":Wi(y,h,n)?["succeeded","done"].includes(n.status)?"complete":n.status:x{const v=Wi(y,h,n);return m.jsxs("div",{className:dt("stageCell",x<=g&&"done",v&&"current"),children:[m.jsx("strong",{children:y.label}),m.jsx("span",{children:p(y,x)})]},y.id)})})]})}function nr(n,i){var r,u,o;if(((r=n==null?void 0:n.config)==null?void 0:r[i])!==void 0&&n.config[i]!==null&&n.config[i]!=="")return n.config[i];for(const c of((u=n==null?void 0:n.config)==null?void 0:u.sections)||[]){const f=(c.items||[]).find(h=>h.key===i);if((f==null?void 0:f.value)!==void 0&&f.value!==null&&f.value!=="")return f.value}return((o=n==null?void 0:n.launch)==null?void 0:o[i])!==void 0&&n.launch[i]!==null&&n.launch[i]!==""?n.launch[i]:null}function Ay(n=[]){return[...n].sort((i,r)=>Date.parse(r.created_at||0)-Date.parse(i.created_at||0))[0]||null}function iA(n){return String((n==null?void 0:n.status)||"").toLowerCase()==="running"}function aA(n){return String(n).replace(/\/$/,"").split("/").pop()||n}function rA({job:n,env:i,onStop:r}){var f;const u=qc(n,["rollout/rewards_mean","reward_mean","reward"]),o=(n.timeperf||[]).slice(-1)[0],c=(f=i==null?void 0:i.gpus)==null?void 0:f[0];return m.jsx("div",{className:"selectedJobArea",children:m.jsxs("div",{className:"jobDetailPreviewGrid",children:[m.jsxs("section",{className:"panel jobDetailOverviewCard",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Job Detail: Overview"}),m.jsx("p",{children:"Current health and recent progress for the selected job."})]}),m.jsxs("div",{className:"detailActions",children:[m.jsx(Mt,{status:n.status}),n.status==="running"&&m.jsxs("button",{className:"dangerButton",onClick:r,children:[m.jsx(yy,{size:16})," Stop"]})]})]}),m.jsxs("div",{className:"jobIdentity",children:[m.jsx("strong",{children:n.name}),m.jsx("span",{className:"mono subline",children:n.id})]}),m.jsxs("p",{className:"healthSummary",children:[m.jsx("strong",{children:"Health summary:"})," ",sA(n)]}),m.jsxs("div",{className:"detailMetricGrid",children:[m.jsxs("div",{children:[m.jsx("span",{children:"Reward"}),m.jsx("strong",{children:u==null?"No data":cf(u)})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Step time"}),m.jsx("strong",{children:o!=null&&o.total_s?`${Number(o.total_s).toFixed(1)}s`:"No data"})]}),m.jsxs("div",{children:[m.jsx("span",{children:"GPU memory"}),m.jsx("strong",{children:c?`${c.memory_used_mb??0} MB`:"No data"})]})]})]}),m.jsxs("section",{className:"panel rolloutSamplePanel",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Rollout Sample"}),m.jsx("p",{children:"Inspect prompt and completion pairs by step and sample."})]})}),m.jsx(Ny,{samples:n.samples||[],jobId:n.id,hideTitle:!0})]})]})})}function uA({job:n,refreshNonce:i,onBack:r,onStop:u}){const o=n.logs||[];return m.jsxs("div",{className:"jobFullDetailPage",children:[m.jsxs("div",{className:"detailPageToolbar",children:[m.jsxs("button",{className:"secondaryButton",onClick:r,children:[m.jsx(kk,{size:16})," Back to Jobs"]}),n.status==="running"&&m.jsxs("button",{className:"dangerButton",onClick:u,children:[m.jsx(yy,{size:16})," Stop job"]})]}),m.jsx(cA,{job:n,detail:!0,refreshNonce:i}),m.jsxs("section",{className:"panel jobDetailSection",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Metrics"}),m.jsx("p",{children:"Training quality and stage timing for this job."})]})}),m.jsx(bA,{job:n,refreshNonce:i})]}),m.jsxs("section",{className:"panel jobDetailSection",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Rollout Sample"}),m.jsx("p",{children:"Prompt and completion output captured during rollout."})]})}),m.jsx(Ny,{samples:n.samples||[],jobId:n.id,hideTitle:!0})]}),m.jsxs("div",{className:"jobDetailDataGrid",children:[m.jsx(ZA,{config:n.config,launch:n.launch}),m.jsx(JA,{logs:o})]})]})}function sA(n){return n.status==="running"?`The job is running at ${n.stage||"its current stage"}, step ${n.step??0}, with no terminal status reported.`:n.status==="failed"?`The job failed during ${n.stage||"an unknown stage"}. Review metrics and logs below.`:["succeeded","done"].includes(n.status)?`The job completed successfully after ${n.step??0} steps.`:`The job is ${n.status||"unknown"} at ${n.stage||"an unknown stage"}, step ${n.step??0}.`}function oA(n){const i=Date.parse((n==null?void 0:n.created_at)||""),r=Date.parse((n==null?void 0:n.status)==="running"?new Date().toISOString():(n==null?void 0:n.updated_at)||"");if(!Number.isFinite(i)||!Number.isFinite(r))return"—";const u=Math.max(0,Math.round((r-i)/1e3));return u<60?`${u}s`:u<3600?`${Math.floor(u/60)}m ${u%60}s`:`${Math.floor(u/3600)}h ${Math.floor(u%3600/60)}m`}function cA({job:n,compact:i=!1,detail:r=!1,refreshNonce:u=0,onOpen:o,onStop:c}){return m.jsxs("section",{className:dt("panel","jobOverview",r&&"detailPanel"),children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("span",{className:"sectionEyebrow",children:i?"Latest job":"Selected job"}),m.jsx("h2",{children:r?"Job Detail: Overview":n.name}),r&&m.jsx("strong",{className:"detailJobName",children:n.name}),m.jsxs("p",{className:"mono",children:[n.id," · updated ",fA(n.updated_at)]})]}),m.jsxs("div",{className:"detailActions",children:[m.jsx(Mt,{status:n.status}),i&&m.jsx("button",{className:"secondaryButton",onClick:o,children:"Open job"})]})]}),m.jsxs("div",{className:"jobOverviewStats",children:[m.jsxs("div",{children:[m.jsx("span",{children:"Stage"}),m.jsx("strong",{children:n.stage||"unknown"})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Step"}),m.jsx("strong",{children:n.step??0})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Latest signal"}),m.jsx("strong",{children:wy(n)})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Process"}),m.jsx("strong",{children:n.pid?`PID ${n.pid}`:n.kind})]})]}),m.jsx(NA,{job:n})]})}function li({label:n,value:i,detail:r,tone:u="neutral"}){return m.jsxs("div",{className:dt("summaryCard",u),children:[m.jsx("span",{children:n}),m.jsx("strong",{children:i}),m.jsx("small",{children:r})]})}function Mt({status:n="unknown"}){const i=String(n).toLowerCase(),r=i==="succeeded"||i==="done"?"ok":i;return m.jsxs("span",{className:dt("statusBadge",r),children:[m.jsx("i",{}),n]})}function qc(n,i){if(!(n!=null&&n.perf))return null;for(const r of i)if(Number.isFinite(Number(n.perf[r])))return Number(n.perf[r]);return null}function cf(n){if(!Number.isFinite(Number(n)))return"—";const i=Number(n);return Math.abs(i)>=100?i.toFixed(0):i.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function wy(n){const i=Object.entries((n==null?void 0:n.perf)||{}).filter(([,o])=>Number.isFinite(Number(o)));if(!i.length)return"No metrics";const[r,u]=i[0];return`${r} ${cf(u)}`}function fA(n){const i=Date.parse(n||"");if(!Number.isFinite(i))return"—";const r=Math.max(0,Math.round((Date.now()-i)/1e3));return r<60?`${r}s ago`:r<3600?`${Math.floor(r/60)}m ago`:r<86400?`${Math.floor(r/3600)}h ago`:`${Math.floor(r/86400)}d ago`}function dA({env:n,onRefresh:i}){var x,v,S;const[r,u]=ie.useState(null),o=(n==null?void 0:n.report)||{},c=o.torch||{},f=(n==null?void 0:n.checks)||[],h=(n==null?void 0:n.gpus)||((x=o==null?void 0:o.torch)==null?void 0:x.gpus)||[],g=((v=n==null?void 0:n.check_counts)==null?void 0:v.warn)??f.filter(w=>String(w.status).toLowerCase()==="warn").length,p=((S=n==null?void 0:n.check_counts)==null?void 0:S.fail)??f.filter(w=>String(w.status).toLowerCase()==="fail").length,y=p?`${p} FAIL`:g?`${g} WARN`:"Clear";return m.jsxs("div",{className:"runtimePrdPage",children:[m.jsxs("section",{className:"runtimeSummaryGrid",children:[m.jsx(li,{label:"AReno Check",value:n!=null&&n.ready?"Ready":n?"Needs attention":"Checking",detail:`Last refreshed ${new Date().toLocaleTimeString()}`,tone:n!=null&&n.ready?"ok":"warn"}),m.jsx(li,{label:"PyTorch / CUDA",value:`${c.version||"n/a"} / ${c.cuda_runtime||c.cuda_build||"n/a"}`,detail:c.cuda_available?"Compatible runtime detected":"CUDA runtime unavailable",tone:c.cuda_available?"ok":"warn"}),m.jsx(li,{label:"Dependency Risk",value:y,detail:mA(f),tone:p||g?"warn":"ok"})]}),m.jsxs("div",{className:"runtimePrdLayout",children:[m.jsxs("section",{className:"panel runtimeChecksPanel",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Environment Checks"}),m.jsx("p",{children:"Runtime requirements, compatibility, and actionable diagnostics."})]}),m.jsxs("button",{className:"secondaryButton",onClick:i,children:[m.jsx(sf,{size:15})," Run Check"]})]}),m.jsxs("div",{className:"runtimeCheckList",children:[f.length===0&&m.jsx(ai,{title:"No checks reported",text:"Run the environment check to populate diagnostics."}),f.slice(0,12).map((w,j)=>m.jsxs("div",{className:"runtimeCheckRow",children:[m.jsx(Mt,{status:w.status||"unknown"}),m.jsxs("div",{children:[m.jsx("strong",{children:w.name||w.label||"Runtime check"}),m.jsx("p",{children:w.detail||w.message||"No additional details."})]}),m.jsx("button",{className:"secondaryButton tableAction",title:"Diagnostic details",onClick:()=>u(w),children:"Details"})]},`${w.name||w.label}-${j}`))]})]}),m.jsxs("section",{className:"panel runtimeGpuPanel",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"GPU Cards"}),m.jsx("p",{children:"Memory pressure and utilization before launch."})]})}),m.jsxs("div",{className:"runtimeGpuList",children:[h.length===0&&m.jsx(ai,{title:"No GPUs reported",text:"GPU cards appear when CUDA devices are visible."}),h.map((w,j)=>m.jsx(pA,{gpu:w,index:j},w.index??j))]})]})]}),r&&m.jsx(Zu,{title:`${r.name||r.label||"Environment Check"} Details`,onClose:()=>u(null),children:m.jsx(hA,{check:r,report:o,onClose:()=>u(null)})})]})}function hA({check:n,report:i,onClose:r}){var f,h,g,p,y,x,v;const u=(i==null?void 0:i.torch)||{},o=(i==null?void 0:i.cuda)||{},c=[["AReno",(f=i==null?void 0:i.areno)==null?void 0:f.version],["Python",(h=i==null?void 0:i.python)==null?void 0:h.version],["PyTorch",u.version],["CUDA build",u.cuda_build],["CUDA runtime",u.cuda_runtime],["CUDA available",u.cuda_available],["Visible GPUs",u.device_count],["NVCC",((g=o.nvcc)==null?void 0:g.version)||((p=o.nvcc)==null?void 0:p.path)],["NVIDIA driver",(y=o.driver)==null?void 0:y.driver_version],["Driver CUDA",(x=o.driver)==null?void 0:x.cuda_version],["Platform",(v=i==null?void 0:i.platform)==null?void 0:v.platform]].filter(([,S])=>S!=null&&S!=="");return m.jsxs("div",{className:"runtimeCheckDetails",children:[m.jsxs("div",{className:"runtimeCheckDetailLead",children:[m.jsx(Mt,{status:n.status||"unknown"}),m.jsxs("div",{children:[m.jsx("strong",{children:n.detail||n.message||"No diagnostic value reported."}),n.next_step&&m.jsx("p",{children:n.next_step})]})]}),m.jsx("div",{className:"runtimeVersionGrid",children:c.map(([S,w])=>m.jsxs("div",{children:[m.jsx("span",{children:S}),m.jsx("strong",{children:String(w)})]},S))}),m.jsx("button",{className:"primaryButton fullButton",onClick:r,children:"Done"})]})}function mA(n){const i=n.find(r=>["fail","warn"].includes(String(r.status).toLowerCase()));return(i==null?void 0:i.name)||(i==null?void 0:i.label)||"No dependency warnings"}function pA({gpu:n,index:i}){const r=Number(n.memory_used_mb??n.memory_used??0),u=Number(n.memory_total_mb??n.memory_total??0),o=Number(n.utilization??n.utilization_gpu??0),c=u>0?Math.min(100,r/u*100):0;return m.jsxs("div",{className:"runtimeGpuCard",children:[m.jsxs("div",{children:[m.jsxs("strong",{children:["GPU ",n.index??i," · ",n.name||"CUDA device"]}),m.jsxs("span",{children:[r.toFixed(0)," / ",u.toFixed(0)," MB · Util ",o.toFixed(0),"%"]})]}),m.jsx("div",{className:"meterTrack",children:m.jsx("i",{style:{width:`${c}%`}})})]})}function gA({provider:n,setProvider:i}){return m.jsxs("div",{className:"agentConfig modalForm",children:[m.jsx(Hu,{label:"Base URL",value:n.base_url||"",onChange:r=>i({...n,base_url:r}),compact:!0}),m.jsx(Hu,{label:"Model",value:n.model||"",onChange:r=>i({...n,model:r}),compact:!0}),m.jsxs("label",{className:"field compact",children:[m.jsx("span",{children:"API key"}),m.jsx("input",{type:"password",value:n.api_key||"",onChange:r=>i({...n,api_key:r.target.value})})]})]})}function yA({sessions:n,activeId:i,onOpen:r,onNew:u}){return m.jsxs("div",{className:"agentHistory",children:[m.jsxs("div",{className:"agentHistoryHeader",children:[m.jsxs("div",{children:[m.jsx("h3",{children:"Chat History"}),m.jsxs("p",{children:[n.length," saved conversations in this browser."]})]}),m.jsxs("button",{className:"secondaryButton",onClick:u,children:[m.jsx(xy,{size:15})," New Chat"]})]}),m.jsx("div",{className:"agentHistoryList",children:n.map(o=>{const c=[...o.messages||[]].reverse().find(f=>f.role==="user"||f.content);return m.jsxs("button",{className:dt("agentHistoryItem",o.id===i&&"active"),onClick:()=>r(o.id),children:[m.jsx("strong",{children:o.title||"New chat"}),m.jsx("span",{children:(c==null?void 0:c.content)||"No messages yet."}),m.jsx("small",{children:new Date(o.updatedAt||o.createdAt||Date.now()).toLocaleString()})]},o.id)})})]})}function Zu({title:n,children:i,onClose:r}){return m.jsx("div",{className:"modalOverlay",role:"presentation",onMouseDown:r,children:m.jsxs("div",{className:"modalCard",role:"dialog","aria-modal":"true","aria-label":n,onMouseDown:u=>u.stopPropagation(),children:[m.jsxs("div",{className:"modalHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:n}),m.jsx("p",{children:"Stored locally in this browser."})]}),m.jsx("button",{className:"iconButton",onClick:r,children:"×"})]}),i]})})}function xA({result:n,onClose:i}){var u,o;const r=((u=n.env)==null?void 0:u.check_counts)||{};return m.jsxs(Zu,{title:"Runtime Check Result",onClose:i,children:[m.jsxs("div",{className:"runtimeResultSummary",children:[m.jsx(Mt,{status:(o=n.env)!=null&&o.ready?"ok":"warn"}),m.jsxs("span",{children:[r.ok||0," OK · ",r.warn||0," WARN · ",r.fail||0," FAIL"]})]}),m.jsx("pre",{className:"runtimeCommandResult",children:n.output||`$ areno check -No output returned.`}),m.jsx("button",{className:"primaryButton fullButton",onClick:i,children:"Done"})]})}function bA({job:n,refreshNonce:i}){return m.jsxs("div",{className:"jobMetricsGrid",children:[m.jsx("div",{className:"panel insetPanel",children:m.jsx(DA,{jobId:n==null?void 0:n.id,metricsDir:n==null?void 0:n.metrics_dir,refreshNonce:i})}),m.jsx("div",{className:"panel insetPanel",children:m.jsx(LA,{rows:(n==null?void 0:n.timeperf)||[],job:n})})]})}function vA({events:n,onPlanConfirm:i}){const r=n.filter(o=>{var c;return o.type==="tool_result"&&((c=o.result)==null?void 0:c.plan)}),u=n.filter(o=>{var c;return!(o.type==="tool_result"&&((c=o.result)!=null&&c.plan))});return m.jsxs("div",{className:"agentEventList",children:[u.map((o,c)=>o.type==="reasoning"?m.jsx(wA,{text:o.text},c):o.type==="content"?m.jsx(ff,{text:o.text},c):o.type==="tool_call"?m.jsx(EA,{call:o.call,live:o.live},c):o.type==="tool_result"?m.jsx(CA,{result:o.result},c):null),r.map((o,c)=>m.jsx(SA,{plan:o.result.plan,onConfirm:i},o.result.plan.id||c))]})}function SA({plan:n,onConfirm:i}){const[r,u]=ie.useState(!1),[o,c]=ie.useState(n.parameters||{}),[f,h]=ie.useState(null);ie.useEffect(()=>c(n.parameters||{}),[n.id]);const g=Object.entries(o),p=n.tool||Ey(n),y=_A(p,o),x={...n,tool:p,parameters:o,command:y};return m.jsxs("section",{className:"agentPlanCard",children:[m.jsxs("div",{className:"agentPlanHeader",children:[m.jsxs("div",{children:[m.jsx("span",{children:"Execution plan"}),m.jsx("strong",{children:n.objective})]}),m.jsx(Mt,{status:n.status||"proposed"})]}),n.summary&&m.jsx("p",{className:"agentPlanSummary",children:n.summary}),g.length>0&&m.jsx("div",{className:dt("agentPlanParams",r&&"editing"),children:g.map(([v,S])=>m.jsxs("label",{children:[m.jsx("span",{children:v.replaceAll("_"," ")}),r?m.jsx("input",{value:String(S),onChange:w=>c(j=>({...j,[v]:w.target.value}))}):m.jsx("strong",{children:String(S)})]},v))}),m.jsx("ol",{className:"agentPlanSteps",children:(n.steps||[]).map((v,S)=>m.jsxs("li",{children:[m.jsx("span",{children:S+1}),m.jsxs("div",{children:[m.jsx("strong",{children:v.title}),v.detail&&m.jsx("p",{children:v.detail})]}),m.jsx("small",{children:v.status||"pending"})]},v.id||S))}),y&&m.jsx("pre",{className:"agentPlanCommand",children:y}),m.jsxs("div",{className:"agentPlanActions",children:[m.jsx("button",{className:"primaryButton",disabled:(f==null?void 0:f.status)==="running",onClick:async()=>{var v;h({status:"running",message:"Starting..."});try{const S=await(i==null?void 0:i(x));h({status:(S==null?void 0:S.ok)===!1?"failed":"ok",message:(v=S==null?void 0:S.job)!=null&&v.id?`Started job ${S.job.id}`:"Execution completed"})}catch(S){h({status:"failed",message:S.message||String(S)})}},children:(f==null?void 0:f.status)==="running"?"Executing...":"Confirm Execution"}),g.length>0&&m.jsx("button",{className:"secondaryButton",onClick:()=>u(v=>!v),children:r?"Save Parameters":"Edit Parameters"}),y&&m.jsx("button",{className:"secondaryButton",onClick:()=>navigator.clipboard.writeText(y),children:"Copy Command"})]}),f&&f.status!=="running"&&m.jsx("p",{className:dt("agentPlanExecution",f.status),children:f.message})]})}function Ey(n){const i=String((n==null?void 0:n.command)||"").toLowerCase();return i.includes("--smoke-train")?"smoke_train":i.includes("--smoke-infer")?"smoke_infer":/\bareno\s+serve\b/.test(i)?"start_serve":"start_train"}function _A(n,i={}){const r=n==="start_serve"?"serve":"train",u=[],o=new Set(["activation_checkpointing","use_kl_loss"]);for(const[f,h]of Object.entries(i)){if(f==="extra_args"||h===""||h===null||h===void 0)continue;const g=`--${f.replaceAll("_","-")}`;if(kA(h)){AA(h)?u.push(g):o.has(f)&&u.push(`--no-${f.replaceAll("_","-")}`);continue}u.push(`${g} ${hf(h)}`)}n==="smoke_train"&&u.push("--smoke-train"),n==="smoke_infer"&&u.push("--smoke-infer");const c=String(i.extra_args||"").trim();return c&&u.push(c),[`areno ${r} \\`,...u.map((f,h)=>` ${f}${h`${i.id} · ${i.kind} · ${i.status} · step ${i.step??0} · ${i.name}`).join(` +`);Qt=Bl.pop()||"";for(const sa of Bl)sa.trim()&&st(JSON.parse(sa))}Qt.trim()&&st(JSON.parse(Qt))}function mi(F,$){cl(ke=>ke.map(ce=>ce.id!==F?ce:$.type==="content_delta"?pi(ce,"content",$.content||""):$.type==="reasoning_delta"?pi(ce,"reasoning",$.content||""):$.type==="tool_calls"?hr(ce,$.tool_calls||[]):$.type==="tool_call_delta"?gi(ce,$.tool_call,!0):$.type==="tool_result"?{...ce,events:[...ce.events||[],{type:"tool_result",result:$.tool_result}]}:$.type==="error"?{...pi(ce,"content",$.content||""),streaming:!1}:$.type==="done"?{...ce,streaming:!1}:ce))}function pi(F,$,ke){if(!ke)return F;const ce=[...F.events||[]],Ve=ce[ce.length-1];(Ve==null?void 0:Ve.type)===$?ce[ce.length-1]={...Ve,text:`${Ve.text||""}${ke}`}:ce.push({type:$,text:ke});const st=$==="content"?`${F.content||""}${ke}`:F.content;return{...F,content:st,events:ce}}function gi(F,$,ke=!1){if(!$)return F;const ce=[...F.events||[]],Ve=ce.findIndex(st=>st.type==="tool_call"&&ua(st.call,$));return Ve>=0?ce[Ve]={...ce[Ve],call:$,live:ke}:ce.push({type:"tool_call",call:$,live:ke}),{...F,events:ce}}function ua(F,$){return!F||!$?!1:!!(F.id&&$.id&&F.id===$.id||F.round!==void 0&&$.round!==void 0&&F.index!==void 0&&$.index!==void 0&&F.round===$.round&&F.index===$.index)}function hr(F,$){let ke=F;for(const ce of $)ke=gi(ke,ce,!1);return ke}function mr(){var F,$,ke,ce,Ve,st,pt,Ke;if(q==="overview")return m.jsx(Jk,{env:nt.data,jobs:Ht,runtimeAttention:Ut.data,quickActions:((F=ol.data)==null?void 0:F.actions)||[],onQuickAction:fi,onRuntimeRepair:ci,runtimeRepair:we?{...we,job:Yt}:null});if(q==="runtime")return m.jsx(dA,{env:nt.data,onRefresh:Ku});if(q==="launcher")return m.jsx($A,{mode:se,setMode:ae,trainConfig:r,setTrainConfig:u,serveConfig:o,setServeConfig:c,onStartTrain:Ot,onStartServe:Qe,env:nt.data,presets:(($=oi.data)==null?void 0:$.presets)||[]});if(q==="agent"){const Ee=((ke=qn.data)==null?void 0:ke.recovery)||{},Qt=G||(Ee.active?{error:Ee.error,attempts:1}:null);return m.jsxs("div",{className:"agentPrdLayout",children:[m.jsxs("section",{className:"panel chatPanel",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Agent Console"}),m.jsx("p",{children:"Natural-language operations with explicit runtime and job context."})]}),m.jsxs("div",{className:"agentHeaderActions",children:[m.jsx(Mt,{status:(ce=nt.data)!=null&&ce.ready?"ok":"warn"}),m.jsxs("button",{className:"secondaryButton",onClick:aa,children:[m.jsx(xy,{size:15})," New Chat"]}),m.jsxs("button",{className:"secondaryButton",onClick:()=>de(!0),children:[m.jsx(vy,{size:15})," Settings"]})]})]}),m.jsxs("div",{className:"pillRow agentContextPills",children:[m.jsxs("span",{children:["repo: ",((st=(Ve=nt.data)==null?void 0:Ve.repo)==null?void 0:st.branch)||"unknown"]}),m.jsxs("span",{children:["job: ",(B==null?void 0:B.id)||"none selected"]}),m.jsxs("span",{children:["GPU: ",((Ke=(pt=nt.data)==null?void 0:pt.gpus)==null?void 0:Ke.length)||0," visible"]})]}),m.jsxs("div",{className:"agentTabs",children:[m.jsxs("button",{className:dt(b==="chat"&&"active"),onClick:()=>S("chat"),children:[m.jsx(Nk,{size:15})," Chat"]}),m.jsxs("button",{className:dt(b==="history"&&"active"),onClick:()=>S("history"),children:[m.jsx(jk,{size:15})," History"]})]}),b==="history"?m.jsx(yA,{sessions:g,activeId:Oe.id,onOpen:ra,onNew:aa}):m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"chatMessages",ref:At,children:St.map((Xe,Mn)=>{var Bl;return m.jsxs("div",{className:dt("chatBubble",Xe.role),children:[m.jsx("span",{children:Xe.role}),(Bl=Xe.events)!=null&&Bl.length?m.jsx(bA,{events:Xe.events,onPlanConfirm:zn}):m.jsx(ff,{text:Xe.content})]},`${Xe.id||Xe.role}-${Mn}`)})}),m.jsxs("div",{className:"chatComposer",children:[m.jsx("label",{className:"chatInputField",children:m.jsx("textarea",{"aria-label":"Message the operations agent",placeholder:B?"Ask about this job, its metrics, or recent logs...":"Ask about the runtime or describe a task to launch...",value:f,onChange:Xe=>h(Xe.target.value),onKeyDown:Xe=>{Xe.key==="Enter"&&!Xe.shiftKey&&(Xe.preventDefault(),en())}})}),m.jsxs("button",{className:"primaryButton chatSendButton",disabled:!f.trim(),onClick:()=>en(),children:[m.jsx(Dk,{size:16})," Send"]})]})]}),W&&m.jsx(Zu,{title:"Agent Settings",onClose:()=>de(!1),children:m.jsx(gA,{provider:w,setProvider:j})})]}),m.jsxs("aside",{className:"agentSideRail",children:[m.jsxs("section",{className:"panel agentRecoveryCard",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Error Recovery"}),m.jsx("p",{children:"Detect and retry failed agent requests."})]}),m.jsx(Mt,{status:Qt?"failed":"ok"})]}),Qt?m.jsxs("div",{className:"attentionItem",children:[m.jsx(Mt,{status:"failed"}),m.jsxs("div",{children:[m.jsx("strong",{children:"Agent request failed"}),m.jsx("p",{children:Qt.error}),Qt.attempts>1&&m.jsxs("small",{children:[Qt.attempts," recovery attempts"]})]})]}):m.jsxs("div",{className:"attentionItem",children:[m.jsx(Mt,{status:"ok"}),m.jsxs("div",{children:[m.jsx("strong",{children:"No active agent errors"}),m.jsx("p",{children:"The current conversation has no failed request."})]})]}),G&&m.jsxs("div",{className:"recoveryButtons",children:[m.jsx("button",{className:"primaryButton fullButton recoveryAction",disabled:le,onClick:()=>en(G.prompt,!0),children:le?"Recovering...":"Retry failed request"}),m.jsx("button",{className:"secondaryButton fullButton recoveryAction",disabled:le,onClick:hi,children:"Dismiss"})]})]}),m.jsxs("section",{className:"panel agentFollowupsCard",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Suggested Follow-ups"}),m.jsx("p",{children:"LLM-generated actions grounded in the current context."})]})}),A&&m.jsx("div",{className:"followupsLoading",children:"Generating follow-ups..."}),!A&&fn.length===0&&m.jsx("p",{children:"Follow-ups appear after the current response completes."}),fn.map(Xe=>m.jsx("button",{className:"secondaryButton",onClick:()=>{S("chat"),en(Xe.prompt)},children:Xe.label},Xe.id))]})]})]})}return M&&B?m.jsx(uA,{job:B,refreshNonce:P,onBack:()=>J(!1),onStop:()=>Vt(B.id)}):m.jsxs("div",{className:"jobsPageStack",children:[m.jsxs("section",{className:"panel jobListPage",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Jobs"}),m.jsx("p",{children:"Registered AReno train and serve processes. Open a job to inspect its full detail page."})]}),m.jsxs("div",{className:"jobsToolbar",children:[m.jsx("div",{className:"tabs compactTabs",children:["all","running","failed","stopped"].map(Ee=>m.jsx("button",{className:dt(K===Ee&&"active"),onClick:()=>{Y(Ee),I(1)},children:Ee[0].toUpperCase()+Ee.slice(1)},Ee))}),m.jsxs("div",{className:"pagerControls",children:[m.jsx("button",{className:"secondaryButton",disabled:ut<=1,onClick:()=>I(Ee=>Math.max(1,Ee-1)),children:"Prev"}),m.jsxs("span",{children:[ut," / ",An]}),m.jsx("button",{className:"secondaryButton",disabled:ut>=An,onClick:()=>I(Ee=>Math.min(An,Ee+1)),children:"Next"})]})]})]}),m.jsxs("div",{className:"jobTableWrap",children:[Wt.length===0&&m.jsx(ai,{title:"No matching jobs",text:"Start a task from Launcher or select another status."}),Wt.length>0&&m.jsxs("table",{className:"jobTable",children:[m.jsx("thead",{children:m.jsxs("tr",{children:[m.jsx("th",{children:"Job"}),m.jsx("th",{children:"Status"}),m.jsx("th",{children:"Stage"}),m.jsx("th",{children:"Metric"}),m.jsx("th",{children:"Elapsed"}),m.jsx("th",{children:"Action"})]})}),m.jsx("tbody",{children:ia.map(Ee=>m.jsxs("tr",{children:[m.jsxs("td",{children:[m.jsx("strong",{children:Ee.name}),m.jsxs("span",{className:"mono subline",children:[Ee.id," · ",Ee.kind]})]}),m.jsx("td",{children:m.jsx(Mt,{status:Ee.status})}),m.jsxs("td",{children:[Ee.stage||"unknown"," · step ",Ee.step??0]}),m.jsx("td",{children:wy(Ee)}),m.jsx("td",{children:oA(Ee)}),m.jsx("td",{children:m.jsx("button",{className:"secondaryButton tableAction",onClick:()=>{i(Ee.id),J(!0)},children:"Open"})})]},Ee.id))})]})]}),Wt.length>Cn&&m.jsxs("div",{className:"listFooter",children:["Showing ",(ut-1)*Cn+1,"-",Math.min(ut*Cn,Wt.length)," of ",Wt.length," jobs"]})]}),Ce?m.jsx(rA,{job:Ce,env:nt.data,onStop:()=>Vt(Ce.id)}):m.jsxs("div",{className:"jobDetailPreviewGrid",children:[m.jsx("section",{className:"panel",children:m.jsx(ai,{title:"No job overview",text:"Launch a task to populate the job overview."})}),m.jsx("section",{className:"panel",children:m.jsx(ai,{title:"No rollout sample",text:"Samples appear after a rollout completes."})})]})]})}const[Nn,_t]=ot[q]||ot.jobs;return m.jsxs("div",{className:"shell",children:[m.jsxs("aside",{className:"rail",children:[m.jsxs("div",{className:"brand",children:[m.jsx("img",{className:"brandMark",src:"https://mdn.alipayobjects.com/huamei_fz8c8n/afts/img/6aFwRZclmL8AAAAAQyAAAAgADpuRAQJr/original",alt:"AReno logo"}),m.jsxs("div",{children:[m.jsx("div",{className:"brandName",children:"AReno Ops"}),m.jsx("div",{className:"brandMeta",children:"runtime workbench"})]})]}),m.jsx("nav",{className:"nav",children:wt.map(F=>m.jsxs("button",{className:dt("navItem",q===F.id&&"active"),onClick:()=>{F.id==="jobs"&&J(!1),N(F.id)},children:[F.icon," ",F.label]},F.id))})]}),m.jsxs("main",{className:"main",children:[m.jsxs("div",{className:"mobileNav",children:[m.jsx("strong",{children:"AReno Ops"}),m.jsx("select",{value:q,onChange:F=>{F.target.value==="jobs"&&J(!1),N(F.target.value)},children:wt.map(F=>m.jsx("option",{value:F.id,children:F.label},F.id))})]}),m.jsxs("header",{className:"topbar",children:[m.jsxs("div",{children:[m.jsx("h1",{children:Nn}),m.jsx("p",{children:_t})]}),m.jsxs("div",{className:"topActions",children:[m.jsx("button",{className:"iconButton",onClick:()=>ne(U==="dark"?"light":"dark"),title:"Toggle theme",children:U==="dark"?m.jsx(Lk,{size:16}):m.jsx(Mk,{size:16})}),m.jsxs("button",{className:"iconButton languageButton",onClick:()=>ye(ue==="en"?"zh":"en"),title:ue==="en"?"Translate to Chinese":"Translate to English",children:[m.jsx(Ck,{size:16}),m.jsx("span",{children:ue==="en"?"中文":"EN"})]})]})]}),R&&m.jsx("div",{className:"notice",children:R}),mr(),he&&m.jsx(xA,{result:he,onClose:()=>je(null)})]})]})}function Jk({env:n,jobs:i,runtimeAttention:r,quickActions:u,onQuickAction:o,onRuntimeRepair:c,runtimeRepair:f}){var U,ne,ue,ye,R,Q,W;const h=i.filter(iA),g=i.filter(de=>de.status==="failed"),p=Ay(h.length?h:i),x=(U=Bn(()=>p?Pe(`/api/jobs/${p.id}`):Promise.resolve(null),2e3,[p==null?void 0:p.id]).data)==null?void 0:U.job,b=(x==null?void 0:x.id)===(p==null?void 0:p.id)?x:p,S=(n==null?void 0:n.gpus)||[],w=(n==null?void 0:n.checks)||[],j=(r==null?void 0:r.attention)||w.find(de=>["warn","fail"].includes(String(de.status).toLowerCase())),q=((ne=j==null?void 0:j.repair)==null?void 0:ne.id)&&(f==null?void 0:f.actionId)===j.repair.id,N=q?String(((ue=f==null?void 0:f.job)==null?void 0:ue.status)||"created").toLowerCase():"",K=["created","running"].includes(N),Y=String(Fu(b,"algo")||"").toLowerCase(),se=["gspo","grpo","ppo"].includes(Y),ae=se?qc(b,["rollout/rewards_mean","reward_mean","reward"]):qc(b,["train/loss","loss","policy_loss"]);return m.jsxs("div",{className:"overviewPage",children:[m.jsxs("section",{className:"summaryGrid",children:[m.jsx(li,{label:"Runtime",value:n!=null&&n.ready?"Ready":n?"Needs attention":"Checking",detail:`${((ye=n==null?void 0:n.check_counts)==null?void 0:ye.ok)??0} OK · ${((R=n==null?void 0:n.check_counts)==null?void 0:R.warn)??0} WARN`,tone:n!=null&&n.ready?"ok":"warn"}),m.jsx(li,{label:"GPU",value:S.length?`${S.length} available`:"No GPU data",detail:((Q=S[0])==null?void 0:Q.name)||"Reported by runtime API"}),m.jsx(li,{label:"Active jobs",value:String(h.length),detail:g.length?`${g.length} failed job${g.length===1?"":"s"}`:"No failed jobs",tone:g.length?"warn":"info"}),m.jsx(li,{label:"Latest health",value:ae==null?"No signal":cf(ae),detail:ae==null?"Waiting for metrics":`Latest ${se?"reward":"loss"} signal`})]}),m.jsxs("div",{className:"overviewLayout",children:[m.jsxs("div",{className:"overviewPrimary",children:[b?m.jsx(lA,{job:b}):m.jsx("section",{className:"panel",children:m.jsx(ai,{title:"No jobs yet",text:"Launch a train or serve task to populate live operations data."})}),m.jsxs("section",{className:"panel overviewSignals",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Metrics"}),m.jsx("p",{children:"Switch between reward and loss for the latest job."})]}),m.jsx("span",{className:"sourceBadge",children:"Live API"})]}),b?m.jsx(Pk,{job:b}):m.jsx(ai,{title:"No metrics available",text:"Metrics appear after a job starts reporting scalar data."})]})]}),m.jsxs("aside",{className:"overviewAside",children:[m.jsxs("section",{className:"panel attentionCard",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Runtime attention"}),m.jsx("p",{children:"Highest-priority environment finding."})]})}),j?m.jsxs("div",{className:"attentionItem",children:[m.jsx(Mt,{status:j.status}),m.jsxs("div",{className:"attentionItemBody",children:[m.jsx("strong",{children:j.name||j.label||"Runtime warning"}),m.jsx("p",{children:j.detail||j.message||"Review the runtime check details."}),((W=j.repair)==null?void 0:W.kind)==="install_package"&&m.jsxs("div",{className:"runtimeRepairControl",children:[m.jsxs("button",{className:"secondaryButton runtimeFixButton",disabled:K||N==="succeeded",onClick:()=>c(j.repair),children:[K?m.jsx(sf,{className:"spinIcon",size:14}):m.jsx(Hk,{size:14}),N==="running"?"Installing...":N==="created"?"Starting...":N==="succeeded"?"Installed":N==="failed"?"Retry fix":j.repair.label||"Fix"]}),q&&m.jsx($k,{job:f.job})]})]})]}):m.jsxs("div",{className:"attentionItem",children:[m.jsx(Mt,{status:"ok"}),m.jsxs("div",{children:[m.jsx("strong",{children:"No blocking checks"}),m.jsx("p",{children:"The current runtime report has no warning or failure."})]})]})]}),m.jsxs("section",{className:"panel quickActions",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Quick actions"}),m.jsx("p",{children:"Short paths into common workflows."})]})}),u.map((de,re)=>m.jsxs("button",{className:re===0?"primaryButton":"secondaryButton",onClick:()=>o(de,b),children:[Ik(de.kind)," ",de.label]},de.id))]})]})]})]})}function $k({job:n}){if(!n)return null;const i=String(n.status||"created").toLowerCase(),r=n.logs||[],u=r.length?r[r.length-1]:"Preparing package installer...";return m.jsxs("div",{className:dt("runtimeRepairProgress",i),"aria-live":"polite",children:[["created","running"].includes(i)&&m.jsx("div",{className:"runtimeRepairTrack",children:m.jsx("i",{})}),m.jsx("small",{children:i==="failed"?"Installation failed":i==="succeeded"?"Installation complete":u})]})}function Ik(n){return n==="launcher_preset"?m.jsx(Xu,{size:15}):n==="runtime_refresh"?m.jsx(sf,{size:15}):m.jsx(gy,{size:15})}function Pk({job:n}){const i=String(Fu(n,"algo")||"").toLowerCase(),r=["gspo","grpo","ppo"].includes(i)?["reward","loss","gradnorm","seqlen"]:["loss","gradnorm","seqlen"],[u,o]=ie.useState({reward:[],loss:[],gradnorm:[],seqlen:[]}),[c,f]=ie.useState({reward:"",loss:"",gradnorm:"",seqlen:""}),[h,g]=ie.useState(r[0]),[p,y]=ie.useState(null);ie.useEffect(()=>{r.includes(h)||g(r[0])},[i,h]),ie.useEffect(()=>{let w=!1,j;const q=async()=>{try{const N=await Pe(`/api/jobs/${n.id}/metrics`),K=Cy(N.metrics||[]),Y=Object.fromEntries(r.map(ae=>[ae,Wk(K,ae)])),se=await Promise.all(r.map(ae=>Y[ae]?Pe(`/api/jobs/${n.id}/metric?name=${encodeURIComponent(Y[ae])}`):Promise.resolve({points:[]})));if(w)return;f(ae=>({...ae,...Y})),o(ae=>({...ae,...Object.fromEntries(r.map((U,ne)=>[U,eA(se[ne].points)]))}))}catch{w||o({reward:[],loss:[],gradnorm:[],seqlen:[]})}};return q(),j=window.setInterval(q,2500),()=>{w=!0,window.clearInterval(j)}},[n.id,i]);const x=u[h]||[],b=tA(x),S=x.length>0;return m.jsxs("div",{className:"overviewMetricChart",children:[m.jsxs("div",{className:"overviewMetricToolbar",children:[m.jsx("div",{className:"tabs compactTabs metricSwitch","aria-label":"Metric plot",children:r.map(w=>m.jsx("button",{className:dt(h===w&&"active"),onClick:()=>g(w),children:Tc(w)},w))}),m.jsx("div",{className:"metricLegend",children:m.jsxs("span",{className:`${h}Legend`,children:[m.jsx("i",{}),c[h]||Tc(h),m.jsx("b",{children:nA(x)})]})})]}),S?m.jsxs("div",{className:"metricPlotWrap",children:[m.jsxs("svg",{className:"metricPlot overviewPlot",viewBox:"0 0 720 220",role:"img","aria-label":`${h} metrics`,children:[m.jsx("g",{className:"plotGrid",children:[0,1,2,3].map(w=>m.jsx("line",{x1:"10",x2:"710",y1:35+w*52,y2:35+w*52},w))}),m.jsx("polyline",{className:`overviewMetricLine ${h}Line`,points:b.points}),x.map((w,j)=>{var q,N,K,Y;return m.jsxs("g",{children:[m.jsx("circle",{className:`metricDataPoint ${h}Point`,cx:((q=b.coords[j])==null?void 0:q.x)||0,cy:((N=b.coords[j])==null?void 0:N.y)||0,r:ky(x.length)}),m.jsx("circle",{className:"metricHoverTarget",cx:((K=b.coords[j])==null?void 0:K.x)||0,cy:((Y=b.coords[j])==null?void 0:Y.y)||0,r:"5",onMouseEnter:()=>y({point:w,coord:b.coords[j]}),onMouseLeave:()=>y(null)})]},`${w.step}-${j}`)})]}),p&&m.jsx(_y,{name:c[h]||Tc(h),point:p.point,coord:p.coord,width:720,height:220})]}):m.jsxs("div",{className:"plotEmpty",children:["No ",h," points reported yet."]}),m.jsxs("div",{className:"plotFooter",children:[m.jsxs("span",{children:["step ",b.stepMin," to ",b.stepMax]}),m.jsxs("span",{children:[b.minLabel," to ",b.maxLabel]})]})]})}function Wk(n,i){var c;const r=n.map(f=>({name:f,key:f.toLowerCase()})),u={reward:["rollout/rewards_mean"],loss:["train/loss","loss","train/policy_loss","policy_loss","actor_loss"],gradnorm:["train/grad_norm","grad_norm"],seqlen:["rollout/seq_len_mean"]}[i]||[];for(const f of u){const h=r.find(g=>g.key===f);if(h)return h.name}if(i==="reward"||i==="seqlen")return"";const o=i==="gradnorm"?"grad_norm":i;return((c=r.find(f=>f.key.includes(o)))==null?void 0:c.name)||""}function Tc(n){return{reward:"Reward",loss:"Loss",gradnorm:"Grad Norm",seqlen:"Sequence Length"}[n]||n}function eA(n=[]){return n.filter(i=>Number.isFinite(Number(i.value))).map(i=>({step:Number(i.step||0),value:Number(i.value),time:i.time}))}function tA(n){if(!n.length)return{points:"",coords:[],stepMin:0,stepMax:0,minLabel:"n/a",maxLabel:"n/a"};const{min:i,max:r}=Gc(n,p=>p.value),u=r===i,{min:o,max:c}=Gc(n,p=>p.step),f=Math.max(r-i,1e-9),h=Math.max(c-o,1),g=n.map(p=>{const y=(p.step-o)/h*680+20,x=u?113:200-(p.value-i)/f*174;return{x:y,y:x}});return{points:g.map(({x:p,y})=>`${p.toFixed(1)},${y.toFixed(1)}`).join(" "),coords:g,stepMin:o,stepMax:c,minLabel:ta(i),maxLabel:ta(r)}}function _y({name:n,point:i,coord:r,width:u,height:o}){const c=r.xu*.8?"end":"center";return m.jsxs("div",{className:`metricPointTooltip ${c}`,style:{left:`${r.x/u*100}%`,top:`${r.y/o*100}%`},children:[m.jsx("strong",{children:n||"metric"}),m.jsxs("span",{children:["Step ",m.jsx("b",{children:i.step})]}),m.jsxs("span",{children:["Value ",m.jsx("b",{children:ta(i.value)})]}),i.time&&m.jsx("small",{children:new Date(i.time).toLocaleString()})]})}function ky(n){return n<=12?2.75:n<=60?1.9:1.15}function nA(n){return n.length?ta(n[n.length-1].value):"—"}function lA({job:n}){const i=nr(n,"algo"),r=nr(n,"ckpt")||nr(n,"model_path"),u=nr(n,"dataset_path")||nr(n,"dataset"),o=(n.timeperf||[]).slice(-1)[0],c=Object.fromEntries(((o==null?void 0:o.segments)||[]).map(y=>[y.name,y.seconds])),f=df(n),h=Ty(n),g=Math.max(0,f.findIndex(y=>Wi(y,h,n))),p=(y,x)=>y.id==="rollout"&&Number.isFinite(Number(c.rollout))?`${Number(c.rollout).toFixed(1)}s`:["train","actor_train","critic_train"].includes(y.id)&&Number.isFinite(Number(c.train))?`${Number(c.train).toFixed(1)}s`:y.id==="created"&&n.created_at?"created":Wi(y,h,n)?["succeeded","done"].includes(n.status)?"complete":n.status:x{const b=Wi(y,h,n);return m.jsxs("div",{className:dt("stageCell",x<=g&&"done",b&&"current"),children:[m.jsx("strong",{children:y.label}),m.jsx("span",{children:p(y,x)})]},y.id)})})]})}function nr(n,i){var r,u,o;if(((r=n==null?void 0:n.config)==null?void 0:r[i])!==void 0&&n.config[i]!==null&&n.config[i]!=="")return n.config[i];for(const c of((u=n==null?void 0:n.config)==null?void 0:u.sections)||[]){const f=(c.items||[]).find(h=>h.key===i);if((f==null?void 0:f.value)!==void 0&&f.value!==null&&f.value!=="")return f.value}return((o=n==null?void 0:n.launch)==null?void 0:o[i])!==void 0&&n.launch[i]!==null&&n.launch[i]!==""?n.launch[i]:null}function Ay(n=[]){return[...n].sort((i,r)=>Date.parse(r.created_at||0)-Date.parse(i.created_at||0))[0]||null}function iA(n){return String((n==null?void 0:n.status)||"").toLowerCase()==="running"}function aA(n){return String(n).replace(/\/$/,"").split("/").pop()||n}function rA({job:n,env:i,onStop:r}){var f;const u=qc(n,["rollout/rewards_mean","reward_mean","reward"]),o=(n.timeperf||[]).slice(-1)[0],c=(f=i==null?void 0:i.gpus)==null?void 0:f[0];return m.jsx("div",{className:"selectedJobArea",children:m.jsxs("div",{className:"jobDetailPreviewGrid",children:[m.jsxs("section",{className:"panel jobDetailOverviewCard",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Job Detail: Overview"}),m.jsx("p",{children:"Current health and recent progress for the selected job."})]}),m.jsxs("div",{className:"detailActions",children:[m.jsx(Mt,{status:n.status}),n.status==="running"&&m.jsxs("button",{className:"dangerButton",onClick:r,children:[m.jsx(yy,{size:16})," Stop"]})]})]}),m.jsxs("div",{className:"jobIdentity",children:[m.jsx("strong",{children:n.name}),m.jsx("span",{className:"mono subline",children:n.id})]}),m.jsxs("p",{className:"healthSummary",children:[m.jsx("strong",{children:"Health summary:"})," ",sA(n)]}),m.jsxs("div",{className:"detailMetricGrid",children:[m.jsxs("div",{children:[m.jsx("span",{children:"Reward"}),m.jsx("strong",{children:u==null?"No data":cf(u)})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Step time"}),m.jsx("strong",{children:o!=null&&o.total_s?`${Number(o.total_s).toFixed(1)}s`:"No data"})]}),m.jsxs("div",{children:[m.jsx("span",{children:"GPU memory"}),m.jsx("strong",{children:c?`${c.memory_used_mb??0} MB`:"No data"})]})]})]}),m.jsxs("section",{className:"panel rolloutSamplePanel",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Rollout Sample"}),m.jsx("p",{children:"Inspect prompt and completion pairs by step and sample."})]})}),m.jsx(Ny,{samples:n.samples||[],jobId:n.id,hideTitle:!0})]})]})})}function uA({job:n,refreshNonce:i,onBack:r,onStop:u}){const o=n.logs||[];return m.jsxs("div",{className:"jobFullDetailPage",children:[m.jsxs("div",{className:"detailPageToolbar",children:[m.jsxs("button",{className:"secondaryButton",onClick:r,children:[m.jsx(kk,{size:16})," Back to Jobs"]}),n.status==="running"&&m.jsxs("button",{className:"dangerButton",onClick:u,children:[m.jsx(yy,{size:16})," Stop job"]})]}),m.jsx(cA,{job:n,detail:!0,refreshNonce:i}),m.jsxs("section",{className:"panel jobDetailSection",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Metrics"}),m.jsx("p",{children:"Training quality and stage timing for this job."})]})}),m.jsx(vA,{job:n,refreshNonce:i})]}),m.jsxs("section",{className:"panel jobDetailSection",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"Rollout Sample"}),m.jsx("p",{children:"Prompt and completion output captured during rollout."})]})}),m.jsx(Ny,{samples:n.samples||[],jobId:n.id,hideTitle:!0})]}),m.jsxs("div",{className:"jobDetailDataGrid",children:[m.jsx(ZA,{config:n.config,launch:n.launch}),m.jsx(JA,{logs:o})]})]})}function sA(n){return n.status==="running"?`The job is running at ${n.stage||"its current stage"}, step ${n.step??0}, with no terminal status reported.`:n.status==="failed"?`The job failed during ${n.stage||"an unknown stage"}. Review metrics and logs below.`:["succeeded","done"].includes(n.status)?`The job completed successfully after ${n.step??0} steps.`:`The job is ${n.status||"unknown"} at ${n.stage||"an unknown stage"}, step ${n.step??0}.`}function oA(n){const i=Date.parse((n==null?void 0:n.created_at)||""),r=Date.parse((n==null?void 0:n.status)==="running"?new Date().toISOString():(n==null?void 0:n.updated_at)||"");if(!Number.isFinite(i)||!Number.isFinite(r))return"—";const u=Math.max(0,Math.round((r-i)/1e3));return u<60?`${u}s`:u<3600?`${Math.floor(u/60)}m ${u%60}s`:`${Math.floor(u/3600)}h ${Math.floor(u%3600/60)}m`}function cA({job:n,compact:i=!1,detail:r=!1,refreshNonce:u=0,onOpen:o,onStop:c}){return m.jsxs("section",{className:dt("panel","jobOverview",r&&"detailPanel"),children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("span",{className:"sectionEyebrow",children:i?"Latest job":"Selected job"}),m.jsx("h2",{children:r?"Job Detail: Overview":n.name}),r&&m.jsx("strong",{className:"detailJobName",children:n.name}),m.jsxs("p",{className:"mono",children:[n.id," · updated ",fA(n.updated_at)]})]}),m.jsxs("div",{className:"detailActions",children:[m.jsx(Mt,{status:n.status}),i&&m.jsx("button",{className:"secondaryButton",onClick:o,children:"Open job"})]})]}),m.jsxs("div",{className:"jobOverviewStats",children:[m.jsxs("div",{children:[m.jsx("span",{children:"Stage"}),m.jsx("strong",{children:n.stage||"unknown"})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Step"}),m.jsx("strong",{children:n.step??0})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Latest signal"}),m.jsx("strong",{children:wy(n)})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Process"}),m.jsx("strong",{children:n.pid?`PID ${n.pid}`:n.kind})]})]}),m.jsx(NA,{job:n})]})}function li({label:n,value:i,detail:r,tone:u="neutral"}){return m.jsxs("div",{className:dt("summaryCard",u),children:[m.jsx("span",{children:n}),m.jsx("strong",{children:i}),m.jsx("small",{children:r})]})}function Mt({status:n="unknown"}){const i=String(n).toLowerCase(),r=i==="succeeded"||i==="done"?"ok":i;return m.jsxs("span",{className:dt("statusBadge",r),children:[m.jsx("i",{}),n]})}function qc(n,i){if(!(n!=null&&n.perf))return null;for(const r of i)if(Number.isFinite(Number(n.perf[r])))return Number(n.perf[r]);return null}function cf(n){if(!Number.isFinite(Number(n)))return"—";const i=Number(n);return Math.abs(i)>=100?i.toFixed(0):i.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function wy(n){const i=Object.entries((n==null?void 0:n.perf)||{}).filter(([,o])=>Number.isFinite(Number(o)));if(!i.length)return"No metrics";const[r,u]=i[0];return`${r} ${cf(u)}`}function fA(n){const i=Date.parse(n||"");if(!Number.isFinite(i))return"—";const r=Math.max(0,Math.round((Date.now()-i)/1e3));return r<60?`${r}s ago`:r<3600?`${Math.floor(r/60)}m ago`:r<86400?`${Math.floor(r/3600)}h ago`:`${Math.floor(r/86400)}d ago`}function dA({env:n,onRefresh:i}){var x,b,S;const[r,u]=ie.useState(null),o=(n==null?void 0:n.report)||{},c=o.torch||{},f=(n==null?void 0:n.checks)||[],h=(n==null?void 0:n.gpus)||((x=o==null?void 0:o.torch)==null?void 0:x.gpus)||[],g=((b=n==null?void 0:n.check_counts)==null?void 0:b.warn)??f.filter(w=>String(w.status).toLowerCase()==="warn").length,p=((S=n==null?void 0:n.check_counts)==null?void 0:S.fail)??f.filter(w=>String(w.status).toLowerCase()==="fail").length,y=p?`${p} FAIL`:g?`${g} WARN`:"Clear";return m.jsxs("div",{className:"runtimePrdPage",children:[m.jsxs("section",{className:"runtimeSummaryGrid",children:[m.jsx(li,{label:"AReno Check",value:n!=null&&n.ready?"Ready":n?"Needs attention":"Checking",detail:`Last refreshed ${new Date().toLocaleTimeString()}`,tone:n!=null&&n.ready?"ok":"warn"}),m.jsx(li,{label:"PyTorch / CUDA",value:`${c.version||"n/a"} / ${c.cuda_runtime||c.cuda_build||"n/a"}`,detail:c.cuda_available?"Compatible runtime detected":"CUDA runtime unavailable",tone:c.cuda_available?"ok":"warn"}),m.jsx(li,{label:"Dependency Risk",value:y,detail:mA(f),tone:p||g?"warn":"ok"})]}),m.jsxs("div",{className:"runtimePrdLayout",children:[m.jsxs("section",{className:"panel runtimeChecksPanel",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Environment Checks"}),m.jsx("p",{children:"Runtime requirements, compatibility, and actionable diagnostics."})]}),m.jsxs("button",{className:"secondaryButton",onClick:i,children:[m.jsx(sf,{size:15})," Run Check"]})]}),m.jsxs("div",{className:"runtimeCheckList",children:[f.length===0&&m.jsx(ai,{title:"No checks reported",text:"Run the environment check to populate diagnostics."}),f.slice(0,12).map((w,j)=>m.jsxs("div",{className:"runtimeCheckRow",children:[m.jsx(Mt,{status:w.status||"unknown"}),m.jsxs("div",{children:[m.jsx("strong",{children:w.name||w.label||"Runtime check"}),m.jsx("p",{children:w.detail||w.message||"No additional details."})]}),m.jsx("button",{className:"secondaryButton tableAction",title:"Diagnostic details",onClick:()=>u(w),children:"Details"})]},`${w.name||w.label}-${j}`))]})]}),m.jsxs("section",{className:"panel runtimeGpuPanel",children:[m.jsx("div",{className:"panelHeader",children:m.jsxs("div",{children:[m.jsx("h2",{children:"GPU Cards"}),m.jsx("p",{children:"Memory pressure and utilization before launch."})]})}),m.jsxs("div",{className:"runtimeGpuList",children:[h.length===0&&m.jsx(ai,{title:"No GPUs reported",text:"GPU cards appear when CUDA devices are visible."}),h.map((w,j)=>m.jsx(pA,{gpu:w,index:j},w.index??j))]})]})]}),r&&m.jsx(Zu,{title:`${r.name||r.label||"Environment Check"} Details`,onClose:()=>u(null),children:m.jsx(hA,{check:r,report:o,onClose:()=>u(null)})})]})}function hA({check:n,report:i,onClose:r}){var f,h,g,p,y,x,b;const u=(i==null?void 0:i.torch)||{},o=(i==null?void 0:i.cuda)||{},c=[["AReno",(f=i==null?void 0:i.areno)==null?void 0:f.version],["Python",(h=i==null?void 0:i.python)==null?void 0:h.version],["PyTorch",u.version],["CUDA build",u.cuda_build],["CUDA runtime",u.cuda_runtime],["CUDA available",u.cuda_available],["Visible GPUs",u.device_count],["NVCC",((g=o.nvcc)==null?void 0:g.version)||((p=o.nvcc)==null?void 0:p.path)],["NVIDIA driver",(y=o.driver)==null?void 0:y.driver_version],["Driver CUDA",(x=o.driver)==null?void 0:x.cuda_version],["Platform",(b=i==null?void 0:i.platform)==null?void 0:b.platform]].filter(([,S])=>S!=null&&S!=="");return m.jsxs("div",{className:"runtimeCheckDetails",children:[m.jsxs("div",{className:"runtimeCheckDetailLead",children:[m.jsx(Mt,{status:n.status||"unknown"}),m.jsxs("div",{children:[m.jsx("strong",{children:n.detail||n.message||"No diagnostic value reported."}),n.next_step&&m.jsx("p",{children:n.next_step})]})]}),m.jsx("div",{className:"runtimeVersionGrid",children:c.map(([S,w])=>m.jsxs("div",{children:[m.jsx("span",{children:S}),m.jsx("strong",{children:String(w)})]},S))}),m.jsx("button",{className:"primaryButton fullButton",onClick:r,children:"Done"})]})}function mA(n){const i=n.find(r=>["fail","warn"].includes(String(r.status).toLowerCase()));return(i==null?void 0:i.name)||(i==null?void 0:i.label)||"No dependency warnings"}function pA({gpu:n,index:i}){const r=Number(n.memory_used_mb??n.memory_used??0),u=Number(n.memory_total_mb??n.memory_total??0),o=Number(n.utilization??n.utilization_gpu??0),c=u>0?Math.min(100,r/u*100):0;return m.jsxs("div",{className:"runtimeGpuCard",children:[m.jsxs("div",{children:[m.jsxs("strong",{children:["GPU ",n.index??i," · ",n.name||"CUDA device"]}),m.jsxs("span",{children:[r.toFixed(0)," / ",u.toFixed(0)," MB · Util ",o.toFixed(0),"%"]})]}),m.jsx("div",{className:"meterTrack",children:m.jsx("i",{style:{width:`${c}%`}})})]})}function gA({provider:n,setProvider:i}){return m.jsxs("div",{className:"agentConfig modalForm",children:[m.jsx(Hu,{label:"Base URL",value:n.base_url||"",onChange:r=>i({...n,base_url:r}),compact:!0}),m.jsx(Hu,{label:"Model",value:n.model||"",onChange:r=>i({...n,model:r}),compact:!0}),m.jsxs("label",{className:"field compact",children:[m.jsx("span",{children:"API key"}),m.jsx("input",{type:"password",value:n.api_key||"",onChange:r=>i({...n,api_key:r.target.value})})]})]})}function yA({sessions:n,activeId:i,onOpen:r,onNew:u}){return m.jsxs("div",{className:"agentHistory",children:[m.jsxs("div",{className:"agentHistoryHeader",children:[m.jsxs("div",{children:[m.jsx("h3",{children:"Chat History"}),m.jsxs("p",{children:[n.length," saved conversations in this browser."]})]}),m.jsxs("button",{className:"secondaryButton",onClick:u,children:[m.jsx(xy,{size:15})," New Chat"]})]}),m.jsx("div",{className:"agentHistoryList",children:n.map(o=>{const c=[...o.messages||[]].reverse().find(f=>f.role==="user"||f.content);return m.jsxs("button",{className:dt("agentHistoryItem",o.id===i&&"active"),onClick:()=>r(o.id),children:[m.jsx("strong",{children:o.title||"New chat"}),m.jsx("span",{children:(c==null?void 0:c.content)||"No messages yet."}),m.jsx("small",{children:new Date(o.updatedAt||o.createdAt||Date.now()).toLocaleString()})]},o.id)})})]})}function Zu({title:n,children:i,onClose:r}){return m.jsx("div",{className:"modalOverlay",role:"presentation",onMouseDown:r,children:m.jsxs("div",{className:"modalCard",role:"dialog","aria-modal":"true","aria-label":n,onMouseDown:u=>u.stopPropagation(),children:[m.jsxs("div",{className:"modalHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:n}),m.jsx("p",{children:"Stored locally in this browser."})]}),m.jsx("button",{className:"iconButton",onClick:r,children:"×"})]}),i]})})}function xA({result:n,onClose:i}){var u,o;const r=((u=n.env)==null?void 0:u.check_counts)||{};return m.jsxs(Zu,{title:"Runtime Check Result",onClose:i,children:[m.jsxs("div",{className:"runtimeResultSummary",children:[m.jsx(Mt,{status:(o=n.env)!=null&&o.ready?"ok":"warn"}),m.jsxs("span",{children:[r.ok||0," OK · ",r.warn||0," WARN · ",r.fail||0," FAIL"]})]}),m.jsx("pre",{className:"runtimeCommandResult",children:n.output||`$ areno check +No output returned.`}),m.jsx("button",{className:"primaryButton fullButton",onClick:i,children:"Done"})]})}function vA({job:n,refreshNonce:i}){return m.jsxs("div",{className:"jobMetricsGrid",children:[m.jsx("div",{className:"panel insetPanel",children:m.jsx(DA,{jobId:n==null?void 0:n.id,metricsDir:n==null?void 0:n.metrics_dir,refreshNonce:i})}),m.jsx("div",{className:"panel insetPanel",children:m.jsx(LA,{rows:(n==null?void 0:n.timeperf)||[],job:n})})]})}function bA({events:n,onPlanConfirm:i}){const r=n.filter(o=>{var c;return o.type==="tool_result"&&((c=o.result)==null?void 0:c.plan)}),u=n.filter(o=>{var c;return!(o.type==="tool_result"&&((c=o.result)!=null&&c.plan))});return m.jsxs("div",{className:"agentEventList",children:[u.map((o,c)=>o.type==="reasoning"?m.jsx(wA,{text:o.text},c):o.type==="content"?m.jsx(ff,{text:o.text},c):o.type==="tool_call"?m.jsx(EA,{call:o.call,live:o.live},c):o.type==="tool_result"?m.jsx(CA,{result:o.result},c):null),r.map((o,c)=>m.jsx(SA,{plan:o.result.plan,onConfirm:i},o.result.plan.id||c))]})}function SA({plan:n,onConfirm:i}){const[r,u]=ie.useState(!1),[o,c]=ie.useState(n.parameters||{}),[f,h]=ie.useState(null);ie.useEffect(()=>c(n.parameters||{}),[n.id]);const g=Object.entries(o),p=n.tool||Ey(n),y=_A(p,o),x={...n,tool:p,parameters:o,command:y};return m.jsxs("section",{className:"agentPlanCard",children:[m.jsxs("div",{className:"agentPlanHeader",children:[m.jsxs("div",{children:[m.jsx("span",{children:"Execution plan"}),m.jsx("strong",{children:n.objective})]}),m.jsx(Mt,{status:n.status||"proposed"})]}),n.summary&&m.jsx("p",{className:"agentPlanSummary",children:n.summary}),g.length>0&&m.jsx("div",{className:dt("agentPlanParams",r&&"editing"),children:g.map(([b,S])=>m.jsxs("label",{children:[m.jsx("span",{children:b.replaceAll("_"," ")}),r?m.jsx("input",{value:String(S),onChange:w=>c(j=>({...j,[b]:w.target.value}))}):m.jsx("strong",{children:String(S)})]},b))}),m.jsx("ol",{className:"agentPlanSteps",children:(n.steps||[]).map((b,S)=>m.jsxs("li",{children:[m.jsx("span",{children:S+1}),m.jsxs("div",{children:[m.jsx("strong",{children:b.title}),b.detail&&m.jsx("p",{children:b.detail})]}),m.jsx("small",{children:b.status||"pending"})]},b.id||S))}),y&&m.jsx("pre",{className:"agentPlanCommand",children:y}),m.jsxs("div",{className:"agentPlanActions",children:[m.jsx("button",{className:"primaryButton",disabled:(f==null?void 0:f.status)==="running",onClick:async()=>{var b;h({status:"running",message:"Starting..."});try{const S=await(i==null?void 0:i(x));h({status:(S==null?void 0:S.ok)===!1?"failed":"ok",message:(b=S==null?void 0:S.job)!=null&&b.id?`Started job ${S.job.id}`:"Execution completed"})}catch(S){h({status:"failed",message:S.message||String(S)})}},children:(f==null?void 0:f.status)==="running"?"Executing...":"Confirm Execution"}),g.length>0&&m.jsx("button",{className:"secondaryButton",onClick:()=>u(b=>!b),children:r?"Save Parameters":"Edit Parameters"}),y&&m.jsx("button",{className:"secondaryButton",onClick:()=>navigator.clipboard.writeText(y),children:"Copy Command"})]}),f&&f.status!=="running"&&m.jsx("p",{className:dt("agentPlanExecution",f.status),children:f.message})]})}function Ey(n){const i=String((n==null?void 0:n.command)||"").toLowerCase();return i.includes("--smoke-train")?"smoke_train":i.includes("--smoke-infer")?"smoke_infer":/\bareno\s+serve\b/.test(i)?"start_serve":"start_train"}function _A(n,i={}){const r=n==="start_serve"?"serve":"train",u=[],o=new Map([["activation_checkpointing","--no-activation-checkpointing"],["fp8_checkpoint_activations","--no-fp8-ckpt-activations"],["drop_rollout_state","--keep-rollout-state"],["use_kl_loss","--no-use-kl-loss"]]);for(const[f,h]of Object.entries(i)){if(f==="extra_args"||h===""||h===null||h===void 0)continue;const g=`--${f.replaceAll("_","-")}`;if(kA(h)){AA(h)?u.push(g):o.has(f)&&u.push(o.get(f));continue}u.push(`${g} ${hf(h)}`)}n==="smoke_train"&&u.push("--smoke-train"),n==="smoke_infer"&&u.push("--smoke-infer");const c=String(i.extra_args||"").trim();return c&&u.push(c),[`areno ${r} \\`,...u.map((f,h)=>` ${f}${h`${i.id} · ${i.kind} · ${i.status} · step ${i.step??0} · ${i.name}`).join(` `)||"No jobs.":n.job?`${n.job.id} · ${n.job.kind} · ${n.job.status} · step ${n.job.step??0} -${n.job.name}`:n.env?`ready=${n.env.ready} · gpu=${n.env.gpu_summary||"n/a"} · cwd=${n.env.cwd||"n/a"}`:JSON.stringify(n,null,2)}function NA({job:n}){const i=df(n),r=Ty(n),u=Math.max(0,i.findIndex(o=>Wi(o,r,n)));return m.jsx("div",{className:"timeline",children:i.map((o,c)=>m.jsxs("div",{className:dt("timelineItem",c<=u&&"done",Wi(o,r,n)&&"current"),children:[m.jsx("span",{children:c+1}),m.jsx("label",{children:o.label})]},o.id))})}function df(n){if((n==null?void 0:n.kind)==="serve")return[{id:"created",label:"created"},{id:"load",label:"load",aliases:["registered"]},{id:"serve",label:"serve",aliases:["running"]},{id:"exit",label:"exit",aliases:["exited","failed","succeeded","stopped"]}];const i=String(Fu(n,"algo")||"").toLowerCase();return i==="sft"?[{id:"created",label:"created",aliases:["registered","epoch_start"]},{id:"train",label:"train",aliases:["train_start","train_end","train_skip"]},{id:"save",label:"save",aliases:["save_checkpoint_start","save_checkpoint_end"]},{id:"done",label:"done",aliases:["max_steps_reached","epoch_end","exited","failed","succeeded","stopped"]}]:i==="dpo"?[{id:"created",label:"created",aliases:["registered","epoch_start"]},{id:"ref_score",label:"ref score",aliases:["logprob_score_start","logprob_score_end"],roles:["ref"]},{id:"train",label:"train",aliases:["train_start","train_end","train_skip"]},{id:"save",label:"save",aliases:["save_checkpoint_start","save_checkpoint_end"]},{id:"done",label:"done",aliases:["max_steps_reached","epoch_end","exited","failed","succeeded","stopped"]}]:i==="ppo"?[{id:"created",label:"created",aliases:["registered","epoch_start"]},{id:"rollout",label:"rollout",aliases:["rollout_start","rollout_end"],roles:["actor"]},{id:"reward",label:"reward",aliases:["score_start","score_end"],roles:["reward"]},{id:"ref_score",label:"ref score",aliases:["logprob_score_start","logprob_score_end"],roles:["ref"]},{id:"old_logprob",label:"old logprob",aliases:["old_logprob_score_start","old_logprob_score_end"],roles:["actor"]},{id:"critic_value",label:"value",aliases:["value_score_start","value_score_end"],roles:["critic"]},{id:"advantage_prepare",label:"advantage",aliases:["advantage_start"],roles:["critic"]},{id:"critic_train",label:"critic train",aliases:["train_start","train_end"],roles:["critic"]},{id:"advantage_ready",label:"advantage ready",aliases:["advantage_end"],roles:["critic"]},{id:"actor_train",label:"actor train",aliases:["train_start","train_end","train_skip"],roles:["actor"]},{id:"save",label:"save",aliases:["save_checkpoint_start","save_checkpoint_end"]},{id:"done",label:"done",aliases:["max_steps_reached","epoch_end","exited","failed","succeeded","stopped"]}]:[{id:"created",label:"created",aliases:["registered","epoch_start"]},{id:"rollout",label:"rollout",aliases:["rollout_start","rollout_end"]},{id:"score",label:"score",aliases:["score_start","score_end","reward_score_start","reward_score_end","logprob_score_start","logprob_score_end","old_logprob_score_start","old_logprob_score_end","value_score_start","value_score_end"]},{id:"train",label:"train",aliases:["train_start","train_end","train_skip"]},{id:"save",label:"save",aliases:["save_checkpoint_start","save_checkpoint_end"]},{id:"done",label:"done",aliases:["max_steps_reached","epoch_end","exited","failed","succeeded","stopped"]}]}function Ty(n){const i=String((n==null?void 0:n.status)||"").toLowerCase();if(["succeeded","failed","stopped","exited"].includes(i))return"done";const r=String((n==null?void 0:n.stage)||"created").toLowerCase(),o=df(n).find(c=>Wi(c,r,n));return(o==null?void 0:o.id)||r}function Wi(n,i,r){var c,f;const u=String(i||"").toLowerCase();return n.id===u||((c=n.aliases)==null?void 0:c.includes(u))?(f=n.roles)!=null&&f.length?n.roles.includes(String((r==null?void 0:r.role)||"").toLowerCase()):!0:!1}function Fu(n,i){const r=n!=null&&n.config&&Object.keys(n.config).length?n.config:(n==null?void 0:n.launch)||{};if(r[i]!==void 0)return r[i];for(const u of r.sections||[]){const o=(u.items||[]).find(c=>c.key===i);if(o)return o.value}}function Cy(n){return(n||[]).map(i=>i.name).sort()}function MA(n,i){return i&&n.includes(i)?i:n[0]||""}function DA({jobId:n,metricsDir:i,refreshNonce:r}){const[u,o]=ie.useState(""),[c,f]=ie.useState(.6),[h,g]=ie.useState([]),[p,y]=ie.useState([]),[x,v]=ie.useState(!1),[S,w]=ie.useState(0),[j,q]=ie.useState(null),[N,K]=ie.useState(n);n!==N&&(K(n),o(""),g([]),y([]),v(!1));const Y=Cy(h),se=MA(Y,u);ie.useEffect(()=>{if(!n)return;const Q=window.setInterval(()=>w(W=>W+1),2500);return()=>window.clearInterval(Q)},[n]),ie.useEffect(()=>{let Q=!1;if(n)return Pe(`/api/jobs/${n}/metrics`).then(W=>{if(Q)return;const de=W.metrics||[];g(de),o(re=>{var I;return re||((I=de[0])==null?void 0:I.name)||""})}).catch(()=>{Q||g([])}),()=>{Q=!0}},[n,r,S]),ie.useEffect(()=>{let Q=!1;if(!n||!se){y([]),v(!1);return}return v(!0),Pe(`/api/jobs/${n}/metric?name=${encodeURIComponent(se)}`).then(W=>{Q||y((W.points||[]).filter(de=>Number.isFinite(Number(de.value))).map(de=>({...de,step:Number(de.step||0),value:Number(de.value)})))}).catch(()=>{Q||y([])}).finally(()=>{Q||v(!1)}),()=>{Q=!0}},[n,se,r,S]);const ae=se,U=p,ne=OA(U,c),ue=c>0,ye=ue?ne:U,R=RA(ye);return m.jsxs("div",{className:"chart",children:[m.jsxs("div",{className:"chartHeader",children:[m.jsxs("span",{children:[m.jsx(py,{size:14})," TensorBoard scalars"]}),m.jsxs("div",{className:"chartControls",children:[m.jsx("select",{value:ae,onChange:Q=>o(Q.target.value),children:Y.length===0?m.jsx("option",{value:"",children:"no metrics"}):Y.map(Q=>m.jsx("option",{children:Q},Q))}),m.jsxs("label",{children:["smooth ",c.toFixed(2),m.jsx("input",{type:"range",min:"0",max:"0.99",step:"0.01",value:c,onChange:Q=>f(Number(Q.target.value))})]})]})]}),U.length===0?m.jsx("div",{className:"plotEmpty",children:x?"Loading selected metric...":"No TensorBoard scalar points loaded yet."}):m.jsxs("div",{className:"metricPlotWrap",children:[m.jsxs("svg",{className:"metricPlot",viewBox:"0 0 720 180",role:"img",children:[m.jsx("g",{className:"plotGrid",children:[0,1,2,3].map(Q=>m.jsx("line",{x1:"0",x2:"720",y1:30+Q*42,y2:30+Q*42},Q))}),m.jsx("polyline",{className:ue?"smoothLine":"rawLine",points:R.line}),!ue&&ye.map((Q,W)=>{var de,re,I,M;return m.jsxs("g",{children:[m.jsx("circle",{className:"metricDataPoint",cx:((de=R.coords[W])==null?void 0:de.x)||0,cy:((re=R.coords[W])==null?void 0:re.y)||0,r:ky(ye.length)}),m.jsx("circle",{className:"metricHoverTarget",cx:((I=R.coords[W])==null?void 0:I.x)||0,cy:((M=R.coords[W])==null?void 0:M.y)||0,r:"5",onMouseEnter:()=>q({point:Q,coord:R.coords[W]}),onMouseLeave:()=>q(null)})]},`${Q.step}-${W}`)})]}),!ue&&j&&m.jsx(_y,{name:ae,point:j.point,coord:j.coord,width:720,height:180})]}),m.jsxs("div",{className:"plotFooter",children:[m.jsxs("span",{children:[ae||"metric"," · ",p.length," points"]}),m.jsxs("span",{children:[i||"no metrics dir"," · ",R.minLabel," to ",R.maxLabel]})]})]})}function OA(n,i){if(!n.length)return[];const r=Math.min(Math.max(Number(i)||0,0),.999);let u=n[0].value;return n.map(o=>(u=u*r+o.value*(1-r),{...o,value:u}))}function RA(n){if(!n.length)return{line:"",coords:[],minLabel:"n/a",maxLabel:"n/a"};const{min:i,max:r}=Gc(n,y=>y.value),u=r===i,o=Math.max(r-i,1e-9),c=n[0].step,f=n[n.length-1].step,h=Math.max(f-c,1),g=y=>({x:(y.step-c)/h*700+10,y:u?95:168-(y.value-i)/o*146}),p=n.map(g);return{line:p.map(y=>`${y.x.toFixed(1)},${y.y.toFixed(1)}`).join(" "),coords:p,minLabel:ta(i),maxLabel:ta(r)}}function Gc(n,i){let r=1/0,u=-1/0;for(const o of n){const c=Number(i(o));cu&&(u=c)}return{min:r,max:u}}function ta(n){return Number.isFinite(n)?Math.abs(n)>=1e3||Math.abs(n)<.001?n.toExponential(2):n.toFixed(4).replace(/0+$/,"").replace(/\.$/,""):"n/a"}function LA({rows:n,job:i}){const r=BA(n||[],i),u=HA(r,7).reverse(),o=r.length?r.reduce((h,g)=>h+Number(g.total_s||0),0)/r.length:0,c=Math.max(1,...u.map(h=>Number(h.total_s||0))),f=Array.from(new Set(r.flatMap(h=>(h.segments||[]).map(g=>g.name)))).slice(0,8);return m.jsxs("div",{className:"timePerf",children:[m.jsxs("div",{className:"timePerfHeader",children:[m.jsx("div",{children:m.jsxs("div",{className:"codeTitle inline",children:[m.jsx(Bk,{size:14})," Runtime timeperf"]})}),m.jsxs("div",{className:"legend",children:[f.map(h=>m.jsxs("span",{children:[m.jsx("i",{className:ag(h)})," ",h]},h)),m.jsxs("b",{children:["avg ",o?`${o.toFixed(1)}s`:"n/a"]})]})]}),u.length===0?m.jsx("div",{className:"sampleEmpty",children:"No step timing captured yet."}):m.jsx("div",{className:"timeRows",children:u.map(h=>{var x;const g=Number(h.total_s||0),p=Math.max(10,g/c*100),y=(x=h.segments)!=null&&x.length?h.segments:[];return m.jsxs("div",{className:"timeRow",children:[m.jsxs("label",{children:["step ",h.step]}),m.jsx("div",{className:"timeTrack",children:m.jsx("div",{className:"timeStack",style:{width:`${p}%`},children:y.map(v=>{const S=Number(v.seconds||0),w=S/Math.max(g,1)*100;return m.jsx("span",{className:ag(v.name),style:{width:`${w}%`},title:`${v.name}: ${S.toFixed(1)}s`,children:w>11?`${S.toFixed(1)}s`:""},v.name)})})}),m.jsxs("strong",{children:[g.toFixed(1),"s"]})]},`${h.step}-${h.time}`)})})]})}function BA(n,i){const r=String(Fu(i,"algo")||"").toLowerCase(),u=UA(r,i==null?void 0:i.kind);return n.map(o=>{const c=[];let f=0;for(const h of o.segments||[]){const g=Number(h.seconds||0);u.has(h.name)?c.push({...h,seconds:g}):f+=g}if(f>0){const h=c.find(g=>g.name==="other");h?h.seconds+=f:c.push({name:"other",seconds:f})}return{...o,segments:c}})}function UA(n,i){return i==="serve"?new Set(["load","prefill","decode","other"]):n==="sft"?new Set(["train","save","other"]):n==="dpo"?new Set(["ref log probs","train","save","other"]):n==="ppo"?new Set(["rollout","make_sample","reward","old policy log probs","actor log probs","ref log probs","value","advantages","sync weight","train","save","other"]):new Set(["rollout","make_sample","reward","old policy log probs","actor log probs","ref log probs","advantages","sync weight","train","save","other"])}function HA(n,i){if(n.length<=i)return n.slice();const r=n.length-1,u=new Set;for(let o=0;oo-c).slice(-i).map(o=>n[o])}function ag(n){return`seg-${String(n||"other").replace(/[^a-zA-Z0-9]+/g,"-")}`}function qA(n){for(const i of[n.completion,n.rendered_completion,n.final_answer])if(typeof i=="string"&&i.trim())return i;return Array.isArray(n.tool_calls)&&n.tool_calls.length?JSON.stringify(n.tool_calls,null,2):"No assistant output was captured."}function zy(n){var r;if(Array.isArray(n.prompt_messages))return n.prompt_messages;if(!Array.isArray(n.messages))return[];const i=[...n.messages];return((r=i.at(-1))==null?void 0:r.role)==="assistant"&&i.pop(),i}function GA(n){if(!n||typeof n!="object")return null;const i=String(n.type||"");if(i==="input_audio"){const o=n.input_audio;if(!(o!=null&&o.data)||String(o.data).includes(""))return null;const c=String(o.format||"wav").toLowerCase(),f=c==="mp3"?"audio/mpeg":`audio/${c}`;return{type:"audio",source:String(o.data).startsWith("data:")?o.data:`data:${f};base64,${o.data}`}}const r=i.replace(/_url$/,"");if(!["image","audio","video"].includes(r))return null;let u=n[i]??n[r]??n.url;return u&&typeof u=="object"&&(u=u.url),typeof u=="string"&&u?{type:r,source:u}:null}function YA(n){const i=[],r=o=>{o&&!i.some(c=>c.type===o.type&&c.source===o.source)&&i.push(o)};for(const o of zy(n))if(Array.isArray(o==null?void 0:o.content))for(const c of o.content)r(GA(c));const u=(o,c="")=>{if(Array.isArray(o)){o.forEach(p=>u(p,c));return}if(o&&typeof o=="object"){Object.entries(o).forEach(([p,y])=>u(y,p));return}if(typeof o!="string")return;const f=c.toLowerCase(),h=["video","audio","image"].find(p=>f.includes(p)),g=["video","videos","audio","audios","image","images"].includes(f);h&&(g||["path","url","file"].some(p=>f.includes(p)))&&r({type:h,source:o})};return u(n.source_record),i}function VA(n,i){return/^(data:|blob:|https?:)/.test(i)?i:`${of}api/jobs/${encodeURIComponent(n)}/media?path=${encodeURIComponent(i)}`}function QA({jobId:n,media:i}){if(!n||!i.length)return null;const r=i.some(c=>c.type==="video"),u=i.some(c=>c.type==="audio"),o=r&&u?"Video + audio":r?"Video":u?"Audio":"Image";return m.jsxs("section",{className:"sampleMediaSection",children:[m.jsxs("div",{className:"sampleSectionLabel",children:[r?m.jsx(Ek,{size:14}):u?m.jsx(Uk,{size:14}):m.jsx(Tk,{size:14}),o]}),m.jsx("div",{className:dt("sampleMediaGrid",i.length===1&&"single"),children:i.map((c,f)=>{const h=VA(n,c.source);return c.type==="video"?m.jsx("video",{src:h,controls:!0,preload:"metadata"},`${c.type}-${c.source}`):c.type==="audio"?m.jsx("audio",{src:h,controls:!0,preload:"metadata"},`${c.type}-${c.source}`):m.jsx("img",{src:h,alt:`Sample media ${f+1}`,loading:"lazy"},`${c.type}-${c.source}`)})})]})}function rg({icon:n,label:i,value:r,emptyText:u}){return m.jsxs("section",{className:"sampleDetailSection",children:[m.jsxs("div",{className:"sampleSectionLabel",children:[n,i]}),m.jsx("pre",{children:r==null?u:JSON.stringify(r,null,2)})]})}function Ny({samples:n,jobId:i,hideTitle:r=!1}){const u=ie.useMemo(()=>[...n||[]].sort((j,q)=>Number(j.step||0)-Number(q.step||0)||Number(j.prompt_idx||0)-Number(q.prompt_idx||0)||Number(j.sample_idx||0)-Number(q.sample_idx||0)),[n]),o=ie.useMemo(()=>Array.from(new Set(u.map(j=>Number(j.step||0)))).sort((j,q)=>q-j),[u]),[c,f]=ie.useState(""),[h,g]=ie.useState("");ie.useEffect(()=>{if(!o.length){f(""),g("");return}(c===""||!o.includes(Number(c)))&&(f(String(o[0])),g(""))},[c,o]);const y=(c===""?[]:u.filter(j=>Number(j.step||0)===Number(c))).map((j,q)=>({key:XA(j,q),label:`prompt ${j.prompt_idx??"?"} · sample ${j.sample_idx??"?"}`,sample:j})),x=y.find(j=>j.key===h)||y[y.length-1]||null,v=(x==null?void 0:x.sample)||null,S=ie.useMemo(()=>v?YA(v):[],[v]),w=v?zy(v):[];return m.jsxs("div",{className:"sampleCard",children:[!r&&m.jsxs("div",{className:"codeTitle sampleTitle",children:[m.jsxs("span",{children:[m.jsx(Wp,{size:14})," Rollout sample"]}),!!u.length&&m.jsxs("div",{className:"sampleControls",children:[m.jsx("select",{value:c,onChange:j=>{f(j.target.value),g("")},children:o.map(j=>m.jsxs("option",{value:j,children:["step ",j]},j))}),m.jsx("select",{value:(x==null?void 0:x.key)||"",onChange:j=>g(j.target.value),children:y.map(j=>m.jsx("option",{value:j.key,children:j.label},j.key))})]})]}),v?m.jsxs("div",{className:"sampleContent",children:[m.jsx(QA,{jobId:i,media:S}),m.jsxs("div",{className:"sampleGrid",children:[m.jsxs("div",{children:[m.jsx("span",{children:"Prompt"}),m.jsx("p",{children:v.prompt||"No prompt text was captured."})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Output"}),m.jsx("p",{children:qA(v)})]})]}),m.jsxs("div",{className:"sampleDetailGrid",children:[m.jsx(rg,{icon:m.jsx(Wp,{size:14}),label:"Full prompt",value:w.length?w:null,emptyText:"No structured prompt messages were captured."}),m.jsx(rg,{icon:m.jsx(wk,{size:14}),label:"Data record",value:v.source_record,emptyText:"No source dataset record was captured."})]})]}):m.jsx("div",{className:"sampleEmpty",children:"No rollout sample captured yet."})]})}function XA(n,i){return`${n.step??"x"}-${n.prompt_idx??"x"}-${n.sample_idx??"x"}-${i}`}function ZA({config:n,launch:i}){const r=n&&Object.keys(n).length?n:i||{},u=FA(r);return m.jsxs("div",{className:"codeCard",children:[m.jsxs("div",{className:"codeTitle",children:[m.jsx(by,{size:14})," Config"]}),u.length>0?m.jsx("div",{className:"configSections",children:u.map(o=>m.jsxs("div",{className:"configSection",children:[m.jsx("h3",{children:o.title}),m.jsx("div",{className:"configGrid",children:o.items.map(({key:c,value:f})=>m.jsxs("div",{className:"configItem",children:[m.jsx("span",{children:c.replace(/_/g," ")}),m.jsx("strong",{children:KA(f)})]},c))})]},o.title))}):m.jsx("pre",{children:"No config captured yet."})]})}function FA(n){if(Array.isArray(n==null?void 0:n.sections))return n.sections.map(r=>({title:r.title||"Config",items:(r.items||[]).filter(({value:u})=>u!=null&&u!=="")})).filter(r=>r.items.length>0);const i=Object.entries(n||{}).filter(([,r])=>r!=null&&r!=="").map(([r,u])=>({key:r,value:u}));return i.length?[{title:"Launch",items:i}]:[]}function KA(n){return Array.isArray(n)?n.join(" "):typeof n=="object"?JSON.stringify(n):String(n)}function JA({logs:n}){const i=ie.useRef(null);return ie.useEffect(()=>{const r=i.current;r&&(r.scrollTop=r.scrollHeight)},[n.length]),m.jsxs("div",{className:"codeCard",ref:i,children:[m.jsxs("div",{className:"codeTitle",children:[m.jsx(Rk,{size:14})," Logs"]}),m.jsx("pre",{children:n.slice(-80).join(` -`)||"No logs yet."})]})}function $A({mode:n,setMode:i,trainConfig:r,setTrainConfig:u,serveConfig:o,setServeConfig:c,onStartTrain:f,onStartServe:h,env:g,presets:p}){var R,Q,W,de,re,I,M,J;const y=n==="train"?r:o,[x,v]=ie.useState(null),[S,w]=ie.useState(""),[j,q]=ie.useState(null),N=Number(y.world_size||0),K=Number(y.tp_size||0),Y=((R=g==null?void 0:g.gpus)==null?void 0:R.length)||0,se=n==="train",ae=se&&["gspo","grpo","ppo"].includes(String(y.algo||"").toLowerCase());ie.useEffect(()=>{var T;if(!((T=j==null?void 0:j.job)!=null&&T.id)||!["created","running"].includes(j.job.status))return;let P=!1;const xe=async()=>{try{const G=await Pe(`/api/jobs/${j.job.id}`);if(P||!G.job)return;const k={...j,job:G.job};q(k),["created","running"].includes(G.job.status)||v({...k,ok:G.job.status==="succeeded",output:(G.job.logs||[]).join(` -`)})}catch(G){P||v({ok:!1,check:j.check,output:G.message})}};xe();const A=window.setInterval(xe,1e3);return()=>{P=!0,window.clearInterval(A)}},[(Q=j==null?void 0:j.job)==null?void 0:Q.id,(W=j==null?void 0:j.job)==null?void 0:W.status]);const U=[{id:"gpu_count",name:"GPU count",status:Y===0?"warn":N<=Y?"ok":"warn",detail:Y?`World size ${N} uses ${Y} visible GPU${Y===1?"":"s"}.`:"No visible GPU inventory is available.",tunable:ae&&Y>0},{id:"tensor_parallel",name:"Tensor parallelism",status:N>0&&K>0&&N%K===0?"ok":"fail",detail:N>0&&K>0&&N%K===0?`World size ${N} is divisible by TP size ${K}.`:"World size must be divisible by TP size.",tunable:se},n==="train"?{id:"batch_relation",name:"Batch relation",status:Number(y.batch_size)>0&&Number(y.mini_bs)>0&&Number(y.batch_size)%Number(y.mini_bs)===0?"ok":"fail",detail:`Batch ${y.batch_size} × samples ${y.n_samples||1}; mini batch ${y.mini_bs}.`,tunable:se}:{id:"batch_relation",name:"Serving capacity",status:Number(y.max_running_prompts)>0?"ok":"warn",detail:`${y.max_running_prompts||0} concurrent prompts configured.`,tunable:!1},...n==="train"?[{id:"max_new_tokens",name:"Max new tokens",status:Number(y.max_new_tokens)>1024?"warn":"ok",detail:Number(y.max_new_tokens)>1024?`${y.max_new_tokens} may increase rollout memory.`:`${y.max_new_tokens||0} is within the preflight target.`,tunable:ae}]:[]],ne=IA(n,y),ue=U.some(P=>P.status==="fail"),ye=async P=>{const xe=P.status!=="ok"&&P.tunable?"tune":"view";w(P.id);try{const A=await Pe("/api/launcher/preflight",{method:"POST",body:JSON.stringify({mode:n,config:y,check_id:P.id,action:xe})});xe==="tune"&&A.job?(v(null),q({...A,check:P,job:A.job})):v(A)}catch(A){v({ok:!1,check:{name:P.name,status:"fail",detail:A.message},patch:{}})}finally{w("")}};return m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"launcherPrdLayout",children:[m.jsxs("section",{className:"panel launcher launcherMainCard",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Task Launcher"}),m.jsx("p",{children:"Configure, validate, and review the generated command before launch."})]}),m.jsxs("div",{className:"tabs",children:[m.jsx("button",{className:dt(n==="train"&&"active"),onClick:()=>i("train"),children:"Train"}),m.jsx("button",{className:dt(n==="serve"&&"active"),onClick:()=>i("serve"),children:"Serve"})]})]}),n==="train"&&p.length>0&&m.jsx("div",{className:"launcherPresetRow",children:p.map(P=>m.jsx("button",{className:"presetPill",title:P.source,onClick:()=>u(xe=>({...xe,...P.preset||{}})),children:P.label},P.id))}),m.jsx("div",{className:"launcherFormScroll",children:n==="train"?m.jsx(PA,{config:r,setConfig:u,onStart:f}):m.jsx(ew,{config:o,setConfig:c,onStart:h})})]}),m.jsxs("aside",{className:"launcherSideRail",children:[m.jsxs("section",{className:"panel launcherPreflight",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Preflight"}),m.jsx("p",{children:"Resolve launch risks before allocating workers."})]}),m.jsx(Mt,{status:ue?"failed":"ok"})]}),m.jsx("div",{className:"runtimeCheckList",children:U.map(P=>{var pe,he,je,we,Ue,At;const xe=S===P.id&&P.status!=="ok"&&P.tunable,A=(j==null?void 0:j.check_id)===P.id&&["created","running"].includes((pe=j.job)==null?void 0:pe.status),T=(j==null?void 0:j.smoke_stage)==="infer"?"Smoke infer":"Smoke train",G=A&&((he=j.job)!=null&&he.created_at)?Math.max(0,Math.floor((Date.now()-Date.parse(j.job.created_at))/1e3)):0,k=A?[...((je=j.job)==null?void 0:je.logs)||[]].reverse().find(nt=>nt&&!String(nt).startsWith("$ ")):"",le=xe?"Starting smoke tuning job...":A?`${T}: ${((we=j.job)==null?void 0:we.stage)||"starting"} · step ${((Ue=j.job)==null?void 0:Ue.step)??0} · ${G}s`:P.detail;return m.jsxs("div",{className:"runtimeCheckRow launcherCheck",children:[m.jsx(Mt,{status:A?"running":P.status}),m.jsxs("div",{children:[m.jsx("strong",{children:P.name}),m.jsx("p",{children:le}),(xe||A)&&m.jsx("div",{className:"preflightProgress",role:"progressbar","aria-label":`Tuning ${P.name}`,children:m.jsx("span",{})}),A&&m.jsxs("div",{className:"preflightTuneDetails",children:[m.jsx("div",{children:Object.entries(j.tuning_params||{}).map(([nt,Dt])=>m.jsxs("span",{children:[m.jsx("b",{children:nt.replaceAll("_"," ")}),String(Dt)]},nt))}),k&&m.jsx("code",{children:k})]})]}),m.jsx("button",{className:"secondaryButton tableAction",disabled:!!S||!!(j&&["created","running"].includes((At=j.job)==null?void 0:At.status)),onClick:()=>ye(P),children:xe?"Starting...":A?`${T}...`:P.status!=="ok"&&P.tunable?"Tune":"View"})]},P.id)})})]}),m.jsxs("section",{className:"panel commandPreviewPanel",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Command Preview"}),m.jsx("p",{children:"Review the final CLI mapping."})]}),m.jsx("button",{className:"secondaryButton",onClick:()=>navigator.clipboard.writeText(ne),children:"Copy"})]}),m.jsx("pre",{className:"commandPreview",children:ne})]})]})]}),x&&m.jsxs(Zu,{title:"Preflight Result",onClose:()=>v(null),children:[m.jsxs("div",{className:"runtimeResultSummary",children:[m.jsx(Mt,{status:((de=x.job)==null?void 0:de.status)||((re=x.check)==null?void 0:re.status)||(x.ok?"ok":"failed")}),m.jsx("span",{children:((I=x.check)==null?void 0:I.name)||"Launcher check"})]}),Object.keys(x.tuning_params||{}).length>0&&m.jsx("div",{className:"preflightResultParams",children:Object.entries(x.tuning_params).map(([P,xe])=>m.jsxs("span",{children:[m.jsx("b",{children:P.replaceAll("_"," ")}),String(xe)]},P))}),m.jsxs("pre",{className:"runtimeCommandResult",children:[(M=x.command)!=null&&M.length?`$ ${x.command.map(hf).join(" ")} +${n.job.name}`:n.env?`ready=${n.env.ready} · gpu=${n.env.gpu_summary||"n/a"} · cwd=${n.env.cwd||"n/a"}`:JSON.stringify(n,null,2)}function NA({job:n}){const i=df(n),r=Ty(n),u=Math.max(0,i.findIndex(o=>Wi(o,r,n)));return m.jsx("div",{className:"timeline",children:i.map((o,c)=>m.jsxs("div",{className:dt("timelineItem",c<=u&&"done",Wi(o,r,n)&&"current"),children:[m.jsx("span",{children:c+1}),m.jsx("label",{children:o.label})]},o.id))})}function df(n){if((n==null?void 0:n.kind)==="serve")return[{id:"created",label:"created"},{id:"load",label:"load",aliases:["registered"]},{id:"serve",label:"serve",aliases:["running"]},{id:"exit",label:"exit",aliases:["exited","failed","succeeded","stopped"]}];const i=String(Fu(n,"algo")||"").toLowerCase();return i==="sft"?[{id:"created",label:"created",aliases:["registered","epoch_start"]},{id:"train",label:"train",aliases:["train_start","train_end","train_skip"]},{id:"save",label:"save",aliases:["save_checkpoint_start","save_checkpoint_end"]},{id:"done",label:"done",aliases:["max_steps_reached","epoch_end","exited","failed","succeeded","stopped"]}]:i==="dpo"?[{id:"created",label:"created",aliases:["registered","epoch_start"]},{id:"ref_score",label:"ref score",aliases:["logprob_score_start","logprob_score_end"],roles:["ref"]},{id:"train",label:"train",aliases:["train_start","train_end","train_skip"]},{id:"save",label:"save",aliases:["save_checkpoint_start","save_checkpoint_end"]},{id:"done",label:"done",aliases:["max_steps_reached","epoch_end","exited","failed","succeeded","stopped"]}]:i==="ppo"?[{id:"created",label:"created",aliases:["registered","epoch_start"]},{id:"rollout",label:"rollout",aliases:["rollout_start","rollout_end"],roles:["actor"]},{id:"reward",label:"reward",aliases:["score_start","score_end"],roles:["reward"]},{id:"ref_score",label:"ref score",aliases:["logprob_score_start","logprob_score_end"],roles:["ref"]},{id:"old_logprob",label:"old logprob",aliases:["old_logprob_score_start","old_logprob_score_end"],roles:["actor"]},{id:"critic_value",label:"value",aliases:["value_score_start","value_score_end"],roles:["critic"]},{id:"advantage_prepare",label:"advantage",aliases:["advantage_start"],roles:["critic"]},{id:"critic_train",label:"critic train",aliases:["train_start","train_end"],roles:["critic"]},{id:"advantage_ready",label:"advantage ready",aliases:["advantage_end"],roles:["critic"]},{id:"actor_train",label:"actor train",aliases:["train_start","train_end","train_skip"],roles:["actor"]},{id:"save",label:"save",aliases:["save_checkpoint_start","save_checkpoint_end"]},{id:"done",label:"done",aliases:["max_steps_reached","epoch_end","exited","failed","succeeded","stopped"]}]:[{id:"created",label:"created",aliases:["registered","epoch_start"]},{id:"rollout",label:"rollout",aliases:["rollout_start","rollout_end"]},{id:"score",label:"score",aliases:["score_start","score_end","reward_score_start","reward_score_end","logprob_score_start","logprob_score_end","old_logprob_score_start","old_logprob_score_end","value_score_start","value_score_end"]},{id:"train",label:"train",aliases:["train_start","train_end","train_skip"]},{id:"save",label:"save",aliases:["save_checkpoint_start","save_checkpoint_end"]},{id:"done",label:"done",aliases:["max_steps_reached","epoch_end","exited","failed","succeeded","stopped"]}]}function Ty(n){const i=String((n==null?void 0:n.status)||"").toLowerCase();if(["succeeded","failed","stopped","exited"].includes(i))return"done";const r=String((n==null?void 0:n.stage)||"created").toLowerCase(),o=df(n).find(c=>Wi(c,r,n));return(o==null?void 0:o.id)||r}function Wi(n,i,r){var c,f;const u=String(i||"").toLowerCase();return n.id===u||((c=n.aliases)==null?void 0:c.includes(u))?(f=n.roles)!=null&&f.length?n.roles.includes(String((r==null?void 0:r.role)||"").toLowerCase()):!0:!1}function Fu(n,i){const r=n!=null&&n.config&&Object.keys(n.config).length?n.config:(n==null?void 0:n.launch)||{};if(r[i]!==void 0)return r[i];for(const u of r.sections||[]){const o=(u.items||[]).find(c=>c.key===i);if(o)return o.value}}function Cy(n){return(n||[]).map(i=>i.name).sort()}function MA(n,i){return i&&n.includes(i)?i:n[0]||""}function DA({jobId:n,metricsDir:i,refreshNonce:r}){const[u,o]=ie.useState(""),[c,f]=ie.useState(.6),[h,g]=ie.useState([]),[p,y]=ie.useState([]),[x,b]=ie.useState(!1),[S,w]=ie.useState(0),[j,q]=ie.useState(null),[N,K]=ie.useState(n);n!==N&&(K(n),o(""),g([]),y([]),b(!1));const Y=Cy(h),se=MA(Y,u);ie.useEffect(()=>{if(!n)return;const Q=window.setInterval(()=>w(W=>W+1),2500);return()=>window.clearInterval(Q)},[n]),ie.useEffect(()=>{let Q=!1;if(n)return Pe(`/api/jobs/${n}/metrics`).then(W=>{if(Q)return;const de=W.metrics||[];g(de),o(re=>{var I;return re||((I=de[0])==null?void 0:I.name)||""})}).catch(()=>{Q||g([])}),()=>{Q=!0}},[n,r,S]),ie.useEffect(()=>{let Q=!1;if(!n||!se){y([]),b(!1);return}return b(!0),Pe(`/api/jobs/${n}/metric?name=${encodeURIComponent(se)}`).then(W=>{Q||y((W.points||[]).filter(de=>Number.isFinite(Number(de.value))).map(de=>({...de,step:Number(de.step||0),value:Number(de.value)})))}).catch(()=>{Q||y([])}).finally(()=>{Q||b(!1)}),()=>{Q=!0}},[n,se,r,S]);const ae=se,U=p,ne=OA(U,c),ue=c>0,ye=ue?ne:U,R=RA(ye);return m.jsxs("div",{className:"chart",children:[m.jsxs("div",{className:"chartHeader",children:[m.jsxs("span",{children:[m.jsx(py,{size:14})," TensorBoard scalars"]}),m.jsxs("div",{className:"chartControls",children:[m.jsx("select",{value:ae,onChange:Q=>o(Q.target.value),children:Y.length===0?m.jsx("option",{value:"",children:"no metrics"}):Y.map(Q=>m.jsx("option",{children:Q},Q))}),m.jsxs("label",{children:["smooth ",c.toFixed(2),m.jsx("input",{type:"range",min:"0",max:"0.99",step:"0.01",value:c,onChange:Q=>f(Number(Q.target.value))})]})]})]}),U.length===0?m.jsx("div",{className:"plotEmpty",children:x?"Loading selected metric...":"No TensorBoard scalar points loaded yet."}):m.jsxs("div",{className:"metricPlotWrap",children:[m.jsxs("svg",{className:"metricPlot",viewBox:"0 0 720 180",role:"img",children:[m.jsx("g",{className:"plotGrid",children:[0,1,2,3].map(Q=>m.jsx("line",{x1:"0",x2:"720",y1:30+Q*42,y2:30+Q*42},Q))}),m.jsx("polyline",{className:ue?"smoothLine":"rawLine",points:R.line}),!ue&&ye.map((Q,W)=>{var de,re,I,M;return m.jsxs("g",{children:[m.jsx("circle",{className:"metricDataPoint",cx:((de=R.coords[W])==null?void 0:de.x)||0,cy:((re=R.coords[W])==null?void 0:re.y)||0,r:ky(ye.length)}),m.jsx("circle",{className:"metricHoverTarget",cx:((I=R.coords[W])==null?void 0:I.x)||0,cy:((M=R.coords[W])==null?void 0:M.y)||0,r:"5",onMouseEnter:()=>q({point:Q,coord:R.coords[W]}),onMouseLeave:()=>q(null)})]},`${Q.step}-${W}`)})]}),!ue&&j&&m.jsx(_y,{name:ae,point:j.point,coord:j.coord,width:720,height:180})]}),m.jsxs("div",{className:"plotFooter",children:[m.jsxs("span",{children:[ae||"metric"," · ",p.length," points"]}),m.jsxs("span",{children:[i||"no metrics dir"," · ",R.minLabel," to ",R.maxLabel]})]})]})}function OA(n,i){if(!n.length)return[];const r=Math.min(Math.max(Number(i)||0,0),.999);let u=n[0].value;return n.map(o=>(u=u*r+o.value*(1-r),{...o,value:u}))}function RA(n){if(!n.length)return{line:"",coords:[],minLabel:"n/a",maxLabel:"n/a"};const{min:i,max:r}=Gc(n,y=>y.value),u=r===i,o=Math.max(r-i,1e-9),c=n[0].step,f=n[n.length-1].step,h=Math.max(f-c,1),g=y=>({x:(y.step-c)/h*700+10,y:u?95:168-(y.value-i)/o*146}),p=n.map(g);return{line:p.map(y=>`${y.x.toFixed(1)},${y.y.toFixed(1)}`).join(" "),coords:p,minLabel:ta(i),maxLabel:ta(r)}}function Gc(n,i){let r=1/0,u=-1/0;for(const o of n){const c=Number(i(o));cu&&(u=c)}return{min:r,max:u}}function ta(n){return Number.isFinite(n)?Math.abs(n)>=1e3||Math.abs(n)<.001?n.toExponential(2):n.toFixed(4).replace(/0+$/,"").replace(/\.$/,""):"n/a"}function LA({rows:n,job:i}){const r=BA(n||[],i),u=HA(r,7).reverse(),o=r.length?r.reduce((h,g)=>h+Number(g.total_s||0),0)/r.length:0,c=Math.max(1,...u.map(h=>Number(h.total_s||0))),f=Array.from(new Set(r.flatMap(h=>(h.segments||[]).map(g=>g.name)))).slice(0,8);return m.jsxs("div",{className:"timePerf",children:[m.jsxs("div",{className:"timePerfHeader",children:[m.jsx("div",{children:m.jsxs("div",{className:"codeTitle inline",children:[m.jsx(Bk,{size:14})," Runtime timeperf"]})}),m.jsxs("div",{className:"legend",children:[f.map(h=>m.jsxs("span",{children:[m.jsx("i",{className:ag(h)})," ",h]},h)),m.jsxs("b",{children:["avg ",o?`${o.toFixed(1)}s`:"n/a"]})]})]}),u.length===0?m.jsx("div",{className:"sampleEmpty",children:"No step timing captured yet."}):m.jsx("div",{className:"timeRows",children:u.map(h=>{var x;const g=Number(h.total_s||0),p=Math.max(10,g/c*100),y=(x=h.segments)!=null&&x.length?h.segments:[];return m.jsxs("div",{className:"timeRow",children:[m.jsxs("label",{children:["step ",h.step]}),m.jsx("div",{className:"timeTrack",children:m.jsx("div",{className:"timeStack",style:{width:`${p}%`},children:y.map(b=>{const S=Number(b.seconds||0),w=S/Math.max(g,1)*100;return m.jsx("span",{className:ag(b.name),style:{width:`${w}%`},title:`${b.name}: ${S.toFixed(1)}s`,children:w>11?`${S.toFixed(1)}s`:""},b.name)})})}),m.jsxs("strong",{children:[g.toFixed(1),"s"]})]},`${h.step}-${h.time}`)})})]})}function BA(n,i){const r=String(Fu(i,"algo")||"").toLowerCase(),u=UA(r,i==null?void 0:i.kind);return n.map(o=>{const c=[];let f=0;for(const h of o.segments||[]){const g=Number(h.seconds||0);u.has(h.name)?c.push({...h,seconds:g}):f+=g}if(f>0){const h=c.find(g=>g.name==="other");h?h.seconds+=f:c.push({name:"other",seconds:f})}return{...o,segments:c}})}function UA(n,i){return i==="serve"?new Set(["load","prefill","decode","other"]):n==="sft"?new Set(["train","save","other"]):n==="dpo"?new Set(["ref log probs","train","save","other"]):n==="ppo"?new Set(["rollout","make_sample","reward","old policy log probs","actor log probs","ref log probs","value","advantages","sync weight","train","save","other"]):new Set(["rollout","make_sample","reward","old policy log probs","actor log probs","ref log probs","advantages","sync weight","train","save","other"])}function HA(n,i){if(n.length<=i)return n.slice();const r=n.length-1,u=new Set;for(let o=0;oo-c).slice(-i).map(o=>n[o])}function ag(n){return`seg-${String(n||"other").replace(/[^a-zA-Z0-9]+/g,"-")}`}function qA(n){for(const i of[n.completion,n.rendered_completion,n.final_answer])if(typeof i=="string"&&i.trim())return i;return Array.isArray(n.tool_calls)&&n.tool_calls.length?JSON.stringify(n.tool_calls,null,2):"No assistant output was captured."}function zy(n){var r;if(Array.isArray(n.prompt_messages))return n.prompt_messages;if(!Array.isArray(n.messages))return[];const i=[...n.messages];return((r=i.at(-1))==null?void 0:r.role)==="assistant"&&i.pop(),i}function GA(n){if(!n||typeof n!="object")return null;const i=String(n.type||"");if(i==="input_audio"){const o=n.input_audio;if(!(o!=null&&o.data)||String(o.data).includes(""))return null;const c=String(o.format||"wav").toLowerCase(),f=c==="mp3"?"audio/mpeg":`audio/${c}`;return{type:"audio",source:String(o.data).startsWith("data:")?o.data:`data:${f};base64,${o.data}`}}const r=i.replace(/_url$/,"");if(!["image","audio","video"].includes(r))return null;let u=n[i]??n[r]??n.url;return u&&typeof u=="object"&&(u=u.url),typeof u=="string"&&u?{type:r,source:u}:null}function YA(n){const i=[],r=o=>{o&&!i.some(c=>c.type===o.type&&c.source===o.source)&&i.push(o)};for(const o of zy(n))if(Array.isArray(o==null?void 0:o.content))for(const c of o.content)r(GA(c));const u=(o,c="")=>{if(Array.isArray(o)){o.forEach(p=>u(p,c));return}if(o&&typeof o=="object"){Object.entries(o).forEach(([p,y])=>u(y,p));return}if(typeof o!="string")return;const f=c.toLowerCase(),h=["video","audio","image"].find(p=>f.includes(p)),g=["video","videos","audio","audios","image","images"].includes(f);h&&(g||["path","url","file"].some(p=>f.includes(p)))&&r({type:h,source:o})};return u(n.source_record),i}function VA(n,i){return/^(data:|blob:|https?:)/.test(i)?i:`${of}api/jobs/${encodeURIComponent(n)}/media?path=${encodeURIComponent(i)}`}function QA({jobId:n,media:i}){if(!n||!i.length)return null;const r=i.some(c=>c.type==="video"),u=i.some(c=>c.type==="audio"),o=r&&u?"Video + audio":r?"Video":u?"Audio":"Image";return m.jsxs("section",{className:"sampleMediaSection",children:[m.jsxs("div",{className:"sampleSectionLabel",children:[r?m.jsx(Ek,{size:14}):u?m.jsx(Uk,{size:14}):m.jsx(Tk,{size:14}),o]}),m.jsx("div",{className:dt("sampleMediaGrid",i.length===1&&"single"),children:i.map((c,f)=>{const h=VA(n,c.source);return c.type==="video"?m.jsx("video",{src:h,controls:!0,preload:"metadata"},`${c.type}-${c.source}`):c.type==="audio"?m.jsx("audio",{src:h,controls:!0,preload:"metadata"},`${c.type}-${c.source}`):m.jsx("img",{src:h,alt:`Sample media ${f+1}`,loading:"lazy"},`${c.type}-${c.source}`)})})]})}function rg({icon:n,label:i,value:r,emptyText:u}){return m.jsxs("section",{className:"sampleDetailSection",children:[m.jsxs("div",{className:"sampleSectionLabel",children:[n,i]}),m.jsx("pre",{children:r==null?u:JSON.stringify(r,null,2)})]})}function Ny({samples:n,jobId:i,hideTitle:r=!1}){const u=ie.useMemo(()=>[...n||[]].sort((j,q)=>Number(j.step||0)-Number(q.step||0)||Number(j.prompt_idx||0)-Number(q.prompt_idx||0)||Number(j.sample_idx||0)-Number(q.sample_idx||0)),[n]),o=ie.useMemo(()=>Array.from(new Set(u.map(j=>Number(j.step||0)))).sort((j,q)=>q-j),[u]),[c,f]=ie.useState(""),[h,g]=ie.useState("");ie.useEffect(()=>{if(!o.length){f(""),g("");return}(c===""||!o.includes(Number(c)))&&(f(String(o[0])),g(""))},[c,o]);const y=(c===""?[]:u.filter(j=>Number(j.step||0)===Number(c))).map((j,q)=>({key:XA(j,q),label:`prompt ${j.prompt_idx??"?"} · sample ${j.sample_idx??"?"}`,sample:j})),x=y.find(j=>j.key===h)||y[y.length-1]||null,b=(x==null?void 0:x.sample)||null,S=ie.useMemo(()=>b?YA(b):[],[b]),w=b?zy(b):[];return m.jsxs("div",{className:"sampleCard",children:[!r&&m.jsxs("div",{className:"codeTitle sampleTitle",children:[m.jsxs("span",{children:[m.jsx(Wp,{size:14})," Rollout sample"]}),!!u.length&&m.jsxs("div",{className:"sampleControls",children:[m.jsx("select",{value:c,onChange:j=>{f(j.target.value),g("")},children:o.map(j=>m.jsxs("option",{value:j,children:["step ",j]},j))}),m.jsx("select",{value:(x==null?void 0:x.key)||"",onChange:j=>g(j.target.value),children:y.map(j=>m.jsx("option",{value:j.key,children:j.label},j.key))})]})]}),b?m.jsxs("div",{className:"sampleContent",children:[m.jsx(QA,{jobId:i,media:S}),m.jsxs("div",{className:"sampleGrid",children:[m.jsxs("div",{children:[m.jsx("span",{children:"Prompt"}),m.jsx("p",{children:b.prompt||"No prompt text was captured."})]}),m.jsxs("div",{children:[m.jsx("span",{children:"Output"}),m.jsx("p",{children:qA(b)})]})]}),m.jsxs("div",{className:"sampleDetailGrid",children:[m.jsx(rg,{icon:m.jsx(Wp,{size:14}),label:"Full prompt",value:w.length?w:null,emptyText:"No structured prompt messages were captured."}),m.jsx(rg,{icon:m.jsx(wk,{size:14}),label:"Data record",value:b.source_record,emptyText:"No source dataset record was captured."})]})]}):m.jsx("div",{className:"sampleEmpty",children:"No rollout sample captured yet."})]})}function XA(n,i){return`${n.step??"x"}-${n.prompt_idx??"x"}-${n.sample_idx??"x"}-${i}`}function ZA({config:n,launch:i}){const r=n&&Object.keys(n).length?n:i||{},u=FA(r);return m.jsxs("div",{className:"codeCard",children:[m.jsxs("div",{className:"codeTitle",children:[m.jsx(vy,{size:14})," Config"]}),u.length>0?m.jsx("div",{className:"configSections",children:u.map(o=>m.jsxs("div",{className:"configSection",children:[m.jsx("h3",{children:o.title}),m.jsx("div",{className:"configGrid",children:o.items.map(({key:c,value:f})=>m.jsxs("div",{className:"configItem",children:[m.jsx("span",{children:c.replace(/_/g," ")}),m.jsx("strong",{children:KA(f)})]},c))})]},o.title))}):m.jsx("pre",{children:"No config captured yet."})]})}function FA(n){if(Array.isArray(n==null?void 0:n.sections))return n.sections.map(r=>({title:r.title||"Config",items:(r.items||[]).filter(({value:u})=>u!=null&&u!=="")})).filter(r=>r.items.length>0);const i=Object.entries(n||{}).filter(([,r])=>r!=null&&r!=="").map(([r,u])=>({key:r,value:u}));return i.length?[{title:"Launch",items:i}]:[]}function KA(n){return Array.isArray(n)?n.join(" "):typeof n=="object"?JSON.stringify(n):String(n)}function JA({logs:n}){const i=ie.useRef(null);return ie.useEffect(()=>{const r=i.current;r&&(r.scrollTop=r.scrollHeight)},[n.length]),m.jsxs("div",{className:"codeCard",ref:i,children:[m.jsxs("div",{className:"codeTitle",children:[m.jsx(Rk,{size:14})," Logs"]}),m.jsx("pre",{children:n.slice(-80).join(` +`)||"No logs yet."})]})}function $A({mode:n,setMode:i,trainConfig:r,setTrainConfig:u,serveConfig:o,setServeConfig:c,onStartTrain:f,onStartServe:h,env:g,presets:p}){var R,Q,W,de,re,I,M,J;const y=n==="train"?r:o,[x,b]=ie.useState(null),[S,w]=ie.useState(""),[j,q]=ie.useState(null),N=Number(y.world_size||0),K=Number(y.tp_size||0),Y=((R=g==null?void 0:g.gpus)==null?void 0:R.length)||0,se=n==="train",ae=se&&["gspo","grpo","ppo"].includes(String(y.algo||"").toLowerCase());ie.useEffect(()=>{var T;if(!((T=j==null?void 0:j.job)!=null&&T.id)||!["created","running"].includes(j.job.status))return;let P=!1;const xe=async()=>{try{const G=await Pe(`/api/jobs/${j.job.id}`);if(P||!G.job)return;const k={...j,job:G.job};q(k),["created","running"].includes(G.job.status)||b({...k,ok:G.job.status==="succeeded",output:(G.job.logs||[]).join(` +`)})}catch(G){P||b({ok:!1,check:j.check,output:G.message})}};xe();const A=window.setInterval(xe,1e3);return()=>{P=!0,window.clearInterval(A)}},[(Q=j==null?void 0:j.job)==null?void 0:Q.id,(W=j==null?void 0:j.job)==null?void 0:W.status]);const U=[{id:"gpu_count",name:"GPU count",status:Y===0?"warn":N<=Y?"ok":"warn",detail:Y?`World size ${N} uses ${Y} visible GPU${Y===1?"":"s"}.`:"No visible GPU inventory is available.",tunable:ae&&Y>0},{id:"tensor_parallel",name:"Tensor parallelism",status:N>0&&K>0&&N%K===0?"ok":"fail",detail:N>0&&K>0&&N%K===0?`World size ${N} is divisible by TP size ${K}.`:"World size must be divisible by TP size.",tunable:se},n==="train"?{id:"batch_relation",name:"Batch relation",status:Number(y.batch_size)>0&&Number(y.mini_bs)>0&&Number(y.batch_size)%Number(y.mini_bs)===0?"ok":"fail",detail:`Batch ${y.batch_size} × samples ${y.n_samples||1}; mini batch ${y.mini_bs}.`,tunable:se}:{id:"batch_relation",name:"Serving capacity",status:Number(y.max_running_prompts)>0?"ok":"warn",detail:`${y.max_running_prompts||0} concurrent prompts configured.`,tunable:!1},...n==="train"?[{id:"max_new_tokens",name:"Max new tokens",status:Number(y.max_new_tokens)>1024?"warn":"ok",detail:Number(y.max_new_tokens)>1024?`${y.max_new_tokens} may increase rollout memory.`:`${y.max_new_tokens||0} is within the preflight target.`,tunable:ae}]:[]],ne=IA(n,y),ue=U.some(P=>P.status==="fail"),ye=async P=>{const xe=P.status!=="ok"&&P.tunable?"tune":"view";w(P.id);try{const A=await Pe("/api/launcher/preflight",{method:"POST",body:JSON.stringify({mode:n,config:y,check_id:P.id,action:xe})});xe==="tune"&&A.job?(b(null),q({...A,check:P,job:A.job})):b(A)}catch(A){b({ok:!1,check:{name:P.name,status:"fail",detail:A.message},patch:{}})}finally{w("")}};return m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"launcherPrdLayout",children:[m.jsxs("section",{className:"panel launcher launcherMainCard",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Task Launcher"}),m.jsx("p",{children:"Configure, validate, and review the generated command before launch."})]}),m.jsxs("div",{className:"tabs",children:[m.jsx("button",{className:dt(n==="train"&&"active"),onClick:()=>i("train"),children:"Train"}),m.jsx("button",{className:dt(n==="serve"&&"active"),onClick:()=>i("serve"),children:"Serve"})]})]}),n==="train"&&p.length>0&&m.jsx("div",{className:"launcherPresetRow",children:p.map(P=>m.jsx("button",{className:"presetPill",title:P.source,onClick:()=>u(xe=>({...xe,...P.preset||{}})),children:P.label},P.id))}),m.jsx("div",{className:"launcherFormScroll",children:n==="train"?m.jsx(PA,{config:r,setConfig:u,onStart:f}):m.jsx(ew,{config:o,setConfig:c,onStart:h})})]}),m.jsxs("aside",{className:"launcherSideRail",children:[m.jsxs("section",{className:"panel launcherPreflight",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Preflight"}),m.jsx("p",{children:"Resolve launch risks before allocating workers."})]}),m.jsx(Mt,{status:ue?"failed":"ok"})]}),m.jsx("div",{className:"runtimeCheckList",children:U.map(P=>{var pe,he,je,we,Ue,At;const xe=S===P.id&&P.status!=="ok"&&P.tunable,A=(j==null?void 0:j.check_id)===P.id&&["created","running"].includes((pe=j.job)==null?void 0:pe.status),T=(j==null?void 0:j.smoke_stage)==="infer"?"Smoke infer":"Smoke train",G=A&&((he=j.job)!=null&&he.created_at)?Math.max(0,Math.floor((Date.now()-Date.parse(j.job.created_at))/1e3)):0,k=A?[...((je=j.job)==null?void 0:je.logs)||[]].reverse().find(nt=>nt&&!String(nt).startsWith("$ ")):"",le=xe?"Starting smoke tuning job...":A?`${T}: ${((we=j.job)==null?void 0:we.stage)||"starting"} · step ${((Ue=j.job)==null?void 0:Ue.step)??0} · ${G}s`:P.detail;return m.jsxs("div",{className:"runtimeCheckRow launcherCheck",children:[m.jsx(Mt,{status:A?"running":P.status}),m.jsxs("div",{children:[m.jsx("strong",{children:P.name}),m.jsx("p",{children:le}),(xe||A)&&m.jsx("div",{className:"preflightProgress",role:"progressbar","aria-label":`Tuning ${P.name}`,children:m.jsx("span",{})}),A&&m.jsxs("div",{className:"preflightTuneDetails",children:[m.jsx("div",{children:Object.entries(j.tuning_params||{}).map(([nt,Dt])=>m.jsxs("span",{children:[m.jsx("b",{children:nt.replaceAll("_"," ")}),String(Dt)]},nt))}),k&&m.jsx("code",{children:k})]})]}),m.jsx("button",{className:"secondaryButton tableAction",disabled:!!S||!!(j&&["created","running"].includes((At=j.job)==null?void 0:At.status)),onClick:()=>ye(P),children:xe?"Starting...":A?`${T}...`:P.status!=="ok"&&P.tunable?"Tune":"View"})]},P.id)})})]}),m.jsxs("section",{className:"panel commandPreviewPanel",children:[m.jsxs("div",{className:"panelHeader",children:[m.jsxs("div",{children:[m.jsx("h2",{children:"Command Preview"}),m.jsx("p",{children:"Review the final CLI mapping."})]}),m.jsx("button",{className:"secondaryButton",onClick:()=>navigator.clipboard.writeText(ne),children:"Copy"})]}),m.jsx("pre",{className:"commandPreview",children:ne})]})]})]}),x&&m.jsxs(Zu,{title:"Preflight Result",onClose:()=>b(null),children:[m.jsxs("div",{className:"runtimeResultSummary",children:[m.jsx(Mt,{status:((de=x.job)==null?void 0:de.status)||((re=x.check)==null?void 0:re.status)||(x.ok?"ok":"failed")}),m.jsx("span",{children:((I=x.check)==null?void 0:I.name)||"Launcher check"})]}),Object.keys(x.tuning_params||{}).length>0&&m.jsx("div",{className:"preflightResultParams",children:Object.entries(x.tuning_params).map(([P,xe])=>m.jsxs("span",{children:[m.jsx("b",{children:P.replaceAll("_"," ")}),String(xe)]},P))}),m.jsxs("pre",{className:"runtimeCommandResult",children:[(M=x.command)!=null&&M.length?`$ ${x.command.map(hf).join(" ")} -`:"",x.output||((J=x.check)==null?void 0:J.detail)||"No details returned."]}),m.jsx("button",{className:"primaryButton fullButton",onClick:()=>v(null),children:"Done"})]})]})}function IA(n,i){const u=(n==="train"?[["algo",i.algo],["ckpt",i.ckpt],["dataset-path",i.dataset_path],["dataset-loader-fn",i.dataset_loader_fn],["reward-fn-path",i.reward_fn_path],["world-size",i.world_size],["tp-size",i.tp_size],["batch-size",i.batch_size],["mini-bs",i.mini_bs],["n-samples",i.n_samples],["max-new-tokens",i.max_new_tokens]]:[["model-path",i.model_path],["host",i.host],["port",i.port],["world-size",i.world_size],["tp-size",i.tp_size],["max-running-prompts",i.max_running_prompts],["default-max-tokens",i.default_max_tokens]]).filter(([,o])=>o!==""&&o!==void 0&&o!==null).map(([o,c])=>` --${o} ${hf(c)}`);return[`areno ${n} \\`,...u.map((o,c)=>`${o}${ci({...n,[y]:x}),f=[ni("algo","Algorithm",["sft","dpo","gspo","grpo","ppo"],!0),oe("ckpt","Checkpoint"),oe("dataset_path","Dataset path"),oe("dataset_loader_fn","Dataset loader"),oe("reward_fn_path","Reward function"),ni("model_hub","Model hub",["modelscope","hf"],!0),oe("world_size","World size",!0),oe("tp_size","TP size",!0),oe("batch_size","Batch size",!0),oe("mini_bs","Mini batch size",!0),oe("n_samples","N samples",!0),oe("max_new_tokens","Max new tokens",!0)],h=new Set(f.map(y=>y.key)),g=o.map(y=>({...y,fields:y.fields.filter(x=>!h.has(x.key))})).filter(y=>y.fields.length),p=y=>m.jsx(Hu,{label:y.label,value:n[y.key],onChange:x=>c(y.key,x),compact:y.compact,type:y.type,options:y.options},y.key);return m.jsxs("div",{className:"launcherSections",children:[m.jsx("div",{className:"formGrid launcherPrimaryFields",children:f.map(p)}),m.jsxs("details",{className:"launcherAdvanced",children:[m.jsx("summary",{children:"Advanced settings"}),m.jsx("div",{className:"launcherAdvancedBody",children:g.map(y=>m.jsxs("div",{className:"launcherSection",children:[m.jsxs("div",{className:"launcherSectionHeader",children:[m.jsx("strong",{children:y.title}),y.note&&m.jsx("span",{children:y.note})]}),m.jsx("div",{className:"formGrid",children:y.fields.map(p)})]},y.title))})]}),m.jsxs("button",{className:"primaryButton launchButton wide",onClick:r,children:[m.jsx(Xu,{size:16})," Start train"]})]})}function WA(n){const i=["gspo","grpo","ppo"].includes(n),r=i,u=n==="dpo",o=n==="ppo",c=n==="gspo",f=n==="grpo",h=[{title:"Basic",note:"model, data, and trainer loop",fields:[ni("algo","Algorithm",["sft","dpo","gspo","grpo","ppo"],!0),oe("ckpt","Checkpoint"),ni("model_hub","Model hub",["modelscope","hf"],!0),oe("dataset_path","Dataset path"),oe("dataset_loader_fn","Dataset loader"),oe("epochs","Epochs",!0),oe("max_steps","Max steps",!0)]},{title:"Runtime",note:"parallelism, memory, and kernels",fields:[oe("world_size","World",!0),oe("tp_size","TP",!0),ni("attn_backend","Attention",["flash","native"],!0),jn("activation_checkpointing","Activation ckpt"),jn("drop_rollout_state","Drop rollout state"),jn("eager_decode","Eager decode"),jn("disable_thinking","Disable thinking")]},{title:"Batching",note:"controls train and rollout memory",fields:[oe("batch_size","Batch",!0),...i?[oe("n_samples","Samples",!0),oe("max_running_prompts","Running prompts",!0)]:[],oe("mini_bs","Mini BS",!0),oe("score_micro_bs","Score micro BS",!0),oe("gradient_accumulation_steps","Grad accum",!0)]},{title:i?"Rollout":"Sequence",note:i?"generation and sampling":"token limits for supervised data",fields:[oe("max_prompt_tokens","Prompt tokens",!0),oe("max_new_tokens","New tokens",!0),...r?[oe("max_context_len","Context",!0),oe("agent_fn","Agent fn"),jn("train_tool_results","Train tool results")]:[],...i?[oe("temperature","Temp",!0),oe("top_k","Top K",!0),oe("top_p","Top P",!0),jn("greedy","Greedy")]:[]]},{title:"Optimizer",note:"policy optimizer settings",fields:[oe("lr","LR",!0),oe("min_lr","Min LR",!0),oe("lr_decay_steps","Decay steps",!0),oe("lr_decay_style","Decay style",!0),oe("adam_beta1","Adam beta1",!0),oe("adam_beta2","Adam beta2",!0),oe("weight_decay","Weight decay",!0),oe("grad_clip_norm","Grad clip",!0),jn("adam_8bit","8-bit Adam"),jn("unfreeze_multimodal_tower","Train media tower"),oe("multimodal_tower_lr","Tower LR",!0),oe("multimodal_tower_min_lr","Tower min LR",!0),oe("multimodal_tower_lr_decay_steps","Tower decay",!0),ni("multimodal_tower_lr_decay_style","Tower schedule",["","constant","linear","cosine"]),jn("unfreeze_multimodal_projector","Train media projector"),oe("multimodal_projector_lr","Projector LR",!0),oe("multimodal_projector_min_lr","Projector min LR",!0),oe("multimodal_projector_lr_decay_steps","Projector decay",!0),ni("multimodal_projector_lr_decay_style","Projector schedule",["","constant","linear","cosine"])]}],g=[];return(u||o)&&g.push(oe("ref_ckpt","Reference ckpt")),i&&g.push(oe("reward_fn_path","Reward fn")),o&&g.push(oe("reward_ckpt","Reward ckpt"),oe("critic_ckpt","Critic ckpt"),oe("critic_lr","Critic LR",!0),oe("critic_warmup_steps","Critic warmup",!0)),c&&g.push(oe("gspo_clip_eps","GSPO clip",!0)),f&&g.push(oe("grpo_clip_eps","GRPO clip",!0)),u&&g.push(oe("dpo_beta","DPO beta",!0)),o&&g.push(jn("use_kl_loss","Use KL loss"),oe("kl_loss_coef","KL coef",!0),oe("kl_loss_type","KL type",!0),oe("clip_eps","Clip eps",!0),oe("clip_ratio_c","Clip ratio C",!0),oe("value_clip_eps","Value clip",!0),oe("value_loss_coef","Value coef",!0),oe("gamma","Gamma",!0),oe("lam","Lambda",!0)),g.length>0&&h.push({title:"Algorithm",note:`${n.toUpperCase()}-specific roles and loss`,fields:g}),h.push({title:"Probe",note:"optional smoke and auto tune helpers",fields:[jn("tune_params","Tune params"),oe("mem_frac","Memory frac",!0),oe("tune_max_samples","Tune samples",!0)]},{title:"Output",note:"checkpointing, metrics, and escape hatch",fields:[oe("save_path","Save path"),oe("save_interval","Save interval",!0),oe("metrics_dir","Metrics dir"),oe("extra_args","Extra args")]}),h}function oe(n,i,r=!1){return{key:n,label:i,compact:r}}function ni(n,i,r,u=!1){return{key:n,label:i,compact:u,type:"select",options:r}}function jn(n,i){return{key:n,label:i,compact:!0,type:"checkbox"}}function ew({config:n,setConfig:i,onStart:r}){return m.jsxs("div",{className:"formGrid",children:[[["model_path","Model path"],["model_hub","Model hub"],["host","Host"],["port","Port"],["world_size","World"],["tp_size","TP"],["max_running_prompts","Running prompts"],["default_max_tokens","Default max tokens"],["decode_progress_interval_s","Progress interval"],["attn_backend","Attention backend"],["eager_decode","Eager decode"],["disable_thinking","Disable thinking"],["extra_args","Extra args"]].map(([u,o])=>m.jsx(Hu,{label:o,value:n[u],onChange:c=>i({...n,[u]:c}),compact:u!=="model_path"},u)),m.jsxs("button",{className:"primaryButton launchButton wide",onClick:r,children:[m.jsx(Xu,{size:16})," Start serve"]})]})}function Hu({label:n,value:i,onChange:r,compact:u,type:o="text",options:c=[]}){return o==="checkbox"?m.jsxs("label",{className:dt("field","compact","checkField"),children:[m.jsx("input",{type:"checkbox",checked:!!i,onChange:f=>r(f.target.checked)}),m.jsx("span",{children:n})]}):m.jsxs("label",{className:dt("field",u&&"compact"),children:[m.jsx("span",{children:n}),o==="select"?m.jsx("select",{value:i??"",onChange:f=>r(f.target.value),children:c.map(f=>m.jsx("option",{value:f,children:f},f))}):m.jsx("input",{value:i??"",onChange:f=>r(f.target.value)})]})}function ai({title:n,text:i}){return m.jsxs("div",{className:"empty",children:[m.jsx(Ak,{size:18}),m.jsx("strong",{children:n}),m.jsx("span",{children:i})]})}const ug=typeof document<"u"?document.getElementById("root"):null;ug&&Jx.createRoot(ug).render(m.jsx(Kk,{})); +`:"",x.output||((J=x.check)==null?void 0:J.detail)||"No details returned."]}),m.jsx("button",{className:"primaryButton fullButton",onClick:()=>b(null),children:"Done"})]})]})}function IA(n,i){const u=(n==="train"?[["algo",i.algo],["ckpt",i.ckpt],["dataset-path",i.dataset_path],["dataset-loader-fn",i.dataset_loader_fn],["reward-fn-path",i.reward_fn_path],["world-size",i.world_size],["tp-size",i.tp_size],["batch-size",i.batch_size],["mini-bs",i.mini_bs],["n-samples",i.n_samples],["max-new-tokens",i.max_new_tokens]]:[["model-path",i.model_path],["host",i.host],["port",i.port],["world-size",i.world_size],["tp-size",i.tp_size],["max-running-prompts",i.max_running_prompts],["default-max-tokens",i.default_max_tokens]]).filter(([,o])=>o!==""&&o!==void 0&&o!==null).map(([o,c])=>` --${o} ${hf(c)}`);return[`areno ${n} \\`,...u.map((o,c)=>`${o}${ci({...n,[y]:x}),f=[ni("algo","Algorithm",["sft","dpo","gspo","grpo","ppo"],!0),oe("ckpt","Checkpoint"),oe("dataset_path","Dataset path"),oe("dataset_loader_fn","Dataset loader"),oe("reward_fn_path","Reward function"),ni("model_hub","Model hub",["modelscope","hf"],!0),oe("world_size","World size",!0),oe("tp_size","TP size",!0),oe("batch_size","Batch size",!0),oe("mini_bs","Mini batch size",!0),oe("n_samples","N samples",!0),oe("max_new_tokens","Max new tokens",!0)],h=new Set(f.map(y=>y.key)),g=o.map(y=>({...y,fields:y.fields.filter(x=>!h.has(x.key))})).filter(y=>y.fields.length),p=y=>m.jsx(Hu,{label:y.label,value:n[y.key],onChange:x=>c(y.key,x),compact:y.compact,type:y.type,options:y.options},y.key);return m.jsxs("div",{className:"launcherSections",children:[m.jsx("div",{className:"formGrid launcherPrimaryFields",children:f.map(p)}),m.jsxs("details",{className:"launcherAdvanced",children:[m.jsx("summary",{children:"Advanced settings"}),m.jsx("div",{className:"launcherAdvancedBody",children:g.map(y=>m.jsxs("div",{className:"launcherSection",children:[m.jsxs("div",{className:"launcherSectionHeader",children:[m.jsx("strong",{children:y.title}),y.note&&m.jsx("span",{children:y.note})]}),m.jsx("div",{className:"formGrid",children:y.fields.map(p)})]},y.title))})]}),m.jsxs("button",{className:"primaryButton launchButton wide",onClick:r,children:[m.jsx(Xu,{size:16})," Start train"]})]})}function WA(n){const i=["gspo","grpo","ppo"].includes(n),r=i,u=n==="dpo",o=n==="ppo",c=n==="gspo",f=n==="grpo",h=[{title:"Basic",note:"model, data, and trainer loop",fields:[ni("algo","Algorithm",["sft","dpo","gspo","grpo","ppo"],!0),oe("ckpt","Checkpoint"),ni("model_hub","Model hub",["modelscope","hf"],!0),oe("dataset_path","Dataset path"),oe("dataset_loader_fn","Dataset loader"),oe("epochs","Epochs",!0),oe("max_steps","Max steps",!0)]},{title:"Runtime",note:"parallelism, memory, and kernels",fields:[oe("world_size","World",!0),oe("tp_size","TP",!0),ni("attn_backend","Attention",["flash","native"],!0),_n("activation_checkpointing","Activation ckpt"),_n("fp8_checkpoint_activations","FP8 ckpt activations"),_n("drop_rollout_state","Drop rollout state"),_n("eager_decode","Eager decode"),_n("disable_thinking","Disable thinking")]},{title:"Batching",note:"controls train and rollout memory",fields:[oe("batch_size","Batch",!0),...i?[oe("n_samples","Samples",!0),oe("max_running_prompts","Running prompts",!0)]:[],oe("mini_bs","Mini BS",!0),oe("score_micro_bs","Score micro BS",!0),oe("gradient_accumulation_steps","Grad accum",!0)]},{title:i?"Rollout":"Sequence",note:i?"generation and sampling":"token limits for supervised data",fields:[oe("max_prompt_tokens","Prompt tokens",!0),oe("max_new_tokens","New tokens",!0),...r?[oe("max_context_len","Context",!0),oe("agent_fn","Agent fn"),_n("train_tool_results","Train tool results")]:[],...i?[oe("temperature","Temp",!0),oe("top_k","Top K",!0),oe("top_p","Top P",!0),_n("greedy","Greedy")]:[]]},{title:"Optimizer",note:"policy optimizer settings",fields:[oe("lr","LR",!0),oe("min_lr","Min LR",!0),oe("lr_decay_steps","Decay steps",!0),oe("lr_decay_style","Decay style",!0),oe("adam_beta1","Adam beta1",!0),oe("adam_beta2","Adam beta2",!0),oe("weight_decay","Weight decay",!0),oe("grad_clip_norm","Grad clip",!0),_n("adam_8bit","8-bit Adam"),_n("unfreeze_multimodal_tower","Train media tower"),oe("multimodal_tower_lr","Tower LR",!0),oe("multimodal_tower_min_lr","Tower min LR",!0),oe("multimodal_tower_lr_decay_steps","Tower decay",!0),ni("multimodal_tower_lr_decay_style","Tower schedule",["","constant","linear","cosine"]),_n("unfreeze_multimodal_projector","Train media projector"),oe("multimodal_projector_lr","Projector LR",!0),oe("multimodal_projector_min_lr","Projector min LR",!0),oe("multimodal_projector_lr_decay_steps","Projector decay",!0),ni("multimodal_projector_lr_decay_style","Projector schedule",["","constant","linear","cosine"])]}],g=[];return(u||o)&&g.push(oe("ref_ckpt","Reference ckpt")),i&&g.push(oe("reward_fn_path","Reward fn")),o&&g.push(oe("reward_ckpt","Reward ckpt"),oe("critic_ckpt","Critic ckpt"),oe("critic_lr","Critic LR",!0),oe("critic_warmup_steps","Critic warmup",!0)),c&&g.push(oe("gspo_clip_eps","GSPO clip",!0)),f&&g.push(oe("grpo_clip_eps","GRPO clip",!0)),u&&g.push(oe("dpo_beta","DPO beta",!0)),o&&g.push(_n("use_kl_loss","Use KL loss"),oe("kl_loss_coef","KL coef",!0),oe("kl_loss_type","KL type",!0),oe("clip_eps","Clip eps",!0),oe("clip_ratio_c","Clip ratio C",!0),oe("value_clip_eps","Value clip",!0),oe("value_loss_coef","Value coef",!0),oe("gamma","Gamma",!0),oe("lam","Lambda",!0)),g.length>0&&h.push({title:"Algorithm",note:`${n.toUpperCase()}-specific roles and loss`,fields:g}),h.push({title:"Probe",note:"optional smoke and auto tune helpers",fields:[_n("tune_params","Tune params"),oe("mem_frac","Memory frac",!0),oe("tune_max_samples","Tune samples",!0)]},{title:"Output",note:"checkpointing, metrics, and escape hatch",fields:[oe("save_path","Save path"),oe("save_interval","Save interval",!0),oe("metrics_dir","Metrics dir"),oe("extra_args","Extra args")]}),h}function oe(n,i,r=!1){return{key:n,label:i,compact:r}}function ni(n,i,r,u=!1){return{key:n,label:i,compact:u,type:"select",options:r}}function _n(n,i){return{key:n,label:i,compact:!0,type:"checkbox"}}function ew({config:n,setConfig:i,onStart:r}){return m.jsxs("div",{className:"formGrid",children:[[["model_path","Model path"],["model_hub","Model hub"],["host","Host"],["port","Port"],["world_size","World"],["tp_size","TP"],["max_running_prompts","Running prompts"],["default_max_tokens","Default max tokens"],["decode_progress_interval_s","Progress interval"],["attn_backend","Attention backend"],["eager_decode","Eager decode"],["disable_thinking","Disable thinking"],["extra_args","Extra args"]].map(([u,o])=>m.jsx(Hu,{label:o,value:n[u],onChange:c=>i({...n,[u]:c}),compact:u!=="model_path"},u)),m.jsxs("button",{className:"primaryButton launchButton wide",onClick:r,children:[m.jsx(Xu,{size:16})," Start serve"]})]})}function Hu({label:n,value:i,onChange:r,compact:u,type:o="text",options:c=[]}){return o==="checkbox"?m.jsxs("label",{className:dt("field","compact","checkField"),children:[m.jsx("input",{type:"checkbox",checked:!!i,onChange:f=>r(f.target.checked)}),m.jsx("span",{children:n})]}):m.jsxs("label",{className:dt("field",u&&"compact"),children:[m.jsx("span",{children:n}),o==="select"?m.jsx("select",{value:i??"",onChange:f=>r(f.target.value),children:c.map(f=>m.jsx("option",{value:f,children:f},f))}):m.jsx("input",{value:i??"",onChange:f=>r(f.target.value)})]})}function ai({title:n,text:i}){return m.jsxs("div",{className:"empty",children:[m.jsx(Ak,{size:18}),m.jsx("strong",{children:n}),m.jsx("span",{children:i})]})}const ug=typeof document<"u"?document.getElementById("root"):null;ug&&Jx.createRoot(ug).render(m.jsx(Kk,{})); diff --git a/areno/dashboard/dist/index.html b/areno/dashboard/dist/index.html index 9bab6daf..aa033356 100644 --- a/areno/dashboard/dist/index.html +++ b/areno/dashboard/dist/index.html @@ -4,7 +4,7 @@ AReno Dashboard - + diff --git a/areno/dashboard/server.py b/areno/dashboard/server.py index 9fd9c183..74b180fb 100644 --- a/areno/dashboard/server.py +++ b/areno/dashboard/server.py @@ -713,7 +713,6 @@ def build_train_command(config: dict[str, Any]) -> list[str]: "--adam-4bit": config.get("adam_4bit"), "--unfreeze-mm-tower": config.get("unfreeze_multimodal_tower"), "--unfreeze-mm-projector": config.get("unfreeze_multimodal_projector"), - "--drop-rollout-state": config.get("drop_rollout_state"), "--eager-decode": config.get("eager_decode"), "--disable-thinking": config.get("disable_thinking"), "--train-tool-results": config.get("train_tool_results"), @@ -723,6 +722,14 @@ def build_train_command(config: dict[str, Any]) -> list[str]: command.append( "--activation-checkpointing" if bool_like(activation_checkpointing) else "--no-activation-checkpointing" ) + fp8_checkpoint_activations = config.get("fp8_checkpoint_activations") + if fp8_checkpoint_activations not in (None, ""): + command.append( + "--fp8-ckpt-activations" if bool_like(fp8_checkpoint_activations) else "--no-fp8-ckpt-activations" + ) + drop_rollout_state = config.get("drop_rollout_state") + if drop_rollout_state not in (None, ""): + command.append("--drop-rollout-state" if bool_like(drop_rollout_state) else "--keep-rollout-state") use_kl_loss = config.get("use_kl_loss") if use_kl_loss not in (None, ""): command.append("--use-kl-loss" if bool_like(use_kl_loss) else "--no-use-kl-loss") diff --git a/areno/engine/config.py b/areno/engine/config.py index fbc6e0f6..4db76626 100644 --- a/areno/engine/config.py +++ b/areno/engine/config.py @@ -64,7 +64,12 @@ class RuntimeConfig: attn_backend: Literal["flash", "native"] = "flash" compile_model: bool = True activation_checkpointing: bool = True - keep_rollout_state: bool = True + fp8_checkpoint_activations: bool | None = None + fp8_checkpoint_group_size: int = 128 + fp8_checkpoint_stochastic: bool = False + fp8_checkpoint_warmup_steps: int = 0 + fp8_checkpoint_fallback_layers: tuple[int, ...] = () + keep_rollout_state: bool = False optimizer_state_offload: Literal["none", "cpu", "disk"] | bool = "none" optimizer_state_offload_dir: str | None = None optimizer_state_offload_batch_size: int = 1 @@ -75,8 +80,19 @@ class RuntimeConfig: ) def __post_init__(self) -> None: + if self.fp8_checkpoint_activations is None: + self.fp8_checkpoint_activations = self.activation_checkpointing + self.fp8_checkpoint_fallback_layers = tuple(self.fp8_checkpoint_fallback_layers) if self.attn_backend not in {"flash", "native"}: raise ValueError("runtime.attn_backend must be one of: flash, native") + if self.fp8_checkpoint_activations and not self.activation_checkpointing: + raise ValueError("runtime.fp8_checkpoint_activations requires activation_checkpointing") + if self.fp8_checkpoint_group_size not in {0, 128, 256}: + raise ValueError("runtime.fp8_checkpoint_group_size must be one of: 0, 128, 256") + if self.fp8_checkpoint_warmup_steps < 0: + raise ValueError("runtime.fp8_checkpoint_warmup_steps must be non-negative") + if any(layer < 0 for layer in self.fp8_checkpoint_fallback_layers): + raise ValueError("runtime.fp8_checkpoint_fallback_layers must contain non-negative indices") if isinstance(self.optimizer_state_offload, bool): self.optimizer_state_offload = "cpu" if self.optimizer_state_offload else "none" if self.optimizer_state_offload not in {"none", "cpu", "disk"}: diff --git a/areno/engine/runtime/fp8_checkpoint.py b/areno/engine/runtime/fp8_checkpoint.py new file mode 100644 index 00000000..237d70bd --- /dev/null +++ b/areno/engine/runtime/fp8_checkpoint.py @@ -0,0 +1,228 @@ +"""FP8 storage for tensors saved at activation-checkpoint boundaries. + +The model forward still consumes BF16 tensors. Only the copy retained by +autograd for the later checkpoint recomputation is quantized, so this module +does not change the original forward graph. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from threading import Lock +from typing import Any + +import torch + +_FP8_DTYPE = torch.float8_e4m3fn +_FP8_MAX = torch.finfo(_FP8_DTYPE).max + + +@dataclass(slots=True) +class FP8CheckpointTensor: + """Quantized tensor payload returned from a saved-tensor pack hook.""" + + values: torch.Tensor + scales: torch.Tensor + shape: torch.Size + dtype: torch.dtype + group_size: int + + +@dataclass(slots=True) +class _MemoryStats: + boundaries: int = 0 + fallback_boundaries: int = 0 + warmup_boundaries: int = 0 + original_bytes: int = 0 + stored_bytes: int = 0 + + +_STATS = _MemoryStats() +_RANGE_AMAX: dict[int, torch.Tensor] = {} +_ROUNDING_GENERATORS: dict[str, torch.Generator] = {} +_LOCK = Lock() + + +def reset_fp8_checkpoint_stats() -> None: + """Reset process-local counters collected for the next train microbatch.""" + + with _LOCK: + # Reset in place. Compiled saved-tensor pack paths can retain the + # original stats object captured during their first trace; rebinding + # ``_STATS`` would make those paths update a stale object while the + # metrics reader observes a new, permanently-zero object. + _STATS.boundaries = 0 + _STATS.fallback_boundaries = 0 + _STATS.warmup_boundaries = 0 + _STATS.original_bytes = 0 + _STATS.stored_bytes = 0 + + +def fp8_checkpoint_metrics() -> dict[str, float]: + """Return checkpoint-boundary compression counters as training metrics.""" + + with _LOCK: + stats = _MemoryStats( + boundaries=_STATS.boundaries, + fallback_boundaries=_STATS.fallback_boundaries, + warmup_boundaries=_STATS.warmup_boundaries, + original_bytes=_STATS.original_bytes, + stored_bytes=_STATS.stored_bytes, + ) + reduction = 0.0 + if stats.original_bytes: + reduction = 1.0 - stats.stored_bytes / stats.original_bytes + return { + "fp8_ckpt_boundaries": float(stats.boundaries), + "fp8_ckpt_fallback_boundaries": float(stats.fallback_boundaries), + "fp8_ckpt_warmup_boundaries": float(stats.warmup_boundaries), + "fp8_ckpt_original_bytes": float(stats.original_bytes), + "fp8_ckpt_stored_bytes": float(stats.stored_bytes), + "fp8_ckpt_storage_reduction": float(reduction), + } + + +def _tensor_bytes(tensor: torch.Tensor) -> int: + return tensor.numel() * tensor.element_size() + + +def _record_compressed(original: torch.Tensor, packed: FP8CheckpointTensor) -> None: + with _LOCK: + _STATS.boundaries += 1 + _STATS.original_bytes += _tensor_bytes(original) + _STATS.stored_bytes += _tensor_bytes(packed.values) + _tensor_bytes(packed.scales) + + +def _record_fallback(tensor: torch.Tensor, *, warmup: bool = False) -> None: + with _LOCK: + _STATS.fallback_boundaries += 1 + _STATS.warmup_boundaries += int(warmup) + size = _tensor_bytes(tensor) + _STATS.original_bytes += size + _STATS.stored_bytes += size + + +def _stochastic_round(values: torch.Tensor) -> torch.Tensor: + """Add unbiased E4M3-bin noise without advancing the caller's RNG.""" + + key = str(values.device) + with _LOCK: + generator = _ROUNDING_GENERATORS.get(key) + if generator is None: + generator = torch.Generator(device=values.device) + generator.manual_seed(0xA8E0 + (values.device.index or 0)) + _ROUNDING_GENERATORS[key] = generator + random = torch.rand(values.shape, dtype=values.dtype, device=values.device, generator=generator) + magnitude = values.abs() + normal_step = torch.pow(2.0, torch.floor(torch.log2(magnitude.clamp_min(2.0**-9))) - 3.0) + step = normal_step.clamp_min(2.0**-9) + noise = (random - 0.5) * step + return torch.where(magnitude == 0, values, values + noise) + + +def pack_fp8_checkpoint_tensor( + tensor: torch.Tensor, + *, + group_size: int = 128, + stochastic: bool = False, +) -> FP8CheckpointTensor: + """Quantize a BF16 checkpoint tensor with E4M3 group-wise scales. + + ``group_size=0`` selects one scale per token. A non-divisible hidden + dimension falls back to per-token scaling rather than retaining padding. + """ + + if tensor.dtype != torch.bfloat16: + raise TypeError("FP8 checkpoint compression requires a BF16 tensor") + if tensor.ndim < 2 or tensor.numel() == 0: + raise ValueError("FP8 checkpoint compression requires a non-empty tensor with ndim >= 2") + if group_size not in {0, 128, 256}: + raise ValueError("FP8 checkpoint group_size must be one of: 0, 128, 256") + + hidden_size = tensor.shape[-1] + actual_group_size = hidden_size if group_size == 0 or hidden_size % group_size else group_size + rows = tensor.reshape(-1, hidden_size).float() + groups = rows.reshape(rows.shape[0], -1, actual_group_size) + amax = groups.abs().amax(dim=-1, keepdim=True) + scales = torch.where(amax == 0, torch.ones_like(amax), amax / _FP8_MAX) + normalized = (groups / scales).clamp(-_FP8_MAX, _FP8_MAX) + if stochastic: + normalized = _stochastic_round(normalized).clamp(-_FP8_MAX, _FP8_MAX) + values = normalized.to(_FP8_DTYPE) + return FP8CheckpointTensor( + values=values, + scales=scales, + shape=tensor.shape, + dtype=tensor.dtype, + group_size=actual_group_size, + ) + + +def unpack_fp8_checkpoint_tensor(packed: FP8CheckpointTensor) -> torch.Tensor: + """Restore a checkpoint payload to its original shape and dtype.""" + + restored = packed.values.float() * packed.scales + return restored.reshape(packed.shape).to(packed.dtype) + + +def _layer_owner(layer_fn: Any) -> Any: + if isinstance(layer_fn, torch.nn.Module): + return layer_fn + return getattr(layer_fn, "__self__", layer_fn) + + +def checkpoint_layer_index(layer_fn: Any) -> int | None: + """Resolve a stable decoder/routed-expert index from a checkpoint callable.""" + + owner = _layer_owner(layer_fn) + for candidate in (owner, getattr(owner, "self_attn", None), getattr(owner, "attention", None)): + if candidate is None: + continue + for name in ("layer_idx", "routing_layer_slot"): + value = getattr(candidate, name, None) + if isinstance(value, int): + return value + return None + + +def checkpoint_saved_tensor_hooks( + layer_fn: Any, + *, + group_size: int, + stochastic: bool, + warmup: bool, + fallback_layers: tuple[int, ...], +): + """Build hooks that compress only the input saved by a checkpoint call.""" + + layer_index = checkpoint_layer_index(layer_fn) + force_fallback = layer_index is not None and layer_index in fallback_layers + + def pack(tensor: torch.Tensor): + if tensor.dtype != torch.bfloat16 or tensor.ndim < 2 or tensor.numel() == 0: + return tensor + if warmup: + if layer_index is not None: + value = tensor.detach().abs().amax() + with _LOCK: + previous = _RANGE_AMAX.get(layer_index) + _RANGE_AMAX[layer_index] = value if previous is None else torch.maximum(previous, value) + _record_fallback(tensor, warmup=True) + return tensor + if force_fallback: + _record_fallback(tensor) + return tensor + try: + packed = pack_fp8_checkpoint_tensor(tensor, group_size=group_size, stochastic=stochastic) + except (RuntimeError, TypeError, ValueError): + _record_fallback(tensor) + return tensor + _record_compressed(tensor, packed) + return packed + + def unpack(value): + if isinstance(value, FP8CheckpointTensor): + return unpack_fp8_checkpoint_tensor(value) + return value + + return torch.autograd.graph.saved_tensors_hooks(pack, unpack) diff --git a/areno/engine/runtime/metadata.py b/areno/engine/runtime/metadata.py index cdf60164..12a33f64 100644 --- a/areno/engine/runtime/metadata.py +++ b/areno/engine/runtime/metadata.py @@ -24,6 +24,12 @@ class TrainMeta: packed: bool = False sequence_parallel: bool = False activation_checkpointing: bool = False + fp8_checkpoint_activations: bool = True + fp8_checkpoint_group_size: int = 128 + fp8_checkpoint_stochastic: bool = False + fp8_checkpoint_warmup_steps: int = 0 + fp8_checkpoint_fallback_layers: tuple[int, ...] = () + global_step: int = 0 num_padding_tokens: int = 0 routing_replay: torch.Tensor | None = None diff --git a/areno/engine/runtime/recompute.py b/areno/engine/runtime/recompute.py index 1915d803..c1b77e3d 100644 --- a/areno/engine/runtime/recompute.py +++ b/areno/engine/runtime/recompute.py @@ -9,6 +9,7 @@ from torch.utils.checkpoint import checkpoint from areno.engine.parallel.collectives import sequence_parallel_region +from areno.engine.runtime.fp8_checkpoint import checkpoint_saved_tensor_hooks from areno.engine.runtime.metadata import InferMeta, TrainMeta @@ -39,6 +40,7 @@ def checkpoint_layer( *args: Any, train_meta: TrainMeta | None = None, infer_meta: InferMeta | None = None, + compress_boundary: bool = True, ) -> Any: """Checkpoint one decoder layer, recomputing its activations in backward.""" @@ -52,12 +54,25 @@ def recompute(states: torch.Tensor) -> Any: with sequence_parallel_region(bool(train_meta.sequence_parallel)): return layer_fn(states, *args) - return checkpoint( - recompute, - hidden_states, - use_reentrant=False, - preserve_rng_state=True, + def run_checkpoint() -> Any: + return checkpoint( + recompute, + hidden_states, + use_reentrant=False, + preserve_rng_state=True, + ) + + if not compress_boundary or not getattr(train_meta, "fp8_checkpoint_activations", False): + return run_checkpoint() + hooks = checkpoint_saved_tensor_hooks( + layer_fn, + group_size=train_meta.fp8_checkpoint_group_size, + stochastic=train_meta.fp8_checkpoint_stochastic, + warmup=train_meta.global_step < train_meta.fp8_checkpoint_warmup_steps, + fallback_layers=train_meta.fp8_checkpoint_fallback_layers, ) + with hooks: + return run_checkpoint() @_disable_dynamo_frame @@ -89,5 +104,6 @@ def checkpoint_routed_moe_layer( topk_weight, train_meta=train_meta, infer_meta=infer_meta, + compress_boundary=False, ) return attended + expert_output diff --git a/areno/engine/runtime/train_step.py b/areno/engine/runtime/train_step.py index 03cd8714..ff6a9575 100644 --- a/areno/engine/runtime/train_step.py +++ b/areno/engine/runtime/train_step.py @@ -64,6 +64,17 @@ def _train_meta(data_pack: dict[str, Any], tokens: torch.Tensor, *, sequence_par packed=True, sequence_parallel=sequence_parallel, activation_checkpointing=bool(data_pack.get("_activation_checkpointing_enabled", False)), + fp8_checkpoint_activations=bool( + data_pack.get( + "_fp8_checkpoint_activations_enabled", + data_pack.get("_activation_checkpointing_enabled", False), + ) + ), + fp8_checkpoint_group_size=int(data_pack.get("_fp8_checkpoint_group_size", 128)), + fp8_checkpoint_stochastic=bool(data_pack.get("_fp8_checkpoint_stochastic", False)), + fp8_checkpoint_warmup_steps=int(data_pack.get("_fp8_checkpoint_warmup_steps", 0)), + fp8_checkpoint_fallback_layers=tuple(data_pack.get("_fp8_checkpoint_fallback_layers", ())), + global_step=int(data_pack.get("_global_step", 0)), num_padding_tokens=int(data_pack.get("packed_singleton_padding", 0)), routing_replay=data_pack.get("packed_routing_replay"), ) diff --git a/areno/engine/training.py b/areno/engine/training.py index e0dcf585..7672f05f 100644 --- a/areno/engine/training.py +++ b/areno/engine/training.py @@ -11,6 +11,7 @@ from areno.engine.modeling import param_grad, unwrap_model from areno.engine.parallel.context import get_tp_context from areno.engine.protocol import TrainPayload +from areno.engine.runtime.fp8_checkpoint import fp8_checkpoint_metrics, reset_fp8_checkpoint_stats from areno.engine.runtime.logprobs import ( packed_next_token_logprobs, packed_next_token_logprobs_from_hidden, @@ -114,7 +115,16 @@ def _train_step( torch.cuda.synchronize(worker.device) torch.cuda.reset_peak_memory_stats(worker.device) data_pack = to_device(data_pack, worker.device) - data_pack["_activation_checkpointing_enabled"] = worker.config.runtime.activation_checkpointing + runtime = worker.config.runtime + data_pack["_activation_checkpointing_enabled"] = runtime.activation_checkpointing + data_pack["_fp8_checkpoint_activations_enabled"] = runtime.fp8_checkpoint_activations + data_pack["_fp8_checkpoint_group_size"] = runtime.fp8_checkpoint_group_size + data_pack["_fp8_checkpoint_stochastic"] = runtime.fp8_checkpoint_stochastic + data_pack["_fp8_checkpoint_warmup_steps"] = runtime.fp8_checkpoint_warmup_steps + data_pack["_fp8_checkpoint_fallback_layers"] = runtime.fp8_checkpoint_fallback_layers + data_pack["_global_step"] = worker._global_step + if runtime.fp8_checkpoint_activations: + reset_fp8_checkpoint_stats() tokens = data_pack["input_ids"].long() position_ids = data_pack.get("position_ids") train_meta = _train_meta( @@ -213,6 +223,7 @@ def _train_step( {"lr": current_lr}, multimodal_lrs, {"sequence_parallel": float(model_kwargs["train_meta"].sequence_parallel)}, + fp8_checkpoint_metrics() if runtime.fp8_checkpoint_activations else None, {"grad_norm": grad_norm} if grad_norm is not None else None, multimodal_grad_metrics, {"clipped_grad_norm": clipped_grad_norm} if clipped_grad_norm is not None else None, diff --git a/areno/models/bailing_v3/model.py b/areno/models/bailing_v3/model.py index a6d0bcd8..baacdbde 100644 --- a/areno/models/bailing_v3/model.py +++ b/areno/models/bailing_v3/model.py @@ -91,6 +91,7 @@ ) from areno.engine.parallel.context import get_tp_context from areno.engine.runtime.metadata import InferMeta, TrainMeta +from areno.engine.runtime.recompute import checkpoint_layer from areno.engine.runtime.routing_replay import resolve_sigmoid_routes from areno.models._shared.dynamo_wrappers import ( _areno_depthwise_causal_conv1d_silu_decode_no_compile, @@ -1520,6 +1521,18 @@ def __init__(self, config: ModelConfig, layer_idx: int): else BailingDenseMLP(config, config.intermediate_size) ) + def _attention_block( + self, + hidden_states: torch.Tensor, + position_ids: torch.Tensor, + train_meta: TrainMeta | None, + infer_meta: InferMeta | None, + ) -> torch.Tensor: + return self.attention(self.input_layernorm(hidden_states), position_ids, train_meta, infer_meta) + + def _dense_mlp_block(self, hidden_states: torch.Tensor) -> torch.Tensor: + return self.mlp(self.post_attention_layernorm(hidden_states)) + def forward( self, hidden_states: torch.Tensor, @@ -1527,17 +1540,30 @@ def forward( train_meta: TrainMeta | None, infer_meta: InferMeta | None, ) -> torch.Tensor: - # Standard pre-norm residual: norm -> sublayer -> add. + # Checkpoint attention for every Ling/Bailing V3 layer. Sparse MoE + # routing remains outside recomputation so its load counters are not + # accumulated twice and rollout-replayed routes stay authoritative. residual = hidden_states - hidden_states = residual + self.attention( - self.input_layernorm(hidden_states), position_ids, train_meta, infer_meta + hidden_states = residual + checkpoint_layer( + self._attention_block, + hidden_states, + position_ids, + train_meta, + infer_meta, + train_meta=train_meta, + infer_meta=infer_meta, ) residual = hidden_states - mlp_input = self.post_attention_layernorm(hidden_states) if isinstance(self.mlp, BailingSparseMoeBlock): + mlp_input = self.post_attention_layernorm(hidden_states) num_padding_tokens = train_meta.num_padding_tokens if train_meta is not None else 0 return residual + self.mlp(mlp_input, num_padding_tokens) - return residual + self.mlp(mlp_input) + return residual + checkpoint_layer( + self._dense_mlp_block, + hidden_states, + train_meta=train_meta, + infer_meta=infer_meta, + ) class BailingMoeV3ForCausalLM(nn.Module): @@ -1695,7 +1721,7 @@ def reset_recurrent_cache_slots(self, slots: torch.Tensor) -> None: slots = slots.to(device=next(self.parameters()).device, dtype=torch.long) for layer in self.layers: attn = layer.attention - if isinstance(attn, (BailingLinearAttention, BailingKDAAttention)) and attn.state_cache.numel() > 0: + if isinstance(attn, BailingLinearAttention | BailingKDAAttention) and attn.state_cache.numel() > 0: attn.state_cache.index_fill_(0, slots, 0) if isinstance(attn, BailingKDAAttention) and attn.conv_cache.numel() > 0: attn.conv_cache.index_fill_(0, slots, 0) diff --git a/areno/models/gemma4/model.py b/areno/models/gemma4/model.py index 2ef5eb88..3dc40018 100644 --- a/areno/models/gemma4/model.py +++ b/areno/models/gemma4/model.py @@ -1602,6 +1602,7 @@ def _gemma4_moe_feedforward_no_compile( dense_input, train_meta=train_meta, infer_meta=infer_meta, + compress_boundary=False, ) router_logits = layer.router(residual) topk_idx, topk_weight = layer.moe.route(router_logits) @@ -1624,6 +1625,7 @@ def _gemma4_moe_feedforward_no_compile( topk_weight, train_meta=train_meta, infer_meta=infer_meta, + compress_boundary=False, ) if moe_sequence_parallel: moe_hidden = scatter_to_sequence_parallel_region(moe_hidden) diff --git a/dashboard/src/main.jsx b/dashboard/src/main.jsx index fb2ddcdf..7493a0dc 100644 --- a/dashboard/src/main.jsx +++ b/dashboard/src/main.jsx @@ -258,7 +258,8 @@ const defaultTrainConfig = { tp_size: 1, attn_backend: "flash", activation_checkpointing: true, - drop_rollout_state: false, + fp8_checkpoint_activations: true, + drop_rollout_state: true, eager_decode: false, disable_thinking: false, batch_size: 8, @@ -1789,13 +1790,18 @@ function inferPlanRunTool(plan) { function commandForPlan(tool, parameters = {}) { const mode = tool === "start_serve" ? "serve" : "train"; const args = []; - const negativeFlags = new Set(["activation_checkpointing", "use_kl_loss"]); + const negativeFlags = new Map([ + ["activation_checkpointing", "--no-activation-checkpointing"], + ["fp8_checkpoint_activations", "--no-fp8-ckpt-activations"], + ["drop_rollout_state", "--keep-rollout-state"], + ["use_kl_loss", "--no-use-kl-loss"], + ]); for (const [key, value] of Object.entries(parameters)) { if (key === "extra_args" || value === "" || value === null || value === undefined) continue; const flag = `--${key.replaceAll("_", "-")}`; if (isPlanBoolean(value)) { if (planBoolValue(value)) args.push(flag); - else if (negativeFlags.has(key)) args.push(`--no-${key.replaceAll("_", "-")}`); + else if (negativeFlags.has(key)) args.push(negativeFlags.get(key)); continue; } args.push(`${flag} ${shellQuote(value)}`); @@ -2878,6 +2884,7 @@ function trainLauncherSections(algo) { field("tp_size", "TP", true), selectField("attn_backend", "Attention", ["flash", "native"], true), checkField("activation_checkpointing", "Activation ckpt"), + checkField("fp8_checkpoint_activations", "FP8 ckpt activations"), checkField("drop_rollout_state", "Drop rollout state"), checkField("eager_decode", "Eager decode"), checkField("disable_thinking", "Disable thinking"), diff --git a/docs/cli/training.rst b/docs/cli/training.rst index 5034c984..55c6cbd1 100644 --- a/docs/cli/training.rst +++ b/docs/cli/training.rst @@ -194,10 +194,11 @@ different visible GPUs for rollout: ``--eager-decode`` Disable decode CUDA graph and run rollout decode eagerly. CUDA only. -``--drop-rollout-state`` +``--drop-rollout-state / --keep-rollout-state`` Drop completed rollout KV/cache state after each step to save device - memory. By default, Areno keeps reusable rollout state between steps for - lower setup overhead. Supported by both CUDA and MLX. + memory. Dropping is enabled by default. Use ``--keep-rollout-state`` to + retain reusable state between steps for lower setup overhead. Supported by + both CUDA and MLX. ``--attn-backend [flash|native]`` Attention backend. Default: ``flash``. Use ``native`` to run without @@ -284,8 +285,8 @@ Search is deliberately conservative: skipped and that concurrency is used directly for training-parameter tuning; * training uses the rollout-selected concurrency to derive a batch size, then tries larger to smaller ``--mini-bs`` values; -* ``--drop-rollout-state`` is enabled for the tuned run so rollout memory does - not remain resident during the training probe or optimizer step. +* the default dropped rollout state is used for the tuned run so rollout + memory does not remain resident during the training probe or optimizer step. ``--mem-frac FLOAT`` Target maximum GPU memory fraction for tuning. Default: ``0.9``. Lower this @@ -339,6 +340,13 @@ in its description; flags for other algorithms are ignored. Enable decoder-layer activation recompute during training. Default: enabled. +``--fp8-ckpt-activations / --no-fp8-ckpt-activations`` + Store the BF16 tensors retained at decoder activation-checkpoint boundaries + as group-wise FP8 E4M3 and restore them before backward recomputation. The + original forward remains BF16. Enabled by default on CUDA when activation + checkpointing is enabled. Use ``--no-fp8-ckpt-activations`` to retain BF16 + boundary tensors. CUDA only. + ``--optimizer-state-offload [none|cpu|disk]`` Select CUDA optimizer-state residency. ``none`` keeps state on the training device. ``cpu`` moves state to host memory between train calls. ``disk`` diff --git a/docs/concepts/backend-topology.rst b/docs/concepts/backend-topology.rst index 4d3b7f78..f6118ad3 100644 --- a/docs/concepts/backend-topology.rst +++ b/docs/concepts/backend-topology.rst @@ -77,8 +77,9 @@ DPO and PPO. MLX runs with ``world-size=1`` and ``tp-size=1`` on unified memory. CUDA device lists, independent rollout partitions, NCCL policy synchronization, -and CUDA graph capture do not apply. ``--drop-rollout-state`` controls whether -completed rollout cache state is retained across session boundaries. +and CUDA graph capture do not apply. Completed rollout cache state is dropped +at session boundaries by default; ``--keep-rollout-state`` retains it across +boundaries. Shared behavior --------------- diff --git a/docs/concepts/multimodal-inputs.rst b/docs/concepts/multimodal-inputs.rst index 24b62eab..b72b23ea 100644 --- a/docs/concepts/multimodal-inputs.rst +++ b/docs/concepts/multimodal-inputs.rst @@ -156,5 +156,6 @@ Troubleshooting * Set ``ARENO_LOG_COMPLETIONS=1`` during agentic smoke tests to verify output and tool-call formatting before launching a long run. * On Apple Silicon, reduce ``--mini-bs`` and ``--max-running-prompts`` first; - use ``--drop-rollout-state`` when retained KV/cache state competes with - training activations. See :doc:`../getting-started/mlx`. + completed rollout KV/cache state is dropped by default so it does not + compete with training activations. Use ``--keep-rollout-state`` only when + retaining reusable state is preferable. See :doc:`../getting-started/mlx`. diff --git a/docs/getting-started/cuda.rst b/docs/getting-started/cuda.rst index 963ed981..6b2cd47e 100644 --- a/docs/getting-started/cuda.rst +++ b/docs/getting-started/cuda.rst @@ -92,14 +92,22 @@ The main CUDA controls are: ``--max-running-prompts N`` Caps active rollout sequences and their KV-cache demand. -``--drop-rollout-state`` - Releases completed rollout state at the session boundary rather than - retaining reusable cache and graph state for the next rollout. +``--drop-rollout-state / --keep-rollout-state`` + Completed rollout state is released at the session boundary by default. + Use ``--keep-rollout-state`` to retain reusable cache and graph state for + the next rollout. ``--activation-checkpointing`` Recomputes supported decoder activations during backward. It is enabled by default. +``--fp8-ckpt-activations / --no-fp8-ckpt-activations`` + Stores activation-checkpoint boundary tensors in FP8 E4M3 by default while + keeping the original forward in BF16. Use the negative flag to retain BF16 + boundary storage. Ling/Bailing V3 checkpoints attention in every decoder + layer and dense MLP blocks; sparse routing and routed experts remain outside + recomputation so routing load counters are updated exactly once. + ``--optimizer-state-offload cpu`` Moves optimizer state to host memory between train calls. diff --git a/docs/getting-started/mlx.rst b/docs/getting-started/mlx.rst index 2bd699f7..a0f8e094 100644 --- a/docs/getting-started/mlx.rst +++ b/docs/getting-started/mlx.rst @@ -87,9 +87,10 @@ options have the largest effect on MLX unified-memory use: Caps active rollout sequences. Reduce it when KV cache or multimodal prefill features dominate memory. -``--drop-rollout-state`` - Releases completed rollout KV/cache state at the rollout-session boundary - instead of retaining it for the next rollout. +``--drop-rollout-state / --keep-rollout-state`` + Completed rollout KV/cache state is released at the rollout-session + boundary by default. Use ``--keep-rollout-state`` to retain it for the next + rollout. ``--adam-8bit`` Stores Adam moment state in the MLX backend's 8-bit representation. This diff --git a/docs/models/supported.rst b/docs/models/supported.rst index d5dbfa29..d6fc83d7 100644 --- a/docs/models/supported.rst +++ b/docs/models/supported.rst @@ -27,6 +27,9 @@ family is available on both backends. ``qwen3_5_moe`` layouts, with Areno MoE kernels. * - Bailing MoE Linear v2 - Local model adapter for Bailing MoE Linear v2 checkpoints. + * - Ling / Bailing MoE V3 + - ``bailing_hybrid`` checkpoints with softmax/KDA attention, sparse MoE, + activation checkpointing, and FP8 checkpoint-boundary storage. * - Gemma4 - Gemma4 text and conditional-generation checkpoints. Native Gemma4 and Gemma4 Unified processors support image, audio, and video inputs for diff --git a/tests/test_config_data_cpu.py b/tests/test_config_data_cpu.py index 81ab4fd5..6c242af7 100644 --- a/tests/test_config_data_cpu.py +++ b/tests/test_config_data_cpu.py @@ -643,15 +643,97 @@ def test_rollout_config_respects_explicit_max_running_prompts(self): self.assertEqual(cfg.resolved_max_running_prompts(), 64) - def test_trainer_config_keeps_rollout_state_by_default(self): - """Runtime defaults should favor rollout speed unless explicitly disabled.""" + def test_trainer_config_drops_rollout_state_by_default(self): + """Runtime defaults should favor lower memory unless explicitly retained.""" cfg = TrainerConfig(algo="sft", ckpt="unused", dataset_path="unused") - self.assertTrue(cfg.keep_rollout_state) + self.assertFalse(cfg.keep_rollout_state) self.assertEqual(cfg.optimizer_state_offload_batch_size, 1) - self.assertTrue(cfg.cuda_config().runtime["keep_rollout_state"]) + self.assertFalse(cfg.cuda_config().runtime["keep_rollout_state"]) self.assertEqual(cfg.cuda_config().runtime["optimizer_state_offload_batch_size"], 1) - self.assertTrue(cfg.mlx_config().keep_rollout_state) + self.assertFalse(cfg.mlx_config().keep_rollout_state) + + def test_fp8_checkpoint_activations_default_to_cuda_checkpointing(self): + cuda = TrainerConfig(algo="sft", backend="cuda", ckpt="unused", dataset_path="unused") + cuda_without_checkpointing = TrainerConfig( + algo="sft", + backend="cuda", + ckpt="unused", + dataset_path="unused", + activation_checkpointing=False, + ) + mlx = TrainerConfig(algo="sft", backend="mlx", ckpt="unused", dataset_path="unused") + + self.assertTrue(cuda.fp8_checkpoint_activations) + self.assertFalse(cuda_without_checkpointing.fp8_checkpoint_activations) + self.assertFalse(mlx.fp8_checkpoint_activations) + self.assertTrue(RuntimeConfig().fp8_checkpoint_activations) + + def test_fp8_checkpoint_activation_config_reaches_cuda_runtime(self): + """The SDK knob should preserve advanced compression controls.""" + cfg = TrainerConfig( + algo="sft", + backend="cuda", + ckpt="unused", + dataset_path="unused", + fp8_checkpoint_activations=True, + fp8_checkpoint_group_size=256, + fp8_checkpoint_stochastic=True, + fp8_checkpoint_warmup_steps=2, + fp8_checkpoint_fallback_layers=(0, 7), + ) + + runtime = cfg.cuda_config().runtime + self.assertTrue(runtime["fp8_checkpoint_activations"]) + self.assertEqual(runtime["fp8_checkpoint_group_size"], 256) + self.assertTrue(runtime["fp8_checkpoint_stochastic"]) + self.assertEqual(runtime["fp8_checkpoint_warmup_steps"], 2) + self.assertEqual(runtime["fp8_checkpoint_fallback_layers"], (0, 7)) + + def test_fp8_checkpoint_activation_config_rejects_invalid_combinations(self): + with self.assertRaisesRegex(ValueError, "requires activation_checkpointing"): + TrainerConfig( + algo="sft", + backend="cuda", + ckpt="unused", + dataset_path="unused", + activation_checkpointing=False, + fp8_checkpoint_activations=True, + ) + with self.assertRaisesRegex(ValueError, "only supported by the CUDA backend"): + TrainerConfig( + algo="sft", + backend="mlx", + ckpt="unused", + dataset_path="unused", + fp8_checkpoint_activations=True, + ) + with self.assertRaisesRegex(ValueError, "group_size"): + RuntimeConfig(fp8_checkpoint_group_size=64) + + def test_fp8_checkpoint_activation_settings_reach_train_metadata(self): + tokens = torch.ones((1, 4), dtype=torch.long) + meta = train_step_runtime._train_meta( + { + "train_cu_seqlens": torch.tensor([0, 4], dtype=torch.int32), + "_activation_checkpointing_enabled": True, + "_fp8_checkpoint_activations_enabled": True, + "_fp8_checkpoint_group_size": 256, + "_fp8_checkpoint_stochastic": True, + "_fp8_checkpoint_warmup_steps": 3, + "_fp8_checkpoint_fallback_layers": (1, 5), + "_global_step": 2, + }, + tokens, + sequence_parallel=False, + ) + + self.assertTrue(meta.fp8_checkpoint_activations) + self.assertEqual(meta.fp8_checkpoint_group_size, 256) + self.assertTrue(meta.fp8_checkpoint_stochastic) + self.assertEqual(meta.fp8_checkpoint_warmup_steps, 3) + self.assertEqual(meta.fp8_checkpoint_fallback_layers, (1, 5)) + self.assertEqual(meta.global_step, 2) def test_train_cli_drop_rollout_state_inverts_runtime_flag(self): """The public CLI exposes the memory-saving inverse of keep_rollout_state.""" @@ -662,13 +744,16 @@ def test_train_cli_drop_rollout_state_inverts_runtime_flag(self): self.assertFalse(cfg.keep_rollout_state) self.assertFalse(cfg.mlx_config().keep_rollout_state) + kept = train_cli._trainer_config_from_args(_train_args(algo="sft", drop_rollout_state=False)) + self.assertTrue(kept.keep_rollout_state) + def test_train_cli_optimizer_state_offload_reaches_cuda_runtime(self): """SFT can offload optimizer state without changing rollout-state retention.""" args = _train_args(algo="sft", optimizer_state_offload="cpu") cfg = train_cli._trainer_config_from_args(args) - self.assertTrue(cfg.keep_rollout_state) + self.assertFalse(cfg.keep_rollout_state) self.assertEqual(cfg.optimizer_state_offload, "cpu") self.assertEqual(cfg.cuda_config().runtime["optimizer_state_offload"], "cpu") @@ -1061,7 +1146,7 @@ def _train_args(**overrides): weight_decay=1e-2, grad_clip_norm=1.0, activation_checkpointing=True, - drop_rollout_state=False, + drop_rollout_state=True, optimizer_state_offload="none", optimizer_state_offload_dir=None, optimizer_state_offload_batch_size=1, diff --git a/tests/test_dashboard_metrics_path_cpu.py b/tests/test_dashboard_metrics_path_cpu.py index c355b6cf..aba8c915 100644 --- a/tests/test_dashboard_metrics_path_cpu.py +++ b/tests/test_dashboard_metrics_path_cpu.py @@ -8,6 +8,7 @@ DashboardState, Job, agent_language_instruction, + build_train_command, repair_action_for_check, sample_media_references, start_runtime_repair, @@ -91,6 +92,16 @@ def test_agent_language_instruction_follows_dashboard_language(): assert "English" in agent_language_instruction({"language": "en"}) +def test_train_command_emits_memory_saving_boolean_choices(): + defaults = build_train_command({"fp8_checkpoint_activations": True, "drop_rollout_state": True}) + disabled = build_train_command({"fp8_checkpoint_activations": False, "drop_rollout_state": False}) + + assert "--fp8-ckpt-activations" in defaults + assert "--drop-rollout-state" in defaults + assert "--no-fp8-ckpt-activations" in disabled + assert "--keep-rollout-state" in disabled + + @pytest.mark.parametrize( ("name", "package", "command_tail"), [ diff --git a/tests/test_moe_sequence_parallel_cpu.py b/tests/test_moe_sequence_parallel_cpu.py index 4c27fcb5..ba479179 100644 --- a/tests/test_moe_sequence_parallel_cpu.py +++ b/tests/test_moe_sequence_parallel_cpu.py @@ -133,6 +133,92 @@ def shared_experts(states): torch.testing.assert_close(output.float(), torch.full_like(output.float(), 5)) +def test_bailing_v3_decoder_checkpoints_attention_and_dense_mlp(monkeypatch): + pytest.importorskip("triton") + import areno.models.bailing_v3.model as bailing_v3 + + checkpointed = [] + + def checkpoint(function, states, *args, train_meta=None, infer_meta=None, **kwargs): + del train_meta, infer_meta, kwargs + checkpointed.append(function.__name__) + return function(states, *args) + + monkeypatch.setattr(bailing_v3, "checkpoint_layer", checkpoint) + + class DenseMlp: + pass + + def attention_block(states, position_ids, train_meta, infer_meta): + del position_ids, train_meta, infer_meta + return states * 2 + + def dense_mlp_block(states): + return states * 3 + + layer = SimpleNamespace( + _attention_block=attention_block, + _dense_mlp_block=dense_mlp_block, + mlp=DenseMlp(), + ) + hidden = torch.ones((1, 2, 2)) + + output = bailing_v3.BailingDecoderLayer.forward( + layer, + hidden, + torch.arange(2).unsqueeze(0), + SimpleNamespace(num_padding_tokens=0), + None, + ) + + assert checkpointed == ["attention_block", "dense_mlp_block"] + torch.testing.assert_close(output, torch.full_like(output, 12)) + + +def test_bailing_v3_decoder_keeps_sparse_router_outside_recompute(monkeypatch): + pytest.importorskip("triton") + import areno.models.bailing_v3.model as bailing_v3 + + checkpointed = [] + sparse_calls = [] + + def checkpoint(function, states, *args, train_meta=None, infer_meta=None, **kwargs): + del train_meta, infer_meta, kwargs + checkpointed.append(function.__name__) + return function(states, *args) + + class SparseMlp: + def __call__(self, states, num_padding_tokens): + sparse_calls.append(num_padding_tokens) + return states * 3 + + monkeypatch.setattr(bailing_v3, "checkpoint_layer", checkpoint) + monkeypatch.setattr(bailing_v3, "BailingSparseMoeBlock", SparseMlp) + + def attention_block(states, position_ids, train_meta, infer_meta): + del position_ids, train_meta, infer_meta + return states * 2 + + layer = SimpleNamespace( + _attention_block=attention_block, + post_attention_layernorm=lambda states: states, + mlp=SparseMlp(), + ) + hidden = torch.ones((1, 2, 2)) + + output = bailing_v3.BailingDecoderLayer.forward( + layer, + hidden, + torch.arange(2).unsqueeze(0), + SimpleNamespace(num_padding_tokens=1), + None, + ) + + assert checkpointed == ["attention_block"] + assert sparse_calls == [1] + torch.testing.assert_close(output, torch.full_like(output, 12)) + + def test_bailing_router_load_ignores_alignment_tokens(monkeypatch): pytest.importorskip("triton") import areno.models.bailing.model as bailing diff --git a/tests/test_recompute_cpu.py b/tests/test_recompute_cpu.py index cbaae558..6611150d 100644 --- a/tests/test_recompute_cpu.py +++ b/tests/test_recompute_cpu.py @@ -5,6 +5,13 @@ import torch from areno.engine.parallel.collectives import is_sequence_parallel_active +from areno.engine.runtime import fp8_checkpoint as fp8_checkpoint_module +from areno.engine.runtime.fp8_checkpoint import ( + fp8_checkpoint_metrics, + pack_fp8_checkpoint_tensor, + reset_fp8_checkpoint_stats, + unpack_fp8_checkpoint_tensor, +) from areno.engine.runtime.metadata import InferMeta, TrainMeta from areno.engine.runtime.recompute import checkpoint_layer, checkpoint_routed_moe_layer, should_checkpoint_layer @@ -12,6 +19,16 @@ class RecomputeTest(unittest.TestCase): """Activation checkpoint tests use tiny CPU tensors and no model weights.""" + def test_fp8_checkpoint_stats_reset_preserves_compiled_reference(self): + captured_stats = fp8_checkpoint_module._STATS + + reset_fp8_checkpoint_stats() + + self.assertIs(fp8_checkpoint_module._STATS, captured_stats) + captured_stats.boundaries += 1 + self.assertEqual(fp8_checkpoint_metrics()["fp8_ckpt_boundaries"], 1.0) + reset_fp8_checkpoint_stats() + def test_should_checkpoint_layer_requires_training_forward(self): """Recompute is enabled only for grad-enabled training forwards.""" train_meta = TrainMeta(activation_checkpointing=True) @@ -41,6 +58,105 @@ def layer_fn(x, bias): self.assertTrue(torch.equal(x.grad, torch.tensor([2.0, 4.0, 6.0]))) self.assertGreaterEqual(calls["count"], 1) + def test_fp8_boundary_storage_reduces_bytes_and_restores_bf16(self): + """Group-128 E4M3 storage should be far smaller than its BF16 source.""" + states = torch.randn((2, 4, 256), dtype=torch.bfloat16) + + packed = pack_fp8_checkpoint_tensor(states, group_size=128) + restored = unpack_fp8_checkpoint_tensor(packed) + + self.assertEqual(packed.values.dtype, torch.float8_e4m3fn) + self.assertEqual(restored.dtype, torch.bfloat16) + self.assertEqual(restored.shape, states.shape) + stored_bytes = packed.values.numel() * packed.values.element_size() + stored_bytes += packed.scales.numel() * packed.scales.element_size() + original_bytes = states.numel() * states.element_size() + self.assertLessEqual(stored_bytes, original_bytes * 0.55) + self.assertTrue(torch.allclose(restored.float(), states.float(), rtol=0.13, atol=0.13)) + + def test_fp8_checkpoint_keeps_forward_exact_and_gradient_close(self): + """Only backward recomputation observes restored FP8 boundary values.""" + source = torch.randn((2, 3, 256), dtype=torch.bfloat16) + exact_states = source.clone().requires_grad_(True) + fp8_states = source.clone().requires_grad_(True) + + def layer_fn(states): + return torch.sin(states.float()).square().sum() + + exact = checkpoint_layer( + layer_fn, + exact_states, + train_meta=TrainMeta(activation_checkpointing=True), + ) + reset_fp8_checkpoint_stats() + compressed = checkpoint_layer( + layer_fn, + fp8_states, + train_meta=TrainMeta(activation_checkpointing=True, fp8_checkpoint_activations=True), + ) + self.assertTrue(torch.equal(exact, compressed)) + exact.backward() + compressed.backward() + + cosine = torch.nn.functional.cosine_similarity( + exact_states.grad.float().flatten(), fp8_states.grad.float().flatten(), dim=0 + ) + self.assertGreaterEqual(float(cosine), 0.99) + metrics = fp8_checkpoint_metrics() + self.assertEqual(metrics["fp8_ckpt_boundaries"], 1.0) + self.assertGreaterEqual(metrics["fp8_ckpt_storage_reduction"], 0.45) + + def test_fp8_checkpoint_warmup_fallback_and_opt_out(self): + """Warm-up, layer fallback, and sensitive boundaries retain BF16.""" + + class Layer(torch.nn.Module): + layer_idx = 2 + + def forward(self, states): + return states.float().square().sum() + + for meta, compress_boundary in ( + ( + TrainMeta( + activation_checkpointing=True, + fp8_checkpoint_activations=True, + fp8_checkpoint_warmup_steps=1, + global_step=0, + ), + True, + ), + ( + TrainMeta( + activation_checkpointing=True, + fp8_checkpoint_activations=True, + fp8_checkpoint_fallback_layers=(2,), + ), + True, + ), + (TrainMeta(activation_checkpointing=True, fp8_checkpoint_activations=True), False), + ): + reset_fp8_checkpoint_stats() + states = torch.randn((1, 2, 256), dtype=torch.bfloat16, requires_grad=True) + output = checkpoint_layer( + Layer(), + states, + train_meta=meta, + compress_boundary=compress_boundary, + ) + output.backward() + metrics = fp8_checkpoint_metrics() + self.assertEqual(metrics["fp8_ckpt_boundaries"], 0.0) + self.assertEqual(metrics["fp8_ckpt_storage_reduction"], 0.0) + + def test_stochastic_fp8_pack_preserves_caller_rng(self): + """Boundary rounding must not perturb dropout RNG in the exact forward.""" + states = torch.randn((2, 2, 256), dtype=torch.bfloat16) + torch.manual_seed(1234) + rng_before = torch.random.get_rng_state() + pack_fp8_checkpoint_tensor(states, stochastic=True) + rng_after = torch.random.get_rng_state() + self.assertTrue(torch.equal(rng_before, rng_after)) + def test_checkpoint_layer_bypasses_checkpoint_for_infer_meta(self): """Inference metadata must bypass checkpointing even when train_meta opts in.""" calls = {"count": 0} diff --git a/tests/test_train_cli_config_cpu.py b/tests/test_train_cli_config_cpu.py index ffd57030..5c88e45f 100644 --- a/tests/test_train_cli_config_cpu.py +++ b/tests/test_train_cli_config_cpu.py @@ -924,6 +924,38 @@ def test_train_help_places_epochs_under_basic_not_checkpointing(): assert "--epochs" not in output[checkpoint:] +def test_train_help_exposes_fp8_checkpoint_activation_flag(): + output = _help_output() + + assert "--fp8-ckpt-activations" in output + assert "--no-fp8-ckpt-activations" in output + assert "--keep-rollout-state" in output + + +def test_train_fp8_checkpoint_activation_flag_reaches_runtime(): + cfg = _trainer_config_from_options(**_options(algo="sft", backend="cuda", fp8_checkpoint_activations=True)) + + assert cfg.fp8_checkpoint_activations is True + assert cfg.cuda_config().runtime["fp8_checkpoint_activations"] is True + + +def test_train_memory_saving_defaults_can_be_disabled(): + defaults = _trainer_config_from_options(**_options(algo="sft", backend="cuda")) + disabled = _trainer_config_from_options( + **_options( + algo="sft", + backend="cuda", + fp8_checkpoint_activations=False, + drop_rollout_state=False, + ) + ) + + assert defaults.fp8_checkpoint_activations is True + assert defaults.keep_rollout_state is False + assert disabled.fp8_checkpoint_activations is False + assert disabled.keep_rollout_state is True + + def test_train_help_remains_complete_and_groups_every_declared_option(): ctx = train_cli.click.Context(train_cli.train_command) declared = { @@ -1005,7 +1037,7 @@ def _options(**overrides): weight_decay=1e-2, grad_clip_norm=1.0, activation_checkpointing=True, - drop_rollout_state=False, + drop_rollout_state=True, eager_decode=False, attn_backend="flash", disable_thinking=False,