@filigran/chatbot 3.20.0 → 3.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{createContext as r,useContext as o,useState as a,useRef as s,useMemo as i,useEffect as c,useCallback as l,useInsertionEffect as d,useLayoutEffect as u,useId as h,Component as p,memo as m,forwardRef as g,useImperativeHandle as f}from"react";import v from"remark-gfm";import w from"remark-parse";import{unified as b}from"unified";import{createPortal as y}from"react-dom";import x from"react-markdown";import k from"remark-breaks";function C(e,t){return`${e}${Math.round(255*t).toString(16).padStart(2,"0")}`}function N(e){return function(e){if(!e)return e;const t=e.split("\n"),n=/^(\s*)(`{3,})(.*)$/,r=/^(markdown|md|mdx|markup)\b/i;let o=-1;for(let e=0;e<t.length;e++){const a=t[e].match(n);if(a&&3===a[2].length&&r.test(a[3].trim())){o=e;break}}if(-1===o)return e;const a=[];for(let e=o+1;e<t.length;e++){const r=t[e].match(n);r&&a.push({idx:e,run:r[2].length,bare:""===r[3].trim()})}const s=(e,n)=>{for(let r=e+1;r<n;r++)if(""!==t[r].trim())return!1;return!0};let i=0,c=3,l=0,d=-1;for(let e=0;e<a.length;e++){const t=a[e];if(t.bare&&0===i){const n=a[e+1];if(!n||!n.bare||s(t.idx,n.idx)){d=t.idx;break}i++}else i=t.bare?Math.max(0,i-1):i+1;l++,c=Math.max(c,t.run)}if(-1===d||0===l)return e;const u="`".repeat(Math.max(c+1,4)),h=t[o].match(n);t[o]=`${h[1]}${u}${h[3]}`;const p=t[d].match(n);return t[d]=`${p[1]}${u}`,t.join("\n")}(function(e){if(!e||-1===e.indexOf("|"))return e;const t=e.split("\n"),n=e=>{let t=e.trim();t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));const n=[];let r="";for(let e=0;e<t.length;e++){const o=t[e];"\\"===o&&e+1<t.length?(r+=o+t[e+1],e++):"|"===o?(n.push(r),r=""):r+=o}return n.push(r),n},r=e=>e.includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e),o=e=>{const t=e.trim(),n=t.startsWith(":"),r=t.endsWith(":");return n&&r?":---:":r?"---:":n?":---":"---"},a=/^\s*(?:(?:>\s?)|(?:[-*+]\s+)|(?:\d{1,9}[.)]\s+))*(`{3,}|~{3,})(.*)$/;let s=null,i=0;const c=/^\s*(?:[-*+]\s+|\d{1,9}[.)]\s+)/;for(let e=0;e<t.length-1;e++){const l=t[e].match(a);if(l){const e=l[1];null===s?(s=e[0],i=e.length):e[0]===s&&e.length>=i&&""===l[2].trim()&&(s=null,i=0);continue}if(null!==s)continue;const d=t[e],u=t[e+1];if(!d.includes("|")||r(d)||!r(u))continue;const h=d.match(c),p=h?h[0].length:d.length-d.trimStart().length,m=h?" ".repeat(p):d.slice(0,p),g=n(d.slice(p)).length,f=n(u);if(g<2||f.length===g)continue;const v=[];for(let e=0;e<g;e++)v.push(f[e]?o(f[e]):"---");t[e+1]=`${m}| ${v.join(" | ")} |`}return t.join("\n")}(function(e){const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("[")||t.startsWith("```"))return e;try{return JSON.parse(t),"```json\n"+t+"\n```"}catch{return e}}((t=e).includes("![")?t.replace(/!\[([^\]]*?\n[^\]]*?)\]\(([^)\s]+)\)/g,(e,t,n)=>`![${t.replace(/\s+/g," ").trim()}](${n})`):t)));var t}const S=new Set(["http","https","mailto","tel"]);function T(e){const t=e.indexOf(":");if(t<0)return e;const n=e.indexOf("/"),r=e.indexOf("?"),o=e.indexOf("#");if(n>-1&&t>n||r>-1&&t>r||o>-1&&t>o)return e;const a=e.slice(0,t).toLowerCase();return S.has(a)||"data"===a&&/^data:image\//i.test(e)?e:""}const A=e=>e;function I(e,t,n){return e(t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]??""):e)}function E(e,t,n,r={}){const o=I(e,t,r),a=`{${n}}`,s=o.indexOf(a);return-1===s?{before:o,after:"",hasSlot:!1}:{before:o.slice(0,s),after:o.slice(s+a.length),hasSlot:!0}}function z(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function R(e){const t=[["GB",1024**3],["MB",1048576],["KB",1024]];for(const[n,r]of t)if(e>=r)return`${Math.floor(e/r*10)/10} ${n}`;return`${Math.floor(e)} B`}function M(e){return e<1e3?`${e}`:e<1e6?`${(e/1e3).toFixed(e<1e4?1:0).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}M`}function D(e,t){if(!e)return"";const n=new Date(e).getTime();if(Number.isNaN(n))return"";const r=Date.now()-n,o=Math.floor(r/6e4);if(o<1)return t("just now");if(o<60)return I(t,"{count}m ago",{count:o});const a=Math.floor(o/60);if(a<24)return I(t,"{count}h ago",{count:a});const s=Math.floor(a/24);return s<7?I(t,"{count}d ago",{count:s}):new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const L=["FILE","PRESENTATION","REPORT","VIDEO"],_=`(${L.join("|")}):([^\\]#]+)(?:#\\/([A-Za-z0-9_-]{1,64}))?`,P=/^[A-Z][A-Z0-9_]*$/;const j=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$=new Map;function U(e){const t=e.filter(e=>!L.includes(e)),n=t.join(","),r=$.get(n);if(r)return r;const o=[...L,...t].map(j).join("|"),a=t.length>0?`|(${t.map(j).join("|")}):([^\\]]+)`:"",s=[...L,...t].map(e=>`[[${e}:`),i={complete:new RegExp(`\\[\\[(?:${_}${a})\\]\\]`,"gi"),partial:new RegExp(`\\[\\[(?:${o})(?::[^\\]]*)?\\]?$`,"i"),heads:s,longestHead:Math.max(...s.map(e=>e.length))};return $.size>=32&&$.delete($.keys().next().value),$.set(n,i),i}function O(e,t=!1,n=[]){if(!e)return[];const r=U(n),o=[];let a=0;for(const t of e.matchAll(r.complete)){if(t.index>a&&o.push({type:"text",value:e.slice(a,t.index)}),t[1]){const e=t[1].toUpperCase();n.includes(e)?o.push({type:"marker",kind:e,args:t[3]?`${t[2]}#/${t[3]}`:t[2]}):"FILE"===e?o.push({type:"file",fileId:t[2]}):o.push({type:"artifact",kind:e.toLowerCase(),id:t[2].toLowerCase(),slideRef:t[3]||void 0})}else o.push({type:"marker",kind:t[4].toUpperCase(),args:t[5]});a=t.index+t[0].length}const s=e.slice(a).replace(r.partial,""),i=t?function(e,t){for(let n=Math.max(0,e.length-t.longestHead);n<e.length;n++){if("["!==e[n])continue;const r=e.slice(n).toUpperCase();if(t.heads.some(e=>e.startsWith(r)))return e.slice(0,n)}return e}(s,r):s;return i&&o.push({type:"text",value:i}),o}function W(e,t=[]){const n=[];for(const r of O(e,!1,t))"text"===r.type&&r.value.trim()&&n.push(N(r.value));return n}const q=(e,t)=>`${e}:${t.toLowerCase()}`;function F(e,t){const n=[];if("presentation"===e.kind&&void 0!==e.slideCount&&n.push(I(t,"{count} slides",{count:e.slideCount})),"report"===e.kind&&void 0!==e.sectionCount&&n.push(I(t,"{count} sections",{count:e.sectionCount})),"video"===e.kind){void 0!==e.sceneCount&&n.push(I(t,"{count} scenes",{count:e.sceneCount}));const r=function(e){if(!e||e<=0)return;const t=Math.round(e/1e3);return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}(e.durationMs);r&&n.push(r)}return n.join(" · ")}function H(e){const t=new Map;for(const n of e){const e=n.group?.trim()||null;t.has(e)||t.set(e,[]),t.get(e).push(n)}const n=t.get(null);return t.delete(null),[...n?[{group:null,agents:n}]:[],...[...t].map(([e,t])=>({group:e,agents:t}))]}function B(e,...t){if(e)try{return e(...t)}catch(e){return void console.error("A chat panel host callback threw",e)}}const V={slack:"Slack",teams:"Teams",whatsapp:"WhatsApp",telegram:"Telegram",discord:"Discord",google_chat:"Google Chat"};function K(e,t){if(!e)return null;const n=B(t,e);return void 0!==n?n?.trim()||null:V[e.toLowerCase()]??null}const G=b().use(w).use(v).freeze(),Y=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function X(e){if(Y.has(e.type))return"";if("text"===e.type||"inlineCode"===e.type)return e.value??"";if("break"===e.type)return" ";const t=(e.children??[]).map(X).join("");return"link"!==e.type||!e.url||t!==e.url&&`mailto:${t}`!==e.url?t:""}function J(e,t){if(!Y.has(e.type))switch(e.type){case"paragraph":case"heading":return void t.push(X(e));case"tableRow":return void t.push((e.children??[]).map(X).map(e=>e.trim()).filter(Boolean).join(", "));default:for(const n of e.children??[])J(n,t)}}function Q(e){const t=[];for(const n of e)n.trim()&&J(G.parse(n),t);return t.map(e=>e.replace(/\s+/g," ").replace(/ ([.,!?;:])/g,"$1").trim()).filter(e=>/[\p{L}\p{N}]/u.test(e)).map(e=>/[.!?;:\u3002\uff01\uff1f]$/.test(e)?e:`${e}.`).join("\n")}const Z=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;function ee(e,t=220){const n=e.split(/\n+|(?<=[.!?;:\u3002\uff01\uff1f])\s+/).map(e=>e.trim()).filter(Boolean),r=[];for(const e of n){if(e.length<=t){r.push(e);continue}let n="";for(const o of e.split(" "))for(let e=0;e<o.length;e+=t){const a=o.slice(e,e+t);n?n.length+1+a.length<=t?n=`${n} ${a}`:(r.push(n),n=a):n=a}n&&r.push(n)}const o=[];for(const e of r){const n=o.length-1;n>=0&&o[n].length+1+e.length<=t?o[n]=`${o[n]} ${e}`:o.push(e)}return o}async function*te(e,t,n,r){const o=o=>async function(e,t,n,r){const o=await e(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.requestHeaders??{}},body:JSON.stringify({text:n,format:"mp3"}),signal:r});if(!o.ok)throw new Error(`TTS failed: ${o.status}`);return o.blob()}(e,t,n[o],r).catch(()=>null);let a=n.length>0?o(0):null;for(let e=0;a;e+=1){const t=await a;a=e+1<n.length&&!r.aborted?o(e+1):null,yield t}}const ne=new Set(["text","search","url","email","tel","password"]);function re(e,t,n,r){const o=t?.[r];return"rest"!==n||t?.singleEndpoint||"string"!=typeof o||!o?null:`${e}${o}`}const oe={surface:"--filigran-chat-surface",surfaceRaised:"--filigran-chat-surface-raised",surfaceSubtle:"--filigran-chat-surface-subtle",surfaceHover:"--filigran-chat-surface-hover",inputSurface:"--filigran-chat-input-surface",headerBackground:"--filigran-chat-header-background",text:"--filigran-chat-text",textMuted:"--filigran-chat-text-muted",textSecondary:"--filigran-chat-text-secondary",border:"--filigran-chat-border",textSize:"--filigran-chat-text-size",userBackground:"--filigran-chat-user-background",userText:"--filigran-chat-user-text",userRadius:"--filigran-chat-user-radius",userPadding:"--filigran-chat-user-padding",userTextSize:"--filigran-chat-user-text-size",fontMono:"--filigran-chat-font-mono",codeSize:"--filigran-chat-code-size",codeSurface:"--filigran-chat-code-surface"};function ae(e){const t={};if(!e)return t;for(const[n,r]of Object.entries(oe)){const o=e[n];"string"==typeof o&&o.trim()&&(t[r]=o)}return t}const se={de:{"(no output)":"(keine Ausgabe)","1 tool call":"1 Tool-Aufruf","1 transfer":"1 Übergabe","A file failed to upload: remove it to send the message":"Eine Datei konnte nicht hochgeladen werden: Entfernen Sie sie, um die Nachricht zu senden","A message references at most {count} conversations":"Eine Nachricht verweist auf höchstens {count} Unterhaltungen","Acting on the page…":"Aktion auf der Seite…","Agent · {channel}":"Agent · {channel}","Agent switching is not available here":"Der Agentenwechsel ist hier nicht verfügbar","Almost there":"Gleich geschafft","Also applies to your scheduled runs, until you revoke it":"Gilt auch für Ihre geplanten Ausführungen, bis Sie die Freigabe widerrufen","Always allowed":"Immer erlaubt","Analyzing results (step {step})…":"Ergebnisse werden analysiert (Schritt {step})…","Analyzing results…":"Ergebnisse werden analysiert…","Analyzing the details":"Details werden analysiert",Approved:"Genehmigt","Archive all conversations":"Alle Unterhaltungen archivieren","Archive all conversations?":"Alle Unterhaltungen archivieren?","Ask Assistant":"Assistenten fragen","Ask a question...":"Stellen Sie eine Frage...",Assistant:"Assistent","Attach files":"Dateien anhängen","Attached files":"Angehängte Dateien","Attachments wait for the current response":"Anhänge warten auf die aktuelle Antwort",Back:"Zurück","Bad response":"Schlechte Antwort","Browse agents":"Agenten durchsuchen",Cancel:"Abbrechen","Cancel question":"Frage abbrechen","Clear all conversations":"Alle Unterhaltungen leeren",Close:"Schließen","Collecting results from one task…":"Ergebnisse einer Aufgabe werden gesammelt…","Collecting results from {count} tasks…":"Ergebnisse von {count} Aufgaben werden gesammelt…","Compacting conversation context…":"Kontext der Unterhaltung wird verdichtet…","Composing answer…":"Antwort wird verfasst…",Confirm:"Bestätigen","Connecting integrations…":"Integrationen werden verbunden…","Connecting the dots":"Zusammenhänge werden hergestellt","Consulting an agent…":"Ein Agent wird konsultiert…","Consulting the sources":"Quellen werden geprüft","Consulting {agent}…":"{agent} wird konsultiert…","Consulting {agent}: {count} questions…":"{agent} wird konsultiert: {count} Fragen…","Consulting {agent}: {tool} (+{count} more)…":"{agent} wird konsultiert: {tool} (+{count} weitere)…","Consulting {agent}: {tool}…":"{agent} wird konsultiert: {tool}…","Consulting {agent}: writing the answer…":"{agent} wird konsultiert: Antwort wird verfasst…","Consulting {count} agents…":"{count} Agenten werden konsultiert…","Context full — older turns are being dropped":"Kontext voll — ältere Runden werden verworfen","Context nearly full — older turns are being summarized":"Kontext fast voll — ältere Runden werden zusammengefasst","Context used":"Genutzter Kontext","Continue now":"Jetzt fortfahren",Conversation:"Unterhaltung","Conversation history":"Verlauf der Unterhaltungen","Conversation title":"Titel der Unterhaltung","Conversation transcript":"Verlauf der Unterhaltung",Copied:"Kopiert","Copied!":"Kopiert!","Copy code":"Code kopieren","Copy message":"Nachricht kopieren","Copy response":"Antwort kopieren","Could not load your conversations.":"Ihre Unterhaltungen konnten nicht geladen werden.","Could not reach the assistant service. Check the connection and try again.":"Der Assistenzdienst ist nicht erreichbar. Prüfen Sie die Verbindung und versuchen Sie es erneut.","Could not send your decision. Please try again.":"Ihre Entscheidung konnte nicht gesendet werden. Bitte versuchen Sie es erneut.","Create agent":"Agent erstellen","Crunching the data":"Daten werden ausgewertet","Decline this call":"Diesen Aufruf ablehnen",Declined:"Abgelehnt","Delegating one task…":"Eine Aufgabe wird delegiert…","Delegating {count} tasks…":"{count} Aufgaben werden delegiert…","Delete all conversations":"Alle Unterhaltungen löschen","Delete all conversations?":"Alle Unterhaltungen löschen?","Delete conversation":"Unterhaltung löschen","Delete workspace":"Arbeitsbereich löschen","Delete?":"Löschen?","Dictate a message":"Nachricht diktieren","Did not answer":"Nicht beantwortet",Download:"Herunterladen","Download {format}":"Als {format} herunterladen","Drop a conversation here, or start one with {icon}.":"Legen Sie hier eine Unterhaltung ab oder beginnen Sie eine mit {icon}.","Drop files to attach them":"Dateien zum Anhängen hier ablegen","End voice call":"Sprachanruf beenden","Enter to send · Shift+Enter for new line":"Eingabetaste zum Senden · Umschalt+Eingabetaste für eine neue Zeile","Enter to send now · Esc to stop":"Eingabetaste zum sofortigen Senden · Esc zum Anhalten","Enter to send when the answer ends · Esc to stop":"Eingabetaste zum Senden nach der Antwort · Esc zum Anhalten","Every conversation is in a workspace.":"Jede Unterhaltung ist in einem Arbeitsbereich.","Expand image":"Bild vergrößern","Failed to get a response. Resuming…":"Keine Antwort erhalten. Wird fortgesetzt…","Feedback already submitted":"Feedback bereits gesendet","Files uploading...":"Dateien werden hochgeladen...",Floating:"Schwebend","Full screen":"Vollbild","Good response":"Gute Antwort","Help me create a new simulation scenario":"Hilf mir, ein neues Simulationsszenario zu erstellen","Hide conversations":"Unterhaltungen ausblenden","How can I help you, {name}?":"Wie kann ich Ihnen helfen, {name}?","How can {agent} help you, {name}?":"Wie kann {agent} Ihnen helfen, {name}?","How do I configure detection rules?":"Wie konfiguriere ich Erkennungsregeln?","Image could not be loaded":"Bild konnte nicht geladen werden","Image preview":"Bildvorschau","Incorporating your message…":"Ihre Nachricht wird einbezogen…",Input:"Eingabe","Insert prompt template":"Prompt-Vorlage einfügen","Interrupted by a server restart.":"Durch einen Serverneustart unterbrochen.","Listening...":"Hört zu...","Load earlier messages":"Frühere Nachrichten laden","Loading earlier messages…":"Frühere Nachrichten werden geladen…","Loading conversation history…":"Verlauf der Unterhaltung wird geladen…","Loading image…":"Bild wird geladen…","MCP & dynamic tools":"MCP und dynamische Tools","Mention an agent":"Einen Agenten erwähnen","Model reasoning":"Überlegungen des Modells","Move to workspace":"In Arbeitsbereich verschieben","Mute microphone":"Mikrofon stummschalten",Muted:"Stummgeschaltet","New chat":"Neuer Chat","New conversation":"Neue Unterhaltung","New conversation in this workspace":"Neue Unterhaltung in diesem Arbeitsbereich","New conversation outside a workspace":"Neue Unterhaltung außerhalb eines Arbeitsbereichs","New conversation — send a message to start it":"Neue Unterhaltung — senden Sie eine Nachricht, um sie zu beginnen","New workspace":"Neuer Arbeitsbereich",No:"Nein","No agent matches":"Kein passender Agent","None of your conversations matches":"Keine Ihrer Unterhaltungen passt","No conversation matches":"Keine passende Unterhaltung","No conversations yet":"Noch keine Unterhaltungen","No prompt matches":"Kein passender Prompt","No response was generated. Please try again.":"Es wurde keine Antwort erzeugt. Bitte versuchen Sie es erneut.","No response.":"Keine Antwort.","Not in a workspace":"In keinem Arbeitsbereich","Not recommended for chat":"Nicht für den Chat empfohlen","Not rendered yet":"Noch nicht gerendert",Open:"Öffnen","Open conversation":"Unterhaltung öffnen","Open in XTM One":"In XTM One öffnen","Other workspaces":"Andere Arbeitsbereiche",Output:"Ausgabe","Play Space Invaders":"Space Invaders spielen","Play Space Invaders in XTM One":"Space Invaders in XTM One spielen","Polishing the answer":"Antwort wird verfeinert",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (bearbeitbar)","Preparing tools…":"Tools werden vorbereitet…","Preparing…":"Wird vorbereitet…",Presentation:"Präsentation","Putting it together":"Alles wird zusammengefügt",Quota:"Kontingent","Quota reached":"Kontingent erreicht","Read aloud":"Vorlesen","Reasoning details":"Details der Überlegungen","Reasoning details — interrupted by a server restart":"Details der Überlegungen — durch einen Serverneustart unterbrochen","Reasoning details — turn limit reached":"Details der Überlegungen — Rundenlimit erreicht","Recalling memory…":"Gedächtnis wird abgerufen…","Reconnecting…":"Verbindung wird wiederhergestellt…","Reference a conversation":"Auf eine Unterhaltung verweisen","Remove from workspace":"Aus Arbeitsbereich entfernen","Rename conversation":"Unterhaltung umbenennen","Rename workspace":"Arbeitsbereich umbenennen","Rendering {progress}%":"Wird gerendert: {progress} %",Report:"Bericht","Response ready":"Antwort bereit","Reticulating splines":"Splines werden retikuliert",Retry:"Erneut versuchen",Save:"Speichern","Scroll to bottom":"Nach unten scrollen","Saving response…":"Antwort wird gespeichert…","Search agents...":"Agenten suchen...","Search conversations...":"Unterhaltungen suchen...","Search prompts...":"Prompts suchen...",Send:"Senden","Send now":"Jetzt senden","Send when the answer ends":"Nach der Antwort senden","Sending…":"Wird gesendet…","Sends when the answer ends:":"Wird nach der Antwort gesendet:","Shared with you":"Mit Ihnen geteilt","Show conversations":"Unterhaltungen anzeigen","Show less":"Weniger anzeigen",Sidebar:"Seitenleiste",Skip:"Überspringen","Skip response":"Antwort überspringen","Sorry, an error occurred. Please try again.":"Leider ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.","Speak or tap to interrupt":"Sprechen oder tippen Sie, um zu unterbrechen","Speaking…":"Spricht…","Started in {channel}":"Begonnen in {channel}","Stop dictation":"Diktat beenden","Stop generating":"Generierung anhalten","Stop reading":"Vorlesen beenden",Stopped:"Angehalten","Stopping…":"Wird angehalten…",Suggestions:"Vorschläge","Summarize my recent findings":"Fasse meine jüngsten Erkenntnisse zusammen","Summarized conversation":"Zusammengefasste Unterhaltung","Summarizing earlier conversation…":"Früherer Teil der Unterhaltung wird zusammengefasst…",Superseded:"Ersetzt","Switch to":"Wechseln zu","Switch to another agent":"Zu einem anderen Agenten wechseln","Switch view":"Ansicht wechseln","System prompt":"System-Prompt","Tap to cancel":"Zum Abbrechen tippen","Tell us what went wrong (optional)":"Was ist schiefgelaufen? (optional)","The agent is answering…":"Der Agent antwortet…","The agent needs your approval to run a tool:":"Der Agent benötigt Ihre Freigabe, um ein Tool auszuführen:","The agent needs your approval to run these tools:":"Der Agent benötigt Ihre Freigabe, um diese Tools auszuführen:","The conversation could not be deleted":"Die Unterhaltung konnte nicht gelöscht werden","The conversation could not be moved":"Die Unterhaltung konnte nicht verschoben werden","The conversation could not be renamed":"Die Unterhaltung konnte nicht umbenannt werden","The conversations could not be archived":"Die Unterhaltungen konnten nicht archiviert werden","The conversations could not be deleted":"Die Unterhaltungen konnten nicht gelöscht werden","The render did not finish":"Das Rendern wurde nicht abgeschlossen","The server restarted while this turn was running, so it stopped before it could finish.":"Der Server wurde während dieser Runde neu gestartet, daher wurde sie vor ihrem Abschluss beendet.","The workspace could not be created":"Der Arbeitsbereich konnte nicht erstellt werden","The workspace could not be deleted":"Der Arbeitsbereich konnte nicht gelöscht werden","The workspace could not be renamed":"Der Arbeitsbereich konnte nicht umbenannt werden","Thinking it through":"Wird durchdacht","Thinking...":"Denkt nach...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Dieser Agent ist für Aufträge gedacht, nicht für den direkten Chat. Auf Unterhaltungen antwortet er womöglich schlecht.","This conversation could not be loaded.":"Diese Unterhaltung konnte nicht geladen werden.","This decision could not be sent. Reload the chat and try again.":"Diese Entscheidung konnte nicht gesendet werden. Laden Sie den Chat neu und versuchen Sie es erneut.","This message waits for the current response":"Diese Nachricht wartet auf die aktuelle Antwort","This message will be read with your next one.":"Diese Nachricht wird mit Ihrer nächsten gelesen.","This item could not be loaded.":"Dieses Element konnte nicht geladen werden.","The response could not be stopped. Try again.":"Die Antwort konnte nicht angehalten werden. Versuchen Sie es erneut.","This turn is no longer waiting for a decision.":"Diese Runde wartet nicht mehr auf eine Entscheidung.","Tool definitions":"Tool-Definitionen","Tool results":"Tool-Ergebnisse","Transfer chain":"Übergabekette","Transferred from {agent}":"Übergeben von {agent}","Transferring to another agent…":"Übergabe an einen anderen Agenten…","Transferring to {agent}…":"Übergabe an {agent}…","Turn limit reached.":"Rundenlimit erreicht.","Unable to connect. Please check the configuration.":"Verbindung nicht möglich. Bitte prüfen Sie die Konfiguration.","Unmute microphone":"Stummschaltung des Mikrofons aufheben","Untitled conversation":"Unbenannte Unterhaltung",Usage:"Nutzung","Upload failed":"Hochladen fehlgeschlagen","Usage · {period}":"Nutzung · {period}","Uses AI. Verify results.":"Nutzt KI. Überprüfen Sie die Ergebnisse.","Using tools…":"Tools werden verwendet…",Video:"Video","Voice call":"Sprachanruf","Waiting before continuing…":"Wartet vor dem Fortfahren…","Waiting for one background task…":"Wartet auf eine Hintergrundaufgabe…","Waiting for your approval…":"Wartet auf Ihre Freigabe…","Waiting for {count} background tasks…":"Wartet auf {count} Hintergrundaufgaben…","Waiting to render":"Wartet auf das Rendern","What are the latest attack patterns?":"Was sind die neuesten Angriffsmuster?","What could be improved?":"Was könnte verbessert werden?","Why not? The agent sees this and can adapt (optional)":"Warum nicht? Der Agent sieht dies und kann sich anpassen (optional)","Working files ({count})":"Arbeitsdateien ({count})","Workspace name":"Name des Arbeitsbereichs",Workspaces:"Arbeitsbereiche","Wrapping things up":"Wird abgeschlossen",Yes:"Ja","Yes, always":"Ja, immer","Your answer is ready":"Ihre Antwort ist bereit",default:"Standard","e.g. wrong environment — use staging instead":"z. B. falsche Umgebung — stattdessen die Staging-Umgebung verwenden","just now":"gerade eben","this month":"diesen Monat","this year":"dieses Jahr",today:"heute","unknown tool":"unbekanntes Tool","{agent} has finished":"{agent} ist fertig","{agent} is answering…":"{agent} antwortet…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"{counts} Tokens","{count} iterations":"{count} Iterationen","{count} scenes":"{count} Szenen","{count} sections":"{count} Abschnitte","{count} slides":"{count} Folien","{count} tool calls":"{count} Tool-Aufrufe","{count} transfers":"{count} Übergaben","{count}d ago":"vor {count} T.","{count}h ago":"vor {count} Std.","{count}m ago":"vor {count} Min.","{decided}/{total} decided":"{decided}/{total} entschieden","{name} was not attached: a file may be at most {size}.":"{name} wurde nicht angehängt: Eine Datei darf höchstens {size} groß sein.","{name} was not attached: a message holds at most {count} files.":"{name} wurde nicht angehängt: Eine Nachricht enthält höchstens {count} Dateien.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} wurde nicht angehängt: Die Dateien einer Nachricht dürfen zusammen höchstens {size} groß sein.","{name} was not attached: this type of file is not accepted.":"{name} wurde nicht angehängt: Dieser Dateityp wird nicht akzeptiert.","{percent}% full":"{percent} % belegt","{quota} (shared across all users)":"{quota} (von allen Benutzern gemeinsam genutzt)","{summary} — click for details":"{summary} — für Details klicken","{tool} (+{count} more)…":"{tool} (+{count} weitere)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Das Iterationsbudget des Agenten ist aufgebraucht: Die Ausführung wurde beendet, bevor alle geplanten Schritte abgeschlossen waren. Die endgültige Antwort fasst die bisher geleistete Arbeit so gut wie möglich zusammen.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"„Ja, immer“ speichert eine Einstellung für Sie. Dieses Tool wird dann ohne Nachfrage ausgeführt — auch bei geplanten Ausführungen, die niemand beobachtet —, bis Sie die Freigabe widerrufen."},es:{"(no output)":"(sin salida)","1 tool call":"1 llamada a una herramienta","1 transfer":"1 transferencia","A file failed to upload: remove it to send the message":"Un archivo no se pudo subir: quítelo para enviar el mensaje","A message references at most {count} conversations":"Un mensaje puede hacer referencia a {count} conversaciones como máximo","Acting on the page…":"Actuando en la página…","Agent · {channel}":"Agente · {channel}","Agent switching is not available here":"El cambio de agente no está disponible aquí","Almost there":"Ya casi estamos","Also applies to your scheduled runs, until you revoke it":"También se aplica a sus ejecuciones programadas, hasta que lo revoque","Always allowed":"Siempre permitido","Analyzing results (step {step})…":"Analizando los resultados (paso {step})…","Analyzing results…":"Analizando los resultados…","Analyzing the details":"Analizando los detalles",Approved:"Aprobado","Archive all conversations":"Archivar todas las conversaciones","Archive all conversations?":"¿Archivar todas las conversaciones?","Ask Assistant":"Preguntar al asistente","Ask a question...":"Haga una pregunta...",Assistant:"Asistente","Attach files":"Adjuntar archivos","Attached files":"Archivos adjuntos","Attachments wait for the current response":"Los archivos adjuntos esperan la respuesta actual",Back:"Volver","Bad response":"Respuesta incorrecta","Browse agents":"Explorar agentes",Cancel:"Cancelar","Cancel question":"Cancelar la pregunta","Clear all conversations":"Borrar todas las conversaciones",Close:"Cerrar","Collecting results from one task…":"Recopilando los resultados de una tarea…","Collecting results from {count} tasks…":"Recopilando los resultados de {count} tareas…","Compacting conversation context…":"Compactando el contexto de la conversación…","Composing answer…":"Redactando la respuesta…",Confirm:"Confirmar","Connecting integrations…":"Conectando las integraciones…","Connecting the dots":"Atando cabos","Consulting an agent…":"Consultando a un agente…","Consulting the sources":"Consultando las fuentes","Consulting {agent}…":"Consultando a {agent}…","Consulting {agent}: {count} questions…":"Consultando a {agent}: {count} preguntas…","Consulting {agent}: {tool} (+{count} more)…":"Consultando a {agent}: {tool} (+{count} más)…","Consulting {agent}: {tool}…":"Consultando a {agent}: {tool}…","Consulting {agent}: writing the answer…":"Consultando a {agent}: redactando la respuesta…","Consulting {count} agents…":"Consultando a {count} agentes…","Context full — older turns are being dropped":"Contexto completo: se están eliminando los turnos más antiguos","Context nearly full — older turns are being summarized":"El contexto está casi lleno: se están resumiendo los turnos más antiguos","Context used":"Contexto utilizado","Continue now":"Continuar ahora",Conversation:"Conversación","Conversation history":"Historial de conversaciones","Conversation title":"Título de la conversación","Conversation transcript":"Hilo de la conversación",Copied:"Copiado","Copied!":"¡Copiado!","Copy code":"Copiar código","Copy message":"Copiar mensaje","Copy response":"Copiar respuesta","Could not load your conversations.":"No se pudieron cargar sus conversaciones.","Could not reach the assistant service. Check the connection and try again.":"No se ha podido conectar con el servicio del asistente. Compruebe la conexión e inténtelo de nuevo.","Could not send your decision. Please try again.":"No se ha podido enviar su decisión. Inténtelo de nuevo.","Create agent":"Crear agente","Crunching the data":"Procesando los datos","Decline this call":"Rechazar esta llamada",Declined:"Rechazado","Delegating one task…":"Delegando una tarea…","Delegating {count} tasks…":"Delegando {count} tareas…","Delete all conversations":"Eliminar todas las conversaciones","Delete all conversations?":"¿Eliminar todas las conversaciones?","Delete conversation":"Eliminar conversación","Delete workspace":"Eliminar espacio de trabajo","Delete?":"¿Eliminar?","Dictate a message":"Dictar un mensaje","Did not answer":"No respondió",Download:"Descargar","Download {format}":"Descargar en {format}","Drop a conversation here, or start one with {icon}.":"Suelte aquí una conversación o inicie una con {icon}.","Drop files to attach them":"Suelte los archivos para adjuntarlos","End voice call":"Finalizar la llamada de voz","Enter to send · Shift+Enter for new line":"Pulse Intro para enviar · Mayús+Intro para una nueva línea","Enter to send now · Esc to stop":"Pulse Intro para enviar ahora · Esc para detener","Enter to send when the answer ends · Esc to stop":"Pulse Intro para enviar cuando termine la respuesta · Esc para detener","Every conversation is in a workspace.":"Todas las conversaciones están en un espacio de trabajo.","Expand image":"Ampliar imagen","Failed to get a response. Resuming…":"No se obtuvo respuesta. Reanudando…","Feedback already submitted":"Valoración ya enviada","Files uploading...":"Cargando archivos...",Floating:"Flotante","Full screen":"Pantalla completa","Good response":"Buena respuesta","Help me create a new simulation scenario":"Ayúdame a crear un nuevo escenario de simulación","Hide conversations":"Ocultar conversaciones","How can I help you, {name}?":"¿En qué puedo ayudarle, {name}?","How can {agent} help you, {name}?":"¿En qué puede ayudarle {agent}, {name}?","How do I configure detection rules?":"¿Cómo configuro las reglas de detección?","Image could not be loaded":"No se ha podido cargar la imagen","Image preview":"Vista previa de la imagen","Incorporating your message…":"Incorporando su mensaje…",Input:"Entrada","Insert prompt template":"Insertar plantilla de prompt","Interrupted by a server restart.":"Interrumpido por un reinicio del servidor.","Listening...":"Escuchando...","Load earlier messages":"Cargar mensajes anteriores","Loading earlier messages…":"Cargando mensajes anteriores…","Loading conversation history…":"Cargando el historial de la conversación…","Loading image…":"Cargando imagen…","MCP & dynamic tools":"MCP y herramientas dinámicas","Mention an agent":"Mencionar un agente","Model reasoning":"Razonamiento del modelo","Move to workspace":"Mover a un espacio de trabajo","Mute microphone":"Silenciar el micrófono",Muted:"Silenciado","New chat":"Nuevo chat","New conversation":"Nueva conversación","New conversation in this workspace":"Nueva conversación en este espacio de trabajo","New conversation outside a workspace":"Nueva conversación fuera de un espacio de trabajo","New conversation — send a message to start it":"Nueva conversación: envíe un mensaje para iniciarla","New workspace":"Nuevo espacio de trabajo",No:"No","No agent matches":"No hay ningún agente que coincida","None of your conversations matches":"Ninguna de sus conversaciones coincide","No conversation matches":"No hay conversaciones que coincidan","No conversations yet":"Aún no hay conversaciones","No prompt matches":"No hay ningún prompt que coincida","No response was generated. Please try again.":"No se ha generado ninguna respuesta. Inténtalo de nuevo.","No response.":"Sin respuesta.","Not in a workspace":"Sin espacio de trabajo","Not recommended for chat":"No recomendado para chat","Not rendered yet":"Renderizado no iniciado",Open:"Abrir","Open conversation":"Abrir conversación","Open in XTM One":"Abrir en XTM One","Other workspaces":"Otros espacios de trabajo",Output:"Salida","Play Space Invaders":"Jugar a Space Invaders","Play Space Invaders in XTM One":"Jugar a Space Invaders en XTM One","Polishing the answer":"Puliendo la respuesta",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (editable)","Preparing tools…":"Preparando las herramientas…","Preparing…":"Preparando…",Presentation:"Presentación","Putting it together":"Juntando las piezas",Quota:"Cuota","Quota reached":"Cuota alcanzada","Read aloud":"Leer en voz alta","Reasoning details":"Detalles del razonamiento","Reasoning details — interrupted by a server restart":"Detalles del razonamiento: interrumpido por un reinicio del servidor","Reasoning details — turn limit reached":"Detalles del razonamiento: se ha alcanzado el límite de turnos","Recalling memory…":"Recuperando la memoria…","Reconnecting…":"Reconectando…","Reference a conversation":"Hacer referencia a una conversación","Remove from workspace":"Quitar del espacio de trabajo","Rename conversation":"Cambiar el nombre de la conversación","Rename workspace":"Cambiar el nombre del espacio de trabajo","Rendering {progress}%":"Renderizando {progress} %",Report:"Informe","Response ready":"Respuesta lista","Reticulating splines":"Reticulando splines",Retry:"Reintentar",Save:"Guardar","Scroll to bottom":"Ir al final","Saving response…":"Guardando la respuesta…","Search agents...":"Buscar agentes...","Search conversations...":"Buscar conversaciones...","Search prompts...":"Buscar prompts...",Send:"Enviar","Send now":"Enviar ahora","Send when the answer ends":"Enviar cuando termine la respuesta","Sending…":"Enviando…","Sends when the answer ends:":"Se enviará cuando termine la respuesta:","Shared with you":"Compartido con usted","Show conversations":"Mostrar conversaciones","Show less":"Mostrar menos",Sidebar:"Barra lateral",Skip:"Omitir","Skip response":"Omitir la respuesta","Sorry, an error occurred. Please try again.":"Lo sentimos, se ha producido un error. Inténtelo de nuevo.","Speak or tap to interrupt":"Habla o toca para interrumpir","Speaking…":"Hablando…","Started in {channel}":"Iniciada en {channel}","Stop dictation":"Detener el dictado","Stop generating":"Detener la generación","Stop reading":"Detener la lectura",Stopped:"Detenido","Stopping…":"Deteniendo…",Suggestions:"Sugerencias","Summarize my recent findings":"Resume mis hallazgos recientes","Summarized conversation":"Conversación resumida","Summarizing earlier conversation…":"Resumiendo la conversación anterior…",Superseded:"Reemplazado","Switch to":"Cambiar a","Switch to another agent":"Cambiar a otro agente","Switch view":"Cambiar de vista","System prompt":"Prompt del sistema","Tap to cancel":"Toca para cancelar","Tell us what went wrong (optional)":"Indíquenos qué ha fallado (opcional)","The agent is answering…":"El agente está respondiendo…","The agent needs your approval to run a tool:":"El agente necesita su aprobación para ejecutar una herramienta:","The agent needs your approval to run these tools:":"El agente necesita su aprobación para ejecutar estas herramientas:","The conversation could not be deleted":"No se ha podido eliminar la conversación","The conversation could not be moved":"No se ha podido mover la conversación","The conversation could not be renamed":"No se ha podido cambiar el nombre de la conversación","The conversations could not be archived":"No se han podido archivar las conversaciones","The conversations could not be deleted":"No se han podido eliminar las conversaciones","The render did not finish":"El renderizado no ha finalizado","The server restarted while this turn was running, so it stopped before it could finish.":"El servidor se reinició mientras se ejecutaba este turno, por lo que se detuvo antes de poder terminar.","The workspace could not be created":"No se ha podido crear el espacio de trabajo","The workspace could not be deleted":"No se ha podido eliminar el espacio de trabajo","The workspace could not be renamed":"No se ha podido cambiar el nombre del espacio de trabajo","Thinking it through":"Reflexionando sobre ello","Thinking...":"Pensando...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Este agente está pensado para asignaciones, no para el chat directo. Puede que no responda bien a una conversación.","This conversation could not be loaded.":"No se ha podido cargar esta conversación.","This decision could not be sent. Reload the chat and try again.":"No se ha podido enviar esta decisión. Actualice el chat e inténtelo de nuevo.","This message waits for the current response":"Este mensaje espera la respuesta actual","This message will be read with your next one.":"Este mensaje se leerá con su próximo mensaje.","This item could not be loaded.":"No se ha podido cargar este elemento.","The response could not be stopped. Try again.":"No se ha podido detener la respuesta. Inténtelo de nuevo.","This turn is no longer waiting for a decision.":"Este turno ya no está a la espera de una decisión.","Tool definitions":"Definiciones de herramientas","Tool results":"Resultados de las herramientas","Transfer chain":"Cadena de transferencia","Transferred from {agent}":"Transferido desde {agent}","Transferring to another agent…":"Transfiriendo a otro agente…","Transferring to {agent}…":"Transfiriendo a {agent}…","Turn limit reached.":"Se ha alcanzado el límite de turnos.","Unable to connect. Please check the configuration.":"No se puede establecer conexión. Compruebe la configuración.","Unmute microphone":"Activar el micrófono","Untitled conversation":"Conversación sin título",Usage:"Uso","Upload failed":"Error al subir","Usage · {period}":"Uso · {period}","Uses AI. Verify results.":"Utiliza IA. Verifique los resultados.","Using tools…":"Usando herramientas…",Video:"Vídeo","Voice call":"Llamada de voz","Waiting before continuing…":"Esperando antes de continuar…","Waiting for one background task…":"Esperando una tarea en segundo plano…","Waiting for your approval…":"Esperando su aprobación…","Waiting for {count} background tasks…":"Esperando {count} tareas en segundo plano…","Waiting to render":"Esperando el renderizado","What are the latest attack patterns?":"¿Cuáles son los últimos patrones de ataque?","What could be improved?":"¿Qué se podría mejorar?","Why not? The agent sees this and can adapt (optional)":"¿Por qué no? El agente ve esto y puede adaptarse (opcional)","Working files ({count})":"Archivos de trabajo ({count})","Workspace name":"Nombre del espacio de trabajo",Workspaces:"Espacios de trabajo","Wrapping things up":"Finalizando",Yes:"Sí","Yes, always":"Sí, siempre","Your answer is ready":"Su respuesta está lista",default:"predeterminado","e.g. wrong environment — use staging instead":"Por ejemplo, entorno incorrecto: utilice el entorno de pruebas en su lugar","just now":"hace un momento","this month":"este mes","this year":"este año",today:"hoy","unknown tool":"herramienta desconocida","{agent} has finished":"{agent} ha finalizado","{agent} is answering…":"{agent} está respondiendo…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"{counts} tokens","{count} iterations":"{count} iteraciones","{count} scenes":"{count} escenas","{count} sections":"{count} secciones","{count} slides":"{count} diapositivas","{count} tool calls":"{count} llamadas a herramientas","{count} transfers":"{count} transferencias","{count}d ago":"hace {count} d","{count}h ago":"hace {count} h","{count}m ago":"hace {count} min","{decided}/{total} decided":"{decided}/{total} decididos","{name} was not attached: a file may be at most {size}.":"{name} no se adjuntó: un archivo puede ocupar como máximo {size}.","{name} was not attached: a message holds at most {count} files.":"{name} no se adjuntó: un mensaje admite como máximo {count} archivos.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} no se adjuntó: los archivos de un mensaje pueden sumar como máximo {size}.","{name} was not attached: this type of file is not accepted.":"{name} no se adjuntó: este tipo de archivo no se acepta.","{percent}% full":"{percent} % completo","{quota} (shared across all users)":"{quota} (compartido entre todos los usuarios)","{summary} — click for details":"{summary} — haga clic para ver más detalles","{tool} (+{count} more)…":"{tool} (+{count} más)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Se agotó el presupuesto de iteraciones del agente: la ejecución se detuvo antes de completar todos los pasos previstos. La respuesta final es un resumen aproximado del trabajo realizado hasta ahora.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"«Sí, siempre» guarda una preferencia para ti. Esa herramienta se ejecutará entonces sin preguntar, incluso en ejecuciones programadas que nadie supervisa, hasta que la revoques."},fr:{"(no output)":"(pas de sortie)","1 tool call":"1 appel d’outil","1 transfer":"1 transfert","A file failed to upload: remove it to send the message":"Un fichier n’a pas pu être envoyé : retirez-le pour envoyer le message","A message references at most {count} conversations":"Un message fait référence à {count} conversations au maximum","Acting on the page…":"Action sur la page…","Agent · {channel}":"Agent · {channel}","Agent switching is not available here":"Le changement d’agent n’est pas disponible ici","Almost there":"On y est presque","Also applies to your scheduled runs, until you revoke it":"S’applique également à vos exécutions planifiées, jusqu’à ce que vous la révoquiez","Always allowed":"Toujours autorisé","Analyzing results (step {step})…":"Analyse des résultats (étape {step})…","Analyzing results…":"Analyse des résultats…","Analyzing the details":"Analyse des détails",Approved:"Approuvé","Archive all conversations":"Archiver toutes les conversations","Archive all conversations?":"Archiver toutes les conversations ?","Ask Assistant":"Demander à l’assistant","Ask a question...":"Poser une question...",Assistant:"Assistant","Attach files":"Joindre des fichiers","Attached files":"Fichiers joints","Attachments wait for the current response":"Les pièces jointes attendent la réponse en cours",Back:"Retour","Bad response":"Réponse incorrecte","Browse agents":"Parcourir les agents",Cancel:"Annuler","Cancel question":"Annuler la question","Clear all conversations":"Effacer toutes les conversations",Close:"Fermer","Collecting results from one task…":"Collecte des résultats d’une tâche…","Collecting results from {count} tasks…":"Collecte des résultats de {count} tâches…","Compacting conversation context…":"Compactage du contexte de la conversation…","Composing answer…":"Rédaction de la réponse…",Confirm:"Confirmer","Connecting integrations…":"Connexion des intégrations…","Connecting the dots":"Relier les points","Consulting an agent…":"Consultation d’un agent…","Consulting the sources":"Consulter les sources","Consulting {agent}…":"Consultation de {agent}…","Consulting {agent}: {count} questions…":"Consultation de {agent} : {count} questions…","Consulting {agent}: {tool} (+{count} more)…":"Consultation de {agent} : {tool} (+{count} autres)…","Consulting {agent}: {tool}…":"Consultation de {agent} : {tool}…","Consulting {agent}: writing the answer…":"Consultation de {agent} : rédaction de la réponse…","Consulting {count} agents…":"Consultation de {count} agents…","Context full — older turns are being dropped":"Contexte complet — les tours plus anciens sont supprimés","Context nearly full — older turns are being summarized":"Contexte presque plein — les tours plus anciens sont en cours de synthèse","Context used":"Contexte utilisé","Continue now":"Continuer maintenant",Conversation:"Conversation","Conversation history":"Historique des conversations","Conversation title":"Titre de la conversation","Conversation transcript":"Fil de la conversation",Copied:"Copié","Copied!":"Copié !","Copy code":"Copier le code","Copy message":"Copier le message","Copy response":"Copier la réponse","Could not load your conversations.":"Impossible de charger vos conversations.","Could not reach the assistant service. Check the connection and try again.":"Impossible d’accéder au service d’assistant. Vérifiez la connexion et réessayez.","Could not send your decision. Please try again.":"Impossible d’envoyer votre décision. Veuillez réessayer.","Create agent":"Créer un agent","Crunching the data":"Traitement des données","Decline this call":"Refuser cet appel",Declined:"Refusé","Delegating one task…":"Délégation d’une tâche…","Delegating {count} tasks…":"Délégation de {count} tâches…","Delete all conversations":"Supprimer toutes les conversations","Delete all conversations?":"Supprimer toutes les conversations ?","Delete conversation":"Supprimer la conversation","Delete workspace":"Supprimer l’espace de travail","Delete?":"Supprimer ?","Dictate a message":"Dicter un message","Did not answer":"N’a pas répondu",Download:"Télécharger","Download {format}":"Télécharger en {format}","Drop a conversation here, or start one with {icon}.":"Déposez une conversation ici ou démarrez-en une avec {icon}.","Drop files to attach them":"Déposez des fichiers pour les joindre","End voice call":"Terminer l’appel vocal","Enter to send · Shift+Enter for new line":"Appuyez sur Entrée pour envoyer · Maj+Entrée pour une nouvelle ligne","Enter to send now · Esc to stop":"Appuyez sur Entrée pour envoyer maintenant · Appuyez sur Échap pour arrêter","Enter to send when the answer ends · Esc to stop":"Appuyez sur Entrée pour envoyer à la fin de la réponse · Appuyez sur Échap pour arrêter","Every conversation is in a workspace.":"Toutes les conversations sont dans un espace de travail.","Expand image":"Agrandir l’image","Failed to get a response. Resuming…":"Aucune réponse reçue. Reprise…","Feedback already submitted":"Avis déjà envoyé","Files uploading...":"Envoi des fichiers en cours...",Floating:"Flottant","Full screen":"Plein écran","Good response":"Bonne réponse","Help me create a new simulation scenario":"Aidez-moi à créer un nouveau scénario de simulation","Hide conversations":"Masquer les conversations","How can I help you, {name}?":"Comment puis-je vous aider, {name} ?","How can {agent} help you, {name}?":"Comment {agent} peut-il vous aider, {name} ?","How do I configure detection rules?":"Comment configurer les règles de détection ?","Image could not be loaded":"Impossible de charger l’image","Image preview":"Aperçu de l’image","Incorporating your message…":"Intégration de votre message…",Input:"Entrée","Insert prompt template":"Insérer un modèle de prompt","Interrupted by a server restart.":"Interrompu par un redémarrage du serveur.","Listening...":"Écoute en cours...","Load earlier messages":"Charger les messages précédents","Loading earlier messages…":"Chargement des messages précédents…","Loading conversation history…":"Chargement de l’historique de la conversation…","Loading image…":"Chargement de l’image…","MCP & dynamic tools":"MCP et outils dynamiques","Mention an agent":"Mentionner un agent","Model reasoning":"Raisonnement du modèle","Move to workspace":"Déplacer vers un espace de travail","Mute microphone":"Couper le micro",Muted:"Micro coupé","New chat":"Nouveau chat","New conversation":"Nouvelle conversation","New conversation in this workspace":"Nouvelle conversation dans cet espace de travail","New conversation outside a workspace":"Nouvelle conversation hors espace de travail","New conversation — send a message to start it":"Nouvelle conversation — envoyez un message pour la démarrer","New workspace":"Nouvel espace de travail",No:"Non","No agent matches":"Aucun agent ne correspond","None of your conversations matches":"Aucune de vos conversations ne correspond","No conversation matches":"Aucune conversation ne correspond","No conversations yet":"Aucune conversation pour l’instant","No prompt matches":"Aucun prompt ne correspond","No response was generated. Please try again.":"Aucune réponse n’a été générée. Veuillez réessayer.","No response.":"Pas de réponse.","Not in a workspace":"Hors espace de travail","Not recommended for chat":"Déconseillé pour le chat","Not rendered yet":"Rendu non lancé",Open:"Ouvrir","Open conversation":"Ouvrir la conversation","Open in XTM One":"Ouvrir dans XTM One","Other workspaces":"Autres espaces de travail",Output:"Sortie","Play Space Invaders":"Jouer à Space Invaders","Play Space Invaders in XTM One":"Jouer à Space Invaders dans XTM One","Polishing the answer":"Peaufiner la réponse",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (modifiable)","Preparing tools…":"Préparation des outils…","Preparing…":"Préparation…",Presentation:"Présentation","Putting it together":"Assemblage des éléments",Quota:"Quota","Quota reached":"Quota atteint","Read aloud":"Lire à voix haute","Reasoning details":"Détails du raisonnement","Reasoning details — interrupted by a server restart":"Détails du raisonnement — interrompu par un redémarrage du serveur","Reasoning details — turn limit reached":"Détails du raisonnement — limite de tours atteinte","Recalling memory…":"Rappel de la mémoire…","Reconnecting…":"Reconnexion…","Reference a conversation":"Faire référence à une conversation","Remove from workspace":"Retirer de l’espace de travail","Rename conversation":"Renommer la conversation","Rename workspace":"Renommer l’espace de travail","Rendering {progress}%":"Rendu en cours : {progress} %",Report:"Rapport","Response ready":"Réponse prête","Reticulating splines":"Réticulation des splines",Retry:"Réessayer",Save:"Sauvegarder","Scroll to bottom":"Aller en bas","Saving response…":"Enregistrement de la réponse…","Search agents...":"Rechercher des agents...","Search conversations...":"Rechercher des conversations...","Search prompts...":"Rechercher des prompts...",Send:"Envoyer","Send now":"Envoyer maintenant","Send when the answer ends":"Envoyer à la fin de la réponse","Sending…":"Envoi en cours…","Sends when the answer ends:":"Envoi à la fin de la réponse :","Shared with you":"Partagé avec vous","Show conversations":"Afficher les conversations","Show less":"Afficher moins",Sidebar:"Barre latérale",Skip:"Passer","Skip response":"Passer la réponse","Sorry, an error occurred. Please try again.":"Désolé, une erreur s’est produite. Veuillez réessayer.","Speak or tap to interrupt":"Parlez ou touchez pour interrompre","Speaking…":"Réponse en cours…","Started in {channel}":"Démarrée dans {channel}","Stop dictation":"Arrêter la dictée","Stop generating":"Arrêter la génération","Stop reading":"Arrêter la lecture",Stopped:"Arrêté","Stopping…":"Arrêt en cours…",Suggestions:"Suggestions","Summarize my recent findings":"Résumez mes dernières découvertes","Summarized conversation":"Résumé de la conversation","Summarizing earlier conversation…":"Résumé du début de la conversation…",Superseded:"Remplacé","Switch to":"Basculer vers","Switch to another agent":"Passer à un autre agent","Switch view":"Changer de vue","System prompt":"Prompt système","Tap to cancel":"Touchez pour annuler","Tell us what went wrong (optional)":"Dites-nous ce qui n’a pas fonctionné (facultatif)","The agent is answering…":"L’agent répond…","The agent needs your approval to run a tool:":"L’agent a besoin de votre accord pour exécuter un outil :","The agent needs your approval to run these tools:":"L’agent a besoin de votre accord pour exécuter ces outils :","The conversation could not be deleted":"Impossible de supprimer la conversation","The conversation could not be moved":"Impossible de déplacer la conversation","The conversation could not be renamed":"Impossible de renommer la conversation","The conversations could not be archived":"Impossible d’archiver les conversations","The conversations could not be deleted":"Impossible de supprimer les conversations","The render did not finish":"Le rendu n’a pas abouti","The server restarted while this turn was running, so it stopped before it could finish.":"Le serveur a redémarré pendant ce tour, qui s’est donc arrêté avant de pouvoir se terminer.","The workspace could not be created":"Impossible de créer l’espace de travail","The workspace could not be deleted":"Impossible de supprimer l’espace de travail","The workspace could not be renamed":"Impossible de renommer l’espace de travail","Thinking it through":"Réfléchir à la question","Thinking...":"Je réfléchis...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Cet agent est conçu pour des missions, pas pour le chat direct. Il risque de mal répondre à une conversation.","This conversation could not be loaded.":"Impossible de charger cette conversation.","This decision could not be sent. Reload the chat and try again.":"Cette décision n’a pas pu être envoyée. Actualisez le chat et réessayez.","This message waits for the current response":"Ce message attend la réponse en cours","This message will be read with your next one.":"Ce message sera lu avec votre prochain message.","This item could not be loaded.":"Impossible de charger cet élément.","The response could not be stopped. Try again.":"La réponse n’a pas pu être arrêtée. Réessayez.","This turn is no longer waiting for a decision.":"Ce tour n’attend plus de décision.","Tool definitions":"Définitions des outils","Tool results":"Résultats des outils","Transfer chain":"Chaîne de transfert","Transferred from {agent}":"Transféré depuis {agent}","Transferring to another agent…":"Transfert vers un autre agent…","Transferring to {agent}…":"Transfert vers {agent}…","Turn limit reached.":"Limite de tours atteinte.","Unable to connect. Please check the configuration.":"Impossible de se connecter. Veuillez vérifier la configuration.","Unmute microphone":"Réactiver le micro","Untitled conversation":"Conversation sans titre",Usage:"Utilisation","Upload failed":"Échec de l’envoi","Usage · {period}":"Utilisation · {period}","Uses AI. Verify results.":"Utilise l’IA. Vérifiez les résultats.","Using tools…":"Utilisation des outils…",Video:"Vidéo","Voice call":"Appel vocal","Waiting before continuing…":"En attente avant de continuer…","Waiting for one background task…":"En attente d’une tâche en arrière-plan…","Waiting for your approval…":"En attente de votre accord…","Waiting for {count} background tasks…":"En attente de {count} tâches en arrière-plan…","Waiting to render":"En attente du rendu","What are the latest attack patterns?":"Quels sont les derniers schémas d’attaque ?","What could be improved?":"Qu’est-ce qui pourrait être amélioré ?","Why not? The agent sees this and can adapt (optional)":"Pourquoi pas ? L’agent en prend connaissance et peut s’adapter (facultatif)","Working files ({count})":"Fichiers de travail ({count})","Workspace name":"Nom de l’espace de travail",Workspaces:"Espaces de travail","Wrapping things up":"Pour conclure",Yes:"Oui","Yes, always":"Oui, toujours","Your answer is ready":"Votre réponse est prête",default:"par défaut","e.g. wrong environment — use staging instead":"Par exemple : environnement incorrect — utilisez plutôt l’environnement de préproduction","just now":"à l’instant","this month":"ce mois-ci","this year":"cette année",today:"aujourd’hui","unknown tool":"outil inconnu","{agent} has finished":"{agent} a terminé","{agent} is answering…":"{agent} répond…","{agent}: {status}":"{agent} : {status}","{counts} tokens":"{counts} tokens","{count} iterations":"{count} itérations","{count} scenes":"{count} scènes","{count} sections":"{count} sections","{count} slides":"{count} diapositives","{count} tool calls":"{count} appels d’outils","{count} transfers":"{count} transferts","{count}d ago":"il y a {count} j","{count}h ago":"il y a {count} h","{count}m ago":"il y a {count} min","{decided}/{total} decided":"{decided}/{total} décidés","{name} was not attached: a file may be at most {size}.":"{name} n’a pas été joint : un fichier ne peut dépasser {size}.","{name} was not attached: a message holds at most {count} files.":"{name} n’a pas été joint : un message contient au plus {count} fichiers.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} n’a pas été joint : les fichiers d’un message ne peuvent dépasser {size} au total.","{name} was not attached: this type of file is not accepted.":"{name} n’a pas été joint : ce type de fichier n’est pas accepté.","{percent}% full":"{percent} % rempli","{quota} (shared across all users)":"{quota} (partagé entre tous les utilisateurs)","{summary} — click for details":"{summary} — cliquez pour plus de détails","{tool} (+{count} more)…":"{tool} (+{count} autres)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Le budget d’itérations de l’agent est épuisé : l’exécution s’est arrêtée avant la fin de toutes les étapes prévues. La réponse finale résume au mieux le travail accompli jusqu’ici.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"« Oui, toujours » enregistre une préférence pour vous. Cet outil s’exécutera alors sans demander, y compris lors des exécutions planifiées que personne ne surveille, jusqu’à ce que vous la révoquiez."},it:{"(no output)":"(nessun output)","1 tool call":"1 chiamata a strumento","1 transfer":"1 trasferimento","A file failed to upload: remove it to send the message":"Il caricamento di un file non è riuscito: rimuovilo per inviare il messaggio","A message references at most {count} conversations":"Un messaggio può fare riferimento al massimo a {count} conversazioni","Acting on the page…":"Azione sulla pagina…","Agent · {channel}":"Agente · {channel}","Agent switching is not available here":"Il cambio di agente non è disponibile qui","Almost there":"Quasi fatto","Also applies to your scheduled runs, until you revoke it":"Vale anche per le tue esecuzioni pianificate, finché non la revochi","Always allowed":"Sempre consentito","Analyzing results (step {step})…":"Analisi dei risultati (passaggio {step})…","Analyzing results…":"Analisi dei risultati…","Analyzing the details":"Analisi dei dettagli",Approved:"Approvato","Archive all conversations":"Archivia tutte le conversazioni","Archive all conversations?":"Archiviare tutte le conversazioni?","Ask Assistant":"Chiedi all’assistente","Ask a question...":"Fai una domanda...",Assistant:"Assistente","Attach files":"Allega file","Attached files":"File allegati","Attachments wait for the current response":"Gli allegati attendono la risposta in corso",Back:"Indietro","Bad response":"Risposta non valida","Browse agents":"Sfoglia gli agenti",Cancel:"Annulla","Cancel question":"Annulla la domanda","Clear all conversations":"Cancella tutte le conversazioni",Close:"Chiudi","Collecting results from one task…":"Raccolta dei risultati di un’attività…","Collecting results from {count} tasks…":"Raccolta dei risultati di {count} attività…","Compacting conversation context…":"Compattazione del contesto della conversazione…","Composing answer…":"Composizione della risposta…",Confirm:"Conferma","Connecting integrations…":"Connessione delle integrazioni…","Connecting the dots":"Collegamento dei punti","Consulting an agent…":"Consulto con un agente…","Consulting the sources":"Consultazione delle fonti","Consulting {agent}…":"Consulto con {agent}…","Consulting {agent}: {count} questions…":"Consulto con {agent}: {count} domande…","Consulting {agent}: {tool} (+{count} more)…":"Consulto con {agent}: {tool} (+{count} altri)…","Consulting {agent}: {tool}…":"Consulto con {agent}: {tool}…","Consulting {agent}: writing the answer…":"Consulto con {agent}: stesura della risposta…","Consulting {count} agents…":"Consultazione di {count} agenti…","Context full — older turns are being dropped":"Contesto pieno — i turni meno recenti vengono eliminati","Context nearly full — older turns are being summarized":"Contesto quasi pieno — i turni meno recenti vengono riassunti","Context used":"Contesto utilizzato","Continue now":"Continua ora",Conversation:"Conversazione","Conversation history":"Cronologia delle conversazioni","Conversation title":"Titolo della conversazione","Conversation transcript":"Trascrizione della conversazione",Copied:"Copiato","Copied!":"Copiato!","Copy code":"Copia il codice","Copy message":"Copia il messaggio","Copy response":"Copia la risposta","Could not load your conversations.":"Impossibile caricare le tue conversazioni.","Could not reach the assistant service. Check the connection and try again.":"Impossibile raggiungere il servizio dell’assistente. Controlla la connessione e riprova.","Could not send your decision. Please try again.":"Impossibile inviare la tua decisione. Riprova.","Create agent":"Crea agente","Crunching the data":"Elaborazione dei dati","Decline this call":"Rifiuta questa chiamata",Declined:"Rifiutato","Delegating one task…":"Delega di un’attività…","Delegating {count} tasks…":"Delega di {count} attività…","Delete all conversations":"Elimina tutte le conversazioni","Delete all conversations?":"Eliminare tutte le conversazioni?","Delete conversation":"Elimina la conversazione","Delete workspace":"Elimina l’area di lavoro","Delete?":"Eliminare?","Dictate a message":"Detta un messaggio","Did not answer":"Nessuna risposta",Download:"Scarica","Download {format}":"Scarica in {format}","Drop a conversation here, or start one with {icon}.":"Trascina qui una conversazione o avviane una con {icon}.","Drop files to attach them":"Trascina qui i file per allegarli","End voice call":"Termina la chiamata vocale","Enter to send · Shift+Enter for new line":"Invio per inviare · Maiusc+Invio per andare a capo","Enter to send now · Esc to stop":"Invio per inviare subito · Esc per interrompere","Enter to send when the answer ends · Esc to stop":"Invio per inviare al termine della risposta · Esc per interrompere","Every conversation is in a workspace.":"Ogni conversazione si trova in un’area di lavoro.","Expand image":"Ingrandisci l’immagine","Failed to get a response. Resuming…":"Nessuna risposta ricevuta. Ripresa in corso…","Feedback already submitted":"Feedback già inviato","Files uploading...":"Caricamento dei file in corso...",Floating:"Fluttuante","Full screen":"Schermo intero","Good response":"Risposta valida","Help me create a new simulation scenario":"Aiutami a creare un nuovo scenario di simulazione","Hide conversations":"Nascondi le conversazioni","How can I help you, {name}?":"Come posso aiutarti, {name}?","How can {agent} help you, {name}?":"Come può aiutarti {agent}, {name}?","How do I configure detection rules?":"Come configuro le regole di rilevamento?","Image could not be loaded":"Impossibile caricare l’immagine","Image preview":"Anteprima dell’immagine","Incorporating your message…":"Integrazione del tuo messaggio…",Input:"Input","Insert prompt template":"Inserisci un modello di prompt","Interrupted by a server restart.":"Interrotto da un riavvio del server.","Listening...":"In ascolto...","Load earlier messages":"Carica i messaggi precedenti","Loading earlier messages…":"Caricamento dei messaggi precedenti…","Loading conversation history…":"Caricamento della cronologia della conversazione…","Loading image…":"Caricamento dell’immagine…","MCP & dynamic tools":"MCP e strumenti dinamici","Mention an agent":"Menziona un agente","Model reasoning":"Ragionamento del modello","Move to workspace":"Sposta in un’area di lavoro","Mute microphone":"Disattiva il microfono",Muted:"Microfono disattivato","New chat":"Nuova chat","New conversation":"Nuova conversazione","New conversation in this workspace":"Nuova conversazione in quest’area di lavoro","New conversation outside a workspace":"Nuova conversazione fuori da un’area di lavoro","New conversation — send a message to start it":"Nuova conversazione — invia un messaggio per avviarla","New workspace":"Nuova area di lavoro",No:"No","No agent matches":"Nessun agente corrispondente","None of your conversations matches":"Nessuna delle tue conversazioni corrisponde","No conversation matches":"Nessuna conversazione corrispondente","No conversations yet":"Ancora nessuna conversazione","No prompt matches":"Nessun prompt corrispondente","No response was generated. Please try again.":"Non è stata generata alcuna risposta. Riprova.","No response.":"Nessuna risposta.","Not in a workspace":"Fuori da un’area di lavoro","Not recommended for chat":"Sconsigliato per la chat","Not rendered yet":"Rendering non ancora avviato",Open:"Apri","Open conversation":"Apri la conversazione","Open in XTM One":"Apri in XTM One","Other workspaces":"Altre aree di lavoro",Output:"Output","Play Space Invaders":"Gioca a Space Invaders","Play Space Invaders in XTM One":"Gioca a Space Invaders in XTM One","Polishing the answer":"Rifinitura della risposta",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (modificabile)","Preparing tools…":"Preparazione degli strumenti…","Preparing…":"Preparazione…",Presentation:"Presentazione","Putting it together":"Assemblaggio degli elementi",Quota:"Quota","Quota reached":"Quota raggiunta","Read aloud":"Leggi ad alta voce","Reasoning details":"Dettagli del ragionamento","Reasoning details — interrupted by a server restart":"Dettagli del ragionamento — interrotto da un riavvio del server","Reasoning details — turn limit reached":"Dettagli del ragionamento — limite di turni raggiunto","Recalling memory…":"Recupero della memoria…","Reconnecting…":"Riconnessione…","Reference a conversation":"Fai riferimento a una conversazione","Remove from workspace":"Rimuovi dall’area di lavoro","Rename conversation":"Rinomina la conversazione","Rename workspace":"Rinomina l’area di lavoro","Rendering {progress}%":"Rendering in corso: {progress}%",Report:"Report","Response ready":"Risposta pronta","Reticulating splines":"Reticolazione delle spline",Retry:"Riprova",Save:"Salva","Scroll to bottom":"Vai in fondo","Saving response…":"Salvataggio della risposta…","Search agents...":"Cerca agenti...","Search conversations...":"Cerca conversazioni...","Search prompts...":"Cerca prompt...",Send:"Invia","Send now":"Invia ora","Send when the answer ends":"Invia al termine della risposta","Sending…":"Invio in corso…","Sends when the answer ends:":"Invio al termine della risposta:","Shared with you":"Condivise con te","Show conversations":"Mostra le conversazioni","Show less":"Mostra meno",Sidebar:"Barra laterale",Skip:"Salta","Skip response":"Salta la risposta","Sorry, an error occurred. Please try again.":"Si è verificato un errore. Riprova.","Speak or tap to interrupt":"Parla o tocca per interrompere","Speaking…":"Sta parlando…","Started in {channel}":"Avviata in {channel}","Stop dictation":"Interrompi la dettatura","Stop generating":"Interrompi la generazione","Stop reading":"Interrompi la lettura",Stopped:"Interrotto","Stopping…":"Interruzione in corso…",Suggestions:"Suggerimenti","Summarize my recent findings":"Riassumi le mie scoperte più recenti","Summarized conversation":"Conversazione riassunta","Summarizing earlier conversation…":"Riepilogo della parte precedente della conversazione…",Superseded:"Sostituito","Switch to":"Passa a","Switch to another agent":"Passa a un altro agente","Switch view":"Cambia vista","System prompt":"Prompt di sistema","Tap to cancel":"Tocca per annullare","Tell us what went wrong (optional)":"Spiegaci cosa non ha funzionato (facoltativo)","The agent is answering…":"L’agente sta rispondendo…","The agent needs your approval to run a tool:":"L’agente ha bisogno della tua approvazione per eseguire uno strumento:","The agent needs your approval to run these tools:":"L’agente ha bisogno della tua approvazione per eseguire questi strumenti:","The conversation could not be deleted":"Impossibile eliminare la conversazione","The conversation could not be moved":"Impossibile spostare la conversazione","The conversation could not be renamed":"Impossibile rinominare la conversazione","The conversations could not be archived":"Impossibile archiviare le conversazioni","The conversations could not be deleted":"Impossibile eliminare le conversazioni","The render did not finish":"Il rendering non è stato completato","The server restarted while this turn was running, so it stopped before it could finish.":"Il server si è riavviato durante questo turno, che si è quindi interrotto prima di poter terminare.","The workspace could not be created":"Impossibile creare l’area di lavoro","The workspace could not be deleted":"Impossibile eliminare l’area di lavoro","The workspace could not be renamed":"Impossibile rinominare l’area di lavoro","Thinking it through":"Riflessione in corso","Thinking...":"Sto pensando...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Questo agente è pensato per gli incarichi, non per la chat diretta. Potrebbe non rispondere bene in una conversazione.","This conversation could not be loaded.":"Impossibile caricare questa conversazione.","This decision could not be sent. Reload the chat and try again.":"Impossibile inviare questa decisione. Ricarica la chat e riprova.","This message waits for the current response":"Questo messaggio attende la risposta in corso","This message will be read with your next one.":"Questo messaggio verrà letto insieme al prossimo.","This item could not be loaded.":"Impossibile caricare questo elemento.","The response could not be stopped. Try again.":"Impossibile interrompere la risposta. Riprova.","This turn is no longer waiting for a decision.":"Questo turno non è più in attesa di una decisione.","Tool definitions":"Definizioni degli strumenti","Tool results":"Risultati degli strumenti","Transfer chain":"Catena di trasferimento","Transferred from {agent}":"Trasferito da {agent}","Transferring to another agent…":"Trasferimento verso un altro agente…","Transferring to {agent}…":"Trasferimento verso {agent}…","Turn limit reached.":"Limite di turni raggiunto.","Unable to connect. Please check the configuration.":"Impossibile connettersi. Controlla la configurazione.","Unmute microphone":"Riattiva il microfono","Untitled conversation":"Conversazione senza titolo",Usage:"Utilizzo","Upload failed":"Caricamento non riuscito","Usage · {period}":"Utilizzo · {period}","Uses AI. Verify results.":"Usa l’IA. Verifica i risultati.","Using tools…":"Utilizzo degli strumenti…",Video:"Video","Voice call":"Chiamata vocale","Waiting before continuing…":"In attesa prima di continuare…","Waiting for one background task…":"In attesa di un’attività in background…","Waiting for your approval…":"In attesa della tua approvazione…","Waiting for {count} background tasks…":"In attesa di {count} attività in background…","Waiting to render":"In attesa del rendering","What are the latest attack patterns?":"Quali sono i pattern di attacco più recenti?","What could be improved?":"Cosa si potrebbe migliorare?","Why not? The agent sees this and can adapt (optional)":"Perché no? L’agente lo vede e può adattarsi (facoltativo)","Working files ({count})":"File di lavoro ({count})","Workspace name":"Nome dell’area di lavoro",Workspaces:"Aree di lavoro","Wrapping things up":"Conclusione in corso",Yes:"Sì","Yes, always":"Sì, sempre","Your answer is ready":"La tua risposta è pronta",default:"predefinito","e.g. wrong environment — use staging instead":"ad es. ambiente errato — usa invece l’ambiente di staging","just now":"proprio ora","this month":"questo mese","this year":"quest’anno",today:"oggi","unknown tool":"strumento sconosciuto","{agent} has finished":"{agent} ha terminato","{agent} is answering…":"{agent} sta rispondendo…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"{counts} token","{count} iterations":"{count} iterazioni","{count} scenes":"{count} scene","{count} sections":"{count} sezioni","{count} slides":"{count} diapositive","{count} tool calls":"{count} chiamate a strumenti","{count} transfers":"{count} trasferimenti","{count}d ago":"{count} g fa","{count}h ago":"{count} h fa","{count}m ago":"{count} min fa","{decided}/{total} decided":"{decided}/{total} decisi","{name} was not attached: a file may be at most {size}.":"{name} non è stato allegato: un file può essere al massimo di {size}.","{name} was not attached: a message holds at most {count} files.":"{name} non è stato allegato: un messaggio può contenere al massimo {count} file.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} non è stato allegato: i file di un messaggio possono arrivare al massimo a {size} in totale.","{name} was not attached: this type of file is not accepted.":"{name} non è stato allegato: questo tipo di file non è accettato.","{percent}% full":"Pieno al {percent}%","{quota} (shared across all users)":"{quota} (condivisa tra tutti gli utenti)","{summary} — click for details":"{summary} — fai clic per i dettagli","{tool} (+{count} more)…":"{tool} (+{count} altri)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Il budget di iterazioni dell’agente è esaurito: l’esecuzione si è interrotta prima di completare tutti i passaggi previsti. La risposta finale riassume al meglio il lavoro svolto finora.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"«Sì, sempre» salva una tua preferenza. Quello strumento verrà quindi eseguito senza chiedere, anche nelle esecuzioni pianificate che nessuno sta seguendo, finché non la revochi."},ja:{"(no output)":"(出力なし)","1 tool call":"ツール呼び出し 1 件","1 transfer":"転送 1 件","A file failed to upload: remove it to send the message":"ファイルのアップロードに失敗しました。メッセージを送信するには削除してください","A message references at most {count} conversations":"1 つのメッセージで参照できる会話は最大 {count} 件です","Acting on the page…":"ページを操作中…","Agent · {channel}":"エージェント · {channel}","Agent switching is not available here":"ここではエージェントの切り替えは利用できません","Almost there":"もうすぐ完了します","Also applies to your scheduled runs, until you revoke it":"予定された実行についても、取り消すまでは同様に適用されます","Always allowed":"常に許可","Analyzing results (step {step})…":"結果を分析中 (ステップ {step})…","Analyzing results…":"結果を分析中…","Analyzing the details":"詳細を分析しています",Approved:"承認済み","Archive all conversations":"すべての会話をアーカイブ","Archive all conversations?":"すべての会話をアーカイブしますか?","Ask Assistant":"アシスタントに質問","Ask a question...":"質問する...",Assistant:"アシスタント","Attach files":"ファイルを添付","Attached files":"添付ファイル","Attachments wait for the current response":"添付ファイルは、現在の応答を待機します",Back:"戻る","Bad response":"不適切な回答","Browse agents":"エージェントを閲覧する",Cancel:"キャンセル","Cancel question":"質問をキャンセル","Clear all conversations":"すべての会話を消去",Close:"閉じる","Collecting results from one task…":"1 件のタスクの結果を収集中…","Collecting results from {count} tasks…":"{count} 件のタスクの結果を収集中…","Compacting conversation context…":"会話のコンテキストを圧縮中…","Composing answer…":"回答を作成中…",Confirm:"確認する","Connecting integrations…":"連携を接続中…","Connecting the dots":"情報を関連付けています","Consulting an agent…":"エージェントに問い合わせ中…","Consulting the sources":"情報源を確認しています","Consulting {agent}…":"{agent} に問い合わせ中…","Consulting {agent}: {count} questions…":"{agent} に問い合わせ中: {count} 件の質問…","Consulting {agent}: {tool} (+{count} more)…":"{agent} に問い合わせ中: {tool}(他 {count} 件)…","Consulting {agent}: {tool}…":"{agent} に問い合わせ中: {tool}…","Consulting {agent}: writing the answer…":"{agent} に問い合わせ中: 回答を作成しています…","Consulting {count} agents…":"{count} 件のエージェントに問い合わせ中…","Context full — older turns are being dropped":"コンテキストが満杯 — 古いターンが削除されています","Context nearly full — older turns are being summarized":"コンテキストがほぼ満杯です — 古いターンが要約されています","Context used":"使用されたコンテキスト","Continue now":"今すぐ続行",Conversation:"会話","Conversation history":"会話履歴","Conversation title":"会話のタイトル","Conversation transcript":"会話の履歴",Copied:"コピーしました","Copied!":"コピー完了!","Copy code":"コードをコピー","Copy message":"メッセージをコピー","Copy response":"応答をコピー","Could not load your conversations.":"会話を読み込めませんでした。","Could not reach the assistant service. Check the connection and try again.":"アシスタントサービスに接続できませんでした。接続状態を確認して、もう一度お試しください。","Could not send your decision. Please try again.":"決定内容を送信できませんでした。もう一度お試しください。","Create agent":"エージェントを作成する","Crunching the data":"データを処理しています","Decline this call":"この呼び出しを拒否",Declined:"拒否済み","Delegating one task…":"1 件のタスクを委任中…","Delegating {count} tasks…":"{count} 件のタスクを委任中…","Delete all conversations":"すべての会話を削除","Delete all conversations?":"すべての会話を削除しますか?","Delete conversation":"会話を削除","Delete workspace":"ワークスペースを削除","Delete?":"削除しますか?","Dictate a message":"メッセージを音声入力する","Did not answer":"回答なし",Download:"ダウンロード","Download {format}":"{format} をダウンロード","Drop a conversation here, or start one with {icon}.":"ここに会話をドロップするか、{icon} で新しく開始してください。","Drop files to attach them":"ファイルをドロップして添付","End voice call":"音声通話を終了","Enter to send · Shift+Enter for new line":"Enterキーで送信 · Shift+Enterキーで改行","Enter to send now · Esc to stop":"Enterキーで今すぐ送信 · Escキーで停止","Enter to send when the answer ends · Esc to stop":"Enterキーで回答の終了後に送信 · Escキーで停止","Every conversation is in a workspace.":"すべての会話がワークスペースに含まれています。","Expand image":"画像を拡大","Failed to get a response. Resuming…":"応答を取得できませんでした。再開しています…","Feedback already submitted":"フィードバックは送信済みです","Files uploading...":"ファイルのアップロード中...",Floating:"フローティング","Full screen":"全画面表示","Good response":"適切な回答","Help me create a new simulation scenario":"新しいシミュレーションシナリオの作成を手伝ってください","Hide conversations":"会話を非表示にする","How can I help you, {name}?":"{name} さん、何かお手伝いできることはありますか?","How can {agent} help you, {name}?":"{name} さん、{agent} がお手伝いできることはありますか?","How do I configure detection rules?":"検出ルールはどのように設定すればよいですか?","Image could not be loaded":"画像を読み込めませんでした","Image preview":"画像プレビュー","Incorporating your message…":"メッセージを組み込んでいます…",Input:"入力","Insert prompt template":"プロンプトテンプレートを挿入","Interrupted by a server restart.":"サーバーの再起動により中断されました。","Listening...":"聞き取り中...","Load earlier messages":"以前のメッセージを読み込む","Loading earlier messages…":"以前のメッセージを読み込み中…","Loading conversation history…":"会話履歴を読み込み中…","Loading image…":"画像を読み込み中…","MCP & dynamic tools":"MCPと動的ツール","Mention an agent":"エージェントをメンション","Model reasoning":"モデルの推論","Move to workspace":"ワークスペースに移動","Mute microphone":"マイクをミュート",Muted:"ミュート中","New chat":"新しいチャット","New conversation":"新しい会話","New conversation in this workspace":"このワークスペースで新しい会話","New conversation outside a workspace":"ワークスペース外で新しい会話","New conversation — send a message to start it":"新しい会話 — メッセージを送信すると開始されます","New workspace":"新しいワークスペース",No:"いいえ","No agent matches":"該当するエージェントはありません","None of your conversations matches":"一致するご自身の会話はありません","No conversation matches":"一致する会話はありません","No conversations yet":"まだ会話はありません","No prompt matches":"一致するプロンプトはありません","No response was generated. Please try again.":"応答が生成されませんでした。もう一度お試しください。","No response.":"応答なし。","Not in a workspace":"ワークスペースなし","Not recommended for chat":"チャットには非推奨","Not rendered yet":"まだレンダリングされていません",Open:"開く","Open conversation":"会話を開く","Open in XTM One":"XTM One で開く","Other workspaces":"その他のワークスペース",Output:"出力","Play Space Invaders":"Space Invaders をプレイ","Play Space Invaders in XTM One":"XTM One で Space Invaders をプレイ","Polishing the answer":"回答を仕上げています",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint(編集可能)","Preparing tools…":"ツールを準備中…","Preparing…":"準備中…",Presentation:"プレゼンテーション","Putting it together":"内容をまとめています",Quota:"クォータ","Quota reached":"クォータに達しました","Read aloud":"読み上げ","Reasoning details":"推論の詳細","Reasoning details — interrupted by a server restart":"推論の詳細 — サーバーの再起動により中断されました","Reasoning details — turn limit reached":"推論の詳細 — ターン制限に達しました","Recalling memory…":"メモリを呼び出し中…","Reconnecting…":"再接続中…","Reference a conversation":"会話を参照","Remove from workspace":"ワークスペースから外す","Rename conversation":"会話の名前を変更","Rename workspace":"ワークスペースの名前を変更","Rendering {progress}%":"レンダリング中 {progress}%",Report:"レポート","Response ready":"応答準備完了","Reticulating splines":"スプラインを網状化しています",Retry:"再試行",Save:"保存","Scroll to bottom":"一番下へスクロール","Saving response…":"応答を保存中…","Search agents...":"エージェントを検索...","Search conversations...":"会話を検索...","Search prompts...":"プロンプトを検索...",Send:"送信","Send now":"今すぐ送信","Send when the answer ends":"回答の終了後に送信","Sending…":"送信中…","Sends when the answer ends:":"回答の終了後に送信:","Shared with you":"他のユーザーから共有","Show conversations":"会話を表示","Show less":"表示を減らす",Sidebar:"サイドバー",Skip:"スキップ","Skip response":"応答をスキップ","Sorry, an error occurred. Please try again.":"申し訳ありません。エラーが発生しました。もう一度お試しください。","Speak or tap to interrupt":"話すかタップして中断","Speaking…":"読み上げ中…","Started in {channel}":"{channel} で開始","Stop dictation":"ディクテーションを停止","Stop generating":"生成を停止","Stop reading":"読み上げを停止",Stopped:"停止","Stopping…":"停止中…",Suggestions:"提案","Summarize my recent findings":"私の最近の発見を要約してください","Summarized conversation":"会話の要約","Summarizing earlier conversation…":"以前の会話を要約中…",Superseded:"置き換え済み","Switch to":"切り替え先","Switch to another agent":"別のエージェントに切り替える","Switch view":"ビューを切り替える","System prompt":"システムプロンプト","Tap to cancel":"タップしてキャンセル","Tell us what went wrong (optional)":"問題があった点をお聞かせください(任意)","The agent is answering…":"エージェントが回答中…","The agent needs your approval to run a tool:":"エージェントがツールを実行するには、あなたの承認が必要です:","The agent needs your approval to run these tools:":"エージェントがこれらのツールを実行するには、あなたの承認が必要です:","The conversation could not be deleted":"会話を削除できませんでした","The conversation could not be moved":"会話を移動できませんでした","The conversation could not be renamed":"会話の名前を変更できませんでした","The conversations could not be archived":"会話をアーカイブできませんでした","The conversations could not be deleted":"会話を削除できませんでした","The render did not finish":"レンダリングが完了しませんでした","The server restarted while this turn was running, so it stopped before it could finish.":"このターンの実行中にサーバーが再起動したため、完了する前に停止しました。","The workspace could not be created":"ワークスペースを作成できませんでした","The workspace could not be deleted":"ワークスペースを削除できませんでした","The workspace could not be renamed":"ワークスペースの名前を変更できませんでした","Thinking it through":"じっくり考えています","Thinking...":"考え中...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"このエージェントはチャットではなくタスク向けに設計されています。会話にはうまく応答できない場合があります。","This conversation could not be loaded.":"この会話を読み込めませんでした。","This decision could not be sent. Reload the chat and try again.":"この決定を送信できませんでした。チャットを再読み込みして、もう一度お試しください。","This message waits for the current response":"このメッセージは、現在の応答を待機します","This message will be read with your next one.":"このメッセージは次のメッセージと一緒に読まれます。","This item could not be loaded.":"この項目を読み込めませんでした。","The response could not be stopped. Try again.":"応答を停止できませんでした。もう一度お試しください。","This turn is no longer waiting for a decision.":"このターンでは、決定を待つ必要がなくなりました。","Tool definitions":"ツールの定義","Tool results":"ツールの結果","Transfer chain":"転送チェーン","Transferred from {agent}":"{agent} から転送されました","Transferring to another agent…":"別のエージェントに転送中…","Transferring to {agent}…":"{agent} に転送中…","Turn limit reached.":"ターン制限に達しました。","Unable to connect. Please check the configuration.":"接続できません。設定を確認してください。","Unmute microphone":"マイクのミュートを解除","Untitled conversation":"タイトルのない会話",Usage:"使用状況","Upload failed":"アップロードに失敗しました","Usage · {period}":"使用状況 · {period}","Uses AI. Verify results.":"AIを使用しています。結果を確認してください。","Using tools…":"ツールを使用中…",Video:"動画","Voice call":"音声通話","Waiting before continuing…":"続行する前に待機中…","Waiting for one background task…":"バックグラウンドタスク 1 件を待機中…","Waiting for your approval…":"承認をお待ちしています…","Waiting for {count} background tasks…":"バックグラウンドタスク {count} 件を待機中…","Waiting to render":"レンダリング待ち","What are the latest attack patterns?":"最新の攻撃パターンにはどのようなものがありますか?","What could be improved?":"改善できる点はありますか?","Why not? The agent sees this and can adapt (optional)":"なぜですか? エージェントはこれを確認し、対応を調整できます(任意)","Working files ({count})":"作業ファイル ({count})","Workspace name":"ワークスペース名",Workspaces:"ワークスペース","Wrapping things up":"仕上げをしています",Yes:"はい","Yes, always":"はい、常に","Your answer is ready":"回答の準備が整いました",default:"デフォルト","e.g. wrong environment — use staging instead":"例:環境が間違っている — 代わりにステージング環境を使用してください","just now":"たった今","this month":"今月","this year":"今年",today:"今日","unknown tool":"不明なツール","{agent} has finished":"{agent} が完了しました","{agent} is answering…":"{agent} が回答中…","{agent}: {status}":"{agent}:{status}","{counts} tokens":"{counts} トークン","{count} iterations":"{count} 回の反復","{count} scenes":"{count} シーン","{count} sections":"{count} セクション","{count} slides":"{count} スライド","{count} tool calls":"ツール呼び出し {count} 件","{count} transfers":"転送 {count} 件","{count}d ago":"{count} 日前","{count}h ago":"{count} 時間前","{count}m ago":"{count} 分前","{decided}/{total} decided":"{decided}/{total} 件が決定済み","{name} was not attached: a file may be at most {size}.":"{name} は添付されませんでした: 1 つのファイルの上限は {size} です。","{name} was not attached: a message holds at most {count} files.":"{name} は添付されませんでした: 1 つのメッセージに添付できるファイルは最大 {count} 件です。","{name} was not attached: the files of a message may add up to at most {size}.":"{name} は添付されませんでした: 1 つのメッセージのファイルの合計は最大 {size} です。","{name} was not attached: this type of file is not accepted.":"{name} は添付されませんでした: この種類のファイルは使用できません。","{percent}% full":"{percent} % 使用中","{quota} (shared across all users)":"{quota}(全ユーザーで共有)","{summary} — click for details":"{summary} — クリックで詳細を表示","{tool} (+{count} more)…":"{tool}(他 {count} 件)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"エージェントの反復回数の上限に達したため、予定されたすべてのステップを完了する前に実行が停止しました。最終的な回答は、これまでに行った作業をできる限りまとめたものです。","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"「はい、常に」を選ぶと、あなたの設定として保存されます。以後、そのツールは確認なしで実行されます(誰も見ていない定期実行を含む)。取り消すまでこの設定は有効です。"},ko:{"(no output)":"(출력 없음)","1 tool call":"도구 호출 1회","1 transfer":"전환 1회","A file failed to upload: remove it to send the message":"파일을 업로드하지 못했습니다. 메시지를 보내려면 해당 파일을 제거하세요","A message references at most {count} conversations":"메시지 하나에서 참조할 수 있는 대화는 최대 {count}개입니다","Acting on the page…":"페이지에서 작업 중…","Agent · {channel}":"에이전트 · {channel}","Agent switching is not available here":"여기서는 에이전트를 전환할 수 없습니다","Almost there":"거의 다 되었습니다","Also applies to your scheduled runs, until you revoke it":"취소할 때까지 예약된 실행에도 적용됩니다","Always allowed":"항상 허용됨","Analyzing results (step {step})…":"결과 분석 중 (단계 {step})…","Analyzing results…":"결과 분석 중…","Analyzing the details":"세부 정보를 분석하는 중",Approved:"승인됨","Archive all conversations":"모든 대화 보관","Archive all conversations?":"모든 대화를 보관하시겠습니까?","Ask Assistant":"어시스턴트에게 질문","Ask a question...":"질문하기...",Assistant:"어시스턴트","Attach files":"파일 첨부","Attached files":"첨부 파일","Attachments wait for the current response":"첨부 파일은 현재 응답이 끝날 때까지 대기합니다",Back:"뒤로","Bad response":"좋지 않은 응답","Browse agents":"에이전트 둘러보기",Cancel:"취소","Cancel question":"질문 취소","Clear all conversations":"모든 대화 지우기",Close:"닫기","Collecting results from one task…":"작업 1개의 결과 수집 중…","Collecting results from {count} tasks…":"작업 {count}개의 결과 수집 중…","Compacting conversation context…":"대화 컨텍스트 압축 중…","Composing answer…":"답변 작성 중…",Confirm:"확인","Connecting integrations…":"통합 연결 중…","Connecting the dots":"단서를 연결하는 중","Consulting an agent…":"에이전트에게 문의 중…","Consulting the sources":"출처를 확인하는 중","Consulting {agent}…":"{agent}에게 문의 중…","Consulting {agent}: {count} questions…":"{agent}에게 문의 중: 질문 {count}개…","Consulting {agent}: {tool} (+{count} more)…":"{agent}에게 문의 중: {tool} (외 {count}개)…","Consulting {agent}: {tool}…":"{agent}에게 문의 중: {tool}…","Consulting {agent}: writing the answer…":"{agent}에게 문의 중: 답변 작성 중…","Consulting {count} agents…":"에이전트 {count}개에 문의 중…","Context full — older turns are being dropped":"컨텍스트 가득 참 — 이전 턴을 삭제하는 중","Context nearly full — older turns are being summarized":"컨텍스트 거의 가득 참 — 이전 턴을 요약하는 중","Context used":"사용된 컨텍스트","Continue now":"지금 계속",Conversation:"대화","Conversation history":"대화 기록","Conversation title":"대화 제목","Conversation transcript":"대화 내용",Copied:"복사됨","Copied!":"복사되었습니다!","Copy code":"코드 복사","Copy message":"메시지 복사","Copy response":"응답 복사","Could not load your conversations.":"대화를 불러올 수 없습니다.","Could not reach the assistant service. Check the connection and try again.":"어시스턴트 서비스에 연결할 수 없습니다. 연결을 확인하고 다시 시도하세요.","Could not send your decision. Please try again.":"결정을 보내지 못했습니다. 다시 시도하세요.","Create agent":"에이전트 만들기","Crunching the data":"데이터를 처리하는 중","Decline this call":"이 호출 거부",Declined:"거부됨","Delegating one task…":"작업 1개 위임 중…","Delegating {count} tasks…":"작업 {count}개 위임 중…","Delete all conversations":"모든 대화 삭제","Delete all conversations?":"모든 대화를 삭제하시겠습니까?","Delete conversation":"대화 삭제","Delete workspace":"작업 공간 삭제","Delete?":"삭제하시겠습니까?","Dictate a message":"메시지 받아쓰기","Did not answer":"응답하지 않음",Download:"다운로드","Download {format}":"{format} 다운로드","Drop a conversation here, or start one with {icon}.":"여기에 대화를 끌어다 놓거나 {icon}(으)로 새 대화를 시작하세요.","Drop files to attach them":"파일을 끌어다 놓아 첨부하세요","End voice call":"음성 통화 종료","Enter to send · Shift+Enter for new line":"Enter 키로 보내기 · Shift+Enter 키로 줄 바꿈","Enter to send now · Esc to stop":"Enter 키로 지금 보내기 · Esc 키로 중지","Enter to send when the answer ends · Esc to stop":"Enter 키로 답변이 끝나면 보내기 · Esc 키로 중지","Every conversation is in a workspace.":"모든 대화가 작업 공간에 있습니다.","Expand image":"이미지 확대","Failed to get a response. Resuming…":"응답을 받지 못했습니다. 다시 시작하는 중…","Feedback already submitted":"피드백을 이미 제출했습니다","Files uploading...":"파일 업로드 중...",Floating:"플로팅","Full screen":"전체 화면","Good response":"좋은 응답","Help me create a new simulation scenario":"새 시뮬레이션 시나리오 만들기를 도와줘","Hide conversations":"대화 숨기기","How can I help you, {name}?":"{name}님, 무엇을 도와드릴까요?","How can {agent} help you, {name}?":"{name}님, {agent}이(가) 무엇을 도와드릴까요?","How do I configure detection rules?":"탐지 규칙은 어떻게 구성하나요?","Image could not be loaded":"이미지를 불러올 수 없습니다","Image preview":"이미지 미리 보기","Incorporating your message…":"메시지를 반영하는 중…",Input:"입력","Insert prompt template":"프롬프트 템플릿 삽입","Interrupted by a server restart.":"서버 재시작으로 중단되었습니다.","Listening...":"듣는 중...","Load earlier messages":"이전 메시지 불러오기","Loading earlier messages…":"이전 메시지 불러오는 중…","Loading conversation history…":"대화 기록 불러오는 중…","Loading image…":"이미지 불러오는 중…","MCP & dynamic tools":"MCP 및 동적 도구","Mention an agent":"에이전트 언급","Model reasoning":"모델 추론","Move to workspace":"작업 공간으로 이동","Mute microphone":"마이크 음소거",Muted:"음소거됨","New chat":"새 채팅","New conversation":"새 대화","New conversation in this workspace":"이 작업 공간에서 새 대화","New conversation outside a workspace":"작업 공간 밖에서 새 대화","New conversation — send a message to start it":"새 대화 — 메시지를 보내 대화를 시작하세요","New workspace":"새 작업 공간",No:"아니요","No agent matches":"일치하는 에이전트가 없습니다","None of your conversations matches":"일치하는 내 대화가 없습니다","No conversation matches":"일치하는 대화가 없습니다","No conversations yet":"아직 대화가 없습니다","No prompt matches":"일치하는 프롬프트가 없습니다","No response was generated. Please try again.":"응답이 생성되지 않았습니다. 다시 시도하세요.","No response.":"응답 없음.","Not in a workspace":"작업 공간에 없음","Not recommended for chat":"채팅에는 권장되지 않음","Not rendered yet":"아직 렌더링되지 않음",Open:"열기","Open conversation":"대화 열기","Open in XTM One":"XTM One에서 열기","Other workspaces":"다른 작업 공간",Output:"출력","Play Space Invaders":"Space Invaders 플레이","Play Space Invaders in XTM One":"XTM One에서 Space Invaders 플레이","Polishing the answer":"답변을 다듬는 중",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (편집 가능)","Preparing tools…":"도구 준비 중…","Preparing…":"준비 중…",Presentation:"프레젠테이션","Putting it together":"내용을 정리하는 중",Quota:"할당량","Quota reached":"할당량 도달","Read aloud":"소리 내어 읽기","Reasoning details":"추론 세부 정보","Reasoning details — interrupted by a server restart":"추론 세부 정보 — 서버 재시작으로 중단됨","Reasoning details — turn limit reached":"추론 세부 정보 — 턴 한도 도달","Recalling memory…":"메모리 불러오는 중…","Reconnecting…":"다시 연결하는 중…","Reference a conversation":"대화 참조","Remove from workspace":"작업 공간에서 제거","Rename conversation":"대화 이름 바꾸기","Rename workspace":"작업 공간 이름 바꾸기","Rendering {progress}%":"렌더링 중 {progress}%",Report:"보고서","Response ready":"응답 준비됨","Reticulating splines":"스플라인을 망상화하는 중",Retry:"다시 시도",Save:"저장","Scroll to bottom":"맨 아래로 스크롤","Saving response…":"응답 저장 중…","Search agents...":"에이전트 검색...","Search conversations...":"대화 검색...","Search prompts...":"프롬프트 검색...",Send:"보내기","Send now":"지금 보내기","Send when the answer ends":"답변이 끝나면 보내기","Sending…":"보내는 중…","Sends when the answer ends:":"답변이 끝나면 보냄:","Shared with you":"나와 공유됨","Show conversations":"대화 표시","Show less":"간단히 보기",Sidebar:"사이드바",Skip:"건너뛰기","Skip response":"응답 건너뛰기","Sorry, an error occurred. Please try again.":"죄송합니다. 오류가 발생했습니다. 다시 시도하세요.","Speak or tap to interrupt":"말하거나 탭하여 중단하세요","Speaking…":"말하는 중…","Started in {channel}":"{channel}에서 시작됨","Stop dictation":"받아쓰기 중지","Stop generating":"생성 중지","Stop reading":"읽기 중지",Stopped:"중지됨","Stopping…":"중지하는 중…",Suggestions:"추천","Summarize my recent findings":"최근 발견 사항을 요약해 줘","Summarized conversation":"요약된 대화","Summarizing earlier conversation…":"이전 대화 요약 중…",Superseded:"대체됨","Switch to":"전환 대상","Switch to another agent":"다른 에이전트로 전환","Switch view":"보기 전환","System prompt":"시스템 프롬프트","Tap to cancel":"탭하여 취소","Tell us what went wrong (optional)":"무엇이 잘못되었는지 알려 주세요 (선택 사항)","The agent is answering…":"에이전트 답변 중…","The agent needs your approval to run a tool:":"에이전트가 도구를 실행하려면 승인이 필요합니다:","The agent needs your approval to run these tools:":"에이전트가 다음 도구를 실행하려면 승인이 필요합니다:","The conversation could not be deleted":"대화를 삭제할 수 없습니다","The conversation could not be moved":"대화를 이동할 수 없습니다","The conversation could not be renamed":"대화 이름을 바꿀 수 없습니다","The conversations could not be archived":"대화를 보관할 수 없습니다","The conversations could not be deleted":"대화를 삭제할 수 없습니다","The render did not finish":"렌더링이 완료되지 않았습니다","The server restarted while this turn was running, so it stopped before it could finish.":"이 턴이 실행되는 동안 서버가 다시 시작되어 완료되기 전에 중지되었습니다.","The workspace could not be created":"작업 공간을 만들 수 없습니다","The workspace could not be deleted":"작업 공간을 삭제할 수 없습니다","The workspace could not be renamed":"작업 공간 이름을 바꿀 수 없습니다","Thinking it through":"깊이 생각하는 중","Thinking...":"생각하는 중...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"이 에이전트는 직접 채팅이 아닌 작업용으로 설계되었습니다. 대화에는 잘 응답하지 못할 수 있습니다.","This conversation could not be loaded.":"이 대화를 불러올 수 없습니다.","This decision could not be sent. Reload the chat and try again.":"이 결정을 보낼 수 없습니다. 채팅을 새로 고친 후 다시 시도하세요.","This message waits for the current response":"이 메시지는 현재 응답이 끝날 때까지 대기합니다","This message will be read with your next one.":"이 메시지는 다음 메시지와 함께 읽힙니다.","This item could not be loaded.":"이 항목을 불러올 수 없습니다.","The response could not be stopped. Try again.":"응답을 중지할 수 없습니다. 다시 시도하세요.","This turn is no longer waiting for a decision.":"이 턴은 더 이상 결정을 기다리지 않습니다.","Tool definitions":"도구 정의","Tool results":"도구 결과","Transfer chain":"전환 체인","Transferred from {agent}":"{agent}에서 전환됨","Transferring to another agent…":"다른 에이전트로 전환 중…","Transferring to {agent}…":"{agent}(으)로 전환 중…","Turn limit reached.":"턴 한도에 도달했습니다.","Unable to connect. Please check the configuration.":"연결할 수 없습니다. 구성을 확인하세요.","Unmute microphone":"마이크 음소거 해제","Untitled conversation":"제목 없는 대화",Usage:"사용량","Upload failed":"업로드 실패","Usage · {period}":"사용량 · {period}","Uses AI. Verify results.":"AI를 사용합니다. 결과를 확인하세요.","Using tools…":"도구 사용 중…",Video:"동영상","Voice call":"음성 통화","Waiting before continuing…":"계속하기 전에 대기 중…","Waiting for one background task…":"백그라운드 작업 1개를 기다리는 중…","Waiting for your approval…":"승인을 기다리는 중…","Waiting for {count} background tasks…":"백그라운드 작업 {count}개를 기다리는 중…","Waiting to render":"렌더링 대기 중","What are the latest attack patterns?":"최신 공격 패턴은 무엇인가요?","What could be improved?":"어떤 점을 개선할 수 있을까요?","Why not? The agent sees this and can adapt (optional)":"거부하는 이유는 무엇인가요? 에이전트가 이를 보고 대응할 수 있습니다 (선택 사항)","Working files ({count})":"작업 파일 ({count})","Workspace name":"작업 공간 이름",Workspaces:"작업 공간","Wrapping things up":"마무리하는 중",Yes:"예","Yes, always":"예, 항상","Your answer is ready":"답변이 준비되었습니다",default:"기본값","e.g. wrong environment — use staging instead":"예: 잘못된 환경 — 대신 스테이징 환경을 사용하세요","just now":"방금","this month":"이번 달","this year":"올해",today:"오늘","unknown tool":"알 수 없는 도구","{agent} has finished":"{agent} 완료","{agent} is answering…":"{agent} 답변 중…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"{counts} 토큰","{count} iterations":"반복 {count}회","{count} scenes":"장면 {count}개","{count} sections":"섹션 {count}개","{count} slides":"슬라이드 {count}개","{count} tool calls":"도구 호출 {count}회","{count} transfers":"전환 {count}회","{count}d ago":"{count}일 전","{count}h ago":"{count}시간 전","{count}m ago":"{count}분 전","{decided}/{total} decided":"{decided}/{total} 결정됨","{name} was not attached: a file may be at most {size}.":"{name}을(를) 첨부하지 않았습니다. 파일 크기는 최대 {size}입니다.","{name} was not attached: a message holds at most {count} files.":"{name}을(를) 첨부하지 않았습니다. 메시지에는 파일을 최대 {count}개까지 첨부할 수 있습니다.","{name} was not attached: the files of a message may add up to at most {size}.":"{name}을(를) 첨부하지 않았습니다. 메시지에 첨부하는 파일의 총 크기는 최대 {size}입니다.","{name} was not attached: this type of file is not accepted.":"{name}을(를) 첨부하지 않았습니다. 허용되지 않는 파일 형식입니다.","{percent}% full":"{percent}% 사용","{quota} (shared across all users)":"{quota} (모든 사용자가 공유)","{summary} — click for details":"{summary} — 클릭하여 자세히 보기","{tool} (+{count} more)…":"{tool} (외 {count}개)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"에이전트의 반복 한도를 모두 사용했습니다. 계획된 모든 단계를 완료하기 전에 실행이 중지되었습니다. 최종 응답은 지금까지 수행한 작업을 최대한 요약한 것입니다.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"“예, 항상”을 선택하면 내 기본 설정으로 저장됩니다. 이후 해당 도구는 취소할 때까지 확인 없이 실행되며, 아무도 지켜보지 않는 예약 실행에서도 마찬가지입니다."},ru:{"(no output)":"(нет вывода)","1 tool call":"1 вызов инструмента","1 transfer":"1 передача","A file failed to upload: remove it to send the message":"Не удалось загрузить файл: удалите его, чтобы отправить сообщение","A message references at most {count} conversations":"Сообщение может ссылаться не более чем на {count} диалогов","Acting on the page…":"Действие на странице…","Agent · {channel}":"Агент · {channel}","Agent switching is not available here":"Смена агента здесь недоступна","Almost there":"Почти готово","Also applies to your scheduled runs, until you revoke it":"Действует и для ваших запланированных запусков, пока вы его не отзовёте","Always allowed":"Всегда разрешено","Analyzing results (step {step})…":"Анализ результатов (шаг {step})…","Analyzing results…":"Анализ результатов…","Analyzing the details":"Анализ подробностей",Approved:"Одобрено","Archive all conversations":"Архивировать все диалоги","Archive all conversations?":"Архивировать все диалоги?","Ask Assistant":"Спросить ассистента","Ask a question...":"Задайте вопрос...",Assistant:"Ассистент","Attach files":"Прикрепить файлы","Attached files":"Прикреплённые файлы","Attachments wait for the current response":"Вложения ждут завершения текущего ответа",Back:"Назад","Bad response":"Плохой ответ","Browse agents":"Обзор агентов",Cancel:"Отмена","Cancel question":"Отменить вопрос","Clear all conversations":"Очистить все диалоги",Close:"Закрыть","Collecting results from one task…":"Сбор результатов одной задачи…","Collecting results from {count} tasks…":"Сбор результатов задач ({count})…","Compacting conversation context…":"Сжатие контекста диалога…","Composing answer…":"Составление ответа…",Confirm:"Подтвердить","Connecting integrations…":"Подключение интеграций…","Connecting the dots":"Сопоставление фактов","Consulting an agent…":"Консультация с агентом…","Consulting the sources":"Изучение источников","Consulting {agent}…":"Консультация с агентом {agent}…","Consulting {agent}: {count} questions…":"Консультация с агентом {agent}: вопросов — {count}…","Consulting {agent}: {tool} (+{count} more)…":"Консультация с агентом {agent}: {tool} (+{count} ещё)…","Consulting {agent}: {tool}…":"Консультация с агентом {agent}: {tool}…","Consulting {agent}: writing the answer…":"Консультация с агентом {agent}: составление ответа…","Consulting {count} agents…":"Консультация с агентами ({count})…","Context full — older turns are being dropped":"Контекст заполнен — старые ходы удаляются","Context nearly full — older turns are being summarized":"Контекст почти заполнен — старые ходы сводятся в краткое изложение","Context used":"Использовано контекста","Continue now":"Продолжить сейчас",Conversation:"Диалог","Conversation history":"История диалогов","Conversation title":"Название диалога","Conversation transcript":"Расшифровка диалога",Copied:"Скопировано","Copied!":"Скопировано!","Copy code":"Копировать код","Copy message":"Копировать сообщение","Copy response":"Копировать ответ","Could not load your conversations.":"Не удалось загрузить ваши диалоги.","Could not reach the assistant service. Check the connection and try again.":"Не удалось связаться со службой ассистента. Проверьте подключение и повторите попытку.","Could not send your decision. Please try again.":"Не удалось отправить ваше решение. Повторите попытку.","Create agent":"Создать агента","Crunching the data":"Обработка данных","Decline this call":"Отклонить этот вызов",Declined:"Отклонено","Delegating one task…":"Делегирование одной задачи…","Delegating {count} tasks…":"Делегирование задач ({count})…","Delete all conversations":"Удалить все диалоги","Delete all conversations?":"Удалить все диалоги?","Delete conversation":"Удалить диалог","Delete workspace":"Удалить рабочее пространство","Delete?":"Удалить?","Dictate a message":"Продиктовать сообщение","Did not answer":"Нет ответа",Download:"Скачать","Download {format}":"Скачать в формате {format}","Drop a conversation here, or start one with {icon}.":"Перетащите сюда диалог или начните новый с помощью {icon}.","Drop files to attach them":"Перетащите файлы, чтобы прикрепить их","End voice call":"Завершить голосовой вызов","Enter to send · Shift+Enter for new line":"Enter — отправить · Shift+Enter — новая строка","Enter to send now · Esc to stop":"Enter — отправить сейчас · Esc — остановить","Enter to send when the answer ends · Esc to stop":"Enter — отправить после ответа · Esc — остановить","Every conversation is in a workspace.":"Все диалоги находятся в рабочих пространствах.","Expand image":"Развернуть изображение","Failed to get a response. Resuming…":"Не удалось получить ответ. Возобновление…","Feedback already submitted":"Отзыв уже отправлен","Files uploading...":"Загрузка файлов...",Floating:"Плавающее окно","Full screen":"Во весь экран","Good response":"Хороший ответ","Help me create a new simulation scenario":"Помоги мне создать новый сценарий симуляции","Hide conversations":"Скрыть диалоги","How can I help you, {name}?":"Чем я могу помочь, {name}?","How can {agent} help you, {name}?":"Чем {agent} может помочь, {name}?","How do I configure detection rules?":"Как настроить правила обнаружения?","Image could not be loaded":"Не удалось загрузить изображение","Image preview":"Предпросмотр изображения","Incorporating your message…":"Учёт вашего сообщения…",Input:"Ввод","Insert prompt template":"Вставить шаблон промпта","Interrupted by a server restart.":"Прервано перезапуском сервера.","Listening...":"Слушаю...","Load earlier messages":"Загрузить предыдущие сообщения","Loading earlier messages…":"Загрузка предыдущих сообщений…","Loading conversation history…":"Загрузка истории диалога…","Loading image…":"Загрузка изображения…","MCP & dynamic tools":"MCP и динамические инструменты","Mention an agent":"Упомянуть агента","Model reasoning":"Рассуждения модели","Move to workspace":"Переместить в рабочее пространство","Mute microphone":"Выключить микрофон",Muted:"Микрофон выключен","New chat":"Новый чат","New conversation":"Новый диалог","New conversation in this workspace":"Новый диалог в этом рабочем пространстве","New conversation outside a workspace":"Новый диалог вне рабочего пространства","New conversation — send a message to start it":"Новый диалог — отправьте сообщение, чтобы начать его","New workspace":"Новое рабочее пространство",No:"Нет","No agent matches":"Подходящих агентов нет","None of your conversations matches":"Ни один из ваших диалогов не подходит","No conversation matches":"Подходящих диалогов нет","No conversations yet":"Диалогов пока нет","No prompt matches":"Подходящих промптов нет","No response was generated. Please try again.":"Ответ не был сформирован. Повторите попытку.","No response.":"Нет ответа.","Not in a workspace":"Вне рабочего пространства","Not recommended for chat":"Не рекомендуется для чата","Not rendered yet":"Ещё не отрисовано",Open:"Открыть","Open conversation":"Открыть диалог","Open in XTM One":"Открыть в XTM One","Other workspaces":"Другие рабочие пространства",Output:"Вывод","Play Space Invaders":"Играть в Space Invaders","Play Space Invaders in XTM One":"Играть в Space Invaders в XTM One","Polishing the answer":"Доработка ответа",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (редактируемый)","Preparing tools…":"Подготовка инструментов…","Preparing…":"Подготовка…",Presentation:"Презентация","Putting it together":"Сведение воедино",Quota:"Квота","Quota reached":"Квота исчерпана","Read aloud":"Прочитать вслух","Reasoning details":"Подробности рассуждений","Reasoning details — interrupted by a server restart":"Подробности рассуждений — прервано перезапуском сервера","Reasoning details — turn limit reached":"Подробности рассуждений — достигнут предел ходов","Recalling memory…":"Обращение к памяти…","Reconnecting…":"Повторное подключение…","Reference a conversation":"Сослаться на диалог","Remove from workspace":"Убрать из рабочего пространства","Rename conversation":"Переименовать диалог","Rename workspace":"Переименовать рабочее пространство","Rendering {progress}%":"Отрисовка: {progress} %",Report:"Отчёт","Response ready":"Ответ готов","Reticulating splines":"Ретикуляция сплайнов",Retry:"Повторить",Save:"Сохранить","Scroll to bottom":"Прокрутить вниз","Saving response…":"Сохранение ответа…","Search agents...":"Поиск агентов...","Search conversations...":"Поиск диалогов...","Search prompts...":"Поиск промптов...",Send:"Отправить","Send now":"Отправить сейчас","Send when the answer ends":"Отправить после ответа","Sending…":"Отправка…","Sends when the answer ends:":"Будет отправлено после ответа:","Shared with you":"Доступные вам","Show conversations":"Показать диалоги","Show less":"Свернуть",Sidebar:"Боковая панель",Skip:"Пропустить","Skip response":"Пропустить ответ","Sorry, an error occurred. Please try again.":"Произошла ошибка. Повторите попытку.","Speak or tap to interrupt":"Говорите или коснитесь, чтобы прервать","Speaking…":"Говорит…","Started in {channel}":"Начат в {channel}","Stop dictation":"Остановить диктовку","Stop generating":"Остановить генерацию","Stop reading":"Остановить чтение",Stopped:"Остановлено","Stopping…":"Остановка…",Suggestions:"Предложения","Summarize my recent findings":"Подведи итоги моих последних находок","Summarized conversation":"Краткое изложение диалога","Summarizing earlier conversation…":"Краткое изложение начала диалога…",Superseded:"Заменён","Switch to":"Переключиться на","Switch to another agent":"Переключиться на другого агента","Switch view":"Сменить вид","System prompt":"Системный промпт","Tap to cancel":"Коснитесь, чтобы отменить","Tell us what went wrong (optional)":"Расскажите, что пошло не так (необязательно)","The agent is answering…":"Агент отвечает…","The agent needs your approval to run a tool:":"Агенту нужно ваше одобрение, чтобы запустить инструмент:","The agent needs your approval to run these tools:":"Агенту нужно ваше одобрение, чтобы запустить эти инструменты:","The conversation could not be deleted":"Не удалось удалить диалог","The conversation could not be moved":"Не удалось переместить диалог","The conversation could not be renamed":"Не удалось переименовать диалог","The conversations could not be archived":"Не удалось архивировать диалоги","The conversations could not be deleted":"Не удалось удалить диалоги","The render did not finish":"Отрисовка не завершилась","The server restarted while this turn was running, so it stopped before it could finish.":"Сервер был перезапущен во время этого хода, поэтому ход остановился, не успев завершиться.","The workspace could not be created":"Не удалось создать рабочее пространство","The workspace could not be deleted":"Не удалось удалить рабочее пространство","The workspace could not be renamed":"Не удалось переименовать рабочее пространство","Thinking it through":"Обдумывание","Thinking...":"Думаю...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Этот агент создан для заданий, а не для прямого чата. В диалоге он может отвечать плохо.","This conversation could not be loaded.":"Не удалось загрузить этот диалог.","This decision could not be sent. Reload the chat and try again.":"Не удалось отправить это решение. Перезагрузите чат и повторите попытку.","This message waits for the current response":"Это сообщение ждёт завершения текущего ответа","This message will be read with your next one.":"Это сообщение будет прочитано вместе со следующим.","This item could not be loaded.":"Не удалось загрузить этот элемент.","The response could not be stopped. Try again.":"Не удалось остановить ответ. Повторите попытку.","This turn is no longer waiting for a decision.":"Этот ход больше не ждёт решения.","Tool definitions":"Определения инструментов","Tool results":"Результаты инструментов","Transfer chain":"Цепочка передач","Transferred from {agent}":"Передано от агента {agent}","Transferring to another agent…":"Передача другому агенту…","Transferring to {agent}…":"Передача агенту {agent}…","Turn limit reached.":"Достигнут предел ходов.","Unable to connect. Please check the configuration.":"Не удалось подключиться. Проверьте конфигурацию.","Unmute microphone":"Включить микрофон","Untitled conversation":"Диалог без названия",Usage:"Использование","Upload failed":"Ошибка загрузки","Usage · {period}":"Использование · {period}","Uses AI. Verify results.":"Использует ИИ. Проверяйте результаты.","Using tools…":"Использование инструментов…",Video:"Видео","Voice call":"Голосовой вызов","Waiting before continuing…":"Ожидание перед продолжением…","Waiting for one background task…":"Ожидание одной фоновой задачи…","Waiting for your approval…":"Ожидание вашего одобрения…","Waiting for {count} background tasks…":"Ожидание фоновых задач ({count})…","Waiting to render":"Ожидание отрисовки","What are the latest attack patterns?":"Какие шаблоны атак появились недавно?","What could be improved?":"Что можно улучшить?","Why not? The agent sees this and can adapt (optional)":"Почему нет? Агент увидит это и сможет учесть (необязательно)","Working files ({count})":"Рабочие файлы ({count})","Workspace name":"Название рабочего пространства",Workspaces:"Рабочие пространства","Wrapping things up":"Завершение",Yes:"Да","Yes, always":"Да, всегда","Your answer is ready":"Ваш ответ готов",default:"по умолчанию","e.g. wrong environment — use staging instead":"например: не та среда — используйте вместо неё тестовую (staging)","just now":"только что","this month":"в этом месяце","this year":"в этом году",today:"сегодня","unknown tool":"неизвестный инструмент","{agent} has finished":"{agent}: готово","{agent} is answering…":"{agent} отвечает…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"Токены: {counts}","{count} iterations":"Итераций: {count}","{count} scenes":"Сцен: {count}","{count} sections":"Разделов: {count}","{count} slides":"Слайдов: {count}","{count} tool calls":"Вызовов инструментов: {count}","{count} transfers":"Передач: {count}","{count}d ago":"{count} дн. назад","{count}h ago":"{count} ч назад","{count}m ago":"{count} мин назад","{decided}/{total} decided":"Решено: {decided}/{total}","{name} was not attached: a file may be at most {size}.":"{name} не прикреплён: размер файла не может превышать {size}.","{name} was not attached: a message holds at most {count} files.":"{name} не прикреплён: к сообщению можно прикрепить не более {count} файлов.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} не прикреплён: общий размер файлов сообщения не может превышать {size}.","{name} was not attached: this type of file is not accepted.":"{name} не прикреплён: файлы этого типа не принимаются.","{percent}% full":"Заполнено на {percent} %","{quota} (shared across all users)":"{quota} (общая для всех пользователей)","{summary} — click for details":"{summary} — нажмите, чтобы узнать подробности","{tool} (+{count} more)…":"{tool} (+{count} ещё)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Бюджет итераций агента исчерпан: выполнение остановлено до завершения всех запланированных шагов. Итоговый ответ — максимально полная сводка проделанной на данный момент работы.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"«Да, всегда» сохраняет ваш выбор. После этого инструмент будет запускаться без запроса — в том числе в запланированных запусках, за которыми никто не следит, — пока вы не отзовёте разрешение."},zh:{"(no output)":"(无输出)","1 tool call":"1 次工具调用","1 transfer":"1 次转交","A file failed to upload: remove it to send the message":"有文件上传失败:请将其移除后再发送消息","A message references at most {count} conversations":"一条消息最多可引用 {count} 个对话","Acting on the page…":"正在页面上执行操作…","Agent · {channel}":"智能体 · {channel}","Agent switching is not available here":"此处无法切换智能体","Almost there":"马上就好","Also applies to your scheduled runs, until you revoke it":"在您撤销之前,也适用于您的计划运行","Always allowed":"始终允许","Analyzing results (step {step})…":"正在分析结果(第 {step} 步)…","Analyzing results…":"正在分析结果…","Analyzing the details":"正在分析细节",Approved:"已批准","Archive all conversations":"归档所有对话","Archive all conversations?":"要归档所有对话吗?","Ask Assistant":"询问助手","Ask a question...":"提出问题...",Assistant:"助手","Attach files":"附加文件","Attached files":"已附加的文件","Attachments wait for the current response":"附件将等待当前回复完成",Back:"返回","Bad response":"回复不佳","Browse agents":"浏览智能体",Cancel:"取消","Cancel question":"取消问题","Clear all conversations":"清除所有对话",Close:"关闭","Collecting results from one task…":"正在收集 1 个任务的结果…","Collecting results from {count} tasks…":"正在收集 {count} 个任务的结果…","Compacting conversation context…":"正在压缩对话上下文…","Composing answer…":"正在撰写回答…",Confirm:"确认","Connecting integrations…":"正在连接集成…","Connecting the dots":"正在串联线索","Consulting an agent…":"正在咨询智能体…","Consulting the sources":"正在查阅来源","Consulting {agent}…":"正在咨询 {agent}…","Consulting {agent}: {count} questions…":"正在咨询 {agent}:{count} 个问题…","Consulting {agent}: {tool} (+{count} more)…":"正在咨询 {agent}:{tool}(另有 {count} 个)…","Consulting {agent}: {tool}…":"正在咨询 {agent}:{tool}…","Consulting {agent}: writing the answer…":"正在咨询 {agent}:正在撰写回答…","Consulting {count} agents…":"正在咨询 {count} 个智能体…","Context full — older turns are being dropped":"上下文已满 — 正在丢弃较早的轮次","Context nearly full — older turns are being summarized":"上下文即将用满 — 正在总结较早的轮次","Context used":"已用上下文","Continue now":"立即继续",Conversation:"对话","Conversation history":"对话历史","Conversation title":"对话标题","Conversation transcript":"对话记录",Copied:"已复制","Copied!":"已复制!","Copy code":"复制代码","Copy message":"复制消息","Copy response":"复制回复","Could not load your conversations.":"无法加载您的对话。","Could not reach the assistant service. Check the connection and try again.":"无法连接到助手服务。请检查连接后重试。","Could not send your decision. Please try again.":"无法发送您的决定。请重试。","Create agent":"创建智能体","Crunching the data":"正在处理数据","Decline this call":"拒绝此调用",Declined:"已拒绝","Delegating one task…":"正在委派 1 个任务…","Delegating {count} tasks…":"正在委派 {count} 个任务…","Delete all conversations":"删除所有对话","Delete all conversations?":"要删除所有对话吗?","Delete conversation":"删除对话","Delete workspace":"删除工作区","Delete?":"要删除吗?","Dictate a message":"语音输入消息","Did not answer":"未回答",Download:"下载","Download {format}":"下载 {format}","Drop a conversation here, or start one with {icon}.":"将对话拖放到此处,或使用 {icon} 开始新对话。","Drop files to attach them":"拖放文件以附加","End voice call":"结束语音通话","Enter to send · Shift+Enter for new line":"按 Enter 发送 · 按 Shift+Enter 换行","Enter to send now · Esc to stop":"按 Enter 立即发送 · 按 Esc 停止","Enter to send when the answer ends · Esc to stop":"按 Enter 在回答结束后发送 · 按 Esc 停止","Every conversation is in a workspace.":"所有对话都已在工作区中。","Expand image":"放大图片","Failed to get a response. Resuming…":"未能获取回复。正在恢复…","Feedback already submitted":"已提交反馈","Files uploading...":"正在上传文件...",Floating:"浮动","Full screen":"全屏","Good response":"回复很好","Help me create a new simulation scenario":"帮我创建一个新的模拟场景","Hide conversations":"隐藏对话","How can I help you, {name}?":"{name},有什么可以帮您?","How can {agent} help you, {name}?":"{name},{agent} 能为您做些什么?","How do I configure detection rules?":"如何配置检测规则?","Image could not be loaded":"无法加载图片","Image preview":"图片预览","Incorporating your message…":"正在纳入您的消息…",Input:"输入","Insert prompt template":"插入提示词模板","Interrupted by a server restart.":"因服务器重启而中断。","Listening...":"正在聆听...","Load earlier messages":"加载更早的消息","Loading earlier messages…":"正在加载更早的消息…","Loading conversation history…":"正在加载对话历史…","Loading image…":"正在加载图片…","MCP & dynamic tools":"MCP 与动态工具","Mention an agent":"提及智能体","Model reasoning":"模型推理","Move to workspace":"移至工作区","Mute microphone":"麦克风静音",Muted:"已静音","New chat":"新聊天","New conversation":"新对话","New conversation in this workspace":"在此工作区中新建对话","New conversation outside a workspace":"在工作区外新建对话","New conversation — send a message to start it":"新对话 — 发送一条消息即可开始","New workspace":"新建工作区",No:"否","No agent matches":"没有匹配的智能体","None of your conversations matches":"您的对话中没有匹配项","No conversation matches":"没有匹配的对话","No conversations yet":"暂无对话","No prompt matches":"没有匹配的提示词","No response was generated. Please try again.":"未生成回复。请重试。","No response.":"无回复。","Not in a workspace":"不在工作区中","Not recommended for chat":"不建议用于聊天","Not rendered yet":"尚未渲染",Open:"打开","Open conversation":"打开对话","Open in XTM One":"在 XTM One 中打开","Other workspaces":"其他工作区",Output:"输出","Play Space Invaders":"玩 Space Invaders","Play Space Invaders in XTM One":"在 XTM One 中玩 Space Invaders","Polishing the answer":"正在润色回答",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint(可编辑)","Preparing tools…":"正在准备工具…","Preparing…":"正在准备…",Presentation:"演示文稿","Putting it together":"正在整合内容",Quota:"配额","Quota reached":"已达配额","Read aloud":"朗读","Reasoning details":"推理详情","Reasoning details — interrupted by a server restart":"推理详情 — 因服务器重启而中断","Reasoning details — turn limit reached":"推理详情 — 已达轮次上限","Recalling memory…":"正在调取记忆…","Reconnecting…":"正在重新连接…","Reference a conversation":"引用对话","Remove from workspace":"从工作区中移除","Rename conversation":"重命名对话","Rename workspace":"重命名工作区","Rendering {progress}%":"正在渲染 {progress}%",Report:"报告","Response ready":"回复已就绪","Reticulating splines":"正在网格化样条",Retry:"重试",Save:"保存","Scroll to bottom":"滚动到底部","Saving response…":"正在保存回复…","Search agents...":"搜索智能体...","Search conversations...":"搜索对话...","Search prompts...":"搜索提示词...",Send:"发送","Send now":"立即发送","Send when the answer ends":"回答结束后发送","Sending…":"正在发送…","Sends when the answer ends:":"将在回答结束后发送:","Shared with you":"与您共享","Show conversations":"显示对话","Show less":"收起",Sidebar:"侧边栏",Skip:"跳过","Skip response":"跳过回复","Sorry, an error occurred. Please try again.":"抱歉,发生了错误。请重试。","Speak or tap to interrupt":"说话或点按即可打断","Speaking…":"正在说话…","Started in {channel}":"始于 {channel}","Stop dictation":"停止语音输入","Stop generating":"停止生成","Stop reading":"停止朗读",Stopped:"已停止","Stopping…":"正在停止…",Suggestions:"建议","Summarize my recent findings":"总结我最近的发现","Summarized conversation":"已总结的对话","Summarizing earlier conversation…":"正在总结较早的对话…",Superseded:"已被替换","Switch to":"切换到","Switch to another agent":"切换到其他智能体","Switch view":"切换视图","System prompt":"系统提示词","Tap to cancel":"点按以取消","Tell us what went wrong (optional)":"请告诉我们哪里出了问题(可选)","The agent is answering…":"智能体正在回答…","The agent needs your approval to run a tool:":"智能体需要您的批准才能运行工具:","The agent needs your approval to run these tools:":"智能体需要您的批准才能运行以下工具:","The conversation could not be deleted":"无法删除该对话","The conversation could not be moved":"无法移动该对话","The conversation could not be renamed":"无法重命名该对话","The conversations could not be archived":"无法归档这些对话","The conversations could not be deleted":"无法删除这些对话","The render did not finish":"渲染未完成","The server restarted while this turn was running, so it stopped before it could finish.":"本轮运行期间服务器重启,因此本轮在完成前已停止。","The workspace could not be created":"无法创建工作区","The workspace could not be deleted":"无法删除工作区","The workspace could not be renamed":"无法重命名工作区","Thinking it through":"正在深入思考","Thinking...":"正在思考...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"此智能体专为任务设计,而非直接聊天,可能无法很好地回应对话。","This conversation could not be loaded.":"无法加载此对话。","This decision could not be sent. Reload the chat and try again.":"无法发送此决定。请重新加载聊天后重试。","This message waits for the current response":"此消息将等待当前回复完成","This message will be read with your next one.":"此消息将与您的下一条消息一起读取。","This item could not be loaded.":"无法加载此项目。","The response could not be stopped. Try again.":"无法停止回复。请重试。","This turn is no longer waiting for a decision.":"本轮已不再等待决定。","Tool definitions":"工具定义","Tool results":"工具结果","Transfer chain":"转交链","Transferred from {agent}":"由 {agent} 转交","Transferring to another agent…":"正在转交给其他智能体…","Transferring to {agent}…":"正在转交给 {agent}…","Turn limit reached.":"已达轮次上限。","Unable to connect. Please check the configuration.":"无法连接。请检查配置。","Unmute microphone":"取消麦克风静音","Untitled conversation":"未命名对话",Usage:"用量","Upload failed":"上传失败","Usage · {period}":"用量 · {period}","Uses AI. Verify results.":"由 AI 生成,请核实结果。","Using tools…":"正在使用工具…",Video:"视频","Voice call":"语音通话","Waiting before continuing…":"正在等待后继续…","Waiting for one background task…":"正在等待 1 个后台任务…","Waiting for your approval…":"正在等待您的批准…","Waiting for {count} background tasks…":"正在等待 {count} 个后台任务…","Waiting to render":"等待渲染","What are the latest attack patterns?":"最新的攻击模式有哪些?","What could be improved?":"有哪些可以改进的地方?","Why not? The agent sees this and can adapt (optional)":"为什么拒绝?智能体会看到并据此调整(可选)","Working files ({count})":"工作文件({count})","Workspace name":"工作区名称",Workspaces:"工作区","Wrapping things up":"正在收尾",Yes:"是","Yes, always":"是,始终允许","Your answer is ready":"您的回答已就绪",default:"默认","e.g. wrong environment — use staging instead":"例如:环境不对 — 请改用预发布环境","just now":"刚刚","this month":"本月","this year":"今年",today:"今天","unknown tool":"未知工具","{agent} has finished":"{agent} 已完成","{agent} is answering…":"{agent} 正在回答…","{agent}: {status}":"{agent}:{status}","{counts} tokens":"{counts} Token","{count} iterations":"{count} 次迭代","{count} scenes":"{count} 个场景","{count} sections":"{count} 个章节","{count} slides":"{count} 张幻灯片","{count} tool calls":"{count} 次工具调用","{count} transfers":"{count} 次转交","{count}d ago":"{count} 天前","{count}h ago":"{count} 小时前","{count}m ago":"{count} 分钟前","{decided}/{total} decided":"已决定 {decided}/{total}","{name} was not attached: a file may be at most {size}.":"未附加 {name}:单个文件不得超过 {size}。","{name} was not attached: a message holds at most {count} files.":"未附加 {name}:一条消息最多包含 {count} 个文件。","{name} was not attached: the files of a message may add up to at most {size}.":"未附加 {name}:一条消息中文件的总大小不得超过 {size}。","{name} was not attached: this type of file is not accepted.":"未附加 {name}:不接受此类型的文件。","{percent}% full":"已用 {percent}%","{quota} (shared across all users)":"{quota}(所有用户共享)","{summary} — click for details":"{summary} — 点击查看详情","{tool} (+{count} more)…":"{tool}(另有 {count} 个)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"智能体的迭代预算已用尽:执行在完成所有计划步骤之前已停止。最终回复是对目前已完成工作的尽力总结。","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"“是,始终允许”会为您保存一项偏好设置。此后,该工具将无需询问即可运行(包括无人值守的计划运行),直到您撤销为止。"}},ie=/^zh(?:[-_](?:cn|sg|hans)(?:[-_].*)?)?$/;function ce(e,t){const n=t||!e?function(e){const t=(e??("undefined"!=typeof navigator?navigator.language:void 0))?.toLowerCase(),n=t?.split(/[-_]/)[0];if(t&&n&&("zh"!==n||ie.test(t)))return se[n]}(t):void 0;return t=>{const r=e?.(t);return r&&r!==t?r:n?.[t]??t}}const le=e=>"up"===e?"positive":"negative";function de(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function ue(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function he(e,t,n){return re(e,t,n,"feedback")}async function pe(e,t,n,r,o,a){const{url:s,init:i}=function(e,t,n,r,o){const a=`${e}/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}/feedback`;return r?{url:a,init:{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...o},body:JSON.stringify({rating:r.rating,comment:ue(r.comment)})}}:{url:a,init:{method:"DELETE",credentials:"include",headers:{...o}}}}(t,n,r,o,a);try{return(await e(s,i)).ok}catch{return!1}}const me=e=>void 0!==e&&/[\w-]/.test(e),ge=/^[\w-]+$/;function fe(e){const t=[],n=/@([\w-]+)/g;let r=n.exec(e);for(;null!==r;){const o=r[1].toLowerCase();me(e[r.index-1])||t.includes(o)||t.push(o),r=n.exec(e)}return t}function ve(e,t){if(0===e.length)return e;const n=new Set(fe(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}function we(e,t){if(0===e.length)return[];const n=[];for(const r of fe(t))for(const t of e)t.key.toLowerCase()!==r||n.some(e=>e.conversationId===t.conversationId)||n.push(t);return n.slice(0,5)}function be(e){const t=Array.isArray(e)?e:Array.isArray(e?.conversations)?e.conversations:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.id&&t.id&&"string"==typeof t.key&&ge.test(t.key)&&(n.some(e=>e.id===t.id)||n.push({id:t.id,title:"string"==typeof t.title?t.title.trim():"",key:t.key,updatedAt:"string"==typeof t.updated_at?t.updated_at:void 0,isOwn:!1!==t.is_own}))}return n}function ye(e,t,n){return re(e,t,n,"conversationReferences")}const xe={query:null,items:[],failed:!1};function ke(e,t){const n=e.toLowerCase();if(!n||t.key.toLowerCase().startsWith(n))return!0;const r=t.title.toLowerCase(),o=n.split(/[\s_-]+/).filter(Boolean);return o.length>0&&o.every(e=>r.includes(e))}function Ce(e,t){if(t.every(t=>e.some(e=>{return r=t,(n=e).id===r.id&&n.key===r.key&&n.title===r.title&&n.isOwn===r.isOwn&&n.updatedAt===r.updatedAt;var n,r})))return e;const n=new Set(t.map(e=>e.id)),r=[...e.filter(e=>!n.has(e.id)),...t];return r.length>200?r.slice(r.length-200):r}function Ne(e){return{id:e.conversationId,title:e.title,key:e.key,isOwn:e.isOwn??!0}}function Se(e,t={}){const n=Array.isArray(e)?e:Array.isArray(e?.workspaces)?e.workspaces:[],r=[];for(const e of n){if(!e||"object"!=typeof e)continue;const n=e;"string"==typeof n.id&&n.id&&"string"==typeof n.name&&(!0!==n.is_archived&&r.push({id:n.id,name:n.name,isOwn:"boolean"==typeof n.is_own?n.is_own:!!t.userId&&n.user_id===t.userId,isDefault:!0===n.is_default,canManage:!0===n.can_manage}))}return r}function Te(e){const t=e=>e.isDefault&&e.isOwn;return[...e].sort((e,n)=>t(e)!==t(n)?t(e)?-1:1:e.name.localeCompare(n.name))}function Ae(e,t,n,r,o){return!!o||(!(!r||!n.conversations.some(e=>e.conversationId===r))||!t.has(e))}function Ie(e,t,n){return!n&&!(t&&e.conversations.some(e=>e.conversationId===t))}const Ee=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&t.length<=500?t:null},ze=/^[\w.-]+$/,Re=/^[A-Z][A-Za-z]*(?: [A-Z][A-Za-z]*)*$/;function Me(e){const t=Ee(e);return!t||ze.test(t)||Re.test(t)?null:t}async function De(e){try{return function(e){if(!e||"object"!=typeof e)return null;const{detail:t,error:n}=e;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;return Ee(e.message)??Ee(e.detail)??Me(n)}return Ee(t)??Me(n)}(await e.json())}catch{return null}}function Le(e){return e?JSON.stringify(Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0)):""}function _e(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}const Pe=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function je(e){const t=e.context_tokens,n=e.context_window;if("number"!=typeof t||"number"!=typeof n)return;if(!Number.isFinite(t)||!Number.isFinite(n)||n<=0||t<0)return;const r=function(e){if(!e||"object"!=typeof e)return;const t=e,n={};let r=!1;for(const[e,o]of Pe){const a=t[e];"number"==typeof a&&Number.isFinite(a)&&a>0&&(n[o]=a,r=!0)}return r?n:void 0}(e.context_breakdown);return r?{used:t,limit:n,breakdown:r}:{used:t,limit:n}}function $e(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.file_id;"string"==typeof r&&r&&t.push({fileId:r,filename:"string"==typeof e.filename?e.filename:"file",type:"string"==typeof e.type?e.type:void 0,size:"number"==typeof e.size?e.size:void 0,contentType:"string"==typeof e.content_type?e.content_type:void 0,fileTag:"working_file"===e.file_tag?"working_file":"download_file"})}return t.length>0?t:void 0}const Ue=["presentation","report","video"],Oe=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0;function We(e){if(!e||"object"!=typeof e)return;const t=e,n=Ue.find(e=>e===t.kind);return n&&"string"==typeof t.id&&t.id?{kind:n,id:t.id,title:"string"==typeof t.title?t.title:"",url:"string"==typeof t.url&&t.url?t.url:void 0,slideRef:"string"==typeof t.slide_ref&&t.slide_ref?t.slide_ref:void 0,slideCount:Oe(t.slide_count),sectionCount:Oe(t.section_count),sceneCount:Oe(t.scene_count),durationMs:Oe(t.duration_ms),status:"string"==typeof t.status&&t.status?t.status:void 0,progress:Oe(t.progress),downloads:Array.isArray(t.downloads)?t.downloads.filter(e=>"string"==typeof e&&!!e):[]}:void 0}function qe(e){if(!Array.isArray(e))return;const t=e.map(We).filter(e=>!!e);return t.length>0?t:void 0}function Fe(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.name&&e.name&&t.push({name:e.name,input:"string"==typeof e.input?e.input:void 0,output:"string"==typeof e.output?e.output:void 0,success:"boolean"!=typeof e.success||e.success})}return t.length>0?t:void 0}function He(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.conversation_id&&e.conversation_id&&(t.some(t=>t.conversationId===e.conversation_id)||t.push({conversationId:e.conversation_id,title:"string"==typeof e.title?e.title.trim():"",key:"string"==typeof e.key?e.key:""}))}return t.length>0?t:void 0}function Be(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.agent_name&&e.agent_name&&t.push({agentId:"string"==typeof e.agent_id?e.agent_id:"",agentName:e.agent_name})}return t.length>0?t:void 0}function Ve(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.tool_call_id;if("string"!=typeof r||!r)continue;const o=e.arguments,a=e.input_schema;t.push({toolCallId:r,toolName:"string"==typeof e.tool_name&&e.tool_name?e.tool_name:"",toolDescription:"string"==typeof e.tool_description?e.tool_description:void 0,arguments:o&&"object"==typeof o&&!Array.isArray(o)?o:{},inputSchema:a&&"object"==typeof a&&!Array.isArray(a)?a:void 0,source:"string"==typeof e.source?e.source:void 0})}return t.length>0?t:void 0}const Ke=e=>"string"==typeof e&&e?e:void 0,Ge=e=>e&&"object"==typeof e&&!Array.isArray(e)?e:void 0;function Ye(e){const t=Ke(e.agent_name);if(!t)return;const n=Ge(e.inner);let r=n;for(let e=0;"consult_progress"===r?.status&&e<8;e+=1)r=Ge(r.inner);const o=Array.isArray(r?.tools)?r.tools.filter(e=>"string"==typeof e):void 0,a=Ke(e.agent_id)??t;return{consultId:Ke(e.consult_id)??a,agentId:a,agentName:t,status:Ke(r?.status),tools:o,answering:"streaming"===n?.status||"composing"===n?.status}}function Xe(e){if("string"==typeof e)return e?{agentName:e}:void 0;if(!e||"object"!=typeof e)return;const t=e,n={agentId:Ke(t.agent_id),agentName:Ke(t.agent_name)??Ke(t.name),agentIcon:Ke(t.agent_icon)};return n.agentId||n.agentName?Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e)):void 0}function Je(e,t){const n=e.type;if("error"===n||"cancelled"===n){const t=Ke(e.message_id),r=!0===e.provisional||void 0,o={...t?{messageId:t,raw:{...e}}:{},...r?{provisional:r}:{}};return"error"===n?{action:"error",content:e.content||"",...o}:{action:"cancelled",...o}}if("session_expired"===n)return{action:"session_ended",reason:Ke(e.reason)};if("approval_resolved"===n)return{action:"approval_resolved"};if("folded_into_active_turn"===n)return{action:"folded",turnId:Ke(e.turn_id)};if("conversation_title"===n){const t=Ke(e.title);return t?{action:"conversation_title",conversationId:Ke(e.conversation_id),title:t}:{action:"noop"}}if("user_message"===n){const[t]=et([e.message]);return t&&"user"===t.role?{action:"user_message",message:{...t,id:Qe(t.serverId)}}:{action:"noop"}}if("thinking"===n)return{action:"status",status:"thinking",resumed:!0===e.resumed||void 0,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};if("status"===n){const n=e.status;if("tool_done"===n||"wind_down"===n)return{action:"noop"};if("streaming"===n)return{action:"status",status:"streaming"};if("thinking_text"===n)return{action:"status",status:"thinking_text",thinkingContent:e.content};if("tool_start"===n)return t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:e.tools};if("tool_progress"===n&&"page_action_required"===e.event){if("string"!=typeof e.action_id||!e.action_id)return{action:"noop"};const t=function(e){if(!e||"object"!=typeof e)return{type:"unsupported",requested:"malformed"};const t=e,n=e=>"string"==typeof e&&e.length>0;return"snapshot"===t.type?{type:"snapshot"}:"navigate"===t.type&&n(t.path)?{type:"navigate",path:t.path}:"click"===t.type&&n(t.ref)?{type:"click",ref:t.ref}:"open"===t.type&&n(t.ref)?{type:"open",ref:t.ref}:"type"===t.type&&n(t.ref)&&"string"==typeof t.text?{type:"type",ref:t.ref,text:t.text}:{type:"unsupported",requested:"string"==typeof t.type?t.type.slice(0,64):"unknown"}}(e.action);return{action:"page_action_required",actionId:e.action_id,pageAction:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}}if("transfer_start"===n||"mention_answering"===n)return{action:"status",status:"transfer_start"===n?"transferring":n,agentName:Ke(e.agent_name),contextUsage:je(e)};if("consult_progress"===n)return{action:"status",status:n,consult:Ye(e)};if("wait_start"===n)return{action:"status",status:"wait_start",waitSeconds:"number"==typeof e.seconds&&e.seconds>0?e.seconds:void 0,waitReason:Ke(e.reason)};if("tool_heartbeat"===n)return{action:"status",status:"tool_heartbeat",tools:e.tools,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};const r=je(e),o="number"==typeof e.iteration&&Number.isInteger(e.iteration)&&e.iteration>0?e.iteration:void 0;return"thinking"===n&&t.hasUsedTools?{action:"status",status:"analyzing",contextUsage:r,iteration:o}:{action:"status",status:n,tools:e.tools,contextUsage:r,phase:Ke(e.phase),iteration:o}}if("approval_required"===n){const t=Ve(e.proposals);return t?{action:"approval_required",proposals:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}:{action:"noop"}}return"stream"===n?{action:"stream",content:e.content}:"done"===n?{action:"done",content:e.content,conversationId:e.conversation_id,toolNames:e.tool_names,toolCallCount:e.tool_call_count,iterations:e.iterations,transferAgentId:e.transfer_agent_id,transferAgentName:e.transfer_agent_name,attachments:$e(e.attachments),artifacts:qe(e.artifacts),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:Fe(e.tool_call_trace),transferChain:Be(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:je(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0,intermediate:!0===e.intermediate||void 0,answeredBy:Xe(e.answered_by),mentionFailed:!0===e.mention_failed||void 0,raw:{...e}}:{action:"noop"}}function Qe(e,t=_e()){return e?`msg-${e}`:t}function Ze(e){if(!e||"object"!=typeof e)return;const{rating:t,comment:n}=e;return"positive"===t||"negative"===t?{rating:t,comment:"string"==typeof n&&n.trim()?n:null}:void 0}function et(e){if(!Array.isArray(e))return[];const t=[];return e.forEach((e,n)=>{if(!e||"object"!=typeof e)return;const r=e;if("user"!==r.role&&"assistant"!==r.role)return;const o="string"==typeof r.created_at?new Date(r.created_at):null,a=o&&!Number.isNaN(o.getTime())?o:null,s="assistant"===r.role?Xe(r.answered_by):void 0,i="string"==typeof r.id&&r.id?r.id:void 0;t.push({id:Qe(i,`restored-${n}`),serverId:i,role:r.role,content:"string"==typeof r.content?r.content:"",timestamp:a??new Date,timestampUnknown:!a||void 0,feedback:"assistant"===r.role?Ze(r.feedback):void 0,agentName:s?.agentName??("string"==typeof r.agent_name?r.agent_name:void 0),answeredBy:s,mentionFailed:"assistant"===r.role&&!0===r.mention_failed||void 0,attachments:$e(r.attachments),artifacts:"assistant"===r.role?qe(r.artifacts):void 0,conversationRefs:"user"===r.role?He(r.conversation_refs):void 0,toolNames:Array.isArray(r.tool_names)?r.tool_names:void 0,toolCallCount:"number"==typeof r.tool_call_count?r.tool_call_count:void 0,iterations:"number"==typeof r.iterations?r.iterations:void 0,reasoning:"string"==typeof r.reasoning?r.reasoning:void 0,toolCallTrace:Fe(r.tool_call_trace),transferChain:Be(r.transfer_chain),isTruncated:!0===r.is_truncated||void 0,interrupted:"assistant"===r.role&&!0===r.interrupted||void 0,raw:{...r}})}),t}function tt(e,t){const n=e.event;if("nextAgentFlow"===n){const n=e.data,r=n?.nodeId;return"INPROGRESS"===n?.status&&r&&(t.activeNodeId=r),{action:"noop"}}if("start"===n)return{action:"noop"};if("token"===n){return{action:"stream",content:(e.data??"").replace(/<br\s*\/?>/g,"\n")}}if("agentReasoning"===n){const n=e.data,r=n?.usedTools;return r?.length?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:r.map(e=>e.tool)}):t.hasUsedTools?{action:"status",status:"analyzing"}:{action:"status",status:"thinking"}}if("usedTools"===n){t.hasUsedTools=!0;const n=e.data;return{action:"status",status:"tool_start",tools:Array.isArray(n)?n.map(e=>e.tool):[]}}if("metadata"===n){const t=e.data,n=t?.chatId;return n?{action:"set_chat_id",chatId:n}:{action:"noop"}}return"error"===n?{action:"error",content:e.data||""}:"end"===n?{action:"done",content:""}:{action:"noop"}}function nt(e,t){const n=e.type;if("RUN_STARTED"===n)return{action:"status",status:"thinking"};if("RUN_FINISHED"===n)return{action:"done",content:""};if("RUN_ERROR"===n)return{action:"error",content:"string"==typeof e.message?e.message:""};if("STEP_STARTED"===n){return{action:"status",status:e.stepName||"thinking"}}if("STEP_FINISHED"===n)return{action:"noop"};if("TEXT_MESSAGE_START"===n)return{action:"status",status:"streaming"};if("TEXT_MESSAGE_CONTENT"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TEXT_MESSAGE_END"===n)return{action:"noop"};if("TEXT_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TOOL_CALL_START"===n){t.hasUsedTools=!0;const n=e.toolCallName;return{action:"status",status:"tool_start",tools:n?[n]:[]}}if("TOOL_CALL_ARGS"===n)return{action:"noop"};if("TOOL_CALL_END"===n)return{action:"status",status:"analyzing"};if("TOOL_CALL_RESULT"===n)return{action:"noop"};if("TOOL_CALL_CHUNK"===n){const n=e.toolCallName;return n?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:[n]}):{action:"noop"}}if("REASONING_START"===n||"REASONING_MESSAGE_START"===n)return{action:"status",status:"thinking"};if("REASONING_MESSAGE_CONTENT"===n||"REASONING_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"status",status:"thinking_text",thinkingContent:t}:{action:"status",status:"thinking"}}return{action:"noop"}}function rt(){let e=0,t=null,n=null;return{get generation(){return e},get pending(){return t},run(r){if(t)return t;const o=e,a=new AbortController;n=a;const s=r(()=>o===e,a.signal).catch(()=>null);return t=s,s.finally(()=>{t===s&&(t=null),n===a&&(n=null)}),s},abandon(){e+=1,t=null,n?.abort(),n=null}}}function ot(e,t){return null!==e&&"function"==typeof t}function at(e){return e?.defaultView?.location?.href??("undefined"==typeof window?void 0:window.location.href)}const st=(e,t)=>{const n=t??at();if(!e||!n)return null;try{const t=new URL(e,n);if("http:"!==t.protocol&&"https:"!==t.protocol)return null;if(t.origin!==new URL(n).origin)return null;const r=`${t.pathname}${t.search}${t.hash}`||"/";return r.startsWith("//")?null:r}catch{return null}};function it(e){const t=e&&"closest"in e?e:e?.parentElement;return!!t?.closest?.(".filigran-chatbot")}const ct=/^(current-password|new-password|one-time-code|cc-)/;function lt(e){const t=e.ownerDocument.defaultView,n={bubbles:!0,cancelable:!0,view:t??void 0,pointerType:"mouse"},r=t?.PointerEvent??t?.MouseEvent??MouseEvent,o=t?.MouseEvent??MouseEvent;e.dispatchEvent(new r("pointerover",n)),e.dispatchEvent(new r("pointerenter",{...n,bubbles:!1})),e.dispatchEvent(new o("mouseover",n)),e.dispatchEvent(new o("mouseenter",{...n,bubbles:!1}))}function dt(e,t,n){const r=e=>e.preventDefault();for(const n of t)e.addEventListener(n,r,!0);try{n()}finally{for(const n of t)e.removeEventListener(n,r,!0)}}function ut(e,t,n){if(e.matches?.("a[href]")){const r=e.getAttribute("target");if(r&&"_self"!==r)return{ok:!1,error:"opens_new_tab"};const o=e.getAttribute("href")??"";if(o&&!o.startsWith("#")){const e=st(o,n);if(!e)return{ok:!1,error:"external_link"};if(t)return t(e),{ok:!0}}}e.focus?.();const r=e.closest?.("a[href]"),o=!!r&&!(r.getAttribute("href")??"").startsWith("#"),a=o?["submit","click"]:["submit"],s=e.matches?.('input[type="checkbox"], input[type="radio"]')??!1,i=e.checked;if(dt(e.ownerDocument,a,()=>e.click()),s&&o&&e.checked===i){const t=e;t.checked="radio"===t.type||!i,t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("input",{bubbles:!0})),t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("change",{bubbles:!0}))}return{ok:!0}}function ht(e){const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!1}for(let t=e;t;t=t.parentElement){if(t.hidden||t.hasAttribute("inert"))return!1;if("true"===t.getAttribute("aria-hidden"))return!1;const e=t.ownerDocument.defaultView?.getComputedStyle(t);if("none"===e?.display||"hidden"===e?.visibility)return!1}return!0}function pt(e){const t=e.getAttribute("aria-expanded");if("true"===t)return!0;if("false"===t)return!1;const n=e.getAttribute("aria-controls");if(!n)return!1;const r=e.ownerDocument.getElementById(n);return!!r&&ht(r)}async function mt(e,t,n){const r=e.hasAttribute("aria-expanded")||e.hasAttribute("aria-controls");if(pt(e))return{ok:!0};if(r){if(lt(e),await(o=()=>pt(e),a=300,new Promise(e=>{const t=Date.now(),n=()=>o()?e(!0):Date.now()-t>=a?e(!1):void setTimeout(n,30);n()})))return{ok:!0}}else if(await function(e,t,n=300){const r=e.defaultView,o=r?.MutationObserver??globalThis.MutationObserver;return o?new Promise(r=>{const a=new o(e=>{e.some(e=>e.addedNodes.length>0&&!it(e.target)&&Array.from(e.addedNodes).some(e=>!it(e)))&&(a.disconnect(),clearTimeout(s),r(!0))});a.observe(e.body??e.documentElement,{subtree:!0,childList:!0}),t();const s=setTimeout(()=>{a.disconnect(),r(!1)},n)}):(t(),Promise.resolve(!0))}(e.ownerDocument,()=>lt(e)))return{ok:!0};var o,a;return n?.aborted?{ok:!1,error:"aborted"}:ut(e,void 0,t)}const gt=/\b(search|query|filter|find|recherche|rechercher)\b/i;async function ft(e,t,n,r,o){try{if(o?.aborted)return{ok:!1,error:"aborted"};if("snapshot"===e.type)return{ok:!0};if("unsupported"===e.type)return{ok:!1,error:`unsupported_action: ${e.requested}`.slice(0,500)};if("navigate"===e.type){if(!n)return{ok:!1,error:"navigation_unavailable"};const t=st(e.path,at(r));return t?(n(t),{ok:!0}):{ok:!1,error:"external_path"}}const a=t.get(e.ref);return a&&a.isConnected?ht(a)?function(e){if(e.hasAttribute("disabled"))return!0;if("true"===e.getAttribute("aria-disabled"))return!0;if(e.matches?.(":disabled"))return!0;if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(a)?{ok:!1,error:"disabled"}:a.matches?.('input[type="file"]')?{ok:!1,error:"opens_file_dialog"}:"open"===e.type?await mt(a,at(r??a.ownerDocument),o):"click"===e.type?ut(a,n,at(r??a.ownerDocument)):function(e){return e.matches?.('textarea, [contenteditable="true"], input:not([type]), input[type="text"], input[type="search"], input[type="email"], input[type="url"], input[type="tel"], input[type="number"]')??!1}(a)?function(e){return!0===e.readOnly||"true"===e.getAttribute("aria-readonly")}(a)?{ok:!1,error:"read_only"}:function(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>ct.test(e))}(a)?{ok:!1,error:"secret_field"}:(a.focus?.(),function(e,t){const n=e.ownerDocument.defaultView;if(n&&(e instanceof n.HTMLInputElement||e instanceof n.HTMLTextAreaElement)){const r=e instanceof n.HTMLInputElement?n.HTMLInputElement.prototype:n.HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(r,"value")?.set?.call(e,t)}else e.textContent=t;e.dispatchEvent(new(n?.Event??Event)("input",{bubbles:!0})),e.dispatchEvent(new(n?.Event??Event)("change",{bubbles:!0}))}(a,e.text),function(e){if("searchbox"===e.getAttribute("role"))return!0;if("search"===e.type)return!0;if(null!==e.closest('[role="search"]'))return!0;if(!["name","id","placeholder","aria-label","title"].some(t=>gt.test(e.getAttribute(t)??"")))return!1;const t=e.form;return!t||1===t.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]), select, textarea, [contenteditable="true"]').length}(a)&&function(e){const t=e.ownerDocument.defaultView,n=t?.KeyboardEvent??KeyboardEvent,r={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:!0,cancelable:!0},o=new n("keydown",r);e.dispatchEvent(o),e.dispatchEvent(new n("keyup",r));const a=e.form;a&&!o.defaultPrevented&&dt(e.ownerDocument,["submit"],()=>a.requestSubmit?.())}(a),{ok:!0}):{ok:!1,error:"not_a_text_field"}:{ok:!1,error:"not_visible"}:{ok:!1,error:"unknown_ref"}}catch(e){return{ok:!1,error:`failed: ${e instanceof Error?e.message:String(e)}`.slice(0,500)}}}const vt="[truncated]",wt=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","checkbox","radio","switch","textbox","searchbox","combobox","treeitem"]);function bt(e){if("select"===e.tagName.toLowerCase())return!1;for(const t of Array.from(e.querySelectorAll('a[href], button, summary, select, textarea, input, [contenteditable="true"], [role]')))if(yt(t))return!0;return!1}function yt(e){const t=e.getAttribute("role");if(t&&wt.has(t))return t;const n=e.tagName.toLowerCase();if("a"===n&&e.hasAttribute("href"))return"link";if("button"===n||"summary"===n)return"button";if("select"===n)return"combobox";if("textarea"===n)return"textbox";if("input"===n){const t=(e.getAttribute("type")||"text").toLowerCase();return"hidden"===t?null:["button","submit","reset","image"].includes(t)?"button":"checkbox"===t||"radio"===t?t:"search"===t?"searchbox":"file"===t?"button":"textbox"}return"true"===e.getAttribute("contenteditable")?"textbox":null}function xt(e){const t=/^h([1-6])$/i.exec(e.tagName);return t?Number(t[1]):null}function kt(e){const t=e.ownerDocument.defaultView;let n="";for(const r of Array.from(e.childNodes))if(3===r.nodeType)n+=r.textContent??"";else if(1===r.nodeType){if(Mt(r)||Et(r))continue;const e=t?.getComputedStyle(r).display??"";n+=""===e||"inline"===e||"contents"===e?kt(r):` ${kt(r)} `}return n}function Ct(e){return(e??"").replace(/\s+/g," ").trim()}const Nt=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","treeitem","switch"]);function St(e,t){const n=e.ownerDocument,r=e.getAttribute("aria-labelledby");if(r){const e=Ct(r.split(/\s+/).map(e=>n.getElementById(e)?.textContent??"").join(" "));if(e)return e}const o=Ct(e.getAttribute("aria-label"));if(o)return o;const a=e.getAttribute("id"),s=a&&Array.from(n.getElementsByTagName("label")).find(e=>e.htmlFor===a)||e.closest("label");if(s){const e=Ct(Array.from(s.childNodes).filter(e=>3===e.nodeType).map(e=>e.textContent).join(" "));if(e||Ct(s.textContent))return e||Ct(s.textContent)}const i=e.tagName.toLowerCase(),c=(e.getAttribute("type")||"").toLowerCase();if("input"===i&&["submit","reset","button"].includes(c)){const t=Ct(e.getAttribute("value"));if(t)return t;if("button"!==c)return"submit"===c?"Submit":"Reset"}const l=Ct(e.getAttribute("alt"))||Ct(e.querySelector("img[alt]")?.getAttribute("alt"));if(l)return l;const d=Et(e)?"":Ct(kt(e));if(Nt.has(t)&&d)return d;const u=Ct(e.getAttribute("placeholder"));if(u)return u;const h=Ct(e.getAttribute("title"));return h||d}function Tt(e){return JSON.stringify(e.slice(0,80))}function At(e){const t=[];(e.hasAttribute("disabled")||function(e){if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(e)||"true"===e.getAttribute("aria-disabled"))&&t.push("disabled"),"true"===e.getAttribute("aria-selected")&&t.push("selected"),(e.checked||"true"===e.getAttribute("aria-checked"))&&t.push("checked"),"true"===e.getAttribute("aria-expanded")?t.push("expanded"):"false"!==(e.getAttribute("aria-haspopup")??"false")?t.push("menu"):"false"===e.getAttribute("aria-expanded")&&t.push("collapsed"),"true"===e.getAttribute("aria-pressed")&&t.push("pressed");const n=e.getAttribute("aria-current");return n&&"false"!==n&&t.push("current"),t}const It=/^(current-password|new-password|one-time-code|cc-)/;function Et(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>It.test(e))}function zt(e,t){if(!["textbox","searchbox","combobox"].includes(t))return null;if(Et(e))return null;const n="value"in e?String(e.value??""):Ct(kt(e));return n||null}function Rt(e){const t=e.getAttribute("href"),n=e.ownerDocument.defaultView?.location;if(!t||!n)return"";try{const e=new URL(t,n.href);return e.origin===n.origin?` -> ${e.pathname}${e.search}`:""}catch{return""}}function Mt(e){if(e.classList.contains("filigran-chatbot"))return!0;const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!0}if(e.hidden||e.hasAttribute("inert"))return!0;if("true"===e.getAttribute("aria-hidden"))return!0;const n=e.ownerDocument.defaultView?.getComputedStyle(e);return"none"===n?.display||"hidden"===n?.visibility}const Dt="filigranChatConversationId",Lt="filigranChatLegacyChatId",_t="filigranChatAgentSlug",Pt="filigranChatSidebarWidth",jt="filigran-chat-collapsed-workspaces",$t="filigranChatDraft:",Ut="filigranChatDraftRefs:";function Ot(e,t){return e?`${e}:${t}`:t}function Wt(e){if("undefined"==typeof window)return null;try{return"local"===e?window.localStorage:window.sessionStorage}catch{return null}}function qt(e,t){try{return Wt(e)?.getItem(t)??null}catch{return null}}function Ft(e,t,n){try{const r=Wt(e);if(!r)return;n?r.setItem(t,n):r.removeItem(t)}catch{}}class Ht extends Error{constructor(){super("the event stream fell silent"),this.name="SseStreamSilentError"}}async function Bt(e,t,{idleTimeoutMs:n}={}){const r=e.getReader(),o=new TextDecoder;let a="",s=null,i=!1,c=!1,l=null;const d=()=>{null!==l&&clearTimeout(l),l=null;const e="function"==typeof n?n():n;i&&void 0!==e&&(l=setTimeout(()=>{c=!0,r.cancel().catch(()=>{})},e))},u=e=>{const r=e.replace(/\r$/,"");if(r.startsWith(":")){const e=Date.now();null===s&&(s=e);const t="function"==typeof n?n():n;void 0!==t&&e-s>=t/3&&(i=!0)}if(!r.startsWith("data:"))return!0;const o=r.startsWith("data: ")?r.slice(6):r.slice(5);let a;try{a=JSON.parse(o)}catch{return!0}return!(a&&"object"==typeof a&&!Array.isArray(a))||!1!==t(a)};try{for(;;){const{done:e,value:t}=await r.read();if(c)throw new Ht;if(e)break;a+=o.decode(t,{stream:!0});const n=a.split("\n");a=n.pop()??"";for(const e of n)if(!u(e))return void await r.cancel().catch(()=>{});d()}a+=o.decode(),a&&u(a)}finally{null!==l&&clearTimeout(l),r.releaseLock()}}const Vt=e=>e.some(e=>"error"===e.uploadStatus),Kt=new Map([["md",["text/markdown"]],["markdown",["text/markdown"]],["yaml",["application/yaml","application/x-yaml","text/yaml"]],["yml",["application/yaml","application/x-yaml","text/yaml"]],["csv",["text/csv"]],["tsv",["text/tab-separated-values"]],["txt",["text/plain"]],["log",["text/plain"]],["json",["application/json"]]]);function Gt(e,t){const n=(e??"").split(",").map(e=>e.trim().toLowerCase()).filter(Boolean);if(0===n.length)return!0;const r=t.name.toLowerCase();if(n.some(e=>e.startsWith(".")&&r.endsWith(e)))return!0;const o=r.lastIndexOf("."),a=t.type?[t.type.toLowerCase()]:o>=0?Kt.get(r.slice(o+1))??[]:[];return n.some(e=>!e.startsWith(".")&&a.some(t=>e.endsWith("/*")?t.startsWith(e.slice(0,-1)):t===e))}function Yt(e,t){try{return e.getData(t)??""}catch{return""}}const Xt=/<(head|style|script|title|template|xml)\b/iy,Jt=/&(?:nbsp|#160|#xa0);/iy,Qt=/\s/;function Zt(e,t){for(let n=t+1;n<e.length;n+=1){const t=e[n];if(">"===t)return n+1;if('"'===t||"'"===t){const r=e.indexOf(t,n+1);if(r<0)return-1;n=r}}return-1}function en(e){if(!e)return[];const t=Array.from(e.files??[]);if(0===t.length)return t;return t.every(e=>e.type.startsWith("image/"))&&/\S/.test(Yt(e,"text/plain"))&&function(e){const t=new Set;let n=0;for(;n<e.length;){const r=e[n];if("<"===r){if(e.startsWith("\x3c!--",n)){const t=e.indexOf("--\x3e",n+4);if(t>=0){n=t+3;continue}}Xt.lastIndex=n;const r=Xt.exec(e)?.[1].toLowerCase();if(r&&!t.has(r)){const o=new RegExp(`</${r}\\s*>`,"gi");if(o.lastIndex=n,o.exec(e)){n=o.lastIndex;continue}t.add(r)}const o=Zt(e,n);if(o<0)return!0;n=o;continue}if("&"===r&&(Jt.lastIndex=n,Jt.test(e)))n=Jt.lastIndex;else{if(!Qt.test(r))return!0;n+=1}}return!1}(Yt(e,"text/html"))?[]:t}function tn(e){if(e.slug&&/^[\w-]+$/.test(e.slug))return e.slug;return e.name.toLowerCase().replace(/[^\w-]+/g,"-").replace(/^-+|-+$/g,"")||null}function nn(e,t){const n=[];for(const r of fe(t))for(const t of e)t.key.toLowerCase()!==r||n.includes(t.agentId)||n.push(t.agentId);return n}const rn=r({fetch:(e,t)=>globalThis.fetch(e,t),sessionEnded:()=>{}}),on=rn.Provider;function an(){return o(rn).fetch}const sn=(e,t)=>Ot(e,`${$t}${t??"new"}`),cn=(e,t)=>Ot(e,`${Ut}${t??"new"}`);function ln(e,t){try{const n=JSON.parse(qt("session",cn(e,t))??"[]");return Array.isArray(n)?n.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.conversationId&&"string"==typeof e.key&&"string"==typeof e.title):[]}catch{return[]}}const dn=(e,t,n,r)=>JSON.stringify([sn(e,t),n,r]);function un(e,t,n,r,o){const a=dn(t,n,r,o);a!==e.current&&(e.current=a,Ft("session",sn(t,n),r),Ft("session",cn(t,n),o.length>0?JSON.stringify(o):null))}function hn(e,t){const n=qt("session",sn(e,t))??"";return{text:n,refs:ve(ln(e,t),n)}}const pn=9e5,mn=pn,gn=new Set(["wait_status","tool_progress"]),fn=new Set(["tool_progress","tool_heartbeat","wait_status","thinking_text"]),vn=new Set(["thinking","analyzing","llm_step","tool_start","composing","streaming","stream_retract","mention_answering","transferring"]);const wn=new Set(["status","stream","done","approval_required","error","cancelled"]),bn=new Set(["mentioned_agent_ids","content","conversation_id","agent_slug","supports_tool_approval","supports_page_actions","supports_artifacts","referenced_conversation_ids","file_ids","context"]);function yn(e,t,n,r){return{...e,content:n,timestamp:r,toolNames:t.toolNames,toolCallCount:t.toolCallCount,iterations:t.iterations,attachments:t.attachments,artifacts:t.artifacts,reasoning:t.reasoning,toolCallTrace:t.toolCallTrace,transferChain:t.transferChain,isTruncated:t.isTruncated,agentName:t.answeredBy?.agentName??e.agentName,answeredBy:t.answeredBy,mentionFailed:t.mentionFailed,serverId:t.messageId??e.serverId,raw:t.raw??e.raw}}const xn=["toolNames","toolCallCount","iterations","attachments","artifacts","reasoning","toolCallTrace","transferChain","isTruncated","interrupted","agentName","answeredBy","mentionFailed","feedback"],kn=Symbol("sentText");function Cn(e,t){return t===e.content?e:{...e,[kn]:t}}function Nn(e){return e[kn]??e.content}const Sn=e=>`${e.role}\0${"user"===e.role?Nn(e):e.content}`,Tn=e=>`${e.role}\0${e.content}`;function An(e,t){const n={...e,serverId:t.serverId??e.serverId,raw:t.raw??e.raw};if("assistant"!==e.role)return n;const r=n;for(const e of xn)void 0!==t[e]&&(r[e]=t[e]);return n}function In(e,t,n){const r=null===n?-1:e.findIndex(e=>e.id===n);return r<0?[...e,t]:[...e.slice(0,r),t,...e.slice(r)]}const En=(e,t)=>[e,t].filter(Boolean).join("\n\n"),zn=(e,t)=>void 0!==e.displayText||void 0!==t.displayText?En(e.displayText??e.text,t.displayText??t.text):void 0;function Rn(e,t){const n=new Set(e.refs.map(e=>e.conversationId)),r=new Set(e.mentions.map(e=>e.agentId));return{text:En(e.text,t.text),draft:En(e.draft,t.draft),files:[...e.files,...t.files],refs:[...e.refs,...t.refs.filter(e=>!n.has(e.conversationId))],mentions:[...e.mentions,...t.mentions.filter(e=>!r.has(e.agentId))],extras:e.extras||t.extras?{...e.extras,...t.extras}:void 0,displayText:zn(e,t)}}const Mn={text:"",draft:"",files:[],refs:[],mentions:[]};function Dn(e){return{...e.reduce(Rn,Mn),parts:e}}function Ln(e,t){return Dn([...e?.parts??[],t])}function _n(e){for(const t of e)B(t.onNotSent)}function Pn(e,t,n){if(!1===t)return null;const r=t&&"object"==typeof t?t:void 0,o=("string"==typeof r?.text?r.text:e).trim(),a="string"==typeof r?.displayText?r.displayText.trim():"",s="string"==typeof n?n.trim():"";return{text:o,displayText:a||s||o,extras:r?.extras}}function jn(e){return"error"===e.action||"cancelled"===e.action||"done"===e.action&&!e.intermediate?e:null}function $n(e){return("error"===e.action||"cancelled"===e.action)&&!!e.provisional}function Un(e){const t=B(e);return t&&"object"==typeof t?t:{}}class On extends Error{detail;constructor(e,t){super(`File upload failed: ${e}`),this.detail=t}}const Wn=52428800;function qn(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t].serverId;if(n)return n}return null}function Fn(e,t){const n=null===t?0:e.findIndex(e=>e.serverId===t)+1;return null!==t&&0===n?"stopped":e.slice(n).some(e=>"assistant"===e.role)?"answered":"stopped"}function Hn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:r,agentPending:o=!1,requestHeaders:d,pageContext:u,onRelativeLinkClick:h,t:p,maxFileCount:m=10,maxTotalSize:g=52428800,maxFileSize:f,acceptFileTypes:v,onFileRefused:w,storageKeyPrefix:b,controlledConversationId:y,onConversationIdChange:x,getRequestExtras:k,onStreamEvent:C,onSessionEnded:N,onConversationTitle:S,onMessageSent:T,historySettledFor:A=null,steerAttachments:E=!1,holdSends:z=!1,agentMentionsEnabled:M=!1,onBeforeSend:D,onHeldSendSettled:L}){const _=an(),P="legacy"===n,[j,$]=a([]),[U,O]=a(!1),[W,q]=a(null),[F,H]=a(null),[V,K]=a(void 0),[G,Y]=a(!1),X=s(!1),J=(e,t)=>{K(e),X.current=t,Y(t)},Q=i(()=>F&&V?{...F,answeringAgentName:V}:F,[F,V]),Z=void 0!==y,ee=Ot(b,Dt),te=Ot(b,Lt),[ne,oe]=a(()=>Z?y??null:qt("local",ee)),[ae]=a(()=>hn(b,ne)),[se,ie]=a(ae.text),[ce,le]=a(ae.refs),de=s(null);de.current??=dn(b,ne,ae.text,ae.refs);const[ue,he]=a([]),[pe,me]=a([]),[ge,be]=a(null),[xe,ke]=a(null),[Ce,Ne]=a(null),[Se,Te]=a(!1),[Ae,Ie]=a(null),[Ee,ze]=a(!1),[Re,Me]=a(0),[Pe,je]=a(0),[$e,Ue]=a(()=>qt("local",te)),Oe=s(!1),We=s(null),qe=s(null),Fe=s(null),He=s(!1),Be=s(null),Ke=s(null),Ge=s(null),Ye=s(null),Xe=s(null),Ze=s(!1),[et,at]=a(null),st=s(et);st.current=et;const[ct,lt]=a(null),[dt,ut]=a(null),ht=s(!1),pt=s(new Map),mt=s(null),[gt,wt]=a(!1),Nt=s(null),It=s(!1),Et=s("off"),_t=s(0),Pt=s(null),jt=s(null),$t=s(null),Ut=s(null),[Wt,Ht]=a(!1),Kt=e=>{const t=Ut.current?.readBack;t&&e!==Ut.current&&window.clearTimeout(t.timer),Ut.current=e,Ht(null!==e)},Yt=s(j);Yt.current=j;const Xt=s(0),[Jt,Qt]=a(()=>_e()),Zt=s(null),tn=s(null),rn=s(!1),on=s(0),sn=s(null),cn=s(null),ln=s(null),xn=()=>{null!==Zt.current&&window.clearTimeout(Zt.current),Zt.current=null,tn.current=null,rn.current=!1,ln.current&&window.clearTimeout(ln.current.timer),ln.current=null;const e=cn.current;cn.current=null,null!==e&&$(t=>t.filter(t=>t.id!==e||t.content))},kn=e=>{mt.current&&window.clearTimeout(mt.current.timer);const t={timer:0,relayed:e};return t.timer=window.setTimeout(()=>En(t),5e3),mt.current=t,wt(!0),t},En=e=>{const t=mt.current;!t||e&&e!==t||(window.clearTimeout(t.timer),mt.current=null,wt(!1))},zn=()=>{mt.current?.relayed&&En()},Rn=s(k);Rn.current=k;const Mn=s(C);Mn.current=C;const Hn=s(N);Hn.current=N;const Bn=s(S);Bn.current=S;const Vn=s(T);Vn.current=T;const Kn=s(D);Kn.current=D;const Gn=s(L);Gn.current=L;const Yn=s(ne),Xn=s(U);Xn.current=U;const Jn=e=>{Xn.current&&q(e),Xn.current=!1,O(!1),J(void 0,!1),ht.current||lt(null)},Qn=s(u);Qn.current=u;const Zn=s(new Map),er=s(h);er.current=h;const tr=s(d);tr.current=d;const nr=s(null),rr=s(!1),or=s(null),ar=s(0),[sr]=a(rt),ir=s(null),[cr,lr]=a(null),dr=s(new AbortController);c(()=>()=>{dr.current.abort(),dr.current=new AbortController},[]);const ur={maxFileCount:Number.isFinite(m)&&m>0?Math.floor(m):10,maxTotalSize:g>0?g:Wn,maxFileSize:void 0!==f&&Number.isFinite(f)&&f>0?f:1/0,accept:v},[hr,pr]=a(0);c(()=>{le(e=>ve(e,se)),he(e=>function(e,t){if(0===e.length)return e;const n=new Set(fe(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}(e,se))},[se]);const mr=l(e=>{he(t=>{return r=e,(n=t).some(e=>e.agentId===r.agentId)?n:[...n,r];var n,r})},[]),gr=l(e=>{le(t=>{return r=e,(n=t).some(e=>e.conversationId===r.conversationId)?n:[...n,r];var n,r})},[]),fr=({draft:e,files:t,refs:n,mentions:r},{before:o})=>{e&&ie(t=>t?o?`${e}\n${t}`:`${t}\n\n${e}`:e),t.length>0&&me(e=>o?[...t,...e]:[...e,...t]),n.length>0&&le(e=>{const t=n.filter(t=>!e.some(e=>e.conversationId===t.conversationId));return o?[...t,...e]:[...e,...t]}),r.length>0&&he(e=>{const t=r.filter(t=>!e.some(e=>e.agentId===t.agentId));return o?[...t,...e]:[...e,...t]})},vr=()=>P||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,wr=()=>re(e,t,n,"approve"),br=s(wr);br.current=wr;const yr=async e=>{const t=_r(e);if(!t)return null;try{const e=await _(t,{headers:{...d??{}}});if(!e.ok)return null;const n=await e.json();return{proposals:Ve(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},xr=l(()=>{Oe.current=!1,Xt.current+=1,Me(Xt.current)},[]),kr=()=>{if(null===tn.current)return;const e=qn(Yt.current);if(xn(),!$r())return void ao("stopped");xr();const t=window.setTimeout(()=>{ln.current?.timer===t&&(ln.current=null,ao("stopped"))},1e4);ln.current={from:Xt.current,shownUpTo:e,timer:t}},Cr=s(kr);Cr.current=kr;const Nr=()=>{null!==Zt.current&&window.clearTimeout(Zt.current),rn.current=!1,Zt.current=window.setTimeout(()=>{Zt.current=null,Ke.current||Cr.current()},Math.max(0,on.current-Date.now()))},Sr=()=>{null===tn.current||Ke.current||rn.current||(rn.current=!0,null!==Zt.current&&window.clearTimeout(Zt.current),Zt.current=window.setTimeout(()=>{Zt.current=null,Ke.current||Cr.current()},5e3))},Tr=s(Sr);Tr.current=Sr;const Ar=()=>{null!==tn.current&&!Ke.current&&rn.current&&Nr()},Ir=s(Ar);Ir.current=Ar;const Er=()=>P||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,zr=()=>re(e,t,n,"cancel"),Rr=()=>re(e,t,n,"skipWait"),Mr=re(e,t,n,"events"),Dr=!!Mr,Lr=re(e,t,n,"pendingApprovals"),_r=e=>Lr?`${Lr}/${encodeURIComponent(e)}/pending-approvals`:null,Pr=()=>Dr?{"X-Chat-Client-Id":Jt}:{},jr=(e,t,n)=>_(e,{method:"POST",headers:{"Content-Type":"application/json",...tr.current??{},...Pr()},body:JSON.stringify({conversation_id:t,...n})}),$r=()=>P||t?.singleEndpoint||null===t?.sessions?null:`${e}${t?.sessions??"/chat/sessions"}`,Ur=s(x);Ur.current=x;const Or=l((e,{notify:t=!0}={})=>{const n=Yn.current!==e;Yn.current=e,oe(e),Z||Ft("local",ee,e),n&&t&&Ur.current?.(e)},[Z,ee]),Wr=s(r);Wr.current=r;const qr=s(o);qr.current=o;const Fr=s([]),Hr=s(null),[Br,Vr]=a(!1);c(()=>{if(!o)for(const e of Fr.current.splice(0))e()},[o]);const Kr=e=>new Promise((t,n)=>{const r=()=>t(Wr.current);if(!qr.current)return r();const o=()=>{Fr.current=Fr.current.filter(e=>e!==r),n(new DOMException("Aborted","AbortError"))};if(e.aborted)return o();e.addEventListener("abort",o,{once:!0}),Fr.current.push(r)}),Gr=async()=>{if(Yn.current)return Yn.current;if(sr.pending)return sr.pending;const e=$r();return e?sr.run(async(t,n)=>{const r=await Kr(n);if(!t())return null;const o=ir.current,a=await _(e,{method:"POST",headers:{"Content-Type":"application/json",...d??{}},body:JSON.stringify(o?{agent_slug:r,workspace_id:o}:{agent_slug:r}),signal:n});if(!a.ok||!t())return null;const s=await a.json();if(!t())return null;const i=s?.conversation_id??null;return i&&(Oe.current=!0,Or(i),ir.current=null,lr(null)),i}):null},Yr=async(e,t,n)=>{const r=Er(),o=new FormData;o.append("conversation_id",t),o.append("file",e,e.name);const a=d?Object.fromEntries(Object.entries(d).filter(([e])=>"content-type"!==e.toLowerCase())):void 0,s=await _(r,{method:"POST",headers:a,body:o,signal:n});if(!s.ok)throw new On(s.status,await De(s));const i=(await s.json()).file_ids??[];if(0===i.length)throw new Error("No file_id returned");return i[0]},Xr=e=>{if(!e||0===e.length||!Er())return;const t=Array.from(e),n=dr.current.signal,r=new Map(t.map(e=>[e,_e()]));let o=[],a=[],s=!1;me(e=>{if(({accepted:o,refused:a}=function(e,t,n){const r=[],o=[];let a=e.length,s=n.maxTotalSize-e.reduce((e,t)=>e+t.size,0);for(const e of t){const t=Gt(n.accept,e)?e.size>n.maxFileSize?"file-size":a>=n.maxFileCount?"file-count":e.size>s?"total-size":null:"file-type";t?o.push({file:e,reason:t}):(r.push(e),a+=1,s-=e.size)}return{accepted:r,refused:o}}(e,t,ur)),s=!0,0===o.length)return e;const n=o.map(e=>({name:e.name,type:e.type,size:e.size,rawFile:e,uploadStatus:"pending",fileId:r.get(e)}));return[...e,...n]});const i=()=>{if(n.aborted)return;if(!s)return void setTimeout(i,0);ut(a.map(({file:e,reason:t})=>function(e,t,n,r){switch(n){case"file-type":return I(e,"{name} was not attached: this type of file is not accepted.",{name:t});case"file-size":return I(e,"{name} was not attached: a file may be at most {size}.",{name:t,size:R(r.maxFileSize)});case"file-count":return I(e,"{name} was not attached: a message holds at most {count} files.",{name:t,count:r.maxFileCount});case"total-size":return I(e,"{name} was not attached: the files of a message may add up to at most {size}.",{name:t,size:R(r.maxTotalSize)})}}(p,e.name,t,ur)).join(" ")||null);for(const{file:e,reason:t}of a)B(w,e,t);const e=(e,t)=>me(n=>n.map(n=>n.fileId===e?{...n,uploadStatus:"error",uploadError:t instanceof On?t.detail??void 0:void 0}:n));for(const t of o){const o=r.get(t);(async()=>{try{const r=await Gr();if(!r)return void e(o);const a=await Yr(t,r,n);me(e=>e.map(e=>e.fileId===o?{...e,fileId:a,uploadStatus:"done"}:e))}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)return;e(o,t)}})()}};setTimeout(i,0)},Jr=async(e,t,n)=>{const r=br.current(),o=n??Yn.current;if(!r||!o||"undefined"==typeof document)return;const a=qe.current?.signal,s=async t=>{try{await _(r,{method:"POST",headers:{"Content-Type":"application/json",...tr.current??{},...Pr()},body:JSON.stringify({conversation_id:o,page_action:{action_id:e,ok:!1,error:t,url:"",title:"",snapshot:""}})})}catch{}};if(a?.aborted)return s("panel_closed");if(!ot(r,er.current))return s("page_actions_not_supported");H(e=>e?{...e,status:"acting_on_page"}:{status:"acting_on_page"});try{const n=await ft(t,Zn.current,er.current,document,a);if(a?.aborted)return s("panel_closed");if("snapshot"!==t.type&&await function(e,{quietMs:t=300,maxMs:n=3e3,signal:r}={}){return new Promise(o=>{if(r?.aborted)return o();const a=e.defaultView,s=a?.MutationObserver??globalThis.MutationObserver;let i;const c=()=>{clearTimeout(i),clearTimeout(d),l?.disconnect(),r?.removeEventListener("abort",c),o()},l=s?new s(e=>{e.some(e=>!it(e.target))&&(clearTimeout(i),i=setTimeout(c,t))}):null;l?.observe(e.body??e.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),i=setTimeout(c,t);const d=setTimeout(c,n);r?.addEventListener("abort",c)})}(document,{signal:a}),a?.aborted)return s("panel_closed");let i={text:"",url:"",title:""},c=null;try{const e=function(e,t=2e4){const n=e.defaultView?.location,r=(n?`${n.pathname}${n.search}`:"").slice(0,500),o=Ct(e.title).slice(0,80),a=Math.max(0,t-12);let s=!1,i=`# ${o} — ${r}`;i.length>a&&(i=i.slice(0,a),s=!0);const c=[i];let l=i.length;const d=new Map,u=e=>{for(const t of Array.from(e.children)){if(Mt(t))continue;const e=yt(t),n=xt(t);let r=null;if(e){const n=`e${d.size+1}`,o=zt(t,e),i=At(t);if(r=`[${n}] ${e} ${Tt(St(t,e))}${i.length?` (${i.join(", ")})`:""}${o?` = ${Tt(o)}`:""}${Rt(t)}`,l+r.length+1>a)return s=!0,!1;d.set(n,t)}else if(n&&(r=`heading ${Tt(Ct(kt(t)))} (level ${n})`,l+r.length+1>a))return s=!0,!1;if(r&&(c.push(r),l+=r.length+1),(!e||bt(t))&&!u(t))return!1}return!0};return e.body&&!s&&u(e.body),s&&c.push(vt),{text:c.join("\n"),url:r,title:o,refs:d}}(document);Zn.current=e.refs,i={text:e.text,url:e.url,title:e.title}}catch(e){Zn.current=new Map,c=`${e instanceof Error?e.message:String(e)}`.slice(0,500)}await _(r,{method:"POST",headers:{"Content-Type":"application/json",...tr.current??{},...Pr()},signal:a,body:JSON.stringify({conversation_id:o,page_action:{action_id:e,ok:n.ok,error:n.error??(null===c?null:`snapshot_failed: ${c}`),url:i.url,title:i.title,snapshot:i.text}})})}catch{}finally{a?.aborted||H(e=>"acting_on_page"===e?.status?{...e,status:"thinking"}:e)}},Qr=(e,t)=>{let n=e;const r=[e];let o="",a=!1,s=!1,i=null;const c=new Map,l=new Set,d=()=>{c.clear(),l.clear()};let u=!0;const h=function(e){let t=!1,n="",r=null,o=!1;const a=()=>{null!==r&&cancelAnimationFrame(r),r=null},s=()=>{if(a(),!t&&!n)return;const r=t,o=n;t=!1,n="",e(r,o)},i=()=>{null===r&&("function"==typeof requestAnimationFrame?r=requestAnimationFrame(()=>{r=null,s()}):s())};return{text:()=>{o||(t=!0,i())},thinking:e=>{o||(n+=e,i())},flush:s,close:()=>{o=!0,a(),t=!1,n=""}}}((e,t)=>{if(e){const e=n,t=o;H(e=>({status:"streaming",thinkingContent:e?.thinkingContent})),$(n=>n.map(n=>n.id===e?{...n,content:t}:n))}t&&H(e=>({...e,status:e?.status??"thinking",thinkingContent:(e?.thinkingContent??"")+t}))}),m=()=>{if(!a)return;h.flush(),a=!1,s=!1,o="",d(),n=_e(),r.push(n);const e=n;$(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),H({status:"thinking"})};return{ctx:{hasUsedTools:!1,activeNodeId:""},deltas:h,apply:e=>{switch(_t.current+=1,e.action){case"status":return(e=>{m();const t=n;if(e.contextUsage&&ke(e.contextUsage),"thinking_text"===e.status)return void h.thinking(e.thinkingContent??"");h.flush();const r="number"==typeof e.elapsedS?Date.now()-1e3*e.elapsedS:void 0;if((e.resumed||vn.has(e.status))&&(d(),u=!0===e.resumed||"tool_start"===e.status),"mention_answering"===e.status&&J(e.agentName,!0),e.resumed)o="",$(e=>e.map(e=>e.id===t?{...e,content:""}:e)),H({status:"thinking",elapsedS:e.elapsedS,elapsedStartMs:r});else if("stream_retract"===e.status)o="",$(e=>e.map(e=>e.id===t?{...e,content:""}:e)),H(e=>({status:"analyzing",thinkingContent:e?.thinkingContent}));else if("tool_heartbeat"===e.status)H(t=>t?{...t,elapsedS:e.elapsedS,elapsedStartMs:r}:{status:"tool_start",tools:e.tools,elapsedS:e.elapsedS,elapsedStartMs:r});else if("consult_progress"===e.status){const t=e.consult;if(!t||!u)return;const{consultId:n,agentId:r,agentName:o,status:a}=t;if(t.answering)c.delete(n),l.add(n);else if(a&&!fn.has(a))l.delete(n),c.delete(n),c.set(n,{agentId:r,agentName:o,status:a,tools:t.tools});else if(!c.has(n)){if(l.has(n))return;c.set(n,{agentId:r,agentName:o,status:"thinking"})}let s={agentName:o,status:a??"thinking",answering:t.answering};const i=new Set;for(const e of c.values())s=e,i.add(e.agentId);const d={agentName:s.agentName,status:s.status,tools:s.tools,answering:s.answering,count:Math.max(c.size,1),agents:Math.max(i.size,1)};H(e=>{return"wait_start"===e?.status||"consulting"===e?.status&&(t=e.consult,n=d,t&&t.agentName===n.agentName&&t.status===n.status&&t.count===n.count&&t.agents===n.agents&&t.answering===n.answering&&(t.tools??[]).join("\n")===(n.tools??[]).join("\n"))?e:{status:"consulting",consult:d,thinkingContent:e?.thinkingContent,elapsedS:e?.elapsedS,elapsedStartMs:e?.elapsedStartMs};var t,n})}else"wait_start"===e.status?H(t=>({status:"wait_start",thinkingContent:t?.thinkingContent,waitSeconds:e.waitSeconds,waitReason:e.waitReason,waitStartMs:Date.now()})):"wait_continued"===e.status?H(e=>"wait_start"===e?.status?{status:"analyzing",thinkingContent:e.thinkingContent}:e):H(t=>"wait_start"===t?.status&&gn.has(e.status)?t:{status:e.status,tools:e.tools,thinkingContent:t?.thinkingContent,...e.phase?{phase:e.phase}:{},...e.iteration?{iteration:e.iteration}:{},...e.agentName?{agentName:e.agentName}:{}})})(e),"continue";case"stream":return m(),o+=e.content,h.text(),"continue";case"done":return(e=>{h.flush(),a=!0,e.intermediate||(s=!0),Ne(null),Ie(null),eo(e,t);const r=n,i=e.content||o,c=new Date;to(r,e.messageId,t=>yn(t,e,i,c))})(e),t&&!e.intermediate?"end":"continue";case"approval_required":return h.flush(),nr.current=e.conversationId??Yn.current,rr.current=!1,Ie(null),Ne(e.proposals),H(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"}),"continue";case"error":{m(),h.flush();const t=n;return i="error",$(n=>n.map(n=>n.id===t?{...n,content:e.content||p("Sorry, an error occurred. Please try again.")}:n)),"end"}case"cancelled":{h.flush(),i="cancelled";const e=n;return $(t=>t.map(t=>t.id===e?{...t,stopped:!0}:t)),"end"}case"session_ended":{h.flush(),i="session";const e=n;return $(t=>t.filter(t=>!(t.id===e&&!t.content))),"end"}default:return"continue"}},currentAssistantId:()=>n,openAnswerId:()=>a?null:n,accumulated:()=>o,doneReceived:()=>a,segmentIds:()=>r,ended:()=>i,outcome:()=>"error"===i?"failed":null===i&&s?"answered":"stopped"}},Zr=l(()=>be(null),[]),eo=(e,t)=>{e.conversationId&&!t&&Or(e.conversationId),e.contextUsage&&ke(e.contextUsage),e.transferAgentId&&e.transferAgentName&&be({id:e.transferAgentId,name:e.transferAgentName})},to=(e,t,n)=>{$(r=>t&&r.some(n=>n.id!==e&&n.serverId===t)?r.filter(t=>t.id!==e):r.map(t=>t.id===e?n(t):t))},no=(e,t,n)=>{const r=jn(t),o=r?.messageId;if(!r||!o)return!1;"done"!==r.action||Xn.current||eo(r,n);const a=new Date;return to(e,o,e=>"done"===r.action?yn(e,r,r.content||e.content,a):{...e,serverId:o,raw:r.raw??e.raw}),!0},ro=(e,t,n,r)=>{let o;try{o=e(t,n)}catch{o=void 0}return B(Mn.current,t,function(e,t){const n={relayed:e};if(!t)return n;const r=jn(t);return r&&$n(r)?n.end="provisional":r?.messageId&&(n.end="stored"),"status"===t.action&&t.resumed&&(n.replayed=!0),n}(r,o)),"session_ended"===o?.action&&B(Hn.current,o.reason),o},oo=e=>{switch(e.action){case"user_message":{const t=e.message,n=Ye.current?.openAnswerId()??cn.current;return $(e=>{if(t.serverId&&e.some(e=>e.serverId===t.serverId))return e;let r=e.length-1;for(;r>=0&&("user"!==e[r].role||e[r].serverId||Nn(e[r])!==t.content);)r-=1;return r>=0&&e.length-r<=3?e.map((e,n)=>n===r?{...e,serverId:t.serverId,raw:t.raw}:e):In(e,t,n)}),!0}case"conversation_title":return Bn.current?.(e.conversationId??Yn.current,e.title),!0;case"approval_resolved":return Ne(null),Ie(null),!0;default:return!1}},ao=e=>{No(),Jn(e),H(null),Ne(null),Ie(null),nr.current=null,rr.current=!1,or.current=Yn.current},so=async o=>{const a=!o,s=o?o.text:se,i=a?se:o?.draft??"",c=a?pe:o?.files??[];if(!s.trim()&&0===c.length)return"dropped";if(Vt(c))return"dropped";const l=a?"composer":o?.source??"host",u=!Xn.current&&(null!==mt.current||null!==Ut.current),h=Xn.current||null!==Ut.current,m=!o?.decided&&h&&Kn.current?{text:s,source:l,extras:o?.extras,displayText:o?.displayText}:void 0,g=Pn(s,o?.decided?void 0:B(Kn.current,{text:s,source:l,turnRunning:h,fileCount:c.length}),o?.displayText);if(!g)return"dropped";ht.current=!1,lt(null),a&&ut(null);const f=g.extras,v=o?.extras||f?{...o?.extras,...f}:void 0,w=g.text,y=o?.decided?o.displayText?.trim()||w:g.displayText,x=y!==w?y:void 0,k=a?ye(e,t,n)?we(ce,se):[]:o?.refs??[],C=a?M?ue:[]:o?.mentions??[],N=nn(C,w);if(!w&&0===c.length)return"dropped";const S=()=>{a&&(ie(""),le([]),he([]),me([]),un(de,b,Yn.current,"",[]))};if(Xn.current||u){const e=c.every(e=>"done"===e.uploadStatus);if(!u&&!Hr.current&&!X.current&&!!vr()&&!!Yn.current&&0===k.length&&0===N.length&&0===Object.keys(v??{}).length&&(0===c.length||E&&e)){S();const e=await(async(e,t,n,o=e)=>{const a=vr(),s=Yn.current;if(!a||!s)return{result:"failed"};const i=Cn({id:_e(),role:"user",content:o,timestamp:new Date,files:t.length>0?t:void 0},e),c=Ye.current?.openAnswerId()??cn.current;$(e=>In(e,i,c));const l=t.filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId);let u=null;try{const t=await _(a,{method:"POST",headers:{"Content-Type":"application/json",...d??{},...Pr()},body:JSON.stringify({conversation_id:s,content:e,agent_slug:r,...l.length>0?{file_ids:l}:{}})});if(t.ok){const e=await t.json().catch(()=>null),n=e&&"object"==typeof e?e:{},r=n.turn_id;return B(Vn.current,s,o),{result:"ok",turnId:"string"==typeof r&&r?r:null,unanswered:!1===n.answered}}if($(e=>e.filter(e=>e.id!==i.id)),409===t.status)return{result:"ended"};u=await De(t)}catch{$(e=>e.filter(e=>e.id!==i.id))}return null!==n&&fr({draft:n,files:t,refs:[],mentions:[]},{before:!0}),{result:"failed",detail:u}})(w,c,a?i:null,y);return"ended"===e.result?(at(e=>Ln(e,{text:w,draft:i,files:c,refs:[],mentions:[],extras:v,displayText:x,asked:m,onSent:o?.onSent,onNotSent:o?.onNotSent})),"held"):"ok"===e.result?(e.unanswered&&(ht.current=!0,lt(p("This message will be read with your next one."))),o?.onSteered?.(e.turnId,e.unanswered),"steered"):(e.detail&&lt(e.detail),"failed")}return(z||u)&&e?(S(),at(e=>Ln(e,{text:w,draft:i,files:c,refs:k,mentions:C,extras:v,displayText:x,asked:m,onSent:o?.onSent,onNotSent:o?.onNotSent})),"held"):"dropped"}const T=Cn({id:_e(),role:"user",content:y,timestamp:new Date,files:c.length>0?[...c]:void 0,conversationRefs:k.length>0?k:void 0},w),A=_e();$(e=>[...e,T,{id:A,role:"assistant",content:"",timestamp:new Date}]),S(),Xn.current=!0,O(!0),H({status:"thinking"});const I=sr.generation,R=Qr(A,!1);Fe.current=R.deltas,Ye.current=R,Ze.current=!1,He.current=!0,Be.current=null,It.current=!1;let D=!1,L=!1,j=!1,U=!1,W=!1,q=!1,F=null;const V=()=>{if(!Dr||!Yn.current||!Be.current||R.ended())return!1;D=!0;const e=R.doneReceived()?_e():R.currentAssistantId();return $(t=>[...t.filter(t=>t.id!==e),{id:e,role:"assistant",content:"",timestamp:new Date}]),cn.current=e,tn.current=Be.current,Be.current=null,Qt(_e()),H(e=>"cancelling"===e?.status?e:{status:"reconnecting"}),on.current=Date.now()+(sn.current?mn:15e3),Nr(),!0},K=new AbortController;qe.current?.abort();const G=new AbortController,Y=()=>{q||(q=!0,R.deltas.close(),Fe.current===R.deltas&&(Fe.current=null),Ye.current===R&&(Ye.current=null),He.current=!1,qe.current===G&&G.abort(),We.current===K&&(We.current=null),sr.generation!==I||D||ao(j?"failed":R.outcome()))};try{let r;We.current=K,qe.current=G,Hr.current=K,Vr(qr.current);try{r=await Kr(K.signal)}finally{Hr.current===K&&(Hr.current=null,Vr(!1))}if(K.signal.aborted)return"dropped";const a=(T.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),s=!!(zr()||Rr()||Dr);if(!Yn.current&&(ir.current||s||null!==vr())){const e=sr.generation,t=await Gr();if(sr.generation!==e)return"dropped";t||(ir.current=null,lr(null))}const i=function(e,t,n){switch(e){case"legacy":return{question:t,chatId:n.legacyChatId??void 0,streaming:!0};case"ag-ui":return{threadId:n.conversationId??_e(),runId:_e(),messages:[{id:_e(),role:"user",content:t}],tools:[],context:[],state:{},forwardedProps:n.agentSlug?{agentSlug:n.agentSlug}:{}};default:{const e={...Object.fromEntries(Object.entries(n.extras??{}).filter(([e])=>!bn.has(e))),content:t,conversation_id:n.conversationId,agent_slug:n.agentSlug};if(n.supportsToolApproval&&(e.supports_tool_approval=!0),n.referencedConversationIds&&n.referencedConversationIds.length>0&&(e.referenced_conversation_ids=n.referencedConversationIds),n.supportsPageActions&&(e.supports_page_actions=!0),e.supports_artifacts=!0,n.pageContext&&Object.keys(n.pageContext).length>0)try{const t=JSON.stringify(n.pageContext);t&&"{}"!==t&&(e.context=n.pageContext)}catch{}return e}}}(n,w,{legacyChatId:$e,conversationId:Yn.current,agentSlug:r,pageContext:Qn.current,supportsToolApproval:null!==wr(),referencedConversationIds:k.map(e=>e.conversationId),supportsPageActions:ot(wr(),er.current),extras:{...Un(Rn.current),...v??{}}});a.length>0&&(i.file_ids=a),N.length>0&&(i.mentioned_agent_ids=N);const c=await _(P||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...d??{},...Pr()},body:JSON.stringify(i),signal:K.signal});if(!c.ok||!c.body){const e=c.ok?null:await De(c);return j=!0,$(t=>t.map(t=>t.id===A?{...t,content:e??p("Unable to connect. Please check the configuration.")}:t)),"failed"}L=!0,o?.onSent?.(),Yn.current&&B(Vn.current,Yn.current,y);const l=function(e){switch(e){case"legacy":return tt;case"ag-ui":return nt;default:return Je}}(n);if(await Bt(c.body,e=>{const t=ro(l,e,R.ctx,!1);if(!t)return!0;try{return W?sr.generation===I&&(!!oo(t)||!no(R.currentAssistantId(),t,!1)):(It.current||Ye.current!==R||(It.current=!0,"resend"===Et.current&&(Et.current="off",null!==Ge.current&&To(Ge.current))),!Be.current&&"string"==typeof e.turn_id&&e.turn_id&&(Be.current=e.turn_id),"folded"===t.action?(t.turnId&&(Be.current=t.turnId),!0):!!oo(t)||("set_chat_id"===t.action?(Ue(t.chatId),Ft("local",te,t.chatId),!0):"page_action_required"===t.action?(R.deltas.flush(),Jr(t.actionId,t.pageAction,t.conversationId),!0):(("session_ended"===t.action||jn(t))&&(U=!0),"end"!==R.apply(t)||!!$n(t)&&(R.deltas.flush(),W=!0,s&&(F=kn(!1)),Nt.current=K,Y(),!0))))}catch{return!0}},{idleTimeoutMs:()=>Dr&&Yn.current&&Be.current?45e3:void 0}),R.deltas.flush(),!D&&!U&&V())return"sent";if(!D&&!R.ended()&&R.accumulated()&&!R.doneReceived()){const e=R.currentAssistantId(),t=R.accumulated();$(n=>n.map(n=>n.id===e?{...n,content:t||p("No response.")}:n))}}catch(e){if(R.deltas.close(),q)return"sent";if(e instanceof DOMException&&"AbortError"===e.name)return L?"sent":"dropped";const t=R.currentAssistantId();if(V())return"sent";L||(j=!0),$(e=>e.map(e=>e.id===t?{...e,content:p("Sorry, an error occurred. Please try again.")}:e))}finally{Y(),F&&En(F),Nt.current===K&&(Nt.current=null)}return L?"sent":"failed"},io=()=>{const e=Ke.current;if(!e)return;Ke.current=null,e.renderer.deltas.flush(),e.renderer.deltas.close(),Fe.current===e.renderer.deltas&&(Fe.current=null),Ye.current===e.renderer&&(Ye.current=null);const t=e.renderer.currentAssistantId();$(e=>e.filter(e=>!(e.id===t&&!e.content&&!e.stopped))),ao(e.renderer.outcome())},co=s(io);co.current=io;const lo=()=>{const e=Ke.current;if(!e)return;const t=e.renderer.doneReceived()?null:e.renderer.currentAssistantId();io(),Kt({turnId:e.turnId,shownUpTo:qn(Yt.current)}),t&&$(e=>e.filter(e=>e.id!==t))},uo=s(lo);uo.current=lo;const ho=e=>{Ut.current&&(Kt(null),e&&q(e))},po=s(ho);po.current=ho;const mo=()=>{jt.current&&window.clearTimeout(jt.current.timer),jt.current=null},go=()=>{mo();const e=Ke.current;if(e){const t=qn(Yt.current);io(),Kt({turnId:e.turnId,shownUpTo:t})}const t=Ut.current;if(!t||t.readBack)return;if(!$r())return void ho("stopped");xr();const n=window.setTimeout(()=>{Ut.current===t&&ho("stopped")},1e4);t.readBack={from:Xt.current,timer:n}},fo=s(go);fo.current=go;const vo=()=>{const e=Ke.current,t=Ut.current;if(!e&&t&&(t.readBack||jt.current?.turn===t))return;mo();const n=e??t;if(!n)return;const r=window.setTimeout(()=>{jt.current=null,(e?Ke.current===e:Ut.current===t)&&go()},5e3);jt.current={turn:n,timer:r}},wo=s(vo);wo.current=vo;const bo=s(new Set),yo=e=>{let t=Ke.current;const n=ro(Je,e,t?.renderer.ctx??{hasUsedTools:!1,activeNodeId:""},!0);if(!n)return;if(oo(n))return;if("session_ended"===n.action)return io(),ho("stopped"),void(null===tn.current&&null===ln.current||He.current||(xn(),ao("stopped")));if(!wn.has(n.action))return;const r="string"==typeof e.turn_id&&e.turn_id?e.turn_id:null;if(!r)return o=String(e.type),void(bo.current.has(o)||(bo.current.add(o),console.warn(`A "${o}" frame of the event stream names no turn and is not read: the events route needs \`turn_id\` on every turn frame (see "Turns that outlive their stream" in the README)`)));var o;const a=pt.current.get(r);if(void 0!==a)return void(no(a,n,!0)&&(pt.current.delete(r),zn()));if(He.current||r===Be.current)return;if(r===Xe.current)return;const s=jt.current;if(s)if(mo(),t&&t===s.turn&&r!==t.turnId){const e=t.renderer.doneReceived()?null:t.renderer.currentAssistantId();io(),e&&$(t=>t.filter(t=>t.id!==e)),xr(),t=null}else t&&t===s.turn&&($t.current=t.renderer,xr());let i=t;if(i&&i.turnId!==r&&(io(),i=null),!i){const t=Ut.current,o=t?.turnId===r,a=r===tn.current;if(!("cancelled"!==n.action&&"error"!==n.action||o||a))return void(t&&go());t&&!o&&(ho(),xr());const s=_e();$(e=>[...e,{id:s,role:"assistant",content:"",timestamp:new Date}]),i={turnId:r,renderer:Qr(s,!0)},Ke.current=i,zn(),Fe.current=i.renderer.deltas,Ye.current=i.renderer,Kt(null);const c=a||o;!0===e.resumed&&c?($t.current=i.renderer,xr()):!a||"cancelled"!==n.action&&"error"!==n.action||xr(),xn(),Ze.current=!1,Xn.current=!0,O(!0),H({status:"thinking"})}if("end"===i.renderer.apply(n)){if($n(n)){const e=pt.current;for(e.set(i.turnId,i.renderer.currentAssistantId());e.size>20;)e.delete(e.keys().next().value);kn(!0)}io()}},xo=s(yo);xo.current=yo;const ko=()=>{const e=st.current;e&&(Gn.current?.(e.text,"cancelled"),_n(e.parts)),at(null)},Co=(e,t,n=!1)=>{const r="string"==typeof e&&e?e:null;ir.current=r,lr(r),Fe.current?.close(),Fe.current=null,We.current?.abort(),We.current=null,qe.current?.abort(),qe.current=null,dr.current.abort(),dr.current=new AbortController,sr.abandon(),Ke.current?.renderer.deltas.close(),Ke.current=null,mo(),$t.current=null,Kt(null),pt.current.clear(),Nt.current?.abort(),Nt.current=null,En(),He.current=!1,ko(),No(),xn(),ht.current=!1,Jn("stopped"),ut(null),$([]),n||(ie(""),le([]),he([]),me([])),H(null),be(null),ke(null),Ne(null),Ie(null),ze(!1),nr.current=null,rr.current=!1,or.current=null,Oe.current=!1,P?(Ue(null),Ft("local",te,null)):Or(null,{notify:t})},No=()=>{null!==Ge.current&&window.clearTimeout(Ge.current),Ge.current=null,Et.current="off",Pt.current=null},So=(e=!0)=>{No();const t=Ye.current;Ye.current=null;const n=Ke.current,r=n?.turnId??tn.current;r&&(Xe.current=r),xn(),Fe.current?.flush(),Fe.current?.close(),Fe.current=null,We.current?.abort(),We.current=null,qe.current?.abort(),qe.current=null,Ke.current=null,Jn("stopped"),H(null),Ne(null),Ie(null),ze(!1),nr.current=null,rr.current=!1,Zn.current=new Map;const o=e?t?.currentAssistantId():void 0;$(e=>e.map(e=>e.id===o?{...e,stopped:!0}:e).filter(e=>!("assistant"===e.role&&!e.content&&!e.stopped)))},To=e=>{const t=zr(),n=Yn.current;if(!t||!n)return;const r=He.current&&!It.current;r&&(Et.current="asked");const o=()=>Ge.current===e;jr(t,n,r?{awaiting_send:!0}:void 0).then(async t=>{if(t.ok){const n=await t.json().catch(()=>null);if(!o())return;const a=!!n&&"object"==typeof n&&"none"===n.turn;if(r)return void(a?It.current?(Et.current="off",To(e)):Et.current="resend":Et.current="off");if(!a)return;return So(),void xr()}const n=await De(t);if(!o())return;const a=Pt.current;No(),Ze.current=!1,H(e=>"cancelling"!==e?.status?e:a&&_t.current===a.frameSeq?a.statusBefore:{...e,status:a?.statusBefore?.status??"thinking"}),a?.approvalsBefore&&Ne(e=>e??a.approvalsBefore),lt(n??p("The response could not be stopped. Try again."))}).catch(()=>{o()&&So()})},Ao=Rr(),Io=ne&&A===ne?(Eo=ne,Mr?`${Mr}/${encodeURIComponent(Eo)}/events?client_id=${encodeURIComponent(Jt)}`:null):null;var Eo;sn.current=Io;const zo=Le(d),Ro=s(zo);Ro.current=zo;const[Mo,Do]=a(null),[Lo,_o]=a(0);c(()=>{Mo&&Mo.url===Io&&Mo.headersKey!==zo&&(Do(null),_o(e=>e+1))},[Mo,Io,zo]),c(()=>{if(!Io)return;let e=!1,t=!1,n=0,r=null,o=null,a=null,s=!1,i=!1;const c=async()=>{if(r=null,e||t)return;if("hidden"===document.visibilityState)return void(s&&(i=!0));t=!0,o=new AbortController;let a=!1,l=null;try{const t=Ro.current,r=await _(Io,{headers:{...tr.current??{},"X-Chat-Client-Id":Jt},signal:o.signal});if([401,403,404,405].includes(r.status))return a=!0,401!==r.status&&403!==r.status||e||Do({url:Io,headersKey:t}),void(e||(fo.current(),Cr.current()));if(!r.ok||!r.body)return void(e||[502,503,504].includes(r.status)||Cr.current());s&&wo.current(),Tr.current(),s=!0,l=Date.now(),await Bt(r.body,e=>{n=0;try{xo.current(e)}catch{}},{idleTimeoutMs:45e3})}catch{}finally{if(t=!1,null===l||e||Ir.current(),null!==l&&Date.now()-l>=5e3&&(n=0),!e&&!a&&!i){const e=Math.min(3e4,1e3*2**n);n+=1,r=window.setTimeout(()=>{c()},e*(.5+Math.random()/2))}}},l=()=>{a=null,e||"hidden"!==document.visibilityState||(i=!0,null!==r&&window.clearTimeout(r),r=null,o?.abort(),uo.current())},d=()=>{"hidden"!==document.visibilityState?(null!==a&&window.clearTimeout(a),a=null,"visible"===document.visibilityState&&(Ut.current&&wo.current(),t||(null!==r&&window.clearTimeout(r),n=0,i&&(i=!1,xr()),c()))):null===a&&(a=window.setTimeout(l,6e4))};return c(),document.addEventListener("visibilitychange",d),()=>{e=!0,null!==r&&window.clearTimeout(r),null!==a&&window.clearTimeout(a),o?.abort(),document.removeEventListener("visibilitychange",d),co.current(),po.current()}},[Io,Jt,Lo,xr]);const Po=s([]),[jo,$o]=a(0),Uo=e=>{Po.current.push(e),$o(e=>e+1)};c(()=>{for(const e of Po.current.splice(0))Gn.current?.(e,"returned")},[jo]),c(()=>{if(U||Wt)return;if(Ze.current&&(Ze.current=!1,et))return at(null),_n(et.parts),et.draft||0!==et.files.length?(Uo(et.text),void fr(et,{before:!0})):void Gn.current?.(et.text,"dropped");if(gt||!et)return;at(null);let e=!1;const t=t=>{e||(e=!0,Gn.current?.(et.text,t))},n=[],r=[];for(const e of et.parts){const{asked:t}=e;if(!t){n.push(e);continue}const o=Pn(t.text,B(Kn.current,{text:t.text,source:t.source,turnRunning:!1,held:!0,fileCount:e.files.length}),t.displayText);o?n.push({...e,text:o.text,displayText:o.displayText!==o.text?o.displayText:void 0,extras:t.extras||o.extras?{...t.extras,...o.extras}:void 0,asked:void 0}):r.push(e)}_n(r);const o=r.filter(e=>e.draft||e.files.length>0);for(const e of o)fr(e,{before:!1});if(0===n.length)return void(o.length>0?Uo(et.text):t("dropped"));const{text:a,draft:s,files:i,refs:c,mentions:l,extras:d,displayText:u}=Dn(n);Oo.current({text:a,draft:s,files:i,refs:c,mentions:l,extras:d,displayText:u,decided:!0,onSent:()=>{t("sent");for(const e of n)B(e.onSent)},onNotSent:()=>_n(n)}).then(e=>{if("held"===e)return;const r="sent"===e||"steered"===e;t(r?"sent":"failed"===e?"failed":"dropped"),r||_n(n)},()=>{t("failed"),_n(n)})},[U,Wt,gt,et]);const Oo=s(so);Oo.current=so,c(()=>{const e=window.setTimeout(()=>{un(de,b,ne,se,ce)},300);return()=>window.clearTimeout(e)},[se,ne,ce,b]),c(()=>()=>{Fe.current?.close(),qe.current?.abort(),Nt.current?.abort(),mt.current&&window.clearTimeout(mt.current.timer),null!==Zt.current&&window.clearTimeout(Zt.current),ln.current&&window.clearTimeout(ln.current.timer),jt.current&&window.clearTimeout(jt.current.timer),ko()},[]);const Wo=s({storageKeyPrefix:b,conversationId:ne,inputValue:se,conversationRefs:ce});Wo.current={storageKeyPrefix:b,conversationId:ne,inputValue:se,conversationRefs:ce},c(()=>{const e=()=>{const{storageKeyPrefix:e,conversationId:t,inputValue:n,conversationRefs:r}=Wo.current;un(de,e,t,n,r)},t=()=>{"hidden"===document.visibilityState&&e()};return window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("pagehide",e),document.removeEventListener("visibilitychange",t),e()}},[]),c(()=>{const e=ne;if(!e||U)return;if(or.current===e)return;_r(e)&&wr()&&(or.current=e,(async()=>{const t=await yr(e);t?.proposals&&(Yn.current!==e||Xn.current||(nr.current=e,rr.current=!0,Ie(null),Ne(t.proposals)))})())},[ne,U]),c(()=>{if(!Ce?.length||!rr.current)return;const e=nr.current,t=e?_r(e):null;if(!t)return;const n=window.setInterval(()=>{_(t,{headers:{...d??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[Ce]),c(()=>{if(!Ee)return;const e=nr.current;if(!e)return void ze(!1);if(Date.now()>=ar.current)return ze(!1),void xr();let t=!1;const n=window.setTimeout(async()=>{const n=await yr(e);if(!t){if(n)return n.proposals?(rr.current=!0,Ie(null),Ne(n.proposals),void ze(!1)):n.turnRunning?void je(e=>e+1):(ze(!1),void xr());je(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[Ee,Pe,xr]);const qo=U&&!Br&&!G&&null!==vr()&&null!==ne;return{messages:j,inputValue:se,setInputValue:ie,isLoading:U,turnRunning:U||Wt,turnEnd:W,agentStatus:Q,attachedFiles:pe,conversationId:ne,contextUsage:xe,transferredAgent:ge,forgetTransfer:Zr,canSteer:qo,pendingApprovals:Ce,isSubmittingApproval:Se,approvalError:Ae,submitApprovalDecisions:async e=>{const t=wr(),n=nr.current??Yn.current;if(0!==e.length)if(t&&n){Ie(null),Te(!0);try{const r=await _(t,{method:"POST",headers:{"Content-Type":"application/json",...d??{},...Pr()},body:JSON.stringify({conversation_id:n,decisions:e.map(e=>({tool_call_id:e.toolCallId,decision:e.verdict,..."reject"===e.verdict&&e.rejectionReason?{rejection_reason:e.rejectionReason}:{}}))})});if(r.ok)return Ne(null),rr.current&&!Ke.current?(rr.current=!1,ar.current=Date.now()+pn,void ze(!0)):void H(e=>e?{...e,status:"thinking"}:{status:"thinking"});Ie(409===r.status?p("This turn is no longer waiting for a decision."):p("Could not send your decision. Please try again."))}catch{Ie(p("Could not send your decision. Please try again."))}finally{Te(!1)}}else Ie(p("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:Ee,historyReloadNonce:Re,historyLoadedRef:Oe,conversationIdRef:Yn,handleFileAdd:Xr,handlePaste:e=>{const t=en(e.clipboardData);t.length>0&&(e.preventDefault(),Xr(t))},handleSendMessage:so,skipWait:Ao?async()=>{const e=Rr(),t=Yn.current;if(e&&t)try{(await jr(e,t)).ok&&H(e=>"wait_start"===e?.status?{status:"thinking",thinkingContent:e.thinkingContent}:e)}catch{}}:null,readPendingApprovals:Lr?yr:null,heldMessage:et,notice:ct,fileNotice:dt,composerFocusRequest:hr,cancelHeldMessage:ko,reloadHistory:xr,mergeTurnHistory:e=>{const t=$t.current;if($t.current=null,!t||He.current)return!1;const n=new Set(t.segmentIds()),r=t.currentAssistantId();return $(t=>function(e,t,n,r){const o=e.findIndex(e=>n.has(e.id));if(o<0)return e;const a=e.slice(0,o),s=e.slice(o),i=new Set(a.map(e=>e.serverId).filter(Boolean));let c=-1;t.forEach((e,t)=>{e.serverId&&i.has(e.serverId)&&(c=t)});const l=new Map;for(const e of a)e.serverId||l.set(Sn(e),(l.get(Sn(e))??0)+1);const d=t.slice(c+1).filter(e=>{if(e.serverId&&i.has(e.serverId))return!1;const t=l.get(Tn(e))??0;return 0===t||(l.set(Tn(e),t-1),!1)});if(0===d.length)return e;const u=new Set,h=d.map(e=>{const t=s.find(t=>!u.has(t.id)&&!!e.serverId&&t.serverId===e.serverId)??s.find(t=>!u.has(t.id)&&t.id!==r&&!t.serverId&&Sn(t)===Tn(e));return t?(u.add(t.id),An(t,e)):{...e,id:Qe(e.serverId)}});return[...a,...h,...s.filter(e=>!u.has(e.id))]}(t,e,n,r)),!0},settleUnseenEnd:(e,t)=>{const n=ln.current;n&&e>=n.from&&(window.clearTimeout(n.timer),ln.current=null,ao(t?Fn(t,n.shownUpTo):"stopped"));const r=Ut.current;!r?.readBack||e<r.readBack.from||ho(t?Fn(t,r.shownUpTo):"stopped")},agentMentions:ue,addAgentMention:mr,handleNewChat:e=>{Co(e,!0),pr(e=>e+1)},adoptRecreatedConversation:e=>{Co(void 0,!1,!0),Or(e)},pendingWorkspaceId:cr,clearPendingWorkspace:e=>{ir.current===e&&(ir.current=null,lr(null))},handleStopGenerating:()=>{const e=Ut.current;if(!Xn.current&&e){const t=zr(),n=Yn.current;return t&&n&&jr(t,n).catch(()=>{}),Xe.current=e.turnId,Ze.current=!0,mo(),void ho("stopped")}if(!Xn.current)return void So(!1);if(Ze.current=!0,Hr.current)return void So();const t=zr(),n=Yn.current,r=null!==tn.current&&!Ke.current;if(!t||!n||r)return t&&n&&jr(t,n).catch(()=>{}),void So();if(null!==Ge.current)return;ht.current=!1,lt(null),Ne(null),Ie(null),H(e=>({...e,status:"cancelling"}));const o=window.setTimeout(()=>So(),1e4);Ge.current=o,Pt.current={statusBefore:F,approvalsBefore:Ce,frameSeq:_t.current},To(o)},conversationRefs:ce,addConversationRef:gr,setAttachedFiles:me,setMessages:$,setContextUsage:ke,updateConversationId:Or,handleSwitchConversation:e=>{if(P||e!==Yn.current){if(Co(void 0,!1),!P){Or(e);const t=hn(b,e);de.current=dn(b,e,t.text,t.refs),ie(t.text),le(t.refs)}pr(e=>e+1)}}}}function Bn(e){return(Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]).filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.id).map(e=>function(e){const t=e,n={...e};delete n.disableChat,(!0===t.disable_chat||!0===t.disableChat)&&(n.disableChat=!0);return n}(function(e){const t=e.badges;if(void 0===t)return e;const n=Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&!!e.trim()).map(e=>e.trim()))]:[],r={...e,badges:n};0===n.length&&delete r.badges;return r}(e)))}function Vn(e,t){if(t)return e.find(e=>e.id===t)??e.find(e=>e.slug===t)}function Kn(e){if(!e||"object"!=typeof e)return null;const t=e,n=t.conversation_id??t.id;if("string"!=typeof n||!n)return null;const r={conversationId:n,title:"string"==typeof t.title?t.title.trim():"",updatedAt:"string"==typeof t.updated_at?t.updated_at:"string"==typeof t.created_at?t.created_at:void 0,messageCount:"number"==typeof t.message_count?t.message_count:void 0,agentName:"string"==typeof t.agent_name&&t.agent_name?t.agent_name:void 0,workspaceId:"string"==typeof t.workspace_id&&t.workspace_id?t.workspace_id:null===t.workspace_id?null:void 0};return"string"==typeof t.last_message_preview&&t.last_message_preview.trim()&&(r.lastMessagePreview=t.last_message_preview.trim()),"string"==typeof t.channel&&t.channel&&(r.channel=t.channel),r}function Gn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=an(),[s,i]=a([]),[c,d]=a(!1),[u,h]=a(!1),p="rest"===n&&!t?.singleEndpoint&&null!==t?.sessions&&null!==t?.history,m=`${e}${t?.history??t?.sessions??"/chat/sessions"}`,g=l(async()=>{if(p){d(!0);try{const e=await o(m,{method:"GET",headers:{...r??{}}});if(404===e.status||405===e.status)return i([]),void h(!1);if(!e.ok)return 401!==e.status&&403!==e.status||i([]),void h(!0);const t=await e.json(),n=Array.isArray(t)?t:Array.isArray(t?.conversations)?t.conversations:[];i(n.map(Kn).filter(e=>null!==e)),h(!1)}catch{h(!0)}finally{d(!1)}}},[p,m,r]),f=l(async e=>{if(!p)return"";try{const t=await o(`${m}/${encodeURIComponent(e)}`,{method:"DELETE",headers:{...r??{}}});return t.ok?(i(t=>t.filter(t=>t.conversationId!==e)),null):await De(t)??""}catch{return""}},[p,m,r]),v=p&&t?.clearAll?`${e}${t.clearAll}`:null,w=l(async()=>{if(!v)return"";try{const e=await o(v,{method:"DELETE",headers:{...r??{}}});return e.ok?(i([]),null):await De(e)??""}catch{return""}},[v,r]),b=l(async(e,t)=>{const n=t.trim();if(!p||!n)return null;const a=s.find(t=>t.conversationId===e)?.title??"",c=()=>i(t=>function(e,t,n,r){return e.map(e=>e.conversationId===t&&e.title===n?{...e,title:r}:e)}(t,e,n,a));i(t=>t.map(t=>t.conversationId===e?{...t,title:n}:t));try{const t=await o(`${m}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({title:n})});return t.ok?null:(c(),await De(t)??"")}catch{return c(),""}},[p,m,r,s]),y=l(async(e,t)=>{if(!p)return"";const n=s.find(t=>t.conversationId===e)?.workspaceId,a=()=>i(r=>function(e,t,n,r){const o=e.findIndex(e=>e.conversationId===t);if(o<0||(e[o].workspaceId??null)!==n)return e;const a=[...e];return a[o]={...e[o],workspaceId:r},a}(r,e,t,n));i(n=>n.map(n=>n.conversationId===e?{...n,workspaceId:t}:n));try{const n=await o(`${m}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({workspace_id:t})});return n.ok?null:(a(),await De(n)??"")}catch{return a(),""}},[p,m,r,s]),x=l((e,t)=>{i(n=>function(e,t,n,r){const o=e.findIndex(e=>e.conversationId===t);return o<0?e:[{...e[o],updatedAt:r.toISOString(),...n.trim()?{lastMessagePreview:n.trim()}:{}},...e.slice(0,o),...e.slice(o+1)]}(n,e,t,new Date))},[]);return{historyEnabled:p,conversations:s,conversationsLoading:c,conversationsFailed:u,refreshConversations:g,deleteConversation:f,renameConversation:b,moveConversation:y,clearConversations:v?w:null,touchConversation:x}}const Yn=400;let Xn=null,Jn=null,Qn=0;function Zn(){null!==Xn&&(window.clearInterval(Xn),Xn=null),null!==Jn&&(document.title=Jn,Jn=null)}function er({isLoading:e,agentName:t,t:n,enabled:r=!0,onComplete:o,isViewingChat:a}){const i=s(!1),l=s(0);c(()=>{if(!r||"undefined"==typeof document)return;Qn+=1;const e=()=>{!document.hidden&&document.hasFocus()&&Zn()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),Qn=Math.max(0,Qn-1),0===Qn&&Zn()}},[r]),c(()=>{const s=i.current;if(i.current=e,!e||s){if(!e&&s&&r){if(Date.now()-l.current<4e3)return;const e="undefined"!=typeof document&&document.hidden,r="undefined"!=typeof document&&!document.hasFocus(),s=e||r,i=!a||a();if(!s&&i)return;const c=n("Response ready"),d=t?I(n,"{agent} has finished",{agent:t}):n("Your answer is ready");s&&(function(e){if("undefined"==typeof document)return;null===Jn&&(Jn=document.title),null!==Xn&&window.clearInterval(Xn);let t=!0;document.title=e,Xn=window.setInterval(()=>{t=!t,document.title=t?e:Jn??e},1200)}(c),function(e,t){try{if("undefined"==typeof Notification||"granted"!==Notification.permission)return;new Notification(e,{body:t,tag:"filigran-chat-complete"})}catch{}}(c,d)),o?.(c,d)}}else l.current=Date.now()},[e,r,t,n,o,a])}function tr({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=an(),[s,i]=a(null),[d,u]=a(null),h="rest"===n&&!t?.singleEndpoint,p=void 0===t?.prompts?"/chat/prompts":t.prompts,m=void 0===t?.quota?"/chat/quota":t.quota,g=h&&p?`${e}${p}`:null,f=h&&m?`${e}${m}`:null;c(()=>{if(!g)return void i(null);let e=!1;return o(g,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){const t=Array.isArray(e)?e:Array.isArray(e?.prompts)?e.prompts:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,r="string"==typeof t.id?t.id:"",o="string"==typeof t.content?t.content:"";r&&o&&n.push({id:r,title:"string"==typeof t.title&&t.title?t.title:r,content:o,description:"string"==typeof t.description?t.description:void 0})}return n}(t);i(n.length>0?n:null)}).catch(()=>{e||i(null)}),()=>{e=!0}},[g,r]);const[v,w]=a(0),b=l(()=>w(e=>e+1),[]);return c(()=>{if(!f)return void u(null);let e=!1;return o(f,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{e||u(function(e){if(!e||"object"!=typeof e)return null;const t=e;return"number"!=typeof t.used?null:{used:t.used,limit:"number"==typeof t.limit?t.limit:null,period:"string"==typeof t.period?t.period:"",..."global"===t.scope||"user"===t.scope?{scope:t.scope}:{}}}(t))}).catch(()=>{e||u(null)}),()=>{e=!0}},[f,r,v]),{prompts:s,quota:d,refreshQuota:b}}function nr({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,agentSlug:o}){const s=an(),[i,l]=a(null),[d,u]=a(!1),h="rest"===n&&!t?.singleEndpoint,p=void 0===t?.suggestions?"/chat/suggestions":t.suggestions,m=h&&p?`${e}${p}`:null;return c(()=>{if(!m)return void l(null);let e=!1;u(!0);const t=o?`${m}?agent_slug=${encodeURIComponent(o)}`:m;return s(t,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){return(Array.isArray(e)?e:Array.isArray(e?.suggestions)?e.suggestions:[]).map(e=>{if("string"==typeof e)return e.trim();if(e&&"object"==typeof e){const t=e,n=t.prompt??t.label??t.text;if("string"==typeof n)return n.trim()}return""}).filter(e=>e.length>0)}(t);l(n.length>0?n:null)}).catch(()=>{e||l(null)}).finally(()=>{e||u(!1)}),()=>{e=!0}},[m,o,r]),{suggestions:i,loading:d}}function rr(e){const t=s(e);return function(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||"object"!=typeof t||null===e||null===t)return!1;if(Array.isArray(e)!==Array.isArray(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))}(t.current,e)||(t.current=e),t.current}function or(e){const t=s(e);d(()=>{t.current=e});const n=l((...e)=>t.current?.(...e),[]);return e?n:void 0}function ar(e,t){let n="idle",r=!1,o=!1,a=!1;const s=()=>"listening"===n||r,i=()=>{o||s()===a||(a=s(),t.onListeningChange(a))},c=()=>{try{return e.start(),!0}catch{return!1}};return e.onresult=e=>{if("listening"!==n&&"stopping"!==n)return;let r="",o="";for(let t=e.resultIndex;t<e.results.length;t++){const n=e.results[t];n.isFinal?r+=n[0].transcript:o+=n[0].transcript}const a=r.trim();a&&t.onFinal(a),"listening"===n&&t.onInterim(o.trim())},e.onerror=()=>{"listening"===n&&(n="stopping",t.onInterim("")),i()},e.onend=()=>{if(t.onInterim(""),"listening"===n){if(c())return;n="idle"}else r?(r=!1,n=c()?"listening":"idle"):n="idle";i()},{toggle:()=>{o||(s()?(()=>{if(r=!1,"listening"===n){n="stopping",t.onInterim("");try{e.stop()}catch{n="idle"}}i()})():(c()?n="listening":"idle"!==n&&(r=!0),i()))},cancel:()=>{if(!o){if(r=!1,"listening"===n||"stopping"===n){n="discarding",t.onInterim("");try{e.abort()}catch{n="idle"}}i()}},dispose:()=>{if(!o){if(o=!0,e.onresult=null,e.onerror=null,e.onend=null,"idle"!==n)try{e.abort()}catch{}n="idle",r=!1}}}}function sr(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const ir=new Set(["thinking","status","stream","turn_started"]);function cr(e,t){const n="string"==typeof t.turn_id&&""!==t.turn_id?t.turn_id:null;if(!0===t.relayed){if(null===e.turnId||n!==e.turnId)return{kind:"ignore"}}else{if("folded_into_active_turn"===t.type){if(null!==n)e.turnId=n,e.folded=!0;else if(!1===t.folded)return{kind:"failed"};return{kind:"progress"}}null!==n&&null===e.turnId&&(e.turnId=n)}const r=t.type;if("status"!==r||"transfer_start"!==t.status||"string"!=typeof t.agent_id||!t.agent_id||null!==n&&n!==e.turnId||(e.agentId=t.agent_id),"string"==typeof r&&ir.has(r))return{kind:"progress"};if("done"===r){const n=function(e){return"string"==typeof e?e:""}(t.content),r=!0!==t.intermediate,o=function(e){const t=Xe(e.answered_by);return t?.agentId&&t.agentName?.trim()?{agentId:t.agentId,agentName:t.agentName}:null}(t);if(null!==o&&o.agentId!==e.agentId)return n&&e.others.push({...o,failed:!0===t.mention_failed,text:n}),r?{kind:"answer",text:e.segments.join("\n\n"),others:e.others}:{kind:"progress"};if(!r)return n&&(e.segments=e.folded?[n]:[...e.segments,n]),{kind:"progress"};return{kind:"answer",text:(e.folded?[n]:[...e.segments,n]).filter(Boolean).join("\n\n"),others:e.others}}return"cancelled"===r||"error"===r?{kind:"failed"}:{kind:"ignore"}}function lr(e){return e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}const dr=new Set(["no-speech","aborted"]);function ur(e){const t=e.setTimer??((e,t)=>window.setTimeout(e,t)),n=e.clearTimer??(e=>window.clearTimeout(e)),r=e.recognition;let o="listening",a=!1,s="",i=[],c="",l=null,d=!1,u=0,h=null,p="",m=null,g=null,f=null,v=null,w=!1,b=!1,y=0;const x=()=>e.onChange({phase:o,muted:a,heard:s,lines:i}),k=e=>(null!==e&&n(e),null),C=()=>!a&&("listening"===o||"speaking"===o),N=()=>{if(C()){if(w||null!==v)return;try{r.start(),w=!0}catch{}}else if(w)try{r.stop()}catch{}},S=e=>{o=e,N(),x()},T=()=>{h?.abort(),h=null,p=""},A=()=>{m=k(m),f=k(f),c="",s="",S("listening")},I=()=>{g=k(g),l=null,d=!1},E=()=>{I(),S("error"),f=t(()=>{f=null,"error"===o&&A()},2e3)},z=()=>{g=k(g);const n=l;g=t(()=>{g=null,e.probe().then(e=>{l===n&&n&&("over"===e?E():z())})},12e4)},R=t=>{if(!l||!d)return;const n=cr(l,t);"ignore"!==n.kind&&("answer"===n.kind?((t,n)=>{I();const r=e.present(t),a=function(e){const t=e.text.trim()?[{content:e.text}]:[];for(const n of e.others)n.text.trim()&&t.push({content:n.text,agent:{name:n.agentName,failed:n.failed}});return t}({text:r,others:n.map(t=>({...t,text:e.present(t.text)}))});i=[...i,...a.map(e=>({role:"assistant",...e}))];const l=r.trim()?e.speakable(r):"";if(!l.trim())return void A();const d=new AbortController;h=d,p=l,s="",c="",S("speaking"),e.speak(l,d.signal).catch(()=>{}).then(()=>{h===d&&(h=null,p="","speaking"===o&&A())})})(n.text,n.others):"failed"===n.kind?E():z())},M=()=>{u+=1,I()};return r.continuous=!0,r.interimResults=!0,e.lang&&(r.lang=e.lang),r.onresult=n=>{if(y=0,a||"listening"!==o&&"speaking"!==o)return;let r="",h="";for(let e=n.resultIndex;e<n.results.length;e++){const t=n.results[e];t.isFinal?r+=t[0].transcript:h+=t[0].transcript}if("speaking"===o){if(!function(e,t){const n=lr(e);if(n.length<2)return!1;const r=new Set(lr(t));return n.filter(e=>r.has(e)).length/n.length<.6}(`${r} ${h}`,p))return;T(),c="",o="listening"}r.trim()&&(c=[c,r.trim()].filter(Boolean).join(" ")),s=[c,h.trim()].filter(Boolean).join(" "),m=k(m),c&&(m=t(()=>{m=null,"listening"===o&&!a&&c.trim()&&(t=>{const n=++u;m=k(m),c="",s="",i=[...i,{role:"user",content:t}],l=function(e=null){return{turnId:null,folded:!1,agentId:e,segments:[],others:[]}}(e.addressedAgentId()),d=!1,S("processing"),z();const r=()=>n===u&&null!==l;e.send(t,{onAccepted:()=>{r()&&(d=!0)},onNotSent:()=>{r()&&E()},onSteered:(e,t)=>{r()&&(d=!0,R(e?{type:"folded_into_active_turn",folded:!0,turn_id:e}:{type:"folded_into_active_turn",...t?{folded:!1}:{}}))}}).then(e=>{!r()||"dropped"!==e&&"failed"!==e||E()},()=>{r()&&E()})})(c.trim())},1e3)),x()},r.onerror=e=>{b=!0,dr.has(e?.error??"")||(y+=1)},r.onend=()=>{w=!1;const e=b;if(b=!1,C())return y>=5?(y=0,a=!0,void x()):void(e?v=t(()=>{v=null,N()},300):N())},{start:A,end:()=>{if("ended"!==o){if(M(),T(),m=k(m),f=k(f),v=k(v),o="ended",r.onresult=null,r.onerror=null,r.onend=null,w)try{r.abort()}catch{}w=!1,x()}},frame:(e,t)=>R({...e,relayed:t||!0===e.relayed}),interrupt:()=>{"speaking"===o?(T(),A()):"processing"===o&&(M(),e.stopTurn(),A())},cancel:()=>{"processing"!==o&&"speaking"!==o||(M(),T(),A())},toggleMute:()=>{if("ended"!==o){if(a=!a,y=0,a)m=k(m),c="",s="";else if("speaking"===o)return T(),void A();N(),x()}}}}const hr=()=>null!==sr();function pr(e,t){return new Promise(n=>{const r=URL.createObjectURL(e),o=new Audio(r),a=e=>{o.pause(),URL.revokeObjectURL(r),t.removeEventListener("abort",s),n(e)},s=()=>a(!0);o.onended=()=>a(!0),o.onerror=()=>a(!1),t.addEventListener("abort",s),o.play().catch(()=>a(!1))})}function mr(e,t,n){return"undefined"!=typeof window&&window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance?new Promise(r=>{const o=new SpeechSynthesisUtterance(e);t&&(o.lang=t);const a=()=>{n.removeEventListener("abort",s),r()},s=()=>{window.speechSynthesis.cancel(),a()};o.onend=a,o.onerror=a,n.addEventListener("abort",s),window.speechSynthesis.speak(o)}):Promise.resolve()}const gr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),t("path",{d:"M12 9v4"}),t("path",{d:"M12 17h.01"})]}),fr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m16 3 4 4-4 4"}),t("path",{d:"M20 7H4"}),t("path",{d:"m8 21-4-4 4-4"}),t("path",{d:"M4 17h16"})]}),vr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),wr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 8V4H8"}),t("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),t("path",{d:"M2 14h2"}),t("path",{d:"M20 14h2"}),t("path",{d:"M15 13v2"}),t("path",{d:"M9 13v2"})]}),br=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),t("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),t("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),t("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),t("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),t("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),t("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),t("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),t("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),yr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m9 12 2 2 4-4"})]}),xr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 6 9 17l-5-5"})}),kr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m6 9 6 6 6-6"})}),Cr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m9 18 6-6-6-6"})}),Nr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),Sr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),t("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),Tr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),t("path",{d:"M3 5V19A9 3 0 0 0 21 19V5"}),t("path",{d:"M3 12A9 3 0 0 0 21 12"})]}),Ar=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),Ir=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),t("polyline",{points:"7 10 12 15 17 10"}),t("line",{x1:"12",x2:"12",y1:"15",y2:"3"})]}),Er=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 20h9"}),t("path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"})]}),zr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M10 14 21 3"}),t("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),Rr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),Mr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M11 13H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7"}),t("rect",{width:"12",height:"12",x:"10",y:"10",rx:"2"})]}),Dr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}),Lr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1"}),t("path",{d:"M2 13h10"}),t("path",{d:"m9 16 3-3-3-3"})]}),_r=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 10v6"}),t("path",{d:"M9 13h6"}),t("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})]}),Pr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),t("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),t("path",{d:"M3 16h3a2 2 0 0 0 2 2v3"}),t("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"})]}),jr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),t("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),t("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),t("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]}),$r=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("line",{x1:"6",x2:"10",y1:"11",y2:"11"}),t("line",{x1:"8",x2:"8",y1:"9",y2:"13"}),t("line",{x1:"15",x2:"15.01",y1:"12",y2:"12"}),t("line",{x1:"18",x2:"18.01",y1:"10",y2:"10"}),t("path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z"})]}),Ur=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),t("path",{d:"M2 12h20"})]}),Or=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),t("path",{d:"M3 3v5h5"}),t("path",{d:"M12 7v5l4 2"})]}),Wr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),t("circle",{cx:"9",cy:"9",r:"2"}),t("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]}),qr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),Fr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),t("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),Hr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M9 21H3v-6"}),t("path",{d:"M21 3l-7 7"}),t("path",{d:"M3 21l7-7"})]}),Br=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),Vr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t("rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"})]}),Kr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-.11 1.23"}),t("path",{d:"M5 10v2a7 7 0 0 0 12 5"}),t("path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33"}),t("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12"}),t("path",{d:"m2 2 20 20"})]}),Gr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}),t("path",{d:"m15 5 4 4"})]}),Yr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272"}),t("path",{d:"M22 2 2 22"}),t("path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473"})]}),Xr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.3"})]}),Jr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),Qr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),Zr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),eo=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),to=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("polyline",{points:"4 17 10 11 4 5"}),t("line",{x1:"12",x2:"20",y1:"19",y2:"19"})]}),no=({className:n,size:r=24,filled:o=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:o?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M17 14V2"}),t("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),ro=({className:n,size:r=24,filled:o=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:o?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M7 10v12"}),t("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),oo=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 6h18"}),t("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),t("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),t("line",{x1:"10",x2:"10",y1:"11",y2:"17"}),t("line",{x1:"14",x2:"14",y1:"11",y2:"17"})]}),ao=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t("circle",{cx:"9",cy:"7",r:"4"}),t("line",{x1:"19",x2:"19",y1:"8",y2:"14"}),t("line",{x1:"22",x2:"16",y1:"11",y2:"11"})]}),so="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",io=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:so}),t("path",{d:"M16 9a5 5 0 0 1 0 6"}),t("path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"})]}),co=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:so}),t("path",{d:"m22 9-6 6"}),t("path",{d:"m16 9 6 6"})]}),lo=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),uo=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m15 9-6 6"}),t("path",{d:"m9 9 6 6"})]}),ho={delete:e=>({offer:e("Clear all conversations"),ask:e("Delete all conversations?"),confirm:e("Delete all conversations")}),archive:e=>({offer:e("Archive all conversations"),ask:e("Archive all conversations?"),confirm:e("Archive all conversations")})};function po({onClear:r,action:o="delete",className:s,iconButtonClass:i,t:c}){const[l,d]=a(!1),u=ho[o](c);return t("div",{className:`flex items-center gap-1 ${s}`,children:l?e(n,{children:[t("span",{className:"flex-1 text-[0.7rem] text-red-600 dark:text-red-400",children:u.ask}),t("button",{type:"button",onClick:()=>{d(!1),r()},"aria-label":u.confirm,className:`${i} hover:text-red-500`,children:t(xr,{size:13})}),t("button",{type:"button",onClick:()=>d(!1),"aria-label":c("Cancel"),className:i,children:t(Nr,{size:13})})]}):e("button",{type:"button",onClick:()=>d(!0),className:"flex items-center gap-1.5 rounded-md px-1 py-0.5 text-[0.7rem] chat-text-muted-400/40 hover:text-red-500 dark:hover:text-red-400 transition-colors",children:[t(oo,{size:12}),u.offer]})})}function mo({onRetry:n,className:r,t:o}){return e("div",{role:"alert","data-testid":"filigran-chat-conversation-list-error",className:`flex flex-col items-start gap-2 ${r}`,children:[t("p",{className:"m-0 text-[0.75rem] chat-text-secondary-600/60",children:o("Could not load your conversations.")}),t("button",{type:"button",onClick:n,className:"rounded-md border chat-border-200/10 px-2.5 py-0.5 text-[0.72rem] font-medium chat-text-secondary-700/80 transition-colors hover:chat-surface-hover-100/6",children:o("Retry")})]})}const go=({open:e,onClose:n,anchorRef:r,placement:o="bottom-start",width:i=280,children:d})=>{const h=s(null),[p,m]=a({top:0,left:0}),g=l(()=>n(),[n]);if(function(e,t,n=!0){c(()=>{if(!n)return;const r=n=>{e.current&&!e.current.contains(n.target)&&t()};return document.addEventListener("mousedown",r),document.addEventListener("touchstart",r),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("touchstart",r)}},[e,t,n])}(h,g,e),u(()=>{if(!e||!r.current)return;const t=r.current.getBoundingClientRect(),n=h.current?.offsetHeight??0,a=window.innerHeight-t.bottom-8,s=t.top-8,c=n>0&&a<n&&s>a?Math.max(8,t.top-n-4):t.bottom+4,l="bottom-end"===o?t.right-i:t.left,d=Math.max(8,Math.min(l,window.innerWidth-i-8));m({top:c,left:d})},[e,r,o,i,d]),!e)return null;const f=z(r.current);return y(t("div",{ref:h,className:"fixed z-[10000] rounded-[10px] overflow-hidden border chat-border-200/10 chat-menu-surface shadow-xl",style:{top:p.top,left:p.left,width:i},children:d}),f)},fo=({size:e=16,className:n=""})=>t("div",{className:`animate-spin rounded-full border-2 border-current/20 border-t-[var(--chat-accent)] ${n}`,style:{width:e,height:e}});function vo(e){return Math.max(e.maxRight-e.minLeft,0)}const wo=({title:n,children:r})=>{const o=s(null),i=s(null),[c,l]=a(null),[d,h]=a({below:!1,shift:0});if(u(()=>{if(!c||!i.current)return;const{width:e,height:t}=i.current.getBoundingClientRect();h(function(e,t){const n=e.center-t.width/2;let r=0;return n<e.minLeft?r=e.minLeft-n:n+t.width>e.maxRight&&(r=e.maxRight-(n+t.width)),{below:e.top-4-t.height<e.minTop,shift:r}}(c,{width:e,height:t}))},[c,n]),!n)return r;const p=()=>{if(!o.current)return;const e=z(o.current).getBoundingClientRect();l(function(e,t,n){return{top:e.top,bottom:e.bottom,center:(e.left+e.right)/2,minTop:Math.max(t.top,0),minLeft:Math.max(t.left,0)+4,maxRight:Math.min(t.right,n)-4}}(o.current.getBoundingClientRect(),e,window.innerWidth))};return e("span",{ref:o,className:"inline-flex",onMouseEnter:p,onMouseLeave:()=>l(null),onFocus:e=>{const t=e.target;"function"==typeof t.matches&&t.matches(":focus-visible")&&p()},onBlur:()=>l(null),children:[r,c&&y(t("span",{ref:i,className:`pointer-events-none fixed z-[10001] w-max -translate-x-1/2 ${d.below?"":"-translate-y-full"} whitespace-normal break-words rounded-md bg-gray-900 dark:bg-gray-100 px-2 py-1 text-xs text-white dark:text-gray-900 shadow-lg`,style:{top:d.below?c.bottom+4:c.top-4,left:c.center+d.shift,maxWidth:vo(c)},role:"tooltip",children:n}),z(o.current))]})},bo=({icon:e,fallback:n})=>{const r=function(e){const t=e?.trim();return t?/^(https:\/\/|data:image\/)/i.test(t)?"image":t.length<=8&&!/[\p{L}\p{N}]/u.test(t)?"emoji":null:null}(e);return"image"===r?t("img",{src:e.trim(),alt:"",className:"w-4 h-4 rounded-sm object-cover"}):t("span","emoji"===r?{className:"text-sm leading-none",children:e.trim()}:{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:n})},yo=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(Mr,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(Qr,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t(jr,{...e})}],xo=({link:r,logoIcon:o,agentName:a})=>{const s="flex min-w-0 items-center gap-1.5 text-sm font-semibold chat-text-900/100 pl-2 pr-1 py-1 rounded-lg hover:chat-surface-hover-100/10 hover:underline transition-colors",i=e(n,{children:[t("span",{className:"flex shrink-0 items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]",children:o}),t("span",{className:"min-w-0 truncate",children:a})]});return r.href?t("a",{href:r.href,onClick:e=>{!r.onClick||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),r.onClick())},className:s,children:i}):t("button",{type:"button",onClick:r.onClick,className:s,children:i})},ko=({mode:r,agentName:o,agents:l,agentsLoading:d=!1,agentsError:u=!1,selectedAgent:h,transferredFrom:p,agentMenuOpen:m,onAgentMenuToggle:g,onAgentMenuClose:f,onSwitchAgent:v,modeMenuOpen:w,onModeMenuToggle:b,onModeMenuClose:y,onModeChange:x,onNewChat:k,onClose:C,logoIcon:N,agentDashboardUrl:S,historyEnabled:T=!1,historyMenuOpen:A=!1,onHistoryMenuToggle:E,onHistoryMenuClose:z,conversations:R=[],conversationsLoading:M=!1,conversationsFailed:L=!1,onRetryConversations:_,activeConversationId:P=null,onSelectConversation:j,onDeleteConversation:$,onClearAll:U,clearAllAction:O,actions:W,title:q,subtitle:F,agentLink:B,t:V})=>{const K=s(null),G=s(null),Y=s(null),[X,J]=a("");c(()=>{m||J("")},[m]);const Q=i(()=>{const e=X.trim().toLowerCase();return e?l.filter(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)):l},[l,X]),Z=l.length>5,ee="sidebar"===r?Qr:"fullscreen"===r?Pr:Mr;return e("div",{className:"flex items-center px-3 py-2 min-h-[48px] border-b chat-border-200/10 chat-header-surface "+("floating"===r?"rounded-t-xl":""),children:[e("div",{className:"min-w-0",children:[e("div",{className:"flex min-w-0 items-center gap-1",children:[B?e(n,{children:[t(xo,{link:B,logoIcon:N,agentName:o}),t("button",{ref:K,type:"button",onClick:g,"aria-label":V("Switch to another agent"),"aria-expanded":m,className:"shrink-0 p-1 rounded-lg chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(kr,{size:16})})]}):e("button",{ref:K,type:"button",onClick:g,className:"flex max-w-full min-w-0 items-center gap-1.5 text-sm font-semibold chat-text-900/100 px-2 py-1 rounded-lg hover:chat-surface-hover-100/10 transition-colors",children:[t("span",{className:"flex shrink-0 items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]",children:N}),t("span",{className:"min-w-0 truncate",children:o}),t(kr,{size:16,className:"shrink-0 chat-text-muted-400/30"})]}),q&&e(n,{children:[t("span",{"aria-hidden":!0,className:"shrink-0 chat-text-muted-400/30",children:"/"}),t("span",{"data-testid":"filigran-chat-header-title",className:"min-w-0 truncate px-1 text-[0.8125rem] chat-text-secondary-700/70",children:q})]})]}),p&&t("div",{className:"pl-10 pr-2 text-[0.6rem] font-normal chat-text-muted-400/30",children:I(V,"Transferred from {agent}",{agent:p})}),F&&t("div",{"data-testid":"filigran-chat-header-subtitle",className:"truncate pl-10 pr-2 text-[0.6rem] font-normal chat-text-muted-400/40",children:F})]}),e(go,{open:m,onClose:f,anchorRef:K,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:V("Switch to another agent")}),0===l.length&&d&&t("div",{className:"px-4 py-2",children:t(fo,{size:16})}),0===l.length&&!d&&u&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(gr,{size:14,className:"mt-0.5 shrink-0 text-amber-500 dark:text-amber-400"}),t("span",{className:"text-[0.75rem] leading-5 chat-text-secondary-600/60",children:V("Could not reach the assistant service. Check the connection and try again.")})]}),0===l.length&&!d&&!u&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:V("Agent switching is not available here")}),Z&&t("div",{className:"px-3 pb-2 pt-1",children:e("div",{className:"relative",children:[t(Xr,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 chat-text-muted-400/40"}),t("input",{autoFocus:!0,type:"text",value:X,onChange:e=>J(e.target.value),onKeyDown:e=>{"Escape"===e.key&&f()},placeholder:V("Search agents..."),"aria-label":V("Search agents..."),className:"w-full h-7 pl-7 pr-2 rounded-md chat-surface-subtle-100/6 text-[0.75rem] chat-text-900/100 placeholder:chat-text-muted-400/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[l.length>0&&0===Q.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:V("No agent matches")}),H(Q).map(({group:n,agents:r})=>e("div",{role:"group","aria-label":n??void 0,children:[n&&t("span",{className:"block px-4 pt-2 pb-0.5 text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",children:n}),r.map(n=>e("button",{type:"button",onClick:()=>v(n),className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors "+(n.id===h?.id?"bg-[var(--chat-accent)]/10":""),children:[t("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t(bo,{icon:n.icon,fallback:N})}),e("div",{className:"min-w-0",children:[e("div",{className:"flex min-w-0 items-center gap-1",children:[t("span",{className:"text-[0.8125rem] font-medium chat-text-900/100 truncate",children:n.name}),n.badges?.map(e=>t("span",{className:"shrink-0 rounded bg-[var(--chat-accent)]/10 px-1 text-[0.6rem] leading-4 text-[var(--chat-accent)]",children:e},e)),n.disableChat&&t("span",{className:"shrink-0 rounded bg-amber-500/10 px-1 text-[0.6rem] leading-4 text-amber-600 dark:text-amber-400",children:V("Not recommended for chat")})]}),n.description&&t("div",{className:"text-[0.7rem] chat-text-secondary-500/40 truncate",children:n.description})]})]},n.id))]},n??""))]}),t("div",{className:"h-px chat-border-fill-200/10 mx-2"}),e("div",{children:[S&&e("button",{type:"button",onClick:()=>{f(),window.open(`${S}/agents`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t(zr,{size:18,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:V("Browse agents")})]}),S&&e("button",{type:"button",onClick:()=>{f(),window.open(`${S}/agents/new`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t(ao,{size:18,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:V("Create agent")})]})]})]}),t("div",{className:"flex-1"}),T&&e(n,{children:[t(wo,{title:V("Conversation history"),children:t("button",{ref:Y,type:"button",onClick:E,"aria-label":V("Conversation history"),"aria-haspopup":"menu","aria-expanded":A,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(Or,{size:18})})}),e(go,{open:A,onClose:()=>z?.(),anchorRef:Y,placement:"bottom-end",width:300,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:V("Conversation history")}),e("div",{className:"max-h-72 overflow-y-auto filigran-chat-scrollable",children:[M&&0===R.length&&t("div",{className:"px-4 py-2",children:t(fo,{size:16})}),!M&&0===R.length&&(L?t(mo,{onRetry:()=>_?.(),className:"px-4 py-3",t:V}):t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:V("No conversations yet")})),R.map(n=>{const r=n.conversationId===P,o=D(n.updatedAt,V);return e("div",{className:"group flex items-center gap-2 px-4 py-1.5 hover:chat-surface-hover-100/10 transition-colors "+(r?"bg-[var(--chat-accent)]/10":""),children:[e("button",{type:"button",onClick:()=>j?.(n.conversationId),className:"flex-1 min-w-0 text-left",children:[t("div",{className:"text-[0.8125rem] font-medium chat-text-900/100 truncate",children:n.title||V("Untitled conversation")}),o&&t("div",{className:"text-[0.7rem] chat-text-muted-500/40 truncate",children:o})]}),$&&t("button",{type:"button",onClick:()=>$(n.conversationId),title:V("Delete conversation"),"aria-label":V("Delete conversation"),className:"shrink-0 p-1 rounded-md chat-text-muted-400/30 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-red-500 dark:hover:text-red-400 transition-all",children:t(oo,{size:14})})]},n.conversationId)})]}),t("div",{className:"h-px chat-border-fill-200/10 mx-2"}),e("button",{type:"button",onClick:()=>{z?.(),k()},className:"w-full flex items-center gap-2 px-4 py-2 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t(Er,{size:16,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:V("New conversation")})]}),U&&R.length>0&&t(po,{onClear:()=>{z?.(),U()},action:O,className:"px-3 pb-2",iconButtonClass:"p-1 rounded-md chat-text-muted-400/40 hover:chat-surface-hover-100/10 transition-colors",t:V})]})]}),W,t(wo,{title:V("New chat"),children:t("button",{type:"button",onClick:k,"aria-label":V("New chat"),className:"w-8 h-8 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(Er,{size:18})})}),"inline"!==r&&x&&e(n,{children:[t(wo,{title:V("Switch view"),children:t("button",{ref:G,type:"button","aria-label":V("Switch view"),onClick:b,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(ee,{size:18})})}),e(go,{open:w,onClose:y,anchorRef:G,placement:"bottom-end",width:180,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:V("Switch to")}),t("div",{className:"pb-1",children:yo.map(n=>e("button",{type:"button",onClick:()=>{x(n.mode),y()},className:"w-full flex items-center gap-3 px-4 py-1 text-left hover:chat-surface-hover-100/10 transition-colors "+(r===n.mode?"bg-[var(--chat-accent)]/10":""),children:[n.getIcon({size:18,className:"chat-text-muted-400/40"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:n.label(V)})]},n.mode))})]})]}),"inline"!==r&&C&&t(n,{children:t(wo,{title:V("Close"),children:t("button",{type:"button","aria-label":V("Close"),onClick:C,className:"w-8 h-8 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(Nr,{size:18})})})})]})};function Co({url:e,query:t,exclude:n,requestHeaders:r}){const o=an(),[s,i]=a(xe);return c(()=>{if(!e||null===t)return void i(xe);let a=!0;const s=new AbortController,c=window.setTimeout(async()=>{try{const c=await o(function(e,t,n){const r=new URLSearchParams({limit:String(8)});return t&&r.set("q",t),n&&r.set("exclude",n),`${e}${e.includes("?")?"&":"?"}${r.toString()}`}(e,t,n),{credentials:"include",headers:{...r??{}},signal:s.signal}),l=c.ok?await c.json():null;if(!a)return;i(c.ok?{query:t,items:be(l),failed:!1}:{query:t,items:[],failed:!0})}catch{a&&i({query:t,items:[],failed:!0})}},150);return()=>{a=!1,window.clearTimeout(c),s.abort()}},[e,t,n,r]),s}function No({url:e,requestHeaders:t,conversationId:n,text:r,onTextChange:o,textareaRef:d,refs:p,onPick:m,agentMentions:g}){const f=null!==e||!!g,[v,w]=a(null),[b,y]=a(null),[x,k]=a(0),C=s(null),N=h(),S=l(e=>`${N}-option-${e}`,[N]),T=l(()=>{const e=d.current,t=f&&e&&document.activeElement===e&&e.selectionStart===e.selectionEnd?function(e){const t=/@([\w-]*)$/.exec(e);return!t||me(e[t.index-1])?null:{anchor:t.index,query:t[1]}}(e.value.slice(0,e.selectionStart)):null;w(e=>{return(n=e)===(r=t)||n&&r&&n.anchor===r.anchor&&n.query===r.query?e:t;var n,r})},[f,d]),A=l(()=>w(null),[]);u(()=>{const e=C.current;if(null===e)return;C.current=null;const t=d.current;t&&(t.focus(),t.setSelectionRange(e,e))},[r,d]),c(()=>{T()},[r,T]),c(()=>{v||y(null)},[v]);const I=Co({url:e,query:v?.query??null,exclude:n,requestHeaders:t}),[E,z]=a([]);c(()=>{z([])},[n]),c(()=>{z(e=>function(e,t,n){if(null===t.query||t.failed)return e;const r=t.query,o=new Set(t.items.map(e=>e.id)),a=t.items.length<8,s=r.toLowerCase(),i=a?e.filter(e=>e.id===n||o.has(e.id)||!e.title.toLowerCase().includes(s)):e;return Ce(i.length===e.length?e:i,t.items)}(e,I,n))},[I,n]);const R=i(()=>Ce(p.map(Ne),E),[p,E]);c(()=>{k(0)},[I]);const M=function(e){const{trigger:t,dismissed:n,search:r,referenced:o,exclude:a,known:s=[]}=e;if(!t||n)return{kind:"closed"};if(o>=5)return{kind:"full"};if(r.failed)return{kind:"closed"};const i=t.query?s.filter(e=>ke(t.query,e)&&!r.items.some(t=>t.id===e.id)):[],c=[...r.items,...i].slice(0,8),l=a?c.filter(e=>e.id!==a):c;return l.length>0?{kind:"results",items:l}:t.query&&r.query===t.query?{kind:"empty"}:{kind:"closed"}}({trigger:v,dismissed:null!==v&&v.anchor===b,search:I,referenced:we(p,r).length,exclude:n,known:R}),D=null!==v&&v.anchor===b,L=[...i(()=>g&&v&&!D?function(e,t){const n=[];for(const r of e){const e=tn(r);if(e&&ke(t,{key:e,title:r.name})&&(n.push({agentId:r.id,name:r.name,key:e}),n.length>=5))break}return n}(g.agents,v.query):[],[g,v,D]).map(e=>({type:"agent",mention:e})),...null!==e&&"results"===M.kind?M.items.map(e=>({type:"conversation",candidate:e})):[]],_=Math.min(x,Math.max(L.length-1,0)),P=e=>{if(!v)return;const t="agent"===e.type?e.mention.key:e.candidate.key,n=function(e,t,n){const r=e.slice(0,t.anchor),o=e.slice(t.anchor+1+t.query.length),a=`@${n}`;return{text:`${r}${a}${/^\s/.test(o)?"":" "}${o}`,caret:r.length+a.length+1}}(r,v,t);"agent"===e.type?g?.onPick(e.mention):m({conversationId:e.candidate.id,title:e.candidate.title,key:t,isOwn:e.candidate.isOwn}),C.current=n.caret,o(n.text),w(null)},j=f?{"aria-autocomplete":"list","aria-controls":L.length>0?N:void 0,"aria-activedescendant":L.length>0?S(_):void 0}:{};return{view:null===e?{kind:"closed"}:M,items:L,activeIndex:_,setActiveIndex:k,listboxId:N,optionId:S,sync:T,close:A,pick:P,onKeyDown:e=>{if("closed"===M.kind&&0===L.length||!v)return!1;if("Escape"===e.key)return e.preventDefault(),y(v.anchor),!0;if(0===L.length)return!1;if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();const t="ArrowDown"===e.key?1:-1;return k((_+t+L.length)%L.length),!0}return!("Enter"!==e.key&&"Tab"!==e.key||e.shiftKey)&&(e.preventDefault(),P(L[_]),!0)},textareaAria:j}}const So=e=>e.nativeEvent.isComposing||229===e.keyCode,To=14,Ao=2*Math.PI*6,Io=[{field:"system",label:e=>e("System prompt"),color:"#9ca3af"},{field:"tools",label:e=>e("Tool definitions"),color:"#a78bfa"},{field:"dynamicTools",label:e=>e("MCP & dynamic tools"),color:"#f0abfc"},{field:"summary",label:e=>e("Summarized conversation"),color:"#fb7185"},{field:"toolResults",label:e=>e("Tool results"),color:"#34d399"},{field:"conversation",label:e=>e("Conversation"),color:"#a1a1aa"}],Eo=({usage:r,t:o})=>{const{used:i,limit:c,breakdown:l}=r,d=s(null),[u,h]=a(!1),p=Math.min(Math.max(i/c,0),1),m=p>=.95,g=p>=.8,f=m?"text-red-500":g?"text-amber-500":"text-[var(--chat-accent)]",v=m?"text-red-500 dark:text-red-400":g?"text-amber-600 dark:text-amber-400":"chat-text-muted-400/30",w=Math.round(100*p),b=`${M(i)}/${M(c)}`,y=o(m?"Context full — older turns are being dropped":g?"Context nearly full — older turns are being summarized":"Context used"),x=I(o,"{counts} tokens",{counts:b}),k=`${y} · ${x}`,C=l?Io.filter(e=>(l[e.field]??0)>0):[],N=C.length>0,S=e("span",{className:"flex items-center gap-1.5",children:[e("svg",{width:To,height:To,viewBox:"0 0 14 14",className:f,"aria-hidden":"true",children:[t("circle",{cx:7,cy:7,r:6,fill:"none",strokeWidth:2,className:"stroke-gray-200 dark:stroke-white/15"}),t("circle",{cx:7,cy:7,r:6,fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeDasharray:Ao,strokeDashoffset:Ao*(1-p),transform:"rotate(-90 7 7)",className:"transition-[stroke-dashoffset] duration-500"})]}),e("span",{className:`text-[0.68rem] tabular-nums ${v}`,children:[w,"%"]})]});return N?e(n,{children:[t(wo,{title:u?"":I(o,"{summary} — click for details",{summary:k}),children:t("button",{ref:d,type:"button",onClick:()=>h(e=>!e),"aria-label":`${k} (${w}%)`,"aria-haspopup":"dialog","aria-expanded":u,className:"flex items-center rounded-md px-1 -mx-1 py-0.5 transition-colors hover:chat-surface-hover-100/10",children:S})}),e(go,{open:u,onClose:()=>h(!1),anchorRef:d,placement:"bottom-end",width:296,children:[e("div",{className:"px-3.5 pt-3 pb-1 flex items-baseline justify-between gap-3",children:[t("span",{className:`text-[0.8125rem] tabular-nums ${v}`,children:I(o,"{percent}% full",{percent:w})}),e("span",{className:"text-[0.7rem] tabular-nums chat-text-muted-400/40 shrink-0",children:["~",x]})]}),t("div",{className:"px-3.5 pb-2.5 pt-1.5",children:t("span",{className:"flex h-1.5 w-full gap-px rounded-full chat-border-fill-200/10 overflow-hidden",children:C.map(e=>t("span",{className:"h-full first:rounded-l-full",style:{width:(l?.[e.field]??0)/Math.max(i,1)*Math.min(i/c,1)*100+"%",backgroundColor:e.color}},e.field))})}),t("div",{className:"px-3.5 pb-1",children:C.map(n=>e("div",{className:"flex items-center gap-2 py-[3px]",children:[t("span",{className:"h-2 w-2 shrink-0",style:{backgroundColor:n.color,borderRadius:2},"aria-hidden":"true"}),t("span",{className:"text-[0.75rem] chat-text-secondary-700/70 truncate",children:n.label(o)}),t("span",{className:"ml-auto text-[0.7rem] tabular-nums chat-text-muted-500/40 shrink-0",children:M(l?.[n.field]??0)})]},n.field))}),g&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${v}`,children:y})]})]}):t(wo,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${w}%)`,children:S})})},zo=({view:n,items:r,activeIndex:o,listboxId:a,optionId:i,onHover:c,onPick:l,t:d})=>{const h=s(null);if(u(()=>{h.current?.querySelector('[aria-selected="true"]')?.scrollIntoView?.({block:"nearest"})},[o,n.kind]),"closed"===n.kind&&0===r.length)return null;const p=r.some(e=>"agent"===e.type),m=d(p?"Mention an agent":"Reference a conversation");return e("div",{className:"absolute left-0 right-0 bottom-full mb-1.5 z-20 rounded-[10px] overflow-hidden border chat-border-200/10 chat-menu-surface shadow-xl",children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:m}),r.length>0&&t("div",{ref:h,id:a,role:"listbox","aria-label":m,className:"max-h-[240px] overflow-y-auto pb-1 filigran-chat-scrollable",children:r.map((n,a)=>{const s=a===o,u="conversation"===n.type&&p&&"agent"===r[a-1]?.type;return e("div",{children:[u&&t("span",{className:"block px-4 pt-2 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:d("Reference a conversation")}),e("div",{id:i(a),role:"option","aria-selected":s,onMouseDown:e=>{e.preventDefault(),l(n)},onMouseMove:()=>{s||c(a)},className:"flex items-center gap-2.5 px-4 py-1.5 cursor-pointer transition-colors "+(s?"chat-surface-subtle-100/10":""),children:[t("span",{className:"shrink-0 text-[var(--chat-accent)]",children:"agent"===n.type?t(wr,{size:14}):t(Br,{size:14})}),"agent"===n.type?e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"text-[0.8125rem] chat-text-900/100 truncate",children:n.mention.name}),e("span",{className:"text-[0.7rem] chat-text-muted-500/40 truncate",children:["@",n.mention.key]})]}):e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"text-[0.8125rem] chat-text-900/100 truncate",children:n.candidate.title||d("Untitled conversation")}),e("span",{className:"text-[0.7rem] chat-text-muted-500/40 truncate",children:["@",n.candidate.key,!n.candidate.isOwn&&` · ${d("Shared with you")}`]})]})]})]},"agent"===n.type?`agent-${n.mention.agentId}`:n.candidate.id)})}),"empty"===n.kind&&0===r.length&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] chat-text-muted-400/40",children:d("No conversation matches")}),"full"===n.kind&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] chat-text-muted-400/40",children:I(d,"A message references at most {count} conversations",{count:5})})]})},Ro=({prompts:r,onPick:o,t:i})=>{const c=s(null),[l,d]=a(!1),[u,h]=a(""),p=()=>{d(!1),h("")},m=u.trim().toLowerCase(),g=m?r.filter(e=>e.title.toLowerCase().includes(m)||(e.description??"").toLowerCase().includes(m)):r;return e(n,{children:[t(wo,{title:i("Insert prompt template"),children:t("button",{ref:c,type:"button",onClick:()=>l?p():d(!0),"aria-label":i("Insert prompt template"),"aria-haspopup":"menu","aria-expanded":l,className:"w-7 h-7 flex items-center justify-center rounded-lg transition-colors "+(l?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10":"chat-text-muted-400/30 hover:chat-surface-hover-100/10"),children:t(Zr,{size:15})})}),e(go,{open:l,onClose:p,anchorRef:c,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:i("Insert prompt template")}),r.length>5&&t("div",{className:"px-3 pb-2 pt-1",children:t("input",{autoFocus:!0,type:"text",value:u,onChange:e=>h(e.target.value),onKeyDown:e=>{"Escape"!==e.key||So(e)||p()},placeholder:i("Search prompts..."),"aria-label":i("Search prompts..."),className:"w-full h-7 px-2 rounded-md chat-surface-subtle-100/6 text-[0.75rem] chat-text-900/100 placeholder:chat-text-muted-400/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[0===g.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:i("No prompt matches")}),g.map(n=>e("button",{type:"button",onClick:()=>{o(n.content),p()},className:"w-full px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t("div",{className:"text-[0.8125rem] chat-text-900/100 truncate",children:n.title}),n.description&&t("div",{className:"text-[0.7rem] chat-text-secondary-500/40 truncate",children:n.description})]},n.id))]})]})]})},Mo=({quota:n,t:r})=>{const{used:o,limit:a}=n,s=function(e,t){switch(e){case"daily":return t("today");case"monthly":return t("this month");case"yearly":return t("this year");default:return e}}(n.period,r),i=e=>"global"===n.scope?I(r,"{quota} (shared across all users)",{quota:e}):e;if(null===a){const e=i(s?I(r,"Usage · {period}",{period:s}):r("Usage"));return t(wo,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums chat-text-muted-400/30",role:"img","aria-label":`${e} ${M(o)}`,children:M(o)})})}const c=a>0?Math.min(o/a,1):1,l=!(a>0)||o>=a,d=c>=.75,u=l?"bg-red-500":d?"bg-amber-500":"bg-[var(--chat-accent)]/60",h=l?"text-red-500 dark:text-red-400":d?"text-amber-600 dark:text-amber-400":"chat-text-muted-400/30",p=`${M(o)}/${M(a)}`,m=r(l?"Quota reached":"Quota"),g=i(s?`${m} · ${s}`:m);return t(wo,{title:g,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${g} ${p}`,children:[t("span",{className:"h-1 w-10 rounded-full chat-border-fill-200/10 overflow-hidden",children:t("span",{className:`block h-full rounded-full transition-[width] duration-300 ${u}`,style:{width:100*c+"%"}})}),t("span",{className:`text-[0.68rem] tabular-nums ${h}`,children:p})]})})};const Do=[],Lo=({header:r,steerAttachments:o=!1,canHold:d=!1,heldMessage:h,notice:p,fileNotice:m,agentNotForChat:g=!1,onCancelHeld:f,inputValue:v,onInputChange:w,onSend:b,onStop:y,isLoading:x,canSteer:k=!1,attachedFiles:C=[],onFileAdd:N,onFileRemove:S,onPaste:T,t:A,mode:I,separatorColor:E,prompts:z,quota:R,contextUsage:M,composerToolbar:D,conversationReferences:L,agentMentions:_,accept:P,placeholder:j,focusRequest:$})=>{const U=s(null),O=s(null),W=_?.agents,q=_?.onPick,F=i(()=>W&&q?{agents:W,onPick:q}:void 0,[W,q]),H=No({url:L?.url??null,requestHeaders:L?.requestHeaders,conversationId:L?.conversationId,text:v,onTextChange:w,textareaRef:O,refs:L?.refs??Do,onPick:e=>L?.onPick(e),agentMentions:F}),B=()=>{const e=O.current;e&&function(e){const t=document.activeElement;if(!t||t===document.body||t===e)return!0;const n=e.closest(".filigran-chatbot");return!(!n?.contains(t)||t.closest('[role="dialog"], [role="alertdialog"], dialog'))&&!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t.isContentEditable)}(e)&&e.focus()},V=s($);c(()=>{$!==V.current&&(V.current=$,B())});const K=s(!1),G=function(e){const[t,n]=a(!1),[r,o]=a(""),i=s(null),d=s(e);d.current=e;const u=null!==sr();return c(()=>{const e=sr();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=ar(t,{onFinal:e=>d.current(e),onInterim:o,onListeningChange:n});return i.current=r,()=>{i.current=null,r.dispose(),n(!1),o("")}},[]),{supported:u,listening:t,interim:r,toggle:l(()=>i.current?.toggle(),[]),cancel:l(()=>i.current?.cancel(),[])}}(e=>{K.current=!0,w(v.trim()?`${v.trimEnd()} ${e}`:e)});u(()=>{const e=O.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`,K.current&&(K.current=!1,e.scrollTop=e.scrollHeight))},[v]);const Y=Boolean(z&&z.length>0||R||M||D),X=Boolean(N&&S&&T),J=C.length>0,Q=v.trim()||J,Z=C.some(e=>"pending"===e.uploadStatus),ee=Vt(C),te=Q&&!Z&&!ee,ne=_?nn(_.mentions,v):[],re=Boolean(L)&&we(L?.refs??Do,v).length>0||ne.length>0,oe=g||ne.some(e=>_?.agents.find(t=>t.id===e)?.disableChat),ae=x&&k&&!re&&(!J||o),se=ae&&!Z&&!ee&&(J||Boolean(v.trim())),ie=x&&d&&!se&&!h&&Boolean(te),ce=()=>{(x?se||ie:te)&&(G.cancel(),b(),B())},le="floating"!==I,de=(ie?A("Enter to send when the answer ends · Esc to stop"):ee?A("A file failed to upload: remove it to send the message"):ae?A("Enter to send now · Esc to stop"):x&&J?A("Attachments wait for the current response"):x&&re?A("This message waits for the current response"):null)??(!le||x||Z?null:A("Enter to send · Shift+Enter for new line")),ue="text-center text-[0.65rem] chat-text-muted-400/30 opacity-70",he=t("p",{"data-testid":"filigran-chat-disclaimer",className:`${ue} ${le?"mt-0.5":"mt-1.5"}`,children:A("Uses AI. Verify results.")});return e("div",{className:"px-4 py-3 border-t chat-border-200/10 "+("floating"===I?"rounded-b-xl":""),style:E?{borderTopColor:E,borderTopWidth:1}:void 0,"data-testid":"filigran-chat-composer",children:[r&&t("div",{className:"mb-2",children:r}),p&&t("div",{role:"alert","data-testid":"filigran-chat-composer-notice",className:"mb-2 text-[0.75rem] text-red-500 dark:text-red-400",children:p}),m&&t("div",{role:"alert","data-testid":"filigran-chat-file-notice",className:"mb-2 text-[0.75rem] text-red-500 dark:text-red-400",children:m}),oe&&e("div",{"data-testid":"filigran-chat-agent-not-for-chat",className:"mb-2 flex items-start gap-1.5 text-[0.7rem] text-amber-600 dark:text-amber-400",children:[t(gr,{size:12,className:"mt-0.5 shrink-0"}),t("span",{children:A("This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.")})]}),h&&e("div",{className:"mb-2 flex items-center gap-2 rounded-lg border border-dashed border-[var(--chat-accent-40)] px-2.5 py-1.5 text-[0.75rem]",children:[t("span",{className:"shrink-0 chat-text-secondary-500/50",children:A("Sends when the answer ends:")}),t("span",{className:"min-w-0 flex-1 truncate chat-text-800/80",children:h.displayText??(h.text||A("Attached files"))}),f&&t("button",{type:"button",onClick:f,className:"shrink-0 chat-text-muted-400/40 hover:text-red-500",children:A("Cancel")})]}),J&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:C.map((n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[0.7rem] "+("error"===n.uploadStatus?"border-red-300 dark:border-red-500/30 text-red-500 dark:text-red-400":"pending"===n.uploadStatus?"chat-border-200/10 chat-text-muted-400/40":"chat-border-200/10 chat-text-secondary-600/60"),children:["pending"===n.uploadStatus?t("span",{className:"w-3.5 h-3.5 border border-current/30 border-t-current rounded-full animate-spin"}):t(Rr,{size:14}),n.name,"error"===n.uploadStatus&&e("span",{"data-testid":"filigran-chat-upload-error",className:"inline-flex min-w-0 items-center gap-1 text-red-400",children:[t("span",{"aria-hidden":"true",className:"text-[0.6rem]",children:"✕"}),t("span",{className:"max-w-[16rem] truncate",title:n.uploadError??A("Upload failed"),children:n.uploadError??A("Upload failed")})]}),t("button",{type:"button",onClick:()=>S?.(r),className:"ml-0.5 chat-text-muted-400/30 hover:chat-text-secondary-600/60",children:"×"})]},r))}),e("div",{className:`relative flex items-end border rounded-xl chat-composer-surface px-2 py-1 transition-colors ${G.listening?"border-red-500/50":"chat-border-200/10 focus-within:border-[var(--chat-accent)]"} ${x?"filigran-chat-active-border":""}`,children:[X&&e(n,{children:[t("input",{ref:U,type:"file",multiple:!0,hidden:!0,accept:P||void 0,onChange:e=>{N?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>U.current?.click(),"aria-label":A("Attach files"),className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg chat-text-muted-400/30 hover:chat-surface-hover-100/10 mr-0.5 transition-colors",children:t(vr,{size:18})})]}),t("textarea",{ref:O,placeholder:G.listening?A("Listening..."):j??A("Ask a question..."),value:v,onChange:e=>w(e.target.value),onKeyDown:e=>{So(e)||H.onKeyDown(e)||("Enter"!==e.key||e.shiftKey||(e.preventDefault(),ce()),"Escape"===e.key&&x&&(e.preventDefault(),y()))},onKeyUp:H.sync,onClick:H.sync,onFocus:H.sync,onBlur:H.close,...H.textareaAria,onPaste:T,rows:1,className:"flex-1 bg-transparent border-none outline-hidden resize-none text-[0.8125rem] py-1.5 chat-text-900/100 placeholder:chat-text-muted-400/30 filigran-chat-scrollable",style:{maxHeight:120}}),t(zo,{view:H.view,items:H.items,activeIndex:H.activeIndex,listboxId:H.listboxId,optionId:H.optionId,onHover:H.setActiveIndex,onPick:H.pick,t:A}),G.supported&&t(wo,{title:G.listening?A("Stop dictation"):A("Dictate a message"),children:e("button",{type:"button",onClick:G.toggle,"aria-label":A("Dictate a message"),"aria-pressed":G.listening,className:"relative w-8 h-8 flex items-center justify-center shrink-0 rounded-lg mr-0.5 transition-colors "+(G.listening?"text-red-500 bg-red-500/10 hover:bg-red-500/20":"chat-text-muted-400/30 hover:chat-surface-hover-100/10"),children:[G.listening?t(Kr,{size:18}):t(Vr,{size:18}),G.listening&&t("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-red-500 motion-safe:animate-pulse"})]})}),ie&&t(wo,{title:A("Send when the answer ends"),children:t("button",{type:"button",onClick:ce,"aria-label":A("Send when the answer ends"),className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Jr,{size:18})})}),se&&t(wo,{title:A("Send now"),children:t("button",{type:"button",onClick:ce,"aria-label":A("Send now"),className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Jr,{size:18})})}),t(wo,{title:x?A("Stop generating"):Z?A("Files uploading..."):"",children:t("button",{type:"button",onClick:x?y:ce,"aria-label":A(x?"Stop generating":"Send"),disabled:!x&&!te,className:"p-1.5 rounded-lg w-8 h-8 flex items-center justify-center transition-all duration-150 "+(x?"text-red-500 bg-red-500/10 hover:bg-red-500/20 ml-0.5":te?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20":"chat-text-muted-300/20 cursor-not-allowed"),children:t(x?eo:Jr,{size:18})})})]}),Y&&e("div",{className:"flex items-center gap-1.5 mt-1.5 px-0.5",children:[z&&z.length>0&&t(Ro,{prompts:z,onPick:e=>{w(v.trim()?`${v.trimEnd()}\n\n${e}`:e),O.current?.focus()},t:A}),D,(M||R)&&e("span",{className:"ml-auto flex items-center gap-2.5",children:[M&&t(Eo,{usage:M,t:A}),R&&t(Mo,{quota:R,t:A})]})]}),G.interim?e("p",{className:"flex items-center justify-center gap-1.5 text-[0.65rem] italic text-red-500 dark:text-red-400 mt-1.5",children:[t("span",{className:"w-1.5 h-1.5 shrink-0 rounded-full bg-red-500 motion-safe:animate-pulse"}),t("span",{className:"truncate",children:G.interim})]}):de||le?t("p",{"data-testid":"filigran-chat-composer-hint",className:`${ue} mt-1.5 min-h-[1lh]`,children:de}):null,(le||!G.interim&&!de)&&he]})},_o=e=>e.serverId??e.id;const Po=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;const jo={time:{hour:"2-digit",minute:"2-digit"},date:{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"},dateWithYear:{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"},full:{dateStyle:"full",timeStyle:"short"}},$o=new Map;function Uo(e,t){const n=`${e??""}|${t}`;let r=$o.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,jo[t])}catch{r=new Intl.DateTimeFormat(void 0,jo[t])}$o.set(n,r)}return r}const Oo={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const Wo=new Set(["ArrowUp","PageUp","Home"]);function qo(e){return 1===e.length?e[0].clientY:null}const Fo=new Set(["auto","scroll","overlay"]);const Ho={presentation:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M2 3h20"}),t("path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"}),t("path",{d:"m7 21 5-5 5 5"})]}),report:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}),t("path",{d:"M10 9H8"}),t("path",{d:"M16 13H8"}),t("path",{d:"M16 17H8"})]}),video:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z"}),t("path",{d:"m6.2 5.3 3.1 3.9"}),t("path",{d:"m12.4 3.4 3.1 4"}),t("path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})]})},Bo="inline-flex items-center gap-1 rounded-md border chat-border-200/10 px-2 py-1 text-[0.7rem] chat-text-secondary-700/70 transition-colors hover:border-[var(--chat-accent)] hover:text-[var(--chat-accent)] disabled:opacity-50 disabled:cursor-default outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",Vo=({artifact:n,t:r,onDownload:o,onRefresh:s,onOpen:i})=>{const[l,d]=a(n),[u,h]=a(null),[p,m]=a(!1);c(()=>d(n),[n]);const g=!!s&&!p&&(e=>"video"===e.kind&&("pending"===e.status||"running"===e.status))(l);c(()=>{if(!g||!s)return;let e=!1;const t=function(e,{intervalMs:t,forMs:n,onGiveUp:r}){let o,a=!1;const s=()=>{o=setTimeout(()=>{e().catch(()=>{}).finally(()=>{a||s()})},t)},i=setTimeout(()=>{a=!0,clearTimeout(o),r?.()},n);return s(),()=>{a=!0,clearTimeout(o),clearTimeout(i)}}(()=>s(l.kind,l.id).then(t=>{!e&&t&&d(t)}),{intervalMs:1e4,forMs:9e5,onGiveUp:()=>m(!0)});return()=>{e=!0,t()}},[g,s,l.kind,l.id]);const f=Ho[l.kind],v=function(e,t){return t("presentation"===e?"Presentation":"report"===e?"Report":"Video")}(l.kind,r),w=l.title||v,b=F(l,r),y=function(e,t){if("video"===e.kind){if("running"===e.status)return I(t,"Rendering {progress}%",{progress:Math.round(e.progress??0)});if("pending"===e.status)return t("Waiting to render");if(!(e.downloads.length>0))return"failed"===e.status||"cancelled"===e.status?t("The render did not finish"):t("Not rendered yet")}}(l,r),x=i?null:function(e){if(e.url)try{const t=new URL(e.url);return"http:"===t.protocol||"https:"===t.protocol?t.toString():void 0}catch{return}}(l),k=o?l.downloads:[];return e("div",{role:"group","aria-label":`${v}: ${w}`,className:"flex flex-col gap-2 w-full max-w-[90%] rounded-lg border chat-border-200/10 chat-surface-subtle-50/4 px-3 py-2.5",children:[e("div",{className:"flex items-start gap-2.5 min-w-0",children:[t("span",{className:"shrink-0 mt-0.5 text-[var(--chat-accent)]",children:t(f,{size:18})}),e("span",{className:"flex flex-col min-w-0 flex-1 gap-0.5",children:[t("span",{className:"truncate text-[0.8125rem] font-medium chat-text-900/100",children:w}),b&&t("span",{className:"text-[0.7rem] chat-text-secondary-500/50",children:b}),y&&e("span",{className:"flex items-center gap-1.5 text-[0.7rem] chat-text-secondary-500/50","aria-live":"polite",children:[g&&t(fo,{size:10}),y]})]})]}),(x||i||k.length>0)&&e("div",{className:"flex flex-wrap items-center gap-1.5 pl-[28px]",children:[i&&t("button",{type:"button",className:Bo,onClick:()=>i(l),children:r("Open")}),x&&e("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:Bo,children:[r("Open in XTM One"),t(zr,{size:12})]}),k.map(n=>{const a=function(e,t){return"pdf"===e?"PDF":"mp4"===e?"MP4":"pptx"===e?t("PowerPoint"):"pptx_native"===e?t("PowerPoint (editable)"):e.toUpperCase()}(n,r);return e("button",{type:"button",className:Bo,disabled:null!==u,"aria-label":I(r,"Download {format}",{format:a}),onClick:()=>{(async e=>{if(o){h(e);try{await o(l,e)}finally{h(null)}}})(n)},children:[u===n?t(fo,{size:11}):t(Ir,{size:12}),a]},n)})]})]})};function Ko(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function Go(e){const t=s(null);return c(()=>{if(!e)return;const n=requestAnimationFrame(()=>{t.current?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})});return()=>cancelAnimationFrame(n)},[e]),t}const Yo="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",Xo=({proposal:n,decision:r,onDecide:o,disabled:s,t:i})=>{const[c,l]=a(!1),[d,u]=a(""),p=h(),m=Go(c),g=r?.verdict,f=Object.keys(n.arguments??{}),v=e=>{o({toolCallId:n.toolCallId,verdict:e,..."reject"===e&&d.trim()?{rejectionReason:d.trim()}:{}})};return e("div",{"data-testid":"filigran-chat-approval",className:"rounded-lg border border-amber-500/25 bg-amber-500/[0.04] p-3 flex flex-col gap-2",children:[e("div",{className:"flex items-start justify-between gap-2",children:[e("div",{className:"min-w-0 flex items-start gap-2",children:[t(lo,{size:13,className:"mt-0.5 shrink-0 text-amber-600 dark:text-amber-400"}),e("div",{className:"min-w-0",children:[t("p",{className:"truncate font-mono text-xs chat-text-800/85",children:n.toolName||i("unknown tool")}),n.toolDescription&&t("p",{className:"mt-0.5 text-[0.7rem] chat-text-secondary-600/60",children:n.toolDescription}),n.source&&t("p",{className:"mt-0.5 text-[0.65rem] chat-text-muted-400/35",children:n.source})]})]}),g&&t("span",{className:"shrink-0 rounded px-1.5 py-0.5 text-[0.65rem] font-medium "+("reject"===g?"bg-red-500/15 text-red-600 dark:text-red-300":"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"),children:i("reject"===g?"Declined":"approve_always"===g?"Always allowed":"Approved")})]}),f.length>0&&t("div",{className:"flex flex-col gap-1.5",children:f.map(r=>{const o=function(e,t){const n=e?.properties;if(!n||"object"!=typeof n)return{};const r=n[t];if(!r||"object"!=typeof r)return{};const o=r;return{description:"string"==typeof o.description?o.description:void 0,type:"string"==typeof o.type?o.type:void 0}}(n.inputSchema,r);return e("div",{className:"text-[0.7rem]",children:[e("div",{className:"flex flex-wrap items-baseline gap-1.5",children:[t("span",{className:"font-mono chat-text-secondary-700/75",children:r}),o.description&&e("span",{className:"chat-text-secondary-500/45",children:["— ",o.description]})]}),t("pre",{className:"mt-0.5 whitespace-pre-wrap break-all font-mono chat-text-secondary-600/60",children:Ko(n.arguments?.[r])})]},r)})}),!g&&c&&e("div",{ref:m,className:"flex flex-col gap-1.5",children:[t("label",{htmlFor:p,className:"text-[0.7rem] chat-text-secondary-500/45",children:i("Why not? The agent sees this and can adapt (optional)")}),t("textarea",{id:p,autoFocus:!0,rows:2,value:d,onChange:e=>u(e.target.value),placeholder:i("e.g. wrong environment — use staging instead"),className:"w-full resize-none rounded-md border chat-border-200/10 chat-input-surface-white/3 px-2 py-1 text-[0.7rem] chat-text-800/85 outline-none focus:border-[var(--chat-accent)]/50"}),e("div",{className:"flex items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>v("reject"),className:`${Yo} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(uo,{size:13}),i("Decline this call")]}),t("button",{type:"button",disabled:s,onClick:()=>{l(!1),u("")},className:`${Yo} chat-text-secondary-500/50 hover:chat-surface-hover-100/5`,children:i("Back")})]})]}),!g&&!c&&e("div",{className:"flex flex-wrap items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>l(!0),className:`${Yo} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(uo,{size:13}),i("No")]}),e("button",{type:"button",disabled:s,onClick:()=>v("approve"),className:`${Yo} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(xr,{size:13}),i("Yes")]}),t("button",{type:"button",disabled:s,onClick:()=>v("approve_always"),title:i("Also applies to your scheduled runs, until you revoke it"),className:`${Yo} border chat-border-200/15 chat-text-secondary-700/70 hover:chat-surface-hover-100/5`,children:i("Yes, always")})]})]})},Jo=({proposals:n,onSubmit:r,isSubmitting:o,error:i,t:l})=>{const[d,u]=a({}),h=s(!1),[p,m]=a(!1);c(()=>{i&&(h.current=!1,m(!1))},[i]);const g=o||p,f=e=>{h.current||o||(h.current=!0,m(!0),r(e))},v=n.filter(e=>d[e.toolCallId]).length,w=v===n.length&&n.length>0,b=Object.values(d).some(e=>"approve_always"===e.verdict),y=Go(b),x=Go(!0);return e("div",{ref:x,className:"flex flex-col gap-2 rounded-lg border border-amber-500/20 bg-amber-500/[0.02] p-3",children:[e("p",{className:"flex items-start gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300",children:[t(gr,{size:13,className:"mt-0.5 shrink-0"}),1===n.length?l("The agent needs your approval to run a tool:"):l("The agent needs your approval to run these tools:")]}),n.map(e=>t(Xo,{proposal:e,decision:d[e.toolCallId],disabled:g,t:l,onDecide:e=>{const t={...d,[e.toolCallId]:e};u(t);const r=n.map(e=>t[e.toolCallId]);r.every(Boolean)&&!r.some(e=>"approve_always"===e.verdict)&&f(r)}},e.toolCallId)),b&&e("p",{className:"flex items-start gap-1.5 text-[0.7rem] text-amber-700 dark:text-amber-300/90",children:[t(gr,{size:13,className:"mt-0.5 shrink-0"}),l("“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.")]}),i&&t("p",{className:"text-[0.7rem] text-red-600 dark:text-red-300",children:i}),e("div",{ref:y,className:"flex items-center justify-between gap-2",children:[t("span",{className:"text-[0.7rem] chat-text-muted-500/40",children:n.length>1?I(l,"{decided}/{total} decided",{decided:v,total:n.length}):""}),t("button",{type:"button",disabled:!w||g,onClick:()=>f(n.map(e=>d[e.toolCallId])),className:`${Yo} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:l(g?"Sending…":"Confirm")})]})]})},Qo=({src:n,alt:r,onClose:o,onDownload:i,t:l})=>{const d=s(null),u=s(null),h=s(null),[p,m]=a(null);return c(()=>{m(z(d.current))},[]),c(()=>{const e=e=>{if("Escape"===e.key)return void o();if("Tab"!==e.key)return;const t=[...h.current?.querySelectorAll("button")??[]];if(0===t.length)return;const n=t[0],r=t[t.length-1],a=document.activeElement;(!(!!a&&t.includes(a))||e.shiftKey&&a===n||!e.shiftKey&&a===r)&&(e.preventDefault(),(e.shiftKey?r:n).focus({preventScroll:!0}))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o]),c(()=>{if(!p)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return u.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[p]),t("span",{ref:d,className:"hidden",children:p&&y(e("div",{ref:h,className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/80 p-4",onClick:o,role:"dialog","aria-modal":"true","aria-label":r.trim()||l("Image preview"),children:[e("div",{className:"absolute top-4 right-4 flex gap-2",children:[i&&t("button",{type:"button",onClick:e=>{e.stopPropagation(),i()},"aria-label":l("Download"),className:"rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20",children:t(Ir,{size:20})}),t("button",{ref:u,type:"button",onClick:o,"aria-label":l("Close"),className:"rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20",children:t(Nr,{size:20})})]}),t("img",{src:n,alt:r,className:"max-h-[90%] max-w-[90%] rounded-lg object-contain",onClick:e=>e.stopPropagation()})]}),p)})};function Zo(e,t){const n=!!e&&!!t&&Object.keys(t).length>0&&(e=>!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(e),[r,o]=a(null),[s,i]=a(null),l=an();return c(()=>{if(!n||!e)return;let r=!1;return l(e,{credentials:"include",headers:{...t}}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(t=>{r||o({src:e,url:URL.createObjectURL(t)})}).catch(()=>{r||i(e)}),()=>{r=!0}},[n,e,t]),c(()=>{if(!r)return;const{url:e}=r;return()=>URL.revokeObjectURL(e)},[r]),e?n?r?.src===e?{src:r.url,status:"ready"}:s===e?{src:null,status:"failed"}:{src:null,status:"loading"}:{src:e,status:"ready"}:{src:null,status:"failed"}}const ea=({src:r,alt:o,requestHeaders:s,maxHeightClass:i="max-h-[400px]",onDownload:c,t:l})=>{const d=Zo(r,s),[u,h]=a(null),[p,m]=a(!1),g=d.src;return"failed"===d.status||null!==g&&u===g?t("p",{className:"my-2 text-[0.75rem] italic chat-text-muted-400/40",children:l("Image could not be loaded")}):g?e(n,{children:[e("span",{className:"group/img relative my-3 inline-block max-w-full rounded-lg border chat-border-200/10 p-1 transition-colors hover:border-[var(--chat-accent)]/40",children:[t("img",{src:g,alt:o,loading:"lazy",onClick:()=>m(!0),onError:()=>h(g),className:`max-w-full cursor-zoom-in rounded-md object-contain ${i}`}),t("button",{type:"button",onClick:()=>m(!0),"aria-label":l("Expand image"),className:"absolute top-2 right-2 rounded-md bg-black/50 p-1.5 text-white opacity-0 transition-opacity hover:bg-black/70 group-hover/img:opacity-100 focus-visible:opacity-100",children:t(Hr,{size:14})})]}),p&&t(Qo,{src:g,alt:o,onClose:()=>m(!1),onDownload:c,t:l})]}):e("span",{className:"my-3 inline-flex items-center gap-2 rounded-lg border chat-border-200/10 px-3 py-2",children:[t(Wr,{size:14,className:"shrink-0 animate-pulse text-[var(--chat-accent)]"}),t("span",{className:"text-[0.7rem] chat-text-muted-500/40",children:l("Loading image…")})]})};const ta="inline-flex items-center gap-1.5 self-start rounded text-xs text-[var(--chat-accent)] opacity-80 transition-opacity hover:opacity-100 focus-visible:opacity-100",na=({t:n,enabled:r=!0,onPlay:o,playUrl:s,keepEndInView:l,messages:d,content:u})=>{const h=i(()=>d&&d.length>0?d:(e=>[e("Crunching the data"),e("Connecting the dots"),e("Consulting the sources"),e("Thinking it through"),e("Reticulating splines"),e("Analyzing the details"),e("Almost there"),e("Putting it together"),e("Polishing the answer"),e("Wrapping things up")])(n),[d,n]),p=function(){const[e,t]=a(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return c(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=()=>t(e.matches);return"function"==typeof e.addEventListener?(e.addEventListener("change",n),()=>e.removeEventListener("change",n)):(e.addListener(n),()=>e.removeListener(n))},[]),e}(),[m,g]=a(0);if(c(()=>{r&&l()},[r,l]),c(()=>{if(!r||u)return;const e=window.setInterval(()=>g(e=>(e+1)%h.length),2600);return()=>window.clearInterval(e)},[r,h.length,!!u]),!r)return null;if(u)return t("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:u});const f=h[m%h.length];return e("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:[t("span",{className:"sr-only",role:"status","aria-live":"polite",children:f}),e("div",{className:"flex flex-col gap-1.5 rounded-md bg-[var(--chat-accent)]/[0.03] px-3 py-2.5",style:p?void 0:{animation:"chat-fade-in 0.5s ease-out"},children:[e("span",{"aria-hidden":!0,className:"text-xs chat-text-muted-500/45",style:p?void 0:{animation:"chat-fade-in 0.4s ease-out"},children:[f,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(p?"":"animate-pulse")})]},f),o?e("button",{type:"button",onClick:o,className:ta,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t($r,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:ta,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t($r,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t(zr,{size:11})})]}):null]})]})};class ra extends p{state={failed:!1,resetKey:this.props.resetKey};static getDerivedStateFromError(){return{failed:!0}}static getDerivedStateFromProps(e,t){return e.resetKey===t.resetKey?null:{failed:!1,resetKey:e.resetKey}}componentDidCatch(e,t){console.error(`${this.props.label} failed to render`,e,t.componentStack)}render(){return this.state.failed?this.props.fallback:this.props.children}}function oa({draw:e}){return t(n,{children:e()})}function aa({t:e}){return t("p",{className:"pl-1 text-[0.75rem] italic chat-text-muted-400/40",children:e("This item could not be loaded.")})}function sa(e,t){return e>1?I(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function ia(e,t){return e>1?I(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function ca(e,t){return e>1?I(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function la(e,t){const n="function"==typeof t?B(t,e):t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;return"string"==typeof n&&n.trim()?n:void 0}function da(e,t){return Array.from(new Set(e.map(e=>la(e,t)??e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()))))}function ua(e,t){switch(e){case"history":return t("Loading conversation history…");case"compaction":return t("Summarizing earlier conversation…");case"memory":return t("Recalling memory…");case"integrations":return t("Connecting integrations…");case"tools":return t("Preparing tools…");default:return t("Preparing…")}}function ha(e,t,n){if(e.agents>1)return I(t,"Consulting {count} agents…",{count:e.agents});const r=e.agentName;if(e.count>1)return I(t,"Consulting {agent}: {count} questions…",{agent:r,count:e.count});const o="tool_start"===e.status?(e.tools??[]).filter(e=>"consult_agent"!==e):[];if(o.length>0){const[e,...a]=da(o,n);return a.length>0?I(t,"Consulting {agent}: {tool} (+{count} more)…",{agent:r,tool:e,count:a.length}):I(t,"Consulting {agent}: {tool}…",{agent:r,tool:e})}return e.answering?I(t,"Consulting {agent}: writing the answer…",{agent:r}):I(t,"Consulting {agent}…",{agent:r})}function pa(e,t,n){if(!e)return{label:t("Thinking..."),StatusIcon:br,showDots:!1};switch(e.status){case"tool_start":{const r=e.tools??[],o=r.map(e=>e.toLowerCase());if(o.some(e=>"spawn_background_task"===e)){return{label:sa(r.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:ao,showDots:!1}}if(o.some(e=>"check_task_status"===e)){return{label:ia(r.filter(e=>"check_task_status"===e).length,t),StatusIcon:Zr,showDots:!1}}if(o.some(e=>"get_task_result"===e)){return{label:ca(r.filter(e=>"get_task_result"===e).length,t),StatusIcon:Zr,showDots:!1}}let a,s=lo;if(o.some(e=>e.includes("search")||e.includes("list"))?s=Xr:o.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?s=Tr:o.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?s=Fr:o.some(e=>e.includes("code")||e.includes("execute"))?s=to:o.some(e=>e.includes("web")||e.includes("browse"))&&(s=Ur),r.length>0){const e=da(r,n);a=1===e.length?`${e[0]}…`:I(t,"{tool} (+{count} more)…",{tool:e[0],count:e.length-1})}else a=t("Using tools…");return{label:a,StatusIcon:s,showDots:!1}}case"awaiting_approval":return{label:t("Waiting for your approval…"),StatusIcon:gr,showDots:!1};case"cancelling":return{label:t("Stopping…"),StatusIcon:br,showDots:!0};case"reconnecting":return{label:t("Reconnecting…"),StatusIcon:br,showDots:!0};case"wait_start":return{label:e.waitReason||t("Waiting before continuing…"),StatusIcon:Zr,showDots:!1};case"acting_on_page":return{label:t("Acting on the page…"),StatusIcon:Zr,showDots:!0};case"analyzing":{const n=e.iteration;return{label:n&&n>1?I(t,"Analyzing results (step {step})…",{step:n}):t("Analyzing results…"),StatusIcon:Zr,showDots:!1}}case"preparing":return{label:ua(e.phase,t),StatusIcon:br,showDots:!1};case"context_compaction":return{label:t("Compacting conversation context…"),StatusIcon:Zr,showDots:!1};case"persisting":return{label:t("Saving response…"),StatusIcon:Tr,showDots:!1};case"mention_answering":{const n=e.agentName;return{label:n?I(t,"{agent} is answering…",{agent:n}):t("The agent is answering…"),StatusIcon:ao,showDots:!0}}case"steering":return{label:t("Incorporating your message…"),StatusIcon:Zr,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:br,showDots:!0};case"consulting":{if(e.consult)return{label:ha(e.consult,t,n),StatusIcon:ao,showDots:!1};const r=e.tools?.[0];return{label:r?I(t,"Consulting {agent}…",{agent:r}):t("Consulting an agent…"),StatusIcon:ao,showDots:!1}}case"delegating":return{label:sa(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:ao,showDots:!1};case"polling":return{label:ia(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:Zr,showDots:!1};case"collecting":return{label:ca(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:Zr,showDots:!1};case"transferring":{const n=e.agentName??e.tools?.[0];return{label:n?I(t,"Transferring to {agent}…",{agent:n}):t("Transferring to another agent…"),StatusIcon:zr,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:br,showDots:!1}}}function ma(e,t,n,r){return e&&n?.(e)||pa(e,t,r).label}function ga(e){return"mention_answering"===e?.status?void 0:e?.answeringAgentName}function fa(e,t,n){return t?I(e,"{agent}: {status}",{agent:t,status:n}):n}function va(e,t,n,r){return fa(t,ga(e),ma(e,t,n,r))}function wa(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/#{1,6}\s+/g,"").replace(/^[ \t]*[-*>]+[ \t]*/gm,"").replace(/[ \t]+/g," ").replace(/\n{3,}/g,"\n\n").trim()}function ba({text:n,action:r}){const o=s(null),[i,l]=a(!1);return c(()=>{const e=o.current;e&&(e.scrollTop=e.scrollHeight,l(e.scrollHeight>e.clientHeight+1))},[n]),e("div",{className:"filigran-chat-reasoning ml-11 mt-2.5 max-w-[75%] rounded-md border-l-2 bg-[var(--chat-accent)]/[0.03] py-2 pl-3 pr-3",children:[r&&t("div",{className:"float-right -mr-2 -mt-1 ml-2",children:r}),t("div",{ref:o,className:"max-h-40 overflow-hidden"+(i?" [-webkit-mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)] [mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]":""),children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-xs leading-5 chat-text-secondary-500/45",children:n})})]})}function ya(e){const t=Math.floor(e);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function xa(e,t,n=0){const[r,o]=a(null);return c(()=>{if(o(null),!e)return;const r=window.setTimeout(()=>o(n),t);return()=>window.clearTimeout(r)},[e,t,n]),e&&r===n}const ka=({agentStatus:r,logoIcon:o,t:s,miniGameEnabled:l=!0,onPlayWaitingGame:d,waitingGameUrl:u,keepEndInView:h,onSkipWait:p,statusLabel:m,waitingMessages:g,renderWaitingPanel:f,renderReasoningAction:v,toolLabels:w})=>{const b=pa(r,s,w),{StatusIcon:y,showDots:x}=b,k=ma(r,s,m,w),C=ga(r),N=r?.thinkingContent,S=r?.elapsedStartMs,T="wait_start"===r?.status?r.waitStartMs:void 0,A=S??T,[I,E]=a(()=>Date.now());c(()=>{if(null==A)return;E(Date.now());const e=window.setInterval(()=>E(Date.now()),1e3);return()=>window.clearInterval(e)},[A]);const z=r?.waitSeconds,R=null!=T&&null!=z?Math.max(0,z-(I-T)/1e3):void 0,M=null!=S?Math.max(0,(I-S)/1e3):r?.elapsedS,D="number"==typeof M&&M>=15,L=i(()=>function(e){if(e.length<=6e3)return wa(e);const t=[];let n=0;for(let r=e.indexOf("```");-1!==r;r=e.indexOf("```",n)){const o=e.indexOf("```",r+3);if(-1===o)break;t.push([n,r]),n=o+3}t.push([n,e.length]);const r=[];let o=6e3;for(let n=t.length-1;n>=0&&o>0;n--){const[a,s]=t[n],i=Math.max(a,s-o);r.push(e.slice(i,s)),o-=s-i+1}let a=r.reverse().join(" ");if(o<=0){const e=a.indexOf("\n\n");-1!==e&&e<a.length/2&&(a=a.slice(e+2))}return wa(a)}(N??""),[N]),_=L.length>=3,P=xa(l&&!_,5e3),j=xa(l&&_,1e4,N?.length??0),$=_?j:P,U=_&&!$?B(v):null,O=null==U||!1===U?null:t(ra,{label:"A reasoning window action",resetKey:"",fallback:null,children:U});return e(n,{children:[e("div",{className:"flex gap-3 items-center justify-start",children:[t("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-[var(--chat-accent)]/15 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:o})}),e("div",{className:"filigran-chat-active-border rounded-lg chat-surface-subtle-50/3 px-4 py-3 relative overflow-hidden",children:[t("div",{className:"absolute inset-0 bg-gradient-to-r from-[var(--chat-accent)]/[0.03] via-transparent to-[var(--chat-accent)]/[0.03] animate-pulse pointer-events-none"}),e("div",{className:"relative flex items-center gap-2.5",children:[x?t("div",{className:"flex gap-[3px] items-center h-3.5 w-3.5 justify-center",children:[0,.15,.3].map((e,n)=>t("span",{className:"h-[5px] w-[5px] rounded-full bg-[var(--chat-accent)]/50",style:{animation:`chat-dot 1s ease-in-out infinite ${e}s`}},n))}):t(y,{size:14,className:"text-[var(--chat-accent)] animate-pulse transition-all duration-300"}),C&&e(n,{children:[t("span",{className:"sr-only",children:fa(s,C,k)}),t("span",{"aria-hidden":"true",className:"text-xs font-medium text-[var(--chat-accent)]/80 shrink-0",children:C})]}),t("span",{"aria-hidden":!!C||void 0,className:"text-sm chat-text-secondary-500/50 transition-all duration-300",children:k}),void 0!==R?t("span",{className:"text-xs chat-text-muted-400/30 tabular-nums shrink-0",children:ya(Math.ceil(R))}):D&&t("span",{className:"text-xs chat-text-muted-400/30 tabular-nums shrink-0",children:ya(M)}),"wait_start"===r?.status&&p&&t("button",{type:"button",onClick:p,className:"ml-1 shrink-0 rounded-md border border-[var(--chat-accent)]/40 px-2 py-0.5 text-xs text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors",children:s("Continue now")})]})]})]}),$?t(na,{t:s,enabled:l,onPlay:d,playUrl:u,keepEndInView:h,messages:g,content:f?.()}):_?t(ba,{text:L,action:O}):null]})},Ca=b().use(w).use(v).freeze();function Na(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some(Na);default:return!1}}function Sa(e,t){return e.lastIndexOf("\n",t-1)+1}function Ta(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(Sa(e,t-1),t-1).trim()}function Aa(e,t,n){const r=e.slice(t,n).split("\n");for(let e=r.length-1;e>=0;e--)if(r[e].trim())return/^(?: {4}|\t)/.test(r[e]);return!1}class Ia{last=null;split(e){return this.last?.source!==e&&(this.last=function(e,t){if(!e.trim())return function(e){return{source:e,blocks:e?[e]:[],starts:e?[0]:[],settled:0,firstDefinition:-1}}(e);const n=t&&t.settled>0&&e.startsWith(t.source)?t.settled:0,r=n?t.starts[n]:0,o=e.slice(r),a=t&&n?t.starts.slice(0,n):[];let s=t&&n&&t.firstDefinition<n?t.firstDefinition:-1;a.push(r);for(const t of Ca.parse(o).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+Sa(o,n),s=a[a.length-1];t>s&&!Aa(e,s,t)&&a.push(t)}s<0&&Na(t)&&(s=a.length-1)}let i=n;for(let t=a.length-1;t>n;t--)if(Ta(e,a[t])){i=t;break}const c=s<0?a.map((t,n)=>e.slice(t,a[n+1]??e.length)):[e];return{source:e,blocks:c,starts:a,settled:i,firstDefinition:s}}(e,this.last)),this.last.blocks}}const Ea=r({copiedBlock:null,onCopyCode:()=>{},streaming:!1,t:A});function za({draw:e,block:r}){const o=e();return null==o||!1===o?t(n,{children:r}):t("div",{className:"my-3",children:o})}const Ra={p:({children:e})=>t("p",{className:"mb-3 last:mb-0 leading-7 break-words chat-answer-text",children:e}),pre:({children:e})=>t(n,{children:e}),code:({className:n,children:r})=>{const{copiedBlock:a,onCopyCode:s,codeBlockRenderers:i,streaming:c,t:l}=o(Ea),d=/(?:^|\s)language-(\S+)/.exec(n||""),u=String(r).replace(/\n$/,""),h=d?i?.[d[1].toLowerCase()]:void 0;if(d||u.includes("\n")){const n=e("div",{className:"my-3 rounded-lg border chat-border-200/10 overflow-hidden chat-code-block",children:[e("div",{className:"flex items-center justify-between px-3 py-1.5 border-b chat-border-200/10 chat-surface-subtle-100/3",children:[t("span",{className:"text-[0.7rem] chat-text-muted-500/40 font-mono",children:d?.[1]??"plaintext"}),t("button",{type:"button",onClick:()=>s(u),"aria-label":l(a===u?"Copied":"Copy code"),className:"p-0.5 rounded-sm hover:chat-surface-hover-200/10 transition-colors",children:a===u?t(xr,{size:14,className:"text-green-500"}):t(Sr,{size:14,className:"chat-text-muted-400/40"})})]}),t("pre",{className:"m-0 px-3 py-2 overflow-x-auto",children:t("code",{className:"chat-code leading-[1.7] chat-text-800/90 whitespace-pre",children:u})})]});return h?t(ra,{label:"A chat code block renderer",resetKey:`${u}\0${c}`,fallback:t(aa,{t:l}),children:t(za,{draw:()=>h(u,{streaming:c}),block:n})}):n}return t("code",{className:"chat-code-inline chat-code px-1.5 py-0.5 rounded-sm text-[var(--chat-accent)]",children:r})},ul:({children:e})=>t("ul",{className:"list-disc pl-5 mb-3 chat-answer-text [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),ol:({children:e})=>t("ol",{className:"list-decimal pl-5 mb-3 chat-answer-text [&_li]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),li:({children:e})=>t("li",{className:"leading-7 break-words",children:e}),strong:({children:e})=>t("strong",{className:"font-semibold chat-text-900/100",children:e}),em:({children:e})=>t("em",{className:"italic",children:e}),hr:()=>t("hr",{className:"my-4 chat-border-200/10"}),blockquote:({children:e})=>t("blockquote",{className:"my-3 border-l-2 border-[var(--chat-accent)]/30 bg-[var(--chat-accent)]/[0.03] pl-4 pr-3 py-2 rounded-r-md italic chat-text-secondary-500/60",children:e}),a:({href:e,children:n})=>{const{onRelativeLinkClick:r}=o(Ea),a=st(e),s=null!==a&&!!r,i=!(s||(e=>!!e&&!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(e)&&null!==a);return t("a",{href:e,onClick:e=>{s&&(e.preventDefault(),r(a))},target:i?"_blank":void 0,rel:i?"noopener noreferrer":void 0,className:"text-[var(--chat-accent)] underline underline-offset-2 hover:brightness-125",children:n})},img:({src:e,alt:n})=>{const{requestHeaders:r,t:a}=o(Ea);return"string"==typeof e&&e?t(ea,{src:e,alt:n||"",requestHeaders:r,t:a},e):null},h1:({children:e})=>t("h1",{className:"mt-4 first:mt-0 mb-2 font-bold chat-answer-heading-1 chat-text-900/100",children:e}),h2:({children:e})=>t("h2",{className:"mt-3 first:mt-0 mb-2 font-bold chat-answer-heading-2 chat-text-900/100",children:e}),h3:({children:e})=>t("h3",{className:"mt-3 first:mt-0 mb-1.5 font-semibold chat-answer-heading-3 chat-text-900/100",children:e}),table:({children:e})=>t("div",{className:"my-3 overflow-x-auto rounded-lg border chat-border-200/10",children:t("table",{className:"w-full border-collapse text-xs",children:e})}),tr:({children:e})=>t("tr",{className:"transition-colors hover:chat-surface-hover-50/2",children:e}),th:({children:e})=>t("th",{className:"px-3 py-2 text-left font-semibold chat-surface-subtle-50/4 border-b chat-border-200/10 chat-text-900/100",children:e}),td:({children:e})=>t("td",{className:"px-3 py-2 border-b chat-border-200/10 chat-text-secondary-700/80",children:e})},Ma=[v,k],Da=m(({source:e})=>t(x,{remarkPlugins:Ma,urlTransform:T,components:Ra,children:e}));Da.displayName="MarkdownBody";const La=({source:e})=>{const[r]=a(()=>new Ia),o=i(()=>r.split(e),[r,e]);return t(n,{children:o.map((e,n)=>t(Da,{source:e},n))})},_a=m(({codeBlockRenderers:e,...n})=>{const{content:r,streaming:o=!1,onRelativeLinkClick:s,requestHeaders:c,t:d=A}=n,[u,h]=a(null),[p,m]=a(o);o&&!p&&m(!0);const g=i(()=>N(r),[r]),f=l(e=>{navigator.clipboard.writeText(e),h(e),setTimeout(()=>h(null),2e3)},[]),v=i(()=>({copiedBlock:u,onCopyCode:f,onRelativeLinkClick:s,requestHeaders:c,codeBlockRenderers:e,streaming:o,t:d}),[u,f,s,c,e,o,d]);return t(Ea.Provider,{value:v,children:t(p?La:Da,{source:g})})});_a.displayName="MarkdownMessage";function Pa(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function ja(e,t){return la(e,t)??e.replace(/_/g," ")}const $a=({entry:n,index:r,toolLabels:o,t:s})=>{const[c,l]=a(!1),d=i(()=>Pa(n.input),[n.input]),u=i(()=>Pa(n.output),[n.output]),h=!!d&&"{}"!==d;return e("div",{className:"border chat-border-200/6 rounded-md overflow-hidden",children:[e("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":c,className:"w-full flex items-center gap-2.5 px-3 py-2 hover:chat-surface-hover-50/3 transition-colors text-left",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),n.success?t(yr,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(uo,{size:12,className:"shrink-0 text-red-500 dark:text-red-400"}),t("span",{className:"flex-1 min-w-0 text-[0.8125rem] chat-text-secondary-700/80 truncate font-mono",children:ja(n.name,o)}),t(kr,{size:14,className:"shrink-0 chat-text-muted-400/50 transition-transform duration-200 "+(c?"rotate-180":"")})]}),c&&e("div",{className:"border-t chat-border-200/6",children:[h&&e("div",{className:"px-3 py-2 border-b chat-border-100/4 chat-detail-surface",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] chat-text-muted-500/40 uppercase tracking-wider font-medium",children:s("Input")}),t("pre",{className:"m-0 text-[0.7rem] chat-text-secondary-600/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-40 overflow-y-auto filigran-chat-scrollable",children:d})]}),e("div",{className:"px-3 py-2 chat-detail-surface",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] chat-text-muted-500/40 uppercase tracking-wider font-medium",children:s("Output")}),t("pre",{className:"m-0 text-[0.7rem] chat-text-secondary-600/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-48 overflow-y-auto filigran-chat-scrollable",children:u||s("(no output)")})]})]})]})},Ua=({msg:n,onClose:r,toolLabels:o,t:i})=>{const l=s(null),d=s(null),u=s(null),[h,p]=a(null);c(()=>{p(z(l.current))},[]),c(()=>{const e=e=>{if("Escape"===e.key)return void r();if("Tab"!==e.key)return;const t=u.current;if(!t)return;const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const o=n[0],a=n[n.length-1],s=document.activeElement;e.shiftKey?s!==o&&t.contains(s)||(e.preventDefault(),a.focus()):s!==a&&t.contains(s)||(e.preventDefault(),o.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r]),c(()=>{if(!h)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return d.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[h]);const m=n.toolCallCount??n.toolCallTrace?.length??n.toolNames?.length??0,g=n.toolNames??[],f=n.iterations??1,v=n.transferChain??[],w=n.toolCallTrace??[],b=(n.reasoning??"").trim(),x=[f>1?I(i,"{count} iterations",{count:f}):"",1===m?i("1 tool call"):I(i,"{count} tool calls",{count:m}),1===v.length?i("1 transfer"):v.length>1?I(i,"{count} transfers",{count:v.length}):""].filter(Boolean);return t("span",{ref:l,className:"hidden",children:h&&y(t("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4",onClick:r,role:"presentation",children:e("div",{ref:u,role:"dialog","aria-modal":"true","aria-label":i("Reasoning details"),onClick:e=>e.stopPropagation(),className:"w-full max-w-md max-h-full flex flex-col rounded-xl border chat-border-200/10 chat-surface-raised shadow-[0_8px_32px_rgba(0,0,0,0.25)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.6)]",children:[e("div",{className:"px-4 pt-3.5 pb-2.5 border-b chat-border-200/10",children:[e("div",{className:"flex items-center gap-2",children:[t(lo,{size:15,className:"text-[var(--chat-accent)]"}),t("span",{className:"flex-1 text-[0.875rem] font-semibold chat-text-900/100",children:i("Reasoning details")}),t("button",{ref:d,type:"button",onClick:r,"aria-label":i("Close"),className:"w-7 h-7 flex items-center justify-center rounded-lg hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(Nr,{size:16})})]}),t("p",{className:"m-0 mt-0.5 text-[0.72rem] chat-text-muted-500/40",children:x.join(" · ")})]}),e("div",{className:"px-4 py-3 overflow-y-auto filigran-chat-scrollable flex flex-col gap-3",children:[n.isTruncated&&e("div",{className:"flex items-start gap-2.5 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-2.5 text-[0.72rem] text-amber-600 dark:text-amber-300/90",children:[t(gr,{size:14,className:"shrink-0 mt-0.5 text-amber-500 dark:text-amber-400"}),e("span",{children:[t("span",{className:"font-semibold",children:i("Turn limit reached.")})," ",i("The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.")]})]}),n.interrupted&&e("div",{className:"flex items-start gap-2.5 rounded-md border border-amber-500/20 bg-amber-500/5 px-3 py-2.5 text-[0.72rem] text-amber-600 dark:text-amber-300/90",children:[t(gr,{size:14,className:"shrink-0 mt-0.5 text-amber-500 dark:text-amber-400"}),e("span",{children:[t("span",{className:"font-semibold",children:i("Interrupted by a server restart.")})," ",i("The server restarted while this turn was running, so it stopped before it could finish.")]})]}),b&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(br,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium chat-text-secondary-500/50",children:i("Model reasoning")})]}),t("div",{className:"rounded-md border chat-border-200/6 chat-detail-surface px-2.5 py-2 max-h-44 overflow-y-auto filigran-chat-scrollable",children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-[0.72rem] leading-5 chat-text-secondary-500/45",children:wa(b)})})]}),w.length>0?t("div",{className:"flex flex-col gap-1.5",children:w.map((e,n)=>t($a,{entry:e,index:n,toolLabels:o,t:i},`${e.name}-${n}`))}):g.length>0&&t("div",{children:g.map((n,r)=>e("div",{className:"flex items-center gap-3 py-2 border-b chat-border-100/4 last:border-0",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),t(lo,{size:12,className:"shrink-0 chat-text-muted-400/50"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/80 truncate font-mono",children:ja(n,o)})]},`${n}-${r}`))}),v.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(fr,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium chat-text-secondary-500/50",children:i("Transfer chain")})]}),t("div",{className:"flex items-center gap-1.5 flex-wrap",children:v.map((n,r)=>e("div",{className:"flex items-center gap-1.5",children:[r>0&&t("span",{className:"chat-text-muted-300/30 text-[0.72rem]",children:"→"}),e("span",{className:"inline-flex items-center gap-1 rounded-md bg-[var(--chat-accent)]/10 px-2 py-0.5 text-[0.72rem] font-medium text-[var(--chat-accent)]",children:[t(wr,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),h)})},Oa=e=>`${e.filename.trim()}\n${(e.contentType||e.type||"").split(";")[0].trim().toLowerCase()}`;const Wa=r(()=>{}),qa="inline-flex items-center gap-1 rounded-md text-[0.7rem] chat-text-muted-400/40 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]";function Fa({url:e,requestHeaders:n}){const{src:r,status:o}=Zo(e??null,n),[s,i]=a(null);return t("span",{className:"flex h-12 w-24 shrink-0 items-center justify-center overflow-hidden rounded-md border chat-border-200/10",children:"ready"===o&&null!==r&&s!==r?t("img",{src:r,alt:"",loading:"lazy",onError:()=>i(r),className:"h-full w-full object-contain"}):"loading"===o?t("span",{className:"h-full w-full animate-pulse chat-surface-subtle-50/4"}):t(Wr,{size:16,className:"chat-text-muted-400/40"})})}function Ha({files:n,requestHeaders:r,t:i}){const[c,l]=a(!1),[d,p]=a(!1),m=h(),g=s(null),f=o(Wa);return u(()=>{c&&f()},[c,f]),e("div",{className:"pl-1",children:[e("button",{ref:g,type:"button","aria-expanded":c,"aria-controls":m,onClick:()=>{l(!c),p(!0)},className:qa,children:[t(kr,{size:13,className:"transition-transform"+(c?" rotate-180":"")}),I(i,"Working files ({count})",{count:n.length})]}),t("ul",{id:m,hidden:!c,className:"mt-1.5 flex flex-col gap-1.5",children:n.map(n=>e("li",{className:"flex items-center gap-1.5",children:[d&&n.isImage&&t(Fa,{url:n.imageUrl,requestHeaders:r}),n.card,n.superseded&&t("span",{className:"shrink-0 text-[0.7rem] chat-text-muted-400/40",children:i("Superseded")})]},n.key))}),c&&n.length>=8&&e("button",{type:"button","aria-controls":m,onClick:()=>{l(!1),g.current?.focus({preventScroll:!0}),g.current?.scrollIntoView({block:"nearest"})},className:`mt-1.5 ${qa}`,children:[t(kr,{size:13,className:"rotate-180"}),i("Show less")]})]})}const Ba=e=>e.parentElement,Va=e=>getComputedStyle(e).overflowY;function Ka(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function Ga(e){const t=e.lastIndexOf(".");if(t<=0||t===e.length-1)return;const n=e.slice(t+1);return n.length<=8?n.toUpperCase():void 0}const Ya=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);function Xa(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&Ya.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&Ya.has(e.filename.slice(n+1).toLowerCase())}const Ja="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",Qa="p-1 rounded-lg transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",Za="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",es=`opacity-0 ${Ja} ${Za}`,ts=`opacity-50 ${Ja} ${Za}`,ns="opacity-100 text-[var(--chat-accent)]",rs=({timestamp:n,locale:r})=>{const o=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:Uo(t,(o=n,(r=e).getFullYear()===o.getFullYear()&&r.getMonth()===o.getMonth()&&r.getDate()===o.getDate()?"time":e.getFullYear()===n.getFullYear()?"date":"dateWithYear")).format(e),full:Uo(t,"full").format(e),iso:e.toISOString()}:null;var r,o}(n,r);return o?t(wo,{title:o.full,children:e("time",{dateTime:o.iso,className:"px-1 text-[0.65rem] tabular-nums chat-text-muted-400/40 select-none",children:[t("span",{"aria-hidden":"true",children:o.label}),t("span",{className:"sr-only",children:o.full})]})}):null},os=({text:e,label:n,t:r})=>{const[o,s]=a(!1),i=o?r("Copied!"):n;return t(wo,{title:i,children:t("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(e||""),s(!0),setTimeout(()=>s(!1),2e3)}catch{}},"aria-label":i,className:`${Qa} ${o?"opacity-100 text-green-500 dark:text-green-400":es}`,children:t(o?xr:Sr,{size:14})})})},as=({value:r,locked:o,pending:a,onChange:s,downRef:i,t:c})=>{const l=h(),d=o||a,u=(e,n)=>{const a=r===e;if(o&&!a)return null;const u="up"===e?ro:no;return t(wo,{title:o?c("Feedback already submitted"):n,children:t("button",{ref:"down"===e?i:void 0,type:"button",onClick:()=>{d||s(a?null:e)},"aria-label":n,"aria-pressed":a,"aria-disabled":d||void 0,"aria-describedby":o?l:void 0,className:`${Qa} ${a?ns:es} ${d?"cursor-default":""}`,children:t(u,{size:14,filled:a})})})};return e(n,{children:[u("up",c("Good response")),u("down",c("Bad response")),o&&t("span",{id:l,className:"sr-only",children:c("Feedback already submitted")})]})},ss=({pending:n,onSave:r,onSkip:o,t:s})=>{const[i,c]=a(""),l=h(),d=!n&&!!i.trim();return e("div",{className:"mt-1 flex w-full max-w-[90%] flex-col gap-1.5 rounded-lg border chat-border-200/10 chat-surface-subtle-50/4 p-2",children:[t("label",{htmlFor:l,className:"text-[0.7rem] chat-text-secondary-600/60",children:s("Tell us what went wrong (optional)")}),t("textarea",{id:l,autoFocus:!0,rows:2,maxLength:2e3,value:i,readOnly:n,onChange:e=>c(e.target.value),onKeyDown:e=>{So(e)||("Escape"===e.key?(e.preventDefault(),e.stopPropagation(),n||o()):"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),d&&r(i)))},placeholder:s("What could be improved?"),className:"w-full resize-y rounded-md border chat-border-200/10 chat-input-surface-white/0 px-2 py-1 text-[0.75rem] leading-5 chat-text-900/100 placeholder:chat-text-muted-400/30 outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]"}),e("div",{className:"flex justify-end gap-1.5",children:[t("button",{type:"button",onClick:()=>{n||o()},"aria-disabled":n||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] chat-text-secondary-500/50 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",children:s("Skip")}),t("button",{type:"button",onClick:()=>{d&&r(i)},"aria-disabled":!d||void 0,className:"rounded-md px-2 py-0.5 text-[0.7rem] text-white bg-[var(--chat-accent)] transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)] "+(d?"hover:opacity-90":"opacity-50 cursor-default"),children:s("Save")})]})]})},is=({speaking:e,onToggle:n,t:r})=>{const o=r(e?"Stop reading":"Read aloud");return t(wo,{title:o,children:t("button",{type:"button",onClick:n,"aria-label":o,className:`${Qa} ${e?ns:es}`,children:t(e?co:io,{size:14})})})},cs=[],ls=new Set(["PRESENTATION","REPORT","VIDEO"]),ds=m(({msg:r,isStreaming:o,agentName:c,logoIcon:l,onRelativeLinkClick:d,onDownloadFile:h,resolveAttachmentUrl:p,onDownloadArtifact:m,onRefreshArtifact:g,requestHeaders:f,feedbackMode:v,feedback:w,onRate:b,onSaveComment:y,onSkipComment:x,locale:k,canSpeak:C,isSpeaking:N,onToggleSpeech:S,openableConversationIds:T,onOpenConversation:A,markerRenderers:I,markerKindList:E=cs,codeBlockRenderers:z,transformMessageText:R,onArtifactOpen:M,renderMessageExtras:D,messageFooterActions:L,collapseUnnamedFiles:_,toolLabels:P,t:j})=>{const[$,F]=a(!1),H="assistant"===r.role,V=i(()=>B(R,r.content,r)??r.content,[R,r]),K=i(()=>H?"":function(e){return e.trimEnd().replace(/^(?:[ \t]*\r?\n)+/,"")}(V),[H,V]),G=!V,Y=s(null),X=!!w?.commentOpen,J=s(X);u(()=>{const e=J.current&&!X;J.current=X,!e||document.activeElement&&document.activeElement!==document.body||Y.current?.focus()},[X]);const Q=(e,n)=>{const r=p&&Xa(e)?p(e):void 0;return r?t(ea,{src:r,alt:e.filename,requestHeaders:f,maxHeightClass:"max-h-[200px]",onDownload:h?()=>h(e):void 0,t:j},n):ee(e,n)},ee=(n,r)=>{const o="working_file"===n.fileTag,a=!(s=n.size)||s<=0?"":s<1024?`${s} B`:s<1048576?`${(s/1024).toFixed(0)} KB`:`${(s/1048576).toFixed(1)} MB`;var s;return e("button",{type:"button",onClick:()=>h?.(n),title:j("Download"),className:"group flex items-center gap-2 text-left rounded-lg border px-2.5 py-1.5 transition-colors cursor-pointer max-w-[90%] "+(o?"chat-border-200/10 bg-transparent":"chat-border-200/10 chat-surface-subtle-50/4 hover:border-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/5"),children:[t("span",{className:"shrink-0 "+(o?"chat-text-muted-400/40":"text-[var(--chat-accent)]"),children:t(Rr,{size:16})}),e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"truncate text-[0.75rem] chat-text-900/100",children:n.filename}),(n.type||a)&&t("span",{className:"text-[0.65rem] chat-text-muted-400/40 uppercase",children:[n.type,a].filter(Boolean).join(" · ")})]}),t("span",{className:"shrink-0 chat-text-muted-400/30 group-hover:text-[var(--chat-accent)]",children:t(Ir,{size:15})})]},r)},te=(n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border chat-border-200/10 text-[0.7rem] chat-text-secondary-600/60",children:[t(Rr,{size:14}),n]},r),ne=(e,n)=>t(Vo,{artifact:e,t:j,onDownload:m,onRefresh:g,onOpen:M},n),re=(e,n,a)=>{const s=I?.[e];return!s||o&&!s.renderWhileStreaming?null:t("div",{className:s.fullWidth?"w-full":"w-full max-w-[90%]",children:t(ra,{label:"A chat marker card",resetKey:`${n}\0${o}`,fallback:t(aa,{t:j}),children:t(oa,{draw:()=>s.render(n,{message:r,streaming:o})})})},a)},oe=function(e){const t=new Set,n=new Map;for(const r of e)t.has(r.fileId)||(t.add(r.fileId),n.set(Oa(r),r.fileId));return new Set(e.filter(e=>n.get(Oa(e))!==e.fileId).map(e=>e.fileId))}(r.attachments??[]),ae=(e,t,n)=>{const r=Xa(e);return{key:t,card:n,isImage:r,imageUrl:r?p?.(e):void 0,superseded:oe.has(e.fileId)}},se=r.toolNames&&r.toolNames.length>0||!!(r.reasoning??"").trim()||r.toolCallTrace&&r.toolCallTrace.length>0||r.transferChain&&r.transferChain.length>0||r.isTruncated||r.interrupted,ie=!(!r.isTruncated&&!r.interrupted),ce=r.interrupted?j("Reasoning details — interrupted by a server restart"):r.isTruncated?j("Reasoning details — turn limit reached"):j("Reasoning details"),le=H&&!G&&!o,de=function(e,t=[]){if(!e)return e;const n=U(t),r=e.replace(n.complete,"").replace(n.partial,"");return r===e?e:r.replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}(V,E),ue=i(()=>le&&C?W(V,E):null,[le,C,V,E]),he=(pe=w,me=r.feedback,pe?{value:pe.value,locked:!1}:me?{value:(ge=me.rating,"positive"===ge?"up":"down"),locked:!0}:{value:null,locked:!1});var pe,me,ge;const fe=_o(r),ve=!H||o||r.stopped||ie||r.attachments?.length||r.artifacts?.length?null:function(e,t,n=[]){if(!t)return null;const r=O(e,!1,n).filter(e=>"text"!==e.type||e.value.trim()),[o]=r;return 1===r.length&&"marker"===o.type&&t[o.kind]?.standalone?{kind:o.kind,args:o.args}:null}(V,I,E);return ve?t("div",{"data-message-id":r.serverId??r.id,"data-testid":"filigran-chat-standalone-marker",className:"flex w-full",children:re(ve.kind,ve.args,"standalone")}):e("div",{"data-message-id":r.serverId??r.id,className:"group/msg flex flex-col "+(H?"items-start":"items-end"),children:[H&&e("div",{className:"flex items-center gap-1.5 mb-1",children:[t("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-3 [&>svg]:h-3",children:l})}),t("span",{className:"font-semibold text-xs chat-text-900/100",children:r.agentName??c})]}),!H&&((r.files?.length??0)>0||(r.attachments?.length??0)>0)&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end",children:(()=>{const e=[],t=new Set;return(r.files??[]).forEach((n,r)=>{!(!h||!n.fileId||"done"!==n.uploadStatus)&&n.fileId?(t.add(n.fileId),e.push(Q({fileId:n.fileId,filename:n.name,type:Ga(n.name),size:n.size,contentType:n.type},`file-${n.fileId}-${r}`))):e.push(te(n.name,`file-${r}`))}),(r.attachments??[]).forEach((n,r)=>{t.has(n.fileId)||(t.add(n.fileId),e.push(h?Q(n,`att-${n.fileId}-${r}`):te(n.filename,`att-${r}`)))}),e})()}),!H&&(r.conversationRefs?.length??0)>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end max-w-[90%]",children:r.conversationRefs.map((r,o)=>{const a=r.title||(r.key?`@${r.key}`:j("Untitled conversation")),s="inline-flex items-center gap-1 max-w-[240px] px-2 py-0.5 rounded-full border text-[0.7rem]",i=e(n,{children:[t(Br,{size:13,className:"shrink-0"}),t("span",{className:"truncate",children:a})]});return A&&T?.has(r.conversationId)?t(wo,{title:j("Open conversation"),children:t("button",{type:"button",onClick:()=>A(r.conversationId),className:`${s} border-[var(--chat-accent-40)] text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]`,children:i})},`ref-${r.conversationId}-${o}`):t(wo,{title:r.key?`@${r.key}`:"",children:t("span",{className:`${s} chat-border-200/10 chat-text-secondary-600/60`,children:i})},`ref-${r.conversationId}-${o}`)})}),H?e("div",{"data-testid":"filigran-chat-assistant-message",className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=O(V,o,E),n=new Map((r.attachments??[]).map(e=>[e.fileId,e])),a=new Map((r.artifacts??[]).map(e=>[q(e.kind,e.id),e])),s=new Set,i=new Set,c=[];e.forEach((e,r)=>{if("text"===e.type)e.value.trim()&&c.push(t("div",{className:"max-w-[90%] pl-1 py-1 text-[0.8125rem] leading-7",children:t(_a,{content:e.value,streaming:o,onRelativeLinkClick:d,requestHeaders:f,codeBlockRenderers:z,t:j})},`t-${r}`));else if("marker"===e.type){"FILE"===e.kind?s.add(e.args):ls.has(e.kind)&&i.add(q(e.kind.toLowerCase(),e.args.split("#/")[0]));const t=re(e.kind,e.args,`m-${e.kind}-${r}`);t&&c.push(t)}else if("artifact"===e.type){const t=q(e.kind,e.id),n=a.get(t);n&&!i.has(t)&&(i.add(t),c.push(ne(n,`a-${t}-${r}`)))}else if(h){const t=n.get(e.fileId);t&&(s.add(e.fileId),c.push(Q(t,`f-${e.fileId}-${r}`)))}}),(r.artifacts??[]).forEach(e=>{const t=q(e.kind,e.id);if(!i.has(t)){i.add(t);const n=e.kind.toUpperCase();if(I?.[n]){const r=re(n,e.slideRef?`${e.id}#/${e.slideRef}`:e.id,`orphan-a-${t}`);r&&c.push(r)}else c.push(ne(e,`orphan-a-${t}`))}});const l=[];if((r.attachments??[]).forEach(e=>{if(s.has(e.fileId))return;const t=`orphan-${e.fileId}`,n=!0===_||"function"==typeof _&&!!B(_,e,r);if(I?.FILE){const r=re("FILE",e.fileId,t);if(!r)return;n?l.push(ae(e,t,r)):c.push(r)}else h&&(n?l.push(ae(e,t,ee(e,t))):c.push(Q(e,t)))}),l.length&&c.push(t(Ha,{files:l,requestHeaders:f,t:j},"working-files")),0===c.length&&!o&&!r.stopped){const e=!V.trim()&&!r.attachments?.length&&!r.artifacts?.length;c.push(t("span",{className:"pl-1 text-[0.8125rem] chat-text-muted-400/40 italic",children:e?j("No response was generated. Please try again."):"..."},"empty"))}return c})(),r.stopped&&!o&&t("p",{className:"pl-1 text-[0.75rem] italic chat-text-muted-400/40",children:j("Stopped")}),!G&&o&&t("span",{className:"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-xs ml-1 animate-pulse"})]}):t("div",{"data-testid":"filigran-chat-user-message",className:"max-w-[90%] chat-user-bubble leading-6 whitespace-pre-wrap break-words",children:K}),D&&t("div",{className:"w-full "+(H?"":"flex justify-end"),children:D(r,{streaming:o})}),!H&&e("div",{className:"mt-0.5 flex items-center justify-end gap-0.5 chat-text-muted-400/40",children:[!!K&&t(os,{text:K,label:j("Copy message"),t:j}),!r.timestampUnknown&&t(rs,{timestamp:r.timestamp,locale:k})]}),(le||H&&!o&&ie)&&e("div",{className:"mt-0.5 flex flex-wrap items-center gap-0.5 chat-text-muted-400/40",children:[!r.timestampUnknown&&t(rs,{timestamp:r.timestamp,locale:k}),se&&t(wo,{title:ce,children:t("button",{type:"button",onClick:()=>F(e=>!e),className:`${Qa} ${ie?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":ts}`,"aria-label":ce,"aria-haspopup":"dialog","aria-expanded":$,children:t(ie?gr:qr,{size:14})})}),le&&e(n,{children:[t(os,{text:de,label:j("Copy response"),t:j}),v&&t(as,{value:he.value,locked:he.locked,pending:!!w?.pending,onChange:e=>b(r,e,w),downRef:Y,t:j}),ue&&(we=ue,we.some(e=>/[\p{L}\p{N}]/u.test(e.replace(Z,""))))&&t(is,{speaking:N,onToggle:()=>S(fe,ue),t:j}),L?.(r,{streaming:o})]})]}),le&&w?.commentOpen&&t(ss,{pending:w.pending,onSave:e=>y(r,e,w),onSkip:()=>x(r,w),t:j}),le&&w?.error&&t("p",{role:"alert",className:"mt-0.5 pl-1 text-[0.7rem] text-red-600 dark:text-red-400",children:w.error}),$&&t(Ua,{msg:r,onClose:()=>F(!1),toolLabels:P,t:j})]});var we});ds.displayName="MessageRow";const us=({messages:n,isLoading:r,agentStatus:o,agentName:h,logoIcon:p,onRelativeLinkClick:m,onDownloadFile:g,resolveAttachmentUrl:f,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:b,miniGameEnabled:y=!0,onPlayWaitingGame:x,waitingGameUrl:k,onMessageFeedback:C,isResumingAfterDecision:N,onSkipWait:S,pendingApprovals:T,onSubmitApprovalDecisions:A,isSubmittingApproval:I,approvalError:E,feedbackUrl:z,conversationId:R,locale:M,openableConversationIds:D,onOpenConversation:L,markerRenderers:_,markerKindList:P,codeBlockRenderers:j,transformMessageText:$,onArtifactOpen:U,renderMessageExtras:O,replaceMessage:W,messageFooterActions:q,transcriptFooter:F,onLoadEarlier:H,collapseUnnamedFiles:B,ttsRoute:V,thinking:K,t:G})=>{const Y=s(null),[X,J]=a(150),{entries:Z,rate:ne,saveComment:re,skipComment:oe}=function({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:o}){const i=an(),[c,u]=a(()=>({scope:t,entries:{}}));let h=c.entries;c.scope!==t&&(h={},u({scope:t,entries:h}));const p=s({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:o});d(()=>{p.current={feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:o}});const m=s(0),g=l((e,t)=>u(n=>({...n,entries:{...n.entries,[e]:t}})),[]),f=l((e,t,n)=>u(r=>{const o=r.entries[e];return o&&o.seq===t?{...r,entries:{...r.entries,[e]:n(o)}}:r}),[]),v=l(async(e,t,n)=>{const{feedbackUrl:r,conversationId:o,requestHeaders:a,onMessageFeedback:s,t:c}=p.current,l=_o(e),d=++m.current;if(!r)return g(l,{seq:d,value:t,comment:null,pending:!1,error:null,commentOpen:!1}),void s?.(l,t,e);if(o&&e.serverId){if(g(l,{seq:d,value:t,comment:null,pending:!0,error:null,commentOpen:!1}),!await pe(i,r,o,e.serverId,t?{rating:le(t),comment:null}:null,a)){const e=c(t?"Could not submit feedback.":"Could not retract feedback.");return void f(l,d,()=>n?{...n,seq:d,pending:!1,commentOpen:!1,error:e}:{seq:d,value:null,comment:null,pending:!1,error:e,commentOpen:!1})}f(l,d,e=>({...e,pending:!1,commentOpen:"down"===t})),p.current.onMessageFeedback?.(l,t,e)}},[g,f]),w=l(async(e,t,n)=>{const{feedbackUrl:r,conversationId:o,requestHeaders:a,t:s}=p.current,c=_o(e),l=ue(t);if(!(r&&o&&e.serverId&&l))return void g(c,{...n,commentOpen:!1,error:null});const d=++m.current;g(c,{...n,seq:d,pending:!0,error:null});const u=await pe(i,r,o,e.serverId,{rating:"negative",comment:l},a);f(c,d,e=>u?{...e,comment:l,pending:!1,commentOpen:!1}:{...e,pending:!1,error:s("Could not submit feedback.")})},[g,f]);return{entries:h,rate:v,saveComment:w,skipComment:l((e,t)=>g(_o(e),{...t,commentOpen:!1,error:null}),[g])}}({feedbackUrl:z,conversationId:R,requestHeaders:b,onMessageFeedback:C,t:G}),ae=function(e,t){const n=an(),[r]=a(Po),o=r||!!t,[i,u]=a(null),h=s(null),p=s(e),m=s(t);d(()=>{p.current=e,m.current=t});const g=s(null),f=l(()=>{const e=g.current;e&&(g.current=null,e.abort.abort(),e.audio?.pause(),e.url&&URL.revokeObjectURL(e.url),u(t=>t===e.id?null:t))},[]),v=l(()=>r?(h.current??=function(e,t,n){let r=0,o=null;const a=e=>{e===r&&null!==o&&(r+=1,o=null,n(null))},s=()=>{null!==o&&(r+=1,o=null,e.cancel(),n(null))};return{speak:(i,c,l)=>{s();const d=c.filter(e=>e.trim());if(!d.length)return!1;const u=r;return o=i,n(i),d.forEach((n,o)=>{const s=o===d.length-1,i=t(n,{lang:l,onEnd:()=>{s&&a(u)},onError:()=>{u===r&&(a(u),e.cancel())}});e.speak(i)}),!0},stop:s,get speakingId(){return o}}}(window.speechSynthesis,(e,{lang:t,onEnd:n,onError:r})=>{const o=new SpeechSynthesisUtterance(e);return t&&(o.lang=t),o.onend=n,o.onerror=r,o},u),h.current):null,[r]),w=l((e,t)=>v()?.speak(e,ee(t),p.current),[v]),b=l(async(e,t,r)=>{const o=new AbortController,a={id:t,abort:o};g.current=a,u(t);const s=ee(r,4096),i=new Audio;a.audio=i;let c=0;try{for await(const t of te(n,e,s,o.signal)){if(g.current!==a)return;if(!t)throw new Error("TTS failed");a.url&&URL.revokeObjectURL(a.url),a.url=URL.createObjectURL(t);const e=new Promise(e=>{i.onended=()=>e(!0),i.onerror=()=>e(!1)});if(i.src=a.url,await i.play(),!await e)throw new Error("TTS playback failed");if(g.current!==a)return;c+=1}f()}catch(e){if(g.current!==a||e instanceof DOMException&&"AbortError"===e.name)return;f(),w(t,s.slice(c).join(" "))}},[w,f]),y=l((e,t)=>{const n=g.current?.id??h.current?.speakingId??null;if(f(),h.current?.stop(),n===e)return;const r=Q(t),o=m.current;o?b(o,e,r):w(e,r)},[w,b,f]),x=l(()=>{f(),h.current?.stop()},[f]);return c(()=>()=>x(),[x]),{supported:o,speakingId:i,toggle:y,stop:x}}(M,V),[se,ie]=a(!0),[ce]=a(()=>function(e,t=Oo,n){let r=!0;const o=e=>{e!==r&&(r=e,n?.(e))};let a=0,s=null;const i=e=>{e.scrollTo({top:e.scrollHeight,behavior:"instant"}),a=e.scrollTop},c=()=>{s&&(t.clear(s.timer),s=null)},l=()=>{c();const t=e();t&&r&&i(t)};return{get following(){return r},reveal:()=>{const n=e();if(!n)return;o(!0),c();const r=Math.max(0,n.scrollHeight-n.clientHeight);n.scrollTo({top:n.scrollHeight,behavior:"smooth"}),a=n.scrollTop,a>=r-1||(s={target:r,timer:t.set(l,1e3)})},keepUp:()=>{const t=e();t&&r&&!s&&i(t)},onScroll:()=>{const t=e();if(!t)return;const n=t.scrollTop,r=n<a-1,i=n>a+1;(r||i)&&(a=n);const c=t.scrollHeight-n-t.clientHeight;r?o(c<=1):i&&c<=100&&o(!0),s&&(r||n>=s.target-1||c<=1)&&l()},leave:()=>{const t=e();!t||t.scrollTop<=0||(o(!1),c())},stay:()=>{const t=e();!t||s||t.scrollHeight-t.scrollTop-t.clientHeight<=1||(o(!1),c())}}}(()=>Y.current,void 0,ie));c(()=>{const e=Y.current;return e?function(e,t,n=globalThis){const{ResizeObserver:r,MutationObserver:o}=n;if(!r)return()=>{};const a=new r(()=>t());a.observe(e);for(const t of Array.from(e.children))a.observe(t);const s=o?new o(e=>{for(const t of e)for(const e of Array.from(t.addedNodes))1===e.nodeType&&a.observe(e)}):null;return s?.observe(e,{childList:!0}),()=>{a.disconnect(),s?.disconnect()}}(e,ce.keepUp):void 0},[ce]);const he=s(null),me=(e,t)=>{t instanceof Element&&e.contains(t)&&(function(e,t,n,r){for(let o=e;o&&o!==t;o=n(o))if(o.scrollTop>0&&o.scrollHeight>o.clientHeight&&Fo.has(r(o)))return!0;return!1}(t,e,Ba,Va)||ce.leave())},ge=n[0]?.id,fe=s(null),[ve,we]=a(void 0),be=void 0!==ve&&ve===(R??null);u(()=>{const e=fe.current,t=e?n.findIndex(t=>t.id===e.firstId):-1;if(e&&t>0)return e.count=t,void J(e.visible+e.count);J(150)},[ge]),u(()=>{const e=fe.current;if(!e?.count||X!==e.visible+e.count)return;fe.current=null;const t=Y.current;t&&(t.scrollTop=e.scrollTop+(t.scrollHeight-e.scrollHeight))});const ye=s({runningIn:-1,settledAt:0,stopped:!1,visit:0});c(()=>{const e=ye.current;e.visit+=1,e.stopped=!1},[R]);const xe=async()=>{const e=Y.current;if(n.length>X)return fe.current={firstId:n[0]?.id,visible:X,count:50,scrollHeight:e?.scrollHeight??0,scrollTop:e?.scrollTop??0},J(X+50),50;if(!H||be)return;const t=R??null;we(t);const r={firstId:n[0]?.id,visible:Math.min(n.length,X),count:0,scrollHeight:e?.scrollHeight??0,scrollTop:e?.scrollTop??0};fe.current=r;const{visit:o}=ye.current;try{const e=await H();return 0===e?fe.current===r&&(fe.current=null):o===ye.current.visit&&(ye.current.stopped=!1),e}finally{we(e=>e===t?void 0:e)}};let ke=0;for(const e of n)"user"===e.role&&(ke+=1);const Ce=s(null);u(()=>{const e=Ce.current;Ce.current={firstMessageId:ge,userMessageCount:ke},fe.current?.count||(!e||e.firstMessageId!==ge||ke>e.userMessageCount?ce.reveal():ce.keepUp())},[n,ge,ke,ce]);const Ne=o?.thinkingContent?.length??0;u(()=>{Ne&&ce.keepUp()},[Ne,ce]);const Se=n.length>X,Te=i(()=>Se?n.slice(n.length-X):n,[n,X,Se]),{speakingId:Ae,stop:Ie}=ae,Ee=null===Ae||n.some(e=>_o(e)===Ae),ze=s({conversationId:R,userMessageCount:ke});c(()=>{const e=ze.current;ze.current={conversationId:R,userMessageCount:ke},(e.conversationId!==R||ke>e.userMessageCount||!Ee)&&Ie()},[R,ke,Ee,Ie]);let Re=null;if(r)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){Re=n[e].id;break}const Me=!!T?.length&&!!A,De=s(new Set);return e("div",{ref:Y,role:"region","aria-label":G("Conversation transcript"),tabIndex:0,onScroll:()=>{ce.onScroll();const e=Y.current,t=ye.current;if(!e||ce.following||t.runningIn===t.visit||t.stopped||e.scrollTop>200)return;if(Date.now()-t.settledAt<1e3)return;const{visit:n}=t;t.runningIn=n,xe().then(e=>{0===e&&n===t.visit&&(t.stopped=!0)}).finally(()=>{t.runningIn===n&&(t.runningIn=-1),n===t.visit&&(t.settledAt=Date.now())})},onWheel:e=>{(function(e){return!e.ctrlKey&&e.deltaY<0&&Math.abs(e.deltaY)>Math.abs(e.deltaX)})(e)&&me(e.currentTarget,e.target)},onKeyDown:e=>{var t;e.defaultPrevented||!function(e){return!e.altKey&&(Wo.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&Ka(e.target)||me(e.currentTarget,e.target))},onPointerDown:e=>{const t=e.currentTarget,n=t.getBoundingClientRect();(function(e){if(1===e.button)return!e.onControl;if(0!==e.button||!e.onContainer||e.x<e.clientWidth)return!1;const t=(e.scrollTop+e.clientHeight)/e.scrollHeight*e.clientHeight;return e.y<=t})({button:e.button,onContainer:e.target===t,onControl:Ka(e.target),x:e.clientX-n.left-t.clientLeft,y:e.clientY-n.top-t.clientTop,clientWidth:t.clientWidth,clientHeight:t.clientHeight,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight})&&me(t,e.target)},onTouchStart:e=>{he.current=qo(e.touches)},onTouchMove:e=>{const t=qo(e.touches),n=he.current;null!==t&&null!==n&&function(e,t){return t-e>4}(n,t)&&me(e.currentTarget,e.target),he.current=function(e,t){return null===t?null:null===e?t:Math.min(e,t)}(n,t)},"data-testid":"filigran-chat-transcript",className:"relative flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--chat-accent-50)]",children:[(Se||H)&&t("div",{className:"flex justify-center",children:e("button",{type:"button",disabled:be,onClick:()=>{xe()},className:"flex items-center gap-1.5 rounded-full border chat-border-200/10 px-3 py-1 text-[0.7rem] chat-text-secondary-500/50 transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)]",children:[t(kr,{size:13,className:"rotate-180"}),G(be?"Loading earlier messages…":"Load earlier messages")]})}),t(Wa.Provider,{value:ce.stay,children:Te.map(e=>{const n=e.id===Re,r=((e,t)=>{if(W)try{const n=W(e,{streaming:t});return"boolean"==typeof n?void 0:n}catch(t){const n=e.serverId??e.id;return void(De.current.has(n)||(De.current.add(n),console.error("A replaced chat message failed to render",t)))}})(e,n);if(null===r)return null;const a=((e,n)=>"assistant"===e.role&&!e.content&&n?Me?null:t("div",{children:t(ka,{agentStatus:o,logoIcon:p,t:G,miniGameEnabled:y,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ce.keepUp,onSkipWait:S,...K})},e.id):t(ds,{msg:e,isStreaming:n,agentName:h,logoIcon:p,onRelativeLinkClick:m,onDownloadFile:g,resolveAttachmentUrl:f,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:b,feedbackMode:"assistant"===e.role?de(e.serverId,z,R,!!C):null,feedback:Z[_o(e)],onRate:ne,onSaveComment:re,onSkipComment:oe,locale:M,canSpeak:ae.supported,isSpeaking:Ae===_o(e),onToggleSpeech:ae.toggle,openableConversationIds:e.conversationRefs?.length?D:void 0,onOpenConversation:e.conversationRefs?.length?L:void 0,markerRenderers:_,markerKindList:P,codeBlockRenderers:j,transformMessageText:$,onArtifactOpen:U,renderMessageExtras:O,messageFooterActions:q,collapseUnnamedFiles:B,toolLabels:K?.toolLabels,t:G},e.id))(e,n);return void 0===r?a:t("div",{"data-message-id":e.serverId??e.id,"data-testid":"filigran-chat-replaced-message",className:"flex w-full",children:t(ra,{label:"A replaced chat message",resetKey:`${e.id}\0${n}`,fallback:a,children:r})},e.id)})}),N&&!Me&&t(ka,{agentStatus:o,logoIcon:p,t:G,miniGameEnabled:y,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ce.keepUp,...K}),Me&&t(Jo,{proposals:T,onSubmit:A,isSubmitting:I,error:E,t:G},T.map(e=>e.toolCallId).join("|")),F,t("div",{className:"sticky bottom-0 z-10 h-0",children:!se&&t("button",{type:"button",onClick:()=>{Y.current?.focus({preventScroll:!0}),ce.reveal()},"aria-label":G("Scroll to bottom"),title:G("Scroll to bottom"),className:"absolute bottom-1 left-1/2 -translate-x-1/2 rounded-full border chat-border-200/10 chat-menu-surface p-1.5 chat-text-secondary-500/50 shadow-md transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",children:t(kr,{size:16})})})]})};function hs(e){const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}const ps=({call:n,agentName:r,logoIcon:o,processingLabel:i,onInterrupt:l,onToggleMute:d,onEnd:u,t:h})=>{const[p,m]=a(0);c(()=>{const e=window.setInterval(()=>m(e=>e+1),1e3);return()=>window.clearInterval(e)},[]);const g=s(null);c(()=>{g.current?.scrollIntoView?.({block:"end"})},[n.lines.length,n.heard]);const{phase:f,muted:v}=n,w="listening"===f?h(v?"Muted":"Listening..."):"processing"===f?i:"speaking"===f?h("Speaking…"):"error"===f?h("Failed to get a response. Resuming…"):"",b="speaking"===f||"processing"===f,y="speaking"===f||"listening"===f&&!v,x="w-12 h-12 rounded-full flex items-center justify-center border transition-colors disabled:opacity-40";return e("div",{role:"dialog","aria-label":h("Voice call"),"data-testid":"filigran-chat-voice-call",className:"absolute inset-0 z-40 flex flex-col rounded-[inherit] chat-surface-raised",children:[e("div",{className:"flex items-center justify-between px-4 py-3 text-[0.7rem] uppercase tracking-[1px] chat-text-secondary-500/50",children:[t("span",{children:h("Voice call")}),t("span",{className:"font-mono normal-case tracking-normal",children:hs(p)})]}),e("div",{className:"flex flex-1 min-h-0 flex-col items-center justify-center gap-1 px-4",children:[e("button",{type:"button",onClick:b?l:void 0,disabled:!b,"aria-label":"speaking"===f?h("Skip response"):"processing"===f?h("Cancel question"):r,className:`relative mb-4 flex h-28 w-28 items-center justify-center rounded-full border-2 transition-colors ${"error"===f?"border-amber-400/50":y?"border-[var(--chat-accent)]":"border-[var(--chat-accent-40)]"} ${b?"cursor-pointer":"cursor-default"}`,children:[y&&t("span",{className:"absolute inset-0 rounded-full border border-[var(--chat-accent-40)] animate-ping","aria-hidden":"true"}),"processing"===f&&t("span",{className:"absolute inset-3 rounded-full border-2 border-dashed border-[var(--chat-accent-40)] animate-spin","aria-hidden":"true"}),t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-10 [&>svg]:h-10",children:o})]}),t("h2",{className:"max-w-full truncate text-base font-semibold chat-text-900/100",children:r}),t("p",{"aria-live":"polite",className:"text-center text-[0.8125rem] chat-text-secondary-500/60",children:w}),"speaking"===f&&t("p",{className:"text-[0.7rem] chat-text-muted-400/40",children:h("Speak or tap to interrupt")}),"processing"===f&&t("p",{className:"text-[0.7rem] chat-text-muted-400/40",children:h("Tap to cancel")}),"listening"===f&&n.heard&&e("p",{className:"mt-3 max-w-md text-center text-[0.8125rem] italic chat-text-secondary-500/50",children:["“",n.heard,"”"]})]}),n.lines.length>0&&t("div",{className:"max-h-[35%] overflow-y-auto filigran-chat-scrollable px-4 pb-2",children:e("div",{className:"flex flex-col gap-2",children:[n.lines.map((n,r)=>t("div",{className:"flex "+("user"===n.role?"justify-end":"justify-start"),children:e("div",{className:"max-w-[85%] rounded-lg px-3 py-1.5 text-[0.75rem] leading-5 "+("user"===n.role?"bg-[var(--chat-accent)]/10 chat-text-800/80":"chat-surface-subtle-100/6 chat-text-secondary-700/70"),children:[n.agent&&e("div",{className:"mb-0.5 text-[0.7rem] font-medium text-[var(--chat-accent)]",children:[n.agent.name,n.agent.failed&&e("span",{className:"font-normal chat-text-secondary-500/50",children:[" · ",h("Did not answer")]})]}),n.content.length>200?`${n.content.slice(0,200)}…`:n.content]})},r)),t("div",{ref:g})]})}),e("div",{className:"flex items-center justify-center gap-5 px-4 pb-5 pt-3",children:[t("button",{type:"button",onClick:d,"aria-label":h(v?"Unmute microphone":"Mute microphone"),"aria-pressed":v,className:`${x} ${v?"border-red-400/40 bg-red-500/10 text-red-500":"chat-border-200/10 chat-text-secondary-600/70 hover:chat-surface-hover-100/6"}`,children:t(v?Kr:Vr,{size:20})}),t("button",{type:"button",onClick:u,"aria-label":h("End voice call"),className:"w-14 h-14 rounded-full flex items-center justify-center bg-red-500 text-white hover:bg-red-600 transition-colors",children:t(Yr,{size:22})}),t("button",{type:"button",onClick:l,disabled:"speaking"!==f,"aria-label":h("Skip response"),className:`${x} chat-border-200/10 chat-text-secondary-600/70 hover:chat-surface-hover-100/6`,children:t(co,{size:20})})]})]})},ms=({firstName:r,agentName:o,t:a})=>{if(!o)return t(n,{children:I(a,"How can I help you, {name}?",{name:r})});const{before:s,after:i,hasSlot:c}=E(a,"How can {agent} help you, {name}?","agent",{name:r});return e(n,{children:[s,c&&t("span",{className:"text-[var(--chat-accent)]",children:o}),i]})},gs=({firstName:n,logoIcon:r,promptSuggestions:o,onPromptClick:a,agentName:s,agentDescription:i,suggestionsLoading:c=!1,t:l})=>e("div",{className:"flex-1 flex flex-col items-center justify-center px-6 pb-8",children:[t("span",{className:"text-[var(--chat-accent)] mb-4 [&>svg]:w-12 [&>svg]:h-12 drop-shadow-[0_0_12px_var(--chat-accent-40)]",children:r}),t("h2",{className:"text-xl font-medium mb-1 text-center chat-text-900/100",style:{fontFamily:'"Geologica", sans-serif',animation:"chat-fade-in 0.35s ease-out"},children:t(ms,{firstName:n,agentName:s,t:l})},s??"default"),i&&t("p",{className:"mb-5 max-w-[320px] text-center text-[0.75rem] leading-5 chat-text-secondary-500/40",children:i}),!i&&t("span",{className:"mb-5"}),a&&(c||o.length>0)&&e("div",{className:"w-full max-w-[320px]",children:[t("span",{className:"block text-center mb-2 text-[0.65rem] tracking-[1.5px] uppercase text-[var(--chat-accent)] font-semibold",children:l("Suggestions")}),c?t("div",{"aria-hidden":!0,className:"space-y-1",children:[0,1,2].map(e=>t("div",{className:"h-8 rounded-lg border chat-border-200/10 chat-skeleton-card animate-pulse"},e))}):o.map(e=>t("button",{type:"button",onClick:()=>a(e),className:"w-full text-left text-[0.8125rem] chat-text-800/100 py-1.5 px-3 mb-1 rounded-lg border chat-border-200/10 bg-transparent transition-colors hover:bg-[var(--chat-accent-10)] hover:border-[var(--chat-accent-50)]",children:e},e))]})]}),fs=m(function({draw:e,query:r}){return t(n,{children:e({query:r})})}),vs="application/x-filigran-conversation";const ws="p-1 rounded-md chat-text-muted-400/30 hover:chat-icon-hover transition-colors disabled:opacity-40 disabled:pointer-events-none",bs="text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",ys=({conversations:r,loading:o,failed:l=!1,onRetry:d,activeConversationId:u,collapsed:h,onToggleCollapsed:p,onSelect:m,onDelete:g,onRename:f,onNewChat:v,workspaces:w,storageKeyPrefix:b,expandedGroups:y,onGroupOpenedChange:x,rowActions:k,headerActions:C,sections:N,onClearAll:S,clearAllAction:T,searchThreshold:A=7,channelLabel:I,notice:E,onNotice:z,t:R})=>{const[M,D]=a(""),[L,_]=a(null),[P,j]=a(""),$=s(!1),U=Ot(b,jt),[O,W]=a(()=>function(e){try{const t=JSON.parse(qt("local",e)??"[]");return new Set(Array.isArray(t)?t.filter(e=>"string"==typeof e):[])}catch{return new Set}}(U)),q=i(()=>y?new Set(y):null,[y]),[F,H]=a(!1),B=(e,t)=>{$.current=!1,_(e),j(t)},V=()=>{if($.current)return;$.current=!0;const e=L,t=P.trim();_(null),e&&t&&f?.(e,t)},G=()=>{$.current=!0,_(null)},Y=(e,t)=>{q&&x?.(e,t)},X=(e,t)=>z?.(e||R(t)),J=async(e,t)=>{w&&!function(e,t,n){const r=e.find(e=>e.conversationId===t);return!!r&&(r.workspaceId??null)===n}(r,e,t)&&await w.onMove(e,t)},Q="function"==typeof N,Z=Q||r.length>A;c(()=>{Z||D("")},[Z]);const ee=Z?M.trim():"",te=ee.toLowerCase(),ne=R(Q?"None of your conversations matches":"No conversation matches"),re=i(()=>te?e=>function(e,t){return[e.title,e.lastMessagePreview,e.agentName].some(e=>!!e&&e.toLowerCase().includes(t))}(e,te):void 0,[te]),oe=i(()=>re?r.filter(re):r,[r,re]),ae=i(()=>w?function(e,t,n={}){const{matches:r}=n,o=r?e.filter(r):e,a=new Set(t.map(e=>e.id)),s=new Set(e.map(e=>e.workspaceId).filter(e=>!!e)),i=new Map,c=[],l=[];for(const e of o){const t=e.workspaceId??null;t?a.has(t)?i.set(t,[...i.get(t)??[],e]):c.push(e):l.push(e)}const d=[];for(const e of Te(t)){const t=i.get(e.id)??[];(e.canManage||s.has(e.id))&&(r&&0===t.length||d.push({workspace:e,key:e.id,conversations:t}))}return c.length>0&&d.push({workspace:null,key:"__elsewhere__",conversations:c}),{groups:d,unfiled:l}}(r,w.list,{matches:re}):null,[r,w,re]),se=q?new Set((ae?.groups??[]).map(e=>e.key).filter(e=>!q.has(e))):O,ie=w?function(e){return Te(e.filter(e=>e.canManage))}(w.list):[],ce=ae?function(e){const{total:t,unfiled:n,loading:r,searching:o}=e;return n>0||r||o?null:0===t?"none":"all-filed"}({total:r.length,unfiled:ae.unfiled.length,loading:o,searching:!!te}):null;if(h)return e("div",{className:"flex flex-col items-center gap-1 border-r chat-border-200/10 px-2 py-3 shrink-0",children:[t(wo,{title:R("Show conversations"),children:t("button",{type:"button",onClick:p,"aria-label":R("Show conversations"),"aria-expanded":!1,className:"w-8 h-8 flex items-center justify-center rounded-lg chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(Qr,{size:17})})}),t(wo,{title:R("New conversation"),children:t("button",{type:"button",onClick:()=>v(),"aria-label":R("New conversation"),className:"w-8 h-8 flex items-center justify-center rounded-lg chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(Er,{size:17})})})]});const le=e=>t(Ss,{conversation:e,isActive:e.conversationId===u,isEditing:e.conversationId===L,draftTitle:P,onDraftTitleChange:j,onCommitRename:V,onCancelRename:G,onStartRename:f?B:void 0,onSelect:m,onDelete:g,fileable:w?ie:void 0,onMove:J,actions:k,channel:K(e.channel,I),t:R},e.conversationId);return e("div",{className:"w-64 shrink-0 flex flex-col border-r chat-border-200/10",children:[e("div",{className:"flex items-center gap-1 px-3 py-3",children:[e("button",{type:"button",onClick:()=>v(),className:"flex-1 flex items-center gap-2 rounded-lg border chat-border-200/10 px-3 py-1.5 text-[0.8125rem] chat-text-secondary-700/70 hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] transition-colors",children:[t(Er,{size:15}),R("New conversation")]}),C,t(wo,{title:R("Hide conversations"),children:t("button",{type:"button",onClick:p,"aria-label":R("Hide conversations"),"aria-expanded":!0,className:"w-8 h-8 flex items-center justify-center shrink-0 rounded-lg chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(Qr,{size:17})})})]}),Z&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(Xr,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 chat-text-muted-400/40"}),t("input",{type:"text",value:M,onChange:e=>D(e.target.value),onKeyDown:e=>{"Escape"!==e.key||So(e)||D("")},placeholder:R("Search conversations..."),"aria-label":R("Search conversations..."),className:"w-full h-7 pl-7 pr-2 rounded-md chat-surface-subtle-100/6 text-[0.75rem] chat-text-900/100 placeholder:chat-text-muted-400/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"flex-1 overflow-y-auto px-2 pb-3 filigran-chat-scrollable",children:[o&&0===r.length&&t("div",{className:"px-3 py-2",children:t(fo,{size:16})}),l&&!o&&0===r.length?t(mo,{onRetry:()=>d?.(),className:"px-3 py-2",t:R}):e(n,ae&&w?{children:[!te&&e("div",{className:"flex items-center justify-between px-2 pb-1 pt-1",children:[t("span",{className:bs,children:R("Workspaces")}),t(wo,{title:R("New workspace"),children:t("button",{type:"button",onClick:()=>H(!0),"aria-label":R("New workspace"),className:ws,children:t(_r,{size:14})})})]}),F&&t(Cs,{placeholder:R("Workspace name"),onSubmit:async e=>{if(H(!1),!e)return;const t=await w.onCreate(e);t.ok?t.workspace&&Y(t.workspace.id,!0):X(t.error,"The workspace could not be created")},onCancel:()=>H(!1)}),ae.groups.map(e=>t(Ns,{workspace:e.workspace,count:e.conversations.length,open:Ae(e.key,se,e,u,!!te),toggleable:Ie(e,u,!!te),pending:!!e.workspace&&w.pendingWorkspaceId===e.workspace.id&&!u,onToggle:()=>{return t=e.key,void(q?Y(t,!q.has(t)):W(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Ft("local",U,JSON.stringify([...n])),n}));var t},onNewChat:w.onNewChat,onRename:async(e,t)=>{const n=await w.onRename(e,t);n.ok||X(n.error,"The workspace could not be renamed")},onDelete:async e=>{const t=await w.onDelete(e);t.ok||X(t.error,"The workspace could not be deleted")},onDropConversation:t=>e.workspace&&void J(t,e.workspace.id),t:R,children:e.conversations.length>0?e.conversations.map(le):t(ks,{t:R})},e.key)),e(xs,{onDropConversation:e=>{J(e,null)},accepts:!0,children:[e("div",{className:"flex items-center justify-between px-2 pb-1 pt-3",children:[t("span",{className:bs,children:R("Not in a workspace")}),e("span",{className:"flex items-center gap-1",children:[t("span",{className:"text-[0.625rem] tabular-nums chat-text-muted-400/30",children:ae.unfiled.length}),t(wo,{title:R("New conversation outside a workspace"),children:t("button",{type:"button",onClick:()=>v(),"aria-label":R("New conversation outside a workspace"),className:ws,children:t(Er,{size:13})})})]})]}),ae.unfiled.map(le),ce&&t("p",{className:"px-3 py-1.5 text-[0.65rem] chat-text-muted-400/30",children:R("none"===ce?"No conversations yet":"Every conversation is in a workspace.")})]}),te&&0===ae.groups.length&&0===ae.unfiled.length&&t("p",{className:"px-3 py-2 text-[0.75rem] chat-text-muted-400/40",children:ne})]}:{children:[!o&&0===r.length&&t("p",{className:"px-3 py-2 text-[0.75rem] chat-text-muted-400/40",children:R("No conversations yet")}),r.length>0&&0===oe.length&&t("p",{className:"px-3 py-2 text-[0.75rem] chat-text-muted-400/40",children:ne}),oe.map(le)]}),"function"==typeof N?t(fs,{draw:N,query:ee}):N,S&&r.length>0&&!te&&t(po,{onClear:S,action:T,className:"px-2 pt-3",iconButtonClass:ws,t:R})]}),E&&t("p",{role:"alert",className:"mx-3 mb-3 rounded-md bg-red-500/10 px-2.5 py-1.5 text-[0.7rem] text-red-600 dark:text-red-400",children:E})]})},xs=({onDropConversation:e,accepts:n,children:r,className:o=""})=>{const[i,c]=a(!1),l=s(0),d=e=>e.dataTransfer.types.includes(vs);return t("div",{className:`rounded-lg transition-colors ${i?"bg-[var(--chat-accent)]/10 ring-1 ring-[var(--chat-accent)]/40":""} ${o}`,...n?{onDragEnter:e=>{d(e)&&(l.current+=1,c(!0))},onDragOver:e=>{d(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},onDragLeave:e=>{d(e)&&(l.current=Math.max(0,l.current-1),0===l.current&&c(!1))},onDrop:t=>{if(!d(t))return;t.preventDefault(),l.current=0,c(!1);const n=t.dataTransfer.getData(vs);n&&e(n)}}:{},children:r})},ks=({t:n})=>{const{before:r,after:o,hasSlot:a}=E(n,"Drop a conversation here, or start one with {icon}.","icon");return e("p",{className:"px-3 py-1.5 text-[0.65rem] chat-text-muted-400/30",children:[r,a&&t("span",{role:"img","aria-label":n("New conversation in this workspace"),className:"inline-block align-[-1px]",children:t(Er,{size:11})}),o]})},Cs=({initial:e="",placeholder:n,onSubmit:r,onCancel:o})=>{const[i,l]=a(e),d=s(!1),u=s(null);c(()=>{u.current?.focus(),u.current?.select()},[]);const h=()=>{d.current||(d.current=!0,r(i.trim()))};return t("input",{ref:u,value:i,maxLength:200,onChange:e=>l(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),So(e)||("Enter"===e.key&&h(),"Escape"===e.key&&(d.current=!0,o()))},onBlur:h,placeholder:n,"aria-label":n,className:"mx-2 mb-1 w-[calc(100%-1rem)] rounded-md chat-input-surface-white/10 px-2 py-1 text-[0.8125rem] chat-text-900/100 outline-hidden ring-1 ring-[var(--chat-accent)]"})},Ns=({workspace:r,count:o,open:s,toggleable:i,pending:c,onToggle:l,onNewChat:d,onRename:u,onDelete:h,onDropConversation:p,t:m,children:g})=>{const[f,v]=a(!1),[w,b]=a(!1),y=!!r?.canManage,x=!!r&&r.isDefault&&r.isOwn;return e(xs,{onDropConversation:p,accepts:y,className:"mb-0.5",children:[e("div",{className:"group/ws flex items-center gap-1 rounded-lg px-1.5 py-1 hover:chat-surface-hover-100/6",children:[f&&r?t(Cs,{initial:r.name,placeholder:m("Workspace name"),onSubmit:e=>{v(!1),e&&e!==r.name&&u(r.id,e)},onCancel:()=>v(!1)}):e("button",{type:"button",onClick:l,disabled:!i,"aria-expanded":s,className:"flex min-w-0 flex-1 items-center gap-1.5 text-left disabled:cursor-default",children:[t(Cr,{size:12,className:"shrink-0 chat-text-muted-400/30 transition-transform "+(s?"rotate-90":"")}),t(Dr,{size:14,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate text-[0.8125rem] font-medium chat-text-800/80",children:r?r.name:m("Other workspaces")}),x&&t("span",{className:"shrink-0 rounded bg-[var(--chat-accent)]/10 px-1 text-[0.6rem] text-[var(--chat-accent)]",children:m("default")}),t("span",{className:"ml-auto shrink-0 pr-1 text-[0.625rem] tabular-nums chat-text-muted-400/30",children:o})]}),r&&y&&!f&&t("span",{className:"flex shrink-0 items-center opacity-0 group-hover/ws:opacity-100 focus-within:opacity-100 transition-opacity",children:e(n,w?{children:[t("span",{className:"px-1 text-[0.65rem] text-red-600 dark:text-red-400",children:m("Delete?")}),t("button",{type:"button",onClick:()=>{b(!1),h(r.id)},"aria-label":m("Delete workspace"),className:`${ws} hover:text-red-500`,children:t(xr,{size:13})}),t("button",{type:"button",onClick:()=>b(!1),"aria-label":m("Cancel"),className:ws,children:t(Nr,{size:13})})]}:{children:[t(wo,{title:m("New conversation in this workspace"),children:t("button",{type:"button",onClick:()=>d(r.id),"aria-label":m("New conversation in this workspace"),className:ws,children:t(Er,{size:13})})}),t(wo,{title:m("Rename workspace"),children:t("button",{type:"button",onClick:()=>v(!0),"aria-label":m("Rename workspace"),className:ws,children:t(Gr,{size:13})})}),!r.isDefault&&t(wo,{title:m("Delete workspace"),children:t("button",{type:"button",onClick:()=>b(!0),"aria-label":m("Delete workspace"),className:`${ws} hover:text-red-500`,children:t(oo,{size:13})})})]})})]}),s&&e("div",{className:"space-y-0.5 pb-1 pl-3",children:[c&&e("div",{className:"flex items-center gap-2 rounded-lg bg-[var(--chat-accent)]/10 px-2.5 py-1.5 text-[0.75rem] text-[var(--chat-accent)]",children:[t(Er,{size:12}),m("New conversation — send a message to start it")]}),g]})]})},Ss=({conversation:r,isActive:o,isEditing:i,draftTitle:c,onDraftTitleChange:l,onCommitRename:d,onCancelRename:u,onStartRename:h,onSelect:p,onDelete:m,fileable:g,onMove:f,actions:v,channel:w,t:b})=>{const[y,x]=a(!1),k=s(null),C=!!g&&!i;return e("div",{role:"button",tabIndex:0,"aria-current":o,draggable:C,onDragStart:C?e=>{e.dataTransfer.setData(vs,r.conversationId),e.dataTransfer.effectAllowed="move"}:void 0,onClick:()=>p(r.conversationId),onKeyDown:e=>{e.target===e.currentTarget&&("Enter"!==e.key&&" "!==e.key||(e.preventDefault(),p(r.conversationId)))},className:"group flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left cursor-pointer transition-colors "+(o?"bg-[var(--chat-accent)]/10":"hover:chat-surface-hover-100/6"),children:[t("span",{className:"mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg "+(o?"bg-[var(--chat-accent)]/20 text-[var(--chat-accent)]":"chat-surface-subtle-100/6 chat-text-muted-400/30"),children:t(wr,{size:13})}),e("span",{className:"min-w-0 flex-1",children:[i?t("input",{autoFocus:!0,value:c,onChange:e=>l(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),So(e)||("Enter"===e.key&&d(),"Escape"===e.key&&u())},onBlur:d,"aria-label":b("Conversation title"),className:"w-full rounded-md chat-input-surface-white/10 px-1.5 py-0.5 text-[0.8125rem] chat-text-900/100 outline-hidden ring-1 ring-[var(--chat-accent)]"}):t("span",{className:"block truncate text-[0.8125rem] "+(o?"chat-text-900/100":"chat-text-secondary-700/70"),children:r.title||b("Untitled conversation")}),r.lastMessagePreview&&!i&&t("span",{className:"block truncate text-[0.7rem] chat-text-secondary-500/50",children:r.lastMessagePreview}),(r.agentName||r.updatedAt||w)&&!i&&e("span",{className:"flex min-w-0 items-center gap-1 text-[0.65rem] chat-text-muted-400/30",children:[w&&t(wo,{title:I(b,"Started in {channel}",{channel:w}),children:t("span",{role:"img","aria-label":I(b,"Started in {channel}",{channel:w}),className:"flex shrink-0",children:t(Br,{size:10})})}),e("span",{className:"truncate",children:[r.agentName,r.agentName&&r.updatedAt?" · ":"",r.updatedAt?D(r.updatedAt,b):""]})]})]}),!i&&e("span",{className:"flex shrink-0 self-center opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity",children:[v&&t("span",{className:"flex",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:v(r)}),C&&e(n,{children:[t("button",{ref:k,type:"button",onClick:e=>{e.stopPropagation(),x(e=>!e)},"aria-label":b("Move to workspace"),title:b("Move to workspace"),"aria-expanded":y,className:"p-1 rounded-md chat-text-muted-400/30 hover:text-[var(--chat-accent)]",children:t(Lr,{size:13})}),t(go,{open:y,onClose:()=>x(!1),anchorRef:k,placement:"bottom-end",width:220,children:e("div",{className:"py-1",onClick:e=>e.stopPropagation(),children:[t("p",{className:"px-3 pb-1 pt-1.5 text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",children:b("Move to workspace")}),g.map(n=>e("button",{type:"button",disabled:n.id===r.workspaceId,onClick:()=>{x(!1),f(r.conversationId,n.id)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] chat-text-secondary-700/80 hover:chat-surface-hover-100/10 disabled:opacity-40",children:[t(Dr,{size:13,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate",children:n.name}),n.id===r.workspaceId&&t(xr,{size:12,className:"ml-auto shrink-0"})]},n.id)),t("div",{className:"my-1 h-px chat-border-fill-200/10"}),e("button",{type:"button",disabled:!r.workspaceId,onClick:()=>{x(!1),f(r.conversationId,null)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] chat-text-secondary-700/80 hover:chat-surface-hover-100/10 disabled:opacity-40",children:[t(Nr,{size:13,className:"shrink-0"}),b("Remove from workspace")]})]})})]}),h&&t("button",{type:"button",onClick:e=>{e.stopPropagation(),h(r.conversationId,r.title||"")},"aria-label":b("Rename conversation"),title:b("Rename conversation"),className:"p-1 rounded-md chat-text-muted-400/30 hover:text-[var(--chat-accent)]",children:t(Er,{size:13})}),t("button",{type:"button",onClick:e=>{e.stopPropagation(),m(r.conversationId)},"aria-label":b("Delete conversation"),title:b("Delete conversation"),className:"p-1 rounded-md chat-text-muted-400/30 hover:text-red-500 dark:hover:text-red-400",children:t(oo,{size:13})})]})]})},Ts=new Set([502,503,504]),As=new Set([401,403]),Is=g(function(e,n){const r=s(e.onSessionEnded);r.current=e.onSessionEnded;const o=s("");o.current=Le(e.requestHeaders);const a=i(()=>{let e=null;const t=t=>{r.current&&e!==o.current&&(e=o.current,B(r.current,t))};return{sessionEnded:t,fetch:(n=()=>r.current?t:void 0,async(e,t)=>{const r=await globalThis.fetch(e,t),o=401===r.status?n():void 0;return o&&"function"==typeof r.clone&&r.clone().json().then(e=>{const t=function(e){if(!e||"object"!=typeof e)return null;const t=e.detail;if(!t||"object"!=typeof t)return null;const{code:n,reason:r}=t;return"session_expired"!==n?null:{reason:"string"==typeof r&&r?r:void 0}}(e);t&&o(t.reason)}).catch(()=>{}),r})};var n},[]);return t(on,{value:a,children:t(Es,{...e,ref:n})})}),Es=g(function({mode:n,onClose:r,onModeChange:u,topOffset:h=0,apiBaseUrl:p,apiEndpoints:m,agentDashboardUrl:g,waitingGameUrl:v,user:w,t:b,accentColor:y="#7b5cff",logoIcon:x,promptSuggestions:k,draftBorderColor:N,resizable:S=!1,onWidthChange:T,onResizeStart:A,onResizeEnd:E,disableFileManagement:z=!1,onRelativeLinkClick:R,onDownloadError:M,maxFileCount:D,maxTotalSize:L,maxFileSize:_,acceptFileTypes:j,onFileRefused:$,placeholder:U,requestHeaders:O,pageContext:q,pushContentSelector:F,backendType:H="rest",miniGameEnabled:V=!0,onPlayWaitingGame:G,notifyOnComplete:Y=!0,onTaskComplete:X,onMessageFeedback:J,locale:Z,disableImagePreviews:oe=!1,contextUsageEnabled:se=!0,composerToolbar:ie,storageKeyPrefix:le,conversationId:de,onConversationChange:ue,initialAgent:pe,onAgentChange:me,readOnly:ge=!1,readOnlyNotice:fe,getRequestExtras:ve,onStreamEvent:we,markerRenderers:be,codeBlockRenderers:xe,transformMessageText:ke,onArtifactOpen:Ce,headerActions:Ne,banner:Te,composerHeader:Ae,transcriptFooter:Ie,welcome:Ee,renderMessageExtras:ze,replaceMessage:Re,messageFooterActions:Me,sidebarRowActions:_e,sidebarHeaderActions:Pe,sidebarSections:$e,statusLabel:Ue,toolLabels:Oe,waitingMessages:qe,renderWaitingPanel:Fe,renderReasoningAction:He,collapseUnnamedFiles:Be,fontFamily:Ve,theme:Ke,onReady:Ge,onBeforeSend:Ye,onHeldSendSettled:Xe,onTurnRunningChange:Je,steerAttachments:Ze=!1,holdSendsDuringTurn:tt=!1,agentMentions:nt=!1,hideConversationList:rt=!1,initialConversationListCollapsed:ot=!1,expandedWorkspaceGroups:at,onExpandedWorkspaceGroupsChange:st,onBeforeMove:it,onConversationActionFailed:ct,sidebarSearchThreshold:lt,channelLabel:dt,headerTitle:ut,headerSubtitle:ht,agentHref:pt,onAgentNameClick:mt,clearAllAction:gt},ft){const vt=rr(m),wt=rr(O),bt=rr(q),yt=rr(k),xt=or(R),kt=or(M),Ct=or($),Nt=or(G),St=or(X),Tt=or(J),At=or(ue),It=or(me),Et=or(ve),zt=or(Ye),[Rt,Mt]=a(at);at&&void 0===Rt&&Mt(at);const Dt=l((e,t)=>{Mt(n=>n&&n.includes(e)!==t?t?[...n,e]:n.filter(t=>t!==e):n)},[]),Lt=s(Rt);c(()=>{const e=Lt.current;Rt!==e&&(Lt.current=Rt,void 0!==e&&Rt&&st?.(Rt))},[Rt,st]);const jt=or(Xe),$t=or(we),Ut=or(Je),Wt=or(it),Ht=or(ct),Bt=or(mt),Vt=or(Ce),Kt=s(null),{fetch:Gt,sessionEnded:Yt}=o(rn),Xt=i(()=>ce(b,Z),[b,Z]),Jt=rr(qe),Qt=i(()=>be?Object.fromEntries(Object.entries(be).map(([e,t])=>[e.toUpperCase(),t])):void 0,[be]),Zt=rr(i(()=>xe?Object.fromEntries(Object.entries(xe).map(([e,t])=>[e.toLowerCase(),t])):void 0,[xe])),en=rr(i(()=>function(e){const t=new Set;for(const n of e??[]){const e=n.toUpperCase();P.test(e)&&t.add(e)}return[...t].sort()}(Qt&&Object.keys(Qt)),[Qt])),tn=rr(Oe),nn=i(()=>({statusLabel:Ue,waitingMessages:Jt,renderWaitingPanel:Fe,renderReasoningAction:He,toolLabels:tn}),[Ue,Jt,Fe,He,tn]),on="fullscreen"===n||"inline"===n,[sn,cn]=a(!1),{agents:ln,agentsLoading:dn,agentsError:un,agentsSettled:hn,agentsDisabled:pn,selectedAgent:mn,agentMenuOpen:gn,setAgentMenuOpen:fn,handleSwitchAgent:vn,followAgent:wn,reloadAgents:bn}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,storageKeyPrefix:o,initialAgent:i,onAgentChange:d}){const u=an(),h=null===t?.agents||!!t?.singleEndpoint||"legacy"===n,p=Ot(o,_t),[m,g]=a([]),[f,v]=a(!1),[w,b]=a(!1),[y,x]=a(h),[k,C]=a(0),N=l(()=>C(e=>e+1),[]),[S,T]=a(null),[A,I]=a(!1),E=s(0);c(()=>{if(h)return void x(!0);const n=`${e}${t?.agents??"/chat/agents"}`,o=++E.current,a=()=>o===E.current;v(!0),u(n,{headers:r}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}).then(e=>{if(!a())return;const t=Bn(e);if(g(t),b(!1),0===t.length)return void T(null);const n=()=>{const e=qt("local",p);return Vn(t,i)??(e?t.find(t=>t.slug===e):void 0)??t[0]};T(e=>e?t.find(t=>t.id===e.id)??n():n())}).catch(()=>{a()&&(b(!0),0===k&&g([]))}).finally(()=>{a()&&(v(!1),x(!0))})},[e,t,n,r,h,k]);const z=l(e=>{T(e),e.slug&&Ft("local",p,e.slug)},[p]);return{agents:m,agentsLoading:f,agentsError:w,agentsSettled:y,agentsDisabled:h,selectedAgent:S,setSelectedAgent:T,agentMenuOpen:A,setAgentMenuOpen:I,handleSwitchAgent:(e,t)=>{e.id!==S?.id?(T(e),e.slug&&Ft("local",p,e.slug),I(!1),d?.(e),t?.()):I(!1)},followAgent:z,reloadAgents:N}}({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt,storageKeyPrefix:le,initialAgent:pe,onAgentChange:me?It:void 0}),[yn,xn]=a(null),kn=s(null),[Cn,Nn]=a(null),[In,En]=a(void 0),[zn,Rn]=a(null),[Mn,Dn]=a(null),[Ln,_n]=a(null),Pn=s(0),[jn,$n]=a(null),Un=s(null),On=s(async()=>{}),Wn=s(()=>{}),qn=s(()=>{}),Fn=l((e,t)=>{B(qn.current,e,t.relayed),B($t,e,t)},[$t]),{messages:Kn,inputValue:Xn,setInputValue:Jn,isLoading:Qn,turnRunning:Zn,turnEnd:ar,agentStatus:ir,attachedFiles:cr,conversationId:lr,contextUsage:dr,transferredAgent:hr,forgetTransfer:fr,adoptRecreatedConversation:vr,canSteer:wr,pendingApprovals:br,isSubmittingApproval:yr,approvalError:xr,submitApprovalDecisions:kr,isResumingAfterDecision:Cr,historyReloadNonce:Nr,reloadHistory:Sr,mergeTurnHistory:Tr,settleUnseenEnd:Ir,historyLoadedRef:Er,conversationIdRef:zr,handleFileAdd:Rr,handlePaste:Mr,handleSendMessage:Dr,skipWait:Lr,readPendingApprovals:_r,heldMessage:Pr,notice:jr,fileNotice:$r,composerFocusRequest:Ur,cancelHeldMessage:Or,agentMentions:Wr,addAgentMention:qr,handleNewChat:Fr,pendingWorkspaceId:Hr,clearPendingWorkspace:Br,handleStopGenerating:Vr,conversationRefs:Kr,addConversationRef:Gr,setAttachedFiles:Yr,setMessages:Xr,setContextUsage:Jr,updateConversationId:Qr,handleSwitchConversation:Zr}=Hn({apiBaseUrl:p,apiEndpoints:vt,backendType:H,agentSlug:mn?.slug,agentPending:!hn,requestHeaders:wt,pageContext:bt,onRelativeLinkClick:R?xt:void 0,t:Xt,maxFileCount:D,maxTotalSize:L,maxFileSize:_,acceptFileTypes:j,onFileRefused:Ct,storageKeyPrefix:le,controlledConversationId:de,onConversationIdChange:ue?At:void 0,getRequestExtras:ve?Et:void 0,onStreamEvent:Fn,onSessionEnded:Yt,onConversationTitle:()=>{On.current()},onMessageSent:(e,t)=>Wn.current(e,t),historySettledFor:Cn,steerAttachments:Ze,holdSends:tt,agentMentionsEnabled:nt,onBeforeSend:Ye?zt:void 0,onHeldSendSettled:Xe?jt:void 0});In!==lr&&(En(lr),null!==Cn&&Nn(null),null!==zn&&zn!==lr&&Rn(null)),c(()=>{void 0!==de&&de!==zr.current&&(de?Zr(de):Fr())},[de]);const{suggestions:eo,loading:to}=nr({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt,agentSlug:mn?.slug}),no=i(()=>(eo??yt)?.map(e=>Xt(e))??(e=>[e("Help me create a new simulation scenario"),e("What are the latest attack patterns?"),e("How do I configure detection rules?"),e("Summarize my recent findings")])(Xt),[eo,yt,Xt]),{prompts:ro,quota:oo,refreshQuota:ao}=tr({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt}),{historyEnabled:so,conversations:io,conversationsLoading:co,conversationsFailed:lo,refreshConversations:uo,deleteConversation:ho,renameConversation:po,moveConversation:mo,clearConversations:go,touchConversation:fo}=Gn({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt});On.current=uo,Wn.current=fo;const{workspacesEnabled:vo,workspaces:wo,refreshWorkspaces:bo,createWorkspace:yo,renameWorkspace:xo,deleteWorkspace:Co}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const o=an(),[i,c]=a([]),[d,u]=a(!1),h=s(0),p=t?.workspaces,m="rest"===n&&!t?.singleEndpoint&&"string"==typeof p&&p.length>0,g=m?`${e}${p}`:null,f=l(async()=>{if(!g)return;const e=++h.current;try{const n=await o(g,{method:"GET",headers:{...r??{}}});if(e!==h.current)return;if(!n.ok)return void(408===(t=n.status)||429===t||t>=500&&501!==t||(u(!1),c([])));const a=Se(await n.json());if(e!==h.current)return;c(a),u(!0)}catch{}var t},[g,r]),v=l(async(e,t,n)=>{try{const a=await o(t,{method:e,headers:{...n?{"Content-Type":"application/json"}:{},...r??{}},...n?{body:JSON.stringify(n)}:{}});if(!a.ok)return{ok:!1,error:await De(a)};const s=204===a.status?[]:Se([await a.json().catch(()=>null)]);return await f(),{ok:!0,workspace:s[0]}}catch{return{ok:!1,error:null}}},[r,f]),w=l(async e=>g?v("POST",g,{name:e.trim()}):{ok:!1,error:null},[g,v]),b=l(async(e,t)=>g?v("PATCH",`${g}/${encodeURIComponent(e)}`,{name:t.trim()}):{ok:!1,error:null},[g,v]),y=l(async e=>g?v("DELETE",`${g}/${encodeURIComponent(e)}`):{ok:!1,error:null},[g,v]);return{workspacesEnabled:m&&d,workspaces:i,refreshWorkspaces:f,createWorkspace:w,renameWorkspace:b,deleteWorkspace:y}}({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt});c(()=>{vo&&Hr&&!function(e,t){return t.some(t=>t.id===e&&t.canManage)}(Hr,wo)&&Br(Hr)},[vo,wo,Hr,Br]);const[No,So]=a(!1),[To,Ao]=a(ot),Io=on&&so&&!rt;c(()=>{Io&&uo()},[Io,lr,uo]),c(()=>{Io&&bo()},[Io,lr,bo]);const Eo=s(null);c(()=>{if(!Io)return;const e=()=>{if("visible"!==document.visibilityState)return;const e=Date.now();(function(e,t){return null===t||e-t>=2e3})(e,Eo.current)&&(Eo.current=e,uo(),bo())};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[Io,uo,bo]);const zo=s(!1);c(()=>{zo.current!==Zn&&(zo.current=Zn,Zn?B(Ut,!0):B(Ut,!1,{ended:ar??"stopped"}))},[Zn,ar,Ut]),c(()=>()=>{zo.current&&(zo.current=!1,B(Ut,!1,{ended:"stopped"}))},[Ut]);const Ro=s(!1);c(()=>{Ro.current&&!Zn&&(ao(),Io&&(uo(),bo())),Ro.current=Zn},[Zn,ao,Io,uo,bo]);const Mo=e=>{So(!1),Zr(e)},Do=ye(p,vt,H),_o=i(()=>new Set(io.map(e=>e.conversationId)),[io]),Po=or(so?Mo:void 0),jo=Kn.some(e=>(e.conversationRefs?.length??0)>0);c(()=>{jo&&so&&uo()},[jo,so,uo,lr]);const $o=re(p,vt,H,"messagesPage"),[Uo,Oo]=a(!1),Wo=re(p,vt,H,"tts"),qo=i(()=>Wo?{url:Wo,requestHeaders:wt}:void 0,[Wo,wt]),Fo=s(Kn);Fo.current=Kn,c(()=>Oo(!1),[lr]);const Ho=l(async()=>{const e=zr.current,t=Fo.current.find(e=>e.serverId)?.serverId;if(!$o||!e||!t)return Oo(!1),0;try{const n=await Gt(`${$o}/${encodeURIComponent(e)}/messages?before=${encodeURIComponent(t)}&limit=50&supports_artifacts=true`,{headers:{...wt??{}}});if(!n.ok||zr.current!==e)return 0;const r=await n.json();if(zr.current!==e)return 0;const o=new Set(Fo.current.map(e=>e.serverId).filter(Boolean)),a=et(r?.messages).filter(e=>!e.serverId||!o.has(e.serverId)).map(e=>({...e,id:Qe(e.serverId)}));return Xr(e=>[...a,...e]),Oo(!0===r?.has_more&&a.length>0),a.length}catch{return 0}},[$o,zr,wt,Xr]),Bo=(e,t,{merge:n,afterTurn:r,keepEarlierOffer:o})=>{if(Nn(e),Rn(e),o||Oo(!!$o&&!0===t.has_more),!t.messages?.length)return;const a=et(t.messages);if(Xr(n?e=>function(e,t){const n=[...e],r=new Map;n.forEach((e,t)=>{e.serverId&&r.set(e.serverId,t)});const o=new Set,a=new Map;let s=-1,i=!1;for(const e of t){let t=void 0!==e.serverId?r.get(e.serverId):void 0;if(void 0===t){const r=Tn(e),a=n.findIndex((e,t)=>!o.has(t)&&!e.serverId&&Sn(e)===r);a>=0&&(t=a,n[a]=An(n[a],e),i=!0)}if(void 0!==t){o.add(t),s=Math.max(s,t);continue}const c=a.get(s)??[];c.push({...e,id:Qe(e.serverId)}),a.set(s,c)}if(0===a.size)return i?n:e;const c=[...a.get(-1)??[]];return n.forEach((e,t)=>{c.push(e,...a.get(t)??[])}),c}(e,a):a),!r)for(let e=t.messages.length-1;e>=0;e-=1){const n=je(t.messages[e]);if(n){Jr(n);break}}},Vo=s(Qn);Vo.current=Qn,c(()=>{Pn.current=0},[lr]),c(()=>{Mn&&!Qn&&(Dn(null),Mn.conversationId===lr&&Bo(Mn.conversationId,Mn.data,{merge:!0,afterTurn:!0,keepEarlierOffer:Mn.host}))},[Mn,Qn,lr]),c(()=>{if(!Ln||Ln.conversationId!==lr||Qn)return;const e=()=>{Vo.current||(_n(null),Pn.current+=1,Un.current=Ln.host?Ln.conversationId:null,Sr())},t=Math.min(6e4,5e3*2**Pn.current),n=window.setTimeout(e,t),r=()=>{"visible"===document.visibilityState&&e()};return window.addEventListener("online",e),document.addEventListener("visibilitychange",r),()=>{window.clearTimeout(n),window.removeEventListener("online",e),document.removeEventListener("visibilitychange",r)}},[Ln,lr,Qn,Sr]);const[Ko,Go]=a(null),Yo=Le(wt),Xo=l(()=>{$n(null),Un.current=jn?.host?jn.conversationId:null,Sr()},[jn,Sr]);c(()=>{jn&&jn.conversationId===lr&&!Qn&&jn.headersKey!==Yo&&Xo()},[jn,lr,Qn,Yo,Xo]);const Jo=jn&&jn.conversationId===lr?jn:null,Qo="rest"===H&&!vt?.singleEndpoint&&null!==vt?.sessions&&!!lr&&yn!==lr,Zo=!ge&&!z&&"rest"===H&&!vt?.singleEndpoint&&null!==vt?.upload,[ea,ta]=a(!1),na=s(0),ra=e=>e.dataTransfer.types.includes("Files"),oa=Zo?{onDragEnter:e=>{ra(e)&&(na.current+=1,ta(!0))},onDragOver:e=>{ra(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDragLeave:e=>{ra(e)&&(na.current=Math.max(0,na.current-1),0===na.current&&ta(!1))},onDrop:e=>{ra(e)&&(e.preventDefault(),e.stopPropagation(),na.current=0,ta(!1),Rr(e.dataTransfer.files))}}:{},aa=e=>!ra(e)||e.isDefaultPrevented()||function(e,t){const n=Array.from(e);if(!n.includes("text/uri-list")&&!n.includes("text/plain"))return!1;const r=t;return!!r&&(!!r.isContentEditable||!r.readOnly&&!r.disabled&&("TEXTAREA"===r.tagName||"INPUT"===r.tagName&&ne.has((r.type??"text").toLowerCase())))}(e.dataTransfer.types,e.target),sa={onDragOver:e=>{aa(e)||e.preventDefault()},onDrop:e=>{aa(e)||e.preventDefault()}},[ia,ca]=a(null),la=l(e=>ca({text:e}),[]);c(()=>{if(!ia)return;const e=setTimeout(()=>ca(null),6e3);return()=>clearTimeout(e)},[ia]);const da=(e,t,n,r)=>{((e,t,n)=>{const r=t?io.find(e=>e.conversationId===t)??null:null;return!0===B(Ht,e,r,n||null)})(e,t,n)||la(n||r)},ua=async()=>{if(!go)return;const e=await go();null===e?Fr():da("clearAll",null,e,Xt("archive"===gt?"The conversations could not be archived":"The conversations could not be deleted"))},ha=async e=>{const t=await ho(e);null===t?e===zr.current&&Fr():da("delete",e,t,Xt("The conversation could not be deleted"))},{sidebarWidth:pa,handleResizeStart:ma,defaultWidth:ga,isResizing:fa}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:r,onResizeEnd:o,storageKeyPrefix:i}){const l=Ot(i,Pt),[d,u]=a(()=>{const e=qt("local",l);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=Yn)return t}return Yn}),[h,p]=a(!1),m=s(!1),g=s(d);g.current=d;const f=s(n);f.current=n;const v=s(o);return v.current=o,c(()=>{"sidebar"===e&&t&&f.current?.(g.current)},[e,t]),c(()=>{if("sidebar"!==e||!t)return;const n=e=>{if(!m.current)return;e.preventDefault();const t=window.innerWidth-e.clientX,n=.4*window.innerWidth,r=Math.min(Math.max(t,Yn),n);u(r),g.current=r,f.current?.(r)},r=()=>{m.current&&(m.current=!1,p(!1),document.body.style.cursor="",document.body.style.userSelect="",Ft("local",l,String(g.current)),v.current?.())},o=()=>{const e=.4*window.innerWidth;if(g.current>e){const t=Math.max(e,Yn);u(t),g.current=t,f.current?.(t)}};return document.addEventListener("mousemove",n),document.addEventListener("mouseup",r),window.addEventListener("resize",o),()=>{document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",r),window.removeEventListener("resize",o)}},[e,t,l]),{sidebarWidth:d,handleResizeStart:e=>{e.preventDefault(),m.current=!0,p(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none",r?.()},defaultWidth:Yn,isResizing:h}}({mode:n,resizable:S,onWidthChange:T,onResizeStart:A,onResizeEnd:E,storageKeyPrefix:le});c(()=>{const e="sidebar"===n?S?pa:ga:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",fa?"none":"all 225ms cubic-bezier(0.4, 0, 0.2, 1)"),F){const e=document.querySelector(F);if(e){const n=e.style.paddingRight,r=e.style.transition;return e.style.paddingRight=t>0?`${t}px`:"",e.style.transition=fa?"none":"padding-right 225ms cubic-bezier(0.4, 0, 0.2, 1)",()=>{e.style.paddingRight=n,e.style.transition=r,document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}}}return()=>{document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}},[F,n,pa,ga,S,fa]);const wa=i(()=>x??t(Ar,{size:24}),[x]),ba=i(()=>function(e,t){if(void 0!==t){const e=t.trim();return/^https?:\/\//i.test(e)||/^\/(?![/\\])/.test(e)?e:null}const n=e?.trim().replace(/\/+$/,"");return n&&/^https?:\/\//i.test(n)?`${n}/chat?arcade=play`:null}(g,v),[g,v]),ya=w.firstName,[xa,ka]=a(null),[Ca,Na]=a(null),Sa=i(()=>"function"==typeof U?B(U,mn??null):U,[U,mn]),Ta=hr?.name||xa||mn?.name||Xt("Assistant"),Aa=l(()=>{const e=Kt.current;return!!e&&("function"==typeof e.checkVisibility?e.checkVisibility():e.getClientRects().length>0)},[]);er({isLoading:Zn,agentName:Ta,t:Xt,enabled:Y,onComplete:St,isViewingChat:Aa});const Ia=null!=vt?.download,Ea="rest"===H&&null!==vt?.download&&(!vt?.singleEndpoint||Ia),za=l(e=>`${p}${vt?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[p,vt]),Ra=l(async e=>{const t=za(e);try{const n=await Gt(t,{method:"GET",credentials:"include",headers:{...wt??{}}});if(!n.ok)throw new Error(`Download failed: ${n.status}`);const r=await n.blob(),o=URL.createObjectURL(r),a=document.createElement("a");a.href=o,a.download=e.filename||"download",document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(o)}catch(t){kt?.(t,e)}},[za,wt,kt]),Ma="rest"===H&&vt?.artifacts?`${p}${vt.artifacts}`:null,Da=l((e,t)=>`${Ma}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,[Ma]),La=l(async(e,t)=>{const n=`${e.title||e.kind}.${function(e){return"pptx_native"===e?"pptx":e}(t)}`;try{const r=await Gt(`${Da(e.kind,e.id)}/download`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...wt??{}},body:JSON.stringify({format:t})});if(!r.ok)throw new Error(`Download failed: ${r.status}`);const o=await r.blob(),a=URL.createObjectURL(o),s=document.createElement("a");s.href=a,s.download=function(e){if(!e)return;const t=/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(e);if(t)try{return decodeURIComponent(t[1].trim().replace(/^"|"$/g,""))||void 0}catch{}const n=/filename\s*=\s*("([^"]*)"|[^;]+)/.exec(e);return(n?(n[2]??n[1]).trim():"")||void 0}(r.headers.get("content-disposition"))??n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(a)}catch(r){kt?.(r,{fileId:e.id,filename:n,type:t.toUpperCase()})}},[Da,wt,kt]),_a=l(async(e,t)=>{const n=await Gt(Da(e,t),{credentials:"include",headers:{...wt??{}}});if(n.ok)return We(await n.json())},[Da,wt]),Pa={"--chat-accent":y,"--chat-accent-10":C(y,.1),"--chat-accent-40":C(y,.25),"--chat-accent-50":C(y,.5),"--chat-accent-dark":y,...Ve?{fontFamily:Ve}:{},...ae(Ke)},ja=s(Tr);ja.current=Tr;const $a=s(Ir);$a.current=Ir;const Ua=s(vr);Ua.current=vr;const Oa=s(!0);c(()=>(Oa.current=!0,()=>{Oa.current=!1}),[]),c(()=>{const e=Un.current;if(Un.current=null,null===vt?.sessions||vt?.singleEndpoint||"legacy"===H||"ag-ui"===H)return;if(!lr)return ka(null),void xn(null);if(Er.current)return kn.current!==lr&&yn!==lr&&xn(lr),void(kn.current!==lr&&Cn!==lr&&Mn?.conversationId!==lr&&Nn(lr));if(!mn&&!pn)return void(hn&&yn!==lr&&xn(lr));Er.current=!0,kn.current=lr,xn(null);const t=`${p}${vt?.sessions??"/chat/sessions"}`,n=lr,r=()=>!Oa.current||zr.current!==n,o=e===n,a=Le(wt),s=Nr;Gt(t,{method:"POST",headers:{"Content-Type":"application/json",...wt??{}},body:JSON.stringify({conversation_id:lr,agent_slug:mn?.slug,supports_artifacts:!0})}).then(e=>r()?null:e.ok?(Pn.current=0,_n(null),$n(null),e.json()):($a.current(s,null),As.has(e.status)?De(e).then(e=>(r()||$n({conversationId:n,detail:e,headersKey:a,host:o}),null)):(Ts.has(e.status)?_n({conversationId:n,host:o}):o||Qr(null),null))).then(e=>{if(!e||r())return;const t="string"==typeof e.conversation_id&&!!e.conversation_id&&e.conversation_id!==n;ka("string"==typeof e.agent_name?e.agent_name:null),Na("string"==typeof e.conversation_id&&"string"==typeof e.channel&&e.channel?{conversationId:e.conversation_id,channel:e.channel}:null);const a=et(e.messages);if($a.current(s,a),t)return Ua.current(e.conversation_id),Er.current=!0,void Bo(e.conversation_id,e,{merge:!1,afterTurn:!1,keepEarlierOffer:!1});o&&fr(),ja.current(a)||(Vo.current?Dn({conversationId:n,data:e,host:o}):Bo(n,e,{merge:o,afterTurn:!1,keepEarlierOffer:o}))}).catch(()=>{r()||($a.current(s,null),_n({conversationId:n,host:o}))}).finally(()=>{kn.current===n&&(kn.current=null),r()||xn(n)})},[lr,mn,hn,yn,$o,p,vt,H,Mn,Nr,Er,zr,Oa,wt,Xr,Jr,Qr,fr]);const Wa=s(Dr);Wa.current=Dr;const qa=s(Fr);qa.current=Fr;const Fa=s(Zr);Fa.current=Zr;const Ha=s(()=>{});Ha.current=e=>{Zo&&e.length>0&&Rr(e)};const Ba=s(ln);Ba.current=ln;const Va=s(mn);Va.current=mn;const Ka=xa?ln.find(e=>e.name===xa)??null:null,[Ga,Ya]=a(null),Xa=hn&&!Qo&&!((Ka?.id??null)!==Ga);c(()=>{if(null===Ko)return;if(Ko!==lr)return void Go(null);if(!Xa||Zn)return;Go(null);const e=zn===lr||Kn.length>0;_n(null),$n(null),Un.current=e?lr:null,Sr()},[Ko,lr,Xa,Zn,zn,Kn.length,Sr]);const Ja=or(Ge),Qa=s(!1);c(()=>{Xa&&!Qa.current&&(Qa.current=!0,Ja?.())},[Xa,Ja]);const Za=s([]),[es,ts]=a(0),ns=(e,t)=>{Za.current.push({run:e,drop:t}),ts(e=>e+1)};c(()=>{if(!Xa||0===Za.current.length)return;Za.current.shift().run(),Za.current.length>0&&ts(e=>e+1)},[Xa,es]),c(()=>()=>{queueMicrotask(()=>{if(!Oa.current)for(const e of Za.current.splice(0))e.drop?.()})},[]);const rs=s(vn);rs.current=vn;const os=s(Vr);os.current=Vr;const as=s(ge);as.current=ge;const ss=s(Xn);ss.current=Xn;const is=hr?ln.find(e=>e.id===hr.id)??null:xa?Ka:mn,cs=hr?.id??Ka?.id??mn?.id??null;c(()=>{const e=Ka?.id??null;e!==Ga&&(Ya(e),Ka&&Ka.id!==mn?.id&&(wn(Ka),It?.(Ka)))},[Ka,Ga,mn,wn,It]);const ls=i(()=>{if(!is||!pt&&!Bt)return;const e=function(e,t){const n=e?.replace(/[\t\n\r]/g,"").trim();if(!n)return;if(/^https?:\/\//i.test(n))return n;if(!n.startsWith("/"))return;const r=new URL(t);if("null"!==r.origin)try{return new URL(n,r).origin===r.origin?n:void 0}catch{return}return/^\/(?![/\\])/.test(n)?n:void 0}(B(pt,is),window.location.href),t=Bt?()=>B(Bt,is):void 0;return e||t?{href:e,onClick:t}:void 0},[is,pt,Bt]),ds={conversation:lr&&io.find(e=>e.conversationId===lr)||null,agent:is},hs=K(ds.conversation?.channel??(Ca?.conversationId===lr?Ca.channel:void 0),dt),ms=function(e){const t=an(),n=s(e);d(()=>{n.current=e});const[r,o]=a(null),i=s(null),u=l(async(e,r)=>{const{tts:o,locale:a}=n.current,s=a||("undefined"!=typeof navigator?navigator.language:void 0),i=ee(e,200),c=o?te(t,o,i,r):null;for(const e of i){if(r.aborted)return;const t=c?(await c.next()).value??null:null;if(r.aborted)return;if(!t||!await pr(t,r)){if(r.aborted)return;await mr(e,s,r)}}},[]),h=l(()=>{if(i.current)return!0;const e=sr();if(!e)return!1;const t=ur({recognition:new e,lang:n.current.locale||("undefined"!=typeof navigator?navigator.language:void 0),send:(e,t)=>n.current.send(e,t),speak:u,speakable:e=>B(n.current.speakable,e)??e,present:e=>B(n.current.present,e)??e,probe:()=>{const e=n.current.readTurnState;return e?async function(e){try{const t=await e();return t?t.running?"running":"over":"unknown"}catch{return"unknown"}}(e):Promise.resolve("over")},stopTurn:()=>n.current.stopTurn(),addressedAgentId:()=>n.current.addressedAgentId(),onChange:e=>{i.current===t&&o(e)}});return i.current=t,t.start(),!0},[u]),p=l(()=>{const e=i.current;i.current=null,e?.end(),o(null)},[]);return c(()=>p,[p]),{snapshot:r,start:h,end:p,onFrame:l((e,t)=>i.current?.frame(e,t),[]),interrupt:l(()=>i.current?.interrupt(),[]),cancel:l(()=>i.current?.cancel(),[]),toggleMute:l(()=>i.current?.toggleMute(),[])}}({send:(e,t)=>Wa.current({text:e,source:"voice",onSent:t.onAccepted,onNotSent:t.onNotSent,onSteered:t.onSteered}),stopTurn:()=>os.current(),readTurnState:_r?async()=>{const e=zr.current,t=e?await _r(e):null;return t&&{running:t.turnRunning}}:void 0,addressedAgentId:()=>cs,speakable:e=>Q(W(e,en)),present:e=>ke?ke(e,{id:"voice-call",role:"assistant",content:e,timestamp:new Date}):e,tts:qo,locale:Z});qn.current=ms.onFrame;f(ft,()=>({send:(e,t)=>as.current?Promise.resolve("dropped"):new Promise(n=>ns(()=>{as.current?n("dropped"):Wa.current({text:e,extras:t?.extras,displayText:t?.displayText,onSent:()=>n("sent")}).then(n,()=>n("failed"))},()=>n("dropped"))),newConversation:e=>ns(()=>{const t=Vn(Ba.current,e?.agent);t&&t.id!==Va.current?.id&&rs.current(t),qa.current(e?.workspaceId)}),selectConversation:e=>ns(()=>Fa.current(e)),setDraft:e=>{ss.current=e,Jn(e)},getDraft:()=>ss.current,focusComposer:()=>Kt.current?.querySelector("textarea")?.focus(),attachFiles:e=>ns(()=>Ha.current(e)),stop:()=>{ms.cancel(),os.current()},startVoiceCall:()=>!as.current&&ms.start(),reloadAgents:bn,reloadConversation:()=>{const e=zr.current;e&&Go(e)},scrollToMessage:e=>{const t=[...Kt.current?.querySelectorAll("[data-message-id]")??[]].find(t=>t.dataset.messageId===e);return!!t&&(t.scrollIntoView?.({block:"center",behavior:"smooth"}),t.classList.add("filigran-chat-highlight"),window.setTimeout(()=>t.classList.remove("filigran-chat-highlight"),2e3),!0)}}),[]);const fs=(()=>{const e="filigran-chatbot";switch(n){case"sidebar":return`${e} fixed right-0 bottom-0 flex flex-col chat-surface-raised border-l chat-border-200/10 z-[1200]`;case"floating":return`${e} fixed bottom-5 right-5 flex flex-col chat-surface-raised rounded-xl shadow-[0_8px_32px_rgba(0,0,0,0.15)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.4)] z-[1300] border chat-border-200/10`;case"fullscreen":return`${e} fixed right-0 bottom-0 left-0 flex flex-col chat-surface z-[1400]`;case"inline":return`${e} relative flex flex-col h-full w-full min-h-0 chat-surface`;default:return e}})(),vs={...Pa,..."sidebar"===n?{top:h,width:S?pa:ga}:"floating"===n?{width:380,height:560}:"inline"===n?{}:{top:h}};return e("div",{ref:Kt,className:fs,style:vs,"data-testid":"filigran-chat-panel",...sa,children:["sidebar"===n&&S&&t("div",{onMouseDown:ma,className:"absolute top-0 -left-1 bottom-0 w-2 cursor-col-resize z-10 group",children:t("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 bottom-0 w-0.5 rounded-sm bg-[var(--chat-accent)] opacity-0 transition-opacity group-hover:opacity-100 group-active:opacity-100"})}),t(ko,{mode:n,agentName:Ta,agents:ln,agentsLoading:dn,agentsError:un,selectedAgent:mn,transferredFrom:hr?mn?.name:void 0,agentMenuOpen:gn,onAgentMenuToggle:()=>fn(e=>!e),onAgentMenuClose:()=>fn(!1),onSwitchAgent:e=>{e&&vn(e,()=>{Fr()})},modeMenuOpen:sn,onModeMenuToggle:()=>cn(e=>!e),onModeMenuClose:()=>cn(!1),onModeChange:u,onNewChat:Fr,onClose:r,logoIcon:wa,actions:Ne,agentDashboardUrl:g,historyEnabled:so&&!Io,historyMenuOpen:No,onHistoryMenuToggle:()=>{const e=!No;e&&uo(),So(e)},onHistoryMenuClose:()=>So(!1),conversations:io,conversationsLoading:co,conversationsFailed:lo,onRetryConversations:()=>{uo()},activeConversationId:lr,onSelectConversation:Mo,onDeleteConversation:e=>{ha(e)},onClearAll:go?()=>{ua()}:void 0,clearAllAction:gt,title:"function"==typeof ut?B(ut,ds):ut,subtitle:"function"==typeof ht?B(ht,ds):void 0===ht?hs&&I(Xt,"Agent · {channel}",{channel:hs}):ht,agentLink:ls,t:Xt}),ia&&(!Io||To)&&t("p",{role:"alert",className:"mx-3 mt-2 shrink-0 rounded-md bg-red-500/10 px-2.5 py-1.5 text-[0.7rem] text-red-600 dark:text-red-400",children:ia.text}),e("div",{className:Io?"flex flex-1 min-h-0":"contents",children:[Io&&t(ys,{conversations:io,loading:co,failed:lo,onRetry:()=>{uo()},activeConversationId:lr,collapsed:To,onToggleCollapsed:()=>Ao(e=>!e),onSelect:Mo,onDelete:e=>{ha(e)},onRename:(e,t)=>{(async(e,t)=>{const n=await po(e,t);null!==n&&da("rename",e,n,Xt("The conversation could not be renamed"))})(e,t)},onNewChat:Fr,workspaces:vo?{list:wo,pendingWorkspaceId:Hr,onCreate:yo,onRename:xo,onDelete:async e=>{const t=await Co(e);return t.ok&&(Br(e),uo()),t},onMove:async(e,t)=>{const n=io.find(t=>t.conversationId===e);if(Wt&&n){const e=t?wo.find(e=>e.id===t)??null:null;let r=!1;try{r=!0===await Wt(n,e)}catch(e){console.error("A chat panel host callback threw",e)}if(!r)return}const r=await mo(e,t);null!==r&&da("move",e,r,Xt("The conversation could not be moved"))},onNewChat:e=>{Fr(e),bo()}}:void 0,storageKeyPrefix:le,expandedGroups:Rt,onGroupOpenedChange:Dt,rowActions:_e,headerActions:Pe,sections:$e,onClearAll:go?()=>{ua()}:void 0,clearAllAction:gt,searchThreshold:lt,channelLabel:dt,notice:ia?.text??null,onNotice:la,t:Xt}),e("div",{className:Io?"relative flex flex-1 flex-col min-w-0":"contents",...oa,children:[ea&&t("div",{className:"pointer-events-none absolute inset-2 z-30 flex items-center justify-center rounded-xl border-2 border-dashed border-[var(--chat-accent)] bg-[var(--chat-accent)]/10 text-sm font-medium text-[var(--chat-accent)]",children:Xt("Drop files to attach them")}),Te&&t("div",{className:"shrink-0",children:Te}),0===Kn.length&&Qo?t("div",{"data-testid":"filigran-chat-loading",className:"flex-1 flex flex-col gap-4 px-4 py-6","aria-busy":"true",children:[0,1,2].map(e=>t("div",{className:"flex "+(e%2?"justify-end":"justify-start"),children:t("div",{className:"h-10 rounded-xl chat-skeleton-fill animate-pulse "+(e%2?"w-1/3":"w-2/3")})},e))}):0===Kn.length&&Jo?e("div",{"data-testid":"filigran-chat-restore-error",role:"alert",className:"flex-1 flex flex-col items-center justify-center gap-3 px-6 py-6 text-center",children:[t(gr,{size:18,className:"text-amber-500 dark:text-amber-400"}),t("p",{className:"max-w-sm text-[0.8125rem] leading-6 chat-text-secondary-600/60",children:Jo.detail??Xt("This conversation could not be loaded.")}),t("button",{type:"button",onClick:Xo,className:"rounded-md border chat-border-200/10 px-3 py-1 text-[0.75rem] font-medium chat-text-secondary-700/80 transition-colors hover:chat-surface-hover-100/6",children:Xt("Retry")})]}):0===Kn.length?Ee?t("div",{className:"flex-1 min-h-0 overflow-y-auto filigran-chat-scrollable",children:Ee}):t(gs,{firstName:ya,logoIcon:wa,promptSuggestions:no,suggestionsLoading:to,agentName:mn?.name,agentDescription:mn?.description,onPromptClick:ge?void 0:Jn,t:Xt}):t(us,{messages:Kn,isLoading:Qn,agentStatus:ir,agentName:Ta,logoIcon:wa,onRelativeLinkClick:xt,onDownloadFile:Ea?Ra:void 0,resolveAttachmentUrl:Ea&&!oe?za:void 0,onDownloadArtifact:Ma?La:void 0,onRefreshArtifact:Ma?_a:void 0,requestHeaders:wt,miniGameEnabled:V,onPlayWaitingGame:Nt,waitingGameUrl:ba,onMessageFeedback:Tt,feedbackUrl:he(p,vt,H),conversationId:lr,locale:Z,isResumingAfterDecision:Cr,onSkipWait:Lr??void 0,pendingApprovals:br,onSubmitApprovalDecisions:kr,isSubmittingApproval:yr,approvalError:xr,openableConversationIds:_o,onOpenConversation:Po,markerRenderers:Qt,markerKindList:en,codeBlockRenderers:Zt,transformMessageText:ke,onArtifactOpen:Vt,renderMessageExtras:ze,replaceMessage:Re,messageFooterActions:Me,transcriptFooter:Ie,onLoadEarlier:Uo?Ho:void 0,collapseUnnamedFiles:Be,ttsRoute:qo,thinking:nn,t:Xt}),ge?fe&&t("div",{className:"px-4 py-3 border-t chat-border-200/10 text-sm chat-text-secondary-500/50",children:fe}):t(Lo,{header:Ae,steerAttachments:Ze,canHold:tt,heldMessage:Pr,notice:jr,fileNotice:$r,agentNotForChat:!!is?.disableChat,onCancelHeld:Or,agentMentions:nt&&ln.length>0?{agents:ln,mentions:Wr,onPick:qr}:void 0,inputValue:Xn,onInputChange:Jn,onSend:Dr,onStop:Vr,isLoading:Qn,canSteer:wr,attachedFiles:cr,onFileAdd:z?void 0:Rr,onFileRemove:e=>Yr(t=>t.filter((t,n)=>n!==e)),onPaste:z?void 0:Mr,accept:j,placeholder:Sa,focusRequest:Ur,t:Xt,mode:n,separatorColor:N,prompts:ro,quota:oo,contextUsage:se?dr:null,composerToolbar:ie,conversationReferences:Do?{url:Do,requestHeaders:wt,conversationId:lr,refs:Kr,onPick:Gr}:void 0})]})]}),ms.snapshot&&t(ps,{call:ms.snapshot,agentName:Ta,logoIcon:wa,processingLabel:va(ir,Xt,Ue,tn),onInterrupt:ms.interrupt,onToggleMute:ms.toggleMute,onEnd:ms.end,t:Xt})]})}),zs=({isOpen:n,onToggle:r,label:o,accentColor:a="#7b5cff",icon:s,t:c,locale:l})=>{const d=i(()=>ce(c,l),[c,l]),u=s??t(Ar,{size:16});return e("button",{type:"button",onClick:r,className:"filigran-chatbot inline-flex items-center gap-1.5 px-3 py-[3px] text-[0.8125rem] font-medium whitespace-nowrap rounded-md border transition-colors",style:{borderColor:n?a:C(a,.5),color:a,backgroundColor:n?C(a,.1):"transparent"},onMouseEnter:e=>{e.currentTarget.style.borderColor=a,e.currentTarget.style.backgroundColor=C(a,.1)},onMouseLeave:e=>{e.currentTarget.style.borderColor=n?a:C(a,.5),e.currentTarget.style.backgroundColor=n?C(a,.1):"transparent"},children:[t("span",{className:"[&>svg]:w-4 [&>svg]:h-4",children:u}),o??d("Ask Assistant")]})};export{Is as ChatPanel,zs as ChatToggleButton,hr as voiceCallSupported};
1
+ import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import{createContext as r,useContext as a,useState as o,useRef as s,useMemo as i,useCallback as c,useEffect as l,useInsertionEffect as d,useLayoutEffect as u,useId as h,Component as p,memo as m,forwardRef as g,useImperativeHandle as f}from"react";import v from"remark-gfm";import w from"remark-parse";import{unified as b}from"unified";import{createPortal as y}from"react-dom";import x from"react-markdown";import k from"remark-breaks";function C(e,t){return`${e}${Math.round(255*t).toString(16).padStart(2,"0")}`}function N(e){return function(e){if(!e)return e;const t=e.split("\n"),n=/^(\s*)(`{3,})(.*)$/,r=/^(markdown|md|mdx|markup)\b/i;let a=-1;for(let e=0;e<t.length;e++){const o=t[e].match(n);if(o&&3===o[2].length&&r.test(o[3].trim())){a=e;break}}if(-1===a)return e;const o=[];for(let e=a+1;e<t.length;e++){const r=t[e].match(n);r&&o.push({idx:e,run:r[2].length,bare:""===r[3].trim()})}const s=(e,n)=>{for(let r=e+1;r<n;r++)if(""!==t[r].trim())return!1;return!0};let i=0,c=3,l=0,d=-1;for(let e=0;e<o.length;e++){const t=o[e];if(t.bare&&0===i){const n=o[e+1];if(!n||!n.bare||s(t.idx,n.idx)){d=t.idx;break}i++}else i=t.bare?Math.max(0,i-1):i+1;l++,c=Math.max(c,t.run)}if(-1===d||0===l)return e;const u="`".repeat(Math.max(c+1,4)),h=t[a].match(n);t[a]=`${h[1]}${u}${h[3]}`;const p=t[d].match(n);return t[d]=`${p[1]}${u}`,t.join("\n")}(function(e){if(!e||-1===e.indexOf("|"))return e;const t=e.split("\n"),n=e=>{let t=e.trim();t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1));const n=[];let r="";for(let e=0;e<t.length;e++){const a=t[e];"\\"===a&&e+1<t.length?(r+=a+t[e+1],e++):"|"===a?(n.push(r),r=""):r+=a}return n.push(r),n},r=e=>e.includes("|")&&/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(e),a=e=>{const t=e.trim(),n=t.startsWith(":"),r=t.endsWith(":");return n&&r?":---:":r?"---:":n?":---":"---"},o=/^\s*(?:(?:>\s?)|(?:[-*+]\s+)|(?:\d{1,9}[.)]\s+))*(`{3,}|~{3,})(.*)$/;let s=null,i=0;const c=/^\s*(?:[-*+]\s+|\d{1,9}[.)]\s+)/;for(let e=0;e<t.length-1;e++){const l=t[e].match(o);if(l){const e=l[1];null===s?(s=e[0],i=e.length):e[0]===s&&e.length>=i&&""===l[2].trim()&&(s=null,i=0);continue}if(null!==s)continue;const d=t[e],u=t[e+1];if(!d.includes("|")||r(d)||!r(u))continue;const h=d.match(c),p=h?h[0].length:d.length-d.trimStart().length,m=h?" ".repeat(p):d.slice(0,p),g=n(d.slice(p)).length,f=n(u);if(g<2||f.length===g)continue;const v=[];for(let e=0;e<g;e++)v.push(f[e]?a(f[e]):"---");t[e+1]=`${m}| ${v.join(" | ")} |`}return t.join("\n")}(function(e){const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("[")||t.startsWith("```"))return e;try{return JSON.parse(t),"```json\n"+t+"\n```"}catch{return e}}((t=e).includes("![")?t.replace(/!\[([^\]]*?\n[^\]]*?)\]\(([^)\s]+)\)/g,(e,t,n)=>`![${t.replace(/\s+/g," ").trim()}](${n})`):t)));var t}const S=new Set(["http","https","mailto","tel"]);function T(e){const t=e.indexOf(":");if(t<0)return e;const n=e.indexOf("/"),r=e.indexOf("?"),a=e.indexOf("#");if(n>-1&&t>n||r>-1&&t>r||a>-1&&t>a)return e;const o=e.slice(0,t).toLowerCase();return S.has(o)||"data"===o&&/^data:image\//i.test(e)?e:""}const A=e=>e;function I(e,t,n){return e(t).replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]??""):e)}function E(e,t,n,r={}){const a=I(e,t,r),o=`{${n}}`,s=a.indexOf(o);return-1===s?{before:a,after:"",hasSlot:!1}:{before:a.slice(0,s),after:a.slice(s+o.length),hasSlot:!0}}function z(e){let t=e;for(;t;){if(t.classList.contains("filigran-chatbot"))return t;t=t.parentElement}return document.body}function R(e){const t=[["GB",1024**3],["MB",1048576],["KB",1024]];for(const[n,r]of t)if(e>=r)return`${Math.floor(e/r*10)/10} ${n}`;return`${Math.floor(e)} B`}function D(e){return e<1e3?`${e}`:e<1e6?`${(e/1e3).toFixed(e<1e4?1:0).replace(/\.0$/,"")}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}M`}function M(e,t){if(!e)return"";const n=new Date(e).getTime();if(Number.isNaN(n))return"";const r=Date.now()-n,a=Math.floor(r/6e4);if(a<1)return t("just now");if(a<60)return I(t,"{count}m ago",{count:a});const o=Math.floor(a/60);if(o<24)return I(t,"{count}h ago",{count:o});const s=Math.floor(o/24);return s<7?I(t,"{count}d ago",{count:s}):new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}const _=["FILE","PRESENTATION","REPORT","VIDEO"],L=`(${_.join("|")}):([^\\]#]+)(?:#\\/([A-Za-z0-9_-]{1,64}))?`,P=/^[A-Z][A-Z0-9_]*$/;const j=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$=new Map;function U(e){const t=e.filter(e=>!_.includes(e)),n=t.join(","),r=$.get(n);if(r)return r;const a=[..._,...t].map(j).join("|"),o=t.length>0?`|(${t.map(j).join("|")}):([^\\]]+)`:"",s=[..._,...t].map(e=>`[[${e}:`),i={complete:new RegExp(`\\[\\[(?:${L}${o})\\]\\]`,"gi"),partial:new RegExp(`\\[\\[(?:${a})(?::[^\\]]*)?\\]?$`,"i"),heads:s,longestHead:Math.max(...s.map(e=>e.length))};return $.size>=32&&$.delete($.keys().next().value),$.set(n,i),i}function O(e,t=!1,n=[]){if(!e)return[];const r=U(n),a=[];let o=0;for(const t of e.matchAll(r.complete)){if(t.index>o&&a.push({type:"text",value:e.slice(o,t.index)}),t[1]){const e=t[1].toUpperCase();n.includes(e)?a.push({type:"marker",kind:e,args:t[3]?`${t[2]}#/${t[3]}`:t[2]}):"FILE"===e?a.push({type:"file",fileId:t[2]}):a.push({type:"artifact",kind:e.toLowerCase(),id:t[2].toLowerCase(),slideRef:t[3]||void 0})}else a.push({type:"marker",kind:t[4].toUpperCase(),args:t[5]});o=t.index+t[0].length}const s=e.slice(o).replace(r.partial,""),i=t?function(e,t){for(let n=Math.max(0,e.length-t.longestHead);n<e.length;n++){if("["!==e[n])continue;const r=e.slice(n).toUpperCase();if(t.heads.some(e=>e.startsWith(r)))return e.slice(0,n)}return e}(s,r):s;return i&&a.push({type:"text",value:i}),a}function W(e,t=[]){const n=[];for(const r of O(e,!1,t))"text"===r.type&&r.value.trim()&&n.push(N(r.value));return n}const q=(e,t)=>`${e}:${t.toLowerCase()}`;function F(e,t){const n=[];if("presentation"===e.kind&&void 0!==e.slideCount&&n.push(I(t,"{count} slides",{count:e.slideCount})),"report"===e.kind&&void 0!==e.sectionCount&&n.push(I(t,"{count} sections",{count:e.sectionCount})),"video"===e.kind){void 0!==e.sceneCount&&n.push(I(t,"{count} scenes",{count:e.sceneCount}));const r=function(e){if(!e||e<=0)return;const t=Math.round(e/1e3);return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}(e.durationMs);r&&n.push(r)}return n.join(" · ")}function B(e,...t){if(e)try{return e(...t)}catch(e){return void console.error("A chat panel host callback threw",e)}}const H={slack:"Slack",teams:"Teams",whatsapp:"WhatsApp",telegram:"Telegram",discord:"Discord",google_chat:"Google Chat"};function V(e,t){if(!e)return null;const n=B(t,e);return void 0!==n?n?.trim()||null:H[e.toLowerCase()]??null}const K=b().use(w).use(v).freeze(),G=new Set(["code","html","image","imageReference","definition","footnoteDefinition","footnoteReference","thematicBreak"]);function X(e){if(G.has(e.type))return"";if("text"===e.type||"inlineCode"===e.type)return e.value??"";if("break"===e.type)return" ";const t=(e.children??[]).map(X).join("");return"link"!==e.type||!e.url||t!==e.url&&`mailto:${t}`!==e.url?t:""}function Y(e,t){if(!G.has(e.type))switch(e.type){case"paragraph":case"heading":return void t.push(X(e));case"tableRow":return void t.push((e.children??[]).map(X).map(e=>e.trim()).filter(Boolean).join(", "));default:for(const n of e.children??[])Y(n,t)}}function J(e){const t=[];for(const n of e)n.trim()&&Y(K.parse(n),t);return t.map(e=>e.replace(/\s+/g," ").replace(/ ([.,!?;:])/g,"$1").trim()).filter(e=>/[\p{L}\p{N}]/u.test(e)).map(e=>/[.!?;:\u3002\uff01\uff1f]$/.test(e)?e:`${e}.`).join("\n")}const Q=/^[ \t]*((`|~)\2{2,})[\s\S]*?(?:^[ \t]*\1\2*[ \t]*$|(?![\s\S]))/gm;function Z(e,t=220){const n=e.split(/\n+|(?<=[.!?;:\u3002\uff01\uff1f])\s+/).map(e=>e.trim()).filter(Boolean),r=[];for(const e of n){if(e.length<=t){r.push(e);continue}let n="";for(const a of e.split(" "))for(let e=0;e<a.length;e+=t){const o=a.slice(e,e+t);n?n.length+1+o.length<=t?n=`${n} ${o}`:(r.push(n),n=o):n=o}n&&r.push(n)}const a=[];for(const e of r){const n=a.length-1;n>=0&&a[n].length+1+e.length<=t?a[n]=`${a[n]} ${e}`:a.push(e)}return a}async function*ee(e,t,n,r){const a=a=>async function(e,t,n,r){const a=await e(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.requestHeaders??{}},body:JSON.stringify({text:n,format:"mp3"}),signal:r});if(!a.ok)throw new Error(`TTS failed: ${a.status}`);return a.blob()}(e,t,n[a],r).catch(()=>null);let o=n.length>0?a(0):null;for(let e=0;o;e+=1){const t=await o;o=e+1<n.length&&!r.aborted?a(e+1):null,yield t}}const te=new Set(["text","search","url","email","tel","password"]);function ne(e,t,n,r){const a=t?.[r];return"rest"!==n||t?.singleEndpoint||"string"!=typeof a||!a?null:`${e}${a}`}const re={surface:"--filigran-chat-surface",surfaceRaised:"--filigran-chat-surface-raised",surfaceSubtle:"--filigran-chat-surface-subtle",surfaceHover:"--filigran-chat-surface-hover",inputSurface:"--filigran-chat-input-surface",inputRadius:"--filigran-chat-input-radius",radiusSm:"--filigran-chat-radius-sm",radiusMd:"--filigran-chat-radius-md",inputMinHeight:"--filigran-chat-input-min-height",focusRing:"--filigran-chat-focus-ring",danger:"--filigran-chat-danger",warning:"--filigran-chat-warning",headerBackground:"--filigran-chat-header-background",text:"--filigran-chat-text",textMuted:"--filigran-chat-text-muted",textSecondary:"--filigran-chat-text-secondary",border:"--filigran-chat-border",textSize:"--filigran-chat-text-size",userBackground:"--filigran-chat-user-background",userText:"--filigran-chat-user-text",userRadius:"--filigran-chat-user-radius",userPadding:"--filigran-chat-user-padding",userTextSize:"--filigran-chat-user-text-size",fontMono:"--filigran-chat-font-mono",codeSize:"--filigran-chat-code-size",codeSurface:"--filigran-chat-code-surface"};function ae(e){const t={};if(!e)return t;for(const[n,r]of Object.entries(re)){const a=e[n];"string"==typeof a&&a.trim()&&(t[r]=a)}return t}const oe={de:{"(no output)":"(keine Ausgabe)","1 tool call":"1 Tool-Aufruf","1 transfer":"1 Übergabe","A file failed to upload: remove it to send the message":"Eine Datei konnte nicht hochgeladen werden: Entfernen Sie sie, um die Nachricht zu senden","A message references at most {count} conversations":"Eine Nachricht verweist auf höchstens {count} Unterhaltungen","Acting on the page…":"Aktion auf der Seite…","Agent · {channel}":"Agent · {channel}","Agent switching is not available here":"Der Agentenwechsel ist hier nicht verfügbar","Almost there":"Gleich geschafft","Also applies to your scheduled runs, until you revoke it":"Gilt auch für Ihre geplanten Ausführungen, bis Sie die Freigabe widerrufen","Always allowed":"Immer erlaubt","Analyzing results (step {step})…":"Ergebnisse werden analysiert (Schritt {step})…","Analyzing results…":"Ergebnisse werden analysiert…","Analyzing the details":"Details werden analysiert",Approved:"Genehmigt","Archive all conversations":"Alle Unterhaltungen archivieren","Archive all conversations?":"Alle Unterhaltungen archivieren?","Ask Assistant":"Assistenten fragen","Ask a question...":"Stellen Sie eine Frage...",Assistant:"Assistent","Attach files":"Dateien anhängen","Attached files":"Angehängte Dateien","Attachments wait for the current response":"Anhänge warten auf die aktuelle Antwort",Back:"Zurück","Bad response":"Schlechte Antwort","Browse agents":"Agenten durchsuchen",Cancel:"Abbrechen","Cancel question":"Frage abbrechen","Clear all conversations":"Alle Unterhaltungen leeren",Close:"Schließen","Collecting results from one task…":"Ergebnisse einer Aufgabe werden gesammelt…","Collecting results from {count} tasks…":"Ergebnisse von {count} Aufgaben werden gesammelt…","Compacting conversation context…":"Kontext der Unterhaltung wird verdichtet…","Composing answer…":"Antwort wird verfasst…",Confirm:"Bestätigen","Connecting integrations…":"Integrationen werden verbunden…","Connecting the dots":"Zusammenhänge werden hergestellt","Consulting an agent…":"Ein Agent wird konsultiert…","Consulting the sources":"Quellen werden geprüft","Consulting {agent}…":"{agent} wird konsultiert…","Consulting {agent}: {count} questions…":"{agent} wird konsultiert: {count} Fragen…","Consulting {agent}: {tool} (+{count} more)…":"{agent} wird konsultiert: {tool} (+{count} weitere)…","Consulting {agent}: {tool}…":"{agent} wird konsultiert: {tool}…","Consulting {agent}: writing the answer…":"{agent} wird konsultiert: Antwort wird verfasst…","Consulting {count} agents…":"{count} Agenten werden konsultiert…","Context full — older turns are being dropped":"Kontext voll — ältere Runden werden verworfen","Context nearly full — older turns are being summarized":"Kontext fast voll — ältere Runden werden zusammengefasst","Context used":"Genutzter Kontext","Continue now":"Jetzt fortfahren",Conversation:"Unterhaltung","Conversation history":"Verlauf der Unterhaltungen","Conversation title":"Titel der Unterhaltung","Conversation transcript":"Verlauf der Unterhaltung",Copied:"Kopiert","Copied!":"Kopiert!","Copy code":"Code kopieren",Conversations:"Unterhaltungen","Copy message":"Nachricht kopieren","Copy response":"Antwort kopieren","Could not load your conversations.":"Ihre Unterhaltungen konnten nicht geladen werden.","Could not reach the assistant service. Check the connection and try again.":"Der Assistenzdienst ist nicht erreichbar. Prüfen Sie die Verbindung und versuchen Sie es erneut.","Could not send your decision. Please try again.":"Ihre Entscheidung konnte nicht gesendet werden. Bitte versuchen Sie es erneut.","Create agent":"Agent erstellen","Crunching the data":"Daten werden ausgewertet","Decline this call":"Diesen Aufruf ablehnen",Declined:"Abgelehnt","Delegating one task…":"Eine Aufgabe wird delegiert…","Delegating {count} tasks…":"{count} Aufgaben werden delegiert…","Delete all conversations":"Alle Unterhaltungen löschen","Delete all conversations?":"Alle Unterhaltungen löschen?","Delete conversation":"Unterhaltung löschen","Delete workspace":"Arbeitsbereich löschen","Delete?":"Löschen?","Dictate a message":"Nachricht diktieren","Did not answer":"Nicht beantwortet",Download:"Herunterladen","Download {format}":"Als {format} herunterladen","Drop a conversation here, or start one with {icon}.":"Legen Sie hier eine Unterhaltung ab oder beginnen Sie eine mit {icon}.","Drop files to attach them":"Dateien zum Anhängen hier ablegen","End voice call":"Sprachanruf beenden","Enter to send · Shift+Enter for new line":"Eingabetaste zum Senden · Umschalt+Eingabetaste für eine neue Zeile","Enter to send now · Esc to stop":"Eingabetaste zum sofortigen Senden · Esc zum Anhalten","Enter to send when the answer ends · Esc to stop":"Eingabetaste zum Senden nach der Antwort · Esc zum Anhalten","Expand image":"Bild vergrößern","Failed to get a response. Resuming…":"Keine Antwort erhalten. Wird fortgesetzt…","Feedback already submitted":"Feedback bereits gesendet","Files uploading...":"Dateien werden hochgeladen...",Floating:"Schwebend","Full screen":"Vollbild","Good response":"Gute Antwort","Hide conversations":"Unterhaltungen ausblenden","Resize the conversation list":"Größe der Unterhaltungsliste ändern","How can I help you, {name}?":"Wie kann ich Ihnen helfen, {name}?","How can {agent} help you, {name}?":"Wie kann {agent} Ihnen helfen, {name}?","Image could not be loaded":"Bild konnte nicht geladen werden","Image preview":"Bildvorschau","Incorporating your message…":"Ihre Nachricht wird einbezogen…",Input:"Eingabe","Insert prompt template":"Prompt-Vorlage einfügen","Interrupted by a server restart.":"Durch einen Serverneustart unterbrochen.","Listening...":"Hört zu...","Load earlier messages":"Frühere Nachrichten laden","Loading earlier messages…":"Frühere Nachrichten werden geladen…","Loading conversation history…":"Verlauf der Unterhaltung wird geladen…","Loading image…":"Bild wird geladen…","MCP & dynamic tools":"MCP und dynamische Tools","Mention an agent":"Einen Agenten erwähnen","Model reasoning":"Überlegungen des Modells","Move to workspace":"In Arbeitsbereich verschieben","Mute microphone":"Mikrofon stummschalten",Muted:"Stummgeschaltet","New chat":"Neuer Chat","New conversation":"Neue Unterhaltung","New conversation in this workspace":"Neue Unterhaltung in diesem Arbeitsbereich","New conversation outside a workspace":"Neue Unterhaltung außerhalb eines Arbeitsbereichs","New conversation — send a message to start it":"Neue Unterhaltung — senden Sie eine Nachricht, um sie zu beginnen","New workspace":"Neuer Arbeitsbereich",No:"Nein","No agent matches":"Kein passender Agent","None of your conversations matches":"Keine Ihrer Unterhaltungen passt","No conversation matches":"Keine passende Unterhaltung","No conversations yet":"Noch keine Unterhaltungen","No prompt matches":"Kein passender Prompt","No response was generated. Please try again.":"Es wurde keine Antwort erzeugt. Bitte versuchen Sie es erneut.","No response.":"Keine Antwort.","Not recommended for chat":"Nicht für den Chat empfohlen","Not rendered yet":"Noch nicht gerendert",Open:"Öffnen","Open agent page":"Agentenseite öffnen","Open conversation":"Unterhaltung öffnen","Open in XTM One":"In XTM One öffnen","Other workspaces":"Andere Arbeitsbereiche",Output:"Ausgabe","Play Space Invaders":"Space Invaders spielen","Play Space Invaders in XTM One":"Space Invaders in XTM One spielen","Polishing the answer":"Antwort wird verfeinert",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (bearbeitbar)","Preparing tools…":"Tools werden vorbereitet…","Preparing…":"Wird vorbereitet…",Presentation:"Präsentation","Putting it together":"Alles wird zusammengefügt",Quota:"Kontingent","Quota reached":"Kontingent erreicht","Read aloud":"Vorlesen","Reasoning details":"Details der Überlegungen","Reasoning details — interrupted by a server restart":"Details der Überlegungen — durch einen Serverneustart unterbrochen","Reasoning details — turn limit reached":"Details der Überlegungen — Rundenlimit erreicht","Recalling memory…":"Gedächtnis wird abgerufen…","Reconnecting…":"Verbindung wird wiederhergestellt…","Reference a conversation":"Auf eine Unterhaltung verweisen","Remove from workspace":"Aus Arbeitsbereich entfernen","Rename conversation":"Unterhaltung umbenennen","Rename workspace":"Arbeitsbereich umbenennen","Rendering {progress}%":"Wird gerendert: {progress} %",Report:"Bericht","Response ready":"Antwort bereit","Reticulating splines":"Splines werden retikuliert",Retry:"Erneut versuchen",Save:"Speichern","Scroll to bottom":"Nach unten scrollen","Saving response…":"Antwort wird gespeichert…","Search agents...":"Agenten suchen...","Search conversations...":"Unterhaltungen suchen...","Search prompts...":"Prompts suchen...",Send:"Senden","Send now":"Jetzt senden","Send when the answer ends":"Nach der Antwort senden","Sending…":"Wird gesendet…","Sends when the answer ends:":"Wird nach der Antwort gesendet:","Several agents are answering: your message is sent once they are done.":"Mehrere Agenten antworten: Ihre Nachricht wird gesendet, sobald sie fertig sind.","Shared with you":"Mit Ihnen geteilt","Show conversations":"Unterhaltungen anzeigen","Show less":"Weniger anzeigen",Sidebar:"Seitenleiste",Skip:"Überspringen","Skip response":"Antwort überspringen","Sorry, an error occurred. Please try again.":"Leider ist ein Fehler aufgetreten. Bitte versuchen Sie es erneut.","Speak or tap to interrupt":"Sprechen oder tippen Sie, um zu unterbrechen","Speaking…":"Spricht…","Started in {channel}":"Begonnen in {channel}","Stop dictation":"Diktat beenden","Stop generating":"Generierung anhalten","Stop reading":"Vorlesen beenden",Stopped:"Angehalten","Stopping…":"Wird angehalten…",Suggestions:"Vorschläge","Summarized conversation":"Zusammengefasste Unterhaltung","Summarizing earlier conversation…":"Früherer Teil der Unterhaltung wird zusammengefasst…",Superseded:"Ersetzt","Switch to":"Wechseln zu","Switch to another agent":"Zu einem anderen Agenten wechseln","Switch view":"Ansicht wechseln","System prompt":"System-Prompt","Tap to cancel":"Zum Abbrechen tippen","Tell us what went wrong (optional)":"Was ist schiefgelaufen? (optional)","The agent is answering…":"Der Agent antwortet…","The agent needs your approval to run a tool:":"Der Agent benötigt Ihre Freigabe, um ein Tool auszuführen:","The agent needs your approval to run these tools:":"Der Agent benötigt Ihre Freigabe, um diese Tools auszuführen:","The agents you mentioned are asked as soon as the current answer ends.":"Die erwähnten Agenten werden gefragt, sobald die aktuelle Antwort endet.","The conversation could not be deleted":"Die Unterhaltung konnte nicht gelöscht werden","The conversation could not be moved":"Die Unterhaltung konnte nicht verschoben werden","The conversations you referenced are read with your message once the current answer ends.":"Die referenzierten Unterhaltungen werden mit Ihrer Nachricht gelesen, sobald die aktuelle Antwort endet.","The conversation could not be renamed":"Die Unterhaltung konnte nicht umbenannt werden","The conversations could not be archived":"Die Unterhaltungen konnten nicht archiviert werden","The conversations could not be deleted":"Die Unterhaltungen konnten nicht gelöscht werden","The render did not finish":"Das Rendern wurde nicht abgeschlossen","The server restarted while this turn was running, so it stopped before it could finish.":"Der Server wurde während dieser Runde neu gestartet, daher wurde sie vor ihrem Abschluss beendet.","The workspace could not be created":"Der Arbeitsbereich konnte nicht erstellt werden","The workspace could not be deleted":"Der Arbeitsbereich konnte nicht gelöscht werden","The workspace could not be renamed":"Der Arbeitsbereich konnte nicht umbenannt werden","Thinking it through":"Wird durchdacht","Thinking...":"Denkt nach...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Dieser Agent ist für Aufträge gedacht, nicht für den direkten Chat. Auf Unterhaltungen antwortet er womöglich schlecht.","This conversation could not be loaded.":"Diese Unterhaltung konnte nicht geladen werden.","This decision could not be sent. Reload the chat and try again.":"Diese Entscheidung konnte nicht gesendet werden. Laden Sie den Chat neu und versuchen Sie es erneut.","This message waits for the current response":"Diese Nachricht wartet auf die aktuelle Antwort","This message will be read with your next one.":"Diese Nachricht wird mit Ihrer nächsten gelesen.","This item could not be loaded.":"Dieses Element konnte nicht geladen werden.","The response could not be stopped. Try again.":"Die Antwort konnte nicht angehalten werden. Versuchen Sie es erneut.","This turn is no longer waiting for a decision.":"Diese Runde wartet nicht mehr auf eine Entscheidung.","Tool definitions":"Tool-Definitionen","Tool results":"Tool-Ergebnisse","Transfer chain":"Übergabekette","Transferred from {agent}":"Übergeben von {agent}","Transferring to another agent…":"Übergabe an einen anderen Agenten…","Transferring to {agent}…":"Übergabe an {agent}…","Turn limit reached.":"Rundenlimit erreicht.","Unable to connect. Please check the configuration.":"Verbindung nicht möglich. Bitte prüfen Sie die Konfiguration.","Unmute microphone":"Stummschaltung des Mikrofons aufheben","Untitled conversation":"Unbenannte Unterhaltung",Usage:"Nutzung","Upload failed":"Hochladen fehlgeschlagen","Usage · {period}":"Nutzung · {period}","Uses AI. Verify results.":"Nutzt KI. Überprüfen Sie die Ergebnisse.","Using tools…":"Tools werden verwendet…",Video:"Video","Voice call":"Sprachanruf","Waiting before continuing…":"Wartet vor dem Fortfahren…","Waiting for one background task…":"Wartet auf eine Hintergrundaufgabe…","Waiting for your approval…":"Wartet auf Ihre Freigabe…","Waiting for {count} background tasks…":"Wartet auf {count} Hintergrundaufgaben…","Waiting to render":"Wartet auf das Rendern","What could be improved?":"Was könnte verbessert werden?","Why not? The agent sees this and can adapt (optional)":"Warum nicht? Der Agent sieht dies und kann sich anpassen (optional)","Working files ({count})":"Arbeitsdateien ({count})","Workspace name":"Name des Arbeitsbereichs",Workspaces:"Arbeitsbereiche","Wrapping things up":"Wird abgeschlossen",Yes:"Ja","Yes, always":"Ja, immer","Your answer is ready":"Ihre Antwort ist bereit",default:"Standard","e.g. wrong environment — use staging instead":"z. B. falsche Umgebung — stattdessen die Staging-Umgebung verwenden","just now":"gerade eben","this month":"diesen Monat","this year":"dieses Jahr",today:"heute","unknown tool":"unbekanntes Tool","{agent} has finished":"{agent} ist fertig","{agent} is answering…":"{agent} antwortet…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"{counts} Tokens","{count} iterations":"{count} Iterationen","{count} scenes":"{count} Szenen","{count} sections":"{count} Abschnitte","{count} slides":"{count} Folien","{count} tool calls":"{count} Tool-Aufrufe","{count} transfers":"{count} Übergaben","{count}d ago":"vor {count} T.","{count}h ago":"vor {count} Std.","{count}m ago":"vor {count} Min.","{decided}/{total} decided":"{decided}/{total} entschieden","{name} was not attached: a file may be at most {size}.":"{name} wurde nicht angehängt: Eine Datei darf höchstens {size} groß sein.","{name} was not attached: a message holds at most {count} files.":"{name} wurde nicht angehängt: Eine Nachricht enthält höchstens {count} Dateien.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} wurde nicht angehängt: Die Dateien einer Nachricht dürfen zusammen höchstens {size} groß sein.","{name} was not attached: this type of file is not accepted.":"{name} wurde nicht angehängt: Dieser Dateityp wird nicht akzeptiert.","{percent}% full":"{percent} % belegt","{quota} (shared across all users)":"{quota} (von allen Benutzern gemeinsam genutzt)","{summary} — click for details":"{summary} — für Details klicken","{tool} (+{count} more)…":"{tool} (+{count} weitere)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Das Iterationsbudget des Agenten ist aufgebraucht: Die Ausführung wurde beendet, bevor alle geplanten Schritte abgeschlossen waren. Die endgültige Antwort fasst die bisher geleistete Arbeit so gut wie möglich zusammen.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"„Ja, immer“ speichert eine Einstellung für Sie. Dieses Tool wird dann ohne Nachfrage ausgeführt — auch bei geplanten Ausführungen, die niemand beobachtet —, bis Sie die Freigabe widerrufen."},es:{"(no output)":"(sin salida)","1 tool call":"1 llamada a una herramienta","1 transfer":"1 transferencia","A file failed to upload: remove it to send the message":"Un archivo no se pudo subir: quítelo para enviar el mensaje","A message references at most {count} conversations":"Un mensaje puede hacer referencia a {count} conversaciones como máximo","Acting on the page…":"Actuando en la página…","Agent · {channel}":"Agente · {channel}","Agent switching is not available here":"El cambio de agente no está disponible aquí","Almost there":"Ya casi estamos","Also applies to your scheduled runs, until you revoke it":"También se aplica a sus ejecuciones programadas, hasta que lo revoque","Always allowed":"Siempre permitido","Analyzing results (step {step})…":"Analizando los resultados (paso {step})…","Analyzing results…":"Analizando los resultados…","Analyzing the details":"Analizando los detalles",Approved:"Aprobado","Archive all conversations":"Archivar todas las conversaciones","Archive all conversations?":"¿Archivar todas las conversaciones?","Ask Assistant":"Preguntar al asistente","Ask a question...":"Haga una pregunta...",Assistant:"Asistente","Attach files":"Adjuntar archivos","Attached files":"Archivos adjuntos","Attachments wait for the current response":"Los archivos adjuntos esperan la respuesta actual",Back:"Volver","Bad response":"Respuesta incorrecta","Browse agents":"Explorar agentes",Cancel:"Cancelar","Cancel question":"Cancelar la pregunta","Clear all conversations":"Borrar todas las conversaciones",Close:"Cerrar","Collecting results from one task…":"Recopilando los resultados de una tarea…","Collecting results from {count} tasks…":"Recopilando los resultados de {count} tareas…","Compacting conversation context…":"Compactando el contexto de la conversación…","Composing answer…":"Redactando la respuesta…",Confirm:"Confirmar","Connecting integrations…":"Conectando las integraciones…","Connecting the dots":"Atando cabos","Consulting an agent…":"Consultando a un agente…","Consulting the sources":"Consultando las fuentes","Consulting {agent}…":"Consultando a {agent}…","Consulting {agent}: {count} questions…":"Consultando a {agent}: {count} preguntas…","Consulting {agent}: {tool} (+{count} more)…":"Consultando a {agent}: {tool} (+{count} más)…","Consulting {agent}: {tool}…":"Consultando a {agent}: {tool}…","Consulting {agent}: writing the answer…":"Consultando a {agent}: redactando la respuesta…","Consulting {count} agents…":"Consultando a {count} agentes…","Context full — older turns are being dropped":"Contexto completo: se están eliminando los turnos más antiguos","Context nearly full — older turns are being summarized":"El contexto está casi lleno: se están resumiendo los turnos más antiguos","Context used":"Contexto utilizado","Continue now":"Continuar ahora",Conversation:"Conversación","Conversation history":"Historial de conversaciones","Conversation title":"Título de la conversación","Conversation transcript":"Hilo de la conversación",Copied:"Copiado","Copied!":"¡Copiado!","Copy code":"Copiar código",Conversations:"Conversaciones","Copy message":"Copiar mensaje","Copy response":"Copiar respuesta","Could not load your conversations.":"No se pudieron cargar sus conversaciones.","Could not reach the assistant service. Check the connection and try again.":"No se ha podido conectar con el servicio del asistente. Compruebe la conexión e inténtelo de nuevo.","Could not send your decision. Please try again.":"No se ha podido enviar su decisión. Inténtelo de nuevo.","Create agent":"Crear agente","Crunching the data":"Procesando los datos","Decline this call":"Rechazar esta llamada",Declined:"Rechazado","Delegating one task…":"Delegando una tarea…","Delegating {count} tasks…":"Delegando {count} tareas…","Delete all conversations":"Eliminar todas las conversaciones","Delete all conversations?":"¿Eliminar todas las conversaciones?","Delete conversation":"Eliminar conversación","Delete workspace":"Eliminar espacio de trabajo","Delete?":"¿Eliminar?","Dictate a message":"Dictar un mensaje","Did not answer":"No respondió",Download:"Descargar","Download {format}":"Descargar en {format}","Drop a conversation here, or start one with {icon}.":"Suelte aquí una conversación o inicie una con {icon}.","Drop files to attach them":"Suelte los archivos para adjuntarlos","End voice call":"Finalizar la llamada de voz","Enter to send · Shift+Enter for new line":"Pulse Intro para enviar · Mayús+Intro para una nueva línea","Enter to send now · Esc to stop":"Pulse Intro para enviar ahora · Esc para detener","Enter to send when the answer ends · Esc to stop":"Pulse Intro para enviar cuando termine la respuesta · Esc para detener","Expand image":"Ampliar imagen","Failed to get a response. Resuming…":"No se obtuvo respuesta. Reanudando…","Feedback already submitted":"Valoración ya enviada","Files uploading...":"Cargando archivos...",Floating:"Flotante","Full screen":"Pantalla completa","Good response":"Buena respuesta","Hide conversations":"Ocultar conversaciones","Resize the conversation list":"Cambiar el tamaño de la lista de conversaciones","How can I help you, {name}?":"¿En qué puedo ayudarle, {name}?","How can {agent} help you, {name}?":"¿En qué puede ayudarle {agent}, {name}?","Image could not be loaded":"No se ha podido cargar la imagen","Image preview":"Vista previa de la imagen","Incorporating your message…":"Incorporando su mensaje…",Input:"Entrada","Insert prompt template":"Insertar plantilla de prompt","Interrupted by a server restart.":"Interrumpido por un reinicio del servidor.","Listening...":"Escuchando...","Load earlier messages":"Cargar mensajes anteriores","Loading earlier messages…":"Cargando mensajes anteriores…","Loading conversation history…":"Cargando el historial de la conversación…","Loading image…":"Cargando imagen…","MCP & dynamic tools":"MCP y herramientas dinámicas","Mention an agent":"Mencionar un agente","Model reasoning":"Razonamiento del modelo","Move to workspace":"Mover a un espacio de trabajo","Mute microphone":"Silenciar el micrófono",Muted:"Silenciado","New chat":"Nuevo chat","New conversation":"Nueva conversación","New conversation in this workspace":"Nueva conversación en este espacio de trabajo","New conversation outside a workspace":"Nueva conversación fuera de un espacio de trabajo","New conversation — send a message to start it":"Nueva conversación: envíe un mensaje para iniciarla","New workspace":"Nuevo espacio de trabajo",No:"No","No agent matches":"No hay ningún agente que coincida","None of your conversations matches":"Ninguna de sus conversaciones coincide","No conversation matches":"No hay conversaciones que coincidan","No conversations yet":"Aún no hay conversaciones","No prompt matches":"No hay ningún prompt que coincida","No response was generated. Please try again.":"No se ha generado ninguna respuesta. Inténtalo de nuevo.","No response.":"Sin respuesta.","Not recommended for chat":"No recomendado para chat","Not rendered yet":"Renderizado no iniciado",Open:"Abrir","Open agent page":"Abrir la página del agente","Open conversation":"Abrir conversación","Open in XTM One":"Abrir en XTM One","Other workspaces":"Otros espacios de trabajo",Output:"Salida","Play Space Invaders":"Jugar a Space Invaders","Play Space Invaders in XTM One":"Jugar a Space Invaders en XTM One","Polishing the answer":"Puliendo la respuesta",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (editable)","Preparing tools…":"Preparando las herramientas…","Preparing…":"Preparando…",Presentation:"Presentación","Putting it together":"Juntando las piezas",Quota:"Cuota","Quota reached":"Cuota alcanzada","Read aloud":"Leer en voz alta","Reasoning details":"Detalles del razonamiento","Reasoning details — interrupted by a server restart":"Detalles del razonamiento: interrumpido por un reinicio del servidor","Reasoning details — turn limit reached":"Detalles del razonamiento: se ha alcanzado el límite de turnos","Recalling memory…":"Recuperando la memoria…","Reconnecting…":"Reconectando…","Reference a conversation":"Hacer referencia a una conversación","Remove from workspace":"Quitar del espacio de trabajo","Rename conversation":"Cambiar el nombre de la conversación","Rename workspace":"Cambiar el nombre del espacio de trabajo","Rendering {progress}%":"Renderizando {progress} %",Report:"Informe","Response ready":"Respuesta lista","Reticulating splines":"Reticulando splines",Retry:"Reintentar",Save:"Guardar","Scroll to bottom":"Ir al final","Saving response…":"Guardando la respuesta…","Search agents...":"Buscar agentes...","Search conversations...":"Buscar conversaciones...","Search prompts...":"Buscar prompts...",Send:"Enviar","Send now":"Enviar ahora","Send when the answer ends":"Enviar cuando termine la respuesta","Sending…":"Enviando…","Sends when the answer ends:":"Se enviará cuando termine la respuesta:","Several agents are answering: your message is sent once they are done.":"Varios agentes están respondiendo: su mensaje se enviará cuando terminen.","Shared with you":"Compartido con usted","Show conversations":"Mostrar conversaciones","Show less":"Mostrar menos",Sidebar:"Barra lateral",Skip:"Omitir","Skip response":"Omitir la respuesta","Sorry, an error occurred. Please try again.":"Lo sentimos, se ha producido un error. Inténtelo de nuevo.","Speak or tap to interrupt":"Habla o toca para interrumpir","Speaking…":"Hablando…","Started in {channel}":"Iniciada en {channel}","Stop dictation":"Detener el dictado","Stop generating":"Detener la generación","Stop reading":"Detener la lectura",Stopped:"Detenido","Stopping…":"Deteniendo…",Suggestions:"Sugerencias","Summarized conversation":"Conversación resumida","Summarizing earlier conversation…":"Resumiendo la conversación anterior…",Superseded:"Reemplazado","Switch to":"Cambiar a","Switch to another agent":"Cambiar a otro agente","Switch view":"Cambiar de vista","System prompt":"Prompt del sistema","Tap to cancel":"Toca para cancelar","Tell us what went wrong (optional)":"Indíquenos qué ha fallado (opcional)","The agent is answering…":"El agente está respondiendo…","The agent needs your approval to run a tool:":"El agente necesita su aprobación para ejecutar una herramienta:","The agent needs your approval to run these tools:":"El agente necesita su aprobación para ejecutar estas herramientas:","The agents you mentioned are asked as soon as the current answer ends.":"Se preguntará a los agentes que mencionó en cuanto termine la respuesta actual.","The conversation could not be deleted":"No se ha podido eliminar la conversación","The conversation could not be moved":"No se ha podido mover la conversación","The conversations you referenced are read with your message once the current answer ends.":"Las conversaciones que referenció se leerán con su mensaje en cuanto termine la respuesta actual.","The conversation could not be renamed":"No se ha podido cambiar el nombre de la conversación","The conversations could not be archived":"No se han podido archivar las conversaciones","The conversations could not be deleted":"No se han podido eliminar las conversaciones","The render did not finish":"El renderizado no ha finalizado","The server restarted while this turn was running, so it stopped before it could finish.":"El servidor se reinició mientras se ejecutaba este turno, por lo que se detuvo antes de poder terminar.","The workspace could not be created":"No se ha podido crear el espacio de trabajo","The workspace could not be deleted":"No se ha podido eliminar el espacio de trabajo","The workspace could not be renamed":"No se ha podido cambiar el nombre del espacio de trabajo","Thinking it through":"Reflexionando sobre ello","Thinking...":"Pensando...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Este agente está pensado para asignaciones, no para el chat directo. Puede que no responda bien a una conversación.","This conversation could not be loaded.":"No se ha podido cargar esta conversación.","This decision could not be sent. Reload the chat and try again.":"No se ha podido enviar esta decisión. Actualice el chat e inténtelo de nuevo.","This message waits for the current response":"Este mensaje espera la respuesta actual","This message will be read with your next one.":"Este mensaje se leerá con su próximo mensaje.","This item could not be loaded.":"No se ha podido cargar este elemento.","The response could not be stopped. Try again.":"No se ha podido detener la respuesta. Inténtelo de nuevo.","This turn is no longer waiting for a decision.":"Este turno ya no está a la espera de una decisión.","Tool definitions":"Definiciones de herramientas","Tool results":"Resultados de las herramientas","Transfer chain":"Cadena de transferencia","Transferred from {agent}":"Transferido desde {agent}","Transferring to another agent…":"Transfiriendo a otro agente…","Transferring to {agent}…":"Transfiriendo a {agent}…","Turn limit reached.":"Se ha alcanzado el límite de turnos.","Unable to connect. Please check the configuration.":"No se puede establecer conexión. Compruebe la configuración.","Unmute microphone":"Activar el micrófono","Untitled conversation":"Conversación sin título",Usage:"Uso","Upload failed":"Error al subir","Usage · {period}":"Uso · {period}","Uses AI. Verify results.":"Utiliza IA. Verifique los resultados.","Using tools…":"Usando herramientas…",Video:"Vídeo","Voice call":"Llamada de voz","Waiting before continuing…":"Esperando antes de continuar…","Waiting for one background task…":"Esperando una tarea en segundo plano…","Waiting for your approval…":"Esperando su aprobación…","Waiting for {count} background tasks…":"Esperando {count} tareas en segundo plano…","Waiting to render":"Esperando el renderizado","What could be improved?":"¿Qué se podría mejorar?","Why not? The agent sees this and can adapt (optional)":"¿Por qué no? El agente ve esto y puede adaptarse (opcional)","Working files ({count})":"Archivos de trabajo ({count})","Workspace name":"Nombre del espacio de trabajo",Workspaces:"Espacios de trabajo","Wrapping things up":"Finalizando",Yes:"Sí","Yes, always":"Sí, siempre","Your answer is ready":"Su respuesta está lista",default:"predeterminado","e.g. wrong environment — use staging instead":"Por ejemplo, entorno incorrecto: utilice el entorno de pruebas en su lugar","just now":"hace un momento","this month":"este mes","this year":"este año",today:"hoy","unknown tool":"herramienta desconocida","{agent} has finished":"{agent} ha finalizado","{agent} is answering…":"{agent} está respondiendo…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"{counts} tokens","{count} iterations":"{count} iteraciones","{count} scenes":"{count} escenas","{count} sections":"{count} secciones","{count} slides":"{count} diapositivas","{count} tool calls":"{count} llamadas a herramientas","{count} transfers":"{count} transferencias","{count}d ago":"hace {count} d","{count}h ago":"hace {count} h","{count}m ago":"hace {count} min","{decided}/{total} decided":"{decided}/{total} decididos","{name} was not attached: a file may be at most {size}.":"{name} no se adjuntó: un archivo puede ocupar como máximo {size}.","{name} was not attached: a message holds at most {count} files.":"{name} no se adjuntó: un mensaje admite como máximo {count} archivos.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} no se adjuntó: los archivos de un mensaje pueden sumar como máximo {size}.","{name} was not attached: this type of file is not accepted.":"{name} no se adjuntó: este tipo de archivo no se acepta.","{percent}% full":"{percent} % completo","{quota} (shared across all users)":"{quota} (compartido entre todos los usuarios)","{summary} — click for details":"{summary} — haga clic para ver más detalles","{tool} (+{count} more)…":"{tool} (+{count} más)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Se agotó el presupuesto de iteraciones del agente: la ejecución se detuvo antes de completar todos los pasos previstos. La respuesta final es un resumen aproximado del trabajo realizado hasta ahora.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"«Sí, siempre» guarda una preferencia para ti. Esa herramienta se ejecutará entonces sin preguntar, incluso en ejecuciones programadas que nadie supervisa, hasta que la revoques."},fr:{"(no output)":"(pas de sortie)","1 tool call":"1 appel d’outil","1 transfer":"1 transfert","A file failed to upload: remove it to send the message":"Un fichier n’a pas pu être envoyé : retirez-le pour envoyer le message","A message references at most {count} conversations":"Un message fait référence à {count} conversations au maximum","Acting on the page…":"Action sur la page…","Agent · {channel}":"Agent · {channel}","Agent switching is not available here":"Le changement d’agent n’est pas disponible ici","Almost there":"On y est presque","Also applies to your scheduled runs, until you revoke it":"S’applique également à vos exécutions planifiées, jusqu’à ce que vous la révoquiez","Always allowed":"Toujours autorisé","Analyzing results (step {step})…":"Analyse des résultats (étape {step})…","Analyzing results…":"Analyse des résultats…","Analyzing the details":"Analyse des détails",Approved:"Approuvé","Archive all conversations":"Archiver toutes les conversations","Archive all conversations?":"Archiver toutes les conversations ?","Ask Assistant":"Demander à l’assistant","Ask a question...":"Poser une question...",Assistant:"Assistant","Attach files":"Joindre des fichiers","Attached files":"Fichiers joints","Attachments wait for the current response":"Les pièces jointes attendent la réponse en cours",Back:"Retour","Bad response":"Réponse incorrecte","Browse agents":"Parcourir les agents",Cancel:"Annuler","Cancel question":"Annuler la question","Clear all conversations":"Effacer toutes les conversations",Close:"Fermer","Collecting results from one task…":"Collecte des résultats d’une tâche…","Collecting results from {count} tasks…":"Collecte des résultats de {count} tâches…","Compacting conversation context…":"Compactage du contexte de la conversation…","Composing answer…":"Rédaction de la réponse…",Confirm:"Confirmer","Connecting integrations…":"Connexion des intégrations…","Connecting the dots":"Relier les points","Consulting an agent…":"Consultation d’un agent…","Consulting the sources":"Consulter les sources","Consulting {agent}…":"Consultation de {agent}…","Consulting {agent}: {count} questions…":"Consultation de {agent} : {count} questions…","Consulting {agent}: {tool} (+{count} more)…":"Consultation de {agent} : {tool} (+{count} autres)…","Consulting {agent}: {tool}…":"Consultation de {agent} : {tool}…","Consulting {agent}: writing the answer…":"Consultation de {agent} : rédaction de la réponse…","Consulting {count} agents…":"Consultation de {count} agents…","Context full — older turns are being dropped":"Contexte complet — les tours plus anciens sont supprimés","Context nearly full — older turns are being summarized":"Contexte presque plein — les tours plus anciens sont en cours de synthèse","Context used":"Contexte utilisé","Continue now":"Continuer maintenant",Conversation:"Conversation","Conversation history":"Historique des conversations","Conversation title":"Titre de la conversation","Conversation transcript":"Fil de la conversation",Copied:"Copié","Copied!":"Copié !","Copy code":"Copier le code",Conversations:"Conversations","Copy message":"Copier le message","Copy response":"Copier la réponse","Could not load your conversations.":"Impossible de charger vos conversations.","Could not reach the assistant service. Check the connection and try again.":"Impossible d’accéder au service d’assistant. Vérifiez la connexion et réessayez.","Could not send your decision. Please try again.":"Impossible d’envoyer votre décision. Veuillez réessayer.","Create agent":"Créer un agent","Crunching the data":"Traitement des données","Decline this call":"Refuser cet appel",Declined:"Refusé","Delegating one task…":"Délégation d’une tâche…","Delegating {count} tasks…":"Délégation de {count} tâches…","Delete all conversations":"Supprimer toutes les conversations","Delete all conversations?":"Supprimer toutes les conversations ?","Delete conversation":"Supprimer la conversation","Delete workspace":"Supprimer l’espace de travail","Delete?":"Supprimer ?","Dictate a message":"Dicter un message","Did not answer":"N’a pas répondu",Download:"Télécharger","Download {format}":"Télécharger en {format}","Drop a conversation here, or start one with {icon}.":"Déposez une conversation ici ou démarrez-en une avec {icon}.","Drop files to attach them":"Déposez des fichiers pour les joindre","End voice call":"Terminer l’appel vocal","Enter to send · Shift+Enter for new line":"Appuyez sur Entrée pour envoyer · Maj+Entrée pour une nouvelle ligne","Enter to send now · Esc to stop":"Appuyez sur Entrée pour envoyer maintenant · Appuyez sur Échap pour arrêter","Enter to send when the answer ends · Esc to stop":"Appuyez sur Entrée pour envoyer à la fin de la réponse · Appuyez sur Échap pour arrêter","Expand image":"Agrandir l’image","Failed to get a response. Resuming…":"Aucune réponse reçue. Reprise…","Feedback already submitted":"Avis déjà envoyé","Files uploading...":"Envoi des fichiers en cours...",Floating:"Flottant","Full screen":"Plein écran","Good response":"Bonne réponse","Hide conversations":"Masquer les conversations","Resize the conversation list":"Redimensionner la liste des conversations","How can I help you, {name}?":"Comment puis-je vous aider, {name} ?","How can {agent} help you, {name}?":"Comment {agent} peut-il vous aider, {name} ?","Image could not be loaded":"Impossible de charger l’image","Image preview":"Aperçu de l’image","Incorporating your message…":"Intégration de votre message…",Input:"Entrée","Insert prompt template":"Insérer un modèle de prompt","Interrupted by a server restart.":"Interrompu par un redémarrage du serveur.","Listening...":"Écoute en cours...","Load earlier messages":"Charger les messages précédents","Loading earlier messages…":"Chargement des messages précédents…","Loading conversation history…":"Chargement de l’historique de la conversation…","Loading image…":"Chargement de l’image…","MCP & dynamic tools":"MCP et outils dynamiques","Mention an agent":"Mentionner un agent","Model reasoning":"Raisonnement du modèle","Move to workspace":"Déplacer vers un espace de travail","Mute microphone":"Couper le micro",Muted:"Micro coupé","New chat":"Nouveau chat","New conversation":"Nouvelle conversation","New conversation in this workspace":"Nouvelle conversation dans cet espace de travail","New conversation outside a workspace":"Nouvelle conversation hors espace de travail","New conversation — send a message to start it":"Nouvelle conversation — envoyez un message pour la démarrer","New workspace":"Nouvel espace de travail",No:"Non","No agent matches":"Aucun agent ne correspond","None of your conversations matches":"Aucune de vos conversations ne correspond","No conversation matches":"Aucune conversation ne correspond","No conversations yet":"Aucune conversation pour l’instant","No prompt matches":"Aucun prompt ne correspond","No response was generated. Please try again.":"Aucune réponse n’a été générée. Veuillez réessayer.","No response.":"Pas de réponse.","Not recommended for chat":"Déconseillé pour le chat","Not rendered yet":"Rendu non lancé",Open:"Ouvrir","Open agent page":"Ouvrir la page de l'agent","Open conversation":"Ouvrir la conversation","Open in XTM One":"Ouvrir dans XTM One","Other workspaces":"Autres espaces de travail",Output:"Sortie","Play Space Invaders":"Jouer à Space Invaders","Play Space Invaders in XTM One":"Jouer à Space Invaders dans XTM One","Polishing the answer":"Peaufiner la réponse",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (modifiable)","Preparing tools…":"Préparation des outils…","Preparing…":"Préparation…",Presentation:"Présentation","Putting it together":"Assemblage des éléments",Quota:"Quota","Quota reached":"Quota atteint","Read aloud":"Lire à voix haute","Reasoning details":"Détails du raisonnement","Reasoning details — interrupted by a server restart":"Détails du raisonnement — interrompu par un redémarrage du serveur","Reasoning details — turn limit reached":"Détails du raisonnement — limite de tours atteinte","Recalling memory…":"Rappel de la mémoire…","Reconnecting…":"Reconnexion…","Reference a conversation":"Faire référence à une conversation","Remove from workspace":"Retirer de l’espace de travail","Rename conversation":"Renommer la conversation","Rename workspace":"Renommer l’espace de travail","Rendering {progress}%":"Rendu en cours : {progress} %",Report:"Rapport","Response ready":"Réponse prête","Reticulating splines":"Réticulation des splines",Retry:"Réessayer",Save:"Sauvegarder","Scroll to bottom":"Aller en bas","Saving response…":"Enregistrement de la réponse…","Search agents...":"Rechercher des agents...","Search conversations...":"Rechercher des conversations...","Search prompts...":"Rechercher des prompts...",Send:"Envoyer","Send now":"Envoyer maintenant","Send when the answer ends":"Envoyer à la fin de la réponse","Sending…":"Envoi en cours…","Sends when the answer ends:":"Envoi à la fin de la réponse :","Several agents are answering: your message is sent once they are done.":"Plusieurs agents répondent : votre message part dès qu’ils ont terminé.","Shared with you":"Partagé avec vous","Show conversations":"Afficher les conversations","Show less":"Afficher moins",Sidebar:"Barre latérale",Skip:"Passer","Skip response":"Passer la réponse","Sorry, an error occurred. Please try again.":"Désolé, une erreur s’est produite. Veuillez réessayer.","Speak or tap to interrupt":"Parlez ou touchez pour interrompre","Speaking…":"Réponse en cours…","Started in {channel}":"Démarrée dans {channel}","Stop dictation":"Arrêter la dictée","Stop generating":"Arrêter la génération","Stop reading":"Arrêter la lecture",Stopped:"Arrêté","Stopping…":"Arrêt en cours…",Suggestions:"Suggestions","Summarized conversation":"Résumé de la conversation","Summarizing earlier conversation…":"Résumé du début de la conversation…",Superseded:"Remplacé","Switch to":"Basculer vers","Switch to another agent":"Passer à un autre agent","Switch view":"Changer de vue","System prompt":"Prompt système","Tap to cancel":"Touchez pour annuler","Tell us what went wrong (optional)":"Dites-nous ce qui n’a pas fonctionné (facultatif)","The agent is answering…":"L’agent répond…","The agent needs your approval to run a tool:":"L’agent a besoin de votre accord pour exécuter un outil :","The agent needs your approval to run these tools:":"L’agent a besoin de votre accord pour exécuter ces outils :","The agents you mentioned are asked as soon as the current answer ends.":"Les agents mentionnés sont sollicités dès la fin de la réponse en cours.","The conversation could not be deleted":"Impossible de supprimer la conversation","The conversation could not be moved":"Impossible de déplacer la conversation","The conversations you referenced are read with your message once the current answer ends.":"Les conversations citées sont lues avec votre message dès la fin de la réponse en cours.","The conversation could not be renamed":"Impossible de renommer la conversation","The conversations could not be archived":"Impossible d’archiver les conversations","The conversations could not be deleted":"Impossible de supprimer les conversations","The render did not finish":"Le rendu n’a pas abouti","The server restarted while this turn was running, so it stopped before it could finish.":"Le serveur a redémarré pendant ce tour, qui s’est donc arrêté avant de pouvoir se terminer.","The workspace could not be created":"Impossible de créer l’espace de travail","The workspace could not be deleted":"Impossible de supprimer l’espace de travail","The workspace could not be renamed":"Impossible de renommer l’espace de travail","Thinking it through":"Réfléchir à la question","Thinking...":"Je réfléchis...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Cet agent est conçu pour des missions, pas pour le chat direct. Il risque de mal répondre à une conversation.","This conversation could not be loaded.":"Impossible de charger cette conversation.","This decision could not be sent. Reload the chat and try again.":"Cette décision n’a pas pu être envoyée. Actualisez le chat et réessayez.","This message waits for the current response":"Ce message attend la réponse en cours","This message will be read with your next one.":"Ce message sera lu avec votre prochain message.","This item could not be loaded.":"Impossible de charger cet élément.","The response could not be stopped. Try again.":"La réponse n’a pas pu être arrêtée. Réessayez.","This turn is no longer waiting for a decision.":"Ce tour n’attend plus de décision.","Tool definitions":"Définitions des outils","Tool results":"Résultats des outils","Transfer chain":"Chaîne de transfert","Transferred from {agent}":"Transféré depuis {agent}","Transferring to another agent…":"Transfert vers un autre agent…","Transferring to {agent}…":"Transfert vers {agent}…","Turn limit reached.":"Limite de tours atteinte.","Unable to connect. Please check the configuration.":"Impossible de se connecter. Veuillez vérifier la configuration.","Unmute microphone":"Réactiver le micro","Untitled conversation":"Conversation sans titre",Usage:"Utilisation","Upload failed":"Échec de l’envoi","Usage · {period}":"Utilisation · {period}","Uses AI. Verify results.":"Utilise l’IA. Vérifiez les résultats.","Using tools…":"Utilisation des outils…",Video:"Vidéo","Voice call":"Appel vocal","Waiting before continuing…":"En attente avant de continuer…","Waiting for one background task…":"En attente d’une tâche en arrière-plan…","Waiting for your approval…":"En attente de votre accord…","Waiting for {count} background tasks…":"En attente de {count} tâches en arrière-plan…","Waiting to render":"En attente du rendu","What could be improved?":"Qu’est-ce qui pourrait être amélioré ?","Why not? The agent sees this and can adapt (optional)":"Pourquoi pas ? L’agent en prend connaissance et peut s’adapter (facultatif)","Working files ({count})":"Fichiers de travail ({count})","Workspace name":"Nom de l’espace de travail",Workspaces:"Espaces de travail","Wrapping things up":"Pour conclure",Yes:"Oui","Yes, always":"Oui, toujours","Your answer is ready":"Votre réponse est prête",default:"par défaut","e.g. wrong environment — use staging instead":"Par exemple : environnement incorrect — utilisez plutôt l’environnement de préproduction","just now":"à l’instant","this month":"ce mois-ci","this year":"cette année",today:"aujourd’hui","unknown tool":"outil inconnu","{agent} has finished":"{agent} a terminé","{agent} is answering…":"{agent} répond…","{agent}: {status}":"{agent} : {status}","{counts} tokens":"{counts} tokens","{count} iterations":"{count} itérations","{count} scenes":"{count} scènes","{count} sections":"{count} sections","{count} slides":"{count} diapositives","{count} tool calls":"{count} appels d’outils","{count} transfers":"{count} transferts","{count}d ago":"il y a {count} j","{count}h ago":"il y a {count} h","{count}m ago":"il y a {count} min","{decided}/{total} decided":"{decided}/{total} décidés","{name} was not attached: a file may be at most {size}.":"{name} n’a pas été joint : un fichier ne peut dépasser {size}.","{name} was not attached: a message holds at most {count} files.":"{name} n’a pas été joint : un message contient au plus {count} fichiers.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} n’a pas été joint : les fichiers d’un message ne peuvent dépasser {size} au total.","{name} was not attached: this type of file is not accepted.":"{name} n’a pas été joint : ce type de fichier n’est pas accepté.","{percent}% full":"{percent} % rempli","{quota} (shared across all users)":"{quota} (partagé entre tous les utilisateurs)","{summary} — click for details":"{summary} — cliquez pour plus de détails","{tool} (+{count} more)…":"{tool} (+{count} autres)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Le budget d’itérations de l’agent est épuisé : l’exécution s’est arrêtée avant la fin de toutes les étapes prévues. La réponse finale résume au mieux le travail accompli jusqu’ici.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"« Oui, toujours » enregistre une préférence pour vous. Cet outil s’exécutera alors sans demander, y compris lors des exécutions planifiées que personne ne surveille, jusqu’à ce que vous la révoquiez."},it:{"(no output)":"(nessun output)","1 tool call":"1 chiamata a strumento","1 transfer":"1 trasferimento","A file failed to upload: remove it to send the message":"Il caricamento di un file non è riuscito: rimuovilo per inviare il messaggio","A message references at most {count} conversations":"Un messaggio può fare riferimento al massimo a {count} conversazioni","Acting on the page…":"Azione sulla pagina…","Agent · {channel}":"Agente · {channel}","Agent switching is not available here":"Il cambio di agente non è disponibile qui","Almost there":"Quasi fatto","Also applies to your scheduled runs, until you revoke it":"Vale anche per le tue esecuzioni pianificate, finché non la revochi","Always allowed":"Sempre consentito","Analyzing results (step {step})…":"Analisi dei risultati (passaggio {step})…","Analyzing results…":"Analisi dei risultati…","Analyzing the details":"Analisi dei dettagli",Approved:"Approvato","Archive all conversations":"Archivia tutte le conversazioni","Archive all conversations?":"Archiviare tutte le conversazioni?","Ask Assistant":"Chiedi all’assistente","Ask a question...":"Fai una domanda...",Assistant:"Assistente","Attach files":"Allega file","Attached files":"File allegati","Attachments wait for the current response":"Gli allegati attendono la risposta in corso",Back:"Indietro","Bad response":"Risposta non valida","Browse agents":"Sfoglia gli agenti",Cancel:"Annulla","Cancel question":"Annulla la domanda","Clear all conversations":"Cancella tutte le conversazioni",Close:"Chiudi","Collecting results from one task…":"Raccolta dei risultati di un’attività…","Collecting results from {count} tasks…":"Raccolta dei risultati di {count} attività…","Compacting conversation context…":"Compattazione del contesto della conversazione…","Composing answer…":"Composizione della risposta…",Confirm:"Conferma","Connecting integrations…":"Connessione delle integrazioni…","Connecting the dots":"Collegamento dei punti","Consulting an agent…":"Consulto con un agente…","Consulting the sources":"Consultazione delle fonti","Consulting {agent}…":"Consulto con {agent}…","Consulting {agent}: {count} questions…":"Consulto con {agent}: {count} domande…","Consulting {agent}: {tool} (+{count} more)…":"Consulto con {agent}: {tool} (+{count} altri)…","Consulting {agent}: {tool}…":"Consulto con {agent}: {tool}…","Consulting {agent}: writing the answer…":"Consulto con {agent}: stesura della risposta…","Consulting {count} agents…":"Consultazione di {count} agenti…","Context full — older turns are being dropped":"Contesto pieno — i turni meno recenti vengono eliminati","Context nearly full — older turns are being summarized":"Contesto quasi pieno — i turni meno recenti vengono riassunti","Context used":"Contesto utilizzato","Continue now":"Continua ora",Conversation:"Conversazione","Conversation history":"Cronologia delle conversazioni","Conversation title":"Titolo della conversazione","Conversation transcript":"Trascrizione della conversazione",Copied:"Copiato","Copied!":"Copiato!","Copy code":"Copia il codice",Conversations:"Conversazioni","Copy message":"Copia il messaggio","Copy response":"Copia la risposta","Could not load your conversations.":"Impossibile caricare le tue conversazioni.","Could not reach the assistant service. Check the connection and try again.":"Impossibile raggiungere il servizio dell’assistente. Controlla la connessione e riprova.","Could not send your decision. Please try again.":"Impossibile inviare la tua decisione. Riprova.","Create agent":"Crea agente","Crunching the data":"Elaborazione dei dati","Decline this call":"Rifiuta questa chiamata",Declined:"Rifiutato","Delegating one task…":"Delega di un’attività…","Delegating {count} tasks…":"Delega di {count} attività…","Delete all conversations":"Elimina tutte le conversazioni","Delete all conversations?":"Eliminare tutte le conversazioni?","Delete conversation":"Elimina la conversazione","Delete workspace":"Elimina l’area di lavoro","Delete?":"Eliminare?","Dictate a message":"Detta un messaggio","Did not answer":"Nessuna risposta",Download:"Scarica","Download {format}":"Scarica in {format}","Drop a conversation here, or start one with {icon}.":"Trascina qui una conversazione o avviane una con {icon}.","Drop files to attach them":"Trascina qui i file per allegarli","End voice call":"Termina la chiamata vocale","Enter to send · Shift+Enter for new line":"Invio per inviare · Maiusc+Invio per andare a capo","Enter to send now · Esc to stop":"Invio per inviare subito · Esc per interrompere","Enter to send when the answer ends · Esc to stop":"Invio per inviare al termine della risposta · Esc per interrompere","Expand image":"Ingrandisci l’immagine","Failed to get a response. Resuming…":"Nessuna risposta ricevuta. Ripresa in corso…","Feedback already submitted":"Feedback già inviato","Files uploading...":"Caricamento dei file in corso...",Floating:"Fluttuante","Full screen":"Schermo intero","Good response":"Risposta valida","Hide conversations":"Nascondi le conversazioni","Resize the conversation list":"Ridimensiona l'elenco delle conversazioni","How can I help you, {name}?":"Come posso aiutarti, {name}?","How can {agent} help you, {name}?":"Come può aiutarti {agent}, {name}?","Image could not be loaded":"Impossibile caricare l’immagine","Image preview":"Anteprima dell’immagine","Incorporating your message…":"Integrazione del tuo messaggio…",Input:"Input","Insert prompt template":"Inserisci un modello di prompt","Interrupted by a server restart.":"Interrotto da un riavvio del server.","Listening...":"In ascolto...","Load earlier messages":"Carica i messaggi precedenti","Loading earlier messages…":"Caricamento dei messaggi precedenti…","Loading conversation history…":"Caricamento della cronologia della conversazione…","Loading image…":"Caricamento dell’immagine…","MCP & dynamic tools":"MCP e strumenti dinamici","Mention an agent":"Menziona un agente","Model reasoning":"Ragionamento del modello","Move to workspace":"Sposta in un’area di lavoro","Mute microphone":"Disattiva il microfono",Muted:"Microfono disattivato","New chat":"Nuova chat","New conversation":"Nuova conversazione","New conversation in this workspace":"Nuova conversazione in quest’area di lavoro","New conversation outside a workspace":"Nuova conversazione fuori da un’area di lavoro","New conversation — send a message to start it":"Nuova conversazione — invia un messaggio per avviarla","New workspace":"Nuova area di lavoro",No:"No","No agent matches":"Nessun agente corrispondente","None of your conversations matches":"Nessuna delle tue conversazioni corrisponde","No conversation matches":"Nessuna conversazione corrispondente","No conversations yet":"Ancora nessuna conversazione","No prompt matches":"Nessun prompt corrispondente","No response was generated. Please try again.":"Non è stata generata alcuna risposta. Riprova.","No response.":"Nessuna risposta.","Not recommended for chat":"Sconsigliato per la chat","Not rendered yet":"Rendering non ancora avviato",Open:"Apri","Open agent page":"Apri la pagina dell'agente","Open conversation":"Apri la conversazione","Open in XTM One":"Apri in XTM One","Other workspaces":"Altre aree di lavoro",Output:"Output","Play Space Invaders":"Gioca a Space Invaders","Play Space Invaders in XTM One":"Gioca a Space Invaders in XTM One","Polishing the answer":"Rifinitura della risposta",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (modificabile)","Preparing tools…":"Preparazione degli strumenti…","Preparing…":"Preparazione…",Presentation:"Presentazione","Putting it together":"Assemblaggio degli elementi",Quota:"Quota","Quota reached":"Quota raggiunta","Read aloud":"Leggi ad alta voce","Reasoning details":"Dettagli del ragionamento","Reasoning details — interrupted by a server restart":"Dettagli del ragionamento — interrotto da un riavvio del server","Reasoning details — turn limit reached":"Dettagli del ragionamento — limite di turni raggiunto","Recalling memory…":"Recupero della memoria…","Reconnecting…":"Riconnessione…","Reference a conversation":"Fai riferimento a una conversazione","Remove from workspace":"Rimuovi dall’area di lavoro","Rename conversation":"Rinomina la conversazione","Rename workspace":"Rinomina l’area di lavoro","Rendering {progress}%":"Rendering in corso: {progress}%",Report:"Report","Response ready":"Risposta pronta","Reticulating splines":"Reticolazione delle spline",Retry:"Riprova",Save:"Salva","Scroll to bottom":"Vai in fondo","Saving response…":"Salvataggio della risposta…","Search agents...":"Cerca agenti...","Search conversations...":"Cerca conversazioni...","Search prompts...":"Cerca prompt...",Send:"Invia","Send now":"Invia ora","Send when the answer ends":"Invia al termine della risposta","Sending…":"Invio in corso…","Sends when the answer ends:":"Invio al termine della risposta:","Several agents are answering: your message is sent once they are done.":"Più agenti stanno rispondendo: il tuo messaggio verrà inviato quando avranno finito.","Shared with you":"Condivise con te","Show conversations":"Mostra le conversazioni","Show less":"Mostra meno",Sidebar:"Barra laterale",Skip:"Salta","Skip response":"Salta la risposta","Sorry, an error occurred. Please try again.":"Si è verificato un errore. Riprova.","Speak or tap to interrupt":"Parla o tocca per interrompere","Speaking…":"Sta parlando…","Started in {channel}":"Avviata in {channel}","Stop dictation":"Interrompi la dettatura","Stop generating":"Interrompi la generazione","Stop reading":"Interrompi la lettura",Stopped:"Interrotto","Stopping…":"Interruzione in corso…",Suggestions:"Suggerimenti","Summarized conversation":"Conversazione riassunta","Summarizing earlier conversation…":"Riepilogo della parte precedente della conversazione…",Superseded:"Sostituito","Switch to":"Passa a","Switch to another agent":"Passa a un altro agente","Switch view":"Cambia vista","System prompt":"Prompt di sistema","Tap to cancel":"Tocca per annullare","Tell us what went wrong (optional)":"Spiegaci cosa non ha funzionato (facoltativo)","The agent is answering…":"L’agente sta rispondendo…","The agent needs your approval to run a tool:":"L’agente ha bisogno della tua approvazione per eseguire uno strumento:","The agent needs your approval to run these tools:":"L’agente ha bisogno della tua approvazione per eseguire questi strumenti:","The agents you mentioned are asked as soon as the current answer ends.":"Gli agenti che hai menzionato vengono interpellati al termine della risposta in corso.","The conversation could not be deleted":"Impossibile eliminare la conversazione","The conversation could not be moved":"Impossibile spostare la conversazione","The conversations you referenced are read with your message once the current answer ends.":"Le conversazioni che hai citato vengono lette con il tuo messaggio al termine della risposta in corso.","The conversation could not be renamed":"Impossibile rinominare la conversazione","The conversations could not be archived":"Impossibile archiviare le conversazioni","The conversations could not be deleted":"Impossibile eliminare le conversazioni","The render did not finish":"Il rendering non è stato completato","The server restarted while this turn was running, so it stopped before it could finish.":"Il server si è riavviato durante questo turno, che si è quindi interrotto prima di poter terminare.","The workspace could not be created":"Impossibile creare l’area di lavoro","The workspace could not be deleted":"Impossibile eliminare l’area di lavoro","The workspace could not be renamed":"Impossibile rinominare l’area di lavoro","Thinking it through":"Riflessione in corso","Thinking...":"Sto pensando...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Questo agente è pensato per gli incarichi, non per la chat diretta. Potrebbe non rispondere bene in una conversazione.","This conversation could not be loaded.":"Impossibile caricare questa conversazione.","This decision could not be sent. Reload the chat and try again.":"Impossibile inviare questa decisione. Ricarica la chat e riprova.","This message waits for the current response":"Questo messaggio attende la risposta in corso","This message will be read with your next one.":"Questo messaggio verrà letto insieme al prossimo.","This item could not be loaded.":"Impossibile caricare questo elemento.","The response could not be stopped. Try again.":"Impossibile interrompere la risposta. Riprova.","This turn is no longer waiting for a decision.":"Questo turno non è più in attesa di una decisione.","Tool definitions":"Definizioni degli strumenti","Tool results":"Risultati degli strumenti","Transfer chain":"Catena di trasferimento","Transferred from {agent}":"Trasferito da {agent}","Transferring to another agent…":"Trasferimento verso un altro agente…","Transferring to {agent}…":"Trasferimento verso {agent}…","Turn limit reached.":"Limite di turni raggiunto.","Unable to connect. Please check the configuration.":"Impossibile connettersi. Controlla la configurazione.","Unmute microphone":"Riattiva il microfono","Untitled conversation":"Conversazione senza titolo",Usage:"Utilizzo","Upload failed":"Caricamento non riuscito","Usage · {period}":"Utilizzo · {period}","Uses AI. Verify results.":"Usa l’IA. Verifica i risultati.","Using tools…":"Utilizzo degli strumenti…",Video:"Video","Voice call":"Chiamata vocale","Waiting before continuing…":"In attesa prima di continuare…","Waiting for one background task…":"In attesa di un’attività in background…","Waiting for your approval…":"In attesa della tua approvazione…","Waiting for {count} background tasks…":"In attesa di {count} attività in background…","Waiting to render":"In attesa del rendering","What could be improved?":"Cosa si potrebbe migliorare?","Why not? The agent sees this and can adapt (optional)":"Perché no? L’agente lo vede e può adattarsi (facoltativo)","Working files ({count})":"File di lavoro ({count})","Workspace name":"Nome dell’area di lavoro",Workspaces:"Aree di lavoro","Wrapping things up":"Conclusione in corso",Yes:"Sì","Yes, always":"Sì, sempre","Your answer is ready":"La tua risposta è pronta",default:"predefinito","e.g. wrong environment — use staging instead":"ad es. ambiente errato — usa invece l’ambiente di staging","just now":"proprio ora","this month":"questo mese","this year":"quest’anno",today:"oggi","unknown tool":"strumento sconosciuto","{agent} has finished":"{agent} ha terminato","{agent} is answering…":"{agent} sta rispondendo…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"{counts} token","{count} iterations":"{count} iterazioni","{count} scenes":"{count} scene","{count} sections":"{count} sezioni","{count} slides":"{count} diapositive","{count} tool calls":"{count} chiamate a strumenti","{count} transfers":"{count} trasferimenti","{count}d ago":"{count} g fa","{count}h ago":"{count} h fa","{count}m ago":"{count} min fa","{decided}/{total} decided":"{decided}/{total} decisi","{name} was not attached: a file may be at most {size}.":"{name} non è stato allegato: un file può essere al massimo di {size}.","{name} was not attached: a message holds at most {count} files.":"{name} non è stato allegato: un messaggio può contenere al massimo {count} file.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} non è stato allegato: i file di un messaggio possono arrivare al massimo a {size} in totale.","{name} was not attached: this type of file is not accepted.":"{name} non è stato allegato: questo tipo di file non è accettato.","{percent}% full":"Pieno al {percent}%","{quota} (shared across all users)":"{quota} (condivisa tra tutti gli utenti)","{summary} — click for details":"{summary} — fai clic per i dettagli","{tool} (+{count} more)…":"{tool} (+{count} altri)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Il budget di iterazioni dell’agente è esaurito: l’esecuzione si è interrotta prima di completare tutti i passaggi previsti. La risposta finale riassume al meglio il lavoro svolto finora.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"«Sì, sempre» salva una tua preferenza. Quello strumento verrà quindi eseguito senza chiedere, anche nelle esecuzioni pianificate che nessuno sta seguendo, finché non la revochi."},ja:{"(no output)":"(出力なし)","1 tool call":"ツール呼び出し 1 件","1 transfer":"転送 1 件","A file failed to upload: remove it to send the message":"ファイルのアップロードに失敗しました。メッセージを送信するには削除してください","A message references at most {count} conversations":"1 つのメッセージで参照できる会話は最大 {count} 件です","Acting on the page…":"ページを操作中…","Agent · {channel}":"エージェント · {channel}","Agent switching is not available here":"ここではエージェントの切り替えは利用できません","Almost there":"もうすぐ完了します","Also applies to your scheduled runs, until you revoke it":"予定された実行についても、取り消すまでは同様に適用されます","Always allowed":"常に許可","Analyzing results (step {step})…":"結果を分析中 (ステップ {step})…","Analyzing results…":"結果を分析中…","Analyzing the details":"詳細を分析しています",Approved:"承認済み","Archive all conversations":"すべての会話をアーカイブ","Archive all conversations?":"すべての会話をアーカイブしますか?","Ask Assistant":"アシスタントに質問","Ask a question...":"質問する...",Assistant:"アシスタント","Attach files":"ファイルを添付","Attached files":"添付ファイル","Attachments wait for the current response":"添付ファイルは、現在の応答を待機します",Back:"戻る","Bad response":"不適切な回答","Browse agents":"エージェントを閲覧する",Cancel:"キャンセル","Cancel question":"質問をキャンセル","Clear all conversations":"すべての会話を消去",Close:"閉じる","Collecting results from one task…":"1 件のタスクの結果を収集中…","Collecting results from {count} tasks…":"{count} 件のタスクの結果を収集中…","Compacting conversation context…":"会話のコンテキストを圧縮中…","Composing answer…":"回答を作成中…",Confirm:"確認する","Connecting integrations…":"連携を接続中…","Connecting the dots":"情報を関連付けています","Consulting an agent…":"エージェントに問い合わせ中…","Consulting the sources":"情報源を確認しています","Consulting {agent}…":"{agent} に問い合わせ中…","Consulting {agent}: {count} questions…":"{agent} に問い合わせ中: {count} 件の質問…","Consulting {agent}: {tool} (+{count} more)…":"{agent} に問い合わせ中: {tool}(他 {count} 件)…","Consulting {agent}: {tool}…":"{agent} に問い合わせ中: {tool}…","Consulting {agent}: writing the answer…":"{agent} に問い合わせ中: 回答を作成しています…","Consulting {count} agents…":"{count} 件のエージェントに問い合わせ中…","Context full — older turns are being dropped":"コンテキストが満杯 — 古いターンが削除されています","Context nearly full — older turns are being summarized":"コンテキストがほぼ満杯です — 古いターンが要約されています","Context used":"使用されたコンテキスト","Continue now":"今すぐ続行",Conversation:"会話","Conversation history":"会話履歴","Conversation title":"会話のタイトル","Conversation transcript":"会話の履歴",Copied:"コピーしました","Copied!":"コピー完了!","Copy code":"コードをコピー",Conversations:"会話","Copy message":"メッセージをコピー","Copy response":"応答をコピー","Could not load your conversations.":"会話を読み込めませんでした。","Could not reach the assistant service. Check the connection and try again.":"アシスタントサービスに接続できませんでした。接続状態を確認して、もう一度お試しください。","Could not send your decision. Please try again.":"決定内容を送信できませんでした。もう一度お試しください。","Create agent":"エージェントを作成する","Crunching the data":"データを処理しています","Decline this call":"この呼び出しを拒否",Declined:"拒否済み","Delegating one task…":"1 件のタスクを委任中…","Delegating {count} tasks…":"{count} 件のタスクを委任中…","Delete all conversations":"すべての会話を削除","Delete all conversations?":"すべての会話を削除しますか?","Delete conversation":"会話を削除","Delete workspace":"ワークスペースを削除","Delete?":"削除しますか?","Dictate a message":"メッセージを音声入力する","Did not answer":"回答なし",Download:"ダウンロード","Download {format}":"{format} をダウンロード","Drop a conversation here, or start one with {icon}.":"ここに会話をドロップするか、{icon} で新しく開始してください。","Drop files to attach them":"ファイルをドロップして添付","End voice call":"音声通話を終了","Enter to send · Shift+Enter for new line":"Enterキーで送信 · Shift+Enterキーで改行","Enter to send now · Esc to stop":"Enterキーで今すぐ送信 · Escキーで停止","Enter to send when the answer ends · Esc to stop":"Enterキーで回答の終了後に送信 · Escキーで停止","Expand image":"画像を拡大","Failed to get a response. Resuming…":"応答を取得できませんでした。再開しています…","Feedback already submitted":"フィードバックは送信済みです","Files uploading...":"ファイルのアップロード中...",Floating:"フローティング","Full screen":"全画面表示","Good response":"適切な回答","Hide conversations":"会話を非表示にする","Resize the conversation list":"会話リストのサイズを変更","How can I help you, {name}?":"{name} さん、何かお手伝いできることはありますか?","How can {agent} help you, {name}?":"{name} さん、{agent} がお手伝いできることはありますか?","Image could not be loaded":"画像を読み込めませんでした","Image preview":"画像プレビュー","Incorporating your message…":"メッセージを組み込んでいます…",Input:"入力","Insert prompt template":"プロンプトテンプレートを挿入","Interrupted by a server restart.":"サーバーの再起動により中断されました。","Listening...":"聞き取り中...","Load earlier messages":"以前のメッセージを読み込む","Loading earlier messages…":"以前のメッセージを読み込み中…","Loading conversation history…":"会話履歴を読み込み中…","Loading image…":"画像を読み込み中…","MCP & dynamic tools":"MCPと動的ツール","Mention an agent":"エージェントをメンション","Model reasoning":"モデルの推論","Move to workspace":"ワークスペースに移動","Mute microphone":"マイクをミュート",Muted:"ミュート中","New chat":"新しいチャット","New conversation":"新しい会話","New conversation in this workspace":"このワークスペースで新しい会話","New conversation outside a workspace":"ワークスペース外で新しい会話","New conversation — send a message to start it":"新しい会話 — メッセージを送信すると開始されます","New workspace":"新しいワークスペース",No:"いいえ","No agent matches":"該当するエージェントはありません","None of your conversations matches":"一致するご自身の会話はありません","No conversation matches":"一致する会話はありません","No conversations yet":"まだ会話はありません","No prompt matches":"一致するプロンプトはありません","No response was generated. Please try again.":"応答が生成されませんでした。もう一度お試しください。","No response.":"応答なし。","Not recommended for chat":"チャットには非推奨","Not rendered yet":"まだレンダリングされていません",Open:"開く","Open agent page":"エージェントのページを開く","Open conversation":"会話を開く","Open in XTM One":"XTM One で開く","Other workspaces":"その他のワークスペース",Output:"出力","Play Space Invaders":"Space Invaders をプレイ","Play Space Invaders in XTM One":"XTM One で Space Invaders をプレイ","Polishing the answer":"回答を仕上げています",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint(編集可能)","Preparing tools…":"ツールを準備中…","Preparing…":"準備中…",Presentation:"プレゼンテーション","Putting it together":"内容をまとめています",Quota:"クォータ","Quota reached":"クォータに達しました","Read aloud":"読み上げ","Reasoning details":"推論の詳細","Reasoning details — interrupted by a server restart":"推論の詳細 — サーバーの再起動により中断されました","Reasoning details — turn limit reached":"推論の詳細 — ターン制限に達しました","Recalling memory…":"メモリを呼び出し中…","Reconnecting…":"再接続中…","Reference a conversation":"会話を参照","Remove from workspace":"ワークスペースから外す","Rename conversation":"会話の名前を変更","Rename workspace":"ワークスペースの名前を変更","Rendering {progress}%":"レンダリング中 {progress}%",Report:"レポート","Response ready":"応答準備完了","Reticulating splines":"スプラインを網状化しています",Retry:"再試行",Save:"保存","Scroll to bottom":"一番下へスクロール","Saving response…":"応答を保存中…","Search agents...":"エージェントを検索...","Search conversations...":"会話を検索...","Search prompts...":"プロンプトを検索...",Send:"送信","Send now":"今すぐ送信","Send when the answer ends":"回答の終了後に送信","Sending…":"送信中…","Sends when the answer ends:":"回答の終了後に送信:","Several agents are answering: your message is sent once they are done.":"複数のエージェントが回答中です。回答が終わるとメッセージが送信されます。","Shared with you":"他のユーザーから共有","Show conversations":"会話を表示","Show less":"表示を減らす",Sidebar:"サイドバー",Skip:"スキップ","Skip response":"応答をスキップ","Sorry, an error occurred. Please try again.":"申し訳ありません。エラーが発生しました。もう一度お試しください。","Speak or tap to interrupt":"話すかタップして中断","Speaking…":"読み上げ中…","Started in {channel}":"{channel} で開始","Stop dictation":"ディクテーションを停止","Stop generating":"生成を停止","Stop reading":"読み上げを停止",Stopped:"停止","Stopping…":"停止中…",Suggestions:"提案","Summarized conversation":"会話の要約","Summarizing earlier conversation…":"以前の会話を要約中…",Superseded:"置き換え済み","Switch to":"切り替え先","Switch to another agent":"別のエージェントに切り替える","Switch view":"ビューを切り替える","System prompt":"システムプロンプト","Tap to cancel":"タップしてキャンセル","Tell us what went wrong (optional)":"問題があった点をお聞かせください(任意)","The agent is answering…":"エージェントが回答中…","The agent needs your approval to run a tool:":"エージェントがツールを実行するには、あなたの承認が必要です:","The agent needs your approval to run these tools:":"エージェントがこれらのツールを実行するには、あなたの承認が必要です:","The agents you mentioned are asked as soon as the current answer ends.":"メンションしたエージェントには、現在の回答が終わり次第たずねます。","The conversation could not be deleted":"会話を削除できませんでした","The conversation could not be moved":"会話を移動できませんでした","The conversations you referenced are read with your message once the current answer ends.":"参照した会話は、現在の回答が終わり次第メッセージと一緒に読み込まれます。","The conversation could not be renamed":"会話の名前を変更できませんでした","The conversations could not be archived":"会話をアーカイブできませんでした","The conversations could not be deleted":"会話を削除できませんでした","The render did not finish":"レンダリングが完了しませんでした","The server restarted while this turn was running, so it stopped before it could finish.":"このターンの実行中にサーバーが再起動したため、完了する前に停止しました。","The workspace could not be created":"ワークスペースを作成できませんでした","The workspace could not be deleted":"ワークスペースを削除できませんでした","The workspace could not be renamed":"ワークスペースの名前を変更できませんでした","Thinking it through":"じっくり考えています","Thinking...":"考え中...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"このエージェントはチャットではなくタスク向けに設計されています。会話にはうまく応答できない場合があります。","This conversation could not be loaded.":"この会話を読み込めませんでした。","This decision could not be sent. Reload the chat and try again.":"この決定を送信できませんでした。チャットを再読み込みして、もう一度お試しください。","This message waits for the current response":"このメッセージは、現在の応答を待機します","This message will be read with your next one.":"このメッセージは次のメッセージと一緒に読まれます。","This item could not be loaded.":"この項目を読み込めませんでした。","The response could not be stopped. Try again.":"応答を停止できませんでした。もう一度お試しください。","This turn is no longer waiting for a decision.":"このターンでは、決定を待つ必要がなくなりました。","Tool definitions":"ツールの定義","Tool results":"ツールの結果","Transfer chain":"転送チェーン","Transferred from {agent}":"{agent} から転送されました","Transferring to another agent…":"別のエージェントに転送中…","Transferring to {agent}…":"{agent} に転送中…","Turn limit reached.":"ターン制限に達しました。","Unable to connect. Please check the configuration.":"接続できません。設定を確認してください。","Unmute microphone":"マイクのミュートを解除","Untitled conversation":"タイトルのない会話",Usage:"使用状況","Upload failed":"アップロードに失敗しました","Usage · {period}":"使用状況 · {period}","Uses AI. Verify results.":"AIを使用しています。結果を確認してください。","Using tools…":"ツールを使用中…",Video:"動画","Voice call":"音声通話","Waiting before continuing…":"続行する前に待機中…","Waiting for one background task…":"バックグラウンドタスク 1 件を待機中…","Waiting for your approval…":"承認をお待ちしています…","Waiting for {count} background tasks…":"バックグラウンドタスク {count} 件を待機中…","Waiting to render":"レンダリング待ち","What could be improved?":"改善できる点はありますか?","Why not? The agent sees this and can adapt (optional)":"なぜですか? エージェントはこれを確認し、対応を調整できます(任意)","Working files ({count})":"作業ファイル ({count})","Workspace name":"ワークスペース名",Workspaces:"ワークスペース","Wrapping things up":"仕上げをしています",Yes:"はい","Yes, always":"はい、常に","Your answer is ready":"回答の準備が整いました",default:"デフォルト","e.g. wrong environment — use staging instead":"例:環境が間違っている — 代わりにステージング環境を使用してください","just now":"たった今","this month":"今月","this year":"今年",today:"今日","unknown tool":"不明なツール","{agent} has finished":"{agent} が完了しました","{agent} is answering…":"{agent} が回答中…","{agent}: {status}":"{agent}:{status}","{counts} tokens":"{counts} トークン","{count} iterations":"{count} 回の反復","{count} scenes":"{count} シーン","{count} sections":"{count} セクション","{count} slides":"{count} スライド","{count} tool calls":"ツール呼び出し {count} 件","{count} transfers":"転送 {count} 件","{count}d ago":"{count} 日前","{count}h ago":"{count} 時間前","{count}m ago":"{count} 分前","{decided}/{total} decided":"{decided}/{total} 件が決定済み","{name} was not attached: a file may be at most {size}.":"{name} は添付されませんでした: 1 つのファイルの上限は {size} です。","{name} was not attached: a message holds at most {count} files.":"{name} は添付されませんでした: 1 つのメッセージに添付できるファイルは最大 {count} 件です。","{name} was not attached: the files of a message may add up to at most {size}.":"{name} は添付されませんでした: 1 つのメッセージのファイルの合計は最大 {size} です。","{name} was not attached: this type of file is not accepted.":"{name} は添付されませんでした: この種類のファイルは使用できません。","{percent}% full":"{percent} % 使用中","{quota} (shared across all users)":"{quota}(全ユーザーで共有)","{summary} — click for details":"{summary} — クリックで詳細を表示","{tool} (+{count} more)…":"{tool}(他 {count} 件)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"エージェントの反復回数の上限に達したため、予定されたすべてのステップを完了する前に実行が停止しました。最終的な回答は、これまでに行った作業をできる限りまとめたものです。","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"「はい、常に」を選ぶと、あなたの設定として保存されます。以後、そのツールは確認なしで実行されます(誰も見ていない定期実行を含む)。取り消すまでこの設定は有効です。"},ko:{"(no output)":"(출력 없음)","1 tool call":"도구 호출 1회","1 transfer":"전환 1회","A file failed to upload: remove it to send the message":"파일을 업로드하지 못했습니다. 메시지를 보내려면 해당 파일을 제거하세요","A message references at most {count} conversations":"메시지 하나에서 참조할 수 있는 대화는 최대 {count}개입니다","Acting on the page…":"페이지에서 작업 중…","Agent · {channel}":"에이전트 · {channel}","Agent switching is not available here":"여기서는 에이전트를 전환할 수 없습니다","Almost there":"거의 다 되었습니다","Also applies to your scheduled runs, until you revoke it":"취소할 때까지 예약된 실행에도 적용됩니다","Always allowed":"항상 허용됨","Analyzing results (step {step})…":"결과 분석 중 (단계 {step})…","Analyzing results…":"결과 분석 중…","Analyzing the details":"세부 정보를 분석하는 중",Approved:"승인됨","Archive all conversations":"모든 대화 보관","Archive all conversations?":"모든 대화를 보관하시겠습니까?","Ask Assistant":"어시스턴트에게 질문","Ask a question...":"질문하기...",Assistant:"어시스턴트","Attach files":"파일 첨부","Attached files":"첨부 파일","Attachments wait for the current response":"첨부 파일은 현재 응답이 끝날 때까지 대기합니다",Back:"뒤로","Bad response":"좋지 않은 응답","Browse agents":"에이전트 둘러보기",Cancel:"취소","Cancel question":"질문 취소","Clear all conversations":"모든 대화 지우기",Close:"닫기","Collecting results from one task…":"작업 1개의 결과 수집 중…","Collecting results from {count} tasks…":"작업 {count}개의 결과 수집 중…","Compacting conversation context…":"대화 컨텍스트 압축 중…","Composing answer…":"답변 작성 중…",Confirm:"확인","Connecting integrations…":"통합 연결 중…","Connecting the dots":"단서를 연결하는 중","Consulting an agent…":"에이전트에게 문의 중…","Consulting the sources":"출처를 확인하는 중","Consulting {agent}…":"{agent}에게 문의 중…","Consulting {agent}: {count} questions…":"{agent}에게 문의 중: 질문 {count}개…","Consulting {agent}: {tool} (+{count} more)…":"{agent}에게 문의 중: {tool} (외 {count}개)…","Consulting {agent}: {tool}…":"{agent}에게 문의 중: {tool}…","Consulting {agent}: writing the answer…":"{agent}에게 문의 중: 답변 작성 중…","Consulting {count} agents…":"에이전트 {count}개에 문의 중…","Context full — older turns are being dropped":"컨텍스트 가득 참 — 이전 턴을 삭제하는 중","Context nearly full — older turns are being summarized":"컨텍스트 거의 가득 참 — 이전 턴을 요약하는 중","Context used":"사용된 컨텍스트","Continue now":"지금 계속",Conversation:"대화","Conversation history":"대화 기록","Conversation title":"대화 제목","Conversation transcript":"대화 내용",Copied:"복사됨","Copied!":"복사되었습니다!","Copy code":"코드 복사",Conversations:"대화","Copy message":"메시지 복사","Copy response":"응답 복사","Could not load your conversations.":"대화를 불러올 수 없습니다.","Could not reach the assistant service. Check the connection and try again.":"어시스턴트 서비스에 연결할 수 없습니다. 연결을 확인하고 다시 시도하세요.","Could not send your decision. Please try again.":"결정을 보내지 못했습니다. 다시 시도하세요.","Create agent":"에이전트 만들기","Crunching the data":"데이터를 처리하는 중","Decline this call":"이 호출 거부",Declined:"거부됨","Delegating one task…":"작업 1개 위임 중…","Delegating {count} tasks…":"작업 {count}개 위임 중…","Delete all conversations":"모든 대화 삭제","Delete all conversations?":"모든 대화를 삭제하시겠습니까?","Delete conversation":"대화 삭제","Delete workspace":"작업 공간 삭제","Delete?":"삭제하시겠습니까?","Dictate a message":"메시지 받아쓰기","Did not answer":"응답하지 않음",Download:"다운로드","Download {format}":"{format} 다운로드","Drop a conversation here, or start one with {icon}.":"여기에 대화를 끌어다 놓거나 {icon}(으)로 새 대화를 시작하세요.","Drop files to attach them":"파일을 끌어다 놓아 첨부하세요","End voice call":"음성 통화 종료","Enter to send · Shift+Enter for new line":"Enter 키로 보내기 · Shift+Enter 키로 줄 바꿈","Enter to send now · Esc to stop":"Enter 키로 지금 보내기 · Esc 키로 중지","Enter to send when the answer ends · Esc to stop":"Enter 키로 답변이 끝나면 보내기 · Esc 키로 중지","Expand image":"이미지 확대","Failed to get a response. Resuming…":"응답을 받지 못했습니다. 다시 시작하는 중…","Feedback already submitted":"피드백을 이미 제출했습니다","Files uploading...":"파일 업로드 중...",Floating:"플로팅","Full screen":"전체 화면","Good response":"좋은 응답","Hide conversations":"대화 숨기기","Resize the conversation list":"대화 목록 크기 조정","How can I help you, {name}?":"{name}님, 무엇을 도와드릴까요?","How can {agent} help you, {name}?":"{name}님, {agent}이(가) 무엇을 도와드릴까요?","Image could not be loaded":"이미지를 불러올 수 없습니다","Image preview":"이미지 미리 보기","Incorporating your message…":"메시지를 반영하는 중…",Input:"입력","Insert prompt template":"프롬프트 템플릿 삽입","Interrupted by a server restart.":"서버 재시작으로 중단되었습니다.","Listening...":"듣는 중...","Load earlier messages":"이전 메시지 불러오기","Loading earlier messages…":"이전 메시지 불러오는 중…","Loading conversation history…":"대화 기록 불러오는 중…","Loading image…":"이미지 불러오는 중…","MCP & dynamic tools":"MCP 및 동적 도구","Mention an agent":"에이전트 언급","Model reasoning":"모델 추론","Move to workspace":"작업 공간으로 이동","Mute microphone":"마이크 음소거",Muted:"음소거됨","New chat":"새 채팅","New conversation":"새 대화","New conversation in this workspace":"이 작업 공간에서 새 대화","New conversation outside a workspace":"작업 공간 밖에서 새 대화","New conversation — send a message to start it":"새 대화 — 메시지를 보내 대화를 시작하세요","New workspace":"새 작업 공간",No:"아니요","No agent matches":"일치하는 에이전트가 없습니다","None of your conversations matches":"일치하는 내 대화가 없습니다","No conversation matches":"일치하는 대화가 없습니다","No conversations yet":"아직 대화가 없습니다","No prompt matches":"일치하는 프롬프트가 없습니다","No response was generated. Please try again.":"응답이 생성되지 않았습니다. 다시 시도하세요.","No response.":"응답 없음.","Not recommended for chat":"채팅에는 권장되지 않음","Not rendered yet":"아직 렌더링되지 않음",Open:"열기","Open agent page":"에이전트 페이지 열기","Open conversation":"대화 열기","Open in XTM One":"XTM One에서 열기","Other workspaces":"다른 작업 공간",Output:"출력","Play Space Invaders":"Space Invaders 플레이","Play Space Invaders in XTM One":"XTM One에서 Space Invaders 플레이","Polishing the answer":"답변을 다듬는 중",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (편집 가능)","Preparing tools…":"도구 준비 중…","Preparing…":"준비 중…",Presentation:"프레젠테이션","Putting it together":"내용을 정리하는 중",Quota:"할당량","Quota reached":"할당량 도달","Read aloud":"소리 내어 읽기","Reasoning details":"추론 세부 정보","Reasoning details — interrupted by a server restart":"추론 세부 정보 — 서버 재시작으로 중단됨","Reasoning details — turn limit reached":"추론 세부 정보 — 턴 한도 도달","Recalling memory…":"메모리 불러오는 중…","Reconnecting…":"다시 연결하는 중…","Reference a conversation":"대화 참조","Remove from workspace":"작업 공간에서 제거","Rename conversation":"대화 이름 바꾸기","Rename workspace":"작업 공간 이름 바꾸기","Rendering {progress}%":"렌더링 중 {progress}%",Report:"보고서","Response ready":"응답 준비됨","Reticulating splines":"스플라인을 망상화하는 중",Retry:"다시 시도",Save:"저장","Scroll to bottom":"맨 아래로 스크롤","Saving response…":"응답 저장 중…","Search agents...":"에이전트 검색...","Search conversations...":"대화 검색...","Search prompts...":"프롬프트 검색...",Send:"보내기","Send now":"지금 보내기","Send when the answer ends":"답변이 끝나면 보내기","Sending…":"보내는 중…","Sends when the answer ends:":"답변이 끝나면 보냄:","Several agents are answering: your message is sent once they are done.":"여러 에이전트가 답변 중입니다. 답변이 끝나면 메시지를 보냅니다.","Shared with you":"나와 공유됨","Show conversations":"대화 표시","Show less":"간단히 보기",Sidebar:"사이드바",Skip:"건너뛰기","Skip response":"응답 건너뛰기","Sorry, an error occurred. Please try again.":"죄송합니다. 오류가 발생했습니다. 다시 시도하세요.","Speak or tap to interrupt":"말하거나 탭하여 중단하세요","Speaking…":"말하는 중…","Started in {channel}":"{channel}에서 시작됨","Stop dictation":"받아쓰기 중지","Stop generating":"생성 중지","Stop reading":"읽기 중지",Stopped:"중지됨","Stopping…":"중지하는 중…",Suggestions:"추천","Summarized conversation":"요약된 대화","Summarizing earlier conversation…":"이전 대화 요약 중…",Superseded:"대체됨","Switch to":"전환 대상","Switch to another agent":"다른 에이전트로 전환","Switch view":"보기 전환","System prompt":"시스템 프롬프트","Tap to cancel":"탭하여 취소","Tell us what went wrong (optional)":"무엇이 잘못되었는지 알려 주세요 (선택 사항)","The agent is answering…":"에이전트 답변 중…","The agent needs your approval to run a tool:":"에이전트가 도구를 실행하려면 승인이 필요합니다:","The agent needs your approval to run these tools:":"에이전트가 다음 도구를 실행하려면 승인이 필요합니다:","The agents you mentioned are asked as soon as the current answer ends.":"언급한 에이전트에게는 현재 답변이 끝나는 즉시 요청합니다.","The conversation could not be deleted":"대화를 삭제할 수 없습니다","The conversation could not be moved":"대화를 이동할 수 없습니다","The conversations you referenced are read with your message once the current answer ends.":"참조한 대화는 현재 답변이 끝나는 즉시 메시지와 함께 읽힙니다.","The conversation could not be renamed":"대화 이름을 바꿀 수 없습니다","The conversations could not be archived":"대화를 보관할 수 없습니다","The conversations could not be deleted":"대화를 삭제할 수 없습니다","The render did not finish":"렌더링이 완료되지 않았습니다","The server restarted while this turn was running, so it stopped before it could finish.":"이 턴이 실행되는 동안 서버가 다시 시작되어 완료되기 전에 중지되었습니다.","The workspace could not be created":"작업 공간을 만들 수 없습니다","The workspace could not be deleted":"작업 공간을 삭제할 수 없습니다","The workspace could not be renamed":"작업 공간 이름을 바꿀 수 없습니다","Thinking it through":"깊이 생각하는 중","Thinking...":"생각하는 중...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"이 에이전트는 직접 채팅이 아닌 작업용으로 설계되었습니다. 대화에는 잘 응답하지 못할 수 있습니다.","This conversation could not be loaded.":"이 대화를 불러올 수 없습니다.","This decision could not be sent. Reload the chat and try again.":"이 결정을 보낼 수 없습니다. 채팅을 새로 고친 후 다시 시도하세요.","This message waits for the current response":"이 메시지는 현재 응답이 끝날 때까지 대기합니다","This message will be read with your next one.":"이 메시지는 다음 메시지와 함께 읽힙니다.","This item could not be loaded.":"이 항목을 불러올 수 없습니다.","The response could not be stopped. Try again.":"응답을 중지할 수 없습니다. 다시 시도하세요.","This turn is no longer waiting for a decision.":"이 턴은 더 이상 결정을 기다리지 않습니다.","Tool definitions":"도구 정의","Tool results":"도구 결과","Transfer chain":"전환 체인","Transferred from {agent}":"{agent}에서 전환됨","Transferring to another agent…":"다른 에이전트로 전환 중…","Transferring to {agent}…":"{agent}(으)로 전환 중…","Turn limit reached.":"턴 한도에 도달했습니다.","Unable to connect. Please check the configuration.":"연결할 수 없습니다. 구성을 확인하세요.","Unmute microphone":"마이크 음소거 해제","Untitled conversation":"제목 없는 대화",Usage:"사용량","Upload failed":"업로드 실패","Usage · {period}":"사용량 · {period}","Uses AI. Verify results.":"AI를 사용합니다. 결과를 확인하세요.","Using tools…":"도구 사용 중…",Video:"동영상","Voice call":"음성 통화","Waiting before continuing…":"계속하기 전에 대기 중…","Waiting for one background task…":"백그라운드 작업 1개를 기다리는 중…","Waiting for your approval…":"승인을 기다리는 중…","Waiting for {count} background tasks…":"백그라운드 작업 {count}개를 기다리는 중…","Waiting to render":"렌더링 대기 중","What could be improved?":"어떤 점을 개선할 수 있을까요?","Why not? The agent sees this and can adapt (optional)":"거부하는 이유는 무엇인가요? 에이전트가 이를 보고 대응할 수 있습니다 (선택 사항)","Working files ({count})":"작업 파일 ({count})","Workspace name":"작업 공간 이름",Workspaces:"작업 공간","Wrapping things up":"마무리하는 중",Yes:"예","Yes, always":"예, 항상","Your answer is ready":"답변이 준비되었습니다",default:"기본값","e.g. wrong environment — use staging instead":"예: 잘못된 환경 — 대신 스테이징 환경을 사용하세요","just now":"방금","this month":"이번 달","this year":"올해",today:"오늘","unknown tool":"알 수 없는 도구","{agent} has finished":"{agent} 완료","{agent} is answering…":"{agent} 답변 중…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"{counts} 토큰","{count} iterations":"반복 {count}회","{count} scenes":"장면 {count}개","{count} sections":"섹션 {count}개","{count} slides":"슬라이드 {count}개","{count} tool calls":"도구 호출 {count}회","{count} transfers":"전환 {count}회","{count}d ago":"{count}일 전","{count}h ago":"{count}시간 전","{count}m ago":"{count}분 전","{decided}/{total} decided":"{decided}/{total} 결정됨","{name} was not attached: a file may be at most {size}.":"{name}을(를) 첨부하지 않았습니다. 파일 크기는 최대 {size}입니다.","{name} was not attached: a message holds at most {count} files.":"{name}을(를) 첨부하지 않았습니다. 메시지에는 파일을 최대 {count}개까지 첨부할 수 있습니다.","{name} was not attached: the files of a message may add up to at most {size}.":"{name}을(를) 첨부하지 않았습니다. 메시지에 첨부하는 파일의 총 크기는 최대 {size}입니다.","{name} was not attached: this type of file is not accepted.":"{name}을(를) 첨부하지 않았습니다. 허용되지 않는 파일 형식입니다.","{percent}% full":"{percent}% 사용","{quota} (shared across all users)":"{quota} (모든 사용자가 공유)","{summary} — click for details":"{summary} — 클릭하여 자세히 보기","{tool} (+{count} more)…":"{tool} (외 {count}개)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"에이전트의 반복 한도를 모두 사용했습니다. 계획된 모든 단계를 완료하기 전에 실행이 중지되었습니다. 최종 응답은 지금까지 수행한 작업을 최대한 요약한 것입니다.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"“예, 항상”을 선택하면 내 기본 설정으로 저장됩니다. 이후 해당 도구는 취소할 때까지 확인 없이 실행되며, 아무도 지켜보지 않는 예약 실행에서도 마찬가지입니다."},ru:{"(no output)":"(нет вывода)","1 tool call":"1 вызов инструмента","1 transfer":"1 передача","A file failed to upload: remove it to send the message":"Не удалось загрузить файл: удалите его, чтобы отправить сообщение","A message references at most {count} conversations":"Сообщение может ссылаться не более чем на {count} диалогов","Acting on the page…":"Действие на странице…","Agent · {channel}":"Агент · {channel}","Agent switching is not available here":"Смена агента здесь недоступна","Almost there":"Почти готово","Also applies to your scheduled runs, until you revoke it":"Действует и для ваших запланированных запусков, пока вы его не отзовёте","Always allowed":"Всегда разрешено","Analyzing results (step {step})…":"Анализ результатов (шаг {step})…","Analyzing results…":"Анализ результатов…","Analyzing the details":"Анализ подробностей",Approved:"Одобрено","Archive all conversations":"Архивировать все диалоги","Archive all conversations?":"Архивировать все диалоги?","Ask Assistant":"Спросить ассистента","Ask a question...":"Задайте вопрос...",Assistant:"Ассистент","Attach files":"Прикрепить файлы","Attached files":"Прикреплённые файлы","Attachments wait for the current response":"Вложения ждут завершения текущего ответа",Back:"Назад","Bad response":"Плохой ответ","Browse agents":"Обзор агентов",Cancel:"Отмена","Cancel question":"Отменить вопрос","Clear all conversations":"Очистить все диалоги",Close:"Закрыть","Collecting results from one task…":"Сбор результатов одной задачи…","Collecting results from {count} tasks…":"Сбор результатов задач ({count})…","Compacting conversation context…":"Сжатие контекста диалога…","Composing answer…":"Составление ответа…",Confirm:"Подтвердить","Connecting integrations…":"Подключение интеграций…","Connecting the dots":"Сопоставление фактов","Consulting an agent…":"Консультация с агентом…","Consulting the sources":"Изучение источников","Consulting {agent}…":"Консультация с агентом {agent}…","Consulting {agent}: {count} questions…":"Консультация с агентом {agent}: вопросов — {count}…","Consulting {agent}: {tool} (+{count} more)…":"Консультация с агентом {agent}: {tool} (+{count} ещё)…","Consulting {agent}: {tool}…":"Консультация с агентом {agent}: {tool}…","Consulting {agent}: writing the answer…":"Консультация с агентом {agent}: составление ответа…","Consulting {count} agents…":"Консультация с агентами ({count})…","Context full — older turns are being dropped":"Контекст заполнен — старые ходы удаляются","Context nearly full — older turns are being summarized":"Контекст почти заполнен — старые ходы сводятся в краткое изложение","Context used":"Использовано контекста","Continue now":"Продолжить сейчас",Conversation:"Диалог","Conversation history":"История диалогов","Conversation title":"Название диалога","Conversation transcript":"Расшифровка диалога",Copied:"Скопировано","Copied!":"Скопировано!","Copy code":"Копировать код",Conversations:"Диалоги","Copy message":"Копировать сообщение","Copy response":"Копировать ответ","Could not load your conversations.":"Не удалось загрузить ваши диалоги.","Could not reach the assistant service. Check the connection and try again.":"Не удалось связаться со службой ассистента. Проверьте подключение и повторите попытку.","Could not send your decision. Please try again.":"Не удалось отправить ваше решение. Повторите попытку.","Create agent":"Создать агента","Crunching the data":"Обработка данных","Decline this call":"Отклонить этот вызов",Declined:"Отклонено","Delegating one task…":"Делегирование одной задачи…","Delegating {count} tasks…":"Делегирование задач ({count})…","Delete all conversations":"Удалить все диалоги","Delete all conversations?":"Удалить все диалоги?","Delete conversation":"Удалить диалог","Delete workspace":"Удалить рабочее пространство","Delete?":"Удалить?","Dictate a message":"Продиктовать сообщение","Did not answer":"Нет ответа",Download:"Скачать","Download {format}":"Скачать в формате {format}","Drop a conversation here, or start one with {icon}.":"Перетащите сюда диалог или начните новый с помощью {icon}.","Drop files to attach them":"Перетащите файлы, чтобы прикрепить их","End voice call":"Завершить голосовой вызов","Enter to send · Shift+Enter for new line":"Enter — отправить · Shift+Enter — новая строка","Enter to send now · Esc to stop":"Enter — отправить сейчас · Esc — остановить","Enter to send when the answer ends · Esc to stop":"Enter — отправить после ответа · Esc — остановить","Expand image":"Развернуть изображение","Failed to get a response. Resuming…":"Не удалось получить ответ. Возобновление…","Feedback already submitted":"Отзыв уже отправлен","Files uploading...":"Загрузка файлов...",Floating:"Плавающее окно","Full screen":"Во весь экран","Good response":"Хороший ответ","Hide conversations":"Скрыть диалоги","Resize the conversation list":"Изменить ширину списка диалогов","How can I help you, {name}?":"Чем я могу помочь, {name}?","How can {agent} help you, {name}?":"Чем {agent} может помочь, {name}?","Image could not be loaded":"Не удалось загрузить изображение","Image preview":"Предпросмотр изображения","Incorporating your message…":"Учёт вашего сообщения…",Input:"Ввод","Insert prompt template":"Вставить шаблон промпта","Interrupted by a server restart.":"Прервано перезапуском сервера.","Listening...":"Слушаю...","Load earlier messages":"Загрузить предыдущие сообщения","Loading earlier messages…":"Загрузка предыдущих сообщений…","Loading conversation history…":"Загрузка истории диалога…","Loading image…":"Загрузка изображения…","MCP & dynamic tools":"MCP и динамические инструменты","Mention an agent":"Упомянуть агента","Model reasoning":"Рассуждения модели","Move to workspace":"Переместить в рабочее пространство","Mute microphone":"Выключить микрофон",Muted:"Микрофон выключен","New chat":"Новый чат","New conversation":"Новый диалог","New conversation in this workspace":"Новый диалог в этом рабочем пространстве","New conversation outside a workspace":"Новый диалог вне рабочего пространства","New conversation — send a message to start it":"Новый диалог — отправьте сообщение, чтобы начать его","New workspace":"Новое рабочее пространство",No:"Нет","No agent matches":"Подходящих агентов нет","None of your conversations matches":"Ни один из ваших диалогов не подходит","No conversation matches":"Подходящих диалогов нет","No conversations yet":"Диалогов пока нет","No prompt matches":"Подходящих промптов нет","No response was generated. Please try again.":"Ответ не был сформирован. Повторите попытку.","No response.":"Нет ответа.","Not recommended for chat":"Не рекомендуется для чата","Not rendered yet":"Ещё не отрисовано",Open:"Открыть","Open agent page":"Открыть страницу агента","Open conversation":"Открыть диалог","Open in XTM One":"Открыть в XTM One","Other workspaces":"Другие рабочие пространства",Output:"Вывод","Play Space Invaders":"Играть в Space Invaders","Play Space Invaders in XTM One":"Играть в Space Invaders в XTM One","Polishing the answer":"Доработка ответа",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint (редактируемый)","Preparing tools…":"Подготовка инструментов…","Preparing…":"Подготовка…",Presentation:"Презентация","Putting it together":"Сведение воедино",Quota:"Квота","Quota reached":"Квота исчерпана","Read aloud":"Прочитать вслух","Reasoning details":"Подробности рассуждений","Reasoning details — interrupted by a server restart":"Подробности рассуждений — прервано перезапуском сервера","Reasoning details — turn limit reached":"Подробности рассуждений — достигнут предел ходов","Recalling memory…":"Обращение к памяти…","Reconnecting…":"Повторное подключение…","Reference a conversation":"Сослаться на диалог","Remove from workspace":"Убрать из рабочего пространства","Rename conversation":"Переименовать диалог","Rename workspace":"Переименовать рабочее пространство","Rendering {progress}%":"Отрисовка: {progress} %",Report:"Отчёт","Response ready":"Ответ готов","Reticulating splines":"Ретикуляция сплайнов",Retry:"Повторить",Save:"Сохранить","Scroll to bottom":"Прокрутить вниз","Saving response…":"Сохранение ответа…","Search agents...":"Поиск агентов...","Search conversations...":"Поиск диалогов...","Search prompts...":"Поиск промптов...",Send:"Отправить","Send now":"Отправить сейчас","Send when the answer ends":"Отправить после ответа","Sending…":"Отправка…","Sends when the answer ends:":"Будет отправлено после ответа:","Several agents are answering: your message is sent once they are done.":"Отвечают несколько агентов: ваше сообщение будет отправлено, когда они закончат.","Shared with you":"Доступные вам","Show conversations":"Показать диалоги","Show less":"Свернуть",Sidebar:"Боковая панель",Skip:"Пропустить","Skip response":"Пропустить ответ","Sorry, an error occurred. Please try again.":"Произошла ошибка. Повторите попытку.","Speak or tap to interrupt":"Говорите или коснитесь, чтобы прервать","Speaking…":"Говорит…","Started in {channel}":"Начат в {channel}","Stop dictation":"Остановить диктовку","Stop generating":"Остановить генерацию","Stop reading":"Остановить чтение",Stopped:"Остановлено","Stopping…":"Остановка…",Suggestions:"Предложения","Summarized conversation":"Краткое изложение диалога","Summarizing earlier conversation…":"Краткое изложение начала диалога…",Superseded:"Заменён","Switch to":"Переключиться на","Switch to another agent":"Переключиться на другого агента","Switch view":"Сменить вид","System prompt":"Системный промпт","Tap to cancel":"Коснитесь, чтобы отменить","Tell us what went wrong (optional)":"Расскажите, что пошло не так (необязательно)","The agent is answering…":"Агент отвечает…","The agent needs your approval to run a tool:":"Агенту нужно ваше одобрение, чтобы запустить инструмент:","The agent needs your approval to run these tools:":"Агенту нужно ваше одобрение, чтобы запустить эти инструменты:","The agents you mentioned are asked as soon as the current answer ends.":"Упомянутым агентам вопрос будет задан сразу после окончания текущего ответа.","The conversation could not be deleted":"Не удалось удалить диалог","The conversation could not be moved":"Не удалось переместить диалог","The conversations you referenced are read with your message once the current answer ends.":"Указанные диалоги будут прочитаны вместе с вашим сообщением сразу после окончания текущего ответа.","The conversation could not be renamed":"Не удалось переименовать диалог","The conversations could not be archived":"Не удалось архивировать диалоги","The conversations could not be deleted":"Не удалось удалить диалоги","The render did not finish":"Отрисовка не завершилась","The server restarted while this turn was running, so it stopped before it could finish.":"Сервер был перезапущен во время этого хода, поэтому ход остановился, не успев завершиться.","The workspace could not be created":"Не удалось создать рабочее пространство","The workspace could not be deleted":"Не удалось удалить рабочее пространство","The workspace could not be renamed":"Не удалось переименовать рабочее пространство","Thinking it through":"Обдумывание","Thinking...":"Думаю...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"Этот агент создан для заданий, а не для прямого чата. В диалоге он может отвечать плохо.","This conversation could not be loaded.":"Не удалось загрузить этот диалог.","This decision could not be sent. Reload the chat and try again.":"Не удалось отправить это решение. Перезагрузите чат и повторите попытку.","This message waits for the current response":"Это сообщение ждёт завершения текущего ответа","This message will be read with your next one.":"Это сообщение будет прочитано вместе со следующим.","This item could not be loaded.":"Не удалось загрузить этот элемент.","The response could not be stopped. Try again.":"Не удалось остановить ответ. Повторите попытку.","This turn is no longer waiting for a decision.":"Этот ход больше не ждёт решения.","Tool definitions":"Определения инструментов","Tool results":"Результаты инструментов","Transfer chain":"Цепочка передач","Transferred from {agent}":"Передано от агента {agent}","Transferring to another agent…":"Передача другому агенту…","Transferring to {agent}…":"Передача агенту {agent}…","Turn limit reached.":"Достигнут предел ходов.","Unable to connect. Please check the configuration.":"Не удалось подключиться. Проверьте конфигурацию.","Unmute microphone":"Включить микрофон","Untitled conversation":"Диалог без названия",Usage:"Использование","Upload failed":"Ошибка загрузки","Usage · {period}":"Использование · {period}","Uses AI. Verify results.":"Использует ИИ. Проверяйте результаты.","Using tools…":"Использование инструментов…",Video:"Видео","Voice call":"Голосовой вызов","Waiting before continuing…":"Ожидание перед продолжением…","Waiting for one background task…":"Ожидание одной фоновой задачи…","Waiting for your approval…":"Ожидание вашего одобрения…","Waiting for {count} background tasks…":"Ожидание фоновых задач ({count})…","Waiting to render":"Ожидание отрисовки","What could be improved?":"Что можно улучшить?","Why not? The agent sees this and can adapt (optional)":"Почему нет? Агент увидит это и сможет учесть (необязательно)","Working files ({count})":"Рабочие файлы ({count})","Workspace name":"Название рабочего пространства",Workspaces:"Рабочие пространства","Wrapping things up":"Завершение",Yes:"Да","Yes, always":"Да, всегда","Your answer is ready":"Ваш ответ готов",default:"по умолчанию","e.g. wrong environment — use staging instead":"например: не та среда — используйте вместо неё тестовую (staging)","just now":"только что","this month":"в этом месяце","this year":"в этом году",today:"сегодня","unknown tool":"неизвестный инструмент","{agent} has finished":"{agent}: готово","{agent} is answering…":"{agent} отвечает…","{agent}: {status}":"{agent}: {status}","{counts} tokens":"Токены: {counts}","{count} iterations":"Итераций: {count}","{count} scenes":"Сцен: {count}","{count} sections":"Разделов: {count}","{count} slides":"Слайдов: {count}","{count} tool calls":"Вызовов инструментов: {count}","{count} transfers":"Передач: {count}","{count}d ago":"{count} дн. назад","{count}h ago":"{count} ч назад","{count}m ago":"{count} мин назад","{decided}/{total} decided":"Решено: {decided}/{total}","{name} was not attached: a file may be at most {size}.":"{name} не прикреплён: размер файла не может превышать {size}.","{name} was not attached: a message holds at most {count} files.":"{name} не прикреплён: к сообщению можно прикрепить не более {count} файлов.","{name} was not attached: the files of a message may add up to at most {size}.":"{name} не прикреплён: общий размер файлов сообщения не может превышать {size}.","{name} was not attached: this type of file is not accepted.":"{name} не прикреплён: файлы этого типа не принимаются.","{percent}% full":"Заполнено на {percent} %","{quota} (shared across all users)":"{quota} (общая для всех пользователей)","{summary} — click for details":"{summary} — нажмите, чтобы узнать подробности","{tool} (+{count} more)…":"{tool} (+{count} ещё)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"Бюджет итераций агента исчерпан: выполнение остановлено до завершения всех запланированных шагов. Итоговый ответ — максимально полная сводка проделанной на данный момент работы.","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"«Да, всегда» сохраняет ваш выбор. После этого инструмент будет запускаться без запроса — в том числе в запланированных запусках, за которыми никто не следит, — пока вы не отзовёте разрешение."},zh:{"(no output)":"(无输出)","1 tool call":"1 次工具调用","1 transfer":"1 次转交","A file failed to upload: remove it to send the message":"有文件上传失败:请将其移除后再发送消息","A message references at most {count} conversations":"一条消息最多可引用 {count} 个对话","Acting on the page…":"正在页面上执行操作…","Agent · {channel}":"智能体 · {channel}","Agent switching is not available here":"此处无法切换智能体","Almost there":"马上就好","Also applies to your scheduled runs, until you revoke it":"在您撤销之前,也适用于您的计划运行","Always allowed":"始终允许","Analyzing results (step {step})…":"正在分析结果(第 {step} 步)…","Analyzing results…":"正在分析结果…","Analyzing the details":"正在分析细节",Approved:"已批准","Archive all conversations":"归档所有对话","Archive all conversations?":"要归档所有对话吗?","Ask Assistant":"询问助手","Ask a question...":"提出问题...",Assistant:"助手","Attach files":"附加文件","Attached files":"已附加的文件","Attachments wait for the current response":"附件将等待当前回复完成",Back:"返回","Bad response":"回复不佳","Browse agents":"浏览智能体",Cancel:"取消","Cancel question":"取消问题","Clear all conversations":"清除所有对话",Close:"关闭","Collecting results from one task…":"正在收集 1 个任务的结果…","Collecting results from {count} tasks…":"正在收集 {count} 个任务的结果…","Compacting conversation context…":"正在压缩对话上下文…","Composing answer…":"正在撰写回答…",Confirm:"确认","Connecting integrations…":"正在连接集成…","Connecting the dots":"正在串联线索","Consulting an agent…":"正在咨询智能体…","Consulting the sources":"正在查阅来源","Consulting {agent}…":"正在咨询 {agent}…","Consulting {agent}: {count} questions…":"正在咨询 {agent}:{count} 个问题…","Consulting {agent}: {tool} (+{count} more)…":"正在咨询 {agent}:{tool}(另有 {count} 个)…","Consulting {agent}: {tool}…":"正在咨询 {agent}:{tool}…","Consulting {agent}: writing the answer…":"正在咨询 {agent}:正在撰写回答…","Consulting {count} agents…":"正在咨询 {count} 个智能体…","Context full — older turns are being dropped":"上下文已满 — 正在丢弃较早的轮次","Context nearly full — older turns are being summarized":"上下文即将用满 — 正在总结较早的轮次","Context used":"已用上下文","Continue now":"立即继续",Conversation:"对话","Conversation history":"对话历史","Conversation title":"对话标题","Conversation transcript":"对话记录",Copied:"已复制","Copied!":"已复制!","Copy code":"复制代码",Conversations:"对话","Copy message":"复制消息","Copy response":"复制回复","Could not load your conversations.":"无法加载您的对话。","Could not reach the assistant service. Check the connection and try again.":"无法连接到助手服务。请检查连接后重试。","Could not send your decision. Please try again.":"无法发送您的决定。请重试。","Create agent":"创建智能体","Crunching the data":"正在处理数据","Decline this call":"拒绝此调用",Declined:"已拒绝","Delegating one task…":"正在委派 1 个任务…","Delegating {count} tasks…":"正在委派 {count} 个任务…","Delete all conversations":"删除所有对话","Delete all conversations?":"要删除所有对话吗?","Delete conversation":"删除对话","Delete workspace":"删除工作区","Delete?":"要删除吗?","Dictate a message":"语音输入消息","Did not answer":"未回答",Download:"下载","Download {format}":"下载 {format}","Drop a conversation here, or start one with {icon}.":"将对话拖放到此处,或使用 {icon} 开始新对话。","Drop files to attach them":"拖放文件以附加","End voice call":"结束语音通话","Enter to send · Shift+Enter for new line":"按 Enter 发送 · 按 Shift+Enter 换行","Enter to send now · Esc to stop":"按 Enter 立即发送 · 按 Esc 停止","Enter to send when the answer ends · Esc to stop":"按 Enter 在回答结束后发送 · 按 Esc 停止","Expand image":"放大图片","Failed to get a response. Resuming…":"未能获取回复。正在恢复…","Feedback already submitted":"已提交反馈","Files uploading...":"正在上传文件...",Floating:"浮动","Full screen":"全屏","Good response":"回复很好","Hide conversations":"隐藏对话","Resize the conversation list":"调整对话列表的宽度","How can I help you, {name}?":"{name},有什么可以帮您?","How can {agent} help you, {name}?":"{name},{agent} 能为您做些什么?","Image could not be loaded":"无法加载图片","Image preview":"图片预览","Incorporating your message…":"正在纳入您的消息…",Input:"输入","Insert prompt template":"插入提示词模板","Interrupted by a server restart.":"因服务器重启而中断。","Listening...":"正在聆听...","Load earlier messages":"加载更早的消息","Loading earlier messages…":"正在加载更早的消息…","Loading conversation history…":"正在加载对话历史…","Loading image…":"正在加载图片…","MCP & dynamic tools":"MCP 与动态工具","Mention an agent":"提及智能体","Model reasoning":"模型推理","Move to workspace":"移至工作区","Mute microphone":"麦克风静音",Muted:"已静音","New chat":"新聊天","New conversation":"新对话","New conversation in this workspace":"在此工作区中新建对话","New conversation outside a workspace":"在工作区外新建对话","New conversation — send a message to start it":"新对话 — 发送一条消息即可开始","New workspace":"新建工作区",No:"否","No agent matches":"没有匹配的智能体","None of your conversations matches":"您的对话中没有匹配项","No conversation matches":"没有匹配的对话","No conversations yet":"暂无对话","No prompt matches":"没有匹配的提示词","No response was generated. Please try again.":"未生成回复。请重试。","No response.":"无回复。","Not recommended for chat":"不建议用于聊天","Not rendered yet":"尚未渲染",Open:"打开","Open agent page":"打开智能体页面","Open conversation":"打开对话","Open in XTM One":"在 XTM One 中打开","Other workspaces":"其他工作区",Output:"输出","Play Space Invaders":"玩 Space Invaders","Play Space Invaders in XTM One":"在 XTM One 中玩 Space Invaders","Polishing the answer":"正在润色回答",PowerPoint:"PowerPoint","PowerPoint (editable)":"PowerPoint(可编辑)","Preparing tools…":"正在准备工具…","Preparing…":"正在准备…",Presentation:"演示文稿","Putting it together":"正在整合内容",Quota:"配额","Quota reached":"已达配额","Read aloud":"朗读","Reasoning details":"推理详情","Reasoning details — interrupted by a server restart":"推理详情 — 因服务器重启而中断","Reasoning details — turn limit reached":"推理详情 — 已达轮次上限","Recalling memory…":"正在调取记忆…","Reconnecting…":"正在重新连接…","Reference a conversation":"引用对话","Remove from workspace":"从工作区中移除","Rename conversation":"重命名对话","Rename workspace":"重命名工作区","Rendering {progress}%":"正在渲染 {progress}%",Report:"报告","Response ready":"回复已就绪","Reticulating splines":"正在网格化样条",Retry:"重试",Save:"保存","Scroll to bottom":"滚动到底部","Saving response…":"正在保存回复…","Search agents...":"搜索智能体...","Search conversations...":"搜索对话...","Search prompts...":"搜索提示词...",Send:"发送","Send now":"立即发送","Send when the answer ends":"回答结束后发送","Sending…":"正在发送…","Sends when the answer ends:":"将在回答结束后发送:","Several agents are answering: your message is sent once they are done.":"多个智能体正在回答:它们完成后将发送您的消息。","Shared with you":"与您共享","Show conversations":"显示对话","Show less":"收起",Sidebar:"侧边栏",Skip:"跳过","Skip response":"跳过回复","Sorry, an error occurred. Please try again.":"抱歉,发生了错误。请重试。","Speak or tap to interrupt":"说话或点按即可打断","Speaking…":"正在说话…","Started in {channel}":"始于 {channel}","Stop dictation":"停止语音输入","Stop generating":"停止生成","Stop reading":"停止朗读",Stopped:"已停止","Stopping…":"正在停止…",Suggestions:"建议","Summarized conversation":"已总结的对话","Summarizing earlier conversation…":"正在总结较早的对话…",Superseded:"已被替换","Switch to":"切换到","Switch to another agent":"切换到其他智能体","Switch view":"切换视图","System prompt":"系统提示词","Tap to cancel":"点按以取消","Tell us what went wrong (optional)":"请告诉我们哪里出了问题(可选)","The agent is answering…":"智能体正在回答…","The agent needs your approval to run a tool:":"智能体需要您的批准才能运行工具:","The agent needs your approval to run these tools:":"智能体需要您的批准才能运行以下工具:","The agents you mentioned are asked as soon as the current answer ends.":"当前回答结束后,将立即询问您提及的智能体。","The conversation could not be deleted":"无法删除该对话","The conversation could not be moved":"无法移动该对话","The conversations you referenced are read with your message once the current answer ends.":"当前回答结束后,您引用的对话将与您的消息一起读取。","The conversation could not be renamed":"无法重命名该对话","The conversations could not be archived":"无法归档这些对话","The conversations could not be deleted":"无法删除这些对话","The render did not finish":"渲染未完成","The server restarted while this turn was running, so it stopped before it could finish.":"本轮运行期间服务器重启,因此本轮在完成前已停止。","The workspace could not be created":"无法创建工作区","The workspace could not be deleted":"无法删除工作区","The workspace could not be renamed":"无法重命名工作区","Thinking it through":"正在深入思考","Thinking...":"正在思考...","This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.":"此智能体专为任务设计,而非直接聊天,可能无法很好地回应对话。","This conversation could not be loaded.":"无法加载此对话。","This decision could not be sent. Reload the chat and try again.":"无法发送此决定。请重新加载聊天后重试。","This message waits for the current response":"此消息将等待当前回复完成","This message will be read with your next one.":"此消息将与您的下一条消息一起读取。","This item could not be loaded.":"无法加载此项目。","The response could not be stopped. Try again.":"无法停止回复。请重试。","This turn is no longer waiting for a decision.":"本轮已不再等待决定。","Tool definitions":"工具定义","Tool results":"工具结果","Transfer chain":"转交链","Transferred from {agent}":"由 {agent} 转交","Transferring to another agent…":"正在转交给其他智能体…","Transferring to {agent}…":"正在转交给 {agent}…","Turn limit reached.":"已达轮次上限。","Unable to connect. Please check the configuration.":"无法连接。请检查配置。","Unmute microphone":"取消麦克风静音","Untitled conversation":"未命名对话",Usage:"用量","Upload failed":"上传失败","Usage · {period}":"用量 · {period}","Uses AI. Verify results.":"由 AI 生成,请核实结果。","Using tools…":"正在使用工具…",Video:"视频","Voice call":"语音通话","Waiting before continuing…":"正在等待后继续…","Waiting for one background task…":"正在等待 1 个后台任务…","Waiting for your approval…":"正在等待您的批准…","Waiting for {count} background tasks…":"正在等待 {count} 个后台任务…","Waiting to render":"等待渲染","What could be improved?":"有哪些可以改进的地方?","Why not? The agent sees this and can adapt (optional)":"为什么拒绝?智能体会看到并据此调整(可选)","Working files ({count})":"工作文件({count})","Workspace name":"工作区名称",Workspaces:"工作区","Wrapping things up":"正在收尾",Yes:"是","Yes, always":"是,始终允许","Your answer is ready":"您的回答已就绪",default:"默认","e.g. wrong environment — use staging instead":"例如:环境不对 — 请改用预发布环境","just now":"刚刚","this month":"本月","this year":"今年",today:"今天","unknown tool":"未知工具","{agent} has finished":"{agent} 已完成","{agent} is answering…":"{agent} 正在回答…","{agent}: {status}":"{agent}:{status}","{counts} tokens":"{counts} Token","{count} iterations":"{count} 次迭代","{count} scenes":"{count} 个场景","{count} sections":"{count} 个章节","{count} slides":"{count} 张幻灯片","{count} tool calls":"{count} 次工具调用","{count} transfers":"{count} 次转交","{count}d ago":"{count} 天前","{count}h ago":"{count} 小时前","{count}m ago":"{count} 分钟前","{decided}/{total} decided":"已决定 {decided}/{total}","{name} was not attached: a file may be at most {size}.":"未附加 {name}:单个文件不得超过 {size}。","{name} was not attached: a message holds at most {count} files.":"未附加 {name}:一条消息最多包含 {count} 个文件。","{name} was not attached: the files of a message may add up to at most {size}.":"未附加 {name}:一条消息中文件的总大小不得超过 {size}。","{name} was not attached: this type of file is not accepted.":"未附加 {name}:不接受此类型的文件。","{percent}% full":"已用 {percent}%","{quota} (shared across all users)":"{quota}(所有用户共享)","{summary} — click for details":"{summary} — 点击查看详情","{tool} (+{count} more)…":"{tool}(另有 {count} 个)…","The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.":"智能体的迭代预算已用尽:执行在完成所有计划步骤之前已停止。最终回复是对目前已完成工作的尽力总结。","“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.":"“是,始终允许”会为您保存一项偏好设置。此后,该工具将无需询问即可运行(包括无人值守的计划运行),直到您撤销为止。"}},se=/^zh(?:[-_](?:cn|sg|hans)(?:[-_].*)?)?$/;function ie(e,t){const n=t||!e?function(e){const t=(e??("undefined"!=typeof navigator?navigator.language:void 0))?.toLowerCase(),n=t?.split(/[-_]/)[0];if(t&&n&&("zh"!==n||se.test(t)))return oe[n]}(t):void 0;return t=>{const r=e?.(t);return r&&r!==t?r:n?.[t]??t}}const ce=e=>"up"===e?"positive":"negative";function le(e,t,n,r){return t?n&&e?"persisted":null:r?"callback":null}function de(e){const t=(e??"").trim();return t?t.slice(0,2e3):null}function ue(e,t,n){return ne(e,t,n,"feedback")}async function he(e,t,n,r,a,o){const{url:s,init:i}=function(e,t,n,r,a){const o=`${e}/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}/feedback`;return r?{url:o,init:{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...a},body:JSON.stringify({rating:r.rating,comment:de(r.comment)})}}:{url:o,init:{method:"DELETE",credentials:"include",headers:{...a}}}}(t,n,r,a,o);try{return(await e(s,i)).ok}catch{return!1}}const pe=e=>void 0!==e&&/[\w-]/.test(e),me=/^[\w-]+$/;function ge(e){const t=[],n=/@([\w-]+)/g;let r=n.exec(e);for(;null!==r;){const a=r[1].toLowerCase();pe(e[r.index-1])||t.includes(a)||t.push(a),r=n.exec(e)}return t}function fe(e,t){if(0===e.length)return e;const n=new Set(ge(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}function ve(e,t){if(0===e.length)return[];const n=[];for(const r of ge(t))for(const t of e)t.key.toLowerCase()!==r||n.some(e=>e.conversationId===t.conversationId)||n.push(t);return n.slice(0,5)}function we(e){const t=Array.isArray(e)?e:Array.isArray(e?.conversations)?e.conversations:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.id&&t.id&&"string"==typeof t.key&&me.test(t.key)&&(n.some(e=>e.id===t.id)||n.push({id:t.id,title:"string"==typeof t.title?t.title.trim():"",key:t.key,updatedAt:"string"==typeof t.updated_at?t.updated_at:void 0,isOwn:!1!==t.is_own}))}return n}function be(e,t,n){return ne(e,t,n,"conversationReferences")}const ye={query:null,items:[],failed:!1};function xe(e,t){const n=e.toLowerCase();if(!n||t.key.toLowerCase().startsWith(n))return!0;const r=t.title.toLowerCase(),a=n.split(/[\s_-]+/).filter(Boolean);return a.length>0&&a.every(e=>r.includes(e))}function ke(e,t){if(t.every(t=>e.some(e=>{return r=t,(n=e).id===r.id&&n.key===r.key&&n.title===r.title&&n.isOwn===r.isOwn&&n.updatedAt===r.updatedAt;var n,r})))return e;const n=new Set(t.map(e=>e.id)),r=[...e.filter(e=>!n.has(e.id)),...t];return r.length>200?r.slice(r.length-200):r}function Ce(e){return{id:e.conversationId,title:e.title,key:e.key,isOwn:e.isOwn??!0}}function Ne(e,t={}){const n=Array.isArray(e)?e:Array.isArray(e?.workspaces)?e.workspaces:[],r=[];for(const e of n){if(!e||"object"!=typeof e)continue;const n=e;"string"==typeof n.id&&n.id&&"string"==typeof n.name&&(!0!==n.is_archived&&r.push({id:n.id,name:n.name,isOwn:"boolean"==typeof n.is_own?n.is_own:!!t.userId&&n.user_id===t.userId,isDefault:!0===n.is_default,canManage:!0===n.can_manage}))}return r}function Se(e){const t=e=>e.isDefault&&e.isOwn;return[...e].sort((e,n)=>t(e)!==t(n)?t(e)?-1:1:e.name.localeCompare(n.name))}function Te(e,t,n,r,a){return!(!r||!n.conversations.some(e=>e.conversationId===r))||!t.has(e)}function Ae(e,t,n){return!(t&&e.conversations.some(e=>e.conversationId===t))}const Ie=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&t.length<=500?t:null},Ee=/^[\w.-]+$/,ze=/^[A-Z][A-Za-z]*(?: [A-Z][A-Za-z]*)*$/;function Re(e){const t=Ie(e);return!t||Ee.test(t)||ze.test(t)?null:t}async function De(e){try{return function(e){if(!e||"object"!=typeof e)return null;const{detail:t,error:n}=e;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;return Ie(e.message)??Ie(e.detail)??Re(n)}return Ie(t)??Re(n)}(await e.json())}catch{return null}}function Me(e){return e?JSON.stringify(Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0)):""}function _e(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}const Le=[["system","system"],["tools","tools"],["dynamic_tools","dynamicTools"],["summary","summary"],["conversation","conversation"],["tool_results","toolResults"]];function Pe(e){const t=e.context_tokens,n=e.context_window;if("number"!=typeof t||"number"!=typeof n)return;if(!Number.isFinite(t)||!Number.isFinite(n)||n<=0||t<0)return;const r=function(e){if(!e||"object"!=typeof e)return;const t=e,n={};let r=!1;for(const[e,a]of Le){const o=t[e];"number"==typeof o&&Number.isFinite(o)&&o>0&&(n[a]=o,r=!0)}return r?n:void 0}(e.context_breakdown);return r?{used:t,limit:n,breakdown:r}:{used:t,limit:n}}function je(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.file_id;"string"==typeof r&&r&&t.push({fileId:r,filename:"string"==typeof e.filename?e.filename:"file",type:"string"==typeof e.type?e.type:void 0,size:"number"==typeof e.size?e.size:void 0,contentType:"string"==typeof e.content_type?e.content_type:void 0,fileTag:"working_file"===e.file_tag?"working_file":"download_file"})}return t.length>0?t:void 0}const $e=["presentation","report","video"],Ue=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0?e:void 0;function Oe(e){if(!e||"object"!=typeof e)return;const t=e,n=$e.find(e=>e===t.kind);return n&&"string"==typeof t.id&&t.id?{kind:n,id:t.id,title:"string"==typeof t.title?t.title:"",url:"string"==typeof t.url&&t.url?t.url:void 0,slideRef:"string"==typeof t.slide_ref&&t.slide_ref?t.slide_ref:void 0,slideCount:Ue(t.slide_count),sectionCount:Ue(t.section_count),sceneCount:Ue(t.scene_count),durationMs:Ue(t.duration_ms),status:"string"==typeof t.status&&t.status?t.status:void 0,progress:Ue(t.progress),downloads:Array.isArray(t.downloads)?t.downloads.filter(e=>"string"==typeof e&&!!e):[]}:void 0}function We(e){if(!Array.isArray(e))return;const t=e.map(Oe).filter(e=>!!e);return t.length>0?t:void 0}function qe(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.name&&e.name&&t.push({name:e.name,input:"string"==typeof e.input?e.input:void 0,output:"string"==typeof e.output?e.output:void 0,success:"boolean"!=typeof e.success||e.success})}return t.length>0?t:void 0}function Fe(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.conversation_id&&e.conversation_id&&(t.some(t=>t.conversationId===e.conversation_id)||t.push({conversationId:e.conversation_id,title:"string"==typeof e.title?e.title.trim():"",key:"string"==typeof e.key?e.key:""}))}return t.length>0?t:void 0}function Be(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n;"string"==typeof e.agent_name&&e.agent_name&&t.push({agentId:"string"==typeof e.agent_id?e.agent_id:"",agentName:e.agent_name})}return t.length>0?t:void 0}function He(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(!n||"object"!=typeof n)continue;const e=n,r=e.tool_call_id;if("string"!=typeof r||!r)continue;const a=e.arguments,o=e.input_schema;t.push({toolCallId:r,toolName:"string"==typeof e.tool_name&&e.tool_name?e.tool_name:"",toolDescription:"string"==typeof e.tool_description?e.tool_description:void 0,arguments:a&&"object"==typeof a&&!Array.isArray(a)?a:{},inputSchema:o&&"object"==typeof o&&!Array.isArray(o)?o:void 0,source:"string"==typeof e.source?e.source:void 0})}return t.length>0?t:void 0}const Ve=e=>"string"==typeof e&&e?e:void 0,Ke=e=>e&&"object"==typeof e&&!Array.isArray(e)?e:void 0;function Ge(e){const t=Ve(e.agent_name);if(!t)return;const n=Ke(e.inner);let r=n;for(let e=0;"consult_progress"===r?.status&&e<8;e+=1)r=Ke(r.inner);const a=Array.isArray(r?.tools)?r.tools.filter(e=>"string"==typeof e):void 0,o=Ve(e.agent_id)??t;return{consultId:Ve(e.consult_id)??o,agentId:o,agentName:t,status:Ve(r?.status),tools:a,answering:"streaming"===n?.status||"composing"===n?.status}}function Xe(e){if("string"==typeof e)return e?{agentName:e}:void 0;if(!e||"object"!=typeof e)return;const t=e,n={agentId:Ve(t.agent_id),agentName:Ve(t.agent_name)??Ve(t.name),agentIcon:Ve(t.agent_icon)};return n.agentId||n.agentName?Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e)):void 0}function Ye(e,t){const n=e.type;if("error"===n||"cancelled"===n){const t=Ve(e.message_id),r=!0===e.provisional||void 0,a={...t?{messageId:t,raw:{...e}}:{},...r?{provisional:r}:{}};return"error"===n?{action:"error",content:e.content||"",...a}:{action:"cancelled",...a}}if("session_expired"===n)return{action:"session_ended",reason:Ve(e.reason)};if("approval_resolved"===n)return{action:"approval_resolved"};if("folded_into_active_turn"===n)return{action:"folded",turnId:Ve(e.turn_id)};if("conversation_title"===n){const t=Ve(e.title);return t?{action:"conversation_title",conversationId:Ve(e.conversation_id),title:t}:{action:"noop"}}if("user_message"===n){const[t]=Ze([e.message]);return t&&"user"===t.role?{action:"user_message",message:{...t,id:Je(t.serverId)}}:{action:"noop"}}if("thinking"===n)return{action:"status",status:"thinking",resumed:!0===e.resumed||void 0,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};if("status"===n){const n=e.status;if("tool_done"===n||"wind_down"===n)return{action:"noop"};if("streaming"===n)return{action:"status",status:"streaming"};if("thinking_text"===n)return{action:"status",status:"thinking_text",thinkingContent:e.content};if("tool_start"===n)return t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:e.tools};if("tool_progress"===n&&"page_action_required"===e.event){if("string"!=typeof e.action_id||!e.action_id)return{action:"noop"};const t=function(e){if(!e||"object"!=typeof e)return{type:"unsupported",requested:"malformed"};const t=e,n=e=>"string"==typeof e&&e.length>0;return"snapshot"===t.type?{type:"snapshot"}:"navigate"===t.type&&n(t.path)?{type:"navigate",path:t.path}:"click"===t.type&&n(t.ref)?{type:"click",ref:t.ref}:"open"===t.type&&n(t.ref)?{type:"open",ref:t.ref}:"type"===t.type&&n(t.ref)&&"string"==typeof t.text?{type:"type",ref:t.ref,text:t.text}:{type:"unsupported",requested:"string"==typeof t.type?t.type.slice(0,64):"unknown"}}(e.action);return{action:"page_action_required",actionId:e.action_id,pageAction:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}}if("transfer_start"===n||"mention_answering"===n)return{action:"status",status:"transfer_start"===n?"transferring":n,agentName:Ve(e.agent_name),contextUsage:Pe(e)};if("consult_progress"===n)return{action:"status",status:n,consult:Ge(e)};if("wait_start"===n)return{action:"status",status:"wait_start",waitSeconds:"number"==typeof e.seconds&&e.seconds>0?e.seconds:void 0,waitReason:Ve(e.reason)};if("tool_heartbeat"===n)return{action:"status",status:"tool_heartbeat",tools:e.tools,elapsedS:"number"==typeof e.elapsed_s?e.elapsed_s:void 0};const r=Pe(e),a="number"==typeof e.iteration&&Number.isInteger(e.iteration)&&e.iteration>0?e.iteration:void 0;return"thinking"===n&&t.hasUsedTools?{action:"status",status:"analyzing",contextUsage:r,iteration:a}:{action:"status",status:n,tools:e.tools,contextUsage:r,phase:Ve(e.phase),iteration:a}}if("approval_required"===n){const t=He(e.proposals);return t?{action:"approval_required",proposals:t,conversationId:"string"==typeof e.conversation_id?e.conversation_id:void 0}:{action:"noop"}}return"stream"===n?{action:"stream",content:e.content}:"done"===n?{action:"done",content:e.content,conversationId:e.conversation_id,toolNames:e.tool_names,toolCallCount:e.tool_call_count,iterations:e.iterations,transferAgentId:e.transfer_agent_id,transferAgentName:e.transfer_agent_name,attachments:je(e.attachments),artifacts:We(e.artifacts),reasoning:"string"==typeof e.reasoning?e.reasoning:void 0,toolCallTrace:qe(e.tool_call_trace),transferChain:Be(e.transfer_chain),isTruncated:!0===e.is_truncated||void 0,contextUsage:Pe(e),messageId:"string"==typeof e.message_id&&e.message_id?e.message_id:void 0,intermediate:!0===e.intermediate||void 0,answeredBy:Xe(e.answered_by),mentionFailed:!0===e.mention_failed||void 0,raw:{...e}}:{action:"noop"}}function Je(e,t=_e()){return e?`msg-${e}`:t}function Qe(e){if(!e||"object"!=typeof e)return;const{rating:t,comment:n}=e;return"positive"===t||"negative"===t?{rating:t,comment:"string"==typeof n&&n.trim()?n:null}:void 0}function Ze(e){if(!Array.isArray(e))return[];const t=[];return e.forEach((e,n)=>{if(!e||"object"!=typeof e)return;const r=e;if("user"!==r.role&&"assistant"!==r.role)return;const a="string"==typeof r.created_at?new Date(r.created_at):null,o=a&&!Number.isNaN(a.getTime())?a:null,s="assistant"===r.role?Xe(r.answered_by):void 0,i="string"==typeof r.id&&r.id?r.id:void 0;t.push({id:Je(i,`restored-${n}`),serverId:i,role:r.role,content:"string"==typeof r.content?r.content:"",timestamp:o??new Date,timestampUnknown:!o||void 0,feedback:"assistant"===r.role?Qe(r.feedback):void 0,agentName:s?.agentName??("string"==typeof r.agent_name?r.agent_name:void 0),answeredBy:s,mentionFailed:"assistant"===r.role&&!0===r.mention_failed||void 0,attachments:je(r.attachments),artifacts:"assistant"===r.role?We(r.artifacts):void 0,conversationRefs:"user"===r.role?Fe(r.conversation_refs):void 0,toolNames:Array.isArray(r.tool_names)?r.tool_names:void 0,toolCallCount:"number"==typeof r.tool_call_count?r.tool_call_count:void 0,iterations:"number"==typeof r.iterations?r.iterations:void 0,reasoning:"string"==typeof r.reasoning?r.reasoning:void 0,toolCallTrace:qe(r.tool_call_trace),transferChain:Be(r.transfer_chain),isTruncated:!0===r.is_truncated||void 0,interrupted:"assistant"===r.role&&!0===r.interrupted||void 0,raw:{...r}})}),t}function et(e,t){const n=e.event;if("nextAgentFlow"===n){const n=e.data,r=n?.nodeId;return"INPROGRESS"===n?.status&&r&&(t.activeNodeId=r),{action:"noop"}}if("start"===n)return{action:"noop"};if("token"===n){return{action:"stream",content:(e.data??"").replace(/<br\s*\/?>/g,"\n")}}if("agentReasoning"===n){const n=e.data,r=n?.usedTools;return r?.length?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:r.map(e=>e.tool)}):t.hasUsedTools?{action:"status",status:"analyzing"}:{action:"status",status:"thinking"}}if("usedTools"===n){t.hasUsedTools=!0;const n=e.data;return{action:"status",status:"tool_start",tools:Array.isArray(n)?n.map(e=>e.tool):[]}}if("metadata"===n){const t=e.data,n=t?.chatId;return n?{action:"set_chat_id",chatId:n}:{action:"noop"}}return"error"===n?{action:"error",content:e.data||""}:"end"===n?{action:"done",content:""}:{action:"noop"}}function tt(e,t){const n=e.type;if("RUN_STARTED"===n)return{action:"status",status:"thinking"};if("RUN_FINISHED"===n)return{action:"done",content:""};if("RUN_ERROR"===n)return{action:"error",content:"string"==typeof e.message?e.message:""};if("STEP_STARTED"===n){return{action:"status",status:e.stepName||"thinking"}}if("STEP_FINISHED"===n)return{action:"noop"};if("TEXT_MESSAGE_START"===n)return{action:"status",status:"streaming"};if("TEXT_MESSAGE_CONTENT"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TEXT_MESSAGE_END"===n)return{action:"noop"};if("TEXT_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"stream",content:t}:{action:"noop"}}if("TOOL_CALL_START"===n){t.hasUsedTools=!0;const n=e.toolCallName;return{action:"status",status:"tool_start",tools:n?[n]:[]}}if("TOOL_CALL_ARGS"===n)return{action:"noop"};if("TOOL_CALL_END"===n)return{action:"status",status:"analyzing"};if("TOOL_CALL_RESULT"===n)return{action:"noop"};if("TOOL_CALL_CHUNK"===n){const n=e.toolCallName;return n?(t.hasUsedTools=!0,{action:"status",status:"tool_start",tools:[n]}):{action:"noop"}}if("REASONING_START"===n||"REASONING_MESSAGE_START"===n)return{action:"status",status:"thinking"};if("REASONING_MESSAGE_CONTENT"===n||"REASONING_MESSAGE_CHUNK"===n){const t=e.delta;return t?{action:"status",status:"thinking_text",thinkingContent:t}:{action:"status",status:"thinking"}}return{action:"noop"}}function nt(){let e=0,t=null,n=null;return{get generation(){return e},get pending(){return t},run(r){if(t)return t;const a=e,o=new AbortController;n=o;const s=r(()=>a===e,o.signal).catch(()=>null);return t=s,s.finally(()=>{t===s&&(t=null),n===o&&(n=null)}),s},abandon(){e+=1,t=null,n?.abort(),n=null}}}function rt(e,t){return null!==e&&"function"==typeof t}function at(e){return e?.defaultView?.location?.href??("undefined"==typeof window?void 0:window.location.href)}const ot=(e,t)=>{const n=t??at();if(!e||!n)return null;try{const t=new URL(e,n);if("http:"!==t.protocol&&"https:"!==t.protocol)return null;if(t.origin!==new URL(n).origin)return null;const r=`${t.pathname}${t.search}${t.hash}`||"/";return r.startsWith("//")?null:r}catch{return null}};function st(e){const t=e&&"closest"in e?e:e?.parentElement;return!!t?.closest?.(".filigran-chatbot")}const it=/^(current-password|new-password|one-time-code|cc-)/;function ct(e){const t=e.ownerDocument.defaultView,n={bubbles:!0,cancelable:!0,view:t??void 0,pointerType:"mouse"},r=t?.PointerEvent??t?.MouseEvent??MouseEvent,a=t?.MouseEvent??MouseEvent;e.dispatchEvent(new r("pointerover",n)),e.dispatchEvent(new r("pointerenter",{...n,bubbles:!1})),e.dispatchEvent(new a("mouseover",n)),e.dispatchEvent(new a("mouseenter",{...n,bubbles:!1}))}function lt(e,t,n){const r=e=>e.preventDefault();for(const n of t)e.addEventListener(n,r,!0);try{n()}finally{for(const n of t)e.removeEventListener(n,r,!0)}}function dt(e,t,n){if(e.matches?.("a[href]")){const r=e.getAttribute("target");if(r&&"_self"!==r)return{ok:!1,error:"opens_new_tab"};const a=e.getAttribute("href")??"";if(a&&!a.startsWith("#")){const e=ot(a,n);if(!e)return{ok:!1,error:"external_link"};if(t)return t(e),{ok:!0}}}e.focus?.();const r=e.closest?.("a[href]"),a=!!r&&!(r.getAttribute("href")??"").startsWith("#"),o=a?["submit","click"]:["submit"],s=e.matches?.('input[type="checkbox"], input[type="radio"]')??!1,i=e.checked;if(lt(e.ownerDocument,o,()=>e.click()),s&&a&&e.checked===i){const t=e;t.checked="radio"===t.type||!i,t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("input",{bubbles:!0})),t.dispatchEvent(new(e.ownerDocument.defaultView?.Event??Event)("change",{bubbles:!0}))}return{ok:!0}}function ut(e){const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!1}for(let t=e;t;t=t.parentElement){if(t.hidden||t.hasAttribute("inert"))return!1;if("true"===t.getAttribute("aria-hidden"))return!1;const e=t.ownerDocument.defaultView?.getComputedStyle(t);if("none"===e?.display||"hidden"===e?.visibility)return!1}return!0}function ht(e){const t=e.getAttribute("aria-expanded");if("true"===t)return!0;if("false"===t)return!1;const n=e.getAttribute("aria-controls");if(!n)return!1;const r=e.ownerDocument.getElementById(n);return!!r&&ut(r)}async function pt(e,t,n){const r=e.hasAttribute("aria-expanded")||e.hasAttribute("aria-controls");if(ht(e))return{ok:!0};if(r){if(ct(e),await(a=()=>ht(e),o=300,new Promise(e=>{const t=Date.now(),n=()=>a()?e(!0):Date.now()-t>=o?e(!1):void setTimeout(n,30);n()})))return{ok:!0}}else if(await function(e,t,n=300){const r=e.defaultView,a=r?.MutationObserver??globalThis.MutationObserver;return a?new Promise(r=>{const o=new a(e=>{e.some(e=>e.addedNodes.length>0&&!st(e.target)&&Array.from(e.addedNodes).some(e=>!st(e)))&&(o.disconnect(),clearTimeout(s),r(!0))});o.observe(e.body??e.documentElement,{subtree:!0,childList:!0}),t();const s=setTimeout(()=>{o.disconnect(),r(!1)},n)}):(t(),Promise.resolve(!0))}(e.ownerDocument,()=>ct(e)))return{ok:!0};var a,o;return n?.aborted?{ok:!1,error:"aborted"}:dt(e,void 0,t)}const mt=/\b(search|query|filter|find|recherche|rechercher)\b/i;async function gt(e,t,n,r,a){try{if(a?.aborted)return{ok:!1,error:"aborted"};if("snapshot"===e.type)return{ok:!0};if("unsupported"===e.type)return{ok:!1,error:`unsupported_action: ${e.requested}`.slice(0,500)};if("navigate"===e.type){if(!n)return{ok:!1,error:"navigation_unavailable"};const t=ot(e.path,at(r));return t?(n(t),{ok:!0}):{ok:!1,error:"external_path"}}const o=t.get(e.ref);return o&&o.isConnected?ut(o)?function(e){if(e.hasAttribute("disabled"))return!0;if("true"===e.getAttribute("aria-disabled"))return!0;if(e.matches?.(":disabled"))return!0;if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(o)?{ok:!1,error:"disabled"}:o.matches?.('input[type="file"]')?{ok:!1,error:"opens_file_dialog"}:"open"===e.type?await pt(o,at(r??o.ownerDocument),a):"click"===e.type?dt(o,n,at(r??o.ownerDocument)):function(e){return e.matches?.('textarea, [contenteditable="true"], input:not([type]), input[type="text"], input[type="search"], input[type="email"], input[type="url"], input[type="tel"], input[type="number"]')??!1}(o)?function(e){return!0===e.readOnly||"true"===e.getAttribute("aria-readonly")}(o)?{ok:!1,error:"read_only"}:function(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>it.test(e))}(o)?{ok:!1,error:"secret_field"}:(o.focus?.(),function(e,t){const n=e.ownerDocument.defaultView;if(n&&(e instanceof n.HTMLInputElement||e instanceof n.HTMLTextAreaElement)){const r=e instanceof n.HTMLInputElement?n.HTMLInputElement.prototype:n.HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(r,"value")?.set?.call(e,t)}else e.textContent=t;e.dispatchEvent(new(n?.Event??Event)("input",{bubbles:!0})),e.dispatchEvent(new(n?.Event??Event)("change",{bubbles:!0}))}(o,e.text),function(e){if("searchbox"===e.getAttribute("role"))return!0;if("search"===e.type)return!0;if(null!==e.closest('[role="search"]'))return!0;if(!["name","id","placeholder","aria-label","title"].some(t=>mt.test(e.getAttribute(t)??"")))return!1;const t=e.form;return!t||1===t.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]), select, textarea, [contenteditable="true"]').length}(o)&&function(e){const t=e.ownerDocument.defaultView,n=t?.KeyboardEvent??KeyboardEvent,r={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:!0,cancelable:!0},a=new n("keydown",r);e.dispatchEvent(a),e.dispatchEvent(new n("keyup",r));const o=e.form;o&&!a.defaultPrevented&&lt(e.ownerDocument,["submit"],()=>o.requestSubmit?.())}(o),{ok:!0}):{ok:!1,error:"not_a_text_field"}:{ok:!1,error:"not_visible"}:{ok:!1,error:"unknown_ref"}}catch(e){return{ok:!1,error:`failed: ${e instanceof Error?e.message:String(e)}`.slice(0,500)}}}const ft="[truncated]",vt=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","checkbox","radio","switch","textbox","searchbox","combobox","treeitem"]);function wt(e){if("select"===e.tagName.toLowerCase())return!1;for(const t of Array.from(e.querySelectorAll('a[href], button, summary, select, textarea, input, [contenteditable="true"], [role]')))if(bt(t))return!0;return!1}function bt(e){const t=e.getAttribute("role");if(t&&vt.has(t))return t;const n=e.tagName.toLowerCase();if("a"===n&&e.hasAttribute("href"))return"link";if("button"===n||"summary"===n)return"button";if("select"===n)return"combobox";if("textarea"===n)return"textbox";if("input"===n){const t=(e.getAttribute("type")||"text").toLowerCase();return"hidden"===t?null:["button","submit","reset","image"].includes(t)?"button":"checkbox"===t||"radio"===t?t:"search"===t?"searchbox":"file"===t?"button":"textbox"}return"true"===e.getAttribute("contenteditable")?"textbox":null}function yt(e){const t=/^h([1-6])$/i.exec(e.tagName);return t?Number(t[1]):null}function xt(e){const t=e.ownerDocument.defaultView;let n="";for(const r of Array.from(e.childNodes))if(3===r.nodeType)n+=r.textContent??"";else if(1===r.nodeType){if(Rt(r)||It(r))continue;const e=t?.getComputedStyle(r).display??"";n+=""===e||"inline"===e||"contents"===e?xt(r):` ${xt(r)} `}return n}function kt(e){return(e??"").replace(/\s+/g," ").trim()}const Ct=new Set(["button","link","tab","menuitem","menuitemcheckbox","menuitemradio","option","treeitem","switch"]);function Nt(e,t){const n=e.ownerDocument,r=e.getAttribute("aria-labelledby");if(r){const e=kt(r.split(/\s+/).map(e=>n.getElementById(e)?.textContent??"").join(" "));if(e)return e}const a=kt(e.getAttribute("aria-label"));if(a)return a;const o=e.getAttribute("id"),s=o&&Array.from(n.getElementsByTagName("label")).find(e=>e.htmlFor===o)||e.closest("label");if(s){const e=kt(Array.from(s.childNodes).filter(e=>3===e.nodeType).map(e=>e.textContent).join(" "));if(e||kt(s.textContent))return e||kt(s.textContent)}const i=e.tagName.toLowerCase(),c=(e.getAttribute("type")||"").toLowerCase();if("input"===i&&["submit","reset","button"].includes(c)){const t=kt(e.getAttribute("value"));if(t)return t;if("button"!==c)return"submit"===c?"Submit":"Reset"}const l=kt(e.getAttribute("alt"))||kt(e.querySelector("img[alt]")?.getAttribute("alt"));if(l)return l;const d=It(e)?"":kt(xt(e));if(Ct.has(t)&&d)return d;const u=kt(e.getAttribute("placeholder"));if(u)return u;const h=kt(e.getAttribute("title"));return h||d}function St(e){return JSON.stringify(e.slice(0,80))}function Tt(e){const t=[];(e.hasAttribute("disabled")||function(e){if(!e.matches?.("button, input, select, textarea"))return!1;const t=e.closest?.("fieldset[disabled]");if(!t)return!1;const n=Array.from(t.children).find(e=>"legend"===e.tagName.toLowerCase());return!n?.contains(e)}(e)||"true"===e.getAttribute("aria-disabled"))&&t.push("disabled"),"true"===e.getAttribute("aria-selected")&&t.push("selected"),(e.checked||"true"===e.getAttribute("aria-checked"))&&t.push("checked"),"true"===e.getAttribute("aria-expanded")?t.push("expanded"):"false"!==(e.getAttribute("aria-haspopup")??"false")?t.push("menu"):"false"===e.getAttribute("aria-expanded")&&t.push("collapsed"),"true"===e.getAttribute("aria-pressed")&&t.push("pressed");const n=e.getAttribute("aria-current");return n&&"false"!==n&&t.push("current"),t}const At=/^(current-password|new-password|one-time-code|cc-)/;function It(e){return"password"===(e.getAttribute("type")||"").toLowerCase()||(e.getAttribute("autocomplete")||"").toLowerCase().split(/\s+/).some(e=>At.test(e))}function Et(e,t){if(!["textbox","searchbox","combobox"].includes(t))return null;if(It(e))return null;const n="value"in e?String(e.value??""):kt(xt(e));return n||null}function zt(e){const t=e.getAttribute("href"),n=e.ownerDocument.defaultView?.location;if(!t||!n)return"";try{const e=new URL(t,n.href);return e.origin===n.origin?` -> ${e.pathname}${e.search}`:""}catch{return""}}function Rt(e){if(e.classList.contains("filigran-chatbot"))return!0;const t=e.closest?.("details:not([open])");if(t&&t!==e){const n=Array.from(t.children).find(e=>"summary"===e.tagName.toLowerCase());if(!n?.contains(e))return!0}if(e.hidden||e.hasAttribute("inert"))return!0;if("true"===e.getAttribute("aria-hidden"))return!0;const n=e.ownerDocument.defaultView?.getComputedStyle(e);return"none"===n?.display||"hidden"===n?.visibility}const Dt="filigranChatConversationId",Mt="filigranChatLegacyChatId",_t="filigranChatAgentSlug",Lt="filigranChatSidebarWidth",Pt="filigranChatConversationListWidth",jt="filigran-chat-collapsed-workspaces",$t="filigran-chat-workspaces-open",Ut="filigranChatDraft:",Ot="filigranChatDraftRefs:";function Wt(e,t){return e?`${e}:${t}`:t}function qt(e){if("undefined"==typeof window)return null;try{return"local"===e?window.localStorage:window.sessionStorage}catch{return null}}function Ft(e,t){try{return qt(e)?.getItem(t)??null}catch{return null}}function Bt(e,t,n){try{const r=qt(e);if(!r)return;n?r.setItem(t,n):r.removeItem(t)}catch{}}class Ht extends Error{constructor(){super("the event stream fell silent"),this.name="SseStreamSilentError"}}async function Vt(e,t,{idleTimeoutMs:n}={}){const r=e.getReader(),a=new TextDecoder;let o="",s=null,i=!1,c=!1,l=null;const d=()=>{null!==l&&clearTimeout(l),l=null;const e="function"==typeof n?n():n;i&&void 0!==e&&(l=setTimeout(()=>{c=!0,r.cancel().catch(()=>{})},e))},u=e=>{const r=e.replace(/\r$/,"");if(r.startsWith(":")){const e=Date.now();null===s&&(s=e);const t="function"==typeof n?n():n;void 0!==t&&e-s>=t/3&&(i=!0)}if(!r.startsWith("data:"))return!0;const a=r.startsWith("data: ")?r.slice(6):r.slice(5);let o;try{o=JSON.parse(a)}catch{return!0}return!(o&&"object"==typeof o&&!Array.isArray(o))||!1!==t(o)};try{for(;;){const{done:e,value:t}=await r.read();if(c)throw new Ht;if(e)break;o+=a.decode(t,{stream:!0});const n=o.split("\n");o=n.pop()??"";for(const e of n)if(!u(e))return void await r.cancel().catch(()=>{});d()}o+=a.decode(),o&&u(o)}finally{null!==l&&clearTimeout(l),r.releaseLock()}}const Kt=e=>e.some(e=>"error"===e.uploadStatus),Gt=new Map([["md",["text/markdown"]],["markdown",["text/markdown"]],["yaml",["application/yaml","application/x-yaml","text/yaml"]],["yml",["application/yaml","application/x-yaml","text/yaml"]],["csv",["text/csv"]],["tsv",["text/tab-separated-values"]],["txt",["text/plain"]],["log",["text/plain"]],["json",["application/json"]]]);function Xt(e,t){const n=(e??"").split(",").map(e=>e.trim().toLowerCase()).filter(Boolean);if(0===n.length)return!0;const r=t.name.toLowerCase();if(n.some(e=>e.startsWith(".")&&r.endsWith(e)))return!0;const a=r.lastIndexOf("."),o=t.type?[t.type.toLowerCase()]:a>=0?Gt.get(r.slice(a+1))??[]:[];return n.some(e=>!e.startsWith(".")&&o.some(t=>e.endsWith("/*")?t.startsWith(e.slice(0,-1)):t===e))}function Yt(e,t){try{return e.getData(t)??""}catch{return""}}const Jt=/<(head|style|script|title|template|xml)\b/iy,Qt=/&(?:nbsp|#160|#xa0);/iy,Zt=/\s/;function en(e,t){for(let n=t+1;n<e.length;n+=1){const t=e[n];if(">"===t)return n+1;if('"'===t||"'"===t){const r=e.indexOf(t,n+1);if(r<0)return-1;n=r}}return-1}function tn(e){if(!e)return[];const t=Array.from(e.files??[]);if(0===t.length)return t;return t.every(e=>e.type.startsWith("image/"))&&/\S/.test(Yt(e,"text/plain"))&&function(e){const t=new Set;let n=0;for(;n<e.length;){const r=e[n];if("<"===r){if(e.startsWith("\x3c!--",n)){const t=e.indexOf("--\x3e",n+4);if(t>=0){n=t+3;continue}}Jt.lastIndex=n;const r=Jt.exec(e)?.[1].toLowerCase();if(r&&!t.has(r)){const a=new RegExp(`</${r}\\s*>`,"gi");if(a.lastIndex=n,a.exec(e)){n=a.lastIndex;continue}t.add(r)}const a=en(e,n);if(a<0)return!0;n=a;continue}if("&"===r&&(Qt.lastIndex=n,Qt.test(e)))n=Qt.lastIndex;else{if(!Zt.test(r))return!0;n+=1}}return!1}(Yt(e,"text/html"))?[]:t}function nn(e){if(e.slug&&/^[\w-]+$/.test(e.slug))return e.slug;return e.name.toLowerCase().replace(/[^\w-]+/g,"-").replace(/^-+|-+$/g,"")||null}function rn(e,t){const n=[];for(const r of ge(t))for(const t of e)t.key.toLowerCase()!==r||n.includes(t.agentId)||n.push(t.agentId);return n}const an=r({fetch:(e,t)=>globalThis.fetch(e,t),sessionEnded:()=>{}}),on=an.Provider;function sn(){return a(an).fetch}const cn=(e,t)=>Wt(e,`${Ut}${t??"new"}`),ln=(e,t)=>Wt(e,`${Ot}${t??"new"}`);function dn(e,t){try{const n=JSON.parse(Ft("session",ln(e,t))??"[]");return Array.isArray(n)?n.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.conversationId&&"string"==typeof e.key&&"string"==typeof e.title):[]}catch{return[]}}const un=(e,t,n,r)=>JSON.stringify([cn(e,t),n,r]);function hn(e,t,n,r,a){const o=un(t,n,r,a);o!==e.current&&(e.current=o,Bt("session",cn(t,n),r),Bt("session",ln(t,n),a.length>0?JSON.stringify(a):null))}function pn(e,t){const n=Ft("session",cn(e,t))??"";return{text:n,refs:fe(dn(e,t),n)}}const mn=9e5,gn=mn,fn=new Set(["wait_status","tool_progress"]),vn=new Set(["tool_progress","tool_heartbeat","wait_status","thinking_text"]),wn=new Set(["thinking","analyzing","llm_step","tool_start","composing","streaming","stream_retract","mention_answering","transferring"]);const bn=new Set(["status","stream","done","approval_required","error","cancelled"]),yn=new Set(["mentioned_agent_ids","content","conversation_id","agent_slug","supports_tool_approval","supports_page_actions","supports_artifacts","referenced_conversation_ids","file_ids","context"]);function xn(e,t,n,r){return{...e,content:n,timestamp:r,toolNames:t.toolNames,toolCallCount:t.toolCallCount,iterations:t.iterations,attachments:t.attachments,artifacts:t.artifacts,reasoning:t.reasoning,toolCallTrace:t.toolCallTrace,transferChain:t.transferChain,isTruncated:t.isTruncated,agentName:t.answeredBy?.agentName??e.agentName,answeredBy:t.answeredBy,mentionFailed:t.mentionFailed,serverId:t.messageId??e.serverId,raw:t.raw??e.raw}}const kn=["toolNames","toolCallCount","iterations","attachments","artifacts","reasoning","toolCallTrace","transferChain","isTruncated","interrupted","agentName","answeredBy","mentionFailed","feedback"],Cn=Symbol("sentText");function Nn(e,t){return t===e.content?e:{...e,[Cn]:t}}function Sn(e){return e[Cn]??e.content}const Tn=e=>`${e.role}\0${"user"===e.role?Sn(e):e.content}`,An=e=>`${e.role}\0${e.content}`;function In(e,t){const n={...e,serverId:t.serverId??e.serverId,raw:t.raw??e.raw};if("assistant"!==e.role)return n;const r=n;for(const e of kn)void 0!==t[e]&&(r[e]=t[e]);return n}function En(e,t,n){const r=null===n?-1:e.findIndex(e=>e.id===n);return r<0?[...e,t]:[...e.slice(0,r),t,...e.slice(r)]}const zn=(e,t)=>[e,t].filter(Boolean).join("\n\n"),Rn=(e,t)=>void 0!==e.displayText||void 0!==t.displayText?zn(e.displayText??e.text,t.displayText??t.text):void 0;function Dn(e,t){const n=new Set(e.refs.map(e=>e.conversationId)),r=new Set(e.mentions.map(e=>e.agentId));return{text:zn(e.text,t.text),draft:zn(e.draft,t.draft),files:[...e.files,...t.files],refs:[...e.refs,...t.refs.filter(e=>!n.has(e.conversationId))],mentions:[...e.mentions,...t.mentions.filter(e=>!r.has(e.agentId))],extras:e.extras||t.extras?{...e.extras,...t.extras}:void 0,displayText:Rn(e,t)}}const Mn={text:"",draft:"",files:[],refs:[],mentions:[]};function _n(e){return{...e.reduce(Dn,Mn),parts:e}}function Ln(e,t){return _n([...e?.parts??[],t])}function Pn(e){for(const t of e)B(t.onNotSent)}function jn(e,t,n){if(!1===t)return null;const r=t&&"object"==typeof t?t:void 0,a=("string"==typeof r?.text?r.text:e).trim(),o="string"==typeof r?.displayText?r.displayText.trim():"",s="string"==typeof n?n.trim():"";return{text:a,displayText:o||s||a,extras:r?.extras}}function $n(e){return"error"===e.action||"cancelled"===e.action||"done"===e.action&&!e.intermediate?e:null}function Un(e){return("error"===e.action||"cancelled"===e.action)&&!!e.provisional}function On(e){const t=B(e);return t&&"object"==typeof t?t:{}}class Wn extends Error{detail;constructor(e,t){super(`File upload failed: ${e}`),this.detail=t}}const qn=52428800;function Fn(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t].serverId;if(n)return n}return null}function Bn(e,t){const n=null===t?0:e.findIndex(e=>e.serverId===t)+1;return null!==t&&0===n?"stopped":e.slice(n).some(e=>"assistant"===e.role)?"answered":"stopped"}function Hn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",agentSlug:r,agentPending:a=!1,requestHeaders:d,pageContext:u,onRelativeLinkClick:h,t:p,maxFileCount:m=10,maxTotalSize:g=52428800,maxFileSize:f,acceptFileTypes:v,onFileRefused:w,storageKeyPrefix:b,controlledConversationId:y,onConversationIdChange:x,getRequestExtras:k,onStreamEvent:C,onSessionEnded:N,onConversationTitle:S,onMessageSent:T,historySettledFor:A=null,steerAttachments:E=!1,holdSends:z=!1,agentMentionsEnabled:D=!1,onBeforeSend:M,onHeldSendSettled:_}){const L=sn(),P="legacy"===n,[j,$]=o([]),[U,O]=o(!1),[W,q]=o(null),[F,H]=o(null),[V,K]=o(void 0),[G,X]=o(!1),Y=s(!1),J=(e,t)=>{K(e),Y.current=t,X(t)},Q=i(()=>F&&V?{...F,answeringAgentName:V}:F,[F,V]),Z=void 0!==y,ee=Wt(b,Dt),te=Wt(b,Mt),[re,ae]=o(()=>Z?y??null:Ft("local",ee)),[oe]=o(()=>pn(b,re)),[se,ie]=o(oe.text),[ce,le]=o(oe.refs),de=s(null);de.current??=un(b,re,oe.text,oe.refs);const[ue,he]=o([]),[pe,me]=o([]),[we,ye]=o(null),[xe,ke]=o(null),[Ce,Ne]=o(null),[Se,Te]=o(!1),[Ae,Ie]=o(null),[Ee,ze]=o(!1),[Re,Le]=o(0),[Pe,je]=o(0),[$e,Ue]=o(()=>Ft("local",te)),Oe=s(!1),We=s(null),qe=s(null),Fe=s(null),Be=s(!1),Ve=s(null),Ke=s(null),Ge=s(null),Xe=s(null),Qe=s(null),Ze=s(!1),[at,ot]=o(null),it=s(at);it.current=at;const[ct,lt]=o(null),[dt,ut]=o(null),ht=s(!1),pt=c(()=>{ht.current=!1,lt(null)},[]),mt=c(()=>ut(null),[]),vt=s(new Map),Ct=s(null),[At,It]=o(!1),_t=s(null),Lt=s(!1),Pt=s("off"),jt=s(0),$t=s(null),Ut=s(null),Ot=s(null),qt=s(null),[Ht,Gt]=o(!1),Yt=e=>{const t=qt.current?.readBack;t&&e!==qt.current&&window.clearTimeout(t.timer),qt.current=e,Gt(null!==e)},Jt=s(j);Jt.current=j;const Qt=s(0),[Zt,en]=o(()=>_e()),nn=s(null),an=s(null),on=s(!1),cn=s(0),ln=s(null),dn=s(null),kn=s(null),Cn=()=>{null!==nn.current&&window.clearTimeout(nn.current),nn.current=null,an.current=null,on.current=!1,kn.current&&window.clearTimeout(kn.current.timer),kn.current=null;const e=dn.current;dn.current=null,null!==e&&$(t=>t.filter(t=>t.id!==e||t.content))},zn=e=>{Ct.current&&window.clearTimeout(Ct.current.timer);const t={timer:0,relayed:e};return t.timer=window.setTimeout(()=>Rn(t),5e3),Ct.current=t,It(!0),t},Rn=e=>{const t=Ct.current;!t||e&&e!==t||(window.clearTimeout(t.timer),Ct.current=null,It(!1))},Dn=()=>{Ct.current?.relayed&&Rn()},Mn=s(k);Mn.current=k;const Hn=s(C);Hn.current=C;const Vn=s(N);Vn.current=N;const Kn=s(S);Kn.current=S;const Gn=s(T);Gn.current=T;const Xn=s(M);Xn.current=M;const Yn=s(_);Yn.current=_;const Jn=s(re),Qn=s(U);Qn.current=U;const Zn=e=>{Qn.current&&q(e),Qn.current=!1,O(!1),J(void 0,!1),ht.current||lt(null)},er=s(u);er.current=u;const tr=s(new Map),nr=s(h);nr.current=h;const rr=s(d);rr.current=d;const ar=s(null),or=s(!1),sr=s(null),ir=s(0),[cr]=o(nt),lr=s(null),[dr,ur]=o(null),hr=s(new AbortController);l(()=>()=>{hr.current.abort(),hr.current=new AbortController},[]);const pr={maxFileCount:Number.isFinite(m)&&m>0?Math.floor(m):10,maxTotalSize:g>0?g:qn,maxFileSize:void 0!==f&&Number.isFinite(f)&&f>0?f:1/0,accept:v},[mr,gr]=o(0);l(()=>{le(e=>fe(e,se)),he(e=>function(e,t){if(0===e.length)return e;const n=new Set(ge(t)),r=e.filter(e=>n.has(e.key.toLowerCase()));return r.length===e.length?e:r}(e,se))},[se]);const fr=c(e=>{he(t=>{return r=e,(n=t).some(e=>e.agentId===r.agentId)?n:[...n,r];var n,r})},[]),vr=c(e=>{le(t=>{return r=e,(n=t).some(e=>e.conversationId===r.conversationId)?n:[...n,r];var n,r})},[]),wr=({draft:e,files:t,refs:n,mentions:r},{before:a})=>{e&&ie(t=>t?a?`${e}\n${t}`:`${t}\n\n${e}`:e),t.length>0&&me(e=>a?[...t,...e]:[...e,...t]),n.length>0&&le(e=>{const t=n.filter(t=>!e.some(e=>e.conversationId===t.conversationId));return a?[...t,...e]:[...e,...t]}),r.length>0&&he(e=>{const t=r.filter(t=>!e.some(e=>e.agentId===t.agentId));return a?[...t,...e]:[...e,...t]})},br=()=>P||"ag-ui"===n||t?.singleEndpoint||null===t?.steer?null:`${e}${t?.steer??"/chat/messages/steer"}`,yr=()=>ne(e,t,n,"approve"),xr=s(yr);xr.current=yr;const kr=async e=>{const t=jr(e);if(!t)return null;try{const e=await L(t,{headers:{...d??{}}});if(!e.ok)return null;const n=await e.json();return{proposals:He(n?.proposals),turnRunning:"running"===n?.turn}}catch{return null}},Cr=c(()=>{Oe.current=!1,Qt.current+=1,Le(Qt.current)},[]),Nr=()=>{if(null===an.current)return;const e=Fn(Jt.current);if(Cn(),!Or())return void ia("stopped");Cr();const t=window.setTimeout(()=>{kn.current?.timer===t&&(kn.current=null,ia("stopped"))},1e4);kn.current={from:Qt.current,shownUpTo:e,timer:t}},Sr=s(Nr);Sr.current=Nr;const Tr=()=>{null!==nn.current&&window.clearTimeout(nn.current),on.current=!1,nn.current=window.setTimeout(()=>{nn.current=null,Ke.current||Sr.current()},Math.max(0,cn.current-Date.now()))},Ar=()=>{null===an.current||Ke.current||on.current||(on.current=!0,null!==nn.current&&window.clearTimeout(nn.current),nn.current=window.setTimeout(()=>{nn.current=null,Ke.current||Sr.current()},5e3))},Ir=s(Ar);Ir.current=Ar;const Er=()=>{null!==an.current&&!Ke.current&&on.current&&Tr()},zr=s(Er);zr.current=Er;const Rr=()=>P||t?.singleEndpoint||null===t?.upload?null:`${e}${t?.upload??"/chat/upload"}`,Dr=()=>ne(e,t,n,"cancel"),Mr=()=>ne(e,t,n,"skipWait"),_r=ne(e,t,n,"events"),Lr=!!_r,Pr=ne(e,t,n,"pendingApprovals"),jr=e=>Pr?`${Pr}/${encodeURIComponent(e)}/pending-approvals`:null,$r=()=>Lr?{"X-Chat-Client-Id":Zt}:{},Ur=(e,t,n)=>L(e,{method:"POST",headers:{"Content-Type":"application/json",...rr.current??{},...$r()},body:JSON.stringify({conversation_id:t,...n})}),Or=()=>P||t?.singleEndpoint||null===t?.sessions?null:`${e}${t?.sessions??"/chat/sessions"}`,Wr=s(x);Wr.current=x;const qr=c((e,{notify:t=!0,created:n=!1}={})=>{const r=Jn.current!==e;Jn.current=e,ae(e),Z||Bt("local",ee,e),r&&t&&Wr.current?.(e,{created:n})},[Z,ee]),Fr=s(r);Fr.current=r;const Br=s(a);Br.current=a;const Hr=s([]),Vr=s(null),[Kr,Gr]=o(!1);l(()=>{if(!a)for(const e of Hr.current.splice(0))e()},[a]);const Xr=e=>new Promise((t,n)=>{const r=()=>t(Fr.current);if(!Br.current)return r();const a=()=>{Hr.current=Hr.current.filter(e=>e!==r),n(new DOMException("Aborted","AbortError"))};if(e.aborted)return a();e.addEventListener("abort",a,{once:!0}),Hr.current.push(r)}),Yr=async()=>{if(Jn.current)return Jn.current;if(cr.pending)return cr.pending;const e=Or();return e?cr.run(async(t,n)=>{const r=await Xr(n);if(!t())return null;const a=lr.current,o=await L(e,{method:"POST",headers:{"Content-Type":"application/json",...d??{}},body:JSON.stringify(a?{agent_slug:r,workspace_id:a}:{agent_slug:r}),signal:n});if(!o.ok||!t())return null;const s=await o.json();if(!t())return null;const i=s?.conversation_id??null;return i&&(Oe.current=!0,qr(i,{created:!0}),lr.current=null,ur(null)),i}):null},Jr=async(e,t,n)=>{const r=Rr(),a=new FormData;a.append("conversation_id",t),a.append("file",e,e.name);const o=d?Object.fromEntries(Object.entries(d).filter(([e])=>"content-type"!==e.toLowerCase())):void 0,s=await L(r,{method:"POST",headers:o,body:a,signal:n});if(!s.ok)throw new Wn(s.status,await De(s));const i=(await s.json()).file_ids??[];if(0===i.length)throw new Error("No file_id returned");return i[0]},Qr=e=>{if(!e||0===e.length||!Rr())return;const t=Array.from(e),n=hr.current.signal,r=new Map(t.map(e=>[e,_e()]));let a=[],o=[],s=!1;me(e=>{if(({accepted:a,refused:o}=function(e,t,n){const r=[],a=[];let o=e.length,s=n.maxTotalSize-e.reduce((e,t)=>e+t.size,0);for(const e of t){const t=Xt(n.accept,e)?e.size>n.maxFileSize?"file-size":o>=n.maxFileCount?"file-count":e.size>s?"total-size":null:"file-type";t?a.push({file:e,reason:t}):(r.push(e),o+=1,s-=e.size)}return{accepted:r,refused:a}}(e,t,pr)),s=!0,0===a.length)return e;const n=a.map(e=>({name:e.name,type:e.type,size:e.size,rawFile:e,uploadStatus:"pending",fileId:r.get(e)}));return[...e,...n]});const i=()=>{if(n.aborted)return;if(!s)return void setTimeout(i,0);ut(o.map(({file:e,reason:t})=>function(e,t,n,r){switch(n){case"file-type":return I(e,"{name} was not attached: this type of file is not accepted.",{name:t});case"file-size":return I(e,"{name} was not attached: a file may be at most {size}.",{name:t,size:R(r.maxFileSize)});case"file-count":return I(e,"{name} was not attached: a message holds at most {count} files.",{name:t,count:r.maxFileCount});case"total-size":return I(e,"{name} was not attached: the files of a message may add up to at most {size}.",{name:t,size:R(r.maxTotalSize)})}}(p,e.name,t,pr)).join(" ")||null);for(const{file:e,reason:t}of o)B(w,e,t);const e=(e,t)=>me(n=>n.map(n=>n.fileId===e?{...n,uploadStatus:"error",uploadError:t instanceof Wn?t.detail??void 0:void 0}:n));for(const t of a){const a=r.get(t);(async()=>{try{const r=await Yr();if(!r)return void e(a);const o=await Jr(t,r,n);me(e=>e.map(e=>e.fileId===a?{...e,fileId:o,uploadStatus:"done"}:e))}catch(t){if(t instanceof DOMException&&"AbortError"===t.name)return;e(a,t)}})()}};setTimeout(i,0)},Zr=async(e,t,n)=>{const r=xr.current(),a=n??Jn.current;if(!r||!a||"undefined"==typeof document)return;const o=qe.current?.signal,s=async t=>{try{await L(r,{method:"POST",headers:{"Content-Type":"application/json",...rr.current??{},...$r()},body:JSON.stringify({conversation_id:a,page_action:{action_id:e,ok:!1,error:t,url:"",title:"",snapshot:""}})})}catch{}};if(o?.aborted)return s("panel_closed");if(!rt(r,nr.current))return s("page_actions_not_supported");H(e=>e?{...e,status:"acting_on_page"}:{status:"acting_on_page"});try{const n=await gt(t,tr.current,nr.current,document,o);if(o?.aborted)return s("panel_closed");if("snapshot"!==t.type&&await function(e,{quietMs:t=300,maxMs:n=3e3,signal:r}={}){return new Promise(a=>{if(r?.aborted)return a();const o=e.defaultView,s=o?.MutationObserver??globalThis.MutationObserver;let i;const c=()=>{clearTimeout(i),clearTimeout(d),l?.disconnect(),r?.removeEventListener("abort",c),a()},l=s?new s(e=>{e.some(e=>!st(e.target))&&(clearTimeout(i),i=setTimeout(c,t))}):null;l?.observe(e.body??e.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),i=setTimeout(c,t);const d=setTimeout(c,n);r?.addEventListener("abort",c)})}(document,{signal:o}),o?.aborted)return s("panel_closed");let i={text:"",url:"",title:""},c=null;try{const e=function(e,t=2e4){const n=e.defaultView?.location,r=(n?`${n.pathname}${n.search}`:"").slice(0,500),a=kt(e.title).slice(0,80),o=Math.max(0,t-12);let s=!1,i=`# ${a} — ${r}`;i.length>o&&(i=i.slice(0,o),s=!0);const c=[i];let l=i.length;const d=new Map,u=e=>{for(const t of Array.from(e.children)){if(Rt(t))continue;const e=bt(t),n=yt(t);let r=null;if(e){const n=`e${d.size+1}`,a=Et(t,e),i=Tt(t);if(r=`[${n}] ${e} ${St(Nt(t,e))}${i.length?` (${i.join(", ")})`:""}${a?` = ${St(a)}`:""}${zt(t)}`,l+r.length+1>o)return s=!0,!1;d.set(n,t)}else if(n&&(r=`heading ${St(kt(xt(t)))} (level ${n})`,l+r.length+1>o))return s=!0,!1;if(r&&(c.push(r),l+=r.length+1),(!e||wt(t))&&!u(t))return!1}return!0};return e.body&&!s&&u(e.body),s&&c.push(ft),{text:c.join("\n"),url:r,title:a,refs:d}}(document);tr.current=e.refs,i={text:e.text,url:e.url,title:e.title}}catch(e){tr.current=new Map,c=`${e instanceof Error?e.message:String(e)}`.slice(0,500)}await L(r,{method:"POST",headers:{"Content-Type":"application/json",...rr.current??{},...$r()},signal:o,body:JSON.stringify({conversation_id:a,page_action:{action_id:e,ok:n.ok,error:n.error??(null===c?null:`snapshot_failed: ${c}`),url:i.url,title:i.title,snapshot:i.text}})})}catch{}finally{o?.aborted||H(e=>"acting_on_page"===e?.status?{...e,status:"thinking"}:e)}},ea=(e,t)=>{let n=e;const r=[e];let a="",o=!1,s=!1,i=null;const c=new Map,l=new Set,d=()=>{c.clear(),l.clear()};let u=!0;const h=function(e){let t=!1,n="",r=null,a=!1;const o=()=>{null!==r&&cancelAnimationFrame(r),r=null},s=()=>{if(o(),!t&&!n)return;const r=t,a=n;t=!1,n="",e(r,a)},i=()=>{null===r&&("function"==typeof requestAnimationFrame?r=requestAnimationFrame(()=>{r=null,s()}):s())};return{text:()=>{a||(t=!0,i())},thinking:e=>{a||(n+=e,i())},flush:s,close:()=>{a=!0,o(),t=!1,n=""}}}((e,t)=>{if(e){const e=n,t=a;H(e=>({status:"streaming",thinkingContent:e?.thinkingContent})),$(n=>n.map(n=>n.id===e?{...n,content:t}:n))}t&&H(e=>({...e,status:e?.status??"thinking",thinkingContent:(e?.thinkingContent??"")+t}))}),m=()=>{if(!o)return;h.flush(),o=!1,s=!1,a="",d(),n=_e(),r.push(n);const e=n;$(t=>[...t,{id:e,role:"assistant",content:"",timestamp:new Date}]),H({status:"thinking"})};return{ctx:{hasUsedTools:!1,activeNodeId:""},deltas:h,apply:e=>{switch(jt.current+=1,e.action){case"status":return(e=>{m();const t=n;if(e.contextUsage&&ke(e.contextUsage),"thinking_text"===e.status)return void h.thinking(e.thinkingContent??"");h.flush();const r="number"==typeof e.elapsedS?Date.now()-1e3*e.elapsedS:void 0;if((e.resumed||wn.has(e.status))&&(d(),u=!0===e.resumed||"tool_start"===e.status),"mention_answering"===e.status&&J(e.agentName,!0),e.resumed)a="",$(e=>e.map(e=>e.id===t?{...e,content:""}:e)),H({status:"thinking",elapsedS:e.elapsedS,elapsedStartMs:r});else if("stream_retract"===e.status)a="",$(e=>e.map(e=>e.id===t?{...e,content:""}:e)),H(e=>({status:"analyzing",thinkingContent:e?.thinkingContent}));else if("tool_heartbeat"===e.status)H(t=>t?{...t,elapsedS:e.elapsedS,elapsedStartMs:r}:{status:"tool_start",tools:e.tools,elapsedS:e.elapsedS,elapsedStartMs:r});else if("consult_progress"===e.status){const t=e.consult;if(!t||!u)return;const{consultId:n,agentId:r,agentName:a,status:o}=t;if(t.answering)c.delete(n),l.add(n);else if(o&&!vn.has(o))l.delete(n),c.delete(n),c.set(n,{agentId:r,agentName:a,status:o,tools:t.tools});else if(!c.has(n)){if(l.has(n))return;c.set(n,{agentId:r,agentName:a,status:"thinking"})}let s={agentName:a,status:o??"thinking",answering:t.answering};const i=new Set;for(const e of c.values())s=e,i.add(e.agentId);const d={agentName:s.agentName,status:s.status,tools:s.tools,answering:s.answering,count:Math.max(c.size,1),agents:Math.max(i.size,1)};H(e=>{return"wait_start"===e?.status||"consulting"===e?.status&&(t=e.consult,n=d,t&&t.agentName===n.agentName&&t.status===n.status&&t.count===n.count&&t.agents===n.agents&&t.answering===n.answering&&(t.tools??[]).join("\n")===(n.tools??[]).join("\n"))?e:{status:"consulting",consult:d,thinkingContent:e?.thinkingContent,elapsedS:e?.elapsedS,elapsedStartMs:e?.elapsedStartMs};var t,n})}else"wait_start"===e.status?H(t=>({status:"wait_start",thinkingContent:t?.thinkingContent,waitSeconds:e.waitSeconds,waitReason:e.waitReason,waitStartMs:Date.now()})):"wait_continued"===e.status?H(e=>"wait_start"===e?.status?{status:"analyzing",thinkingContent:e.thinkingContent}:e):H(t=>"wait_start"===t?.status&&fn.has(e.status)?t:{status:e.status,tools:e.tools,thinkingContent:t?.thinkingContent,...e.phase?{phase:e.phase}:{},...e.iteration?{iteration:e.iteration}:{},...e.agentName?{agentName:e.agentName}:{}})})(e),"continue";case"stream":return m(),a+=e.content,h.text(),"continue";case"done":return(e=>{h.flush(),o=!0,e.intermediate||(s=!0),Ne(null),Ie(null),na(e,t);const r=n,i=e.content||a,c=new Date;ra(r,e.messageId,t=>xn(t,e,i,c))})(e),t&&!e.intermediate?"end":"continue";case"approval_required":return h.flush(),ar.current=e.conversationId??Jn.current,or.current=!1,Ie(null),Ne(e.proposals),H(e=>e?{...e,status:"awaiting_approval"}:{status:"awaiting_approval"}),"continue";case"error":{m(),h.flush();const t=n;return i="error",$(n=>n.map(n=>n.id===t?{...n,content:e.content||p("Sorry, an error occurred. Please try again.")}:n)),"end"}case"cancelled":{h.flush(),i="cancelled";const e=n;return $(t=>t.map(t=>t.id===e?{...t,stopped:!0}:t)),"end"}case"session_ended":{h.flush(),i="session";const e=n;return $(t=>t.filter(t=>!(t.id===e&&!t.content))),"end"}default:return"continue"}},currentAssistantId:()=>n,openAnswerId:()=>o?null:n,accumulated:()=>a,doneReceived:()=>o,segmentIds:()=>r,ended:()=>i,outcome:()=>"error"===i?"failed":null===i&&s?"answered":"stopped"}},ta=c(()=>ye(null),[]),na=(e,t)=>{e.conversationId&&!t&&qr(e.conversationId,{created:!Jn.current}),e.contextUsage&&ke(e.contextUsage),e.transferAgentId&&e.transferAgentName&&ye({id:e.transferAgentId,name:e.transferAgentName})},ra=(e,t,n)=>{$(r=>t&&r.some(n=>n.id!==e&&n.serverId===t)?r.filter(t=>t.id!==e):r.map(t=>t.id===e?n(t):t))},aa=(e,t,n)=>{const r=$n(t),a=r?.messageId;if(!r||!a)return!1;"done"!==r.action||Qn.current||na(r,n);const o=new Date;return ra(e,a,e=>"done"===r.action?xn(e,r,r.content||e.content,o):{...e,serverId:a,raw:r.raw??e.raw}),!0},oa=(e,t,n,r)=>{let a;try{a=e(t,n)}catch{a=void 0}return B(Hn.current,t,function(e,t){const n={relayed:e};if(!t)return n;const r=$n(t);return r&&Un(r)?n.end="provisional":r?.messageId&&(n.end="stored"),"status"===t.action&&t.resumed&&(n.replayed=!0),n}(r,a)),"session_ended"===a?.action&&B(Vn.current,a.reason),a},sa=e=>{switch(e.action){case"user_message":{const t=e.message,n=Xe.current?.openAnswerId()??dn.current;return $(e=>{if(t.serverId&&e.some(e=>e.serverId===t.serverId))return e;let r=e.length-1;for(;r>=0&&("user"!==e[r].role||e[r].serverId||Sn(e[r])!==t.content);)r-=1;return r>=0&&e.length-r<=3?e.map((e,n)=>n===r?{...e,serverId:t.serverId,raw:t.raw}:e):En(e,t,n)}),!0}case"conversation_title":return Kn.current?.(e.conversationId??Jn.current,e.title),!0;case"approval_resolved":return Ne(null),Ie(null),!0;default:return!1}},ia=e=>{Sa(),Zn(e),H(null),Ne(null),Ie(null),ar.current=null,or.current=!1,sr.current=Jn.current},ca=async a=>{const o=!a,s=a?a.text:se,i=o?se:a?.draft??"",c=o?pe:a?.files??[];if(!s.trim()&&0===c.length)return"dropped";if(Kt(c))return"dropped";const l=o?"composer":a?.source??"host",u=!Qn.current&&(null!==Ct.current||null!==qt.current),h=Qn.current||null!==qt.current,m=!a?.decided&&h&&Xn.current?{text:s,source:l,extras:a?.extras,displayText:a?.displayText}:void 0,g=jn(s,a?.decided?void 0:B(Xn.current,{text:s,source:l,turnRunning:h,fileCount:c.length}),a?.displayText);if(!g)return"dropped";ht.current=!1,lt(null),o&&ut(null);const f=g.extras,v=a?.extras||f?{...a?.extras,...f}:void 0,w=g.text,y=a?.decided?a.displayText?.trim()||w:g.displayText,x=y!==w?y:void 0,k=o?be(e,t,n)?ve(ce,se):[]:a?.refs??[],C=o?D?ue:[]:a?.mentions??[],N=rn(C,w);if(!w&&0===c.length)return"dropped";const S=()=>{o&&(ie(""),le([]),he([]),me([]),hn(de,b,Jn.current,"",[]))};if(Qn.current||u){const e=c.every(e=>"done"===e.uploadStatus);if(!u&&!Vr.current&&!Y.current&&!!br()&&!!Jn.current&&0===k.length&&0===N.length&&0===Object.keys(v??{}).length&&(0===c.length||E&&e)){S();const e=await(async(e,t,n,a=e)=>{const o=br(),s=Jn.current;if(!o||!s)return{result:"failed"};const i=Nn({id:_e(),role:"user",content:a,timestamp:new Date,files:t.length>0?t:void 0},e),c=Xe.current?.openAnswerId()??dn.current;$(e=>En(e,i,c));const l=t.filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId);let u=null;try{const t=await L(o,{method:"POST",headers:{"Content-Type":"application/json",...d??{},...$r()},body:JSON.stringify({conversation_id:s,content:e,agent_slug:r,...l.length>0?{file_ids:l}:{}})});if(t.ok){const e=await t.json().catch(()=>null),n=e&&"object"==typeof e?e:{},r=n.turn_id;return B(Gn.current,s,a),{result:"ok",turnId:"string"==typeof r&&r?r:null,unanswered:!1===n.answered}}if($(e=>e.filter(e=>e.id!==i.id)),409===t.status)return{result:"ended"};u=await De(t)}catch{$(e=>e.filter(e=>e.id!==i.id))}return null!==n&&wr({draft:n,files:t,refs:[],mentions:[]},{before:!0}),{result:"failed",detail:u}})(w,c,o?i:null,y);return"ended"===e.result?(ot(e=>Ln(e,{text:w,draft:i,files:c,refs:[],mentions:[],extras:v,displayText:x,asked:m,onSent:a?.onSent,onNotSent:a?.onNotSent})),"held"):"ok"===e.result?(e.unanswered&&(ht.current=!0,lt(p("This message will be read with your next one."))),a?.onSteered?.(e.turnId,e.unanswered),"steered"):(e.detail&&lt(e.detail),"failed")}return(z||u)&&e?(S(),ot(e=>Ln(e,{text:w,draft:i,files:c,refs:k,mentions:C,extras:v,displayText:x,asked:m,onSent:a?.onSent,onNotSent:a?.onNotSent})),"held"):"dropped"}const T=Nn({id:_e(),role:"user",content:y,timestamp:new Date,files:c.length>0?[...c]:void 0,conversationRefs:k.length>0?k:void 0},w),A=_e();$(e=>[...e,T,{id:A,role:"assistant",content:"",timestamp:new Date}]),S(),Qn.current=!0,O(!0),H({status:"thinking"});const I=cr.generation,R=ea(A,!1);Fe.current=R.deltas,Xe.current=R,Ze.current=!1,Be.current=!0,Ve.current=null,Lt.current=!1;let M=!1,_=!1,j=!1,U=!1,W=!1,q=!1,F=null;const V=()=>{if(!Lr||!Jn.current||!Ve.current||R.ended())return!1;M=!0;const e=R.doneReceived()?_e():R.currentAssistantId();return $(t=>[...t.filter(t=>t.id!==e),{id:e,role:"assistant",content:"",timestamp:new Date}]),dn.current=e,an.current=Ve.current,Ve.current=null,en(_e()),H(e=>"cancelling"===e?.status?e:{status:"reconnecting"}),cn.current=Date.now()+(ln.current?gn:15e3),Tr(),!0},K=new AbortController;qe.current?.abort();const G=new AbortController,X=()=>{q||(q=!0,R.deltas.close(),Fe.current===R.deltas&&(Fe.current=null),Xe.current===R&&(Xe.current=null),Be.current=!1,qe.current===G&&G.abort(),We.current===K&&(We.current=null),cr.generation!==I||M||ia(j?"failed":R.outcome()))};try{let r;We.current=K,qe.current=G,Vr.current=K,Gr(Br.current);try{r=await Xr(K.signal)}finally{Vr.current===K&&(Vr.current=null,Gr(!1))}if(K.signal.aborted)return"dropped";const o=(T.files??[]).filter(e=>"done"===e.uploadStatus&&e.fileId).map(e=>e.fileId),s=!!(Dr()||Mr()||Lr);if(!Jn.current&&(lr.current||s||null!==br())){const e=cr.generation,t=await Yr();if(cr.generation!==e)return"dropped";t||(lr.current=null,ur(null))}const i=function(e,t,n){switch(e){case"legacy":return{question:t,chatId:n.legacyChatId??void 0,streaming:!0};case"ag-ui":return{threadId:n.conversationId??_e(),runId:_e(),messages:[{id:_e(),role:"user",content:t}],tools:[],context:[],state:{},forwardedProps:n.agentSlug?{agentSlug:n.agentSlug}:{}};default:{const e={...Object.fromEntries(Object.entries(n.extras??{}).filter(([e])=>!yn.has(e))),content:t,conversation_id:n.conversationId,agent_slug:n.agentSlug};if(n.supportsToolApproval&&(e.supports_tool_approval=!0),n.referencedConversationIds&&n.referencedConversationIds.length>0&&(e.referenced_conversation_ids=n.referencedConversationIds),n.supportsPageActions&&(e.supports_page_actions=!0),e.supports_artifacts=!0,n.pageContext&&Object.keys(n.pageContext).length>0)try{const t=JSON.stringify(n.pageContext);t&&"{}"!==t&&(e.context=n.pageContext)}catch{}return e}}}(n,w,{legacyChatId:$e,conversationId:Jn.current,agentSlug:r,pageContext:er.current,supportsToolApproval:null!==yr(),referencedConversationIds:k.map(e=>e.conversationId),supportsPageActions:rt(yr(),nr.current),extras:{...On(Mn.current),...v??{}}});o.length>0&&(i.file_ids=o),N.length>0&&(i.mentioned_agent_ids=N);const c=await L(P||t?.singleEndpoint?e:`${e}${t?.messages??"/chat/messages"}`,{method:"POST",headers:{"Content-Type":"application/json",...d??{},...$r()},body:JSON.stringify(i),signal:K.signal});if(!c.ok||!c.body){const e=c.ok?null:await De(c);return j=!0,$(t=>t.map(t=>t.id===A?{...t,content:e??p("Unable to connect. Please check the configuration.")}:t)),"failed"}_=!0,a?.onSent?.(),Jn.current&&B(Gn.current,Jn.current,y);const l=function(e){switch(e){case"legacy":return et;case"ag-ui":return tt;default:return Ye}}(n);if(await Vt(c.body,e=>{const t=oa(l,e,R.ctx,!1);if(!t)return!0;try{return W?cr.generation===I&&(!!sa(t)||!aa(R.currentAssistantId(),t,!1)):(Lt.current||Xe.current!==R||(Lt.current=!0,"resend"===Pt.current&&(Pt.current="off",null!==Ge.current&&Aa(Ge.current))),!Ve.current&&"string"==typeof e.turn_id&&e.turn_id&&(Ve.current=e.turn_id),"folded"===t.action?(t.turnId&&(Ve.current=t.turnId),!0):!!sa(t)||("set_chat_id"===t.action?(Ue(t.chatId),Bt("local",te,t.chatId),!0):"page_action_required"===t.action?(R.deltas.flush(),Zr(t.actionId,t.pageAction,t.conversationId),!0):(("session_ended"===t.action||$n(t))&&(U=!0),"end"!==R.apply(t)||!!Un(t)&&(R.deltas.flush(),W=!0,s&&(F=zn(!1)),_t.current=K,X(),!0))))}catch{return!0}},{idleTimeoutMs:()=>Lr&&Jn.current&&Ve.current?45e3:void 0}),R.deltas.flush(),!M&&!U&&V())return"sent";if(!M&&!R.ended()&&R.accumulated()&&!R.doneReceived()){const e=R.currentAssistantId(),t=R.accumulated();$(n=>n.map(n=>n.id===e?{...n,content:t||p("No response.")}:n))}}catch(e){if(R.deltas.close(),q)return"sent";if(e instanceof DOMException&&"AbortError"===e.name)return _?"sent":"dropped";const t=R.currentAssistantId();if(V())return"sent";_||(j=!0),$(e=>e.map(e=>e.id===t?{...e,content:p("Sorry, an error occurred. Please try again.")}:e))}finally{X(),F&&Rn(F),_t.current===K&&(_t.current=null)}return _?"sent":"failed"},la=()=>{const e=Ke.current;if(!e)return;Ke.current=null,e.renderer.deltas.flush(),e.renderer.deltas.close(),Fe.current===e.renderer.deltas&&(Fe.current=null),Xe.current===e.renderer&&(Xe.current=null);const t=e.renderer.currentAssistantId();$(e=>e.filter(e=>!(e.id===t&&!e.content&&!e.stopped))),ia(e.renderer.outcome())},da=s(la);da.current=la;const ua=()=>{const e=Ke.current;if(!e)return;const t=e.renderer.doneReceived()?null:e.renderer.currentAssistantId();la(),Yt({turnId:e.turnId,shownUpTo:Fn(Jt.current)}),t&&$(e=>e.filter(e=>e.id!==t))},ha=s(ua);ha.current=ua;const pa=e=>{qt.current&&(Yt(null),e&&q(e))},ma=s(pa);ma.current=pa;const ga=()=>{Ut.current&&window.clearTimeout(Ut.current.timer),Ut.current=null},fa=()=>{ga();const e=Ke.current;if(e){const t=Fn(Jt.current);la(),Yt({turnId:e.turnId,shownUpTo:t})}const t=qt.current;if(!t||t.readBack)return;if(!Or())return void pa("stopped");Cr();const n=window.setTimeout(()=>{qt.current===t&&pa("stopped")},1e4);t.readBack={from:Qt.current,timer:n}},va=s(fa);va.current=fa;const wa=()=>{const e=Ke.current,t=qt.current;if(!e&&t&&(t.readBack||Ut.current?.turn===t))return;ga();const n=e??t;if(!n)return;const r=window.setTimeout(()=>{Ut.current=null,(e?Ke.current===e:qt.current===t)&&fa()},5e3);Ut.current={turn:n,timer:r}},ba=s(wa);ba.current=wa;const ya=s(new Set),xa=e=>{let t=Ke.current;const n=oa(Ye,e,t?.renderer.ctx??{hasUsedTools:!1,activeNodeId:""},!0);if(!n)return;if(sa(n))return;if("session_ended"===n.action)return la(),pa("stopped"),void(null===an.current&&null===kn.current||Be.current||(Cn(),ia("stopped")));if(!bn.has(n.action))return;const r="string"==typeof e.turn_id&&e.turn_id?e.turn_id:null;if(!r)return a=String(e.type),void(ya.current.has(a)||(ya.current.add(a),console.warn(`A "${a}" frame of the event stream names no turn and is not read: the events route needs \`turn_id\` on every turn frame (see "Turns that outlive their stream" in the README)`)));var a;const o=vt.current.get(r);if(void 0!==o)return void(aa(o,n,!0)&&(vt.current.delete(r),Dn()));if(Be.current||r===Ve.current)return;if(r===Qe.current)return;const s=Ut.current;if(s)if(ga(),t&&t===s.turn&&r!==t.turnId){const e=t.renderer.doneReceived()?null:t.renderer.currentAssistantId();la(),e&&$(t=>t.filter(t=>t.id!==e)),Cr(),t=null}else t&&t===s.turn&&(Ot.current=t.renderer,Cr());let i=t;if(i&&i.turnId!==r&&(la(),i=null),!i){const t=qt.current,a=t?.turnId===r,o=r===an.current;if(!("cancelled"!==n.action&&"error"!==n.action||a||o))return void(t&&fa());t&&!a&&(pa(),Cr());const s=_e();$(e=>[...e,{id:s,role:"assistant",content:"",timestamp:new Date}]),i={turnId:r,renderer:ea(s,!0)},Ke.current=i,Dn(),Fe.current=i.renderer.deltas,Xe.current=i.renderer,Yt(null);const c=o||a;!0===e.resumed&&c?(Ot.current=i.renderer,Cr()):!o||"cancelled"!==n.action&&"error"!==n.action||Cr(),Cn(),Ze.current=!1,Qn.current=!0,O(!0),H({status:"thinking"})}if("end"===i.renderer.apply(n)){if(Un(n)){const e=vt.current;for(e.set(i.turnId,i.renderer.currentAssistantId());e.size>20;)e.delete(e.keys().next().value);zn(!0)}la()}},ka=s(xa);ka.current=xa;const Ca=()=>{const e=it.current;e&&(Yn.current?.(e.text,"cancelled"),Pn(e.parts)),ot(null)},Na=(e,t,n=!1)=>{const r="string"==typeof e&&e?e:null;lr.current=r,ur(r),Fe.current?.close(),Fe.current=null,We.current?.abort(),We.current=null,qe.current?.abort(),qe.current=null,hr.current.abort(),hr.current=new AbortController,cr.abandon(),Ke.current?.renderer.deltas.close(),Ke.current=null,ga(),Ot.current=null,Yt(null),vt.current.clear(),_t.current?.abort(),_t.current=null,Rn(),Be.current=!1,Ca(),Sa(),Cn(),ht.current=!1,Zn("stopped"),ut(null),$([]),n||(ie(""),le([]),he([]),me([])),H(null),ye(null),ke(null),Ne(null),Ie(null),ze(!1),ar.current=null,or.current=!1,sr.current=null,Oe.current=!1,P?(Ue(null),Bt("local",te,null)):qr(null,{notify:t})},Sa=()=>{null!==Ge.current&&window.clearTimeout(Ge.current),Ge.current=null,Pt.current="off",$t.current=null},Ta=(e=!0)=>{Sa();const t=Xe.current;Xe.current=null;const n=Ke.current,r=n?.turnId??an.current;r&&(Qe.current=r),Cn(),Fe.current?.flush(),Fe.current?.close(),Fe.current=null,We.current?.abort(),We.current=null,qe.current?.abort(),qe.current=null,Ke.current=null,Zn("stopped"),H(null),Ne(null),Ie(null),ze(!1),ar.current=null,or.current=!1,tr.current=new Map;const a=e?t?.currentAssistantId():void 0;$(e=>e.map(e=>e.id===a?{...e,stopped:!0}:e).filter(e=>!("assistant"===e.role&&!e.content&&!e.stopped)))},Aa=e=>{const t=Dr(),n=Jn.current;if(!t||!n)return;const r=Be.current&&!Lt.current;r&&(Pt.current="asked");const a=()=>Ge.current===e;Ur(t,n,r?{awaiting_send:!0}:void 0).then(async t=>{if(t.ok){const n=await t.json().catch(()=>null);if(!a())return;const o=!!n&&"object"==typeof n&&"none"===n.turn;if(r)return void(o?Lt.current?(Pt.current="off",Aa(e)):Pt.current="resend":Pt.current="off");if(!o)return;return Ta(),void Cr()}const n=await De(t);if(!a())return;const o=$t.current;Sa(),Ze.current=!1,H(e=>"cancelling"!==e?.status?e:o&&jt.current===o.frameSeq?o.statusBefore:{...e,status:o?.statusBefore?.status??"thinking"}),o?.approvalsBefore&&Ne(e=>e??o.approvalsBefore),lt(n??p("The response could not be stopped. Try again."))}).catch(()=>{a()&&Ta()})},Ia=Mr(),Ea=re&&A===re?(za=re,_r?`${_r}/${encodeURIComponent(za)}/events?client_id=${encodeURIComponent(Zt)}`:null):null;var za;ln.current=Ea;const Ra=Me(d),Da=s(Ra);Da.current=Ra;const[Ma,_a]=o(null),[La,Pa]=o(0);l(()=>{Ma&&Ma.url===Ea&&Ma.headersKey!==Ra&&(_a(null),Pa(e=>e+1))},[Ma,Ea,Ra]),l(()=>{if(!Ea)return;let e=!1,t=!1,n=0,r=null,a=null,o=null,s=!1,i=!1;const c=async()=>{if(r=null,e||t)return;if("hidden"===document.visibilityState)return void(s&&(i=!0));t=!0,a=new AbortController;let o=!1,l=null;try{const t=Da.current,r=await L(Ea,{headers:{...rr.current??{},"X-Chat-Client-Id":Zt},signal:a.signal});if([401,403,404,405].includes(r.status))return o=!0,401!==r.status&&403!==r.status||e||_a({url:Ea,headersKey:t}),void(e||(va.current(),Sr.current()));if(!r.ok||!r.body)return void(e||[502,503,504].includes(r.status)||Sr.current());s&&ba.current(),Ir.current(),s=!0,l=Date.now(),await Vt(r.body,e=>{n=0;try{ka.current(e)}catch{}},{idleTimeoutMs:45e3})}catch{}finally{if(t=!1,null===l||e||zr.current(),null!==l&&Date.now()-l>=5e3&&(n=0),!e&&!o&&!i){const e=Math.min(3e4,1e3*2**n);n+=1,r=window.setTimeout(()=>{c()},e*(.5+Math.random()/2))}}},l=()=>{o=null,e||"hidden"!==document.visibilityState||(i=!0,null!==r&&window.clearTimeout(r),r=null,a?.abort(),ha.current())},d=()=>{"hidden"!==document.visibilityState?(null!==o&&window.clearTimeout(o),o=null,"visible"===document.visibilityState&&(qt.current&&ba.current(),t||(null!==r&&window.clearTimeout(r),n=0,i&&(i=!1,Cr()),c()))):null===o&&(o=window.setTimeout(l,6e4))};return c(),document.addEventListener("visibilitychange",d),()=>{e=!0,null!==r&&window.clearTimeout(r),null!==o&&window.clearTimeout(o),a?.abort(),document.removeEventListener("visibilitychange",d),da.current(),ma.current()}},[Ea,Zt,La,Cr]);const ja=s([]),[$a,Ua]=o(0),Oa=e=>{ja.current.push(e),Ua(e=>e+1)};l(()=>{for(const e of ja.current.splice(0))Yn.current?.(e,"returned")},[$a]),l(()=>{if(U||Ht)return;if(Ze.current&&(Ze.current=!1,at))return ot(null),Pn(at.parts),at.draft||0!==at.files.length?(Oa(at.text),void wr(at,{before:!0})):void Yn.current?.(at.text,"dropped");if(At||!at)return;ot(null);let e=!1;const t=t=>{e||(e=!0,Yn.current?.(at.text,t))},n=[],r=[];for(const e of at.parts){const{asked:t}=e;if(!t){n.push(e);continue}const a=jn(t.text,B(Xn.current,{text:t.text,source:t.source,turnRunning:!1,held:!0,fileCount:e.files.length}),t.displayText);a?n.push({...e,text:a.text,displayText:a.displayText!==a.text?a.displayText:void 0,extras:t.extras||a.extras?{...t.extras,...a.extras}:void 0,asked:void 0}):r.push(e)}Pn(r);const a=r.filter(e=>e.draft||e.files.length>0);for(const e of a)wr(e,{before:!1});if(0===n.length)return void(a.length>0?Oa(at.text):t("dropped"));const{text:o,draft:s,files:i,refs:c,mentions:l,extras:d,displayText:u}=_n(n);Wa.current({text:o,draft:s,files:i,refs:c,mentions:l,extras:d,displayText:u,decided:!0,onSent:()=>{t("sent");for(const e of n)B(e.onSent)},onNotSent:()=>Pn(n)}).then(e=>{if("held"===e)return;const r="sent"===e||"steered"===e;t(r?"sent":"failed"===e?"failed":"dropped"),r||Pn(n)},()=>{t("failed"),Pn(n)})},[U,Ht,At,at]);const Wa=s(ca);Wa.current=ca,l(()=>{const e=window.setTimeout(()=>{hn(de,b,re,se,ce)},300);return()=>window.clearTimeout(e)},[se,re,ce,b]),l(()=>()=>{Fe.current?.close(),qe.current?.abort(),_t.current?.abort(),Ct.current&&window.clearTimeout(Ct.current.timer),null!==nn.current&&window.clearTimeout(nn.current),kn.current&&window.clearTimeout(kn.current.timer),Ut.current&&window.clearTimeout(Ut.current.timer),Ca()},[]);const qa=s({storageKeyPrefix:b,conversationId:re,inputValue:se,conversationRefs:ce});qa.current={storageKeyPrefix:b,conversationId:re,inputValue:se,conversationRefs:ce},l(()=>{const e=()=>{const{storageKeyPrefix:e,conversationId:t,inputValue:n,conversationRefs:r}=qa.current;hn(de,e,t,n,r)},t=()=>{"hidden"===document.visibilityState&&e()};return window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("pagehide",e),document.removeEventListener("visibilitychange",t),e()}},[]),l(()=>{const e=re;if(!e||U)return;if(sr.current===e)return;jr(e)&&yr()&&(sr.current=e,(async()=>{const t=await kr(e);t?.proposals&&(Jn.current!==e||Qn.current||(ar.current=e,or.current=!0,Ie(null),Ne(t.proposals)))})())},[re,U]),l(()=>{if(!Ce?.length||!or.current)return;const e=ar.current,t=e?jr(e):null;if(!t)return;const n=window.setInterval(()=>{L(t,{headers:{...d??{}}}).catch(()=>{})},6e5);return()=>window.clearInterval(n)},[Ce]),l(()=>{if(!Ee)return;const e=ar.current;if(!e)return void ze(!1);if(Date.now()>=ir.current)return ze(!1),void Cr();let t=!1;const n=window.setTimeout(async()=>{const n=await kr(e);if(!t){if(n)return n.proposals?(or.current=!0,Ie(null),Ne(n.proposals),void ze(!1)):n.turnRunning?void je(e=>e+1):(ze(!1),void Cr());je(e=>e+1)}},5e3);return()=>{t=!0,window.clearTimeout(n)}},[Ee,Pe,Cr]);const Fa=U&&!Kr&&!G&&null!==br()&&null!==re,Ba=at?rn(at.mentions,at.text).length>0?"mentions":at.refs.length>0?"references":G?"agents":null:null;return{messages:j,inputValue:se,setInputValue:ie,isLoading:U,turnRunning:U||Ht,turnEnd:W,agentStatus:Q,attachedFiles:pe,conversationId:re,contextUsage:xe,transferredAgent:we,forgetTransfer:ta,canSteer:Fa,pendingApprovals:Ce,isSubmittingApproval:Se,approvalError:Ae,submitApprovalDecisions:async e=>{const t=yr(),n=ar.current??Jn.current;if(0!==e.length)if(t&&n){Ie(null),Te(!0);try{const r=await L(t,{method:"POST",headers:{"Content-Type":"application/json",...d??{},...$r()},body:JSON.stringify({conversation_id:n,decisions:e.map(e=>({tool_call_id:e.toolCallId,decision:e.verdict,..."reject"===e.verdict&&e.rejectionReason?{rejection_reason:e.rejectionReason}:{}}))})});if(r.ok)return Ne(null),or.current&&!Ke.current?(or.current=!1,ir.current=Date.now()+mn,void ze(!0)):void H(e=>e?{...e,status:"thinking"}:{status:"thinking"});Ie(409===r.status?p("This turn is no longer waiting for a decision."):p("Could not send your decision. Please try again."))}catch{Ie(p("Could not send your decision. Please try again."))}finally{Te(!1)}}else Ie(p("This decision could not be sent. Reload the chat and try again."))},isResumingAfterDecision:Ee,historyReloadNonce:Re,historyLoadedRef:Oe,conversationIdRef:Jn,handleFileAdd:Qr,handlePaste:e=>{const t=tn(e.clipboardData);t.length>0&&(e.preventDefault(),Qr(t))},handleSendMessage:ca,skipWait:Ia?async()=>{const e=Mr(),t=Jn.current;if(e&&t)try{(await Ur(e,t)).ok&&H(e=>"wait_start"===e?.status?{status:"thinking",thinkingContent:e.thinkingContent}:e)}catch{}}:null,readPendingApprovals:Pr?kr:null,heldMessage:at,heldReason:Ba,notice:ct,fileNotice:dt,dismissNotice:pt,dismissFileNotice:mt,composerFocusRequest:mr,cancelHeldMessage:Ca,reloadHistory:Cr,mergeTurnHistory:e=>{const t=Ot.current;if(Ot.current=null,!t||Be.current)return!1;const n=new Set(t.segmentIds()),r=t.currentAssistantId();return $(t=>function(e,t,n,r){const a=e.findIndex(e=>n.has(e.id));if(a<0)return e;const o=e.slice(0,a),s=e.slice(a),i=new Set(o.map(e=>e.serverId).filter(Boolean));let c=-1;t.forEach((e,t)=>{e.serverId&&i.has(e.serverId)&&(c=t)});const l=new Map;for(const e of o)e.serverId||l.set(Tn(e),(l.get(Tn(e))??0)+1);const d=t.slice(c+1).filter(e=>{if(e.serverId&&i.has(e.serverId))return!1;const t=l.get(An(e))??0;return 0===t||(l.set(An(e),t-1),!1)});if(0===d.length)return e;const u=new Set,h=d.map(e=>{const t=s.find(t=>!u.has(t.id)&&!!e.serverId&&t.serverId===e.serverId)??s.find(t=>!u.has(t.id)&&t.id!==r&&!t.serverId&&Tn(t)===An(e));return t?(u.add(t.id),In(t,e)):{...e,id:Je(e.serverId)}});return[...o,...h,...s.filter(e=>!u.has(e.id))]}(t,e,n,r)),!0},settleUnseenEnd:(e,t)=>{const n=kn.current;n&&e>=n.from&&(window.clearTimeout(n.timer),kn.current=null,ia(t?Bn(t,n.shownUpTo):"stopped"));const r=qt.current;!r?.readBack||e<r.readBack.from||pa(t?Bn(t,r.shownUpTo):"stopped")},agentMentions:ue,addAgentMention:fr,handleNewChat:e=>{Na(e,!0),gr(e=>e+1)},adoptRecreatedConversation:e=>{Na(void 0,!1,!0),qr(e)},pendingWorkspaceId:dr,clearPendingWorkspace:e=>{lr.current===e&&(lr.current=null,ur(null))},handleStopGenerating:()=>{const e=qt.current;if(!Qn.current&&e){const t=Dr(),n=Jn.current;return t&&n&&Ur(t,n).catch(()=>{}),Qe.current=e.turnId,Ze.current=!0,ga(),void pa("stopped")}if(!Qn.current)return void Ta(!1);if(Ze.current=!0,Vr.current)return void Ta();const t=Dr(),n=Jn.current,r=null!==an.current&&!Ke.current;if(!t||!n||r)return t&&n&&Ur(t,n).catch(()=>{}),void Ta();if(null!==Ge.current)return;ht.current=!1,lt(null),Ne(null),Ie(null),H(e=>({...e,status:"cancelling"}));const a=window.setTimeout(()=>Ta(),1e4);Ge.current=a,$t.current={statusBefore:F,approvalsBefore:Ce,frameSeq:jt.current},Aa(a)},conversationRefs:ce,addConversationRef:vr,setAttachedFiles:me,setMessages:$,setContextUsage:ke,updateConversationId:qr,handleSwitchConversation:e=>{if(P||e!==Jn.current){if(Na(void 0,!1),!P){qr(e);const t=pn(b,e);de.current=un(b,e,t.text,t.refs),ie(t.text),le(t.refs)}gr(e=>e+1)}}}}function Vn(e){return(Array.isArray(e)?e:Array.isArray(e?.agents)?e.agents:[]).filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.id).map(e=>function(e){const t=e,n={...e};delete n.disableChat,(!0===t.disable_chat||!0===t.disableChat)&&(n.disableChat=!0);return n}(function(e){const t=e.badges;if(void 0===t)return e;const n=Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e&&!!e.trim()).map(e=>e.trim()))]:[],r={...e,badges:n};0===n.length&&delete r.badges;return r}(e)))}function Kn(e,t){if(t)return e.find(e=>e.id===t)??e.find(e=>e.slug===t)}function Gn(e){if(!e||"object"!=typeof e)return null;const t=e,n=t.conversation_id??t.id;if("string"!=typeof n||!n)return null;const r={conversationId:n,title:"string"==typeof t.title?t.title.trim():"",updatedAt:"string"==typeof t.updated_at?t.updated_at:"string"==typeof t.created_at?t.created_at:void 0,messageCount:"number"==typeof t.message_count?t.message_count:void 0,agentName:"string"==typeof t.agent_name&&t.agent_name?t.agent_name:void 0,workspaceId:"string"==typeof t.workspace_id&&t.workspace_id?t.workspace_id:null===t.workspace_id?null:void 0};return"string"==typeof t.last_message_preview&&t.last_message_preview.trim()&&(r.lastMessagePreview=t.last_message_preview.trim()),"string"==typeof t.channel&&t.channel&&(r.channel=t.channel),"string"==typeof t.agent_icon&&t.agent_icon.trim()&&(r.agentIcon=t.agent_icon.trim()),r}function Xn({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const a=sn(),[s,i]=o([]),[l,d]=o(!1),[u,h]=o(!1),p="rest"===n&&!t?.singleEndpoint&&null!==t?.sessions&&null!==t?.history,m=`${e}${t?.history??t?.sessions??"/chat/sessions"}`,g=c(async()=>{if(p){d(!0);try{const e=await a(m,{method:"GET",headers:{...r??{}}});if(404===e.status||405===e.status)return i([]),void h(!1);if(!e.ok)return 401!==e.status&&403!==e.status||i([]),void h(!0);const t=await e.json(),n=Array.isArray(t)?t:Array.isArray(t?.conversations)?t.conversations:[];i(n.map(Gn).filter(e=>null!==e)),h(!1)}catch{h(!0)}finally{d(!1)}}},[p,m,r]),f=c(async e=>{if(!p)return"";try{const t=await a(`${m}/${encodeURIComponent(e)}`,{method:"DELETE",headers:{...r??{}}});return t.ok?(i(t=>t.filter(t=>t.conversationId!==e)),null):await De(t)??""}catch{return""}},[p,m,r]),v=p&&t?.clearAll?`${e}${t.clearAll}`:null,w=c(async()=>{if(!v)return"";try{const e=await a(v,{method:"DELETE",headers:{...r??{}}});return e.ok?(i([]),null):await De(e)??""}catch{return""}},[v,r]),b=c(async(e,t)=>{const n=t.trim();if(!p||!n)return null;const o=s.find(t=>t.conversationId===e)?.title??"",c=()=>i(t=>function(e,t,n,r){return e.map(e=>e.conversationId===t&&e.title===n?{...e,title:r}:e)}(t,e,n,o));i(t=>t.map(t=>t.conversationId===e?{...t,title:n}:t));try{const t=await a(`${m}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({title:n})});return t.ok?null:(c(),await De(t)??"")}catch{return c(),""}},[p,m,r,s]),y=c(async(e,t)=>{if(!p)return"";const n=s.find(t=>t.conversationId===e)?.workspaceId,o=()=>i(r=>function(e,t,n,r){const a=e.findIndex(e=>e.conversationId===t);if(a<0||(e[a].workspaceId??null)!==n)return e;const o=[...e];return o[a]={...e[a],workspaceId:r},o}(r,e,t,n));i(n=>n.map(n=>n.conversationId===e?{...n,workspaceId:t}:n));try{const n=await a(`${m}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...r??{}},body:JSON.stringify({workspace_id:t})});return n.ok?null:(o(),await De(n)??"")}catch{return o(),""}},[p,m,r,s]),x=c((e,t)=>{i(n=>function(e,t,n,r){const a=e.findIndex(e=>e.conversationId===t);return a<0?e:[{...e[a],updatedAt:r.toISOString(),...n.trim()?{lastMessagePreview:n.trim()}:{}},...e.slice(0,a),...e.slice(a+1)]}(n,e,t,new Date))},[]);return{historyEnabled:p,conversations:s,conversationsLoading:l,conversationsFailed:u,refreshConversations:g,deleteConversation:f,renameConversation:b,moveConversation:y,clearConversations:v?w:null,touchConversation:x}}const Yn=400;let Jn=null,Qn=null,Zn=0;function er(){null!==Jn&&(window.clearInterval(Jn),Jn=null),null!==Qn&&(document.title=Qn,Qn=null)}function tr({isLoading:e,agentName:t,t:n,enabled:r=!0,onComplete:a,isViewingChat:o}){const i=s(!1),c=s(0);l(()=>{if(!r||"undefined"==typeof document)return;Zn+=1;const e=()=>{!document.hidden&&document.hasFocus()&&er()};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),Zn=Math.max(0,Zn-1),0===Zn&&er()}},[r]),l(()=>{const s=i.current;if(i.current=e,!e||s){if(!e&&s&&r){if(Date.now()-c.current<4e3)return;const e="undefined"!=typeof document&&document.hidden,r="undefined"!=typeof document&&!document.hasFocus(),s=e||r,i=!o||o();if(!s&&i)return;const l=n("Response ready"),d=t?I(n,"{agent} has finished",{agent:t}):n("Your answer is ready");s&&(function(e){if("undefined"==typeof document)return;null===Qn&&(Qn=document.title),null!==Jn&&window.clearInterval(Jn);let t=!0;document.title=e,Jn=window.setInterval(()=>{t=!t,document.title=t?e:Qn??e},1200)}(l),function(e,t){try{if("undefined"==typeof Notification||"granted"!==Notification.permission)return;new Notification(e,{body:t,tag:"filigran-chat-complete"})}catch{}}(l,d)),a?.(l,d)}}else c.current=Date.now()},[e,r,t,n,a,o])}function nr({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const a=sn(),[s,i]=o(null),[d,u]=o(null),h="rest"===n&&!t?.singleEndpoint,p=void 0===t?.prompts?"/chat/prompts":t.prompts,m=void 0===t?.quota?"/chat/quota":t.quota,g=h&&p?`${e}${p}`:null,f=h&&m?`${e}${m}`:null;l(()=>{if(!g)return void i(null);let e=!1;return a(g,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){const t=Array.isArray(e)?e:Array.isArray(e?.prompts)?e.prompts:[],n=[];for(const e of t){if(!e||"object"!=typeof e)continue;const t=e,r="string"==typeof t.id?t.id:"",a="string"==typeof t.content?t.content:"";r&&a&&n.push({id:r,title:"string"==typeof t.title&&t.title?t.title:r,content:a,description:"string"==typeof t.description?t.description:void 0})}return n}(t);i(n.length>0?n:null)}).catch(()=>{e||i(null)}),()=>{e=!0}},[g,r]);const[v,w]=o(0),b=c(()=>w(e=>e+1),[]);return l(()=>{if(!f)return void u(null);let e=!1;return a(f,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{e||u(function(e){if(!e||"object"!=typeof e)return null;const t=e;return"number"!=typeof t.used?null:{used:t.used,limit:"number"==typeof t.limit?t.limit:null,period:"string"==typeof t.period?t.period:"",..."global"===t.scope||"user"===t.scope?{scope:t.scope}:{}}}(t))}).catch(()=>{e||u(null)}),()=>{e=!0}},[f,r,v]),{prompts:s,quota:d,refreshQuota:b}}function rr({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,agentSlug:a}){const s=sn(),[i,c]=o(null),[d,u]=o(!1),h="rest"===n&&!t?.singleEndpoint,p=void 0===t?.suggestions?"/chat/suggestions":t.suggestions,m=h&&p?`${e}${p}`:null;return l(()=>{if(!m)return void c(null);let e=!1;u(!0);const t=a?`${m}?agent_slug=${encodeURIComponent(a)}`:m;return s(t,{credentials:"include",headers:{...r??{}}}).then(e=>e.ok?e.json():null).then(t=>{if(e)return;const n=null===t?[]:function(e){return(Array.isArray(e)?e:Array.isArray(e?.suggestions)?e.suggestions:[]).map(e=>{if("string"==typeof e)return e.trim();if(e&&"object"==typeof e){const t=e,n=t.prompt??t.label??t.text;if("string"==typeof n)return n.trim()}return""}).filter(e=>e.length>0)}(t);c(n.length>0?n:null)}).catch(()=>{e||c(null)}).finally(()=>{e||u(!1)}),()=>{e=!0}},[m,a,r]),{suggestions:i,loading:d}}function ar(e){const t=s(e);return function(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||"object"!=typeof t||null===e||null===t)return!1;if(Array.isArray(e)!==Array.isArray(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))}(t.current,e)||(t.current=e),t.current}function or(e){const t=s(e);d(()=>{t.current=e});const n=c((...e)=>t.current?.(...e),[]);return e?n:void 0}function sr(e,t){let n="idle",r=!1,a=!1,o=!1;const s=()=>"listening"===n||r,i=()=>{a||s()===o||(o=s(),t.onListeningChange(o))},c=()=>{try{return e.start(),!0}catch{return!1}};return e.onresult=e=>{if("listening"!==n&&"stopping"!==n)return;let r="",a="";for(let t=e.resultIndex;t<e.results.length;t++){const n=e.results[t];n.isFinal?r+=n[0].transcript:a+=n[0].transcript}const o=r.trim();o&&t.onFinal(o),"listening"===n&&t.onInterim(a.trim())},e.onerror=()=>{"listening"===n&&(n="stopping",t.onInterim("")),i()},e.onend=()=>{if(t.onInterim(""),"listening"===n){if(c())return;n="idle"}else r?(r=!1,n=c()?"listening":"idle"):n="idle";i()},{toggle:()=>{a||(s()?(()=>{if(r=!1,"listening"===n){n="stopping",t.onInterim("");try{e.stop()}catch{n="idle"}}i()})():(c()?n="listening":"idle"!==n&&(r=!0),i()))},cancel:()=>{if(!a){if(r=!1,"listening"===n||"stopping"===n){n="discarding",t.onInterim("");try{e.abort()}catch{n="idle"}}i()}},dispose:()=>{if(!a){if(a=!0,e.onresult=null,e.onerror=null,e.onend=null,"idle"!==n)try{e.abort()}catch{}n="idle",r=!1}}}}function ir(){if("undefined"==typeof window)return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}const cr=new Set(["thinking","status","stream","turn_started"]);function lr(e,t){const n="string"==typeof t.turn_id&&""!==t.turn_id?t.turn_id:null;if(!0===t.relayed){if(null===e.turnId||n!==e.turnId)return{kind:"ignore"}}else{if("folded_into_active_turn"===t.type){if(null!==n)e.turnId=n,e.folded=!0;else if(!1===t.folded)return{kind:"failed"};return{kind:"progress"}}null!==n&&null===e.turnId&&(e.turnId=n)}const r=t.type;if("status"!==r||"transfer_start"!==t.status||"string"!=typeof t.agent_id||!t.agent_id||null!==n&&n!==e.turnId||(e.agentId=t.agent_id),"string"==typeof r&&cr.has(r))return{kind:"progress"};if("done"===r){const n=function(e){return"string"==typeof e?e:""}(t.content),r=!0!==t.intermediate,a=function(e){const t=Xe(e.answered_by);return t?.agentId&&t.agentName?.trim()?{agentId:t.agentId,agentName:t.agentName}:null}(t);if(null!==a&&a.agentId!==e.agentId)return n&&e.others.push({...a,failed:!0===t.mention_failed,text:n}),r?{kind:"answer",text:e.segments.join("\n\n"),others:e.others}:{kind:"progress"};if(!r)return n&&(e.segments=e.folded?[n]:[...e.segments,n]),{kind:"progress"};return{kind:"answer",text:(e.folded?[n]:[...e.segments,n]).filter(Boolean).join("\n\n"),others:e.others}}return"cancelled"===r||"error"===r?{kind:"failed"}:{kind:"ignore"}}function dr(e){return e.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}const ur=new Set(["no-speech","aborted"]);function hr(e){const t=e.setTimer??((e,t)=>window.setTimeout(e,t)),n=e.clearTimer??(e=>window.clearTimeout(e)),r=e.recognition;let a="listening",o=!1,s="",i=[],c="",l=null,d=!1,u=0,h=null,p="",m=null,g=null,f=null,v=null,w=!1,b=!1,y=0;const x=()=>e.onChange({phase:a,muted:o,heard:s,lines:i}),k=e=>(null!==e&&n(e),null),C=()=>!o&&("listening"===a||"speaking"===a),N=()=>{if(C()){if(w||null!==v)return;try{r.start(),w=!0}catch{}}else if(w)try{r.stop()}catch{}},S=e=>{a=e,N(),x()},T=()=>{h?.abort(),h=null,p=""},A=()=>{m=k(m),f=k(f),c="",s="",S("listening")},I=()=>{g=k(g),l=null,d=!1},E=()=>{I(),S("error"),f=t(()=>{f=null,"error"===a&&A()},2e3)},z=()=>{g=k(g);const n=l;g=t(()=>{g=null,e.probe().then(e=>{l===n&&n&&("over"===e?E():z())})},12e4)},R=t=>{if(!l||!d)return;const n=lr(l,t);"ignore"!==n.kind&&("answer"===n.kind?((t,n)=>{I();const r=e.present(t),o=function(e){const t=e.text.trim()?[{content:e.text}]:[];for(const n of e.others)n.text.trim()&&t.push({content:n.text,agent:{name:n.agentName,failed:n.failed}});return t}({text:r,others:n.map(t=>({...t,text:e.present(t.text)}))});i=[...i,...o.map(e=>({role:"assistant",...e}))];const l=r.trim()?e.speakable(r):"";if(!l.trim())return void A();const d=new AbortController;h=d,p=l,s="",c="",S("speaking"),e.speak(l,d.signal).catch(()=>{}).then(()=>{h===d&&(h=null,p="","speaking"===a&&A())})})(n.text,n.others):"failed"===n.kind?E():z())},D=()=>{u+=1,I()};return r.continuous=!0,r.interimResults=!0,e.lang&&(r.lang=e.lang),r.onresult=n=>{if(y=0,o||"listening"!==a&&"speaking"!==a)return;let r="",h="";for(let e=n.resultIndex;e<n.results.length;e++){const t=n.results[e];t.isFinal?r+=t[0].transcript:h+=t[0].transcript}if("speaking"===a){if(!function(e,t){const n=dr(e);if(n.length<2)return!1;const r=new Set(dr(t));return n.filter(e=>r.has(e)).length/n.length<.6}(`${r} ${h}`,p))return;T(),c="",a="listening"}r.trim()&&(c=[c,r.trim()].filter(Boolean).join(" ")),s=[c,h.trim()].filter(Boolean).join(" "),m=k(m),c&&(m=t(()=>{m=null,"listening"===a&&!o&&c.trim()&&(t=>{const n=++u;m=k(m),c="",s="",i=[...i,{role:"user",content:t}],l=function(e=null){return{turnId:null,folded:!1,agentId:e,segments:[],others:[]}}(e.addressedAgentId()),d=!1,S("processing"),z();const r=()=>n===u&&null!==l;e.send(t,{onAccepted:()=>{r()&&(d=!0)},onNotSent:()=>{r()&&E()},onSteered:(e,t)=>{r()&&(d=!0,R(e?{type:"folded_into_active_turn",folded:!0,turn_id:e}:{type:"folded_into_active_turn",...t?{folded:!1}:{}}))}}).then(e=>{!r()||"dropped"!==e&&"failed"!==e||E()},()=>{r()&&E()})})(c.trim())},1e3)),x()},r.onerror=e=>{b=!0,ur.has(e?.error??"")||(y+=1)},r.onend=()=>{w=!1;const e=b;if(b=!1,C())return y>=5?(y=0,o=!0,void x()):void(e?v=t(()=>{v=null,N()},300):N())},{start:A,end:()=>{if("ended"!==a){if(D(),T(),m=k(m),f=k(f),v=k(v),a="ended",r.onresult=null,r.onerror=null,r.onend=null,w)try{r.abort()}catch{}w=!1,x()}},frame:(e,t)=>R({...e,relayed:t||!0===e.relayed}),interrupt:()=>{"speaking"===a?(T(),A()):"processing"===a&&(D(),e.stopTurn(),A())},cancel:()=>{"processing"!==a&&"speaking"!==a||(D(),T(),A())},toggleMute:()=>{if("ended"!==a){if(o=!o,y=0,o)m=k(m),c="",s="";else if("speaking"===a)return T(),void A();N(),x()}}}}const pr=()=>null!==ir();function mr(e,t){return new Promise(n=>{const r=URL.createObjectURL(e),a=new Audio(r),o=e=>{a.pause(),URL.revokeObjectURL(r),t.removeEventListener("abort",s),n(e)},s=()=>o(!0);a.onended=()=>o(!0),a.onerror=()=>o(!1),t.addEventListener("abort",s),a.play().catch(()=>o(!1))})}function gr(e,t,n){return"undefined"!=typeof window&&window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance?new Promise(r=>{const a=new SpeechSynthesisUtterance(e);t&&(a.lang=t);const o=()=>{n.removeEventListener("abort",s),r()},s=()=>{window.speechSynthesis.cancel(),o()};a.onend=o,a.onerror=o,n.addEventListener("abort",s),window.speechSynthesis.speak(a)}):Promise.resolve()}const fr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),t("path",{d:"M12 9v4"}),t("path",{d:"M12 17h.01"})]}),vr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m16 3 4 4-4 4"}),t("path",{d:"M20 7H4"}),t("path",{d:"m8 21-4-4 4-4"}),t("path",{d:"M4 17h16"})]}),wr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),br=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 8V4H8"}),t("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),t("path",{d:"M2 14h2"}),t("path",{d:"M20 14h2"}),t("path",{d:"M15 13v2"}),t("path",{d:"M9 13v2"})]}),yr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),t("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),t("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),t("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),t("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),t("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),t("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),t("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),t("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),xr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m9 12 2 2 4-4"})]}),kr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 6 9 17l-5-5"})}),Cr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m6 9 6 6 6-6"})}),Nr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"m9 18 6-6-6-6"})}),Sr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M18 6 6 18"}),t("path",{d:"m6 6 12 12"})]}),Tr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),t("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),Ar=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),t("path",{d:"M3 5V19A9 3 0 0 0 21 19V5"}),t("path",{d:"M3 12A9 3 0 0 0 21 12"})]}),Ir=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),Er=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),t("polyline",{points:"7 10 12 15 17 10"}),t("line",{x1:"12",x2:"12",y1:"15",y2:"3"})]}),zr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 20h9"}),t("path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"})]}),Rr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M10 14 21 3"}),t("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]}),Dr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"})]}),Mr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M11 13H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7"}),t("rect",{width:"12",height:"12",x:"10",y:"10",rx:"2"})]}),_r=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}),Lr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1"}),t("path",{d:"M2 13h10"}),t("path",{d:"m9 16 3-3-3-3"})]}),Pr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 10v6"}),t("path",{d:"M9 13h6"}),t("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})]}),jr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),t("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),t("path",{d:"M3 16h3a2 2 0 0 0 2 2v3"}),t("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"})]}),$r=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),t("path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}),t("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}),t("path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"})]}),Ur=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("line",{x1:"6",x2:"10",y1:"11",y2:"11"}),t("line",{x1:"8",x2:"8",y1:"9",y2:"13"}),t("line",{x1:"15",x2:"15.01",y1:"12",y2:"12"}),t("line",{x1:"18",x2:"18.01",y1:"10",y2:"10"}),t("path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z"})]}),Or=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),t("path",{d:"M2 12h20"})]}),Wr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),t("path",{d:"M3 3v5h5"}),t("path",{d:"M12 7v5l4 2"})]}),qr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),t("circle",{cx:"9",cy:"9",r:"2"}),t("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]}),Fr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"M12 16v-4"}),t("path",{d:"M12 8h.01"})]}),Br=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),t("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),Hr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 3h6v6"}),t("path",{d:"M9 21H3v-6"}),t("path",{d:"M21 3l-7 7"}),t("path",{d:"M3 21l7-7"})]}),Vr=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),Kr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),t("rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"})]}),Gr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M12 19v3"}),t("path",{d:"M19 10v2a7 7 0 0 1-.11 1.23"}),t("path",{d:"M5 10v2a7 7 0 0 0 12 5"}),t("path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33"}),t("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12"}),t("path",{d:"m2 2 20 20"})]}),Xr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}),t("path",{d:"m15 5 4 4"})]}),Yr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272"}),t("path",{d:"M22 2 2 22"}),t("path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473"})]}),Jr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"11",cy:"11",r:"8"}),t("path",{d:"m21 21-4.3-4.3"})]}),Qr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"m22 2-7 20-4-9-9-4Z"}),t("path",{d:"m22 2-11 11"})]}),Zr=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),t("path",{d:"M15 3v18"})]}),ea=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})}),ta=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("rect",{width:"6",height:"6",x:"9",y:"9"})]}),na=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("polyline",{points:"4 17 10 11 4 5"}),t("line",{x1:"12",x2:"20",y1:"19",y2:"19"})]}),ra=({className:n,size:r=24,filled:a=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M17 14V2"}),t("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),aa=({className:n,size:r=24,filled:a=!1})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:a?"currentColor":"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M7 10v12"}),t("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),oa=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M3 6h18"}),t("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),t("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}),t("line",{x1:"10",x2:"10",y1:"11",y2:"17"}),t("line",{x1:"14",x2:"14",y1:"11",y2:"17"})]}),sa=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t("circle",{cx:"9",cy:"7",r:"4"}),t("line",{x1:"19",x2:"19",y1:"8",y2:"14"}),t("line",{x1:"22",x2:"16",y1:"11",y2:"11"})]}),ia="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",ca=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:ia}),t("path",{d:"M16 9a5 5 0 0 1 0 6"}),t("path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"})]}),la=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:ia}),t("path",{d:"m22 9-6 6"}),t("path",{d:"m16 9 6 6"})]}),da=({className:e,size:n=24})=>t("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:e,children:t("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),ua=({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("path",{d:"m15 9-6 6"}),t("path",{d:"m9 9 6 6"})]}),ha=r(void 0),pa=ha.Provider,ma=({icon:e,size:r,fallback:o,imageClassName:s,emojiClassName:i})=>{const c=a(ha),l=e?.trim(),d=function(e){const t=e?.trim();return t?/^(https:\/\/|data:image\/)/i.test(t)?"image":t.length<=8&&!/[\p{L}\p{N}]/u.test(t)?"emoji":null:null}(l);if("image"===d)return t("img",{src:l,alt:"","data-agent-icon":"image",className:s});if("emoji"===d)return t("span",{"data-agent-icon":"emoji",className:i,children:l});const u=l&&c?c(l,{size:r}):null;return null!=u&&!1!==u?t("span",{"data-agent-icon":"named",className:"flex shrink-0 items-center",children:u}):t(n,{children:o})};function ga(e){return Math.max(e.maxRight-e.minLeft,0)}const fa=({title:n,children:r,truncated:a=!1,className:i="inline-flex"})=>{const c=a?"flex min-w-0 max-w-full":i,d=s(null),h=s(null),p=s(null),[m,g]=o(null),[f,v]=o({below:!1,shift:0});if(u(()=>{if(!m||!h.current)return;const{width:e,height:t}=h.current.getBoundingClientRect();v(function(e,t){const n=e.center-t.width/2;let r=0;return n<e.minLeft?r=e.minLeft-n:n+t.width>e.maxRight&&(r=e.maxRight-(n+t.width)),{below:e.top-8-t.height<e.minTop,shift:r}}(m,{width:e,height:t}))},[m,n]),l(()=>()=>w(),[]),l(()=>{if(!m)return;const e=e=>{"Escape"===e.key&&g(null)};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[m]),!n)return"inline-flex"===c?r:t("span",{className:c,children:r});function w(){p.current&&clearTimeout(p.current),p.current=null}const b=()=>{if(w(),!d.current)return;if(a&&!((e=d.current.firstElementChild)&&e.scrollWidth>e.clientWidth))return;var e;const t=z(d.current).getBoundingClientRect();g(function(e,t,n){return{top:e.top,bottom:e.bottom,center:(e.left+e.right)/2,minTop:Math.max(t.top,0),minLeft:Math.max(t.left,0)+4,maxRight:Math.min(t.right,n)-4}}(d.current.getBoundingClientRect(),t,window.innerWidth))},x=()=>{w(),g(null)};return e("span",{ref:d,className:c,onMouseEnter:()=>{w(),p.current=setTimeout(b,300)},onMouseLeave:x,onFocus:e=>{const t=e.target;"function"==typeof t.matches&&t.matches(":focus-visible")&&b()},onBlur:x,children:[r,m&&y(t("span",{ref:h,className:`chat-tooltip pointer-events-none fixed z-[10001] w-max -translate-x-1/2 ${f.below?"":"-translate-y-full"} whitespace-normal break-words`,style:{top:f.below?m.bottom+8:m.top-8,left:m.center+f.shift,maxWidth:Math.min(300,ga(m))},role:"tooltip","data-testid":"filigran-chat-tooltip",children:n}),z(d.current))]})},va={error:"border-[var(--chat-danger)]/25 bg-[var(--chat-danger)]/[0.06] text-[var(--chat-danger)]",warning:"border-[var(--chat-warning)]/25 bg-[var(--chat-warning)]/[0.06] text-[var(--chat-warning)]",info:"border-[var(--chat-accent-40)] bg-[var(--chat-accent-10)] chat-text-secondary-700/80"},wa={error:ua,warning:fr,info:Fr},ba=({tone:n,children:r,onDismiss:a,dismissLabel:o,role:s=("error"===n?"alert":"status"),className:i="",...c})=>{const l=wa[n];return e("div",{role:s,"data-tone":n,"data-testid":c["data-testid"],className:`filigran-chat-notice flex items-start gap-2 chat-radius-md border px-2.5 py-1.5 text-[0.75rem] leading-5 ${va[n]} ${i}`,children:[t(l,{size:14,className:"mt-[3px] shrink-0"}),t("div",{className:"min-w-0 flex-1 break-words",children:r}),a&&t(fa,{title:o??"",children:t("button",{type:"button",onClick:a,"aria-label":o,"data-testid":"filigran-chat-notice-dismiss",className:"-my-0.5 -mr-1.5 flex h-6 w-6 shrink-0 items-center justify-center chat-radius-sm opacity-70 transition-opacity hover:opacity-100 focus-visible:opacity-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-current",children:t(Sr,{size:12})})})]})},ya={delete:e=>({offer:e("Clear all conversations"),ask:e("Delete all conversations?"),confirm:e("Delete all conversations")}),archive:e=>({offer:e("Archive all conversations"),ask:e("Archive all conversations?"),confirm:e("Archive all conversations")})};function xa({onClear:r,action:a="delete",className:s,iconButtonClass:i,t:c}){const[l,d]=o(!1),u=ya[a](c);return t("div",{className:`flex items-center gap-1 ${s}`,children:l?e(n,{children:[t("span",{className:"flex-1 text-[0.7rem] text-red-600 dark:text-red-400",children:u.ask}),t("button",{type:"button",onClick:()=>{d(!1),r()},"aria-label":u.confirm,className:`${i} hover:text-red-500`,children:t(kr,{size:13})}),t("button",{type:"button",onClick:()=>d(!1),"aria-label":c("Cancel"),className:i,children:t(Sr,{size:13})})]}):e("button",{type:"button",onClick:()=>d(!0),className:"flex items-center gap-1.5 chat-radius-sm px-1 py-0.5 text-[0.7rem] chat-text-muted-400/40 hover:text-red-500 dark:hover:text-red-400 transition-colors",children:[t(oa,{size:12}),u.offer]})})}function ka({onRetry:n,className:r,t:a}){return e("div",{role:"alert","data-testid":"filigran-chat-conversation-list-error",className:`flex flex-col items-start gap-2 ${r}`,children:[t("p",{className:"m-0 text-[0.75rem] chat-text-secondary-600/60",children:a("Could not load your conversations.")}),t("button",{type:"button",onClick:n,className:"chat-radius-sm border chat-border-200/10 px-2.5 py-0.5 text-[0.72rem] font-medium chat-text-secondary-700/80 transition-colors hover:chat-surface-hover-100/6",children:a("Retry")})]})}const Ca=({open:e,onClose:n,anchorRef:r,placement:a="bottom-start",width:i=280,children:d})=>{const h=s(null),[p,m]=o({top:0,left:0}),g=c(()=>n(),[n]);if(function(e,t,n=!0){l(()=>{if(!n)return;const r=n=>{e.current&&!e.current.contains(n.target)&&t()};return document.addEventListener("mousedown",r),document.addEventListener("touchstart",r),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("touchstart",r)}},[e,t,n])}(h,g,e),u(()=>{if(!e||!r.current)return;const t=r.current.getBoundingClientRect(),n=h.current?.offsetHeight??0,o=window.innerHeight-t.bottom-8,s=t.top-8,c=n>0&&o<n&&s>o?Math.max(8,t.top-n-4):t.bottom+4,l="bottom-end"===a?t.right-i:t.left,d=Math.max(8,Math.min(l,window.innerWidth-i-8));m({top:c,left:d})},[e,r,a,i,d]),!e)return null;const f=z(r.current);return y(t("div",{ref:h,className:"fixed z-[10000] chat-radius-md overflow-hidden border chat-border-200/10 chat-menu-surface shadow-xl",style:{top:p.top,left:p.left,width:i},children:d}),f)},Na=({size:e=16,className:n=""})=>t("div",{className:`animate-spin rounded-full border-2 border-current/20 border-t-[var(--chat-accent)] ${n}`,style:{width:e,height:e}}),Sa=({icon:e,fallback:n,size:r=16})=>t(ma,{icon:e,size:r,fallback:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:n}),imageClassName:"w-4 h-4 chat-radius-sm object-cover",emojiClassName:"text-sm leading-none"}),Ta=[{mode:"floating",label:e=>e("Floating"),getIcon:e=>t(Mr,{...e})},{mode:"sidebar",label:e=>e("Sidebar"),getIcon:e=>t(Zr,{...e})},{mode:"fullscreen",label:e=>e("Full screen"),getIcon:e=>t($r,{...e})}],Aa="w-full flex items-center gap-2 px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",Ia=({link:r,onDone:a,t:o})=>{const s=e(n,{children:[t(br,{size:18,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:o("Open agent page")})]});return r.href?t("a",{href:r.href,"data-testid":"filigran-chat-agent-page-link",onClick:e=>{a(),!r.onClick||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),r.onClick())},className:Aa,children:s}):t("button",{type:"button",onClick:()=>{a(),r.onClick?.()},className:Aa,children:s})},Ea=({mode:r,agentName:a,agents:c,agentsLoading:d=!1,agentsError:u=!1,selectedAgent:h,transferredFrom:p,agentMenuOpen:m,onAgentMenuToggle:g,onAgentMenuClose:f,onSwitchAgent:v,modeMenuOpen:w,onModeMenuToggle:b,onModeMenuClose:y,onModeChange:x,onNewChat:k,onClose:C,logoIcon:N,agentDashboardUrl:S,historyEnabled:T=!1,historyMenuOpen:A=!1,onHistoryMenuToggle:E,onHistoryMenuClose:z,conversations:R=[],conversationsLoading:D=!1,conversationsFailed:_=!1,onRetryConversations:L,activeConversationId:P=null,onSelectConversation:j,onDeleteConversation:$,onClearAll:U,clearAllAction:O,actions:W,title:q,subtitle:F,agentLink:B,t:H})=>{const V=s(null),K=s(null),G=s(null),[X,Y]=o("");l(()=>{m||Y("")},[m]);const J=i(()=>{const e=X.trim().toLowerCase();return e?c.filter(t=>t.name.toLowerCase().includes(e)||(t.description??"").toLowerCase().includes(e)):c},[c,X]),Q=i(()=>function(e){const t=new Map;for(const n of e){const e=n.group?.trim()||null;t.has(e)||t.set(e,[]),t.get(e).push(n)}const n=t.get(null);return t.delete(null),[...n?[{group:null,agents:n}]:[],...[...t].map(([e,t])=>({group:e,agents:t}))]}(J),[J]),Z=i(()=>Q.flatMap(e=>e.agents),[Q]),[ee,te]=o(0);l(()=>{if(!m)return;const e=Z.findIndex(e=>e.id===h?.id);te(X.trim()||e<0?0:e)},[m,X]);const ne=s(null);l(()=>{ne.current?.querySelector('[data-active="true"]')?.scrollIntoView?.({block:"nearest"})},[ee]);const re=()=>{setTimeout(()=>V.current?.focus(),0)},ae=e=>{v(e),re()},oe=c.length>0,se="sidebar"===r?Zr:"fullscreen"===r?jr:Mr;return e("div",{className:"flex items-center px-3 py-2 min-h-[48px] border-b chat-border-200/10 chat-header-surface "+("floating"===r?"chat-radius-t-md":""),children:[e("div",{className:"min-w-0",children:[e("div",{className:"flex min-w-0 items-center gap-1",children:[t(fa,{title:m?"":H("Switch to another agent"),className:"inline-flex min-w-0 max-w-full",children:e("button",{ref:V,type:"button",onClick:g,"aria-haspopup":"listbox","aria-expanded":m,"data-testid":"filigran-chat-agent-switcher",className:"flex h-8 max-w-full min-w-0 items-center gap-1.5 text-sm font-semibold chat-text-900/100 pl-2 pr-1.5 chat-radius-sm border border-transparent hover:chat-surface-hover-100/10 hover:chat-border-200/10 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-[var(--chat-accent)] transition-colors "+(m?"chat-surface-hover-100/10 chat-border-200/10":""),children:[t("span",{className:"flex shrink-0 items-center text-[var(--chat-accent)] [&>svg]:w-[18px] [&>svg]:h-[18px]",children:t(ma,{icon:h?.icon,size:18,fallback:N,imageClassName:"w-[18px] h-[18px] chat-radius-sm object-cover",emojiClassName:"text-base leading-none"})}),t("span",{className:"min-w-0 truncate",children:a}),t(Cr,{size:16,className:"shrink-0 chat-text-muted-400/40 transition-transform "+(m?"rotate-180":"")})]})}),q&&e(n,{children:[t("span",{"aria-hidden":!0,className:"shrink-0 chat-text-muted-400/30",children:"/"}),t("span",{"data-testid":"filigran-chat-header-title",className:"min-w-0 truncate px-1 text-[0.8125rem] chat-text-secondary-700/70",children:q})]})]}),p&&t("div",{className:"pl-10 pr-2 text-[0.6rem] font-normal chat-text-muted-400/30",children:I(H,"Transferred from {agent}",{agent:p})}),F&&t("div",{"data-testid":"filigran-chat-header-subtitle",className:"truncate pl-10 pr-2 text-[0.6rem] font-normal chat-text-muted-400/40",children:F})]}),e(Ca,{open:m,onClose:f,anchorRef:V,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:H("Switch to another agent")}),0===c.length&&d&&t("div",{className:"px-4 py-2",children:t(Na,{size:16})}),0===c.length&&!d&&u&&e("div",{className:"px-4 py-3 flex items-start gap-2",children:[t(fr,{size:14,className:"mt-0.5 shrink-0 text-amber-500 dark:text-amber-400"}),t("span",{className:"text-[0.75rem] leading-5 chat-text-secondary-600/60",children:H("Could not reach the assistant service. Check the connection and try again.")})]}),0===c.length&&!d&&!u&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:H("Agent switching is not available here")}),oe&&t("div",{className:"px-3 pb-2 pt-1",children:e("div",{className:"relative",children:[t(Jr,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 chat-text-muted-400/40"}),t("input",{autoFocus:!0,type:"text",role:"combobox","aria-expanded":!0,"aria-controls":"filigran-chat-agent-options","aria-activedescendant":Z[ee]?`filigran-chat-agent-option-${Z[ee].id}`:void 0,value:X,onChange:e=>Y(e.target.value),onKeyDown:e=>{if("Escape"===e.key)return e.preventDefault(),f(),void re();if(0!==Z.length)if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();const t="ArrowDown"===e.key?1:-1;te(e=>(e+t+Z.length)%Z.length)}else if("Enter"===e.key){e.preventDefault();const t=Z[Math.min(ee,Z.length-1)];t&&ae(t)}},placeholder:H("Search agents..."),"aria-label":H("Search agents..."),className:"w-full h-7 pl-7 pr-2 chat-radius-sm chat-surface-subtle-100/6 text-[0.75rem] chat-text-900/100 placeholder:chat-text-muted-400/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{ref:ne,id:"filigran-chat-agent-options",role:"listbox","aria-label":H("Switch to another agent"),className:"max-h-[320px] overflow-y-auto filigran-chat-scrollable",children:[c.length>0&&0===J.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:H("No agent matches")}),Q.map(({group:n,agents:r})=>e("div",{role:"group","aria-label":n??void 0,children:[n&&t("span",{className:"block px-4 pt-2 pb-0.5 text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",children:n}),r.map(n=>{const r=Z.indexOf(n),a=n.id===h?.id,o=r===ee;return e("button",{id:`filigran-chat-agent-option-${n.id}`,type:"button",role:"option","aria-selected":a,"data-active":o?"true":void 0,tabIndex:-1,onClick:()=>ae(n),onMouseMove:()=>{o||te(r)},className:`w-full flex items-center gap-2 px-4 py-1.5 text-left transition-colors ${o?"chat-surface-hover-100/10":""} ${a?"bg-[var(--chat-accent)]/10":""}`,children:[t("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t(Sa,{icon:n.icon,fallback:N})}),e("div",{className:"min-w-0",children:[e("div",{className:"flex min-w-0 items-center gap-1",children:[t("span",{className:"text-[0.8125rem] font-medium chat-text-900/100 truncate",children:n.name}),n.badges?.map(e=>t("span",{className:"shrink-0 chat-radius-sm bg-[var(--chat-accent)]/10 px-1 text-[0.6rem] leading-4 text-[var(--chat-accent)]",children:e},e)),n.disableChat&&t("span",{className:"shrink-0 chat-radius-sm bg-amber-500/10 px-1 text-[0.6rem] leading-4 text-amber-600 dark:text-amber-400",children:H("Not recommended for chat")})]}),n.description&&t("div",{className:"text-[0.7rem] chat-text-secondary-500/40 truncate",children:n.description})]}),a&&t(kr,{size:14,className:"ml-auto shrink-0 text-[var(--chat-accent)]"})]},n.id)})]},n??""))]}),t("div",{className:"h-px chat-border-fill-200/10 mx-2"}),e("div",{children:[B&&t(Ia,{link:B,onDone:f,t:H}),S&&e("button",{type:"button",onClick:()=>{f(),window.open(`${S}/agents`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t(Rr,{size:18,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:H("Browse agents")})]}),S&&e("button",{type:"button",onClick:()=>{f(),window.open(`${S}/agents/new`,"_blank")},className:"w-full flex items-center gap-2 px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t(sa,{size:18,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:H("Create agent")})]})]})]}),t("div",{className:"flex-1"}),T&&e(n,{children:[t(fa,{title:H("Conversation history"),children:t("button",{ref:G,type:"button",onClick:E,"aria-label":H("Conversation history"),"aria-haspopup":"menu","aria-expanded":A,className:"w-8 h-8 flex items-center justify-center chat-radius-sm hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(Wr,{size:18})})}),e(Ca,{open:A,onClose:()=>z?.(),anchorRef:G,placement:"bottom-end",width:300,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:H("Conversation history")}),e("div",{className:"max-h-72 overflow-y-auto filigran-chat-scrollable",children:[D&&0===R.length&&t("div",{className:"px-4 py-2",children:t(Na,{size:16})}),!D&&0===R.length&&(_?t(ka,{onRetry:()=>L?.(),className:"px-4 py-3",t:H}):t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:H("No conversations yet")})),R.map(n=>{const r=n.conversationId===P,a=M(n.updatedAt,H);return e("div",{className:"group flex items-center gap-2 px-4 py-1.5 hover:chat-surface-hover-100/10 transition-colors "+(r?"bg-[var(--chat-accent)]/10":""),children:[e("button",{type:"button",onClick:()=>j?.(n.conversationId),className:"flex-1 min-w-0 text-left",children:[t("div",{className:"text-[0.8125rem] font-medium chat-text-900/100 truncate",children:n.title||H("Untitled conversation")}),a&&t("div",{className:"text-[0.7rem] chat-text-muted-500/40 truncate",children:a})]}),$&&t(fa,{title:H("Delete conversation"),className:"inline-flex shrink-0",children:t("button",{type:"button",onClick:()=>$(n.conversationId),"aria-label":H("Delete conversation"),className:"shrink-0 p-1 chat-radius-sm chat-text-muted-400/30 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:text-red-500 dark:hover:text-red-400 transition-all",children:t(oa,{size:14})})})]},n.conversationId)})]}),t("div",{className:"h-px chat-border-fill-200/10 mx-2"}),e("button",{type:"button",onClick:()=>{z?.(),k()},className:"w-full flex items-center gap-2 px-4 py-2 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t(zr,{size:16,className:"chat-text-muted-400/40 shrink-0"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:H("New conversation")})]}),U&&R.length>0&&t(xa,{onClear:()=>{z?.(),U()},action:O,className:"px-3 pb-2",iconButtonClass:"p-1 chat-radius-sm chat-text-muted-400/40 hover:chat-surface-hover-100/10 transition-colors",t:H})]})]}),W,t(fa,{title:H("New chat"),children:t("button",{type:"button",onClick:k,"aria-label":H("New chat"),className:"w-8 h-8 flex items-center justify-center chat-radius-sm hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(zr,{size:18})})}),"inline"!==r&&x&&e(n,{children:[t(fa,{title:H("Switch view"),children:t("button",{ref:K,type:"button","aria-label":H("Switch view"),onClick:b,className:"w-8 h-8 flex items-center justify-center chat-radius-sm hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(se,{size:18})})}),e(Ca,{open:w,onClose:y,anchorRef:K,placement:"bottom-end",width:180,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:H("Switch to")}),t("div",{className:"pb-1",children:Ta.map(n=>e("button",{type:"button",onClick:()=>{x(n.mode),y()},className:"w-full flex items-center gap-3 px-4 py-1 text-left hover:chat-surface-hover-100/10 transition-colors "+(r===n.mode?"bg-[var(--chat-accent)]/10":""),children:[n.getIcon({size:18,className:"chat-text-muted-400/40"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/70",children:n.label(H)})]},n.mode))})]})]}),"inline"!==r&&C&&t(n,{children:t(fa,{title:H("Close"),children:t("button",{type:"button","aria-label":H("Close"),onClick:C,className:"w-8 h-8 flex items-center justify-center chat-radius-sm hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(Sr,{size:18})})})})]})};function za({url:e,query:t,exclude:n,requestHeaders:r}){const a=sn(),[s,i]=o(ye);return l(()=>{if(!e||null===t)return void i(ye);let o=!0;const s=new AbortController,c=window.setTimeout(async()=>{try{const c=await a(function(e,t,n){const r=new URLSearchParams({limit:String(8)});return t&&r.set("q",t),n&&r.set("exclude",n),`${e}${e.includes("?")?"&":"?"}${r.toString()}`}(e,t,n),{credentials:"include",headers:{...r??{}},signal:s.signal}),l=c.ok?await c.json():null;if(!o)return;i(c.ok?{query:t,items:we(l),failed:!1}:{query:t,items:[],failed:!0})}catch{o&&i({query:t,items:[],failed:!0})}},150);return()=>{o=!1,window.clearTimeout(c),s.abort()}},[e,t,n,r]),s}function Ra({url:e,requestHeaders:t,conversationId:n,text:r,onTextChange:a,textareaRef:d,refs:p,onPick:m,agentMentions:g}){const f=null!==e||!!g,[v,w]=o(null),[b,y]=o(null),[x,k]=o(0),C=s(null),N=h(),S=c(e=>`${N}-option-${e}`,[N]),T=c(()=>{const e=d.current,t=f&&e&&document.activeElement===e&&e.selectionStart===e.selectionEnd?function(e){const t=/@([\w-]*)$/.exec(e);return!t||pe(e[t.index-1])?null:{anchor:t.index,query:t[1]}}(e.value.slice(0,e.selectionStart)):null;w(e=>{return(n=e)===(r=t)||n&&r&&n.anchor===r.anchor&&n.query===r.query?e:t;var n,r})},[f,d]),A=c(()=>w(null),[]);u(()=>{const e=C.current;if(null===e)return;C.current=null;const t=d.current;t&&(t.focus(),t.setSelectionRange(e,e))},[r,d]),l(()=>{T()},[r,T]),l(()=>{v||y(null)},[v]);const I=za({url:e,query:v?.query??null,exclude:n,requestHeaders:t}),[E,z]=o([]);l(()=>{z([])},[n]),l(()=>{z(e=>function(e,t,n){if(null===t.query||t.failed)return e;const r=t.query,a=new Set(t.items.map(e=>e.id)),o=t.items.length<8,s=r.toLowerCase(),i=o?e.filter(e=>e.id===n||a.has(e.id)||!e.title.toLowerCase().includes(s)):e;return ke(i.length===e.length?e:i,t.items)}(e,I,n))},[I,n]);const R=i(()=>ke(p.map(Ce),E),[p,E]);l(()=>{k(0)},[I]);const D=function(e){const{trigger:t,dismissed:n,search:r,referenced:a,exclude:o,known:s=[]}=e;if(!t||n)return{kind:"closed"};if(a>=5)return{kind:"full"};if(r.failed)return{kind:"closed"};const i=t.query?s.filter(e=>xe(t.query,e)&&!r.items.some(t=>t.id===e.id)):[],c=[...r.items,...i].slice(0,8),l=o?c.filter(e=>e.id!==o):c;return l.length>0?{kind:"results",items:l}:t.query&&r.query===t.query?{kind:"empty"}:{kind:"closed"}}({trigger:v,dismissed:null!==v&&v.anchor===b,search:I,referenced:ve(p,r).length,exclude:n,known:R}),M=null!==v&&v.anchor===b,_=[...i(()=>g&&v&&!M?function(e,t){const n=[];for(const r of e){const e=nn(r);if(e&&xe(t,{key:e,title:r.name})&&(n.push({agentId:r.id,name:r.name,key:e}),n.length>=5))break}return n}(g.agents,v.query):[],[g,v,M]).map(e=>({type:"agent",mention:e})),...null!==e&&"results"===D.kind?D.items.map(e=>({type:"conversation",candidate:e})):[]],L=Math.min(x,Math.max(_.length-1,0)),P=e=>{if(!v)return;const t="agent"===e.type?e.mention.key:e.candidate.key,n=function(e,t,n){const r=e.slice(0,t.anchor),a=e.slice(t.anchor+1+t.query.length),o=`@${n}`;return{text:`${r}${o}${/^\s/.test(a)?"":" "}${a}`,caret:r.length+o.length+1}}(r,v,t);"agent"===e.type?g?.onPick(e.mention):m({conversationId:e.candidate.id,title:e.candidate.title,key:t,isOwn:e.candidate.isOwn}),C.current=n.caret,a(n.text),w(null)},j=f?{"aria-autocomplete":"list","aria-controls":_.length>0?N:void 0,"aria-activedescendant":_.length>0?S(L):void 0}:{};return{view:null===e?{kind:"closed"}:D,items:_,activeIndex:L,setActiveIndex:k,listboxId:N,optionId:S,sync:T,close:A,pick:P,onKeyDown:e=>{if("closed"===D.kind&&0===_.length||!v)return!1;if("Escape"===e.key)return e.preventDefault(),y(v.anchor),!0;if(0===_.length)return!1;if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();const t="ArrowDown"===e.key?1:-1;return k((L+t+_.length)%_.length),!0}return!("Enter"!==e.key&&"Tab"!==e.key||e.shiftKey)&&(e.preventDefault(),P(_[L]),!0)},textareaAria:j}}const Da=e=>e.nativeEvent.isComposing||229===e.keyCode,Ma=/^[ \t\u00a0]*$/;function _a(e){return e.replace(/\r\n?/g,"\n").replace(/^(?:[ \t\u00a0]*\n)+/,"").replace(/(?:\n[ \t\u00a0]*)+$/,"")}function La(e){const t=e.target;if(t?.closest?.('input, textarea, [contenteditable="true"]'))return!1;const n=e.currentTarget?.ownerDocument,r=n?.getSelection();if(!n||!r||r.isCollapsed||0===r.rangeCount||!e.clipboardData)return!1;const a=function(e){const t=[];for(const n of _a(e).split("\n")){const e=Ma.test(n);e&&""===t[t.length-1]||t.push(e?"":n)}return t.join("\n")}(r.toString());if(!a)return!1;const o=n.createDocumentFragment();for(let e=0;e<r.rangeCount;e+=1)o.appendChild(r.getRangeAt(e).cloneContents());return e.preventDefault(),e.clipboardData.setData("text/plain",a),e.clipboardData.setData("text/html",function(e){e.querySelectorAll('button, time, .sr-only, .select-none, [aria-hidden="true"]').forEach(e=>e.remove());const t=(e.ownerDocument??document).createElement("div");return t.appendChild(e),t.innerHTML}(o)),!0}const Pa=14,ja=2*Math.PI*6,$a=[{field:"system",label:e=>e("System prompt"),color:"#9ca3af"},{field:"tools",label:e=>e("Tool definitions"),color:"#a78bfa"},{field:"dynamicTools",label:e=>e("MCP & dynamic tools"),color:"#f0abfc"},{field:"summary",label:e=>e("Summarized conversation"),color:"#fb7185"},{field:"toolResults",label:e=>e("Tool results"),color:"#34d399"},{field:"conversation",label:e=>e("Conversation"),color:"#a1a1aa"}],Ua=({usage:r,t:a})=>{const{used:i,limit:c,breakdown:l}=r,d=s(null),[u,h]=o(!1),p=Math.min(Math.max(i/c,0),1),m=p>=.95,g=p>=.8,f=m?"text-red-500":g?"text-amber-500":"text-[var(--chat-accent)]",v=m?"text-red-500 dark:text-red-400":g?"text-amber-600 dark:text-amber-400":"chat-text-muted-400/30",w=Math.round(100*p),b=`${D(i)}/${D(c)}`,y=a(m?"Context full — older turns are being dropped":g?"Context nearly full — older turns are being summarized":"Context used"),x=I(a,"{counts} tokens",{counts:b}),k=`${y} · ${x}`,C=l?$a.filter(e=>(l[e.field]??0)>0):[],N=C.length>0,S=e("span",{className:"flex items-center gap-1.5",children:[e("svg",{width:Pa,height:Pa,viewBox:"0 0 14 14",className:f,"aria-hidden":"true",children:[t("circle",{cx:7,cy:7,r:6,fill:"none",strokeWidth:2,className:"stroke-gray-200 dark:stroke-white/15"}),t("circle",{cx:7,cy:7,r:6,fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeDasharray:ja,strokeDashoffset:ja*(1-p),transform:"rotate(-90 7 7)",className:"transition-[stroke-dashoffset] duration-500"})]}),e("span",{className:`text-[0.68rem] tabular-nums ${v}`,children:[w,"%"]})]});return N?e(n,{children:[t(fa,{title:u?"":I(a,"{summary} — click for details",{summary:k}),children:t("button",{ref:d,type:"button",onClick:()=>h(e=>!e),"aria-label":`${k} (${w}%)`,"aria-haspopup":"dialog","aria-expanded":u,className:"flex items-center chat-radius-sm px-1 -mx-1 py-0.5 transition-colors hover:chat-surface-hover-100/10",children:S})}),e(Ca,{open:u,onClose:()=>h(!1),anchorRef:d,placement:"bottom-end",width:296,children:[e("div",{className:"px-3.5 pt-3 pb-1 flex items-baseline justify-between gap-3",children:[t("span",{className:`text-[0.8125rem] tabular-nums ${v}`,children:I(a,"{percent}% full",{percent:w})}),e("span",{className:"text-[0.7rem] tabular-nums chat-text-muted-400/40 shrink-0",children:["~",x]})]}),t("div",{className:"px-3.5 pb-2.5 pt-1.5",children:t("span",{className:"flex h-1.5 w-full gap-px rounded-full chat-border-fill-200/10 overflow-hidden",children:C.map(e=>t("span",{className:"h-full first:rounded-l-full",style:{width:(l?.[e.field]??0)/Math.max(i,1)*Math.min(i/c,1)*100+"%",backgroundColor:e.color}},e.field))})}),t("div",{className:"px-3.5 pb-1",children:C.map(n=>e("div",{className:"flex items-center gap-2 py-[3px]",children:[t("span",{className:"h-2 w-2 shrink-0 chat-radius-sm",style:{backgroundColor:n.color},"aria-hidden":"true"}),t("span",{className:"text-[0.75rem] chat-text-secondary-700/70 truncate",children:n.label(a)}),t("span",{className:"ml-auto text-[0.7rem] tabular-nums chat-text-muted-500/40 shrink-0",children:D(l?.[n.field]??0)})]},n.field))}),g&&t("p",{className:`px-3.5 pt-1 pb-3 text-[0.68rem] leading-snug ${v}`,children:y})]})]}):t(fa,{title:k,children:t("span",{className:"flex items-center",role:"img","aria-label":`${k} (${w}%)`,children:S})})},Oa=({view:n,items:r,activeIndex:a,listboxId:o,optionId:i,onHover:c,onPick:l,t:d})=>{const h=s(null);if(u(()=>{h.current?.querySelector('[aria-selected="true"]')?.scrollIntoView?.({block:"nearest"})},[a,n.kind]),"closed"===n.kind&&0===r.length)return null;const p=r.some(e=>"agent"===e.type),m=d(p?"Mention an agent":"Reference a conversation");return e("div",{className:"absolute left-0 right-0 bottom-full mb-1.5 z-20 chat-radius-md overflow-hidden border chat-border-200/10 chat-menu-surface shadow-xl",children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:m}),r.length>0&&t("div",{ref:h,id:o,role:"listbox","aria-label":m,className:"max-h-[240px] overflow-y-auto pb-1 filigran-chat-scrollable",children:r.map((n,o)=>{const s=o===a,u="conversation"===n.type&&p&&"agent"===r[o-1]?.type;return e("div",{children:[u&&t("span",{className:"block px-4 pt-2 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:d("Reference a conversation")}),e("div",{id:i(o),role:"option","aria-selected":s,onMouseDown:e=>{e.preventDefault(),l(n)},onMouseMove:()=>{s||c(o)},className:"flex items-center gap-2.5 px-4 py-1.5 cursor-pointer transition-colors "+(s?"chat-surface-subtle-100/10":""),children:[t("span",{className:"shrink-0 text-[var(--chat-accent)]",children:"agent"===n.type?t(br,{size:14}):t(Vr,{size:14})}),"agent"===n.type?e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"text-[0.8125rem] chat-text-900/100 truncate",children:n.mention.name}),e("span",{className:"text-[0.7rem] chat-text-muted-500/40 truncate",children:["@",n.mention.key]})]}):e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"text-[0.8125rem] chat-text-900/100 truncate",children:n.candidate.title||d("Untitled conversation")}),e("span",{className:"text-[0.7rem] chat-text-muted-500/40 truncate",children:["@",n.candidate.key,!n.candidate.isOwn&&` · ${d("Shared with you")}`]})]})]})]},"agent"===n.type?`agent-${n.mention.agentId}`:n.candidate.id)})}),"empty"===n.kind&&0===r.length&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] chat-text-muted-400/40",children:d("No conversation matches")}),"full"===n.kind&&t("div",{role:"status",className:"px-4 pt-1 pb-3 text-[0.75rem] chat-text-muted-400/40",children:I(d,"A message references at most {count} conversations",{count:5})})]})},Wa=({prompts:r,onPick:a,t:i})=>{const c=s(null),[l,d]=o(!1),[u,h]=o(""),p=()=>{d(!1),h("")},m=u.trim().toLowerCase(),g=m?r.filter(e=>e.title.toLowerCase().includes(m)||(e.description??"").toLowerCase().includes(m)):r;return e(n,{children:[t(fa,{title:i("Insert prompt template"),children:t("button",{ref:c,type:"button",onClick:()=>l?p():d(!0),"aria-label":i("Insert prompt template"),"aria-haspopup":"menu","aria-expanded":l,className:"w-8 h-8 flex items-center justify-center shrink-0 chat-radius-sm transition-colors "+(l?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10":"chat-text-muted-400/30 hover:chat-surface-hover-100/10"),children:t(ea,{size:18})})}),e(Ca,{open:l,onClose:p,anchorRef:c,width:280,children:[t("span",{className:"block px-4 pt-3 pb-1 text-[0.68rem] tracking-[1px] uppercase chat-text-muted-400/40",children:i("Insert prompt template")}),r.length>5&&t("div",{className:"px-3 pb-2 pt-1",children:t("input",{autoFocus:!0,type:"text",value:u,onChange:e=>h(e.target.value),onKeyDown:e=>{"Escape"!==e.key||Da(e)||p()},placeholder:i("Search prompts..."),"aria-label":i("Search prompts..."),className:"w-full h-7 px-2 chat-radius-sm chat-surface-subtle-100/6 text-[0.75rem] chat-text-900/100 placeholder:chat-text-muted-400/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})}),e("div",{className:"max-h-[240px] overflow-y-auto filigran-chat-scrollable",children:[0===g.length&&t("div",{className:"px-4 py-3 text-[0.75rem] chat-text-muted-400/40",children:i("No prompt matches")}),g.map(n=>e("button",{type:"button",onClick:()=>{a(n.content),p()},className:"w-full px-4 py-1.5 text-left hover:chat-surface-hover-100/10 transition-colors",children:[t("div",{className:"text-[0.8125rem] chat-text-900/100 truncate",children:n.title}),n.description&&t("div",{className:"text-[0.7rem] chat-text-secondary-500/40 truncate",children:n.description})]},n.id))]})]})]})},qa=({quota:n,t:r})=>{const{used:a,limit:o}=n,s=function(e,t){switch(e){case"daily":return t("today");case"monthly":return t("this month");case"yearly":return t("this year");default:return e}}(n.period,r),i=e=>"global"===n.scope?I(r,"{quota} (shared across all users)",{quota:e}):e;if(null===o){const e=i(s?I(r,"Usage · {period}",{period:s}):r("Usage"));return t(fa,{title:e,children:t("span",{className:"text-[0.68rem] tabular-nums chat-text-muted-400/30",role:"img","aria-label":`${e} ${D(a)}`,children:D(a)})})}const c=o>0?Math.min(a/o,1):1,l=!(o>0)||a>=o,d=c>=.75,u=l?"bg-red-500":d?"bg-amber-500":"bg-[var(--chat-accent)]/60",h=l?"text-red-500 dark:text-red-400":d?"text-amber-600 dark:text-amber-400":"chat-text-muted-400/30",p=`${D(a)}/${D(o)}`,m=r(l?"Quota reached":"Quota"),g=i(s?`${m} · ${s}`:m);return t(fa,{title:g,children:e("span",{className:"flex items-center gap-1.5",role:"img","aria-label":`${g} ${p}`,children:[t("span",{className:"h-1 w-10 rounded-full chat-border-fill-200/10 overflow-hidden",children:t("span",{className:`block h-full rounded-full transition-[width] duration-300 ${u}`,style:{width:100*c+"%"}})}),t("span",{className:`text-[0.68rem] tabular-nums ${h}`,children:p})]})})};const Fa=[],Ba=({header:r,steerAttachments:a=!1,canHold:d=!1,heldMessage:h,heldReason:p,notice:m,fileNotice:g,onDismissNotice:f,onDismissFileNotice:v,agentNotForChat:w=!1,onCancelHeld:b,inputValue:y,onInputChange:x,onSend:k,onStop:C,isLoading:N,canSteer:S=!1,attachedFiles:T=[],onFileAdd:A,onFileRemove:I,onPaste:E,t:z,mode:R,separatorColor:D,prompts:M,quota:_,contextUsage:L,composerToolbar:P,conversationReferences:j,agentMentions:$,accept:U,placeholder:O,focusRequest:W})=>{const q=s(null),F=s(null),B=$?.agents,H=$?.onPick,V=i(()=>B&&H?{agents:B,onPick:H}:void 0,[B,H]),K=Ra({url:j?.url??null,requestHeaders:j?.requestHeaders,conversationId:j?.conversationId,text:y,onTextChange:x,textareaRef:F,refs:j?.refs??Fa,onPick:e=>j?.onPick(e),agentMentions:V}),G=()=>{const e=F.current;e&&function(e){const t=document.activeElement;if(!t||t===document.body||t===e)return!0;const n=e.closest(".filigran-chatbot");return!(!n?.contains(t)||t.closest('[role="dialog"], [role="alertdialog"], dialog'))&&!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t.isContentEditable)}(e)&&e.focus()},X=s(W);l(()=>{W!==X.current&&(X.current=W,G())});const Y=s(!1),J=function(e){const[t,n]=o(!1),[r,a]=o(""),i=s(null),d=s(e);d.current=e;const u=null!==ir();return l(()=>{const e=ir();if(!e)return;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang="undefined"!=typeof navigator&&navigator.language||"en-US";const r=sr(t,{onFinal:e=>d.current(e),onInterim:a,onListeningChange:n});return i.current=r,()=>{i.current=null,r.dispose(),n(!1),a("")}},[]),{supported:u,listening:t,interim:r,toggle:c(()=>i.current?.toggle(),[]),cancel:c(()=>i.current?.cancel(),[])}}(e=>{Y.current=!0,x(y.trim()?`${y.trimEnd()} ${e}`:e)});u(()=>{const e=F.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`,Y.current&&(Y.current=!1,e.scrollTop=e.scrollHeight))},[y]);const Q=Boolean(A&&I&&E),Z=T.length>0,ee=y.trim()||Z,te=T.some(e=>"pending"===e.uploadStatus),ne=Kt(T),re=ee&&!te&&!ne,ae=$?rn($.mentions,y):[],oe=Boolean(j)&&ve(j?.refs??Fa,y).length>0||ae.length>0,se=w||ae.some(e=>$?.agents.find(t=>t.id===e)?.disableChat),ie=N&&S&&!oe&&(!Z||a),ce=ie&&!te&&!ne&&(Z||Boolean(y.trim())),le=N&&d&&!ce&&!h&&Boolean(re),de=()=>{(N?ce||le:re)&&(J.cancel(),k(),G())},ue=le?z("Enter to send when the answer ends · Esc to stop"):ne?z("A file failed to upload: remove it to send the message"):ie?z("Enter to send now · Esc to stop"):N&&Z?z("Attachments wait for the current response"):N&&oe?z("This message waits for the current response"):null,he="text-center text-[0.65rem] chat-text-muted-400/30 opacity-70 mt-1.5 min-h-[1lh] truncate",pe=z(te?"Files uploading...":"Enter to send · Shift+Enter for new line");return e("div",{className:"px-4 py-3 border-t chat-border-200/10 "+("floating"===R?"chat-radius-b-md":""),style:D?{borderTopColor:D,borderTopWidth:1}:void 0,"data-testid":"filigran-chat-composer",children:[r&&t("div",{className:"mb-2",children:r}),m&&t(ba,{tone:"warning",role:"alert","data-testid":"filigran-chat-composer-notice",className:"mb-2",onDismiss:f,dismissLabel:z("Close"),children:m}),g&&t(ba,{tone:"warning",role:"alert","data-testid":"filigran-chat-file-notice",className:"mb-2",onDismiss:v,dismissLabel:z("Close"),children:g}),se&&t(ba,{tone:"warning","data-testid":"filigran-chat-agent-not-for-chat",className:"mb-2",children:z("This agent is designed for assignments, not direct chat. It may not respond well to conversational interactions.")}),h&&e("div",{className:"mb-2 flex items-center gap-2 chat-radius-md border border-dashed border-[var(--chat-accent-40)] px-2.5 py-1.5 text-[0.75rem]",children:[t("span",{className:"shrink-0 chat-text-secondary-500/50",children:z("Sends when the answer ends:")}),t("span",{className:"min-w-0 flex-1 truncate chat-text-800/80",children:h.displayText??(h.text||z("Attached files"))}),b&&t("button",{type:"button",onClick:b,className:"shrink-0 chat-text-muted-400/40 hover:text-[var(--chat-danger)]",children:z("Cancel")})]}),h&&p&&t(ba,{tone:"info","data-testid":"filigran-chat-held-reason",className:"mb-2",children:z("mentions"===p?"The agents you mentioned are asked as soon as the current answer ends.":"references"===p?"The conversations you referenced are read with your message once the current answer ends.":"Several agents are answering: your message is sent once they are done.")}),Z&&t("div",{className:"flex gap-1.5 flex-wrap mb-2",children:T.map((n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[0.7rem] "+("error"===n.uploadStatus?"border-[var(--chat-danger)]/25 bg-[var(--chat-danger)]/[0.06] text-[var(--chat-danger)]":"pending"===n.uploadStatus?"chat-border-200/10 chat-text-muted-400/40":"chat-border-200/10 chat-text-secondary-600/60"),children:["pending"===n.uploadStatus?t("span",{className:"w-3.5 h-3.5 border border-current/30 border-t-current rounded-full animate-spin"}):t(Dr,{size:14}),n.name,"error"===n.uploadStatus&&e("span",{"data-testid":"filigran-chat-upload-error",className:"inline-flex min-w-0 items-center gap-1",children:[t(ua,{size:12,className:"shrink-0"}),t(fa,{title:n.uploadError??z("Upload failed"),className:"inline-flex min-w-0",children:t("span",{className:"max-w-[16rem] truncate",children:n.uploadError??z("Upload failed")})})]}),t("button",{type:"button",onClick:()=>I?.(r),className:"ml-0.5 chat-text-muted-400/30 hover:chat-text-secondary-600/60",children:"×"})]},r))}),e("div",{"data-testid":"filigran-chat-composer-box","data-working":N?"":void 0,className:`filigran-chat-composer-box relative flex flex-col border chat-composer-surface px-2 pt-1 pb-1.5 transition-colors ${J.listening?"border-[var(--chat-danger)]/50":"chat-border-200/10"} ${N?"filigran-chat-active-border":""}`,children:[t("textarea",{ref:F,placeholder:J.listening?z("Listening..."):O??z("Ask a question..."),value:y,onChange:e=>x(e.target.value),onKeyDown:e=>{Da(e)||K.onKeyDown(e)||("Enter"!==e.key||e.shiftKey||(e.preventDefault(),de()),"Escape"===e.key&&N&&(e.preventDefault(),C()))},onKeyUp:K.sync,onClick:K.sync,onFocus:K.sync,onBlur:K.close,...K.textareaAria,onPaste:e=>{if(E?.(e),e.defaultPrevented)return;let t;try{t=e.clipboardData?.getData("text/plain")??""}catch{return}const n=function(e){if(!e)return null;const t=_a(e);return t===e?null:t}(t);if(null===n)return;e.preventDefault();const r=e.currentTarget,a=function(e,t,n,r){const a=Math.max(0,Math.min(t,e.length)),o=Math.max(a,Math.min(n,e.length));return{value:e.slice(0,a)+r+e.slice(o),caret:a+r.length}}(y,r.selectionStart??y.length,r.selectionEnd??y.length,n);x(a.value),requestAnimationFrame(()=>{F.current&&(F.current.selectionStart=F.current.selectionEnd=a.caret)})},rows:1,className:"filigran-chat-composer-field w-full bg-transparent border-none outline-hidden resize-none text-[0.8125rem] px-1 py-1.5 chat-text-900/100 placeholder:chat-text-muted-400/30 filigran-chat-scrollable",style:{maxHeight:120}}),t(Oa,{view:K.view,items:K.items,activeIndex:K.activeIndex,listboxId:K.listboxId,optionId:K.optionId,onHover:K.setActiveIndex,onPick:K.pick,t:z}),e("div",{"data-testid":"filigran-chat-composer-actions",className:"flex shrink-0 items-center gap-1 pt-1",children:[Q&&e(n,{children:[t("input",{ref:q,type:"file",multiple:!0,hidden:!0,accept:U||void 0,onChange:e=>{A?.(e.target.files),e.target.value=""}}),t("button",{type:"button",onClick:()=>q.current?.click(),"aria-label":z("Attach files"),className:"w-8 h-8 flex items-center justify-center shrink-0 chat-radius-sm chat-text-muted-400/30 hover:chat-surface-hover-100/10 mr-0.5 transition-colors",children:t(wr,{size:18})})]}),M&&M.length>0&&t(Wa,{prompts:M,onPick:e=>{x(y.trim()?`${y.trimEnd()}\n\n${e}`:e),F.current?.focus()},t:z}),P,e("span",{className:"ml-auto flex items-center gap-2.5 pr-1",children:[L&&t(Ua,{usage:L,t:z}),_&&t(qa,{quota:_,t:z})]}),J.supported&&t(fa,{title:J.listening?z("Stop dictation"):z("Dictate a message"),children:e("button",{type:"button",onClick:J.toggle,"aria-label":z("Dictate a message"),"aria-pressed":J.listening,className:"relative w-8 h-8 flex items-center justify-center shrink-0 chat-radius-sm mr-0.5 transition-colors "+(J.listening?"text-[var(--chat-danger)] bg-[var(--chat-danger)]/10 hover:bg-[var(--chat-danger)]/20":"chat-text-muted-400/30 hover:chat-surface-hover-100/10"),children:[J.listening?t(Gr,{size:18}):t(Kr,{size:18}),J.listening&&t("span",{className:"absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-[var(--chat-danger)] motion-safe:animate-pulse"})]})}),le&&t(fa,{title:z("Send when the answer ends"),children:t("button",{type:"button",onClick:de,"aria-label":z("Send when the answer ends"),className:"p-1.5 chat-radius-sm w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Qr,{size:18})})}),ce&&t(fa,{title:z("Send now"),children:t("button",{type:"button",onClick:de,"aria-label":z("Send now"),className:"p-1.5 chat-radius-sm w-8 h-8 flex items-center justify-center transition-all duration-150 text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20",children:t(Qr,{size:18})})}),t(fa,{title:N?z("Stop generating"):pe,children:t("button",{type:"button",onClick:N?C:de,"aria-label":z(N?"Stop generating":"Send"),disabled:!N&&!re,className:"p-1.5 chat-radius-sm w-8 h-8 flex items-center justify-center transition-all duration-150 "+(N?"text-[var(--chat-danger)] bg-[var(--chat-danger)]/10 hover:bg-[var(--chat-danger)]/20 ml-0.5":re?"text-[var(--chat-accent)] bg-[var(--chat-accent)]/10 hover:bg-[var(--chat-accent)]/20":"chat-text-muted-300/20 cursor-not-allowed"),children:t(N?ta:Qr,{size:18})})})]})]}),J.interim?e("p",{className:"flex items-center justify-center gap-1.5 text-[0.65rem] italic text-[var(--chat-danger)] mt-1.5 min-h-[1lh]",children:[t("span",{className:"w-1.5 h-1.5 shrink-0 rounded-full bg-[var(--chat-danger)] motion-safe:animate-pulse"}),t("span",{className:"truncate",children:J.interim})]}):t("p",ue?{"data-testid":"filigran-chat-composer-hint",className:he,children:ue}:{"data-testid":"filigran-chat-disclaimer",className:he,children:z("Uses AI. Verify results.")})]})},Ha=e=>e.serverId??e.id;const Va=()=>"undefined"!=typeof window&&!!window.speechSynthesis&&"function"==typeof window.SpeechSynthesisUtterance;const Ka={time:{hour:"2-digit",minute:"2-digit"},date:{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"},dateWithYear:{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"},full:{dateStyle:"full",timeStyle:"short"}},Ga=new Map;function Xa(e,t){const n=`${e??""}|${t}`;let r=Ga.get(n);if(!r){try{r=new Intl.DateTimeFormat(e||void 0,Ka[t])}catch{r=new Intl.DateTimeFormat(void 0,Ka[t])}Ga.set(n,r)}return r}const Ya={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e)};const Ja=new Set(["ArrowUp","PageUp","Home"]);function Qa(e){return 1===e.length?e[0].clientY:null}const Za=new Set(["auto","scroll","overlay"]);const eo={presentation:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M2 3h20"}),t("path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"}),t("path",{d:"m7 21 5-5 5 5"})]}),report:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),t("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}),t("path",{d:"M10 9H8"}),t("path",{d:"M16 13H8"}),t("path",{d:"M16 17H8"})]}),video:({className:n,size:r=24})=>e("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[t("path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z"}),t("path",{d:"m6.2 5.3 3.1 3.9"}),t("path",{d:"m12.4 3.4 3.1 4"}),t("path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})]})},to="inline-flex items-center gap-1 chat-radius-sm border chat-border-200/10 px-2 py-1 text-[0.7rem] chat-text-secondary-700/70 transition-colors hover:border-[var(--chat-accent)] hover:text-[var(--chat-accent)] disabled:opacity-50 disabled:cursor-default outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",no=({artifact:n,t:r,onDownload:a,onRefresh:s,onOpen:i})=>{const[c,d]=o(n),[u,h]=o(null),[p,m]=o(!1);l(()=>d(n),[n]);const g=!!s&&!p&&(e=>"video"===e.kind&&("pending"===e.status||"running"===e.status))(c);l(()=>{if(!g||!s)return;let e=!1;const t=function(e,{intervalMs:t,forMs:n,onGiveUp:r}){let a,o=!1;const s=()=>{a=setTimeout(()=>{e().catch(()=>{}).finally(()=>{o||s()})},t)},i=setTimeout(()=>{o=!0,clearTimeout(a),r?.()},n);return s(),()=>{o=!0,clearTimeout(a),clearTimeout(i)}}(()=>s(c.kind,c.id).then(t=>{!e&&t&&d(t)}),{intervalMs:1e4,forMs:9e5,onGiveUp:()=>m(!0)});return()=>{e=!0,t()}},[g,s,c.kind,c.id]);const f=eo[c.kind],v=function(e,t){return t("presentation"===e?"Presentation":"report"===e?"Report":"Video")}(c.kind,r),w=c.title||v,b=F(c,r),y=function(e,t){if("video"===e.kind){if("running"===e.status)return I(t,"Rendering {progress}%",{progress:Math.round(e.progress??0)});if("pending"===e.status)return t("Waiting to render");if(!(e.downloads.length>0))return"failed"===e.status||"cancelled"===e.status?t("The render did not finish"):t("Not rendered yet")}}(c,r),x=i?null:function(e){if(e.url)try{const t=new URL(e.url);return"http:"===t.protocol||"https:"===t.protocol?t.toString():void 0}catch{return}}(c),k=a?c.downloads:[];return e("div",{role:"group","aria-label":`${v}: ${w}`,className:"flex flex-col gap-2 w-full max-w-[90%] chat-radius-md border chat-border-200/10 chat-surface-subtle-50/4 px-3 py-2.5",children:[e("div",{className:"flex items-start gap-2.5 min-w-0",children:[t("span",{className:"shrink-0 mt-0.5 text-[var(--chat-accent)]",children:t(f,{size:18})}),e("span",{className:"flex flex-col min-w-0 flex-1 gap-0.5",children:[t("span",{className:"truncate text-[0.8125rem] font-medium chat-text-900/100",children:w}),b&&t("span",{className:"text-[0.7rem] chat-text-secondary-500/50",children:b}),y&&e("span",{className:"flex items-center gap-1.5 text-[0.7rem] chat-text-secondary-500/50","aria-live":"polite",children:[g&&t(Na,{size:10}),y]})]})]}),(x||i||k.length>0)&&e("div",{className:"flex flex-wrap items-center gap-1.5 pl-[28px]",children:[i&&t("button",{type:"button",className:to,onClick:()=>i(c),children:r("Open")}),x&&e("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:to,children:[r("Open in XTM One"),t(Rr,{size:12})]}),k.map(n=>{const o=function(e,t){return"pdf"===e?"PDF":"mp4"===e?"MP4":"pptx"===e?t("PowerPoint"):"pptx_native"===e?t("PowerPoint (editable)"):e.toUpperCase()}(n,r);return e("button",{type:"button",className:to,disabled:null!==u,"aria-label":I(r,"Download {format}",{format:o}),onClick:()=>{(async e=>{if(a){h(e);try{await a(c,e)}finally{h(null)}}})(n)},children:[u===n?t(Na,{size:11}):t(Er,{size:12}),o]},n)})]})]})};function ro(e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function ao(e){const t=s(null);return l(()=>{if(!e)return;const n=requestAnimationFrame(()=>{t.current?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})});return()=>cancelAnimationFrame(n)},[e]),t}const oo="inline-flex items-center gap-1.5 chat-radius-sm px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",so=({proposal:n,decision:r,onDecide:a,disabled:s,t:i})=>{const[c,l]=o(!1),[d,u]=o(""),p=h(),m=ao(c),g=r?.verdict,f=Object.keys(n.arguments??{}),v=e=>{a({toolCallId:n.toolCallId,verdict:e,..."reject"===e&&d.trim()?{rejectionReason:d.trim()}:{}})};return e("div",{"data-testid":"filigran-chat-approval",className:"chat-radius-md border border-amber-500/25 bg-amber-500/[0.04] p-3 flex flex-col gap-2",children:[e("div",{className:"flex items-start justify-between gap-2",children:[e("div",{className:"min-w-0 flex items-start gap-2",children:[t(da,{size:13,className:"mt-0.5 shrink-0 text-amber-600 dark:text-amber-400"}),e("div",{className:"min-w-0",children:[t("p",{className:"truncate font-mono text-xs chat-text-800/85",children:n.toolName||i("unknown tool")}),n.toolDescription&&t("p",{className:"mt-0.5 text-[0.7rem] chat-text-secondary-600/60",children:n.toolDescription}),n.source&&t("p",{className:"mt-0.5 text-[0.65rem] chat-text-muted-400/35",children:n.source})]})]}),g&&t("span",{className:"shrink-0 chat-radius-sm px-1.5 py-0.5 text-[0.65rem] font-medium "+("reject"===g?"bg-red-500/15 text-red-600 dark:text-red-300":"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300"),children:i("reject"===g?"Declined":"approve_always"===g?"Always allowed":"Approved")})]}),f.length>0&&t("div",{className:"flex flex-col gap-1.5",children:f.map(r=>{const a=function(e,t){const n=e?.properties;if(!n||"object"!=typeof n)return{};const r=n[t];if(!r||"object"!=typeof r)return{};const a=r;return{description:"string"==typeof a.description?a.description:void 0,type:"string"==typeof a.type?a.type:void 0}}(n.inputSchema,r);return e("div",{className:"text-[0.7rem]",children:[e("div",{className:"flex flex-wrap items-baseline gap-1.5",children:[t("span",{className:"font-mono chat-text-secondary-700/75",children:r}),a.description&&e("span",{className:"chat-text-secondary-500/45",children:["— ",a.description]})]}),t("pre",{className:"mt-0.5 whitespace-pre-wrap break-all font-mono chat-text-secondary-600/60",children:ro(n.arguments?.[r])})]},r)})}),!g&&c&&e("div",{ref:m,className:"flex flex-col gap-1.5",children:[t("label",{htmlFor:p,className:"text-[0.7rem] chat-text-secondary-500/45",children:i("Why not? The agent sees this and can adapt (optional)")}),t("textarea",{id:p,autoFocus:!0,rows:2,value:d,onChange:e=>u(e.target.value),placeholder:i("e.g. wrong environment — use staging instead"),className:"w-full resize-none chat-radius-sm border chat-border-200/10 chat-input-surface-white/3 px-2 py-1 text-[0.7rem] chat-text-800/85 outline-none focus:border-[var(--chat-accent)]/50"}),e("div",{className:"flex items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>v("reject"),className:`${oo} bg-red-500/10 text-red-600 hover:bg-red-500/20 dark:text-red-300`,children:[t(ua,{size:13}),i("Decline this call")]}),t("button",{type:"button",disabled:s,onClick:()=>{l(!1),u("")},className:`${oo} chat-text-secondary-500/50 hover:chat-surface-hover-100/5`,children:i("Back")})]})]}),!g&&!c&&e("div",{className:"flex flex-wrap items-center gap-1.5",children:[e("button",{type:"button",disabled:s,onClick:()=>l(!0),className:`${oo} text-red-600 hover:bg-red-500/10 dark:text-red-300`,children:[t(ua,{size:13}),i("No")]}),e("button",{type:"button",disabled:s,onClick:()=>v("approve"),className:`${oo} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:[t(kr,{size:13}),i("Yes")]}),t(fa,{title:i("Also applies to your scheduled runs, until you revoke it"),children:t("button",{type:"button",disabled:s,onClick:()=>v("approve_always"),className:`${oo} border chat-border-200/15 chat-text-secondary-700/70 hover:chat-surface-hover-100/5`,children:i("Yes, always")})})]})]})},io=({proposals:n,onSubmit:r,isSubmitting:a,error:i,t:c})=>{const[d,u]=o({}),h=s(!1),[p,m]=o(!1);l(()=>{i&&(h.current=!1,m(!1))},[i]);const g=a||p,f=e=>{h.current||a||(h.current=!0,m(!0),r(e))},v=n.filter(e=>d[e.toolCallId]).length,w=v===n.length&&n.length>0,b=Object.values(d).some(e=>"approve_always"===e.verdict),y=ao(b),x=ao(!0);return e("div",{ref:x,className:"flex flex-col gap-2 chat-radius-md border border-amber-500/20 bg-amber-500/[0.02] p-3",children:[e("p",{className:"flex items-start gap-1.5 text-xs font-medium text-amber-700 dark:text-amber-300",children:[t(fr,{size:13,className:"mt-0.5 shrink-0"}),1===n.length?c("The agent needs your approval to run a tool:"):c("The agent needs your approval to run these tools:")]}),n.map(e=>t(so,{proposal:e,decision:d[e.toolCallId],disabled:g,t:c,onDecide:e=>{const t={...d,[e.toolCallId]:e};u(t);const r=n.map(e=>t[e.toolCallId]);r.every(Boolean)&&!r.some(e=>"approve_always"===e.verdict)&&f(r)}},e.toolCallId)),b&&t(ba,{tone:"warning",children:c("“Yes, always” saves a preference for you. That tool will then run without asking — including on scheduled runs nobody is watching — until you revoke it.")}),i&&t(ba,{tone:"error",children:i}),e("div",{ref:y,className:"flex items-center justify-between gap-2",children:[t("span",{className:"text-[0.7rem] chat-text-muted-500/40",children:n.length>1?I(c,"{decided}/{total} decided",{decided:v,total:n.length}):""}),t("button",{type:"button",disabled:!w||g,onClick:()=>f(n.map(e=>d[e.toolCallId])),className:`${oo} bg-[var(--chat-accent)] text-white hover:opacity-90`,children:c(g?"Sending…":"Confirm")})]})]})},co=({src:n,alt:r,onClose:a,onDownload:i,t:c})=>{const d=s(null),u=s(null),h=s(null),[p,m]=o(null);return l(()=>{m(z(d.current))},[]),l(()=>{const e=e=>{if("Escape"===e.key)return void a();if("Tab"!==e.key)return;const t=[...h.current?.querySelectorAll("button")??[]];if(0===t.length)return;const n=t[0],r=t[t.length-1],o=document.activeElement;(!(!!o&&t.includes(o))||e.shiftKey&&o===n||!e.shiftKey&&o===r)&&(e.preventDefault(),(e.shiftKey?r:n).focus({preventScroll:!0}))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[a]),l(()=>{if(!p)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return u.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[p]),t("span",{ref:d,className:"hidden",children:p&&y(e("div",{ref:h,className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/80 p-4",onClick:a,role:"dialog","aria-modal":"true","aria-label":r.trim()||c("Image preview"),children:[e("div",{className:"absolute top-4 right-4 flex gap-2",children:[i&&t("button",{type:"button",onClick:e=>{e.stopPropagation(),i()},"aria-label":c("Download"),className:"rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20",children:t(Er,{size:20})}),t("button",{ref:u,type:"button",onClick:a,"aria-label":c("Close"),className:"rounded-full bg-white/10 p-2 text-white transition-colors hover:bg-white/20",children:t(Sr,{size:20})})]}),t("img",{src:n,alt:r,className:"max-h-[90%] max-w-[90%] chat-radius-md object-contain",onClick:e=>e.stopPropagation()})]}),p)})};function lo(e,t){const n=!!e&&!!t&&Object.keys(t).length>0&&(e=>!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(e),[r,a]=o(null),[s,i]=o(null),c=sn();return l(()=>{if(!n||!e)return;let r=!1;return c(e,{credentials:"include",headers:{...t}}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(t=>{r||a({src:e,url:URL.createObjectURL(t)})}).catch(()=>{r||i(e)}),()=>{r=!0}},[n,e,t]),l(()=>{if(!r)return;const{url:e}=r;return()=>URL.revokeObjectURL(e)},[r]),e?n?r?.src===e?{src:r.url,status:"ready"}:s===e?{src:null,status:"failed"}:{src:null,status:"loading"}:{src:e,status:"ready"}:{src:null,status:"failed"}}const uo=({src:r,alt:a,requestHeaders:s,maxHeightClass:i="max-h-[400px]",onDownload:c,t:l})=>{const d=lo(r,s),[u,h]=o(null),[p,m]=o(!1),g=d.src;return"failed"===d.status||null!==g&&u===g?t("p",{className:"my-2 text-[0.75rem] italic chat-text-muted-400/40",children:l("Image could not be loaded")}):g?e(n,{children:[e("span",{className:"group/img relative my-3 inline-block max-w-full chat-radius-md border chat-border-200/10 p-1 transition-colors hover:border-[var(--chat-accent)]/40",children:[t("img",{src:g,alt:a,loading:"lazy",onClick:()=>m(!0),onError:()=>h(g),className:`max-w-full cursor-zoom-in chat-radius-sm object-contain ${i}`}),t("button",{type:"button",onClick:()=>m(!0),"aria-label":l("Expand image"),className:"absolute top-2 right-2 chat-radius-sm bg-black/50 p-1.5 text-white opacity-0 transition-opacity hover:bg-black/70 group-hover/img:opacity-100 focus-visible:opacity-100",children:t(Hr,{size:14})})]}),p&&t(co,{src:g,alt:a,onClose:()=>m(!1),onDownload:c,t:l})]}):e("span",{className:"my-3 inline-flex items-center gap-2 chat-radius-md border chat-border-200/10 px-3 py-2",children:[t(qr,{size:14,className:"shrink-0 animate-pulse text-[var(--chat-accent)]"}),t("span",{className:"text-[0.7rem] chat-text-muted-500/40",children:l("Loading image…")})]})};const ho="inline-flex items-center gap-1.5 self-start chat-radius-sm text-xs text-[var(--chat-accent)] opacity-80 transition-opacity hover:opacity-100 focus-visible:opacity-100",po=({t:n,enabled:r=!0,onPlay:a,playUrl:s,keepEndInView:c,messages:d,content:u})=>{const h=i(()=>d&&d.length>0?d:(e=>[e("Crunching the data"),e("Connecting the dots"),e("Consulting the sources"),e("Thinking it through"),e("Reticulating splines"),e("Analyzing the details"),e("Almost there"),e("Putting it together"),e("Polishing the answer"),e("Wrapping things up")])(n),[d,n]),p=function(){const[e,t]=o(()=>!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);return l(()=>{if("undefined"==typeof window||!window.matchMedia)return;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=()=>t(e.matches);return"function"==typeof e.addEventListener?(e.addEventListener("change",n),()=>e.removeEventListener("change",n)):(e.addListener(n),()=>e.removeListener(n))},[]),e}(),[m,g]=o(0);if(l(()=>{r&&c()},[r,c]),l(()=>{if(!r||u)return;const e=window.setInterval(()=>g(e=>(e+1)%h.length),2600);return()=>window.clearInterval(e)},[r,h.length,!!u]),!r)return null;if(u)return t("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:u});const f=h[m%h.length];return e("div",{className:"ml-11 mt-2.5 max-w-[78%]",children:[t("span",{className:"sr-only",role:"status","aria-live":"polite",children:f}),e("div",{className:"flex flex-col gap-1.5 chat-radius-md bg-[var(--chat-accent)]/[0.03] px-3 py-2.5",style:p?void 0:{animation:"chat-fade-in 0.5s ease-out"},children:[e("span",{"aria-hidden":!0,className:"text-xs chat-text-muted-500/45",style:p?void 0:{animation:"chat-fade-in 0.4s ease-out"},children:[f,t("span",{className:"ml-0.5 inline-block w-1 h-3 align-middle bg-[var(--chat-accent)]/60 "+(p?"":"animate-pulse")})]},f),a?e("button",{type:"button",onClick:a,className:ho,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(Ur,{size:13})}),n("Play Space Invaders")]}):s?e("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:ho,children:[t("span",{"aria-hidden":!0,className:"inline-flex",children:t(Ur,{size:13})}),n("Play Space Invaders in XTM One"),t("span",{"aria-hidden":!0,className:"inline-flex",children:t(Rr,{size:11})})]}):null]})]})};class mo extends p{state={failed:!1,resetKey:this.props.resetKey};static getDerivedStateFromError(){return{failed:!0}}static getDerivedStateFromProps(e,t){return e.resetKey===t.resetKey?null:{failed:!1,resetKey:e.resetKey}}componentDidCatch(e,t){console.error(`${this.props.label} failed to render`,e,t.componentStack)}render(){return this.state.failed?this.props.fallback:this.props.children}}function go({draw:e}){return t(n,{children:e()})}function fo({t:e}){return t("p",{className:"pl-1 text-[0.75rem] italic chat-text-muted-400/40",children:e("This item could not be loaded.")})}function vo(e,t){return e>1?I(t,"Delegating {count} tasks…",{count:e}):t("Delegating one task…")}function wo(e,t){return e>1?I(t,"Waiting for {count} background tasks…",{count:e}):t("Waiting for one background task…")}function bo(e,t){return e>1?I(t,"Collecting results from {count} tasks…",{count:e}):t("Collecting results from one task…")}function yo(e,t){const n="function"==typeof t?B(t,e):t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;return"string"==typeof n&&n.trim()?n:void 0}function xo(e,t){return Array.from(new Set(e.map(e=>yo(e,t)??e.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()))))}function ko(e,t){switch(e){case"history":return t("Loading conversation history…");case"compaction":return t("Summarizing earlier conversation…");case"memory":return t("Recalling memory…");case"integrations":return t("Connecting integrations…");case"tools":return t("Preparing tools…");default:return t("Preparing…")}}function Co(e,t,n){if(e.agents>1)return I(t,"Consulting {count} agents…",{count:e.agents});const r=e.agentName;if(e.count>1)return I(t,"Consulting {agent}: {count} questions…",{agent:r,count:e.count});const a="tool_start"===e.status?(e.tools??[]).filter(e=>"consult_agent"!==e):[];if(a.length>0){const[e,...o]=xo(a,n);return o.length>0?I(t,"Consulting {agent}: {tool} (+{count} more)…",{agent:r,tool:e,count:o.length}):I(t,"Consulting {agent}: {tool}…",{agent:r,tool:e})}return e.answering?I(t,"Consulting {agent}: writing the answer…",{agent:r}):I(t,"Consulting {agent}…",{agent:r})}function No(e,t,n){if(!e)return{label:t("Thinking..."),StatusIcon:yr,showDots:!1};switch(e.status){case"tool_start":{const r=e.tools??[],a=r.map(e=>e.toLowerCase());if(a.some(e=>"spawn_background_task"===e)){return{label:vo(r.filter(e=>"spawn_background_task"===e).length,t),StatusIcon:sa,showDots:!1}}if(a.some(e=>"check_task_status"===e)){return{label:wo(r.filter(e=>"check_task_status"===e).length,t),StatusIcon:ea,showDots:!1}}if(a.some(e=>"get_task_result"===e)){return{label:bo(r.filter(e=>"get_task_result"===e).length,t),StatusIcon:ea,showDots:!1}}let o,s=da;if(a.some(e=>e.includes("search")||e.includes("list"))?s=Jr:a.some(e=>e.includes("read")||e.includes("get")||e.includes("query"))?s=Ar:a.some(e=>e.includes("send")||e.includes("create")||e.includes("draft")||e.includes("reply")||e.includes("flag"))?s=Br:a.some(e=>e.includes("code")||e.includes("execute"))?s=na:a.some(e=>e.includes("web")||e.includes("browse"))&&(s=Or),r.length>0){const e=xo(r,n);o=1===e.length?`${e[0]}…`:I(t,"{tool} (+{count} more)…",{tool:e[0],count:e.length-1})}else o=t("Using tools…");return{label:o,StatusIcon:s,showDots:!1}}case"awaiting_approval":return{label:t("Waiting for your approval…"),StatusIcon:fr,showDots:!1};case"cancelling":return{label:t("Stopping…"),StatusIcon:yr,showDots:!0};case"reconnecting":return{label:t("Reconnecting…"),StatusIcon:yr,showDots:!0};case"wait_start":return{label:e.waitReason||t("Waiting before continuing…"),StatusIcon:ea,showDots:!1};case"acting_on_page":return{label:t("Acting on the page…"),StatusIcon:ea,showDots:!0};case"analyzing":{const n=e.iteration;return{label:n&&n>1?I(t,"Analyzing results (step {step})…",{step:n}):t("Analyzing results…"),StatusIcon:ea,showDots:!1}}case"preparing":return{label:ko(e.phase,t),StatusIcon:yr,showDots:!1};case"context_compaction":return{label:t("Compacting conversation context…"),StatusIcon:ea,showDots:!1};case"persisting":return{label:t("Saving response…"),StatusIcon:Ar,showDots:!1};case"mention_answering":{const n=e.agentName;return{label:n?I(t,"{agent} is answering…",{agent:n}):t("The agent is answering…"),StatusIcon:sa,showDots:!0}}case"steering":return{label:t("Incorporating your message…"),StatusIcon:ea,showDots:!0};case"composing":return{label:t("Composing answer…"),StatusIcon:yr,showDots:!0};case"consulting":{if(e.consult)return{label:Co(e.consult,t,n),StatusIcon:sa,showDots:!1};const r=e.tools?.[0];return{label:r?I(t,"Consulting {agent}…",{agent:r}):t("Consulting an agent…"),StatusIcon:sa,showDots:!1}}case"delegating":return{label:vo(e.tools?.filter(e=>"spawn_background_task"===e).length??0,t),StatusIcon:sa,showDots:!1};case"polling":return{label:wo(e.tools?.filter(e=>"check_task_status"===e).length??0,t),StatusIcon:ea,showDots:!1};case"collecting":return{label:bo(e.tools?.filter(e=>"get_task_result"===e).length??0,t),StatusIcon:ea,showDots:!1};case"transferring":{const n=e.agentName??e.tools?.[0];return{label:n?I(t,"Transferring to {agent}…",{agent:n}):t("Transferring to another agent…"),StatusIcon:Rr,showDots:!1}}default:return{label:t("Thinking..."),StatusIcon:yr,showDots:!1}}}function So(e,t,n,r){return e&&n?.(e)||No(e,t,r).label}function To(e){return"mention_answering"===e?.status?void 0:e?.answeringAgentName}function Ao(e,t,n){return t?I(e,"{agent}: {status}",{agent:t,status:n}):n}function Io(e,t,n,r){return Ao(t,To(e),So(e,t,n,r))}function Eo(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]+)`/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/#{1,6}\s+/g,"").replace(/^[ \t]*[-*>]+[ \t]*/gm,"").replace(/[ \t]+/g," ").replace(/\n{3,}/g,"\n\n").trim()}function zo({text:n,action:r}){const a=s(null),[i,c]=o(!1);return l(()=>{const e=a.current;e&&(e.scrollTop=e.scrollHeight,c(e.scrollHeight>e.clientHeight+1))},[n]),e("div",{className:"filigran-chat-reasoning ml-11 mt-2.5 max-w-[75%] chat-radius-md border-l-2 bg-[var(--chat-accent)]/[0.03] py-2 pl-3 pr-3",children:[r&&t("div",{className:"float-right -mr-2 -mt-1 ml-2",children:r}),t("div",{ref:a,className:"max-h-40 overflow-hidden"+(i?" [-webkit-mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)] [mask-image:linear-gradient(to_bottom,transparent_0,rgb(0_0_0/0.25)_1.5rem,rgb(0_0_0/0.7)_3rem,black_4.5rem)]":""),children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-xs leading-5 chat-text-secondary-500/45",children:n})})]})}function Ro(e){const t=Math.floor(e);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function Do(e,t,n=0){const[r,a]=o(null);return l(()=>{if(a(null),!e)return;const r=window.setTimeout(()=>a(n),t);return()=>window.clearTimeout(r)},[e,t,n]),e&&r===n}const Mo=({agentStatus:r,logoIcon:a,t:s,miniGameEnabled:c=!0,onPlayWaitingGame:d,waitingGameUrl:u,keepEndInView:h,onSkipWait:p,statusLabel:m,waitingMessages:g,renderWaitingPanel:f,renderReasoningAction:v,toolLabels:w})=>{const b=No(r,s,w),{StatusIcon:y,showDots:x}=b,k=So(r,s,m,w),C=To(r),N=r?.thinkingContent,S=r?.elapsedStartMs,T="wait_start"===r?.status?r.waitStartMs:void 0,A=S??T,[I,E]=o(()=>Date.now());l(()=>{if(null==A)return;E(Date.now());const e=window.setInterval(()=>E(Date.now()),1e3);return()=>window.clearInterval(e)},[A]);const z=r?.waitSeconds,R=null!=T&&null!=z?Math.max(0,z-(I-T)/1e3):void 0,D=null!=S?Math.max(0,(I-S)/1e3):r?.elapsedS,M="number"==typeof D&&D>=15,_=i(()=>function(e){if(e.length<=6e3)return Eo(e);const t=[];let n=0;for(let r=e.indexOf("```");-1!==r;r=e.indexOf("```",n)){const a=e.indexOf("```",r+3);if(-1===a)break;t.push([n,r]),n=a+3}t.push([n,e.length]);const r=[];let a=6e3;for(let n=t.length-1;n>=0&&a>0;n--){const[o,s]=t[n],i=Math.max(o,s-a);r.push(e.slice(i,s)),a-=s-i+1}let o=r.reverse().join(" ");if(a<=0){const e=o.indexOf("\n\n");-1!==e&&e<o.length/2&&(o=o.slice(e+2))}return Eo(o)}(N??""),[N]),L=_.length>=3,P=Do(c&&!L,5e3),j=Do(c&&L,1e4,N?.length??0),$=L?j:P,U=L&&!$?B(v):null,O=null==U||!1===U?null:t(mo,{label:"A reasoning window action",resetKey:"",fallback:null,children:U});return e(n,{children:[e("div",{className:"flex gap-3 items-center justify-start",children:[t("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center chat-radius-sm bg-gradient-to-br from-[var(--chat-accent)]/15 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-4 [&>svg]:h-4",children:a})}),t("div",{"data-testid":"filigran-chat-status",className:"chat-radius-md border chat-border-200/10 chat-surface-subtle-50/3 px-4 py-3",children:e("div",{className:"flex items-center gap-2.5",children:[x?t("div",{className:"flex gap-[3px] items-center h-3.5 w-3.5 justify-center",children:[0,.15,.3].map((e,n)=>t("span",{className:"h-[5px] w-[5px] rounded-full bg-[var(--chat-accent)]/50",style:{animation:`chat-dot 1s ease-in-out infinite ${e}s`}},n))}):t(y,{size:14,className:"text-[var(--chat-accent)] animate-pulse transition-all duration-300"}),C&&e(n,{children:[t("span",{className:"sr-only",children:Ao(s,C,k)}),t("span",{"aria-hidden":"true",className:"text-xs font-medium text-[var(--chat-accent)]/80 shrink-0",children:C})]}),t("span",{"aria-hidden":!!C||void 0,className:"text-sm chat-text-secondary-500/50 transition-all duration-300",children:k}),void 0!==R?t("span",{className:"text-xs chat-text-muted-400/30 tabular-nums shrink-0",children:Ro(Math.ceil(R))}):M&&t("span",{className:"text-xs chat-text-muted-400/30 tabular-nums shrink-0",children:Ro(D)}),"wait_start"===r?.status&&p&&t("button",{type:"button",onClick:p,className:"ml-1 shrink-0 chat-radius-sm border border-[var(--chat-accent)]/40 px-2 py-0.5 text-xs text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors",children:s("Continue now")})]})})]}),$?t(po,{t:s,enabled:c,onPlay:d,playUrl:u,keepEndInView:h,messages:g,content:f?.()}):L?t(zo,{text:_,action:O}):null]})},_o=b().use(w).use(v).freeze();function Lo(e){switch(e.type){case"definition":case"footnoteDefinition":return!0;case"blockquote":case"list":case"listItem":return e.children.some(Lo);default:return!1}}function Po(e,t){return e.lastIndexOf("\n",t-1)+1}function jo(e,t){if(t<2||-1===e.indexOf("\n",t))return!1;return""===e.slice(Po(e,t-1),t-1).trim()}function $o(e,t,n){const r=e.slice(t,n).split("\n");for(let e=r.length-1;e>=0;e--)if(r[e].trim())return/^(?: {4}|\t)/.test(r[e]);return!1}class Uo{last=null;split(e){return this.last?.source!==e&&(this.last=function(e,t){if(!e.trim())return function(e){return{source:e,blocks:e?[e]:[],starts:e?[0]:[],settled:0,firstDefinition:-1}}(e);const n=t&&t.settled>0&&e.startsWith(t.source)?t.settled:0,r=n?t.starts[n]:0,a=e.slice(r),o=t&&n?t.starts.slice(0,n):[];let s=t&&n&&t.firstDefinition<n?t.firstDefinition:-1;o.push(r);for(const t of _o.parse(a).children){const n=t.position?.start.offset;if(void 0!==n){const t=r+Po(a,n),s=o[o.length-1];t>s&&!$o(e,s,t)&&o.push(t)}s<0&&Lo(t)&&(s=o.length-1)}let i=n;for(let t=o.length-1;t>n;t--)if(jo(e,o[t])){i=t;break}const c=s<0?o.map((t,n)=>e.slice(t,o[n+1]??e.length)):[e];return{source:e,blocks:c,starts:o,settled:i,firstDefinition:s}}(e,this.last)),this.last.blocks}}const Oo=e=>e.trim().split(/\s+/).join("|"),Wo=Oo("\n abstract as async await break case catch class const continue debugger declare default delete do else enum\n export extends finally for from function get if implements import in instanceof interface keyof let module\n namespace new of private protected public readonly return satisfies set static super switch this throw try\n type typeof var void while with yield\n"),qo=Oo("true false null undefined NaN Infinity"),Fo=Oo("any boolean never number object string symbol unknown bigint Array Date Error JSON Map Math Object Promise Record Set console window document"),Bo=Oo("\n and as assert async await break class continue def del elif else except finally for from global if import in\n is lambda match case nonlocal not or pass raise return try while with yield\n"),Ho=Oo("True False None"),Vo=Oo("print len range dict list set tuple str int float bool bytes isinstance enumerate zip map filter open self cls super type sorted any all min max sum"),Ko=Oo("\n select from where and or not in is null as join inner left right full outer cross on group by order having\n limit offset union all distinct insert into values update set delete create table view index drop alter add\n column primary key foreign references default case when then else end exists between like ilike asc desc\n with returning cascade constraint unique if begin commit rollback transaction grant revoke over partition\n"),Go=Oo("count sum avg min max coalesce now cast lower upper length substring date_trunc extract round"),Xo=Oo("if then else elif fi for while until do done case esac in function return local export readonly unset select time"),Yo=Oo("\n echo printf cd ls cat grep sed awk find xargs curl wget git docker kubectl helm npm npx yarn pip python python3\n node make sudo chmod chown mkdir rm cp mv tar ssh source set test read exit kill ps tail head sort uniq wc tee\n"),Jo={javascript:{pattern:new RegExp([String.raw`(?<comment>\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$))`,String.raw`(?<string>"(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?|\x60(?:[^\x60\\]|\\[\s\S])*\x60?)`,String.raw`(?<number>\b(?:0[xX][\da-fA-F_]+|0[bB][01_]+|\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?n?)\b)`,`(?<keyword>\\b(?:${Wo})\\b)`,`(?<literal>\\b(?:${qo})\\b)`,`(?<builtin>\\b(?:${Fo})\\b)`,String.raw`(?<function>\b[A-Za-z_$][\w$]*(?=\s*\())`].join("|"),"y")},python:{pattern:new RegExp([String.raw`(?<comment>#[^\n]*)`,String.raw`(?<string>(?:[rRbBuUfF]{1,2})?(?:"""[\s\S]*?(?:"""|$)|'''[\s\S]*?(?:'''|$)|"(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?))`,String.raw`(?<number>\b(?:0[xXoObB][\da-fA-F_]+|\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?j?)\b)`,`(?<keyword>\\b(?:${Bo})\\b)`,`(?<literal>\\b(?:${Ho})\\b)`,`(?<builtin>\\b(?:${Vo})\\b)`,String.raw`(?<function>(?<=@)[\w.]+|\b[A-Za-z_]\w*(?=\s*\())`].join("|"),"y")},json:{pattern:new RegExp([String.raw`(?<comment>\/\/[^\n]*)`,String.raw`(?<property>"(?:[^"\\\n]|\\.)*"(?=\s*:))`,String.raw`(?<string>"(?:[^"\\\n]|\\.)*"?)`,String.raw`(?<number>-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)`,String.raw`(?<literal>\b(?:true|false|null)\b)`].join("|"),"y")},bash:{pattern:new RegExp([String.raw`(?<comment>(?<![^\s;|&(])#[^\n]*)`,String.raw`(?<string>"(?:[^"\\]|\\[\s\S])*"?|'[^']*'?)`,String.raw`(?<variable>\$(?:\{[^}\n]*\}?|\w+|[@*#?$!0-9-]))`,`(?<keyword>(?<![\\w-])(?:${Xo})(?![\\w-]))`,`(?<builtin>(?<![\\w./-])(?:${Yo})(?![\\w-]))`,String.raw`(?<property>(?<![\w-])--?[A-Za-z][\w-]*)`,String.raw`(?<number>\b\d+\b)`].join("|"),"y")},sql:{pattern:new RegExp([String.raw`(?<comment>--[^\n]*|\/\*[\s\S]*?(?:\*\/|$))`,String.raw`(?<string>'(?:[^']|'')*'?)`,String.raw`(?<property>"(?:[^"]|"")*"?|\x60[^\x60]*\x60?)`,String.raw`(?<number>\b\d+(?:\.\d+)?\b)`,`(?<keyword>\\b(?:${Ko})\\b)`,"(?<literal>\\b(?:true|false)\\b)",`(?<builtin>\\b(?:${Go})\\b(?=\\s*\\())`].join("|"),"iy")},yaml:{pattern:new RegExp([String.raw`(?<comment>(?<![^\s])#[^\n]*)`,String.raw`(?<property>(?<=^|\n)[ \t]*(?:- )?[\w.-]+(?=\s*:(?:\s|$)))`,String.raw`(?<string>"(?:[^"\\\n]|\\.)*"?|'(?:[^'\n]|'')*'?)`,String.raw`(?<literal>\b(?:true|false|null|yes|no|on|off)\b)`,String.raw`(?<number>(?<![\w.])-?\d+(?:\.\d+)?(?![\w.]))`].join("|"),"y")}},Qo={js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",ts:"javascript",tsx:"javascript",typescript:"javascript",py:"python",python3:"python",jsonc:"json",json5:"json",sh:"bash",shell:"bash",zsh:"bash",console:"bash",postgres:"sql",postgresql:"sql",mysql:"sql",sqlite:"sql",yml:"yaml"};function Zo(e,t){const n=function(e){if(!e)return null;const t=e.toLowerCase(),n=Qo[t]??t;return Object.prototype.hasOwnProperty.call(Jo,n)?n:null}(t);if(!n||e.length>1e5)return e?[{type:"plain",text:e}]:[];const r=new RegExp(Jo[n].pattern.source,Jo[n].pattern.flags),a=[];let o=0,s=0;const i=t=>{t>o&&a.push({type:"plain",text:e.slice(o,t)})};for(;s<e.length;){r.lastIndex=s;const t=r.exec(e);if(!t||0===t[0].length){const t=/^[\w$]+/.exec(e.slice(s,s+256));s+=t?t[0].length:1;continue}const n=Object.entries(t.groups??{}).find(([,e])=>void 0!==e)?.[0]??"plain";i(s),a.push({type:n,text:t[0]}),s+=t[0].length,o=s}return i(e.length),a}const es=r({copiedBlock:null,onCopyCode:()=>{},streaming:!1,t:A}),ts={comment:"chat-hl-comment",string:"chat-hl-string",number:"chat-hl-number",keyword:"chat-hl-keyword",literal:"chat-hl-literal",builtin:"chat-hl-builtin",function:"chat-hl-function",property:"chat-hl-property",variable:"chat-hl-variable",plain:void 0},ns=m(({code:e,language:r})=>{const a=i(()=>Zo(e,r),[e,r]);return t(n,{children:a.map((e,n)=>{const r=ts[e.type];return r?t("span",{className:r,children:e.text},n):e.text})})});function rs({draw:e,block:r}){const a=e();return null==a||!1===a?t(n,{children:r}):t("div",{className:"my-3",children:a})}ns.displayName="HighlightedCode";const as={p:({children:e})=>t("p",{className:"mb-3 last:mb-0 leading-7 break-words chat-answer-text",children:e}),pre:({children:e})=>t(n,{children:e}),code:({className:n,children:r})=>{const{copiedBlock:o,onCopyCode:s,codeBlockRenderers:i,streaming:c,t:l}=a(es),d=/(?:^|\s)language-(\S+)/.exec(n||""),u=String(r).replace(/\n$/,""),h=d?i?.[d[1].toLowerCase()]:void 0;if(d||u.includes("\n")){const n=e("div",{className:"my-3 chat-radius-md border chat-border-200/10 overflow-hidden chat-code-block",children:[e("div",{className:"flex items-center justify-between px-3 py-1.5 border-b chat-border-200/10 chat-surface-subtle-100/3 select-none",children:[t("span",{className:"text-[0.7rem] chat-text-muted-500/40 font-mono",children:d?.[1]??"plaintext"}),t("button",{type:"button",onClick:()=>s(u),"aria-label":l(o===u?"Copied":"Copy code"),className:"p-0.5 chat-radius-sm hover:chat-surface-hover-200/10 transition-colors",children:o===u?t(kr,{size:14,className:"text-green-500"}):t(Tr,{size:14,className:"chat-text-muted-400/40"})})]}),t("pre",{className:"m-0 px-3 py-2 overflow-x-auto",children:t("code",{className:"chat-code leading-[1.7] chat-text-800/90 whitespace-pre","data-language":d?.[1]?.toLowerCase(),children:t(ns,{code:u,language:d?.[1]})})})]});return h?t(mo,{label:"A chat code block renderer",resetKey:`${u}\0${c}`,fallback:t(fo,{t:l}),children:t(rs,{draw:()=>h(u,{streaming:c}),block:n})}):n}return t("code",{className:"chat-code-inline chat-code px-1.5 py-0.5 chat-radius-sm text-[var(--chat-accent)]",children:r})},ul:({className:e,children:n})=>t("ul",{className:(e?.includes("contains-task-list")?"list-none pl-1":"list-disc pl-5")+" mb-3 chat-answer-text [&_li]:mb-1 [&_ul]:list-[circle] [&_ul]:mt-1 [&_ul]:mb-1 [&_ol]:mt-1 [&_ol]:mb-1 marker:text-[var(--chat-accent)]/50",children:n}),ol:({children:e})=>t("ol",{className:"list-decimal pl-5 mb-3 chat-answer-text [&_li]:mb-1 [&_ul]:mt-1 [&_ul]:mb-1 [&_ol]:mt-1 [&_ol]:mb-1 marker:text-[var(--chat-accent)]/50",children:e}),li:({children:e})=>t("li",{className:"leading-7 break-words",children:e}),input:({type:e,checked:n})=>"checkbox"===e?t("input",{type:"checkbox",checked:!!n,readOnly:!0,disabled:!0,className:"mr-2 align-[-2px] accent-[var(--chat-accent)]"}):null,del:({children:e})=>t("del",{className:"chat-text-muted-500/50",children:e}),strong:({children:e})=>t("strong",{className:"font-semibold chat-text-900/100",children:e}),em:({children:e})=>t("em",{className:"italic",children:e}),hr:()=>t("hr",{className:"my-4 chat-border-200/10"}),blockquote:({children:e})=>t("blockquote",{className:"my-3 border-l-2 border-[var(--chat-accent)]/30 bg-[var(--chat-accent)]/[0.03] pl-4 pr-3 py-2 chat-radius-r-sm italic chat-text-secondary-500/60",children:e}),a:({href:e,children:n})=>{const{onRelativeLinkClick:r}=a(es),o=ot(e),s=null!==o&&!!r,i=!(s||(e=>!!e&&!e.startsWith("//")&&!/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(e))(e)&&null!==o);return t("a",{href:e,onClick:e=>{s&&(e.preventDefault(),r(o))},target:i?"_blank":void 0,rel:i?"noopener noreferrer":void 0,className:"text-[var(--chat-accent)] underline underline-offset-2 hover:brightness-125",children:n})},img:({src:e,alt:n})=>{const{requestHeaders:r,t:o}=a(es);return"string"==typeof e&&e?t(uo,{src:e,alt:n||"",requestHeaders:r,t:o},e):null},h1:({children:e})=>t("h1",{className:"mt-4 first:mt-0 mb-2 font-bold chat-answer-heading-1 chat-text-900/100",children:e}),h2:({children:e})=>t("h2",{className:"mt-3 first:mt-0 mb-2 font-bold chat-answer-heading-2 chat-text-900/100",children:e}),h3:({children:e})=>t("h3",{className:"mt-3 first:mt-0 mb-1.5 font-semibold chat-answer-heading-3 chat-text-900/100",children:e}),h4:({children:e})=>t("h4",{className:"mt-3 first:mt-0 mb-1 font-semibold chat-answer-text chat-text-900/100",children:e}),h5:({children:e})=>t("h5",{className:"mt-2 first:mt-0 mb-1 font-semibold chat-answer-text chat-text-secondary-700/80",children:e}),h6:({children:e})=>t("h6",{className:"mt-2 first:mt-0 mb-1 font-semibold chat-answer-text chat-text-muted-500/60",children:e}),table:({children:e})=>t("div",{className:"my-3 max-w-full overflow-x-auto chat-radius-md border chat-border-200/15 filigran-chat-scrollable",children:t("table",{className:"min-w-full border-collapse chat-answer-text",children:e})}),thead:({children:e})=>t("thead",{className:"chat-table-head",children:e}),tbody:({children:e})=>t("tbody",{className:"[&>tr:nth-child(even)]:chat-table-stripe",children:e}),tr:({children:e})=>t("tr",{className:"border-t chat-border-200/15 first:border-t-0 transition-colors hover:chat-surface-hover-100/5",children:e}),th:({children:e,style:n})=>t("th",{style:n,className:"px-3 py-2 min-w-[6rem] text-left align-bottom font-semibold leading-5 border-b chat-border-200/15 chat-text-900/100",children:e}),td:({children:e,style:n})=>t("td",{style:n,className:"px-3 py-2 min-w-[6rem] max-w-[32rem] align-top leading-6 break-words chat-text-secondary-700/90",children:e}),section:({className:e,children:n})=>e?.includes("footnotes")?t("section",{className:"mt-4 pt-2 border-t chat-border-200/10 text-xs chat-text-muted-500/60 [&_ol]:mb-0 [&_h2]:sr-only",children:n}):t("section",{className:e,children:n}),sup:({children:e})=>t("sup",{className:"text-[0.7em] leading-none",children:e})},os=[v,k],ss=m(({source:e})=>t(x,{remarkPlugins:os,urlTransform:T,components:as,children:e}));ss.displayName="MarkdownBody";const is=({source:e})=>{const[r]=o(()=>new Uo),a=i(()=>r.split(e),[r,e]);return t(n,{children:a.map((e,n)=>t(ss,{source:e},n))})},cs=m(({codeBlockRenderers:e,...n})=>{const{content:r,streaming:a=!1,onRelativeLinkClick:s,requestHeaders:l,t:d=A}=n,[u,h]=o(null),[p,m]=o(a);a&&!p&&m(!0);const g=i(()=>N(r),[r]),f=c(e=>{navigator.clipboard.writeText(e),h(e),setTimeout(()=>h(null),2e3)},[]),v=i(()=>({copiedBlock:u,onCopyCode:f,onRelativeLinkClick:s,requestHeaders:l,codeBlockRenderers:e,streaming:a,t:d}),[u,f,s,l,e,a,d]);return t(es.Provider,{value:v,children:t(p?is:ss,{source:g})})});cs.displayName="MarkdownMessage";function ls(e){if(!e)return"";if(e.length>1e4)return e;try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function ds(e,t){return yo(e,t)??e.replace(/_/g," ")}const us=({entry:n,index:r,toolLabels:a,t:s})=>{const[c,l]=o(!1),d=i(()=>ls(n.input),[n.input]),u=i(()=>ls(n.output),[n.output]),h=!!d&&"{}"!==d;return e("div",{className:"border chat-border-200/6 chat-radius-md overflow-hidden",children:[e("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":c,className:"w-full flex items-center gap-2.5 px-3 py-2 hover:chat-surface-hover-50/3 transition-colors text-left",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center chat-radius-sm bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),n.success?t(xr,{size:12,className:"shrink-0 text-emerald-500 dark:text-emerald-400"}):t(ua,{size:12,className:"shrink-0 text-red-500 dark:text-red-400"}),t("span",{className:"flex-1 min-w-0 text-[0.8125rem] chat-text-secondary-700/80 truncate font-mono",children:ds(n.name,a)}),t(Cr,{size:14,className:"shrink-0 chat-text-muted-400/50 transition-transform duration-200 "+(c?"rotate-180":"")})]}),c&&e("div",{className:"border-t chat-border-200/6",children:[h&&e("div",{className:"px-3 py-2 border-b chat-border-100/4 chat-detail-surface",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] chat-text-muted-500/40 uppercase tracking-wider font-medium",children:s("Input")}),t("pre",{className:"m-0 text-[0.7rem] chat-text-secondary-600/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-40 overflow-y-auto filigran-chat-scrollable",children:d})]}),e("div",{className:"px-3 py-2 chat-detail-surface",children:[t("p",{className:"m-0 mb-1.5 text-[0.6rem] chat-text-muted-500/40 uppercase tracking-wider font-medium",children:s("Output")}),t("pre",{className:"m-0 text-[0.7rem] chat-text-secondary-600/60 font-mono whitespace-pre-wrap break-all leading-relaxed max-h-48 overflow-y-auto filigran-chat-scrollable",children:u||s("(no output)")})]})]})]})},hs=({msg:n,onClose:r,toolLabels:a,t:i})=>{const c=s(null),d=s(null),u=s(null),[h,p]=o(null);l(()=>{p(z(c.current))},[]),l(()=>{const e=e=>{if("Escape"===e.key)return void r();if("Tab"!==e.key)return;const t=u.current;if(!t)return;const n=t.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(0===n.length)return;const a=n[0],o=n[n.length-1],s=document.activeElement;e.shiftKey?s!==a&&t.contains(s)||(e.preventDefault(),o.focus()):s!==o&&t.contains(s)||(e.preventDefault(),a.focus())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r]),l(()=>{if(!h)return;const e=document.activeElement instanceof HTMLElement?document.activeElement:null;return d.current?.focus({preventScroll:!0}),()=>e?.focus({preventScroll:!0})},[h]);const m=n.toolCallCount??n.toolCallTrace?.length??n.toolNames?.length??0,g=n.toolNames??[],f=n.iterations??1,v=n.transferChain??[],w=n.toolCallTrace??[],b=(n.reasoning??"").trim(),x=[f>1?I(i,"{count} iterations",{count:f}):"",1===m?i("1 tool call"):I(i,"{count} tool calls",{count:m}),1===v.length?i("1 transfer"):v.length>1?I(i,"{count} transfers",{count:v.length}):""].filter(Boolean);return t("span",{ref:c,className:"hidden",children:h&&y(t("div",{className:"absolute inset-0 z-[10000] flex items-center justify-center bg-black/30 dark:bg-black/50 p-4",onClick:r,role:"presentation",children:e("div",{ref:u,role:"dialog","aria-modal":"true","aria-label":i("Reasoning details"),onClick:e=>e.stopPropagation(),className:"w-full max-w-md max-h-full flex flex-col chat-radius-md border chat-border-200/10 chat-surface-raised shadow-[0_8px_32px_rgba(0,0,0,0.25)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.6)]",children:[e("div",{className:"px-4 pt-3.5 pb-2.5 border-b chat-border-200/10",children:[e("div",{className:"flex items-center gap-2",children:[t(da,{size:15,className:"text-[var(--chat-accent)]"}),t("span",{className:"flex-1 text-[0.875rem] font-semibold chat-text-900/100",children:i("Reasoning details")}),t("button",{ref:d,type:"button",onClick:r,"aria-label":i("Close"),className:"w-7 h-7 flex items-center justify-center chat-radius-sm hover:chat-surface-hover-100/10 chat-text-muted-500/40 hover:chat-text-secondary-700/70 transition-colors",children:t(Sr,{size:16})})]}),t("p",{className:"m-0 mt-0.5 text-[0.72rem] chat-text-muted-500/40",children:x.join(" · ")})]}),e("div",{className:"px-4 py-3 overflow-y-auto filigran-chat-scrollable flex flex-col gap-3",children:[n.isTruncated&&t(ba,{tone:"warning",children:e("span",{children:[t("span",{className:"font-semibold",children:i("Turn limit reached.")})," ",i("The agent's iteration budget was exhausted - execution stopped before completing all planned steps. The final response is a best-effort summary of work done so far.")]})}),n.interrupted&&t(ba,{tone:"warning",children:e("span",{children:[t("span",{className:"font-semibold",children:i("Interrupted by a server restart.")})," ",i("The server restarted while this turn was running, so it stopped before it could finish.")]})}),b&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(yr,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium chat-text-secondary-500/50",children:i("Model reasoning")})]}),t("div",{className:"chat-radius-md border chat-border-200/6 chat-detail-surface px-2.5 py-2 max-h-44 overflow-y-auto filigran-chat-scrollable",children:t("p",{className:"m-0 whitespace-pre-wrap break-words text-[0.72rem] leading-5 chat-text-secondary-500/45",children:Eo(b)})})]}),w.length>0?t("div",{className:"flex flex-col gap-1.5",children:w.map((e,n)=>t(us,{entry:e,index:n,toolLabels:a,t:i},`${e.name}-${n}`))}):g.length>0&&t("div",{children:g.map((n,r)=>e("div",{className:"flex items-center gap-3 py-2 border-b chat-border-100/4 last:border-0",children:[t("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center chat-radius-sm bg-[var(--chat-accent)]/10 text-[0.65rem] font-medium text-[var(--chat-accent)]",children:r+1}),t(da,{size:12,className:"shrink-0 chat-text-muted-400/50"}),t("span",{className:"text-[0.8125rem] chat-text-secondary-700/80 truncate font-mono",children:ds(n,a)})]},`${n}-${r}`))}),v.length>0&&e("div",{children:[e("div",{className:"flex items-center gap-1.5 mb-1.5",children:[t(vr,{size:13,className:"text-[var(--chat-accent)]/70"}),t("span",{className:"text-[0.72rem] font-medium chat-text-secondary-500/50",children:i("Transfer chain")})]}),t("div",{className:"flex items-center gap-1.5 flex-wrap",children:v.map((n,r)=>e("div",{className:"flex items-center gap-1.5",children:[r>0&&t("span",{className:"chat-text-muted-300/30 text-[0.72rem]",children:"→"}),e("span",{className:"inline-flex items-center gap-1 chat-radius-sm bg-[var(--chat-accent)]/10 px-2 py-0.5 text-[0.72rem] font-medium text-[var(--chat-accent)]",children:[t(br,{size:12}),n.agentName]})]},`${n.agentId}-${r}`))})]})]})]})}),h)})},ps=e=>`${e.filename.trim()}\n${(e.contentType||e.type||"").split(";")[0].trim().toLowerCase()}`;const ms=r(()=>{}),gs="inline-flex items-center gap-1 chat-radius-sm text-[0.7rem] chat-text-muted-400/40 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]";function fs({url:e,requestHeaders:n}){const{src:r,status:a}=lo(e??null,n),[s,i]=o(null);return t("span",{className:"flex h-12 w-24 shrink-0 items-center justify-center overflow-hidden chat-radius-sm border chat-border-200/10",children:"ready"===a&&null!==r&&s!==r?t("img",{src:r,alt:"",loading:"lazy",onError:()=>i(r),className:"h-full w-full object-contain"}):"loading"===a?t("span",{className:"h-full w-full animate-pulse chat-surface-subtle-50/4"}):t(qr,{size:16,className:"chat-text-muted-400/40"})})}function vs({files:n,requestHeaders:r,t:i}){const[c,l]=o(!1),[d,p]=o(!1),m=h(),g=s(null),f=a(ms);return u(()=>{c&&f()},[c,f]),e("div",{className:"pl-1",children:[e("button",{ref:g,type:"button","aria-expanded":c,"aria-controls":m,onClick:()=>{l(!c),p(!0)},className:gs,children:[t(Cr,{size:13,className:"transition-transform"+(c?" rotate-180":"")}),I(i,"Working files ({count})",{count:n.length})]}),t("ul",{id:m,hidden:!c,className:"mt-1.5 flex flex-col gap-1.5",children:n.map(n=>e("li",{className:"flex items-center gap-1.5",children:[d&&n.isImage&&t(fs,{url:n.imageUrl,requestHeaders:r}),n.card,n.superseded&&t("span",{className:"shrink-0 text-[0.7rem] chat-text-muted-400/40",children:i("Superseded")})]},n.key))}),c&&n.length>=8&&e("button",{type:"button","aria-controls":m,onClick:()=>{l(!1),g.current?.focus({preventScroll:!0}),g.current?.scrollIntoView({block:"nearest"})},className:`mt-1.5 ${gs}`,children:[t(Cr,{size:13,className:"rotate-180"}),i("Show less")]})]})}const ws=e=>e.parentElement,bs=e=>getComputedStyle(e).overflowY;function ys(e){return e instanceof Element&&!!e.closest('a[href], button, summary, label, input, textarea, select, [role="button"], [role="link"]')}function xs(e){const t=e.lastIndexOf(".");if(t<=0||t===e.length-1)return;const n=e.slice(t+1);return n.length<=8?n.toUpperCase():void 0}const ks=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);function Cs(e){if(e.contentType?.toLowerCase().startsWith("image/"))return!0;const t=e.type?.toLowerCase();if(t&&ks.has(t))return!0;const n=e.filename.lastIndexOf(".");return n>0&&ks.has(e.filename.slice(n+1).toLowerCase())}const Ns="group-hover/msg:opacity-100 group-focus-within/msg:opacity-100 focus-visible:opacity-100 [@media(hover:none)]:opacity-100",Ss="p-1 chat-radius-sm transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",Ts="hover:text-[var(--chat-accent)] focus-visible:text-[var(--chat-accent)]",As=`opacity-0 ${Ns} ${Ts}`,Is=`opacity-50 ${Ns} ${Ts}`,Es="opacity-100 text-[var(--chat-accent)]",zs=({timestamp:n,locale:r})=>{const a=function(e,t,n=new Date){return e instanceof Date&&!Number.isNaN(e.getTime())?{label:Xa(t,(a=n,(r=e).getFullYear()===a.getFullYear()&&r.getMonth()===a.getMonth()&&r.getDate()===a.getDate()?"time":e.getFullYear()===n.getFullYear()?"date":"dateWithYear")).format(e),full:Xa(t,"full").format(e),iso:e.toISOString()}:null;var r,a}(n,r);return a?t(fa,{title:a.full,children:e("time",{dateTime:a.iso,className:"px-1 text-[0.65rem] tabular-nums chat-text-muted-400/40 select-none",children:[t("span",{"aria-hidden":"true",children:a.label}),t("span",{className:"sr-only",children:a.full})]})}):null},Rs=({text:e,label:n,t:r})=>{const[a,s]=o(!1),i=a?r("Copied!"):n;return t(fa,{title:i,children:t("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText(_a(e||"")),s(!0),setTimeout(()=>s(!1),2e3)}catch{}},"aria-label":i,className:`${Ss} ${a?"opacity-100 text-green-500 dark:text-green-400":As}`,children:t(a?kr:Tr,{size:14})})})},Ds=({value:r,locked:a,pending:o,onChange:s,downRef:i,t:c})=>{const l=h(),d=a||o,u=(e,n)=>{const o=r===e;if(a&&!o)return null;const u="up"===e?aa:ra;return t(fa,{title:a?c("Feedback already submitted"):n,children:t("button",{ref:"down"===e?i:void 0,type:"button",onClick:()=>{d||s(o?null:e)},"aria-label":n,"aria-pressed":o,"aria-disabled":d||void 0,"aria-describedby":a?l:void 0,className:`${Ss} ${o?Es:As} ${d?"cursor-default":""}`,children:t(u,{size:14,filled:o})})})};return e(n,{children:[u("up",c("Good response")),u("down",c("Bad response")),a&&t("span",{id:l,className:"sr-only",children:c("Feedback already submitted")})]})},Ms=({pending:n,onSave:r,onSkip:a,t:s})=>{const[i,c]=o(""),l=h(),d=!n&&!!i.trim();return e("div",{className:"mt-1 flex w-full max-w-[90%] flex-col gap-1.5 chat-radius-md border chat-border-200/10 chat-surface-subtle-50/4 p-2",children:[t("label",{htmlFor:l,className:"text-[0.7rem] chat-text-secondary-600/60",children:s("Tell us what went wrong (optional)")}),t("textarea",{id:l,autoFocus:!0,rows:2,maxLength:2e3,value:i,readOnly:n,onChange:e=>c(e.target.value),onKeyDown:e=>{Da(e)||("Escape"===e.key?(e.preventDefault(),e.stopPropagation(),n||a()):"Enter"===e.key&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),d&&r(i)))},placeholder:s("What could be improved?"),className:"w-full resize-y chat-radius-sm border chat-border-200/10 chat-input-surface-white/0 px-2 py-1 text-[0.75rem] leading-5 chat-text-900/100 placeholder:chat-text-muted-400/30 outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]"}),e("div",{className:"flex justify-end gap-1.5",children:[t("button",{type:"button",onClick:()=>{n||a()},"aria-disabled":n||void 0,className:"chat-radius-sm px-2 py-0.5 text-[0.7rem] chat-text-secondary-500/50 transition-colors hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",children:s("Skip")}),t("button",{type:"button",onClick:()=>{d&&r(i)},"aria-disabled":!d||void 0,className:"chat-radius-sm px-2 py-0.5 text-[0.7rem] text-white bg-[var(--chat-accent)] transition-opacity outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)] "+(d?"hover:opacity-90":"opacity-50 cursor-default"),children:s("Save")})]})]})},_s=({speaking:e,onToggle:n,t:r})=>{const a=r(e?"Stop reading":"Read aloud");return t(fa,{title:a,children:t("button",{type:"button",onClick:n,"aria-label":a,className:`${Ss} ${e?Es:As}`,children:t(e?la:ca,{size:14})})})},Ls=[],Ps=new Set(["PRESENTATION","REPORT","VIDEO"]),js=m(({msg:r,isStreaming:a,agentName:c,logoIcon:l,onRelativeLinkClick:d,onDownloadFile:h,resolveAttachmentUrl:p,onDownloadArtifact:m,onRefreshArtifact:g,requestHeaders:f,feedbackMode:v,feedback:w,onRate:b,onSaveComment:y,onSkipComment:x,locale:k,canSpeak:C,isSpeaking:N,onToggleSpeech:S,openableConversationIds:T,onOpenConversation:A,markerRenderers:I,markerKindList:E=Ls,codeBlockRenderers:z,transformMessageText:R,onArtifactOpen:D,renderMessageExtras:M,messageFooterActions:_,collapseUnnamedFiles:L,toolLabels:P,t:j})=>{const[$,F]=o(!1),H="assistant"===r.role,V=i(()=>B(R,r.content,r)??r.content,[R,r]),K=i(()=>H?"":function(e){return e.trimEnd().replace(/^(?:[ \t]*\r?\n)+/,"")}(V),[H,V]),G=!V,X=s(null),Y=!!w?.commentOpen,J=s(Y);u(()=>{const e=J.current&&!Y;J.current=Y,!e||document.activeElement&&document.activeElement!==document.body||X.current?.focus()},[Y]);const Z=(e,n)=>{const r=p&&Cs(e)?p(e):void 0;return r?t(uo,{src:r,alt:e.filename,requestHeaders:f,maxHeightClass:"max-h-[200px]",onDownload:h?()=>h(e):void 0,t:j},n):ee(e,n)},ee=(n,r)=>{const a="working_file"===n.fileTag,o=!(s=n.size)||s<=0?"":s<1024?`${s} B`:s<1048576?`${(s/1024).toFixed(0)} KB`:`${(s/1048576).toFixed(1)} MB`;var s;return t(fa,{title:j("Download"),className:"inline-flex min-w-0 max-w-[90%]",children:e("button",{type:"button",onClick:()=>h?.(n),className:"group flex w-full min-w-0 items-center gap-2 text-left chat-radius-md border px-2.5 py-1.5 transition-colors cursor-pointer "+(a?"chat-border-200/10 bg-transparent":"chat-border-200/10 chat-surface-subtle-50/4 hover:border-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/5"),children:[t("span",{className:"shrink-0 "+(a?"chat-text-muted-400/40":"text-[var(--chat-accent)]"),children:t(Dr,{size:16})}),e("span",{className:"flex flex-col min-w-0 flex-1",children:[t("span",{className:"truncate text-[0.75rem] chat-text-900/100",children:n.filename}),(n.type||o)&&t("span",{className:"text-[0.65rem] chat-text-muted-400/40 uppercase",children:[n.type,o].filter(Boolean).join(" · ")})]}),t("span",{className:"shrink-0 chat-text-muted-400/30 group-hover:text-[var(--chat-accent)]",children:t(Er,{size:15})})]})},r)},te=(n,r)=>e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border chat-border-200/10 text-[0.7rem] chat-text-secondary-600/60",children:[t(Dr,{size:14}),n]},r),ne=(e,n)=>t(no,{artifact:e,t:j,onDownload:m,onRefresh:g,onOpen:D},n),re=(e,n,o)=>{const s=I?.[e];return!s||a&&!s.renderWhileStreaming?null:t("div",{className:s.fullWidth?"w-full":"w-full max-w-[90%]",children:t(mo,{label:"A chat marker card",resetKey:`${n}\0${a}`,fallback:t(fo,{t:j}),children:t(go,{draw:()=>s.render(n,{message:r,streaming:a})})})},o)},ae=function(e){const t=new Set,n=new Map;for(const r of e)t.has(r.fileId)||(t.add(r.fileId),n.set(ps(r),r.fileId));return new Set(e.filter(e=>n.get(ps(e))!==e.fileId).map(e=>e.fileId))}(r.attachments??[]),oe=(e,t,n)=>{const r=Cs(e);return{key:t,card:n,isImage:r,imageUrl:r?p?.(e):void 0,superseded:ae.has(e.fileId)}},se=r.toolNames&&r.toolNames.length>0||!!(r.reasoning??"").trim()||r.toolCallTrace&&r.toolCallTrace.length>0||r.transferChain&&r.transferChain.length>0||r.isTruncated||r.interrupted,ie=!(!r.isTruncated&&!r.interrupted),ce=r.interrupted?j("Reasoning details — interrupted by a server restart"):r.isTruncated?j("Reasoning details — turn limit reached"):j("Reasoning details"),le=H&&!G&&!a,de=function(e,t=[]){if(!e)return e;const n=U(t),r=e.replace(n.complete,"").replace(n.partial,"");return r===e?e:r.replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}(V,E),ue=i(()=>le&&C?W(V,E):null,[le,C,V,E]),he=(pe=w,me=r.feedback,pe?{value:pe.value,locked:!1}:me?{value:(ge=me.rating,"positive"===ge?"up":"down"),locked:!0}:{value:null,locked:!1});var pe,me,ge;const fe=Ha(r),ve=!H||a||r.stopped||ie||r.attachments?.length||r.artifacts?.length?null:function(e,t,n=[]){if(!t)return null;const r=O(e,!1,n).filter(e=>"text"!==e.type||e.value.trim()),[a]=r;return 1===r.length&&"marker"===a.type&&t[a.kind]?.standalone?{kind:a.kind,args:a.args}:null}(V,I,E);return ve?t("div",{"data-message-id":r.serverId??r.id,"data-testid":"filigran-chat-standalone-marker",className:"flex w-full",children:re(ve.kind,ve.args,"standalone")}):e("div",{"data-message-id":r.serverId??r.id,className:"group/msg flex flex-col "+(H?"items-start":"items-end"),children:[H&&e("div",{className:"flex items-center gap-1.5 mb-1 select-none",children:[t("div",{className:"w-6 h-6 chat-radius-sm flex items-center justify-center bg-gradient-to-br from-[var(--chat-accent)]/20 to-[var(--chat-accent)]/5",children:t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-3 [&>svg]:h-3",children:l})}),t("span",{className:"font-semibold text-xs chat-text-900/100",children:r.agentName??c})]}),!H&&((r.files?.length??0)>0||(r.attachments?.length??0)>0)&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end",children:(()=>{const e=[],t=new Set;return(r.files??[]).forEach((n,r)=>{!(!h||!n.fileId||"done"!==n.uploadStatus)&&n.fileId?(t.add(n.fileId),e.push(Z({fileId:n.fileId,filename:n.name,type:xs(n.name),size:n.size,contentType:n.type},`file-${n.fileId}-${r}`))):e.push(te(n.name,`file-${r}`))}),(r.attachments??[]).forEach((n,r)=>{t.has(n.fileId)||(t.add(n.fileId),e.push(h?Z(n,`att-${n.fileId}-${r}`):te(n.filename,`att-${r}`)))}),e})()}),!H&&(r.conversationRefs?.length??0)>0&&t("div",{className:"flex gap-1.5 flex-wrap mb-1.5 justify-end max-w-[90%]",children:r.conversationRefs.map((r,a)=>{const o=r.title||(r.key?`@${r.key}`:j("Untitled conversation")),s="inline-flex items-center gap-1 max-w-[240px] px-2 py-0.5 rounded-full border text-[0.7rem]",i=e(n,{children:[t(Vr,{size:13,className:"shrink-0"}),t("span",{className:"truncate",children:o})]});return A&&T?.has(r.conversationId)?t(fa,{title:j("Open conversation"),children:t("button",{type:"button",onClick:()=>A(r.conversationId),className:`${s} border-[var(--chat-accent-40)] text-[var(--chat-accent)] hover:bg-[var(--chat-accent)]/10 transition-colors outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]`,children:i})},`ref-${r.conversationId}-${a}`):t(fa,{title:r.key?`@${r.key}`:"",children:t("span",{className:`${s} chat-border-200/10 chat-text-secondary-600/60`,children:i})},`ref-${r.conversationId}-${a}`)})}),H?e("div",{"data-testid":"filigran-chat-assistant-message",className:"flex flex-col gap-1.5 w-full items-start",children:[(()=>{const e=O(V,a,E),n=new Map((r.attachments??[]).map(e=>[e.fileId,e])),o=new Map((r.artifacts??[]).map(e=>[q(e.kind,e.id),e])),s=new Set,i=new Set,c=[];e.forEach((e,r)=>{if("text"===e.type)e.value.trim()&&c.push(t("div",{className:"max-w-[90%] pl-1 py-1 text-[0.8125rem] leading-7",children:t(cs,{content:e.value,streaming:a,onRelativeLinkClick:d,requestHeaders:f,codeBlockRenderers:z,t:j})},`t-${r}`));else if("marker"===e.type){"FILE"===e.kind?s.add(e.args):Ps.has(e.kind)&&i.add(q(e.kind.toLowerCase(),e.args.split("#/")[0]));const t=re(e.kind,e.args,`m-${e.kind}-${r}`);t&&c.push(t)}else if("artifact"===e.type){const t=q(e.kind,e.id),n=o.get(t);n&&!i.has(t)&&(i.add(t),c.push(ne(n,`a-${t}-${r}`)))}else if(h){const t=n.get(e.fileId);t&&(s.add(e.fileId),c.push(Z(t,`f-${e.fileId}-${r}`)))}}),(r.artifacts??[]).forEach(e=>{const t=q(e.kind,e.id);if(!i.has(t)){i.add(t);const n=e.kind.toUpperCase();if(I?.[n]){const r=re(n,e.slideRef?`${e.id}#/${e.slideRef}`:e.id,`orphan-a-${t}`);r&&c.push(r)}else c.push(ne(e,`orphan-a-${t}`))}});const l=[];if((r.attachments??[]).forEach(e=>{if(s.has(e.fileId))return;const t=`orphan-${e.fileId}`,n=!0===L||"function"==typeof L&&!!B(L,e,r);if(I?.FILE){const r=re("FILE",e.fileId,t);if(!r)return;n?l.push(oe(e,t,r)):c.push(r)}else h&&(n?l.push(oe(e,t,ee(e,t))):c.push(Z(e,t)))}),l.length&&c.push(t(vs,{files:l,requestHeaders:f,t:j},"working-files")),0===c.length&&!a&&!r.stopped){const e=!V.trim()&&!r.attachments?.length&&!r.artifacts?.length;c.push(t("span",{className:"pl-1 text-[0.8125rem] chat-text-muted-400/40 italic",children:e?j("No response was generated. Please try again."):"..."},"empty"))}return c})(),r.stopped&&!a&&t("p",{className:"pl-1 text-[0.75rem] italic chat-text-muted-400/40",children:j("Stopped")}),!G&&a&&t("span",{className:"inline-block w-1.5 h-4 bg-[var(--chat-accent)]/70 rounded-full ml-1 animate-pulse"})]}):t("div",{"data-testid":"filigran-chat-user-message",className:"max-w-[90%] chat-user-bubble leading-6 whitespace-pre-wrap break-words",children:K}),M&&t("div",{className:"w-full "+(H?"":"flex justify-end"),children:M(r,{streaming:a})}),!H&&e("div",{className:"mt-0.5 flex items-center justify-end gap-0.5 chat-text-muted-400/40 select-none",children:[!!K&&t(Rs,{text:K,label:j("Copy message"),t:j}),!r.timestampUnknown&&t(zs,{timestamp:r.timestamp,locale:k})]}),(le||H&&!a&&ie)&&e("div",{className:"mt-0.5 flex flex-wrap items-center gap-0.5 chat-text-muted-400/40 select-none",children:[!r.timestampUnknown&&t(zs,{timestamp:r.timestamp,locale:k}),se&&t(fa,{title:ce,children:t("button",{type:"button",onClick:()=>F(e=>!e),className:`${Ss} ${ie?"opacity-100 text-amber-500 dark:text-amber-400 hover:text-amber-600 dark:hover:text-amber-300":Is}`,"aria-label":ce,"aria-haspopup":"dialog","aria-expanded":$,children:t(ie?fr:Fr,{size:14})})}),le&&e(n,{children:[t(Rs,{text:de,label:j("Copy response"),t:j}),v&&t(Ds,{value:he.value,locked:he.locked,pending:!!w?.pending,onChange:e=>b(r,e,w),downRef:X,t:j}),ue&&(we=ue,we.some(e=>/[\p{L}\p{N}]/u.test(e.replace(Q,""))))&&t(_s,{speaking:N,onToggle:()=>S(fe,ue),t:j}),_?.(r,{streaming:a})]})]}),le&&w?.commentOpen&&t(Ms,{pending:w.pending,onSave:e=>y(r,e,w),onSkip:()=>x(r,w),t:j}),le&&w?.error&&t(ba,{tone:"error",className:"mt-1",children:w.error}),$&&t(hs,{msg:r,onClose:()=>F(!1),toolLabels:P,t:j})]});var we});js.displayName="MessageRow";const $s=({messages:n,isLoading:r,agentStatus:a,agentName:h,logoIcon:p,onRelativeLinkClick:m,onDownloadFile:g,resolveAttachmentUrl:f,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:b,miniGameEnabled:y=!0,onPlayWaitingGame:x,waitingGameUrl:k,onMessageFeedback:C,isResumingAfterDecision:N,onSkipWait:S,pendingApprovals:T,onSubmitApprovalDecisions:A,isSubmittingApproval:I,approvalError:E,feedbackUrl:z,conversationId:R,locale:D,openableConversationIds:M,onOpenConversation:_,markerRenderers:L,markerKindList:P,codeBlockRenderers:j,transformMessageText:$,onArtifactOpen:U,renderMessageExtras:O,replaceMessage:W,messageFooterActions:q,transcriptFooter:F,onLoadEarlier:B,collapseUnnamedFiles:H,ttsRoute:V,thinking:K,t:G})=>{const X=s(null),[Y,Q]=o(150),{entries:te,rate:ne,saveComment:re,skipComment:ae}=function({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:a}){const i=sn(),[l,u]=o(()=>({scope:t,entries:{}}));let h=l.entries;l.scope!==t&&(h={},u({scope:t,entries:h}));const p=s({feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:a});d(()=>{p.current={feedbackUrl:e,conversationId:t,requestHeaders:n,onMessageFeedback:r,t:a}});const m=s(0),g=c((e,t)=>u(n=>({...n,entries:{...n.entries,[e]:t}})),[]),f=c((e,t,n)=>u(r=>{const a=r.entries[e];return a&&a.seq===t?{...r,entries:{...r.entries,[e]:n(a)}}:r}),[]),v=c(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,onMessageFeedback:s,t:c}=p.current,l=Ha(e),d=++m.current;if(!r)return g(l,{seq:d,value:t,comment:null,pending:!1,error:null,commentOpen:!1}),void s?.(l,t,e);if(a&&e.serverId){if(g(l,{seq:d,value:t,comment:null,pending:!0,error:null,commentOpen:!1}),!await he(i,r,a,e.serverId,t?{rating:ce(t),comment:null}:null,o)){const e=c(t?"Could not submit feedback.":"Could not retract feedback.");return void f(l,d,()=>n?{...n,seq:d,pending:!1,commentOpen:!1,error:e}:{seq:d,value:null,comment:null,pending:!1,error:e,commentOpen:!1})}f(l,d,e=>({...e,pending:!1,commentOpen:"down"===t})),p.current.onMessageFeedback?.(l,t,e)}},[g,f]),w=c(async(e,t,n)=>{const{feedbackUrl:r,conversationId:a,requestHeaders:o,t:s}=p.current,c=Ha(e),l=de(t);if(!(r&&a&&e.serverId&&l))return void g(c,{...n,commentOpen:!1,error:null});const d=++m.current;g(c,{...n,seq:d,pending:!0,error:null});const u=await he(i,r,a,e.serverId,{rating:"negative",comment:l},o);f(c,d,e=>u?{...e,comment:l,pending:!1,commentOpen:!1}:{...e,pending:!1,error:s("Could not submit feedback.")})},[g,f]);return{entries:h,rate:v,saveComment:w,skipComment:c((e,t)=>g(Ha(e),{...t,commentOpen:!1,error:null}),[g])}}({feedbackUrl:z,conversationId:R,requestHeaders:b,onMessageFeedback:C,t:G}),oe=function(e,t){const n=sn(),[r]=o(Va),a=r||!!t,[i,u]=o(null),h=s(null),p=s(e),m=s(t);d(()=>{p.current=e,m.current=t});const g=s(null),f=c(()=>{const e=g.current;e&&(g.current=null,e.abort.abort(),e.audio?.pause(),e.url&&URL.revokeObjectURL(e.url),u(t=>t===e.id?null:t))},[]),v=c(()=>r?(h.current??=function(e,t,n){let r=0,a=null;const o=e=>{e===r&&null!==a&&(r+=1,a=null,n(null))},s=()=>{null!==a&&(r+=1,a=null,e.cancel(),n(null))};return{speak:(i,c,l)=>{s();const d=c.filter(e=>e.trim());if(!d.length)return!1;const u=r;return a=i,n(i),d.forEach((n,a)=>{const s=a===d.length-1,i=t(n,{lang:l,onEnd:()=>{s&&o(u)},onError:()=>{u===r&&(o(u),e.cancel())}});e.speak(i)}),!0},stop:s,get speakingId(){return a}}}(window.speechSynthesis,(e,{lang:t,onEnd:n,onError:r})=>{const a=new SpeechSynthesisUtterance(e);return t&&(a.lang=t),a.onend=n,a.onerror=r,a},u),h.current):null,[r]),w=c((e,t)=>v()?.speak(e,Z(t),p.current),[v]),b=c(async(e,t,r)=>{const a=new AbortController,o={id:t,abort:a};g.current=o,u(t);const s=Z(r,4096),i=new Audio;o.audio=i;let c=0;try{for await(const t of ee(n,e,s,a.signal)){if(g.current!==o)return;if(!t)throw new Error("TTS failed");o.url&&URL.revokeObjectURL(o.url),o.url=URL.createObjectURL(t);const e=new Promise(e=>{i.onended=()=>e(!0),i.onerror=()=>e(!1)});if(i.src=o.url,await i.play(),!await e)throw new Error("TTS playback failed");if(g.current!==o)return;c+=1}f()}catch(e){if(g.current!==o||e instanceof DOMException&&"AbortError"===e.name)return;f(),w(t,s.slice(c).join(" "))}},[w,f]),y=c((e,t)=>{const n=g.current?.id??h.current?.speakingId??null;if(f(),h.current?.stop(),n===e)return;const r=J(t),a=m.current;a?b(a,e,r):w(e,r)},[w,b,f]),x=c(()=>{f(),h.current?.stop()},[f]);return l(()=>()=>x(),[x]),{supported:a,speakingId:i,toggle:y,stop:x}}(D,V),[se,ie]=o(!0),[ue]=o(()=>function(e,t=Ya,n){let r=!0;const a=e=>{e!==r&&(r=e,n?.(e))};let o=0,s=null;const i=e=>{e.scrollTo({top:e.scrollHeight,behavior:"instant"}),o=e.scrollTop},c=()=>{s&&(t.clear(s.timer),s=null)},l=()=>{c();const t=e();t&&r&&i(t)};return{get following(){return r},reveal:()=>{const n=e();if(!n)return;a(!0),c();const r=Math.max(0,n.scrollHeight-n.clientHeight);n.scrollTo({top:n.scrollHeight,behavior:"smooth"}),o=n.scrollTop,o>=r-1||(s={target:r,timer:t.set(l,1e3)})},keepUp:()=>{const t=e();t&&r&&!s&&i(t)},onScroll:()=>{const t=e();if(!t)return;const n=t.scrollTop,r=n<o-1,i=n>o+1;(r||i)&&(o=n);const c=t.scrollHeight-n-t.clientHeight;r?a(c<=1):i&&c<=100&&a(!0),s&&(r||n>=s.target-1||c<=1)&&l()},leave:()=>{const t=e();!t||t.scrollTop<=0||(a(!1),c())},stay:()=>{const t=e();!t||s||t.scrollHeight-t.scrollTop-t.clientHeight<=1||(a(!1),c())}}}(()=>X.current,void 0,ie));l(()=>{const e=X.current;return e?function(e,t,n=globalThis){const{ResizeObserver:r,MutationObserver:a}=n;if(!r)return()=>{};const o=new r(()=>t());o.observe(e);for(const t of Array.from(e.children))o.observe(t);const s=a?new a(e=>{for(const t of e)for(const e of Array.from(t.addedNodes))1===e.nodeType&&o.observe(e)}):null;return s?.observe(e,{childList:!0}),()=>{o.disconnect(),s?.disconnect()}}(e,ue.keepUp):void 0},[ue]);const pe=s(null),me=(e,t)=>{t instanceof Element&&e.contains(t)&&(function(e,t,n,r){for(let a=e;a&&a!==t;a=n(a))if(a.scrollTop>0&&a.scrollHeight>a.clientHeight&&Za.has(r(a)))return!0;return!1}(t,e,ws,bs)||ue.leave())},ge=n[0]?.id,fe=s(null),[ve,we]=o(void 0),be=void 0!==ve&&ve===(R??null);u(()=>{const e=fe.current,t=e?n.findIndex(t=>t.id===e.firstId):-1;if(e&&t>0)return e.count=t,void Q(e.visible+e.count);Q(150)},[ge]),u(()=>{const e=fe.current;if(!e?.count||Y!==e.visible+e.count)return;fe.current=null;const t=X.current;t&&(t.scrollTop=e.scrollTop+(t.scrollHeight-e.scrollHeight))});const ye=s({runningIn:-1,settledAt:0,stopped:!1,visit:0});l(()=>{const e=ye.current;e.visit+=1,e.stopped=!1},[R]);const xe=async()=>{const e=X.current;if(n.length>Y)return fe.current={firstId:n[0]?.id,visible:Y,count:50,scrollHeight:e?.scrollHeight??0,scrollTop:e?.scrollTop??0},Q(Y+50),50;if(!B||be)return;const t=R??null;we(t);const r={firstId:n[0]?.id,visible:Math.min(n.length,Y),count:0,scrollHeight:e?.scrollHeight??0,scrollTop:e?.scrollTop??0};fe.current=r;const{visit:a}=ye.current;try{const e=await B();return 0===e?fe.current===r&&(fe.current=null):a===ye.current.visit&&(ye.current.stopped=!1),e}finally{we(e=>e===t?void 0:e)}};let ke=0;for(const e of n)"user"===e.role&&(ke+=1);const Ce=s(null);u(()=>{const e=Ce.current;Ce.current={firstMessageId:ge,userMessageCount:ke},fe.current?.count||(!e||e.firstMessageId!==ge||ke>e.userMessageCount?ue.reveal():ue.keepUp())},[n,ge,ke,ue]);const Ne=a?.thinkingContent?.length??0;u(()=>{Ne&&ue.keepUp()},[Ne,ue]);const Se=n.length>Y,Te=i(()=>Se?n.slice(n.length-Y):n,[n,Y,Se]),{speakingId:Ae,stop:Ie}=oe,Ee=null===Ae||n.some(e=>Ha(e)===Ae),ze=s({conversationId:R,userMessageCount:ke});l(()=>{const e=ze.current;ze.current={conversationId:R,userMessageCount:ke},(e.conversationId!==R||ke>e.userMessageCount||!Ee)&&Ie()},[R,ke,Ee,Ie]);let Re=null;if(r)for(let e=n.length-1;e>=0;e--)if("assistant"===n[e].role){Re=n[e].id;break}const De=!!T?.length&&!!A,Me=s(new Set);return e("div",{ref:X,role:"region","aria-label":G("Conversation transcript"),tabIndex:0,onScroll:()=>{ue.onScroll();const e=X.current,t=ye.current;if(!e||ue.following||t.runningIn===t.visit||t.stopped||e.scrollTop>200)return;if(Date.now()-t.settledAt<1e3)return;const{visit:n}=t;t.runningIn=n,xe().then(e=>{0===e&&n===t.visit&&(t.stopped=!0)}).finally(()=>{t.runningIn===n&&(t.runningIn=-1),n===t.visit&&(t.settledAt=Date.now())})},onWheel:e=>{(function(e){return!e.ctrlKey&&e.deltaY<0&&Math.abs(e.deltaY)>Math.abs(e.deltaX)})(e)&&me(e.currentTarget,e.target)},onKeyDown:e=>{var t;e.defaultPrevented||!function(e){return!e.altKey&&(Ja.has(e.key)||" "===e.key&&e.shiftKey)}(e)||(t=e.target,t instanceof HTMLElement&&(t.isContentEditable||t.closest("input, textarea, select")))||(" "===e.key&&ys(e.target)||me(e.currentTarget,e.target))},onPointerDown:e=>{const t=e.currentTarget,n=t.getBoundingClientRect();(function(e){if(1===e.button)return!e.onControl;if(0!==e.button||!e.onContainer||e.x<e.clientWidth)return!1;const t=(e.scrollTop+e.clientHeight)/e.scrollHeight*e.clientHeight;return e.y<=t})({button:e.button,onContainer:e.target===t,onControl:ys(e.target),x:e.clientX-n.left-t.clientLeft,y:e.clientY-n.top-t.clientTop,clientWidth:t.clientWidth,clientHeight:t.clientHeight,scrollTop:t.scrollTop,scrollHeight:t.scrollHeight})&&me(t,e.target)},onTouchStart:e=>{pe.current=Qa(e.touches)},onTouchMove:e=>{const t=Qa(e.touches),n=pe.current;null!==t&&null!==n&&function(e,t){return t-e>4}(n,t)&&me(e.currentTarget,e.target),pe.current=function(e,t){return null===t?null:null===e?t:Math.min(e,t)}(n,t)},onCopy:La,"data-testid":"filigran-chat-transcript",className:"relative flex-1 overflow-y-auto px-4 py-3 flex flex-col gap-4 filigran-chat-scrollable outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--chat-accent-50)]",children:[(Se||B)&&t("div",{className:"flex justify-center",children:e("button",{type:"button",disabled:be,onClick:()=>{xe()},className:"flex items-center gap-1.5 rounded-full border chat-border-200/10 px-3 py-1 text-[0.7rem] chat-text-secondary-500/50 transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)]",children:[t(Cr,{size:13,className:"rotate-180"}),G(be?"Loading earlier messages…":"Load earlier messages")]})}),t(ms.Provider,{value:ue.stay,children:Te.map(e=>{const n=e.id===Re,r=((e,t)=>{if(W)try{const n=W(e,{streaming:t});return"boolean"==typeof n?void 0:n}catch(t){const n=e.serverId??e.id;return void(Me.current.has(n)||(Me.current.add(n),console.error("A replaced chat message failed to render",t)))}})(e,n);if(null===r)return null;const o=((e,n)=>"assistant"===e.role&&!e.content&&n?De?null:t("div",{children:t(Mo,{agentStatus:a,logoIcon:p,t:G,miniGameEnabled:y,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ue.keepUp,onSkipWait:S,...K})},e.id):t(js,{msg:e,isStreaming:n,agentName:h,logoIcon:p,onRelativeLinkClick:m,onDownloadFile:g,resolveAttachmentUrl:f,onDownloadArtifact:v,onRefreshArtifact:w,requestHeaders:b,feedbackMode:"assistant"===e.role?le(e.serverId,z,R,!!C):null,feedback:te[Ha(e)],onRate:ne,onSaveComment:re,onSkipComment:ae,locale:D,canSpeak:oe.supported,isSpeaking:Ae===Ha(e),onToggleSpeech:oe.toggle,openableConversationIds:e.conversationRefs?.length?M:void 0,onOpenConversation:e.conversationRefs?.length?_:void 0,markerRenderers:L,markerKindList:P,codeBlockRenderers:j,transformMessageText:$,onArtifactOpen:U,renderMessageExtras:O,messageFooterActions:q,collapseUnnamedFiles:H,toolLabels:K?.toolLabels,t:G},e.id))(e,n);return void 0===r?o:t("div",{"data-message-id":e.serverId??e.id,"data-testid":"filigran-chat-replaced-message",className:"flex w-full",children:t(mo,{label:"A replaced chat message",resetKey:`${e.id}\0${n}`,fallback:o,children:r})},e.id)})}),N&&!De&&t(Mo,{agentStatus:a,logoIcon:p,t:G,miniGameEnabled:y,onPlayWaitingGame:x,waitingGameUrl:k,keepEndInView:ue.keepUp,...K}),De&&t(io,{proposals:T,onSubmit:A,isSubmitting:I,error:E,t:G},T.map(e=>e.toolCallId).join("|")),F,t("div",{className:"sticky bottom-0 z-10 h-0",children:!se&&t(fa,{title:G("Scroll to bottom"),className:"absolute bottom-1 left-1/2 inline-flex -translate-x-1/2",children:t("button",{type:"button",onClick:()=>{X.current?.focus({preventScroll:!0}),ue.reveal()},"aria-label":G("Scroll to bottom"),className:"rounded-full border chat-border-200/10 chat-menu-surface p-1.5 chat-text-secondary-500/50 shadow-md transition-colors hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent-50)]",children:t(Cr,{size:16})})})})]})};function Us(e){const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}const Os=({call:n,agentName:r,logoIcon:a,processingLabel:i,onInterrupt:c,onToggleMute:d,onEnd:u,t:h})=>{const[p,m]=o(0);l(()=>{const e=window.setInterval(()=>m(e=>e+1),1e3);return()=>window.clearInterval(e)},[]);const g=s(null);l(()=>{g.current?.scrollIntoView?.({block:"end"})},[n.lines.length,n.heard]);const{phase:f,muted:v}=n,w="listening"===f?h(v?"Muted":"Listening..."):"processing"===f?i:"speaking"===f?h("Speaking…"):"error"===f?h("Failed to get a response. Resuming…"):"",b="speaking"===f||"processing"===f,y="speaking"===f||"listening"===f&&!v,x="w-12 h-12 rounded-full flex items-center justify-center border transition-colors disabled:opacity-40";return e("div",{role:"dialog","aria-label":h("Voice call"),"data-testid":"filigran-chat-voice-call",className:"absolute inset-0 z-40 flex flex-col rounded-[inherit] chat-surface-raised",children:[e("div",{className:"flex items-center justify-between px-4 py-3 text-[0.7rem] uppercase tracking-[1px] chat-text-secondary-500/50",children:[t("span",{children:h("Voice call")}),t("span",{className:"font-mono normal-case tracking-normal",children:Us(p)})]}),e("div",{className:"flex flex-1 min-h-0 flex-col items-center justify-center gap-1 px-4",children:[e("button",{type:"button",onClick:b?c:void 0,disabled:!b,"aria-label":"speaking"===f?h("Skip response"):"processing"===f?h("Cancel question"):r,className:`relative mb-4 flex h-28 w-28 items-center justify-center rounded-full border-2 transition-colors ${"error"===f?"border-amber-400/50":y?"border-[var(--chat-accent)]":"border-[var(--chat-accent-40)]"} ${b?"cursor-pointer":"cursor-default"}`,children:[y&&t("span",{className:"absolute inset-0 rounded-full border border-[var(--chat-accent-40)] animate-ping","aria-hidden":"true"}),"processing"===f&&t("span",{className:"absolute inset-3 rounded-full border-2 border-dashed border-[var(--chat-accent-40)] animate-spin","aria-hidden":"true"}),t("span",{className:"text-[var(--chat-accent)] [&>svg]:w-10 [&>svg]:h-10",children:a})]}),t("h2",{className:"max-w-full truncate text-base font-semibold chat-text-900/100",children:r}),t("p",{"aria-live":"polite",className:"text-center text-[0.8125rem] chat-text-secondary-500/60",children:w}),"speaking"===f&&t("p",{className:"text-[0.7rem] chat-text-muted-400/40",children:h("Speak or tap to interrupt")}),"processing"===f&&t("p",{className:"text-[0.7rem] chat-text-muted-400/40",children:h("Tap to cancel")}),"listening"===f&&n.heard&&e("p",{className:"mt-3 max-w-md text-center text-[0.8125rem] italic chat-text-secondary-500/50",children:["“",n.heard,"”"]})]}),n.lines.length>0&&t("div",{className:"max-h-[35%] overflow-y-auto filigran-chat-scrollable px-4 pb-2",children:e("div",{className:"flex flex-col gap-2",children:[n.lines.map((n,r)=>t("div",{className:"flex "+("user"===n.role?"justify-end":"justify-start"),children:e("div",{className:"max-w-[85%] chat-radius-md px-3 py-1.5 text-[0.75rem] leading-5 "+("user"===n.role?"bg-[var(--chat-accent)]/10 chat-text-800/80":"chat-surface-subtle-100/6 chat-text-secondary-700/70"),children:[n.agent&&e("div",{className:"mb-0.5 text-[0.7rem] font-medium text-[var(--chat-accent)]",children:[n.agent.name,n.agent.failed&&e("span",{className:"font-normal chat-text-secondary-500/50",children:[" · ",h("Did not answer")]})]}),n.content.length>200?`${n.content.slice(0,200)}…`:n.content]})},r)),t("div",{ref:g})]})}),e("div",{className:"flex items-center justify-center gap-5 px-4 pb-5 pt-3",children:[t("button",{type:"button",onClick:d,"aria-label":h(v?"Unmute microphone":"Mute microphone"),"aria-pressed":v,className:`${x} ${v?"border-red-400/40 bg-red-500/10 text-red-500":"chat-border-200/10 chat-text-secondary-600/70 hover:chat-surface-hover-100/6"}`,children:t(v?Gr:Kr,{size:20})}),t("button",{type:"button",onClick:u,"aria-label":h("End voice call"),className:"w-14 h-14 rounded-full flex items-center justify-center bg-red-500 text-white hover:bg-red-600 transition-colors",children:t(Yr,{size:22})}),t("button",{type:"button",onClick:c,disabled:"speaking"!==f,"aria-label":h("Skip response"),className:`${x} chat-border-200/10 chat-text-secondary-600/70 hover:chat-surface-hover-100/6`,children:t(la,{size:20})})]})]})},Ws=({firstName:r,agentName:a,t:o})=>{if(!a)return t(n,{children:I(o,"How can I help you, {name}?",{name:r})});const{before:s,after:i,hasSlot:c}=E(o,"How can {agent} help you, {name}?","agent",{name:r});return e(n,{children:[s,c&&t("span",{className:"text-[var(--chat-accent)]",children:a}),i]})},qs=({firstName:n,logoIcon:r,promptSuggestions:a,onPromptClick:o,agentName:s,suggestionsLoading:i=!1,t:c})=>e("div",{className:"flex-1 flex flex-col items-center justify-center px-6 pb-8",children:[t("span",{className:"text-[var(--chat-accent)] mb-3 [&>svg]:w-10 [&>svg]:h-10",children:r}),t("h2",{className:"text-xl font-medium text-center chat-text-900/100",style:{fontFamily:'"Geologica", sans-serif',animation:"chat-fade-in 0.35s ease-out"},children:t(Ws,{firstName:n,agentName:s,t:c})},s??"default"),o&&(i||a.length>0)&&t("div",{role:"group","aria-label":c("Suggestions"),"aria-busy":i||void 0,className:"mt-5 flex w-full max-w-[480px] flex-wrap justify-center gap-2",children:i?[0,1,2].map(e=>t("div",{"aria-hidden":!0,className:"h-8 w-32 rounded-full border chat-border-200/10 chat-skeleton-card animate-pulse"},e)):a.map(e=>t(fa,{title:e,className:"inline-flex min-w-0 max-w-full",children:t("button",{type:"button",onClick:()=>o(e),className:"h-8 max-w-full truncate rounded-full border chat-border-200/10 bg-transparent px-3 text-[0.8125rem] chat-text-800/100 transition-colors hover:bg-[var(--chat-accent-10)] hover:border-[var(--chat-accent-50)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--chat-accent)]",children:e})},e))})]}),Fs=m(function({draw:e,query:r}){return t(n,{children:e({query:r})})}),Bs="application/x-filigran-conversation";const Hs=224,Vs=256,Ks=480;function Gs(e){return Math.round(Math.min(Math.max(e,Hs),Ks))}const Xs="p-1 chat-radius-sm chat-text-muted-400/30 hover:chat-icon-hover transition-colors disabled:opacity-40 disabled:pointer-events-none",Ys=({conversations:r,loading:a,failed:c=!1,onRetry:d,activeConversationId:u,collapsed:h,onToggleCollapsed:p,onSelect:m,onDelete:g,onRename:f,onNewChat:v,workspaces:w,storageKeyPrefix:b,expandedGroups:y,onGroupOpenedChange:x,rowActions:k,headerActions:C,sections:N,onClearAll:S,clearAllAction:T,searchThreshold:A=7,channelLabel:I,notice:E,onNotice:z,t:R})=>{const[D,M]=o(""),[_,L]=o(null),[P,j]=o(""),$=s(!1),U=Wt(b,jt),[O,W]=o(()=>function(e){try{const t=JSON.parse(Ft("local",e)??"[]");return new Set(Array.isArray(t)?t.filter(e=>"string"==typeof e):[])}catch{return new Set}}(U)),q=i(()=>y?new Set(y):null,[y]),[F,B]=o(!1),H=Wt(b,$t),[K,G]=o(()=>"1"===Ft("local",H)),X=e=>{G(e),Bt("local",H,e?"1":null)},Y=Wt(b,Pt),[J,Q]=o(()=>function(e){const t=Number.parseInt(Ft("local",e)??"",10);return Number.isNaN(t)?Vs:Gs(t)}(Y)),Z=(e,t)=>{$.current=!1,L(e),j(t)},ee=()=>{if($.current)return;$.current=!0;const e=_,t=P.trim();L(null),e&&t&&f?.(e,t)},te=()=>{$.current=!0,L(null)},ne=(e,t)=>{q&&x?.(e,t)},re=(e,t)=>z?.(e||R(t)),ae=async(e,t)=>{w&&!function(e,t,n){const r=e.find(e=>e.conversationId===t);return!!r&&(r.workspaceId??null)===n}(r,e,t)&&await w.onMove(e,t)},oe="function"==typeof N,se=oe||r.length>A;l(()=>{se||M("")},[se]);const ie=se?D.trim():"",ce=ie.toLowerCase(),le=R(oe?"None of your conversations matches":"No conversation matches"),de=i(()=>ce?e=>function(e,t){return[e.title,e.lastMessagePreview,e.agentName].some(e=>!!e&&e.toLowerCase().includes(t))}(e,ce):void 0,[ce]),ue=i(()=>de?r.filter(de):r,[r,de]),he=i(()=>w?function(e,t,n={}){const{matches:r}=n,a=r?e.filter(r):e,o=new Set(t.map(e=>e.id)),s=new Set(e.map(e=>e.workspaceId).filter(e=>!!e)),i=new Map,c=[],l=[];for(const e of a){const t=e.workspaceId??null;t?o.has(t)?i.set(t,[...i.get(t)??[],e]):c.push(e):l.push(e)}const d=[];for(const e of Se(t)){const t=i.get(e.id)??[];(e.canManage||s.has(e.id))&&(r&&0===t.length||d.push({workspace:e,key:e.id,conversations:t}))}return c.length>0&&d.push({workspace:null,key:"__elsewhere__",conversations:c}),{groups:d,unfiled:l}}(r,w.list,{matches:de}):null,[r,w,de]),pe=q?new Set((he?.groups??[]).map(e=>e.key).filter(e=>!q.has(e))):O,me=w?function(e){return Se(e.filter(e=>e.canManage))}(w.list):[],ge=!a&&!ce&&0===r.length,fe=K||F||!!w?.pendingWorkspaceId&&!u,ve=i(()=>new Map((w?.list??[]).map(e=>[e.id,e.name])),[w]);if(h)return e("div",{className:"flex flex-col items-center gap-1 border-r chat-border-200/10 px-2 py-3 shrink-0",children:[t(fa,{title:R("Show conversations"),children:t("button",{type:"button",onClick:p,"aria-label":R("Show conversations"),"aria-expanded":!1,className:"w-8 h-8 flex items-center justify-center chat-radius-sm chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(Zr,{size:17})})}),t(fa,{title:R("New conversation"),children:t("button",{type:"button",onClick:()=>v(),"aria-label":R("New conversation"),className:"w-8 h-8 flex items-center justify-center chat-radius-sm chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(zr,{size:17})})})]});const we=e=>t(ri,{conversation:e,isActive:e.conversationId===u,isEditing:e.conversationId===_,draftTitle:P,onDraftTitleChange:j,onCommitRename:ee,onCancelRename:te,onStartRename:f?Z:void 0,onSelect:m,onDelete:g,fileable:w?me:void 0,onMove:ae,actions:k,channel:V(e.channel,I),workspaceName:w&&e.workspaceId?ve.get(e.workspaceId)??R("Other workspaces"):null,t:R},e.conversationId);return e("div",{className:"relative shrink-0 flex flex-col border-r chat-border-200/10",style:{width:J},children:[t(Js,{width:J,onResize:(e,t)=>{Q(e),t&&Bt("local",Y,e===Vs?null:String(e))},t:R}),e("div",{className:"flex items-center gap-1 px-3 py-3",children:[e("button",{type:"button",onClick:()=>v(),className:"flex-1 flex items-center gap-2 chat-radius-sm border chat-border-200/10 px-3 py-1.5 text-[0.8125rem] chat-text-secondary-700/70 hover:border-[var(--chat-accent)]/40 hover:text-[var(--chat-accent)] transition-colors",children:[t(zr,{size:15}),R("New conversation")]}),C,t(fa,{title:R("Hide conversations"),children:t("button",{type:"button",onClick:p,"aria-label":R("Hide conversations"),"aria-expanded":!0,className:"w-8 h-8 flex items-center justify-center shrink-0 chat-radius-sm chat-text-muted-400/30 hover:chat-surface-hover-100/10 transition-colors",children:t(Zr,{size:17})})})]}),se&&t("div",{className:"px-3 pb-2",children:e("div",{className:"relative",children:[t(Jr,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 chat-text-muted-400/40"}),t("input",{type:"text",value:D,onChange:e=>M(e.target.value),onKeyDown:e=>{"Escape"!==e.key||Da(e)||M("")},placeholder:R("Search conversations..."),"aria-label":R("Search conversations..."),className:"w-full h-7 pl-7 pr-2 chat-radius-sm chat-surface-subtle-100/6 text-[0.75rem] chat-text-900/100 placeholder:chat-text-muted-400/40 outline-hidden focus:ring-1 focus:ring-[var(--chat-accent)]"})]})}),e("div",{className:"flex-1 overflow-y-auto px-2 pb-3 filigran-chat-scrollable",children:[a&&0===r.length&&t("div",{className:"px-3 py-2",children:t(Na,{size:16})}),c&&!a&&0===r.length?t(ka,{onRetry:()=>d?.(),className:"px-3 py-2",t:R}):e(n,he&&w?{children:[!ce&&e("div",{className:"mb-1",children:[e("div",{className:"group/wsh flex items-center gap-1 chat-radius-sm px-1.5 py-1 hover:chat-surface-hover-100/6",children:[e("button",{type:"button",onClick:()=>X(!fe),"aria-expanded":fe,className:"flex min-w-0 flex-1 items-center gap-1.5 text-left",children:[t(Nr,{size:12,className:"shrink-0 chat-text-muted-400/30 transition-transform "+(fe?"rotate-90":"")}),t(_r,{size:14,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate text-[0.8125rem] font-medium chat-text-800/80",children:R("Workspaces")}),t("span",{className:"ml-auto shrink-0 pr-1 text-[0.625rem] tabular-nums chat-text-muted-400/30",children:he.groups.length})]}),t(fa,{title:R("New workspace"),children:t("button",{type:"button",onClick:()=>{X(!0),B(!0)},"aria-label":R("New workspace"),className:Xs,children:t(Pr,{size:14})})})]}),fe&&e("div",{className:"pl-2",children:[F&&t(ei,{placeholder:R("Workspace name"),onSubmit:async e=>{if(B(!1),!e)return;const t=await w.onCreate(e);t.ok?t.workspace&&ne(t.workspace.id,!0):re(t.error,"The workspace could not be created")},onCancel:()=>B(!1)}),he.groups.map(e=>t(ti,{workspace:e.workspace,count:e.conversations.length,open:Te(e.key,pe,e,u),toggleable:Ae(e,u),pending:!!e.workspace&&w.pendingWorkspaceId===e.workspace.id&&!u,onToggle:()=>{return t=e.key,void(q?ne(t,!q.has(t)):W(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Bt("local",U,JSON.stringify([...n])),n}));var t},onNewChat:w.onNewChat,onRename:async(e,t)=>{const n=await w.onRename(e,t);n.ok||re(n.error,"The workspace could not be renamed")},onDelete:async e=>{const t=await w.onDelete(e);t.ok||re(t.error,"The workspace could not be deleted")},onDropConversation:t=>e.workspace&&void ae(t,e.workspace.id),t:R,children:e.conversations.length>0?e.conversations.map(we):t(Zs,{t:R})},e.key))]})]}),e(Qs,{onDropConversation:e=>{ae(e,null)},accepts:!0,children:[e("div",{className:"flex items-center justify-between px-2 pb-1 pt-2",children:[t("span",{className:"text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",children:R("Conversations")}),t(fa,{title:R("New conversation outside a workspace"),children:t("button",{type:"button",onClick:()=>v(),"aria-label":R("New conversation outside a workspace"),className:Xs,children:t(zr,{size:13})})})]}),ue.map(we),ge&&t("p",{className:"px-3 py-1.5 text-[0.65rem] chat-text-muted-400/30",children:R("No conversations yet")})]}),ce&&0===ue.length&&t("p",{className:"px-3 py-2 text-[0.75rem] chat-text-muted-400/40",children:le})]}:{children:[!a&&0===r.length&&t("p",{className:"px-3 py-2 text-[0.75rem] chat-text-muted-400/40",children:R("No conversations yet")}),r.length>0&&0===ue.length&&t("p",{className:"px-3 py-2 text-[0.75rem] chat-text-muted-400/40",children:le}),ue.map(we)]}),"function"==typeof N?t(Fs,{draw:N,query:ie}):N,S&&r.length>0&&!ce&&t(xa,{onClear:S,action:T,className:"px-2 pt-3",iconButtonClass:Xs,t:R})]}),E&&t(ba,{tone:"error",className:"mx-3 mb-3",children:E})]})},Js=({width:e,onResize:n,t:r})=>{const a=s(null),[i,c]=o(!1),l=()=>{if(!a.current)return;const{last:e}=a.current;a.current=null,c(!1),n(e,!0)};return t("div",{role:"separator","aria-orientation":"vertical","aria-label":r("Resize the conversation list"),"aria-valuemin":Hs,"aria-valuemax":Ks,"aria-valuenow":e,tabIndex:0,onPointerDown:t=>{0===t.button&&(t.preventDefault(),a.current={x:t.clientX,width:e,last:e},t.currentTarget.setPointerCapture?.(t.pointerId),c(!0))},onPointerMove:e=>{a.current&&(a.current.last=Gs(a.current.width+e.clientX-a.current.x),n(a.current.last,!1))},onPointerUp:l,onPointerCancel:l,onDoubleClick:()=>n(Vs,!0),onKeyDown:t=>{const r="ArrowLeft"===t.key?e-16:"ArrowRight"===t.key?e+16:"Home"===t.key?Hs:"End"===t.key?Ks:null;null!==r&&(t.preventDefault(),n(Gs(r),!0))},className:"group absolute inset-y-0 -right-1 z-10 w-2 cursor-col-resize touch-none outline-hidden",children:t("span",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 transition-colors "+(i?"bg-[var(--chat-accent)]":"group-hover:bg-[var(--chat-accent)]/40 group-focus-visible:bg-[var(--chat-accent)]")})})},Qs=({onDropConversation:e,accepts:n,children:r,className:a=""})=>{const[i,c]=o(!1),l=s(0),d=e=>e.dataTransfer.types.includes(Bs);return t("div",{className:`chat-radius-sm transition-colors ${i?"bg-[var(--chat-accent)]/10 ring-1 ring-[var(--chat-accent)]/40":""} ${a}`,...n?{onDragEnter:e=>{d(e)&&(l.current+=1,c(!0))},onDragOver:e=>{d(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},onDragLeave:e=>{d(e)&&(l.current=Math.max(0,l.current-1),0===l.current&&c(!1))},onDrop:t=>{if(!d(t))return;t.preventDefault(),l.current=0,c(!1);const n=t.dataTransfer.getData(Bs);n&&e(n)}}:{},children:r})},Zs=({t:n})=>{const{before:r,after:a,hasSlot:o}=E(n,"Drop a conversation here, or start one with {icon}.","icon");return e("p",{className:"px-3 py-1.5 text-[0.65rem] chat-text-muted-400/30",children:[r,o&&t("span",{role:"img","aria-label":n("New conversation in this workspace"),className:"inline-block align-[-1px]",children:t(zr,{size:11})}),a]})},ei=({initial:e="",placeholder:n,onSubmit:r,onCancel:a})=>{const[i,c]=o(e),d=s(!1),u=s(null);l(()=>{u.current?.focus(),u.current?.select()},[]);const h=()=>{d.current||(d.current=!0,r(i.trim()))};return t("input",{ref:u,value:i,maxLength:200,onChange:e=>c(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),Da(e)||("Enter"===e.key&&h(),"Escape"===e.key&&(d.current=!0,a()))},onBlur:h,placeholder:n,"aria-label":n,className:"mx-2 mb-1 w-[calc(100%-1rem)] chat-radius-sm chat-input-surface-white/10 px-2 py-1 text-[0.8125rem] chat-text-900/100 outline-hidden ring-1 ring-[var(--chat-accent)]"})},ti=({workspace:r,count:a,open:s,toggleable:i,pending:c,onToggle:l,onNewChat:d,onRename:u,onDelete:h,onDropConversation:p,t:m,children:g})=>{const[f,v]=o(!1),[w,b]=o(!1),y=!!r?.canManage,x=!!r&&r.isDefault&&r.isOwn;return e(Qs,{onDropConversation:p,accepts:y,className:"mb-0.5",children:[e("div",{className:"group/ws flex items-center gap-1 chat-radius-sm px-1.5 py-1 hover:chat-surface-hover-100/6",children:[f&&r?t(ei,{initial:r.name,placeholder:m("Workspace name"),onSubmit:e=>{v(!1),e&&e!==r.name&&u(r.id,e)},onCancel:()=>v(!1)}):e("button",{type:"button",onClick:l,disabled:!i,"aria-expanded":s,className:"flex min-w-0 flex-1 items-center gap-1.5 text-left disabled:cursor-default",children:[t(Nr,{size:12,className:"shrink-0 chat-text-muted-400/30 transition-transform "+(s?"rotate-90":"")}),t(_r,{size:14,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate text-[0.8125rem] font-medium chat-text-800/80",children:r?r.name:m("Other workspaces")}),x&&t("span",{className:"shrink-0 chat-radius-sm bg-[var(--chat-accent)]/10 px-1 text-[0.6rem] text-[var(--chat-accent)]",children:m("default")}),t("span",{className:"ml-auto shrink-0 pr-1 text-[0.625rem] tabular-nums chat-text-muted-400/30",children:a})]}),r&&y&&!f&&t("span",{className:"flex shrink-0 items-center opacity-0 group-hover/ws:opacity-100 focus-within:opacity-100 transition-opacity",children:e(n,w?{children:[t("span",{className:"px-1 text-[0.65rem] text-red-600 dark:text-red-400",children:m("Delete?")}),t("button",{type:"button",onClick:()=>{b(!1),h(r.id)},"aria-label":m("Delete workspace"),className:`${Xs} hover:text-red-500`,children:t(kr,{size:13})}),t("button",{type:"button",onClick:()=>b(!1),"aria-label":m("Cancel"),className:Xs,children:t(Sr,{size:13})})]}:{children:[t(fa,{title:m("New conversation in this workspace"),children:t("button",{type:"button",onClick:()=>d(r.id),"aria-label":m("New conversation in this workspace"),className:Xs,children:t(zr,{size:13})})}),t(fa,{title:m("Rename workspace"),children:t("button",{type:"button",onClick:()=>v(!0),"aria-label":m("Rename workspace"),className:Xs,children:t(Xr,{size:13})})}),!r.isDefault&&t(fa,{title:m("Delete workspace"),children:t("button",{type:"button",onClick:()=>b(!0),"aria-label":m("Delete workspace"),className:`${Xs} hover:text-red-500`,children:t(oa,{size:13})})})]})})]}),s&&e("div",{className:"space-y-0.5 pb-1 pl-3",children:[c&&e("div",{className:"flex items-center gap-2 chat-radius-sm bg-[var(--chat-accent)]/10 px-2.5 py-1.5 text-[0.75rem] text-[var(--chat-accent)]",children:[t(zr,{size:12}),m("New conversation — send a message to start it")]}),g]})]})},ni=({icon:e})=>t(ma,{icon:e,size:14,fallback:t(br,{size:13}),imageClassName:"h-4 w-4 chat-radius-sm object-cover",emojiClassName:"text-[0.8125rem] leading-none"}),ri=({conversation:r,isActive:a,isEditing:i,draftTitle:c,onDraftTitleChange:l,onCommitRename:d,onCancelRename:u,onStartRename:h,onSelect:p,onDelete:m,fileable:g,onMove:f,actions:v,channel:w,workspaceName:b=null,t:y})=>{const[x,k]=o(!1),C=s(null),N=!!g&&!i;return e("div",{role:"button",tabIndex:0,"aria-current":a,draggable:N,onDragStart:N?e=>{e.dataTransfer.setData(Bs,r.conversationId),e.dataTransfer.effectAllowed="move"}:void 0,onClick:()=>p(r.conversationId),onKeyDown:e=>{e.target===e.currentTarget&&("Enter"!==e.key&&" "!==e.key||(e.preventDefault(),p(r.conversationId)))},className:"group relative flex w-full items-start gap-2.5 chat-radius-sm px-2.5 py-2 text-left cursor-pointer transition-colors "+(a?"bg-[var(--chat-accent)]/10":"hover:chat-surface-hover-100/6"),children:[t("span",{className:"mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center chat-radius-sm "+(a?"bg-[var(--chat-accent)]/20 text-[var(--chat-accent)]":"chat-surface-subtle-100/6 chat-text-muted-400/30"),children:t(ni,{icon:r.agentIcon})}),e("span",{className:"min-w-0 flex-1",children:[i?t("input",{autoFocus:!0,value:c,onChange:e=>l(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{e.stopPropagation(),Da(e)||("Enter"===e.key&&d(),"Escape"===e.key&&u())},onBlur:d,"aria-label":y("Conversation title"),className:"w-full chat-radius-sm chat-input-surface-white/10 px-1.5 py-0.5 text-[0.8125rem] chat-text-900/100 outline-hidden ring-1 ring-[var(--chat-accent)]"}):t(fa,{title:r.title||y("Untitled conversation"),truncated:!0,children:t("span",{className:"block min-w-0 truncate text-[0.8125rem] "+(a?"chat-text-900/100":"chat-text-secondary-700/70"),children:r.title||y("Untitled conversation")})}),r.lastMessagePreview&&!i&&t("span",{className:"block truncate text-[0.7rem] chat-text-secondary-500/50",children:r.lastMessagePreview}),(r.agentName||r.updatedAt||w||b)&&!i&&e("span",{className:"flex min-w-0 items-center gap-1 text-[0.65rem] chat-text-muted-400/30",children:[w&&t(fa,{title:I(y,"Started in {channel}",{channel:w}),children:t("span",{role:"img","aria-label":I(y,"Started in {channel}",{channel:w}),className:"flex shrink-0",children:t(Vr,{size:10})})}),b&&e("span",{className:"flex min-w-[4.5rem] max-w-[50%] shrink items-center gap-0.5","data-testid":"filigran-chat-row-workspace",children:[t(_r,{size:10,className:"shrink-0 text-[var(--chat-accent)]"}),t(fa,{title:b,truncated:!0,children:t("span",{className:"min-w-0 truncate",children:b})})]}),r.agentName&&t(fa,{title:r.agentName,truncated:!0,children:t("span",{"data-agent-pill":"",className:"min-w-0 truncate rounded-full border chat-border-200/10 chat-surface-subtle-100/6 px-1.5 leading-4 chat-text-secondary-500/50",children:r.agentName})}),r.updatedAt&&t("span",{className:"shrink-0 whitespace-nowrap",children:M(r.updatedAt,y)})]})]}),!i&&e("span",{"data-row-actions":"",className:"pointer-events-none absolute right-1.5 top-1/2 flex -translate-y-1/2 chat-radius-sm border chat-border-200/10 chat-menu-surface opacity-0 shadow-sm transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100",children:[v&&t("span",{className:"flex",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:v(r)}),N&&e(n,{children:[t(fa,{title:x?"":y("Move to workspace"),children:t("button",{ref:C,type:"button",onClick:e=>{e.stopPropagation(),k(e=>!e)},"aria-label":y("Move to workspace"),"aria-expanded":x,className:"p-1 chat-radius-sm chat-text-muted-400/30 hover:text-[var(--chat-accent)]",children:t(Lr,{size:13})})}),t(Ca,{open:x,onClose:()=>k(!1),anchorRef:C,placement:"bottom-end",width:220,children:e("div",{className:"py-1",onClick:e=>e.stopPropagation(),children:[t("p",{className:"px-3 pb-1 pt-1.5 text-[0.625rem] font-medium uppercase tracking-wide chat-text-muted-400/40",children:y("Move to workspace")}),g.map(n=>e("button",{type:"button",disabled:n.id===r.workspaceId,onClick:()=>{k(!1),f(r.conversationId,n.id)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] chat-text-secondary-700/80 hover:chat-surface-hover-100/10 disabled:opacity-40",children:[t(_r,{size:13,className:"shrink-0 text-[var(--chat-accent)]"}),t("span",{className:"truncate",children:n.name}),n.id===r.workspaceId&&t(kr,{size:12,className:"ml-auto shrink-0"})]},n.id)),t("div",{className:"my-1 h-px chat-border-fill-200/10"}),e("button",{type:"button",disabled:!r.workspaceId,onClick:()=>{k(!1),f(r.conversationId,null)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[0.8125rem] chat-text-secondary-700/80 hover:chat-surface-hover-100/10 disabled:opacity-40",children:[t(Sr,{size:13,className:"shrink-0"}),y("Remove from workspace")]})]})})]}),h&&t(fa,{title:y("Rename conversation"),children:t("button",{type:"button",onClick:e=>{e.stopPropagation(),h(r.conversationId,r.title||"")},"aria-label":y("Rename conversation"),className:"p-1 chat-radius-sm chat-text-muted-400/30 hover:text-[var(--chat-accent)]",children:t(zr,{size:13})})}),t(fa,{title:y("Delete conversation"),children:t("button",{type:"button",onClick:e=>{e.stopPropagation(),m(r.conversationId)},"aria-label":y("Delete conversation"),className:"p-1 chat-radius-sm chat-text-muted-400/30 hover:text-red-500 dark:hover:text-red-400",children:t(oa,{size:13})})})]})]})},ai=new Set([502,503,504]),oi=new Set([401,403]),si=g(function(e,n){const r=s(e.onSessionEnded);r.current=e.onSessionEnded;const a=s("");a.current=Me(e.requestHeaders);const o=i(()=>{let e=null;const t=t=>{r.current&&e!==a.current&&(e=a.current,B(r.current,t))};return{sessionEnded:t,fetch:(n=()=>r.current?t:void 0,async(e,t)=>{const r=await globalThis.fetch(e,t),a=401===r.status?n():void 0;return a&&"function"==typeof r.clone&&r.clone().json().then(e=>{const t=function(e){if(!e||"object"!=typeof e)return null;const t=e.detail;if(!t||"object"!=typeof t)return null;const{code:n,reason:r}=t;return"session_expired"!==n?null:{reason:"string"==typeof r&&r?r:void 0}}(e);t&&a(t.reason)}).catch(()=>{}),r})};var n},[]);return t(on,{value:o,children:t(pa,{value:e.renderAgentIcon,children:t(ii,{...e,ref:n})})})}),ii=g(function({mode:n,onClose:r,onModeChange:u,topOffset:h=0,apiBaseUrl:p,apiEndpoints:m,agentDashboardUrl:g,waitingGameUrl:v,user:w,t:b,accentColor:y="#7b5cff",logoIcon:x,promptSuggestions:k,draftBorderColor:N,resizable:S=!1,onWidthChange:T,onResizeStart:A,onResizeEnd:E,disableFileManagement:z=!1,onRelativeLinkClick:R,onDownloadError:D,maxFileCount:M,maxTotalSize:_,maxFileSize:L,acceptFileTypes:j,onFileRefused:$,placeholder:U,requestHeaders:O,pageContext:q,pushContentSelector:F,backendType:H="rest",miniGameEnabled:K=!0,onPlayWaitingGame:G,notifyOnComplete:X=!0,onTaskComplete:Y,onMessageFeedback:Q,locale:re,disableImagePreviews:oe=!1,contextUsageEnabled:se=!0,composerToolbar:ce,storageKeyPrefix:le,conversationId:de,onConversationChange:he,initialAgent:pe,onAgentChange:me,readOnly:ge=!1,readOnlyNotice:fe,getRequestExtras:ve,onStreamEvent:we,markerRenderers:ye,codeBlockRenderers:xe,transformMessageText:ke,onArtifactOpen:Ce,headerActions:Se,banner:Te,composerHeader:Ae,transcriptFooter:Ie,welcome:Ee,renderMessageExtras:ze,replaceMessage:Re,messageFooterActions:_e,sidebarRowActions:Le,sidebarHeaderActions:je,sidebarSections:$e,statusLabel:Ue,toolLabels:We,waitingMessages:qe,renderWaitingPanel:Fe,renderReasoningAction:Be,collapseUnnamedFiles:He,fontFamily:Ve,theme:Ke,onReady:Ge,onBeforeSend:Xe,onHeldSendSettled:Ye,onTurnRunningChange:Qe,steerAttachments:et=!1,holdSendsDuringTurn:tt=!1,agentMentions:nt=!1,hideConversationList:rt=!1,initialConversationListCollapsed:at=!1,expandedWorkspaceGroups:ot,onExpandedWorkspaceGroupsChange:st,onBeforeMove:it,onConversationActionFailed:ct,sidebarSearchThreshold:lt,channelLabel:dt,headerTitle:ut,headerSubtitle:ht,agentHref:pt,onAgentNameClick:mt,clearAllAction:gt},ft){const vt=ar(m),wt=ar(O),bt=ar(q),yt=ar(k),xt=or(R),kt=or(D),Ct=or($),Nt=or(G),St=or(Y),Tt=or(Q),At=or(he),It=or(me),Et=or(ve),zt=or(Xe),[Rt,Dt]=o(ot);ot&&void 0===Rt&&Dt(ot);const Mt=c((e,t)=>{Dt(n=>n&&n.includes(e)!==t?t?[...n,e]:n.filter(t=>t!==e):n)},[]),Pt=s(Rt);l(()=>{const e=Pt.current;Rt!==e&&(Pt.current=Rt,void 0!==e&&Rt&&st?.(Rt))},[Rt,st]);const jt=or(Ye),$t=or(we),Ut=or(Qe),Ot=or(it),qt=or(ct),Ht=or(mt),Vt=or(Ce),Kt=s(null),{fetch:Gt,sessionEnded:Xt}=a(an),Yt=i(()=>ie(b,re),[b,re]),Jt=ar(qe),Qt=i(()=>ye?Object.fromEntries(Object.entries(ye).map(([e,t])=>[e.toUpperCase(),t])):void 0,[ye]),Zt=ar(i(()=>xe?Object.fromEntries(Object.entries(xe).map(([e,t])=>[e.toLowerCase(),t])):void 0,[xe])),en=ar(i(()=>function(e){const t=new Set;for(const n of e??[]){const e=n.toUpperCase();P.test(e)&&t.add(e)}return[...t].sort()}(Qt&&Object.keys(Qt)),[Qt])),tn=ar(We),nn=i(()=>({statusLabel:Ue,waitingMessages:Jt,renderWaitingPanel:Fe,renderReasoningAction:Be,toolLabels:tn}),[Ue,Jt,Fe,Be,tn]),rn="fullscreen"===n||"inline"===n,[on,cn]=o(!1),{agents:ln,agentsLoading:dn,agentsError:un,agentsSettled:hn,agentsDisabled:pn,selectedAgent:mn,agentMenuOpen:gn,setAgentMenuOpen:fn,handleSwitchAgent:vn,followAgent:wn,reloadAgents:bn}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r,storageKeyPrefix:a,initialAgent:i,onAgentChange:d}){const u=sn(),h=null===t?.agents||!!t?.singleEndpoint||"legacy"===n,p=Wt(a,_t),[m,g]=o([]),[f,v]=o(!1),[w,b]=o(!1),[y,x]=o(h),[k,C]=o(0),N=c(()=>C(e=>e+1),[]),[S,T]=o(null),[A,I]=o(!1),E=s(0);l(()=>{if(h)return void x(!0);const n=`${e}${t?.agents??"/chat/agents"}`,a=++E.current,o=()=>a===E.current;v(!0),u(n,{headers:r}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}).then(e=>{if(!o())return;const t=Vn(e);if(g(t),b(!1),0===t.length)return void T(null);const n=()=>{const e=Ft("local",p);return Kn(t,i)??(e?t.find(t=>t.slug===e):void 0)??t[0]};T(e=>e?t.find(t=>t.id===e.id)??n():n())}).catch(()=>{o()&&(b(!0),0===k&&g([]))}).finally(()=>{o()&&(v(!1),x(!0))})},[e,t,n,r,h,k]);const z=c(e=>{T(e),e.slug&&Bt("local",p,e.slug)},[p]);return{agents:m,agentsLoading:f,agentsError:w,agentsSettled:y,agentsDisabled:h,selectedAgent:S,setSelectedAgent:T,agentMenuOpen:A,setAgentMenuOpen:I,handleSwitchAgent:(e,t)=>{e.id!==S?.id?(T(e),e.slug&&Bt("local",p,e.slug),I(!1),d?.(e),t?.()):I(!1)},followAgent:z,reloadAgents:N}}({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt,storageKeyPrefix:le,initialAgent:pe,onAgentChange:me?It:void 0}),[yn,xn]=o(null),kn=s(null),[Cn,Nn]=o(null),[Sn,En]=o(void 0),[zn,Rn]=o(null),[Dn,Mn]=o(null),[_n,Ln]=o(null),Pn=s(0),[jn,$n]=o(null),Un=s(null),On=s(async()=>{}),Wn=s(()=>{}),qn=s(()=>{}),Fn=c((e,t)=>{B(qn.current,e,t.relayed),B($t,e,t)},[$t]),{messages:Bn,inputValue:Gn,setInputValue:Jn,isLoading:Qn,turnRunning:Zn,turnEnd:er,agentStatus:sr,attachedFiles:cr,conversationId:lr,contextUsage:dr,transferredAgent:ur,forgetTransfer:pr,adoptRecreatedConversation:vr,canSteer:wr,pendingApprovals:br,isSubmittingApproval:yr,approvalError:xr,submitApprovalDecisions:kr,isResumingAfterDecision:Cr,historyReloadNonce:Nr,reloadHistory:Sr,mergeTurnHistory:Tr,settleUnseenEnd:Ar,historyLoadedRef:Er,conversationIdRef:zr,handleFileAdd:Rr,handlePaste:Dr,handleSendMessage:Mr,skipWait:_r,readPendingApprovals:Lr,heldMessage:Pr,heldReason:jr,notice:$r,fileNotice:Ur,dismissNotice:Or,dismissFileNotice:Wr,composerFocusRequest:qr,cancelHeldMessage:Fr,agentMentions:Br,addAgentMention:Hr,handleNewChat:Vr,pendingWorkspaceId:Kr,clearPendingWorkspace:Gr,handleStopGenerating:Xr,conversationRefs:Yr,addConversationRef:Jr,setAttachedFiles:Qr,setMessages:Zr,setContextUsage:ea,updateConversationId:ta,handleSwitchConversation:na}=Hn({apiBaseUrl:p,apiEndpoints:vt,backendType:H,agentSlug:mn?.slug,agentPending:!hn,requestHeaders:wt,pageContext:bt,onRelativeLinkClick:R?xt:void 0,t:Yt,maxFileCount:M,maxTotalSize:_,maxFileSize:L,acceptFileTypes:j,onFileRefused:Ct,storageKeyPrefix:le,controlledConversationId:de,onConversationIdChange:he?At:void 0,getRequestExtras:ve?Et:void 0,onStreamEvent:Fn,onSessionEnded:Xt,onConversationTitle:()=>{On.current()},onMessageSent:(e,t)=>Wn.current(e,t),historySettledFor:Cn,steerAttachments:et,holdSends:tt,agentMentionsEnabled:nt,onBeforeSend:Xe?zt:void 0,onHeldSendSettled:Ye?jt:void 0});Sn!==lr&&(En(lr),null!==Cn&&Nn(null),null!==zn&&zn!==lr&&Rn(null)),l(()=>{void 0!==de&&de!==zr.current&&(de?na(de):Vr())},[de]);const{suggestions:ra,loading:aa}=rr({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt,agentSlug:mn?.slug}),oa=i(()=>(ra??yt)?.map(e=>Yt(e))??[],[ra,yt,Yt]),{prompts:sa,quota:ia,refreshQuota:ca}=nr({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt}),{historyEnabled:la,conversations:da,conversationsLoading:ua,conversationsFailed:ha,refreshConversations:pa,deleteConversation:ma,renameConversation:ga,moveConversation:fa,clearConversations:va,touchConversation:wa}=Xn({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt});On.current=pa,Wn.current=wa;const{workspacesEnabled:ya,workspaces:xa,refreshWorkspaces:ka,createWorkspace:Ca,renameWorkspace:Na,deleteWorkspace:Sa}=function({apiBaseUrl:e,apiEndpoints:t,backendType:n="rest",requestHeaders:r}){const a=sn(),[i,l]=o([]),[d,u]=o(!1),h=s(0),p=t?.workspaces,m="rest"===n&&!t?.singleEndpoint&&"string"==typeof p&&p.length>0,g=m?`${e}${p}`:null,f=c(async()=>{if(!g)return;const e=++h.current;try{const n=await a(g,{method:"GET",headers:{...r??{}}});if(e!==h.current)return;if(!n.ok)return void(408===(t=n.status)||429===t||t>=500&&501!==t||(u(!1),l([])));const o=Ne(await n.json());if(e!==h.current)return;l(o),u(!0)}catch{}var t},[g,r]),v=c(async(e,t,n)=>{try{const o=await a(t,{method:e,headers:{...n?{"Content-Type":"application/json"}:{},...r??{}},...n?{body:JSON.stringify(n)}:{}});if(!o.ok)return{ok:!1,error:await De(o)};const s=204===o.status?[]:Ne([await o.json().catch(()=>null)]);return await f(),{ok:!0,workspace:s[0]}}catch{return{ok:!1,error:null}}},[r,f]),w=c(async e=>g?v("POST",g,{name:e.trim()}):{ok:!1,error:null},[g,v]),b=c(async(e,t)=>g?v("PATCH",`${g}/${encodeURIComponent(e)}`,{name:t.trim()}):{ok:!1,error:null},[g,v]),y=c(async e=>g?v("DELETE",`${g}/${encodeURIComponent(e)}`):{ok:!1,error:null},[g,v]);return{workspacesEnabled:m&&d,workspaces:i,refreshWorkspaces:f,createWorkspace:w,renameWorkspace:b,deleteWorkspace:y}}({apiBaseUrl:p,apiEndpoints:vt,backendType:H,requestHeaders:wt});l(()=>{ya&&Kr&&!function(e,t){return t.some(t=>t.id===e&&t.canManage)}(Kr,xa)&&Gr(Kr)},[ya,xa,Kr,Gr]);const[Ta,Aa]=o(!1),[Ia,za]=o(at),Ra=rn&&la&&!rt;l(()=>{Ra&&pa()},[Ra,lr,pa]),l(()=>{Ra&&ka()},[Ra,lr,ka]);const Da=s(null);l(()=>{if(!Ra)return;const e=()=>{if("visible"!==document.visibilityState)return;const e=Date.now();(function(e,t){return null===t||e-t>=2e3})(e,Da.current)&&(Da.current=e,pa(),ka())};return document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}},[Ra,pa,ka]);const Ma=s(!1);l(()=>{Ma.current!==Zn&&(Ma.current=Zn,Zn?B(Ut,!0):B(Ut,!1,{ended:er??"stopped"}))},[Zn,er,Ut]),l(()=>()=>{Ma.current&&(Ma.current=!1,B(Ut,!1,{ended:"stopped"}))},[Ut]);const _a=s(!1);l(()=>{_a.current&&!Zn&&(ca(),Ra&&(pa(),ka())),_a.current=Zn},[Zn,ca,Ra,pa,ka]);const La=e=>{Aa(!1),na(e)},Pa=be(p,vt,H),ja=i(()=>new Set(da.map(e=>e.conversationId)),[da]),$a=or(la?La:void 0),Ua=Bn.some(e=>(e.conversationRefs?.length??0)>0);l(()=>{Ua&&la&&pa()},[Ua,la,pa,lr]);const Oa=ne(p,vt,H,"messagesPage"),[Wa,qa]=o(!1),Fa=ne(p,vt,H,"tts"),Ha=i(()=>Fa?{url:Fa,requestHeaders:wt}:void 0,[Fa,wt]),Va=s(Bn);Va.current=Bn,l(()=>qa(!1),[lr]);const Ka=c(async()=>{const e=zr.current,t=Va.current.find(e=>e.serverId)?.serverId;if(!Oa||!e||!t)return qa(!1),0;try{const n=await Gt(`${Oa}/${encodeURIComponent(e)}/messages?before=${encodeURIComponent(t)}&limit=50&supports_artifacts=true`,{headers:{...wt??{}}});if(!n.ok||zr.current!==e)return 0;const r=await n.json();if(zr.current!==e)return 0;const a=new Set(Va.current.map(e=>e.serverId).filter(Boolean)),o=Ze(r?.messages).filter(e=>!e.serverId||!a.has(e.serverId)).map(e=>({...e,id:Je(e.serverId)}));return Zr(e=>[...o,...e]),qa(!0===r?.has_more&&o.length>0),o.length}catch{return 0}},[Oa,zr,wt,Zr]),Ga=(e,t,{merge:n,afterTurn:r,keepEarlierOffer:a})=>{if(Nn(e),Rn(e),a||qa(!!Oa&&!0===t.has_more),!t.messages?.length)return;const o=Ze(t.messages);if(Zr(n?e=>function(e,t){const n=[...e],r=new Map;n.forEach((e,t)=>{e.serverId&&r.set(e.serverId,t)});const a=new Set,o=new Map;let s=-1,i=!1;for(const e of t){let t=void 0!==e.serverId?r.get(e.serverId):void 0;if(void 0===t){const r=An(e),o=n.findIndex((e,t)=>!a.has(t)&&!e.serverId&&Tn(e)===r);o>=0&&(t=o,n[o]=In(n[o],e),i=!0)}if(void 0!==t){a.add(t),s=Math.max(s,t);continue}const c=o.get(s)??[];c.push({...e,id:Je(e.serverId)}),o.set(s,c)}if(0===o.size)return i?n:e;const c=[...o.get(-1)??[]];return n.forEach((e,t)=>{c.push(e,...o.get(t)??[])}),c}(e,o):o),!r)for(let e=t.messages.length-1;e>=0;e-=1){const n=Pe(t.messages[e]);if(n){ea(n);break}}},Xa=s(Qn);Xa.current=Qn,l(()=>{Pn.current=0},[lr]),l(()=>{Dn&&!Qn&&(Mn(null),Dn.conversationId===lr&&Ga(Dn.conversationId,Dn.data,{merge:!0,afterTurn:!0,keepEarlierOffer:Dn.host}))},[Dn,Qn,lr]),l(()=>{if(!_n||_n.conversationId!==lr||Qn)return;const e=()=>{Xa.current||(Ln(null),Pn.current+=1,Un.current=_n.host?_n.conversationId:null,Sr())},t=Math.min(6e4,5e3*2**Pn.current),n=window.setTimeout(e,t),r=()=>{"visible"===document.visibilityState&&e()};return window.addEventListener("online",e),document.addEventListener("visibilitychange",r),()=>{window.clearTimeout(n),window.removeEventListener("online",e),document.removeEventListener("visibilitychange",r)}},[_n,lr,Qn,Sr]);const[Ya,Ja]=o(null),Qa=Me(wt),Za=c(()=>{$n(null),Un.current=jn?.host?jn.conversationId:null,Sr()},[jn,Sr]);l(()=>{jn&&jn.conversationId===lr&&!Qn&&jn.headersKey!==Qa&&Za()},[jn,lr,Qn,Qa,Za]);const eo=jn&&jn.conversationId===lr?jn:null,to="rest"===H&&!vt?.singleEndpoint&&null!==vt?.sessions&&!!lr&&yn!==lr,no=!ge&&!z&&"rest"===H&&!vt?.singleEndpoint&&null!==vt?.upload,[ro,ao]=o(!1),oo=s(0),so=e=>e.dataTransfer.types.includes("Files"),io=no?{onDragEnter:e=>{so(e)&&(oo.current+=1,ao(!0))},onDragOver:e=>{so(e)&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDragLeave:e=>{so(e)&&(oo.current=Math.max(0,oo.current-1),0===oo.current&&ao(!1))},onDrop:e=>{so(e)&&(e.preventDefault(),e.stopPropagation(),oo.current=0,ao(!1),Rr(e.dataTransfer.files))}}:{},co=e=>!so(e)||e.isDefaultPrevented()||function(e,t){const n=Array.from(e);if(!n.includes("text/uri-list")&&!n.includes("text/plain"))return!1;const r=t;return!!r&&(!!r.isContentEditable||!r.readOnly&&!r.disabled&&("TEXTAREA"===r.tagName||"INPUT"===r.tagName&&te.has((r.type??"text").toLowerCase())))}(e.dataTransfer.types,e.target),lo={onDragOver:e=>{co(e)||e.preventDefault()},onDrop:e=>{co(e)||e.preventDefault()}},[uo,ho]=o(null),po=c(e=>ho({text:e}),[]);l(()=>{if(!uo)return;const e=setTimeout(()=>ho(null),6e3);return()=>clearTimeout(e)},[uo]);const mo=(e,t,n,r)=>{((e,t,n)=>{const r=t?da.find(e=>e.conversationId===t)??null:null;return!0===B(qt,e,r,n||null)})(e,t,n)||po(n||r)},go=async()=>{if(!va)return;const e=await va();null===e?Vr():mo("clearAll",null,e,Yt("archive"===gt?"The conversations could not be archived":"The conversations could not be deleted"))},fo=async e=>{const t=await ma(e);null===t?e===zr.current&&Vr():mo("delete",e,t,Yt("The conversation could not be deleted"))},{sidebarWidth:vo,handleResizeStart:wo,defaultWidth:bo,isResizing:yo}=function({mode:e,resizable:t,onWidthChange:n,onResizeStart:r,onResizeEnd:a,storageKeyPrefix:i}){const c=Wt(i,Lt),[d,u]=o(()=>{const e=Ft("local",c);if(e){const t=parseInt(e,10);if(!Number.isNaN(t)&&t>=Yn)return t}return Yn}),[h,p]=o(!1),m=s(!1),g=s(d);g.current=d;const f=s(n);f.current=n;const v=s(a);return v.current=a,l(()=>{"sidebar"===e&&t&&f.current?.(g.current)},[e,t]),l(()=>{if("sidebar"!==e||!t)return;const n=e=>{if(!m.current)return;e.preventDefault();const t=window.innerWidth-e.clientX,n=.4*window.innerWidth,r=Math.min(Math.max(t,Yn),n);u(r),g.current=r,f.current?.(r)},r=()=>{m.current&&(m.current=!1,p(!1),document.body.style.cursor="",document.body.style.userSelect="",Bt("local",c,String(g.current)),v.current?.())},a=()=>{const e=.4*window.innerWidth;if(g.current>e){const t=Math.max(e,Yn);u(t),g.current=t,f.current?.(t)}};return document.addEventListener("mousemove",n),document.addEventListener("mouseup",r),window.addEventListener("resize",a),()=>{document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",r),window.removeEventListener("resize",a)}},[e,t,c]),{sidebarWidth:d,handleResizeStart:e=>{e.preventDefault(),m.current=!0,p(!0),document.body.style.cursor="col-resize",document.body.style.userSelect="none",r?.()},defaultWidth:Yn,isResizing:h}}({mode:n,resizable:S,onWidthChange:T,onResizeStart:A,onResizeEnd:E,storageKeyPrefix:le});l(()=>{const e="sidebar"===n?S?vo:bo:0,t=e>0?e+6:0;if(document.documentElement.style.setProperty("--chatbot-sidebar-width",`${t}px`),document.documentElement.style.setProperty("--chatbot-transition",yo?"none":"all 225ms cubic-bezier(0.4, 0, 0.2, 1)"),F){const e=document.querySelector(F);if(e){const n=e.style.paddingRight,r=e.style.transition;return e.style.paddingRight=t>0?`${t}px`:"",e.style.transition=yo?"none":"padding-right 225ms cubic-bezier(0.4, 0, 0.2, 1)",()=>{e.style.paddingRight=n,e.style.transition=r,document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}}}return()=>{document.documentElement.style.setProperty("--chatbot-sidebar-width","0px")}},[F,n,vo,bo,S,yo]);const xo=i(()=>x??t(Ir,{size:24}),[x]),ko=i(()=>function(e,t){if(void 0!==t){const e=t.trim();return/^https?:\/\//i.test(e)||/^\/(?![/\\])/.test(e)?e:null}const n=e?.trim().replace(/\/+$/,"");return n&&/^https?:\/\//i.test(n)?`${n}/chat?arcade=play`:null}(g,v),[g,v]),Co=w.firstName,[No,So]=o(null),[To,Ao]=o(null),Eo=i(()=>"function"==typeof U?B(U,mn??null):U,[U,mn]),zo=ur?.name||No||mn?.name||Yt("Assistant"),Ro=c(()=>{const e=Kt.current;return!!e&&("function"==typeof e.checkVisibility?e.checkVisibility():e.getClientRects().length>0)},[]);tr({isLoading:Zn,agentName:zo,t:Yt,enabled:X,onComplete:St,isViewingChat:Ro});const Do=null!=vt?.download,Mo="rest"===H&&null!==vt?.download&&(!vt?.singleEndpoint||Do),_o=c(e=>`${p}${vt?.download??"/chat/files"}/${encodeURIComponent(e.fileId)}/download`,[p,vt]),Lo=c(async e=>{const t=_o(e);try{const n=await Gt(t,{method:"GET",credentials:"include",headers:{...wt??{}}});if(!n.ok)throw new Error(`Download failed: ${n.status}`);const r=await n.blob(),a=URL.createObjectURL(r),o=document.createElement("a");o.href=a,o.download=e.filename||"download",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a)}catch(t){kt?.(t,e)}},[_o,wt,kt]),Po="rest"===H&&vt?.artifacts?`${p}${vt.artifacts}`:null,jo=c((e,t)=>`${Po}/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,[Po]),$o=c(async(e,t)=>{const n=`${e.title||e.kind}.${function(e){return"pptx_native"===e?"pptx":e}(t)}`;try{const r=await Gt(`${jo(e.kind,e.id)}/download`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...wt??{}},body:JSON.stringify({format:t})});if(!r.ok)throw new Error(`Download failed: ${r.status}`);const a=await r.blob(),o=URL.createObjectURL(a),s=document.createElement("a");s.href=o,s.download=function(e){if(!e)return;const t=/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(e);if(t)try{return decodeURIComponent(t[1].trim().replace(/^"|"$/g,""))||void 0}catch{}const n=/filename\s*=\s*("([^"]*)"|[^;]+)/.exec(e);return(n?(n[2]??n[1]).trim():"")||void 0}(r.headers.get("content-disposition"))??n,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(o)}catch(r){kt?.(r,{fileId:e.id,filename:n,type:t.toUpperCase()})}},[jo,wt,kt]),Uo=c(async(e,t)=>{const n=await Gt(jo(e,t),{credentials:"include",headers:{...wt??{}}});if(n.ok)return Oe(await n.json())},[jo,wt]),Oo={"--chat-accent":y,"--chat-accent-10":C(y,.1),"--chat-accent-40":C(y,.25),"--chat-accent-50":C(y,.5),"--chat-accent-dark":y,...Ve?{fontFamily:Ve}:{},...ae(Ke)},Wo=s(Tr);Wo.current=Tr;const qo=s(Ar);qo.current=Ar;const Fo=s(vr);Fo.current=vr;const Bo=s(!0);l(()=>(Bo.current=!0,()=>{Bo.current=!1}),[]),l(()=>{const e=Un.current;if(Un.current=null,null===vt?.sessions||vt?.singleEndpoint||"legacy"===H||"ag-ui"===H)return;if(!lr)return So(null),void xn(null);if(Er.current)return kn.current!==lr&&yn!==lr&&xn(lr),void(kn.current!==lr&&Cn!==lr&&Dn?.conversationId!==lr&&Nn(lr));if(!mn&&!pn)return void(hn&&yn!==lr&&xn(lr));Er.current=!0,kn.current=lr,xn(null);const t=`${p}${vt?.sessions??"/chat/sessions"}`,n=lr,r=()=>!Bo.current||zr.current!==n,a=e===n,o=Me(wt),s=Nr;Gt(t,{method:"POST",headers:{"Content-Type":"application/json",...wt??{}},body:JSON.stringify({conversation_id:lr,agent_slug:mn?.slug,supports_artifacts:!0})}).then(e=>r()?null:e.ok?(Pn.current=0,Ln(null),$n(null),e.json()):(qo.current(s,null),oi.has(e.status)?De(e).then(e=>(r()||$n({conversationId:n,detail:e,headersKey:o,host:a}),null)):(ai.has(e.status)?Ln({conversationId:n,host:a}):a||ta(null),null))).then(e=>{if(!e||r())return;const t="string"==typeof e.conversation_id&&!!e.conversation_id&&e.conversation_id!==n;So("string"==typeof e.agent_name?e.agent_name:null),Ao("string"==typeof e.conversation_id&&"string"==typeof e.channel&&e.channel?{conversationId:e.conversation_id,channel:e.channel}:null);const o=Ze(e.messages);if(qo.current(s,o),t)return Fo.current(e.conversation_id),Er.current=!0,void Ga(e.conversation_id,e,{merge:!1,afterTurn:!1,keepEarlierOffer:!1});a&&pr(),Wo.current(o)||(Xa.current?Mn({conversationId:n,data:e,host:a}):Ga(n,e,{merge:a,afterTurn:!1,keepEarlierOffer:a}))}).catch(()=>{r()||(qo.current(s,null),Ln({conversationId:n,host:a}))}).finally(()=>{kn.current===n&&(kn.current=null),r()||xn(n)})},[lr,mn,hn,yn,Oa,p,vt,H,Dn,Nr,Er,zr,Bo,wt,Zr,ea,ta,pr]);const Ho=s(Mr);Ho.current=Mr;const Vo=s(Vr);Vo.current=Vr;const Ko=s(na);Ko.current=na;const Go=s(()=>{});Go.current=e=>{no&&e.length>0&&Rr(e)};const Xo=s(ln);Xo.current=ln;const Yo=s(mn);Yo.current=mn;const Jo=No?ln.find(e=>e.name===No)??null:null,[Qo,Zo]=o(null),es=hn&&!to&&!((Jo?.id??null)!==Qo);l(()=>{if(null===Ya)return;if(Ya!==lr)return void Ja(null);if(!es||Zn)return;Ja(null);const e=zn===lr||Bn.length>0;Ln(null),$n(null),Un.current=e?lr:null,Sr()},[Ya,lr,es,Zn,zn,Bn.length,Sr]);const ts=or(Ge),ns=s(!1);l(()=>{es&&!ns.current&&(ns.current=!0,ts?.())},[es,ts]);const rs=s([]),[as,os]=o(0),ss=(e,t)=>{rs.current.push({run:e,drop:t}),os(e=>e+1)};l(()=>{if(!es||0===rs.current.length)return;rs.current.shift().run(),rs.current.length>0&&os(e=>e+1)},[es,as]),l(()=>()=>{queueMicrotask(()=>{if(!Bo.current)for(const e of rs.current.splice(0))e.drop?.()})},[]);const is=s(vn);is.current=vn;const cs=s(Xr);cs.current=Xr;const ls=s(ge);ls.current=ge;const ds=s(Gn);ds.current=Gn;const us=ur?ln.find(e=>e.id===ur.id)??null:No?Jo:mn,hs=ur?.id??Jo?.id??mn?.id??null;l(()=>{const e=Jo?.id??null;e!==Qo&&(Zo(e),Jo&&Jo.id!==mn?.id&&(wn(Jo),It?.(Jo)))},[Jo,Qo,mn,wn,It]);const ps=i(()=>{if(!us||!pt&&!Ht)return;const e=function(e,t){const n=e?.replace(/[\t\n\r]/g,"").trim();if(!n)return;if(/^https?:\/\//i.test(n))return n;if(!n.startsWith("/"))return;const r=new URL(t);if("null"!==r.origin)try{return new URL(n,r).origin===r.origin?n:void 0}catch{return}return/^\/(?![/\\])/.test(n)?n:void 0}(B(pt,us),window.location.href),t=Ht?()=>B(Ht,us):void 0;return e||t?{href:e,onClick:t}:void 0},[us,pt,Ht]),ms={conversation:lr&&da.find(e=>e.conversationId===lr)||null,agent:us},gs=V(ms.conversation?.channel??(To?.conversationId===lr?To.channel:void 0),dt),fs=function(e){const t=sn(),n=s(e);d(()=>{n.current=e});const[r,a]=o(null),i=s(null),u=c(async(e,r)=>{const{tts:a,locale:o}=n.current,s=o||("undefined"!=typeof navigator?navigator.language:void 0),i=Z(e,200),c=a?ee(t,a,i,r):null;for(const e of i){if(r.aborted)return;const t=c?(await c.next()).value??null:null;if(r.aborted)return;if(!t||!await mr(t,r)){if(r.aborted)return;await gr(e,s,r)}}},[]),h=c(()=>{if(i.current)return!0;const e=ir();if(!e)return!1;const t=hr({recognition:new e,lang:n.current.locale||("undefined"!=typeof navigator?navigator.language:void 0),send:(e,t)=>n.current.send(e,t),speak:u,speakable:e=>B(n.current.speakable,e)??e,present:e=>B(n.current.present,e)??e,probe:()=>{const e=n.current.readTurnState;return e?async function(e){try{const t=await e();return t?t.running?"running":"over":"unknown"}catch{return"unknown"}}(e):Promise.resolve("over")},stopTurn:()=>n.current.stopTurn(),addressedAgentId:()=>n.current.addressedAgentId(),onChange:e=>{i.current===t&&a(e)}});return i.current=t,t.start(),!0},[u]),p=c(()=>{const e=i.current;i.current=null,e?.end(),a(null)},[]);return l(()=>p,[p]),{snapshot:r,start:h,end:p,onFrame:c((e,t)=>i.current?.frame(e,t),[]),interrupt:c(()=>i.current?.interrupt(),[]),cancel:c(()=>i.current?.cancel(),[]),toggleMute:c(()=>i.current?.toggleMute(),[])}}({send:(e,t)=>Ho.current({text:e,source:"voice",onSent:t.onAccepted,onNotSent:t.onNotSent,onSteered:t.onSteered}),stopTurn:()=>cs.current(),readTurnState:Lr?async()=>{const e=zr.current,t=e?await Lr(e):null;return t&&{running:t.turnRunning}}:void 0,addressedAgentId:()=>hs,speakable:e=>J(W(e,en)),present:e=>ke?ke(e,{id:"voice-call",role:"assistant",content:e,timestamp:new Date}):e,tts:Ha,locale:re});qn.current=fs.onFrame;f(ft,()=>({send:(e,t)=>ls.current?Promise.resolve("dropped"):new Promise(n=>ss(()=>{ls.current?n("dropped"):Ho.current({text:e,extras:t?.extras,displayText:t?.displayText,onSent:()=>n("sent")}).then(n,()=>n("failed"))},()=>n("dropped"))),newConversation:e=>ss(()=>{const t=Kn(Xo.current,e?.agent);t&&t.id!==Yo.current?.id&&is.current(t),Vo.current(e?.workspaceId)}),selectConversation:e=>ss(()=>Ko.current(e)),setDraft:e=>{ds.current=e,Jn(e)},getDraft:()=>ds.current,focusComposer:()=>Kt.current?.querySelector("textarea")?.focus(),attachFiles:e=>ss(()=>Go.current(e)),stop:()=>{fs.cancel(),cs.current()},startVoiceCall:()=>!ls.current&&fs.start(),reloadAgents:bn,reloadConversation:()=>{const e=zr.current;e&&Ja(e)},scrollToMessage:e=>{const t=[...Kt.current?.querySelectorAll("[data-message-id]")??[]].find(t=>t.dataset.messageId===e);return!!t&&(t.scrollIntoView?.({block:"center",behavior:"smooth"}),t.classList.add("filigran-chat-highlight"),window.setTimeout(()=>t.classList.remove("filigran-chat-highlight"),2e3),!0)}}),[]);const vs=(()=>{const e="filigran-chatbot";switch(n){case"sidebar":return`${e} fixed right-0 bottom-0 flex flex-col chat-surface-raised border-l chat-border-200/10 z-[1200]`;case"floating":return`${e} fixed bottom-5 right-5 flex flex-col chat-surface-raised chat-radius-md shadow-[0_8px_32px_rgba(0,0,0,0.15)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.4)] z-[1300] border chat-border-200/10`;case"fullscreen":return`${e} fixed right-0 bottom-0 left-0 flex flex-col chat-surface z-[1400]`;case"inline":return`${e} relative flex flex-col h-full w-full min-h-0 chat-surface`;default:return e}})(),ws={...Oo,..."sidebar"===n?{top:h,width:S?vo:bo}:"floating"===n?{width:380,height:560}:"inline"===n?{}:{top:h}};return e("div",{ref:Kt,className:vs,style:ws,"data-testid":"filigran-chat-panel",...lo,children:["sidebar"===n&&S&&t("div",{onMouseDown:wo,className:"absolute top-0 -left-1 bottom-0 w-2 cursor-col-resize z-10 group",children:t("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 bottom-0 w-0.5 chat-radius-sm bg-[var(--chat-accent)] opacity-0 transition-opacity group-hover:opacity-100 group-active:opacity-100"})}),t(Ea,{mode:n,agentName:zo,agents:ln,agentsLoading:dn,agentsError:un,selectedAgent:mn,transferredFrom:ur?mn?.name:void 0,agentMenuOpen:gn,onAgentMenuToggle:()=>fn(e=>!e),onAgentMenuClose:()=>fn(!1),onSwitchAgent:e=>{e&&vn(e,()=>{Vr()})},modeMenuOpen:on,onModeMenuToggle:()=>cn(e=>!e),onModeMenuClose:()=>cn(!1),onModeChange:u,onNewChat:Vr,onClose:r,logoIcon:xo,actions:Se,agentDashboardUrl:g,historyEnabled:la&&!Ra,historyMenuOpen:Ta,onHistoryMenuToggle:()=>{const e=!Ta;e&&pa(),Aa(e)},onHistoryMenuClose:()=>Aa(!1),conversations:da,conversationsLoading:ua,conversationsFailed:ha,onRetryConversations:()=>{pa()},activeConversationId:lr,onSelectConversation:La,onDeleteConversation:e=>{fo(e)},onClearAll:va?()=>{go()}:void 0,clearAllAction:gt,title:"function"==typeof ut?B(ut,ms):ut,subtitle:"function"==typeof ht?B(ht,ms):void 0===ht?gs&&I(Yt,"Agent · {channel}",{channel:gs}):ht,agentLink:ps,t:Yt}),uo&&(!Ra||Ia)&&t(ba,{tone:"error",className:"mx-3 mt-2 shrink-0",onDismiss:()=>ho(null),dismissLabel:Yt("Close"),children:uo.text}),e("div",{className:Ra?"flex flex-1 min-h-0":"contents",children:[Ra&&t(Ys,{conversations:da,loading:ua,failed:ha,onRetry:()=>{pa()},activeConversationId:lr,collapsed:Ia,onToggleCollapsed:()=>za(e=>!e),onSelect:La,onDelete:e=>{fo(e)},onRename:(e,t)=>{(async(e,t)=>{const n=await ga(e,t);null!==n&&mo("rename",e,n,Yt("The conversation could not be renamed"))})(e,t)},onNewChat:Vr,workspaces:ya?{list:xa,pendingWorkspaceId:Kr,onCreate:Ca,onRename:Na,onDelete:async e=>{const t=await Sa(e);return t.ok&&(Gr(e),pa()),t},onMove:async(e,t)=>{const n=da.find(t=>t.conversationId===e);if(Ot&&n){const e=t?xa.find(e=>e.id===t)??null:null;let r=!1;try{r=!0===await Ot(n,e)}catch(e){console.error("A chat panel host callback threw",e)}if(!r)return}const r=await fa(e,t);null!==r&&mo("move",e,r,Yt("The conversation could not be moved"))},onNewChat:e=>{Vr(e),ka()}}:void 0,storageKeyPrefix:le,expandedGroups:Rt,onGroupOpenedChange:Mt,rowActions:Le,headerActions:je,sections:$e,onClearAll:va?()=>{go()}:void 0,clearAllAction:gt,searchThreshold:lt,channelLabel:dt,notice:uo?.text??null,onNotice:po,t:Yt}),e("div",{className:Ra?"relative flex flex-1 flex-col min-w-0":"contents",...io,children:[ro&&t("div",{className:"pointer-events-none absolute inset-2 z-30 flex items-center justify-center chat-radius-md border-2 border-dashed border-[var(--chat-accent)] bg-[var(--chat-accent)]/10 text-sm font-medium text-[var(--chat-accent)]",children:Yt("Drop files to attach them")}),Te&&t("div",{className:"shrink-0",children:Te}),0===Bn.length&&to?t("div",{"data-testid":"filigran-chat-loading",className:"flex-1 flex flex-col gap-4 px-4 py-6","aria-busy":"true",children:[0,1,2].map(e=>t("div",{className:"flex "+(e%2?"justify-end":"justify-start"),children:t("div",{className:"h-10 chat-radius-md chat-skeleton-fill animate-pulse "+(e%2?"w-1/3":"w-2/3")})},e))}):0===Bn.length&&eo?e("div",{"data-testid":"filigran-chat-restore-error",role:"alert",className:"flex-1 flex flex-col items-center justify-center gap-3 px-6 py-6 text-center",children:[t(fr,{size:18,className:"text-amber-500 dark:text-amber-400"}),t("p",{className:"max-w-sm text-[0.8125rem] leading-6 chat-text-secondary-600/60",children:eo.detail??Yt("This conversation could not be loaded.")}),t("button",{type:"button",onClick:Za,className:"chat-radius-sm border chat-border-200/10 px-3 py-1 text-[0.75rem] font-medium chat-text-secondary-700/80 transition-colors hover:chat-surface-hover-100/6",children:Yt("Retry")})]}):0===Bn.length?Ee?t("div",{className:"flex-1 min-h-0 overflow-y-auto filigran-chat-scrollable",children:Ee}):t(qs,{firstName:Co,logoIcon:xo,promptSuggestions:oa,suggestionsLoading:aa,agentName:mn?.name,onPromptClick:ge?void 0:Jn,t:Yt}):t($s,{messages:Bn,isLoading:Qn,agentStatus:sr,agentName:zo,logoIcon:xo,onRelativeLinkClick:xt,onDownloadFile:Mo?Lo:void 0,resolveAttachmentUrl:Mo&&!oe?_o:void 0,onDownloadArtifact:Po?$o:void 0,onRefreshArtifact:Po?Uo:void 0,requestHeaders:wt,miniGameEnabled:K,onPlayWaitingGame:Nt,waitingGameUrl:ko,onMessageFeedback:Tt,feedbackUrl:ue(p,vt,H),conversationId:lr,locale:re,isResumingAfterDecision:Cr,onSkipWait:_r??void 0,pendingApprovals:br,onSubmitApprovalDecisions:kr,isSubmittingApproval:yr,approvalError:xr,openableConversationIds:ja,onOpenConversation:$a,markerRenderers:Qt,markerKindList:en,codeBlockRenderers:Zt,transformMessageText:ke,onArtifactOpen:Vt,renderMessageExtras:ze,replaceMessage:Re,messageFooterActions:_e,transcriptFooter:Ie,onLoadEarlier:Wa?Ka:void 0,collapseUnnamedFiles:He,ttsRoute:Ha,thinking:nn,t:Yt}),ge?fe&&t("div",{className:"px-4 py-3 border-t chat-border-200/10 text-sm chat-text-secondary-500/50",children:fe}):t(Ba,{header:Ae,steerAttachments:et,canHold:tt,heldMessage:Pr,heldReason:jr,notice:$r,fileNotice:Ur,onDismissNotice:Or,onDismissFileNotice:Wr,agentNotForChat:!!us?.disableChat,onCancelHeld:Fr,agentMentions:nt&&ln.length>0?{agents:ln,mentions:Br,onPick:Hr}:void 0,inputValue:Gn,onInputChange:Jn,onSend:Mr,onStop:Xr,isLoading:Qn,canSteer:wr,attachedFiles:cr,onFileAdd:z?void 0:Rr,onFileRemove:e=>Qr(t=>t.filter((t,n)=>n!==e)),onPaste:z?void 0:Dr,accept:j,placeholder:Eo,focusRequest:qr,t:Yt,mode:n,separatorColor:N,prompts:sa,quota:ia,contextUsage:se?dr:null,composerToolbar:ce,conversationReferences:Pa?{url:Pa,requestHeaders:wt,conversationId:lr,refs:Yr,onPick:Jr}:void 0})]})]}),fs.snapshot&&t(Os,{call:fs.snapshot,agentName:zo,logoIcon:xo,processingLabel:Io(sr,Yt,Ue,tn),onInterrupt:fs.interrupt,onToggleMute:fs.toggleMute,onEnd:fs.end,t:Yt})]})}),ci=({isOpen:n,onToggle:r,label:a,accentColor:o="#7b5cff",icon:s,t:c,locale:l})=>{const d=i(()=>ie(c,l),[c,l]),u=s??t(Ir,{size:16});return e("button",{type:"button",onClick:r,className:"filigran-chatbot inline-flex items-center gap-1.5 px-3 py-[3px] text-[0.8125rem] font-medium whitespace-nowrap chat-radius-sm border transition-colors",style:{borderColor:n?o:C(o,.5),color:o,backgroundColor:n?C(o,.1):"transparent"},onMouseEnter:e=>{e.currentTarget.style.borderColor=o,e.currentTarget.style.backgroundColor=C(o,.1)},onMouseLeave:e=>{e.currentTarget.style.borderColor=n?o:C(o,.5),e.currentTarget.style.backgroundColor=n?C(o,.1):"transparent"},children:[t("span",{className:"[&>svg]:w-4 [&>svg]:h-4",children:u}),a??d("Ask Assistant")]})};export{si as ChatPanel,ci as ChatToggleButton,pr as voiceCallSupported};
2
2
  //# sourceMappingURL=index.js.map