autosnippet 3.3.9 → 3.4.0
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/README.md +1 -1
- package/config/default.json +1 -1
- package/dashboard/dist/assets/{index-DEU4tJtP.js → index-8b1Gf3Bb.js} +1 -1
- package/dashboard/dist/index.html +1 -1
- package/dist/lib/agent/AgentRuntime.js +13 -1
- package/dist/lib/agent/AgentRuntimeTypes.d.ts +2 -0
- package/dist/lib/agent/PipelineStrategy.js +32 -2
- package/dist/lib/agent/context/ContextWindow.d.ts +2 -1
- package/dist/lib/agent/context/ContextWindow.js +18 -4
- package/dist/lib/agent/context/ExplorationTracker.js +6 -1
- package/dist/lib/agent/context/exploration/ExplorationStrategies.js +2 -1
- package/dist/lib/agent/core/LoopContext.d.ts +3 -0
- package/dist/lib/agent/core/LoopContext.js +3 -0
- package/dist/lib/agent/domain/EpisodicConsolidator.d.ts +5 -0
- package/dist/lib/agent/domain/EpisodicConsolidator.js +60 -5
- package/dist/lib/agent/domain/insight-analyst.d.ts +16 -0
- package/dist/lib/agent/domain/insight-analyst.js +38 -0
- package/dist/lib/agent/domain/insight-gate.js +12 -0
- package/dist/lib/agent/memory/MemoryConsolidator.js +17 -0
- package/dist/lib/domain/dimension/DimensionRegistry.d.ts +6 -4
- package/dist/lib/domain/dimension/DimensionRegistry.js +19 -23
- package/dist/lib/external/ai/AiProvider.d.ts +2 -0
- package/dist/lib/external/ai/AiProvider.js +4 -0
- package/dist/lib/external/ai/providers/ClaudeProvider.d.ts +1 -1
- package/dist/lib/external/ai/providers/ClaudeProvider.js +6 -2
- package/dist/lib/external/ai/providers/GoogleGeminiProvider.d.ts +1 -1
- package/dist/lib/external/ai/providers/GoogleGeminiProvider.js +6 -2
- package/dist/lib/external/ai/providers/OpenAiProvider.d.ts +1 -1
- package/dist/lib/external/ai/providers/OpenAiProvider.js +7 -3
- package/dist/lib/external/mcp/handlers/bootstrap/MissionBriefingBuilder.js +10 -2
- package/dist/lib/external/mcp/handlers/bootstrap/pipeline/orchestrator.js +37 -4
- package/dist/lib/http/routes/ai.js +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -48,7 +48,7 @@ asd ui # Start background service (MCP Server + Dashboard) — IDE and MC
|
|
|
48
48
|
|
|
49
49
|
> **First time:** Manually enable the `autosnippet` service in your IDE's MCP settings.
|
|
50
50
|
|
|
51
|
-
> **Tip:** Stronger models work better. We recommend Claude Opus 4 / Sonnet 4, GPT-5, or Gemini 3 Pro in Cursor / Copilot for more accurate patterns and fewer false positives.
|
|
51
|
+
> **Tip:** Stronger models work better. We recommend Claude Opus 4.6 / Sonnet 4.6, GPT-5.4, or Gemini 3.1 Pro in Cursor / Copilot for more accurate patterns and fewer false positives.
|
|
52
52
|
|
|
53
53
|
### Cold Start: Build Your Knowledge Base
|
|
54
54
|
|
package/config/default.json
CHANGED
|
@@ -106,7 +106,7 @@ ${F.rationale||""}`;Me=Me.replace(/^\s*\{["']name["']\s*:.*\}\s*\n?/,"").trim(),
|
|
|
106
106
|
`);for(let v=0;v<Math.min(N.length,5);v++){const U=N[v].trim();if(!(!U||U.startsWith("```"))&&U.startsWith("{")&&U.endsWith("}"))try{const ae=JSON.parse(U);if(ae.name){E=ae.name,L=ae.description||"";let be=v+1;for(;be<N.length&&!N[be].trim();)be++;O=N.slice(be).join(`
|
|
107
107
|
`).trim();break}}catch{}}}if(!E){const N=/"name"\s*:\s*"([a-z][a-z0-9-]{1,62}[a-z0-9])"/,v=/"description"\s*:\s*"([^"]+)"/,U=k.match(N),ae=k.match(v);U&&(E=U[1]),ae&&(L=ae[1])}O=O.replace(/```(?:json)?\s*\n?\s*\{[^}]*"name"[^}]*\}\s*\n?\s*```/gi,"").replace(/^\s*\{[^}]*"name"[^}]*\}\s*$/gm,"").trim(),E&&x(E),L&&u(L),c(O||k.trim()),J(!0),o("manual"),re(a("skills.checkGenerated"),{title:a("skills.aiGenerated")})}catch(z){I(a("skills.aiGenFailed")+": "+ke(z,""))}finally{d(!1)}}},B=async()=>{if(!g.trim()||!h.trim()||!m.trim()){I(a("skills.fillRequired"));return}A(!0),I("");try{await Q.createSkill({name:g.trim(),description:h.trim(),content:m.trim(),createdBy:P?"user-ai":"manual"}),re(a("skills.savedToKB"),{title:`Skill "${g}" ${a("skills.createSuccess")}`}),s()}catch(z){I(a("skills.createFailed")+": "+ke(z,""))}finally{A(!1)}};return e.jsxs($e,{className:"z-40 flex items-center justify-center",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] rounded-2xl shadow-2xl w-[720px] max-h-[85vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-violet-100 rounded-lg flex items-center justify-center",children:e.jsx(Le,{size:16,className:"text-violet-600"})}),e.jsx("h3",{className:"font-bold text-lg",children:a("skills.addSkill")})]}),e.jsx("button",{onClick:t,className:"p-1.5 rounded-lg hover:bg-[var(--bg-subtle)] transition-colors",children:e.jsx(ze,{size:18,className:"text-[var(--fg-muted)]"})})]}),e.jsx("div",{className:"px-6 pt-4",children:e.jsxs("div",{className:"inline-flex items-center gap-1 p-1 bg-[var(--bg-subtle)] rounded-lg",children:[e.jsxs("button",{onClick:()=>o("ai"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${r==="ai"?"bg-[var(--bg-surface)] text-violet-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:[e.jsx(Le,{size:12}),a("skills.aiGenMode")]}),e.jsxs("button",{onClick:()=>o("manual"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${r==="manual"?"bg-[var(--bg-surface)] text-violet-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:[e.jsx(Qe,{size:12}),a("skills.manualMode")]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[r==="ai"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:a("skills.describeSkill")}),e.jsx("div",{className:"relative",children:e.jsx("textarea",{value:l,onChange:z=>i(z.target.value),placeholder:a("skillsView.placeholderDesc"),className:"w-full h-32 px-4 py-3 border border-[var(--border-default)] rounded-xl text-sm resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400",disabled:p})})]}),e.jsx("button",{onClick:w,disabled:p||!l.trim(),className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-violet-600 text-white rounded-xl hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium",children:p?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:16,className:"animate-spin"}),a("skills.aiGeneratingContent")]}):e.jsxs(e.Fragment,{children:[e.jsx(Zs,{size:16}),a("skills.generateSkill")]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:[a("skills.skillName")," ",e.jsx("span",{className:"text-[var(--fg-muted)] text-xs",children:"(kebab-case)"})]}),e.jsx("input",{type:"text",value:g,onChange:z=>x(z.target.value),placeholder:"my-custom-skill",className:"w-full px-3 py-2 border border-[var(--border-default)] rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:a("skills.skillDescription")}),e.jsx("input",{type:"text",value:h,onChange:z=>u(z.target.value),placeholder:a("skillsView.placeholderName"),className:"w-full px-3 py-2 border border-[var(--border-default)] rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:[a("skills.skillContent")," ",e.jsx("span",{className:"text-[var(--fg-muted)] text-xs",children:"(Markdown)"})]}),e.jsx("textarea",{value:m,onChange:z=>c(z.target.value),placeholder:a("skillsView.placeholderContent"),className:"w-full h-64 px-4 py-3 border border-[var(--border-default)] rounded-xl text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400 leading-relaxed"})]})]}),D&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:[e.jsx(Et,{size:16,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:D})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-[var(--border-default)] flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] transition-colors",children:a("common.cancel")}),r==="manual"&&e.jsx("button",{onClick:B,disabled:j||!g.trim()||!h.trim()||!m.trim(),className:"flex items-center gap-2 px-5 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm font-medium",children:j?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:14,className:"animate-spin"}),a("common.saving")]}):e.jsxs(e.Fragment,{children:[e.jsx(mt,{size:14}),a("skills.addSkill")]})})]})]})]})},Ha=["architecture","swift-objc-idiom","ts-js-module","python-structure","jvm-annotation","go-module","rust-ownership","csharp-dotnet","react-patterns","vue-patterns","spring-patterns","swiftui-patterns","django-fastapi","coding-standards","design-patterns","ui-interaction","error-resilience","concurrency-async","data-event-flow","networking-api","testing-quality","security-auth","performance-optimization","observability-logging","agent-guidelines"],Lc={architecture:e.jsx(Ge,{className:"w-5 h-5"}),"coding-standards":e.jsx(qe,{className:"w-5 h-5"}),"design-patterns":e.jsx(At,{className:"w-5 h-5"}),"error-resilience":e.jsx(Le,{className:"w-5 h-5"}),"concurrency-async":e.jsx(Be,{className:"w-5 h-5"}),"data-event-flow":e.jsx(Be,{className:"w-5 h-5"}),"networking-api":e.jsx(Vt,{className:"w-5 h-5"}),"ui-interaction":e.jsx(Ge,{className:"w-5 h-5"}),"testing-quality":e.jsx(At,{className:"w-5 h-5"}),"security-auth":e.jsx(Vt,{className:"w-5 h-5"}),"performance-optimization":e.jsx(Le,{className:"w-5 h-5"}),"observability-logging":e.jsx(qe,{className:"w-5 h-5"}),"agent-guidelines":e.jsx(aa,{className:"w-5 h-5"})};function Fc(t){return Lc[t]||e.jsx(At,{className:"w-5 h-5"})}const _c=({task:t})=>{const{t:s}=Ae(),{status:a,meta:r}=t,o={skeleton:"bg-[var(--bg-subtle)] border-[var(--border-default)]",filling:"bg-blue-50 border-blue-300",completed:"bg-emerald-50 border-emerald-300",failed:"bg-red-50 border-red-300"},l={skeleton:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-[var(--border-emphasis)]"}),s("bootstrap.statusLabels.skeleton")]}),filling:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-blue-600",children:[e.jsx(Ne,{className:"w-3 h-3 animate-spin"}),s("bootstrap.statusLabels.filling")]}),completed:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-emerald-600",children:[e.jsx(ot,{className:"w-3 h-3"}),s("bootstrap.statusLabels.completed")]}),failed:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-red-600",children:[e.jsx(ze,{className:"w-3 h-3"}),s("bootstrap.statusLabels.failed")]})};return e.jsxs("div",{className:`relative rounded-xl border p-4 transition-all duration-300 ${o[a]||o.skeleton}`,children:[a==="skeleton"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-[var(--border-default)]/40 to-transparent h-full w-full"})}),a==="filling"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-blue-200/30 to-transparent h-full w-full"})}),e.jsxs("div",{className:"relative z-10 flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`flex-shrink-0 p-2 rounded-lg ${a==="completed"?"bg-emerald-100 text-emerald-600":a==="filling"?"bg-blue-100 text-blue-600":a==="failed"?"bg-red-100 text-red-600":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:Fc(t.id)}),e.jsxs("div",{children:[e.jsx("h3",{className:`font-medium text-sm ${a==="skeleton"?"text-[var(--fg-muted)]":"text-[var(--fg-primary)]"}`,children:(()=>{const i=`bootstrap.pipelineLabels.${r.dimId}`,p=s(i);return p!==i?p:r.label})()}),a==="completed"&&t.result&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:(()=>{const i=t.result,p=i.sourceCount??0,d=i.extracted??0;return i.type==="empty"?s("bootstrap.noMatch"):i.type==="skill"?i.empty?s("bootstrap.noMatch"):d>0?s("bootstrap.featuresAndCandidates",{sourceCount:p,extracted:d}):s("bootstrap.featuresOnly",{sourceCount:p}):d>0?s("bootstrap.candidatesOnly",{extracted:d}):s("bootstrap.noMatch")})()}),a==="failed"&&t.error&&e.jsx("p",{className:"text-xs text-red-500 mt-0.5 truncate max-w-[240px]",children:t.error})]})]}),e.jsx("div",{className:"flex-shrink-0",children:l[a]})]})]})},zc=[{key:"round1",labelKey:"bootstrap.reviewRounds.round1Label",descKey:"bootstrap.reviewRounds.round1Desc",icon:e.jsx(sa,{className:"w-4 h-4"})},{key:"round2",labelKey:"bootstrap.reviewRounds.round2Label",descKey:"bootstrap.reviewRounds.round2Desc",icon:e.jsx(us,{className:"w-4 h-4"})},{key:"round3",labelKey:"bootstrap.reviewRounds.round3Label",descKey:"bootstrap.reviewRounds.round3Desc",icon:e.jsx(fl,{className:"w-4 h-4"})}],Bc=({review:t})=>{const{t:s}=Ae();return t.activeRound===0?null:e.jsxs("div",{className:"mt-5 border border-purple-200 rounded-xl bg-purple-50/50 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Mt,{className:"w-5 h-5 text-purple-600"}),e.jsx("h3",{className:"text-sm font-semibold text-purple-800",children:s("bootstrap.reviewPipeline")})]}),e.jsx("div",{className:"space-y-2.5",children:zc.map(({key:a,labelKey:r,descKey:o,icon:l})=>{const i=t[a],p=i.status==="running",d=i.status==="completed",g=i.status==="idle";return e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg border transition-all duration-300 ${p?"border-purple-300 bg-purple-100/60":d?"border-emerald-300 bg-emerald-50/60":"border-[var(--border-default)] bg-[var(--bg-surface)]"}`,children:[e.jsx("div",{className:`flex-shrink-0 p-1.5 rounded-md ${p?"bg-purple-200 text-purple-700":d?"bg-emerald-100 text-emerald-600":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:l}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-sm font-medium ${g?"text-[var(--fg-muted)]":"text-[var(--fg-primary)]"}`,children:s(r)}),e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:s(o)})]}),a==="round1"&&d&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round1Done",{kept:t.round1.kept??"?",merged:t.round1.merged??0,dropped:t.round1.dropped??0})}),a==="round2"&&p&&typeof t.round2.progress=="number"&&e.jsxs("div",{className:"mt-1.5",children:[e.jsx("div",{className:"w-full h-1.5 bg-purple-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-purple-500 rounded-full transition-all duration-300",style:{width:`${t.round2.progress}%`}})}),e.jsx("p",{className:"text-xs text-purple-600 mt-0.5",children:s("bootstrap.round2Progress",{current:t.round2.current??0,total:t.round2.total??"?"})})]}),a==="round2"&&d&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round2Done",{refined:t.round2.refined??"?",total:t.round2.total??"?"})}),a==="round3"&&d&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round3Done",{afterDedup:t.round3.afterDedup??"?",relationsFound:t.round3.relationsFound??0})})]}),e.jsxs("div",{className:"flex-shrink-0",children:[p&&e.jsx(Ne,{className:"w-4 h-4 text-purple-500 animate-spin"}),d&&e.jsx(ot,{className:"w-4 h-4 text-emerald-500"})]})]},a)})})]})};function Ka(t){if(t<0)return"--";const s=Math.floor(t/1e3),a=Math.floor(s/60),r=s%60;return a===0?`${r}s`:`${a}m ${r.toString().padStart(2,"0")}s`}const Gc=({session:t,isAllDone:s,reviewState:a,onDismiss:r,onCancel:o,isCancelling:l=!1})=>{const{t:i}=Ae(),[p,d]=n.useState(Date.now());if(n.useEffect(()=>{if(!t||t.status!=="running")return;const A=setInterval(()=>d(Date.now()),1e3);return()=>clearInterval(A)},[t?.status]),!t)return null;const g=t.startedAt?p-t.startedAt:t.elapsedMs??0,x=t.completed+t.failed,h=t.total-x,u=t.elapsedMs??0,m=x>0&&u>0?Math.round(u/x*h):-1,c=t.totalToolCalls??0,j=t.status==="completed"?i("bootstrap.allCompleted"):t.status==="completed_with_errors"?i("bootstrap.completedWithErrors"):null;return e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] shadow-sm p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:i("bootstrap.title")}),j&&e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mt-0.5",children:j})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.status==="running"&&o&&e.jsxs("button",{onClick:o,disabled:l,className:"flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-lg border border-red-200 bg-red-50 hover:bg-red-100 text-red-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[l?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(bl,{size:14}),i("bootstrap.cancel")]}),s&&r&&e.jsx("button",{onClick:r,className:"text-sm px-3 py-1.5 rounded-lg bg-[var(--bg-subtle)] hover:bg-[var(--bg-subtle)] text-[var(--fg-secondary)] transition-colors",children:i("bootstrap.close")})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-5 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(Ye,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{children:[i("bootstrap.elapsed")," ",e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:Ka(g)})]})]}),t.status==="running"&&h>0&&m>0&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(Ye,{size:14,className:"text-blue-400"}),e.jsxs("span",{children:[i("bootstrap.estimatedRemaining")," ",e.jsx("span",{className:"font-medium text-blue-600",children:Ka(m)})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(Ks,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{children:[i("bootstrap.toolCalls")," ",e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:c})]})]}),e.jsx("div",{className:"text-[var(--fg-muted)] text-xs",children:i("bootstrap.dimensions",{done:x,total:t.total})})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:[...t.tasks].sort((A,D)=>{const I=Ha.indexOf(A.meta?.dimId??A.id),P=Ha.indexOf(D.meta?.dimId??D.id);return(I===-1?999:I)-(P===-1?999:P)}).map(A=>e.jsx(_c,{task:A},A.id))}),a&&a.activeRound>0&&e.jsx(Bc,{review:a})]})},cs={index:{icon:qe,color:"text-blue-600",label:"overview"},architecture:{icon:Ge,color:"text-violet-600",label:"architecture"},"getting-started":{icon:pt,color:"text-emerald-600",label:"getting-started"},protocols:{icon:Le,color:"text-amber-600",label:"protocols"},components:{icon:pt,color:"text-emerald-600",label:"components"},patterns:{icon:Le,color:"text-amber-600",label:"patterns"},module:{icon:Lt,color:"text-cyan-600",label:"module"},document:{icon:Qe,color:"text-orange-600",label:"document"},_index:{icon:Ys,color:"text-[var(--fg-secondary)]",label:"index"}};function $c(t){const s=t.split("/").pop()?.replace(".md","")||"";return s==="_index"?cs._index:t.startsWith("modules/")?cs.module:t.startsWith("documents/")?cs.document:cs[s]||{icon:Qe,color:"text-[var(--fg-secondary)]",label:"doc"}}const Oc={"cursor-devdocs":{label:"Cursor Docs",color:"text-orange-700",bg:"bg-orange-50 border-orange-200"}},Hc={modules:"modules",documents:"documents"};function en(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Kc(t){if(!t)return"";const s=new Date(t);if(isNaN(s.getTime()))return"";const r=Date.now()-s.getTime();return r<6e4?"just now":r<36e5?`${Math.floor(r/6e4)} min ago`:r<864e5?`${Math.floor(r/36e5)} hr ago`:r<6048e5?`${Math.floor(r/864e5)} d ago`:s.toLocaleDateString("zh-CN")}const qc=({task:t,wiki:s})=>{const{t:a}=Ae();return t.status==="running"?null:t.status==="error"?e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-red-100 rounded-lg",children:e.jsx(Et,{size:H.md,className:"text-red-600"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-red-800",children:a("wiki.genFailed")}),e.jsx("span",{className:"text-sm text-red-600 ml-3",children:t.error||a("common.operationFailed")})]})]}):s?.exists&&s.hasChanges?e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-amber-100 rounded-lg",children:e.jsx(Et,{size:H.md,className:"text-amber-600"})}),e.jsx("span",{className:"text-sm text-amber-700",children:a("wiki.outOfDateHint")})]}):null};function Uc(t,s){const a=[],r=new Map(s?.map(g=>[g.path,g])||[]),o=[],l=new Map;for(const g of t){const x=g.path.split("/"),h=r.get(g.path);if(x.length===1)o.push({name:x[0],path:g.path,isDir:!1,file:g,metaInfo:h});else{const u=x[0];l.has(u)||l.set(u,[]),l.get(u).push({name:x.slice(1).join("/"),path:g.path,isDir:!1,file:g,metaInfo:h})}}const i=["index.md","architecture.md","getting-started.md","patterns.md","protocols.md","components.md"];o.sort((g,x)=>{const h=i.indexOf(g.name),u=i.indexOf(x.name);return h!==-1&&u!==-1?h-u:h!==-1?-1:u!==-1?1:g.name.localeCompare(x.name)}),a.push(...o);const p=["modules","patterns","documents"],d=[...l.entries()].sort(([g],[x])=>{const h=p.indexOf(g),u=p.indexOf(x);return h!==-1&&u!==-1?h-u:h!==-1?-1:u!==-1?1:g.localeCompare(x)});for(const[g,x]of d){const h=x.filter(u=>!u.name.startsWith("_index")).sort((u,m)=>u.name.localeCompare(m.name));a.push({name:g,path:g,isDir:!0,children:h})}return a}const Wc=({tree:t,selectedFile:s,onSelect:a,searchQuery:r})=>{const[o,l]=n.useState(new Set(["modules","documents"])),i=g=>{l(x=>{const h=new Set(x);return h.has(g)?h.delete(g):h.add(g),h})},d=(g=>{if(!r)return g;const x=r.toLowerCase();return g.filter(h=>h.isDir?h.children?.some(u=>u.name.toLowerCase().includes(x)||u.path.toLowerCase().includes(x)):h.name.toLowerCase().includes(x)||h.path.toLowerCase().includes(x))})(t);return e.jsx("div",{className:"space-y-0.5",children:d.map(g=>{if(g.isDir){const x=o.has(g.path),h=r.toLowerCase(),u=r?g.children?.filter(m=>m.name.toLowerCase().includes(h)||m.path.toLowerCase().includes(h)):g.children;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>i(g.path),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)] rounded-lg transition-colors",children:[x?e.jsx(vt,{size:14,className:"text-[var(--fg-muted)] flex-shrink-0"}):e.jsx(Ue,{size:14,className:"text-[var(--fg-muted)] flex-shrink-0"}),e.jsx(Lt,{size:14,className:"text-amber-500 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Hc[g.name]||g.name}),e.jsx("span",{className:"ml-auto text-xs text-[var(--fg-muted)]",children:u?.length||0})]}),x&&u&&e.jsx("div",{className:"ml-3",children:u.map(m=>e.jsx(qa,{node:m,isActive:s===m.path,onSelect:a},m.path))})]},g.path)}return e.jsx(qa,{node:g,isActive:s===g.path,onSelect:a},g.path)})})},qa=({node:t,isActive:s,onSelect:a})=>{const r=$c(t.path),o=r.icon,l=t.metaInfo?.polished,i=t.metaInfo?.source;return e.jsxs("button",{onClick:()=>a(t.path),className:`w-full flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-all ${s?"bg-blue-50 text-blue-700 border border-blue-200 shadow-sm":"text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:[e.jsx(o,{size:14,className:`flex-shrink-0 ${s?"text-blue-500":r.color}`}),e.jsx("span",{className:"truncate text-left",children:t.name.replace(".md","")}),e.jsxs("span",{className:"ml-auto flex items-center gap-1 flex-shrink-0",children:[l&&e.jsx("span",{title:"AI Enhanced",children:e.jsx(Le,{size:10,className:"text-violet-400"})}),i&&e.jsx("span",{title:`Source: ${i}`,children:e.jsx(yl,{size:10,className:"text-orange-400"})})]})]})},Vc=({filePath:t,content:s,loading:a,meta:r,onBack:o})=>{const{t:l}=Ae(),[i,p]=n.useState(!1),d=r?.files?.find(u=>u.path===t),g=()=>{navigator.clipboard.writeText(s).catch(()=>{}),p(!0),setTimeout(()=>p(!1),2e3)},x=t.split("/"),h=x.map((u,m)=>({label:m===x.length-1?u.replace(".md",""):u,isLast:m===x.length-1}));return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:o,className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors lg:hidden",title:l("wiki.backToList"),children:e.jsx(vl,{size:H.md})}),e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(qe,{size:14,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"wiki"}),h.map((u,m)=>e.jsxs(it.Fragment,{children:[e.jsx(Ue,{size:12,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:u.isLast?"font-medium text-[var(--fg-primary)]":"text-[var(--fg-muted)]",children:u.label})]},m))]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d?.polished&&e.jsxs("span",{className:"flex items-center gap-1 text-xs text-violet-700 bg-violet-50 border border-violet-200 px-2 py-0.5 rounded-full",children:[e.jsx(Le,{size:10}),l("wiki.aiBadge")]}),d?.source&&(()=>{const u=Oc[d.source];return e.jsx("span",{className:`flex items-center gap-1 text-xs border px-2 py-0.5 rounded-full ${u?.bg||"bg-[var(--bg-subtle)] border-[var(--border-default)]"} ${u?.color||"text-[var(--fg-secondary)]"}`,children:u?.label||d.source})})(),e.jsxs("button",{onClick:g,className:"flex items-center gap-1 px-2.5 py-1 text-xs text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] hover:bg-[var(--bg-subtle)] rounded-md transition-colors",children:[i?e.jsx(ot,{size:12,className:"text-emerald-500"}):e.jsx(Rr,{size:12}),l(i?"wiki.copySuccess":"wiki.copyBtn")]})]})]}),e.jsx("div",{className:"flex-1 overflow-auto scrollbar-light",style:{scrollbarGutter:"stable"},children:a?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Ne,{size:H.xl,className:"text-blue-500 animate-spin"})}):e.jsx("div",{className:"px-4 xl:px-6 2xl:px-8 py-6 max-w-4xl mx-auto",children:e.jsx(Qt,{content:s,className:"wiki-reader"})})})]})},Jc=()=>{const{t}=Ae();return e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-[var(--bg-surface)] rounded-2xl border border-dashed border-[var(--border-default)] text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-[var(--bg-subtle)] flex items-center justify-center mb-4",children:e.jsx(qe,{size:32,className:"text-[var(--fg-muted)]"})}),e.jsx("p",{className:"text-sm font-medium text-[var(--fg-secondary)]",children:t("wiki.emptyTitle")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-[var(--fg-muted)]",children:t("wiki.emptyDesc")}),e.jsx("p",{className:"mt-3 text-[11px] text-[var(--fg-muted)]",children:t("wiki.emptyHint")})]})},Yc=({meta:t,onSelectFile:s,isGenerating:a,progress:r,message:o})=>{const{t:l}=Ae(),i=[{path:"index.md",label:l("wiki.quickOverview"),desc:l("wiki.quickOverviewDesc"),icon:qe,color:"bg-blue-50 text-blue-600 border-blue-200"},{path:"architecture.md",label:l("wiki.quickArch"),desc:l("wiki.quickArchDesc"),icon:Ge,color:"bg-violet-50 text-violet-600 border-violet-200"},{path:"getting-started.md",label:l("wiki.quickStart"),desc:l("wiki.quickStartDesc"),icon:pt,color:"bg-emerald-50 text-emerald-600 border-emerald-200"},{path:"protocols.md",label:l("wiki.quickProtocols"),desc:l("wiki.quickProtocolsDesc"),icon:Le,color:"bg-amber-50 text-amber-600 border-amber-200"}],p=new Set(t?.files?.map(g=>g.path||g.name)??[]),d=i.filter(g=>p.size===0||p.has(g.path));return e.jsxs("div",{className:"p-4 xl:p-6 2xl:p-8 overflow-y-auto flex-1",children:[a&&e.jsxs("div",{className:"mb-8 flex flex-col items-center",children:[e.jsxs("div",{className:"relative w-20 h-20 mb-5",children:[e.jsx("span",{className:"absolute inset-0 rounded-full bg-blue-100 animate-ping opacity-20"}),e.jsx("span",{className:"absolute inset-2 rounded-full bg-blue-50 animate-pulse"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(aa,{size:36,className:"text-blue-500 animate-pulse"})})]}),e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-1",children:l("wiki.wikiGenerating")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] max-w-md text-center leading-relaxed",children:o||l("wiki.generating")}),typeof r=="number"&&e.jsxs("div",{className:"mt-4 w-48",children:[e.jsx("div",{className:"w-full bg-[var(--bg-subtle)] rounded-full h-2",children:e.jsx("div",{className:"bg-gradient-to-r from-blue-500 to-indigo-500 h-2 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(r,3)}%`}})}),e.jsxs("p",{className:"text-xs text-center text-blue-500 mt-1.5 font-mono",children:[r,"%"]})]})]}),!a&&e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-12 h-12 bg-[var(--bg-subtle)] rounded-xl flex items-center justify-center mx-auto mb-3",children:e.jsx(Qe,{size:24,className:"text-[var(--fg-muted)]"})}),e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:l("wiki.selectFile")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mt-1",children:l("wiki.selectPlaceholder")})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 max-w-lg mx-auto",children:d.map(g=>{const x=g.icon;return e.jsxs("button",{onClick:()=>s(g.path),className:`text-left p-4 rounded-xl border ${g.color} hover:shadow-sm transition-all group`,children:[e.jsx(x,{size:20,className:"mb-2 opacity-70 group-hover:opacity-100"}),e.jsx("div",{className:"font-medium text-sm",children:g.label}),e.jsx("div",{className:"text-xs opacity-60 mt-0.5",children:g.desc})]},g.path)})}),t&&e.jsxs("div",{className:"mt-8 text-center text-xs text-[var(--fg-muted)]",children:[t.generatedAt&&`${l("wiki.lastGenerated")}: ${new Date(t.generatedAt).toLocaleString()}`,t.duration!=null&&` · ${l("wiki.duration")} ${en(t.duration)}`,t.version&&` · v${t.version}`]})]})},Qc=()=>{const{t}=Ae(),[s,a]=n.useState({task:{status:"idle"}}),[r,o]=n.useState([]),[l,i]=n.useState(!1),[p,d]=n.useState(null),[g,x]=n.useState(""),[h,u]=n.useState(!1),[m,c]=n.useState(!0),[j,A]=n.useState(""),[D,I]=n.useState(null),P=n.useRef(null),J=n.useCallback(async()=>{try{const q=await Q.wikiStatus();return a(q),q}catch{return null}},[]),w=n.useCallback(async()=>{try{const q=await Q.wikiFiles();o(q.files||[]),i(q.exists)}catch{}},[]),B=n.useCallback(async()=>{try{const q=await Q.wikiFileContent("meta.json");q?.content&&I(JSON.parse(q.content))}catch{}},[]);n.useEffect(()=>{(async()=>(c(!0),await Promise.all([J(),w(),B()]),c(!1)))()},[J,w,B]),n.useEffect(()=>{if(s.task.status==="running"){let q=0;P.current=setInterval(async()=>{const N=await J();q++,q%3===0&&await w(),N&&N.task.status!=="running"&&(await Promise.all([w(),B()]),P.current&&clearInterval(P.current))},1500)}else P.current&&clearInterval(P.current);return()=>{P.current&&clearInterval(P.current)}},[s.task.status,J,w,B]);const z=async()=>{try{await Q.wikiUpdate(),a(q=>({...q,task:{...q.task,status:"running",progress:0,message:t("wiki.incrementalUpdating")}}))}catch(q){console.error("Wiki update failed:",q)}},k=async q=>{if(q!=="meta.json"){d(q),u(!0);try{const N=await Q.wikiFileContent(q);x(N.content)}catch{x(`# ${t("wiki.loadFailed")}
|
|
108
108
|
|
|
109
|
-
${t("wiki.loadFailedDesc")}`)}finally{u(!1)}}},E=()=>{d(null),x("")},L=n.useMemo(()=>r.filter(q=>q.path!=="meta.json"),[r]),O=n.useMemo(()=>Uc(L,D?.files),[L,D]);if(m)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(Ne,{size:H.xl,className:"text-blue-500 animate-spin"})});const W=!l&&L.length===0&&s.task.status!=="running";return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden p-6 pt-4",children:[e.jsx(qc,{task:s.task,wiki:s.wiki}),W?e.jsx(Jc,{}):e.jsxs(e.Fragment,{children:[s.task.status==="running"&&e.jsxs("div",{className:"mb-3 flex items-center gap-3 px-4 py-2.5 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/70 rounded-xl shrink-0",children:[e.jsxs("div",{className:"relative flex items-center justify-center w-6 h-6",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-30 animate-ping"}),e.jsx(Ne,{size:16,className:"text-blue-600 animate-spin relative"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-blue-800",children:t("wiki.wikiGenerating")}),s.task.message&&e.jsx("span",{className:"text-xs text-blue-500 ml-2 truncate",children:s.task.message})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"w-24 bg-blue-100 rounded-full h-1.5",children:e.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(s.task.progress||0,3)}%`}})}),e.jsxs("span",{className:"text-xs font-mono text-blue-600 w-8 text-right",children:[s.task.progress||0,"%"]})]})]}),e.jsxs("div",{className:"flex gap-4 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:`w-64 flex-shrink-0 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl flex flex-col overflow-hidden ${p?"hidden lg:flex":""}`,children:[e.jsxs("div",{className:"px-3 pt-3 pb-2 border-b border-[var(--border-default)] shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{size:16,className:"text-blue-500"}),e.jsx("span",{className:"text-sm font-semibold text-[var(--fg-primary)]",children:"Wiki"}),D?.version&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["v",D.version]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[l&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("wiki.fileCount",{count:L.length})}),s.task.status!=="running"&&l&&e.jsx("button",{onClick:z,title:t("wiki.incrementalUpdate"),className:"p-1 rounded-md text-blue-500 hover:bg-blue-50 transition-colors",children:e.jsx(at,{size:13})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--fg-muted)]"}),e.jsx("input",{type:"text",placeholder:t("wiki.searchPlaceholder"),value:j,onChange:q=>A(q.target.value),className:"w-full pl-8 pr-3 py-2 text-sm bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-300 transition-all"})]})]}),e.jsxs("div",{className:"p-2 overflow-y-auto flex-1 min-h-0 scrollbar-light",children:[e.jsx(Wc,{tree:O,selectedFile:p,onSelect:k,searchQuery:j}),s.task.status==="running"&&e.jsxs("div",{className:"mx-2 mt-3 mb-1 flex items-center gap-2 px-3 py-2 bg-blue-50 border border-blue-100 rounded-lg",children:[e.jsx(Ne,{size:12,className:"text-blue-500 animate-spin flex-shrink-0"}),e.jsx("span",{className:"text-[11px] text-blue-600 leading-tight",children:t("wiki.generating")})]})]}),D?.generatedAt&&e.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-default)] shrink-0",children:e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-[var(--fg-muted)]",children:[e.jsx(Ye,{size:10}),e.jsx("span",{children:Kc(D.generatedAt)}),D.duration!=null&&e.jsxs("span",{children:["· ",en(D.duration)]})]})})]}),e.jsx("div",{className:`flex-1 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl overflow-hidden flex flex-col min-h-0 ${p?"":"hidden lg:flex"}`,children:p?e.jsx(Vc,{filePath:p,content:g,loading:h,meta:D,onBack:E}):e.jsx(Yc,{meta:D,onSelectFile:k,isGenerating:s.task.status==="running",progress:s.task.progress,message:s.task.message})})]})]})]})},Zc={guard:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",search:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",forge:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300",usage:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300",lifecycle:"bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300",quality:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",decay:"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300",context:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",anomaly:"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300",intent:"bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300",exploration:"bg-teal-100 text-teal-700 dark:bg-teal-900/30 dark:text-teal-300",panorama:"bg-sky-100 text-sky-700 dark:bg-sky-900/30 dark:text-sky-300"},Xc={governance:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300",compliance:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",metrics:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",analysis:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300"},ed=["time1h","time6h","time24h","time7d","timeAll"],td=[36e5,216e5,864e5,6048e5,0];function tn(t){const s=new Date(t),a=r=>String(r).padStart(2,"0");return`${a(s.getMonth()+1)}-${a(s.getDate())} ${a(s.getHours())}:${a(s.getMinutes())}:${a(s.getSeconds())}`}function sn(t,s){return s[t]??"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300"}function sd({signal:t}){const[s,a]=n.useState(!1);return e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-3 hover:bg-[var(--bg-muted)]/40 transition-colors cursor-pointer",onClick:()=>{a(!s)},children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-xs font-medium ${sn(t.type,Zc)}`,children:t.type}),e.jsx("span",{className:"text-[var(--fg-default)] font-medium truncate",children:t.source}),t.target&&e.jsxs("span",{className:"text-[var(--fg-subtle)] truncate",children:["→ ",t.target]}),e.jsxs("span",{className:"ml-auto shrink-0 tabular-nums text-xs text-[var(--fg-subtle)]",children:[(t.value*100).toFixed(0),"%"]}),e.jsx("span",{className:"shrink-0 text-xs text-[var(--fg-subtle)] tabular-nums",children:tn(t.timestamp)})]}),s&&t.metadata&&(typeof t.metadata=="object"&&!Array.isArray(t.metadata)?e.jsx("div",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs bg-[var(--bg-muted)] rounded p-2.5",children:Object.entries(t.metadata).map(([r,o])=>e.jsxs(it.Fragment,{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:r}),e.jsx("span",{className:"text-[var(--fg-default)] tabular-nums",children:typeof o=="object"?JSON.stringify(o):String(o)})]},r))}):e.jsx("pre",{className:"mt-2 text-xs text-[var(--fg-secondary)] bg-[var(--bg-muted)] rounded p-2.5 overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(t.metadata,null,2)}))]})}function ad({report:t}){const[s,a]=n.useState(!1);return e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-3 hover:bg-[var(--bg-muted)]/40 transition-colors cursor-pointer",onClick:()=>{a(!s)},children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-xs font-medium ${sn(t.category,Xc)}`,children:t.category}),e.jsx("span",{className:"text-[var(--fg-default)] font-medium truncate",children:t.type}),e.jsx("span",{className:"text-[var(--fg-subtle)] text-xs truncate",children:t.producer}),t.duration_ms!=null&&e.jsxs("span",{className:"text-xs text-[var(--fg-subtle)]",children:[t.duration_ms,"ms"]}),e.jsx("span",{className:"ml-auto shrink-0 text-xs text-[var(--fg-subtle)] tabular-nums",children:tn(t.timestamp)})]}),s&&(typeof t.data=="object"&&t.data&&!Array.isArray(t.data)?e.jsx("div",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs bg-[var(--bg-muted)] rounded p-2.5",children:Object.entries(t.data).map(([r,o])=>e.jsxs(it.Fragment,{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:r}),e.jsx("span",{className:"text-[var(--fg-default)] tabular-nums",children:typeof o=="object"?JSON.stringify(o):String(o)})]},r))}):e.jsx("pre",{className:"mt-2 text-xs text-[var(--fg-secondary)] bg-[var(--bg-muted)] rounded p-2.5 overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(t.data,null,2)}))]})}function Ua({label:t,value:s,max:a}){const r=a>0?Math.round(s/a*100):0;return e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"w-24 truncate text-[var(--fg-subtle)]",children:t}),e.jsx("div",{className:"flex-1 h-2 rounded-full bg-[var(--bg-muted)] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--accent)] transition-all duration-300",style:{width:`${r}%`}})}),e.jsx("span",{className:"w-12 text-right text-xs tabular-nums text-[var(--fg-subtle)]",children:s})]})}const rd=()=>{const{t}=Ae(),[s,a]=n.useState("signals"),[r,o]=n.useState(2),[l,i]=n.useState(""),[p,d]=n.useState(!1),[g,x]=n.useState(null),[h,u]=n.useState([]),[m,c]=n.useState(0),[j,A]=n.useState([]),[D,I]=n.useState(0),[P,J]=n.useState(null),w=n.useMemo(()=>{const k=td[r];return k===0?{}:{from:Date.now()-k}},[r]),B=n.useCallback(async()=>{d(!0),x(null);try{if(s==="signals"){const k=l?l.split(",").map(L=>L.trim()).filter(Boolean):void 0,E=await Q.getSignalTrace({...w,type:k,limit:100});u(E.signals),c(E.total)}else if(s==="reports"){const k=await Q.getReports({...w,limit:50});A(k.reports),I(k.total)}else{const k=await Q.getSignalStats(w);J(k)}}catch(k){x(ke(k))}finally{d(!1)}},[s,w,l]);n.useEffect(()=>{B()},[B]);const z=n.useMemo(()=>{if(!P)return 1;const k=Object.values(P.byType);return Math.max(...k,1)},[P]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yt,{size:20,className:"text-[var(--accent)]"}),e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-default)]",children:t("signals.title")})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s==="signals"&&e.jsxs("div",{className:"relative",children:[e.jsx(sa,{size:13,className:"absolute left-2 top-1/2 -translate-y-1/2 text-[var(--fg-subtle)]"}),e.jsx("input",{type:"text",placeholder:t("signals.filterPlaceholder"),value:l,onChange:k=>{i(k.target.value)},className:"pl-7 pr-2 py-1.5 text-xs rounded-lg border border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--fg-default)] w-40"})]}),e.jsx("div",{className:"flex items-center gap-1",children:[["signals",e.jsx(Be,{size:13},"s"),t("signals.tabSignals")],["reports",e.jsx(Qe,{size:13},"r"),t("signals.tabReports")],["stats",e.jsx(Tt,{size:13},"st"),t("signals.tabStats")]].map(([k,E,L])=>e.jsxs("button",{type:"button",onClick:()=>{a(k)},className:`flex items-center gap-1 px-4 py-1.5 rounded-md text-xs font-medium transition-colors ${s===k?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:[E,L]},k))}),e.jsx("div",{className:"flex items-center gap-1",children:ed.map((k,E)=>e.jsx("button",{type:"button",onClick:()=>{o(E)},className:`px-4 py-1.5 rounded-md text-xs font-medium transition-colors ${r===E?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:t(`signals.${k}`)},k))}),e.jsxs("button",{type:"button",onClick:B,disabled:p,className:"flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-lg border border-[var(--border-default)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] transition-colors disabled:opacity-50",children:[p?e.jsx(Ne,{size:13,className:"animate-spin"}):e.jsx(at,{size:13}),t("signals.refresh")]})]})]}),g&&e.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm rounded-lg bg-red-50 text-red-700 dark:bg-red-900/20 dark:text-red-300",children:[e.jsx(st,{size:16}),g]}),p&&!h.length&&!j.length&&!P?e.jsxs("div",{className:"flex items-center justify-center py-20 text-[var(--fg-subtle)]",children:[e.jsx(Ne,{size:24,className:"animate-spin mr-2"}),t("signals.loading")]}):s==="signals"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)]",children:t("signals.showingSignals",{shown:h.length,total:m})}),h.length===0?e.jsxs("div",{className:"text-center py-12 text-[var(--fg-subtle)]",children:[e.jsx(js,{size:32,className:"mx-auto mb-2 opacity-40"}),e.jsx("p",{children:t("signals.noSignals")})]}):e.jsx("div",{className:"space-y-1.5",children:h.map((k,E)=>e.jsx(sd,{signal:k},`${k.timestamp}-${E}`))})]}):s==="reports"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)]",children:t("signals.showingReports",{shown:j.length,total:D})}),j.length===0?e.jsxs("div",{className:"text-center py-12 text-[var(--fg-subtle)]",children:[e.jsx(Qe,{size:32,className:"mx-auto mb-2 opacity-40"}),e.jsx("p",{children:t("signals.noReports")})]}):e.jsx("div",{className:"space-y-1.5",children:j.map(k=>e.jsx(ad,{report:k},k.id))})]}):e.jsx("div",{className:"space-y-6",children:P?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)] mb-1",children:t("signals.totalSignals")}),e.jsx("div",{className:"text-2xl font-bold text-[var(--fg-default)] tabular-nums",children:P.total})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)] mb-1",children:t("signals.signalTypes")}),e.jsx("div",{className:"text-2xl font-bold text-[var(--fg-default)] tabular-nums",children:Object.keys(P.byType).length})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)] mb-1",children:t("signals.sources")}),e.jsx("div",{className:"text-2xl font-bold text-[var(--fg-default)] tabular-nums",children:Object.keys(P.bySource).length})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("h3",{className:"text-sm font-medium text-[var(--fg-default)] mb-3",children:t("signals.byType")}),e.jsx("div",{className:"space-y-2",children:Object.entries(P.byType).sort((k,E)=>E[1]-k[1]).map(([k,E])=>e.jsx(Ua,{label:k,value:E,max:z},k))})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("h3",{className:"text-sm font-medium text-[var(--fg-default)] mb-3",children:t("signals.bySource")}),e.jsx("div",{className:"space-y-2",children:Object.entries(P.bySource).sort((k,E)=>E[1]-k[1]).slice(0,15).map(([k,E])=>e.jsx(Ua,{label:k,value:E,max:z},k))})]})]}):e.jsxs("div",{className:"text-center py-12 text-[var(--fg-subtle)]",children:[e.jsx(Tt,{size:32,className:"mx-auto mb-2 opacity-40"}),e.jsx("p",{children:t("signals.noStats")})]})})]})},nd={authority:0,guardUsageCount:0,humanUsageCount:0,aiUsageCount:0,lastUsedAt:null,authorityScore:0},ld=({editingRecipe:t,setEditingRecipe:s,handleSaveRecipe:a,closeRecipeEdit:r,isSavingRecipe:o=!1})=>{const{t:l}=Ae(),[i,p]=n.useState("preview"),d=n.useRef(!0);n.useEffect(()=>()=>{d.current=!1},[]);const g=(()=>{const u=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(u)?"objectivec":t.language||"text"})(),x=async u=>{try{if(await Q.setRecipeAuthority(t.name,u),d.current){const m=t.stats?{...t.stats,authority:u}:{...nd,authority:u};s({...t,stats:m})}}catch(m){console.warn(l("recipeEditor.authorityFailed"),ke(m))}},h=u=>{if(!u)return"";const m=typeof u=="string"?new Date(u).getTime():u;return isNaN(m)?"":new Date(m).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})};return e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] w-full max-w-6xl rounded-2xl shadow-2xl flex flex-col h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-[var(--border-default)] flex justify-between items-center flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-bold",children:l("recipeEditor.title")}),t.kind&&(()=>{const m={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:Ve},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:St},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:qe}}[t.kind];if(!m)return null;const c=m.icon;return e.jsxs("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase flex items-center gap-1 border ${m.bg} ${m.color} ${m.border}`,children:[e.jsx(c,{size:H.sm}),m.label]})})(),t.status&&t.status!=="active"&&t.status!=="published"&&e.jsx("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase border ${t.status==="draft"?"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border-[var(--border-default)]":t.status==="archived"?"bg-orange-50 text-orange-600 border-orange-200":"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border-[var(--border-default)]"}`,children:t.status})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-[var(--fg-muted)]",children:l("recipeEditor.authorityScore")}),i==="preview"?e.jsx("span",{className:"text-sm text-[var(--fg-primary)]",children:t.stats?.authority??3}):e.jsx(tt,{value:String(t.stats?.authority??3),onChange:u=>x(parseInt(u)),options:[{value:"1",label:`1 - ${l("recipeEditor.qualityLevels.basic")}`,icon:"⭐"},{value:"2",label:`2 - ${l("recipeEditor.qualityLevels.good")}`,icon:"⭐⭐"},{value:"3",label:`3 - ${l("recipeEditor.qualityLevels.solid")}`,icon:"⭐⭐⭐"},{value:"4",label:`4 - ${l("recipeEditor.qualityLevels.great")}`,icon:"⭐⭐⭐⭐"},{value:"5",label:`5 - ${l("recipeEditor.qualityLevels.excellent")}`,icon:"⭐⭐⭐⭐⭐"}],size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]}),e.jsxs("div",{className:"flex bg-[var(--bg-subtle)] p-1 rounded-lg mr-4",children:[e.jsxs("button",{onClick:()=>p("preview"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${i==="preview"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx(Ut,{size:H.sm})," ",l("recipeEditor.preview")]}),e.jsxs("button",{onClick:()=>p("edit"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${i==="edit"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx(It,{size:H.sm})," ",l("recipeEditor.edit")]})]}),e.jsx("button",{onClick:r,className:"p-2 hover:bg-[var(--bg-subtle)] rounded-full",children:e.jsx(ze,{size:H.lg})})]})]}),e.jsx("div",{className:"p-6 space-y-4 flex-1 flex flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:i==="edit"?e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-5 pr-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:l("recipeEditor.path")}),e.jsx("input",{className:"w-full p-2 bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg text-sm",value:t.name,onChange:u=>s({...t,name:u.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:l("recipeEditor.description")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-none",rows:2,value:t.description||"",onChange:u=>s({...t,description:u.target.value}),placeholder:l("recipeEditor.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-blue-400"})," ",l("recipeEditor.markdown")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ys,{value:t.content?.markdown||"",onChange:u=>s({...t,content:{...t.content,markdown:u}}),language:"markdown",height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(At,{size:11,className:"text-emerald-500"})," ",l("recipeEditor.code")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ys,{value:t.content?.pattern||"",onChange:u=>s({...t,content:{...t.content,pattern:u}}),language:g,height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:l("recipeEditor.rationale")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-y",rows:3,value:t.content?.rationale||"",onChange:u=>s({...t,content:{...t.content,rationale:u.target.value}}),placeholder:l("recipeEditor.rationalePlaceholder")})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-6 scrollbar-light",children:[(()=>{const u=[["trigger",t.trigger],["language",t.language],["category",t.category],["kind",t.kind],["knowledgeType",t.knowledgeType],["status",t.status],["complexity",t.complexity],["scope",t.scope],["source",t.source],["updatedAt",t.updatedAt?h(t.updatedAt):void 0]].filter(([,m])=>!!m);return u.length===0?null:e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-4",children:"Recipe Metadata"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-y-4 gap-x-8",children:u.map(([m,c])=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold uppercase mb-1",children:m}),e.jsx("span",{className:"text-sm text-[var(--fg-primary)] break-all font-medium",children:c})]},m))})]})})(),t.description&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.description")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.description})]}),t.content?.markdown&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-blue-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-blue-400"})," ",l("recipeEditor.markdown")]}),e.jsx("div",{className:"bg-blue-50/30 border border-blue-100 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-[var(--fg-primary)] leading-relaxed",children:e.jsx(Qt,{content:t.content.markdown})})})]}),t.content?.pattern&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-emerald-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(At,{size:11,className:"text-emerald-500"})," ",l("recipeEditor.code")]}),e.jsx(ft,{code:t.content.pattern,language:g,showLineNumbers:!0})]}),t.content?.rationale&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.rationale")}),e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.content.rationale})})]}),t.content?.steps&&t.content.steps.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.steps")}),e.jsx("div",{className:"space-y-2",children:t.content.steps.map((u,m)=>typeof u=="string"?e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)] flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:m+1}),e.jsx("p",{className:"text-xs text-[var(--fg-primary)] leading-relaxed",children:u})]},m):e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:m+1}),u.title&&e.jsx("span",{className:"text-xs font-bold text-[var(--fg-primary)]",children:u.title})]}),u.description&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] ml-7 leading-relaxed",children:u.description}),u.code&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:u.code})]},m))})]}),t.content?.codeChanges&&t.content.codeChanges.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.codeChanges")}),e.jsx("div",{className:"space-y-2",children:t.content.codeChanges.map((u,m)=>e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex items-center gap-2",children:[e.jsx(pt,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-[var(--fg-secondary)]",children:u.file})]}),u.explanation&&e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)] px-3 py-1.5 border-b border-[var(--border-default)] bg-yellow-50/30",children:u.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words font-mono",children:u.before||l("recipes.emptyValue")})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/20",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:"After"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-primary)] whitespace-pre-wrap break-words font-mono",children:u.after})]})]},m))})]}),t.content?.verification&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-teal-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.validation")}),e.jsxs("div",{className:"bg-teal-50/50 border border-teal-100 rounded-xl p-4 space-y-1.5",children:[t.content.verification.method&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-teal-600",children:l("recipeEditor.validationMethod")})," ",t.content.verification.method]}),t.content.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-teal-600",children:l("recipeEditor.validationExpected")})," ",t.content.verification.expectedResult]}),t.content.verification.testCode&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md overflow-x-auto whitespace-pre-wrap mt-1",children:t.content.verification.testCode})]})]}),t.tags&&t.tags.length>0&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-3 flex items-center gap-1.5",children:[e.jsx(jr,{size:11,className:"text-blue-400"})," ",l("recipeEditor.tags")]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map((u,m)=>e.jsx("span",{className:"px-2.5 py-1 bg-blue-50 text-blue-700 border border-blue-100 rounded-full text-xs font-medium",children:u},m))})]}),!!(t.constraints&&(t.constraints.guards?.length||t.constraints.boundaries?.length||t.constraints.preconditions?.length||t.constraints.sideEffects?.length))&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6 space-y-4",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest flex items-center gap-1.5",children:[e.jsx(Ve,{size:11,className:"text-amber-500"})," ",l("recipeEditor.constraints")]}),t.constraints.guards&&t.constraints.guards.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.guardRules")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.guards.map((u,m)=>e.jsxs("li",{className:"flex gap-2 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${u.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-xs bg-[var(--bg-subtle)] px-1.5 py-0.5 rounded",children:u.pattern}),u.message&&e.jsxs("span",{className:"text-xs text-[var(--fg-muted)]",children:["— ",u.message]})]},m))})]}),t.constraints.boundaries&&t.constraints.boundaries.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.boundaryConstraints")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.boundaries.map((u,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),u]},m))})]}),t.constraints.preconditions&&t.constraints.preconditions.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.preconditions")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.preconditions.map((u,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),u]},m))})]}),t.constraints.sideEffects&&t.constraints.sideEffects.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.sideEffects")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.sideEffects.map((u,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),u]},m))})]})]}),t.relations&&Object.entries(t.relations).some(([,u])=>Array.isArray(u)&&u.length>0)&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-4",children:l("recipeEditor.relations")}),e.jsx("div",{className:"space-y-2",children:[{key:"inherits",label:l("recipeEditor.relationTypes.inherits"),color:"text-green-600",icon:"↑"},{key:"implements",label:l("recipeEditor.relationTypes.implements"),color:"text-blue-600",icon:"◇"},{key:"calls",label:l("recipeEditor.relationTypes.calls"),color:"text-cyan-600",icon:"→"},{key:"dependsOn",label:l("recipeEditor.relationTypes.dependsOn"),color:"text-yellow-600",icon:"⊕"},{key:"dataFlow",label:l("recipeEditor.relationTypes.dataFlow"),color:"text-purple-600",icon:"⇢"},{key:"conflicts",label:l("recipeEditor.relationTypes.conflicts"),color:"text-red-600",icon:"✕"},{key:"extends",label:l("recipeEditor.relationTypes.extends"),color:"text-teal-600",icon:"⊃"},{key:"related",label:l("recipeEditor.relationTypes.associates"),color:"text-[var(--fg-muted)]",icon:"∼"}].map(({key:u,label:m,color:c,icon:j})=>{const A=t.relations?.[u];return!A||!Array.isArray(A)||A.length===0?null:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:`text-xs font-mono ${c} shrink-0 whitespace-nowrap pt-0.5`,children:[j," ",m]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:A.map((D,I)=>e.jsx("span",{className:"px-2 py-0.5 bg-[var(--bg-surface)] border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-lg text-xs font-mono",children:typeof D=="string"?D:D.id||D.title||JSON.stringify(D)},I))})]},u)})})]}),!t.content?.markdown&&!t.content?.pattern&&!t.description&&e.jsx("div",{className:"bg-[var(--bg-surface)] p-8 rounded-2xl border border-[var(--border-default)] shadow-sm min-h-[200px] flex items-center justify-center",children:e.jsx("div",{className:"text-[var(--fg-muted)] italic",children:l("recipeEditor.noContent")})})]})})}),e.jsxs("div",{className:"p-6 border-t border-[var(--border-default)] flex justify-end gap-3",children:[e.jsx("button",{onClick:r,disabled:o,className:"px-4 py-2 text-[var(--fg-secondary)] font-medium disabled:opacity-50",children:l("recipeEditor.cancel")}),e.jsxs("button",{onClick:a,disabled:o,className:"px-6 py-2 bg-blue-600 text-white rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 disabled:opacity-60 disabled:cursor-not-allowed",children:[o?e.jsx(Ne,{size:H.lg,className:"animate-spin"}):e.jsx(ws,{size:H.lg}),l(o?"recipeEditor.saving":"recipeEditor.saveChanges")]})]})]})]})},od=({setShowCreateModal:t,createPath:s,setCreatePath:a,handleCreateFromPath:r,handleCreateFromClipboard:o,isExtracting:l})=>{const{t:i}=Ae();return e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden bg-[var(--bg-surface)]",children:[e.jsxs("div",{className:"p-6 border-b flex justify-between items-center bg-[var(--bg-subtle)] border-[var(--border-default)]",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx(mt,{size:H.xl,className:"text-blue-600"})," ",i("createModal.title")]}),e.jsx("button",{onClick:()=>t(!1),className:"p-2 rounded-full transition-all duration-150 text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] hover:text-[var(--fg-primary)]",children:e.jsx(ze,{size:H.lg})})]}),e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(va,{size:H.sm})," ",i("createModal.importFromPath")]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:"flex-1 p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] border bg-[var(--bg-subtle)] border-[var(--border-default)] text-[var(--fg-primary)]",placeholder:i("createModal.pathPlaceholder"),value:s,onChange:p=>a(p.target.value)}),e.jsxs("button",{onClick:r,disabled:!s||l,className:"px-5 py-2 rounded-xl text-sm font-bold whitespace-nowrap disabled:opacity-40 transition-all duration-150 bg-[var(--accent)] text-white hover:opacity-90 shadow-sm",children:[e.jsx(va,{size:14,className:"inline -mt-0.5 mr-1"}),i("createModal.scanFile")]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:"w-full border-t border-[var(--border-default)]"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"px-2 font-bold bg-[var(--bg-surface)] text-[var(--fg-muted)]",children:i("createModal.or")})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(jl,{size:H.sm})," ",i("createModal.importFromClipboard")]}),e.jsxs("button",{onClick:()=>o(),disabled:l,className:"w-full flex items-center justify-center gap-3 p-4 rounded-xl font-bold transition-all duration-150 border bg-[var(--accent-subtle)] text-[var(--accent)] border-[var(--accent-emphasis)]/20 hover:bg-[var(--accent-emphasis)]/10",children:[e.jsx(Be,{size:H.lg})," ",i("createModal.useClipboard")]})]})]}),l&&e.jsxs("div",{className:"bg-blue-600 text-white p-4 flex items-center justify-center gap-3 animate-pulse",children:[e.jsx(Jt,{size:H.lg,className:"animate-spin"}),e.jsx("span",{className:"font-bold text-sm",children:i("createModal.aiThinking")})]})]})]})};function id(t){if(!t)return"";if(typeof t=="object"){const o=t.code||t.pattern||t.markdown||t.snippet||t.body||"";if(o)return o}const a=(typeof t=="string"?t:JSON.stringify(t)).replace(/^---[\s\S]*?---\s*\n?/,"").trim(),r=a.match(/```[\w]*\n([\s\S]*?)```/);return r&&r[1]?r[1].trim():a.slice(0,8e3)}const cd=({searchQ:t,insertPath:s,onClose:a})=>{const{t:r}=Ae(),[o,l]=n.useState([]),[i,p]=n.useState(!0),[d,g]=n.useState(null),x=n.useRef(!0),h=n.useRef(null);n.useEffect(()=>(x.current=!0,h.current=new AbortController,Q.search(t||"",{mode:"auto",type:"recipe",signal:h.current.signal}).then(m=>{x.current&&l((m.items||[]).map(c=>({name:(c.title||c.name||"")+".md",path:"",content:c.content,qualityScore:(c.quality||{}).overall||c.qualityScore||0,recommendReason:""})))}).catch(m=>{m.name!=="AbortError"&&x.current&&l([])}).finally(()=>{x.current&&p(!1)}),()=>{x.current=!1,h.current&&h.current.abort()}),[t]);const u=async m=>{g(m.name);try{const c=id(m.content);await Q.insertAtSearchMark({path:s,content:c}),x.current&&(alert(r("searchModal.insertSuccess")+" "+s),a())}catch{x.current&&alert(r("searchModal.insertFailed"))}finally{x.current&&g(null)}};return e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-[var(--border-default)] flex justify-between items-center bg-[var(--bg-subtle)]",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx(xt,{size:H.xl,className:"text-blue-600"})," ",r("searchModal.title")]}),e.jsx("button",{onClick:a,className:"p-2 hover:bg-[var(--bg-surface)] rounded-full transition-colors",children:e.jsx(ze,{size:H.lg})})]}),e.jsxs("div",{className:"p-4 text-sm text-[var(--fg-muted)] border-b border-[var(--border-default)]",children:[r("searchModal.keyword")," ",t||r("searchModal.keywordAll")," · ",r("searchModal.insertTo")," ",s]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:i?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):o.length===0?e.jsx("div",{className:"text-[var(--fg-muted)] text-center py-8",children:r("searchModal.noResults")}):e.jsx("ul",{className:"space-y-2",children:o.map(m=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>u(m),disabled:d!==null,className:"w-full flex items-center justify-between gap-3 p-4 rounded-xl border border-[var(--border-default)] hover:border-[var(--accent-emphasis)] hover:bg-[var(--accent-subtle)]/50 transition-all text-left disabled:opacity-50",children:[e.jsxs("div",{className:"flex-1 flex flex-col gap-1",children:[e.jsx("span",{className:"font-medium text-[var(--fg-primary)] truncate",children:m.name}),(m.qualityScore!==void 0||m.recommendReason)&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[m.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",r("searchModal.quality")," ",(m.qualityScore*100).toFixed(0),"%"]}),m.recommendReason&&e.jsx("span",{className:"text-xs text-[var(--fg-secondary)] italic truncate max-w-xs",children:m.recommendReason})]})]}),d===m.name?e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⏳"})," ",r("searchModal.inserting")]}):e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx(kr,{size:H.md})," ",r("searchModal.insertBtn")]})]})},m.name))})})]})]})},Bs=[{id:"google",labelKey:"llmConfig.providers.gemini",defaultModel:"gemini-2.0-flash",keyEnv:"ASD_GOOGLE_API_KEY"},{id:"openai",labelKey:"llmConfig.providers.openai",defaultModel:"gpt-4o",keyEnv:"ASD_OPENAI_API_KEY"},{id:"deepseek",labelKey:"llmConfig.providers.deepseek",defaultModel:"deepseek-chat",keyEnv:"ASD_DEEPSEEK_API_KEY"},{id:"claude",labelKey:"llmConfig.providers.claude",defaultModel:"claude-3-5-sonnet-20240620",keyEnv:"ASD_CLAUDE_API_KEY"},{id:"ollama",labelKey:"llmConfig.providers.ollama",defaultModel:"llama3",keyEnv:""}],dd=({onClose:t,onSaved:s})=>{const{t:a}=Ae(),[r,o]=n.useState(!0),[l,i]=n.useState(!1),[p,d]=n.useState(!1),[g,x]=n.useState("google"),[h,u]=n.useState("gemini-2.0-flash"),[m,c]=n.useState(""),[j,A]=n.useState(""),[D,I]=n.useState(!1),[P,J]=n.useState({}),[w,B]=n.useState(!1);n.useEffect(()=>{z()},[]);const z=async()=>{o(!0);try{const N=await Q.getLlmEnvConfig();d(N.hasEnvFile);const v=N.vars||{};v.ASD_AI_PROVIDER&&x(v.ASD_AI_PROVIDER),v.ASD_AI_MODEL&&u(v.ASD_AI_MODEL),v.ASD_AI_PROXY&&A(v.ASD_AI_PROXY),J(v)}catch{}finally{o(!1)}},k=Bs.find(N=>N.id===g),E=k?.keyEnv||"",L=E?!!P[E]:!0,O=N=>{x(N);const v=Bs.find(U=>U.id===N);v&&u(v.defaultModel),c("")},W=async()=>{if(g){if(E&&!L&&!m.trim()){alert(a("llmConfig.apiKeyRequired"));return}i(!0),B(!1);try{await Q.saveLlmEnvConfig({provider:g,model:h||void 0,apiKey:m.trim()||void 0,proxy:j.trim()||void 0}),B(!0),setTimeout(()=>{s(),t()},800)}catch(N){alert(ke(N,a("llmConfig.saveFailed")))}finally{i(!1)}}},q=N=>!N||N.length<10?N?"••••••":"":`${N.slice(0,6)}••••${N.slice(-4)}`;return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50",onClick:t,children:e.jsxs("div",{className:"rounded-2xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden bg-[var(--bg-surface)]",onClick:N=>N.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:a("llmConfig.title")}),e.jsx("button",{onClick:t,className:"p-1 rounded-lg transition-all duration-150 hover:bg-[var(--bg-subtle)] text-[var(--fg-muted)] hover:text-[var(--fg-primary)]",children:e.jsx(ze,{size:H.md})})]}),e.jsx("div",{className:"px-6 py-5 space-y-5",children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ne,{size:24,className:"animate-spin text-blue-500"})}):e.jsxs(e.Fragment,{children:[!p&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-700",children:[e.jsx(st,{size:16,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:a("llmConfig.envWarning")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2 text-[var(--fg-primary)]",children:a("llmConfig.provider")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Bs.map(N=>e.jsx("button",{type:"button",onClick:()=>O(N.id),className:`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${g===N.id?"bg-[var(--accent-subtle)] border-[var(--accent-emphasis)] text-[var(--accent)] ring-1 ring-[var(--accent-emphasis)]/30":"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]"}`,children:a(N.labelKey)},N.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:a("llmConfig.model")}),e.jsx("input",{type:"text",value:h,onChange:N=>u(N.target.value),placeholder:k?.defaultModel||"",className:"w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]}),E&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:[a("llmConfig.apiKey"),L&&e.jsxs("span",{className:"ml-2 text-xs text-green-600 font-normal",children:["(",a("llmConfig.configured")," ",q(P[E]),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:D?"text":"password",value:m,onChange:N=>c(N.target.value),placeholder:a(L?"llmConfig.apiKeyPlaceholderSet":"llmConfig.apiKeyPlaceholderEmpty"),className:"w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"}),e.jsx("button",{type:"button",onClick:()=>I(N=>!N),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",children:D?e.jsx(wl,{size:16}):e.jsx(Ut,{size:16})})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:[a("llmConfig.proxy")," ",e.jsx("span",{className:"text-xs font-normal text-[var(--fg-muted)]",children:a("llmConfig.optional")})]}),e.jsx("input",{type:"text",value:j,onChange:N=>A(N.target.value),placeholder:"http://127.0.0.1:7890",className:"w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]})]})}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-[var(--border-default)] bg-[var(--bg-subtle)]",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm font-medium transition-colors text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]",children:a("llmConfig.cancel")}),e.jsxs("button",{onClick:W,disabled:l||r||w,className:`flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-medium transition-all ${w?"bg-green-500 text-white":"bg-blue-600 text-white hover:bg-blue-700 shadow-sm"} disabled:opacity-60`,children:[l?e.jsx(Ne,{size:16,className:"animate-spin"}):w?e.jsx(ht,{size:16}):e.jsx(ws,{size:16}),a(w?"llmConfig.saved":"llmConfig.saveToEnv")]})]})]})})},Wa=200,ud=({open:t,onClose:s})=>{const{t:a}=Ae(),[r,o]=n.useState([]),[l,i]=n.useState(!1),[p,d]=n.useState(""),g=n.useRef(null);n.useEffect(()=>{if(!t)return;let D=!1;Q.getSignalTrace({limit:100}).then(J=>{if(D)return;const w=J.signals.map(B=>({type:B.type,source:B.source,target:B.target,value:B.value,metadata:B.metadata,timestamp:B.timestamp}));o(w)}).catch(()=>{});const I=Cs(),P=J=>{l||o(w=>{const B=[J,...w];return B.length>Wa?B.slice(0,Wa):B})};return I.on("signal:event",P),()=>{D=!0,I.off("signal:event",P)}},[t,l]);const x=p?r.filter(D=>D.type.toLowerCase().includes(p.toLowerCase())||D.source.toLowerCase().includes(p.toLowerCase())):r,h={guard:"text-red-500",search:"text-blue-500",usage:"text-green-500",lifecycle:"text-purple-500",exploration:"text-cyan-500",quality:"text-yellow-500",panorama:"text-indigo-500",decay:"text-orange-500",forge:"text-pink-500"},u={guard:"#ef4444",search:"#3b82f6",usage:"#22c55e",lifecycle:"#a855f7",decay:"#f97316"},m=["guard","search","usage","lifecycle","decay"],c=50,j=n.useMemo(()=>{const D={};for(const P of m)D[P]=0;for(const P of r)P.type in D&&D[P.type]++;const I=Math.max(1,...Object.values(D));return{counts:D,max:I}},[r]),A=n.useMemo(()=>{const D=[];for(const I of m)j.counts[I]>c&&D.push(`${I} 信号量过高 (${j.counts[I]})`);if(r.length>0){const I=r[0].timestamp;Date.now()-I>300*1e3&&D.push("超过 5 分钟未收到新信号")}else t&&D.push("尚未收到任何信号");return D},[r,j,t]);return t?e.jsxs("div",{className:"fixed right-0 top-0 h-full w-80 glass-surface border-l border-[var(--border-muted)] shadow-xl z-50 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-[var(--border-muted)]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"w-4 h-4 text-[var(--accent)]"}),e.jsx("span",{className:"text-sm font-semibold text-[var(--text-primary)]",children:"Signal Monitor"}),e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-[var(--accent)]/10 text-[var(--accent)]",children:r.length})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>i(!l),className:`p-1 rounded text-xs ${l?"text-red-500":"text-green-500"} hover:bg-[var(--bg-elevated)]`,children:l?"▶":"⏸"}),e.jsx("button",{onClick:()=>o([]),className:"p-1 rounded text-xs text-[var(--text-tertiary)] hover:bg-[var(--bg-elevated)]",children:"Clear"}),e.jsx("button",{onClick:s,className:"p-1 rounded text-[var(--text-tertiary)] hover:bg-[var(--bg-elevated)]",children:e.jsx(ze,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"p-2 border-b border-[var(--border-muted)]",children:e.jsx("input",{type:"text",value:p,onChange:D=>d(D.target.value),placeholder:"Filter by type or source...",className:"w-full px-2 py-1 text-xs rounded bg-[var(--bg-elevated)] text-[var(--text-primary)] border border-[var(--border-muted)] focus:outline-none focus:border-[var(--accent)]"})}),e.jsx("div",{ref:g,className:"flex-1 overflow-y-auto min-h-0",children:x.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-[var(--text-tertiary)]",children:[e.jsx(js,{className:"w-5 h-5 mb-2 opacity-50"}),e.jsx("span",{className:"text-xs",children:"Waiting for signals..."})]}):e.jsx("div",{className:"divide-y divide-[var(--border-muted)]",children:x.map((D,I)=>e.jsxs("div",{className:"p-2 hover:bg-[var(--bg-elevated)] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`text-xs font-mono font-semibold ${h[D.type]??"text-[var(--text-secondary)]"}`,children:D.type}),e.jsx("span",{className:"text-[10px] text-[var(--text-tertiary)]",children:new Date(D.timestamp).toLocaleTimeString()})]}),e.jsx("div",{className:"text-[11px] text-[var(--text-tertiary)] mt-0.5 truncate",children:D.source})]},`${D.type}-${D.timestamp}-${I}`))})}),e.jsxs("div",{className:"border-t border-[var(--border-muted)] p-3 shrink-0",children:[e.jsx("h3",{className:"text-xs font-medium text-[var(--fg-muted)] uppercase tracking-wider mb-2",children:"Signal Statistics"}),e.jsx("div",{className:"space-y-1.5",children:m.map(D=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono w-14 text-[var(--text-tertiary)] text-right",children:D}),e.jsx("div",{className:"flex-1 h-3 rounded-sm bg-[var(--bg-elevated)] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-sm transition-all duration-300",style:{width:`${j.counts[D]/j.max*100}%`,backgroundColor:u[D]}})}),e.jsx("span",{className:"text-[10px] font-mono w-6 text-[var(--text-tertiary)] text-right",children:j.counts[D]})]},D))})]}),A.length>0&&e.jsxs("div",{className:"border-t border-[var(--border-muted)] p-3 shrink-0",children:[e.jsx("h3",{className:"text-xs font-medium text-[var(--fg-muted)] uppercase tracking-wider mb-2",children:"Anomaly Alerts"}),e.jsx("div",{className:"space-y-1",children:A.map((D,I)=>e.jsxs("div",{className:"text-[11px] text-yellow-500 bg-yellow-500/10 rounded px-2 py-1",children:["⚠️ ",D]},I))})]})]}):null};class md extends it.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}render(){return this.state.hasError?e.jsxs("div",{style:{padding:40,textAlign:"center"},children:[e.jsx("h2",{style:{color:"#ef4444",marginBottom:12},children:Us.app.errorBoundary.title}),e.jsx("pre",{style:{fontSize:12,color:"#64748b",whiteSpace:"pre-wrap",maxWidth:600,margin:"0 auto"},children:this.state.error?.message}),e.jsx("button",{onClick:()=>{this.setState({hasError:!1,error:null}),window.location.reload()},style:{marginTop:16,padding:"8px 20px",background:"#3b82f6",color:"#fff",border:"none",borderRadius:8,cursor:"pointer"},children:Us.app.errorBoundary.refreshBtn})]}):this.props.children}}function Ht(t,s="ai-scan"){return{title:t.title||"",description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:t.category||"",tags:t.tags||[],kind:t.kind||"",knowledgeType:t.knowledgeType||"",scope:t.scope||"",complexity:t.complexity||"",difficulty:t.difficulty||"",authority:t.authority,lifecycle:t.lifecycle||"pending",source:t.source||s,doClause:t.doClause||"",dontClause:t.dontClause||"",whenClause:t.whenClause||"",topicHint:t.topicHint||"",coreCode:t.coreCode||"",content:t.content||{},constraints:t.constraints||{},reasoning:t.reasoning||{},quality:t.quality||{},stats:t.stats||{},relations:t.relations||{},headers:t.headers||[],headerPaths:t.headerPaths,moduleName:t.moduleName,includeHeaders:t.includeHeaders,createdAt:t.createdAt,updatedAt:t.updatedAt}}const pd=()=>{const t=eo(),s=so(t.user?.role),a=ao(),{t:r}=Ae(),o=()=>{const S=window.location.pathname.replace(/^\//,"").split("/")[0]||"";return $l.includes(S)?S:"help"},[l,i]=n.useState(null),[p,d]=n.useState(o()),[g,x]=n.useState(""),[h,u]=n.useState(!1),[m,c]=n.useState(!0),[j,A]=n.useState(null),[D,I]=n.useState([]),[P,J]=n.useState([]),[w,B]=n.useState(null),[z,k]=n.useState(!1),[E,L]=n.useState({current:0,total:0,status:""}),[O,W]=n.useState([]),[q,N]=n.useState([]),[v,U]=n.useState(null),ae=n.useRef(null),be=S=>{const K=ae.current;return K?`asd:spm:${S}:${K}`:null},me=n.useCallback(S=>{N(K=>{const Y=typeof S=="function"?S(K):S;try{const ie=be("scan-results");ie&&sessionStorage.setItem(ie,JSON.stringify(Y))}catch{}return Y})},[]);n.useEffect(()=>{try{const S=be("selected-target");if(!S)return;w?sessionStorage.setItem(S,w):sessionStorage.removeItem(S)}catch{}},[w]),n.useEffect(()=>{try{const S=be("guard-audit");if(!S)return;v?sessionStorage.setItem(S,JSON.stringify(v)):sessionStorage.removeItem(S)}catch{}},[v]);const[je,G]=n.useState(1),[le,de]=n.useState(12),[R,T]=n.useState(!1),[X,oe]=n.useState(""),[pe,ue]=n.useState(!1),[M,Ce]=n.useState(null),[F,Se]=n.useState(null),[Te,Fe]=n.useState(!1),[Me,ee]=n.useState(!0),[ce,f]=n.useState(!1),[V,xe]=n.useState(0),[fe,C]=n.useState(!1),b=n.useRef(null),_=n.useRef(null);n.useEffect(()=>{G(1)},[g]),n.useEffect(()=>{if(l?.projectRoot)try{const S=`asd:custom-folder-targets:${l.projectRoot}`,K=localStorage.getItem(S);J(K?JSON.parse(K):[])}catch{J([])}},[l?.projectRoot]),n.useEffect(()=>{if(!l?.projectRoot)return;ae.current=l.projectRoot;const S=l.projectRoot;try{B(sessionStorage.getItem(`asd:spm:selected-target:${S}`)||null)}catch{B(null)}try{const K=sessionStorage.getItem(`asd:spm:scan-results:${S}`);N(K?JSON.parse(K):[])}catch{N([])}try{const K=sessionStorage.getItem(`asd:spm:guard-audit:${S}`);U(K?JSON.parse(K):null)}catch{U(null)}},[l?.projectRoot]);const ne=()=>{b.current&&b.current.abort()},[$,y]=n.useState(!1),te=async()=>{if(!$){y(!0);try{b.current&&b.current.abort(),await Q.cancelBootstrap("Cancelled by user via Dashboard")}catch{}finally{y(!1)}}};n.useEffect(()=>{let S=!1;const K=async()=>{try{const ie=await Q.getSignalStatus();if(!S){const ve=ie?.suggestions?.length||0,Re=ie?.snapshot?.lastResult?.newSuggestions||0;xe(ve||Re)}}catch{}};K();const Y=setInterval(K,300*1e3);return()=>{S=!0,clearInterval(Y)}},[]);const ge=n.useRef(null);n.useEffect(()=>{if(a.isAllDone&&a.session){if(ge.current!==a.session.id){ge.current=a.session.id;const S=a.session.failed>0?r("bootstrap.notifyPartial",{completed:a.session.completed,total:a.session.total,failed:a.session.failed}):r("bootstrap.notifySuccess",{completed:a.session.completed});re(S,{title:r("bootstrap.coldStartComplete"),type:a.session.failed>0?"error":"success"})}we()}},[a.isAllDone,a.session?.id]),n.useEffect(()=>{if(a.candidateCreatedTick>0){const S=setTimeout(()=>we(),2e3);return()=>clearTimeout(S)}},[a.candidateCreatedTick]);const he=(S,K)=>{d(S);const Y=K?.preserveSearch&&window.location.search?window.location.search:"";window.history.pushState({},document.title,`/${S}${Y}`)},De=S=>{A(S),d("recipes");const K=new URLSearchParams(window.location.search);K.set("edit",encodeURIComponent(S.name)),window.history.pushState({},document.title,`/recipes?${K.toString()}`)},se=()=>{A(null),window.history.replaceState({},document.title,"/recipes")};n.useEffect(()=>{g===""&&Ce(null)},[g]),n.useEffect(()=>{d(o())},[]),n.useEffect(()=>{if(!l)return;const S=window.location.pathname.replace(/^\//,"").split("/")[0],Y=new URLSearchParams(window.location.search).get("edit");if(S==="recipes"&&Y&&l.recipes)try{const ie=decodeURIComponent(Y),ve=l.recipes.find(Re=>Re.name===ie);ve&&!j&&(d("recipes"),De(ve))}catch{}},[l]),n.useEffect(()=>{we(),Oe(),rt();const S=()=>{d(o())};window.addEventListener("popstate",S);const K=new URLSearchParams(window.location.search),Y=K.get("action"),ie=K.get("path"),ve=K.get("q")||"";return Y==="search"&&ie?Se({q:ve,path:ie}):Y==="create"&&ie&&(oe(ie),T(!0),K.get("autoScan")==="1"&&setTimeout(()=>Xt(ie),500)),Y&&window.history.replaceState({},document.title,window.location.pathname),()=>{window.removeEventListener("popstate",S)}},[]);const we=async()=>{c(!0);try{const S=await Q.fetchData();i(S)}catch(S){re(ke(S,r("app.load.failed")),{title:r("app.load.failedTitle"),type:"error"})}finally{c(!1)}},Oe=async()=>{try{const S=await Q.fetchTargets();I(S)}catch(S){console.warn("删除候选残留失败:",ke(S))}},rt=async()=>{try{const S=await Q.getLlmEnvConfig();ee(S.llmReady)}catch{}},ct=async()=>{try{await Q.refreshProject(),Oe(),re(r("app.projectRefresh.success"),{title:r("app.projectRefresh.successTitle")})}catch{re(r("app.load.failedHint"),{title:r("app.projectRefresh.failed"),type:"error"})}},Xt=async S=>{ue(!0);try{const K=await Q.extractFromPath(S);me(K.result.map(Y=>({...Ht(Y,"extract"),mode:"full",lang:"cn"}))),he("spm"),T(!1),we(),K.result?.length>0&&re(r("app.extract.success"),{title:r("app.extract.successTitle")})}catch{re(r("app.extract.failed"),{type:"error"})}finally{ue(!1)}},nt=async()=>{if(X){ue(!0);try{const S=await Q.extractFromPath(X);me(S.result.map(K=>({...Ht(K,"extract"),mode:"full",lang:"cn"}))),he("spm"),T(!1),we(),S.result?.length>0?re(S.isMarked?r("app.extract.markerSuccess"):r("app.extract.normalSuccess"),{title:r("app.extract.successTitle")}):S.isMarked||re(r("app.extract.noMarker"),{title:r("app.extract.extracting"),type:"info"})}catch{re(r("app.extract.failed"),{type:"error"})}finally{ue(!1)}}},Ss=async S=>{try{const K=await navigator.clipboard.readText();if(!K)return re(r("app.clipboard.empty"),{title:r("app.clipboard.emptyTitle"),type:"info"});re(r("app.clipboard.analyzing"),{title:r("app.clipboard.analyzingTitle"),type:"info"}),ue(!0);const Y=S||X;try{const ie=await Q.extractFromText(K,Y||void 0),ve=ie._multipleCount;me([{...Ht(ie,"clipboard"),mode:"full",lang:"cn"}]),he("spm"),T(!1),we(),re(ve?r("app.clipboard.resultMulti",{count:ve}):r("app.extract.normalSuccess"),{title:r("app.clipboard.resultTitle")})}catch(ie){const ve=ke(ie);Vl(ie)?re(ve,{title:r("app.clipboard.aiFailed"),type:"error"}):re(ve,{title:r("common.operationFailed"),type:"error"})}}catch{re(r("app.clipboard.permissionError"),{title:r("app.clipboard.permissionTitle"),type:"error"})}finally{ue(!1)}},an={"scan:started":{percent:5,status:r("app.scan.events.initializing")},"scan:files-loaded":{percent:15,status:S=>r("app.scan.events.filesLoaded",{count:S.count||0})},"scan:reading":{percent:25,status:S=>r("app.scan.events.readingFiles",{count:S.count||0})},"scan:ai-extracting":{percent:40,status:r("app.scan.events.aiAnalyzing")},"scan:enriching":{percent:85,status:S=>r("app.scan.events.enriching",{count:S.recipeCount||0})},"scan:completed":{percent:95,status:r("app.scan.events.completing")}},rn=async S=>{if(z)return;b.current&&b.current.abort(),_.current&&(clearInterval(_.current),_.current=null);const K=new AbortController;b.current=K,B(S.name),k(!0),me([]),U(null),W([]),L({current:0,total:100,status:r("app.scan.streamInit")});try{const Y=await Q.scanTargetStream(S,Re=>{const Pe=an[Re.type];if(Pe){const _e=typeof Pe.status=="function"?Pe.status(Re):Pe.status;L({current:Pe.percent,total:100,status:_e})}Re.type==="scan:files-loaded"&&Re.files&&W(Re.files),Re.type==="scan:ai-extracting"&&(_.current&&clearInterval(_.current),_.current=setInterval(()=>{L(_e=>({..._e,current:Math.min(_e.current+1,80)}))},3e3)),(Re.type==="scan:enriching"||Re.type==="scan:completed")&&_.current&&(clearInterval(_.current),_.current=null)},K.signal);_.current&&(clearInterval(_.current),_.current=null),L({current:100,total:100,status:r("app.scan.completed")});const ie=Y.recipes||[],ve=Y.scannedFiles||[];if(ie.length>0||ve.length>0){const Re=typeof S=="string"?S:S?.name||"unknown",Pe=ie.map(_e=>({...Ht(_e,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:Re,scanMode:"target"}));if(me(Pe),ve.length>0&&W(ve),we(),ie.length>0)re(r("app.scan.targetSuccess",{count:ie.length}),{title:r("app.scan.targetSuccessTitle")});else if(Y.message){const _e=Y.noAi;re(Y.message,{title:r(_e?"app.scan.aiNotConfigured":"app.scan.noResults"),type:_e?"info":"error"})}else re(r("app.scan.noResults"),{title:r("app.scan.scanComplete"),type:"info"})}else re(r("app.scan.scanFailedHint"),{title:r("app.scan.scanFailed"),type:"error"})}catch(Y){if(_.current&&(clearInterval(_.current),_.current=null),fs(Y))return;const ie=ss(Y),ve=ie?r("app.scan.timeout"):ke(Y,r("app.scan.scanError"));re(ve,{title:r(ie?"app.scan.timeoutTitle":"app.scan.scanError"),type:"error"})}finally{b.current===K&&(k(!1),L({current:0,total:0,status:""}),b.current=null)}},nn=async()=>{if(z)return;b.current&&b.current.abort();const S=new AbortController;b.current=S,he("candidates"),k(!0),me([]),U(null),W([]),L({current:0,total:100,status:r("app.coldStart.collecting")}),a.resetSession();try{const K=await Q.bootstrap(S.signal);L({current:100,total:100,status:r("app.coldStart.skeletonCreated")}),K.bootstrapSession&&a.initFromApiResponse(K.bootstrapSession),we();const Y=K.report||{},ie=K.targets?.length||0,ve=Y.totals?.files||0,Re=Y.totals?.graphEdges||0,Pe=K.guardSummary,_e=Pe?`, ${r("app.coldStart.guardSuffix",{count:Pe.totalViolations})}`:"";re(r("app.coldStart.skeletonDetail",{targets:ie,files:ve,deps:Re})+_e)}catch(K){if(Is(K))return;const ie=ss(K)?r("app.coldStart.timeout"):ke(K);re(ie,{type:"error"})}finally{b.current===S&&(k(!1),L({current:0,total:0,status:""}),b.current=null)}},ln=async()=>{if(z)return;b.current&&b.current.abort();const S=new AbortController;b.current=S,he("candidates"),k(!0),L({current:0,total:100,status:r("app.rescan.analyzing")}),a.resetSession();try{const K=await Q.rescan({reason:"dashboard-rescan"},S.signal);L({current:100,total:100,status:r("app.rescan.done")}),K.bootstrapSession&&a.initFromApiResponse(K.bootstrapSession),we();const Y=K.relevanceAudit||{},ie=K.gapAnalysis||{};re(r("app.rescan.success",{preserved:K.rescan?.preservedRecipes||0,healthy:Y.healthy||0,decayed:(Y.decay||0)+(Y.severe||0)+(Y.dead||0)})+(ie.gapDimensions>0?` ${r("app.rescan.filling",{count:ie.gapDimensions})}`:""))}catch(K){if(Is(K))return;const Y=ss(K)?r("app.rescan.timeout"):ke(K);re(Y,{type:"error"})}finally{b.current===S&&(k(!1),L({current:0,total:0,status:""}),b.current=null)}},on=async()=>{if(z)return;b.current&&b.current.abort();const S=new AbortController;b.current=S,he("spm"),B("__project__"),k(!0),me([]),U(null),W([]),L({current:0,total:100,status:r("app.fullScan.collecting")});const K=[{status:r("app.fullScan.phase5"),percent:5},{status:r("app.fullScan.phase15"),percent:15},{status:r("app.fullScan.phase25"),percent:25},{status:r("app.fullScan.phase35"),percent:35},{status:r("app.fullScan.phase45"),percent:45},{status:r("app.fullScan.phase55"),percent:55},{status:r("app.fullScan.phase65"),percent:65},{status:r("app.fullScan.phase75"),percent:75},{status:r("app.fullScan.phase85"),percent:85}];let Y=0;const ie=setInterval(()=>{Y=Math.min(Y+1,K.length);const ve=K[Y-1];ve&&L(Re=>({...Re,current:ve.percent,status:ve.status}))},15e3);try{const ve=await Q.scanProject(S.signal);clearInterval(ie),L({current:100,total:100,status:ve.partial?r("app.fullScan.partialComplete"):r("app.fullScan.completed")});const Re=ve.recipes||[],Pe=ve.scannedFiles||[];if(Re.length>0||Pe.length>0){const _e=Re.map(vn=>({...Ht(vn,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:"__project__",scanMode:"project"}));me(_e),W(Pe),U(ve.guardAudit||null),we();const Ze=ve.guardAudit?.summary,es=Ze?`, ${r("app.fullScan.guardSuffix",{count:Ze.totalViolations})}`:"",Ft=ve.partial?r("app.fullScan.timeoutSuffix"):"";re(r("app.fullScan.resultDetail",{count:Re.length})+es+Ft)}else re(r("app.fullScan.noContent"))}catch(ve){if(clearInterval(ie),Is(ve))return;const Pe=ss(ve)?r("app.fullScan.timeout"):ke(ve);re(Pe,{type:"error"})}finally{b.current===S&&(k(!1),L({current:0,total:0,status:""}),b.current=null)}},cn=(S,K)=>{const Y=[...q],ie={...Y[S],...K};Y[S]=ie,me(Y)},dn=async S=>{if(!Te){Fe(!0);try{const K=(S.content?.pattern||"").trim(),Y=(()=>{if(!K)return!1;const Ze=K.split(`
|
|
109
|
+
${t("wiki.loadFailedDesc")}`)}finally{u(!1)}}},E=()=>{d(null),x("")},L=n.useMemo(()=>r.filter(q=>q.path!=="meta.json"),[r]),O=n.useMemo(()=>Uc(L,D?.files),[L,D]);if(m)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(Ne,{size:H.xl,className:"text-blue-500 animate-spin"})});const W=!l&&L.length===0&&s.task.status!=="running";return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden p-6 pt-4",children:[e.jsx(qc,{task:s.task,wiki:s.wiki}),W?e.jsx(Jc,{}):e.jsxs(e.Fragment,{children:[s.task.status==="running"&&e.jsxs("div",{className:"mb-3 flex items-center gap-3 px-4 py-2.5 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/70 rounded-xl shrink-0",children:[e.jsxs("div",{className:"relative flex items-center justify-center w-6 h-6",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-30 animate-ping"}),e.jsx(Ne,{size:16,className:"text-blue-600 animate-spin relative"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-blue-800",children:t("wiki.wikiGenerating")}),s.task.message&&e.jsx("span",{className:"text-xs text-blue-500 ml-2 truncate",children:s.task.message})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"w-24 bg-blue-100 rounded-full h-1.5",children:e.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(s.task.progress||0,3)}%`}})}),e.jsxs("span",{className:"text-xs font-mono text-blue-600 w-8 text-right",children:[s.task.progress||0,"%"]})]})]}),e.jsxs("div",{className:"flex gap-4 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:`w-64 flex-shrink-0 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl flex flex-col overflow-hidden ${p?"hidden lg:flex":""}`,children:[e.jsxs("div",{className:"px-3 pt-3 pb-2 border-b border-[var(--border-default)] shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{size:16,className:"text-blue-500"}),e.jsx("span",{className:"text-sm font-semibold text-[var(--fg-primary)]",children:"Wiki"}),D?.version&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["v",D.version]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[l&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("wiki.fileCount",{count:L.length})}),s.task.status!=="running"&&l&&e.jsx("button",{onClick:z,title:t("wiki.incrementalUpdate"),className:"p-1 rounded-md text-blue-500 hover:bg-blue-50 transition-colors",children:e.jsx(at,{size:13})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--fg-muted)]"}),e.jsx("input",{type:"text",placeholder:t("wiki.searchPlaceholder"),value:j,onChange:q=>A(q.target.value),className:"w-full pl-8 pr-3 py-2 text-sm bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-300 transition-all"})]})]}),e.jsxs("div",{className:"p-2 overflow-y-auto flex-1 min-h-0 scrollbar-light",children:[e.jsx(Wc,{tree:O,selectedFile:p,onSelect:k,searchQuery:j}),s.task.status==="running"&&e.jsxs("div",{className:"mx-2 mt-3 mb-1 flex items-center gap-2 px-3 py-2 bg-blue-50 border border-blue-100 rounded-lg",children:[e.jsx(Ne,{size:12,className:"text-blue-500 animate-spin flex-shrink-0"}),e.jsx("span",{className:"text-[11px] text-blue-600 leading-tight",children:t("wiki.generating")})]})]}),D?.generatedAt&&e.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-default)] shrink-0",children:e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-[var(--fg-muted)]",children:[e.jsx(Ye,{size:10}),e.jsx("span",{children:Kc(D.generatedAt)}),D.duration!=null&&e.jsxs("span",{children:["· ",en(D.duration)]})]})})]}),e.jsx("div",{className:`flex-1 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl overflow-hidden flex flex-col min-h-0 ${p?"":"hidden lg:flex"}`,children:p?e.jsx(Vc,{filePath:p,content:g,loading:h,meta:D,onBack:E}):e.jsx(Yc,{meta:D,onSelectFile:k,isGenerating:s.task.status==="running",progress:s.task.progress,message:s.task.message})})]})]})]})},Zc={guard:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",search:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",forge:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300",usage:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300",lifecycle:"bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300",quality:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",decay:"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300",context:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",anomaly:"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300",intent:"bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300",exploration:"bg-teal-100 text-teal-700 dark:bg-teal-900/30 dark:text-teal-300",panorama:"bg-sky-100 text-sky-700 dark:bg-sky-900/30 dark:text-sky-300"},Xc={governance:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300",compliance:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",metrics:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",analysis:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300"},ed=["time1h","time6h","time24h","time7d","timeAll"],td=[36e5,216e5,864e5,6048e5,0];function tn(t){const s=new Date(t),a=r=>String(r).padStart(2,"0");return`${a(s.getMonth()+1)}-${a(s.getDate())} ${a(s.getHours())}:${a(s.getMinutes())}:${a(s.getSeconds())}`}function sn(t,s){return s[t]??"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300"}function sd({signal:t}){const[s,a]=n.useState(!1);return e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-3 hover:bg-[var(--bg-muted)]/40 transition-colors cursor-pointer",onClick:()=>{a(!s)},children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-xs font-medium ${sn(t.type,Zc)}`,children:t.type}),e.jsx("span",{className:"text-[var(--fg-default)] font-medium truncate",children:t.source}),t.target&&e.jsxs("span",{className:"text-[var(--fg-subtle)] truncate",children:["→ ",t.target]}),e.jsxs("span",{className:"ml-auto shrink-0 tabular-nums text-xs text-[var(--fg-subtle)]",children:[(t.value*100).toFixed(0),"%"]}),e.jsx("span",{className:"shrink-0 text-xs text-[var(--fg-subtle)] tabular-nums",children:tn(t.timestamp)})]}),s&&t.metadata&&(typeof t.metadata=="object"&&!Array.isArray(t.metadata)?e.jsx("div",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs bg-[var(--bg-muted)] rounded p-2.5",children:Object.entries(t.metadata).map(([r,o])=>e.jsxs(it.Fragment,{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:r}),e.jsx("span",{className:"text-[var(--fg-default)] tabular-nums",children:typeof o=="object"?JSON.stringify(o):String(o)})]},r))}):e.jsx("pre",{className:"mt-2 text-xs text-[var(--fg-secondary)] bg-[var(--bg-muted)] rounded p-2.5 overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(t.metadata,null,2)}))]})}function ad({report:t}){const[s,a]=n.useState(!1);return e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-3 hover:bg-[var(--bg-muted)]/40 transition-colors cursor-pointer",onClick:()=>{a(!s)},children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-xs font-medium ${sn(t.category,Xc)}`,children:t.category}),e.jsx("span",{className:"text-[var(--fg-default)] font-medium truncate",children:t.type}),e.jsx("span",{className:"text-[var(--fg-subtle)] text-xs truncate",children:t.producer}),t.duration_ms!=null&&e.jsxs("span",{className:"text-xs text-[var(--fg-subtle)]",children:[t.duration_ms,"ms"]}),e.jsx("span",{className:"ml-auto shrink-0 text-xs text-[var(--fg-subtle)] tabular-nums",children:tn(t.timestamp)})]}),s&&(typeof t.data=="object"&&t.data&&!Array.isArray(t.data)?e.jsx("div",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs bg-[var(--bg-muted)] rounded p-2.5",children:Object.entries(t.data).map(([r,o])=>e.jsxs(it.Fragment,{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:r}),e.jsx("span",{className:"text-[var(--fg-default)] tabular-nums",children:typeof o=="object"?JSON.stringify(o):String(o)})]},r))}):e.jsx("pre",{className:"mt-2 text-xs text-[var(--fg-secondary)] bg-[var(--bg-muted)] rounded p-2.5 overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(t.data,null,2)}))]})}function Ua({label:t,value:s,max:a}){const r=a>0?Math.round(s/a*100):0;return e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"w-24 truncate text-[var(--fg-subtle)]",children:t}),e.jsx("div",{className:"flex-1 h-2 rounded-full bg-[var(--bg-muted)] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--accent)] transition-all duration-300",style:{width:`${r}%`}})}),e.jsx("span",{className:"w-12 text-right text-xs tabular-nums text-[var(--fg-subtle)]",children:s})]})}const rd=()=>{const{t}=Ae(),[s,a]=n.useState("signals"),[r,o]=n.useState(2),[l,i]=n.useState(""),[p,d]=n.useState(!1),[g,x]=n.useState(null),[h,u]=n.useState([]),[m,c]=n.useState(0),[j,A]=n.useState([]),[D,I]=n.useState(0),[P,J]=n.useState(null),w=n.useMemo(()=>{const k=td[r];return k===0?{}:{from:Date.now()-k}},[r]),B=n.useCallback(async()=>{d(!0),x(null);try{if(s==="signals"){const k=l?l.split(",").map(L=>L.trim()).filter(Boolean):void 0,E=await Q.getSignalTrace({...w,type:k,limit:100});u(E.signals),c(E.total)}else if(s==="reports"){const k=await Q.getReports({...w,limit:50});A(k.reports),I(k.total)}else{const k=await Q.getSignalStats(w);J(k)}}catch(k){x(ke(k))}finally{d(!1)}},[s,w,l]);n.useEffect(()=>{B()},[B]);const z=n.useMemo(()=>{if(!P)return 1;const k=Object.values(P.byType);return Math.max(...k,1)},[P]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yt,{size:20,className:"text-[var(--accent)]"}),e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-default)]",children:t("signals.title")})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s==="signals"&&e.jsxs("div",{className:"relative",children:[e.jsx(sa,{size:13,className:"absolute left-2 top-1/2 -translate-y-1/2 text-[var(--fg-subtle)]"}),e.jsx("input",{type:"text",placeholder:t("signals.filterPlaceholder"),value:l,onChange:k=>{i(k.target.value)},className:"pl-7 pr-2 py-1.5 text-xs rounded-lg border border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--fg-default)] w-40"})]}),e.jsx("div",{className:"flex items-center gap-1",children:[["signals",e.jsx(Be,{size:13},"s"),t("signals.tabSignals")],["reports",e.jsx(Qe,{size:13},"r"),t("signals.tabReports")],["stats",e.jsx(Tt,{size:13},"st"),t("signals.tabStats")]].map(([k,E,L])=>e.jsxs("button",{type:"button",onClick:()=>{a(k)},className:`flex items-center gap-1 px-4 py-1.5 rounded-md text-xs font-medium transition-colors ${s===k?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:[E,L]},k))}),e.jsx("div",{className:"flex items-center gap-1",children:ed.map((k,E)=>e.jsx("button",{type:"button",onClick:()=>{o(E)},className:`px-4 py-1.5 rounded-md text-xs font-medium transition-colors ${r===E?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:t(`signals.${k}`)},k))}),e.jsxs("button",{type:"button",onClick:B,disabled:p,className:"flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-lg border border-[var(--border-default)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] transition-colors disabled:opacity-50",children:[p?e.jsx(Ne,{size:13,className:"animate-spin"}):e.jsx(at,{size:13}),t("signals.refresh")]})]})]}),g&&e.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm rounded-lg bg-red-50 text-red-700 dark:bg-red-900/20 dark:text-red-300",children:[e.jsx(st,{size:16}),g]}),p&&!h.length&&!j.length&&!P?e.jsxs("div",{className:"flex items-center justify-center py-20 text-[var(--fg-subtle)]",children:[e.jsx(Ne,{size:24,className:"animate-spin mr-2"}),t("signals.loading")]}):s==="signals"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)]",children:t("signals.showingSignals",{shown:h.length,total:m})}),h.length===0?e.jsxs("div",{className:"text-center py-12 text-[var(--fg-subtle)]",children:[e.jsx(js,{size:32,className:"mx-auto mb-2 opacity-40"}),e.jsx("p",{children:t("signals.noSignals")})]}):e.jsx("div",{className:"space-y-1.5",children:h.map((k,E)=>e.jsx(sd,{signal:k},`${k.timestamp}-${E}`))})]}):s==="reports"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)]",children:t("signals.showingReports",{shown:j.length,total:D})}),j.length===0?e.jsxs("div",{className:"text-center py-12 text-[var(--fg-subtle)]",children:[e.jsx(Qe,{size:32,className:"mx-auto mb-2 opacity-40"}),e.jsx("p",{children:t("signals.noReports")})]}):e.jsx("div",{className:"space-y-1.5",children:j.map(k=>e.jsx(ad,{report:k},k.id))})]}):e.jsx("div",{className:"space-y-6",children:P?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)] mb-1",children:t("signals.totalSignals")}),e.jsx("div",{className:"text-2xl font-bold text-[var(--fg-default)] tabular-nums",children:P.total})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)] mb-1",children:t("signals.signalTypes")}),e.jsx("div",{className:"text-2xl font-bold text-[var(--fg-default)] tabular-nums",children:Object.keys(P.byType).length})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)] mb-1",children:t("signals.sources")}),e.jsx("div",{className:"text-2xl font-bold text-[var(--fg-default)] tabular-nums",children:Object.keys(P.bySource).length})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("h3",{className:"text-sm font-medium text-[var(--fg-default)] mb-3",children:t("signals.byType")}),e.jsx("div",{className:"space-y-2",children:Object.entries(P.byType).sort((k,E)=>E[1]-k[1]).map(([k,E])=>e.jsx(Ua,{label:k,value:E,max:z},k))})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("h3",{className:"text-sm font-medium text-[var(--fg-default)] mb-3",children:t("signals.bySource")}),e.jsx("div",{className:"space-y-2",children:Object.entries(P.bySource).sort((k,E)=>E[1]-k[1]).slice(0,15).map(([k,E])=>e.jsx(Ua,{label:k,value:E,max:z},k))})]})]}):e.jsxs("div",{className:"text-center py-12 text-[var(--fg-subtle)]",children:[e.jsx(Tt,{size:32,className:"mx-auto mb-2 opacity-40"}),e.jsx("p",{children:t("signals.noStats")})]})})]})},nd={authority:0,guardUsageCount:0,humanUsageCount:0,aiUsageCount:0,lastUsedAt:null,authorityScore:0},ld=({editingRecipe:t,setEditingRecipe:s,handleSaveRecipe:a,closeRecipeEdit:r,isSavingRecipe:o=!1})=>{const{t:l}=Ae(),[i,p]=n.useState("preview"),d=n.useRef(!0);n.useEffect(()=>()=>{d.current=!1},[]);const g=(()=>{const u=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(u)?"objectivec":t.language||"text"})(),x=async u=>{try{if(await Q.setRecipeAuthority(t.name,u),d.current){const m=t.stats?{...t.stats,authority:u}:{...nd,authority:u};s({...t,stats:m})}}catch(m){console.warn(l("recipeEditor.authorityFailed"),ke(m))}},h=u=>{if(!u)return"";const m=typeof u=="string"?new Date(u).getTime():u;return isNaN(m)?"":new Date(m).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})};return e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] w-full max-w-6xl rounded-2xl shadow-2xl flex flex-col h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-[var(--border-default)] flex justify-between items-center flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-bold",children:l("recipeEditor.title")}),t.kind&&(()=>{const m={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:Ve},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:St},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:qe}}[t.kind];if(!m)return null;const c=m.icon;return e.jsxs("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase flex items-center gap-1 border ${m.bg} ${m.color} ${m.border}`,children:[e.jsx(c,{size:H.sm}),m.label]})})(),t.status&&t.status!=="active"&&t.status!=="published"&&e.jsx("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase border ${t.status==="draft"?"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border-[var(--border-default)]":t.status==="archived"?"bg-orange-50 text-orange-600 border-orange-200":"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border-[var(--border-default)]"}`,children:t.status})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-[var(--fg-muted)]",children:l("recipeEditor.authorityScore")}),i==="preview"?e.jsx("span",{className:"text-sm text-[var(--fg-primary)]",children:t.stats?.authority??3}):e.jsx(tt,{value:String(t.stats?.authority??3),onChange:u=>x(parseInt(u)),options:[{value:"1",label:`1 - ${l("recipeEditor.qualityLevels.basic")}`,icon:"⭐"},{value:"2",label:`2 - ${l("recipeEditor.qualityLevels.good")}`,icon:"⭐⭐"},{value:"3",label:`3 - ${l("recipeEditor.qualityLevels.solid")}`,icon:"⭐⭐⭐"},{value:"4",label:`4 - ${l("recipeEditor.qualityLevels.great")}`,icon:"⭐⭐⭐⭐"},{value:"5",label:`5 - ${l("recipeEditor.qualityLevels.excellent")}`,icon:"⭐⭐⭐⭐⭐"}],size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]}),e.jsxs("div",{className:"flex bg-[var(--bg-subtle)] p-1 rounded-lg mr-4",children:[e.jsxs("button",{onClick:()=>p("preview"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${i==="preview"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx(Ut,{size:H.sm})," ",l("recipeEditor.preview")]}),e.jsxs("button",{onClick:()=>p("edit"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${i==="edit"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx(It,{size:H.sm})," ",l("recipeEditor.edit")]})]}),e.jsx("button",{onClick:r,className:"p-2 hover:bg-[var(--bg-subtle)] rounded-full",children:e.jsx(ze,{size:H.lg})})]})]}),e.jsx("div",{className:"p-6 space-y-4 flex-1 flex flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:i==="edit"?e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-5 pr-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:l("recipeEditor.path")}),e.jsx("input",{className:"w-full p-2 bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg text-sm",value:t.name,onChange:u=>s({...t,name:u.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:l("recipeEditor.description")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-none",rows:2,value:t.description||"",onChange:u=>s({...t,description:u.target.value}),placeholder:l("recipeEditor.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-blue-400"})," ",l("recipeEditor.markdown")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ys,{value:t.content?.markdown||"",onChange:u=>s({...t,content:{...t.content,markdown:u}}),language:"markdown",height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(At,{size:11,className:"text-emerald-500"})," ",l("recipeEditor.code")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ys,{value:t.content?.pattern||"",onChange:u=>s({...t,content:{...t.content,pattern:u}}),language:g,height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:l("recipeEditor.rationale")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-y",rows:3,value:t.content?.rationale||"",onChange:u=>s({...t,content:{...t.content,rationale:u.target.value}}),placeholder:l("recipeEditor.rationalePlaceholder")})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-6 scrollbar-light",children:[(()=>{const u=[["trigger",t.trigger],["language",t.language],["category",t.category],["kind",t.kind],["knowledgeType",t.knowledgeType],["status",t.status],["complexity",t.complexity],["scope",t.scope],["source",t.source],["updatedAt",t.updatedAt?h(t.updatedAt):void 0]].filter(([,m])=>!!m);return u.length===0?null:e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-4",children:"Recipe Metadata"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-y-4 gap-x-8",children:u.map(([m,c])=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold uppercase mb-1",children:m}),e.jsx("span",{className:"text-sm text-[var(--fg-primary)] break-all font-medium",children:c})]},m))})]})})(),t.description&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.description")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.description})]}),t.content?.markdown&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-blue-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-blue-400"})," ",l("recipeEditor.markdown")]}),e.jsx("div",{className:"bg-blue-50/30 border border-blue-100 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-[var(--fg-primary)] leading-relaxed",children:e.jsx(Qt,{content:t.content.markdown})})})]}),t.content?.pattern&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-emerald-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(At,{size:11,className:"text-emerald-500"})," ",l("recipeEditor.code")]}),e.jsx(ft,{code:t.content.pattern,language:g,showLineNumbers:!0})]}),t.content?.rationale&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.rationale")}),e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.content.rationale})})]}),t.content?.steps&&t.content.steps.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.steps")}),e.jsx("div",{className:"space-y-2",children:t.content.steps.map((u,m)=>typeof u=="string"?e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)] flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:m+1}),e.jsx("p",{className:"text-xs text-[var(--fg-primary)] leading-relaxed",children:u})]},m):e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:m+1}),u.title&&e.jsx("span",{className:"text-xs font-bold text-[var(--fg-primary)]",children:u.title})]}),u.description&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] ml-7 leading-relaxed",children:u.description}),u.code&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:u.code})]},m))})]}),t.content?.codeChanges&&t.content.codeChanges.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.codeChanges")}),e.jsx("div",{className:"space-y-2",children:t.content.codeChanges.map((u,m)=>e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex items-center gap-2",children:[e.jsx(pt,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-[var(--fg-secondary)]",children:u.file})]}),u.explanation&&e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)] px-3 py-1.5 border-b border-[var(--border-default)] bg-yellow-50/30",children:u.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words font-mono",children:u.before||l("recipes.emptyValue")})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/20",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:"After"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-primary)] whitespace-pre-wrap break-words font-mono",children:u.after})]})]},m))})]}),t.content?.verification&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-teal-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.validation")}),e.jsxs("div",{className:"bg-teal-50/50 border border-teal-100 rounded-xl p-4 space-y-1.5",children:[t.content.verification.method&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-teal-600",children:l("recipeEditor.validationMethod")})," ",t.content.verification.method]}),t.content.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-teal-600",children:l("recipeEditor.validationExpected")})," ",t.content.verification.expectedResult]}),t.content.verification.testCode&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md overflow-x-auto whitespace-pre-wrap mt-1",children:t.content.verification.testCode})]})]}),t.tags&&t.tags.length>0&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-3 flex items-center gap-1.5",children:[e.jsx(jr,{size:11,className:"text-blue-400"})," ",l("recipeEditor.tags")]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map((u,m)=>e.jsx("span",{className:"px-2.5 py-1 bg-blue-50 text-blue-700 border border-blue-100 rounded-full text-xs font-medium",children:u},m))})]}),!!(t.constraints&&(t.constraints.guards?.length||t.constraints.boundaries?.length||t.constraints.preconditions?.length||t.constraints.sideEffects?.length))&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6 space-y-4",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest flex items-center gap-1.5",children:[e.jsx(Ve,{size:11,className:"text-amber-500"})," ",l("recipeEditor.constraints")]}),t.constraints.guards&&t.constraints.guards.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.guardRules")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.guards.map((u,m)=>e.jsxs("li",{className:"flex gap-2 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${u.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-xs bg-[var(--bg-subtle)] px-1.5 py-0.5 rounded",children:u.pattern}),u.message&&e.jsxs("span",{className:"text-xs text-[var(--fg-muted)]",children:["— ",u.message]})]},m))})]}),t.constraints.boundaries&&t.constraints.boundaries.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.boundaryConstraints")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.boundaries.map((u,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),u]},m))})]}),t.constraints.preconditions&&t.constraints.preconditions.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.preconditions")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.preconditions.map((u,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),u]},m))})]}),t.constraints.sideEffects&&t.constraints.sideEffects.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.sideEffects")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.sideEffects.map((u,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),u]},m))})]})]}),t.relations&&Object.entries(t.relations).some(([,u])=>Array.isArray(u)&&u.length>0)&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-4",children:l("recipeEditor.relations")}),e.jsx("div",{className:"space-y-2",children:[{key:"inherits",label:l("recipeEditor.relationTypes.inherits"),color:"text-green-600",icon:"↑"},{key:"implements",label:l("recipeEditor.relationTypes.implements"),color:"text-blue-600",icon:"◇"},{key:"calls",label:l("recipeEditor.relationTypes.calls"),color:"text-cyan-600",icon:"→"},{key:"dependsOn",label:l("recipeEditor.relationTypes.dependsOn"),color:"text-yellow-600",icon:"⊕"},{key:"dataFlow",label:l("recipeEditor.relationTypes.dataFlow"),color:"text-purple-600",icon:"⇢"},{key:"conflicts",label:l("recipeEditor.relationTypes.conflicts"),color:"text-red-600",icon:"✕"},{key:"extends",label:l("recipeEditor.relationTypes.extends"),color:"text-teal-600",icon:"⊃"},{key:"related",label:l("recipeEditor.relationTypes.associates"),color:"text-[var(--fg-muted)]",icon:"∼"}].map(({key:u,label:m,color:c,icon:j})=>{const A=t.relations?.[u];return!A||!Array.isArray(A)||A.length===0?null:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:`text-xs font-mono ${c} shrink-0 whitespace-nowrap pt-0.5`,children:[j," ",m]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:A.map((D,I)=>e.jsx("span",{className:"px-2 py-0.5 bg-[var(--bg-surface)] border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-lg text-xs font-mono",children:typeof D=="string"?D:D.id||D.title||JSON.stringify(D)},I))})]},u)})})]}),!t.content?.markdown&&!t.content?.pattern&&!t.description&&e.jsx("div",{className:"bg-[var(--bg-surface)] p-8 rounded-2xl border border-[var(--border-default)] shadow-sm min-h-[200px] flex items-center justify-center",children:e.jsx("div",{className:"text-[var(--fg-muted)] italic",children:l("recipeEditor.noContent")})})]})})}),e.jsxs("div",{className:"p-6 border-t border-[var(--border-default)] flex justify-end gap-3",children:[e.jsx("button",{onClick:r,disabled:o,className:"px-4 py-2 text-[var(--fg-secondary)] font-medium disabled:opacity-50",children:l("recipeEditor.cancel")}),e.jsxs("button",{onClick:a,disabled:o,className:"px-6 py-2 bg-blue-600 text-white rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 disabled:opacity-60 disabled:cursor-not-allowed",children:[o?e.jsx(Ne,{size:H.lg,className:"animate-spin"}):e.jsx(ws,{size:H.lg}),l(o?"recipeEditor.saving":"recipeEditor.saveChanges")]})]})]})]})},od=({setShowCreateModal:t,createPath:s,setCreatePath:a,handleCreateFromPath:r,handleCreateFromClipboard:o,isExtracting:l})=>{const{t:i}=Ae();return e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden bg-[var(--bg-surface)]",children:[e.jsxs("div",{className:"p-6 border-b flex justify-between items-center bg-[var(--bg-subtle)] border-[var(--border-default)]",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx(mt,{size:H.xl,className:"text-blue-600"})," ",i("createModal.title")]}),e.jsx("button",{onClick:()=>t(!1),className:"p-2 rounded-full transition-all duration-150 text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] hover:text-[var(--fg-primary)]",children:e.jsx(ze,{size:H.lg})})]}),e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(va,{size:H.sm})," ",i("createModal.importFromPath")]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:"flex-1 p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] border bg-[var(--bg-subtle)] border-[var(--border-default)] text-[var(--fg-primary)]",placeholder:i("createModal.pathPlaceholder"),value:s,onChange:p=>a(p.target.value)}),e.jsxs("button",{onClick:r,disabled:!s||l,className:"px-5 py-2 rounded-xl text-sm font-bold whitespace-nowrap disabled:opacity-40 transition-all duration-150 bg-[var(--accent)] text-white hover:opacity-90 shadow-sm",children:[e.jsx(va,{size:14,className:"inline -mt-0.5 mr-1"}),i("createModal.scanFile")]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:"w-full border-t border-[var(--border-default)]"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"px-2 font-bold bg-[var(--bg-surface)] text-[var(--fg-muted)]",children:i("createModal.or")})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(jl,{size:H.sm})," ",i("createModal.importFromClipboard")]}),e.jsxs("button",{onClick:()=>o(),disabled:l,className:"w-full flex items-center justify-center gap-3 p-4 rounded-xl font-bold transition-all duration-150 border bg-[var(--accent-subtle)] text-[var(--accent)] border-[var(--accent-emphasis)]/20 hover:bg-[var(--accent-emphasis)]/10",children:[e.jsx(Be,{size:H.lg})," ",i("createModal.useClipboard")]})]})]}),l&&e.jsxs("div",{className:"bg-blue-600 text-white p-4 flex items-center justify-center gap-3 animate-pulse",children:[e.jsx(Jt,{size:H.lg,className:"animate-spin"}),e.jsx("span",{className:"font-bold text-sm",children:i("createModal.aiThinking")})]})]})]})};function id(t){if(!t)return"";if(typeof t=="object"){const o=t.code||t.pattern||t.markdown||t.snippet||t.body||"";if(o)return o}const a=(typeof t=="string"?t:JSON.stringify(t)).replace(/^---[\s\S]*?---\s*\n?/,"").trim(),r=a.match(/```[\w]*\n([\s\S]*?)```/);return r&&r[1]?r[1].trim():a.slice(0,8e3)}const cd=({searchQ:t,insertPath:s,onClose:a})=>{const{t:r}=Ae(),[o,l]=n.useState([]),[i,p]=n.useState(!0),[d,g]=n.useState(null),x=n.useRef(!0),h=n.useRef(null);n.useEffect(()=>(x.current=!0,h.current=new AbortController,Q.search(t||"",{mode:"auto",type:"recipe",signal:h.current.signal}).then(m=>{x.current&&l((m.items||[]).map(c=>({name:(c.title||c.name||"")+".md",path:"",content:c.content,qualityScore:(c.quality||{}).overall||c.qualityScore||0,recommendReason:""})))}).catch(m=>{m.name!=="AbortError"&&x.current&&l([])}).finally(()=>{x.current&&p(!1)}),()=>{x.current=!1,h.current&&h.current.abort()}),[t]);const u=async m=>{g(m.name);try{const c=id(m.content);await Q.insertAtSearchMark({path:s,content:c}),x.current&&(alert(r("searchModal.insertSuccess")+" "+s),a())}catch{x.current&&alert(r("searchModal.insertFailed"))}finally{x.current&&g(null)}};return e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-[var(--border-default)] flex justify-between items-center bg-[var(--bg-subtle)]",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx(xt,{size:H.xl,className:"text-blue-600"})," ",r("searchModal.title")]}),e.jsx("button",{onClick:a,className:"p-2 hover:bg-[var(--bg-surface)] rounded-full transition-colors",children:e.jsx(ze,{size:H.lg})})]}),e.jsxs("div",{className:"p-4 text-sm text-[var(--fg-muted)] border-b border-[var(--border-default)]",children:[r("searchModal.keyword")," ",t||r("searchModal.keywordAll")," · ",r("searchModal.insertTo")," ",s]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:i?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):o.length===0?e.jsx("div",{className:"text-[var(--fg-muted)] text-center py-8",children:r("searchModal.noResults")}):e.jsx("ul",{className:"space-y-2",children:o.map(m=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>u(m),disabled:d!==null,className:"w-full flex items-center justify-between gap-3 p-4 rounded-xl border border-[var(--border-default)] hover:border-[var(--accent-emphasis)] hover:bg-[var(--accent-subtle)]/50 transition-all text-left disabled:opacity-50",children:[e.jsxs("div",{className:"flex-1 flex flex-col gap-1",children:[e.jsx("span",{className:"font-medium text-[var(--fg-primary)] truncate",children:m.name}),(m.qualityScore!==void 0||m.recommendReason)&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[m.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",r("searchModal.quality")," ",(m.qualityScore*100).toFixed(0),"%"]}),m.recommendReason&&e.jsx("span",{className:"text-xs text-[var(--fg-secondary)] italic truncate max-w-xs",children:m.recommendReason})]})]}),d===m.name?e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⏳"})," ",r("searchModal.inserting")]}):e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx(kr,{size:H.md})," ",r("searchModal.insertBtn")]})]})},m.name))})})]})]})},Bs=[{id:"google",labelKey:"llmConfig.providers.gemini",defaultModel:"gemini-3-flash-preview",keyEnv:"ASD_GOOGLE_API_KEY"},{id:"openai",labelKey:"llmConfig.providers.openai",defaultModel:"gpt-5.4",keyEnv:"ASD_OPENAI_API_KEY"},{id:"deepseek",labelKey:"llmConfig.providers.deepseek",defaultModel:"deepseek-chat",keyEnv:"ASD_DEEPSEEK_API_KEY"},{id:"claude",labelKey:"llmConfig.providers.claude",defaultModel:"claude-sonnet-4-20250514",keyEnv:"ASD_CLAUDE_API_KEY"},{id:"ollama",labelKey:"llmConfig.providers.ollama",defaultModel:"llama3",keyEnv:""}],dd=({onClose:t,onSaved:s})=>{const{t:a}=Ae(),[r,o]=n.useState(!0),[l,i]=n.useState(!1),[p,d]=n.useState(!1),[g,x]=n.useState("google"),[h,u]=n.useState("gemini-3-flash-preview"),[m,c]=n.useState(""),[j,A]=n.useState(""),[D,I]=n.useState(!1),[P,J]=n.useState({}),[w,B]=n.useState(!1);n.useEffect(()=>{z()},[]);const z=async()=>{o(!0);try{const N=await Q.getLlmEnvConfig();d(N.hasEnvFile);const v=N.vars||{};v.ASD_AI_PROVIDER&&x(v.ASD_AI_PROVIDER),v.ASD_AI_MODEL&&u(v.ASD_AI_MODEL),v.ASD_AI_PROXY&&A(v.ASD_AI_PROXY),J(v)}catch{}finally{o(!1)}},k=Bs.find(N=>N.id===g),E=k?.keyEnv||"",L=E?!!P[E]:!0,O=N=>{x(N);const v=Bs.find(U=>U.id===N);v&&u(v.defaultModel),c("")},W=async()=>{if(g){if(E&&!L&&!m.trim()){alert(a("llmConfig.apiKeyRequired"));return}i(!0),B(!1);try{await Q.saveLlmEnvConfig({provider:g,model:h||void 0,apiKey:m.trim()||void 0,proxy:j.trim()||void 0}),B(!0),setTimeout(()=>{s(),t()},800)}catch(N){alert(ke(N,a("llmConfig.saveFailed")))}finally{i(!1)}}},q=N=>!N||N.length<10?N?"••••••":"":`${N.slice(0,6)}••••${N.slice(-4)}`;return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50",onClick:t,children:e.jsxs("div",{className:"rounded-2xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden bg-[var(--bg-surface)]",onClick:N=>N.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:a("llmConfig.title")}),e.jsx("button",{onClick:t,className:"p-1 rounded-lg transition-all duration-150 hover:bg-[var(--bg-subtle)] text-[var(--fg-muted)] hover:text-[var(--fg-primary)]",children:e.jsx(ze,{size:H.md})})]}),e.jsx("div",{className:"px-6 py-5 space-y-5",children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ne,{size:24,className:"animate-spin text-blue-500"})}):e.jsxs(e.Fragment,{children:[!p&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-700",children:[e.jsx(st,{size:16,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:a("llmConfig.envWarning")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2 text-[var(--fg-primary)]",children:a("llmConfig.provider")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Bs.map(N=>e.jsx("button",{type:"button",onClick:()=>O(N.id),className:`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${g===N.id?"bg-[var(--accent-subtle)] border-[var(--accent-emphasis)] text-[var(--accent)] ring-1 ring-[var(--accent-emphasis)]/30":"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]"}`,children:a(N.labelKey)},N.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:a("llmConfig.model")}),e.jsx("input",{type:"text",value:h,onChange:N=>u(N.target.value),placeholder:k?.defaultModel||"",className:"w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]}),E&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:[a("llmConfig.apiKey"),L&&e.jsxs("span",{className:"ml-2 text-xs text-green-600 font-normal",children:["(",a("llmConfig.configured")," ",q(P[E]),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:D?"text":"password",value:m,onChange:N=>c(N.target.value),placeholder:a(L?"llmConfig.apiKeyPlaceholderSet":"llmConfig.apiKeyPlaceholderEmpty"),className:"w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"}),e.jsx("button",{type:"button",onClick:()=>I(N=>!N),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",children:D?e.jsx(wl,{size:16}):e.jsx(Ut,{size:16})})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:[a("llmConfig.proxy")," ",e.jsx("span",{className:"text-xs font-normal text-[var(--fg-muted)]",children:a("llmConfig.optional")})]}),e.jsx("input",{type:"text",value:j,onChange:N=>A(N.target.value),placeholder:"http://127.0.0.1:7890",className:"w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]})]})}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-[var(--border-default)] bg-[var(--bg-subtle)]",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm font-medium transition-colors text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]",children:a("llmConfig.cancel")}),e.jsxs("button",{onClick:W,disabled:l||r||w,className:`flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-medium transition-all ${w?"bg-green-500 text-white":"bg-blue-600 text-white hover:bg-blue-700 shadow-sm"} disabled:opacity-60`,children:[l?e.jsx(Ne,{size:16,className:"animate-spin"}):w?e.jsx(ht,{size:16}):e.jsx(ws,{size:16}),a(w?"llmConfig.saved":"llmConfig.saveToEnv")]})]})]})})},Wa=200,ud=({open:t,onClose:s})=>{const{t:a}=Ae(),[r,o]=n.useState([]),[l,i]=n.useState(!1),[p,d]=n.useState(""),g=n.useRef(null);n.useEffect(()=>{if(!t)return;let D=!1;Q.getSignalTrace({limit:100}).then(J=>{if(D)return;const w=J.signals.map(B=>({type:B.type,source:B.source,target:B.target,value:B.value,metadata:B.metadata,timestamp:B.timestamp}));o(w)}).catch(()=>{});const I=Cs(),P=J=>{l||o(w=>{const B=[J,...w];return B.length>Wa?B.slice(0,Wa):B})};return I.on("signal:event",P),()=>{D=!0,I.off("signal:event",P)}},[t,l]);const x=p?r.filter(D=>D.type.toLowerCase().includes(p.toLowerCase())||D.source.toLowerCase().includes(p.toLowerCase())):r,h={guard:"text-red-500",search:"text-blue-500",usage:"text-green-500",lifecycle:"text-purple-500",exploration:"text-cyan-500",quality:"text-yellow-500",panorama:"text-indigo-500",decay:"text-orange-500",forge:"text-pink-500"},u={guard:"#ef4444",search:"#3b82f6",usage:"#22c55e",lifecycle:"#a855f7",decay:"#f97316"},m=["guard","search","usage","lifecycle","decay"],c=50,j=n.useMemo(()=>{const D={};for(const P of m)D[P]=0;for(const P of r)P.type in D&&D[P.type]++;const I=Math.max(1,...Object.values(D));return{counts:D,max:I}},[r]),A=n.useMemo(()=>{const D=[];for(const I of m)j.counts[I]>c&&D.push(`${I} 信号量过高 (${j.counts[I]})`);if(r.length>0){const I=r[0].timestamp;Date.now()-I>300*1e3&&D.push("超过 5 分钟未收到新信号")}else t&&D.push("尚未收到任何信号");return D},[r,j,t]);return t?e.jsxs("div",{className:"fixed right-0 top-0 h-full w-80 glass-surface border-l border-[var(--border-muted)] shadow-xl z-50 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-[var(--border-muted)]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"w-4 h-4 text-[var(--accent)]"}),e.jsx("span",{className:"text-sm font-semibold text-[var(--text-primary)]",children:"Signal Monitor"}),e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-[var(--accent)]/10 text-[var(--accent)]",children:r.length})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>i(!l),className:`p-1 rounded text-xs ${l?"text-red-500":"text-green-500"} hover:bg-[var(--bg-elevated)]`,children:l?"▶":"⏸"}),e.jsx("button",{onClick:()=>o([]),className:"p-1 rounded text-xs text-[var(--text-tertiary)] hover:bg-[var(--bg-elevated)]",children:"Clear"}),e.jsx("button",{onClick:s,className:"p-1 rounded text-[var(--text-tertiary)] hover:bg-[var(--bg-elevated)]",children:e.jsx(ze,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"p-2 border-b border-[var(--border-muted)]",children:e.jsx("input",{type:"text",value:p,onChange:D=>d(D.target.value),placeholder:"Filter by type or source...",className:"w-full px-2 py-1 text-xs rounded bg-[var(--bg-elevated)] text-[var(--text-primary)] border border-[var(--border-muted)] focus:outline-none focus:border-[var(--accent)]"})}),e.jsx("div",{ref:g,className:"flex-1 overflow-y-auto min-h-0",children:x.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-[var(--text-tertiary)]",children:[e.jsx(js,{className:"w-5 h-5 mb-2 opacity-50"}),e.jsx("span",{className:"text-xs",children:"Waiting for signals..."})]}):e.jsx("div",{className:"divide-y divide-[var(--border-muted)]",children:x.map((D,I)=>e.jsxs("div",{className:"p-2 hover:bg-[var(--bg-elevated)] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`text-xs font-mono font-semibold ${h[D.type]??"text-[var(--text-secondary)]"}`,children:D.type}),e.jsx("span",{className:"text-[10px] text-[var(--text-tertiary)]",children:new Date(D.timestamp).toLocaleTimeString()})]}),e.jsx("div",{className:"text-[11px] text-[var(--text-tertiary)] mt-0.5 truncate",children:D.source})]},`${D.type}-${D.timestamp}-${I}`))})}),e.jsxs("div",{className:"border-t border-[var(--border-muted)] p-3 shrink-0",children:[e.jsx("h3",{className:"text-xs font-medium text-[var(--fg-muted)] uppercase tracking-wider mb-2",children:"Signal Statistics"}),e.jsx("div",{className:"space-y-1.5",children:m.map(D=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono w-14 text-[var(--text-tertiary)] text-right",children:D}),e.jsx("div",{className:"flex-1 h-3 rounded-sm bg-[var(--bg-elevated)] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-sm transition-all duration-300",style:{width:`${j.counts[D]/j.max*100}%`,backgroundColor:u[D]}})}),e.jsx("span",{className:"text-[10px] font-mono w-6 text-[var(--text-tertiary)] text-right",children:j.counts[D]})]},D))})]}),A.length>0&&e.jsxs("div",{className:"border-t border-[var(--border-muted)] p-3 shrink-0",children:[e.jsx("h3",{className:"text-xs font-medium text-[var(--fg-muted)] uppercase tracking-wider mb-2",children:"Anomaly Alerts"}),e.jsx("div",{className:"space-y-1",children:A.map((D,I)=>e.jsxs("div",{className:"text-[11px] text-yellow-500 bg-yellow-500/10 rounded px-2 py-1",children:["⚠️ ",D]},I))})]})]}):null};class md extends it.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}render(){return this.state.hasError?e.jsxs("div",{style:{padding:40,textAlign:"center"},children:[e.jsx("h2",{style:{color:"#ef4444",marginBottom:12},children:Us.app.errorBoundary.title}),e.jsx("pre",{style:{fontSize:12,color:"#64748b",whiteSpace:"pre-wrap",maxWidth:600,margin:"0 auto"},children:this.state.error?.message}),e.jsx("button",{onClick:()=>{this.setState({hasError:!1,error:null}),window.location.reload()},style:{marginTop:16,padding:"8px 20px",background:"#3b82f6",color:"#fff",border:"none",borderRadius:8,cursor:"pointer"},children:Us.app.errorBoundary.refreshBtn})]}):this.props.children}}function Ht(t,s="ai-scan"){return{title:t.title||"",description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:t.category||"",tags:t.tags||[],kind:t.kind||"",knowledgeType:t.knowledgeType||"",scope:t.scope||"",complexity:t.complexity||"",difficulty:t.difficulty||"",authority:t.authority,lifecycle:t.lifecycle||"pending",source:t.source||s,doClause:t.doClause||"",dontClause:t.dontClause||"",whenClause:t.whenClause||"",topicHint:t.topicHint||"",coreCode:t.coreCode||"",content:t.content||{},constraints:t.constraints||{},reasoning:t.reasoning||{},quality:t.quality||{},stats:t.stats||{},relations:t.relations||{},headers:t.headers||[],headerPaths:t.headerPaths,moduleName:t.moduleName,includeHeaders:t.includeHeaders,createdAt:t.createdAt,updatedAt:t.updatedAt}}const pd=()=>{const t=eo(),s=so(t.user?.role),a=ao(),{t:r}=Ae(),o=()=>{const S=window.location.pathname.replace(/^\//,"").split("/")[0]||"";return $l.includes(S)?S:"help"},[l,i]=n.useState(null),[p,d]=n.useState(o()),[g,x]=n.useState(""),[h,u]=n.useState(!1),[m,c]=n.useState(!0),[j,A]=n.useState(null),[D,I]=n.useState([]),[P,J]=n.useState([]),[w,B]=n.useState(null),[z,k]=n.useState(!1),[E,L]=n.useState({current:0,total:0,status:""}),[O,W]=n.useState([]),[q,N]=n.useState([]),[v,U]=n.useState(null),ae=n.useRef(null),be=S=>{const K=ae.current;return K?`asd:spm:${S}:${K}`:null},me=n.useCallback(S=>{N(K=>{const Y=typeof S=="function"?S(K):S;try{const ie=be("scan-results");ie&&sessionStorage.setItem(ie,JSON.stringify(Y))}catch{}return Y})},[]);n.useEffect(()=>{try{const S=be("selected-target");if(!S)return;w?sessionStorage.setItem(S,w):sessionStorage.removeItem(S)}catch{}},[w]),n.useEffect(()=>{try{const S=be("guard-audit");if(!S)return;v?sessionStorage.setItem(S,JSON.stringify(v)):sessionStorage.removeItem(S)}catch{}},[v]);const[je,G]=n.useState(1),[le,de]=n.useState(12),[R,T]=n.useState(!1),[X,oe]=n.useState(""),[pe,ue]=n.useState(!1),[M,Ce]=n.useState(null),[F,Se]=n.useState(null),[Te,Fe]=n.useState(!1),[Me,ee]=n.useState(!0),[ce,f]=n.useState(!1),[V,xe]=n.useState(0),[fe,C]=n.useState(!1),b=n.useRef(null),_=n.useRef(null);n.useEffect(()=>{G(1)},[g]),n.useEffect(()=>{if(l?.projectRoot)try{const S=`asd:custom-folder-targets:${l.projectRoot}`,K=localStorage.getItem(S);J(K?JSON.parse(K):[])}catch{J([])}},[l?.projectRoot]),n.useEffect(()=>{if(!l?.projectRoot)return;ae.current=l.projectRoot;const S=l.projectRoot;try{B(sessionStorage.getItem(`asd:spm:selected-target:${S}`)||null)}catch{B(null)}try{const K=sessionStorage.getItem(`asd:spm:scan-results:${S}`);N(K?JSON.parse(K):[])}catch{N([])}try{const K=sessionStorage.getItem(`asd:spm:guard-audit:${S}`);U(K?JSON.parse(K):null)}catch{U(null)}},[l?.projectRoot]);const ne=()=>{b.current&&b.current.abort()},[$,y]=n.useState(!1),te=async()=>{if(!$){y(!0);try{b.current&&b.current.abort(),await Q.cancelBootstrap("Cancelled by user via Dashboard")}catch{}finally{y(!1)}}};n.useEffect(()=>{let S=!1;const K=async()=>{try{const ie=await Q.getSignalStatus();if(!S){const ve=ie?.suggestions?.length||0,Re=ie?.snapshot?.lastResult?.newSuggestions||0;xe(ve||Re)}}catch{}};K();const Y=setInterval(K,300*1e3);return()=>{S=!0,clearInterval(Y)}},[]);const ge=n.useRef(null);n.useEffect(()=>{if(a.isAllDone&&a.session){if(ge.current!==a.session.id){ge.current=a.session.id;const S=a.session.failed>0?r("bootstrap.notifyPartial",{completed:a.session.completed,total:a.session.total,failed:a.session.failed}):r("bootstrap.notifySuccess",{completed:a.session.completed});re(S,{title:r("bootstrap.coldStartComplete"),type:a.session.failed>0?"error":"success"})}we()}},[a.isAllDone,a.session?.id]),n.useEffect(()=>{if(a.candidateCreatedTick>0){const S=setTimeout(()=>we(),2e3);return()=>clearTimeout(S)}},[a.candidateCreatedTick]);const he=(S,K)=>{d(S);const Y=K?.preserveSearch&&window.location.search?window.location.search:"";window.history.pushState({},document.title,`/${S}${Y}`)},De=S=>{A(S),d("recipes");const K=new URLSearchParams(window.location.search);K.set("edit",encodeURIComponent(S.name)),window.history.pushState({},document.title,`/recipes?${K.toString()}`)},se=()=>{A(null),window.history.replaceState({},document.title,"/recipes")};n.useEffect(()=>{g===""&&Ce(null)},[g]),n.useEffect(()=>{d(o())},[]),n.useEffect(()=>{if(!l)return;const S=window.location.pathname.replace(/^\//,"").split("/")[0],Y=new URLSearchParams(window.location.search).get("edit");if(S==="recipes"&&Y&&l.recipes)try{const ie=decodeURIComponent(Y),ve=l.recipes.find(Re=>Re.name===ie);ve&&!j&&(d("recipes"),De(ve))}catch{}},[l]),n.useEffect(()=>{we(),Oe(),rt();const S=()=>{d(o())};window.addEventListener("popstate",S);const K=new URLSearchParams(window.location.search),Y=K.get("action"),ie=K.get("path"),ve=K.get("q")||"";return Y==="search"&&ie?Se({q:ve,path:ie}):Y==="create"&&ie&&(oe(ie),T(!0),K.get("autoScan")==="1"&&setTimeout(()=>Xt(ie),500)),Y&&window.history.replaceState({},document.title,window.location.pathname),()=>{window.removeEventListener("popstate",S)}},[]);const we=async()=>{c(!0);try{const S=await Q.fetchData();i(S)}catch(S){re(ke(S,r("app.load.failed")),{title:r("app.load.failedTitle"),type:"error"})}finally{c(!1)}},Oe=async()=>{try{const S=await Q.fetchTargets();I(S)}catch(S){console.warn("删除候选残留失败:",ke(S))}},rt=async()=>{try{const S=await Q.getLlmEnvConfig();ee(S.llmReady)}catch{}},ct=async()=>{try{await Q.refreshProject(),Oe(),re(r("app.projectRefresh.success"),{title:r("app.projectRefresh.successTitle")})}catch{re(r("app.load.failedHint"),{title:r("app.projectRefresh.failed"),type:"error"})}},Xt=async S=>{ue(!0);try{const K=await Q.extractFromPath(S);me(K.result.map(Y=>({...Ht(Y,"extract"),mode:"full",lang:"cn"}))),he("spm"),T(!1),we(),K.result?.length>0&&re(r("app.extract.success"),{title:r("app.extract.successTitle")})}catch{re(r("app.extract.failed"),{type:"error"})}finally{ue(!1)}},nt=async()=>{if(X){ue(!0);try{const S=await Q.extractFromPath(X);me(S.result.map(K=>({...Ht(K,"extract"),mode:"full",lang:"cn"}))),he("spm"),T(!1),we(),S.result?.length>0?re(S.isMarked?r("app.extract.markerSuccess"):r("app.extract.normalSuccess"),{title:r("app.extract.successTitle")}):S.isMarked||re(r("app.extract.noMarker"),{title:r("app.extract.extracting"),type:"info"})}catch{re(r("app.extract.failed"),{type:"error"})}finally{ue(!1)}}},Ss=async S=>{try{const K=await navigator.clipboard.readText();if(!K)return re(r("app.clipboard.empty"),{title:r("app.clipboard.emptyTitle"),type:"info"});re(r("app.clipboard.analyzing"),{title:r("app.clipboard.analyzingTitle"),type:"info"}),ue(!0);const Y=S||X;try{const ie=await Q.extractFromText(K,Y||void 0),ve=ie._multipleCount;me([{...Ht(ie,"clipboard"),mode:"full",lang:"cn"}]),he("spm"),T(!1),we(),re(ve?r("app.clipboard.resultMulti",{count:ve}):r("app.extract.normalSuccess"),{title:r("app.clipboard.resultTitle")})}catch(ie){const ve=ke(ie);Vl(ie)?re(ve,{title:r("app.clipboard.aiFailed"),type:"error"}):re(ve,{title:r("common.operationFailed"),type:"error"})}}catch{re(r("app.clipboard.permissionError"),{title:r("app.clipboard.permissionTitle"),type:"error"})}finally{ue(!1)}},an={"scan:started":{percent:5,status:r("app.scan.events.initializing")},"scan:files-loaded":{percent:15,status:S=>r("app.scan.events.filesLoaded",{count:S.count||0})},"scan:reading":{percent:25,status:S=>r("app.scan.events.readingFiles",{count:S.count||0})},"scan:ai-extracting":{percent:40,status:r("app.scan.events.aiAnalyzing")},"scan:enriching":{percent:85,status:S=>r("app.scan.events.enriching",{count:S.recipeCount||0})},"scan:completed":{percent:95,status:r("app.scan.events.completing")}},rn=async S=>{if(z)return;b.current&&b.current.abort(),_.current&&(clearInterval(_.current),_.current=null);const K=new AbortController;b.current=K,B(S.name),k(!0),me([]),U(null),W([]),L({current:0,total:100,status:r("app.scan.streamInit")});try{const Y=await Q.scanTargetStream(S,Re=>{const Pe=an[Re.type];if(Pe){const _e=typeof Pe.status=="function"?Pe.status(Re):Pe.status;L({current:Pe.percent,total:100,status:_e})}Re.type==="scan:files-loaded"&&Re.files&&W(Re.files),Re.type==="scan:ai-extracting"&&(_.current&&clearInterval(_.current),_.current=setInterval(()=>{L(_e=>({..._e,current:Math.min(_e.current+1,80)}))},3e3)),(Re.type==="scan:enriching"||Re.type==="scan:completed")&&_.current&&(clearInterval(_.current),_.current=null)},K.signal);_.current&&(clearInterval(_.current),_.current=null),L({current:100,total:100,status:r("app.scan.completed")});const ie=Y.recipes||[],ve=Y.scannedFiles||[];if(ie.length>0||ve.length>0){const Re=typeof S=="string"?S:S?.name||"unknown",Pe=ie.map(_e=>({...Ht(_e,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:Re,scanMode:"target"}));if(me(Pe),ve.length>0&&W(ve),we(),ie.length>0)re(r("app.scan.targetSuccess",{count:ie.length}),{title:r("app.scan.targetSuccessTitle")});else if(Y.message){const _e=Y.noAi;re(Y.message,{title:r(_e?"app.scan.aiNotConfigured":"app.scan.noResults"),type:_e?"info":"error"})}else re(r("app.scan.noResults"),{title:r("app.scan.scanComplete"),type:"info"})}else re(r("app.scan.scanFailedHint"),{title:r("app.scan.scanFailed"),type:"error"})}catch(Y){if(_.current&&(clearInterval(_.current),_.current=null),fs(Y))return;const ie=ss(Y),ve=ie?r("app.scan.timeout"):ke(Y,r("app.scan.scanError"));re(ve,{title:r(ie?"app.scan.timeoutTitle":"app.scan.scanError"),type:"error"})}finally{b.current===K&&(k(!1),L({current:0,total:0,status:""}),b.current=null)}},nn=async()=>{if(z)return;b.current&&b.current.abort();const S=new AbortController;b.current=S,he("candidates"),k(!0),me([]),U(null),W([]),L({current:0,total:100,status:r("app.coldStart.collecting")}),a.resetSession();try{const K=await Q.bootstrap(S.signal);L({current:100,total:100,status:r("app.coldStart.skeletonCreated")}),K.bootstrapSession&&a.initFromApiResponse(K.bootstrapSession),we();const Y=K.report||{},ie=K.targets?.length||0,ve=Y.totals?.files||0,Re=Y.totals?.graphEdges||0,Pe=K.guardSummary,_e=Pe?`, ${r("app.coldStart.guardSuffix",{count:Pe.totalViolations})}`:"";re(r("app.coldStart.skeletonDetail",{targets:ie,files:ve,deps:Re})+_e)}catch(K){if(Is(K))return;const ie=ss(K)?r("app.coldStart.timeout"):ke(K);re(ie,{type:"error"})}finally{b.current===S&&(k(!1),L({current:0,total:0,status:""}),b.current=null)}},ln=async()=>{if(z)return;b.current&&b.current.abort();const S=new AbortController;b.current=S,he("candidates"),k(!0),L({current:0,total:100,status:r("app.rescan.analyzing")}),a.resetSession();try{const K=await Q.rescan({reason:"dashboard-rescan"},S.signal);L({current:100,total:100,status:r("app.rescan.done")}),K.bootstrapSession&&a.initFromApiResponse(K.bootstrapSession),we();const Y=K.relevanceAudit||{},ie=K.gapAnalysis||{};re(r("app.rescan.success",{preserved:K.rescan?.preservedRecipes||0,healthy:Y.healthy||0,decayed:(Y.decay||0)+(Y.severe||0)+(Y.dead||0)})+(ie.gapDimensions>0?` ${r("app.rescan.filling",{count:ie.gapDimensions})}`:""))}catch(K){if(Is(K))return;const Y=ss(K)?r("app.rescan.timeout"):ke(K);re(Y,{type:"error"})}finally{b.current===S&&(k(!1),L({current:0,total:0,status:""}),b.current=null)}},on=async()=>{if(z)return;b.current&&b.current.abort();const S=new AbortController;b.current=S,he("spm"),B("__project__"),k(!0),me([]),U(null),W([]),L({current:0,total:100,status:r("app.fullScan.collecting")});const K=[{status:r("app.fullScan.phase5"),percent:5},{status:r("app.fullScan.phase15"),percent:15},{status:r("app.fullScan.phase25"),percent:25},{status:r("app.fullScan.phase35"),percent:35},{status:r("app.fullScan.phase45"),percent:45},{status:r("app.fullScan.phase55"),percent:55},{status:r("app.fullScan.phase65"),percent:65},{status:r("app.fullScan.phase75"),percent:75},{status:r("app.fullScan.phase85"),percent:85}];let Y=0;const ie=setInterval(()=>{Y=Math.min(Y+1,K.length);const ve=K[Y-1];ve&&L(Re=>({...Re,current:ve.percent,status:ve.status}))},15e3);try{const ve=await Q.scanProject(S.signal);clearInterval(ie),L({current:100,total:100,status:ve.partial?r("app.fullScan.partialComplete"):r("app.fullScan.completed")});const Re=ve.recipes||[],Pe=ve.scannedFiles||[];if(Re.length>0||Pe.length>0){const _e=Re.map(vn=>({...Ht(vn,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:"__project__",scanMode:"project"}));me(_e),W(Pe),U(ve.guardAudit||null),we();const Ze=ve.guardAudit?.summary,es=Ze?`, ${r("app.fullScan.guardSuffix",{count:Ze.totalViolations})}`:"",Ft=ve.partial?r("app.fullScan.timeoutSuffix"):"";re(r("app.fullScan.resultDetail",{count:Re.length})+es+Ft)}else re(r("app.fullScan.noContent"))}catch(ve){if(clearInterval(ie),Is(ve))return;const Pe=ss(ve)?r("app.fullScan.timeout"):ke(ve);re(Pe,{type:"error"})}finally{b.current===S&&(k(!1),L({current:0,total:0,status:""}),b.current=null)}},cn=(S,K)=>{const Y=[...q],ie={...Y[S],...K};Y[S]=ie,me(Y)},dn=async S=>{if(!Te){Fe(!0);try{const K=(S.content?.pattern||"").trim(),Y=(()=>{if(!K)return!1;const Ze=K.split(`
|
|
110
110
|
`).filter(Ft=>Ft.trim());return Ze.filter(Ft=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Ft)).length<=Ze.length*.3})(),ie=(S.trigger||"").split(/[,,\s]+/).map(Ze=>Ze.trim()).filter(Boolean);if(Y&&ie.length===0){re(r("app.recipe.triggerRequired"),{type:"error"}),Fe(!1);return}const ve={title:S.title||"Untitled",description:S.description||"",trigger:ie.join(", ")||"",language:S.language||"",category:S.category||"Utility",kind:S.kind||"pattern",knowledgeType:S.knowledgeType||"code-pattern",complexity:S.complexity||"intermediate",scope:S.scope||void 0,difficulty:S.difficulty||"",tags:S.tags||[],source:S.source||"ai-scan",sourceFile:S.sourceFile||"",moduleName:S.moduleName||"",doClause:S.doClause||"",dontClause:S.dontClause||"",whenClause:S.whenClause||"",topicHint:S.topicHint||"",coreCode:S.coreCode||"",content:S.content||{},reasoning:S.reasoning||{},quality:S.quality||{},constraints:S.constraints||{},relations:S.relations||{},stats:S.stats||{},headers:S.headers||[],headerPaths:S.headerPaths||[],includeHeaders:S.includeHeaders||!1},Re=await Q.knowledgeCreate(ve);if(Re?.id)try{await Q.knowledgeLifecycle(Re.id,"publish")}catch(Ze){console.warn("auto-publish after save failed:",Ze)}re(r(Y?"app.recipe.savedAsRecipe":"app.recipe.savedToKb")),me(Ze=>Ze.filter(es=>es.title!==S.title));const Pe=S.candidateTargetName,_e=S.candidateId;if(Pe&&_e)try{await Q.deleteCandidate(_e)}catch{}we()}catch(K){const Y=ka(K)??ps(K);re(Y??r("app.recipe.saveFailed"),{type:"error"})}finally{Fe(!1)}}},un=async()=>{if(!(!j||Te)){Fe(!0);try{const S=j.id||j.name?.replace(/\.md$/,""),K=typeof j.content=="string"?{pattern:j.content,markdown:"",rationale:"",steps:[],codeChanges:[],verification:null}:j.content||{};await Q.knowledgeUpdate(S,{title:j.name?.replace(/\.md$/,"")||"",description:j.description||"",content:K,tags:j.tags||[],kind:j.kind,language:j.language,category:j.category}),se(),we()}catch(S){const K=ka(S)??ps(S);re(K??r("app.recipe.saveRecipeFailed"),{type:"error"})}finally{Fe(!1)}}},mn=async S=>{if(window.confirm(r("common.areYouSure")))try{await Q.deleteRecipe(S),we()}catch(K){const Y=ps(K);re(Y??r("common.deleteFailed"),{type:"error"})}},ua=async(S,K)=>{try{await Q.deleteCandidate(K),me(Y=>Y.filter(ie=>!(ie.candidateId===K&&ie.candidateTargetName===S))),i(Y=>{if(!Y?.candidates)return Y;const ie={...Y.candidates};if(ie[S]){const ve=ie[S].items.filter(Re=>Re.id!==K);ve.length===0?delete ie[S]:ie[S]={...ie[S],items:ve}}return{...Y,candidates:ie}})}catch{re(r("common.operationFailed"),{type:"error"})}},pn=async S=>{if(window.confirm(r("app.candidate.clearConfirm",{name:S})))try{await Q.deleteAllCandidatesInTarget(S),we(),re(r("app.candidate.clearDone",{name:S}))}catch{re(r("common.operationFailed"),{type:"error"})}},xn=async(S,K)=>{try{await Q.promoteToCandidate(S,S.candidateTargetName||w||"_review"),re(r("app.candidate.pushSuccess")),me(Y=>Y.filter((ie,ve)=>ve!==K)),we()}catch(Y){re(ke(Y,r("app.candidate.pushFailed")),{type:"error"})}},gn=(l?.recipes||[]).filter(S=>{if(M)return M.some(ve=>ve.metadata.type==="recipe"&&ve.metadata.name===S.name);const K=S.name||"",Y=typeof S.content=="string"?S.content:[S.content?.pattern,S.content?.markdown].filter(Boolean).join(" ");return K.toLowerCase().includes(g.toLowerCase())||Y.toLowerCase().includes(g.toLowerCase())||(S.description||"").toLowerCase().includes(g.toLowerCase())}).sort((S,K)=>{if(M){const ve=M.find(Pe=>Pe.metadata.name===S.name)?.similarity||0;return(M.find(Pe=>Pe.metadata.name===K.name)?.similarity||0)-ve}const Y=S.stats?.authorityScore??0;return(K.stats?.authorityScore??0)-Y}),ma=it.useMemo(()=>{const S=new Set(D.map(Y=>`${Y.discovererId||""}::${Y.name}`)),K=P.filter(Y=>!S.has(`${Y.discovererId||""}::${Y.name}`));return[...D,...K]},[D,P]),hn=ma.filter(S=>S.name.toLowerCase().includes(g.toLowerCase())).sort((S,K)=>{const Y=ts(S.name),ie=ts(K.name);if(Y&&!ie)return 1;if(!Y&&ie)return-1;const ve=S.isVirtual?1:0,Re=K.isVirtual?1:0;return ve!==Re?ve-Re:S.name.localeCompare(K.name)}),bn=n.useCallback(S=>{J(K=>{if(K.some(ie=>ie.path===S.path))return K;const Y=[...K,S];return l?.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${l.projectRoot}`,JSON.stringify(Y)),Y})},[l?.projectRoot]),fn=n.useCallback(S=>{J(K=>{const Y=K.filter(ie=>ie.path!==S);return l?.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${l.projectRoot}`,JSON.stringify(Y)),Y})},[l?.projectRoot]),As=Object.values(l?.candidates||{}).reduce((S,K)=>S+K.items.length,0);return e.jsx(md,{children:e.jsx(Co,{children:e.jsxs("div",{className:"flex h-screen bg-[var(--bg-root)] text-[var(--fg-primary)] overflow-hidden font-sans ambient-bg",children:[e.jsx(_n,{position:"top-center",toastOptions:{duration:5e3,style:{background:"none",padding:0,boxShadow:"none",border:"none"}},containerStyle:{top:24}}),e.jsx(ro,{activeTab:p,navigateToTab:he,candidateCount:As,signalSuggestionCount:V,currentUser:s.user!=="anonymous"?s.user:void 0,currentRole:s.role,permissionMode:s.mode,onLogout:void 0,projectName:l?.projectName}),e.jsxs("main",{className:"flex-1 flex flex-col overflow-hidden relative",children:[e.jsx(Lo,{setShowCreateModal:T,aiConfig:l?.aiConfig,llmReady:Me,onOpenLlmConfig:()=>f(!0),onBeforeAiSwitch:ne,onAiConfigChange:we,activeTab:p,onOpenCommandPalette:()=>u(!0),projectName:l?.projectName,candidateCount:As,showSignalMonitor:fe,onToggleSignalMonitor:()=>C(S=>!S)}),e.jsx("div",{className:`flex-1 ${p==="wiki"?"overflow-hidden":"overflow-y-auto p-4 xl:p-6 2xl:p-8"}`,children:e.jsx(Nl,{mode:"wait",children:e.jsx(kl.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0,transition:{duration:.2,ease:[.4,0,.2,1]}},exit:{opacity:0,transition:{duration:.15}},className:"h-full",children:m?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--accent-emphasis)]"})}):p==="recipes"?e.jsx(Ci,{recipes:gn,openRecipeEdit:De,handleDeleteRecipe:mn,onRefresh:we,idTitleMap:l?.idTitleMap,currentPage:je,onPageChange:G,pageSize:le,onPageSizeChange:S=>{de(S),G(1)}}):p==="guard"?e.jsx(Wi,{onRefresh:we}):p==="panorama"?e.jsx(pc,{}):p==="skills"?e.jsx(Pc,{onRefresh:we,signalSuggestionCount:V,onSuggestionCountChange:xe}):p==="candidates"?e.jsxs(e.Fragment,{children:[a.session&&e.jsx("div",{className:"mb-4",children:e.jsx(Gc,{session:a.session,isAllDone:a.isAllDone,reviewState:a.reviewState,onDismiss:()=>a.resetSession(),onCancel:te,isCancelling:$})}),e.jsx(Fi,{data:l,isShellTarget:ts,isSilentTarget:Hl,isPendingTarget:Kl,handleDeleteCandidate:ua,onEditRecipe:De,onColdStart:nn,onRescan:ln,isScanning:z,isBootstrapping:a.session?.status==="running",onRefresh:we,onAuditCandidate:(S,K)=>{const Y=(S.content?.pattern||"").trim(),ie=!!Y&&(()=>{const ve=Y.split(`
|
|
111
111
|
`).filter(Pe=>Pe.trim());return ve.filter(Pe=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Pe)).length<=ve.length*.3})();me([{...S,mode:ie?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:S.difficulty||S.complexity||"intermediate",authority:S.stats?.authority||3,candidateId:S.id,candidateTargetName:K}]),he("spm")},onAuditAllInTarget:(S,K)=>{me(S.map(Y=>{const ie=(Y.content?.pattern||"").trim(),ve=!!ie&&(()=>{const Re=ie.split(`
|
|
112
112
|
`).filter(_e=>_e.trim());return Re.filter(_e=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(_e)).length<=Re.length*.3})();return{...Y,mode:ve?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:Y.difficulty||Y.complexity||"intermediate",authority:Y.stats?.authority||3,candidateId:Y.id,candidateTargetName:K}})),he("spm")},handleDeleteAllInTarget:pn})]}):p==="knowledge"?e.jsx(Ec,{onRefresh:ct,idTitleMap:l?.idTitleMap}):p==="spm"?e.jsx(Hi,{targets:ma,filteredTargets:hn,selectedTargetName:w,isScanning:z,scanProgress:E,scanFileList:O,scanResults:q,guardAudit:v,handleScanTarget:rn,handleScanProject:on,handleUpdateScanResult:cn,handleSaveExtracted:dn,handlePromoteToCandidate:xn,handleDeleteCandidate:ua,onEditRecipe:De,isShellTarget:ts,recipes:l?.recipes??[],isSavingRecipe:Te,handleRefreshProject:ct,onAddCustomFolder:bn,onRemoveCustomFolder:fn}):p==="wiki"?e.jsx(Qc,{}):p==="signals"?e.jsx(rd,{}):p==="help"?e.jsx(Ri,{}):e.jsx(Cc,{})},p)})}),j&&e.jsx(ld,{editingRecipe:j,setEditingRecipe:A,handleSaveRecipe:un,closeRecipeEdit:se,isSavingRecipe:Te}),R&&e.jsx(od,{setShowCreateModal:T,createPath:X,setCreatePath:oe,handleCreateFromPath:nt,handleCreateFromClipboard:Ss,isExtracting:pe}),F&&e.jsx(cd,{searchQ:F.q,insertPath:F.path,onClose:()=>{Se(null),window.history.replaceState({},document.title,window.location.pathname)}}),ce&&e.jsx(dd,{onClose:()=>f(!1),onSaved:()=>{rt(),we()}}),e.jsx(ud,{open:fe,onClose:()=>C(!1)})]}),e.jsx(xd,{}),e.jsx($o,{open:h,onOpenChange:u,navigateToTab:he,setShowCreateModal:T,searchQuery:g,setSearchQuery:x,onOpenLlmConfig:()=>f(!0),candidateCount:As})]})})})},xd=()=>{const{isOpen:t}=Zt();return t?e.jsx(So,{}):null};zn.createRoot(document.getElementById("root")).render(e.jsx(it.StrictMode,{children:e.jsx(Tl,{children:e.jsx(Dl,{children:e.jsx(pd,{})})})}));
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>AutoSnippet Dashboard</title>
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-8b1Gf3Bb.js"></script>
|
|
9
9
|
<link rel="modulepreload" crossorigin href="/assets/yaml-qRaU8Ldn.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/vendor-BZEJEVBn.js">
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/icons-BMNb0V6L.js">
|
|
@@ -252,7 +252,7 @@ export class AgentRuntime {
|
|
|
252
252
|
// ─── 提取方法: reactLoop 内部阶段 ────────────
|
|
253
253
|
/** 初始化循环上下文 — 封装 reactLoop 前 ~60 行初始化逻辑 */
|
|
254
254
|
#initLoop(prompt, opts) {
|
|
255
|
-
const { history = [], context = {}, capabilityOverride, budgetOverride, systemPromptOverride, onToolCall, contextWindow, tracker, trace, memoryCoordinator, sharedState, source, toolChoiceOverride, } = opts;
|
|
255
|
+
const { history = [], context = {}, capabilityOverride, budgetOverride, systemPromptOverride, onToolCall, contextWindow, tracker, trace, memoryCoordinator, sharedState, source, toolChoiceOverride, abortSignal, } = opts;
|
|
256
256
|
// 解析 capabilities
|
|
257
257
|
const caps = capabilityOverride
|
|
258
258
|
? this.#resolveCapabilities(capabilityOverride)
|
|
@@ -314,6 +314,7 @@ export class AgentRuntime {
|
|
|
314
314
|
context: context || {},
|
|
315
315
|
contextWindow: contextWindow || null,
|
|
316
316
|
toolChoiceOverride: toolChoiceOverride || null,
|
|
317
|
+
abortSignal: abortSignal || null,
|
|
317
318
|
});
|
|
318
319
|
}
|
|
319
320
|
/**
|
|
@@ -321,6 +322,11 @@ export class AgentRuntime {
|
|
|
321
322
|
* @returns true = 应退出循环
|
|
322
323
|
*/
|
|
323
324
|
#shouldExit(ctx) {
|
|
325
|
+
// 外部中止信号 — 立即退出
|
|
326
|
+
if (ctx.abortSignal?.aborted) {
|
|
327
|
+
this.logger.info('[AgentRuntime] ⛔ abortSignal fired — exiting loop');
|
|
328
|
+
return true;
|
|
329
|
+
}
|
|
324
330
|
// ExplorationTracker: tick + 退出检查
|
|
325
331
|
if (ctx.tracker) {
|
|
326
332
|
ctx.tracker.tick();
|
|
@@ -451,6 +457,7 @@ export class AgentRuntime {
|
|
|
451
457
|
systemPrompt: effectiveSystemPrompt,
|
|
452
458
|
temperature: ctx.budget.temperature ?? (ctx.isSystem ? 0.3 : 0.7),
|
|
453
459
|
maxTokens: ctx.budget.maxTokens ?? (ctx.isSystem ? 8192 : 4096),
|
|
460
|
+
abortSignal: ctx.abortSignal ?? undefined,
|
|
454
461
|
}));
|
|
455
462
|
ctx.consecutiveAiErrors = 0;
|
|
456
463
|
}
|
|
@@ -518,6 +525,11 @@ export class AgentRuntime {
|
|
|
518
525
|
* @returns continueResult() 或 null (退出)
|
|
519
526
|
*/
|
|
520
527
|
async #handleAiError(ctx, aiErr) {
|
|
528
|
+
// AbortError — 外部中止信号已触发,不计入错误计数,立即退出
|
|
529
|
+
if (ctx.abortSignal?.aborted) {
|
|
530
|
+
this.logger.info('[AgentRuntime] ⛔ abortSignal fired during LLM call — exiting');
|
|
531
|
+
return null;
|
|
532
|
+
}
|
|
521
533
|
ctx.consecutiveAiErrors++;
|
|
522
534
|
this.logger.warn(`[AgentRuntime] AI call failed (attempt ${ctx.consecutiveAiErrors}): ${aiErr.message}`);
|
|
523
535
|
ctx.tracker?.rollbackTick?.();
|
|
@@ -106,6 +106,8 @@ export interface ReactLoopOpts {
|
|
|
106
106
|
sharedState?: Record<string, unknown>;
|
|
107
107
|
source?: string;
|
|
108
108
|
toolChoiceOverride?: string | null;
|
|
109
|
+
/** 外部中止信号 — PipelineStrategy hard timeout 时取消进行中的 LLM 调用 */
|
|
110
|
+
abortSignal?: AbortSignal;
|
|
109
111
|
[key: string]: unknown;
|
|
110
112
|
}
|
|
111
113
|
/** 单次迭代允许的最大工具调用数 */
|