agent-nuvira 3.3.18 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -64,7 +64,7 @@ Error generating stack: `+s.message+`
64
64
  * LICENSE.md file in the root directory of this source tree.
65
65
  *
66
66
  * @license MIT
67
- */function nh(){return nh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},nh.apply(null,arguments)}function ET(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function D2(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function B2(e,t){return e.button===0&&(!t||t==="_self")&&!D2(e)}const z2=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],F2=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],U2="6";try{window.__reactRouterVersion=U2}catch{}const W2=x.createContext({isTransitioning:!1}),H2="startTransition",eS=$$[H2];function G2(e){let{basename:t,children:n,future:r,window:a}=e,s=x.useRef();s.current==null&&(s.current=VD({window:a,v5Compat:!0}));let o=s.current,[l,c]=x.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},d=x.useCallback(f=>{u&&eS?eS(()=>c(f)):c(f)},[c,u]);return x.useLayoutEffect(()=>o.listen(d),[o,d]),x.useEffect(()=>I2(r),[r]),x.createElement($2,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}const q2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",K2=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,rn=x.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:s,replace:o,state:l,target:c,to:u,preventScrollReset:d,viewTransition:f}=t,h=ET(t,z2),{basename:p}=x.useContext(Da),m,g=!1;if(typeof u=="string"&&K2.test(u)&&(m=u,q2))try{let w=new URL(window.location.href),j=u.startsWith("//")?new URL(w.protocol+u):new URL(u),k=Ko(j.pathname,p);j.origin===w.origin&&k!=null?u=k+j.search+j.hash:g=!0}catch{}let y=x2(u,{relative:a}),v=Y2(u,{replace:o,state:l,target:c,preventScrollReset:d,relative:a,viewTransition:f});function S(w){r&&r(w),w.defaultPrevented||v(w)}return x.createElement("a",nh({},h,{href:m||y,onClick:g||s?r:S,ref:n,target:c}))}),tS=x.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:s="",end:o=!1,style:l,to:c,viewTransition:u,children:d}=t,f=ET(t,F2),h=Pp(c,{relative:f.relative}),p=Ri(),m=x.useContext(xT),{navigator:g,basename:y}=x.useContext(Da),v=m!=null&&X2(h)&&u===!0,S=g.encodeLocation?g.encodeLocation(h).pathname:h.pathname,w=p.pathname,j=m&&m.navigation&&m.navigation.location?m.navigation.location.pathname:null;a||(w=w.toLowerCase(),j=j?j.toLowerCase():null,S=S.toLowerCase()),j&&y&&(j=Ko(j,y)||j);const k=S!=="/"&&S.endsWith("/")?S.length-1:S.length;let b=w===S||!o&&w.startsWith(S)&&w.charAt(k)==="/",N=j!=null&&(j===S||!o&&j.startsWith(S)&&j.charAt(S.length)==="/"),_={isActive:b,isPending:N,isTransitioning:v},T=b?r:void 0,A;typeof s=="function"?A=s(_):A=[s,b?"active":null,N?"pending":null,v?"transitioning":null].filter(Boolean).join(" ");let O=typeof l=="function"?l(_):l;return x.createElement(rn,nh({},f,{"aria-current":T,className:A,ref:n,style:O,to:c,viewTransition:u}),typeof d=="function"?d(_):d)});var dy;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(dy||(dy={}));var nS;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(nS||(nS={}));function V2(e){let t=x.useContext(Tp);return t||At(!1),t}function Y2(e,t){let{target:n,replace:r,state:a,preventScrollReset:s,relative:o,viewTransition:l}=t===void 0?{}:t,c=Qx(),u=Ri(),d=Pp(e,{relative:o});return x.useCallback(f=>{if(B2(f,n)){f.preventDefault();let h=r!==void 0?r:th(u)===th(d);c(e,{replace:h,state:a,preventScrollReset:s,relative:o,viewTransition:l})}},[u,c,d,r,a,n,e,s,o,l])}function X2(e,t){t===void 0&&(t={});let n=x.useContext(W2);n==null&&At(!1);let{basename:r}=V2(dy.useViewTransitionState),a=Pp(e,{relative:t.relative});if(!n.isTransitioning)return!1;let s=Ko(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Ko(n.nextLocation.pathname,r)||n.nextLocation.pathname;return cy(a.pathname,o)!=null||cy(a.pathname,s)!=null}async function ot(e){if(!e.ok)return null;const t=e.headers.get("content-type")||"";if(!t.includes("application/json")&&!t.includes("text/json"))return t.includes("text/html")&&console.warn(`[dashboard] GET ${e.url||"/api/*"} returned HTML (${e.status}) instead of JSON — the dashboard server may be an older version. Stop it and start it again (agent-nuvira dashboard stop, or Ctrl+C in its terminal).`),null;try{return await e.json()}catch{return null}}const No="buff-dashboard-admin-token";function _T(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}return null}function Q2(e){if(!e||typeof e!="object")return!1;const t=e,n=t.diff;return typeof t.dir=="string"&&typeof t.base=="string"&&typeof t.removed=="boolean"&&!!n&&typeof n=="object"&&Array.isArray(n.files)&&n.files.every(r=>typeof r=="string")&&typeof n.summary=="string"&&!!n.payload&&typeof n.payload=="object"&&typeof n.payload.summary=="string"&&Array.isArray(n.payload.files)&&n.payload.files.every(r=>!!r&&typeof r.path=="string"&&typeof r.body=="string")}function Z2(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.replayed=="number"&&typeof t.modelCalls=="number"&&typeof t.saved=="boolean"&&typeof t.notice=="string"&&(t.callsAvoided===void 0||typeof t.callsAvoided=="number")}function J2(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.goal=="string"&&typeof t.planned=="boolean"&&Array.isArray(t.steps)&&!!t.stepCounts&&typeof t.stepCounts=="object"&&typeof t.stepCounts.total=="number"&&typeof t.verification=="string"&&["verified","unverified","blocked","not-applicable","delivered-and-read-back"].includes(t.verification)&&(t.summary===null||typeof t.summary=="string")&&Array.isArray(t.changedPaths)&&!!t.flags&&typeof t.flags=="object"}const fy=new Map;function eB(){const e=_T();if(e)try{const t=e.getItem(No);if(t)return t}catch{}return fy.get(No)??null}function tB(e){const t=_T();if(t)try{e?t.setItem(No,e):t.removeItem(No);return}catch{}e?fy.set(No,e):fy.delete(No)}function en(){return eB()}let hy=0;const py=new Set;function nB(){return hy}function rB(e){return py.add(e),()=>{py.delete(e)}}function aB(){hy+=1;for(const e of py)try{e(hy)}catch{}}function sg(e){tB(e),aB()}function yt(){const e=en();return e?{Authorization:`Bearer ${e}`}:{}}class iB{constructor(t=""){Jr(this,"sse",null);Jr(this,"listeners",new Set);Jr(this,"connectionListeners",new Set);Jr(this,"dagListeners",new Set);Jr(this,"typingListeners",new Set);Jr(this,"chatRetryListeners",new Set);Jr(this,"reconnectTimer",null);Jr(this,"baseUrl");Jr(this,"lastData",null);this.baseUrl=t}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}onConnectionChange(t){return this.connectionListeners.add(t),()=>this.connectionListeners.delete(t)}onDAGEvent(t){return this.dagListeners.add(t),()=>this.dagListeners.delete(t)}onTypingEvent(t){return this.typingListeners.add(t),()=>this.typingListeners.delete(t)}onChatRetryEvent(t){return this.chatRetryListeners.add(t),()=>this.chatRetryListeners.delete(t)}connect(){this.sse||(this.sse=new EventSource(`${this.baseUrl}/api/sse`),this.sse.addEventListener("init",t=>{try{const n=JSON.parse(t.data);this.lastData=n,this.notify(n),this.notifyConnection(!0)}catch(n){console.error("Failed to parse SSE init data:",n)}}),this.sse.addEventListener("refresh",t=>{try{const n=JSON.parse(t.data);this.lastData=n,this.notify(n),this.notifyConnection(!0)}catch(n){console.error("Failed to parse SSE refresh data:",n)}}),this.sse.addEventListener("dag",t=>{try{const n=JSON.parse(t.data);if(this.notifyDAG(n),this.lastData){const r={...this.lastData,dag:n};this.lastData=r,this.notify(r)}}catch(n){console.error("Failed to parse SSE dag event:",n)}}),this.sse.addEventListener("quota",t=>{try{const n=JSON.parse(t.data);if(this.lastData&&n.quota){const r={...this.lastData,routing:{...this.lastData.routing||{},quota:n.quota},serverTime:n.serverTime||this.lastData.serverTime};this.lastData=r,this.notify(r)}}catch(n){console.error("Failed to parse SSE quota event:",n)}}),this.sse.addEventListener("conversation",t=>{try{const n=JSON.parse(t.data);if(this.lastData&&n.conversations){const r={...this.lastData,conversations:{total:n.total??n.conversations.length,recent:n.conversations},serverTime:n.serverTime||this.lastData.serverTime};this.lastData=r,this.notify(r)}}catch(n){console.error("Failed to parse SSE conversation event:",n)}}),this.sse.addEventListener("typing",t=>{try{const n=JSON.parse(t.data);for(const r of this.typingListeners)try{r(n)}catch{}}catch(n){console.error("Failed to parse SSE typing event:",n)}}),this.sse.addEventListener("chat-retry",t=>{try{const n=JSON.parse(t.data);if(!n||typeof n.sessionId!="string"||typeof n.content!="string")return;for(const r of this.chatRetryListeners)try{r(n)}catch{}}catch(n){console.error("Failed to parse SSE chat-retry event:",n)}}),this.sse.onerror=()=>{this.notifyConnection(!1),this.disconnect(),this.reconnect()},this.sse.onopen=()=>{this.notifyConnection(!0)})}disconnect(){this.sse&&(this.sse.close(),this.sse=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}reconnect(){this.reconnectTimer=setTimeout(()=>{this.connect()},3e3)}notify(t){this.listeners.forEach(n=>n(t))}notifyDAG(t){this.dagListeners.forEach(n=>n(t))}notifyConnection(t){this.connectionListeners.forEach(n=>n(t))}async fetchAll(){try{const t=await fetch(`${this.baseUrl}/api/all`),n=await ot(t);return n?(this.lastData=n,n):null}catch{return null}}async fetchExecutionAudit(t){try{const n=new URLSearchParams;t!=null&&t.skillName&&n.set("skillName",t.skillName),t!=null&&t.status&&n.set("status",t.status),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await fetch(`${this.baseUrl}/api/executions${r?`?${r}`:""}`,{signal:AbortSignal.timeout(8e3)}),s=await ot(a);return(s==null?void 0:s.entries)??[]}catch{return[]}}async fetchTraces(){try{const t=await fetch(`${this.baseUrl}/api/traces`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return n!=null&&n.traces?n.traces:null}catch{return null}}async fetchAcceptance(){try{const t=await fetch(`${this.baseUrl}/api/acceptance`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||typeof n.labelled!="number"?null:n}catch{return null}}acceptanceExportUrl(t="json"){return`${this.baseUrl}/api/acceptance/export?format=${t}`}async importAcceptance(t,n){try{const r=await fetch(`${this.baseUrl}/api/acceptance/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t,...n?{format:n}:{}})}),a=await ot(r);return!a||typeof a.ok!="boolean"?null:a}catch{return null}}async fetchDecisions(t,n){try{const r=new URLSearchParams;t&&r.set("dir",t),n&&n.trim()&&r.set("for",n.trim());const a=await fetch(`${this.baseUrl}/api/decisions?${r.toString()}`,{signal:AbortSignal.timeout(8e3)}),s=await ot(a);return!s||!Array.isArray(s.decisions)?null:s}catch{return null}}async reviseDecision(t,n,r,a){try{const s=await fetch(`${this.baseUrl}/api/decisions/revise`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dir:t,id:n,answer:r,...a?{note:a}:{}})}),o=await ot(s);return!o||o.ok!==!0||!o.decision?null:o.decision}catch{return null}}async fetchGates(){try{const t=await fetch(`${this.baseUrl}/api/gates`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||typeof n.events!="number"?null:n}catch{return null}}async fetchConsent(){try{const t=await fetch(`${this.baseUrl}/api/consent`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||n.ok!==!0||!n.picture||!n.picture.denied?null:n.picture}catch{return null}}async fetchCapabilities(){try{const t=await fetch(`${this.baseUrl}/api/capabilities`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||n.ok!==!0||!Array.isArray(n.verbs)?null:n}catch{return null}}async saveLearnedCommand(t,n,r){try{const a=await fetch(`${this.baseUrl}/api/capabilities/commands`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verb:t,command:n,...r?{note:r}:{}})}),s=await ot(a);return{ok:(s==null?void 0:s.ok)===!0,commands:s==null?void 0:s.commands,error:s==null?void 0:s.error}}catch{return{ok:!1,error:"Could not reach the server."}}}async forgetLearnedCommand(t){try{const n=await fetch(`${this.baseUrl}/api/capabilities/commands/forget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verb:t})}),r=await ot(n);return{ok:(r==null?void 0:r.ok)===!0,commands:r==null?void 0:r.commands,error:r==null?void 0:r.error}}catch{return{ok:!1,error:"Could not reach the server."}}}async fetchSessionGrants(){try{const t=await fetch(`${this.baseUrl}/api/session-grants`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||!Array.isArray(n.grants)?null:n.grants}catch{return null}}async revokeSessionGrant(t){try{const n=await fetch(`${this.baseUrl}/api/session-grants/clear`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t})}),r=await ot(n);return(r==null?void 0:r.ok)===!0}catch{return!1}}async fetchAdminChecks(){try{const t=await fetch(`${this.baseUrl}/api/admin/checks`,{signal:AbortSignal.timeout(15e3)}),n=await ot(t);return!n||!Array.isArray(n.system)||!Array.isArray(n.enterprise)||!Array.isArray(n.providers)?null:n}catch{return null}}async fetchHub(){var t;try{const n=await fetch(`${this.baseUrl}/api/hub`,{signal:AbortSignal.timeout(8e3)}),r=await ot(n);return!r||!Array.isArray((t=r.toolsets)==null?void 0:t.toolsets)?null:r}catch{return null}}async rateTrace(t,n){try{const r=await fetch(`${this.baseUrl}/api/traces/${encodeURIComponent(t)}/verdict`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verdict:n}),signal:AbortSignal.timeout(8e3)}),a=await ot(r);return a!=null&&a.ok&&a.rated?{traceId:a.rated.traceId,corpusLabeled:!!a.rated.corpusLabeled}:null}catch{return null}}async fetchTraceDetail(t){try{const n=await fetch(`${this.baseUrl}/api/traces/${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(8e3)}),r=await ot(n);return r&&Array.isArray(r.steps)?r:null}catch{return null}}async sendAdminRequest(t,n,r){try{const a=en(),s=await fetch(`${this.baseUrl}${t}`,{method:n,headers:{"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{}},body:r!==void 0?JSON.stringify(r):void 0,signal:AbortSignal.timeout(15e3)}),o=s.headers.get("content-type")||"";let l=null;if(o.includes("application/json")||o.includes("text/json"))try{l=await s.json()}catch{l=null}return{status:s.status,data:l}}catch{return null}}async fetchAdminAuthStatus(){const t=await this.sendAdminRequest("/api/admin/auth-status","GET");if(!t||typeof t.data!="object"||t.data===null)return null;const n=t.data;return typeof n.configured!="boolean"||typeof n.authenticated!="boolean"?null:{configured:n.configured,authenticated:n.authenticated,user:typeof n.user=="string"?n.user:null,role:typeof n.role=="string"?n.role:null,mustChangePassword:n.mustChangePassword===!0}}async changeAdminPassword(t,n){const r=await this.sendAdminRequest("/api/admin/change-password","POST",{currentPassword:t,newPassword:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?{ok:!0}:{ok:!1,error:a.error||"Could not change the password."}}async fetchAdminUsers(){const t=await this.sendAdminRequest("/api/admin/users","GET");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok&&Array.isArray(n.users)?n:{ok:!1,error:n.error||"Failed to load users.",forbidden:t.status===403,unauthorized:t.status===401}}async addAdminUser(t,n,r){const a=await this.sendAdminRequest("/api/admin/users","POST",{user:t,password:n,role:r});if(!a)return{ok:!1,error:"Could not reach the dashboard server."};const s=a.data??{};return a.status===200&&s.ok?s:{ok:!1,error:s.error||"Failed to add user.",forbidden:a.status===403,unauthorized:a.status===401}}async removeAdminUser(t){const n=await this.sendAdminRequest(`/api/admin/users/${encodeURIComponent(t)}`,"DELETE");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Failed to remove user.",forbidden:n.status===403,unauthorized:n.status===401}}async fetchAdminCatalog(){const t=await this.sendAdminRequest("/api/admin/catalog","GET"),n=t==null?void 0:t.data;return!n||!Array.isArray(n.providers)?null:n.providers}async adminSetup(t,n){const r=await this.sendAdminRequest("/api/admin/setup","POST",{user:t,password:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&typeof a.token=="string"?(sg(a.token),{ok:!0,user:a.user,token:a.token}):{ok:!1,error:a.error||"Setup failed.",unauthorized:r.status===401}}async adminLogin(t,n){const r=await this.sendAdminRequest("/api/admin/login","POST",{user:t,password:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&typeof a.token=="string"?(sg(a.token),{ok:!0,user:a.user,token:a.token}):{ok:!1,error:a.error||"Login failed.",unauthorized:r.status===401}}async adminLogout(){await this.sendAdminRequest("/api/admin/logout","POST"),sg(null)}async shutdown(t){const n=await this.sendAdminRequest("/api/admin/shutdown","POST",{target:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Shutdown failed.",unauthorized:n.status===401,forbidden:n.status===403}}async saveProvider(t,n){const r=await this.sendAdminRequest(`/api/admin/providers/${encodeURIComponent(t)}`,"PUT",n);if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Save failed.",unauthorized:r.status===401}}async deleteProvider(t){const n=await this.sendAdminRequest(`/api/admin/providers/${encodeURIComponent(t)}`,"DELETE");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Remove failed.",unauthorized:n.status===401}}async testProvider(t){const n=await this.sendAdminRequest(`/api/admin/providers/${encodeURIComponent(t)}/test`,"POST");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200?r:{ok:!1,error:r.error||"Test failed.",unauthorized:n.status===401}}async fetchOmniRouteStatus(){const t=await this.sendAdminRequest("/api/admin/omniroute","GET");if(!t)return null;const n=t.data??{};return t.status!==200||!n.status?null:n.status}async controlOmniRoute(t){const n=await this.sendAdminRequest("/api/admin/omniroute","POST",{action:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200?r:{ok:!1,error:r.error||"OmniRoute control failed.",unauthorized:n.status===401,forbidden:n.status===403}}async fetchAdminWorkspace(){const t=await this.sendAdminRequest("/api/admin/workspace","GET");if(!t)return null;const n=t.data??{};return t.status!==200||n.ok!==!0?null:{configured:typeof n.configured=="string"?n.configured:null,effective:typeof n.effective=="string"?n.effective:null,processCwd:typeof n.processCwd=="string"?n.processCwd:"",configuredValid:n.configuredValid===!0}}async saveAdminWorkspace(t){const n=await this.sendAdminRequest("/api/admin/workspace","PUT",{cwd:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok===!0?{ok:!0,workspace:{configured:typeof r.configured=="string"?r.configured:null,effective:typeof r.effective=="string"?r.effective:null,processCwd:typeof r.processCwd=="string"?r.processCwd:"",configuredValid:r.configuredValid===!0}}:{ok:!1,error:r.error||"Save failed.",unauthorized:n.status===401,forbidden:n.status===403}}async fetchAdminCache(){const t=await this.sendAdminRequest("/api/admin/cache","GET");if(!t)return null;const n=t.data;return!n||n.ok!==!0||!Array.isArray(n.workspaces)?null:n}async clearAdminCache(t){const n=await this.sendAdminRequest("/api/admin/cache/clear","POST",{scope:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0,removed:r.removed??0}:{ok:!1,error:r.error||"Could not clear the cache.",unauthorized:n.status===401,forbidden:n.status===403}}async fetchAdminServices(){const t=await this.sendAdminRequest("/api/admin/services","GET");if(!t)return null;const n=t.data;return!n||n.ok!==!0||!Array.isArray(n.services)?null:n}async saveService(t,n){const r=await this.sendAdminRequest(`/api/admin/services/${encodeURIComponent(t)}`,"PUT",{values:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Save failed.",unauthorized:r.status===401,forbidden:r.status===403}}async testService(t){const n=await this.sendAdminRequest(`/api/admin/services/${encodeURIComponent(t)}/test`,"POST");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200?r:{ok:!1,error:r.error||"Test failed."}}async removeService(t){const n=await this.sendAdminRequest(`/api/admin/services/${encodeURIComponent(t)}`,"DELETE");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Remove failed.",unauthorized:n.status===401,forbidden:n.status===403}}async fetchAdminQuota(){const t=await this.sendAdminRequest("/api/admin/quota","GET");if(!t)return null;const n=t.data;return!n||!n.ok||typeof n.quota!="object"?null:n}async setToolsetEnabled(t,n){const r=await this.sendAdminRequest(`/api/admin/hub/toolsets/${encodeURIComponent(t)}`,"PUT",{enabled:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Toggle failed.",unauthorized:r.status===401,forbidden:r.status===403}}async setSkillEnabled(t,n){const r=await this.sendAdminRequest(`/api/admin/hub/skills/${encodeURIComponent(t)}`,"PUT",{enabled:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Toggle failed.",unauthorized:r.status===401,forbidden:r.status===403}}async fetchKnowledge(){try{const n=await(await fetch(`${this.baseUrl}/api/knowledge`,{headers:yt(),signal:AbortSignal.timeout(8e3)})).json();return Array.isArray(n.tags)?n.tags:null}catch{return null}}async knowledgeIngest(t,n){try{const r=await fetch(`${this.baseUrl}/api/knowledge/ingest`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({tag:t,paths:n})}),a=await r.json();return r.status===200&&a.ok?{...a,ok:!0}:{ok:!1,error:a.error||"Ingest failed."}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}}async knowledgeQuery(t,n,r){try{const a=await fetch(`${this.baseUrl}/api/knowledge/query`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({tag:t,question:n,topK:r})}),s=await a.json();return a.status===200&&s.ok?{...s,ok:!0}:{ok:!1,error:s.error||"Query failed."}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}async knowledgeForget(t){try{const n=await fetch(`${this.baseUrl}/api/knowledge/forget`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({tag:t})}),r=await n.json();return n.status===200&&r.ok?{...r,ok:!0}:{ok:!1,error:r.error||"Forget failed."}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async marketplaceSearch(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/marketplace?q=${encodeURIComponent(t)}`,{headers:yt()})).json();return Array.isArray(r.results)?r.results:[]}catch{return[]}}async marketplaceInstall(t){try{const n=await fetch(`${this.baseUrl}/api/skills/marketplace/install`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})}),r=await n.json();return n.status===200&&r.ok?{ok:!0}:{ok:!1,error:r.error||"Install failed.",quarantined:r.quarantined===!0}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async marketplaceUninstall(t){try{const n=await fetch(`${this.baseUrl}/api/skills/marketplace/uninstall`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})}),r=await n.json();return n.status===200&&r.ok?{ok:!0}:{ok:!1,error:r.error||"Uninstall failed."}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async sendChannelMessage(t,n){const r=await this.sendAdminRequest("/api/admin/hub/channels/send","POST",{target:t,text:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Send failed.",unauthorized:r.status===401,forbidden:r.status===403}}async gatewayPolicies(){const t=await this.sendAdminRequest("/api/admin/gateway/policies","GET");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?{ok:!0,policies:n.policies,statusRecipients:n.statusRecipients,contacts:n.contacts,askUserWait:n.askUserWait,askUserTimeoutMs:n.askUserTimeoutMs}:{ok:!1,error:n.error||"Failed to read policies.",unauthorized:t.status===401,forbidden:t.status===403}}async saveGatewayPolicies(t,n,r,a){const s={policies:t};Array.isArray(n)&&(s.statusRecipients=n),Array.isArray(r)&&(s.contacts=r),a&&(s.askUserWait=a.wait,typeof a.timeoutMs=="number"&&(s.askUserTimeoutMs=a.timeoutMs));const o=await this.sendAdminRequest("/api/admin/gateway/policies","PUT",s);if(!o)return{ok:!1,error:"Could not reach the dashboard server."};const l=o.data??{};return o.status===200&&l.ok?l:{ok:!1,error:l.error||"Failed to save policies.",unauthorized:o.status===401,forbidden:o.status===403}}async fetchGatewayConversations(t={}){const n=new URLSearchParams;t.offset&&n.set("offset",String(t.offset)),t.limit&&n.set("limit",String(t.limit)),t.q&&n.set("q",t.q);const r=n.toString(),a=await this.sendAdminRequest(`/api/admin/gateway/conversations${r?`?${r}`:""}`,"GET");if(!a)return{ok:!1,error:"Could not reach the dashboard server."};const s=a.data??{};return a.status===200&&s.ok?{ok:!0,conversations:s.conversations,total:s.total,hasMore:s.hasMore}:{ok:!1,error:s.error||"Failed to load conversations.",unauthorized:a.status===401,forbidden:a.status===403}}async clearGatewayConversation(t){const n=await this.sendAdminRequest("/api/admin/gateway/conversations","DELETE",{key:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0}:{ok:!1,error:r.error||"Failed to clear conversation.",unauthorized:n.status===401,forbidden:n.status===403}}async addConversationTag(t,n){const r=await this.sendAdminRequest("/api/admin/gateway/conversations/tags","PUT",{action:"add",key:t,tag:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?{ok:!0}:{ok:!1,error:a.error||"Failed to add tag.",unauthorized:r.status===401,forbidden:r.status===403}}async removeConversationTag(t,n){const r=await this.sendAdminRequest("/api/admin/gateway/conversations/tags","PUT",{action:"remove",key:t,tag:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?{ok:!0}:{ok:!1,error:a.error||"Failed to remove tag.",unauthorized:r.status===401,forbidden:r.status===403}}async getAllConversationTags(){const t=await this.sendAdminRequest("/api/admin/gateway/conversations/tags","PUT",{action:"getAllTags"});if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?{ok:!0,tags:n.tags}:{ok:!1,error:n.error||"Failed to load tags.",unauthorized:t.status===401,forbidden:t.status===403}}async exportGatewayConversations(t){var n,r,a;try{const s=en(),o=await fetch(`${this.baseUrl}/api/admin/gateway/conversations/export`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({keys:t}),signal:AbortSignal.timeout(3e4)});if(o.status===200&&((n=o.headers.get("content-type"))!=null&&n.includes("application/zip"))){const c=await o.blob(),u=URL.createObjectURL(c),d=document.createElement("a");return d.href=u,d.download=((a=(r=o.headers.get("content-disposition"))==null?void 0:r.match(/filename="(.+)"/))==null?void 0:a[1])||"conversations.zip",document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(u),{ok:!0}}return{ok:!1,error:(await o.json().catch(()=>({}))).error||"Export failed."}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}async getContacts(){const t=await this.sendAdminRequest("/api/admin/contacts","GET");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?{ok:!0,contacts:n.contacts}:{ok:!1,error:n.error||"Failed to read contacts."}}async approveContact(t,n){return this.contactAction("approve",t,n)}async rejectContact(t,n){return this.contactAction("reject",t,n)}async deleteContact(t,n){return this.contactAction("delete",t,n)}async updateContact(t,n,r){const a=await this.sendAdminRequest("/api/admin/contacts","PUT",{action:"update",platform:t,id:n,...r});if(!a)return{ok:!1,error:"Could not reach the dashboard server."};const s=a.data??{};return a.status===200&&s.ok?s:{ok:!1,error:s.error||"Update failed."}}async contactAction(t,n,r){const a=await this.sendAdminRequest("/api/admin/contacts","PUT",{action:t,platform:n,nameOrId:r});if(!a)return{ok:!1,error:"Could not reach the dashboard server."};const s=a.data??{};return a.status===200&&s.ok?s:{ok:!1,error:s.error||`${t} failed.`}}async getPlatformConfigs(){const t=await this.sendAdminRequest("/api/config/platforms","GET");if(!t)return[];const n=t.data??{};return Array.isArray(n.platforms)?n.platforms:[]}async setPlatformConfig(t,n){const r=await this.sendAdminRequest(`/api/config/platforms/${encodeURIComponent(t)}`,"POST",{values:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Save failed.",unauthorized:r.status===401,forbidden:r.status===403}}async removePlatformConfig(t){const n=await this.sendAdminRequest(`/api/config/platforms/${encodeURIComponent(t)}`,"DELETE");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Remove failed.",unauthorized:n.status===401,forbidden:n.status===403}}async verifyPlatformConfig(t,n){const r=await this.sendAdminRequest(`/api/config/platforms/${encodeURIComponent(t)}/verify`,"POST",{values:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return{ok:a.ok??!1,info:a.info,error:a.error}}async saveAdminQuota(t){const n=await this.sendAdminRequest("/api/admin/quota","PUT",t);if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Save failed.",unauthorized:n.status===401}}async getBedrockStatus(){const t=await this.sendAdminRequest("/api/bedrock/status","GET");return!t||t.status!==200?{configured:!1,region:"us-east-1",authMethod:"none",apiKeySet:!1,iamKeySet:!1}:t.data??{}}async setupBedrock(t){const n=await this.sendAdminRequest("/api/bedrock/setup","POST",{envVars:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0,envVarsWritten:r.envVarsWritten}:{ok:!1,error:r.error||"Save failed."}}async probeBedrock(t){const n=await this.sendAdminRequest("/api/bedrock/probe","POST",{region:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0,models:r.models}:{ok:!1,error:r.error||"Probe failed."}}async listTasks(){const t=await this.sendAdminRequest("/api/tasks","GET");if(!t)return null;const n=t.data??{};return{status:t.status,tasks:Array.isArray(n.tasks)?n.tasks:[]}}async startTask(t,n){const r=await this.sendAdminRequest("/api/tasks","POST",{args:t,timeoutMs:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok&&a.task?a:{ok:!1,error:a.error||"Start failed.",unauthorized:r.status===401,forbidden:r.status===403}}async getTask(t){const n=await this.sendAdminRequest(`/api/tasks/${encodeURIComponent(t)}`,"GET");if(!n)return null;const r=n.data??{};return{status:n.status,task:r.task??null}}async cancelTask(t){const n=await this.sendAdminRequest(`/api/tasks/${encodeURIComponent(t)}/cancel`,"POST");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Cancel failed.",unauthorized:n.status===401,forbidden:n.status===403}}subscribeTask(t,n){const r=en(),a=new EventSource(`${this.baseUrl}/api/tasks/${encodeURIComponent(t)}/events?token=${encodeURIComponent(r??"")}`);return a.addEventListener("log",s=>{var o;try{(o=n.onLog)==null||o.call(n,JSON.parse(s.data))}catch{}}),a.addEventListener("status",s=>{var o;try{const l=JSON.parse(s.data);l.status&&((o=n.onStatus)==null||o.call(n,l.status))}catch{}}),()=>a.close()}async getWhatsAppStatus(){const t=await this.sendAdminRequest("/api/whatsapp","GET");if(!t)return null;const n=t.data??{};return t.status===200&&n.ok&&n.status?{status:n.status,contacts:n.contacts??{}}:null}async startWhatsAppPair(t){const n=await this.sendAdminRequest("/api/whatsapp/pair","POST",{phone:t||void 0});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Pairing failed to start.",unauthorized:n.status===401,forbidden:n.status===403}}async cancelWhatsAppPair(){const t=await this.sendAdminRequest("/api/whatsapp/cancel","POST");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?n:{ok:!1,error:n.error||"Cancel failed.",unauthorized:t.status===401,forbidden:t.status===403}}async unpairWhatsApp(){const t=await this.sendAdminRequest("/api/whatsapp/unpair","POST");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?n:{ok:!1,error:n.error||"Unpair failed.",unauthorized:t.status===401,forbidden:t.status===403}}subscribeWhatsApp(t){const n=en(),r=new EventSource(`${this.baseUrl}/api/whatsapp/events?token=${encodeURIComponent(n??"")}`);return r.addEventListener("qr",a=>{var s;try{const o=JSON.parse(a.data);o.qr&&((s=t.onQr)==null||s.call(t,o.qr))}catch{}}),r.addEventListener("code",a=>{var s;try{const o=JSON.parse(a.data);o.code&&((s=t.onCode)==null||s.call(t,o.code))}catch{}}),r.addEventListener("status",a=>{var s;try{(s=t.onStatus)==null||s.call(t,JSON.parse(a.data))}catch{}}),()=>r.close()}async chatResolve(t){const n=en();try{const r=await fetch(`${this.baseUrl}/api/chat/resolve`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({message:t}),signal:AbortSignal.timeout(1e4)}),a=await r.json();return r.status===200&&a.ok&&Array.isArray(a.matches)?{ok:!0,matches:a.matches}:{ok:!1,matches:[],error:typeof a.error=="string"?a.error:"Resolve failed."}}catch{return{ok:!1,matches:[],error:"Could not reach the dashboard server."}}}async listRoutableModels(){const t=en();try{const n=await fetch(`${this.baseUrl}/api/chat/routable-models`,{headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(1e4)}),r=await n.json();return n.status===200&&r.ok&&Array.isArray(r.models)?r.models:[]}catch{return[]}}async listProjects(){const t=en();try{const n=await fetch(`${this.baseUrl}/api/projects`,{headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(1e4)}),r=await n.json();return n.status===200&&r.ok&&Array.isArray(r.projects)?r.projects:[]}catch{return[]}}async attachProject(t){const n=en();try{const r=await fetch(`${this.baseUrl}/api/projects/attach`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({path:t}),signal:AbortSignal.timeout(3e4)}),a=await r.json();return r.status===200&&a.ok&&a.project?{ok:!0,project:a.project}:{ok:!1,error:typeof a.error=="string"?a.error:"Attach failed."}}catch{return{ok:!1,error:"Could not reach the dashboard server."}}}async browseDirectories(t,n){const r=en();try{const a=new URLSearchParams;t&&a.set("path",t),n!=null&&n.showDrives&&a.set("showDrives","1");const s=a.toString()?`?${a.toString()}`:"",o=await fetch(`${this.baseUrl}/api/browse${s}`,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(1e4)}),l=await o.json();return o.status===200&&l.ok&&Array.isArray(l.entries)?{ok:!0,path:l.path??"",entries:l.entries,parent:l.parent??null,isProject:l.isProject??!1,drives:l.drives,breadcrumbs:l.breadcrumbs}:{ok:!1,path:"",entries:[],parent:null,isProject:!1,error:typeof l.error=="string"?l.error:"Browse failed."}}catch{return{ok:!1,path:"",entries:[],parent:null,isProject:!1,error:"Could not reach the dashboard server."}}}async resolveFolder(t,n){const r=en();try{const a=await fetch(this.baseUrl+"/api/browse/resolve-folder",{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:"Bearer "+r}:{}},body:JSON.stringify({name:t,subPath:n||""}),signal:AbortSignal.timeout(1e4)}),s=await a.json();return a.status===200&&s.ok&&s.path?{ok:!0,path:s.path}:{ok:!1,path:"",error:typeof s.error=="string"?s.error:"Could not resolve folder."}}catch{return{ok:!1,path:"",error:"Could not reach the dashboard server."}}}async listChatSessions(){const t=en();try{const n=await fetch(`${this.baseUrl}/api/sessions`,{headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(1e4)}),r=await n.json();return n.status===200&&r.ok&&Array.isArray(r.sessions)?r.sessions:[]}catch{return[]}}async deleteChatSession(t){const n=en();try{const r=await fetch(`${this.baseUrl}/api/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:n?{Authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(1e4)}),a=await r.json();return r.status===200&&a.ok?{ok:!0}:{ok:!1,error:a.error||"Could not delete the session."}}catch{return{ok:!1,error:"Network error — could not delete the session."}}}async renameChatSession(t,n){const r=en();try{const a=await fetch(`${this.baseUrl}/api/sessions/${encodeURIComponent(t)}/rename`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({title:n}),signal:AbortSignal.timeout(1e4)}),s=await a.json();return a.status===200&&s.ok?{ok:!0}:{ok:!1,error:s.error||"Could not rename the session."}}catch{return{ok:!1,error:"Network error — could not rename the session."}}}async getChatSession(t){const n=en();try{const r=await fetch(`${this.baseUrl}/api/sessions/${encodeURIComponent(t)}`,{headers:n?{Authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(1e4)}),a=await r.json();return r.status===200&&a.ok&&a.session?a.session:null}catch{return null}}async chatSend(t,n,r,a){const s=en();try{const o=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({sessionId:t,message:n,provider:r==null?void 0:r.provider,model:r==null?void 0:r.model,...(r==null?void 0:r.strict)===!0?{strict:!0}:{},projectPath:r==null?void 0:r.projectPath,attachments:r==null?void 0:r.attachments,...(r==null?void 0:r.worktree)===void 0?{}:{worktree:r.worktree},...(r==null?void 0:r.keepWorktree)===void 0?{}:{keepWorktree:r.keepWorktree},...(r==null?void 0:r.resume)===void 0?{}:{resume:r.resume}}),signal:a?AbortSignal.any([AbortSignal.timeout(3e5),a]):AbortSignal.timeout(3e5)}),l=await o.json();return o.status===200&&l.ok?{ok:!0,content:typeof l.content=="string"?l.content:"",followups:Array.isArray(l.followups)?l.followups:[],provider:typeof l.provider=="string"?l.provider:null,model:typeof l.model=="string"?l.model:null,...typeof l.routingNotice=="string"&&l.routingNotice?{routingNotice:l.routingNotice}:{},...typeof l.workspaceNotice=="string"&&l.workspaceNotice?{workspaceNotice:l.workspaceNotice}:{},...typeof l.workspacePath=="string"&&l.workspacePath?{workspacePath:l.workspacePath}:{},...typeof l.workspaceSource=="string"&&l.workspaceSource?{workspaceSource:l.workspaceSource}:{},generationFailed:l.generationFailed===!0,retryQueued:l.retryQueued===!0,...l.needsProject===!0?{needsProject:!0}:{},...l.refused===!0?{refused:!0}:{},...Q2(l.worktree)?{worktree:l.worktree}:{},...Z2(l.resume)?{resume:l.resume}:{},...Array.isArray(l.findings)?{findings:l.findings}:{},...J2(l.turnReport)?{turnReport:l.turnReport}:{}}:{ok:!1,error:typeof l.error=="string"?l.error:"The agent could not answer.",unauthorized:o.status===401,forbidden:o.status===403}}catch{return{ok:!1,error:"Could not reach the dashboard server, or the turn timed out."}}}async chatCancel(t){const n=await this.sendAdminRequest("/api/chat/cancel","POST",{sessionId:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0,cancelled:r.cancelled===!0}:{ok:!1,error:r.error||"Cancel failed."}}async chatReset(t){const n=await this.sendAdminRequest("/api/chat/reset","POST",{sessionId:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0}:{ok:!1,error:r.error||"Reset failed."}}async chatSupportBundle(t){var r,a,s;const n=en();try{const o=await fetch(`${this.baseUrl}/api/chat/${encodeURIComponent(t)}/support-bundle`,{method:"GET",headers:{...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(3e4)});if(o.status===200&&((r=o.headers.get("content-type"))!=null&&r.includes("application/zip"))){const c=await o.blob(),u=URL.createObjectURL(c),d=document.createElement("a");return d.href=u,d.download=((s=(a=o.headers.get("content-disposition"))==null?void 0:a.match(/filename="(.+)"/))==null?void 0:s[1])||"nuvira-support.zip",document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(u),{ok:!0}}return{ok:!1,error:(await o.json().catch(()=>({}))).error||"Could not build the support bundle."}}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Could not reach the dashboard server."}}}subscribeChat(t,n){const r=en(),a=new EventSource(`${this.baseUrl}/api/chat/${encodeURIComponent(t)}/events?token=${encodeURIComponent(r??"")}`);return a.addEventListener("progress",s=>{var o;try{const l=JSON.parse(s.data);l.line&&((o=n.onProgress)==null||o.call(n,l.line))}catch{}}),a.addEventListener("status",s=>{var o;try{const l=JSON.parse(s.data);l.status&&((o=n.onStatus)==null||o.call(n,l.status))}catch{}}),a.addEventListener("token",s=>{var o;try{const l=JSON.parse(s.data);typeof l.text=="string"&&l.text.length>0&&((o=n.onToken)==null||o.call(n,l.text))}catch{}}),a.addEventListener("tool",s=>{var o;try{const l=JSON.parse(s.data);l.tool&&(l.phase==="started"||l.phase==="called")&&((o=n.onTool)==null||o.call(n,{id:l.id||`call_${Math.random().toString(36).slice(2,8)}`,tool:l.tool,phase:l.phase,args:l.args,ok:l.ok,result:l.result,error:l.error,durationMs:l.durationMs}))}catch{}}),a.addEventListener("plan",s=>{var o;try{const l=JSON.parse(s.data);l.goal&&Array.isArray(l.steps)&&((o=n.onPlan)==null||o.call(n,{goal:l.goal,steps:l.steps,revision:l.revision??0}))}catch{}}),a.addEventListener("diff",s=>{var o;try{const l=JSON.parse(s.data);Array.isArray(l.files)&&((o=n.onDiff)==null||o.call(n,{files:l.files,summary:l.summary??""}))}catch{}}),a.addEventListener("finding",s=>{var o;try{const c=JSON.parse(s.data).finding;c&&typeof c.claim=="string"&&(c.verdict==="CONFIRMED"||c.verdict==="PLAUSIBLE")&&((o=n.onFinding)==null||o.call(n,{claim:c.claim,verdict:c.verdict,outcome:typeof c.outcome=="string"?c.outcome:"",evidence:Array.isArray(c.evidence)?c.evidence:[],source:typeof c.source=="string"?c.source:""}))}catch{}}),a.addEventListener("skill_draft",s=>{var o;try{const l=JSON.parse(s.data);l.name&&l.markdown&&((o=n.onSkillDraft)==null||o.call(n,{name:l.name,description:l.description??"",markdown:l.markdown,updatedAt:l.updatedAt??0}))}catch{}}),a.addEventListener("secret_request",s=>{var o;try{const l=JSON.parse(s.data);l.skillName&&Array.isArray(l.missing)&&((o=n.onSecretRequest)==null||o.call(n,{skillName:l.skillName,missing:l.missing,persisted:l.persisted??{}}))}catch{}}),a.addEventListener("execution_result",s=>{var o;try{const l=JSON.parse(s.data);l.skillName&&l.runtime!==void 0&&((o=n.onExecutionResult)==null||o.call(n,{skillName:l.skillName,runtime:l.runtime,success:l.success??!1,durationMs:l.durationMs??0,exitCode:l.exitCode??0,stdout:l.stdout??"",stderr:l.stderr??"",timestamp:l.timestamp??Date.now()}))}catch{}}),a.addEventListener("question",s=>{var o;try{const l=JSON.parse(s.data);l.questionId&&l.question&&((o=n.onQuestion)==null||o.call(n,{questionId:l.questionId,question:l.question,choices:l.choices??[],multiSelect:l.multiSelect===!0}))}catch{}}),()=>a.close()}async chatRespond(t,n,r={}){try{const s=await(await fetch(`${this.baseUrl}/api/chat/${encodeURIComponent(t)}/respond`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({questionId:n,...r})})).json();return{ok:s.ok===!0,error:s.error}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}async skillDraftAccept(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/drafts/${encodeURIComponent(t)}/accept`,{method:"POST",headers:{...yt()}})).json();return{ok:r.ok===!0,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async skillDraftReject(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/drafts/${encodeURIComponent(t)}`,{method:"DELETE",headers:{...yt()}})).json();return{ok:r.ok===!0,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async saveSecrets(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/secrets`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({vars:t})})).json();return{ok:r.ok===!0,error:r.error,saved:r.saved,refused:r.refused}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async fetchSkillEnv(){try{const t=await fetch(`${this.baseUrl}/api/skills/env`,{headers:{...yt()}}),n=await ot(t);return(n==null?void 0:n.vars)??[]}catch{return[]}}async deleteSkillEnvVar(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/env/delete`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})})).json();return{ok:r.ok===!0,removed:r.removed,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async testSkillEnvVar(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/env/test`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})})).json();return{ok:r.ok===!0,usable:r.usable,detail:r.detail,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async fetchProcessEnv(){try{const t=await fetch(`${this.baseUrl}/api/process-env`,{headers:{...yt()}}),n=await ot(t);return(n==null?void 0:n.vars)??[]}catch{return[]}}async fetchLimits(){try{const t=await fetch(`${this.baseUrl}/api/limits`),n=await ot(t);return!n||typeof n.attachmentMaxBytes!="number"||n.attachmentMaxBytes<=0?null:{attachmentMaxBytes:n.attachmentMaxBytes,extractMaxChars:typeof n.extractMaxChars=="number"?n.extractMaxChars:0}}catch{return null}}async fetchContinuity(){try{const t=await fetch(`${this.baseUrl}/api/continuity`,{headers:{...yt()}}),n=await ot(t);return!n||n.ok!==!0?null:{sessions:n.sessions??[],recall:n.recall??[],toggles:n.toggles??{sessionStore:!1,sessionRecall:!1}}}catch{return null}}async clearContinuity(t,n,r){try{const s=await(await fetch(`${this.baseUrl}/api/continuity/clear`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({target:t,...n?{id:n}:{},...r?{olderThanMs:r}:{}})})).json();return{ok:s.ok===!0,removed:s.removed,error:s.error}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}async fetchHistory(){try{const t=await fetch(`${this.baseUrl}/api/history`,{headers:{...yt()}});return await ot(t)}catch{return null}}async clearHistory(t,n={}){try{const a=await(await fetch(`${this.baseUrl}/api/history/clear`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({target:t,...n.id?{id:n.id}:{},...n.olderThanMs?{olderThanMs:n.olderThanMs}:{}})})).json();return{ok:a.ok===!0,removed:a.removed,error:a.error}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}}async fetchVerifyBacklog(){try{const t=await fetch(`${this.baseUrl}/api/models/verify-next`,{headers:{...yt()}});return await ot(t)}catch{return null}}async startVerifyBacklog(t){try{const n=await fetch(`${this.baseUrl}/api/models/verify-next`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({count:t})}),r=await ot(n);return r?{ok:r.ok===!0,error:r.error,refusal:r.refusal,state:r.state}:{ok:!1,error:"The dashboard server did not respond."}}catch(n){return{ok:!1,error:n instanceof Error?n.message:"Could not start the run."}}}async saveProcessEnvVar(t,n){try{const a=await(await fetch(`${this.baseUrl}/api/process-env`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t,value:n})})).json();return{ok:a.ok===!0,row:a.row,error:a.error,reason:a.reason}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}}async deleteProcessEnvVar(t){try{const r=await(await fetch(`${this.baseUrl}/api/process-env/delete`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})})).json();return{ok:r.ok===!0,removed:r.removed,row:r.row,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async fetchHooks(){try{const t=await fetch(`${this.baseUrl}/api/hooks`,{headers:{...yt()}}),n=await ot(t);return!n||!Array.isArray(n.hooks)?null:n}catch{return null}}async saveHooks(t){try{const n=await fetch(`${this.baseUrl}/api/hooks`,{method:"PUT",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({hooks:t})}),r=await n.json();return{ok:r.ok===!0,hooks:r.hooks,error:r.error,forbidden:n.status===403}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}}const K=new iB,au=["enterprise","neutral","pastel","executive","contrast"],Rp=["light","dark"],Zx=[100,112,125,150],rh={enterprise:"Enterprise",neutral:"Neutral",pastel:"Pastel",executive:"Executive",contrast:"High contrast"},CT="nuvira.dashboard.theme",rS={palette:"enterprise",mode:"dark",a11y:!1,fontScale:100};function Io(e,t){return e.includes(t)}function sB(){return typeof window>"u"||typeof window.matchMedia!="function"?null:window.matchMedia("(prefers-color-scheme: dark)").matches}function AT(){const e=sB();return e===null?{...rS}:{...rS,mode:e?"dark":"light"}}function TT(){const e=AT();if(typeof localStorage>"u")return e;let t;try{const a=localStorage.getItem(CT);if(!a)return e;t=JSON.parse(a)}catch{return e}if(typeof t!="object"||t===null)return e;const n=t,r=Io(Zx,n.fontScale)?n.fontScale:e.fontScale;return{palette:Io(au,n.palette)?n.palette:e.palette,mode:Io(Rp,n.mode)?n.mode:e.mode,a11y:typeof n.a11y=="boolean"?n.a11y:e.a11y,fontScale:r}}function OT(e){if(!(typeof localStorage>"u"))try{localStorage.setItem(CT,JSON.stringify(e))}catch{}}function Jx(e,t){const n=typeof document<"u"?document.documentElement:void 0;n&&(n.setAttribute("data-palette",e.palette),n.setAttribute("data-mode",e.mode),n.setAttribute("data-a11y",e.a11y?"on":"off"),n.setAttribute("data-font-scale",String(e.fontScale)),n.style.colorScheme=e.mode)}function oB(e,t){const n={palette:Io(au,t.palette)?t.palette:e.palette,mode:Io(Rp,t.mode)?t.mode:e.mode,a11y:t.a11y??e.a11y,fontScale:Io(Zx,t.fontScale)?t.fontScale:e.fontScale};return n.a11y||(n.fontScale=100),n}let gr=TT();const my=new Set;function PT(){for(const e of my)e()}function lB(e){return my.add(e),()=>{my.delete(e)}}function aS(){return gr}function zd(e){const t=oB(gr,e);t.palette===gr.palette&&t.mode===gr.mode&&t.a11y===gr.a11y&&t.fontScale===gr.fontScale||(gr=t,Jx(gr),OT(gr),PT())}function cB(){gr=AT(),Jx(gr),OT(gr),PT()}function uB(){return x.useSyncExternalStore(lB,aS,aS)}const iS={light:"Light",dark:"Dark"},sS={100:"100%",112:"112%",125:"125%",150:"150%"};function dB(){const e=uB(),[t,n]=x.useState(!1),r=x.useRef(null),a=x.useRef(null),s=x.useRef(null),o=x.useId(),l=`${o}-panel`;x.useEffect(()=>{if(!t)return;function u(f){var h;f.key==="Escape"&&(n(!1),(h=r.current)==null||h.focus())}function d(f){var p;const h=f.target;h&&((p=s.current)!=null&&p.contains(h))||n(!1)}return document.addEventListener("keydown",u),document.addEventListener("pointerdown",d),()=>{document.removeEventListener("keydown",u),document.removeEventListener("pointerdown",d)}},[t]),x.useEffect(()=>{var d,f,h;if(!t)return;(h=((d=a.current)==null?void 0:d.querySelector("input:checked"))??((f=a.current)==null?void 0:f.querySelector("input")))==null||h.focus()},[t]);const c=`${rh[e.palette]} palette, ${iS[e.mode].toLowerCase()} mode, text size ${sS[e.fontScale]}`+(e.a11y?", accessibility mode on":"");return i.jsxs("div",{className:"theme-switcher",ref:s,onBlur:u=>{const d=u.relatedTarget;d&&!u.currentTarget.contains(d)&&n(!1)},children:[i.jsxs("button",{type:"button",ref:r,className:"theme-trigger","aria-expanded":t,"aria-controls":t?l:void 0,onClick:()=>n(u=>!u),children:[i.jsx("span",{"aria-hidden":"true",children:"🎨"}),i.jsx("span",{children:"Appearance"})]}),t&&i.jsxs("div",{className:"theme-panel",id:l,ref:a,children:[i.jsxs("fieldset",{className:"theme-group",children:[i.jsx("legend",{className:"theme-group-label",children:"Palette"}),au.map(u=>i.jsxs("label",{className:"theme-option",children:[i.jsx("input",{type:"radio",name:`${o}-palette`,value:u,checked:e.palette===u,onChange:()=>zd({palette:u})}),i.jsx("span",{className:"theme-swatch","data-swatch":u,"aria-hidden":"true"}),i.jsx("span",{className:"theme-option-label",children:rh[u]})]},u))]}),i.jsxs("fieldset",{className:"theme-group",children:[i.jsx("legend",{className:"theme-group-label",children:"Mode"}),Rp.map(u=>i.jsxs("label",{className:"theme-option",children:[i.jsx("input",{type:"radio",name:`${o}-mode`,value:u,checked:e.mode===u,onChange:()=>zd({mode:u})}),i.jsx("span",{className:"theme-option-label",children:iS[u]})]},u))]}),i.jsxs("fieldset",{className:"theme-group",children:[i.jsx("legend",{className:"theme-group-label",children:"Text size"}),Zx.map(u=>i.jsxs("label",{className:"theme-option",children:[i.jsx("input",{type:"radio",name:`${o}-scale`,value:u,checked:e.fontScale===u,onChange:()=>zd({fontScale:u,a11y:e.a11y||u!==100})}),i.jsx("span",{className:"theme-option-label",children:sS[u]})]},u)),!e.a11y&&i.jsx("p",{className:"theme-hint",children:"A larger size turns on accessibility mode, which is what defines it."})]}),i.jsxs("div",{className:"theme-group",children:[i.jsxs("label",{className:"theme-switch",children:[i.jsx("input",{type:"checkbox",checked:e.a11y,onChange:u=>zd({a11y:u.target.checked})}),i.jsx("span",{className:"theme-switch-track","aria-hidden":"true"}),i.jsx("span",{className:"theme-option-label",children:"Accessibility mode"})]}),i.jsx("p",{className:"theme-hint",children:"Larger targets, stronger borders and no motion. Off by default so it never changes the look for anyone who does not need it."})]}),i.jsx("button",{type:"button",className:"theme-reset",onClick:cB,children:"Reset to system default"}),i.jsx("p",{className:"sr-only",role:"status",children:c})]})]})}function fB(){const[e,t]=x.useState(null),[n,r]=x.useState(!1),[a,s]=x.useState(""),[o,l]=x.useState(""),[c,u]=x.useState(!1),[d,f]=x.useState(null),h=x.useRef(null),p=x.useCallback(()=>{K.fetchAdminAuthStatus().then(w=>t(w))},[]);x.useEffect(()=>{p()},[p]),x.useEffect(()=>{if(!n)return;function w(k){h.current&&!h.current.contains(k.target)&&r(!1)}function j(k){k.key==="Escape"&&r(!1)}return document.addEventListener("mousedown",w),document.addEventListener("keydown",j),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",j)}},[n]);const m=(e==null?void 0:e.authenticated)===!0,g=(e==null?void 0:e.configured)===!0,y=async w=>{w.preventDefault(),u(!0),f(null);const j=g?await K.adminLogin(a,o):await K.adminSetup(a,o);j.ok?(s(""),l(""),r(!1),p()):f(j.error||(g?"Login failed.":"Setup failed.")),u(!1)},v=async()=>{r(!1),await K.adminLogout(),p()},S=e?m?`👤 ${e.user||"account"}${e.role?` · ${e.role}`:""}`:"👤 Sign in":"👤 Account";return i.jsxs("div",{className:"topbar-account",ref:h,children:[i.jsx("button",{type:"button",className:"topbar-action","aria-haspopup":"menu","aria-expanded":n,onClick:()=>r(w=>!w),children:S}),n?i.jsx("div",{className:"topbar-account-menu",role:"menu",children:m?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"topbar-account-user",children:[i.jsx("span",{children:(e==null?void 0:e.user)||"account"}),e!=null&&e.role?i.jsx("span",{className:`admin-role-badge admin-role-${e.role}`,children:e.role}):null]}),e!=null&&e.mustChangePassword?i.jsx("p",{className:"topbar-account-hint",children:"Still on the first-run password — change it on the Admin page before writes will work."}):null,i.jsx("button",{type:"button",className:"topbar-account-item",onClick:()=>void v(),children:"🚪 Log out"})]}):i.jsxs("form",{className:"topbar-account-form",onSubmit:y,children:[i.jsx("p",{className:"topbar-account-title",children:g?"Sign in":"Create the first admin"}),i.jsxs("label",{children:[i.jsx("span",{children:"Username"}),i.jsx("input",{type:"text",value:a,onChange:w=>s(w.target.value),autoComplete:"username",placeholder:"admin"})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Password"}),i.jsx("input",{type:"password",value:o,onChange:w=>l(w.target.value),autoComplete:g?"current-password":"new-password",placeholder:"••••••••"})]}),d?i.jsx("div",{className:"admin-error",children:d}):null,i.jsx("button",{type:"submit",className:"admin-refresh-btn",disabled:c||!a||!o,children:c?"⏳ …":g?"🔐 Sign in":"🔐 Create admin"}),g?null:i.jsx("p",{className:"topbar-account-hint",children:"The first user is always an admin."})]})}):null]})}const RT=[{group:"General",items:[{keys:["?"],description:"Show the shortcut cheatsheet"},{keys:["F1"],description:"Open the Help page"},{keys:["Esc"],description:"Close a dialog or panel"},{keys:["g","c"],description:"Go to Chat"},{keys:["g","o"],description:"Go to Overview"},{keys:["g","t"],description:"Go to Tasks"},{keys:["g","m"],description:"Go to Models"},{keys:["g","s"],description:"Go to System"},{keys:["g","h"],description:"Go to Agent Hub"}]},{group:"Navigation",items:[{keys:["/"],description:"Focus the navigation filter"},{keys:["["],description:"Collapse / expand the navigation drawer"}]}],hB={c:"/chat",o:"/overview",t:"/tasks",m:"/models",s:"/system",h:"/hub"};function pB(e){var a;const t=e;if(!t||typeof t.tagName!="string")return!1;if(t.isContentEditable)return!0;const n=(a=t.getAttribute)==null?void 0:a.call(t,"contenteditable");if(n!=null&&n!=="false")return!0;const r=t.tagName.toLowerCase();return r==="input"||r==="textarea"||r==="select"}function mB({open:e,onClose:t}){const n=x.useId(),r=x.useRef(null),a=x.useRef(null);return x.useEffect(()=>{var l;if(!e)return;a.current=document.activeElement;const s=()=>{var c;return Array.from(((c=r.current)==null?void 0:c.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))??[])};(l=s()[0])==null||l.focus();function o(c){if(c.key==="Escape"){c.stopPropagation(),t();return}if(c.key!=="Tab")return;const u=s();if(u.length===0)return;const d=u[0],f=u[u.length-1];c.shiftKey&&document.activeElement===d?(c.preventDefault(),f.focus()):!c.shiftKey&&document.activeElement===f&&(c.preventDefault(),d.focus())}return document.addEventListener("keydown",o),()=>{var c;document.removeEventListener("keydown",o),(c=a.current)==null||c.focus()}},[e,t]),e?i.jsx("div",{className:"modal-scrim",onClick:t,children:i.jsxs("div",{className:"shortcuts-dialog",role:"dialog","aria-modal":"true","aria-labelledby":n,ref:r,onClick:s=>s.stopPropagation(),children:[i.jsxs("div",{className:"shortcuts-head",children:[i.jsx("h2",{className:"shortcuts-title",id:n,children:"⌨️ Keyboard shortcuts"}),i.jsx("button",{type:"button",className:"btn-secondary",onClick:t,"aria-label":"Close keyboard shortcuts",children:"✕ Close"})]}),RT.map(s=>i.jsxs("section",{className:"shortcuts-group",children:[i.jsx("h3",{className:"shortcuts-group-title",children:s.group}),i.jsx("dl",{className:"shortcuts-list",children:s.items.map(o=>i.jsxs("div",{className:"shortcuts-row",children:[i.jsx("dt",{className:"shortcuts-keys",children:o.keys.map(l=>i.jsx("kbd",{className:"shortcuts-key",children:l},l))}),i.jsx("dd",{className:"shortcuts-description",children:o.description})]},o.description))})]},s.group)),i.jsxs("p",{className:"shortcuts-note",children:["Shortcuts are ignored while you are typing, so ",i.jsx("kbd",{className:"shortcuts-key",children:"?"})," in a question stays a question mark."]})]})}):null}const MT=[{path:"/overview",label:"Overview",icon:"📊"},{path:"/tasks",label:"Tasks",icon:"🚀"},{path:"/models",label:"Models",icon:"🧠"},{path:"/system",label:"System",icon:"⚙️"},{path:"/help",label:"Help",icon:"❓"}],gy=[{label:"Agent Management",items:[{path:"/chat",label:"Chat",icon:"💬"},{path:"/hub",label:"Agent Hub",icon:"🧰"},{path:"/capabilities",label:"Capabilities",icon:"📋"},{path:"/dag",label:"Execution",icon:"🔀"},{path:"/routing",label:"Routing",icon:"🤖"},{path:"/requests",label:"Requests",icon:"📨"},{path:"/hooks",label:"Hooks",icon:"🪝"}]},{label:"Analysis & Monitoring",items:[{path:"/traces",label:"Traces",icon:"🔍"},{path:"/evals",label:"Evals",icon:"🏆"},{path:"/benchmarks",label:"Benchmarks",icon:"📈"},{path:"/costs",label:"Costs",icon:"💰"}]},{label:"Resources",items:[{path:"/memory",label:"Memory",icon:"💾"},{path:"/knowledge",label:"Knowledge",icon:"📚"},{path:"/history",label:"History",icon:"📝"},{path:"/decisions",label:"Decisions",icon:"🧭"},{path:"/env",label:"Env Config",icon:"🔐"},{path:"/process-env",label:"Process Env",icon:"🌱"}]},{label:"Integrations",items:[{path:"/platforms",label:"Platforms",icon:"🌐"},{path:"/gateway",label:"Gateway",icon:"📡"},{path:"/contacts",label:"Contacts",icon:"📇"},{path:"/bedrock",label:"Bedrock",icon:"🪨"}]},{label:"Runtime",items:[{path:"/models/timeline",label:"Timeline",icon:"📅"},{path:"/executions",label:"Executions",icon:"📜"},{path:"/admin",label:"Admin",icon:"🛠️"}]}];function gB(e){const t=e.trim().toLowerCase();return t?gy.map(n=>n.label.toLowerCase().includes(t)?n:{...n,items:n.items.filter(r=>r.label.toLowerCase().includes(t))}).filter(n=>n.items.length>0):gy}function vB({children:e,connected:t,lastUpdated:n,onRefresh:r,refreshing:a=!1}){const[s,o]=x.useState(!1),[l,c]=x.useState(""),[u,d]=x.useState(!1),f=x.useRef(null),h=x.useRef(null),p=x.useRef(0),m=x.useId(),g=Ri(),y=Qx(),v=t?"connected":"reconnecting",S=t?"Connected":"Reconnecting...",w=gB(l),j=()=>o(!1);return x.useEffect(()=>{function k(b){var N,_;if(!(b.metaKey||b.ctrlKey||b.altKey)&&!pB(b.target)){if(b.key==="Escape"){if(u)return;s&&(o(!1),(N=f.current)==null||N.focus());return}if(b.key==="?"){b.preventDefault(),d(!0);return}if(b.key==="F1"){b.preventDefault(),y("/help");return}if(b.key==="/"){b.preventDefault(),(_=h.current)==null||_.focus();return}if(b.key==="["){b.preventDefault(),o(T=>!T);return}if(b.key==="g"){p.current=Date.now();return}if(Date.now()-p.current<1500){const T=hB[b.key.toLowerCase()];p.current=0,T&&(b.preventDefault(),y(T))}}}return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[s,u,y]),x.useEffect(()=>{var k;s&&((k=h.current)==null||k.focus())},[s]),x.useEffect(()=>{j()},[g.pathname]),i.jsxs("div",{className:"layout",children:[i.jsxs("header",{className:"topbar",children:[i.jsx("button",{type:"button",ref:f,className:"topbar-menu","aria-label":"Toggle navigation","aria-controls":"app-nav","aria-expanded":s,onClick:()=>o(k=>!k),children:i.jsx("span",{"aria-hidden":"true",children:"☰"})}),i.jsxs("div",{className:"topbar-brand",children:[i.jsx("span",{className:"topbar-logo","aria-hidden":"true",children:"🤖"}),i.jsx("span",{className:"topbar-title",children:"Agent-Nuvira"})]}),i.jsx("nav",{className:"primary-nav","aria-label":"Primary",children:MT.map(k=>i.jsxs(tS,{to:k.path,end:!0,className:({isActive:b})=>`primary-link${b?" active":""}`,children:[i.jsx("span",{"aria-hidden":"true",children:k.icon})," ",k.label]},k.path))}),i.jsxs("div",{className:"topbar-actions",children:[i.jsxs("button",{type:"button",className:"topbar-action",onClick:r,disabled:a,"aria-busy":a,children:[i.jsx("span",{"aria-hidden":"true",children:"⟳"})," ",a?"Refreshing…":"Refresh"]}),i.jsxs("button",{type:"button",className:"topbar-action","aria-haspopup":"dialog","aria-expanded":u,onClick:()=>d(!0),children:[i.jsx("span",{"aria-hidden":"true",children:"⌨️"})," Shortcuts"]}),i.jsx(dB,{}),i.jsxs("a",{className:"topbar-action",href:"https://www.agent-nuvira.com",target:"_blank",rel:"noopener noreferrer",title:"Agent-Nuvira website — capabilities, commands, docs, setup",children:[i.jsx("span",{"aria-hidden":"true",children:"🌐"})," Website"]}),i.jsx(fB,{})]})]}),i.jsxs("div",{className:"layout-body",children:[s&&i.jsx("div",{className:"nav-scrim",onClick:j,"aria-hidden":"true"}),i.jsxs("nav",{className:`nav${s?" open":""}`,id:"app-nav","aria-label":"Sections",children:[i.jsxs("div",{className:"nav-search",children:[i.jsx("label",{className:"sr-only",htmlFor:m,children:"Filter navigation"}),i.jsx("input",{id:m,ref:h,type:"search",className:"nav-search-input",placeholder:"Search",value:l,onChange:k=>c(k.target.value)})]}),i.jsxs("div",{className:"nav-links",children:[w.map(k=>i.jsxs("section",{className:"nav-group",children:[i.jsx("h2",{className:"nav-group-title",children:k.label}),k.items.map(b=>i.jsxs(tS,{to:b.path,end:b.path==="/",className:({isActive:N})=>`nav-link${N?" active":""}`,children:[i.jsx("span",{className:"nav-icon","aria-hidden":"true",children:b.icon}),b.label]},b.path))]},k.label)),w.length===0&&i.jsxs("p",{className:"nav-empty",children:["No sections match “",l,"”."]})]}),i.jsxs("div",{className:"nav-footer",children:[i.jsx("span",{className:`status-dot ${v}`}),i.jsx("span",{className:"status-text",children:S}),i.jsx("span",{className:"last-updated",children:n})]})]}),i.jsx("main",{className:"main",children:e})]}),i.jsx(mB,{open:u,onClose:()=>d(!1)})]})}function IT(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var a=e.length;for(t=0;t<a;t++)e[t]&&(n=IT(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Qe(){for(var e,t,n=0,r="",a=arguments.length;n<a;n++)(e=arguments[n])&&(t=IT(e))&&(r&&(r+=" "),r+=t);return r}var yB=Array.isArray,Hn=yB,bB=typeof li=="object"&&li&&li.Object===Object&&li,$T=bB,xB=$T,wB=typeof self=="object"&&self&&self.Object===Object&&self,kB=xB||wB||Function("return this")(),pa=kB,SB=pa,jB=SB.Symbol,Xu=jB,oS=Xu,LT=Object.prototype,NB=LT.hasOwnProperty,EB=LT.toString,tc=oS?oS.toStringTag:void 0;function _B(e){var t=NB.call(e,tc),n=e[tc];try{e[tc]=void 0;var r=!0}catch{}var a=EB.call(e);return r&&(t?e[tc]=n:delete e[tc]),a}var CB=_B,AB=Object.prototype,TB=AB.toString;function OB(e){return TB.call(e)}var PB=OB,lS=Xu,RB=CB,MB=PB,IB="[object Null]",$B="[object Undefined]",cS=lS?lS.toStringTag:void 0;function LB(e){return e==null?e===void 0?$B:IB:cS&&cS in Object(e)?RB(e):MB(e)}var Ba=LB;function DB(e){return e!=null&&typeof e=="object"}var za=DB,BB=Ba,zB=za,FB="[object Symbol]";function UB(e){return typeof e=="symbol"||zB(e)&&BB(e)==FB}var kl=UB,WB=Hn,HB=kl,GB=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,qB=/^\w*$/;function KB(e,t){if(WB(e))return!1;var n=typeof e;return n=="number"||n=="symbol"||n=="boolean"||e==null||HB(e)?!0:qB.test(e)||!GB.test(e)||t!=null&&e in Object(t)}var ew=KB;function VB(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Mi=VB;const Sl=tt(Mi);var YB=Ba,XB=Mi,QB="[object AsyncFunction]",ZB="[object Function]",JB="[object GeneratorFunction]",ez="[object Proxy]";function tz(e){if(!XB(e))return!1;var t=YB(e);return t==ZB||t==JB||t==QB||t==ez}var tw=tz;const De=tt(tw);var nz=pa,rz=nz["__core-js_shared__"],az=rz,og=az,uS=function(){var e=/[^.]+$/.exec(og&&og.keys&&og.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function iz(e){return!!uS&&uS in e}var sz=iz,oz=Function.prototype,lz=oz.toString;function cz(e){if(e!=null){try{return lz.call(e)}catch{}try{return e+""}catch{}}return""}var DT=cz,uz=tw,dz=sz,fz=Mi,hz=DT,pz=/[\\^$.*+?()[\]{}|]/g,mz=/^\[object .+?Constructor\]$/,gz=Function.prototype,vz=Object.prototype,yz=gz.toString,bz=vz.hasOwnProperty,xz=RegExp("^"+yz.call(bz).replace(pz,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function wz(e){if(!fz(e)||dz(e))return!1;var t=uz(e)?xz:mz;return t.test(hz(e))}var kz=wz;function Sz(e,t){return e==null?void 0:e[t]}var jz=Sz,Nz=kz,Ez=jz;function _z(e,t){var n=Ez(e,t);return Nz(n)?n:void 0}var Us=_z,Cz=Us,Az=Cz(Object,"create"),Mp=Az,dS=Mp;function Tz(){this.__data__=dS?dS(null):{},this.size=0}var Oz=Tz;function Pz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Rz=Pz,Mz=Mp,Iz="__lodash_hash_undefined__",$z=Object.prototype,Lz=$z.hasOwnProperty;function Dz(e){var t=this.__data__;if(Mz){var n=t[e];return n===Iz?void 0:n}return Lz.call(t,e)?t[e]:void 0}var Bz=Dz,zz=Mp,Fz=Object.prototype,Uz=Fz.hasOwnProperty;function Wz(e){var t=this.__data__;return zz?t[e]!==void 0:Uz.call(t,e)}var Hz=Wz,Gz=Mp,qz="__lodash_hash_undefined__";function Kz(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Gz&&t===void 0?qz:t,this}var Vz=Kz,Yz=Oz,Xz=Rz,Qz=Bz,Zz=Hz,Jz=Vz;function jl(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}jl.prototype.clear=Yz;jl.prototype.delete=Xz;jl.prototype.get=Qz;jl.prototype.has=Zz;jl.prototype.set=Jz;var eF=jl;function tF(){this.__data__=[],this.size=0}var nF=tF;function rF(e,t){return e===t||e!==e&&t!==t}var nw=rF,aF=nw;function iF(e,t){for(var n=e.length;n--;)if(aF(e[n][0],t))return n;return-1}var Ip=iF,sF=Ip,oF=Array.prototype,lF=oF.splice;function cF(e){var t=this.__data__,n=sF(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():lF.call(t,n,1),--this.size,!0}var uF=cF,dF=Ip;function fF(e){var t=this.__data__,n=dF(t,e);return n<0?void 0:t[n][1]}var hF=fF,pF=Ip;function mF(e){return pF(this.__data__,e)>-1}var gF=mF,vF=Ip;function yF(e,t){var n=this.__data__,r=vF(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var bF=yF,xF=nF,wF=uF,kF=hF,SF=gF,jF=bF;function Nl(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Nl.prototype.clear=xF;Nl.prototype.delete=wF;Nl.prototype.get=kF;Nl.prototype.has=SF;Nl.prototype.set=jF;var $p=Nl,NF=Us,EF=pa,_F=NF(EF,"Map"),rw=_F,fS=eF,CF=$p,AF=rw;function TF(){this.size=0,this.__data__={hash:new fS,map:new(AF||CF),string:new fS}}var OF=TF;function PF(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var RF=PF,MF=RF;function IF(e,t){var n=e.__data__;return MF(t)?n[typeof t=="string"?"string":"hash"]:n.map}var Lp=IF,$F=Lp;function LF(e){var t=$F(this,e).delete(e);return this.size-=t?1:0,t}var DF=LF,BF=Lp;function zF(e){return BF(this,e).get(e)}var FF=zF,UF=Lp;function WF(e){return UF(this,e).has(e)}var HF=WF,GF=Lp;function qF(e,t){var n=GF(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var KF=qF,VF=OF,YF=DF,XF=FF,QF=HF,ZF=KF;function El(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}El.prototype.clear=VF;El.prototype.delete=YF;El.prototype.get=XF;El.prototype.has=QF;El.prototype.set=ZF;var aw=El,BT=aw,JF="Expected a function";function iw(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(JF);var n=function(){var r=arguments,a=t?t.apply(this,r):r[0],s=n.cache;if(s.has(a))return s.get(a);var o=e.apply(this,r);return n.cache=s.set(a,o)||s,o};return n.cache=new(iw.Cache||BT),n}iw.Cache=BT;var zT=iw;const eU=tt(zT);var tU=zT,nU=500;function rU(e){var t=tU(e,function(r){return n.size===nU&&n.clear(),r}),n=t.cache;return t}var aU=rU,iU=aU,sU=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,oU=/\\(\\)?/g,lU=iU(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(sU,function(n,r,a,s){t.push(a?s.replace(oU,"$1"):r||n)}),t}),cU=lU;function uU(e,t){for(var n=-1,r=e==null?0:e.length,a=Array(r);++n<r;)a[n]=t(e[n],n,e);return a}var sw=uU,hS=Xu,dU=sw,fU=Hn,hU=kl,pS=hS?hS.prototype:void 0,mS=pS?pS.toString:void 0;function FT(e){if(typeof e=="string")return e;if(fU(e))return dU(e,FT)+"";if(hU(e))return mS?mS.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var pU=FT,mU=pU;function gU(e){return e==null?"":mU(e)}var UT=gU,vU=Hn,yU=ew,bU=cU,xU=UT;function wU(e,t){return vU(e)?e:yU(e,t)?[e]:bU(xU(e))}var WT=wU,kU=kl;function SU(e){if(typeof e=="string"||kU(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var Dp=SU,jU=WT,NU=Dp;function EU(e,t){t=jU(t,e);for(var n=0,r=t.length;e!=null&&n<r;)e=e[NU(t[n++])];return n&&n==r?e:void 0}var ow=EU,_U=ow;function CU(e,t,n){var r=e==null?void 0:_U(e,t);return r===void 0?n:r}var HT=CU;const Sr=tt(HT);function AU(e){return e==null}var TU=AU;const Ze=tt(TU);var OU=Ba,PU=Hn,RU=za,MU="[object String]";function IU(e){return typeof e=="string"||!PU(e)&&RU(e)&&OU(e)==MU}var $U=IU;const Ms=tt($U);var GT={exports:{}},st={};/**
67
+ */function nh(){return nh=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},nh.apply(null,arguments)}function ET(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function D2(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function B2(e,t){return e.button===0&&(!t||t==="_self")&&!D2(e)}const z2=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],F2=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],U2="6";try{window.__reactRouterVersion=U2}catch{}const W2=x.createContext({isTransitioning:!1}),H2="startTransition",eS=$$[H2];function G2(e){let{basename:t,children:n,future:r,window:a}=e,s=x.useRef();s.current==null&&(s.current=VD({window:a,v5Compat:!0}));let o=s.current,[l,c]=x.useState({action:o.action,location:o.location}),{v7_startTransition:u}=r||{},d=x.useCallback(f=>{u&&eS?eS(()=>c(f)):c(f)},[c,u]);return x.useLayoutEffect(()=>o.listen(d),[o,d]),x.useEffect(()=>I2(r),[r]),x.createElement($2,{basename:t,children:n,location:l.location,navigationType:l.action,navigator:o,future:r})}const q2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",K2=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,rn=x.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:s,replace:o,state:l,target:c,to:u,preventScrollReset:d,viewTransition:f}=t,h=ET(t,z2),{basename:p}=x.useContext(Da),m,g=!1;if(typeof u=="string"&&K2.test(u)&&(m=u,q2))try{let w=new URL(window.location.href),j=u.startsWith("//")?new URL(w.protocol+u):new URL(u),k=Ko(j.pathname,p);j.origin===w.origin&&k!=null?u=k+j.search+j.hash:g=!0}catch{}let y=x2(u,{relative:a}),v=Y2(u,{replace:o,state:l,target:c,preventScrollReset:d,relative:a,viewTransition:f});function S(w){r&&r(w),w.defaultPrevented||v(w)}return x.createElement("a",nh({},h,{href:m||y,onClick:g||s?r:S,ref:n,target:c}))}),tS=x.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:s="",end:o=!1,style:l,to:c,viewTransition:u,children:d}=t,f=ET(t,F2),h=Pp(c,{relative:f.relative}),p=Ri(),m=x.useContext(xT),{navigator:g,basename:y}=x.useContext(Da),v=m!=null&&X2(h)&&u===!0,S=g.encodeLocation?g.encodeLocation(h).pathname:h.pathname,w=p.pathname,j=m&&m.navigation&&m.navigation.location?m.navigation.location.pathname:null;a||(w=w.toLowerCase(),j=j?j.toLowerCase():null,S=S.toLowerCase()),j&&y&&(j=Ko(j,y)||j);const k=S!=="/"&&S.endsWith("/")?S.length-1:S.length;let b=w===S||!o&&w.startsWith(S)&&w.charAt(k)==="/",N=j!=null&&(j===S||!o&&j.startsWith(S)&&j.charAt(S.length)==="/"),_={isActive:b,isPending:N,isTransitioning:v},T=b?r:void 0,A;typeof s=="function"?A=s(_):A=[s,b?"active":null,N?"pending":null,v?"transitioning":null].filter(Boolean).join(" ");let O=typeof l=="function"?l(_):l;return x.createElement(rn,nh({},f,{"aria-current":T,className:A,ref:n,style:O,to:c,viewTransition:u}),typeof d=="function"?d(_):d)});var dy;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(dy||(dy={}));var nS;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(nS||(nS={}));function V2(e){let t=x.useContext(Tp);return t||At(!1),t}function Y2(e,t){let{target:n,replace:r,state:a,preventScrollReset:s,relative:o,viewTransition:l}=t===void 0?{}:t,c=Qx(),u=Ri(),d=Pp(e,{relative:o});return x.useCallback(f=>{if(B2(f,n)){f.preventDefault();let h=r!==void 0?r:th(u)===th(d);c(e,{replace:h,state:a,preventScrollReset:s,relative:o,viewTransition:l})}},[u,c,d,r,a,n,e,s,o,l])}function X2(e,t){t===void 0&&(t={});let n=x.useContext(W2);n==null&&At(!1);let{basename:r}=V2(dy.useViewTransitionState),a=Pp(e,{relative:t.relative});if(!n.isTransitioning)return!1;let s=Ko(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Ko(n.nextLocation.pathname,r)||n.nextLocation.pathname;return cy(a.pathname,o)!=null||cy(a.pathname,s)!=null}async function ot(e){if(!e.ok)return null;const t=e.headers.get("content-type")||"";if(!t.includes("application/json")&&!t.includes("text/json"))return t.includes("text/html")&&console.warn(`[dashboard] GET ${e.url||"/api/*"} returned HTML (${e.status}) instead of JSON — the dashboard server may be an older version. Stop it and start it again (agent-nuvira dashboard stop, or Ctrl+C in its terminal).`),null;try{return await e.json()}catch{return null}}const No="buff-dashboard-admin-token";function _T(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}return null}function Q2(e){if(!e||typeof e!="object")return!1;const t=e,n=t.diff;return typeof t.dir=="string"&&typeof t.base=="string"&&typeof t.removed=="boolean"&&!!n&&typeof n=="object"&&Array.isArray(n.files)&&n.files.every(r=>typeof r=="string")&&typeof n.summary=="string"&&!!n.payload&&typeof n.payload=="object"&&typeof n.payload.summary=="string"&&Array.isArray(n.payload.files)&&n.payload.files.every(r=>!!r&&typeof r.path=="string"&&typeof r.body=="string")}function Z2(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.replayed=="number"&&typeof t.modelCalls=="number"&&typeof t.saved=="boolean"&&typeof t.notice=="string"&&(t.callsAvoided===void 0||typeof t.callsAvoided=="number")}function J2(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.goal=="string"&&typeof t.planned=="boolean"&&Array.isArray(t.steps)&&!!t.stepCounts&&typeof t.stepCounts=="object"&&typeof t.stepCounts.total=="number"&&typeof t.verification=="string"&&["verified","unverified","blocked","not-applicable","delivered-and-read-back"].includes(t.verification)&&(t.summary===null||typeof t.summary=="string")&&Array.isArray(t.changedPaths)&&!!t.flags&&typeof t.flags=="object"}const fy=new Map;function eB(){const e=_T();if(e)try{const t=e.getItem(No);if(t)return t}catch{}return fy.get(No)??null}function tB(e){const t=_T();if(t)try{e?t.setItem(No,e):t.removeItem(No);return}catch{}e?fy.set(No,e):fy.delete(No)}function en(){return eB()}let hy=0;const py=new Set;function nB(){return hy}function rB(e){return py.add(e),()=>{py.delete(e)}}function aB(){hy+=1;for(const e of py)try{e(hy)}catch{}}function sg(e){tB(e),aB()}function yt(){const e=en();return e?{Authorization:`Bearer ${e}`}:{}}class iB{constructor(t=""){Jr(this,"sse",null);Jr(this,"listeners",new Set);Jr(this,"connectionListeners",new Set);Jr(this,"dagListeners",new Set);Jr(this,"typingListeners",new Set);Jr(this,"chatRetryListeners",new Set);Jr(this,"reconnectTimer",null);Jr(this,"baseUrl");Jr(this,"lastData",null);this.baseUrl=t}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}onConnectionChange(t){return this.connectionListeners.add(t),()=>this.connectionListeners.delete(t)}onDAGEvent(t){return this.dagListeners.add(t),()=>this.dagListeners.delete(t)}onTypingEvent(t){return this.typingListeners.add(t),()=>this.typingListeners.delete(t)}onChatRetryEvent(t){return this.chatRetryListeners.add(t),()=>this.chatRetryListeners.delete(t)}connect(){this.sse||(this.sse=new EventSource(`${this.baseUrl}/api/sse`),this.sse.addEventListener("init",t=>{try{const n=JSON.parse(t.data);this.lastData=n,this.notify(n),this.notifyConnection(!0)}catch(n){console.error("Failed to parse SSE init data:",n)}}),this.sse.addEventListener("refresh",t=>{try{const n=JSON.parse(t.data);this.lastData=n,this.notify(n),this.notifyConnection(!0)}catch(n){console.error("Failed to parse SSE refresh data:",n)}}),this.sse.addEventListener("dag",t=>{try{const n=JSON.parse(t.data);if(this.notifyDAG(n),this.lastData){const r={...this.lastData,dag:n};this.lastData=r,this.notify(r)}}catch(n){console.error("Failed to parse SSE dag event:",n)}}),this.sse.addEventListener("quota",t=>{try{const n=JSON.parse(t.data);if(this.lastData&&n.quota){const r={...this.lastData,routing:{...this.lastData.routing||{},quota:n.quota},serverTime:n.serverTime||this.lastData.serverTime};this.lastData=r,this.notify(r)}}catch(n){console.error("Failed to parse SSE quota event:",n)}}),this.sse.addEventListener("conversation",t=>{try{const n=JSON.parse(t.data);if(this.lastData&&n.conversations){const r={...this.lastData,conversations:{total:n.total??n.conversations.length,recent:n.conversations},serverTime:n.serverTime||this.lastData.serverTime};this.lastData=r,this.notify(r)}}catch(n){console.error("Failed to parse SSE conversation event:",n)}}),this.sse.addEventListener("typing",t=>{try{const n=JSON.parse(t.data);for(const r of this.typingListeners)try{r(n)}catch{}}catch(n){console.error("Failed to parse SSE typing event:",n)}}),this.sse.addEventListener("chat-retry",t=>{try{const n=JSON.parse(t.data);if(!n||typeof n.sessionId!="string"||typeof n.content!="string")return;for(const r of this.chatRetryListeners)try{r(n)}catch{}}catch(n){console.error("Failed to parse SSE chat-retry event:",n)}}),this.sse.onerror=()=>{this.notifyConnection(!1),this.disconnect(),this.reconnect()},this.sse.onopen=()=>{this.notifyConnection(!0)})}disconnect(){this.sse&&(this.sse.close(),this.sse=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}reconnect(){this.reconnectTimer=setTimeout(()=>{this.connect()},3e3)}notify(t){this.listeners.forEach(n=>n(t))}notifyDAG(t){this.dagListeners.forEach(n=>n(t))}notifyConnection(t){this.connectionListeners.forEach(n=>n(t))}async fetchAll(){try{const t=await fetch(`${this.baseUrl}/api/all`),n=await ot(t);return n?(this.lastData=n,n):null}catch{return null}}async fetchExecutionAudit(t){try{const n=new URLSearchParams;t!=null&&t.skillName&&n.set("skillName",t.skillName),t!=null&&t.status&&n.set("status",t.status),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await fetch(`${this.baseUrl}/api/executions${r?`?${r}`:""}`,{signal:AbortSignal.timeout(8e3)}),s=await ot(a);return(s==null?void 0:s.entries)??[]}catch{return[]}}async fetchTraces(){try{const t=await fetch(`${this.baseUrl}/api/traces`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return n!=null&&n.traces?n.traces:null}catch{return null}}async fetchAcceptance(){try{const t=await fetch(`${this.baseUrl}/api/acceptance`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||typeof n.labelled!="number"?null:n}catch{return null}}acceptanceExportUrl(t="json"){return`${this.baseUrl}/api/acceptance/export?format=${t}`}async importAcceptance(t,n){try{const r=await fetch(`${this.baseUrl}/api/acceptance/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t,...n?{format:n}:{}})}),a=await ot(r);return!a||typeof a.ok!="boolean"?null:a}catch{return null}}async fetchDecisions(t,n){try{const r=new URLSearchParams;t&&r.set("dir",t),n&&n.trim()&&r.set("for",n.trim());const a=await fetch(`${this.baseUrl}/api/decisions?${r.toString()}`,{signal:AbortSignal.timeout(8e3)}),s=await ot(a);return!s||!Array.isArray(s.decisions)?null:s}catch{return null}}async reviseDecision(t,n,r,a){try{const s=await fetch(`${this.baseUrl}/api/decisions/revise`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dir:t,id:n,answer:r,...a?{note:a}:{}})}),o=await ot(s);return!o||o.ok!==!0||!o.decision?null:o.decision}catch{return null}}async fetchGates(){try{const t=await fetch(`${this.baseUrl}/api/gates`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||typeof n.events!="number"?null:n}catch{return null}}async fetchConsent(){try{const t=await fetch(`${this.baseUrl}/api/consent`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||n.ok!==!0||!n.picture||!n.picture.denied?null:n.picture}catch{return null}}async fetchCapabilities(){try{const t=await fetch(`${this.baseUrl}/api/capabilities`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||n.ok!==!0||!Array.isArray(n.verbs)?null:n}catch{return null}}async saveLearnedCommand(t,n,r){try{const a=await fetch(`${this.baseUrl}/api/capabilities/commands`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verb:t,command:n,...r?{note:r}:{}})}),s=await ot(a);return{ok:(s==null?void 0:s.ok)===!0,commands:s==null?void 0:s.commands,error:s==null?void 0:s.error}}catch{return{ok:!1,error:"Could not reach the server."}}}async forgetLearnedCommand(t){try{const n=await fetch(`${this.baseUrl}/api/capabilities/commands/forget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verb:t})}),r=await ot(n);return{ok:(r==null?void 0:r.ok)===!0,commands:r==null?void 0:r.commands,error:r==null?void 0:r.error}}catch{return{ok:!1,error:"Could not reach the server."}}}async fetchSessionGrants(){try{const t=await fetch(`${this.baseUrl}/api/session-grants`,{signal:AbortSignal.timeout(8e3)}),n=await ot(t);return!n||!Array.isArray(n.grants)?null:n.grants}catch{return null}}async revokeSessionGrant(t){try{const n=await fetch(`${this.baseUrl}/api/session-grants/clear`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t})}),r=await ot(n);return(r==null?void 0:r.ok)===!0}catch{return!1}}async fetchAdminChecks(){try{const t=await fetch(`${this.baseUrl}/api/admin/checks`,{signal:AbortSignal.timeout(15e3)}),n=await ot(t);return!n||!Array.isArray(n.system)||!Array.isArray(n.enterprise)||!Array.isArray(n.providers)?null:n}catch{return null}}async fetchHub(){var t;try{const n=await fetch(`${this.baseUrl}/api/hub`,{signal:AbortSignal.timeout(8e3)}),r=await ot(n);return!r||!Array.isArray((t=r.toolsets)==null?void 0:t.toolsets)?null:r}catch{return null}}async rateTrace(t,n){try{const r=await fetch(`${this.baseUrl}/api/traces/${encodeURIComponent(t)}/verdict`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verdict:n}),signal:AbortSignal.timeout(8e3)}),a=await ot(r);return a!=null&&a.ok&&a.rated?{traceId:a.rated.traceId,corpusLabeled:!!a.rated.corpusLabeled}:null}catch{return null}}async fetchTraceDetail(t){try{const n=await fetch(`${this.baseUrl}/api/traces/${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(8e3)}),r=await ot(n);return r&&Array.isArray(r.steps)?r:null}catch{return null}}async sendAdminRequest(t,n,r){try{const a=en(),s=await fetch(`${this.baseUrl}${t}`,{method:n,headers:{"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{}},body:r!==void 0?JSON.stringify(r):void 0,signal:AbortSignal.timeout(15e3)}),o=s.headers.get("content-type")||"";let l=null;if(o.includes("application/json")||o.includes("text/json"))try{l=await s.json()}catch{l=null}return{status:s.status,data:l}}catch{return null}}async fetchAdminAuthStatus(){const t=await this.sendAdminRequest("/api/admin/auth-status","GET");if(!t||typeof t.data!="object"||t.data===null)return null;const n=t.data;return typeof n.configured!="boolean"||typeof n.authenticated!="boolean"?null:{configured:n.configured,authenticated:n.authenticated,user:typeof n.user=="string"?n.user:null,role:typeof n.role=="string"?n.role:null,mustChangePassword:n.mustChangePassword===!0}}async changeAdminPassword(t,n){const r=await this.sendAdminRequest("/api/admin/change-password","POST",{currentPassword:t,newPassword:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?{ok:!0}:{ok:!1,error:a.error||"Could not change the password."}}async fetchAdminUsers(){const t=await this.sendAdminRequest("/api/admin/users","GET");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok&&Array.isArray(n.users)?n:{ok:!1,error:n.error||"Failed to load users.",forbidden:t.status===403,unauthorized:t.status===401}}async addAdminUser(t,n,r){const a=await this.sendAdminRequest("/api/admin/users","POST",{user:t,password:n,role:r});if(!a)return{ok:!1,error:"Could not reach the dashboard server."};const s=a.data??{};return a.status===200&&s.ok?s:{ok:!1,error:s.error||"Failed to add user.",forbidden:a.status===403,unauthorized:a.status===401}}async removeAdminUser(t){const n=await this.sendAdminRequest(`/api/admin/users/${encodeURIComponent(t)}`,"DELETE");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Failed to remove user.",forbidden:n.status===403,unauthorized:n.status===401}}async fetchAdminCatalog(){const t=await this.sendAdminRequest("/api/admin/catalog","GET"),n=t==null?void 0:t.data;return!n||!Array.isArray(n.providers)?null:n.providers}async adminSetup(t,n){const r=await this.sendAdminRequest("/api/admin/setup","POST",{user:t,password:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&typeof a.token=="string"?(sg(a.token),{ok:!0,user:a.user,token:a.token}):{ok:!1,error:a.error||"Setup failed.",unauthorized:r.status===401}}async adminLogin(t,n){const r=await this.sendAdminRequest("/api/admin/login","POST",{user:t,password:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&typeof a.token=="string"?(sg(a.token),{ok:!0,user:a.user,token:a.token}):{ok:!1,error:a.error||"Login failed.",unauthorized:r.status===401}}async adminLogout(){await this.sendAdminRequest("/api/admin/logout","POST"),sg(null)}async shutdown(t){const n=await this.sendAdminRequest("/api/admin/shutdown","POST",{target:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Shutdown failed.",unauthorized:n.status===401,forbidden:n.status===403}}async saveProvider(t,n){const r=await this.sendAdminRequest(`/api/admin/providers/${encodeURIComponent(t)}`,"PUT",n);if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Save failed.",unauthorized:r.status===401}}async deleteProvider(t){const n=await this.sendAdminRequest(`/api/admin/providers/${encodeURIComponent(t)}`,"DELETE");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Remove failed.",unauthorized:n.status===401}}async testProvider(t){const n=await this.sendAdminRequest(`/api/admin/providers/${encodeURIComponent(t)}/test`,"POST");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200?r:{ok:!1,error:r.error||"Test failed.",unauthorized:n.status===401}}async fetchOmniRouteStatus(){const t=await this.sendAdminRequest("/api/admin/omniroute","GET");if(!t)return null;const n=t.data??{};return t.status!==200||!n.status?null:n.status}async controlOmniRoute(t){const n=await this.sendAdminRequest("/api/admin/omniroute","POST",{action:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200?r:{ok:!1,error:r.error||"OmniRoute control failed.",unauthorized:n.status===401,forbidden:n.status===403}}async fetchAdminWorkspace(){const t=await this.sendAdminRequest("/api/admin/workspace","GET");if(!t)return null;const n=t.data??{};return t.status!==200||n.ok!==!0?null:{configured:typeof n.configured=="string"?n.configured:null,effective:typeof n.effective=="string"?n.effective:null,processCwd:typeof n.processCwd=="string"?n.processCwd:"",configuredValid:n.configuredValid===!0}}async saveAdminWorkspace(t){const n=await this.sendAdminRequest("/api/admin/workspace","PUT",{cwd:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok===!0?{ok:!0,workspace:{configured:typeof r.configured=="string"?r.configured:null,effective:typeof r.effective=="string"?r.effective:null,processCwd:typeof r.processCwd=="string"?r.processCwd:"",configuredValid:r.configuredValid===!0}}:{ok:!1,error:r.error||"Save failed.",unauthorized:n.status===401,forbidden:n.status===403}}async fetchAdminCache(){const t=await this.sendAdminRequest("/api/admin/cache","GET");if(!t)return null;const n=t.data;return!n||n.ok!==!0||!Array.isArray(n.workspaces)?null:n}async clearAdminCache(t){const n=await this.sendAdminRequest("/api/admin/cache/clear","POST",{scope:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0,removed:r.removed??0}:{ok:!1,error:r.error||"Could not clear the cache.",unauthorized:n.status===401,forbidden:n.status===403}}async fetchAdminServices(){const t=await this.sendAdminRequest("/api/admin/services","GET");if(!t)return null;const n=t.data;return!n||n.ok!==!0||!Array.isArray(n.services)?null:n}async saveService(t,n){const r=await this.sendAdminRequest(`/api/admin/services/${encodeURIComponent(t)}`,"PUT",{values:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Save failed.",unauthorized:r.status===401,forbidden:r.status===403}}async testService(t){const n=await this.sendAdminRequest(`/api/admin/services/${encodeURIComponent(t)}/test`,"POST");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200?r:{ok:!1,error:r.error||"Test failed."}}async removeService(t){const n=await this.sendAdminRequest(`/api/admin/services/${encodeURIComponent(t)}`,"DELETE");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Remove failed.",unauthorized:n.status===401,forbidden:n.status===403}}async fetchAdminQuota(){const t=await this.sendAdminRequest("/api/admin/quota","GET");if(!t)return null;const n=t.data;return!n||!n.ok||typeof n.quota!="object"?null:n}async setToolsetEnabled(t,n){const r=await this.sendAdminRequest(`/api/admin/hub/toolsets/${encodeURIComponent(t)}`,"PUT",{enabled:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Toggle failed.",unauthorized:r.status===401,forbidden:r.status===403}}async setSkillEnabled(t,n){const r=await this.sendAdminRequest(`/api/admin/hub/skills/${encodeURIComponent(t)}`,"PUT",{enabled:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Toggle failed.",unauthorized:r.status===401,forbidden:r.status===403}}async fetchKnowledge(){try{const n=await(await fetch(`${this.baseUrl}/api/knowledge`,{headers:yt(),signal:AbortSignal.timeout(8e3)})).json();return Array.isArray(n.tags)?n.tags:null}catch{return null}}async knowledgeIngest(t,n){try{const r=await fetch(`${this.baseUrl}/api/knowledge/ingest`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({tag:t,paths:n})}),a=await r.json();return r.status===200&&a.ok?{...a,ok:!0}:{ok:!1,error:a.error||"Ingest failed."}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}}async knowledgeQuery(t,n,r){try{const a=await fetch(`${this.baseUrl}/api/knowledge/query`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({tag:t,question:n,topK:r})}),s=await a.json();return a.status===200&&s.ok?{...s,ok:!0}:{ok:!1,error:s.error||"Query failed."}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}async knowledgeForget(t){try{const n=await fetch(`${this.baseUrl}/api/knowledge/forget`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({tag:t})}),r=await n.json();return n.status===200&&r.ok?{...r,ok:!0}:{ok:!1,error:r.error||"Forget failed."}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async marketplaceSearch(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/marketplace?q=${encodeURIComponent(t)}`,{headers:yt()})).json();return Array.isArray(r.results)?r.results:[]}catch{return[]}}async marketplaceInstall(t){try{const n=await fetch(`${this.baseUrl}/api/skills/marketplace/install`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})}),r=await n.json();return n.status===200&&r.ok?{ok:!0}:{ok:!1,error:r.error||"Install failed.",quarantined:r.quarantined===!0}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async marketplaceUninstall(t){try{const n=await fetch(`${this.baseUrl}/api/skills/marketplace/uninstall`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})}),r=await n.json();return n.status===200&&r.ok?{ok:!0}:{ok:!1,error:r.error||"Uninstall failed."}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async sendChannelMessage(t,n){const r=await this.sendAdminRequest("/api/admin/hub/channels/send","POST",{target:t,text:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Send failed.",unauthorized:r.status===401,forbidden:r.status===403}}async gatewayPolicies(){const t=await this.sendAdminRequest("/api/admin/gateway/policies","GET");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?{ok:!0,policies:n.policies,statusRecipients:n.statusRecipients,contacts:n.contacts,askUserWait:n.askUserWait,askUserTimeoutMs:n.askUserTimeoutMs}:{ok:!1,error:n.error||"Failed to read policies.",unauthorized:t.status===401,forbidden:t.status===403}}async saveGatewayPolicies(t,n,r,a){const s={policies:t};Array.isArray(n)&&(s.statusRecipients=n),Array.isArray(r)&&(s.contacts=r),a&&(s.askUserWait=a.wait,typeof a.timeoutMs=="number"&&(s.askUserTimeoutMs=a.timeoutMs));const o=await this.sendAdminRequest("/api/admin/gateway/policies","PUT",s);if(!o)return{ok:!1,error:"Could not reach the dashboard server."};const l=o.data??{};return o.status===200&&l.ok?l:{ok:!1,error:l.error||"Failed to save policies.",unauthorized:o.status===401,forbidden:o.status===403}}async fetchGatewayConversations(t={}){const n=new URLSearchParams;t.offset&&n.set("offset",String(t.offset)),t.limit&&n.set("limit",String(t.limit)),t.q&&n.set("q",t.q);const r=n.toString(),a=await this.sendAdminRequest(`/api/admin/gateway/conversations${r?`?${r}`:""}`,"GET");if(!a)return{ok:!1,error:"Could not reach the dashboard server."};const s=a.data??{};return a.status===200&&s.ok?{ok:!0,conversations:s.conversations,total:s.total,hasMore:s.hasMore}:{ok:!1,error:s.error||"Failed to load conversations.",unauthorized:a.status===401,forbidden:a.status===403}}async clearGatewayConversation(t){const n=await this.sendAdminRequest("/api/admin/gateway/conversations","DELETE",{key:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0}:{ok:!1,error:r.error||"Failed to clear conversation.",unauthorized:n.status===401,forbidden:n.status===403}}async addConversationTag(t,n){const r=await this.sendAdminRequest("/api/admin/gateway/conversations/tags","PUT",{action:"add",key:t,tag:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?{ok:!0}:{ok:!1,error:a.error||"Failed to add tag.",unauthorized:r.status===401,forbidden:r.status===403}}async removeConversationTag(t,n){const r=await this.sendAdminRequest("/api/admin/gateway/conversations/tags","PUT",{action:"remove",key:t,tag:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?{ok:!0}:{ok:!1,error:a.error||"Failed to remove tag.",unauthorized:r.status===401,forbidden:r.status===403}}async getAllConversationTags(){const t=await this.sendAdminRequest("/api/admin/gateway/conversations/tags","PUT",{action:"getAllTags"});if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?{ok:!0,tags:n.tags}:{ok:!1,error:n.error||"Failed to load tags.",unauthorized:t.status===401,forbidden:t.status===403}}async exportGatewayConversations(t){var n,r,a;try{const s=en(),o=await fetch(`${this.baseUrl}/api/admin/gateway/conversations/export`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({keys:t}),signal:AbortSignal.timeout(3e4)});if(o.status===200&&((n=o.headers.get("content-type"))!=null&&n.includes("application/zip"))){const c=await o.blob(),u=URL.createObjectURL(c),d=document.createElement("a");return d.href=u,d.download=((a=(r=o.headers.get("content-disposition"))==null?void 0:r.match(/filename="(.+)"/))==null?void 0:a[1])||"conversations.zip",document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(u),{ok:!0}}return{ok:!1,error:(await o.json().catch(()=>({}))).error||"Export failed."}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}async getContacts(){const t=await this.sendAdminRequest("/api/admin/contacts","GET");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?{ok:!0,contacts:n.contacts}:{ok:!1,error:n.error||"Failed to read contacts."}}async approveContact(t,n){return this.contactAction("approve",t,n)}async rejectContact(t,n){return this.contactAction("reject",t,n)}async deleteContact(t,n){return this.contactAction("delete",t,n)}async updateContact(t,n,r){const a=await this.sendAdminRequest("/api/admin/contacts","PUT",{action:"update",platform:t,id:n,...r});if(!a)return{ok:!1,error:"Could not reach the dashboard server."};const s=a.data??{};return a.status===200&&s.ok?s:{ok:!1,error:s.error||"Update failed."}}async contactAction(t,n,r){const a=await this.sendAdminRequest("/api/admin/contacts","PUT",{action:t,platform:n,nameOrId:r});if(!a)return{ok:!1,error:"Could not reach the dashboard server."};const s=a.data??{};return a.status===200&&s.ok?s:{ok:!1,error:s.error||`${t} failed.`}}async getPlatformConfigs(){const t=await this.sendAdminRequest("/api/config/platforms","GET");if(!t)return[];const n=t.data??{};return Array.isArray(n.platforms)?n.platforms:[]}async setPlatformConfig(t,n){const r=await this.sendAdminRequest(`/api/config/platforms/${encodeURIComponent(t)}`,"POST",{values:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok?a:{ok:!1,error:a.error||"Save failed.",unauthorized:r.status===401,forbidden:r.status===403}}async removePlatformConfig(t){const n=await this.sendAdminRequest(`/api/config/platforms/${encodeURIComponent(t)}`,"DELETE");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Remove failed.",unauthorized:n.status===401,forbidden:n.status===403}}async verifyPlatformConfig(t,n){const r=await this.sendAdminRequest(`/api/config/platforms/${encodeURIComponent(t)}/verify`,"POST",{values:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return{ok:a.ok??!1,info:a.info,error:a.error}}async saveAdminQuota(t){const n=await this.sendAdminRequest("/api/admin/quota","PUT",t);if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Save failed.",unauthorized:n.status===401}}async getBedrockStatus(){const t=await this.sendAdminRequest("/api/bedrock/status","GET");return!t||t.status!==200?{configured:!1,region:"us-east-1",authMethod:"none",apiKeySet:!1,iamKeySet:!1}:t.data??{}}async setupBedrock(t){const n=await this.sendAdminRequest("/api/bedrock/setup","POST",{envVars:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0,envVarsWritten:r.envVarsWritten}:{ok:!1,error:r.error||"Save failed."}}async probeBedrock(t){const n=await this.sendAdminRequest("/api/bedrock/probe","POST",{region:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0,models:r.models}:{ok:!1,error:r.error||"Probe failed."}}async listTasks(){const t=await this.sendAdminRequest("/api/tasks","GET");if(!t)return null;const n=t.data??{};return{status:t.status,tasks:Array.isArray(n.tasks)?n.tasks:[]}}async startTask(t,n){const r=await this.sendAdminRequest("/api/tasks","POST",{args:t,timeoutMs:n});if(!r)return{ok:!1,error:"Could not reach the dashboard server."};const a=r.data??{};return r.status===200&&a.ok&&a.task?a:{ok:!1,error:a.error||"Start failed.",unauthorized:r.status===401,forbidden:r.status===403}}async getTask(t){const n=await this.sendAdminRequest(`/api/tasks/${encodeURIComponent(t)}`,"GET");if(!n)return null;const r=n.data??{};return{status:n.status,task:r.task??null}}async cancelTask(t){const n=await this.sendAdminRequest(`/api/tasks/${encodeURIComponent(t)}/cancel`,"POST");if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Cancel failed.",unauthorized:n.status===401,forbidden:n.status===403}}subscribeTask(t,n){const r=en(),a=new EventSource(`${this.baseUrl}/api/tasks/${encodeURIComponent(t)}/events?token=${encodeURIComponent(r??"")}`);return a.addEventListener("log",s=>{var o;try{(o=n.onLog)==null||o.call(n,JSON.parse(s.data))}catch{}}),a.addEventListener("status",s=>{var o;try{const l=JSON.parse(s.data);l.status&&((o=n.onStatus)==null||o.call(n,l.status))}catch{}}),()=>a.close()}async getWhatsAppStatus(){const t=await this.sendAdminRequest("/api/whatsapp","GET");if(!t)return null;const n=t.data??{};return t.status===200&&n.ok&&n.status?{status:n.status,contacts:n.contacts??{}}:null}async startWhatsAppPair(t){const n=await this.sendAdminRequest("/api/whatsapp/pair","POST",{phone:t||void 0});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?r:{ok:!1,error:r.error||"Pairing failed to start.",unauthorized:n.status===401,forbidden:n.status===403}}async cancelWhatsAppPair(){const t=await this.sendAdminRequest("/api/whatsapp/cancel","POST");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?n:{ok:!1,error:n.error||"Cancel failed.",unauthorized:t.status===401,forbidden:t.status===403}}async unpairWhatsApp(){const t=await this.sendAdminRequest("/api/whatsapp/unpair","POST");if(!t)return{ok:!1,error:"Could not reach the dashboard server."};const n=t.data??{};return t.status===200&&n.ok?n:{ok:!1,error:n.error||"Unpair failed.",unauthorized:t.status===401,forbidden:t.status===403}}subscribeWhatsApp(t){const n=en(),r=new EventSource(`${this.baseUrl}/api/whatsapp/events?token=${encodeURIComponent(n??"")}`);return r.addEventListener("qr",a=>{var s;try{const o=JSON.parse(a.data);o.qr&&((s=t.onQr)==null||s.call(t,o.qr))}catch{}}),r.addEventListener("code",a=>{var s;try{const o=JSON.parse(a.data);o.code&&((s=t.onCode)==null||s.call(t,o.code))}catch{}}),r.addEventListener("status",a=>{var s;try{(s=t.onStatus)==null||s.call(t,JSON.parse(a.data))}catch{}}),()=>r.close()}async chatResolve(t){const n=en();try{const r=await fetch(`${this.baseUrl}/api/chat/resolve`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({message:t}),signal:AbortSignal.timeout(1e4)}),a=await r.json();return r.status===200&&a.ok&&Array.isArray(a.matches)?{ok:!0,matches:a.matches}:{ok:!1,matches:[],error:typeof a.error=="string"?a.error:"Resolve failed."}}catch{return{ok:!1,matches:[],error:"Could not reach the dashboard server."}}}async listRoutableModels(){const t=en();try{const n=await fetch(`${this.baseUrl}/api/chat/routable-models`,{headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(1e4)}),r=await n.json();return n.status===200&&r.ok&&Array.isArray(r.models)?r.models:[]}catch{return[]}}async listProjects(){const t=en();try{const n=await fetch(`${this.baseUrl}/api/projects`,{headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(1e4)}),r=await n.json();return n.status===200&&r.ok&&Array.isArray(r.projects)?r.projects:[]}catch{return[]}}async attachProject(t){const n=en();try{const r=await fetch(`${this.baseUrl}/api/projects/attach`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({path:t}),signal:AbortSignal.timeout(3e4)}),a=await r.json();return r.status===200&&a.ok&&a.project?{ok:!0,project:a.project}:{ok:!1,error:typeof a.error=="string"?a.error:"Attach failed."}}catch{return{ok:!1,error:"Could not reach the dashboard server."}}}async browseDirectories(t,n){const r=en();try{const a=new URLSearchParams;t&&a.set("path",t),n!=null&&n.showDrives&&a.set("showDrives","1");const s=a.toString()?`?${a.toString()}`:"",o=await fetch(`${this.baseUrl}/api/browse${s}`,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(1e4)}),l=await o.json();return o.status===200&&l.ok&&Array.isArray(l.entries)?{ok:!0,path:l.path??"",entries:l.entries,parent:l.parent??null,isProject:l.isProject??!1,drives:l.drives,breadcrumbs:l.breadcrumbs}:{ok:!1,path:"",entries:[],parent:null,isProject:!1,error:typeof l.error=="string"?l.error:"Browse failed."}}catch{return{ok:!1,path:"",entries:[],parent:null,isProject:!1,error:"Could not reach the dashboard server."}}}async resolveFolder(t,n){const r=en();try{const a=await fetch(this.baseUrl+"/api/browse/resolve-folder",{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:"Bearer "+r}:{}},body:JSON.stringify({name:t,subPath:n||""}),signal:AbortSignal.timeout(1e4)}),s=await a.json();return a.status===200&&s.ok&&s.path?{ok:!0,path:s.path}:{ok:!1,path:"",error:typeof s.error=="string"?s.error:"Could not resolve folder."}}catch{return{ok:!1,path:"",error:"Could not reach the dashboard server."}}}async listChatSessions(){const t=en();try{const n=await fetch(`${this.baseUrl}/api/sessions`,{headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(1e4)}),r=await n.json();return n.status===200&&r.ok&&Array.isArray(r.sessions)?r.sessions:[]}catch{return[]}}async deleteChatSession(t){const n=en();try{const r=await fetch(`${this.baseUrl}/api/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:n?{Authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(1e4)}),a=await r.json();return r.status===200&&a.ok?{ok:!0}:{ok:!1,error:a.error||"Could not delete the session."}}catch{return{ok:!1,error:"Network error — could not delete the session."}}}async renameChatSession(t,n){const r=en();try{const a=await fetch(`${this.baseUrl}/api/sessions/${encodeURIComponent(t)}/rename`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({title:n}),signal:AbortSignal.timeout(1e4)}),s=await a.json();return a.status===200&&s.ok?{ok:!0}:{ok:!1,error:s.error||"Could not rename the session."}}catch{return{ok:!1,error:"Network error — could not rename the session."}}}async getChatSession(t){const n=en();try{const r=await fetch(`${this.baseUrl}/api/sessions/${encodeURIComponent(t)}`,{headers:n?{Authorization:`Bearer ${n}`}:{},signal:AbortSignal.timeout(1e4)}),a=await r.json();return r.status===200&&a.ok&&a.session?a.session:null}catch{return null}}async chatSend(t,n,r,a){const s=en();try{const o=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...s?{Authorization:`Bearer ${s}`}:{}},body:JSON.stringify({sessionId:t,message:n,provider:r==null?void 0:r.provider,model:r==null?void 0:r.model,...(r==null?void 0:r.strict)===!0?{strict:!0}:{},projectPath:r==null?void 0:r.projectPath,attachments:r==null?void 0:r.attachments,...(r==null?void 0:r.worktree)===void 0?{}:{worktree:r.worktree},...(r==null?void 0:r.keepWorktree)===void 0?{}:{keepWorktree:r.keepWorktree},...(r==null?void 0:r.resume)===void 0?{}:{resume:r.resume}}),signal:a?AbortSignal.any([AbortSignal.timeout(3e5),a]):AbortSignal.timeout(3e5)}),l=await o.json();return o.status===200&&l.ok?{ok:!0,content:typeof l.content=="string"?l.content:"",followups:Array.isArray(l.followups)?l.followups:[],provider:typeof l.provider=="string"?l.provider:null,model:typeof l.model=="string"?l.model:null,...typeof l.routingNotice=="string"&&l.routingNotice?{routingNotice:l.routingNotice}:{},...typeof l.workspaceNotice=="string"&&l.workspaceNotice?{workspaceNotice:l.workspaceNotice}:{},...typeof l.workspacePath=="string"&&l.workspacePath?{workspacePath:l.workspacePath}:{},...typeof l.workspaceSource=="string"&&l.workspaceSource?{workspaceSource:l.workspaceSource}:{},generationFailed:l.generationFailed===!0,retryQueued:l.retryQueued===!0,...l.needsProject===!0?{needsProject:!0}:{},...l.refused===!0?{refused:!0}:{},...Q2(l.worktree)?{worktree:l.worktree}:{},...Z2(l.resume)?{resume:l.resume}:{},...Array.isArray(l.findings)?{findings:l.findings}:{},...J2(l.turnReport)?{turnReport:l.turnReport}:{}}:{ok:!1,error:typeof l.error=="string"?l.error:"The agent could not answer.",unauthorized:o.status===401,forbidden:o.status===403}}catch(o){const l=o==null?void 0:o.name;return l==="TimeoutError"?{ok:!1,error:"The dashboard stopped waiting after 5 minutes — the turn is STILL RUNNING on the server. Reopen this conversation (or watch Traces) to see the result when it lands."}:l==="AbortError"?{ok:!1,error:"Cancelled."}:{ok:!1,error:"Could not reach the dashboard server."}}}async chatCancel(t){const n=await this.sendAdminRequest("/api/chat/cancel","POST",{sessionId:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0,cancelled:r.cancelled===!0}:{ok:!1,error:r.error||"Cancel failed."}}async chatReset(t){const n=await this.sendAdminRequest("/api/chat/reset","POST",{sessionId:t});if(!n)return{ok:!1,error:"Could not reach the dashboard server."};const r=n.data??{};return n.status===200&&r.ok?{ok:!0}:{ok:!1,error:r.error||"Reset failed."}}async chatSupportBundle(t){var r,a,s;const n=en();try{const o=await fetch(`${this.baseUrl}/api/chat/${encodeURIComponent(t)}/support-bundle`,{method:"GET",headers:{...n?{Authorization:`Bearer ${n}`}:{}},signal:AbortSignal.timeout(3e4)});if(o.status===200&&((r=o.headers.get("content-type"))!=null&&r.includes("application/zip"))){const c=await o.blob(),u=URL.createObjectURL(c),d=document.createElement("a");return d.href=u,d.download=((s=(a=o.headers.get("content-disposition"))==null?void 0:a.match(/filename="(.+)"/))==null?void 0:s[1])||"nuvira-support.zip",document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(u),{ok:!0}}return{ok:!1,error:(await o.json().catch(()=>({}))).error||"Could not build the support bundle."}}catch(o){return{ok:!1,error:o instanceof Error?o.message:"Could not reach the dashboard server."}}}subscribeChat(t,n){const r=en(),a=new EventSource(`${this.baseUrl}/api/chat/${encodeURIComponent(t)}/events?token=${encodeURIComponent(r??"")}`);return a.addEventListener("progress",s=>{var o;try{const l=JSON.parse(s.data);l.line&&((o=n.onProgress)==null||o.call(n,l.line))}catch{}}),a.addEventListener("status",s=>{var o;try{const l=JSON.parse(s.data);l.status&&((o=n.onStatus)==null||o.call(n,l.status))}catch{}}),a.addEventListener("token",s=>{var o;try{const l=JSON.parse(s.data);typeof l.text=="string"&&l.text.length>0&&((o=n.onToken)==null||o.call(n,l.text))}catch{}}),a.addEventListener("tool",s=>{var o;try{const l=JSON.parse(s.data);l.tool&&(l.phase==="started"||l.phase==="called")&&((o=n.onTool)==null||o.call(n,{id:l.id||`call_${Math.random().toString(36).slice(2,8)}`,tool:l.tool,phase:l.phase,args:l.args,ok:l.ok,result:l.result,error:l.error,durationMs:l.durationMs}))}catch{}}),a.addEventListener("plan",s=>{var o;try{const l=JSON.parse(s.data);l.goal&&Array.isArray(l.steps)&&((o=n.onPlan)==null||o.call(n,{goal:l.goal,steps:l.steps,revision:l.revision??0}))}catch{}}),a.addEventListener("diff",s=>{var o;try{const l=JSON.parse(s.data);Array.isArray(l.files)&&((o=n.onDiff)==null||o.call(n,{files:l.files,summary:l.summary??""}))}catch{}}),a.addEventListener("finding",s=>{var o;try{const c=JSON.parse(s.data).finding;c&&typeof c.claim=="string"&&(c.verdict==="CONFIRMED"||c.verdict==="PLAUSIBLE")&&((o=n.onFinding)==null||o.call(n,{claim:c.claim,verdict:c.verdict,outcome:typeof c.outcome=="string"?c.outcome:"",evidence:Array.isArray(c.evidence)?c.evidence:[],source:typeof c.source=="string"?c.source:""}))}catch{}}),a.addEventListener("skill_draft",s=>{var o;try{const l=JSON.parse(s.data);l.name&&l.markdown&&((o=n.onSkillDraft)==null||o.call(n,{name:l.name,description:l.description??"",markdown:l.markdown,updatedAt:l.updatedAt??0}))}catch{}}),a.addEventListener("secret_request",s=>{var o;try{const l=JSON.parse(s.data);l.skillName&&Array.isArray(l.missing)&&((o=n.onSecretRequest)==null||o.call(n,{skillName:l.skillName,missing:l.missing,persisted:l.persisted??{}}))}catch{}}),a.addEventListener("execution_result",s=>{var o;try{const l=JSON.parse(s.data);l.skillName&&l.runtime!==void 0&&((o=n.onExecutionResult)==null||o.call(n,{skillName:l.skillName,runtime:l.runtime,success:l.success??!1,durationMs:l.durationMs??0,exitCode:l.exitCode??0,stdout:l.stdout??"",stderr:l.stderr??"",timestamp:l.timestamp??Date.now()}))}catch{}}),a.addEventListener("question",s=>{var o;try{const l=JSON.parse(s.data);l.questionId&&l.question&&((o=n.onQuestion)==null||o.call(n,{questionId:l.questionId,question:l.question,choices:l.choices??[],multiSelect:l.multiSelect===!0}))}catch{}}),()=>a.close()}async chatRespond(t,n,r={}){try{const s=await(await fetch(`${this.baseUrl}/api/chat/${encodeURIComponent(t)}/respond`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({questionId:n,...r})})).json();return{ok:s.ok===!0,error:s.error}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}async skillDraftAccept(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/drafts/${encodeURIComponent(t)}/accept`,{method:"POST",headers:{...yt()}})).json();return{ok:r.ok===!0,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async skillDraftReject(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/drafts/${encodeURIComponent(t)}`,{method:"DELETE",headers:{...yt()}})).json();return{ok:r.ok===!0,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async saveSecrets(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/secrets`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({vars:t})})).json();return{ok:r.ok===!0,error:r.error,saved:r.saved,refused:r.refused}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async fetchSkillEnv(){try{const t=await fetch(`${this.baseUrl}/api/skills/env`,{headers:{...yt()}}),n=await ot(t);return(n==null?void 0:n.vars)??[]}catch{return[]}}async deleteSkillEnvVar(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/env/delete`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})})).json();return{ok:r.ok===!0,removed:r.removed,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async testSkillEnvVar(t){try{const r=await(await fetch(`${this.baseUrl}/api/skills/env/test`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})})).json();return{ok:r.ok===!0,usable:r.usable,detail:r.detail,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async fetchProcessEnv(){try{const t=await fetch(`${this.baseUrl}/api/process-env`,{headers:{...yt()}}),n=await ot(t);return(n==null?void 0:n.vars)??[]}catch{return[]}}async fetchLimits(){try{const t=await fetch(`${this.baseUrl}/api/limits`),n=await ot(t);return!n||typeof n.attachmentMaxBytes!="number"||n.attachmentMaxBytes<=0?null:{attachmentMaxBytes:n.attachmentMaxBytes,extractMaxChars:typeof n.extractMaxChars=="number"?n.extractMaxChars:0}}catch{return null}}async fetchContinuity(){try{const t=await fetch(`${this.baseUrl}/api/continuity`,{headers:{...yt()}}),n=await ot(t);return!n||n.ok!==!0?null:{sessions:n.sessions??[],recall:n.recall??[],toggles:n.toggles??{sessionStore:!1,sessionRecall:!1}}}catch{return null}}async clearContinuity(t,n,r){try{const s=await(await fetch(`${this.baseUrl}/api/continuity/clear`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({target:t,...n?{id:n}:{},...r?{olderThanMs:r}:{}})})).json();return{ok:s.ok===!0,removed:s.removed,error:s.error}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}async fetchHistory(){try{const t=await fetch(`${this.baseUrl}/api/history`,{headers:{...yt()}});return await ot(t)}catch{return null}}async clearHistory(t,n={}){try{const a=await(await fetch(`${this.baseUrl}/api/history/clear`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({target:t,...n.id?{id:n.id}:{},...n.olderThanMs?{olderThanMs:n.olderThanMs}:{}})})).json();return{ok:a.ok===!0,removed:a.removed,error:a.error}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}}async fetchVerifyBacklog(){try{const t=await fetch(`${this.baseUrl}/api/models/verify-next`,{headers:{...yt()}});return await ot(t)}catch{return null}}async startVerifyBacklog(t){try{const n=await fetch(`${this.baseUrl}/api/models/verify-next`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({count:t})}),r=await ot(n);return r?{ok:r.ok===!0,error:r.error,refusal:r.refusal,state:r.state}:{ok:!1,error:"The dashboard server did not respond."}}catch(n){return{ok:!1,error:n instanceof Error?n.message:"Could not start the run."}}}async saveProcessEnvVar(t,n){try{const a=await(await fetch(`${this.baseUrl}/api/process-env`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t,value:n})})).json();return{ok:a.ok===!0,row:a.row,error:a.error,reason:a.reason}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}}async deleteProcessEnvVar(t){try{const r=await(await fetch(`${this.baseUrl}/api/process-env/delete`,{method:"POST",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({name:t})})).json();return{ok:r.ok===!0,removed:r.removed,row:r.row,error:r.error}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}async fetchHooks(){try{const t=await fetch(`${this.baseUrl}/api/hooks`,{headers:{...yt()}}),n=await ot(t);return!n||!Array.isArray(n.hooks)?null:n}catch{return null}}async saveHooks(t){try{const n=await fetch(`${this.baseUrl}/api/hooks`,{method:"PUT",headers:{"Content-Type":"application/json",...yt()},body:JSON.stringify({hooks:t})}),r=await n.json();return{ok:r.ok===!0,hooks:r.hooks,error:r.error,forbidden:n.status===403}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}}const K=new iB,au=["enterprise","neutral","pastel","executive","contrast","premium","premium-amoled"],Rp=["light","dark"],Zx=[100,112,125,150],rh={enterprise:"Enterprise",neutral:"Neutral",pastel:"Pastel",executive:"Executive",contrast:"High contrast",premium:"Premium","premium-amoled":"Premium AMOLED"},CT="nuvira.dashboard.theme",rS={palette:"enterprise",mode:"dark",a11y:!1,fontScale:100};function Io(e,t){return e.includes(t)}function sB(){return typeof window>"u"||typeof window.matchMedia!="function"?null:window.matchMedia("(prefers-color-scheme: dark)").matches}function AT(){const e=sB();return e===null?{...rS}:{...rS,mode:e?"dark":"light"}}function TT(){const e=AT();if(typeof localStorage>"u")return e;let t;try{const a=localStorage.getItem(CT);if(!a)return e;t=JSON.parse(a)}catch{return e}if(typeof t!="object"||t===null)return e;const n=t,r=Io(Zx,n.fontScale)?n.fontScale:e.fontScale;return{palette:Io(au,n.palette)?n.palette:e.palette,mode:Io(Rp,n.mode)?n.mode:e.mode,a11y:typeof n.a11y=="boolean"?n.a11y:e.a11y,fontScale:r}}function OT(e){if(!(typeof localStorage>"u"))try{localStorage.setItem(CT,JSON.stringify(e))}catch{}}function Jx(e,t){const n=typeof document<"u"?document.documentElement:void 0;n&&(n.setAttribute("data-palette",e.palette),n.setAttribute("data-mode",e.mode),n.setAttribute("data-a11y",e.a11y?"on":"off"),n.setAttribute("data-font-scale",String(e.fontScale)),n.style.colorScheme=e.mode)}function oB(e,t){const n={palette:Io(au,t.palette)?t.palette:e.palette,mode:Io(Rp,t.mode)?t.mode:e.mode,a11y:t.a11y??e.a11y,fontScale:Io(Zx,t.fontScale)?t.fontScale:e.fontScale};return n.a11y||(n.fontScale=100),n}let gr=TT();const my=new Set;function PT(){for(const e of my)e()}function lB(e){return my.add(e),()=>{my.delete(e)}}function aS(){return gr}function zd(e){const t=oB(gr,e);t.palette===gr.palette&&t.mode===gr.mode&&t.a11y===gr.a11y&&t.fontScale===gr.fontScale||(gr=t,Jx(gr),OT(gr),PT())}function cB(){gr=AT(),Jx(gr),OT(gr),PT()}function uB(){return x.useSyncExternalStore(lB,aS,aS)}const iS={light:"Light",dark:"Dark"},sS={100:"100%",112:"112%",125:"125%",150:"150%"};function dB(){const e=uB(),[t,n]=x.useState(!1),r=x.useRef(null),a=x.useRef(null),s=x.useRef(null),o=x.useId(),l=`${o}-panel`;x.useEffect(()=>{if(!t)return;function u(f){var h;f.key==="Escape"&&(n(!1),(h=r.current)==null||h.focus())}function d(f){var p;const h=f.target;h&&((p=s.current)!=null&&p.contains(h))||n(!1)}return document.addEventListener("keydown",u),document.addEventListener("pointerdown",d),()=>{document.removeEventListener("keydown",u),document.removeEventListener("pointerdown",d)}},[t]),x.useEffect(()=>{var d,f,h;if(!t)return;(h=((d=a.current)==null?void 0:d.querySelector("input:checked"))??((f=a.current)==null?void 0:f.querySelector("input")))==null||h.focus()},[t]);const c=`${rh[e.palette]} palette, ${iS[e.mode].toLowerCase()} mode, text size ${sS[e.fontScale]}`+(e.a11y?", accessibility mode on":"");return i.jsxs("div",{className:"theme-switcher",ref:s,onBlur:u=>{const d=u.relatedTarget;d&&!u.currentTarget.contains(d)&&n(!1)},children:[i.jsxs("button",{type:"button",ref:r,className:"theme-trigger","aria-expanded":t,"aria-controls":t?l:void 0,onClick:()=>n(u=>!u),children:[i.jsx("span",{"aria-hidden":"true",children:"🎨"}),i.jsx("span",{children:"Appearance"})]}),t&&i.jsxs("div",{className:"theme-panel",id:l,ref:a,children:[i.jsxs("fieldset",{className:"theme-group",children:[i.jsx("legend",{className:"theme-group-label",children:"Palette"}),au.map(u=>i.jsxs("label",{className:"theme-option",children:[i.jsx("input",{type:"radio",name:`${o}-palette`,value:u,checked:e.palette===u,onChange:()=>zd({palette:u})}),i.jsx("span",{className:"theme-swatch","data-swatch":u,"aria-hidden":"true"}),i.jsx("span",{className:"theme-option-label",children:rh[u]})]},u))]}),i.jsxs("fieldset",{className:"theme-group",children:[i.jsx("legend",{className:"theme-group-label",children:"Mode"}),Rp.map(u=>i.jsxs("label",{className:"theme-option",children:[i.jsx("input",{type:"radio",name:`${o}-mode`,value:u,checked:e.mode===u,onChange:()=>zd({mode:u})}),i.jsx("span",{className:"theme-option-label",children:iS[u]})]},u))]}),i.jsxs("fieldset",{className:"theme-group",children:[i.jsx("legend",{className:"theme-group-label",children:"Text size"}),Zx.map(u=>i.jsxs("label",{className:"theme-option",children:[i.jsx("input",{type:"radio",name:`${o}-scale`,value:u,checked:e.fontScale===u,onChange:()=>zd({fontScale:u,a11y:e.a11y||u!==100})}),i.jsx("span",{className:"theme-option-label",children:sS[u]})]},u)),!e.a11y&&i.jsx("p",{className:"theme-hint",children:"A larger size turns on accessibility mode, which is what defines it."})]}),i.jsxs("div",{className:"theme-group",children:[i.jsxs("label",{className:"theme-switch",children:[i.jsx("input",{type:"checkbox",checked:e.a11y,onChange:u=>zd({a11y:u.target.checked})}),i.jsx("span",{className:"theme-switch-track","aria-hidden":"true"}),i.jsx("span",{className:"theme-option-label",children:"Accessibility mode"})]}),i.jsx("p",{className:"theme-hint",children:"Larger targets, stronger borders and no motion. Off by default so it never changes the look for anyone who does not need it."})]}),i.jsx("button",{type:"button",className:"theme-reset",onClick:cB,children:"Reset to system default"}),i.jsx("p",{className:"sr-only",role:"status",children:c})]})]})}function fB(){const[e,t]=x.useState(null),[n,r]=x.useState(!1),[a,s]=x.useState(""),[o,l]=x.useState(""),[c,u]=x.useState(!1),[d,f]=x.useState(null),h=x.useRef(null),p=x.useCallback(()=>{K.fetchAdminAuthStatus().then(w=>t(w))},[]);x.useEffect(()=>{p()},[p]),x.useEffect(()=>{if(!n)return;function w(k){h.current&&!h.current.contains(k.target)&&r(!1)}function j(k){k.key==="Escape"&&r(!1)}return document.addEventListener("mousedown",w),document.addEventListener("keydown",j),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",j)}},[n]);const m=(e==null?void 0:e.authenticated)===!0,g=(e==null?void 0:e.configured)===!0,y=async w=>{w.preventDefault(),u(!0),f(null);const j=g?await K.adminLogin(a,o):await K.adminSetup(a,o);j.ok?(s(""),l(""),r(!1),p()):f(j.error||(g?"Login failed.":"Setup failed.")),u(!1)},v=async()=>{r(!1),await K.adminLogout(),p()},S=e?m?`👤 ${e.user||"account"}${e.role?` · ${e.role}`:""}`:"👤 Sign in":"👤 Account";return i.jsxs("div",{className:"topbar-account",ref:h,children:[i.jsx("button",{type:"button",className:"topbar-action","aria-haspopup":"menu","aria-expanded":n,onClick:()=>r(w=>!w),children:S}),n?i.jsx("div",{className:"topbar-account-menu",role:"menu",children:m?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"topbar-account-user",children:[i.jsx("span",{children:(e==null?void 0:e.user)||"account"}),e!=null&&e.role?i.jsx("span",{className:`admin-role-badge admin-role-${e.role}`,children:e.role}):null]}),e!=null&&e.mustChangePassword?i.jsx("p",{className:"topbar-account-hint",children:"Still on the first-run password — change it on the Admin page before writes will work."}):null,i.jsx("button",{type:"button",className:"topbar-account-item",onClick:()=>void v(),children:"🚪 Log out"})]}):i.jsxs("form",{className:"topbar-account-form",onSubmit:y,children:[i.jsx("p",{className:"topbar-account-title",children:g?"Sign in":"Create the first admin"}),i.jsxs("label",{children:[i.jsx("span",{children:"Username"}),i.jsx("input",{type:"text",value:a,onChange:w=>s(w.target.value),autoComplete:"username",placeholder:"admin"})]}),i.jsxs("label",{children:[i.jsx("span",{children:"Password"}),i.jsx("input",{type:"password",value:o,onChange:w=>l(w.target.value),autoComplete:g?"current-password":"new-password",placeholder:"••••••••"})]}),d?i.jsx("div",{className:"admin-error",children:d}):null,i.jsx("button",{type:"submit",className:"admin-refresh-btn",disabled:c||!a||!o,children:c?"⏳ …":g?"🔐 Sign in":"🔐 Create admin"}),g?null:i.jsx("p",{className:"topbar-account-hint",children:"The first user is always an admin."})]})}):null]})}const RT=[{group:"General",items:[{keys:["?"],description:"Show the shortcut cheatsheet"},{keys:["F1"],description:"Open the Help page"},{keys:["Esc"],description:"Close a dialog or panel"},{keys:["g","c"],description:"Go to Chat"},{keys:["g","o"],description:"Go to Overview"},{keys:["g","t"],description:"Go to Tasks"},{keys:["g","m"],description:"Go to Models"},{keys:["g","s"],description:"Go to System"},{keys:["g","h"],description:"Go to Agent Hub"}]},{group:"Navigation",items:[{keys:["/"],description:"Focus the navigation filter"},{keys:["["],description:"Collapse / expand the navigation drawer"}]}],hB={c:"/chat",o:"/overview",t:"/tasks",m:"/models",s:"/system",h:"/hub"};function pB(e){var a;const t=e;if(!t||typeof t.tagName!="string")return!1;if(t.isContentEditable)return!0;const n=(a=t.getAttribute)==null?void 0:a.call(t,"contenteditable");if(n!=null&&n!=="false")return!0;const r=t.tagName.toLowerCase();return r==="input"||r==="textarea"||r==="select"}function mB({open:e,onClose:t}){const n=x.useId(),r=x.useRef(null),a=x.useRef(null);return x.useEffect(()=>{var l;if(!e)return;a.current=document.activeElement;const s=()=>{var c;return Array.from(((c=r.current)==null?void 0:c.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))??[])};(l=s()[0])==null||l.focus();function o(c){if(c.key==="Escape"){c.stopPropagation(),t();return}if(c.key!=="Tab")return;const u=s();if(u.length===0)return;const d=u[0],f=u[u.length-1];c.shiftKey&&document.activeElement===d?(c.preventDefault(),f.focus()):!c.shiftKey&&document.activeElement===f&&(c.preventDefault(),d.focus())}return document.addEventListener("keydown",o),()=>{var c;document.removeEventListener("keydown",o),(c=a.current)==null||c.focus()}},[e,t]),e?i.jsx("div",{className:"modal-scrim",onClick:t,children:i.jsxs("div",{className:"shortcuts-dialog",role:"dialog","aria-modal":"true","aria-labelledby":n,ref:r,onClick:s=>s.stopPropagation(),children:[i.jsxs("div",{className:"shortcuts-head",children:[i.jsx("h2",{className:"shortcuts-title",id:n,children:"⌨️ Keyboard shortcuts"}),i.jsx("button",{type:"button",className:"btn-secondary",onClick:t,"aria-label":"Close keyboard shortcuts",children:"✕ Close"})]}),RT.map(s=>i.jsxs("section",{className:"shortcuts-group",children:[i.jsx("h3",{className:"shortcuts-group-title",children:s.group}),i.jsx("dl",{className:"shortcuts-list",children:s.items.map(o=>i.jsxs("div",{className:"shortcuts-row",children:[i.jsx("dt",{className:"shortcuts-keys",children:o.keys.map(l=>i.jsx("kbd",{className:"shortcuts-key",children:l},l))}),i.jsx("dd",{className:"shortcuts-description",children:o.description})]},o.description))})]},s.group)),i.jsxs("p",{className:"shortcuts-note",children:["Shortcuts are ignored while you are typing, so ",i.jsx("kbd",{className:"shortcuts-key",children:"?"})," in a question stays a question mark."]})]})}):null}const MT=[{path:"/overview",label:"Overview",icon:"📊"},{path:"/tasks",label:"Tasks",icon:"🚀"},{path:"/models",label:"Models",icon:"🧠"},{path:"/system",label:"System",icon:"⚙️"},{path:"/help",label:"Help",icon:"❓"}],gy=[{label:"Agent Management",items:[{path:"/chat",label:"Chat",icon:"💬"},{path:"/hub",label:"Agent Hub",icon:"🧰"},{path:"/capabilities",label:"Capabilities",icon:"📋"},{path:"/dag",label:"Execution",icon:"🔀"},{path:"/routing",label:"Routing",icon:"🤖"},{path:"/requests",label:"Requests",icon:"📨"},{path:"/hooks",label:"Hooks",icon:"🪝"}]},{label:"Analysis & Monitoring",items:[{path:"/traces",label:"Traces",icon:"🔍"},{path:"/evals",label:"Evals",icon:"🏆"},{path:"/benchmarks",label:"Benchmarks",icon:"📈"},{path:"/costs",label:"Costs",icon:"💰"}]},{label:"Resources",items:[{path:"/memory",label:"Memory",icon:"💾"},{path:"/knowledge",label:"Knowledge",icon:"📚"},{path:"/history",label:"History",icon:"📝"},{path:"/decisions",label:"Decisions",icon:"🧭"},{path:"/env",label:"Env Config",icon:"🔐"},{path:"/process-env",label:"Process Env",icon:"🌱"}]},{label:"Integrations",items:[{path:"/platforms",label:"Platforms",icon:"🌐"},{path:"/gateway",label:"Gateway",icon:"📡"},{path:"/contacts",label:"Contacts",icon:"📇"},{path:"/bedrock",label:"Bedrock",icon:"🪨"}]},{label:"Runtime",items:[{path:"/models/timeline",label:"Timeline",icon:"📅"},{path:"/executions",label:"Executions",icon:"📜"},{path:"/admin",label:"Admin",icon:"🛠️"}]}];function gB(e){const t=e.trim().toLowerCase();return t?gy.map(n=>n.label.toLowerCase().includes(t)?n:{...n,items:n.items.filter(r=>r.label.toLowerCase().includes(t))}).filter(n=>n.items.length>0):gy}function vB({children:e,connected:t,lastUpdated:n,onRefresh:r,refreshing:a=!1}){const[s,o]=x.useState(!1),[l,c]=x.useState(""),[u,d]=x.useState(!1),f=x.useRef(null),h=x.useRef(null),p=x.useRef(0),m=x.useId(),g=Ri(),y=Qx(),v=t?"connected":"reconnecting",S=t?"Connected":"Reconnecting...",w=gB(l),j=()=>o(!1);return x.useEffect(()=>{function k(b){var N,_;if(!(b.metaKey||b.ctrlKey||b.altKey)&&!pB(b.target)){if(b.key==="Escape"){if(u)return;s&&(o(!1),(N=f.current)==null||N.focus());return}if(b.key==="?"){b.preventDefault(),d(!0);return}if(b.key==="F1"){b.preventDefault(),y("/help");return}if(b.key==="/"){b.preventDefault(),(_=h.current)==null||_.focus();return}if(b.key==="["){b.preventDefault(),o(T=>!T);return}if(b.key==="g"){p.current=Date.now();return}if(Date.now()-p.current<1500){const T=hB[b.key.toLowerCase()];p.current=0,T&&(b.preventDefault(),y(T))}}}return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[s,u,y]),x.useEffect(()=>{var k;s&&((k=h.current)==null||k.focus())},[s]),x.useEffect(()=>{j()},[g.pathname]),i.jsxs("div",{className:"layout",children:[i.jsxs("header",{className:"topbar",children:[i.jsx("button",{type:"button",ref:f,className:"topbar-menu","aria-label":"Toggle navigation","aria-controls":"app-nav","aria-expanded":s,onClick:()=>o(k=>!k),children:i.jsx("span",{"aria-hidden":"true",children:"☰"})}),i.jsxs("div",{className:"topbar-brand",children:[i.jsx("span",{className:"topbar-logo","aria-hidden":"true",children:"🤖"}),i.jsx("span",{className:"topbar-title",children:"Agent-Nuvira"})]}),i.jsx("nav",{className:"primary-nav","aria-label":"Primary",children:MT.map(k=>i.jsxs(tS,{to:k.path,end:!0,className:({isActive:b})=>`primary-link${b?" active":""}`,children:[i.jsx("span",{"aria-hidden":"true",children:k.icon})," ",k.label]},k.path))}),i.jsxs("div",{className:"topbar-actions",children:[i.jsxs("button",{type:"button",className:"topbar-action",onClick:r,disabled:a,"aria-busy":a,children:[i.jsx("span",{"aria-hidden":"true",children:"⟳"})," ",a?"Refreshing…":"Refresh"]}),i.jsxs("button",{type:"button",className:"topbar-action","aria-haspopup":"dialog","aria-expanded":u,onClick:()=>d(!0),children:[i.jsx("span",{"aria-hidden":"true",children:"⌨️"})," Shortcuts"]}),i.jsx(dB,{}),i.jsxs("a",{className:"topbar-action",href:"https://www.agent-nuvira.com",target:"_blank",rel:"noopener noreferrer",title:"Agent-Nuvira website — capabilities, commands, docs, setup",children:[i.jsx("span",{"aria-hidden":"true",children:"🌐"})," Website"]}),i.jsx(fB,{})]})]}),i.jsxs("div",{className:"layout-body",children:[s&&i.jsx("div",{className:"nav-scrim",onClick:j,"aria-hidden":"true"}),i.jsxs("nav",{className:`nav${s?" open":""}`,id:"app-nav","aria-label":"Sections",children:[i.jsxs("div",{className:"nav-search",children:[i.jsx("label",{className:"sr-only",htmlFor:m,children:"Filter navigation"}),i.jsx("input",{id:m,ref:h,type:"search",className:"nav-search-input",placeholder:"Search",value:l,onChange:k=>c(k.target.value)})]}),i.jsxs("div",{className:"nav-links",children:[w.map(k=>i.jsxs("section",{className:"nav-group",children:[i.jsx("h2",{className:"nav-group-title",children:k.label}),k.items.map(b=>i.jsxs(tS,{to:b.path,end:b.path==="/",className:({isActive:N})=>`nav-link${N?" active":""}`,children:[i.jsx("span",{className:"nav-icon","aria-hidden":"true",children:b.icon}),b.label]},b.path))]},k.label)),w.length===0&&i.jsxs("p",{className:"nav-empty",children:["No sections match “",l,"”."]})]}),i.jsxs("div",{className:"nav-footer",children:[i.jsx("span",{className:`status-dot ${v}`}),i.jsx("span",{className:"status-text",children:S}),i.jsx("span",{className:"last-updated",children:n})]})]}),i.jsx("main",{className:"main",children:e})]}),i.jsx(mB,{open:u,onClose:()=>d(!1)})]})}function IT(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var a=e.length;for(t=0;t<a;t++)e[t]&&(n=IT(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Qe(){for(var e,t,n=0,r="",a=arguments.length;n<a;n++)(e=arguments[n])&&(t=IT(e))&&(r&&(r+=" "),r+=t);return r}var yB=Array.isArray,Hn=yB,bB=typeof li=="object"&&li&&li.Object===Object&&li,$T=bB,xB=$T,wB=typeof self=="object"&&self&&self.Object===Object&&self,kB=xB||wB||Function("return this")(),pa=kB,SB=pa,jB=SB.Symbol,Xu=jB,oS=Xu,LT=Object.prototype,NB=LT.hasOwnProperty,EB=LT.toString,tc=oS?oS.toStringTag:void 0;function _B(e){var t=NB.call(e,tc),n=e[tc];try{e[tc]=void 0;var r=!0}catch{}var a=EB.call(e);return r&&(t?e[tc]=n:delete e[tc]),a}var CB=_B,AB=Object.prototype,TB=AB.toString;function OB(e){return TB.call(e)}var PB=OB,lS=Xu,RB=CB,MB=PB,IB="[object Null]",$B="[object Undefined]",cS=lS?lS.toStringTag:void 0;function LB(e){return e==null?e===void 0?$B:IB:cS&&cS in Object(e)?RB(e):MB(e)}var Ba=LB;function DB(e){return e!=null&&typeof e=="object"}var za=DB,BB=Ba,zB=za,FB="[object Symbol]";function UB(e){return typeof e=="symbol"||zB(e)&&BB(e)==FB}var kl=UB,WB=Hn,HB=kl,GB=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,qB=/^\w*$/;function KB(e,t){if(WB(e))return!1;var n=typeof e;return n=="number"||n=="symbol"||n=="boolean"||e==null||HB(e)?!0:qB.test(e)||!GB.test(e)||t!=null&&e in Object(t)}var ew=KB;function VB(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Mi=VB;const Sl=tt(Mi);var YB=Ba,XB=Mi,QB="[object AsyncFunction]",ZB="[object Function]",JB="[object GeneratorFunction]",ez="[object Proxy]";function tz(e){if(!XB(e))return!1;var t=YB(e);return t==ZB||t==JB||t==QB||t==ez}var tw=tz;const De=tt(tw);var nz=pa,rz=nz["__core-js_shared__"],az=rz,og=az,uS=function(){var e=/[^.]+$/.exec(og&&og.keys&&og.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function iz(e){return!!uS&&uS in e}var sz=iz,oz=Function.prototype,lz=oz.toString;function cz(e){if(e!=null){try{return lz.call(e)}catch{}try{return e+""}catch{}}return""}var DT=cz,uz=tw,dz=sz,fz=Mi,hz=DT,pz=/[\\^$.*+?()[\]{}|]/g,mz=/^\[object .+?Constructor\]$/,gz=Function.prototype,vz=Object.prototype,yz=gz.toString,bz=vz.hasOwnProperty,xz=RegExp("^"+yz.call(bz).replace(pz,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function wz(e){if(!fz(e)||dz(e))return!1;var t=uz(e)?xz:mz;return t.test(hz(e))}var kz=wz;function Sz(e,t){return e==null?void 0:e[t]}var jz=Sz,Nz=kz,Ez=jz;function _z(e,t){var n=Ez(e,t);return Nz(n)?n:void 0}var Us=_z,Cz=Us,Az=Cz(Object,"create"),Mp=Az,dS=Mp;function Tz(){this.__data__=dS?dS(null):{},this.size=0}var Oz=Tz;function Pz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Rz=Pz,Mz=Mp,Iz="__lodash_hash_undefined__",$z=Object.prototype,Lz=$z.hasOwnProperty;function Dz(e){var t=this.__data__;if(Mz){var n=t[e];return n===Iz?void 0:n}return Lz.call(t,e)?t[e]:void 0}var Bz=Dz,zz=Mp,Fz=Object.prototype,Uz=Fz.hasOwnProperty;function Wz(e){var t=this.__data__;return zz?t[e]!==void 0:Uz.call(t,e)}var Hz=Wz,Gz=Mp,qz="__lodash_hash_undefined__";function Kz(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Gz&&t===void 0?qz:t,this}var Vz=Kz,Yz=Oz,Xz=Rz,Qz=Bz,Zz=Hz,Jz=Vz;function jl(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}jl.prototype.clear=Yz;jl.prototype.delete=Xz;jl.prototype.get=Qz;jl.prototype.has=Zz;jl.prototype.set=Jz;var eF=jl;function tF(){this.__data__=[],this.size=0}var nF=tF;function rF(e,t){return e===t||e!==e&&t!==t}var nw=rF,aF=nw;function iF(e,t){for(var n=e.length;n--;)if(aF(e[n][0],t))return n;return-1}var Ip=iF,sF=Ip,oF=Array.prototype,lF=oF.splice;function cF(e){var t=this.__data__,n=sF(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():lF.call(t,n,1),--this.size,!0}var uF=cF,dF=Ip;function fF(e){var t=this.__data__,n=dF(t,e);return n<0?void 0:t[n][1]}var hF=fF,pF=Ip;function mF(e){return pF(this.__data__,e)>-1}var gF=mF,vF=Ip;function yF(e,t){var n=this.__data__,r=vF(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var bF=yF,xF=nF,wF=uF,kF=hF,SF=gF,jF=bF;function Nl(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Nl.prototype.clear=xF;Nl.prototype.delete=wF;Nl.prototype.get=kF;Nl.prototype.has=SF;Nl.prototype.set=jF;var $p=Nl,NF=Us,EF=pa,_F=NF(EF,"Map"),rw=_F,fS=eF,CF=$p,AF=rw;function TF(){this.size=0,this.__data__={hash:new fS,map:new(AF||CF),string:new fS}}var OF=TF;function PF(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var RF=PF,MF=RF;function IF(e,t){var n=e.__data__;return MF(t)?n[typeof t=="string"?"string":"hash"]:n.map}var Lp=IF,$F=Lp;function LF(e){var t=$F(this,e).delete(e);return this.size-=t?1:0,t}var DF=LF,BF=Lp;function zF(e){return BF(this,e).get(e)}var FF=zF,UF=Lp;function WF(e){return UF(this,e).has(e)}var HF=WF,GF=Lp;function qF(e,t){var n=GF(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var KF=qF,VF=OF,YF=DF,XF=FF,QF=HF,ZF=KF;function El(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}El.prototype.clear=VF;El.prototype.delete=YF;El.prototype.get=XF;El.prototype.has=QF;El.prototype.set=ZF;var aw=El,BT=aw,JF="Expected a function";function iw(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(JF);var n=function(){var r=arguments,a=t?t.apply(this,r):r[0],s=n.cache;if(s.has(a))return s.get(a);var o=e.apply(this,r);return n.cache=s.set(a,o)||s,o};return n.cache=new(iw.Cache||BT),n}iw.Cache=BT;var zT=iw;const eU=tt(zT);var tU=zT,nU=500;function rU(e){var t=tU(e,function(r){return n.size===nU&&n.clear(),r}),n=t.cache;return t}var aU=rU,iU=aU,sU=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,oU=/\\(\\)?/g,lU=iU(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(sU,function(n,r,a,s){t.push(a?s.replace(oU,"$1"):r||n)}),t}),cU=lU;function uU(e,t){for(var n=-1,r=e==null?0:e.length,a=Array(r);++n<r;)a[n]=t(e[n],n,e);return a}var sw=uU,hS=Xu,dU=sw,fU=Hn,hU=kl,pS=hS?hS.prototype:void 0,mS=pS?pS.toString:void 0;function FT(e){if(typeof e=="string")return e;if(fU(e))return dU(e,FT)+"";if(hU(e))return mS?mS.call(e):"";var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var pU=FT,mU=pU;function gU(e){return e==null?"":mU(e)}var UT=gU,vU=Hn,yU=ew,bU=cU,xU=UT;function wU(e,t){return vU(e)?e:yU(e,t)?[e]:bU(xU(e))}var WT=wU,kU=kl;function SU(e){if(typeof e=="string"||kU(e))return e;var t=e+"";return t=="0"&&1/e==-1/0?"-0":t}var Dp=SU,jU=WT,NU=Dp;function EU(e,t){t=jU(t,e);for(var n=0,r=t.length;e!=null&&n<r;)e=e[NU(t[n++])];return n&&n==r?e:void 0}var ow=EU,_U=ow;function CU(e,t,n){var r=e==null?void 0:_U(e,t);return r===void 0?n:r}var HT=CU;const Sr=tt(HT);function AU(e){return e==null}var TU=AU;const Ze=tt(TU);var OU=Ba,PU=Hn,RU=za,MU="[object String]";function IU(e){return typeof e=="string"||!PU(e)&&RU(e)&&OU(e)==MU}var $U=IU;const Ms=tt($U);var GT={exports:{}},st={};/**
68
68
  * @license React
