PageSourceSearch

https://info-lens.app/attribution.js

js info-lens.app collected 2026-10-02 01:13:54 UTC 173,004 bytes, 1 lines download raw bytes

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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),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.