import{b as R,r as p,u as C,c as w,j as e}from"./query-Bw69rE6b.js";import{e as Re}from"./react-CQKYBN-P.js";import{P as et}from"./PageHeader-qtVByY5c.js";import{C as O,a as I,b as U}from"./Card-nuKO-lKR.js";import{S as G}from"./StatusPill-DBEWzsQ3.js";import{E as M}from"./EmptyState-CgO0CCgi.js";import{d as X,b as y,Z,a as H,p as ee,_ as he,B as te,$ as tt,a0 as st,R as Ke,j as fe,I as Me,e as le,V as re,c as V,t as ze,v as Be,w as Oe,x as B,D as Ie,S as Ue,k as be,g as nt,U as de,a1 as at,a2 as rt,Y,a3 as it,a4 as Qe}from"./index-CoUu6FiM.js";import{M as se}from"./Modal-t7k2CeNu.js";import{J as He}from"./JobProgress-CArMtskB.js";import{A as J}from"./AlertDialog-IkMNJ6QG.js";import{R as Q}from"./RouteState-Cu5M7yS-.js";import{F as ie}from"./Field-8f_CfRxg.js";import{B as K}from"./Badge-DwoQNRW3.js";import{U as Je}from"./users-jdZTWVcJ.js";import{E as ot}from"./eye-DjFgzw_3.js";import{C as ge}from"./code-zqIp-0hD.js";import{P as ce}from"./pencil-ByuKsEO5.js";import"./rotate-ccw-CDH4c_fo.js";/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const lt=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],dt=X("circle-x",lt);/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ct=[["path",{d:"M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z",key:"1vdc57"}],["path",{d:"M5 21h14",key:"11awu3"}]],mt=X("crown",ct);/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ut=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],We=X("shield-check",ut);/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const xt=[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]],pt=X("shield-off",xt);/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ht=[["path",{d:"m16 11 2 2 4-4",key:"9rsbq5"}],["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],ft=X("user-check",ht);/**
 * @license lucide-react v0.577.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const bt=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]],gt=X("user-x",bt);function Ge(s){if(!s||!Number.isFinite(s))return"never";const r=Date.now()/1e3,t=Math.max(0,r-s);if(t<30)return"just now";if(t<60)return"less than a minute ago";const l=Math.floor(t/60);if(l<60)return`${l} minute${l===1?"":"s"} ago`;const n=Math.floor(t/3600);if(n<24)return`${n} hour${n===1?"":"s"} ago`;const o=Math.floor(t/86400);if(o===1)return"yesterday";if(o<30)return`${o} days ago`;const i=Math.floor(t/(86400*30));if(i<12)return`${i} month${i===1?"":"s"} ago`;const d=Math.floor(t/(86400*365));return`${d} year${d===1?"":"s"} ago`}function Ve(s){s.invalidateQueries({queryKey:["profiles","db"]}),s.invalidateQueries({queryKey:["db-profiles","list"]}),s.invalidateQueries({queryKey:["context"]}),s.invalidateQueries({queryKey:["live-catalogs"]}),s.invalidateQueries({queryKey:["live-databases"]}),s.invalidateQueries({queryKey:["live-schemas"]}),s.invalidateQueries({queryKey:["live-assets"]}),s.invalidateQueries({queryKey:["recent-runs"]})}function yt({llmProfile:s}){const r=R(),[t,l]=p.useState(""),[n,o]=p.useState(""),[i,d]=p.useState(""),[h,b]=p.useState(""),[u,a]=p.useState(!1),m=s??"",c=!!m,x=C({queryKey:["profiles","db","for-style"],queryFn:()=>y("/api/profiles/db"),retry:!1});p.useEffect(()=>{!t&&x.data?.profiles?.length&&l(x.data.profiles[0].name)},[t,x.data]);const N=C({queryKey:["live-catalogs",t,"for-style"],queryFn:()=>H.liveCatalogs({profile:t}),enabled:!!t,retry:!1}),k=N.data?.supports_catalogs??!1,_=C({queryKey:["live-databases",t,"for-style"],queryFn:()=>H.liveDatabases({profile:t}),enabled:t&&N.data?!k:!1,retry:!1}),g=p.useMemo(()=>k?N.data?.catalogs??[]:_.data?.databases??[],[k,N.data,_.data]);p.useEffect(()=>{o(""),d(""),b("")},[t]),p.useEffect(()=>{d(""),b("")},[n]),p.useEffect(()=>{b("")},[i]);const T=C({queryKey:["live-schemas",t,k?"cat":"db",n,"for-style"],queryFn:()=>H.liveSchemas({profile:t,kind:k?"catalog":"database",catalog:k?n:void 0,database:k?void 0:n}),enabled:!!(t&&n),retry:!1}),j=C({queryKey:["live-assets",t,k?"cat":"db",n,i,"for-style"],queryFn:()=>H.liveAssets({profile:t,kind:k?"catalog":"database",catalog:k?n:void 0,database:k?void 0:n},i),enabled:!!(t&&n&&i),retry:!1}),D=t&&n&&i&&h?`${n}.${i}.${h}`:"",$=C({queryKey:["style",m],queryFn:async()=>{try{return await y(`/api/llm-profiles/${encodeURIComponent(m)}/style`)}catch(A){if(A.status===404)return null;throw A}},enabled:c,retry:!1}),v=w({mutationFn:A=>y(`/api/llm-profiles/${encodeURIComponent(m)}/style/extract`,{method:"POST",body:JSON.stringify(A)}),onSuccess:()=>r.invalidateQueries({queryKey:["style",m]})}),F=w({mutationFn:A=>y(`/api/llm-profiles/${encodeURIComponent(m)}/style`,{method:"PATCH",body:JSON.stringify({enabled:A})}),onSuccess:()=>r.invalidateQueries({queryKey:["style",m]})}),E=w({mutationFn:()=>y(`/api/llm-profiles/${encodeURIComponent(m)}/style`,{method:"DELETE"}),onSuccess:()=>r.invalidateQueries({queryKey:["style",m]})});if(!m)return e.jsx(O,{children:e.jsx(I,{title:"Writing style reference",description:"Activate an LLM profile to configure a style reference."})});const P=$.data,q=v.isPending||F.isPending||E.isPending;return e.jsxs(O,{children:[e.jsx(I,{title:"Writing style reference",description:P?`Attached to '${m}'. AMX matches this style on runs.`:`Attach a reference table so AMX matches your description style for '${m}'.`}),e.jsxs(U,{children:[v.isPending?e.jsx("div",{className:"text-sm text-ink-dim",children:"Extracting style…"}):P?e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:["Source: ",e.jsx("code",{className:"font-mono",children:P.source_ref})," ·"," ","backend: ",e.jsx("span",{className:"font-mono",children:P.source_db_kind})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-ink-muted",children:[e.jsxs("div",{children:["Language: ",P.profile.language]}),e.jsxs("div",{children:["Tone: ",P.profile.tone]}),e.jsxs("div",{children:["Length: ",P.profile.length_range[0],"–",P.profile.length_range[1]," words"]}),e.jsxs("div",{children:["Samples: ",P.sample_count]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer text-xs text-ink-dim",children:"Raw profile JSON"}),e.jsx("pre",{className:"mt-2 max-h-72 overflow-auto rounded-md bg-surface-subtle p-3 text-xs",children:JSON.stringify(P.profile,null,2)})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:P.enabled,disabled:q,onChange:A=>F.mutate(A.target.checked)}),"Use this style on runs"]}),e.jsx($e,{dbProfiles:x.data?.profiles??[],dbProfile:t,onDbProfileChange:l,supportsCatalogs:k,catOrDbOptions:g,catOrDbLoading:N.isLoading||_.isLoading,catalogOrDb:n,onCatOrDbChange:o,schemaOptions:T.data?.schemas??[],schemaLoading:T.isLoading,schema:i,onSchemaChange:d,tableOptions:(j.data?.assets??[]).map(A=>A.name),tableLoading:j.isLoading,table:h,onTableChange:b,busy:q}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:!D||q,onClick:()=>v.mutate({source_ref:D,db_profile:t}),className:"rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90 disabled:opacity-50",children:"Re-extract"}),e.jsx("button",{type:"button",disabled:q,onClick:()=>a(!0),className:"rounded-md border border-surface-border px-3 py-1.5 text-sm text-ink-muted hover:bg-surface-subtle",children:"Clear"})]})]}):e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx("p",{className:"text-ink-muted",children:"Provide a reference table whose column comments show your team's writing style. AMX reads only column comments — never row data — and distills a style profile used on future runs. Domain terms from the reference table are never leaked into other tables' descriptions."}),e.jsx($e,{dbProfiles:x.data?.profiles??[],dbProfile:t,onDbProfileChange:l,supportsCatalogs:k,catOrDbOptions:g,catOrDbLoading:N.isLoading||_.isLoading,catalogOrDb:n,onCatOrDbChange:o,schemaOptions:T.data?.schemas??[],schemaLoading:T.isLoading,schema:i,onSchemaChange:d,tableOptions:(j.data?.assets??[]).map(A=>A.name),tableLoading:j.isLoading,table:h,onTableChange:b,busy:q}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsx("button",{type:"button",disabled:!D||q,onClick:()=>v.mutate({source_ref:D,db_profile:t}),className:"rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90 disabled:opacity-50",children:"Extract style"})})]}),v.isError&&e.jsxs("div",{className:"mt-3 rounded-md bg-critical/10 px-3 py-2 text-sm text-critical",children:["Extract failed: ",v.error.message]})]}),e.jsx(J,{open:u,onClose:()=>{E.isPending||a(!1)},onConfirm:()=>E.mutate(void 0,{onSettled:()=>a(!1)}),title:`Clear style reference for '${m}'?`,description:"The extracted style profile is removed from this LLM. Future runs fall back to the default tone until you attach a new reference.",confirmLabel:"Clear",loading:E.isPending})]})}function oe({label:s,hint:r,children:t}){return e.jsxs("label",{className:"flex flex-col gap-1 text-xs text-ink-dim",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium uppercase tracking-wide",children:s}),r?e.jsx("span",{className:"text-ink-dim/80 normal-case",children:r}):null]}),t]})}function $e({dbProfiles:s,dbProfile:r,onDbProfileChange:t,supportsCatalogs:l,catOrDbOptions:n,catOrDbLoading:o,catalogOrDb:i,onCatOrDbChange:d,schemaOptions:h,schemaLoading:b,schema:u,onSchemaChange:a,tableOptions:m,tableLoading:c,table:x,onTableChange:N,busy:k}){if(s.length===0)return e.jsx("div",{className:"rounded-md border border-dashed border-surface-border bg-surface-subtle px-3 py-2 text-sm text-ink-muted",children:"Add a DB profile from the Database tab to pick a reference table."});const _=l?"Catalog":"Database";return e.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(oe,{label:"DB profile",children:e.jsx(Z,{value:r,disabled:k,onChange:g=>t(g.target.value),children:s.map(g=>e.jsxs("option",{value:g.name,children:[g.name," (",g.backend,")"]},g.name))})}),e.jsx(oe,{label:_,hint:r&&o?"loading…":void 0,children:e.jsxs(Z,{value:i,disabled:k||!r||o||n.length===0,onChange:g=>d(g.target.value),children:[e.jsx("option",{value:"",children:n.length===0&&!o?`(no ${_.toLowerCase()}s visible)`:`Select a ${_.toLowerCase()}…`}),n.map(g=>e.jsx("option",{value:g,children:g},g))]})}),e.jsx(oe,{label:"Schema",hint:i&&b?"loading…":void 0,children:e.jsxs(Z,{value:u,disabled:k||!i||b||h.length===0,onChange:g=>a(g.target.value),children:[e.jsx("option",{value:"",children:h.length===0&&!b&&i?"(no schemas visible)":"Select a schema…"}),h.map(g=>e.jsx("option",{value:g,children:g},g))]})}),e.jsx(oe,{label:"Table",hint:u&&c?"loading…":void 0,children:e.jsxs(Z,{value:x,disabled:k||!u||c||m.length===0,onChange:g=>N(g.target.value),children:[e.jsx("option",{value:"",children:m.length===0&&!c&&u?"(no tables visible)":"Select a table…"}),m.map(g=>e.jsx("option",{value:g,children:g},g))]})})]})}const Xe={docs:"Docs RAG embedding",code:"Code RAG embedding"},jt={docs:"Vectorises documentation chunks for /search and /ask retrieval.",code:"Vectorises code snippets for /code search and the code agent."},vt="********";function kt(){const s=C({queryKey:["embedding","kinds"],queryFn:()=>y("/api/profiles/embedding/kinds"),staleTime:6e5}),r=C({queryKey:["embedding"],queryFn:()=>y("/api/profiles/embedding")}),t=C({queryKey:["embedding","status"],queryFn:()=>y("/api/profiles/embedding/status")});if(s.isPending||r.isPending)return e.jsxs("div",{className:"flex items-center gap-2 py-8 text-sm text-ink-dim",children:[e.jsx(ee,{size:14,className:"animate-spin"})," Loading embedding settings…"]});if(s.error||r.error)return e.jsx("div",{className:"rounded-md border border-critical/40 bg-critical/10 px-3 py-2 text-sm text-critical",children:"Failed to load embedding settings."});const l=s.data.kinds,n=s.data.presets,o=r.data,i=t.data;return e.jsx("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:Object.keys(Xe).map(d=>e.jsx(Nt,{side:d,kinds:l,presets:n,initial:o[d],status:i?.[d]},d))})}function Nt({side:s,kinds:r,presets:t,initial:l,status:n}){const o=R(),[i,d]=p.useState(l.kind||"minilm"),[h,b]=p.useState(l.model||""),[u,a]=p.useState(l.base_url||""),[m,c]=p.useState(l.api_key||""),[x,N]=p.useState(null),[k,_]=p.useState(!1);p.useEffect(()=>{d(l.kind||"minilm"),b(l.model||""),a(l.base_url||""),c(l.api_key||"")},[l.kind,l.model,l.base_url,l.api_key]);const g=r.find(S=>S.id===i)??r[0],T=g?.needs_model??!1,j=g?.needs_key??!1,D=g?.needs_base??!1,$=w({mutationFn:()=>y(`/api/profiles/embedding/${s}`,{method:"PUT",body:JSON.stringify({kind:i,model:T?h:"",base_url:D?u:"",api_key:j?m:""})}),onSuccess:()=>{o.invalidateQueries({queryKey:["embedding"]}),o.invalidateQueries({queryKey:["embedding","status"]})}}),v=w({mutationFn:()=>y(`/api/profiles/embedding/${s}/test`,{method:"POST",body:JSON.stringify({kind:i,model:T?h:"",base_url:D?u:"",api_key:j?m:""})}),onSuccess:S=>N(S),onError:S=>N({ok:!1,message:S.message||"Test failed"})}),F=w({mutationFn:()=>y(`/api/profiles/embedding/${s}/rebuild`,{method:"POST",body:JSON.stringify({})}),onSuccess:()=>{o.invalidateQueries({queryKey:["embedding","status"]}),s==="docs"&&o.invalidateQueries({queryKey:["profiles","docs"]}),s==="code"&&o.invalidateQueries({queryKey:["profiles","code"]})},onSettled:()=>_(!1)}),E=S=>{const z=t.find(ne=>ne.id===S);z&&a(z.base_url)},P=i==="minilm"?!0:!(T&&!h.trim()),q=(n?.collections??[]).reduce((S,z)=>S+(z.count||0),0),A=n?.collections?.length??0;return e.jsxs(O,{children:[e.jsx(I,{title:Xe[s],description:jt[s]}),e.jsxs(U,{className:"flex flex-col gap-4",children:[e.jsxs("fieldset",{className:"flex flex-col gap-2",children:[e.jsx("legend",{className:"text-xs font-medium text-ink-muted",children:"Provider"}),e.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(S=>{const z=!S.available;return e.jsxs("label",{className:"flex cursor-pointer items-start gap-2 rounded-md border border-surface-border px-3 py-2 text-sm transition hover:border-accent "+(i===S.id?"border-accent bg-accent/5":"")+(z?" cursor-not-allowed opacity-50 hover:border-surface-border":""),children:[e.jsx("input",{type:"radio",name:`kind-${s}`,value:S.id,checked:i===S.id,disabled:z,onChange:()=>d(S.id),className:"mt-1"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:S.label}),e.jsx("span",{className:"text-xs text-ink-dim",children:S.hint})]})]},S.id)})})]}),i==="openai_compatible"&&e.jsx(ie,{label:"Preset (optional)",children:e.jsxs(Z,{value:"",onChange:S=>E(S.target.value),children:[e.jsx("option",{value:"",children:"Pick a preset…"}),t.map(S=>e.jsx("option",{value:S.id,children:S.label},S.id))]})}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[T&&e.jsx(ie,{label:"Model",required:!0,description:i==="openai_compatible"?"e.g. text-embedding-3-small":"HuggingFace model id, e.g. BAAI/bge-large-en-v1.5",children:e.jsx(he,{value:h,onChange:S=>b(S.target.value),placeholder:"model-id"})}),D&&e.jsx(ie,{label:"Base URL",description:"The /embeddings endpoint.",children:e.jsx(he,{value:u,onChange:S=>a(S.target.value),placeholder:"https://api.openai.com/v1"})}),j&&e.jsx(ie,{label:"API key",description:"Stored in the OS keyring, never in YAML.",children:e.jsx(he,{type:"password",value:m,onChange:S=>c(S.target.value),placeholder:vt})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(te,{variant:"secondary",disabled:!P||v.isPending,onClick:()=>v.mutate(),children:v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{size:13,className:"mr-1 animate-spin"})," Testing…"]}):"Test connection"}),e.jsx(te,{variant:"primary",disabled:!P||$.isPending,onClick:()=>$.mutate(),children:$.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{size:13,className:"mr-1 animate-spin"})," Saving…"]}):"Save"}),x&&e.jsxs(K,{tone:x.ok?"positive":"critical",children:[x.ok?e.jsx(tt,{size:11}):e.jsx(dt,{size:11})," ",x.ok?`OK${x.dim?` · dim ${x.dim}`:""}`:x.message]}),$.isSuccess&&!$.isPending&&e.jsx(K,{tone:"positive",children:"Saved"}),$.error&&e.jsx(K,{tone:"critical",children:$.error.message})]}),n?.stale&&e.jsx("div",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(st,{size:14,className:"mt-0.5 text-amber-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium",children:"Vectors are stale"}),e.jsxs("div",{className:"text-xs text-ink-dim",children:[A," collection",A===1?"":"s"," · ",q.toLocaleString()," chunks embedded with a different provider. Rebuild to re-embed with the active settings."]}),e.jsx("div",{className:"mt-2",children:e.jsx(te,{variant:"secondary",onClick:()=>_(!0),disabled:F.isPending,children:F.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ee,{size:13,className:"mr-1 animate-spin"})," Rebuilding…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ke,{size:13,className:"mr-1"})," Rebuild"," ",s==="docs"?"docs":"code"]})})})]})]})}),e.jsx(J,{open:k,title:`Rebuild ${s} embeddings?`,description:`This clears ${A} collection${A===1?"":"s"} (${q.toLocaleString()} chunks) and re-embeds them with the active provider. Existing data is preserved; only the vector index is rebuilt.`,confirmLabel:"Rebuild",onConfirm:()=>F.mutate(),onClose:()=>_(!1),loading:F.isPending,tone:"danger"})]})]})}function St(){const s=R(),r=fe(),t=C({queryKey:["history-store-status"],queryFn:()=>y("/api/admin/history-store-status"),retry:!1}),l=C({queryKey:["profiles","db","list"],queryFn:()=>y("/api/profiles/db"),retry:!1}),[n,o]=p.useState(""),[i,d]=p.useState("AMX"),[h,b]=p.useState(""),[u,a]=p.useState(!0),c=((l.data?.profiles??[]).find(g=>g.name===n)?.backend||"").toLowerCase(),x=c==="databricks"||c==="bigquery"||c==="snowflake"||c==="mssql",N=c==="databricks"?"Catalog":c==="bigquery"?"Project":"Database",k=w({mutationFn:g=>H.enableHistoryStore({profile:g.profile,schema:g.schema,database:g.database,create_missing:g.create_missing}),onSuccess:()=>{s.invalidateQueries({queryKey:["history-store-status"]}),r.push({title:"Team history store enabled",description:"Future runs will dual-write to the team schema.",tone:"success"}),o("")},onError:g=>r.push({title:"Could not enable",description:g.message,tone:"error"})}),_=w({mutationFn:()=>H.disableHistoryStore(),onSuccess:()=>{s.invalidateQueries({queryKey:["history-store-status"]}),r.push({title:"Team history store disabled",description:"Runs revert to local-only writes.",tone:"info"})},onError:g=>r.push({title:"Could not disable",description:g.message,tone:"error"})});return e.jsxs(O,{children:[e.jsx(I,{title:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Je,{size:16,className:"text-accent"}),"Team history store",e.jsx(Me,{text:"When enabled, every /run dual-writes to a shared team database so colleagues can replay each other's runs. Configure from CLI with `/team enable`; this card is read-only."})]}),actions:e.jsxs("button",{type:"button",onClick:()=>t.refetch(),className:"inline-flex items-center gap-1 rounded-md bg-surface-subtle px-2.5 py-1 text-xs text-ink-muted hover:bg-surface-border",children:[e.jsx(Ke,{size:12}),"Refresh"]})}),e.jsx(U,{children:t.isLoading?e.jsx("div",{className:"text-sm text-ink-dim",children:"Loading…"}):t.error?e.jsx("div",{className:"text-sm text-critical",children:t.error.message}):t.data?e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(G,{tone:t.data.enabled?"positive":"neutral",children:t.data.enabled?"Active":"Disabled"}),t.data.outbox_pending>0&&e.jsxs(G,{tone:"warning",children:[t.data.outbox_pending," retry queue"]}),t.data.enabled&&t.data.outbox_pending===0&&e.jsx(G,{tone:"positive",children:"in sync"})]}),e.jsxs("p",{className:"text-xs text-ink-muted",children:["When enabled, every ",e.jsx("code",{className:"font-mono",children:"/run"})," ","dual-writes its history into a Postgres/MySQL schema your teammates also point at, so anyone can replay each other's runs. Reads stay local; only writes are mirrored."]}),e.jsxs("dl",{className:"grid grid-cols-1 gap-2 text-xs sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-md border border-border bg-surface-subtle/40 px-3 py-2",children:[e.jsx("dt",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:"Target profile"}),e.jsx("dd",{className:"mt-0.5 font-mono text-ink",children:t.data.profile||"—"})]}),e.jsxs("div",{className:"rounded-md border border-border bg-surface-subtle/40 px-3 py-2",children:[e.jsx("dt",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:"Target schema"}),e.jsx("dd",{className:"mt-0.5 font-mono text-ink",children:t.data.schema||"—"})]}),e.jsxs("div",{className:"rounded-md border border-border bg-surface-subtle/40 px-3 py-2",children:[e.jsx("dt",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:"Outbox depth"}),e.jsx("dd",{className:"mt-0.5 font-mono tabular-nums text-ink",children:t.data.outbox_pending})]}),e.jsxs("div",{className:"rounded-md border border-border bg-surface-subtle/40 px-3 py-2",children:[e.jsx("dt",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:"Mode"}),e.jsx("dd",{className:"mt-0.5 font-mono text-ink",children:t.data.enabled?"dual-write":"local-only"})]})]}),t.data.enabled?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border border-border bg-surface-subtle/30 px-3 py-2 text-xs",children:[e.jsx("span",{className:"text-ink-muted",children:"Dual-write is on. Switch back to local-only with the button."}),e.jsx(te,{variant:"subtle",size:"sm",loading:_.isPending,onClick:()=>_.mutate(),children:"Disable"})]}):e.jsxs("div",{className:"space-y-3 rounded-md border border-border bg-surface-subtle/30 px-3 py-2.5 text-xs text-ink-muted",children:[e.jsx("p",{className:"font-medium text-ink",children:"Enable team history store"}),e.jsx("p",{className:"text-[11px] text-ink-dim",children:"Pick a DB profile to dual-write into. For Databricks / BigQuery / Snowflake / MSSQL also pick the target catalog or database so tables don't land in the workspace default."}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:[e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:"DB profile"}),e.jsxs("select",{value:n,onChange:g=>o(g.target.value),className:"h-8 w-full rounded-md border border-border bg-surface-raised px-2 text-xs text-ink focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/20",children:[e.jsx("option",{value:"",children:"Select target profile…"}),(l.data?.profiles??[]).map(g=>e.jsxs("option",{value:g.name,children:[g.name,g.backend?` (${g.backend})`:""]},g.name))]})]}),x&&e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:N}),e.jsx("input",{type:"text",value:h,onChange:g=>b(g.target.value),placeholder:`${N.toLowerCase()} name`,className:"h-8 w-full rounded-md border border-border bg-surface-raised px-2 font-mono text-xs text-ink focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/20"})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-ink-dim",children:"Schema"}),e.jsx("input",{type:"text",value:i,onChange:g=>d(g.target.value),placeholder:"Schema name",className:"h-8 w-full rounded-md border border-border bg-surface-raised px-2 font-mono text-xs text-ink focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/20"})]})]}),x&&e.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-ink-muted",children:[e.jsx("input",{type:"checkbox",checked:u,onChange:g=>a(g.target.checked),className:"h-3 w-3 rounded border-border accent-accent"}),"Create ",N.toLowerCase()," if it doesn't exist yet",c==="databricks"&&e.jsx("span",{className:"ml-1 text-ink-dim",children:"(requires Unity Catalog metastore-admin)"})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(te,{variant:"primary",size:"sm",loading:k.isPending,disabled:!n||!i||x&&!h||k.isPending,onClick:()=>k.mutate({profile:n,schema:i,database:x?h:"",create_missing:x&&u}),children:"Enable"})}),e.jsxs("p",{className:"text-[10.5px] text-ink-dim",children:["Or run ",e.jsx("code",{className:"font-mono",children:"/history-store enable"})," in the CLI for the full guided wizard (creates DB roles, validates connectivity, etc.)."]})]}),t.data.enabled&&t.data.outbox_pending>0&&e.jsxs("div",{className:"rounded-md border border-warning/40 bg-warning-soft px-3 py-2 text-xs text-warning",children:[e.jsxs("span",{className:"font-medium",children:[t.data.outbox_pending," dual-writes queued for retry."]})," ","Run"," ",e.jsx("code",{className:"font-mono",children:"/history-store flush-pending"})," ","to drain the outbox."]})]}):null})]})}function Ct(){const s=C({queryKey:["admin-me"],queryFn:()=>y("/api/admin/me"),staleTime:12e4,retry:!1,meta:{silentError:!0}});return{role:s.data?.role??"viewer",username:s.data?.username??"",hostname:s.data?.hostname??"",isLoading:s.isLoading}}function De(s){if(!s)return"—";try{return new Date(s).toLocaleString(void 0,{dateStyle:"short",timeStyle:"short"})}catch{return s}}function wt(){const s=R(),r=fe(),t=C({queryKey:["admin-me"],queryFn:()=>y("/api/admin/me"),staleTime:6e4}),l=C({queryKey:["admin-members"],queryFn:()=>y("/api/admin/members"),refetchInterval:6e4}),n=t.data?.role==="admin",o=l.data?.members.filter(a=>a.role==="admin"&&!a.revoked_at).length??0,i=w({mutationFn:a=>y("/api/admin/promote",{method:"POST",body:JSON.stringify({username:a})}),onSuccess:(a,m)=>{s.invalidateQueries({queryKey:["admin-members"]}),r.push({title:`${m} promoted to admin`,tone:"success"})},onError:a=>{r.push({title:"Promote failed",description:a.message,tone:"error"})}}),d=w({mutationFn:a=>y("/api/admin/demote",{method:"POST",body:JSON.stringify({username:a})}),onSuccess:(a,m)=>{s.invalidateQueries({queryKey:["admin-members"]}),r.push({title:`${m} demoted to viewer`,tone:"success"})},onError:a=>{r.push({title:"Demote failed",description:a.message,tone:"error"})}}),h=w({mutationFn:a=>y("/api/admin/revoke",{method:"POST",body:JSON.stringify({username:a})}),onSuccess:(a,m)=>{s.invalidateQueries({queryKey:["admin-members"]}),r.push({title:`${m} revoked`,tone:"success"})},onError:a=>{r.push({title:"Revoke failed",description:a.message,tone:"error"})}}),b=w({mutationFn:a=>y("/api/admin/unrevoke",{method:"POST",body:JSON.stringify({username:a})}),onSuccess:(a,m)=>{s.invalidateQueries({queryKey:["admin-members"]}),r.push({title:`${m} reinstated`,tone:"success"})},onError:a=>{r.push({title:"Unrevoke failed",description:a.message,tone:"error"})}});if(l.isLoading)return e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((a,m)=>e.jsx(le,{className:"h-12 w-full"},m))});if(l.isError)return e.jsx(M,{title:"Could not load members",description:l.error.message});const u=l.data?.members??[];return u.length===0?e.jsx(M,{title:"No members yet",description:"Members appear here once they connect to the shared workspace."}):e.jsxs("div",{className:"overflow-hidden rounded-lg border border-border",children:[e.jsxs("table",{className:"hidden w-full text-sm sm:table",children:[e.jsx("thead",{className:"border-b border-border bg-surface-subtle/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left font-medium text-ink-dim",children:"User"}),e.jsx("th",{className:"px-4 py-2 text-left font-medium text-ink-dim",children:"Role"}),e.jsx("th",{className:"hidden px-4 py-2 text-left font-medium text-ink-dim md:table-cell",children:"First seen"}),e.jsx("th",{className:"hidden px-4 py-2 text-left font-medium text-ink-dim lg:table-cell",children:"Last seen"}),e.jsx("th",{className:"hidden px-4 py-2 text-left font-medium text-ink-dim lg:table-cell",children:"Version"}),n&&e.jsx("th",{className:"px-4 py-2 text-right font-medium text-ink-dim",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-border",children:u.map(a=>{const m=a.username===t.data?.username&&a.hostname===t.data?.hostname,c=a.role==="admin"&&o<=1,x=!!a.revoked_at;return e.jsxs("tr",{className:V("transition-colors hover:bg-surface-subtle/40",x&&"opacity-50"),children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-ink",children:[a.username,m&&e.jsx("span",{className:"ml-1.5 rounded bg-accent-soft px-1.5 py-px text-[10px] font-medium text-accent-ink",children:"you"})]}),e.jsxs("span",{className:"font-mono text-xs text-ink-dim",children:["@",a.hostname]})]}),x&&e.jsx("span",{className:"text-xs text-critical",children:"Revoked"})]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(K,{tone:a.role==="admin"?"info":x?"warning":"neutral",children:x?"revoked":a.role})}),e.jsx("td",{className:"hidden px-4 py-3 text-xs text-ink-dim md:table-cell",children:De(a.first_seen_at)}),e.jsx("td",{className:"hidden px-4 py-3 text-xs text-ink-dim lg:table-cell",children:De(a.last_seen_at)}),e.jsx("td",{className:"hidden px-4 py-3 font-mono text-xs text-ink-dim lg:table-cell",children:a.client_version||"—"}),n&&e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[!x&&a.role!=="admin"&&e.jsx(re,{content:"Promote to admin",children:e.jsx("button",{type:"button",disabled:i.isPending,onClick:()=>i.mutate(a.username),"aria-label":`Promote ${a.username} to admin`,className:"rounded p-1.5 text-ink-dim hover:bg-surface-subtle hover:text-ink",children:e.jsx(We,{size:14})})}),!x&&a.role==="admin"&&e.jsx(re,{content:c?"Cannot demote the only admin":"Demote to viewer",children:e.jsx("span",{children:e.jsx("button",{type:"button",disabled:c||d.isPending,onClick:()=>d.mutate(a.username),"aria-label":`Demote ${a.username} to viewer`,className:V("rounded p-1.5 text-ink-dim",c?"cursor-not-allowed opacity-40":"hover:bg-surface-subtle hover:text-ink"),children:e.jsx(pt,{size:14})})})}),!x&&e.jsx(re,{content:"Revoke access",children:e.jsx("button",{type:"button",disabled:h.isPending,onClick:()=>h.mutate(a.username),"aria-label":`Revoke ${a.username}`,className:"rounded p-1.5 text-ink-dim hover:bg-surface-subtle hover:text-critical",children:e.jsx(gt,{size:14})})}),x&&e.jsx(re,{content:"Reinstate",children:e.jsx("button",{type:"button",disabled:b.isPending,onClick:()=>b.mutate(a.username),"aria-label":`Reinstate ${a.username}`,className:"rounded p-1.5 text-ink-dim hover:bg-surface-subtle hover:text-ink",children:e.jsx(ft,{size:14})})})]})})]},a.id)})})]}),e.jsx("ul",{className:"divide-y divide-border sm:hidden",children:u.map(a=>{const m=a.username===t.data?.username&&a.hostname===t.data?.hostname,c=!!a.revoked_at;return e.jsx("li",{className:V("flex items-center justify-between gap-3 px-4 py-3",c&&"opacity-50"),children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"font-medium text-ink",children:[a.username,m&&e.jsx("span",{className:"ml-1 rounded bg-accent-soft px-1 py-px text-[10px] text-accent-ink",children:"you"})]}),e.jsx(K,{tone:a.role==="admin"?"info":c?"warning":"neutral",children:c?"revoked":a.role})]}),e.jsxs("div",{className:"mt-0.5 truncate font-mono text-xs text-ink-dim",children:["@",a.hostname]})]})},a.id)})})]})}function Fe(s){if(!s)return"—";try{const r=new Date(s);return isNaN(r.getTime())?s:r.toLocaleString(void 0,{dateStyle:"short",timeStyle:"short"})}catch{return s}}function _t(){const s=C({queryKey:["admin-sessions"],queryFn:()=>y("/api/admin/sessions?limit=100"),refetchInterval:3e4,retry:!1});if(s.isLoading)return e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((t,l)=>e.jsx(le,{className:"h-10 w-full"},l))});if(s.isError)return e.jsx(M,{title:"Could not load session events",description:s.error.message});const r=s.data?.events??[];return r.length===0?e.jsx(M,{title:"No session events yet",description:"Connection events appear here as team members connect to the shared workspace."}):e.jsxs("div",{className:"overflow-hidden rounded-lg border border-border",children:[e.jsxs("table",{className:"hidden w-full text-sm sm:table",children:[e.jsx("thead",{className:"border-b border-border bg-surface-subtle/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left font-medium text-ink-dim",children:"User"}),e.jsx("th",{className:"px-4 py-2 text-left font-medium text-ink-dim",children:"Event"}),e.jsx("th",{className:"hidden px-4 py-2 text-left font-medium text-ink-dim md:table-cell",children:"Profiles"}),e.jsx("th",{className:"px-4 py-2 text-left font-medium text-ink-dim",children:"When"})]})}),e.jsx("tbody",{className:"divide-y divide-border",children:r.map(t=>e.jsxs("tr",{className:"transition-colors hover:bg-surface-subtle/40",children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("span",{className:"font-medium text-ink",children:t.username}),e.jsxs("span",{className:"ml-1 font-mono text-xs text-ink-dim",children:["@",t.hostname]})]}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx(K,{tone:t.event_kind==="connect"||t.event_kind==="first_seen"?"positive":"neutral",children:t.event_kind}),t.client_version&&e.jsxs("span",{className:"ml-2 font-mono text-xs text-ink-dim",children:["v",t.client_version]})]}),e.jsx("td",{className:"hidden px-4 py-3 md:table-cell",children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[(t.db_profiles_seen??[]).map(l=>e.jsx("span",{className:"rounded bg-surface-subtle px-1.5 py-px font-mono text-[11px] text-ink-muted",children:l},l)),!t.db_profiles_seen?.length&&e.jsx("span",{className:"text-xs text-ink-dim",children:"—"})]})}),e.jsx("td",{className:"px-4 py-3 text-xs text-ink-dim",children:Fe(t.event_at)})]},t.id))})]}),e.jsx("ul",{className:"divide-y divide-border sm:hidden",children:r.map(t=>e.jsxs("li",{className:"px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium text-ink",children:t.username}),e.jsx(K,{tone:t.event_kind==="connect"||t.event_kind==="first_seen"?"positive":"neutral",children:t.event_kind})]}),e.jsxs("div",{className:"mt-0.5 font-mono text-xs text-ink-dim",children:["@",t.hostname," · ",Fe(t.event_at)]})]},t.id))})]})}function Te(s){try{return new Date(s).toLocaleString(void 0,{dateStyle:"short",timeStyle:"short"})}catch{return s}}function qe(s){return s.startsWith("promote")?"info":s.startsWith("demote")||s.startsWith("revoke")||s.startsWith("forced_overwrite")?"warning":"neutral"}function Pt(){const[s,r]=p.useState(""),[t,l]=p.useState(""),n=C({queryKey:["admin-audit",s,t],queryFn:()=>{const i=new URLSearchParams({limit:"200"});return s.trim()&&i.set("actor",s.trim()),t.trim()&&i.set("action",t.trim()),y(`/api/admin/audit?${i.toString()}`)},retry:!1}),o=n.data?.events??[];return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs("label",{className:"flex flex-col text-sm",children:[e.jsx("span",{className:"mb-1 text-xs text-ink-muted",children:"Actor"}),e.jsx("input",{value:s,onChange:i=>r(i.target.value),placeholder:"username…",className:"rounded border border-border bg-surface px-2 py-1 text-sm sm:w-44"})]}),e.jsxs("label",{className:"flex flex-col text-sm",children:[e.jsx("span",{className:"mb-1 text-xs text-ink-muted",children:"Action"}),e.jsx("input",{value:t,onChange:i=>l(i.target.value),placeholder:"e.g. promote",className:"rounded border border-border bg-surface px-2 py-1 text-sm sm:w-44"})]}),(s||t)&&e.jsx("div",{className:"flex items-end",children:e.jsx("button",{type:"button",onClick:()=>{r(""),l("")},className:"rounded border border-border px-2 py-1 text-sm hover:bg-surface-subtle",children:"Clear"})})]}),n.isLoading?e.jsx("div",{className:"space-y-2",children:[...Array(4)].map((i,d)=>e.jsx(le,{className:"h-10 w-full"},d))}):n.isError?e.jsx(M,{title:"Could not load audit log",description:n.error.message}):o.length===0?e.jsx(M,{title:"No audit events",description:s||t?"No events match the current filters.":"Admin actions (promote, demote, revoke, forced overwrites) appear here."}):e.jsxs("div",{className:"overflow-hidden rounded-lg border border-border",children:[e.jsxs("table",{className:"hidden w-full text-sm sm:table",children:[e.jsx("thead",{className:"border-b border-border bg-surface-subtle/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left font-medium text-ink-dim",children:"Actor"}),e.jsx("th",{className:"px-4 py-2 text-left font-medium text-ink-dim",children:"Action"}),e.jsx("th",{className:"hidden px-4 py-2 text-left font-medium text-ink-dim md:table-cell",children:"Target"}),e.jsx("th",{className:"px-4 py-2 text-left font-medium text-ink-dim",children:"When"})]})}),e.jsx("tbody",{className:"divide-y divide-border",children:o.map(i=>e.jsxs("tr",{className:"transition-colors hover:bg-surface-subtle/40",children:[e.jsx("td",{className:"px-4 py-3 font-medium text-ink",children:i.actor_username||"system"}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(K,{tone:qe(i.action),children:i.action})}),e.jsx("td",{className:"hidden px-4 py-3 font-mono text-xs text-ink-dim md:table-cell",children:i.target_resource||"—"}),e.jsx("td",{className:"px-4 py-3 text-xs text-ink-dim",children:Te(i.occurred_at)})]},i.id))})]}),e.jsx("ul",{className:"divide-y divide-border sm:hidden",children:o.map(i=>e.jsxs("li",{className:"px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium text-ink",children:i.actor_username||"system"}),e.jsx(K,{tone:qe(i.action),children:i.action})]}),e.jsx("div",{className:"mt-0.5 text-xs text-ink-dim",children:Te(i.occurred_at)})]},i.id))})]})]})}function Lt({scope:s,state:r}){const t=r==="done"?"positive":r==="running"?"info":"neutral";return e.jsxs("tr",{className:"border-b border-border last:border-0",children:[e.jsx("td",{className:"py-2 pr-4 font-mono text-xs text-ink-dim",children:s}),e.jsx("td",{className:"py-2",children:e.jsx(K,{tone:t,children:r})})]})}function $t(){const s=C({queryKey:["history-status"],queryFn:()=>y("/api/history/status"),staleTime:3e4});if(s.isLoading)return e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,n)=>e.jsx(le,{className:"h-10 w-full"},n))});if(s.isError)return e.jsx(M,{title:"Could not load workspace settings",description:s.error.message});const r=s.data,t=Object.entries(r?.backfill??{});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-lg border border-border bg-surface-subtle/40 p-5",children:[e.jsx("h3",{className:"mb-4 text-sm font-semibold text-ink",children:"Team workspace configuration"}),e.jsxs("dl",{className:"grid grid-cols-1 gap-y-3 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs font-medium text-ink-dim",children:"Status"}),e.jsx("dd",{className:"mt-0.5",children:e.jsx(K,{tone:r?.enabled?"positive":"neutral",children:r?.enabled?"enabled":"disabled"})})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs font-medium text-ink-dim",children:"Shared profile"}),e.jsx("dd",{className:"mt-0.5 font-mono text-ink",children:r?.shared_profile||e.jsx("span",{className:"text-ink-dim",children:"not configured"})})]})]})]}),t.length>0&&e.jsxs("div",{className:"rounded-lg border border-border bg-surface-subtle/40 p-5",children:[e.jsx("h3",{className:"mb-4 text-sm font-semibold text-ink",children:"Migration / backfill state"}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("th",{className:"pb-2 pr-4 text-left text-xs font-medium text-ink-dim",children:"Scope"}),e.jsx("th",{className:"pb-2 text-left text-xs font-medium text-ink-dim",children:"State"})]})}),e.jsx("tbody",{children:t.map(([l,n])=>e.jsx(Lt,{scope:l,state:n},l))})]})]}),t.length===0&&e.jsx("p",{className:"text-sm text-ink-dim",children:"No migration state recorded. Backfill runs automatically when the shared workspace is first enabled."})]})}const Dt=[{id:"members",label:"Members"},{id:"activity",label:"Activity"},{id:"audit",label:"Audit log"},{id:"settings",label:"Settings"}],Ft=["members","activity","audit","settings"];function Tt(s){return s!==null&&Ft.includes(s)}function qt(){const s=R(),r=fe(),{role:t,username:l,hostname:n}=Ct(),o=C({queryKey:["admin-members"],queryFn:()=>y("/api/admin/members"),staleTime:6e4}),i=(o.data?.members??[]).filter(u=>u.role==="admin"&&!u.revoked_at),d=t==="admin",h=!o.isLoading&&i.length===0,b=w({mutationFn:()=>y("/api/admin/claim",{method:"POST"}),onSuccess:()=>{s.invalidateQueries({queryKey:["admin-me"]}),s.invalidateQueries({queryKey:["admin-members"]}),r.push({title:"You are now the workspace admin",tone:"success"})},onError:u=>{r.push({title:"Claim failed",description:u.message,tone:"error"})}});return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-surface-subtle/40 px-4 py-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[d?e.jsx(We,{size:18,className:"text-accent"}):e.jsx(ot,{size:18,className:"text-ink-muted"}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium text-ink",children:[l,e.jsxs("span",{className:"ml-1.5 font-mono text-xs text-ink-dim",children:["@",n]})]}),e.jsxs("div",{className:"text-xs text-ink-muted",children:["Your role:"," ",e.jsx(K,{tone:d?"info":"neutral",children:t})]})]})]}),!d&&h&&e.jsxs("button",{type:"button",disabled:b.isPending,onClick:()=>b.mutate(),className:"inline-flex items-center gap-1.5 rounded-md border border-accent bg-accent-soft px-3 py-1.5 text-xs font-medium text-accent-ink hover:bg-accent hover:text-white disabled:opacity-50",children:[e.jsx(mt,{size:13}),b.isPending?"Claiming…":"Claim admin role"]}),!d&&i.length>0&&e.jsxs("div",{className:"text-xs text-ink-muted",children:["To request admin access, contact:"," ",e.jsx("span",{className:"font-mono text-ink",children:i.map(u=>u.username).join(", ")})]})]})}function Et(){const[s,r]=Re(),t=s.get("inner"),l=Tt(t)?t:"members";function n(o){r(i=>{const d=new URLSearchParams(i);return d.set("inner",o),d},{replace:!0})}return e.jsxs("div",{className:"space-y-6",children:[e.jsx(St,{}),e.jsx(qt,{}),e.jsxs(ze,{value:l,onValueChange:o=>n(o),children:[e.jsx(Be,{className:"flex-wrap gap-1 sm:flex-nowrap overflow-x-auto",children:Dt.map(o=>e.jsx(Oe,{value:o.id,children:o.label},o.id))}),e.jsx(B,{value:"members",children:e.jsx(wt,{})}),e.jsx(B,{value:"activity",children:e.jsx(_t,{})}),e.jsx(B,{value:"audit",children:e.jsx(Pt,{})}),e.jsx(B,{value:"settings",children:e.jsx($t,{})})]})]})}const At=[{id:"db",label:"Database",icon:Ie},{id:"llm",label:"LLM",icon:Ue},{id:"docs",label:"Docs",icon:be},{id:"code",label:"Code",icon:ge},{id:"embeddings",label:"Embeddings",icon:nt},{id:"team",label:"Team workspace",icon:Je}],Rt=["db","llm","docs","code","embeddings","team"];function Kt(s){return s!==null&&Rt.includes(s)}function ks(){const[s,r]=Re(),t=s.get("tab"),l=Kt(t)?t:"db",n=o=>{r(i=>{const d=new URLSearchParams(i);return d.set("tab",o),d},{replace:!0})};return e.jsxs(e.Fragment,{children:[e.jsx(et,{title:"Settings",breadcrumbs:[{label:"Settings"}]}),e.jsxs(ze,{value:l,onValueChange:o=>n(o),children:[e.jsx(Be,{children:At.map(o=>e.jsx(Oe,{value:o.id,icon:e.jsx(o.icon,{size:13}),children:o.label},o.id))}),e.jsx(B,{value:"db",children:e.jsx(Mt,{})}),e.jsx(B,{value:"llm",children:e.jsx(Ut,{})}),e.jsx(B,{value:"docs",children:e.jsx(Vt,{})}),e.jsx(B,{value:"code",children:e.jsx(ss,{})}),e.jsx(B,{value:"embeddings",children:e.jsx(kt,{})}),e.jsx(B,{value:"team",children:e.jsx(Et,{})})]})]})}function Mt(){const s=R(),[r,t]=p.useState(null),[l,n]=p.useState(null),[o,i]=p.useState({}),d=C({queryKey:["profiles","db"],queryFn:()=>y("/api/profiles/db"),retry:!1,meta:{silentError:!0}}),h=w({mutationFn:u=>y(`/api/profiles/db/${encodeURIComponent(u)}`,{method:"DELETE"}),onSuccess:()=>Ve(s)}),b=w({mutationFn:async u=>{const a=await y(`/api/profiles/db/${encodeURIComponent(u)}/test`,{method:"POST"});return{name:u,...a}},onSuccess:u=>i(a=>({...a,[u.name]:{ok:u.ok,message:u.message}}))});return e.jsxs(e.Fragment,{children:[e.jsxs(O,{children:[e.jsx(I,{title:`${d.data?.count??0} DB profile${d.data?.count===1?"":"s"}`,description:"Every defined profile is selectable from Run, Ask, and Browse. There's no separate Activate step.",actions:e.jsxs("button",{type:"button",onClick:()=>t({name:null}),className:"inline-flex items-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90",children:[e.jsx(de,{size:14}),"Add"]})}),e.jsx(U,{className:"p-0",children:d.isLoading?e.jsx("div",{className:"px-5 py-6",children:e.jsx(Q,{status:"loading",hideLoadingTitle:!0,loadingBlocks:3})}):d.isError?e.jsx("div",{className:"px-5 py-6",children:e.jsx(Q,{status:"error",error:d.error,onRetry:()=>d.refetch()})}):d.data?.profiles.length?e.jsx("ul",{className:"divide-y divide-surface-border",children:d.data.profiles.map(u=>{const a=o[u.name];return e.jsx("li",{className:"px-5 py-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:u.name}),e.jsxs("div",{className:"text-xs text-ink-dim",children:[e.jsx("span",{className:"font-mono",children:u.backend}),u.host&&e.jsxs(e.Fragment,{children:[" · ",u.host]}),u.database&&e.jsxs(e.Fragment,{children:[" · ",u.database]}),u.catalog&&e.jsxs(e.Fragment,{children:[" · ",u.catalog]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[a&&e.jsxs("div",{title:a.message,className:V("inline-flex max-w-[260px] items-center gap-1.5 rounded-md px-2 py-1 text-[11px]",a.ok?"bg-positive/10 text-positive":"bg-critical/10 text-critical"),children:[a.ok?e.jsx(at,{size:12,className:"shrink-0"}):e.jsx(rt,{size:12,className:"shrink-0"}),e.jsx("span",{className:"truncate",children:a.message||(a.ok?"OK":"Failed")})]}),e.jsx("button",{type:"button",onClick:()=>b.mutate(u.name),disabled:b.isPending&&b.variables===u.name,className:"inline-flex items-center gap-1.5 rounded-md bg-surface-subtle px-2 py-1 text-xs text-ink-muted hover:bg-surface-border disabled:opacity-60",children:b.isPending&&b.variables===u.name?e.jsxs(e.Fragment,{children:[e.jsx(ee,{size:12,className:"animate-spin"}),"Testing…"]}):"Connection test"}),e.jsx("button",{type:"button",onClick:()=>t({name:u.name}),className:"rounded-md p-1 text-ink-dim hover:bg-surface-subtle hover:text-ink",title:"Edit",children:e.jsx(ce,{size:14})}),e.jsx("button",{type:"button",onClick:()=>{n(u.name)},className:"rounded-md p-1 text-ink-dim hover:bg-critical/10 hover:text-critical",title:"Delete",children:e.jsx(Y,{size:14})})]})]})},u.name)})}):e.jsx(M,{icon:Ie,title:"No DB profiles yet",description:"Click Add to create your first one. The same wizard the CLI's /add-db-profile uses."})})]}),r&&e.jsx(Ot,{open:!0,editingName:r.name,onClose:()=>t(null)}),e.jsx(J,{open:l!==null,onClose:()=>{h.isPending||n(null)},onConfirm:()=>{if(l){const u=l;h.mutate(u,{onSettled:()=>n(a=>a===u?null:a)})}},title:`Delete DB profile '${l??""}'?`,description:"This removes the connection and unbinds it from any linked doc or code profiles. The action cannot be undone.",confirmLabel:"Delete",loading:h.isPending})]})}const zt={host:"Host",port:"Port",user:"User",password:"Password",database:"Database"},Ee=new Set(["password","access_token"]);function Bt(s){return{name:s,kind:Ee.has(s)?"password":"text",label:zt[s]??s,help:"",secret:Ee.has(s),required:!1,group:"basic",options:[]}}function Ot({open:s,onClose:r,editingName:t}){const l=R(),n=t!=null,o=C({queryKey:["profiles","db-backends"],queryFn:()=>y("/api/profiles/db/backends")}),i=C({queryKey:["profiles","db",t],queryFn:()=>y(`/api/profiles/db/${encodeURIComponent(t)}`),enabled:n}),[d,h]=p.useState(t??""),[b,u]=p.useState("postgresql"),[a,m]=p.useState({}),[c,x]=p.useState(null);p.useEffect(()=>{if(!n||!i.data)return;const j=i.data;if((typeof j.name=="string"?j.name:null)!==t||c===t)return;u(String(j.backend||"postgresql"));const $={};for(const[v,F]of Object.entries(j))(typeof F=="string"||typeof F=="number"||typeof F=="boolean")&&($[v]=String(F));m($),x(t)},[n,i.data,t,c]);const N=o.data?.backends.find(j=>j.id===b),k=N?.field_specs??(N?.fields??["host","port","user","password","database"]).map(Bt),_=k.filter(j=>j.group!=="advanced"),g=k.filter(j=>j.group==="advanced"),T=w({mutationFn:()=>{const j={backend:b};for(const D of k){const $=a[D.name];$!==void 0&&(D.secret&&$==="********"||(j[D.name]=It(D,$)))}return y(`/api/profiles/db/${encodeURIComponent(d)}`,{method:"PUT",body:JSON.stringify(j)})},onSuccess:()=>{Ve(l),l.invalidateQueries({queryKey:["profiles","db",d]}),r()}});return e.jsx(se,{open:s,onClose:r,size:"lg",title:n?`Edit ${t}`:"Add DB profile",description:n?"Tweak fields and save. Secrets stay unchanged unless you replace the masked placeholder.":"Pick a backend and fill the connection details. Same fields the CLI's /add-db-profile asks for.",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:r,className:"rounded-md bg-surface-subtle px-3 py-1.5 text-sm text-ink-muted hover:bg-surface-border",children:"Cancel"}),e.jsx("button",{type:"button",onClick:()=>T.mutate(),disabled:!d.trim()||T.isPending,className:"rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90 disabled:opacity-40",children:T.isPending?"Saving…":"Save"})]}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(L,{label:"Profile name",children:e.jsx("input",{type:"text",value:d,onChange:j=>h(j.target.value),disabled:n,placeholder:"e.g. local-postgre",className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/20 disabled:opacity-60"})}),e.jsx(L,{label:"Backend",hint:"Which database engine you're connecting to (Postgres, Snowflake, Databricks…).",children:e.jsx("select",{value:b,onChange:j=>u(j.target.value),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 text-sm focus:border-accent focus:outline-none",children:(o.data?.backends??[]).map(j=>e.jsx("option",{value:j.id,children:j.label},j.id))})}),N&&N.supports_shared_history===!1&&e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-700 dark:text-amber-300",children:["Shared history is unavailable on this backend. AMX run history stays on this machine only — ",e.jsx("code",{children:"/history-store enable"})," will refuse to bootstrap on ",N.label,". Use it as a sandbox / personal connection, not as the team's workspace."]}),N&&N.supports_shared_history!==!1&&e.jsxs("div",{className:"rounded-md border border-surface-border bg-surface-subtle/40 px-3 py-2 text-xs text-ink-muted",children:[e.jsx("span",{className:"font-semibold text-ink",children:"Team workspace location."})," ","Choose one database profile to host the shared team workspace. This single backend stores history runs, lineage diagrams, and documentation pages for ",e.jsx("strong",{children:"all"})," your database profiles — the team manages everything from one place. You do not need to configure this per profile. Run"," ",e.jsx("code",{className:"rounded bg-surface px-1 py-px font-mono text-[11px]",children:"/history-store enable"})," ","from the AMX CLI to activate."]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:_.map(j=>e.jsx(Ae,{spec:j,value:a[j.name],defaultPort:N?.default_port,onChange:D=>m({...a,[j.name]:D})},j.name))}),g.length>0&&e.jsxs("details",{className:"rounded-md border border-surface-border bg-surface-subtle px-3 py-2 text-sm",children:[e.jsx("summary",{className:"cursor-pointer font-medium text-ink-muted",children:"Advanced (TLS / SSL / driver options)"}),e.jsx("div",{className:"mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3",children:g.map(j=>e.jsx(Ae,{spec:j,value:a[j.name],defaultPort:N?.default_port,onChange:D=>m({...a,[j.name]:D})},j.name))})]}),T.isError&&e.jsx("div",{className:"rounded-md border border-critical/40 bg-critical/5 px-3 py-2 text-xs text-critical",children:T.error instanceof Error?T.error.message:"Save failed."})]})})}function It(s,r){if(s.kind==="int"){const t=Number(r);return Number.isFinite(t)?t:r}return s.kind==="bool"?r==="true":r}function Ae({spec:s,value:r,defaultPort:t,onChange:l}){return e.jsx(L,{label:s.label,hint:s.help||void 0,narrow:s.kind==="int",children:s.kind==="bool"?e.jsx("input",{type:"checkbox",checked:r==="true",onChange:n=>l(n.target.checked?"true":"false"),className:"h-4 w-4 cursor-pointer accent-current"}):s.kind==="select"?e.jsx("select",{value:r??"",onChange:n=>l(n.target.value),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/20",children:s.options.map(n=>e.jsx("option",{value:n,children:n||"(default)"},n))}):e.jsx("input",{type:s.kind==="password"?"password":"text",value:r??"",onChange:n=>l(n.target.value),placeholder:s.name==="port"&&t?String(t):"",className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/20"})})}function Ut(){const s=R(),[r,t]=p.useState(null),[l,n]=p.useState(null),o=C({queryKey:["profiles","llm"],queryFn:()=>y("/api/profiles/llm"),retry:!1,meta:{silentError:!0}}),i=w({mutationFn:h=>y(`/api/profiles/llm/${encodeURIComponent(h)}/activate`,{method:"POST"}),onSuccess:()=>s.invalidateQueries({queryKey:["profiles","llm"]})}),d=w({mutationFn:h=>y(`/api/profiles/llm/${encodeURIComponent(h)}`,{method:"DELETE"}),onSuccess:()=>s.invalidateQueries({queryKey:["profiles","llm"]})});return e.jsxs(e.Fragment,{children:[e.jsxs(O,{children:[e.jsx(I,{title:`${o.data?.count??0} LLM profile${o.data?.count===1?"":"s"}`,description:`Active: ${o.data?.active??"—"}`,actions:e.jsxs("button",{type:"button",onClick:()=>t({name:null}),className:"inline-flex items-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90",children:[e.jsx(de,{size:14}),"Add"]})}),e.jsx(U,{className:"p-0",children:o.isLoading?e.jsx("div",{className:"px-5 py-6",children:e.jsx(Q,{status:"loading",hideLoadingTitle:!0,loadingBlocks:3})}):o.isError?e.jsx("div",{className:"px-5 py-6",children:e.jsx(Q,{status:"error",error:o.error,onRetry:()=>o.refetch()})}):o.data?.profiles.length?e.jsx("ul",{className:"divide-y divide-surface-border",children:o.data.profiles.map(h=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-5 py-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:h.name}),e.jsxs("div",{className:"text-xs text-ink-dim",children:[e.jsx("span",{className:"font-mono",children:h.provider||"—"})," ·"," ",e.jsx("span",{className:"font-mono",children:h.model||"—"})]}),e.jsx(it,{provider:h.provider,model:h.model,isActive:h.is_active})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[h.is_active?e.jsx(G,{tone:"positive",children:"Active"}):e.jsx("button",{type:"button",onClick:()=>i.mutate(h.name),className:"rounded-md bg-surface-subtle px-2 py-1 text-xs text-ink-muted hover:bg-accent-soft hover:text-accent-ink",children:"Activate"}),e.jsx("button",{type:"button",onClick:()=>t({name:h.name}),className:"rounded-md p-1 text-ink-dim hover:bg-surface-subtle hover:text-ink",title:"Edit",children:e.jsx(ce,{size:14})}),!h.is_active&&e.jsx("button",{type:"button",onClick:()=>{n(h.name)},className:"rounded-md p-1 text-ink-dim hover:bg-critical/10 hover:text-critical",title:"Delete",children:e.jsx(Y,{size:14})})]})]},h.name))}):e.jsx(M,{icon:Ue,title:"No LLM profiles yet",description:"Click Add to wire up an OpenAI / Anthropic / Gemini / OpenRouter / local provider."})})]}),e.jsx(yt,{llmProfile:o.data?.active??null}),r&&e.jsx(Qt,{open:!0,editingName:r.name,onClose:()=>t(null)}),e.jsx(J,{open:l!==null,onClose:()=>{d.isPending||n(null)},onConfirm:()=>{if(l){const h=l;d.mutate(h,{onSettled:()=>n(b=>b===h?null:b)})}},title:`Delete LLM profile '${l??""}'?`,description:"This removes the provider credentials and any chat-style defaults bound to it. The action cannot be undone.",confirmLabel:"Delete",loading:d.isPending})]})}function Qt({open:s,onClose:r,editingName:t}){const l=R(),n=t!=null,o=C({queryKey:["profiles","llm-providers"],queryFn:()=>y("/api/profiles/llm/providers")}),i=C({queryKey:["profiles","llm",t],queryFn:()=>y(`/api/profiles/llm/${encodeURIComponent(t)}`),enabled:n}),[d,h]=p.useState(t??""),[b,u]=p.useState("openrouter"),[a,m]=p.useState(""),[c,x]=p.useState(""),[N,k]=p.useState(""),[_,g]=p.useState(.2),[T,j]=p.useState(16384),[D,$]=p.useState(""),[v,F]=p.useState(""),[E,P]=p.useState(3),[q,A]=p.useState(10),[S,z]=p.useState("standard"),[ne,ye]=p.useState("brief"),[je,ve]=p.useState("self_consistency"),[ke,Ne]=p.useState("semantic"),[me,Se]=p.useState(.85),[ue,Ce]=p.useState(.5),[we,Ze]=p.useState(null);p.useEffect(()=>{if(!n||!i.data)return;const f=i.data;if((typeof f.name=="string"?f.name:null)===t&&we!==t){u(String(f.provider||"openrouter")),m(String(f.model||"")),x(String(f.api_key||"")),k(String(f.api_base??"")||""),g(Number(f.temperature??.2)),j(Number(f.max_tokens??16384)),$(f.custom_input_cost_per_mtok!=null?String(f.custom_input_cost_per_mtok):""),F(f.custom_output_cost_per_mtok!=null?String(f.custom_output_cost_per_mtok):""),P(Number(f.n_alternatives??3)),A(Number(f.column_batch_size??10)),z(String(f.prompt_detail||"standard")),ye(String(f.description_verbosity||"brief")),ve(String(f.confidence_signal||"self_consistency"));{const ae=String(f.alternatives_mode||"semantic").toLowerCase();Ne(ae==="lexical"?"lexical":"semantic")}Se(Number(f.logprob_high??.85)),Ce(Number(f.logprob_medium??.5)),Ze(t)}},[n,i.data,t,we]);const _e=o.data?.providers.find(f=>f.id===b),Pe=!!_e?.needs_base,Le=!!_e?.needs_key,xe=C({queryKey:["pricing","model",b,a],queryFn:()=>H.lookupPrice(b,a),enabled:!!(b&&a.trim().length>0),retry:!1,staleTime:6e4}),W=w({mutationFn:()=>{const f={provider:b,model:a,temperature:_,max_tokens:T,custom_input_cost_per_mtok:D.trim()===""?null:Number(D),custom_output_cost_per_mtok:v.trim()===""?null:Number(v),n_alternatives:E,column_batch_size:q,prompt_detail:S,description_verbosity:ne,confidence_signal:je,alternatives_mode:ke,logprob_high:me,logprob_medium:ue};return Le&&c!=="********"&&(f.api_key=c),Pe&&(f.api_base=N),y(`/api/profiles/llm/${encodeURIComponent(d)}`,{method:"PUT",body:JSON.stringify(f)})},onSuccess:()=>{l.invalidateQueries({queryKey:["profiles","llm"]}),l.invalidateQueries({queryKey:["profiles","llm",d]}),r()}});return e.jsx(se,{open:s,onClose:r,size:"lg",title:n?`Edit ${t}`:"Add LLM profile",description:"Provider, model, and the run-time knobs that affect every /run + /ask.",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:r,className:"rounded-md bg-surface-subtle px-3 py-1.5 text-sm text-ink-muted hover:bg-surface-border",children:"Cancel"}),e.jsx("button",{type:"button",onClick:()=>W.mutate(),disabled:!d.trim()||!a.trim()||W.isPending,className:"rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90 disabled:opacity-40",children:W.isPending?"Saving…":"Save"})]}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(L,{label:"Profile name",children:e.jsx("input",{type:"text",value:d,onChange:f=>h(f.target.value),disabled:n,placeholder:"e.g. or-kimi",className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm disabled:opacity-60"})}),e.jsx(L,{label:"Provider",children:e.jsx("select",{value:b,onChange:f=>u(f.target.value),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 text-sm",children:(o.data?.providers??[]).map(f=>e.jsx("option",{value:f.id,children:f.label},f.id))})})]}),e.jsx(L,{label:"Model",children:e.jsx("input",{type:"text",value:a,onChange:f=>m(f.target.value),placeholder:"e.g. moonshotai/kimi-k2-instruct",className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm"})}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[Le&&e.jsx(L,{label:"API key",children:e.jsx("input",{type:"password",value:c,onChange:f=>x(f.target.value),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm"})}),Pe&&e.jsx(L,{label:"API base URL",children:e.jsx("input",{type:"text",value:N,onChange:f=>k(f.target.value),placeholder:"https://…/v1",className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm"})})]}),e.jsx("h3",{className:"border-t border-surface-border pt-4 text-[11px] font-semibold uppercase tracking-wider text-ink-dim",children:"Generation knobs"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(L,{label:`Temperature (${_.toFixed(2)})`,hint:"Creativity: low = consistent, high = varied (0.1–0.3 recommended).",children:e.jsx("input",{type:"range",min:0,max:2,step:.05,value:_,onChange:f=>g(Number(f.target.value)),className:"w-full"})}),e.jsx(L,{label:`Max output tokens (${T.toLocaleString()})`,hint:"Output budget per LLM call. Reasoning models (Kimi K2.x, Claude extended-thinking, GPT-5/o-series, deepseek-reasoner) automatically get a 32k floor on top — this value is the floor for non-reasoning models. Higher = bigger answers + higher cost.",children:e.jsx("input",{type:"number",min:256,max:262144,step:1024,value:T,onChange:f=>j(Math.max(256,Number(f.target.value)||0)),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm"})}),e.jsx("div",{className:"col-span-2",children:e.jsx(Ht,{loading:xe.isFetching,data:xe.data,error:xe.error,hasModel:!!a.trim()})}),e.jsx(L,{label:"Custom input cost (USD / 1M tokens)",hint:"Override the auto-detected price. Leave blank to use LiteLLM / OpenRouter / bundled prices. Both rates must be set together — a half-override is treated as no override.",children:e.jsx("input",{type:"number",min:0,step:.01,value:D,placeholder:"auto",onChange:f=>$(f.target.value),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm"})}),e.jsx(L,{label:"Custom output cost (USD / 1M tokens)",hint:"Same rules as the input rate — both must be set or both blank.",children:e.jsx("input",{type:"number",min:0,step:.01,value:v,placeholder:"auto",onChange:f=>F(f.target.value),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm"})}),e.jsx(L,{label:`Alternatives per column (${E})`,hint:"How many alternative description proposals to generate per column.",children:e.jsx("input",{type:"range",min:1,max:5,step:1,value:E,onChange:f=>P(Number(f.target.value)),className:"w-full"})}),e.jsx(L,{label:"Alternatives diversity mode",hint:E<=1?"Has no effect when alternatives per column is 1.":"Semantic = paraphrase the chosen description (same meaning, different wording). Lexical = share core vocabulary while letting the meaning shift through added nuances.",children:e.jsx("div",{role:"radiogroup","aria-label":"Alternatives diversity mode",className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:["semantic","lexical"].map(f=>{const pe=ke===f,ae=E<=1;return e.jsxs("button",{type:"button",role:"radio","aria-checked":pe,disabled:ae,onClick:()=>Ne(f),className:"rounded-md border px-3 py-2 text-left text-sm transition "+(pe?"border-accent bg-accent/10 text-accent":"border-surface-border bg-surface text-ink-base hover:border-accent/60")+(ae?" opacity-60 cursor-not-allowed":""),children:[e.jsx("div",{className:"font-medium capitalize",children:f}),e.jsx("div",{className:"text-[11px] text-ink-dim",children:f==="semantic"?"Same meaning, different wording (default)":"Shared vocabulary, meaning may shift"})]},f)})})}),e.jsx(L,{label:`Column batch size (${q})`,hint:"Columns processed per LLM call. Higher = cheaper; lower = more stable.",children:e.jsx("input",{type:"number",min:1,max:100,value:q,onChange:f=>A(Number(f.target.value)),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm"})}),e.jsx(L,{label:"Prompt detail",hint:"How much context the model receives. More = accurate; less = fast/cheap.",children:e.jsx("select",{value:S,onChange:f=>z(f.target.value),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 text-sm",children:["minimal","standard","detailed","full"].map(f=>e.jsx("option",{value:f,children:f},f))})}),e.jsx(L,{label:"Description verbosity",hint:"Output length: brief = one sentence, exhaustive = detailed.",children:e.jsx("select",{value:ne,onChange:f=>ye(f.target.value),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 text-sm",children:["brief","detailed","comprehensive","exhaustive"].map(f=>e.jsx("option",{value:f,children:f},f))})}),e.jsx(L,{label:"Confidence signal",hint:"Picks which scorer drives the HIGH / MED / LOW badge on each alternative. Only one runs per analysis. 'judge' issues a second LLM call (roughly doubles tokens); 'none' hides the badge.",children:e.jsx("select",{value:je,onChange:f=>ve(f.target.value),className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 text-sm",children:["self_consistency","logprob","self_decl","judge","none"].map(f=>e.jsx("option",{value:f,children:f},f))})})]}),e.jsx("h3",{className:"border-t border-surface-border pt-4 text-[11px] font-semibold uppercase tracking-wider text-ink-dim",children:"Confidence thresholds"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(L,{label:`High (≥ ${me.toFixed(2)})`,hint:"Predictions above this score are flagged 'high confidence'.",children:e.jsx("input",{type:"range",min:0,max:1,step:.05,value:me,onChange:f=>Se(Number(f.target.value)),className:"w-full"})}),e.jsx(L,{label:`Medium (≥ ${ue.toFixed(2)})`,hint:"Above this is 'medium confidence'; below counts as 'low'.",children:e.jsx("input",{type:"range",min:0,max:1,step:.05,value:ue,onChange:f=>Ce(Number(f.target.value)),className:"w-full"})})]}),W.isError&&e.jsx("div",{className:"rounded-md border border-critical/40 bg-critical/5 px-3 py-2 text-xs text-critical",children:W.error instanceof Error?W.error.message:"Save failed."})]})})}function Ht({loading:s,data:r,error:t,hasModel:l}){if(!l)return e.jsx("div",{className:"rounded-md border border-dashed border-surface-border px-3 py-2 text-[11px] text-ink-dim",children:"Fill the model field above to see the auto-detected price."});if(s)return e.jsx("div",{className:"rounded-md border border-surface-border bg-surface-subtle/40 px-3 py-2 text-[11px] text-ink-dim",children:"Looking up auto-detected price…"});if(t)return e.jsxs("div",{className:"rounded-md border border-critical/40 bg-critical-soft/40 px-3 py-2 text-[11px] text-critical",children:["Could not look up price: ",t.message]});if(!r)return null;if(r.source==="unknown")return e.jsxs("div",{className:"rounded-md border border-warning/40 bg-warning-soft/40 px-3 py-2 text-[11px] text-warning",children:["No price entry found for this model. Run ",e.jsx("code",{className:"font-mono",children:"/refresh-prices"})," ","from the CLI (or click ↻ in the TopBar pricing badge) to re-pull the LiteLLM / OpenRouter tables, or set both custom rates below to bill it explicitly."]});const n=r.source==="user_override"?"your override":r.source;return e.jsxs("div",{className:"rounded-md border border-info/40 bg-info-soft/40 px-3 py-2 text-[11px] text-info",children:["Auto-detected: ",e.jsxs("span",{className:"font-mono",children:["$",r.input_per_mtok.toFixed(4)]})," /"," ",e.jsxs("span",{className:"font-mono",children:["$",r.output_per_mtok.toFixed(4)]})," per 1M tokens (",e.jsx("span",{className:"font-medium",children:n}),"). Set both inputs below to override."]})}function Jt({profile:s,onJobStarted:r}){const t=R(),[l,n]=p.useState(!1),[o,i]=p.useState(null),[d,h]=p.useState(!1),b=async u=>{if(i(null),!s){i("Pick a doc profile first.");return}h(!0);try{const a=new FormData;a.append("profile",s),a.append("ingest","true");for(let k=0;k<u.length;k+=1)a.append("files",u[k]);const m=Qe(),c={};m&&(c.Authorization=`Bearer ${m}`);const x=await fetch("/api/docs/upload",{method:"POST",body:a,headers:c,credentials:"include"});if(!x.ok){const k=await x.text();throw new Error(k||`Upload failed: HTTP ${x.status}`)}const N=await x.json();if(t.invalidateQueries({queryKey:["profiles","docs"]}),N.job_id){const k=N.saved.filter(_=>!_.duplicate).length;r(N.job_id,`Ingesting ${k} new file${k===1?"":"s"} in ${s}`)}}catch(a){i(a instanceof Error?a.message:String(a))}finally{h(!1)}};return e.jsxs("div",{className:"px-5 pb-3",children:[e.jsx("div",{onDragOver:u=>{u.preventDefault(),n(!0)},onDragLeave:()=>n(!1),onDrop:u=>{u.preventDefault(),n(!1),u.dataTransfer.files?.length&&b(u.dataTransfer.files)},className:"rounded-md border border-dashed px-3 py-2 text-xs transition "+(l?"border-accent bg-accent-soft text-accent-ink":"border-surface-border text-ink-dim hover:border-accent/40"),children:e.jsxs("label",{className:"flex cursor-pointer items-center justify-between gap-2",children:[e.jsx("span",{children:d?"Uploading…":`Drag-drop files here to add to ${s||"(pick a profile)"} — or click to browse.`}),e.jsx("input",{type:"file",multiple:!0,disabled:d||!s,onChange:u=>{u.target.files?.length&&b(u.target.files),u.target.value=""},className:"hidden",accept:".md,.markdown,.txt,.pdf,.docx,.doc,.csv,.tsv,.html,.htm,.rst,.rtf,.json,.yaml,.yml"}),e.jsx("span",{className:"rounded bg-surface-subtle px-2 py-0.5 text-[10px]",children:"Browse"})]})}),o&&e.jsx("div",{className:"mt-1 text-[11px] text-critical",children:o})]})}function Wt(s){return s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:s<1024*1024*1024?`${(s/(1024*1024)).toFixed(1)} MB`:`${(s/(1024*1024*1024)).toFixed(2)} GB`}function Gt({name:s}){const[r,t]=p.useState(!1),[l,n]=p.useState(null),o=R(),i=C({queryKey:["profiles","docs",s,"health"],queryFn:()=>y(`/api/profiles/docs/${encodeURIComponent(s)}/health`),retry:!1,staleTime:1e4}),d=w({mutationFn:x=>y(`/api/profiles/docs/${encodeURIComponent(s)}/files?path=${encodeURIComponent(x.path)}`,{method:"DELETE"}),onSuccess:()=>{o.invalidateQueries({queryKey:["profiles","docs",s,"health"]})}});if(i.isLoading)return e.jsx("div",{className:"mt-2 pl-3 text-[10.5px] text-ink-dim",children:"Loading health…"});if(i.error||!i.data)return null;const h=i.data,b=h.chunk_count||0,u=h.last_ingested_at&&h.last_ingested_at>0?Ge(h.last_ingested_at):null,a=[];b>0?a.push(`📚 ${b.toLocaleString()} chunk${b===1?"":"s"}`):a.push("📚 not indexed yet"),u&&a.push(`indexed ${u}`),h.embedding_model&&a.push(`model ${h.embedding_model}`);const m=(h.local_files??[]).filter(x=>!("__truncated__"in x)),c=(h.local_files??[]).some(x=>"__truncated__"in x);return m.length>0&&a.push(`📄 ${m.length}${c?"+":""} file${m.length===1?"":"s"}`),e.jsxs("div",{className:"mt-2 pl-3 text-[10.5px]",children:[e.jsx("div",{className:"text-ink-dim",children:a.join(" · ")}),m.length>0&&e.jsxs("details",{className:"mt-1 text-ink-muted",children:[e.jsx("summary",{className:"cursor-pointer select-none text-[10.5px] text-ink-dim hover:text-ink",children:"Show / hide files"}),e.jsxs("ul",{className:"mt-1.5 max-h-64 space-y-0.5 overflow-y-auto pr-2",children:[m.map((x,N)=>{const k=x.display_name||x.name,_=x.display_name&&x.display_name!==x.name;return e.jsxs("li",{className:"flex items-center gap-2 text-[10.5px]",children:[e.jsx("span",{className:V("truncate text-ink",_?"":"font-mono"),title:_?`${x.name} → ${x.path}`:x.path,children:k}),e.jsx("span",{className:"ml-auto shrink-0 font-mono text-ink-dim",children:Wt(x.size_bytes)}),e.jsx("button",{type:"button",onClick:()=>n(x),disabled:d.isPending,className:"shrink-0 rounded-md p-1 text-ink-dim hover:bg-critical/10 hover:text-critical disabled:opacity-40",title:`Delete ${k}`,"aria-label":`Delete ${k}`,children:e.jsx(Y,{size:11})})]},`${x.path}-${N}`)}),c&&e.jsx("li",{className:"text-[10.5px] italic text-ink-dim",children:"… more files exist; run Scan to see the full inventory."})]})]}),h.last_error&&e.jsxs("button",{type:"button",onClick:()=>t(x=>!x),className:"mt-1 block w-full text-left text-critical/90 hover:text-critical",children:[e.jsx("span",{className:"mr-1",children:"⚠ Last ingest failed:"}),r?e.jsx("span",{className:"font-mono",children:h.last_error}):e.jsx("span",{className:"line-clamp-1 font-mono",children:h.last_error}),e.jsxs("span",{className:"ml-1 opacity-70",children:["(",r?"hide":"Inspect",")"]})]}),e.jsx(J,{open:l!==null,onClose:()=>{d.isPending||n(null)},onConfirm:()=>{l&&d.mutate(l,{onSettled:()=>n(null)})},title:l?`Delete '${l.display_name||l.name}'?`:"Delete file?",description:"Drops the file from disk and removes any chunks it produced from the search index. The other files in this profile stay intact.",confirmLabel:"Delete",loading:d.isPending})]})}function Vt(){const s=R(),[r,t]=p.useState(null),[l,n]=p.useState(null),[o,i]=p.useState(null),d=C({queryKey:["profiles","docs"],queryFn:()=>y("/api/profiles/docs"),retry:!1,meta:{silentError:!0}}),h=w({mutationFn:m=>y(`/api/profiles/docs/${encodeURIComponent(m)}/activate`,{method:"POST"}),onSuccess:()=>s.invalidateQueries({queryKey:["profiles","docs"]})}),b=w({mutationFn:m=>y(`/api/profiles/docs/${encodeURIComponent(m)}`,{method:"DELETE"}),onSuccess:()=>s.invalidateQueries({queryKey:["profiles","docs"]})}),u=w({mutationFn:m=>y("/api/docs/scan",{method:"POST",body:JSON.stringify({profile:m})}),onSuccess:(m,c)=>i({jobId:m.job_id,label:`Scanning ${c}`})}),a=w({mutationFn:m=>y("/api/docs/ingest",{method:"POST",body:JSON.stringify({profile:m.profile,refresh:m.refresh})}),onSuccess:(m,c)=>i({jobId:m.job_id,label:`Ingesting ${c.profile}${c.refresh?" (refresh)":""}`})});return e.jsxs(e.Fragment,{children:[e.jsx(Yt,{}),o&&e.jsxs("div",{className:"mb-4",children:[e.jsx(He,{jobId:o.jobId,kind:"docs/scan",onTerminal:()=>i(null)}),e.jsx("p",{className:"mt-1 text-xs text-ink-dim",children:o.label})]}),e.jsxs(O,{children:[e.jsx(I,{title:`${d.data?.profiles?.length??0} doc profile${d.data?.profiles?.length===1?"":"s"}`,description:`Active: ${d.data?.active??"—"} · Each profile groups one or more directories / URLs / S3 prefixes that AMX feeds to the doc RAG agent.`,actions:e.jsxs("button",{type:"button",onClick:()=>t({name:null}),className:"inline-flex items-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90",children:[e.jsx(de,{size:14}),"Add"]})}),e.jsx(U,{className:"p-0",children:d.isLoading?e.jsx("div",{className:"px-5 py-6",children:e.jsx(Q,{status:"loading",hideLoadingTitle:!0,loadingBlocks:3})}):d.isError?e.jsx("div",{className:"px-5 py-6",children:e.jsx(Q,{status:"error",error:d.error,onRetry:()=>d.refetch()})}):d.data?.profiles?.length?e.jsx("ul",{className:"divide-y divide-surface-border",children:d.data.profiles.map(m=>e.jsxs("li",{className:"px-5 py-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:m.name}),e.jsxs("div",{className:"text-xs text-ink-dim",children:[m.paths.length," path",m.paths.length===1?"":"s"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[m.is_active?e.jsx(G,{tone:"positive",children:"Active"}):e.jsx("button",{type:"button",onClick:()=>h.mutate(m.name),className:"rounded-md bg-surface-subtle px-2 py-1 text-xs text-ink-muted hover:bg-accent-soft hover:text-accent-ink",children:"Activate"}),e.jsx("button",{type:"button",onClick:()=>u.mutate(m.name),disabled:u.isPending||!!o,className:"rounded-md bg-surface-subtle px-2 py-1 text-xs text-ink-muted hover:bg-surface-border disabled:opacity-50",title:"Scan: list what would be ingested",children:"Scan"}),e.jsx("button",{type:"button",onClick:()=>a.mutate({profile:m.name,refresh:!1}),disabled:a.isPending||!!o,className:"rounded-md bg-accent-soft px-2 py-1 text-xs text-accent-ink hover:opacity-90 disabled:opacity-50",title:"Ingest into Chroma RAG store",children:"Ingest"}),e.jsx("button",{type:"button",onClick:()=>a.mutate({profile:m.name,refresh:!0}),disabled:a.isPending||!!o,className:"rounded-md bg-surface-subtle px-2 py-1 text-xs text-ink-muted hover:bg-surface-border disabled:opacity-50",title:"Refresh: drop existing chunks for these sources before re-ingesting",children:"Re-ingest"}),e.jsx("button",{type:"button",onClick:()=>t({name:m.name}),className:"rounded-md p-1 text-ink-dim hover:bg-surface-subtle hover:text-ink",title:"Edit",children:e.jsx(ce,{size:14})}),e.jsx("button",{type:"button",onClick:()=>{n(m.name)},className:"rounded-md p-1 text-ink-dim hover:bg-critical/10 hover:text-critical",title:"Delete",children:e.jsx(Y,{size:14})})]})]}),m.paths.length>0&&e.jsx("ul",{className:"mt-2 space-y-0.5 pl-3 text-[11px] text-ink-muted",children:m.paths.map((c,x)=>e.jsx("li",{className:"truncate font-mono",children:c},x))}),e.jsx(Gt,{name:m.name}),(m.linked_db_profiles?.length??0)>0&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1 pl-3 text-[10px] text-ink-dim",children:[e.jsx("span",{children:"Links:"}),m.linked_db_profiles.map(c=>e.jsx("span",{className:"rounded bg-surface-subtle px-1.5 py-0.5 font-mono text-accent-ink",children:c},c))]}),e.jsx("div",{className:"mt-2",children:e.jsx(Jt,{profile:m.name,onJobStarted:(c,x)=>i({jobId:c,label:x})})})]},m.name))}):e.jsx(M,{icon:be,title:"No doc profiles yet",description:"Bind a folder of design docs / data dictionaries so the RAG agent can ground its descriptions."})})]}),r&&e.jsx(Xt,{open:!0,editingName:r.name,existingPaths:r.name?d.data?.profiles?.find(m=>m.name===r.name)?.paths??[]:[],existingLinkedDbs:r.name?d.data?.profiles?.find(m=>m.name===r.name)?.linked_db_profiles??[]:[],onClose:()=>t(null)}),e.jsx(J,{open:l!==null,onClose:()=>{b.isPending||n(null)},onConfirm:()=>{if(l){const m=l;b.mutate(m,{onSettled:()=>n(c=>c===m?null:c)})}},title:`Delete doc profile '${l??""}'?`,description:"Drops the ingested document index and unbinds this profile from any linked DB connections. The action cannot be undone.",confirmLabel:"Delete",loading:b.isPending})]})}function Xt({open:s,onClose:r,editingName:t,existingPaths:l,existingLinkedDbs:n}){const o=R(),i=t!=null,[d,h]=p.useState(t??""),[b,u]=p.useState(l.join(`