69
69
  * react-is.production.min.js
70
70
  *
@@ -207,4 +207,4 @@ ${r}`);return n&&t.push(n),t}function Sye(e){return/(^|\n)\s*(PASS|FAIL|✅|❌|
207
207
  `).map(L=>L.trim()).filter(Boolean);if(!u.trim()||P.length===0){o("A tag and at least one file or folder path are required.");return}m(!0);try{const L=await K.knowledgeIngest(u,P);if(!L.ok)o(L.error||"Ingest failed.");else{const M=(z=L.skipped)!=null&&z.length?` Skipped: ${L.skipped.map(D=>`${mv(D.path)} (${D.reason})`).join("; ")}`:"";c(`Ingested ${L.files??0} document(s) / ${L.chunks??0} chunk(s) under '${L.tag}'.${M}`),h(""),await _()}}finally{m(!1)}},[u,f,_]),A=x.useCallback(async()=>{if(o(null),j(null),!g.trim()||!v.trim()){o("A tag and a question are required.");return}b(!0);try{const P=await K.knowledgeQuery(g,v);P.ok?j(P.hits??[]):o(P.error||"Query failed.")}finally{b(!1)}},[g,v]),O=x.useCallback(async P=>{o(null),c(null);const z=await K.knowledgeForget(P);z.ok?c(`Removed knowledge tag '${P}'.`):o(z.error||`Could not remove '${P}'.`),await _()},[_]);return i.jsxs("div",{children:[i.jsx(Re,{icon:"📚",title:"Knowledge Base",description:"Tag your own documents once; answer questions scoped to a tag. The data part comes from your documents, the general part from the model."}),i.jsxs("div",{className:"env-var-header",children:[i.jsx("span",{className:"env-var-title",children:"Documents and vectors live in ~/.nuvira/memory — never in a repository or package."}),i.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void _(),children:"↻ Refresh"})]}),e.authenticated?null:i.jsx("div",{className:"admin-hint",children:e.configured?"Log in to view or manage knowledge tags.":"Set up an admin account to manage knowledge tags."}),s?i.jsx("div",{className:"admin-error",children:s}):null,l?i.jsx("div",{className:"admin-hint",children:l}):null,i.jsx("h2",{className:"section-title",children:"Tags"}),r&&r.length===0?i.jsx("div",{className:"admin-hint",children:"No knowledge tags yet. Ingest a document below to create one."}):null,r&&r.length>0?i.jsx("div",{className:"admin-table-wrapper",children:i.jsxs("table",{className:"admin-table",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Tag"}),i.jsx("th",{children:"Chunks"}),i.jsx("th",{children:"Documents"}),N?i.jsx("th",{}):null]})}),i.jsx("tbody",{children:r.map(P=>i.jsxs("tr",{children:[i.jsx("td",{children:P.tag}),i.jsx("td",{children:P.chunkCount}),i.jsx("td",{children:P.documents.map(z=>i.jsxs("div",{title:z.path,children:[mv(z.path)," (",z.chunks," chunk",z.chunks===1?"":"s",")"]},z.path))}),N?i.jsx("td",{children:i.jsx("button",{className:"admin-mini-danger",type:"button",onClick:()=>void O(P.tag),"aria-label":`Remove knowledge tag ${P.tag}`,children:"Forget"})}):null]},P.tag))})]})}):null,N?i.jsxs(i.Fragment,{children:[i.jsx("h2",{className:"section-title",children:"Ingest under a tag"}),i.jsx("div",{className:"admin-hint",children:"One file or folder path per line (PDF, DOCX, XLSX, PPTX, Markdown, CSV, JSON, plain text). Tags are normalized: “Dheeraj Health Report” becomes “dheeraj-health-report”."}),i.jsxs("div",{className:"admin-gate-form",children:[i.jsx("input",{className:"admin-input",type:"text",placeholder:"tag (e.g. dheeraj-health-report)",value:u,onChange:P=>d(P.target.value),"aria-label":"Knowledge tag"}),i.jsx("textarea",{className:"admin-input",rows:3,placeholder:`/path/to/labs.pdf
208
208
  /path/to/notes/`,value:f,onChange:P=>h(P.target.value),"aria-label":"Paths to ingest"}),i.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void T(),disabled:p,children:p?"Ingesting…":"Ingest"})]})]}):null,i.jsx("h2",{className:"section-title",children:"Ask a tagged knowledge base"}),i.jsxs("div",{className:"admin-gate-form",children:[i.jsx("input",{className:"admin-input",type:"text",placeholder:"tag",list:"knowledge-tags",value:g,onChange:P=>y(P.target.value),"aria-label":"Tag to query"}),i.jsx("datalist",{id:"knowledge-tags",children:(r??[]).map(P=>i.jsx("option",{value:P.tag},P.tag))}),i.jsx("input",{className:"admin-input",type:"text",placeholder:"what is my LDL and how do I lower it",value:v,onChange:P=>S(P.target.value),"aria-label":"Question"}),i.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void A(),disabled:k,children:k?"Searching…":"Query"})]}),w&&w.length===0?i.jsx("div",{className:"admin-hint",children:"No passages matched that tag — check the tag name, or ingest documents first."}):null,w&&w.length>0?i.jsx("div",{children:w.map((P,z)=>i.jsxs("div",{className:"admin-summary-card",children:[i.jsxs("div",{className:"admin-summary-label",children:[mv(P.sourcePath)," · chunk ",P.chunkIndex+1," · sim ",P.similarity.toFixed(3)]}),i.jsx("div",{className:"admin-summary-value",style:{whiteSpace:"pre-wrap",fontWeight:400},children:P.text.slice(0,600)})]},`${P.sourcePath}-${P.chunkIndex}-${z}`))}):null]})}const bbe=7*24*60*60*1e3;function xbe(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function wbe({data:e}){const[t,n]=x.useState(null),[r,a]=x.useState(!1),[s,o]=x.useState(null),l=t??(e==null?void 0:e.history),c=x.useCallback(async(d,f={})=>{a(!0),o(null);const h=await K.clearHistory(d,f);h.ok?o(d==="all"?`Removed ${h.removed??0} conversation(s).`:d==="older"?h.removed?`Removed ${h.removed} conversation(s) older than a week.`:"Nothing older than a week — nothing removed.":`Removed ${h.removed?h.removed:0} conversation(s).`):o(h.error||"Could not delete that.");const p=await K.fetchHistory();p&&n(p),a(!1)},[]);if(!l)return i.jsxs(i.Fragment,{children:[i.jsx(Re,{icon:"📝",title:"Conversation History"}),i.jsx("div",{className:"loading-state",children:i.jsx("p",{children:"Loading history..."})})]});const u=l.recent||[];return i.jsxs(i.Fragment,{children:[i.jsx(Re,{icon:"📝",title:"Conversation History"}),i.jsxs("div",{className:"history-stats",children:[i.jsxs("span",{className:"history-count",children:["Total: ",i.jsx("strong",{children:l.total})," sessions"]}),i.jsxs("div",{className:"admin-row-actions",children:[i.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",disabled:r,title:"Delete only conversations started more than 7 days ago",onClick:()=>void c("older",{olderThanMs:bbe}),children:"🗑️ Forget older than a week"}),i.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",disabled:r||l.total===0,onClick:()=>{window.confirm("Delete ALL stored conversations? This cannot be undone.")&&c("all")},children:"🗑️ Clear all history"})]})]}),s?i.jsx("div",{className:"env-var-notice",children:s}):null,i.jsx("div",{className:"history-list",children:u.length===0?i.jsx("div",{className:"empty-state",children:"No conversations recorded yet."}):u.map(d=>i.jsxs("div",{className:"history-item",children:[i.jsx("div",{className:"history-summary",children:d.summary||"Untitled"}),i.jsxs("div",{className:"history-meta",children:[i.jsxs("span",{children:["📅 ",xbe(d.startedAt)]}),i.jsxs("span",{children:["🤖 ",d.provider||"--"]}),i.jsxs("span",{children:["💬 ",d.messageCount||0," msgs"]}),d.tags&&d.tags.length>0&&i.jsxs("span",{children:["🏷️ ",d.tags.map(f=>i.jsx("span",{className:"history-tag",children:f},f))]}),i.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",disabled:r,"aria-label":`Forget conversation ${d.summary||d.id}`,onClick:()=>void c("session",{id:d.id}),children:"🗑️ Forget"})]})]},d.id))})]})}function kbe(e){const t=Math.max(0,Math.round((Date.now()-e)/6e4));if(t<1)return"just now";if(t<60)return`${t}m ago`;const n=Math.round(t/60);return n<24?`${n}h ago`:`${Math.round(n/24)}d ago`}function Sbe(){const[e,t]=x.useState([]),[n,r]=x.useState(""),[a,s]=x.useState(""),[o,l]=x.useState(null),[c,u]=x.useState(!1),[d,f]=x.useState(!1),[h,p]=x.useState(null),[m,g]=x.useState(null),[y,v]=x.useState(""),[S,w]=x.useState(""),j=x.useCallback(async(_,T)=>{const A=await K.fetchDecisions(_,T);l(A),u(!0)},[]);x.useEffect(()=>{let _=!0;return K.listProjects().then(T=>{var O,P;if(!_)return;t(T);const A=((O=T.find(z=>z.kind==="cwd"))==null?void 0:O.path)??((P=T[0])==null?void 0:P.path)??"";r(A),j(A)}),()=>{_=!1}},[j]);const k=x.useCallback(()=>{n&&j(n,a.trim()||void 0)},[n,a,j]),b=x.useCallback(async _=>{if(!n||!y.trim())return;f(!0),p(null),await K.reviseDecision(n,_,y.trim(),S.trim()||void 0)?(p(`Revised ${_} — the previous answer is kept in its history.`),g(null),v(""),w(""),await j(n,a.trim()||void 0)):p("Could not revise that decision — it may no longer exist."),f(!1)},[n,y,S,a,j]),N=(o==null?void 0:o.decisions)??[];return i.jsxs(i.Fragment,{children:[i.jsx(Re,{icon:"🧭",title:"Decisions",description:"The choices the agent asked YOU to make (ask_user), kept so you can refer back and revise them. Written to the project's .nuvira/decisions.jsonl — never a substitute for asking."}),c?o===null?i.jsxs("p",{className:"memory-namespace-note",children:["Decision data is unavailable — this dashboard server has no ",i.jsx("code",{children:"/api/decisions"})," endpoint."]}):i.jsxs(i.Fragment,{children:[i.jsx("h2",{className:"section-subtitle",children:"Workspace"}),e.length>1?i.jsxs("label",{className:"memory-backend",children:["Project:"," ",i.jsx("select",{value:n,onChange:_=>{r(_.target.value),j(_.target.value,a.trim()||void 0)},children:e.map(_=>i.jsxs("option",{value:_.path,children:[_.name," (",_.kind,")"]},_.path))})]}):i.jsx("p",{className:"memory-backend",children:i.jsx("code",{children:o.dir})}),i.jsxs("div",{className:"admin-row-actions",children:[i.jsx("input",{type:"search",value:a,placeholder:"Find decisions relevant to an ask…","aria-label":"Search decisions relevant to an ask",onChange:_=>s(_.target.value),onKeyDown:_=>{_.key==="Enter"&&k()}}),i.jsx("button",{className:"admin-mini-btn",type:"button",disabled:!n,onClick:k,children:"🔎 Search"}),o.relevant?i.jsx("button",{className:"admin-mini-btn",type:"button",disabled:!n,onClick:()=>{s(""),j(n)},children:"✕ Clear"}):null]}),h?i.jsx("div",{className:"env-var-notice",children:h}):null,i.jsx("h2",{className:"section-subtitle",children:o.relevant?`Relevant decisions (${N.length})`:`Recorded decisions (${N.length})`}),N.length===0?i.jsx("p",{className:"memory-namespace-note",children:o.relevant?"No recorded decision matches that ask.":"None yet — a decision is recorded when the agent has to ask you one."}):i.jsx("div",{className:"memory-list",children:N.map(_=>{var T;return i.jsxs("div",{className:"memory-item",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"memory-project",children:[_.status==="revised"?"✏️":"✅"," ",_.question]}),i.jsxs("div",{className:"memory-count",children:["→ ",_.answer||"(none)"," · ",kbe(_.at)," · ",_.source," · ",_.id,_.status==="revised"?` · revised ${((T=_.revisions)==null?void 0:T.length)??0}×`:""]}),_.choices&&_.choices.length>0?i.jsxs("div",{className:"memory-count",children:["offered: ",_.choices.join(" | ")]}):null]}),m===_.id?i.jsxs("div",{children:[i.jsx("input",{type:"text",value:y,placeholder:"New answer","aria-label":`New answer for ${_.question}`,onChange:A=>v(A.target.value)}),i.jsx("input",{type:"text",value:S,placeholder:"Why it changed (optional)","aria-label":`Note for ${_.question}`,onChange:A=>w(A.target.value)}),i.jsx("button",{className:"admin-mini-btn",type:"button",disabled:d||!y.trim(),onClick:()=>void b(_.id),children:"💾 Save"}),i.jsx("button",{className:"admin-mini-btn",type:"button",disabled:d,onClick:()=>{g(null),v(""),w("")},children:"✕ Cancel"})]}):i.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>{g(_.id),v(_.answer),w("")},children:"✏️ Revise"})]},_.id)})})]}):i.jsx("div",{className:"loading-state",children:i.jsx("p",{children:"Loading decisions…"})})]})}function jbe({onFetch:e,onClear:t,onExport:n}){const[r,a]=x.useState([]),[s,o]=x.useState(!1),[l,c]=x.useState(""),[u,d]=x.useState(""),[f,h]=x.useState(null),[p,m]=x.useState(null);x.useEffect(()=>{g()},[l,u]);const g=async()=>{o(!0);try{const j=await e({skillName:l||void 0,status:u||void 0,limit:100});a(j);const k=j.length,b=j.filter(T=>T.status==="success").length,N=j.filter(T=>T.status==="failure").length,_=k>0?Math.round(j.reduce((T,A)=>T+A.durationMs,0)/k):0;m({total:k,success:b,failure:N,avgDuration:_})}catch(j){console.error("Failed to fetch execution history:",j)}finally{o(!1)}},y=async j=>{if(n)try{const k=await n(j),b=new Blob([k],{type:j==="json"?"application/json":"text/csv"}),N=URL.createObjectURL(b),_=document.createElement("a");_.href=N,_.download=`execution-history.${j}`,_.click(),URL.revokeObjectURL(N)}catch(k){console.error("Failed to export history:",k)}},v=async()=>{if(t&&confirm("Are you sure you want to clear all execution history?"))try{await t(),a([]),m(null)}catch(j){console.error("Failed to clear history:",j)}},S=j=>{switch(j){case"success":return"✅";case"failure":return"❌";case"timeout":return"⏰";case"rejected":return"🚫";case"error":return"💥";default:return"❓"}},w=j=>{switch(j){case"python":return"🐍";case"node":return"🟢";case"shell":return"🖥️";case"ruby":return"💎";case"go":return"🔵";case"rust":return"🦀";default:return"📜"}};return i.jsxs("div",{className:"execution-history",children:[i.jsx(Re,{icon:"📜",title:"Execution History",actions:i.jsxs("div",{className:"execution-history-actions",children:[i.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>y("json"),children:"📥 Export JSON"}),i.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>y("csv"),children:"📥 Export CSV"}),t&&i.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",onClick:v,children:"🗑️ Clear"})]})}),p&&i.jsxs("div",{className:"execution-history-stats",children:[i.jsxs("div",{className:"stat-item",children:[i.jsx("span",{className:"stat-value",children:p.total}),i.jsx("span",{className:"stat-label",children:"Total"})]}),i.jsxs("div",{className:"stat-item stat-success",children:[i.jsx("span",{className:"stat-value",children:p.success}),i.jsx("span",{className:"stat-label",children:"Success"})]}),i.jsxs("div",{className:"stat-item stat-failure",children:[i.jsx("span",{className:"stat-value",children:p.failure}),i.jsx("span",{className:"stat-label",children:"Failed"})]}),i.jsxs("div",{className:"stat-item",children:[i.jsxs("span",{className:"stat-value",children:[p.avgDuration,"ms"]}),i.jsx("span",{className:"stat-label",children:"Avg Duration"})]})]}),i.jsxs("div",{className:"execution-history-filters",children:[i.jsx("input",{className:"env-var-input",type:"text","aria-label":"Filter by skill name",placeholder:"Filter by skill name...",value:l,onChange:j=>c(j.target.value)}),i.jsxs("select",{className:"env-var-input","aria-label":"Filter by status",value:u,onChange:j=>d(j.target.value),children:[i.jsx("option",{value:"",children:"All statuses"}),i.jsx("option",{value:"success",children:"Success"}),i.jsx("option",{value:"failure",children:"Failure"}),i.jsx("option",{value:"timeout",children:"Timeout"}),i.jsx("option",{value:"rejected",children:"Rejected"}),i.jsx("option",{value:"error",children:"Error"})]})]}),i.jsx("div",{className:"execution-history-list",children:s?i.jsx("div",{className:"execution-history-empty",children:"Loading..."}):r.length===0?i.jsx("div",{className:"execution-history-empty",children:"No execution history found. Execute a skill to see results here."}):r.map(j=>i.jsxs("div",{className:`execution-history-entry ${j.status}`,onClick:()=>h((f==null?void 0:f.id)===j.id?null:j),children:[i.jsxs("div",{className:"entry-header",children:[i.jsx("span",{className:"entry-icon",children:S(j.status)}),i.jsx("span",{className:"entry-skill",children:j.skillName}),i.jsxs("span",{className:"entry-runtime",children:[w(j.runtime)," ",j.runtime]}),i.jsxs("span",{className:"entry-duration",children:[j.durationMs,"ms"]}),i.jsx("span",{className:"entry-time",children:new Date(j.timestamp).toLocaleString()}),i.jsx("span",{className:"entry-expand",children:(f==null?void 0:f.id)===j.id?"▼":"▶"})]}),(f==null?void 0:f.id)===j.id&&i.jsxs("div",{className:"entry-details",children:[i.jsxs("div",{className:"entry-detail-row",children:[i.jsx("span",{className:"detail-label",children:"Status:"}),i.jsx("span",{className:"detail-value",children:j.status})]}),i.jsxs("div",{className:"entry-detail-row",children:[i.jsx("span",{className:"detail-label",children:"Runtime:"}),i.jsx("span",{className:"detail-value",children:j.runtime})]}),i.jsxs("div",{className:"entry-detail-row",children:[i.jsx("span",{className:"detail-label",children:"Duration:"}),i.jsxs("span",{className:"detail-value",children:[j.durationMs,"ms"]})]}),j.exitCode!==void 0&&i.jsxs("div",{className:"entry-detail-row",children:[i.jsx("span",{className:"detail-label",children:"Exit Code:"}),i.jsx("span",{className:"detail-value",children:j.exitCode})]}),j.error&&i.jsxs("div",{className:"entry-detail-row",children:[i.jsx("span",{className:"detail-label",children:"Error:"}),i.jsx("span",{className:"detail-value entry-error",children:j.error})]}),j.command&&i.jsxs("div",{className:"entry-detail-row",children:[i.jsx("span",{className:"detail-label",children:"Command:"}),i.jsx("code",{className:"detail-value",children:j.command})]})]})]},j.id))})]})}function Nbe({envVars:e,onSave:t,onDelete:n,onTest:r,readOnly:a=!1}){const[s,o]=x.useState(null),[l,c]=x.useState(""),[u,d]=x.useState(!1),[f,h]=x.useState(""),[p,m]=x.useState(""),[g,y]=x.useState(null),[v,S]=x.useState({}),w=[...e].sort((N,_)=>N.requiredBy&&!_.requiredBy?-1:!N.requiredBy&&_.requiredBy?1:N.name.localeCompare(_.name)),j=N=>{t(N,l),o(null),c("")},k=()=>{f&&p&&(t(f,p),h(""),m(""),d(!1))},b=async N=>{if(r){y(N);try{const _=await r(N);S(T=>({...T,[N]:_}))}catch{S(_=>({..._,[N]:!1}))}finally{y(null)}}};return i.jsxs("div",{className:"env-var-editor",children:[i.jsxs("div",{className:"env-var-header",children:[i.jsx("h2",{className:"env-var-title",children:"🔐 Environment Variables"}),!a&&i.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>d(!u),children:u?"✕ Cancel":"+ Add Variable"})]}),u&&!a&&i.jsxs("div",{className:"env-var-add-form",children:[i.jsx("input",{className:"env-var-input",type:"text",placeholder:"Variable name (e.g., MY_API_KEY)",value:f,onChange:N=>h(N.target.value)}),i.jsx("input",{className:"env-var-input",type:"password",placeholder:"Value",value:p,onChange:N=>m(N.target.value)}),i.jsx("button",{className:"admin-refresh-btn",type:"button",disabled:!f||!p,onClick:k,children:"💾 Save"})]}),i.jsx("div",{className:"env-var-list",children:w.length===0?i.jsx("div",{className:"env-var-empty",children:"No environment variables configured. Add one to get started."}):w.map(N=>i.jsxs("div",{className:`env-var-row ${N.isSet?"env-var-set":"env-var-missing"} ${N.isProviderCredential?"env-var-blocked":""}`,children:[i.jsxs("div",{className:"env-var-row-header",children:[i.jsxs("span",{className:"env-var-name",children:[N.name,N.requiredBy&&i.jsxs("span",{className:"env-var-required-badge",children:["required by ",N.requiredBy]}),N.isProviderCredential&&i.jsx("span",{className:"env-var-blocked-badge",children:"🔒 provider credential (blocked)"})]}),i.jsx("span",{className:"env-var-status",children:N.isSet?"✅ Set":"❌ Not set"})]}),N.description&&i.jsx("div",{className:"env-var-description",children:N.description}),s===N.name?i.jsxs("div",{className:"env-var-edit",children:[i.jsx("input",{className:"env-var-input",type:"password",value:l,onChange:_=>c(_.target.value),placeholder:"Enter new value..."}),i.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>j(N.name),children:"💾 Save"}),i.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>o(null),children:"Cancel"})]}):i.jsxs("div",{className:"env-var-actions",children:[!a&&!N.isProviderCredential&&i.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>{o(N.name),c("")},children:"✏️ Edit"}),r&&i.jsx("button",{className:"admin-mini-btn",type:"button",disabled:g===N.name,onClick:()=>b(N.name),children:g===N.name?"⏳ Testing...":"🧪 Test"}),!a&&i.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",onClick:()=>n(N.name),children:"🗑️ Delete"}),v[N.name]!==void 0&&i.jsx("span",{className:`env-var-test-result ${v[N.name]?"env-var-test-pass":"env-var-test-fail"}`,children:v[N.name]?"✅ Valid":"❌ Invalid"})]})]},N.name))}),i.jsx("div",{className:"env-var-help",children:i.jsxs("p",{children:[i.jsx("strong",{children:"Tip:"})," Environment variables are stored in ",i.jsx("code",{children:"~/.nuvira/.env"})," and injected into skill executions. Provider credentials (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.) are automatically blocked from skill execution for security."]})})]})}function Ebe(){const[e,t]=x.useState({configured:!1,authenticated:!1,role:null}),n=Vr(),[r,a]=x.useState([]),[s,o]=x.useState(!0),[l,c]=x.useState(null),[u,d]=x.useState(null),f=e.authenticated&&(e.role==="admin"||e.role==="operator"),h=x.useCallback(async()=>{o(!0);const y=await K.fetchSkillEnv();a(y),o(!1)},[]);x.useEffect(()=>{K.fetchAdminAuthStatus().then(y=>{t(y?{configured:y.configured,authenticated:y.authenticated,role:y.role??null}:{configured:!1,authenticated:!1,role:null})}),h()},[h,n]);const p=x.useCallback(async(y,v)=>{var j;c(null),d(null);const S=await K.saveSecrets({[y]:v}),w=(j=S.refused)==null?void 0:j.find(k=>k.name===y);!S.ok||w?c(w?_be(y,w.reason):S.error||`Could not save ${y}.`):d(`Saved ${y}.`),await h()},[h]),m=x.useCallback(async y=>{c(null),d(null);const v=await K.deleteSkillEnvVar(y);v.ok?d(v.removed?`Deleted ${y}.`:`${y} was not stored in the env file.`):c(v.error||`Could not delete ${y}.`),await h()},[h]),g=x.useCallback(async y=>{const v=await K.testSkillEnvVar(y);return v.ok?(c(null),d(v.detail||`${y}: ${v.usable?"usable by skills":"not usable by skills"}`),v.usable===!0):(c(v.error||`Could not test ${y}.`),!1)},[]);return i.jsxs("div",{children:[i.jsx(Re,{icon:"🔐",title:"Skill Environment Variables"}),i.jsxs("div",{className:"env-var-header",children:[i.jsx("span",{className:"env-var-title",children:"Values are masked; only names and set/unset state are shown."}),i.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void h(),children:"↻ Refresh"})]}),i.jsxs("div",{className:"admin-hint",children:["Secrets here are injected into skill executions that declare them (",i.jsx("code",{children:"required_environment_variables"}),"). Provider credentials are listed but locked — they belong to provider setup, and skills never receive them."]}),e.authenticated?null:i.jsx("div",{className:"admin-hint",children:e.configured?"Log in to view or edit skill secrets.":"Set up an admin account to manage skill secrets."}),e.authenticated&&!f?i.jsx("div",{className:"admin-hint",children:"Read-only — admins and operators can change these values."}):null,l?i.jsx("div",{className:"env-var-notice env-var-notice-error",children:l}):null,u?i.jsx("div",{className:"env-var-notice",children:u}):null,s?i.jsx("div",{className:"loading-state",children:"Loading…"}):i.jsx(Nbe,{envVars:r,onSave:(y,v)=>void p(y,v),onDelete:y=>void m(y),onTest:g,readOnly:!f})]})}function _be(e,t){switch(t){case"provider-credential":return`${e} is a provider credential — configure it in provider setup instead. Skills never receive it.`;case"invalid-name":return`${e} is not a valid environment variable name.`;case"write-failed":return`${e} could not be written to the env file.`;default:return`${e} was not saved (${t}).`}}const Cbe=[{id:"turn",title:"Turn behaviour",blurb:"How each turn runs. Unset means nobody has asked for anything, which is not the same as asking for no."},{id:"observability",title:"Observability",blurb:"What a run records about itself. Both are off by default and off unless asked for."},{id:"hooks",title:"Tool hooks",blurb:"A command run around every tool call, with the call on stdin as JSON. For a phase, a value here REPLACES the hooks declared in tools.hooks."}];function Abe(){const[e,t]=x.useState({configured:!1,authenticated:!1,role:null}),n=Vr(),[r,a]=x.useState([]),[s,o]=x.useState(!0),[l,c]=x.useState(null),[u,d]=x.useState(null),[f,h]=x.useState({}),[p,m]=x.useState(null),g=e.authenticated&&(e.role==="admin"||e.role==="operator"),y=x.useCallback(async()=>{o(!0),a(await K.fetchProcessEnv()),o(!1)},[]);x.useEffect(()=>{K.fetchAdminAuthStatus().then(w=>{t(w?{configured:w.configured,authenticated:w.authenticated,role:w.role??null}:{configured:!1,authenticated:!1,role:null})}),y()},[y,n]);const v=x.useCallback(async(w,j)=>{m(w),c(null),d(null);const k=await K.saveProcessEnvVar(w,j);if(!k.ok||!k.row)c(k.error||`Could not set ${w}.`);else{const b=k.row;a(N=>N.map(_=>_.name===b.name?b:_)),h(N=>({...N,[w]:""})),d(`${w} = ${b.fileValue}. Takes effect on the next turn; the dashboard picked it up immediately.`)}m(null)},[]),S=x.useCallback(async w=>{m(w),c(null),d(null);const j=await K.deleteProcessEnvVar(w);if(!j.ok||!j.row)c(j.error||`Could not unset ${w}.`);else{const k=j.row;a(b=>b.map(N=>N.name===k.name?k:N)),h(b=>({...b,[w]:""})),d(j.removed?`${w} removed from the env file. ${k.unsetMeans}`:`${w} had no line in the env file. ${k.unsetMeans}`)}m(null)},[]);return i.jsxs("div",{children:[i.jsx(Re,{icon:"🌱",title:"Process Environment"}),i.jsxs("div",{className:"env-var-header",children:[i.jsx("span",{className:"env-var-title",children:"These are the switches Agent-Nuvira reads for how a run behaves. Values are written to the credential env file and are not masked — do not put a secret in a hook command."}),i.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void y(),children:"↻ Refresh"})]}),i.jsxs("div",{className:"admin-hint",children:["A value exported in your shell ",i.jsx("strong",{children:"wins over this file"}),", for the dashboard and for every CLI run in that shell. A row that says ",i.jsx("em",{children:"shell value wins"})," is reporting exactly that, and writes here will not change it."]}),e.authenticated?null:i.jsx("div",{className:"admin-hint",children:e.configured?"Log in to view or change the process environment.":"Set up an admin account to change the process environment."}),e.authenticated&&!g?i.jsx("div",{className:"admin-hint",children:"Read-only — admins and operators can change these values."}):null,l?i.jsx("div",{className:"env-var-notice env-var-notice-error",children:l}):null,u?i.jsx("div",{className:"env-var-notice",children:u}):null,s?i.jsx("div",{className:"loading-state",children:"Loading…"}):Cbe.map(w=>{const j=r.filter(k=>k.group===w.id);return j.length===0?null:i.jsxs("section",{className:"process-env-group",children:[i.jsx("h3",{className:"process-env-group-title",children:w.title}),i.jsx("p",{className:"process-env-group-blurb",children:w.blurb}),i.jsx("div",{className:"env-var-list",children:j.map(k=>i.jsx(Tbe,{row:k,draft:f[k.name]??"",busy:p===k.name,readOnly:!g,onDraft:b=>h(N=>({...N,[k.name]:b})),onSet:b=>void v(k.name,b),onUnset:()=>void S(k.name)},k.name))})]},w.id)})]})}function Tbe({row:e,draft:t,busy:n,readOnly:r,onDraft:a,onSet:s,onUnset:o}){const l=e.state==="on",c=e.state!=="unset",u=f=>`admin-mini-btn${f?" process-env-active":""}`,d=e.kind==="flag"&&e.fileValue!==null&&e.fileValue!=="1"&&e.fileValue!=="0"?e.fileValue:null;return i.jsxs("div",{className:`env-var-row ${c?"env-var-set":"env-var-missing"}`,"data-testid":`process-env-row-${e.name}`,children:[i.jsxs("div",{className:"env-var-row-header",children:[i.jsxs("span",{className:"env-var-name",children:[e.name,e.shadowed?i.jsxs("span",{className:"env-var-blocked-badge",children:["⚠️ shell value wins: ",e.processValue]}):null]}),i.jsxs("span",{className:"env-var-status",children:[e.kind==="flag"?l?"✅ On":c?"⭕ Off":"➖ Unset":c?"✅ Set":"➖ Unset",d?` (${d})`:""]})]}),i.jsxs("div",{className:"env-var-description",children:[i.jsx("strong",{children:e.label})," — ",e.description]}),i.jsxs("div",{className:"env-var-description",children:["Unset: ",e.unsetMeans]}),e.cliEquivalent?i.jsxs("div",{className:"env-var-description",children:["Same switch: ",i.jsx("code",{children:e.cliEquivalent})]}):null,e.warning?i.jsxs("div",{className:"env-var-warning",children:["⚠️ ",e.warning]}):null,r?null:i.jsxs("div",{className:"env-var-actions",children:[e.kind==="flag"?i.jsxs(i.Fragment,{children:[i.jsx("button",{className:u(l),type:"button",disabled:n,onClick:()=>s("1"),children:"On"}),i.jsx("button",{className:u(c&&!l),type:"button",disabled:n,onClick:()=>s("0"),children:"Off"}),i.jsx("button",{className:u(!c),type:"button",disabled:n,onClick:o,children:"Unset"})]}):null,e.kind==="text"||e.acceptsValue?i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"env-var-input",type:"text",value:t,placeholder:e.placeholder,disabled:n,onChange:f=>a(f.target.value),"aria-label":`${e.name} value`}),i.jsxs("button",{className:"admin-mini-btn",type:"button",disabled:n||t.trim()==="",onClick:()=>s(t),children:["💾 ",e.valueLabel??"Save"]})]}):null,e.kind==="text"?i.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",disabled:n,onClick:o,children:"🗑️ Unset"}):null]})]})}const tC={before_tool_call:"🛑",after_tool_call:"✅",failed_tool_call:"❌",on_session_end:"🏁"};function nC(e){const t={};for(const n of e.split(`
209
209
  `)){const r=n.trim();if(!r)continue;const a=r.indexOf("=");if(a<=0)continue;const s=r.slice(0,a).trim(),o=r.slice(a+1).trim();s&&o&&(t[s]=o)}return Object.keys(t).length>0?t:void 0}function Obe(e){const t=e.when??{},n=[];if(t.tool&&n.push(`tool ${t.tool}`),t.surface&&n.push(`surface ${t.surface}`),t.cwdPrefix&&n.push(`cwd ${t.cwdPrefix}*`),t.argsMatch)for(const[a,s]of Object.entries(t.argsMatch))n.push(`${a}=${s}`);const r=n.length>0?n.join(" · "):"every call";switch(e.action.kind){case"deny":return`${r} → deny${e.action.reason?`: ${e.action.reason}`:""}`;case"notify":return`${r} → notify: ${e.action.message}`;case"scan-args":return`${r} → scan args for secrets${e.action.denyOnHit?" (deny on hit)":""}`}}function Pbe(){const e=Vr(),[t,n]=x.useState({configured:!1,authenticated:!1,role:null}),[r,a]=x.useState(null),[s,o]=x.useState(!0),[l,c]=x.useState(null),[u,d]=x.useState(null),[f,h]=x.useState(!1),[p,m]=x.useState([]),[g,y]=x.useState(""),[v,S]=x.useState(""),[w,j]=x.useState("before_tool_call"),[k,b]=x.useState("deny"),[N,_]=x.useState(""),[T,A]=x.useState(""),[O,P]=x.useState(""),[z,L]=x.useState(""),[M,D]=x.useState(""),[W,R]=x.useState("hook fired: {tool}"),[B,C]=x.useState(!1),J=t.authenticated&&(t.role==="admin"||t.role==="operator"),F=x.useCallback(async()=>{o(!0);const H=await K.fetchHooks();H?(a(H),m(H.hooks)):c("Could not load hooks — the dashboard server may be older than this bundle."),o(!1)},[]);x.useEffect(()=>{K.fetchAdminAuthStatus().then(H=>{n(H?{configured:H.configured,authenticated:H.authenticated,role:H.role??null}:{configured:!1,authenticated:!1,role:null})}),F()},[F,e]);const $=(r==null?void 0:r.events)??["before_tool_call","after_tool_call","failed_tool_call","on_session_end"],ie=(r==null?void 0:r.eventDescriptions)??{},de=(r==null?void 0:r.actionKinds)??["deny","notify","scan-args"],me=(r==null?void 0:r.actionDescriptions)??{},Te=x.useMemo(()=>p.some(H=>H.id===g.trim()),[p,g]),Q=/^[a-z0-9][a-z0-9-]{0,63}$/.test(g.trim()),X=Q&&!Te&&v.trim().length>0,ae=x.useCallback(()=>{c(null),d(null);const H={...N.trim()?{tool:N.trim()}:{},...T.trim()?{surface:T.trim()}:{},...O.trim()?{cwdPrefix:O.trim()}:{},...nC(z)?{argsMatch:nC(z)}:{}},xe=k==="deny"?{kind:"deny",...M.trim()?{reason:M.trim()}:{}}:k==="notify"?{kind:"notify",message:W.trim()||"hook fired: {tool}"}:{kind:"scan-args",denyOnHit:B,...M.trim()?{reason:M.trim()}:{}},we={id:g.trim(),label:v.trim(),event:w,enabled:!0,...Object.keys(H).length>0?{when:H}:{},action:xe,source:"user",updatedAt:Date.now()};m(je=>[...je,we]),y(""),S(""),_(""),A(""),P(""),L(""),D(""),C(!1)},[g,v,w,k,N,T,O,z,M,W,B]),ce=x.useCallback(async()=>{h(!0),c(null),d(null);const H=await K.saveHooks(p);H.ok?(m(H.hooks??p),d(`Saved ${(H.hooks??p).length} hook(s). They are in force on the next tool call.`)):c(H.error||"Could not save hooks."),h(!1)},[p]);return i.jsxs("div",{children:[i.jsx(Re,{icon:"🪝",title:"Hooks",description:"Declarative lifecycle rules bound to nuvira's own seams. A hook is DATA, not code: its only possible actions are deny, notify and secret-scan. There is no run-command action and no third-party script — nothing here executes."}),i.jsxs("div",{className:"env-var-header",children:[i.jsxs("span",{className:"env-var-title",children:[p.length," declared · ",p.filter(H=>H.enabled).length," enabled",r!=null&&r.file?i.jsxs(i.Fragment,{children:[" · stored at ",i.jsx("code",{children:r.file})]}):null]}),i.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void F(),children:"↻ Refresh"}),J?i.jsxs("button",{className:"admin-refresh-btn",type:"button",disabled:f,onClick:()=>void ce(),children:["💾 ",f?"Saving…":"Save hooks"]}):null]}),t.authenticated?null:i.jsx("div",{className:"admin-hint",children:t.configured?"Log in to view or change hooks.":"Set up an admin account to change hooks."}),t.authenticated&&!J?i.jsx("div",{className:"admin-hint",children:"Read-only — admins and operators can change hooks."}):null,l?i.jsx("div",{className:"env-var-notice env-var-notice-error",children:l}):null,u?i.jsx("div",{className:"env-var-notice",children:u}):null,i.jsxs("section",{className:"panel",children:[i.jsx("h2",{className:"section-title",children:"How it works"}),i.jsxs("p",{className:"admin-hint",children:["When a seam fires, nuvira tests each enabled hook whose event matches, in order, and the FIRST ",i.jsx("code",{children:"deny"})," ","wins. Every action is implemented natively, so a bad hook can at worst block a call or print a line — it can never run code, reach the network, or read a credential."]}),i.jsxs("table",{className:"chat-plan-table",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Seam"}),i.jsx("th",{children:"When it fires"})]})}),i.jsx("tbody",{children:$.map(H=>i.jsxs("tr",{children:[i.jsxs("td",{children:[tC[H]," ",i.jsx("code",{children:H})]}),i.jsx("td",{children:ie[H]??""})]},H))})]}),i.jsxs("table",{className:"chat-plan-table",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Action"}),i.jsx("th",{children:"What it can do"})]})}),i.jsx("tbody",{children:de.map(H=>i.jsxs("tr",{children:[i.jsx("td",{children:i.jsx("code",{children:H})}),i.jsx("td",{children:me[H]??""})]},H))})]})]}),i.jsxs("section",{className:"panel",children:[i.jsx("h2",{className:"section-title",children:"Declared hooks"}),s?i.jsx("div",{className:"loading-state",children:"Loading…"}):p.length===0?i.jsx("div",{className:"admin-hint",children:"No hooks declared. Add one below — it stays a draft until you Save."}):i.jsx("div",{className:"env-var-list",children:p.map(H=>i.jsxs("div",{className:`env-var-row ${H.enabled?"env-var-set":"env-var-missing"}`,"data-testid":`hook-row-${H.id}`,children:[i.jsxs("div",{className:"env-var-row-header",children:[i.jsxs("span",{className:"env-var-name",children:[tC[H.event]," ",i.jsx("code",{children:H.id})," — ",H.label,H.source==="builtin"?i.jsx("span",{className:"hub-chip",children:"builtin"}):null]}),i.jsx("span",{className:"env-var-status",children:H.event})]}),i.jsx("div",{className:"env-var-description",children:Obe(H)}),J?i.jsxs("div",{className:"env-var-actions",children:[i.jsx("button",{className:`admin-mini-btn${H.enabled?" process-env-active":""}`,type:"button",onClick:()=>m(xe=>xe.map(we=>we.id===H.id?{...we,enabled:!we.enabled}:we)),children:H.enabled?"✅ Enabled":"⭕ Disabled"}),H.source==="builtin"?i.jsx("span",{className:"admin-hint",children:"Built-in default — disable it to switch it off; it cannot be deleted."}):i.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",onClick:()=>m(xe=>xe.filter(we=>we.id!==H.id)),children:"🗑️ Remove"})]}):null]},H.id))})]}),J?i.jsxs("section",{className:"panel",children:[i.jsx("h2",{className:"section-title",children:"Add a hook"}),i.jsxs("div",{className:"env-var-row",children:[i.jsx("div",{className:"env-var-row-header",children:i.jsxs("span",{className:"env-var-name",children:[i.jsx("input",{className:"env-var-input",type:"text",value:g,placeholder:"id (e.g. block-rm-rf)","aria-label":"Hook id",onChange:H=>y(H.target.value)}),i.jsx("input",{className:"env-var-input",type:"text",value:v,placeholder:"label","aria-label":"Hook label",onChange:H=>S(H.target.value)})]})}),g.trim()&&!Q?i.jsx("div",{className:"env-var-warning",children:"⚠️ id must be lowercase letters, digits and hyphens."}):null,Te?i.jsx("div",{className:"env-var-warning",children:"⚠️ that id is already declared."}):null,i.jsxs("div",{className:"env-var-description",children:[i.jsxs("label",{children:["Seam:"," ",i.jsx("select",{value:w,"aria-label":"Hook event",onChange:H=>j(H.target.value),children:$.map(H=>i.jsx("option",{value:H,children:H},H))})]})," ",i.jsxs("label",{children:["Action:"," ",i.jsx("select",{value:k,"aria-label":"Hook action",onChange:H=>b(H.target.value),children:de.map(H=>i.jsx("option",{value:H,disabled:H==="deny"&&w!=="before_tool_call",children:H},H))})]})]}),i.jsxs("div",{className:"env-var-description",children:["Match (blank = every call):"," ",i.jsx("input",{className:"env-var-input",type:"text",value:N,placeholder:"tool glob (run_*)","aria-label":"Tool glob",onChange:H=>_(H.target.value)})," ",i.jsx("input",{className:"env-var-input",type:"text",value:T,placeholder:"surface glob","aria-label":"Surface glob",onChange:H=>A(H.target.value)})," ",i.jsx("input",{className:"env-var-input",type:"text",value:O,placeholder:"cwd prefix","aria-label":"Cwd prefix",onChange:H=>P(H.target.value)})]}),i.jsxs("div",{className:"env-var-description",children:["Arg match (one ",i.jsx("code",{children:"key=glob"})," per line, optional):"," ",i.jsx("textarea",{className:"env-var-input",value:z,placeholder:"command=rm -rf*","aria-label":"Arg match",onChange:H=>L(H.target.value)})]}),k==="notify"?i.jsxs("div",{className:"env-var-description",children:["Message:"," ",i.jsx("input",{className:"env-var-input",type:"text",value:W,"aria-label":"Notify message",onChange:H=>R(H.target.value)})," ",i.jsxs("span",{className:"admin-hint",children:["{tool} {surface} {event}"," are interpolated."]})]}):i.jsxs("div",{className:"env-var-description",children:[k==="deny"?"Reason":"Reason (when denied)",":"," ",i.jsx("input",{className:"env-var-input",type:"text",value:M,"aria-label":"Reason",onChange:H=>D(H.target.value)})]}),k==="scan-args"&&w==="before_tool_call"?i.jsxs("label",{className:"env-var-description",children:[i.jsx("input",{type:"checkbox",checked:B,onChange:H=>C(H.target.checked)})," Block the call when a secret shape is found"]}):null,i.jsxs("div",{className:"env-var-actions",children:[i.jsx("button",{className:"admin-refresh-btn",type:"button",disabled:!X,onClick:ae,children:"➕ Add to draft"}),i.jsx("span",{className:"admin-hint",children:"Nothing is in force until you press Save hooks."})]})]})]}):null]})}const Rbe={read:{label:"read",className:"cap-effect-read"},"local-write":{label:"local write",className:"cap-effect-local"},"local-state":{label:"machine state",className:"cap-effect-local"},external:{label:"off-machine",className:"cap-effect-external"},destructive:{label:"destructive",className:"cap-effect-destructive"}};function Mbe(e){return Rbe[e]??{label:e,className:"cap-effect-local"}}function Ibe(){const[e,t]=x.useState(null),[n,r]=x.useState([]),[a,s]=x.useState({authenticated:!1,role:null}),o=Vr(),[l,c]=x.useState(!0),[u,d]=x.useState(null),[f,h]=x.useState(null),[p,m]=x.useState(null),[g,y]=x.useState(""),[v,S]=x.useState(""),[w,j]=x.useState(""),k=a.authenticated&&(a.role==="admin"||a.role==="operator"),b=x.useCallback(async()=>{c(!0);const[M,D]=await Promise.all([K.fetchCapabilities(),K.fetchSessionGrants()]);d(M?null:"Could not read capabilities from the server."),t(M),r(D??[]),c(!1)},[]);x.useEffect(()=>{K.fetchAdminAuthStatus().then(M=>{s(M?{authenticated:M.authenticated,role:M.role??null}:{authenticated:!1,role:null})}),b()},[b,o]);const N=x.useCallback(async M=>{m(M),d(null),await K.revokeSessionGrant(M)?r(W=>W.filter(R=>R.sessionId!==M)):d(`Could not end the grant for ${M}.`),m(null)},[]),_=x.useCallback(M=>{M&&t(D=>D&&{...D,learnedCommands:M})},[]),T=x.useCallback(async()=>{const M=g.trim(),D=v.trim();if(!M||!D)return;m("__save__"),d(null),h(null);const W=await K.saveLearnedCommand(M,D,w.trim()||void 0);W.ok?(_(W.commands),y(""),S(""),j(""),h(`Learned "${M}" for this machine.`)):d(W.error||"Could not save the command."),m(null)},[g,v,w,_]),A=x.useCallback(async M=>{m(M),d(null),h(null);const D=await K.forgetLearnedCommand(M);D.ok?(_(D.commands),h(`Forgot "${M}" on this machine.`)):d(D.error||`Could not forget "${M}".`),m(null)},[_]),O=(e==null?void 0:e.readyCount)??0,P=(e==null?void 0:e.blockedCount)??0,z=(e==null?void 0:e.missingExecutables)??[],L=(e==null?void 0:e.learnedCommands)??[];return i.jsxs("div",{children:[i.jsx(Re,{icon:"🧰",title:"Capabilities"}),i.jsxs("div",{className:"env-var-header",children:[i.jsx("span",{className:"env-var-title",children:"What the agent can do on this machine, read from the same declarations the model discovers. A missing executable blocks a verb; a credential that is not an environment variable does not — it may live in the vault."}),i.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void b(),children:"↻ Refresh"})]}),u?i.jsx("div",{className:"env-var-notice env-var-notice-error",children:u}):null,f?i.jsx("div",{className:"env-var-notice",children:f}):null,l?i.jsx("div",{className:"loading-state",children:"Loading…"}):e?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"cap-summary","data-testid":"cap-summary",children:[i.jsxs("span",{className:"cap-tile cap-tile-ok","data-testid":"cap-tile-ready",children:[i.jsx("strong",{children:O})," ready"]}),i.jsxs("span",{className:`cap-tile${P>0?" cap-tile-blocked":""}`,"data-testid":"cap-tile-blocked",children:[i.jsx("strong",{children:P})," blocked"]}),i.jsxs("span",{className:`cap-tile${z.length>0?" cap-tile-blocked":""}`,"data-testid":"cap-tile-missing",children:[i.jsx("strong",{children:z.length})," missing executable",z.length===1?"":"s"]}),i.jsxs("span",{className:"cap-tile","data-testid":"cap-tile-grants",children:[i.jsx("strong",{children:n.length})," live session grant",n.length===1?"":"s"]})]}),i.jsxs("section",{className:"cap-section","data-testid":"cap-missing",children:[i.jsx("h3",{className:"cap-section-title",children:"Missing executables"}),z.length===0?i.jsx("p",{className:"cap-empty",children:"Every executable the curated verbs need is on PATH."}):i.jsx("ul",{className:"cap-missing-list",children:z.map(M=>i.jsxs("li",{className:"cap-missing-row",children:[i.jsx("code",{className:"cap-missing-bins",children:M.anyOf.join(" or ")}),i.jsxs("span",{className:"cap-missing-for",children:["needed by ",M.forRefs.join(", ")]}),i.jsx("span",{className:"cap-missing-remedy",children:M.remedy})]},M.anyOf.join("|")))})]}),i.jsxs("section",{className:"cap-section","data-testid":"cap-verbs",children:[i.jsx("h3",{className:"cap-section-title",children:"Curated verbs"}),i.jsx("div",{className:"cap-verb-list",children:e.verbs.map(M=>i.jsx($be,{verb:M},M.id))})]}),i.jsxs("section",{className:"cap-section","data-testid":"cap-learned",children:[i.jsxs("h3",{className:"cap-section-title",children:["Learned commands (",L.length,")"]}),i.jsx("p",{className:"cap-section-blurb",children:"Commands derived for this machine, keyed by what they do — recorded by the model or observed from a labelled run. They are HINTS: the agent still checks presence before running one. Add or replace one with the same verb below."}),L.length===0?i.jsx("p",{className:"cap-empty",children:"Nothing learned yet — the agent records a command when it derives one, or when a labelled run succeeds."}):i.jsx("ul",{className:"cap-learned-list",children:L.map(M=>i.jsxs("li",{className:"cap-learned-row","data-testid":`cap-learned-${M.verb}`,children:[i.jsx("span",{className:"cap-learned-verb",children:M.verb}),i.jsx("span",{className:"cap-badge cap-effect-local",children:M.os}),i.jsx("span",{className:"cap-badge cap-effect-read",children:M.source}),i.jsx("code",{className:"cap-learned-cmd",children:M.command}),M.note?i.jsx("span",{className:"cap-learned-note",children:M.note}):null,k?i.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",disabled:p===M.verb,onClick:()=>void A(M.verb),children:"Forget"}):null]},`${M.verb}|${M.os}`))}),k?i.jsxs("div",{className:"cap-learned-form",children:[i.jsx("input",{className:"env-var-input",type:"text","aria-label":"learned verb",placeholder:"verb (e.g. install java)",value:g,disabled:p==="__save__",onChange:M=>y(M.target.value)}),i.jsx("input",{className:"env-var-input",type:"text","aria-label":"learned command",placeholder:"command (e.g. brew install openjdk)",value:v,disabled:p==="__save__",onChange:M=>S(M.target.value)}),i.jsx("input",{className:"env-var-input",type:"text","aria-label":"learned note",placeholder:"note (optional)",value:w,disabled:p==="__save__",onChange:M=>j(M.target.value)}),i.jsx("button",{className:"admin-mini-btn",type:"button",disabled:!g.trim()||!v.trim()||p==="__save__",onClick:()=>void T(),children:"💾 Learn"})]}):i.jsx("div",{className:"admin-hint",children:"Read-only — admins and operators can add or remove learned commands."})]}),i.jsxs("section",{className:"cap-section","data-testid":"cap-grants",children:[i.jsx("h3",{className:"cap-section-title",children:"Live session grants"}),n.length===0?i.jsx("p",{className:"cap-empty",children:"No live session grants — off-machine actions will ask."}):i.jsx("ul",{className:"cap-grant-list",children:n.map(M=>i.jsxs("li",{className:"cap-grant-row","data-testid":`cap-grant-${M.sessionId}`,children:[i.jsx("code",{className:"cap-grant-id",children:M.sessionId}),i.jsx("span",{className:"cap-grant-cats",children:M.categories.join(", ")||"(no categories)"}),i.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",disabled:p===M.sessionId,onClick:()=>void N(M.sessionId),children:"End"})]},M.sessionId))})]})]}):i.jsx("div",{className:"admin-hint",children:"Capabilities are unavailable right now."})]})}function $be({verb:e}){const t=Mbe(e.effect);return i.jsxs("div",{className:`cap-verb${e.ready?" cap-verb-ready":" cap-verb-blocked"}`,"data-testid":`cap-verb-${e.ref}`,children:[i.jsxs("div",{className:"cap-verb-header",children:[i.jsx("span",{className:"cap-verb-name",children:e.name}),i.jsx("span",{className:`cap-badge ${t.className}`,children:t.label}),i.jsx("span",{className:`cap-badge ${e.ready?"cap-effect-read":"cap-effect-destructive"}`,children:e.ready?"✅ ready":"⛔ blocked"}),e.grantable?i.jsxs("span",{className:"cap-badge cap-effect-local",children:["grantable: ",e.grantable]}):null]}),i.jsx("div",{className:"cap-verb-does",children:e.does}),e.gaps.length>0?i.jsx("ul",{className:"cap-verb-gaps",children:e.gaps.map(n=>i.jsx("li",{children:n},n))}):null,e.ask.length>0?i.jsxs("div",{className:"cap-verb-ask",children:["Will ask for: ",e.ask.join(", ")]}):null,e.onThisMachine?i.jsxs("div",{className:"cap-verb-cmd",children:["On this machine: ",i.jsx("code",{children:e.onThisMachine.command}),e.onThisMachine.note?i.jsxs("span",{className:"cap-verb-note",children:[" — ",e.onThisMachine.note]}):null]}):null,e.undo?i.jsxs("div",{className:"cap-verb-undo",children:["Undo: ",e.undo]}):null]})}function Lbe(){const[e,t]=x.useState(null),[n,r]=x.useState(!1),[a,s]=x.useState("--"),[o,l]=x.useState(!1),u=Ri().pathname==="/chat",[d,f]=x.useState(u);x.useEffect(()=>{u&&f(!0)},[u]);const h=x.useCallback(g=>{t(g),s(new Date().toLocaleTimeString())},[]),p=x.useCallback(g=>{r(g)},[]),m=x.useCallback(async()=>{l(!0);try{const g=await K.fetchAll();g&&h(g)}finally{l(!1)}},[h]);return x.useEffect(()=>{K.fetchAll().then(v=>{v&&h(v)});const g=K.subscribe(h),y=K.onConnectionChange(p);return K.connect(),()=>{g(),y(),K.disconnect()}},[h,p]),i.jsxs(vB,{connected:n,lastUpdated:a,onRefresh:m,refreshing:o,children:[d&&i.jsx("div",{style:{display:u?void 0:"none"},children:i.jsx(tbe,{})}),i.jsx("div",{style:{display:u?"none":void 0},children:i.jsxs(L2,{children:[i.jsx(Ke,{path:"/",element:i.jsx(Jk,{to:"/overview",replace:!0})}),i.jsx(Ke,{path:"/overview",element:i.jsx(Qie,{data:e,onRefresh:m,refreshing:o})}),i.jsx(Ke,{path:"/chat",element:null}),i.jsx(Ke,{path:"/dag",element:i.jsx(lse,{data:e})}),i.jsx(Ke,{path:"/costs",element:i.jsx(use,{data:e})}),i.jsx(Ke,{path:"/benchmarks",element:i.jsx(fse,{data:e})}),i.jsx(Ke,{path:"/models",element:i.jsx(toe,{})}),i.jsx(Ke,{path:"/models/timeline",element:i.jsx(pbe,{})}),i.jsx(Ke,{path:"/routing",element:i.jsx($oe,{data:e})}),i.jsx(Ke,{path:"/requests",element:i.jsx(Uoe,{data:e})}),i.jsx(Ke,{path:"/traces",element:i.jsx(ele,{})}),i.jsx(Ke,{path:"/hub",element:i.jsx(vle,{})}),i.jsx(Ke,{path:"/capabilities",element:i.jsx(Ibe,{})}),i.jsx(Ke,{path:"/tasks",element:i.jsx(Nle,{})}),i.jsx(Ke,{path:"/evals",element:i.jsx(ibe,{data:e})}),i.jsx(Ke,{path:"/platforms",element:i.jsx(lbe,{})}),i.jsx(Ke,{path:"/bedrock",element:i.jsx(ube,{canWrite:!0,sessionExpired:g=>console.error(g)})}),i.jsx(Ke,{path:"/contacts",element:i.jsx(dbe,{})}),i.jsx(Ke,{path:"/gateway",element:i.jsx(obe,{})}),i.jsx(Ke,{path:"/env",element:i.jsx(Ebe,{})}),i.jsx(Ke,{path:"/process-env",element:i.jsx(Abe,{})}),i.jsx(Ke,{path:"/hooks",element:i.jsx(Pbe,{})}),i.jsx(Ke,{path:"/memory",element:i.jsx(vbe,{data:e})}),i.jsx(Ke,{path:"/knowledge",element:i.jsx(ybe,{})}),i.jsx(Ke,{path:"/history",element:i.jsx(wbe,{data:e})}),i.jsx(Ke,{path:"/decisions",element:i.jsx(Sbe,{})}),i.jsx(Ke,{path:"/executions",element:i.jsx(jbe,{onFetch:g=>K.fetchExecutionAudit(g)})}),i.jsx(Ke,{path:"/system",element:i.jsx(vse,{data:e,connected:n,lastUpdated:a})}),i.jsx(Ke,{path:"/admin",element:i.jsx(sle,{})}),i.jsx(Ke,{path:"/help",element:i.jsx(Zie,{})}),i.jsx(Ke,{path:"*",element:i.jsx(Jk,{to:"/overview",replace:!0})})]})})]})}Jx(TT());mT(document.getElementById("root")).render(i.jsx(x.StrictMode,{children:i.jsx(G2,{children:i.jsx(Lbe,{})})}));
210
- //# sourceMappingURL=index-UJ1VG4JG.js.map
210
+ //# sourceMappingURL=index-DeD3L0kG.js.map