PageSourceSearch

https://app.praksis.ai/_next/static/chunks/8029-a5d59d4467ce4d2f.js?dpl=dpl_GSWi7rZYnz2uQ1jJhewgJsXczpjf

js praksis.ai collected 2026-10-05 15:25:03 UTC 321,059 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8029,81775],{82622:function(e,t,n){n.d(t,{r:function(){return x}});var r=n(27573),a=n(7653),s=n(46393),i=n(72725),l=n(13890),o=n(87354),c=n(16273),d=n(26798),u=n(17515),m=n(52260),p=n(59971),f=n(74685);let h=f.Ryn({requestId:f.Z_8().uuid(),conversationId:f.Z_8().uuid().nullable(),replacementRequestId:f.Z_8().uuid().nullable().optional(),status:f.KmV(["pending_user","authorizing","ready","resuming","consumed","cancelled","failed","expired","admin_needed"]),service:f.Ryn({name:f.Z_8().min(1),iconUrl:f.Z_8().nullable()}),reason:f.Z_8(),scopeLabel:f.Z_8(),organizationApproved:f.O72(),accountLabel:f.Z_8().nullable(),nextAction:f.KmV(["authorize","resume","retry","none"]),expiresAt:f.Z_8().datetime({offset:!0})});function g(e){var t,n;let{requestId:i,conversationId:g,onResume:x,className:v}=e,[k,y]=(0,a.useState)(i);(0,a.useEffect)(()=>y(i),[i]);let w=(0,s.T)("connectionRequest"),[j,b]=(0,a.useState)(null),[N,C]=(0,a.useState)(!1),[S,T]=(0,a.useState)(!1),[I,E]=(0,a.useState)(0),[_,A]=(0,a.useState)(!1),R="".concat(k,":").concat(g),[P,D]=(0,a.useState)(null),F=(null==P?void 0:P.identity)===R?P.state:"idle";async function O(){var e;let t=null!==(e=null==j?void 0:j.service.name)&&void 0!==e?e:w("service");try{await navigator.clipboard.writeText(w("adminRequestText",{service:t})),D({identity:R,state:"copied"})}catch(e){D({identity:R,state:"failed"})}}let U=(0,a.useRef)(!1),L=(0,a.useRef)(x);L.current=x;let M=(0,a.useRef)(null),Z=(0,a.useRef)(k);async function z(e){if(U.current)return;U.current=!0,T(!0),C(!1);let t="authorize"===e?window.open("about:blank","_blank"):null;t&&(t.opener=null);try{var n,r;if("authorize"===e&&!t)throw Error("Consent window blocked");let a=await fetch("/api/agents/connections/requests/".concat(encodeURIComponent(k),"/").concat(e),{method:"POST",headers:(0,p.p)()}),s=await a.json();if(!a.ok)throw Error("Connection action refused");if(Z.current!==k){null==t||t.close();return}if("retry"===e){let e=h.shape.requestId.parse(null===(r=s.request)||void 0===r?void 0:r.id);if(e===k)throw Error("Retry must create a new request");y(e)}else if("authorize"===e&&(null===(n=s.request)||void 0===n?void 0:n.status)!=="ready"){let e=function(e){if("string"!=typeof e)return null;let t=/^\/api\/plugins\/oauth\/[a-z0-9-]{1,64}\/auth(?:\?connection_request_id=([a-fA-F0-9-]{36}))?$/.exec(e);return!t||/[\\\r\n]/.test(e)||t[1]&&!f.Z_8().uuid().safeParse(t[1]).success?null:e}(s.authorize_path);if(!e||!e.endsWith("?connection_request_id=".concat(k)))throw Error("Invalid consent destination");t&&(t.location.href=e)}else null==t||t.close();E(e=>e+1)}catch(e){null==t||t.close(),Z.current===k&&C(!0)}finally{U.current=!1,Z.current===k&&T(!1)}}if(Z.current=k,(0,a.useEffect)(()=>{let e;let t=new AbortController,n=!1,r=Date.now();b(null),C(!1),A(!1);let a=async()=>{let s=setTimeout(()=>t.abort(),15e3);try{let i=await fetch("/api/agents/connections/requests/".concat(encodeURIComponent(k)),{signal:t.signal});if(!i.ok)throw Error("Connection request unavailable");let l=await i.json();clearTimeout(s);let o=h.parse(l.view);if(o.requestId!==k||o.conversationId!==g)throw Error("Connection request does not belong to this conversation");if(n)return;if(o.replacementRequestId&&o.replacementRequestId!==k){y(o.replacementRequestId);return}if(b(o),C(!1),"ready"===o.status&&"resume"===o.nextAction&&M.current!==k){M.current=k;try{await L.current(k,g)}catch(e){if(e instanceof m.N)M.current=null;else{n||C(!0);return}}}if(!n&&(["pending_user","authorizing","ready","resuming"].includes(o.status)||"retry"===o.nextAction)){if("resuming"===o.status&&Date.now()-r>=12e4){C(!0);return}new Date(o.expiresAt).getTime()-Date.now()<=0&&["pending_user","authorizing","ready"].includes(o.status)&&b({...o,status:"expired",nextAction:o.organizationApproved?"retry":"none"}),e=setTimeout(()=>void a(),"retry"===o.nextAction?1e4:3e3)}}catch(e){n||C(!0)}finally{clearTimeout(s)}};return a(),()=>{n=!0,t.abort(),e&&clearTimeout(e)}},[k,g,I]),_)return null;let K=null!==(t=null==j?void 0:j.service.name)&&void 0!==t?t:w("service"),W=null==j?void 0:j.status,q="ready"===W||"resuming"===W||"consumed"===W,G="cancelled"===W||"failed"===W||"expired"===W||"admin_needed"===W;return(0,r.jsxs)(d.Zb,{className:"min-w-0 space-y-4 rounded-lg border-border p-4 ".concat(null!=v?v:""),"aria-live":"polite",children:[(0,r.jsxs)("div",{className:"flex items-start gap-3",children:[(0,r.jsx)("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md border border-border bg-muted",children:(0,r.jsx)(l.Z,{className:"h-5 w-5","aria-hidden":"true"})}),(0,r.jsxs)("div",{className:"min-w-0 space-y-1",children:[(0,r.jsx)("h3",{className:"break-words text-sm font-semibold",children:q?w("connected",{service:K}):"admin_needed"===W?w("unavailable",{service:K}):G?w("notCompleted"):w("connect",{service:K})}),(j||!N)&&(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:null!==(n=null==j?void 0:j.reason)&&void 0!==n?n:w("loading")})]})]}),(null==j?void 0:j.organizationApproved)&&!G&&(0,r.jsx)("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[w("approved"),j.scopeLabel,w("noSecrets")].map(e=>(0,r.jsxs)("li",{className:"flex items-start gap-2",children:[(0,r.jsx)(o.Z,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),(0,r.jsx)("span",{children:e})]},e))}),(null==j?void 0:j.accountLabel)&&(0,r.jsx)("p",{className:"break-words text-sm text-muted-foreground",children:w("account",{account:j.accountLabel})}),N&&(0,r.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w("failed")}),"admin_needed"===W&&(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:w("adminNeeded")}),"admin_needed"===W&&"copied"===F&&(0,r.jsx)("p",{role:"status",className:"text-sm text-muted-foreground",children:w("adminRequestCopied")}),"admin_needed"===W&&"failed"===F&&(0,r.jsx)("p",{role:"alert",className:"text-sm text-destructive",children:w("adminRequestCopyFailed",{service:K})}),("cancelled"===W||"failed"===W)&&(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:w("preserved")}),"expired"===W&&(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:w("expired")}),("authorizing"===W||"resuming"===W)&&!N&&(0,r.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,r.jsx)(u.Gl,{size:"sm"}),w("authorizing"===W?"waiting":"resuming")]}),(0,r.jsxs)("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between",children:[j&&!q&&(0,r.jsx)(c.z,{variant:"ghost",disabled:S,onClick:()=>G?A(!0):void z("cancel"),children:w(G&&"admin_needed"!==W?"continueWithout":"notNow")}),q&&(0,r.jsx)("a",{className:"text-sm underline underline-offset-4",href:"/settings/connections",children:w("settings")}),N||"admin_needed"!==W?N?(0,r.jsx)(c.z,{variant:"outline",disabled:S,onClick:()=>{M.current=null,E(e=>e+1)},children:w("retry")}):(null==j?void 0:j.nextAction)==="retry"?(0,r.jsx)(c.z,{variant:"outline",disabled:S,onClick:()=>void z("retry"),children:w("retry")}):(null==j?void 0:j.nextAction)==="authorize"&&j.organizationApproved&&(0,r.jsxs)(c.z,{disabled:S,onClick:()=>void z("authorize"),children:[S&&(0,r.jsx)(u.Gl,{size:"sm"}),w("connect",{service:K})]}):(0,r.jsx)(c.z,{onClick:()=>void O(),children:w("copyAdminRequest")})]})]})}
1function x(e){let{conversationId:t,onResume:n,empty:l}=e,o=(0,s.T)("connectionRequest"),[d,u]=(0,a.useState)([]),[m,p]=(0,a.useState)(!1),[f,h]=(0,a.useState)(!1),[x,v]=(0,a.useState)(0);return(0,a.useEffect)(()=>{u([]),p(!1),h(!1);let e=new AbortController,n=e=>{"connection_required"!==e.type||e.colleague||e.conversationId!==t||u(t=>t.includes(e.requestId)?t:[...t,e.requestId])};(0,i.lW)().forEach(n);let r=e=>n(e.detail);window.addEventListener(i.dD,r);let a=setTimeout(()=>e.abort(),15e3);fetch("/api/agents/connections/requests?conversation_id=".concat(encodeURIComponent(t)),{signal:e.signal}).then(async t=>{if(!t.ok)throw Error("Could not load connection requests");let n=await t.json();if(!Array.isArray(n.requestIds)||!n.requestIds.every(e=>"string"==typeof e))throw Error("Invalid connection requests");e.signal.aborted||(u(e=>Array.from(new Set([...e,...n.requestIds]))),h(!0))}).catch(()=>{s||p(!0)}).finally(()=>clearTimeout(a));let s=!1;return()=>{s=!0,e.abort(),clearTimeout(a),window.removeEventListener(i.dD,r)}},[t,x]),(0,r.jsxs)("div",{className:"space-y-3",children:[f&&!m&&0===d.length&&l,m&&(0,r.jsxs)("div",{role:"alert",className:"space-y-2 text-sm",children:[(0,r.jsx)("p",{children:o("failed")}),(0,r.jsx)(c.z,{variant:"outline",onClick:()=>v(e=>e+1),children:o("retry")})]}),d.map(e=>(0,r.jsx)(g,{requestId:e,conversationId:t,onResume:n},"".concat(t,":").concat(e)))]})}},21764:function(e,t,n){n.d(t,{CN:function(){return Y}});var r=n(27573),a=n(47200),s=n(7653),i=n(81695),l=n(37811),o=n(30609),c=n(62539),d=n(77248),u=n(79901),m=n(64386),p=n(17022),f=n(6315),h=n(3349),g=n(94097),x=n(10269),v=n(93017),k=n(10997),y=n(69790),w=n(49743),j=n(44526),b=n(36673),N=n(3172),C=n(17515),S=n(16273),T=n(19369),I=n(65455),E=n(86320),_=n(79258),A=n(93739),R=n(98521),P=n(79590),D=n(63769),F=n(81236),O=n(808),U=n(98810),L=n(46393),M=n(17787),Z=n(59971);function z(e){return new URLSearchParams({configuration_root_id:e,folder_id:e,include_descendants:"true"})}var K=n(88146),W=n(61883),q=n(32917),G=n(30022),V=n(14807),H=n(22579);
1function J(e){let{configurationRootId:t,creatingConversation:n,workspaceId:a,showBackLink:s,viewMode:i,onNewConversation:l,onViewModeChange:o}=e,c=(0,L.T)("chat");return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"p-4 border-b border-border flex-shrink-0",children:[t?(0,r.jsx)("p",{className:"text-xs font-medium text-muted-foreground",children:c("configurationContent")}):(0,r.jsx)(H.V,{onBeforeWorkspaceSwitch:l}),a&&s&&(0,r.jsxs)(K.default,{href:"/production/workspaces/".concat(a),className:"flex items-center justify-end gap-1.5 mt-2 text-[11px] text-muted-foreground/70 hover:text-muted-foreground transition-colors",children:[(0,r.jsx)(W.Z,{className:"h-3 w-3"}),(0,r.jsx)("span",{children:c("backToWorkspace")})]})]}),(0,r.jsxs)("div",{className:"p-3 border-b border-border/50 flex-shrink-0 space-y-2",children:[(0,r.jsxs)(S.z,{onClick:l,disabled:!!(t&&n),variant:"outline",className:"w-full gap-2",size:"sm",children:[(0,r.jsx)(q.Z,{className:"h-4 w-4"}),c("newConversationLabel")]}),!t&&(0,r.jsx)("div",{className:"flex items-center gap-1 bg-muted/50 rounded-md p-0.5",children:["agent","folder"].map(e=>{let t="agent"===e?G.Z:V.Z;return(0,r.jsxs)("button",{onClick:()=>o(e),className:(0,T.cn)("flex-1 flex items-center justify-center gap-1.5 py-1 rounded text-xs font-medium transition-all",i===e?"bg-card shadow-sm text-foreground":"text-muted-foreground hover:text-foreground"),children:[(0,r.jsx)(t,{className:"h-3 w-3"}),"agent"===e?c("conversations"):c("folders")]},e)})})]})]})}function B(e){return"sv"===e?"sv-SE":"no"===e||"nb"===e||"nn"===e?"nb-NO":"en-US"}function X(e,t,n){let r=new Date,a=new Date(e);if(Number.isNaN(a.getTime()))return e;let s=Math.floor((r.getTime()-a.getTime())/1e3),i=Math.floor(s/60),l=Math.floor(i/60),o=Math.floor(l/24);return s<10?n("relativeNow"):s<60?n("relativeSecondsShort",{count:s}):i<60?n("relativeMinutesShort",{count:i}):l<24?n("relativeHoursShort",{count:l}):1===o?n("relativeOneDayShort"):o<30?n("relativeDaysShort",{count:o}):a.toLocaleDateString(B(t),{day:"numeric",month:"short"})}function Q(e){let{sessionStatus:t,agentStatus:n,updatedAt:a,nowMs:s=Date.now()}=e,i=(0,L.T)("chat");if("working"===n){let e=a?Date.parse(a):Number.NaN;return Number.isFinite(e)&&s-e<3e5?(0,r.jsx)("span",{role:"status","aria-label":i("thinking"),children:(0,r.jsx)(C.Gl,{className:"flex-shrink-0 text-muted-foreground"})}):(0,r.jsx)(o.Z,{role:"img","aria-label":i("regenerationFailed"),className:"w-3.5 h-3.5 flex-shrink-0 text-destructive"})}return"needs_input"===n?(0,r.jsx)(c.Z,{className:"w-3.5 h-3.5 flex-shrink-0 text-muted-foreground"}):"error"===n?(0,r.jsx)(o.Z,{className:"w-3.5 h-3.5 flex-shrink-0 text-destructive"}):"in_doubt"===n?(0,r.jsx)(o.Z,{className:"w-3.5 h-3.5 flex-shrink-0 text-amber-600"}):"aborted_client"===n||"aborted"===n?(0,r.jsx)(d.Z,{role:"img","aria-label":i("aborted"===n?"stoppedByYou":"generationStopped"),className:"w-3.5 h-3.5 flex-shrink-0 text-muted-foreground"}):"completed"===t||"completed"===n?(0,r.jsx)(u.Z,{className:"w-3.5 h-3.5 flex-shrink-0 text-muted-foreground/60"}):"paused"===t?(0,r.jsx)(m.Z,{className:"w-3.5 h-3.5 flex-shrink-0 text-muted-foreground/40"}):(0,r.jsx)(m.Z,{className:"w-3.5 h-3.5 flex-shrink-0 text-muted-foreground/30"})}let Y=(0,s.memo)(function(e){let{currentConversationId:t,currentAIProjectId:n,conversationStatusOverrides:o,onConversationSelect:c,onNewConversation:d,onAIProjectChange:u,onRefreshRef:m,onConversationsLoaded:K,onProductionFileClick:W,configurationRootId:q,configurationSkillId:G,className:V}=e,H=(0,L.T)("chat"),Y=(0,L.T)("folderTree"),$=(0,l.bU)(),ee=(0,i.useRouter)(),et=(0,i.usePathname)(),{workspace:en}=(0,O.c)(),{currentProjectId:er}=(0,U.P)(),ea=(null==en?void 0:en.id)&&et==="/production/workspaces/".concat(en.id),[es,ei]=(0,s.useState)([]),[el,eo]=(0,s.useState)([]),[ec,ed]=(0,s.useState)(!0),[eu,em]=(0,s.useState)(()=>Date.now()),[ep,ef]=(0,s.useState)(()=>localStorage.getItem("sidebar-view-mode")||"agent"),eh=q?"folder":ep,[eg,ex]=(0,s.useState)(!1),[ev,ek]=(0,s.useState)(null),[ey,ew]=(0,s.useState)(!1),[ej,eb]=(0,s.useState)(null),[eN,eC]=(0,s.use
1State)(""),[eS,eT]=(0,s.useState)(!1),eI=(0,s.useMemo)(()=>el.some(e=>"working"===e.agent_status),[el]),eE=(0,s.useCallback)(async()=>{if(!(null==en?void 0:en.id)){ei([]);return}try{let e=q?"&".concat(z(q).toString()):"",t=await fetch("/api/production/folders?workspace_id=".concat(en.id).concat(e));if(t.ok){let e=await t.json();ei(e.folders||[])}}catch(e){a.kg.error("Error loading folders:",e),ei([])}},[q,null==en?void 0:en.id]),e_=(0,s.useCallback)(async()=>{if(!(null==en?void 0:en.id)){eo([]);return}try{let e=q?"&".concat(z(q).toString()):"",t=await fetch("/api/ai/conversations?limit=200&workspace_id=".concat(en.id,"&include_document_conversations=1").concat(e));if(t.ok){let e=await t.json();eo(e.conversations||[]),em(Date.now())}}catch(e){a.kg.error("Error loading conversations:",e),eo([])}},[q,null==en?void 0:en.id]),[eA,eR]=(0,s.useState)([]),eP=!!W,eD=(0,s.useCallback)(async()=>{if(!(null==en?void 0:en.id)||!eP){eR([]);return}try{let e=q?"&".concat(z(q).toString()):"",t=await fetch("/api/production/overview?workspace_id=".concat(en.id).concat(e));if(t.ok){let e=((await t.json()).items||[]).filter(e=>"file"===e.type||"presentation"===e.type||"dialogue"===e.type);eR(e)}}catch(e){a.kg.error("Error loading production items:",e),eR([])}},[q,null==en?void 0:en.id,eP]);(0,s.useEffect)(()=>{(async()=>{ed(!0),(null==en?void 0:en.id)?await Promise.all([eE(),e_(),eD()]):(ei([]),eo([]),eR([])),ed(!1)})()},[eE,e_,eD,null==en?void 0:en.id]),(0,s.useEffect)(()=>{if(!eI)return;let e=window.setInterval(()=>{em(Date.now())},3e4);return()=>window.clearInterval(e)},[eI]),(0,s.useEffect)(()=>(m&&(m.current=()=>{e_(),eD()}),()=>{m&&(m.current=null)}),[m,e_,eD]),(0,s.useEffect)(()=>{if(!K)return;let e=[...el.map(e=>({id:e.id,title:e.title,updated_at:e.updated_at,type:"conversation"})),...eA.map(e=>({id:e.id,title:e.name,updated_at:e.updated_at||"",type:"file"===e.type?"canvas":e.type}))].sort((e,t)=>new Date(t.updated_at).getTime()-new Date(e.updated_at).getTime()).slice(0,8);e.length>0&&K(e)},[el,eA,K]),(0,s.useEffect)(()=>{let e=e=>{e.detail.workspaceId===(null==en?void 0:en.id)&&(eE(),e_(),eD())};return window.addEventListener("workspace-refresh",e),()=>{window.removeEventListener("workspace-refresh",e)}},[null==en?void 0:en.id,eE,e_,eD]);let eF=(0,s.useCallback)(async e=>{try{let n=await fetch("/api/ai/conversations/".concat(e),{method:"DELETE",headers:(0,Z.p)()});if(n.ok)eo(t=>t.filter(t=>t.id!==e)),t===e&&(null==d||d());else{let e=await n.json().catch(()=>({}));M.toast.error(e.error||H("failedToDeleteConversation"))}}catch(e){a.kg.error("Failed to delete conversation:",e),M.toast.error(H("failedToDeleteConversation"))}},[t,d,H]),eO=(0,s.useCallback)(async e=>{try{(await fetch("/api/ai/conversations/".concat(e),{method:"PATCH",headers:{"Content-Type":"application/json",...(0,Z.p)()},body:JSON.stringify({session_status:"archived"})})).ok?(eo(t=>t.filter(t=>t.id!==e)),t===e&&(null==d||d())):M.toast.error(H("failedToArchiveConversation"))}catch(e){a.kg.error("Failed to archive conversation:",e),M.toast.error(H("failedToArchiveConversation"))}},[t,d,H]),[eU,eL]=(0,s.useState)(null),eM=(0,s.useCallback)(async e=>{if(eU)return;eL(e);let t=M.toast.loading(H("preparingFreshSession"));try{let r=await fetch("/api/ai/conversations/".concat(e,"/branch"),{method:"POST",headers:{"Content-Type":"application/json",...(0,Z.p)()},body:JSON.stringify({})});if(r.ok){var n;let e=await r.json();await e_(),(null===(n=e.conversation)||void 0===n?void 0:n.id)&&(null==c||c(e.conversation.id)),M.toast.success(e.summary_generated?H("freshSessionReady"):H("conversationBranched"),{id:t})}else M.toast.error(H("couldNotBranchConversation"),{id:t})}catch(e){a.kg.error("Failed to fork conversation:",e),M.toast.error(H("couldNotBranchConversation"),{id:t})}finally{eL(null)}},[eU,e_,c,H]),eZ=(0,s.useCallback)(async(e,t)=>{try{(await fetch("/api/ai/conversations/".concat(e),{method:"PUT",headers:{"Content-Type":"application/json",...(0,Z.p)()},body:JSON.stringify({folder_id:t})})).ok&&await e_()}catch(e){a.kg.error("Failed to move conversation:",e)}},[e_]),ez=(0,s.useCallback)(async()=>
1{if(ej&&eN.trim())try{(await fetch("/api/ai/conversations/".concat(ej.id),{method:"PUT",headers:{"Content-Type":"application/json",...(0,Z.p)()},body:JSON.stringify({title:eN.trim()})})).ok&&(eo(e=>e.map(e=>e.id===ej.id?{...e,title:eN.trim()}:e)),ew(!1),eb(null),eC(""))}catch(e){a.kg.error("Failed to rename conversation:",e)}},[ej,eN]),eK=(0,s.useMemo)(()=>{let e=new Map;for(let t of es)e.set(t.id,t.name);return e},[es]),eW=(0,s.useMemo)(()=>el.reduce((e,t)=>(t.folder_id&&(e[t.folder_id]||(e[t.folder_id]=[]),e[t.folder_id].push(t)),e),{}),[el]),eq=(0,s.useMemo)(()=>eA.reduce((e,t)=>(t.folder_id&&(e[t.folder_id]||(e[t.folder_id]=[]),e[t.folder_id].push(t)),e),{}),[eA]),eG=(0,s.useMemo)(()=>el.filter(e=>!e.folder_id||e.folder_id===q),[q,el]),eV=(0,s.useMemo)(()=>eA.filter(e=>!e.folder_id||e.folder_id===q),[q,eA]),eH=(0,s.useMemo)(()=>[...el].sort((e,t)=>new Date(t.updated_at).getTime()-new Date(e.updated_at).getTime()),[el]),eJ=(0,s.useMemo)(()=>es.filter(e=>!e.is_system),[es]),eB=(0,s.useMemo)(()=>(0,I.y)(eJ.map(e=>({id:e.id,name:e.name,parent_id:e.parent_id}))),[eJ]),eX=(0,s.useCallback)(function(e,t,n){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;return e.map(e=>(0,r.jsxs)("div",{children:[(0,r.jsxs)(P.Xi,{disabled:e.id===n,onClick:()=>eZ(t,e.id),style:(0,A.sj)(a,{cap:null}),children:[(0,r.jsx)(p.Z,{className:"w-3.5 h-3.5 mr-2 flex-shrink-0"}),(0,r.jsx)("span",{className:"truncate",children:e.name})]}),e.children&&e.children.length>0&&eX(e.children,t,n,a+1)]},e.id))},[eZ]),eQ=(0,s.useCallback)(e=>{let{conv:t,children:n}=e;return(0,r.jsxs)(P.h_,{children:[(0,r.jsx)(P.$F,{asChild:!0,children:n}),(0,r.jsxs)(P.AW,{align:"start",className:"w-48",children:[(0,r.jsxs)(P.Xi,{onSelect:()=>{setTimeout(()=>{document.body.style.pointerEvents="",eb(t),eC(t.title),ew(!0)},150)},children:[(0,r.jsx)(f.Z,{className:"w-3.5 h-3.5 mr-2"}),H("rename")]}),(0,r.jsxs)(P.Xi,{onSelect:()=>eM(t.id),children:[(0,r.jsx)(h.Z,{className:"w-3.5 h-3.5 mr-2"}),H("branchConversation")]}),(0,r.jsxs)(P.Ph,{children:[(0,r.jsxs)(P.kt,{children:[(0,r.jsx)(g.Z,{className:"w-3.5 h-3.5 mr-2"}),H("moveToFolder")]}),(0,r.jsxs)(P.TG,{className:"w-52 max-h-72 overflow-y-auto",children:[t.folder_id&&(0,r.jsxs)(P.Xi,{onSelect:()=>eZ(t.id,null),children:[(0,r.jsx)(x.Z,{className:"w-3.5 h-3.5 mr-2"}),H("removeFromFolder")]}),eB.length>0?eX(eB,t.id,t.folder_id):(0,r.jsx)(P.Xi,{disabled:!0,children:(0,r.jsx)("span",{className:"text-muted-foreground text-xs",children:H("noFolders")})})]})]}),(0,r.jsx)(P.VD,{}),(0,r.jsxs)(P.Xi,{onSelect:()=>eO(t.id),children:[(0,r.jsx)(v.Z,{className:"w-3.5 h-3.5 mr-2"}),H("archive")]}),(0,r.jsxs)(P.Xi,{onSelect:()=>eF(t.id),className:"text-destructive focus:text-destructive",children:[(0,r.jsx)(k.Z,{className:"w-3.5 h-3.5 mr-2"}),H("delete")]})]})]})},[eM,eZ,eO,eF,eB,eX,H]),eY=(0,s.useCallback)((e,n)=>{var a,s,i;let l=t===e.id,d=e.folder_id?eK.get(e.folder_id):null,u=null==o?void 0:o.get(e.id),m=null==u?void 0:u.agentStatus,p=m&&"idle"!==m?m:null!==(s=e.agent_status)&&void 0!==s?s:m,f=m&&"idle"!==m&&null!==(i=u.agentStatusUpdatedAt)&&void 0!==i?i:e.updated_at;return(0,r.jsxs)("div",{draggable:(null==n?void 0:n.draggable)&&"folder"===eh,onDragStart:(null==n?void 0:n.draggable)?t=>{t.dataTransfer.setData("application/json",JSON.stringify([e.id])),t.dataTransfer.effectAllowed="move"}:void 0,className:(0,T.cn)("group flex items-start gap-2 px-2 py-1.5 rounded-md text-sm transition-all duration-150 w-full cursor-pointer",(null==n?void 0:n.draggable)&&"folder"===eh&&"cursor-grab active:cursor-grabbing",l?"bg-card shadow-sm":"hover:bg-card/60"),"data-conversation-id":e.id,onClick:()=>null==c?void 0:c(e.id),children:[(0,r.jsx)("div",{className:"mt-0.5","data-agent-status":null!=p?p:"idle",children:(0,r.jsx)(Q,{sessionStatus:e.session_status,agentStatus:null!=p?p:null,updatedAt:f,nowMs:eu})}),(0,r.jsxs)("div",{className:"flex-1 min-w-0 overflow-hidden",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)("span",{className:(0,T.cn)("truncate flex-1 min-w-0 text-sm",l?"font-medium text-foreground":"text-foreground
1/80"),children:/^(Ny samtale|Untitled Session|New Session|Samtale|AI Chat)?$/i.test((null===(a=e.title)||void 0===a?void 0:a.trim())||"")?H("sessionWithDate",{date:new Date(e.created_at).toLocaleDateString(B($),{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}):e.title}),(null==u?void 0:u.hasUnread)&&!l&&(0,r.jsx)("span",{"aria-hidden":"true","data-conversation-unread":e.id,className:"h-1.5 w-1.5 rounded-full bg-foreground flex-shrink-0"}),(0,r.jsx)("span",{className:"text-[10px] text-muted-foreground/50 flex-shrink-0 tabular-nums",children:X(e.updated_at,$,H)})]}),"agent"===eh&&d&&(0,r.jsx)("div",{className:"flex items-center gap-1 mt-0.5",children:(0,r.jsx)("span",{className:"text-xs text-muted-foreground/50 truncate",children:d})})]}),(0,r.jsx)(eQ,{conv:e,children:(0,r.jsx)("button",{onClick:e=>e.stopPropagation(),className:"opacity-0 group-hover:opacity-100 p-0.5 rounded hover:bg-muted transition-all flex-shrink-0 mt-0.5",children:(0,r.jsx)(y.Z,{className:"w-3.5 h-3.5 text-muted-foreground"})})})]},e.id)},[t,o,eK,eh,c,eQ,$,H]),e$=(0,s.useMemo)(()=>{let e=new Map;for(let n of es){var t;n.parent_id&&e.set(n.parent_id,(null!==(t=e.get(n.parent_id))&&void 0!==t?t:0)+1)}let n=new Set(es.filter(t=>{var n;return t.is_system&&(null!==(n=e.get(t.id))&&void 0!==n?n:0)>0||t.id===q}).map(e=>e.id));return es.filter(e=>!n.has(e.id)).map(e=>{var t,r,a,s;return{id:e.id,name:e.name,parentId:e.parent_id&&n.has(e.parent_id)?null:e.parent_id,isSystem:e.is_system,count:(null!==(a=null===(t=eW[e.id])||void 0===t?void 0:t.length)&&void 0!==a?a:0)+(null!==(s=null===(r=eq[e.id])||void 0===r?void 0:r.length)&&void 0!==s?s:0)}})},[q,es,eW,eq]),e0=(0,s.useCallback)(async(e,t,n)=>{try{let r=await fetch(e,t);if(!r.ok){let e=await r.json().catch(()=>({}));return M.toast.error(e.error||n),!1}return!0}catch(e){return a.kg.error(n,e),M.toast.error(n),!1}},[]),[e1,e3]=(0,s.useState)(null),e2=(0,s.useCallback)(async e=>{if(!e1){e3(e.id);try{var t,n;let r=await fetch("/api/ai/conversations",{method:"POST",headers:{"Content-Type":"application/json",...(0,Z.p)()},body:JSON.stringify({folder_id:null!=q?q:e.id,workspace_id:null!==(n=null==en?void 0:en.id)&&void 0!==n?n:null,source:"workspace",active_skill_ids:G?[G]:void 0})});if(!r.ok){M.toast.error(H("couldNotStartConversationInFolder"));return}let a=await r.json(),s=null===(t=a.conversation)||void 0===t?void 0:t.id;if(!s){M.toast.error(H("couldNotStartConversationInFolder"));return}await e_(),null==c||c(s)}catch(e){a.kg.error("Failed to start a conversation in folder:",e),M.toast.error(H("couldNotStartConversationInFolder"))}finally{e3(null)}}},[q,G,e1,e_,c,H,null==en?void 0:en.id]),e5=(0,s.useMemo)(()=>({onNewConversation:e=>void e2(e),onNewSubfolder:e=>{ek(e.id),ex(!0)},onRename:async(e,t)=>{await e0("/api/production/folders/".concat(e.id),{method:"PATCH",headers:{"Content-Type":"application/json",...(0,Z.p)()},body:JSON.stringify({name:t})},Y("couldNotRename"))&&await eE()},onDuplicate:async e=>{await e0("/api/production/folders/".concat(e.id,"/duplicate"),{method:"POST",headers:(0,Z.p)()},Y("couldNotDuplicate"))&&await eE()},onMoveTo:async(e,t)=>{await e0("/api/production/folders/".concat(e.id),{method:"PATCH",headers:{"Content-Type":"application/json",...(0,Z.p)()},body:JSON.stringify({parent_id:t})},Y("couldNotMove"))&&await eE()},onSettings:e=>ee.push("/production/folders/".concat(e.id,"/settings")),onDelete:async e=>{await e0("/api/production/folders/".concat(e.id),{method:"DELETE",headers:(0,Z.p)()},Y("couldNotDelete"))&&await Promise.all([eE(),e_(),eD()])}}),[e0,e2,e_,eE,eD,ee,Y]),e4=(0,s.useCallback)(async(e,t)=>{let n=t.getData("application/x-production-file");if(n){try{let t=await fetch("/api/library/files/".concat(n),{method:"PATCH",headers:{"Content-Type":"application/json",...(0,Z.p)()},body:JSON.stringify({folder_id:e.id}),credentials:"include"});t.ok?await eD():(a.kg.error("Failed to move file:",await t.text()),M.toast.error(H("couldNotMoveFile")))}catch(e){a.kg.error("Failed to move file:",e),M.toast.error(H("couldNotMoveFile"))}return}let r=t.getData("application/json");if(r)try{let t=JSON.parse(r),n=!0;for(let r of Array.isArray(t)?t:[t]){let t=await fetch("/api/ai/conversations/".concat(r),{method:"PUT",headers:{"Content-Type":"application/json",...(0,Z.p)()},body:JSON.stringify({folder_id:e.id})});
1t.ok||(n=!1,a.kg.error("Failed to move conversation:",await t.text()))}await e_(),n||M.toast.error(H("couldNotMoveConversation"))}catch(e){a.kg.error("Failed to move conversation:",e),M.toast.error(H("couldNotMoveConversation"))}},[e_,eD,H]),e7=(0,s.useCallback)((e,t)=>{let n=eW[e.id]||[],a=eq[e.id]||[],s=e$.some(t=>t.parentId===e.id),i=n.length>0||a.length>0||s;return(0,r.jsxs)(r.Fragment,{children:[a.map(e=>(0,r.jsxs)("div",{draggable:!0,onDragStart:t=>{t.dataTransfer.setData("application/x-production-file",e.id),t.dataTransfer.effectAllowed="move"},className:(0,T.cn)("group flex items-start gap-2 py-1.5 pr-2 rounded-md text-sm transition-all duration-150 cursor-grab active:cursor-grabbing w-full","hover:bg-accent"),style:(0,A.sj)(t+1),onClick:()=>{let t="presentation"===e.type?"presentation":"dialogue"===e.type?"dialogue":"canvas";null==W||W(e.id,e.name,t)},children:[(0,r.jsx)("div",{className:"mt-0.5",children:"presentation"===e.type?(0,r.jsx)(w.Z,{className:"w-3.5 h-3.5 text-muted-foreground"}):"dialogue"===e.type?(0,r.jsx)(j.Z,{className:"w-3.5 h-3.5 text-muted-foreground"}):(0,r.jsx)(b.Z,{className:"w-3.5 h-3.5 text-muted-foreground"})}),(0,r.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)("span",{className:"truncate flex-1 min-w-0 text-sm text-foreground/80",children:e.name}),e.updated_at&&(0,r.jsx)("span",{className:"text-[10px] text-muted-foreground/50 flex-shrink-0 tabular-nums",children:X(e.updated_at,$,H)})]})})]},"prod-".concat(e.id))),n.map(e=>(0,r.jsx)("div",{className:"w-full",style:(0,A.sj)(t+1),children:eY(e,{draggable:!0})},e.id)),!i&&(0,r.jsx)("div",{style:(0,A.sj)(t+1),className:"text-xs text-muted-foreground/50 py-2 rounded-md transition-colors",children:H("dragConversationsHere")})]})},[eW,eq,e$,W,eY,$,H]),e6=(0,s.useCallback)(()=>{q?e2({id:q,name:H("configurationContent"),parentId:null}):null==d||d()},[q,e2,d,H]),e8=(0,r.jsx)(J,{configurationRootId:q,creatingConversation:!!e1,workspaceId:null==en?void 0:en.id,showBackLink:!ea,viewMode:eh,onNewConversation:e6,onViewModeChange:e=>{ef(e),localStorage.setItem("sidebar-view-mode",e)}}),e9=(0,r.jsx)("div",{children:ec?(0,r.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,r.jsx)(C.Gl,{size:"md"})}):"agent"===eh?(0,r.jsx)("div",{className:"space-y-0.5",children:eH.length>0?(0,r.jsxs)(r.Fragment,{children:[(eS?eH:eH.slice(0,8)).map(e=>eY(e)),eH.length>8&&(0,r.jsxs)("button",{onClick:()=>eT(e=>!e),className:"flex items-center gap-1.5 px-2 py-2 w-full text-xs text-muted-foreground hover:text-foreground transition-colors",children:[(0,r.jsx)(y.Z,{className:"w-3.5 h-3.5"}),(0,r.jsx)("span",{children:eS?H("showLess"):H("more")})]})]}):(0,r.jsx)("p",{className:"text-sm text-muted-foreground text-center py-8",children:H("startConversationPrompt")})}):(0,r.jsxs)("div",{className:"space-y-4",children:[(0,r.jsx)(_.Z,{folders:e$,actions:e5,renderChildren:e7,dragAndDrop:{onDrop:e4}}),(eG.length>0||eV.length>0)&&(0,r.jsxs)("div",{className:"w-full",children:[(0,r.jsx)("div",{className:"px-2 py-1 text-xs font-medium uppercase tracking-wider text-muted-foreground",children:q?H("configurationContent"):H("unsorted")}),(0,r.jsxs)("div",{className:"mt-1 space-y-0.5 w-full",children:[eV.map(e=>(0,r.jsxs)("div",{draggable:!0,onDragStart:t=>{t.dataTransfer.setData("application/x-production-file",e.id),t.dataTransfer.effectAllowed="move"},className:(0,T.cn)("group flex items-start gap-2 px-2 py-1.5 rounded-md text-sm transition-all duration-150 w-full cursor-grab active:cursor-grabbing","hover:bg-background/60"),onClick:()=>{let t="presentation"===e.type?"presentation":"dialogue"===e.type?"dialogue":"canvas";null==W||W(e.id,e.name,t)},children:[(0,r.jsx)("div",{className:"mt-0.5",children:"presentation"===e.type?(0,r.jsx)(w.Z,{className:"w-3.5 h-3.5 text-muted-foreground"}):"dialogue"===e.type?(0,r.jsx)(j.Z,{className:"w-3.5 h-3.5 text-muted-foreground"}):(0,r.jsx)(b.Z,{className:"w-3.5 h-3.5 text-muted-foreground"})}),(0,r.jsx)("div",{className:"flex-1 min-w-0 overflow-hidden",children:(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)("span",{className:"truncate flex-1 min-w-0 text-sm text-foreground
1/80",children:e.name}),e.updated_at&&(0,r.jsx)("span",{className:"text-[10px] text-muted-foreground/50 flex-shrink-0 tabular-nums",children:X(e.updated_at,$,H)})]})})]},"prod-unsorted-".concat(e.id))),eG.map(e=>eY(e,{draggable:!0}))]})]}),0===es.length&&0===el.length&&(0,r.jsx)("p",{className:"text-sm text-muted-foreground text-center py-8",children:H("startConversationOrCreateFolder")})]})}),te=(0,r.jsx)("div",{className:"p-3 border-t border-border/50 flex-shrink-0",children:(0,r.jsxs)(S.z,{onClick:()=>{ek(null!=q?q:null),ex(!0)},variant:"ghost",className:"w-full justify-start gap-2 text-muted-foreground hover:text-foreground",size:"sm",children:[(0,r.jsx)(N.Z,{className:"h-4 w-4"}),H("addFolder")]})});return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(E.t6,{surface:"worksessions",header:e8,footer:te,mobileTitle:H("aiChat"),className:V,children:e9}),(0,r.jsx)(F.CreateFolderDialog,{open:eg,onOpenChange:ex,workspaceId:(null==en?void 0:en.id)||"",projectId:er||"",defaultParentId:ev,existingFolders:es.map(e=>({id:e.id,name:e.name,parent_id:e.parent_id})),showParentSelector:!q,showConfigureOption:!0,onSuccess:()=>{eE()},onCreateAndConfigure:e=>{eE(),ee.push("/production/folders/".concat(e.id,"/settings"))}}),(0,r.jsx)(R.Vq,{open:ey,onOpenChange:e=>{ew(e),e||(eb(null),eC(""))},children:(0,r.jsxs)(R.cZ,{children:[(0,r.jsx)(R.fK,{children:(0,r.jsx)(R.$N,{children:H("rename")})}),(0,r.jsx)("div",{className:"py-4",children:(0,r.jsx)(D.I,{value:eN,onChange:e=>eC(e.target.value),onKeyDown:e=>{"Enter"===e.key&&ez()},autoFocus:!0})}),(0,r.jsxs)(R.cN,{children:[(0,r.jsx)(S.z,{variant:"outline",onClick:()=>ew(!1),children:H("cancel")}),(0,r.jsx)(S.z,{onClick:ez,children:H("save")})]})]})})]})})},51889:function(e,t,n){n.d(t,{be:function(){return u}});var r=n(27573),a=n(19369),s=n(68854),i=n(25555),l=n(95802),o=n(30609),c=n(88623);n(16273);var d=n(46393);function u(e){let{message:t,onRetry:n,onDismiss:s,className:i}=e,l=(0,d.T)("chat");return(0,r.jsxs)("div",{className:(0,a.cn)("flex items-center gap-2 px-3 py-2 rounded-lg","bg-destructive/10 border border-destructive/20","text-destructive text-sm","animate-in fade-in slide-in-from-bottom-1 duration-200",i),children:[(0,r.jsx)(o.Z,{className:"w-4 h-4 shrink-0"}),(0,r.jsx)("span",{className:"flex-1",children:t}),n&&(0,r.jsx)("button",{onClick:n,className:"p-1 hover:bg-destructive/10 rounded",title:l("tryAgain"),children:(0,r.jsx)(c.Z,{className:"w-3.5 h-3.5"})}),s&&(0,r.jsx)("button",{onClick:s,className:"p-1 hover:bg-destructive/10 rounded",title:l("close"),children:(0,r.jsx)("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:(0,r.jsx)("path",{d:"M18 6L6 18M6 6l12 12"})})})]})}s.Z,i.Z,l.Z,i.Z,o.Z},31804:function(e,t,n){n.r(t),n.d(t,{CodeBlock:function(){return p},InlineCode:function(){return f}});var r=n(27573),a=n(47200),s=n(7653),i=n(19369),l=n(87354),o=n(51856),c=n(45144),d=n(35756),u=n(46393);let m={js:"JavaScript",javascript:"JavaScript",ts:"TypeScript",typescript:"TypeScript",tsx:"TypeScript (React)",jsx:"JavaScript (React)",py:"Python",python:"Python",rb:"Ruby",ruby:"Ruby",go:"Go",rust:"Rust",rs:"Rust",java:"Java",kotlin:"Kotlin",swift:"Swift",cpp:"C++",c:"C",cs:"C#",csharp:"C#",php:"PHP",sql:"SQL",html:"HTML",css:"CSS",scss:"SCSS",sass:"Sass",json:"JSON",yaml:"YAML",yml:"YAML",xml:"XML",md:"Markdown",markdown:"Markdown",bash:"Bash",sh:"Shell",shell:"Shell",zsh:"Zsh",powershell:"PowerShell",ps1:"PowerShell",dockerfile:"Dockerfile",docker:"Docker",graphql:"GraphQL",prisma:"Prisma",vue:"Vue",svelte:"Svelte"};function p(e){var t;let{code:n,language:p,showLineNumbers:f=!1,className:h}=e,g=(0,u.T)("chat"),[x,v]=(0,s.useState)(!1),k=(0,s.useCallback)(async()=>{try{await navigator.clipboard.writeText(n),v(!0),setTimeout(()=>v(!1),2e3)}catch(e){a.kg.error("Failed to copy code:",e)}},[n]),y=(t=g("codeLanguage"),p?m[p.toLowerCase()]||p.toUpperCase():t);return(0,r.jsxs)("div",{className:(0,i.cn)("not-prose","relative group rounded-lg overflow-hidden","border border-border/50 bg-[#282c34]",h),children:[(0,r.jsxs)("div",{className:(0,i.cn)("flex items-center justify-between px-3 py-1.5","border-b border-white/10 bg-white/5"),children:[(0,r.jsx)("span",{className:"text-xs text-white/60 font-mono",children:y}),(0,r.jsx)("button",{onClick:k,className:(0,i.cn)("flex items-center gap-1.5 px-2 py-1 rounded-md text-xs","transition-all duration-200","text-white/60 hover:text-white hover:bg-white/10",x&&"text-green-400 bg-green-500/10"),"aria-label":g(x?"copied":"copyCode"),children:x?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(l.Z,{className:"w-3.5 h-3.5"}),(0,r.jsx)("span",{children:g("copied")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(o.Z,{className:"w-3.5 h-3.5"}),(0,r.jsx)("span",{className:"hidden sm:inline",children:g("copy")})]})})]}),(0,r.jsx)(c.Z,{style:d.Z,language:p||"text",showLineNumbers:f,customStyle:{margin:0,padding:"1rem",background:"transparent",fontSize:"0.875rem",lineHeight:"1.5"},codeTagProps:{style:{fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',color:"#abb2bf"}},PreTag:e=>{let{children:t,...n}=e;return(0,r.jsx)("pre",{...n,className:"!bg-transparent !text-[#abb2bf]",children:t})},children:n})]})}function f(e){let{children:t,className:n}=e;return(0,r.jsx)("code",{className:(0,i.cn)("px-1.5 py-0.5 rounded text-sm","bg-muted-foreground
1/10 text-foreground","font-mono",n),children:t})}t.default=p},40233:function(e,t,n){n.r(t),n.d(t,{DiffOverlay:function(){return x}});var r=n(27573),a=n(7653),s=n(16273),i=n(26798),l=n(82041),o=n(11440),c=n(96825),d=n(10269),u=n(58410),m=n(2966),p=n(87354),f=n(71505),h=n(19369),g=n(46393);function x(e){let{patches:t,activePatchIndex:n,onApply:x,onReject:v,onSkip:k,onApproveAll:y,onRejectAll:w,onNavigate:j,onClose:b,className:N}=e,C=(0,g.T)("chat"),[S,T]=(0,a.useState)({x:20,y:100}),[I,E]=(0,a.useState)(!1),_=(0,a.useRef)(null),A=(0,a.useRef)(null),R=t[n],P=t.filter(e=>"pending"===e.status).length,D=(0,a.useCallback)(e=>{e.preventDefault(),E(!0),_.current={startX:e.clientX,startY:e.clientY,startPosX:S.x,startPosY:S.y}},[S]),F=(0,a.useCallback)(e=>{if(!I||!_.current)return;let t=e.clientX-_.current.startX,n=e.clientY-_.current.startY;T({x:_.current.startPosX+t,y:_.current.startPosY+n})},[I]),O=(0,a.useCallback)(()=>{E(!1),_.current=null},[]);a.useEffect(()=>{if(I)return window.addEventListener("mousemove",F),window.addEventListener("mouseup",O),()=>{window.removeEventListener("mousemove",F),window.removeEventListener("mouseup",O)}},[I,F,O]);let U=(0,a.useCallback)(()=>{n>0&&j&&j(n-1)},[n,j]),L=(0,a.useCallback)(()=>{n<t.length-1&&j&&j(n+1)},[n,t.length,j]);return R?(0,r.jsx)("div",{ref:A,id:"diff-overlay-".concat(R.id),className:(0,h.cn)("fixed z-50 shadow-2xl rounded-lg",I&&"cursor-grabbing",N),style:{left:S.x,top:S.y,maxWidth:"400px",minWidth:"320px"},children:(0,r.jsxs)(i.Zb,{className:"border-2 border-blue-500/50 dark:border-blue-400/50 overflow-hidden",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 bg-blue-50 dark:bg-blue-950/50 border-b cursor-grab active:cursor-grabbing",onMouseDown:D,children:[(0,r.jsx)(c.Z,{className:"h-4 w-4 text-muted-foreground"}),(0,r.jsxs)("div",{className:"flex-1 flex items-center gap-2",children:[(0,r.jsxs)(l.C,{variant:"outline",className:"text-xs",children:[n+1," / ",t.length]}),(0,r.jsx)("span",{className:"text-sm font-medium truncate",children:R.section})]}),(0,r.jsx)(l.C,{variant:P>0?"default":"secondary",className:"text-xs",children:C("remainingCount",{count:P})}),b&&(0,r.jsx)(s.z,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:b,"aria-label":C("close"),children:(0,r.jsx)(d.Z,{className:"h-4 w-4"})})]}),(0,r.jsx)(o.x,{className:"max-h-[300px]",children:(0,r.jsx)("div",{className:"p-3 space-y-1 font-mono text-xs",id:"patch-".concat(R.id),children:R.diffLines.map((e,t)=>(0,r.jsxs)("div",{className:(0,h.cn)("px-2 py-0.5 rounded-sm","removed"===e.type&&"bg-red-500/20 text-red-700 dark:text-red-300","added"===e.type&&"bg-green-500/20 text-green-700 dark:text-green-300","unchanged"===e.type&&"text-muted-foreground","context"===e.type&&"text-muted-foreground/50 italic"),children:[(0,r.jsx)("span",{className:"select-none mr-2 opacity-50",children:"removed"===e.type?"-":"added"===e.type?"+":" "}),e.text||" "]},t))})}),j&&t.length>1&&(0,r.jsxs)("div",{className:"flex items-center justify-between px-3 py-2 border-t bg-muted/30",children:[(0,r.jsxs)(s.z,{variant:"ghost",size:"sm",onClick:U,disabled:0===n,children:[(0,r.jsx)(u.Z,{className:"h-4 w-4 mr-1"}),C("previous")]}),(0,r.jsxs)(s.z,{variant:"ghost",size:"sm",onClick:L,disabled:n===t.length-1,children:[C("next"),(0,r.jsx)(m.Z,{className:"h-4 w-4 ml-1"})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap gap-2 p-3 border-t bg-muted/20",children:[(0,r.jsxs)("div",{className:"flex gap-2 flex-1",children:[(0,r.jsxs)(s.z,{size:"sm",variant:"default",className:"flex-1 bg-green-600 hover:bg-green-700 text-white",onClick:()=>x(n),disabled:"pending"!==R.status,children:[(0,r.jsx)(p.Z,{className:"h-4 w-4 mr-1"}),C("accept")]}),(0,r.jsxs)(s.z,{size:"sm",variant:"outline",className:"flex-1 border-red-300 text-red-600 hover:bg-red-50 dark:hover:bg-red-950/20",onClick:()=>v(n),disabled:"pending"!==R.status,children:[(0,r.jsx)(d.Z,{className:"h-4 w-4 mr-1"}),C("reject")]}),k&&(0,r.jsx)(s.z,{size:"sm",variant:"ghost",onClick:()=>k(n),disabled:"pending"!==R.status,children:(0,r.jsx)(f.Z,{className:"h-4 w-4"})})]}),P>1&&(0,r.jsxs)("div",{className:"flex gap-2 w-full pt-2 border-t",children:[(0,r.jsxs)(s.z,{size:"sm",variant:"outline",className:"flex-1 text-xs",onClick:y,children:[(0,r.jsx)(p.Z,{className:"h-3 w-3 mr-1"}),C("acceptAllCount",{count:P})]}),(0,r.jsxs)(s.z,{size:"sm",variant:"ghost",className:"flex-1 text-xs text-muted-foreground",onClick:w,children:[(0,r.jsx)(d.Z,{className:"h-3 w-3 mr-1"}),C("rejectAll")]})]})]}),"pending"!==R.status&&(0,r.jsxs)("div",{className:(0,h.cn)("px-3 py-2 text-center text-sm font-medium","approved"===R.status&&"bg-green-100 dark:bg-green-950/30 text-green-700 dark:text-green-300","rejected"===R.status&&"bg-red-100 dark:bg-red-950/30 text-red-700 dark:text-red-300","skipped"===R.status&&"bg-yellow-100 dark:bg-yellow-950/30 text-yellow-700 dark:text-yellow-300"),children:["approved"===R.status&&"✅ ".concat(C("approved")),"rejected"===R.status&&"❌ ".concat(C("rejected")),"skipped"===R.status&&"⏭️ ".concat(C("skipped"))]})]})}):null}t.default=x},23664:function(e,t,n){n.d(t,{eU:function(){return h.DiffOverlay},tN:function(){return T},h6:function(){return E},c6:function(){return r.UniversalAIChat}}),n(2820),n(43274);var r=n(24452),a=n(27573);n(47200);var s=n(7653);n(81695);var i=n(16273),l=n(11440);n(98521),n(63769),n(76225),n(99696),n(30048),n(21764),n(4520),n(81775),n(59916),n(17515),n(29330
1),n(31804),n(65316),n(57219),n(84643),n(51889),n(29656),n(79590);var o=n(90743),c=n(36673),d=n(72829),u=n(670),m=n(31815),p=n(34078),f=n(92482);o.Z,c.Z,d.Z,u.Z,m.Z,p.Z,f.Z,n(20575),n(81920);var h=n(40233),g=n(26798),x=n(82041),v=n(79901),k=n(53512),y=n(71505),w=n(64386),j=n(2966),b=n(87354),N=n(10269),C=n(19369),S=n(46393);function T(e){let{patches:t,activePatchIndex:n,onPatchClick:r,onApproveAll:o,onRejectAll:d,onScrollToSection:u,className:m}=e,p=(0,S.T)("chat"),f=t.filter(e=>"pending"===e.status).length,h=t.filter(e=>"approved"===e.status).length,T=t.filter(e=>"rejected"===e.status).length,I=(0,s.useCallback)(e=>{let n=t[e];n&&(r(e),u&&n.section&&u(n.section))},[t,r,u]),E=e=>{switch(e){case"approved":return(0,a.jsx)(v.Z,{className:"h-4 w-4 text-green-600 dark:text-green-400"});case"rejected":return(0,a.jsx)(k.Z,{className:"h-4 w-4 text-red-600 dark:text-red-400"});case"skipped":return(0,a.jsx)(y.Z,{className:"h-4 w-4 text-yellow-600 dark:text-yellow-400"});default:return(0,a.jsx)(w.Z,{className:"h-4 w-4 text-muted-foreground"})}};return(0,a.jsxs)(g.Zb,{className:(0,C.cn)("flex flex-col",m),children:[(0,a.jsxs)("div",{className:"flex items-center justify-between px-3 py-2 border-b bg-muted/30",children:[(0,a.jsxs)("div",{className:"flex items-center gap-2",children:[(0,a.jsx)(c.Z,{className:"h-4 w-4 text-muted-foreground"}),(0,a.jsx)("span",{className:"text-sm font-medium",children:p("changes")}),(0,a.jsx)(x.C,{variant:"outline",className:"text-xs",children:t.length})]}),(0,a.jsxs)("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[h>0&&(0,a.jsxs)("span",{className:"text-green-600 dark:text-green-400",children:["✓",h]}),T>0&&(0,a.jsxs)("span",{className:"text-red-600 dark:text-red-400",children:["✗",T]}),f>0&&(0,a.jsxs)("span",{children:["○",f]})]})]}),(0,a.jsx)(l.x,{className:"flex-1 max-h-[200px]",children:(0,a.jsx)("div",{className:"p-2 space-y-1",children:t.map((e,t)=>(0,a.jsxs)("button",{id:"patch-nav-".concat(e.id),onClick:()=>I(t),className:(0,C.cn)("w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left text-sm transition-colors","hover:bg-muted/50",t===n&&"bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800","approved"===e.status&&"opacity-60","rejected"===e.status&&"opacity-40 line-through"),children:[E(e.status),(0,a.jsx)("span",{className:"flex-1 truncate",children:e.section}),t===n&&(0,a.jsx)(j.Z,{className:"h-4 w-4 text-blue-600 dark:text-blue-400"})]},e.id))})}),f>0&&(0,a.jsxs)("div",{className:"flex gap-2 p-2 border-t bg-muted/20",children:[(0,a.jsxs)(i.z,{size:"sm",variant:"outline",className:"flex-1 text-xs h-7",onClick:o,children:[(0,a.jsx)(b.Z,{className:"h-3 w-3 mr-1"}),p("acceptAllCount",{count:f})]}),(0,a.jsxs)(i.z,{size:"sm",variant:"ghost",className:"flex-1 text-xs h-7 text-muted-foreground",onClick:d,children:[(0,a.jsx)(N.Z,{className:"h-3 w-3 mr-1"}),p("rejectAll")]})]}),0===f&&t.length>0&&(0,a.jsx)("div",{className:"p-3 text-center text-sm text-muted-foreground border-t",children:h===t.length?(0,a.jsxs)("span",{className:"text-green-600 dark:text-green-400",children:["✅ ",p("allChangesApproved")]}):T===t.length?(0,a.jsxs)("span",{className:"text-red-600 dark:text-red-400",children:["❌ ",p("allChangesRejected")]}):(0,a.jsx)("span",{children:p("changesDecisionSummary",{approved:h,rejected:T})})})]})}var I=n(59622);function E(e){let{onUndo:t,timeoutSeconds:n=30,className:r,label:l}=e,o=(0,S.T)("chat"),[c,d]=(0,s.useState)(n),[u,m]=(0,s.useState)(!0),p=(0,s.useRef)(null);(0,s.useEffect)(()=>{if(c<=0){m(!1);return}return p.current=setTimeout(()=>{d(e=>e-1)},1e3),()=>{p.current&&clearTimeout(p.current)}},[c]);let f=(0,s.useCallback)(()=>{p.current&&clearTimeout(p.current),t(),m(!1)},[t]);return u?(0,a.jsxs)(i.z,{variant:"outline",size:"sm",onClick:f,className:(0,C.cn)("gap-2 transition-all",c<=5&&"border-orange-400 text-orange-600 dark:border-orange-600 dark:text-orange-400",c<=3&&"animate-pulse",r),children:[(0,a.jsx)(I.Z,{className:"h-4 w-4"}),(0,a.jsx)("span",{children:null!=l?l:o("undo")}),(0,a.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",o("secondsShort",{count:c}
1),")"]})]}):null}},81775:function(e,t,n){n.r(t),n.d(t,{PromptPicker:function(){return x}});var r=n(27573),a=n(47200),s=n(7653),i=n(19369),l=n(16273),o=n(63769),c=n(11440),d=n(98521),u=n(13040),m=n(70548),p=n(95731),f=n(32917),h=n(17515),g=n(46393);function x(e){let{open:t,onOpenChange:n,onSelect:x}=e,v=(0,g.T)("chat"),[k,y]=(0,s.useState)([]),[w,j]=(0,s.useState)([]),[b,N]=(0,s.useState)(!1),[C,S]=(0,s.useState)(""),[T,I]=(0,s.useState)("all"),[E,_]=(0,s.useState)(null),A=(0,s.useRef)(!1),R=(0,s.useCallback)(async()=>{try{let e=await fetch("/api/prompts/categories");if(e.ok){let t=await e.json();j(t.categories||[])}}catch(e){a.kg.error("Failed to fetch categories:",e)}},[]),P=(0,s.useCallback)(async function(e,t){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];n&&N(!0);try{let n=new URLSearchParams;e&&n.set("search",e),t&&"all"!==t&&n.set("category",t);let r=await fetch("/api/prompts?".concat(n.toString())),s=await r.json();r.ok?y(s.prompts||[]):(a.kg.error("[PromptPicker] API error:",s),y([]))}catch(e){a.kg.error("[PromptPicker] Failed to fetch prompts:",e),y([])}finally{n&&N(!1)}},[]);return(0,s.useEffect)(()=>{A.current||(A.current=!0,R(),P(void 0,void 0,!1))},[R,P]),(0,s.useEffect)(()=>{t&&(_(null),0===k.length&&P())},[t,k.length,P]),(0,s.useEffect)(()=>{let e=setTimeout(()=>{t&&P(C||void 0,T)},300);return()=>clearTimeout(e)},[C,T,t,P]),(0,r.jsx)(d.Vq,{open:t,onOpenChange:n,children:(0,r.jsxs)(d.cZ,{className:"max-w-3xl max-h-[80vh] flex flex-col",children:[(0,r.jsxs)(d.fK,{children:[(0,r.jsxs)(d.$N,{className:"flex items-center gap-2",children:[(0,r.jsx)(m.Z,{className:"w-5 h-5 text-primary"}),v("promptLibrary")]}),(0,r.jsx)(d.Be,{children:v("promptPickerDescription")})]}),(0,r.jsxs)("div",{className:"flex gap-3",children:[(0,r.jsxs)("div",{className:"relative flex-1",children:[(0,r.jsx)(p.Z,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),(0,r.jsx)(o.I,{placeholder:v("searchPrompts"),value:C,onChange:e=>S(e.target.value),className:"pl-9"})]}),(0,r.jsxs)(u.Ph,{value:T,onValueChange:I,children:[(0,r.jsx)(u.i4,{className:"w-[180px]",children:(0,r.jsx)(u.ki,{placeholder:v("category")})}),(0,r.jsxs)(u.Bw,{children:[(0,r.jsx)(u.Ql,{value:"all",children:v("allCategories")}),w.map(e=>(0,r.jsx)(u.Ql,{value:e.slug,children:e.name},e.slug))]})]})]}),(0,r.jsxs)("div",{className:"flex-1 flex gap-4 min-h-[300px] max-h-[400px]",children:[(0,r.jsx)(c.x,{className:"flex-1 border rounded-lg",children:b?(0,r.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,r.jsx)(h.KI,{size:"sm"})}):0===k.length?(0,r.jsxs)("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[(0,r.jsx)(f.Z,{className:"w-12 h-12 text-muted-foreground/50 mb-3"}),(0,r.jsx)("p",{className:"text-muted-foreground",children:v(C?"noPromptsFound":"noPromptsInLibrary")})]}):(0,r.jsx)("div",{className:"p-1",children:k.map(e=>(0,r.jsx)("button",{onClick:()=>_(e),className:(0,i.cn)("w-full text-left px-3 py-2 rounded-md text-sm transition-colors","hover:bg-muted/50",(null==E?void 0:E.id)===e.id&&"bg-primary/10 text-primary font-medium"),children:e.name},e.id))})}),E&&(0,r.jsxs)("div",{className:"w-[300px] flex-shrink-0 border-l pl-4 flex flex-col",children:[(0,r.jsx)("h4",{className:"font-medium mb-2 flex-shrink-0",children:v("promptPreview")}),(0,r.jsx)("div",{className:"flex-1 min-h-0 rounded-lg bg-muted/30 overflow-hidden",children:(0,r.jsx)(c.x,{className:"h-full max-h-[350px]",children:(0,r.jsx)("pre",{className:"text-sm whitespace-pre-wrap font-mono p-3",children:E.content})})})]})]}),(0,r.jsxs)("div",{className:"flex justify-end gap-2 pt-2 border-t",children:[(0,r.jsx)(l.z,{variant:"outline",onClick:()=>n(!1),children:v("cancel")}),(0,r.jsx)(l.z,{onClick:()=>{E&&(x(E),n(!1))},disabled:!E,children:v("usePrompt")})]})]})})}t.default=x},24452:function(e,t,n){n.r(t),n.d(t,{CLEAR_CONVERSATION_SETTLEMENT_DEADLINE_MS:function(){return nU},UniversalAIChat:function(){return nL},default:function(){return nM}});var r=n(27573),a=n(82622),s=n(52260),i=n(34782),l=n(47200),o=n(7653),c=n(81695),d=n(37811),u=n(46393),m=n(19369),p=n(59971),f=n(26918);n(74859),(()=>{let e={workspaceBrief:2e4,folderInstructions:2e4,skillInstructions:1e4,workspaceDescription:2e3,contextFilesTotal:45e3,contextFilePerFile:12e3,toolResultPerCallCap:12e3},t=(t,n)=>({...e,historyTotal:t,historyRecentMessagesToKeep:n});return t(2e4,4),t(12e3,4),t(4e3,2),t(2e4,4),t(12e3,4),t(4e3,2),t(2e4,4),t(12e3,4),t(4e3,2),t(2e4,4),t(12e3,4),t(4e3,2),t(2e4,4),t(12e3,4),t(4e3,2)})(),(()=>{let e={workspaceBrief:8e3,folderInstructions:4e3,skillInstructions:4e3,workspaceDescription:1e3,contextFilesTotal:2e4,contextFilePerFile:6e3,toolResultPerCallCap:8e3},t=(t,n)=>({...e,historyTotal:t,historyRecentMessagesToKeep:n});return t(12e3,4),t(8e3,4),t(3e3,2),t(12e3,4),t(8e3,4),t(3e3,2),t(12e3,4),t(8e3,4),t(3e3,2),t(2e4,6),t(14e3,6),t(6e3,2),t(1e4,4),t(6e3,4),t(2e3,2)})();
1let h=new Set(["image/jpeg","image/png","image/gif","image/webp"]),g=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function x(e){if(void 0===e)return[];if(!Array.isArray(e))return null;let t=[],n=new Set;for(let r of e){if(!r||"object"!=typeof r||Array.isArray(r)||"string"!=typeof r.id||!g.test(r.id)||n.has(r.id.toLowerCase())||"string"!=typeof r.name||!r.name.trim()||"string"!=typeof r.content)return null;n.add(r.id.toLowerCase());let e={id:r.id,name:r.name,content:r.content};if(void 0!==r.images){if(!Array.isArray(r.images))return null;let t=[];for(let e of r.images){if(!e||"object"!=typeof e||"string"!=typeof e.data||!e.data||!h.has(e.mediaType)||void 0!==e.pageNumber&&(!Number.isSafeInteger(e.pageNumber)||e.pageNumber<1)||void 0!==e.description&&"string"!=typeof e.description)return null;t.push({data:e.data,mediaType:e.mediaType,...void 0!==e.pageNumber&&{pageNumber:e.pageNumber},...void 0!==e.description&&{description:e.description}})}e.images=t}t.push(e)}return t}function v(e){return"".concat("auto-start:").concat(e)}function k(e,t){return null!==t&&e.id===v(t)&&"[START]"===e.content}function y(e){var t;return(null===(t=e.internal)||void 0===t?void 0:t.v)===1&&"silent"===e.internal.visibility}function w(e){var t,n,r;if(!e||"object"!=typeof e||"string"!=typeof e.id||"string"!=typeof e.content)return null;let a=e.internal;return a&&"object"==typeof a?1===a.v&&"silent"===a.visibility&&"string"==typeof a.kind&&["workflow_start","tool_complete","runtime_continue","auto_prompt"].includes(a.kind)&&"string"==typeof a.turnRequestId?{id:e.id,content:e.content,attachments:null!==(r=x(e.attachments))&&void 0!==r?r:[],internal:a}:{id:e.id,content:e.content,attachments:null!==(n=x(e.attachments))&&void 0!==n?n:[]}:{id:e.id,content:e.content,attachments:null!==(t=x(e.attachments))&&void 0!==t?t:[]}}function j(e,t){return{v:1,visibility:"silent",kind:e,turnRequestId:null!=t?t:b()}}function b(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();let e=Array.from({length:12},()=>Math.floor(16*Math.random()).toString(16)).join("");return"00000000-0000-4000-8000-".concat(e)}var N=n(97041),C=n(34282),S=n(92482),T=n(6315),I=n(17022),E=n(58153),_=n(2461),A=n(16273),R=n(30048);function P(e){let{resolvedLayout:t,showSidebar:n,sidebarOpen:a,onToggleSidebar:s,t:i}=e;return"chat"===t&&n?(0,r.jsx)(R.pn,{children:(0,r.jsxs)(R.u,{children:[(0,r.jsx)(R.aJ,{asChild:!0,children:(0,r.jsx)(A.z,{variant:"ghost",size:"icon-sm",onClick:s,className:"text-muted-foreground","aria-label":i(a?"hideProjects":"showProjects"),"aria-expanded":a,children:a?(0,r.jsx)(N.Z,{className:"w-4 h-4","aria-hidden":"true"}):(0,r.jsx)(C.Z,{className:"w-4 h-4","aria-hidden":"true"})})}),(0,r.jsx)(R._v,{side:"right",children:(0,r.jsx)("p",{children:i(a?"hideProjects":"showProjects")})})]})}):null}function D(e){let{effectiveMode:t,resolvedLayout:n,showSidebar:a,sidebarOpen:s,onToggleSidebar:i,isEditingTitle:l,editingTitleValue:o,onEditingTitleValueChange:c,onSaveTitle:d,onCancelEditTitle:u,onStartEditTitle:p,titleInputRef:f,conversationTitle:h,document:g,folderContext:x,t:v}=e;return(0,r.jsxs)("div",{className:"flex items-center gap-2 min-w-0 flex-1 overflow-hidden",children:[(0,r.jsx)(P,{resolvedLayout:n,showSidebar:a,sidebarOpen:s,onToggleSidebar:i,t:v}),(0,r.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,r.jsx)(S.Z,{className:(0,m.cn)("text-primary/70 flex-shrink-0","wide"===t?"w-5 h-5":"w-4 h-4")}),l&&!g?(0,r.jsx)("div",{className:"flex items-center gap-1",children:(0,r.jsx)("input",{ref:f,type:"text",value:o,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&d(),"Escape"===e.key&&u()},onBlur:d,"aria-label":v("clickToRename"),className:(0,m.cn)("bg-transparent border-b border-primary/50 focus:border-primary outline-none font-black text-foreground","wide"===t?"text-lg w-[280px]":"text-sm w-[140px]")})}):(0,r.jsxs)("button",{onClick:p,className:"group flex items-center gap-1.5 min-w-0",title:v("clickToRename"),children:[(0,r.jsx)("h1",{className:(0,m.cn)("font-black text-foreground truncate","wide"===t?"text-lg max-w-[250px]":"text-sm max-w-[130px]"),children:g?g.name:h}),!g&&(0,r.jsx)(T.Z,{className:"w-3 h-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"})]}),x&&(0,r.jsxs)("div",{className:"flex items-center gap-1 px-2 py-0.5 bg-muted/50 rounded text-xs text-muted-foreground flex-shrink min-w-0",children:[(0,r.jsx)(I.Z,{className:"w-3 h-3 flex-shrink-0"}),(0,r.jsx)("span",{className:"truncate",children:x.folder.name})]})]})]})}function F(e){let{effectiveMode:t,resolvedLayout:n,headerAction:a,onOpenCanvas:s,messages:i,document:l,presentationContext:o,onClearConversation:c,t:d}=e;return(0,r.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a,s&&"chat"===n&&i.length>0&&(0,r.jsx)(R.pn,{children:(0,r.jsxs)(R.u,{children:[(0,r.jsx)(R.aJ,{asChild:!0,children:(0,r.jsxs)(A.z,{variant:"ghost",size:"sm",onClick:()=>{let e=[...i].reverse().find(e=>"assistant"===e.role);e&&s(e.content)},className:"text-muted-foreground hover:text-foreground","aria-label":d("openInCanvas"),children:[(0,r.jsx)(E.Z,{className:"w-4 h-4 mr-1","aria-hidden":"true"}),(0,r.jsx)("span",{className:(0,m.cn)("narrow"===t&&"hidden"),children:d("openInCanvas")})]})}),(0,r.jsx)(R._v,{side:"bottom",children:(0,r.jsx)("p",{children:d("openInCanvasF
1orEditing")})})]})}),(l||o)&&i.length>0&&(0,r.jsx)(R.pn,{children:(0,r.jsxs)(R.u,{children:[(0,r.jsx)(R.aJ,{asChild:!0,children:(0,r.jsx)(A.z,{variant:"ghost",size:"icon",onClick:c,className:"h-8 w-8 text-muted-foreground hover:text-foreground","aria-label":d("clearConversation"),children:(0,r.jsx)(_.Z,{className:"w-4 h-4","aria-hidden":"true"})})}),(0,r.jsx)(R._v,{side:"bottom",children:(0,r.jsx)("p",{children:d("clearConversation")})})]})})]})}function O(e){let{hideHeader:t,effectiveMode:n,resolvedLayout:a,showSidebar:s,sidebarOpen:i,onToggleSidebar:l,isEditingTitle:o,editingTitleValue:c,onEditingTitleValueChange:d,onSaveTitle:u,onCancelEditTitle:p,onStartEditTitle:f,titleInputRef:h,conversationTitle:g,document:x,folderContext:v,headerAction:k,onOpenCanvas:y,messages:w,presentationContext:j,onClearConversation:b,t:N}=e;return t?null:(0,r.jsxs)("header",{className:(0,m.cn)("flex items-center justify-between border-b border-border/30 gap-2","wide"===n?"px-4 py-3":"px-3 py-2"),children:[(0,r.jsx)(D,{effectiveMode:n,resolvedLayout:a,showSidebar:s,sidebarOpen:i,onToggleSidebar:l,isEditingTitle:o,editingTitleValue:c,onEditingTitleValueChange:d,onSaveTitle:u,onCancelEditTitle:p,onStartEditTitle:f,titleInputRef:h,conversationTitle:g,document:x,folderContext:v,t:N}),(0,r.jsx)(F,{effectiveMode:n,resolvedLayout:a,headerAction:k,onOpenCanvas:y,messages:w,document:x,presentationContext:j,onClearConversation:b,t:N})]})}var U=n(4520),L=n(81775),M=n(59916),Z=n(98521),z=n(62665),K=n(64711),W=n(30609),q=n(31095),G=n(18948),V=n(26691),H=n(17515);function J(e){if("priority"===e.type)return"".concat(e.progress,"%");if("12_month_goal"===e.type&&"kpi"in e&&void 0!==e.current&&void 0!==e.target){let t=e.unit||"";return"".concat(e.current,"/").concat(e.target).concat(t?" "+t:"")}return"".concat(e.progress,"%")}function B(e){let{priority:t,selected:n,onToggle:a,t:s}=e;return(0,r.jsxs)(z.di,{value:t.id,onSelect:a,className:"flex items-center gap-3 px-3 py-2",children:[(0,r.jsx)(K.X,{checked:n,className:"h-4 w-4",onClick:e=>e.stopPropagation(),onCheckedChange:a}),(0,r.jsx)("div",{className:(0,m.cn)("h-2.5 w-2.5 rounded-full flex-shrink-0",function(e){switch(e){case"on_track":return"bg-green-500";case"at_risk":return"bg-yellow-500";case"off_track":return"bg-red-500";default:return"bg-gray-500"}}(t.status)),title:function(e,t){switch(e){case"on_track":return t("priorityStatusOnTrack");case"at_risk":return t("priorityStatusAtRisk");case"off_track":return t("priorityStatusOffTrack");default:return t("unknown")}}(t.status,s)}),(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsx)("div",{className:"text-sm font-medium truncate",children:t.name}),t.category&&(0,r.jsx)("div",{className:"text-xs text-muted-foreground truncate",children:t.category})]}),(0,r.jsx)("div",{className:"text-xs text-muted-foreground flex-shrink-0",children:J(t)})]})}function X(e){let{goal:t,selected:n,onToggle:a}=e;return(0,r.jsxs)(z.di,{value:t.id,onSelect:a,className:"flex items-center gap-3 px-3 py-2",children:[(0,r.jsx)(K.X,{checked:n,className:"h-4 w-4",onClick:e=>e.stopPropagation(),onCheckedChange:a}),(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsx)("div",{className:"text-sm font-medium truncate",children:t.name}),(t.kpi||t.category)&&(0,r.jsx)("div",{className:"text-xs text-muted-foreground truncate",children:t.kpi||t.category})]}),(0,r.jsx)("div",{className:"text-xs text-muted-foreground flex-shrink-0",children:J(t)})]})}function Q(e){let{query:t,onToggle:n,selectedIds:a}=e,s=(0,u.T)("chat"),[i,l]=(0,o.useState)(null),[c,d]=(0,o.useState)(!0),[m,p]=(0,o.useState)(null);(0,o.useEffect)(()=>{!async function(){try{d(!0),p(null);let e=await fetch("/api/ai/context/goals");if(!e.ok)throw Error(s("goalsAndPrioritiesLoadFailed"));let t=await e.json();l(t)}catch(e){p(e instanceof Error?e.message:s("unknownError"))}finally{d(!1)}}()},[s]);let f=(0,o.useMemo)(()=>{if(!(null==i?void 0:i.priorities))return[];if(!t)return i.priorities;let e=t.toLowerCase();return i.priorities.filter(t=>{var n,r;return t.name.toLowerCase().includes(e)||(null===(n=t.category)||void 0===n?void 0:n.toLowerCase().includes(e))||(null===(r=t.owner)||void 0===r?void 0:r.toLowerCase().includes(e))})},[null==i?void 0:i.priorities,t]),h=(0,o.useMemo)(()=>
1{if(!(null==i?void 0:i.goals))return[];if(!t)return i.goals;let e=t.toLowerCase();return i.goals.filter(t=>{var n,r,a;return t.name.toLowerCase().includes(e)||(null===(n=t.category)||void 0===n?void 0:n.toLowerCase().includes(e))||(null===(r=t.kpi)||void 0===r?void 0:r.toLowerCase().includes(e))||(null===(a=t.owner)||void 0===a?void 0:a.toLowerCase().includes(e))})},[null==i?void 0:i.goals,t]),g=(0,o.useMemo)(()=>h.filter(e=>"12_month_goal"===e.type),[h]),x=(0,o.useMemo)(()=>h.filter(e=>"long_term_goal"===e.type),[h]),v=(0,o.useCallback)(e=>{var t,r;if(!n)return;let s=a.includes(e.id);n("priority"===e.type?(t=!s,{id:e.id,name:e.name,description:e.category||void 0,category:"goals",data:e,badge:J(e),badgeVariant:"on_track"===e.status?"success":"at_risk"===e.status?"warning":"danger",selected:t}):(r=!s,{id:e.id,name:e.name,description:e.category||e.kpi||e.description||void 0,category:"goals",data:e,badge:J(e),selected:r}))},[n,a]);return c?(0,r.jsxs)("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[(0,r.jsx)(H.Gl,{size:"md"}),(0,r.jsx)("span",{className:"text-sm",children:s("loadingGoalsAndPriorities")})]}):m?(0,r.jsxs)("div",{className:"flex items-center justify-center py-8 text-destructive",children:[(0,r.jsx)(W.Z,{className:"h-5 w-5 mr-2"}),(0,r.jsx)("span",{className:"text-sm",children:m})]}):f.length>0||g.length>0||x.length>0?(0,r.jsxs)("div",{className:"overflow-y-auto max-h-[350px]",children:[f.length>0&&(0,r.jsx)(z.fu,{heading:(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)(G.Z,{className:"h-3.5 w-3.5 text-teal-500"}),s("priorities")]}),children:f.map(e=>(0,r.jsx)(B,{priority:e,selected:a.includes(e.id),onToggle:()=>v(e),t:s},e.id))}),g.length>0&&(0,r.jsxs)(r.Fragment,{children:[f.length>0&&(0,r.jsx)(z.zz,{}),(0,r.jsx)(z.fu,{heading:(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)(q.Z,{className:"h-3.5 w-3.5 text-amber-500"}),s("twelveMonthGoals")]}),children:g.map(e=>(0,r.jsx)(X,{goal:e,selected:a.includes(e.id),onToggle:()=>v(e)},e.id))})]}),x.length>0&&(0,r.jsxs)(r.Fragment,{children:[(f.length>0||g.length>0)&&(0,r.jsx)(z.zz,{}),(0,r.jsx)(z.fu,{heading:(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)(V.Z,{className:"h-3.5 w-3.5 text-violet-500"}),s("longTermGoals")]}),children:x.map(e=>(0,r.jsx)(X,{goal:e,selected:a.includes(e.id),onToggle:()=>v(e)},e.id))})]})]}):(0,r.jsxs)("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[(0,r.jsx)(q.Z,{className:"h-8 w-8 mb-2 opacity-50"}),t?(0,r.jsx)("span",{className:"text-sm",children:s("noResultsForQuery",{query:t})}):(0,r.jsx)("span",{className:"text-sm",children:s("noGoalsOrPrioritiesDefined")})]})}function Y(e){let{open:t,onOpenChange:n,onSelect:a,initialSelectedIds:s=[],className:i}=e,l=(0,u.T)("chat"),[c,d]=(0,o.useState)(""),[p,f]=(0,o.useState)(new Map),[h,g]=(0,o.useState)(s),x=(0,o.useCallback)(e=>{let t=e.data;f(n=>{let r=new Map(n);return r.has(e.id)?r.delete(e.id):r.set(e.id,t),r}),g(t=>t.includes(e.id)?t.filter(t=>t!==e.id):[...t,e.id])},[]),v=(0,o.useCallback)(()=>{a(Array.from(p.values())),n(!1),d(""),f(new Map),g([])},[p,a,n]),k=(0,o.useCallback)(()=>{n(!1),d(""),f(new Map),g([])},[n]),y=h.length;return(0,r.jsx)(Z.Vq,{open:t,onOpenChange:n,children:(0,r.jsxs)(Z.cZ,{className:(0,m.cn)("sm:max-w-[500px] p-0 gap-0 overflow-hidden",i),children:[(0,r.jsx)(Z.fK,{className:"px-4 py-3 border-b",children:(0,r.jsxs)(Z.$N,{className:"flex items-center gap-2 text-base",children:[(0,r.jsx)(q.Z,{className:"h-5 w-5 text-amber-500"}),l("selectGoalsAndPriorities")]})}),(0,r.jsxs)(z.mY,{className:"border-none",children:[(0,r.jsx)("div",{className:"px-4 py-2 border-b",children:(0,r.jsx)(z.sZ,{placeholder:l("searchGoalsOrPriorities"),value:c,onValueChange:d,className:"h-9"})}),(0,r.jsx)("div",{className:"min-h-[300px] max-h-[400px]",children:(0,r.jsx)(Q,{query:c,onSelect:x,onToggle:x,selectedIds:h,multiSelect:!0,expanded:!0})})]}),(0,r.jsx)(Z.cN,{className:"px-4 py-3 border-t bg-muted/30",children:(0,r.jsxs)("div",{className:"flex items-center justify-between w-full",children:[(0,r.jsx)("span",{className:"text-sm text-muted-foreground",children:y>0?l("selectedCount",{count:y}):l("selectGoalsForContext")}),(0,r.jsxs)("div",{className:"flex gap-2",children:[(0,r.jsx)(A.z,{variant:"outline",size:"sm",onClick:k,children:l("cancel")}),(0,r.jsxs)(A.z,{size:"sm",onClick:v,disabled:0===y,children:[l("add"),y>0?" (".concat(y,")"):""]})]})]})})]})})}var $=n(63769),ee=n(82041),et=n(36673),en=n(21673),er=n(95731),ea=n(90324),es=n(72829),ei=n(97236),el=n(17051),eo=n(22113),ec=n(75330),ed=n(62441),eu=n(34078),em=n(81066),ep=n(61883),ef=n(61990),eh=n(24875);let eg={category:I.Z,prompt:et.Z,skill:en.Z,research:er.Z,file:ea.Z,pack:es.Z,goal:q.Z,priority:G.Z,task:ei.Z,tool:el.Z,semantic:eo.Z},ex={category:"text-muted-foreground bg-muted",prompt:"text-blue-500 bg-blue-500/10",skill:"text-amber-500 bg-amber-500/10",research:"text-violet-500 bg-violet-500/10",file:"text-muted-foreground bg-muted",pack:"text-primary bg-primary/10",goal:"text-amber-500 bg-amber-500/10",priority:"text-teal-500 bg-teal-500/10",task:"text-sky-500 bg-sky-500/10",tool:"text-orange-500 bg-orange-500/10",semantic:"text-emerald-500 bg-emerald-500/10"},ev={category:"slashTypeCategory",prompt:"slashTypePrompt",skill:"slashTypeSkill",research:"slashTypeResearch",file:"slashTypeFile",pack:"slashTypePack",goal:"slashTypeGoal",priority:"slashTypePriority",task:"slashTypeTask",tool:"slashTypeTool",semantic:"slashTypeSemantic"},ek={user:ec.Z,organization:ed.Z,system:eu.Z},ey={user:"slashScopeUserFull",organization:"slashScopeOrganizationFull",system:"slashScopeSystemFull"};function ew(e){let{isOpen:t,onClose:n,initialQuery:a,onUseCommand:s}=e,i=(0,u.T)("chat"),[c,d]=(0,o.useState)(""),[m,p]=(0,o.useState)([]),[f,h]=(0,o.useState)(!1),[g,x]=(0,o.useState)(null),v=(0,o.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";h(!0);try{let n=new URLSearchParams({q:e,limit:"50"}),r=await fetch("/api/slash-commands/search?".concat(n));if(r.ok){var t;let n=await r.json();p(n.results||[]),e&&(null===(t=n.results)||void 0===t?void 0:t.length)===1&&x(n.results[0])}}catch(e){l.kg.error("Failed to fetch commands:",e),p([])}finally{h(!1)}},[]);(0,o.useEffect)(()=>{t&&(d(a||""),x(null),v(a||""))},[t,a,v]),(0,o.useEffect)(()=>
1{if(t&&!g){let e=setTimeout(()=>{v(c)},200);return()=>clearTimeout(e)}},[c,t,g,v]);let k=e=>{null==s||s(e),n()};return(0,r.jsx)(Z.Vq,{open:t,onOpenChange:e=>!e&&n(),children:(0,r.jsxs)(Z.cZ,{className:"sm:max-w-[600px] max-h-[80vh] flex flex-col",children:[(0,r.jsxs)(Z.fK,{children:[(0,r.jsxs)(Z.$N,{className:"flex items-center gap-2",children:[(0,r.jsx)(em.Z,{className:"w-5 h-5 text-primary"}),g?(0,r.jsx)("span",{children:i("slashCommandTitle",{command:g.shortcut||g.name})}):(0,r.jsx)("span",{children:i("slashCommandsTitle")})]}),(0,r.jsx)(Z.Be,{children:i(g?"slashCommandDetailsDescription":"slashCommandListDescription")})]}),(0,r.jsx)("div",{className:"flex-1 overflow-hidden flex flex-col",children:g?(0,r.jsx)(eb,{command:g,onBack:()=>{x(null)},onUse:()=>k(g)}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"mb-4",children:(0,r.jsx)($.I,{placeholder:i("searchCommands"),value:c,onChange:e=>d(e.target.value),className:"w-full",autoFocus:!0})}),(0,r.jsx)("div",{className:"flex-1 overflow-y-auto -mx-6 px-6",children:f?(0,r.jsxs)("div",{className:"flex items-center justify-center py-8 text-muted-foreground",children:[(0,r.jsx)(H.Gl,{size:"md"}),i("loading")]}):0===m.length?(0,r.jsx)("div",{className:"text-center py-8 text-muted-foreground",children:c?i("slashNoCommandsFound",{query:c}):i("slashNoCommandsAvailable")}):(0,r.jsx)("div",{className:"space-y-1",children:m.map(e=>(0,r.jsx)(ej,{command:e,onClick:()=>x(e)},"".concat(e.type,"-").concat(e.id)))})}),(0,r.jsxs)("div",{className:"mt-4 pt-4 border-t text-xs text-muted-foreground text-center",children:[i("slashTipBefore")," ",(0,r.jsx)("code",{className:"px-1 py-0.5 bg-muted rounded",children:i("slashCommandExample")})," ",i("slashTipAfter")]})]})})]})})}function ej(e){let{command:t,onClick:n}=e,a=(0,u.T)("chat"),s=eg[t.type],i=ek[t.scope];return(0,r.jsxs)("button",{onClick:n,className:(0,m.cn)("w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left","transition-colors hover:bg-muted/50"),children:[(0,r.jsx)("div",{className:(0,m.cn)("p-2 rounded-lg",ex[t.type]),children:(0,r.jsx)(s,{className:"w-4 h-4"})}),(0,r.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsxs)("span",{className:"font-mono text-sm font-medium",children:["/",t.shortcut||t.name]}),(0,r.jsx)(ee.C,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:a(ev[t.type])})]}),t.description&&(0,r.jsx)("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:t.description})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1 text-muted-foreground/60",children:[(0,r.jsx)(i,{className:"w-3.5 h-3.5"}),(0,r.jsx)("span",{className:"text-[10px]",children:a(ey[t.scope])})]})]})}function eb(e){let{command:t,onBack:n,onUse:a}=e,s=(0,u.T)("chat"),i=eg[t.type],l=ek[t.scope];return(0,r.jsxs)("div",{className:"space-y-6",children:[(0,r.jsxs)("button",{onClick:n,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[(0,r.jsx)(ep.Z,{className:"w-4 h-4"}),s("slashBackToList")]}),(0,r.jsxs)("div",{className:"flex items-start gap-4",children:[(0,r.jsx)("div",{className:(0,m.cn)("p-3 rounded-xl",ex[t.type]),children:(0,r.jsx)(i,{className:"w-6 h-6"})}),(0,r.jsxs)("div",{className:"flex-1",children:[(0,r.jsxs)("h3",{className:"text-lg font-semibold font-mono",children:["/",t.shortcut||t.name]}),(0,r.jsxs)("div",{className:"flex items-center gap-2 mt-1",children:[(0,r.jsx)(ee.C,{variant:"secondary",children:s(ev[t.type])}),(0,r.jsxs)("div",{className:"flex items-center gap-1 text-muted-foreground",children:[(0,r.jsx)(l,{className:"w-3.5 h-3.5"}),(0,r.jsx)("span",{className:"text-xs",children:s(ey[t.scope])})]})]})]})]}),(0,r.jsxs)("div",{className:"space-y-4",children:[t.shortcut&&t.shortcut!==t.name&&(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:s("slashNameLabel")}),(0,r.jsx)("p",{className:"mt-1",children:t.name})]}),t.description&&(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:s("slashDescriptionLabel")}),(0,r.jsx)("p",{className:"mt-1 text-muted-foreground",children:t.description})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:s("slashTypeLabel")}),(0,r.jsxs)("p",{className:"mt-1 text-muted-foreground",children:["prompt"===t.type&&s("slashTypeExplanationPrompt"),"skill"===t.type&&s("slashTypeExplanationSkill"),"research"===t.type&&s("slashTypeExplanationResearch"),"file"===t.type&&s("slashTypeExplanationFile"),"pack"===t.type&&s("slashTypeExplanationPack")]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:s("slashAvailabilityLabel")}),(0,r.jsxs)("p",{className:"mt-1 text-muted-foreground",children:["user"===t.scope&&s("slashScopeExplanationUser"),"organization"===t.scope&&s("slashScopeExplanationOrganization"),"system"===t.scope&&s("slashScopeExplanationSystem")]})]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-3 pt-4 border-t",children:[(0,r.jsxs)(A.z,{onClick:a,className:"flex-1",children:[(0,r.jsx)(ef.Z,{className:"w-4 h-4 mr-2"}),s("slashUseCommand")]}),(0,r.jsx)(A.z,{variant:"outline",asChild:!0,children:(0,r.jsxs)("a",{href:"/tools/shortcuts",className:"flex items-center gap-2",children:[(0,r.jsx)(eh.Z,{className:"w-4 h-4"}),s("slashViewInManager")]})})]})]})}var eN=n(58410),eC=n(10269),eS=n(25555),eT=n(90743),eI=n(70548),eE=n(12198),e_=n(43584);let eA={recent:{label:"recent",labelKey:"commandCategoryRecent",icon:eS.Z,color:"gray",multiSelect:!1,priority:100},files:{label:"files",labelKey:"commandCategoryFiles",icon:et.Z,color:"blue",multiSelect:!0,priority:90},goals:{label:"goals",labelKey:"commandCategoryGoals",icon:q.Z,color:"teal",multiSelect:!0,priority:85},skills:{label:"skills",labelKey:"commandCategorySkills",icon:eT.Z,color:"yellow",multiSelect:!1,priority:80},prompts:{label:"prompts",labelKey:"commandCategoryPrompts",icon:eI.Z,color:"purple",multiSelect:!1,priority:70},packs:{label:"packs",labelKey:"commandCategoryPacks",icon:es.Z,color:"orange",multiSelect:!0,priority:60},workflows:{label:"workflows",labelKey:"commandCategoryWorkflows",icon:ef.Z,color:"green",multiSelect:!1,priority:50},actions:{label:"actions",labelKey:"commandCategoryActions",icon:eE.Z,color:"gray",multiSelect:!1,priority:40},navigation:{label:"navigation",labelKey:"commandCategoryNavigation",icon:e_.Z,color:"indigo",multiSelect:!1,priority:30},settings:{label:"settings",labelKey:"commandCategorySettings",icon:eE.Z,color:"slate",multiSelect:!1,priority:20}};function eR(e){let{value:t,onChange:n,placeholder:a,activeCategory:s,onBack:i,onSpaceToggle:l,autoFocus:c=!0,className:d}=e,p=(0,u.T)("chat"),f=(0,o.useRef)(null);(0,o.useEffect)(()=>
1{if(c){let e=setTimeout(()=>{var e;null===(e=f.current)||void 0===e||e.focus()},50);return()=>clearTimeout(e)}},[c]);let h=(0,o.useCallback)(e=>{if("Backspace"===e.key&&!t&&s&&i){e.preventDefault(),i();return}if(" "===e.key&&s&&l&&!t){e.preventDefault(),l();return}},[t,s,i,l]),g=s?eA[s]:null,x=(null==g?void 0:g.labelKey)?p(g.labelKey):null==g?void 0:g.label;return(0,r.jsxs)("div",{className:(0,m.cn)("relative flex items-center border-b",d),children:[s&&i&&(0,r.jsxs)("button",{type:"button",onClick:i,className:(0,m.cn)("flex items-center gap-1 px-3 py-2","text-sm text-muted-foreground hover:text-foreground","transition-colors"),children:[(0,r.jsx)(eN.Z,{className:"h-4 w-4"}),x&&(0,r.jsx)("span",{className:"font-medium",children:x})]}),(0,r.jsx)(z.sZ,{ref:f,value:t,onValueChange:n,onKeyDown:h,placeholder:s?p("searchInCategory",{category:(x||p("category")).toLowerCase()}):null!=a?a:p("searchCommands"),className:(0,m.cn)("flex-1",s&&"border-l")}),t&&(0,r.jsx)("button",{type:"button",onClick:()=>n(""),className:(0,m.cn)("p-2 mr-1","text-muted-foreground hover:text-foreground","transition-colors"),"aria-label":p("clearSearch"),children:(0,r.jsx)(eC.Z,{className:"h-4 w-4"})}),!s&&!t&&(0,r.jsx)("div",{className:"hidden sm:flex items-center gap-1 pr-3 text-muted-foreground",children:(0,r.jsx)("kbd",{className:"px-1.5 py-0.5 rounded text-[10px] font-mono bg-muted/50 border border-border/50",children:"/"})})]})}var eP=n(2966);let eD={default:"bg-muted text-muted-foreground",success:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400",warning:"bg-amber-500/10 text-amber-600 dark:text-amber-400",danger:"bg-rose-500/10 text-rose-600 dar
1k:text-rose-400"};function eF(e){let{id:t,name:n,description:a,icon:s,shortcut:i,expandable:l=!1,disabled:c=!1,disabledReason:d,badge:u,badgeVariant:p="default",onSelect:f,className:h}=e,g=(0,o.useMemo)(()=>s?"function"==typeof s||"object"==typeof s&&null!==s&&"$$typeof"in s&&"render"in s?(0,r.jsx)(s,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):s:null,[s]);return(0,r.jsxs)(z.di,{value:"".concat(t,"-").concat(n),onSelect:c?void 0:f,disabled:c,className:(0,m.cn)("group flex items-center gap-3 px-3 py-2.5 rounded-lg cursor-pointer","transition-colors duration-100",c&&"opacity-50 cursor-not-allowed",h),title:c&&d?d:void 0,children:[g&&(0,r.jsx)("div",{className:"flex-shrink-0",children:g}),(0,r.jsxs)("div",{className:"flex flex-col flex-1 min-w-0",children:[(0,r.jsx)("span",{className:"text-sm font-medium truncate",children:n}),a&&(0,r.jsx)("span",{className:"text-xs text-muted-foreground truncate",children:a})]}),u&&(0,r.jsx)("span",{className:(0,m.cn)("px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0",eD[p]),children:u}),i&&!l&&(0,r.jsx)("kbd",{className:(0,m.cn)("hidden sm:inline-flex items-center justify-center","px-1.5 py-0.5 rounded text-[10px] font-mono shrink-0","bg-muted/50 border border-border/50 text-muted-foreground"),children:i}),l&&(0,r.jsx)(eP.Z,{className:"h-4 w-4 text-muted-foreground opacity-50 group-aria-selected:opacity-100"})]})}function eO(e){let{commands:t,query:n,activeCategory:a,recentItems:s=[],onCommandSelect:i,onCategoryExpand:l,className:c}=e,d=(0,u.T)("chat"),p=(0,o.useCallback)(e=>{let t=eA[e];return t.labelKey?d(t.labelKey):t.label},[d]),f=(0,o.useCallback)(e=>e.nameKey?d(e.nameKey):e.name,[d]),h=(0,o.useCallback)(e=>e.descriptionKey?d(e.descriptionKey):e.description,[d]),g=(0,o.useMemo)(()=>(function(e,t,n,r){let a=new Map,s=t.toLowerCase();for(let l of e){if(t){var i;let e=n(l),t=r(l),a=l.name.toLowerCase().includes(s)||e.toLowerCase().includes(s),o=(null===(i=l.description)||void 0===i?void 0:i.toLowerCase().includes(s))||(null==t?void 0:t.toLowerCase().includes(s)),c=l.keywords.some(e=>e.toLowerCase().includes(s));if(!a&&!o&&!c)continue}let e=a.get(l.category)||[];e.push(l),a.set(l.category,e)}for(let[,e]of a)e.sort((e,t)=>(t.priority||0)-(e.priority||0));return a})(t,n,f,h),[t,n,f,h]),x=(0,o.useMemo)(()=>Array.from(g.keys()).sort((e,t)=>{let n=eA[e];return eA[t].priority-n.priority}),[g]);if(a){let e=g.get(a)||[],t=p(a);return(0,r.jsxs)(z.e8,{className:(0,m.cn)("max-h-[400px]",c),children:[(0,r.jsx)(z.rb,{children:d("commandPaletteNoResultsInCategory",{category:t.toLowerCase()})}),(0,r.jsx)(z.fu,{heading:t,children:e.map(e=>(0,r.jsx)(eF,{id:e.id,name:f(e),description:h(e),icon:e.icon,shortcut:e.shortcut,disabled:e.disabled,disabledReason:e.disabledReason,onSelect:()=>i(e)},e.id))})]})}return(0,r.jsxs)(z.e8,{className:(0,m.cn)("max-h-[400px]",c),children:[(0,r.jsx)(z.rb,{children:d("commandPaletteNoCommandsFound",{query:n})}),!n&&s.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(z.fu,{heading:d("commandCategoryRecent"),children:s.slice(0,5).map(e=>(0,r.jsx)(eF,{id:e.id,name:e.name,description:e.description,icon:e.icon,onSelect:()=>{let n=t.find(t=>t.id===e.id);n&&i(n)}},e.id))}),x.length>0&&(0,r.jsx)(z.zz,{})]}),x.map(e=>{let t=g.get(e)||[],n=p(e),a=["files","goals","skills","prompts","packs"].includes(e);if("actions"===e)return(0,r.jsx)(z.fu,{heading:n,children:t.map(e=>(0,r.jsx)(eF,{id:e.id,name:f(e),description:h(e),icon:e.icon,shortcut:e.shortcut,disabled:e.disabled,disabledReason:e.disabledReason,onSelect:()=>i(e)},e.id))},e);if(a){let n=t[0];return n?(0,r.jsx)(z.fu,{children:(0,r.jsx)(eF,{id:n.id,name:f(n),description:h(n),icon:n.icon,shortcut:n.shortcut,expandable:!0,onSelect:()=>l(e)},n.id)},e):null}return(0,r.jsx)(z.fu,{heading:n,children:t.map(e=>(0,r.jsx)(eF,{id:e.id,name:f(e),description:h(e),icon:e.icon,shortcut:e.shortcut,disabled:e.disabled,disabledReason:e.disabledReason,onSelect:()=>i(e)},e.id))},e)})]})}class eU{register(e){this.commands.set(e.id,e),this.notifyListeners()}unregister(e){this.commands.delete(e),this.notifyListeners()}getAll(){return Array.from(this.commands.values()).sort((e,t)=>
1{var n,r;return(null!==(n=t.priority)&&void 0!==n?n:0)-(null!==(r=e.priority)&&void 0!==r?r:0)})}getByCategory(e){return this.getAll().filter(t=>t.category===e)}search(e){if(!e.trim())return this.getAll();let t=e.toLowerCase().trim();return this.getAll().filter(e=>{var n;return e.name.toLowerCase().includes(t)||(null===(n=e.description)||void 0===n?void 0:n.toLowerCase().includes(t))||e.keywords.some(e=>e.toLowerCase().includes(t))})}get(e){return this.commands.get(e)}has(e){return this.commands.has(e)}get size(){return this.commands.size}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){this.listeners.forEach(e=>e())}clear(){this.commands.clear(),this.notifyListeners()}constructor(){this.commands=new Map,this.listeners=new Set}}let eL=new eU;var eM=n(3172),eZ=n(10997);let ez={id:"files",name:"Filer",nameKey:"commandFiles",description:"Legg til filer som kontekst",descriptionKey:"commandFilesDescription",category:"files",icon:et.Z,keywords:["fil","file","dokument","pdf","library","vedlegg","attach"],shortcut:"⌘F",priority:100},eK={id:"goals",name:"M\xe5l & Prioriteter",nameKey:"commandGoals",description:"Legg til strategiske m\xe5l som kontekst",descriptionKey:"commandGoalsDescription",category:"goals",icon:q.Z,keywords:["m\xe5l","goal","prioritet","priority","strategi","kpi","target"],shortcut:"⌘G",priority:90},eW={id:"skills",name:"Skills",nameKey:"commandSkills",description:"Aktiver en AI-skill",descriptionKey:"commandSkillsDescription",category:"skills",icon:eT.Z,keywords:["skill","evne","spesialist","ekspert","ability"],shortcut:"⌘S",priority:80},eq={id:"prompts",name:"Prompts",nameKey:"commandPrompts",description:"Bruk en prompt fra biblioteket",descriptionKey:"commandPromptsDescription",category:"prompts",icon:eI.Z,keywords:["prompt","mal","template","instruksjon"],priority:70},eG=[ez,eK,eW,eq,{id:"packs",name:"Context Packs",nameKey:"commandContextPacks",description:"Legg til en kontekstpakke",descriptionKey:"commandContextPacksDescription",category:"packs",icon:es.Z,keywords:["pack","pakke","context","kontekst","bundle"],priority:60},{id:"new-conversation",name:"Ny samtale",nameKey:"commandNewConversation",description:"Start en ny samtale",descriptionKey:"commandNewConversationDescription",category:"actions",icon:eM.Z,keywords:["ny","new","start","samtale","conversation","fresh"],priority:50},{id:"clear-context",name:"T\xf8m kontekst",nameKey:"commandClearContext",description:"Fjern alle vedlagte filer og m\xe5l",descriptionKey:"commandClearContextDescription",category:"actions",icon:eZ.Z,keywords:["t\xf8m","clear","fjern","reset","remove","slett"],priority:40}];function eV(e){let{open:t,onOpenChange:n,query:a,onQueryChange:s,activeCategory:i,onCategoryChange:l,recentItems:c=[],onCommandExecute:d,onOpenPicker:p,onAction:f,className:h}=e,g=(0,u.T)("chat"),x=(0,o.useRef)(!1);(0,o.useEffect)(()=>{x.current||(!function(){for(let e of eG)eL.register(e)}(),x.current=!0)},[]);let v=(0,o.useMemo)(()=>eL.getAll(),[t]),k=(0,o.useCallback)(e=>{if(e.onSelect){e.onSelect(),n(!1);return}if("actions"!==e.category&&p){p(e.category),n(!1);return}if("actions"===e.category&&f){f(e.id),n(!1);return}d&&d(e),n(!1)},[n,p,f,d]),y=(0,o.useCallback)(e=>{p?(p(e),n(!1)):l&&l(e)},[l,p,n]),w=(0,o.useCallback)(()=>{l&&l(null),s("")},[l,s]);return(0,r.jsx)(Z.Vq,{open:t,onOpenChange:n,children:(0,r.jsx)(Z.cZ,{className:(0,m.cn)("p-0","sm:max-w-[600px] max-h-[80vh]","border-0","bg-gradient-to-b from-background to-background/95","shadow-2xl shadow-black/20 dark:shadow-black/40","rounded-xl overflow-hidden","backdrop-blur-xl",h),children:(0,r.jsxs)(z.mY,{shouldFilter:!1,className:(0,m.cn)("flex flex-col","bg-transparent","[&_[cmdk-group-heading]]:px-3 [&_[cmdk-group-heading]]:py-2","[&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-semibold","[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:uppercase","[&_[cmdk-group-heading]]:tracking-wider","[&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0"),loop:!0,children:[(0,r.jsx)(eR,{value:a,onChange:s,activeCategory:i,onBack:i?w:void 0,placeholder:g("whatDoYouWantToDo")}),(0,r.jsx)(eO,{commands:v,query:a,activeCategory:i,recentItems:c,onCommandSelect:k,onCategoryExpand:y}),(0,r.jsxs)("div",{className:(0,m.cn)("flex items-center justify-between","px-3 py-2 border-t","text-[10px] text-muted-foreground"),children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsx)("kbd",{className:"px-1 py-0.5 rounded bg-muted/50 border border-border/50",children:"↑↓"}),g("commandPaletteNavigate")]}),(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsx)("kbd",{className:"px-1 py-0.5 rounded bg-muted/50 border border-border/50",children:"↵"}),g("commandPaletteSelect")]}),(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsx)("kbd",{className:"px-1 py-0.5 rounded bg-muted/50 border border-border/50",children:"esc"}),g("commandPaletteClose")]})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)("span",{className:"opacity-60",children:g("commandPaletteAiChat")}),(0,r.jsx)("span",{children:"•"}),(0,r.jsx)("span",{className:"opacity-60",children:g("commandPaletteTitle")})]})]})]})})})}function eH(e){let{showContextPicker:t,onShowContextPickerChange:n,contextFiles:a,onContextFilesC
1hange:s,onContextFilesAdded:i,selectedPacks:l,onSelectedPacksChange:o}=e;return(0,r.jsx)(U.ContextFilePicker,{open:t,onOpenChange:n,onSelect:e=>{let t=new Set(a.map(e=>e.id)),n=e.filter(e=>!t.has(e.id));n.length>0&&(s(e=>[...e,...n]),null==i||i(n.map(e=>({id:e.id,name:e.name,source:e.source}))))},onSelectPacks:e=>{o(t=>{let n=new Set(t.map(e=>e.id));return[...t,...e.filter(e=>!n.has(e.id))]})},selectedIds:a.map(e=>e.id),selectedPackIds:l.map(e=>e.id),showContextPacks:!0})}function eJ(e){let{commandPalette:t,onShowContextPickerChange:n,onShowGoalsPickerChange:a,onShowSkillPickerChange:s,onShowPromptPickerChange:i,onContextFilesChange:l,onSelectedPacksChange:o,onSelectedSkillsChange:c,onNewConversation:d}=e;return(0,r.jsx)(eV,{open:t.isOpen,onOpenChange:e=>e?t.open():t.close(),query:t.query,onQueryChange:t.setQuery,activeCategory:t.activeCategory,onCategoryChange:t.setActiveCategory,recentItems:t.recentItems,onOpenPicker:e=>{switch(e){case"files":case"packs":n(!0);break;case"goals":a(!0);break;case"skills":s(!0);break;case"prompts":i(!0)}},onAction:e=>{switch(e){case"new-conversation":d();break;case"clear-context":l([]),o([]),c([])}}})}function eB(e){let{showContextPicker:t,onShowContextPickerChange:n,contextFiles:a,onContextFilesChange:s,onContextFilesAdded:i,selectedPacks:l,onSelectedPacksChange:o,showPromptPicker:c,onShowPromptPickerChange:d,onInputChange:u,showSkillPicker:m,onShowSkillPickerChange:p,onSelectedSkillsChange:f,showGoalsPicker:h,onShowGoalsPickerChange:g,pinnedGoals:x,onPinnedGoalsChange:v,showSlashHelp:k,onShowSlashHelpChange:y,slashHelpQuery:w,onSlashHelpQueryChange:j,commandPalette:b,onNewConversation:N}=e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(eH,{showContextPicker:t,onShowContextPickerChange:n,contextFiles:a,onContextFilesChange:s,onContextFilesAdded:i,selectedPacks:l,onSelectedPacksChange:o}),(0,r.jsx)(L.PromptPicker,{open:c,onOpenChange:d,onSelect:e=>{u(t=>t.trim()?t+"\n\n"+e.content:e.content)}}),(0,r.jsx)(M.d,{open:m,onOpenChange:p,onSelect:e=>{f(t=>t.some(t=>t.id===e.id)?t:[...t,e])}}),(0,r.jsx)(Y,{open:h,onOpenChange:g,initialSelectedIds:x.map(e=>e.id),onSelect:e=>{v(e)}}),(0,r.jsx)(ew,{isOpen:k,onClose:()=>{y(!1),j(void 0)},initialQuery:w,onUseCommand:e=>{y(!1),j(void 0)}}),(0,r.jsx)(eJ,{commandPalette:b,onShowContextPickerChange:n,onShowGoalsPickerChange:g,onShowSkillPickerChange:p,onShowPromptPickerChange:d,onContextFilesChange:s,onSelectedPacksChange:o,onSelectedSkillsChange:f,onNewConversation:N})]})}var eX=n(23664);function eQ(e){let{previewMode:t,hasPendingPatches:n,onDocumentEdit:a,effectiveMode:s,pendingPatches:i,activePatchIndex:l,onNavigateToPatch:o,onApplyPatch:c,onRejectPatch:d,onApplyAll:u,onRejectAll:p,onScrollToSection:f,canUndo:h,undoTimeRemaining:g,onUndo:x,t:v}=e;return(0,r.jsxs)(r.Fragment,{children:[t&&n&&a&&(0,r.jsxs)("div",{className:(0,m.cn)("max-w-3xl mx-auto w-full","wide"===s?"px-4 py-2":"px-2 py-1"),children:[i.length>1&&(0,r.jsx)(eX.tN,{patches:i,activePatchIndex:l,onPatchClick:o,onApproveAll:u,onRejectAll:p,onScrollToSection:f,className:"mb-3"}),(0,r.jsx)(eX.eU,{patches:i,activePatchIndex:l,onApply:c,onReject:d,onApproveAll:u,onRejectAll:p,onNavigate:o})]}),h&&g&&(0,r.jsx)("div",{className:(0,m.cn)("max-w-3xl mx-auto w-full","wide"===s?"px-4 py-1":"px-2 py-1"),children:(0,r.jsx)(eX.h6,{onUndo:x,timeoutSeconds:g,label:v("undoChange")})})]})}var eY=n(3374),e$=n(2820);function e0(e){if(!e)return null;let t=Date.parse(e);return Number.isFinite(t)?t:null}let e1={proff_scraper:"Proff.no",brreg_api:"Br\xf8nn\xf8ysund",parallel_search:"researchToolWebSearch",smart_crawler:"researchToolWebsiteCrawler",website_crawler:"researchToolWebsiteCrawler",jina_reader:"researchToolPageReader",linkedin_browser:"LinkedIn",apify_linkedin:"LinkedIn"};function e3(e){var t;let{plan:n,onApprove:a,onEdit:s,isLoading:i=!1,className:l}=e,o=(0,u.T)("chat");return(0,r.jsxs)("div",{className:(0,m.cn)("border rounded-lg p-4 bg-muted/30 space-y-4",l),children:[(0,r.jsxs)("div",{className:"flex items-center justify-between",children:[(0,r.jsx)("h3",{className:"font-semibold text-sm",children:o("researchPlan")}),(0,r.jsx)("span",{className:"text-xs text-muted-foreground px-2 py-0.5 bg-background rounded",children:o("researchPlanStatus".concat(null===(t=n.status[0])||void 0===t?void 0:t.toUpperCase()).concat(n.status.slice(1)))})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-sm font-medium mb-1",children:o("goal")}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:n.goal})]}),(0,r.jsxs)("div",{className:"bg-background/50 border rounded p-3",children:[(0,r.jsx)("p",{className:"text-sm font-medium mb-1",children:o("myStrategy")}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:n.strategy})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-sm font-medium mb-2",children:o("steps")}),(0,r.jsx)("div",{className:"space-y-2",children:n.steps.map((e,t)=>(0,r.jsxs)("div",{className:"flex items-start gap-2 text-sm",children:[(0,r.jsx)("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-primary/10 text-primary text-xs flex items-center justify-center",children:t+1}),(0,r.jsxs)("div",{className:"flex-1",children:[(0,r.jsx)("p",{className:"text-muted-foreground",children:e.description}),e.tools.length>0&&(0,r.jsx)("p",{className:"mt-1 text-xs text-muted-foreground",children:e.tools.map(e=>(function(e,t){let n=e1[e];return n?n.startsWith("researchTool")?t(n):n:e})(e,o)).join(" \xb7 ")}),e.targets.length>0&&(0,r.jsx)("div",{className:"mt-1 flex flex-wrap gap-1",children:e.targets.map((e,t)=>(0,r.jsx)("span",{className:"text-xs px-1.5 py-0.5 bg-muted rounded",title:e.reason,children:e.identifier},t))})]})]},t))})]}),n.exclusions.length>0&&(0,r.jsxs)("div",{className:"border-l-2 border-border pl-3",children:[(0,r.jsx)("p",{className:"mb-1 text-sm font-medium text-foreground",children:o("willNotDo")}),(0,r.jsx)("ul",{className:"text-sm text-muted-foreground space-y-0.5",children:n.exclusions.map((e,t)=>(0,r.jsxs)("li",{className:"flex items-start gap-1.5",children:[(0,r.jsx)("span",{className:"mt-1 text-muted-foreground",children:"-"}),(0,r.jsx)("span",{children:e})]},t))})]}),(0,r.jsxs)("div",{className:"flex items-center gap-4 text-xs text-muted-foreground pt-2 border-t",children:[(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)(e2,{className:"w-3.5 h-3.5"}),(0,r.jsx)("span",{children:o("estimatedMinutesShort",{count:n.estimates.timeMinutes})})]}),(0,r.jsxs)("div",{className:"flex items-center gap-1",children:[(0,r.jsx)(e5,{className:"w-3.5 h-3.5"}),(0,r.jsx)("span",{children:o("estimatedCostUnits",{count:n.estimates.costUnits})})]})]}),"draft"===n.status&&(0,r.jsxs)("div",{className:"flex gap-2 pt-2",children:[(0,r.jsx)(A.z,{onClick:()=>
1a(n.id),disabled:i,size:"sm",className:"flex-1",children:i?o("starting"):o("approveResearchPlan")}),(0,r.jsx)(A.z,{onClick:s,disabled:i,variant:"outline",size:"sm",children:o("adjustResearchPlan")})]})]})}function e2(e){let{className:t}=e;return(0,r.jsxs)("svg",{className:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("polyline",{points:"12 6 12 12 16 14"})]})}function e5(e){let{className:t}=e;return(0,r.jsx)("svg",{className:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"})})}var e4=n(52872),e7=n(3470),e6=n(83071),e8=n(49743),e9=n(32917),te=n(16843);function tt(e){let{references:t,onOpen:n}=e,a=(0,u.T)("chat"),[s,i]=(0,o.useState)(()=>t.length>0?{status:"loading",resources:[]}:{status:"success",resources:[]}),[l,c]=(0,o.useState)(0),d=(0,o.useRef)(0),m=(0,o.useMemo)(()=>JSON.stringify(t),[t]);return((0,o.useEffect)(()=>{let e=++d.current;if(0===t.length){i({status:"success",resources:[]});return}let n=new AbortController;return i({status:"loading",resources:[]}),async function(){try{let r=await fetch("/api/ai/resources/resolve",{method:"POST",headers:{"Content-Type":"application/json",...(0,p.p)()},body:JSON.stringify({references:t}),signal:n.signal});if(!r.ok)throw Error("resolve failed");let a=await r.json();if(!Array.isArray(a.resources))throw Error("invalid resolve response");if(n.signal.aborted||d.current!==e)return;i({status:"success",resources:a.resources})}catch(t){if(n.signal.aborted||d.current!==e)return;i({status:"error",resources:[]})}}(),()=>{n.abort(),d.current===e&&(d.current+=1)}},[m,l]),"loading"===s.status)?(0,r.jsxs)("div",{role:"status",className:"flex items-center gap-2 rounded-lg border border-border/60 bg-card p-3 text-sm text-muted-foreground shadow-sm",children:[(0,r.jsx)(H.Gl,{size:"md",className:"shrink-0"}),a("resourceCardLoading")]}):"error"===s.status?(0,r.jsxs)("div",{role:"alert",className:"flex items-center justify-between gap-3 rounded-lg border border-border/60 bg-card p-3 shadow-sm",children:[(0,r.jsx)("p",{className:"text-sm text-foreground",children:a("resourceCardError")}),(0,r.jsxs)(A.z,{type:"button",size:"sm",variant:"outline",onClick:()=>c(e=>e+1),children:[a("resourceCardRetry"),(0,r.jsx)(_.Z,{className:"ml-1.5 h-3.5 w-3.5","aria-hidden":"true"})]})]}):0===s.resources.length?null:(0,r.jsx)("div",{className:"space-y-2","data-testid":"agent-resource-result-cards",children:s.resources.map(e=>{var t,s;let i="task"===(s=e.kind)?e7.Z:"board"===s?e6.Z:"presentation"===s?e8.Z:"dialogue"===s?e9.Z:et.Z;return(0,r.jsx)("div",{className:"rounded-lg border border-border/60 bg-card p-3 shadow-sm",children:(0,r.jsxs)("div",{className:"flex items-start gap-3",children:[(0,r.jsx)("div",{className:"rounded-md border border-border/50 bg-muted/40 p-2",children:(0,r.jsx)(i,{className:"h-4 w-4 text-foreground","aria-hidden":"true"})}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("p",{className:"truncate text-sm font-medium text-foreground",children:e.name}),e.workspaceName&&(0,r.jsxs)("dl",{className:"mt-1 grid gap-0.5 text-xs text-muted-foreground",children:[(0,r.jsxs)("div",{className:"flex min-w-0 gap-1",children:[(0,r.jsxs)("dt",{children:[a("resourceCardWorkspace"),":"]}),(0,r.jsx)("dd",{className:"truncate",children:e.workspaceName})]}),(0,r.jsxs)("div",{className:"flex min-w-0 gap-1",children:[(0,r.jsxs)("dt",{children:[a("resourceCardLocation"),":"]}),(0,r.jsx)("dd",{className:"truncate",children:null!==(t=e.locationName)&&void 0!==t?t:a("resourceCardWorkspaceRoot")})]})]})]}),(0,r.jsxs)(A.z,{size:"sm",variant:"outline",onClick:()=>{if(n){n(e);return}window.location.assign(e.href)},children:[a("resourceCardOpen"),(0,r.jsx)(te.Z,{className:"ml-1.5 h-3.5 w-3.5","aria-hidden":"true"})]})]})},"".concat(e.kind,":").concat(e.id))})})}function tn(e){let{content:t,onApprove:n,onAdjust:a}=e,s=(0,e4.P0)(t);return 0===s.length?null:(0,r.jsx)("div",{className:"space-y-2","data-testid":"research-plan-result-cards",children:s.map(e=>(0,r.jsx)(e3,{plan:e,onApprove:n,onEdit:a},e.id))})}
1function tr(e){let{conversationId:t,historyStatus:n,hasMessages:a,discoveryPending:s=!1,loadingFallback:i,children:l}=e;return void 0!==i&&!a&&(s||null!==t&&"loaded"!==n)?(0,r.jsx)("div",{className:"flex min-h-0 flex-1 items-center justify-center","aria-busy":"true",children:i}):l}var ta=n(1836),ts=n(76251),ti=n(74737),tl=n(88623),to=n(79901),tc=n(92472),td=n(53512),tu=n(75721),tm=n(72768),tp=n(83152),tf=n(77930),th=n(15969);function tg(e){let{conversationId:t,recordingSessionId:n,mode:a="wide"}=e,{data:s}=(0,tm.L)(t,{limit:3,recordingSessionId:n}),i=function(e,t){if(null!==t)return void 0===t?null==e?void 0:e[0]:null==e?void 0:e.find(e=>e.recording_session_id===t)}(null==s?void 0:s.runs,n);return i?(0,r.jsx)("div",{className:(0,m.cn)("mx-auto px-4 pt-4","wide"===a?"max-w-3xl":"max-w-full"),children:(0,r.jsx)(tx,{run:i})}):null}function tx(e){var t,n,a,s,i,l,o,c,d,p;let{run:f}=e,h=(0,u.T)("chat"),g=f.context_manifest_summary,x=(d="meeting_companion"===f.origin_type?f.recording_session_id:null,(0,tp.a)({queryKey:["meeting-hermes-events",d],enabled:!!d,queryFn:async e=>{let{signal:t}=e;if(!d)return{events:[]};let n=await fetch("/api/meetings/recording-sessions/".concat(encodeURIComponent(d),"/hermes-events"),{signal:t});if(!n.ok)throw Error("Failed to fetch Hermes meeting events");return await n.json()},staleTime:5e3,refetchInterval:e=>{var t,n;return!!(null!=(n=null===(t=e.state.data)||void 0===t?void 0:t.events)?n:[]).some(e=>["pending","pending_manual","sending","failed"].includes(e.status))&&3e3},refetchOnWindowFocus:!1,retry:1})),v=function(e){let t=(0,tf.NL)();return(0,th.D)({mutationFn:async t=>{if(!e)throw Error("Missing recording session");let n=await fetch("/api/meetings/recording-sessions/".concat(encodeURIComponent(e),"/hermes-events/").concat(encodeURIComponent(t),"/retry"),{method:"POST"});if(!n.ok)throw Error((await n.json().catch(()=>({}))).error||"Failed to retry Hermes meeting event");return await n.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["meeting-hermes-events",e]}),t.invalidateQueries({queryKey:["external-agent-runs"]})}})}("meeting_companion"===f.origin_type?f.recording_session_id:null),k=function(e){switch(e){case"completed":return{labelKey:"externalAgentRunStatusCompleted",icon:to.Z,spin:!1};case"cancelled":return{labelKey:"externalAgentRunStatusCancelled",icon:tc.Z,spin:!1};case"error":return{labelKey:"externalAgentRunStatusError",icon:td.Z,spin:!1};case"streaming":case"dispatched":case"queued":return{labelKey:"externalAgentRunStatusRunning",icon:tu.Z,spin:!0}}}(f.status),y=k.icon,w=null!==(s=null==g?void 0:g.request.context_profile)&&void 0!==s?s:f.context_profile,j=null!==(i=null==g?void 0:g.request.budget_profile)&&void 0!==i?i:f.budget_profile,b=null==g?void 0:g.request.model,N=null==g?void 0:g.prompt_layers.history_message_count,C=null==g?void 0:g.context_files_count,S=null!==(l=null==g?void 0:g.mcp.run_credential_attached)&&void 0!==l?l:f.mcp_credential_attached,T=null!==(o=null==g?void 0:g.mcp.unavailable_reason)&&void 0!==o?o:f.mcp_unavailable_reason,I=null!==(c=null==g?void 0:g.mcp.scopes.length)&&void 0!==c?c:0,E="praksis_native"===(p={runtime:f.runtime,credentialAttached:S,unavailableReason:T}).runtime?null:p.credentialAttached?"externalAgentRunMcpAttached":"mcp_url_missing"===p.unavailableReason?"externalAgentRunMcpUrlMissing":"run_credential_missing"===p.unavailableReason?"externalAgentRunMcpCredentialMissing":"mcp_url_and_run_credential_missing"===p.unavailableReason?"externalAgentRunMcpUrlAndCredentialMissing":"externalAgentRunMcpNotAttached",_=h("meeting_companion"===f.origin_type?"externalAgentRunMeetingCompanion":"elevenlabs"===f.runtime?"externalAgentRunPraksisVoice":"externalAgentRunHermes");return(0,r.jsxs)("div",{className:"rounded-md border border-border/50 bg-muted/20 px-3 py-2 text-xs text-muted-foreground",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5 font-medium text-foreground",children:[(0,r.jsx)(ta.Z,{className:"h-3.5 w-3.5"}),_]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)(y,{className:(0,m.cn)("h-3.5 w-3.5",k.spin&&"animate-spin")}
1),f.companion_phase?function(e,t){switch(e){case"preparing":return t("externalAgentRunPhasePreparing");case"idle":case"awaiting_split":return t("externalAgentRunPhaseAwaitingPart");case"processing":return t("externalAgentRunPhaseReadingPart");case"awaiting_manual_release":return t("externalAgentRunPhaseAwaitingApproval");case"finalizing":return t("externalAgentRunPhaseFinalizing");case"completed":return t("externalAgentRunPhaseCompleted");case"cancelled":return t("externalAgentRunPhaseStopped");case"error":case"lost_connection":return t("externalAgentRunPhaseFailed")}}(f.companion_phase,h):h(k.labelKey)]}),b&&(0,r.jsx)("span",{children:b}),w&&(0,r.jsx)("span",{children:h("externalAgentRunContext",{contextProfile:w})}),j&&(0,r.jsx)("span",{children:h("externalAgentRunBudget",{budgetProfile:j})}),"number"==typeof N&&(0,r.jsx)("span",{children:h("externalAgentRunHistoryMessages",{count:N})}),"number"==typeof C&&(0,r.jsx)("span",{children:h("externalAgentRunContextFiles",{count:C})}),E?(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)(ts.Z,{className:"h-3.5 w-3.5"}),h(E),I>0?", ".concat(h("externalAgentRunScopes",{count:I})):""]}):null,(null===(t=f.error)||void 0===t?void 0:t.code)&&(0,r.jsx)("span",{children:h("externalAgentRunNeedsAttention")})]}),"meeting_companion"===f.origin_type&&(null===(a=x.data)||void 0===a?void 0:null===(n=a.events)||void 0===n?void 0:n.length)?(0,r.jsx)(tv,{events:x.data.events,t:h,onRetry:e=>v.mutate(e),retryingEventId:v.isPending?v.variables:null}):null]})}function tv(e){let{events:t,t:n,onRetry:a,retryingEventId:s}=e;return(0,r.jsx)("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.slice(-6).map(e=>{var t,i;let l="pending_manual"===(t=e.status)?"release":"pending"===t||"failed"===t||"dead_letter"===t?"retry":null,o=s===e.id,c="release"===l?ti.Z:tl.Z;return(0,r.jsxs)("span",{className:(0,m.cn)("inline-flex max-w-full items-center gap-1 rounded-sm border px-1.5 py-0.5","accepted"===(i=e.status)||"duplicate"===i?"border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-200":"failed"===i||"dead_letter"===i?"border-destructive/30 bg-destructive/10 text-destructive":"border-border bg-background text-muted-foreground"),title:e.last_error?n("externalAgentRunNeedsAttention"):void 0,children:[(0,r.jsx)("span",{className:"truncate",children:function(e,t){if("meeting.prepared"===e.event_type)return t("externalAgentRunEventPrepared");if("meeting.completed"===e.event_type)return t("externalAgentRunEventCompleted");let n=e.summary.split_index,r=e.summary.split_title||e.split_id;return"number"==typeof n?r?t("externalAgentRunEventPartWithIndexAndTitle",{index:n,title:r}):t("externalAgentRunEventPartWithIndex",{index:n}):r?t("externalAgentRunEventPartWithTitle",{title:r}):t("externalAgentRunEventPart")}(e,n)}),(0,r.jsx)("span",{className:"shrink-0 opacity-75",children:function(e,t,n){switch(e){case"accepted":case"duplicate":return n("externalAgentRunEventStatusSent");case"sending":return n("externalAgentRunEventStatusSending");case"pending_manual":return n("externalAgentRunEventStatusManual");case"pending":return n("externalAgentRunEventStatusWaiting");case"dead_letter":return n("externalAgentRunEventStatusStopped");case"failed":return n("externalAgentRunEventStatusRetry");case"skipped":return n(t?"externalAgentRunEventStatusDeliveredToMeetingAgent":"externalAgentRunEventStatusSkipped");default:return e}}(e.status,e.parent_external_agent_run_id,n)}),l?(0,r.jsxs)("button",{type:"button",className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-sm hover:bg-background/70 disabled:cursor-not-allowed disabled:opacity-60",disabled:o,onClick:()=>a(e.id),title:"release"===l?n("externalAgentRunSendToHermes"):n("externalAgentRunTryAgain"),children:[(0,r.jsx)(c,{className:(0,m.cn)("h-3 w-3",o&&"animate-spin")}),(0,r.jsx)("span",{className:"sr-only",children:"release"===l?n("externalAgentRunSendToHermes"):n("externalAgentRunTryAgain")})]}):null]},e.id)})})}var tk=n(61325),ty=n(20565),tw=n(29681),tj=n(44526),tb=n(91741),tN=n(68914);let tC=tN.aM.filter(e=>tN.GM.includes(e)&&"handbook_run_evaluation"!==e);async function tS(e,t){let n=new URLSearchParams({conversation_id:e}),r=await fetch("/api/voice/elevenlabs-agent/conversation-token?".concat(n),{headers:(0,p.p)()});if(!r.ok)throw Error((await r.json().catch(()=>({}))).error||t.startElevenLabsConversationError);let a=await r.json();if(!a.conversationToken||"string"!=typeof a.conversationToken)throw Error(t.missingConversationTokenError);return a}
1async function tT(e,t){e&&await fetch("/api/voice/elevenlabs-agent/session/".concat(e),{method:"POST",headers:{"Content-Type":"application/json",...(0,p.p)()},body:JSON.stringify(t)}).catch(e=>{l.kg.warn("[AgentTurnTakingVoice] Failed to post voice run event:",e)})}async function tI(e,t,n,r){if(!e)return{ok:!1,error:r.noActivePraksisVoiceRun};let a=await fetch("/api/voice/elevenlabs-agent/client-tool",{method:"POST",headers:{"Content-Type":"application/json",...(0,p.p)()},body:JSON.stringify({externalAgentRunId:e,toolName:t,arguments:n})}),s=await a.json().catch(()=>null);return a.ok?s:{ok:!1,error:s&&"string"==typeof s.error?s.error:r.praksisToolFailedWithStatus(a.status)}}function tE(e){let t=JSON.stringify(e);return t.length<=18e3?t:JSON.stringify({ok:!0,truncated:!0,result:t.slice(0,18e3)})}function t_(e){var t;if(!e||"object"!=typeof e)return null;let n=[e.tool_name,e.toolName,e.name,null===(t=e.tool)||void 0===t?void 0:t.toString(),e.mcp_tool_call&&"object"==typeof e.mcp_tool_call?e.mcp_tool_call.tool_name:null].find(e=>"string"==typeof e&&e.trim());return"string"==typeof n?n:null}function tA(e){let{targetLabel:t,disabled:n=!1,compact:a=!1,className:s,onEnsureConversation:i,onVoiceMessage:c}=e,d=(0,u.T)("voice"),[p,f]=(0,o.useState)(!1),[h,g]=(0,o.useState)(!1),[x,v]=(0,o.useState)(null),[k,y]=(0,o.useState)(!1),[w,j]=(0,o.useState)(null),b=(0,o.useRef)(null),N=(0,o.useRef)(!1),C=(0,o.useRef)(!1),S=(0,o.useMemo)(()=>({agent:{firstMessage:d("agentFirstMessage"),language:"no"}}),[d]),T=(0,o.useCallback)(async(e,t)=>{let n=t&&"object"==typeof t&&!Array.isArray(t)?t:{};y(!0),j(d("praksisToolRunning",{toolName:e})),tT(b.current,{event:"tool_event",kind:"client_tool_call",toolName:e});try{let t=await tI(b.current,e,n,{noActivePraksisVoiceRun:d("noActivePraksisVoiceRun"),praksisToolFailedWithStatus:t=>d("praksisToolFailedWithStatus",{toolName:e,status:t})});return j(d("praksisToolAnswered",{toolName:e})),tE(t)}catch(n){let t=n instanceof Error?n.message:d("praksisToolFailed",{toolName:e});return j(d("praksisToolFailedStatus",{toolName:e})),tE({ok:!1,error:t})}finally{y(!1)}},[d]),I=(0,tk.sX)({overrides:S,clientTools:Object.fromEntries(tC.map(e=>[e,t=>T(e,t)])),onConnect:()=>{f(!0),v(null)},onDisconnect:()=>{C.current||(C.current=!0,tT(b.current,{event:N.current?"completed":"cancelled"})),f(!1),y(!1),b.current=null,N.current=!1,C.current=!1},onError:e=>{let t="string"==typeof e?e:d("elevenLabsConversationFailed");C.current=!0,tT(b.current,{event:"error",message:t}),v(t),f(!1),y(!1)},onMessage:e=>{if(!(null==e?void 0:e.message)||"string"!=typeof e.message)return;let t=e.message.trim();if(!t)return;y(!1);let n={role:"user"===e.source?"user":"assistant",content:t};null==c||c(n),tT(b.current,{event:"transcript",role:n.role,content:t})},onAgentToolResponse:e=>{let t=t_(e);j(t?d("mcpAnsweredTool",{toolName:t}):d("mcpAnswered")),tT(b.current,{event:"tool_event",kind:"agent_tool_response",toolName:t}),y(!1)},onMCPConnectionStatus:e=>{let t=function(e){if(!e||"object"!=typeof e)return null;let t=[e.status,e.state,e.connection_status,e.connectionStatus].find(e=>"string"==typeof e&&e.trim());return"string"==typeof t?t:null}(e);j(t?d("mcpConnectionStatus",{status:t}):d("mcpStatus")),tT(b.current,{event:"tool_event",kind:"mcp_connection_status",status:e}),l.kg.info("[AgentTurnTakingVoice] ElevenLabs MCP status:",e)},onMCPToolCall:e=>{let t=t_(e);j(t?d("mcpToolRunning",{toolName:t}):d("mcpToolRunningFallback")),tT(b.current,{event:"tool_event",kind:"mcp_tool_call",toolName:t}),y(!0)}}),E=(0,o.useCallback)(async()=>{try{var e,t,n;g(!0),v(null),await (0,tb.j)(),await navigator.mediaDevices.getUserMedia({audio:!0});let r=await i();if(!r)throw Error(d("createPraksisConversationFailed"));let a=await tS(r,{startElevenLabsConversationError:d("startElevenLabsConversationFailed"),missingConversationTokenError:d("missingConversationToken")});if((null===(e=a.mcp)||void 0===e?void 0:e.toolNames)&&!function(e){let t=new Set(tC);return e.every(e=>t.has(e))}(a.mcp.toolNames))throw Error(d("startElevenLabsConversationFailed"));b.current=a.externalAgentRunId,j((null===(n=a.mcp)||void 0===n?void 0:null===(t=n.probe)||void 0===t?void 0:t.ok)?!0===a.mcp.probe.stages.silWorkContext?d("mcpVerifiedSilWorkContext"):d("mcpVerified"):d("mcpNotVerified")),N.current=!1,C.current=!1;let s=await I.startSession({conversationToken:a.conversationToken,dynamicVariables:a.dynamicVariables,userId:a.endUserId,overrides:S});await tT(a.externalAgentRunId,{event:"started",providerConversationId:s})}catch(t){let e=t instanceof Error?t.message:d("startVoiceConversationFailed");v(e),f(!1),C.current=!0,tT(b.current,{event:"error",message:e}),b.current=null,C.current=!1}finally{g(!1)}},[I,i,S,d]),_=(0,o.useCallback)(async()=>{try{N.current=!0,await I.endSession()}finally{f(!1),y(!1)}},[I]),R=h?d("statusStarting"):k?null!=w?w:d("statusUsingTools",{targetLabel:t}):I.isSpeaking?d("statusSpeaking",{targetLabel:t}):p?d("statusListening"):d("statusVoiceConversation"),P=x||(p?null!=w?w:d("subtitleLiveAgent"):d("subtitleStartNativeVoiceAgent"));return(0,r.jsxs)("div",{className:(0,m.cn)("flex items-center justify-between gap-2 px-1.5 py-1",a?"mb-1":"mb-2",s),children:[(0,r.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[(0,r.jsx)(ty.Z,{className:(0,m.cn)("h-3.5 w-3.5 shrink-0",p?"text-foreground":"text-muted-foreground",(k||I.isSpeaking)&&"animate-pulse")}),(0,r.jsxs)("div",{className:"min-w-0",children:[(0,r.jsx)("div",{className:"truncate text-xs font-medium",children:R}),(0,r.jsx)("div",{className:(0,m.cn)("truncate text-[11px]",x?"text-destructive":"text-muted-foreground"),children:P})]})]}),p?(0,r.jsx)(A.z,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8",onClick:_,children:(0,r.jsx)(tw.Z,{className:"h-3.5 w-3.5"})}):(0,r.jsx)(A.z,{type:"button",size:"icon",variant:"outline",className:"h-8 w-8",onClick:E,disabled:n||h,"aria-label":d("startVoiceConversation"),children:h?(0,r.jsx)(H.Gl,{}):(0,r.jsx)(tj.Z,{className:"h-3.5 w-3.5"})})]})}var tR=n(43274);function tP(e){let{surface:t,...n}=e;return(0,r.jsx)("div",{className:"contents","data-testid":"universal-composer-".concat(t),children:(0,r.jsx)(tR.g,{...n})})}function tD(e){let{featureEnabled:t=!1,hasVoiceTarget:n,isDocumentMode:r}=e;return t&&n&&!r}function tF(e){let{children:t,...n}=e;return tD(n)?t:null}var tO=n(87354);function tU(e){let{suggestions:t,onApply:n}=e,a=(0,u.T)("chat");return 0===t.length?null:(0,r.jsxs)("div",{className:"rounded-lg border border-primary/20 bg-primary/5 p-3",children:[(0,r.jsx)("div",{className:"text-sm font-medium mb-2",children:a("formSuggestionsTitle")}),(0,r.jsx)("div",{className:"space-y-2",children:t.slice(0,8).map((e,t)=>(0,r.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsx)("div",{className:"text-xs text-muted-foreground",children:e.field}),(0,r.jsx)("div",{className:"text-sm break-words",children:e.value})]}),(0,r.jsxs)(A.z,{size:"sm",className:"h-7 px-2 text-xs shrink-0",onClick:()=>n(e.field,e.value),children:[(0,r.jsx)(tO.Z,{className:"h-3 w-3 mr-1"}),a("formSuggestionsApply")]})]},"".concat(e.field,"-").concat(t)))})]})}var tL=n(82626);let tM=e=>Promise.resolve().then(n.bind(n,17787)).then(t=>{let{toast:n}=t;return n.success(e)});function tZ(e){let{widget:t,onDismiss:n,currentProjectId:a,setInput:s}=e,i=()=>n(t.id);return(0,r.jsx)(tL.Kg,{projectId:a||void 0,onComplete:e=>{e.summary&&s(t=>t+(t?"\n\n":"")+"[Research: ".concat(e.topic,"]\n").concat(e.summary)),i()},onCancel:i})}function tz(e){let{widget:t,onDismiss:n,workflowContext:a,setContextFiles:s,sendToolCompleteSignal:i}=e,l=()=>n(t.id);return(0,r.jsx)(tL.cR,{workflowId:null==a?void 0:a.workflowId,instanceId:null==a?void 0:a.instanceId,onFilesUploaded:e=>{if(!a&&e&&e.length>0){let t=e.map(e=>({id:e.id,name:e.name,content:""}));s(e=>[...e,...t])}(null==a?void 0:a.refreshWorkspaceData)&&a.refreshWorkspaceData(),a&&e&&e.length>0&&i("files",{count:String(e.length),fileNames:e.map(e=>e.name).join(", ")}),l()},onCancel:l})}function tK(e){let{widget:t,onDismiss:n,workflowContext:a,setInput:s,sendToolCompleteSignal:i}=e,l=()=>n(t.id);return(0,r.jsx)(tL.kI,{workflowId:null==a?void 0:a.workflowId,instanceId:null==a?void 0:a.instanceId,existingVoiceItems:null==a?void 0:a.voiceItems,onComplete:e=>{!a&&e&&s(t=>t+(t?"\n\n":"")+e),(null==a?void 0:a.refreshWorkspaceData)&&a.refreshWorkspaceData(),a&&e&&i("voice",{transcriptLength:String(e.length)}),l()},onExpand:l})}function tW(e){let{widget:t,onDismiss:n,setContextFiles:a,t:s}=e,i=()=>n(t.id);return(0,r.jsx)(tL.fX,{onComplete:(e,t)=>
1{let n=(null==t?void 0:t.fileName)||s("pdfDocument"),r={id:"pdf-".concat(Date.now()),name:n,content:e,type:"document"};a(e=>[...e,r]),tM(s("pdfExtracted",{fileName:n})),i()},onExpand:()=>window.location.href="/capture?tool=pdf",enableImageAnalysis:!0})}function tq(e){let{widget:t,onDismiss:n,setContextFiles:a,t:s}=e,i=()=>n(t.id);return(0,r.jsx)(tL.Ry,{onComplete:(e,t)=>{let n=(null==t?void 0:t.fileName)||s("document"),r={id:"document-".concat(Date.now()),name:n,content:e,type:"document"};a(e=>[...e,r]),tM(s("documentExtracted",{fileName:n})),i()},onExpand:()=>window.location.href="/capture?tool=document",showPreview:!0})}function tG(e){let{widget:t,onDismiss:n,setContextFiles:a,t:s}=e,i=()=>n(t.id);return(0,r.jsx)(tL.ao,{onComplete:(e,t)=>{let n=(null==t?void 0:t.title)||s("videoTranscript"),r={id:"video-".concat(Date.now()),name:n,content:e,type:"upload"};a(e=>[...e,r]),tM(s("videoTranscribed",{title:n})),i()},onExpand:()=>window.location.href="/capture?tool=video"})}function tV(e){let{widget:t,onDismiss:n,setContextFiles:a,t:s}=e,i=()=>n(t.id);return(0,r.jsx)(tL.I9,{onComplete:e=>{let t={id:"audio-".concat(Date.now()),name:s("audioTranscript"),content:e,type:"upload"};a(e=>[...e,t]),tM(s("audioFileTranscribedAdded")),i()},onExpand:()=>window.location.href="/capture?tool=audio"})}function tH(e){let{widget:t,onDismiss:n,setContextFiles:a,t:s}=e,i=()=>n(t.id);return(0,r.jsx)(tL.ZU,{onComplete:e=>{let t={id:"text-".concat(Date.now()),name:s("pastedText"),content:e,type:"upload"};a(e=>[...e,t]),tM(s("textAddedToContext")),i()},onExpand:()=>window.location.href="/capture?tool=text"})}function tJ(e){let{widgets:t,...n}=e,a=[];for(let e of t){let t={...n,widget:e};switch(e.type){case"research":a.push((0,r.jsx)(tZ,{...t},e.id));break;case"upload":a.push((0,r.jsx)(tz,{...t},e.id));break;case"voice":a.push((0,r.jsx)(tK,{...t},e.id));break;case"pdf":a.push((0,r.jsx)(tW,{...t},e.id));break;case"document":a.push((0,r.jsx)(tq,{...t},e.id));break;case"video":a.push((0,r.jsx)(tG,{...t},e.id));break;case"audio":a.push((0,r.jsx)(tV,{...t},e.id));break;case"text":a.push((0,r.jsx)(tH,{...t},e.id))}}return a}var tB=n(31001),tX=n(43029);function tQ(e){var t,a;let{workflowId:s,instanceId:i,fresh:l=!1,canvasFileId:c,onNavigateToTab:d,onCanvasRegenerated:p,className:f}=e,h=(0,u.T)("workflows"),[g,x]=(0,o.useState)(null),[v,k]=(0,o.useState)(!0),[y,w]=(0,o.useState)(!1),[j,b]=(0,o.useState)(0),[N,C]=(0,o.useState)(!1),S=(0,o.useRef)(null),T=(0,o.useRef)(new Date().toISOString()),I=(0,o.useRef)(!1),E=(0,o.useCallback)(async()=>{try{let e=await fetch("/api/workflows/".concat(s,"/evaluation?instanceId=").concat(i));if(!e.ok)return{report:null,createdAt:null};let t=await e.json();return{report:t.report,createdAt:t.created_at}}catch(e){return{report:null,createdAt:null}}},[s,i]),_=(0,o.useCallback)(async()=>{if(c&&!I.current){I.current=!0;try{(await fetch("/api/workflows/".concat(s,"/evaluation"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({instanceId:i,canvasFileId:c})})).ok||console.error("[EvalWidget] Failed to trigger evaluation")}catch(e){console.error("[EvalWidget] Error triggering evaluation:",e)}}},[s,i,c]);(0,o.useEffect)(()=>{let e=!0,t=T.current,n=async()=>{let{report:n,createdAt:r}=await E();if(e){if(n){if(l&&r&&new Date(r).getTime()<new Date(t).getTime()-5e3){b(e=>{let t=e+1;return t>=10&&(x(n),C(!0),k(!1),S.current&&(clearInterval(S.current),S.current=null)),t});return}x(n),k(!1),S.current&&(clearInterval(S.current),S.current=null);return}b(e=>{let t=e+1;return t>=10&&(C(!0),k(!1),S.current&&(clearInterval(S.current),S.current=null)),t})}};return l&&c&&_(),n(),S.current=setInterval(n,2e3),()=>{e=!1,S.current&&clearInterval(S.current)}},[E,l,c,_]);let R=(0,o.useCallback)(async()=>{if(!s||!i)return;w(!0);let{toast:e}=await Promise.resolve().then(n.bind(n,17787));e.loading(h("regeneratingFromEvaluation"),{id:"regen"});try{let t=await fetch("/api/workflows/".concat(s,"/regenerate"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({instanceId:i})});if(!t.ok){let n=await t.json();console.error("[EvalWidget] Regeneration failed:",n.error),e.error(h("regenerationFailed"),{id:"regen"});return}let n=await t.json();if(n.success&&n.canvas){let t=n.canvas.version||0;e.success(h("documentUpdatedToVersion",{version:t}),{id:"regen"}),null==p||p(n.canvas)}}catch(t){console.error("[EvalWidget] Regeneration error:",t),e.error(h("regenerationFailed"),{id:"regen"})}finally{w(!1)}},[s,i,p,h]),P=g?{passed:g.results.filter(e=>e.pass).length,failed:g.results.filter(e=>!e.pass).length,total:g.results.length}:null;return v&&!g?(0,r.jsxs)("div",{className:(0,m.cn)("p-4 border rounded-lg space-y-3",f),children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(tB.O,{className:"h-8 w-8 rounded"}),(0,r.jsx)(tB.O,{className:"h-4 w-32"})]}),(0,r.jsx)(tB.O,{className:"h-4 w-full"}),(0,r.jsx)("div",{className:"text-xs text-muted-foreground",children:h("evaluatingWithPolls",{count:j,max:10})})]}):N&&!g?(0,r.jsxs)("div",{className:(0,m.cn)("p-4 border rounded-lg",f),children:[(0,r.jsx)("p",{className:"text-sm text-muted-foreground mb-3",children:h("evaluationTakingLonger")}),(0,r.jsxs)(A.z,{variant:"outline",size:"sm",onClick:()=>null==d?void 0:d("evaluation"),className:"gap-2",children:[h("viewFullEvaluation"),(0,r.jsx)(tX.Z,{className:"h-3 w-3"})]})]}):g?(0,r.jsxs)("div",{className:(0,m.cn)("border rounded-lg bg-card overflow-hidden",f),children:[(0,r.jsx)("div",{className:"p-4 border-b bg-muted/30",children:(0,r.jsx)("div",{className:"flex items-center justify-between",children:(0,r.jsxs)("div",{className:"flex items-center gap-4",children:[(0,r.jsx)("div",{className:"flex items-center justify-center w-12 h-12 rounded-lg bg-foreground text-background font-bold text-xl",children:g.total_score}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"font-medium",children:h("evaluationCompleted")}),(0,r.jsxs)("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsx)(tO.Z,{className:"h-3.5 w-3.5"}),h("passedCount",{count:null!==(t=null==P?void 0:P.passed)&&void 0!==t?t:0})]}),(0,r.jsx)("span",{children:"\xb7"}),(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsx)(eC.Z,{className:"h-3.5 w-3.5"}),h("failedCount",{count:null!==(a=null==P?void 0:P.failed)&&void 0!==a?a:0})]})]})]})]})})}),g.summary&&(0,r.jsx)("div",{className:"p-4 border-b",children:(0,r.jsx)("p",{className:"text-sm text-muted-foreground leading-relaxed",children:g.summary})}),(0,r.jsxs)("div",{className:"p-3 flex items-center gap-2 bg-muted/20",children:[(0,r.jsxs)(A.z,{variant:"outline",size:"sm",onClick:()=>null==d?void 0:d("evaluation"),className:"gap-2",children:[h("viewFullEvaluation"),(0,r.jsx)(tX.Z,{className:"h-3.5 w-3.5"})]}),P&&P.failed>0&&(0,r.jsx)(A.z,{variant:"default",size:"sm",onClick:R,disabled:v||y,className:"gap-2",children:y?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(tl.Z,{className:"h-3 w-3 animate-spin"}),h("regenerating")]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(tl.Z,{className:"h-3 w-3"}),h("improve")]})})]})]}):(0,r.jsx)("div",{className:(0,m.cn)("p-4 border rounded-lg",f),children:(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:h("noEvaluationFound")})})}function tY(e){let{workflowContext:t,currentProjectId:n,sendToolCompleteSignal:a,t:s}=e;return(0,r.jsx)(tL.cR,{projectId:n||void 0,workflowId:t.workflowId,instanceId:t.instanceId,onFilesUploaded:e=>{l.kg.log("[UniversalAIChat] Files uploaded via workflow widget:",e.length),a("files",{fileNames:e.map(e=>e.name).join(", "),count:String(e.length)},{refreshWorkspace:!0,toastMessage:s("filesUploadedCount",{count:e.length})})},onExpand:t.onNavigateToTab?()=>{var e;return null===(e=t.onNavigateToTab)||void 0===e?void 0:e.call(t,"files")}:void 0})}function t$(e){let{workflowContext:t,setContextFiles:n,sendToolCompleteSignal:a,t:s}=e;return(0,r.jsx)(tL.kI,{workflowId:t.workflowId,instanceId:t.instanceId,existingVoiceItems:t.voiceItems,onComplete:e=>{let t={id:"interview-".concat(Date.now()),name:s("voiceInterviewTranscript"),content:e,type:"upload"};
1n(e=>[...e,t]),a("voice",{},{refreshWorkspace:!0,toastMessage:s("voiceInterviewCompleted")})},onExpand:()=>{var e;null===(e=t.onNavigateToTab)||void 0===e||e.call(t,"voice")}})}function t0(e){let{workflowContext:t}=e;return(0,r.jsx)(tQ,{workflowId:t.workflowId,instanceId:t.instanceId,fresh:!0,canvasFileId:t.canvasFileId,onNavigateToTab:t.onNavigateToTab,onCanvasRegenerated:e=>{var n,r;null===(n=t.onCanvasPreview)||void 0===n||n.call(t,{title:e.title,content:e.content,fileId:e.id}),null===(r=t.refreshWorkspaceData)||void 0===r||r.call(t)},className:"mt-2"})}let t1=e=>Promise.resolve().then(n.bind(n,17787)).then(t=>{let{toast:n}=t;return n.success(e)});function t3(e){e.setContextFiles(t=>[...t,e.contextFile]),e.workflowContext?e.sendToolCompleteSignal(e.toolType,e.metadata,e.refreshWorkspace?{refreshWorkspace:!0,toastMessage:e.toastMessage}:{toastMessage:e.toastMessage}):t1(e.toastMessage)}let t2=e=>()=>{window.location.href="/capture?tool=".concat(e)};function t5(e){let{t}=e;return(0,r.jsx)(tL.ZU,{onComplete:n=>{t3({...e,contextFile:{id:"text-".concat(Date.now()),name:t("pastedText"),content:n,type:"upload"},toolType:"text",metadata:{},refreshWorkspace:!1,toastMessage:t("textAddedToContext")})},onExpand:t2("text")})}function t4(e){let{t}=e;return(0,r.jsx)(tL.Sp,{onComplete:n=>{t3({...e,contextFile:{id:"recording-".concat(Date.now()),name:t("voiceRecordingTranscript"),content:n,type:"upload"},toolType:"audio",metadata:{},refreshWorkspace:!0,toastMessage:t("voiceRecordingTranscribedAdded")})},onExpand:t2("voice")})}function t7(e){let{t}=e;return(0,r.jsx)(tL.ao,{onComplete:(n,r)=>{let a=(null==r?void 0:r.title)||t("videoTranscript");t3({...e,contextFile:{id:"video-".concat(Date.now()),name:a,content:n,type:"upload"},toolType:"video",metadata:{title:a},refreshWorkspace:!0,toastMessage:t("videoTranscribed",{title:a})})},onExpand:t2("video")})}function t6(e){let{t}=e;return(0,r.jsx)(tL.I9,{onComplete:n=>{t3({...e,contextFile:{id:"audio-".concat(Date.now()),name:t("audioTranscript"),content:n,type:"upload"},toolType:"audio",metadata:{},refreshWorkspace:!0,toastMessage:t("audioFileTranscribedAdded")})},onExpand:t2("audio")})}function t8(e){let{t}=e;return(0,r.jsx)(tL.fX,{onComplete:(n,r)=>{let a=(null==r?void 0:r.fileName)||t("pdfDocument");t3({...e,contextFile:{id:"pdf-".concat(Date.now()),name:a,content:n,type:"document"},toolType:"pdf",metadata:{fileName:a},refreshWorkspace:!0,toastMessage:t("pdfExtracted",{fileName:a})})},onExpand:t2("pdf"),enableImageAnalysis:!0})}function t9(e){let{t}=e;return(0,r.jsx)(tL.Ry,{onComplete:(n,r)=>{let a=(null==r?void 0:r.fileName)||t("document");t3({...e,contextFile:{id:"document-".concat(Date.now()),name:a,content:n,type:"document"},toolType:"document",metadata:{fileName:a},refreshWorkspace:!0,toastMessage:t("documentExtracted",{fileName:a})})},onExpand:t2("document"),showPreview:!0})}function ne(e){let{setContextFiles:t,t:n}=e;return(0,r.jsx)(tL.kI,{onComplete:e=>{let r={id:"interview-".concat(Date.now()),name:n("voiceInterviewTranscript"),content:e,type:"upload"};t(e=>[...e,r])},onExpand:t2("voice-interview")})}function nt(e){let{currentProjectId:t,workspaceContext:a,onFileUploaded:s,setContextFiles:i,t:o}=e;return(0,r.jsx)(tL.cR,{projectId:t||void 0,onFilesUploaded:e=>{l.kg.log("[UniversalAIChat] Files uploaded via inline widget:",e.length),e.forEach(e=>{if(a&&s)s({id:e.id,name:e.name,type:"file"}),Promise.resolve().then(n.bind(n,17787)).then(t=>{let{toast:n}=t;n.success(o("addedToInboxTitle",{name:e.name}),{description:o("addedToInboxDescription")})});else{let t={id:e.id,name:e.name,content:"[Uploaded file: ".concat(e.name,"]"),type:"upload"};i(e=>[...e,t])}})}})}function nn(e){let{actions:t}=e,n=t.find(e=>"RESEARCH"===e.type);return(0,r.jsx)(tL.Kg,{initialTopic:n&&"topic"in n?String(n.topic):void 0,autoStart:(null==n?void 0:n.mode)==="START"})}function nr(e){let{workflowContext:t}=e;return(null==t?void 0:t.instanceId)?(0,r.jsx)(tQ,{workflowId:t.workflowId,instanceId:t.instanceId,fresh:!0,canvasFileId:t.canvasFileId,onNavigateToTab:t.onNavigateToTab}):null}var na=n(21764),ns=n(17787);let ni="command-palette-recent";var nl=n(20361),no=n(51889),nc=n(55298);
1function nd(e){var t;return{id:e.id,role:e.role,content:e.content,attachments:null!==(t=x(e.attachments))&&void 0!==t?t:[],model:e.model,researchProvenance:(0,nc.w3)(e.content),createdAt:new Date(e.created_at)}}function nu(e,t,n,r){if("aborted"!==t)return e;let a=e.findLastIndex(e=>"assistant"===e.role);if(a<0)return e;let s=e[a];if(!s||s.content.trim()&&s.content!==n)return e;let i=[...e];return i[a]={...s,content:r},i}var nm=n(13207);let np=[{ids:e=>e.context_pack_ids,url:"/api/context-packs",failure:"[UniversalAIChat] Failed to load pack details:",read:e=>{let{packs:t}=e;return(e,n)=>{let r=new Set(n),a=t.filter(e=>r.has(e.id));e.setSelectedPacks(a)}}},{ids:e=>e.active_skill_ids,url:"/api/tools",failure:"[UniversalAIChat] Failed to load skill details:",read:e=>{let{tools:t}=e;return(e,n)=>{let r=function(e,t){let n=new Set(t);return(e||[]).filter(e=>n.has(e.id)).map(e=>({id:e.id,name:e.name,description:e.description,instructions:e.instructions,category:e.category,domain:e.domain,owner_type:e.owner_type,voice_enabled:e.voice_enabled,definition:e.definition}))}(t,n);e.setSelectedSkills(r)}},none:e=>e.setSelectedSkills([])},{ids:e=>e.active_filter_ids,url:"/api/tools",failure:"[UniversalAIChat] Failed to load filter details:",read:e=>{let{tools:t}=e;return(e,n)=>{let r=function(e,t){let n=new Set(t);return(e||[]).filter(e=>{var t;return n.has(e.id)&&(null===(t=e.category)||void 0===t?void 0:t.startsWith("filter-"))}).map(e=>({id:e.id,name:e.name,instructions:e.instructions||"",category:e.category}))}(t,n);e.setSelectedFilters(r)}},none:e=>e.setSelectedFilters([])}];async function nf(e,t){var n;let{t:r,setConversationHistoryLoad:a,setIsLoading:s,setError:i}=e,{isCurrentLoad:o,signal:c}=function(e,t){var n;let r=++e.conversationLoadGenerationRef.current;null===(n=e.conversationLoadAbortRef.current)||void 0===n||n.abort();let a=new AbortController;return e.conversationLoadAbortRef.current=a,{isCurrentLoad:n=>{var a;return(a={loadGeneration:r,currentGeneration:e.conversationLoadGenerationRef.current,activeConversationId:e.activeConversationIdRef.current,requestedConversationId:t,responseConversationId:n}).loadGeneration===a.currentGeneration&&a.activeConversationId===a.requestedConversationId&&(void 0===a.responseConversationId||a.responseConversationId===a.requestedConversationId)},signal:a.signal}}(e,t);e.conversationDataOwnerRef.current=null,a({conversationId:t,status:"loading"}),s(!0),i(null);try{let a=await fetch("/api/ai/conversations/".concat(t),{signal:c});if(a.ok){let r=await a.json();if(!o())return;let s=r.conversation;if(!o(null==s?void 0:s.id))return;for(let r of(function(e,t,n){let{t:r,setError:a,setInput:s}=e,i=(n.messages||[]).map(nd);e.setMessages(i),"error"===n.agent_status&&a(r("systemInterrupted")),e.setModel(n.model||nm.Q6),e.setConversationTitle(n.title||r("conversation")),e.setHasSummary(!!n.context_summary);let l=function(e,t){let n=null!=e?e:{},r=Array.isArray(n.message_queue)?n.message_queue.map(w).filter(e=>null!==e).map(e=>k(e,t)&&!e.internal?{...e,internal:j("workflow_start",t)}:e):[];return{queue:r,autoInitiateItem:r.find(e=>k(e,t)),queueRevision:"number"==typeof n.message_queue_revision?n.message_queue_revision:0,draftRevision:"number"==typeof n.draft_revision?n.draft_revision:0,draft:"string"==typeof n.draft&&n.draft.trim()?n.draft:null}}(n.metadata,n.id),o=l.queue,c=l.autoInitiateItem;if(e.autoInitiateEmptyConversationRef.current=0===i.length?n.id:null,c&&(e.autoInitiateQueuedMessageIdRef.current=c.id,e.autoInitiateQueueRetryBlockedRef.current=!1,e.pendingConfirmationRef.current="[START]",e.autoInitiateTriggeredRef.current=!0,e.setIsAutoInitiating(!0)),e.setMessageQueue(o),e.messageQueueRef.current=o,e.queueRevisionRef.current=l.queueRevision,e.draftRevisionRef.current=l.draftRevision,null!==l.draft){let e=l.draft;s(t=>t.trim()?t:e)}if(e.conversationDataOwnerRef.current=n.id,e.queueDispatchInFlightRef.current=!1,n.title&&t){var d;null===(d=e.onTitleChange)||void 0===d||d.call(e,t,n.title)}}(e,t,s),e.contextJustLoadedRef.current=!0,s.context_files&&Array.isArray(s.context_files)&&s.context_files.length>0?e.setContextFiles(s.context_files.filter(e=>"upload"!==e.type)):e.setContextFiles([]),s.attachments&&Array.isArray(s.attachments)&&s.attachments.length>0?e.setAttachments(s.attachments):e.setAttachments([]),s.context_goals&&Array.isArray(s.context_goals)&&s.context_goals.length>0?e.setPinnedGoals(s.context_goals):e.setPinnedGoals([]),np)){let t=r.ids(s);if(!(t&&Array.isArray(t)&&t.length>0)){null===(n=r.none)||void 0===n||n.call(r,e);continue}try{let n=await fetch(r.url);if(!(n.ok&&o()))continue;let a=r.read(await n.json());if(!o())return;a(e,t)}catch(e){l.kg.error(r.failure,e)}}o(s.id)&&s.ai_project_id&&s.ai_project_id!==e.currentProjectId&&e.setCurrentProjectId(s.ai_project_id)}else{if(!o())return;let n=await a.json().catch(()=>({error:r("unknownError")}));if(!o())return;!function(e,t,n,r){let{t:a,setError:s}=e,i=r.error||"HTTP ".concat(n.status);l.kg.error("[UniversalAIChat] Failed to load conversation:",{conversationId:t,status:n.status,error:i}),s(404===n.status?a("conversationNotFound"):401===n.status?a("conversationLoginRequired"):a("conversationLoadFailed",{error:i}))}(e,t,a,n)}}catch(t){t instanceof Error&&"AbortError"===t.name||o()&&(l.kg.error("[UniversalAIChat] Failed to load conversation:",t),e.setError(e.t("conversationNetworkLoadFailed")))}finally{o()&&(e.setConversationHistoryLoad(e=>e.conversationId===t?{conversationId:t,status:"loaded"}:e),e.setIsLoading(!1))}}var nh=n(23442);let ng=["task_created","task_updated","task_deleted","goal_created","goal_updated","goal_deleted","priority_created","priority_updated","priority_deleted","log_added","workspace_linked","workspace_unlinked","milestone_created","milestone_updated"];function nx(e){let t=function(e){var t,n;let r=e.replace(/<!--WORKSPACE_REFRESH:[^>]+-->\n?/g,""),a=r.match(/<!--SUGGEST_EDIT:(.*?)-->/),s=null!==(t=null==a?void 0:a[1])&&void 0!==t?t:null;s&&(r=r.replace(/<!--SUGGEST_EDIT:.*?-->\n?/g,""));let i=r.match(/<!--NOTIFY_USER:(.*?)-->/),l=null!==(n=null==i?void 0:i[1])&&void 0!==n?n:null;l&&(r=r.replace(/<!--NOTIFY_USER:.*?-->\n?/g,""));let o=r.match(/<!--CONVERSATION_TITLE:([\s\S]*?)-->/),c=o&&o[1]?o[1].replace(/\n/g," ").trim():null,d=(r=r.replace(/<!--CONVERSATION_TITLE:[\s\S]*?-->/g,"")).indexOf("<!--CONVERSATION_TITLE:");return -1!==d&&(r=r.slice(0,d).trimEnd()),{content:r,suggestEditPayloadText:s,notifyUserPayloadText:l,conversationTitle:c}}(e),n=function(e){var t;let n=Array.from(e.matchAll(/<!--ASSISTANT_MESSAGE_ID:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-->/gi)),r=n[n.length-1],a=e.replace(/<!--ASSISTANT_MESSAGE_ID:[0-9a-f-]{36}-->
1/gi,""),s=a.includes("<!--SUGGEST_PLAN_MODE-->");s&&(a=a.replace(/<!--SUGGEST_PLAN_MODE-->/g,""));let i=[];for(let e of Array.from(a.matchAll(/<!-- EXECUTION_WIDGET:(\{.*?\}) -->/g)))try{if(!e[1])continue;let t=JSON.parse(e[1]);(null==t?void 0:t.widget_type)&&ng.includes(t.widget_type)&&i.push(t.widget_type)}catch(e){}return{content:a,persistedMessageId:null!==(t=null==r?void 0:r[1])&&void 0!==t?t:null,suggestPlanMode:s,executionMutationTypes:i}}(t.content);return{content:n.content,suggestEditPayloadText:t.suggestEditPayloadText,notifyUserPayloadText:t.notifyUserPayloadText,conversationTitle:t.conversationTitle,persistedMessageId:n.persistedMessageId,suggestPlanMode:n.suggestPlanMode,executionMutationTypes:n.executionMutationTypes}}function nv(e,t){if(e.suggestEditPayloadText)try{let t=JSON.parse(e.suggestEditPayloadText);window.dispatchEvent(new CustomEvent("workspace-suggest-edit",{detail:{fileId:t.fileId,fileName:t.fileName,patches:t.patches,description:t.description}}))}catch(e){console.warn("[UniversalAIChat] Failed to parse SUGGEST_EDIT payload:",e)}if(e.notifyUserPayloadText)try{let r=JSON.parse(e.notifyUserPayloadText);Promise.resolve().then(n.bind(n,17787)).then(e=>{let{toast:n}=e;t.stillOwnsConversation()&&("success"===r.type?n.success:"warning"===r.type?n.warning:"error"===r.type?n.error:n.info)(r.message)})}catch(e){}if(e.conversationTitle){var r,a,s;t.setConversationTitle(e.conversationTitle),null===(r=t.onTitleChange)||void 0===r||r.call(t,t.conversationId,e.conversationTitle),null===(a=(s=t.sidebarRefreshRef).current)||void 0===a||a.call(s)}if(e.persistedMessageId){let n=e.persistedMessageId;t.setMessages(e=>e.map(e=>e.id===t.assistantMessageId?{...e,id:n}:e))}e.suggestPlanMode&&(t.readOnlyTools||t.setPlanMode(!0))}function nk(e,t){return e.slice(t).replace(/<!--CANVAS_META:.*?-->/g,"").trim()}function ny(e,t){if(!t.canvasMode&&e.includes("<!--CANVAS_META:")){let t=function(e){var t,n;let r=null===(t=e.match(/<!--AGENT_RESOURCE_NONCE:([0-9a-f-]{36})-->/i))||void 0===t?void 0:t[1];for(let t of e.matchAll(/<!--CANVAS_META:(\{.*?\})-->/g))try{let e=JSON.parse(null!==(n=t[1])&&void 0!==n?n:"");if(!e||"object"!=typeof e||!("__canvas__"in e))continue;let a=e.__canvas__;if(null===a||"object"!=typeof a||!("started"in a)||!0!==a.started||r&&(!("nonce"in a)||a.nonce!==r))continue;return{start:t.index,end:t.index+t[0].length,filename:"filename"in a&&"string"==typeof a.filename?a.filename:"output.md",isRegeneration:"isRegeneration"in a&&!0===a.isRegeneration}}catch(e){}return null}(e);if(t)return{phase:"native-start",title:t.filename,isRegeneration:t.isRegeneration,contentStart:t.end,preContent:e.slice(0,t.start).trim(),content:nk(e,t.end)}}if(t.isNativeCanvasMode&&t.canvasMode)return{phase:"native-stream",content:nk(e,t.nativeCanvasContentStart)};if(!t.canvasMode&&e.includes("[CANVAS")){let t=e.match(/\[CANVAS\s*:\s*create\s*\]/i);if(t){let n=e.indexOf(t[0]);return{phase:"legacy-start",preContent:e.slice(0,n).trim(),content:e.slice(n+t[0].length)}}}return t.canvasMode?function(e){var t,n;let r=e.indexOf("[CANVAS"),a=(null===(n=e.match(/\[CANVAS\s*:\s*create\s*\]/i))||void 0===n?void 0:null===(t=n[0])||void 0===t?void 0:t.length)||0,s=e.slice(r+a),i=s.match(/\[\s*\/\s*CANVAS\s*\]/i);if(!i)return{phase:"legacy-stream",content:s,end:null};let l=s.indexOf(i[0]);return{phase:"legacy-stream",content:s,end:{content:s.slice(0,l).trim(),postContent:s.slice(l+i[0].length).trim()}}}(e):{phase:"plain"}}function nw(e){var t;let n=e.match(/^#+ (.+)$/m);return(null==n?void 0:n[1])?n[1].trim():(null===(t=e.split("\n")[0])||void 0===t?void 0:t.replace(/^#+\s*/,"").slice(0,50))||void 0}function nj(e){return e.slice(e.indexOf("-->")+3).replace(/<!--CANVAS_META:.*?-->/g,"").trim()}let nb=["cut-from-katalogvedtak","pending-factor-coverage"],nN={"cut-from-katalogvedtak":"modelUnavailableSwitched","pending-factor-coverage":"modelPendingSwitched"},nC={"cut-from-katalogvedtak":"normalize","pending-factor-coverage":"keep"};var nS=n(33860),nT=n(90697);let nI="praksis:conversation-messages-changed";var nE=n(72725);function n_(e,t){return t?"turn_blocked"===t.type?{code:t.code,notice:t.notice}:"lifecycle"===t.type&&"request_sent"===t.phase?null:e:e}function nA(e,t){return!(null!==t&&Number.isFinite(t))||e-t>=33e4}var nR=n(8400),nP=n(69654),nD=n(58975),nF=n(97973);function nO(){return{"Content-Type":"application/json",...(0,p.p)()}}let nU=3e4;function nL(e){var t,h,g,w;let{layout:N="chat",showSidebar:C=!0,sidebarOpen:S=!0,onProductionFileClick:T,onAgentResourceOpen:I,onProducedRes
1ourcesChange:E,initialProjectId:_,initialConversationId:R,externalAgentRecordingSessionId:P,initialMessageId:D,timelineItems:F,conversationHistoryLoadingFallback:U,internalClearSettlementDeadlineMs:L,initialFolderId:M,startNewConversation:Z=!1,initialContext:z=[],initialSkillId:K,initialSkillIds:W=[],onMessageSent:q,readOnlyTools:G=!1,onSkillDraft:V,onBeforeSend:H,onConversationChange:J,onTitleChange:B,onSkillsChange:X,onFiltersChange:Q,onContextPacksChange:Y,onContextFilesAdded:$,initialFilterIds:ee=[],document:et,onDocumentEdit:en,previewMode:er=!1,askAIRequest:ea,onAskAIRequestHandled:es,headerAction:ei,onOpenCanvas:el,onCanvasCreate:eo,className:ec,folderId:ed,folderSystemPrompt:eu,executionForm:em,skillPreview:ep,source:ef="chat",boardContext:eh,presentationContext:eg,workflowContext:ex,workspaceContext:ev,executionContext:ek,onFormFieldUpdate:ey,initialPinnedGoals:ew=[],onRemovePinnedGoal:ej,onExecutionWidgetAddContext:eb,executionContextItems:eN=[],onExecutionWidgetOpenDetails:eC,onExecutionWidgetSelectForChat:eS,onFileUploaded:eT,onAttachmentsChange:eI,allowedModelProviders:eE,defaultModel:e_,autoPrompt:eA,onAutoPromptExecuted:eR,hideEmptyState:eP=!1,recentSessions:eD,emptyStateIntentFirst:eF=!1,emptyStateTitle:eO,emptyStateSubtitle:eU,emptyStateInputControls:eL,searchableRecentSessions:eM=!1,onSessionClick:eZ,onViewAllSessions:ez,autoInitiate:eK=!1,hideHeader:eW=!1,topBar:eq,chatActionsRef:eG}=e,eV=!!ev,eH=void 0!==L&&Number.isFinite(L)&&L>0?L:nU,eJ=(0,d.bU)(),eX=(0,u.T)("chat"),e1=eX("newConversationLabel"),e3=(0,o.useMemo)(()=>new Set([e1,eX("conversation"),"Ny samtale","Samtale","AI Chat","New conversation","Ny konversation","Untitled Session","New Session"]),[e1,eX]),e2=ex?"workflow":eg?"presentation":"canvas"===ef||"board"===ef?ef:ev?"workspace":ef,e5=null!=eE?eE:void 0;ex&&l.kg.debug("[UniversalAIChat] Workflow context:",{instanceId:ex.instanceId,workflowId:ex.workflowId,hasCanvas:!!ex.canvasContent});let e7="sidebar"===N?"narrow":"wide",[e6,e8]=(0,o.useState)(S),[e9,te]=(0,o.useState)(_||null),[ta,ts]=(0,o.useState)(R||null);function ti(e){var t,n,r;let a=rD.current!==e;if(!a){ts(e);return}let s=rD.current,i=null===s&&aG.current===e;if(tG.current.set(s,i?[]:tq.current),tV(i?tq.current:null!==(n=tG.current.get(e))&&void 0!==n?n:[]),rW.current+=1,null===(t=rq.current)||void 0===t||t.abort(),rq.current=null,a){for(let e of(null===(r=r_.current)||void 0===r||r.abort(),r_.current=null,rA.current=null,rE.current=null,rN.current=!1,td(!1),tm(void 0),rL.current))clearTimeout(e);rL.current.clear(),sh.current&&clearTimeout(sh.current),sh.current=null,rC.current=!1,rS.current=null,rT.current=!1,rI.current=null,a$.current=!1,rk.current=null,a1(!1)}rD.current=e,rZ.current=null,rz.current=0,rK.current=0,rO.current=!1,rF.current=null,rR.current=null,rP.current=null,nM.current=[],nL([]),np(""),nz(!1),to([]),tM([]),tR([]),tz([]),tQ([]),r1([]),ar([]),n6([]),ts(e)}let[tl,to]=(0,o.useState)([]),[tc,td]=(0,o.useState)(!1);(0,nF.A9)(ta,tc);let[tu,tm]=(0,o.useState)(),[tp,tf]=(0,o.useState)(!1),[th,tx]=(0,o.useState)({conversationId:null!=R?R:null,status:"not-started"}),[tv,tk]=(0,o.useState)(()=>"en"===eJ||"sv"===eJ?eJ:"no"),[ty,tw]=(0,o.useState)(e_||nm.Q6),[tj,tb]=(0,o.useState)("vercel"),[tN,tC]=(0,o.useState)([]),[tS,tT]=(0,o.useState)(!1),[tI,tE]=(0,o.useState)(!1),[t_,tR]=(0,o.useState)(z),[tO,tM]=(0,o.useState)([]),{attachments:tZ,setAttachments:tz,pendingUploads:tK,setPendingUploadsState:tW,pendingUploadsRef:tq,pendingUploadDraftsRef:tG}=function(){let[e,t]=(0,o.useState)([]),[n,r]=(0,o.useState)([]);return{attachments:e,setAttachments:t,pendingUploads:n,setPendingUploadsState:r,pendingUploadsRef:(0,o.useRef)([]),pendingUploadDraftsRef:(0,o.useRef)(new Map)}}(),tV=(0,o.useCallback)(e=>{let t="function"==typeof e?e(tq.current):e;tq.current=t,tW(t)},[]),[tH,tB]=(0,o.useState)(null),[tX,tQ]=(0,o.useState)([]),[t1,t3]=(0,o.useState)(null),t2=function(){let[e,t]=(0,o.useState)(null);return(0,o.useEffect)(()=>{t(e=>(0,nE.lW)().reduce(n_,e));let e=e=>{let n=e.detail;t(e=>n_(e,n))};return window.addEventListener(nE.dD,e),()=>window.removeEventListener(nE.dD,e)},[]),e}(),{input:nc,setInput:np,messageQueue:ng,setMessageQueue:nL,messageQueueRef:nM}=function(){let[e,t]=(0,o.useState)(""),[n,r]=(0,o.useState)([]);return{input:e,setInput:t,messageQueue:n,setMessageQueue:r,messageQueueRef:(0,o.useRef)([])}}(),[nZ,nz]=(0,o.useState)(!1),[nK,nW]=(0,o.useState)(e1),[nq,nG]=(0,o.useState)(!1),[nV,nH]=(0,o.useState)(!1),[nJ,nB]=(0,o.useState)(!1),[nX,nQ]=(0,o.useState)(!1),[nY,n$]=(0,o.useState)(!1),[n0,n1]=(0,o.useState)(!1),[n3,n2]=(0,o.useState)(),{updateProcess:n5,processes:n4}=(0,nD.a)(),[n7,n6]=(0,o.useState)(ew);(0,o.useEffect)(()=>{ew.length>0&&n6(e=>{let t=new Set(e.map(e=>e.id));return[...e,...ew.filter(e=>!t.has(e.id))]})},[ew]),(0,o.useEffect)(()=>{let e=!1;return async function(){try{var t;let n=await fetch("/api/ai/runtimes");if(!n.ok)return;let r=await n.json();if(e)return;let a=null!==(t=r.runtimes)&&void 0!==t?t:[];tC(a),a.some(e=>"hermes"===e.id&&e.available)||tb("vercel")}catch(t){e||l.kg.warn("[UniversalAIChat] Failed to load agent runtimes",{error:t instanceof Error?t.message:String(t)})}}(),()=>{e=!0}},[]);let n8=(0,o.useMemo)(()=>tl.reduce((e,t)=>
1t.tokensUsed?e+t.tokensUsed:"string"==typeof t.content?e+(0,nT.f8)(t.content):e,0),[tl]),n9=(0,o.useMemo)(()=>tN.some(e=>"hermes"===e.id&&e.available),[tN]),re=(0,o.useMemo)(()=>{var e,t;return[{id:"vercel",label:"Praksis",available:!0},{id:"hermes",label:(e={capabilities:tN,hermesAvailable:n9,hermesLabel:eX("externalAgentRunHermes")}).hermesLabel,available:e.hermesAvailable,unavailableReason:null===(t=e.capabilities.find(e=>"hermes"===e.id))||void 0===t?void 0:t.unavailable_reason}]},[tN,n9,eX]),rt="hermes"===(g={agentRuntime:tj,model:ty}).agentRuntime?"hermes-main":g.model,rn=(w={hermesRuntimeAvailable:n9,workspaceHermesVoiceAvailable:tS,workspaceId:null==ev?void 0:ev.workspaceId}).hermesRuntimeAvailable&&w.workspaceHermesVoiceAvailable&&!!w.workspaceId,rr=(0,o.useMemo)(()=>{var e;return(e={hermesVoiceTargetAvailable:rn,model:ty,hermesLabel:eX("externalAgentRunHermes")}).hermesVoiceTargetAvailable?{label:e.hermesLabel,runtime:"hermes",model:"hermes-main"}:{label:"Praksis",runtime:"vercel",model:e.model}},[rn,ty,eX]),ra=tD({featureEnabled:!1,hasVoiceTarget:!!rr,isDocumentMode:!!et});(0,o.useEffect)(()=>{let e=null==ev?void 0:ev.workspaceId;if(!e||!n9){tT(!1);return}let t=new AbortController;return async function(){try{let n=await fetch("/api/meetings/hermes-settings?workspace_id=".concat(encodeURIComponent(e)),{signal:t.signal});if(!n.ok){if(t.signal.aborted)return;tT(!1);return}let r=await n.json();if(t.signal.aborted)return;tT(!!r.enabled)}catch(n){if(n instanceof Error&&"AbortError"===n.name)return;l.kg.warn("[UniversalAIChat] Failed to resolve workspace Hermes availability",{error:n instanceof Error?n.message:String(n),workspaceId:e}),t.signal.aborted||tT(!1)}}(),()=>t.abort()},[n9,null==ev?void 0:ev.workspaceId]);let rs=(0,o.useCallback)(e=>{let t=(0,eY.createClient)();t.auth.getUser().then(n=>{let{data:{user:r}}=n;r&&t.from("user_settings").update({default_model:e,updated_at:new Date().toISOString()}).eq("user_id",r.id).then(e=>{let{error:t}=e;t&&l.kg.error("[UniversalAIChat] Failed to save default model:",t)})})},[]);(0,o.useEffect)(()=>{if(e_||tI)return;let e=(0,eY.createClient)();e.auth.getUser().then(t=>{let{data:{user:n}}=t;n&&e.from("user_settings").select("default_model").eq("user_id",n.id).maybeSingle().then(e=>{let{data:t}=e;if((null==t?void 0:t.default_model)&&!ta){if((0,nS.aA)(t.default_model))tw(t.default_model);else{let e=(0,nS.Ih)();tw(e),rs(e)}}tE(!0)})})},[]);let ri=(0,o.useCallback)((e,t)=>{tw(e),t&&fetch("/api/ai/conversations/".concat(t),{method:"PUT",headers:nO(),body:JSON.stringify({model:e})}).catch(e=>l.kg.error("[UniversalAIChat] Failed to persist model:",e))},[]),rl=(0,o.useCallback)(e=>{ri(e,ta),rs(e)},[ri,rs,ta]),ro=(0,o.useCallback)((e,t)=>{let r=function(e){let t=function(e){if("string"!=typeof e||0===e.length)return null;let t=e.split("|");if(3!==t.length)return null;try{let e=decodeURIComponent(t[0]),n=decodeURIComponent(t[1]),r=decodeURIComponent(t[2]);if(!e||!n||!nb.includes(r))return null;return{requestedId:e,effectiveId:n,reason:r}}catch(e){return null}}(e);return t?{effectiveId:t.effectiveId,messageKey:nN[t.reason],values:{requested:t.requestedId,effective:t.effectiveId},normalizePersistedChoice:"normalize"===nC[t.reason]}:null}(e.headers.get("X-Praksis-Model-Substituted"));r&&(r.normalizePersistedChoice?ri(r.effectiveId,t):tw(r.effectiveId),Promise.resolve().then(n.bind(n,17787)).then(e=>{let{toast:t}=e;t.warning(eX(r.messageKey,r.values),{duration:8e3})}))},[ri,eX]),[rc,rd]=(0,o.useState)(!1);(0,o.useEffect)(()=>{(null==ex?void 0:ex.instanceId)&&rd(!1)},[null==ex?void 0:ex.instanceId]),(0,o.useEffect)(()=>{if(!(null==ex?void 0:ex.instanceId)||ta){rd(!0);return}let e=rW.current,t=rD.current,n=!1,r=()=>!n&&e===rW.current&&t===rD.current;return(async()=>{try{l.kg.debug("[UniversalAIChat] Loading workflow conversation for instance:",ex.instanceId);let t=await fetch("/api/ai/conversations?workflow_instance_id=".concat(ex.instanceId,"&source=workflow"));if(!r())return;if(t.ok){var e;let n=await t.json();if(!r())return;if((null===(e=n.conversations)||void 0===e?void 0:e.length)>0){let e=n.conversations[0];l.kg.debug("[UniversalAIChat] Found workflow conversation:",e.id),ti(e.id)}else l.kg.debug("[UniversalAIChat] No existing workflow conversation found")}}catch(e){if(!r())return;
1l.kg.error("[UniversalAIChat] Failed to load workflow conversation:",e)}finally{r()&&rd(!0)}})(),()=>{n=!0}},[null==ex?void 0:ex.instanceId,ta]),(0,o.useEffect)(()=>{if(!(null==eh?void 0:eh.boardId))return;let e=rW.current,t=rD.current,n=!1,r=()=>!n&&e===rW.current&&t===rD.current;return(async()=>{try{var e,t;let n=await fetch("/api/ai/conversations?board_id=".concat(encodeURIComponent(eh.boardId),"&source=board"));if(!n.ok||!r())return;let a=await n.json();if(!r())return;let s=null===(t=a.conversations)||void 0===t?void 0:null===(e=t[0])||void 0===e?void 0:e.id;"string"==typeof s&&ti(s)}catch(e){if(!r())return;l.kg.error("[UniversalAIChat] Failed to load board conversation:",e)}})(),()=>{n=!0}},[null==eh?void 0:eh.boardId]);let[ru,rm]=(0,o.useState)(null),rp=!!(null==eg?void 0:eg.presentationId)&&ru!==(null==eg?void 0:eg.presentationId);(0,o.useEffect)(()=>{if(!(null==eg?void 0:eg.presentationId))return;let e=rW.current,t=rD.current,n=!1,r=()=>!n&&e===rW.current&&t===rD.current;return(async()=>{try{var e,t;let n=await fetch("/api/ai/conversations?presentation_id=".concat(encodeURIComponent(eg.presentationId),"&source=presentation"));if(!r())return;if(!n.ok){let e=await n.json().catch(()=>({error:eX("unknownError")}));if(!r())return;let t=e.error||"HTTP ".concat(n.status);l.kg.error("[UniversalAIChat] Failed to discover presentation conversation:",{presentationId:eg.presentationId,status:n.status,error:t}),t3(eX("conversationLoadFailed",{error:t})),rm(eg.presentationId);return}let a=await n.json();if(!r())return;let s=null===(t=a.conversations)||void 0===t?void 0:null===(e=t[0])||void 0===e?void 0:e.id;rm(eg.presentationId),"string"==typeof s&&ti(s)}catch(e){if(!r())return;l.kg.error("[UniversalAIChat] Failed to load presentation conversation:",e),t3(eX("conversationNetworkLoadFailed")),rm(eg.presentationId)}})(),()=>{n=!0}},[null==eg?void 0:eg.presentationId,eX]);let rf=function(){let[e,t]=(0,o.useState)(!1),[n,r]=(0,o.useState)(""),[a,s]=(0,o.useState)(null),[i,l]=(0,o.useState)([]),[c,d]=(0,o.useState)(new Map),[u,m]=(0,o.useState)(0);(0,o.useEffect)(()=>{try{let e=localStorage.getItem(ni);if(e){let t=JSON.parse(e);l(t.slice(0,5))}}catch(e){}},[]);let p=(0,o.useCallback)(()=>{t(!0),m(0)},[]),f=(0,o.useCallback)(()=>{t(!1),r(""),s(null),m(0)},[]),h=(0,o.useCallback)(()=>{t(e=>!e)},[]),g=(0,o.useCallback)(e=>{r(e),m(0)},[]),x=(0,o.useCallback)(()=>{r(""),m(0)},[]),v=(0,o.useCallback)(e=>{s(e),m(0)},[]),k=(0,o.useCallback)(()=>{s(null),m(0)},[]),y=(0,o.useCallback)(e=>{l(t=>{let n=t.filter(t=>t.id!==e.id),r=[e,...n].slice(0,5);try{localStorage.setItem(ni,JSON.stringify(r))}catch(e){}return r})},[]),w=(0,o.useCallback)(()=>{l([]);try{localStorage.removeItem(ni)}catch(e){}},[]),j=(0,o.useCallback)(e=>{d(t=>{let n=new Map(t);return n.has(e.id)?n.delete(e.id):n.set(e.id,e),n})},[]),b=(0,o.useCallback)(e=>{d(t=>{let n=new Map(t);return n.set(e.id,e),n})},[]),N=(0,o.useCallback)(e=>{d(t=>{let n=new Map(t);return n.delete(e),n})},[]),C=(0,o.useCallback)(()=>{d(new Map)},[]),S=(0,o.useCallback)(e=>c.has(e),[c]),T=(0,o.useCallback)(()=>{m(0)},[]);return{isOpen:e,open:p,close:f,toggle:h,query:n,setQuery:g,clearQuery:x,activeCategory:a,setActiveCategory:v,clearCategory:k,recentItems:i,addToRecent:y,clearRecent:w,selectedItems:c,toggleSelect:j,selectItem:b,deselectItem:N,clearSelection:C,isSelected:S,activeIndex:u,setActiveIndex:m,resetActiveIndex:T}}(),rh=function(){let e=(0,u.T)("library"),[t,n]=(0,o.useState)(!1),[r,a]=(0,o.useState)(null),s=(0,o.useCallback)(async e=>{try{let t=await fetch("/api/prompts/".concat(e));if(!t.ok)return l.kg.error("Failed to fetch prompt ".concat(e)),null;let n=(await t.json()).data;return{id:(null==n?void 0:n.id)||e,name:(null==n?void 0:n.name)||"Unknown",content:(null==n?void 0:n.content)||"",shortcut:(null==n?void 0:n.shortcut)||""}}catch(t){return l.kg.error("Error fetching prompt ".concat(e,":"),t),null}},[]),i=(0,o.useCallback)(async e=>{try{let t=await fetch("/api/tools/".concat(e));if(!t.ok)return l.kg.error("Failed to fetch skill ".concat(e)),null;let n=(await t.json()).tool,r=[null==n?void 0:n.system_prompt,null==n?void 0:n.user_prompt].filter(
1Boolean).join("\n\n");return{id:(null==n?void 0:n.id)||e,name:(null==n?void 0:n.name)||"Unknown",instructions:r||"",shortcut:(null==n?void 0:n.shortcut)||""}}catch(t){return l.kg.error("Error fetching skill ".concat(e,":"),t),null}},[]),c=(0,o.useCallback)(async t=>{try{var n,r,a;let s=await fetch("/api/library/files/".concat(t));if(!s.ok)return l.kg.error("Failed to fetch file ".concat(t)),ns.toast.error(e("couldNotLoadFileContent")),null;let i=await s.json();return{id:(null===(n=i.file)||void 0===n?void 0:n.id)||t,name:(null===(r=i.file)||void 0===r?void 0:r.name)||"Unknown",content:(null===(a=i.file)||void 0===a?void 0:a.content)||"",type:"file"}}catch(n){return l.kg.error("Error fetching file ".concat(t,":"),n),ns.toast.error(e("couldNotLoadFileContent")),null}},[e]),d=(0,o.useCallback)(async e=>{try{var t,n,r;let a=await fetch("/api/context-packs/".concat(e));if(!a.ok)return l.kg.error("Failed to fetch pack ".concat(e)),null;let s=await a.json(),i=((null===(t=s.pack)||void 0===t?void 0:t.files)||[]).map(e=>"## ".concat(e.name,"\n\n").concat(e.content)).join("\n\n---\n\n");return{id:(null===(n=s.pack)||void 0===n?void 0:n.id)||e,name:(null===(r=s.pack)||void 0===r?void 0:r.name)||"Unknown",content:i,type:"pack"}}catch(t){return l.kg.error("Error fetching pack ".concat(e,":"),t),null}},[]);return{isLoading:t,error:r,execute:(0,o.useCallback)(async e=>{if(0===e.length)return null;n(!0),a(null);try{let t=[],n=[],r=[],a=e.map(async e=>{switch(e.type){case"prompt":{let n=await s(e.id);n&&t.push(n);break}case"skill":{let t=await i(e.id);t&&n.push(t);break}case"file":{let t=await c(e.id);t&&r.push(t);break}case"pack":{let t=await d(e.id);t&&r.push(t);break}case"research":try{let t=await fetch("/api/research/briefs/".concat(e.id));if(t.ok){var a,o,u,m;let n=await t.json();r.push({id:(null===(a=n.brief)||void 0===a?void 0:a.id)||e.id,name:(null===(o=n.brief)||void 0===o?void 0:o.name)||(null===(u=n.brief)||void 0===u?void 0:u.title)||"Research",content:(null===(m=n.brief)||void 0===m?void 0:m.content)||"",type:"file"})}}catch(t){l.kg.error("Error fetching research ".concat(e.id,":"),t)}break;case"semantic":e.chunkText&&r.push({id:e.id,name:"S\xf8keresultat: ".concat(e.name),content:e.chunkText,type:"file"});break;case"goal":case"priority":case"task":e.chunkText&&r.push({id:e.id,name:e.name,content:e.chunkText,type:e.type})}});return await Promise.all(a),{prompts:t,skills:n,contexts:r,commands:e}}catch(e){return l.kg.error("Error executing slash commands:",e),a("Kunne ikke hente kommando-innhold"),null}finally{n(!1)}},[s,i,c,d]),clearError:(0,o.useCallback)(()=>{a(null)},[])}}(),[rg,rx]=(0,o.useState)(null),rv=(0,o.useRef)(null),rk=(0,o.useRef)(null),ry=(0,o.useRef)(!1),rw=(0,o.useRef)(void 0),rj=(0,o.useRef)(()=>{}),rb=(0,o.useMemo)(()=>(0,s.t)(e=>rj.current(e)),[]),rN=(0,o.useRef)(!1),rC=(0,o.useRef)(!1),rS=(0,o.useRef)(null),rT=(0,o.useRef)(!1),rI=(0,o.useRef)(null),rE=(0,o.useRef)(null),r_=(0,o.useRef)(null),rA=(0,o.useRef)(null),rR=(0,o.useRef)(null),rP=(0,o.useRef)(null),rD=(0,o.useRef)(ta),rF=(0,o.useRef)(null),rO=(0,o.useRef)(!1),rU=(0,o.useRef)(new Map),rL=(0,o.useRef)(new Set),rM=(0,o.useRef)(null),rZ=(0,o.useRef)(null),rz=(0,o.useRef)(0),rK=(0,o.useRef)(0),rW=(0,o.useRef)(0),rq=(0,o.useRef)(null),rG=(0,o.useCallback)(function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rD.current;return{conversationId:e,generation:rW.current}},[]),rV=(0,o.useCallback)(function(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return e.generation===rW.current&&e.conversationId===rD.current&&(!t||e.conversationId===rZ.current)},[]),rH=(0,o.useCallback)(function(e,t,n){let r=!(arguments.length>3)||void 0===arguments[3]||arguments[3],a=setTimeout(()=>{rL.current.delete(a),rV(e,r)&&t()},n);return rL.current.add(a),a},[rV]);(0,o.useEffect)(()=>()=>{var e,t;for(let n of(rW.current+=1,null===(e=rq.current)||void 0===e||e.abort(),null===(t=r_.current)||void 0===t||t.abort(),rL.current))clearTimeout(n);rL.current.clear()},[]);let rJ=(0,o.useCallback)((e,t)=>{let r=rG(),a=null!==r.conversationId;(null==t?void 0:t.refreshWorkspace)&&(null==ex?void 0:ex.refreshWorkspaceData)&&ex.refreshWorkspaceData(),(null==t?void 0:t.toastMessage)&&Promise.resolve().then(n.bind(n,17787)).then(e=>{let{toast:n}=e;rV(r,a)&&n.success(t.toastMessage)}),rH(r,()=>{rj.current({content:e,silentKind:"runtime_continue"})},500,a)},[rG,rH,rV,ex]),rB=(0,o.useCallback)((e,t,r)=>{let a=rG(),s=null!==a.conversationId;if((null==r?void 0:r.refreshWorkspace)&&(null==ex?void 0:ex.refreshWorkspaceData)&&ex.refreshWorkspaceData(),(null==r?void 0:r.toastMessage)&&Promise.resolve().then(n.bind(n,17787)).then(e=>{let{toast:t}=e;rV(a,s)&&t.success(r.toastMessage)}),ex){var i;let n=t?JSON.stringify(t):"{}",r="[TOOL_COMPLETE:".concat(e,":").concat(n,"]");null===(i=ex.onChatActivity)||void 0===i||i.call(ex),rH(a,()=>{rj.current({content:r,silentKind:"tool_complete"})},500,s)}else(null==r?void 0:r.fallbackMessage)&&rJ(r.fallbackMessage)}
1,[rG,rH,rV,rJ,ex]),rX=(0,o.useRef)(null!==(t=null==ex?void 0:ex.fileUploadSignal)&&void 0!==t?t:0);(0,o.useEffect)(()=>{var e;let t=null!==(e=null==ex?void 0:ex.fileUploadSignal)&&void 0!==e?e:0;t>0&&t!==rX.current&&(rX.current=t,rB("files",{},{refreshWorkspace:!1}))},[null==ex?void 0:ex.fileUploadSignal,rB]);let rQ=(0,o.useRef)(null!==(h=null==ex?void 0:ex.voiceCompleteSignal)&&void 0!==h?h:0);(0,o.useEffect)(()=>{var e;let t=null!==(e=null==ex?void 0:ex.voiceCompleteSignal)&&void 0!==e?e:0;t>0&&t!==rQ.current&&(rQ.current=t,rB("voice",{},{refreshWorkspace:!1}))},[null==ex?void 0:ex.voiceCompleteSignal,rB]);let[rY,r$]=(0,o.useState)([]),[r0,r1]=(0,o.useState)([]),r3=(0,o.useRef)(new Set),[r2,r5]=(0,o.useState)(0),[r4,r7]=(0,o.useState)(null),r6=[K,...W].some(e=>e&&!r3.current.has(e)&&!r0.some(t=>(0,i.XI)(t,e))),r8=r0[0]||null,r9=(0,o.useCallback)(e=>{e?r1(t=>[e,...t.slice(1)]):r1(e=>e.slice(1))},[]),[ae,at]=(0,o.useState)({available:!0,reasonCode:null}),[an,ar]=(0,o.useState)([]),[aa,as]=(0,o.useState)(!1),[ai,al]=(0,o.useState)(!1),[ao,ac]=(0,o.useState)(!1),[ad,au]=(0,o.useState)(M||ed||null),[am,ap]=(0,o.useState)(null),[af,ah]=(0,o.useState)(!1),[ag,ax]=(0,o.useState)(!1),av=ae.available?void 0:eX("researchUnavailable"),ak=(0,o.useCallback)(e=>{let t=eV?"\n\n## Workspace Agent Mode\nDu kj\xf8rer i agent mode med MCP-verkt\xf8y. Bruk research_plan f\xf8rst, deretter company_lookup / website_crawl / linkedin_search / web_search / deep_research etter behov. For omfattende research skal du prioritere deep_research n\xe5r sp\xf8rsm\xe5let krever fler-kilde analyse. Ikke si at research eller web search er utilgjengelig med mindre et faktisk verkt\xf8ykall returnerer den feilen. Ikke fall tilbake til legacy agentic_research i workspace mode.":"";return{...e,instructions:"".concat(e.instructions).concat(t),_isResearchSkill:!0}},[eV]),ay=(0,o.useCallback)(async()=>{try{var e;let t=await fetch("/api/tools?name=Advanced Research"),n=await t.json(),r=null===(e=n.tools)||void 0===e?void 0:e.find(e=>"advanced-research"===e.id);r9(ak(r||{id:"advanced-research",name:"Advanced Research",instructions:'# Research Facilitator\n\nVIKTIG: Still et \xc5PENT oppf\xf8lgingssp\xf8rsm\xe5l F\xd8R du starter research!\n\n## Prosess:\n\n### Steg 1: STILL ET \xc5PENT SP\xd8RSM\xc5L\nN\xe5r bruker ber om research, still ETT \xe5pent sp\xf8rsm\xe5l:\n\n"Hva skal du bruke denne researchen til? Fortell meg litt om konteksten, s\xe5 kan jeg tilpasse s\xf8ket."\n\nEller:\n"Hva er det viktigste du trenger \xe5 finne ut om [selskap]?"\n\nIKKE gi ledende alternativer! La brukeren forklare med egne ord.\n\n### Steg 2: FORST\xc5 KONTEKSTEN\nLytt til brukerens svar. De kan si ting som:\n- "Jeg skal lage en tone of voice analyse, trenger artikler og LinkedIn-poster"\n- "Jeg vil bli kjent med selskapet - finanser, struktur, posisjonering"\n- "Jeg trenger bevis p\xe5 at de er markedsledende"\n- "Jeg skal pitche til dem, trenger \xe5 forst\xe5 deres utfordringer"\n\n### Steg 3: BEKREFT FORST\xc5ELSE (valgfritt)\nHvis n\xf8dvendig, oppsummer kort:\n"S\xe5 du trenger [X] for \xe5 [Y]. Skal jeg starte researchen?"\n\n### Steg 4: UTF\xd8R RESEARCH\nBruk de verkt\xf8yene du har tilgjengelig:\n\n**Workspace-modus (MCP tools):**\n- research_plan: Lag en strukturert plan f\xf8rst\n- company_lookup: Selskapsdata (BRREG + Proff)\n- website_crawl: Crawle nettsider for innhold\n- linkedin_search: LinkedIn-profiler og selskapssider\n- web_search: Generelt netts\xf8k via Parallel AI\n- deep_research: Dyp, multi-kilde research (4-30 min)\n- url_extract: Les innhold fra spesifikke URLer\n- research_synthesize: Synthetiser resultater til rapport\n\n**Document/Canvas-modus:**\n- Kall agentic_research med brukerens fulle kontekst i query.\n\n### Steg 5: PRESENTER RESULTATER\nPresenter KUN resultatene fra verkt\xf8yene. IKKE generer data selv.\n\n## ALDRI:\n- ❌ Start research uten \xe5 forst\xe5 konteksten f\xf8rst\n- ❌ Gi ledende multiple-choice sp\xf8rsm\xe5l\n- ❌ Generer selskapsdata uten tool (= hallusinering)',description:eX("advancedResearchDescription"),category:"research",owner_type:"system"}))}catch(e){l.kg.error("[UniversalAIChat] Failed to load Advanced Research skill:",e)}},[ak,r9,eX]);(0,o.useEffect)(()=>{let e=!1;return fetch("/api/ai/capabilities?mode=".concat(eV?"agent":"chat")).then(async e=>{if(!e.ok)throw Error("HTTP ".concat(e.status));return e.json()}).then(t=>{var n,r;e||at({available:(null==t?void 0:null===(n=t.advancedResearch)||void 0===n?void 0:n.available)!==!1,reasonCode:(null==t?void 0:null===(r=t.advancedResearch)||void 0===r?void 0:r.reasonCode)||null})}).catch(e=>{l.kg.warn("[UniversalAIChat] Failed to load AI capabilities, keeping research enabled",{error:e instanceof Error?e.message:String(e)})}),()=>{e=!0}},[eV]),(0,o.useEffect)(()=>{let e=new Set;for(let t of(K&&e.add(K),W.forEach(t=>e.add(t)),r3.current))e.has(t)||r3.current.delete(t);if(0===e.size)return;let t=Array.from(e).filter(e=>!r0.some(t=>(0,i.XI)(t,e))&&!r3.current.has(e));if(0===t.length)return;let n=rG(),r=new AbortController,a=!1,s=null;return fetch("/api/tools",{signal:r.signal}).then(async e=>{if(s=e.status,!e.ok)throw Error("HTTP ".concat(e.status));return e.json()}).then(e=>{if(a||!rV(n,!1))return;if(!Array.isArray(null==e?void 0:e.tools))throw Error("Invalid skills response");let r=new Map(e.tools.map(e=>[e.id,e])),s=[],i=[];for(let e of t){var l;let t=null!==(l=r.get(e))&&void 0!==l?l:r.get("tool-".concat(e));t?s.push({...t,instructions:t.instructions||""}):i.push(e)}r7(i.length>0?eX("initialSkillUnavailableDetails",{ids:i.join(", ")}):null),t3(e=>i.length>0?eX("initialSkillLoadFailed"):e===eX("initialSkillLoadFailed")?null:e),s.length>0&&r1(e=>{let t=[...e];for(let e of s)t.some(t=>
1t.id===e.id)||t.push(e);return t.length===e.length?e:t})}).catch(e=>{!a&&rV(n,!1)&&(l.kg.error("[UniversalAIChat] Failed to load initial skills:",e),r7(eX(null===s?"initialSkillNetworkDetails":s>=200&&s<300?"initialSkillInvalidResponseDetails":"initialSkillHttpDetails",{ids:t.join(", "),status:null!=s?s:0})),t3(eX("initialSkillLoadFailed")))}),()=>{a=!0,r.abort()}},[K,W.join(","),r0,ta,r2]),(0,o.useEffect)(()=>{0===ee.length||an.length>0||fetch("/api/tools").then(e=>e.ok?e.json():null).then(e=>{if(!(null==e?void 0:e.tools))return;let t=new Set(ee),n=e.tools.filter(e=>{var n;return t.has(e.id)&&(null===(n=e.category)||void 0===n?void 0:n.startsWith("filter-"))}).map(e=>({id:e.id,name:e.name,instructions:e.instructions||"",category:e.category}));n.length>0&&ar(n)}).catch(e=>console.error("[UniversalAIChat] Failed to load initial filters:",e))},[ee.join(","),an.length]);let[aw,aj]=(0,o.useState)(!1),[ab,aN]=(0,o.useState)(""),aC=(0,o.useRef)(null),aS=(0,o.useRef)(null),aT=(0,o.useCallback)(e=>{rj.current({content:"godkjent, kj\xf8r planen (plan: ".concat(e,")")})},[]),aI=(0,o.useCallback)(()=>{var e;null===(e=aS.current)||void 0===e||e.focus()},[]),aE=(0,o.useRef)((null==et?void 0:et.content)||""),a_=!!et&&!!en,{pendingPatches:aA,hasPendingPatches:aR,activePatchIndex:aP,processEditResponse:aD,applyPatch:aF,rejectPatch:aO,applyAll:aU,rejectAll:aL,canUndo:aM,undo:aZ,undoTimeRemaining:az,navigateToPatch:aK,scrollToSection:aW}=(0,nP.b)({documentContent:(null==et?void 0:et.content)||"",onApply:e=>null==en?void 0:en(e),enabled:er});(0,o.useEffect)(()=>{(null==et?void 0:et.content)&&(aE.current=et.content)},[null==et?void 0:et.content]),(0,o.useEffect)(()=>{let e=null==et?void 0:et.id;if(!e)return;let t=rG(),n=new AbortController,r=!1,a=()=>!r&&rV(t,!1);if("new"===e||e.startsWith("new-")){l.kg.log("[UniversalAIChat] Skipping conversation load for new document:",e);return}if(ta){l.kg.log("[UniversalAIChat] Skipping document conversation load - already have conversation:",ta);return}return async function(){try{let t=await fetch("/api/ai/conversations?document_id=".concat(e),{signal:n.signal});if(!a())return;if(t.ok){let e=await t.json();if(!a())return;e.conversation&&ti(e.conversation.id)}}catch(e){if(n.signal.aborted||!a())return;l.kg.error("Failed to load document conversation:",e)}}(),()=>{r=!0,n.abort()}},[null==et?void 0:et.id]);let aq=(0,o.useRef)(null),aG=(0,o.useRef)(null),aV=(0,c.useSearchParams)(),aH=(0,o.useCallback)((e,t,a)=>{var s,i;let l=function(e){let{message:t,onOpen:n,onApproveResearchPlan:a,onAdjustResearchPlan:s}=e;if("assistant"!==t.role)return[];let i=[],l=(0,e4.DW)(t.content);return l.length>0&&i.push((0,r.jsx)(tt,{references:l,onOpen:n},"".concat(t.id,"-agent-resources"))),i.push((0,r.jsx)(tn,{content:t.content,onApprove:a,onAdjust:s},"".concat(t.id,"-research-plan"))),i}({message:e,onOpen:I,onApproveResearchPlan:aT,onAdjustResearchPlan:aI});if(l.push(...function(e){let{workflowContext:t,messageContent:n}=e;if(!t)return[];let a={...e,workflowContext:t},s=[],i=!t.runtimeControlEnabled;return i&&n.includes("<!--WIDGET:files-->")&&s.push((0,r.jsx)(tY,{...a},"".concat(e.messageId,"-files"))),i&&n.includes("<!--WIDGET:voice-->")&&s.push((0,r.jsx)(t$,{...a},"".concat(e.messageId,"-voice"))),n.includes("<!--WIDGET:evaluation-->")&&s.push((0,r.jsx)(t0,{...a},"".concat(e.messageId,"-evaluation"))),s}({messageId:e.id,messageContent:e.content,workflowContext:ex,currentProjectId:e9,setContextFiles:tR,sendToolCompleteSignal:rB,t:eX})),!a||tc)return l.length>0?(0,r.jsx)("div",{className:"space-y-2 mt-3",children:l}):null;let{actions:o}=function(e){let t;let n=[],r=e,a=/\[ACTION:BUTTONS:(\[.+?\])\]/g;for(;null!==(t=a.exec(e));){let[e,a]=t;r=r.replace(e,"").trim();try{let e=JSON.parse(a);Array.isArray(e)&&n.push({type:"BUTTONS",choices:e})}catch(e){console.error("Failed to parse button choices:",e)}}let s=/\[MARKER:(\w+):(\w+)\]/g;for(;null!==(t=s.exec(e));){let[e,a,s]=t;r=r.replace(e,"").trim(),"WORK_SESSION"===a&&"START"===s&&n.push({type:"MARKER",marker:"WORK_SESSION_START"})}let i=/\[ACTION:(\w+)(?::([^\]]+))?\]/g;for(;null!==(t=i.exec(e));){let[e,a,s]=t;switch(r=r.replace(e,"").trim(),a){case"VIDEO":n.push({type:"VIDEO",videoId:s,autoplay:!0});break;case"FILES":n.push({type:"FILES",mode:s});break;case"INTERVIEW":n.push({type:"INTERVIEW",mode:s});break;case"INTERVIEW_SCRIPT":if(null==s?void 0:s.startsWith("START:")){let e=s.substring(6);e&&n.push({type:"INTERVIEW_SCRIPT",mode:"START",scriptId:e})}break;case"TEXT_PASTE":n.push({type:"TEXT_PASTE",mode:"START"});break;case"VOICE_RECORD":n.push({type:"VOICE_RECORD",mode:"START"});break;case"VIDEO_CAPTURE":n.push({type:"VIDEO_CAPTURE",mode:"START"});break;case"AUDIO_CAPTURE":n.push({type:"AUDIO_CAPTURE",mode:"START"});break;case"PDF_CAPTURE":n.push({type:"PDF_CAPTURE",mode:"START"});break;case"DOCUMENT_CAPTURE":n.push({type:"DOCUMENT_CAPTURE",mode:"START"});break;case"FILE_ANALYZE":n.push({type:"FILE_ANALYZE",mode:"START"});break;case"RESEARCH":n.push({type:"RESEARCH",mode:s});break;case"ANALYZE_DOCUMENTS":n.push({type:"ANALYZE_DOCUMENTS",mode:s});break;case"PROGRESS":if(s){let e=s.split(":"),t=e[0],r=e[1]?parseInt(e[1],10):void 0;n.push({type:"PROGRESS",kapittel:t,trinn:isNaN(r)?void 0:r})}break;case"JOURNAL":if(s){let e=s.indexOf(":");if(e>0){let t=s.substring(0,e),r=s.substring(e+1);r&&["decision","insight","completed","note"].includes(t)&&n.push({type:"JOURNAL",entryType:t,content:r})}}break;case"LAYOUT":n.push({type:"LAYOUT",layout:s});break;case"PHASE":n.push({type:"PHASE",phase:s});break;case"GENERATE_V0":n.push({type:"GENERATE_V0"});break;case"EVALUATE":{let t=s||"RUN",r={type:"EVALUATE",mode:t};if("RESULT"===t&&e&&e.includes(":RESULT:")){let t=e.indexOf(":RESULT:")+8,n=e.lastIndexOf("]");n>t&&(r.data=e.slice(t,n))}n.push(r);break}case"SAVE":n.push({type:"SAVE"});break;case"COMPLETE":n.push({type:"COMPLETE"});break;case"GENERATE":case"GENERATE_FINAL":{if(!s||!s.startsWith("START:")){console.error("Invalid GENERATE/GENERATE_FINAL action: missing START:",e);break}let t=s.substring(6),r={md:"markdown",json:"json",csv:"csv",pdf:"pdf",docx:"docx"};if(t.includes(",")){let e=t.split(",").map(e=>e.trim()).filter(e=>e.length>0).map(e=>{let t=e.match(/\.(\w+)(?::format=(\w+))?$/),n=(null==t?void 0:t[1])||"md",a=null==t?void 0:t[2],s=a?r[a]||"markdown":r[n]||"markdown",i=e.split(":")[0];return i?{fileName:i,fileType:s}:null}).filter(e=>null!==e);n.push({type:"GENERATE_FINAL",mode:"START",files:e})}else{var l;let e=t.match(/:format=(\w+)$/),a=null==e?void 0:e[1],s=t.split(":")[0];if(!s){console.error("Invalid GENERATE_FINAL action: no filename provided");break}let i=(null===(l=s.split(".").pop())||void 0===l?void 0:l.toLowerCase())||"md",o=a?r[a]||"markdown":r[i]||"markdown";n.push({type:"GENERATE_FINAL",mode:"START",fileName:s,fileType:o})}}}}return{cleanMessage:r,actions:n}}(e.content);if(l.push(...function(e){let{actions:t,workflowContext:n}=e,a=e=>t.some(t=>t.type===e),s=[];return a("TEXT_PASTE")&&s.push((0,r.jsx)(t5,{...e},"ai-text-paste")),a("VOICE_RECORD")&&s.push((0,r.jsx)(t4,{...e},"ai-voice-record")),a("VIDEO_CAPTURE")&&s.push((0,r.jsx)(t7,{...e},"ai-video-capture")),a("AUDIO_CAPTURE")&&s.push((0,r.jsx)(t6,{...e},"ai-audio-capture")),a("PDF_CAPTURE")&&s.push((0,r.jsx)(t8,{...e},"ai-pdf-capture")),a("DOCUMENT_CAPTURE")&&s.push((0,r.jsx)(t9,{...e},"ai-document-capture")),!n&&a("INTERVIEW")&&s.push((0,r.jsx)(ne,{...e},"ai-interview")),!n&&a("FILES")&&s.push((0,r.jsx)(nt,{...e},"ai-files")),a("RESEARCH")&&s.push((0,r.jsx)(nn,{...e},"ai-research")),a("EVALUATE")&&(null==n?void 0:n.instanceId)&&s.push((0,r.jsx)(nr,{...e},"ai-evaluate")),s}({actions:o,workflowContext:ex,workspaceContext:ev,onFileUploaded:eT,currentProjectId:e9,setContextFiles:tR,sendToolCompleteSignal:rB,t:eX})),o.some(e=>"SAVE"===e.type)&&ex&&(null===(s=ex.onNavigateToTab)||void 0===s||s.call(ex,"canvas"),Promise.resolve().then(n.bind(n,17787)).then(e=>{let{toast:t}=e;t.success(eX("alreadySavedToCoreContext"),{description:eX("alreadySavedToCoreContextDescription")})}
1)),o.some(e=>"COMPLETE"===e.type)&&ex&&(null===(i=ex.onNavigateToTab)||void 0===i||i.call(ex,"canvas"),Promise.resolve().then(n.bind(n,17787)).then(e=>{let{toast:t}=e;t.success(eX("worksessionCompleted"))})),ex||l.push(...tJ({widgets:rY,onDismiss:e=>r$(t=>t.filter(t=>t.id!==e)),currentProjectId:e9,workflowContext:ex,setInput:np,setContextFiles:tR,sendToolCompleteSignal:rB,t:eX})),ey){let t=function(e){let t;if(!e)return[];let n=[],r=/\[FORM_SUGGESTION\]([\s\S]*?)\[\s*\/\s*FORM_SUGGESTION\s*\]/gi;for(;t=r.exec(e);){let e=(t[1]||"").trim();if(e)try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))continue;for(let[e,r]of Object.entries(t)){if(null==r)continue;let t="string"==typeof r?r:JSON.stringify(r);n.push({field:e,value:t})}}catch(e){}}return n}(e.content);t.length>0&&l.push((0,r.jsx)(tU,{suggestions:t,onApply:ey},"form-suggestions"))}return 0===l.length?null:(0,r.jsx)("div",{className:"space-y-2 mt-3",children:l})},[tc,rY,e9,tR,r$,np,ek,ey,I,aI,aT,ex,rB,eX]),aJ=(0,o.useCallback)(()=>{let e=[];return(rY.length>0&&!tc&&e.push(...tJ({widgets:rY,onDismiss:e=>r$(t=>t.filter(t=>t.id!==e)),currentProjectId:e9,workflowContext:ex,setInput:np,setContextFiles:tR,sendToolCompleteSignal:rB,t:eX})),0===e.length)?null:(0,r.jsx)("div",{className:"space-y-2 mt-3",children:e})},[rY,tl,tc,e9,tR,r$,np,ex,rB,rJ,eX]),aB=(0,o.useMemo)(()=>F&&F.length>0?function(e,t){let n=[],r=new Map,a=[],s=e.map(e=>({id:e.id,at:e.createdAt.getTime()})).filter(e=>Number.isFinite(e.at));for(let e of t.map((e,t)=>({item:e,index:t,at:e0(e.at)})).sort((e,t)=>null===e.at&&null===t.at?e.index-t.index:null===e.at?1:null===t.at?-1:e.at-t.at||e.index-t.index).map(e=>e.item)){let t=e0(e.at);if(null===t||0===s.length){a.push(e);continue}let l=null;for(let e of s)if(e.at<=t)l=e.id;else break;if(null===l)n.push(e);else if(l===s[s.length-1].id)a.push(e);else{var i;let t=null!==(i=r.get(l))&&void 0!==i?i:[];t.push(e),r.set(l,t)}}return{beforeFirst:n,afterMessage:r,atEnd:a}}(tl,F):null,[tl,F]),aX=(0,o.useCallback)((e,t,n)=>{var a;let s=aH(e,t,n),i=null!==(a=null==aB?void 0:aB.afterMessage.get(e.id))&&void 0!==a?a:[];return 0===i.length?s:(0,r.jsxs)(r.Fragment,{children:[s,i.map(e=>(0,r.jsx)("div",{"data-timeline-item":e.id,children:e.node},e.id))]})},[aH,aB]),aQ=(0,o.useCallback)(()=>{var e;let t=null!==(e=null==aB?void 0:aB.beforeFirst)&&void 0!==e?e:[];return 0===t.length?null:(0,r.jsx)(r.Fragment,{children:t.map(e=>(0,r.jsx)("div",{"data-timeline-item":e.id,children:e.node},e.id))})},[aB]),aY=(0,o.useCallback)(()=>{var e;let t=null!==(e=null==aB?void 0:aB.atEnd)&&void 0!==e?e:[],n=aJ(),s=ta?(0,r.jsx)(a.r,{conversationId:ta,onResume:rb}):null;return 0!==t.length||s?(0,r.jsxs)(r.Fragment,{children:[t.map(e=>(0,r.jsx)("div",{"data-timeline-item":e.id,children:e.node},e.id)),n,s]}):n},[aJ,aB,ta,rb]);(0,o.useEffect)(()=>{let e=null==aV?void 0:aV.get("prompt");if(e){np(decodeURIComponent(e));let t=new URL(window.location.href);t.searchParams.delete("prompt"),window.history.replaceState({},"",t.toString())}},[aV]),(0,o.useEffect)(()=>{ea&&ea.selectedText&&ea.instruction&&(np('Jeg har valgt f\xf8lgende tekst:\n\n"'.concat(ea.selectedText,'"\n\n').concat(ea.instruction)),null==es||es())},[ea,es]),(0,o.useEffect)(()=>{if(!eA){ry.current=!1,rw.current=void 0;return}if(void 0===rw.current&&(rw.current=ta),rw.current!==ta)return;let e=!ta||th.conversationId===ta&&"loaded"===th.status&&rZ.current===ta&&!t1;if(!ry.current&&e&&!tc&&!tp){eA.context&&eA.context.length>0&&tR(e=>{let t=new Set(e.map(e=>e.id));return[...e,...eA.context.filter(e=>!t.has(e.id))]});let e=rG(),t=rH(e,()=>{ry.current||(ry.current=!0,rj.current({content:eA.message,...!1!==eA.silent&&{silentKind:"auto_prompt"}}),null==eR||eR())},100,null!==e.conversationId);return()=>{clearTimeout(t),rL.current.delete(t)}}},[eA,rG,ta,th,t1,tp,tc,eR,rH]);let a$=(0,o.useRef)(!1),[a0,a1]=(0,o.useState)(!1),[a3,a2]=(0,o.useState)(0);(0,o.useEffect)(()=>{void 0!==ed&&au(ed)},[ed]),(0,o.useEffect)(()=>{Z&&!ag&&(r3.current.clear(),ax(!0),au(null!=M?M:null),ti(null),to([]),nW(e1),nG(!1),tR([]),tz([]),tQ([]),r1([]),ar([]),n6([]))},[Z,M,ag,e1]),(0,o.useEffect)(()=>
1{if(!ad){ap(null);return}let e=rG(),t=new AbortController,n=!1,r=()=>!n&&!t.signal.aborted&&ad==ad&&rV(e,!1);return async function(){ah(!0);try{let e=await fetch("/api/production/folders/".concat(ad,"/inherited-context"),{signal:t.signal});if(e.ok&&r()){let t=await e.json();if(!r())return;ap(t),t.effective_model&&ty===nm.Q6&&tw(t.effective_model),l.kg.log("[UniversalAIChat] Loaded folder context:",{folder:t.folder.name,files:t.total_unique_files,hasInstructions:!!t.effective_instructions,model:t.effective_model})}}catch(e){if(!r())return;l.kg.error("[UniversalAIChat] Failed to load folder context:",e),ap(null)}finally{r()&&ah(!1)}}(),()=>{n=!0,t.abort()}},[ad]);let{loadedConversationRef:a5,contextJustLoadedRef:a4}=function(e){let{currentConversationId:t,loadConversation:n,newConversationTitle:r,justCreatedConversationRef:a,setConversationHistoryLoad:s,setMessages:i,setConversationTitle:c,setHasSummary:d}=e,u=(0,o.useRef)(null),m=(0,o.useRef)(!1);return(0,o.useEffect)(()=>{if(!t)return;let e=e=>{let r=e.detail;(null==r?void 0:r.conversation_id)===t&&(u.current=t,n(t))};return window.addEventListener(nI,e),()=>window.removeEventListener(nI,e)},[t,n]),(0,o.useEffect)(()=>{if(t){if(a.current===t||u.current===t){s({conversationId:t,status:"loaded"}),l.kg.log("[UniversalAIChat] Skipping load - already have conversation:",t);return}u.current=t,n(t)}else u.current=null,a.current=null,s({conversationId:null,status:"not-started"}),i([]),c(r),d(!1)},[t,n,r]),{loadedConversationRef:u,contextJustLoadedRef:m}}({currentConversationId:ta,loadConversation:(0,o.useCallback)(e=>nf({t:eX,currentProjectId:e9,onTitleChange:B,conversationLoadGenerationRef:rW,conversationLoadAbortRef:rq,activeConversationIdRef:rD,autoInitiateEmptyConversationRef:rI,autoInitiateQueuedMessageIdRef:rS,autoInitiateQueueRetryBlockedRef:rT,pendingConfirmationRef:rk,autoInitiateTriggeredRef:a$,messageQueueRef:nM,queueRevisionRef:rz,draftRevisionRef:rK,conversationDataOwnerRef:rZ,queueDispatchInFlightRef:rO,contextJustLoadedRef:a4,setConversationHistoryLoad:tx,setIsLoading:tf,setError:t3,setMessages:to,setModel:tw,setConversationTitle:nW,setHasSummary:nG,setIsAutoInitiating:a1,setMessageQueue:nL,setInput:np,setContextFiles:tR,setAttachments:tz,setPinnedGoals:n6,setSelectedPacks:tQ,setSelectedSkills:r1,setSelectedFilters:ar,setCurrentProjectId:te},e),[e9,B,eX]),newConversationTitle:e1,justCreatedConversationRef:aG,setConversationHistoryLoad:tx,setMessages:to,setConversationTitle:nW,setHasSummary:nG});(0,o.useEffect)(()=>{null==J||J(ta)},[ta,J]),(0,o.useEffect)(()=>{rD.current=ta},[ta]);let a7=(0,o.useCallback)(e=>{tz(t=>{let n=t.find(t=>t.id===e);return n?(tR(e=>[...e,n]),t.filter(t=>t.id!==e)):t})},[]),a6=(0,o.useCallback)(e=>{tz(t=>t.filter(t=>t.id!==e))},[]);(0,o.useEffect)(()=>(eG&&(eG.current={switchConversation:e=>{rD.current!==e&&(a5.current=null,aG.current=null,null===e&&r3.current.clear(),ti(e),td(!1),tm(void 0),to([]),tR([]),tz([]),tQ([]),r1([]),ar([]),n6([]))},refreshSidebar:()=>{var e;null===(e=aq.current)||void 0===e||e.call(aq)},promoteAttachment:a7,removeAttachment:a6,toggleSidebar:()=>e8(e=>!e),getSidebarOpen:()=>e6,resumeConnection:rb,sendMessage:(e,t)=>{rj.current({content:e,...(null==t?void 0:t.silent)===!0&&{silentKind:"auto_prompt"}})}}),()=>{eG&&(eG.current=null)}),[eG,rb]),(0,o.useEffect)(()=>{null==X||X(r0.map(e=>({id:e.id,name:e.name})))},[r0,X]),(0,o.useEffect)(()=>{null==E||E((0,nh.G)(tl))},[tl,E]),(0,o.useEffect)(()=>{null==Q||Q(an.map(e=>({id:e.id,name:e.name,category:e.category})))},[an,Q]),(0,o.useEffect)(()=>{null==Y||Y(tX.map(e=>({id:e.id,name:e.name})))},[tX,Y]),(0,o.useEffect)(()=>{if(!ta||tp)return;if(0===tX.length&&0===n7.length){if(a5.current!==ta)return;if(a4.current){a4.current=!1;return}}let e=setTimeout(async()=>{try{let e=tX.map(e=>e.id);await fetch("/api/ai/conversations/".concat(ta),{method:"PUT",headers:nO(),body:JSON.stringify({context_pack_ids:e,context_goals:n7})})}catch(e){l.kg.error("[UniversalAIChat] Failed to save context packs/goals:",e)}},1e3);return()=>clearTimeout(e)},[tX,n7,ta,tp]),(0,o.useEffect)(()=>{if(!ta||tp||a5.current!==ta&&0===tZ.length)return;null==eI||eI(tZ);let e=setTimeout(async()=>{try{let e=tZ.map(e=>({id:e.id,name:e.name,type:e.type,content:e.content}));await fetch("/api/ai/conversations/".concat(ta),{method:"PUT",headers:nO(),body:JSON.stringify({attachments:e})})}catch(e){l.kg.error("[UniversalAIChat] Failed to save attachments:",e)}},1e3);return()=>clearTimeout(e)},[tZ,ta,tp,eI]),(0,o.useEffect)(()=>
1{if(!ta||tp||a5.current!==ta&&0===r0.length)return;let e=setTimeout(async()=>{try{let e=r0.map(e=>e.id);await fetch("/api/ai/conversations/".concat(ta),{method:"PUT",headers:nO(),body:JSON.stringify({active_skill_ids:e})})}catch(e){l.kg.error("[UniversalAIChat] Failed to save active skills:",e)}},1e3);return()=>clearTimeout(e)},[r0,ta,tp]),(0,o.useEffect)(()=>{if(!ta||tp||a5.current!==ta&&0===an.length)return;let e=setTimeout(async()=>{try{let e=an.map(e=>e.id);await fetch("/api/ai/conversations/".concat(ta),{method:"PUT",headers:nO(),body:JSON.stringify({active_filter_ids:e})})}catch(e){l.kg.error("[UniversalAIChat] Failed to save active filters:",e)}},1e3);return()=>clearTimeout(e)},[an,ta,tp]);let a8=async()=>{try{var e,t,n,r;if(null==eh?void 0:eh.boardId){let n=await fetch("/api/ai/conversations?board_id=".concat(encodeURIComponent(eh.boardId),"&source=board"));if(n.ok){let r=await n.json(),a=null===(t=r.conversations)||void 0===t?void 0:null===(e=t[0])||void 0===e?void 0:e.id;if("string"==typeof a)return a}}if(null==eg?void 0:eg.presentationId){let e=await fetch("/api/ai/conversations?presentation_id=".concat(encodeURIComponent(eg.presentationId),"&source=presentation"));if(e.ok){let t=await e.json(),a=null===(r=t.conversations)||void 0===r?void 0:null===(n=r[0])||void 0===n?void 0:n.id;if("string"==typeof a)return a}}let a=null==et?void 0:et.id,s=!a||"new"===a||a.startsWith("new-"),i=ex?{document_id:s?null:a,model:ty,source:e2,workflow_instance_id:ex.instanceId}:{ai_project_id:e9,folder_id:ad,document_id:s?null:a,model:ty,source:e2,workspace_id:(null==ev?void 0:ev.workspaceId)||null,board_id:(null==eh?void 0:eh.boardId)||null,presentation_id:(null==eg?void 0:eg.presentationId)||null,...tX.length>0&&{context_pack_ids:tX.map(e=>e.id)},...r0.length>0&&{active_skill_ids:r0.map(e=>e.id)},...an.length>0&&{active_filter_ids:an.map(e=>e.id)}},o=await fetch("/api/ai/conversations",{method:"POST",headers:nO(),body:JSON.stringify(i)});if(o.ok)return(await o.json()).conversation.id;{let e=await o.json().catch(()=>({}));l.kg.error("Failed to create conversation:",o.status,e)}}catch(e){l.kg.error("Failed to create conversation:",e)}return null},a9=(0,o.useCallback)(async()=>{let e=rW.current,t=()=>e===rW.current&&rD.current===ta;if(ta){let e="/api/ai/conversations/".concat(encodeURIComponent(ta)),c=Date.now()+eH,d=async e=>{let t=Math.max(0,c-Date.now());if(0===t)throw Error("Conversation settlement timed out");let n=null;try{return await Promise.race([Promise.resolve(e),new Promise((e,r)=>{n=setTimeout(()=>r(Error("Conversation settlement timed out")),t)})])}finally{n&&clearTimeout(n)}};try{var n,r,a,s,i,o;t3(null),nz(!0);let l=await d(fetch(e,{headers:(0,p.p)()}));if(!l.ok)throw Error("Conversation status failed: HTTP ".concat(l.status));let c=await d(l.json());if(!t())return;let u=null===(n=c.conversation)||void 0===n?void 0:n.agent_status;if("string"!=typeof u)throw Error("Conversation status is missing");if("in_doubt"===u){nz(!0),t3(eX("mutationInDoubt"));return}if("working"===u||"aborting"===u){nz(!0);let n=await d(fetch(e,{method:"PATCH",headers:nO(),body:JSON.stringify({agent_control:"stop_current"})}));if(!n.ok)throw Error("Stop failed: HTTP ".concat(n.status));let l=await d(n.json().catch(()=>null));if((null==l?void 0:null===(r=l.conversation)||void 0===r?void 0:r.agent_status)==="in_doubt"){t3(eX("mutationInDoubt"));return}if(((null==l?void 0:null===(a=l.conversation)||void 0===a?void 0:a.agent_status)==="working"||(null==l?void 0:null===(s=l.conversation)||void 0===s?void 0:s.agent_status)==="aborting")&&(null==l?void 0:l.pending)!==!0&&(null==l?void 0:l.stopped)!==!0)throw Error("Authoritative turn changed before Stop was accepted");for(null===(i=r_.current)||void 0===i||i.abort();t();){let t=await d(fetch(e,{headers:(0,p.p)()}));if(!t.ok)throw Error("Conversation settlement failed: HTTP ".concat(t.status));let n=await d(t.json());if(u=null===(o=n.conversation)||void 0===o?void 0:o.agent_status,"in_doubt"===u){t3(eX("mutationInDoubt"));return}if("working"!==u&&"aborting"!==u)break;await d(new Promise(e=>setTimeout(e,400)))}if(!t())return}let m=await d(fetch(e,{method:"PUT",headers:nO(),body:JSON.stringify({is_archived:!0})}));if(!m.ok)throw Error("Archive failed: HTTP ".concat(m.status))}catch(e){l.kg.error("Failed to settle and archive conversation:",e),t()&&t3(eX("clearConversationFailed"));return}}ti(null),to([]),nW((null==et?void 0:et.name)||e1),nz(!1),null==J||J(null)},[eH,ta,null==et?void 0:et.name,e1,J,eX]),se=(0,o.useCallback)(async(e,t,n,r)=>{let a=new TextDecoder,s="",i=!1,o=!1,c=!1,d=-1;tM([]);let u=(0,nE.qf)({getWorkspaceId:()=>null==ev?void 0:ev.workspaceId,onSkillDraft:V,onContextFileTruncations:tM});for(;;){let{done:m,value:p}=await e.read();if(m)break;if(!r())continue;let f=u.consume(a.decode(p,{stream:!0})),h=nx(s+=f);nv(h,{conversationId:n,assistantMessageId:t,stillOwnsConversation:r,setConversationTitle:nW,onTitleChange:B,sidebarRefreshRef:aq,setMessages:to,readOnlyTools:G,setPlanMode:ac}),s=h.content,!o&&!i&&s.match(/\[SUGGESTION\]/i)&&(o=!0,l.kg.log("[UniversalAIChat] \uD83D\uDCDD Track Changes mode detected - [SUGGESTION] block found"));let g=s.match(/\[DOCUMENT_EDIT\]/i);if(!c&&g&&(c=!0,i=!0,d=g.index+g[0].length),i){let e=s.substring(d).match(/\[DOCUMENT_EDIT\]|\[\/DOCUMENT_EDIT\]/i),n=e?d+e.index:-1;if(-1!==n){let e=s.substring(d,n).trim();if(e){let n=(0,nR.W9)(e);if(l.kg.log("[UniversalAIChat] \uD83D\uDCDD Edit detected:",{format:n,contentLength:e.length,hasOnDocumentEdit:!!en,previewMode:er}),"patch"===n){let n=(0,nR.md)(e);if(n&&n.length>0){if(er)aD(e),to(e=>e.map(e=>e.id===t?{...e,content:1===n.length?eX("documentEditPatchProposedOne"):eX("documentEditPatchProposedMany",{count:n.length})}:e));else if(en){let e=(0,nR.QE)(aE.current,n);l.kg.log("[UniversalAIChat] \uD83D\uDD27 Applying patches:",{patchCount:n.length,originalLength:aE.current.length,updatedLength:e.length,changed:e!==aE.current}),en(e),to(e=>e.map(e=>e.id===t?{...e,content:1===n.length?eX("documentEditPatchAppliedOne"):eX("documentEditPatchAppliedMany",{count:n.length})}:e))}}else l.kg.warn("[UniversalAIChat] ⚠️ PATCH format detected but no patches parsed")}else if("full"===n||"unknown"===n){let r=(0,nR.oz)(e)||e.replace(/\[FULL\]/gi,"").trim();l.kg.log("[UniversalAIChat] \uD83D\uDCC4 Full/Unknown format:",{format:n,fullContentLength:r.length,originalLength:aE.current.length}),er?(aD(e),to(e=>e.map(e=>e.id===t?{...e,content:eX("documentEditChangesProposed")}:e))):en&&(l.kg.log("[UniversalAIChat] ✅ Calling onDocumentEdit with content length:",r.length),en(r),to(e=>e.map(e=>e.id===t?{...e,content:eX("documentEditChangesApplied")}:e)))}}else l.kg.warn("[UniversalAIChat] ⚠️ Edit markers found but content is empty");return}{let e=s.substring(d).trim();if("patch"===(0,nR.W9)(e)){let n=(e.match(/\[PATCH\]/g)||[]).length/2;to(e=>e.map(e=>e.id===t?{...e,content:n>0?eX("documentEditFindingChangesCount",{count:Math.floor(n)}):eX("documentEditAnalyzing")}:e))}else to(n=>n.map(n=>
1n.id===t?{...n,content:eX("documentEditEditingCount",{count:e.length})}:n))}}else if(o){let e=s.match(/\[\/SUGGESTION\]/gi),n=(null==e?void 0:e.length)||0;to(e=>e.map(e=>e.id===t?{...e,content:n>0?1===n?eX("documentEditSuggestionProgressOne"):eX("documentEditSuggestionProgressMany",{count:n}):eX("documentEditAnalyzing")}:e))}else to(e=>e.map(e=>e.id===t?{...e,content:s}:e))}if(!r())return s;if(u.finish(),o&&en){let e=s.match(/\[SUGGESTION\][\s\S]*?\[\/SUGGESTION\]/gi);if(e&&e.length>0){l.kg.log("[UniversalAIChat] Track Changes - applying suggestions:",{suggestionCount:e.length}),en(e.join("\n"));let n=s.replace(/\[SUGGESTION\][\s\S]*?\[\/SUGGESTION\]/gi,"").trim();to(r=>r.map(r=>r.id===t?{...r,content:n||(1===e.length?eX("documentEditSuggestionFallbackOne"):eX("documentEditSuggestionFallbackMany",{count:e.length}))}:r))}}return s},[en,er,eX,V,null==ev?void 0:ev.workspaceId,G]),st=(0,o.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ta;if(!t)return null;let n=rW.current;try{let a=await fetch("/api/ai/conversations/".concat(t),{method:"PATCH",headers:nO(),body:JSON.stringify({message_queue_operation:e})});if(!a.ok)throw Error("Queue persistence failed: HTTP ".concat(a.status));let s=await a.json(),i=null==s?void 0:s.conversation;if(!Array.isArray(null==i?void 0:i.message_queue))throw Error("Queue persistence returned no authoritative queue");let l=Number(i.message_queue_revision);if(!Number.isSafeInteger(l)||l<0)throw Error("Queue persistence returned no authoritative revision");let o=!1;if(rW.current===n&&rD.current===t&&rZ.current===t){var r;r=rz.current,Number.isSafeInteger(l)&&l>r&&(rz.current=l,nM.current=i.message_queue,nL(i.message_queue),o=!0)}return{queue:i.message_queue,revision:l,applied:o}}catch(e){return l.kg.error("[UniversalAIChat] Failed to persist message queue:",e),rW.current===n&&rD.current===t&&rZ.current===t&&t3(eX("unknownError")),null}},[ta,eX]),sn=(0,o.useCallback)(async(e,t)=>{var n,r;let a=e.trim();if(!a)return null;let s={id:null!==(n=null==t?void 0:t.id)&&void 0!==n?n:"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"q-".concat(Date.now(),"-").concat(Math.random().toString(36).slice(2,8)),content:a,attachments:null!==(r=null==t?void 0:t.attachments)&&void 0!==r?r:[],...(null==t?void 0:t.internal)&&{internal:t.internal}};return await st({id:b(),type:"append",item:s},null==t?void 0:t.conversationId)?s:null},[st]),sr=(0,o.useCallback)(e=>{st({id:b(),type:"remove",queue_id:e})},[st]),sa=(0,o.useCallback)(async e=>{if(nc.trim()||tK.length)return;let t=ng.find(t=>t.id===e);if(!t)return;let n=rW.current,r=await st({id:b(),type:"remove",queue_id:e});(null==r?void 0:r.applied)&&n===rW.current&&rD.current===ta&&rZ.current===ta&&(np(t.content),tV(e=>{var n;return[...e,...(null!==(n=t.attachments)&&void 0!==n?n:[]).filter(t=>!e.some(e=>e.id===t.id))]}))},[ta,nc,tK.length,ng,st]);(0,o.useEffect)(()=>{if(!ta||rZ.current!==ta)return;let e=rW.current;return rM.current&&clearTimeout(rM.current),rM.current=setTimeout(()=>{let t=++rK.current;fetch("/api/ai/conversations/".concat(ta),{method:"PATCH",headers:nO(),body:JSON.stringify({draft:nc,draft_revision:t})}).then(async t=>{if(e!==rW.current||rD.current!==ta||rZ.current!==ta||t.ok)return;let n=await t.json().catch(()=>null);if(e===rW.current&&rD.current===ta&&rZ.current===ta)throw 409===t.status&&(null==n?void 0:n.conversation)&&(rK.current=Math.max(rK.current,Number(n.conversation.draft_revision)||0)),Error("Draft persistence failed: HTTP ".concat(t.status))}).catch(t=>{l.kg.error("[UniversalAIChat] Failed to persist draft:",t),e===rW.current&&rD.current===ta&&rZ.current===ta&&t3(eX("unknownError"))})},800),()=>{rM.current&&clearTimeout(rM.current)}},[nc,ta]),(0,o.useEffect)(()=>{if(tc){rO.current=!1;return}if(r6||0===ng.length||!ta||nZ||rZ.current!==ta||rN.current||rO.current)return;let[e]=ng;if(!e)return;let t=k(e,ta);if(t&&rT.current)return;rO.current=!0;let n=rW.current,r=()=>n===rW.current&&rD.current===ta&&rZ.current===ta;(async()=>{let n=await st({id:b(),type:"remove",queue_id:e.id});if(!(null==n?void 0:n.applied)){r()&&(rO.current=!1,t&&(rT.current=!0,a1(!1)));return}if(!r())return;let a={conversationId:ta,item:e,receiptId:b()};rU.current.set(ta,a),nL(n.queue),nM.current=n.queue,rF.current=e,rj.current()})()},[tc,r6,ng,nZ,ta,st,a3]);let ss=(0,o.useCallback)(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(e,t){var n,r,a,s;let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{document:l,model:o,readOnlyTools:c,agentRuntime:d,deepThinking:u,webSearch:m,planMode:p,locale:f,contextFiles:h,selectedPacks:g,workspaceContext:x,currentFolderId:v,executionForm:k,skillPreview:y,executionContext:w,workflowContext:j,selectedSkill:b,selectedSkills:N,selectedFilters:C,pinnedGoals:S,executionContextItems:T,pendingSlashPayload:I}=e,E=(null==l?void 0:l.metadata)?{...l.metadata,id:l.metadata.presentationId,name:l.name}:(null==l?void 0:l.id)?{type:"document",id:l.id,name:l.name,content:null!==(s=l.content)&&void 0!==s?s:"",inlineComments:null===(a=l.inlineComments)||void 0===a?void 0:a.filter(e=>!e.resolved)}:void 0;return{message:t,model:o,runtime:c?"vercel":d,deepThinking:u,webSearchEnabled:m,planMode:!c&&p,readOnlyTools:c,locale:f,documentContext:E,attachments:null!==(n=i.attachments)&&void 0!==n?n:[],contextFiles:h.filter(e=>!e.loadFailed).map(e=>({id:e.id,name:e.name,content:e.content,images:e.images,source:e.source})),contextPackIds:Array.from(new Set([...g.map(e=>e.id),...(null==x?void 0:x.contextPackIds)||[]])),folderId:v||void 0,executionForm:k,skillPreview:y,executionItem:w?{id:w.id,type:w.type}:void 0,workflowEditMode:(null==j?void 0:j.currentStateType)==="complete"&&(null==E?void 0:E.type)==="document",skillIds:(N.length>0?N:b?[b]:[]).map(e=>e.id),filterIds:C.map(e=>e.id),pinnedGoals:S.length>0?S:void 0,executionContextItems:T.length>0?T.map(e=>({id:e.id,type:e.type})):void 0,slashPromptIds:null!==(r=null==I?void 0:I.prompts.map(e=>e.id))&&void 0!==r?r:[],slashContexts:(null==I?void 0:I.contexts.length)?I.contexts.map(e=>({name:e.name,content:e.content})):void 0,workspaceId:null==x?void 0:x.workspaceId,contextFileIds:null==x?void 0:x.contextFileIds,...i}}({document:et,model:ty,readOnlyTools:G,agentRuntime:tj,deepThinking:aa,webSearch:ai,planMode:ao,locale:eJ,contextFiles:t_,selectedPacks:tX,workspaceContext:ev,currentFolderId:ad,executionForm:em,skillPreview:ep,executionContext:ek,workflowContext:ex,selectedSkill:r8,selectedSkills:r0,selectedFilters:an,pinnedGoals:n7,executionContextItems:eN,pendingSlashPayload:rv.current},e,t)},[et,ty,G,tj,aa,ai,ao,eJ,t_,tK,tX,ev,ad,am,eu,em,ep,ek,ex,r8,r0,an,n7,eN]),si=(0,o.useCallback)(async e=>{var t,n,r,a,i,o,c,d,u,m,f,h,g,w,N,C,S,T,I,E,_,A,R,P,D;l.kg.log("[handleSend] Starting...");let F=rG(),O=null!==F.conversationId,U=!!(null==e?void 0:e.connectionResumeId);if(U){if(!F.conversationId||e.connectionConversationId!==F.conversationId)throw Error("Connection request belongs to another conversation");if(tc||nZ||rN.current||rO.current||rF.current||r6||rZ.current!==F.conversationId)throw new s.N("Conversation is not ready to resume")}let L=rk.current,M=null!==(t=null==e?void 0:e.content)&&void 0!==t?t:L,Z=rF.current;rF.current=null;let z=null!==(n=null==Z?void 0:Z.content)&&void 0!==n?n:null,K=z&&F.conversationId&&rU.current.get(F.conversationId)||null,W=!!Z&&k(Z,F.conversationId),J=W||"[START]"===M&&(!z||W),X=x(Z?null!==(r=Z.attachments)&&void 0!==r?r:[]:M||(null==e?void 0:e.silentKind)?[]:tK.filter(e=>!e.loadFailed));
1if(null===X){t3(eX("messageAttachmentsInvalid"));return}let Q=()=>tV(e=>e.filter(e=>!X.some(t=>t.id===e.id))),Y=null!=z?z:M||nc.trim();if(!Y&&!U){l.kg.log("[handleSend] Early return - no message");return}if(!U&&M&&!z&&F.conversationId){let t="[START]"===M?v(F.conversationId):null;t&&(rS.current=t);let n=(null==e?void 0:e.silentKind)?j(e.silentKind,null!==(a=e.turnRequestId)&&void 0!==a?a:"workflow_start"===e.silentKind?F.conversationId:void 0):"[START]"===M?j("workflow_start",F.conversationId):void 0,r=await sn(Y,{...t&&{id:t},conversationId:F.conversationId,...n&&{internal:n}});if(!rV(F,O))return;r?"[START]"===M?rT.current=!1:e||rk.current!==L||(rk.current=null):r||"[START]"!==M||(rS.current=t,a1(!1));return}if(tc){if(!z&&!M){await sn(Y,{attachments:X})&&rV(F,O)&&(np(""),Q());return}l.kg.log("[handleSend] Early return - streaming (non-queue path)");return}if(nZ){!z&&await sn(Y,{attachments:X})&&!M&&rV(F,O)&&(np(""),Q());return}if(rN.current){l.kg.log("[handleSend] Blocked by sendLock — already in progress");return}let $=crypto.randomUUID();rN.current=!0,rE.current=$;let ee=!1,er=!1,ea=!1;try{if(r6){er=!0;return}t3(null);let t=!!et&&!!en,n=ta;if(n)l.kg.log("[handleSend] Using existing conversation:",n);else{l.kg.log("[handleSend] Creating new conversation...");let e=Date.now();if(n=await a8(),!rV(F,O))return;if(l.kg.log("[handleSend] createConversation took",Date.now()-e,"ms, convId:",n),n)aG.current=n,rD.current=n,ti(n),rZ.current=n,t||null===(o=aq.current)||void 0===o||o.call(aq);else{l.kg.error("[handleSend] Failed to create conversation"),t3(eX("conversationStartFailed")),"[START]"===M&&a1(!1);return}}let r=null!==(c=null==e?void 0:e.silentKind)&&void 0!==c?c:"[START]"===M?"workflow_start":void 0;if(!Z&&r&&null===F.conversationId){let t=j(r,null!==(d=null==e?void 0:e.turnRequestId)&&void 0!==d?d:"workflow_start"===r?n:void 0),a="workflow_start"===r?v(n):void 0;a&&(rS.current=a);let s=await sn(Y,{...a&&{id:a},conversationId:n,internal:t});if(rD.current!==n)return;if(!s){"workflow_start"===r&&a1(!1);return}rT.current=!1,a2(e=>e+1);return}let a=rW.current;if(!(rW.current===a&&rD.current===n&&rZ.current===n&&rE.current===$)||(U||await (null==H?void 0:H(n)),!(rW.current===a&&rD.current===n&&rZ.current===n&&rE.current===$)))return;let s=U||(Z?y(Z):(null==e?void 0:e.silentKind)!==void 0||"[START]"===M),x={id:"temp-".concat(Date.now()),role:"user",content:Y,attachments:X,createdAt:new Date};s||to(e=>[...e,x]),z||U||np(""),U||null==q||q(x.content);let k="temp-".concat(Date.now()+1),b={id:k,role:"assistant",content:"",model:rt,createdAt:new Date},L=null!==(m=null!==(u=null==Z?void 0:null===(i=Z.internal)||void 0===i?void 0:i.turnRequestId)&&void 0!==u?u:null==e?void 0:e.turnRequestId)&&void 0!==m?m:J?n:crypto.randomUUID();rR.current=L,rP.current=null,to(e=>[...e,b]),td(!0),tm(new Date),tM([]),(0,nE.Lf)(rt),rA.current=n;let ea=rW.current,es=()=>rW.current===ea&&rA.current===n&&rD.current===n&&rZ.current===n;r_.current=new AbortController;try{let r;{l.kg.log("[handleSend] Calling /api/ai/conversations/"+n+"/messages...");let t=Array.from(new Set([...tX.map(e=>e.id),...(null==ev?void 0:ev.contextPackIds)||[]])),a=(null==ev?void 0:ev.contextFileIds)||[],s=r0.length>0?r0.map(e=>e.name):[];if(console.log("[handleSend] Context being sent:",{contextPackIds:t,contextFileIds:a,skills:s,selectedPacksCount:tX.length,workspaceContextPackIds:null==ev?void 0:ev.contextPackIds,workspaceContextFileIds:null==ev?void 0:ev.contextFileIds,workspaceContextDefined:!!ev}),r=await fetch("/api/ai/conversations/".concat(n,"/messages"),{method:"POST",headers:nO(),body:JSON.stringify(U?{connection_resume_id:e.connectionResumeId,turnRequestId:L,model:ty,runtime:"vercel",locale:eJ,requireTerminalAgentStatus:!0}:ss(x.content,{requireTerminalAgentStatus:!0,turnRequestId:L,internalMessage:null==Z?void 0:Z.internal,attachments:X})),signal:r_.current.signal}),!es())return;!U&&(rx(null),rv.current=null,r.ok&&Q())}if(l.kg.log("[handleSend] Response received, status:",r.status),!r.ok){let e=await r.json().catch(()=>({error:eX("unknownError")}));if(!es())return;if(l.kg.error("[handleSend] Response NOT OK:",r.status,e),402===r.status&&"INSUFFICIENT_TOKENS"===e.code)throw to(e=>e.filter(e=>e.id!==k)),Error(eX("insufficientTokensWithSettings"));throw Error(e.error||"HTTP ".concat(r.status))}ee=!0,ro(r,n),"1"===r.headers.get("X-Praksis-Turn-Replayed")&&to(e=>e.filter(e=>e.id!==k)),M&&(!z||W)&&rk.current===M&&(rk.current=null,"[START]"===M&&(rS.current=null,rT.current=!1,rI.current=null,a1(!1)));let a=r.headers.get("X-Praksis-User-Message-Id"),s="1"===r.headers.get("X-Praksis-Agent-Mode");if(!U&&s&&!a)throw Error(eX("durableUserMessageMissing"));K&&rU.current.get(n)===K&&rU.current.delete(n),a&&to(e=>e.map(e=>e.id===x.id?{...e,id:a}:e)),l.kg.log("[handleSend] Starting stream processing...");let i=null===(f=r.body)||void 0===f?void 0:f.getReader();if(!i)throw Error(eX("responseBodyMissing"));let o=null==ex?void 0:ex.onCanvasPreview;if(t&&!o)await se(i,k,n,es);else{let e=new TextDecoder,t="",a=!1,s=0,o=!1,c=!1,d="",u="",m="",p=!1,f=(0,nE.qf)({getWorkspaceId:()=>null==ev?void 0:ev.workspaceId,onSkillDraft:V,onContextFileTruncations:tM});for(;;){let{done:r,value:g}=await i.read();if(r)break;
1if(!es())continue;let x=f.consume(e.decode(g,{stream:!0}));t+=x,x.includes("<!--PLAN_MODE-->")&&(t=t.replace("<!--PLAN_MODE-->",""));let v=nx(t);for(let e of(nv(v,{conversationId:n,assistantMessageId:k,stillOwnsConversation:es,setConversationTitle:nW,onTitleChange:B,sidebarRefreshRef:aq,setMessages:to,readOnlyTools:G,setPlanMode:ac}),t=v.content,v.executionMutationTypes))window.dispatchEvent(new CustomEvent("execution-data-changed",{detail:{type:e}}));let y=ny(t,{canvasMode:a,isNativeCanvasMode:o,nativeCanvasContentStart:s});if("native-start"===y.phase){try{a=!0,o=!0,u=y.title;let e=y.isRegeneration;c=e,c=e,l.kg.log("[UniversalAIChat] \uD83C\uDFAC Native canvas generation started:",u,e?"(REGENERATION)":"(NEW)"),s=y.contentStart,m=y.preContent,d=y.content;let t=e?eX("canvasUpdatingStatus",{title:u}):eX("canvasGeneratingStatus",{title:u});to(e=>e.map(e=>e.id===k?{...e,content:"\uD83D\uDCDD ".concat(t)}:e)),(null==ex?void 0:ex.onCanvasPreview)&&ex.onCanvasPreview({title:u,content:d,streaming:!0,fileId:e?ex.canvasFileId:void 0});continue}catch(e){l.kg.error("[UniversalAIChat] Failed to parse CANVAS_META:",e)}
1y=ny(t,{canvasMode:a,isNativeCanvasMode:o,nativeCanvasContentStart:s})}if("native-stream"===y.phase){(d=y.content).length>50&&(null==ex?void 0:ex.onCanvasPreview)&&ex.onCanvasPreview({title:u,content:d,streaming:!0,fileId:c?ex.canvasFileId:void 0});let e=c?eX("canvasUpdatingProgress",{title:u,count:d.length}):eX("canvasGeneratingProgress",{title:u,count:d.length});to(t=>t.map(t=>t.id===k?{...t,content:"\uD83D\uDCDD ".concat(e)}:t));continue}if("legacy-start"===y.phase){a=!0,m=y.preContent,d=y.content,to(e=>e.map(e=>e.id===k?{...e,content:(m||"")+"\n\n**".concat(eX("canvasOpeningAndWriting"),"**")}:e));continue}if("legacy-stream"===y.phase){d=y.content;let e=y.end;if(!e&&d.length>0&&d.length<100&&l.kg.log("[UniversalAIChat] Canvas streaming:",{contentLength:d.length,hasEndMarker:!!e,lastChars:d.slice(-30)}),e){let t=e.postContent;d=e.content,u=null!==(h=nw(d))&&void 0!==h?h:eX("untitledCanvas"),!p&&eo&&(p=!0,l.kg.log("[UniversalAIChat] Canvas complete, opening:",u),(async()=>{try{let e=await eo(d,u);if(!es())return;if(e){let e=t||"✅ **".concat(eX("canvasOpenedWithTitle",{title:u}),"**");to(t=>t.map(t=>t.id===k?{...t,content:(m?m+"\n\n":"")+e}:t))}else l.kg.warn("[UniversalAIChat] Canvas creation returned null - API likely failed"),to(e=>e.map(e=>e.id===k?{...e,content:(m||"")+"\n\n".concat(eX("canvasCreationFailedInline"),"\n\n")+d}:e))}catch(e){if(!es())return;l.kg.error("[UniversalAIChat] Canvas creation error:",e),to(t=>t.map(t=>t.id===k?{...t,content:(m||"")+"\n\n".concat(eX("canvasErrorInline",{error:e instanceof Error?e.message:eX("unknownError")}),"\n\n")+d}:t))}})())}else{let e=function(e){var t,n;return null===(n=e.match(/^#+ (.+)$/m))||void 0===n?void 0:null===(t=n[1])||void 0===t?void 0:t.trim()}(d)||eX("writing");to(t=>t.map(t=>t.id===k?{...t,content:(m||"")+"\n\n".concat(eX("canvasWritingProgress",{title:e,count:d.length}))}:t))}}else to(e=>e.map(e=>e.id===k?{...e,content:t}:e))}if(!es())return;if(f.finish(),o&&a&&(null==ex?void 0:ex.onCanvasPreview)){let e=nk(t,s);if(e.length>100){if(l.kg.log("[UniversalAIChat] ✅ Native canvas generation COMPLETE, content length:",e.length),function(e,t){let n=e.toLowerCase().includes("voice_dna")||e.toLowerCase().includes("voice dna"),r=t.includes("LAG 7")||t.includes("LAYER 7")||t.includes("VURDERING"),a=t.includes("LAG 5")||t.includes("LAYER 5")||t.includes("M\xd8NSTERBIBLIOTEK");return n&&(!r||!a)}(u,e)&&(null==ex?void 0:ex.onCanvasPreview)){l.kg.log("[UniversalAIChat] ⚠️ Document incomplete, auto-continuing..."),ex.onCanvasPreview({title:u,content:e+"\n\n---\n\n*".concat(eX("continuingGeneration"),"*"),streaming:!0});let t=u;if(await new Promise(e=>setTimeout(e,300)),!es())return;try{let r=await fetch("/api/ai/conversations/".concat(n,"/messages"),{method:"POST",headers:nO(),body:JSON.stringify(ss('FORTSETT DOKUMENTET I CANVAS:\n\nDu stoppet midt i dokumentet. Kall generate_canvas med SAMME filename ("'.concat(t,'") og fortsett \xe5 skrive fra der du slapp.\n\nVIKTIG:\n- Kall generate_canvas(output_type="final", filename="').concat(t,'") F\xd8RST\n- Deretter FORTSETT dokumentet fra der det sluttet\n- IKKE gjenta innhold som allerede er skrevet\n- Skriv de resterende lagene (5, 6, 7 hvis de mangler)\n\nStart direkte med innholdet som mangler.')))});if(!es())return;if(!r.ok)throw Error("Continuation failed");let a=null===(g=r.body)||void 0===g?void 0:g.getReader();if(!a)throw Error(eX("responseBodyMissing"));let s=new TextDecoder,i="",o=!1;for(;;){let{done:n,value:r}=await a.read();if(n)break;if(!es())continue;let l=s.decode(r,{stream:!0});for(let n of function(e){let t=[];for(let n of e.split("\n")){if(!n.startsWith("data: "))continue;let e=n.slice(6);if("[DONE]"!==e)try{let n=JSON.parse(e);n.content&&t.push(String(n.content))}catch(e){}}return t}(l))try{if((i+=n).includes("<!--CANVAS_META:")){o=!0;let n=nj(i);n.length>50&&(null===(C=ex.onCanvasPreview)||void 0===C||C.call(ex,{title:t,content:e+"\n\n"+n,streaming:!0}))}else if(o){let n=nj(i);null===(S=ex.onCanvasPreview)||void 0===S||S.call(ex,{title:t,content:e+"\n\n"+n,streaming:!0})}}catch(e){}}if(!es())return;let c=e;if(o&&i.includes("-->")){let t=nj(i);c=e+"\n\n"+t}l.kg.log("[UniversalAIChat] ✅ Auto-continuation complete:",c.length),null===(w=ex.onCanvasPreview)||void 0===w||w.call(ex,{title:t,content:c,streaming:!1}),to(e=>e.map(e=>e.id===k?{...e,content:eX("documentGeneratedInCanvas",{title:t})}:e)),(null==ex?void 0:ex.refreshWorkspaceData)&&ex.refreshWorkspaceData(),null===(N=ex.onChatActivity)||void 0===N||N.call(ex),rJ("[Dokumentet er ferdig generert og lagret som dokument. Statemaskinen har oppdatert steget. Fortell brukeren kort at dokumentet er klart, og hva de kan gj\xf8re n\xe5 basert p\xe5 ditt n\xe5v\xe6rende steg. Maks 2-3 setninger.]")}catch(n){if(!es())return;l.kg.error("[UniversalAIChat] Auto-continuation error:",n),null===(T=ex.onCanvasPreview)||void 0===T||T.call(ex,{title:t,content:e+"\n\n---\n\n*".concat(eX("generationStoppedContinue"),"*"),streaming:!1})}}else ex.onCanvasPreview({title:u,content:e,streaming:!1,fileId:c?ex.canvasFileId:void 0}),to(e=>e.map(e=>e.id===k?{...e,content:eX("documentGeneratedInCanvas",{title:u})}:e)),(null==ex?void 0:ex.refreshWorkspaceData)&&ex.refreshWorkspaceData(),null===(I=ex.onChatActivity)||void 0===I||I.call(ex),rJ("[Dokumentet er ferdig generert og lagret som dokument. Statemaskinen har oppdatert steget. Fortell brukeren kort at dokumentet er klart, og hva de kan gj\xf8re n\xe5 basert p\xe5 ditt n\xe5v\xe6rende steg. Maks 2-3 setninger.]")}else{let t=e||d;l.kg.warn("[UniversalAIChat] ⚠️ Native canvas generation ended with short finalCanvasContent:",e.length,"canvasContent length:",d.length),t.length>10?ex.onCanvasPreview({title:u,content:t,streaming:!1}):ex.onCanvasPreview({title:u,content:eX("documentGenerationEmpty"),streaming:!1})}}else if(a&&!p&&d&&eo){let e=d.replace(/\[\s*\/?\s*CANVAS\s*\]?$/i,"").trim();if(e){let t=null!==(E=nw(e))&&void 0!==E?E:eX("untitledCanvas");l.kg.log("[UniversalAIChat] Canvas incomplete (no end marker), creating anyway:",t,"Content length:",e.length),p=!0;try{let n=await eo(e,t);if(!es())return;n?to(e=>e.map(e=>e.id===k?{...e,content:(m||eX("hereIsYourDocument"))+"\n\n✅ **".concat(eX("canvasOpenedWithT
1itle",{title:t}),"**")}:e)):(l.kg.warn("[UniversalAIChat] Canvas creation returned null, showing inline"),to(t=>t.map(t=>t.id===k?{...t,content:(m||"")+"\n\n"+e}:t)))}catch(t){if(!es())return;l.kg.error("[UniversalAIChat] Canvas creation failed:",t),to(t=>t.map(t=>t.id===k?{...t,content:(m||"")+"\n\n"+e}:t))}}}r.ok&&!U&&Q()}}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)es()&&to(e=>e.map(e=>e.id===k?{...e,content:e.content||eX("generationStopped")}:e));else{if(U)throw e;let t=e instanceof Error?e.message:eX("unknownError");es()&&(t3(t),J&&!ee&&(rT.current=W,a1(!1)),to(e=>e.map(e=>e.id===k?{...e,content:eX("messageErrorPrefix",{error:t})}:e)))}}finally{try{let e=await fetch("/api/ai/conversations/".concat(n));if(e.ok){let t=await e.json();if(es()){let e=null===(_=t.conversation)||void 0===_?void 0:_.title;"string"==typeof e&&e.trim()&&(nW(e),null==B||B(n,e),null===(P=aq.current)||void 0===P||P.call(aq));let r=null===(A=t.conversation)||void 0===A?void 0:A.agent_status;if(r&&"working"!==r&&"aborting"!==r&&"in_doubt"!==r&&(rP.current=L),"working"===r||"aborting"===r||"in_doubt"===r){nz(!0),t3("in_doubt"===r?eX("mutationInDoubt"):eX("turnStillFinalizing"));let e=rW.current,t=()=>e===rW.current&&rD.current===n&&rZ.current===n;(async()=>{let e=null,a=r,s=async()=>{e=Date.now();try{await fetch("/api/ai/conversations/".concat(encodeURIComponent(n)),{method:"PATCH",headers:nO(),body:JSON.stringify({agent_control:"stop_current"})})}catch(e){}};for("in_doubt"!==a&&await s();t();){if(await new Promise(e=>setTimeout(e,400)),!t()||"in_doubt"!==a&&nA(Date.now(),e)&&(await s(),!t()))return;try{var i;let e=await fetch("/api/ai/conversations/".concat(encodeURIComponent(n)),{headers:(0,p.p)()});if(!e.ok)continue;let r=await e.json();if(!t())return;let s=null===(i=r.conversation)||void 0===i?void 0:i.agent_status;if("string"==typeof s&&(a=s),s&&"working"!==s&&"aborting"!==s&&"in_doubt"!==s){rP.current=L,nz(!1),t3("error"===s?eX("systemInterrupted"):null);return}}catch(e){}}})()}if(Array.isArray(null===(R=t.conversation)||void 0===R?void 0:R.messages)){let e=t.conversation.messages.map(nd);to("aborted"===r||"aborted_client"===r?nu(e,r,eX("generationStopped"),eX("stoppedByYou")):e)}else("aborted"===r||"aborted_client"===r)&&to(e=>nu(e,r,eX("generationStopped"),eX("stoppedByYou")))}}}catch(e){l.kg.error("[UniversalAIChat] Failed to refetch authoritative title:",e)}es()&&(td(!1),tm(void 0),await (null==ex?void 0:null===(D=ex.onRuntimeStateChange)||void 0===D?void 0:D.call(ex)),es()&&(r_.current=null,rA.current=null)),rR.current===L&&(rR.current=null)}}finally{if(z&&!ee&&K&&rU.current.get(K.conversationId)===K){let e=K.conversationId;await st({id:b(),type:"prepend",item:K.item},e)&&rU.current.get(e)===K&&(rU.current.delete(e),ea=!0)}rE.current===$&&(rE.current=null,rN.current=!1),er&&ea&&rV(F,O)&&(rO.current=!1,a2(e=>e+1))}},[ss,nc,tc,nZ,ta,e9,ty,rt,tj,tl.length,nK,e3,t_,tK,tX,r8,r0,r6,an,n7,ad,am,eu,G,V,ev,ex,aa,ai,ao,eJ,et,en,H,rG,er,se,sn,st,rV,eX]);rj.current=si;let sl=(0,o.useCallback)(()=>{if(!eK||"[START]"!==rk.current||tc||rN.current||rC.current)return;rC.current=!0,t3(null),a1(!0);let e=rS.current;if(e&&nM.current.some(t=>t.id===e)){rT.current=!1,a2(e=>e+1),Promise.resolve().finally(()=>{rC.current=!1});return}e&&(rT.current=!1),Promise.resolve(rj.current({content:"[START]",silentKind:"workflow_start"})).finally(()=>{rC.current=!1})},[eK,tc]),so=(0,o.useMemo)(()=>tl.filter(e=>"assistant"===e.role).map(e=>e.content),[tl]),sc=(0,o.useCallback)(async e=>{let t=rG(),r=null!==t.conversationId,a=()=>rV(t,r);if(!(0,e4.CP)(so,e)){Promise.resolve().then(n.bind(n,17787)).then(e=>{let{toast:t}=e;t.error(eX("coreContextUpdateFailed"),{description:eX("coreContextProposalUnverified")})});return}tB(e.file_id);try{if(!Number.isSafeInteger(e.content_version)||e.content_version<0)throw Error("Forslaget mangler dokumentversjon. Be om et nytt forslag.");let t=await fetch("/api/library/files/".concat(e.file_id),{method:"PATCH",headers:nO(),body:JSON.stringify({content:e.proposed_content,expected_version:e.content_version})});if(!t.ok){let e=await t.json().catch(()=>({}));if(!a())return;throw Error("string"==typeof e.message?e.message:"string"==typeof e.error?e.error:"HTTP ".concat(t.status))}if(!a())return;tR(t=>t.map(t=>
1t.id===e.file_id?{...t,content:e.proposed_content}:t)),(null==et?void 0:et.id)===e.file_id&&(null==en||en(e.proposed_content)),window.dispatchEvent(new CustomEvent("workspace-refresh",{detail:{tool:"core-context-human-approved-update",workspaceId:null==ev?void 0:ev.workspaceId,fileId:e.file_id}})),Promise.resolve().then(n.bind(n,17787)).then(t=>{let{toast:n}=t;a()&&n.success(eX("coreContextUpdateSuccess"),{description:eX("coreContextUpdateSuccessDescription",{fileName:e.file_name})})})}catch(t){if(!a())return;let e=t instanceof Error?t.message:eX("coreContextUpdateFailed");t3(e),Promise.resolve().then(n.bind(n,17787)).then(t=>{let{toast:n}=t;a()&&n.error(eX("coreContextUpdateFailed"),{description:e})})}finally{a()&&tB(null)}},[rG,null==et?void 0:et.id,en,so,rV,eX,null==ev?void 0:ev.workspaceId]),sd=(0,o.useCallback)(e=>{Promise.resolve().then(n.bind(n,17787)).then(t=>{let{toast:n}=t;n.info(eX("coreContextProposalRejected"),{description:eX("coreContextProposalRejectedDescription",{fileName:e.file_name})})})},[eX]),su=(0,o.useCallback)(e=>{let t=e.content.trim();t&&to(n=>{let r=n[n.length-1];return(null==r?void 0:r.role)===e.role&&r.content.trim()===t?n:[...n,{id:"voice-elevenlabs-".concat(e.role,"-").concat(Date.now()),role:e.role,content:t,createdAt:new Date}]})},[]),sm=(0,o.useCallback)(async()=>{var e;if(ta)return ta;let t=await a8();return t?(aG.current=t,rD.current=t,ti(t),null==J||J(t),null===(e=aq.current)||void 0===e||e.call(aq),t):(t3(eX("voiceConversationStartFailed")),null)},[a8,ta,J,eX]),sp=(0,o.useCallback)(()=>{if("hermes"===tj&&ta){let e=n4.find(e=>"hermes_agent"===e.type&&e.conversation_id===ta&&("pending"===e.status||"processing"===e.status));e&&n5(e.id,{currentStep:eX("stoppingHermesRun")}),fetch("/api/ai/conversations/".concat(encodeURIComponent(ta),"/external-agent-runs/stop"),{method:"POST",headers:nO()}).catch(e=>{l.kg.error("[UniversalAIChat] Failed to stop Hermes run:",e)})}if("hermes"!==tj&&ta){let t=rR.current,n=rW.current,r=()=>n===rW.current&&rD.current===ta&&rZ.current===ta;if(!t){var e;t3(eX("unknownError")),null===(e=r_.current)||void 0===e||e.abort();return}nz(!0),(async()=>{for(var e,n;r();){try{let n=await fetch("/api/ai/conversations/".concat(encodeURIComponent(ta)),{method:"PATCH",headers:nO(),body:JSON.stringify({agent_control:"stop",turn_request_id:t})}),a=await n.json().catch(()=>null);if(!r())return;if(!n.ok)throw Error("Stop failed: HTTP ".concat(n.status));if((null==a?void 0:a.pending)===!0||(null==a?void 0:a.stopped)===!0)break;if((null==a?void 0:null===(e=a.conversation)||void 0===e?void 0:e.agent_status)==="in_doubt"){t3(eX("mutationInDoubt"));break}}catch(e){l.kg.error("[UniversalAIChat] Failed to signal server-side stop:",e)}await new Promise(e=>setTimeout(e,400))}if(r())for(;;){if(!r())return;try{let e=await fetch("/api/ai/conversations/".concat(encodeURIComponent(ta)),{headers:(0,p.p)()});if(e.ok){let t=await e.json();if(!r())return;let a=null===(n=t.conversation)||void 0===n?void 0:n.agent_status;if("in_doubt"===a)t3(eX("mutationInDoubt"));else if(a&&"working"!==a&&"aborting"!==a){"aborted"===a&&to(e=>nu(e,a,eX("generationStopped"),eX("stoppedByYou"))),t3("error"===a?eX("systemInterrupted"):null),nz(!1);break}}}catch(e){}await new Promise(e=>setTimeout(e,400))}})()}r_.current&&r_.current.abort()},[tj,n4,ta,eX,n5]),sf=(0,o.useCallback)(async e=>{if(!ng.find(t=>t.id===e))return;let t=rW.current,n=tc?rR.current:null;tc&&nz(!0);let r=await st({id:b(),type:"move_to_front",queue_id:e});if(!(null==r?void 0:r.applied)){t===rW.current&&rD.current===ta&&rZ.current===ta&&nz(!1);return}if(t===rW.current&&rD.current===ta&&rZ.current===ta&&tc){if(n&&rR.current===n)sp();else if(!rR.current){if(n&&rP.current===n)nz(!1);else{let e=()=>t===rW.current&&rD.current===ta&&rZ.current===ta;(async()=>{let t=Date.now(),r=null,a=async()=>{t=Date.now();try{await fetch("/api/ai/conversations/".concat(encodeURIComponent(ta||"")),{method:"PATCH",headers:nO(),body:JSON.stringify({agent_control:"stop_current"})})}catch(e){}};for(;e();){if("in_doubt"!==r&&nA(Date.now(),t)&&(await a(),!e()))return;try{let t=await fetch("/api/ai/conversations/".concat(encodeURIComponent(ta||"")),{headers:(0,p.p)()});if(t.ok){var s;let a=await t.json();if(!e())return;let i=null===(s=a.conversation)||void 0===s?void 0:s.agent_status;if("string"==typeof i&&(r=i),"in_doubt"===i)t3(eX("mutationInDoubt"));else if(i&&"working"!==i&&"aborting"!==i){rP.current=n,t3("error"===i?eX("systemInterrupted"):null),nz(!1);return}}}catch(e){}await new Promise(e=>setTimeout(e,400))}})()}}}},[ta,tc,ng,st,sp,eX]),sh=(0,o.useRef)(null);(0,o.useEffect)(()=>{let e=ex?rc:!ta,t=!!ta&&a5.current!==ta&&aG.current!==ta,n=!!ta&&rI.current===ta||0===tl.length&&!tc;if(eK&&e&&!t&&n&&!tp&&!a$.current&&!sh.current){a$.current=!0,a1(!0),ex?l.kg.log("[UniversalAIChat] Auto-initiating workflow conversation (silent)",{instanceId:ex.instanceId,workflowId:ex.workflowId,hasExistingConversation:!!ta}):l.kg.log("[UniversalAIChat] Auto-initiating conversation (silent)",{source:e2,hasExistingConversation:!!ta});let e=rG(),t=rH(e,()=>{(async()=>{rk.current="[START]",l.kg.log("[UniversalAIChat] Calling handleSend for auto-initiate...");let n=Date.now();try{if(await rj.current({content:"[START]",silentKind:"workflow_start"}),!rV(e,null!==e.conversationId))return;l.kg.log("[UniversalAIChat] handleSend completed in",Date.now()-n,"ms")}catch(t){if(!rV(e,null!==e.conversationId))return;l.kg.error("[UniversalAIChat] handleSend FAILED:",t),a1(!1)}finally{sh.current===t&&(sh.current=null)}})()},100,null!==e.conversationId);sh.current=t}return()=>{}},[eK,ex,rc,ta,e2,tl.length,tc,tp,rG,rH,rV]),(0,o.useEffect)(()=>{tl.length>0&&a0&&a1(!1)},[tl.length,a0]);let sg=(0,o.useCallback)(async e=>{if(0===e.length)return;let t=rG(),n=null!==t.conversationId,r=e.filter(e=>"tool"===e.type);if(r.length>0){for(let e of r){var a;let t=(null===(a=e.shortcut)||void 0===a?void 0:a.toLowerCase())||e.name.toLowerCase();["upload","voice","pdf","document","video","audio","text"].includes(t)&&r$(e=>[...e,{id:"widget-".concat(Date.now(),"-").concat(Math.random().toString(36).slice(2,9)),type:t,timestamp:Date.now()}])}if(e.length===r.length)return}let s=e.filter(e=>"tool"!==e.type),i=await rh.execute(s);if(!rV(t,n)||!i)return;if(i.skills.length>0){let e=i.skills[0];e&&r9({id:e.id,name:e.name,instructions:e.instructions,description:"",category:"skill",owner_type:"system"})}if(i.contexts.length>0){let e=i.contexts.map(e=>({id:"goal"===e.type||"priority"===e.type||"task"===e.type?"execution_".concat(e.type,":").concat(e.id):e.id,name:e.name,content:e.content,type:"pack"===e.type?"pack":"library"}));e.length>0&&tR(t=>{let n=new Set(t.map(e=>e.id));return[...t,...e.filter(e=>!n.has(e.id))]})}rx(i),rv.current=i;let l=i.contexts.some(e=>"file"===e.type||"pack"===e.type),o=i.prompts.length>0||i.skills.length>0;if(!l&&!o){rx(null),rv.current=null;return}let c=[];if(i.skills.length>0){let e=i.skills.map(e=>e.name).join(", ");c.push("Aktiver skill: ".concat(e))}if(i.prompts.length>0){let e=i.prompts.map(e=>"/".concat(e.shortcut||e.name)).join(" ");c.push("Kj\xf8r: ".concat(e))}if(i.contexts.length>0){let e=i.contexts.filter(e=>"file"===e.type||"pack"===e.type).map(e=>e.name).join(", ");e&&c.push("Les kontekst: ".concat(e))}np(c.join(" | ")||"Start"),rH(t,()=>{{let e=window.document.querySelector("[data-send-button]");e&&e.click()}},150,n)},[rG,rH,rh,rV,eX]),sx=(0,o.useCallback)(()=>{r3.current.clear(),ti(null),to([]),nW(e1),nG(!1),t3(null),np(""),tR([]),tz([]),tQ([]),r1([]),ar([]),n6([]),nM.current=[],nL([]),rZ.current=null,rO.current=!1,rF.current=null},[e1]),sv=(0,o.useCallback)(e=>{rD.current!==e&&(a5.current=null,aG.current=null,ti(e),tR([]),tz([]),tQ([]),r1([]),ar([]),n6([]),nM.current=[],nL([]),np(""),rZ.current=null,rO.current=!1,rF.current=null)},[]),sk=(0,o.useCallback)(async()=>
1{if(!ab.trim()){aj(!1);return}let e=ab.trim();if(nW(e),aj(!1),ta)try{var t;await fetch("/api/ai/conversations/".concat(ta),{method:"PUT",headers:nO(),body:JSON.stringify({title:e})}),null===(t=aq.current)||void 0===t||t.call(aq)}catch(e){l.kg.error("Failed to update conversation title:",e)}},[ab,ta]),sy=(0,o.useCallback)(()=>{aN(nK),aj(!0),setTimeout(()=>{var e;return null===(e=aC.current)||void 0===e?void 0:e.focus()},0)},[nK]),sw=(0,o.useCallback)(async e=>{let t=rG(),r=null!==t.conversationId,a=()=>rV(t,r);for(let t of e){if(!a())return;if(t.size>10485760){t3(eX("fileTooLarge",{name:t.name}));continue}let e=t.name.toLowerCase().split(".").pop()||"",r="pdf"===e||"application/pdf"===t.type,s="docx"===e||"application/vnd.openxmlformats-officedocument.wordprocessingml.document"===t.type,i=["md","json","csv","txt","js","ts","tsx","jsx","py","html","css","xml","yaml","yml","toml","sql","sh","env","gitignore","log"].includes(e),o=t.type.startsWith("text/")||"application/json"===t.type||"application/xml"===t.type,c=i||o;l.kg.log("[File Drop] Processing: ".concat(t.name,", type: ").concat(t.type,", ext: ").concat(e,", isPDF: ").concat(r,", isDocx: ").concat(s,", isText: ").concat(c));let d=["png","jpg","jpeg","gif","webp"].includes(e);try{let e="",i=[];if(r){l.kg.log("[File Drop] Extracting text from PDF: ".concat(t.name));let{extractTextFromPDFClient:r,extractImagesFromFile:s,VISUAL_ANALYSIS_ENABLED:o}=await Promise.resolve().then(n.bind(n,42508));if(!a()||(e=await r(t),!a()))return;if(l.kg.log("[File Drop] PDF extracted ".concat(e.length," chars from ").concat(t.name)),o){l.kg.log("[File Drop] Extracting images from PDF for visual analysis: ".concat(t.name));let e=await s(t,{maxPages:5,imageQuality:.7});if(!a())return;i=e,l.kg.log("[File Drop] Extracted ".concat(i.length," images from ").concat(t.name))}}else if(s){l.kg.log("[File Drop] Extracting text from DOCX: ".concat(t.name));let n=await t.arrayBuffer();if(!a())return;let r=btoa(new Uint8Array(n).reduce((e,t)=>e+String.fromCharCode(t),"")),s="data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,".concat(r),i=await (0,f.it)(s,t.name);if(!a())return;if(!i.success)throw Error("Failed to extract text from ".concat(t.name));e=i.text,l.kg.log("[File Drop] DOCX extracted ".concat(e.length," chars from ").concat(t.name))}else if(d){l.kg.log("[File Drop] Reading image: ".concat(t.name));let{extractImagesFromFile:r}=await Promise.resolve().then(n.bind(n,42508));if(!a())return;let s=await r(t);if(!a())return;i=s,e="[Bilde: ".concat(t.name,"]"),l.kg.log("[File Drop] Image ready for visual analysis: ".concat(t.name))}else if(c){if(e=await t.text(),!a())return;l.kg.log("[File Drop] Read ".concat(e.length," chars from ").concat(t.name))}else{t3(eX("unsupportedFileType",{name:t.name}));continue}if((!e||0===e.trim().length)&&0===i.length){t3(eX("fileContentExtractionFailed",{name:t.name}));continue}let o={id:crypto.randomUUID(),name:t.name,content:e||"[Visuelt innhold: ".concat(t.name,"]"),type:"upload",images:i.length>0?i:void 0};l.kg.log("[File Drop] Added context file: ".concat(t.name," with ").concat(e.length," chars and ").concat(i.length," images")),tV(e=>[...e,o])}catch(e){if(!a())return;l.kg.error("Failed to read file:",e),t3(eX("fileReadFailed",{name:t.name,error:e instanceof Error?e.message:eX("unknownError")}))}}},[rG,rV,eX]),sj=(0,o.useCallback)(()=>{let e=[...tl].reverse().find(e=>"assistant"===e.role);(null==e?void 0:e.content)&&navigator.clipboard.writeText(e.content)},[tl]),sb=(0,o.useCallback)(async(e,t,n)=>{var r,a,s;if(!ta||tc||nZ)return;let i=(null==n?void 0:n.modelOverride)||ty,o=rW.current,c=()=>o===rW.current&&rD.current===ta&&rZ.current===ta,d=tl.find(t=>t.id===e);if(!d)return;let u=tl.indexOf(d),m=tl.slice(u).map(e=>e.id).filter(e=>!e.startsWith("temp-"));if(d.id.startsWith("temp-")||m.length!==tl.length-u){t3(eX("unknownError"));return}if((null==n?void 0:n.modelOverride)&&n.modelOverride!==ty)try{let e=await fetch("/api/ai/conversations/".concat(ta),{method:"PUT",headers:nO(),body:JSON.stringify({model:n.modelOverride})});if(!e.ok)throw Error("HTTP ".concat(e.status));if(!c())return;tw(n.modelOverride)}catch(e){l.kg.error("[UniversalAIChat] Failed to persist retry model:",e),c()&&t3(eX("unknownError"));return}let p=tl.slice(0,u),f={id:d.id,role:d.role,content:t,model:d.model,attachments:d.attachments,createdAt:d.createdAt};to([...p,f]);let h="temp-".concat(Date.now()),g={id:h,role:"assistant",content:"",model:"hermes"===tj?rt:i,createdAt:new Date};to(e=>[...e,g]);let x=crypto.randomUUID();
1rR.current=x,td(!0),tm(new Date),t3(null),r_.current=new AbortController;try{if(await (null==H?void 0:H(ta)),!c())return;tM([]);let e=await fetch("/api/ai/conversations/".concat(ta,"/messages"),{method:"POST",headers:nO(),body:JSON.stringify(ss(t,{model:i,replaceFromMessageId:d.id,attachments:null!==(a=d.attachments)&&void 0!==a?a:[],replaceMessageIds:m,requireTerminalAgentStatus:!0,turnRequestId:x})),signal:r_.current.signal});if(!c())return;if(!e.ok){let t=await e.json().catch(()=>({error:eX("unknownError")}));if(!c())return;if(402===e.status&&"INSUFFICIENT_TOKENS"===t.code){to(e=>e.filter(e=>e.id!==h)),t3(eX("insufficientTokens")),td(!1);return}throw Error(t.error||"HTTP ".concat(e.status))}let n=e.headers.get("X-Praksis-User-Message-Id");if("1"===e.headers.get("X-Praksis-Agent-Mode")&&!n)throw Error(eX("durableReplacementMessageMissing"));n&&to(e=>e.map(e=>e.id===f.id?{...e,id:n}:e));let s=null===(r=e.body)||void 0===r?void 0:r.getReader();if(!s)throw Error(eX("responseBodyMissing"));let l=new TextDecoder,o="",u=(0,nE.qf)({getWorkspaceId:()=>null==ev?void 0:ev.workspaceId,onContextFileTruncations:tM});for(;;){let{done:e,value:t}=await s.read();if(e)break;c()&&(o+=u.consume(l.decode(t,{stream:!0})),c()&&to(e=>e.map(e=>e.id===h?{...e,content:o}:e)))}c()&&u.finish()}catch(e){e instanceof Error&&"AbortError"===e.name?l.kg.log("[UniversalAIChat] Edit regeneration aborted"):(l.kg.error("[UniversalAIChat] Edit regeneration error:",e),c()&&t3(e instanceof Error?e.message:eX("regenerationFailed")))}finally{try{let e=await fetch("/api/ai/conversations/".concat(encodeURIComponent(ta)));if(e.ok&&c()){let t=await e.json();c()&&Array.isArray(null===(s=t.conversation)||void 0===s?void 0:s.messages)&&to(t.conversation.messages.map(nd))}}catch(e){l.kg.error("[UniversalAIChat] Edit reconciliation failed:",e)}c()&&(td(!1),tm(void 0),r_.current=null),rR.current===x&&(rR.current=null)}},[ss,ta,tc,nZ,tl,ty,rt,tj,aa,ai,t_,tK,tX,ad,am,eu,G,V,r8,r0,an,n7,ev,ao,eJ,H,eX]),sN=(0,o.useCallback)(e=>{if(!ta||tc)return;let t=[...tl].reverse().find(e=>"user"===e.role);t&&sb(t.id,t.content,e?{modelOverride:e}:void 0)},[ta,tc,tl,sb]),sC=(0,o.useCallback)(()=>{if(nc.trim())return;let e=[...tl].reverse().find(e=>"user"===e.role);(null==e?void 0:e.content)&&np(e.content)},[nc,tl]),sS=(0,o.useCallback)(e=>{let t=["library","production","dialogue","flow","folder"].includes(e.source)?e.source:"library";tR(n=>n.some(t=>t.id===e.id)?n:[...n,{id:e.id,name:e.name,content:"",type:"library",source:t}]),null==$||$([{id:e.id,name:e.name,source:t}])},[$]),sT=(0,o.useCallback)(e=>{let t=rG();np({explain:"Forklar dette mer detaljert.",shorter:"Gj\xf8r dette svaret kortere og mer konsist.",example:"Gi meg et konkret eksempel.",why:"Hvorfor? Forklar begrunnelsen."}[e]),rH(t,()=>{var e;let t=null===(e=globalThis.document)||void 0===e?void 0:e.querySelector("[data-send-button]");t&&!t.disabled&&t.click()},100,null!==t.conversationId)},[rG,rH]);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{enabled:n=!0,isGenerating:r=!1}=t,a=(0,o.useRef)(e);(0,o.useEffect)(()=>{a.current=e},[e]);let s=(0,o.useCallback)(e=>{var t,s,i,l,o,c,d,u,m,p,f,h,g,x,v,k,y,w;if(!n)return;let j=e.metaKey||e.ctrlKey,b=e.shiftKey,N=e.key,C=e.target,S="INPUT"===C.tagName||"TEXTAREA"===C.tagName||C.isContentEditable;if(j&&"k"===N){e.preventDefault(),null===(t=(s=a.current).onOpenPalette)||void 0===t||t.call(s);return}if(!j||"Enter"!==N||!S){if("Escape"===N&&r){e.preventDefault(),null===(i=(l=a.current).onStopGeneration)||void 0===i||i.call(l);return}if(!S||j){if(j&&b&&"c"===N){e.preventDefault(),null===(o=(c=a.current).onCopyLastResponse)||void 0===o||o.call(c);return}if(j&&"n"===N){e.preventDefault(),null===(d=(u=a.current).onNewConversation)||void 0===d||d.call(u);return}if(j&&"u"===N){e.preventDefault(),null===(m=(p=a.current).onUploadFile)||void 0===m||m.call(p);return}if(j&&"."===N){e.preventDefault(),null===(f=(h=a.current).onToggleDeepThinking)||void 0===f||f.call(h);return}if(j&&","===N){e.preventDefault(),null===(g=(x=a.current).onToggleWebSearch)||void 0===g||g.call(x);return}if(j&&"/"===N){e.preventDefault(),null===(v=(k=a.current).onShowShortcuts)||void 0===v||v.call(k);return}if(j&&"i"===N){e.preventDefault(),null===(y=(w=a.current).onFocusInput)||void 0===y||y.call(w);return}}}},[n,r]);(0,o.useEffect)(()=>
1{if(n)return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[n,s])}({onSend:si,onStopGeneration:sp,onNewConversation:sx,onCopyLastResponse:sj,onShowShortcuts:()=>{},onFocusInput:()=>{var e;return null===(e=aS.current)||void 0===e?void 0:e.focus()},onToggleDeepThinking:()=>as(e=>!e),onToggleWebSearch:()=>al(e=>!e)},{enabled:!0,isGenerating:tc});let sI=(()=>{var e,t,n,a,s;let i=(null==ex?void 0:ex.runtimeActions)||[],l=tl.some(e=>"user"===e.role),o=tl[tl.length-1],c=i.some(e=>"context"===e.kind)||(null==ex?void 0:ex.showOptionalContextAdvance)===!0,d=i.some(e=>"context"!==e.kind)&&i.length>0,u=!tc&&(!!d||(c?(null==o?void 0:o.role)==="assistant":l&&(null==o?void 0:o.role)==="assistant"));if((null==ex?void 0:ex.outputReviewAccepted)&&0===i.length)return(0,r.jsx)("div",{className:"rounded-xl border border-border bg-card p-4 shadow-sm",children:(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsx)("p",{className:"text-sm font-medium text-foreground",children:eX("documentSaved")}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:eX("documentSavedDescription")})]})});if(!ex||!u||0===i.length&&!ex.showOptionalContextAdvance)return null;let m=null===(e=ex.availableTools)||void 0===e?void 0:e.some(e=>["files","request_files"].includes(e)),p=null===(t=ex.availableTools)||void 0===t?void 0:t.some(e=>["voice","request_voice"].includes(e)),f=i.length>0?i:[{id:"skip_optional_context",label:eX("continueWithoutMoreContext"),kind:"context",description:eX("optionalContextDescription")}],h=f.some(e=>"task"===e.kind),g=f.some(e=>"evaluation"===e.kind),x=f.some(e=>"action"===e.kind),v=f.some(e=>"output_review"===e.kind),k=h?eX("runtimeGenerateDescription"):g?eX("runtimeEvaluateDescription"):x?(null===(n=f[0])||void 0===n?void 0:n.description)||eX("runtimeActionDescription"):v?(null===(a=f[0])||void 0===a?void 0:a.description)||eX("runtimeOutputReviewDescription"):(null===(s=f[0])||void 0===s?void 0:s.description)||eX("runtimeChooseNextDescription");return(0,r.jsxs)("div",{className:"rounded-xl border border-border bg-card p-4 shadow-sm",children:[(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsx)("p",{className:"text-sm font-medium text-foreground",children:f.some(e=>"task"===e.kind)?eX("readyToGenerate"):f.some(e=>"evaluation"===e.kind)?eX("readyToEvaluate"):f.some(e=>"action"===e.kind)?eX("readyToAct"):f.some(e=>"output_review"===e.kind)?eX("documentReady"):eX("chooseNextStep")}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:k})]}),h&&(0,r.jsxs)("div",{className:"mt-4 flex items-center gap-2",children:[(0,r.jsx)("label",{htmlFor:"workflow-output-language",className:"text-xs text-muted-foreground",children:eX("outputLanguage")}),(0,r.jsxs)("select",{id:"workflow-output-language",value:tv,onChange:e=>tk(e.target.value),className:"h-8 rounded-md border border-input bg-input-bg px-2 text-sm",children:[(0,r.jsx)("option",{value:"no",children:eX("languageNorwegian")}),(0,r.jsx)("option",{value:"en",children:eX("languageEnglish")}),(0,r.jsx)("option",{value:"sv",children:eX("languageSwedish")})]})]}),(0,r.jsxs)("div",{className:"mt-4 flex flex-wrap gap-2",children:[m&&(0,r.jsx)(A.z,{type:"button",variant:"outline",size:"sm",onClick:()=>{var e;return null===(e=ex.onNavigateToTab)||void 0===e?void 0:e.call(ex,"files")},children:eX("yesUploadFile")}),p&&(0,r.jsx)(A.z,{type:"button",variant:"outline",size:"sm",onClick:()=>{var e;return null===(e=ex.onNavigateToTab)||void 0===e?void 0:e.call(ex,"voice")},children:eX("yesUseVoice")}),f.map(e=>(0,r.jsx)(A.z,{type:"button",size:"sm",disabled:ex.runningRuntimeActionId===e.id||"skip_optional_context"===e.id&&ex.isSkippingOptionalContext,onClick:()=>{if(ex.onRuntimeAction){ex.onRuntimeAction(e.id,{outputLanguage:"task"===e.kind?tv:void 0});return}if("skip_optional_context"===e.id){var t;null===(t=ex.onSkipOptionalContext)||void 0===t||t.call(ex)}},children:ex.runningRuntimeActionId===e.id?"task"===e.kind?eX("generating"):eX("updating"):e.label},e.id))]})]})})(),sE=ng.filter(e=>!y(e)&&!k(e,ta)&&e.id!==rS.current),s_=et?"document":"presentation"===ef?"presentation":"worksession";return(0,r.jsx)(tL._N,{children:(0,r.jsxs)("div",{className:(0,m.cn)("flex flex-1 min-h-0 h-full","sidebar"===N&&"bg-card",ec),children:["chat"===N&&C&&e6&&(0,r.jsx)(na.CN,{currentConversationId:ta,currentAIProjectId:e9,onConversationSelect:sv,onNewConversation:(e,t)=>{e&&te(e),t&&au(t),sx()},onAIProjectChange:te,onRefreshRef:aq,onProductionFileClick:T,className:"w-64 flex-shrink-0"}),(0,r.jsxs)("div",{className:(0,m.cn)("flex-1 flex flex-col min-w-0 min-h-0",0!==tl.length||eP?"bg-card":"bg-background"),children:[eq,(0,r.jsx)(O,{hideHeader:eW,effectiveMode:e7,resolvedLayout:N,showSidebar:C,sidebarOpen:e6,onToggleSidebar:()=>e8(!e6),isEditingTitle:aw,editingTitleValue:ab,onEditingTitleValueChange:aN,onSaveTitle:sk,onCancelEditTitle:()=>aj(!1),onStartEditTitle:sy,titleInputRef:aC,conversationTitle:nK,document:et,folderContext:am,headerAction:ei,onOpenCanvas:el,messages:tl,presentationContext:eg,onClearConversation:a9,t:eX}),(0,r.jsx)("div",{role:"log","aria-live":"polite","aria-atomic":"false","aria-relevant":"additions text","aria-busy":tc,"aria-label":eX("chatMessages"),className:"contents",children:(0,r.jsxs)(tr,{conversationId:ta,historyStatus:th.conversationId===ta?th.status:"not-started",hasMessages:tl.length>0,discoveryPending:rp,loadingFallback:U,children:[(0,r.jsx)(tg,{conversationId:ta,recordingSessionId:P,mode:e7}),(0,r.jsx)(e$.H,{messageTarget:R&&D?{conversationId:R,messageId:D}:void 0,messageTargetState:th.conversationId!==ta||"loaded"!==th.status?"loading":rZ.current===ta?"ready":"unavailable",messages:tl,conversationId:ta,isStreaming:tc,className:"flex-1",mode:e7,onEditMessage:sb,onRegenerate:()=>sN(),onRegenerateWithModel:e=>sN(e),renderAfterMessage:aX,renderAtEnd:aY,renderBeforeMessages:aQ,hideEmptyState:eP||eK||null!==aB,isLoadingFirstMessage:a0||eK&&0===tl.length&&tc,forkedWithSummary:nq&&0===tl.length,recentSessions:eD,emptyStateIntentFirst:eF,emptyStateTitle:eO,emptyStateSubtitle:eU,searchableRecentSessions:eM,onSessionClick:eZ,onViewAllSessions:ez,onCoreContextAccept:sc,onCoreContextReject:sd,processingCoreContextProposalId:tH,inputSlot:0!==tl.length||eP||eK||ra?void 0:(0,r.jsxs)("div",{role:"region","aria-label":eX("messageInput"),className:"bg-card border border-border rounded-xl shadow-sm p-2 sm:p-3",children:[eL&&(0,r.jsx)("div",{className:"flex min-h-10 items-center border-b border-border/60 px-1 pb-2 mb-2",children:eL}),(0,r.jsx)(tP,{surface:s_,embedded:!0,value:nc,onChange:np,onSend:si,focusTargetRef
1:aS,onStop:sp,onRecallLastMessage:sC,onReferencePasted:sS,isLoading:tp||r6,isStreaming:tc,model:ty,onModelChange:rl,runtime:G?"vercel":tj,onRuntimeChange:G?void 0:tb,runtimeOptions:re,hideRuntimeSelector:!n9,deepThinking:aa,contextFiles:t_,contextFileTruncations:tO,onAddContextFile:()=>nH(!0),onRemoveContextFile:e=>tR(t=>t.filter(t=>t.id!==e)),onClearAllContextFiles:()=>tR([]),onFilesDropped:sw,pendingUploads:tK,onRemovePendingUpload:e=>tV(t=>t.filter(t=>t.id!==e)),selectedPacks:Y?[]:tX,onRemovePack:e=>tQ(t=>t.filter(t=>t.id!==e)),onOpenPromptLibrary:()=>nB(!0),onOpenSkillPicker:()=>nQ(!0),selectedSkill:r8,selectedSkills:r0,onRemoveSkill:e=>{if(e){for(let t of(r3.current.add(e),[K,...W]))t&&(0,i.XI)({id:e},t)&&r3.current.add(t);r1(t=>t.filter(t=>t.id!==e))}else r9(null)},advancedResearchAvailable:ae.available,advancedResearchUnavailableReason:av,onActivateAdvancedResearch:ay,webSearch:ai,planMode:!G&&ao,onOpenCommandPalette:rf.open,pinnedGoals:n7,onRemovePinnedGoal:e=>{n6(t=>t.filter(t=>t.id!==e)),null==ej||ej(e)},onOpenSlashHelp:e=>{n2(e),n1(!0)},onSlashAutoExecute:sg,placeholder:eX("workPromptPlaceholder"),mode:e7,allowedModelProviders:e5,disableSlashCommands:!!ex,conversationTokens:n8,hasSummary:nq})]}),onConfirmation:a_?e=>{let t=e?eX("confirmYes"):eX("confirmNo");rk.current=t,si()}:void 0,onQuickAction:sT,hideThinkingWidget:!1,thinkingPhase:tc?"thinking":void 0,deepThinkingEnabled:aa,webSearchEnabled:ai,streamStartTime:tu,onExecutionContextAdd:eb,onExecutionOpenDetails:eC,onExecutionSelectForChat:eS})]})}),(0,r.jsx)(eQ,{previewMode:er,hasPendingPatches:aR,onDocumentEdit:en,effectiveMode:e7,pendingPatches:aA,activePatchIndex:aP,onNavigateToPatch:aK,onApplyPatch:aF,onRejectPatch:aO,onApplyAll:aU,onRejectAll:aL,onScrollToSection:aW,canUndo:aM,undoTimeRemaining:az,onUndo:aZ,t:eX}),t2&&(0,r.jsx)("div",{"data-testid":"agent-turn-blocked","data-block-code":t2.code,className:(0,m.cn)("max-w-3xl mx-auto w-full","wide"===e7?"px-4 py-2":"px-2 py-1"),children:(0,r.jsx)(no.be,{message:t2.notice})}),t1&&(0,r.jsxs)("div",{className:(0,m.cn)("max-w-3xl mx-auto w-full","wide"===e7?"px-4 py-2":"px-2 py-1"),children:[(0,r.jsx)(no.be,{message:t1,onRetry:t1===eX("initialSkillLoadFailed")?()=>{t3(null),r5(e=>e+1)}:eK&&"[START]"===rk.current?sl:void 0,onDismiss:t1===eX("initialSkillLoadFailed")?void 0:()=>t3(null)}),t1===eX("initialSkillLoadFailed")&&r4&&(0,r.jsx)("p",{className:"px-3 py-2 text-sm text-muted-foreground break-words",children:r4}),t1===eX("initialSkillLoadFailed")&&(0,r.jsx)(A.z,{type:"button",variant:"ghost",size:"sm",onClick:()=>{for(let e of[K,...W])e&&!r0.some(t=>(0,i.XI)(t,e))&&r3.current.add(e);t3(null),r1(e=>[...e])},children:eX("continueWithoutUnavailableSkill")})]}),ao&&!G&&(0,r.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 bg-amber-500/10 border-t border-amber-500/20 text-amber-700 dark:text-amber-400 text-xs",children:[(0,r.jsx)(nl.Z,{className:"w-3.5 h-3.5 flex-shrink-0"}),(0,r.jsx)("span",{children:eX("planModeReadOnlyBanner")}),(0,r.jsx)("button",{onClick:()=>ac(!1),className:"ml-auto text-amber-600 dark:text-amber-400 hover:text-amber-800 dark:hover:text-amber-200 underline underline-offset-2",children:eX("switchToAgent")})]}),(tl.length>0||eP||eK||ra)&&(0,r.jsx)("div",{role:"region","aria-label":eX("messageInput"),className:(0,m.cn)("bg-muted/30 border-t border-border/30","wide"===e7?"px-4 pb-6 pt-3":"px-2 pb-2 pt-2"),children:(0,r.jsxs)("div",{className:"max-w-3xl mx-auto",children:[sE.length>0&&(0,r.jsxs)("div",{className:"mb-2 space-y-1",children:[(0,r.jsx)("div",{className:"px-1 text-xs text-muted-foreground",children:eX("queueHint",{count:sE.length})}),sE.map(e=>(0,r.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-border/60 bg-muted/40 px-3 py-2 text-sm",children:[(0,r.jsx)("span",{className:"line-clamp-2 flex-1 whitespace-pre-wrap break-words text-foreground/80",children:e.content}),(0,r.jsxs)("div",{className:"flex shrink-0 gap-2",children:[(0,r.jsx)("button",{type:"button",onClick:()=>sf(e.id),className:"text-xs font-medium text-foreground/80 transition-colors hover:text-foreground",title:eX("queueSendNowHint"),children:eX("queueSendNow")}),(0,r.jsx)("button",{type:"button",onClick:()=>sa(e.id),className:"text-xs text-muted-foreground transition-colors hover:text-foreground",children:eX("queueEdit")}),(0,r.jsx)("button",{type:"button",onClick:()=>sr(e.id),className:"text-xs text-muted-foreground transition-colors hover:text-foreground",children:eX("queueDelete")})]})]},e.id))]}),(0,r.jsx)(tF,{featureEnabled:!1,hasVoiceTarget:!!rr,isDocumentMode:!!et,children:(0,r.jsx)(tA,{targetLabel:rr.label,compact:"wide"!==e7,disabled:tc,onEnsureConversation:sm,onVoiceMessage:su})}),sI||(0,r.jsx)(tP,{surface:s_,value:nc,onChange:np,onSend:si,focusTargetRef
1:aS,onStop:sp,onRecallLastMessage:sC,onReferencePasted:sS,isLoading:tp||r6,isStreaming:tc,model:ty,onModelChange:rl,runtime:G?"vercel":tj,onRuntimeChange:G?void 0:tb,runtimeOptions:re,hideRuntimeSelector:!n9,deepThinking:aa,contextFiles:t_,contextFileTruncations:tO,onAddContextFile:()=>nH(!0),onRemoveContextFile:e=>tR(t=>t.filter(t=>t.id!==e)),onClearAllContextFiles:()=>tR([]),onFilesDropped:sw,pendingUploads:tK,onRemovePendingUpload:e=>tV(t=>t.filter(t=>t.id!==e)),selectedPacks:Y?[]:tX,onRemovePack:e=>tQ(t=>t.filter(t=>t.id!==e)),onOpenPromptLibrary:()=>nB(!0),onOpenSkillPicker:()=>nQ(!0),selectedSkill:r8,selectedSkills:r0,onRemoveSkill:e=>{if(e){for(let t of(r3.current.add(e),[K,...W]))t&&(0,i.XI)({id:e},t)&&r3.current.add(t);r1(t=>t.filter(t=>t.id!==e))}else r9(null)},onActivateAdvancedResearch:ay,advancedResearchAvailable:ae.available,advancedResearchUnavailableReason:av,webSearch:ai,planMode:!G&&ao,onOpenCommandPalette:rf.open,pinnedGoals:n7,onRemovePinnedGoal:e=>{n6(t=>t.filter(t=>t.id!==e)),null==ej||ej(e)},onOpenSlashHelp:e=>{n2(e),n1(!0)},onSlashAutoExecute:sg,placeholder:et?eX("documentChatPlaceholder"):eX("generalChatPlaceholder"),mode:e7,allowedModelProviders:e5,disableSlashCommands:!!ex,conversationTokens:n8,hasSummary:nq})]})})]}),(0,r.jsx)(eB,{showContextPicker:nV,onShowContextPickerChange:nH,contextFiles:t_,onContextFilesChange:tR,onContextFilesAdded:$,selectedPacks:tX,onSelectedPacksChange:tQ,showPromptPicker:nJ,onShowPromptPickerChange:nB,onInputChange:np,showSkillPicker:nX,onShowSkillPickerChange:nQ,onSelectedSkillsChange:r1,showGoalsPicker:nY,onShowGoalsPickerChange:n$,pinnedGoals:n7,onPinnedGoalsChange:n6,showSlashHelp:n0,onShowSlashHelpChange:n1,slashHelpQuery:n3,onSlashHelpQueryChange:n2,commandPalette:rf,onNewConversation:sx})]})})}var nM=nL},60037:function(e,t,n){n.d(t,{p:function(){return g}});var r=n(27573),a=n(47200),s=n(7653),i=n(3374),l=n(26798),o=n(16273),c=n(30609),d=n(88623),u=n(79901),m=n(44526),p=n(17515),f=n(13948),h=n(57212);function g(e){let{workflowId:t,instanceId:n,workflowContent:g,contextFiles:x=[],existingVoiceItems:v=[],guide:k,autoGenerateScript:y=!1,compact:w=!1,onComplete:j,onCanvasPreview:b,onNavigateToVoiceTab:N}=e;a.kg.log("\uD83C\uDFA4 [VoiceInterviewModule] Rendering with:",{workflowId:t,instanceId:n,existingVoiceItemsLength:null==v?void 0:v.length,contextFilesLength:null==x?void 0:x.length});
1let[C,S]=(0,s.useState)(!1),[T,I]=(0,s.useState)(!1),[E,_]=(0,s.useState)(""),[A,R]=(0,s.useState)(null),[P,D]=(0,s.useState)(!1),[F,O]=(0,s.useState)(null),[U,L]=(0,s.useState)(!1),[M,Z]=(0,s.useState)(null),[z,K]=(0,s.useState)(null),[W,q]=(0,s.useState)(null),[G,V]=(0,s.useState)(!1),[H,J]=(0,s.useState)(null),B=(0,s.useRef)(null);(0,s.useEffect)(()=>{g||!t||H||(0,i.createClient)().from("workflows").select("definition").eq("workflow_id",t).single().then(e=>{var t,n;let{data:r}=e,s=null==r?void 0:null===(t=r.definition)||void 0===t?void 0:t.modules,i=null==s?void 0:null===(n=s[0])||void 0===n?void 0:n.content;i&&(J(i),a.kg.log("[VoiceInterviewModule] Auto-fetched workflowContent from DB"))})},[t,g,H]);let X=g||H||void 0;(0,s.useEffect)(()=>{if(v&&v.length>0&&!T&&!B.current){let t=[...v].sort((e,t)=>new Date(t.created_at).getTime()-new Date(e.created_at).getTime())[0];if(null==t?void 0:t.payload_ref){var e;R(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t.payload_ref)?t.payload_ref:null),I(!0);let n=(null===(e=t.meta)||void 0===e?void 0:e.transcript)||"";n&&_(n)}}},[null==v?void 0:v.length,T]);let Q=(0,s.useRef)(!1);(0,s.useEffect)(()=>{var e,n;if(!Q.current&&!U){if(v&&v.length>0&&!M&&t&&X){let t=[...v].sort((e,t)=>new Date(t.created_at).getTime()-new Date(e.created_at).getTime())[0],n=null==t?void 0:null===(e=t.meta)||void 0===e?void 0:e.script;if(n){Z(n),Q.current=!0;return}}if(T&&!M&&v&&v.length>0){let e=[...v].sort((e,t)=>new Date(t.created_at).getTime()-new Date(e.created_at).getTime())[0],t=null==e?void 0:null===(n=e.meta)||void 0===n?void 0:n.script;t&&(Z(t),Q.current=!0)}}},[null==v?void 0:v.length,M,t,T,U]);let Y=[z,...x.map(e=>e.content).filter(e=>e.trim().length>0)].filter(Boolean).join("\n\n---\n\n"),$=(0,s.useCallback)(()=>{if(!t||!X||k||U)return;if(M){S(!0);return}V(!0),L(!0),q(null);let e=new AbortController,r=setTimeout(()=>e.abort(),12e4);fetch("/api/voice/generate-script-from-workflow",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workflowContent:X,instanceId:n,contextFiles:x}),signal:e.signal}).then(async e=>{if(!e.ok){var t,n,r;let a=await e.json().catch(()=>({}));if(429===e.status||(null===(t=a.error)||void 0===t?void 0:t.includes("overloaded"))||(null===(n=a.error)||void 0===n?void 0:n.type)==="overloaded_error")throw Error("AI-tjenesten er overbelastet akkurat n\xe5. Vennligst pr\xf8v igjen om noen sekunder.");if(503===e.status)throw Error("AI-tjenesten er midlertidig utilgjengelig. Vennligst pr\xf8v igjen om et \xf8yeblikk.");if(408===e.status)throw Error("Foresp\xf8rselen tok for lang tid. Pr\xf8v igjen eller reduser mengden kontekst.");throw Error((null===(r=a.error)||void 0===r?void 0:r.message)||a.error||a.message||"Kunne ikke generere intervju-script")}return e.json()}).then(e=>{var t,n;if(e.error){let n="string"==typeof e.error?{message:e.error}:e.error;if("overloaded_error"===n.type||(null===(t=n.message)||void 0===t?void 0:t.includes("overloaded")))throw Error("AI-tjenesten er overbelastet akkurat n\xe5. Vennligst pr\xf8v igjen om noen sekunder.");throw Error(e.message||n.message||("string"==typeof e.error?e.error:"Kunne ikke generere intervju-script"))}if(e.script)Z(e.script),K("string"==typeof(null===(n=e.contextCapsule)||void 0===n?void 0:n.markdown)?e.contextCapsule.markdown:null);else throw Error("No script returned from API")}).catch(e=>{clearTimeout(r),a.kg.error("Failed to generate interview script:",e),q("AbortError"===e.name?"Foresp\xf8rselen tok for lang tid (over 2 minutter). Pr\xf8v igjen - dette kan skyldes midlertidig overbelastning.":e instanceof Error?e.message:"Kunne ikke generere intervju-script"),V(!1)}).finally(()=>{clearTimeout(r),L(!1)})},[t,X,k,U,M,n,x]),ee=(0,s.useRef)(!1);(0,s.useEffect)(()=>{!y||ee.current||U||M||T||!t||!X||k||(a.kg.log("\uD83C\uDFAF [VoiceInterviewModule] Auto-generating script triggered by ACTION tag"),ee.current=!0,$())},[y,U,M,T,t,X,k,$]),(0,s.useEffect)(()=>{!M||U||C||T||P||F||S(!0)},[M,U,C,T,P,F]);let et=(0,s.useCallback)(async e=>{D(!0),O(null);
1try{if(!t||!n)throw Error("Workflow-instansen mangler. Transkripsjonen er ikke lagret.");let r=await fetch("/api/workflows/".concat(t,"/promote-voice"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({completionId:e.completionId,instanceId:n,key:"voice_interview_transcript",transcript:e.transcript,manualInsights:null})});if(!r.ok){let e=await r.json().catch(()=>null);throw Error((null==e?void 0:e.error)||"Transkripsjonen kunne ikke kobles til workflowen. Pr\xf8v igjen.")}B.current=null,I(!0),null==j||j(e.transcript)}catch(e){throw O(e instanceof Error?e.message:"Transkripsjonen kunne ikke kobles til workflowen. Pr\xf8v igjen."),e}finally{D(!1)}},[n,j,t]),en=async e=>{S(!1),I(!1);let n=(null==e?void 0:e.transcript)?e.transcript.map(e=>"".concat("ai"===e.speaker?"AI":"You",": ").concat(e.content)).join("\n\n"):"[Intervju gjennomf\xf8rt - transkripsjon ikke tilgjengelig]";if(_(n),t&&n){let e={completionId:crypto.randomUUID(),transcript:n};B.current=e,await et(e).catch(e=>{a.kg.error("Error saving workflow transcript:",e)});return}I(!0),null==j||j(n)};if(C&&M)return(0,r.jsx)("div",{className:"w-full",children:(0,r.jsx)("div",{className:w?"overflow-hidden":"border rounded-lg overflow-hidden",children:(0,r.jsx)(f.InterviewSessionV2,{script:M,language:"nb-NO",contextFile:Y||void 0,voiceId:h.L.ELEVENLABS_VOICE_ID,onComplete:en})})});if(P)return(0,r.jsxs)("div",{className:"flex items-center gap-2 rounded-md border p-3 text-sm",children:[(0,r.jsx)(p.Gl,{}),"Lagrer transkripsjonen i workflow-konteksten…"]});if(F&&B.current)return(0,r.jsxs)("div",{className:"space-y-3 rounded-md border border-destructive/40 p-3",role:"alert",children:[(0,r.jsxs)("div",{className:"flex items-start gap-2 text-sm text-destructive",children:[(0,r.jsx)(c.Z,{className:"mt-0.5 h-4 w-4 shrink-0"}),(0,r.jsx)("span",{children:F})]}),(0,r.jsxs)(o.z,{variant:"outline",size:"sm",onClick:()=>{let e=B.current;e&&et(e).catch(e=>{a.kg.error("Error retrying workflow transcript save:",e)})},children:[(0,r.jsx)(d.Z,{className:"mr-1.5 h-3.5 w-3.5"}),"Pr\xf8v lagring p\xe5 nytt"]})]});if(T){let e=(0,r.jsxs)("div",{className:w?"space-y-2":"space-y-3",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(u.Z,{className:w?"h-3.5 w-3.5 text-green-600":"h-4 w-4 text-green-600"}),(0,r.jsx)("span",{className:w?"text-xs font-medium":"text-sm font-medium",children:"Intervju Fullf\xf8rt"})]}),(0,r.jsx)("p",{className:w?"text-[11px] text-muted-foreground":"text-xs text-muted-foreground",children:"Transkripsjon er lagret og vil bli brukt i strategiprosessen."}),A&&(w?N:b)&&(0,r.jsx)(o.z,{variant:"outline",className:w?"w-full h-7 text-xs":"w-full",size:"sm",onClick:()=>{w&&N?N():b&&fetch("/api/library/files/".concat(A)).then(e=>e.json()).then(e=>{if(e.file&&b){let t=e.file.content||E;!/<[^>]+>/.test(t)&&t.includes("\n")&&(t=t.split(/\n\n+/).filter(e=>e.trim()).map(e=>"<p>".concat(e.trim().replace(/\n/g,"<br>"),"</p>")).join("")),b({title:e.file.name,content:t,fileId:A,sourceType:null})}}).catch(e=>{a.kg.error("Failed to fetch file for preview:",e),b&&b({title:"Voice Interview Transcript",content:E,fileId:A,sourceType:null})})},children:w?"Se transkripsjon →":"\xc5pne transkripsjon"}),(0,r.jsxs)(o.z,{variant:"outline",className:w?"w-full h-7 text-xs":"w-full",size:"sm",onClick:()=>{M?(S(!0),I(!1)):$()},children:[(0,r.jsx)(m.Z,{className:w?"mr-1 h-3 w-3":"mr-1.5 h-3.5 w-3.5"}),"Ta intervjuet p\xe5 nytt"]})]});return w?e:(0,r.jsxs)(l.Zb,{className:"border",children:[(0,r.jsx)(l.Ol,{className:"pb-3",children:(0,r.jsxs)(l.ll,{className:"flex items-center gap-2 text-sm",children:[(0,r.jsx)(u.Z,{className:"h-4 w-4"}),"Intervju Fullf\xf8rt"]})}),(0,r.jsx)(l.aY,{children:e})]})}let er=(0,r.jsxs)("div",{className:w?"space-y-2":"space-y-3",children:[!w&&(0,r.jsxs)("div",{className:"p-2 bg-muted rounded-md",children:[(0,r.jsx)("p",{className:"font-semibold mb-1 text-xs",children:"Slik fungerer det:"}),(0,r.jsx)("ul",{className:"list-disc pl-4 space-y-0.5 text-muted-foreground text-xs leading-relaxed",children:y?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("li",{children:"Script-generering starter automatisk (tar 20-30 sekunder)"}),(0,r.jsx)("li",{children:"N\xe5r scriptet er klart, starter intervjuet automatisk"}),(0,r.jsx)("li",{children:"AI stiller sp\xf8rsm\xe5l med stemme - svar naturlig"}),(0,r.jsx)("li",{children:"Intervjuet tar ca. 10-15 minutter"})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("li",{children:'Klikk "Klargj\xf8r intervju" for \xe5 generere script (tar 20-30 sekunder)'}),(0,r.jsx)("li",{children:"N\xe5r scriptet er klart, starter intervjuet automatisk"}),(0,r.jsx)("li",{children:"AI stiller sp\xf8rsm\xe5l med stemme - svar naturlig"}),(0,r.jsx)("li",{children:"Intervjuet tar ca. 10-15 minutter"})]})})]}),U&&(0,r.jsxs)("div",{className:w?"flex items-center gap-2":"p-2 bg-muted rounded-md text-xs space-y-1",children:[(0,r.jsx)(p.Gl,{size:"sm"}),(0,r.jsx)("span",{className:w?"text-[11px] text-muted-foreground":"font-medium",children:w?"Genererer script...":"Genererer intervju-script..."}),!w&&(0,r.jsx)("p",{className:"text-muted-foreground pl-5",children:"Dette tar vanligvis 20-30 sekunder. Vennligst vent mens vi lager sp\xf8rsm\xe5lene."})]}),W&&(0,r.jsxs)("div",{className:w?"space-y-1.5":"p-2 bg-muted rounded-md text-xs border border-destructive/50 space-y-2",children:[(0,r.jsxs)("p",{className:w?"text-[11px] text-destructive":"text-muted-foreground text-xs",children:[w?"Feil: ":"",W]}),(0,r.jsx)(o.z,{variant:"outline",size:"sm",onClick:$,className:w?"w-full h-7 text-xs":"w-full",children:"Pr\xf8v igjen"})]}),M&&!U&&!W&&(0,r.jsx)("div",{className:w?"":"p-2 bg-muted rounded-md",children:(0,r.jsx)("p",{className:w?"text-[11px] text-muted-foreground":"text-muted-foreground text-xs",children:w?"Script klart - starter...":"Intervju-script er klart. Intervjuet starter automatisk..."})}),!G&&!M&&!U&&(0,r.jsxs)(o.z,{onClick:$,className:w?"w-full h-8":"w-full",size:"sm",disabled:!t||!X||!!k||U,children:[(0,r.jsx)(m.Z,{className:w?"mr-1 h-3 w-3":"mr-1.5 h-3.5 w-3.5"}),"Klargj\xf8r intervju"]})]});return w?er:(0,r.jsxs)(l.Zb,{className:"border",children:[(0,r.jsx)(l.Ol,{className:"pb-3",children:(0,r.jsxs)(l.ll,{className:"flex items-center gap-2 text-sm",children:[(0,r.jsx)(m.Z,{className:"w-4 h-4"}),"Voice Intervju"]})}),(0,r.jsx)(l.aY,{children:er})]})}},81236:function(e,t,n){n.r(t),n.d(t,{CreateFolderDialog:function(){return g}});var r=n(27573),a=n(47200),s=n(7653),i=n(17022),l=n(12198),o=n(93739),c=n(17515),d=n(16273),u=n(98521),m=n(63769),p=n(99696),f=n(13040),h=n(59971);function g(e){let{open:t,onOpenChange:n,workspaceId:g,projectId:x,defaultParentId:v=null,onSuccess:k,onCreateAndConfigure:y,existingFolders:w=[],showParentSelector:j=!0,showConfigureOption:b=!1}
1=e,[N,C]=(0,s.useState)(""),[S,T]=(0,s.useState)(v),[I,E]=(0,s.useState)(!1),[_,A]=(0,s.useState)(w),[R,P]=(0,s.useState)(!1);(0,s.useEffect)(()=>{t&&(C(""),T(v),0===w.length&&j?D():A(w))},[t,v,w,j]);let D=(0,s.useCallback)(async()=>{if(g&&x){P(!0);try{let e=await fetch("/api/production/folders?workspace_id=".concat(g,"&project_id=").concat(x));if(e.ok){let t=await e.json();A(t.folders||[])}}catch(e){a.kg.error("Error loading folders:",e)}finally{P(!1)}}},[g,x]),F=async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(N.trim()&&g&&x){E(!0);try{let t=await fetch("/api/production/folders",{method:"POST",headers:{"Content-Type":"application/json",...(0,h.p)()},body:JSON.stringify({workspace_id:g,project_id:x,name:N.trim(),parent_id:S})});if(!t.ok){let e=await t.json();throw Error(e.error||"Failed to create folder")}let r=await t.json(),a={id:r.folder.id,name:r.folder.name};n(!1),e&&y?y(a):null==k||k(a)}catch(e){a.kg.error("Error creating folder:",e),alert(e.message||"Failed to create folder")}finally{E(!1)}}},O=e=>{let t=0,n=new Set([e.id]),r=e;for(;r.parent_id&&!n.has(r.parent_id);){t++;let e=_.find(e=>e.id===r.parent_id);if(!e)break;n.add(e.id),r=e}return t};return(0,r.jsx)(u.Vq,{open:t,onOpenChange:n,children:(0,r.jsxs)(u.cZ,{className:"sm:max-w-[450px]",children:[(0,r.jsxs)(u.fK,{children:[(0,r.jsx)(u.$N,{children:S?"Opprett undermappe":"Ny mappe"}),(0,r.jsx)(u.Be,{children:"Opprett en mappe for \xe5 organisere filene dine."})]}),(0,r.jsxs)("div",{className:"space-y-4 py-3",children:[(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)(p._,{htmlFor:"folder-name",children:"Mappenavn"}),(0,r.jsx)(m.I,{id:"folder-name",placeholder:"Research, Utkast, etc.",value:N,onChange:e=>C(e.target.value),autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&N.trim()&&F(!1)},disabled:I})]}),j&&_.length>0&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)(p._,{htmlFor:"parent-folder",children:"Overordnet mappe"}),(0,r.jsxs)(f.Ph,{value:S||"root",onValueChange:e=>T("root"===e?null:e),disabled:I||R,children:[(0,r.jsx)(f.i4,{id:"parent-folder",children:(0,r.jsx)(f.ki,{placeholder:"Velg mappe"})}),(0,r.jsxs)(f.Bw,{children:[(0,r.jsx)(f.Ql,{value:"root",children:(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)(i.Z,{className:"h-4 w-4"}),"Root level"]})}),_.map(e=>{let t=O(e);return(0,r.jsx)(f.Ql,{value:e.id,children:(0,r.jsxs)("span",{className:"flex items-center gap-2",style:(0,o.sj)(t,{base:0,step:12}),children:[(0,r.jsx)(i.Z,{className:"h-4 w-4"}),e.name]})},e.id)})]})]}),(0,r.jsx)("p",{className:"text-xs text-muted-foreground",children:"Opprett denne mappen inne i en annen mappe"})]})]}),(0,r.jsx)(u.cN,{className:"flex-col gap-2 sm:gap-2",children:(0,r.jsxs)("div",{className:"flex flex-col-reverse sm:flex-row gap-2 w-full",children:[(0,r.jsx)(d.z,{variant:"outline",onClick:()=>n(!1),disabled:I,className:"sm:flex-shrink-0",children:"Avbryt"}),(0,r.jsxs)("div",{className:"flex flex-col sm:flex-row gap-2 flex-1 sm:justify-end",children:[b&&y&&(0,r.jsxs)(d.z,{variant:"outline",onClick:()=>F(!0),disabled:!N.trim()||I,className:"gap-1.5",children:[I&&(0,r.jsx)(c.Gl,{}),(0,r.jsx)(l.Z,{className:"h-4 w-4"}),(0,r.jsx)("span",{className:"hidden sm:inline",children:"Opprett og konfigurer"}),(0,r.jsx)("span",{className:"sm:hidden",children:"Konfigurer"})]}),(0,r.jsxs)(d.z,{onClick:()=>F(!1),disabled:!N.trim()||I,children:[I&&(0,r.jsx)(c.Gl,{className:"mr-2"}),"Opprett"]})]})]})})]})})}},22579:function(e,t,n){n.d(t,{V:function(){return j}});var r=n(27573),a=n(47200),s=n(7653),i=n(3458),l=n(81695),o=n(77930),c=n(38983),d=n(87354),u=n(3172),m=n(17515),p=n(19369),f=n(16273),h=n(98521),g=n(63769),x=n(99696),v=n(76225),k=n(808),y=n(98810),w=n(46393);function j(){let{onBeforeWorkspaceSwitch:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{workspace:t,workspaces:n,setActiveWorkspace:j,refreshWorkspaces:b,isLoading:N,loadFailed:C}=(0,k.c)(),{currentProject:S}=(0,y.P)(),T=(0,w.T)("production"),I=(0,l.usePathname)(),E=(0,l.useRouter)(),_=(0,l.useSearchParams)(),A=(0,o.NL)(),[R,P]=(0,s.use
1State)(!1),[D,F]=(0,s.useState)(!1),[O,U]=(0,s.useState)(""),[L,M]=(0,s.useState)(""),[Z,z]=(0,s.useState)(!1),K=(0,s.useRef)(null),W=(0,s.useRef)(null),[q,G]=(0,s.useState)({top:0,left:0,width:0}),V=(null==t?void 0:t.name)||(C?T("workspaceSwitcherLoadFailed"):"Select workspace..."),H=(0,s.useCallback)(()=>{if(K.current){let e=K.current.getBoundingClientRect();G({top:e.bottom+4,left:e.left,width:Math.max(e.width,300)})}},[]),J=(0,s.useCallback)(async n=>{var r;let a=null==t?void 0:t.id;if(a!==n&&(null==e||e(n)),j(n),P(!1),a&&a!==n){let e=e=>e.queryKey.some(e=>e===a||"object"==typeof e&&null!==e&&("workspaceId"in e||"workspace_id"in e)&&(e.workspaceId===a||e.workspace_id===a));await A.cancelQueries({predicate:e}),A.removeQueries({predicate:e})}let s=new URLSearchParams(null!==(r=null==_?void 0:_.toString())&&void 0!==r?r:"");s.set("workspace_id",n),s.has("workspace")&&s.set("workspace",n),"/production/sessions"===I&&(s.delete("conversation"),s.delete("folder"),s.set("new","true"));let i=(null!=I?I:"").replace(/^\/production\/workspaces\/[^/]+/,"/production/workspaces/".concat(encodeURIComponent(n))),l=s.toString();E.replace("".concat(i).concat(l?"?".concat(l):""),{scroll:!1}),requestAnimationFrame(()=>{var e;return null===(e=K.current)||void 0===e?void 0:e.focus()})},[e,I,A,E,_,j,null==t?void 0:t.id]);(0,s.useEffect)(()=>{R&&H()},[R,H]),(0,s.useEffect)(()=>{let e=e=>{let t=e.target;W.current&&!W.current.contains(t)&&K.current&&!K.current.contains(t)&&P(!1)};if(R)return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[R]);let B=async()=>{if(O.trim()&&(null==S?void 0:S.id)){z(!0);try{let e=await fetch("/api/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project_id:S.id,name:O.trim(),description:L.trim()||null})});if(!e.ok){let t=await e.json();throw Error(t.error||"Failed to create workspace")}let t=await e.json();await b(),await J(t.workspace.id),F(!1),U(""),M("")}catch(e){a.kg.error("Error creating workspace:",e),alert(e.message||"Failed to create workspace")}finally{z(!1)}}};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsxs)(f.z,{ref:K,variant:"outline",className:"w-full min-w-0 justify-between",onClick:()=>{P(!R)},disabled:N,children:[(0,r.jsx)("span",{className:(0,p.cn)("min-w-0 flex-1 truncate text-left",C&&"text-status-gap-foreground"),title:V,children:V}),(0,r.jsx)(c.Z,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]}),R&&"undefined"!=typeof document&&(0,i.createPortal)((0,r.jsxs)("div",{ref:W,className:"fixed bg-popover text-popover-foreground rounded-md border shadow-md p-1 z-[99999]",style:{to
1p:q.top,left:q.left,width:q.width},children:[C&&(0,r.jsxs)("div",{className:"px-2 py-1.5",children:[(0,r.jsx)("p",{className:"text-sm text-status-gap-foreground",children:T("workspaceSwitcherLoadFailed")}),(0,r.jsx)("button",{onClick:()=>void b(),className:"mt-1 text-xs underline text-muted-foreground hover:text-foreground",children:T("workspaceSwitcherRetry")})]}),n.map(e=>(0,r.jsxs)("button",{onClick:()=>void J(e.id),className:"flex items-center gap-2 w-full rounded-sm px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground cursor-pointer text-left",children:[(0,r.jsx)(d.Z,{className:(0,p.cn)("h-4 w-4 shrink-0",(null==t?void 0:t.id)===e.id?"opacity-100":"opacity-0")}),(0,r.jsxs)("div",{className:"flex flex-col flex-1 min-w-0",children:[(0,r.jsx)("span",{className:"min-w-0 truncate font-medium",title:e.name,children:e.name}),e.description&&(0,r.jsx)("span",{className:"text-xs text-muted-foreground truncate",children:e.description})]})]},e.id)),(0,r.jsx)("div",{className:"bg-border h-px my-1 -mx-1"}),(0,r.jsxs)("button",{onClick:()=>{P(!1),F(!0)},className:"flex items-center gap-2 w-full rounded-sm px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground cursor-pointer text-left",children:[(0,r.jsx)(u.Z,{className:"h-4 w-4"}),"New Workspace"]})]}),document.body)]}),(0,r.jsx)(h.Vq,{open:D,onOpenChange:F,children:(0,r.jsxs)(h.cZ,{children:[(0,r.jsxs)(h.fK,{children:[(0,r.jsx)(h.$N,{children:"Create New Workspace"}),(0,r.jsx)(h.Be,{children:"Add a new workspace to organize your production files."})]}),(0,r.jsxs)("div",{className:"space-y-4 py-4",children:[(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)(x._,{htmlFor:"name",children:"Name"}),(0,r.jsx)(g.I,{id:"name",placeholder:"Research, Campaign 2024, etc.",value:O,onChange:e=>U(e.target.value),autoFocus:!0})]}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)(x._,{htmlFor:"description",children:"Description (optional)"}),(0,r.jsx)(v.g,{id:"description",placeholder:"What will you use this workspace for?",value:L,onChange:e=>M(e.target.value),rows:3})]})]}),(0,r.jsxs)(h.cN,{children:[(0,r.jsx)(f.z,{variant:"outline",onClick:()=>F(!1),disabled:Z,children:"Cancel"}),(0,r.jsxs)(f.z,{onClick:B,disabled:!O.trim()||Z,children:[Z&&(0,r.jsx)(m.Gl,{className:"mr-2"}),"Create Workspace"]})]})]})})]})}},82626:function(e,t,n){n.d(t,{I9:function(){return en},Ry:function(){return ec},cR:function(){return E},fX:function(){return ea},Kg:function(){return F},ZU:function(){return W},_N:function(){return h},ao:function(){return Q},Sp:function(){return G},kI:function(){return L}});var r=n(47200);let a=new Map;function s(e,t){let n=a.get(e.id);if(n&&!(null==t?void 0:t.override)){r.kg.warn('[ToolRegistry] Tool "'.concat(e.id,'" already registered. ')+"Use { override: true } to replace it.");return}n&&(null==t?void 0:t.override)&&r.kg.info('[ToolRegistry] Overriding tool "'.concat(e.id,'"')),a.set(e.id,e)}function i(e){return a.get(e)}function l(e){return Array.from(a.values()).filter(t=>t.contexts.includes(e)||t.contexts.includes("global"))}function o(){return Array.from(a.values())}function c(e){return a.has(e)}function d(e){for(let t of Array.from(a.values()))if(t&&t.aiTriggerable&&t.actionPattern){let n=e.match(t.actionPattern);if(n)return{tool:t,match:n}}}var u=n(27573),m=n(7653);let p=[{id:"text-paste",name:"Lim inn tekst",description:"Lim inn tekst som kontekst for AI",icon:"type",contexts:["universal-chat","global"],aiTriggerable:!0,actionPattern:/\[ACTION:TEXT_PASTE:START\]/},{id:"voice-recording",name:"Lydopptak",description:"Ta opp stemme og transkriber til tekst",icon:"mic",contexts:["universal-chat","global"],aiTriggerable:!0,actionPattern:/\[ACTION:VOICE_RECORD:START\]/},{id:"voice-interview",name:"Stemmeintervju",description:"AI-styrt stemmeintervju med transkripsjon",icon:"mic-vocal",contexts:["universal-chat","workflow-v3","global"],aiTriggerable:!0,actionPattern:/\[ACTION:INTERVIEW:START\]/},{id:"video-capture",name:"Video",description:"Transkriber YouTube-videoer eller videofiler",icon:"video",contexts:["universal-chat","global"],aiTriggerable:!0,actionPattern:/\[ACTION:VIDEO_
1CAPTURE:START\]/},{id:"audio-capture",name:"Lyd",description:"Transkriber lydfiler",icon:"audio-lines",contexts:["universal-chat","global"],aiTriggerable:!0,actionPattern:/\[ACTION:AUDIO_CAPTURE:START\]/},{id:"pdf-capture",name:"PDF",description:"Ekstraher tekst fra PDF-filer med AI OCR",icon:"file-text",contexts:["universal-chat","global"],aiTriggerable:!0,actionPattern:/\[ACTION:PDF_CAPTURE:START\]/},{id:"document-capture",name:"Dokument",description:"Ekstraher tekst fra DOCX, PPTX og andre dokumenter",icon:"file",contexts:["universal-chat","global"],aiTriggerable:!0,actionPattern:/\[ACTION:DOCUMENT_CAPTURE:START\]/},{id:"file-analyzer",name:"Analyser",description:"AI-analyse av dokumenter med egne instruksjoner eller skills",icon:"file-search",contexts:["universal-chat","global"],aiTriggerable:!0,actionPattern:/\[ACTION:FILE_ANALYZE:START\]/}],f=(0,m.createContext)(null);function h(e){let{children:t,onWidgetExpand:n,onWidgetCollapse:a,onActionProcessed:h}=e,[g,x]=(0,m.useState)([]),[v,k]=(0,m.useState)(),y=(0,m.useRef)(!1),w=(0,m.useMemo)(()=>({register:s,get:i,getForContext:l,getAll:o,has:c,findByAction:e=>{var t;return null===(t=d(e))||void 0===t?void 0:t.tool}}),[]);(0,m.useEffect)(()=>{y.current||(!function(e,t){for(let t of e)s(t,void 0)}(p),r.kg.info("[CaptureTools] Registered",p.length,"capture tools"),y.current=!0)},[]);let j=(0,m.useCallback)((e,t,n)=>{let r=function(e){let t=Date.now(),n=Math.random().toString(36).substring(2,9);return"".concat(e,"-").concat(t,"-").concat(n)}(e),a={id:r,toolId:e,status:"idle",startedAt:new Date},s={id:r,toolId:e,state:a,config:t,position:n};return x(e=>[...e,s]),r},[]),b=(0,m.useCallback)(e=>{x(t=>t.filter(t=>t.id!==e)),k(t=>t===e?void 0:t)},[]),N=(0,m.useCallback)((e,t)=>{x(n=>n.map(n=>n.id===e?{...n,state:{...n.state,...t}}:n))},[]),C=(0,m.useCallback)(e=>{k(e);let t=g.find(t=>t.id===e);t&&n&&n(e,t.toolId)},[g,n]),S=(0,m.useCallback)(e=>{v===e&&(k(void 0),null==a||a(e))},[v,a]),T=(0,m.useCallback)(e=>g.find(t=>t.id===e),[g]),I=(0,m.useCallback)(e=>{let t=d(e);if(!t)return!1;let{tool:n,match:r}=t,a={};r.length>1&&(a.matchGroups=r.slice(1),r[1]&&(a.param=r[1]));let s=j(n.id,a);return null==h||h(n.id,s),!0},[j,h]),E=(0,m.useMemo)(()=>({widgets:g,addWidget:j,removeWidget:b,updateWidgetState:N,expandWidget:C,collapseWidget:S,getWidget:T,registry:w,processAction:I,expandedWidgetId:v}),[g,j,b,N,C,S,T,w,I,v]);return(0,u.jsx)(f.Provider,{value:E,children:t})}var g=n(2756),x=n(56692),v=n(30609),k=n(90324),y=n(10997),w=n(39937),j=n(670),b=n(16273),N=n(4230),C=n(4520),S=n(19369),T=n(59971),I=n(26918);function E(e){let{onFilesUploaded:t,onFileRemoved:n,onExpand:a,onCancel:s,instanceId:i,workflowId:l,projectId:o,maxSizeMB:c=100,accept:d=".pdf,.docx,.doc,.txt,.md,.csv,.xlsx,.xls,.pptx,.ppt",initialFiles:p=[],status:f,className:h,uploadEndpoint:E="/api/library/files/upload"}=e,[_,A]=(0,m.useState)(p),[R,P]=(0,m.useState)(!1),[D,F]=(0,m.useState)(0),[O,U]=(0,m.useState)(null),[L,M]=(0,m.useState)(!1),[Z,z]=(0,m.useState)(!1);(0,m.useEffect)(()=>{p.length>0&&A(p)},[p]);let K=O?"error":R?"running":_.length>0?"completed":f||"idle",W=O||(R?"Laster opp...":_.length>0?"".concat(_.length," fil").concat(_.length>1?"er":""," lastet opp"):void 0),q=(0,m.useCallback)(async e=>{P(!0),F(0),U(null);let n=e.length,a={count:0};try{let s=e.map(async(e,t)=>{var s,c,d;if(!e)return null;let u=e.name.toLowerCase(),m=u.endsWith(".md")||u.endsWith(".txt")||u.endsWith(".json")||u.endsWith(".markdown")||u.endsWith(".text"),p=m||e.type.startsWith("text/")||"application/json"===e.type||"application/octet-stream"===e.type||""===e.type;if(r.kg.log("[FileUploadWidget] Processing ".concat(e.name,', type: "').concat(e.type,'", extension match: ').concat(m,", isText: ").concat(p)),l&&i&&p){let o;try{o=await e.text(),r.kg.log("[FileUploadWidget] Read file content for ".concat(e.name,", length: ").concat(o.length))}catch(t){return r.kg.error("[FileUploadWidget] Failed to read file ".concat(e.name,":"),t),null}let c=e.name.replace(/\.[^.]+$/,"").replace(/[^\w\s-]/g,"_").trim();r.kg.log("[FileUploadWidget] Uploading ".concat(e.name," with key: ").concat(c));let d=await fetch("/api/workflows/".concat(l,"/upload-file"),{method:"POST",headers:{"Content-Type":"application/json",...(0,T.p)()},body:JSON.stringify({fileContent:o,fileName:e.name,instanceId:i,suggestedKey:c,createNewVersion:!0})});if(a.count++,F(Math.round(a.count/n*100)),!d.ok){let t=await d.json().catch(()=>({}));return r.kg.error("[FileUploadWidget] Failed to upload ".concat(e.name,":"),{status:d.status,statusText:d.statusText,error:t}),null}let u=await d.json();return{id:(null===(s=u.contextItem)||void 0===s?void 0:s.id)||"file-".concat(Date.now(),"-").concat(t),name:e.name,size:e.size,uploadedAt:new Date}}if(l&&i){let s;let o=e.name.toLowerCase().split(".").pop();if(["pdf","docx"].includes(o||"")){let t=await new Promise((t,n)=>{let r=new FileReader;r.onload=()=>
1t(r.result),r.onerror=n,r.readAsDataURL(e)});s=(await (0,I.LO)(t,e.name)).text}else s=await e.text();let d=e.name.replace(/\.[^.]+$/,"").replace(/[^\w\s-]/g,"_").trim(),u=await fetch("/api/workflows/".concat(l,"/upload-file"),{method:"POST",headers:{"Content-Type":"application/json",...(0,T.p)()},body:JSON.stringify({fileContent:s,fileName:e.name,instanceId:i,suggestedKey:d,createNewVersion:!0})});if(a.count++,F(Math.round(a.count/n*100)),!u.ok){let t=await u.json().catch(()=>({}));return r.kg.error("[FileUploadWidget] Failed to upload ".concat(e.name,":"),{status:u.status,error:t}),null}let m=await u.json();return{id:(null===(c=m.contextItem)||void 0===c?void 0:c.id)||"file-".concat(Date.now(),"-").concat(t),name:e.name,size:e.size,uploadedAt:new Date}}{let s=new FormData;s.append("file",e),i&&s.append("instanceId",i),o&&s.append("projectId",o);let l=await fetch("/api/library/files",{method:"POST",headers:(0,T.p)(),body:s});if(a.count++,F(Math.round(a.count/n*100)),!l.ok){let t=await l.json().catch(()=>({}));return r.kg.error("Failed to upload ".concat(e.name,":"),t),null}let c=await l.json();return{id:c.id||(null===(d=c.file)||void 0===d?void 0:d.id)||"file-".concat(Date.now(),"-").concat(t),name:e.name,size:e.size,uploadedAt:new Date}}}),c=(await Promise.all(s)).filter(e=>null!==e);if(c.length>0){let e=[..._,...c];A(e),F(100),r.kg.log("[FileUploadWidget] Calling onFilesUploaded with",c.length,"new files"),null==t||t(c)}else e.length>0&&U("Ingen filer ble lastet opp")}catch(e){r.kg.error("Upload error:",e),U(e instanceof Error?e.message:"Opplasting feilet")}finally{P(!1),F(0)}},[i,l,o,_,t]),G=(0,m.useCallback)(e=>{let r=_.filter(t=>t.id!==e);A(r),U(null),null==n||n(e),null==t||t(r)},[_,n,t]),V=(0,m.useCallback)(()=>{P(!1),F(0),U(null),null==s||s()},[s]),H=(0,m.useCallback)(()=>{U(null)},[]),J=(0,m.useCallback)(async e=>{if(!l||!i){U("Mangler workflow/instance ID for \xe5 legge til filer");return}if(0===e.length){M(!1);return}z(!0),U(null);try{let n=await fetch("/api/workflows/".concat(l,"/add-library-files"),{method:"POST",headers:{"Content-Type":"application/json",...(0,T.p)()},body:JSON.stringify({instanceId:i,fileIds:e.map(e=>e.id)})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error||"Kunne ikke legge til filer fra bibliotek")}let a=await n.json();if(a.contextItems&&a.contextItems.length>0){let e=a.contextItems.map(e=>{var t;return{id:e.id,name:(null===(t=e.meta)||void 0===t?void 0:t.file_name)||"Ukjent fil",size:0,uploadedAt:new Date}}),n=[..._,...e];A(n),null==t||t(n)}a.errors&&a.errors.length>0&&r.kg.warn("Some files failed to add:",a.errors),M(!1)}catch(e){r.kg.error("Library select error:",e),U(e instanceof Error?e.message:"Kunne ikke legge til filer")}finally{z(!1)}},[l,i,_,t]),B=e=>e<1024?"".concat(e," B"):e<1048576?"".concat((e/1024).toFixed(1)," KB"):"".concat((e/1048576).toFixed(1)," MB");return(0,u.jsxs)(g.C,{icon:(0,u.jsx)(x.Z,{className:"h-4 w-4"}),title:"FILER",status:K,progress:R?D:void 0,statusMessage:W,onExpand:a,onCancel:R?V:void 0,onDismiss:O?H:void 0,className:h,children:[O&&(0,u.jsxs)("div",{className:"flex items-center gap-2 mb-3 p-2 rounded bg-muted text-sm text-muted-foreground",children:[(0,u.jsx)(v.Z,{className:"h-4 w-4 flex-shrink-0"}),(0,u.jsx)("span",{className:"flex-1",children:O}),(0,u.jsx)(b.z,{variant:"ghost",size:"sm",className:"h-6 px-2",onClick:H,children:"Pr\xf8v igjen"})]}),_.length>0&&(0,u.jsx)("div",{className:"space-y-1.5 mb-3",children:_.map(e=>(0,u.jsxs)("div",{className:"flex items-center justify-between py-1.5 px-2 rounded bg-muted/50 text-sm group",children:[(0,u.jsxs)("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[(0,u.jsx)(k.Z,{className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),(0,u.jsx)("span",{className:"truncate flex-1",children:e.name}),(0,u.jsx)("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:B(e.size)})]}),(0,u.jsx)(b.z,{variant:"ghost",size:"icon",className:"h-6 w-6 flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>G(e.id),title:"Fjern fil",children:(0,u.jsx)(y.Z,{className:"h-3 w-3"})})]},e.id))}),(0,u.jsx)("div",{className:(0,S.cn)("transition-opacity",R&&"opacity-50 pointer-events-none"),children:(0,u.jsx)(N.d,{accept:d,maxSizeMB:c,multiple:!0,onFilesSelect:q,disabled:R,title:"Last opp filer",description:"Dra og slipp eller klikk"})}),(0,u.jsxs)("div",{className:"flex items-center gap-2 mt-3 pt-3 border-t border-border/50",children:[(0,u.jsxs)(b.z,{variant:"outline",size:"sm",className:"flex-1 h-8 text-xs",onClick:()=>M(!0),disabled:R||Z,children:[(0,u.jsx)(w.Z,{className:"h-3.5 w-3.5 mr-1.5"}),"Velg fra bibliotek"]}),a&&(0,u.jsxs)(b.z,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:a,children:[(0,u.jsx)(j.Z,{className:"h-3.5 w-3.5 mr-1.5"}),"\xc5pne i tab"]})]}),(0,u.jsxs)("p",{className:"text-xs text-muted-foreground mt-2",children:["St\xf8tter: PDF, Word, Excel, PowerPoint, Markdown, CSV (maks ",c,"MB)"]}),(0,u.jsx)(C.ContextFilePicker,{open:L,onOpenChange:M,onSelect:J,selectedIds:_.map(e=>e.id),showGoogleDrive:!0,showContextPacks:!0})]})}var _=n(95731),A=n(88623),R=n(34078),P=n(24875),D=n(63769);function F(e){let{initialTopic:t="",autoStart:n=!1,briefId:a,projectId:s,onComplete:i,onExpand:l,onCancel:o,status:c,className:d,researchEndpoint:p="/api/research/execute",maxInlineSources:f=4}=e,[h,x]=(0,m.useState)(t),[k,y]=(0,m.useState)(!1),[w,j]=(0,m.useState)(0),[N,C]=(0,m.useState)([]),[T,I]=(0,m.useState)(null),[E,F]=(0,m.useState)(!1),O
1=T?"error":k?"running":N.length>0?"completed":c||"idle",U=T||(k?w<30?"Starter research...":w<60?"S\xf8ker kilder...":w<90?"Analyserer...":"Ferdigstiller...":N.length>0?"".concat(N.length," kilder funnet"):void 0),L=(0,m.useCallback)(async()=>{if(!h.trim())return;y(!0),j(10),I(null),C([]);let e=setInterval(()=>{j(e=>Math.min(e+5,85))},800);try{let t;let n={topic:h.trim()};a&&(n.tool_id=a),s&&(n.projectId=s);let r=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(clearInterval(e),!r.ok){let e=await r.json().catch(()=>({}));throw Error(e.error||e.message||"Research feilet")}if(j(90),(r.headers.get("content-type")||"").includes("text/event-stream"))throw Error("Streaming research krever full research-visning. Klikk [↗️] for \xe5 \xe5pne.");let l=(t=await r.json()).sources||t.citations||[];C(l),j(100),null==i||i({topic:h,sources:l,summary:t.summary})}catch(t){clearInterval(e),r.kg.error("Research error:",t),I(t instanceof Error?t.message:"Research feilet")}finally{y(!1),j(0)}},[h,a,s,p,i]),M=(0,m.useCallback)(()=>{y(!1),j(0),I(null),null==o||o()},[o]),Z=(0,m.useCallback)(()=>{I(null),L()},[L]),z=(0,m.useCallback)(()=>{I(null)},[]),K=(0,m.useCallback)(e=>{"Enter"===e.key&&h.trim()&&L()},[h,L]);return(0,m.useEffect)(()=>{n&&t&&!E&&!k&&(F(!0),L())},[n,t,E,k,L]),(0,u.jsxs)(g.C,{icon:(0,u.jsx)(_.Z,{className:"h-4 w-4"}),title:"RESEARCH",status:O,progress:k?w:void 0,statusMessage:U,onExpand:l,onCancel:k?M:void 0,onDismiss:T?z:void 0,className:d,children:[T&&(0,u.jsxs)("div",{className:"flex items-center gap-2 mb-3 p-2 rounded bg-muted text-sm text-muted-foreground",children:[(0,u.jsx)(v.Z,{className:"h-4 w-4 flex-shrink-0"}),(0,u.jsx)("span",{className:"flex-1 truncate",children:T}),(0,u.jsxs)(b.z,{variant:"ghost",size:"sm",className:"h-6 px-2 flex-shrink-0",onClick:Z,children:[(0,u.jsx)(A.Z,{className:"h-3 w-3 mr-1"}),"Pr\xf8v igjen"]})]}),"idle"===O&&!T&&(0,u.jsxs)("div",{className:"flex gap-2",children:[(0,u.jsx)(D.I,{value:h,onChange:e=>x(e.target.value),placeholder:"Hva vil du unders\xf8ke?",className:"text-sm h-8",onKeyDown:K}),(0,u.jsx)(b.z,{size:"sm",onClick:L,disabled:!h.trim(),className:"h-8 px-3",children:(0,u.jsx)(_.Z,{className:"h-3.5 w-3.5"})})]}),k&&h&&(0,u.jsxs)("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[(0,u.jsx)(_.Z,{className:"h-3.5 w-3.5 animate-pulse"}),(0,u.jsxs)("span",{className:"truncate",children:['Tema: "',h,'"']}
1)]}),N.length>0&&!T&&(0,u.jsxs)("div",{className:"space-y-2",children:[(0,u.jsxs)("div",{className:"text-xs text-muted-foreground font-medium flex items-center gap-1",children:[(0,u.jsx)(R.Z,{className:"h-3 w-3"}),N.length," kilder funnet"]}),(0,u.jsxs)("div",{className:"space-y-1.5",children:[N.slice(0,f).map((e,t)=>(0,u.jsxs)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:(0,S.cn)("flex items-center gap-2 py-1.5 px-2 rounded text-sm","bg-muted/50 hover:bg-muted transition-colors","group"),children:[(0,u.jsx)(R.Z,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),(0,u.jsx)("span",{className:"truncate flex-1",children:e.title||e.url}),(0,u.jsx)(P.Z,{className:"h-3 w-3 text-muted-foreground flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity"})]},"".concat(e.url,"-").concat(t))),N.length>f&&l&&(0,u.jsxs)(b.z,{variant:"ghost",size:"sm",className:"w-full text-xs h-7",onClick:l,children:["+",N.length-f," flere kilder →"]})]})]}),"idle"===O&&!T&&(0,u.jsx)("p",{className:"text-xs text-muted-foreground mt-2",children:"S\xf8k etter markedsinformasjon, konkurrenter, trender, eller annet."})]})}var O=n(44526),U=n(60037);function L(e){let{workflowId:t,instanceId:n,workflowContent:r,contextFiles:a=[],existingVoiceItems:s=[],onComplete:i,onExpand:l,onCanvasPreview:o,className:c}=e,d=s.some(e=>"voice"===e.kind&&e.payload_ref);return(0,u.jsx)(g.C,{icon:(0,u.jsx)(O.Z,{className:"h-4 w-4"}),title:"INTERVJU",status:d?"completed":"idle",onExpand:l,className:c,children:(0,u.jsx)(U.p,{workflowId:t,instanceId:n,workflowContent:r,contextFiles:a,existingVoiceItems:s,compact:!0,onComplete:i,onCanvasPreview:o,onNavigateToVoiceTab:l})})}var M=n(36673),Z=n(10269),z=n(74737),K=n(76225);function W(e){let{onComplete:t,onExpand:n,className:a}=e,[s,i]=(0,m.useState)(""),[l,o]=(0,m.useState)("idle"),c=(0,m.useRef)(null),d=async()=>{if(!s.trim())return;o("running");let e=s.trim();try{let t=await fetch("/api/library/files",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"Tekst: ".concat(e.slice(0,50)).concat(e.length>50?"...":""),type:"document",content:e,is_inbox:!0,source_type:"quick_capture",capture_method:"selection",metadata:{capture_widget:"text-paste",char_count:e.length}})});if(t.ok){let e=await t.json();r.kg.log("✅ Text saved to inbox:",e.id)}}catch(e){r.kg.warn("⚠️ Failed to save text to library:",e)}null==t||t(e),i(""),o("completed"),setTimeout(()=>o("idle"),2e3)};return(0,u.jsx)(g.C,{icon:(0,u.jsx)(M.Z,{className:"h-4 w-4"}),title:"TEKST",status:l,onExpand:n,className:a,children:(0,u.jsxs)("div",{className:"space-y-3",children:[(0,u.jsx)(K.g,{ref:c,value:s,onChange:e=>i(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&(e.preventDefault(),d())},placeholder:"Lim inn eller skriv tekst...",className:(0,S.cn)("min-h-[100px] resize-none","bg-background/50 border-border/50","focus:ring-1 focus:ring-primary/30"),autoFocus:!0}),(0,u.jsxs)("div",{className:"flex items-center justify-between",children:[(0,u.jsx)("p",{className:"text-xs text-muted-foreground",children:"⌘+Enter for \xe5 sende"}),(0,u.jsxs)("div",{className:"flex gap-2",children:[s&&(0,u.jsxs)(b.z,{variant:"ghost",size:"sm",onClick:()=>{var e;i(""),null===(e=c.current)||void 0===e||e.focus()},className:"text-muted-foreground",children:[(0,u.jsx)(Z.Z,{className:"h-4 w-4 mr-1"}),"T\xf8m"]}),(0,u.jsxs)(b.z,{size:"sm",onClick:d,disabled:!s.trim()||"running"===l,className:"gap-1",children:[(0,u.jsx)(z.Z,{className:"h-4 w-4"}),"Legg til"]})]})]}),"completed"===l&&(0,u.jsx)("p",{className:"text-xs text-muted-foreground",children:"✓ Lagt til som kontekst \xb7 Lagret i inbox"})]})})}var q=n(97481);function G(e){let{onComplete:t,onExpand:n,className:a}=e,[s,i]=(0,m.useState)("idle"),l=async e=>{if(!e.trim())return;i("completed");let n=e.trim();try{let e=await fetch("/api/library/files",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"Lydopptak: ".concat(new Date().toLocaleDateString("nb-NO")," ").concat(new Date().toLocaleTimeString("nb-NO",{hour:"2-digit",minute:"2-digit"})),type:"transcript",content:n,is_inbox:!0,source_type:"quick_capture",metadata:{capture_widget:"voice-recording",char_count:n.length,recorded_at:new Date().toISOString()}})});if(e.ok){let t=await e.json();r.kg.log("✅ Voice recording saved to inbox:",t.id)}}catch(e){r.kg.warn("⚠️ Failed to save voice recording to library:",e)}null==t||t(n),setTimeout(()=>i("idle"),3e3)};return(0,u.jsx)(g.C,{icon:(0,u.jsx)(O.Z,{className:"h-4 w-4"}),title:"LYDOPPTAK",status:s,onExpand:n,className:a,children:(0,u.jsxs)("div",{className:"space-y-3",children:[(0,u.jsx)(q.w,{defaultLanguage:"nb-NO",autoDetectLanguage:!0,showStats:!1,onStopped:l}),(0,u.jsx)("p",{className:"text-xs text-muted-foreground text-center",children:"Trykk p\xe5 mikrofonen for \xe5 starte opptak"}),"completed"===s&&(0,u.jsx)("p",{className:"text-xs text-muted-foreground text-center",children:"✓ Lagt til som kontekst \xb7 Lagret i inbox"})]})})}var V=n(31690),H=n(24239),J=n(17515),B=n(14741),X=n(49268);function Q(e){let{onComplete:t,onExpand:n,className:r}=e,[a,s]=(0,m.useState)(""),[i,l]=(0,m.useState)("idle"),[o,c]=(0,m.useState)(0),[d,p]=(0,m.useState)(null),[f,h]=(0,m.useState)(null),x=async()=>
1{if(a.trim()){if(!(a.includes("youtube.com")||a.includes("youtu.be"))){p("Vennligst lim inn en gyldig YouTube-URL");return}l("running"),p(null),c(10),h("~2-5 min");try{c(30);let e=await (0,X.aN)("video-transcription",{source_type:"youtube",url:a.trim(),options:{extract_tone:!0,extract_insights:!0}});c(80),null==t||t(e.transcript,{title:e.video_title,summary:e.summary,tags:e.tags,file_id:e.file_id}),c(100),l("completed"),s(""),setTimeout(()=>{l("idle"),c(0),h(null)},3e3)}catch(e){p(e instanceof Error?e.message:"Transcription failed"),l("error")}}};return(0,u.jsx)(g.C,{icon:(0,u.jsx)(V.Z,{className:"h-4 w-4"}),title:"VIDEO",status:i,onExpand:n,className:r,children:(0,u.jsxs)("div",{className:"space-y-3",children:[(0,u.jsxs)("div",{className:"flex gap-2",children:[(0,u.jsxs)("div",{className:"relative flex-1",children:[(0,u.jsx)(H.Z,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-red-500"}),(0,u.jsx)(D.I,{value:a,onChange:e=>s(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),x())},placeholder:"https://youtube.com/watch?v=...",className:(0,S.cn)("pl-10","bg-background/50 border-border/50","focus:ring-1 focus:ring-primary/30"),disabled:"running"===i})]}),(0,u.jsx)(b.z,{size:"sm",onClick:x,disabled:!a.trim()||"running"===i,children:"running"===i?(0,u.jsx)(J.Gl,{}):"Transkriber"})]}),"running"===i&&(0,u.jsxs)("div",{className:"space-y-2",children:[(0,u.jsx)(B.E,{value:o,className:"h-2"}),(0,u.jsxs)("div",{className:"flex justify-between text-xs text-muted-foreground",children:[(0,u.jsx)("span",{children:"Transkriberer video..."}),f&&(0,u.jsxs)("span",{children:["Estimert: ",f]})]})]}),d&&(0,u.jsxs)("p",{className:"text-xs text-destructive",children:["✗ ",d]}),"completed"===i&&(0,u.jsx)("p",{className:"text-xs text-muted-foreground",children:"✓ Lagt til som kontekst \xb7 Lagret i inbox"})]})})}var Y=n(78291),$=n(36120),ee=n(55568),et=n(4814);function en(e){let{onComplete:t,onExpand:n,className:r}=e,[a,s]=(0,m.useState)("idle"),[i,l]=(0,m.useState)(null),[o,c]=(0,m.useState)(null),[d,p]=(0,m.useState)(null),f=(0,m.useRef)(null),{transcribe:h}=(0,ee.oM)(),{startProcess:x,completeProcess:v,failProcess:k}=(0,et.v)(),y=async e=>{s("running"),l(null),p(e.name);let n=e.size/1048576;c("~".concat(Math.ceil(n/5)+1," min"));let r=x("Audio Transcription","transcription",{file_name:e.name,failureNotification:"inline"});try{let n=await h({file:e,tool_id:"audio-transcription",tool_name:"Audio Transcription"});v(r,n.file_id?"/library?file=".concat(n.file_id):void 0),null==t||t(n.transcript,{summary:n.summary,tags:n.tags,chapters:n.chapters,file_id:n.file_id}),s("completed"),setTimeout(()=>{s("idle"),p(null),c(null)},3e3)}catch(t){let e=t instanceof Error?t.message:"Failed to transcribe audio";k(r,e),l(e),s("error")}};return(0,u.jsx)(g.C,{icon:(0,u.jsx)(Y.Z,{className:"h-4 w-4"}),title:"AUDIO",status:a,onExpand:n,className:r,children:(0,u.jsxs)("div",{className:"space-y-3",children:[(0,u.jsx)("input",{ref:f,type:"file",accept:"audio/*",onChange:e=>{var t;let n=null===(t=e.target.files)||void 0===t?void 0:t[0];n&&y(n)},className:"hidden"}),"idle"===a&&(0,u.jsxs)("div",{onClick:()=>{var e;null===(e=f.current)||void 0===e||e.click()},onDrop:e=>{var t;e.preventDefault();let n=null===(t=e.dataTransfer.files)||void 0===t?void 0:t[0];n&&n.type.startsWith("audio/")&&y(n)},onDragOver:e=>{e.preventDefault()},className:(0,S.cn)("border-2 border-dashed border-border/50 rounded-lg p-4","flex flex-col items-center justify-center gap-2","cursor-pointer transition-colors","hover:border-primary/50 hover:bg-accent/30"),children:[(0,u.jsx)($.Z,{className:"h-6 w-6 text-muted-foreground"}),(0,u.jsx)("p",{className:"text-sm text-muted-foreground text-center",children:"Klikk eller dra & slipp en lydfil"}),(0,u.jsx)("p",{className:"text-xs text-muted-foreground/70",children:"MP3, WAV, M4A (maks 200MB)"})]}),"running"===a&&(0,u.jsxs)("div",{className:"space-y-2",children:[d&&(0,u.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,u.jsx)(Y.Z,{className:"h-4 w-4 animate-pulse"}),(0,u.jsx)("span",{className:"truncate",children:d})]}),(0,u.jsxs)("div",{className:"flex justify-between text-xs text-muted-foreground",children:[(0,u.jsxs)("span",{className:"flex items-center gap-1",children:[(0,u.jsx)(J.Gl,{size:"sm"}),"Transkriberer..."]}
1),o&&(0,u.jsxs)("span",{children:["Estimert: ",o]})]}),(0,u.jsx)("p",{className:"text-xs text-muted-foreground/70",children:"\uD83D\uDD12 Lydfilen blir ikke lagret - kun transkriptet."})]}),i&&(0,u.jsxs)("div",{className:"space-y-2",children:[(0,u.jsxs)("p",{className:"text-xs text-destructive",children:["✗ ",i]}),(0,u.jsx)(b.z,{variant:"ghost",size:"sm",onClick:()=>{s("idle"),l(null)},children:"Pr\xf8v igjen"})]}),"completed"===a&&(0,u.jsx)("p",{className:"text-xs text-muted-foreground",children:"✓ Lagt til som kontekst \xb7 Lagret i inbox"})]})})}var er=n(42508);function ea(e){let{onComplete:t,onExpand:n,enableImageAnalysis:a=!0,className:s}=e,[i,l]=(0,m.useState)("idle"),[o,c]=(0,m.useState)(0),[d,p]=(0,m.useState)(""),[f,h]=(0,m.useState)(null),[x,v]=(0,m.useState)(null),[k,y]=(0,m.useState)(null),w=(0,m.useRef)(null),{startProcess:j,updateProgress:N,completeProcess:C,failProcess:T}=(0,et.v)(),I=async e=>{l("running"),h(null),c(5),y(e.name),p("Starting...");let n=e.size/1048576;v("~".concat(Math.ceil(n/2)+1," min"));let s=j("PDF Extraction","extraction",{file_name:e.name,failureNotification:"inline"});try{let n;p(a?"Extracting text with AI OCR...":"Extracting text..."),c(30),N(s,30);let i=await (0,er.extractTextFromPDFClient)(e);if(i.startsWith("[PDF tekst-ekstraksjon feilet"))throw Error(i);c(60),N(s,60),p("Saving to library..."),c(75),N(s,75);try{let t=await fetch("/api/library/files",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"PDF: ".concat(e.name),type:"document",content:i,is_inbox:!0,source_type:"upload",capture_method:"upload",metadata:{original_filename:e.name,file_size:e.size,capture_widget:"pdf"}})});t.ok?(n=(await t.json()).id,r.kg.log("✅ PDF saved to inbox:",n)):r.kg.warn("⚠️ Failed to save PDF to library, continuing with context only")}catch(e){r.kg.warn("⚠️ Error saving to library:",e)}p("Processing complete"),c(90),N(s,90),C(s,n?"/library?file=".concat(n):void 0),null==t||t(i,{fileName:e.name,textLength:i.length,fileId:n}),c(100),l("completed"),setTimeout(()=>{l("idle"),c(0),y(null),p(""),v(null)},3e3)}catch(t){let e=t instanceof Error?t.message:"PDF extraction failed";T(s,e),h(e),l("error")}};return(0,u.jsx)(g.C,{icon:(0,u.jsx)(M.Z,{className:"h-4 w-4"}),title:"PDF",status:i,onExpand:n,className:s,children:(0,u.jsxs)("div",{className:"space-y-3",children:[(0,u.jsx)("input",{ref:w,type:"file",accept:".pdf,application/pdf",onChange:e=>{var t;let n=null===(t=e.target.files)||void 0===t?void 0:t[0];n&&I(n)},className:"hidden"}),"idle"===i&&(0,u.jsxs)("div",{onClick:()=>{var e;null===(e=w.current)||void 0===e||e.click()},onDrop:e=>{var t;e.preventDefault();let n=null===(t=e.dataTransfer.files)||void 0===t?void 0:t[0];n&&"application/pdf"===n.type&&I(n)},onDragOver:e=>{e.preventDefault()},className:(0,S.cn)("border-2 border-dashed border-border/50 rounded-lg p-4","flex flex-col items-center justify-center gap-2","cursor-pointer transition-colors","hover:border-primary/50 hover:bg-accent/30"),children:[(0,u.jsx)($.Z,{className:"h-6 w-6 text-muted-foreground"}),(0,u.jsx)("p",{className:"text-sm text-muted-foreground text-center",children:"Klikk eller dra & slipp en PDF-fil"}),(0,u.jsx)("p",{className:"text-xs text-muted-foreground/70",children:"St\xf8tter OCR for skannede dokumenter"})]}),"running"===i&&(0,u.jsxs)("div",{className:"space-y-2",children:[k&&(0,u.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,u.jsx)(M.Z,{className:"h-4 w-4"}),(0,u.jsx)("span",{className:"truncate",children:k})]}),(0,u.jsx)(B.E,{value:o,className:"h-2"}),(0,u.jsxs)("div",{className:"flex justify-between text-xs text-muted-foreground",children:[(0,u.jsxs)("span",{className:"flex items-center gap-1",children:[(0,u.jsx)(J.Gl,{size:"sm"}),d||"Processing..."]}),x&&(0,u.jsxs)("span",{children:["Estimert: ",x]})]})]}),f&&(0,u.jsxs)("div",{className:"space-y-2",children:[(0,u.jsxs)("p",{className:"text-xs text-destructive",children:["✗ ",f]}),(0,u.jsx)(b.z,{variant:"ghost",size:"sm",onClick:()=>{l("idle"),h(null)},children:"Pr\xf8v igjen"})]}),"completed"===i&&(0,u.jsx)("p",{className:"text-xs text-muted-foreground",children:"✓ Lagt til som kontekst \xb7 Lagret i inbox"})]})})}var es=n(38333),ei=n(87354),el=n(98521),eo=n(11440);function ec(e){let{onComplete:t,onExpand:n,showPreview:r=!0,className:a}=e,[s,i]=(0,m.useState)("idle"),[l,o]=(0,m.useState)(0),[c,d]=(0,m.useState)(""),[p,f]=(0,m.useState)(null),[h,x]=(0,m.useState)(null),[v,k]=(0,m.useState)(null),[y,w]=(0,m.useState)(!1),[j,N]=(0,m.useState)(""),[C,T]=(0,m.useState)({}),I=(0,m.useRef)(null),{startProcess:E,updateProgress:_,completeProcess:A,failProcess:R}=(0,et.v)(),P=async e=>{i("running"),f(null),o(5),k(e.name),d("Starting...");let n=Math.ceil(e.size/1048576*2)+5;x(n<60?"~".concat(n," sek"):"~".concat(Math.ceil(n/60)," min"));let a=E("Document Extraction","extraction",{file_name:e.name,failureNotification:"inline"});try{var s;d("Initializing..."),o(15),_(a,15),d("Reading document..."),o(30),_(a,30);let n=null===(s=e.name.split(".").pop())||void 0===s?void 0:s.toLowerCase();d("pptx"===n?"Parsing slides...":"Extracting text..."),o(50),_(a,50);let l=await (0,X.xt)("document-extract",e);d("Processing complete"),o(90),_(a,90);let c={fileName:e.name,fileExtension:n,...l};r?(N(l.text),T(c),w(!0),i("idle"),A(a)):(A(a,l.file_id?"/library?file=".concat(l.file_id):void 0),null==t||t(l.text,c),o(100),i("completed"),setTimeout(()=>{i("idle"),o(0),k(null),d(""),x(null)},3e3))}catch(t){let e=t instanceof Error?t.message:"Document extraction failed";R(a,e),f(e),i("error")}};return(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(g.C,{icon:(0,u.jsx)(M.Z,{className:"h-4 w-4"}),title:"DOKUMENT",status:s,onExpand:n,className:a,children:(0,u.jsxs)("div",{className:"space-y-3",children:[(0,u.jsx)("input",{ref:I,type:"file",accept:".doc,.docx,.pptx,.txt,.md,.rtf",onChange:e=>{var t;let n=null===(t=e.target.files)||void 0===t?void 0:t[0];n&&P(n)},className:"hidden"}),"idle"===s&&(0,u.jsxs)("div",{onClick:()=>{var e;null===(e=I.current)||void 0===e||e.click()},onDrop:e=>{var t,n;e.preventDefault();let r=null===(t=e.dataTransfer.files)||void 0===t?void 0:t[0];if(r){let e=null===(n=r.name.split(".").pop())||void 0===n?void 0:n.toLowerCase();e&&["doc","docx","pptx","txt","md","rtf"].includes(e)&&P(r)}},onDragOver:e=>{e.preventDefault()},className:(0,S.cn)("border-2 border-dashed border-border/50 rounded-lg p-4","flex flex-col items-center justify-center gap-2","cursor-pointer transition-colors","hover:border-primary/50 hover:bg-accent/30"),children:[(0,u.jsx)($.Z,{className:"h-6 w-6 text-muted-foreground"}),(0,u.jsx)("p",{className:"text-sm text-muted-foreground text-center",children:"Klikk eller dra & slipp et dokument"}
1),(0,u.jsx)("p",{className:"text-xs text-muted-foreground/70",children:"DOCX, PPTX, TXT, MD, RTF"})]}),"running"===s&&(0,u.jsxs)("div",{className:"space-y-2",children:[v&&(0,u.jsxs)("div",{className:"flex items-center gap-2 text-sm",children:[(0,u.jsx)(M.Z,{className:"h-4 w-4"}),(0,u.jsx)("span",{className:"truncate",children:v})]}),(0,u.jsx)(B.E,{value:l,className:"h-2"}),(0,u.jsxs)("div",{className:"flex justify-between text-xs text-muted-foreground",children:[(0,u.jsxs)("span",{className:"flex items-center gap-1",children:[(0,u.jsx)(J.Gl,{size:"sm"}),c||"Processing..."]}),h&&(0,u.jsxs)("span",{children:["Estimert: ",h]})]})]}),p&&(0,u.jsxs)("div",{className:"space-y-2",children:[(0,u.jsxs)("p",{className:"text-xs text-destructive",children:["✗ ",p]}),(0,u.jsx)(b.z,{variant:"ghost",size:"sm",onClick:()=>{i("idle"),f(null)},children:"Pr\xf8v igjen"})]}),"completed"===s&&(0,u.jsx)("p",{className:"text-xs text-muted-foreground",children:"✓ Lagt til som kontekst \xb7 Lagret i inbox"})]})}),(0,u.jsx)(el.Vq,{open:y,onOpenChange:w,children:(0,u.jsxs)(el.cZ,{className:"max-w-2xl max-h-[80vh]",children:[(0,u.jsx)(el.fK,{children:(0,u.jsxs)(el.$N,{className:"flex items-center gap-2",children:[(0,u.jsx)(es.Z,{className:"h-5 w-5"}),"Forh\xe5ndsvisning: ",v]})}),(0,u.jsx)(eo.x,{className:"h-[400px] rounded-md border p-4 bg-muted/30",children:(0,u.jsxs)("pre",{className:"text-sm whitespace-pre-wrap font-mono",children:[j.slice(0,5e3),j.length>5e3&&(0,u.jsxs)("span",{className:"text-muted-foreground",children:["\n\n","... (",j.length-5e3," tegn til)"]})]})}),(0,u.jsxs)(el.cN,{className:"gap-2",children:[(0,u.jsxs)(b.z,{variant:"ghost",onClick:()=>{w(!1),N(""),T({}),k(null)},children:[(0,u.jsx)(Z.Z,{className:"h-4 w-4 mr-1"}),"Avbryt"]}),(0,u.jsxs)(b.z,{onClick:()=>{w(!1),null==t||t(j,C),i("completed"),setTimeout(()=>{i("idle"),o(0),k(null),d(""),x(null),N(""),T({})},3e3)},children:[(0,u.jsx)(ei.Z,{className:"h-4 w-4 mr-1"}),"Legg til som kontekst"]})]})]})})]})}n(21654)},97481:function(e,t,n){n.d(t,{w:function(){return y}});var r=n(27573),a=n(7653),s=n(79107),i=n(16273),l=n(13040),o=n(44526),c=n(52377),d=n(52893),u=n(61990),m=n(10997),p=n(19369);function f(e){var t;let{status:n,detectedLanguage:a,onStart:s,onStop:f,onPause:h,onResume:g,onLanguageChange:x,onClear:v,error:k}=e,y=!!(null===(t=window.strategyAI)||void 0===t?void 0:t.isDesktop),w="idle"===n||"disconnected"===n,j="paused"===n,b="listening"===n||"transcribing"===n||"connected"===n;return(0,r.jsxs)("div",{className:"flex items-center justify-between gap-4 p-4 border-b",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[w&&(0,r.jsxs)(i.z,{onClick:s,className:"gap-2",disabled:"connecting"===n,children:[(0,r.jsx)(o.Z,{className:"h-4 w-4"}),"Start Transcription"]}),b&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(i.z,{onClick:h,variant:"outline",className:"gap-2",disabled:"transcribing"===n,children:[(0,r.jsx)(c.Z,{className:"h-4 w-4"}),"Pause"]}),(0,r.jsxs)(i.z,{onClick:f,variant:"destructive",className:"gap-2",children:[(0,r.jsx)(d.Z,{className:"h-4 w-4"}),"Stop"]})]}),j&&(0,r.jsxs)(i.z,{onClick:g,className:"gap-2",children:[(0,r.jsx)(u.Z,{className:"h-4 w-4"}),"Resume"]}),(0,r.jsxs)("div",{className:"flex items-center gap-2 ml-4",children:[(0,r.jsx)("div",{className:(0,p.cn)("h-2 w-2 rounded-full",b&&"bg-green-600 dark:bg-green-400 animate-pulse",j&&"bg-yellow-600 dark:bg-yellow-400",w&&"bg-muted-foreground","error"===n&&"bg-destructive")}
1),(0,r.jsx)("span",{className:"text-sm text-muted-foreground capitalize",children:n})]})]}),(0,r.jsx)("div",{className:"flex items-center gap-2",children:(0,r.jsxs)(l.Ph,{value:a||"nb-NO",onValueChange:e=>x(e),children:[(0,r.jsx)(l.i4,{className:"w-[140px]",children:(0,r.jsx)(l.ki,{placeholder:"Language"})}),(0,r.jsxs)(l.Bw,{children:[(0,r.jsx)(l.Ql,{value:"nb-NO",children:"Norwegian"}),(0,r.jsx)(l.Ql,{value:"en-US",children:"English (US)"}),(0,r.jsx)(l.Ql,{value:"en-GB",children:"English (GB)"})]})]})}),(0,r.jsx)("div",{className:"flex items-center gap-2",children:(0,r.jsxs)(i.z,{onClick:v,variant:"ghost",size:"sm",className:"gap-2",disabled:b,children:[(0,r.jsx)(m.Z,{className:"h-4 w-4"}),"Clear"]})}),k&&(0,r.jsx)("div",{className:"flex-1",children:(0,r.jsx)("div",{className:"bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-md p-3",children:(0,r.jsx)("div",{className:"text-sm font-medium text-red-800 dark:text-red-200",children:k.includes("permission")||k.includes("Permission")?(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsx)("div",{className:"font-semibold",children:"Mikrofontilgang avsl\xe5tt"}),(0,r.jsx)("div",{className:"text-xs font-normal text-red-700 dark:text-red-300",children:"For \xe5 bruke transkripsjon m\xe5 du gi tilgang til mikrofon."}),(0,r.jsxs)("div",{className:"text-xs font-normal text-red-600 dark:text-red-400 mt-1",children:[(0,r.jsx)("strong",{children:"L\xf8sning:"}),' Klikk p\xe5 ikonet i adresselinjen og velg "Tillat" for mikrofon. Last siden p\xe5 nytt og pr\xf8v igjen.']})]}):k.includes("Security")||k.includes("insecure")||k.includes("SECURITY")?(0,r.jsxs)("div",{className:"space-y-1",children:[(0,r.jsx)("div",{className:"font-semibold",children:"Sikkerhetsfeil"}),(0,r.jsx)("div",{className:"text-xs font-normal text-red-700 dark:text-red-300",children:y?"Desktop-appen fikk ikke startet sikker lydfangst. Dette skyldes vanligvis manglende mikrofontilgang i macOS eller at appen m\xe5 installeres p\xe5 nytt etter en desktop-oppdatering.":"Nettleseren blokkerer tilkobling til taletjenesten fra HTTP (localhost)."}),(0,r.jsx)("div",{className:"text-xs font-normal text-red-600 dark:text-red-400 mt-1",children:y?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("strong",{children:"L\xf8sning:"})," Sjekk macOS System Settings → Privacy & Security → Microphone, og installer den nyeste desktop-appen p\xe5 nytt f\xf8r du pr\xf8ver igjen."]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("strong",{children:"L\xf8sning:"})," Last siden p\xe5 nytt (F5). Hvis problemet vedvarer:",(0,r.jsxs)("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[(0,r.jsxs)("li",{children:[(0,r.jsx)("strong",{children:"Chrome/Edge:"})," Start med flagget:"," ",(0,r.jsx)("code",{className:"bg-red-100 dark:bg-red-900 px-1 rounded text-[10px]",children:"--unsafely-treat-insecure-origin-as-secure=http://localhost:3000"})]}),(0,r.jsxs)("li",{children:[(0,r.jsx)("strong",{children:"Safari:"})," Safari → Preferences → Websites → Microphone → Allow for localhost"]}),(0,r.jsxs)("li",{children:[(0,r.jsx)("strong",{children:"Anbefaling:"})," Bruk Chrome eller Edge for best st\xf8tte"]})]})]})})]}):k})})})]})}var h=n(11440);function g(e){let{transcript:t,partialTranscript:n,detectedLanguage:a}=e,s=t.trim()||n.trim();return(0,r.jsx)(h.x,{className:"h-full w-full p-6",children:(0,r.jsxs)("div",{className:"space-y-4",children:[t&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("div",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:["Transcript",a&&(0,r.jsxs)("span",{className:"ml-2",children:["(","nb-NO"===a?"Norwegian":"en-US"===a?"English (US)":"English (GB)",")"]})]}),(0,r.jsxs)("div",{className:"text-base leading-relaxed whitespace-pre-wrap",children:[t,n&&(0,r.jsxs)("span",{className:"text-muted-foreground italic",children:[" ",n]})]})]}),!t&&n&&(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsxs)("div",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:["Listening...",a&&(0,r.jsxs)("span",{className:"ml-2",children:["(","nb-NO"===a?"Norweg
1ian":"en-US"===a?"English (US)":"English (GB)",")"]})]}),(0,r.jsx)("div",{className:"text-base leading-relaxed text-muted-foreground italic",children:n})]}),!s&&(0,r.jsx)("div",{className:"flex items-center justify-center h-full text-center text-muted-foreground",children:(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("p",{className:"text-sm",children:"No transcription yet"}),(0,r.jsx)("p",{className:"text-xs",children:'Click "Start Transcription" to begin'})]})})]})})}function x(e){let{stats:t,detectedLanguage:n}=e,{wordCount:a,averageConfidence:s,totalDuration:i}=t;return(0,r.jsx)("div",{className:"border-t p-4 bg-muted/50",children:(0,r.jsxs)("div",{className:"grid grid-cols-4 gap-4 text-sm",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-muted-foreground text-xs uppercase tracking-wide",children:"Words"}),(0,r.jsx)("div",{className:"font-medium mt-1",children:a})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-muted-foreground text-xs uppercase tracking-wide",children:"Confidence"}),(0,r.jsx)("div",{className:"font-medium mt-1",children:s>0?"".concat(Math.round(100*s),"%"):"—"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-muted-foreground text-xs uppercase tracking-wide",children:"Duration"}),(0,r.jsx)("div",{className:"font-medium mt-1",children:i>0?"".concat(Math.round(i),"s"):"—"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:"text-muted-foreground text-xs uppercase tracking-wide",children:"Language"}),(0,r.jsx)("div",{className:"font-medium mt-1",children:n?"nb-NO"===n?"Norwegian":"en-US"===n?"English (US)":"English (GB)":"—"})]})]})})}let v=new(n(79015)).Ov,k={info:function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return v.info([e,...n].map(e=>e instanceof Error?e.message:"object"==typeof e?JSON.stringify(e):String(e)).join(" "))}};function y(e){var t;let{defaultLanguage:n="nb-NO",autoDetectLanguage:i=!0,onFinalTranscript:l,onStopped:o,showStats:c=!0}=e,d=!!(null===(t=window.strategyAI)||void 0===t?void 0:t.isDesktop),{status:u,transcript:m,partialTranscript:p,detectedLanguage:h,start:v,stop:y,pause:w,resume:j,changeLanguage:b,clear:N,stats:C,error:S}=(0,s.X)({language:n,autoDetectLanguage:i,enablePunctuation:!0,onFinalTranscript:e=>{l&&l(e)}}),T=(0,a.useRef)(u),I=(0,a.useRef)(""),E=(0,a.useRef)(o);return(0,a.useEffect)(()=>{E.current=o},[o]),(0,a.useEffect)(()=>{let e="listening"===T.current||"transcribing"===T.current||"connected"===T.current,t="idle"===u||"disconnected"===u;if(e&&t&&E.current){let e=m||"";I.current!==e&&(I.current=e,k.info("\uD83D\uDED1 Transcription stopped, calling onStopped. Transcript length:",e.length),setTimeout(()=>{let e=m||"";E.current&&(k.info("\uD83D\uDCDD Calling onStopped callback with transcript:",e.substring(0,100)+(e.length>100?"...":"")),E.current(e))},200))}T.current=u},[u,m]),(0,r.jsxs)("div",{className:"flex flex-col h-full w-full",children:[(0,r.jsx)(f,{status:u,detectedLanguage:h,onStart:v,onStop:y,onPause:w,onResume:j,onLanguageChange:b,onClear:N,error:S}),(0,r.jsx)("div",{className:"flex-1 overflow-hidden",children:S&&(S.includes("permission")||S.includes("Permission")||S.includes("Security")||S.includes("insecure"))?(0,r.jsx)("div",{className:"flex items-center justify-center h-full p-8",children:(0,r.jsx)("div",{className:"max-w-md space-y-4 text-center",children:S.includes("Security")||S.includes("insecure")?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"text-4xl",children:"\uD83D\uDD12"}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("h3",{className:"text-lg font-semibold",children:"Sikkerhetsfeil"}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:d?"Desktop-appen fikk ikke startet sikker lydfangst. Dette er vanligvis et macOS mikrofontilgangsproblem i appen, ikke i nettleseren.":"Nettleseren blokkerer tilkobling til taletjenesten fra HTTP (localhost)."}),(0,r.jsx)("div",{className:"bg-muted p-4 rounded-md text-left text-xs space-y-2 mt-4",children:d?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"Steg 1:"})," Lukk desktop-appen helt"]}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"Steg 2:"})," Installer siste versjon av appen p\xe5 nytt"]}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"Steg 3:"})," Sjekk macOS System Settings → Privacy & Security → Microphone og bekreft at Praksis er tillatt"]}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"Steg 4:"})," \xc5pne appen igjen og pr\xf8v p\xe5 nytt"]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"L\xf8sning 1:"})," Last siden p\xe5 nytt (F5 eller Cmd+R)"]}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"L\xf8sning 2 (Chrome/Edge):"})," Start nettleseren med dette flagget:"]}),(0,r.jsx)("code",{className:"block bg-background p-2 rounded text-[10px] break-all mb-2",children:"--unsafely-treat-insecure-origin-as-secure=http://localhost:3000"}),(0,r.jsx)("p",{children:(0,r.jsx)("strong",{children:"L\xf8sning 3 (Safari):"})}),(0,r.jsxs)("ul",{className:"list-disc list-inside ml-2 space-y-1",children:[(0,r.jsx)("li",{children:"G\xe5 til Safari → Preferences → Websites → Microphone"}),(0,r.jsx)("li",{children:'Finn localhost og sett til "Allow"'}),(0,r.jsx)("li",{children:"Last siden p\xe5 nytt"})]}),(0,r.jsxs)("p",{className:"text-xs text-muted-foreground mt-2",children:[(0,r.jsx)("strong",{children:"⚠️ Safari-begrensning:"})," Safari har kjente problemer med sanntids-lyd p\xe5 HTTP localhost.",(0,r.jsx)("br",{}),(0,r.jsx)("strong",{children:"✅ Anbefaling:"})," Bruk Chrome eller Edge for best st\xf8tte. Eller sett opp HTTPS (se guide)."]})]})})]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"text-4xl",children:"\uD83C\uDFA4"}),(0,r.jsxs)("div",{className:"space-y-2",children:[(0,r.jsx)("h3",{className:"text-lg font-semibold",children:"Mikrofontilgang p\xe5krevd"}),(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:"For \xe5 transkribere lyd trenger vi tilgang til mikrofon."}),(0,r.jsxs)("div",{className:"bg-muted p-4 rounded-md text-left text-xs space-y-2 mt-4",children:[(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"Steg 1:"})," Se etter ikonet i adresselinjen (\xf8verst til venstre i Chrome/Edge)"]}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"Steg 2:"}),' Klikk p\xe5 ikonet og velg "Tillat" for mikrofon']}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"Steg 3:"})," Last siden p\xe5 nytt (F5 eller Cmd+R)"]}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"Steg 4:"}),' Klikk "Start Transcription" igjen']})]})]})]})})}):(0,r.jsx)(g,{transcript:m,partialTranscript:p,detectedLanguage:h})}),c&&(0,r.jsx)(x,{stats:C,detectedLanguage:h})]})}},69654:function(e,t,n){n.d(t,{b:function(){return s}});var r=n(7653),a=n(8400);function s(e){let{documentContent:t,onApply:n,enabled:s=!0,undoTimeoutMs:i=3e4}=e,[l,o]=(0,r.useState)([]),[c,d]=(0,r.useState)(0),[u,m]=(0,r.useState)([]),[p,f]=(0,r.useState)(null),h=(0,r.useRef)(null),g=(0,r.useRef)(t);(0,r.useEffect)(()=>{g.current=t},[t]);let x=(0,r.useCallback)(e=>{if(!s){let t=(0,a.W9)(e);if("patch"===t){let t=(0,a.md)(e);t&&t.length>0&&n((0,a.QE)(g.current,t))}else"full"===t&&n((0,a.oz)(e)||e.replace(/\[FULL\]/gi,"").trim());return}let t=(0,a.W9)(e),r=[];if("patch"===t)r=(0,a.md)(e)||[];else if("full"===t){let t=(0,a.oz)(e)||e.replace(/\[FULL\]/gi,"").trim();r=[{find:g.current,replace:t}]}0!==r.length&&(o(r.map((t,n)=>{var r;let s="Dokument",i=e.match(/\[SECTION:\s*([^\]]+)\]/i),l=null==i?void 0:null===(r=i[1])||void 0===r?void 0:r.trim();if(l)s=l;else{let e=(0,a.V3)(g.current,t.find);e&&(s=e.section)}let o=(0,a.qm)(t.find,t.replace);return{id:"patch-".concat(Date.now(),"-").concat(n),section:s,patch:t,status:"pending",diffLines:o}})),d(0))},[s,n]),v=(0,r.useCallback)(e=>{m(t=>[...t,{content:e,timestamp:Date.now()}]),f(Math.floor(i/1e3)),h.current&&clearInterval(h.current),h.current=setInterval(()=>{f(e=>null===e||e<=1?(h.current&&clearInterval(h.current),m(e=>e.filter(e=>Date.now()-e.timestamp<i)),null):e-1)},1e3)},[i]),k=(0,r.useCallback)(e=>{let t=l[e];if(!t||"pending"!==t.status)return;v(g.current),n((0,a.QE)(g.current,[t.patch])),o(t=>t.map((t,n)=>n===e?{...t,status:"approved"}:t));let r=l.findIndex((t,n)=>n>e&&"pending"===t.status);-1!==r&&d(r)},[l,n,v]),y=(0,r.useCallback)(e=>{o(t=>t.map((t,n)=>n===e?{...t,status:"rejected"}:t));let t=l.findIndex((t,n)=>n>e&&"pending"===t.status);-1!==t&&d(t)},[l]),w=(0,r.useCallback)(e=>{o(t=>t.map((t,n)=>n===e?{...t,status:"skipped"}:t));let t=l.findIndex((t,n)=>n>e&&"pending"===t.status);-1!==t&&d(t)},[l]),j=(0,r.useCallback)(()=>{let e=l.filter(e=>"pending"===e.status);0!==e.length&&(v(g.current),n((0,a.QE)(g.current,e.map(e=>e.patch))),o(e=>e.map(e=>"pending"===e.status?{...e,status:"approved"}:e)))},[l,n,v]),b=(0,r.useCallback)(()=>{o(e=>e.map(e=>"pending"===e.status?{...e,status:"rejected"}:e))},[]),N=(0,r.useCallback)(()=>{o([]),d(0)},[]),C=u[u.length-1],S=!!C&&Date.now()-C.timestamp<i,T=(0,r.useCallback)(()=>
1{if(0===u.length)return;let e=u[u.length-1];if(e){if(Date.now()-e.timestamp>i){m([]),f(null);return}n(e.content),m(e=>e.slice(0,-1)),1===u.length&&(h.current&&clearInterval(h.current),f(null))}},[u,i,n]);(0,r.useEffect)(()=>()=>{h.current&&clearInterval(h.current)},[]);let I=(0,r.useCallback)(e=>{let t=l[e];if(!t)return;d(e);let n=document.getElementById("diff-overlay-".concat(t.id));n&&n.scrollIntoView({behavior:"smooth",block:"center"})},[l]),E=(0,r.useCallback)(()=>{let e=l.findIndex((e,t)=>t>c&&"pending"===e.status);if(-1!==e)I(e);else{let e=l.findIndex(e=>"pending"===e.status);-1!==e&&I(e)}},[l,c,I]),_=(0,r.useCallback)(e=>{for(let n of document.querySelectorAll("h1, h2, h3, h4, h5, h6, [data-heading]")){var t;if(null===(t=n.textContent)||void 0===t?void 0:t.includes(e)){n.scrollIntoView({behavior:"smooth",block:"start"});break}}},[]),A=l.filter(e=>"pending"===e.status).length,R=l.filter(e=>"approved"===e.status).length,P=l.filter(e=>"rejected"===e.status).length,D=A>0,F=D?{content:(0,a.QE)(g.current,l.filter(e=>"pending"===e.status).map(e=>e.patch)),originalLength:g.current.length}:null;return{pendingPatches:l,activePatchIndex:c,processEditResponse:x,applyPatch:k,rejectPatch:y,skipPatch:w,applyAll:j,rejectAll:b,clearPatches:N,canUndo:S,undo:T,undoTimeRemaining:p,navigateToPatch:I,navigateToNextPending:E,scrollToSection:_,hasPendingPatches:D,pendingCount:A,approvedCount:R,rejectedCount:P,legacyPendingEdit:F}}},97973:function(e,t,n){n.d(t,{A9:function(){return o},Dl:function(){return l}});var r=n(7653);let a=new Map,s=new Set;function i(e){return s.add(e),()=>{s.delete(e)}}function l(e){let t=null!=e?e:"",n=()=>{var e;return t&&null!==(e=a.get(t))&&void 0!==e?e:0};return(0,r.useSyncExternalStore)(i,n,n)}function o(e,t){let n=(0,r.useRef)(null);(0,r.useEffect)(()=>{if(t){e&&!n.current&&(n.current=e);return}let r=n.current;r&&(n.current=null,function(e){var t;for(let n of(a.set(e,(null!==(t=a.get(e))&&void 0!==t?t:0)+1),s))n()}(r))},[e,t])}},52260:function(e,t,n){n.d(t,{N:function(){return a},t:function(){return s}});var r=n(74685);class a extends Error{}function s(e){let t=new Map;return(n,a)=>{r.Z_8().uuid().parse(n),r.Z_8().uuid().parse(a);let s="".concat(a,":").concat(n),i=t.get(s);if(i)return i;let l=Promise.resolve().then(()=>e({content:"",connectionResumeId:n,connectionConversationId:a,turnRequestId:n})).catch(e=>{throw t.delete(s),e});return t.set(s,l),l}}},23442:function(e,t,n){n.d(t,{G:function(){return a},R:function(){return s}});var r=n(52872);function a(e){let t=new Set,n=[];for(let a of e){if("assistant"!==a.role)continue;
1let e=(0,r.DW)(a.content);if(0===e.length)continue;let s=(0,r.bJ)(a.content);for(let r of e){let e="".concat(r.kind,":").concat(r.id);t.has(e)||(t.add(e),n.push({kind:r.kind,id:r.id,producedAt:function(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":t.toISOString()}(a.createdAt),messageId:a.id,outcome:s}))}}return n}function s(e){return"task"===e?"task":"board"===e?"board":"presentation"===e?"presentation":"dialogue"===e?"dialogue":"canvas"}},34782:function(e,t,n){n.d(t,{BP:function(){return p},El:function(){return m},IQ:function(){return x},L8:function(){return r.L8},S4:function(){return g},Ti:function(){return v},XI:function(){return s},Xr:function(){return h},Y0:function(){return o},ei:function(){return f},mv:function(){return i},pO:function(){return a},t$:function(){return y},uX:function(){return u},vC:function(){return k},vk:function(){return r.vk}});var r=n(17211);let a="uncategorized";function s(e,t){return!!t&&(e.id===t||e.id==="tool-".concat(t))}function i(e){return"draft"===e.status}function l(e){return"archived"===e.status}function o(e,t){return"user"===e.owner_type&&!!e.owner_id&&e.owner_id===t}function c(e){return"system"===e.owner_type||"system"===e.visibility}function d(e,t,n){var r,a,s;if("hidden"!==t&&l(e))return!1;switch(t){case"all":return!0;case"activated":return(null!==(a=null===(r=n.activations[e.id])||void 0===r?void 0:r.length)&&void 0!==a?a:0)>0;case"mine":return o(e,n.me.id);case"organization":return s=n.me.id,!c(e)&&("organization"===e.visibility||"user"===e.owner_type&&!!e.owner_id&&e.owner_id!==s);case"system":return c(e);case"drafts":return i(e);case"hidden":return l(e)}}function u(e,t,n){let r=t.search.trim().toLowerCase();return e.filter(e=>{var s;if(!d(e,t.scope,n))return!1;if(t.categoryId===a){if(e.skill_category_id)return!1}else if("all"!==t.categoryId&&e.skill_category_id!==t.categoryId)return!1;return!r||e.name.toLowerCase().includes(r)||(null!==(s=e.description)&&void 0!==s?s:"").toLowerCase().includes(r)})}function m(e,t){let n=["all","activated","mine","organization","system","drafts","hidden"],r=Object.fromEntries(n.map(e=>[e,0]));for(let a of e)for(let e of n)d(a,e,t)&&(r[e]+=1);return r}function p(e){let t={};for(let s of e){var n,r;if(l(s))continue;let e=null!==(n=s.skill_category_id)&&void 0!==n?n:a;t[e]=(null!==(r=t[e])&&void 0!==r?r:0)+1}return t}function f(e,t){let n=[...e];return"updated"===t?n.sort((e,t)=>{var n,r,a,s;return(null!==(r=null!==(n=t.updated_at)&&void 0!==n?n:t.created_at)&&void 0!==r?r:"").localeCompare(null!==(s=null!==(a=e.updated_at)&&void 0!==a?a:e.created_at)&&void 0!==s?s:"")}):n.sort((e,t)=>e.name.localeCompare(t.name,"nb")),n}function h(e,t,n){let r=[];for(let n of t){let t=e.filter(e=>e.skill_category_id===n.id);t.length>0&&r.push({id:n.id,label:n.name,skills:t})}let s=new Set(t.map(e=>e.id)),i=e.filter(e=>!e.skill_category_id||!s.has(e.skill_category_id));return i.length>0&&r.push({id:a,label:n,skills:i}),r}function g(e,t,n){let r=new Map,a=[];for(let n of e){var s,i;let e=null!==(s=t[n.id])&&void 0!==s?s:[];if(0===e.length){a.push(n);continue}for(let t of e){let e=null!==(i=r.get(t.workspaceId))&&void 0!==i?i:{id:t.workspaceId,label:t.workspaceName,skills:[]};e.skills.some(e=>e.id===n.id)||e.skills.push(n),r.set(t.workspaceId,e)}}let l=[...r.values()].sort((e,t)=>e.label.localeCompare(t.label,"nb"));return a.length>0&&l.push({id:"not-activated",label:n,skills:a}),l}function x(e,t,n){var r,a,s,i;return c(e)?n.system:"organization"===e.visibility&&(null===(r=t.organization)||void 0===r?void 0:r.name)?t.organization.name:e.owner_id&&e.owner_id===t.me.id?null!==(s=t.me.name)&&void 0!==s?s:n.me:e.owner_id&&t.owners[e.owner_id]?t.owners[e.owner_id]:null!==(i=null===(a=t.organization)||void 0===a?void 0:a.name)&&void 0!==i?i:"—"}function v(e,t,n){var r;let a=[...new Set((null!==(r=t[e.id])&&void 0!==r?r:[]).map(e=>e.workspaceName))];return 0===a.length?"—":a.length<=2?a.join(" \xb7 "):n(a.length)}function k(e){var t;let n=(null!==(t=e.version)&&void 0!==t?t:"").trim();return n?n.startsWith("v")?n:"v".concat(n):null}function y(e){return"/production/sessions?skill=".concat(encodeURIComponent(e))}},17211:function(e,t,n){n.d(t,{Bp:function(){return d},L8:function(){return f},Nh:function(){return c},Ou:function(){return h},T1:function(){return u},W0:function(){return o},W_:function(){return s},aO:function(){return a},bZ:function(){return g},c8:function(){return m},ib:function(){return r},vk:function(){return p}});let r="none",a=[{value:"production",labelKey:"categoryProduction"},{value:"research",labelKey:"categoryResearch"},{value:"dialogue",labelKey:"categoryDialogue"},{value:"analysis",labelKey:"categoryAnalysis"},{value:"strategy",labelKey:"categoryStrategy"},{value:"format-skills",labelKey:"categoryOutputFormat"},{value:"canvas",labelKey:"categoryCanvas"},{value:"meta",labelKey:"categoryMetaSkillCreators"}],s={name:"",description:"",skillCategoryId:r,type:"production",visibility:"private",instructions:"",outputFormat:"",contextRequirements:""},i=e=>"string"==typeof e&&e.trim()?e.trim():null;function l(e){return a.some(t=>t.value===e)}function o(e,t){let n={...e},r=i(t.name),a=i(t.description),s=i(t.instructions),o=i(t.output_format),c=i(t.context_requirements),d=i(t.category);return r&&(n.name=r),a&&(n.description=a),s&&(n.instructions=s),o&&(n.outputFormat=o),c&&(n.contextRequirements=c),d&&l(d)&&(n.type=d),n}function c(e){return e.name.trim().length>0&&e.description.trim().length>0&&e.instructions.trim().length>0}function d(e){let t=[];
1return e.name.trim()||t.push("name"),e.description.trim()||t.push("description"),e.instructions.trim()||t.push("instructions"),t}function u(e){var t,n,a,s,l;return{name:null!==(t=i(e.name))&&void 0!==t?t:void 0,description:null!==(n=i(e.description))&&void 0!==n?n:void 0,category:e.type,skill_category_id:e.skillCategoryId===r?null:e.skillCategoryId,visibility:e.visibility,voice_enabled:"dialogue"===e.type,instructions:null!==(a=i(e.instructions))&&void 0!==a?a:void 0,output_format:null!==(s=i(e.outputFormat))&&void 0!==s?s:void 0,context_requirements:null!==(l=i(e.contextRequirements))&&void 0!==l?l:void 0}}function m(e){var t,n,a,o,c,d,u;let m=null!==(t=e.definition)&&void 0!==t?t:{},p=m.output_format,f=m.context_requirements,h=i(e.category);return{name:null!==(n=e.name)&&void 0!==n?n:"",description:null!==(a=e.description)&&void 0!==a?a:"",skillCategoryId:null!==(o=e.skill_category_id)&&void 0!==o?o:r,type:h&&l(h)?h:s.type,visibility:"organization"===e.visibility?"organization":"private",instructions:null!==(c=e.instructions)&&void 0!==c?c:"",outputFormat:null!==(d=i(null==p?void 0:p.description))&&void 0!==d?d:"",contextRequirements:null!==(u=i(null==f?void 0:f.description))&&void 0!==u?u:""}}let p="/skills/create";function f(e){return"/skills/create?draft=".concat(encodeURIComponent(e))}function h(e){return"/skills/".concat(encodeURIComponent(e))}function g(e){return{id:"",name:e.name,description:e.description,category:e.type,instructions:[e.instructions,e.outputFormat?"## Output format\n".concat(e.outputFormat):"",e.contextRequirements?"## Required context\n".concat(e.contextRequirements):""].filter(Boolean).join("\n\n"),workspaces:null,license:null,allowed_tools:null,agent_skills_compatible:!0,metadata:null,owner_type:"user",source:"skill-creator",created_at:null,updated_at:null}}},8400:function(e,t,n){function r(e){let t=[];for(let n of[/\[PATCH\]\s*Find:\s*"([\s\S]*?)"\s*Replace:\s*"([\s\S]*?)"/gi,/find:\s*"([\s\S]*?)"\s*replace:\s*"([\s\S]*?)"/gi,/Find:\s*"([\s\S]*?)"\s*[\n\r]+\s*Replace:\s*"([\s\S]*?)"/gi]){let r;for(n.lastIndex=0;null!==(r=n.exec(e));
1)if(void 0!==r[1]&&void 0!==r[2]){let e=r[1].replace(/\\n/g,"\n").replace(/\\"/g,'"'),n=r[2].replace(/\\n/g,"\n").replace(/\\"/g,'"');t.some(t=>t.find===e&&t.replace===n)||t.push({find:e,replace:n})}}return t.length>0?t:null}function a(e){let t=e.match(/\[FULL\]\s*([\s\S]*?)\s*\[FULL\]/i);return t&&t[1]?t[1].trim():null}function s(e,t){let n=e;for(let e of t)if(n.includes(e.find)){let t=RegExp(e.find.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");n=n.replace(t,e.replace)}else{let t=RegExp(e.find.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");t.test(n)?n=n.replace(t,e.replace):console.warn("Patch not found exactly, skipping:",e.find.substring(0,50))}return n}function i(e){return e.includes("[PATCH]")||/find:\s*"/i.test(e)?"patch":e.includes("[FULL]")?"full":"unknown"}function l(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:2,r=e.split("\n"),a=t.split("\n"),s=[],i=function(e,t){var n,r,a,s,i,l,o,c,d,u;let m=e.length,p=t.length,f=Array(m+1).fill(null).map(()=>Array(p+1).fill(0));for(let o=1;o<=m;o++)for(let c=1;c<=p;c++){let d=e[o-1],u=t[c-1];void 0!==d&&void 0!==u&&d===u?f[o][c]=(null!==(r=null===(n=f[o-1])||void 0===n?void 0:n[c-1])&&void 0!==r?r:0)+1:f[o][c]=Math.max(null!==(i=null===(a=f[o-1])||void 0===a?void 0:a[c])&&void 0!==i?i:0,null!==(l=null===(s=f[o])||void 0===s?void 0:s[c-1])&&void 0!==l?l:0)}let h=[],g=m,x=p;for(;g>0&&x>0;){let n=e[g-1],r=t[x-1];void 0!==n&&void 0!==r&&n===r?(h.unshift(n),g--,x--):(null!==(d=null===(o=f[g-1])||void 0===o?void 0:o[x])&&void 0!==d?d:0)>(null!==(u=null===(c=f[g])||void 0===c?void 0:c[x-1])&&void 0!==u?u:0)?g--:x--}return h}
1(r,a),l=0,o=0,c=0;for(;l<r.length||o<a.length;){var d,u,m,p;c<i.length&&l<r.length&&r[l]===i[c]?o<a.length&&a[o]===i[c]?(s.push({type:"unchanged",text:null!==(d=r[l])&&void 0!==d?d:"",lineNumber:l+1}),l++,o++,c++):(s.push({type:"added",text:null!==(u=a[o])&&void 0!==u?u:"",lineNumber:o+1}),o++):l<r.length&&(c>=i.length||r[l]!==i[c])?(s.push({type:"removed",text:null!==(m=r[l])&&void 0!==m?m:"",lineNumber:l+1}),l++):o<a.length&&(s.push({type:"added",text:null!==(p=a[o])&&void 0!==p?p:"",lineNumber:o+1}),o++)}return function(e,t){if(t<0)return e;let n=[];if(e.forEach((e,t)=>{("added"===e.type||"removed"===e.type)&&n.push(t)}),0===n.length)return[];let r=new Set;for(let a of n)for(let n=a-t;n<=a+t;n++)n>=0&&n<e.length&&r.add(n);let a=[],s=-1;for(let t=0;t<e.length;t++)if(r.has(t)){s>=0&&t>s+1&&a.push({type:"context",text:"..."});let n=e[t];n&&a.push(n),s=t}return a}(s,n)}function o(e,t){var n,r;let a=e.split("\n"),s=e.indexOf(t);if(-1===s)return null;let i=0,l=0;for(let e=0;e<a.length;e++){let t=null!==(n=a[e])&&void 0!==n?n:"";if(i+t.length>=s){l=e+1;break}i+=t.length+1}let o="Dokumentstart",c=0;for(let e=0;e<l&&e<a.length;e++){let t=null!==(r=a[e])&&void 0!==r?r:"",n=t.match(/^(#{1,6})\s+(.+)$/);if(n){let e=n[1],t=n[2];e&&t&&(c=e.length,o=t.trim())}let s=t.match(/<h([1-6])[^>]*>(.+?)<\/h\1>/i);if(s){let e=s[1],t=s[2];e&&t&&(c=parseInt(e,10),o=t.replace(/<[^>]+>/g,"").trim())}}return{section:o,level:c,lineNumber:l,charOffset:s}}n.d(t,{QE:function(){return s},V3:function(){return o},W9:function(){return i},md:function(){return r},oz:function(){return a},qm:function(){return l}})}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.