1(()=>{"use strict";var e,t={5101(e,t,n){var i=n(3559);i.r1M.prototype.attrs=function(e){for(const t in e)this.attr(t,e[t]);return this},i.r1M.prototype.styles=function(e){for(const t in e)this.style(t,e[t]);return this},i.kYK&&(i.kYK.prototype.attrs=function(e){for(const t in e)this.attr(t,e[t]);return this},i.kYK.prototype.styles=function(e){for(const t in e)this.style(t,e[t]);return this});const o={zh:{"Back to Info Lens":"è¿å Info Lens ä¿¡æ¯éé","A toolbox for exploring the informational nature of LLMs and language":"ç¨äºæ¢ç´¢ LLM ä¸è¯è¨çä¿¡æ¯æ¬è´¨çå·¥å
·ç®±","Info Highlight":"Info Highlight ä¿¡æ¯é«äº®","- highlight the 'informative' parts":"- é«äº®âä¿¡æ¯é大âçå°æ¹","LLM Raw Chat":"LLM Raw Chat åå§å¯¹è¯","- chat with explicit raw prompts":"- ç¨ç²¾ç¡®ç prompt è¿è¡å¯¹è¯","Context Attribution":"Context Attribution ä¸ä¸æå½å ","- attribute a predicted token to its context":"- å°é¢æµ token å½å å°ä¸ä¸æ","LLM Causal Flow":"LLM Causal Flow å ææµ","- explore the context-attribution DAG":"- æ¢ç´¢ä¸ä¸æå½å ç DAG å
³ç³»å¾","1M+ plays on RedNote":"å°çº¢ä¹¦ 100ä¸+æ¬¡ææ¾","Go to demo on RedNote: xhslink.com":"å¨å°çº¢ä¹¦æå¼demoï¼xhslink.com","500 likes/stars on RedNote":"å°çº¢ä¹¦ 500 èµè","1K+ likes/stars on RedNote":"å°çº¢ä¹¦ 1å+ èµè","Info Lens - A toolbox for exploring the informational nature of LLMs and language":"Info Lens ä¿¡æ¯éé - ç¨äºæ¢ç´¢ LLM ä¸è¯è¨çä¿¡æ¯æ¬è´¨çå·¥å
·ç®±","Info Highlight - highlight the 'informative' parts":"Info Highlight ä¿¡æ¯é«äº® - é«äº®âä¿¡æ¯é大âçå°æ¹","LLM Raw Chat - chat with explicit raw prompts":"LLM Raw Chat åå§å¯¹è¯ - ç¨ç²¾ç¡®ç prompt è¿è¡å¯¹è¯","Context Attribution - attribute a predicted token to its context":"Context Attribution ä¸ä¸æå½å - å°é¢æµ token å½å å°ä¸ä¸æ","LLM Causal Flow - explore the context-attribution DAG":"LLM Causal Flow å ææµ - æ¢ç´¢ä¸ä¸æå½å ç DAG å
³ç³»å¾","Max new tokens must not exceed {limit}":"Max new tokens ä¸å¾è¶
è¿ {limit}","Max new tokens must be a positive integer":"Max new tokens é¡»ä¸ºæ£æ´æ°","When enabled, each line below is a regex with the global flag, matched only within input areas (excluding generated continuation). Matched prompt tokens are physically removed from the DAG â they neither appear nor occupy layout space (stricter than Exclude + Hide).":"å¯ç¨åä»
å¨ input åºï¼ä¸å«å·²çæ continuationï¼å
æä¸åæ£åå¹é
ï¼å½ä¸ç prompt token ä» DAG ç©çç§»é¤ï¼ä¸å å¸å±ï¼æ¯ Exclude + Hide æ´ä¸¥æ ¼ï¼ã","One regex per line (global flag), matched only within input areas (excluding generated continuation); matched tokens are deleted from the DAG and do not occupy layout space.":"æ¯è¡ä¸æ¡æ£åï¼`g`ï¼ä»
å¨ input åºï¼ä¸å«å·²çæ continuationï¼å
å¹é
ï¼å½ä¸ç token ä» DAG å é¤ä¸ä¸å å¸å±ç©ºé´ã","When enabled, each line below is a regex with the global flag, matched only within input areas (excluding generated continuation). If a token offset lies fully inside a match, its score is treated as 0.":"å¯ç¨åä»
å¨ input åºï¼ä¸å«å·²çæ continuationï¼å
æä¸åæ£åå¹é
ï¼token ç offset å®å
¨è½å¨ææ¬¡å¹é
åºé´å
å score è§ä¸º 0ã","One regex per line (input areas only)":"æ¯è¡ä¸æ¡æ£åï¼ä»
input åºï¼","One regex per line (global flag), matched only within input areas (excluding generated continuation); if a token offset lies fully inside a match, its score is treated as 0.":"æ¯è¡ä¸æ¡æ£åï¼`g`ï¼ä»
å¨ input åºï¼ä¸å«å·²çæ continuationï¼å
å¹é
ï¼token ç offset å®å
¨è½å¨ææ¬¡å¹é
åºé´å
å score è§ä¸º 0ã","When enabled, each line below is a regex with the global flag, matched only within the model-generated continuation (excluding the initial static prompt). If a token offset lies fully inside a match, its score is treated as 0.":"å¯ç¨åä»
卿¨¡åå·²çæç continuationï¼ä¸å«åå§éæ promptï¼å
æä¸åæ£åå¹é
ï¼token ç offset å®å
¨è½å¨ææ¬¡å¹é
åºé´å
å score è§ä¸º 0ã","One regex per line (generated continuation only)":"æ¯è¡ä¸æ¡æ£åï¼ä»
å·²çæ continuationï¼","One regex per line (global flag), matched only within the generated suffix; if a token offset lies fully inside a match, its score is treated as 0.":"æ¯è¡ä¸æ¡æ£åï¼`g`ï¼ä»
å¨å·²çæåç¼å
å¹é
ï¼token ç offset å®å
¨è½å¨ææ¬¡å¹é
åºé´å
å score è§ä¸º 0ã","Coverage is the cumulative mass share within each generation step's Top-N candidate pool (after sorting candidates into the pool and n
1ormalizing mass inside that pool). Higher values keep more incoming edges. The denominator is this pool only, not every token-attribution entry returned for the step.":"Coverage ææ¯ä¸æ¥å¨ Top-N åéæ± å
ç累计质é份é¢ï¼å
å
¥æ± ãæ± å
å½ä¸åæå¼ºåº¦æåºåç´¯å ï¼ãæ°å¼è¶å¤§ä¿çç DAG å
¥è¾¹è¶å¤ï¼åæ¯ä»
为该åéæ± ï¼ä¸æ¯è¯¥æ¥ API è¿åçå
¨é¨å½å tokenã","When checked, gray DAG edges (or gray matrix cells) not highlighted by the current focus are hidden.":"å¾éåï¼æªå¤äºå½åç¦ç¹é«äº®æçç°è²è¾¹ï¼æ matrix ç°æ ¼ï¼å°è¢«éèã","Show token tooltip":"æ¾ç¤º token æç¤º","When checked, selecting or hovering a token node shows token information in the results area.":"å¾éåï¼éä¸ææ¬æµ® token èç¹æ¶ï¼å¨å³ä¾§ç»æåºå±ç¤ºè¯¥ token çä¿¡æ¯ï¼ä¿¡æ¯éã颿µåå¸ãå½å 份é¢çï¼ã","Width (px) of the invisible measurement layer used for DAG layout. Only this width affects wrapping and node positions. When idle, changes replay and fit automatically; during generation or DAG step replay (â¶), the setting updates for the next run or refresh.":"DAG èç¹å 使åºäºçä¸å¯è§æµéå±å®½åº¦ï¼pxï¼ãåªææµéå±å®½åº¦ä¼å½±åèç¹æè¡/ä½ç½®ãä¿®æ¹åï¼ç¨³æä¸èªå¨ææ°å®½åº¦éæ¾å¹¶ fitï¼è¥æ£å¨çææ DAG æ¥è¿éæ¾ï¼â¶ï¼ä¸ï¼ä»
æ´æ°è®¾ç½®ï¼ä¸æ¬¡å·æ°/çææ¶çæã","Token distance":"Token distance é´è·","Horizontal gap (px) between the outer left/right edges of adjacent token nodes in linear-arc / linear-arc-step-down layout only. When idle, the DAG refits; during generation or DAG step replay (â¶), the value is stored and applied on the next sync.":"ä»
linear-arc / linear-arc-step-down å¸å±ä¸çæï¼ç¸é» token èç¹ç©å½¢å¤ä¾§è¾¹ä¹é´çæ°´å¹³é´éï¼pxï¼ãä¿®æ¹åï¼ç¨³æä¸ç«å³éç»å¹¶ fitï¼è¥æ£å¨çææ DAG æ¥è¿éæ¾ï¼â¶ï¼ä¸ï¼ä»
åå
¥åå¨ï¼ä¸ä¸è½®åæ¥æ¶ååæ ã","Horizontal gap (px) between the outer left/right edges of adjacent token nodes in linear-arc layout only. When idle, the DAG refits; during generation or DAG step replay (â¶), the value is stored and applied on the next sync.":"ä»
linear-arc / linear-arc-step-down å¸å±ä¸çæï¼ç¸é» token èç¹ç©å½¢å¤ä¾§è¾¹ä¹é´çæ°´å¹³é´éï¼pxï¼ãä¿®æ¹åï¼ç¨³æä¸ç«å³éç»å¹¶ fitï¼è¥æ£å¨çææ DAG æ¥è¿éæ¾ï¼â¶ï¼ä¸ï¼ä»
åå
¥åå¨ï¼ä¸ä¸è½®åæ¥æ¶ååæ ã",Compactness:"DAG ç´§å度",Transition:"转åº","When checked, animate DAG layout switches. Duration is in seconds. Saved locally.":"å¾éåï¼åæ¢ DAG layout æ¶ææ¾è½¬åºå¨ç»ï¼æ¶é¿åä½ä¸ºç§ãåå
¥æ¬å°åå¨ã","Seconds for layout transition animation when Transition is checked. Saved locally.":"å¾é Transition æ¶ï¼layout 转åºå¨ç»æ¶é¿ï¼ç§ï¼ãåå
¥æ¬å°åå¨ã","Scales DAG node boxes and labels relative to the measurement layer; 1 matches full readout scale. When idle, changes replay and fit automatically; during generation or DAG step replay (â¶), the setting updates for the next run or refresh.":"ç¸å¯¹æµéå±ç¼©æ¾ DAG èç¹æ¡ä¸æ ç¾ï¼1 䏿£æé
读æ¯ä¾ä¸è´ãä¿®æ¹åï¼ç¨³æä¸èªå¨éæ¾å¹¶ fitï¼è¥æ£å¨çææ DAG æ¥è¿éæ¾ï¼â¶ï¼ä¸ï¼ä»
æ´æ°è®¾ç½®ï¼ä¸æ¬¡è¿è¡æå·æ°æ¶çæã","Delay in milliseconds between steps during DAG step replay (â¶). Stored locally; the value is read when you press playâchanging it mid-playback does not affect the current run.":"DAG æ¥è¿éæ¾ï¼â¶ï¼æ¶ç¸é»ä¸¤æ¥ä¹é´çé´éï¼msï¼ãåå
¥æ¬å°åå¨ï¼æ¯æ¬¡ç¹å»ææ¾æ¶è¯»åå½åè¾å
¥ï¼ææ¾ä¸éæ¹æ°å¼ä¸å½±åæ¬è½®ã","Perform gradient attribution on the target token below.":"对以ä¸target token忢¯åº¦å½å ã",Context:"Context ä¸ä¸æ","Target prediction":"Target prediction ç®æ 颿µ","Analyze attribution":"å½å åæ","{count} tokens":"{count} 个 token","Exclude prompt patterns":"æé¤prompté¨åçæ£å","Exclude generated patterns":"æé¤çæé¨åçæ£å","One regex per line (context only)":"æ¯è¡ä¸æ¡æ£åï¼ä»
contextï¼","When enabled, each line below is a regex with the global flag, matched only within the context field below. If a token offset lies fully inside a match, its score is treated as 0.":"å¯ç¨åä»
å¨ä¸æ¹ context è¾å
¥æ¡å
¨æå
æä¸åæ£åå¹é
ï¼token ç offset å®å
¨è½å¨ææ¬¡å¹é
åºé´å
å score è§ä¸º 0ã","One regex per line (global flag), matched only within the context text; if a token offset lies fully inside a match, its score is treated as 0.":"æ¯è¡ä¸æ¡æ£åï¼`g`ï¼ä»
å¨ context å
¨æä¸å¹é
ï¼token ç offset å®å
¨è½å¨ææ¬¡å¹é
åºé´å
å score è§ä¸º 0ã","For threshold xâ(0,1]: map normalized scores in [0,x] linearly to display intensities [0,1]; scores above x saturate at maximum intensity. At x=1, equivalent to disabling mapping.":"éå¼ xâ(0,1]ï¼å°å·²å½ä¸çåæ°å
1¨ [0,x] ä¸çº¿æ§æ å°å°æ¾ç¤ºå¼ºåº¦ [0,1]ï¼é«äº x ç忰饱å为æé«å¼ºåº¦ãx=1 æ¶ä¸å
³éæ å°çä»·ã","A â¤ï¸ would mean a lot!":"忬¢å°±ç¹ä¸ªâ¤ï¸å§ï¼","LLM à Linguistics à Information Theory":"大模å à è¯è¨å¦ à 信æ¯è®º",Add:"æ·»å ",Analyze:"åæ","Analyze & Upload":"åæå¹¶ä¸ä¼ ","Analyze&Upload":"åæå¹¶ä¸ä¼ ","Analyze URL":"åæ URL","Analyze URL content":"åæ URL å
容","Please enter a URL.":"请è¾å
¥ URLã","Invalid input":"è¾å
¥æ æ","Invalid URL":"URL æ æ","This does not look like a valid URL. Check for typos.":"è¿ä¸åææçç½åï¼è¯·æ£æ¥æ¯å¦è¾éã",Cancel:"åæ¶",Clear:"æ¸
空","Compare results":"对æ¯ç»æ","Compare analysis results":"对æ¯åæç»æ","Info Highlight / Compare":"Info Highlight ä¿¡æ¯é«äº® / 对æ¯",Compare:"对æ¯",Confirm:"ç¡®å®",Delete:"å é¤",Remove:"ç§»é¤","Move to top":"ç§»å°é¡¶é¨",Edit:"ç¼è¾",Enter:"è¿å
¥",Exit:"éåº","Finish editing":"宿ç¼è¾",Move:"ç§»å¨",OK:"ç¡®å®",Overwrite:"è¦ç",Paste:"ç²è´´","Cached completion not found":"æªæ¾å°è¯¥æ¡ç»åç¼åï¼å¯è½å·²è¢«å é¤","Cached completion not found (link may be expired)":"æªæ¾å°è¯¥æ¡ç»åç¼åï¼åäº«é¾æ¥å¯è½å·²è¿æï¼","Cached result not found":"æªæ¾å°è¯¥æ¡å½å ç¼åï¼å¯è½å·²è¢«å é¤","Cached result not found (link may be expired)":"æªæ¾å°è¯¥æ¡å½å ç¼åï¼åäº«é¾æ¥å¯è½å·²è¿æï¼","Cached run not found":"æªæ¾å°è¯¥æ¡çæç¼åï¼å¯è½å·²è¢«å é¤","Cached run not found (link may be expired)":"æªæ¾å°è¯¥æ¡çæç¼åï¼åäº«é¾æ¥å¯è½å·²è¿æï¼","Reset UI options":"éç½®çé¢é项","Restore DAG options, play speed, exclusions, etc. to defaults and clear saved preferences for those controls.":"å° DAG åæ°ãææ¾é度ãæé¤æ£åçæ¢å¤ä¸ºé»è®¤å¼ï¼å¹¶æ¸
é¤è¿äºæ§ä»¶çæ¬å°ä¿å项ã","Play speed":"ææ¾é度","Token stage":"éè¯èå°",Fullscreen:"å
¨å±","Exit fullscreen":"éåºå
¨å±",Refresh:"å·æ°",Pause:"æå","Step replay (â¶)":"æ¥è¿åæ¾ï¼â¶ï¼","Milliseconds at the reference max surprisal (18 bit; range 200â5000). Lower surprisal maps linearly down to 100ms. Saved locally; applied when you press play.":"åç
§æå¤§æè®¶åº¦ï¼18 bitï¼å¯¹åºçæ¯«ç§æ°ï¼200â5000ï¼ãæ´ä½æè®¶åº¦çº¿æ§æ å°å°æä½ 100msãæ¬å°ä¿åï¼ç¹å»ææ¾æ¶çæã","Simulate attention":"模æ attention","When checked, step replay (â¶) expands prompt and gen steps into attention scan + FFN animation. Requires step replay without Causal Flow focus. Saved locally.":"å¾éåï¼æ¥è¿éæ¾ï¼â¶ï¼å° prompt ä¸çææ¥å±å¼ä¸º attention æ«æ + FFN å¨ç»ãéå¨éå ææµæ¨¡å¼ä¸ä½¿ç¨ â¶ãæ¬å°ä¿åã","Skip prefill":"è·³è¿ prefill","When checked, multi-token uncached prep skips per-token query rounds; scan still follows query position in context. Saved locally.":"å¾éåï¼uncached å¤ token æ¶è·³è¿é token query 轮次ï¼scan ä»é query å¨ context ä¸çä½ç½®ååç¼ã","Prefill style":"Prefill æ ·å¼","Plain: sequential left-to-right scan per query. Random: shuffled query batches, random attend burst highlight, persistent query outlines. Saved locally.":"Plainï¼æ¯ä¸ª query éè½®ä»å·¦å°å³æ«æãRandomï¼ä¹±åº query æ¹å¤çãattend burst éæºé«äº®ãquery 夿¡æä¹
ãæ¬å°ä¿åã","Prefill burst":"Prefill burst","Random prefill only: parallel query tokens established per attend step (ms). Saved locally.":"ä»
Random prefillï¼æ¯æ attendï¼msï¼å¹¶è¡å»ºç«ç query æ°ãæ¬å°ä¿åã",Dwell:"åç","à attend":"à attend","ms attend":"ms attend","Dwell before and after each new gen token, as a multiple of one attend step (ms). Saved locally.":"æ¯ä¸ªæ° gen token åºç°ååçåçæ¶é´ï¼ä¸ºå次 attendï¼msï¼çåæ°ãæ¬å°ä¿åã","Milliseconds per attend step when Simulate attention is checked (step time mode). Saved locally.":"å¾é模æ attention ä¸ä¸º step time æ¨¡å¼æ¶ï¼æ¯æ¬¡ attend çæ¯«ç§æ°ãæ¬å°ä¿åã","Attend burst":"Attend burst","Tokens scanned in parallel per attend step (plain/gen scan) and random lit count per query. Saved locally.":"æ¯æ attend å¹¶è¡æ«è¿ç token æ°ï¼plain/gen scanï¼å random æ¯ query éæºé«äº®æ°ãæ¬å°ä¿åã","Hide arrows":"éèç®å¤´","When checked, DAG edges (arrows) stay hidden for the whole step replay (â¶) session while Simulate attention is enabled. Saved locally.":"å¾éåï¼å¨å¯ç¨ Simulate attention çæ¥è¿åæ¾ï¼â¶ï¼æ´åºæé´éè DAG è¾¹ï¼ç®å¤´ï¼ãæ¬å°ä¿åã","Disable smart step time":"ç¦ç¨æºè½æ¥é¿æ
1¶é´","When checked, propagation chain animation (â¯) uses a uniform interval per frame instead of scaling by attribution weight. DAG step replay (â¶) is unchanged. Saved locally; applied when you press play.":"å¾éåï¼ä¼ æé¾å¨ç»ï¼â¯ï¼å帧使ç¨ååé´éï¼ä¸åæå½å æé缩æ¾ï¼æ¥è¿éæ¾ï¼â¶ï¼ä¸åå½±åãæ¬å°ä¿åï¼ç¹å»ææ¾æ¶çæã","Lightning effect":"éªçµææ","When checked, forward propagation play (â¯) highlights propagation edges in peak contrast during the last-frame dwell (boundary frame à slow-mo). Extra wall time; not counted in Play speed total time. Saved locally; applied when you press play.":"å¾éåï¼æ£åä¼ æææ¾ï¼â¯ï¼å¨æ«å¸§ dwellï¼è¾¹ç帧 à æ
¢æ¾åæ°ï¼å
以峰å¼å¯¹æ¯åº¦é«äº®ä¼ æèè¾¹ãé¢å¤å¢éæ¶é´ï¼ä¸è®¡å
¥ææ¾éåº¦çæ»æ¶é¿ãæ¬å°ä¿åï¼ç¹å»ææ¾æ¶çæã","Lightning linear boost denominator Ï on render strength: opacity = min(1, strength / Ï). Lower Ï brightens more edges. Saved locally.":"éªçµçº¿æ§å¢å¼ºåæ¯ Ïï¼åºäºå½å render strengthï¼ï¼opacity = min(1, strength / Ï)ãÏ è¶å°è¶å¤è¾¹é¡¶æ»¡ãæ¬å°ä¿åã","Lightning slow-mo x":"éªçµæ
¢æ¾ x","Slows lightning dwell and animation rhythm by this factor (1â10). Saved locally; applied when you press play.":"ææ¤åæ°æ¾æ
¢éªçµ dwell ä¸å¨ç»èå¥ï¼1â10ï¼ãæ¬å°ä¿åï¼ç¹å»ææ¾æ¶çæã","Thunder sound":"é·å£°","When checked, forward propagation play (â¯) plays thunder strike and rumble with the lightning effect. Saved locally.":"å¾éåï¼æ£åä¼ æææ¾ï¼â¯ï¼å¨éªçµæææ¶ææ¾é·å»ä¸èæ¯é·é·ãæ¬å°ä¿åã","Auto zoom":"èªå¨ç¼©æ¾","Slide prompt in animation":"å¨ç»ä¸ slide æ«è¿ prompt","When checked, step replay (â¶) fits the viewport after each step (stops if you pan or zoom). Saved locally.":"å¾éåï¼æ¥è¿éæ¾ï¼â¶ï¼æ¯æ¥èªå¨éé
è§å£ï¼æå¨å¹³ç§»/缩æ¾å忢ï¼ãæ¬å°ä¿åã","Causal Flow Mode":"å ææµæ¨¡å¼","Unchecked: direct attribution â immediate predecessors only (default). Checked: Causal Flow Mode (â¯) â trace from the focused token back to information sources. Sources: prompt; surprising or teacher-forced generated tokens (MI decay stops the chain). Conduits: high-confidence middle tokensâattribution passes through. Blue edges: propagated share; node ring: attribution stay (strong where explanation lands). Use with Decay attribution to high-surprisal targets. On the DAG, ⯠plays the focus propagation chain; â¶ replays generation steps when no token is focused.":"æªå¾éï¼åå§ç´æ¥å½å ï¼ä»
ä¸è·³å驱ï¼é»è®¤ï¼ãå¾éï¼å ææµæ¨¡å¼ï¼â¯ï¼â ä»ç¦ç¹ token åä¸è¿½æº¯å°ä¿¡æ¯æ¥æºãæ¥æºï¼promptï¼é«æè®¶æ teacher-forced ççæ tokenï¼MI è¡°å坿ªæé¾ï¼ãä¼ å¯¼ï¼é«ç½®ä¿¡ä¸é´ tokenï¼å½å ç©¿è¿ãèè¾¹ï¼ä¼ æä»½é¢ï¼èç¹ç¯ï¼å½å åçï¼è§£éè½ç¹å¤æ´å¼ºï¼ã建议ä¸ãåé«æè®¶ç®æ è¡°åå½å ãé
å使ç¨ãDAG ä¸ï¼â¯ ææ¾ç¦ç¹ä¼ æé¾ï¼æ ç¦ç¹æ¶ â¶ æ¥è¿éæ¾çæè¿ç¨ã","Direction for focus-chain batch animation when you press propagation play (â¯) on the DAG with a focused token in Causal Flow Mode.":"å ææµæ¨¡å¼ä¸ï¼å¯¹å·²èç¦ token å¨ DAG ä¸æä¼ æææ¾ï¼â¯ï¼æ¶ï¼ç¦ç¹ä¼ æé¾åæ¹å¨ç»çæ¹åã","When checked, focus also shows outgoing edges as downstream influence (red). Direct mode: one hop. Causal Flow Mode: recursive â propagate as arrive à one-hop weight (sum at merges); display scales each sourceâs outs so strongest = arrive.":"å¾éåï¼ç¦ç¹ä¸é¢å¤æ¾ç¤ºä¸æ¸¸å½±ååºè¾¹ï¼çº¢ï¼ãç´æ¥æ¨¡å¼ï¼ä¸è·³ãå ææµæ¨¡å¼ï¼éå½ââä¼ æä¸º arrive à ä¸è·³è¾¹æï¼æ±åç¸å ï¼ï¼æ¾ç¤ºæ¶å°æ¯ä¸ªæºçåºè¾¹ç¼©æ¾å°æå¼º = arriveã","Total duration or per-step simulated cost. DAG step replay (â¶) divides evenly or uses a fixed per-token cost; propagation chain animation (â¯) scales each frame by attribution weight.":"æ»æ¶é¿æåæ¥æ¨¡æå¼éãDAG æ¥è¿éæ¾ï¼â¶ï¼ææ¥ååæåºå®åæ¥å¼éï¼ä¼ æé¾å¨ç»ï¼â¯ï¼æåå±å½å æéç¼©æ¾æ¯å¸§æ¨¡æå¼éã","Total seconds. DAG step replay (â¶) divi
1des evenly across steps; propagation chain (â¯) splits by layer weight. Saved locally; applied when you press play or select a focus node.":"æ»ç§æ°ãæ¥è¿éæ¾ï¼â¶ï¼å¨æ¥é´ååï¼ä¼ æé¾ï¼â¯ï¼æå±æéåé
ãæ¬å°ä¿åï¼ç¹å»å¯¹åºææ¾é®æéä¸ç¦ç¹èç¹æ¶çæã","Total seconds. With no focused token, DAG step replay (â¶) divides evenly; in Causal Flow Mode with a focused token, propagation play (â¯) runs focus-chain animation split by layer weight. Saved locally; applied when you press play.":"æ»ç§æ°ãæ ç¦ç¹æ¶æ¥è¿éæ¾ï¼â¶ï¼å¨æ¥é´ååï¼å ææµæ¨¡å¼ä¸å¯¹å·²èç¦ token æä¼ æææ¾ï¼â¯ï¼æ¶ï¼æå±æéè¿è¡ç¦ç¹ä¼ æé¾å¨ç»ãæ¬å°ä¿åï¼ç¹å»ææ¾æ¶çæã","Total seconds for weighted propagation frames. Lightning effect dwell at the end is extra wall time and not included. With no focused token, DAG step replay (â¶) divides evenly; in Causal Flow Mode with a focused token, propagation play (â¯) runs focus-chain animation split by layer weight. Saved locally; applied when you press play.":"å æä¼ æå¸§çæ»ç§æ°ãæ«å¸§éªçµææ dwell 为é¢å¤å¢éæ¶é´ï¼ä¸è®¡å
¥æ¤é¡¹ãæ ç¦ç¹æ¶æ¥è¿éæ¾ï¼â¶ï¼å¨æ¥é´ååï¼å ææµæ¨¡å¼ä¸å¯¹å·²èç¦ token æä¼ æææ¾ï¼â¯ï¼æ¶ï¼æå±æéè¿è¡ç¦ç¹ä¼ æé¾å¨ç»ãæ¬å°ä¿åï¼ç¹å»ææ¾æ¶çæã","Milliseconds per step. DAG step replay (â¶) uses this fixed interval; propagation chain (â¯) multiplies by layer weight. Saved locally; applied when you press play or select a focus node.":"æ¯æ¥æ¯«ç§æ°ãæ¥è¿éæ¾ï¼â¶ï¼ä½¿ç¨åºå®é´éï¼ä¼ æé¾ï¼â¯ï¼ä¹ä»¥å±æéãæ¬å°ä¿åï¼ç¹å»å¯¹åºææ¾é®æéä¸ç¦ç¹èç¹æ¶çæã","Milliseconds per step. DAG step replay (â¶) uses this as the 1à output-gen clock; with a focused token in Causal Flow Mode, propagation play (â¯) scales each batch by layer weight. Saved locally; applied when you press play.":"æ¯æ¥æ¯«ç§æ°ãæ¥è¿éæ¾ï¼â¶ï¼ä½ä¸º output gen ç 1à æ¶éï¼å ææµæ¨¡å¼ä¸å¯¹å·²èç¦ token æä¼ æææ¾ï¼â¯ï¼æ¶ï¼åæ¹æå±æéç¼©æ¾æ¨¡æå¼éãæ¬å°ä¿åï¼ç¹å»ææ¾æ¶çæã","Cached history":"åå²ç¼å","Cached demo":"示ä¾ç¼å","Demo not found":"æªæ¾å°è¯¥ç¤ºä¾ç¼å","No run to export":"å½åæ å¯å¯¼åºçè¿è¡ç»æ",History:"è¾å
¥åå²","Raw prompt":"åå§æç¤ºè¯","Raw prompt mode":"åå§æç¤ºè¯æ¨¡å¼","Enable thinking":"å¯ç¨æè模å¼","OpenRouter (custom)":"OpenRouterï¼èªå®ä¹ï¼","OpenRouter model":"OpenRouter 模å","OpenRouter API key":"OpenRouter API Key","Enter OpenRouter model id and API key (admin).":"请填å OpenRouter 模å ID ä¸ API Keyï¼ç®¡çåå®éªåè½ï¼ã","Tool use":"å·¥å
·ä½¿ç¨","Multi-turn":"å¤è½®","Config tools":"é
置工å
·","Add tool":"æ°å¢å·¥å
·",custom:"èªå®ä¹","custom, will not save":"èªå®ä¹ï¼æªå¾éä¸ä¼ä¿å","When Tool use is on, configure at least one tool in Config tools.":"å·²å¼å¯ Tool useï¼è¯·å
å¨ Config tools ä¸è³å°å¾éä¸ä¸ªå·¥å
·ã","Invalid tool_call JSON in model output":"模åè¾åºä¸ tool_call JSON æ æã","Tool calling reached max rounds ({max})":"Tool calling 已达æå¤§è½®æ°ï¼{max}ï¼ï¼å·²åæ¢ã","Teacher forcing":"Teacher forcing 强å¶ç»å","Stop after teacher forcing":"ç»åç»æå忢ï¼ä¸ç»§ç» top-1 çæï¼","When enabled, type the exact continuation after the assembled prompt. Each step attributes the next token toward that text (same tokenizer as Model), then stops when the continuation is consumed or EOS.":"å¯ç¨åï¼å¨ä¸æ¹å¡«åæ¥å¨ã宿´ promptãä¹åçææç»åææ¬ãæ¯ä¸æ¥ç¨è¯¥ä¸²å©ä½é¨åç第ä¸ä¸ª token ä½ä¸ºå½å ç®æ ï¼ä¸æé Model æ§½ä½åè¯å¨ä¸è´ï¼ï¼ç»åæ¶è´¹å®æéå° EOS æ¶ç»æã","Expected generated text after the full prompt. Each API step uses the first token of what remains here as the attribution target.":"æææ¨¡åå¨å®æ´ prompt ä¹åçæçæåï¼æ¯ä¸æ¥å¯¹å½åå©ä½ä¸²ç第ä¸ä¸ª token åå½å ç®æ ã","When unchecked, generation continues with top-1 after teacher forcing tokens are exhausted, up to Max tokens.":"æªå¾éæ¶ï¼teacher forcing ç»åç¨å®åå°ç»§ç»ä»¥ top-1 è´ªå¿çæï¼ç´å° Max tokens æ EOSã","When enabled, this text is appended to the assembled prompt (raw or chat template) before completion. GLTR colors apply only to newly generated tokens, not the appended suffix.":"å¯ç¨åï¼è¯¥ææ¬ä¼æ¼æ¥å°å·²ç»è£
ç promptï¼åå§æ chat 模æ¿ï¼ä¹åãåè°ç¨ completionãGLTR çè²ä»
ä½ç¨äºæ°çæç tokenï¼ä¸å
嫿¼æ¥çç»ååç¼ã","Text appended to the full prompt before calling /v1/completions. The suffix is part of the input, not model-generated output.":"è°ç¨ /v1/completions åæ¼æ¥å°å®æ´ prompt æ«å°¾çææ¬ï¼å±äºè¾å
¥çä¸é¨åï¼è鿍¡åçæç»æã",Ask:"æé®","Force retry":"强å¶éè¯",Retry:"éè¯","Fetch again without using cached result":"ä¸ä½¿ç¨ç¼åï¼éæ°åæå¡å¨è¯·æ±",Save:"ä¿å",Search:"æç´¢",Stop:"忢",Stopped:"已忢","EOS reached":"å·²å°è¾¾åºåç»æï¼EOSï¼","{count} tokens reached":"已达 {count} 个 token","Maximum length reached":"已达çæé¿åº¦ä¸é","Fullscreen unavailable":"å½åç¯å¢æ æ³ä½¿ç¨è¯¥å
¨å±åè½",Upload:"ä¸ä¼ ","Demo name:":"Demoåç§°ï¼","Enter folder name":"请è¾å
¥æä»¶å¤¹åç§°","Please enter demo name:":"请è¾å
¥demoåç§°ï¼","Folder name:":"æä»¶å¤¹åç§°ï¼","New name:":"æ°åç§°ï¼","Save directory:":"ä¿åç®å½ï¼","Target folder:":"ç®æ æä»¶å¤¹ï¼","Text content:":"ææ¬å
容ï¼","URL address:":"URL å°åï¼","Downloaded to local":"å·²ä¸è½½å°æ¬å°","File already exists":"æä»¶å·²åå¨",'File "{name}.json" already exists, overwrite?':'æä»¶ "{name}
1.json" å·²åå¨ï¼æ¯å¦è¦çï¼',Info:"æç¤º","Loading...":"å è½½ä¸...","No file selected":"æªéæ©æä»¶","Queuing...":"æéä¸...","Refreshing...":"æ£å¨å·æ°...",Success:"æå","Upload successful":"ä¸ä¼ æå","User cancelled save":"ç¨æ·åæ¶ä¿å","Demo path is missing":"缺å°demoè·¯å¾","Saved to local cache":"å·²ä¿åå°æ¬å°ç¼å","Storage quota exceeded, please clear cache and try again":"åå¨ç©ºé´ä¸è¶³ï¼è¯·æ¸
çç¼ååéè¯","Key is missing":"缺å°key","File not found in local cache, please open again":"æ¬å°ç¼å䏿ªæ¾å°è¯¥æä»¶ï¼è¯·éæ°æå¼","Failed to read from cache":"ä»ç¼å读å失败","Request failed, please try again later.":"请æ±å¤±è´¥ï¼è¯·ç¨åéè¯ã","File name cannot be empty":"æä»¶åä¸è½ä¸ºç©º","File name too long (max 255 characters)":"æä»¶åè¿é¿ï¼æå¤255个å符ï¼",'File name contains invalid characters (cannot contain < > : " | ? * or control characters)':'æä»¶åå
å«éæ³å符ï¼ä¸è½å
å« < > : " | ? * ææ§å¶å符ï¼',"File name cannot be a system reserved name":"æä»¶åä¸è½ä½¿ç¨ç³»ç»ä¿çåç§°","File name cannot start or end with a dot":"æä»¶åä¸è½ä»¥ç¹å¼å¤´æç»å°¾","File name cannot contain path separators":"æä»¶åä¸è½å
å«è·¯å¾åé符",Chinese:"䏿","Browser does not support IndexedDB, the following features will not be available:":"æµè§å¨ä¸æ¯æ IndexedDBï¼ä»¥ä¸åè½å°ä¸å¯ç¨ï¼","Local file cache (unable to cache local files to browser after opening)":"⢠æ¬å°æä»¶ç¼åï¼æå¼æ¬å°æä»¶åæ æ³ç¼åå°æµè§å¨ï¼","Other features (text analysis, server save, local file download, etc.) are still available.":"⢠å
¶ä»åè½ï¼ææ¬åæãæå¡å¨ä¿åãæ¬å°æä»¶ä¸è½½çï¼ä»ç¶å¯ç¨ã","Or configure HTTPS access":"æé
ç½®HTTPS访é®","Or: Configure HTTPS access":"æè
ï¼é
ç½®HTTPS访é®","Reason: Browser does not support or has disabled encryption API.":"åå ï¼æµè§å¨ä¸æ¯ææç¦ç¨äºå å¯APIã","Reason: Currently accessing via non-HTTPS non-localhost address, browser security policy has disabled encryption API.":"åå ï¼å½åéè¿éHTTPSçélocalhostå°å访é®ï¼æµè§å¨å®å
¨çç¥ç¦ç¨äºå å¯APIã","Reason: Opening page via file:// protocol, browser security policy has disabled encryption API.":"åå ï¼éè¿ file:// åè®®æå¼é¡µé¢ï¼æµè§å¨å®å
¨çç¥ç¦ç¨äºå å¯APIã","Restore local files after refresh (need to reselect files after refreshing the page)":"â¢ å·æ°åæ¢å¤æ¬å°æä»¶ï¼å·æ°é¡µé¢åéè¦éæ°éæ©æä»¶ï¼","Solution:":"è§£å³æ¹æ¡ï¼","Solution: Please access the application via http://localhost:port":"è§£å³æ¹æ¡ï¼è¯·éè¿ http://localhost:ç«¯å£ è®¿é®åºç¨","Recommended: Access via http://localhost:port (recommended)":"æ¨èï¼éè¿ http://localhost:ç«¯å£ è®¿é®ï¼æ¨èï¼","Use http://localhost:port to access (recommended)":"ä½¿ç¨ http://localhost:ç«¯å£ è®¿é®ï¼æ¨èï¼",Auto:"èªå¨",Dark:"æè²",Light:"亮è²","Language:":"è¯è¨ï¼","Minimap:":"æ»å¨æ¡ç¼©ç¥å¾ï¼",Settings:"设置",Theme:"主é¢","Theme:":"主é¢ï¼","Force narrow screen:":"强å¶çªå±ï¼","Toggle dark mode":"忢å¤é´æ¨¡å¼","Load text from URL and analyze":"ä»URLå è½½ææ¬å¹¶åæ","Open demo file from local":"仿¬å°æå¼demoæä»¶","Save to local file":"ä¿åå°æ¬å°æä»¶","Select local":"éæ©æ¬å°",'Are you sure you want to delete {type} "{name}"?':"ç¡®å®è¦å é¤{type}â{name}âåï¼","Confirm deletion":"确认å é¤",File:"æä»¶",Folder:"æä»¶å¤¹","More actions":"æ´å¤æä½","Move to...":"ç§»å¨å°...","New folder":"æ°å»ºæä»¶å¤¹",Rename:"éå½å","/(Root)":"/ï¼æ ¹ç®å½ï¼","/ (Root)":"/ï¼æ ¹ç®å½ï¼","This action cannot be undone.":"æ¤æä½ä¸å¯æ¤éã","Import Result":"导å
¥ç»æ","Diff Mode":"差忍¡å¼","Move left":"左移","Move right":"å³ç§»","Move to leftmost":"ç§»å°æå·¦","Move to rightmost":"ç§»å°æå³","No comparison data":"æ å¯¹æ¯æ°æ®","No demos to compare":"å½å没æå¯¹æ¯çdemo","Please select at least one demo":"请è³å°éæ©ä¸ä¸ªdemo","Please wait for all demos to load":"请çå¾
ææ demo å è½½å®æ","Refresh demo list":"å·æ°demoå表","Select Demo":"éæ©Demo","Select demo to add:":"éæ©è¦æ·»å çdemoï¼","Show Text Rendering":"æ¾ç¤ºææ¬æ¸²æ","This demo is already in the comparison list":"该demoå·²å¨å¯¹æ¯å表ä¸",'Demo "{name}" analyzed and uploaded successfully!':'Demo "{name}" åæå¹¶ä¸ä¼ æåï¼',"Exit multi-select mode":"éåºå¤é模å¼","Multi-select mode":"å¤é模å¼","No selection":"æªéæ©","Partial success":"é¨åæå","Please select items to delete first":"请å
éæ©è¦å é¤ç项","Please select items to move first":"请å
éæ©è¦ç§»å¨ç项","Select all":"å
¨é","Selected {count}":"å·²é {count}","Successfully deleted {count} items":"å·²æåå é¤ {count} 项","Successfully deleted {success} items, failed {fail} items":"æåå é¤ {success} 项ï¼å¤±è´¥ {fail} 项","Successfully moved {count} items":"å·²æåç§»å¨ {count} 项","Successfully moved {success} items, failed {fail} items":"æåç§»å¨ {success} 项ï¼å¤±è´¥ {fail} 项","Are you sure you want to delete the following {count}
1 items?":"ç¡®å®è¦å é¤ä»¥ä¸ {count} 项åï¼","Î bits/Byte":"Î æ¯ç¹/åè","Îinformation per byte histogram":"Îåèä¿¡æ¯éç´æ¹å¾","bits/Byte":"æ¯ç¹/åè","bits/token":"æ¯ç¹/token","information (bits)":"ä¿¡æ¯éï¼æ¯ç¹ï¼","information per byte histogram":"åèä¿¡æ¯éç´æ¹å¾","information per token histogram":"tokenä¿¡æ¯éç´æ¹å¾","information per token progress":"tokenä¿¡æ¯éè¿åº¦å¾","semantic match progress":"å¹é
度è¿åº¦å¾","chunk match degree":"chunkå¹é
度","token index":"tokenç´¢å¼","character offset":"å符åç§»","semantic score histogram":"è¯ä¹åæ°ç´æ¹å¾","signal prob":"signalæ¦ç","signal ratio":"ä¿¡å·æ¯","pw score":"pw åæ°","information density:":"ä¿¡æ¯å¯åº¦ï¼","pw score:":"pw åæ°ï¼","signal prob:":"signalæ¦çï¼","signal probability:":"ä¿¡å·æ¦çï¼","raw score normed:":"å½ä¸ååå§åæ°ï¼","Match: {0}%":"å¹é
度: {0}%","raw score:":"åå§åæ°ï¼","prob:":"æ¦çï¼","BPE overlap merge: overlapping spans were combined.":"BPE éå åå¹¶ï¼å·²åå¹¶éå åºé´ã","Digit merge: adjacent digit sub-tokens were combined.":"æ°ååå¹¶ï¼å·²åå¹¶ç¸é»æ°åå tokenã","information:":"ä¿¡æ¯éï¼","log perplexity:":"对æ°å°æåº¦ï¼","Top-k data not available.":"æªæä¾ Top-k æ°æ®ã","UTF-8 size:":"UTF-8大å°ï¼","Attribution share:":"å½å 份é¢ï¼","Attribution share (Total):":"å½å 份é¢ï¼æ»è®¡ï¼ï¼","Attribution share (Self):":"å½å 份é¢ï¼èªèº«ï¼ï¼",bytes:"åè",chars:"å符",model:"模å","index model":"ç´¢å¼æ¨¡å",tokens:"token","total information":"æ»ä¿¡æ¯é","or enter text:":"æè¾å
¥ææ¬ï¼","Quick start - select a demo:":"å¿«éå¼å§ - éæ©ç¤ºä¾ï¼","0 chars":"0 å符","total information = 0 bits":"æ»ä¿¡æ¯é = 0 æ¯ç¹","All files import failed:":"æææä»¶å¯¼å
¥å¤±è´¥ï¼","Analysis failed":"åæå¤±è´¥","Batch delete failed, please check console for details.":"æ¹éå é¤å¤±è´¥ï¼è¯·æ£æ¥æ§å¶å°è·å详ç»ä¿¡æ¯ã","Batch move failed, please check console for details.":"æ¹éç§»å¨å¤±è´¥ï¼è¯·æ£æ¥æ§å¶å°è·å详ç»ä¿¡æ¯ã","Cannot add demo, source text inconsistent with existing demos:":"æ æ³æ·»å ä»¥ä¸ demoï¼åæä¸å·²æ demo ä¸ä¸è´ï¼","Cannot enable model diff mode: current demos have inconsistent source text":"æ æ³å¯ç¨æ¨¡å差忍¡å¼ï¼å½å demo çåæä¸ä¸è´","Cannot find corresponding demo file path, unable to load.":"æ¾ä¸å°å¯¹åºç demo æä»¶è·¯å¾ï¼æ æ³å è½½ã","Delete failed":"å é¤å¤±è´¥","Delete failed, please check console for details.":"å é¤å¤±è´¥ï¼è¯·æ£æ¥æ§å¶å°è·å详ç»ä¿¡æ¯ã","Demo precheck failed:":"颿£æ¥ demo 失败:",Error:"é误","Error loading demos, please check console for details.":"å è½½ demos æ¶åºéï¼è¯·æ£æ¥æ§å¶å°è·å详ç»ä¿¡æ¯ã","Failed items:":"失败项ï¼","All files failed to read:":"æææä»¶è¯»å失败ï¼","Failed to add local file":"æ·»å æ¬å°æä»¶å¤±è´¥","Failed to create folder":"å建æä»¶å¤¹å¤±è´¥","Failed to read file":"æä»¶è¯»å失败","Partial files failed:":"é¨åæä»¶å¤±è´¥ï¼","Read failed":"读å失败","Failed to create folder, please check console for details.":"å建æä»¶å¤¹å¤±è´¥ï¼è¯·æ£æ¥æ§å¶å°è·å详ç»ä¿¡æ¯ã","Failed to get folder list, please check console for details.":"è·åæä»¶å¤¹å表失败ï¼è¯·æ£æ¥æ§å¶å°è·å详ç»ä¿¡æ¯ã","Failed to load folder list":"å è½½æä»¶å¤¹å表失败","Failed to load folder list: {message}":"å è½½æä»¶å¤¹å表失败: {message}","Failed to open file":"æå¼æä»¶å¤±è´¥","Failed to open IndexedDB":"æ æ³æå¼ IndexedDB","Failed to read clipboard, please paste manually":"æ æ³è¯»ååªè´´æ¿ï¼è¯·æå¨ç²è´´","Failed to refresh demo list, please check console for details.":"å·æ°demoå表失败ï¼è¯·æ£æ¥æ§å¶å°è·å详ç»ä¿¡æ¯ã","Failed to restore":"æ¢å¤å¤±è´¥","Failed to save to cache":"ä¿åå°ç¼å失败","File content is not a valid JSON object":"æä»¶å
容䏿¯ææçJSON对象","File download failed":"æä»¶ä¸è½½å¤±è´¥","File is not a valid JSON format":"æä»¶ä¸æ¯ææçJSONæ ¼å¼",'Invalid hash format: "{hash}", expected 4 hexadecimal characters':'æ æçåå¸å¼æ ¼å¼: "{hash}"ï¼åºä¸º4ä½åå
è¿å¶å符',"File opened, but cannot be saved to local cache due to browser security policy restrictions.":"æä»¶å·²æå¼ï¼ä½ç±äºæµè§å¨å®å
¨çç¥éå¶ï¼æ æ³ä¿åå°æ¬å°ç¼åã","Hash value missing":"åå¸å¼ç¼ºå¤±","Import failed":"导å
¥å¤±è´¥","Invalid URL format":"URLæ ¼å¼æ æ","Load failed":"å 载失败","Load failed: {message}":"å 载失败: {message}",'Local resource identifier missing hash: "{identifier}", format should be local://filename.json~hash':'æ¬å°èµæºæ è¯ç¬¦ç¼ºå°åå¸å¼: "{identifier}"ï¼æ ¼å¼åºä¸º local://filename.json~hash','Missing required "request" field':'缺å°å¿
éç"request"åæ®µ','Missing required "result" field':'缺å°å¿
éç"result"åæ®µ','Unable to extract local resource info: "{identifier}"':'æ æ³æåæ¬å°èµæºä¿¡æ¯: "{identifier}"',"Move failed":"ç§»å¨å¤±è´¥","Move failed, please check console for details.":"ç§»å¨å¤±è´¥ï¼è¯·æ£æ¥æ§å¶å°è·å详ç»ä¿¡æ¯ã","No data to save, please analyze text first":"没æå¯ä¿åçæ°æ®ï¼è¯·å
åæææ¬","Only refresh recovery of opened files is affected, other features work normally.":"ä»
å·²æå¼æä»¶çå·æ°æ¢å¤åå½±åï¼å
¶ä»åè½å坿£å¸¸ä½¿ç¨ã","Precheck failed":"颿£æ¥å¤±è´¥","Processing failed":"å¤ç失败","Rename failed":"éå½å失败","Rename failed, please check console for details.":"éå½å失败ï¼è¯·æ£æ¥æ§å¶å°è·å详ç»ä¿¡æ¯ã","Returned JSON missing valid bpe_strings array":"è¿å JSON 缺å°åæ³ç bpe_strings æ°ç»","Returned JSON missing valid bpe_strings array, processing cancelled.":"è¿å JSON 缺å°åæ³ç bpe_strings æ°ç»ï¼å·²åæ¶æ¬æ¬¡å¤çã","S
1ave failed":"ä¿å失败","Save failed: {message}":"ä¿å失败: {message}","Some demos failed to load":"é¨å Demo å 载失败","Some files import failed":"é¨åæä»¶å¯¼å
¥å¤±è´¥","Unable to extract text from URL":"æ æ³ä» URL æåææ¬","Unable to load project configuration, please check backend logs.":"æ æ³å 载项ç®é
ç½®ï¼è¯·æ£æ¥å端æ¥å¿ã","Unable to use encryption API (crypto.subtle), local cache save feature is unavailable.":"æ æ³ä½¿ç¨å å¯APIï¼crypto.subtleï¼ï¼ä¿åå°æ¬å°ç¼ååè½ä¸å¯ç¨ã","URL text extraction failed":"URL ææ¬æå失败","Semantic analysis failed":"è¯ä¹åæå¤±è´¥","Semantic Find":"è¯ä¹æ¥æ¾","Enter query question or topic":"请è¾å
¥æ¥è¯¢é®é¢æä¸»é¢","Semantic find":"è¯ä¹æ¥æ¾","Tokenizer results inconsistent: semantic and info-density token boundaries differ.":"Tokenizer ç»æä¸ä¸è´ï¼è¯ä¹åæä¸ä¿¡æ¯å¯åº¦ç token è¾¹çåå¨å·®å¼ï¼å±é¢æå¤æ
åµã","No data to analyze, please analyze text first":"没æå¯åæçæ°æ®ï¼è¯·å
åæææ¬","User cancelled file selection":"ç¨æ·åæ¶äºæä»¶éæ©","Missing required field: context":"ç¼ºå° context åæ®µ","context must be a string":"context 须为å符串","target_prediction must be a string":"target_prediction 须为å符串","target_prediction must not be empty":"target_prediction ä¸è½ä¸ºç©ºå符串","Missing required field: model":"ç¼ºå° model åæ®µ","model must be a string":"model 须为å符串",'model must be "base" or "instruct"':"model ä»
è½ä¸º base æ instruct","Gradient did not propagate; this model may not support attribution (e.g. int8 quantization).":"梯度æªåä¼ ï¼å¯è½æ¨¡å䏿¯æå½å ï¼å¦ int8 éåï¼","Unable to resolve context for this token":"æ æ³è§£æè¯¥ token çä¸ä¸æ","Completion response missing choices[0].text":"ç»åååºç¼ºå° choices[0].text","Response missing info_radar.bpe_strings":"ååºç¼ºå° info_radar.bpe_strings","completions/prompt response missing prompt_used":"completions/prompt ååºç¼ºå° prompt_used","... and {count} more items failed":"...è¿æ {count} 项失败","Source fragments ({count}):":"æ¥æºåçæ®µï¼å
± {count} 段ï¼ï¼","(+{n} more)":"ï¼å¦æ {n} 段æªååºï¼"}};function s(e){try{return localStorage.getItem(e)}catch{return null}}function a(e,t){try{localStorage.setItem(e,t)}catch{}}function r(e){try{localStorage.removeItem(e)}catch{}}function l(e,t,n){const i=n?.encoding??"true",o=s(e);return null===o?t:"1"===i?"1"===o:"true"===o}function c(e,t,n="true"){a(e,"1"===n?t?"1":"0":t?"true":"false")}let d="en";const h="app_language",u=s(h);function p(e){if("en"===d)return e;const t=o[d];return t&&t[e]?t[e]:e}function m(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function g(e,t){let n=p(e);for(const[e,i]of Object.entries(t)){const t=new RegExp(`\\{${m(e)}\\}`,"g");n=n.replace(t,String(i))}return n}"en"!==u&&"zh"!==u||(d=u),window.addEventListener("storage",e=>{if(e.key!==h)return;const t=e.newValue;"en"!==t&&"zh"!==t||location.reload()});function f(e){const{container:t,classPrefix:n,options:o,dataAttr:s,bodyClickNamespace:a,onSelect:r}=e,l=`${n}-dropdown-container`,c=`${n}-current-btn`,d=`${n}-dropdown-menu`,h=`${n}-option`;t.html("");const u=t.append("div").attr("class",`${l} settings-dropdown`),p=u.append("button").attr("class",`${c} settings-dropdown-btn`).attr("type","button"),m=u.append("div").attr("class",`${d} settings-dropdown-menu`);o.forEach(({value:e,html:t})=>{m.append("button").attr("class",`${h} ${h}-${e} settings-dropdown-option`).attr(s,e).attr("type","button").html(t).on("click",function(e){e.stopPropagation(),i.Ltv(this).classed("active")||(r(i.Ltv(this).attr(s)),f())})});let g=!1;const f=()=>{g=!1,m.classed("open",!1),p.classed("active",!1)};p.on("click",e=>{e.stopPropagation(),g?f():(g=!0,m.classed("open",!0),p.classed("active",!0))});const y=e=>{if(!g)return;const t=e.target,n=u.node();n&&!n.contains(t)&&f()};return setTimeout(()=>{document.addEventListener("click",y,!0)},0),{updateCurrent:e=>{const t=o.find(t=>t.value===e);t&&p.html(t.html),m.selectAll(`.${h}`).classed("active",function(){return i.Ltv(this).attr(s)===e})},dispose:()=>{document.removeEventListener("click",y,!0),t.selectAll("*").remove()}}}function y(e){return"auto"===e?window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dar
1k":"light":e}function v(){const e=s("theme-mode");if(e&&["light","dark","auto"].includes(e))return e;const t=s("theme");return"light"===t||"dark"===t?(r("theme"),t):"auto"}const b=[{lang:"en",label:"English"},{lang:"zh",label:"Chinese"}];class w{static basicURL(){const e=window.location.pathname.split("/").slice(0,-2).join("/");return window.location.origin+(e.length?e:"")}static get parameters(){const e=window.location.search.substring(1).split("&"),t={};return e.forEach(e=>{if(e.length>0){const i=e.split("="),o=decodeURIComponent(i[0]),s=decodeURIComponent(i[1]);t[o]=s.length<1?"":/^[0-9]+$/.test(n=s)?Number.parseInt(n,10):/^[0-9]+\.[0-9]*$/.test(n)?Number.parseFloat(n):n}var n}),t}static urlString(e){const t=[];Object.keys(e).forEach(n=>{const i=e[n];void 0!==i&&t.push(encodeURI(n+"="+i))});const n=window.location.pathname;let i=n.substring(n.lastIndexOf("/")+1);return t.length>0&&(i+="?"+t.join("&")),i}static updateURLParam(e,t,n=!0){const i=w.parameters;i[e]=t,w.updateUrl(i,n)}static updateUrl(e,t=!0){t?window.history.pushState(e,"",w.urlString(e)):window.history.replaceState(e,"",w.urlString(e))}}function k(e){const t=e.trim();return t?t.replace(/\/+$/,""):""}function x(){const e="undefined"!=typeof document?document.querySelector('meta[name="inforadar-api-base"]')?.getAttribute("content"):null;return function(e,t){const n=t?.trim();if(n)return k(n);if(null!=e){const t=String(e).trim();if(t)return k(t)}return""}(w.parameters.api,e)}function _(e,t){return`${void 0!==t?k(t):x()}${e.startsWith("/")?e:`/${e}`}`}const S="admin_token",C="is_admin_mode";class T{constructor(){this.adminToken=null,this.isAdminMode=!1,this.listeners=[];const e=s(S),t=s(C);e&&(this.adminToken=e),"true"===t&&(this.isAdminMode=!0)}static getInstance(){return T.instance||(T.instance=new T),T.instance}getAdminToken(){return this.adminToken}isInAdminMode(){return this.isAdminMode&&null!==this.adminToken}async setAdminToken(e){try{const t=await fetch(_("/api/check_admin"),{method:"POST",headers:{"Content-Type":"application/json","X-Admin-Token":e},body:JSON.stringify({token:e})}),n=await t.json();return n.success?(this.adminToken=e,this.isAdminMode=!0,a(S,e),a(C,"true"),{success:!0,message:n.message}):(this.clearAdminToken(),{success:!1,message:n&&"string"==typeof n.message?n.message:void 0})}catch(e){return console.error("éªè¯admin token失败:",e),this.clearAdminToken(),{success:!1,message:"Request failed, please try again later."}}}clearAdminToken(){this.adminToken=null,this.isAdminMode=!1,r(S),r(C)}onAdminModeChange(e){this.listeners.push(e)}notifyListeners(){const e=this.isInAdminMode();this.listeners.forEach(t=>t(e))}async setAdminTokenAndNotify(e){const t=await this.setAdminToken(e);return this.notifyListeners(),t}clearAdminTokenAndNotify(){this.clearAdminToken(),this.notifyListeners()}}T.instance=null;let M=0;class A{static simpleUId({prefix:e=""}){return M+=1,e+M}}function E(e){return"number"==typeof e&&Number.isFinite(e)}function R(e){return-Math.log2(Math.max(e,Number.EPSILON))}const L=new TextEncoder,I=e=>L.encode(e).length;function P(e){const[t,n]=e.real_topk;return function(e,t){const n=I(t);return n>0?e/n:0}(R(n),e.raw)}function O(e){const t=[];let n=0;for(let i=0;i<e.length;i++){t[i]=n;const o=e[i];n+=I(o)}return t[e.length]=n,t}function D(e){const{title:t,content:n,onConfirm:o,onCancel:s,confirmText:a=p("Confirm"),cancelText:r,loadingConfirmText:l=p("Queuing..."),width:c="clamp(300px, 90vw, 500px)",height:d}=e,h=o??(()=>{}),u=i.Ltv("body").append("div").attr("class","dialog-overlay"),m=u.append("div").attr("class","dialog").style("width",c);d&&m.style("height",d),m.append("div").attr("class","dialog-title").text(t);const g=m.append("div").attr("class","dialog-content"),f=m.append("div").attr("class","dialog-buttons");null!=r&&f.append("button").attr("class","dialog-button cancel").text(r).on("click",()=>{u.remove(),s&&s()});const y=null!=a?f.append("button").attr("class","dialog-button confirm").text(a):null,v=a??"",b=(e,t=!1)=>{const n=y?.node();n&&(n.disabled=!e||t,t?(n.setAttribute("data-state","queuing"),y.classed("queuing",!0),n.innerHTML=`\n <sp
1an class="queuing-text">${l}</span>\n <span class="queuing-spinner"></span>\n `):(n.setAttribute("data-state",e?"enabled":"disabled"),y.classed("queuing",!1),n.textContent=v))},w=n(g,b);y?.on("click",async()=>{if(w.validate&&!w.validate())return;const e=y?.node();if(e&&"queuing"===e.getAttribute("data-state"))return;const t=w.getValue?w.getValue():void 0;!1!==await h(t)&&u.remove()}),m.on("click",function(e){e.stopPropagation()});const k=e=>{e.isComposing||"Escape"===e.key&&(document.removeEventListener("keydown",k),u.remove(),s&&s())};return document.addEventListener("keydown",k),w.focus&&w.focus(),{setConfirmButtonState:b}}function F(e){return(t,n)=>(t.append("div").attr("class","dialog-message").text(e),{getValue:()=>!0,validate:()=>!0})}function N(e,t,n){D({title:e,content:F(t),onConfirm:()=>{n&&n()},confirmText:p("OK"),cancelText:void 0})}const $="info_radar_token_render_style";function H(){return"density"===s($)?"density":"classic"}function B(){const e=w.parameters.semantic_analysis;return"1"===e||"true"===e||1===e||!0===e}const z="info_radar_digits_merge_enabled",U=new Set;function q(e){try{e()}catch(e){console.error("[digitsMerge] render listener failed",e)}}function G(){for(const e of Array.from(U))q(e)}let W=!1;function j(){const e=s(z);return null===e||"true"===e}let V=null,K=null;const J="info_radar_force_narrow",Y="force-narrow-change",Z=()=>"1"===s(J),X=()=>{const e=document.documentElement;Z()?e.setAttribute("data-force-narrow",""):e.removeAttribute("data-force-narrow")};let Q=!1;const ee=()=>(null===K&&(null===V&&(V=(e=>{const t=document.documentElement,n=getComputedStyle(t).getPropertyValue(e).trim();if(!n)throw new Error(`CSS variable ${e} is not defined`);const i=parseInt(n,10);if(isNaN(i))throw new Error(`CSS variable ${e} is not a valid number: ${n}`);return i})("--breakpoint-mobile")),K=window.matchMedia(`(max-width: ${V}px)`)),K).matches||Z(),te=()=>{const e=document.getElementById("results");if(e){const t=getComputedStyle(e).overflowY;if("auto"===t||"scroll"===t)return e}return document.querySelector(".right_panel")};function ne(){const e=s("info_radar_semantic_match_threshold");if(null==e)return.1;const t=parseFloat(e);return Number.isFinite(t)&&t>=0&&t<=1?t:.1}const ie=Math.log2(262144);Math.log2(4);const oe=ie,se=.1*.7;function ae(e,t,n=.7){let i=Math.max(0,Math.min(1,e))*n;return null!=t&&(i=Math.max(t,i)),`rgba(255, 71, 64, ${i})`}function re(e,t){return e<0?0:e>=t?1:e/t}function le(e,t,n,i){return ae(re(e,n??oe),t,i)}function ce(e,t=1,n,i,o){return ae(re(e*t,i??6),n,o)}function de(e,t){return E(e)?ae(re(e,1),t):"transparent"}function he(e){let t;return t=e<=-10?-1:e>=10?1:e/10,function(e){const t=Math.max(-1,Math.min(1,e));if(0===t)return"rgba(0, 0, 0, 0)";if(t>0){const e="rgba(226, 74, 74, 0)",n="rgba(226, 74, 74, 1)";return i.GWP(e,n)(t)}{const e="rgba(115, 209, 61, 0)",n="rgba(115, 209, 61, 1)";return i.GWP(e,n)(Math.abs(t))}}(t)}const ue="info_radar_weaken_surprisal_color";function pe(){return l(ue,!1)}function me(){return pe()?.5:.7}const ge="%Y-%m-%dT%H:%M:%SZ",fe=[{value:"active_visits",label:"Active visits"},{value:"active_sec",label:"Active time"}];function ye(e,t){return e[t]??0}const ve=i.GYh(ge);function be(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function we(e){const[t,n,i]=e.split("-").map(e=>parseInt(e,10));return new Date(t,n-1,i)}function ke(e,t){return new Date(e.getFullYear(),e.getMonth(),e.getDate()+t)}function xe(e){return e.toLocaleString()}function _e(e){return e.toLocaleDateString()}const Se=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Ce(e){return e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function Te(e){return Se[e.getDay()]}function Me(e){return`${Te(e)} ${Ce(e)}`}function Ae(e,t){return"none"===t?"none":"day"===t?"day24":"hour"===e?"week168":"week7"}function Ee(e){return document.fullscreenElement===e}function Re(e){return i.aLc(ge)(i.pzD.floor(e))}function Le(e,t){const n=new Map;for(const i of e){const e=be(ve(i.hour));n.set(e,(n.get(e)??0)+ye(i,t))}return[...n.keys()].sort().map(e=>({day:e,value:n.get(e)}))}function Ie(e,t,n,o){const s=Ae(t,n);return"day24"===s?function(e,t){const n=new Array(24).fill(0);for(const i of e){const e=ve(i.hour);e&&(n[e.getHours()]+=ye(i,t))}const i=new Date(2e3,0,1);return n.map((e,t)=>({t:new Date(i.getFullYear(),i.getMonth(),i.getDate(),t),value:e}))}(e,o):"week168"===s?function(e,t){const n=new Array(168).fill(0);for(const i of e){const e=ve(i.hour);e&&(n[24*e.getDay()+e.getHours()]+=ye(i,t))}const i=new Date(2e3,0,2);return n.map((e,t)=>{const n=Math.floor(t/24),o=t%24;return{t:new Date(i.getFullYear(),i.getMonth(),i.getDate()+n,o),value:e}})}(e,o):"week7"===s?function(e,t){const n=new Array(7).fill(0);for(const{day:i,value:o}of Le(e,t))n[we(i).getDay()]+=o;const i=new Date(2e3,0,2);return n.map((e,t)=>({t:ke(i,t),value:e}))}(e,o):function(e,t,n){return"hour"===t?function(e,t){if(0===e.length)return[];const n=new Map(e.map(e=>[e.hour,ye(e,t)])),o=i.pzD.floor(ve(e[0].hour)),s=i.pzD.floor(ve(e[e.length-1].hour)),a=[];for(let e=o;e<=s;e=i.pzD.offset(e,1)){const t=Re(e);a.push({t:e,value:n.get(t)??0})}return a}(e,n):function(e){if(0===e.length)return[];const t=new Map(e.map(e=>[e.day,e.value]));let n=we(e[0].day);const i=we(e[e.length-1].day),o=[];for(let e=n;e<=i;e=ke(e,1)){const n=be(e);
1o.push({t:e,value:t.get(n)??0})}return o}(Le(e,n))}(e,t,o)}function Pe(e,t,n){const o=Ae(t,n);return"day24"===o||"week168"===o?function(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours()+1)}(e):"week7"===o?ke(e,1):"hour"===t?i.pzD.offset(e,1):ke(e,1)}function Oe(e,t,n,o,s,a,r){e.selectAll("*").remove();const l=Ie(t,o,s,n),c=function(e){return"active_sec"===e?"active time (s)":"active visits"}(n),d=Ae(o,s);if(0===l.length)return void e.append("p").style("margin","0").style("font-size","13px").text("No timeline data yet.");const h=e.node(),{width:u,height:p}=function(e,t){if(!t)return{width:560,height:220};const n=e.getBoundingClientRect(),i=Math.max(320,Math.floor(n.width)),o=Math.max(200,Math.floor(n.height));return i>0&&o>0?{width:i,height:o}:{width:Math.max(320,window.innerWidth-64),height:Math.max(200,window.innerHeight-120)}}(h,a),m=u-40-12,g=p-12-36,f=i.w7C().domain([l[0].t,Pe(l[l.length-1].t,o,s)]).range([0,m]),y=Math.min(l.length,16),v="day24"===d?e=>Ce(e):"week168"===d?e=>Me(e):"week7"===d?e=>Te(e):"hour"===o?e=>function(e){return 0===e.getHours()&&0===e.getMinutes()?_e(e):e.toLocaleString(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}(e):e=>_e(e),b=e.append("svg").attr("width",u).attr("height",p).attr("role","img").attr("aria-label","day24"===d?`${c} by hour of day (all dates summed, local time).`:"week168"===d?`${c} by hour within week (all weeks summed, local time).`:"week7"===d?`${c} by weekday (all weeks summed, local time).`:"hour"===o?`${c} per hour (local time). Drag to pan; Ctrl+wheel or fullscreen wheel to zoom; double-click to reset.`:`${c} per day (local time). Drag to pan; Ctrl+wheel or fullscreen wheel to zoom; double-click to reset.`).append("g").attr("transform","translate(40,12)"),w=b.append("g").attr("class","visit-stats-timeline-y"),k=b.append("g").attr("transform",`translate(0,${g})`).attr("class","visit-stats-timeline-x"),x=b.append("g").attr("class","visit-stats-timeline-plot");x.append("rect").attr("class","visit-stats-timeline-plot-bg").attr("width",m).attr("height",g).attr("fill","transparent");const _=x.append("g").attr("class","visit-stats-timeline-weekend-bg"),S=e.append("div").attr("class","visit-stats-timeline-tip").style("position","absolute").style("pointer-events","none").style("visibility","hidden").style("font-size","12px").style("padding","4px 8px").style("border-radius","4px").style("background","var(--panel-bg, rgba(0,0,0,0.75))").style("color","var(--text-color, #fff)");e.style("position","relative");const C="day24"===d?[]:l.filter(e=>function(e){const t=e.getDay();return 0===t||6===t}(e.t)),T=x.append("g").attr("class","visit-stats-timeline-bars");T.selectAll("rect.visit-stats-timeline-bar").data(l).join("rect").attr("class","visit-stats-timeline-bar").attr("fill","#22c55e").style("cursor","pointer").attr("opacity",e=>e.value>0?.85:.15).on("mouseenter",function(e,t){i.Ltv(this).attr("opacity",1),S.style("visibility","visible").html((e=>{const t=function(e,t){return"active_sec"===t?`${e}s`:`${e} ${1===e?"active visit":"active visits"}`}(e.value,n),i=Pe(e.t,o,s);return"day24"===d?`${Ce(e.t)} â ${Ce(i)} (all dates)<br/>${t}`:"week168"===d?`${Me(e.t)} â ${Me(i)} (all weeks)<br/>${t}`:"week7"===d?`${Te(e.t)} (all weeks)<br/>${t}`:"hour"===o?`${xe(e.t)} â ${xe(i)}<br/>${t}`:`${_e(e.t)}<br/>${t}`})(t))}).on("mousemove",e=>{const t=h.getBoundingClientRect();S.style("left",e.clientX-t.left+8+"px").style("top",e.clientY-t.top-28+"px")}).on("mouseleave",function(){const e=i.Ltv(this).datum();i.Ltv(this).attr("opacity",e.value>0?.85:.15),S.style("visibility","hidden")});const M=e=>{const t=(e=>{const t=l.filter(t=>((e,t)=>{const[n,i]=t.domain(),a=e.t.getTime();return Pe(e.t,o,s).getTime()>n.getTime()&&a<i.getTime()})(t,e)),n=i.T9B(t,e=>e.value)??1;return i.m4Y().domain([0,n]).nice().range([g,0])})(e),n=t.domain()[1]??1;k.call(i.l78(e).tickValues(e.ticks(y)).tickFormat(v)).selectAll("text").attr("transform","rotate(-24)").style("text-anchor","end"),w.call(i.V4s(t).ticks(Math.min(5,n+1)).tickFormat(i.GPZ("d"))).call(e=>e.select(".domain").remove()),_.selectAll("rect").data(C).join("rect").attr("x",t=>e(t.t)).attr("y",0).attr("width",t=>Math.max(1,e(Pe(t.t,o,s))-e(t.t))).attr("height",g).attr("fill","rgba(128, 128, 128, 0.14)").attr("pointer-events","none"),T.selectAll("rect.visit-stats-timeline-bar").attr("x",t=>e(t.t)).attr("width",t=>Math.max(1,e(Pe(t.t,o,s))-e(t.t)-1)).attr("y",e=>t(e.value)).attr("height",e=>g-t(e.value))},A=r.transform??i.GSI;if(M(A.rescaleX(f)),"day24"!==d&&"week7"!==d&&l.length>=2){const e=i.s_O().scaleExtent([1,48]).translateExtent([[0,0],[m,g]]).extent([[0,0],[m,g]]).filter(e=>function(e,t){return"wheel"===e.type?!(!t&&!e.ctrlKey||(e.preventDefault(),0)):!e.ctrlKey&&1!==e.button}(e,a)).on("zoom",e=>{x.attr("transform",null),r.transform=e.transform,M(e.transform.rescaleX(f))});x.style("cursor","grab").call(e).call(e.transform,A).on("dblclick.zoom",t=>{t.preventDefault(),r.transform=null,x.call(e.transform,i.GSI)})}}async function De(e){let t=[],n="active_visits",o="hour",s="none";const a={transform:null};let r=null,l=null,c=null;const d=()=>requestAnimationFrame(()=>{r&&l&&!l.empty()&&(Oe(l,t,n,o,s,Ee(r),a),c&&function(e,t){const n=Ee(t);e.text(n?"Ã":"â¶").attr("title",n?"Exit fullscreen":"Fullscreen")}(c,r))}),h=()=>{r&&Ee(r)&&d()};D({title:"Visits timeline",content:u=>{const p=i.Ltv(u.node().parentElement);r=p.node(),p.classed("visit-stats-timeline-dialog",!0);const m=u.append("div").attr("class","dialog-form-container dialog-form-container--fill"),g=m.append("div").attr("class","visit-stats-timeline-toolbar").style("display","flex").style("flex-wrap","wrap").style("align-items","center").style("gap","12px").style("margin","0 0 8px").style("font-size","13px"),f=g.append("select").attr("class","visit-stats-timeline-metric").style("width","fit-content");f.selectAll("option").data(fe).join("option").attr("value",e=>e.value).property("selected",e=>e.value===n).text(e=>e.label),g.append("span").text("per");const y=g.append("select").attr("class","visit-stats-timeline-granularity").style("width","fit-content");y.selectAll("option").data([{value:"hour",label:"Hour"},{value:"day",label:"Day"}]).join("option").attr("value",e=>e.value).property("selected",e=>e.value===o).text(e=>e.label);const v=g.append("label").style("display","inline-flex").style("align-items","center").style("gap","4px").style("cursor","pointer"),b=v.append("input").attr("type","checkbox").property("checked","day"===s);v.append("span").text("Sum to 1 day");
1const w=g.append("label").style("display","inline-flex").style("align-items","center").style("gap","4px").style("cursor","pointer"),k=w.append("input").attr("type","checkbox").property("checked","week"===s);w.append("span").text("Sum to 1 week");const x=()=>{const e="hour"===o;v.style("display",e?"inline-flex":"none"),e||"day"!==s||(s="none",b.property("checked",!1))};f.on("change",function(){n=this.value,a.transform=null,d()}),y.on("change",function(){o=this.value,a.transform=null,x(),d()});const _=e=>{"day"===e&&"hour"!==o&&(e="none"),s=e,b.property("checked","day"===e),k.property("checked","week"===e),x(),a.transform=null,d()};return b.on("change",function(){_(this.checked?"day":"none")}),k.on("change",function(){_(this.checked?"week":"none")}),x(),l=m.append("div").attr("class","visit-stats-timeline-chart"),l.append("p").style("margin","0 0 8px").style("font-size","13px").style("opacity","0.75").text("Loadingâ¦"),c=p.select(".dialog-buttons").insert("button",".dialog-button.cancel").attr("type","button").attr("class","dialog-button cancel visit-stats-timeline-fullscreen-btn").attr("title","Fullscreen").text("â¶").on("click",async function(){if(r){try{await async function(e){document.fullscreenElement!==e?(document.fullscreenElement&&await document.exitFullscreen(),await e.requestFullscreen()):await document.exitFullscreen()}(r)}catch{}d()}}),document.addEventListener("fullscreenchange",h),window.addEventListener("resize",h),(async()=>{try{const n=await e.getVisitStatsActiveVisitsTimeline();if(!n?.success)throw new Error(n?.error??"Failed to load timeline");t=(n.bins??[]).map(e=>({hour:e.hour,active_visits:e.active_visits??0,active_sec:e.active_sec??0})),a.transform=null,l.select("p").remove(),d()}catch(e){l.selectAll("*").remove();const t=e instanceof Error?e.message:String(e);l.append("p").style("margin","0").style("font-size","13px").text(`Failed to load timeline: ${t}`)}})(),{focus:()=>{}}},onCancel:()=>{document.removeEventListener("fullscreenchange",h),window.removeEventListener("resize",h),r&&document.fullscreenElement===r&&document.exitFullscreen()},cancelText:p("Exit"),confirmText:null,width:"clamp(360px, 94vw, 620px)"})}const Fe=["index.html","analysis.html","compare.html","chat.html","attribution.html","causal_flow.html"],Ne=["analyze","analyze_semantic","analyze_semantic__relevance","analyze_semantic__keywords","info_highlight_run","info_highlight_run__local","info_highlight_run__cloud","info_highlight_run__cached","info_highlight_run__cancelled","info_highlight_run__failed","chat","causal_flow","prediction_attribute","prediction_attribute__attribution.html","prediction_attribute__chat.html","prediction_attribute__analysis.html"],$e=["ios","android","windows","macos","linux","unknown"],He=["layout_linear_arc","layout_step_down","layout_spiral","layout_attribution_matrix","causal_flow","causal_flow_anim_backward","downstream","token_tooltip","tool_use"],Be={propagated:"causal_flow",propagated_anim_backward:"causal_flow_anim_backward"};function ze(e){const t={...e};for(const[e,n]of Object.entries(Be)){const i=t[e];i&&(t[n]=(t[n]??0)+i,delete t[e])}return t}const Ue={causal_flow:"Causal Flow Mode",causal_flow_anim_backward:"Causal Flow Mode / animation backward",layout_linear_arc:"DAG layout/linear_arc",layout_step_down:"DAG layout/step-down",layout_spiral:"DAG layout/spiral",layout_attribution_matrix:"DAG layout/matrix",downstream:"Show downstream influence",token_tooltip:"Show token tooltip",tool_use:"Tool use"};function qe(e,t){const n=new Set(e),i=Object.keys(t).filter(e=>(t[e]??0)>0),o=new Set(i);return[...e.filter(e=>o.has(e)),...i.filter(e=>!n.has(e)).sort()]}function Ge(e){const t=e<0?"-":"";let n=Math.abs(Math.floor(e));const i=Math.floor(n/3600);n%=3600;const o=Math.floor(n/60),s=n%60,a=[];return i&&a.push(`${i}h`),o&&a.push(`${o}m`),(s||0===a.length)&&a.push(`${s}s`),t+a.join(" ")}function We(e){return"number"==typeof e&&Number.isFinite(e)?String(e):"-"}function je(e){return e?`${We(e.total_tokens)} tokens<br/>prompt | completion = ${We(e.prompt_tokens)} | ${We(e.completion_tokens)} tokens`:null}function Ve(e,t){e.text(`${p("model")}: ${t}`)}function Ke(...e){return e.every(e=>!e.empty())}class Je{constructor(e){this.options=e,this.initialize()}initialize(){this.updateButtonStates();const e=this.options.textField.node();e&&e.addEventListener("input",()=>{this.updateButtonStates()}),this.options.clearBtn.on("click",()=>{this.handleClear()}),this.options.pasteBtn.on("click",async()=>{await this.handlePaste()})}updateButtonStates(){const e=this.options.textField.property("value")||"",t=e.length>0;if(this.options.clearBtn.classed("inactive",!t),!this.options.textCountValue.empty()){const t=(n=e,Array.from(n).length);this.options.textCountValue.text(t.toString())}var n}updateTextMetrics(e,t,n){const{metricBytes:i,metricChars:o,metricTokens:s,metricTotalSurprisal:a,metricUsage:r,metricModel:l,totalSurprisalFormat:c}=this.options;if(r&&!r.empty()){if(!l||l.empty()||!Ke(r,l))return;return function(e,t){const n=je(t??null);n?e.html(`<span class="text-metrics-api-usage">${n}</span>`):e.text("")}(r,n??null),void Ve(l,t)}i&&o&&s&&a&&l&&!l.empty()&&Ke(i,o,s,a,l)&&(e&&(function(e,t,n,i,o){e.text(`${i.byteCount} B`),t.text(`${i.charCount} ${p("chars")}`);const s=`${i.tokenCount} ${p("tokens")}`;let a;a=i.tokenCount>
10&&i.byteCount>0?`${s} (${(i.byteCount/i.tokenCount).toFixed(2)} B/t)`:s;const r=je(o??null);r?n.html(`${a}<br/><span class="text-metrics-api-usage">${r}</span>`):n.text(a)}(i,o,s,e,n),function(e,t,n){if(null!==t.totalSurprisal&&Number.isFinite(t.totalSurprisal)){const i=`${p("total information")} = ${n(t.totalSurprisal)} bits`;if(t.byteCount>0&&t.tokenCount>0){const o=t.totalSurprisal/t.byteCount,s=t.totalSurprisal/t.tokenCount;e.html(`${i}<br>${n(o)} bits/Byte, ${n(s)} bits/token`)}else if(t.byteCount>0){const o=t.totalSurprisal/t.byteCount;e.html(`${i}<br>${n(o)} bits/Byte`)}else e.text(i)}else e.text(`${p("total information")} = -- bits`)}(a,e,c)),Ve(l,t))}handleClear(){0!==(this.options.textField.property("value")||"").length&&(this.options.textField.property("value",""),this.options.textField.node()?.dispatchEvent(new Event("input",{bubbles:!0})))}async handlePaste(){try{const e=await navigator.clipboard.readText();if(e){const t=this.options.textField.property("value")||"",n=this.options.textField.node();if(n){const i=n.selectionStart||t.length,o=n.selectionEnd||t.length,s=t.substring(0,i)+e+t.substring(o);this.options.textField.property("value",s),n.setSelectionRange(i+e.length,i+e.length)}else this.options.textField.property("value",t+e);
1this.options.textField.node()?.dispatchEvent(new Event("input",{bubbles:!0}))}}catch(e){console.error("ç²è´´å¤±è´¥:",e),this.options.showAlertDialog(p("Info"),p("Failed to read clipboard, please paste manually"))}}getTextValue(){return this.options.textField.property("value")||""}setTextValue(e,t=!1){this.options.textField.property("value",e);const n=new Event("input",{bubbles:!0});n.isMatchingAnalysis=t,this.options.textField.node()?.dispatchEvent(n)}}class Ye{constructor(e){this.element=e,this.eventListeners=[]}bind(e,t){for(const n of e.split(" ")){this.eventListeners.push({eventName:n,eventFunction:t});const e=e=>t(e.detail,e);this.element.addEventListener(n,e,!1)}}getListeners(){return this.eventListeners}trigger(e,t){this.element.dispatchEvent(new CustomEvent(e,{detail:t}))}}const Ze="info_radar_semantic_result_cache";function Xe(e,t,n){return function(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}([e,t,n??""].join("\0"))}const Qe=new Map;let et=[];function tt(e,t,n,i){const o=Xe(e,t,i);if(Qe.has(o)){const e=et.indexOf(o);e>=0&&et.splice(e,1)}!function(){if(et.length<100)return;const e=et.shift();Qe.delete(e)}(),Qe.set(o,{...n,_query:t}),et.push(o),function(){const e={};for(const[t,n]of Qe)e[t]=n;const t=function(e,t){try{return void localStorage.setItem(e,t)}catch(e){return e}}(Ze,JSON.stringify({entries:e,keyOrder:et}));if(void 0===t)return;const n=t instanceof DOMException&&"QuotaExceededError"===t.name?"localStorage é
é¢å·²æ»¡ï¼Chrome 约 5MB/ååï¼ï¼å»ºè®®åå° MAX_SIZE ææ¸
çå
¶ä»ç«ç¹æ°æ®":String(t);console.warn("[semanticResultCache] æä¹
å失败ï¼å·æ°åç¼åå¯è½ä¸¢å¤±ãåå :",n)}()}function nt(e){return!!e?.__fromCache}!function(){try{const e=s(Ze);if(!e)return;const t=JSON.parse(e);if(!t?.entries||"object"!=typeof t.entries)return;Qe.clear();for(const[e,n]of Object.entries(t.entries))n&&"object"==typeof n&&Qe.set(e,n);et=Array.isArray(t.keyOrder)?t.keyOrder.filter(e=>Qe.has(e)).slice(-100):[...Qe.keys()]}catch{Qe.clear(),et=[]}}();class it{constructor(e=null){this.baseURL=e,this.adminToken=null,null==this.baseURL&&(this.baseURL=x())}url(e){return _(e,this.baseURL??"")}setAdminToken(e){this.adminToken=e}getHeaders(e){const t={"Content-type":"application/json; charset=UTF-8",...e};return this.adminToken&&(t["X-Admin-Token"]=this.adminToken),t}list_demos(e){const t=this.url("/api/list_demos")+(e?`?path=${encodeURIComponent(e)}`:"");return i.Pq9(t,{headers:this.getHeaders()})}load_demo_file(e){return i.Pq9(function(e){return function(e,t){return _(`/demo${t.startsWith("/")?t:`/${t}`}`,e)}(x(),e)}(e),{headers:this.getHeaders()})}save_demo(e,t,n="/",o=!1){return i.Pq9(this.url("/api/save_demo"),{method:"POST",body:JSON.stringify({name:e,data:t,path:n,overwrite:o}),headers:this.getHeaders()})}delete_demo(e){return i.Pq9(this.url("/api/delete_demo"),{method:"POST",body:JSON.stringify({file:e}),headers:this.getHeaders()})}move_demo(e,t){return i.Pq9(this.url("/api/move_demo"),{method:"POST",body:JSON.stringify({file:e,target_path:t}),headers:this.getHeaders()})}move_folder(e,t){return i.Pq9(this.url("/api/move_demo"),{method:"POST",body:JSON.stringify({path:e,target_path:t}),headers:this.getHeaders()})}rename_demo(e,t){return i.Pq9(this.url("/api/rename_demo"),{method:"POST",body:JSON.stringify({file:e,new_name:t}),headers:this.getHeaders()})}rename_folder(e,t){return i.Pq9(this.url("/api/rename_folder"),{method:"POST",body:JSON.stringify({path:e,new_name:t}),headers:this.getHeaders()})}delete_folder(e){return i.Pq9(this.url("/api/delete_folder"),{method:"POST",body:JSON.stringify({path:e}),headers:this.getHeaders()})}list_all_folders(){return i.Pq9(this.url("/api/list_all_folders"),{headers:this.getHeaders()})}create_folder(e,t){return i.Pq9(this.url("/api/create_folder"),{method:"POST",body:JSON.stringify({parent_path:e,folder_name:t}),headers:this.getHeaders()})}buildAnalyzePayload(e,t,n=null,i=!1){const o={model:e,text:t};return n&&(o.bitmask=n),i&&(o.stream=!0),o}analyze(e,t,n=null,o=!1,s){if(o)return this.analyzeWithProgress(e,t,s);const a=this.buildAnalyzePayload(e,t,n,o);return i.Pq9(this.url("/api/analyze"),{method:"POST",body:JSON.stringify(a),headers:{"Content-type":"application/json; charset=UTF-8"}}).then(e=>{if(e&&!1===e.success)throw new Error(e.message||"Analysis failed");return e})}fetchUrlText(e){return i.Pq9(this.url("/api/fetch_url"),{method:"POST",body:JSON.stringify({url:e}),headers:{"Content-type":"application/json; charset=UTF-8"}}).then(e=>{if(e&&!1===e.success)throw new Error(e.message||"URL text extraction failed");return e})}getVisitStats(){return i.Pq9(this.url("/api/visit_stats"),{headers:this.getHeaders()})}resetVisitStats(){return i.Pq9(this.url("/api/visit_stats/reset"),{method:"POST",headers:this.getHeaders()})}getVisitStatsActiveVisitsTimeline(){return i.Pq9(this.url("/api/visit_stats/active_visits_timeline"),{headers:this.getHeaders()})}getAvailableModels(){return i.Pq9(this.url("/api/available_models"))}getCurrentModel(){return i.Pq9(this.url("/api/current_model"))}switchModel(e,t,n){return i.Pq9(this.url("/api/switch_model"),{method:"POST",body:JSON.stringify({model:e,use_int8:t||!1,use_bfloat16:n||!1}),headers:this.getHeaders()})}async analyzeSemantic(e,t,n){const i=await this.analyzeSemanticRelevance(e,t,n);if(!i.success)return{success:!1,message:i.message,full_match_degree:0,token_attention:[]};if("number"!=typeof i.full_match_degree)throw new Error("Semantic relevance response missing full_match_degree");if(i.full_match_degree<ne())return{...i,token_attention:[]};const o=await this.analyzeSemanticKeywords(e,t,n);return o.success?{...o,full_match_degree:i.full_match_degree,__fromCache:nt(i)&&nt(o)}:{success:!1,message:o.message,full_match_degree:i.full_match_degree,token_attention:[]}}async analyzeSemanticRelevance(e,t,n){return this.fetchSemanticEndpoint("/api/analyze-semantic-relevance","relevance",e,t,n,e=>"number"==typeof e.full_match_degree)}async analyzeSemanticKeywords(e,t,n){return this.fetchSemanticEndpoint("/api/analyze-semantic-keywords","keywords",e,t,n,e=>Array.isArray(e.token_attention))}async fetchSemanticEndpoint(e,t,n,i,o,s){const{debug_info:a,signal:r}=o??{},l=function(e,t,n){const i=Xe(e,t,n),o=Qe.get(i);if(!o)return;const{_query:s,...a}=o;return a}(i,n,t);
1if(l&&s(l))return{...l,__fromCache:!0};const c={query:n,text:i};a&&(c.debug_info=!0);const d=await this.fetchSemanticJson(e,c,r);return d?.success&&tt(i,n,d,t),d}async fetchSemanticJson(e,t,n){const i=await fetch(this.url(e),{method:"POST",headers:this.getHeaders(),body:JSON.stringify(t),signal:n}),o=await i.json();if(o&&!1===o.success)throw new Error(o.message||"Semantic analysis failed");return o}analyzeWithProgress(e,t,n){return this.fetchSSEStream("/api/analyze",this.buildAnalyzePayload(e,t,null,!0),n,"Analysis failed")}fetchSSEStream(e,t,n,i,o){return new Promise((s,a)=>{let r=!1;const l=e=>{r||o?.aborted||(r=!0,s(e))},c=e=>{r||(r=!0,a(e))};fetch(this.url(e),{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(t),signal:o}).then(e=>{if(!e.ok)throw new Error(`HTTP error! status: ${e.status}`);const t=e.body.getReader();o?.addEventListener("abort",()=>t.cancel(),{once:!0});const s=new TextDecoder;let a="";const d=e=>{r||o?.aborted||this.processSSEMessage(e,n,l,c,i)},h=()=>t.read().then(({done:e,value:t})=>{if(r||o?.aborted)return;if(e)return void(a.trim()&&d(a));a+=s.decode(t,{stream:!0});const n=a.split("\n");a=n.pop()||"";for(const e of n)e.startsWith("data: ")&&d(e.slice(6));return h()});return h()}).catch(e=>{r||(r=!0,a(e))})})}processSSEMessage(e,t,n,i,o="Analysis failed"){try{const s=JSON.parse(e);if("progress"===s.type)t&&t(s.step,s.total_steps,s.stage,s.percentage);else if("result"===s.type){const e=s.data;e&&!1===e.success?i(new Error(e.message||o)):n(e)}else"error"===s.type&&i(new Error(s.message||o))}catch(e){const t=e instanceof SyntaxError?`Failed to parse SSE data: ${e.message} (backend may have returned invalid JSON, e.g. NaN)`:`Failed to process SSE message: ${e instanceof Error?e.message:String(e)}`;i(new Error(t))}}}const ot="online_count_value";let st;const at=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function rt(e){if("undefined"==typeof window)return;const t=T.getInstance(),n=_("/api/client-activity",e??void 0);let i=0,o=0;const s=e=>{const s=Math.max(i-o,0),a={page_path:location.pathname+location.search,total_active_sec:i,delta_active_sec:s},r=function(){if("undefined"==typeof document)return null;for(const e of document.cookie.split(";")){const t=e.indexOf("=");if(t<0)continue;if("il_aid"!==e.slice(0,t).trim())continue;let n=e.slice(t+1).trim();try{n=decodeURIComponent(n)}catch{}return at.test(n)?n.toLowerCase():null}return null}();r&&(a.client_id=r),e&&(a.client_os=function(){const e="undefined"!=typeof navigator&&navigator.userAgent||"";if(/iPad|iPhone|iPod/i.test(e))return"ios";if(/Android/i.test(e))return"android";const t="undefined"!=typeof navigator?navigator:void 0,n=t?.platform??"",i=t&&"number"==typeof t.maxTouchPoints?t.maxTouchPoints:0;return"MacIntel"===n&&i>1?"ios":/Win/i.test(e)?"windows":/Mac/i.test(e)?"macos":/Linux/i.test(e)?"linux":"unknown"}(),a.client_origin=location.hostname);const l={"Content-Type":"application/json"},c=t.isInAdminMode()?t.getAdminToken():null;c&&(l["X-Admin-Token"]=c),fetch(n,{method:"POST",headers:l,body:JSON.stringify(a),keepalive:!0}).then(e=>{(function(e){(e.headers.get("content-type")||"").includes("application/json")&&e.clone().json().then(e=>{e&&"online_now"in e&&function(e){const t=document.getElementById(ot);t&&(t.textContent="number"==typeof e&&Number.isFinite(e)?String(e):"â")}(e.online_now)}).catch(()=>{})})(e),e.ok&&(o=i)}).catch(()=>{})};window.setInterval(()=>{("undefined"!=typeof document&&"visible"===document.visibilityState||st?.())&&(i+=1,function(e){return 2===e||e%10==0}(i)&&s(2===i))},1e3)}const lt="info_radar_query_search_history";function ct(e,t,n){return t?!n:e}function dt(e,t){return!e||!t}function ht(e){try{const t=s(e);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)?n.map(e=>"string"==typeof e?e:e&&"string"==typeof e.query?e.query:null).filter(e=>"string"==typeof e).slice(0,100):[]}catch{return[]}}function ut(e,t){const n=ht(e).filter(e=>e!==t);a(e,JSON.stringify(n))}function pt(e,t=lt){const n=[e,...ht(t).filter(t=>t!==e)].slice(0,100);a(t,JSON.stringify(n))}function mt(e){const{input:t,dropdownId:n,onSelect:i,onHistorySelect:o,onRemove:s,onPromote:a,historyButton:r,storageKey:l=lt,openDropdownOnFocusInput:c=!0,filterHistoryByInput
1:d=!0,clickOutsideRoot:h=null,fillInputOnSelect:u=!0,closeOnSelect:m=!0,getHistoryItems:g,getHistoryEntries:f,refreshHistoryItems:y,applyHistoryOnHover:v=!1}=e,b=document.getElementById(n);if(!b)return;if(!t&&!r)return;if(!t&&c)return;const w=t?.closest(".semantic-search-input-wrapper")??r?.closest(".semantic-search-input-wrapper")??null,k=h??w,x=()=>b.classList.remove("is-visible"),_=()=>{const e=v&&"undefined"!=typeof window&&window.matchMedia("(hover: hover) and (pointer: fine)").matches,n=d&&t?(t.value??"").toLowerCase():"",i=t?(t.value??"").toLowerCase():null,r=null!=f,c=r?f():null,h=r?null:g?g():ht(l),y=c?c.filter(e=>{const t=e.label.toLowerCase();return(null===i||t!==i)&&(!n||t.includes(n))}):null,w=h?h.filter(e=>{const t=e.toLowerCase();return(null===i||t!==i)&&(!n||t.includes(n))}):null;if(b.innerHTML="",0!==(y??w??[]).length)if(b.classList.add("is-visible"),y){b.classList.toggle("has-featured-marks",c.some(e=>null!=e.featuredStyle));for(const n of y){const i=n.id,r=n.label,l=document.createElement("li"),c=document.createElement("span");c.className="bold"===n.featuredStyle?"history-text history-text--bold":"history-text",c.textContent=r,e||(c.title=r);let d=null;a&&(d=document.createElement("button"),d.className="demo-history-promote-btn",d.type="button",d.textContent="â",d.title=p("Move to top"),d.onclick=e=>{e.stopPropagation(),Promise.resolve(a?.(i)).then(()=>S())});const h=e=>{ct(m,v,e)&&x(),u&&t&&(t.value=r,t.dispatchEvent(new Event("input",{bubbles:!0}))),o?.(i,dt(v,e))};if(c.onclick=()=>h(!1),e&&c.addEventListener("pointerenter",()=>h(!0)),l.appendChild(c),d&&l.appendChild(d),s){const e=document.createElement("button");e.className="demo-delete-btn",e.type="button",e.textContent="Ã",e.title=p("Remove"),e.onclick=e=>{e.stopPropagation(),Promise.resolve(s(i)).then(()=>S())},l.appendChild(e)}b.appendChild(l)}}else for(const n of w){const i=document.createElement("li"),r=document.createElement("span");r.className="history-text",r.textContent=n,e||(r.title=n);let c=null;a&&(c=document.createElement("button"),c.className="demo-history-promote-btn",c.type="button",c.textContent="â",c.title=p("Move to top"),c.onclick=e=>{e.stopPropagation(),Promise.resolve(a?.(n)).then(()=>S())});const d=document.createElement("button");d.className="demo-delete-btn",d.type="button",d.textContent="Ã",d.title=p("Remove");const h=e=>{ct(m,v,e)&&x(),u&&t&&(t.value=n,t.dispatchEvent(new Event("input",{bubbles:!0}))),o?.(n,dt(v,e))};r.onclick=()=>h(!1),e&&r.addEventListener("pointerenter",()=>h(!0)),d.onclick=e=>{e.stopPropagation(),g||f||ut(l,n),Promise.resolve(s?.(n)).then(()=>S())},i.appendChild(r),c&&i.appendChild(c),i.appendChild(d),b.appendChild(i)}else x()},S=()=>{y?Promise.resolve(y()).then(_).catch(()=>_()):_()},C=t?w?.querySelector(".semantic-search-clear"):null,T=()=>C?.classList.toggle("is-visible",(t?.value??"").length>0);t&&(c&&t.addEventListener("focus",S),t.addEventListener("input",()=>{i(),c?t===document.activeElement&&S():d&&b.classList.contains("is-visible")&&S(),T()})),r?.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),t?.focus(),S()}),document.addEventListener("click",e=>{const t=e.target;r?.contains(t)||k&&!k.contains(t)&&x()}),C&&t&&(T(),C.addEventListener("click",()=>{t.value="",t.focus(),t.dispatchEvent(new Event("input",{bubbles:!0}))}))}const gt="content";function ft(e,t=gt,n){!function(e,t,n){try{const n=new URL(window.location.href);n.searchParams.delete(t),e&&n.searchParams.set(t,e),window.history.replaceState(null,"",n.toString())}catch(e){console.warn(`[${n}] URL sync failed:`,e)}}(e,t,n??"contentUrl")}function yt(e){return p(e)}Error;class vt{static translate({x:e,y:t}){return"translate("+e+","+t+")"}static group(e,t,n={x:0,y:0}){return e.append("g").attrs({class:t,transform:vt.translate(n)})}}class bt{constructor(e,t){this.id=A.simpleUId({}),this.parent=e,this.eventHandler=t||new Ye(this.parent.node()),this._visibility={hidden:!1}}superInitHTML(e={}){Object.keys(e).forEach(t=>this.options[t]=e[t]),this.base=this.parent.append("div").classed(this.css_name,!0)}superInitSVG(e={},t=["bg","main","fg"]){Object.keys(e).forEach(t=>this.options[t]=e[t]),this.layers={},this.base=vt.group(this.parent,this.css_name+" ID"+this.id,this.options.pos),t&&t.forEach(e
1=>{this.layers[e]=vt.group(this.base,e)})}update(e){this.data=e,this._visibility.hidden||(this.renderData=this._wrangle(e),this._render(this.renderData))}updateOptions(e,t=!1){Object.keys(e).forEach(t=>this.options[t]=e[t]),t&&this._render(this.renderData)}setHideElement(e){this._visibility.hideElement=e}hideView(){this._visibility.hidden||((this._visibility.hideElement||this.parent).transition().styles({opacity:0,"pointer-events":"none",display:"none"}),this._visibility.hidden=!0)}unhideView(){this._visibility.hidden&&((this._visibility.hideElement||this.parent).transition().styles({opacity:1,"pointer-events":null,display:null}),this._visibility.hidden=!1)}destroy(){this.base.remove()}}bt.events={noEvent:"VComponent_noEvent"};class wt{constructor(e={}){this.options={enabled:e.enabled??!0,batchSize:e.batchSize??32,delayBetweenBatches:e.delayBetweenBatches??8}}async renderWithAnimation(e,t,n,i,o){if(!this.options.enabled||0===e.length)return void e.forEach(e=>{i(e,t,n)});const s=e.length,a="function"==typeof this.options.batchSize?this.options.batchSize(s):this.options.batchSize;for(let o=e.length-1;o>=0;o--)i(e[o],t,n);let r=0,l=a;for(await new Promise(e=>setTimeout(e,this.options.delayBetweenBatches));r<e.length;){const t=[],n=Math.min(l,e.length-r);for(let i=0;i<n;i++)t.push(e[r+i]);this.animateBatch(t.map(e=>e.index),o),r+=n,r<e.length&&(await new Promise(e=>setTimeout(e,this.options.delayBetweenBatches)),l=Math.floor(1.5*l))}}animateBatch(e,t){t&&requestAnimationFrame(()=>{e.forEach(e=>{const n=t.querySelector(`[data-token-index="${e}"]`);if(n){const e=n.getAttribute("data-target-color");e&&(n.style.transition="none",n.style.backgroundColor=e)}})})}setEnabled(e){this.options.enabled=e}isEnabled(){return this.options.enabled}}const kt="bin-highlighted",xt="var(--accent-color, #1e6fff)";class _t{constructor(e,t,n){this.currentStyle="border",this.MAX_RETRY_ATTEMPTS=10,this.rectCacheWait={indices:0,interval:0},this.intervalUnderlineLines=[],this.svgOverlay=e,this.rectCache=t,this.underlineCache=n}setHighlightedIndices(e,t="border"){this.whenRectCacheReady("indices","HighlightManager: token é«äº®ç¼åæªå°±ç»ªï¼å·²è¾¾æå¤§éè¯",()=>{this.removeIntervalSvgLines(),this.currentStyle!==t&&this.clearPreviousStyle(this.currentStyle),this.currentStyle=t;const n=[];this.rectCache.forEach(({rect:i,tokenIndex:o},s)=>{const a=i.getAttribute("class")||"",r=e.has(o);"underline"===t?this.applyUnderlineHighlight(i,s,r,a):this.applyBorderHighlight(i,s,r,a,n)}),"border"===t&&n.length>0&&n.forEach(e=>{e.parentNode===this.svgOverlay&&this.svgOverlay.appendChild(e)})})}applyUnderlineHighlight(e,t,n,i){if(n){this.removeBorderStyle(e);let n=this.underlineCache.get(t);n||(n=this.createUnderline(t)),this.updateUnderlinePosition(e,n),this.updateHighlightClass(e,!0)}else{const n=this.underlineCache.get(t);n&&(n.style.display="none"),this.removeBorderStyle(e),this.updateHighlightClass(e,!1)}}applyBorderHighlight(e,t,n,i,o){if(n){const n=this.underlineCache.get(t);n&&(n.style.display="none"),e.setAttribute("stroke",xt),e.setAttribute("stroke-width","1.5"),e.setAttribute("stroke-opacity","1"),e.removeAttribute("stroke-dasharray"),this.updateHighlightClass(e,!0),o.push(e)}else{this.removeBorderStyle(e);const n=this.underlineCache.get(t);n&&(n.style.display="none"),this.updateHighlightClass(e,!1)}}clearHighlight(){this.cancelCharIntervalFade(),this.clearRectHighlightsOnly(),this.removeIntervalSvgLines()}clearTokenHighlights(){this.clearRectHighlightsOnly()}clearRectHighlightsOnly(){this.rectCache.forEach(({rect:e},t)=>{this.removeBorderStyle(e),this.updateHighlightClass(e,!1);const n=this.underlineCache.get(t);n&&(n.style.display="none")})}removeIntervalSvgLines(){for(const e of this.intervalUnderlineLines)e.remove();this.intervalUnderlineLines=[]}clearCharIntervalUnderlines(){this.cancelCharIntervalFade(),this.removeIntervalSvgLines()}cancelCharIntervalFade(){void 0!==this.charIntervalFadeTimeout&&(window.clearTimeout(this.charIntervalFadeTimeout),this.charIntervalFadeTimeout=void 0)}fadeOutCharIntervalUnderlines(e,t){this.cancelCharIntervalFade();const n=this.intervalUnderlineLines;if(0!==n.length){for(const e of n)e.style.transition="",e.setAttribute("stroke-opacity","1");requestAnimationFrame(()=>{for(const t of n)t.style.transition=`stroke-opacity ${e}ms ease-out`,t.setAttribute("stroke-opacity","0");this.charIntervalFadeTimeout=window.setTimeout(()=>{this.charIntervalFadeTimeout=void 0,this.removeIntervalSvgLines(),t?.()},e)})}else t?.()}setCharIntervalUnderlines(e){this.whenRectCacheReady("interval","HighlightManager: åºé´ä¸å线ç¼åæªå°±ç»ªï¼å·²è¾¾æå¤§éè¯",()=>{this.cancelCharIntervalFade(),this.clearRectHighlightsOnly(),this.removeIntervalSvgLines(),this.appendIntervalUnderlineLines(e)})}updateCharIntervalUnderlines(e){this.removeIntervalSvgLines(),this.appendIntervalUnderlineLines(e)}
1whenRectCacheReady(e,t,n){return this.rectCache.size>0?(this.rectCacheWait[e]=0,void n()):this.rectCacheWait[e]<this.MAX_RETRY_ATTEMPTS?(this.rectCacheWait[e]+=1,void setTimeout(()=>this.whenRectCacheReady(e,t,n),50)):(console.warn(t),void(this.rectCacheWait[e]=0))}static underlineStrokeAttrs(e,t){e.setAttribute("stroke",xt),e.setAttribute("stroke-width","2"),e.setAttribute("stroke-opacity","1"),e.setAttribute("class",t)}appendIntervalUnderlineLines(e){for(const t of e){const e=document.createElementNS("http://www.w3.org/2000/svg","line");_t.underlineStrokeAttrs(e,"chunk-interval-underline"),e.setAttribute("x1",String(t.x1)),e.setAttribute("x2",String(t.x2)),e.setAttribute("y1",String(t.y)),e.setAttribute("y2",String(t.y)),this.svgOverlay.appendChild(e),this.intervalUnderlineLines.push(e)}}clearPreviousStyle(e){"underline"===e?this.underlineCache.forEach(e=>{e.style.display="none"}):"border"===e&&this.rectCache.forEach(({rect:e})=>{this.removeBorderStyle(e)})}removeBorderStyle(e){e.removeAttribute("stroke"),e.removeAttribute("stroke-width"),e.removeAttribute("stroke-opacity"),e.removeAttribute("stroke-dasharray")}createUnderline(e){const t=document.createElementNS("http://www.w3.org/2000/svg","line");return _t.underlineStrokeAttrs(t,"bin-highlight-underline"),this.svgOverlay.appendChild(t),this.underlineCache.set(e,t),t}updateHighlightClass(e,t){const n=e.getAttribute("class")||"";if(t)n.includes(kt)||e.setAttribute("class",(n+" "+kt).trim());else{const t=n.replace(new RegExp(`\\b${kt}\\b`,"g"),"").trim();e.setAttribute("class",t)}}updateUnderlinePosition(e,t){const n=parseFloat(e.getAttribute("x")||"0"),i=parseFloat(e.getAttribute("y")||"0"),o=parseFloat(e.getAttribute("width")||"0"),s=i+parseFloat(e.getAttribute("height")||"0");t.setAttribute("x1",n.toString()),t.setAttribute("x2",(n+o).toString()),t.setAttribute("y1",s.toString()),t.setAttribute("y2",s.toString()),t.style.display=""}updateUnderlinePositions(){this.rectCache.forEach(({rect:e},t)=>{const n=this.underlineCache.get(t);n&&"none"!==n.style.display&&this.updateUnderlinePosition(e,n)})}}class St{constructor(e,t){this.rectCache=new Map,this.semanticOverlayCache=new Map,this.baseNode=e,this.options=t}createSvgOverlay(e,t){const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("class","svg-overlay");const i=this.baseNode.clientWidth||this.baseNode.offsetWidth||800,o=this.baseNode.clientHeight||this.calculateContainerHeight(e);return n.setAttribute("width",i.toString()),n.setAttribute("height",o.toString()),n.setAttribute("viewBox",`0 0 ${i} ${o}`),n.setAttribute("preserveAspectRatio","none"),n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.pointerEvents="none",n.style.zIndex="1",this.rectCache.clear(),this.semanticOverlayCache.clear(),this.groupPositionsByToken(e).forEach((e,i)=>{const o=this.createTokenGroup(n,e,i,t);n.appendChild(o)}),n}updateSvgPositions(e,t){const n=this.baseNode.clientWidth||0,i=this.baseNode.clientHeight||this.calculateContainerHeight(t);e.setAttribute("width",n.toString()),e.setAttribute("height",i.toString()),e.setAttribute("viewBox",`0 0 ${n} ${i}`),t.forEach(e=>{const t={x:Math.max(0,e.x),y:Math.max(0,e.y),width:Math.max(1,this.displayWidth(e)),height:Math.max(1,e.height)},n=this.rectCache.get(e.rectKey);n?.rect&&Object.entries(t).forEach(([e,t])=>n.rect.setAttribute(e,t.toString()));const i=this.semanticOverlayCache.get(e.rectKey);i&&Object.entries(t).forEach(([e,t])=>i.setAttribute(e,t.toString()))})}getRectCache(){return this.rectCache}getSemanticOverlayCache(){return this.semanticOverlayCache}appendTokenRects(e,t,n){this.groupPositionsByToken(e).forEach((e,i)=>{const o=this.createTokenGroup(t,e,i,n);t.appendChild(o)})}updateBaseRectColors(e,t){this.rectCache.forEach(({rect:n,tokenIndex:i},o)=>{const s=this.computeBaseRectColor(o,i,e,t);n.setAttribute("fill",s),n.setAttribute("data-target-color",s)})}updateSemanticColors(e,t=0){let n=0;for(let i=t;i<e.length;i++){const t=e[i],o=void 0!==t?de(t):"transparent";for(let e=0;;e++){const t=`${i}-${e}`,s=this.semanticOverlayCache.get(t);if(!s)break;s.setAttribute("fill",o),s.setAttribute("data-target-color",o),n++}}return n}
1clearRectCache(){this.rectCache.clear(),this.semanticOverlayCache.clear()}hasMissingRects(e){return e.some(e=>!this.rectCache.has(e.rectKey))||e.length!==this.rectCache.size}calculateContainerHeight(e){const t=this.baseNode.querySelector(".text-layer"),n=this.baseNode.getBoundingClientRect(),i=e.length>0?Math.max(...e.map(e=>e.y+e.height)):0;if(t){const e=t.getBoundingClientRect();return Math.max(e.height||0,i,this.baseNode.clientHeight||0)}return Math.max(i,this.baseNode.scrollHeight||0,this.baseNode.clientHeight||0,n.height||0,600)}groupPositionsByToken(e){const t=new Map;return e.forEach(e=>{t.has(e.tokenIndex)||t.set(e.tokenIndex,[]),t.get(e.tokenIndex).push(e)}),t}createTokenGroup(e,t,n,i){const o=document.createElementNS("http://www.w3.org/2000/svg","g");return o.setAttribute("data-token-index",n.toString()),o.setAttribute("class","token-group"),o.style.pointerEvents="auto",o.style.cursor="pointer",t.forEach(e=>{const t=this.createRect(e,n,i);o.appendChild(t);const s=this.options.semantic;if(s?.analysisMode){const t=this.createSemanticOverlayRect(e,n,i);o.appendChild(t)}}),this.options.addTokenEventListeners(o,n,i),o}computeBaseRectColor(e,t,n,i){const o=i?.disableInfoDensityRender??this.options.disableInfoDensityRender,s=i?.tokenRenderStyle??this.options.tokenRenderStyle??"classic";if(this.options.diff?.enabled&&this.options.diff.deltaByteSurprisals.length>0){const e=this.options.diff,i=n.bpe_strings[t].offset,o=i[0],s=i[1],a=e.charToByteIndexMap,r=e.deltaByteSurprisals,l=[];if(!a.length)return he(0);const c=a[o]??o,d=a[s]??s;for(let e=c;e<d&&e<r.length;e++)l.push(r[e]);return he(l.length>0?l.reduce((e,t)=>e+t,0)/l.length:0)}if(o)return"transparent";const a=n.bpe_strings[t],r=this.options.surprisalColorMax,l=me();if("classic"===s){const e=this.options.getTokenRealTopk(n,t);return le(null!=e?R(e[1]):0,void 0,r,l)}return ce(P(a),1,void 0,r,l)}createRect(e,t,n){const i=document.createElementNS("http://www.w3.org/2000/svg","rect");this.setRectGeometry(i,e),i.setAttribute("data-token-index",e.tokenIndex.toString()),i.setAttribute("data-fragment-index",e.fragmentIndex.toString()),i.setAttribute("data-rect-key",e.rectKey),this.rectCache.set(e.rectKey,{rect:i,tokenIndex:e.tokenIndex});const o=this.computeBaseRectColor(e.rectKey,e.tokenIndex,n);return i.setAttribute("fill",o),i.setAttribute("data-target-color",o),i.style.pointerEvents="auto",i}createSemanticOverlayRect(e,t,n){const i=document.createElementNS("http://www.w3.org/2000/svg","rect"),o=this.options.semantic.rawScoresNormed[t],s=void 0!==o?de(o):"transparent";return this.setRectGeometry(i,e),i.setAttribute("data-token-index",e.tokenIndex.toString()),i.setAttribute("data-fragment-index",e.fragmentIndex.toString()),i.setAttribute("data-rect-key",e.rectKey),i.setAttribute("fill",s),i.setAttribute("data-target-color",s),i.style.pointerEvents="auto",this.semanticOverlayCache.set(e.rectKey,i),i}setRectGeometry(e,t){const n=Math.max(0,t.x),i=Math.max(0,t.y),o=Math.max(1,this.displayWidth(t)),s=Math.max(1,t.height);e.setAttribute("x",n.toString()),e.setAttribute("y",i.toString()),e.setAttribute("width",o.toString()),e.setAttribute("height",s.toString()),e.setAttribute("rx","6"),e.setAttribute("ry","6")}displayWidth(e){return e.width>0?e.width:10}}class Ct{constructor(e){this.baseNode=e}getZoom(){return this.getAccumulatedZoom(this.baseNode)}getAccumulatedZoom(e){let t=1,n=e,i=0;for(;n&&i<50;){const e=window.getComputedStyle(n);if("string"==typeof e.zoom&&""!==e.zoom&&"normal"!==e.zoom){const i=parseFloat(e.zoom);!isNaN(i)&&i>0?t*=i:!isNaN(i)&&i<=0&&console.warn(`[TokenPositionCalculator] Invalid zoom value: ${e.zoom}`,n)}n=n.parentElement,i++}return i>=50&&console.warn("[TokenPositionCalculator] DOM depth exceeded 50, stopping zoom calculation"),t}calculateTokenPositions(e,t=0){if(!this.baseNode)return[];const n=[],i=this.baseNode.getBoundingClientRect(),o=this.getAccumulatedZoom(this.baseNode);return e.bpe_strings.map((e,t)=>({tokenObj:e,index:t,offset:e.offset})).filter(({index:e,offset:n})=>{if(e<t)return!1;const[i,o]=n;return!(i===o||i<0||o<0||o<=i)}).forEach(({tokenObj:e,index:t,offset:s})=>
1{const[a,r]=s,l=this.findNodeAndOffset(a),c=this.findNodeAndOffset(r);if(!l||!c)return void console.warn(`â ï¸ æ æ³æ¾å°token ${t} çä½ç½® (${a}, ${r})`);const d=document.createRange();d.setStart(l.node,l.offset),d.setEnd(c.node,c.offset);const h=Array.from(d.getClientRects()),u=h.length>0?h:[d.getBoundingClientRect()];u.forEach((e,s)=>{if(!e||0===e.height)return;const a=e.height/o;if(a<=0)return;const r=e.width/o,l={tokenIndex:t,fragmentIndex:s,fragmentCount:u.length,rectKey:`${t}-${s}`,x:(e.left-i.left)/o,y:(e.top-i.top)/o,width:r,height:a};n.push(l)})}),n}buildTextNodeIndex(){if(!this.baseNode)return void(this.textNodeIndex=void 0);const e=[];let t=0,n=0;const i=document.createTreeWalker(this.baseNode,NodeFilter.SHOW_TEXT,null);let o;for(;o=i.nextNode();){const i=o.textContent||"",s=Array.from(i),a=s.length,r=i.length,l=t,c=t+a,d=n,h=n+r,u=new Array(a+1);let p=0;for(let e=0;e<=a;e++)u[e]=p,e<a&&(p+=s[e].length);e.push({node:o,startOffset:l,endOffset:c,utf16Start:d,utf16End:h,charToUtf16Map:u}),t+=a,n+=r}this.textNodeIndex=e}findNodeAndOffset(e){if(!(this.textNodeIndex&&0!==this.textNodeIndex.length||(this.buildTextNodeIndex(),this.textNodeIndex&&0!==this.textNodeIndex.length)))return null;const t=this.textNodeIndex;let n=0,i=t.length-1,o=-1;for(;n<=i;){const s=Math.floor((n+i)/2),a=t[s];if(e>=a.startOffset&&e<a.endOffset){o=s;break}e<a.startOffset?i=s-1:n=s+1}if(-1===o&&t.length>0){const n=t[t.length-1];if(e===n.endOffset){o=t.length-1;const e=n.endOffset-n.startOffset,i=n.charToUtf16Map[e];return{node:n.node,offset:i}}return null}if(-1===o)return null;const s=t[o],a=e-s.startOffset,r=s.charToUtf16Map[a];return{node:s.node,offset:r}}resetIndex(){this.textNodeIndex=void 0}}class Tt{constructor(e,t){this.lastResizeTime=0,this.resizeEventCount=0,this.baseNode=e,this.options={rapidResizeThresholdMs:t.rapidResizeThresholdMs??100,rapidResizeCountThreshold:t.rapidResizeCountThreshold??3,resizeDebounceMs:t.resizeDebounceMs??100,onPositionUpdate:t.onPositionUpdate,getCurrentSvg:t.getCurrentSvg,onTransitionStart:t.onTransitionStart}}setup(){this.resizeObserver||(this.resizeObserver=new ResizeObserver(e=>{const t=Date.now();t-this.lastResizeTime<this.options.rapidResizeThresholdMs?this.resizeEventCount++:this.resizeEventCount=1,this.lastResizeTime=t,this.resizeEventCount>=this.options.rapidResizeCountThreshold?this.handleRapidResize():this.handleSingleResize()}),this.resizeObserver.observe(this.baseNode))}handleRapidResize(){const e=this.options.getCurrentSvg();e&&"0"!==e.style.opacity&&(e.style.opacity="0",e.style.pointerEvents="none"),this.options.onTransitionStart&&this.options.onTransitionStart(),void 0!==this.positionUpdateTimer&&(cancelAnimationFrame(this.positionUpdateTimer),this.positionUpdateTimer=void 0),void 0!==this.resizeEndTimer&&clearTimeout(this.resizeEndTimer),this.resizeEndTimer=window.setTimeout(()=>{this.resizeEventCount=0,this.options.onPositionUpdate();const e=this.options.getCurrentSvg();e&&(e.style.opacity="1",e.style.pointerEvents=""),this.resizeEndTimer=void 0},this.options.resizeDebounceMs)}handleSingleResize(){void 0!==this.resizeEndTimer&&(clearTimeout(this.resizeEndTimer),this.resizeEndTimer=void 0),void 0!==this.positionUpdateTimer&&cancelAnimationFrame(this.positionUpdateTimer),this.positionUpdateTimer=requestAnimationFrame(()=>{this.options.onPositionUpdate(),this.positionUpdateTimer=void 0})}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),void 0!==this.positionUpdateTimer&&(cancelAnimationFrame(this.positionUpdateTimer),this.positionUpdateTimer=void 0),void 0!==this.resizeEndTimer&&(clearTimeout(this.resizeEndTimer),this.resizeEndTimer=void 0)}}function Mt(e,t,n,i=2e3){let o=!1,s=0;const a=()=>{o||(o=!0,c(),n())},r=()=>{Math.abs((e===window?window.scrollY:e.scrollTop)-t)<1&&a()},l=()=>a(),c=()=>{s&&window.clearTimeout(s),e.removeEventListener("scroll",r),e.removeEventListener("scrollend",l)};return e.addEventListener("scroll",r,{passive:!0}),e.addEventListener("scrollend",l,{once:!0}),r(),o||(s=window.setTimeout(a,i)),()=>{o=!0,c()}}class At{constructor(e,t){this.container=e,this.options={width:12,...t},this.createPortal()}createPortal(){this.portal=document.createElement("div"),this.portal.className="surprisal-minimap-portal",this.portal.style.cssText="\n position: fixed;\n right: 0;\n top: 0;\n pointer-events: none;\n z-index: 1;\n ",this.canvas=document.createElement("canvas"),this.canvas.className="surprisal-minimap",this.canvas.style.cssText=`\n width: ${this.options.width}px;\n `,this.portal.appendChild(this.canvas),document.body.appendChild(this.portal)}hide(){this.portal.style.opacity="0"}updateMinimapLayout(){let e;if(this.canvas.width=this.options.width,this.canvas.style.width=`${this.options.width}px`,ee()){const t=document.documentElement.clientHeight;t?e=t:(e=window.innerHeight,console.warn("[ScrollbarMinimap] 使ç¨åå¤å¼ window.innerHeightï¼document.documentElement.clientHeight ä¸å¯ç¨",{clientHeight:t,innerHe
1ight:window.innerHeight,viewportHeight:e}))}else e=window.innerHeight;this.canvas.height=e,this.portal.style.top="0px"}async render(e,t,n={}){if(0===e.length)return void this.clear();this.portal.style.opacity="1",this.updateMinimapLayout();const i=this.canvas.getContext("2d");if(!i)return;let o;i.clearRect(0,0,this.canvas.width,this.canvas.height);let s,a=0;if(ee()){const e=this.canvas.height,t=document.body.scrollHeight;o=t/e;const n=this.container.getBoundingClientRect();a=window.scrollY+n.top}else{const e=this.canvas.height,t=this.container.querySelector(".text-layer").scrollHeight;o=t/e;const n=1;o=Math.max(n,o)}if(ee())s=document.body.scrollHeight;else{const e=this.container.querySelector(".text-layer");s=e?e.scrollHeight:0}const r=t.chunkInfos??[];if(n.semanticAnalysisMode)return void(r.length>0&&this.renderChunkMatchMinimap(i,r,a,o,n.measureCharRangeY));const l=e[0].height;let c;l>0?c=Math.floor((s-0)/l):(console.log("[ScrollbarMinimap] è¡é«åº¦ä¸º0ï¼è·³è¿bucketCount计ç®",{positions:e,lineHeight:l}),c=1/0);const d=Math.floor(this.canvas.height/2);c=Math.min(c,d);const h=(s-0)/c,u=Math.max(1,h/o),p=this.aggregateToBuckets(e,t,c,0,s),{buckets:m}=p;m.forEach(e=>{const t=ce(e.TokenFragmentCount>0?e.surprisalDensitySum/e.TokenFragmentCount:0,1.3,void 0,void 0,me());i.fillStyle=t;const n=(a+e.y)/o;i.fillRect(0,n,this.canvas.width,u)})}renderChunkMatchMinimap(e,t,n,i,o){let s=null,a=null;for(let r=0;r<t.length;r++){const l=t[r];if(!E(l.chunkMatchDegree))continue;const c=("chunkIndex"in l?l.chunkIndex:void 0)??r,d=o?.(l.startOffset,l.endOffset);if(!d)continue;const{minY:h,maxY:u}=d;if(!Number.isFinite(h)||!Number.isFinite(u)||u<=h)continue;const p=null==s?(n+h)/i:s,m=(n+u)/i-p,g=m<0?0:m,f=p+g;e.fillStyle=de(.4*l.chunkMatchDegree),e.fillRect(0,p,this.canvas.width,g),s=f,a=c}}aggregateToBuckets(e,t,n,i,o){if(0===e.length||o<=i)return{buckets:[]};const s=(o-i)/n,a=Array.from({length:n},(e,t)=>({y:i+t*s,surprisalDensitySum:0,TokenFragmentCount:0}));return e.forEach(e=>{const o=e.y+e.height/2,r=Math.floor((o-i)/s);if(r<0||r>=n)return;const l=a[r],c=P(t.bpe_strings[e.tokenIndex]);l.surprisalDensitySum+=c,l.TokenFragmentCount+=1}),{buckets:a}}updateOptions(e){this.options={...this.options,...e}}clear(){const e=this.canvas.getContext("2d");e&&e.clearRect(0,0,this.canvas.width,this.canvas.height),this.portal.style.opacity="0"}destroy(){this.clear(),this.portal.parentElement&&this.portal.parentElement.removeChild(this.portal)}}function Et(){const e=getComputedStyle(document.documentElement).getPropertyValue("--minimap-width").trim();if(!e)return console.warn("CSS åé --minimap-width æªå®ä¹ï¼ä½¿ç¨é»è®¤å¼ 12px"),12;const t=e.match(/^(\d+(?:\.\d+)?)px$/);return t?parseFloat(t[1]):(console.warn(`CSS åé --minimap-width æ ¼å¼æ æ: "${e}"ï¼ä½¿ç¨é»è®¤å¼ 12px`),12)}var Rt;!function(e){e[e.fract_p=0]="fract_p"}(Rt||(Rt={}));class Lt extends bt{getOverlayDisableInfoDensityRender(){return!!this.options.overlayForceDisableInfoDensityRender}getThemeMode(){return"dark"===document.documentElement.getAttribute("data-theme")?"dark":"light"}getCurrentAnalyzeResult(){const e=this.currentRenderData??this.renderData;return e?.bpe_strings?.length?e:null}notifyFullTextLayerRenderCompleteIfCurrent(e){e===this._renderVersion&&this.options.onFullTextLayerRenderComplete?.()}constructor(e,t,n={}){super(e,t),this._current={maxValue:-1,highlightedIndices:new Set,highlightStyle:"border",chunkCharRange:null,diffMode:!1,deltaByteSurprisals:[],charToByteIndexMap:[]},this.css_name="LMF",this.options={gltrMode:Rt.fract_p,diffScale:i.RWy().exponent(.3).range(["#b4e876","#fff"]),fracScale:i.m4Y().domain([0,15]).range(["#fff","#ff8080"]),enableRenderAnimation:!1,enableMinimap:!1,minimapWidth:Et(),semanticAnalysisMode:!1,surprisalColorMax:void 0,overlayTokenRenderStyle:void 0,overlayForceDisableInfoDensityRender:!1,onFullTextLayerRenderComplete:void 0},this.animationDelay=100,this._renderVersion=0,this.cachedPositionsTokenCount=0,this.cachedContainerWidth=0,this.underlineCache=new Map,this.playbackHoverIndex=null,this._refreshBaseRectColorsOrFullRender=()=>{if(this.svgOverlayManager&&this.currentRenderData){if(this.svgOverlayManager.getRectCache().size<this.currentRenderData.bpe_strings.length)return void this.reRenderCurrent(!0);this.svgOverlayManager.updateBaseRectColors(this.currentRenderData,{disableInfoDensityRender:this.getOverlayDisableInfoDensityRender(),tokenRenderStyle:this.options.overlayTokenRenderStyle??H()})}else this.reRenderCurrent(!0)},this._onTokenRenderStyleChange=()=>this._refreshBaseRectColorsOrFullRender(),this._onSurprisalColorWeakenChange=()=>{this._refreshBaseRectColorsOrFullRender(),this.options.enableMinimap&&this.cachedPositions&&this.currentRenderData&&this.renderMinimap(this.cachedPositions,this.currentRenderData).catch(e=>{console.error("Minimap渲æåºé:",e)})},this.superInitHTML(n),this._init(),this.animationDelay=100,this.renderAnimator=new wt({enabled:this.options.enableRenderAnimation,delayBetweenBat
1ches:this.animationDelay}),this.setupThemeListener(),window.addEventListener("token-render-style-change",this._onTokenRenderStyleChange),window.addEventListener("surprisal-color-weaken-change",this._onSurprisalColorWeakenChange),this.updateColorScales(),this.syncMinimapEnabledClass()}_init(){this.createLoadingOverlay()}createLoadingOverlay(){const e=this.base.node();if(!e)return;if(e.querySelector(".text-loading-overlay"))return;const t=document.createElement("div");t.className="text-loading-overlay",t.innerHTML='\n <div class="loading-content">\n <div class="loading-spinner"></div>\n </div>\n ',e.appendChild(t)}_render(e=this.renderData){if(e){if(this._renderVersion++,this.currentRenderData=e,this._current.diffMode&&this._current.deltaByteSurprisals.length>0){const t=e.originalText;this._current.charToByteIndexMap=O(t)}this.hideLoading(),this._renderWithSvgOverlay(e).catch(e=>{console.error("SVG渲æåºé:",e)})}}async _renderWithSvgOverlay(e){const t=this._renderVersion,n=e,i=n.rawScoresNormed,o=(n.colorScores?.length?n.colorScores:void 0)??i,s=this.options.semanticAnalysisMode&&o?.length,a=this.base.node(),r=!!this.currentSvgOverlay?.parentNode,l=Boolean(n.chunkInfos?.length),c=e.bpe_strings.length,d=this.cachedPositionsTokenCount,h=l&&c>d,u=c===d||h;if(s&&this.currentSvgOverlay&&r&&this.cachedPositions&&this.svgOverlayManager&&u&&e.originalText===this.cachedPositionsText&&null!=a&&a.clientWidth===this.cachedContainerWidth){if(this.updateGrayBoundary(e),this.positionCalculator?.resetIndex(),e.bpe_strings.length>this.cachedPositionsTokenCount){const t=this.cachedPositionsTokenCount,n=this.positionCalculator.calculateTokenPositions(e,t);this.svgOverlayManager.appendTokenRects(n,this.currentSvgOverlay,e),this.cachedPositions=[...this.cachedPositions??[],...n],this.cachedPositionsTokenCount=e.bpe_strings.length}const t=n.chunkInfos?.[n.chunkInfos.length-1],i=h&&t?Math.max(0,e.bpe_strings.findIndex(e=>e.offset[0]>=t.startOffset)):0;return this.svgOverlayManager.updateSemanticColors(o,i),this.cachedPositions&&this.cachedPositions.length>0&&await this.renderMinimap(this.cachedPositions,e),void this.applyPlaybackHoverClass()}if(this.clearVisualization(),this.setContainerText(e),await new Promise(e=>requestAnimationFrame(e)),await new Promise(e=>setTimeout(e,10)),t!==this._renderVersion)return;const p=this.base.node();if(!p)return;this.positionCalculator||(this.positionCalculator=new Ct(p));const m=e;let g=this.positionCalculator.calculateTokenPositions(m);if(s&&i?.length){const t=e.chunkInfos;t?.length||(g=g.filter(e=>void 0!==i[e.tokenIndex]))}if(0===g.length)return e.bpe_strings.length>0&&console.warn("â ï¸ æ²¡æææçtokenä½ç½®"),void this.notifyFullTextLayerRenderCompleteIfCurrent(t);const f={getTokenRealTopk:(e,t)=>this.getTokenRealTopk(e,t),addTokenEventListeners:(e,t,n)=>this.addTokenEventListeners(e,t,n),tokenRenderStyle:this.options.overlayTokenRenderStyle??H(),disableInfoDensityRender:this.getOverlayDisableInfoDensityRender(),diff:this._current.diffMode&&this._current.deltaByteSurprisals.length>0?{enabled:!0,deltaByteSurprisals:this._current.deltaByteSurprisals,charToByteIndexMap:this._current.charToByteIndexMap}:void 0,semantic:this.options.semanticAnalysisMode?{analysisMode:!0,rawScoresNormed:o}:void 0,surprisalColorMax:this.options.surprisalColorMax};this.svgOverlayManager=new St(p,f);const y=this.svgOverlayManager.createSvgOverlay(g,m);if(this.highlightManager=new _t(y,this.svgOverlayManager.getRectCache(),this.underlineCache),t!==this._renderVersion)return;this.currentSvgOverlay=y,p.appendChild(y),this.applyPlaybackHoverClass(),this.cachedPositions=g,this.cachedPositionsText=e.originalText,this.cachedPositionsTokenCount=e.bpe_strings.length,this.cachedContainerWidth=p.clientWidth,this.setupResizeHandler(),this.renderAnimator&&this.options.enableRenderAnimation&&await this.animateSvgRects(y,g);const v=this.renderAnimator&&this.options.enableRenderAnimation?200:0;if(this._current.chunkCharRange){const{x0:e,x1:t}=this._current.chunkCharRange;setTimeout(()=>this.setChunkCharRangeHighlight(e,t),v)}else this._current.highlightedIndices.size>0&&setTimeout(()=>{this.setHighlightedIndices(this._current.highlightedIndices,this._current.highlightStyle)},v);await this.renderMinimap(g,e),this.notifyFullTextLayerRenderCompleteIf
1Current(t)}async animateSvgRects(e,t){if(!this.renderAnimator)return;const n=t.length;let i=0,o=32;const s=this.svgOverlayManager?.getRectCache(),a=this.svgOverlayManager?.getSemanticOverlayCache();for(s&&s.forEach(({rect:e})=>e.setAttribute("fill-opacity","0")),a?.forEach(e=>e.setAttribute("fill-opacity","0")),await new Promise(e=>setTimeout(e,this.animationDelay));i<n;){const e=Math.min(o,n-i);for(let n=i;n<i+e;n++){const e=t[n].rectKey;s?.get(e)?.rect?.setAttribute("fill-opacity","1"),a?.get(e)?.setAttribute("fill-opacity","1")}i+=e,i<n&&(await new Promise(e=>setTimeout(e,this.animationDelay)),o=Math.floor(1.5*o))}}computeGrayBoundaryLength(e,t,n){if(n?.length)return n[n.length-1].endOffset;if(t?.length&&e.length>0){let n=-1;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e]){n=e;break}if(n>=0)return e[n].offset[1]}return e.length>0?e[e.length-1].offset[1]:0}updateGrayBoundary(e){const t=this.base.node();if(!t)return;const n=t.querySelector(".text-layer");if(!n)return;const i=e,o=this.computeGrayBoundaryLength(e.bpe_strings,i.rawScoresNormed,i.chunkInfos),s=e.originalText,a=o<s.length,r=n.firstChild;if(r&&r.nodeType===Node.TEXT_NODE){const e=a?s.slice(0,o):s;r.textContent!==e&&(r.textContent=e)}const l=n.querySelector(".gray-text"),c=a?s.slice(o):"";if(c)if(l)l.textContent!==c&&(l.textContent=c);else{const e=document.createElement("span");e.className="gray-text",e.textContent=c,n.appendChild(e)}else l&&l.remove()}setContainerText(e){const t=this.base.node();if(!t)return;for(;t.firstChild;)t.removeChild(t.firstChild);const n=e.originalText;if(!n)return void(t&&(this.positionCalculator?this.positionCalculator.resetIndex():this.positionCalculator=new Ct(t)));const i=document.createElement("div");i.className="text-layer",i.style.position="relative",i.style.zIndex="2";const o=e.bpe_strings,s=e.rawScoresNormed,a=e.chunkInfos,r=this.computeGrayBoundaryLength(o,s,a);if(r<n.length){i.appendChild(document.createTextNode(n.slice(0,r)));const e=document.createElement("span");e.className="gray-text",e.textContent=n.slice(r),i.appendChild(e)}else i.appendChild(document.createTextNode(n));t.appendChild(i),t&&(this.positionCalculator?this.positionCalculator.resetIndex():this.positionCalculator=new Ct(t))}applyPlainTextDom(e){const t=this.base.node();if(!t)return;this.clearHighlight(),this.options.enableMinimap&&this.minimapManager&&this.minimapManager.clear();const n=t.querySelector(".text-loading-overlay");for(;t.firstChild;)t.removeChild(t.firstChild);if(this.currentSvgOverlay=void 0,this.playbackHoverIndex=null,this.base.classed("playback-active",!1),this.cachedPositions=void 0,this.cachedPositionsText=void 0,this.cachedPositionsTokenCount=0,this.cachedContainerWidth=0,this.svgOverlayManager?.clearRectCache(),e){const n=document.createElement("div");n.className="text-layer",n.style.position="relative",n.style.zIndex="2";const i=document.createTextNode(e);n.appendChild(i),t.appendChild(n)}n?t.appendChild(n):this.createLoadingOverlay()}setTextOnly(e){this.applyPlainTextDom(e),this.showLoading()}showPlainText(e){this.currentRenderData=void 0,this.applyPlainTextDom(e),this.hideLoading(),i.Ltv("#all_result").style("opacity",1).style("display",null)}showLoading(){const e=this.base.node();if(!e)return;e.classList.add("loading");const t=e.querySelector(".text-loading-overlay");t&&t.classList.add("visible")}hideLoading(){const e=this.base.node();if(!e)return;e.classList.remove("loading");const t=e.querySelector(".text-loading-overlay");t&&t.classList.remove("visible")}clearVisualization(){const e=this.base.node();if(e){const t=e.querySelector(".svg-overlay");t&&t.remove(),this.currentSvgOverlay=void 0,this.cachedPositions=void 0,this.cachedPositionsText=void 0,this.cachedPositionsTokenCount=0,this.cachedContainerWidth=0,this.svgOverlayManager?.clearRectCache(),this.underlineCache.clear(),this.options.enableMinimap&&this.minimapManager&&this.minimapManager.clear(),e.querySelector(".text-loading-overlay")||this.createLoadingOverlay()}}setupResizeHandler(){if(this.resizeHandler)return;const e=this.base.node();e&&(this.resizeHandler=new Tt(e,{onPositionUpdate:()=>this.updateSvgPositions(),getCurrentSvg:()=>this.currentSvgOverlay,onTransitionStart:()=>{this.options.enableMinimap&&this.minimapManager&&this.minimapManager.hide()}}),this.resizeHandler.setup())}updateSvgPositions(){if(!this.currentSvgOverlay||!this.currentRenderData)return;const e=this.base.node();if(!e)return;this.positionCalculator||(this.positionCalculator=new Ct(e));const t=this.positionCalculator.calculateTokenPositions(this.currentRenderData);0!==t.length&&(this.svgOverlayManager&&!this.svgOverlayManager.hasMissingRects(t)?(this.svgOverlayManager.updateSvgPositions(this.currentSvgOverlay,t),this.cachedPositions=t,this.cachedPositionsText=this.currentRenderData.originalText,this.cachedPositionsTokenCount=this.currentRenderData.bpe_strings.length,this.cachedContainerWidth=e.clientWidth,this.highlightManager?.updateUnderlinePositions(),this.refreshChunkCharRangeUnderlines(),this.options.enableMinimap&&this.minimapManager&&this.renderMinimap(t,this.currentRenderData).catch(e=>{console.error("Minimap渲æåºé:",e)})):this._renderWithSvgOverlay(this.currentRenderData).catch(e=>{console.error("SVG渲æåºé:",e)}))}reRenderCurrent(e=!1){if(!this.currentRenderData)return;e&&(this.cachedPositions=void 0,this.cachedPositionsText=void 0,this.cachedPositionsTokenCount=0,this.cachedContainerWidth=0);const t=this.options.enableRenderAnimation;this.options.enableRenderAnimation=!1,this._render(this.currentRenderData),setTimeout(()=>{this.options.enableRenderAnimation=t},0)}updateColorScales(){const e=this.getThemeMode(),t="dark"===e?"#191919":"#fff";this.options.fracScale.range([t,"#ff8080"]);const n="dark"===e?"#191919":"#fff";this.options.diffScale.range(["#b4e876",n])}setupThemeListener(){new MutationObserver(e=>
1{e.forEach(e=>{"attributes"===e.type&&"data-theme"===e.attributeName&&this.updateColorScales()})}).observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]})}getTokenRealTopk(e,t){const n=e.bpe_strings[t];return n.real_topk?n.real_topk:void 0}addTokenEventListeners(e,t,n){const i=n.bpe_strings[t],o=()=>{const e=this.currentRenderData??n,o=e,s=o.rawScoresNormed,a=s?.length&&t<s.length;let r=function(e){const t="rawScoreNormed"in e&&"number"==typeof e.rawScoreNormed?e.rawScoreNormed:void 0;if(void 0!==t)return{rawScoreNormed:t}}(i);if(a&&s){const n=s[t],i=o.tokenRawScores?.[t],a=o.pPwValues?.[t],l=o.pwScores?.[t],c=e.bpeBpeMergedTokens?.[t]?.offset??e.bpe_strings[t]?.offset,d=e.chunkInfos,h=c&&d?.find(e=>c[0]>=e.startOffset&&c[0]<e.endOffset);r={...r,rawScoreNormed:n,rawScore:i,signalProb:a,pwScore:l,chunkIndex:h?.chunkIndex,chunkMatchDegree:h?.chunkMatchDegree}}return r};e.addEventListener("mouseenter",e=>{null==this.playbackHoverIndex&&(1&e.buttons||this.eventHandler.trigger(Lt.events.tokenHovered,{hovered:!0,d:{tokenData:i,semantic:o()},event:e}))}),e.addEventListener("mouseleave",e=>{null==this.playbackHoverIndex&&this.eventHandler.trigger(Lt.events.tokenHovered,{hovered:!1,d:{tokenData:i,semantic:void 0},event:e})}),e.addEventListener("mousedown",e=>{null==this.playbackHoverIndex&&0===e.button&&this.eventHandler.trigger(Lt.events.tokenHovered,{hovered:!1,d:{tokenData:i,semantic:void 0},event:e})}),e.addEventListener("click",e=>{0===e.button&&(e.stopPropagation(),this.eventHandler.trigger(Lt.events.tokenClicked,{tokenIndex:t}))})}async renderMinimap(e,t){this.options.enableMinimap&&(this.ensureMinimapManager(),this.minimapManager&&(0!==e.length?await this.minimapManager.render(e,t,{semanticAnalysisMode:this.options.semanticAnalysisMode,measureCharRangeY:(e,t)=>this.measureCharRangeY(e,t)}):this.minimapManager.clear()))}measureCharRangeY(e,t){const n=this.base.node();if(!n||t<=e)return null;const i=this.positionCalculator??new Ct(n),o=i.findNodeAndOffset(Math.max(0,e)),s=i.findNodeAndOffset(Math.max(0,t));if(!o||!s)return null;const a=document.createRange();a.setStart(o.node,o.offset),a.setEnd(s.node,s.offset);const r=n.getBoundingClientRect(),l=i.getZoom();let c=Number.POSITIVE_INFINITY,d=Number.NEGATIVE_INFINITY;for(const e of a.getClientRects()){if(0===e.width&&0===e.height)continue;const t=(e.top-r.top)/l,n=(e.bottom-r.top)/l;c=Math.min(c,t),d=Math.max(d,n)}return Number.isFinite(c)&&Number.isFinite(d)?{minY:c,maxY:d}:null}calculateTraditionalScrollbarWidth(){const e=this.base.node();if(!e)return 0;const t=te();if(!t)return 0;const n=t.offsetWidth-e.offsetWidth;return n>0?n:0}ensureMinimapManager(){const e=this.base.node();if(!e)return;let t=this.options.minimapWidth;if(!ee()){const e=this.calculateTraditionalScrollbarWidth();e>0&&(t=e),t>1&&(t-=1)}const n={width:t};this.minimapManager?this.minimapManager.updateOptions(n):this.minimapManager=new At(e,n)}syncMinimapEnabledClass(){const e=this.base.node();e&&e.classList.toggle("minimap-enabled",this.options.enableMinimap)}destroy(){this.resizeHandler&&(this.resizeHandler.destroy(),this.resizeHandler=void 0),this.minimapManager&&(this.minimapManager.destroy(),this.minimapManager=void 0),this.currentSvgOverlay=void 0,window.removeEventListener("token-render-style-change",this._onTokenRenderStyleChange),window.removeEventListener("surprisal-color-weaken-change",this._onSurprisalColorWeakenChange),super.destroy()}_wrangle(e){const t=e.bpe_strings.map(e=>e.pred_topk.length>0?e.pred_topk[0][1]:null).filter(e=>"number"==typeof e&&Number.isFinite(e));if(0===t.length)return this._current.maxValue=0,this.options.diffScale.domain([0,1]),e;const n=i.T9B(t);return this._current.maxValue=n??0,this.options.diffScale.domain([0,this._current.maxValue||1]),e}updateOptions(e,t=!1){e.hasOwnProperty("enableRenderAnimation")&&this.renderAnimator&&this.renderAnimator.setEnabled(e.enableRenderAnimation);const n=this.options.enableMinimap;if(super.updateOptions(e,t),e.hasOwnProperty("enableMinimap")){if(this.syncMinimapEnabledClass(),this.currentRenderData&&this.positionCalculator)if(this.options.enableMinimap&&!n){const e=this.positionCalculator.calculateTokenPositions(this.currentRenderData);e.length>0&&this.renderMinimap(e,this.currentRenderData).catch(e=>{console.error("Minimap渲æåºé:",e)})}else!this.options.enableMinimap&&n&&this.minimapManager&&(this.minimapManager.destroy(),this.minimapManager=void 0)}else if(this.options.enableMinimap&&this.minimapManager&&this.currentRenderData&&this.positionCalculator){const e=this.positionCalculator.calculateTokenPositions(this.currentRenderData);this.renderMinimap(e,this.currentRenderData).catch(e=>{console.error("Minimap渲æåºé:",e)})}}cancelChunkHighlightFade(){this.chunkScrollEndCancel?.(),this.chunkScrollEndCancel=void 0,void 0!==this.chunkHighlightHoldTimer&&(window.clearTimeout(this.chunkHighlightHoldTimer),this.chunkHighlightHoldTimer=void 0),this.highlightManager?.cancelCharIntervalFade()}setChunkCharRangeHighlight(e,t){const n=Math.max(0,Math.floor(e)),i=Math.max(0,Math.floor(t));if(i<=n)return this._current.chunkCharRange=null,void this.highlightManager?.clearCharIntervalUnderlines();if(this._current.chunkCharRange={x0:n,x1:i},this._current.highlightedIndices.clear(),!this.highlightManager)return void setTimeout(()=>this.setChunkCharRangeHighlight(n,i),50);const o=this.computeCharIntervalUnderlineSegments(n,i);this.highlightManager.setCharIntervalUnderlines(o)}scrollToChunkStart(e,t){this.scrollToUnicodeCharOffset(Math.max(0,Math.floor(e)),t)}jumpToChunkHighlight(e,t){this.cancelChunkHighlightFade(),this.setChunkCharRangeHighlight(e,t);const n=Math.max(0,Math.floor(e));this.scrollToChunkStart(n,()=>{this.chunkHighlightHoldTimer=window.setTimeout(()=>{this.chunkHighlightHoldTimer=void 0,this.fadeCurrentChunkHighlight()},200)})}fadeCurrentChunkHighlight(){if(!this._current.chunkCharRange||!this.highlightManager)return;this.highlightManager.fadeOutCharIntervalUnderlines(1400,()=>{this._current.chunkCharRange=null})}static clientRectToUnderlineSeg(e,t,n){return{x1:(e.left-t.left)/n,x2:(e.right-t.left)/n,y:(e.bottom-t.top)/n}}computeCharIntervalUnderlineSegments(e,t){const n=this.base.node();if(!n)throw new Error("[GLTR_Text_Box] chunk ä¸å线ï¼ç¼ºå° base èç¹");if(t<=e)return[];const i=this.positionCalculator??new Ct(n),o=i.findNodeAndOffset(e),s=i.findNodeAndOffset(t);if(!o||!s)throw new Error(`[GLTR_Text_Box] chunk ä¸åçº¿ï¼æ æ³å°
1 Unicode åå¼åºé´ [${e}, ${t}) æ å°å°ææ¬èç¹`);const a=document.createRange();a.setStart(o.node,o.offset),a.setEnd(s.node,s.offset);const r=n.getBoundingClientRect(),l=i.getZoom(),c=e=>Lt.clientRectToUnderlineSeg(e,r,l),d=[];for(const e of a.getClientRects())0===e.width&&0===e.height||d.push(c(e));if(0===d.length)throw new Error(`[GLTR_Text_Box] chunk ä¸å线 [${e}, ${t})ï¼Range.getClientRects() æªäº§ç任使æç©å½¢ï¼ä¸åå
å´çåéï¼`);return d}refreshChunkCharRangeUnderlines(){const e=this._current.chunkCharRange;e&&this.highlightManager&&this.highlightManager.updateCharIntervalUnderlines(this.computeCharIntervalUnderlineSegments(e.x0,e.x1))}scrollToUnicodeCharOffset(e,t,n=.2){this.chunkScrollEndCancel?.(),this.chunkScrollEndCancel=void 0,requestAnimationFrame(()=>{const i=this.base.node();if(!i)return void t?.();const o=this.positionCalculator??new Ct(i),s=Math.max(0,Math.floor(e)),a=o.findNodeAndOffset(s);if(!a)return void t?.();const r=document.createRange();r.setStart(a.node,a.offset),r.collapse(!0);let l=r.getBoundingClientRect();if(0===l.width&&0===l.height){const e=r.getClientRects();if(!e.length)return void t?.();l=e[0]}if(ee()){const e=window.scrollY+l.top-window.innerHeight*n,i=Math.max(0,(document.scrollingElement||document.documentElement).scrollHeight-window.innerHeight),o=Math.max(0,Math.min(e,i));return window.scrollTo({top:o,behavior:"smooth"}),void(t&&(this.chunkScrollEndCancel=Mt(window,o,t)))}const c=te();if(!c)return void t?.();const d=c.getBoundingClientRect(),h=l.top-d.top+c.scrollTop-c.clientHeight*n,u=Math.max(0,c.scrollHeight-c.clientHeight),p=Math.max(0,Math.min(h,u));c.scrollTo({top:p,behavior:"smooth"}),t&&(this.chunkScrollEndCancel=Mt(c,p,t))})}setHighlightedIndices(e,t="border"){this.cancelChunkHighlightFade(),this._current.chunkCharRange=null,this._current.highlightedIndices=e,this._current.highlightStyle=t,this.highlightManager?this.highlightManager.setHighlightedIndices(e,t):setTimeout(()=>{this.setHighlightedIndices(e,t)},50)}clearHighlight(e){const t=!0===e?.preserveChunkInterval;t||(this.cancelChunkHighlightFade(),this._current.chunkCharRange=null),this._current.highlightedIndices.clear(),this.highlightManager&&(t?this.highlightManager.clearTokenHighlights():this.highlightManager.clearHighlight())}getTokenGroupElement(e){const t=this.currentSvgOverlay;return t?t.querySelector(`g.token-group[data-token-index="${e}"]`):null}setPlaybackHoverToken(e){this.playbackHoverIndex=e,this.base.classed("playback-active",null!=e),this.applyPlaybackHoverClass()}applyPlaybackHoverClass(){const e=this.currentSvgOverlay;e&&(e.querySelectorAll("g.token-group.token-playback-hover").forEach(e=>{e.classList.remove("token-playback-hover")}),null!=this.playbackHoverIndex&&this.getTokenGroupElement(this.playbackHoverIndex)?.classList.add("token-playback-hover"))}ensureTokenVisible(e){this.getTokenGroupElement(e)?.scrollIntoView({block:"nearest",inline:"nearest",behavior:"auto"})}setDiffMode(e,t=[]){if(this._current.diffMode=e,this._current.deltaByteSurprisals=t,this.currentRenderData){const e=this.currentRenderData.originalText;this._current.charToByteIndexMap=O(e);const t=this.options.enableRenderAnimation;this.options.enableRenderAnimation=!1,this._render(this.currentRenderData),setTimeout(()=>{this.options.enableRenderAnimation=t},100)}}}function It(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function Pt(e){if(function(e){return/\p{White_Space}/u.test(e)}(e))return!1;const t=e.codePointAt(0);return void 0!==t&&(t>=32&&t<=126||t>=160&&t<=255||t>=256&&t<=383||t>=384&&t<=591||t>=8192&&t<=8303||t>=8304&&t<=8351||t>=8352&&t<=8399||t>=8448&&t<=8527||t>=8592&&t<=8703||t>=8704&&t<=8959||t>=8960&&t<=9215||t>=9216&&t<=9279||t>=11776&&t<=11903||t>=12288&&t<=12351||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=19968&&t<=40959||t>=44032&&t<=55215||t>=63744&&t<=64255||t>=65280&&t<=65519)}function Ot(e){return It(function(e,t){let n=e.replace(/\r\n/g,"[CRLF]").replace(/\n/g,"[LF]").replace(/\r/g,"[CR]").replace(/\t/g,"[TAB]").replace(/\u3000/g,"[FS]");n=!0===t?.spaceDotExceptBeforeAsciiLetterOrNumber?n.replace(/ (?![A-Za-z0-9])/g,"·"):n.replace(/ /g,"·");const i=[];let o=!1;for(let e=0;e<n.length;e++){const s=n[e];if("["===s)o=!0,i.push(s);else if("]"===s&&o)i.push(s),o=!1;else if(o)i.push(s);else if(" "===s)i.push(s);else if(Pt(s))i.push(s);else{const e=s.codePointAt(0);void 0!==e?i.push(!0===t?.omitHexInCodePointLabel?"[]":`[${e.toString(16).toLowerCase().padStart(4,"0")}]`):i.push(s)}}return i.join("")}(e))}function Dt(e){return Ot(e)}function Ft(e){return It(e)}function Nt(e){return i.GPZ(".3g")(100*e)+"%"}Lt.events={tokenHovered:"lmf-view-token-hovered",tokenClicked:"lmf-view-token-clicked"};const $t="\0__TOPK_SEP__\0";function Ht(e,t){if(null!=e&&""!==e&&null!=t&&Number.isFinite(t))return{token:e,prob:t}}function Bt(e,t){if(!t||!e.length)return e;const{token:n,prob:i}=t;return""!==n&&Number.isFinite(i)?(s=n,a=i,(o=e).length&&""!==s&&Number.isFinite(a)?o.some(e=>e.token===s)?o:[...o,{token:$t,prob:0},{token:s,prob:a}]:o):e;var o,s,a}function zt(e,t){if(!e.length)return"";const n=t?.maxBarWidth??60,o=t?.numFormat??Nt,s=i.m4Y().domain([0,1]).range([0,n]),a=t?.barCellWidth??110,r=!0===t?.interactivePickable,l=function(e,t,n){if(void 0===t||""===t)return-1;if(null!=n&&Number.isFinite(n)){const i=e.findIndex(e=>e.token!==$t&&e.token===t&&function(e,t){if(e===t)return!0;const n=Math.abs(e-t);return n<1e-12||n/Math.max(Math.abs(e),Math.abs(t),1e-15)<1e-9}(e.prob,n));if(i>=0)return i}return e.findIndex(e=>e.token!==$t&&e.token===t)}(e,t?.selectedToken,t?.selectedProb);return e.map((e,t)=>{if(e.token===$t)return'<div class="row topk-chart-row topk-chart-row--ellipsis">â®</div>';const n=["row","topk-chart-row",r?"topk-chart-row--pickable":"",l>
1=0&&t===l?"topk-chart-row--selected":""].filter(Boolean).join(" "),i=`<div class="topk-chart-bar-cell" style="width:${a}px;"><span class="topk-chart-bar-fill" style="width: ${s(e.prob)}px;"></span> <span class="topk-chart-prob">${o(e.prob)}</span></div>`,c=`<div class="topk-chart-token-cell">${Ot(e.token)}</div>`;return`<div class="${n}"${r?` data-topk-pick="${encodeURIComponent(e.token)}"`:""}>${i}${c}</div>`}).join("")}function Ut(e){const t=e.pred_topk??[],n=null!=e.real_topk&&Array.isArray(e.real_topk)&&1===e.real_topk[1]&&0===t.length;return{predTopk:t,isPlaceholderTopk:n,hasRealTopk:null!=e.real_topk&&Array.isArray(e.real_topk)&&!n}}function qt(e,t,n){const i=!1!==e.valueColor?n:t;return`<span style="color: ${t}">${e.label}</span> <span style="color: ${i}">${e.value}</span>`}class Gt{constructor(e,t,n){this.parent=e,this.eh=t,this.numF=i.GPZ(".3f"),this.significantF=i.GPZ(".3g"),this.themeColors={selectedColor:"#933",detailColor:"#666666",valueColor:"#333"},this.pendingUpdate=null,this.pendingData=null,this.themeObserver=null,this.surprisalRowLabel=n?.surprisalRowLabel??p("information:"),this.placement=n?.placement??"anchor",this.pointerInteractive=n?.pointerInteractive??!0,this.pointerInteractive||this.parent.classed("tooltip-no-pointer-hit",!0);const o=this.parent.node();o&&"parent-bottom-right"===this.placement&&(o.style.position="absolute"),this._init(),this._setupThemeObserver(),this._updateThemeColors()}_init(){this.predictions=this.parent.select(".predictions"),this.myDetail=this.parent.select(".myDetail"),this.currentToken=this.parent.select(".currentToken"),this.pointerInteractive&&(this.parent.on("click",e=>{e.stopPropagation(),e.preventDefault(),this.visibility=!1}),this.parent.on("touchstart",e=>{e.stopPropagation(),e.preventDefault(),this.visibility=!1}))}_setupThemeObserver(){this.themeObserver=new MutationObserver(()=>{this._updateThemeColors()}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]})}_updateThemeColors(){const e="dark"===document.documentElement.getAttribute("data-theme"),t=getComputedStyle(document.documentElement).getPropertyValue("--text-color-light").trim()||"#e0e0e0";this.themeColors={selectedColor:e?"#ff6666":"#933",detailColor:e?"#888":"#666666",valueColor:e?t:"#333"}}_getViewportInfo(){return window.visualViewport?{width:window.visualViewport.width,height:window.visualViewport.height,offsetTop:window.visualViewport.offsetTop||0,offsetLeft:window.visualViewport.offsetLeft||0}:{width:window.innerWidth,height:document.documentElement.clientHeight||window.innerHeight,offsetTop:0,offsetLeft:0}}_resolveAnchorRectElement(e){if(!(e&&e instanceof Element))return null;let t=e;if(t instanceof SVGRectElement)return t;if(t instanceof SVGGElement)return t.querySelector("rect");for(;t;){if(t instanceof SVGRectElement)return t;if(t instanceof SVGGElement){const e=t.querySelector("rect");if(e)return e}t=t.parentElement}return null}dispose(){this.themeObserver&&(this.themeObserver.disconnect(),this.themeObserver=null),null!==this.pendingUpdate&&(cancelAnimationFrame(this.pendingUpdate),this.pendingUpdate=null)}hideAndReset(){const e=this.parent.node();null!==this.pendingUpdate&&(cancelAnimationFrame(this.pendingUpdate),this.pendingUpdate=null),this.pendingData=null,this.visibility=!1,e&&("parent-bottom-right"===this.placement?this._placeParentBottomRight(e):(e.style.top="0px",e.style.left="0px"))}_placeParentBottomRight(e){e.style.position="absolute",e.style.right="0px",e.style.left="auto",e.style.top="auto",e.style.bottom="0px"}set visibility(e){const t=this.parent.node();1==e?(t?.classList.add("tooltip-visible"),t?.style.removeProperty("opacity"),this.parent.style("pointer-events",this.pointerInteractive?"auto":"none")):(t?.classList.remove("tooltip-visible"),this.parent.style("opacity",0),this.parent.style("pointer-events","none"))}updateData(e,t,n){null!==this.pendingUpdate&&cancelAnimationFrame(this.pendingUpdate);const i=t instanceof Element?t:t&&"target"in t?t.target:null;this.pendingData={ri:e,anchorTarget:i,augment:n};const o=this.parent.node();o&&("parent-bottom-right"===this.placement?this._placeParentBottomRight(o):o.style.left="-9999px"),this.visibility=!0,this.pendingUpdate=requestAnimationFrame(()=>{if(this.pendingUpdate=null,!this.pendingData)return;const{ri:e,anchorTarget:t,augment:n}=this.pendingData;this.pendingData=null,this._updateContent(e,n),this._updatePosition(t)})}_updateContent(e,t){const{selectedColor:n,detailColor:o,valueColor:s}=this.themeColors;this.currentToken.html(()=>{const i=null!=t?.headerLines?t.headerLines.map(e=>Dt(e)).join("<br/>"):Dt(e.tokenData.raw);return`<span style="color: ${n};">${i}</span>`});const a=e.tokenData,r=e.semantic,l=r&&(void 0!==r.pwScore||void 0!==r.signalProb||void 0!==r.rawScoreNormed||void 0!==r.rawScore||void 0!==r.chunkIndex&&void 0!==r.chunkMatchDegree),{hasRealTopk:c}=Ut(a),d=[];l&&r&&(void 0!==r.pwScore&&d.push(qt({label:p("pw score:"),value:this.numF(r.pwScore)},o,s)),void 0!==r.signalProb&&d.push(qt({label:p("signal probability:"),value:this.numF(r.signalProb)},o,s)),void 0!==r.rawScoreNormed&&d.push(qt({label:p("raw score normed:"),value:this.numF(r.rawScoreNormed)},o,s)),void 0!==r.rawScore&&d.push(qt({label:p("raw score:"),value:i.GPZ(".6f")(r.rawScore),valueColor:!1},o,s)),void 0!==r.chunkIndex&&void 0!==r.chunkMatchDegree&&d.push(qt({label:`chunk #${r.chunkIndex} match score:`,value:(100*r.chunkMatchDegree).toFixed(1)+"%"},o,s)));for(const e of t?.rowsBeforeInfo??[])d.push(qt(e,o,s));const h=[];if(c){const e=R(a.real_topk[1]);if("classic"!==H()){const e=P(a),t=(new TextEncoder).encode(a.raw).length;h.push(qt({label:p("information density:"),value:`${this.significantF(e)} ${p("bits/Byte")}`},o,s)),h.push(qt({label:p("UTF-8 size:"),value:`${t} ${p("bytes")}`,valueColor:!1},o,s))}h.push(qt({label:this.surprisalRowLabel,value:`${this.significantF(e)} bits`},o,s))}for(const e of t?.rowsAfterSurprisal??[])h.push(qt(e,o,s));const u=[];d.length&&u.push(d.join("<br/>")),d.length&&h.length&&u.push(`<span style="color:${o}">âââââââââââââ</span>`),h.length&&u.push(h.join("<br/>")),this.myDetail.html(u.join("<br/>"));const m=function(e,t){if(!e)return"";const{predTopk:n,hasRealTopk:i}=Ut(e),o=n.length>0;if(!o&&null==e.bpe_merged)return"";if(null!=e.bpe_merged){const t=function(e){if(!e?.length)return"";const t=e.slice(0,8),n=e.length-t.length,i=t.map(e=>Dt(e)).join("<br/>"),o=n>0?`<br/>${Ft(g("(+{n} more)",{n}))}`:"";return`<div class="topk-chart-info-parts">${Ft(g("Source fragments ({count}):",{count:e.length}))}<br/>${i}${o}</div>`}(e.bpe_merge_parts);return`<div class="row info-row topk-chart-info-row"><div class="topk-chart-info-msg">${function(e){switch(e){case"overlap":return p("BPE overlap merge: overlapping spans were combined.");case"digit":return p("Digit merge: adjacent digit sub-tokens were combined.")}}(e.bpe_merged)}</div>`+t+"</div>"}if(!o)return`<div class="row info-row topk-chart-info-row"><div class="topk-chart-info-msg">${p("Top-k data not available.")}</div></div>`;let s=n.slice(0,10).map(([e,t])=>({token:e,prob:t}));s=Bt(s,i&&null!=e.real_topk?Ht(e.raw,e.real_topk[1]):void 0);const a=t?.highlightToken??e.raw;let r;if(null!=t?.highlightProb&&Number.isFinite(t.highlightProb))r=t.highlightProb;else if(i&&a===e.raw&&null!=e.real_topk)r=e.real_topk[1];else{const e=n.find(([e])=>e===a);e&&(r=e[1])}return zt(s,{selectedToken:a,selectedProb:r,interactivePickable:!0===t?.interactive})}(a);""===m?this.predictions.selectAll(".row").data([]).join("div").remove():this.predictions.html(m)}_updatePosition(e){const t=this.parent.node();if(!t)return;if("parent-bottom-right"===this.placement)return void this._placeParentBottomRight(t);const n=this._getViewportInfo(),i="fixed"===window.getComputedStyle(t).position;let o,s=null;if(i)o={left:0,top:0,width:n.width,height:n.height};else{if(s=t.offsetParent,!s)throw new Error("[ToolTip] position:absolute ç tooltip å¿
é¡»æ offsetParentï¼è¯·ä¸ºç¥å
设置 position çå®ä½ä¸ä¸æï¼");o=s.getBoundingClientRect()}const a=this._resolveAnchorRectElement(e);
1if(!a)throw new Error("[ToolTip] æ æ³ä»éç¹è§£æå° SVG rectï¼è¯·ä¼ å
¥ token rectãg æå
¶å®å« rect çç¥å
å
ç´ ");let r=0,l=0,c=0,d=0;const h=a.getBoundingClientRect();i?(r=h.left,l=h.right,c=h.top,d=h.bottom):(r=h.left-o.left+s.scrollLeft,l=h.right-o.left+s.scrollLeft,c=h.top-o.top+s.scrollTop,d=h.bottom-o.top+s.scrollTop);const u=t.getBoundingClientRect(),p=u.width||250,m=u.height||100;let g=l+15,f=d+15;const y=i?n.width:o.width;if(g+p>y){const e=r-p-15;g=e>=5?e:y-p-5}if(i)f+m>n.height&&(f=Math.max(5,c-m-15));else{let e=o.top+f-s.scrollTop;e+m>n.height&&(f=c-m-15,e=o.top+f-s.scrollTop,e<0&&(f=-o.top+s.scrollTop+5))}this.parent.styles({top:f+"px",left:g+"px"})}}function Wt(e,t,n){const i=Array.from(e||"");if(0===i.length)return"";const o=Math.max(0,Math.min(t,i.length)),s=Math.max(o,Math.min(n,i.length));return o>=s?"":i.slice(o,s).join("")}function jt(e){return 1===e.length&&e>="0"&&e<="9"}function Vt(e,t,n){const i=e.length;let o=0;for(;o<i&&e[o].offset[1]<=t;)o++;if(o>=i)return null;if(e[o].offset[0]!==t)return null;const s=[];for(;o<i;){const[a,r]=e[o].offset;if(a<t||r>n)return null;if(s.push(o),r===n)return s;if(o++,o>=i)return null;if(e[o].offset[0]!==r)return null}return null}function Kt(e,t,n){return[...t.bpe_merge_parts??[Wt(e,t.offset[0],t.offset[1])],...n.bpe_merge_parts??[Wt(e,n.offset[0],n.offset[1])]]}function Jt(e,t){return e.flatMap(e=>{const n=t[e];return n.bpe_merge_parts??[n.raw]})}function Yt(e){const t=e;return void 0!==t.rawScore?t.rawScore:e.score}function Zt(e,t,n={}){const i=function(e,t){if(0===e.length)return e;const n=function(e){return e.filter(e=>{const[t,n]=e.offset;return!(t===n&&""===(e.raw??""))})}(e);return 0===n.length?n:function(e,t){if(!Array.isArray(e)||0===e.length)return[];const{getOffset:n,cloneForStep:i,mergeOverlappingPair:o,sliceMergedRaw:s}=t,a=[];let r=i(e[0]);for(let t=1;t<e.length;t++){const l=i(e[t]),[c]=n(l),[d,h]=n(r),u=h;let p=c<u;if(!p&&d===h){const[e,t]=n(l);(e<=d&&d<t||e===t&&e===d)&&(p=!0)}if(p){const e=Math.max(u,n(l)[1]),t=[n(r)[0],e];r=o(r,l,t,s(t[0],e))}else a.push(r),r=l}return a.push(r),a}(n,{getOffset:e=>e.offset,cloneForStep:e=>({...e,offset:[e.offset[0],e.offset[1]]}),sliceMergedRaw:(e,n)=>Wt(t,e,n),mergeOverlappingPair:(e,n,i,o)=>({...e,offset:i,raw:o,score:e.score+n.score,bpe_merge_parts:Kt(t,e,n),bpe_merged:"overlap"})})}(e,t);return!1===n.digitMerge?i:function(e,t){return function(e,t){const n=t.length;if(0===n)return[];const i=function(e){const t=Array.from(e||""),n=t.length,i=[];let o=0;for(;o<n;){if(!jt(t[o])){o++;continue}const e=o;let s=o;for(;s<n&&jt(t[s]);)s++;const a=e>0&&" "===t[e-1]?e-1:e;i.push([a,s]),o=s}return i}(e),o=new Array(n).fill(null);let s=0;for(const[e,n]of i){const i=Vt(t,e,n);if(!i)continue;if(i.length<2)continue;const a=s++;for(const e of i){if(null!==o[e]){const n=t[e],i=o[e];throw new Error(`digitMerge: token index ${e} falls in two digit spans (offset=[${n.offset[0]},${n.offset[1]}), prior span id=${i})`)}o[e]=a}}const a=[];let r=0;for(;r<n;){const e=o[r];if(null===e){a.push([r]),r++;continue}const t=[r];for(r++;r<n&&o[r]===e;)t.push(r),r++;a.push(t)}return a}(t,e).map(n=>{if(1===n.length)return e[n[0]];const i=e[n[0]],o=e[n[n.length-1]],s=Wt(t,i.offset[0],o.offset[1]),a=n.reduce((t,n)=>t+e[n].score,0);return{...i,offset:[i.offset[0],o.offset[1]],raw:s,score:a,bpe_merge_parts:Jt(n,e),bpe_merged:"digit"}})}(i,t)}function Xt(e,t){const n=e.select(".LMF .text-layer").node();if(!n)return;n.querySelector(".attribution-predicted-ghost-pill")?.remove();const i=document.createElement("span");i.className="attribution-predicted-ghost-pill",i.innerHTML=Ot(t??""),n.append(i)}new TextEncoder;const Qt="payloads",en="mru_order";let tn=null;function nn(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function on(e,t){return`${e}:${t}`}function sn(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??new Error("IndexedDB request failed"))})}function an(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error??new Error("IndexedDB transaction failed")),e.onabort=()=>n(e.error??new Error("IndexedDB transaction aborted"))})}async function rn(){return tn||(tn=new Promise((e,t)=>
1{const n=indexedDB.open("InfoRadarSharedCache",1);n.onerror=()=>t(n.error??new Error("Failed to open IndexedDB")),n.onsuccess=()=>e(n.result),n.onupgradeneeded=()=>{const e=n.result;e.objectStoreNames.contains(Qt)||e.createObjectStore(Qt,{keyPath:"id"}),e.objectStoreNames.contains(en)||e.createObjectStore(en,{keyPath:"namespace"})}}).catch(e=>{throw tn=null,e})),tn}async function ln(e,t){const n=await sn(e.objectStore(en).get(t));return Array.isArray(n?.keyOrder)?n.keyOrder:[]}async function cn(e,t,n){await sn(e.objectStore(en).put({namespace:t,keyOrder:n}))}function dn(e){return{contentKey:e.contentKey,businessKeyJson:e.businessKeyJson,listLabel:e.listLabel,payload:e.payload,status:e.status,createdAt:e.createdAt}}async function hn(e,t){const n=(await rn()).transaction(Qt,"readonly"),i=await sn(n.objectStore(Qt).get(on(e,t)));if(await an(n),i)return dn(i)}async function un(e,t){const n=(await rn()).transaction([Qt,en],"readwrite"),i=n.objectStore(Qt);if(!await sn(i.get(on(e,t))))return void await an(n);let o=await ln(n,e);const s=o.indexOf(t);s>=0&&o.splice(s,1),o.push(t),await cn(n,e,o),await an(n)}const pn="attribution";function mn(e,t){return n={context:e,targetPrediction:t},nn(JSON.stringify(n));var n}async function gn(e){if(!e)return;const t=await hn(pn,e);return t?.payload}async function fn(e){e&&await async function(e,t){const n=(await rn()).transaction([Qt,en],"readwrite");await sn(n.objectStore(Qt).delete(on(e,t)));let i=await ln(n,e);i=i.filter(e=>e!==t),await cn(n,e,i),await an(n)}(pn,e)}async function yn(e){await un(pn,e)}async function vn(e,t){const n=mn(e,t),i=await hn(pn,n);if(i?.payload?.response?.success)return await un(pn,n),{response:i.payload.response,contentKey:i.contentKey}}async function bn(e){const{apiBaseForRequests:t,context:n,targetPrediction:i,model:o,sourcePage:s,forceRefresh:a}=e;if(a&&await fn(mn(n,i)),!a){const e=await vn(n,i);if(e)return e}const r=await async function(e,t,n,i,o){const s={context:t,model:i,source_page:o};null!==n&&(s.target_prediction=n);const a=await fetch(_("/api/prediction-attribute",e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),r=await a.text();let l;try{l=JSON.parse(r)}catch{const e=r.slice(0,160)+(r.length>160?"â¦":"");throw new Error(`Response is not JSON (HTTP ${a.status}). Gateway or proxy may have returned HTML: ${e}`)}if(!a.ok)throw new Error(l.message??`HTTP ${a.status}`);if(!l.success)throw new Error(l.message??`Request failed (HTTP ${a.status})`);return l}(t,n,i,o,s),{contentKey:l}=await async function(e,t,n=(t.success?"complete":"partial")){return async function(e){const{namespace:t,businessKeyJson:n,listLabel:i,payload:o,status:s,maxEntries:a}=e,r=nn(n),l=on(t,r),c=(await rn()).transaction([Qt,en],"readwrite"),d=c.objectStore(Qt),h=await sn(d.get(l)),u=Date.now(),p=!!h;let m=await ln(c,t);const g=m.indexOf(r);if(g>=0&&m.splice(g,1),m.length>=a&&!p){const e=m.shift();void 0!==e&&await sn(d.delete(on(t,e)))}return await sn(d.put({id:l,namespace:t,contentKey:r,businessKeyJson:n,listLabel:i,payload:o,status:s,createdAt:h?.createdAt??u})),m.push(r),await cn(c,t,m),await an(c),{contentKey:r}}({namespace:pn,businessKeyJson:JSON.stringify({context:e.context,targetPrediction:e.targetPrediction}),listLabel:(i=e.context,o=e.targetPrediction,`${i.length>48?`${i.slice(0,48)}â¦`:i} â ${o}`),payload:{context:e.context,targetPrediction:e.targetPrediction,response:t},status:n,maxEntries:100});var i,o}({context:n,targetPrediction:i},r,"complete");return{response:r,contentKey:l}}const wn="info_radar_attribution_exclude_tokens",kn="info_radar_attribution_exclude_tokens_enabled",xn=["#comment# use '#comment#' to comment lines; support regex","<\\|im_start\\|>system\\n","<\\|im_start\\|>user\\n","<\\|im_start\\|>assistant\\n","<\\|im_start\\|>assistant\\n\\n","<\\|im_end\\|>\\n","<think>\\n\\n","</think>\\n\\n","<\\|im_start\\|>system\\n[\\s\\S]*?<\\|im_end\\|>#comment# all system prompt"].join("\n");function _n(){try{if(!l(kn,!0,{encoding:"1"}))return"";const e=s(wn);return null===e?xn:e}catch{return""}}function Sn(e,t){t&&(t.hidden=!e?.checked)}["<think>\\n","</think>
1\\n\\n"].join("\n"),i.Ubm(".loadersmall").style("display","none"),"en"!==d&&document.querySelectorAll("[data-i18n]").forEach(e=>{const t=e.getAttribute("data-i18n");(t&&"text"!==t?t.split(",").map(e=>e.trim()):["text"]).forEach(t=>{let n=null;"text"===t?(n=e.textContent?.trim()||null,n&&(e.textContent=p(n))):"html"===t?(n=e.innerHTML?.trim()||null,n&&(e.innerHTML=p(n))):(n=e.getAttribute(t),n&&e.setAttribute(t,p(n)))})});const Cn=function(){const e=i.Ltv("#toast");let t=null;const n=()=>{e.classed("show",!1),setTimeout(()=>{e.selectAll("*").remove(),e.text("").classed("success",!1).classed("error",!1).classed("dismissible",!1)},300)};return{show:(i,o="success",s=3e3)=>{t&&(clearTimeout(t),t=null),e.selectAll("*").remove(),e.classed("success","success"===o).classed("error","error"===o).classed("dismissible","error"===o).classed("show",!0),"error"===o?(e.append("span").attr("class","toast-message").text(i),e.append("button").attr("class","toast-close").attr("type","button").attr("aria-label","Close").text("Ã").on("click",()=>n())):(e.text(i),t=setTimeout(n,s))}}}().show,Tn="info_radar_attribution_context_history",Mn="info_radar_attribution_target_history",An="info_radar_attribution_model_variant",En=i.Ltv("body").node(),{eventHandler:Rn,totalSurprisalFormat:Ln,api:In,apiBase:Pn}=function(e,t){const n=x();X(),Q||(Q=!0,window.addEventListener("storage",e=>{e.key===J&&(X(),window.dispatchEvent(new Event(Y)),window.dispatchEvent(new Event("resize")))})),function(){const e=document.getElementById(ot);e&&!e.textContent?.trim()&&(e.textContent="â")}(),function(){const e=document.getElementById("frontend_build_time");e&&(e.textContent=`Build: ${function(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}("2026-09-21T08:10:31.004Z")}`)}(),rt(n);const o=new it(n),s=t||document.body,a=i.GPZ(".2f");return{eventHandler:new Ye(s),api:o,apiBase:n,tokenSurprisalColorScale:e=>le(e,se),byteSurprisalColorScale:e=>ce(e,1,se),totalSurprisalFormat:e=>null!==e&&Number.isFinite(e)?a(e):String(e)}}(0,En),On=Pn,Dn=T.getInstance();In.setAdminToken(Dn.isInAdminMode()?Dn.getAdminToken():null);const Fn=i.Ltv("#context_text"),Nn=i.Ltv("#context_count_value"),$n=i.Ltv("#clear_context_btn"),Hn=i.Ltv("#paste_context_btn"),Bn=document.getElementById("context_history_btn"),zn=i.Ltv("#target_text"),Un=i.Ltv("#target_count_value"),qn=i.Ltv("#clear_target_btn"),Gn=i.Ltv("#paste_target_btn"),Wn=document.getElementById("target_history_btn"),jn=i.Ltv("#analyze_btn"),Vn=document.getElementById("attribution_model_variant"),Kn=i.Ltv("#force_retry_btn"),Jn=i.Ltv(".loadersmall"),Yn=i.Ltv("#attribution_result_info"),Zn=document.getElementById("attribution_use_mapping"),Xn=document.getElementById("attribution_max_score_range"),Qn=document.getElementById("attribution_max_score_value");function ei(){const e=Vn?.value;return"base"===e||"instruct"===e?e:"instruct"}Vn&&(Vn.value=function(e){const t=s(e);return null!==t&&["base","instruct"].includes(t)?t:"instruct"}(An)),Vn?.addEventListener("change",()=>{a(An,ei())}),new Je({textField:Fn,textCountValue:Nn,clearBtn:$n,submitBtn:jn,saveBtn:i.Ltv(null),pasteBtn:Hn,totalSurprisalFormat:Ln,showAlertDialog:N}),new Je({textField:zn,textCountValue:Un,clearBtn:qn,submitBtn:jn,saveBtn:i.Ltv(null),pasteBtn:Gn,totalSurprisalFormat:Ln,showAlertDialog:N});const ti=function(e){const{resultsRoot:t,eventHandler:n,tooltipRoot:o,debugPanelElementId:s="attribution_debug_info",tooltipHideRoot:a=i.Ltv("body")}=e,r=e.debugParentId??t.node()?.id??"results",l=o&&!o.empty()?o:t.select("#major_tooltip"),c=new Gt(l,n);let d=null,h=null;const u=new Lt(t,n,{onFullTextLayerRenderComplete:()=>{d&&Xt(t,d.response.target_token)}});function p(e,n,i){d={context:e,response:n},h=i;const o=function(e,t,n){const i=t.token_attribution??[],o=n.excludePromptPatternsRegion??{start:0,end:e.length},s=function(e,t,n){const i=n?.start??0,o=n?.end??e.length,s=Math.max(0,Math.min(i,e.length)),a=Math.max(s,Math.min(o,e.length)),r=e.slice(s,a),l=[];for(const e of t.split("\n")){const t=e.indexOf("#comment#"),n=-1===t?e:e.slice(0,t);if(""!==n)try{const e=new RegExp(n,"g");for(const t of r.matchAll(e)){if(void 0===t.index)continue;const e=s+t.index;l.push([e,e+t[0].length])}}catch{}}return l}(e,n.excludePromptPatternsText,o),a=i.map(e=>({raw:e.raw,offset:e.offset,pred_topk:[]})),r=function(e){const t=Math.max(0,...e.map(e=>e.score).filter(Number.isFinite));return e.map(e=>{const n=Yt(e);return t<=0?{...e,rawScore:n}:{...e,rawScore:n,score:e.score/t}})}(Zt(i.map(e=>{const[t,n]=e.offset,i=function(e,t,n){for(const[i,o]of n)if(i<=e&&t<=o)return!0;return!1}(t,n,s);return{offset:e.offset,raw:e.raw,score:i?0:e.score}}),e,{digitMerge:j()})),l=r.map(e=>{const t=e.bpe_merged,n=e.bpe_merge_parts,i={offset:e.offset,raw:e.raw,pred_topk:[]};return void 0!==t&&(i.bpe_merged=t),void 0!==n&&(i.bpe_merge_parts=[...n]),i}),c=r.map(e=>Yt(e)),d=r.map(e=>e.score),h={model:t.model??null,error:null,bpe_strings:l,originalTokens:a,bpeBpeMergedTokens:l.map(e=>({...e})),originalText:e},u=h;return u.rawScoresNormed=d,u.tokenRawScores=c,null!=n.colorRangeMax&&(u.colorScores=function(e,t){return e.map(e=>e>t?1:e/t)}(d,n.colorRangeMax)),h}(e,n,i);u.update(o),Xt(t,n.target_token),function(e,t,n){const i=document.getElementById(e);if(!i)return;let o=document.getElementById(t);o||(o=document.createElement("div"),o.id=t,o.className="semantic-debug-info",i.appendChild(o));const s=n.abbrev??n.debugInfo?.abbrev;let a=function(e){if(e?.topk_tokens?.length&&e?.topk_probs?.length)return e.topk_tokens.map((t,n)=>({token:t,prob:e.topk_probs[n]??0}))}(n.debugInfo);const r=Ht(n.attributionTarget?.token,n.attributionTarget?.prob);a?.length&&(a=Bt(a,r));const l=function(e,t,n){const i=!n?.omitAbbrev&&!!e;if(!i&&!t?.length)return"";const o=[];if(i&&e&&o.push(`<div class="semantic-debug-abbrev"><pre>${Ft(e)}</pre></div>`),t?.length){const e=n?.attributionTarget,i=e?.token,s=void 0!==i&&""!==i?{selectedToken:i,...null!=e?.prob&&Number.isFinite(e.prob)?{selectedProb:e.prob}:{}}:void 0;o.push(function(e,t){const n=t??{},i=zt(e,{...n,maxBarWidth:n.maxBarWidth??100,barCellWidth:n.barCellWidth??180});return i?`<div class="semantic-debug-topk-chart predictions predictions-table">${i}</div>`:""}(t,s))}return o.join("")}(s,a,{omitAbbrev:n.omitAbbrev,attributionTarget:n.attributionTarget});if(!l)return o.style.display="none",void(o.innerHTML="");o.style.display="block",o.innerHTML=l}(r,s,{debugInfo:n.debug_info,attributionTarget:{token:n.target_token,prob:n.target_prob}})}return u.updateOptions({gltrMode:Rt.fract_p,enableRenderAnimation:!1,enableMinimap:!1,semanticAnalysisMode:!0,overlayForceDisableInfoDensityRender:!0},!0),n.bind(Lt.events.tokenHovered,e=>{e.hovered?c.updateData(e.d,e.event):c.visibility=!1}),a.on("touchstart.attributionInspector",()=>{c.hideAndReset()}),m=()=>{d&&h&&p(d.context,d.response,h)},U.add(m),W||(W=!0,window.addEventListener("storage",e=>{e.key===z&&G()})),{apply(e,t,n){p(e,t,n)},reapply(e){if(!d)return;const{context:t,response:n}=d;p(t,n,e)},getLastPayload:()=>d};var m}({resultsRoot:i.Ltv("#results"),eventHandler:Rn,debugParentId:"attribution_debug_container"});function ni(){return{colorRangeMax:di(),excludePromptPatternsText:_n()}}let ii=!1,oi=null;function si(){const e=Fn.node()?.value??"",t=zn.node()?.value??"",n=e.length>0&&t.length>0,i=null===oi||e!==oi.context||t!==oi.target;!function(e){const{primaryBtn:t,forceRetryBtn:n,inFlight:i,primaryInFlightMode:o,primaryInFlightLabel:s,primaryIdleLabel:a,idleInputsReady:r,hasUncommittedDraft:l}=e;if(i&&"stop"===o){if(void 0===s)throw new Error("syncDraftCommittedButtonPair: primaryInFlightLabel is required when primaryInFlightMode is stop");return t.text(s),t.property("disabled",!1),t.classed("inactive",!1),n.property("disabled",!0),void n.classed("inactive",!0)}if(i&&"freeze"===o)return t.property("disabled",!0),t.classed("inactive",!0),n.property("disabled",!0),void n.classed("inactive",!0);if(t.text(a),!r)return t.property("disabled",!0),t.classed("inactive",!0),n.property("disabled",!0),void n.classed("inactive",!0);const c=l;t.property("disabled",!c),t.classed("inactive",!c),n.property("disabled",!1),n.classed("inactive",!1)}({primaryBtn:jn,forceRetryBtn:Kn,inFlight:ii,primaryInFlightMode:"freeze",primaryIdleLabel:p("Analyze attribution"),idleInputsReady:n,hasUncommittedDraft:i})}function ai(e){ii=e,Jn.style("display",e?null:"none"),si()}var ri;function li(){const e=!!Zn?.checked;Xn&&(Xn.disabled=!e)}function ci(){if(!Xn||!Qn)return;const e=Number(Xn.value);Qn.textContent=Number.isFinite(e)?e.toFixed(2):"â"}function di(){if(!Zn?.checked)return null;if(!Xn)return null;const e=Number(Xn.value);return!Number.isFinite(e)||e<=0||e>1?null:e}function hi(e,t,n){(function(e,t){ti.apply(e,t,ni()),function(e){const t=e.token_attribution?.length??0,n=e.model??"â";Yn.classed("is-hidden",!1).text(`${g("{count} tokens",{count:t})}\n${p("model")}: ${n}`)}(t),oi={context:Fn.node()?.value??"",target:zn.node()?.value??""},si()})(e,t),ft(n,gt,"attribution")}
1function ui(){ti.reapply(ni())}async function pi(e){const t=Fn.node()?.value??"",n=zn.node()?.value??"";if(ii||!t||!n)return;const i=!0===e?.forceRefresh;if(!i){const e=await vn(t,n);if(e)return hi(t,e.response,e.contentKey),pt(t,Tn),void pt(n,Mn)}ai(!0);try{const{response:e,contentKey:o}=await bn({apiBaseForRequests:On,context:t,targetPrediction:n,model:ei(),sourcePage:"attribution",forceRefresh:i});hi(t,e,o),pt(t,Tn),pt(n,Mn)}catch(e){const t=e instanceof Error?e.message:String(e);N(p("Context Attribution"),yt(t))}finally{ai(!1)}}st=()=>ii,[Fn,zn].forEach(e=>{e.node()?.addEventListener("input",si)}),si(),li(),ci(),Zn?.addEventListener("change",()=>{li(),ui()}),Xn?.addEventListener("input",()=>{ci(),ui()}),ri={textInput:document.getElementById("attribution_exclude_prompt_patterns"),enableCheckbox:document.getElementById("attribution_exclude_prompt_patterns_enable"),onEffectiveChange:ui},function(e){const{storageKeys:t,textInput:n,enableCheckbox:i,onEffectiveChange:o,defaultTextWhenKeyAbsent:r,defaultEnabledWhenKeyAbsent:d=!0,skipLocalStoragePersist:h=!1}=e,{textKey:u,enabledKey:p}=t;try{const e=s(u);n&&(null!==e?n.value=e:void 0!==r&&(n.value=r)),i&&(i.checked=l(p,d,{encoding:"1"}))}catch{}Sn(i,n),i?.addEventListener("change",()=>{h||(n&&a(u,n.value),c(p,i.checked,"1")),Sn(i,n),o()}),n?.addEventListener("blur",()=>{h||a(u,n.value),o()}),window.addEventListener("storage",e=>{if(e.storageArea!==localStorage)return;const t=e.key;t!==u&&t!==p||(t===u&&n&&(n.value=e.newValue??""),t===p&&i&&(i.checked=null===e.newValue?d:"1"===e.newValue),Sn(i,n),o())})}({storageKeys:{textKey:wn,enabledKey:kn},...ri,defaultTextWhenKeyAbsent:xn}),jn.on("click",()=>{pi()}),Kn.on("click",()=>{pi({forceRefresh:!0})}),Fn.node()?.addEventListener("keydown",e=>{"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&pi()});const mi=Fn.node(),gi=zn.node();async function fi(e,t){try{Fn.property("value",e.context),zn.property("value",e.targetPrediction),mi?.dispatchEvent(new Event("input",{bubbles:!0})),gi?.dispatchEvent(new Event("input",{bubbles:!0})),si(),hi(e.context,e.response,t.contentKey),t.shouldTouch&&t.ctx&&(await yn(t.contentKey),await t.ctx.refreshList())}catch(e){const t=e instanceof Error?e.message:String(e);Cn(yt(t),"error")}}mt({input:mi,dropdownId:"context_history_dropdown",storageKey:Tn,openDropdownOnFocusInput:!1,filterHistoryByInput:!1,onSelect:si,historyButton:Bn,applyHistoryOnHover:!0}),mt({input:gi,dropdownId:"target_history_dropdown",storageKey:Mn,openDropdownOnFocusInput:!1,filterHistoryByInput:!1,onSelect:si,historyButton:Wn,applyHistoryOnHover:!0}),function(e){const t=function(e){let t=[];return{getEntries:()=>t,refresh:async()=>{t=await e()}}}(e.listMru),n={refreshList:()=>t.refresh()};mt({input:null,dropdownId:e.dropdownId,getHistoryEntries:()=>t.getEntries().map(e=>({id:e.contentKey,label:e.listLabel})),refreshHistoryItems:()=>t.refresh(),openDropdownOnFocusInput:!1,filterHistoryByInput:!1,onSelect:()=>{},fillInputOnSelect:!1,onHistorySelect:t=>{Promise.resolve(e.onSelectEntry(t,!1,n))},onRemove:e.onRemove,onPromote:e.onPromote,historyButton:e.historyButton,clickOutsideRoot:e.clickOutsideRoot,applyHistoryOnHover:!0}),t.refresh()}({dropdownId:"attribution_cached_history_dropdown",historyButton:document.getElementById("attribution_cached_history_btn"),clickOutsideRoot:document.getElementById("attribution_cached_history_dropdown"),listMru:async function(){const e=await async function(e){const t=(await rn()).transaction([Qt,en],"readonly"),n=await ln(t,e),i=t.objectStore(Qt),o=[];for(let t=n.length-1;t>=0;t--){const s=n[t],a=await sn(i.get(on(e,s)));a&&o.push(dn(a))}return await an(t),o}(pn);return e.map(e=>({contentKey:e.contentKey,listLabel:e.listLabel}))},onSelectEntry:async(e,t,n)=>{const i=await gn(e);i?await fi(i,{shouldTouch:Boolean(t),ctx:n,contentKey:e}):Cn(p("Cached result not found"),"error")},onRemove:fn,onPromote:yn}),async function(e){const t=e.readRaw();if(!t)return;const n=await e.fetchEntry(t);if(null==n||e.isValid&&!e.isValid(n))await Promise.resolve(e.onMissing());else try{await e.apply(n,t)}catch(t){if(!e.onApplyError)throw t;await Promise.resolve(e.onApplyError(t))}}
1({readRaw:function(e=gt){return function(e){try{const t=new URL(window.location.href).searchParams.get(e);return null!=t&&t.length>0?t:null}catch{return null}}(e)},fetchEntry:gn,apply:async(e,t)=>{await fi(e,{shouldTouch:!1,contentKey:t})},onMissing:async()=>{Cn(p("Cached result not found (link may be expired)"),"error"),ft(null,gt,"attribution")},onApplyError:e=>{const t=e instanceof Error?e.message:String(e);Cn(yt(t),"error"),ft(null,gt,"attribution")}}),function(){const e=i.Ltv("#resizer"),t=i.Ltv(".left_panel");if(e.empty()||t.empty())return;const{storageKey:n}={storageKey:"info_radar_panel_split_attribution"};let o=function(e){const t=s(e);if(null===t)return.5;const n=Number(t);return Number.isFinite(n)?Math.max(.1,Math.min(.9,n)):.5}(n),r=!1,l=0,c=0;const d=(e=window.innerWidth,n=window.innerHeight)=>{const s=i.Ubm(".main_frame");ee()?s.style("height",null).style("width",null):(s.style("height",n-53+"px").style("width",`${e}px`),(e=>{const n=e-8,i=n*o,s=.1*e,a=.9*e,r=Math.max(s,Math.min(a,i));o=r/n,t.style("flex-basis",`${r}px`)})(e))};d(),e.on("mousedown",e=>{if(e.preventDefault(),e.stopPropagation(),ee())return;r=!0,l=e.clientX;const n=window.innerWidth,s=t.style("flex-basis"),a=parseInt(s,10),d=n-8;c=Number.isFinite(a)?a:d*o,i.Ltv("body").style("cursor","col-resize").style("user-select","none"),i.Ltv(window).on("mousemove.chatResizer",e=>h(e)).on("mouseup.chatResizer",()=>u())});const h=e=>{if(!r)return;e.preventDefault();const n=window.innerWidth,i=n-8,s=e.clientX-l,a=Math.max(.1*n,Math.min(.9*n,c+s));t.style("flex-basis",`${a}px`),o=a/i},u=()=>{r&&(r=!1,function(e,t){const n=Math.max(.1,Math.min(.9,t));a(e,String(n))}(n,o),i.Ltv("body").style("cursor",null).style("user-select",null),i.Ltv(window).on("mousemove.chatResizer",null).on("mouseup.chatResizer",null))};window.addEventListener("resize",()=>{d(window.innerWidth,window.innerHeight)})}();const yi=function(e={},t="#dark_mode_toggle"){const{onThemeChange:n}=e,o=i.Ltv(t),l=[{mode:"light",icon:"âï¸",label:p("Light")},{mode:"dark",icon:"ð",label:p("Dark")},{mode:"auto",icon:"ð",label:p("Auto")}],c=e=>{document.documentElement.setAttribute("data-theme",e),n?.(e)},d=f({container:o,classPrefix:"theme",options:l.map(({mode:e,icon:t,label:n})=>({value:e,html:`${t} <span>${n}</span>`})),dataAttr:"data-mode",bodyClickNamespace:"theme-dropdown",onSelect:(e,t=!0)=>{t?a("theme-mode",e):r("theme-mode"),c(y(e)),d.updateCurrent(e)}}),h=e=>{if("theme-mode"!==e.key)return;const t=v();c(y(t)),d.updateCurrent(t)},u=v();d.updateCurrent(u),c(y(u));let m=null;const g=()=>{const e=s("theme-mode");"auto"!==e&&(e||s("theme"))||c(m.matches?"dark":"light")};return window.matchMedia&&(m=window.matchMedia("(prefers-color-scheme: dark)"),m.addEventListener("change",g)),window.addEventListener("storage",h),{dispose:()=>{m?.removeEventListener("change",g),window.removeEventListener("storage",h),d.dispose()}}}({onThemeChange:()=>{ui()}},"#theme_dropdown"),vi=function(e={},t="#language_toggle"){const{onLanguageChange:n}=e,o=f({container:i.Ltv(t),classPrefix:"language",options:b.map(({lang:e,label:t})=>({value:e,html:`<span>${p(t)}</span>`})),dataAttr:"data-lang",bodyClickNamespace:"language-dropdown",onSelect:e=>{(function(e){d=e,a(h,e)})(e),o.updateCurrent(e),n?.(),location.reload()}}),s=e=>{"app_language"===e.key&&("en"!==e.newValue&&"zh"!==e.newValue||location.reload())};return o.updateCurrent(d),window.addEventListener("storage",s),{dispose:()=>{window.removeEventListener("storage",s),o.dispose()}}}({},"#language_dropdown");new class{constructor(e,t,n,o,s,a,r,l,c,d="analysis"){this.tokenRenderStyleDropdown=null,this.menuContext=d,this.settingsBtn=i.Ltv(e),this.settingsMenu=i.Ltv(t),this.adminModeBtn=i.Ltv(n),this.modelManageBtn=i.Ltv("#model_manage_btn"),this.visitStatsBtn=i.Ltv("#visit_stats_btn"),this.tokenRenderStyleDropdown="analysis"===d?this.initTokenRenderStyleDropdown():null,this.minimapToggle=i.Ltv("#enable_minimap_toggle"),this.semanticAnalysisToggle=i.Ltv("#semantic_analysis_toggle"),this.digitsMergeToggle=i.Ltv("#enable_digits_merge_toggle"),this.forceNarrowToggle=i.Ltv("#force_narrow_toggle"),this.semanticThresholdInput=i.Ltv("#semantic_threshold_input"),this.semanticThresholdItem=i.Ltv("#semantic_threshold_item"),this.semanticOptionsRow=i.Ltv("#semantic_options_row"),this.weakenSurprisalColorToggle=i.Ltv("#weaken_surprisal_color_toggle"),this.themeDropdownContainer=i.Ltv("#theme_dropdown"),this.adminManager=o,this.api=s,this.onAdminStateChange=a,this.callbacks=r||{},this.themeManager=l,this.languageManager=c,this.initialize()}initialize(){this.settingsBtn.on("click",e=>{e.stopPropagation(),this.toggleMenu()}),i.Ltv("body").on("click.settings-menu",()=>{this.closeMenu()}),this.settingsMenu.on("click",e=>{e.stopPropagation()}),this.minimapToggle.node()&&this.minimapToggle.on("change",()=>{const e=this.minimapToggle.node()?.checked||!1;this.callbacks.onMinimapToggle&&this.callbacks.onMinimapToggle(e)}),this.digitsMergeToggle.node()&&this.digitsMergeToggle.on("change",()=>{var e;e=this.digitsMergeToggle.node()?.checked??!1,c(z,e),G()}),this.forceNarrowToggle.node()&&(this.forceNarrowToggle.on("change",()=>{(()=>{this.forceNarrowToggle.node()?.checked??!1?a(J,"1"):r(J),X(),window.dispatchEvent(new Event(Y)),window.dispatchEvent(new Event("resize"))})()}),window.addEventListener(Y,()=>{this.setCheckboxChecked(this.forceNarrowToggle,Z())})),"analysis"===this.menuContext&&this.semanticAnalysisToggle.node()&&this.semanticAnalysisToggle.on("change",()=>{const e=this.semanticAnalysisToggle.node()?.checked||!1;!function(e){const t=w.parameters;e?t.semantic_analysis="1":delete t.semantic_analysis,w.updateUrl(t,!1)}(e),this.updateSemanticThresholdVisibility(),this.updateSemanticOptionsRowVisibility(),this.callbacks.onSemanticAnalysisToggle&&this.callbacks.onSemanticAnalysisToggle(e)}),"analysis"===this.menuContext&&this.weakenSurprisalColorToggle.node()&&this.weakenSurprisalColorToggle.on("change",()=>{var e;e=this.weakenSurprisalColorToggle.node()?.checked||!1,c(ue,e),window.dispatchEvent(new CustomEvent("surprisal-color-weaken-change"))}),this.adminModeBtn.node()&&this.adminModeBtn.on("click",()=>{this.closeMenu(),this.handleAdminModeClick()}),this.modelManageBtn.node()&&this.modelManageBtn.on("click",()=>{this.closeMenu(),async function(e){try{const[t,n]=await Promise.all([e.getAvailableModels(),e.getCurrentModel()]);if(!t.success||!n.success)return void N(p("Error"),"Failed to load model management information");const o=t.models;let s=n.model,a=n.device_type,r=n.use_int8,l=n.use_bfloat16,c=n.loading,d=null,h=()=>{};
1D({title:"Model Management",loadingConfirmText:"Applying...",content:(t,n)=>{h=n??(()=>{});const u=t.append("div").attr("class","dialog-form-container"),p=u.append("div").attr("class","device-info").style("margin-bottom","12px").style("padding","8px").style("background-color","var(--panel-bg)").style("border-radius","4px").style("font-size","12px"),m=p.append("div").style("display","flex").style("justify-content","space-between").style("align-items","center").style("margin-bottom","6px"),g=m.append("div").style("font-weight","bold").style("color","var(--primary-color, #2196F3)"),f=m.append("button").attr("class","refresh-btn").attr("title","Refresh").text("â»"),y=()=>{g.text(`Current Model: ${s}${c?" (Loading...)":""}`),p.select(".device-type").text(`Device Type: ${a.toUpperCase()}`);const e=r?"INT8":l?"bfloat16":"cpu"===a?"float32":"float16";p.select(".quantization").text(`Current Quantization: ${e}`),p.style("opacity","1")};p.append("div").attr("class","device-type"),p.append("div").attr("class","quantization"),y();const v=async()=>{p.style("opacity","0");try{const t=await e.getCurrentModel();t.success&&(s=t.model,a=t.device_type,r=t.use_int8,l=t.use_bfloat16,c=t.loading,y())}catch{}};f.on("click",async()=>{f.property("disabled",!0).text("â¦"),await v(),f.property("disabled",!1).text("â»")});const b=p.node()?.closest(".dialog-overlay");d=window.setInterval(async()=>{if(!b?.isConnected)return null!=d&&window.clearInterval(d),void(d=null);await v()},2e3),u.append("label").attr("class","dialog-label").style("margin-top","12px").text("Select model:");const w=u.append("div").attr("class","model-list").style("max-height","200px").style("overflow-y","auto").style("margin-top","8px");let k=s;o.forEach(e=>{const t=w.append("div").attr("class","model-item").style("padding","8px 12px").style("margin","4px 0").style("border","1px solid var(--border-color, #ddd)").style("border-radius","4px").style("cursor","pointer").style("transition","background-color 0.2s").classed("current-model",e===s);e===s&&t.style("background-color","var(--bg-hover, #f0f0f0)").style("font-weight","bold"),t.append("span").text(e),t.on("click",function(){k=e,w.selectAll(".model-item").style("background-color",null).style("font-weight",null),i.Ltv(this).style("background-color","var(--bg-hover, #f0f0f0)").style("font-weight","bold")}),t.on("mouseenter",function(){e!==k&&i.Ltv(this).style("background-color","var(--bg-hover-light, #f8f8f8)")}).on("mouseleave",function(){e!==k&&i.Ltv(this).style("background-color",null)})}),u.append("label").attr("class","dialog-label").style("margin-top","16px").text("Quantization Options:");const x=u.append("div").attr("class","quantization-options").style("margin-top","8px").style("padding","8px").style("border","1px solid var(--border-color, #ddd)").style("border-radius","4px"),_=x.append("div").style("margin-bottom","8px"),S=_.append("input").attr("type","checkbox").attr("id","use_int8_checkbox").property("checked",r).property("disabled","mps"===a),C="mps"===a?"Use INT8 Quantization (not supported on MPS)":"Use INT8 Quantization";_.append("label").attr("for","use_int8_checkbox").style("margin-left","6px").style("cursor","mps"===a?"not-allowed":"pointer").style("color","mps"===a?"var(--text-disabled, #999)":null).text(C);const T=x.append("div"),M=T.append("input").attr("type","checkbox").attr("id","use_bfloat16_checkbox").property("checked",l).property("disabled","cpu"!==a),A="cpu"!==a?"Use bfloat16 (CPU only)":"Use bfloat16";return T.append("label").attr("for","use_bfloat16_checkbox").style("margin-left","6px").style("cursor","cpu"!==a?"not-allowed":"pointer").style("color","cpu"!==a?"var(--text-disabled, #999)":null).text(A),S.on("change",function(){this.checked&&M.property("checked",!1)}),M.on("change",function(){this.checked&&S.property("checked",!1)}),{getValue:()=>({model:k,use_int8:S.node()?.checked||!1,use_bfloat16:M.node()?.checked||!1}),validate:()=>{if(c)return!1;const e=S.node()?.checked||!1,t=M.node()?.checked||!1;return k!==s||e!==r||t!==l},focus:()=>{}}},onConfirm:async t=>{h(!1,!0);try{const n=await e.switchModel(t.model,t.use_int8,t.use_bfloat16);h(!0,!1),n.success?N(p("Success"),n.message||"Model settings applied. The selected model will be used for the next analysis."):N(p("Error"),n.message||"Failed to apply model settings")}catch(e){h(!0,!1),N(p("Error"),"Failed to apply model settings: "+e.message)}return!1},onCancel:()=>{null!=d&&(window.clearInterval(d),d=null)}
1,confirmText:"Apply",cancelText:p("Exit"),width:"clamp(400px, 90vw, 500px)"})}catch(e){console.error("Failed to load models:",e),N(p("Error"),"Failed to load model management information")}}(this.api)}),this.visitStatsBtn.node()&&this.visitStatsBtn.on("click",()=>{this.closeMenu(),async function(e){const t=async t=>{let n=t.select("div.visit-stats-body");n.empty()&&(n=t.append("div").attr("class","visit-stats-body").style("margin","0").style("white-space","pre-wrap").style("font","inherit").style("font-size","13px")),n.style("opacity","0.75").text("Loadingâ¦");try{const t=await e.getVisitStats();if(!t?.success)throw new Error("bad");n.style("opacity",null).html(function(e){const t=e=>`<span style="color:#22c55e">${e}</span>`,n=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),i=(Object.keys(e.reset_base??{}).length>0?e.reset_base:e.startup_base)??{},o=e=>0!==e?` ${t(`(${e>0?"+":""}${e})`)}`:"",s=e=>{if(0===e)return"";const n=Ge(e);return` ${t(`(${e>0?`+${n}`:n})`)}`},a=e.totals,r=e.page_sec??{},l=e.api??{},c=e.os??{},d=e.origin_visits??{},h=i.origin_visits??{},u=Object.keys(i).length>0,p=e=>u?String(e):"unknown",m=(e,t,i)=>e.length?e.map(e=>{const s=t[e]??0;return`${n(e)}: ${p(s)}${o(s-(i[e]??0))}`}):["(none)"],g=ze(e.gen_attr_opt_sec??{}),f=ze(i.gen_attr_opt_sec??{}),y=r["causal_flow.html"]??0,v=qe(He,g),b=v.length>0&&y>0?v.map(e=>{const t=g[e]??0,i=Math.round(t/y*100),o=u?`${Ge(t)} (${i}%)`:"unknown",a=f[e]??0;return`${n(Ue[e]??e)}: ${o}${s(t-a)}`}):["(none)"],w=Object.keys(d).filter(e=>(d[e]??0)>0).sort().map(e=>{const t=d[e]??0;return`\t${n(e)}: ${p(t)}${o(t-(h[e]??0))}`});return[`Last delta reset: ${n(e.reset_at?new Date(e.reset_at).toLocaleString():"unknown")}`,`Last persisted: ${n(e.saved_at?new Date(e.saved_at).toLocaleString():"unknown")}`,"",`[All-time (${t("+ delta since reset")})]`,`Page loads: ${p(a.page_loads)}${o(a.page_loads-(i.page_loads??0))}`,`Active visits: ${p(a.active_visits)}${o(a.active_visits-(i.active_visits??0))}`,...w,`Online: ${e.online_now??"unknown"}`,"","[OS]",...m(qe($e,c),c,i.os??{}),"","[Page active time]",...(k=qe(Fe,r),x=r,_=i.page_sec??{},k.length?k.map(e=>{const t=x[e]??0,i=u?Ge(t):"unknown";return`${n(e)}: ${i}${s(t-(_[e]??0))}`}):["(none)"]),"","[API]",...m(qe(Ne,l),l,i.api??{}),"","[causal_flow options (% active time)]",...b].join("\n");var k,x,_}(t))}catch{n.style("opacity",null).text("Failed to load stats.")}};D({title:"Visit Stats",content:n=>{const o=i.Ltv(n.node().parentElement),s=o.select(".dialog-title").text();o.select(".dialog-title").remove();const a=o.insert("div",".dialog-content").attr("class","dialog-title-row");a.append("div").attr("class","dialog-title").text(s);const r=a.append("div").attr("class","dialog-title-actions");let l;r.append("button").attr("type","button").attr("class","refresh-btn").style("font-size","13px").attr("title","Persist current increments then reset delta base").text("Persist and reset delta").on("click",async function(){const n=i.Ltv(this);n.property("disabled",!0).style("opacity","0.4").text("â¦");try{const n=await e.resetVisitStats();if(!n?.success)throw new Error(n?.error??"failed");await t(l)}catch(e){alert(`Reset failed: ${e}`)}finally{n.property("disabled",!1).style("opacity",null).text("Persist and reset delta")}}),r.append("button").attr("type","button").attr("class","refresh-btn").attr("title","Refresh").text("â»").on("click",async function(){const e=i.Ltv(this);e.property("disabled",!0).text("â¦"),await t(l),e.property("disabled",!1).text("â»")});const c=n.append("div").attr("class","dialog-form-container dialog-form-container--fill");return l=c.append("div").attr("class","dialog-scroll-region"),t(l),o.select(".dialog-buttons").insert("button",".dialog-button.cancel").attr("type","button").attr("class","dialog-button cancel").attr("title","Visit stats timeline (local time)").text("Timeline").on("click",()=>{De(e)}),{focus:()=>{}}},cancelText:p("Exit"),confirmText:null,width:"clamp(340px, 90vw, 460px)"})}(this.api)}),"analysis"===this.menuContext&&this.semanticAnalysisToggle.node()&&this.setSemanticAnalysisEnabled(B()),this.setDigitsMergeCheckbox(j()),this.setCheckboxChecked(this.forceNarrowToggle,Z()),"analysis"===this.menuContext&&this.semanticThresholdInput.node()&&this.setSemanticThresholdValue(ne()),"analysis"===this.menuContext&&this.weakenSurprisalColorToggle.node()&&this.setWeakenSurprisalColor(pe()),this.applyAdminUiState()}initTokenRenderStyleDropdown(){const e=i.Ltv("#token_render_style_dropdown");
1if(!e.node())throw new Error("initTokenRenderStyleDropdown: #token_render_style_dropdown missing on analysis page");const t=f({container:e,classPrefix:"token-render-style",options:[{value:"classic",label:"Classic"},{value:"density",label:"Density"}].map(e=>({value:e.value,html:`<span>${e.label}</span>`})),dataAttr:"data-style",bodyClickNamespace:"token-render-style-dropdown",onSelect:e=>{!function(e){a($,e)}(e),t.updateCurrent(e),window.dispatchEvent(new CustomEvent("token-render-style-change"))}});return t.updateCurrent(H()),t}closeMenu(){this.settingsMenu.style("display","none")}toggleMenu(){const e=this.settingsMenu.style("display");this.settingsMenu.style("display","none"===e||""===e?"block":"none")}applyAdminUiState(){const e=this.adminManager.isInAdminMode();this.adminModeBtn.text(e?"Exit":"Enter"),this.adminModeBtn.classed("active",e),this.settingsMenu.selectAll(".settings-menu-item[data-admin-only]").style("display",e?null:"none"),this.tokenRenderStyleDropdown?.updateCurrent(H()),"analysis"===this.menuContext&&this.semanticAnalysisToggle.node()&&this.setSemanticAnalysisEnabled(B()),this.setDigitsMergeCheckbox(j()),this.setCheckboxChecked(this.forceNarrowToggle,Z()),"analysis"===this.menuContext&&this.semanticThresholdInput.node()&&(this.setSemanticThresholdValue(ne()),this.updateSemanticThresholdVisibility()),"analysis"===this.menuContext&&this.weakenSurprisalColorToggle.node()&&this.setWeakenSurprisalColor(pe()),this.onAdminStateChange&&this.onAdminStateChange()}setMinimapEnabled(e){const t=this.minimapToggle.node();t&&(t.checked=e)}setSemanticAnalysisEnabled(e){const t=this.semanticAnalysisToggle.node();t&&(t.checked=e)}setDigitsMergeCheckbox(e){this.setCheckboxChecked(this.digitsMergeToggle,e)}setCheckboxChecked(e,t){const n=e.node();n&&(n.checked=t)}updateSemanticThresholdVisibility(){if(!this.semanticThresholdItem.node())return;const e=this.adminManager.isInAdminMode(),t=B();this.semanticThresholdItem.style("display",e&&t?null:"none")}updateSemanticOptionsRowVisibility(){if(!this.semanticOptionsRow.node())return;const e=this.adminManager.isInAdminMode();this.semanticOptionsRow.style("display",e?null:"none")}setSemanticThresholdValue(e){const t=this.semanticThresholdInput.node();t&&(t.value=String(e))}setWeakenSurprisalColor(e){const t=this.weakenSurprisalColorToggle.node();t&&(t.checked=e)}handleAdminModeClick(){if(this.adminManager.isInAdminMode())return this.adminManager.clearAdminTokenAndNotify(),void window.location.reload();D({title:"Admin Mode",content:e=>{const t=e.append("div").attr("class","dialog-form-container");t.append("label").attr("class","dialog-label").text("Please enter admin token:");const n=t.append("input").attr("type","password").attr("class","dialog-input").attr("placeholder","INFORADAR_ADMIN_TOKEN");return{getValue:()=>n.node()?.value?.trim()||"",validate:()=>(n.node()?.value?.trim()||"").length>0,focus:()=>{const e=n.node();e&&e.focus()}}},onConfirm:async e=>{const{success:t,message:n}=await this.adminManager.setAdminTokenAndNotify(e);t?(this.api.setAdminToken(this.adminManager.getAdminToken()),window.location.reload()):N(p("Error"),n||"Admin token verification failed.")},onCancel:()=>{},confirmText:"Enter",cancelText:p("Cancel"),width:"clamp(300px, 90vw, 420px)"})}}("#settings_btn","#settings_menu","#admin_mode_btn",Dn,In,void 0,void 0,yi,vi,"common")}},n={};function i(e){var o=n[e];if(void 0!==o)return o.exports;var s=n[e]={exports:{}};return t[e](s,s.exports,i),s.exports}i.m=t,e=[],i.O=(t,n,o,s)=>{if(!n){var a=1/0;for(d=0;d<e.length;d++){for(var[n,o,s]=e[d],r=!0,l=0;l<n.length;l++)(!1&s||a>=s)&&Object.keys(i.O).every(e=>i.O[e](n[l]))?n.splice(l--,1):(r=!1,s<a&&(a=s));if(r){e.splice(d--,1);var c=o();void 0!==c&&(t=c)}}return t}s=s||0;for(var d=e.length;d>0&&e[d-1][2]>s;d--)e[d]=e[d-1];e[d]=[n,o,s]},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.j=210,(()=>{var e={210:0};i.O.j=t=>0===e[t];var t=(t,n)=>{var o,s,[a,r,l]=n,c=0;if(a.some(t=>0!==e[t])){for(o in r)i.o(r,o)&&(i.m[o]=r[o]);if(l)var d=l(i)}for(t&&t(n);c<a.length;c++)s=a[c],i.o(e,s)&&e[s]&&e[s][0](),e[s]=0;return i.O(d)},n=self.webpackChunkinforadar=self.webpackChunkinforadar||[];
1n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))})();var o=i.O(void 0,[121],()=>i(5101));o=i.O(o)})();
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.