stratagate-dsh 0.3.52 → 0.3.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -322,7 +322,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
322
322
  \r
323
323
  `,STAR_REPOSITORY_URL="https://github.com/diqierjia/StrataGate-AgentMemory",ISSUE_URL=STAR_REPOSITORY_URL+"/issues/new",DISCUSSION_URL=STAR_REPOSITORY_URL+"/discussions/categories/q-a",FEEDBACK_AI_PROMPT="\u8BF7\u6839\u636E\u5F53\u524D\u4F1A\u8BDD\u4E2D StrataGate \u63D2\u4EF6\u7684\u6545\u969C\u3001\u4F7F\u7528\u7591\u95EE\u6216\u6539\u8FDB\u5EFA\u8BAE\u6574\u7406\u53CD\u9988\u3002\u53EA\u7528\u5DF2\u77E5\u4E8B\u5B9E\uFF0C\u4E0D\u8981\u731C\u6D4B\uFF0C\u672A\u77E5\u7559\u7A7A\uFF0C\u53BB\u9664\u51ED\u636E\u3002\u8C03\u7528 feedback_prepare \u4FDD\u5B58\u672C\u5730\u8349\u7A3F\uFF1B\u65B0\u95EE\u9898\u4F20 new_draft=true\u3002\u8BCA\u65AD\u7531\u7A0B\u5E8F\u81EA\u52A8\u8865\u5145\u3002\u7ED9\u6211\u201C\u6253\u5F00\u53CD\u9988\u8349\u7A3F\u201D\u7684\u94FE\u63A5\uFF0C\u6211\u4F1A\u68C0\u67E5\u540E\u624B\u52A8\u53D1\u90AE\u4EF6\u3002",FEEDBACK_SETTINGS_ID="stratagate-memory",FEEDBACK_VIEW_ID="feedback",MEMORY_PANEL_ID="stratagate-memory",SIDEBAR_PROMPT_STORAGE_KEY="stratagate-dsh.sidebar-prompt.v1",SIDEBAR_PROMPT_STYLES=".sg-sidebar-panel-icon{display:block;flex-shrink:0}.sg-sidebar-placement-prompt{display:inline-flex;align-items:center;gap:8px;flex-wrap:wrap;max-width:100%;font-size:11px;line-height:1.5;color:var(--sg-muted)}.sg-sidebar-placement-text{min-width:0}.sg-memory .sg-sidebar-placement-action{padding:0;border:0;background:transparent;color:var(--sg-accent);font-size:11px;line-height:1.5;cursor:pointer;white-space:nowrap}.sg-sidebar-placement-action:hover{text-decoration:underline}.sg-memory .sg-sidebar-placement-close{display:inline-grid;place-items:center;width:20px;height:20px;flex:none;padding:0;border:0;border-radius:4px;background:transparent;color:var(--sg-muted);font-size:15px;line-height:1;cursor:pointer}.sg-sidebar-placement-close:hover{background:var(--sg-soft);color:var(--sg-text)}",pendingFeedbackNavigation=null,feedbackNavigationListeners=new Set;function setFeedbackNavigation(state){pendingFeedbackNavigation=state;for(let listener of feedbackNavigationListeners)listener(state);feedbackNavigationListeners.size&&(pendingFeedbackNavigation=null)}function FeedbackSettingsPage(props){let[navigationState,setNavigationState]=React.useState(()=>pendingFeedbackNavigation);return React.useEffect(()=>(feedbackNavigationListeners.add(setNavigationState),pendingFeedbackNavigation&&setNavigationState(pendingFeedbackNavigation),pendingFeedbackNavigation=null,()=>feedbackNavigationListeners.delete(setNavigationState)),[]),h(MemoryPage,{...props,navigationState:navigationState||props.navigationState})}let ISSUE_BODY_HINT=`> \u8BF7\u5728\u4E0B\u65B9\u7C98\u8D34 StrataGate \u53CD\u9988\u62A5\u544A\uFF08Ctrl+V / \u2318V\uFF09\uFF0C\u68C0\u67E5\u540E\u63D0\u4EA4\u3002\u82E5\u65E0\u6CD5\u7C98\u8D34\uFF0C\u8BF7\u8FD4\u56DE StrataGate \u624B\u52A8\u590D\u5236\u62A5\u544A\u3002
324
324
 
325
- `,STRATAGATE_CLIENT_VERSION="0.3.52",MEMORY_CITATIONS_KIND="stratagate-memory-citations",MEMORY_RETRIEVAL_TOOLS=new Set(["memory_search_events","memory_search_graph","memory_expand_graph_node","memory_search_elements","memory_search_raw","memory_get_blocks","memory_expand_block","memory_expand_event","memory_expand_element"]);function readFeedbackDeepLink(locationRef=window.location){let params=new URLSearchParams(String(locationRef?.search||""));if(params.get("settings")!==FEEDBACK_SETTINGS_ID||params.get("stratagateView")!==FEEDBACK_VIEW_ID)return null;let namespace=String(params.get("namespace")||"").trim();return namespace?{namespace}:null}function readFeedbackNavigationState(state){if(!state||state.view!==FEEDBACK_VIEW_ID)return null;let namespace=String(state.namespace||"").trim();return namespace?{namespace}:null}function readNewFeedbackNavigationState(previousState,state){return state===previousState?null:readFeedbackNavigationState(state)}function readGraphNodeNavigationState(state){if(!state||state.view!=="graph-node")return null;let namespace=String(state.namespace||"").trim(),nodeId=String(state.nodeId||"").trim();return namespace&&nodeId?{namespace,nodeId}:null}function readGraphNodeDeepLink(locationRef=window.location){let params=new URLSearchParams(String(locationRef?.search||""));if(params.get("settings")!==FEEDBACK_SETTINGS_ID||params.get("stratagateView")!=="graph-node")return null;let namespace=String(params.get("namespace")||"").trim(),nodeId=String(params.get("nodeId")||"").trim();return namespace&&nodeId?{namespace,nodeId}:null}function consumeFeedbackDeepLink(locationRef=window.location,historyRef=window.history){let params=new URLSearchParams(String(locationRef?.search||""));params.delete("settings"),params.delete("stratagateView"),params.delete("namespace");let search=params.toString(),next2=String(locationRef?.pathname||"/")+(search?"?"+search:"")+String(locationRef?.hash||"");return historyRef?.replaceState?.(historyRef.state,"",next2),next2}function consumeGraphNodeDeepLink(locationRef=window.location,historyRef=window.history){let params=new URLSearchParams(String(locationRef?.search||""));params.delete("settings"),params.delete("stratagateView"),params.delete("namespace"),params.delete("nodeId");let search=params.toString(),next2=String(locationRef?.pathname||"/")+(search?"?"+search:"")+String(locationRef?.hash||"");return historyRef?.replaceState?.(historyRef.state,"",next2),next2}function isDesktopFeedbackSurface(locationRef){try{let url=new URL(String(locationRef?.href||""));return url.protocol==="dsh-app:"&&url.hostname==="app"}catch{return!1}}function desktopFeedbackOrigin(value){try{let url=new URL(String(value||""));return url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)&&!url.username&&!url.password&&url.pathname==="/"&&!url.search&&!url.hash?url.origin:""}catch{return""}}function feedbackAnchorTarget(target,locationRef){let anchor=target?.closest?.("a[href]")||target?.parentElement?.closest?.("a[href]");if(!anchor)return null;let url;try{url=new URL(String(anchor.getAttribute?.("href")||""),String(locationRef?.href||""))}catch{return null}return!readFeedbackDeepLink(url)||url.pathname!=="/"||url.username||url.password?null:{anchor,url}}function feedbackLinkTarget(target,locationRef=window.location,desktopHostOrigin=""){let match2=feedbackAnchorTarget(target,locationRef);return match2&&(match2.url.origin===String(locationRef?.origin||"")||isDesktopFeedbackSurface(locationRef)&&desktopFeedbackOrigin(desktopHostOrigin)===match2.url.origin)?match2:null}function navigateToFeedback(ctx,targetUrl,locationRef=window.location,allowHttpFallback=!0){let feedback=readFeedbackDeepLink(targetUrl);if(!feedback)return"ignored";let navigation=ctx?.get?.("settingsNavigation");if(typeof navigation?.openSection=="function")return navigation.openSection(FEEDBACK_SETTINGS_ID,{view:FEEDBACK_VIEW_ID,namespace:feedback.namespace}),"host";let shell=ctx?.get?.("slots")?.entries?.("sidebar.settings")?.find(entry=>typeof entry.store?.create=="function")?.store.create();return typeof shell?.actions?.openSection=="function"?(setFeedbackNavigation({view:FEEDBACK_VIEW_ID,namespace:feedback.namespace}),shell.actions.openSection(FEEDBACK_SETTINGS_ID),"host"):(allowHttpFallback&&locationRef.assign(targetUrl.href),"http")}function navigateToGraphNode(ctx,namespace,nodeId,locationRef=window.location,allowHttpFallback=!0){let targetNamespace=String(namespace||"").trim(),targetNodeId=String(nodeId||"").trim();if(!targetNamespace||!targetNodeId)return Promise.resolve(!1);let navigation=ctx?.get?.("settingsNavigation");if(typeof navigation?.openSection!="function"){if(!allowHttpFallback||typeof locationRef?.assign!="function")return Promise.resolve(!1);try{let targetUrl=new URL(String(locationRef.href||""));return targetUrl.searchParams.set("settings",FEEDBACK_SETTINGS_ID),targetUrl.searchParams.set("stratagateView","graph-node"),targetUrl.searchParams.set("namespace",targetNamespace),targetUrl.searchParams.set("nodeId",targetNodeId),locationRef.assign(targetUrl.href),Promise.resolve(!0)}catch{return Promise.resolve(!1)}}try{return Promise.resolve(navigation.openSection(FEEDBACK_SETTINGS_ID,{view:"graph-node",namespace:targetNamespace,nodeId:targetNodeId})).then(result=>result!==!1,()=>!1)}catch{return Promise.resolve(!1)}}function installFeedbackLinkNavigation(ctx,documentRef=document,locationRef=window.location){let desktop=isDesktopFeedbackSurface(locationRef),active=!0,desktopHostOrigin="",bootPending=desktop&&typeof window.dshDesktopBoot?.ready=="function",replayingAnchor=null,bootReady=bootPending?Promise.resolve().then(()=>window.dshDesktopBoot.ready()).then(boot=>{active&&(desktopHostOrigin=desktopFeedbackOrigin(boot?.streamBaseUrl))}).catch(()=>{}).finally(()=>{bootPending=!1}):Promise.resolve(),takeClick=event3=>{event3.preventDefault(),event3.stopPropagation()},onClick=event3=>{if(event3.defaultPrevented||typeof event3.button=="number"&&event3.button!==0||event3.metaKey||event3.ctrlKey||event3.shiftKey||event3.altKey)return;let candidate=feedbackAnchorTarget(event3.target,locationRef);if(!candidate||candidate.anchor===replayingAnchor)return;let match2=feedbackLinkTarget(event3.target,locationRef,desktopHostOrigin);match2?(takeClick(event3),navigateToFeedback(ctx,match2.url,locationRef,!desktop)):bootPending&&desktopFeedbackOrigin(candidate.url.origin)&&(takeClick(event3),bootReady.then(()=>{if(active)if(candidate.url.origin===desktopHostOrigin)navigateToFeedback(ctx,candidate.url,locationRef,!1);else{replayingAnchor=candidate.anchor;try{candidate.anchor.click()}finally{replayingAnchor=null}}}))};return documentRef.addEventListener("click",onClick,!0),()=>{active=!1,documentRef.removeEventListener("click",onClick,!0)}}function exactInteractiveControl(labels,documentRef){let selector='button,[role="button"],[role="tab"],a',matches33=element3=>{let values=[element3.getAttribute?.("aria-label"),element3.getAttribute?.("title"),element3.textContent].map(value=>String(value||"").trim());return labels.some(label=>values.includes(label))},visible=element3=>!element3.hidden&&element3.getAttribute?.("aria-hidden")!=="true"&&(typeof element3.getClientRects!="function"||element3.getClientRects().length>0),direct=Array.from(documentRef.querySelectorAll(selector)).find(element3=>visible(element3)&&matches33(element3));if(direct)return direct;for(let element3 of Array.from(documentRef.querySelectorAll("*"))){if(String(element3.textContent||"").trim()!==labels[0])continue;let control=element3.closest?.(selector)||element3;if(visible(control)&&typeof control.click=="function")return control}return null}function openLegacyFeedbackDeepLink(documentRef=document){let observer=null,timer=null,settingsClicked=!1,sectionClicked=!1,cleanup=()=>{observer?.disconnect?.(),timer!==null&&window.clearTimeout(timer)},attempt=()=>{if(documentRef.querySelector('[data-testid="stratagate-memory-ui"]')){cleanup();return}if(!sectionClicked){let section=exactInteractiveControl(["StrataGate-AgentMemory"],documentRef);if(section){sectionClicked=!0,section.click();return}}if(!settingsClicked){let settings=exactInteractiveControl(["\u8BBE\u7F6E","Settings"],documentRef);settings&&(settingsClicked=!0,settings.click())}},Observer=window.MutationObserver||globalThis.MutationObserver;return typeof Observer=="function"&&(observer=new Observer(attempt),observer.observe(documentRef.documentElement||documentRef.body,{childList:!0,subtree:!0})),timer=window.setTimeout(cleanup,12e3),attempt(),cleanup}function openFeedbackDeepLink(ctx,documentRef=document,locationRef=window.location,historyRef=window.history){if(!readFeedbackDeepLink(locationRef))return()=>{};if(navigateToFeedback(ctx,locationRef,locationRef,!1)==="host")return consumeFeedbackDeepLink(locationRef,historyRef),()=>{};let legacyCleanup=()=>{},timer=window.setTimeout(()=>{legacyCleanup=openLegacyFeedbackDeepLink(documentRef)},250);return ctx?.inject?.(["settingsNavigation"],scope=>{navigateToFeedback(scope,locationRef,locationRef,!1)==="host"&&(window.clearTimeout(timer),legacyCleanup(),consumeFeedbackDeepLink(locationRef,historyRef))}),()=>{window.clearTimeout(timer),legacyCleanup()}}function openGraphNodeDeepLink(ctx,documentRef=document,locationRef=window.location,historyRef=window.history){let graphLink=readGraphNodeDeepLink(locationRef);if(!graphLink)return()=>{};if(typeof ctx?.get?.("settingsNavigation")?.openSection=="function")return navigateToGraphNode(ctx,graphLink.namespace,graphLink.nodeId,locationRef,!1).then(opened=>{opened&&consumeGraphNodeDeepLink(locationRef,historyRef)}),()=>{};let legacyCleanup=()=>{},timer=window.setTimeout(()=>{legacyCleanup=openLegacyFeedbackDeepLink(documentRef)},250);return ctx?.inject?.(["settingsNavigation"],scope=>{navigateToGraphNode(scope,graphLink.namespace,graphLink.nodeId,locationRef,!1).then(opened=>{opened&&(window.clearTimeout(timer),legacyCleanup(),consumeGraphNodeDeepLink(locationRef,historyRef))})}),()=>{window.clearTimeout(timer),legacyCleanup()}}let eventDetailCss=`
325
+ `,STRATAGATE_CLIENT_VERSION="0.3.54",MEMORY_CITATIONS_KIND="stratagate-memory-citations",MEMORY_RETRIEVAL_TOOLS=new Set(["memory_search_events","memory_search_graph","memory_expand_graph_node","memory_search_elements","memory_search_raw","memory_get_blocks","memory_expand_block","memory_expand_event","memory_expand_element"]);function readFeedbackDeepLink(locationRef=window.location){let params=new URLSearchParams(String(locationRef?.search||""));if(params.get("settings")!==FEEDBACK_SETTINGS_ID||params.get("stratagateView")!==FEEDBACK_VIEW_ID)return null;let namespace=String(params.get("namespace")||"").trim();return namespace?{namespace}:null}function readFeedbackNavigationState(state){if(!state||state.view!==FEEDBACK_VIEW_ID)return null;let namespace=String(state.namespace||"").trim();return namespace?{namespace}:null}function readNewFeedbackNavigationState(previousState,state){return state===previousState?null:readFeedbackNavigationState(state)}function readGraphNodeNavigationState(state){if(!state||state.view!=="graph-node")return null;let namespace=String(state.namespace||"").trim(),nodeId=String(state.nodeId||"").trim();return namespace&&nodeId?{namespace,nodeId}:null}function readGraphNodeDeepLink(locationRef=window.location){let params=new URLSearchParams(String(locationRef?.search||""));if(params.get("settings")!==FEEDBACK_SETTINGS_ID||params.get("stratagateView")!=="graph-node")return null;let namespace=String(params.get("namespace")||"").trim(),nodeId=String(params.get("nodeId")||"").trim();return namespace&&nodeId?{namespace,nodeId}:null}function consumeFeedbackDeepLink(locationRef=window.location,historyRef=window.history){let params=new URLSearchParams(String(locationRef?.search||""));params.delete("settings"),params.delete("stratagateView"),params.delete("namespace");let search=params.toString(),next2=String(locationRef?.pathname||"/")+(search?"?"+search:"")+String(locationRef?.hash||"");return historyRef?.replaceState?.(historyRef.state,"",next2),next2}function consumeGraphNodeDeepLink(locationRef=window.location,historyRef=window.history){let params=new URLSearchParams(String(locationRef?.search||""));params.delete("settings"),params.delete("stratagateView"),params.delete("namespace"),params.delete("nodeId");let search=params.toString(),next2=String(locationRef?.pathname||"/")+(search?"?"+search:"")+String(locationRef?.hash||"");return historyRef?.replaceState?.(historyRef.state,"",next2),next2}function isDesktopFeedbackSurface(locationRef){try{let url=new URL(String(locationRef?.href||""));return url.protocol==="dsh-app:"&&url.hostname==="app"}catch{return!1}}function desktopFeedbackOrigin(value){try{let url=new URL(String(value||""));return url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)&&!url.username&&!url.password&&url.pathname==="/"&&!url.search&&!url.hash?url.origin:""}catch{return""}}function feedbackAnchorTarget(target,locationRef){let anchor=target?.closest?.("a[href]")||target?.parentElement?.closest?.("a[href]");if(!anchor)return null;let url;try{url=new URL(String(anchor.getAttribute?.("href")||""),String(locationRef?.href||""))}catch{return null}return!readFeedbackDeepLink(url)||url.pathname!=="/"||url.username||url.password?null:{anchor,url}}function feedbackLinkTarget(target,locationRef=window.location,desktopHostOrigin=""){let match2=feedbackAnchorTarget(target,locationRef);return match2&&(match2.url.origin===String(locationRef?.origin||"")||isDesktopFeedbackSurface(locationRef)&&desktopFeedbackOrigin(desktopHostOrigin)===match2.url.origin)?match2:null}function navigateToFeedback(ctx,targetUrl,locationRef=window.location,allowHttpFallback=!0){let feedback=readFeedbackDeepLink(targetUrl);if(!feedback)return"ignored";let navigation=ctx?.get?.("settingsNavigation");if(typeof navigation?.openSection=="function")return navigation.openSection(FEEDBACK_SETTINGS_ID,{view:FEEDBACK_VIEW_ID,namespace:feedback.namespace}),"host";let shell=ctx?.get?.("slots")?.entries?.("sidebar.settings")?.find(entry=>typeof entry.store?.create=="function")?.store.create();return typeof shell?.actions?.openSection=="function"?(setFeedbackNavigation({view:FEEDBACK_VIEW_ID,namespace:feedback.namespace}),shell.actions.openSection(FEEDBACK_SETTINGS_ID),"host"):(allowHttpFallback&&locationRef.assign(targetUrl.href),"http")}function navigateToGraphNode(ctx,namespace,nodeId,locationRef=window.location,allowHttpFallback=!0){let targetNamespace=String(namespace||"").trim(),targetNodeId=String(nodeId||"").trim();if(!targetNamespace||!targetNodeId)return Promise.resolve(!1);let navigation=ctx?.get?.("settingsNavigation");if(typeof navigation?.openSection!="function"){if(!allowHttpFallback||typeof locationRef?.assign!="function")return Promise.resolve(!1);try{let targetUrl=new URL(String(locationRef.href||""));return targetUrl.searchParams.set("settings",FEEDBACK_SETTINGS_ID),targetUrl.searchParams.set("stratagateView","graph-node"),targetUrl.searchParams.set("namespace",targetNamespace),targetUrl.searchParams.set("nodeId",targetNodeId),locationRef.assign(targetUrl.href),Promise.resolve(!0)}catch{return Promise.resolve(!1)}}try{return Promise.resolve(navigation.openSection(FEEDBACK_SETTINGS_ID,{view:"graph-node",namespace:targetNamespace,nodeId:targetNodeId})).then(result=>result!==!1,()=>!1)}catch{return Promise.resolve(!1)}}function installFeedbackLinkNavigation(ctx,documentRef=document,locationRef=window.location){let desktop=isDesktopFeedbackSurface(locationRef),active=!0,desktopHostOrigin="",bootPending=desktop&&typeof window.dshDesktopBoot?.ready=="function",replayingAnchor=null,bootReady=bootPending?Promise.resolve().then(()=>window.dshDesktopBoot.ready()).then(boot=>{active&&(desktopHostOrigin=desktopFeedbackOrigin(boot?.streamBaseUrl))}).catch(()=>{}).finally(()=>{bootPending=!1}):Promise.resolve(),takeClick=event3=>{event3.preventDefault(),event3.stopPropagation()},onClick=event3=>{if(event3.defaultPrevented||typeof event3.button=="number"&&event3.button!==0||event3.metaKey||event3.ctrlKey||event3.shiftKey||event3.altKey)return;let candidate=feedbackAnchorTarget(event3.target,locationRef);if(!candidate||candidate.anchor===replayingAnchor)return;let match2=feedbackLinkTarget(event3.target,locationRef,desktopHostOrigin);match2?(takeClick(event3),navigateToFeedback(ctx,match2.url,locationRef,!desktop)):bootPending&&desktopFeedbackOrigin(candidate.url.origin)&&(takeClick(event3),bootReady.then(()=>{if(active)if(candidate.url.origin===desktopHostOrigin)navigateToFeedback(ctx,candidate.url,locationRef,!1);else{replayingAnchor=candidate.anchor;try{candidate.anchor.click()}finally{replayingAnchor=null}}}))};return documentRef.addEventListener("click",onClick,!0),()=>{active=!1,documentRef.removeEventListener("click",onClick,!0)}}function exactInteractiveControl(labels,documentRef){let selector='button,[role="button"],[role="tab"],a',matches33=element3=>{let values=[element3.getAttribute?.("aria-label"),element3.getAttribute?.("title"),element3.textContent].map(value=>String(value||"").trim());return labels.some(label=>values.includes(label))},visible=element3=>!element3.hidden&&element3.getAttribute?.("aria-hidden")!=="true"&&(typeof element3.getClientRects!="function"||element3.getClientRects().length>0),direct=Array.from(documentRef.querySelectorAll(selector)).find(element3=>visible(element3)&&matches33(element3));if(direct)return direct;for(let element3 of Array.from(documentRef.querySelectorAll("*"))){if(String(element3.textContent||"").trim()!==labels[0])continue;let control=element3.closest?.(selector)||element3;if(visible(control)&&typeof control.click=="function")return control}return null}function openLegacyFeedbackDeepLink(documentRef=document){let observer=null,timer=null,settingsClicked=!1,sectionClicked=!1,cleanup=()=>{observer?.disconnect?.(),timer!==null&&window.clearTimeout(timer)},attempt=()=>{if(documentRef.querySelector('[data-testid="stratagate-memory-ui"]')){cleanup();return}if(!sectionClicked){let section=exactInteractiveControl(["StrataGate-AgentMemory"],documentRef);if(section){sectionClicked=!0,section.click();return}}if(!settingsClicked){let settings=exactInteractiveControl(["\u8BBE\u7F6E","Settings"],documentRef);settings&&(settingsClicked=!0,settings.click())}},Observer=window.MutationObserver||globalThis.MutationObserver;return typeof Observer=="function"&&(observer=new Observer(attempt),observer.observe(documentRef.documentElement||documentRef.body,{childList:!0,subtree:!0})),timer=window.setTimeout(cleanup,12e3),attempt(),cleanup}function openFeedbackDeepLink(ctx,documentRef=document,locationRef=window.location,historyRef=window.history){if(!readFeedbackDeepLink(locationRef))return()=>{};if(navigateToFeedback(ctx,locationRef,locationRef,!1)==="host")return consumeFeedbackDeepLink(locationRef,historyRef),()=>{};let legacyCleanup=()=>{},timer=window.setTimeout(()=>{legacyCleanup=openLegacyFeedbackDeepLink(documentRef)},250);return ctx?.inject?.(["settingsNavigation"],scope=>{navigateToFeedback(scope,locationRef,locationRef,!1)==="host"&&(window.clearTimeout(timer),legacyCleanup(),consumeFeedbackDeepLink(locationRef,historyRef))}),()=>{window.clearTimeout(timer),legacyCleanup()}}function openGraphNodeDeepLink(ctx,documentRef=document,locationRef=window.location,historyRef=window.history){let graphLink=readGraphNodeDeepLink(locationRef);if(!graphLink)return()=>{};if(typeof ctx?.get?.("settingsNavigation")?.openSection=="function")return navigateToGraphNode(ctx,graphLink.namespace,graphLink.nodeId,locationRef,!1).then(opened=>{opened&&consumeGraphNodeDeepLink(locationRef,historyRef)}),()=>{};let legacyCleanup=()=>{},timer=window.setTimeout(()=>{legacyCleanup=openLegacyFeedbackDeepLink(documentRef)},250);return ctx?.inject?.(["settingsNavigation"],scope=>{navigateToGraphNode(scope,graphLink.namespace,graphLink.nodeId,locationRef,!1).then(opened=>{opened&&(window.clearTimeout(timer),legacyCleanup(),consumeGraphNodeDeepLink(locationRef,historyRef))})}),()=>{window.clearTimeout(timer),legacyCleanup()}}let eventDetailCss=`
326
326
  .sg-event-metadata{display:flex;align-items:center;gap:7px 16px;flex-wrap:wrap;margin-top:8px;color:var(--sg-muted);font-size:12px;line-height:1.45}.sg-event-metadata-item{display:inline-flex;align-items:center;gap:5px;min-width:0}.sg-event-metadata b{color:var(--sg-muted);font-weight:620}.sg-event-participants{display:inline-flex;align-items:center;gap:5px;flex-wrap:wrap}.sg-event-metadata .sg-entity-pill{padding:2px 7px}.sg-entity-pill-static{cursor:default;opacity:.82}.sg-entity-pill-static:hover{transform:none!important;background:transparent!important}.sg-event-section{display:grid;gap:9px;padding:17px 0;border-bottom:1px solid var(--sg-border)}.sg-event-section-title{margin:0;color:var(--sg-text);font-size:14px;font-weight:730}.sg-event-memory-copy{max-width:65ch;margin:0;color:var(--sg-text);font-size:14px;line-height:1.72;white-space:pre-wrap;overflow-wrap:anywhere;text-wrap:pretty}.sg-event-weight-section{gap:0}
327
327
  .sg-weight-header{display:flex;align-items:baseline;justify-content:space-between;gap:12px;margin-bottom:9px}.sg-weight-header .sg-section-title,.sg-long-detail .sg-weight-header h3{margin:0}.sg-weight-metrics{display:grid!important;grid-template-columns:1fr!important;gap:0!important;margin:0 0 13px!important}.sg-weight-metric{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:14px;min-width:0;padding:7px 2px!important;border-bottom:1px solid color-mix(in srgb,var(--sg-border) 72%,transparent);border-radius:0!important;background:transparent!important}.sg-weight-metric:last-child{border-bottom:0}.sg-weight-metric>span:first-child{color:var(--sg-muted);font-size:12px}.sg-weight-metric strong{margin:0!important;color:var(--sg-text);font-size:15px!important;font-weight:740;font-variant-numeric:tabular-nums;white-space:nowrap}.sg-weight-value{display:inline-flex!important;align-items:center;justify-content:flex-end;gap:6px;color:var(--sg-text)!important}
328
328
  .sg-info-disclosure{position:relative;display:inline-flex}.sg-info-trigger{display:grid;place-items:center;width:19px;height:19px;padding:0;border:0;border-radius:50%;background:transparent;color:var(--sg-muted);font-size:13px;line-height:1;cursor:pointer}.sg-info-trigger:hover,.sg-info-trigger[aria-expanded="true"]{background:var(--sg-soft);color:var(--sg-text)}.sg-info-popover{position:absolute;right:0;top:calc(100% + 7px);z-index:20;width:min(320px,calc(100vw - 40px));padding:13px 14px;border:1px solid color-mix(in srgb,var(--sg-accent) 20%,var(--sg-border));border-radius:9px;background:var(--sg-page);color:var(--sg-text);box-shadow:0 14px 36px color-mix(in srgb,var(--sg-text) 18%,transparent);font-size:12px;line-height:1.58;text-align:left}.sg-info-title{display:block;margin-bottom:7px;font-size:13px}.sg-info-popover p{margin:0;color:var(--sg-muted)}.sg-info-popover p+p{margin-top:7px}.sg-adoption-history{display:grid;gap:10px;margin:0;padding:0;list-style:none;counter-reset:history}.sg-adoption-history li{display:grid;gap:1px;padding-bottom:9px;border-bottom:1px solid var(--sg-border)}.sg-adoption-history li:last-child{padding-bottom:0;border-bottom:0}.sg-adoption-history time,.sg-adoption-history span{color:var(--sg-muted)}.sg-floor-table{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:4px 14px;margin:10px 0 0;padding-top:9px;border-top:1px solid var(--sg-border)}.sg-floor-table dt,.sg-floor-table dd{margin:0;color:var(--sg-muted)}.sg-floor-table .current{color:var(--sg-accent);font-weight:720}
@@ -704,59 +704,195 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
704
704
  .sg-memory .sg-tab.active:after{left:2px;right:2px}
705
705
  }
706
706
 
707
- /* \u603B\u89C8\uFF1A\u5927\u6570\u5B57 + \u7CBE\u7B80\u8BB0\u5FC6\u67F1 + \u957F\u671F\u8BB0\u5FC6\u70ED\u529B\u683C */
708
- .sg-ov{display:grid;gap:22px;min-width:0}
709
- .sg-ov-top{display:grid;grid-template-columns:minmax(180px,240px) minmax(0,1fr);gap:36px;align-items:start}
710
- .sg-ov-big{display:flex;align-items:flex-end;gap:8px}
711
- .sg-ov-big b{font:400 76px/0.9 var(--sg-serif);letter-spacing:-.03em}
712
- .sg-ov-big .sg-used svg{width:30px;height:24px;margin-bottom:12px}
713
- .sg-ov-stat p{margin:12px 0 0;color:var(--sg-muted);font-size:13px;line-height:1.6}
714
- .sg-ov-empty{color:var(--sg-muted)}
707
+ /* Share the approved top bar across views; keep page-body styling local. */
708
+ .sg-memory-panel{container:sg-memory-host / inline-size}
709
+ .sg-memory.sg-unified-top{
710
+ --sg-top-sans:"Noto Sans SC","Microsoft YaHei","PingFang SC",sans-serif;
711
+ --sg-top-serif:"Noto Serif SC","Times New Roman",serif;
712
+ --sg-overview-unit:clamp(.48px,.05733945cqi,1px);
713
+ --sg-overview-gutter:clamp(16px,2.6087cqi,48px);
714
+ max-width:1920px;padding:calc(30 * var(--sg-overview-unit)) var(--sg-overview-gutter) calc(32 * var(--sg-overview-unit));
715
+ }
716
+ .sg-memory.sg-overview-page{
717
+ --sg-sans:var(--sg-top-sans);--sg-serif:var(--sg-top-serif);
718
+ --sg-ink:color-mix(in srgb,#3d3c38 88%,var(--sg-text));
719
+ --sg-moss:#607f4e;--sg-water:#426f9b;--sg-sand:#a98431;
720
+ font-family:var(--sg-sans);
721
+ }
722
+ .sg-unified-top .sg-header-row-primary,.sg-unified-top .sg-tabs{
723
+ --sg-serif:var(--sg-top-serif);
724
+ --sg-ink:color-mix(in srgb,#3d3c38 88%,var(--sg-text));
725
+ --sg-moss:#607f4e;--sg-water:#426f9b;--sg-sand:#a98431;
726
+ font-family:var(--sg-top-sans);
727
+ }
728
+ .sg-page-body{display:contents}
729
+ .sg-memory.sg-unified-top:not(.sg-overview-page){padding-bottom:0}
730
+ .sg-unified-top:not(.sg-overview-page) .sg-page-body{
731
+ display:block;container:sg-memory / inline-size;box-sizing:border-box;
732
+ --sg-body-gutter:clamp(16px,2.7523cqi,48px);
733
+ width:min(1200px,calc(100% + 2 * var(--sg-body-gutter)));
734
+ margin-inline:calc((100% - min(1200px,calc(100% + 2 * var(--sg-body-gutter)))) / 2);
735
+ padding:max(6px,calc(62 * var(--sg-overview-unit) - 24px)) 20px 36px;
736
+ }
737
+ .sg-unified-top.sg-settings-page .sg-page-body{container-name:sg-settings}
738
+ @media (max-width:560px){.sg-unified-top:not(.sg-overview-page) .sg-page-body{padding-inline:12px;padding-bottom:26px}}
739
+ .sg-unified-top .sg-header{padding:calc(6 * var(--sg-overview-unit)) 0 0}
740
+ .sg-unified-top .sg-header-row{padding:0}
741
+ .sg-unified-top .sg-brand{gap:calc(20 * var(--sg-overview-unit))}
742
+ .sg-unified-top .sg-logo{width:calc(46 * var(--sg-overview-unit));height:calc(46 * var(--sg-overview-unit))}
743
+ .sg-unified-top .sg-brand-title{gap:calc(16 * var(--sg-overview-unit));flex-wrap:nowrap}
744
+ .sg-unified-top .sg-brand-name{font-family:var(--sg-serif);font-size:calc(34 * var(--sg-overview-unit));font-weight:600}
745
+ .sg-unified-top .sg-brand-version{font-size:calc(24 * var(--sg-overview-unit));font-weight:400}
746
+ .sg-unified-top .sg-header-usage{gap:calc(16 * var(--sg-overview-unit));font-size:calc(20 * var(--sg-overview-unit))}
747
+ .sg-unified-top .sg-header-end{gap:calc(16 * var(--sg-overview-unit))}
748
+ .sg-unified-top .sg-project{min-height:calc(56 * var(--sg-overview-unit));min-width:calc(210 * var(--sg-overview-unit));padding:0 calc(14 * var(--sg-overview-unit));gap:calc(12 * var(--sg-overview-unit));font-size:calc(24 * var(--sg-overview-unit));border-radius:calc(10 * var(--sg-overview-unit))}
749
+ .sg-unified-top .sg-project-label{display:none}
750
+ .sg-unified-top .sg-project-select{flex:1;width:auto;max-width:20ch;font-size:calc(24 * var(--sg-overview-unit));font-weight:400}
751
+ .sg-unified-top .sg-ghstar{height:calc(56 * var(--sg-overview-unit));min-width:calc(220 * var(--sg-overview-unit));font-size:calc(24 * var(--sg-overview-unit));border-radius:calc(10 * var(--sg-overview-unit));color:color-mix(in srgb,var(--sg-text) 45%,var(--sg-muted))}
752
+ .sg-unified-top .sg-ghstar:hover{color:var(--sg-text)}
753
+ .sg-unified-top .sg-ghstar-label,.sg-unified-top .sg-ghstar-count{padding:0 calc(18 * var(--sg-overview-unit))}
754
+ .sg-unified-top .sg-ghstar-label{flex:1;justify-content:center;gap:calc(12 * var(--sg-overview-unit))}
755
+ .sg-unified-top .sg-ghstar-icon{width:calc(27 * var(--sg-overview-unit));height:calc(27 * var(--sg-overview-unit))}
756
+ .sg-unified-top .sg-ghstar-count{min-width:calc(82 * var(--sg-overview-unit));justify-content:center;font-family:inherit}
757
+ .sg-unified-top .sg-tabs{gap:calc(24 * var(--sg-overview-unit));margin:calc(22 * var(--sg-overview-unit)) calc(-1 * var(--sg-overview-gutter)) 0;padding:0 var(--sg-overview-gutter)}
758
+ .sg-unified-top .sg-tab{gap:calc(12 * var(--sg-overview-unit));padding:calc(14 * var(--sg-overview-unit)) calc(14 * var(--sg-overview-unit)) calc(20 * var(--sg-overview-unit));font-size:calc(26 * var(--sg-overview-unit));color:color-mix(in srgb,var(--sg-text) 35%,var(--sg-muted))}
759
+ .sg-unified-top .sg-tab.active{color:var(--sg-text)}
760
+ .sg-unified-top .sg-tab-swatch{width:calc(17 * var(--sg-overview-unit));height:calc(17 * var(--sg-overview-unit));border-radius:3px}
761
+ /* Native control/readability floors need less surrounding space as the
762
+ panel narrows; retain the original spacing at the reference width. */
763
+ .sg-overview-page .sg-view{padding-top:max(6px,calc(62 * var(--sg-overview-unit) - 24px))}
764
+ .sg-overview-page .sg-footer{margin:max(12px,calc(50 * var(--sg-overview-unit) - 11px)) calc(-1 * var(--sg-overview-gutter)) 0;padding:calc(26 * var(--sg-overview-unit)) var(--sg-overview-gutter) 0;font-size:calc(23 * var(--sg-overview-unit));flex-wrap:wrap}
765
+ .sg-overview-page .sg-footer-links{display:inline-flex;align-items:center;gap:calc(8 * var(--sg-overview-unit));flex-wrap:wrap}
766
+ .sg-overview-page .sg-footer a{color:inherit;text-decoration:none}
767
+ .sg-overview-page .sg-footer a:hover{text-decoration:underline}
768
+ .sg-ov{--sg-bar-width:calc(168 * var(--sg-overview-unit));display:grid;gap:calc(55 * var(--sg-overview-unit));min-width:0}
769
+ .sg-ov-top{display:grid;grid-template-columns:minmax(0,25%) minmax(0,1fr);gap:calc(44 * var(--sg-overview-unit));align-items:start}
770
+ .sg-ov-big{display:flex;align-items:flex-end;gap:calc(14 * var(--sg-overview-unit));min-width:0}
771
+ .sg-ov-big b{font:400 calc(144 * var(--sg-overview-unit))/.925 "Times New Roman",var(--sg-serif);letter-spacing:0}
772
+ .sg-ov-speech{display:block;width:calc(54 * var(--sg-overview-unit));height:calc(48 * var(--sg-overview-unit));flex:none;color:var(--sg-text)}
773
+ .sg-ov-big .sg-ov-speech{margin-bottom:calc(6 * var(--sg-overview-unit))}
774
+ .sg-ov-summary{margin:calc(32 * var(--sg-overview-unit)) 0 0;color:color-mix(in srgb,var(--sg-text) 35%,var(--sg-muted));font-size:calc(24 * var(--sg-overview-unit));line-height:1.6;text-wrap:pretty}
775
+ .sg-memory .sg-ov-status{display:inline-flex;align-items:center;gap:calc(14 * var(--sg-overview-unit));max-width:100%;margin:calc(22 * var(--sg-overview-unit)) 0 0;padding:0;border:0;background:none;color:var(--sg-muted);font-size:calc(24 * var(--sg-overview-unit));line-height:1.5;text-align:left;cursor:pointer}
776
+ .sg-ov-status:hover{color:var(--sg-text)}
777
+ .sg-runtime-dot{display:inline-block;flex:none;width:13px;height:13px;border-radius:50%;background:var(--sg-muted)}
778
+ .sg-unified-top .sg-runtime-dot{width:calc(13 * var(--sg-overview-unit));height:calc(13 * var(--sg-overview-unit))}
779
+ .sg-runtime-dot[data-state="ok"]{background:#2d8b57}
780
+ .sg-runtime-dot[data-state="processing"],.sg-runtime-dot[data-state="warning"]{background:#a98431}
781
+ .sg-runtime-dot[data-state="failed"]{background:var(--sg-danger)}
782
+ .sg-project .sg-runtime-dot{width:12px;height:12px}
783
+ .sg-unified-top .sg-project .sg-runtime-dot{width:calc(12 * var(--sg-overview-unit));height:calc(12 * var(--sg-overview-unit))}
784
+ .sg-pillar-group{min-width:0}
785
+ .sg-pillar-cap{display:flex;flex-direction:column;align-items:center;gap:calc(10 * var(--sg-overview-unit));width:var(--sg-bar-width);height:calc(92 * var(--sg-overview-unit));padding-top:calc(6 * var(--sg-overview-unit))}
786
+ .sg-pillar-cap:after{content:"";flex:none;width:3px;height:calc(20 * var(--sg-overview-unit));background:var(--sg-text)}
715
787
  .sg-pillar{display:grid;gap:0}
716
- .sg-pillar-row{display:grid;grid-template-columns:72px minmax(0,1fr) auto minmax(108px,auto) minmax(132px,auto);column-gap:12px;align-items:center;width:100%;min-height:46px;padding:0;border:0;border-bottom:1px solid var(--sg-hair);border-radius:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
717
- .sg-pillar-row:hover{background:color-mix(in srgb,var(--sg-soft) 65%,transparent)}
718
- .sg-pillar-row:focus-visible{outline:2px solid var(--sg-accent);outline-offset:-2px;border-radius:6px}
719
- .sg-pillar-tail{display:contents}
720
- .sg-pillar-bar{width:72px;height:34px;border-radius:3px;background:var(--sg-ink);animation:sg-r6-rise .45s both}
721
- .sg-pillar-bar.moss{background:var(--sg-moss)}
722
- .sg-pillar-bar.water{background:var(--sg-water)}
723
- .sg-pillar-bar.sand{background:var(--sg-sand)}
724
- .sg-pillar-bar.lib{height:42px;background:color-mix(in srgb,var(--sg-moss) 12%,transparent);box-shadow:inset 0 0 0 1.5px var(--sg-moss)}
725
- .sg-pillar-gap{height:0;margin:8px 0 8px 84px;border-top:1px dashed var(--sg-border)}
726
- .sg-pillar-name,.sg-pillar-use,.sg-pillar-val,.sg-pillar-when{display:flex;align-items:center;min-width:0;min-height:40px}
727
- .sg-pillar-name b{font-size:14px;font-weight:600;white-space:nowrap}
728
- .sg-pillar-use{justify-content:flex-end}
729
- .sg-pillar-use:empty{visibility:hidden}
730
- .sg-pillar-val{justify-content:flex-end;gap:6px;color:var(--sg-muted);font-size:12px;white-space:nowrap}
731
- .sg-pillar-val b{font:400 22px/1 var(--sg-serif);color:var(--sg-text)}
732
- .sg-pillar-when{justify-content:flex-end;padding-left:14px;color:var(--sg-muted);font-size:12px;white-space:nowrap}
733
- .sg-pillar-key{display:flex;gap:16px;flex-wrap:wrap;margin-top:12px;color:var(--sg-muted);font-size:12px}
734
- .sg-pillar-key span{display:inline-flex;align-items:center;gap:6px}
735
- .sg-heat{padding-top:16px;border-top:1px solid var(--sg-hair)}
736
- .sg-heat-head{display:flex;justify-content:space-between;gap:12px;margin-bottom:10px;color:var(--sg-muted);font-size:12px}
737
- .sg-heat-head span:first-child{display:inline-flex;align-items:center;gap:6px;color:var(--sg-text);font-weight:600}
738
- .sg-heat-grid{display:grid;grid-template-columns:repeat(28,minmax(0,1fr));gap:4px}
739
- .sg-heat-grid i{aspect-ratio:1;border-radius:3px;background:var(--sg-sheet);box-shadow:inset 0 0 0 1px var(--sg-hair)}
740
- .sg-heat-scale{display:flex;justify-content:space-between;margin-top:6px;color:var(--sg-muted);font:11px var(--sg-mono)}
741
- @container sg-memory (max-width:520px){
742
- .sg-ov-top{grid-template-columns:minmax(0,1fr);gap:18px}
743
- .sg-ov-big b{font-size:58px}
744
- .sg-pillar-row{grid-template-columns:44px minmax(0,1fr) auto;column-gap:10px;row-gap:2px;align-items:center;padding:7px 0 8px}
745
- .sg-pillar-bar{width:44px;height:28px}
746
- .sg-pillar-name,.sg-pillar-val,.sg-pillar-when{min-height:0}
747
- .sg-pillar-name{grid-column:2;grid-row:1}
748
- .sg-pillar-name b{white-space:nowrap}
749
- .sg-pillar-use{display:none}
750
- .sg-pillar-tail{grid-column:3;grid-row:1;display:flex;align-items:center;justify-content:flex-end;gap:8px;min-width:0}
751
- .sg-pillar-tail .sg-pillar-use{display:flex;min-height:0}
752
- .sg-pillar-val{white-space:nowrap}
753
- .sg-pillar-when{grid-column:2 / -1;grid-row:2;justify-content:flex-start;padding-left:0;font-size:11.5px;white-space:normal}
754
- .sg-pillar-gap{margin:6px 0;margin-left:0}
755
- .sg-heat-grid{grid-template-columns:repeat(14,minmax(0,1fr))}
788
+ .sg-memory .sg-pillar-row{display:grid;grid-template-columns:var(--sg-bar-width) minmax(0,1fr) auto;column-gap:calc(28 * var(--sg-overview-unit));align-items:center;width:100%;min-height:0;padding:0;border:0;border-radius:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;position:relative}
789
+ .sg-pillar-row:after{content:"";position:absolute;left:var(--sg-bar-width);right:0;bottom:0;border-bottom:1px solid var(--sg-hair);pointer-events:none}
790
+ .sg-memory .sg-pillar-row:hover{background:color-mix(in srgb,var(--sg-soft) 65%,transparent)}
791
+ .sg-pillar-row:focus-visible{outline:2px solid var(--sg-accent);outline-offset:3px}
792
+ .sg-pillar-tail{display:flex;align-items:center;justify-content:flex-end;gap:calc(66 * var(--sg-overview-unit));min-width:0}
793
+ .sg-pillar-bar{display:block;width:100%;height:calc(86 * var(--sg-overview-unit));margin:0 0 calc(6 * var(--sg-overview-unit));border-radius:3px 3px 0 0;background:var(--sg-ink)}
794
+ .sg-pillar-bar.moss{height:calc(66 * var(--sg-overview-unit));background:var(--sg-moss)}
795
+ .sg-pillar-bar.water{height:calc(94 * var(--sg-overview-unit));background:var(--sg-water)}
796
+ .sg-pillar-bar.sand{height:calc(78 * var(--sg-overview-unit));background:var(--sg-sand)}
797
+ .sg-pillar-bar.lib{height:calc(124 * var(--sg-overview-unit));margin:0;border:2px dashed var(--sg-moss);border-radius:3px;background:color-mix(in srgb,var(--sg-moss) 12%,var(--sg-page))}
798
+ .sg-pillar-gap{height:0;margin:calc(16 * var(--sg-overview-unit)) 0 calc(16 * var(--sg-overview-unit)) calc(var(--sg-bar-width) + calc(24 * var(--sg-overview-unit)));border-top:1px dashed var(--sg-border)}
799
+ .sg-pillar-name,.sg-pillar-use,.sg-pillar-val{display:flex;align-items:center;min-width:0}
800
+ .sg-pillar-name b{font-size:calc(28 * var(--sg-overview-unit));font-weight:600;white-space:nowrap}
801
+ .sg-pillar-use:empty{display:none}
802
+ .sg-ov .sg-used{gap:calc(6 * var(--sg-overview-unit));font-family:inherit;font-size:calc(24 * var(--sg-overview-unit));line-height:1.2}
803
+ .sg-ov .sg-used svg{width:calc(23 * var(--sg-overview-unit));height:calc(20 * var(--sg-overview-unit))}
804
+ .sg-pillar-val{justify-content:flex-end;gap:calc(10 * var(--sg-overview-unit));min-width:calc(178 * var(--sg-overview-unit));color:var(--sg-muted);font-size:calc(23 * var(--sg-overview-unit));white-space:nowrap}
805
+ .sg-pillar-val b{font:400 calc(40 * var(--sg-overview-unit))/1 var(--sg-serif);color:var(--sg-text)}
806
+ .sg-pillar-key{display:flex;gap:calc(40 * var(--sg-overview-unit));flex-wrap:wrap;margin-top:calc(30 * var(--sg-overview-unit));color:var(--sg-muted);font-size:calc(23 * var(--sg-overview-unit))}
807
+ .sg-pillar-key>span{display:inline-flex;align-items:center;gap:calc(10 * var(--sg-overview-unit))}
808
+ .sg-pillar-key .sg-sw{width:calc(19 * var(--sg-overview-unit));height:calc(19 * var(--sg-overview-unit));border-radius:3px;background:var(--sg-ink)}
809
+ .sg-pillar-key .sg-sw.lib{border:2px dashed currentColor;background:transparent;box-shadow:none}
810
+ .sg-heat{padding-top:calc(32 * var(--sg-overview-unit));border-top:1px solid var(--sg-hair)}
811
+ .sg-heat-head{display:flex;justify-content:space-between;gap:calc(16 * var(--sg-overview-unit));margin-bottom:calc(22 * var(--sg-overview-unit));color:var(--sg-muted);font-size:calc(23 * var(--sg-overview-unit))}
812
+ .sg-heat-head>span:first-child{display:inline-flex;align-items:center;gap:calc(12 * var(--sg-overview-unit));color:var(--sg-text);font-weight:600}
813
+ .sg-heat-grid{display:grid;grid-template-columns:repeat(28,minmax(0,1fr));gap:calc(8 * var(--sg-overview-unit))}
814
+ .sg-heat-grid i{aspect-ratio:1;border-radius:calc(5 * var(--sg-overview-unit));background:var(--sg-sheet);box-shadow:inset 0 0 0 1px var(--sg-hair)}
815
+ .sg-heat-scale{display:flex;justify-content:space-between;margin-top:calc(10 * var(--sg-overview-unit));color:var(--sg-muted);font-size:calc(21 * var(--sg-overview-unit))}
816
+ /* Keep small text readable without restoring the reference's large
817
+ desktop minimums inside a host sidebar or a scaled application. */
818
+ @container (min-width:721px){
819
+ .sg-unified-top .sg-header-row-primary{min-height:0}
820
+ .sg-unified-top .sg-brand-name{font-size:max(18px,calc(34 * var(--sg-overview-unit)))}
821
+ .sg-unified-top .sg-brand-version{font-size:max(12px,calc(24 * var(--sg-overview-unit)))}
822
+ .sg-unified-top .sg-project{min-height:max(32px,calc(56 * var(--sg-overview-unit)));min-width:max(120px,calc(210 * var(--sg-overview-unit)))}
823
+ .sg-unified-top .sg-project,.sg-unified-top .sg-project-select{font-size:max(13px,calc(24 * var(--sg-overview-unit)))}
824
+ .sg-unified-top .sg-ghstar{height:max(32px,calc(56 * var(--sg-overview-unit)));min-width:max(126px,calc(220 * var(--sg-overview-unit)));font-size:max(13px,calc(24 * var(--sg-overview-unit)))}
825
+ .sg-unified-top .sg-tab{font-size:max(14px,calc(26 * var(--sg-overview-unit)))}
826
+ .sg-ov-summary{font-size:max(12px,calc(24 * var(--sg-overview-unit)))}
827
+ .sg-memory .sg-ov-status{font-size:max(12px,calc(24 * var(--sg-overview-unit)))}
828
+ .sg-pillar-name b{font-size:max(14px,calc(28 * var(--sg-overview-unit)))}
829
+ .sg-pillar-val{font-size:max(12px,calc(23 * var(--sg-overview-unit)))}
830
+ .sg-pillar-key,.sg-ov .sg-used,.sg-heat-head,.sg-overview-page .sg-footer{font-size:max(12px,calc(23 * var(--sg-overview-unit)))}
831
+ .sg-heat-scale{font-size:max(11px,calc(21 * var(--sg-overview-unit)))}
832
+ }
833
+ @container (min-width:721px) and (max-width:820px){
834
+ .sg-ov-top{grid-template-columns:minmax(220px,28%) minmax(0,1fr)}
835
+ }
836
+ @container (max-width:720px){
837
+ .sg-unified-top .sg-runtime-dot{width:10px;height:10px}
838
+ .sg-unified-top .sg-project .sg-runtime-dot{width:9px;height:9px}
839
+ .sg-unified-top .sg-brand{gap:10px}
840
+ .sg-unified-top .sg-logo{width:34px;height:34px}
841
+ .sg-unified-top .sg-brand-title{gap:4px 10px}
842
+ .sg-unified-top .sg-brand-name{font-size:24px}
843
+ .sg-unified-top .sg-brand-version{font-size:12px}
844
+ .sg-unified-top .sg-header-row-primary{flex-wrap:wrap;gap:16px}
845
+ .sg-unified-top .sg-header-usage{gap:10px}
846
+ .sg-unified-top .sg-project{min-width:0;padding:0 9px;gap:8px}
847
+ .sg-unified-top .sg-project,.sg-unified-top .sg-project-select{font-size:14px;min-height:34px}
848
+ .sg-unified-top .sg-header-end{gap:10px}
849
+ .sg-unified-top .sg-ghstar{height:34px;min-width:0;font-size:14px}
850
+ .sg-unified-top .sg-ghstar-label,.sg-unified-top .sg-ghstar-count{padding:0 9px}
851
+ .sg-unified-top .sg-ghstar-label{gap:6px}
852
+ .sg-unified-top .sg-ghstar-count{min-width:0}
853
+ .sg-unified-top .sg-ghstar-icon{width:17px;height:17px}
854
+ .sg-unified-top .sg-tabs{gap:8px;margin-top:20px}
855
+ .sg-unified-top .sg-tab{flex:0 0 auto;gap:6px;padding:12px 6px;font-size:14px}
856
+ .sg-unified-top .sg-tab-swatch{width:11px;height:11px}
857
+ .sg-overview-page .sg-view{padding-top:28px}
858
+ .sg-ov{--sg-bar-width:72px;gap:30px}
859
+ .sg-ov-top{grid-template-columns:minmax(0,1fr);gap:24px}
860
+ .sg-ov-big b{font-size:88px}
861
+ .sg-ov-big .sg-ov-speech{width:38px;height:34px}
862
+ .sg-ov-summary{margin-top:16px;font-size:16px}
863
+ .sg-memory .sg-ov-status{margin-top:18px;gap:10px;font-size:16px}
864
+ .sg-pillar-cap{height:66px;gap:6px}
865
+ .sg-pillar-cap .sg-ov-speech{width:38px;height:34px}
866
+ .sg-pillar-cap:after{height:14px;width:2px}
867
+ .sg-memory .sg-pillar-row{column-gap:14px}
868
+ .sg-pillar-bar{height:56px;margin-bottom:4px}
869
+ .sg-pillar-bar.moss{height:44px}.sg-pillar-bar.water{height:60px}.sg-pillar-bar.sand{height:52px}.sg-pillar-bar.lib{height:80px}
870
+ .sg-pillar-name b{font-size:18px}
871
+ .sg-pillar-tail{gap:12px}
872
+ .sg-pillar-val{gap:5px;min-width:0;font-size:14px}
873
+ .sg-pillar-val b{font-size:28px}
874
+ .sg-ov .sg-used{font-size:14px;gap:4px}
875
+ .sg-ov .sg-used svg{width:16px;height:14px}
876
+ .sg-pillar-gap{margin:12px 0 12px calc(var(--sg-bar-width) + 14px)}
877
+ .sg-pillar-key{gap:20px;margin-top:20px;font-size:14px}
878
+ .sg-pillar-key>span{gap:7px}.sg-pillar-key .sg-sw{width:13px;height:13px}
879
+ .sg-heat{padding-top:22px}.sg-heat-head{margin-bottom:14px;font-size:14px}
880
+ .sg-heat-grid{grid-template-columns:repeat(14,minmax(0,1fr));gap:5px}
756
881
  .sg-heat-grid i:nth-child(-n+14){display:none}
757
882
  .sg-heat-scale span:first-child{font-size:0}
758
- .sg-heat-scale span:first-child:before{content:'2 \u5468\u524D';font-size:11px}
759
- }
883
+ .sg-heat-scale span:first-child:before{content:'2 \u5468\u524D';font-size:13px}
884
+ .sg-overview-page .sg-footer{font-size:13px;margin-top:30px;padding-top:20px}
885
+ }
886
+ @container (max-width:380px){
887
+ .sg-unified-top .sg-tabs{gap:4px}
888
+ .sg-unified-top .sg-tab{flex:0 0 auto;gap:4px;padding-inline:2px;font-size:12px}
889
+ .sg-unified-top .sg-tab-swatch{width:9px;height:9px}
890
+ .sg-ov{--sg-bar-width:52px}
891
+ .sg-memory .sg-pillar-row{column-gap:10px}
892
+ .sg-pillar-name b{font-size:16px}
893
+ .sg-pillar-tail{gap:8px}
894
+ .sg-pillar-val{font-size:12px;gap:4px}.sg-pillar-val b{font-size:25px}
895
+ .sg-heat-head{gap:8px;font-size:12px}.sg-heat-head>span:first-child{gap:6px}
760
896
  }
761
897
 
762
898
  /* \u5E38\u9A7B\u753B\u50CF\uFF1A\u5206\u7EC4\u5217\u8868\uFF0C\u4E00\u884C\u5C31\u662F\u4E00\u9879 */
@@ -1063,6 +1199,16 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1063
1199
  .sg-settings-group.sg-settings-compact{padding-bottom:4px}
1064
1200
  .sg-settings-shell .sg-settings-group-copy{display:none}
1065
1201
  .sg-settings-shell .sg-pg-head{margin-bottom:10px}
1202
+ .sg-memory .sg-dreaming-setting{margin:0 0 16px;padding:14px}
1203
+ .sg-dreaming-setting-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
1204
+ .sg-dreaming-setting-icon{display:grid;place-items:center;flex:none;width:36px;height:36px;border-radius:9px;background:var(--sg-soft);color:var(--sg-text);font:24px/1 'Segoe UI Symbol',sans-serif}
1205
+ .sg-dreaming-setting-title{flex:1;min-width:0;margin:0;font-size:14px;font-weight:650}
1206
+ .sg-memory .sg-dreaming-setting .sg-dreaming-setting-start{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:34px;margin:0;padding:6px 12px;font:inherit;font-size:12px;font-weight:650;white-space:nowrap;transition:background-color var(--sg-fast) var(--sg-ease)}
1207
+ .sg-dreaming-setting-start:focus-visible{outline:2px solid var(--sg-accent);outline-offset:3px}
1208
+ .sg-memory .sg-dreaming-setting .sg-dreaming{margin-top:12px;padding:12px;border-radius:8px}
1209
+ .sg-memory .sg-dreaming-setting .sg-dreaming-actions,.sg-memory .sg-dreaming-setting .sg-dreaming-session{margin-left:0}
1210
+ .sg-dreaming-setting .sg-dreaming-failure{overflow-wrap:anywhere}
1211
+ .sg-memory .sg-dreaming-setting .sg-dreaming-toast{margin:10px 0 0}
1066
1212
  .sg-settings-shell .sg-pg-head .sg-pg-tag{display:none}
1067
1213
  @media (max-width:680px){.sg-more{grid-template-columns:minmax(0,1fr);gap:16px}}
1068
1214
  /* The settings dialog can be ~900px wide, where two columns get cramped.
@@ -1192,9 +1338,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1192
1338
  `+citation.detailKind+": "+citation.id)):null)}let shortTermMemoryFeeds=new Map,SHORT_TERM_POLL_WINDOW_MS=12e4;function shortTermLayerName(level){return["\u7D22\u5F15","\u6458\u8981","\u5173\u952E\u4E8B\u5B9E","\u7CBE\u7B80\u5BF9\u8BDD","\u8FD1\u539F\u6587","\u539F\u6587"][Number(level)]||"\u4F1A\u8BDD\u89C6\u56FE"}function shortTermFeed(sessionId){let feed=shortTermMemoryFeeds.get(sessionId);return feed||(feed={sessionId,snapshot:{payload:null,loading:!0,error:""},listeners:new Set,request:null,controller:null,namespace:"",workspacePath:"",signal:"",queuedWorkspacePath:"",queuedSignal:"",pollTimer:null,pollSignal:"",pollUntil:0},shortTermMemoryFeeds.set(sessionId,feed),feed)}function publishShortTermFeed(feed,patch){feed.snapshot={...feed.snapshot,...patch};for(let listener of feed.listeners)listener(feed.snapshot)}function sessionWorkspacePath(sessionId,sessionById,workspaceItems){let candidateId=sessionId,visited=new Set;for(;candidateId&&!visited.has(candidateId);){visited.add(candidateId);let workspace=workspaceItems.find(item=>(item.sessionIds||[]).some(id2=>String(id2)===candidateId));if(workspace?.path)return workspace.path;candidateId=sessionById[candidateId]?.parentId||""}return sessionById[sessionId]?.cwd||""}function shortTermBlocks(data4){return Array.isArray(data4?.blocks)?data4.blocks:Array.isArray(data4?.items)?data4.items:[]}function shortTermBlockNumber(block){return Number(block?.blockIndex||block?.sequence||1)}function shortTermTurnRangeText(range){return!Array.isArray(range)||range.length<2||Number(range[1])<Number(range[0])?"\u7B49\u5F85\u65B0\u5BF9\u8BDD":"\u7B2C "+Number(range[0])+"\u2013"+Number(range[1])+" \u8F6E"}function shortTermDisplayLabel(display){return display.kind==="progress"?"\u4F1A\u8BDD\u8BB0\u5FC6 \xB7 "+display.current+"/"+display.capacity:display.kind==="processing"?"\u5DF2\u5C01\u5757 "+display.current+"/"+display.capacity+" \xB7 \u6B63\u5728\u538B\u7F29\u2026":display.kind==="failed"?shortTermTurnRangeText(display.block.turnRange)+" \xB7 \u538B\u7F29\u6682\u4E0D\u53EF\u7528":"Block "+shortTermBlockNumber(display.block)+" \xB7 "+shortTermTurnRangeText(display.block.turnRange)+" \xB7 \u5DF2\u538B\u7F29\u4E3A L"+Number(display.block.currentLevel)+" \xB7 "+Number(display.block.compressionPercent??0)+"%"}function strataGateStatusVisible(settingsSnapshot){return settingsSnapshot?.value?.showStrataGateStatus!==!1}function shortTermStatusVisible(settingsSnapshot){return strataGateStatusVisible(settingsSnapshot)&&settingsSnapshot?.value?.showShortTermStatus!==!1}function retrievalStatusVisible(settingsSnapshot){return strataGateStatusVisible(settingsSnapshot)&&settingsSnapshot?.value?.showRetrievalStatus!==!1}function shortTermNeedsPolling(payload,signal){let data4=payload?.data,blocks=shortTermBlocks(data4);if(blocks.some(block=>block.processingStatus==="pending"&&!summaryUnavailable(block)))return!0;let match2=/^(\d+):idle$/.exec(signal);if(!match2||!data4)return!1;let turn=Number(match2[1]);if(blocks.some(block=>Number(block.turnRange?.[1])===turn))return!1;let open=data4.openBlock,capacity=Number(open?.capacity||data4.blockTurnSize||6),count=Number(open?.turns||0),lastTurn=Number(open?.turnRange?.[1]);return capacity>0&&(lastTurn===turn-1&&count===capacity-1||lastTurn===turn&&count>=capacity)}function scheduleShortTermPoll(feed){feed.pollTimer!==null||feed.listeners.size===0||Date.now()>=feed.pollUntil||(feed.pollTimer=window.setTimeout(()=>{feed.pollTimer=null,refreshShortTermFeed(feed,feed.workspacePath,feed.signal,!0)},1200))}function loadSessionBlocks(namespace,sessionId,signal,offset=0,items=[]){return api2("memories",{namespace,kind:"blocks",threadId:sessionId,offset,limit:200},{signal}).then(page=>{let combined=[...items,...page.items||[]];return combined.length<Number(page.total||0)?loadSessionBlocks(namespace,sessionId,signal,combined.length,combined):{...page,items:combined}})}function refreshShortTermFeed(feed,workspacePath,signal,force=!1){if(!workspacePath)return publishShortTermFeed(feed,{loading:!1,error:"\u65E0\u6CD5\u786E\u5B9A\u5F53\u524D\u4F1A\u8BDD\u6240\u5C5E\u7684\u5DE5\u4F5C\u533A\u3002"}),Promise.resolve();let workspaceChanged=feed.workspacePath!==workspacePath;if(!force&&!workspaceChanged&&feed.signal===signal&&feed.snapshot.payload)return feed.request||Promise.resolve();if((feed.pollSignal!==signal||workspaceChanged)&&(feed.pollSignal=signal,feed.pollUntil=Date.now()+SHORT_TERM_POLL_WINDOW_MS),feed.request)return(workspaceChanged||feed.signal!==signal)&&(feed.queuedWorkspacePath=workspacePath,feed.queuedSignal=signal),feed.request;feed.pollTimer!==null&&(window.clearTimeout(feed.pollTimer),feed.pollTimer=null),workspaceChanged?(feed.workspacePath=workspacePath,feed.namespace="",publishShortTermFeed(feed,{payload:null,loading:!0,error:""})):feed.snapshot.payload||publishShortTermFeed(feed,{loading:!0,error:""}),feed.signal=signal;let controller=new AbortController;feed.controller=controller;let run=workspaceProjectKey(workspacePath).then(projectKey=>{if(controller.signal.aborted)throw new DOMException("Aborted","AbortError");if(!projectKey)throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u5F53\u524D\u4F1A\u8BDD\u7684\u5DE5\u4F5C\u533A\u6807\u8BC6\u3002");let namespace="dsh:project:"+projectKey;return feed.namespace=namespace,loadSessionBlocks(namespace,feed.sessionId,controller.signal)}).then(data4=>{let payload=data4?.activeThreadId===feed.sessionId?{namespace:feed.namespace,data:data4}:null;publishShortTermFeed(feed,{payload,loading:!1,error:""}),shortTermNeedsPolling(feed.snapshot.payload,feed.signal)&&scheduleShortTermPoll(feed)}).catch(reason=>{reason?.name!=="AbortError"&&publishShortTermFeed(feed,{loading:!1,error:String(reason?.message||reason)})}).finally(()=>{feed.controller===controller&&(feed.controller=null),feed.request===run&&(feed.request=null);let queuedWorkspacePath=feed.queuedWorkspacePath,queuedSignal=feed.queuedSignal;feed.queuedWorkspacePath="",feed.queuedSignal="",queuedWorkspacePath&&(queuedWorkspacePath!==feed.workspacePath||queuedSignal!==feed.signal)&&refreshShortTermFeed(feed,queuedWorkspacePath,queuedSignal,!0)});return feed.request=run,run}function shortTermTurnDisplay(data4,turn){let block=shortTermBlocks(data4).find(item=>Array.isArray(item.turnRange)&&Number(item.turnRange[1])===Number(turn));if(block)return block.processingStatus==="ready"?{kind:"block",block}:{kind:summaryUnavailable(block)?"failed":"processing",block,current:block.turnRange[1]-block.turnRange[0]+1,capacity:data4.blockTurnSize||6};let open=data4?.openBlock;if(!Array.isArray(open?.turnRange)||Number(open.turnRange[1])!==Number(turn))return null;let current=Math.max(0,Number(open.turns??open.turnRange[1]-open.turnRange[0]+1)),capacity=Math.max(1,Number(open.capacity||data4.blockTurnSize||6));return current>=capacity?{kind:"processing",block:null,current,capacity}:{kind:"progress",block:null,current,capacity}}function useShortTermMemoryFeed(sessionId,workspacePath,signal){let feed=shortTermFeed(sessionId),[state,setState]=React.useState(()=>feed.snapshot);return React.useEffect(()=>(feed.listeners.add(setState),setState(feed.snapshot),()=>{feed.listeners.delete(setState),feed.listeners.size===0&&(feed.pollTimer!==null&&(window.clearTimeout(feed.pollTimer),feed.pollTimer=null),feed.controller?.abort(),feed.controller=null,feed.queuedWorkspacePath="",feed.queuedSignal="")}),[feed]),React.useEffect(()=>{refreshShortTermFeed(feed,workspacePath,signal,!0)},[feed,workspacePath,signal]),state}function ShortTermMemoryBlockDetail({namespace,block}){let actualLayer=Number(block.currentLevel),[selectedPreviewLayer,setSelectedPreviewLayer]=React.useState(actualLayer),[detail,setDetail]=React.useState(null),[loading,setLoading]=React.useState(!0),[error3,setError]=React.useState("");React.useEffect(()=>{setSelectedPreviewLayer(actualLayer),setDetail(null),setLoading(!0),setError("");let controller=new AbortController;return api2("sources",{namespace,blockId:block.id},{signal:controller.signal}).then(setDetail).catch(reason=>{reason?.name!=="AbortError"&&setError(String(reason?.message||reason))}).finally(()=>{controller.signal.aborted||setLoading(!1)}),()=>controller.abort()},[namespace,block.id]);let layerMetrics=new Map((block.layerTokens||[]).map(layer=>[Number(layer.level),layer])),layers=new Map((detail?.layers||[]).map(layer=>[Number(layer.level),layer])),preview=layers.get(selectedPreviewLayer),previewMetrics=preview||layerMetrics.get(selectedPreviewLayer)||{tokens:0,percentOfL5:selectedPreviewLayer===5?100:0};return h("section",{className:"sg-stm-detail","aria-label":"\u4F1A\u8BDD\u8BB0\u5FC6\u8BE6\u60C5"},h("div",{className:"sg-stm-detail-head"},h("strong",null,"Block "+Number(block.blockIndex||block.sequence||1)+" \xB7 "+shortTermTurnRangeText(block.turnRange)),h("span",null,"\u539F\u6587\u4E00\u76F4\u4FDD\u7559\uFF1B\u9009\u62E9\u5C42\u7EA7\u53EA\u5207\u6362\u9884\u89C8")),h("div",{className:"sg-stm-facts"},h("span",null,"\u5F53\u524D\u4F7F\u7528\uFF1A",h("strong",null,"L"+actualLayer)),h("span",null,"\u538B\u7F29\u81F3\uFF1A",h("strong",null,Number(block.compressionPercent??0)+"%")),h("span",null,h("strong",null,Number(block.currentTokens||0)+" / "+Number(block.l5Tokens||0))," tokens")),h("div",{className:"sg-stm-layers",role:"tablist","aria-label":"\u540C\u4E00\u4F1A\u8BDD\u5757\u7684\u516D\u5C42\u538B\u7F29\u89C6\u56FE"},[5,4,3,2,1,0].map(level=>{let metrics=layerMetrics.get(level)||{tokens:0,percentOfL5:level===5?100:0},available=!loading&&layers.has(level);return h("button",{key:level,type:"button",role:"tab",className:"sg-stm-layer "+(level===actualLayer?"actual ":"")+(level===selectedPreviewLayer?"selected":""),"aria-selected":level===selectedPreviewLayer,disabled:!available,title:"L"+level+" \xB7 "+shortTermLayerName(level)+" \xB7 "+Number(metrics.tokens||0)+" tokens \xB7 L5 \u7684 "+Number(metrics.percentOfL5??0)+"%",onClick:()=>setSelectedPreviewLayer(level)},h("span",{className:"sg-stm-layer-level"},"L"+level),h("span",{className:"sg-stm-layer-name"},shortTermLayerName(level)),h("span",{className:"sg-stm-layer-size"},Number(metrics.tokens||0)+"t \xB7 "+Number(metrics.percentOfL5??0)+"%"),h("span",{className:"sg-stm-layer-current"},level===actualLayer?"\u5F53\u524D\u4F7F\u7528":""))})),loading?h("div",{className:"sg-stm-loading",role:"status"},"\u6B63\u5728\u8BFB\u53D6 L0\u2013L5\u2026"):error3?h("div",{className:"sg-stm-error"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\u538B\u7F29\u89C6\u56FE\uFF1A"+error3):preview?h("div",{className:"sg-stm-preview",role:"tabpanel"},h("div",{className:"sg-stm-preview-head"},h("strong",null,"L"+selectedPreviewLayer+" \xB7 "+shortTermLayerName(selectedPreviewLayer)),h("span",null,Number(previewMetrics.tokens||0)+" tokens \xB7 "+(selectedPreviewLayer===5?"100%":"L5 \u7684 "+Number(previewMetrics.percentOfL5??0)+"%"))),h("pre",{className:"sg-stm-content"},preview.content)):null)}function ShortTermMemoryTurnStatus({matched,sessionId,useSession,useSessions,useWorkspaces}){let sessionById=useSessions(state=>state.byId||{}),workspaceItems=useWorkspaces(state=>state.items||[]),sessionSignal=useSession(state=>{let latestTurn=0;for(let turn of state.turnEnds?.keys?.()||[])latestTurn=Math.max(latestTurn,Number(turn)||0);return String(latestTurn)+":"+(state.running?"running":"idle")}),workspacePath=sessionWorkspacePath(sessionId,sessionById,workspaceItems),feed=useShortTermMemoryFeed(sessionId,workspacePath,sessionSignal),data4=feed.payload?.data,display=shortTermTurnDisplay(data4,matched.turn),[expanded,setExpanded]=React.useState(!1);if(React.useEffect(()=>{display?.kind!=="block"&&setExpanded(!1)},[display?.kind,display?.block?.id]),!display)return null;let rule=()=>h("span",{className:"sg-stm-rule","aria-hidden":"true"});if(display.kind==="progress")return h("div",{className:"sg-stm","data-testid":"stratagate-short-term-progress"},h("div",{className:"sg-stm-line",role:"status"},rule(),h("span",{className:"sg-stm-line-copy"},shortTermDisplayLabel(display)),rule()));if(display.kind==="processing")return h("div",{className:"sg-stm","data-testid":"stratagate-short-term-processing"},h("div",{className:"sg-stm-line processing",role:"status","aria-live":"polite"},rule(),h("span",{className:"sg-stm-line-copy"},shortTermDisplayLabel(display)),rule()));if(display.kind==="failed")return null;let block=display.block;return h("div",{className:"sg-stm","data-testid":"stratagate-short-term-block","data-block-id":block.id},h("div",{className:"sg-stm-line"},rule(),h("button",{type:"button",className:"sg-stm-toggle","aria-expanded":expanded,onClick:()=>setExpanded(value=>!value)},shortTermDisplayLabel(display),h("span",{className:"sg-stm-chevron "+(expanded?"open":""),"aria-hidden":"true"},"\u203A")),rule()),expanded?h(ShortTermMemoryBlockDetail,{namespace:feed.payload.namespace,block}):null)}function RetrievalProcessPanel({retrievalGroups,retrievedCount,citations,open}){let adoptedRefs=new Set(citations.map(citation=>citation.evidenceRef));return h("section",{className:"sg-retrieved-panel","aria-label":"\u672C\u6B21\u8BB0\u5FC6\u68C0\u7D22\u8FC7\u7A0B"},h("div",{className:"sg-retrieved-heading"},h("strong",null,"\u68C0\u7D22\u8FC7\u7A0B"),h("span",null,retrievalGroups.length+" \u8F6E \xB7 \u5171\u8FD4\u56DE "+retrievedCount+" \u6761")),retrievalGroups.map((group2,groupIndex)=>{let gateLabel=evidenceGateLabel(group2);return h("details",{key:group2.batchId||group2.seq,className:"sg-retrieved-group"},h("summary",null,h("span",{className:"sg-retrieved-group-title"},retrievalGroupLabel(groupIndex)+" \xB7 \u8FD4\u56DE "+group2.count+" \u6761"),gateLabel?h("span",{className:"sg-retrieved-gate "+(group2.verdict==="sufficient"?"sufficient":"")},gateLabel):null),group2.memories.length?h("ol",{className:"sg-retrieved-list"},group2.memories.map((memory,memoryIndex)=>{let action=citationActionLabel(memory),adopted=adoptedRefs.has(memory.evidenceRef),state=adopted?"\u6700\u7EC8\u91C7\u7528":"\u68C0\u7D22\u5230 \xB7 \u672A\u91C7\u7528";return h("li",{key:memory.batchId+":"+memory.evidenceRef},h("button",{type:"button",className:"sg-retrieved-memory",title:memory.evidenceRef,onClick:()=>open(memory,adopted)},h("span",{className:"sg-retrieved-index","aria-hidden":"true"},memoryIndex+1+"."),h("span",{className:"sg-retrieved-memory-kind"},citationKindLabel(memory)),h("span",{className:"sg-retrieved-memory-title"},memory.title),h("span",{className:"sg-retrieved-memory-state"},action?action+" \xB7 "+state:state)))})):h("div",{className:"sg-retrieved-unavailable"},group2.count===0?"\u672C\u8F6E\u68C0\u7D22\u6CA1\u6709\u8FD4\u56DE\u5339\u914D\u8BB0\u5FC6\u3002":"\u8FD9\u6761\u5386\u53F2\u56DE\u6267\u672A\u4FDD\u5B58\u5019\u9009\u6458\u8981\u3002"))}),h("div",{className:"sg-retrieved-final"},h("span",null,"\u6700\u7EC8\u91C7\u7528 "+citations.length+" \u6761"),h("span",null,"\u68C0\u7D22\u547D\u4E2D\u4E0D\u4F1A\u81EA\u52A8\u5F3A\u5316\u8BB0\u5FC6")))}function MemoryCitationTail({matched,turn,seq,sessionId,useSession,useSessions,useWorkspaces,usePluginSettings,onOpenGraphNode}){matched=matched||selectMemoryCitations({turn,seq});let citations=matched.citations,retrievedCount=matched.retrievedCount,retrievalGroups=matched.retrievalGroups,pluginSettings=usePluginSettings?usePluginSettings(state=>state):null,[showRetrieved,setShowRetrieved]=React.useState(!1),[selected,setSelected]=React.useState(null),[detail,setDetail]=React.useState(null),[loading,setLoading]=React.useState(!1),[error3,setError]=React.useState(""),close=()=>{setSelected(null),setDetail(null),setError(""),setLoading(!1)},openGraphNode=(nodeId,event3)=>{event3?.stopPropagation?.();let namespace=selected?.namespace;if(!namespace||!nodeId||typeof onOpenGraphNode!="function"){setError("\u6682\u65F6\u65E0\u6CD5\u6253\u5F00\u5BF9\u5E94\u7684\u77E5\u8BC6\u56FE\u8C31\u8282\u70B9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002");return}setError(""),Promise.resolve(onOpenGraphNode(namespace,nodeId)).then(opened=>{if(opened===!1){setError("\u6682\u65F6\u65E0\u6CD5\u6253\u5F00\u5BF9\u5E94\u7684\u77E5\u8BC6\u56FE\u8C31\u8282\u70B9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002");return}close()}).catch(reason=>setError("\u6682\u65F6\u65E0\u6CD5\u6253\u5F00\u5BF9\u5E94\u7684\u77E5\u8BC6\u56FE\u8C31\u8282\u70B9\uFF1A"+String(reason?.message||reason)))},open=(citation,adopted=!0)=>{setSelected({...citation,adopted}),setDetail(null),setError(""),setLoading(!0),api2("sources",{namespace:citation.namespace,[citation.detailKind]:citation.id}).then(setDetail).catch(reason=>setError(String(reason?.message||reason))).finally(()=>setLoading(!1))};return React.useEffect(()=>{if(!selected)return;let onKeyDown=event3=>{event3.key==="Escape"&&(document.querySelector('.sg-citation-dialog .sg-info-trigger[aria-expanded="true"]')||close())};return document.addEventListener("keydown",onKeyDown),()=>document.removeEventListener("keydown",onKeyDown)},[selected]),h(React.Fragment,null,shortTermStatusVisible(pluginSettings)?h(ShortTermMemoryTurnStatus,{matched,sessionId,useSession,useSessions,useWorkspaces}):null,retrievalStatusVisible(pluginSettings)&&citations.length?h("div",{className:"sg-answer-citations","data-testid":"stratagate-answer-citations"},h("div",{className:"sg-answer-citations-head"},h("span",{className:"sg-answer-citations-label"},"\u672C\u56DE\u7B54\u91C7\u7528\u4E86 "+citations.length+" \u6761\u8BB0\u5FC6"),retrievalGroups.length?h("button",{type:"button",className:"sg-answer-process-link","aria-expanded":showRetrieved,onClick:()=>setShowRetrieved(value=>!value)},h("span",null,"\xB7 \u67E5\u770B\u68C0\u7D22\u8FC7\u7A0B"),h("span",{className:"sg-answer-retrieval-chevron "+(showRetrieved?"open":""),"aria-hidden":"true"},"\u203A")):null),h("div",{className:"sg-answer-citations-list"},citations.map(citation=>{let action=citationActionLabel(citation);return h("button",{key:citation.batchId+":"+citation.evidenceRef,type:"button",className:"sg-answer-citation",title:citation.evidenceRef,onClick:()=>open(citation,!0)},h("span",{className:"sg-answer-citation-kind"},citationKindLabel(citation)),h("span",{className:"sg-answer-citation-title"},citation.title),action?h("span",{className:"sg-answer-citation-action"},action):null)})),showRetrieved&&retrievalGroups.length?h(RetrievalProcessPanel,{retrievalGroups,retrievedCount,citations,open}):null):null,retrievalStatusVisible(pluginSettings)&&citations.length===0&&retrievalGroups.length>0?h("div",{className:"sg-answer-retrieval","data-testid":"stratagate-answer-retrieval-note"},h("button",{type:"button",className:"sg-answer-retrieval-toggle","aria-expanded":showRetrieved,onClick:()=>setShowRetrieved(value=>!value)},h("span",null,"\u68C0\u7D22 "+retrievalGroups.length+" \u8F6E \xB7 \u8FD4\u56DE "+retrievedCount+" \u6761 \xB7 \u672A\u91C7\u7528"),h("span",{className:"sg-answer-retrieval-chevron "+(showRetrieved?"open":""),"aria-hidden":"true"},"\u203A")),showRetrieved?h(RetrievalProcessPanel,{retrievalGroups,retrievedCount,citations,open}):null):null,retrievalStatusVisible(pluginSettings)&&selected?h("div",{className:"sg-citation-overlay",onMouseDown:event3=>{event3.target===event3.currentTarget&&close()}},h(InfoPopoverGroup,null,h("section",{className:"sg-citation-dialog",role:"dialog","aria-modal":"true","aria-label":citationKindLabel(selected)+" \u8BE6\u60C5"},h("header",{className:"sg-citation-dialog-head"},h("div",{className:"sg-citation-dialog-heading"},h("div",{className:"sg-citation-dialog-kicker"},citationKindLabel(selected)),h("h3",{className:"sg-citation-dialog-title"},(selected.kind==="event"?detail?.events?.find(item=>item.id===selected.id)?.title||detail?.events?.[0]?.title:"")||selected.title),selected.kind==="event"?h(EventMetadata,{event:detail?.events?.find(item=>item.id===selected.id)||detail?.events?.[0],nodes:detail?.relatedNodes||[],onNode:openGraphNode}):null),h("div",{className:"sg-citation-dialog-actions"},h("span",{className:"sg-citation-status "+(selected.adopted?"adopted":"retrieved")},selected.adopted?"\u5DF2\u7528\u4E8E\u56DE\u7B54":"\u68C0\u7D22\u5019\u9009 \xB7 \u672A\u91C7\u7528"),selected.adopted?h(InfoPopover,{label:"\u672C\u6B21\u91C7\u7528\u8BF4\u660E",className:"sg-status-info"},h("p",null,"\u53EA\u6709\u6807\u8BB0\u4E3A\u672C\u6B21\u91C7\u7528\u7684\u8BB0\u5FC6\u5185\u5BB9\u53C2\u4E0E\u4E86\u672C\u6B21\u56DE\u7B54\uFF1B\u5173\u8054\u4FE1\u606F\u548C\u6765\u6E90\u5185\u5BB9\u4EC5\u7528\u4E8E\u67E5\u770B\u4E0E\u8FFD\u6EAF\u4F9D\u636E\u3002")):null,h("button",{type:"button",className:"sg-citation-close",onClick:close,"aria-label":"\u5173\u95ED\u8BB0\u5FC6\u8BE6\u60C5"},"\xD7"))),h("div",{className:"sg-citation-dialog-body"},loading?h("div",{className:"sg-citation-loading"},"\u6B63\u5728\u8BFB\u53D6\u6765\u6E90\u2026"):error3?h("div",{className:"sg-citation-error"},error3):h(CitationDetail,{citation:selected,detail,adopted:selected.adopted,onNode:openGraphNode}))))):null)}function dashboardApi(params,options2={}){let query=new URLSearchParams(params||{}),url="/api/stratagate/dashboard"+(query.size?"?"+query:""),attempt=0,request=()=>fetch(url,{cache:"no-cache",signal:options2.signal,headers:options2.etag?{"If-None-Match":options2.etag}:void 0}).then(async res=>{let etag=res.headers.get("etag")||options2.etag||"";if(res.status===304)return{notModified:!0,etag,data:null};let data4=await res.json().catch(()=>({}));if(!res.ok)throw new Error(data4&&data4.error||"HTTP "+res.status);return{notModified:!1,etag,data:data4}}).catch(reason=>{if(reason?.name==="AbortError")throw reason;let message=String(reason?.message||reason);if((reason instanceof TypeError||message.includes("Failed to fetch"))&&attempt<2)return attempt+=1,new Promise(resolve2=>window.setTimeout(resolve2,attempt*300)).then(request);throw new Error(message+"\uFF08dashboard\uFF09")});return request()}function pageMeta(value,fallbackLimit){return{total:Math.max(0,Number(value?.total||0)),offset:Math.max(0,Number(value?.offset||0)),limit:Math.max(1,Number(value?.limit||fallbackLimit))}}function usePagedMemory({namespace,kind,initialItems,initialPage,fallbackLimit,extraParams={},reloadOnParamsChange=!1}){let key=namespace+"\0"+kind,paramsKey=JSON.stringify(extraParams),[state,setState]=React.useState(()=>({items:initialItems,page:pageMeta(initialPage,fallbackLimit)})),[loading,setLoading]=React.useState(!1),[error3,setError]=React.useState(""),requestVersion=React.useRef(0),previousParamsKey=React.useRef(paramsKey),previousInitialData=React.useRef({items:initialItems,total:initialPage?.total,limit:initialPage?.limit});React.useEffect(()=>{requestVersion.current+=1,setState({items:initialItems,page:pageMeta(initialPage,fallbackLimit)}),setError("")},[key]);let loadOffset=offset=>{let version2=++requestVersion.current;setLoading(!0),setError("");let path=kind==="audit"?"audit":"memories",params={namespace,offset,limit:state.page.limit,...extraParams};return kind!=="audit"&&(params.kind=kind),api2(path,params).then(result=>{version2===requestVersion.current&&setState({items:result.items||[],page:pageMeta(result,state.page.limit)})}).catch(reason=>{version2===requestVersion.current&&setError(String(reason?.message||reason))}).finally(()=>{version2===requestVersion.current&&setLoading(!1)})};return React.useEffect(()=>{let previous=previousInitialData.current,changed=previous.items!==initialItems||previous.total!==initialPage?.total||previous.limit!==initialPage?.limit;if(previousInitialData.current={items:initialItems,total:initialPage?.total,limit:initialPage?.limit},reloadOnParamsChange){changed&&previousParamsKey.current===paramsKey&&(setState(current=>({...current,page:{...current.page,offset:0}})),loadOffset(0));return}setState(current=>current.page.offset===0?{items:initialItems,page:pageMeta(initialPage,fallbackLimit)}:current)},[initialItems,initialPage?.total,initialPage?.limit,reloadOnParamsChange,paramsKey]),React.useEffect(()=>{if(!reloadOnParamsChange){previousParamsKey.current=paramsKey;return}previousParamsKey.current!==paramsKey&&(previousParamsKey.current=paramsKey,setState(current=>({items:[],page:{...current.page,total:0,offset:0}})),loadOffset(0))},[paramsKey,reloadOnParamsChange]),{...state,loading,error:error3,loadOffset}}function Pagination({page,loading,error:error3,onOffset}){let totalPages=Math.max(1,Math.ceil(page.total/page.limit)),currentPage=Math.min(totalPages,Math.floor(page.offset/page.limit)+1),start=page.total?page.offset+1:0,end=Math.min(page.total,page.offset+page.limit);return h("div",{className:"sg-pagination",role:"navigation","aria-label":"\u5206\u9875"},h("button",{type:"button",className:"sg-page-button",disabled:loading||page.offset<=0,onClick:()=>onOffset(Math.max(0,page.offset-page.limit))},"\u4E0A\u4E00\u9875"),h("span",null,loading?"\u52A0\u8F7D\u4E2D\u2026":"\u7B2C "+currentPage+" / "+totalPages+" \u9875 \xB7 \u663E\u793A "+start+"\u2013"+end+" / \u5171 "+page.total+" \u6761"),h("button",{type:"button",className:"sg-page-button",disabled:loading||page.offset+page.limit>=page.total,onClick:()=>onOffset(page.offset+page.limit)},"\u4E0B\u4E00\u9875"),error3?h("span",{className:"sg-page-error"},"\u52A0\u8F7D\u5931\u8D25\uFF1A"+error3):null)}function projectName(item,workspaceTitles={}){let name=projectNameRaw(item,workspaceTitles);return name==="default-workspace"?"\u9ED8\u8BA4\u5DE5\u4F5C\u533A":name}function projectNameRaw(item,workspaceTitles={}){let value=String(item?.namespace||item||"");if(value.includes(":project:")){let key=value.split(":project:").pop();return key&&workspaceTitles[key]?workspaceTitles[key]:item?.workspaceName&&item.workspaceName!=="\u5F53\u524D\u5DE5\u4F5C\u533A"?item.workspaceName:"\u5DE5\u4F5C\u533A\u540D\u79F0\u8BFB\u53D6\u4E2D\u2026"}return item?.workspaceName?item.workspaceName:value.includes(":global:")?value.split(":global:").pop()||"\u5168\u5C40\u8BB0\u5FC6":value.includes(":session:")?"\u5F53\u524D\u5BF9\u8BDD":value||"\u5F53\u524D\u5DE5\u4F5C\u533A"}function workspaceProjectKey(path){let canonical=String(path||"").replaceAll("\\","/").toLowerCase();return!canonical||!globalThis.crypto?.subtle?Promise.resolve(""):globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(canonical)).then(digest=>Array.from(new Uint8Array(digest).slice(0,10),byte=>byte.toString(16).padStart(2,"0")).join(""))}function formatTime(value){if(!value)return"\u65F6\u95F4\u672A\u77E5";let date=new Date(value);if(Number.isNaN(date.getTime()))return String(value);let seconds=Math.round((Date.now()-date.getTime())/1e3);if(seconds>=0&&seconds<60)return"\u521A\u521A";if(seconds>=60&&seconds<3600)return Math.floor(seconds/60)+" \u5206\u949F\u524D";let timeZone="Asia/Shanghai",dayKey=input=>new Intl.DateTimeFormat("en-CA",{timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).format(input),clock=input=>new Intl.DateTimeFormat("zh-CN",{timeZone,hour:"2-digit",minute:"2-digit",hour12:!1}).format(input),now=new Date;if(dayKey(date)===dayKey(now))return"\u4ECA\u5929 "+clock(date);let yesterday=new Date(now.getTime()-1440*60*1e3);return dayKey(date)===dayKey(yesterday)?"\u6628\u5929 "+clock(date):new Intl.DateTimeFormat("zh-CN",{timeZone,month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(date)}function statusText(status){return status==="organized"?"\u5DF2\u6574\u7406":status==="failed"?"\u6574\u7406\u5931\u8D25":status==="waiting"?"\u7B49\u5F85\u6574\u7406":"\u6574\u7406\u4E2D"}function UsedMark({count,title}){let numeric=Number(count);return h("span",{className:"sg-used",title:title||"\u88AB\u56DE\u7B54\u7528\u5230"},h("svg",{viewBox:"0 0 13 11","aria-hidden":"true",focusable:"false"},h("path",{d:"M2 .5h9A1.5 1.5 0 0 1 12.5 2v4.5A1.5 1.5 0 0 1 11 8H6L3 10.5V8H2A1.5 1.5 0 0 1 .5 6.5V2A1.5 1.5 0 0 1 2 .5z",fill:"currentColor"})),Number.isFinite(numeric)&&numeric>0?String(numeric):null)}function eventDayKey(value){let time2=Date.parse(value);return Number.isFinite(time2)?new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(time2)):""}function eventDayLabel(value){let time2=Date.parse(value);if(!Number.isFinite(time2))return{day:"?",week:"\u65F6\u95F4\u672A\u77E5"};let date=new Date(time2),today=eventDayKey(new Date().toISOString()),key=eventDayKey(value),day=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Shanghai",day:"2-digit"}).format(date);if(key===today)return{day,week:"\u4ECA\u5929"};let yesterday=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(Date.now()-864e5));return key===yesterday?{day,week:"\u6628\u5929"}:{day,week:new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"numeric",day:"numeric"}).format(date)}}function Loading(){return h("div",{className:"sg-loading",role:"status"},h("div",{className:"sg-skeleton"}),h("div",{className:"sg-skeleton"}),h("div",{className:"sg-skeleton"}))}function Empty({title,copy:copy3}){return h("div",{className:"sg-empty"},h("strong",null,title),h("span",null,copy3))}function BackBar({label,onBack}){return h("div",{className:"sg-backbar"},h("button",{className:"sg-back",onClick:onBack,title:"\u8FD4\u56DE"},h("span",{"aria-hidden":"true"},"\u2190"),label))}function activeProcessingCount(overview){let scheduledRetries=(overview?.failedJobDetails||[]).filter(job=>job.nextRetryAt).length;return Math.max(0,Number(overview?.processingJobs||0)-scheduledRetries)}function statusJobKey(job){return String(job?.kind||"job")+":"+String(job?.id||"")}function emptyTaskStatus(){return{processing:0,retryable:0,terminalFailed:0,completed:0,blocked:0}}function taskStatus(overview){let explicit=overview?.taskStatus;if(explicit?.blockSummary&&explicit?.eventExtraction&&explicit?.graphProjection)return explicit;let result={blockSummary:emptyTaskStatus(),eventExtraction:emptyTaskStatus(),graphProjection:emptyTaskStatus()},kindMap={"block-summary":result.blockSummary,"event-extraction":result.eventExtraction,"graph-projection":result.graphProjection},processingKeys=new Set;for(let job of overview?.processingJobDetails||[]){let group2=kindMap[job.kind];group2&&(processingKeys.add(statusJobKey(job)),group2.processing+=1)}for(let job of overview?.failedJobDetails||[]){let group2=kindMap[job.kind];if(!group2)continue;let retryable=!!job.nextRetryAt&&Number(job.attempts||0)<3;retryable?(group2.retryable+=1,processingKeys.has(statusJobKey(job))||(group2.processing+=1)):retryable||(group2.terminalFailed+=1)}return result}function graphMigrationState(overview,status=taskStatus(overview)){let migration=overview?.graphMigration||{};if(status.graphProjection.processing>0||migration.processing>0)return"processing";if(status.graphProjection.terminalFailed>0||migration.failed>0)return"failed";if(migration.state==="processing"||migration.state==="failed")return migration.state;let total=Number(migration.total??overview?.events);return Number.isFinite(total)?total===0?"empty":migration.state?migration.state:migration.complete?"complete":"incomplete":"unknown"}function graphMigrationNotice(migration){if(!migration)return"";let total=Number(migration.total),projected=Number(migration.projected);return migration.total!=null&&migration.projected!=null&&Number.isSafeInteger(total)&&total>0&&Number.isSafeInteger(projected)&&projected>=0&&projected<total||Number(migration.processing)>0||Number(migration.failed)>0?"\u5F53\u524D\u56FE\u8C31\u5C1A\u672A\u66F4\u65B0\u5B8C\u6574\u3002":""}function summaryUnavailable(block){let job=block?.summaryJob;return job?.state==="terminal-failed"||job?.status==="failed"&&!job.state&&!(Number(job.attempts||0)<3&&job.nextRetryAt&&Number.isFinite(Date.parse(job.nextRetryAt)))}function SearchBox({value,onChange,placeholder="\u641C\u7D22\u8BB0\u5FC6\u3001\u4EBA\u7269\u3001\u9879\u76EE\u3001\u6982\u5FF5\u2026"}){return h("div",{className:"sg-search"},h("span",{className:"sg-search-mark","aria-hidden":"true"},"\u2315"),h("input",{value,onChange:event3=>onChange(event3.target.value),placeholder,"aria-label":"\u641C\u7D22\u957F\u671F\u8BB0\u5FC6"}))}function useDebouncedValue(value,delay2=250){let[debounced,setDebounced]=React.useState(value);return React.useEffect(()=>{let timer=window.setTimeout(()=>setDebounced(value),delay2);return()=>window.clearTimeout(timer)},[value,delay2]),debounced}let NODE_META={person:["\u4EBA\u7269","#8b6ccf","\u2659"],project:["\u9879\u76EE","#6f55ae","\u25A3"],organization:["\u7EC4\u7EC7","#3978cf","\u2318"],tool:["\u5DE5\u5177","#3b854d","\u25A4"],place:["\u5730\u70B9","#8a8378","\u2302"]},EVENT_TYPE_TEXT={decision:"\u51B3\u7B56",release:"\u53D1\u5E03",task_completed:"\u4EFB\u52A1\u5B8C\u6210",plan:"\u8BA1\u5212",change:"\u53D8\u66F4",cancellation:"\u53D6\u6D88",incident:"\u4E8B\u4EF6",meeting:"\u4F1A\u8BAE",collaboration:"\u534F\u4F5C",migration:"\u8FC1\u79FB",other:"\u5176\u4ED6"},EVENT_STATUS_TEXT={occurred:"\u5DF2\u53D1\u751F",planned:"\u8BA1\u5212\u4E2D",cancelled:"\u5DF2\u53D6\u6D88",ongoing:"\u8FDB\u884C\u4E2D",unknown:"\u672A\u77E5"},EVENT_RELATIONS=[["supersedesEventIds","\u53D6\u4EE3"],["conflictsWithEventIds","\u51B2\u7A81"],["sameEventId","\u540C\u4E00\u4E8B\u4EF6"],["beforeEventIds","\u4E4B\u524D"],["afterEventIds","\u4E4B\u540E"],["relatedEventIds","\u76F8\u5173"]];function exactTime(value){if(!value)return"\u672A\u77E5";let date=new Date(value);return Number.isNaN(date.getTime())?String(value):new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).format(date)}function eventOccurrence(event3){let happened=event3.temporal?.happenedStart||event3.temporal?.happenedEnd;return{value:happened||event3.temporal?.mentionedAt||event3.createdAt,known:!!happened}}function NodePill({node,onClick}){let meta3=NODE_META[node.type]||["\u5B9E\u4F53","#64748b","\u2022"];return h("button",{type:"button",className:"sg-entity-pill",onPointerDown:event3=>event3.stopPropagation(),onClick:event3=>{event3.stopPropagation(),onClick?.(event3)},title:"\u5728\u77E5\u8BC6\u56FE\u8C31\u4E2D\u67E5\u770B "+node.name},h("span",{style:{color:meta3[1]},"aria-hidden":"true"},meta3[2]),node.name)}function StaticEntityPill({name}){return h("span",{className:"sg-entity-pill sg-entity-pill-static"},name)}function NodeSummaryBubble({node,x:x2,y:y2,width:width2,height:height2=560,onViewDetails}){if(!node)return null;let facts=(node.facts||[]).filter(fact=>fact.status==="active").slice(0,5),eventCount=new Set(node.sourceEventIds||[]).size;return h("aside",{className:"sg-node-bubble "+(x2>width2*.62?"flip":""),style:{left:x2/width2*100+"%",top:y2/height2*100+"%"}},h("div",{className:"sg-node-bubble-head"},h("h3",null,node.name),h("span",{className:"sg-status-dot"},"\u25CF "+(node.status==="active"?"\u6D3B\u8DC3":node.status||"\u672A\u77E5"))),(node.tags||[]).length?h("div",{className:"sg-node-tags"},node.tags.slice(0,4).map(tag=>h("span",{key:tag,className:"sg-node-tag"},tag))):null,h("p",{className:"sg-node-bubble-state"},node.currentState||"\u6682\u65E0\u5F53\u524D\u72B6\u6001"),facts.length?h("ul",null,facts.map(fact=>h("li",{key:fact.id},h("strong",null,fact.key+"\uFF1A"),Array.isArray(fact.value)?fact.value.join("\u3001"):fact.value))):h("p",{className:"sg-node-bubble-state"},"\u6682\u65E0\u5173\u952E\u4E8B\u5B9E"),h("div",{className:"sg-node-bubble-foot"},h("span",null,eventCount+" \u6761\u76F8\u5173\u4E8B\u4EF6"),h("button",{type:"button",onClick:onViewDetails},"\u67E5\u770B\u8BE6\u60C5 \u2192")))}let GRAPH_NODE_RADIUS={peripheral:30,normal:38,important:46,core:54},GRAPH_IMPORTANCE_TEXT={peripheral:"\u8FB9\u7F18\u8282\u70B9",normal:"\u666E\u901A\u8282\u70B9",important:"\u91CD\u8981\u8282\u70B9",core:"\u6838\u5FC3\u8282\u70B9"};function graphNameKey(value){return String(value||"").toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu,"")}function graphTimestamp(value){let timestamp=Date.parse(String(value||""));return Number.isFinite(timestamp)?timestamp:0}function graphNodeImportance(nodes3,edges3,project){let activeEdges=edges3.filter(edge=>edge.status==="active"),activeSupportingEvents=node=>(node.supportingEvents||[]).filter(event3=>event3.status!=="forgotten"&&event3.status!=="archived"),relationCounts=new Map(nodes3.map(node=>[node.id,0])),neighbors=new Map(nodes3.map(node=>[node.id,new Set]));for(let edge of activeEdges)relationCounts.set(edge.fromNodeId,(relationCounts.get(edge.fromNodeId)||0)+1),relationCounts.set(edge.toNodeId,(relationCounts.get(edge.toNodeId)||0)+1),neighbors.get(edge.fromNodeId)?.add(edge.toNodeId),neighbors.get(edge.toNodeId)?.add(edge.fromNodeId);let projectKey=graphNameKey(project),directWorkspaceNodes=new Set(nodes3.filter(node=>projectKey&&[node.name,...node.aliases||[]].some(name=>{let key=graphNameKey(name);return key===projectKey||key.length>=5&&projectKey.length>=5&&(key.includes(projectKey)||projectKey.includes(key))})).map(node=>node.id)),workspaceAffinity=new Map(nodes3.map(node=>[node.id,directWorkspaceNodes.has(node.id)?1:0]));for(let nodeId of directWorkspaceNodes)for(let neighborId of neighbors.get(nodeId)||[]){workspaceAffinity.set(neighborId,Math.max(workspaceAffinity.get(neighborId)||0,.55));for(let secondHopId of neighbors.get(neighborId)||[])workspaceAffinity.set(secondHopId,Math.max(workspaceAffinity.get(secondHopId)||0,.25))}let supportCounts=new Map(nodes3.map(node=>{let supportingEvents=activeSupportingEvents(node);return[node.id,supportingEvents.length?new Set(supportingEvents.map(event3=>event3.id)).size:new Set(node.sourceEventIds||[]).size]})),maxSupport=Math.max(1,...supportCounts.values()),maxRelations=Math.max(1,...relationCounts.values()),latestActivity=0;for(let node of nodes3){latestActivity=Math.max(latestActivity,graphTimestamp(node.updatedAt));for(let event3 of activeSupportingEvents(node))latestActivity=Math.max(latestActivity,graphTimestamp(event3.updatedAt||event3.createdAt))}for(let edge of activeEdges)latestActivity=Math.max(latestActivity,graphTimestamp(edge.updatedAt));let halfLife=2160*60*60*1e3,recency=timestamp=>timestamp&&latestActivity?Math.exp(-Math.max(0,latestActivity-timestamp)/halfLife):0,scored=nodes3.map(node=>{let sustainedMentions=activeSupportingEvents(node).map(event3=>recency(graphTimestamp(event3.updatedAt||event3.createdAt))).sort((left,right)=>right-left).slice(0,3),recentScore=.25*recency(graphTimestamp(node.updatedAt))+.75*sustainedMentions.reduce((sum,value)=>sum+value,0)/3,supportScore=Math.log1p(supportCounts.get(node.id)||0)/Math.log1p(maxSupport),relationScore=Math.log1p(relationCounts.get(node.id)||0)/Math.log1p(maxRelations),score=.42*supportScore+.28*relationScore+.15*recentScore+.15*(workspaceAffinity.get(node.id)||0);return{id:node.id,score}}),ordered=scored.map(({score})=>score).sort((left,right)=>left-right),quantile=ratio=>ordered[Math.ceil(Math.max(0,ordered.length-1)*ratio)]||0,spread=(ordered[ordered.length-1]||0)-(ordered[0]||0),thresholds={normal:quantile(.25),important:quantile(.6),core:quantile(.85)};return new Map(scored.map(({id:id2,score})=>{let tier;return spread<.02?tier=score>=.65?"core":score>=.38?"important":"normal":score>=thresholds.core?tier="core":score>=thresholds.important?tier="important":score>=thresholds.normal?tier="normal":tier="peripheral",[id2,{score,tier,radius:GRAPH_NODE_RADIUS[tier]}]}))}function GraphCanvas({nodes:nodes3,edges:edges3,clusters,importance,selectedId,onSelect,nodeLimit=100,showSummary=!1,onViewDetails}){let containerRef=React.useRef(null),graphRef=React.useRef(null),selectedIdRef=React.useRef(selectedId);selectedIdRef.current=selectedId;let[selectedPoint,setSelectedPoint]=React.useState(null),[zoomPercent,setZoomPercent]=React.useState(100),displayedNodes=[...nodes3].sort((left,right)=>(importance.get(right.id)?.score||0)-(importance.get(left.id)?.score||0)).slice(0,nodeLimit),displayedIds=new Set(displayedNodes.map(node=>node.id)),visibleClusters=(clusters||[]).map(cluster=>({...cluster,nodeIds:(cluster.nodeIds||[]).filter(id2=>displayedIds.has(id2))})).filter(cluster=>cluster.nodeIds.length),assignedIds=new Set(visibleClusters.flatMap(cluster=>cluster.nodeIds));for(let node of displayedNodes.filter(item=>!assignedIds.has(item.id)))visibleClusters.push({id:"fallback-"+node.id,label:(node.tags||[])[0]||node.name,nodeIds:[node.id],tags:node.tags||[]});let membership=new Map(visibleClusters.flatMap(cluster=>cluster.nodeIds.map(id2=>[id2,cluster.id]))),activeEdges=edges3.filter(edge=>edge.status==="active"&&displayedIds.has(edge.fromNodeId)&&displayedIds.has(edge.toNodeId)),signature=JSON.stringify({nodes:displayedNodes.map(node=>[node.id,node.name,node.type,node.tags||[],importance.get(node.id)?.tier]),edges:activeEdges.map(edge=>[edge.id,edge.fromNodeId,edge.toNodeId,edge.relation,edge.confidence]),clusters:visibleClusters.map(cluster=>[cluster.id,cluster.label,cluster.nodeIds])});React.useEffect(()=>{let container2=containerRef.current;if(!container2||!cytoscape4||!displayedNodes.length)return;let computed=getComputedStyle(container2),textColor=computed.getPropertyValue("--sg-text").trim()||"#0f1115",mutedColor=computed.getPropertyValue("--sg-muted").trim()||"#64748b",borderColor=computed.getPropertyValue("--sg-border").trim()||"#d5d9df",pageColor=computed.getPropertyValue("--sg-page").trim()||"#ffffff",accentColor=computed.getPropertyValue("--sg-accent").trim()||"#4176e6",reduceMotion=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0,parentIds=new Map(visibleClusters.map(cluster=>[cluster.id,"sg-parent-"+cluster.id])),clusterSizes=new Map(visibleClusters.map(cluster=>[cluster.id,cluster.nodeIds.length])),elements=[...visibleClusters.map(cluster=>({data:{id:parentIds.get(cluster.id),label:cluster.label+" \xB7 "+cluster.nodeIds.length},classes:"sg-community"})),...displayedNodes.map(node=>{let meta3=NODE_META[node.type]||["\u5B9E\u4F53","#64748b","\u2022"],semantic=(node.tags||[])[0]||meta3[0],visualImportance=importance.get(node.id)||{tier:"normal",radius:GRAPH_NODE_RADIUS.normal};return{data:{id:node.id,parent:parentIds.get(membership.get(node.id)),label:node.name+`
1193
1339
  `+semantic,color:meta3[1],size:visualImportance.radius*2,tier:visualImportance.tier},classes:"sg-memory-node"}}),...activeEdges.map(edge=>{let fromCluster=membership.get(edge.fromNodeId),toCluster=membership.get(edge.toNodeId),sameCluster=fromCluster===toCluster,labeled=sameCluster&&(clusterSizes.get(fromCluster)||0)<=6;return{data:{id:"sg-edge-"+edge.id,source:edge.fromNodeId,target:edge.toNodeId,label:edge.relation},classes:"sg-memory-edge "+(sameCluster?"same-community":"cross-community")+(labeled?" labeled":"")}})],graph=cytoscape4({container:container2,elements,wheelSensitivity:.22,minZoom:.25,maxZoom:2.4,selectionType:"single",boxSelectionEnabled:!1,style:[{selector:"node.sg-community",style:{"background-color":accentColor,"background-opacity":.045,"border-color":accentColor,"border-opacity":.28,"border-width":1,"border-style":"dashed",shape:"round-rectangle",padding:"22px",label:"data(label)",color:mutedColor,"font-size":12,"font-weight":700,"text-valign":"top","text-halign":"center","text-margin-y":-9,"text-background-color":pageColor,"text-background-opacity":.82,"text-background-padding":"3px"}},{selector:"node.sg-memory-node",style:{width:"data(size)",height:"data(size)","background-color":"data(color)","background-opacity":.28,"border-color":"data(color)","border-width":1.5,label:"data(label)",color:textColor,"font-size":11,"font-weight":650,"text-wrap":"wrap","text-max-width":96,"text-valign":"center","text-halign":"center","overlay-opacity":0,"transition-property":"border-width, border-color, underlay-opacity","transition-duration":reduceMotion?"0ms":"180ms"}},{selector:"node.sg-memory-node:selected",style:{"border-width":4,"border-color":accentColor,"underlay-color":accentColor,"underlay-opacity":.16,"underlay-padding":7}},{selector:"edge.sg-memory-edge",style:{width:1.2,"line-color":mutedColor,"target-arrow-color":mutedColor,"target-arrow-shape":"triangle","curve-style":"bezier",opacity:.58,"arrow-scale":.75,label:"","overlay-opacity":0}},{selector:"edge.sg-memory-edge.labeled",style:{label:"data(label)",color:textColor,"font-size":10,"text-background-color":pageColor,"text-background-opacity":.88,"text-background-padding":"2px","text-rotation":"autorotate"}},{selector:"edge.sg-memory-edge.cross-community",style:{opacity:.24,"line-style":"dashed"}},{selector:"edge.sg-memory-edge.selected-relation",style:{opacity:.9,width:2,label:"data(label)",color:textColor,"font-size":10,"text-background-color":pageColor,"text-background-opacity":.9,"text-background-padding":"2px"}}]});graphRef.current=graph;let updatePoint=()=>{let selected=graph.getElementById(selectedIdRef.current);if(!selected.length){setSelectedPoint(null);return}let point=selected.renderedPosition();setSelectedPoint({x:point.x,y:point.y,width:container2.clientWidth||760,height:container2.clientHeight||522})};graph.on("tap","node.sg-memory-node",event3=>onSelect(event3.target.id()));let updateZoom=()=>setZoomPercent(Math.round(graph.zoom()*100));graph.on("pan zoom resize",updatePoint),graph.on("zoom",updateZoom),graph.on("layoutstop",updatePoint),graph.on("layoutstop",updateZoom);let resizeObserver=globalThis.ResizeObserver?new globalThis.ResizeObserver(()=>{graph.resize(),updatePoint()}):null;return resizeObserver?.observe(container2),graph.layout({name:"fcose",quality:"default",randomize:!0,animate:reduceMotion?!1:"end",animationDuration:reduceMotion?0:320,animationEasing:"ease-out-cubic",fit:!0,padding:48,nodeRepulsion:5200,idealEdgeLength:edge=>edge.hasClass("cross-community")?170:78,edgeElasticity:.42,nestingFactor:1.35,gravity:.28,gravityCompound:1,gravityRangeCompound:1.5,tile:!0}).run(),()=>{resizeObserver?.disconnect(),graphRef.current=null,graph.destroy()}},[signature]),React.useEffect(()=>{let graph=graphRef.current;if(!graph)return;graph.nodes(".sg-memory-node").unselect(),graph.edges().removeClass("selected-relation");let selected=graph.getElementById(selectedId);if(!selected.length){setSelectedPoint(null);return}selected.select(),selected.connectedEdges().addClass("selected-relation"),graph.center(selected);let point=selected.renderedPosition(),container2=containerRef.current;setSelectedPoint({x:point.x,y:point.y,width:container2?.clientWidth||760,height:container2?.clientHeight||522})},[selectedId,signature]);let setGraphZoom=nextPercent=>{let graph=graphRef.current,container2=containerRef.current;if(!graph||!container2)return;let percent=Math.min(240,Math.max(25,Number(nextPercent)));graph.zoom({level:percent/100,renderedPosition:{x:container2.clientWidth/2,y:container2.clientHeight/2}})};if(!nodes3.length)return h(Empty,{title:"\u77E5\u8BC6\u56FE\u8C31\u6B63\u5728\u5F62\u6210",copy:"Event \u4F1A\u5728\u540E\u53F0\u5206\u6279\u6295\u5F71\u4E3A\u8282\u70B9\u4E0E\u5173\u7CFB\u3002"});if(!cytoscape4)return h(Empty,{title:"\u56FE\u8C31\u7EC4\u4EF6\u672A\u80FD\u52A0\u8F7D",copy:"\u8BF7\u91CD\u65B0\u52A0\u8F7D\u9875\u9762\u540E\u518D\u8BD5\u3002"});let selectedNode=nodes3.find(node=>node.id===selectedId);return h("div",{className:"sg-graph-canvas",role:"img","aria-label":visibleClusters.length+" \u4E2A Leiden \u4E3B\u9898\u7FA4\u7EC4\u7684\u77E5\u8BC6\u56FE\u8C31"},h("div",{ref:containerRef,className:"sg-cytoscape"}),h("div",{className:"sg-graph-zoom",role:"group","aria-label":"\u77E5\u8BC6\u56FE\u8C31\u7F29\u653E"},h("button",{type:"button",onClick:()=>setGraphZoom(zoomPercent-20),disabled:zoomPercent<=25,title:"\u7F29\u5C0F","aria-label":"\u7F29\u5C0F\u77E5\u8BC6\u56FE\u8C31"},"\u2212"),h("input",{type:"range",min:"25",max:"240",step:"5",value:String(zoomPercent),onInput:event3=>setGraphZoom(event3.target.value),title:"\u7F29\u653E\u6BD4\u4F8B "+zoomPercent+"%","aria-label":"\u77E5\u8BC6\u56FE\u8C31\u7F29\u653E\u6BD4\u4F8B","aria-valuetext":zoomPercent+"%"}),h("button",{type:"button",onClick:()=>setGraphZoom(zoomPercent+20),disabled:zoomPercent>=240,title:"\u653E\u5927","aria-label":"\u653E\u5927\u77E5\u8BC6\u56FE\u8C31"},"+")),h("div",{className:"sg-graph-a11y","aria-label":"\u77E5\u8BC6\u56FE\u8C31\u8282\u70B9\u5217\u8868"},displayedNodes.map(node=>h("button",{key:node.id,onClick:()=>onSelect(node.id)},node.name+"\uFF0C"+((node.tags||[])[0]||(NODE_META[node.type]||["\u5B9E\u4F53"])[0])+"\uFF0C"+GRAPH_IMPORTANCE_TEXT[importance.get(node.id)?.tier||"normal"]))),showSummary&&selectedNode&&selectedPoint?h(NodeSummaryBubble,{node:selectedNode,x:selectedPoint.x,y:selectedPoint.y,width:selectedPoint.width,height:selectedPoint.height,onViewDetails}):null,h("div",{className:"sg-graph-legend"},Object.entries(NODE_META).map(([type,meta3])=>h("span",{key:type},h("i",{style:{background:meta3[1]}}),meta3[0]))))}function NodeDetailPanel({node,nodes:nodes3,edges:edges3,events,onEvent}){if(!node)return h("aside",{className:"sg-long-detail sg-placeholder-detail"},"\u9009\u62E9\u8282\u70B9\u67E5\u770B\u5F53\u524D\u72B6\u6001\u4E0E\u8BC1\u636E");let meta3=NODE_META[node.type]||["\u5B9E\u4F53","#64748b","\u2022"],relations=edges3.filter(edge=>edge.status==="active"&&(edge.fromNodeId===node.id||edge.toNodeId===node.id)),eventMap=new Map(events.map(event3=>[event3.id,event3]));return h("aside",{className:"sg-long-detail"},h("div",{className:"sg-node-head"},h("span",{className:"sg-node-avatar",style:{background:meta3[1]}},meta3[2]),h("div",null,h("h2",null,node.name),h("span",{className:"sg-muted"},meta3[0]))),(node.tags||[]).length?h("section",null,h("h3",null,"\u8BED\u4E49\u6807\u7B7E"),h("div",{className:"sg-node-tags"},node.tags.map(tag=>h("span",{key:tag,className:"sg-node-tag"},tag)))):null,h("section",null,h("h3",null,"\u5F53\u524D\u72B6\u6001"),h("span",{className:"sg-status-dot"},"\u25CF "+(node.status==="active"?"\u6D3B\u8DC3":node.status)),node.currentState?h("p",{className:"sg-detail-copy"},node.currentState):null),h("section",null,h("h3",null,"\u5173\u952E\u4E8B\u5B9E"),node.facts?.filter(fact=>fact.status==="active").length?h("ul",null,node.facts.filter(fact=>fact.status==="active").map(fact=>h("li",{key:fact.id},h("strong",null,fact.key+"\uFF1A"),Array.isArray(fact.value)?fact.value.join("\u3001"):fact.value))):h("p",{className:"sg-muted"},"\u6682\u65E0\u5173\u952E\u4E8B\u5B9E")),h("section",null,h("h3",null,"\u76F8\u5173\u5173\u7CFB"),relations.length?relations.map(edge=>{let outgoing=edge.fromNodeId===node.id,other=nodes3.find(item=>item.id===(outgoing?edge.toNodeId:edge.fromNodeId));return h("div",{key:edge.id,className:"sg-relation-row"},h("span",null,outgoing?edge.relation:"\u88AB"+edge.relation),h("strong",null,other?.name||"\u672A\u77E5\u8282\u70B9"),h("small",null,Math.round(edge.confidence*100)+"%"))}):h("p",{className:"sg-muted"},"\u6682\u65E0\u5173\u7CFB")),h("section",null,h("h3",null,"\u652F\u6491\u4E8B\u4EF6"),(node.sourceEventIds||[]).flatMap(id2=>eventMap.get(id2)||[]).slice(0,8).map(event3=>h("button",{key:event3.id,className:"sg-support-event",onClick:()=>onEvent(event3.id)},h("span",null,exactTime(eventOccurrence(event3).value)+" \xB7 "+event3.title),h("b",null,"\u203A")))))}let CRITICALITY_INFO={routine:["\u666E\u901A\u4E8B\u4EF6",0],preference:["\u7528\u6237\u504F\u597D",.3],identity:["\u8EAB\u4EFD\u4FE1\u606F",.9],safety:["\u5B89\u5168\u76F8\u5173",1]};function eventDate(value){if(!value)return"";let date=new Date(value);return Number.isNaN(date.getTime())?String(value):new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit"}).format(date).replaceAll("/","-")}function participantIdentity(value){return String(value||"").normalize("NFKC").trim().toLocaleLowerCase().replace(/[\s._\-·•/\\]+/g,"")}function EventMetadata({event:event3,nodes:nodes3=[],onNode}){if(!event3)return null;let temporal=event3.temporal||{},start=eventDate(temporal.happenedStart),end=eventDate(temporal.happenedEnd),happened=start?start+(end&&end!==start?" \u2014 "+end:""):end,nodeMap=new Map(nodes3.map(node=>[node.id,node])),linked=[...new Set(temporal.participantNodeIds||[])].map(id2=>nodeMap.get(id2)).filter(Boolean),linkedNames=new Set(linked.flatMap(node=>[node.name,...node.aliases||[]]).map(participantIdentity).filter(Boolean)),seenText=new Set,unlinked=(temporal.participants||[]).map(name=>String(name||"").trim()).filter(name=>{let identity3=participantIdentity(name);return!identity3||linkedNames.has(identity3)||seenText.has(identity3)?!1:(seenText.add(identity3),!0)}),mentioned=eventDate(temporal.mentionedAt);return!happened&&!Number.isSafeInteger(event3.formedTurn)&&!linked.length&&!unlinked.length&&!mentioned?null:h("div",{className:"sg-event-metadata"},happened?h("span",{className:"sg-event-metadata-item"},h("b",null,"\u5B9E\u9645\u53D1\u751F\uFF1A"),happened):null,Number.isSafeInteger(event3.formedTurn)?h("span",{className:"sg-event-metadata-item"},h("b",null,"\u8BB0\u5FC6\u5F62\u6210\uFF1A"),"\u7B2C "+event3.formedTurn+" \u8F6E"):null,linked.length||unlinked.length?h("span",{className:"sg-event-metadata-item"},h("b",null,"\u53C2\u4E0E\uFF1A"),h("span",{className:"sg-event-participants"},linked.map(node=>h(NodePill,{key:node.id,node,onClick:onNode?event4=>onNode(node.id,event4):void 0})),unlinked.map(name=>h(StaticEntityPill,{key:name,name})))):null,mentioned?h("span",{className:"sg-event-metadata-item"},h("b",null,"\u63D0\u53CA\uFF1A"),mentioned):null)}let InfoPopoverContext=React.createContext(null);function InfoPopoverGroup({children}){let[openId,setOpenId]=React.useState(null);return h(InfoPopoverContext.Provider,{value:{openId,setOpenId}},children)}function InfoPopover({label,children,className=""}){let id2=React.useId(),rootRef=React.useRef(null),group2=React.useContext(InfoPopoverContext),[localOpenId,setLocalOpenId]=React.useState(null),openId=group2?.openId??localOpenId,setOpenId=group2?.setOpenId??setLocalOpenId,open=openId===id2;return React.useEffect(()=>{if(!open)return;let onPointerDown=event3=>{rootRef.current?.contains(event3.target)||setOpenId(null)},onKeyDown=event3=>{event3.key==="Escape"&&setOpenId(null)};return document.addEventListener("pointerdown",onPointerDown,!0),document.addEventListener("keydown",onKeyDown),()=>{document.removeEventListener("pointerdown",onPointerDown,!0),document.removeEventListener("keydown",onKeyDown)}},[open,setOpenId]),h("span",{ref:rootRef,className:"sg-info-disclosure "+className},h("button",{type:"button",className:"sg-info-trigger","aria-label":label,title:label,"aria-expanded":open,"aria-controls":id2,onClick:()=>setOpenId(current=>current===id2?null:id2)},"\u24D8"),open?h("div",{id:id2,className:"sg-info-popover",role:"dialog","aria-label":label,onPointerDown:event3=>event3.stopPropagation()},h("strong",{className:"sg-info-title"},label),children):null)}function AdoptionHistoryInfo({trajectory}){let history=Array.isArray(trajectory?.adoptionHistory)?trajectory.adoptionHistory:[],total=Number.isSafeInteger(trajectory?.effectiveAdoptions)?trajectory.effectiveAdoptions:0;return h(InfoPopover,{label:"\u91C7\u7EB3\u5386\u53F2"},total===0?h("p",null,"\u8BE5 Event \u5C1A\u672A\u88AB Agent \u91C7\u7EB3\u3002"):history.length?null:h("p",null,"\u5F53\u524D\u6CA1\u6709\u53EF\u5C55\u793A\u7684\u91C7\u7EB3\u56DE\u6267\u8BE6\u60C5\u3002"),history.length?h("ol",{className:"sg-adoption-history"},history.map((receipt,index)=>h("li",{key:receipt.receiptId||index},h("strong",null,"\u5DF2\u786E\u8BA4\u91C7\u7EB3"),h("time",{dateTime:receipt.createdAt},exactTime(receipt.createdAt)),h("span",null,"\u4F1A\u8BDD\uFF1A"+receipt.sessionId+" \xB7 \u7B2C "+receipt.turn+" \u8F6E"),Number.isFinite(receipt.relativeTurn)?h("span",null,"\u8DDD\u8BB0\u5FC6\u5F62\u6210 +"+receipt.relativeTurn+" \u8F6E"):null))):null)}function FloorWeightInfo({event:event3,floorWeight}){let type=CRITICALITY_INFO[event3?.criticality];return h(InfoPopover,{label:"\u6700\u4F4E\u6743\u91CD"},type?h("p",null,"\u6B64 Event \u88AB\u8BC6\u522B\u4E3A\u300C"+type[0]+"\u300D\uFF0C\u56E0\u6B64\u6700\u4F4E\u6743\u91CD\u4E3A "+Number(floorWeight).toFixed(2)+"\u3002"):h("p",null,"\u6B64 Event \u7684\u6700\u4F4E\u6743\u91CD\u4E3A "+Number(floorWeight).toFixed(2)+"\u3002"),h("p",null,"\u8BB0\u5FC6\u4F1A\u968F\u5BF9\u8BDD\u63A8\u8FDB\u9010\u6E10\u8870\u51CF\uFF0C\u4F46\u4E0D\u4F1A\u4F4E\u4E8E\u5BF9\u5E94\u7C7B\u578B\u7684\u6700\u4F4E\u6743\u91CD\u3002"),type?h("dl",{className:"sg-floor-table"},Object.entries(CRITICALITY_INFO).map(([key,value])=>h(React.Fragment,{key},h("dt",{className:key===event3.criticality?"current":""},value[0]),h("dd",{className:key===event3.criticality?"current":""},Number(value[1]).toFixed(2))))):null)}function denseWeightPath(points,x2,y2){return points.reduce((path,point,index)=>{let px=x2(point.turn),py=y2(point.weight);return index===0?"M"+px.toFixed(1)+" "+py.toFixed(1):path+" L"+px.toFixed(1)+" "+py.toFixed(1)},"")}function relativeTurnTicks(maximum){if(maximum<=0)return[0];let target=Math.max(1,maximum/5),magnitude=10**Math.floor(Math.log10(target)),step3=[1,2,5,10].map(value=>value*magnitude).reduce((best,value)=>Math.abs(value-target)<Math.abs(best-target)?value:best),ticks=[];for(let value=0;value<=maximum;value+=step3)ticks.push(Math.round(value));return ticks.at(-1)!==maximum&&ticks.push(maximum),[...new Set(ticks)]}function MemoryWeightTrajectory({event:event3}){let[hoveredSegment,setHoveredSegment]=React.useState(null),trajectory=event3?.weightTrajectory,points=Array.isArray(trajectory?.points)?trajectory.points.filter(point=>Number.isFinite(point?.turn)&&Number.isFinite(point?.weight)):[],formedTurn=Number.isSafeInteger(event3?.formedTurn)?event3.formedTurn:Number.isSafeInteger(trajectory?.formedTurn)?trajectory.formedTurn:null,trajectoryStartTurn=Number.isSafeInteger(trajectory?.trajectoryStartTurn)?trajectory.trajectoryStartTurn:points[0]?.turn,currentWeight=Number.isFinite(trajectory?.currentWeight)?trajectory.currentWeight:Number(event3?.weight?.forcedCap??1),effectiveAdoptions=Number.isSafeInteger(trajectory?.effectiveAdoptions)?trajectory.effectiveAdoptions:Math.max(0,Number(event3?.weight?.mentionCount||1)-1),floorWeight=Number.isFinite(event3?.weight?.floorWeight)?event3.weight.floorWeight:Number.isFinite(trajectory?.floorWeight)?trajectory.floorWeight:0,metrics=h("div",{className:"sg-weight-metrics"},h("div",{className:"sg-weight-metric"},h("span",null,"\u5F53\u524D\u6743\u91CD"),h("strong",null,Number(currentWeight).toFixed(2))),h("div",{className:"sg-weight-metric"},h("span",null,"Agent \u5DF2\u91C7\u7EB3"),h("span",{className:"sg-weight-value"},h("strong",null,effectiveAdoptions+" \u6B21"),h(AdoptionHistoryInfo,{trajectory}))),h("div",{className:"sg-weight-metric"},h("span",null,"\u6700\u4F4E\u6743\u91CD"),h("span",{className:"sg-weight-value"},h("strong",null,Number(floorWeight).toFixed(2)),h(FloorWeightInfo,{event:event3,floorWeight}))));if(!trajectory||points.length===0)return h(React.Fragment,null,h("div",{className:"sg-weight-header"},h("h3",{className:"sg-section-title"},"\u8BB0\u5FC6\u72B6\u6001")),metrics);let segments=(Array.isArray(trajectory.segments)?trajectory.segments:[points]).map(segment=>{let source=Array.isArray(segment)?segment:segment?.points,certainty=Array.isArray(segment)?"known":segment?.certainty==="incomplete"?"incomplete":"known";return{certainty,points:(Array.isArray(source)?source:[]).filter(point=>Number.isFinite(point?.turn)&&Number.isFinite(point?.weight)).map(point=>({...point,weight:Math.max(certainty==="incomplete"?floorWeight:0,Math.min(1,point.weight))}))}}).filter(segment=>segment.points.length),maxTurn=Math.max(...points.map(point=>point.turn)),minTurn=Math.min(Number.isSafeInteger(trajectoryStartTurn)?trajectoryStartTurn:maxTurn,...points.map(point=>point.turn)),turnSpan=Math.max(0,maxTurn-minTurn),x2=turn=>turnSpan===0?307:48+(turn-minTurn)/turnSpan*518,y2=weight8=>22+(1-Math.max(0,Math.min(1,weight8)))*154,nodeByTurn=new Map;for(let point of points.filter(candidate=>candidate.kind!=="sample")){let existing=nodeByTurn.get(point.turn);!existing||point.kind==="adoption"||point.kind==="current"&&existing.kind!=="adoption"?nodeByTurn.set(point.turn,{...point,isCurrent:point.kind==="current"||existing?.isCurrent}):point.kind==="current"&&nodeByTurn.set(point.turn,{...existing,isCurrent:!0})}let nodes3=[...nodeByTurn.values()].sort((left,right)=>left.turn-right.turn),adoptionNodes=nodes3.filter(point=>point.kind==="adoption"),ticks=relativeTurnTicks(turnSpan),relativeAxis=formedTurn!==null,nodeLabel=point=>point.kind==="creation"?point.label||"":point.kind==="current"?"\u5F53\u524D":point.kind!=="adoption"?"":point.isCurrent?"\u6700\u8FD1\u91C7\u7EB3 \xB7 \u5F53\u524D":adoptionNodes.length<=3||point.turn===trajectory.latestAdoptionTurn?point.adoptionCount>1?"\u91C7\u7EB3 \xD7"+point.adoptionCount:"\u91C7\u7EB3":"",nodeTooltip=point=>{let count=point.kind==="adoption"&&point.adoptionCount>1?"\uFF08\u540C\u8F6E "+point.adoptionCount+" \u6B21\uFF09":"";return(point.kind==="creation"?trajectory.formationTurnSource==="sourceBlock"?"\u6765\u6E90 Block \u7ED3\u675F":"\u8BB0\u5FC6\u5F62\u6210":point.kind==="adoption"?"Agent \u91C7\u7EB3"+count:"\u5F53\u524D\u6743\u91CD")+" \xB7 \u7B2C "+point.turn+" \u8F6E \xB7 \u6743\u91CD\uFF1A"+Number(point.weight).toFixed(2)},occupiedLabels=[],labelPositions=new Map;for(let[index,point]of nodes3.entries()){let label=nodeLabel(point);if(!label)continue;let px=x2(point.turn),anchor=index===0?"start":index===nodes3.length-1?"end":"middle",width2=Math.max(28,label.length*6.6),left=anchor==="start"?px:anchor==="end"?px-width2:px-width2/2,candidates=[y2(point.weight)-11,y2(point.weight)-27,y2(point.weight)+24,y2(point.weight)+40],py=candidates.map(value=>Math.max(13,Math.min(169,value))).find(value=>!occupiedLabels.some(box=>left<box.right+7&&left+width2>box.left-7&&Math.abs(value-box.y)<15))??Math.max(13,Math.min(169,candidates.at(-1)));occupiedLabels.push({left,right:left+width2,y:py}),labelPositions.set(point,{x:px,y:py,anchor,label})}let showSegmentTooltip=(event4,segment)=>{let bounds2=event4.currentTarget?.ownerSVGElement?.parentElement?.getBoundingClientRect?.();if(!bounds2)return;let first2=segment.points[0],last2=segment.points.at(-1);setHoveredSegment({x:Math.max(128,Math.min(bounds2.width-128,event4.clientX-bounds2.left)),y:Math.max(18,event4.clientY-bounds2.top),below:event4.clientY-bounds2.top<72,certainty:segment.certainty,startTurn:first2.turn,endTurn:last2.turn,startWeight:first2.weight,endWeight:last2.weight})};return h(React.Fragment,null,h("div",{className:"sg-weight-header"},h("h3",{className:"sg-section-title"},"\u8BB0\u5FC6\u72B6\u6001")),metrics,h("div",{className:"sg-weight-chart"},h("svg",{viewBox:"0 0 620 238",preserveAspectRatio:"xMidYMid meet",role:"img","aria-label":"\u8BE5 Event \u7684\u8BB0\u5FC6\u6743\u91CD\u8F68\u8FF9\uFF0C\u6A2A\u8F74\u4E3A"+(relativeAxis?"\u8DDD\u8BB0\u5FC6\u5F62\u6210\u7684\u5BF9\u8BDD\u8F6E\u6B21":"\u5BF9\u8BDD\u8F6E\u6B21")+"\uFF0C\u7EB5\u8F74\u4E3A\u8BB0\u5FC6\u6743\u91CD\uFF0C\u6700\u4F4E\u6743\u91CD\u4E3A "+Number(floorWeight).toFixed(2)},[0,.5,1].map(weight8=>h(React.Fragment,{key:weight8},h("line",{className:"sg-weight-grid",x1:"48",y1:String(y2(weight8)),x2:"566",y2:String(y2(weight8))}),h("text",{className:"sg-weight-axis-label",x:"39",y:String(y2(weight8)+4),textAnchor:"end"},weight8.toFixed(1)))),h("line",{className:"sg-weight-floor",x1:"48",y1:String(y2(floorWeight)),x2:"566",y2:String(y2(floorWeight))}),h("text",{className:"sg-weight-floor-label",x:"562",y:String(y2(floorWeight)+16),textAnchor:"end"},"\u6700\u4F4E\u6743\u91CD "+Number(floorWeight).toFixed(2)),segments.filter(segment=>segment.points.length>1).map((segment,index)=>h(React.Fragment,{key:"segment:"+index},h("path",{className:"sg-weight-line "+(segment.certainty==="incomplete"?"incomplete":"known"),d:denseWeightPath(segment.points,x2,y2)}),h("path",{className:"sg-weight-line-hit",d:denseWeightPath(segment.points,x2,y2),onPointerEnter:event4=>showSegmentTooltip(event4,segment),onPointerMove:event4=>showSegmentTooltip(event4,segment),onPointerLeave:()=>setHoveredSegment(null),"aria-label":segment.certainty==="incomplete"?"\u65E7\u6570\u636E\u63A8\u7B97\u7684\u8BB0\u5FC6\u6743\u91CD\u8F68\u8FF9":"\u5DF2\u786E\u8BA4\u7684\u8BB0\u5FC6\u6743\u91CD\u8F68\u8FF9"}))),nodes3.map((point,index)=>h(React.Fragment,{key:point.kind+":"+point.turn+":"+index},h("circle",{className:"sg-weight-node "+point.kind,cx:String(x2(point.turn)),cy:String(y2(point.weight)),r:point.kind==="adoption"?"6":"5"},h("title",null,nodeTooltip(point))),labelPositions.has(point)?h("text",{className:"sg-weight-node-label",x:String(labelPositions.get(point).x),y:String(labelPositions.get(point).y),textAnchor:labelPositions.get(point).anchor},labelPositions.get(point).label):null)),ticks.map(offset=>{let turn=minTurn+offset;return h(React.Fragment,{key:"tick:"+turn},h("line",{className:"sg-weight-tick",x1:String(x2(turn)),y1:"176",x2:String(x2(turn)),y2:"181"}),h("text",{className:"sg-weight-axis-label",x:String(x2(turn)),y:"215",textAnchor:offset===0?"start":offset===turnSpan?"end":"middle"},relativeAxis?turn-formedTurn:turn))}),h("text",{className:"sg-weight-axis-label",x:"307",y:"232",textAnchor:"middle"},relativeAxis?"\u8DDD\u8BB0\u5FC6\u5F62\u6210\u7684\u5BF9\u8BDD\u8F6E\u6B21":"\u5BF9\u8BDD\u8F6E\u6B21")),hoveredSegment?h("div",{className:"sg-weight-tooltip "+(hoveredSegment.below?"below":"above"),style:{left:hoveredSegment.x+"px",top:hoveredSegment.y+"px"},role:"tooltip"},h("strong",null,hoveredSegment.certainty==="incomplete"?"\u65E7\u6570\u636E\u63A8\u7B97\u8F68\u8FF9":"\u5DF2\u786E\u8BA4\u8F68\u8FF9"),h("small",null,"\u7B2C "+hoveredSegment.startTurn+"\u2013"+hoveredSegment.endTurn+" \u8F6E \xB7 "+Number(hoveredSegment.startWeight).toFixed(2)+" \u2192 "+Number(hoveredSegment.endWeight).toFixed(2)),hoveredSegment.certainty==="incomplete"?h("small",null,"\u65E7\u7248\u672C\u672A\u8BB0\u5F55\u90E8\u5206\u91C7\u7EB3\u7684\u51C6\u786E\u8F6E\u6B21"):null):null))}function CopyEventId({value}){let[copied,setCopied]=React.useState(!1);return h("button",{type:"button",className:"sg-copy-id",onClick:()=>{globalThis.navigator?.clipboard?.writeText&&globalThis.navigator.clipboard.writeText(String(value)).then(()=>{setCopied(!0),window.setTimeout(()=>setCopied(!1),1400)})},disabled:!globalThis.navigator?.clipboard?.writeText},copied?"\u5DF2\u590D\u5236":"\u590D\u5236")}function EventSourceDisclosure({sourceMessages}){return sourceMessages?.length?h(CitationDisclosure,{title:"\u6765\u6E90\u4E0E\u8BC1\u636E"},h("p",{className:"sg-provenance-note"},"\u4EE5\u4E0B\u539F\u59CB\u5185\u5BB9\u7528\u4E8E\u67E5\u770B\u4E0E\u8FFD\u6EAF\u4F9D\u636E\uFF0C\u4E0D\u4EE3\u8868\u5168\u90E8\u5185\u5BB9\u90FD\u53C2\u4E0E\u4E86\u67D0\u6B21\u56DE\u7B54\u3002"),h("div",{className:"sg-citation-messages"},sourceMessages.map((message,index)=>h("div",{key:message.id||index,className:"sg-citation-message"},h("span",{className:"sg-citation-message-role"},(message.role||"message")+(message.createdAt?" \xB7 "+exactTime(message.createdAt):"")),String(message.content||""))))):null}function EventTechnicalDisclosure({event:event3,citation}){let evidenceRef=String(citation?.evidenceRef||""),redundantEvidenceRef=!evidenceRef||evidenceRef===event3.id||evidenceRef==="event:"+event3.id;return h(CitationDisclosure,{title:"\u6280\u672F\u4FE1\u606F"},h("dl",{className:"sg-event-technical"},h("dt",null,"Event ID"),h("dd",null,h("code",null,event3.id),h(CopyEventId,{value:event3.id})),redundantEvidenceRef?null:h(React.Fragment,null,h("dt",null,"evidenceRef"),h("dd",null,h("code",null,evidenceRef))),citation?.detailKind?h(React.Fragment,null,h("dt",null,"detailKind"),h("dd",null,h("code",null,citation.detailKind))):null,event3.sourceBlockId?h(React.Fragment,null,h("dt",null,"\u6765\u6E90 Block"),h("dd",null,h("code",null,event3.sourceBlockId))):null))}function EventMemoryDetails({event:event3,sourceMessages=[],citation=null,relatedEvents=[]}){let memoryContent=event3?.summary;return h(React.Fragment,null,h("section",{className:"sg-event-section"},h("h3",{className:"sg-event-section-title"},"\u8BB0\u5FC6\u5185\u5BB9"),h("p",{className:"sg-event-memory-copy"},memoryContent||"\u6682\u65E0\u53EF\u5C55\u793A\u7684\u8BB0\u5FC6\u5185\u5BB9\u3002")),h("section",{className:"sg-event-section sg-event-weight-section"},h(MemoryWeightTrajectory,{event:event3})),relatedEvents.length?h(CitationDisclosure,{title:"\u5173\u8054\u4FE1\u606F"},h("div",{className:"sg-citation-events"},relatedEvents.map((related,index)=>h("article",{key:related.id||index,className:"sg-citation-event"},h("strong",null,related.title||"\u5173\u8054\u4E8B\u4EF6"),h("p",null,related.summary||"\u6682\u65E0\u6458\u8981"))))):null,h(EventSourceDisclosure,{sourceMessages}),h(EventTechnicalDisclosure,{event:event3,citation}))}function EventDetailPanel({event:event3,nodes:nodes3,events,onNode,openSource,className="",onMouseEnter,onMouseLeave}){if(!event3)return h("aside",{className:"sg-long-detail sg-placeholder-detail"},"\u9009\u62E9\u4E8B\u4EF6\u67E5\u770B\u5B8C\u6574\u65F6\u95F4\u3001\u5173\u7CFB\u4E0E\u8BC1\u636E");let temporal=event3.temporal||{},eventMap=new Map(events.map(item=>[item.id,item])),relations=EVENT_RELATIONS.flatMap(([key,label])=>{let value=temporal[key];return(Array.isArray(value)?value:value?[value]:[]).map(id2=>({id:id2,label}))});return h(InfoPopoverGroup,{key:event3.id},h("aside",{className:"sg-long-detail "+className,onMouseEnter,onMouseLeave},h("div",{className:"sg-event-detail-head"},h("div",null,h("span",{className:"sg-event-detail-kicker"},"Event"),h("h2",null,event3.title)),h("span",{className:"sg-event-status "+(temporal.status||"unknown")},EVENT_STATUS_TEXT[temporal.status]||"\u672A\u77E5")),h(EventMetadata,{event:event3,nodes:nodes3,onNode}),h("section",null,h("h3",null,"\u8BB0\u5FC6\u5185\u5BB9"),h("p",{className:"sg-detail-copy"},event3.summary||"\u6682\u65E0\u53EF\u5C55\u793A\u7684\u8BB0\u5FC6\u5185\u5BB9\u3002")),relations.length?h("section",null,h("h3",null,"\u4E8B\u4EF6\u5173\u7CFB"),relations.map(relation=>h("div",{key:relation.label+relation.id,className:"sg-relation-row"},h("span",null,relation.label),h("strong",null,eventMap.get(relation.id)?.title||relation.id)))):null,event3.weightTrajectory?h("section",null,h(MemoryWeightTrajectory,{event:event3})):null,h("button",{className:"sg-source-button",onClick:()=>openSource(event3)},"\u67E5\u770B\u6765\u6E90\u4E0E\u8BC1\u636E \u2192")))}function dismissedDreamKey(id2){return id2?"sg-dream-dismiss:"+id2:""}function dreamDismissed(id2){let key=dismissedDreamKey(id2);if(!key||typeof localStorage>"u")return!1;try{return localStorage.getItem(key)==="1"}catch{return!1}}function dismissDream(id2){let key=dismissedDreamKey(id2);if(!(!key||typeof localStorage>"u"))try{localStorage.setItem(key,"1")}catch{}}function TimelineList({events,nodes:nodes3,onSelect,selectedId,floating=!1,onNode,openSource,dreaming=null}){let[preview,setPreview]=React.useState(null),pinnedId=React.useRef(""),hideTimer=React.useRef(null),cancelHide=()=>{hideTimer.current&&window.clearTimeout(hideTimer.current),hideTimer.current=null},hidePreview=()=>{cancelHide(),setPreview(null),pinnedId.current=""},showPreview=(event3,target,pin=!1)=>{if(!floating||!pin&&pinnedId.current)return;cancelHide();let rect=target.getBoundingClientRect(),width2=Math.min(380,window.innerWidth-24),maxHeight=Math.min(620,window.innerHeight*.72),left=rect.right+12+width2<=window.innerWidth-12?rect.right+12:Math.max(12,rect.left-width2-12),top=Math.min(Math.max(12,rect.top-8),Math.max(12,window.innerHeight-maxHeight-12));setPreview({event:event3,left,top}),pin&&(pinnedId.current=event3.id)},scheduleHide=()=>{pinnedId.current||(cancelHide(),hideTimer.current=window.setTimeout(()=>setPreview(null),140))};React.useEffect(()=>()=>cancelHide(),[]);let sorted=events.slice().sort((a,b)=>String(eventOccurrence(b).value).localeCompare(String(eventOccurrence(a).value))),days=[];for(let event3 of sorted){let info=eventOccurrence(event3),key=eventDayKey(info.value)||"unknown",group2=days.find(item=>item.key===key);group2||(group2={key,label:key==="unknown"?{day:"?",week:"\u53D1\u751F\u65F6\u95F4\u672A\u77E5"}:eventDayLabel(info.value),items:[]},days.push(group2)),group2.items.push({event:event3,info})}let nodeMap=new Map(nodes3.map(node=>[node.id,node])),usedCount=event3=>Number(event3?.weight?.mentionCount||0)-1,[dreamHidden,setDreamHidden]=React.useState(()=>dreamDismissed(dreaming?.id)),dreamRun=!dreamHidden&&dreaming&&["completed","terminated"].includes(dreaming.status)&&dreaming.updatedAt?dreaming:null,dreamDay=dreamRun?eventDayKey(dreamRun.updatedAt):"",dreamStrip=kind=>h("div",{className:"sg-tl-day sg-tl-dream","aria-label":"Dreaming \u6574\u7406\u8BB0\u5F55"},h("div",{className:"sg-tl-date"}),h("div",{className:"sg-tl-axis","aria-hidden":"true"}),h("div",{className:"sg-tl-items"},h("div",{className:"sg-dream"},h("span",null,kind==="terminated"?"\u6574\u7406\u5DF2\u7EC8\u6B62":"\u6574\u7406\u8FC7"),h("span",{className:"sg-m","aria-hidden":"true"},Array.from({length:4},(_,index)=>h("i",{key:index})),h("span",null,"\u2192"),Array.from({length:2},(_,index)=>h("i",{key:"n"+index,className:"o"}))),h("span",{className:"sg-dream-note"},kind==="terminated"?"\u6539\u8FC7\u7684\u7AE0\u8282\u5DF2\u4FDD\u7559":"\u7AE0\u8282\u5DF2\u5408\u5E76"),h("button",{type:"button",className:"sg-dream-close","aria-label":"\u5173\u95ED\u8FD9\u6B21\u6574\u7406\u8BB0\u5F55",onClick:()=>{dismissDream(dreaming?.id),setDreamHidden(!0)}},"\xD7"))));return h("div",{className:"sg-timeline sg-tl"},dreamRun&&!days.some(group2=>group2.key===dreamDay)?dreamStrip(dreamRun.status):null,days.map(group2=>h(React.Fragment,{key:group2.key},h("section",{className:"sg-tl-day","aria-label":group2.label.week},h("div",{className:"sg-tl-date"},h("b",null,group2.label.day),h("span",null,group2.label.week)),h("div",{className:"sg-tl-axis","aria-hidden":"true"}),h("div",{className:"sg-tl-items"},group2.items.map(({event:event3,info})=>{let temporal=event3.temporal||{},faded=event3.status==="forgotten"||event3.status==="archived"||temporal.status==="cancelled";return h("button",{key:event3.id,className:"sg-ev"+(faded?" fade":"")+(event3.id===selectedId?" selected":""),"data-event-id":event3.id,onMouseEnter:hover=>showPreview(event3,hover.currentTarget),onMouseLeave:scheduleHide,onFocus:focus=>showPreview(event3,focus.currentTarget),onBlur:scheduleHide,onClick:click=>{onSelect(event3.id),showPreview(event3,click.currentTarget,!0)}},h("i",{className:"sg-nd","aria-hidden":"true"}),h("span",{className:"sg-t"},event3.title||"\u8BB0\u5FC6\u4E8B\u4EF6"),h("span",{className:"sg-tp"},temporal.eventType?EVENT_TYPE_TEXT[temporal.eventType]||"\u5176\u4ED6":"\u672A\u5206\u7C7B"),usedCount(event3)>0?h(UsedMark,{count:usedCount(event3),title:"\u88AB\u56DE\u7B54\u7528\u5230 "+usedCount(event3)+" \u6B21"}):h("span"))}))),group2.key===dreamDay?dreamStrip(dreamRun.status):null)),floating&&preview?h("div",{className:"sg-event-popover",style:{left:preview.left+"px",top:preview.top+"px"},onMouseEnter:cancelHide,onMouseLeave:scheduleHide},h("button",{type:"button",className:"sg-popover-close","aria-label":"\u5173\u95ED\u4E8B\u4EF6\u8BE6\u60C5",onClick:hidePreview},"\xD7"),h(EventDetailPanel,{event:preview.event,nodes:nodes3,events,onNode,openSource})):null)}function chapterOrdinal(value){let digits=["\u96F6","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D","\u4E03","\u516B","\u4E5D"];return value<10?digits[value]:value<100?(value<20?"":digits[Math.floor(value/10)])+"\u5341"+(value%10?digits[value%10]:""):String(value)}function topicSections(topic){return(topic.sections||[]).map(section=>({...section,uiKey:section.key,uiTitle:section.title}))}function directoryScrollAction(saved,section,namespace,viewName){return saved?section!=="long"||namespace!==saved.namespace?"clear":viewName==="root"?"restore":viewName==="event"?"detail":"clear":"none"}function DirectoryFold({open,id:id2,children}){let bodyRef=React.useRef(null);return React.useEffect(()=>{open?bodyRef.current?.removeAttribute("inert"):bodyRef.current?.setAttribute("inert","")},[open]),h("div",{id:id2,ref:bodyRef,className:"sg-directory-fold "+(open?"open":""),"aria-hidden":!open},h("div",{className:"sg-directory-fold-inner"},children))}function TopicEventRow({event:event3,number:number3,openEvent}){return h("button",{type:"button",className:"sg-topic-event","data-topic-event-id":event3.id,onClick:click=>openEvent(event3,click.currentTarget),title:event3.title||event3.summary||void 0},number3?h("span",{className:"sg-directory-number"},number3):h("span",{className:"sg-topic-pending-mark","aria-hidden":"true"},"\xB7"),h("span",{className:"sg-topic-event-title"},event3.title||event3.summary||"\u8BB0\u5FC6\u4E8B\u4EF6"),h("span",{className:"sg-topic-event-date","data-event-date":eventDayKey(event3.createdAt)||"","aria-hidden":"true"}),h("span",{className:"sg-topic-event-arrow","aria-hidden":"true"},"\u2197"))}function useTopicEventPages({namespace,revision,topicId,sectionKey="",total,active,wantAll,onDirectoryChanged}){let key=JSON.stringify([namespace,revision,topicId,sectionKey]),empty2={key,epoch:0,items:[],total,nextOffset:total?0:null,loading:!1,error:""},[state,setState]=React.useState(empty2),[retry,setRetry]=React.useState(0),requestRef=React.useRef({key,epoch:0,generation:0,controller:null}),changedRef=React.useRef(onDirectoryChanged);changedRef.current=onDirectoryChanged,requestRef.current.key!==key&&(requestRef.current.controller?.abort(),requestRef.current={key,epoch:requestRef.current.epoch+1,generation:requestRef.current.generation+1,controller:null});let epoch=requestRef.current.epoch,current=state.key===key&&state.epoch===epoch?state:{...empty2,epoch};return React.useEffect(()=>{if(!active||!revision||!total||current.error||current.items.length&&(!wantAll||current.nextOffset===null))return;let controller=new AbortController,generation=++requestRef.current.generation;requestRef.current.controller=controller;let valid2=()=>!controller.signal.aborted&&requestRef.current.key===key&&requestRef.current.generation===generation,items=current.items,nextOffset=current.nextOffset??0,pageTotal=current.total;return setState({...current,loading:!0,error:""}),(async()=>{do{let offset=nextOffset,page=await api2("topic-events",{namespace,topicId,...sectionKey?{sectionKey}:{},offset,limit:9,expectedRevision:revision},{signal:controller.signal});if(!valid2())return;if(page.revision!==revision||page.namespace!==namespace||page.topicId!==topicId||String(page.sectionKey||"")!==sectionKey){let error3=new Error("\u76EE\u5F55\u5DF2\u66F4\u65B0");throw error3.code="directory-changed",error3}if(!Array.isArray(page.items)||page.items.length>9||Number(page.offset)!==offset||page.nextOffset!==null&&(!Number.isSafeInteger(page.nextOffset)||page.nextOffset<=offset))throw new Error("\u4E8B\u4EF6\u5206\u9875\u54CD\u5E94\u65E0\u6548");items=[...items,...page.items],pageTotal=Number(page.total||0),nextOffset=page.nextOffset,setState({key,epoch,items,total:pageTotal,nextOffset,loading:wantAll&&nextOffset!==null,error:""})}while(wantAll&&nextOffset!==null&&valid2())})().catch(reason=>{!valid2()||reason?.name==="AbortError"||(reason?.code==="directory-changed"||reason?.status===409||reason?.status===404?(setState({key,epoch,items:[],total,nextOffset:0,loading:!1,error:"\u76EE\u5F55\u5DF2\u6709\u66F4\u65B0\uFF0C\u6B63\u5728\u8BFB\u53D6\u6700\u65B0\u76EE\u5F55\u3002"}),changedRef.current?.()):setState({key,epoch,items,total:pageTotal,nextOffset,loading:!1,error:"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4E8B\u4EF6\uFF0C\u8BF7\u91CD\u8BD5\u3002"}))}),()=>{controller.abort(),requestRef.current.generation+=1,setState(previous=>previous.key===key&&previous.epoch===epoch&&previous.loading?{...previous,loading:!1}:previous)}},[key,active,wantAll,retry]),{...current,items:revision?wantAll?current.items:current.items.slice(0,9):[],retry:()=>{setState({...current,error:""}),setRetry(value=>value+1)}}}function TopicEventList({namespace,revision,topicId,sectionKey="",total,active,openEvent,numberPrefix,onDirectoryChanged,expandLabel,collapseLabel="\u6536\u8D77\u591A\u4F59\u4E8B\u4EF6"}){let[showAll,setShowAll]=React.useState(!1),page=useTopicEventPages({namespace,revision,topicId,sectionKey,total,active,wantAll:showAll,onDirectoryChanged});return h("div",{className:"sg-topic-event-list","data-topic-event-scope":topicId+":"+sectionKey},page.items.map((event3,index)=>h(TopicEventRow,{key:event3.id,event:event3,number:numberPrefix?numberPrefix+"."+(index+1):void 0,openEvent})),page.loading?h("p",{className:"sg-topic-read-status",role:"status"},showAll?"\u6B63\u5728\u8BFB\u53D6\u4E8B\u4EF6 \xB7 "+page.items.length+" / "+page.total:"\u6B63\u5728\u8BFB\u53D6\u4E8B\u4EF6\u2026"):null,page.error?h("div",{className:"sg-topic-read-error",role:"alert"},h("span",null,page.error),h("button",{type:"button",onClick:page.retry},"\u91CD\u65B0\u8BFB\u53D6\u4E8B\u4EF6")):null,page.total>9?h("button",{type:"button",className:"sg-topic-show-all",disabled:!showAll&&(page.loading||!!page.error),"aria-expanded":showAll,onClick:()=>setShowAll(value=>!value)},showAll?collapseLabel:"\u8FD8\u6709 "+(page.total-9)+" \u6761\u4E8B\u4EF6 \xB7 "+(expandLabel||"\u5C55\u5F00\u5168\u90E8")):null)}function TopicSection({part,chapter,index,topicId,namespace,revision,active,openEvent,onDirectoryChanged,open=!1,onToggle}){let[overviewOpen,setOverviewOpen]=React.useState(!0),sectionNumber=chapter+"."+index,regionId="sg-topic-"+encodeURIComponent(topicId)+"-"+encodeURIComponent(part.uiKey),sourceCount=Number(part.sourceEventCount||0),paragraphs=(part.paragraphs||[]).map(paragraph=>paragraph.text||"").filter(Boolean);return h("section",{className:"sg-topic-section","data-section-index":String(index)},h("h3",{className:"sg-topic-section-heading"},h("button",{type:"button",className:"sg-topic-section-toggle"+(open?" cur":""),title:part.uiTitle,"data-count":String(sourceCount),"aria-expanded":open,"aria-controls":regionId,onClick:()=>onToggle?.(part.uiKey)},h("span",{className:"sg-directory-number"},sectionNumber),h("span",{className:"sg-toc-sec-title"},part.uiTitle),h("span",{className:"sg-toc-lead","aria-hidden":"true"}),h("span",{className:"sg-toc-cnt",title:sourceCount+" \u6761\u4E8B\u4EF6"},String(sourceCount)),h("span",{className:"sg-directory-chevron","aria-hidden":"true"},"\u203A"))),h(DirectoryFold,{open,id:regionId},h("div",{className:"sg-topic-section-body"},h("div",{className:"sg-leaf-head"},h("span",{className:"sg-leaf-k"},sectionNumber),h("h3",null,part.uiTitle),h("p",{className:"sg-leaf-sum"},paragraphs.join(`
1194
1340
 
1195
- `)||"\u8FD9\u4E00\u8282\u6682\u65F6\u6CA1\u6709\u6982\u8981\u3002")),(part.paragraphs||[]).length?h("div",{className:"sg-topic-overview"},h("h4",{className:"sg-topic-overview-heading"},h("button",{type:"button",className:"sg-topic-overview-toggle","aria-expanded":overviewOpen,"aria-controls":regionId+"-overview",onClick:()=>setOverviewOpen(current=>!current)},h("span",{className:"sg-directory-number"},sectionNumber+".0"),h("span",null,"\u603B\u89C8"),h("span",{className:"sg-directory-chevron","aria-hidden":"true"},"\u203A"))),h(DirectoryFold,{open:overviewOpen,id:regionId+"-overview"},(part.paragraphs||[]).map((paragraph,paragraphIndex)=>h("p",{key:paragraphIndex,className:"sg-topic-overview-text","data-overview-paragraph-index":String(paragraphIndex)},paragraph.text||"\u6682\u65E0\u603B\u89C8")))):null,h(TopicEventList,{namespace,revision,topicId,sectionKey:part.uiKey,total:sourceCount,active:active&&open,openEvent,numberPrefix:sectionNumber,onDirectoryChanged}),h("div",{className:"sg-leaf-folio","aria-hidden":"true"},"\u2014 \u7B2C"+chapterOrdinal(chapter)+"\u7AE0 \xB7 "+sectionNumber+" \u2014"))))}function TopicChapter({topic,number:number3,namespace,revision,active,openEvent,onDirectoryChanged,expandRequest=0,openSection="",onSectionToggle}){let[open,setOpen]=React.useState(!0),[otherOpen,setOtherOpen]=React.useState(!1);React.useEffect(()=>{expandRequest>0&&setOpen(!0)},[expandRequest]);let regionId="sg-topic-chapter-"+encodeURIComponent(topic.id),chapterLabel="\u7B2C"+chapterOrdinal(number3)+"\u7AE0",chapterEvents=topicSections(topic).reduce((sum,part)=>sum+Number(part.sourceEventCount||0),0);return h("article",{className:"sg-topic-chapter","data-topic-id":topic.id},h("header",{className:"sg-topic-chapter-header"},h("span",{className:"sg-topic-chapter-number","aria-hidden":"true"},String(number3).padStart(2,"0")),h("div",{className:"sg-topic-chapter-copy"},h("h2",null,h("button",{type:"button",className:"sg-topic-chapter-toggle",title:topic.title,"data-count":String(chapterEvents),"aria-expanded":open,"aria-controls":regionId,"aria-label":chapterLabel+" "+topic.title,onClick:()=>setOpen(current=>!current)},h("span",{className:"sg-topic-chapter-label"},chapterLabel),h("span",{className:"sg-topic-chapter-title"},topic.title),h("span",{className:"sg-toc-lead","aria-hidden":"true"}),h("span",{className:"sg-toc-cnt",title:chapterEvents+" \u6761\u4E8B\u4EF6"},String(chapterEvents)),h("span",{className:"sg-directory-chevron","aria-hidden":"true"},"\u203A"))),topic.description?h("p",{className:"sg-topic-description"},topic.description):null)),h(DirectoryFold,{open,id:regionId},h("div",{className:"sg-topic-sections"},topicSections(topic).map((part,index)=>h(TopicSection,{key:part.uiKey,part,chapter:number3,index:index+1,topicId:topic.id,namespace,revision,open:openSection===part.uiKey,onToggle:key=>onSectionToggle?.(key,part),active:active&&open,openEvent,onDirectoryChanged})),(topic.sections||[]).length?null:h("p",{className:"sg-topic-no-overview"},"\u8FD9\u4E2A\u4E3B\u9898\u8FD8\u6CA1\u6709\u5C0F\u8282\u3002"),(()=>{let remaining=Number(topic.coverage?.unassignedEvents??topic.coverage?.omittedEvents??0);return remaining?h("details",{className:"sg-topic-other-events",open:otherOpen,onToggle:event3=>setOtherOpen(event3.currentTarget.open)},h("summary",null,"\u5F85\u5F52\u7C7B\u4E8B\u4EF6 \xB7 "+remaining),h(TopicEventList,{namespace,revision,topicId:topic.id,sectionKey:"uncovered",total:remaining,active:active&&open&&otherOpen,openEvent,onDirectoryChanged})):null})())))}function TopicRetryButton({failure,namespace,revision,onDirectoryChanged}){let scope=JSON.stringify([namespace,revision,failure.jobId]),[state,setState]=React.useState({scope,busy:!1,error:""}),current=state.scope===scope?state:{scope,busy:!1,error:""},request=React.useRef(null),scopeRef=React.useRef(scope);scopeRef.current!==scope&&(request.current?.abort(),request.current=null,scopeRef.current=scope),React.useEffect(()=>()=>{scopeRef.current===scope&&(request.current?.abort(),request.current=null)},[scope]);let retry=async()=>{if(request.current)return;let controller=new AbortController;request.current=controller,setState({scope,busy:!0,error:""});try{if(await api2("topics/retry",{namespace,jobId:failure.jobId,expectedRevision:revision},{method:"POST",signal:controller.signal}),request.current!==controller||controller.signal.aborted)return;await onDirectoryChanged?.()}catch(reason){if(request.current!==controller||controller.signal.aborted)return;reason?.status===409?await onDirectoryChanged?.():setState({scope,busy:!1,error:"\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{request.current===controller&&(request.current=null,setState(previous=>previous.scope===scope?{...previous,busy:!1}:previous))}};return h("div",{className:"sg-topic-retry"},h("button",{type:"button",className:"sg-topic-status-details",disabled:current.busy||!revision,onClick:retry},current.busy?"\u6B63\u5728\u63D0\u4EA4\u2026":"\u91CD\u65B0\u6574\u7406\u8FD9 "+Number(failure.eventCount||0)+" \u6761"),current.error?h("p",{role:"alert"},current.error):null)}function TopicBootstrapNotice({directory}){if(!directory)return null;let bootstrap=directory.bootstrap,working=bootstrap?.status==="pending"||bootstrap?.status==="running",total=bootstrap?.total,completed2=bootstrap?.completed,counted=Number.isSafeInteger(total)&&total>0&&Number.isSafeInteger(completed2)&&completed2>=0&&completed2<=total;return!working||bootstrap?.total===0?null:h("aside",{className:"sg-topic-bootstrap","aria-label":"\u5386\u53F2\u8BB0\u5FC6\u6574\u7406\u72B6\u6001"},h("p",{className:"sg-muted"},"\u5386\u53F2\u8BB0\u5FC6\u6574\u7406\u4E2D"+(counted?" \xB7 \u5DF2\u5904\u7406 "+completed2+" / "+total+" \u6761\u4E8B\u4EF6":"")))}let DREAMING_STYLES=".sg-dreaming{margin:0 0 20px;padding:14px 16px;border:1px solid var(--sg-border);border-radius:12px;background:var(--sg-surface)}.sg-dreaming-row{display:flex;align-items:center;gap:14px;flex-wrap:wrap}.sg-dreaming-animation{position:relative;width:48px;height:48px;flex:0 0 48px;color:var(--sg-accent)}.sg-dreaming-moon{display:block;font-size:43px;line-height:48px;animation:sg-dream-breathe 4s ease-in-out infinite}.sg-dreaming-star{position:absolute;right:0;top:1px;font-size:12px;animation:sg-dream-twinkle 3s ease-in-out infinite}.sg-dreaming-sleep{position:absolute;right:4px;bottom:1px;font-size:13px;animation:sg-dream-float 3s ease-in-out infinite}.sg-dreaming.resting .sg-dreaming-animation span{animation-play-state:paused}.sg-dreaming-copy{display:grid;gap:5px;flex:1;min-width:150px}.sg-dreaming-copy strong{font-size:14px;color:var(--sg-text)}.sg-dreaming-copy>span,.sg-dreaming p{font-size:12px;color:var(--sg-muted);line-height:1.6}.sg-dreaming-actions{display:flex;gap:8px;flex-wrap:wrap}.sg-dreaming button{padding:7px 12px;border:1px solid var(--sg-border);border-radius:7px;background:var(--sg-page);color:var(--sg-text);cursor:pointer}.sg-dreaming button:hover{border-color:var(--sg-accent)}.sg-dreaming button:disabled{opacity:.5;cursor:default}.sg-dreaming .sg-dreaming-stop{color:var(--sg-danger)}.sg-dreaming-progress{display:flex;align-items:center;gap:12px;margin-top:12px;color:var(--sg-muted);font-size:11px}.sg-dreaming-progress progress{width:100%;height:7px;accent-color:var(--sg-accent);flex:1;min-width:0}@keyframes sg-dream-breathe{50%{opacity:.6;transform:translateY(-2px)}}@keyframes sg-dream-twinkle{50%{opacity:.25;transform:scale(.7)}}@keyframes sg-dream-float{50%{opacity:.4;transform:translate(2px,-5px)}}@media(prefers-reduced-motion:reduce){.sg-dreaming-animation span{animation:none!important}}",DIRECTORY_PREVIEW_STYLES=".sg-topic-directory-intro{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;padding-bottom:14px}.sg-context-trigger{display:inline-flex;align-items:center;gap:7px;padding:5px 0;border:0;background:transparent;color:var(--sg-muted);font-size:12px;cursor:pointer}.sg-context-trigger:hover,.sg-context-trigger[aria-expanded=true]{color:var(--sg-accent)}.sg-dreaming-start{padding:6px 12px;border:0;border-radius:7px;background:var(--sg-soft);color:var(--sg-accent);font-size:12px;cursor:pointer}.sg-dreaming-start:disabled{opacity:.5;cursor:default}.sg-dreaming{flex:1 0 100%;margin:0;border:0;background:var(--sg-soft);padding:12px 14px}.sg-dreaming-animation{width:36px;height:40px;flex-basis:36px}.sg-dreaming-moon{font-size:34px;line-height:40px}.sg-dreaming-copy strong{font-size:13px}.sg-dreaming-copy>span{font-size:12px;color:var(--sg-muted)}.sg-dreaming-progress{margin-top:9px}.sg-dreaming-session{margin:5px 0 0 50px;padding:2px 0!important;border:0!important;background:transparent!important;color:var(--sg-accent)!important;font-size:12px!important}.sg-context-overlay{position:fixed;inset:0;z-index:2147483020;background:transparent}.sg-context-window{position:fixed;display:flex;flex-direction:column;width:min(520px,calc(100vw - 24px));padding:16px;border:1px solid var(--sg-border);border-radius:11px;background:var(--sg-page);color:var(--sg-text);box-shadow:0 12px 42px rgba(0,0,0,.25);overflow:auto}.sg-context-window-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.sg-context-window-head h3{font-size:14px;margin:0;font-weight:600}.sg-context-close{display:grid;place-items:center;width:29px;height:29px;padding:0;border:0;border-radius:5px;background:transparent;color:var(--sg-muted);cursor:pointer}.sg-context-subtitle{font-size:12px;color:var(--sg-muted);margin:3px 0 13px}.sg-context-injection{margin:0;padding:13px;background:var(--sg-soft);border-radius:7px;font:12px/1.8 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--sg-text)}@media(max-width:600px){.sg-context-overlay{background:rgba(0,0,0,.32)}.sg-context-window{left:12px!important;right:12px!important;top:auto!important;bottom:12px;width:auto;border-radius:13px;max-height:80vh!important}.sg-dreaming-actions{margin-left:50px}.sg-dreaming-copy{min-width:140px}}";function DirectoryContextPreview({context,active}){let[open,setOpen]=React.useState(!1),[position3,setPosition]=React.useState({left:12,top:12,maxHeight:"70vh"}),trigger=React.useRef(null),closeButton=React.useRef(null),close=()=>{setOpen(!1),trigger.current?.focus?.()};return React.useEffect(()=>{(!active||!context)&&setOpen(!1)},[active,context]),React.useEffect(()=>{if(!open||typeof window>"u")return;let place=()=>{let rect=trigger.current?.getBoundingClientRect?.(),width2=window.innerWidth||800,height2=window.innerHeight||700,top=Math.max(12,Math.min((rect?.bottom||80)+8,height2-220));setPosition({left:Math.max(12,Math.min(rect?.left||12,width2-Math.min(520,width2-24)-12)),top,maxHeight:Math.max(180,height2-top-20)})};place(),closeButton.current?.focus?.(),window.addEventListener("resize",place);let key=event3=>{event3.key==="Escape"&&close(),event3.key==="Tab"&&(event3.preventDefault(),closeButton.current?.focus?.())};return window.addEventListener("keydown",key),()=>{window.removeEventListener("resize",place),window.removeEventListener("keydown",key)}},[open]),h(React.Fragment,null,h("button",{type:"button",ref:trigger,className:"sg-context-trigger","aria-haspopup":"dialog","aria-expanded":open,disabled:!context,onClick:()=>setOpen(value=>!value)},"AI \u4F1A\u770B\u5230\u7684\u76EE\u5F55",h("span",{"aria-hidden":"true"},"\u2197")),open?h("div",{className:"sg-context-overlay",onClick:close},h("section",{className:"sg-context-window",style:position3,role:"dialog","aria-modal":!0,"aria-label":"AI \u4F1A\u770B\u5230\u7684\u76EE\u5F55",onClick:event3=>event3.stopPropagation()},h("div",{className:"sg-context-window-head"},h("h3",null,"AI \u4F1A\u770B\u5230\u7684\u76EE\u5F55"),h("button",{type:"button",ref:closeButton,className:"sg-context-close","aria-label":"\u5173\u95ED\u76EE\u5F55\u9884\u89C8",onClick:close},"\xD7")),h("p",{className:"sg-context-subtitle"},"\u4EE5\u4E0B\u76EE\u5F55\u5185\u5BB9\u9ED8\u8BA4\u63D0\u4F9B\u7ED9 AI"),h("pre",{className:"sg-context-injection"},context))):null)}function DreamingPanel({namespace,initialRun,active,available,inline=!1,onDirectoryChanged,onOpenDreamingSession}){let[run,setRun]=React.useState(initialRun||null),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[confirmStop,setConfirmStop]=React.useState(!1),stopDialog=React.useRef(null),stopTrigger=React.useRef(null);React.useEffect(()=>{if(!confirmStop)return;let previous=stopTrigger.current;stopDialog.current?.querySelector("button")?.focus?.();let onKeyDown=event3=>{if(event3.key==="Escape"&&!busy&&(event3.preventDefault(),setConfirmStop(!1)),event3.key!=="Tab")return;let buttons=[...stopDialog.current?.querySelectorAll("button:not(:disabled)")||[]];if(!buttons.length)return;let first2=buttons[0],last2=buttons.at(-1);event3.shiftKey&&document.activeElement===first2?(event3.preventDefault(),last2.focus()):!event3.shiftKey&&document.activeElement===last2&&(event3.preventDefault(),first2.focus())};return document.addEventListener("keydown",onKeyDown),()=>{document.removeEventListener("keydown",onKeyDown),previous?.isConnected&&previous.focus?.()}},[confirmStop,busy]);let request=React.useRef(null),previousStatus=React.useRef(initialRun?.status),[toast,setToast]=React.useState("");React.useEffect(()=>{initialRun&&(!run||initialRun.updatedAt>run.updatedAt)&&(initialRun.status==="completed"&&previousStatus.current&&previousStatus.current!=="completed"&&(setToast("\u76EE\u5F55\u5DF2\u6574\u7406\u597D"),previousStatus.current="completed"),setRun(initialRun))},[initialRun]),React.useEffect(()=>{if(!toast)return;let timer=window.setTimeout(()=>setToast(""),3600);return()=>window.clearTimeout(timer)},[toast]);let accept=React.useCallback(value=>{let next2=value?.run||null;next2&&previousStatus.current!==next2.status&&["completed","paused","terminated"].includes(next2.status)&&onDirectoryChanged?.(),next2?.status==="completed"&&previousStatus.current!=="completed"&&setToast("\u76EE\u5F55\u5DF2\u6574\u7406\u597D"),previousStatus.current=next2?.status,setRun(next2),setError("")},[onDirectoryChanged]);React.useEffect(()=>{if(!active||!run||!["running","pausing"].includes(run.status))return;let controller=new AbortController,timer,poll=()=>api2("dreaming",{namespace},{signal:controller.signal}).then(accept).catch(()=>{controller.signal.aborted||setError("\u72B6\u6001\u8BFB\u53D6\u5931\u8D25\uFF0C\u53EF\u91CD\u65B0\u8BFB\u53D6\u3002")}).finally(()=>{controller.signal.aborted||(timer=window.setTimeout(poll,2e3))});return timer=window.setTimeout(poll,1500),()=>{controller.abort(),window.clearTimeout(timer)}},[active,namespace,run?.id,run?.status,accept]),React.useEffect(()=>()=>request.current?.abort(),[]);let control=async action=>{if(request.current)return;let controller=new AbortController;request.current=controller,setBusy(!0),setError("");try{let params={namespace,action};action!=="start"&&(params.id=run.id),accept(await api2("dreaming",params,{method:"POST",signal:controller.signal}))}catch(reason){controller.signal.aborted||setError(reason?.message||"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002")}finally{request.current===controller&&(request.current=null,setBusy(!1))}},running=run?.status==="running",pausing=run?.status==="pausing",paused=run?.status==="paused",outstanding=running||pausing||paused,openSession=async()=>{if(!busy){setBusy(!0),setError("");try{let response=await api2("dreaming",{namespace,action:"open-session",id:run.id},{method:"POST"});if(!response.sessionId||!onOpenDreamingSession)throw new Error("\u5F53\u524D\u5BBF\u4E3B\u65E0\u6CD5\u6253\u5F00 Dreaming \u4F1A\u8BDD");await onOpenDreamingSession(response.sessionId)}catch(reason){setError(reason?.message||"\u65E0\u6CD5\u6253\u5F00\u4F1A\u8BDD\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}finally{setBusy(!1)}}};return!!run&&["running","pausing","paused"].includes(run.status)?h("aside",{className:"sg-dreaming "+(running?"running":"resting")+(inline?" inline":""),"aria-label":"Dreaming \u76EE\u5F55\u6574\u7406","data-testid":"stratagate-dreaming"},h("style",null,DREAMING_STYLES+DIRECTORY_PREVIEW_STYLES),toast?h("p",{className:"sg-dreaming-toast",role:"status","aria-live":"polite"},toast):null,h("div",{className:"sg-dreaming-row"},h("div",{className:"sg-dreaming-animation","aria-hidden":"true"},h("span",{className:"sg-dreaming-moon"},"\u263E"),h("span",{className:"sg-dreaming-star"},"\u2726"),h("span",{className:"sg-dreaming-sleep"},"z")),h("div",{className:"sg-dreaming-copy",role:"status","aria-live":"polite"},h("strong",null,running?run.waitingForProjection?"Dreaming \u6B63\u5728\u51C6\u5907\u2026":"\u6B63\u5728\u505A\u68A6\u2026":pausing?"\u6B63\u5728\u6682\u505C\u2026":"Dreaming \u5DF2\u6682\u505C"),h("span",null,run?.activity||"\u6574\u7406\u76EE\u5F55\u3001\u603B\u89C8\u4E0E\u7ECF\u9A8C")),h("div",{className:"sg-dreaming-actions"},running||pausing?h("button",{type:"button",disabled:busy||pausing,onClick:()=>control("pause")},pausing?"\u6B63\u5728\u6682\u505C\u2026":"\u6682\u505C"):null,paused&&!run.replanRequired?h("button",{type:"button",disabled:busy,onClick:()=>control("resume")},"\u7EE7\u7EED"):null,outstanding?h("button",{type:"button",className:"sg-dreaming-stop",disabled:busy,onClick:event3=>{stopTrigger.current=event3.currentTarget,setConfirmStop(!0)}},"\u7EC8\u6B62"):null)),run?h("div",{className:"sg-dreaming-progress"},h("progress",{max:Math.max(1,run.total),value:run.completed,"aria-label":"Dreaming \u6574\u7406\u8FDB\u5EA6\uFF08\u6279\u6B21\uFF09"}),h("span",null,Math.round(100*run.completed/Math.max(1,run.total))+"% \xB7 "+run.completed+"/"+run.total+" \u6279\u6B21")):null,h("button",{type:"button",className:"sg-dreaming-session",disabled:busy||!run.sessionId,onClick:openSession},run.sessionId?"\u6253\u5F00 Dreaming \u4F1A\u8BDD \u2197":running||pausing?"\u4F1A\u8BDD\u51C6\u5907\u4E2D\u2026":"\u672C\u8F6E\u672A\u521B\u5EFA\u4F1A\u8BDD"),run?.reason?h("p",null,run.reason):null,error3?h("p",{className:"sg-dreaming-failure",role:"alert"},error3,h("button",{type:"button",className:"sg-dreaming-retry",disabled:busy,onClick:()=>api2("dreaming",{namespace}).then(accept).catch(()=>setError("\u72B6\u6001\u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))},"\u91CD\u8BD5")):null,confirmStop?h("div",{className:"sg-import-overlay",role:"presentation"},h("section",{ref:stopDialog,className:"sg-dlg",role:"alertdialog","aria-modal":"true","aria-labelledby":"sg-stop-title","aria-describedby":"sg-stop-copy"},h("h3",{id:"sg-stop-title"},"\u7EC8\u6B62\u8FD9\u6B21\u6574\u7406\uFF1F"),h("div",{className:"sg-steps","aria-hidden":"true"},Array.from({length:7},(_,index)=>h("i",{key:index,className:index<Math.min(7,Math.max(0,Math.round(run.completed/Math.max(1,run.total)*7)))?"":"todo"}))),h("div",{className:"sg-steps-l",id:"sg-stop-copy"},h("span",null,h("b",null,Math.min(7,Math.max(0,Math.round(run.completed/Math.max(1,run.total)*7)))+" \u7AE0"),"\u6574\u7406\u597D\u7684\u4F1A\u4FDD\u7559"),h("span",null,7-Math.min(7,Math.max(0,Math.round(run.completed/Math.max(1,run.total)*7)))+" \u7AE0\u4FDD\u6301\u539F\u6837")),h("div",{className:"sg-dlg-acts"},h("button",{type:"button",className:"sg-btn ghost",disabled:busy,onClick:()=>setConfirmStop(!1)},"\u7EE7\u7EED\u6574\u7406"),h("button",{type:"button",className:"sg-btn danger",disabled:busy,onClick:async()=>{await control("terminate"),setConfirmStop(!1)}},"\u7EC8\u6B62")))):null):h(React.Fragment,null,h("style",null,DREAMING_STYLES+DIRECTORY_PREVIEW_STYLES),toast?h("p",{className:"sg-dreaming-toast",role:"status","aria-live":"polite"},toast):null,h("button",{type:"button",className:"sg-dreaming-start"+(inline?" sg-dreaming-arrange":""),disabled:busy||!available,onClick:()=>control("start")},inline?"\u6574\u7406\u8FD9\u4E9B":"\u{1F319} Dreaming"),error3?h("p",{className:"sg-dreaming-failure",role:"alert"},error3,h("button",{type:"button",className:"sg-dreaming-retry",disabled:busy,onClick:()=>api2("dreaming",{namespace}).then(accept).catch(()=>setError("\u72B6\u6001\u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"))},"\u91CD\u8BD5")):null)}function TopicDirectory({directory,namespace,active=!0,openEvent,onDirectoryChanged,onOpenDreamingSession}){let[pendingOpen,setPendingOpen]=React.useState(!1),[invalidatedRevision,setInvalidatedRevision]=React.useState(null),[expandRequest,setExpandRequest]=React.useState(0),[selectedSection,setSelectedSection]=React.useState(""),[summaryBusy,setSummaryBusy]=React.useState(!1),[summaryError,setSummaryError]=React.useState(""),chaptersRef=React.useRef(null),revision=directory?.revision||"",blocked=invalidatedRevision===revision;React.useEffect(()=>{setInvalidatedRevision(null)},[directory]);let pageRevision=blocked?"":revision,invalidate=React.useCallback(()=>(setInvalidatedRevision(revision),onDirectoryChanged?.()),[revision,onDirectoryChanged]),topics=directory?.topics||[],pendingTotal=Number(directory?.pending?.total||0),unassignedTotal=pendingTotal,firstSection=topics.flatMap(topic=>topicSections(topic).map(part=>({topic,part})))[0],openSection=selectedSection,[dreamHidden,setDreamHidden]=React.useState(()=>dreamDismissed(directory?.dreaming?.id)),dreamRun=!dreamHidden&&directory?.dreaming&&["completed","terminated"].includes(directory.dreaming.status)?directory.dreaming:null,openDreamRun=async()=>{if(!(summaryBusy||!dreamRun?.sessionId||!onOpenDreamingSession)){setSummaryBusy(!0),setSummaryError("");try{let response=await api2("dreaming",{namespace,action:"open-session",id:dreamRun.id},{method:"POST"});if(!response.sessionId)throw new Error("\u5F53\u524D\u5BBF\u4E3B\u65E0\u6CD5\u6253\u5F00 Dreaming \u4F1A\u8BDD");await onOpenDreamingSession(response.sessionId)}catch(reason){setSummaryError(reason?.message||"\u65E0\u6CD5\u6253\u5F00\u4F1A\u8BDD\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}finally{setSummaryBusy(!1)}}},dreamSummary=()=>{if(!dreamRun?.updatedAt)return h("span",null,"\u76EE\u5F55\u4F1A\u968F\u6574\u7406\u66F4\u65B0");let changed=Math.max(0,Number(dreamRun.changedBatches||0)),sections=topics.reduce((sum,topic)=>sum+topicSections(topic).length,0),[,month,day]=eventDayKey(dreamRun.updatedAt).split("-"),stamp=month&&day?month+"/"+day:formatTime(dreamRun.updatedAt);return h("span",{className:"sg-toc-dream"},h("button",{type:"button",className:"sg-toc-dream-run",disabled:summaryBusy||!dreamRun.sessionId||!onOpenDreamingSession,onClick:openDreamRun,title:dreamRun.sessionId?"\u6253\u5F00\u5F53\u8F6E Dreaming \u4F1A\u8BDD":"\u672C\u8F6E\u6CA1\u6709\u521B\u5EFA\u4F1A\u8BDD"},"\u4E0A\u6B21\u6574\u7406 "+stamp+(changed?" \xB7 "+changed+" \u8282 \u2192 "+sections+" \u8282":"")+(dreamRun.status==="terminated"?" \xB7 \u5DF2\u7EC8\u6B62":"")),h("span",{className:"sg-toc-dream-merge","aria-hidden":"true"},Array.from({length:4},(_,index)=>h("i",{key:"f"+index})),h("span",null,"\u2192"),Array.from({length:2},(_,index)=>h("i",{key:"t"+index,className:"o"}))),dreamRun.status==="terminated"?h("span",{className:"sg-toc-dream-note"},"\u5DF2\u6574\u7406\u7684\u7AE0\u8282\u5DF2\u4FDD\u7559"):null,h("button",{type:"button",className:"sg-toc-dream-close","aria-label":"\u5173\u95ED\u8FD9\u6B21\u6574\u7406\u8BB0\u5F55",onClick:()=>{dismissDream(dreamRun.id),setDreamHidden(!0)}},"\xD7"),summaryError?h("span",{className:"sg-toc-dream-error",role:"alert"},summaryError,h("button",{type:"button",className:"sg-toc-dream-retry",onClick:openDreamRun,disabled:summaryBusy},"\u91CD\u8BD5")):null)};return h("section",{className:"sg-topic-directory","data-testid":"stratagate-topic-directory","aria-label":"\u4E3B\u9898\u76EE\u5F55"},blocked?h("p",{className:"sg-topic-read-error",role:"status"},"\u76EE\u5F55\u5DF2\u6709\u66F4\u65B0\uFF0C\u6B63\u5728\u91CD\u65B0\u8BFB\u53D6\u3002",h("button",{type:"button",onClick:onDirectoryChanged},"\u91CD\u65B0\u8BFB\u53D6\u76EE\u5F55")):null,h("div",{hidden:blocked},h(TopicBootstrapNotice,{directory}),directory?!topics.length&&!pendingTotal?h("div",{className:"sg-topic-empty"},h("h3",null,"\u8FD8\u6CA1\u6709\u957F\u671F\u8BB0\u5FC6"),h("p",null,"\u4EA7\u751F\u957F\u671F\u4E8B\u4EF6\u540E\uFF0C\u4E3B\u9898\u4F1A\u5728\u8FD9\u91CC\u9010\u6B65\u6574\u7406\u6210\u76EE\u5F55\u3002")):null:h("p",{className:"sg-topic-empty",role:"status"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4E3B\u9898\u76EE\u5F55\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u6253\u5F00\u3002"),topics.length||pendingTotal?h("div",{className:"sg-how"},h("i",{className:"sg-sw moss","aria-hidden":"true"}),"\u76EE\u5F55\u4E00\u76F4\u5E26\u7740",h("span",{"aria-hidden":"true"},"\u2192"),h("i",{className:"sg-sw lib","aria-hidden":"true"}),"\u9700\u8981\u65F6\u7FFB\u5230\u5177\u4F53\u4E8B\u4EF6"):null,h("div",{className:"sg-book"},h("div",{className:"sg-leaf"},h("h3",{className:"sg-toc-title"},"\u76EE\u5F55"),h("div",{className:"sg-toc-col"},"\u4E8B\u4EF6"),h("div",{ref:chaptersRef},topics.map((topic,index)=>h(TopicChapter,{key:topic.id,topic,number:index+1,namespace,revision:pageRevision,active:active&&!blocked,openEvent,onDirectoryChanged:invalidate,expandRequest,openSection,onSectionToggle:(key,part)=>setSelectedSection(key)}))),!selectedSection&&firstSection?h("div",{className:"sg-book-preview","aria-label":"\u9ED8\u8BA4\u6253\u5F00\u7684\u7AE0\u8282"},h("span",{className:"sg-leaf-k"},"1.1"),h("h3",null,firstSection.part.uiTitle),h("p",{className:"sg-leaf-sum"},(firstSection.part.paragraphs||[]).map(paragraph=>paragraph.text||"").filter(Boolean).join(`
1341
+ `)||"\u8FD9\u4E00\u8282\u6682\u65F6\u6CA1\u6709\u6982\u8981\u3002")),(part.paragraphs||[]).length?h("div",{className:"sg-topic-overview"},h("h4",{className:"sg-topic-overview-heading"},h("button",{type:"button",className:"sg-topic-overview-toggle","aria-expanded":overviewOpen,"aria-controls":regionId+"-overview",onClick:()=>setOverviewOpen(current=>!current)},h("span",{className:"sg-directory-number"},sectionNumber+".0"),h("span",null,"\u603B\u89C8"),h("span",{className:"sg-directory-chevron","aria-hidden":"true"},"\u203A"))),h(DirectoryFold,{open:overviewOpen,id:regionId+"-overview"},(part.paragraphs||[]).map((paragraph,paragraphIndex)=>h("p",{key:paragraphIndex,className:"sg-topic-overview-text","data-overview-paragraph-index":String(paragraphIndex)},paragraph.text||"\u6682\u65E0\u603B\u89C8")))):null,h(TopicEventList,{namespace,revision,topicId,sectionKey:part.uiKey,total:sourceCount,active:active&&open,openEvent,numberPrefix:sectionNumber,onDirectoryChanged}),h("div",{className:"sg-leaf-folio","aria-hidden":"true"},"\u2014 \u7B2C"+chapterOrdinal(chapter)+"\u7AE0 \xB7 "+sectionNumber+" \u2014"))))}function TopicChapter({topic,number:number3,namespace,revision,active,openEvent,onDirectoryChanged,expandRequest=0,openSection="",onSectionToggle}){let[open,setOpen]=React.useState(!0),[otherOpen,setOtherOpen]=React.useState(!1);React.useEffect(()=>{expandRequest>0&&setOpen(!0)},[expandRequest]);let regionId="sg-topic-chapter-"+encodeURIComponent(topic.id),chapterLabel="\u7B2C"+chapterOrdinal(number3)+"\u7AE0",chapterEvents=topicSections(topic).reduce((sum,part)=>sum+Number(part.sourceEventCount||0),0);return h("article",{className:"sg-topic-chapter","data-topic-id":topic.id},h("header",{className:"sg-topic-chapter-header"},h("span",{className:"sg-topic-chapter-number","aria-hidden":"true"},String(number3).padStart(2,"0")),h("div",{className:"sg-topic-chapter-copy"},h("h2",null,h("button",{type:"button",className:"sg-topic-chapter-toggle",title:topic.title,"data-count":String(chapterEvents),"aria-expanded":open,"aria-controls":regionId,"aria-label":chapterLabel+" "+topic.title,onClick:()=>setOpen(current=>!current)},h("span",{className:"sg-topic-chapter-label"},chapterLabel),h("span",{className:"sg-topic-chapter-title"},topic.title),h("span",{className:"sg-toc-lead","aria-hidden":"true"}),h("span",{className:"sg-toc-cnt",title:chapterEvents+" \u6761\u4E8B\u4EF6"},String(chapterEvents)),h("span",{className:"sg-directory-chevron","aria-hidden":"true"},"\u203A"))),topic.description?h("p",{className:"sg-topic-description"},topic.description):null)),h(DirectoryFold,{open,id:regionId},h("div",{className:"sg-topic-sections"},topicSections(topic).map((part,index)=>h(TopicSection,{key:part.uiKey,part,chapter:number3,index:index+1,topicId:topic.id,namespace,revision,open:openSection===part.uiKey,onToggle:key=>onSectionToggle?.(key,part),active:active&&open,openEvent,onDirectoryChanged})),(topic.sections||[]).length?null:h("p",{className:"sg-topic-no-overview"},"\u8FD9\u4E2A\u4E3B\u9898\u8FD8\u6CA1\u6709\u5C0F\u8282\u3002"),(()=>{let remaining=Number(topic.coverage?.unassignedEvents??topic.coverage?.omittedEvents??0);return remaining?h("details",{className:"sg-topic-other-events",open:otherOpen,onToggle:event3=>setOtherOpen(event3.currentTarget.open)},h("summary",null,"\u5F85\u5F52\u7C7B\u4E8B\u4EF6 \xB7 "+remaining),h(TopicEventList,{namespace,revision,topicId:topic.id,sectionKey:"uncovered",total:remaining,active:active&&open&&otherOpen,openEvent,onDirectoryChanged})):null})())))}function TopicRetryButton({failure,namespace,revision,onDirectoryChanged}){let scope=JSON.stringify([namespace,revision,failure.jobId]),[state,setState]=React.useState({scope,busy:!1,error:""}),current=state.scope===scope?state:{scope,busy:!1,error:""},request=React.useRef(null),scopeRef=React.useRef(scope);scopeRef.current!==scope&&(request.current?.abort(),request.current=null,scopeRef.current=scope),React.useEffect(()=>()=>{scopeRef.current===scope&&(request.current?.abort(),request.current=null)},[scope]);let retry=async()=>{if(request.current)return;let controller=new AbortController;request.current=controller,setState({scope,busy:!0,error:""});try{if(await api2("topics/retry",{namespace,jobId:failure.jobId,expectedRevision:revision},{method:"POST",signal:controller.signal}),request.current!==controller||controller.signal.aborted)return;await onDirectoryChanged?.()}catch(reason){if(request.current!==controller||controller.signal.aborted)return;reason?.status===409?await onDirectoryChanged?.():setState({scope,busy:!1,error:"\u63D0\u4EA4\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{request.current===controller&&(request.current=null,setState(previous=>previous.scope===scope?{...previous,busy:!1}:previous))}};return h("div",{className:"sg-topic-retry"},h("button",{type:"button",className:"sg-topic-status-details",disabled:current.busy||!revision,onClick:retry},current.busy?"\u6B63\u5728\u63D0\u4EA4\u2026":"\u91CD\u65B0\u6574\u7406\u8FD9 "+Number(failure.eventCount||0)+" \u6761"),current.error?h("p",{role:"alert"},current.error):null)}function TopicBootstrapNotice({directory}){if(!directory)return null;let bootstrap=directory.bootstrap,working=bootstrap?.status==="pending"||bootstrap?.status==="running",total=bootstrap?.total,completed2=bootstrap?.completed,counted=Number.isSafeInteger(total)&&total>0&&Number.isSafeInteger(completed2)&&completed2>=0&&completed2<=total;return!working||bootstrap?.total===0?null:h("aside",{className:"sg-topic-bootstrap","aria-label":"\u5386\u53F2\u8BB0\u5FC6\u6574\u7406\u72B6\u6001"},h("p",{className:"sg-muted"},"\u5386\u53F2\u8BB0\u5FC6\u6574\u7406\u4E2D"+(counted?" \xB7 \u5DF2\u5904\u7406 "+completed2+" / "+total+" \u6761\u4E8B\u4EF6":"")))}let DREAMING_STYLES=".sg-dreaming{margin:0 0 20px;padding:14px 16px;border:1px solid var(--sg-border);border-radius:12px;background:var(--sg-surface)}.sg-dreaming-row{display:flex;align-items:center;gap:14px;flex-wrap:wrap}.sg-dreaming-animation{position:relative;width:48px;height:48px;flex:0 0 48px;color:var(--sg-accent)}.sg-dreaming-moon{display:block;font-size:43px;line-height:48px;animation:sg-dream-breathe 4s ease-in-out infinite}.sg-dreaming-star{position:absolute;right:0;top:1px;font-size:12px;animation:sg-dream-twinkle 3s ease-in-out infinite}.sg-dreaming-sleep{position:absolute;right:4px;bottom:1px;font-size:13px;animation:sg-dream-float 3s ease-in-out infinite}.sg-dreaming.resting .sg-dreaming-animation span{animation-play-state:paused}.sg-dreaming-copy{display:grid;gap:5px;flex:1;min-width:150px}.sg-dreaming-copy strong{font-size:14px;color:var(--sg-text)}.sg-dreaming-copy>span,.sg-dreaming p{font-size:12px;color:var(--sg-muted);line-height:1.6}.sg-dreaming-actions{display:flex;gap:8px;flex-wrap:wrap}.sg-dreaming button{padding:7px 12px;border:1px solid var(--sg-border);border-radius:7px;background:var(--sg-page);color:var(--sg-text);cursor:pointer}.sg-dreaming button:hover{border-color:var(--sg-accent)}.sg-dreaming button:disabled{opacity:.5;cursor:default}.sg-dreaming .sg-dreaming-stop{color:var(--sg-danger)}.sg-dreaming-progress{display:flex;align-items:center;gap:12px;margin-top:12px;color:var(--sg-muted);font-size:11px}.sg-dreaming-progress progress{width:100%;height:7px;accent-color:var(--sg-accent);flex:1;min-width:0}@keyframes sg-dream-breathe{50%{opacity:.6;transform:translateY(-2px)}}@keyframes sg-dream-twinkle{50%{opacity:.25;transform:scale(.7)}}@keyframes sg-dream-float{50%{opacity:.4;transform:translate(2px,-5px)}}@media(prefers-reduced-motion:reduce){.sg-dreaming-animation span{animation:none!important}}",DIRECTORY_PREVIEW_STYLES=".sg-topic-directory-intro{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;padding-bottom:14px}.sg-context-trigger{display:inline-flex;align-items:center;gap:7px;padding:5px 0;border:0;background:transparent;color:var(--sg-muted);font-size:12px;cursor:pointer}.sg-context-trigger:hover,.sg-context-trigger[aria-expanded=true]{color:var(--sg-accent)}.sg-dreaming-start{padding:6px 12px;border:0;border-radius:7px;background:var(--sg-soft);color:var(--sg-accent);font-size:12px;cursor:pointer}.sg-dreaming-start:disabled{opacity:.5;cursor:default}.sg-dreaming{flex:1 0 100%;margin:0;border:0;background:var(--sg-soft);padding:12px 14px}.sg-dreaming-animation{width:36px;height:40px;flex-basis:36px}.sg-dreaming-moon{font-size:34px;line-height:40px}.sg-dreaming-copy strong{font-size:13px}.sg-dreaming-copy>span{font-size:12px;color:var(--sg-muted)}.sg-dreaming-progress{margin-top:9px}.sg-dreaming-session{margin:5px 0 0 50px;padding:2px 0!important;border:0!important;background:transparent!important;color:var(--sg-accent)!important;font-size:12px!important}.sg-context-overlay{position:fixed;inset:0;z-index:2147483020;background:transparent}.sg-context-window{position:fixed;display:flex;flex-direction:column;width:min(520px,calc(100vw - 24px));padding:16px;border:1px solid var(--sg-border);border-radius:11px;background:var(--sg-page);color:var(--sg-text);box-shadow:0 12px 42px rgba(0,0,0,.25);overflow:auto}.sg-context-window-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.sg-context-window-head h3{font-size:14px;margin:0;font-weight:600}.sg-context-close{display:grid;place-items:center;width:29px;height:29px;padding:0;border:0;border-radius:5px;background:transparent;color:var(--sg-muted);cursor:pointer}.sg-context-subtitle{font-size:12px;color:var(--sg-muted);margin:3px 0 13px}.sg-context-injection{margin:0;padding:13px;background:var(--sg-soft);border-radius:7px;font:12px/1.8 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--sg-text)}@media(max-width:600px){.sg-context-overlay{background:rgba(0,0,0,.32)}.sg-context-window{left:12px!important;right:12px!important;top:auto!important;bottom:12px;width:auto;border-radius:13px;max-height:80vh!important}.sg-dreaming-actions{margin-left:50px}.sg-dreaming-copy{min-width:140px}}";function DirectoryContextPreview({context,active}){let[open,setOpen]=React.useState(!1),[position3,setPosition]=React.useState({left:12,top:12,maxHeight:"70vh"}),trigger=React.useRef(null),closeButton=React.useRef(null),close=()=>{setOpen(!1),trigger.current?.focus?.()};return React.useEffect(()=>{(!active||!context)&&setOpen(!1)},[active,context]),React.useEffect(()=>{if(!open||typeof window>"u")return;let place=()=>{let rect=trigger.current?.getBoundingClientRect?.(),width2=window.innerWidth||800,height2=window.innerHeight||700,top=Math.max(12,Math.min((rect?.bottom||80)+8,height2-220));setPosition({left:Math.max(12,Math.min(rect?.left||12,width2-Math.min(520,width2-24)-12)),top,maxHeight:Math.max(180,height2-top-20)})};place(),closeButton.current?.focus?.(),window.addEventListener("resize",place);let key=event3=>{event3.key==="Escape"&&close(),event3.key==="Tab"&&(event3.preventDefault(),closeButton.current?.focus?.())};return window.addEventListener("keydown",key),()=>{window.removeEventListener("resize",place),window.removeEventListener("keydown",key)}},[open]),h(React.Fragment,null,h("button",{type:"button",ref:trigger,className:"sg-context-trigger","aria-haspopup":"dialog","aria-expanded":open,disabled:!context,onClick:()=>setOpen(value=>!value)},"AI \u4F1A\u770B\u5230\u7684\u76EE\u5F55",h("span",{"aria-hidden":"true"},"\u2197")),open?h("div",{className:"sg-context-overlay",onClick:close},h("section",{className:"sg-context-window",style:position3,role:"dialog","aria-modal":!0,"aria-label":"AI \u4F1A\u770B\u5230\u7684\u76EE\u5F55",onClick:event3=>event3.stopPropagation()},h("div",{className:"sg-context-window-head"},h("h3",null,"AI \u4F1A\u770B\u5230\u7684\u76EE\u5F55"),h("button",{type:"button",ref:closeButton,className:"sg-context-close","aria-label":"\u5173\u95ED\u76EE\u5F55\u9884\u89C8",onClick:close},"\xD7")),h("p",{className:"sg-context-subtitle"},"\u4EE5\u4E0B\u76EE\u5F55\u5185\u5BB9\u9ED8\u8BA4\u63D0\u4F9B\u7ED9 AI"),h("pre",{className:"sg-context-injection"},context))):null)}function DreamingPanel({namespace,initialRun,active,available,inline=!1,settings=!1,onDirectoryChanged,onOpenDreamingSession}){let[run,setRun]=React.useState(initialRun||null),[statusReady,setStatusReady]=React.useState(!settings),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[confirmStop,setConfirmStop]=React.useState(!1),stopDialog=React.useRef(null),stopTrigger=React.useRef(null);React.useEffect(()=>{if(!confirmStop)return;let previous=stopTrigger.current;stopDialog.current?.querySelector("button")?.focus?.();let onKeyDown=event3=>{if(event3.key==="Escape"&&!busy&&(event3.preventDefault(),setConfirmStop(!1)),event3.key!=="Tab")return;let buttons=[...stopDialog.current?.querySelectorAll("button:not(:disabled)")||[]];if(!buttons.length)return;let first2=buttons[0],last2=buttons.at(-1);event3.shiftKey&&document.activeElement===first2?(event3.preventDefault(),last2.focus()):!event3.shiftKey&&document.activeElement===last2&&(event3.preventDefault(),first2.focus())};return document.addEventListener("keydown",onKeyDown),()=>{document.removeEventListener("keydown",onKeyDown),previous?.isConnected&&previous.focus?.()}},[confirmStop,busy]);let request=React.useRef(null),previousStatus=React.useRef(initialRun?.status),previousRunId=React.useRef(initialRun?.id),[toast,setToast]=React.useState("");React.useEffect(()=>{initialRun&&(!run||initialRun.updatedAt>run.updatedAt)&&(initialRun.status==="completed"&&previousStatus.current&&previousStatus.current!=="completed"&&(setToast(initialRun.scope==="memory"?"\u672C\u8F6E\u8BB0\u5FC6\u6574\u7406\u5B8C\u6210":"\u76EE\u5F55\u5DF2\u6574\u7406\u597D"),previousStatus.current="completed"),setRun(initialRun),previousRunId.current=initialRun.id)},[initialRun]),React.useEffect(()=>{if(!toast)return;let timer=window.setTimeout(()=>setToast(""),3600);return()=>window.clearTimeout(timer)},[toast]);let accept=React.useCallback((value,announce=!0)=>{let next2=value?.run||null,changed=previousRunId.current!==next2?.id||previousStatus.current!==next2?.status;next2&&changed&&(settings||["completed","paused","terminated"].includes(next2.status))&&onDirectoryChanged?.(),announce&&next2?.status==="completed"&&changed&&setToast(next2.scope==="memory"?"\u672C\u8F6E\u8BB0\u5FC6\u6574\u7406\u5B8C\u6210":"\u76EE\u5F55\u5DF2\u6574\u7406\u597D"),previousRunId.current=next2?.id,previousStatus.current=next2?.status,setRun(next2),setStatusReady(!0),setError("")},[settings,onDirectoryChanged]);React.useEffect(()=>{if(!active||!namespace||busy)return;let pollingDelay=["running","pausing"].includes(run?.status)?2e3:45e3,controller=new AbortController,timer,poll=()=>api2("dreaming",{namespace},{signal:controller.signal}).then(value=>{!controller.signal.aborted&&!request.current&&accept(value,statusReady)}).catch(()=>{controller.signal.aborted||setError("\u72B6\u6001\u8BFB\u53D6\u5931\u8D25\uFF0C\u53EF\u91CD\u65B0\u8BFB\u53D6\u3002")}).finally(()=>{controller.signal.aborted||(timer=window.setTimeout(poll,pollingDelay))});return timer=window.setTimeout(poll,statusReady?pollingDelay:0),()=>{controller.abort(),window.clearTimeout(timer)}},[active,namespace,busy,statusReady,run?.id,run?.status,accept]),React.useEffect(()=>()=>request.current?.abort(),[]);let control=async action=>{if(request.current)return;let controller=new AbortController;request.current=controller,setBusy(action),setError("");try{let signal=controller.signal;if(action==="refresh")accept(await api2("dreaming",{namespace},{signal}),statusReady);else{let params={namespace,action};action!=="start"&&(params.id=run.id),accept(await api2("dreaming",params,{method:"POST",signal}))}}catch(reason){controller.signal.aborted||setError(action==="refresh"?"\u72B6\u6001\u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":reason?.message||"\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002")}finally{request.current===controller&&(request.current=null,setBusy(!1))}},running=run?.status==="running",pausing=run?.status==="pausing",paused=run?.status==="paused",outstanding=running||pausing||paused,openSession=async()=>{if(!busy){setBusy(!0),setError("");try{let response=await api2("dreaming",{namespace,action:"open-session",id:run.id},{method:"POST"});if(!response.sessionId||!onOpenDreamingSession)throw new Error("\u5F53\u524D\u5BBF\u4E3B\u65E0\u6CD5\u6253\u5F00 Dreaming \u4F1A\u8BDD");await onOpenDreamingSession(response.sessionId)}catch(reason){setError(reason?.message||"\u65E0\u6CD5\u6253\u5F00\u4F1A\u8BDD\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}finally{setBusy(!1)}}},showCard=!!run&&["running","pausing","paused"].includes(run.status),renderSettings=(content,action=null)=>h("section",{className:"sg-settings-panel sg-dreaming-setting","aria-label":"Dreaming \u8BB0\u5FC6\u6574\u7406"},h("div",{className:"sg-dreaming-setting-head"},h("span",{className:"sg-dreaming-setting-icon","aria-hidden":"true"},"\u263E"),h("h3",{className:"sg-dreaming-setting-title"},"Dreaming \u8BB0\u5FC6\u6574\u7406"),action),content),feedback=error3?h("p",{className:"sg-dreaming-failure",role:"alert"},error3,h("button",{type:"button",className:"sg-dreaming-retry",disabled:!!busy,onClick:()=>control("refresh")},settings?"\u5237\u65B0\u72B6\u6001":"\u91CD\u8BD5")):null,toastMessage=toast?h("p",{className:"sg-dreaming-toast",role:"status","aria-live":"polite"},toast):null,styles=h("style",null,DREAMING_STYLES+DIRECTORY_PREVIEW_STYLES);if(settings&&!showCard)return renderSettings(h(React.Fragment,null,styles,toastMessage,feedback),h("button",{type:"button",className:"sg-save-button sg-dreaming-setting-start",disabled:!!busy||!available||!statusReady,onClick:()=>control("start")},busy==="start"?"\u6B63\u5728\u542F\u52A8\u2026":"\u7ACB\u5373\u6574\u7406",h("span",{"aria-hidden":"true"},"\u2192")));if(!showCard)return h(React.Fragment,null,styles,toastMessage,h("button",{type:"button",className:"sg-dreaming-start"+(inline?" sg-dreaming-arrange":""),disabled:busy||!available,onClick:()=>control("start")},inline?"\u6574\u7406\u8BB0\u5FC6":"\u{1F319} Dreaming"),feedback);let progressCard=h("aside",{className:"sg-dreaming "+(running?"running":"resting")+(inline?" inline":""),"aria-label":"Dreaming \u8BB0\u5FC6\u6574\u7406","data-testid":"stratagate-dreaming"},styles,toastMessage,h("div",{className:"sg-dreaming-row"},settings?null:h("div",{className:"sg-dreaming-animation","aria-hidden":"true"},h("span",{className:"sg-dreaming-moon"},"\u263E"),h("span",{className:"sg-dreaming-star"},"\u2726"),h("span",{className:"sg-dreaming-sleep"},"z")),h("div",{className:"sg-dreaming-copy",role:"status","aria-live":"polite"},h("strong",null,running?run.waitingForProjection?"Dreaming \u6B63\u5728\u51C6\u5907\u2026":settings?"\u6B63\u5728\u6574\u7406\u8BB0\u5FC6\u2026":"\u6B63\u5728\u505A\u68A6\u2026":pausing?"\u6B63\u5728\u6682\u505C\u2026":"Dreaming \u5DF2\u6682\u505C"),settings&&!run.activity?null:h("span",null,run.activity||"\u6B63\u5728\u6574\u7406\u8BB0\u5FC6")),h("div",{className:"sg-dreaming-actions"},running||pausing?h("button",{type:"button",disabled:busy||pausing,onClick:()=>control("pause")},pausing?"\u6B63\u5728\u6682\u505C\u2026":"\u6682\u505C"):null,paused&&!run.replanRequired?h("button",{type:"button",disabled:busy,onClick:()=>control("resume")},"\u7EE7\u7EED"):null,outstanding?h("button",{type:"button",className:"sg-dreaming-stop",disabled:busy,onClick:event3=>{stopTrigger.current=event3.currentTarget,setConfirmStop(!0)}},"\u7EC8\u6B62"):null)),run?h("div",{className:"sg-dreaming-progress"},h("progress",{max:Math.max(1,run.total),value:run.completed,"aria-label":"Dreaming \u6574\u7406\u8FDB\u5EA6\uFF08\u6279\u6B21\uFF09"}),h("span",null,Math.round(100*run.completed/Math.max(1,run.total))+"% \xB7 "+run.completed+"/"+run.total+" \u6279\u6B21")):null,h("button",{type:"button",className:"sg-dreaming-session",disabled:busy||!run.sessionId,onClick:openSession},run.sessionId?"\u6253\u5F00 Dreaming \u4F1A\u8BDD \u2197":running||pausing?"\u4F1A\u8BDD\u51C6\u5907\u4E2D\u2026":"\u672C\u8F6E\u672A\u521B\u5EFA\u4F1A\u8BDD"),run?.reason?h("p",null,run.reason):null,feedback,confirmStop?h("div",{className:"sg-import-overlay",role:"presentation"},h("section",{ref:stopDialog,className:"sg-dlg",role:"alertdialog","aria-modal":"true","aria-labelledby":"sg-stop-title","aria-describedby":"sg-stop-copy"},h("h3",{id:"sg-stop-title"},"\u7EC8\u6B62\u8FD9\u6B21\u6574\u7406\uFF1F"),h("div",{className:"sg-steps","aria-hidden":"true"},Array.from({length:7},(_,index)=>h("i",{key:index,className:index<Math.min(7,Math.max(0,Math.round(run.completed/Math.max(1,run.total)*7)))?"":"todo"}))),h("div",{className:"sg-steps-l",id:"sg-stop-copy"},h("span",null,"\u5DF2\u4FDD\u5B58\u7684\u4FEE\u6539\u4F1A\u4FDD\u7559\u3002"),h("span",null,"\u5DF2\u5B8C\u6210 "+run.completed+"/"+run.total+" \u6279\u3002")),h("div",{className:"sg-dlg-acts"},h("button",{type:"button",className:"sg-btn ghost",disabled:busy,onClick:()=>setConfirmStop(!1)},"\u7EE7\u7EED\u6574\u7406"),h("button",{type:"button",className:"sg-btn danger",disabled:busy,onClick:async()=>{await control("terminate"),setConfirmStop(!1)}},"\u7EC8\u6B62")))):null);return settings?renderSettings(progressCard):progressCard}function TopicDirectory({directory,namespace,active=!0,openEvent,onDirectoryChanged,onOpenDreamingSession}){let[pendingOpen,setPendingOpen]=React.useState(!1),[invalidatedRevision,setInvalidatedRevision]=React.useState(null),[expandRequest,setExpandRequest]=React.useState(0),[selectedSection,setSelectedSection]=React.useState(""),[summaryBusy,setSummaryBusy]=React.useState(!1),[summaryError,setSummaryError]=React.useState(""),chaptersRef=React.useRef(null),revision=directory?.revision||"",blocked=invalidatedRevision===revision;React.useEffect(()=>{setInvalidatedRevision(null)},[directory]);let pageRevision=blocked?"":revision,invalidate=React.useCallback(()=>(setInvalidatedRevision(revision),onDirectoryChanged?.()),[revision,onDirectoryChanged]),topics=directory?.topics||[],pendingTotal=Number(directory?.pending?.total||0),unassignedTotal=pendingTotal,firstSection=topics.flatMap(topic=>topicSections(topic).map(part=>({topic,part})))[0],openSection=selectedSection,[dreamHidden,setDreamHidden]=React.useState(()=>dreamDismissed(directory?.dreaming?.id)),dreamRun=!dreamHidden&&directory?.dreaming&&["completed","terminated"].includes(directory.dreaming.status)?directory.dreaming:null,openDreamRun=async()=>{if(!(summaryBusy||!dreamRun?.sessionId||!onOpenDreamingSession)){setSummaryBusy(!0),setSummaryError("");try{let response=await api2("dreaming",{namespace,action:"open-session",id:dreamRun.id},{method:"POST"});if(!response.sessionId)throw new Error("\u5F53\u524D\u5BBF\u4E3B\u65E0\u6CD5\u6253\u5F00 Dreaming \u4F1A\u8BDD");await onOpenDreamingSession(response.sessionId)}catch(reason){setSummaryError(reason?.message||"\u65E0\u6CD5\u6253\u5F00\u4F1A\u8BDD\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}finally{setSummaryBusy(!1)}}},dreamSummary=()=>{if(!dreamRun?.updatedAt)return h("span",null,"\u76EE\u5F55\u4F1A\u968F\u6574\u7406\u66F4\u65B0");let changed=Math.max(0,Number(dreamRun.changedBatches||0)),sections=topics.reduce((sum,topic)=>sum+topicSections(topic).length,0),[,month,day]=eventDayKey(dreamRun.updatedAt).split("-"),stamp=month&&day?month+"/"+day:formatTime(dreamRun.updatedAt);return h("span",{className:"sg-toc-dream"},h("button",{type:"button",className:"sg-toc-dream-run",disabled:summaryBusy||!dreamRun.sessionId||!onOpenDreamingSession,onClick:openDreamRun,title:dreamRun.sessionId?"\u6253\u5F00\u5F53\u8F6E Dreaming \u4F1A\u8BDD":"\u672C\u8F6E\u6CA1\u6709\u521B\u5EFA\u4F1A\u8BDD"},"\u4E0A\u6B21\u6574\u7406 "+stamp+(changed?dreamRun.scope==="memory"?" \xB7 \u4FDD\u5B58 "+changed+" \u6B21\u4FEE\u6539":" \xB7 "+changed+" \u8282 \u2192 "+sections+" \u8282":"")+(dreamRun.status==="terminated"?" \xB7 \u5DF2\u7EC8\u6B62":"")),h("span",{className:"sg-toc-dream-merge","aria-hidden":"true"},Array.from({length:4},(_,index)=>h("i",{key:"f"+index})),h("span",null,"\u2192"),Array.from({length:2},(_,index)=>h("i",{key:"t"+index,className:"o"}))),dreamRun.status==="terminated"?h("span",{className:"sg-toc-dream-note"},dreamRun.scope==="memory"?"\u5DF2\u4FDD\u5B58\u7684\u4FEE\u6539\u5DF2\u4FDD\u7559":"\u5DF2\u6574\u7406\u7684\u7AE0\u8282\u5DF2\u4FDD\u7559"):null,h("button",{type:"button",className:"sg-toc-dream-close","aria-label":"\u5173\u95ED\u8FD9\u6B21\u6574\u7406\u8BB0\u5F55",onClick:()=>{dismissDream(dreamRun.id),setDreamHidden(!0)}},"\xD7"),summaryError?h("span",{className:"sg-toc-dream-error",role:"alert"},summaryError,h("button",{type:"button",className:"sg-toc-dream-retry",onClick:openDreamRun,disabled:summaryBusy},"\u91CD\u8BD5")):null)};return h("section",{className:"sg-topic-directory","data-testid":"stratagate-topic-directory","aria-label":"\u4E3B\u9898\u76EE\u5F55"},blocked?h("p",{className:"sg-topic-read-error",role:"status"},"\u76EE\u5F55\u5DF2\u6709\u66F4\u65B0\uFF0C\u6B63\u5728\u91CD\u65B0\u8BFB\u53D6\u3002",h("button",{type:"button",onClick:onDirectoryChanged},"\u91CD\u65B0\u8BFB\u53D6\u76EE\u5F55")):null,h("div",{hidden:blocked},h(TopicBootstrapNotice,{directory}),directory?!topics.length&&!pendingTotal?h("div",{className:"sg-topic-empty"},h("h3",null,"\u8FD8\u6CA1\u6709\u957F\u671F\u8BB0\u5FC6"),h("p",null,"\u4EA7\u751F\u957F\u671F\u4E8B\u4EF6\u540E\uFF0C\u4E3B\u9898\u4F1A\u5728\u8FD9\u91CC\u9010\u6B65\u6574\u7406\u6210\u76EE\u5F55\u3002")):null:h("p",{className:"sg-topic-empty",role:"status"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4E3B\u9898\u76EE\u5F55\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u6253\u5F00\u3002"),topics.length||pendingTotal?h("div",{className:"sg-how"},h("i",{className:"sg-sw moss","aria-hidden":"true"}),"\u76EE\u5F55\u4E00\u76F4\u5E26\u7740",h("span",{"aria-hidden":"true"},"\u2192"),h("i",{className:"sg-sw lib","aria-hidden":"true"}),"\u9700\u8981\u65F6\u7FFB\u5230\u5177\u4F53\u4E8B\u4EF6"):null,h("div",{className:"sg-book"},h("div",{className:"sg-leaf"},h("h3",{className:"sg-toc-title"},"\u76EE\u5F55"),h("div",{className:"sg-toc-col"},"\u4E8B\u4EF6"),h("div",{ref:chaptersRef},topics.map((topic,index)=>h(TopicChapter,{key:topic.id,topic,number:index+1,namespace,revision:pageRevision,active:active&&!blocked,openEvent,onDirectoryChanged:invalidate,expandRequest,openSection,onSectionToggle:(key,part)=>setSelectedSection(key)}))),!selectedSection&&firstSection?h("div",{className:"sg-book-preview","aria-label":"\u9ED8\u8BA4\u6253\u5F00\u7684\u7AE0\u8282"},h("span",{className:"sg-leaf-k"},"1.1"),h("h3",null,firstSection.part.uiTitle),h("p",{className:"sg-leaf-sum"},(firstSection.part.paragraphs||[]).map(paragraph=>paragraph.text||"").filter(Boolean).join(`
1196
1342
 
1197
- `)||"\u70B9\u5DE6\u4FA7\u5C0F\u8282\uFF0C\u7FFB\u5F00\u5177\u4F53\u4E8B\u4EF6\u3002")):null,unassignedTotal?h("section",{className:"sg-topic-pending","aria-label":"\u5F85\u6574\u7406\u4E8B\u4EF6"},h("div",{className:"sg-topic-pending-heading"},h("button",{type:"button",className:"sg-topic-pending-toggle","aria-expanded":pendingOpen,"aria-controls":"sg-topic-pending-events",onClick:()=>setPendingOpen(value=>!value)},h("span",{className:"sg-topic-pending-label"},"\u5F85\u6574\u7406"),h("span",null,unassignedTotal+" \u6761"),h("span",{className:"sg-directory-chevron","aria-hidden":"true"},"\u203A")),h(DreamingPanel,{key:namespace,namespace,initialRun:directory?.dreaming,active,available:unassignedTotal>0&&!blocked,inline:!0,onDirectoryChanged,onOpenDreamingSession})),h(DirectoryFold,{open:pendingOpen,id:"sg-topic-pending-events"},h("p",null,"\u8FD9\u4E9B\u8BB0\u5FC6\u5C1A\u672A\u5F62\u6210\u7A33\u5B9A\u4E3B\u9898\uFF0C\u4ECD\u53EF\u76F4\u63A5\u67E5\u770B\u539F\u4E8B\u4EF6\u3002"),h(TopicEventList,{namespace,revision:pageRevision,topicId:"pending",total:pendingTotal,active:active&&!blocked&&pendingOpen,openEvent,onDirectoryChanged:invalidate,expandLabel:"\u67E5\u770B\u5168\u90E8\u5F85\u6574\u7406",collapseLabel:"\u6536\u8D77\u5F85\u6574\u7406\u4E8B\u4EF6"}))):null,h("div",{className:"sg-toc-foot sg-leaf-foot"},dreamSummary(),h(DirectoryContextPreview,{context:blocked?"":directory?.context,active}))))))}function LongTermPage({events,eventPage,graph,graphSettings={},project,query,setQuery,openEvent,namespace,focusNodeId,onFocusHandled,topicDirectory,onDirectoryChanged,onOpenDreamingSession,extractionGap=!1,active=!0,refresh}){let graphVisible=graphSettings.enabled===!0||graphSettings.noticeSeen!==!0,[mode,setMode]=React.useState("topics"),[selectedNodeId,setSelectedNodeId]=React.useState(""),[selectedEventId,setSelectedEventId]=React.useState(""),[graphNodeLimit,setGraphNodeLimit]=React.useState(100),[eventFilters,setEventFilters]=React.useState({time:"",node:"",type:"",status:""}),[nodeType,setNodeType]=React.useState(""),[nodeTag,setNodeTag]=React.useState(""),[filtersOpen,setFiltersOpen]=React.useState(!1),[fullScreen,setFullScreen]=React.useState(!1),[graphMenuOpen,setGraphMenuOpen]=React.useState(!1),graphMenuRef=React.useRef(null),debouncedQuery=useDebouncedValue(query),timelineParams=mode==="timeline"?{timeline:"true",...debouncedQuery.trim()?{q:debouncedQuery.trim()}:{},...eventFilters.time?{time:eventFilters.time}:{},...eventFilters.node?{participant:eventFilters.node}:{},...eventFilters.type?{eventType:eventFilters.type}:{},...eventFilters.status?{eventStatus:eventFilters.status}:{}}:{},pagedEvents=usePagedMemory({namespace,kind:"events",initialItems:events,initialPage:eventPage,fallbackLimit:40,extraParams:timelineParams,reloadOnParamsChange:mode==="timeline"}),timelineEvents=pagedEvents.items,nodes3=graph.nodes||[],edges3=graph.edges||[],clusters=graph.clusters||[],normalized=query.trim().toLocaleLowerCase(),nodeImportance=React.useMemo(()=>graphNodeImportance(nodes3,edges3,project),[nodes3,edges3,project]),nodeTags=[...new Set(nodes3.flatMap(node=>node.tags||[]))].sort((left,right)=>left.localeCompare(right));React.useEffect(()=>{if(!graphVisible||!focusNodeId||!nodes3.some(node=>node.id===focusNodeId))return;setMode("graph"),setNodeType(""),setNodeTag("");let rank=[...nodes3].sort((left,right)=>(nodeImportance.get(right.id)?.score||0)-(nodeImportance.get(left.id)?.score||0)).findIndex(node=>node.id===focusNodeId);rank>=0&&setGraphNodeLimit(current=>Math.max(current,rank+1)),setSelectedNodeId(focusNodeId),setFullScreen(!0),onFocusHandled?.()},[graphVisible,focusNodeId,nodes3,nodeImportance,onFocusHandled]),React.useEffect(()=>{if(!fullScreen||!active)return;let previous=document.body.style.overflow;document.body.style.overflow="hidden";let onKeyDown=event3=>{event3.key==="Escape"&&(document.querySelector('.sg-long-explorer .sg-info-trigger[aria-expanded="true"]')||(setFullScreen(!1),setFiltersOpen(!1)))};return window.addEventListener("keydown",onKeyDown),()=>{document.body.style.overflow=previous,window.removeEventListener("keydown",onKeyDown)}},[fullScreen,active]),React.useEffect(()=>{if(!graphMenuOpen)return;let onPointerDown=event3=>{graphMenuRef.current?.contains(event3.target)||setGraphMenuOpen(!1)},onKeyDown=event3=>{event3.key==="Escape"&&setGraphMenuOpen(!1)};return document.addEventListener("pointerdown",onPointerDown),document.addEventListener("keydown",onKeyDown),()=>{document.removeEventListener("pointerdown",onPointerDown),document.removeEventListener("keydown",onKeyDown)}},[graphMenuOpen]);let visibleNodes=nodes3.filter(node=>node.status!=="archived").filter(node=>!nodeType||node.type===nodeType).filter(node=>!nodeTag||(node.tags||[]).includes(nodeTag)).filter(node=>!normalized||JSON.stringify(node).toLocaleLowerCase().includes(normalized)),visibleGraphIds=new Set(visibleNodes.map(node=>node.id)),displayedGraphIds=new Set([...visibleNodes].sort((left,right)=>(nodeImportance.get(right.id)?.score||0)-(nodeImportance.get(left.id)?.score||0)).slice(0,graphNodeLimit).map(node=>node.id)),activeEdges=edges3.filter(edge=>edge.status==="active"&&visibleGraphIds.has(edge.fromNodeId)&&visibleGraphIds.has(edge.toNodeId)),displayedEdgeCount=activeEdges.filter(edge=>displayedGraphIds.has(edge.fromNodeId)&&displayedGraphIds.has(edge.toNodeId)).length,displayedNodeCount=Math.min(graphNodeLimit,visibleNodes.length),countText=(shown,total,unit)=>(shown===total?String(total):shown+" / "+total)+" "+unit,resultCount=mode==="graph"?countText(displayedNodeCount,visibleNodes.length,"\u4E2A\u8282\u70B9")+" \xB7 "+countText(displayedEdgeCount,activeEdges.length,"\u6761\u5173\u7CFB"):countText(timelineEvents.length,pagedEvents.page.total,"\u6761\u4E8B\u4EF6"),selectEvent=id2=>{setSelectedEventId(id2),setMode("timeline")},selectNode=id2=>{setSelectedNodeId(id2),setMode("graph")},openExplorer=()=>{mode==="graph"&&!selectedNodeId&&visibleNodes[0]&&setSelectedNodeId(visibleNodes[0].id),mode==="timeline"&&!selectedEventId&&timelineEvents[0]&&setSelectedEventId(timelineEvents[0].id),setFiltersOpen(!0),setFullScreen(!0)},migrationNotice=graphMigrationNotice(graph.migration),activeFilterCount=mode==="graph"?+!!nodeType+ +!!nodeTag:Object.values(eventFilters).filter(Boolean).length,filterControls=mode==="graph"?h("div",{className:"sg-filterbar"},h("select",{value:nodeType,onChange:event3=>setNodeType(event3.target.value),"aria-label":"\u8282\u70B9\u7C7B\u578B"},h("option",{value:""},"\u5168\u90E8\u8282\u70B9\u7C7B\u578B"),Object.entries(NODE_META).map(([value,meta3])=>h("option",{key:value,value},meta3[0]))),h("select",{value:nodeTag,onChange:event3=>setNodeTag(event3.target.value),"aria-label":"\u8BED\u4E49\u6807\u7B7E"},h("option",{value:""},"\u5168\u90E8\u8BED\u4E49\u6807\u7B7E"),nodeTags.map(tag=>h("option",{key:tag,value:tag},tag)))):h("div",{className:"sg-filterbar"},h("select",{value:eventFilters.time,onChange:event3=>setEventFilters({...eventFilters,time:event3.target.value}),"aria-label":"\u65F6\u95F4\u8303\u56F4"},h("option",{value:""},"\u5168\u90E8\u65F6\u95F4"),h("option",{value:"today"},"\u4ECA\u5929"),h("option",{value:"week"},"\u672C\u5468"),h("option",{value:"unknown"},"\u53D1\u751F\u65F6\u95F4\u672A\u77E5")),h("select",{value:eventFilters.node,onChange:event3=>setEventFilters({...eventFilters,node:event3.target.value}),"aria-label":"\u53C2\u4E0E\u5B9E\u4F53"},h("option",{value:""},"\u5168\u90E8\u5B9E\u4F53"),nodes3.map(node=>h("option",{key:node.id,value:node.id},node.name))),h("select",{value:eventFilters.type,onChange:event3=>setEventFilters({...eventFilters,type:event3.target.value}),"aria-label":"\u4E8B\u4EF6\u7C7B\u578B"},h("option",{value:""},"\u5168\u90E8\u7C7B\u578B"),Object.entries(EVENT_TYPE_TEXT).map(([value,label])=>h("option",{key:value,value},label))),h("select",{value:eventFilters.status,onChange:event3=>setEventFilters({...eventFilters,status:event3.target.value}),"aria-label":"\u4E8B\u4EF6\u72B6\u6001"},h("option",{value:""},"\u5168\u90E8\u72B6\u6001"),Object.entries(EVENT_STATUS_TEXT).map(([value,label])=>h("option",{key:value,value},label)))),longTabs=[["topics","\u76EE\u5F55"],...graphSettings.enabled===!0?[["graph","\u77E5\u8BC6\u56FE\u8C31"]]:[],["timeline","\u65F6\u95F4\u7EBF"]],tabButton=([id2,label])=>h("button",{key:id2,type:"button",className:mode===id2?"active":"","aria-current":mode===id2?"page":void 0,"aria-pressed":mode===id2,"aria-label":id2==="graph-add"?"\u91CD\u65B0\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31":label,onClick:()=>{setMode(id2==="graph-add"?"graph":id2),setGraphMenuOpen(id2==="graph-add"||id2==="graph"&&graphSettings.enabled!==!0&&graphSettings.noticeSeen!==!0),id2==="topics"&&(setFullScreen(!1),setFiltersOpen(!1))}},label),graphMenu=h("div",{ref:graphMenuRef,className:"sg-graph-menu"},h("button",{type:"button",className:"sg-graph-menu-trigger","aria-label":"\u77E5\u8BC6\u56FE\u8C31\u8BBE\u7F6E","aria-expanded":graphMenuOpen,onClick:()=>setGraphMenuOpen(value=>!value)},h("svg",{width:16,height:16,viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false"},h("path",{d:"M12 5v14M5 12h14",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"}))),graphMenuOpen?h("div",{className:"sg-graph-menu-popover"},h(GraphControlPanel,{state:graphSettings,refresh,page:!0,onOpenGraph:()=>{setGraphMenuOpen(!1),setMode("graph")},onGraphHidden:()=>{setGraphMenuOpen(!1),setMode("topics")}})):null),tabChildren=[...longTabs.map(tabButton),graphMenu];return h("section",{className:"sg-long-explorer "+(fullScreen?"fullscreen":""),"aria-label":fullScreen?"\u957F\u671F\u8BB0\u5FC6\u5168\u5C4F\u63A2\u7D22":"\u957F\u671F\u8BB0\u5FC6\u6D4F\u89C8"},h("div",{className:"sg-pg-head"},h("h2",null,"\u957F\u671F\u8BB0\u5FC6"),h("span",{className:"sg-pg-end"},h("nav",{className:"sg-long-tabs sg-seg","aria-label":"\u957F\u671F\u8BB0\u5FC6\u89C6\u89D2"},tabChildren))),h("div",{hidden:mode!=="topics"},h(TopicDirectory,{directory:topicDirectory,namespace,active:active&&mode==="topics",openEvent,onDirectoryChanged,onOpenDreamingSession})),mode==="topics"?null:h(React.Fragment,null,mode==="graph"&&migrationNotice?h("p",{className:"sg-muted"},migrationNotice):null,mode==="timeline"&&extractionGap?h("p",{className:"sg-muted"},"\u90E8\u5206\u5BF9\u8BDD\u5C1A\u672A\u5F62\u6210\u957F\u671F\u8BB0\u5FC6\uFF0C\u6682\u4E0D\u80FD\u901A\u8FC7\u957F\u671F\u8BB0\u5FC6\u68C0\u7D22\u3002"):null,h("div",{className:"sg-long-toolbar"},h(SearchBox,{value:query,onChange:setQuery,placeholder:mode==="graph"?"\u641C\u7D22\u4EBA\u7269\u3001\u9879\u76EE\u3001\u6982\u5FF5\u2026":"\u641C\u7D22\u4E8B\u4EF6\u2026"}),h("button",{type:"button",className:"sg-toolbar-button","aria-expanded":filtersOpen?"true":"false",onClick:()=>setFiltersOpen(!filtersOpen)},"\u7B5B\u9009 \u25BE",activeFilterCount?h("span",{className:"sg-active-filter-count"},activeFilterCount):null),mode==="graph"&&graphNodeLimit<visibleNodes.length?h("button",{type:"button",className:"sg-toolbar-button",onClick:()=>setGraphNodeLimit(current=>Math.min(visibleNodes.length,current+100))},"\u518D\u663E\u793A 100 \u4E2A"):null,h("button",{type:"button",className:"sg-toolbar-button",onClick:fullScreen?()=>{setFullScreen(!1),setFiltersOpen(!1)}:openExplorer},fullScreen?"\u9000\u51FA\u5168\u5C4F":"\u26F6 \u5168\u5C4F\u67E5\u770B"+(mode==="graph"?"\u56FE\u8C31":"\u65F6\u95F4\u7EBF"))),h("div",{className:"sg-toolbar-count"},resultCount),filtersOpen?filterControls:null,mode==="graph"?h("div",{className:"sg-long-layout "+(fullScreen?"":"sg-summary-layout"),"aria-disabled":!graphSettings.enabled,inert:graphSettings.enabled?void 0:"",style:graphSettings.enabled?void 0:{filter:"grayscale(1)",opacity:.4,pointerEvents:"none"}},h(GraphCanvas,{nodes:visibleNodes,edges:edges3,clusters,importance:nodeImportance,selectedId:selectedNodeId,onSelect:setSelectedNodeId,nodeLimit:graphNodeLimit,showSummary:!fullScreen,onViewDetails:openExplorer}),fullScreen?h(NodeDetailPanel,{node:nodes3.find(node=>node.id===selectedNodeId),nodes:nodes3,edges:edges3,events,onEvent:selectEvent}):null):h(React.Fragment,null,h("div",{className:"sg-long-layout "+(fullScreen?"sg-timeline-layout":"sg-summary-layout")},h(TimelineList,{events:timelineEvents,nodes:nodes3,onSelect:setSelectedEventId,selectedId:selectedEventId,floating:!fullScreen,onNode:selectNode,openSource:openEvent,dreaming:topicDirectory?.dreaming}),fullScreen?h(EventDetailPanel,{event:timelineEvents.find(event3=>event3.id===selectedEventId),nodes:nodes3,events:timelineEvents,onNode:selectNode,openSource:openEvent}):null),h(Pagination,{page:pagedEvents.page,loading:pagedEvents.loading,error:pagedEvents.error,onOffset:pagedEvents.loadOffset}))))}function previewText(value){let text=String(value||"").replace(/\s+/g," ").trim()||"\u6682\u65E0\u5185\u5BB9";return text.length>200?text.slice(0,200)+"\u2026":text}function turnRangeText(range){return!Array.isArray(range)||range.length<2||range[1]<range[0]?"\u7B49\u5F85\u65B0\u5BF9\u8BDD":"Turn "+range[0]+"\u2013"+range[1]}function LayerPreview({layer,currentLevel,expanding,busy,pendingSelection,allowExpand,onExpand}){let itemRef=React.useRef(null),hideTimer=React.useRef(null),popoverRef=React.useRef(null),level=Number(layer.level),actionable=allowExpand&&Number.isInteger(level)&&(level!==currentLevel||pendingSelection),cancelHide=()=>{hideTimer.current&&window.clearTimeout(hideTimer.current),hideTimer.current=null},removePopover=()=>{popoverRef.current?.remove(),popoverRef.current=null},showPopover=()=>{cancelHide();let rect=itemRef.current?.getBoundingClientRect();if(!rect)return;let inline=window.innerWidth<860,width2=Math.min(390,Math.max(240,window.innerWidth-24)),maxHeight=Math.min(520,window.innerHeight*.7),right=rect.right+12,left=right+width2<=window.innerWidth-12?right:Math.max(12,rect.left-width2-12),top=Math.min(Math.max(12,rect.top-8),Math.max(12,window.innerHeight-maxHeight-12));if(!popoverRef.current){let popover=document.createElement("aside"),title=document.createElement("strong"),content=document.createElement("p"),theme=window.getComputedStyle(itemRef.current),pageTheme=window.getComputedStyle(itemRef.current.closest(".sg-memory"));popover.className="sg-layer-popover",popover.setAttribute("role","tooltip"),popover.style.background=pageTheme.backgroundColor,popover.style.color=pageTheme.color,popover.style.borderColor=theme.borderColor,title.textContent="L"+level+" \u5B8C\u6574\u5185\u5BB9",content.className="sg-layer-full",content.textContent=String(layer.content||"\u6682\u65E0\u5185\u5BB9"),popover.append(title,content),popover.addEventListener("mouseenter",cancelHide),popover.addEventListener("mouseleave",scheduleHide),inline?itemRef.current.parentElement.appendChild(popover):document.body.appendChild(popover),popoverRef.current=popover}popoverRef.current.style.setProperty("position",inline?"relative":"fixed","important"),popoverRef.current.style.width=inline?"auto":width2+"px",popoverRef.current.style.left=inline?"0":left+"px",popoverRef.current.style.top=inline?"0":top+"px",popoverRef.current.style.maxHeight=inline?"240px":maxHeight+"px"},scheduleHide=()=>{cancelHide(),hideTimer.current=window.setTimeout(removePopover,140)};return React.useEffect(()=>()=>{cancelHide(),removePopover()},[]),h("div",{className:"sg-layer-hover"},h("div",{ref:itemRef,className:"sg-layer-item "+(level===currentLevel?"current":""),"data-level":String(level)},h("span",{className:"sg-layer-label"},"L"+level),h("span",{className:"sg-layer-preview",tabIndex:0,onMouseEnter:showPopover,onMouseLeave:scheduleHide,onFocus:showPopover,onBlur:scheduleHide},previewText(layer.content)),actionable?h("button",{className:"sg-layer-use",type:"button",disabled:busy,onMouseEnter:removePopover,onFocus:removePopover,onClick:event3=>{event3.stopPropagation(),onExpand(level)}},expanding?"\u6B63\u5728\u5E94\u7528\u2026":"\u8BA9\u52A9\u624B\u53C2\u8003 L"+level):h("span",{className:"sg-layer-using"},level===currentLevel?"\u52A9\u624B\u53EF\u89C1":"\u4EC5\u4F9B\u9884\u89C8")))}function BlockLayerPanel({block,detail,loading,expandingLevel,selectionBusy,onExpand}){if(loading)return h("div",{className:"sg-layer-panel"},h(Loading));let layers=Array.isArray(detail?.layers)?detail.layers:[],visibleLevel=visibleBlockLevel(block);return h("div",{className:"sg-layer-panel"},h("div",{className:"sg-layer-heading"},h("strong",null,"\u5206\u5C42\u5185\u5BB9\u9884\u89C8"),h("span",null,"\u52A9\u624B\u53EF\u89C1\uFF1A"+(visibleLevel===null?"\u5C1A\u672A\u786E\u8BA4":"L"+visibleLevel))),h("p",{className:"sg-layer-hint"},"\u9884\u89C8\u4E0D\u4F1A\u6539\u53D8\u52A9\u624B\u53EF\u89C1\u7684\u5185\u5BB9\u3002\u60AC\u505C\u6216\u805A\u7126\u53EF\u67E5\u770B\u5B8C\u6574\u5185\u5BB9\u3002"),block.virtual?h("div",{className:"sg-virtual-note"},"\u65E7\u4F1A\u8BDD\u5C55\u793A\u7247\u6BB5\u4E3A\u53EA\u8BFB\u5185\u5BB9\uFF0C\u4E0D\u4F1A\u6539\u5199\u539F\u59CB\u6570\u636E\u5E93\u3002"):null,layers.length?h("div",{className:"sg-layer-stack"},layers.slice().sort((a,b)=>a.level-b.level).map(layer=>h(LayerPreview,{key:layer.level,layer,currentLevel:visibleLevel,expanding:expandingLevel===layer.level,busy:selectionBusy||expandingLevel>=0,pendingSelection:block.surfaceSync?.status==="pending"||block.surfaceSync?.status==="blocked",allowExpand:!block.virtual,onExpand}))):h("div",{className:"sg-muted"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u8FD9\u6BB5\u5386\u53F2\u7684\u5206\u5C42\u5185\u5BB9\u3002"))}function visibleBlockLevel(block){return block.surfaceLevelKnown===!1||!Number.isInteger(block.currentLevel)?null:block.currentLevel}function BlockSelectionFeedback({block,feedback,onRefresh}){let value=feedback||block.surfaceSync;if(!value||value.status==="applied"&&!feedback)return null;let visible=visibleBlockLevel(block),current=visible===null?"\u52A9\u624B\u53EF\u89C1\u7684\u5C42\u7EA7\u5C1A\u672A\u786E\u8BA4\u3002":(value.uncertain?"\u4E0A\u6B21\u786E\u8BA4\u52A9\u624B\u53EF\u89C1 L":"\u52A9\u624B\u5F53\u524D\u53EF\u89C1 L")+visible+"\u3002",level=value.level??block.targetLevel,selected=Number.isInteger(level)?"L"+level:"\u6240\u9009\u5185\u5BB9",message=value.status==="applied"?value.message:(value.status==="pending"?"\u5DF2\u9009\u62E9 "+selected+"\u3002":"\u6682\u65F6\u65E0\u6CD5\u5E94\u7528 "+selected+"\u3002")+value.message+" "+current;return h("div",{className:"sg-selection-feedback"+(value.status==="blocked"?" error":""),role:value.status==="blocked"?"alert":"status"},message,value.uncertain&&onRefresh?h("button",{type:"button",className:"sg-quiet-button",onClick:onRefresh},"\u5237\u65B0\u72B6\u6001"):null)}function SummaryUnavailable({namespace,block}){let[source,setSource]=React.useState(null),[readError,setReadError]=React.useState(null),[loading,setLoading]=React.useState(!1),[open,setOpen]=React.useState(!1),request=React.useRef(null);React.useEffect(()=>()=>request.current?.abort(),[]);let openRaw=async()=>{if(request.current)return;if(source){setOpen(!0);return}let controller=new AbortController;request.current=controller,setLoading(!0),setReadError(null);try{let value=await api2("sources",{namespace,blockId:block.id},{signal:controller.signal});if(controller.signal.aborted)return;if(value.namespace!==namespace||!Array.isArray(value.messages)){setReadError({kind:"temporary",text:"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u8FD9\u6BB5\u5BF9\u8BDD\u7684\u539F\u6587\u3002"});return}if(!value.messages.some(message=>String(message.content||"").trim())){setReadError({kind:"unavailable",text:"\u5F53\u524D\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684\u539F\u6587\u3002"});return}setSource(value),setOpen(!0)}catch(reason){controller.signal.aborted||setReadError({kind:[401,403,404,410].includes(reason?.status)?"unavailable":"temporary",text:"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u8FD9\u6BB5\u5BF9\u8BDD\u7684\u539F\u6587\u3002"})}finally{request.current===controller&&(request.current=null,controller.signal.aborted||setLoading(!1))}},rawId="sg-summary-raw-"+block.id;return h("div",{className:"sg-block-expanded sg-muted"},h("p",null,"\u8FD9\u6BB5\u5BF9\u8BDD\u7684\u6458\u8981\u6682\u4E0D\u53EF\u7528\u3002"),(block.rawAvailable||source)&&readError?.kind!=="unavailable"?h("button",{type:"button",className:"sg-quiet-button",disabled:loading,"aria-expanded":open,"aria-controls":rawId,onClick:open?()=>setOpen(!1):openRaw},open?"\u6536\u8D77\u539F\u59CB\u5BF9\u8BDD":loading?"\u6B63\u5728\u8BFB\u53D6\u2026":readError?.kind==="temporary"?"\u91CD\u65B0\u8BFB\u53D6\u539F\u6587":"\u67E5\u770B\u539F\u59CB\u5BF9\u8BDD"):null,readError?h("p",{role:"status"},readError.text):null,open&&source?h("div",{id:rawId,className:"sg-summary-raw"},source.messages.map(message=>h("div",{key:message.id,className:"sg-raw-message"},h("div",{className:"sg-muted"},message.role+" \xB7 "+formatTime(message.createdAt)),h("div",{className:"sg-code"},String(message.content||""))))):null)}let DAILY_WEEK=["\u5468\u65E5","\u5468\u4E00","\u5468\u4E8C","\u5468\u4E09","\u5468\u56DB","\u5468\u4E94","\u5468\u516D"];function dailyParts(date){let[year,month,day]=date.split("-").map(Number);return{year,month,day,week:DAILY_WEEK[new Date(Date.UTC(year,month-1,day)).getUTCDay()]}}function dailyRelative(date,today){let days=Math.round((Date.parse(today+"T00:00:00Z")-Date.parse(date+"T00:00:00Z"))/864e5);return days===0?"\u4ECA\u5929":days===1?"\u6628\u5929":days>1?days+" \u5929\u524D":Math.abs(days)+" \u5929\u540E"}function DailyIcon({name}){let paths={calendar:["M8 2v4","M16 2v4","M3 10h18","M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2"],folder:["M6 14 7.5 11a2 2 0 0 1 1.8-1H20a2 2 0 0 1 1.9 2.6l-2.2 7A2 2 0 0 1 17.8 21H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v2"],left:["m15 18-6-6 6-6"],right:["m9 18 6-6-6-6"],refresh:["M3 12a9 9 0 0 1 15.4-6.4L21 8","M21 3v5h-5","M21 12a9 9 0 0 1-15.4 6.4L3 16","M8 16H3v5"],notebook:["M2 6h4","M2 10h4","M2 14h4","M2 18h4","M8 2v20","M6 2h13a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2"],alert:["M12 8v4","M12 16h.01"],pause:["M10 8v8","M14 8v8"]};return h("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},["alert","pause"].includes(name)?h("circle",{cx:12,cy:12,r:10}):null,(paths[name]||[]).map((d,key)=>h("path",{key,d})))}function dailyInline(text){return String(text).split(/(`[^`\n]+`)/g).map((part,key)=>/^`[^`\n]+`$/.test(part)?h("code",{key},part.slice(1,-1)):part)}function renderDailyMarkdown(markdown){let output2=[],children=[],title=null,list=[],flushList=()=>{list.length&&(children.push(h("ul",{key:"list-"+children.length},list)),list=[])},flushItem=()=>{flushList(),(children.length||title!==null)&&output2.push(h("article",{className:"sg-daily-item",key:output2.length},title!==null?h("h4",null,dailyInline(title)):null,children)),children=[],title=null};for(let raw of String(markdown).split(/\r?\n/)){let line=raw.trimEnd();if(/^# \d{4}-\d{2}-\d{2}$/.test(line))continue;if(line.startsWith("## ")){flushItem(),title=line.slice(3);continue}if(line.startsWith("- ")){list.push(h("li",{key:list.length},dailyInline(line.slice(2))));continue}if(flushList(),!line)continue;let status=line.match(/^(当前|已完成):\s*(.*)$/);children.push(status?h("p",{key:children.length,className:"sg-daily-status"+(status[1]==="\u5DF2\u5B8C\u6210"?" done":"")},h("b",null,status[1]),h("span",null,dailyInline(status[2]))):h("p",{key:children.length},dailyInline(line)))}return flushItem(),output2}function dailyNoteDigest(markdown){let items=[],current=null;for(let raw of String(markdown||"").split(/\r?\n/)){let line=raw.trim();if(!line||/^# \d{4}-\d{2}-\d{2}$/.test(line))continue;if(line.startsWith("## ")){current={title:line.slice(3),detail:"",time:""},items.push(current);continue}if(!current)continue;let clock=line.match(/\b([01]?\d|2[0-3]):([0-5]\d)\b/);clock&&!current.time&&(current.time=clock[1].padStart(2,"0")+":"+clock[2]),current.detail||(current.detail=line.replace(/^(当前|已完成):\s*/,"").replace(/^[-*]\s+/,""))}return items}function DailyNotesPage({namespace,setDailyInjectionDays}){let[index,setIndex]=React.useState(null),[indexLoading,setIndexLoading]=React.useState(!0),[indexError,setIndexError]=React.useState(""),[selected,setSelected]=React.useState(""),[note,setNote]=React.useState({loading:!1,date:"",markdown:"",error:""}),[revision,setRevision]=React.useState(0),[noteRevision,setNoteRevision]=React.useState(0),[dayDigests,setDayDigests]=React.useState({}),[daySaving,setDaySaving]=React.useState(!1),[dayError,setDayError]=React.useState(""),[daysOverride,setDaysOverride]=React.useState(null),[openDay,setOpenDay]=React.useState(!1);React.useEffect(()=>{let abort=new AbortController;return setIndexLoading(!0),setIndexError(""),setOpenDay(!1),namespace?(api2("daily",{namespace},{signal:abort.signal}).then(data4=>{abort.signal.aborted||(setDaysOverride(null),setIndex(data4),setSelected(current=>data4.dates.includes(current)?current:data4.injectedDates[0]||data4.dates[0]||""))}).catch(error3=>{abort.signal.aborted||setIndexError(String(error3.message||error3))}).finally(()=>{abort.signal.aborted||setIndexLoading(!1)}),()=>abort.abort()):(setIndex(null),setSelected(""),setIndexLoading(!1),()=>abort.abort())},[namespace,revision]),React.useEffect(()=>{let abort=new AbortController;return setNote({loading:!!selected,date:selected,markdown:"",error:""}),selected&&api2("daily/note",{namespace,date:selected},{signal:abort.signal}).then(data4=>{abort.signal.aborted||setNote({loading:!1,date:selected,markdown:data4.markdown,error:""})}).catch(error3=>{abort.signal.aborted||setNote({loading:!1,date:selected,markdown:"",error:String(error3.message||error3)})}),()=>abort.abort()},[namespace,selected,noteRevision]);let choose=date2=>{setSelected(date2),setOpenDay(!0)},dates=index?.dates||[],injected=index?.injectedDates||[],enabled=index?.enabled!==!1,savedInjectionDays=index?.injectionDays??3,injectionDays=daysOverride??savedInjectionDays,digests=dayDigests&&typeof dayDigests=="object"?dayDigests:{};React.useEffect(()=>{let active=!0,controller=new AbortController,wanted=dates.slice(0,14).filter(date2=>!(date2 in digests));return!wanted.length||indexError||!namespace?()=>controller.abort():(Promise.all(wanted.map(async date2=>{try{let value=await api2("daily/note",{namespace,date:date2},{signal:controller.signal});return[date2,dailyNoteDigest(value?.markdown)]}catch{return[date2,null]}})).then(entries=>{!active||controller.signal.aborted||setDayDigests(current=>{let next2={...current};for(let[date2,items]of entries)next2[date2]=items;return next2})}),()=>{active=!1,controller.abort()})},[namespace,indexError,dates.join(",")]);let stepDays=async delta=>{if(!setDailyInjectionDays||daySaving)return;let next2=Math.min(30,Math.max(1,injectionDays+delta));if(next2!==injectionDays){setDaysOverride(next2),setDaySaving(!0),setDayError("");try{await setDailyInjectionDays(next2)||(setDaysOverride(null),setDayError("\u5929\u6570\u672A\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002"))}catch(reason){setDaysOverride(null),setDayError("\u5929\u6570\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason?.message||reason))}finally{setDaySaving(!1)}}},failure=error3=>h("div",{className:"sg-daily-state error",role:"alert"},h("span",{className:"sg-daily-icon-wrap"},h(DailyIcon,{name:"alert"})),h("h3",null,"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u7B14\u8BB0"),h("p",null,"\u6587\u4EF6\u53EF\u80FD\u88AB\u5360\u7528\u6216\u6743\u9650\u4E0D\u8DB3\uFF0C\u5DF2\u6709\u7B14\u8BB0\u4E0D\u4F1A\u4E22\u5931\u3002"),h("button",{type:"button",className:"sg-daily-retry",onClick:()=>indexError?setRevision(v=>v+1):setNoteRevision(v=>v+1)},h(DailyIcon,{name:"refresh"}),"\u91CD\u65B0\u8BFB\u53D6"),h("details",null,h("summary",null,"\u9519\u8BEF\u8BE6\u60C5"),error3)),date=selected?dailyParts(selected):null,days=dates.slice(0,14),dayRows=()=>{let rows=[],cutShown=!1;return days.forEach((day,position3)=>{let parts=dailyParts(day),isInjected=enabled&&injected.includes(day),items=digests[day];enabled&&!cutShown&&!isInjected&&days.slice(0,position3).some(earlier=>injected.includes(earlier))&&(cutShown=!0,rows.push(h("div",{key:day+"-cut",className:"sg-day-cut"},h("span",null,"\u4EE5\u4E0B\u4E0D\u5E26\u5165"))));let lines=(Array.isArray(items)&&items.length?items:[{title:"\u67E5\u770B\u5F53\u5929\u7B14\u8BB0",detail:"",time:""}]).slice(0,6).map((item,key)=>h("li",{key},h("span",{className:"sg-day-t"},item.time||""),h("button",{type:"button",className:"sg-day-s",onClick:()=>choose(day),"aria-label":parts.month+"\u6708"+parts.day+"\u65E5 "+item.title+"\uFF0C\u67E5\u770B\u5F53\u5929\u7B14\u8BB0"},item.title),h("span")));rows.push(h("div",{key:day,className:"sg-day"+(isInjected?"":" out"),style:{animationDelay:position3*40+"ms"}},h("button",{type:"button",role:"tab",id:"sg-day-tab-"+day,"aria-controls":"sg-day-note","data-day":day,"aria-selected":selected===day,tabIndex:selected===day||!days.includes(selected)&&position3===0?0:-1,className:"sg-day-d",onClick:()=>choose(day),onKeyDown:event3=>{let next2=event3.key==="ArrowDown"?(position3+1)%days.length:event3.key==="ArrowUp"?(position3+days.length-1)%days.length:event3.key==="Home"?0:event3.key==="End"?days.length-1:-1;next2>=0&&(event3.preventDefault(),choose(days[next2]),event3.currentTarget.closest(".sg-days")?.querySelector('[data-day="'+days[next2]+'"]')?.focus())}},h("b",null,parts.day),h("span",null,parts.week),h("span",{className:"sg-visually-hidden"},parts.month+"\u6708 \xB7 "+dailyRelative(day,index.today))),h("div",{className:"sg-day-rail","aria-hidden":"true"}),h("ul",null,lines)))}),rows};return h("div",{className:"sg-daily"},h("div",{className:"sg-pg-head"},h("h2",null,"\u77ED\u671F\u8BB0\u5FC6"),h("span",{className:"sg-pg-tag"},h("i",{className:"sg-sw sand","aria-hidden":"true"}),enabled?"\u65B0\u4F1A\u8BDD\u5E26\u5165\u6700\u8FD1 "+injectionDays+" \u4E2A\u6709\u7B14\u8BB0\u65E5\u671F":"\u5DF2\u6682\u505C\u6CE8\u5165"),h("span",{className:"sg-pg-end"},setDailyInjectionDays?h("span",{className:"sg-stp",role:"group","aria-label":"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570"},h("button",{type:"button","aria-label":"\u51CF\u5C11\u4E00\u5929",disabled:daySaving||injectionDays<=1,onClick:()=>{stepDays(-1)}},"\u2212"),h("span",{"aria-live":"polite"},injectionDays+" \u5929"),h("button",{type:"button","aria-label":"\u589E\u52A0\u4E00\u5929",disabled:daySaving||injectionDays>=30,onClick:()=>{stepDays(1)}},"+")):null,null),dayError?h("p",{className:"sg-storage-feedback failed",role:"alert"},dayError):null,indexLoading?h(Loading):indexError?failure(indexError):h(React.Fragment,null,enabled?null:h("div",{className:"sg-daily-off"},h(DailyIcon,{name:"pause"}),"\u5DF2\u5173\u95ED\uFF0C\u4E0D\u518D\u5199\u5165\uFF0C\u4E5F\u4E0D\u4F1A\u5E26\u5165\u65B0\u4F1A\u8BDD\u3002"),dates.length?h(React.Fragment,null,h("div",{className:"sg-days",role:"tablist","aria-label":"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u7B14\u8BB0"},dayRows()),openDay?note.loading||note.date!==selected?h(Loading):note.error?failure(note.error):date?h("article",{key:selected,id:"sg-day-note",role:"tabpanel","aria-labelledby":"sg-day-tab-"+selected,className:"sg-daily-note"},h("div",{className:"sg-daily-note-date"},h("h3",null,date.month+" \u6708 "+date.day+" \u65E5"),h("span",null,date.week+" \xB7 "+dailyRelative(selected,index.today))),h("div",{className:"sg-daily-meta"},h("button",{type:"button",className:"sg-daily-back",onClick:()=>setOpenDay(!1)},"\u6536\u8D77\u7B14\u8BB0"),h("span",{className:"sg-daily-pill"+(!enabled||!injected.includes(selected)?" muted":"")},enabled?injected.includes(selected)?"\u4F1A\u5E26\u5165\u65B0\u4F1A\u8BDD":"\u4E0D\u5728\u5E26\u5165\u8303\u56F4\u5185":"\u5DF2\u6682\u505C\u6CE8\u5165"),!injected.includes(selected)&&enabled?h("button",{type:"button",className:"sg-daily-back",onClick:()=>choose(injected[0])},"\u56DE\u5230\u6700\u8FD1\u7B14\u8BB0"):null),renderDailyMarkdown(note.markdown)):null:null):h("div",{className:"sg-daily-state"},h("span",{className:"sg-daily-icon-wrap"},h(DailyIcon,{name:"notebook"})),h("h3",null,"\u8FD8\u6CA1\u6709\u7B14\u8BB0"),h("p",null,"Agent \u63A8\u8FDB\u5DE5\u4F5C\u65F6\u4F1A\u81EA\u52A8\u8BB0\u5F55\u3002")))))}function ShortTermPage({blocks,blockPage,openBlock,conversations,activeThreadId,namespace,onConversationChange,refresh,blockTurnSize=6}){let pagedBlocks=usePagedMemory({namespace,kind:"blocks",initialItems:blocks,initialPage:blockPage,fallbackLimit:40,extraParams:{threadId:activeThreadId}}),visible=[...pagedBlocks.items].sort((a,b)=>Number(a.sequence||0)-Number(b.sequence||0)||String(a.createdAt).localeCompare(String(b.createdAt))),[expandedId,setExpandedId]=React.useState(""),[detailBlockId,setDetailBlockId]=React.useState(""),[details,setDetails]=React.useState({}),[loadingId,setLoadingId]=React.useState(""),[expanding,setExpanding]=React.useState({blockId:"",level:-1}),[previewError,setPreviewError]=React.useState(null),[selectionFeedback,setSelectionFeedback]=React.useState({}),scope=namespace+"\0"+activeThreadId,activeScope=React.useRef(scope);activeScope.current=scope;let selectionRequest=React.useRef(null),currentOpen=openBlock||{turnRange:null,messages:0,status:"open"};React.useEffect(()=>{setExpandedId(""),setDetailBlockId(""),setDetails({}),setLoadingId(""),setPreviewError(null),setSelectionFeedback({})},[scope]),React.useEffect(()=>{let applied=Object.entries(selectionFeedback).filter(([,value])=>value?.status==="applied");if(!applied.length)return;let timer=window.setTimeout(()=>setSelectionFeedback(current=>{let next2={...current};for(let[id2,value]of applied)next2[id2]===value&&delete next2[id2];return next2}),4e3);return()=>window.clearTimeout(timer)},[selectionFeedback]);let toggleBlock=block=>{if(expandedId===block.id){setExpandedId("");return}setExpandedId(block.id),setPreviewError(null),!details[block.id]&&(setLoadingId(block.id),api2("sources",{namespace,blockId:block.id}).then(value=>{activeScope.current===scope&&setDetails(current=>({...current,[block.id]:value}))}).catch(()=>{activeScope.current===scope&&setPreviewError({scope,blockId:block.id,message:"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u9884\u89C8\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u6253\u5F00\u3002"})}).finally(()=>{activeScope.current===scope&&setLoadingId(current=>current===block.id?"":current)}))},expandTo=async(block,level)=>{if(selectionRequest.current?.scope===scope)return;let request={scope,blockId:block.id,level};selectionRequest.current=request;let isCurrent=()=>activeScope.current===scope&&selectionRequest.current===request;setSelectionFeedback(current=>({...current,[block.id]:null})),setExpanding(request);let result;try{result=await api2("blocks/expand",{namespace,blockId:block.id,level:"L"+level},{method:"PATCH"})}catch(reason){let rejected=reason?.code==="BLOCK_SELECTION_REJECTED"||[400,403,404,409].includes(reason?.status);isCurrent()&&setSelectionFeedback(current=>({...current,[block.id]:{scope,level,status:rejected?"blocked":"pending",uncertain:!rejected,message:rejected?/[\u4e00-\u9fff]/.test(reason?.message||"")?reason.message.replace("\uFF08blocks/expand\uFF09",""):"\u8FD9\u6B21\u9009\u62E9\u672A\u80FD\u5E94\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u5E94\u7528\u7ED3\u679C\uFF0C\u8BF7\u5237\u65B0\u540E\u67E5\u770B\u3002"}}))}if(isCurrent())try{await refresh(),isCurrent()&&pagedBlocks.page.offset>0&&await pagedBlocks.loadOffset(pagedBlocks.page.offset),result&&isCurrent()&&setSelectionFeedback(current=>({...current,[block.id]:result.surfaceSync?.status==="applied"?{scope,level,status:"applied",message:"\u5DF2\u5E94\u7528 L"+level+"\uFF0C\u4F9B\u52A9\u624B\u540E\u7EED\u56DE\u590D\u53C2\u8003\u3002"}:null}))}catch{isCurrent()&&setSelectionFeedback(current=>({...current,[block.id]:{scope,level,status:"pending",uncertain:!0,message:"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u5E94\u7528\u7ED3\u679C\uFF0C\u8BF7\u5237\u65B0\u540E\u67E5\u770B\u3002"}}))}selectionRequest.current===request&&(selectionRequest.current=null,setExpanding({blockId:"",level:-1}))},selectedBlock=visible.find(block=>block.id===expandedId)||visible[visible.length-1]||null,levelOf=block=>{let level=visibleBlockLevel(block);return level===null?0:Math.min(5,Math.max(0,level))},openCapacity=Math.max(1,Number(currentOpen.capacity||blockTurnSize||6)),openUsed=Math.min(openCapacity,Math.max(0,Number(currentOpen.turns||0))),remainingDots=Math.max(1,openCapacity-openUsed),firstTurn=visible.length?visible[0].turnRange?.[0]:null,lastTurn=visible.length?visible[visible.length-1].turnRange?.[1]:null,turnSpan=Number.isInteger(firstTurn)&&Number.isInteger(lastTurn)?" \xB7 \u7B2C "+firstTurn+"\u2013"+lastTurn+" \u8F6E":"",narrow=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 680px)").matches===!0:!1,detailBlock=narrow&&detailBlockId?visible.find(block=>block.id===detailBlockId):null;return detailBlock?h("div",{className:"sg-ss-detail-page"},h(BackBar,{label:"\u4F1A\u8BDD\u8BB0\u5FC6",onBack:()=>setDetailBlockId("")}),h(ShortTermMemoryBlockDetail,{key:namespace+":"+detailBlock.id,namespace,block:detailBlock})):h(React.Fragment,null,h("div",{className:"sg-pg-head"},h("h2",null,"\u4F1A\u8BDD\u8BB0\u5FC6"),h("span",{className:"sg-pg-tag"},h("i",{className:"sg-sw water","aria-hidden":"true"}),pagedBlocks.page.total+" \u5757"+turnSpan),conversations.length?h("span",{className:"sg-pg-end"},h("label",{className:"sg-conversation"},h("span",null,"\u5F53\u524D\u5BF9\u8BDD\uFF1A"),h("select",{value:activeThreadId||"",onChange:event3=>onConversationChange(event3.target.value),"aria-label":"\u5F53\u524D\u5BF9\u8BDD"},conversations.map(conversation=>h("option",{key:conversation.id,value:conversation.id},conversation.label))))):null),h("section",{className:"sg-block-list sg-ss-list","aria-label":"Block \u5217\u8868"},h("section",{className:"sg-visually-hidden","aria-labelledby":"sg-decay-title"},h("h2",{id:"sg-decay-title"},"\u5757\u8870\u51CF\u603B\u89C8"),h("div",{className:"sg-distribution","aria-label":"Block \u5F53\u524D\u5C42\u7EA7\u5206\u5E03"},visible.map(block=>h("span",{key:block.id,className:"sg-level-chip","data-level":visibleBlockLevel(block)===null?void 0:String(block.currentLevel),title:"Block #"+block.sequence},visibleBlockLevel(block)===null?"\u5C1A\u672A\u786E\u8BA4":"L"+block.currentLevel)),h("span",{className:"sg-level-chip sg-open-chip"},"\u5F00\u653E\u5757 \xB7 \u672A\u5C01\u5B58")),h("input",{className:"sg-distribution-rail",type:"range",min:"0",max:"0",step:"1",value:"0",disabled:!0,readOnly:!0,"aria-label":"Block \u5206\u5E03\u6ED1\u8F68"})),h("div",{className:"sg-block-header sg-visually-hidden","aria-hidden":"true"},h("span",null,"\u52A9\u624B\u53EF\u89C1\u5C42\u7EA7"),h("span",null,"Block"),h("span",null,"\u8986\u76D6 Turn"),h("span",null,"\u8DDD\u6700\u65B0\u5C01\u5B58\u5757"),h("span")),h("div",{className:"sg-ss-scale"},h("span",null,"\u66F4\u65E9"),h("span",{className:"sg-r","aria-hidden":"true"},[0,1,2,3,4,5].map(level=>h("i",{key:level,style:{height:5+level*3+"px",opacity:.3+level*.14}}))),h("span",null,"\u6700\u8FD1"),h("span",null,"\u8D8A\u65E9\u7684\u5BF9\u8BDD\u538B\u5F97\u8D8A\u8584")),h("div",{className:"sg-ss"},h("div",{className:"sg-ss-main"},visible.map(block=>h("div",{key:block.id,className:"sg-block-unit"},h("button",{className:"sg-block-toggle",type:"button",onClick:()=>narrow?setDetailBlockId(block.id):toggleBlock(block),"aria-expanded":narrow?void 0:expandedId===block.id?"true":"false","aria-label":"\u8BB0\u5FC6\u5757 "+block.sequence+"\uFF0C"+turnRangeText(block.turnRange)+(narrow?"\uFF0C\u6253\u5F00\u8BE6\u60C5":"")},h("span",{className:"sg-ss-num"},String(block.sequence)),h("span",{className:"sg-ss-bar",style:{height:20+levelOf(block)*5+"px",background:"color-mix(in srgb, var(--sg-water) "+(14+levelOf(block)*14)+"%, var(--sg-page))"}},h("span",null,block.title||(block.virtual?"\u65E7 Block #":"Block #")+block.sequence)),h("span",{className:"sg-ss-use"}),h("span",{className:"sg-block-turn"},turnRangeText(block.turnRange)),h("span",{className:"sg-block-distance"},block.distanceFromLatest===0?"0\uFF08\u6700\u65B0\uFF09":block.distanceFromLatest+" \u4E2A Block"),null),h(BlockSelectionFeedback,{block,feedback:selectionFeedback[block.id]?.scope===scope?selectionFeedback[block.id]:null,onRefresh:async()=>{try{if(await refresh(),activeScope.current!==scope)return;pagedBlocks.page.offset>0&&await pagedBlocks.loadOffset(pagedBlocks.page.offset),activeScope.current===scope&&setSelectionFeedback(current=>({...current,[block.id]:null}))}catch{}}}),previewError?.scope===scope&&previewError.blockId===block.id?h("div",{role:"alert",className:"sg-selection-feedback error"},previewError.message):null,summaryUnavailable(block)?h(SummaryUnavailable,{key:namespace+":"+block.id,namespace,block}):null,expandedId===block.id?h("div",{className:"sg-block-expanded"},h(BlockLayerPanel,{block,detail:details[block.id],loading:loadingId===block.id,selectionBusy:expanding.scope===scope&&expanding.level>=0,expandingLevel:expanding.scope===scope&&expanding.blockId===block.id?expanding.level:-1,onExpand:level=>expandTo(block,level)})):null)),h("div",{className:"sg-block-unit"},h("div",{className:"sg-ss-open"},h("span",{className:"sg-ss-num"},"\xB7"),h("div",{className:"sg-ss-bar"},h("span",null,"\u6B63\u5728\u8BB0\u5F55"),h("span",{className:"sg-ss-dots",role:"img","aria-label":"\u8FD8\u5DEE "+remainingDots+" \u8F6E\u5C01\u5B58","aria-hidden":void 0},Array.from({length:remainingDots},(_,index)=>h("i",{key:index,className:index<Math.min(remainingDots,Math.max(0,openCapacity-openUsed))?"":"o"})))),h("span")))),selectedBlock?h("aside",{className:"sg-ss-side","aria-label":"\u9009\u4E2D\u8BB0\u5FC6\u5757\u8BE6\u60C5"},h("h3",null,selectedBlock.title||"Block #"+selectedBlock.sequence),h("span",{className:"sg-k"},"\u8BB0\u5FC6\u5757 "+selectedBlock.sequence+" \xB7 "+turnRangeText(selectedBlock.turnRange)),h("div",{className:"sg-lvl","aria-hidden":"true"},[0,1,2,3,4,5].map(level=>h("i",{key:level,className:level<=levelOf(selectedBlock)?"on":""}))),h("div",{className:"sg-lvl-l"},h("span",null,"\u53EA\u7559\u6807\u9898"),h("span",null,"\u539F\u6587")),h("p",null,selectedBlock.summary||(selectedBlock.keypoints||[]).join("\uFF1B")||"\u8FD9\u4E00\u5757\u6682\u65F6\u6CA1\u6709\u6458\u8981\u3002"),h("button",{type:"button",className:"sg-btn",onClick:()=>toggleBlock(selectedBlock)},expandedId===selectedBlock.id?"\u6536\u8D77\u8BE6\u60C5":"\u770B\u539F\u6587")):null)),h(Pagination,{page:pagedBlocks.page,loading:pagedBlocks.loading,error:pagedBlocks.error,onOffset:pagedBlocks.loadOffset}))}function SourceDetails({item,source,kind}){let messages=source?.messages||[];return h("div",{className:"sg-detail-section"},h("h3",{className:"sg-section-title"},"\u6765\u6E90"),h("div",{className:"sg-source-label"},h("span",{className:"sg-source-icon","aria-hidden":"true"},"\u25A3"),h("span",null,"\u5F53\u524D DeepSeek \u5BF9\u8BDD")),h("details",{className:"sg-tech"},h("summary",null,"\u6280\u672F\u8BE6\u60C5"),h("div",{className:"sg-tech-body"},h("div",{className:"sg-tech-row"},h("span",{className:"sg-muted"},kind==="block"?"Block ID":"Event ID"),h("span",{className:"sg-code"},item.id)),kind==="block"&&item.turnRange?h("div",{className:"sg-tech-row"},h("span",{className:"sg-muted"},"Turn"),h("span",null,item.turnRange.join(" - "))):null,messages.length?messages.map(message=>h("div",{key:message.id,className:"sg-raw-message"},h("div",{className:"sg-muted"},String(message.role||"")+" \xB7 "+formatTime(message.createdAt)),h("div",{className:"sg-code"},String(message.content||"")))):h("div",{className:"sg-muted"},"\u5F53\u524D\u6570\u636E\u4E2D\u6CA1\u6709\u53EF\u663E\u793A\u7684\u6765\u6E90\u6D88\u606F\u3002"))))}function EventDetail({event:event3,project,source,onBack,backLabel,onNode}){let detailedEvent=source?.events?.find(item=>item.id===event3.id)||event3;return h(InfoPopoverGroup,null,h(BackBar,{label:backLabel,onBack}),h("header",{className:"sg-detail-header sg-event-page-header"},h("span",{className:"sg-event-detail-kicker"},"Event"),h("h2",{className:"sg-detail-title"},detailedEvent.title||"\u8BB0\u5FC6\u8BE6\u60C5"),h(EventMetadata,{event:detailedEvent,nodes:source?.relatedNodes||[],onNode})),h(EventMemoryDetails,{event:detailedEvent,sourceMessages:source?.messages||[]}))}function ElementDetail({element:element3,events,source,openEvent,onBack,backLabel}){let facts=[];element3.currentState&&facts.push(element3.currentState);for(let fact of element3.facts||[]){let value=Array.isArray(fact.value)?fact.value.join("\u3001"):fact.value;value&&!facts.includes(String(value))&&facts.push(String(value))}let related=events.filter(event3=>(element3.sourceEventIds||[]).includes(event3.id)).sort((a,b)=>String(b.updatedAt).localeCompare(String(a.updatedAt)));return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("header",{className:"sg-detail-header"},h("h2",{className:"sg-detail-title"},element3.name||"\u76F8\u5173\u4E8B\u7269"),h("p",{className:"sg-detail-subtitle"},"AI \u5173\u4E8E\u5B83\u76EE\u524D\u77E5\u9053\u8FD9\u4E9B"),h("div",{className:"sg-meta"},h("span",null,"\u76F8\u5173\u7ECF\u5386 "+related.length+" \u6761"),h("span",{className:"sg-meta-sep"},"\u6700\u8FD1\u66F4\u65B0 "+formatTime(element3.updatedAt)))),h("div",{className:"sg-detail-section"},facts.length?h("ul",{className:"sg-facts"},facts.map((fact,index)=>h("li",{key:index},fact))):h("div",{className:"sg-muted"},"\u6682\u65F6\u6CA1\u6709\u5F62\u6210\u53EF\u5C55\u793A\u7684\u8BA4\u8BC6\u3002")),h("div",{className:"sg-detail-section"},h("h3",{className:"sg-section-title"},"\u76F8\u5173\u7ECF\u5386"),related.length?h("div",{className:"sg-related-list"},related.map(event3=>h("button",{key:event3.id,className:"sg-related",onClick:()=>openEvent(event3)},h("span",{className:"sg-related-name"},event3.title),h("span",{className:"sg-related-time"},formatTime(event3.updatedAt||event3.createdAt))))):h("div",{className:"sg-muted"},"\u6CA1\u6709\u5173\u8054\u7ECF\u5386\u3002")),h(SourceDetails,{item:element3,source,kind:"element"}))}function processingFingerprint(overview){return JSON.stringify({failedJobs:Number(overview?.failedJobs||0),duplicateRepair:overview?.duplicateRepair??null,processingJobs:Number(overview?.processingJobs||0),failures:(overview?.failedJobDetails||[]).map(({kind,id:id2,attempts,updatedAt,lastError})=>({kind,id:id2,attempts,updatedAt,lastError})),processing:(overview?.processingJobDetails||[]).map(({kind,id:id2,status,attempts,updatedAt})=>({kind,id:id2,status,attempts,updatedAt}))})}function ProcessingStatus({overview,blocks,conversations,namespace,serverVersion,onBack,backLabel="\u8FD4\u56DE",refresh}){let failures=overview.failedJobDetails||[],failedKeys=new Set(failures.map(statusJobKey)),terminalFailedKeys=new Set(failures.filter(job=>job.state==="terminal-failed"||!job.state&&!job.nextRetryAt).map(statusJobKey)),hasProcessingDetails=Array.isArray(overview.processingJobDetails),rawProcessingCount=activeProcessingCount(overview),jobsByKey=new Map((overview.processingJobDetails||[]).map(job=>[statusJobKey(job),job]));for(let job of failures)jobsByKey.set(statusJobKey(job),job);let[refreshing,setRefreshing]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),[retrying,setRetrying]=React.useState(""),retryRequest=React.useRef(!1),[retryErrors,setRetryErrors]=React.useState({}),blockById=new Map(blocks.map(block=>[block.id,block])),conversationById=new Map((conversations||[]).map(conversation=>[conversation.id,conversation]));if(!hasProcessingDetails&&rawProcessingCount>0){let addLegacyJob=(block,kind,status,details={})=>{let job={id:"legacy:"+block.id+":"+kind,kind,status,attempts:details.attempts??0,nextRetryAt:details.nextRetryAt??null,updatedAt:details.updatedAt||block.createdAt,legacy:!0,blockIds:[block.id],blockDetails:[{id:block.id,sourceId:block.sourceId||block.id,sequence:block.sequence||block.blockIndex,title:block.title||block.l0Title,threadId:block.threadId,turnRange:block.turnRange,shouldExtract:block.shouldExtract}]};jobsByKey.set(statusJobKey(job),job)};for(let block of blocks){if(!(block.status==="processing"||block.processingStatus==="pending"))continue;let found=!1;(["pending","running"].includes(block.summaryJob?.status)||block.processingStatus==="pending")&&(addLegacyJob(block,"block-summary",block.summaryJob?.status||"pending",block.summaryJob),found=!0),block.eventExtraction?.status==="running"&&(addLegacyJob(block,"event-extraction","running",block.eventExtraction),found=!0),["pending","running"].includes(block.graphProjection?.status)&&(addLegacyJob(block,"graph-projection",block.graphProjection.status,block.graphProjection),found=!0),found||addLegacyJob(block,"event-extraction","running")}}let taskLabel=kind=>kind==="block-summary"?"\u4F1A\u8BDD\u8BB0\u5FC6\u538B\u7F29":kind==="event-extraction"?"\u957F\u671F\u8BB0\u5FC6\u63D0\u53D6":kind==="topic-projection"?"\u4E3B\u9898\u6574\u7406":"\u77E5\u8BC6\u56FE\u8C31\u66F4\u65B0",retryKey=statusJobKey,technicalStatusText=(status,job)=>job?.state==="terminal-failed"?"\u7EC8\u6001\u5931\u8D25":job?.state==="retryable"?"\u8BA1\u5212\u81EA\u52A8\u91CD\u8BD5":status==="running"?"\u8FD0\u884C\u4E2D":status==="pending"?"\u6392\u961F\u4E2D":status==="failed"?"\u5931\u8D25":status==="succeeded"||status==="completed"?"\u5DF2\u5B8C\u6210":String(status||"\u672A\u77E5"),workItems=new Map;for(let job of jobsByKey.values()){let details=Array.isArray(job.blockDetails)?job.blockDetails:[];details.length||(details=(Array.isArray(job.blockIds)&&job.blockIds.length?job.blockIds:job.id&&!["graph-projection","topic-projection"].includes(job.kind)?[job.id]:[]).map(id2=>blockById.get(id2)).filter(Boolean).map(block=>({id:block.id,sourceId:block.id,sequence:block.sequence,title:block.title||block.l0Title,threadId:block.threadId,turnRange:block.turnRange,shouldExtract:block.shouldExtract,rawAvailable:block.rawAvailable}))),details.length||(details=[{id:statusJobKey(job),sourceId:"",sequence:null,title:"",threadId:job.threadId||"",turnRange:job.turnRange,shouldExtract:null}]);for(let detail of details){let key=String(detail.threadId||"")+":"+String(detail.id||detail.sourceId||statusJobKey(job)),item=workItems.get(key)||{...detail,jobs:[]};item.jobs.some(candidate=>statusJobKey(candidate)===statusJobKey(job))||item.jobs.push(job),workItems.set(key,item)}}let items=[...workItems.values()].sort((left,right)=>{let threadOrder=String(left.threadId||"").localeCompare(String(right.threadId||""));return threadOrder||Number(left.turnRange?.[0]||left.sequence||0)-Number(right.turnRange?.[0]||right.sequence||0)}),itemState=item=>item.jobs.some(job=>terminalFailedKeys.has(statusJobKey(job)))?{kind:"failed",label:"\u7EC8\u6001\u5931\u8D25\uFF0C\u53EF\u91CD\u8BD5",mark:"!"}:item.jobs.some(job=>job.status==="running")?{kind:"processing",label:"\u6B63\u5728\u6574\u7406",mark:"\u25CF"}:item.jobs.some(job=>job.state==="retryable"||failedKeys.has(statusJobKey(job))&&job.nextRetryAt)?{kind:"processing",label:"\u8BA1\u5212\u81EA\u52A8\u91CD\u8BD5",mark:"\u21BB"}:{kind:"waiting",label:"\u7B49\u5F85\u6574\u7406",mark:"\u25CB"},itemStages=item=>{let summaryJob=item.jobs.find(job=>job.kind==="block-summary"),extractionJobs=item.jobs.filter(job=>job.kind==="event-extraction"),graphJobs=item.jobs.filter(job=>job.kind==="graph-projection"),topicJobs=item.jobs.filter(job=>job.kind==="topic-projection"),summaryFailed=summaryJob&&terminalFailedKeys.has(statusJobKey(summaryJob)),extractionFailed=extractionJobs.some(job=>terminalFailedKeys.has(statusJobKey(job))),graphFailed=graphJobs.some(job=>terminalFailedKeys.has(statusJobKey(job))),shortStage=summaryFailed?{kind:"failed",mark:"!",label:"\u7EC8\u6001\u5931\u8D25\uFF0C\u53EF\u91CD\u8BD5"}:summaryJob?.status==="running"?{kind:"processing",mark:"\u25CF",label:"\u5904\u7406\u4E2D"}:summaryJob?.state==="retryable"?{kind:"processing",mark:"\u21BB",label:"\u8BA1\u5212\u81EA\u52A8\u91CD\u8BD5"}:summaryJob?{kind:"waiting",mark:"\u25CB",label:"\u6392\u961F\u4E2D"}:{kind:"done",mark:"\u2713",label:"\u5DF2\u5B8C\u6210"},stageForJobs=(jobs,failed,emptyLabel,failedLabel="\u7EC8\u6001\u5931\u8D25\uFF0C\u53EF\u91CD\u8BD5")=>failed?{kind:"failed",mark:"!",label:failedLabel}:jobs.some(job=>job.status==="running")?{kind:"processing",mark:"\u25CF",label:"\u5904\u7406\u4E2D"}:jobs.some(job=>job.state==="retryable")?{kind:"processing",mark:"\u21BB",label:"\u8BA1\u5212\u81EA\u52A8\u91CD\u8BD5"}:jobs.length?{kind:"waiting",mark:"\u25CB",label:"\u6392\u961F\u4E2D"}:{kind:"waiting",mark:"\u25CB",label:emptyLabel};if(topicJobs.length===item.jobs.length)return[["\u4E3B\u9898\u6574\u7406",stageForJobs(topicJobs,topicJobs.some(job=>terminalFailedKeys.has(statusJobKey(job))),"\u7B49\u5F85\u6574\u7406")]];let extractionStage=extractionFailed?stageForJobs(extractionJobs,!0,"\u7B49\u5F85\u63D0\u53D6"):extractionJobs.length?stageForJobs(extractionJobs,!1,"\u7B49\u5F85\u63D0\u53D6"):graphJobs.length?{kind:"done",mark:"\u2713",label:"\u5DF2\u5B8C\u6210"}:shortStage.kind!=="done"?{kind:"waiting",mark:"\u25CB",label:"\u7B49\u5F85\u77ED\u671F\u6458\u8981"}:item.shouldExtract===!1?{kind:"skipped",mark:"\u2013",label:"\u65E0\u9700\u63D0\u53D6"}:{kind:"waiting",mark:"\u25CB",label:"\u7B49\u5F85\u63D0\u53D6"},graphStage=graphFailed?stageForJobs(graphJobs,!0,"\u7B49\u5F85\u56FE\u8C31\u66F4\u65B0","\u66F4\u65B0\u5931\u8D25\uFF0C\u53EF\u91CD\u8BD5"):graphJobs.length?stageForJobs(graphJobs,!1,"\u7B49\u5F85\u56FE\u8C31\u66F4\u65B0"):extractionStage.kind==="failed"||extractionStage.kind==="waiting"||extractionStage.kind==="processing"?{kind:"waiting",mark:"\u25CB",label:"\u7B49\u5F85\u957F\u671F\u8BB0\u5FC6\u63D0\u53D6"}:{kind:"waiting",mark:"\u25CB",label:"\u7B49\u5F85\u56FE\u8C31\u66F4\u65B0"};return[["\u539F\u59CB\u5BF9\u8BDD",item.rawAvailable===!0?{kind:"done",mark:"\u2713",label:"\u5F53\u524D\u53EF\u8BFB\u53D6"}:{kind:"waiting",mark:"\u25CB",label:item.rawAvailable===!1?"\u5F53\u524D\u65E0\u53EF\u8BFB\u53D6\u539F\u6587":"\u65E0\u6CD5\u786E\u8BA4\u662F\u5426\u53EF\u8BFB\u53D6"}],["\u538B\u7F29\u4F1A\u8BDD\u8BB0\u5FC6",shortStage],["\u63D0\u53D6\u957F\u671F\u8BB0\u5FC6",extractionStage],["\u66F4\u65B0\u77E5\u8BC6\u56FE\u8C31",graphStage]]},conversationLabel=threadId=>threadId==="__legacy__"?"\u5386\u53F2\u5BF9\u8BDD":conversationById.get(threadId)?.label||(threadId?"\u5BF9\u8BDD "+String(threadId).slice(0,8):"\u5386\u53F2\u6216\u672A\u77E5\u5BF9\u8BDD"),groups=[];for(let item of items){let key=item.threadId||"__unknown__",group2=groups.find(candidate=>candidate.key===key);group2||(group2={key,label:conversationLabel(item.threadId),items:[]},groups.push(group2)),group2.items.push(item)}let checkStatus=()=>{let before=processingFingerprint(overview);return setRefreshing(!0),setFeedback({kind:"",text:"\u6B63\u5728\u8BFB\u53D6\u2026"}),refresh({propagateError:!0}).then(next2=>{let selected=next2?.overview?.namespaces?.find(item=>item.namespace===namespace),changed=selected&&processingFingerprint(selected)!==before;setFeedback({kind:"done",text:changed?"\u72B6\u6001\u5DF2\u66F4\u65B0":"\u72B6\u6001\u6CA1\u6709\u53D8\u5316"})}).catch(reason=>{setFeedback({kind:"failed",text:"\u8BFB\u53D6\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}).finally(()=>setRefreshing(!1))},retryJob=job=>{if(retryRequest.current)return;retryRequest.current=!0;let key=retryKey(job);return setRetrying(key),setRetryErrors(current=>({...current,[key]:""})),setFeedback({kind:"",text:taskLabel(job.kind)+" \u6B63\u5728\u5904\u7406\u2026"}),api2("jobs/retry",{namespace,kind:job.kind,jobId:job.id},{method:"POST"}).then(()=>refresh({propagateError:!0})).then(()=>setFeedback({kind:"done",text:job.kind==="topic-projection"?"\u5DF2\u91CD\u65B0\u6392\u961F\uFF0C\u6309\u5386\u53F2\u989D\u5EA6\u7EE7\u7EED\u6574\u7406":"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u72B6\u6001\u5DF2\u66F4\u65B0"})).catch(async reason=>{let message=String(reason?.message||reason);setRetryErrors(current=>({...current,[key]:message})),setFeedback({kind:"failed",text:"\u91CD\u8BD5\u5931\u8D25\uFF1A"+message});try{await refresh({propagateError:!0})}catch{}}).finally(()=>{retryRequest.current=!1,setRetrying("")})},failedItems=items.filter(item=>item.jobs.some(job=>terminalFailedKeys.has(statusJobKey(job)))).length,activeItems=Math.max(0,items.length-failedItems),unresolvedProcessingCount=hasProcessingDetails?0:Math.max(0,rawProcessingCount-activeItems),detailsUnavailable=!hasProcessingDetails&&rawProcessingCount>0,versionMismatch=!!(serverVersion&&serverVersion!==STRATAGATE_CLIENT_VERSION),summary=items.length?groups.length+" \u4E2A\u4F1A\u8BDD \xB7 "+(activeItems?activeItems+" \u4E2A\u6B63\u5728\u6574\u7406":"")+(activeItems&&failedItems?" \xB7 ":"")+(failedItems?failedItems+" \u4E2A\u9700\u8981\u91CD\u8BD5":"")+(unresolvedProcessingCount?" \xB7 \u53E6\u6709 "+unresolvedProcessingCount+" \u4E2A\u8BE6\u60C5\u6682\u4E0D\u53EF\u7528":""):detailsUnavailable?"\u4ECD\u6709 "+rawProcessingCount+" \u4E2A\u540E\u53F0\u4EFB\u52A1\u6B63\u5728\u6574\u7406":hasProcessingDetails?"\u5F53\u524D\u6CA1\u6709\u5F85\u5904\u7406\u6216\u5931\u8D25\u7684\u4EFB\u52A1":"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u540E\u53F0\u4EFB\u52A1\u72B6\u6001";return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u540E\u53F0\u4EFB\u52A1"),h("p",null,summary)),h("div",{className:"sg-process-summary"},h("strong",null,"\u540E\u53F0\u6574\u7406\u72B6\u6001"),h("span",null,"\u5DF2\u6709\u8BB0\u5FC6\u53EF\u7EE7\u7EED\u67E5\u770B\uFF1B\u5177\u4F53\u6765\u6E90\u4EE5\u5B9E\u9645\u53EF\u8BFB\u53D6\u5185\u5BB9\u4E3A\u51C6\u3002")),detailsUnavailable?h("div",{className:"sg-process-notice",role:"status"},h("strong",null,versionMismatch?"\u524D\u540E\u7AEF\u7248\u672C\u5C1A\u672A\u540C\u6B65":"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u5B8C\u6574\u4EFB\u52A1\u8BE6\u60C5"),h("span",null,versionMismatch?"\u5F53\u524D\u9875\u9762\u4E3A "+STRATAGATE_CLIENT_VERSION+"\uFF0C\u540E\u53F0\u4E3A "+serverVersion+"\u3002\u8BF7\u786E\u8BA4\u5B89\u88C5\u65B0\u5305\u540E\u5B8C\u5168\u9000\u51FA\u5E76\u91CD\u65B0\u542F\u52A8 DSH\u3002":"\u540E\u53F0\u53EA\u8FD4\u56DE\u4E86\u4EFB\u52A1\u6570\u91CF\uFF0C\u6CA1\u6709\u8FD4\u56DE\u4F1A\u8BDD\u548C\u8F6E\u6B21\u3002\u8BF7\u5B8C\u5168\u9000\u51FA\u5E76\u91CD\u65B0\u542F\u52A8 DSH \u540E\u518D\u68C0\u67E5\u3002")):null,groups.length?h("div",{className:"sg-process-groups"},groups.map(group2=>h("section",{key:group2.key,className:"sg-process-group"},h("header",{className:"sg-process-group-head"},h("h3",{className:"sg-process-group-title"},group2.label),h("span",{className:"sg-process-group-count"},group2.items.length+" \u4E2A\u5BF9\u8BDD\u7247\u6BB5")),group2.items.map(item=>{let state=itemState(item),range=Array.isArray(item.turnRange)?"\u7B2C "+item.turnRange[0]+"\u2013"+item.turnRange[1]+" \u8F6E":item.title||"\u5BF9\u8BDD\u7247\u6BB5",technicalJobs=item.jobs.filter(job=>!job.legacy);return h("article",{key:String(item.id||item.sourceId),className:"sg-process-card"},h("div",{className:"sg-process-card-head"},h("span",{className:"sg-process-range"},range),h("span",{className:"sg-process-state "+state.kind},h("span",{"aria-hidden":"true"},state.mark),state.label)),h("div",{className:"sg-process-stages"},itemStages(item).map(([name,stage])=>h("div",{key:name,className:"sg-process-stage"},h("span",{className:"sg-process-stage-state "+stage.kind,"aria-hidden":"true"},stage.mark),h("span",{className:"sg-process-stage-name"},name),h("span",{className:"sg-process-stage-state "+stage.kind},stage.label)))),technicalJobs.length?h("details",{className:"sg-process-tech"},h("summary",null,"\u67E5\u770B\u6280\u672F\u8BE6\u60C5"),technicalJobs.map(job=>{let key=retryKey(job),failed=terminalFailedKeys.has(key),busy=retrying===key;return h("div",{key,className:"sg-process-job"},h("div",{className:"sg-process-job-head"},h("strong",null,taskLabel(job.kind)),h("span",{className:"sg-stage-value "+(terminalFailedKeys.has(key)?"failed":job.status==="running"||job.state==="retryable"?"processing":"waiting")},technicalStatusText(job.status,job))),h("div",{className:"sg-process-job-meta sg-code"},"\u4EFB\u52A1 "+job.id+" \xB7 \u5DF2\u5C1D\u8BD5 "+String(job.attempts??0)+" \u6B21 \xB7 \u66F4\u65B0\u4E8E "+formatTime(job.updatedAt)),job.nextRetryAt?h("div",{className:"sg-process-job-meta"},"\u8BA1\u5212\u91CD\u8BD5\uFF1A"+formatTime(job.nextRetryAt)):null,failed&&!job.nextRetryAt?h("div",{className:"sg-process-job-meta"},"\u81EA\u52A8\u91CD\u8BD5\u5DF2\u505C\u6B62"):null,failed?h("pre",{className:"sg-job-error sg-code"},job.lastErrorFull||job.lastError||"\u6CA1\u6709\u8BB0\u5F55\u6280\u672F\u9519\u8BEF\u3002"):null,job.kind==="topic-projection"&&job.diagnostics?h("pre",{className:"sg-code"},JSON.stringify(job.diagnostics,null,2)):null,job.kind==="topic-projection"&&overview.topicDirectoryReadError?h("p",{className:"sg-muted"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55\u72B6\u6001\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u72B6\u6001\u3002"):null,failed?h("div",{className:"sg-process-job-actions"},h("span",{className:"sg-status-feedback failed",role:retryErrors[key]?"alert":void 0},retryErrors[key]||""),job.kind==="topic-projection"?h(TopicRetryButton,{failure:{jobId:job.id,eventCount:job.eventCount},namespace,revision:overview.topicDirectoryRevision,onDirectoryChanged:()=>refresh({propagateError:!0})}):h("button",{type:"button",className:"sg-save-button",disabled:!!retrying,onClick:()=>{retryJob(job)}},busy?"\u6B63\u5728\u5904\u7406\u2026":"\u91CD\u8BD5\u6B64\u4EFB\u52A1")):null)})):null)})))):detailsUnavailable?h("div",{className:"sg-process-unavailable"},h("strong",null,"\u4EFB\u52A1\u4ECD\u5728\u6574\u7406\uFF0C\u5177\u4F53\u4F1A\u8BDD\u6682\u4E0D\u53EF\u7528"),h("span",null,"\u8FD9\u4E0D\u4EE3\u8868\u5BF9\u8BDD\u4E22\u5931\uFF1B\u91CD\u542F\u5E76\u52A0\u8F7D\u540C\u4E00\u7248\u672C\u540E\u5373\u53EF\u663E\u793A\u8BE6\u60C5\u3002")):h(Empty,{title:hasProcessingDetails?"\u5F53\u524D\u6CA1\u6709\u5F85\u5904\u7406\u6216\u5931\u8D25\u7684\u4EFB\u52A1":"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4EFB\u52A1\u8BE6\u60C5",copy:"\u76EE\u5F55\u4E0E\u56FE\u8C31\u7684\u8986\u76D6\u60C5\u51B5\u8BF7\u4EE5\u5BF9\u5E94\u9875\u9762\u4E3A\u51C6\u3002"}),h("div",{className:"sg-process-footer"},h("button",{type:"button",className:"sg-quiet-button",disabled:refreshing,onClick:()=>{checkStatus()}},refreshing?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u21BB \u91CD\u65B0\u68C0\u67E5\u72B6\u6001"),h("span",{className:"sg-muted"},"\u53EA\u8BFB\u53D6\u6700\u65B0\u72B6\u6001\uFF0C\u4E0D\u4F1A\u89E6\u53D1\u6A21\u578B\u8C03\u7528\u3002"),feedback.text?h("span",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null))}let profilePageMemory=new Map,profileFieldDrafts=new Map,importDrafts=new Map,importRequests=new Map;function usePageMemoryState(cache3,key,initial){cache3.has(key)||cache3.set(key,initial);let[value,setValue]=React.useState(cache3.get(key));return[value,next2=>{let resolved=typeof next2=="function"?next2(cache3.get(key)):next2;cache3.set(key,resolved),setValue(resolved)}]}function ImportPage({namespace,onBack,refresh}){let[draft,setDraft]=usePageMemoryState(importDrafts,namespace,{text:""}),text=draft.text,setText=value=>setDraft({text:value}),[prompt,setPrompt]=React.useState(""),[promptLoading,setPromptLoading]=React.useState(!0),[copied,setCopied]=React.useState(!1),[busy,setBusy]=React.useState(!1),[job,setJob]=React.useState(null),[choices,setChoices]=React.useState({}),[result,setResult]=React.useState(null),[error3,setError]=React.useState(""),[connectionError,setConnectionError]=React.useState(""),[restoring,setRestoring]=React.useState(!0),lifecycle=React.useRef(null);React.useEffect(()=>{let active=!0,restoreTimer,controller=new AbortController;lifecycle.current=controller,api2("import",{},{signal:controller.signal}).then(value=>{active&&setPrompt(String(value.prompt||""))}).catch(reason=>{active&&setError(String(reason?.message||reason))}).finally(()=>{active&&setPromptLoading(!1)});let restore=async()=>{if(await importRequests.get(namespace)?.catch(()=>{}),!!active)return api2("import",{operation:"status",namespace},{signal:controller.signal}).then(value=>{active&&(setConnectionError(""),setRestoring(!1),value?.jobId&&!["undone","abandoned"].includes(value.status)&&(setJob(value),value.status==="committed"&&(setResult(value),clearCommittedDraft(value))))}).catch(()=>{active&&(setConnectionError("\u8FDE\u63A5\u6682\u65F6\u4E2D\u65AD\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\u2026"),restoreTimer=window.setTimeout(restore,2500))})};restore();let onKeyDown=event3=>{event3.key==="Escape"&&onBack()};return window.addEventListener("keydown",onKeyDown),()=>{active=!1,controller.abort(),lifecycle.current=null,window.clearTimeout(restoreTimer),window.removeEventListener("keydown",onKeyDown)}},[]),React.useEffect(()=>{if(!job?.jobId||!["extracting","processing"].includes(job.status))return;let active=!0,timer,controller=new AbortController,poll=()=>api2("import",{operation:"status",namespace,jobId:job.jobId},{signal:controller.signal}).then(next2=>{active&&(setConnectionError(""),setJob(next2),["extracting","processing"].includes(next2.status)&&(timer=window.setTimeout(poll,1200)))}).catch(()=>{active&&(setConnectionError("\u8FDE\u63A5\u6682\u65F6\u4E2D\u65AD\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\u2026"),timer=window.setTimeout(poll,2500))});return timer=window.setTimeout(poll,600),()=>{active=!1,controller.abort(),window.clearTimeout(timer)}},[job?.jobId,job?.status,namespace]);let copyPrompt=()=>{if(!prompt)return;(navigator.clipboard?.writeText?navigator.clipboard.writeText(prompt):Promise.reject(new Error("\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236"))).then(()=>{setCopied(!0),window.setTimeout(()=>setCopied(!1),1600)}).catch(reason=>setError(String(reason?.message||reason)))},clearCommittedDraft=next2=>{let current=importDrafts.get(namespace);next2.status==="committed"&&current?.jobId===next2.jobId&&current.text.trim()===next2.text&&setText("")},mutate=(body,onResult,submission)=>{if(importRequests.has(namespace))return;let controller=lifecycle.current,valid2=()=>controller&&lifecycle.current===controller&&!controller.signal.aborted;setBusy(!0),setError("");let request=api2("import",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...body,namespace})});return importRequests.set(namespace,request),request.then(next2=>{if(submission&&importDrafts.get(namespace)===submission&&next2?.jobId&&(submission.jobId=next2.jobId),valid2())return onResult(next2)}).catch(reason=>{valid2()&&setError(String(reason?.message||reason))}).finally(()=>{importRequests.get(namespace)===request&&importRequests.delete(namespace),valid2()&&setBusy(!1)})},analyze=()=>{if(!(!text.trim()||busy||restoring||job&&job.status!=="failed"))return setResult(null),setJob(null),setChoices({}),mutate({operation:"preview",text},setJob,draft)},commit=()=>{if(!job||busy)return;let requestedChoices=(job.decisions||[]).flatMap((decision,index)=>decision.requiresConfirmation?[{index,action:choices[index]||decision.action||"IGNORE"}]:[]);return draft.text.trim()===job.text&&(draft.jobId=job.jobId),mutate({operation:"commit",jobId:job.jobId,choices:requestedChoices},next2=>(clearCommittedDraft(next2),setResult(next2),setJob(next2),refresh()))},retry=()=>{if(!(!job?.jobId||busy))return mutate({operation:"retry",jobId:job.jobId},setJob)},abandon=()=>{if(!(!job?.jobId||busy))return mutate({operation:"abandon",jobId:job.jobId},()=>{setJob(null),setText(""),setChoices({})})},undo=()=>{if(!(!result?.sourceBlockId||busy))return mutate({operation:"undo",sourceBlockId:result.sourceBlockId},()=>(setResult(null),setJob(null),refresh()))},reset2=()=>{setResult(null),setJob(null),setChoices({}),setError("")},actionLabel={ADD:"\u65B0\u589E",MERGE:"\u5408\u5E76",SUPERSEDE:"\u53D6\u4EE3\u65E7\u8BB0\u5FC6",CONFLICT:"\u4FDD\u7559\u5E76\u6807\u8BB0\u51B2\u7A81",IGNORE:"\u5FFD\u7565"},running=job&&["extracting","processing"].includes(job.status),reviewable=job&&["ready","awaiting_confirmation"].includes(job.status),emptyJob=reviewable&&Number(job.totalCount||0)===0,percent=job?job.status==="extracting"?5:job.totalCount?Math.round(job.processedCount/job.totalCount*100):100:0;return h("div",{className:"sg-import-overlay",role:"presentation",onMouseDown:event3=>{event3.target===event3.currentTarget&&onBack()}},h("section",{className:"sg-import-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"sg-import-title"},h("header",{className:"sg-import-dialog-head"},h("h2",{id:"sg-import-title",className:"sg-import-dialog-title"},"\u5C06\u8BB0\u5FC6\u5BFC\u5165 StrataGate"),h("button",{type:"button",className:"sg-icon-button",onClick:onBack,"aria-label":"\u5173\u95ED"},"\xD7")),h("div",{className:"sg-import-step"},h("div",{className:"sg-import-step-head"},h("span",{className:"sg-import-step-num"},"1"),h("span",{className:"sg-import-step-title"},"\u590D\u5236\u4EE5\u4E0B\u63D0\u793A\u8BCD\u5230\u5176\u4ED6 AI \u5BF9\u8BDD\u4E2D"),h("button",{type:"button",className:"sg-import-copy",disabled:promptLoading||!prompt,onClick:copyPrompt},copied?"\u5DF2\u590D\u5236":"\u590D\u5236")),promptLoading?h("div",{className:"sg-import-loading"},"\u6B63\u5728\u52A0\u8F7D\u63D0\u793A\u8BCD\u2026"):h("div",{className:"sg-import-prompt",tabIndex:"0"},prompt||"\u63D0\u793A\u8BCD\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u3002")),h("div",{className:"sg-import-step"},h("div",{className:"sg-import-step-head"},h("span",{className:"sg-import-step-num"},"2"),h("span",{className:"sg-import-step-title"},"\u7C98\u8D34\u7ED3\u679C\uFF0C\u5148\u5206\u6790\u518D\u5BFC\u5165")),h("div",{className:"sg-import-card"},h("textarea",{value:text,disabled:restoring||busy||!!result||!!job&&job.status!=="failed",onChange:event3=>setText(event3.target.value),placeholder:"\u7C98\u8D34 JSON\uFF1B\u683C\u5F0F\u4E0D\u5408\u683C\u65F6\u4F1A\u81EA\u52A8\u5C1D\u8BD5\u6062\u590D","aria-label":"\u5916\u90E8 AI \u8BB0\u5FC6 JSON"})),!job&&!result?h("div",{className:"sg-import-hint"},restoring?"\u6B63\u5728\u68C0\u67E5\u5DF2\u6709\u5BFC\u5165\u4EFB\u52A1\u2026":"\u5173\u95ED\u540E\u53EF\u7EE7\u7EED\u7F16\u8F91\uFF1B\u8349\u7A3F\u4EC5\u5728\u5F53\u524D\u6D4F\u89C8\u5668\u9875\u9762\u4FDD\u7559\uFF0C\u5237\u65B0\u540E\u6E05\u7A7A\u3002"):null),running?h("div",{className:"sg-import-step"},h("div",{className:"sg-import-step-head"},h("span",{className:"sg-import-step-num"},"3"),h("span",{className:"sg-import-step-title"},job.status==="extracting"?"\u6B63\u5728\u4FEE\u590D\u5E76\u63D0\u53D6\u5019\u9009\u8BB0\u5FC6":"\u6B63\u5728\u68C0\u6D4B\u91CD\u590D\u4E0E\u51B2\u7A81")),h("div",{role:"progressbar","aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":percent,style:{height:"9px",overflow:"hidden",borderRadius:"999px",background:"var(--sg-border)"}},h("div",{style:{width:percent+"%",height:"100%",background:"var(--sg-accent)",transition:"width .25s ease"}})),h("div",{className:"sg-import-hint",style:{marginTop:"8px"}},job.status==="extracting"?"\u539F JSON \u4E0D\u5408\u683C\uFF0C\u6B63\u5728\u4F7F\u7528\u6A21\u578B\u515C\u5E95\u3002\u53EF\u4EE5\u5173\u95ED\u9875\u9762\uFF0C\u4EFB\u52A1\u4F1A\u7EE7\u7EED\u3002":"\u5DF2\u5B8C\u6210 "+job.processedCount+"/"+job.totalCount+"\uFF0C\u6B63\u5728\u5224\u65AD\u7B2C "+Math.min(job.processedCount+1,job.totalCount)+" \u6761\uFF1B\u53EF\u4EE5\u5173\u95ED\u9875\u9762\uFF0C\u7A0D\u540E\u91CD\u65B0\u6253\u5F00\u67E5\u770B\u3002")):null,reviewable?h("div",{className:"sg-import-step"},h("div",{className:"sg-import-step-head"},h("span",{className:"sg-import-step-num"},"3"),h("span",{className:"sg-import-step-title"},"\u5BFC\u5165\u9884\u89C8")),h("div",{className:"sg-import-hint"},emptyJob?"\u6CA1\u6709\u53D1\u73B0\u53EF\u5BFC\u5165\u7684\u957F\u671F\u8BB0\u5FC6\u3002":job.recoveredFromInvalidJson?"\u8FD9\u4E9B\u5019\u9009\u7531\u515C\u5E95\u6A21\u578B\u6062\u590D\uFF0C\u5168\u90E8\u9700\u8981\u4EBA\u5DE5\u786E\u8BA4\u3002":"\u9AD8\u7F6E\u4FE1\u5EA6\u7ED3\u679C\u81EA\u52A8\u91C7\u7528\uFF1B\u4F4E\u7F6E\u4FE1\u5EA6\u7ED3\u679C\u8BF7\u4EBA\u5DE5\u9009\u62E9\u5904\u7406\u65B9\u5F0F\u3002"),h("div",{className:"sg-import-preview"},(job.decisions||[]).map((decision,index)=>h("div",{key:index,className:"sg-import-preview-item"},h("div",{className:"sg-import-preview-title"},decision.candidate?.title||"\u672A\u547D\u540D\u8BB0\u5FC6"),h("div",{className:"sg-import-preview-content"},h("strong",null,"\u65B0\u8BB0\u5FC6\uFF1A"),h("span",null,decision.candidate?.summary||"\u65E0\u5185\u5BB9"),decision.candidate?.narrative?h("div",null,decision.candidate.narrative):null),decision.mergedCandidate?h("div",{className:"sg-import-preview-content"},h("strong",null,"\u5408\u5E76\u540E\uFF1A"),h("span",null,decision.mergedCandidate.title+"\uFF1A"+decision.mergedCandidate.summary)):null,decision.existingEventIds?.length&&decision.matches?.length?h("div",{className:"sg-import-preview-content"},h("strong",null,"\u53D7\u5F71\u54CD\u7684\u65E7\u8BB0\u5FC6\uFF1A"),decision.matches.filter(match2=>decision.existingEventIds.includes(match2.event.id)).map(match2=>h("div",{key:match2.event.id},match2.event.title+"\uFF1A"+match2.event.summary))):null,h("div",{className:"sg-import-preview-meta"},h("span",null,actionLabel[decision.action]||decision.action),h("span",null,"\u7F6E\u4FE1\u5EA6 "+Math.round(Number(decision.confidence||0)*100)+"%"),decision.existingEventIds?.length?h("span",null,"\u5173\u8054 "+decision.existingEventIds.length+" \u6761"):null),decision.reason?h("div",{className:"sg-import-preview-reason"},decision.reason):null,decision.requiresConfirmation?h("label",{className:"sg-import-review"},h("span",null,"\u4EBA\u5DE5\u9009\u62E9"),h("select",{value:choices[index]||decision.action,onChange:event3=>setChoices(current=>({...current,[index]:event3.target.value}))},(decision.existingEventIds?.length?["ADD","MERGE","SUPERSEDE","CONFLICT","IGNORE"]:["ADD","IGNORE"]).map(action=>h("option",{key:action,value:action},actionLabel[action])))):null)))):null,job?.status==="failed"?h("div",{className:"sg-import-error"},"\u4EFB\u52A1\u5931\u8D25\uFF1A"+(job.lastError||"\u672A\u77E5\u9519\u8BEF")):null,connectionError?h("div",{className:"sg-import-hint"},connectionError):null,error3?h("div",{className:"sg-import-error"},error3):null,result?h("div",{className:"sg-import-result"},"\u5BFC\u5165\u5B8C\u6210\uFF1A\u65B0\u589E "+Number(result.importedCount||0)+" \u6761\u8BB0\u5FC6\u3002\u53EF\u7ACB\u5373\u64A4\u9500\u672C\u6279\u6B21\u3002"):null,h("footer",{className:"sg-import-dialog-foot"},result?h("button",{type:"button",className:"sg-import-cancel",disabled:busy,onClick:undo},busy?"\u6B63\u5728\u64A4\u9500\u2026":"\u64A4\u9500\u672C\u6B21\u5BFC\u5165"):h("button",{type:"button",className:"sg-import-cancel",onClick:onBack},running?"\u5173\u95ED\uFF0C\u540E\u53F0\u7EE7\u7EED":"\u5173\u95ED"),!job&&!result&&text?h("button",{type:"button",className:"sg-import-cancel",disabled:restoring||busy,onClick:()=>{setText(""),setError("")}},"\u653E\u5F03\u8349\u7A3F"):null,result?h("button",{type:"button",className:"sg-import-button",disabled:busy,onClick:reset2},"\u5BFC\u5165\u53E6\u4E00\u6279"):job?.status==="failed"?h(React.Fragment,null,h("button",{type:"button",className:"sg-import-cancel",disabled:busy,onClick:()=>{setJob(null),setChoices({}),setError("")}},"\u4FEE\u6539\u540E\u91CD\u65B0\u5206\u6790"),h("button",{type:"button",className:"sg-import-cancel",disabled:busy,onClick:abandon},"\u653E\u5F03\u672C\u6B21\u5BFC\u5165"),h("button",{type:"button",className:"sg-import-button",disabled:busy,onClick:retry},busy?"\u6B63\u5728\u91CD\u8BD5\u2026":"\u91CD\u8BD5")):emptyJob?h("button",{type:"button",className:"sg-import-button",onClick:reset2},"\u5BFC\u5165\u53E6\u4E00\u6279"):reviewable?h("button",{type:"button",className:"sg-import-button",disabled:busy,onClick:commit},busy?"\u6B63\u5728\u5BFC\u5165\u2026":"\u786E\u8BA4\u5BFC\u5165"):running?h("button",{type:"button",className:"sg-import-button",disabled:!0},"\u540E\u53F0\u5904\u7406\u4E2D"):h("button",{type:"button",className:"sg-import-button",disabled:restoring||busy||!text.trim(),onClick:analyze},busy?"\u6B63\u5728\u521B\u5EFA\u4EFB\u52A1\u2026":"\u5206\u6790\u5E76\u9884\u89C8"))))}function SettingStepper({value,unit="",min:min4=1,max:max5=30,step:step3=1,disabled=!1,label,onChange}){let current=Number(value),bump=direction=>{if(!Number.isFinite(current)||disabled)return;let next2=Math.min(max5,Math.max(min4,Number((current+direction*step3).toFixed(2))));next2!==current&&onChange(next2)};return h("span",{className:"sg-stp",role:"group","aria-label":label},h("button",{type:"button","aria-label":"\u51CF\u5C11"+label,disabled:disabled||!Number.isFinite(current)||current<=min4,onClick:()=>bump(-1)},"\u2212"),h("span",{"aria-live":"polite",className:"sg-stp-value"},(Number.isFinite(current)?String(current):"")+unit),h("button",{type:"button","aria-label":"\u589E\u52A0"+label,disabled:disabled||!Number.isFinite(current)||current>=max5,onClick:()=>bump(1)},"+"))}function MoreHome({setView,selected,overview={},namespace,dataDirectory,updateSettings,savingSettings,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,setDailyEnabled,setDailyInjectionDays}){let pluginSettings=usePluginSettings?usePluginSettings(state=>state):null,settingsWritable=pluginSettings?.writable===!0,[pending,setPending]=React.useState({}),[settingError,setSettingError]=React.useState({key:"",text:""}),[savingKey,setSavingKey]=React.useState(""),[copyState,setCopyState]=React.useState("");React.useEffect(()=>{setPending({blockTurnSize:String(selected?.blockTurnSize??6),blockDecayLambda:String(selected?.blockDecayLambda??.3),agentMemoryRetrievalWeight:String(selected?.agentMemoryRetrievalWeight??1)})},[selected?.blockTurnSize,selected?.blockDecayLambda,selected?.agentMemoryRetrievalWeight]);let engine=[["blockTurnSize","\u6BCF\u5757\u8F6E\u6570","",1,30,1],["blockDecayLambda","\u8870\u51CF\u7CFB\u6570","",0,.4,.05],["agentMemoryRetrievalWeight","\u4E3B\u52A8\u68C0\u7D22\u5360\u6BD4","",0,5,.05]],saved=key=>Number(selected?.[key]??(key==="blockTurnSize"?6:key==="blockDecayLambda"?.3:1)),changedKeys=engine.map(([key])=>key).filter(key=>pending[key]!==void 0&&Number(pending[key])!==saved(key)&&pending[key]!==""),validEngine=engine.every(([key])=>{let raw=pending[key];return raw!==void 0&&raw!==""&&Number.isFinite(Number(raw))}),saveEngine=async()=>{if(!(!changedKeys.length||!validEngine||savingSettings)){setSettingError({key:"",text:""});try{await updateSettings({blockTurnSize:Number(pending.blockTurnSize),blockDecayLambda:Number(pending.blockDecayLambda),agentMemoryRetrievalWeight:Number(pending.agentMemoryRetrievalWeight)})}catch(reason){setSettingError({key:"engine",text:"\u672A\u80FD\u4FDD\u5B58\u5F15\u64CE\u53C2\u6570\uFF1A"+String(reason?.message||reason)})}}},discardEngine=()=>setPending({blockTurnSize:String(saved("blockTurnSize")),blockDecayLambda:String(saved("blockDecayLambda")),agentMemoryRetrievalWeight:String(saved("agentMemoryRetrievalWeight"))}),toggle=async(key,setter,next2)=>{if(setter){setSavingKey(key),setSettingError({key:"",text:""});try{await setter(next2)||setSettingError({key,text:"\u672A\u80FD\u4FDD\u5B58\u8FD9\u9879\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}catch(reason){setSettingError({key,text:"\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}finally{setSavingKey("")}}},stepDays=async next2=>{if(setDailyInjectionDays){setSavingKey("dailyDays"),setSettingError({key:"",text:""});try{await setDailyInjectionDays(next2)||setSettingError({key:"dailyDays",text:"\u5929\u6570\u672A\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}catch(reason){setSettingError({key:"dailyDays",text:"\u5929\u6570\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}finally{setSavingKey("")}}},copyWorkspace=async()=>{if(navigator?.clipboard?.writeText)try{await navigator.clipboard.writeText(namespace||""),setCopyState("\u5DF2\u590D\u5236"),setSettingError({key:"",text:""})}catch{setSettingError({key:"workspace",text:"\u590D\u5236\u5DE5\u4F5C\u533A ID \u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u3002"})}},retry=async(key,apply3)=>{setSettingError({key:"",text:""});try{await apply3()||setSettingError({key,text:"\u4ECD\u7136\u65E0\u6CD5\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"})}catch(reason){setSettingError({key,text:"\u4ECD\u7136\u65E0\u6CD5\u4FDD\u5B58\uFF1A"+String(reason?.message||reason)})}},rowError=(key,apply3)=>settingError.key===key?h("p",{className:"sg-more-error",role:"alert"},settingError.text,apply3?h("button",{type:"button",className:"sg-more-retry",onClick:()=>{retry(key,apply3)}},"\u91CD\u8BD5"):null):null,switchRow=({key,title,description,checked,setter,disabled=!1,child=!1})=>h("li",{key,className:"sg-more-row sg-more-switch"+(child?" child":"")},h("div",null,h("span",{className:"sg-k2"},title),description?h("span",{className:"sg-s2"},description):null,rowError(key,()=>setter(!checked))),h("button",{type:"button",className:"sg-setting-switch",role:"switch","aria-label":title,"aria-checked":checked,disabled:disabled||!settingsWritable||savingKey===key,onClick:()=>{toggle(key,setter,!checked)}})),goRow=(key,title,description,view)=>h("li",{key,className:"sg-more-row"},h("button",{type:"button",className:"sg-more-go",onClick:()=>setView({name:view})},h("div",null,h("span",{className:"sg-k2"},title),description?h("span",{className:"sg-s2"},description):null),h("span",{className:"sg-row-go","aria-hidden":"true"},"\u203A"))),group2=(title,rows,extra="")=>h("section",{key:title,className:"sg-profile-group","aria-label":title},h("h4",null,title),h("ul",null,rows,extra)),duplicates=Number(selected?.duplicateRepair?.needsReview||0),failed=Number(selected?.failedJobs||0),processing=Number(selected?.processingJobs||0),statusRows=[h("li",{key:"kpi",className:"sg-more-kpi"},h("div",null,["blocks","events","graphNodes"].map((key,index)=>h("div",{key},h("b",null,String(Number(selected?.[key]||0))),h("span",null,["\u8BB0\u5FC6\u5757","\u4E8B\u4EF6","\u56FE\u8C31\u8282\u70B9"][index]))))),goRow("system","\u7CFB\u7EDF\u72B6\u6001",failed?failed+" \u4E2A\u4EFB\u52A1\u9700\u8981\u91CD\u8BD5":processing?processing+" \u4E2A\u4EFB\u52A1\u8FDB\u884C\u4E2D":"\u8FD0\u884C\u6B63\u5E38","system"),goRow("duplicates","\u91CD\u590D\u8BB0\u5FC6",duplicates?duplicates+" \u7EC4\u7B49\u4F60\u786E\u8BA4":"\u6CA1\u6709\u9700\u8981\u786E\u8BA4\u7684\u5206\u7EC4","duplicates")],dataRows=[goRow("import","\u5BFC\u5165\u5176\u4ED6 AI \u7684\u8BB0\u5FC6","\u628A\u522B\u7684 AI \u7684\u5386\u53F2\u8BB0\u5FC6\u5E26\u8FDB\u6765","import"),goRow("settings","\u9AD8\u7EA7\u8BBE\u7F6E","\u5411\u91CF\u68C0\u7D22\u3001\u7CBE\u6392\u4E0E\u8BB0\u5FC6\u914D\u7F6E","settings"),h("li",{key:"directory",className:"sg-more-row sg-more-row-path"},h("div",{className:"sg-more-path"},h("span",{className:"sg-k2"},"\u6570\u636E\u76EE\u5F55"),h("span",{className:"sg-s2 sg-mono sg-path",title:dataDirectory||void 0},dataDirectory||"\u5F53\u524D\u4F7F\u7528\u5185\u5B58\u5B58\u50A8")),h("button",{type:"button",className:"sg-quiet-button",disabled:!dataDirectory,onClick:()=>{api2("storage/open-directory",{},{method:"POST"}).catch(reason=>setSettingError({key:"directory",text:"\u6253\u5F00\u5931\u8D25\uFF1A"+String(reason?.message||reason)}))}},"\u6253\u5F00")),h("li",{key:"workspace",className:"sg-more-row"},h("div",null,h("span",{className:"sg-k2"},"\u5F53\u524D\u5DE5\u4F5C\u533A"),h("span",{className:"sg-s2 sg-mono"},selected?.workspaceName||"\u5F53\u524D\u5DE5\u4F5C\u533A")),h("button",{type:"button",className:"sg-quiet-button",disabled:!namespace,onClick:copyWorkspace},copyState||"\u590D\u5236 ID"))],feedbackRows=[h("li",{key:"issue",className:"sg-more-row"},h("div",null,h("span",{className:"sg-k2"},"GitHub Issue"),h("span",{className:"sg-s2"},"\u95EE\u9898\u548C\u5EFA\u8BAE\u63D0\u5230 GitHub")),h("a",{className:"sg-quiet-button",href:ISSUE_URL,target:"_blank",rel:"noopener noreferrer"},"\u63D0 Issue")),goRow("support","\u751F\u6210\u53CD\u9988\u62A5\u544A","\u53D1\u51FA\u524D\u53EF\u4EE5\u5148\u770B\u5B8C\u6574\u5185\u5BB9","support")],displayRows=[switchRow({key:"sidebar",title:"\u653E\u5230\u5DE6\u4FA7\u680F",checked:pluginSettings?.value?.showSidebarEntry===!0,setter:setSidebarEntry}),switchRow({key:"shortStatus",title:"\u4F1A\u8BDD\u8BB0\u5FC6\u72B6\u6001",checked:pluginSettings?.value?.showShortTermStatus!==!1,setter:setShortTermStatus}),switchRow({key:"retrievalStatus",title:"\u8BB0\u5FC6\u68C0\u7D22\u72B6\u6001",checked:pluginSettings?.value?.showRetrievalStatus!==!1,setter:setRetrievalStatus}),pluginSettings?.value?.showStrataGateStatus===!1?switchRow({key:"master",title:"\u6062\u590D\u72B6\u6001\u63D0\u793A",description:"\u4E4B\u524D\u6574\u4F53\u5173\u95ED\u4E86\u804A\u5929\u754C\u9762\u7684\u72B6\u6001\u63D0\u793A",checked:!1,setter:setStrataGateStatus}):null].filter(Boolean),dailyRows=[switchRow({key:"daily",title:"\u5199\u6BCF\u65E5\u7B14\u8BB0",description:"\u5173\u95ED\u540E\u4E0D\u518D\u5199\u5165\uFF0C\u5DF2\u6709\u7B14\u8BB0\u4FDD\u7559",checked:pluginSettings?.value?.dailyNotesEnabled!==!1,setter:setDailyEnabled}),h("li",{key:"days",className:"sg-more-row"},h("div",null,h("span",{className:"sg-k2"},"\u5E26\u5165\u5929\u6570"),h("span",{className:"sg-s2"},"\u53D6\u6700\u8FD1\u6709\u7B14\u8BB0\u7684\u65E5\u671F")),SettingStepper({value:pluginSettings?.value?.dailyNotesInjectionDays??3,unit:" \u5929",min:1,max:30,disabled:!settingsWritable||savingKey==="dailyDays",label:"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570",onChange:next2=>{stepDays(next2)}}))],engineRows=engine.map(([key,title,unit,min4,max5,step3])=>{let dirty=changedKeys.includes(key);return h("li",{key,className:"sg-more-row"},h("div",null,h("span",{className:"sg-k2"+(dirty?" dirty":"")},title)),h("span",{className:"sg-engine-value"+(dirty?" dirty":"")},SettingStepper({value:pending[key]??saved(key),unit,min:min4,max:max5,step:step3,disabled:savingSettings,label:title,onChange:next2=>setPending(current=>({...current,[key]:String(next2)}))})))});return h(React.Fragment,null,h("div",{className:"sg-pg-head"},h("h2",null,"\u66F4\u591A")),h("div",{className:"sg-more"},h("div",{className:"sg-more-col"},group2("\u8FD0\u884C\u72B6\u6001",statusRows),group2("\u6570\u636E",dataRows),group2("\u53CD\u9988",feedbackRows)),h("div",{className:"sg-more-col"},group2("\u663E\u793A",displayRows),group2("\u77ED\u671F\u8BB0\u5FC6",dailyRows),group2("\u5F15\u64CE\u53C2\u6570",engineRows,h(React.Fragment,null,rowError("engine",()=>updateSettings({blockTurnSize:Number(pending.blockTurnSize),blockDecayLambda:Number(pending.blockDecayLambda),agentMemoryRetrievalWeight:Number(pending.agentMemoryRetrievalWeight)})),changedKeys.length?h("li",{className:"sg-dirty"},h("span",null,changedKeys.length+" \u9879\u672A\u4FDD\u5B58"),h("button",{type:"button",className:"sg-quiet-button",disabled:savingSettings,onClick:discardEngine},"\u653E\u5F03"),h("button",{type:"button",className:"sg-save-button",disabled:savingSettings||!validEngine,onClick:()=>{saveEngine()}},savingSettings?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):null)))))}function DisplayPage({onBack,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry}){let pluginSettings=usePluginSettings?usePluginSettings(state=>state):null,settingsWritable=pluginSettings?.writable===!0,[sidebarSaving,setSidebarSaving]=React.useState(!1),[sidebarError,setSidebarError]=React.useState(""),changeSidebar=async visible=>{setSidebarSaving(!0),setSidebarError("");try{await setSidebarEntry?.(visible)||setSidebarError("\u672A\u80FD\u4FDD\u5B58\u4FA7\u680F\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u8BD5\u3002")}catch{setSidebarError("\u672A\u80FD\u4FDD\u5B58\u4FA7\u680F\u8BBE\u7F6E\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002")}finally{setSidebarSaving(!1)}},showStrataGateStatus=strataGateStatusVisible(pluginSettings),showShortTermStatus=pluginSettings?.value?.showShortTermStatus!==!1,showRetrievalStatus=pluginSettings?.value?.showRetrievalStatus!==!1,setting=({title,description,checked,disabled=!1,onChange,child=!1})=>h("div",{className:"sg-display-setting "+(child?"child ":"")+(disabled?"sg-display-disabled":"")},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},title),h("span",{className:"sg-display-setting-description"},description)),h("button",{type:"button",className:"sg-setting-switch",role:"switch","aria-checked":checked,"aria-label":title,disabled:!settingsWritable||disabled,onClick:()=>{onChange&&onChange(!checked)}}));return h(React.Fragment,null,h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-pg-head"},h("h2",null,"\u754C\u9762\u4E0E\u663E\u793A")),h("p",{className:"sg-settings-group-copy"},"\u63A7\u5236\u4FA7\u680F\u5165\u53E3\u548C\u804A\u5929\u754C\u9762\u4E2D\u7684\u663E\u793A\u4FE1\u606F\u3002\u8BBE\u7F6E\u5BF9\u6240\u6709\u5DE5\u4F5C\u533A\u751F\u6548\u3002"),h("div",{className:"sg-settings-panel sg-display-settings"},setting({title:"\u5728\u5DE6\u4FA7\u680F\u663E\u793A StrataGate",description:"\u5173\u95ED\u540E\u9690\u85CF\u4FA7\u680F\u5165\u53E3\uFF0C\u4ECD\u53EF\u4ECE\u8BBE\u7F6E\u6253\u5F00\uFF1B\u8BB0\u5FC6\u3001\u68C0\u7D22\u548C\u540E\u53F0\u5904\u7406\u4E0D\u53D7\u5F71\u54CD\u3002",checked:pluginSettings?.value?.showSidebarEntry===!0,disabled:sidebarSaving||!setSidebarEntry,onChange:changeSidebar}),sidebarError?h("p",{role:"alert",className:"sg-error-note"},sidebarError):null,setting({title:"\u663E\u793A StrataGate \u72B6\u6001\u63D0\u793A",description:"\u5173\u95ED\u540E\u9690\u85CF\u804A\u5929\u754C\u9762\u4E2D\u7684 StrataGate \u72B6\u6001\u4FE1\u606F\uFF0C\u4E0D\u5F71\u54CD\u8BB0\u5FC6\u3001\u68C0\u7D22\u548C\u540E\u53F0\u5904\u7406\u3002",checked:showStrataGateStatus,onChange:setStrataGateStatus}),setting({title:"\u4F1A\u8BDD\u8BB0\u5FC6\u72B6\u6001",description:"\u663E\u793A Block \u8FDB\u5EA6\u3001\u5C01\u5B58\u7ED3\u679C\u548C\u6B63\u5728\u6574\u7406\u4F1A\u8BDD\u8BB0\u5FC6\u7B49\u72B6\u6001\u3002",checked:showShortTermStatus,disabled:!showStrataGateStatus,onChange:setShortTermStatus,child:!0}),setting({title:"\u8BB0\u5FC6\u68C0\u7D22\u72B6\u6001",description:"\u663E\u793A\u68C0\u7D22\u6B21\u6570\u3001\u8FD4\u56DE\u6570\u91CF\uFF0C\u4EE5\u53CA\u56DE\u7B54\u4E0B\u65B9\u7684\u8BB0\u5FC6\u91C7\u7528\u4FE1\u606F\u3002",checked:showRetrievalStatus,disabled:!showStrataGateStatus,onChange:setRetrievalStatus,child:!0})))}function redactText(value){return String(value??"").split(/\nRaw response(?: preview| \(full\))/i)[0].replace(/\b(?:sk[-_]|gh[opasu]_|github_pat_)[A-Za-z0-9_-]{8,}\b/g,"[REDACTED]").replace(/(["']?\b(?:api[_-]?key|token|password|passwd|access[_-]?token|refresh[_-]?token|secret|authorization)["']?\s*[:=]\s*)(["'])([\s\S]*?)\2/gi,"$1$2[REDACTED]$2").replace(/(\bauthorization\s*[:=]\s*)(Bearer|Basic|Token)\s+[^\s,;}]+/gi,"$1$2 [REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}\b/gi,"Bearer [REDACTED]").replace(/\b(?:Basic|Token)\s+[^\s,;}]+/gi,match2=>match2.replace(/\s+[^\s,;}]+$/," [REDACTED]")).replace(/(["']?\b(?:api[_-]?key|token|password|passwd|access[_-]?token|refresh[_-]?token|secret|authorization)["']?\s*[:=]\s*)([^\s,;}]+)/gi,"$1[REDACTED]").replace(/https?:\/\/[^\s<>"']+/gi,"[url]").replace(/[A-Z]:[\\/][^\s"'<>]+/gi,"[path]").replace(/\\\\[^\s"'<>\\]+\\[^\s"'<>]+/g,"[path]").replace(/(^|[\s"'(=:])\/(?:[^\s"'<>/]+\/)+[^\s"'<>]*/g,"$1[path]").replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi,"[email]")}function redactedJson(value){let sensitive=/^(password|passwd|token|access[_-]?token|refresh[_-]?token|api[_-]?key|secret|authorization)$/i,visit=(current,key="")=>sensitive.test(String(key))?"[REDACTED]":typeof current=="string"?redactText(current):Array.isArray(current)?current.map(item=>visit(item)):current&&typeof current=="object"?Object.fromEntries(Object.entries(current).map(([name,item])=>[name,visit(item,name)])):current;return JSON.stringify(visit(value),null,2)??"null"}function restoreFeedbackDraftValues(draft,touched={}){return{title:touched.title?void 0:String(draft?.title||""),problemContent:touched.body?void 0:feedbackDraftMarkdown(draft)}}function whitelistedMessage(message){return{id:message?.id,role:message?.role,content:message?.content,createdAt:message?.createdAt,threadId:message?.threadId,toolCalls:Array.isArray(message?.toolCalls)?message.toolCalls.map(call=>({name:call?.name,arguments:call?.arguments,result:call?.result})):void 0}}function whitelistedEvent(event3){let temporal=event3?.temporal,weight8=event3?.weight;return{id:event3?.id,formedTurn:event3?.formedTurn,title:event3?.title,summary:event3?.summary,tags:event3?.tags,quotes:event3?.quotes,sourceBlockId:event3?.sourceBlockId,sourceMessageIds:event3?.sourceMessageIds,temporal:temporal?{mentionedAt:temporal.mentionedAt,happenedStart:temporal.happenedStart,happenedEnd:temporal.happenedEnd,originalText:temporal.originalText,precision:temporal.precision,basis:temporal.basis,status:temporal.status,participants:temporal.participants,participantNodeIds:temporal.participantNodeIds,eventType:temporal.eventType,threadId:temporal.threadId,sameEventId:temporal.sameEventId,beforeEventIds:temporal.beforeEventIds,afterEventIds:temporal.afterEventIds,supersedesEventIds:temporal.supersedesEventIds,conflictsWithEventIds:temporal.conflictsWithEventIds,relatedEventIds:temporal.relatedEventIds}:void 0,scope:event3?.scope,criticality:event3?.criticality,status:event3?.status,supersededBy:event3?.supersededBy,weight:weight8?{mentionCount:weight8.mentionCount,lastAdoptedTurn:weight8.lastAdoptedTurn,lastRetrievedAt:weight8.lastRetrievedAt,pinned:weight8.pinned,floorWeight:weight8.floorWeight,forcedCap:weight8.forcedCap}:void 0,createdAt:event3?.createdAt,updatedAt:event3?.updatedAt}}function whitelistedBlock(block){let source=block?.source||block||{},messages=block?.messages||block?.l5Raw||source?.l5Raw;return{id:block?.id??source?.id,threadId:block?.threadId??source?.threadId,sequence:block?.sequence??source?.sequence,blockIndex:block?.blockIndex,turnRange:block?.turnRange||(source?.startTurn!==void 0&&source?.endTurn!==void 0?[source.startTurn,source.endTurn]:void 0),title:block?.title??source?.l0Title,tags:block?.tags??source?.l0Tags,summary:block?.summary??source?.l1Summary,keypoints:block?.keypoints??source?.l2Keypoints,condensed:source?.l3Condensed,readable:source?.l4Readable,messages:Array.isArray(messages)?messages.map(whitelistedMessage):void 0,layers:Array.isArray(block?.layers)?block.layers.map(layer=>({level:layer?.level,content:layer?.content,tokens:layer?.tokens,percentOfL5:layer?.percentOfL5})):void 0,currentLevel:block?.currentLevel??source?.pointerCurrentLevel,currentTokens:block?.currentTokens,l5Tokens:block?.l5Tokens,compressionPercent:block?.compressionPercent,layerTokens:block?.layerTokens,distanceFromLatest:block?.distanceFromLatest,expansionSource:block?.expansionSource,lastLiftedAt:block?.lastLiftedAt??source?.lastLiftedAt,sourceMessages:block?.sourceMessages,createdAt:block?.createdAt??source?.createdAt,virtual:block?.virtual,processingStatus:block?.processingStatus??source?.processingStatus,summaryJob:block?.summaryJob?{status:block.summaryJob.status,attempts:block.summaryJob.attempts,nextRetryAt:block.summaryJob.nextRetryAt,updatedAt:block.summaryJob.updatedAt}:void 0,eventExtraction:block?.eventExtraction?{status:block.eventExtraction.status,attempts:block.eventExtraction.attempts,updatedAt:block.eventExtraction.updatedAt,lastError:block.eventExtraction.lastError}:void 0,graphProjection:block?.graphProjection?{status:block.graphProjection.status,jobs:block.graphProjection.jobs,lastError:block.graphProjection.lastError}:void 0,relatedEvents:Array.isArray(block?.relatedEvents)?block.relatedEvents.map(whitelistedEvent):void 0,relatedNodes:Array.isArray(block?.relatedNodes)?block.relatedNodes.map(node=>({id:node?.id,name:node?.name,type:node?.type})):void 0}}function whitelistedGraphNode(node){return{id:node?.id,name:node?.name,type:node?.type,aliases:node?.aliases,tags:node?.tags,currentState:node?.currentState,facts:Array.isArray(node?.facts)?node.facts.map(fact=>({id:fact?.id,key:fact?.key,value:fact?.value,status:fact?.status,validFrom:fact?.validFrom,validTo:fact?.validTo,confidence:fact?.confidence,sourceEventIds:fact?.sourceEventIds,createdAt:fact?.createdAt,updatedAt:fact?.updatedAt})):void 0,status:node?.status,confidence:node?.confidence,sourceEventIds:node?.sourceEventIds,supportingEvents:Array.isArray(node?.supportingEvents)?node.supportingEvents.map(whitelistedEvent):void 0,createdAt:node?.createdAt,updatedAt:node?.updatedAt}}function whitelistedGraph(graph){return{projectorVersion:graph?.projectorVersion,nodes:Array.isArray(graph?.nodes)?graph.nodes.map(whitelistedGraphNode):[],edges:Array.isArray(graph?.edges)?graph.edges.map(edge=>({id:edge?.id,fromNodeId:edge?.fromNodeId,toNodeId:edge?.toNodeId,relation:edge?.relation,status:edge?.status,validFrom:edge?.validFrom,validTo:edge?.validTo,confidence:edge?.confidence,sourceEventIds:edge?.sourceEventIds,createdAt:edge?.createdAt,updatedAt:edge?.updatedAt})):[],clusters:Array.isArray(graph?.clusters)?graph.clusters.map(cluster=>({id:cluster?.id,label:cluster?.label,nodeIds:cluster?.nodeIds,tags:cluster?.tags})):[],migration:graph?.migration?{projected:graph.migration.projected,total:graph.migration.total,pending:graph.migration.pending,running:graph.migration.running,failed:graph.migration.failed,retryable:graph.migration.retryable,processing:graph.migration.processing,state:graph.migration.state,complete:graph.migration.complete}:null}}function feedbackDraftMarkdown(draft={}){if(String(draft.bodyMarkdown||"").trim())return String(draft.bodyMarkdown).trim();let lines=[],section=(heading,value)=>{let text=String(value||"").trim();text&&lines.push("## "+heading,"",text,"")};section("\u95EE\u9898\u63CF\u8FF0",draft.description);let steps=Array.isArray(draft.reproduction)?draft.reproduction.map(value=>String(value||"").trim()).filter(Boolean):[];return steps.length&&lines.push("## \u590D\u73B0\u6B65\u9AA4","",...steps.map((value,index)=>index+1+". "+value),""),section("\u9884\u671F\u884C\u4E3A",draft.expected),section("\u5B9E\u9645\u884C\u4E3A",draft.actual),section("\u76F8\u5173\u9519\u8BEF\u4FE1\u606F",draft.errorContext),lines.join(`
1343
+ `)||"\u70B9\u5DE6\u4FA7\u5C0F\u8282\uFF0C\u7FFB\u5F00\u5177\u4F53\u4E8B\u4EF6\u3002")):null,h("section",{className:"sg-topic-pending","aria-label":unassignedTotal?"\u5F85\u6574\u7406\u4E8B\u4EF6":"\u8BB0\u5FC6\u6574\u7406"},h("div",{className:"sg-topic-pending-heading"},unassignedTotal?h("button",{type:"button",className:"sg-topic-pending-toggle","aria-expanded":pendingOpen,"aria-controls":"sg-topic-pending-events",onClick:()=>setPendingOpen(value=>!value)},h("span",{className:"sg-topic-pending-label"},"\u5F85\u6574\u7406"),h("span",null,unassignedTotal+" \u6761"),h("span",{className:"sg-directory-chevron","aria-hidden":"true"},"\u203A")):null,h(DreamingPanel,{key:namespace,namespace,initialRun:directory?.dreaming,active,available:!blocked,inline:!0,onDirectoryChanged,onOpenDreamingSession})),unassignedTotal?h(DirectoryFold,{open:pendingOpen,id:"sg-topic-pending-events"},h("p",null,"\u8FD9\u4E9B\u8BB0\u5FC6\u5C1A\u672A\u5F62\u6210\u7A33\u5B9A\u4E3B\u9898\uFF0C\u4ECD\u53EF\u76F4\u63A5\u67E5\u770B\u539F\u4E8B\u4EF6\u3002"),h(TopicEventList,{namespace,revision:pageRevision,topicId:"pending",total:pendingTotal,active:active&&!blocked&&pendingOpen,openEvent,onDirectoryChanged:invalidate,expandLabel:"\u67E5\u770B\u5168\u90E8\u5F85\u6574\u7406",collapseLabel:"\u6536\u8D77\u5F85\u6574\u7406\u4E8B\u4EF6"})):null),h("div",{className:"sg-toc-foot sg-leaf-foot"},dreamSummary(),h(DirectoryContextPreview,{context:blocked?"":directory?.context,active}))))))}function LongTermPage({events,eventPage,graph,graphSettings={},project,query,setQuery,openEvent,namespace,focusNodeId,onFocusHandled,topicDirectory,onDirectoryChanged,onOpenDreamingSession,extractionGap=!1,active=!0,refresh}){let graphVisible=graphSettings.enabled===!0||graphSettings.noticeSeen!==!0,[mode,setMode]=React.useState("topics"),[selectedNodeId,setSelectedNodeId]=React.useState(""),[selectedEventId,setSelectedEventId]=React.useState(""),[graphNodeLimit,setGraphNodeLimit]=React.useState(100),[eventFilters,setEventFilters]=React.useState({time:"",node:"",type:"",status:""}),[nodeType,setNodeType]=React.useState(""),[nodeTag,setNodeTag]=React.useState(""),[filtersOpen,setFiltersOpen]=React.useState(!1),[fullScreen,setFullScreen]=React.useState(!1),[graphMenuOpen,setGraphMenuOpen]=React.useState(!1),graphMenuRef=React.useRef(null),debouncedQuery=useDebouncedValue(query),timelineParams=mode==="timeline"?{timeline:"true",...debouncedQuery.trim()?{q:debouncedQuery.trim()}:{},...eventFilters.time?{time:eventFilters.time}:{},...eventFilters.node?{participant:eventFilters.node}:{},...eventFilters.type?{eventType:eventFilters.type}:{},...eventFilters.status?{eventStatus:eventFilters.status}:{}}:{},pagedEvents=usePagedMemory({namespace,kind:"events",initialItems:events,initialPage:eventPage,fallbackLimit:40,extraParams:timelineParams,reloadOnParamsChange:mode==="timeline"}),timelineEvents=pagedEvents.items,nodes3=graph.nodes||[],edges3=graph.edges||[],clusters=graph.clusters||[],normalized=query.trim().toLocaleLowerCase(),nodeImportance=React.useMemo(()=>graphNodeImportance(nodes3,edges3,project),[nodes3,edges3,project]),nodeTags=[...new Set(nodes3.flatMap(node=>node.tags||[]))].sort((left,right)=>left.localeCompare(right));React.useEffect(()=>{if(!graphVisible||!focusNodeId||!nodes3.some(node=>node.id===focusNodeId))return;setMode("graph"),setNodeType(""),setNodeTag("");let rank=[...nodes3].sort((left,right)=>(nodeImportance.get(right.id)?.score||0)-(nodeImportance.get(left.id)?.score||0)).findIndex(node=>node.id===focusNodeId);rank>=0&&setGraphNodeLimit(current=>Math.max(current,rank+1)),setSelectedNodeId(focusNodeId),setFullScreen(!0),onFocusHandled?.()},[graphVisible,focusNodeId,nodes3,nodeImportance,onFocusHandled]),React.useEffect(()=>{if(!fullScreen||!active)return;let previous=document.body.style.overflow;document.body.style.overflow="hidden";let onKeyDown=event3=>{event3.key==="Escape"&&(document.querySelector('.sg-long-explorer .sg-info-trigger[aria-expanded="true"]')||(setFullScreen(!1),setFiltersOpen(!1)))};return window.addEventListener("keydown",onKeyDown),()=>{document.body.style.overflow=previous,window.removeEventListener("keydown",onKeyDown)}},[fullScreen,active]),React.useEffect(()=>{if(!graphMenuOpen)return;let onPointerDown=event3=>{graphMenuRef.current?.contains(event3.target)||setGraphMenuOpen(!1)},onKeyDown=event3=>{event3.key==="Escape"&&setGraphMenuOpen(!1)};return document.addEventListener("pointerdown",onPointerDown),document.addEventListener("keydown",onKeyDown),()=>{document.removeEventListener("pointerdown",onPointerDown),document.removeEventListener("keydown",onKeyDown)}},[graphMenuOpen]);let visibleNodes=nodes3.filter(node=>node.status!=="archived").filter(node=>!nodeType||node.type===nodeType).filter(node=>!nodeTag||(node.tags||[]).includes(nodeTag)).filter(node=>!normalized||JSON.stringify(node).toLocaleLowerCase().includes(normalized)),visibleGraphIds=new Set(visibleNodes.map(node=>node.id)),displayedGraphIds=new Set([...visibleNodes].sort((left,right)=>(nodeImportance.get(right.id)?.score||0)-(nodeImportance.get(left.id)?.score||0)).slice(0,graphNodeLimit).map(node=>node.id)),activeEdges=edges3.filter(edge=>edge.status==="active"&&visibleGraphIds.has(edge.fromNodeId)&&visibleGraphIds.has(edge.toNodeId)),displayedEdgeCount=activeEdges.filter(edge=>displayedGraphIds.has(edge.fromNodeId)&&displayedGraphIds.has(edge.toNodeId)).length,displayedNodeCount=Math.min(graphNodeLimit,visibleNodes.length),countText=(shown,total,unit)=>(shown===total?String(total):shown+" / "+total)+" "+unit,resultCount=mode==="graph"?countText(displayedNodeCount,visibleNodes.length,"\u4E2A\u8282\u70B9")+" \xB7 "+countText(displayedEdgeCount,activeEdges.length,"\u6761\u5173\u7CFB"):countText(timelineEvents.length,pagedEvents.page.total,"\u6761\u4E8B\u4EF6"),selectEvent=id2=>{setSelectedEventId(id2),setMode("timeline")},selectNode=id2=>{setSelectedNodeId(id2),setMode("graph")},openExplorer=()=>{mode==="graph"&&!selectedNodeId&&visibleNodes[0]&&setSelectedNodeId(visibleNodes[0].id),mode==="timeline"&&!selectedEventId&&timelineEvents[0]&&setSelectedEventId(timelineEvents[0].id),setFiltersOpen(!0),setFullScreen(!0)},migrationNotice=graphMigrationNotice(graph.migration),activeFilterCount=mode==="graph"?+!!nodeType+ +!!nodeTag:Object.values(eventFilters).filter(Boolean).length,filterControls=mode==="graph"?h("div",{className:"sg-filterbar"},h("select",{value:nodeType,onChange:event3=>setNodeType(event3.target.value),"aria-label":"\u8282\u70B9\u7C7B\u578B"},h("option",{value:""},"\u5168\u90E8\u8282\u70B9\u7C7B\u578B"),Object.entries(NODE_META).map(([value,meta3])=>h("option",{key:value,value},meta3[0]))),h("select",{value:nodeTag,onChange:event3=>setNodeTag(event3.target.value),"aria-label":"\u8BED\u4E49\u6807\u7B7E"},h("option",{value:""},"\u5168\u90E8\u8BED\u4E49\u6807\u7B7E"),nodeTags.map(tag=>h("option",{key:tag,value:tag},tag)))):h("div",{className:"sg-filterbar"},h("select",{value:eventFilters.time,onChange:event3=>setEventFilters({...eventFilters,time:event3.target.value}),"aria-label":"\u65F6\u95F4\u8303\u56F4"},h("option",{value:""},"\u5168\u90E8\u65F6\u95F4"),h("option",{value:"today"},"\u4ECA\u5929"),h("option",{value:"week"},"\u672C\u5468"),h("option",{value:"unknown"},"\u53D1\u751F\u65F6\u95F4\u672A\u77E5")),h("select",{value:eventFilters.node,onChange:event3=>setEventFilters({...eventFilters,node:event3.target.value}),"aria-label":"\u53C2\u4E0E\u5B9E\u4F53"},h("option",{value:""},"\u5168\u90E8\u5B9E\u4F53"),nodes3.map(node=>h("option",{key:node.id,value:node.id},node.name))),h("select",{value:eventFilters.type,onChange:event3=>setEventFilters({...eventFilters,type:event3.target.value}),"aria-label":"\u4E8B\u4EF6\u7C7B\u578B"},h("option",{value:""},"\u5168\u90E8\u7C7B\u578B"),Object.entries(EVENT_TYPE_TEXT).map(([value,label])=>h("option",{key:value,value},label))),h("select",{value:eventFilters.status,onChange:event3=>setEventFilters({...eventFilters,status:event3.target.value}),"aria-label":"\u4E8B\u4EF6\u72B6\u6001"},h("option",{value:""},"\u5168\u90E8\u72B6\u6001"),Object.entries(EVENT_STATUS_TEXT).map(([value,label])=>h("option",{key:value,value},label)))),longTabs=[["topics","\u76EE\u5F55"],...graphSettings.enabled===!0?[["graph","\u77E5\u8BC6\u56FE\u8C31"]]:[],["timeline","\u65F6\u95F4\u7EBF"]],tabButton=([id2,label])=>h("button",{key:id2,type:"button",className:mode===id2?"active":"","aria-current":mode===id2?"page":void 0,"aria-pressed":mode===id2,"aria-label":id2==="graph-add"?"\u91CD\u65B0\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31":label,onClick:()=>{setMode(id2==="graph-add"?"graph":id2),setGraphMenuOpen(id2==="graph-add"||id2==="graph"&&graphSettings.enabled!==!0&&graphSettings.noticeSeen!==!0),id2==="topics"&&(setFullScreen(!1),setFiltersOpen(!1))}},label),graphMenu=h("div",{ref:graphMenuRef,className:"sg-graph-menu"},h("button",{type:"button",className:"sg-graph-menu-trigger","aria-label":"\u77E5\u8BC6\u56FE\u8C31\u8BBE\u7F6E","aria-expanded":graphMenuOpen,onClick:()=>setGraphMenuOpen(value=>!value)},h("svg",{width:16,height:16,viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false"},h("path",{d:"M12 5v14M5 12h14",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"}))),graphMenuOpen?h("div",{className:"sg-graph-menu-popover"},h(GraphControlPanel,{state:graphSettings,refresh,page:!0,onOpenGraph:()=>{setGraphMenuOpen(!1),setMode("graph")},onGraphHidden:()=>{setGraphMenuOpen(!1),setMode("topics")}})):null),tabChildren=[...longTabs.map(tabButton),graphMenu];return h("section",{className:"sg-long-explorer "+(fullScreen?"fullscreen":""),"aria-label":fullScreen?"\u957F\u671F\u8BB0\u5FC6\u5168\u5C4F\u63A2\u7D22":"\u957F\u671F\u8BB0\u5FC6\u6D4F\u89C8"},h("div",{className:"sg-pg-head"},h("h2",null,"\u957F\u671F\u8BB0\u5FC6"),h("span",{className:"sg-pg-end"},h("nav",{className:"sg-long-tabs sg-seg","aria-label":"\u957F\u671F\u8BB0\u5FC6\u89C6\u89D2"},tabChildren))),h("div",{hidden:mode!=="topics"},h(TopicDirectory,{directory:topicDirectory,namespace,active:active&&mode==="topics",openEvent,onDirectoryChanged,onOpenDreamingSession})),mode==="topics"?null:h(React.Fragment,null,mode==="graph"&&migrationNotice?h("p",{className:"sg-muted"},migrationNotice):null,mode==="timeline"&&extractionGap?h("p",{className:"sg-muted"},"\u90E8\u5206\u5BF9\u8BDD\u5C1A\u672A\u5F62\u6210\u957F\u671F\u8BB0\u5FC6\uFF0C\u6682\u4E0D\u80FD\u901A\u8FC7\u957F\u671F\u8BB0\u5FC6\u68C0\u7D22\u3002"):null,h("div",{className:"sg-long-toolbar"},h(SearchBox,{value:query,onChange:setQuery,placeholder:mode==="graph"?"\u641C\u7D22\u4EBA\u7269\u3001\u9879\u76EE\u3001\u6982\u5FF5\u2026":"\u641C\u7D22\u4E8B\u4EF6\u2026"}),h("button",{type:"button",className:"sg-toolbar-button","aria-expanded":filtersOpen?"true":"false",onClick:()=>setFiltersOpen(!filtersOpen)},"\u7B5B\u9009 \u25BE",activeFilterCount?h("span",{className:"sg-active-filter-count"},activeFilterCount):null),mode==="graph"&&graphNodeLimit<visibleNodes.length?h("button",{type:"button",className:"sg-toolbar-button",onClick:()=>setGraphNodeLimit(current=>Math.min(visibleNodes.length,current+100))},"\u518D\u663E\u793A 100 \u4E2A"):null,h("button",{type:"button",className:"sg-toolbar-button",onClick:fullScreen?()=>{setFullScreen(!1),setFiltersOpen(!1)}:openExplorer},fullScreen?"\u9000\u51FA\u5168\u5C4F":"\u26F6 \u5168\u5C4F\u67E5\u770B"+(mode==="graph"?"\u56FE\u8C31":"\u65F6\u95F4\u7EBF"))),h("div",{className:"sg-toolbar-count"},resultCount),filtersOpen?filterControls:null,mode==="graph"?h("div",{className:"sg-long-layout "+(fullScreen?"":"sg-summary-layout"),"aria-disabled":!graphSettings.enabled,inert:graphSettings.enabled?void 0:"",style:graphSettings.enabled?void 0:{filter:"grayscale(1)",opacity:.4,pointerEvents:"none"}},h(GraphCanvas,{nodes:visibleNodes,edges:edges3,clusters,importance:nodeImportance,selectedId:selectedNodeId,onSelect:setSelectedNodeId,nodeLimit:graphNodeLimit,showSummary:!fullScreen,onViewDetails:openExplorer}),fullScreen?h(NodeDetailPanel,{node:nodes3.find(node=>node.id===selectedNodeId),nodes:nodes3,edges:edges3,events,onEvent:selectEvent}):null):h(React.Fragment,null,h("div",{className:"sg-long-layout "+(fullScreen?"sg-timeline-layout":"sg-summary-layout")},h(TimelineList,{events:timelineEvents,nodes:nodes3,onSelect:setSelectedEventId,selectedId:selectedEventId,floating:!fullScreen,onNode:selectNode,openSource:openEvent,dreaming:topicDirectory?.dreaming}),fullScreen?h(EventDetailPanel,{event:timelineEvents.find(event3=>event3.id===selectedEventId),nodes:nodes3,events:timelineEvents,onNode:selectNode,openSource:openEvent}):null),h(Pagination,{page:pagedEvents.page,loading:pagedEvents.loading,error:pagedEvents.error,onOffset:pagedEvents.loadOffset}))))}function previewText(value){let text=String(value||"").replace(/\s+/g," ").trim()||"\u6682\u65E0\u5185\u5BB9";return text.length>200?text.slice(0,200)+"\u2026":text}function turnRangeText(range){return!Array.isArray(range)||range.length<2||range[1]<range[0]?"\u7B49\u5F85\u65B0\u5BF9\u8BDD":"Turn "+range[0]+"\u2013"+range[1]}function LayerPreview({layer,currentLevel,expanding,busy,pendingSelection,allowExpand,onExpand}){let itemRef=React.useRef(null),hideTimer=React.useRef(null),popoverRef=React.useRef(null),level=Number(layer.level),actionable=allowExpand&&Number.isInteger(level)&&(level!==currentLevel||pendingSelection),cancelHide=()=>{hideTimer.current&&window.clearTimeout(hideTimer.current),hideTimer.current=null},removePopover=()=>{popoverRef.current?.remove(),popoverRef.current=null},showPopover=()=>{cancelHide();let rect=itemRef.current?.getBoundingClientRect();if(!rect)return;let inline=window.innerWidth<860,width2=Math.min(390,Math.max(240,window.innerWidth-24)),maxHeight=Math.min(520,window.innerHeight*.7),right=rect.right+12,left=right+width2<=window.innerWidth-12?right:Math.max(12,rect.left-width2-12),top=Math.min(Math.max(12,rect.top-8),Math.max(12,window.innerHeight-maxHeight-12));if(!popoverRef.current){let popover=document.createElement("aside"),title=document.createElement("strong"),content=document.createElement("p"),theme=window.getComputedStyle(itemRef.current),pageTheme=window.getComputedStyle(itemRef.current.closest(".sg-memory"));popover.className="sg-layer-popover",popover.setAttribute("role","tooltip"),popover.style.background=pageTheme.backgroundColor,popover.style.color=pageTheme.color,popover.style.borderColor=theme.borderColor,title.textContent="L"+level+" \u5B8C\u6574\u5185\u5BB9",content.className="sg-layer-full",content.textContent=String(layer.content||"\u6682\u65E0\u5185\u5BB9"),popover.append(title,content),popover.addEventListener("mouseenter",cancelHide),popover.addEventListener("mouseleave",scheduleHide),inline?itemRef.current.parentElement.appendChild(popover):document.body.appendChild(popover),popoverRef.current=popover}popoverRef.current.style.setProperty("position",inline?"relative":"fixed","important"),popoverRef.current.style.width=inline?"auto":width2+"px",popoverRef.current.style.left=inline?"0":left+"px",popoverRef.current.style.top=inline?"0":top+"px",popoverRef.current.style.maxHeight=inline?"240px":maxHeight+"px"},scheduleHide=()=>{cancelHide(),hideTimer.current=window.setTimeout(removePopover,140)};return React.useEffect(()=>()=>{cancelHide(),removePopover()},[]),h("div",{className:"sg-layer-hover"},h("div",{ref:itemRef,className:"sg-layer-item "+(level===currentLevel?"current":""),"data-level":String(level)},h("span",{className:"sg-layer-label"},"L"+level),h("span",{className:"sg-layer-preview",tabIndex:0,onMouseEnter:showPopover,onMouseLeave:scheduleHide,onFocus:showPopover,onBlur:scheduleHide},previewText(layer.content)),actionable?h("button",{className:"sg-layer-use",type:"button",disabled:busy,onMouseEnter:removePopover,onFocus:removePopover,onClick:event3=>{event3.stopPropagation(),onExpand(level)}},expanding?"\u6B63\u5728\u5E94\u7528\u2026":"\u8BA9\u52A9\u624B\u53C2\u8003 L"+level):h("span",{className:"sg-layer-using"},level===currentLevel?"\u52A9\u624B\u53EF\u89C1":"\u4EC5\u4F9B\u9884\u89C8")))}function BlockLayerPanel({block,detail,loading,expandingLevel,selectionBusy,onExpand}){if(loading)return h("div",{className:"sg-layer-panel"},h(Loading));let layers=Array.isArray(detail?.layers)?detail.layers:[],visibleLevel=visibleBlockLevel(block);return h("div",{className:"sg-layer-panel"},h("div",{className:"sg-layer-heading"},h("strong",null,"\u5206\u5C42\u5185\u5BB9\u9884\u89C8"),h("span",null,"\u52A9\u624B\u53EF\u89C1\uFF1A"+(visibleLevel===null?"\u5C1A\u672A\u786E\u8BA4":"L"+visibleLevel))),h("p",{className:"sg-layer-hint"},"\u9884\u89C8\u4E0D\u4F1A\u6539\u53D8\u52A9\u624B\u53EF\u89C1\u7684\u5185\u5BB9\u3002\u60AC\u505C\u6216\u805A\u7126\u53EF\u67E5\u770B\u5B8C\u6574\u5185\u5BB9\u3002"),block.virtual?h("div",{className:"sg-virtual-note"},"\u65E7\u4F1A\u8BDD\u5C55\u793A\u7247\u6BB5\u4E3A\u53EA\u8BFB\u5185\u5BB9\uFF0C\u4E0D\u4F1A\u6539\u5199\u539F\u59CB\u6570\u636E\u5E93\u3002"):null,layers.length?h("div",{className:"sg-layer-stack"},layers.slice().sort((a,b)=>a.level-b.level).map(layer=>h(LayerPreview,{key:layer.level,layer,currentLevel:visibleLevel,expanding:expandingLevel===layer.level,busy:selectionBusy||expandingLevel>=0,pendingSelection:block.surfaceSync?.status==="pending"||block.surfaceSync?.status==="blocked",allowExpand:!block.virtual,onExpand}))):h("div",{className:"sg-muted"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u8FD9\u6BB5\u5386\u53F2\u7684\u5206\u5C42\u5185\u5BB9\u3002"))}function visibleBlockLevel(block){return block.surfaceLevelKnown===!1||!Number.isInteger(block.currentLevel)?null:block.currentLevel}function BlockSelectionFeedback({block,feedback,onRefresh}){let value=feedback||block.surfaceSync;if(!value||value.status==="applied"&&!feedback)return null;let visible=visibleBlockLevel(block),current=visible===null?"\u52A9\u624B\u53EF\u89C1\u7684\u5C42\u7EA7\u5C1A\u672A\u786E\u8BA4\u3002":(value.uncertain?"\u4E0A\u6B21\u786E\u8BA4\u52A9\u624B\u53EF\u89C1 L":"\u52A9\u624B\u5F53\u524D\u53EF\u89C1 L")+visible+"\u3002",level=value.level??block.targetLevel,selected=Number.isInteger(level)?"L"+level:"\u6240\u9009\u5185\u5BB9",message=value.status==="applied"?value.message:(value.status==="pending"?"\u5DF2\u9009\u62E9 "+selected+"\u3002":"\u6682\u65F6\u65E0\u6CD5\u5E94\u7528 "+selected+"\u3002")+value.message+" "+current;return h("div",{className:"sg-selection-feedback"+(value.status==="blocked"?" error":""),role:value.status==="blocked"?"alert":"status"},message,value.uncertain&&onRefresh?h("button",{type:"button",className:"sg-quiet-button",onClick:onRefresh},"\u5237\u65B0\u72B6\u6001"):null)}function SummaryUnavailable({namespace,block}){let[source,setSource]=React.useState(null),[readError,setReadError]=React.useState(null),[loading,setLoading]=React.useState(!1),[open,setOpen]=React.useState(!1),request=React.useRef(null);React.useEffect(()=>()=>request.current?.abort(),[]);let openRaw=async()=>{if(request.current)return;if(source){setOpen(!0);return}let controller=new AbortController;request.current=controller,setLoading(!0),setReadError(null);try{let value=await api2("sources",{namespace,blockId:block.id},{signal:controller.signal});if(controller.signal.aborted)return;if(value.namespace!==namespace||!Array.isArray(value.messages)){setReadError({kind:"temporary",text:"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u8FD9\u6BB5\u5BF9\u8BDD\u7684\u539F\u6587\u3002"});return}if(!value.messages.some(message=>String(message.content||"").trim())){setReadError({kind:"unavailable",text:"\u5F53\u524D\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684\u539F\u6587\u3002"});return}setSource(value),setOpen(!0)}catch(reason){controller.signal.aborted||setReadError({kind:[401,403,404,410].includes(reason?.status)?"unavailable":"temporary",text:"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u8FD9\u6BB5\u5BF9\u8BDD\u7684\u539F\u6587\u3002"})}finally{request.current===controller&&(request.current=null,controller.signal.aborted||setLoading(!1))}},rawId="sg-summary-raw-"+block.id;return h("div",{className:"sg-block-expanded sg-muted"},h("p",null,"\u8FD9\u6BB5\u5BF9\u8BDD\u7684\u6458\u8981\u6682\u4E0D\u53EF\u7528\u3002"),(block.rawAvailable||source)&&readError?.kind!=="unavailable"?h("button",{type:"button",className:"sg-quiet-button",disabled:loading,"aria-expanded":open,"aria-controls":rawId,onClick:open?()=>setOpen(!1):openRaw},open?"\u6536\u8D77\u539F\u59CB\u5BF9\u8BDD":loading?"\u6B63\u5728\u8BFB\u53D6\u2026":readError?.kind==="temporary"?"\u91CD\u65B0\u8BFB\u53D6\u539F\u6587":"\u67E5\u770B\u539F\u59CB\u5BF9\u8BDD"):null,readError?h("p",{role:"status"},readError.text):null,open&&source?h("div",{id:rawId,className:"sg-summary-raw"},source.messages.map(message=>h("div",{key:message.id,className:"sg-raw-message"},h("div",{className:"sg-muted"},message.role+" \xB7 "+formatTime(message.createdAt)),h("div",{className:"sg-code"},String(message.content||""))))):null)}let DAILY_WEEK=["\u5468\u65E5","\u5468\u4E00","\u5468\u4E8C","\u5468\u4E09","\u5468\u56DB","\u5468\u4E94","\u5468\u516D"];function dailyParts(date){let[year,month,day]=date.split("-").map(Number);return{year,month,day,week:DAILY_WEEK[new Date(Date.UTC(year,month-1,day)).getUTCDay()]}}function dailyRelative(date,today){let days=Math.round((Date.parse(today+"T00:00:00Z")-Date.parse(date+"T00:00:00Z"))/864e5);return days===0?"\u4ECA\u5929":days===1?"\u6628\u5929":days>1?days+" \u5929\u524D":Math.abs(days)+" \u5929\u540E"}function DailyIcon({name}){let paths={calendar:["M8 2v4","M16 2v4","M3 10h18","M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2"],folder:["M6 14 7.5 11a2 2 0 0 1 1.8-1H20a2 2 0 0 1 1.9 2.6l-2.2 7A2 2 0 0 1 17.8 21H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v2"],left:["m15 18-6-6 6-6"],right:["m9 18 6-6-6-6"],refresh:["M3 12a9 9 0 0 1 15.4-6.4L21 8","M21 3v5h-5","M21 12a9 9 0 0 1-15.4 6.4L3 16","M8 16H3v5"],notebook:["M2 6h4","M2 10h4","M2 14h4","M2 18h4","M8 2v20","M6 2h13a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2"],alert:["M12 8v4","M12 16h.01"],pause:["M10 8v8","M14 8v8"]};return h("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},["alert","pause"].includes(name)?h("circle",{cx:12,cy:12,r:10}):null,(paths[name]||[]).map((d,key)=>h("path",{key,d})))}function dailyInline(text){return String(text).split(/(`[^`\n]+`)/g).map((part,key)=>/^`[^`\n]+`$/.test(part)?h("code",{key},part.slice(1,-1)):part)}function renderDailyMarkdown(markdown){let output2=[],children=[],title=null,list=[],flushList=()=>{list.length&&(children.push(h("ul",{key:"list-"+children.length},list)),list=[])},flushItem=()=>{flushList(),(children.length||title!==null)&&output2.push(h("article",{className:"sg-daily-item",key:output2.length},title!==null?h("h4",null,dailyInline(title)):null,children)),children=[],title=null};for(let raw of String(markdown).split(/\r?\n/)){let line=raw.trimEnd();if(/^# \d{4}-\d{2}-\d{2}$/.test(line))continue;if(line.startsWith("## ")){flushItem(),title=line.slice(3);continue}if(line.startsWith("- ")){list.push(h("li",{key:list.length},dailyInline(line.slice(2))));continue}if(flushList(),!line)continue;let status=line.match(/^(当前|已完成):\s*(.*)$/);children.push(status?h("p",{key:children.length,className:"sg-daily-status"+(status[1]==="\u5DF2\u5B8C\u6210"?" done":"")},h("b",null,status[1]),h("span",null,dailyInline(status[2]))):h("p",{key:children.length},dailyInline(line)))}return flushItem(),output2}function dailyNoteDigest(markdown){let items=[],current=null;for(let raw of String(markdown||"").split(/\r?\n/)){let line=raw.trim();if(!line||/^# \d{4}-\d{2}-\d{2}$/.test(line))continue;if(line.startsWith("## ")){current={title:line.slice(3),detail:"",time:""},items.push(current);continue}if(!current)continue;let clock=line.match(/\b([01]?\d|2[0-3]):([0-5]\d)\b/);clock&&!current.time&&(current.time=clock[1].padStart(2,"0")+":"+clock[2]),current.detail||(current.detail=line.replace(/^(当前|已完成):\s*/,"").replace(/^[-*]\s+/,""))}return items}function DailyNotesPage({namespace,setDailyInjectionDays}){let[index,setIndex]=React.useState(null),[indexLoading,setIndexLoading]=React.useState(!0),[indexError,setIndexError]=React.useState(""),[selected,setSelected]=React.useState(""),[note,setNote]=React.useState({loading:!1,date:"",markdown:"",error:""}),[revision,setRevision]=React.useState(0),[noteRevision,setNoteRevision]=React.useState(0),[dayDigests,setDayDigests]=React.useState({}),[daySaving,setDaySaving]=React.useState(!1),[dayError,setDayError]=React.useState(""),[daysOverride,setDaysOverride]=React.useState(null),[openDay,setOpenDay]=React.useState(!1);React.useEffect(()=>{let abort=new AbortController;return setIndexLoading(!0),setIndexError(""),setOpenDay(!1),namespace?(api2("daily",{namespace},{signal:abort.signal}).then(data4=>{abort.signal.aborted||(setDaysOverride(null),setIndex(data4),setSelected(current=>data4.dates.includes(current)?current:data4.injectedDates[0]||data4.dates[0]||""))}).catch(error3=>{abort.signal.aborted||setIndexError(String(error3.message||error3))}).finally(()=>{abort.signal.aborted||setIndexLoading(!1)}),()=>abort.abort()):(setIndex(null),setSelected(""),setIndexLoading(!1),()=>abort.abort())},[namespace,revision]),React.useEffect(()=>{let abort=new AbortController;return setNote({loading:!!selected,date:selected,markdown:"",error:""}),selected&&api2("daily/note",{namespace,date:selected},{signal:abort.signal}).then(data4=>{abort.signal.aborted||setNote({loading:!1,date:selected,markdown:data4.markdown,error:""})}).catch(error3=>{abort.signal.aborted||setNote({loading:!1,date:selected,markdown:"",error:String(error3.message||error3)})}),()=>abort.abort()},[namespace,selected,noteRevision]);let choose=date2=>{setSelected(date2),setOpenDay(!0)},dates=index?.dates||[],injected=index?.injectedDates||[],enabled=index?.enabled!==!1,savedInjectionDays=index?.injectionDays??3,injectionDays=daysOverride??savedInjectionDays,digests=dayDigests&&typeof dayDigests=="object"?dayDigests:{};React.useEffect(()=>{let active=!0,controller=new AbortController,wanted=dates.slice(0,14).filter(date2=>!(date2 in digests));return!wanted.length||indexError||!namespace?()=>controller.abort():(Promise.all(wanted.map(async date2=>{try{let value=await api2("daily/note",{namespace,date:date2},{signal:controller.signal});return[date2,dailyNoteDigest(value?.markdown)]}catch{return[date2,null]}})).then(entries=>{!active||controller.signal.aborted||setDayDigests(current=>{let next2={...current};for(let[date2,items]of entries)next2[date2]=items;return next2})}),()=>{active=!1,controller.abort()})},[namespace,indexError,dates.join(",")]);let stepDays=async delta=>{if(!setDailyInjectionDays||daySaving)return;let next2=Math.min(30,Math.max(1,injectionDays+delta));if(next2!==injectionDays){setDaysOverride(next2),setDaySaving(!0),setDayError("");try{await setDailyInjectionDays(next2)||(setDaysOverride(null),setDayError("\u5929\u6570\u672A\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002"))}catch(reason){setDaysOverride(null),setDayError("\u5929\u6570\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason?.message||reason))}finally{setDaySaving(!1)}}},failure=error3=>h("div",{className:"sg-daily-state error",role:"alert"},h("span",{className:"sg-daily-icon-wrap"},h(DailyIcon,{name:"alert"})),h("h3",null,"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u7B14\u8BB0"),h("p",null,"\u6587\u4EF6\u53EF\u80FD\u88AB\u5360\u7528\u6216\u6743\u9650\u4E0D\u8DB3\uFF0C\u5DF2\u6709\u7B14\u8BB0\u4E0D\u4F1A\u4E22\u5931\u3002"),h("button",{type:"button",className:"sg-daily-retry",onClick:()=>indexError?setRevision(v=>v+1):setNoteRevision(v=>v+1)},h(DailyIcon,{name:"refresh"}),"\u91CD\u65B0\u8BFB\u53D6"),h("details",null,h("summary",null,"\u9519\u8BEF\u8BE6\u60C5"),error3)),date=selected?dailyParts(selected):null,days=dates.slice(0,14),dayRows=()=>{let rows=[],cutShown=!1;return days.forEach((day,position3)=>{let parts=dailyParts(day),isInjected=enabled&&injected.includes(day),items=digests[day];enabled&&!cutShown&&!isInjected&&days.slice(0,position3).some(earlier=>injected.includes(earlier))&&(cutShown=!0,rows.push(h("div",{key:day+"-cut",className:"sg-day-cut"},h("span",null,"\u4EE5\u4E0B\u4E0D\u5E26\u5165"))));let lines=(Array.isArray(items)&&items.length?items:[{title:"\u67E5\u770B\u5F53\u5929\u7B14\u8BB0",detail:"",time:""}]).slice(0,6).map((item,key)=>h("li",{key},h("span",{className:"sg-day-t"},item.time||""),h("button",{type:"button",className:"sg-day-s",onClick:()=>choose(day),"aria-label":parts.month+"\u6708"+parts.day+"\u65E5 "+item.title+"\uFF0C\u67E5\u770B\u5F53\u5929\u7B14\u8BB0"},item.title),h("span")));rows.push(h("div",{key:day,className:"sg-day"+(isInjected?"":" out"),style:{animationDelay:position3*40+"ms"}},h("button",{type:"button",role:"tab",id:"sg-day-tab-"+day,"aria-controls":"sg-day-note","data-day":day,"aria-selected":selected===day,tabIndex:selected===day||!days.includes(selected)&&position3===0?0:-1,className:"sg-day-d",onClick:()=>choose(day),onKeyDown:event3=>{let next2=event3.key==="ArrowDown"?(position3+1)%days.length:event3.key==="ArrowUp"?(position3+days.length-1)%days.length:event3.key==="Home"?0:event3.key==="End"?days.length-1:-1;next2>=0&&(event3.preventDefault(),choose(days[next2]),event3.currentTarget.closest(".sg-days")?.querySelector('[data-day="'+days[next2]+'"]')?.focus())}},h("b",null,parts.day),h("span",null,parts.week),h("span",{className:"sg-visually-hidden"},parts.month+"\u6708 \xB7 "+dailyRelative(day,index.today))),h("div",{className:"sg-day-rail","aria-hidden":"true"}),h("ul",null,lines)))}),rows};return h("div",{className:"sg-daily"},h("div",{className:"sg-pg-head"},h("h2",null,"\u77ED\u671F\u8BB0\u5FC6"),h("span",{className:"sg-pg-tag"},h("i",{className:"sg-sw sand","aria-hidden":"true"}),enabled?"\u65B0\u4F1A\u8BDD\u5E26\u5165\u6700\u8FD1 "+injectionDays+" \u4E2A\u6709\u7B14\u8BB0\u65E5\u671F":"\u5DF2\u6682\u505C\u6CE8\u5165"),h("span",{className:"sg-pg-end"},setDailyInjectionDays?h("span",{className:"sg-stp",role:"group","aria-label":"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570"},h("button",{type:"button","aria-label":"\u51CF\u5C11\u4E00\u5929",disabled:daySaving||injectionDays<=1,onClick:()=>{stepDays(-1)}},"\u2212"),h("span",{"aria-live":"polite"},injectionDays+" \u5929"),h("button",{type:"button","aria-label":"\u589E\u52A0\u4E00\u5929",disabled:daySaving||injectionDays>=30,onClick:()=>{stepDays(1)}},"+")):null,null),dayError?h("p",{className:"sg-storage-feedback failed",role:"alert"},dayError):null,indexLoading?h(Loading):indexError?failure(indexError):h(React.Fragment,null,enabled?null:h("div",{className:"sg-daily-off"},h(DailyIcon,{name:"pause"}),"\u5DF2\u5173\u95ED\uFF0C\u4E0D\u518D\u5199\u5165\uFF0C\u4E5F\u4E0D\u4F1A\u5E26\u5165\u65B0\u4F1A\u8BDD\u3002"),dates.length?h(React.Fragment,null,h("div",{className:"sg-days",role:"tablist","aria-label":"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u7B14\u8BB0"},dayRows()),openDay?note.loading||note.date!==selected?h(Loading):note.error?failure(note.error):date?h("article",{key:selected,id:"sg-day-note",role:"tabpanel","aria-labelledby":"sg-day-tab-"+selected,className:"sg-daily-note"},h("div",{className:"sg-daily-note-date"},h("h3",null,date.month+" \u6708 "+date.day+" \u65E5"),h("span",null,date.week+" \xB7 "+dailyRelative(selected,index.today))),h("div",{className:"sg-daily-meta"},h("button",{type:"button",className:"sg-daily-back",onClick:()=>setOpenDay(!1)},"\u6536\u8D77\u7B14\u8BB0"),h("span",{className:"sg-daily-pill"+(!enabled||!injected.includes(selected)?" muted":"")},enabled?injected.includes(selected)?"\u4F1A\u5E26\u5165\u65B0\u4F1A\u8BDD":"\u4E0D\u5728\u5E26\u5165\u8303\u56F4\u5185":"\u5DF2\u6682\u505C\u6CE8\u5165"),!injected.includes(selected)&&enabled?h("button",{type:"button",className:"sg-daily-back",onClick:()=>choose(injected[0])},"\u56DE\u5230\u6700\u8FD1\u7B14\u8BB0"):null),renderDailyMarkdown(note.markdown)):null:null):h("div",{className:"sg-daily-state"},h("span",{className:"sg-daily-icon-wrap"},h(DailyIcon,{name:"notebook"})),h("h3",null,"\u8FD8\u6CA1\u6709\u7B14\u8BB0"),h("p",null,"Agent \u63A8\u8FDB\u5DE5\u4F5C\u65F6\u4F1A\u81EA\u52A8\u8BB0\u5F55\u3002")))))}function ShortTermPage({blocks,blockPage,openBlock,conversations,activeThreadId,namespace,onConversationChange,refresh,blockTurnSize=6}){let pagedBlocks=usePagedMemory({namespace,kind:"blocks",initialItems:blocks,initialPage:blockPage,fallbackLimit:40,extraParams:{threadId:activeThreadId}}),visible=[...pagedBlocks.items].sort((a,b)=>Number(a.sequence||0)-Number(b.sequence||0)||String(a.createdAt).localeCompare(String(b.createdAt))),[expandedId,setExpandedId]=React.useState(""),[detailBlockId,setDetailBlockId]=React.useState(""),[details,setDetails]=React.useState({}),[loadingId,setLoadingId]=React.useState(""),[expanding,setExpanding]=React.useState({blockId:"",level:-1}),[previewError,setPreviewError]=React.useState(null),[selectionFeedback,setSelectionFeedback]=React.useState({}),scope=namespace+"\0"+activeThreadId,activeScope=React.useRef(scope);activeScope.current=scope;let selectionRequest=React.useRef(null),currentOpen=openBlock||{turnRange:null,messages:0,status:"open"};React.useEffect(()=>{setExpandedId(""),setDetailBlockId(""),setDetails({}),setLoadingId(""),setPreviewError(null),setSelectionFeedback({})},[scope]),React.useEffect(()=>{let applied=Object.entries(selectionFeedback).filter(([,value])=>value?.status==="applied");if(!applied.length)return;let timer=window.setTimeout(()=>setSelectionFeedback(current=>{let next2={...current};for(let[id2,value]of applied)next2[id2]===value&&delete next2[id2];return next2}),4e3);return()=>window.clearTimeout(timer)},[selectionFeedback]);let toggleBlock=block=>{if(expandedId===block.id){setExpandedId("");return}setExpandedId(block.id),setPreviewError(null),!details[block.id]&&(setLoadingId(block.id),api2("sources",{namespace,blockId:block.id}).then(value=>{activeScope.current===scope&&setDetails(current=>({...current,[block.id]:value}))}).catch(()=>{activeScope.current===scope&&setPreviewError({scope,blockId:block.id,message:"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u9884\u89C8\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u6253\u5F00\u3002"})}).finally(()=>{activeScope.current===scope&&setLoadingId(current=>current===block.id?"":current)}))},expandTo=async(block,level)=>{if(selectionRequest.current?.scope===scope)return;let request={scope,blockId:block.id,level};selectionRequest.current=request;let isCurrent=()=>activeScope.current===scope&&selectionRequest.current===request;setSelectionFeedback(current=>({...current,[block.id]:null})),setExpanding(request);let result;try{result=await api2("blocks/expand",{namespace,blockId:block.id,level:"L"+level},{method:"PATCH"})}catch(reason){let rejected=reason?.code==="BLOCK_SELECTION_REJECTED"||[400,403,404,409].includes(reason?.status);isCurrent()&&setSelectionFeedback(current=>({...current,[block.id]:{scope,level,status:rejected?"blocked":"pending",uncertain:!rejected,message:rejected?/[\u4e00-\u9fff]/.test(reason?.message||"")?reason.message.replace("\uFF08blocks/expand\uFF09",""):"\u8FD9\u6B21\u9009\u62E9\u672A\u80FD\u5E94\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002":"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u5E94\u7528\u7ED3\u679C\uFF0C\u8BF7\u5237\u65B0\u540E\u67E5\u770B\u3002"}}))}if(isCurrent())try{await refresh(),isCurrent()&&pagedBlocks.page.offset>0&&await pagedBlocks.loadOffset(pagedBlocks.page.offset),result&&isCurrent()&&setSelectionFeedback(current=>({...current,[block.id]:result.surfaceSync?.status==="applied"?{scope,level,status:"applied",message:"\u5DF2\u5E94\u7528 L"+level+"\uFF0C\u4F9B\u52A9\u624B\u540E\u7EED\u56DE\u590D\u53C2\u8003\u3002"}:null}))}catch{isCurrent()&&setSelectionFeedback(current=>({...current,[block.id]:{scope,level,status:"pending",uncertain:!0,message:"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u5E94\u7528\u7ED3\u679C\uFF0C\u8BF7\u5237\u65B0\u540E\u67E5\u770B\u3002"}}))}selectionRequest.current===request&&(selectionRequest.current=null,setExpanding({blockId:"",level:-1}))},selectedBlock=visible.find(block=>block.id===expandedId)||visible[visible.length-1]||null,levelOf=block=>{let level=visibleBlockLevel(block);return level===null?0:Math.min(5,Math.max(0,level))},openCapacity=Math.max(1,Number(currentOpen.capacity||blockTurnSize||6)),openUsed=Math.min(openCapacity,Math.max(0,Number(currentOpen.turns||0))),remainingDots=Math.max(1,openCapacity-openUsed),firstTurn=visible.length?visible[0].turnRange?.[0]:null,lastTurn=visible.length?visible[visible.length-1].turnRange?.[1]:null,turnSpan=Number.isInteger(firstTurn)&&Number.isInteger(lastTurn)?" \xB7 \u7B2C "+firstTurn+"\u2013"+lastTurn+" \u8F6E":"",narrow=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 680px)").matches===!0:!1,detailBlock=narrow&&detailBlockId?visible.find(block=>block.id===detailBlockId):null;return detailBlock?h("div",{className:"sg-ss-detail-page"},h(BackBar,{label:"\u4F1A\u8BDD\u8BB0\u5FC6",onBack:()=>setDetailBlockId("")}),h(ShortTermMemoryBlockDetail,{key:namespace+":"+detailBlock.id,namespace,block:detailBlock})):h(React.Fragment,null,h("div",{className:"sg-pg-head"},h("h2",null,"\u4F1A\u8BDD\u8BB0\u5FC6"),h("span",{className:"sg-pg-tag"},h("i",{className:"sg-sw water","aria-hidden":"true"}),pagedBlocks.page.total+" \u5757"+turnSpan),conversations.length?h("span",{className:"sg-pg-end"},h("label",{className:"sg-conversation"},h("span",null,"\u5F53\u524D\u5BF9\u8BDD\uFF1A"),h("select",{value:activeThreadId||"",onChange:event3=>onConversationChange(event3.target.value),"aria-label":"\u5F53\u524D\u5BF9\u8BDD"},conversations.map(conversation=>h("option",{key:conversation.id,value:conversation.id},conversation.label))))):null),h("section",{className:"sg-block-list sg-ss-list","aria-label":"Block \u5217\u8868"},h("section",{className:"sg-visually-hidden","aria-labelledby":"sg-decay-title"},h("h2",{id:"sg-decay-title"},"\u5757\u8870\u51CF\u603B\u89C8"),h("div",{className:"sg-distribution","aria-label":"Block \u5F53\u524D\u5C42\u7EA7\u5206\u5E03"},visible.map(block=>h("span",{key:block.id,className:"sg-level-chip","data-level":visibleBlockLevel(block)===null?void 0:String(block.currentLevel),title:"Block #"+block.sequence},visibleBlockLevel(block)===null?"\u5C1A\u672A\u786E\u8BA4":"L"+block.currentLevel)),h("span",{className:"sg-level-chip sg-open-chip"},"\u5F00\u653E\u5757 \xB7 \u672A\u5C01\u5B58")),h("input",{className:"sg-distribution-rail",type:"range",min:"0",max:"0",step:"1",value:"0",disabled:!0,readOnly:!0,"aria-label":"Block \u5206\u5E03\u6ED1\u8F68"})),h("div",{className:"sg-block-header sg-visually-hidden","aria-hidden":"true"},h("span",null,"\u52A9\u624B\u53EF\u89C1\u5C42\u7EA7"),h("span",null,"Block"),h("span",null,"\u8986\u76D6 Turn"),h("span",null,"\u8DDD\u6700\u65B0\u5C01\u5B58\u5757"),h("span")),h("div",{className:"sg-ss-scale"},h("span",null,"\u66F4\u65E9"),h("span",{className:"sg-r","aria-hidden":"true"},[0,1,2,3,4,5].map(level=>h("i",{key:level,style:{height:5+level*3+"px",opacity:.3+level*.14}}))),h("span",null,"\u6700\u8FD1"),h("span",null,"\u8D8A\u65E9\u7684\u5BF9\u8BDD\u538B\u5F97\u8D8A\u8584")),h("div",{className:"sg-ss"},h("div",{className:"sg-ss-main"},visible.map(block=>h("div",{key:block.id,className:"sg-block-unit"},h("button",{className:"sg-block-toggle",type:"button",onClick:()=>narrow?setDetailBlockId(block.id):toggleBlock(block),"aria-expanded":narrow?void 0:expandedId===block.id?"true":"false","aria-label":"\u8BB0\u5FC6\u5757 "+block.sequence+"\uFF0C"+turnRangeText(block.turnRange)+(narrow?"\uFF0C\u6253\u5F00\u8BE6\u60C5":"")},h("span",{className:"sg-ss-num"},String(block.sequence)),h("span",{className:"sg-ss-bar",style:{height:20+levelOf(block)*5+"px",background:"color-mix(in srgb, var(--sg-water) "+(14+levelOf(block)*14)+"%, var(--sg-page))"}},h("span",null,block.title||(block.virtual?"\u65E7 Block #":"Block #")+block.sequence)),h("span",{className:"sg-ss-use"}),h("span",{className:"sg-block-turn"},turnRangeText(block.turnRange)),h("span",{className:"sg-block-distance"},block.distanceFromLatest===0?"0\uFF08\u6700\u65B0\uFF09":block.distanceFromLatest+" \u4E2A Block"),null),h(BlockSelectionFeedback,{block,feedback:selectionFeedback[block.id]?.scope===scope?selectionFeedback[block.id]:null,onRefresh:async()=>{try{if(await refresh(),activeScope.current!==scope)return;pagedBlocks.page.offset>0&&await pagedBlocks.loadOffset(pagedBlocks.page.offset),activeScope.current===scope&&setSelectionFeedback(current=>({...current,[block.id]:null}))}catch{}}}),previewError?.scope===scope&&previewError.blockId===block.id?h("div",{role:"alert",className:"sg-selection-feedback error"},previewError.message):null,summaryUnavailable(block)?h(SummaryUnavailable,{key:namespace+":"+block.id,namespace,block}):null,expandedId===block.id?h("div",{className:"sg-block-expanded"},h(BlockLayerPanel,{block,detail:details[block.id],loading:loadingId===block.id,selectionBusy:expanding.scope===scope&&expanding.level>=0,expandingLevel:expanding.scope===scope&&expanding.blockId===block.id?expanding.level:-1,onExpand:level=>expandTo(block,level)})):null)),h("div",{className:"sg-block-unit"},h("div",{className:"sg-ss-open"},h("span",{className:"sg-ss-num"},"\xB7"),h("div",{className:"sg-ss-bar"},h("span",null,"\u6B63\u5728\u8BB0\u5F55"),h("span",{className:"sg-ss-dots",role:"img","aria-label":"\u8FD8\u5DEE "+remainingDots+" \u8F6E\u5C01\u5B58","aria-hidden":void 0},Array.from({length:remainingDots},(_,index)=>h("i",{key:index,className:index<Math.min(remainingDots,Math.max(0,openCapacity-openUsed))?"":"o"})))),h("span")))),selectedBlock?h("aside",{className:"sg-ss-side","aria-label":"\u9009\u4E2D\u8BB0\u5FC6\u5757\u8BE6\u60C5"},h("h3",null,selectedBlock.title||"Block #"+selectedBlock.sequence),h("span",{className:"sg-k"},"\u8BB0\u5FC6\u5757 "+selectedBlock.sequence+" \xB7 "+turnRangeText(selectedBlock.turnRange)),h("div",{className:"sg-lvl","aria-hidden":"true"},[0,1,2,3,4,5].map(level=>h("i",{key:level,className:level<=levelOf(selectedBlock)?"on":""}))),h("div",{className:"sg-lvl-l"},h("span",null,"\u53EA\u7559\u6807\u9898"),h("span",null,"\u539F\u6587")),h("p",null,selectedBlock.summary||(selectedBlock.keypoints||[]).join("\uFF1B")||"\u8FD9\u4E00\u5757\u6682\u65F6\u6CA1\u6709\u6458\u8981\u3002"),h("button",{type:"button",className:"sg-btn",onClick:()=>toggleBlock(selectedBlock)},expandedId===selectedBlock.id?"\u6536\u8D77\u8BE6\u60C5":"\u770B\u539F\u6587")):null)),h(Pagination,{page:pagedBlocks.page,loading:pagedBlocks.loading,error:pagedBlocks.error,onOffset:pagedBlocks.loadOffset}))}function SourceDetails({item,source,kind}){let messages=source?.messages||[];return h("div",{className:"sg-detail-section"},h("h3",{className:"sg-section-title"},"\u6765\u6E90"),h("div",{className:"sg-source-label"},h("span",{className:"sg-source-icon","aria-hidden":"true"},"\u25A3"),h("span",null,"\u5F53\u524D DeepSeek \u5BF9\u8BDD")),h("details",{className:"sg-tech"},h("summary",null,"\u6280\u672F\u8BE6\u60C5"),h("div",{className:"sg-tech-body"},h("div",{className:"sg-tech-row"},h("span",{className:"sg-muted"},kind==="block"?"Block ID":"Event ID"),h("span",{className:"sg-code"},item.id)),kind==="block"&&item.turnRange?h("div",{className:"sg-tech-row"},h("span",{className:"sg-muted"},"Turn"),h("span",null,item.turnRange.join(" - "))):null,messages.length?messages.map(message=>h("div",{key:message.id,className:"sg-raw-message"},h("div",{className:"sg-muted"},String(message.role||"")+" \xB7 "+formatTime(message.createdAt)),h("div",{className:"sg-code"},String(message.content||"")))):h("div",{className:"sg-muted"},"\u5F53\u524D\u6570\u636E\u4E2D\u6CA1\u6709\u53EF\u663E\u793A\u7684\u6765\u6E90\u6D88\u606F\u3002"))))}function EventDetail({event:event3,project,source,onBack,backLabel,onNode}){let detailedEvent=source?.events?.find(item=>item.id===event3.id)||event3;return h(InfoPopoverGroup,null,h(BackBar,{label:backLabel,onBack}),h("header",{className:"sg-detail-header sg-event-page-header"},h("span",{className:"sg-event-detail-kicker"},"Event"),h("h2",{className:"sg-detail-title"},detailedEvent.title||"\u8BB0\u5FC6\u8BE6\u60C5"),h(EventMetadata,{event:detailedEvent,nodes:source?.relatedNodes||[],onNode})),h(EventMemoryDetails,{event:detailedEvent,sourceMessages:source?.messages||[]}))}function ElementDetail({element:element3,events,source,openEvent,onBack,backLabel}){let facts=[];element3.currentState&&facts.push(element3.currentState);for(let fact of element3.facts||[]){let value=Array.isArray(fact.value)?fact.value.join("\u3001"):fact.value;value&&!facts.includes(String(value))&&facts.push(String(value))}let related=events.filter(event3=>(element3.sourceEventIds||[]).includes(event3.id)).sort((a,b)=>String(b.updatedAt).localeCompare(String(a.updatedAt)));return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("header",{className:"sg-detail-header"},h("h2",{className:"sg-detail-title"},element3.name||"\u76F8\u5173\u4E8B\u7269"),h("p",{className:"sg-detail-subtitle"},"AI \u5173\u4E8E\u5B83\u76EE\u524D\u77E5\u9053\u8FD9\u4E9B"),h("div",{className:"sg-meta"},h("span",null,"\u76F8\u5173\u7ECF\u5386 "+related.length+" \u6761"),h("span",{className:"sg-meta-sep"},"\u6700\u8FD1\u66F4\u65B0 "+formatTime(element3.updatedAt)))),h("div",{className:"sg-detail-section"},facts.length?h("ul",{className:"sg-facts"},facts.map((fact,index)=>h("li",{key:index},fact))):h("div",{className:"sg-muted"},"\u6682\u65F6\u6CA1\u6709\u5F62\u6210\u53EF\u5C55\u793A\u7684\u8BA4\u8BC6\u3002")),h("div",{className:"sg-detail-section"},h("h3",{className:"sg-section-title"},"\u76F8\u5173\u7ECF\u5386"),related.length?h("div",{className:"sg-related-list"},related.map(event3=>h("button",{key:event3.id,className:"sg-related",onClick:()=>openEvent(event3)},h("span",{className:"sg-related-name"},event3.title),h("span",{className:"sg-related-time"},formatTime(event3.updatedAt||event3.createdAt))))):h("div",{className:"sg-muted"},"\u6CA1\u6709\u5173\u8054\u7ECF\u5386\u3002")),h(SourceDetails,{item:element3,source,kind:"element"}))}function processingFingerprint(overview){return JSON.stringify({failedJobs:Number(overview?.failedJobs||0),duplicateRepair:overview?.duplicateRepair??null,processingJobs:Number(overview?.processingJobs||0),failures:(overview?.failedJobDetails||[]).map(({kind,id:id2,attempts,updatedAt,lastError})=>({kind,id:id2,attempts,updatedAt,lastError})),processing:(overview?.processingJobDetails||[]).map(({kind,id:id2,status,attempts,updatedAt})=>({kind,id:id2,status,attempts,updatedAt}))})}function ProcessingStatus({overview,blocks,conversations,namespace,serverVersion,onBack,backLabel="\u8FD4\u56DE",refresh}){let failures=overview.failedJobDetails||[],failedKeys=new Set(failures.map(statusJobKey)),terminalFailedKeys=new Set(failures.filter(job=>job.state==="terminal-failed"||!job.state&&!job.nextRetryAt).map(statusJobKey)),hasProcessingDetails=Array.isArray(overview.processingJobDetails),rawProcessingCount=activeProcessingCount(overview),jobsByKey=new Map((overview.processingJobDetails||[]).map(job=>[statusJobKey(job),job]));for(let job of failures)jobsByKey.set(statusJobKey(job),job);let[refreshing,setRefreshing]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),[retrying,setRetrying]=React.useState(""),retryRequest=React.useRef(!1),[retryErrors,setRetryErrors]=React.useState({}),blockById=new Map(blocks.map(block=>[block.id,block])),conversationById=new Map((conversations||[]).map(conversation=>[conversation.id,conversation]));if(!hasProcessingDetails&&rawProcessingCount>0){let addLegacyJob=(block,kind,status,details={})=>{let job={id:"legacy:"+block.id+":"+kind,kind,status,attempts:details.attempts??0,nextRetryAt:details.nextRetryAt??null,updatedAt:details.updatedAt||block.createdAt,legacy:!0,blockIds:[block.id],blockDetails:[{id:block.id,sourceId:block.sourceId||block.id,sequence:block.sequence||block.blockIndex,title:block.title||block.l0Title,threadId:block.threadId,turnRange:block.turnRange,shouldExtract:block.shouldExtract}]};jobsByKey.set(statusJobKey(job),job)};for(let block of blocks){if(!(block.status==="processing"||block.processingStatus==="pending"))continue;let found=!1;(["pending","running"].includes(block.summaryJob?.status)||block.processingStatus==="pending")&&(addLegacyJob(block,"block-summary",block.summaryJob?.status||"pending",block.summaryJob),found=!0),block.eventExtraction?.status==="running"&&(addLegacyJob(block,"event-extraction","running",block.eventExtraction),found=!0),["pending","running"].includes(block.graphProjection?.status)&&(addLegacyJob(block,"graph-projection",block.graphProjection.status,block.graphProjection),found=!0),found||addLegacyJob(block,"event-extraction","running")}}let taskLabel=kind=>kind==="block-summary"?"\u4F1A\u8BDD\u8BB0\u5FC6\u538B\u7F29":kind==="event-extraction"?"\u957F\u671F\u8BB0\u5FC6\u63D0\u53D6":kind==="topic-projection"?"\u4E3B\u9898\u6574\u7406":"\u77E5\u8BC6\u56FE\u8C31\u66F4\u65B0",retryKey=statusJobKey,technicalStatusText=(status,job)=>job?.state==="terminal-failed"?"\u7EC8\u6001\u5931\u8D25":job?.state==="retryable"?"\u8BA1\u5212\u81EA\u52A8\u91CD\u8BD5":status==="running"?"\u8FD0\u884C\u4E2D":status==="pending"?"\u6392\u961F\u4E2D":status==="failed"?"\u5931\u8D25":status==="succeeded"||status==="completed"?"\u5DF2\u5B8C\u6210":String(status||"\u672A\u77E5"),workItems=new Map;for(let job of jobsByKey.values()){let details=Array.isArray(job.blockDetails)?job.blockDetails:[];details.length||(details=(Array.isArray(job.blockIds)&&job.blockIds.length?job.blockIds:job.id&&!["graph-projection","topic-projection"].includes(job.kind)?[job.id]:[]).map(id2=>blockById.get(id2)).filter(Boolean).map(block=>({id:block.id,sourceId:block.id,sequence:block.sequence,title:block.title||block.l0Title,threadId:block.threadId,turnRange:block.turnRange,shouldExtract:block.shouldExtract,rawAvailable:block.rawAvailable}))),details.length||(details=[{id:statusJobKey(job),sourceId:"",sequence:null,title:"",threadId:job.threadId||"",turnRange:job.turnRange,shouldExtract:null}]);for(let detail of details){let key=String(detail.threadId||"")+":"+String(detail.id||detail.sourceId||statusJobKey(job)),item=workItems.get(key)||{...detail,jobs:[]};item.jobs.some(candidate=>statusJobKey(candidate)===statusJobKey(job))||item.jobs.push(job),workItems.set(key,item)}}let items=[...workItems.values()].sort((left,right)=>{let threadOrder=String(left.threadId||"").localeCompare(String(right.threadId||""));return threadOrder||Number(left.turnRange?.[0]||left.sequence||0)-Number(right.turnRange?.[0]||right.sequence||0)}),itemState=item=>item.jobs.some(job=>terminalFailedKeys.has(statusJobKey(job)))?{kind:"failed",label:"\u7EC8\u6001\u5931\u8D25\uFF0C\u53EF\u91CD\u8BD5",mark:"!"}:item.jobs.some(job=>job.status==="running")?{kind:"processing",label:"\u6B63\u5728\u6574\u7406",mark:"\u25CF"}:item.jobs.some(job=>job.state==="retryable"||failedKeys.has(statusJobKey(job))&&job.nextRetryAt)?{kind:"processing",label:"\u8BA1\u5212\u81EA\u52A8\u91CD\u8BD5",mark:"\u21BB"}:{kind:"waiting",label:"\u7B49\u5F85\u6574\u7406",mark:"\u25CB"},itemStages=item=>{let summaryJob=item.jobs.find(job=>job.kind==="block-summary"),extractionJobs=item.jobs.filter(job=>job.kind==="event-extraction"),graphJobs=item.jobs.filter(job=>job.kind==="graph-projection"),topicJobs=item.jobs.filter(job=>job.kind==="topic-projection"),summaryFailed=summaryJob&&terminalFailedKeys.has(statusJobKey(summaryJob)),extractionFailed=extractionJobs.some(job=>terminalFailedKeys.has(statusJobKey(job))),graphFailed=graphJobs.some(job=>terminalFailedKeys.has(statusJobKey(job))),shortStage=summaryFailed?{kind:"failed",mark:"!",label:"\u7EC8\u6001\u5931\u8D25\uFF0C\u53EF\u91CD\u8BD5"}:summaryJob?.status==="running"?{kind:"processing",mark:"\u25CF",label:"\u5904\u7406\u4E2D"}:summaryJob?.state==="retryable"?{kind:"processing",mark:"\u21BB",label:"\u8BA1\u5212\u81EA\u52A8\u91CD\u8BD5"}:summaryJob?{kind:"waiting",mark:"\u25CB",label:"\u6392\u961F\u4E2D"}:{kind:"done",mark:"\u2713",label:"\u5DF2\u5B8C\u6210"},stageForJobs=(jobs,failed,emptyLabel,failedLabel="\u7EC8\u6001\u5931\u8D25\uFF0C\u53EF\u91CD\u8BD5")=>failed?{kind:"failed",mark:"!",label:failedLabel}:jobs.some(job=>job.status==="running")?{kind:"processing",mark:"\u25CF",label:"\u5904\u7406\u4E2D"}:jobs.some(job=>job.state==="retryable")?{kind:"processing",mark:"\u21BB",label:"\u8BA1\u5212\u81EA\u52A8\u91CD\u8BD5"}:jobs.length?{kind:"waiting",mark:"\u25CB",label:"\u6392\u961F\u4E2D"}:{kind:"waiting",mark:"\u25CB",label:emptyLabel};if(topicJobs.length===item.jobs.length)return[["\u4E3B\u9898\u6574\u7406",stageForJobs(topicJobs,topicJobs.some(job=>terminalFailedKeys.has(statusJobKey(job))),"\u7B49\u5F85\u6574\u7406")]];let extractionStage=extractionFailed?stageForJobs(extractionJobs,!0,"\u7B49\u5F85\u63D0\u53D6"):extractionJobs.length?stageForJobs(extractionJobs,!1,"\u7B49\u5F85\u63D0\u53D6"):graphJobs.length?{kind:"done",mark:"\u2713",label:"\u5DF2\u5B8C\u6210"}:shortStage.kind!=="done"?{kind:"waiting",mark:"\u25CB",label:"\u7B49\u5F85\u77ED\u671F\u6458\u8981"}:item.shouldExtract===!1?{kind:"skipped",mark:"\u2013",label:"\u65E0\u9700\u63D0\u53D6"}:{kind:"waiting",mark:"\u25CB",label:"\u7B49\u5F85\u63D0\u53D6"},graphStage=graphFailed?stageForJobs(graphJobs,!0,"\u7B49\u5F85\u56FE\u8C31\u66F4\u65B0","\u66F4\u65B0\u5931\u8D25\uFF0C\u53EF\u91CD\u8BD5"):graphJobs.length?stageForJobs(graphJobs,!1,"\u7B49\u5F85\u56FE\u8C31\u66F4\u65B0"):extractionStage.kind==="failed"||extractionStage.kind==="waiting"||extractionStage.kind==="processing"?{kind:"waiting",mark:"\u25CB",label:"\u7B49\u5F85\u957F\u671F\u8BB0\u5FC6\u63D0\u53D6"}:{kind:"waiting",mark:"\u25CB",label:"\u7B49\u5F85\u56FE\u8C31\u66F4\u65B0"};return[["\u539F\u59CB\u5BF9\u8BDD",item.rawAvailable===!0?{kind:"done",mark:"\u2713",label:"\u5F53\u524D\u53EF\u8BFB\u53D6"}:{kind:"waiting",mark:"\u25CB",label:item.rawAvailable===!1?"\u5F53\u524D\u65E0\u53EF\u8BFB\u53D6\u539F\u6587":"\u65E0\u6CD5\u786E\u8BA4\u662F\u5426\u53EF\u8BFB\u53D6"}],["\u538B\u7F29\u4F1A\u8BDD\u8BB0\u5FC6",shortStage],["\u63D0\u53D6\u957F\u671F\u8BB0\u5FC6",extractionStage],["\u66F4\u65B0\u77E5\u8BC6\u56FE\u8C31",graphStage]]},conversationLabel=threadId=>threadId==="__legacy__"?"\u5386\u53F2\u5BF9\u8BDD":conversationById.get(threadId)?.label||(threadId?"\u5BF9\u8BDD "+String(threadId).slice(0,8):"\u5386\u53F2\u6216\u672A\u77E5\u5BF9\u8BDD"),groups=[];for(let item of items){let key=item.threadId||"__unknown__",group2=groups.find(candidate=>candidate.key===key);group2||(group2={key,label:conversationLabel(item.threadId),items:[]},groups.push(group2)),group2.items.push(item)}let checkStatus=()=>{let before=processingFingerprint(overview);return setRefreshing(!0),setFeedback({kind:"",text:"\u6B63\u5728\u8BFB\u53D6\u2026"}),refresh({propagateError:!0}).then(next2=>{let selected=next2?.overview?.namespaces?.find(item=>item.namespace===namespace),changed=selected&&processingFingerprint(selected)!==before;setFeedback({kind:"done",text:changed?"\u72B6\u6001\u5DF2\u66F4\u65B0":"\u72B6\u6001\u6CA1\u6709\u53D8\u5316"})}).catch(reason=>{setFeedback({kind:"failed",text:"\u8BFB\u53D6\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}).finally(()=>setRefreshing(!1))},retryJob=job=>{if(retryRequest.current)return;retryRequest.current=!0;let key=retryKey(job);return setRetrying(key),setRetryErrors(current=>({...current,[key]:""})),setFeedback({kind:"",text:taskLabel(job.kind)+" \u6B63\u5728\u5904\u7406\u2026"}),api2("jobs/retry",{namespace,kind:job.kind,jobId:job.id},{method:"POST"}).then(()=>refresh({propagateError:!0})).then(()=>setFeedback({kind:"done",text:job.kind==="topic-projection"?"\u5DF2\u91CD\u65B0\u6392\u961F\uFF0C\u6309\u5386\u53F2\u989D\u5EA6\u7EE7\u7EED\u6574\u7406":"\u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u72B6\u6001\u5DF2\u66F4\u65B0"})).catch(async reason=>{let message=String(reason?.message||reason);setRetryErrors(current=>({...current,[key]:message})),setFeedback({kind:"failed",text:"\u91CD\u8BD5\u5931\u8D25\uFF1A"+message});try{await refresh({propagateError:!0})}catch{}}).finally(()=>{retryRequest.current=!1,setRetrying("")})},failedItems=items.filter(item=>item.jobs.some(job=>terminalFailedKeys.has(statusJobKey(job)))).length,activeItems=Math.max(0,items.length-failedItems),unresolvedProcessingCount=hasProcessingDetails?0:Math.max(0,rawProcessingCount-activeItems),detailsUnavailable=!hasProcessingDetails&&rawProcessingCount>0,versionMismatch=!!(serverVersion&&serverVersion!==STRATAGATE_CLIENT_VERSION),summary=items.length?groups.length+" \u4E2A\u4F1A\u8BDD \xB7 "+(activeItems?activeItems+" \u4E2A\u6B63\u5728\u6574\u7406":"")+(activeItems&&failedItems?" \xB7 ":"")+(failedItems?failedItems+" \u4E2A\u9700\u8981\u91CD\u8BD5":"")+(unresolvedProcessingCount?" \xB7 \u53E6\u6709 "+unresolvedProcessingCount+" \u4E2A\u8BE6\u60C5\u6682\u4E0D\u53EF\u7528":""):detailsUnavailable?"\u4ECD\u6709 "+rawProcessingCount+" \u4E2A\u540E\u53F0\u4EFB\u52A1\u6B63\u5728\u6574\u7406":hasProcessingDetails?"\u5F53\u524D\u6CA1\u6709\u5F85\u5904\u7406\u6216\u5931\u8D25\u7684\u4EFB\u52A1":"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u540E\u53F0\u4EFB\u52A1\u72B6\u6001";return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u540E\u53F0\u4EFB\u52A1"),h("p",null,summary)),h("div",{className:"sg-process-summary"},h("strong",null,"\u540E\u53F0\u6574\u7406\u72B6\u6001"),h("span",null,"\u5DF2\u6709\u8BB0\u5FC6\u53EF\u7EE7\u7EED\u67E5\u770B\uFF1B\u5177\u4F53\u6765\u6E90\u4EE5\u5B9E\u9645\u53EF\u8BFB\u53D6\u5185\u5BB9\u4E3A\u51C6\u3002")),detailsUnavailable?h("div",{className:"sg-process-notice",role:"status"},h("strong",null,versionMismatch?"\u524D\u540E\u7AEF\u7248\u672C\u5C1A\u672A\u540C\u6B65":"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u5B8C\u6574\u4EFB\u52A1\u8BE6\u60C5"),h("span",null,versionMismatch?"\u5F53\u524D\u9875\u9762\u4E3A "+STRATAGATE_CLIENT_VERSION+"\uFF0C\u540E\u53F0\u4E3A "+serverVersion+"\u3002\u8BF7\u786E\u8BA4\u5B89\u88C5\u65B0\u5305\u540E\u5B8C\u5168\u9000\u51FA\u5E76\u91CD\u65B0\u542F\u52A8 DSH\u3002":"\u540E\u53F0\u53EA\u8FD4\u56DE\u4E86\u4EFB\u52A1\u6570\u91CF\uFF0C\u6CA1\u6709\u8FD4\u56DE\u4F1A\u8BDD\u548C\u8F6E\u6B21\u3002\u8BF7\u5B8C\u5168\u9000\u51FA\u5E76\u91CD\u65B0\u542F\u52A8 DSH \u540E\u518D\u68C0\u67E5\u3002")):null,groups.length?h("div",{className:"sg-process-groups"},groups.map(group2=>h("section",{key:group2.key,className:"sg-process-group"},h("header",{className:"sg-process-group-head"},h("h3",{className:"sg-process-group-title"},group2.label),h("span",{className:"sg-process-group-count"},group2.items.length+" \u4E2A\u5BF9\u8BDD\u7247\u6BB5")),group2.items.map(item=>{let state=itemState(item),range=Array.isArray(item.turnRange)?"\u7B2C "+item.turnRange[0]+"\u2013"+item.turnRange[1]+" \u8F6E":item.title||"\u5BF9\u8BDD\u7247\u6BB5",technicalJobs=item.jobs.filter(job=>!job.legacy);return h("article",{key:String(item.id||item.sourceId),className:"sg-process-card"},h("div",{className:"sg-process-card-head"},h("span",{className:"sg-process-range"},range),h("span",{className:"sg-process-state "+state.kind},h("span",{"aria-hidden":"true"},state.mark),state.label)),h("div",{className:"sg-process-stages"},itemStages(item).map(([name,stage])=>h("div",{key:name,className:"sg-process-stage"},h("span",{className:"sg-process-stage-state "+stage.kind,"aria-hidden":"true"},stage.mark),h("span",{className:"sg-process-stage-name"},name),h("span",{className:"sg-process-stage-state "+stage.kind},stage.label)))),technicalJobs.length?h("details",{className:"sg-process-tech"},h("summary",null,"\u67E5\u770B\u6280\u672F\u8BE6\u60C5"),technicalJobs.map(job=>{let key=retryKey(job),failed=terminalFailedKeys.has(key),busy=retrying===key;return h("div",{key,className:"sg-process-job"},h("div",{className:"sg-process-job-head"},h("strong",null,taskLabel(job.kind)),h("span",{className:"sg-stage-value "+(terminalFailedKeys.has(key)?"failed":job.status==="running"||job.state==="retryable"?"processing":"waiting")},technicalStatusText(job.status,job))),h("div",{className:"sg-process-job-meta sg-code"},"\u4EFB\u52A1 "+job.id+" \xB7 \u5DF2\u5C1D\u8BD5 "+String(job.attempts??0)+" \u6B21 \xB7 \u66F4\u65B0\u4E8E "+formatTime(job.updatedAt)),job.nextRetryAt?h("div",{className:"sg-process-job-meta"},"\u8BA1\u5212\u91CD\u8BD5\uFF1A"+formatTime(job.nextRetryAt)):null,failed&&!job.nextRetryAt?h("div",{className:"sg-process-job-meta"},"\u81EA\u52A8\u91CD\u8BD5\u5DF2\u505C\u6B62"):null,failed?h("pre",{className:"sg-job-error sg-code"},job.lastErrorFull||job.lastError||"\u6CA1\u6709\u8BB0\u5F55\u6280\u672F\u9519\u8BEF\u3002"):null,job.kind==="topic-projection"&&job.diagnostics?h("pre",{className:"sg-code"},JSON.stringify(job.diagnostics,null,2)):null,job.kind==="topic-projection"&&overview.topicDirectoryReadError?h("p",{className:"sg-muted"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55\u72B6\u6001\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u72B6\u6001\u3002"):null,failed?h("div",{className:"sg-process-job-actions"},h("span",{className:"sg-status-feedback failed",role:retryErrors[key]?"alert":void 0},retryErrors[key]||""),job.kind==="topic-projection"?h(TopicRetryButton,{failure:{jobId:job.id,eventCount:job.eventCount},namespace,revision:overview.topicDirectoryRevision,onDirectoryChanged:()=>refresh({propagateError:!0})}):h("button",{type:"button",className:"sg-save-button",disabled:!!retrying,onClick:()=>{retryJob(job)}},busy?"\u6B63\u5728\u5904\u7406\u2026":"\u91CD\u8BD5\u6B64\u4EFB\u52A1")):null)})):null)})))):detailsUnavailable?h("div",{className:"sg-process-unavailable"},h("strong",null,"\u4EFB\u52A1\u4ECD\u5728\u6574\u7406\uFF0C\u5177\u4F53\u4F1A\u8BDD\u6682\u4E0D\u53EF\u7528"),h("span",null,"\u8FD9\u4E0D\u4EE3\u8868\u5BF9\u8BDD\u4E22\u5931\uFF1B\u91CD\u542F\u5E76\u52A0\u8F7D\u540C\u4E00\u7248\u672C\u540E\u5373\u53EF\u663E\u793A\u8BE6\u60C5\u3002")):h(Empty,{title:hasProcessingDetails?"\u5F53\u524D\u6CA1\u6709\u5F85\u5904\u7406\u6216\u5931\u8D25\u7684\u4EFB\u52A1":"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u4EFB\u52A1\u8BE6\u60C5",copy:"\u76EE\u5F55\u4E0E\u56FE\u8C31\u7684\u8986\u76D6\u60C5\u51B5\u8BF7\u4EE5\u5BF9\u5E94\u9875\u9762\u4E3A\u51C6\u3002"}),h("div",{className:"sg-process-footer"},h("button",{type:"button",className:"sg-quiet-button",disabled:refreshing,onClick:()=>{checkStatus()}},refreshing?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u21BB \u91CD\u65B0\u68C0\u67E5\u72B6\u6001"),h("span",{className:"sg-muted"},"\u53EA\u8BFB\u53D6\u6700\u65B0\u72B6\u6001\uFF0C\u4E0D\u4F1A\u89E6\u53D1\u6A21\u578B\u8C03\u7528\u3002"),feedback.text?h("span",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null))}let profilePageMemory=new Map,profileFieldDrafts=new Map,importDrafts=new Map,importRequests=new Map;function usePageMemoryState(cache3,key,initial){cache3.has(key)||cache3.set(key,initial);let[value,setValue]=React.useState(cache3.get(key));return[value,next2=>{let resolved=typeof next2=="function"?next2(cache3.get(key)):next2;cache3.set(key,resolved),setValue(resolved)}]}function ImportPage({namespace,onBack,refresh}){let[draft,setDraft]=usePageMemoryState(importDrafts,namespace,{text:""}),text=draft.text,setText=value=>setDraft({text:value}),[prompt,setPrompt]=React.useState(""),[promptLoading,setPromptLoading]=React.useState(!0),[copied,setCopied]=React.useState(!1),[busy,setBusy]=React.useState(!1),[job,setJob]=React.useState(null),[choices,setChoices]=React.useState({}),[result,setResult]=React.useState(null),[error3,setError]=React.useState(""),[connectionError,setConnectionError]=React.useState(""),[restoring,setRestoring]=React.useState(!0),lifecycle=React.useRef(null);React.useEffect(()=>{let active=!0,restoreTimer,controller=new AbortController;lifecycle.current=controller,api2("import",{},{signal:controller.signal}).then(value=>{active&&setPrompt(String(value.prompt||""))}).catch(reason=>{active&&setError(String(reason?.message||reason))}).finally(()=>{active&&setPromptLoading(!1)});let restore=async()=>{if(await importRequests.get(namespace)?.catch(()=>{}),!!active)return api2("import",{operation:"status",namespace},{signal:controller.signal}).then(value=>{active&&(setConnectionError(""),setRestoring(!1),value?.jobId&&!["undone","abandoned"].includes(value.status)&&(setJob(value),value.status==="committed"&&(setResult(value),clearCommittedDraft(value))))}).catch(()=>{active&&(setConnectionError("\u8FDE\u63A5\u6682\u65F6\u4E2D\u65AD\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\u2026"),restoreTimer=window.setTimeout(restore,2500))})};restore();let onKeyDown=event3=>{event3.key==="Escape"&&onBack()};return window.addEventListener("keydown",onKeyDown),()=>{active=!1,controller.abort(),lifecycle.current=null,window.clearTimeout(restoreTimer),window.removeEventListener("keydown",onKeyDown)}},[]),React.useEffect(()=>{if(!job?.jobId||!["extracting","processing"].includes(job.status))return;let active=!0,timer,controller=new AbortController,poll=()=>api2("import",{operation:"status",namespace,jobId:job.jobId},{signal:controller.signal}).then(next2=>{active&&(setConnectionError(""),setJob(next2),["extracting","processing"].includes(next2.status)&&(timer=window.setTimeout(poll,1200)))}).catch(()=>{active&&(setConnectionError("\u8FDE\u63A5\u6682\u65F6\u4E2D\u65AD\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\u2026"),timer=window.setTimeout(poll,2500))});return timer=window.setTimeout(poll,600),()=>{active=!1,controller.abort(),window.clearTimeout(timer)}},[job?.jobId,job?.status,namespace]);let copyPrompt=()=>{if(!prompt)return;(navigator.clipboard?.writeText?navigator.clipboard.writeText(prompt):Promise.reject(new Error("\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236"))).then(()=>{setCopied(!0),window.setTimeout(()=>setCopied(!1),1600)}).catch(reason=>setError(String(reason?.message||reason)))},clearCommittedDraft=next2=>{let current=importDrafts.get(namespace);next2.status==="committed"&&current?.jobId===next2.jobId&&current.text.trim()===next2.text&&setText("")},mutate=(body,onResult,submission)=>{if(importRequests.has(namespace))return;let controller=lifecycle.current,valid2=()=>controller&&lifecycle.current===controller&&!controller.signal.aborted;setBusy(!0),setError("");let request=api2("import",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...body,namespace})});return importRequests.set(namespace,request),request.then(next2=>{if(submission&&importDrafts.get(namespace)===submission&&next2?.jobId&&(submission.jobId=next2.jobId),valid2())return onResult(next2)}).catch(reason=>{valid2()&&setError(String(reason?.message||reason))}).finally(()=>{importRequests.get(namespace)===request&&importRequests.delete(namespace),valid2()&&setBusy(!1)})},analyze=()=>{if(!(!text.trim()||busy||restoring||job&&job.status!=="failed"))return setResult(null),setJob(null),setChoices({}),mutate({operation:"preview",text},setJob,draft)},commit=()=>{if(!job||busy)return;let requestedChoices=(job.decisions||[]).flatMap((decision,index)=>decision.requiresConfirmation?[{index,action:choices[index]||decision.action||"IGNORE"}]:[]);return draft.text.trim()===job.text&&(draft.jobId=job.jobId),mutate({operation:"commit",jobId:job.jobId,choices:requestedChoices},next2=>(clearCommittedDraft(next2),setResult(next2),setJob(next2),refresh()))},retry=()=>{if(!(!job?.jobId||busy))return mutate({operation:"retry",jobId:job.jobId},setJob)},abandon=()=>{if(!(!job?.jobId||busy))return mutate({operation:"abandon",jobId:job.jobId},()=>{setJob(null),setText(""),setChoices({})})},undo=()=>{if(!(!result?.sourceBlockId||busy))return mutate({operation:"undo",sourceBlockId:result.sourceBlockId},()=>(setResult(null),setJob(null),refresh()))},reset2=()=>{setResult(null),setJob(null),setChoices({}),setError("")},actionLabel={ADD:"\u65B0\u589E",MERGE:"\u5408\u5E76",SUPERSEDE:"\u53D6\u4EE3\u65E7\u8BB0\u5FC6",CONFLICT:"\u4FDD\u7559\u5E76\u6807\u8BB0\u51B2\u7A81",IGNORE:"\u5FFD\u7565"},running=job&&["extracting","processing"].includes(job.status),reviewable=job&&["ready","awaiting_confirmation"].includes(job.status),emptyJob=reviewable&&Number(job.totalCount||0)===0,percent=job?job.status==="extracting"?5:job.totalCount?Math.round(job.processedCount/job.totalCount*100):100:0;return h("div",{className:"sg-import-overlay",role:"presentation",onMouseDown:event3=>{event3.target===event3.currentTarget&&onBack()}},h("section",{className:"sg-import-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"sg-import-title"},h("header",{className:"sg-import-dialog-head"},h("h2",{id:"sg-import-title",className:"sg-import-dialog-title"},"\u5C06\u8BB0\u5FC6\u5BFC\u5165 StrataGate"),h("button",{type:"button",className:"sg-icon-button",onClick:onBack,"aria-label":"\u5173\u95ED"},"\xD7")),h("div",{className:"sg-import-step"},h("div",{className:"sg-import-step-head"},h("span",{className:"sg-import-step-num"},"1"),h("span",{className:"sg-import-step-title"},"\u590D\u5236\u4EE5\u4E0B\u63D0\u793A\u8BCD\u5230\u5176\u4ED6 AI \u5BF9\u8BDD\u4E2D"),h("button",{type:"button",className:"sg-import-copy",disabled:promptLoading||!prompt,onClick:copyPrompt},copied?"\u5DF2\u590D\u5236":"\u590D\u5236")),promptLoading?h("div",{className:"sg-import-loading"},"\u6B63\u5728\u52A0\u8F7D\u63D0\u793A\u8BCD\u2026"):h("div",{className:"sg-import-prompt",tabIndex:"0"},prompt||"\u63D0\u793A\u8BCD\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u3002")),h("div",{className:"sg-import-step"},h("div",{className:"sg-import-step-head"},h("span",{className:"sg-import-step-num"},"2"),h("span",{className:"sg-import-step-title"},"\u7C98\u8D34\u7ED3\u679C\uFF0C\u5148\u5206\u6790\u518D\u5BFC\u5165")),h("div",{className:"sg-import-card"},h("textarea",{value:text,disabled:restoring||busy||!!result||!!job&&job.status!=="failed",onChange:event3=>setText(event3.target.value),placeholder:"\u7C98\u8D34 JSON\uFF1B\u683C\u5F0F\u4E0D\u5408\u683C\u65F6\u4F1A\u81EA\u52A8\u5C1D\u8BD5\u6062\u590D","aria-label":"\u5916\u90E8 AI \u8BB0\u5FC6 JSON"})),!job&&!result?h("div",{className:"sg-import-hint"},restoring?"\u6B63\u5728\u68C0\u67E5\u5DF2\u6709\u5BFC\u5165\u4EFB\u52A1\u2026":"\u5173\u95ED\u540E\u53EF\u7EE7\u7EED\u7F16\u8F91\uFF1B\u8349\u7A3F\u4EC5\u5728\u5F53\u524D\u6D4F\u89C8\u5668\u9875\u9762\u4FDD\u7559\uFF0C\u5237\u65B0\u540E\u6E05\u7A7A\u3002"):null),running?h("div",{className:"sg-import-step"},h("div",{className:"sg-import-step-head"},h("span",{className:"sg-import-step-num"},"3"),h("span",{className:"sg-import-step-title"},job.status==="extracting"?"\u6B63\u5728\u4FEE\u590D\u5E76\u63D0\u53D6\u5019\u9009\u8BB0\u5FC6":"\u6B63\u5728\u68C0\u6D4B\u91CD\u590D\u4E0E\u51B2\u7A81")),h("div",{role:"progressbar","aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":percent,style:{height:"9px",overflow:"hidden",borderRadius:"999px",background:"var(--sg-border)"}},h("div",{style:{width:percent+"%",height:"100%",background:"var(--sg-accent)",transition:"width .25s ease"}})),h("div",{className:"sg-import-hint",style:{marginTop:"8px"}},job.status==="extracting"?"\u539F JSON \u4E0D\u5408\u683C\uFF0C\u6B63\u5728\u4F7F\u7528\u6A21\u578B\u515C\u5E95\u3002\u53EF\u4EE5\u5173\u95ED\u9875\u9762\uFF0C\u4EFB\u52A1\u4F1A\u7EE7\u7EED\u3002":"\u5DF2\u5B8C\u6210 "+job.processedCount+"/"+job.totalCount+"\uFF0C\u6B63\u5728\u5224\u65AD\u7B2C "+Math.min(job.processedCount+1,job.totalCount)+" \u6761\uFF1B\u53EF\u4EE5\u5173\u95ED\u9875\u9762\uFF0C\u7A0D\u540E\u91CD\u65B0\u6253\u5F00\u67E5\u770B\u3002")):null,reviewable?h("div",{className:"sg-import-step"},h("div",{className:"sg-import-step-head"},h("span",{className:"sg-import-step-num"},"3"),h("span",{className:"sg-import-step-title"},"\u5BFC\u5165\u9884\u89C8")),h("div",{className:"sg-import-hint"},emptyJob?"\u6CA1\u6709\u53D1\u73B0\u53EF\u5BFC\u5165\u7684\u957F\u671F\u8BB0\u5FC6\u3002":job.recoveredFromInvalidJson?"\u8FD9\u4E9B\u5019\u9009\u7531\u515C\u5E95\u6A21\u578B\u6062\u590D\uFF0C\u5168\u90E8\u9700\u8981\u4EBA\u5DE5\u786E\u8BA4\u3002":"\u9AD8\u7F6E\u4FE1\u5EA6\u7ED3\u679C\u81EA\u52A8\u91C7\u7528\uFF1B\u4F4E\u7F6E\u4FE1\u5EA6\u7ED3\u679C\u8BF7\u4EBA\u5DE5\u9009\u62E9\u5904\u7406\u65B9\u5F0F\u3002"),h("div",{className:"sg-import-preview"},(job.decisions||[]).map((decision,index)=>h("div",{key:index,className:"sg-import-preview-item"},h("div",{className:"sg-import-preview-title"},decision.candidate?.title||"\u672A\u547D\u540D\u8BB0\u5FC6"),h("div",{className:"sg-import-preview-content"},h("strong",null,"\u65B0\u8BB0\u5FC6\uFF1A"),h("span",null,decision.candidate?.summary||"\u65E0\u5185\u5BB9"),decision.candidate?.narrative?h("div",null,decision.candidate.narrative):null),decision.mergedCandidate?h("div",{className:"sg-import-preview-content"},h("strong",null,"\u5408\u5E76\u540E\uFF1A"),h("span",null,decision.mergedCandidate.title+"\uFF1A"+decision.mergedCandidate.summary)):null,decision.existingEventIds?.length&&decision.matches?.length?h("div",{className:"sg-import-preview-content"},h("strong",null,"\u53D7\u5F71\u54CD\u7684\u65E7\u8BB0\u5FC6\uFF1A"),decision.matches.filter(match2=>decision.existingEventIds.includes(match2.event.id)).map(match2=>h("div",{key:match2.event.id},match2.event.title+"\uFF1A"+match2.event.summary))):null,h("div",{className:"sg-import-preview-meta"},h("span",null,actionLabel[decision.action]||decision.action),h("span",null,"\u7F6E\u4FE1\u5EA6 "+Math.round(Number(decision.confidence||0)*100)+"%"),decision.existingEventIds?.length?h("span",null,"\u5173\u8054 "+decision.existingEventIds.length+" \u6761"):null),decision.reason?h("div",{className:"sg-import-preview-reason"},decision.reason):null,decision.requiresConfirmation?h("label",{className:"sg-import-review"},h("span",null,"\u4EBA\u5DE5\u9009\u62E9"),h("select",{value:choices[index]||decision.action,onChange:event3=>setChoices(current=>({...current,[index]:event3.target.value}))},(decision.existingEventIds?.length?["ADD","MERGE","SUPERSEDE","CONFLICT","IGNORE"]:["ADD","IGNORE"]).map(action=>h("option",{key:action,value:action},actionLabel[action])))):null)))):null,job?.status==="failed"?h("div",{className:"sg-import-error"},"\u4EFB\u52A1\u5931\u8D25\uFF1A"+(job.lastError||"\u672A\u77E5\u9519\u8BEF")):null,connectionError?h("div",{className:"sg-import-hint"},connectionError):null,error3?h("div",{className:"sg-import-error"},error3):null,result?h("div",{className:"sg-import-result"},"\u5BFC\u5165\u5B8C\u6210\uFF1A\u65B0\u589E "+Number(result.importedCount||0)+" \u6761\u8BB0\u5FC6\u3002\u53EF\u7ACB\u5373\u64A4\u9500\u672C\u6279\u6B21\u3002"):null,h("footer",{className:"sg-import-dialog-foot"},result?h("button",{type:"button",className:"sg-import-cancel",disabled:busy,onClick:undo},busy?"\u6B63\u5728\u64A4\u9500\u2026":"\u64A4\u9500\u672C\u6B21\u5BFC\u5165"):h("button",{type:"button",className:"sg-import-cancel",onClick:onBack},running?"\u5173\u95ED\uFF0C\u540E\u53F0\u7EE7\u7EED":"\u5173\u95ED"),!job&&!result&&text?h("button",{type:"button",className:"sg-import-cancel",disabled:restoring||busy,onClick:()=>{setText(""),setError("")}},"\u653E\u5F03\u8349\u7A3F"):null,result?h("button",{type:"button",className:"sg-import-button",disabled:busy,onClick:reset2},"\u5BFC\u5165\u53E6\u4E00\u6279"):job?.status==="failed"?h(React.Fragment,null,h("button",{type:"button",className:"sg-import-cancel",disabled:busy,onClick:()=>{setJob(null),setChoices({}),setError("")}},"\u4FEE\u6539\u540E\u91CD\u65B0\u5206\u6790"),h("button",{type:"button",className:"sg-import-cancel",disabled:busy,onClick:abandon},"\u653E\u5F03\u672C\u6B21\u5BFC\u5165"),h("button",{type:"button",className:"sg-import-button",disabled:busy,onClick:retry},busy?"\u6B63\u5728\u91CD\u8BD5\u2026":"\u91CD\u8BD5")):emptyJob?h("button",{type:"button",className:"sg-import-button",onClick:reset2},"\u5BFC\u5165\u53E6\u4E00\u6279"):reviewable?h("button",{type:"button",className:"sg-import-button",disabled:busy,onClick:commit},busy?"\u6B63\u5728\u5BFC\u5165\u2026":"\u786E\u8BA4\u5BFC\u5165"):running?h("button",{type:"button",className:"sg-import-button",disabled:!0},"\u540E\u53F0\u5904\u7406\u4E2D"):h("button",{type:"button",className:"sg-import-button",disabled:restoring||busy||!text.trim(),onClick:analyze},busy?"\u6B63\u5728\u521B\u5EFA\u4EFB\u52A1\u2026":"\u5206\u6790\u5E76\u9884\u89C8"))))}function SettingStepper({value,unit="",min:min4=1,max:max5=30,step:step3=1,disabled=!1,label,onChange}){let current=Number(value),bump=direction=>{if(!Number.isFinite(current)||disabled)return;let next2=Math.min(max5,Math.max(min4,Number((current+direction*step3).toFixed(2))));next2!==current&&onChange(next2)};return h("span",{className:"sg-stp",role:"group","aria-label":label},h("button",{type:"button","aria-label":"\u51CF\u5C11"+label,disabled:disabled||!Number.isFinite(current)||current<=min4,onClick:()=>bump(-1)},"\u2212"),h("span",{"aria-live":"polite",className:"sg-stp-value"},(Number.isFinite(current)?String(current):"")+unit),h("button",{type:"button","aria-label":"\u589E\u52A0"+label,disabled:disabled||!Number.isFinite(current)||current>=max5,onClick:()=>bump(1)},"+"))}function MoreHome({setView,selected,overview={},namespace,dataDirectory,updateSettings,savingSettings,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,setDailyEnabled,setDailyInjectionDays}){let pluginSettings=usePluginSettings?usePluginSettings(state=>state):null,settingsWritable=pluginSettings?.writable===!0,[pending,setPending]=React.useState({}),[settingError,setSettingError]=React.useState({key:"",text:""}),[savingKey,setSavingKey]=React.useState(""),[copyState,setCopyState]=React.useState("");React.useEffect(()=>{setPending({blockTurnSize:String(selected?.blockTurnSize??6),blockDecayLambda:String(selected?.blockDecayLambda??.3),agentMemoryRetrievalWeight:String(selected?.agentMemoryRetrievalWeight??1)})},[selected?.blockTurnSize,selected?.blockDecayLambda,selected?.agentMemoryRetrievalWeight]);let engine=[["blockTurnSize","\u6BCF\u5757\u8F6E\u6570","",1,30,1],["blockDecayLambda","\u8870\u51CF\u7CFB\u6570","",0,.4,.05],["agentMemoryRetrievalWeight","\u4E3B\u52A8\u68C0\u7D22\u5360\u6BD4","",0,5,.05]],saved=key=>Number(selected?.[key]??(key==="blockTurnSize"?6:key==="blockDecayLambda"?.3:1)),changedKeys=engine.map(([key])=>key).filter(key=>pending[key]!==void 0&&Number(pending[key])!==saved(key)&&pending[key]!==""),validEngine=engine.every(([key])=>{let raw=pending[key];return raw!==void 0&&raw!==""&&Number.isFinite(Number(raw))}),saveEngine=async()=>{if(!(!changedKeys.length||!validEngine||savingSettings)){setSettingError({key:"",text:""});try{await updateSettings({blockTurnSize:Number(pending.blockTurnSize),blockDecayLambda:Number(pending.blockDecayLambda),agentMemoryRetrievalWeight:Number(pending.agentMemoryRetrievalWeight)})}catch(reason){setSettingError({key:"engine",text:"\u672A\u80FD\u4FDD\u5B58\u5F15\u64CE\u53C2\u6570\uFF1A"+String(reason?.message||reason)})}}},discardEngine=()=>setPending({blockTurnSize:String(saved("blockTurnSize")),blockDecayLambda:String(saved("blockDecayLambda")),agentMemoryRetrievalWeight:String(saved("agentMemoryRetrievalWeight"))}),toggle=async(key,setter,next2)=>{if(setter){setSavingKey(key),setSettingError({key:"",text:""});try{await setter(next2)||setSettingError({key,text:"\u672A\u80FD\u4FDD\u5B58\u8FD9\u9879\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}catch(reason){setSettingError({key,text:"\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}finally{setSavingKey("")}}},stepDays=async next2=>{if(setDailyInjectionDays){setSavingKey("dailyDays"),setSettingError({key:"",text:""});try{await setDailyInjectionDays(next2)||setSettingError({key:"dailyDays",text:"\u5929\u6570\u672A\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}catch(reason){setSettingError({key:"dailyDays",text:"\u5929\u6570\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}finally{setSavingKey("")}}},copyWorkspace=async()=>{if(navigator?.clipboard?.writeText)try{await navigator.clipboard.writeText(namespace||""),setCopyState("\u5DF2\u590D\u5236"),setSettingError({key:"",text:""})}catch{setSettingError({key:"workspace",text:"\u590D\u5236\u5DE5\u4F5C\u533A ID \u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u3002"})}},retry=async(key,apply3)=>{setSettingError({key:"",text:""});try{await apply3()||setSettingError({key,text:"\u4ECD\u7136\u65E0\u6CD5\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002"})}catch(reason){setSettingError({key,text:"\u4ECD\u7136\u65E0\u6CD5\u4FDD\u5B58\uFF1A"+String(reason?.message||reason)})}},rowError=(key,apply3)=>settingError.key===key?h("p",{className:"sg-more-error",role:"alert"},settingError.text,apply3?h("button",{type:"button",className:"sg-more-retry",onClick:()=>{retry(key,apply3)}},"\u91CD\u8BD5"):null):null,switchRow=({key,title,description,checked,setter,disabled=!1,child=!1})=>h("li",{key,className:"sg-more-row sg-more-switch"+(child?" child":"")},h("div",null,h("span",{className:"sg-k2"},title),description?h("span",{className:"sg-s2"},description):null,rowError(key,()=>setter(!checked))),h("button",{type:"button",className:"sg-setting-switch",role:"switch","aria-label":title,"aria-checked":checked,disabled:disabled||!settingsWritable||savingKey===key,onClick:()=>{toggle(key,setter,!checked)}})),goRow=(key,title,description,view)=>h("li",{key,className:"sg-more-row"},h("button",{type:"button",className:"sg-more-go",onClick:()=>setView({name:view})},h("div",null,h("span",{className:"sg-k2"},title),description?h("span",{className:"sg-s2"},description):null),h("span",{className:"sg-row-go","aria-hidden":"true"},"\u203A"))),group2=(title,rows,extra="")=>h("section",{key:title,className:"sg-profile-group","aria-label":title},h("h4",null,title),h("ul",null,rows,extra)),duplicates=Number(selected?.duplicateRepair?.needsReview||0),failed=Number(selected?.failedJobs||0),processing=Number(selected?.processingJobs||0),statusRows=[h("li",{key:"kpi",className:"sg-more-kpi"},h("div",null,["blocks","events","graphNodes"].map((key,index)=>h("div",{key},h("b",null,String(Number(selected?.[key]||0))),h("span",null,["\u8BB0\u5FC6\u5757","\u4E8B\u4EF6","\u56FE\u8C31\u8282\u70B9"][index]))))),goRow("system","\u7CFB\u7EDF\u72B6\u6001",failed?failed+" \u4E2A\u4EFB\u52A1\u9700\u8981\u91CD\u8BD5":processing?processing+" \u4E2A\u4EFB\u52A1\u8FDB\u884C\u4E2D":"\u8FD0\u884C\u6B63\u5E38","system"),goRow("duplicates","\u91CD\u590D\u8BB0\u5FC6",duplicates?duplicates+" \u7EC4\u7B49\u4F60\u786E\u8BA4":"\u6CA1\u6709\u9700\u8981\u786E\u8BA4\u7684\u5206\u7EC4","duplicates")],dataRows=[goRow("import","\u5BFC\u5165\u5176\u4ED6 AI \u7684\u8BB0\u5FC6","\u628A\u522B\u7684 AI \u7684\u5386\u53F2\u8BB0\u5FC6\u5E26\u8FDB\u6765","import"),goRow("settings","\u9AD8\u7EA7\u8BBE\u7F6E","\u5411\u91CF\u68C0\u7D22\u3001\u7CBE\u6392\u4E0E\u8BB0\u5FC6\u914D\u7F6E","settings"),h("li",{key:"directory",className:"sg-more-row sg-more-row-path"},h("div",{className:"sg-more-path"},h("span",{className:"sg-k2"},"\u6570\u636E\u76EE\u5F55"),h("span",{className:"sg-s2 sg-mono sg-path",title:dataDirectory||void 0},dataDirectory||"\u5F53\u524D\u4F7F\u7528\u5185\u5B58\u5B58\u50A8")),h("button",{type:"button",className:"sg-quiet-button",disabled:!dataDirectory,onClick:()=>{api2("storage/open-directory",{},{method:"POST"}).catch(reason=>setSettingError({key:"directory",text:"\u6253\u5F00\u5931\u8D25\uFF1A"+String(reason?.message||reason)}))}},"\u6253\u5F00")),h("li",{key:"workspace",className:"sg-more-row"},h("div",null,h("span",{className:"sg-k2"},"\u5F53\u524D\u5DE5\u4F5C\u533A"),h("span",{className:"sg-s2 sg-mono"},selected?.workspaceName||"\u5F53\u524D\u5DE5\u4F5C\u533A")),h("button",{type:"button",className:"sg-quiet-button",disabled:!namespace,onClick:copyWorkspace},copyState||"\u590D\u5236 ID"))],feedbackRows=[h("li",{key:"issue",className:"sg-more-row"},h("div",null,h("span",{className:"sg-k2"},"GitHub Issue"),h("span",{className:"sg-s2"},"\u95EE\u9898\u548C\u5EFA\u8BAE\u63D0\u5230 GitHub")),h("a",{className:"sg-quiet-button",href:ISSUE_URL,target:"_blank",rel:"noopener noreferrer"},"\u63D0 Issue")),goRow("support","\u751F\u6210\u53CD\u9988\u62A5\u544A","\u53D1\u51FA\u524D\u53EF\u4EE5\u5148\u770B\u5B8C\u6574\u5185\u5BB9","support")],displayRows=[switchRow({key:"sidebar",title:"\u653E\u5230\u5DE6\u4FA7\u680F",checked:pluginSettings?.value?.showSidebarEntry===!0,setter:setSidebarEntry}),switchRow({key:"shortStatus",title:"\u4F1A\u8BDD\u8BB0\u5FC6\u72B6\u6001",checked:pluginSettings?.value?.showShortTermStatus!==!1,setter:setShortTermStatus}),switchRow({key:"retrievalStatus",title:"\u8BB0\u5FC6\u68C0\u7D22\u72B6\u6001",checked:pluginSettings?.value?.showRetrievalStatus!==!1,setter:setRetrievalStatus}),pluginSettings?.value?.showStrataGateStatus===!1?switchRow({key:"master",title:"\u6062\u590D\u72B6\u6001\u63D0\u793A",description:"\u4E4B\u524D\u6574\u4F53\u5173\u95ED\u4E86\u804A\u5929\u754C\u9762\u7684\u72B6\u6001\u63D0\u793A",checked:!1,setter:setStrataGateStatus}):null].filter(Boolean),dailyRows=[switchRow({key:"daily",title:"\u5199\u6BCF\u65E5\u7B14\u8BB0",description:"\u5173\u95ED\u540E\u4E0D\u518D\u5199\u5165\uFF0C\u5DF2\u6709\u7B14\u8BB0\u4FDD\u7559",checked:pluginSettings?.value?.dailyNotesEnabled!==!1,setter:setDailyEnabled}),h("li",{key:"days",className:"sg-more-row"},h("div",null,h("span",{className:"sg-k2"},"\u5E26\u5165\u5929\u6570"),h("span",{className:"sg-s2"},"\u53D6\u6700\u8FD1\u6709\u7B14\u8BB0\u7684\u65E5\u671F")),SettingStepper({value:pluginSettings?.value?.dailyNotesInjectionDays??3,unit:" \u5929",min:1,max:30,disabled:!settingsWritable||savingKey==="dailyDays",label:"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570",onChange:next2=>{stepDays(next2)}}))],engineRows=engine.map(([key,title,unit,min4,max5,step3])=>{let dirty=changedKeys.includes(key);return h("li",{key,className:"sg-more-row"},h("div",null,h("span",{className:"sg-k2"+(dirty?" dirty":"")},title)),h("span",{className:"sg-engine-value"+(dirty?" dirty":"")},SettingStepper({value:pending[key]??saved(key),unit,min:min4,max:max5,step:step3,disabled:savingSettings,label:title,onChange:next2=>setPending(current=>({...current,[key]:String(next2)}))})))});return h(React.Fragment,null,h("div",{className:"sg-pg-head"},h("h2",null,"\u66F4\u591A")),h("div",{className:"sg-more"},h("div",{className:"sg-more-col"},group2("\u8FD0\u884C\u72B6\u6001",statusRows),group2("\u6570\u636E",dataRows),group2("\u53CD\u9988",feedbackRows)),h("div",{className:"sg-more-col"},group2("\u663E\u793A",displayRows),group2("\u77ED\u671F\u8BB0\u5FC6",dailyRows),group2("\u5F15\u64CE\u53C2\u6570",engineRows,h(React.Fragment,null,rowError("engine",()=>updateSettings({blockTurnSize:Number(pending.blockTurnSize),blockDecayLambda:Number(pending.blockDecayLambda),agentMemoryRetrievalWeight:Number(pending.agentMemoryRetrievalWeight)})),changedKeys.length?h("li",{className:"sg-dirty"},h("span",null,changedKeys.length+" \u9879\u672A\u4FDD\u5B58"),h("button",{type:"button",className:"sg-quiet-button",disabled:savingSettings,onClick:discardEngine},"\u653E\u5F03"),h("button",{type:"button",className:"sg-save-button",disabled:savingSettings||!validEngine,onClick:()=>{saveEngine()}},savingSettings?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):null)))))}function DisplayPage({onBack,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry}){let pluginSettings=usePluginSettings?usePluginSettings(state=>state):null,settingsWritable=pluginSettings?.writable===!0,[sidebarSaving,setSidebarSaving]=React.useState(!1),[sidebarError,setSidebarError]=React.useState(""),changeSidebar=async visible=>{setSidebarSaving(!0),setSidebarError("");try{await setSidebarEntry?.(visible)||setSidebarError("\u672A\u80FD\u4FDD\u5B58\u4FA7\u680F\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u8BD5\u3002")}catch{setSidebarError("\u672A\u80FD\u4FDD\u5B58\u4FA7\u680F\u8BBE\u7F6E\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002")}finally{setSidebarSaving(!1)}},showStrataGateStatus=strataGateStatusVisible(pluginSettings),showShortTermStatus=pluginSettings?.value?.showShortTermStatus!==!1,showRetrievalStatus=pluginSettings?.value?.showRetrievalStatus!==!1,setting=({title,description,checked,disabled=!1,onChange,child=!1})=>h("div",{className:"sg-display-setting "+(child?"child ":"")+(disabled?"sg-display-disabled":"")},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},title),h("span",{className:"sg-display-setting-description"},description)),h("button",{type:"button",className:"sg-setting-switch",role:"switch","aria-checked":checked,"aria-label":title,disabled:!settingsWritable||disabled,onClick:()=>{onChange&&onChange(!checked)}}));return h(React.Fragment,null,h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-pg-head"},h("h2",null,"\u754C\u9762\u4E0E\u663E\u793A")),h("p",{className:"sg-settings-group-copy"},"\u63A7\u5236\u4FA7\u680F\u5165\u53E3\u548C\u804A\u5929\u754C\u9762\u4E2D\u7684\u663E\u793A\u4FE1\u606F\u3002\u8BBE\u7F6E\u5BF9\u6240\u6709\u5DE5\u4F5C\u533A\u751F\u6548\u3002"),h("div",{className:"sg-settings-panel sg-display-settings"},setting({title:"\u5728\u5DE6\u4FA7\u680F\u663E\u793A StrataGate",description:"\u5173\u95ED\u540E\u9690\u85CF\u4FA7\u680F\u5165\u53E3\uFF0C\u4ECD\u53EF\u4ECE\u8BBE\u7F6E\u6253\u5F00\uFF1B\u8BB0\u5FC6\u3001\u68C0\u7D22\u548C\u540E\u53F0\u5904\u7406\u4E0D\u53D7\u5F71\u54CD\u3002",checked:pluginSettings?.value?.showSidebarEntry===!0,disabled:sidebarSaving||!setSidebarEntry,onChange:changeSidebar}),sidebarError?h("p",{role:"alert",className:"sg-error-note"},sidebarError):null,setting({title:"\u663E\u793A StrataGate \u72B6\u6001\u63D0\u793A",description:"\u5173\u95ED\u540E\u9690\u85CF\u804A\u5929\u754C\u9762\u4E2D\u7684 StrataGate \u72B6\u6001\u4FE1\u606F\uFF0C\u4E0D\u5F71\u54CD\u8BB0\u5FC6\u3001\u68C0\u7D22\u548C\u540E\u53F0\u5904\u7406\u3002",checked:showStrataGateStatus,onChange:setStrataGateStatus}),setting({title:"\u4F1A\u8BDD\u8BB0\u5FC6\u72B6\u6001",description:"\u663E\u793A Block \u8FDB\u5EA6\u3001\u5C01\u5B58\u7ED3\u679C\u548C\u6B63\u5728\u6574\u7406\u4F1A\u8BDD\u8BB0\u5FC6\u7B49\u72B6\u6001\u3002",checked:showShortTermStatus,disabled:!showStrataGateStatus,onChange:setShortTermStatus,child:!0}),setting({title:"\u8BB0\u5FC6\u68C0\u7D22\u72B6\u6001",description:"\u663E\u793A\u68C0\u7D22\u6B21\u6570\u3001\u8FD4\u56DE\u6570\u91CF\uFF0C\u4EE5\u53CA\u56DE\u7B54\u4E0B\u65B9\u7684\u8BB0\u5FC6\u91C7\u7528\u4FE1\u606F\u3002",checked:showRetrievalStatus,disabled:!showStrataGateStatus,onChange:setRetrievalStatus,child:!0})))}function redactText(value){return String(value??"").split(/\nRaw response(?: preview| \(full\))/i)[0].replace(/\b(?:sk[-_]|gh[opasu]_|github_pat_)[A-Za-z0-9_-]{8,}\b/g,"[REDACTED]").replace(/(["']?\b(?:api[_-]?key|token|password|passwd|access[_-]?token|refresh[_-]?token|secret|authorization)["']?\s*[:=]\s*)(["'])([\s\S]*?)\2/gi,"$1$2[REDACTED]$2").replace(/(\bauthorization\s*[:=]\s*)(Bearer|Basic|Token)\s+[^\s,;}]+/gi,"$1$2 [REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}\b/gi,"Bearer [REDACTED]").replace(/\b(?:Basic|Token)\s+[^\s,;}]+/gi,match2=>match2.replace(/\s+[^\s,;}]+$/," [REDACTED]")).replace(/(["']?\b(?:api[_-]?key|token|password|passwd|access[_-]?token|refresh[_-]?token|secret|authorization)["']?\s*[:=]\s*)([^\s,;}]+)/gi,"$1[REDACTED]").replace(/https?:\/\/[^\s<>"']+/gi,"[url]").replace(/[A-Z]:[\\/][^\s"'<>]+/gi,"[path]").replace(/\\\\[^\s"'<>\\]+\\[^\s"'<>]+/g,"[path]").replace(/(^|[\s"'(=:])\/(?:[^\s"'<>/]+\/)+[^\s"'<>]*/g,"$1[path]").replace(/[\w.+-]+@[\w.-]+\.[a-z]{2,}/gi,"[email]")}function redactedJson(value){let sensitive=/^(password|passwd|token|access[_-]?token|refresh[_-]?token|api[_-]?key|secret|authorization)$/i,visit=(current,key="")=>sensitive.test(String(key))?"[REDACTED]":typeof current=="string"?redactText(current):Array.isArray(current)?current.map(item=>visit(item)):current&&typeof current=="object"?Object.fromEntries(Object.entries(current).map(([name,item])=>[name,visit(item,name)])):current;return JSON.stringify(visit(value),null,2)??"null"}function restoreFeedbackDraftValues(draft,touched={}){return{title:touched.title?void 0:String(draft?.title||""),problemContent:touched.body?void 0:feedbackDraftMarkdown(draft)}}function whitelistedMessage(message){return{id:message?.id,role:message?.role,content:message?.content,createdAt:message?.createdAt,threadId:message?.threadId,toolCalls:Array.isArray(message?.toolCalls)?message.toolCalls.map(call=>({name:call?.name,arguments:call?.arguments,result:call?.result})):void 0}}function whitelistedEvent(event3){let temporal=event3?.temporal,weight8=event3?.weight;return{id:event3?.id,formedTurn:event3?.formedTurn,title:event3?.title,summary:event3?.summary,tags:event3?.tags,quotes:event3?.quotes,sourceBlockId:event3?.sourceBlockId,sourceMessageIds:event3?.sourceMessageIds,temporal:temporal?{mentionedAt:temporal.mentionedAt,happenedStart:temporal.happenedStart,happenedEnd:temporal.happenedEnd,originalText:temporal.originalText,precision:temporal.precision,basis:temporal.basis,status:temporal.status,participants:temporal.participants,participantNodeIds:temporal.participantNodeIds,eventType:temporal.eventType,threadId:temporal.threadId,sameEventId:temporal.sameEventId,beforeEventIds:temporal.beforeEventIds,afterEventIds:temporal.afterEventIds,supersedesEventIds:temporal.supersedesEventIds,conflictsWithEventIds:temporal.conflictsWithEventIds,relatedEventIds:temporal.relatedEventIds}:void 0,scope:event3?.scope,criticality:event3?.criticality,status:event3?.status,supersededBy:event3?.supersededBy,weight:weight8?{mentionCount:weight8.mentionCount,lastAdoptedTurn:weight8.lastAdoptedTurn,lastRetrievedAt:weight8.lastRetrievedAt,pinned:weight8.pinned,floorWeight:weight8.floorWeight,forcedCap:weight8.forcedCap}:void 0,createdAt:event3?.createdAt,updatedAt:event3?.updatedAt}}function whitelistedBlock(block){let source=block?.source||block||{},messages=block?.messages||block?.l5Raw||source?.l5Raw;return{id:block?.id??source?.id,threadId:block?.threadId??source?.threadId,sequence:block?.sequence??source?.sequence,blockIndex:block?.blockIndex,turnRange:block?.turnRange||(source?.startTurn!==void 0&&source?.endTurn!==void 0?[source.startTurn,source.endTurn]:void 0),title:block?.title??source?.l0Title,tags:block?.tags??source?.l0Tags,summary:block?.summary??source?.l1Summary,keypoints:block?.keypoints??source?.l2Keypoints,condensed:source?.l3Condensed,readable:source?.l4Readable,messages:Array.isArray(messages)?messages.map(whitelistedMessage):void 0,layers:Array.isArray(block?.layers)?block.layers.map(layer=>({level:layer?.level,content:layer?.content,tokens:layer?.tokens,percentOfL5:layer?.percentOfL5})):void 0,currentLevel:block?.currentLevel??source?.pointerCurrentLevel,currentTokens:block?.currentTokens,l5Tokens:block?.l5Tokens,compressionPercent:block?.compressionPercent,layerTokens:block?.layerTokens,distanceFromLatest:block?.distanceFromLatest,expansionSource:block?.expansionSource,lastLiftedAt:block?.lastLiftedAt??source?.lastLiftedAt,sourceMessages:block?.sourceMessages,createdAt:block?.createdAt??source?.createdAt,virtual:block?.virtual,processingStatus:block?.processingStatus??source?.processingStatus,summaryJob:block?.summaryJob?{status:block.summaryJob.status,attempts:block.summaryJob.attempts,nextRetryAt:block.summaryJob.nextRetryAt,updatedAt:block.summaryJob.updatedAt}:void 0,eventExtraction:block?.eventExtraction?{status:block.eventExtraction.status,attempts:block.eventExtraction.attempts,updatedAt:block.eventExtraction.updatedAt,lastError:block.eventExtraction.lastError}:void 0,graphProjection:block?.graphProjection?{status:block.graphProjection.status,jobs:block.graphProjection.jobs,lastError:block.graphProjection.lastError}:void 0,relatedEvents:Array.isArray(block?.relatedEvents)?block.relatedEvents.map(whitelistedEvent):void 0,relatedNodes:Array.isArray(block?.relatedNodes)?block.relatedNodes.map(node=>({id:node?.id,name:node?.name,type:node?.type})):void 0}}function whitelistedGraphNode(node){return{id:node?.id,name:node?.name,type:node?.type,aliases:node?.aliases,tags:node?.tags,currentState:node?.currentState,facts:Array.isArray(node?.facts)?node.facts.map(fact=>({id:fact?.id,key:fact?.key,value:fact?.value,status:fact?.status,validFrom:fact?.validFrom,validTo:fact?.validTo,confidence:fact?.confidence,sourceEventIds:fact?.sourceEventIds,createdAt:fact?.createdAt,updatedAt:fact?.updatedAt})):void 0,status:node?.status,confidence:node?.confidence,sourceEventIds:node?.sourceEventIds,supportingEvents:Array.isArray(node?.supportingEvents)?node.supportingEvents.map(whitelistedEvent):void 0,createdAt:node?.createdAt,updatedAt:node?.updatedAt}}function whitelistedGraph(graph){return{projectorVersion:graph?.projectorVersion,nodes:Array.isArray(graph?.nodes)?graph.nodes.map(whitelistedGraphNode):[],edges:Array.isArray(graph?.edges)?graph.edges.map(edge=>({id:edge?.id,fromNodeId:edge?.fromNodeId,toNodeId:edge?.toNodeId,relation:edge?.relation,status:edge?.status,validFrom:edge?.validFrom,validTo:edge?.validTo,confidence:edge?.confidence,sourceEventIds:edge?.sourceEventIds,createdAt:edge?.createdAt,updatedAt:edge?.updatedAt})):[],clusters:Array.isArray(graph?.clusters)?graph.clusters.map(cluster=>({id:cluster?.id,label:cluster?.label,nodeIds:cluster?.nodeIds,tags:cluster?.tags})):[],migration:graph?.migration?{projected:graph.migration.projected,total:graph.migration.total,pending:graph.migration.pending,running:graph.migration.running,failed:graph.migration.failed,retryable:graph.migration.retryable,processing:graph.migration.processing,state:graph.migration.state,complete:graph.migration.complete}:null}}function feedbackDraftMarkdown(draft={}){if(String(draft.bodyMarkdown||"").trim())return String(draft.bodyMarkdown).trim();let lines=[],section=(heading,value)=>{let text=String(value||"").trim();text&&lines.push("## "+heading,"",text,"")};section("\u95EE\u9898\u63CF\u8FF0",draft.description);let steps=Array.isArray(draft.reproduction)?draft.reproduction.map(value=>String(value||"").trim()).filter(Boolean):[];return steps.length&&lines.push("## \u590D\u73B0\u6B65\u9AA4","",...steps.map((value,index)=>index+1+". "+value),""),section("\u9884\u671F\u884C\u4E3A",draft.expected),section("\u5B9E\u9645\u884C\u4E3A",draft.actual),section("\u76F8\u5173\u9519\u8BEF\u4FE1\u606F",draft.errorContext),lines.join(`
1198
1344
  `).trim()}function issueUrl(title=""){let value=String(title||"").trim(),params=new URLSearchParams;return value&&params.set("title",value),params.set("body",ISSUE_BODY_HINT),ISSUE_URL+"?"+params.toString()}function feedbackEmailUrl(title=""){let value=String(title||"").replace(/[\uD800-\uDFFF]/gu,"\uFFFD").replace(/[\u0000-\u001F\u007F-\u009F]+/g," ").trim().slice(0,240).replace(/[\uD800-\uDBFF]$/,""),subject="StrataGate \u53CD\u9988"+(value?"\uFF1A"+value:"");return"mailto:"+FEEDBACK_EMAIL+"?subject="+encodeURIComponent(subject)+"&body="+encodeURIComponent(EMAIL_BODY_HINT)}async function copyReportAndComposeEmail(report,clipboard=navigator?.clipboard,compose=url=>{window.location.href=url},title=""){let copyPromise=null,copyError="";if(!clipboard?.writeText)copyError="\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236\u3002";else try{copyPromise=Promise.resolve(clipboard.writeText(report))}catch(reason){copyError="\u590D\u5236\u5931\u8D25\uFF1A"+String(reason?.message||reason)}let composeRequested=!1;try{compose(feedbackEmailUrl(title)),composeRequested=!0}catch{}if(copyError)return{copied:!1,composeRequested,error:copyError};try{return await copyPromise,{copied:!0,composeRequested,error:""}}catch(reason){return{copied:!1,composeRequested,error:"\u590D\u5236\u5931\u8D25\uFF1A"+String(reason?.message||reason)}}}function handleFeedbackEmailResult(result,callbacks={}){if(result?.copied)callbacks.setStatus?.(result.composeRequested?"\u62A5\u544A\u5DF2\u590D\u5236\u3002\u8BF7\u5728\u90AE\u4EF6\u64B0\u5199\u7A97\u53E3\u4E2D\u7C98\u8D34\u3001\u68C0\u67E5\u5E76\u53D1\u9001\uFF1B\u82E5\u672A\u6253\u5F00\uFF0C\u8BF7\u590D\u5236\u4E0B\u65B9\u90AE\u7BB1\u81EA\u884C\u53D1\u9001\u3002":"\u62A5\u544A\u5DF2\u590D\u5236\u3002\u8BF7\u70B9\u51FB\u4E0B\u65B9\u90AE\u4EF6\u94FE\u63A5\uFF0C\u6216\u590D\u5236\u90AE\u7BB1\u81EA\u884C\u53D1\u9001\u3002");else{callbacks.setPreviewOpen?.(!0);let message=(result?.error||"\u590D\u5236\u62A5\u544A\u5931\u8D25\u3002")+" \u62A5\u544A\u4ECD\u4FDD\u7559\u5728\u9884\u89C8\u4E2D\uFF0C\u53EF\u624B\u52A8\u590D\u5236\u6216\u4E0B\u8F7D\u540E\u53D1\u9001\u81F3 "+FEEDBACK_EMAIL+"\u3002";callbacks.setError?.(current=>current?current+" "+message:message)}return result}let GITHUB_STARS_FALLBACK=128,GITHUB_STARS=(()=>{let value=Number(globalThis.__STRATAGATE_GITHUB_STARS__);return Number.isSafeInteger(value)&&value>=0?value:GITHUB_STARS_FALLBACK})();function formatStarCount(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?Math.floor(value).toLocaleString("en-US"):""}function loadStarCount(){return Promise.resolve(formatStarCount(GITHUB_STARS))}function GitHubMarkIcon(){return h("svg",{className:"sg-ghstar-icon",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",focusable:"false"},h("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"}))}function StrataGateMark(){return h("svg",{className:"sg-logo",viewBox:"0 0 32 32",role:"img","aria-label":"StrataGate",focusable:"false"},h("rect",{className:"sg-logo-back",x:10,y:5,width:16,height:17,rx:3,strokeWidth:1.5}),h("rect",{className:"sg-logo-middle",x:7,y:8,width:16,height:17,rx:3,strokeWidth:1.5}),h("rect",{className:"sg-logo-front",x:4,y:11,width:16,height:17,rx:3,strokeWidth:1.8}),h("path",{className:"sg-logo-rule",d:"M8 17h8M8 21h5",fill:"none",strokeWidth:1.8,strokeLinecap:"round"}))}function HeaderStarLink(){let shown=formatStarCount(GITHUB_STARS),label=shown?"\u5728 GitHub \u4E0A\u7ED9 StrataGate \u70B9 Star\uFF0C\u5F53\u524D "+shown+" \u4E2A":"\u5728 GitHub \u4E0A\u7ED9 StrataGate \u70B9 Star";return h("a",{className:"sg-ghstar",href:STAR_REPOSITORY_URL,target:"_blank",rel:"noopener noreferrer",title:label,"aria-label":label},h("span",{className:"sg-ghstar-label"},h(GitHubMarkIcon),h("b",null,"Star")),shown?h("span",{className:"sg-ghstar-count","aria-hidden":"true"},shown):null)}function buildSupportReport({problemContent="",overview={},selected={},data:data4={},recentError="",includeLogs=!1,includeMemory=!1,willingToContribute=!1,diagnostics=null}={}){let problem=redactText(String(problemContent||"").trim());if(!problem)return"";let reportDiagnostics=diagnostics&&!includeLogs?{...diagnostics,records:Array.isArray(diagnostics.records)?diagnostics.records.filter(record=>record&&typeof record=="object").map(({detail:_detail,...record})=>record):[]}:diagnostics,lines=["# StrataGate \u95EE\u9898\u62A5\u544A","",problem,"","## \u81EA\u52A8\u8BCA\u65AD\u4FE1\u606F","","- StrataGate \u7248\u672C\uFF1A"+(overview.pluginVersion||"unknown"),"- Harness \u7248\u672C\uFF1A"+(overview.harnessVersion||"unknown"),"- blockTurnSize\uFF1A"+(selected?.blockTurnSize??"unknown"),"- \u5DF2\u5C01\u5B58\u5757\uFF1A"+(selected?.blocks??"unknown"),"- Event / Graph Node \u6570\u91CF\uFF1A"+(selected?.events??"unknown")+" / "+(selected?.graphNodes??"unknown"),"- \u5F02\u5E38\u6458\u8981\uFF1A\u89C1\u4E0B\u65B9\u7ED3\u6784\u5316\u7EDF\u8BA1\u4E0E\u8BCA\u65AD\u3002","","> \u6B64\u62A5\u544A\u5728\u6D4F\u89C8\u5668\u672C\u5730\u751F\u6210\u3002\u9ED8\u8BA4\u8BCA\u65AD\u4E0D\u5305\u542B\u539F\u59CB\u804A\u5929\u3001L5\u3001Event \u6216 Graph \u5185\u5BB9\u3002\u6B63\u5219\u8131\u654F\u4EC5\u662F\u7EB5\u6DF1\u9632\u5FA1\uFF0C\u63D0\u4EA4\u524D\u4ECD\u9700\u4EBA\u5DE5\u68C0\u67E5\u3002"];if(lines.push("","## \u8FD1\u671F\u8FD0\u884C\u6458\u8981","","> \u8FD0\u884C\u6570\u636E\u5728\u672C\u5730\u91C7\u96C6\uFF1B\u65F6\u95F4\u8303\u56F4\u3001\u7F3A\u5931\u6570\u636E\u4E0E\u7EDF\u8BA1\u53E3\u5F84\u89C1\u4E0B\u65B9\u3002"),diagnostics){let totals=diagnostics.totals||{},shown=key=>typeof totals[key]=="number"?totals[key]:"\u672A\u53D6\u5F97";lines.push("","- \u7EDF\u8BA1\u8303\u56F4\uFF1A"+(diagnostics.since||"\u672A\u53D6\u5F97")+" \u81F3 "+(diagnostics.through||"\u672A\u53D6\u5F97")+"\uFF08UTC\uFF09","- \u6A21\u578B\u8BF7\u6C42\u6B21\u6570\uFF1A"+shown("modelCalls")+"\uFF1B\u5176\u4E2D\u7F3A\u5C11\u7528\u91CF\u8BB0\u5F55\uFF1A"+shown("missingUsageCalls"),"- \u5DF2\u62A5\u544A Token \u5408\u8BA1\uFF1A"+shown("totalTokens")+"\uFF1B\u5B8C\u6574\u603B\u91CF\u8BB0\u5F55\u7684\u8BF7\u6C42\u6570\uFF1A"+shown("totalTokenCalls"),"- \u8BB0\u5FC6\u64CD\u4F5C\u6210\u529F / \u5931\u8D25\uFF1A"+shown("operationsSucceeded")+" / "+shown("operationsFailed"))}if(lines.push("","### \u7ED3\u6784\u5316\u7EDF\u8BA1\u4E0E\u8BCA\u65AD","","```json",redactedJson(reportDiagnostics||{coverage:{available:!1,note:"\u8FD0\u884C\u7EDF\u8BA1\u5C1A\u672A\u53D6\u5F97\u3002"}}),"```"),willingToContribute&&lines.push("","## \u8D21\u732E\u610F\u613F","","- [x] \u6211\u613F\u610F\u5C1D\u8BD5\u4FEE\u590D\u5E76\u63D0\u4EA4 PR\u3002"),includeLogs){let failedJobs=Array.isArray(selected?.failedJobDetails)?selected.failedJobDetails.map(job=>({id:job?.id,kind:job?.kind,attempts:job?.attempts,lastError:job?.lastErrorFull||job?.lastError,updatedAt:job?.updatedAt,...job?.kind==="topic-projection"?{diagnostics:job?.diagnostics}:{}})):[];lines.push("","## \u8BCA\u65AD\u65E5\u5FD7","","```json",redactedJson({frontendError:recentError||null,failedJobs}),"```")}return includeMemory&&lines.push("","## \u7528\u6237\u4E3B\u52A8\u9644\u52A0\u7684\u8BB0\u5FC6\u6570\u636E\uFF08\u53EF\u80FD\u5305\u542B\u79C1\u4EBA\u5BF9\u8BDD\uFF09","","> \u8B66\u544A\uFF1A\u8FD9\u4E9B\u5185\u5BB9\u53EF\u80FD\u5305\u542B\u79C1\u4EBA\u5BF9\u8BDD\u3002\u81EA\u52A8\u8131\u654F\u4E0D\u80FD\u4FDD\u8BC1\u8BC6\u522B\u6240\u6709\u654F\u611F\u4FE1\u606F\uFF0C\u63D0\u4EA4\u524D\u5FC5\u987B\u4EBA\u5DE5\u68C0\u67E5\u3002","","```json",redactedJson({blocks:Array.isArray(data4?.blocks)?data4.blocks.map(whitelistedBlock):[],events:Array.isArray(data4?.events)?data4.events.map(whitelistedEvent):[],graph:whitelistedGraph(data4?.graph)}),"```"),lines.join(`
1199
1345
  `)}async function copyReportAndOpenIssue(report,clipboard=navigator?.clipboard,openWindow=url=>window.open(url,"_blank"),title=""){let copyPromise=null,copyError="";if(!clipboard?.writeText)copyError="\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236\u3002";else try{copyPromise=Promise.resolve(clipboard.writeText(report))}catch(reason){copyError="\u590D\u5236\u5931\u8D25\uFF1A"+String(reason?.message||reason)}let opened=!1;try{let issueWindow=openWindow(issueUrl(title));opened=!!issueWindow,issueWindow&&(issueWindow.opener=null)}catch{}if(copyError)return{copied:!1,opened,error:copyError};try{return await copyPromise,{copied:!0,opened,error:""}}catch(reason){return{copied:!1,opened,error:"\u590D\u5236\u5931\u8D25\uFF1A"+String(reason?.message||reason)}}}function shouldExpandFeedbackPreview(result){return result?.copied===!1}function handleFeedbackIssueResult(result,callbacks={}){let messages=[];return result?.copied?callbacks.setStatus?.(result.opened?"\u62A5\u544A\u5DF2\u590D\u5236\u3002\u8BF7\u5728\u65B0\u6253\u5F00\u7684 Issue \u4E2D\u7C98\u8D34\u3001\u68C0\u67E5\u5E76\u63D0\u4EA4\u3002":"\u62A5\u544A\u5DF2\u590D\u5236\uFF0C\u4F46\u6D4F\u89C8\u5668\u53EF\u80FD\u62E6\u622A\u4E86\u65B0\u7A97\u53E3\u3002\u8BF7\u70B9\u51FB\u4E0B\u65B9\u666E\u901A\u94FE\u63A5\u6253\u5F00 Issue\u3002"):(shouldExpandFeedbackPreview(result)&&callbacks.setPreviewOpen?.(!0),messages.push((result?.error||"\u590D\u5236\u6216\u6253\u5F00 Issue \u5931\u8D25")+" \u62A5\u544A\u4ECD\u4FDD\u7559\u5728\u9884\u89C8\u4E2D\uFF1B\u8BF7\u624B\u52A8\u590D\u5236\u6216\u4E0B\u8F7D\u8BCA\u65AD\u6587\u4EF6\u3002"+(result?.opened?"":" \u4E5F\u53EF\u70B9\u51FB\u4E0B\u65B9\u666E\u901A\u94FE\u63A5\u6253\u5F00 Issue\u3002")),callbacks.setError?.(current=>current?current+" "+messages.join(" "):messages.join(" "))),result}function downloadSupportReport(report,documentRef=document,urlRef=URL){let blob=new Blob([report],{type:"text/plain;charset=utf-8"}),objectUrl=urlRef.createObjectURL(blob),link=documentRef.createElement("a");link.href=objectUrl,link.download="stratagate-diagnostics.txt",link.style.display="none";try{documentRef.body?.appendChild(link),link.click()}finally{link.remove(),urlRef.revokeObjectURL(objectUrl)}return blob}function SupportPage({namespace,overview,selected,data:data4,recentError,onBack}){let[includeLogs,setIncludeLogs]=React.useState(!1),[includeMemory,setIncludeMemory]=React.useState(!1),[willingToContribute,setWillingToContribute]=React.useState(!1),[status,setStatus]=React.useState(""),[error3,setError]=React.useState(""),[title,setTitle]=React.useState(""),[problemContent,setProblemContent]=React.useState(""),[draftLoading,setDraftLoading]=React.useState(!0),titleTouchedRef=React.useRef(!1),bodyTouchedRef=React.useRef(!1),[aiPromptCopied,setAiPromptCopied]=React.useState(!1),[previewOpen,setPreviewOpen]=React.useState(!1),[feedbackStep,setFeedbackStep]=React.useState(0),[reviewedReport,setReviewedReport]=React.useState(null),feedbackHeadingRef=React.useRef(null),previousFeedbackStepRef=React.useRef(0),aiNoticeRef=React.useRef(null),diagnosticsRef=React.useRef(null);React.useEffect(()=>{previousFeedbackStepRef.current!==feedbackStep&&feedbackHeadingRef.current?.focus({preventScroll:!0}),previousFeedbackStepRef.current=feedbackStep},[feedbackStep]),React.useEffect(()=>{let active=!0;return titleTouchedRef.current=!1,bodyTouchedRef.current=!1,setDraftLoading(!0),Promise.resolve().then(()=>api2("feedback",{namespace})).then(result=>{if(!active||(diagnosticsRef.current=result?.diagnostics||null,!result?.draft))return;let restored=restoreFeedbackDraftValues(result.draft,{title:titleTouchedRef.current,body:bodyTouchedRef.current});titleTouchedRef.current||setTitle(restored.title),bodyTouchedRef.current||setProblemContent(restored.problemContent),result.draft.aiPrepared&&restored.problemContent&&!titleTouchedRef.current&&!bodyTouchedRef.current&&(setReviewedReport(Object.freeze({title:restored.title,text:buildSupportReport({problemContent:restored.problemContent,overview,selected,data:data4,recentError,diagnostics:diagnosticsRef.current})})),setFeedbackStep(1))}).catch(reason=>{active&&setError("\u8BFB\u53D6\u53CD\u9988\u8349\u7A3F\u5931\u8D25\uFF1A"+String(reason?.message||reason))}).finally(()=>{active&&setDraftLoading(!1)}),()=>{active=!1}},[namespace]),React.useEffect(()=>{if(!aiPromptCopied)return;let reveal=()=>aiNoticeRef.current?.scrollIntoView({behavior:"smooth",block:"start"});if(typeof window.requestAnimationFrame!="function"){reveal();return}let frame=window.requestAnimationFrame(reveal);return()=>window.cancelAnimationFrame?.(frame)},[aiPromptCopied]);let saveDraft=async()=>{namespace&&await api2("feedback",{},{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({namespace,title,bodyMarkdown:problemContent})})},reportSnapshot=Object.freeze({text:buildSupportReport({problemContent,overview,selected,data:data4,recentError,includeLogs,includeMemory,willingToContribute,diagnostics:diagnosticsRef.current}),title}),reportBytes=reportSnapshot.text?new Blob([reportSnapshot.text]).size:0,hasProblem=!!problemContent.trim(),persistDraft=()=>{setStatus(""),setError(""),saveDraft().then(()=>setStatus("\u53CD\u9988\u8349\u7A3F\u5DF2\u4FDD\u5B58\u5728\u672C\u5730\u3002")).catch(reason=>setError("\u4FDD\u5B58\u53CD\u9988\u8349\u7A3F\u5931\u8D25\uFF1A"+String(reason?.message||reason)))},copyAndOpen=()=>{setStatus(""),setError(""),saveDraft().catch(reason=>setError(current=>{let message="\u4FDD\u5B58\u53CD\u9988\u8349\u7A3F\u5931\u8D25\uFF1A"+String(reason?.message||reason);return current?current+" "+message:message})),copyReportAndOpenIssue(reportSnapshot.text,navigator?.clipboard,url=>window.open(url,"_blank"),title).then(result=>handleFeedbackIssueResult(result,{setStatus,setError,setPreviewOpen})).catch(reason=>setError(current=>{let message="\u590D\u5236\u6216\u6253\u5F00 Issue \u5931\u8D25\uFF1A"+String(reason?.message||reason);return current?current+" "+message:message}))},copyAndEmail=()=>{setStatus(""),setError(""),saveDraft().catch(reason=>setError(current=>{let message="\u4FDD\u5B58\u53CD\u9988\u8349\u7A3F\u5931\u8D25\uFF1A"+String(reason?.message||reason);return current?current+" "+message:message})),copyReportAndComposeEmail(reportSnapshot.text,navigator?.clipboard,void 0,title).then(result=>handleFeedbackEmailResult(result,{setStatus,setError,setPreviewOpen})).catch(reason=>setError(current=>{let message="\u51C6\u5907\u90AE\u4EF6\u53CD\u9988\u5931\u8D25\uFF1A"+String(reason?.message||reason);return current?current+" "+message:message}))},copyEmail=async()=>{if(setStatus(""),GITHUB_FEEDBACK_ENABLED&&setError(""),!navigator?.clipboard?.writeText){setError("\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u90AE\u7BB1\uFF1A"+FEEDBACK_EMAIL);return}try{await navigator.clipboard.writeText(FEEDBACK_EMAIL),setStatus("\u90AE\u7BB1\u5DF2\u590D\u5236\uFF1A"+FEEDBACK_EMAIL)}catch{setError("\u590D\u5236\u90AE\u7BB1\u5931\u8D25\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\uFF1A"+FEEDBACK_EMAIL)}},copyAiPrompt=()=>{if(setStatus(""),setError(""),!navigator?.clipboard?.writeText){setError("\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236\u3002\u8BF7\u5C55\u5F00\u4E0B\u65B9\u63D0\u793A\u8BCD\u5E76\u624B\u52A8\u590D\u5236\u3002");return}navigator.clipboard.writeText(FEEDBACK_AI_PROMPT).then(()=>setAiPromptCopied(!0)).catch(reason=>setError("\u590D\u5236 AI \u63D0\u793A\u8BCD\u5931\u8D25\uFF1A"+String(reason?.message||reason)))},download=()=>{setStatus(""),setError("");try{downloadSupportReport(GITHUB_FEEDBACK_ENABLED?reportSnapshot.text:reviewedReport?.text||""),setStatus("\u8BCA\u65AD\u6587\u4EF6\u5DF2\u4E0B\u8F7D\u3002\u6587\u4EF6\u5185\u5BB9\u4E0E\u5F53\u524D\u9884\u89C8\u5B8C\u5168\u4E00\u81F4\u3002")}catch(reason){setError("\u4E0B\u8F7D\u5931\u8D25\uFF1A"+String(reason?.message||reason)+"\u3002\u62A5\u544A\u4ECD\u4FDD\u7559\u5728\u9884\u89C8\u4E2D\uFF0C\u53EF\u624B\u52A8\u590D\u5236\u3002")}};if(!GITHUB_FEEDBACK_ENABLED){let review=()=>{!hasProblem||draftLoading||(setStatus(""),setError(""),setReviewedReport(reportSnapshot),setFeedbackStep(1),saveDraft().catch(reason=>setError("\u4FDD\u5B58\u53CD\u9988\u8349\u7A3F\u5931\u8D25\uFF1A"+String(reason?.message||reason))))},edit=()=>{setFeedbackStep(0),setReviewedReport(null),setStatus(""),setError("")},copyReport=async()=>{if(reviewedReport?.text){setStatus("");try{if(!globalThis.navigator?.clipboard?.writeText)throw new Error("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236");await globalThis.navigator.clipboard.writeText(reviewedReport.text),setStatus("\u62A5\u544A\u5DF2\u590D\u5236\u3002\u8BF7\u5728\u81EA\u5DF1\u7684\u90AE\u7BB1\u4E2D\u7C98\u8D34\u3001\u68C0\u67E5\u5E76\u53D1\u9001\u3002")}catch{setError("\u65E0\u6CD5\u81EA\u52A8\u590D\u5236\u3002\u4E0B\u65B9\u4FDD\u7559\u5B8C\u6574\u62A5\u544A\uFF0C\u53EF\u9009\u4E2D\u624B\u52A8\u590D\u5236\uFF0C\u6216\u4E0B\u8F7D\u62A5\u544A\u3002")}}};return h(React.Fragment,null,h(BackBar,{label:"\u66F4\u591A",onBack}),h("section",{className:"sg-feedback-wizard","aria-label":"StrataGate \u63D2\u4EF6\u53CD\u9988"},h("div",{className:"sg-feedback-heading"},h("h2",{ref:feedbackHeadingRef,tabIndex:-1},"\u53CD\u9988 StrataGate"),h("p",null,feedbackStep===0?"\u8BA9 AI \u6839\u636E\u521A\u624D\u7684\u4F1A\u8BDD\u6574\u7406\uFF0C\u4F60\u4E5F\u53EF\u4EE5\u8865\u5145\u4E00\u4E24\u53E5\u3002\u8FD0\u884C\u6458\u8981\u4F1A\u81EA\u52A8\u52A0\u5165\u62A5\u544A\u3002":"\u68C0\u67E5\u4E0B\u9762\u7684\u5B8C\u6574\u62A5\u544A\uFF0C\u518D\u590D\u5236\u5230\u81EA\u5DF1\u7684\u90AE\u7BB1\u53D1\u9001\u3002")),draftLoading?h("p",{className:"sg-support-sync",role:"status"},"\u6B63\u5728\u8BFB\u53D6\u672C\u5730\u53CD\u9988\u8349\u7A3F\u2026"):null,feedbackStep===0?h("section",{className:"sg-feedback-stage","aria-label":"\u7F16\u8F91\u53CD\u9988"},AGENT_FEEDBACK_ENABLED?h("div",{className:"sg-feedback-actions"},h("button",{type:"button",className:"sg-quiet-button",onClick:copyAiPrompt},"\u8BA9 AI \u6574\u7406\u53CD\u9988")):null,AGENT_FEEDBACK_ENABLED?h("details",null,h("summary",null,"\u67E5\u770B AI \u63D0\u793A\u8BCD"),h("pre",{className:"sg-raw-json sg-code"},FEEDBACK_AI_PROMPT)):null,aiPromptCopied?h("p",{ref:aiNoticeRef,role:"status"},"\u63D0\u793A\u8BCD\u5DF2\u590D\u5236\u3002\u56DE\u5230\u521A\u624D\u7684\u4F1A\u8BDD\uFF0C\u7C98\u8D34\u5E76\u53D1\u9001\uFF0CAI \u4F1A\u751F\u6210\u672C\u5730\u8349\u7A3F\u3002"):null,h("label",{className:"sg-support-field"},h("span",null,"\u95EE\u9898\u5185\u5BB9"),h("textarea",{className:"sg-support-description",rows:7,value:problemContent,onChange:event3=>{bodyTouchedRef.current=!0,setProblemContent(event3.target.value)},onBlur:persistDraft,placeholder:"\u53EF\u4EE5\u8BA9 AI \u6574\u7406\u540E\u518D\u8865\u5145\uFF0C\u4E5F\u53EF\u4EE5\u76F4\u63A5\u63CF\u8FF0\u95EE\u9898\u3001\u5EFA\u8BAE\u6216\u7591\u95EE\u3002","aria-label":"\u95EE\u9898\u5185\u5BB9"})),h("label",{className:"sg-support-field"},h("span",null,"\u90AE\u4EF6\u4E3B\u9898\uFF08\u53EF\u9009\uFF09"),h("input",{className:"sg-support-input",value:title,onChange:event3=>{titleTouchedRef.current=!0,setTitle(event3.target.value)},onBlur:persistDraft})),h("fieldset",{className:"sg-feedback-options"},h("legend",null,"\u9644\u52A0\u4FE1\u606F"),h("p",null,"\u9ED8\u8BA4\u5305\u542B\u57FA\u7840\u8BCA\u65AD\u3001\u8FD1\u671F\u8FD0\u884C\u7EDF\u8BA1\u548C\u5F02\u5E38\u5206\u7C7B\uFF1B\u4EE5\u4E0B\u5185\u5BB9\u7531\u4F60\u9009\u62E9\u52A0\u5165\u3002"),h("div",{className:"sg-feedback-checks"},h("label",{className:"sg-check"},h("input",{type:"checkbox",checked:includeLogs,onChange:event3=>setIncludeLogs(event3.target.checked),"aria-label":"\u52A0\u5165\u65E5\u5FD7"}),h("span",null,"\u52A0\u5165\u8BE6\u7EC6\u9519\u8BEF\u65E5\u5FD7")),h("label",{className:"sg-check"},h("input",{type:"checkbox",checked:includeMemory,onChange:event3=>setIncludeMemory(event3.target.checked),"aria-label":"\u52A0\u5165\u8BB0\u5FC6\u5185\u5BB9"}),h("span",null,"\u52A0\u5165\u8BB0\u5FC6\u5185\u5BB9"))),includeMemory?h("p",{className:"sg-error-note"},"\u8BB0\u5FC6\u5185\u5BB9\u53EF\u80FD\u5305\u542B\u79C1\u4EBA\u5BF9\u8BDD\uFF0C\u8BF7\u9010\u9879\u68C0\u67E5\u540E\u53D1\u9001\u3002"):null),hasProblem?null:h("p",{className:"sg-support-empty"},"\u6709\u4E86\u95EE\u9898\u63CF\u8FF0\u540E\uFF0C\u5373\u53EF\u68C0\u67E5\u62A5\u544A\u3002"),h("div",{className:"sg-feedback-actions"},h("button",{type:"button",className:"sg-primary-link",disabled:!hasProblem||draftLoading,onClick:review},"\u68C0\u67E5\u62A5\u544A"))):null,feedbackStep>0&&reviewedReport?h("section",{className:"sg-feedback-stage","aria-label":"\u68C0\u67E5\u5E76\u53D1\u9001\u53CD\u9988"},h("div",{className:"sg-feedback-ready"},h("span",{className:"sg-feedback-unsent"},"\u5C1A\u672A\u53D1\u9001"),h("p",null,"\u62A5\u544A\u5305\u542B\u95EE\u9898\u63CF\u8FF0\u548C\u672C\u5730\u8FD0\u884C\u6458\u8981\u3002\u8BF7\u68C0\u67E5\u51ED\u636E\u4E0E\u79C1\u4EBA\u5185\u5BB9\uFF1B\u53EF\u8FD4\u56DE\u4FEE\u6539\u3002")),h("label",{className:"sg-support-field"},h("span",null,"\u5B8C\u6574\u62A5\u544A \xB7 "+new Blob([reviewedReport.text]).size+" \u5B57\u8282"),h("textarea",{className:"sg-support-preview",readOnly:!0,value:reviewedReport.text,spellCheck:!1,"aria-label":"\u672C\u5730\u53CD\u9988\u62A5\u544A\u9884\u89C8"})),h("div",{className:"sg-feedback-actions"},h("button",{type:"button",className:"sg-primary-link",onClick:copyReport},"\u590D\u5236\u62A5\u544A"),h("button",{type:"button",className:"sg-quiet-button",onClick:edit},"\u4FEE\u6539\u6216\u8865\u5145"),h("button",{type:"button",className:"sg-quiet-button",onClick:download},"\u4E0B\u8F7D\u62A5\u544A")),h("section",{className:"sg-feedback-contact","aria-label":"\u90AE\u4EF6\u53D1\u9001\u4FE1\u606F"},h("p",{className:"sg-feedback-email"},FEEDBACK_EMAIL),h("button",{type:"button",className:"sg-quiet-button",onClick:copyEmail},"\u590D\u5236\u90AE\u7BB1"),h("p",null,"\u90AE\u4EF6\u4E3B\u9898\uFF1AStrataGate \u53CD\u9988"+(reviewedReport.title?"\uFF1A"+reviewedReport.title:"")),h("p",{className:"sg-feedback-caption"},"\u5728\u81EA\u5DF1\u7684\u90AE\u7BB1\u586B\u5199\u6536\u4EF6\u5730\u5740\uFF0C\u7C98\u8D34\u62A5\u544A\u540E\u53D1\u9001\u3002")),h("p",{className:"sg-feedback-caption"},"\u8D44\u6599\u4FDD\u5B58\u5728\u672C\u5730\uFF1B\u4F5C\u8005\u5728\u6536\u5230\u4F60\u53D1\u9001\u7684\u90AE\u4EF6\u540E\u624D\u80FD\u67E5\u770B\u3002")):null,status?h("p",{className:"sg-support-status",role:"status","aria-live":"polite"},status):null,error3?h("p",{className:"sg-support-error",role:"alert"},error3):null))}return h(React.Fragment,null,h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u53CD\u9988\u4E0E\u652F\u6301"),h("p",null,GITHUB_FEEDBACK_ENABLED?"\u62A5\u544A\u53EA\u5728\u672C\u5730\u751F\u6210\u3002\u53EA\u6709\u4F60\u4E3B\u52A8\u7C98\u8D34\u6216\u4E0A\u4F20\u540E\uFF0C\u5185\u5BB9\u624D\u4F1A\u8FDB\u5165 GitHub\u3002":"\u62A5\u544A\u53EA\u5728\u672C\u5730\u751F\u6210\u3002\u8BF7\u901A\u8FC7\u90AE\u4EF6\u53CD\u9988\u95EE\u9898\uFF0C\u68C0\u67E5\u5185\u5BB9\u540E\u81EA\u884C\u53D1\u9001\u3002")),GITHUB_FEEDBACK_ENABLED&&aiPromptCopied?h("div",{ref:aiNoticeRef,className:"sg-support-ai-notice",role:"status","aria-live":"polite"},h("span",{className:"sg-support-ai-notice-mark","aria-hidden":"true"},"\u2713"),h("div",null,h("strong",null,"AI \u63D0\u793A\u8BCD\u5DF2\u590D\u5236"),h("p",null,"\u4E0B\u4E00\u6B65\uFF1A\u56DE\u5230\u521A\u624D\u51FA\u73B0\u95EE\u9898\u7684\u4F1A\u8BDD\uFF0C\u76F4\u63A5\u7C98\u8D34\u5E76\u53D1\u9001\u3002"),h("p",null,"Agent \u4F1A\u6839\u636E\u521A\u624D\u7684\u4F1A\u8BDD\u6574\u7406\u95EE\u9898\uFF0C\u5E76\u81EA\u52A8\u521B\u5EFA\u53CD\u9988\u8349\u7A3F\u3002"),h("button",{type:"button",className:"sg-quiet-button",onClick:copyAiPrompt},"\u518D\u6B21\u590D\u5236\u63D0\u793A\u8BCD")),h("button",{type:"button",className:"sg-support-ai-notice-close",onClick:()=>setAiPromptCopied(!1),"aria-label":"\u5173\u95ED AI \u63D0\u793A\u8BCD\u63D0\u793A"},"\xD7")):null,h("div",{className:"sg-privacy-note"},GITHUB_FEEDBACK_ENABLED?"GitHub \u94FE\u63A5\u4E0D\u5305\u542B\u62A5\u544A\u6B63\u6587\u3001\u8BCA\u65AD\u65E5\u5FD7\u6216\u8BB0\u5FC6\u6570\u636E\u3002StrataGate \u6C38\u8FDC\u4E0D\u4F1A\u81EA\u52A8\u63D0\u4EA4 Issue\u3002":"\u90AE\u4EF6\u94FE\u63A5\u53EA\u9884\u586B\u4E3B\u9898\u548C\u7C98\u8D34\u63D0\u793A\uFF0C\u4E0D\u5305\u542B\u62A5\u544A\u6B63\u6587\u3001\u8BCA\u65AD\u65E5\u5FD7\u6216\u8BB0\u5FC6\u6570\u636E\u3002StrataGate \u4E0D\u4F1A\u81EA\u52A8\u53D1\u9001\u90AE\u4EF6\u3002"),GITHUB_FEEDBACK_ENABLED?null:h("section",{className:"sg-support-card"},h("h3",null,"\u53CD\u9988\u90AE\u7BB1"),h("p",null,h("a",{className:"sg-link",href:feedbackEmailUrl(title)},FEEDBACK_EMAIL)),h("button",{type:"button",className:"sg-quiet-button",onClick:copyEmail},"\u590D\u5236\u90AE\u7BB1"),h("p",null,"\u82E5\u70B9\u51FB\u94FE\u63A5\u540E\u6CA1\u6709\u6253\u5F00\u90AE\u4EF6\u5E94\u7528\uFF0C\u53EF\u590D\u5236\u90AE\u7BB1\uFF0C\u5728\u5E38\u7528\u90AE\u7BB1\u4E2D\u64B0\u5199\u90AE\u4EF6\uFF1B\u8BCA\u65AD\u6587\u4EF6\u53EF\u624B\u52A8\u6DFB\u52A0\u4E3A\u9644\u4EF6\u3002")),h("section",{className:"sg-support-card sg-support-compose"},h("div",{className:"sg-support-compose-head"},h("div",null,h("h3",null,"\u63CF\u8FF0\u95EE\u9898"),h("p",null,"\u81EA\u7531\u63CF\u8FF0\u5373\u53EF\uFF0C\u4E0D\u9700\u8981\u586B\u5199\u591A\u7EC4\u5FC5\u586B\u8868\u5355\u3002")),GITHUB_FEEDBACK_ENABLED?h("button",{type:"button",className:"sg-support-ai",onClick:copyAiPrompt},"AI \u5E2E\u6211\u586B"):null),h("label",{className:"sg-support-field"},h("span",null,GITHUB_FEEDBACK_ENABLED?"Issue \u6807\u9898\uFF08\u53EF\u9009\uFF09":"\u90AE\u4EF6\u4E3B\u9898\uFF08\u53EF\u9009\uFF09"),h("input",{className:"sg-support-input",value:title,onChange:event3=>{titleTouchedRef.current=!0,setTitle(event3.target.value)},onBlur:persistDraft,placeholder:"\u7B80\u77ED\u6982\u62EC\u95EE\u9898"})),h("label",{className:"sg-support-field"},h("span",null,"\u95EE\u9898\u5185\u5BB9"),h("textarea",{className:"sg-support-description",value:problemContent,onChange:event3=>{bodyTouchedRef.current=!0,setProblemContent(event3.target.value)},onBlur:persistDraft,placeholder:GITHUB_FEEDBACK_ENABLED?"\u63CF\u8FF0\u521A\u624D\u53D1\u751F\u4E86\u4EC0\u4E48\uFF1B\u4E5F\u53EF\u4EE5\u70B9\u51FB\u201CAI \u5E2E\u6211\u586B\u201D\u3002":"\u63CF\u8FF0\u53D1\u751F\u4E86\u4EC0\u4E48\u3001\u590D\u73B0\u6B65\u9AA4\uFF0C\u4EE5\u53CA\u9884\u671F\u548C\u5B9E\u9645\u7ED3\u679C\u3002","aria-label":"\u95EE\u9898\u5185\u5BB9"})),GITHUB_FEEDBACK_ENABLED?h("details",null,h("summary",null,"\u67E5\u770B\u53EF\u624B\u52A8\u590D\u5236\u7684 AI \u63D0\u793A\u8BCD"),h("pre",{className:"sg-raw-json sg-code"},FEEDBACK_AI_PROMPT)):null,draftLoading?h("div",{className:"sg-support-sync"},"\u6B63\u5728\u8BFB\u53D6\u672C\u5730\u53CD\u9988\u8349\u7A3F\u2026"):null),h("section",{className:"sg-support-card"},h("h3",null,"\u9644\u52A0\u4FE1\u606F"),h("p",null,"\u57FA\u7840\u8BCA\u65AD\u9ED8\u8BA4\u5305\u542B\uFF1B\u65E5\u5FD7\u548C\u8BB0\u5FC6\u6570\u636E\u53EA\u6709\u5728\u4F60\u4E3B\u52A8\u52FE\u9009\u540E\u624D\u4F1A\u52A0\u5165\u3002"),h("label",{className:"sg-check"},h("input",{type:"checkbox",checked:!0,disabled:!0}),h("span",null,"\u9ED8\u8BA4\u57FA\u7840\u8BCA\u65AD")),h("label",{className:"sg-check"},h("input",{type:"checkbox",checked:includeLogs,onChange:event3=>setIncludeLogs(event3.target.checked)}),h("span",null,"\u9644\u52A0\u8BCA\u65AD\u65E5\u5FD7")),h("label",{className:"sg-check"},h("input",{type:"checkbox",checked:includeMemory,onChange:event3=>setIncludeMemory(event3.target.checked)}),h("span",null,"\u9644\u52A0\u8BB0\u5FC6\u6570\u636E\uFF08\u53EF\u80FD\u5305\u542B\u5BF9\u8BDD\u5185\u5BB9\uFF09")),includeMemory?h("div",{className:"sg-error-note"},"\u8B66\u544A\uFF1A\u5185\u5BB9\u53EF\u80FD\u5305\u542B\u79C1\u4EBA\u5BF9\u8BDD\uFF1B\u81EA\u52A8\u8131\u654F\u4E0D\u80FD\u4FDD\u8BC1\u8BC6\u522B\u6240\u6709\u654F\u611F\u4FE1\u606F\uFF1B\u63D0\u4EA4\u524D\u5FC5\u987B\u4EBA\u5DE5\u68C0\u67E5\u3002"):null,GITHUB_FEEDBACK_ENABLED?h("label",{className:"sg-check"},h("input",{type:"checkbox",checked:willingToContribute,onChange:event3=>setWillingToContribute(event3.target.checked)}),h("span",null,"\u6211\u613F\u610F\u5C1D\u8BD5\u4FEE\u590D\u5E76\u63D0\u4EA4 PR")):null,hasProblem?null:h("div",{className:"sg-support-empty"},GITHUB_FEEDBACK_ENABLED?"\u8BF7\u5148\u63CF\u8FF0\u95EE\u9898\uFF0C\u6216\u4F7F\u7528 AI \u5E2E\u4F60\u586B\u5199\u3002":"\u8BF7\u5148\u63CF\u8FF0\u95EE\u9898\uFF0C\u518D\u590D\u5236\u62A5\u544A\u5E76\u901A\u8FC7\u90AE\u4EF6\u53D1\u9001\u3002"),h("div",{className:"sg-support-actions"},h("button",{type:"button",className:"sg-primary-link",disabled:!hasProblem,onClick:GITHUB_FEEDBACK_ENABLED?copyAndOpen:copyAndEmail},GITHUB_FEEDBACK_ENABLED?"\u590D\u5236\u62A5\u544A\u5E76\u6253\u5F00 GitHub Issue":"\u590D\u5236\u62A5\u544A\u5E76\u64B0\u5199\u90AE\u4EF6"),h("button",{type:"button",className:"sg-quiet-button",disabled:!hasProblem,onClick:()=>setPreviewOpen(open=>!open),"aria-expanded":previewOpen},previewOpen?"\u6536\u8D77\u5C06\u590D\u5236\u7684\u5185\u5BB9":"\u67E5\u770B\u5C06\u590D\u5236\u7684\u5185\u5BB9"),h("button",{type:"button",className:"sg-quiet-button",disabled:!hasProblem,onClick:download},"\u4E0B\u8F7D\u8BCA\u65AD\u6587\u4EF6"),GITHUB_FEEDBACK_ENABLED?h("a",{className:"sg-link",href:issueUrl(title),target:"_blank",rel:"noopener noreferrer"},"\u4EC5\u6253\u5F00 GitHub Issue"):h("a",{className:"sg-link",href:feedbackEmailUrl(title)},"\u4EC5\u64B0\u5199\u90AE\u4EF6")),hasProblem&&previewOpen?h("div",{className:"sg-support-preview-panel",role:"region","aria-label":"\u5C06\u590D\u5236\u7684\u53CD\u9988\u62A5\u544A"},h("div",{className:"sg-support-preview-head"},h("strong",null,"\u5C06\u590D\u5236\u7684\u5185\u5BB9"),h("div",{className:"sg-support-metrics"},reportSnapshot.text.length+" \u4E2A\u5B57\u7B26 \xB7 "+reportBytes+" \u5B57\u8282")),includeMemory?h("div",{className:"sg-error-note"},"\u5DF2\u5305\u542B\u4F60\u4E3B\u52A8\u52FE\u9009\u7684 Memory \u6570\u636E\uFF0C\u8BF7\u9010\u9879\u68C0\u67E5\u8131\u654F\u7ED3\u679C\u548C\u79C1\u4EBA\u5BF9\u8BDD\u3002"):null,h("textarea",{id:"sg-support-preview",className:"sg-support-preview",readOnly:!0,value:reportSnapshot.text,spellCheck:!1,"aria-label":"\u672C\u5730\u53CD\u9988\u62A5\u544A\u9884\u89C8"})):null,status?h("div",{className:"sg-support-status",role:"status"},status):null,error3?h("div",{className:"sg-support-error",role:"alert"},error3):null),GITHUB_FEEDBACK_ENABLED?h("section",{className:"sg-support-card"},h("h3",null,"\u529F\u80FD\u5EFA\u8BAE"),h("p",null,"GitHub \u5165\u53E3\u4E0D\u4F1A\u9884\u586B\u6B63\u6587\uFF0C\u8BF7\u5728\u9875\u9762\u4E2D\u4E3B\u52A8\u586B\u5199\u5E76\u63D0\u4EA4\u3002"),h("a",{className:"sg-link",href:ISSUE_URL,target:"_blank",rel:"noopener noreferrer"},"\u521B\u5EFA Feature Request \u2192")):h("section",{className:"sg-support-card"},h("h3",null,"\u529F\u80FD\u5EFA\u8BAE"),h("p",null,"\u6B22\u8FCE\u901A\u8FC7\u90AE\u4EF6\u63D0\u51FA\u529F\u80FD\u5EFA\u8BAE\u3002"),h("a",{className:"sg-link",href:feedbackEmailUrl("\u529F\u80FD\u5EFA\u8BAE")},"\u53D1\u9001\u529F\u80FD\u5EFA\u8BAE \u2192")),GITHUB_FEEDBACK_ENABLED?h("section",{className:"sg-support-card"},h("h3",null,"\u4F7F\u7528\u7591\u95EE"),h("p",null,"\u5728 GitHub Discussion \u7684 Q&A \u533A\u4EA4\u6D41\u4F7F\u7528\u65B9\u6CD5\u3002"),h("a",{className:"sg-link",href:DISCUSSION_URL,target:"_blank",rel:"noopener noreferrer"},"\u524D\u5F80 Discussion / Q&A \u2192")):h("section",{className:"sg-support-card"},h("h3",null,"\u4F7F\u7528\u7591\u95EE"),h("p",null,"\u6B22\u8FCE\u901A\u8FC7\u90AE\u4EF6\u54A8\u8BE2\u4F7F\u7528\u65B9\u6CD5\u3002"),h("a",{className:"sg-link",href:feedbackEmailUrl("\u4F7F\u7528\u7591\u95EE")},"\u90AE\u4EF6\u54A8\u8BE2 \u2192")))}function StructurePage({events,eventPage,graph,openEvent,namespace,onBack}){let pagedEvents=usePagedMemory({namespace,kind:"events",initialItems:events,initialPage:eventPage,fallbackLimit:40});return h(React.Fragment,null,h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u8BB0\u5FC6\u7ED3\u6784"),h("p",null,"\u5B8C\u6574\u6D4F\u89C8\u73B0\u6709\u7ED3\u6784\u5316\u8BB0\u5FC6")),h("div",{className:"sg-counts"},h("div",null,h("div",{className:"sg-count-value"},pagedEvents.page.total),h("div",{className:"sg-count-label"},"\u7ECF\u5386 / Event")),h("div",null,h("div",{className:"sg-count-value"},graph.nodes.length),h("div",{className:"sg-count-label"},"\u77E5\u8BC6\u56FE\u8C31\u8282\u70B9"))),h("div",{className:"sg-structured-group"},h("h3",{className:"sg-section-title"},"\u7ECF\u5386"),pagedEvents.items.map(event3=>h("button",{key:event3.id,className:"sg-related",onClick:()=>openEvent(event3)},h("span",null,event3.title),h("span",{className:"sg-related-time"},formatTime(event3.updatedAt))))),h(Pagination,{page:pagedEvents.page,loading:pagedEvents.loading,error:pagedEvents.error,onOffset:pagedEvents.loadOffset}),h("div",{className:"sg-structured-group"},h("h3",{className:"sg-section-title"},"\u56FE\u8C31\u8282\u70B9"),graph.nodes.map(node=>h("div",{key:node.id,className:"sg-related"},h("span",null,node.name),h("span",{className:"sg-related-time"},(node.sourceEventIds||[]).length+" \u6761\u652F\u6491\u4E8B\u4EF6")))))}let DUPLICATE_STYLES=`
1200
1346
  .sg-memory-review .sg-header{padding:10px 12px;margin-bottom:12px}.sg-memory-review .sg-logo{width:28px;height:28px}.sg-memory-review .sg-brand-name{font-size:14px}.sg-memory-review .sg-header-row-secondary{margin-top:4px}.sg-memory-review .sg-tabs{margin-bottom:12px}.sg-memory-review .sg-dup-heading h2{font-size:21px}
@@ -1220,4 +1366,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1220
1366
  @container(max-width:600px){.sg-dup-options{grid-template-columns:1fr}.sg-dup-option{padding:12px}.sg-dup-draft-heading{flex-wrap:wrap}}
1221
1367
  @media(prefers-reduced-motion:reduce){.sg-dup-draft-skeleton span{animation:none}}
1222
1368
  @container(max-width:420px){.sg-dup-comparison,.sg-dup-methods{grid-template-columns:1fr}.sg-dup-heading h2{font-size:21px}.sg-dup-card-body{padding:13px}.sg-dup-actions>div{width:100%;justify-content:space-between}.sg-dup-button.primary{flex:1}.sg-dup-preview{padding:13px}}
1223
- `;function DuplicateIcon({kind="cards",size:size3=17}){let paths={cards:"M7 3H3v14h10v-4M7 3v10h10V3H7Z",check:"m4 10 4 4 8-8",info:"M10 9v5m0-8v.2M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Z",back:"m12 5-5 5 5 5",next:"m8 5 5 5-5 5",merge:"M4 3v3c0 3 6 3 6 6v5m6-14v3c0 3-6 3-6 6m-3 2 3 3 3-3"};return h("svg",{width:size3,height:size3,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},h("path",{d:paths[kind]||paths.cards}))}function DuplicateEvidence({namespace,card,hideSummary=!1}){let[result,setResult]=React.useState(null),[error3,setError]=React.useState(""),[attempt,setAttempt]=React.useState(0);return React.useEffect(()=>{let active=!0;return setResult(null),setError(""),api2("sources",{namespace,eventId:card.id}).then(value=>{active&&setResult(value)}).catch(reason=>{active&&setError(String(reason.message||reason))}),()=>{active=!1}},[namespace,card.id,attempt]),h("section",{className:"sg-dup-source","aria-label":"\u5B8C\u6574\u8BB0\u5FC6\u4E0E\u6765\u6E90"},h("h4",null,hideSummary?"\u539F\u59CB\u6765\u6E90":"\u5B8C\u6574\u8BB0\u5FC6\u4E0E\u6765\u6E90"),hideSummary?null:h("p",{className:"sg-dup-summary"},card.summary),error3?h("div",{role:"alert"},error3,h("button",{type:"button",className:"sg-dup-button",onClick:()=>setAttempt(value=>value+1)},"\u91CD\u8BD5\u8BFB\u53D6\u6765\u6E90")):result?result.messages?.length?h("div",{className:"sg-citation-messages"},result.messages.map(message=>h("div",{key:message.id,className:"sg-citation-message"},h("span",{className:"sg-citation-message-role"},(message.role||"Recorded")+(message.createdAt?" \xB7 "+exactTime(message.createdAt):"")),String(message.content||"")))):h("p",null,"\u5F53\u524D\u6CA1\u6709\u53EF\u663E\u793A\u7684\u539F\u59CB\u6765\u6E90\u6D88\u606F\u3002"):h("p",{role:"status"},"\u6B63\u5728\u8BFB\u53D6\u6765\u6E90\u2026"))}function DuplicateCard({card,letter,selected,onSelect,unavailable,disabled,namespace,fullContent=!1,selectionMade=!1}){let[expanded,setExpanded]=React.useState(!1),[showSource,setShowSource]=React.useState(!1),sourcePosition=React.useRef(null);(React.useLayoutEffect||React.useEffect)(()=>{if(showSource||!sourcePosition.current)return;let{trigger,ancestors,top,left}=sourcePosition.current;trigger?.focus?.({preventScroll:!0});for(let saved of ancestors)saved.node.scrollTop=saved.top,saved.node.scrollLeft=saved.left;window.scrollTo?.(left,top),sourcePosition.current=null},[showSource]);let toggleSource=event3=>{if(!showSource){let ancestors=[];for(let node=event3.currentTarget.parentElement;node;node=node.parentElement)node.scrollHeight>node.clientHeight&&ancestors.push({node,top:node.scrollTop,left:node.scrollLeft});sourcePosition.current={trigger:event3.currentTarget,ancestors,top:window.scrollY||0,left:window.scrollX||0}}setShowSource(value=>!value)};if(!card)return h("article",{className:"sg-dup-card"},h("div",{className:"sg-dup-card-body"},h("h3",null,"\u8BB0\u5FC6 "+letter),h("p",null,"\u539F\u5361\u5DF2\u4E0D\u53EF\u7528")));let status={active:"\u5F53\u524D\u6709\u6548",superseded:"\u5DF2\u88AB\u66FF\u4EE3",archived:"\u5DF2\u5F52\u6863",forgotten:"\u5DF2\u9057\u5FD8"},criticality={routine:"\u4E00\u822C\u8BB0\u5FC6",preference:"\u504F\u597D",identity:"\u4E2A\u4EBA\u7ECF\u5386",safety:"\u91CD\u8981\u7EA6\u675F"},scope={user:"\u4E2A\u4EBA",project:"\u9879\u76EE",session:"\u672C\u6B21\u4F1A\u8BDD"},temporal=card.temporal||{},date=temporal.happenedStart||temporal.originalText;return h("article",{className:"sg-dup-card"+(selected?" selected":"")+(card.status==="archived"?" archived":"")},h("label",{className:"sg-dup-choice"},onSelect?h("input",{id:"sg-retain-"+card.id,type:"radio",name:"duplicate-retained",checked:selected,disabled:disabled||!!unavailable,onChange:onSelect,"aria-label":"\u53EA\u4FDD\u7559 "+letter+"\uFF1A"+card.title}):h("span",{className:"sg-dup-letter"},letter),h("span",null,onSelect?"\u53EA\u4FDD\u7559 "+letter:"\u8BB0\u5FC6 "+letter),h("em",null,status[card.status]||"")),h(onSelect?"label":"div",{className:"sg-dup-card-body",htmlFor:onSelect?"sg-retain-"+card.id:void 0},h("h3",null,card.title),h("div",{className:"sg-dup-meta"},date?h("span",null,date):null,h("span",null,criticality[card.criticality]||"\u4E00\u822C\u8BB0\u5FC6"),h("span",null,scope[card.scope]||card.scope||"\u4E2A\u4EBA"),card.weight?.pinned?h("span",null,"\u5DF2\u7F6E\u9876"):null),h("p",{className:"sg-dup-summary"+(!expanded&&!fullContent?" collapsed":"")},card.summary),!fullContent&&card.summary?.length>160?h("button",{type:"button",className:"sg-dup-expand",onClick:()=>setExpanded(!expanded),"aria-expanded":expanded},expanded?"\u6536\u8D77\u5168\u6587":"\u5C55\u5F00\u5168\u6587"):null,h("dl",{className:"sg-dup-evidence"},card.quotes?.length?h(React.Fragment,null,h("dt",null,"\u5F15\u8BED"),h("dd",null,card.quotes.map(quote=>h("blockquote",{key:quote},quote)))):null,temporal.participants?.length?h(React.Fragment,null,h("dt",null,"\u53C2\u4E0E\u8005"),h("dd",null,temporal.participants.join("\u3001"))):null,card.tags?.length?h(React.Fragment,null,h("dt",null,"\u6807\u7B7E"),h("dd",null,card.tags.join(" \xB7 "))):null)),fullContent&&onSelect&&!unavailable?null:h("div",{className:"sg-dup-card-footer"},fullContent&&onSelect?null:h("button",{type:"button",className:"sg-dup-button","aria-expanded":showSource,onClick:toggleSource},showSource?"\u6536\u8D77\u6765\u6E90\uFF0C\u8FD4\u56DE\u5BF9\u6BD4":"\u67E5\u770B "+(card.sourceMessageIds?.length||0)+" \u6761\u6765\u6E90\u4E0E\u5B8C\u6574\u8BB0\u5FC6"),unavailable?h("small",null,unavailable):null),fullContent&&onSelect?h("p",{className:"sg-dup-selection-result"},selectionMade?selected?"\u786E\u8BA4\u540E\u4FDD\u7559\u8FD9\u5F20":"\u786E\u8BA4\u540E\u5C06\u8FD9\u5F20\u5F52\u6863 \xB7 \u539F\u6587\u548C\u6765\u6E90\u4ECD\u4FDD\u7559":"\u70B9\u51FB\u4FDD\u7559\u8FD9\u5F20\u8BB0\u5FC6"):null,showSource||fullContent&&onSelect?h(React.Fragment,null,h(DuplicateEvidence,{namespace,card,hideSummary:fullContent}),showSource?h("button",{type:"button",className:"sg-dup-button text",onClick:toggleSource},"\u6536\u8D77\u6765\u6E90\uFF0C\u8FD4\u56DE\u5BF9\u6BD4"):null):null)}function DuplicatePair({item,busy,namespace,onResolve,onPrepareDraft,onTakeOver,draftState,onDraftState}){let[selectedId,setSelectedId]=React.useState(draftState?.selectedId||""),[mode,setMode]=React.useState(draftState?.mode||""),[draft,setDraft]=React.useState(draftState?.draft||item.draft||{title:"",summary:""}),[draftError,setDraftError]=React.useState(""),[draftBusy,setDraftBusy]=React.useState(!1),[dirty,setDirty]=React.useState(!!draftState?.dirty),[regenerate,setRegenerate]=React.useState(!1),[saveError,setSaveError]=React.useState(""),[draftOrigin,setDraftOrigin]=React.useState(draftState?.draftOrigin||(item.draft?"AI \u5408\u5E76\u7A3F \xB7 \u8BF7\u6838\u5BF9":"\u624B\u52A8\u586B\u5199\u5408\u5E76\u7A3F")),stageHeading=React.useRef(null);React.useEffect(()=>{onDraftState?.({selectedId,mode,draft,draftOrigin,dirty})},[selectedId,mode,draft,draftOrigin,dirty]),React.useEffect(()=>{mode&&(stageHeading.current?.focus({preventScroll:!0}),stageHeading.current?.scrollIntoView({block:"nearest"}))},[mode]);let archived=item.outcome==="merged"||item.outcome==="selected",retained=item.outcome==="kept"&&(item.aiResolved||item.userReviewed),done=archived||retained,awaitingAI=item.outcome==="pending",selected=selectedId===item.leftId?item.left:selectedId===item.rightId?item.right:null,letter=selectedId===item.leftId?"A":"B",mergeId=item.recommendedKeepId||(item.choices?.right?.canMerge?item.rightId:item.leftId),mergeCard=mergeId===item.leftId?item.left:item.right,selection=item.choices?.[selectedId===item.leftId?"left":"right"],draftValid=!!(draft.title.trim()&&draft.summary.trim()),generateDraft=async(force=!1)=>{if(dirty&&!force){setRegenerate(!0);return}setRegenerate(!1),setDraftBusy(!0),setDraftError("");try{let result2=await onPrepareDraft(item,force);if(!result2?.draft)throw new Error("AI \u5C1A\u672A\u751F\u6210\u5B8C\u6574\u7A3F\uFF0C\u4F60\u53EF\u4EE5\u624B\u52A8\u586B\u5199\u6216\u7A0D\u540E\u91CD\u8BD5\u3002");setDraft(result2.draft),setDirty(!1),setDraftOrigin("AI \u5408\u5E76\u7A3F \xB7 \u8BF7\u6838\u5BF9")}catch(reason){setDraftError(String(reason.message||reason).replace(/\s*[((]duplicates[))]$/,""))}finally{setDraftBusy(!1)}},start=value=>{setMode(value),setSaveError(""),value==="select"&&setSelectedId(""),value==="merge"&&!draft.title&&!draft.summary&&onPrepareDraft&&generateDraft()},save=async()=>{setSaveError("");try{await onResolve(mode==="both"?"keep":mode,item,mode==="select"?selectedId:mode==="merge"?mergeId:void 0,mode==="merge"?draft:void 0)}catch(reason){setSaveError("\u4F60\u7684\u9009\u62E9\u548C\u7F16\u8F91\u5DF2\u4FDD\u7559\u3002"+String(reason.message||reason).replace(/\s*[((]duplicates[))]$/,""))}},cards=(selectable=!1,originals=!1)=>h("div",{className:"sg-dup-comparison",role:selectable?"radiogroup":void 0,"aria-label":selectable?"\u9009\u62E9\u8981\u4FDD\u7559\u7684\u8BB0\u5FC6":"\u53CC\u65B9\u5B8C\u6574\u8BB0\u5FC6"},[originals&&item.originalLeft||item.left,originals&&item.originalRight||item.right].map((card,i2)=>h(DuplicateCard,{key:card?.id||i2,card,letter:i2?"B":"A",namespace,fullContent:!0,selected:selectable&&selectedId===card?.id,selectionMade:!!selectedId,onSelect:selectable?()=>{setSelectedId(i2?item.rightId:item.leftId),setSaveError("")}:null,disabled:busy||draftBusy,unavailable:selectable?item.choices?.[i2?"right":"left"]?.selectBlockedReason:""}))),back=()=>{setMode(""),setSaveError(""),setRegenerate(!1)},result=done&&item.keepId===item.leftId?item.left:item.right,consequences=h("section",{className:"sg-dup-consequences"},h("h3",null,"\u786E\u8BA4\u540E\u4F1A\u53D1\u751F\u4EC0\u4E48"),h("dl",{className:"sg-dup-result"},h("dt",null,"\u65E5\u5E38\u68C0\u7D22"),h("dd",null,mode==="merge"?"\u663E\u793A\u4E0A\u9762\u7684\u5B8C\u6574\u5408\u5E76\u7A3F\u3002":mode==="both"?"\u4E24\u5F20\u8BB0\u5FC6\u5206\u522B\u4FDD\u7559\uFF0C\u5185\u5BB9\u548C\u6765\u6E90\u4E0D\u53D8\u3002":"\u53EA\u663E\u793A\u8BB0\u5FC6 "+letter+" \xB7 "+(selected?.title||"")),h("dt",null,"\u539F\u59CB\u8BB0\u5F55"),h("dd",null,mode==="merge"?"\u53CC\u65B9\u5904\u7406\u524D\u7684\u5185\u5BB9\u3001\u6765\u6E90\u548C\u5386\u53F2\u5173\u8054\u4FDD\u7559\uFF0C\u53EF\u5728\u5DF2\u5904\u7406\u8BB0\u5F55\u4E2D\u6838\u5BF9\u3002":mode==="both"?"\u53CC\u65B9\u539F\u5361\u5747\u4FDD\u7559\u3002":"\u8BB0\u5FC6 "+(letter==="A"?"B":"A")+" \u8F6C\u5165\u5386\u53F2\uFF1B\u72EC\u6709\u5185\u5BB9\u4E0D\u4F1A\u5408\u5165\u6240\u9009\u5361\uFF0C\u539F\u6587\u548C\u6765\u6E90\u4ECD\u4FDD\u7559\u3002"),mode==="merge"&&mergeCard?.temporal?.happenedStart?h(React.Fragment,null,h("dt",null,"\u65E5\u671F"),h("dd",null,"\u68C0\u7D22\u65E5\u671F\u6CBF\u7528 "+mergeCard.temporal.happenedStart+"\uFF1B\u8BF7\u6838\u5BF9\u6B63\u6587\u4E2D\u7684\u539F\u5B89\u6392\u3001\u540E\u7EED\u53D8\u5316\u4E0E\u5F53\u524D\u4E8B\u5B9E\u3002")):null,h("dt",null,"\u540E\u7EED\u8C03\u6574"),h("dd",null,"\u53EF\u5728\u201C\u5DF2\u5904\u7406\u201D\u67E5\u770B\u7ED3\u679C\uFF1B\u6CA1\u6709\u540E\u7EED\u51B2\u7A81\u65F6\u53EF\u64A4\u9500\u3002")));return h("section",{className:"sg-dup-pair","aria-label":"\u8BB0\u5FC6\u5BF9\u6BD4\u4E0E\u5904\u7406","aria-busy":busy||draftBusy},h("nav",{className:"sg-dup-steps","aria-label":"\u5904\u7406\u6B65\u9AA4"},["\u5BF9\u6BD4\u8BB0\u5FC6","\u6838\u5BF9\u7ED3\u679C","\u5B8C\u6210"].map((label,i2)=>h("span",{key:label,"aria-current":(done?2:mode?1:0)===i2?"step":void 0},i2+1+" "+label))),done?h(React.Fragment,null,h("h3",{className:"sg-dup-stage-title"},archived?item.outcome==="merged"?"\u5DF2\u6574\u7406\u6210\u4E00\u5F20\u5B8C\u6574\u8BB0\u5FC6":"\u5DF2\u4FDD\u7559\u8BB0\u5FC6 "+(item.keepId===item.leftId?"A":"B"):"\u5DF2\u5206\u522B\u4FDD\u7559\u4E24\u5F20\u8BB0\u5FC6"),h("p",{className:"sg-dup-reason"},item.aiResolved?"\u7531 AI \u81EA\u52A8\u5904\u7406 \xB7 "+item.reason:item.reason),archived?h(React.Fragment,null,h("div",{className:"sg-dup-result-card"},h("small",null,"\u4ECA\u540E\u4F7F\u7528\u7684\u8BB0\u5FC6"),h("h3",null,result?.title),h("p",{className:"sg-dup-summary"},result?.summary)),h("details",null,h("summary",null,item.originalLeft&&item.originalRight?"\u67E5\u770B\u5904\u7406\u524D\u7684\u4E24\u5F20\u8BB0\u5FC6\u4E0E\u6765\u6E90":"\u67E5\u770B\u4E24\u5F20\u8BB0\u5FC6\u4E0E\u6765\u6E90\uFF08\u6309\u5F53\u524D\u8BB0\u5F55\uFF09"),cards(!1,!0))):cards(),h("div",{className:"sg-dup-actions"},h("p",null,"\u64A4\u9500\u524D\u4F1A\u68C0\u67E5\u540E\u7EED\u53D8\u5316\uFF0C\u907F\u514D\u8986\u76D6\u65B0\u6570\u636E\u3002"),item.undoId?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onResolve("undo",item).catch(()=>{})},"\u64A4\u9500\u672C\u6B21\u5904\u7406"):retained?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onTakeOver?.(item)},"\u91CD\u65B0\u5904\u7406\u8FD9\u7EC4"):h("p",null,"\u6B64\u8BB0\u5F55\u521B\u5EFA\u4E8E\u652F\u6301\u64A4\u9500\u4E4B\u524D\u3002"))):awaitingAI?h(React.Fragment,null,h("div",{className:"sg-dup-reason"},h("strong",null,"AI \u4F1A\u5148\u5224\u65AD\u8FD9\u7EC4\u8BB0\u5FC6"),h("p",null,"\u5224\u65AD\u660E\u786E\u7684\u81EA\u52A8\u5904\u7406\u5E76\u7559\u4E0B\u8BB0\u5F55\uFF1B\u4E0D\u786E\u5B9A\u6216\u5904\u7406\u5931\u8D25\u7684\uFF0C\u624D\u4F1A\u8FDB\u5165\u201C\u9700\u8981\u4F60\u5224\u65AD\u201D\u3002\u4E24\u5F20\u539F\u5361\u76EE\u524D\u5747\u4FDD\u7559\u3002"),h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onTakeOver(item)},"\u6211\u6765\u5904\u7406\u8FD9\u7EC4")),cards()):mode?h(React.Fragment,null,h("button",{type:"button",className:"sg-dup-button text sg-dup-back",disabled:busy||draftBusy,onClick:back},h(DuplicateIcon,{kind:"back",size:14}),"\u8FD4\u56DE\u5BF9\u6BD4"),h("div",{className:"sg-dup-stage-heading"},h("h3",{ref:stageHeading,tabIndex:-1},mode==="merge"?"\u628A\u53CC\u65B9\u4FE1\u606F\u6574\u7406\u6210\u4E00\u5F20\u8BB0\u5FC6":mode==="select"?"\u53EA\u4FDD\u7559\u54EA\u5F20\u8BB0\u5FC6\uFF1F":"\u5206\u522B\u4FDD\u7559\u8FD9\u4E24\u5F20\u8BB0\u5FC6"),h("p",null,mode==="merge"?"\u53CC\u65B9\u6709\u6548\u4FE1\u606F\u4F1A\u6574\u7406\u8FDB\u5B8C\u6574\u7A3F\uFF0C\u4FDD\u5B58\u524D\u4F60\u53EF\u4EE5\u4FEE\u6539\u6807\u9898\u548C\u6B63\u6587\u3002":mode==="select"?"\u4E24\u5F20\u5B8C\u6574\u5185\u5BB9\u90FD\u5728\u4E0B\u65B9\uFF0C\u70B9\u51FB\u8981\u4FDD\u7559\u7684\u5361\u7247\u3002\u53E6\u4E00\u5F20\u8F6C\u5165\u5386\u53F2\uFF0C\u5185\u5BB9\u4E0D\u4F1A\u81EA\u52A8\u5408\u5E76\u3002":"\u9002\u7528\u4E8E\u4E0D\u540C\u4E8B\u4EF6\u3001\u524D\u540E\u8FDB\u5C55\uFF0C\u6216\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u7684\u60C5\u51B5\u3002")),mode==="merge"?h(React.Fragment,null,item.historyNotice||item.mergeWarning?h("p",{className:"sg-dup-reason"},item.historyNotice||item.mergeWarning):null,!item.canMerge&&item.mergeBlockedReason?h("p",{className:"sg-dup-notice error",role:"note"},item.mergeBlockedReason," \u4ECD\u53EF\u5728\u4E0B\u65B9\u6574\u7406\u8349\u7A3F\uFF0C\u539F\u5361\u4E0D\u4F1A\u81EA\u52A8\u6539\u52A8\u3002"):null,h("div",{className:"sg-dup-editor"},h("div",{className:"sg-dup-draft-heading"},h("strong",null,draftBusy?"AI \u6B63\u5728\u6574\u7406\u5408\u5E76\u7A3F\u2026":draftOrigin),h("button",{type:"button",className:"sg-dup-button",disabled:busy||draftBusy,onClick:()=>generateDraft(!dirty)},"\u91CD\u65B0\u8BA9 AI \u6574\u7406")),regenerate?h("div",{className:"sg-dup-reason"},"\u91CD\u65B0\u751F\u6210\u4F1A\u66FF\u6362\u4F60\u5F53\u524D\u7F16\u8F91\u7684\u6807\u9898\u548C\u6B63\u6587\u3002",h("div",{className:"sg-dup-actions"},h("button",{type:"button",className:"sg-dup-button",onClick:()=>setRegenerate(!1)},"\u4FDD\u7559\u5F53\u524D\u7F16\u8F91"),h("button",{type:"button",className:"sg-dup-button",onClick:()=>generateDraft(!0)},"\u66FF\u6362\u4E3A\u65B0\u7A3F"))):null,draftError?h("p",{role:"alert",className:"sg-dup-notice error"},draftError," \u539F\u5361\u672A\u6539\u52A8\uFF0C\u53EF\u76F4\u63A5\u586B\u5199\u4E0B\u65B9\u5B8C\u6574\u8BB0\u5FC6\u3002"):null,draftBusy?h("div",{className:"sg-dup-draft-skeleton",role:"status","aria-label":"\u6B63\u5728\u751F\u6210\u5408\u5E76\u7A3F"},[1,2,3,4].map(i2=>h("span",{key:i2}))):h(React.Fragment,null,h("label",null,"\u5408\u5E76\u540E\u7684\u6807\u9898",h("input",{type:"text","aria-label":"\u5408\u5E76\u540E\u7684\u6807\u9898",value:draft.title,maxLength:200,disabled:busy,onChange:event3=>{setDraft({...draft,title:event3.target.value}),setDirty(!0),setDraftOrigin("\u4F60\u5DF2\u7F16\u8F91")}})),h("label",null,"\u5408\u5E76\u540E\u7684\u5B8C\u6574\u6B63\u6587",h("textarea",{"aria-label":"\u5408\u5E76\u540E\u7684\u5B8C\u6574\u6B63\u6587",value:draft.summary,maxLength:12e3,rows:8,disabled:busy,placeholder:"\u5199\u51FA\u4F60\u5E0C\u671B\u4ECA\u540E\u8BB0\u4F4F\u7684\u5B8C\u6574\u5185\u5BB9\uFF0C\u4FDD\u7559\u65F6\u95F4\u3001\u6761\u4EF6\u548C\u4E0D\u786E\u5B9A\u6027\u3002",onChange:event3=>{setDraft({...draft,summary:event3.target.value}),setDirty(!0),setDraftOrigin("\u4F60\u5DF2\u7F16\u8F91")}})),h("p",{className:"sg-dup-constraint"},draftValid?"\u5C06\u6309\u6B64\u5168\u6587\u4FDD\u5B58\uFF0C\u539F\u59CB\u8BC1\u636E\u53E6\u884C\u4FDD\u7559\u3002":"\u8BF7\u586B\u5199\u5B8C\u6574\u6807\u9898\u548C\u6B63\u6587\u540E\u518D\u4FDD\u5B58\u3002"))),h("details",null,h("summary",null,"\u5C55\u5F00\u53CC\u65B9\u539F\u5361\uFF0C\u6838\u5BF9\u5408\u5E76\u7A3F"),cards())):cards(mode==="select"),mode==="select"&&selected?.status==="superseded"?h("p",{className:"sg-dup-reason",role:"note"},"\u4F60\u9009\u62E9\u7684\u662F\u5386\u53F2\u7248\u672C "+letter+"\u3002\u4FDD\u5B58\u540E\u5B83\u4F1A\u91CD\u65B0\u6210\u4E3A\u6709\u6548\u8BB0\u5FC6\uFF0C\u53E6\u4E00\u5F20\u7684\u65B0\u589E\u5185\u5BB9\u4E0D\u4F1A\u5408\u5165\uFF1B\u8BF7\u786E\u8BA4\u8FD9\u7B26\u5408\u4F60\u7684\u610F\u601D\u3002"):null,mode==="select"&&selected&&selection?.selectBlockedReason?h("p",{className:"sg-dup-notice error",role:"note"},selection.selectBlockedReason):null,mode!=="select"||selected?consequences:h("p",{className:"sg-dup-constraint"},"\u5C1A\u672A\u9009\u62E9\u3002\u8BF7\u5BF9\u6BD4\u4E0A\u65B9\u5B8C\u6574\u5185\u5BB9\uFF0C\u518D\u9009\u62E9\u4FDD\u7559 A \u6216 B\u3002"),saveError?h("p",{className:"sg-dup-notice error",role:"alert"},saveError):null,h("div",{className:"sg-dup-actions"},h("p",null,"\u53EA\u6709\u786E\u8BA4\u4FDD\u5B58\uFF0C\u624D\u4F1A\u66F4\u65B0\u8BB0\u5FC6\u3002"),h("div",null,h("button",{type:"button",className:"sg-dup-button",disabled:busy||draftBusy,onClick:back},"\u8FD4\u56DE\u5BF9\u6BD4"),h("button",{type:"button",className:"sg-dup-button primary",disabled:busy||draftBusy||mode==="merge"&&!draftValid||mode==="select"&&!selected,onClick:save},busy?"\u6B63\u5728\u4FDD\u5B58\u2026":saveError?"\u91CD\u8BD5\u4FDD\u5B58":mode==="merge"?"\u786E\u8BA4\u4FDD\u5B58\u5408\u5E76\u7A3F":mode==="both"?"\u786E\u8BA4\u4FDD\u7559\u4E24\u5F20":selected?"\u786E\u8BA4\u53EA\u4FDD\u7559 "+letter:"\u8BF7\u9009\u62E9 A \u6216 B")))):h(React.Fragment,null,h("p",{className:"sg-dup-reason"},h("strong",null,"\u4E3A\u4EC0\u4E48\u9700\u8981\u4F60\u5224\u65AD"),item.reason),cards(),h("h3",{className:"sg-dup-stage-title"},"\u4F60\u5E0C\u671B\u600E\u4E48\u5904\u7406\uFF1F"),h("div",{className:"sg-dup-options"},[["merge","\u5408\u5E76\u53CC\u65B9\u5185\u5BB9","AI \u6574\u7406\u5B8C\u6574\u7A3F\uFF0C\u4F60\u53EF\u4EE5\u7F16\u8F91\u540E\u518D\u786E\u8BA4\u3002"],["select","\u53EA\u4FDD\u7559\u4E00\u5F20","\u67E5\u770B\u5B8C\u6574\u5185\u5BB9\uFF0C\u9009\u62E9 A \u6216 B\uFF0C\u53E6\u4E00\u5F20\u8F6C\u5165\u5386\u53F2\u3002"],["both","\u4FDD\u7559\u4E24\u5F20","\u5206\u522B\u4FDD\u7559\uFF0C\u7ED3\u675F\u8FD9\u7EC4\u6574\u7406\u3002"]].map(([value,title,description])=>h("button",{key:value,type:"button",className:"sg-dup-option",disabled:busy||draftBusy,onClick:()=>start(value)},h(DuplicateIcon,{kind:value==="merge"?"merge":"cards"}),h("strong",null,title),h("span",null,description)))),h("p",{className:"sg-dup-constraint"},"\u9009\u62E9\u540E\u5148\u6838\u5BF9\u5904\u7406\u7ED3\u679C\uFF0C\u786E\u8BA4\u4FDD\u5B58\u524D\u4E0D\u4F1A\u6539\u52A8\u539F\u5361\u3002")))}function DuplicateReviewPage({namespace,repair,onBack,openEvent,refresh}){let[page,setPage]=React.useState({items:[],offset:0,limit:20,total:0}),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[notice,setNotice]=React.useState(""),[loading,setLoading]=React.useState(!0),[index,setIndex]=React.useState(0),[queue,setQueue]=React.useState("review"),[lastAction,setLastAction]=React.useState(null),draftCache=React.useRef(new Map),focusPair=React.useRef(null),committedRead=React.useRef(!1),readFailure=reason=>(committedRead.current?"\u5904\u7406\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u8BFB\u53D6\u7ED3\u679C\u5931\u8D25\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u7ED3\u679C\u3002":"")+String(reason.message||reason),requestId=React.useRef(0),load=(offset=0,targetQueue=queue,focus=focusPair.current)=>{let id2=++requestId.current;return setLoading(!0),api2("duplicates",{namespace,offset,limit:20,queue:targetQueue,...focus?{focusLeft:focus.leftId,focusRight:focus.rightId}:{}}).then(value=>{id2===requestId.current&&(setPage(value),setIndex(i2=>value.focusIndex??Math.min(i2,Math.max(0,value.items.length-1))),focusPair.current=null,committedRead.current=!1)}).finally(()=>{id2===requestId.current&&setLoading(!1)})};React.useEffect(()=>{let active=!0,id2=++requestId.current;setLoading(!0),setError("");let focus=focusPair.current;return api2("duplicates",{namespace,offset:page.namespace===namespace&&page.queue===queue?page.offset:0,limit:20,queue,...focus?{focusLeft:focus.leftId,focusRight:focus.rightId}:{}}).then(value=>{active&&id2===requestId.current&&(setPage(value),setIndex(i2=>value.focusIndex??(page.namespace===namespace&&page.queue===queue?Math.min(i2,Math.max(0,value.items.length-1)):0)),focusPair.current=null,committedRead.current=!1)}).catch(reason=>{active&&id2===requestId.current&&setError(readFailure(reason))}).finally(()=>{active&&id2===requestId.current&&setLoading(!1)}),()=>{active=!1}},[namespace,queue,JSON.stringify(repair)]);let pairInput=item=>item?{leftId:item.leftId,rightId:item.rightId,leftFingerprint:item.leftFingerprint,rightFingerprint:item.rightFingerprint,exact:item.exact,similarity:item.similarity}:void 0,takeOver=item=>(setBusy(!0),setError(""),api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"takeover",pair:pairInput(item)})}).then(()=>(focusPair.current=item,setQueue("review"),setNotice("\u5DF2\u7531\u4F60\u63A5\u7BA1\uFF0CAI \u4E0D\u518D\u81EA\u52A8\u5904\u7406\u8FD9\u7EC4\u3002"),refresh())).catch(reason=>setError(String(reason.message||reason))).finally(()=>setBusy(!1))),prepareDraft=(item,regenerate=!1)=>(setBusy(!0),api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"draft",pair:pairInput(item),regenerate})}).finally(()=>setBusy(!1))),control=(action,item,keepId,draft)=>{let committed=!1;setBusy(!0),setError(""),setNotice("");let pair=item?{leftId:item.leftId,rightId:item.rightId,leftFingerprint:item.leftFingerprint,rightFingerprint:item.rightFingerprint,exact:item.exact,similarity:item.similarity}:void 0;return api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action,pair,keepId,draft,undoId:action==="undo"?item?.undoId:void 0})}).then(result=>{if(committed=!0,committedRead.current=!0,action==="undo"){for(let key of draftCache.current.keys())key.startsWith(namespace+":"+item.leftId+":"+item.rightId+":")&&draftCache.current.delete(key);focusPair.current=item,setQueue("review")}return setLastAction(result.undoId?{...item,undoId:result.undoId}:null),["merge","select","keep"].includes(action)&&(focusPair.current=item,setQueue("history")),setNotice(action==="rescan"?"\u5DF2\u91CD\u65B0\u626B\u63CF\uFF0CAI \u4F1A\u5148\u5904\u7406\u5019\u9009\u3002":action==="undo"?"\u5DF2\u64A4\u9500\uFF0C\u6062\u590D\u4E86\u5904\u7406\u524D\u7684\u5185\u5BB9\u3001\u72B6\u6001\u548C\u5173\u8054\u3002":action==="merge"?"\u5DF2\u4FDD\u5B58\u5B8C\u6574\u5408\u5E76\u7A3F\uFF0C\u53CC\u65B9\u8BC1\u636E\u4E0E\u6765\u6E90\u5DF2\u4FDD\u7559\u3002":action==="select"?"\u5DF2\u4FDD\u7559\u6240\u9009\u8BB0\u5FC6\uFF0C\u53E6\u4E00\u5F20\u5DF2\u5F52\u6863\uFF0C\u5185\u5BB9\u672A\u6DF7\u5408\u3002":"\u5DF2\u786E\u8BA4\u4FDD\u7559\u4E24\u5F20\u3002"),refresh()}).then(()=>(action==="rescan"&&setIndex(0),action==="undo"?load(0,"review",item):["merge","select","keep"].includes(action)?load(0,"history",item):load(action==="rescan"?0:page.offset))).catch(reason=>{if(committed){setError("\u5904\u7406\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u8BFB\u53D6\u7ED3\u679C\u5931\u8D25\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u7ED3\u679C\u3002"+String(reason.message||reason));return}throw["merge","select","keep"].includes(action)||setError(String(reason.message||reason)),reason}).finally(()=>setBusy(!1))},navigate=direction=>{if(setError(""),setNotice(""),index+direction>=0&&index+direction<page.items.length){setIndex(index+direction);return}let id2=++requestId.current;setLoading(!0),api2("duplicates",{namespace,offset:Math.max(0,page.offset+direction*page.limit),limit:20,queue}).then(value=>{id2===requestId.current&&(setPage(value),setIndex(direction>0?0:Math.max(0,value.items.length-1)))}).catch(reason=>{id2===requestId.current&&setError(String(reason.message||reason))}).finally(()=>{id2===requestId.current&&setLoading(!1)})},current=page.items[Math.min(index,Math.max(0,page.items.length-1))],draftKey=current?namespace+":"+current.leftId+":"+current.rightId+":"+current.leftFingerprint+":"+current.rightFingerprint:"";return h(React.Fragment,null,h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-duplicates"},h("header",{className:"sg-dup-heading"},h("div",null,h("h2",null,"\u91CD\u590D\u8BB0\u5FC6\u6574\u7406"),h("p",null,"AI \u5148\u5224\u65AD\u5E76\u6574\u7406\u3002\u8FD9\u91CC\u53EA\u9700\u8981\u4F60\u5904\u7406\u62FF\u4E0D\u51C6\u7684\u8BB0\u5FC6\u3002")),h(DuplicateIcon,{size:25})),h("nav",{className:"sg-dup-queues","aria-label":"\u6574\u7406\u961F\u5217"},[["review","\u9700\u8981\u4F60\u5224\u65AD",repair?.needsReview||0],["ai","\u7B49\u5F85 AI",repair?.awaitingAI||0],["history","\u5DF2\u5904\u7406",(repair?.merged||0)+(repair?.selected||0)+(repair?.retained||0)-(repair?.needsReview||0)+(repair?.failed||0)]].map(([value,label,count])=>h("button",{key:value,type:"button",className:"sg-dup-button","aria-pressed":queue===value,disabled:busy,onClick:()=>{setQueue(value),setError(""),setIndex(0)}},label+" "+Math.max(0,count)))),error3?h("div",{role:"alert",className:"sg-dup-notice error"},error3,h("button",{type:"button",className:"sg-dup-button text",disabled:busy||loading,onClick:()=>{setError(""),load(page.offset).catch(reason=>setError(readFailure(reason)))}},"\u91CD\u65B0\u8BFB\u53D6")):null,notice?h("div",{role:"status",className:"sg-dup-notice","aria-live":"polite"},notice,lastAction?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>{control("undo",lastAction).catch(()=>{})}},"\u64A4\u9500\u672C\u6B21\u5904\u7406"):null):null,!error3&&(loading||page.namespace!==namespace||page.queue!==queue)?h("div",{className:"sg-dup-comparison",role:"status","aria-label":"\u6B63\u5728\u8BFB\u53D6\u91CD\u590D\u8BB0\u5FC6"},h("div",{className:"sg-dup-skeleton"}),h("div",{className:"sg-dup-skeleton"})):current&&page.namespace===namespace&&page.queue===queue?h(React.Fragment,null,h("nav",{className:"sg-dup-navigation","aria-label":"\u5207\u6362\u5019\u9009\u7EC4"},h("button",{type:"button",className:"sg-dup-button","aria-label":"\u4E0A\u4E00\u7EC4",disabled:busy||page.offset+index<=0,onClick:()=>navigate(-1)},h(DuplicateIcon,{kind:"back",size:14})),h("select",{value:index,disabled:busy,onChange:event3=>{setIndex(Number(event3.target.value)),setNotice("")},"aria-label":"\u5F53\u524D\u5019\u9009\u7EC4"},page.items.map((item,i2)=>h("option",{key:item.leftId+":"+item.rightId,value:i2},item.left?.title||item.right?.title||"\u539F\u5361\u5DF2\u4E0D\u53EF\u7528"))),h("span",{className:"sg-dup-count"},page.offset+index+1+" / "+page.total),h("button",{type:"button",className:"sg-dup-button","aria-label":"\u4E0B\u4E00\u7EC4",disabled:busy||page.offset+index+1>=page.total,onClick:()=>navigate(1)},h(DuplicateIcon,{kind:"next",size:14}))),h(DuplicatePair,{key:namespace+current.leftId+current.rightId+current.leftFingerprint+current.rightFingerprint+current.outcome+!!current.userReviewed,item:current,busy,namespace,onResolve:control,onPrepareDraft:prepareDraft,onTakeOver:takeOver,draftState:draftCache.current.get(draftKey),onDraftState:value=>{draftCache.current.set(draftKey,value),draftCache.current.size>50&&draftCache.current.delete(draftCache.current.keys().next().value)}})):error3?null:h("section",{className:"sg-dup-empty"},h(DuplicateIcon,{kind:"check",size:28}),h("strong",null,queue==="review"?"\u6682\u65F6\u6CA1\u6709\u9700\u8981\u4F60\u5224\u65AD\u7684\u8BB0\u5FC6":queue==="ai"?"\u6CA1\u6709\u7B49\u5F85 AI \u7684\u5019\u9009":"\u8FD8\u6CA1\u6709\u5904\u7406\u8BB0\u5F55"),h("p",null,queue==="review"?"AI \u80FD\u5904\u7406\u7684\u4F1A\u81EA\u52A8\u5B8C\u6210\u3002\u4F60\u53EF\u4EE5\u5728\u201C\u5DF2\u5904\u7406\u201D\u67E5\u770B\u7ED3\u679C\u3002":"\u626B\u63CF\u548C\u5904\u7406\u8FDB\u5EA6\u4F1A\u5728\u5BF9\u5E94\u961F\u5217\u4E2D\u663E\u793A\u3002")),h("details",{className:"sg-dup-tools"},h("summary",null,"\u91CD\u65B0\u68C0\u67E5\u8BB0\u5FC6\u5E93"),h("p",null,"\u6309\u5F53\u524D\u89C4\u5219\u91CD\u65B0\u626B\u63CF\u3002\u540E\u7EED\u5224\u65AD\u53EF\u80FD\u4F7F\u7528\u5F53\u524D\u6A21\u578B\uFF0C\u5DF2\u5B8C\u6210\u7684\u626B\u63CF\u4E0D\u4F1A\u5728\u6BCF\u6B21\u542F\u52A8\u65F6\u91CD\u590D\u6267\u884C\u3002"),h("button",{type:"button",className:"sg-dup-button",disabled:busy||loading,onClick:()=>{control("rescan").catch(()=>{})}},"\u91CD\u65B0\u626B\u63CF\u4E0E\u5224\u65AD"))))}function SystemPage({selected,blocks,onBack,backLabel="\u66F4\u591A",refresh,onDuplicates}){let processing=blocks.filter(block=>block.status==="processing").length,[refreshing,setRefreshing]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),repair=selected.duplicateRepair,checkStatus=()=>{let before=processingFingerprint(selected);return setRefreshing(!0),setFeedback({kind:"",text:"\u6B63\u5728\u8BFB\u53D6\u2026"}),refresh({propagateError:!0}).then(next2=>{let updated=next2?.overview?.namespaces?.find(item=>item.namespace===selected.namespace);setFeedback({kind:"done",text:updated&&processingFingerprint(updated)!==before?"\u72B6\u6001\u5DF2\u66F4\u65B0":"\u72B6\u6001\u6CA1\u6709\u53D8\u5316"})}).catch(reason=>{setFeedback({kind:"failed",text:"\u8BFB\u53D6\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}).finally(()=>setRefreshing(!1))};return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u7CFB\u7EDF\u72B6\u6001"),h("p",null,"\u4EC5\u5728\u8FD9\u91CC\u5C55\u793A\u8BB0\u5FC6\u5904\u7406\u7684\u5DE5\u7A0B\u72B6\u6001")),h("div",{className:"sg-pipeline"},[["Block \u6570\u91CF",selected.blocks],["\u5F85\u5904\u7406\u4EFB\u52A1",processing],["\u5931\u8D25\u4EFB\u52A1",selected.failedJobs],["\u6700\u8FD1\u6574\u7406\u65F6\u95F4",formatTime(selected.lastActivityAt)],["Event \u63D0\u53D6",selected.failedJobDetails?.some(item=>item.kind==="event-extraction")?"\u6709\u5931\u8D25":"\u6B63\u5E38"],["\u56FE\u8C31\u6295\u5F71",selected.failedJobDetails?.some(item=>item.kind==="graph-projection")?"\u6709\u5931\u8D25":"\u6B63\u5E38"]].map(([label,value])=>h("div",{key:label,className:"sg-stage"},h("span",null,label),h("span",{className:"sg-stage-value "+(label==="\u5931\u8D25\u4EFB\u52A1"&&value?"failed":"waiting")},String(value))))),repair?h("p",{className:"sg-setting-note",role:"status"},"\u5386\u53F2\u91CD\u590D\u8BB0\u5FC6\u6574\u7406"+(repair.status==="completed"?"\u5DF2\u5B8C\u6210":"\u8FDB\u884C\u4E2D")+"\uFF1A\u5DF2\u626B\u63CF "+repair.scannedEvents+" \u5F20\u5361\uFF0C\u5F52\u6863\u91CD\u590D\u5361 "+repair.merged+" \u5F20\uFF1B\u5176\u4F59\u4FDD\u7559\u3002"+(repair.failed?" \u90E8\u5206\u5224\u65AD\u672A\u5B8C\u6210\uFF0C\u539F\u5361\u5DF2\u4FDD\u7559\u3002":"")):null,h("button",{type:"button",className:"sg-quiet-button",onClick:onDuplicates},"\u67E5\u770B\u91CD\u590D\u5019\u9009\u4E0E\u5904\u7406\u539F\u56E0"),h("button",{type:"button",className:"sg-quiet-button",disabled:refreshing,onClick:()=>{checkStatus()},style:{marginTop:"14px"}},refreshing?"\u21BB \u6B63\u5728\u8BFB\u53D6\u2026":"\u21BB \u91CD\u65B0\u68C0\u67E5"),feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null)}function AuditPage({audit,auditPage,namespace,onBack,backLabel="\u66F4\u591A"}){let pagedAudit=usePagedMemory({namespace,kind:"audit",initialItems:audit,initialPage:auditPage,fallbackLimit:100});return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u4F7F\u7528\u8BB0\u5F55"),h("p",null,"\u957F\u671F\u8BB0\u5FC6\u88AB\u4F7F\u7528\u7684\u65F6\u95F4\u4E0E\u6765\u6E90")),pagedAudit.items.length?pagedAudit.items.map(item=>{let value=item.audit||{};return h("details",{key:item.id,className:"sg-audit"},h("summary",null,h("strong",null,"\u4F7F\u7528\u4E86 "+((item.events||[]).length+(item.elements||[]).length)+" \u6761\u8BB0\u5FC6"),h("span",{className:"sg-muted"}," \xB7 "+formatTime(item.createdAt))),h("div",{className:"sg-audit-body"},h("div",null,(item.events||[]).map(event3=>event3.title).join("\u3001")||(item.elements||[]).map(element3=>element3.name).join("\u3001")||"\u65E7\u7248\u4F7F\u7528\u8BB0\u5F55"),h("div",{className:"sg-tech-row sg-audit-evidence"},h("span",{className:"sg-muted"},"\u6765\u6E90\u4F1A\u8BDD"),h("span",{className:"sg-code"},value.sessionId||"\u672A\u8BB0\u5F55")),value.turn!==void 0?h("div",{className:"sg-tech-row"},h("span",{className:"sg-muted"},"Turn"),h("span",null,value.turn)):null))}):h(Empty,{title:"\u8FD8\u6CA1\u6709\u4F7F\u7528\u8BB0\u5F55",copy:"AI \u5728\u56DE\u7B54\u4E2D\u91C7\u7528\u957F\u671F\u8BB0\u5FC6\u540E\u4F1A\u8BB0\u5F55\u5728\u8FD9\u91CC\u3002"}),h(Pagination,{page:pagedAudit.page,loading:pagedAudit.loading,error:pagedAudit.error,onOffset:pagedAudit.loadOffset}))}function RawPage({data:data4,selected,onBack,backLabel="\u66F4\u591A"}){let groups=[["Block raw",data4.blocks,data4.pagination?.blocks?.total],["Event raw",data4.events,data4.pagination?.events?.total],["Graph raw",data4.graph],["Usage raw",data4.audit,data4.pagination?.audit?.total],["\u6A21\u578B\u54CD\u5E94",selected.successfulModelResponses||[]]];return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u539F\u59CB\u6570\u636E"),h("p",null,"\u4F9B\u6392\u67E5\u95EE\u9898\u4F7F\u7528\u7684\u5185\u90E8\u5B57\u6BB5\u4E0E JSON")),groups.map(([label,value,total])=>h("details",{key:label,className:"sg-raw-group"},h("summary",null,label+" ("+(Array.isArray(value)&&Number(total)>value.length?"\u5DF2\u52A0\u8F7D "+value.length+" / \u5171 "+total:Array.isArray(value)?value.length:(value.nodes?.length||0)+(value.edges?.length||0))+")"),h("pre",{className:"sg-raw-json sg-code"},JSON.stringify(value,null,2)))))}let profileGroups=[["\u79F0\u547C\u4E0E\u8BED\u8A00",[["userPreferredName","\u600E\u4E48\u79F0\u547C\u4F60",100],["assistantPreferredName","\u52A9\u624B\u53EB\u4EC0\u4E48",100],["preferredLanguage","\u56DE\u7B54\u7528\u4EC0\u4E48\u8BED\u8A00",100],["reasoningLanguage","\u601D\u8003\u8FC7\u7A0B\u7528\u4EC0\u4E48\u8BED\u8A00",100]]],["\u5730\u70B9",[["defaultLocation","\u5E38\u9A7B\u5730\u5740",200],["currentCity","\u73B0\u5728\u5728\u54EA",100],["homeCity","\u5E38\u9A7B\u57CE\u5E02\uFF08\u539F\u6709\u5B57\u6BB5\uFF09",100]]],["\u600E\u4E48\u56DE\u7B54\u4F60",[["responsePreferences","\u56DE\u590D\u65B9\u5F0F",1e3],["standingInstructions","\u4E00\u76F4\u8981\u9075\u5B88\u7684\u8981\u6C42",1e3]]],["\u5173\u4E8E\u4F60",[["userBackground","\u80CC\u666F",1500],["longTermGoals","\u957F\u671F\u76EE\u6807",1e3]]],["\u5176\u4ED6",[["persistentNotes","\u5176\u4ED6\u8981\u4E00\u76F4\u8BB0\u4F4F\u7684",1200]]]],PROFILE_EMPTY_HINTS={userPreferredName:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5C0F\u7A0B",assistantPreferredName:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u6A59\u5B50",preferredLanguage:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E2D\u6587",reasoningLanguage:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E2D\u6587",responsePreferences:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5148\u7ED9\u7ED3\u8BBA\uFF0C\u518D\u5C55\u5F00",standingInstructions:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u6539\u4EE3\u7801\u524D\u5148\u8BF4\u65B9\u6848",defaultLocation:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5317\u4EAC\u5E02\u6D77\u6DC0\u533A",currentCity:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E0A\u6D77",homeCity:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u676D\u5DDE",userBackground:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u8F6F\u4EF6\u5DE5\u7A0B\u5E08\uFF0C\u719F\u6089 Python",longTermGoals:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4ECA\u5E74\u5B8C\u6210\u4E00\u7BC7\u8BBA\u6587",persistentNotes:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u9879\u76EE\u7EDF\u4E00\u4F7F\u7528 pnpm"},profileFieldNames=profileGroups.flatMap(([,fields])=>fields.map(([field])=>field)),PROFILE_LIMIT_DEFAULT=6e3,PROFILE_LIMIT_MIN=2e3,PROFILE_LIMIT_MAX=12e3,profileTotalLimit=value=>{let candidate=Number(value?._limits?.totalMaxLength);return Number.isSafeInteger(candidate)&&candidate>0?candidate:PROFILE_LIMIT_DEFAULT},profileTotalLength=value=>profileFieldNames.reduce((sum,field)=>sum+Array.from(value?.[field]||"").length,0),profileRightColumn=new Set(["\u600E\u4E48\u56DE\u7B54\u4F60","\u5173\u4E8E\u4F60","\u5176\u4ED6"]),formatCount=value=>Number(value||0).toLocaleString("en-US");function sameProfile(left,right){return profileFieldNames.every(field=>left?.[field]===right?.[field]&&left?._revisions?.[field]===right?._revisions?.[field])&&profileTotalLimit(left)===profileTotalLimit(right)}function ProfilePage(){let[profile,setProfile]=usePageMemoryState(profilePageMemory,"profile",null),[editing,updateEditing]=usePageMemoryState(profilePageMemory,"editing",null),setEditing=update2=>{let previous=profilePageMemory.get("editing"),next2=typeof update2=="function"?update2(previous):update2;next2?profileFieldDrafts.set(next2.field,next2):previous&&profileFieldDrafts.delete(previous.field),updateEditing(next2)},[saving,setSaving]=React.useState(!1),[syncStatus,setSyncStatus]=React.useState("\u66F4\u65B0\u4E2D\u2026"),[error3,setError]=React.useState(""),[conflicts,setConflicts]=usePageMemoryState(profilePageMemory,"conflicts",{}),conflict=!!conflicts[editing?.field],setConflict=(value,field=profilePageMemory.get("editing")?.field)=>{field&&setConflicts(current=>({...current,[field]:value}))},[saveResults,setSaveResults]=usePageMemoryState(profilePageMemory,"saveResults",{}),[reading,setReading]=React.useState(!1),session=React.useRef(0),action=React.useRef(null),actionTimeout=React.useRef(null),readController=React.useRef(null),savedTimers=React.useRef(new Map),requestVersion=React.useRef(0),refreshRef=React.useRef(null),clearSavedTimer=field=>{window.clearTimeout(savedTimers.current.get(field)),savedTimers.current.delete(field)},showSaved=submission=>{clearSavedTimer(submission.field),setSaveResults(current=>({...current,[submission.field]:{kind:"saved",submission,flash:!0}}));let timer=window.setTimeout(()=>{savedTimers.current.get(submission.field)===timer&&(savedTimers.current.delete(submission.field),setSaveResults(current=>current[submission.field]?.submission===submission?{...current,[submission.field]:{...current[submission.field],flash:!1}}:current))},2e3);savedTimers.current.set(submission.field,timer)};React.useEffect(()=>{let active=!0,timer=null,controller=null,stopRequest=()=>{controller&&controller.abort(),controller=null,readController.current=null},check=({valid:valid2=()=>!0,onResult}={})=>{if(!active||document.hidden)return;if(timer!==null&&window.clearTimeout(timer),timer=null,stopRequest(),action.current){timer=window.setTimeout(check,5e3);return}let version2=++requestVersion.current,requestController=new AbortController;return controller=requestController,readController.current=requestController,api2("profile",{},{method:"GET",signal:requestController.signal}).then(latest=>{if(!(!active||document.hidden||version2!==requestVersion.current||!valid2())){if(!profileFieldNames.every(field=>typeof latest?.[field]=="string")||!latest?._revisions)throw new Error("\u753B\u50CF\u8BFB\u53D6\u54CD\u5E94\u4E0D\u5B8C\u6574");setProfile(current=>sameProfile(current,latest)?current:latest),setSyncStatus("\u5DF2\u662F\u6700\u65B0"),setError(""),onResult?.(latest)}}).catch(reason=>{active&&version2===requestVersion.current&&valid2()&&reason?.name!=="AbortError"&&(setSyncStatus("\u8BFB\u53D6\u5931\u8D25"),setError(String(reason?.message||reason)))}).finally(()=>{controller===requestController&&(controller=null,readController.current=null),active&&!document.hidden&&version2===requestVersion.current&&(timer=window.setTimeout(check,5e3))})};refreshRef.current=check;let onVisibilityChange=()=>{timer!==null&&window.clearTimeout(timer),timer=null,document.hidden?(++requestVersion.current,stopRequest()):check()};return document.addEventListener("visibilitychange",onVisibilityChange),check(),()=>{let submission=action.current?.submission;submission&&!profilePageMemory.get("saveResults")?.[submission.field]&&setSaveResults(current=>({...current,[submission.field]:{kind:"unknown",submission}})),active=!1,++session.current,++requestVersion.current,refreshRef.current=null,timer!==null&&window.clearTimeout(timer),stopRequest(),action.current?.abort(),action.current=null,window.clearTimeout(actionTimeout.current),actionTimeout.current=null,savedTimers.current.forEach(id2=>window.clearTimeout(id2)),savedTimers.current.clear(),setSaveResults(current=>Object.fromEntries(Object.entries(current).map(([field,result])=>[field,result.kind==="saved"?{...result,flash:!1}:result]))),document.removeEventListener("visibilitychange",onVisibilityChange)}},[]);let resetEdit=field=>{++session.current,++requestVersion.current,readController.current?.abort(),setReading(!1),field&&(setConflict(!1,field),clearSavedTimer(field),setSaveResults(current=>{let next2={...current};return delete next2[field],next2})),refreshRef.current?.()},beginEdit=field=>{resetEdit(profileFieldDrafts.has(field)?void 0:field),setEditing(profileFieldDrafts.get(field)||{field,draft:profile[field]||"",baseValue:profile[field]||"",baseRevision:profile._revisions?.[field]||0})},reloadField=()=>{if(!editing||saving||reading)return;let id2=session.current;setReading(!0),refreshRef.current?.({valid:()=>session.current===id2,onResult:latest=>{setEditing(current=>current?{...current,draft:latest[current.field],baseValue:latest[current.field],baseRevision:latest._revisions[current.field]}:null),setConflict(!1),setSaveResults(current=>{let next2={...current};return delete next2[editing.field],next2})}})?.finally(()=>{session.current===id2&&setReading(!1)})},save=()=>{if(!editing||action.current||saving||reading||saveResults[editing.field]?.kind==="unknown")return;if(conflict||profile[editing.field]!==editing.baseValue||profile._revisions?.[editing.field]!==editing.baseRevision){setConflict(!0);return}let submission={...editing},id2=session.current,controller=new AbortController;controller.submission=submission,action.current=controller;let valid2=()=>session.current===id2&&action.current===controller;setSaving(!0),setSaveResults(current=>{let next2={...current};return delete next2[submission.field],next2}),++requestVersion.current,readController.current?.abort();let timeout=window.setTimeout(()=>controller.abort(),15e3);actionTimeout.current=timeout,api2("profile",{},{method:"PATCH",signal:controller.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({field:submission.field,value:submission.draft,expectedValue:submission.baseValue,expectedRevision:submission.baseRevision})}).then(result=>{if(valid2()){if(!profileFieldNames.every(field=>typeof result?.snapshot?.[field]=="string")||!Number.isSafeInteger(result.snapshot?._revisions?.[submission.field]))throw new Error("\u753B\u50CF\u4FDD\u5B58\u54CD\u5E94\u4E0D\u5B8C\u6574");setProfile(result.snapshot),setEditing(null),setConflict(!1,submission.field),showSaved(submission)}}).catch(reason=>{if(!valid2())return;let message=String(reason?.message||reason);if(reason?.status===409||message.includes("\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0")){setConflict(!0);return}let unknown=!reason?.status||[408,502,504].includes(reason.status),invalid=[400,413,422].includes(reason?.status),maximum=profileGroups.flatMap(([,fields])=>fields).find(([field])=>field===submission.field)?.[2],detail=/Persistent Profile exceeds/.test(message)?"\u753B\u50CF\u603B\u5B57\u7B26\u6570\u4E0D\u80FD\u8D85\u8FC7 6000\uFF0C\u8BF7\u7F29\u77ED\u5185\u5BB9\u3002":/exceeds \d+ characters/.test(message)?"\u6B64\u5B57\u6BB5\u4E0D\u80FD\u8D85\u8FC7 "+maximum+" \u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u5185\u5BB9\u3002":message;setSaveResults(current=>({...current,[submission.field]:{kind:unknown?"unknown":invalid?"invalid":"failed",submission,detail}}))}).finally(()=>{window.clearTimeout(timeout),actionTimeout.current===timeout&&(actionTimeout.current=null),valid2()&&(action.current=null,setSaving(!1),refreshRef.current?.())})},checkSave=result=>{if(reading||action.current)return;let id2=session.current,{submission}=result;setReading(!0),refreshRef.current?.({valid:()=>session.current===id2,onResult:latest=>{latest[submission.field]===submission.draft&&Number.isSafeInteger(latest._revisions[submission.field])&&latest._revisions[submission.field]>submission.baseRevision&&(showSaved(submission),setEditing(current=>current?.field===submission.field?current.draft===submission.draft?null:{...current,baseValue:latest[submission.field],baseRevision:latest._revisions[submission.field]}:current),setConflict(!1,submission.field))}})?.finally(()=>{session.current===id2&&setReading(!1)})},total=profileTotalLength(profile),limit2=profileTotalLimit(profile);return h(React.Fragment,null,h("div",{className:"sg-pg-head"},h("h2",null,"\u5E38\u9A7B\u753B\u50CF"),h("span",{className:"sg-pg-tag"},h("i",{className:"sg-sw ink","aria-hidden":"true"}),"\u6BCF\u8F6E\u90FD\u5E26\u7ED9 AI \xB7 \u70B9\u4EFB\u610F\u4E00\u884C\u4FEE\u6539"),syncStatus==="\u8BFB\u53D6\u5931\u8D25"?h("span",{className:"sg-pg-end"},h("span",{className:"sg-profile-sync failed",role:"alert"},syncStatus)):null),error3?h("p",{className:"sg-profile-error",role:"alert"},error3):null,profile?h(React.Fragment,null,h("div",{className:"sg-cap-row"},h("div",{className:"sg-cap-bar",role:"img","aria-label":"\u5E38\u9A7B\u753B\u50CF\u5DF2\u7528 "+total+" \u5B57\uFF0C\u4E0A\u9650 "+formatCount(limit2)+" \u5B57"},h("i",{style:{width:Math.min(100,total/limit2*100)+"%"}})),h("span",{className:"sg-cap-num"},h("b",null,formatCount(total)),"/ "+formatCount(limit2)+" \u5B57")),h("div",{className:"sg-pf"},[["1",profileGroups.filter(([title])=>!profileRightColumn.has(title))],["2",profileGroups.filter(([title])=>profileRightColumn.has(title))]].map(([column,groups])=>h("div",{key:column,className:"sg-pf-col","data-pf-stack":column},groups.map(([title,fields])=>h("section",{key:title,className:"sg-profile-group","aria-label":title},h("h4",null,title),h("ul",null,fields.filter(([field])=>field!=="homeCity"||profile.homeCity||profileFieldDrafts.has(field)).map(([field,label,maximum])=>{let value=profile[field]||"",isEditing=editing?.field===field,changedElsewhere=isEditing&&(value!==editing.baseValue||profile._revisions?.[field]!==editing.baseRevision),draftLength=isEditing?Array.from(editing.draft).length:0,nextTotal=total-Array.from(value).length+draftLength,result=saveResults[field],savedReadError=result?.kind==="saved"&&!!error3,savedFeedback=result?.kind==="saved"&&result.flash?h("span",{className:"sg-profile-saved",role:"status"},isEditing&&editing.draft!==result.submission.draft?"\u4E0A\u6B21\u63D0\u4EA4\u5DF2\u4FDD\u5B58":"\u5DF2\u4FDD\u5B58"):null,editor=isEditing?h("div",{className:"sg-profile-editor"},field==="userPreferredName"||field==="assistantPreferredName"||field==="preferredLanguage"||field==="reasoningLanguage"||field==="defaultLocation"||field==="homeCity"||field==="currentCity"?h("input",{id:"sg-profile-"+field,"aria-label":label,autoFocus:!0,disabled:saving,value:editing.draft,onChange:event3=>setEditing(current=>({...current,draft:event3.target.value}))}):h("textarea",{id:"sg-profile-"+field,"aria-label":label,autoFocus:!0,disabled:saving,value:editing.draft,onChange:event3=>setEditing(current=>({...current,draft:event3.target.value}))}),changedElsewhere||conflict?h("p",{className:"sg-profile-conflict",role:"alert"},"\u8BE5\u9879\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0\u3002",h("button",{type:"button",className:"sg-profile-action",disabled:saving||reading,onClick:reloadField},"\u653E\u5F03\u8349\u7A3F\u5E76\u8F7D\u5165\u6700\u65B0\u5185\u5BB9")):null,result&&["failed","invalid","unknown"].includes(result.kind)?h("div",{className:"sg-profile-save-feedback sg-profile-save-feedback-"+result.kind,role:result.kind==="unknown"?"status":"alert"},h("p",null,result.kind==="unknown"?"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u662F\u5426\u5DF2\u4FDD\u5B58\uFF0C\u8F93\u5165\u5185\u5BB9\u5DF2\u4FDD\u7559\u3002":"\u4FEE\u6539\u672A\u4FDD\u5B58\uFF0C\u8F93\u5165\u5185\u5BB9\u5DF2\u4FDD\u7559\u3002"),result.kind==="unknown"?h("button",{type:"button",className:"sg-profile-action",disabled:reading,onClick:()=>checkSave(result)},reading?"\u68C0\u67E5\u4E2D\u2026":"\u68C0\u67E5\u4FDD\u5B58\u7ED3\u679C"):result.kind==="invalid"?h("p",null,result.detail):null):null,h("div",{className:"sg-profile-editor-foot"},h("span",{className:"sg-profile-count"},formatCount(draftLength)+" / "+formatCount(maximum),draftLength>maximum?"\uFF0C\u8BF7\u7F29\u77ED\u81F3 "+formatCount(maximum)+" \u4E2A\u5B57\u7B26\u4EE5\u5185\u3002":nextTotal>limit2?"\uFF0C\u753B\u50CF\u603B\u5B57\u7B26\u6570\u4E0D\u80FD\u8D85\u8FC7 "+formatCount(limit2)+"\u3002":"",savedFeedback),h("div",{className:"sg-profile-actions"},h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:()=>{resetEdit(field),setEditing(null)}},"\u53D6\u6D88\u7F16\u8F91"),h("button",{type:"button",className:"sg-save-button",disabled:saving||reading||result?.kind==="unknown"||draftLength>maximum||nextTotal>limit2||editing.draft===editing.baseValue||changedElsewhere||conflict,onClick:save},saving?"\u4FDD\u5B58\u4E2D\u2026":result?.kind==="failed"?"\u91CD\u65B0\u4FDD\u5B58":"\u4FDD\u5B58")))):null;return h("li",{key:field,className:"sg-profile-row",onClick:isEditing?void 0:()=>{saving||beginEdit(field)}},h("div",{className:"sg-profile-summary"+(isEditing?" editing":"")},h("div",{className:"sg-profile-label-cell"},h("span",{className:"sg-profile-label"},label),editor||h("span",{className:"sg-profile-content"},h("button",{type:"button",className:"sg-profile-value "+(value?"":"empty"),title:value||PROFILE_EMPTY_HINTS[field],"aria-label":label+(value?"\uFF0C\u70B9\u51FB\u7F16\u8F91":"\uFF0C\u672A\u586B\u5199\uFF0C\u70B9\u51FB\u586B\u5199"),disabled:saving,onClick:event3=>{event3?.stopPropagation?.(),beginEdit(field)}},profileFieldDrafts.has(field)?"\u7EE7\u7EED\u7F16\u8F91\u8349\u7A3F":value||"\u672A\u586B\u5199"),savedFeedback)),isEditing?null:h("span",{className:"sg-profile-chev","aria-hidden":"true"},"\u203A"),h("button",{type:"button",className:"sg-profile-action",onClick:event3=>{event3?.stopPropagation?.(),beginEdit(field)},disabled:saving,"aria-hidden":isEditing||void 0},!isEditing&&profileFieldDrafts.has(field)?"\u7EE7\u7EED\u7F16\u8F91":value?"\u7F16\u8F91":"\u6DFB\u52A0")),savedReadError?h("p",{className:"sg-profile-save-feedback",role:"status"},h("span",null,"\u4FEE\u6539\u5DF2\u4FDD\u5B58\uFF0C\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6700\u65B0\u5185\u5BB9\u3002"),h("button",{type:"button",className:"sg-profile-action",disabled:reading,onClick:()=>refreshRef.current?.()},"\u91CD\u65B0\u8BFB\u53D6")):null)})))))))):h("p",null,"\u6B63\u5728\u8BFB\u53D6\u5E38\u9A7B\u753B\u50CF\u2026"))}let GRAPH_EXPLANATION="\u7531\u4E8E\u77E5\u8BC6\u56FE\u8C31\u529F\u80FD\u4E0E\u4E8B\u4EF6\u8BB0\u5F55\u548C\u4E3B\u9898\u76EE\u5F55\u6709\u90E8\u5206\u91CD\u590D\uFF0C\u8FD8\u9700\u8981\u989D\u5916\u6D88\u8017token\u7EF4\u62A4\u5B9E\u4F53\u5173\u7CFB\uFF0C\u5C06\u4F1A\u9ED8\u8BA4\u5173\u95ED\u77E5\u8BC6\u56FE\u8C31\u529F\u80FD\uFF0C\u5DF2\u7ECF\u751F\u6210\u7684\u56FE\u8C31\u6570\u636E\u4F1A\u4FDD\u7559\u3002",GRAPH_USAGE_HINT="\u63D0\u793A\uFF1A\u5982\u9700\u4F7F\u7528\uFF0C\u53EF\u4EE5\u5728\u957F\u671F\u8BB0\u5FC6\u9875\u9762\u70B9\u51FB\u201C\uFF0B\u201D\uFF0C\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31\uFF0C\u529F\u80FD\u53EF\u4EE5\u6B63\u5E38\u4F7F\u7528\u3002",GRAPH_CONTROL_STYLES=".sg-graph-no-reminder{display:inline-flex;align-items:center;min-height:30px;padding:5px 8px;border:1px solid var(--sg-border);border-radius:6px;background:var(--sg-surface);color:var(--sg-muted);cursor:pointer}.sg-graph-no-reminder:hover{border-color:var(--sg-accent);color:var(--sg-accent);background:var(--sg-soft)}.sg-graph-no-reminder:disabled{cursor:not-allowed;opacity:.5}.sg-graph-notice-toggle{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 0;border-top:1px solid var(--sg-border);border-bottom:1px solid var(--sg-border)}.sg-graph-notice-toggle>span{font-size:13px;font-weight:650}.sg-graph-menu{position:relative;z-index:31;display:inline-flex;align-items:center}.sg-long-tabs .sg-graph-menu-trigger{display:grid;place-items:center;align-self:center;flex:none;box-sizing:border-box;width:32px;height:32px;min-width:32px;min-height:32px;padding:0;border:0;border-radius:999px;background:transparent;color:var(--sg-muted);font-size:22px;line-height:1;cursor:pointer}.sg-graph-menu-trigger svg{display:block;width:16px;height:16px;flex:none}.sg-graph-menu-trigger:hover,.sg-graph-menu-trigger[aria-expanded=true]{background:var(--sg-soft);color:var(--sg-accent)}.sg-graph-menu-popover{position:absolute;z-index:32;right:0;left:auto;top:calc(100% + 8px);width:min(300px,calc(100vw - 32px));padding:10px;border:1px solid var(--sg-border);border-radius:10px;background:var(--sg-page);box-shadow:var(--sg-shadow);text-align:left}.sg-graph-menu-title{display:block;padding:0 2px 8px;color:var(--sg-text);font-size:13px;font-weight:650;line-height:1.4}.sg-graph-open{display:block;width:100%;margin-top:8px;padding:6px 2px 2px;border:0;border-top:1px solid var(--sg-border);background:none;color:var(--sg-text);font-size:12.5px;text-align:left;cursor:pointer}.sg-graph-open:hover{color:var(--sg-accent)}.sg-graph-copy{display:block;min-width:0}.sg-graph-title-row{display:flex;align-items:center;gap:6px;min-width:0}.sg-graph-copy b{display:block;font-size:13.5px;font-weight:650;color:var(--sg-text)}.sg-graph-copy span{display:block;margin-top:2px;font-size:11.5px;line-height:1.45;color:var(--sg-muted)}.sg-graph-title-row .sg-info-disclosure{display:inline-flex;flex:none} .sg-graph-copy .sg-graph-title-row{display:flex}.sg-graph-title-row .sg-info-trigger{width:18px;height:18px;font-size:12px}.sg-graph-menu-popover .sg-storage-card{padding:0;border:0;background:transparent}.sg-graph-menu-popover .sg-setting-note{font-size:11px;line-height:1.5}.sg-graph-dialog-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}.sg-graph-dialog-heading h3{margin:0}.sg-graph-dialog-control{display:flex;align-items:center;gap:7px;color:var(--sg-muted);font-size:12px}";function GraphControlPanel({state={},refresh,page=!1,onGraphHidden,onOpenGraph}){let shouldShowNotice=!page&&state.enabled!==!0&&state.noticeSeen!==!0,[notice,setNotice]=React.useState(shouldShowNotice),[preview,setPreview]=React.useState(null),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[hideExplanation,setHideExplanation]=React.useState(!1),dialogRef=React.useRef(null);React.useEffect(()=>{setNotice(!page&&state.enabled!==!0&&state.noticeSeen!==!0)},[page,state.enabled,state.noticeSeen]),React.useEffect(()=>{if(!notice&&!preview)return;let previous=document.activeElement;return dialogRef.current?.querySelector("button")?.focus(),()=>{previous?.isConnected&&previous.focus?.()}},[notice,preview]);let control=async(action,token)=>{setBusy(!0),setError("");try{let result=await api2("graph/control",{action,...token?{token}:{}},{method:"POST"});action==="preview"?result.pending>0?setPreview(result):(await api2("graph/control",{action:"enable",token:result.token},{method:"POST"}),await refresh?.()):(setPreview(null),action==="notice"&&(setNotice(!1),setHideExplanation(!0),onGraphHidden?.()),await refresh?.())}catch(reason){setError(String(reason?.message||reason))}finally{setBusy(!1)}},graphStatus=state.enabled===!0?state.paused?"\u5DF2\u6682\u505C\u66F4\u65B0\uFF0C\u53EF\u67E5\u770B\u65E7\u56FE\u8C31":"\u5DF2\u5F00\u542F":"\u9ED8\u8BA4\u5173\u95ED\uFF0C\u6253\u5F00\u540E\u53EF\u67E5\u770B\u5DF2\u6709\u56FE\u8C31",graphInfo=page?null:h(InfoPopover,{label:"\u77E5\u8BC6\u56FE\u8C31\u8BF4\u660E"},h("p",null,GRAPH_EXPLANATION),h("p",null,GRAPH_USAGE_HINT)),showExplanation=!hideExplanation&&(!page||state.noticeSeen!==!0);return h(React.Fragment,null,h("style",null,GRAPH_CONTROL_STYLES),h("aside",{className:"sg-storage-card sg-graph-control"+(page?" sg-graph-page-control":""),"aria-label":page?"\u77E5\u8BC6\u56FE\u8C31\u5F00\u5173":void 0},h("div",{className:"sg-stage"},h("span",{className:"sg-graph-copy"},h("span",{className:"sg-graph-title-row"},h("b",null,page?"\u663E\u793A\u77E5\u8BC6\u56FE\u8C31":"\u542F\u7528\u77E5\u8BC6\u56FE\u8C31"),graphInfo),page?h("span",null,graphStatus):null),h("span",{className:"sg-lambda-control sg-graph-toggle"},!page&&showExplanation?h("button",{type:"button",className:"sg-icon-button","aria-label":"\u4E0D\u518D\u63D0\u9192",title:"\u4E0D\u518D\u63D0\u9192",disabled:busy,onClick:()=>{control("notice")}},"\xD7"):null,h("button",{type:"button",role:"switch","aria-label":"\u663E\u793A\u77E5\u8BC6\u56FE\u8C31","aria-checked":state.enabled===!0,disabled:busy,className:"sg-setting-switch",onClick:()=>{control(state.enabled?"disable":"preview")}}))),page&&state.enabled===!0?h("button",{type:"button",className:"sg-graph-open",onClick:()=>onOpenGraph?.()},"\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31 \u2192"):null,!page&&state.enabled?h("button",{type:"button",className:"sg-storage-button",disabled:busy,onClick:()=>{control(state.paused?"preview":"pause")}},state.paused?"\u7EDF\u8BA1\u5E76\u7EE7\u7EED\u56FE\u8C31\u4EFB\u52A1":"\u6682\u505C\u56FE\u8C31\u4EFB\u52A1"):null,error3?h("p",{role:"alert",className:"sg-error-note"},error3):null,notice||preview?h("div",{className:"sg-import-overlay"},h("section",{ref:dialogRef,role:"dialog","aria-modal":"true","aria-label":notice?"\u77E5\u8BC6\u56FE\u8C31\u9ED8\u8BA4\u5173\u95ED\u8BF4\u660E":"\u786E\u8BA4\u6062\u590D\u77E5\u8BC6\u56FE\u8C31",className:"sg-import-dialog",onKeyDown:event3=>{if(event3.key==="Escape"&&preview&&!notice&&!busy&&(event3.preventDefault(),setPreview(null)),event3.key==="Tab"){let buttons=[...dialogRef.current.querySelectorAll("button:not(:disabled)")];if(!buttons.length){event3.preventDefault();return}let first2=buttons[0],last2=buttons.at(-1);event3.shiftKey&&document.activeElement===first2?(event3.preventDefault(),last2.focus()):!event3.shiftKey&&document.activeElement===last2&&(event3.preventDefault(),first2.focus())}}},h("div",{className:"sg-graph-dialog-heading"},h("h3",null,notice?"\u77E5\u8BC6\u56FE\u8C31\u9ED8\u8BA4\u5173\u95ED":"\u786E\u8BA4\u6062\u590D\u77E5\u8BC6\u56FE\u8C31"),notice?h("span",{className:"sg-graph-dialog-control"},h("span",null,"\u5F00\u542F"),h("button",{type:"button",role:"switch","aria-label":"\u542F\u7528\u77E5\u8BC6\u56FE\u8C31","aria-checked":state.enabled===!0,disabled:busy,className:"sg-setting-switch",onClick:()=>{control("preview")}})):null),h("p",null,GRAPH_EXPLANATION),h("p",null,GRAPH_USAGE_HINT),preview&&!notice?h("p",null,"\u5F53\u524D\u6709 "+preview.pending+" \u6761\u5F85\u5904\u7406\u4E8B\u4EF6\uFF0C\u7EA6 "+preview.batches+" \u4E2A\u6279\u6B21\u3002\u786E\u8BA4\u540E\u4EC5\u8865\u5EFA\u8FD9\u4EFD\u6E05\u5355\uFF0C\u6CBF\u7528\u73B0\u6709\u79DF\u7EA6\u3001\u5E76\u53D1\u548C\u91CD\u8BD5\u9650\u989D\uFF1B\u53EF\u968F\u65F6\u6682\u505C\u3002"):null,notice&&!preview?h("button",{type:"button",className:"sg-graph-no-reminder",disabled:busy,onClick:()=>{control("notice")}},"\u6682\u65F6\u5173\u95ED"):!notice&&preview?h(React.Fragment,null,h("button",{type:"button",disabled:busy,onClick:()=>setPreview(null)},"\u53D6\u6D88"),h("button",{type:"button",disabled:busy,onClick:()=>{control("enable",preview.token)}},"\u786E\u8BA4\u5F00\u542F\u5E76\u5206\u6279\u5904\u7406")):null,!notice&&!preview?h("button",{type:"button",className:"sg-graph-no-reminder",disabled:busy,onClick:()=>{control("notice")}},"\u6682\u65F6\u5173\u95ED"):null)):null))}function GraphSettingsPanel({state={},refresh}){return h(GraphControlPanel,{state,refresh})}function DailyNotesSettings({usePluginSettings,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[saving,setSaving]=React.useState(!1),[error3,setError]=React.useState(""),localTimeZone=Intl.DateTimeFormat().resolvedOptions().timeZone,timeZone=settings?.value?.dailyNotesTimeZone||"",enabled=settings?.value?.dailyNotesEnabled!==!1,injectionDays=settings?.value?.dailyNotesInjectionDays??3,zones=[...new Set(["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Asia/Kolkata","Europe/London","Europe/Berlin","America/New_York","America/Los_Angeles","Australia/Sydney","UTC",timeZone].filter(Boolean))],save=async(setter,value)=>{setSaving(!0),setError("");try{(!setter||!await setter(value))&&setError("\u672A\u80FD\u4FDD\u5B58\u7B14\u8BB0\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u8BD5\u3002")}catch(reason){setError("\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason.message||reason))}finally{setSaving(!1)}},disabled=settings?.writable!==!0||saving;return h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u77ED\u671F\u8BB0\u5FC6"),h("span",{className:"sg-display-setting-description"},"\u6BCF\u5929\u4E00\u4EFD\u5DE5\u4F5C\u7B14\u8BB0\u3002\u5173\u95ED\u540E\u4E0D\u518D\u5199\u5165\u548C\u6CE8\u5165\uFF0C\u5DF2\u6709\u7B14\u8BB0\u4FDD\u7559\u3002")),h("button",{type:"button",className:"sg-setting-switch",role:"switch","aria-label":"\u77ED\u671F\u8BB0\u5FC6","aria-checked":enabled,disabled:disabled||!setDailyEnabled,onClick:()=>{save(setDailyEnabled,!enabled)}})),h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570"),h("span",{className:"sg-display-setting-description"},"\u53D6\u6700\u8FD1\u6709\u7B14\u8BB0\u7684\u65E5\u671F\uFF0C\u9ED8\u8BA4 3 \u5929\u3002\u4FEE\u6539\u540E\u7528\u4E8E\u65B0\u4F1A\u8BDD\uFF1B\u5185\u5BB9\u4ECD\u53D7\u957F\u5EA6\u4E0A\u9650\u7EA6\u675F\u3002")),h("select",{className:"sg-effort-select","aria-label":"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570",value:injectionDays,disabled:disabled||!setDailyInjectionDays,onChange:event3=>{save(setDailyInjectionDays,Number(event3.target.value))}},Array.from({length:30},(_,i2)=>h("option",{key:i2+1,value:i2+1},i2+1+" \u5929")))),h("div",{className:"sg-stage"},h("span",null,"\u7B14\u8BB0\u65F6\u533A"),h("select",{className:"sg-effort-select",style:{maxWidth:"100%",minWidth:0},"aria-label":"\u7B14\u8BB0\u65F6\u533A",value:timeZone,disabled:disabled||!setDailyTimeZone,onChange:event3=>{save(setDailyTimeZone,event3.target.value)}},h("option",{value:""},"\u8DDF\u968F\u672C\u673A\uFF08"+localTimeZone+"\uFF09"),zones.map(zone=>h("option",{key:zone,value:zone},zone)))),error3?h("p",{className:"sg-storage-feedback failed",role:"alert"},error3):null)}function ProfileLimitSettings(){let[profile,setProfile]=React.useState(null),[loading,setLoading]=React.useState(!0),[loadError,setLoadError]=React.useState(""),[editing,setEditing]=React.useState(!1),[draft,setDraft]=React.useState(""),[saving,setSaving]=React.useState(!1),[error3,setError]=React.useState(""),total=profileTotalLength(profile),limit2=profileTotalLimit(profile);React.useEffect(()=>{let controller=new AbortController;return api2("profile",{},{method:"GET",signal:controller.signal}).then(value=>{controller.signal.aborted||setProfile(value),setLoadError("")}).catch(reason=>{controller.signal.aborted||setLoadError("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u753B\u50CF\u7528\u91CF\uFF1A"+String(reason?.message||reason))}).finally(()=>{controller.signal.aborted||setLoading(!1)}),()=>controller.abort()},[]);let begin=()=>{loading||loadError||(setDraft(String(limit2)),setError(""),setEditing(!0))},cancel=()=>{saving||(setEditing(!1),setError(""))},save=async()=>{if(saving)return;let next2=Number(draft);if(!Number.isSafeInteger(next2)||next2<PROFILE_LIMIT_MIN||next2>PROFILE_LIMIT_MAX){setError("\u8BF7\u8F93\u5165 "+formatCount(PROFILE_LIMIT_MIN)+" \u5230 "+formatCount(PROFILE_LIMIT_MAX)+" \u4E4B\u95F4\u7684\u6574\u6570\u3002");return}if(next2<total){setError("\u4E0A\u9650\u4E0D\u80FD\u4F4E\u4E8E\u5F53\u524D\u5DF2\u7528\u7684 "+formatCount(total)+" \u5B57\u3002");return}if(next2===limit2){setEditing(!1);return}setSaving(!0),setError("");try{let result=await api2("settings",null,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileMaxLength:next2})}),saved=Number(result?.profileMaxLength);if(!Number.isSafeInteger(saved)||saved!==next2)throw new Error("\u4E0A\u9650\u4FDD\u5B58\u7ED3\u679C\u4E0D\u5B8C\u6574");setProfile(current=>current&&{...current,_limits:{...current._limits||{},totalMaxLength:next2}}),setEditing(!1)}catch(reason){setError("\u4E0A\u9650\u672A\u4FDD\u5B58\uFF1A"+String(reason?.message||reason))}finally{setSaving(!1)}};return h("div",{className:"sg-settings-panel sg-profile-limit","data-testid":"stratagate-profile-limit-settings"},h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u5E38\u9A7B\u753B\u50CF\u5B57\u6570\u4E0A\u9650"),h("span",{className:"sg-display-setting-description"},"\u9650\u5236\u6BCF\u8F6E\u5E26\u5165\u7684\u5E38\u9A7B\u753B\u50CF\u603B\u91CF\uFF0C\u4E0D\u80FD\u4F4E\u4E8E\u5F53\u524D\u5DF2\u5199\u5185\u5BB9\u3002")),h("span",{className:"sg-profile-limit-control"},loading?h("span",{className:"sg-setting-note"},"\u8BFB\u53D6\u4E2D\u2026"):h(React.Fragment,null,loadError?null:h("span",{className:"sg-profile-limit-value","aria-label":"\u5E38\u9A7B\u753B\u50CF\u5DF2\u7528 "+total+" \u5B57\uFF0C\u4E0A\u9650 "+formatCount(limit2)+" \u5B57"},formatCount(total)+" / "+formatCount(limit2)+" \u5B57"),!loadError&&!editing?h("button",{type:"button",className:"sg-cap-limit",onClick:begin},"\u8C03\u6574\u4E0A\u9650"):null))),editing?h("div",{className:"sg-cap-edit sg-profile-limit-edit"},h("input",{type:"number",inputMode:"numeric",min:PROFILE_LIMIT_MIN,max:PROFILE_LIMIT_MAX,step:100,"aria-label":"\u5E38\u9A7B\u753B\u50CF\u5B57\u6570\u4E0A\u9650",value:draft,disabled:saving,autoFocus:!0,onChange:event3=>setDraft(event3.target.value),onKeyDown:event3=>{event3.key==="Enter"?(event3.preventDefault(),save()):event3.key==="Escape"&&(event3.preventDefault(),cancel())}}),h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:cancel},"\u53D6\u6D88"),h("button",{type:"button",className:"sg-save-button",disabled:saving,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):null,loadError?h("p",{className:"sg-storage-feedback failed",role:"alert"},loadError):null,error3?h("p",{className:"sg-cap-error",role:"alert"},error3):null)}function MemoryModelSettings({usePluginSettings,setMemoryModel}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[catalog,setCatalog]=React.useState(null),[draft,setDraft]=React.useState(null),customDraft=React.useRef(null),[models,setModels]=React.useState([]),[loading,setLoading]=React.useState(!1),[catalogError,setCatalogError]=React.useState(""),[modelsError,setModelsError]=React.useState(""),[feedback,setFeedback]=React.useState({kind:"",text:""}),[saving,setSaving]=React.useState(!1),[revision,setRevision]=React.useState(0);React.useEffect(()=>{if(feedback.kind!=="done")return;let timer=window.setTimeout(()=>setFeedback({kind:"",text:""}),4500);return()=>window.clearTimeout(timer)},[feedback]);let saved=settings?.value?.memoryModel||catalog?.selection||{mode:"auto"},value=draft||saved,provider=value.mode==="custom"&&value.provider||"";React.useEffect(()=>{let active=!0;return settings?.value?.memoryModel?.mode==="auto"&&value.mode==="auto"?(setCatalog(null),setCatalogError(""),()=>{active=!1}):(setCatalogError(""),api2("models").then(result=>{active&&setCatalog(result)}).catch(reason=>{active&&setCatalogError(String(reason?.message||reason))}),()=>{active=!1})},[revision,settings?.value?.memoryModel?.mode,value.mode]),React.useEffect(()=>{let active=!0;return setModels([]),setModelsError(""),provider?(setLoading(!0),api2("models",{provider}).then(result=>{active&&setModels(result.models)}).catch(reason=>{active&&setModelsError(String(reason?.message||reason))}).finally(()=>{active&&setLoading(!1)}),()=>{active=!1}):(setLoading(!1),()=>{active=!1})},[provider,revision]);let providers=catalog?.providers||[],custom=value.mode==="custom";React.useEffect(()=>{if(!draft||!custom||provider||!providers[0])return;let next2={...value,provider:providers[0].id};customDraft.current=next2,setDraft(next2)},[providers,custom,provider,draft,value]);let valid2=!custom||providers.some(item=>item.id===provider)&&!!value.model?.trim(),changed=value.mode!==saved.mode||custom&&(value.provider!==saved.provider||value.model!==saved.model),editingDisabled=settings?.writable!==!0||!setMemoryModel||saving,disabled=editingDisabled,edit=next2=>{next2.mode==="custom"&&(customDraft.current=next2),setDraft(next2),setFeedback({kind:"",text:""})},save=async()=>{if(!(disabled||!valid2||!changed)){setSaving(!0),setFeedback({kind:"",text:""});try{if(!await setMemoryModel(value))throw new Error("\u5BBF\u4E3B\u672A\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002");setCatalog(current=>({...current,selection:value})),setDraft(null),setFeedback({kind:"done",text:"\u5DF2\u4FDD\u5B58\uFF0C\u5BF9\u540E\u7EED\u8BB0\u5FC6\u5904\u7406\u8C03\u7528\u751F\u6548\u3002\u6B63\u5728\u8FD0\u884C\u7684\u8C03\u7528\u7EE7\u7EED\u5B8C\u6210\u3002"})}catch(reason){setFeedback({kind:"failed",text:"\u672A\u80FD\u786E\u8BA4\u4FDD\u5B58\uFF1A"+String(reason?.message||reason)+" \u5F53\u524D\u9009\u62E9\u5DF2\u4FDD\u7559\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{setSaving(!1)}}},savedProvider=providers.find(item=>item.id===saved.provider)?.name||saved.provider,savedModel=saved.provider===provider&&models.find(item=>item.id===saved.model)?.name||saved.model,pendingProvider=providers.find(item=>item.id===value.provider)?.name||value.provider,pendingModel=value.provider===provider&&models.find(item=>item.id===value.model)?.name||value.model,savedSummary=saved.mode==="custom"?savedProvider+" / "+savedModel:"\u8DDF\u968F\u804A\u5929\u6A21\u578B",pendingSummary=value.mode==="custom"?pendingProvider+" / "+pendingModel:"\u8DDF\u968F\u804A\u5929\u6A21\u578B";return h("div",{className:"sg-settings-panel sg-model-settings"},h("h4",{className:"sg-model-heading"},"\u8BB0\u5FC6\u5904\u7406\u6A21\u578B"),h("div",{className:"sg-model-modes",role:"radiogroup","aria-label":"\u8BB0\u5FC6\u5904\u7406\u6A21\u578B"},[{mode:"auto",title:"\u8DDF\u968F\u804A\u5929\u6A21\u578B"},{mode:"custom",title:"\u5355\u72EC\u6307\u5B9A\u6A21\u578B"}].map(item=>h("label",{key:item.mode,className:"sg-model-mode"+(value.mode===item.mode?" selected":"")},h("input",{type:"radio",name:"sg-memory-model-mode",value:item.mode,checked:value.mode===item.mode,disabled:editingDisabled,onChange:()=>edit(item.mode==="auto"?{mode:"auto"}:customDraft.current||(saved.mode==="custom"?saved:{mode:"custom",provider:providers[0]?.id||"",model:""}))}),h("span",{className:"sg-model-mode-copy"},h("span",{className:"sg-model-mode-title"},item.title))))),custom?h(React.Fragment,null,h("div",{className:"sg-model-fields"},h("label",{className:"sg-model-field"},"\u670D\u52A1\u5546",h("select",{className:"sg-effort-select","aria-label":"\u8BB0\u5FC6\u5904\u7406\u670D\u52A1\u5546",value:provider,disabled:editingDisabled||!catalog,onChange:event3=>edit({mode:"custom",provider:event3.target.value,model:""})},h("option",{value:""},"\u8BF7\u9009\u62E9\u670D\u52A1\u5546"),provider&&!providers.some(item=>item.id===provider)?h("option",{value:provider},provider+"\uFF08\u5F53\u524D\u4E0D\u53EF\u7528\uFF09"):null,providers.map(item=>h("option",{key:item.id,value:item.id},item.name||item.id)))),h("label",{className:"sg-model-field"},"\u6A21\u578B",h("select",{className:"sg-effort-select","aria-label":"\u8BB0\u5FC6\u5904\u7406\u5177\u4F53\u6A21\u578B",value:value.model||"",disabled:editingDisabled||!catalog||!provider||loading||!!modelsError,onChange:event3=>edit({...value,model:event3.target.value})},h("option",{value:""},loading?"\u6B63\u5728\u8BFB\u53D6\u6A21\u578B\u2026":"\u8BF7\u9009\u62E9\u6A21\u578B"),value.model&&!models.some(item=>item.id===value.model)?h("option",{value:value.model},value.model+"\uFF08\u672A\u5728\u5217\u8868\u4E2D\uFF09"):null,models.map(item=>h("option",{key:item.id,value:item.id},item.name||item.id))))),null):null,custom&&!catalog&&!catalogError?h("p",{className:"sg-status-feedback",role:"status"},"\u6B63\u5728\u8BFB\u53D6\u670D\u52A1\u5546\u2026"):null,settings&&settings.writable!==!0?h("p",{className:"sg-status-feedback"},"\u5F53\u524D\u914D\u7F6E\u4E3A\u53EA\u8BFB\u3002"):null,catalogError||modelsError?h("p",{className:"sg-status-feedback failed",role:"alert"},"\u8BFB\u53D6\u5931\u8D25\uFF1A"+(catalogError||modelsError)," ",h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:()=>setRevision(current=>current+1)},"\u91CD\u65B0\u8BFB\u53D6")):null,h("div",{className:"sg-model-save-row"},h("div",{className:"sg-model-saved"},h("span",{className:"sg-model-active-label"},"\u5F53\u524D\u751F\u6548"),h("strong",null,catalog||settings?.value?.memoryModel?savedSummary:"\u8DDF\u968F\u804A\u5929\u6A21\u578B"),changed?h("span",{className:"sg-model-pending"},"\u2192 "+pendingSummary):null),changed?h("button",{type:"button",className:"sg-save-button",disabled:editingDisabled||!valid2||custom&&!catalog,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58"):h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"})),feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null)}function RetrievalModelSettings({kind,settings,writable,onSaved}){let embedding=kind==="embedding",title=embedding?"\u5411\u91CF\u68C0\u7D22":"\u7ED3\u679C\u7CBE\u6392\uFF08Rerank\uFF09",prefix=embedding?"embedding":"rerank",urlKey=prefix+"Url",secretKey=prefix+"Key",modelKey=prefix+"Model",[saved,setSaved]=React.useState(settings||null),[draft,setDraft]=React.useState({}),[models,setModels]=React.useState([]),[listing,setListing]=React.useState(!1),[listFeedback,setListFeedback]=React.useState(""),[saving,setSaving]=React.useState(!1),[reading,setReading]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),lookup2=React.useRef(0);React.useEffect(()=>{settings&&setSaved(settings)},[settings]),React.useEffect(()=>()=>{lookup2.current+=1},[]),React.useEffect(()=>{if(feedback.kind!=="done")return;let timer=window.setTimeout(()=>setFeedback({kind:"",text:""}),4500);return()=>window.clearTimeout(timer)},[feedback]);let value=key=>draft[key]??saved?.[key]??"",url=String(value(urlKey)).trim().replace(/\/+$/,""),keyEdited=Object.hasOwn(draft,secretKey),keyConfigured=keyEdited?!!draft[secretKey].trim():saved?.[prefix+"KeyConfigured"]===!0,urlValid=!url;try{urlValid=["http:","https:"].includes(new URL(url).protocol)}catch{}let numericValid=!embedding||["vectorWeight","embeddingMinScore"].every(key=>{let raw=draft[key]??saved?.[key]??(key==="vectorWeight"?1:.3);return String(raw).trim()!==""&&Number.isFinite(Number(raw))&&Number(raw)>=0&&Number(raw)<=(key==="vectorWeight"?5:1)}),changed=Object.keys(draft).some(key=>key===secretKey||String(draft[key])!==String(saved?.[key]??"")),disabled=!saved||writable!==!0||saving||reading,edit=(key,next2)=>{setDraft(current=>({...current,[key]:next2})),setFeedback({kind:"",text:""}),(key===urlKey||key===secretKey)&&(lookup2.current+=1,setModels([]),setListing(!1),setListFeedback(""))},listModels=async()=>{if(disabled||listing||!url||!urlValid||!keyConfigured)return;let request=++lookup2.current;setListing(!0),setModels([]),setListFeedback("");try{let result=await api2("models",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind,url,...keyEdited?{key:draft[secretKey].trim()}:{}})});if(request!==lookup2.current)return;let ids=Array.isArray(result.models)?result.models.filter(id2=>typeof id2=="string"&&id2):[];setModels(ids),setListFeedback(ids.length?"\u5DF2\u8BFB\u53D6\u6A21\u578B\u5217\u8868\u3002\u8BF7\u9009\u62E9\u5BF9\u5E94\u7C7B\u578B\u7684\u6A21\u578B\uFF0C\u4E5F\u53EF\u624B\u52A8\u586B\u5199\u3002":"\u672A\u80FD\u8BFB\u53D6\u6A21\u578B\u5217\u8868\uFF0C\u53EF\u91CD\u8BD5\u6216\u624B\u52A8\u586B\u5199\u6A21\u578B\u540D\u79F0\u3002")}catch{request===lookup2.current&&setListFeedback("\u672A\u80FD\u8BFB\u53D6\u6A21\u578B\u5217\u8868\uFF0C\u53EF\u91CD\u8BD5\u6216\u624B\u52A8\u586B\u5199\u6A21\u578B\u540D\u79F0\u3002")}finally{request===lookup2.current&&setListing(!1)}},save=async()=>{if(disabled||!changed||!urlValid||!numericValid)return;let patch={};for(let key of Object.keys(draft))patch[key]=key==="vectorWeight"||key==="embeddingMinScore"?Number(draft[key]):key===urlKey?url:draft[key].trim();setSaving(!0),setFeedback({kind:"",text:""}),lookup2.current+=1,setListing(!1);try{let result=await api2("settings",null,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(patch)});if(!result.vectorSettings||typeof result.vectorSettings[prefix+"Ready"]!="boolean")throw new Error("Missing saved settings");setSaved(result.vectorSettings),setDraft({}),onSaved?.(result.vectorSettings),setFeedback({kind:"done",text:"\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002"})}catch{setFeedback({kind:"failed",text:"\u672A\u80FD\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8F93\u5165\u5DF2\u4FDD\u7559\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u914D\u7F6E\u540E\u6838\u5BF9\uFF0C\u6216\u91CD\u8BD5\u4FDD\u5B58\u3002"})}finally{setSaving(!1)}},readSaved=async()=>{if(!(saving||reading)){setReading(!0);try{let result=await api2("overview");if(!result.vectorSettings||typeof result.vectorSettings[prefix+"Ready"]!="boolean")throw new Error("Missing saved settings");setSaved(result.vectorSettings),onSaved?.(result.vectorSettings),setFeedback({kind:"done",text:"\u5DF2\u91CD\u65B0\u8BFB\u53D6\u4FDD\u5B58\u7684\u914D\u7F6E\uFF1B\u672A\u4FDD\u5B58\u8F93\u5165\u5DF2\u4FDD\u7559\u3002"})}catch{setFeedback({kind:"failed",text:"\u672A\u80FD\u8BFB\u53D6\u4FDD\u5B58\u7684\u914D\u7F6E\uFF0C\u8F93\u5165\u5DF2\u4FDD\u7559\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{setReading(!1)}}},ready4=saved?.[prefix+"Ready"]===!0,active=ready4&&(!embedding||Number(saved.vectorWeight)>0),status=saved?active?"\u5DF2\u914D\u7F6E \xB7 "+saved[modelKey]:ready4&&embedding?"\u5DF2\u505C\u7528\uFF08\u5411\u91CF\u68C0\u7D22\u5360\u6BD4\u4E3A 0\uFF09":saved[urlKey]?"\u914D\u7F6E\u672A\u5B8C\u6574\uFF0C\u6682\u672A\u542F\u7528":"\u672A\u542F\u7528":"\u5C1A\u672A\u8BFB\u53D6\u914D\u7F6E";return h("div",{className:"sg-settings-panel sg-model-settings sg-retrieval-settings","data-kind":kind},h("div",{className:"sg-model-heading-row"},h("h4",{className:"sg-model-heading"},title),h(InfoPopover,{label:title+"\u8BF4\u660E"},h("p",null,"\u586B\u5199\u5730\u5740\u3001\u5BC6\u94A5\u548C\u6A21\u578B\u540E\u542F\u7528\uFF1B\u6E05\u7A7A\u5730\u5740\u5E76\u4FDD\u5B58\u5373\u53EF\u505C\u7528\u3002\u542F\u7528\u4F1A\u4EA7\u751F\u670D\u52A1\u5546 API \u8D39\u7528\u3002"),h("p",null,embedding?"\u542F\u7528\u540E\uFF0C\u4E8B\u4EF6\u6807\u9898\u548C\u6458\u8981\u4F1A\u53D1\u9001\u7ED9\u5411\u91CF\u670D\u52A1\u5546\u3002":"\u542F\u7528\u540E\uFF0C\u68C0\u7D22\u95EE\u9898\u548C\u5019\u9009\u4E8B\u4EF6\u5185\u5BB9\u4F1A\u53D1\u9001\u7ED9\u7CBE\u6392\u670D\u52A1\u5546\u3002"),h("p",null,"\u586B\u5199 OpenAI \u517C\u5BB9\u63A5\u53E3\u57FA\u7840\u5730\u5740\uFF0C\u4E0D\u542B "+(embedding?"/embeddings":"/rerank")+"\u3002"),h("p",null,"\u4FDD\u5B58\u4E0D\u9A8C\u8BC1\u8FDE\u63A5\u3002"+(embedding?"\u5DF2\u6709\u4E8B\u4EF6\u7684\u5411\u91CF\u4F1A\u5728\u540E\u7EED\u68C0\u7D22\u65F6\u8865\u9F50\u3002":"")))),h("div",{className:"sg-retrieval-fields"},h("label",{className:"sg-model-field"},"API \u5730\u5740",h("input",{type:"url",value:value(urlKey),disabled,placeholder:"https://\u4F60\u7684\u670D\u52A1\u5730\u5740/v1","aria-label":title+" API \u5730\u5740",spellCheck:!1,onChange:event3=>edit(urlKey,event3.target.value)})),urlValid?null:h("p",{className:"sg-status-feedback failed",role:"alert"},"\u8BF7\u586B\u5199\u4EE5 http:// \u6216 https:// \u5F00\u5934\u7684\u6709\u6548\u5730\u5740\u3002"),h("label",{className:"sg-model-field"},"API Key",h("input",{type:"password",value:draft[secretKey]??"",disabled,placeholder:keyEdited&&!draft[secretKey]?"\u4FDD\u5B58\u540E\u6E05\u9664\u5BC6\u94A5":saved?.[prefix+"KeyConfigured"]?"\u5DF2\u4FDD\u5B58\u5BC6\u94A5\uFF0C\u672A\u4FEE\u6539\u65F6\u4FDD\u7559":"\u586B\u5199 API Key","aria-label":title+" API Key",autoComplete:"new-password",spellCheck:!1,onChange:event3=>edit(secretKey,event3.target.value)})),h("div",{className:"sg-retrieval-actions"},saved?.[prefix+"KeyConfigured"]?h("button",{type:"button",className:"sg-quiet-button",disabled,onClick:()=>edit(secretKey,"")},"\u6E05\u9664\u5DF2\u4FDD\u5B58\u5BC6\u94A5"):null,keyEdited?h("button",{type:"button",className:"sg-quiet-button",disabled,onClick:()=>{setDraft(current=>{let next2={...current};return delete next2[secretKey],next2}),lookup2.current+=1,setModels([]),setListing(!1),setListFeedback(""),setFeedback({kind:"",text:""})}},"\u64A4\u9500\u5BC6\u94A5\u4FEE\u6539"):null),keyEdited&&!draft[secretKey].trim()?h("p",{className:"sg-setting-note"},"\u4FDD\u5B58\u540E\u5C06\u6E05\u9664\u5BC6\u94A5\u5E76\u505C\u7528\u6B64\u529F\u80FD\u3002"):null,h("label",{className:"sg-model-field"},"\u6A21\u578B\u540D\u79F0",h("input",{type:"text",value:value(modelKey),disabled,list:"sg-"+kind+"-models",placeholder:"\u586B\u5199\u6A21\u578B\u540D\u79F0\u6216\u4ECE\u5217\u8868\u9009\u62E9","aria-label":title+"\u6A21\u578B\u540D\u79F0",autoComplete:"off",spellCheck:!1,onChange:event3=>edit(modelKey,event3.target.value)})),h("datalist",{id:"sg-"+kind+"-models"},models.map(id2=>h("option",{key:id2,value:id2}))),h("div",{className:"sg-retrieval-actions"},h("button",{type:"button",className:"sg-storage-button",disabled:disabled||listing||!url||!urlValid||!keyConfigured,onClick:()=>{listModels()}},listing?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u8BFB\u53D6\u6A21\u578B\u5217\u8868")),listFeedback?h("p",{className:"sg-status-feedback",role:"status"},listFeedback):null),embedding?h("details",{className:"sg-retrieval-tuning"},h("summary",null,"\u68C0\u7D22\u53C2\u6570"),h("div",{className:"sg-model-fields"},h("label",{className:"sg-model-field"},"\u5411\u91CF\u68C0\u7D22\u5360\u6BD4",h("input",{type:"number",min:0,max:5,step:.1,value:draft.vectorWeight??saved?.vectorWeight??1,disabled,"aria-label":"\u5411\u91CF\u68C0\u7D22\u5360\u6BD4",onChange:event3=>edit("vectorWeight",event3.target.value)})),h("label",{className:"sg-model-field"},"\u6700\u4F4E\u76F8\u4F3C\u5EA6",h("input",{type:"number",min:0,max:1,step:.05,value:draft.embeddingMinScore??saved?.embeddingMinScore??.3,disabled,"aria-label":"\u6700\u4F4E\u76F8\u4F3C\u5EA6",onChange:event3=>edit("embeddingMinScore",event3.target.value)}))),h("p",{className:"sg-setting-note"},"\u5360\u6BD4 1 \u4E0E\u5173\u952E\u8BCD\u68C0\u7D22\u5E73\u6743\uFF1B0 \u505C\u7528\u3002\u6700\u4F4E\u76F8\u4F3C\u5EA6\u8303\u56F4 0\u20131\u3002"),numericValid?null:h("p",{className:"sg-status-feedback failed",role:"alert"},"\u5360\u6BD4\u9700\u4E3A 0\u20135 \u7684\u6570\u5B57\uFF0C\u6700\u4F4E\u76F8\u4F3C\u5EA6\u9700\u4E3A 0\u20131 \u7684\u6570\u5B57\u3002")):null,h("div",{className:"sg-model-save-row"},h("div",{className:"sg-model-saved"},h("span",{className:"sg-model-active-label"},"\u5F53\u524D\u751F\u6548"),h("strong",null,status)),changed?h("button",{type:"button",className:"sg-save-button",disabled:disabled||!urlValid||!numericValid,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58"):saved?h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"}):null),!saved||writable!==!0?h("p",{className:"sg-status-feedback"},saved?"\u5F53\u524D\u68C0\u7D22\u914D\u7F6E\u4E3A\u53EA\u8BFB\u3002":"\u68C0\u7D22\u914D\u7F6E\u5C1A\u672A\u8BFB\u53D6\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u3002"):null,feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null,!saved||feedback.kind==="failed"?h("button",{type:"button",className:"sg-quiet-button",disabled:saving||reading,onClick:()=>{readSaved()}},reading?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u91CD\u65B0\u8BFB\u53D6\u914D\u7F6E"):null)}function SettingsPage({selected,graphSettings,vectorSettings,retrievalSettingsWritable,onRetrievalSettingsSaved,refresh,namespace,dataDirectory,onBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let[turnSize,setTurnSize]=React.useState(String(selected.blockTurnSize??6)),[lambda,setLambda]=React.useState(String(selected.blockDecayLambda??.3)),[agentWeight,setAgentWeight]=React.useState(String(selected.agentMemoryRetrievalWeight??1)),[directoryOpening,setDirectoryOpening]=React.useState(!1),[directoryFeedback,setDirectoryFeedback]=React.useState({kind:"",text:""});React.useEffect(()=>{setTurnSize(String(selected.blockTurnSize??6)),setLambda(String(selected.blockDecayLambda??.3)),setAgentWeight(String(selected.agentMemoryRetrievalWeight??1))},[selected.blockTurnSize,selected.blockDecayLambda,selected.agentMemoryRetrievalWeight]);let turnSizeValue=Number(turnSize),lambdaValue=Number(lambda),agentWeightValue=Number(agentWeight),changed=Number.isSafeInteger(turnSizeValue)&&turnSizeValue>=1&&lambda!==""&&Number.isFinite(lambdaValue)&&lambdaValue>=0&&agentWeight!==""&&Number.isFinite(agentWeightValue)&&agentWeightValue>=0&&agentWeightValue<=5&&(turnSizeValue!==selected.blockTurnSize||lambdaValue!==selected.blockDecayLambda||agentWeightValue!==(selected.agentMemoryRetrievalWeight??1)),suggestedLambda=Math.round((selected.blockDecayLambda??.3)*turnSizeValue/(selected.blockTurnSize||6)/.05)*.05,showSuggestion=Number.isSafeInteger(turnSizeValue)&&turnSizeValue>=1&&turnSizeValue!==selected.blockTurnSize,pluginSettings=usePluginSettings?usePluginSettings(state=>state):null,effortMode=pluginSettings?.value?.structuredReasoningEffort||"auto",effortOverridden=pluginSettings?.user?.structuredReasoningEffort!==void 0,settingsWritable=pluginSettings?.writable===!0,workspaceRows=[["Schema","v"+selected.schemaVersion],["\u5DE5\u4F5C\u533A",selected.workspaceName||"\u5F53\u524D\u5DE5\u4F5C\u533A"],["\u5185\u90E8\u7A7A\u95F4 ID",namespace],["\u5DF2\u5904\u7406\u8F6E\u6B21",selected.currentTurn]],runtimeDiagnostics=[["duplicates","\u21C4","\u91CD\u590D\u8BB0\u5FC6\u6574\u7406","\u67E5\u770B\u4FDD\u7559\u539F\u56E0\u3001\u5408\u5E76\u5019\u9009\u4E0E\u91CD\u65B0\u626B\u63CF"],["system","\u2713","\u7CFB\u7EDF\u72B6\u6001","\u5904\u7406\u6982\u89C8\u4E0E\u6700\u8FD1\u6574\u7406\u65F6\u95F4"],["audit","\u2197","\u4F7F\u7528\u8BB0\u5F55","\u957F\u671F\u8BB0\u5FC6\u4F55\u65F6\u88AB\u4F7F\u7528"],["status","\u21BB","\u540E\u53F0\u4EFB\u52A1","\u5904\u7406\u8FDB\u5EA6\u3001\u5931\u8D25\u4EFB\u52A1\u4E0E\u91CD\u8BD5"]],openDirectory=()=>{!dataDirectory||directoryOpening||(setDirectoryOpening(!0),setDirectoryFeedback({kind:"",text:""}),api2("storage/open-directory",{},{method:"POST"}).then(()=>setDirectoryFeedback({kind:"done",text:"\u5DF2\u5728\u6587\u4EF6\u7BA1\u7406\u5668\u4E2D\u6253\u5F00"})).catch(reason=>setDirectoryFeedback({kind:"failed",text:"\u6253\u5F00\u5931\u8D25\uFF1A"+String(reason?.message||reason)})).finally(()=>setDirectoryOpening(!1)))},copyDirectory=()=>{if(dataDirectory){if(setDirectoryFeedback({kind:"",text:""}),!navigator?.clipboard?.writeText){setDirectoryFeedback({kind:"failed",text:"\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236"});return}navigator.clipboard.writeText(dataDirectory).then(()=>setDirectoryFeedback({kind:"done",text:"\u8DEF\u5F84\u5DF2\u590D\u5236"})).catch(reason=>setDirectoryFeedback({kind:"failed",text:"\u590D\u5236\u5931\u8D25\uFF1A"+String(reason?.message||reason)}))}},menu=items=>h("div",{className:"sg-menu sg-settings-menu"},items.map(([id2,icon,title,subtitle])=>h("button",{key:id2,type:"button",className:"sg-menu-row",onClick:()=>setView({name:id2,back:{name:"settings"}})},h("span",{className:"sg-menu-icon","aria-hidden":"true"},icon),h("span",null,h("span",{className:"sg-menu-title"},title),h("br"),h("span",{className:"sg-menu-subtitle"},subtitle)),h("span",{className:"sg-chevron"},"\u203A")))),stepper=({value,onChange,min:min4,max:max5,step:step3,label,allowFloat})=>{let current=Number(value),delta=allowFloat?step3:1,bump=direction=>{if(!Number.isFinite(current))return;let next2=Math.min(max5,Math.max(min4,Number((current+direction*delta).toFixed(2))));onChange(String(next2))};return h("span",{className:"sg-stp sg-stp-wide"},h("button",{type:"button","aria-label":"\u51CF\u5C11"+label,disabled:!Number.isFinite(current)||current<=min4,onClick:()=>bump(-1)},"\u2212"),h("input",{className:"sg-number-input",type:"number",min:String(min4),max:max5===void 0?void 0:String(max5),step:String(step3),value,onChange:event3=>onChange(event3.target.value),"aria-label":label}),h("button",{type:"button","aria-label":"\u589E\u52A0"+label,disabled:!Number.isFinite(current)||max5===void 0||current>=max5,onClick:()=>bump(1)},"+"))},blockSettings=h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-stage"},h("span",null,"\u6BCF\u4E2A Block \u7684\u5BF9\u8BDD\u8F6E\u6570"),h("span",{className:"sg-lambda-control"},stepper({value:turnSize,onChange:setTurnSize,min:1,max:30,step:1,label:"\u6BCF\u4E2A Block \u7684\u5BF9\u8BDD\u8F6E\u6570"}),h("span",{className:"sg-stage-value waiting"},"\u8F6E"))),h("p",{className:"sg-setting-note"},"1 \u8F6E\u7B49\u4E8E\u4E00\u6B21\u63D0\u95EE\u548C\u5B8C\u6574\u56DE\u590D\uFF0C\u53EA\u5F71\u54CD\u540E\u7EED\u672A\u5C01\u5B58\u5185\u5BB9\u3002"),h("div",{className:"sg-stage"},h("span",null,"Block \u8870\u51CF\u7CFB\u6570 \u03BB"),h("span",{className:"sg-lambda-control"},stepper({value:lambda,onChange:setLambda,min:0,max:.4,step:.05,label:"Block \u8870\u51CF\u7CFB\u6570 \u03BB",allowFloat:!0}))),h("p",{className:"sg-setting-note"},"\u8D8A\u5C0F\u9057\u5FD8\u8D8A\u6162\uFF0Ctoken \u6D88\u8017\u8D8A\u591A\u3002"),showSuggestion?h("div",{className:"sg-setting-suggestion"},h("span",null,"\u5EFA\u8BAE \u03BB \u8C03\u6574\u4E3A "+suggestedLambda.toFixed(2)+"\u3002"),h("button",{type:"button",className:"sg-quiet-button",onClick:()=>setLambda(String(Number(suggestedLambda.toFixed(2))))},"\u91C7\u7528\u5EFA\u8BAE\u503C")):null,h("div",{className:"sg-stage"},h("span",null,"\u4E3B\u52A8\u8BB0\u5FC6\u68C0\u7D22\u5360\u6BD4"),h("span",{className:"sg-lambda-control"},stepper({value:agentWeight,onChange:setAgentWeight,min:0,max:5,step:.05,label:"\u4E3B\u52A8\u8BB0\u5FC6\u68C0\u7D22\u5360\u6BD4",allowFloat:!0}))),h("p",{className:"sg-setting-note"},"1 \u4E3A\u5E73\u6743\uFF0C0 \u4E0D\u5C55\u793A agent \u8BB0\u5F55\u3002"),changed?h("div",{className:"sg-dirty"},h("span",null,[turnSizeValue!==selected.blockTurnSize,lambdaValue!==selected.blockDecayLambda,agentWeightValue!==(selected.agentMemoryRetrievalWeight??1)].filter(Boolean).length+" \u9879\u672A\u4FDD\u5B58"),h("button",{type:"button",className:"sg-quiet-button",disabled:savingSettings,onClick:()=>{setTurnSize(String(selected.blockTurnSize??6)),setLambda(String(selected.blockDecayLambda??.3)),setAgentWeight(String(selected.agentMemoryRetrievalWeight??1))}},"\u653E\u5F03"),h("button",{type:"button",className:"sg-save-button",disabled:!changed||savingSettings,onClick:()=>{updateSettings({blockTurnSize:turnSizeValue,blockDecayLambda:lambdaValue,agentMemoryRetrievalWeight:agentWeightValue})}},savingSettings?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"})),effortSettings=h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-stage"},h("span",null,"\u7ED3\u6784\u5316\u63A8\u7406\u6863\u4F4D"),h("span",{className:"sg-lambda-control"},h("select",{className:"sg-effort-select",value:effortMode,disabled:!settingsWritable,onChange:event3=>{setEffort&&setEffort(event3.target.value)},"aria-label":"\u7ED3\u6784\u5316\u63A8\u7406\u6863\u4F4D\u7B56\u7565"},h("option",{value:"auto"},"auto\uFF08\u81EA\u52A8\uFF09"),h("option",{value:"force-off"},"force-off\uFF08\u5F3A\u5236\u5173\u95ED\uFF09")),effortOverridden?h("button",{type:"button",className:"sg-effort-button",onClick:()=>{resetEffort&&resetEffort()}},"\u6062\u590D\u9ED8\u8BA4"):h("span",{className:"sg-stage-value waiting"},"\u9ED8\u8BA4"))),h("p",{className:"sg-setting-note"},"auto \u8DDF\u968F\u6A21\u578B\u80FD\u529B\uFF1Bforce-off \u4F18\u5148\u5173\u95ED\uFF0C\u4E0D\u652F\u6301\u65F6\u81EA\u52A8\u964D\u7EA7\u3002")),workspaceInfo=h("div",{className:"sg-settings-panel sg-pipeline"},workspaceRows.map(([label,value])=>h("div",{key:label,className:"sg-stage"},h("span",null,label),h("span",{className:label==="\u5185\u90E8\u7A7A\u95F4 ID"?"sg-stage-value sg-code":"sg-stage-value"},String(value)))));return h("div",{className:"sg-settings-shell"},h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-pg-head"},h("h2",null,"\u9AD8\u7EA7\u8BBE\u7F6E")),h("section",{className:"sg-settings-group sg-settings-install","aria-labelledby":"sg-memory-settings-title"},h("h3",{id:"sg-memory-settings-title",className:"sg-settings-group-title"},"\u5B89\u88C5\u7EA7\u8BBE\u7F6E"),h("div",{className:"sg-settings-columns"},h("div",{className:"sg-settings-column"},h(GraphSettingsPanel,{state:graphSettings,refresh}),h(ProfileLimitSettings),h(DailyNotesSettings,{usePluginSettings,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}),blockSettings),h("div",{className:"sg-settings-column"},h(RetrievalModelSettings,{kind:"embedding",settings:vectorSettings,writable:retrievalSettingsWritable,onSaved:onRetrievalSettingsSaved}),h(RetrievalModelSettings,{kind:"rerank",settings:vectorSettings,writable:retrievalSettingsWritable,onSaved:onRetrievalSettingsSaved})))),h("section",{className:"sg-settings-group","aria-labelledby":"sg-host-settings-title"},h("h3",{id:"sg-host-settings-title",className:"sg-settings-group-title"},"\u5BBF\u4E3B\u914D\u7F6E"),h("div",{className:"sg-settings-columns"},h("div",{className:"sg-settings-column"},h(MemoryModelSettings,{usePluginSettings,setMemoryModel})),h("div",{className:"sg-settings-column"},effortSettings))),h("section",{className:"sg-settings-group","aria-labelledby":"sg-workspace-settings-title"},h("h3",{id:"sg-workspace-settings-title",className:"sg-settings-group-title"},"\u5DE5\u4F5C\u533A\u4FE1\u606F"),workspaceInfo),h("section",{className:"sg-settings-group","aria-labelledby":"sg-storage-title"},h("h3",{id:"sg-storage-title",className:"sg-settings-group-title"},"\u6570\u636E\u4E0E\u5B58\u50A8"),h("div",{className:"sg-storage-card"},h("span",{className:"sg-storage-label"},"\u6570\u636E\u5B58\u50A8\u4F4D\u7F6E"),h("span",{className:"sg-storage-path",title:dataDirectory||void 0},dataDirectory||"\u5F53\u524D\u4F7F\u7528\u5185\u5B58\u5B58\u50A8\uFF0C\u6CA1\u6709\u672C\u5730\u6570\u636E\u76EE\u5F55"),h("div",{className:"sg-storage-actions"},h("button",{type:"button",className:"sg-storage-button",disabled:!dataDirectory||directoryOpening,onClick:openDirectory},directoryOpening?"\u6B63\u5728\u6253\u5F00\u2026":"\u6253\u5F00\u6587\u4EF6\u5939"),h("button",{type:"button",className:"sg-storage-button",disabled:!dataDirectory,onClick:copyDirectory},"\u590D\u5236\u8DEF\u5F84")),h("p",{className:"sg-storage-feedback "+directoryFeedback.kind,role:directoryFeedback.kind==="failed"?"alert":"status","aria-live":"polite"},directoryFeedback.text)),menu([["raw","{}","\u67E5\u770B\u539F\u59CB\u6570\u636E","Block\u3001Event\u3001Graph \u4E0E\u6A21\u578B\u54CD\u5E94"]])),h("section",{className:"sg-settings-group sg-settings-compact","aria-labelledby":"sg-diagnostics-title"},h("h3",{id:"sg-diagnostics-title",className:"sg-settings-group-title"},"\u8FD0\u884C\u4E0E\u8BCA\u65AD"),menu(runtimeDiagnostics)))}function overviewAbsolute(value){let date=new Date(value);return Number.isNaN(date.getTime())?"\u65F6\u95F4\u672A\u77E5":new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(date)}function overviewRelative(value){let time2=Date.parse(value||"");if(!Number.isFinite(time2))return"\u8FD8\u6CA1\u6709\u66F4\u65B0";let seconds=Math.round((Date.now()-time2)/1e3);if(seconds<60)return"\u521A\u521A";if(seconds<3600)return Math.floor(seconds/60)+" \u5206\u949F\u524D";if(seconds<86400)return Math.floor(seconds/3600)+" \u5C0F\u65F6\u524D";let days=Math.floor(seconds/86400);return days===1?"\u6628\u5929":days<30?days+" \u5929\u524D":overviewAbsolute(value)}function overviewCount(value){return Number(value||0).toLocaleString("en-US")}function OverviewPage({selected,loading,onOpenSection}){let stats=selected?.memoryOverview;if(loading&&!stats)return h(Loading);if(!stats)return h(Empty,{title:"\u8FD8\u6CA1\u6709\u53EF\u6C47\u603B\u7684\u8BB0\u5FC6",copy:"\u8FD9\u4E2A\u5DE5\u4F5C\u533A\u7684\u8BB0\u5FC6\u8BFB\u51FA\u6765\u4E4B\u540E\uFF0C\u4F1A\u663E\u793A\u5728\u8FD9\u91CC\u3002"});let layers=[{key:"profile",name:"\u5E38\u9A7B\u753B\u50CF",tone:"ink",section:"profile",value:stats.layers.profile?overviewCount(stats.layers.profile.characters):"\u2014",unit:"\u5B57",updatedAt:stats.layers.profile?.updatedAt},{key:"directory",name:"\u8BB0\u5FC6\u76EE\u5F55",tone:"moss",section:"long",value:stats.layers.directory?overviewCount(stats.layers.directory.chapters):"\u2014",unit:"\u7AE0",updatedAt:stats.layers.directory?.updatedAt},{key:"session",name:"\u4F1A\u8BDD\u8BB0\u5FC6",tone:"water",section:"short",value:overviewCount(stats.layers.session.blocks),unit:"\u5757",updatedAt:stats.layers.session.updatedAt},{key:"short",name:"\u77ED\u671F\u8BB0\u5FC6",tone:"sand",section:"daily",value:stats.layers.shortTerm?overviewCount(stats.layers.shortTerm.items):"\u2014",unit:"\u6761",updatedAt:stats.layers.shortTerm?.updatedAt},{key:"long",name:"\u957F\u671F\u8BB0\u5FC6",tone:"lib",section:"long",value:overviewCount(stats.layers.longTerm.events),unit:"\u4E2A\u4E8B\u4EF6",updatedAt:stats.layers.longTerm.updatedAt,answers:stats.layers.longTerm.answers}],heatmap=Array.isArray(stats.heatmap)?stats.heatmap:[],peak=Math.max(1,...heatmap.map(day=>Number(day.answers)||0));return h("section",{className:"sg-ov","data-testid":"stratagate-overview","aria-label":"\u8BB0\u5FC6\u603B\u89C8"},h("div",{className:"sg-ov-top"},h("div",{className:"sg-ov-stat"},h("div",{className:"sg-ov-big"},h("b",{className:"sg-mono","data-testid":"overview-answer-count"},overviewCount(stats.answeredLast7Days)),h(UsedMark,{title:"\u957F\u671F\u8BB0\u5FC6\u5E2E\u5230\u7684\u56DE\u7B54"})),stats.lastRecall?h("p",{"data-testid":"overview-last-recall"},"\u6700\u8FD1\u4E00\u6B21\uFF1A\u5E2E\u4F60\u60F3\u8D77\u4E86\u300C"+stats.lastRecall.title+"\u300D"):h("p",{className:"sg-ov-empty","data-testid":"overview-last-recall"},"\u6700\u8FD1\u8FD8\u6CA1\u6709\u957F\u671F\u8BB0\u5FC6\u88AB\u7528\u5230\u56DE\u7B54\u91CC")),h("div",{className:"sg-pillar","aria-label":"\u8BB0\u5FC6\u5206\u5C42"},layers.map((layer,index)=>{let when="\u6700\u8FD1\u66F4\u65B0\uFF1A"+overviewRelative(layer.updatedAt),countText=layer.value==="\u2014"?"\u6682\u65E0\u6570\u636E":layer.value+" "+layer.unit,summary=layer.name+" "+countText+"\uFF0C"+when,open=()=>{typeof onOpenSection=="function"&&onOpenSection(layer.section)};return h(React.Fragment,{key:layer.key},layer.key==="long"?h("div",{className:"sg-pillar-gap","aria-hidden":"true"}):null,h("button",{type:"button",className:"sg-pillar-row","data-testid":"overview-layer-"+layer.key,"aria-label":"\u6253\u5F00"+layer.name+"\uFF1A"+countText+"\uFF0C"+when,title:summary,onClick:open},h("span",{className:"sg-pillar-bar "+layer.tone,style:{animationDelay:index*60+"ms"},"aria-hidden":"true"}),h("span",{className:"sg-pillar-name"},h("b",null,layer.name)),h("span",{className:"sg-pillar-tail"},h("span",{className:"sg-pillar-use"},layer.key==="long"&&layer.answers>0?h(UsedMark,{count:layer.answers,title:"\u88AB\u56DE\u7B54\u7528\u5230 "+layer.answers+" \u6B21"}):null),h("span",{className:"sg-pillar-val"},h("b",{className:"sg-mono"},layer.value))),h("span",{className:"sg-pillar-when"},when)))})),h("div",{className:"sg-pillar-key"},h("span",null,h("i",{className:"sg-sw","aria-hidden":"true"}),"\u4E00\u76F4\u5E26\u7740"),h("span",null,h("i",{className:"sg-sw lib","aria-hidden":"true"}),"\u9700\u8981\u65F6\u53BB\u627E"),h("span",null,h(UsedMark),"\u88AB\u7528\u5230"))),h("div",{className:"sg-heat"},h("div",{className:"sg-heat-head"},h("span",null,h(UsedMark),"\u6BCF\u5929\u88AB\u56DE\u7B54\u7528\u5230\u51E0\u6B21"),h("span",null,"\u989C\u8272\u8D8A\u6DF1\u8D8A\u591A")),h("div",{className:"sg-heat-grid","aria-label":"\u6700\u8FD1 "+heatmap.length+" \u5929\u957F\u671F\u8BB0\u5FC6\u91C7\u7528"},heatmap.map(day=>{let answers=Number(day.answers)||0,ink=answers?Math.min(28+Math.round(answers/peak*62),90):0;return h("i",{key:day.day,title:day.day+" \xB7 "+answers+" \u6B21\u56DE\u7B54",style:answers?{background:"color-mix(in srgb, var(--sg-ink) "+ink+"%, var(--sg-sheet))",boxShadow:"none"}:void 0})})),h("div",{className:"sg-heat-scale"},h("span",null,heatmap.length>14?"4 \u5468\u524D":"2 \u5468\u524D"),h("span",null,"\u4ECA\u5929"))))}function MemoryPage({useWorkspaces,useSessions,navigationState,usePluginSettings,setMemoryModel,setEffort,resetEffort,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,onOpenDreamingSession,onChooseSidebar,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let TAB_SWATCH={profile:"ink",short:"water",daily:"sand",long:"lib"},workspaceItems=useWorkspaces(state=>state.items),sessionById=useSessions(state=>state.byId||{}),[overview,setOverview]=React.useState({namespaces:[]}),[namespace,setNamespace]=React.useState(""),[workspaceTitles,setWorkspaceTitles]=React.useState({}),[workspaceSessionIds,setWorkspaceSessionIds]=React.useState({}),[conversationId,setConversationId]=React.useState(""),[section,setSection]=React.useState("overview"),[view,setView]=React.useState({name:"root"}),[graphFocusNodeId,setGraphFocusNodeId]=React.useState(""),consumeGraphFocus=React.useCallback(()=>setGraphFocusNodeId(""),[]),[data4,setData]=React.useState({events:[],graph:{nodes:[],edges:[],migration:null},blocks:[],openBlock:null,conversations:[],activeThreadId:null,audit:[],pagination:{events:{total:0,offset:0,limit:40},blocks:{total:0,offset:0,limit:40},audit:{total:0,offset:0,limit:100}}}),[query,setQuery]=React.useState(""),[source,setSource]=React.useState(null),[loading,setLoading]=React.useState(!0),[error3,setError]=React.useState(""),[recentError,setRecentError]=React.useState(""),[savingSettings,setSavingSettings]=React.useState(!1),[pollFast,setPollFast]=React.useState(!1),dashboardRequestRef=React.useRef(null),sourceRequestRef=React.useRef(null),namespaceRef=React.useRef(namespace);namespaceRef.current=namespace;let dashboardEtagsRef=React.useRef(new Map),loadedNamespaceRef=React.useRef(""),feedbackDeepLinkRef=React.useRef(readFeedbackNavigationState(navigationState)||readFeedbackDeepLink()),graphNodeNavigationRef=React.useRef(readGraphNodeNavigationState(navigationState)||readGraphNodeDeepLink()),feedbackNavigationStateRef=React.useRef(navigationState),namespaceNavigationRef=React.useRef(null),directoryScrollRef=React.useRef(null),reportError=reason=>{let message=String(reason?.message||reason);if(setError(message),setRecentError(message),namespace){let category=/timeout|timed out|超时/i.test(message)?"timeout":/fetch|network|网络/i.test(message)?"network":"request-failed";api2("diagnostics",{namespace,category},{method:"POST"}).catch(()=>{})}};React.useEffect(()=>{let active=!0;return Promise.all((workspaceItems||[]).map(async workspace=>({key:await workspaceProjectKey(workspace.path),title:String(workspace.title||"").trim(),sessionIds:Array.isArray(workspace.sessionIds)?workspace.sessionIds.map(String):[]}))).then(entries=>{active&&(setWorkspaceTitles(Object.fromEntries(entries.filter(({key,title})=>key&&title).map(({key,title})=>[key,title]))),setWorkspaceSessionIds(Object.fromEntries(entries.filter(({key})=>key).map(({key,sessionIds})=>[key,sessionIds]))))}),()=>{active=!1}},[workspaceItems]);let loadDashboard=React.useCallback((activeNamespace,options2={})=>{let background=options2.background===!0;if(background&&!options2.force&&dashboardRequestRef.current)return Promise.resolve(null);dashboardRequestRef.current?.abort();let controller=new AbortController;dashboardRequestRef.current=controller;let key=String(activeNamespace||"")+"\0"+String(options2.threadId||"");return background||setLoading(!0),background||setError(""),dashboardApi({...activeNamespace?{namespace:activeNamespace}:{},...options2.threadId?{threadId:options2.threadId}:{}},{etag:options2.force?"":dashboardEtagsRef.current.get(key),signal:controller.signal}).then(result=>{if(controller.signal.aborted||dashboardRequestRef.current!==controller||(result.etag&&dashboardEtagsRef.current.set(key,result.etag),result.notModified||!result.data))return null;let next2=result.data;return setOverview(next2.overview||{namespaces:[]}),setPollFast(next2.processing===!0),next2.namespace&&(loadedNamespaceRef.current=next2.namespace,setNamespace(current=>next2.overview?.namespaces?.some(item=>item.namespace===current)?current:next2.namespace)),next2.data&&(setData(next2.data),setConversationId(next2.data.activeThreadId||"")),setError(""),next2}).catch(reason=>{if(controller.signal.aborted||dashboardRequestRef.current!==controller)return null;if(reason?.name!=="AbortError"&&reportError(reason),options2.propagateError===!0&&reason?.name!=="AbortError")throw reason;return null}).finally(()=>{dashboardRequestRef.current===controller&&(dashboardRequestRef.current=null,setLoading(!1))})},[]);React.useEffect(()=>{let graphLink=graphNodeNavigationRef.current,feedbackLink=feedbackDeepLinkRef.current;return graphLink?(setSection("long"),setQuery(""),setView({name:"root"}),setSource(null),setGraphFocusNodeId(graphLink.nodeId),readGraphNodeDeepLink()&&consumeGraphNodeDeepLink()):feedbackLink&&(setSection("more"),setView({name:"support"}),setSource(null),readFeedbackDeepLink()&&consumeFeedbackDeepLink()),loadDashboard(graphLink?.namespace||feedbackLink?.namespace||""),()=>{dashboardRequestRef.current?.abort(),sourceRequestRef.current?.abort()}},[loadDashboard]),React.useEffect(()=>{let graphLink=navigationState!==feedbackNavigationStateRef.current?readGraphNodeNavigationState(navigationState):null,feedback=readNewFeedbackNavigationState(feedbackNavigationStateRef.current,navigationState);if(feedbackNavigationStateRef.current=navigationState,graphLink){setSection("long"),setView({name:"root"}),setSource(null),setGraphFocusNodeId(graphLink.nodeId),namespaceNavigationRef.current=namespace!==graphLink.namespace?{namespace:graphLink.namespace}:null,setNamespace(graphLink.namespace),namespace===graphLink.namespace&&loadDashboard(graphLink.namespace,{force:!0});return}feedback&&(setSection("more"),setView({name:"support"}),setSource(null),namespaceNavigationRef.current=namespace!==feedback.namespace?{namespace:feedback.namespace}:null,setNamespace(feedback.namespace),namespace===feedback.namespace&&loadDashboard(feedback.namespace,{force:!0}))},[navigationState,loadDashboard]),React.useEffect(()=>{if(!namespace)return;let navigated=namespaceNavigationRef.current?.namespace===namespace;namespaceNavigationRef.current=null,loadedNamespaceRef.current!==namespace&&(directoryScrollRef.current=null,setConversationId(""),navigated||setView({name:"root"}),setSource(null),setRecentError(""),setData({events:[],graph:{nodes:[],edges:[],migration:null},blocks:[],openBlock:null,conversations:[],activeThreadId:null,audit:[],pagination:{events:{total:0,offset:0,limit:40},blocks:{total:0,offset:0,limit:40},audit:{total:0,offset:0,limit:100}}}),loadDashboard(namespace,{force:!0}))},[namespace,loadDashboard]),React.useEffect(()=>{if(!namespace)return;let stopped=!1,timer=null,schedule=delay2=>{stopped||document.hidden||(timer=window.setTimeout(run,delay2))},run=()=>{stopped||document.hidden||loadDashboard(namespace,{background:!0,threadId:conversationId}).finally(()=>{schedule(pollFast?2500:3e4)})},onVisibilityChange=()=>{document.hidden?(timer!==null&&window.clearTimeout(timer),timer=null,dashboardRequestRef.current?.abort()):run()};return document.addEventListener("visibilitychange",onVisibilityChange),schedule(pollFast?2500:3e4),()=>{stopped=!0,timer!==null&&window.clearTimeout(timer),document.removeEventListener("visibilitychange",onVisibilityChange)}},[namespace,conversationId,pollFast,loadDashboard]);let selected=(overview.namespaces||[]).find(item=>item.namespace===namespace),project=projectName(selected||namespace,workspaceTitles),activeProjectKey=namespace.includes(":project:")?namespace.split(":project:").pop():"",hostSessionIds=workspaceSessionIds[activeProjectKey]||[],memoryConversations=new Map(data4.conversations.map(conversation=>[conversation.id,conversation])),conversations=[],seenConversations=new Set;for(let id2 of hostSessionIds){let session=sessionById[id2];if(session?.parentId)continue;let memory=memoryConversations.get(id2),dshTitle=String(session?.title||"").trim();conversations.push({...memory||{},id:id2,label:dshTitle||memory?.label||"\u5BF9\u8BDD "+id2.slice(0,8)}),seenConversations.add(id2)}for(let memory of data4.conversations)seenConversations.has(memory.id)||conversations.push(memory);conversations.sort((left,right)=>left.id==="__legacy__"?1:right.id==="__legacy__"?-1:0);let clearSource=()=>{sourceRequestRef.current?.abort(),sourceRequestRef.current=null,setSource(null)},goSection=next2=>{directoryScrollRef.current=null,setSection(next2),setView({name:"root"}),clearSource()},sourceParams=(kind,item)=>kind==="event"?{eventId:item.id}:kind==="element"?{elementId:item.id}:{blockId:item.id},loadSource=(kind,item)=>{clearSource();let controller=new AbortController;sourceRequestRef.current=controller;let requestedNamespace=namespace,requestedId=String(item?.id||"");api2("sources",{namespace,...sourceParams(kind,item)},{signal:controller.signal}).then(value=>{if(sourceRequestRef.current!==controller||controller.signal.aborted||namespaceRef.current!==requestedNamespace)return;let returnedId=value?.event?.id||value?.element?.id||value?.block?.id||value?.id,returnedIds=Array.isArray(value?.events)?value.events.map(entry=>String(entry?.id||"")):[];returnedId&&String(returnedId)!==requestedId||returnedIds.length&&!returnedIds.includes(requestedId)||setSource(value)}).catch(reason=>{reason?.name!=="AbortError"&&sourceRequestRef.current===controller&&reportError(reason)})},openWithSource=(kind,item)=>{setView(current=>({name:kind,item,back:current})),loadSource(kind,item)},openEvent=(event3,trigger)=>{if(trigger?.getAttribute?.("data-topic-event-id")){let ancestors=[];for(let node=trigger.parentElement;node;node=node.parentElement)node.scrollHeight>node.clientHeight&&ancestors.push({node,top:node.scrollTop,left:node.scrollLeft});directoryScrollRef.current={namespace,eventId:event3.id,trigger,ancestors,top:window.scrollY||0,left:window.scrollX||0}}openWithSource("event",data4.events.find(item=>item.id===event3.id)||event3)};(React.useLayoutEffect||React.useEffect)(()=>{let saved=directoryScrollRef.current,action=directoryScrollAction(saved,section,namespace,view.name);if(action!=="none"){if(action==="clear"){directoryScrollRef.current=null;return}if(action==="detail"){for(let{node}of saved.ancestors)node.scrollTop=0,node.scrollLeft=0;window.scrollTo?.(0,0)}else if(action==="restore"){(saved.trigger?.isConnected&&saved.trigger.getClientRects().length?saved.trigger:Array.from(document.querySelectorAll(".sg-topic-event[data-topic-event-id]")).find(node=>node.getAttribute("data-topic-event-id")===saved.eventId&&node.getClientRects().length))?.focus?.({preventScroll:!0});for(let{node,top,left}of saved.ancestors)node.scrollTop=top,node.scrollLeft=left;window.scrollTo?.(saved.left,saved.top),directoryScrollRef.current=null}}},[view.name,section,namespace]);let openGraphNode=nodeId=>{directoryScrollRef.current=null,setSection("long"),setQuery(""),setView({name:"root"}),clearSource(),setGraphFocusNodeId(nodeId)},goBack=()=>{let previous=view.back||{name:"root"};setView(previous),previous.item&&["event","block"].includes(previous.name)?loadSource(previous.name,previous.item):clearSource()},backLabel=view.back?.name==="duplicates"?"\u91CD\u590D\u8BB0\u5FC6\u6574\u7406":view.back?.name==="block"?"\u4F1A\u8BDD\u8BB0\u5FC6":view.back?.name==="event"?"\u957F\u671F\u8BB0\u5FC6":view.back?.name==="structure"?"\u8BB0\u5FC6\u7ED3\u6784":section==="short"?"\u4F1A\u8BDD\u8BB0\u5FC6":"\u957F\u671F\u8BB0\u5FC6",refresh=(options2={})=>loadDashboard(namespace,{threadId:conversationId,force:!0,...options2}),refreshDirectory=React.useCallback(()=>loadDashboard(namespace,{threadId:conversationId,background:!0,force:!0}),[namespace,conversationId,loadDashboard]),selectConversation=nextConversationId=>(setConversationId(nextConversationId),loadDashboard(namespace,{threadId:nextConversationId,force:!0})),updateSettings=values=>(setSavingSettings(!0),setError(""),api2("settings",values,{method:"PATCH"}).then(()=>loadDashboard(namespace,{threadId:conversationId,force:!0})).catch(reportError).finally(()=>setSavingSettings(!1))),onRetrievalSettingsSaved=vectorSettings=>setOverview(current=>({...current,vectorSettings})),moreBack=()=>setView({name:"root"}),content=null;return(section==="long"||view.name==="support")&&loadedNamespaceRef.current!==namespace||loading&&!selected?content=h(Loading):view.name==="settings"&&!selected?content=h(SettingsPage,{graphSettings:overview.graphSettings,vectorSettings:overview.vectorSettings,retrievalSettingsWritable:overview.settingsWritable,onRetrievalSettingsSaved,refresh,selected:{blockTurnSize:6,blockDecayLambda:.3,agentMemoryRetrievalWeight:1,currentTurn:0,schemaVersion:12},namespace,dataDirectory:overview.dataDirectory,onBack:moreBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}):section==="overview"&&view.name==="root"?content=h(OverviewPage,{key:namespace,selected,loading,onOpenSection:goSection}):section==="profile"&&view.name==="root"?content=h(ProfilePage):section==="daily"&&view.name==="root"?content=h(DailyNotesPage,{key:namespace,namespace,setDailyInjectionDays}):!selected&&section!=="more"?content=h(Empty,{title:"\u8FD8\u6CA1\u6709\u8BB0\u5FC6",copy:"\u5B8C\u6210\u4E00\u4E9B DSH \u5BF9\u8BDD\u540E\uFF0C\u4F1A\u8BDD\u8BB0\u5FC6\u548C\u957F\u671F\u8BB0\u5FC6\u4F1A\u51FA\u73B0\u5728\u8FD9\u91CC\u3002"}):view.name==="event"?content=h(EventDetail,{event:view.item,project,source,onBack:goBack,backLabel,onNode:openGraphNode}):view.name==="status"?content=h(ProcessingStatus,{key:namespace,overview:selected,blocks:data4.blocks,conversations,namespace,serverVersion:overview.pluginVersion,onBack:view.back?goBack:()=>setView({name:"root"}),backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u8FD4\u56DE",refresh}):view.name==="import"?content=h(ImportPage,{key:namespace,namespace,onBack:moreBack,refresh}):view.name==="structure"?content=h(StructurePage,{events:data4.events,eventPage:data4.pagination?.events,graph:data4.graph,openEvent,namespace,onBack:moreBack}):view.name==="duplicates"?content=h(DuplicateReviewPage,{namespace,repair:selected?.duplicateRepair,onBack:moreBack,openEvent,refresh}):view.name==="system"?content=h(SystemPage,{selected,blocks:data4.blocks,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A",refresh,onDuplicates:()=>setView({name:"duplicates"})}):view.name==="audit"?content=h(AuditPage,{audit:data4.audit,auditPage:data4.pagination?.audit,namespace,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A"}):view.name==="raw"?content=h(RawPage,{data:data4,selected,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A"}):view.name==="display"?content=h(DisplayPage,{onBack:moreBack,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry}):view.name==="settings"?content=h(SettingsPage,{selected,graphSettings:overview.graphSettings,vectorSettings:overview.vectorSettings,retrievalSettingsWritable:overview.settingsWritable,onRetrievalSettingsSaved,refresh,namespace,dataDirectory:overview.dataDirectory,onBack:moreBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}):view.name==="support"?content=h(SupportPage,{key:namespace,namespace,overview,selected,data:data4,recentError,onBack:moreBack}):content=h(React.Fragment,null,loading?h(Loading):section==="short"?h(ShortTermPage,{key:namespace+":"+conversationId,blockTurnSize:selected?.blockTurnSize||6,blocks:data4.blocks,blockPage:data4.pagination?.blocks,openBlock:data4.openBlock,conversations,activeThreadId:conversationId||data4.activeThreadId||"",namespace,onConversationChange:selectConversation,refresh}):section==="long"?null:h(MoreHome,{setView,selected,overview,namespace,dataDirectory:overview.dataDirectory,updateSettings,savingSettings,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,setDailyEnabled,setDailyInjectionDays})),h("main",{className:"sg-memory"+(view.name==="duplicates"?" sg-memory-review":"")+(view.name==="settings"||view.name==="display"||section==="more"&&view.name==="root"?" sg-settings-page":""),"data-testid":"stratagate-memory-ui"},h("style",null,css+DUPLICATE_STYLES+DAILY_NOTES_CSS+R6_STYLES),h("header",{className:"sg-header"},h("div",{className:"sg-header-row sg-header-row-primary"},h(GITHUB_FEEDBACK_ENABLED?"a":"div",{className:"sg-brand",href:GITHUB_FEEDBACK_ENABLED?STAR_REPOSITORY_URL:void 0,target:GITHUB_FEEDBACK_ENABLED?"_blank":void 0,rel:GITHUB_FEEDBACK_ENABLED?"noopener noreferrer":void 0},h(StrataGateMark),h("span",{className:"sg-brand-copy"},h("span",{className:"sg-brand-title"},h("span",{className:"sg-brand-name"},"StrataGate"),overview.pluginVersion&&overview.pluginVersion!=="unknown"?h("span",{className:"sg-brand-version"},"v"+overview.pluginVersion):null),onChooseSidebar?h(SidebarPlacementPrompt,{onChooseSidebar,usePluginSettings}):null)),h("div",{className:"sg-header-end"},h("div",{className:"sg-project"},h("span",{className:"sg-project-label"},"\u5F53\u524D\u5DE5\u4F5C\u533A"),h("select",{className:"sg-project-select",value:namespace,onChange:event3=>setNamespace(event3.target.value),"aria-label":"\u5F53\u524D\u5DE5\u4F5C\u533A"},(overview.namespaces||[]).map(item=>h("option",{key:item.namespace,value:item.namespace},projectName(item,workspaceTitles))))),GITHUB_FEEDBACK_ENABLED?h(HeaderStarLink):null)),h("nav",{className:"sg-tabs","aria-label":"\u8BB0\u5FC6\u89C6\u56FE"},[["overview","\u603B\u89C8"],["profile","\u5E38\u9A7B\u753B\u50CF"],["short","\u4F1A\u8BDD\u8BB0\u5FC6"],["daily","\u77ED\u671F\u8BB0\u5FC6"],["long","\u957F\u671F\u8BB0\u5FC6"],["more","\u66F4\u591A"]].map(([id2,label])=>h("button",{key:id2,type:"button",className:"sg-tab "+(section===id2?"active":""),"aria-current":section===id2?"page":void 0,onClick:()=>goSection(id2)},TAB_SWATCH[id2]?h("i",{key:"sw",className:"sg-tab-swatch "+TAB_SWATCH[id2],"aria-hidden":"true"}):null,label))),error3?h("div",{className:"sg-error"},h("div",{className:"sg-error-title"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u5B8C\u6574\u8BB0\u5FC6"),h("div",null,"\u5DF2\u663E\u793A\u80FD\u591F\u8BFB\u53D6\u7684\u5185\u5BB9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u52A0\u8F7D\u3002"),h("details",null,h("summary",null,"\u6280\u672F\u8BE6\u60C5"),h("div",{className:"sg-code"},error3))):null,view.name==="root"&&selected?.duplicateRepair?.needsReview>0?h("button",{type:"button",className:"sg-dup-entry",onClick:()=>setView({name:"duplicates"})},h(DuplicateIcon,{size:23}),h("span",null,h("strong",null,selected.duplicateRepair.needsReview+" \u7EC4\u76F8\u4F3C\u8BB0\u5FC6\uFF0C\u7B49\u4F60\u786E\u8BA4"),h("small",null,"\u5BF9\u6BD4\u5185\u5BB9\uFF0C\u9009\u62E9\u4FDD\u7559\u54EA\u5F20\u6216\u5408\u5E76\u53CC\u65B9\u8BC1\u636E")),h(DuplicateIcon,{kind:"next"})):null,h("section",{key:section,className:"sg-view","aria-label":"StrataGate \u8BB0\u5FC6\u5185\u5BB9"},section==="long"&&selected&&loadedNamespaceRef.current===namespace?h(React.Fragment,null,h("div",{key:"long-browser",hidden:view.name!=="root"},h(LongTermPage,{graphSettings:overview.graphSettings,extractionGap:selected?.longTermExtractionGap===!0,key:namespace,events:data4.events,eventPage:data4.pagination?.events,graph:data4.graph,project,query,setQuery,openEvent,namespace,focusNodeId:graphFocusNodeId,onFocusHandled:consumeGraphFocus,topicDirectory:data4.topicDirectory,onDirectoryChanged:refreshDirectory,onOpenDreamingSession,refresh,active:view.name==="root"})),view.name==="root"?null:content):content),h("footer",{className:"sg-footer"},h("span",null,"StrataGate-AgentMemory \xB7 MIT"),h("span",{className:"sg-footer-links"},h("a",{href:STAR_REPOSITORY_URL,target:"_blank",rel:"noopener noreferrer"},"GitHub \u4ED3\u5E93")," \xB7 ",h("a",{href:ISSUE_URL,target:"_blank",rel:"noopener noreferrer"},"\u63D0 Issue")," \xB7 ",h("a",{href:STAR_REPOSITORY_URL+"/releases",target:"_blank",rel:"noopener noreferrer"},"\u66F4\u65B0\u8BB0\u5F55")))))}function MemoryPanel(props){return h("div",{className:"sg-memory-panel",style:{flex:"1 1 0%",minHeight:0,width:"100%",overflowY:"auto",overflowX:"hidden"}},h(MemoryPage,props))}function readSidebarPromptState(){try{return String(globalThis.localStorage?.getItem(SIDEBAR_PROMPT_STORAGE_KEY)||"")}catch{return""}}function writeSidebarPromptState(value){try{globalThis.localStorage?.setItem(SIDEBAR_PROMPT_STORAGE_KEY,value)}catch{}}function StrataGatePanelIcon({size:size3=20}){return h("svg",{width:size3,height:size3,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,focusable:!1,className:"sg-sidebar-panel-icon",style:{display:"block",flexShrink:0}},h("path",{opacity:.28,strokeWidth:1.4,d:"M3 12V4a1 1 0 0 1 1-1h8"}),h("path",{opacity:.55,d:"M6 15V7a1 1 0 0 1 1-1h9"}),h("rect",{x:9,y:9,width:12,height:13,rx:1.8}),h("path",{d:"M12 13h6M12 17h4"}))}function SidebarPlacementPrompt({onChooseSidebar,usePluginSettings}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[visible,setVisible]=React.useState(()=>readSidebarPromptState()!=="dismissed"),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState("");if(!visible||settings?.value?.showSidebarEntry===!0||settings?.writable!==!0)return null;let dismiss=()=>{writeSidebarPromptState("dismissed"),setVisible(!1)},chooseSidebar=async()=>{setBusy(!0),setError("");try{if(!await onChooseSidebar?.()){setError("\u672A\u80FD\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002");return}writeSidebarPromptState("sidebar"),setVisible(!1)}catch{setError("\u672A\u80FD\u4FDD\u5B58\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002")}finally{setBusy(!1)}};return h(React.Fragment,null,h("style",null,SIDEBAR_PROMPT_STYLES),h("span",{className:"sg-sidebar-placement-prompt",role:"region","aria-label":"StrataGate \u4FA7\u680F\u5165\u53E3\u63D0\u793A"},h("span",{className:"sg-sidebar-placement-text"},"\u4ECE\u5DE6\u4FA7\u680F\u5FEB\u901F\u6253\u5F00\u8BB0\u5FC6"),h("button",{type:"button",className:"sg-sidebar-placement-action",disabled:busy,onClick:()=>{chooseSidebar()}},"\u653E\u5230\u5DE6\u4FA7\u680F"),h("button",{type:"button",className:"sg-sidebar-placement-close","aria-label":"\u5173\u95ED\u4FA7\u680F\u5165\u53E3\u63D0\u793A",title:"\u4E0D\u518D\u63D0\u9192",disabled:busy,onClick:dismiss},"\xD7"),error3?h("span",{role:"alert"},error3):null))}let disposeFeedbackLinkNavigation=null;function apply2(ctx){let slots=ctx.get("slots");if(!slots)return;let configForms=ctx.get("configForms"),settingsScope=ctx.get("settingsScope"),pluginSettingsScope=configForms?configForms.get("stratagate-memory"):settingsScope?settingsScope.bind({namespace:"stratagate-memory"}):null,setSidebarEntry=async visible=>{if(!pluginSettingsScope||!await pluginSettingsScope.set("showSidebarEntry",visible))return!1;if(!visible){let layout4=ctx.get("layout");layout4?.activePanelId===MEMORY_PANEL_ID&&layout4.selectPanel?.(null)}return!0},warnCitationFailure=(part,error3)=>{if(!(typeof console>"u"||typeof console.warn!="function"))try{console.warn("[StrataGate] "+part+" registration failed; memory settings remain available.",error3)}catch{}};slots.inject("settings.section",()=>slots.register({name:"settings.section",id:"stratagate-memory",order:32,label:()=>"StrataGate-AgentMemory",inject:()=>({hooks:{pluginSettings:pluginSettingsScope},setMemoryModel:pluginSettingsScope?selection=>pluginSettingsScope.set("memoryModel",selection):null,setEffort:pluginSettingsScope?mode=>pluginSettingsScope.set("structuredReasoningEffort",mode):null,setDailyEnabled:pluginSettingsScope?enabled=>pluginSettingsScope.set("dailyNotesEnabled",enabled):null,setDailyInjectionDays:pluginSettingsScope?days=>pluginSettingsScope.set("dailyNotesInjectionDays",days):null,setDailyTimeZone:pluginSettingsScope?zone=>zone?pluginSettingsScope.set("dailyNotesTimeZone",zone):pluginSettingsScope.unset("dailyNotesTimeZone"):null,resetEffort:pluginSettingsScope?()=>pluginSettingsScope.unset("structuredReasoningEffort"):null,setStrataGateStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showStrataGateStatus",visible):null,setShortTermStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showShortTermStatus",visible):null,setRetrievalStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showRetrievalStatus",visible):null,setSidebarEntry:pluginSettingsScope?setSidebarEntry:null})},props=>h(FeedbackSettingsPage,{...props,onChooseSidebar:async()=>{let layout4=ctx.get("layout");return typeof layout4?.selectPanel!="function"||!await setSidebarEntry(!0)?!1:(layout4.selectPanel(MEMORY_PANEL_ID),props.close?.(),!0)},onOpenDreamingSession:sessionId=>{let navigation=ctx.get("uiWorkspace");if(typeof navigation?.openSession!="function")throw new Error("\u5F53\u524D DSH \u672A\u63D0\u4F9B\u4F1A\u8BDD\u5BFC\u822A\uFF0C\u8BF7\u5347\u7EA7\u5BBF\u4E3B\u540E\u91CD\u8BD5");navigation.openSession(sessionId),props.close?.()}})));let memoryPanelInject=()=>({setMemoryModel:pluginSettingsScope?selection=>pluginSettingsScope.set("memoryModel",selection):null,...pluginSettingsScope?{hooks:{pluginSettings:pluginSettingsScope}}:{},setEffort:pluginSettingsScope?mode=>pluginSettingsScope.set("structuredReasoningEffort",mode):null,setDailyEnabled:pluginSettingsScope?enabled=>pluginSettingsScope.set("dailyNotesEnabled",enabled):null,setDailyInjectionDays:pluginSettingsScope?days=>pluginSettingsScope.set("dailyNotesInjectionDays",days):null,setDailyTimeZone:pluginSettingsScope?zone=>zone?pluginSettingsScope.set("dailyNotesTimeZone",zone):pluginSettingsScope.unset("dailyNotesTimeZone"):null,resetEffort:pluginSettingsScope?()=>pluginSettingsScope.unset("structuredReasoningEffort"):null,setStrataGateStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showStrataGateStatus",visible):null,setShortTermStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showShortTermStatus",visible):null,setRetrievalStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showRetrievalStatus",visible):null,setSidebarEntry:pluginSettingsScope?setSidebarEntry:null,onOpenDreamingSession:sessionId=>{let navigation=ctx.get("uiWorkspace");if(typeof navigation?.openSession!="function")throw new Error("\u5F53\u524D DSH \u672A\u63D0\u4F9B\u4F1A\u8BDD\u5BFC\u822A\uFF0C\u8BF7\u5347\u7EA7\u5BBF\u4E3B\u540E\u91CD\u8BD5");navigation.openSession(sessionId)}});try{slots.inject("main",()=>slots.register({name:"main",key:MEMORY_PANEL_ID,order:20,inject:memoryPanelInject},MemoryPanel)),slots.inject("sidebar.panellist",()=>{let removeEntry=null,syncSidebar=()=>{let snapshot=pluginSettingsScope?.getSnapshot?.();if(snapshot?.status==="loading")return;let visible=snapshot?.value?.showSidebarEntry===!0;visible&&!removeEntry?removeEntry=slots.register({name:"sidebar.panellist",id:MEMORY_PANEL_ID,order:20,label:()=>"StrataGate \u8BB0\u5FC6"},StrataGatePanelIcon)||(()=>{}):!visible&&removeEntry&&(removeEntry(),removeEntry=null)},unsubscribe=pluginSettingsScope?.subscribe?.(syncSidebar);return syncSidebar(),()=>{unsubscribe?.(),removeEntry?.(),removeEntry=null}})}catch(error3){warnCitationFailure("sidebar entry",error3)}try{let uiConversation=ctx.get("uiConversation");uiConversation&&(uiConversation.events.register(memoryCitationsDefinition),ensureCitationStyles(),slots.inject("conversation.chat.turnTail",()=>{try{return slots.register({name:"conversation.chat.turnTail",id:"stratagate-memory-citations",select:selectMemoryCitations,inject:()=>({...pluginSettingsScope?{hooks:{pluginSettings:pluginSettingsScope}}:{},onOpenGraphNode:(namespace,nodeId)=>navigateToGraphNode(ctx,namespace,nodeId)})},MemoryCitationTail)}catch(error3){return warnCitationFailure("chat turn tail",error3),()=>{}}}))}catch(error3){warnCitationFailure("chat citations",error3)}if(typeof document<"u"){disposeFeedbackLinkNavigation?.();let disposeLinkNavigation=installFeedbackLinkNavigation(ctx),disposeDeepLink=openFeedbackDeepLink(ctx),disposeGraphDeepLink=openGraphNodeDeepLink(ctx);disposeFeedbackLinkNavigation=()=>{disposeLinkNavigation(),disposeDeepLink(),disposeGraphDeepLink()}}}return exports.name="stratagate-dsh",exports.inject=["slots","uiConversation"],exports.apply=apply2,module.exports}});})();
1369
+ `;function DuplicateIcon({kind="cards",size:size3=17}){let paths={cards:"M7 3H3v14h10v-4M7 3v10h10V3H7Z",check:"m4 10 4 4 8-8",info:"M10 9v5m0-8v.2M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0Z",back:"m12 5-5 5 5 5",next:"m8 5 5 5-5 5",merge:"M4 3v3c0 3 6 3 6 6v5m6-14v3c0 3-6 3-6 6m-3 2 3 3 3-3"};return h("svg",{width:size3,height:size3,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},h("path",{d:paths[kind]||paths.cards}))}function DuplicateEvidence({namespace,card,hideSummary=!1}){let[result,setResult]=React.useState(null),[error3,setError]=React.useState(""),[attempt,setAttempt]=React.useState(0);return React.useEffect(()=>{let active=!0;return setResult(null),setError(""),api2("sources",{namespace,eventId:card.id}).then(value=>{active&&setResult(value)}).catch(reason=>{active&&setError(String(reason.message||reason))}),()=>{active=!1}},[namespace,card.id,attempt]),h("section",{className:"sg-dup-source","aria-label":"\u5B8C\u6574\u8BB0\u5FC6\u4E0E\u6765\u6E90"},h("h4",null,hideSummary?"\u539F\u59CB\u6765\u6E90":"\u5B8C\u6574\u8BB0\u5FC6\u4E0E\u6765\u6E90"),hideSummary?null:h("p",{className:"sg-dup-summary"},card.summary),error3?h("div",{role:"alert"},error3,h("button",{type:"button",className:"sg-dup-button",onClick:()=>setAttempt(value=>value+1)},"\u91CD\u8BD5\u8BFB\u53D6\u6765\u6E90")):result?result.messages?.length?h("div",{className:"sg-citation-messages"},result.messages.map(message=>h("div",{key:message.id,className:"sg-citation-message"},h("span",{className:"sg-citation-message-role"},(message.role||"Recorded")+(message.createdAt?" \xB7 "+exactTime(message.createdAt):"")),String(message.content||"")))):h("p",null,"\u5F53\u524D\u6CA1\u6709\u53EF\u663E\u793A\u7684\u539F\u59CB\u6765\u6E90\u6D88\u606F\u3002"):h("p",{role:"status"},"\u6B63\u5728\u8BFB\u53D6\u6765\u6E90\u2026"))}function DuplicateCard({card,letter,selected,onSelect,unavailable,disabled,namespace,fullContent=!1,selectionMade=!1}){let[expanded,setExpanded]=React.useState(!1),[showSource,setShowSource]=React.useState(!1),sourcePosition=React.useRef(null);(React.useLayoutEffect||React.useEffect)(()=>{if(showSource||!sourcePosition.current)return;let{trigger,ancestors,top,left}=sourcePosition.current;trigger?.focus?.({preventScroll:!0});for(let saved of ancestors)saved.node.scrollTop=saved.top,saved.node.scrollLeft=saved.left;window.scrollTo?.(left,top),sourcePosition.current=null},[showSource]);let toggleSource=event3=>{if(!showSource){let ancestors=[];for(let node=event3.currentTarget.parentElement;node;node=node.parentElement)node.scrollHeight>node.clientHeight&&ancestors.push({node,top:node.scrollTop,left:node.scrollLeft});sourcePosition.current={trigger:event3.currentTarget,ancestors,top:window.scrollY||0,left:window.scrollX||0}}setShowSource(value=>!value)};if(!card)return h("article",{className:"sg-dup-card"},h("div",{className:"sg-dup-card-body"},h("h3",null,"\u8BB0\u5FC6 "+letter),h("p",null,"\u539F\u5361\u5DF2\u4E0D\u53EF\u7528")));let status={active:"\u5F53\u524D\u6709\u6548",superseded:"\u5DF2\u88AB\u66FF\u4EE3",archived:"\u5DF2\u5F52\u6863",forgotten:"\u5DF2\u9057\u5FD8"},criticality={routine:"\u4E00\u822C\u8BB0\u5FC6",preference:"\u504F\u597D",identity:"\u4E2A\u4EBA\u7ECF\u5386",safety:"\u91CD\u8981\u7EA6\u675F"},scope={user:"\u4E2A\u4EBA",project:"\u9879\u76EE",session:"\u672C\u6B21\u4F1A\u8BDD"},temporal=card.temporal||{},date=temporal.happenedStart||temporal.originalText;return h("article",{className:"sg-dup-card"+(selected?" selected":"")+(card.status==="archived"?" archived":"")},h("label",{className:"sg-dup-choice"},onSelect?h("input",{id:"sg-retain-"+card.id,type:"radio",name:"duplicate-retained",checked:selected,disabled:disabled||!!unavailable,onChange:onSelect,"aria-label":"\u53EA\u4FDD\u7559 "+letter+"\uFF1A"+card.title}):h("span",{className:"sg-dup-letter"},letter),h("span",null,onSelect?"\u53EA\u4FDD\u7559 "+letter:"\u8BB0\u5FC6 "+letter),h("em",null,status[card.status]||"")),h(onSelect?"label":"div",{className:"sg-dup-card-body",htmlFor:onSelect?"sg-retain-"+card.id:void 0},h("h3",null,card.title),h("div",{className:"sg-dup-meta"},date?h("span",null,date):null,h("span",null,criticality[card.criticality]||"\u4E00\u822C\u8BB0\u5FC6"),h("span",null,scope[card.scope]||card.scope||"\u4E2A\u4EBA"),card.weight?.pinned?h("span",null,"\u5DF2\u7F6E\u9876"):null),h("p",{className:"sg-dup-summary"+(!expanded&&!fullContent?" collapsed":"")},card.summary),!fullContent&&card.summary?.length>160?h("button",{type:"button",className:"sg-dup-expand",onClick:()=>setExpanded(!expanded),"aria-expanded":expanded},expanded?"\u6536\u8D77\u5168\u6587":"\u5C55\u5F00\u5168\u6587"):null,h("dl",{className:"sg-dup-evidence"},card.quotes?.length?h(React.Fragment,null,h("dt",null,"\u5F15\u8BED"),h("dd",null,card.quotes.map(quote=>h("blockquote",{key:quote},quote)))):null,temporal.participants?.length?h(React.Fragment,null,h("dt",null,"\u53C2\u4E0E\u8005"),h("dd",null,temporal.participants.join("\u3001"))):null,card.tags?.length?h(React.Fragment,null,h("dt",null,"\u6807\u7B7E"),h("dd",null,card.tags.join(" \xB7 "))):null)),fullContent&&onSelect&&!unavailable?null:h("div",{className:"sg-dup-card-footer"},fullContent&&onSelect?null:h("button",{type:"button",className:"sg-dup-button","aria-expanded":showSource,onClick:toggleSource},showSource?"\u6536\u8D77\u6765\u6E90\uFF0C\u8FD4\u56DE\u5BF9\u6BD4":"\u67E5\u770B "+(card.sourceMessageIds?.length||0)+" \u6761\u6765\u6E90\u4E0E\u5B8C\u6574\u8BB0\u5FC6"),unavailable?h("small",null,unavailable):null),fullContent&&onSelect?h("p",{className:"sg-dup-selection-result"},selectionMade?selected?"\u786E\u8BA4\u540E\u4FDD\u7559\u8FD9\u5F20":"\u786E\u8BA4\u540E\u5C06\u8FD9\u5F20\u5F52\u6863 \xB7 \u539F\u6587\u548C\u6765\u6E90\u4ECD\u4FDD\u7559":"\u70B9\u51FB\u4FDD\u7559\u8FD9\u5F20\u8BB0\u5FC6"):null,showSource||fullContent&&onSelect?h(React.Fragment,null,h(DuplicateEvidence,{namespace,card,hideSummary:fullContent}),showSource?h("button",{type:"button",className:"sg-dup-button text",onClick:toggleSource},"\u6536\u8D77\u6765\u6E90\uFF0C\u8FD4\u56DE\u5BF9\u6BD4"):null):null)}function DuplicatePair({item,busy,namespace,onResolve,onPrepareDraft,onTakeOver,draftState,onDraftState}){let[selectedId,setSelectedId]=React.useState(draftState?.selectedId||""),[mode,setMode]=React.useState(draftState?.mode||""),[draft,setDraft]=React.useState(draftState?.draft||item.draft||{title:"",summary:""}),[draftError,setDraftError]=React.useState(""),[draftBusy,setDraftBusy]=React.useState(!1),[dirty,setDirty]=React.useState(!!draftState?.dirty),[regenerate,setRegenerate]=React.useState(!1),[saveError,setSaveError]=React.useState(""),[draftOrigin,setDraftOrigin]=React.useState(draftState?.draftOrigin||(item.draft?"AI \u5408\u5E76\u7A3F \xB7 \u8BF7\u6838\u5BF9":"\u624B\u52A8\u586B\u5199\u5408\u5E76\u7A3F")),stageHeading=React.useRef(null);React.useEffect(()=>{onDraftState?.({selectedId,mode,draft,draftOrigin,dirty})},[selectedId,mode,draft,draftOrigin,dirty]),React.useEffect(()=>{mode&&(stageHeading.current?.focus({preventScroll:!0}),stageHeading.current?.scrollIntoView({block:"nearest"}))},[mode]);let archived=item.outcome==="merged"||item.outcome==="selected",retained=item.outcome==="kept"&&(item.aiResolved||item.userReviewed),done=archived||retained,awaitingAI=item.outcome==="pending",selected=selectedId===item.leftId?item.left:selectedId===item.rightId?item.right:null,letter=selectedId===item.leftId?"A":"B",mergeId=item.recommendedKeepId||(item.choices?.right?.canMerge?item.rightId:item.leftId),mergeCard=mergeId===item.leftId?item.left:item.right,selection=item.choices?.[selectedId===item.leftId?"left":"right"],draftValid=!!(draft.title.trim()&&draft.summary.trim()),generateDraft=async(force=!1)=>{if(dirty&&!force){setRegenerate(!0);return}setRegenerate(!1),setDraftBusy(!0),setDraftError("");try{let result2=await onPrepareDraft(item,force);if(!result2?.draft)throw new Error("AI \u5C1A\u672A\u751F\u6210\u5B8C\u6574\u7A3F\uFF0C\u4F60\u53EF\u4EE5\u624B\u52A8\u586B\u5199\u6216\u7A0D\u540E\u91CD\u8BD5\u3002");setDraft(result2.draft),setDirty(!1),setDraftOrigin("AI \u5408\u5E76\u7A3F \xB7 \u8BF7\u6838\u5BF9")}catch(reason){setDraftError(String(reason.message||reason).replace(/\s*[((]duplicates[))]$/,""))}finally{setDraftBusy(!1)}},start=value=>{setMode(value),setSaveError(""),value==="select"&&setSelectedId(""),value==="merge"&&!draft.title&&!draft.summary&&onPrepareDraft&&generateDraft()},save=async()=>{setSaveError("");try{await onResolve(mode==="both"?"keep":mode,item,mode==="select"?selectedId:mode==="merge"?mergeId:void 0,mode==="merge"?draft:void 0)}catch(reason){setSaveError("\u4F60\u7684\u9009\u62E9\u548C\u7F16\u8F91\u5DF2\u4FDD\u7559\u3002"+String(reason.message||reason).replace(/\s*[((]duplicates[))]$/,""))}},cards=(selectable=!1,originals=!1)=>h("div",{className:"sg-dup-comparison",role:selectable?"radiogroup":void 0,"aria-label":selectable?"\u9009\u62E9\u8981\u4FDD\u7559\u7684\u8BB0\u5FC6":"\u53CC\u65B9\u5B8C\u6574\u8BB0\u5FC6"},[originals&&item.originalLeft||item.left,originals&&item.originalRight||item.right].map((card,i2)=>h(DuplicateCard,{key:card?.id||i2,card,letter:i2?"B":"A",namespace,fullContent:!0,selected:selectable&&selectedId===card?.id,selectionMade:!!selectedId,onSelect:selectable?()=>{setSelectedId(i2?item.rightId:item.leftId),setSaveError("")}:null,disabled:busy||draftBusy,unavailable:selectable?item.choices?.[i2?"right":"left"]?.selectBlockedReason:""}))),back=()=>{setMode(""),setSaveError(""),setRegenerate(!1)},result=done&&item.keepId===item.leftId?item.left:item.right,consequences=h("section",{className:"sg-dup-consequences"},h("h3",null,"\u786E\u8BA4\u540E\u4F1A\u53D1\u751F\u4EC0\u4E48"),h("dl",{className:"sg-dup-result"},h("dt",null,"\u65E5\u5E38\u68C0\u7D22"),h("dd",null,mode==="merge"?"\u663E\u793A\u4E0A\u9762\u7684\u5B8C\u6574\u5408\u5E76\u7A3F\u3002":mode==="both"?"\u4E24\u5F20\u8BB0\u5FC6\u5206\u522B\u4FDD\u7559\uFF0C\u5185\u5BB9\u548C\u6765\u6E90\u4E0D\u53D8\u3002":"\u53EA\u663E\u793A\u8BB0\u5FC6 "+letter+" \xB7 "+(selected?.title||"")),h("dt",null,"\u539F\u59CB\u8BB0\u5F55"),h("dd",null,mode==="merge"?"\u53CC\u65B9\u5904\u7406\u524D\u7684\u5185\u5BB9\u3001\u6765\u6E90\u548C\u5386\u53F2\u5173\u8054\u4FDD\u7559\uFF0C\u53EF\u5728\u5DF2\u5904\u7406\u8BB0\u5F55\u4E2D\u6838\u5BF9\u3002":mode==="both"?"\u53CC\u65B9\u539F\u5361\u5747\u4FDD\u7559\u3002":"\u8BB0\u5FC6 "+(letter==="A"?"B":"A")+" \u8F6C\u5165\u5386\u53F2\uFF1B\u72EC\u6709\u5185\u5BB9\u4E0D\u4F1A\u5408\u5165\u6240\u9009\u5361\uFF0C\u539F\u6587\u548C\u6765\u6E90\u4ECD\u4FDD\u7559\u3002"),mode==="merge"&&mergeCard?.temporal?.happenedStart?h(React.Fragment,null,h("dt",null,"\u65E5\u671F"),h("dd",null,"\u68C0\u7D22\u65E5\u671F\u6CBF\u7528 "+mergeCard.temporal.happenedStart+"\uFF1B\u8BF7\u6838\u5BF9\u6B63\u6587\u4E2D\u7684\u539F\u5B89\u6392\u3001\u540E\u7EED\u53D8\u5316\u4E0E\u5F53\u524D\u4E8B\u5B9E\u3002")):null,h("dt",null,"\u540E\u7EED\u8C03\u6574"),h("dd",null,"\u53EF\u5728\u201C\u5DF2\u5904\u7406\u201D\u67E5\u770B\u7ED3\u679C\uFF1B\u6CA1\u6709\u540E\u7EED\u51B2\u7A81\u65F6\u53EF\u64A4\u9500\u3002")));return h("section",{className:"sg-dup-pair","aria-label":"\u8BB0\u5FC6\u5BF9\u6BD4\u4E0E\u5904\u7406","aria-busy":busy||draftBusy},h("nav",{className:"sg-dup-steps","aria-label":"\u5904\u7406\u6B65\u9AA4"},["\u5BF9\u6BD4\u8BB0\u5FC6","\u6838\u5BF9\u7ED3\u679C","\u5B8C\u6210"].map((label,i2)=>h("span",{key:label,"aria-current":(done?2:mode?1:0)===i2?"step":void 0},i2+1+" "+label))),done?h(React.Fragment,null,h("h3",{className:"sg-dup-stage-title"},archived?item.outcome==="merged"?"\u5DF2\u6574\u7406\u6210\u4E00\u5F20\u5B8C\u6574\u8BB0\u5FC6":"\u5DF2\u4FDD\u7559\u8BB0\u5FC6 "+(item.keepId===item.leftId?"A":"B"):"\u5DF2\u5206\u522B\u4FDD\u7559\u4E24\u5F20\u8BB0\u5FC6"),h("p",{className:"sg-dup-reason"},item.aiResolved?"\u7531 AI \u81EA\u52A8\u5904\u7406 \xB7 "+item.reason:item.reason),archived?h(React.Fragment,null,h("div",{className:"sg-dup-result-card"},h("small",null,"\u4ECA\u540E\u4F7F\u7528\u7684\u8BB0\u5FC6"),h("h3",null,result?.title),h("p",{className:"sg-dup-summary"},result?.summary)),h("details",null,h("summary",null,item.originalLeft&&item.originalRight?"\u67E5\u770B\u5904\u7406\u524D\u7684\u4E24\u5F20\u8BB0\u5FC6\u4E0E\u6765\u6E90":"\u67E5\u770B\u4E24\u5F20\u8BB0\u5FC6\u4E0E\u6765\u6E90\uFF08\u6309\u5F53\u524D\u8BB0\u5F55\uFF09"),cards(!1,!0))):cards(),h("div",{className:"sg-dup-actions"},h("p",null,"\u64A4\u9500\u524D\u4F1A\u68C0\u67E5\u540E\u7EED\u53D8\u5316\uFF0C\u907F\u514D\u8986\u76D6\u65B0\u6570\u636E\u3002"),item.undoId?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onResolve("undo",item).catch(()=>{})},"\u64A4\u9500\u672C\u6B21\u5904\u7406"):retained?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onTakeOver?.(item)},"\u91CD\u65B0\u5904\u7406\u8FD9\u7EC4"):h("p",null,"\u6B64\u8BB0\u5F55\u521B\u5EFA\u4E8E\u652F\u6301\u64A4\u9500\u4E4B\u524D\u3002"))):awaitingAI?h(React.Fragment,null,h("div",{className:"sg-dup-reason"},h("strong",null,"AI \u4F1A\u5148\u5224\u65AD\u8FD9\u7EC4\u8BB0\u5FC6"),h("p",null,"\u5224\u65AD\u660E\u786E\u7684\u81EA\u52A8\u5904\u7406\u5E76\u7559\u4E0B\u8BB0\u5F55\uFF1B\u4E0D\u786E\u5B9A\u6216\u5904\u7406\u5931\u8D25\u7684\uFF0C\u624D\u4F1A\u8FDB\u5165\u201C\u9700\u8981\u4F60\u5224\u65AD\u201D\u3002\u4E24\u5F20\u539F\u5361\u76EE\u524D\u5747\u4FDD\u7559\u3002"),h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>onTakeOver(item)},"\u6211\u6765\u5904\u7406\u8FD9\u7EC4")),cards()):mode?h(React.Fragment,null,h("button",{type:"button",className:"sg-dup-button text sg-dup-back",disabled:busy||draftBusy,onClick:back},h(DuplicateIcon,{kind:"back",size:14}),"\u8FD4\u56DE\u5BF9\u6BD4"),h("div",{className:"sg-dup-stage-heading"},h("h3",{ref:stageHeading,tabIndex:-1},mode==="merge"?"\u628A\u53CC\u65B9\u4FE1\u606F\u6574\u7406\u6210\u4E00\u5F20\u8BB0\u5FC6":mode==="select"?"\u53EA\u4FDD\u7559\u54EA\u5F20\u8BB0\u5FC6\uFF1F":"\u5206\u522B\u4FDD\u7559\u8FD9\u4E24\u5F20\u8BB0\u5FC6"),h("p",null,mode==="merge"?"\u53CC\u65B9\u6709\u6548\u4FE1\u606F\u4F1A\u6574\u7406\u8FDB\u5B8C\u6574\u7A3F\uFF0C\u4FDD\u5B58\u524D\u4F60\u53EF\u4EE5\u4FEE\u6539\u6807\u9898\u548C\u6B63\u6587\u3002":mode==="select"?"\u4E24\u5F20\u5B8C\u6574\u5185\u5BB9\u90FD\u5728\u4E0B\u65B9\uFF0C\u70B9\u51FB\u8981\u4FDD\u7559\u7684\u5361\u7247\u3002\u53E6\u4E00\u5F20\u8F6C\u5165\u5386\u53F2\uFF0C\u5185\u5BB9\u4E0D\u4F1A\u81EA\u52A8\u5408\u5E76\u3002":"\u9002\u7528\u4E8E\u4E0D\u540C\u4E8B\u4EF6\u3001\u524D\u540E\u8FDB\u5C55\uFF0C\u6216\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u7684\u60C5\u51B5\u3002")),mode==="merge"?h(React.Fragment,null,item.historyNotice||item.mergeWarning?h("p",{className:"sg-dup-reason"},item.historyNotice||item.mergeWarning):null,!item.canMerge&&item.mergeBlockedReason?h("p",{className:"sg-dup-notice error",role:"note"},item.mergeBlockedReason," \u4ECD\u53EF\u5728\u4E0B\u65B9\u6574\u7406\u8349\u7A3F\uFF0C\u539F\u5361\u4E0D\u4F1A\u81EA\u52A8\u6539\u52A8\u3002"):null,h("div",{className:"sg-dup-editor"},h("div",{className:"sg-dup-draft-heading"},h("strong",null,draftBusy?"AI \u6B63\u5728\u6574\u7406\u5408\u5E76\u7A3F\u2026":draftOrigin),h("button",{type:"button",className:"sg-dup-button",disabled:busy||draftBusy,onClick:()=>generateDraft(!dirty)},"\u91CD\u65B0\u8BA9 AI \u6574\u7406")),regenerate?h("div",{className:"sg-dup-reason"},"\u91CD\u65B0\u751F\u6210\u4F1A\u66FF\u6362\u4F60\u5F53\u524D\u7F16\u8F91\u7684\u6807\u9898\u548C\u6B63\u6587\u3002",h("div",{className:"sg-dup-actions"},h("button",{type:"button",className:"sg-dup-button",onClick:()=>setRegenerate(!1)},"\u4FDD\u7559\u5F53\u524D\u7F16\u8F91"),h("button",{type:"button",className:"sg-dup-button",onClick:()=>generateDraft(!0)},"\u66FF\u6362\u4E3A\u65B0\u7A3F"))):null,draftError?h("p",{role:"alert",className:"sg-dup-notice error"},draftError," \u539F\u5361\u672A\u6539\u52A8\uFF0C\u53EF\u76F4\u63A5\u586B\u5199\u4E0B\u65B9\u5B8C\u6574\u8BB0\u5FC6\u3002"):null,draftBusy?h("div",{className:"sg-dup-draft-skeleton",role:"status","aria-label":"\u6B63\u5728\u751F\u6210\u5408\u5E76\u7A3F"},[1,2,3,4].map(i2=>h("span",{key:i2}))):h(React.Fragment,null,h("label",null,"\u5408\u5E76\u540E\u7684\u6807\u9898",h("input",{type:"text","aria-label":"\u5408\u5E76\u540E\u7684\u6807\u9898",value:draft.title,maxLength:200,disabled:busy,onChange:event3=>{setDraft({...draft,title:event3.target.value}),setDirty(!0),setDraftOrigin("\u4F60\u5DF2\u7F16\u8F91")}})),h("label",null,"\u5408\u5E76\u540E\u7684\u5B8C\u6574\u6B63\u6587",h("textarea",{"aria-label":"\u5408\u5E76\u540E\u7684\u5B8C\u6574\u6B63\u6587",value:draft.summary,maxLength:12e3,rows:8,disabled:busy,placeholder:"\u5199\u51FA\u4F60\u5E0C\u671B\u4ECA\u540E\u8BB0\u4F4F\u7684\u5B8C\u6574\u5185\u5BB9\uFF0C\u4FDD\u7559\u65F6\u95F4\u3001\u6761\u4EF6\u548C\u4E0D\u786E\u5B9A\u6027\u3002",onChange:event3=>{setDraft({...draft,summary:event3.target.value}),setDirty(!0),setDraftOrigin("\u4F60\u5DF2\u7F16\u8F91")}})),h("p",{className:"sg-dup-constraint"},draftValid?"\u5C06\u6309\u6B64\u5168\u6587\u4FDD\u5B58\uFF0C\u539F\u59CB\u8BC1\u636E\u53E6\u884C\u4FDD\u7559\u3002":"\u8BF7\u586B\u5199\u5B8C\u6574\u6807\u9898\u548C\u6B63\u6587\u540E\u518D\u4FDD\u5B58\u3002"))),h("details",null,h("summary",null,"\u5C55\u5F00\u53CC\u65B9\u539F\u5361\uFF0C\u6838\u5BF9\u5408\u5E76\u7A3F"),cards())):cards(mode==="select"),mode==="select"&&selected?.status==="superseded"?h("p",{className:"sg-dup-reason",role:"note"},"\u4F60\u9009\u62E9\u7684\u662F\u5386\u53F2\u7248\u672C "+letter+"\u3002\u4FDD\u5B58\u540E\u5B83\u4F1A\u91CD\u65B0\u6210\u4E3A\u6709\u6548\u8BB0\u5FC6\uFF0C\u53E6\u4E00\u5F20\u7684\u65B0\u589E\u5185\u5BB9\u4E0D\u4F1A\u5408\u5165\uFF1B\u8BF7\u786E\u8BA4\u8FD9\u7B26\u5408\u4F60\u7684\u610F\u601D\u3002"):null,mode==="select"&&selected&&selection?.selectBlockedReason?h("p",{className:"sg-dup-notice error",role:"note"},selection.selectBlockedReason):null,mode!=="select"||selected?consequences:h("p",{className:"sg-dup-constraint"},"\u5C1A\u672A\u9009\u62E9\u3002\u8BF7\u5BF9\u6BD4\u4E0A\u65B9\u5B8C\u6574\u5185\u5BB9\uFF0C\u518D\u9009\u62E9\u4FDD\u7559 A \u6216 B\u3002"),saveError?h("p",{className:"sg-dup-notice error",role:"alert"},saveError):null,h("div",{className:"sg-dup-actions"},h("p",null,"\u53EA\u6709\u786E\u8BA4\u4FDD\u5B58\uFF0C\u624D\u4F1A\u66F4\u65B0\u8BB0\u5FC6\u3002"),h("div",null,h("button",{type:"button",className:"sg-dup-button",disabled:busy||draftBusy,onClick:back},"\u8FD4\u56DE\u5BF9\u6BD4"),h("button",{type:"button",className:"sg-dup-button primary",disabled:busy||draftBusy||mode==="merge"&&!draftValid||mode==="select"&&!selected,onClick:save},busy?"\u6B63\u5728\u4FDD\u5B58\u2026":saveError?"\u91CD\u8BD5\u4FDD\u5B58":mode==="merge"?"\u786E\u8BA4\u4FDD\u5B58\u5408\u5E76\u7A3F":mode==="both"?"\u786E\u8BA4\u4FDD\u7559\u4E24\u5F20":selected?"\u786E\u8BA4\u53EA\u4FDD\u7559 "+letter:"\u8BF7\u9009\u62E9 A \u6216 B")))):h(React.Fragment,null,h("p",{className:"sg-dup-reason"},h("strong",null,"\u4E3A\u4EC0\u4E48\u9700\u8981\u4F60\u5224\u65AD"),item.reason),cards(),h("h3",{className:"sg-dup-stage-title"},"\u4F60\u5E0C\u671B\u600E\u4E48\u5904\u7406\uFF1F"),h("div",{className:"sg-dup-options"},[["merge","\u5408\u5E76\u53CC\u65B9\u5185\u5BB9","AI \u6574\u7406\u5B8C\u6574\u7A3F\uFF0C\u4F60\u53EF\u4EE5\u7F16\u8F91\u540E\u518D\u786E\u8BA4\u3002"],["select","\u53EA\u4FDD\u7559\u4E00\u5F20","\u67E5\u770B\u5B8C\u6574\u5185\u5BB9\uFF0C\u9009\u62E9 A \u6216 B\uFF0C\u53E6\u4E00\u5F20\u8F6C\u5165\u5386\u53F2\u3002"],["both","\u4FDD\u7559\u4E24\u5F20","\u5206\u522B\u4FDD\u7559\uFF0C\u7ED3\u675F\u8FD9\u7EC4\u6574\u7406\u3002"]].map(([value,title,description])=>h("button",{key:value,type:"button",className:"sg-dup-option",disabled:busy||draftBusy,onClick:()=>start(value)},h(DuplicateIcon,{kind:value==="merge"?"merge":"cards"}),h("strong",null,title),h("span",null,description)))),h("p",{className:"sg-dup-constraint"},"\u9009\u62E9\u540E\u5148\u6838\u5BF9\u5904\u7406\u7ED3\u679C\uFF0C\u786E\u8BA4\u4FDD\u5B58\u524D\u4E0D\u4F1A\u6539\u52A8\u539F\u5361\u3002")))}function DuplicateReviewPage({namespace,repair,onBack,openEvent,refresh}){let[page,setPage]=React.useState({items:[],offset:0,limit:20,total:0}),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[notice,setNotice]=React.useState(""),[loading,setLoading]=React.useState(!0),[index,setIndex]=React.useState(0),[queue,setQueue]=React.useState("review"),[lastAction,setLastAction]=React.useState(null),draftCache=React.useRef(new Map),focusPair=React.useRef(null),committedRead=React.useRef(!1),readFailure=reason=>(committedRead.current?"\u5904\u7406\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u8BFB\u53D6\u7ED3\u679C\u5931\u8D25\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u7ED3\u679C\u3002":"")+String(reason.message||reason),requestId=React.useRef(0),load=(offset=0,targetQueue=queue,focus=focusPair.current)=>{let id2=++requestId.current;return setLoading(!0),api2("duplicates",{namespace,offset,limit:20,queue:targetQueue,...focus?{focusLeft:focus.leftId,focusRight:focus.rightId}:{}}).then(value=>{id2===requestId.current&&(setPage(value),setIndex(i2=>value.focusIndex??Math.min(i2,Math.max(0,value.items.length-1))),focusPair.current=null,committedRead.current=!1)}).finally(()=>{id2===requestId.current&&setLoading(!1)})};React.useEffect(()=>{let active=!0,id2=++requestId.current;setLoading(!0),setError("");let focus=focusPair.current;return api2("duplicates",{namespace,offset:page.namespace===namespace&&page.queue===queue?page.offset:0,limit:20,queue,...focus?{focusLeft:focus.leftId,focusRight:focus.rightId}:{}}).then(value=>{active&&id2===requestId.current&&(setPage(value),setIndex(i2=>value.focusIndex??(page.namespace===namespace&&page.queue===queue?Math.min(i2,Math.max(0,value.items.length-1)):0)),focusPair.current=null,committedRead.current=!1)}).catch(reason=>{active&&id2===requestId.current&&setError(readFailure(reason))}).finally(()=>{active&&id2===requestId.current&&setLoading(!1)}),()=>{active=!1}},[namespace,queue,JSON.stringify(repair)]);let pairInput=item=>item?{leftId:item.leftId,rightId:item.rightId,leftFingerprint:item.leftFingerprint,rightFingerprint:item.rightFingerprint,exact:item.exact,similarity:item.similarity}:void 0,takeOver=item=>(setBusy(!0),setError(""),api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"takeover",pair:pairInput(item)})}).then(()=>(focusPair.current=item,setQueue("review"),setNotice("\u5DF2\u7531\u4F60\u63A5\u7BA1\uFF0CAI \u4E0D\u518D\u81EA\u52A8\u5904\u7406\u8FD9\u7EC4\u3002"),refresh())).catch(reason=>setError(String(reason.message||reason))).finally(()=>setBusy(!1))),prepareDraft=(item,regenerate=!1)=>(setBusy(!0),api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"draft",pair:pairInput(item),regenerate})}).finally(()=>setBusy(!1))),control=(action,item,keepId,draft)=>{let committed=!1;setBusy(!0),setError(""),setNotice("");let pair=item?{leftId:item.leftId,rightId:item.rightId,leftFingerprint:item.leftFingerprint,rightFingerprint:item.rightFingerprint,exact:item.exact,similarity:item.similarity}:void 0;return api2("duplicates",{namespace},{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action,pair,keepId,draft,undoId:action==="undo"?item?.undoId:void 0})}).then(result=>{if(committed=!0,committedRead.current=!0,action==="undo"){for(let key of draftCache.current.keys())key.startsWith(namespace+":"+item.leftId+":"+item.rightId+":")&&draftCache.current.delete(key);focusPair.current=item,setQueue("review")}return setLastAction(result.undoId?{...item,undoId:result.undoId}:null),["merge","select","keep"].includes(action)&&(focusPair.current=item,setQueue("history")),setNotice(action==="rescan"?"\u5DF2\u91CD\u65B0\u626B\u63CF\uFF0CAI \u4F1A\u5148\u5904\u7406\u5019\u9009\u3002":action==="undo"?"\u5DF2\u64A4\u9500\uFF0C\u6062\u590D\u4E86\u5904\u7406\u524D\u7684\u5185\u5BB9\u3001\u72B6\u6001\u548C\u5173\u8054\u3002":action==="merge"?"\u5DF2\u4FDD\u5B58\u5B8C\u6574\u5408\u5E76\u7A3F\uFF0C\u53CC\u65B9\u8BC1\u636E\u4E0E\u6765\u6E90\u5DF2\u4FDD\u7559\u3002":action==="select"?"\u5DF2\u4FDD\u7559\u6240\u9009\u8BB0\u5FC6\uFF0C\u53E6\u4E00\u5F20\u5DF2\u5F52\u6863\uFF0C\u5185\u5BB9\u672A\u6DF7\u5408\u3002":"\u5DF2\u786E\u8BA4\u4FDD\u7559\u4E24\u5F20\u3002"),refresh()}).then(()=>(action==="rescan"&&setIndex(0),action==="undo"?load(0,"review",item):["merge","select","keep"].includes(action)?load(0,"history",item):load(action==="rescan"?0:page.offset))).catch(reason=>{if(committed){setError("\u5904\u7406\u5DF2\u4FDD\u5B58\uFF0C\u4F46\u8BFB\u53D6\u7ED3\u679C\u5931\u8D25\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u7ED3\u679C\u3002"+String(reason.message||reason));return}throw["merge","select","keep"].includes(action)||setError(String(reason.message||reason)),reason}).finally(()=>setBusy(!1))},navigate=direction=>{if(setError(""),setNotice(""),index+direction>=0&&index+direction<page.items.length){setIndex(index+direction);return}let id2=++requestId.current;setLoading(!0),api2("duplicates",{namespace,offset:Math.max(0,page.offset+direction*page.limit),limit:20,queue}).then(value=>{id2===requestId.current&&(setPage(value),setIndex(direction>0?0:Math.max(0,value.items.length-1)))}).catch(reason=>{id2===requestId.current&&setError(String(reason.message||reason))}).finally(()=>{id2===requestId.current&&setLoading(!1)})},current=page.items[Math.min(index,Math.max(0,page.items.length-1))],draftKey=current?namespace+":"+current.leftId+":"+current.rightId+":"+current.leftFingerprint+":"+current.rightFingerprint:"";return h(React.Fragment,null,h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-duplicates"},h("header",{className:"sg-dup-heading"},h("div",null,h("h2",null,"\u91CD\u590D\u8BB0\u5FC6\u6574\u7406"),h("p",null,"AI \u5148\u5224\u65AD\u5E76\u6574\u7406\u3002\u8FD9\u91CC\u53EA\u9700\u8981\u4F60\u5904\u7406\u62FF\u4E0D\u51C6\u7684\u8BB0\u5FC6\u3002")),h(DuplicateIcon,{size:25})),h("nav",{className:"sg-dup-queues","aria-label":"\u6574\u7406\u961F\u5217"},[["review","\u9700\u8981\u4F60\u5224\u65AD",repair?.needsReview||0],["ai","\u7B49\u5F85 AI",repair?.awaitingAI||0],["history","\u5DF2\u5904\u7406",(repair?.merged||0)+(repair?.selected||0)+(repair?.retained||0)-(repair?.needsReview||0)+(repair?.failed||0)]].map(([value,label,count])=>h("button",{key:value,type:"button",className:"sg-dup-button","aria-pressed":queue===value,disabled:busy,onClick:()=>{setQueue(value),setError(""),setIndex(0)}},label+" "+Math.max(0,count)))),error3?h("div",{role:"alert",className:"sg-dup-notice error"},error3,h("button",{type:"button",className:"sg-dup-button text",disabled:busy||loading,onClick:()=>{setError(""),load(page.offset).catch(reason=>setError(readFailure(reason)))}},"\u91CD\u65B0\u8BFB\u53D6")):null,notice?h("div",{role:"status",className:"sg-dup-notice","aria-live":"polite"},notice,lastAction?h("button",{type:"button",className:"sg-dup-button",disabled:busy,onClick:()=>{control("undo",lastAction).catch(()=>{})}},"\u64A4\u9500\u672C\u6B21\u5904\u7406"):null):null,!error3&&(loading||page.namespace!==namespace||page.queue!==queue)?h("div",{className:"sg-dup-comparison",role:"status","aria-label":"\u6B63\u5728\u8BFB\u53D6\u91CD\u590D\u8BB0\u5FC6"},h("div",{className:"sg-dup-skeleton"}),h("div",{className:"sg-dup-skeleton"})):current&&page.namespace===namespace&&page.queue===queue?h(React.Fragment,null,h("nav",{className:"sg-dup-navigation","aria-label":"\u5207\u6362\u5019\u9009\u7EC4"},h("button",{type:"button",className:"sg-dup-button","aria-label":"\u4E0A\u4E00\u7EC4",disabled:busy||page.offset+index<=0,onClick:()=>navigate(-1)},h(DuplicateIcon,{kind:"back",size:14})),h("select",{value:index,disabled:busy,onChange:event3=>{setIndex(Number(event3.target.value)),setNotice("")},"aria-label":"\u5F53\u524D\u5019\u9009\u7EC4"},page.items.map((item,i2)=>h("option",{key:item.leftId+":"+item.rightId,value:i2},item.left?.title||item.right?.title||"\u539F\u5361\u5DF2\u4E0D\u53EF\u7528"))),h("span",{className:"sg-dup-count"},page.offset+index+1+" / "+page.total),h("button",{type:"button",className:"sg-dup-button","aria-label":"\u4E0B\u4E00\u7EC4",disabled:busy||page.offset+index+1>=page.total,onClick:()=>navigate(1)},h(DuplicateIcon,{kind:"next",size:14}))),h(DuplicatePair,{key:namespace+current.leftId+current.rightId+current.leftFingerprint+current.rightFingerprint+current.outcome+!!current.userReviewed,item:current,busy,namespace,onResolve:control,onPrepareDraft:prepareDraft,onTakeOver:takeOver,draftState:draftCache.current.get(draftKey),onDraftState:value=>{draftCache.current.set(draftKey,value),draftCache.current.size>50&&draftCache.current.delete(draftCache.current.keys().next().value)}})):error3?null:h("section",{className:"sg-dup-empty"},h(DuplicateIcon,{kind:"check",size:28}),h("strong",null,queue==="review"?"\u6682\u65F6\u6CA1\u6709\u9700\u8981\u4F60\u5224\u65AD\u7684\u8BB0\u5FC6":queue==="ai"?"\u6CA1\u6709\u7B49\u5F85 AI \u7684\u5019\u9009":"\u8FD8\u6CA1\u6709\u5904\u7406\u8BB0\u5F55"),h("p",null,queue==="review"?"AI \u80FD\u5904\u7406\u7684\u4F1A\u81EA\u52A8\u5B8C\u6210\u3002\u4F60\u53EF\u4EE5\u5728\u201C\u5DF2\u5904\u7406\u201D\u67E5\u770B\u7ED3\u679C\u3002":"\u626B\u63CF\u548C\u5904\u7406\u8FDB\u5EA6\u4F1A\u5728\u5BF9\u5E94\u961F\u5217\u4E2D\u663E\u793A\u3002")),h("details",{className:"sg-dup-tools"},h("summary",null,"\u91CD\u65B0\u68C0\u67E5\u8BB0\u5FC6\u5E93"),h("p",null,"\u6309\u5F53\u524D\u89C4\u5219\u91CD\u65B0\u626B\u63CF\u3002\u540E\u7EED\u5224\u65AD\u53EF\u80FD\u4F7F\u7528\u5F53\u524D\u6A21\u578B\uFF0C\u5DF2\u5B8C\u6210\u7684\u626B\u63CF\u4E0D\u4F1A\u5728\u6BCF\u6B21\u542F\u52A8\u65F6\u91CD\u590D\u6267\u884C\u3002"),h("button",{type:"button",className:"sg-dup-button",disabled:busy||loading,onClick:()=>{control("rescan").catch(()=>{})}},"\u91CD\u65B0\u626B\u63CF\u4E0E\u5224\u65AD"))))}function SystemPage({selected,blocks,onBack,backLabel="\u66F4\u591A",refresh,onDuplicates}){let processing=blocks.filter(block=>block.status==="processing").length,[refreshing,setRefreshing]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),repair=selected.duplicateRepair,checkStatus=()=>{let before=processingFingerprint(selected);return setRefreshing(!0),setFeedback({kind:"",text:"\u6B63\u5728\u8BFB\u53D6\u2026"}),refresh({propagateError:!0}).then(next2=>{let updated=next2?.overview?.namespaces?.find(item=>item.namespace===selected.namespace);setFeedback({kind:"done",text:updated&&processingFingerprint(updated)!==before?"\u72B6\u6001\u5DF2\u66F4\u65B0":"\u72B6\u6001\u6CA1\u6709\u53D8\u5316"})}).catch(reason=>{setFeedback({kind:"failed",text:"\u8BFB\u53D6\u5931\u8D25\uFF1A"+String(reason?.message||reason)})}).finally(()=>setRefreshing(!1))};return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u7CFB\u7EDF\u72B6\u6001"),h("p",null,"\u4EC5\u5728\u8FD9\u91CC\u5C55\u793A\u8BB0\u5FC6\u5904\u7406\u7684\u5DE5\u7A0B\u72B6\u6001")),h("div",{className:"sg-pipeline"},[["Block \u6570\u91CF",selected.blocks],["\u5F85\u5904\u7406\u4EFB\u52A1",processing],["\u5931\u8D25\u4EFB\u52A1",selected.failedJobs],["\u6700\u8FD1\u6574\u7406\u65F6\u95F4",formatTime(selected.lastActivityAt)],["Event \u63D0\u53D6",selected.failedJobDetails?.some(item=>item.kind==="event-extraction")?"\u6709\u5931\u8D25":"\u6B63\u5E38"],["\u56FE\u8C31\u6295\u5F71",selected.failedJobDetails?.some(item=>item.kind==="graph-projection")?"\u6709\u5931\u8D25":"\u6B63\u5E38"]].map(([label,value])=>h("div",{key:label,className:"sg-stage"},h("span",null,label),h("span",{className:"sg-stage-value "+(label==="\u5931\u8D25\u4EFB\u52A1"&&value?"failed":"waiting")},String(value))))),repair?h("p",{className:"sg-setting-note",role:"status"},"\u5386\u53F2\u91CD\u590D\u8BB0\u5FC6\u6574\u7406"+(repair.status==="completed"?"\u5DF2\u5B8C\u6210":"\u8FDB\u884C\u4E2D")+"\uFF1A\u5DF2\u626B\u63CF "+repair.scannedEvents+" \u5F20\u5361\uFF0C\u5F52\u6863\u91CD\u590D\u5361 "+repair.merged+" \u5F20\uFF1B\u5176\u4F59\u4FDD\u7559\u3002"+(repair.failed?" \u90E8\u5206\u5224\u65AD\u672A\u5B8C\u6210\uFF0C\u539F\u5361\u5DF2\u4FDD\u7559\u3002":"")):null,h("button",{type:"button",className:"sg-quiet-button",onClick:onDuplicates},"\u67E5\u770B\u91CD\u590D\u5019\u9009\u4E0E\u5904\u7406\u539F\u56E0"),h("button",{type:"button",className:"sg-quiet-button",disabled:refreshing,onClick:()=>{checkStatus()},style:{marginTop:"14px"}},refreshing?"\u21BB \u6B63\u5728\u8BFB\u53D6\u2026":"\u21BB \u91CD\u65B0\u68C0\u67E5"),feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null)}function AuditPage({audit,auditPage,namespace,onBack,backLabel="\u66F4\u591A"}){let pagedAudit=usePagedMemory({namespace,kind:"audit",initialItems:audit,initialPage:auditPage,fallbackLimit:100});return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u4F7F\u7528\u8BB0\u5F55"),h("p",null,"\u957F\u671F\u8BB0\u5FC6\u88AB\u4F7F\u7528\u7684\u65F6\u95F4\u4E0E\u6765\u6E90")),pagedAudit.items.length?pagedAudit.items.map(item=>{let value=item.audit||{};return h("details",{key:item.id,className:"sg-audit"},h("summary",null,h("strong",null,"\u4F7F\u7528\u4E86 "+((item.events||[]).length+(item.elements||[]).length)+" \u6761\u8BB0\u5FC6"),h("span",{className:"sg-muted"}," \xB7 "+formatTime(item.createdAt))),h("div",{className:"sg-audit-body"},h("div",null,(item.events||[]).map(event3=>event3.title).join("\u3001")||(item.elements||[]).map(element3=>element3.name).join("\u3001")||"\u65E7\u7248\u4F7F\u7528\u8BB0\u5F55"),h("div",{className:"sg-tech-row sg-audit-evidence"},h("span",{className:"sg-muted"},"\u6765\u6E90\u4F1A\u8BDD"),h("span",{className:"sg-code"},value.sessionId||"\u672A\u8BB0\u5F55")),value.turn!==void 0?h("div",{className:"sg-tech-row"},h("span",{className:"sg-muted"},"Turn"),h("span",null,value.turn)):null))}):h(Empty,{title:"\u8FD8\u6CA1\u6709\u4F7F\u7528\u8BB0\u5F55",copy:"AI \u5728\u56DE\u7B54\u4E2D\u91C7\u7528\u957F\u671F\u8BB0\u5FC6\u540E\u4F1A\u8BB0\u5F55\u5728\u8FD9\u91CC\u3002"}),h(Pagination,{page:pagedAudit.page,loading:pagedAudit.loading,error:pagedAudit.error,onOffset:pagedAudit.loadOffset}))}function RawPage({data:data4,selected,onBack,backLabel="\u66F4\u591A"}){let groups=[["Block raw",data4.blocks,data4.pagination?.blocks?.total],["Event raw",data4.events,data4.pagination?.events?.total],["Graph raw",data4.graph],["Usage raw",data4.audit,data4.pagination?.audit?.total],["\u6A21\u578B\u54CD\u5E94",selected.successfulModelResponses||[]]];return h(React.Fragment,null,h(BackBar,{label:backLabel,onBack}),h("div",{className:"sg-intro"},h("h2",null,"\u539F\u59CB\u6570\u636E"),h("p",null,"\u4F9B\u6392\u67E5\u95EE\u9898\u4F7F\u7528\u7684\u5185\u90E8\u5B57\u6BB5\u4E0E JSON")),groups.map(([label,value,total])=>h("details",{key:label,className:"sg-raw-group"},h("summary",null,label+" ("+(Array.isArray(value)&&Number(total)>value.length?"\u5DF2\u52A0\u8F7D "+value.length+" / \u5171 "+total:Array.isArray(value)?value.length:(value.nodes?.length||0)+(value.edges?.length||0))+")"),h("pre",{className:"sg-raw-json sg-code"},JSON.stringify(value,null,2)))))}let profileGroups=[["\u79F0\u547C\u4E0E\u8BED\u8A00",[["userPreferredName","\u600E\u4E48\u79F0\u547C\u4F60",100],["assistantPreferredName","\u52A9\u624B\u53EB\u4EC0\u4E48",100],["preferredLanguage","\u56DE\u7B54\u7528\u4EC0\u4E48\u8BED\u8A00",100],["reasoningLanguage","\u601D\u8003\u8FC7\u7A0B\u7528\u4EC0\u4E48\u8BED\u8A00",100]]],["\u5730\u70B9",[["defaultLocation","\u5E38\u9A7B\u5730\u5740",200],["currentCity","\u73B0\u5728\u5728\u54EA",100],["homeCity","\u5E38\u9A7B\u57CE\u5E02\uFF08\u539F\u6709\u5B57\u6BB5\uFF09",100]]],["\u600E\u4E48\u56DE\u7B54\u4F60",[["responsePreferences","\u56DE\u590D\u65B9\u5F0F",1e3],["standingInstructions","\u4E00\u76F4\u8981\u9075\u5B88\u7684\u8981\u6C42",1e3]]],["\u5173\u4E8E\u4F60",[["userBackground","\u80CC\u666F",1500],["longTermGoals","\u957F\u671F\u76EE\u6807",1e3]]],["\u5176\u4ED6",[["persistentNotes","\u5176\u4ED6\u8981\u4E00\u76F4\u8BB0\u4F4F\u7684",1200]]]],PROFILE_EMPTY_HINTS={userPreferredName:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5C0F\u7A0B",assistantPreferredName:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u6A59\u5B50",preferredLanguage:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E2D\u6587",reasoningLanguage:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E2D\u6587",responsePreferences:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5148\u7ED9\u7ED3\u8BBA\uFF0C\u518D\u5C55\u5F00",standingInstructions:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u6539\u4EE3\u7801\u524D\u5148\u8BF4\u65B9\u6848",defaultLocation:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u5317\u4EAC\u5E02\u6D77\u6DC0\u533A",currentCity:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4E0A\u6D77",homeCity:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u676D\u5DDE",userBackground:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u8F6F\u4EF6\u5DE5\u7A0B\u5E08\uFF0C\u719F\u6089 Python",longTermGoals:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u4ECA\u5E74\u5B8C\u6210\u4E00\u7BC7\u8BBA\u6587",persistentNotes:"\u672A\u8BBE\u7F6E \xB7 \u4F8B\u5982\uFF1A\u9879\u76EE\u7EDF\u4E00\u4F7F\u7528 pnpm"},profileFieldNames=profileGroups.flatMap(([,fields])=>fields.map(([field])=>field)),PROFILE_LIMIT_DEFAULT=6e3,PROFILE_LIMIT_MIN=2e3,PROFILE_LIMIT_MAX=12e3,profileTotalLimit=value=>{let candidate=Number(value?._limits?.totalMaxLength);return Number.isSafeInteger(candidate)&&candidate>0?candidate:PROFILE_LIMIT_DEFAULT},profileTotalLength=value=>profileFieldNames.reduce((sum,field)=>sum+Array.from(value?.[field]||"").length,0),profileRightColumn=new Set(["\u600E\u4E48\u56DE\u7B54\u4F60","\u5173\u4E8E\u4F60","\u5176\u4ED6"]),formatCount=value=>Number(value||0).toLocaleString("en-US");function sameProfile(left,right){return profileFieldNames.every(field=>left?.[field]===right?.[field]&&left?._revisions?.[field]===right?._revisions?.[field])&&profileTotalLimit(left)===profileTotalLimit(right)}function ProfilePage(){let[profile,setProfile]=usePageMemoryState(profilePageMemory,"profile",null),[editing,updateEditing]=usePageMemoryState(profilePageMemory,"editing",null),setEditing=update2=>{let previous=profilePageMemory.get("editing"),next2=typeof update2=="function"?update2(previous):update2;next2?profileFieldDrafts.set(next2.field,next2):previous&&profileFieldDrafts.delete(previous.field),updateEditing(next2)},[saving,setSaving]=React.useState(!1),[syncStatus,setSyncStatus]=React.useState("\u66F4\u65B0\u4E2D\u2026"),[error3,setError]=React.useState(""),[conflicts,setConflicts]=usePageMemoryState(profilePageMemory,"conflicts",{}),conflict=!!conflicts[editing?.field],setConflict=(value,field=profilePageMemory.get("editing")?.field)=>{field&&setConflicts(current=>({...current,[field]:value}))},[saveResults,setSaveResults]=usePageMemoryState(profilePageMemory,"saveResults",{}),[reading,setReading]=React.useState(!1),session=React.useRef(0),action=React.useRef(null),actionTimeout=React.useRef(null),readController=React.useRef(null),savedTimers=React.useRef(new Map),requestVersion=React.useRef(0),refreshRef=React.useRef(null),clearSavedTimer=field=>{window.clearTimeout(savedTimers.current.get(field)),savedTimers.current.delete(field)},showSaved=submission=>{clearSavedTimer(submission.field),setSaveResults(current=>({...current,[submission.field]:{kind:"saved",submission,flash:!0}}));let timer=window.setTimeout(()=>{savedTimers.current.get(submission.field)===timer&&(savedTimers.current.delete(submission.field),setSaveResults(current=>current[submission.field]?.submission===submission?{...current,[submission.field]:{...current[submission.field],flash:!1}}:current))},2e3);savedTimers.current.set(submission.field,timer)};React.useEffect(()=>{let active=!0,timer=null,controller=null,stopRequest=()=>{controller&&controller.abort(),controller=null,readController.current=null},check=({valid:valid2=()=>!0,onResult}={})=>{if(!active||document.hidden)return;if(timer!==null&&window.clearTimeout(timer),timer=null,stopRequest(),action.current){timer=window.setTimeout(check,5e3);return}let version2=++requestVersion.current,requestController=new AbortController;return controller=requestController,readController.current=requestController,api2("profile",{},{method:"GET",signal:requestController.signal}).then(latest=>{if(!(!active||document.hidden||version2!==requestVersion.current||!valid2())){if(!profileFieldNames.every(field=>typeof latest?.[field]=="string")||!latest?._revisions)throw new Error("\u753B\u50CF\u8BFB\u53D6\u54CD\u5E94\u4E0D\u5B8C\u6574");setProfile(current=>sameProfile(current,latest)?current:latest),setSyncStatus("\u5DF2\u662F\u6700\u65B0"),setError(""),onResult?.(latest)}}).catch(reason=>{active&&version2===requestVersion.current&&valid2()&&reason?.name!=="AbortError"&&(setSyncStatus("\u8BFB\u53D6\u5931\u8D25"),setError(String(reason?.message||reason)))}).finally(()=>{controller===requestController&&(controller=null,readController.current=null),active&&!document.hidden&&version2===requestVersion.current&&(timer=window.setTimeout(check,5e3))})};refreshRef.current=check;let onVisibilityChange=()=>{timer!==null&&window.clearTimeout(timer),timer=null,document.hidden?(++requestVersion.current,stopRequest()):check()};return document.addEventListener("visibilitychange",onVisibilityChange),check(),()=>{let submission=action.current?.submission;submission&&!profilePageMemory.get("saveResults")?.[submission.field]&&setSaveResults(current=>({...current,[submission.field]:{kind:"unknown",submission}})),active=!1,++session.current,++requestVersion.current,refreshRef.current=null,timer!==null&&window.clearTimeout(timer),stopRequest(),action.current?.abort(),action.current=null,window.clearTimeout(actionTimeout.current),actionTimeout.current=null,savedTimers.current.forEach(id2=>window.clearTimeout(id2)),savedTimers.current.clear(),setSaveResults(current=>Object.fromEntries(Object.entries(current).map(([field,result])=>[field,result.kind==="saved"?{...result,flash:!1}:result]))),document.removeEventListener("visibilitychange",onVisibilityChange)}},[]);let resetEdit=field=>{++session.current,++requestVersion.current,readController.current?.abort(),setReading(!1),field&&(setConflict(!1,field),clearSavedTimer(field),setSaveResults(current=>{let next2={...current};return delete next2[field],next2})),refreshRef.current?.()},beginEdit=field=>{resetEdit(profileFieldDrafts.has(field)?void 0:field),setEditing(profileFieldDrafts.get(field)||{field,draft:profile[field]||"",baseValue:profile[field]||"",baseRevision:profile._revisions?.[field]||0})},reloadField=()=>{if(!editing||saving||reading)return;let id2=session.current;setReading(!0),refreshRef.current?.({valid:()=>session.current===id2,onResult:latest=>{setEditing(current=>current?{...current,draft:latest[current.field],baseValue:latest[current.field],baseRevision:latest._revisions[current.field]}:null),setConflict(!1),setSaveResults(current=>{let next2={...current};return delete next2[editing.field],next2})}})?.finally(()=>{session.current===id2&&setReading(!1)})},save=()=>{if(!editing||action.current||saving||reading||saveResults[editing.field]?.kind==="unknown")return;if(conflict||profile[editing.field]!==editing.baseValue||profile._revisions?.[editing.field]!==editing.baseRevision){setConflict(!0);return}let submission={...editing},id2=session.current,controller=new AbortController;controller.submission=submission,action.current=controller;let valid2=()=>session.current===id2&&action.current===controller;setSaving(!0),setSaveResults(current=>{let next2={...current};return delete next2[submission.field],next2}),++requestVersion.current,readController.current?.abort();let timeout=window.setTimeout(()=>controller.abort(),15e3);actionTimeout.current=timeout,api2("profile",{},{method:"PATCH",signal:controller.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify({field:submission.field,value:submission.draft,expectedValue:submission.baseValue,expectedRevision:submission.baseRevision})}).then(result=>{if(valid2()){if(!profileFieldNames.every(field=>typeof result?.snapshot?.[field]=="string")||!Number.isSafeInteger(result.snapshot?._revisions?.[submission.field]))throw new Error("\u753B\u50CF\u4FDD\u5B58\u54CD\u5E94\u4E0D\u5B8C\u6574");setProfile(result.snapshot),setEditing(null),setConflict(!1,submission.field),showSaved(submission)}}).catch(reason=>{if(!valid2())return;let message=String(reason?.message||reason);if(reason?.status===409||message.includes("\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0")){setConflict(!0);return}let unknown=!reason?.status||[408,502,504].includes(reason.status),invalid=[400,413,422].includes(reason?.status),maximum=profileGroups.flatMap(([,fields])=>fields).find(([field])=>field===submission.field)?.[2],detail=/Persistent Profile exceeds/.test(message)?"\u753B\u50CF\u603B\u5B57\u7B26\u6570\u4E0D\u80FD\u8D85\u8FC7 6000\uFF0C\u8BF7\u7F29\u77ED\u5185\u5BB9\u3002":/exceeds \d+ characters/.test(message)?"\u6B64\u5B57\u6BB5\u4E0D\u80FD\u8D85\u8FC7 "+maximum+" \u4E2A\u5B57\u7B26\uFF0C\u8BF7\u7F29\u77ED\u5185\u5BB9\u3002":message;setSaveResults(current=>({...current,[submission.field]:{kind:unknown?"unknown":invalid?"invalid":"failed",submission,detail}}))}).finally(()=>{window.clearTimeout(timeout),actionTimeout.current===timeout&&(actionTimeout.current=null),valid2()&&(action.current=null,setSaving(!1),refreshRef.current?.())})},checkSave=result=>{if(reading||action.current)return;let id2=session.current,{submission}=result;setReading(!0),refreshRef.current?.({valid:()=>session.current===id2,onResult:latest=>{latest[submission.field]===submission.draft&&Number.isSafeInteger(latest._revisions[submission.field])&&latest._revisions[submission.field]>submission.baseRevision&&(showSaved(submission),setEditing(current=>current?.field===submission.field?current.draft===submission.draft?null:{...current,baseValue:latest[submission.field],baseRevision:latest._revisions[submission.field]}:current),setConflict(!1,submission.field))}})?.finally(()=>{session.current===id2&&setReading(!1)})},total=profileTotalLength(profile),limit2=profileTotalLimit(profile);return h(React.Fragment,null,h("div",{className:"sg-pg-head"},h("h2",null,"\u5E38\u9A7B\u753B\u50CF"),h("span",{className:"sg-pg-tag"},h("i",{className:"sg-sw ink","aria-hidden":"true"}),"\u6BCF\u8F6E\u90FD\u5E26\u7ED9 AI \xB7 \u70B9\u4EFB\u610F\u4E00\u884C\u4FEE\u6539"),syncStatus==="\u8BFB\u53D6\u5931\u8D25"?h("span",{className:"sg-pg-end"},h("span",{className:"sg-profile-sync failed",role:"alert"},syncStatus)):null),error3?h("p",{className:"sg-profile-error",role:"alert"},error3):null,profile?h(React.Fragment,null,h("div",{className:"sg-cap-row"},h("div",{className:"sg-cap-bar",role:"img","aria-label":"\u5E38\u9A7B\u753B\u50CF\u5DF2\u7528 "+total+" \u5B57\uFF0C\u4E0A\u9650 "+formatCount(limit2)+" \u5B57"},h("i",{style:{width:Math.min(100,total/limit2*100)+"%"}})),h("span",{className:"sg-cap-num"},h("b",null,formatCount(total)),"/ "+formatCount(limit2)+" \u5B57")),h("div",{className:"sg-pf"},[["1",profileGroups.filter(([title])=>!profileRightColumn.has(title))],["2",profileGroups.filter(([title])=>profileRightColumn.has(title))]].map(([column,groups])=>h("div",{key:column,className:"sg-pf-col","data-pf-stack":column},groups.map(([title,fields])=>h("section",{key:title,className:"sg-profile-group","aria-label":title},h("h4",null,title),h("ul",null,fields.filter(([field])=>field!=="homeCity"||profile.homeCity||profileFieldDrafts.has(field)).map(([field,label,maximum])=>{let value=profile[field]||"",isEditing=editing?.field===field,changedElsewhere=isEditing&&(value!==editing.baseValue||profile._revisions?.[field]!==editing.baseRevision),draftLength=isEditing?Array.from(editing.draft).length:0,nextTotal=total-Array.from(value).length+draftLength,result=saveResults[field],savedReadError=result?.kind==="saved"&&!!error3,savedFeedback=result?.kind==="saved"&&result.flash?h("span",{className:"sg-profile-saved",role:"status"},isEditing&&editing.draft!==result.submission.draft?"\u4E0A\u6B21\u63D0\u4EA4\u5DF2\u4FDD\u5B58":"\u5DF2\u4FDD\u5B58"):null,editor=isEditing?h("div",{className:"sg-profile-editor"},field==="userPreferredName"||field==="assistantPreferredName"||field==="preferredLanguage"||field==="reasoningLanguage"||field==="defaultLocation"||field==="homeCity"||field==="currentCity"?h("input",{id:"sg-profile-"+field,"aria-label":label,autoFocus:!0,disabled:saving,value:editing.draft,onChange:event3=>setEditing(current=>({...current,draft:event3.target.value}))}):h("textarea",{id:"sg-profile-"+field,"aria-label":label,autoFocus:!0,disabled:saving,value:editing.draft,onChange:event3=>setEditing(current=>({...current,draft:event3.target.value}))}),changedElsewhere||conflict?h("p",{className:"sg-profile-conflict",role:"alert"},"\u8BE5\u9879\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0\u3002",h("button",{type:"button",className:"sg-profile-action",disabled:saving||reading,onClick:reloadField},"\u653E\u5F03\u8349\u7A3F\u5E76\u8F7D\u5165\u6700\u65B0\u5185\u5BB9")):null,result&&["failed","invalid","unknown"].includes(result.kind)?h("div",{className:"sg-profile-save-feedback sg-profile-save-feedback-"+result.kind,role:result.kind==="unknown"?"status":"alert"},h("p",null,result.kind==="unknown"?"\u6682\u65F6\u65E0\u6CD5\u786E\u8BA4\u662F\u5426\u5DF2\u4FDD\u5B58\uFF0C\u8F93\u5165\u5185\u5BB9\u5DF2\u4FDD\u7559\u3002":"\u4FEE\u6539\u672A\u4FDD\u5B58\uFF0C\u8F93\u5165\u5185\u5BB9\u5DF2\u4FDD\u7559\u3002"),result.kind==="unknown"?h("button",{type:"button",className:"sg-profile-action",disabled:reading,onClick:()=>checkSave(result)},reading?"\u68C0\u67E5\u4E2D\u2026":"\u68C0\u67E5\u4FDD\u5B58\u7ED3\u679C"):result.kind==="invalid"?h("p",null,result.detail):null):null,h("div",{className:"sg-profile-editor-foot"},h("span",{className:"sg-profile-count"},formatCount(draftLength)+" / "+formatCount(maximum),draftLength>maximum?"\uFF0C\u8BF7\u7F29\u77ED\u81F3 "+formatCount(maximum)+" \u4E2A\u5B57\u7B26\u4EE5\u5185\u3002":nextTotal>limit2?"\uFF0C\u753B\u50CF\u603B\u5B57\u7B26\u6570\u4E0D\u80FD\u8D85\u8FC7 "+formatCount(limit2)+"\u3002":"",savedFeedback),h("div",{className:"sg-profile-actions"},h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:()=>{resetEdit(field),setEditing(null)}},"\u53D6\u6D88\u7F16\u8F91"),h("button",{type:"button",className:"sg-save-button",disabled:saving||reading||result?.kind==="unknown"||draftLength>maximum||nextTotal>limit2||editing.draft===editing.baseValue||changedElsewhere||conflict,onClick:save},saving?"\u4FDD\u5B58\u4E2D\u2026":result?.kind==="failed"?"\u91CD\u65B0\u4FDD\u5B58":"\u4FDD\u5B58")))):null;return h("li",{key:field,className:"sg-profile-row",onClick:isEditing?void 0:()=>{saving||beginEdit(field)}},h("div",{className:"sg-profile-summary"+(isEditing?" editing":"")},h("div",{className:"sg-profile-label-cell"},h("span",{className:"sg-profile-label"},label),editor||h("span",{className:"sg-profile-content"},h("button",{type:"button",className:"sg-profile-value "+(value?"":"empty"),title:value||PROFILE_EMPTY_HINTS[field],"aria-label":label+(value?"\uFF0C\u70B9\u51FB\u7F16\u8F91":"\uFF0C\u672A\u586B\u5199\uFF0C\u70B9\u51FB\u586B\u5199"),disabled:saving,onClick:event3=>{event3?.stopPropagation?.(),beginEdit(field)}},profileFieldDrafts.has(field)?"\u7EE7\u7EED\u7F16\u8F91\u8349\u7A3F":value||"\u672A\u586B\u5199"),savedFeedback)),isEditing?null:h("span",{className:"sg-profile-chev","aria-hidden":"true"},"\u203A"),h("button",{type:"button",className:"sg-profile-action",onClick:event3=>{event3?.stopPropagation?.(),beginEdit(field)},disabled:saving,"aria-hidden":isEditing||void 0},!isEditing&&profileFieldDrafts.has(field)?"\u7EE7\u7EED\u7F16\u8F91":value?"\u7F16\u8F91":"\u6DFB\u52A0")),savedReadError?h("p",{className:"sg-profile-save-feedback",role:"status"},h("span",null,"\u4FEE\u6539\u5DF2\u4FDD\u5B58\uFF0C\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6700\u65B0\u5185\u5BB9\u3002"),h("button",{type:"button",className:"sg-profile-action",disabled:reading,onClick:()=>refreshRef.current?.()},"\u91CD\u65B0\u8BFB\u53D6")):null)})))))))):h("p",null,"\u6B63\u5728\u8BFB\u53D6\u5E38\u9A7B\u753B\u50CF\u2026"))}let GRAPH_EXPLANATION="\u7531\u4E8E\u77E5\u8BC6\u56FE\u8C31\u529F\u80FD\u4E0E\u4E8B\u4EF6\u8BB0\u5F55\u548C\u4E3B\u9898\u76EE\u5F55\u6709\u90E8\u5206\u91CD\u590D\uFF0C\u8FD8\u9700\u8981\u989D\u5916\u6D88\u8017token\u7EF4\u62A4\u5B9E\u4F53\u5173\u7CFB\uFF0C\u5C06\u4F1A\u9ED8\u8BA4\u5173\u95ED\u77E5\u8BC6\u56FE\u8C31\u529F\u80FD\uFF0C\u5DF2\u7ECF\u751F\u6210\u7684\u56FE\u8C31\u6570\u636E\u4F1A\u4FDD\u7559\u3002",GRAPH_USAGE_HINT="\u63D0\u793A\uFF1A\u5982\u9700\u4F7F\u7528\uFF0C\u53EF\u4EE5\u5728\u957F\u671F\u8BB0\u5FC6\u9875\u9762\u70B9\u51FB\u201C\uFF0B\u201D\uFF0C\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31\uFF0C\u529F\u80FD\u53EF\u4EE5\u6B63\u5E38\u4F7F\u7528\u3002",GRAPH_CONTROL_STYLES=".sg-graph-no-reminder{display:inline-flex;align-items:center;min-height:30px;padding:5px 8px;border:1px solid var(--sg-border);border-radius:6px;background:var(--sg-surface);color:var(--sg-muted);cursor:pointer}.sg-graph-no-reminder:hover{border-color:var(--sg-accent);color:var(--sg-accent);background:var(--sg-soft)}.sg-graph-no-reminder:disabled{cursor:not-allowed;opacity:.5}.sg-graph-notice-toggle{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 0;border-top:1px solid var(--sg-border);border-bottom:1px solid var(--sg-border)}.sg-graph-notice-toggle>span{font-size:13px;font-weight:650}.sg-graph-menu{position:relative;z-index:31;display:inline-flex;align-items:center}.sg-long-tabs .sg-graph-menu-trigger{display:grid;place-items:center;align-self:center;flex:none;box-sizing:border-box;width:32px;height:32px;min-width:32px;min-height:32px;padding:0;border:0;border-radius:999px;background:transparent;color:var(--sg-muted);font-size:22px;line-height:1;cursor:pointer}.sg-graph-menu-trigger svg{display:block;width:16px;height:16px;flex:none}.sg-graph-menu-trigger:hover,.sg-graph-menu-trigger[aria-expanded=true]{background:var(--sg-soft);color:var(--sg-accent)}.sg-graph-menu-popover{position:absolute;z-index:32;right:0;left:auto;top:calc(100% + 8px);width:min(300px,calc(100vw - 32px));padding:10px;border:1px solid var(--sg-border);border-radius:10px;background:var(--sg-page);box-shadow:var(--sg-shadow);text-align:left}.sg-graph-menu-title{display:block;padding:0 2px 8px;color:var(--sg-text);font-size:13px;font-weight:650;line-height:1.4}.sg-graph-open{display:block;width:100%;margin-top:8px;padding:6px 2px 2px;border:0;border-top:1px solid var(--sg-border);background:none;color:var(--sg-text);font-size:12.5px;text-align:left;cursor:pointer}.sg-graph-open:hover{color:var(--sg-accent)}.sg-graph-copy{display:block;min-width:0}.sg-graph-title-row{display:flex;align-items:center;gap:6px;min-width:0}.sg-graph-copy b{display:block;font-size:13.5px;font-weight:650;color:var(--sg-text)}.sg-graph-copy span{display:block;margin-top:2px;font-size:11.5px;line-height:1.45;color:var(--sg-muted)}.sg-graph-title-row .sg-info-disclosure{display:inline-flex;flex:none} .sg-graph-copy .sg-graph-title-row{display:flex}.sg-graph-title-row .sg-info-trigger{width:18px;height:18px;font-size:12px}.sg-graph-menu-popover .sg-storage-card{padding:0;border:0;background:transparent}.sg-graph-menu-popover .sg-setting-note{font-size:11px;line-height:1.5}.sg-graph-dialog-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}.sg-graph-dialog-heading h3{margin:0}.sg-graph-dialog-control{display:flex;align-items:center;gap:7px;color:var(--sg-muted);font-size:12px}";function GraphControlPanel({state={},refresh,page=!1,onGraphHidden,onOpenGraph}){let shouldShowNotice=!page&&state.enabled!==!0&&state.noticeSeen!==!0,[notice,setNotice]=React.useState(shouldShowNotice),[preview,setPreview]=React.useState(null),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState(""),[hideExplanation,setHideExplanation]=React.useState(!1),dialogRef=React.useRef(null);React.useEffect(()=>{setNotice(!page&&state.enabled!==!0&&state.noticeSeen!==!0)},[page,state.enabled,state.noticeSeen]),React.useEffect(()=>{if(!notice&&!preview)return;let previous=document.activeElement;return dialogRef.current?.querySelector("button")?.focus(),()=>{previous?.isConnected&&previous.focus?.()}},[notice,preview]);let control=async(action,token)=>{setBusy(!0),setError("");try{let result=await api2("graph/control",{action,...token?{token}:{}},{method:"POST"});action==="preview"?result.pending>0?setPreview(result):(await api2("graph/control",{action:"enable",token:result.token},{method:"POST"}),await refresh?.()):(setPreview(null),action==="notice"&&(setNotice(!1),setHideExplanation(!0),onGraphHidden?.()),await refresh?.())}catch(reason){setError(String(reason?.message||reason))}finally{setBusy(!1)}},graphStatus=state.enabled===!0?state.paused?"\u5DF2\u6682\u505C\u66F4\u65B0\uFF0C\u53EF\u67E5\u770B\u65E7\u56FE\u8C31":"\u5DF2\u5F00\u542F":"\u9ED8\u8BA4\u5173\u95ED\uFF0C\u6253\u5F00\u540E\u53EF\u67E5\u770B\u5DF2\u6709\u56FE\u8C31",graphInfo=page?null:h(InfoPopover,{label:"\u77E5\u8BC6\u56FE\u8C31\u8BF4\u660E"},h("p",null,GRAPH_EXPLANATION),h("p",null,GRAPH_USAGE_HINT)),showExplanation=!hideExplanation&&(!page||state.noticeSeen!==!0);return h(React.Fragment,null,h("style",null,GRAPH_CONTROL_STYLES),h("aside",{className:"sg-storage-card sg-graph-control"+(page?" sg-graph-page-control":""),"aria-label":page?"\u77E5\u8BC6\u56FE\u8C31\u5F00\u5173":void 0},h("div",{className:"sg-stage"},h("span",{className:"sg-graph-copy"},h("span",{className:"sg-graph-title-row"},h("b",null,page?"\u663E\u793A\u77E5\u8BC6\u56FE\u8C31":"\u542F\u7528\u77E5\u8BC6\u56FE\u8C31"),graphInfo),page?h("span",null,graphStatus):null),h("span",{className:"sg-lambda-control sg-graph-toggle"},!page&&showExplanation?h("button",{type:"button",className:"sg-icon-button","aria-label":"\u4E0D\u518D\u63D0\u9192",title:"\u4E0D\u518D\u63D0\u9192",disabled:busy,onClick:()=>{control("notice")}},"\xD7"):null,h("button",{type:"button",role:"switch","aria-label":"\u663E\u793A\u77E5\u8BC6\u56FE\u8C31","aria-checked":state.enabled===!0,disabled:busy,className:"sg-setting-switch",onClick:()=>{control(state.enabled?"disable":"preview")}}))),page&&state.enabled===!0?h("button",{type:"button",className:"sg-graph-open",onClick:()=>onOpenGraph?.()},"\u6253\u5F00\u77E5\u8BC6\u56FE\u8C31 \u2192"):null,!page&&state.enabled?h("button",{type:"button",className:"sg-storage-button",disabled:busy,onClick:()=>{control(state.paused?"preview":"pause")}},state.paused?"\u7EDF\u8BA1\u5E76\u7EE7\u7EED\u56FE\u8C31\u4EFB\u52A1":"\u6682\u505C\u56FE\u8C31\u4EFB\u52A1"):null,error3?h("p",{role:"alert",className:"sg-error-note"},error3):null,notice||preview?h("div",{className:"sg-import-overlay"},h("section",{ref:dialogRef,role:"dialog","aria-modal":"true","aria-label":notice?"\u77E5\u8BC6\u56FE\u8C31\u9ED8\u8BA4\u5173\u95ED\u8BF4\u660E":"\u786E\u8BA4\u6062\u590D\u77E5\u8BC6\u56FE\u8C31",className:"sg-import-dialog",onKeyDown:event3=>{if(event3.key==="Escape"&&preview&&!notice&&!busy&&(event3.preventDefault(),setPreview(null)),event3.key==="Tab"){let buttons=[...dialogRef.current.querySelectorAll("button:not(:disabled)")];if(!buttons.length){event3.preventDefault();return}let first2=buttons[0],last2=buttons.at(-1);event3.shiftKey&&document.activeElement===first2?(event3.preventDefault(),last2.focus()):!event3.shiftKey&&document.activeElement===last2&&(event3.preventDefault(),first2.focus())}}},h("div",{className:"sg-graph-dialog-heading"},h("h3",null,notice?"\u77E5\u8BC6\u56FE\u8C31\u9ED8\u8BA4\u5173\u95ED":"\u786E\u8BA4\u6062\u590D\u77E5\u8BC6\u56FE\u8C31"),notice?h("span",{className:"sg-graph-dialog-control"},h("span",null,"\u5F00\u542F"),h("button",{type:"button",role:"switch","aria-label":"\u542F\u7528\u77E5\u8BC6\u56FE\u8C31","aria-checked":state.enabled===!0,disabled:busy,className:"sg-setting-switch",onClick:()=>{control("preview")}})):null),h("p",null,GRAPH_EXPLANATION),h("p",null,GRAPH_USAGE_HINT),preview&&!notice?h("p",null,"\u5F53\u524D\u6709 "+preview.pending+" \u6761\u5F85\u5904\u7406\u4E8B\u4EF6\uFF0C\u7EA6 "+preview.batches+" \u4E2A\u6279\u6B21\u3002\u786E\u8BA4\u540E\u4EC5\u8865\u5EFA\u8FD9\u4EFD\u6E05\u5355\uFF0C\u6CBF\u7528\u73B0\u6709\u79DF\u7EA6\u3001\u5E76\u53D1\u548C\u91CD\u8BD5\u9650\u989D\uFF1B\u53EF\u968F\u65F6\u6682\u505C\u3002"):null,notice&&!preview?h("button",{type:"button",className:"sg-graph-no-reminder",disabled:busy,onClick:()=>{control("notice")}},"\u6682\u65F6\u5173\u95ED"):!notice&&preview?h(React.Fragment,null,h("button",{type:"button",disabled:busy,onClick:()=>setPreview(null)},"\u53D6\u6D88"),h("button",{type:"button",disabled:busy,onClick:()=>{control("enable",preview.token)}},"\u786E\u8BA4\u5F00\u542F\u5E76\u5206\u6279\u5904\u7406")):null,!notice&&!preview?h("button",{type:"button",className:"sg-graph-no-reminder",disabled:busy,onClick:()=>{control("notice")}},"\u6682\u65F6\u5173\u95ED"):null)):null))}function GraphSettingsPanel({state={},refresh}){return h(GraphControlPanel,{state,refresh})}function DailyNotesSettings({usePluginSettings,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[saving,setSaving]=React.useState(!1),[error3,setError]=React.useState(""),localTimeZone=Intl.DateTimeFormat().resolvedOptions().timeZone,timeZone=settings?.value?.dailyNotesTimeZone||"",enabled=settings?.value?.dailyNotesEnabled!==!1,injectionDays=settings?.value?.dailyNotesInjectionDays??3,zones=[...new Set(["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Asia/Kolkata","Europe/London","Europe/Berlin","America/New_York","America/Los_Angeles","Australia/Sydney","UTC",timeZone].filter(Boolean))],save=async(setter,value)=>{setSaving(!0),setError("");try{(!setter||!await setter(value))&&setError("\u672A\u80FD\u4FDD\u5B58\u7B14\u8BB0\u8BBE\u7F6E\uFF0C\u8BF7\u91CD\u8BD5\u3002")}catch(reason){setError("\u4FDD\u5B58\u5931\u8D25\uFF1A"+String(reason.message||reason))}finally{setSaving(!1)}},disabled=settings?.writable!==!0||saving;return h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u77ED\u671F\u8BB0\u5FC6"),h("span",{className:"sg-display-setting-description"},"\u6BCF\u5929\u4E00\u4EFD\u5DE5\u4F5C\u7B14\u8BB0\u3002\u5173\u95ED\u540E\u4E0D\u518D\u5199\u5165\u548C\u6CE8\u5165\uFF0C\u5DF2\u6709\u7B14\u8BB0\u4FDD\u7559\u3002")),h("button",{type:"button",className:"sg-setting-switch",role:"switch","aria-label":"\u77ED\u671F\u8BB0\u5FC6","aria-checked":enabled,disabled:disabled||!setDailyEnabled,onClick:()=>{save(setDailyEnabled,!enabled)}})),h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570"),h("span",{className:"sg-display-setting-description"},"\u53D6\u6700\u8FD1\u6709\u7B14\u8BB0\u7684\u65E5\u671F\uFF0C\u9ED8\u8BA4 3 \u5929\u3002\u4FEE\u6539\u540E\u7528\u4E8E\u65B0\u4F1A\u8BDD\uFF1B\u5185\u5BB9\u4ECD\u53D7\u957F\u5EA6\u4E0A\u9650\u7EA6\u675F\u3002")),h("select",{className:"sg-effort-select","aria-label":"\u5E26\u5165\u65B0\u4F1A\u8BDD\u7684\u5929\u6570",value:injectionDays,disabled:disabled||!setDailyInjectionDays,onChange:event3=>{save(setDailyInjectionDays,Number(event3.target.value))}},Array.from({length:30},(_,i2)=>h("option",{key:i2+1,value:i2+1},i2+1+" \u5929")))),h("div",{className:"sg-stage"},h("span",null,"\u7B14\u8BB0\u65F6\u533A"),h("select",{className:"sg-effort-select",style:{maxWidth:"100%",minWidth:0},"aria-label":"\u7B14\u8BB0\u65F6\u533A",value:timeZone,disabled:disabled||!setDailyTimeZone,onChange:event3=>{save(setDailyTimeZone,event3.target.value)}},h("option",{value:""},"\u8DDF\u968F\u672C\u673A\uFF08"+localTimeZone+"\uFF09"),zones.map(zone=>h("option",{key:zone,value:zone},zone)))),error3?h("p",{className:"sg-storage-feedback failed",role:"alert"},error3):null)}function ProfileLimitSettings(){let[profile,setProfile]=React.useState(null),[loading,setLoading]=React.useState(!0),[loadError,setLoadError]=React.useState(""),[editing,setEditing]=React.useState(!1),[draft,setDraft]=React.useState(""),[saving,setSaving]=React.useState(!1),[error3,setError]=React.useState(""),total=profileTotalLength(profile),limit2=profileTotalLimit(profile);React.useEffect(()=>{let controller=new AbortController;return api2("profile",{},{method:"GET",signal:controller.signal}).then(value=>{controller.signal.aborted||setProfile(value),setLoadError("")}).catch(reason=>{controller.signal.aborted||setLoadError("\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u753B\u50CF\u7528\u91CF\uFF1A"+String(reason?.message||reason))}).finally(()=>{controller.signal.aborted||setLoading(!1)}),()=>controller.abort()},[]);let begin=()=>{loading||loadError||(setDraft(String(limit2)),setError(""),setEditing(!0))},cancel=()=>{saving||(setEditing(!1),setError(""))},save=async()=>{if(saving)return;let next2=Number(draft);if(!Number.isSafeInteger(next2)||next2<PROFILE_LIMIT_MIN||next2>PROFILE_LIMIT_MAX){setError("\u8BF7\u8F93\u5165 "+formatCount(PROFILE_LIMIT_MIN)+" \u5230 "+formatCount(PROFILE_LIMIT_MAX)+" \u4E4B\u95F4\u7684\u6574\u6570\u3002");return}if(next2<total){setError("\u4E0A\u9650\u4E0D\u80FD\u4F4E\u4E8E\u5F53\u524D\u5DF2\u7528\u7684 "+formatCount(total)+" \u5B57\u3002");return}if(next2===limit2){setEditing(!1);return}setSaving(!0),setError("");try{let result=await api2("settings",null,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({profileMaxLength:next2})}),saved=Number(result?.profileMaxLength);if(!Number.isSafeInteger(saved)||saved!==next2)throw new Error("\u4E0A\u9650\u4FDD\u5B58\u7ED3\u679C\u4E0D\u5B8C\u6574");setProfile(current=>current&&{...current,_limits:{...current._limits||{},totalMaxLength:next2}}),setEditing(!1)}catch(reason){setError("\u4E0A\u9650\u672A\u4FDD\u5B58\uFF1A"+String(reason?.message||reason))}finally{setSaving(!1)}};return h("div",{className:"sg-settings-panel sg-profile-limit","data-testid":"stratagate-profile-limit-settings"},h("div",{className:"sg-display-setting"},h("span",{className:"sg-display-setting-copy"},h("span",{className:"sg-display-setting-title"},"\u5E38\u9A7B\u753B\u50CF\u5B57\u6570\u4E0A\u9650"),h("span",{className:"sg-display-setting-description"},"\u9650\u5236\u6BCF\u8F6E\u5E26\u5165\u7684\u5E38\u9A7B\u753B\u50CF\u603B\u91CF\uFF0C\u4E0D\u80FD\u4F4E\u4E8E\u5F53\u524D\u5DF2\u5199\u5185\u5BB9\u3002")),h("span",{className:"sg-profile-limit-control"},loading?h("span",{className:"sg-setting-note"},"\u8BFB\u53D6\u4E2D\u2026"):h(React.Fragment,null,loadError?null:h("span",{className:"sg-profile-limit-value","aria-label":"\u5E38\u9A7B\u753B\u50CF\u5DF2\u7528 "+total+" \u5B57\uFF0C\u4E0A\u9650 "+formatCount(limit2)+" \u5B57"},formatCount(total)+" / "+formatCount(limit2)+" \u5B57"),!loadError&&!editing?h("button",{type:"button",className:"sg-cap-limit",onClick:begin},"\u8C03\u6574\u4E0A\u9650"):null))),editing?h("div",{className:"sg-cap-edit sg-profile-limit-edit"},h("input",{type:"number",inputMode:"numeric",min:PROFILE_LIMIT_MIN,max:PROFILE_LIMIT_MAX,step:100,"aria-label":"\u5E38\u9A7B\u753B\u50CF\u5B57\u6570\u4E0A\u9650",value:draft,disabled:saving,autoFocus:!0,onChange:event3=>setDraft(event3.target.value),onKeyDown:event3=>{event3.key==="Enter"?(event3.preventDefault(),save()):event3.key==="Escape"&&(event3.preventDefault(),cancel())}}),h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:cancel},"\u53D6\u6D88"),h("button",{type:"button",className:"sg-save-button",disabled:saving,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):null,loadError?h("p",{className:"sg-storage-feedback failed",role:"alert"},loadError):null,error3?h("p",{className:"sg-cap-error",role:"alert"},error3):null)}function MemoryModelSettings({usePluginSettings,setMemoryModel}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[catalog,setCatalog]=React.useState(null),[draft,setDraft]=React.useState(null),customDraft=React.useRef(null),[models,setModels]=React.useState([]),[loading,setLoading]=React.useState(!1),[catalogError,setCatalogError]=React.useState(""),[modelsError,setModelsError]=React.useState(""),[feedback,setFeedback]=React.useState({kind:"",text:""}),[saving,setSaving]=React.useState(!1),[revision,setRevision]=React.useState(0);React.useEffect(()=>{if(feedback.kind!=="done")return;let timer=window.setTimeout(()=>setFeedback({kind:"",text:""}),4500);return()=>window.clearTimeout(timer)},[feedback]);let saved=settings?.value?.memoryModel||catalog?.selection||{mode:"auto"},value=draft||saved,provider=value.mode==="custom"&&value.provider||"";React.useEffect(()=>{let active=!0;return settings?.value?.memoryModel?.mode==="auto"&&value.mode==="auto"?(setCatalog(null),setCatalogError(""),()=>{active=!1}):(setCatalogError(""),api2("models").then(result=>{active&&setCatalog(result)}).catch(reason=>{active&&setCatalogError(String(reason?.message||reason))}),()=>{active=!1})},[revision,settings?.value?.memoryModel?.mode,value.mode]),React.useEffect(()=>{let active=!0;return setModels([]),setModelsError(""),provider?(setLoading(!0),api2("models",{provider}).then(result=>{active&&setModels(result.models)}).catch(reason=>{active&&setModelsError(String(reason?.message||reason))}).finally(()=>{active&&setLoading(!1)}),()=>{active=!1}):(setLoading(!1),()=>{active=!1})},[provider,revision]);let providers=catalog?.providers||[],custom=value.mode==="custom";React.useEffect(()=>{if(!draft||!custom||provider||!providers[0])return;let next2={...value,provider:providers[0].id};customDraft.current=next2,setDraft(next2)},[providers,custom,provider,draft,value]);let valid2=!custom||providers.some(item=>item.id===provider)&&!!value.model?.trim(),changed=value.mode!==saved.mode||custom&&(value.provider!==saved.provider||value.model!==saved.model),editingDisabled=settings?.writable!==!0||!setMemoryModel||saving,disabled=editingDisabled,edit=next2=>{next2.mode==="custom"&&(customDraft.current=next2),setDraft(next2),setFeedback({kind:"",text:""})},save=async()=>{if(!(disabled||!valid2||!changed)){setSaving(!0),setFeedback({kind:"",text:""});try{if(!await setMemoryModel(value))throw new Error("\u5BBF\u4E3B\u672A\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002");setCatalog(current=>({...current,selection:value})),setDraft(null),setFeedback({kind:"done",text:"\u5DF2\u4FDD\u5B58\uFF0C\u5BF9\u540E\u7EED\u8BB0\u5FC6\u5904\u7406\u8C03\u7528\u751F\u6548\u3002\u6B63\u5728\u8FD0\u884C\u7684\u8C03\u7528\u7EE7\u7EED\u5B8C\u6210\u3002"})}catch(reason){setFeedback({kind:"failed",text:"\u672A\u80FD\u786E\u8BA4\u4FDD\u5B58\uFF1A"+String(reason?.message||reason)+" \u5F53\u524D\u9009\u62E9\u5DF2\u4FDD\u7559\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{setSaving(!1)}}},savedProvider=providers.find(item=>item.id===saved.provider)?.name||saved.provider,savedModel=saved.provider===provider&&models.find(item=>item.id===saved.model)?.name||saved.model,pendingProvider=providers.find(item=>item.id===value.provider)?.name||value.provider,pendingModel=value.provider===provider&&models.find(item=>item.id===value.model)?.name||value.model,savedSummary=saved.mode==="custom"?savedProvider+" / "+savedModel:"\u8DDF\u968F\u804A\u5929\u6A21\u578B",pendingSummary=value.mode==="custom"?pendingProvider+" / "+pendingModel:"\u8DDF\u968F\u804A\u5929\u6A21\u578B";return h("div",{className:"sg-settings-panel sg-model-settings"},h("h4",{className:"sg-model-heading"},"\u8BB0\u5FC6\u5904\u7406\u6A21\u578B"),h("div",{className:"sg-model-modes",role:"radiogroup","aria-label":"\u8BB0\u5FC6\u5904\u7406\u6A21\u578B"},[{mode:"auto",title:"\u8DDF\u968F\u804A\u5929\u6A21\u578B"},{mode:"custom",title:"\u5355\u72EC\u6307\u5B9A\u6A21\u578B"}].map(item=>h("label",{key:item.mode,className:"sg-model-mode"+(value.mode===item.mode?" selected":"")},h("input",{type:"radio",name:"sg-memory-model-mode",value:item.mode,checked:value.mode===item.mode,disabled:editingDisabled,onChange:()=>edit(item.mode==="auto"?{mode:"auto"}:customDraft.current||(saved.mode==="custom"?saved:{mode:"custom",provider:providers[0]?.id||"",model:""}))}),h("span",{className:"sg-model-mode-copy"},h("span",{className:"sg-model-mode-title"},item.title))))),custom?h(React.Fragment,null,h("div",{className:"sg-model-fields"},h("label",{className:"sg-model-field"},"\u670D\u52A1\u5546",h("select",{className:"sg-effort-select","aria-label":"\u8BB0\u5FC6\u5904\u7406\u670D\u52A1\u5546",value:provider,disabled:editingDisabled||!catalog,onChange:event3=>edit({mode:"custom",provider:event3.target.value,model:""})},h("option",{value:""},"\u8BF7\u9009\u62E9\u670D\u52A1\u5546"),provider&&!providers.some(item=>item.id===provider)?h("option",{value:provider},provider+"\uFF08\u5F53\u524D\u4E0D\u53EF\u7528\uFF09"):null,providers.map(item=>h("option",{key:item.id,value:item.id},item.name||item.id)))),h("label",{className:"sg-model-field"},"\u6A21\u578B",h("select",{className:"sg-effort-select","aria-label":"\u8BB0\u5FC6\u5904\u7406\u5177\u4F53\u6A21\u578B",value:value.model||"",disabled:editingDisabled||!catalog||!provider||loading||!!modelsError,onChange:event3=>edit({...value,model:event3.target.value})},h("option",{value:""},loading?"\u6B63\u5728\u8BFB\u53D6\u6A21\u578B\u2026":"\u8BF7\u9009\u62E9\u6A21\u578B"),value.model&&!models.some(item=>item.id===value.model)?h("option",{value:value.model},value.model+"\uFF08\u672A\u5728\u5217\u8868\u4E2D\uFF09"):null,models.map(item=>h("option",{key:item.id,value:item.id},item.name||item.id))))),null):null,custom&&!catalog&&!catalogError?h("p",{className:"sg-status-feedback",role:"status"},"\u6B63\u5728\u8BFB\u53D6\u670D\u52A1\u5546\u2026"):null,settings&&settings.writable!==!0?h("p",{className:"sg-status-feedback"},"\u5F53\u524D\u914D\u7F6E\u4E3A\u53EA\u8BFB\u3002"):null,catalogError||modelsError?h("p",{className:"sg-status-feedback failed",role:"alert"},"\u8BFB\u53D6\u5931\u8D25\uFF1A"+(catalogError||modelsError)," ",h("button",{type:"button",className:"sg-quiet-button",disabled:saving,onClick:()=>setRevision(current=>current+1)},"\u91CD\u65B0\u8BFB\u53D6")):null,h("div",{className:"sg-model-save-row"},h("div",{className:"sg-model-saved"},h("span",{className:"sg-model-active-label"},"\u5F53\u524D\u751F\u6548"),h("strong",null,catalog||settings?.value?.memoryModel?savedSummary:"\u8DDF\u968F\u804A\u5929\u6A21\u578B"),changed?h("span",{className:"sg-model-pending"},"\u2192 "+pendingSummary):null),changed?h("button",{type:"button",className:"sg-save-button",disabled:editingDisabled||!valid2||custom&&!catalog,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58"):h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"})),feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null)}function RetrievalModelSettings({kind,settings,writable,onSaved}){let embedding=kind==="embedding",title=embedding?"\u5411\u91CF\u68C0\u7D22":"\u7ED3\u679C\u7CBE\u6392\uFF08Rerank\uFF09",prefix=embedding?"embedding":"rerank",urlKey=prefix+"Url",secretKey=prefix+"Key",modelKey=prefix+"Model",[saved,setSaved]=React.useState(settings||null),[draft,setDraft]=React.useState({}),[models,setModels]=React.useState([]),[listing,setListing]=React.useState(!1),[listFeedback,setListFeedback]=React.useState(""),[saving,setSaving]=React.useState(!1),[reading,setReading]=React.useState(!1),[feedback,setFeedback]=React.useState({kind:"",text:""}),lookup2=React.useRef(0);React.useEffect(()=>{settings&&setSaved(settings)},[settings]),React.useEffect(()=>()=>{lookup2.current+=1},[]),React.useEffect(()=>{if(feedback.kind!=="done")return;let timer=window.setTimeout(()=>setFeedback({kind:"",text:""}),4500);return()=>window.clearTimeout(timer)},[feedback]);let value=key=>draft[key]??saved?.[key]??"",url=String(value(urlKey)).trim().replace(/\/+$/,""),keyEdited=Object.hasOwn(draft,secretKey),keyConfigured=keyEdited?!!draft[secretKey].trim():saved?.[prefix+"KeyConfigured"]===!0,urlValid=!url;try{urlValid=["http:","https:"].includes(new URL(url).protocol)}catch{}let numericValid=!embedding||["vectorWeight","embeddingMinScore"].every(key=>{let raw=draft[key]??saved?.[key]??(key==="vectorWeight"?1:.3);return String(raw).trim()!==""&&Number.isFinite(Number(raw))&&Number(raw)>=0&&Number(raw)<=(key==="vectorWeight"?5:1)}),changed=Object.keys(draft).some(key=>key===secretKey||String(draft[key])!==String(saved?.[key]??"")),disabled=!saved||writable!==!0||saving||reading,edit=(key,next2)=>{setDraft(current=>({...current,[key]:next2})),setFeedback({kind:"",text:""}),(key===urlKey||key===secretKey)&&(lookup2.current+=1,setModels([]),setListing(!1),setListFeedback(""))},listModels=async()=>{if(disabled||listing||!url||!urlValid||!keyConfigured)return;let request=++lookup2.current;setListing(!0),setModels([]),setListFeedback("");try{let result=await api2("models",null,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind,url,...keyEdited?{key:draft[secretKey].trim()}:{}})});if(request!==lookup2.current)return;let ids=Array.isArray(result.models)?result.models.filter(id2=>typeof id2=="string"&&id2):[];setModels(ids),setListFeedback(ids.length?"\u5DF2\u8BFB\u53D6\u6A21\u578B\u5217\u8868\u3002\u8BF7\u9009\u62E9\u5BF9\u5E94\u7C7B\u578B\u7684\u6A21\u578B\uFF0C\u4E5F\u53EF\u624B\u52A8\u586B\u5199\u3002":"\u672A\u80FD\u8BFB\u53D6\u6A21\u578B\u5217\u8868\uFF0C\u53EF\u91CD\u8BD5\u6216\u624B\u52A8\u586B\u5199\u6A21\u578B\u540D\u79F0\u3002")}catch{request===lookup2.current&&setListFeedback("\u672A\u80FD\u8BFB\u53D6\u6A21\u578B\u5217\u8868\uFF0C\u53EF\u91CD\u8BD5\u6216\u624B\u52A8\u586B\u5199\u6A21\u578B\u540D\u79F0\u3002")}finally{request===lookup2.current&&setListing(!1)}},save=async()=>{if(disabled||!changed||!urlValid||!numericValid)return;let patch={};for(let key of Object.keys(draft))patch[key]=key==="vectorWeight"||key==="embeddingMinScore"?Number(draft[key]):key===urlKey?url:draft[key].trim();setSaving(!0),setFeedback({kind:"",text:""}),lookup2.current+=1,setListing(!1);try{let result=await api2("settings",null,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(patch)});if(!result.vectorSettings||typeof result.vectorSettings[prefix+"Ready"]!="boolean")throw new Error("Missing saved settings");setSaved(result.vectorSettings),setDraft({}),onSaved?.(result.vectorSettings),setFeedback({kind:"done",text:"\u914D\u7F6E\u5DF2\u4FDD\u5B58\u3002"})}catch{setFeedback({kind:"failed",text:"\u672A\u80FD\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8F93\u5165\u5DF2\u4FDD\u7559\u3002\u8BF7\u91CD\u65B0\u8BFB\u53D6\u914D\u7F6E\u540E\u6838\u5BF9\uFF0C\u6216\u91CD\u8BD5\u4FDD\u5B58\u3002"})}finally{setSaving(!1)}},readSaved=async()=>{if(!(saving||reading)){setReading(!0);try{let result=await api2("overview");if(!result.vectorSettings||typeof result.vectorSettings[prefix+"Ready"]!="boolean")throw new Error("Missing saved settings");setSaved(result.vectorSettings),onSaved?.(result.vectorSettings),setFeedback({kind:"done",text:"\u5DF2\u91CD\u65B0\u8BFB\u53D6\u4FDD\u5B58\u7684\u914D\u7F6E\uFF1B\u672A\u4FDD\u5B58\u8F93\u5165\u5DF2\u4FDD\u7559\u3002"})}catch{setFeedback({kind:"failed",text:"\u672A\u80FD\u8BFB\u53D6\u4FDD\u5B58\u7684\u914D\u7F6E\uFF0C\u8F93\u5165\u5DF2\u4FDD\u7559\uFF0C\u8BF7\u91CD\u8BD5\u3002"})}finally{setReading(!1)}}},ready4=saved?.[prefix+"Ready"]===!0,active=ready4&&(!embedding||Number(saved.vectorWeight)>0),status=saved?active?"\u5DF2\u914D\u7F6E \xB7 "+saved[modelKey]:ready4&&embedding?"\u5DF2\u505C\u7528\uFF08\u5411\u91CF\u68C0\u7D22\u5360\u6BD4\u4E3A 0\uFF09":saved[urlKey]?"\u914D\u7F6E\u672A\u5B8C\u6574\uFF0C\u6682\u672A\u542F\u7528":"\u672A\u542F\u7528":"\u5C1A\u672A\u8BFB\u53D6\u914D\u7F6E";return h("div",{className:"sg-settings-panel sg-model-settings sg-retrieval-settings","data-kind":kind},h("div",{className:"sg-model-heading-row"},h("h4",{className:"sg-model-heading"},title),h(InfoPopover,{label:title+"\u8BF4\u660E"},h("p",null,"\u586B\u5199\u5730\u5740\u3001\u5BC6\u94A5\u548C\u6A21\u578B\u540E\u542F\u7528\uFF1B\u6E05\u7A7A\u5730\u5740\u5E76\u4FDD\u5B58\u5373\u53EF\u505C\u7528\u3002\u542F\u7528\u4F1A\u4EA7\u751F\u670D\u52A1\u5546 API \u8D39\u7528\u3002"),h("p",null,embedding?"\u542F\u7528\u540E\uFF0C\u4E8B\u4EF6\u6807\u9898\u548C\u6458\u8981\u4F1A\u53D1\u9001\u7ED9\u5411\u91CF\u670D\u52A1\u5546\u3002":"\u542F\u7528\u540E\uFF0C\u68C0\u7D22\u95EE\u9898\u548C\u5019\u9009\u4E8B\u4EF6\u5185\u5BB9\u4F1A\u53D1\u9001\u7ED9\u7CBE\u6392\u670D\u52A1\u5546\u3002"),h("p",null,"\u586B\u5199 OpenAI \u517C\u5BB9\u63A5\u53E3\u57FA\u7840\u5730\u5740\uFF0C\u4E0D\u542B "+(embedding?"/embeddings":"/rerank")+"\u3002"),h("p",null,"\u4FDD\u5B58\u4E0D\u9A8C\u8BC1\u8FDE\u63A5\u3002"+(embedding?"\u5DF2\u6709\u4E8B\u4EF6\u7684\u5411\u91CF\u4F1A\u5728\u540E\u7EED\u68C0\u7D22\u65F6\u8865\u9F50\u3002":"")))),h("div",{className:"sg-retrieval-fields"},h("label",{className:"sg-model-field"},"API \u5730\u5740",h("input",{type:"url",value:value(urlKey),disabled,placeholder:"https://\u4F60\u7684\u670D\u52A1\u5730\u5740/v1","aria-label":title+" API \u5730\u5740",spellCheck:!1,onChange:event3=>edit(urlKey,event3.target.value)})),urlValid?null:h("p",{className:"sg-status-feedback failed",role:"alert"},"\u8BF7\u586B\u5199\u4EE5 http:// \u6216 https:// \u5F00\u5934\u7684\u6709\u6548\u5730\u5740\u3002"),h("label",{className:"sg-model-field"},"API Key",h("input",{type:"password",value:draft[secretKey]??"",disabled,placeholder:keyEdited&&!draft[secretKey]?"\u4FDD\u5B58\u540E\u6E05\u9664\u5BC6\u94A5":saved?.[prefix+"KeyConfigured"]?"\u5DF2\u4FDD\u5B58\u5BC6\u94A5\uFF0C\u672A\u4FEE\u6539\u65F6\u4FDD\u7559":"\u586B\u5199 API Key","aria-label":title+" API Key",autoComplete:"new-password",spellCheck:!1,onChange:event3=>edit(secretKey,event3.target.value)})),h("div",{className:"sg-retrieval-actions"},saved?.[prefix+"KeyConfigured"]?h("button",{type:"button",className:"sg-quiet-button",disabled,onClick:()=>edit(secretKey,"")},"\u6E05\u9664\u5DF2\u4FDD\u5B58\u5BC6\u94A5"):null,keyEdited?h("button",{type:"button",className:"sg-quiet-button",disabled,onClick:()=>{setDraft(current=>{let next2={...current};return delete next2[secretKey],next2}),lookup2.current+=1,setModels([]),setListing(!1),setListFeedback(""),setFeedback({kind:"",text:""})}},"\u64A4\u9500\u5BC6\u94A5\u4FEE\u6539"):null),keyEdited&&!draft[secretKey].trim()?h("p",{className:"sg-setting-note"},"\u4FDD\u5B58\u540E\u5C06\u6E05\u9664\u5BC6\u94A5\u5E76\u505C\u7528\u6B64\u529F\u80FD\u3002"):null,h("label",{className:"sg-model-field"},"\u6A21\u578B\u540D\u79F0",h("input",{type:"text",value:value(modelKey),disabled,list:"sg-"+kind+"-models",placeholder:"\u586B\u5199\u6A21\u578B\u540D\u79F0\u6216\u4ECE\u5217\u8868\u9009\u62E9","aria-label":title+"\u6A21\u578B\u540D\u79F0",autoComplete:"off",spellCheck:!1,onChange:event3=>edit(modelKey,event3.target.value)})),h("datalist",{id:"sg-"+kind+"-models"},models.map(id2=>h("option",{key:id2,value:id2}))),h("div",{className:"sg-retrieval-actions"},h("button",{type:"button",className:"sg-storage-button",disabled:disabled||listing||!url||!urlValid||!keyConfigured,onClick:()=>{listModels()}},listing?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u8BFB\u53D6\u6A21\u578B\u5217\u8868")),listFeedback?h("p",{className:"sg-status-feedback",role:"status"},listFeedback):null),embedding?h("details",{className:"sg-retrieval-tuning"},h("summary",null,"\u68C0\u7D22\u53C2\u6570"),h("div",{className:"sg-model-fields"},h("label",{className:"sg-model-field"},"\u5411\u91CF\u68C0\u7D22\u5360\u6BD4",h("input",{type:"number",min:0,max:5,step:.1,value:draft.vectorWeight??saved?.vectorWeight??1,disabled,"aria-label":"\u5411\u91CF\u68C0\u7D22\u5360\u6BD4",onChange:event3=>edit("vectorWeight",event3.target.value)})),h("label",{className:"sg-model-field"},"\u6700\u4F4E\u76F8\u4F3C\u5EA6",h("input",{type:"number",min:0,max:1,step:.05,value:draft.embeddingMinScore??saved?.embeddingMinScore??.3,disabled,"aria-label":"\u6700\u4F4E\u76F8\u4F3C\u5EA6",onChange:event3=>edit("embeddingMinScore",event3.target.value)}))),h("p",{className:"sg-setting-note"},"\u5360\u6BD4 1 \u4E0E\u5173\u952E\u8BCD\u68C0\u7D22\u5E73\u6743\uFF1B0 \u505C\u7528\u3002\u6700\u4F4E\u76F8\u4F3C\u5EA6\u8303\u56F4 0\u20131\u3002"),numericValid?null:h("p",{className:"sg-status-feedback failed",role:"alert"},"\u5360\u6BD4\u9700\u4E3A 0\u20135 \u7684\u6570\u5B57\uFF0C\u6700\u4F4E\u76F8\u4F3C\u5EA6\u9700\u4E3A 0\u20131 \u7684\u6570\u5B57\u3002")):null,h("div",{className:"sg-model-save-row"},h("div",{className:"sg-model-saved"},h("span",{className:"sg-model-active-label"},"\u5F53\u524D\u751F\u6548"),h("strong",null,status)),changed?h("button",{type:"button",className:"sg-save-button",disabled:disabled||!urlValid||!numericValid,onClick:()=>{save()}},saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58"):saved?h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"}):null),!saved||writable!==!0?h("p",{className:"sg-status-feedback"},saved?"\u5F53\u524D\u68C0\u7D22\u914D\u7F6E\u4E3A\u53EA\u8BFB\u3002":"\u68C0\u7D22\u914D\u7F6E\u5C1A\u672A\u8BFB\u53D6\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u3002"):null,feedback.text?h("p",{className:"sg-status-feedback "+feedback.kind,role:feedback.kind==="failed"?"alert":"status"},feedback.text):null,!saved||feedback.kind==="failed"?h("button",{type:"button",className:"sg-quiet-button",disabled:saving||reading,onClick:()=>{readSaved()}},reading?"\u6B63\u5728\u8BFB\u53D6\u2026":"\u91CD\u65B0\u8BFB\u53D6\u914D\u7F6E"):null)}function SettingsPage({selected,graphSettings,vectorSettings,retrievalSettingsWritable,onRetrievalSettingsSaved,refresh,namespace,dataDirectory,onBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays,onDirectoryChanged,onOpenDreamingSession}){let[turnSize,setTurnSize]=React.useState(String(selected.blockTurnSize??6)),[lambda,setLambda]=React.useState(String(selected.blockDecayLambda??.3)),[agentWeight,setAgentWeight]=React.useState(String(selected.agentMemoryRetrievalWeight??1)),[directoryOpening,setDirectoryOpening]=React.useState(!1),[directoryFeedback,setDirectoryFeedback]=React.useState({kind:"",text:""});React.useEffect(()=>{setTurnSize(String(selected.blockTurnSize??6)),setLambda(String(selected.blockDecayLambda??.3)),setAgentWeight(String(selected.agentMemoryRetrievalWeight??1))},[selected.blockTurnSize,selected.blockDecayLambda,selected.agentMemoryRetrievalWeight]);let turnSizeValue=Number(turnSize),lambdaValue=Number(lambda),agentWeightValue=Number(agentWeight),changed=Number.isSafeInteger(turnSizeValue)&&turnSizeValue>=1&&lambda!==""&&Number.isFinite(lambdaValue)&&lambdaValue>=0&&agentWeight!==""&&Number.isFinite(agentWeightValue)&&agentWeightValue>=0&&agentWeightValue<=5&&(turnSizeValue!==selected.blockTurnSize||lambdaValue!==selected.blockDecayLambda||agentWeightValue!==(selected.agentMemoryRetrievalWeight??1)),suggestedLambda=Math.round((selected.blockDecayLambda??.3)*turnSizeValue/(selected.blockTurnSize||6)/.05)*.05,showSuggestion=Number.isSafeInteger(turnSizeValue)&&turnSizeValue>=1&&turnSizeValue!==selected.blockTurnSize,pluginSettings=usePluginSettings?usePluginSettings(state=>state):null,effortMode=pluginSettings?.value?.structuredReasoningEffort||"auto",effortOverridden=pluginSettings?.user?.structuredReasoningEffort!==void 0,settingsWritable=pluginSettings?.writable===!0,workspaceRows=[["Schema","v"+selected.schemaVersion],["\u5DE5\u4F5C\u533A",selected.workspaceName||"\u5F53\u524D\u5DE5\u4F5C\u533A"],["\u5185\u90E8\u7A7A\u95F4 ID",namespace],["\u5DF2\u5904\u7406\u8F6E\u6B21",selected.currentTurn]],runtimeDiagnostics=[["duplicates","\u21C4","\u91CD\u590D\u8BB0\u5FC6\u6574\u7406","\u67E5\u770B\u4FDD\u7559\u539F\u56E0\u3001\u5408\u5E76\u5019\u9009\u4E0E\u91CD\u65B0\u626B\u63CF"],["system","\u2713","\u7CFB\u7EDF\u72B6\u6001","\u5904\u7406\u6982\u89C8\u4E0E\u6700\u8FD1\u6574\u7406\u65F6\u95F4"],["audit","\u2197","\u4F7F\u7528\u8BB0\u5F55","\u957F\u671F\u8BB0\u5FC6\u4F55\u65F6\u88AB\u4F7F\u7528"],["status","\u21BB","\u540E\u53F0\u4EFB\u52A1","\u5904\u7406\u8FDB\u5EA6\u3001\u5931\u8D25\u4EFB\u52A1\u4E0E\u91CD\u8BD5"]],openDirectory=()=>{!dataDirectory||directoryOpening||(setDirectoryOpening(!0),setDirectoryFeedback({kind:"",text:""}),api2("storage/open-directory",{},{method:"POST"}).then(()=>setDirectoryFeedback({kind:"done",text:"\u5DF2\u5728\u6587\u4EF6\u7BA1\u7406\u5668\u4E2D\u6253\u5F00"})).catch(reason=>setDirectoryFeedback({kind:"failed",text:"\u6253\u5F00\u5931\u8D25\uFF1A"+String(reason?.message||reason)})).finally(()=>setDirectoryOpening(!1)))},copyDirectory=()=>{if(dataDirectory){if(setDirectoryFeedback({kind:"",text:""}),!navigator?.clipboard?.writeText){setDirectoryFeedback({kind:"failed",text:"\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u81EA\u52A8\u590D\u5236"});return}navigator.clipboard.writeText(dataDirectory).then(()=>setDirectoryFeedback({kind:"done",text:"\u8DEF\u5F84\u5DF2\u590D\u5236"})).catch(reason=>setDirectoryFeedback({kind:"failed",text:"\u590D\u5236\u5931\u8D25\uFF1A"+String(reason?.message||reason)}))}},menu=items=>h("div",{className:"sg-menu sg-settings-menu"},items.map(([id2,icon,title,subtitle])=>h("button",{key:id2,type:"button",className:"sg-menu-row",onClick:()=>setView({name:id2,back:{name:"settings"}})},h("span",{className:"sg-menu-icon","aria-hidden":"true"},icon),h("span",null,h("span",{className:"sg-menu-title"},title),h("br"),h("span",{className:"sg-menu-subtitle"},subtitle)),h("span",{className:"sg-chevron"},"\u203A")))),stepper=({value,onChange,min:min4,max:max5,step:step3,label,allowFloat})=>{let current=Number(value),delta=allowFloat?step3:1,bump=direction=>{if(!Number.isFinite(current))return;let next2=Math.min(max5,Math.max(min4,Number((current+direction*delta).toFixed(2))));onChange(String(next2))};return h("span",{className:"sg-stp sg-stp-wide"},h("button",{type:"button","aria-label":"\u51CF\u5C11"+label,disabled:!Number.isFinite(current)||current<=min4,onClick:()=>bump(-1)},"\u2212"),h("input",{className:"sg-number-input",type:"number",min:String(min4),max:max5===void 0?void 0:String(max5),step:String(step3),value,onChange:event3=>onChange(event3.target.value),"aria-label":label}),h("button",{type:"button","aria-label":"\u589E\u52A0"+label,disabled:!Number.isFinite(current)||max5===void 0||current>=max5,onClick:()=>bump(1)},"+"))},blockSettings=h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-stage"},h("span",null,"\u6BCF\u4E2A Block \u7684\u5BF9\u8BDD\u8F6E\u6570"),h("span",{className:"sg-lambda-control"},stepper({value:turnSize,onChange:setTurnSize,min:1,max:30,step:1,label:"\u6BCF\u4E2A Block \u7684\u5BF9\u8BDD\u8F6E\u6570"}),h("span",{className:"sg-stage-value waiting"},"\u8F6E"))),h("p",{className:"sg-setting-note"},"1 \u8F6E\u7B49\u4E8E\u4E00\u6B21\u63D0\u95EE\u548C\u5B8C\u6574\u56DE\u590D\uFF0C\u53EA\u5F71\u54CD\u540E\u7EED\u672A\u5C01\u5B58\u5185\u5BB9\u3002"),h("div",{className:"sg-stage"},h("span",null,"Block \u8870\u51CF\u7CFB\u6570 \u03BB"),h("span",{className:"sg-lambda-control"},stepper({value:lambda,onChange:setLambda,min:0,max:.4,step:.05,label:"Block \u8870\u51CF\u7CFB\u6570 \u03BB",allowFloat:!0}))),h("p",{className:"sg-setting-note"},"\u8D8A\u5C0F\u9057\u5FD8\u8D8A\u6162\uFF0Ctoken \u6D88\u8017\u8D8A\u591A\u3002"),showSuggestion?h("div",{className:"sg-setting-suggestion"},h("span",null,"\u5EFA\u8BAE \u03BB \u8C03\u6574\u4E3A "+suggestedLambda.toFixed(2)+"\u3002"),h("button",{type:"button",className:"sg-quiet-button",onClick:()=>setLambda(String(Number(suggestedLambda.toFixed(2))))},"\u91C7\u7528\u5EFA\u8BAE\u503C")):null,h("div",{className:"sg-stage"},h("span",null,"\u4E3B\u52A8\u8BB0\u5FC6\u68C0\u7D22\u5360\u6BD4"),h("span",{className:"sg-lambda-control"},stepper({value:agentWeight,onChange:setAgentWeight,min:0,max:5,step:.05,label:"\u4E3B\u52A8\u8BB0\u5FC6\u68C0\u7D22\u5360\u6BD4",allowFloat:!0}))),h("p",{className:"sg-setting-note"},"1 \u4E3A\u5E73\u6743\uFF0C0 \u4E0D\u5C55\u793A agent \u8BB0\u5F55\u3002"),changed?h("div",{className:"sg-dirty"},h("span",null,[turnSizeValue!==selected.blockTurnSize,lambdaValue!==selected.blockDecayLambda,agentWeightValue!==(selected.agentMemoryRetrievalWeight??1)].filter(Boolean).length+" \u9879\u672A\u4FDD\u5B58"),h("button",{type:"button",className:"sg-quiet-button",disabled:savingSettings,onClick:()=>{setTurnSize(String(selected.blockTurnSize??6)),setLambda(String(selected.blockDecayLambda??.3)),setAgentWeight(String(selected.agentMemoryRetrievalWeight??1))}},"\u653E\u5F03"),h("button",{type:"button",className:"sg-save-button",disabled:!changed||savingSettings,onClick:()=>{updateSettings({blockTurnSize:turnSizeValue,blockDecayLambda:lambdaValue,agentMemoryRetrievalWeight:agentWeightValue})}},savingSettings?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58")):h("span",{className:"sg-status organized sg-save-state",role:"status",title:"\u5DF2\u4FDD\u5B58","aria-label":"\u5DF2\u4FDD\u5B58"})),effortSettings=h("div",{className:"sg-settings-panel sg-pipeline"},h("div",{className:"sg-stage"},h("span",null,"\u7ED3\u6784\u5316\u63A8\u7406\u6863\u4F4D"),h("span",{className:"sg-lambda-control"},h("select",{className:"sg-effort-select",value:effortMode,disabled:!settingsWritable,onChange:event3=>{setEffort&&setEffort(event3.target.value)},"aria-label":"\u7ED3\u6784\u5316\u63A8\u7406\u6863\u4F4D\u7B56\u7565"},h("option",{value:"auto"},"auto\uFF08\u81EA\u52A8\uFF09"),h("option",{value:"force-off"},"force-off\uFF08\u5F3A\u5236\u5173\u95ED\uFF09")),effortOverridden?h("button",{type:"button",className:"sg-effort-button",onClick:()=>{resetEffort&&resetEffort()}},"\u6062\u590D\u9ED8\u8BA4"):h("span",{className:"sg-stage-value waiting"},"\u9ED8\u8BA4"))),h("p",{className:"sg-setting-note"},"auto \u8DDF\u968F\u6A21\u578B\u80FD\u529B\uFF1Bforce-off \u4F18\u5148\u5173\u95ED\uFF0C\u4E0D\u652F\u6301\u65F6\u81EA\u52A8\u964D\u7EA7\u3002")),workspaceInfo=h("div",{className:"sg-settings-panel sg-pipeline"},workspaceRows.map(([label,value])=>h("div",{key:label,className:"sg-stage"},h("span",null,label),h("span",{className:label==="\u5185\u90E8\u7A7A\u95F4 ID"?"sg-stage-value sg-code":"sg-stage-value"},String(value)))));return h("div",{className:"sg-settings-shell"},h(BackBar,{label:"\u66F4\u591A",onBack}),h("div",{className:"sg-pg-head"},h("h2",null,"\u9AD8\u7EA7\u8BBE\u7F6E")),namespace?h(DreamingPanel,{key:namespace,namespace,active:!0,available:!0,settings:!0,onDirectoryChanged,onOpenDreamingSession}):null,h("section",{className:"sg-settings-group sg-settings-install","aria-labelledby":"sg-memory-settings-title"},h("h3",{id:"sg-memory-settings-title",className:"sg-settings-group-title"},"\u5B89\u88C5\u7EA7\u8BBE\u7F6E"),h("div",{className:"sg-settings-columns"},h("div",{className:"sg-settings-column"},h(GraphSettingsPanel,{state:graphSettings,refresh}),h(ProfileLimitSettings),h(DailyNotesSettings,{usePluginSettings,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}),blockSettings),h("div",{className:"sg-settings-column"},h(RetrievalModelSettings,{kind:"embedding",settings:vectorSettings,writable:retrievalSettingsWritable,onSaved:onRetrievalSettingsSaved}),h(RetrievalModelSettings,{kind:"rerank",settings:vectorSettings,writable:retrievalSettingsWritable,onSaved:onRetrievalSettingsSaved})))),h("section",{className:"sg-settings-group","aria-labelledby":"sg-host-settings-title"},h("h3",{id:"sg-host-settings-title",className:"sg-settings-group-title"},"\u5BBF\u4E3B\u914D\u7F6E"),h("div",{className:"sg-settings-columns"},h("div",{className:"sg-settings-column"},h(MemoryModelSettings,{usePluginSettings,setMemoryModel})),h("div",{className:"sg-settings-column"},effortSettings))),h("section",{className:"sg-settings-group","aria-labelledby":"sg-workspace-settings-title"},h("h3",{id:"sg-workspace-settings-title",className:"sg-settings-group-title"},"\u5DE5\u4F5C\u533A\u4FE1\u606F"),workspaceInfo),h("section",{className:"sg-settings-group","aria-labelledby":"sg-storage-title"},h("h3",{id:"sg-storage-title",className:"sg-settings-group-title"},"\u6570\u636E\u4E0E\u5B58\u50A8"),h("div",{className:"sg-storage-card"},h("span",{className:"sg-storage-label"},"\u6570\u636E\u5B58\u50A8\u4F4D\u7F6E"),h("span",{className:"sg-storage-path",title:dataDirectory||void 0},dataDirectory||"\u5F53\u524D\u4F7F\u7528\u5185\u5B58\u5B58\u50A8\uFF0C\u6CA1\u6709\u672C\u5730\u6570\u636E\u76EE\u5F55"),h("div",{className:"sg-storage-actions"},h("button",{type:"button",className:"sg-storage-button",disabled:!dataDirectory||directoryOpening,onClick:openDirectory},directoryOpening?"\u6B63\u5728\u6253\u5F00\u2026":"\u6253\u5F00\u6587\u4EF6\u5939"),h("button",{type:"button",className:"sg-storage-button",disabled:!dataDirectory,onClick:copyDirectory},"\u590D\u5236\u8DEF\u5F84")),h("p",{className:"sg-storage-feedback "+directoryFeedback.kind,role:directoryFeedback.kind==="failed"?"alert":"status","aria-live":"polite"},directoryFeedback.text)),menu([["raw","{}","\u67E5\u770B\u539F\u59CB\u6570\u636E","Block\u3001Event\u3001Graph \u4E0E\u6A21\u578B\u54CD\u5E94"]])),h("section",{className:"sg-settings-group sg-settings-compact","aria-labelledby":"sg-diagnostics-title"},h("h3",{id:"sg-diagnostics-title",className:"sg-settings-group-title"},"\u8FD0\u884C\u4E0E\u8BCA\u65AD"),menu(runtimeDiagnostics)))}function overviewAbsolute(value){let date=new Date(value);return Number.isNaN(date.getTime())?"\u65F6\u95F4\u672A\u77E5":new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(date)}function overviewRelative(value){let time2=Date.parse(value||"");if(!Number.isFinite(time2))return"\u8FD8\u6CA1\u6709\u66F4\u65B0";let seconds=Math.round((Date.now()-time2)/1e3);if(seconds<60)return"\u521A\u521A";if(seconds<3600)return Math.floor(seconds/60)+" \u5206\u949F\u524D";if(seconds<86400)return Math.floor(seconds/3600)+" \u5C0F\u65F6\u524D";let days=Math.floor(seconds/86400);return days===1?"\u6628\u5929":days<30?days+" \u5929\u524D":overviewAbsolute(value)}function overviewCount(value){return Number(value||0).toLocaleString("en-US")}function OverviewSpeechMark(){return h("svg",{className:"sg-ov-speech",viewBox:"0 0 54 48",fill:"none",stroke:"currentColor",strokeWidth:3,"aria-hidden":"true",focusable:"false"},h("path",{d:"M7 3h40a4 4 0 0 1 4 4v24a4 4 0 0 1-4 4H23L10 45V35H7a4 4 0 0 1-4-4V7a4 4 0 0 1 4-4Z"}),h("path",{d:"M14 15h27M14 23h18"}))}function overviewRuntimeState(selected,loading,error3){if(error3)return{state:"warning",text:"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u6700\u65B0\u72B6\u6001"};if(loading)return{state:"loading",text:"\u6B63\u5728\u8BFB\u53D6\u72B6\u6001"};if(!selected?.memoryOverview||!Number.isSafeInteger(selected.failedJobs)||selected.failedJobs<0||!Number.isSafeInteger(selected.processingJobs)||selected.processingJobs<0)return{state:"unknown",text:"\u72B6\u6001\u6682\u4E0D\u53EF\u7528"};if(selected.failedJobs>0)return{state:"failed",text:selected.failedJobs+" \u4E2A\u4EFB\u52A1\u9700\u8981\u5904\u7406"};let layers=selected.memoryOverview.layers;return selected.topicDirectoryReadError||!layers?.profile||!layers.directory||!layers.session||!layers.shortTerm||!layers.longTerm?{state:"warning",text:"\u90E8\u5206\u8BB0\u5FC6\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6"}:selected.processingJobs>0?{state:"processing",text:"\u6B63\u5728\u6574\u7406\u8BB0\u5FC6"}:{state:"ok",text:"\u8FD0\u884C\u6B63\u5E38"}}function OverviewPage({selected,loading,error:error3,onOpenSection,onOpenStatus}){let stats=selected?.memoryOverview;if(loading&&!stats)return h(Loading);if(!stats)return h(Empty,{title:"\u8FD8\u6CA1\u6709\u53EF\u6C47\u603B\u7684\u8BB0\u5FC6",copy:"\u8FD9\u4E2A\u5DE5\u4F5C\u533A\u7684\u8BB0\u5FC6\u8BFB\u51FA\u6765\u4E4B\u540E\uFF0C\u4F1A\u663E\u793A\u5728\u8FD9\u91CC\u3002"});let runtimeState=overviewRuntimeState(selected,loading,error3),layers=[{key:"profile",name:"\u5E38\u9A7B\u753B\u50CF",tone:"ink",section:"profile",value:stats.layers.profile?overviewCount(stats.layers.profile.characters):"\u2014",unit:"\u5B57",updatedAt:stats.layers.profile?.updatedAt},{key:"directory",name:"\u8BB0\u5FC6\u76EE\u5F55",tone:"moss",section:"long",value:stats.layers.directory?overviewCount(stats.layers.directory.chapters):"\u2014",unit:"\u7AE0",updatedAt:stats.layers.directory?.updatedAt},{key:"session",name:"\u4F1A\u8BDD\u8BB0\u5FC6",tone:"water",section:"short",value:overviewCount(stats.layers.session.blocks),unit:"\u5757",updatedAt:stats.layers.session.updatedAt},{key:"short",name:"\u77ED\u671F\u8BB0\u5FC6",tone:"sand",section:"daily",value:stats.layers.shortTerm?overviewCount(stats.layers.shortTerm.items):"\u2014",unit:"\u6761",updatedAt:stats.layers.shortTerm?.updatedAt},{key:"long",name:"\u957F\u671F\u8BB0\u5FC6",tone:"lib",section:"long",value:overviewCount(stats.layers.longTerm.events),unit:"\u4E2A\u4E8B\u4EF6",updatedAt:stats.layers.longTerm.updatedAt,answers:stats.layers.longTerm.answers}],heatmap=Array.isArray(stats.heatmap)?stats.heatmap:[],peak=Math.max(1,...heatmap.map(day=>Number(day.answers)||0));return h("section",{className:"sg-ov","data-testid":"stratagate-overview","aria-label":"\u8BB0\u5FC6\u603B\u89C8"},h("div",{className:"sg-ov-top"},h("div",{className:"sg-ov-stat"},h("div",{className:"sg-ov-big"},h("b",{className:"sg-mono","data-testid":"overview-answer-count"},overviewCount(stats.answeredLast7Days)),h(OverviewSpeechMark)),h("p",{className:"sg-ov-summary","data-testid":"overview-answer-summary"},"\u6700\u8FD1 7 \u5929\uFF0C\u957F\u671F\u8BB0\u5FC6\u5E2E\u5230 "+overviewCount(stats.answeredLast7Days)+" \u6B21\u56DE\u7B54"),h(typeof onOpenStatus=="function"?"button":"div",{type:typeof onOpenStatus=="function"?"button":void 0,className:"sg-ov-status","data-testid":"overview-runtime-status","data-state":runtimeState.state,onClick:onOpenStatus,title:typeof onOpenStatus=="function"?"\u67E5\u770B\u7CFB\u7EDF\u72B6\u6001":void 0},h("i",{className:"sg-runtime-dot","data-state":runtimeState.state,"aria-hidden":"true"}),h("span",null,runtimeState.text))),h("div",{className:"sg-pillar-group"},h("div",{className:"sg-pillar-cap","aria-hidden":"true"},h(OverviewSpeechMark)),h("div",{className:"sg-pillar","aria-label":"\u8BB0\u5FC6\u5206\u5C42"},layers.map(layer=>{let when="\u6700\u8FD1\u66F4\u65B0\uFF1A"+overviewRelative(layer.updatedAt),countText=layer.value==="\u2014"?"\u6682\u65E0\u6570\u636E":layer.value+" "+layer.unit,summary=layer.name+" "+countText+"\uFF0C"+when,open=()=>{typeof onOpenSection=="function"&&onOpenSection(layer.section)};return h(React.Fragment,{key:layer.key},layer.key==="long"?h("div",{className:"sg-pillar-gap","aria-hidden":"true"}):null,h("button",{type:"button",className:"sg-pillar-row","data-testid":"overview-layer-"+layer.key,"aria-label":"\u6253\u5F00"+layer.name+"\uFF1A"+countText+"\uFF0C"+when,title:summary,onClick:open},h("span",{className:"sg-pillar-bar "+layer.tone,"aria-hidden":"true"}),h("span",{className:"sg-pillar-name"},h("b",null,layer.name)),h("span",{className:"sg-pillar-tail"},h("span",{className:"sg-pillar-use"},layer.key==="long"&&layer.answers>0?h(UsedMark,{count:layer.answers,title:"\u88AB\u56DE\u7B54\u7528\u5230 "+layer.answers+" \u6B21"}):null),h("span",{className:"sg-pillar-val"},h("b",{className:"sg-mono"},layer.value),layer.value!=="\u2014"?h("span",{className:"sg-pillar-unit"},layer.unit):null))))})),h("div",{className:"sg-pillar-key"},h("span",null,h("i",{className:"sg-sw","aria-hidden":"true"}),"\u4E00\u76F4\u5E26\u7740"),h("span",null,h("i",{className:"sg-sw lib","aria-hidden":"true"}),"\u9700\u8981\u65F6\u53BB\u627E"),h("span",null,h(UsedMark),"\u88AB\u7528\u5230")))),h("div",{className:"sg-heat"},h("div",{className:"sg-heat-head"},h("span",null,h(UsedMark),"\u6BCF\u5929\u88AB\u56DE\u7B54\u7528\u5230\u51E0\u6B21"),h("span",null,"\u989C\u8272\u8D8A\u6DF1\u8D8A\u591A")),h("div",{className:"sg-heat-grid","aria-label":"\u6700\u8FD1 "+heatmap.length+" \u5929\u957F\u671F\u8BB0\u5FC6\u91C7\u7528"},heatmap.map(day=>{let answers=Number(day.answers)||0,ink=answers?Math.min(28+Math.round(answers/peak*62),90):0;return h("i",{key:day.day,title:day.day+" \xB7 "+answers+" \u6B21\u56DE\u7B54",style:answers?{background:"color-mix(in srgb, var(--sg-ink) "+ink+"%, var(--sg-sheet))",boxShadow:"none"}:void 0})})),h("div",{className:"sg-heat-scale"},h("span",null,heatmap.length>14?"4 \u5468\u524D":"2 \u5468\u524D"),h("span",null,"\u4ECA\u5929"))))}function MemoryPage({useWorkspaces,useSessions,navigationState,usePluginSettings,setMemoryModel,setEffort,resetEffort,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,onOpenDreamingSession,onChooseSidebar,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays}){let TAB_SWATCH={profile:"ink",short:"water",daily:"sand",long:"lib"},workspaceItems=useWorkspaces(state=>state.items),sessionById=useSessions(state=>state.byId||{}),[overview,setOverview]=React.useState({namespaces:[]}),[namespace,setNamespace]=React.useState(""),[workspaceTitles,setWorkspaceTitles]=React.useState({}),[workspaceSessionIds,setWorkspaceSessionIds]=React.useState({}),[conversationId,setConversationId]=React.useState(""),[section,setSection]=React.useState("overview"),[view,setView]=React.useState({name:"root"}),[graphFocusNodeId,setGraphFocusNodeId]=React.useState(""),consumeGraphFocus=React.useCallback(()=>setGraphFocusNodeId(""),[]),[data4,setData]=React.useState({events:[],graph:{nodes:[],edges:[],migration:null},blocks:[],openBlock:null,conversations:[],activeThreadId:null,audit:[],pagination:{events:{total:0,offset:0,limit:40},blocks:{total:0,offset:0,limit:40},audit:{total:0,offset:0,limit:100}}}),[query,setQuery]=React.useState(""),[source,setSource]=React.useState(null),[loading,setLoading]=React.useState(!0),[error3,setError]=React.useState(""),[recentError,setRecentError]=React.useState(""),[savingSettings,setSavingSettings]=React.useState(!1),[pollFast,setPollFast]=React.useState(!1),dashboardRequestRef=React.useRef(null),sourceRequestRef=React.useRef(null),namespaceRef=React.useRef(namespace);namespaceRef.current=namespace;let dashboardEtagsRef=React.useRef(new Map),loadedNamespaceRef=React.useRef(""),feedbackDeepLinkRef=React.useRef(readFeedbackNavigationState(navigationState)||readFeedbackDeepLink()),graphNodeNavigationRef=React.useRef(readGraphNodeNavigationState(navigationState)||readGraphNodeDeepLink()),feedbackNavigationStateRef=React.useRef(navigationState),namespaceNavigationRef=React.useRef(null),directoryScrollRef=React.useRef(null),reportError=reason=>{let message=String(reason?.message||reason);if(setError(message),setRecentError(message),namespace){let category=/timeout|timed out|超时/i.test(message)?"timeout":/fetch|network|网络/i.test(message)?"network":"request-failed";api2("diagnostics",{namespace,category},{method:"POST"}).catch(()=>{})}};React.useEffect(()=>{let active=!0;return Promise.all((workspaceItems||[]).map(async workspace=>({key:await workspaceProjectKey(workspace.path),title:String(workspace.title||"").trim(),sessionIds:Array.isArray(workspace.sessionIds)?workspace.sessionIds.map(String):[]}))).then(entries=>{active&&(setWorkspaceTitles(Object.fromEntries(entries.filter(({key,title})=>key&&title).map(({key,title})=>[key,title]))),setWorkspaceSessionIds(Object.fromEntries(entries.filter(({key})=>key).map(({key,sessionIds})=>[key,sessionIds]))))}),()=>{active=!1}},[workspaceItems]);let loadDashboard=React.useCallback((activeNamespace,options2={})=>{let background=options2.background===!0;if(background&&!options2.force&&dashboardRequestRef.current)return Promise.resolve(null);dashboardRequestRef.current?.abort();let controller=new AbortController;dashboardRequestRef.current=controller;let key=String(activeNamespace||"")+"\0"+String(options2.threadId||"");return background||setLoading(!0),background||setError(""),dashboardApi({...activeNamespace?{namespace:activeNamespace}:{},...options2.threadId?{threadId:options2.threadId}:{}},{etag:options2.force?"":dashboardEtagsRef.current.get(key),signal:controller.signal}).then(result=>{if(controller.signal.aborted||dashboardRequestRef.current!==controller||(result.etag&&dashboardEtagsRef.current.set(key,result.etag),result.notModified||!result.data))return null;let next2=result.data;return setOverview(next2.overview||{namespaces:[]}),setPollFast(next2.processing===!0),next2.namespace&&(loadedNamespaceRef.current=next2.namespace,setNamespace(current=>next2.overview?.namespaces?.some(item=>item.namespace===current)?current:next2.namespace)),next2.data&&(setData(next2.data),setConversationId(next2.data.activeThreadId||"")),setError(""),next2}).catch(reason=>{if(controller.signal.aborted||dashboardRequestRef.current!==controller)return null;if(reason?.name!=="AbortError"&&reportError(reason),options2.propagateError===!0&&reason?.name!=="AbortError")throw reason;return null}).finally(()=>{dashboardRequestRef.current===controller&&(dashboardRequestRef.current=null,setLoading(!1))})},[]);React.useEffect(()=>{let graphLink=graphNodeNavigationRef.current,feedbackLink=feedbackDeepLinkRef.current;return graphLink?(setSection("long"),setQuery(""),setView({name:"root"}),setSource(null),setGraphFocusNodeId(graphLink.nodeId),readGraphNodeDeepLink()&&consumeGraphNodeDeepLink()):feedbackLink&&(setSection("more"),setView({name:"support"}),setSource(null),readFeedbackDeepLink()&&consumeFeedbackDeepLink()),loadDashboard(graphLink?.namespace||feedbackLink?.namespace||""),()=>{dashboardRequestRef.current?.abort(),sourceRequestRef.current?.abort()}},[loadDashboard]),React.useEffect(()=>{let graphLink=navigationState!==feedbackNavigationStateRef.current?readGraphNodeNavigationState(navigationState):null,feedback=readNewFeedbackNavigationState(feedbackNavigationStateRef.current,navigationState);if(feedbackNavigationStateRef.current=navigationState,graphLink){setSection("long"),setView({name:"root"}),setSource(null),setGraphFocusNodeId(graphLink.nodeId),namespaceNavigationRef.current=namespace!==graphLink.namespace?{namespace:graphLink.namespace}:null,setNamespace(graphLink.namespace),namespace===graphLink.namespace&&loadDashboard(graphLink.namespace,{force:!0});return}feedback&&(setSection("more"),setView({name:"support"}),setSource(null),namespaceNavigationRef.current=namespace!==feedback.namespace?{namespace:feedback.namespace}:null,setNamespace(feedback.namespace),namespace===feedback.namespace&&loadDashboard(feedback.namespace,{force:!0}))},[navigationState,loadDashboard]),React.useEffect(()=>{if(!namespace)return;let navigated=namespaceNavigationRef.current?.namespace===namespace;namespaceNavigationRef.current=null,loadedNamespaceRef.current!==namespace&&(directoryScrollRef.current=null,setConversationId(""),navigated||setView({name:"root"}),setSource(null),setRecentError(""),setData({events:[],graph:{nodes:[],edges:[],migration:null},blocks:[],openBlock:null,conversations:[],activeThreadId:null,audit:[],pagination:{events:{total:0,offset:0,limit:40},blocks:{total:0,offset:0,limit:40},audit:{total:0,offset:0,limit:100}}}),loadDashboard(namespace,{force:!0}))},[namespace,loadDashboard]),React.useEffect(()=>{if(!namespace)return;let stopped=!1,timer=null,schedule=delay2=>{stopped||document.hidden||(timer=window.setTimeout(run,delay2))},run=()=>{stopped||document.hidden||loadDashboard(namespace,{background:!0,threadId:conversationId}).finally(()=>{schedule(pollFast?2500:3e4)})},onVisibilityChange=()=>{document.hidden?(timer!==null&&window.clearTimeout(timer),timer=null,dashboardRequestRef.current?.abort()):run()};return document.addEventListener("visibilitychange",onVisibilityChange),schedule(pollFast?2500:3e4),()=>{stopped=!0,timer!==null&&window.clearTimeout(timer),document.removeEventListener("visibilitychange",onVisibilityChange)}},[namespace,conversationId,pollFast,loadDashboard]);let selected=(overview.namespaces||[]).find(item=>item.namespace===namespace),runtimeState=overviewRuntimeState(selected,loading,error3),project=projectName(selected||namespace,workspaceTitles),activeProjectKey=namespace.includes(":project:")?namespace.split(":project:").pop():"",hostSessionIds=workspaceSessionIds[activeProjectKey]||[],memoryConversations=new Map(data4.conversations.map(conversation=>[conversation.id,conversation])),conversations=[],seenConversations=new Set;for(let id2 of hostSessionIds){let session=sessionById[id2];if(session?.parentId)continue;let memory=memoryConversations.get(id2),dshTitle=String(session?.title||"").trim();conversations.push({...memory||{},id:id2,label:dshTitle||memory?.label||"\u5BF9\u8BDD "+id2.slice(0,8)}),seenConversations.add(id2)}for(let memory of data4.conversations)seenConversations.has(memory.id)||conversations.push(memory);conversations.sort((left,right)=>left.id==="__legacy__"?1:right.id==="__legacy__"?-1:0);let clearSource=()=>{sourceRequestRef.current?.abort(),sourceRequestRef.current=null,setSource(null)},goSection=next2=>{directoryScrollRef.current=null,setSection(next2),setView({name:"root"}),clearSource()},sourceParams=(kind,item)=>kind==="event"?{eventId:item.id}:kind==="element"?{elementId:item.id}:{blockId:item.id},loadSource=(kind,item)=>{clearSource();let controller=new AbortController;sourceRequestRef.current=controller;let requestedNamespace=namespace,requestedId=String(item?.id||"");api2("sources",{namespace,...sourceParams(kind,item)},{signal:controller.signal}).then(value=>{if(sourceRequestRef.current!==controller||controller.signal.aborted||namespaceRef.current!==requestedNamespace)return;let returnedId=value?.event?.id||value?.element?.id||value?.block?.id||value?.id,returnedIds=Array.isArray(value?.events)?value.events.map(entry=>String(entry?.id||"")):[];returnedId&&String(returnedId)!==requestedId||returnedIds.length&&!returnedIds.includes(requestedId)||setSource(value)}).catch(reason=>{reason?.name!=="AbortError"&&sourceRequestRef.current===controller&&reportError(reason)})},openWithSource=(kind,item)=>{setView(current=>({name:kind,item,back:current})),loadSource(kind,item)},openEvent=(event3,trigger)=>{if(trigger?.getAttribute?.("data-topic-event-id")){let ancestors=[];for(let node=trigger.parentElement;node;node=node.parentElement)node.scrollHeight>node.clientHeight&&ancestors.push({node,top:node.scrollTop,left:node.scrollLeft});directoryScrollRef.current={namespace,eventId:event3.id,trigger,ancestors,top:window.scrollY||0,left:window.scrollX||0}}openWithSource("event",data4.events.find(item=>item.id===event3.id)||event3)};(React.useLayoutEffect||React.useEffect)(()=>{let saved=directoryScrollRef.current,action=directoryScrollAction(saved,section,namespace,view.name);if(action!=="none"){if(action==="clear"){directoryScrollRef.current=null;return}if(action==="detail"){for(let{node}of saved.ancestors)node.scrollTop=0,node.scrollLeft=0;window.scrollTo?.(0,0)}else if(action==="restore"){(saved.trigger?.isConnected&&saved.trigger.getClientRects().length?saved.trigger:Array.from(document.querySelectorAll(".sg-topic-event[data-topic-event-id]")).find(node=>node.getAttribute("data-topic-event-id")===saved.eventId&&node.getClientRects().length))?.focus?.({preventScroll:!0});for(let{node,top,left}of saved.ancestors)node.scrollTop=top,node.scrollLeft=left;window.scrollTo?.(saved.left,saved.top),directoryScrollRef.current=null}}},[view.name,section,namespace]);let openGraphNode=nodeId=>{directoryScrollRef.current=null,setSection("long"),setQuery(""),setView({name:"root"}),clearSource(),setGraphFocusNodeId(nodeId)},goBack=()=>{let previous=view.back||{name:"root"};setView(previous),previous.item&&["event","block"].includes(previous.name)?loadSource(previous.name,previous.item):clearSource()},backLabel=view.back?.name==="duplicates"?"\u91CD\u590D\u8BB0\u5FC6\u6574\u7406":view.back?.name==="block"?"\u4F1A\u8BDD\u8BB0\u5FC6":view.back?.name==="event"?"\u957F\u671F\u8BB0\u5FC6":view.back?.name==="structure"?"\u8BB0\u5FC6\u7ED3\u6784":section==="short"?"\u4F1A\u8BDD\u8BB0\u5FC6":"\u957F\u671F\u8BB0\u5FC6",refresh=(options2={})=>loadDashboard(namespace,{threadId:conversationId,force:!0,...options2}),refreshDirectory=React.useCallback(()=>loadDashboard(namespace,{threadId:conversationId,background:!0,force:!0}),[namespace,conversationId,loadDashboard]),selectConversation=nextConversationId=>(setConversationId(nextConversationId),loadDashboard(namespace,{threadId:nextConversationId,force:!0})),updateSettings=values=>(setSavingSettings(!0),setError(""),api2("settings",values,{method:"PATCH"}).then(()=>loadDashboard(namespace,{threadId:conversationId,force:!0})).catch(reportError).finally(()=>setSavingSettings(!1))),onRetrievalSettingsSaved=vectorSettings=>setOverview(current=>({...current,vectorSettings})),moreBack=()=>setView({name:"root"}),content=null;return(section==="long"||view.name==="support")&&loadedNamespaceRef.current!==namespace||loading&&!selected?content=h(Loading):view.name==="settings"?content=h(SettingsPage,{selected:selected||{blockTurnSize:6,blockDecayLambda:.3,agentMemoryRetrievalWeight:1,currentTurn:0,schemaVersion:12},graphSettings:overview.graphSettings,vectorSettings:overview.vectorSettings,retrievalSettingsWritable:overview.settingsWritable,onRetrievalSettingsSaved,refresh,namespace,dataDirectory:overview.dataDirectory,onBack:moreBack,setView,updateSettings,savingSettings,usePluginSettings,setMemoryModel,setEffort,resetEffort,setDailyEnabled,setDailyTimeZone,setDailyInjectionDays,onDirectoryChanged:refreshDirectory,onOpenDreamingSession}):section==="overview"&&view.name==="root"?content=h(OverviewPage,{key:namespace,selected,loading,error:error3,onOpenSection:goSection,onOpenStatus:()=>setView({name:"status"})}):section==="profile"&&view.name==="root"?content=h(ProfilePage):section==="daily"&&view.name==="root"?content=h(DailyNotesPage,{key:namespace,namespace,setDailyInjectionDays}):!selected&&section!=="more"?content=h(Empty,{title:"\u8FD8\u6CA1\u6709\u8BB0\u5FC6",copy:"\u5B8C\u6210\u4E00\u4E9B DSH \u5BF9\u8BDD\u540E\uFF0C\u4F1A\u8BDD\u8BB0\u5FC6\u548C\u957F\u671F\u8BB0\u5FC6\u4F1A\u51FA\u73B0\u5728\u8FD9\u91CC\u3002"}):view.name==="event"?content=h(EventDetail,{event:view.item,project,source,onBack:goBack,backLabel,onNode:openGraphNode}):view.name==="status"?content=h(ProcessingStatus,{key:namespace,overview:selected,blocks:data4.blocks,conversations,namespace,serverVersion:overview.pluginVersion,onBack:view.back?goBack:()=>setView({name:"root"}),backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u8FD4\u56DE",refresh}):view.name==="import"?content=h(ImportPage,{key:namespace,namespace,onBack:moreBack,refresh}):view.name==="structure"?content=h(StructurePage,{events:data4.events,eventPage:data4.pagination?.events,graph:data4.graph,openEvent,namespace,onBack:moreBack}):view.name==="duplicates"?content=h(DuplicateReviewPage,{namespace,repair:selected?.duplicateRepair,onBack:moreBack,openEvent,refresh}):view.name==="system"?content=h(SystemPage,{selected,blocks:data4.blocks,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A",refresh,onDuplicates:()=>setView({name:"duplicates"})}):view.name==="audit"?content=h(AuditPage,{audit:data4.audit,auditPage:data4.pagination?.audit,namespace,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A"}):view.name==="raw"?content=h(RawPage,{data:data4,selected,onBack:view.back?goBack:moreBack,backLabel:view.back?.name==="settings"?"\u9AD8\u7EA7\u8BBE\u7F6E":"\u66F4\u591A"}):view.name==="display"?content=h(DisplayPage,{onBack:moreBack,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry}):view.name==="support"?content=h(SupportPage,{key:namespace,namespace,overview,selected,data:data4,recentError,onBack:moreBack}):content=h(React.Fragment,null,loading?h(Loading):section==="short"?h(ShortTermPage,{key:namespace+":"+conversationId,blockTurnSize:selected?.blockTurnSize||6,blocks:data4.blocks,blockPage:data4.pagination?.blocks,openBlock:data4.openBlock,conversations,activeThreadId:conversationId||data4.activeThreadId||"",namespace,onConversationChange:selectConversation,refresh}):section==="long"?null:h(MoreHome,{setView,selected,overview,namespace,dataDirectory:overview.dataDirectory,updateSettings,savingSettings,usePluginSettings,setStrataGateStatus,setShortTermStatus,setRetrievalStatus,setSidebarEntry,setDailyEnabled,setDailyInjectionDays})),h("main",{className:"sg-memory sg-unified-top"+(section==="overview"&&view.name==="root"?" sg-overview-page":"")+(view.name==="duplicates"?" sg-memory-review":"")+(view.name==="settings"||view.name==="display"||section==="more"&&view.name==="root"?" sg-settings-page":""),"data-testid":"stratagate-memory-ui"},h("style",null,css+DUPLICATE_STYLES+DAILY_NOTES_CSS+R6_STYLES),h("header",{className:"sg-header"},h("div",{className:"sg-header-row sg-header-row-primary"},h(GITHUB_FEEDBACK_ENABLED?"a":"div",{className:"sg-brand",href:GITHUB_FEEDBACK_ENABLED?STAR_REPOSITORY_URL:void 0,target:GITHUB_FEEDBACK_ENABLED?"_blank":void 0,rel:GITHUB_FEEDBACK_ENABLED?"noopener noreferrer":void 0},h(StrataGateMark),h("span",{className:"sg-brand-copy"},h("span",{className:"sg-brand-title"},h("span",{className:"sg-brand-name"},"StrataGate"),overview.pluginVersion&&overview.pluginVersion!=="unknown"?h("span",{className:"sg-brand-version"},"v"+overview.pluginVersion):null),onChooseSidebar?h(SidebarPlacementPrompt,{onChooseSidebar,usePluginSettings}):null)),h("div",{className:"sg-header-end"},h("div",{className:"sg-project"},h("i",{className:"sg-runtime-dot","data-testid":"overview-workspace-dot","data-state":runtimeState.state,role:"img","aria-label":runtimeState.text,title:runtimeState.text}),h("span",{className:"sg-project-label"},"\u5F53\u524D\u5DE5\u4F5C\u533A"),h("select",{className:"sg-project-select",value:namespace,onChange:event3=>setNamespace(event3.target.value),"aria-label":"\u5F53\u524D\u5DE5\u4F5C\u533A"},(overview.namespaces||[]).map(item=>h("option",{key:item.namespace,value:item.namespace},projectName(item,workspaceTitles))))),GITHUB_FEEDBACK_ENABLED?h(HeaderStarLink):null)),h("nav",{className:"sg-tabs","aria-label":"\u8BB0\u5FC6\u89C6\u56FE"},[["overview","\u603B\u89C8"],["profile","\u5E38\u9A7B\u753B\u50CF"],["short","\u4F1A\u8BDD\u8BB0\u5FC6"],["daily","\u77ED\u671F\u8BB0\u5FC6"],["long","\u957F\u671F\u8BB0\u5FC6"],["more","\u66F4\u591A"]].map(([id2,label])=>h("button",{key:id2,type:"button",className:"sg-tab "+(section===id2?"active":""),"aria-current":section===id2?"page":void 0,onClick:()=>goSection(id2)},TAB_SWATCH[id2]?h("i",{key:"sw",className:"sg-tab-swatch "+TAB_SWATCH[id2],"aria-hidden":"true"}):null,label))),h("div",{className:"sg-page-body"},error3?h("div",{className:"sg-error"},h("div",{className:"sg-error-title"},"\u6682\u65F6\u65E0\u6CD5\u8BFB\u53D6\u5B8C\u6574\u8BB0\u5FC6"),h("div",null,"\u5DF2\u663E\u793A\u80FD\u591F\u8BFB\u53D6\u7684\u5185\u5BB9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u65B0\u52A0\u8F7D\u3002"),h("details",null,h("summary",null,"\u6280\u672F\u8BE6\u60C5"),h("div",{className:"sg-code"},error3))):null,view.name==="root"&&selected?.duplicateRepair?.needsReview>0?h("button",{type:"button",className:"sg-dup-entry",onClick:()=>setView({name:"duplicates"})},h(DuplicateIcon,{size:23}),h("span",null,h("strong",null,selected.duplicateRepair.needsReview+" \u7EC4\u76F8\u4F3C\u8BB0\u5FC6\uFF0C\u7B49\u4F60\u786E\u8BA4"),h("small",null,"\u5BF9\u6BD4\u5185\u5BB9\uFF0C\u9009\u62E9\u4FDD\u7559\u54EA\u5F20\u6216\u5408\u5E76\u53CC\u65B9\u8BC1\u636E")),h(DuplicateIcon,{kind:"next"})):null,h("section",{key:section,className:"sg-view","aria-label":"StrataGate \u8BB0\u5FC6\u5185\u5BB9"},section==="long"&&selected&&loadedNamespaceRef.current===namespace?h(React.Fragment,null,h("div",{key:"long-browser",hidden:view.name!=="root"},h(LongTermPage,{graphSettings:overview.graphSettings,extractionGap:selected?.longTermExtractionGap===!0,key:namespace,events:data4.events,eventPage:data4.pagination?.events,graph:data4.graph,project,query,setQuery,openEvent,namespace,focusNodeId:graphFocusNodeId,onFocusHandled:consumeGraphFocus,topicDirectory:data4.topicDirectory,onDirectoryChanged:refreshDirectory,onOpenDreamingSession,refresh,active:view.name==="root"})),view.name==="root"?null:content):content),h("footer",{className:"sg-footer"},h("span",null,"StrataGate-AgentMemory \xB7 MIT"),h("span",{className:"sg-footer-links"},h("a",{href:STAR_REPOSITORY_URL,target:"_blank",rel:"noopener noreferrer"},"GitHub \u4ED3\u5E93")," \xB7 ",h("a",{href:ISSUE_URL,target:"_blank",rel:"noopener noreferrer"},"\u63D0 Issue")," \xB7 ",h("a",{href:STAR_REPOSITORY_URL+"/releases",target:"_blank",rel:"noopener noreferrer"},"\u66F4\u65B0\u8BB0\u5F55"))))))}function MemoryPanel(props){return h("div",{className:"sg-memory-panel",style:{flex:"1 1 0%",minHeight:0,width:"100%",overflowY:"auto",overflowX:"hidden"}},h(MemoryPage,props))}function readSidebarPromptState(){try{return String(globalThis.localStorage?.getItem(SIDEBAR_PROMPT_STORAGE_KEY)||"")}catch{return""}}function writeSidebarPromptState(value){try{globalThis.localStorage?.setItem(SIDEBAR_PROMPT_STORAGE_KEY,value)}catch{}}function StrataGatePanelIcon({size:size3=20}){return h("svg",{width:size3,height:size3,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,focusable:!1,className:"sg-sidebar-panel-icon",style:{display:"block",flexShrink:0}},h("path",{opacity:.28,strokeWidth:1.4,d:"M3 12V4a1 1 0 0 1 1-1h8"}),h("path",{opacity:.55,d:"M6 15V7a1 1 0 0 1 1-1h9"}),h("rect",{x:9,y:9,width:12,height:13,rx:1.8}),h("path",{d:"M12 13h6M12 17h4"}))}function SidebarPlacementPrompt({onChooseSidebar,usePluginSettings}){let settings=usePluginSettings?usePluginSettings(state=>state):null,[visible,setVisible]=React.useState(()=>readSidebarPromptState()!=="dismissed"),[busy,setBusy]=React.useState(!1),[error3,setError]=React.useState("");if(!visible||settings?.value?.showSidebarEntry===!0||settings?.writable!==!0)return null;let dismiss=()=>{writeSidebarPromptState("dismissed"),setVisible(!1)},chooseSidebar=async()=>{setBusy(!0),setError("");try{if(!await onChooseSidebar?.()){setError("\u672A\u80FD\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u8BD5\u3002");return}writeSidebarPromptState("sidebar"),setVisible(!1)}catch{setError("\u672A\u80FD\u4FDD\u5B58\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5\u540E\u91CD\u8BD5\u3002")}finally{setBusy(!1)}};return h(React.Fragment,null,h("style",null,SIDEBAR_PROMPT_STYLES),h("span",{className:"sg-sidebar-placement-prompt",role:"region","aria-label":"StrataGate \u4FA7\u680F\u5165\u53E3\u63D0\u793A"},h("span",{className:"sg-sidebar-placement-text"},"\u4ECE\u5DE6\u4FA7\u680F\u5FEB\u901F\u6253\u5F00\u8BB0\u5FC6"),h("button",{type:"button",className:"sg-sidebar-placement-action",disabled:busy,onClick:()=>{chooseSidebar()}},"\u653E\u5230\u5DE6\u4FA7\u680F"),h("button",{type:"button",className:"sg-sidebar-placement-close","aria-label":"\u5173\u95ED\u4FA7\u680F\u5165\u53E3\u63D0\u793A",title:"\u4E0D\u518D\u63D0\u9192",disabled:busy,onClick:dismiss},"\xD7"),error3?h("span",{role:"alert"},error3):null))}let disposeFeedbackLinkNavigation=null;function apply2(ctx){let slots=ctx.get("slots");if(!slots)return;let configForms=ctx.get("configForms"),settingsScope=ctx.get("settingsScope"),pluginSettingsScope=configForms?configForms.get("stratagate-memory"):settingsScope?settingsScope.bind({namespace:"stratagate-memory"}):null,setSidebarEntry=async visible=>{if(!pluginSettingsScope||!await pluginSettingsScope.set("showSidebarEntry",visible))return!1;if(!visible){let layout4=ctx.get("layout");layout4?.activePanelId===MEMORY_PANEL_ID&&layout4.selectPanel?.(null)}return!0},warnCitationFailure=(part,error3)=>{if(!(typeof console>"u"||typeof console.warn!="function"))try{console.warn("[StrataGate] "+part+" registration failed; memory settings remain available.",error3)}catch{}};slots.inject("settings.section",()=>slots.register({name:"settings.section",id:"stratagate-memory",order:32,label:()=>"StrataGate-AgentMemory",inject:()=>({hooks:{pluginSettings:pluginSettingsScope},setMemoryModel:pluginSettingsScope?selection=>pluginSettingsScope.set("memoryModel",selection):null,setEffort:pluginSettingsScope?mode=>pluginSettingsScope.set("structuredReasoningEffort",mode):null,setDailyEnabled:pluginSettingsScope?enabled=>pluginSettingsScope.set("dailyNotesEnabled",enabled):null,setDailyInjectionDays:pluginSettingsScope?days=>pluginSettingsScope.set("dailyNotesInjectionDays",days):null,setDailyTimeZone:pluginSettingsScope?zone=>zone?pluginSettingsScope.set("dailyNotesTimeZone",zone):pluginSettingsScope.unset("dailyNotesTimeZone"):null,resetEffort:pluginSettingsScope?()=>pluginSettingsScope.unset("structuredReasoningEffort"):null,setStrataGateStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showStrataGateStatus",visible):null,setShortTermStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showShortTermStatus",visible):null,setRetrievalStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showRetrievalStatus",visible):null,setSidebarEntry:pluginSettingsScope?setSidebarEntry:null})},props=>h(FeedbackSettingsPage,{...props,onChooseSidebar:async()=>{let layout4=ctx.get("layout");return typeof layout4?.selectPanel!="function"||!await setSidebarEntry(!0)?!1:(layout4.selectPanel(MEMORY_PANEL_ID),props.close?.(),!0)},onOpenDreamingSession:sessionId=>{let navigation=ctx.get("uiWorkspace");if(typeof navigation?.openSession!="function")throw new Error("\u5F53\u524D DSH \u672A\u63D0\u4F9B\u4F1A\u8BDD\u5BFC\u822A\uFF0C\u8BF7\u5347\u7EA7\u5BBF\u4E3B\u540E\u91CD\u8BD5");navigation.openSession(sessionId),props.close?.()}})));let memoryPanelInject=()=>({setMemoryModel:pluginSettingsScope?selection=>pluginSettingsScope.set("memoryModel",selection):null,...pluginSettingsScope?{hooks:{pluginSettings:pluginSettingsScope}}:{},setEffort:pluginSettingsScope?mode=>pluginSettingsScope.set("structuredReasoningEffort",mode):null,setDailyEnabled:pluginSettingsScope?enabled=>pluginSettingsScope.set("dailyNotesEnabled",enabled):null,setDailyInjectionDays:pluginSettingsScope?days=>pluginSettingsScope.set("dailyNotesInjectionDays",days):null,setDailyTimeZone:pluginSettingsScope?zone=>zone?pluginSettingsScope.set("dailyNotesTimeZone",zone):pluginSettingsScope.unset("dailyNotesTimeZone"):null,resetEffort:pluginSettingsScope?()=>pluginSettingsScope.unset("structuredReasoningEffort"):null,setStrataGateStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showStrataGateStatus",visible):null,setShortTermStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showShortTermStatus",visible):null,setRetrievalStatus:pluginSettingsScope?visible=>pluginSettingsScope.set("showRetrievalStatus",visible):null,setSidebarEntry:pluginSettingsScope?setSidebarEntry:null,onOpenDreamingSession:sessionId=>{let navigation=ctx.get("uiWorkspace");if(typeof navigation?.openSession!="function")throw new Error("\u5F53\u524D DSH \u672A\u63D0\u4F9B\u4F1A\u8BDD\u5BFC\u822A\uFF0C\u8BF7\u5347\u7EA7\u5BBF\u4E3B\u540E\u91CD\u8BD5");navigation.openSession(sessionId)}});try{slots.inject("main",()=>slots.register({name:"main",key:MEMORY_PANEL_ID,order:20,inject:memoryPanelInject},MemoryPanel)),slots.inject("sidebar.panellist",()=>{let removeEntry=null,syncSidebar=()=>{let snapshot=pluginSettingsScope?.getSnapshot?.();if(snapshot?.status==="loading")return;let visible=snapshot?.value?.showSidebarEntry===!0;visible&&!removeEntry?removeEntry=slots.register({name:"sidebar.panellist",id:MEMORY_PANEL_ID,order:20,label:()=>"StrataGate \u8BB0\u5FC6"},StrataGatePanelIcon)||(()=>{}):!visible&&removeEntry&&(removeEntry(),removeEntry=null)},unsubscribe=pluginSettingsScope?.subscribe?.(syncSidebar);return syncSidebar(),()=>{unsubscribe?.(),removeEntry?.(),removeEntry=null}})}catch(error3){warnCitationFailure("sidebar entry",error3)}try{let uiConversation=ctx.get("uiConversation");uiConversation&&(uiConversation.events.register(memoryCitationsDefinition),ensureCitationStyles(),slots.inject("conversation.chat.turnTail",()=>{try{return slots.register({name:"conversation.chat.turnTail",id:"stratagate-memory-citations",select:selectMemoryCitations,inject:()=>({...pluginSettingsScope?{hooks:{pluginSettings:pluginSettingsScope}}:{},onOpenGraphNode:(namespace,nodeId)=>navigateToGraphNode(ctx,namespace,nodeId)})},MemoryCitationTail)}catch(error3){return warnCitationFailure("chat turn tail",error3),()=>{}}}))}catch(error3){warnCitationFailure("chat citations",error3)}if(typeof document<"u"){disposeFeedbackLinkNavigation?.();let disposeLinkNavigation=installFeedbackLinkNavigation(ctx),disposeDeepLink=openFeedbackDeepLink(ctx),disposeGraphDeepLink=openGraphNodeDeepLink(ctx);disposeFeedbackLinkNavigation=()=>{disposeLinkNavigation(),disposeDeepLink(),disposeGraphDeepLink()}}}return exports.name="stratagate-dsh",exports.inject=["slots","uiConversation"],exports.apply=apply2,module.exports}});})();