`)),[a,m]=p.useState(n),[c,x]=p.useState([]),[N,k]=p.useState(null),[_,g]=p.useState(!1),[T,j]=p.useState(null),D=v=>{const F=[...c];for(let E=0;E<v.length;E+=1){const P=v[E]??v[E];P&&!F.some(q=>q.name===P.name&&q.size===P.size)&&F.push(P)}x(F)},$=w({mutationFn:async()=>{if(await y(`/api/profiles/docs/${encodeURIComponent(d)}`,{method:"PUT",body:JSON.stringify({paths:b.split(`
`).map(q=>q.trim()).filter(Boolean),linked_db_profiles:a})}),c.length===0)return;j(`Uploading ${c.length} file${c.length===1?"":"s"}…`);const v=new FormData;v.append("profile",d),v.append("ingest","true");for(const q of c)v.append("files",q);const F=Qe(),E={};F&&(E.Authorization=`Bearer ${F}`);const P=await fetch("/api/docs/upload",{method:"POST",body:v,headers:E,credentials:"include"});if(!P.ok){const q=await P.text();throw new Error(q||`Upload failed: HTTP ${P.status}`)}},onSuccess:()=>{o.invalidateQueries({queryKey:["profiles","docs"]}),j(null),r()},onError:v=>{k(v instanceof Error?v.message:String(v)),j(null)}});return e.jsx(se,{open:s,onClose:r,title:i?`Edit ${t}`:"Add doc profile",description:"One path per line. Local directories, file:// URIs, and remote URLs (https / s3 / gcs) all work.",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:r,className:"rounded-md bg-surface-subtle px-3 py-1.5 text-sm text-ink-muted hover:bg-surface-border",children:"Cancel"}),e.jsx("button",{type:"button",onClick:()=>$.mutate(),disabled:!d.trim()||$.isPending,className:"rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90 disabled:opacity-40",children:$.isPending?"Saving…":"Save"})]}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(L,{label:"Profile name",children:e.jsx("input",{type:"text",value:d,onChange:v=>h(v.target.value),disabled:i,placeholder:"e.g. design-docs",className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm disabled:opacity-60"})}),e.jsx(L,{label:"Paths (one per line)",children:e.jsx("textarea",{value:b,onChange:v=>u(v.target.value),rows:6,placeholder:`/abs/path/to/docs
https://example.com/handbook.pdf
s3://bucket/key/`,className:"w-full rounded-md border border-surface-border bg-surface px-3 py-2 font-mono text-xs"})}),e.jsxs(L,{label:"Or drop files (optional)",children:[e.jsxs("p",{className:"mb-2 text-[11px] text-ink-dim",children:["PDF, DOCX, MD, TXT, CSV, HTML, RST, JSON, YAML accepted. Files land under ",e.jsxs("code",{children:["~/.amx/uploads/",d||"<profile>","/"]})," and ingest immediately when you save the profile."]}),e.jsx("div",{onDragOver:v=>{v.preventDefault(),g(!0)},onDragLeave:()=>g(!1),onDrop:v=>{v.preventDefault(),g(!1),v.dataTransfer.files?.length&&D(v.dataTransfer.files)},className:"rounded-md border border-dashed px-3 py-3 text-xs transition "+(_?"border-accent bg-accent-soft text-accent-ink":"border-surface-border text-ink-dim hover:border-accent/40"),children:e.jsxs("label",{className:"flex cursor-pointer items-center justify-between gap-2",children:[e.jsx("span",{children:c.length===0?"Drag-drop files here, or click to browse.":`${c.length} file${c.length===1?"":"s"} staged — drop more or click to add.`}),e.jsx("input",{type:"file",multiple:!0,onChange:v=>{v.target.files?.length&&D(v.target.files),v.target.value=""},className:"hidden",accept:".md,.markdown,.txt,.pdf,.docx,.doc,.csv,.tsv,.html,.htm,.rst,.rtf,.json,.yaml,.yml"}),e.jsx("span",{className:"rounded bg-surface-subtle px-2 py-0.5 text-[10px]",children:"Browse"})]})}),c.length>0&&e.jsx("ul",{className:"mt-2 space-y-0.5 text-[11px] text-ink-muted",children:c.map((v,F)=>e.jsxs("li",{className:"flex items-center justify-between gap-2 rounded bg-surface-subtle px-2 py-1",children:[e.jsxs("span",{className:"truncate font-mono",children:[v.name," ",e.jsxs("span",{className:"text-ink-dim",children:["(",(v.size/1024).toFixed(1)," KB)"]})]}),e.jsx("button",{type:"button",onClick:()=>x(c.filter((E,P)=>P!==F)),className:"rounded p-0.5 text-ink-dim hover:bg-critical/10 hover:text-critical",title:"Remove",children:e.jsx(Y,{size:11})})]},`${v.name}-${F}`))}),T&&e.jsx("p",{className:"mt-1 text-[11px] text-ink-muted",children:T}),N&&e.jsx("p",{className:"mt-1 text-[11px] text-critical",children:N})]}),e.jsx(Ye,{selected:a,onChange:m,kind:"doc"}),$.isError&&e.jsx("div",{className:"rounded-md border border-critical/40 bg-critical/5 px-3 py-2 text-xs text-critical",children:$.error instanceof Error?$.error.message:"Save failed."})]})})}function Ye({selected:s,onChange:r,kind:t}){const n=C({queryKey:["profiles","db","names-only"],queryFn:()=>y("/api/profiles/db"),retry:!1}).data?.profiles??[],o=i=>{s.includes(i)?r(s.filter(d=>d!==i)):r([...s,i])};return e.jsxs(L,{label:"Linked DB profiles (optional)",children:[e.jsxs("p",{className:"mb-2 text-[11px] text-ink-dim",children:["Pick which DB profiles this ",t," documents. Empty = global (in scope for every /ask). When set, /ask only pulls from this ",t," ","profile when at least one of the selected DBs is in the question's scope."]}),n.length===0?e.jsxs("p",{className:"text-xs text-ink-dim",children:["No DB profiles configured yet — leave empty to keep this ",t," ","profile global."]}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(i=>{const d=s.includes(i.name);return e.jsx("button",{type:"button",onClick:()=>o(i.name),className:"rounded-md border px-2 py-1 text-xs font-mono transition "+(d?"border-accent bg-accent-soft text-accent-ink":"border-surface-border bg-surface text-ink-muted hover:border-accent/40"),children:i.name},i.name)})})]})}function Yt(){const[s,r]=p.useState(""),[t,l]=p.useState(""),n=C({queryKey:["docs-search",t],queryFn:()=>y(`/api/docs/search?q=${encodeURIComponent(t)}&n=8`),enabled:t.length>0,retry:!1});return e.jsxs(O,{className:"mb-4",children:[e.jsx(I,{title:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(be,{size:14,className:"text-accent"}),"Search docs"]}),description:"Embedding-only Chroma similarity over every chunk you've ingested. No LLM call — instant."}),e.jsxs(U,{className:"space-y-3",children:[e.jsxs("form",{onSubmit:o=>{o.preventDefault(),l(s.trim())},className:"flex gap-2",children:[e.jsx("input",{type:"text",value:s,onChange:o=>r(o.target.value),placeholder:"e.g. customer master, order pipeline, GDPR…",className:"flex-1 rounded-md border border-surface-border bg-surface px-3 py-1.5 text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/20"}),e.jsx("button",{type:"submit",disabled:!s.trim()||n.isFetching,className:"rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90 disabled:opacity-40",children:n.isFetching?"Searching…":"Search"})]}),n.error&&e.jsx("div",{className:"rounded-md border border-critical/40 bg-critical/5 px-3 py-2 text-xs text-critical",children:n.error.message}),n.data&&e.jsxs("div",{className:"space-y-2",children:[n.data.message&&e.jsx("p",{className:"text-xs text-warning",children:n.data.message}),n.data.hits.length===0?e.jsx("p",{className:"text-xs text-ink-dim",children:"No matches."}):e.jsx("ul",{className:"space-y-2",children:n.data.hits.map((o,i)=>e.jsxs("li",{className:"rounded-md border border-surface-border bg-surface px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px]",children:[e.jsx("span",{className:"truncate font-mono text-ink-muted",children:o.source}),e.jsxs("span",{className:"font-mono text-ink-dim",children:["d=",o.distance.toFixed(3)]})]}),e.jsx("p",{className:"mt-1 line-clamp-3 text-xs text-ink-muted",children:o.preview})]},`${o.source}-${i}`))})]})]})]})}function Zt(){const[s,r]=p.useState(""),[t,l]=p.useState(""),n=C({queryKey:["code-search",t],queryFn:()=>y(`/api/code/search?q=${encodeURIComponent(t)}&n=8`),enabled:t.length>0,retry:!1});return e.jsxs(O,{className:"mb-4",children:[e.jsx(I,{title:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(ge,{size:14,className:"text-accent"}),"Search code"]}),description:"Embedding-only Chroma similarity over every snippet you've indexed via /code-scan. No LLM call — instant. For a comprehensive table-level review, use Code Analyze (CLI: /code-analyze)."}),e.jsxs(U,{className:"space-y-3",children:[e.jsxs("form",{onSubmit:o=>{o.preventDefault(),l(s.trim())},className:"flex gap-2",children:[e.jsx("input",{type:"text",value:s,onChange:o=>r(o.target.value),placeholder:"e.g. where is customers written, ETL job for orders…",className:"flex-1 rounded-md border border-surface-border bg-surface px-3 py-1.5 text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/20"}),e.jsx("button",{type:"submit",disabled:!s.trim()||n.isFetching,className:"rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90 disabled:opacity-40",children:n.isFetching?"Searching…":"Search"})]}),n.error&&e.jsx("div",{className:"rounded-md border border-critical/40 bg-critical/5 px-3 py-2 text-xs text-critical",children:n.error.message}),n.data&&e.jsxs("div",{className:"space-y-2",children:[n.data.message&&e.jsx("p",{className:"text-xs text-warning",children:n.data.message}),n.data.hits.length===0?e.jsx("p",{className:"text-xs text-ink-dim",children:"No matches."}):e.jsx("ul",{className:"space-y-2",children:n.data.hits.map((o,i)=>{const d=typeof o.score=="number"&&o.score>0;return e.jsxs("li",{className:"rounded-md border border-surface-border bg-surface px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px]",children:[e.jsxs("span",{className:"truncate font-mono text-ink-muted",children:[o.source,o.symbol?e.jsxs("span",{className:"ml-2 text-accent-ink",children:["· ",o.symbol]}):null]}),e.jsx("span",{className:"font-mono text-ink-dim",title:`distance: ${o.distance.toFixed(3)}`,children:d?`score ${o.score.toFixed(2)}`:`d=${o.distance.toFixed(3)}`})]}),e.jsx("p",{className:"mt-1 line-clamp-3 whitespace-pre-wrap text-xs text-ink-muted",children:o.preview})]},`${o.source}-${i}`)})})]})]})]})}function es({open:s,onClose:r,codeProfile:t,onJobStarted:l}){const[n,o]=p.useState(""),[i,d]=p.useState(""),[h,b]=p.useState(null),u=w({mutationFn:()=>{const a=i.split(/[\n,]/).map(m=>m.trim()).filter(Boolean);return y("/api/code/analyze",{method:"POST",body:JSON.stringify({schema:n,tables:a,code_profile:t})})},onSuccess:a=>{l(a.job_id,`Code Analyze ${t} (${a.tables.length} table${a.tables.length===1?"":"s"})`),r()},onError:a=>b(a instanceof Error?a.message:String(a))});return e.jsx(se,{open:s,onClose:r,title:`Code Analyze — ${t}`,description:"Run the Code Agent against the cached /code-scan for the listed tables. Results write to ~/.amx/code_agent_results.json — the next /run will pick them up automatically.",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:r,className:"rounded-md bg-surface-subtle px-3 py-1.5 text-sm text-ink-muted hover:bg-surface-border",children:"Cancel"}),e.jsx("button",{type:"button",onClick:()=>{b(null),u.mutate()},disabled:!n.trim()||!i.trim()||u.isPending,className:"rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90 disabled:opacity-40",children:u.isPending?"Starting…":"Run analyze"})]}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(L,{label:"Schema",children:e.jsx("input",{type:"text",value:n,onChange:a=>o(a.target.value),placeholder:"e.g. sales",className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm"})}),e.jsx(L,{label:"Tables (comma- or newline-separated)",children:e.jsx("textarea",{value:i,onChange:a=>d(a.target.value),rows:4,placeholder:`orders
customers
...`,className:"w-full rounded-md border border-surface-border bg-surface px-3 py-2 font-mono text-xs"})}),h&&e.jsx("div",{className:"rounded-md border border-critical/40 bg-critical/5 px-3 py-2 text-xs text-critical",children:h})]})})}function ts({name:s}){const[r,t]=p.useState(!1),l=C({queryKey:["profiles","code",s,"health"],queryFn:()=>y(`/api/profiles/code/${encodeURIComponent(s)}/health`),retry:!1,staleTime:1e4});if(l.isLoading)return e.jsx("div",{className:"mt-2 pl-3 text-[10.5px] text-ink-dim",children:"Loading health…"});if(l.error||!l.data)return null;const n=l.data,o=n.chunk_count||0,i=n.last_indexed_at&&n.last_indexed_at>0?Ge(n.last_indexed_at):null,d=[];return o>0?d.push(`💻 ${o.toLocaleString()} chunk${o===1?"":"s"}`):d.push("💻 not indexed yet"),i&&d.push(`indexed ${i}`),n.embedding_model&&d.push(`model ${n.embedding_model}`),e.jsxs("div",{className:"mt-2 pl-3 text-[10.5px]",children:[e.jsx("div",{className:"text-ink-dim",children:d.join(" · ")}),n.last_error&&e.jsxs("button",{type:"button",onClick:()=>t(h=>!h),className:"mt-1 block w-full text-left text-critical/90 hover:text-critical",children:[e.jsx("span",{className:"mr-1",children:"⚠ Last index failed:"}),r?e.jsx("span",{className:"font-mono",children:n.last_error}):e.jsx("span",{className:"line-clamp-1 font-mono",children:n.last_error}),e.jsxs("span",{className:"ml-1 opacity-70",children:["(",r?"hide":"Inspect",")"]})]})]})}function ss(){const s=R(),[r,t]=p.useState(null),[l,n]=p.useState(null),[o,i]=p.useState(null),[d,h]=p.useState(null),b=C({queryKey:["profiles","code"],queryFn:()=>y("/api/profiles/code"),retry:!1,meta:{silentError:!0}}),u=w({mutationFn:c=>y(`/api/profiles/code/${encodeURIComponent(c)}/activate`,{method:"POST"}),onSuccess:()=>s.invalidateQueries({queryKey:["profiles","code"]})}),a=w({mutationFn:c=>y(`/api/profiles/code/${encodeURIComponent(c)}`,{method:"DELETE"}),onSuccess:()=>s.invalidateQueries({queryKey:["profiles","code"]})}),m=w({mutationFn:c=>y("/api/code/scan",{method:"POST",body:JSON.stringify({profile:c.profile,column_scan:c.column_scan})}),onSuccess:(c,x)=>h({jobId:c.job_id,label:`Scanning ${x.profile}${x.column_scan?" (incl. columns)":""}`})});return e.jsxs(e.Fragment,{children:[e.jsx(Zt,{}),d&&e.jsxs("div",{className:"mb-4",children:[e.jsx(He,{jobId:d.jobId,kind:"docs/scan",onTerminal:()=>h(null)}),e.jsx("p",{className:"mt-1 text-xs text-ink-dim",children:d.label})]}),e.jsxs(O,{children:[e.jsx(I,{title:`${b.data?.profiles?.length??0} code profile${b.data?.profiles?.length===1?"":"s"}`,description:`Active: ${b.data?.active??"—"} · A code profile points at a single codebase (local dir or Git URL) that the Code agent scans for table/column references.`,actions:e.jsxs("button",{type:"button",onClick:()=>t({name:null}),className:"inline-flex items-center gap-1.5 rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90",children:[e.jsx(de,{size:14}),"Add"]})}),e.jsx(U,{className:"p-0",children:b.isLoading?e.jsx("div",{className:"px-5 py-6",children:e.jsx(Q,{status:"loading",hideLoadingTitle:!0,loadingBlocks:3})}):b.isError?e.jsx("div",{className:"px-5 py-6",children:e.jsx(Q,{status:"error",error:b.error,onRetry:()=>b.refetch()})}):b.data?.profiles?.length?e.jsx("ul",{className:"divide-y divide-surface-border",children:b.data.profiles.map(c=>e.jsxs("li",{className:"px-5 py-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:c.name}),e.jsx("div",{className:"truncate font-mono text-xs text-ink-dim",children:c.path}),(c.linked_db_profiles?.length??0)>0&&e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1 text-[10px] text-ink-dim",children:[e.jsx("span",{children:"Links:"}),c.linked_db_profiles.map(x=>e.jsx("span",{className:"rounded bg-surface-subtle px-1.5 py-0.5 font-mono text-accent-ink",children:x},x))]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.is_active?e.jsx(G,{tone:"positive",children:"Active"}):e.jsx("button",{type:"button",onClick:()=>u.mutate(c.name),className:"rounded-md bg-surface-subtle px-2 py-1 text-xs text-ink-muted hover:bg-accent-soft hover:text-accent-ink",children:"Activate"}),e.jsx("button",{type:"button",onClick:()=>m.mutate({profile:c.name,column_scan:!1}),disabled:m.isPending||!!d,className:"rounded-md bg-accent-soft px-2 py-1 text-xs text-accent-ink hover:opacity-90 disabled:opacity-50",title:"Scan: walk source files for table references",children:"Scan"}),e.jsx("button",{type:"button",onClick:()=>m.mutate({profile:c.name,column_scan:!0}),disabled:m.isPending||!!d,className:"rounded-md bg-surface-subtle px-2 py-1 text-xs text-ink-muted hover:bg-surface-border disabled:opacity-50",title:"Scan + columns: also pick up column-name references (slower)",children:"+Cols"}),e.jsx("button",{type:"button",onClick:()=>i(c.name),disabled:!!d,className:"rounded-md bg-surface-subtle px-2 py-1 text-xs text-ink-muted hover:bg-accent-soft hover:text-accent-ink disabled:opacity-50",title:"Run the Code Agent against /code-scan output for selected tables",children:"Analyze"}),e.jsx("button",{type:"button",onClick:()=>t({name:c.name}),className:"rounded-md p-1 text-ink-dim hover:bg-surface-subtle hover:text-ink",title:"Edit",children:e.jsx(ce,{size:14})}),e.jsx("button",{type:"button",onClick:()=>{n(c.name)},className:"rounded-md p-1 text-ink-dim hover:bg-critical/10 hover:text-critical",title:"Delete",children:e.jsx(Y,{size:14})})]})]}),e.jsx(ts,{name:c.name})]},c.name))}):e.jsx(M,{icon:ge,title:"No code profiles yet",description:"Bind a repository so the Code agent can pick up SQL/Python references when generating descriptions."})})]}),r&&e.jsx(ns,{open:!0,editingName:r.name,existingPath:r.name?b.data?.profiles?.find(c=>c.name===r.name)?.path??"":"",existingLinkedDbs:r.name?b.data?.profiles?.find(c=>c.name===r.name)?.linked_db_profiles??[]:[],onClose:()=>t(null)}),o&&e.jsx(es,{open:!0,codeProfile:o,onClose:()=>i(null),onJobStarted:(c,x)=>h({jobId:c,label:x})}),e.jsx(J,{open:l!==null,onClose:()=>{a.isPending||n(null)},onConfirm:()=>{if(l){const c=l;a.mutate(c,{onSettled:()=>n(x=>x===c?null:x)})}},title:`Delete code profile '${l??""}'?`,description:"Drops the indexed repository snapshot and unbinds this profile from any linked DB connections. The action cannot be undone.",confirmLabel:"Delete",loading:a.isPending})]})}function ns({open:s,onClose:r,editingName:t,existingPath:l,existingLinkedDbs:n}){const o=R(),i=t!=null,[d,h]=p.useState(t??""),[b,u]=p.useState(l),[a,m]=p.useState(n),c=w({mutationFn:()=>y(`/api/profiles/code/${encodeURIComponent(d)}`,{method:"PUT",body:JSON.stringify({path:b,linked_db_profiles:a})}),onSuccess:()=>{o.invalidateQueries({queryKey:["profiles","code"]}),r()}});return e.jsx(se,{open:s,onClose:r,title:i?`Edit ${t}`:"Add code profile",description:"A single repository or local directory the Code agent walks for SQL/Python references.",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:r,className:"rounded-md bg-surface-subtle px-3 py-1.5 text-sm text-ink-muted hover:bg-surface-border",children:"Cancel"}),e.jsx("button",{type:"button",onClick:()=>c.mutate(),disabled:!d.trim()||!b.trim()||c.isPending,className:"rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-accent-soft transition hover:opacity-90 disabled:opacity-40",children:c.isPending?"Saving…":"Save"})]}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(L,{label:"Profile name",children:e.jsx("input",{type:"text",value:d,onChange:x=>h(x.target.value),disabled:i,placeholder:"e.g. main-repo",className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm disabled:opacity-60"})}),e.jsx(L,{label:"Path or Git URL",children:e.jsx("input",{type:"text",value:b,onChange:x=>u(x.target.value),placeholder:"/abs/path/to/repo or https://github.com/org/repo",className:"w-full rounded-md border border-surface-border bg-surface px-3 py-1.5 font-mono text-sm"})}),e.jsx(Ye,{selected:a,onChange:m,kind:"code"}),c.isError&&e.jsx("div",{className:"rounded-md border border-critical/40 bg-critical/5 px-3 py-2 text-xs text-critical",children:c.error instanceof Error?c.error.message:"Save failed."})]})})}function L({label:s,children:r,narrow:t,hint:l}){return e.jsxs("label",{className:V("block",t&&"max-w-[160px]"),children:[e.jsxs("span",{className:"mb-1 flex items-center gap-1 text-[11px] font-semibold uppercase tracking-wider text-ink-dim",children:[s,l&&e.jsx(Me,{text:l})]}),r]})}export{ks as default};
