@m6d/cortex-react 0.6.1 → 0.7.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,9 +1,9 @@
1
- var M2=Object.create;var{getPrototypeOf:O2,defineProperty:z0,getOwnPropertyNames:P2}=Object;var A2=Object.prototype.hasOwnProperty;var H_=(_,$,X)=>{X=_!=null?M2(O2(_)):{};let Y=$||!_||!_.__esModule?z0(X,"default",{value:_,enumerable:!0}):X;for(let Q of P2(_))if(!A2.call(Y,Q))z0(Y,Q,{get:()=>_[Q],enumerable:!0});return Y};var B_=((_)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(_,{get:($,X)=>(typeof require<"u"?require:$)[X]}):_)(function(_){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+_+'" is not supported')});import{useEffect as o8,useRef as H2,useState as t_}from"react";var e_=["en","ar"];var _1=["image/png","image/jpeg","image/webp","application/pdf"];var V0=5;function K0(_,$){if(!_1.some((X)=>X===_))return"type";if($>10485760)return"size";return"ok"}function $1(_){return{..._,role:_.role==="trigger"?"user":_.role}}var W0="clientToolAnswers";function D0(_){return _.approval?.id??`approval_${_.id}`}var X1="X-Cortex-Timezone";function Y1(_){let $=_.getHeaders();return $ instanceof Promise?$.then(H0):Promise.resolve(H0($))}function H0(_){let $={..._},X=E2(),Y=Object.keys($).some((Q)=>Q.toLowerCase()===X1.toLowerCase());if(X&&!Y)$[X1]=X;return $}function E2(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function R2(_,$){let X=_.baseUrl;return(typeof X==="string"?X:X()).replace(/\/$/,"")+$}function y2(_){let $=_?.match(/filename\*\s*=\s*[^']*'[^']*'([^;\r\n]+)/i)?.[1]?.trim().replace(/^"|"$/g,"");if($)try{return decodeURIComponent($)}catch{}return _?.match(/filename\s*=\s*"?([^";\r\n]+)"?/i)?.[1]}function Q1(_){function $(){return Y1(_())}function X(Q){return R2(_(),Q)}async function Y(Q,N){let Z=new Headers(await $());if(new Headers(N?.headers).forEach((z,V)=>{Z.set(V,z)}),N?.body instanceof FormData)Z.delete("Content-Type");else if(!Z.has("Content-Type"))Z.set("Content-Type","application/json");let G=await fetch(X(Q),{...N,headers:Z});if(!G.ok)throw Error(`HTTP ${G.status}: ${G.statusText}`);let J=await G.text();return J?JSON.parse(J):void 0}return{getCapabilities(){return Y("/capabilities")},listThreads(){return Y("/threads")},createThread(){return Y("/threads",{method:"POST"})},deleteThread(Q){return Y(`/threads/${Q}`,{method:"DELETE"})},listMessages(Q){return Y(`/threads/${Q}/messages`)},listLlmRequests(Q){return Y(`/messages/${Q}/llm-requests`)},abortStream(Q){return Y(`/chat/${Q}/abort`,{method:"POST"})},initiateToolCall(Q,N){return Y(`/chat/${Q}/tools/${N}/initiate`,{method:"POST"})},uploadAttachment(Q,N){let Z=new FormData;return Z.append("file",N),Y(`/threads/${Q}/files`,{method:"POST",body:Z})},deleteAttachment(Q){return Y(`/files/${Q}`,{method:"DELETE"})},async downloadAttachment(Q){let N=await fetch(X(`/files/${Q}`),{headers:await $()});if(!N.ok)throw Error(`HTTP ${N.status}: ${N.statusText}`);return{blob:await N.blob(),name:y2(N.headers.get("Content-Disposition"))??Q}},resolveHeaders:$,resolveUrl:X}}var w2={complete:"success",error:"error","approval-requested":"approval","approval-responded":"approval","awaiting-input":"pending","input-streaming":"pending","input-complete":"pending"},I2={"awaiting-input":"translate_calling","input-streaming":"translate_calling","input-complete":"translate_input_ready","approval-requested":"translate_needs_approval","approval-responded":"translate_responded",complete:"translate_completed",error:"translate_error"};function N1(_){let{state:$,approval:X}=_;return{modifier:w2[$],labelKey:X?.approved===!1?"translate_declined":$==="approval-responded"&&X?.approved?"translate_approved":I2[$],pulse:$==="awaiting-input"||$==="input-streaming"?"default":$==="approval-requested"?"violet":void 0}}function Z1(_){let $=_.output;if($===void 0||$===null)return"";if(typeof $==="string")return $;return JSON.stringify($,null,2)}var B0={code:"javascript",query:"cypher"};function G1(_){let $=_&&typeof _==="object"?_:null,X=$?Object.entries(B0).flatMap(([Q,N])=>{let Z=$[Q];return typeof Z==="string"?[{key:Q,lang:N,value:Z.replace(/\\n/g,`
2
- `)}]:[]}):[],Y=_;if($){let Q=Object.fromEntries(Object.entries($).filter(([N])=>!Object.hasOwn(B0,N)));Y=Object.keys(Q).length>0?Q:null}return{codeSnippets:X,remainingInput:Y,remainingInputText:Y?JSON.stringify(Y,null,2):""}}var F0=10,b2={"awaiting-input":"starting","input-streaming":"starting","input-complete":"processing","approval-requested":"approval","approval-responded":"processing",complete:"complete",error:"error"};function C2(_){let $=0;for(let X=0;X<_.length;X++)$=$*31+_.charCodeAt(X)|0;return Math.abs($)%F0}function S2(_){let $=_.input;if(!$||typeof $!=="object"||!("status"in $))return;let X=$.status;return typeof X==="string"&&X.trim()?X.trim():void 0}function v2(_){let $=_.output;if(typeof $==="string")try{$=JSON.parse($)}catch{return!1}return!!$&&typeof $==="object"&&"error"in $&&$.error===!0}function T2(_){let $=_.output;if(!$||typeof $!=="object"||!("rowCount"in $))return;return typeof $.rowCount==="number"?$.rowCount:void 0}function f2(_,$,X){if(X)return"translate_declined";if($==="error")return"translate_tool_error";if($==="approval")return"translate_needs_approval";let Y=_.name==="readAttachment"?"attachment":"tool",Q=Y==="tool"?`_${C2(_.id)}`:"";return`translate_${Y}_${$==="complete"?"done":"status"}${Q}`}function F_(_){let $=_.approval?.approved===!1,Y=$||_.state==="complete"&&v2(_)?"error":b2[_.state]??"processing";return{state:Y,active:Y==="starting"||Y==="processing",gated:_.approval!==void 0,titleKey:f2(_,Y,$),statement:S2(_),rowCount:Y==="complete"?T2(_):void 0}}function J1(_,$){let X=_.metadata;if(!X||typeof X!=="object"||!("cortex"in X))return;return X.cortex?.approval?.[$]||void 0}function z1(_){return Array.from({length:F0},($,X)=>`translate_${_}_${X}`)}function U_(_,$){return _.filter((X,Y)=>{if(X.type==="tool-result")return!1;if($.debugMode)return!0;if($.fold?.get(X)?.kind==="hidden")return!1;if(X.type==="text"&&!X.content.trim())return!1;let Q=Y===_.length-1;return X.type!=="thinking"||$.isStreaming&&Q})}function V1(_){return _.filter(($)=>$.type==="text").map(($)=>$.content).join(`
1
+ var S2=Object.create;var{getPrototypeOf:T2,defineProperty:O0,getOwnPropertyNames:v2}=Object;var f2=Object.prototype.hasOwnProperty;var U_=(_,$,X)=>{X=_!=null?S2(T2(_)):{};let Y=$||!_||!_.__esModule?O0(X,"default",{value:_,enumerable:!0}):X;for(let Q of v2(_))if(!f2.call(Y,Q))O0(Y,Q,{get:()=>_[Q],enumerable:!0});return Y};var L_=((_)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(_,{get:($,X)=>(typeof require<"u"?require:$)[X]}):_)(function(_){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+_+'" is not supported')});import{useEffect as G4,useRef as R2,useState as _1}from"react";var X1=["en","ar"];var Y1=["image/png","image/jpeg","image/webp","application/pdf"];var P0=5;function M0(_,$){if(!Y1.some((X)=>X===_))return"type";if($>10485760)return"size";return"ok"}function Q1(_){return{..._,role:_.role==="trigger"?"user":_.role}}var k0="clientToolAnswers";function A0(_){return _.approval?.id??`approval_${_.id}`}var N1="X-Cortex-Timezone";function Z1(_){let $=_.getHeaders();return $ instanceof Promise?$.then(E0):Promise.resolve(E0($))}function E0(_){let $={..._},X=j2(),Y=Object.keys($).some((Q)=>Q.toLowerCase()===N1.toLowerCase());if(X&&!Y)$[N1]=X;return $}function j2(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function g2(_,$){let X=_.baseUrl;return(typeof X==="string"?X:X()).replace(/\/$/,"")+$}function m2(_){let $=_?.match(/filename\*\s*=\s*[^']*'[^']*'([^;\r\n]+)/i)?.[1]?.trim().replace(/^"|"$/g,"");if($)try{return decodeURIComponent($)}catch{}return _?.match(/filename\s*=\s*"?([^";\r\n]+)"?/i)?.[1]}function G1(_){function $(){return Z1(_())}function X(Q){return g2(_(),Q)}async function Y(Q,N){let Z=new Headers(await $());if(new Headers(N?.headers).forEach((z,V)=>{Z.set(V,z)}),N?.body instanceof FormData)Z.delete("Content-Type");else if(!Z.has("Content-Type"))Z.set("Content-Type","application/json");let G=await fetch(X(Q),{...N,headers:Z});if(!G.ok)throw Error(`HTTP ${G.status}: ${G.statusText}`);let J=await G.text();return J?JSON.parse(J):void 0}return{getCapabilities(){return Y("/capabilities")},listThreads(){return Y("/threads")},createThread(){return Y("/threads",{method:"POST"})},deleteThread(Q){return Y(`/threads/${Q}`,{method:"DELETE"})},listMessages(Q){return Y(`/threads/${Q}/messages`)},listLlmRequests(Q){return Y(`/messages/${Q}/llm-requests`)},abortStream(Q){return Y(`/chat/${Q}/abort`,{method:"POST"})},initiateToolCall(Q,N){return Y(`/chat/${Q}/tools/${N}/initiate`,{method:"POST"})},uploadAttachment(Q,N){let Z=new FormData;return Z.append("file",N),Y(`/threads/${Q}/files`,{method:"POST",body:Z})},deleteAttachment(Q){return Y(`/files/${Q}`,{method:"DELETE"})},async downloadAttachment(Q){let N=await fetch(X(`/files/${Q}`),{headers:await $()});if(!N.ok)throw Error(`HTTP ${N.status}: ${N.statusText}`);return{blob:await N.blob(),name:m2(N.headers.get("Content-Disposition"))??Q}},resolveHeaders:$,resolveUrl:X}}var x2=["completed","cancelled","failed"],f_="requestLocation";function R0(_,$,X){if($!==X)return null;if(typeof _!=="object"||_===null)return null;let Y=_;if(Y.type!=="cortex:client-tool")return null;let Q=x2.find((Z)=>Z===Y.status);if(!Q)return null;let N=Y.reference;return{type:"cortex:client-tool",status:Q,...typeof N==="string"?{reference:N}:{},...Y.result!==void 0?{result:Y.result}:{}}}var h2=new Set(["complete","error"]);function v(_){return h2.has(_)}function a(_){return(c2(_)?.parts??[]).filter((X)=>X.type==="tool-call"&&!v(X.state))}function O_(_){let $=_.at(-1);if($?.role!=="assistant")return;let X=$.parts.at(-1),Y=X?.type==="tool-call"||X?.type==="tool-result",Q=$.parts.every((N)=>N.type!=="tool-call"||v(N.state));return Y&&Q?void 0:$}function c2(_){for(let $=_.length-1;$>=0;$-=1){let X=_[$];if(X?.role==="assistant")return X}return}var u2={complete:"success",error:"error","approval-requested":"approval","approval-responded":"approval","awaiting-input":"pending","input-streaming":"pending","input-complete":"pending"},p2={"awaiting-input":"translate_calling","input-streaming":"translate_calling","input-complete":"translate_input_ready","approval-requested":"translate_needs_approval","approval-responded":"translate_responded",complete:"translate_completed",error:"translate_error"};function J1(_){let{state:$,approval:X}=_;return{modifier:u2[$],labelKey:X?.approved===!1?"translate_declined":$==="approval-responded"&&X?.approved?"translate_approved":p2[$],pulse:$==="awaiting-input"||$==="input-streaming"?"default":$==="approval-requested"?"violet":void 0}}function z1(_){let $=_.output;if($===void 0||$===null)return"";if(typeof $==="string")return $;return JSON.stringify($,null,2)}var y0={code:"javascript",query:"cypher"};function V1(_){let $=_&&typeof _==="object"?_:null,X=$?Object.entries(y0).flatMap(([Q,N])=>{let Z=$[Q];return typeof Z==="string"?[{key:Q,lang:N,value:Z.replace(/\\n/g,`
2
+ `)}]:[]}):[],Y=_;if($){let Q=Object.fromEntries(Object.entries($).filter(([N])=>!Object.hasOwn(y0,N)));Y=Object.keys(Q).length>0?Q:null}return{codeSnippets:X,remainingInput:Y,remainingInputText:Y?JSON.stringify(Y,null,2):""}}var w0=10,l2={"awaiting-input":"starting","input-streaming":"starting","input-complete":"processing","approval-requested":"approval","approval-responded":"processing",complete:"complete",error:"error"};function d2(_){let $=0;for(let X=0;X<_.length;X++)$=$*31+_.charCodeAt(X)|0;return Math.abs($)%w0}function n2(_){let $=_.input;if(!$||typeof $!=="object"||!("status"in $))return;let X=$.status;return typeof X==="string"&&X.trim()?X.trim():void 0}function i2(_){let $=_.output;if(typeof $==="string")try{$=JSON.parse($)}catch{return!1}return!!$&&typeof $==="object"&&"error"in $&&$.error===!0}function r2(_){let $=_.output;if(!$||typeof $!=="object"||!("rowCount"in $))return;return typeof $.rowCount==="number"?$.rowCount:void 0}function o2(_,$,X){if(X)return"translate_declined";if($==="error")return"translate_tool_error";if($==="approval")return"translate_needs_approval";let Y=_.name==="readAttachment"?"attachment":"tool",Q=Y==="tool"?`_${d2(_.id)}`:"";return`translate_${Y}_${$==="complete"?"done":"status"}${Q}`}function P_(_){let $=_.approval?.approved===!1,Y=$||_.state==="complete"&&i2(_)?"error":l2[_.state]??"processing";return{state:Y,active:Y==="starting"||Y==="processing",gated:_.approval!==void 0,titleKey:o2(_,Y,$),statement:n2(_),rowCount:Y==="complete"?r2(_):void 0}}function K1(_,$){let X=_.metadata;if(!X||typeof X!=="object"||!("cortex"in X))return;return X.cortex?.approval?.[$]||void 0}function W1(_){return Array.from({length:w0},($,X)=>`translate_${_}_${X}`)}function J_(_,$){return _.filter((X,Y)=>{if(X.type==="tool-result")return!1;if($.debugMode)return!0;if(X.type==="text"&&!X.content.trim())return!1;let Q=Y===_.length-1;return X.type!=="thinking"||$.isStreaming&&Q})}function D1(_){return _.filter(($)=>$.type==="text").map(($)=>$.content).join(`
3
3
 
4
- `)}var j2=new Set(["complete","error"]);function m(_){return j2.has(_)}function r(_){return(g2(_)?.parts??[]).filter((X)=>X.type==="tool-call"&&!m(X.state))}function K1(_){let $=_.at(-1);if($?.role!=="assistant")return;let X=$.parts.at(-1),Y=X?.type==="tool-call"||X?.type==="tool-result",Q=$.parts.every((N)=>N.type!=="tool-call"||m(N.state));return Y&&Q?void 0:$}function g2(_){for(let $=_.length-1;$>=0;$-=1){let X=_[$];if(X?.role==="assistant")return X}return}function W1(){let _=new Map;return($,X)=>{let Y=new Map;for(let[Q,N]of m2($,X)){let Z=_.get(Q);Y.set(Q,Z&&c2(Z,N)?Z:N)}return _=Y,Y}}function m2(_,$){let X=new Map;if($.debugMode)return X;let Q=$.agentWorking||r(_).length>0?x2(_):_,N=[];function Z(){let G=N[0]?.part.id;if(N.length>1&&G&&!$.opened.has(G))for(let[J,{messageId:z,part:V}]of N.entries()){let W=X.get(z)??new Map;X.set(z,W);let q=J===N.length-1;W.set(V,q?{kind:"more",count:N.length-1,runId:G}:{kind:"hidden"})}N=[]}for(let G of Q){if(G.role!=="assistant"){Z();continue}let J=U_(G.parts,{debugMode:!1,isStreaming:!1});for(let z of J)if(z.type==="tool-call"&&m(z.state)&&$.foldable(z))N.push({messageId:G.id,part:z});else Z()}return Z(),X}function x2(_){let $=_.map((X)=>X.role).lastIndexOf("user");return $<0?[]:_.slice(0,$)}function c2(_,$){if(_.size!==$.size)return!1;for(let[X,Y]of _){let Q=$.get(X);if(!Q||Q.kind!==Y.kind)return!1;if(Y.kind==="more"&&Q.kind==="more"){if(Y.count!==Q.count||Y.runId!==Q.runId)return!1}}return!0}import{EventType as L0}from"@tanstack/ai";import{fetchServerSentEvents as U0}from"@tanstack/ai-client";function h2(_){for(let $=_.length-1;$>=0;$-=1){let X=_[$],Y="parts"in X&&X.parts.some((Q)=>Q.type==="tool-result"||Q.type==="tool-call"&&Q.state==="approval-responded");if(X.role==="user"||Y)return _.slice($,$+1)}return _.slice(-1)}function u2(_){if(_.state==="approval-responded"){let $=_.approval?.approved;if($===void 0)return null;return{toolCallId:_.id,output:null,state:$?"approved":"denied"}}if(!m(_.state))return null;return{toolCallId:_.id,output:_.output??null,state:_.state==="error"?"error":"complete"}}function l2(_){let[$]=_;if(!$||$.role!=="assistant"||!("parts"in $))return null;let X=$.parts.flatMap((Y)=>{let Q=Y.type==="tool-call"?u2(Y):null;return Q?[Q]:[]});return X.length>0?X:null}async function*q0(_,$,X){for await(let Y of _){if(Y.type!==L0.MESSAGES_SNAPSHOT){yield Y;continue}let Q=$.localMessages(),N=Q.findIndex((G)=>G.id===X),Z=N===-1?[]:Q.slice(N+1).filter((G)=>G.role==="user");$.onTranscriptCarried?.(Y.timestamp??Date.now()),yield{...Y,messages:[...Y.messages,...Z]}}}function D1(_){let{api:$,thread:X}=_,Y=async()=>({headers:await $.resolveHeaders()}),Q=U0(()=>$.resolveUrl("/chat"),Y),N=function(J,z,V,W){let q=h2(J),L=l2(q),U=L?Q.connect([],{...z,[W0]:L},V,W):Q.connect(q,z,V,W);return q0(U,_,J.at(-1)?.id)},Z=U0(()=>$.resolveUrl(`/chat/${X.id}/stream`),Y),G=[];return{connect:N,async*joinRun(J,z){yield{type:L0.MESSAGES_SNAPSHOT,timestamp:Date.now(),messages:G},yield*q0(Z.joinRun(J,z),_,G.at(-1)?.id)},hydrate:async()=>{let J=await p2(_);return G=J.messages,J}}}async function p2(_){let{api:$,thread:X,mode:Y}=_,Q=X.isRunning?{runId:X.id}:null;if(Y==="skip")return{messages:[],activeRun:Q,interrupts:null};if(Y==="load")_.setLoadingMessages?.(!0);try{let Z=(await $.listMessages(X.id)).map($1);return _.onHydrated?.(Z),{messages:Z,activeRun:Q,interrupts:null}}finally{_.setLoadingMessages?.(!1)}}async function H1(_){if(_.isStale?.()||_.isStreaming())return;try{let $=await _.api.listMessages(_.threadId);if(_.isStale?.()||_.isStreaming())return;let X=$.map($1);return _.setMessages(X),X}catch{return}}function q_(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let _=crypto.getRandomValues(new Uint8Array(16));_[6]=_[6]&15|64,_[8]=_[8]&63|128;let $=Array.from(_,(X)=>X.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}function B1(_){let{api:$}=_,X=new Set,Y=new Set,Q=[],N=[];function Z(){return Q}function G(H){return X.add(H),()=>{X.delete(H)}}function J(H){Q=H;for(let D of X)D()}function z(H,D){J(Q.map((K)=>K.localId===H?{...K,...D}:K))}function V(H){if(Y.delete(H))return;z(H,{status:"error"})}function W(H){let D=[];for(let K of H){let O=K0(K.type,K.size)!=="ok"||Q.filter((T)=>T.status!=="error").length>=V0,C=q_();if(J([...Q,{localId:C,filename:K.name,status:O?"error":"uploading"}]),!O)D.push({localId:C,file:K})}if(!D.length)return;_.ensureThread().then((K)=>{for(let{localId:O,file:C}of D){if(Y.delete(O))continue;z(O,{threadId:K}),$.uploadAttachment(K,C).then((T)=>{if(Y.delete(O)){$.deleteAttachment(T.id).catch(()=>{});return}z(O,{status:"ready",attachmentId:T.id,summary:T})},()=>V(O))}},()=>{for(let{localId:K}of D)V(K)})}function q(H){let D=Q.find((K)=>K.localId===H);if(!D)return;if(D.status==="uploading"){Y.add(H),J(Q.filter((K)=>K.localId!==H));return}if(D.attachmentId){z(H,{status:"deleting"}),$.deleteAttachment(D.attachmentId).then(()=>J(Q.filter((K)=>K.localId!==H)),()=>z(H,{status:"error"}));return}J(Q.filter((K)=>K.localId!==H))}function L(H){let D=[];for(let K of Q){if(K.threadId!==void 0&&K.threadId!==H){D.push(K);continue}if(K.status==="uploading")Y.add(K.localId);else if(K.status==="ready"&&K.threadId===H&&K.attachmentId)$.deleteAttachment(K.attachmentId).catch(()=>{})}J(D)}function U(){let H=Q.flatMap((D)=>D.status==="ready"&&D.summary?[{...D,status:"ready",summary:D.summary}]:[]);return J(Q.filter((D)=>D.status!=="ready")),N=H,H}function k(H){let D=N;if(N=[],D.some((K)=>K.threadId!==H))return;J([...D.map((K)=>({...K,status:"error"})),...Q])}function M(){N=[]}return{getState:Z,subscribe:G,accept:W,remove:q,clear:L,consumeReady:U,restoreConsumed:k,discardConsumed:M}}function F1(_){return{uploading:_.some(($)=>$.status==="uploading"),busy:_.some(($)=>$.status==="uploading"||$.status==="deleting"),hasReady:_.some(($)=>$.status==="ready")}}var d2=["completed","cancelled","failed"],k0="requestLocation";function M0(_,$,X){if($!==X)return null;if(typeof _!=="object"||_===null)return null;let Y=_;if(Y.type!=="cortex:client-tool")return null;let Q=d2.find((Z)=>Z===Y.status);if(!Q)return null;let N=Y.reference;return{type:"cortex:client-tool",status:Q,...typeof N==="string"?{reference:N}:{},...Y.result!==void 0?{result:Y.result}:{}}}function U1(_,$,X){try{return new URL(_).origin===$&&!X?"allow-scripts allow-forms allow-popups":"allow-scripts allow-forms allow-popups allow-same-origin"}catch{return"allow-scripts allow-forms allow-popups"}}function q1(_,$,X){try{return X===!0&&new URL(_).origin===$}catch{return!1}}function L1(_,$){try{return _.contentWindow?.location.origin===$}catch{return!1}}function k1(_){let $=!1,X=!1,Y,Q;function N(J){if(!$)_.onState(J)}function Z(){if($)return;X=!1,N({phase:"error"})}function G(J){if($||X)return;X=!0,N({phase:"settling"});try{let z=_.submit(J);if(z instanceof Promise)z.catch(Z)}catch{Z()}}return{async start(){N({phase:"initiating"});try{let J=await _.initiate();if(!J.embed){N({phase:"unavailable"});return}if(!/^https?:$/.test(new URL(J.embedUrl).protocol)){N({phase:"error"});return}Y=J.embedOrigin,N({phase:"embedded",embedUrl:J.embedUrl,surface:J.surface,embedOrigin:J.embedOrigin})}catch(J){let z=J instanceof Error?J.message:"";N({phase:/HTTP 404/.test(z)?"unavailable":"error"})}},setSource(J){if(J!==null&&J!==void 0)Q=J},handleMessage(J){if(!Y)return;if(Q===void 0||J.source!==Q)return;let z=M0(J.data,J.origin,Y);if(!z)return;G({status:z.status,reference:z.reference,result:z.result})},cancel(){G({status:"cancelled"})},terminate(){if($||X)return;Y=void 0,Q=void 0,N({phase:"error"})},dispose(){$=!0}}}function M1(_,$,X){let Y=_.interrupts.find((Q)=>Q.id===$);if(!Y||!("resolveInterrupt"in Y))return _.addToolApprovalResponse({id:$,approved:X});return Y.resolveInterrupt({approved:X}),Promise.resolve()}async function L_(_,$){let X=await import("leaflet"),Y=!$.interactive,Q=X.map(_,{center:$.center,zoom:$.zoom,zoomControl:!Y,dragging:!Y,scrollWheelZoom:!Y,doubleClickZoom:!Y,touchZoom:!Y,boxZoom:!Y,keyboard:!Y});X.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'}).addTo(Q);let N=new ResizeObserver(()=>Q.invalidateSize());return N.observe(_),{leaflet:X,map:Q,dispose(){N.disconnect(),Q.remove()}}}var S_={position:void 0,locating:!1,locateFailed:!1,mapFailed:!1,submitting:!1,deliveryFailed:!1},n2={center:{lat:20,lng:0},zoom:2},i2=13,P0=16,r2=1e4;function O1(_,$){let X=S_,Y=!1,Q=!1,N,Z,G,J=0;function z(L){if(X={...X,...L},!Y)$.onState(X)}function V(){let L=X.position;if(!N||!L)return;let{leaflet:U,map:k}=N;if(Z)Z.setLatLng(L);else{let M=U.marker(L,{draggable:!X.submitting}).addTo(k);M.on("dragend",()=>{let{lat:H,lng:D}=M.getLatLng();W({lat:H,lng:O0(D)})}),Z=M}G?.remove(),G=L.accuracy?U.circle(L,{radius:L.accuracy}).addTo(k):void 0}function W(L){if(X.submitting)return;J+=1,z({position:L,locating:!1,locateFailed:!1}),V()}function q(L){if(Y||Q)return;Q=!0,J+=1,Z?.dragging?.disable(),z({submitting:!0,locating:!1,deliveryFailed:!1});let U=()=>{Q=!1,Z?.dragging?.enable(),z({submitting:!1,deliveryFailed:!0})};try{let k=$.submit(L);if(k instanceof Promise)k.catch(U)}catch{U()}}return{async start(){let L=$.center?{center:$.center,zoom:i2}:n2,U;try{U=await L_(_,{...L,interactive:!0})}catch{z({mapFailed:!0});return}if(Y){U.dispose();return}N=U,U.map.on("click",(k)=>W({lat:k.latlng.lat,lng:O0(k.latlng.lng)})),V()},locate(){if(X.locating||X.submitting)return;if(!navigator.geolocation){z({locateFailed:!0});return}J+=1;let L=J;z({locating:!0,locateFailed:!1}),navigator.geolocation.getCurrentPosition(({coords:U})=>{if(Y||L!==J)return;let k={lat:U.latitude,lng:U.longitude,accuracy:Math.round(U.accuracy)};W(k),N?.map.setView(k,P0)},()=>{if(L===J)z({locating:!1,locateFailed:!0})},{enableHighAccuracy:!0,timeout:r2})},confirm(){if(X.position)q({status:"completed",result:X.position})},cancel(){q({status:"cancelled"})},dispose(){Y=!0,N?.dispose()}}}function P1(_,$,X){let Y=!1,Q;return L_(_,{center:$,zoom:P0,interactive:!1}).then((N)=>{if(Y){N.dispose();return}Q=N.dispose,N.leaflet.marker($).addTo(N.map)},()=>{if(!Y)X()}),()=>{Y=!0,Q?.()}}function O0(_){if(_>=-180&&_<=180)return _;return((_+180)%360+360)%360-180}function A0(_){if(!_||typeof _!=="object")return!1;let{lat:$,lng:X}=_;return typeof $==="number"&&typeof X==="number"&&Math.abs($)<=90&&Math.abs(X)<=180}function A1(_){let $=_&&typeof _==="object"?_.center:void 0;return A0($)?$:void 0}function E1(_){if(!_||typeof _!=="object")return;let{status:$,result:X}=_;if($!=="completed"||!A0(X))return;let{accuracy:Y}=X;return{...X,...typeof Y==="number"?{accuracy:Y}:{}}}function v_(_){let $=`${_.lat.toFixed(4)}, ${_.lng.toFixed(4)}`;return _.accuracy?`${$} ±${_.accuracy} m`:$}function R1(_){if(_.locating)return{key:"translate_location_locating",failed:!1};if(_.deliveryFailed)return{key:"translate_location_send_failed",failed:!0};if(_.locateFailed)return{key:"translate_location_locate_failed",failed:!0};if(_.mapFailed)return{key:"translate_location_map_failed",failed:!0};return{key:"translate_location_hint",failed:!1}}function y1(_){return Math.min(1000*2**(_-1),30000)}var o2=1e4;function w1(_){let $,X,Y=0,Q=!1;function N(){let{wsUrl:G,transport:J}=_.getConfig();if(G===!1)return;let z=a2(G,J.baseUrl);Y1(J).then((V)=>{if(Q)return;$=new WebSocket(t2(z,V)),$.addEventListener("open",()=>{let W=$;setTimeout(()=>{if($===W&&!Q)Y=0},o2),_.onOpen?.()}),$.addEventListener("message",(W)=>{let q=W.data;if(typeof q!=="string")return;let L;try{L=JSON.parse(q)}catch{return}_.onEvent(L)}),$.addEventListener("close",Z)}).catch(Z)}function Z(){if(Q||X)return;Y+=1,X=setTimeout(()=>{X=void 0,N()},y1(Y))}return N(),{close(){Q=!0,clearTimeout(X),$?.close()}}}function a2(_,$){if(_)return _;let X=typeof $==="string"?$:$(),Y=new URL(X,window.location.origin);return Y.protocol=Y.protocol==="https:"?"wss:":"ws:",Y.pathname=Y.pathname.replace(/\/$/,"")+"/ws",Y.toString()}function t2(_,$){let X=$.Authorization??$.authorization;if(!X?.startsWith("Bearer "))return _;let Y=new URL(_,window.location.origin);if(Y.searchParams.has("token"))return Y.toString();return Y.searchParams.set("token",X.slice(7)),Y.toString()}function I1(_,$,X=y1){let Y=!1,Q,N=0;function Z(){_.getCapabilities().then((G)=>{if(!Y)$(G)},()=>{if(Y)return;N+=1,Q=setTimeout(Z,X(N))})}return Z(),function(){Y=!0,clearTimeout(Q)}}function T_(_){return[..._].sort(($,X)=>{let Y=Date.parse(X.updatedAt)-Date.parse($.updatedAt);if(Y!==0)return Y;return Date.parse(X.createdAt)-Date.parse($.createdAt)})}function k_(_,$){let X=[..._],Y=X.findIndex((Q)=>Q.id===$.id);if(Y===-1)X.push($);else X[Y]={...X[Y],...$};return T_(X)}function f_(_,$){return _.filter((X)=>X.id!==$)}function b1(_,$){switch($.type){case"thread:deleted":return f_(_,$.payload.threadId);case"thread:created":case"thread:title-updated":case"thread:run-started":case"thread:run-finished":case"thread:messages-updated":return k_(_,$.payload.thread);default:return _}}import{marked as s2}from"marked";import e2 from"dompurify";function C1(_,$=[]){if(!_)return"";let X=s2.parse(_,{async:!1});if(X=X.replace(/<table>/g,'<div style="overflow-x:auto"><table style="width:auto">').replace(/<\/table>/g,"</table></div>").replace(/<(t[hd])([\s>])/g,'<$1 style="padding:0.5rem 1rem"$2'),$.length)X=_5(X,$);return e2.sanitize(X,{FORBID_TAGS:["img","picture","source"]})}function _5(_,$){let X=document.createElement("template");X.innerHTML=_;let Y=[...$].sort((Z,G)=>Z.length-G.length),Q=Y[Y.length-1]?.length??0,N=0;for(let Z of $5(X.content)){if(N>=Q)break;Z.replaceWith(...X5(Z.data,N,Y)),N+=Z.data.length}return X.innerHTML}function $5(_){let $=document.createTreeWalker(_,4),X=[];for(let Y=$.nextNode();Y;Y=$.nextNode())if(Y.data.trim())X.push(Y);return X.reverse()}function X5(_,$,X){let Y=[],Q=_.length;for(let N of X){if(N.length<=$)continue;if(Q<=0)break;let Z=Math.min(Q,N.length-$);if(Z<Q&&/[\uDC00-\uDFFF]/.test(_[Q-Z]))Z+=1;let G=document.createElement("span");G.className="cortex-stream-fade",G.style.animationDelay=`-${N.age}ms`,G.textContent=_.slice(Q-Z,Q),Y.unshift(G),Q-=Z,$+=Z}if(Q>0)Y.unshift(document.createTextNode(_.slice(0,Q)));return Y}function E0(){let _=null;return($)=>{let X=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec($),Y=X?.[1],Q=X?.[2]??"";if(Y){let N=Y.charAt(0);if(_){if(N===_.marker&&Y.length>=_.length&&Q.trim()==="")return _=null,"close";return"inside"}if(N==="`"&&Q.includes("`"))return"outside";return _={marker:N,length:Y.length},"open"}return _?"inside":"outside"}}var Y5=/^\s*!\[([^\]]*)\]\(attachment#([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)\s*$/i,Q5=/^\s*(`{3,}|~{3,})/;function S1(_,$){let X=[],Y=[],Q=null;function N(){if(Y.length)X.push({kind:"markdown",text:Y.join(`
4
+ `)}function H1(_,$){if($&&_.name in $)return!1;return _.name!==f_||!v(_.state)}function I0(_,$){if(_.type!=="tool-call")return!0;return!v(_.state)&&!_.approval&&$.foldable(_)}function B1(_,$){let X=O_(_);if(!X)return;let Y=J_(X.parts,{debugMode:!1,isStreaming:!0}),Q=Y.at(-1);if(Q&&I0(Q,$))return Q;return Y.filter((N)=>N.type==="tool-call"&&I0(N,$)).at(-1)}function F1(){let _=new Map;return($,X)=>{let Y=new Map;for(let[Q,N]of a2($,X)){let Z=_.get(Q);Y.set(Q,Z&&s2(Z,N)?Z:N)}return _=Y,Y}}function a2(_,$){let X=new Map;if($.debugMode)return X;let Q=$.agentWorking||a(_).length>0?t2(_):_,N=[];function Z(){let G=N[0]?.part.id;if(N.length>1&&G&&!$.opened.has(G))for(let[J,{messageId:z,part:V}]of N.entries()){let W=X.get(z)??new Map;X.set(z,W);let U=J===N.length-1;W.set(V,U?{kind:"more",count:N.length-1,runId:G}:{kind:"hidden"})}N=[]}for(let G of Q){if(G.role!=="assistant"){Z();continue}let J=J_(G.parts,{debugMode:!1,isStreaming:!1});for(let z of J)if(z.type==="tool-call"&&v(z.state)&&$.foldable(z))N.push({messageId:G.id,part:z});else Z()}return Z(),X}function t2(_){let $=_.map((X)=>X.role).lastIndexOf("user");return $<0?[]:_.slice(0,$)}function s2(_,$){if(_.size!==$.size)return!1;for(let[X,Y]of _){let Q=$.get(X);if(!Q||Q.kind!==Y.kind)return!1;if(Y.kind==="more"&&Q.kind==="more"){if(Y.count!==Q.count||Y.runId!==Q.runId)return!1}}return!0}import{EventType as S0}from"@tanstack/ai";import{fetchServerSentEvents as C0}from"@tanstack/ai-client";function e2(_){for(let $=_.length-1;$>=0;$-=1){let X=_[$],Y="parts"in X&&X.parts.some((Q)=>Q.type==="tool-result"||Q.type==="tool-call"&&Q.state==="approval-responded");if(X.role==="user"||Y)return _.slice($,$+1)}return _.slice(-1)}function _5(_){if(_.state==="approval-responded"){let $=_.approval?.approved;if($===void 0)return null;return{toolCallId:_.id,output:null,state:$?"approved":"denied"}}if(!v(_.state))return null;return{toolCallId:_.id,output:_.output??null,state:_.state==="error"?"error":"complete"}}function $5(_){let[$]=_;if(!$||$.role!=="assistant"||!("parts"in $))return null;let X=$.parts.flatMap((Y)=>{let Q=Y.type==="tool-call"?_5(Y):null;return Q?[Q]:[]});return X.length>0?X:null}async function*b0(_,$,X){for await(let Y of _){if(Y.type!==S0.MESSAGES_SNAPSHOT){yield Y;continue}let Q=$.localMessages(),N=Q.findIndex((G)=>G.id===X),Z=N===-1?[]:Q.slice(N+1).filter((G)=>G.role==="user");$.onTranscriptCarried?.(Y.timestamp??Date.now()),yield{...Y,messages:[...Y.messages,...Z]}}}function q1(_){let{api:$,thread:X}=_,Y=async()=>({headers:await $.resolveHeaders()}),Q=C0(()=>$.resolveUrl("/chat"),Y),N=function(J,z,V,W){let U=e2(J),B=$5(U),F=B?Q.connect([],{...z,[k0]:B},V,W):Q.connect(U,z,V,W);return b0(F,_,J.at(-1)?.id)},Z=C0(()=>$.resolveUrl(`/chat/${X.id}/stream`),Y),G=[];return{connect:N,async*joinRun(J,z){yield{type:S0.MESSAGES_SNAPSHOT,timestamp:Date.now(),messages:G},yield*b0(Z.joinRun(J,z),_,G.at(-1)?.id)},hydrate:async()=>{let J=await X5(_);return G=J.messages,J}}}async function X5(_){let{api:$,thread:X,mode:Y}=_,Q=X.isRunning?{runId:X.id}:null;if(Y==="skip")return{messages:[],activeRun:Q,interrupts:null};if(Y==="load")_.setLoadingMessages?.(!0);try{let Z=(await $.listMessages(X.id)).map(Q1);return _.onHydrated?.(Z),{messages:Z,activeRun:Q,interrupts:null}}finally{_.setLoadingMessages?.(!1)}}async function U1(_){if(_.isStale?.()||_.isStreaming())return;try{let $=await _.api.listMessages(_.threadId);if(_.isStale?.()||_.isStreaming())return;let X=$.map(Q1);return _.setMessages(X),X}catch{return}}function M_(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let _=crypto.getRandomValues(new Uint8Array(16));_[6]=_[6]&15|64,_[8]=_[8]&63|128;let $=Array.from(_,(X)=>X.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}function L1(_){let{api:$}=_,X=new Set,Y=new Set,Q=[],N=[];function Z(){return Q}function G(D){return X.add(D),()=>{X.delete(D)}}function J(D){Q=D;for(let H of X)H()}function z(D,H){J(Q.map((K)=>K.localId===D?{...K,...H}:K))}function V(D){if(Y.delete(D))return;z(D,{status:"error"})}function W(D){let H=[];for(let K of D){let M=M0(K.type,K.size)!=="ok"||Q.filter((R)=>R.status!=="error").length>=P0,k=M_();if(J([...Q,{localId:k,filename:K.name,status:M?"error":"uploading"}]),!M)H.push({localId:k,file:K})}if(!H.length)return;_.ensureThread().then((K)=>{for(let{localId:M,file:k}of H){if(Y.delete(M))continue;z(M,{threadId:K}),$.uploadAttachment(K,k).then((R)=>{if(Y.delete(M)){$.deleteAttachment(R.id).catch(()=>{});return}z(M,{status:"ready",attachmentId:R.id,summary:R})},()=>V(M))}},()=>{for(let{localId:K}of H)V(K)})}function U(D){let H=Q.find((K)=>K.localId===D);if(!H)return;if(H.status==="uploading"){Y.add(D),J(Q.filter((K)=>K.localId!==D));return}if(H.attachmentId){z(D,{status:"deleting"}),$.deleteAttachment(H.attachmentId).then(()=>J(Q.filter((K)=>K.localId!==D)),()=>z(D,{status:"error"}));return}J(Q.filter((K)=>K.localId!==D))}function B(D){let H=[];for(let K of Q){if(K.threadId!==void 0&&K.threadId!==D){H.push(K);continue}if(K.status==="uploading")Y.add(K.localId);else if(K.status==="ready"&&K.threadId===D&&K.attachmentId)$.deleteAttachment(K.attachmentId).catch(()=>{})}J(H)}function F(){let D=Q.flatMap((H)=>H.status==="ready"&&H.summary?[{...H,status:"ready",summary:H.summary}]:[]);return J(Q.filter((H)=>H.status!=="ready")),N=D,D}function O(D){let H=N;if(N=[],H.some((K)=>K.threadId!==D))return;J([...H.map((K)=>({...K,status:"error"})),...Q])}function P(){N=[]}return{getState:Z,subscribe:G,accept:W,remove:U,clear:B,consumeReady:F,restoreConsumed:O,discardConsumed:P}}function O1(_){return{uploading:_.some(($)=>$.status==="uploading"),busy:_.some(($)=>$.status==="uploading"||$.status==="deleting"),hasReady:_.some(($)=>$.status==="ready")}}function P1(_,$,X){try{return new URL(_).origin===$&&!X?"allow-scripts allow-forms allow-popups":"allow-scripts allow-forms allow-popups allow-same-origin"}catch{return"allow-scripts allow-forms allow-popups"}}function M1(_,$,X){try{return X===!0&&new URL(_).origin===$}catch{return!1}}function k1(_,$){try{return _.contentWindow?.location.origin===$}catch{return!1}}function A1(_){let $=!1,X=!1,Y,Q;function N(J){if(!$)_.onState(J)}function Z(){if($)return;X=!1,N({phase:"error"})}function G(J){if($||X)return;X=!0,N({phase:"settling"});try{let z=_.submit(J);if(z instanceof Promise)z.catch(Z)}catch{Z()}}return{async start(){N({phase:"initiating"});try{let J=await _.initiate();if(!J.embed){N({phase:"unavailable"});return}if(!/^https?:$/.test(new URL(J.embedUrl).protocol)){N({phase:"error"});return}Y=J.embedOrigin,N({phase:"embedded",embedUrl:J.embedUrl,surface:J.surface,embedOrigin:J.embedOrigin})}catch(J){let z=J instanceof Error?J.message:"";N({phase:/HTTP 404/.test(z)?"unavailable":"error"})}},setSource(J){if(J!==null&&J!==void 0)Q=J},handleMessage(J){if(!Y)return;if(Q===void 0||J.source!==Q)return;let z=R0(J.data,J.origin,Y);if(!z)return;G({status:z.status,reference:z.reference,result:z.result})},cancel(){G({status:"cancelled"})},terminate(){if($||X)return;Y=void 0,Q=void 0,N({phase:"error"})},dispose(){$=!0}}}function E1(_,$,X){let Y=_.interrupts.find((Q)=>Q.id===$);if(!Y||!("resolveInterrupt"in Y))return _.addToolApprovalResponse({id:$,approved:X});return Y.resolveInterrupt({approved:X}),Promise.resolve()}async function k_(_,$){let X=await import("leaflet"),Y=!$.interactive,Q=X.map(_,{center:$.center,zoom:$.zoom,zoomControl:!Y,dragging:!Y,scrollWheelZoom:!Y,doubleClickZoom:!Y,touchZoom:!Y,boxZoom:!Y,keyboard:!Y});X.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'}).addTo(Q);let N=new ResizeObserver(()=>Q.invalidateSize());return N.observe(_),{leaflet:X,map:Q,dispose(){N.disconnect(),Q.remove()}}}var j_={position:void 0,locating:!1,locateFailed:!1,mapFailed:!1,submitting:!1,deliveryFailed:!1},Y5={center:{lat:20,lng:0},zoom:2},Q5=13,v0=16,N5=1e4;function R1(_,$){let X=j_,Y=!1,Q=!1,N,Z,G,J=0;function z(B){if(X={...X,...B},!Y)$.onState(X)}function V(){let B=X.position;if(!N||!B)return;let{leaflet:F,map:O}=N;if(Z)Z.setLatLng(B);else{let P=F.marker(B,{draggable:!X.submitting}).addTo(O);P.on("dragend",()=>{let{lat:D,lng:H}=P.getLatLng();W({lat:D,lng:T0(H)})}),Z=P}G?.remove(),G=B.accuracy?F.circle(B,{radius:B.accuracy}).addTo(O):void 0}function W(B){if(X.submitting)return;J+=1,z({position:B,locating:!1,locateFailed:!1}),V()}function U(B){if(Y||Q)return;Q=!0,J+=1,Z?.dragging?.disable(),z({submitting:!0,locating:!1,deliveryFailed:!1});let F=()=>{Q=!1,Z?.dragging?.enable(),z({submitting:!1,deliveryFailed:!0})};try{let O=$.submit(B);if(O instanceof Promise)O.catch(F)}catch{F()}}return{async start(){let B=$.center?{center:$.center,zoom:Q5}:Y5,F;try{F=await k_(_,{...B,interactive:!0})}catch{z({mapFailed:!0});return}if(Y){F.dispose();return}N=F,F.map.on("click",(O)=>W({lat:O.latlng.lat,lng:T0(O.latlng.lng)})),V()},locate(){if(X.locating||X.submitting)return;if(!navigator.geolocation){z({locateFailed:!0});return}J+=1;let B=J;z({locating:!0,locateFailed:!1}),navigator.geolocation.getCurrentPosition(({coords:F})=>{if(Y||B!==J)return;let O={lat:F.latitude,lng:F.longitude,accuracy:Math.round(F.accuracy)};W(O),N?.map.setView(O,v0)},()=>{if(B===J)z({locating:!1,locateFailed:!0})},{enableHighAccuracy:!0,timeout:N5})},confirm(){if(X.position)U({status:"completed",result:X.position})},cancel(){U({status:"cancelled"})},dispose(){Y=!0,N?.dispose()}}}function y1(_,$,X){let Y=!1,Q;return k_(_,{center:$,zoom:v0,interactive:!1}).then((N)=>{if(Y){N.dispose();return}Q=N.dispose,N.leaflet.marker($).addTo(N.map)},()=>{if(!Y)X()}),()=>{Y=!0,Q?.()}}function T0(_){if(_>=-180&&_<=180)return _;return((_+180)%360+360)%360-180}function f0(_){if(!_||typeof _!=="object")return!1;let{lat:$,lng:X}=_;return typeof $==="number"&&typeof X==="number"&&Math.abs($)<=90&&Math.abs(X)<=180}function I1(_){let $=_&&typeof _==="object"?_.center:void 0;return f0($)?$:void 0}function w1(_){if(!_||typeof _!=="object")return;let{status:$,result:X}=_;if($!=="completed"||!f0(X))return;let{accuracy:Y}=X;return{...X,...typeof Y==="number"?{accuracy:Y}:{}}}function g_(_){let $=`${_.lat.toFixed(4)}, ${_.lng.toFixed(4)}`;return _.accuracy?`${$} ±${_.accuracy} m`:$}function C1(_){if(_.locating)return{key:"translate_location_locating",failed:!1};if(_.deliveryFailed)return{key:"translate_location_send_failed",failed:!0};if(_.locateFailed)return{key:"translate_location_locate_failed",failed:!0};if(_.mapFailed)return{key:"translate_location_map_failed",failed:!0};return{key:"translate_location_hint",failed:!1}}function b1(_){return Math.min(1000*2**(_-1),30000)}var Z5=1e4;function S1(_){let $,X,Y=0,Q=!1;function N(){let{wsUrl:G,transport:J}=_.getConfig();if(G===!1)return;let z=G5(G,J.baseUrl);Z1(J).then((V)=>{if(Q)return;$=new WebSocket(J5(z,V)),$.addEventListener("open",()=>{let W=$;setTimeout(()=>{if($===W&&!Q)Y=0},Z5),_.onOpen?.()}),$.addEventListener("message",(W)=>{let U=W.data;if(typeof U!=="string")return;let B;try{B=JSON.parse(U)}catch{return}_.onEvent(B)}),$.addEventListener("close",Z)}).catch(Z)}function Z(){if(Q||X)return;Y+=1,X=setTimeout(()=>{X=void 0,N()},b1(Y))}return N(),{close(){Q=!0,clearTimeout(X),$?.close()}}}function G5(_,$){if(_)return _;let X=typeof $==="string"?$:$(),Y=new URL(X,window.location.origin);return Y.protocol=Y.protocol==="https:"?"wss:":"ws:",Y.pathname=Y.pathname.replace(/\/$/,"")+"/ws",Y.toString()}function J5(_,$){let X=$.Authorization??$.authorization;if(!X?.startsWith("Bearer "))return _;let Y=new URL(_,window.location.origin);if(Y.searchParams.has("token"))return Y.toString();return Y.searchParams.set("token",X.slice(7)),Y.toString()}function T1(_,$,X=b1){let Y=!1,Q,N=0;function Z(){_.getCapabilities().then((G)=>{if(!Y)$(G)},()=>{if(Y)return;N+=1,Q=setTimeout(Z,X(N))})}return Z(),function(){Y=!0,clearTimeout(Q)}}function m_(_){return[..._].sort(($,X)=>{let Y=Date.parse(X.updatedAt)-Date.parse($.updatedAt);if(Y!==0)return Y;return Date.parse(X.createdAt)-Date.parse($.createdAt)})}function A_(_,$){let X=[..._],Y=X.findIndex((Q)=>Q.id===$.id);if(Y===-1)X.push($);else X[Y]={...X[Y],...$};return m_(X)}function x_(_,$){return _.filter((X)=>X.id!==$)}function v1(_,$){switch($.type){case"thread:deleted":return x_(_,$.payload.threadId);case"thread:created":case"thread:title-updated":case"thread:run-started":case"thread:run-finished":case"thread:messages-updated":return A_(_,$.payload.thread);default:return _}}import{marked as z5}from"marked";import V5 from"dompurify";function f1(_,$=[]){if(!_)return"";let X=z5.parse(_,{async:!1});if(X=X.replace(/<table>/g,'<div style="overflow-x:auto"><table style="width:auto">').replace(/<\/table>/g,"</table></div>").replace(/<(t[hd])([\s>])/g,'<$1 style="padding:0.5rem 1rem"$2'),$.length)X=K5(X,$);return V5.sanitize(X,{FORBID_TAGS:["img","picture","source"]})}function K5(_,$){let X=document.createElement("template");X.innerHTML=_;let Y=[...$].sort((Z,G)=>Z.length-G.length),Q=Y[Y.length-1]?.length??0,N=0;for(let Z of W5(X.content)){if(N>=Q)break;Z.replaceWith(...D5(Z.data,N,Y)),N+=Z.data.length}return X.innerHTML}function W5(_){let $=document.createTreeWalker(_,4),X=[];for(let Y=$.nextNode();Y;Y=$.nextNode())if(Y.data.trim())X.push(Y);return X.reverse()}function D5(_,$,X){let Y=[],Q=_.length;for(let N of X){if(N.length<=$)continue;if(Q<=0)break;let Z=Math.min(Q,N.length-$);if(Z<Q&&/[\uDC00-\uDFFF]/.test(_[Q-Z]))Z+=1;let G=document.createElement("span");G.className="cortex-stream-fade",G.style.animationDelay=`-${N.age}ms`,G.textContent=_.slice(Q-Z,Q),Y.unshift(G),Q-=Z,$+=Z}if(Q>0)Y.unshift(document.createTextNode(_.slice(0,Q)));return Y}function j0(){let _=null;return($)=>{let X=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec($),Y=X?.[1],Q=X?.[2]??"";if(Y){let N=Y.charAt(0);if(_){if(N===_.marker&&Y.length>=_.length&&Q.trim()==="")return _=null,"close";return"inside"}if(N==="`"&&Q.includes("`"))return"outside";return _={marker:N,length:Y.length},"open"}return _?"inside":"outside"}}var H5=/^\s*!\[([^\]]*)\]\(attachment#([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)\s*$/i,B5=/^\s*(`{3,}|~{3,})/;function j1(_,$){let X=[],Y=[],Q=null;function N(){if(Y.length)X.push({kind:"markdown",text:Y.join(`
5
5
  `)});Y=[]}function Z(z){if(Q)X.push({kind:"media",...Q,source:Q.source.join(`
6
- `),closed:z});Q=null}let G=E0(),J=_.split(`
7
- `);for(let[z,V]of J.entries()){let W=G(V);if(Q){if(W==="close")Z(!0);else Q.source.push(V);continue}if(W==="open"&&z===J.length-1)break;let q=N5(V,W,$);if(!q){Y.push(V);continue}if(N(),q.kind==="media")Q={language:q.language,source:[]};else X.push(q)}return Z(!1),N(),X}function N5(_,$,X){if($==="open"){let Q=_.replace(Q5,"").trim().split(/\s+/)[0],N=X.find((Z)=>Z===Q);return N?{kind:"media",language:N}:void 0}let Y=$==="outside"?Y5.exec(_):null;return Y?{kind:"attachment",alt:Y[1]??"",id:(Y[2]??"").toLowerCase()}:void 0}var w0=new Set(["flatten","fold","density","impute","regression","loess","quantile","sample"]),Z5=`Use Vega-Lite JSON with inline \`data.values\` only, at most 200 rows, and no \`url\` anywhere. Compute folds, trend lines and densities yourself. For several series, write one row per series and x value, or keep one row per x value and draw a layer per series (color by \`datum\`) when that would exceed the row limit. These keys are refused anywhere in the spec: ${[...w0,"params","selection"].join(", ")}. Expressions in \`calculate\`, \`filter\` and \`labelExpr\` may use only datum fields, literals, operators and simple math or date-part functions (no format or timeFormat), so put formatted values in the rows or use an axis \`format\`.`;function I0(_,$){if(_==="url")return"Charts may only use inline data and no URLs.";if(_==="sequence"||_==="graticule")return"Charts may only use inline data.";if(w0.has(_))return"Charts may not use transforms that generate rows.";if(_==="params"||_==="selection"||_==="signals"||_==="on")return"Charts may not be interactive.";if(_==="expr")return"Charts may not carry expressions.";if(G5.has(_)&&typeof $==="string"&&!J5($))return"Charts may only use simple expressions over datum.";if(_==="usermeta")return"Charts may not carry usermeta.";if(typeof $==="string"&&j_($))return"Charts may not reference URLs.";if((_==="width"||_==="height")&&z5($)>4000)return"Charts may be at most 4000 pixels wide or tall.";return}var G5=new Set(["calculate","filter","test","signal","labelExpr"]),R0=new Set(["abs","ceil","floor","round","min","max","sqrt","pow","log","exp","year","month","date","day","hours","minutes","toNumber","toString","toDate","isValid","isNaN","if","indexof","length"]);function J5(_){if(_.length>500||/[\\`]/.test(_))return!1;let $=_.replace(/'[^']*'|"[^"]*"/g,'""');for(let[,Y]of $.matchAll(/([A-Za-z_$][\w$]*)\s*\(/g))if(!R0.has(Y??""))return!1;let X=$.replace(/(datum|parent)(\s*\.[\w$]+|\s*\[\s*""\s*\])+|\b\d[\w.]*/g,"").matchAll(/[A-Za-z_$][\w$]*/g);for(let[Y]of X)if(!R0.has(Y)&&!["true","false","null"].includes(Y))return!1;return!0}function z5(_){if(typeof _==="number")return _;let $=_?.step;return typeof $==="number"?$:0}function y0(_,$){let X=_?.features,Y=Array.isArray(_)?_.length:Array.isArray(X)?X.length:-1;if(Y<0)return I0($,_)??T1(v1(_,$),M_);return Y>200?"Charts may hold at most 200 rows.":void 0}function M_(_,$=""){if($==="values")return y0(_,$);if($==="datasets")return T1(v1(_),y0);return I0($,_)??T1(v1(_,$),(X,Y)=>M_(X,Y))}function v1(_,$=""){if(Array.isArray(_))return _.map((X)=>[$,X]);return _&&typeof _==="object"?Object.entries(_):[]}function T1(_,$){for(let[X,Y]of _){let Q=$(Y,X);if(Q)return Q}return}var b0=/url\(([^)]*)\)/gi,f1="src|image|image-set|-webkit-image-set|cross-fade|element",j1=new RegExp(String.raw`\b(url|${f1})\(`,"i"),V5=new RegExp(String.raw`\b(${f1})\(`,"i"),K5=new RegExp(String.raw`\b(${f1})\([^)]*\)`,"gi"),W5=/\\([0-9a-f]{1,6})\s?|\\(.)/gi;function D5(_){return _.replace(W5,($,X,Y)=>{if(!X)return Y??"";let Q=parseInt(X,16),N=Q===0||Q>=55296&&Q<=57343||Q>1114111;return String.fromCodePoint(N?65533:Q)})}function C0(_){return _.trim().replace(/^(['"])(.*)\1$/s,"$2").trim()}function j_(_){if(_.includes("\\")||V5.test(_))return!0;for(let[,$]of _.matchAll(b0))if(!C0($??"").startsWith("#"))return!0;return!1}function g1(_){return D5(_).replace(K5,"none").replace(b0,($,X)=>C0(X).startsWith("#")?$:"none")}var g0={async mermaid(_,$,{scheme:X}){let[{default:Y},{default:Q}]=await Promise.all([import("mermaid"),import("dompurify")]);if(j1.test($)||$.includes("\\"))throw Error("Diagrams may not reference URLs.");if(/%%\{/.test($))throw Error("Diagrams may not carry init directives.");if(/^\s*---\s*$/m.test($))throw Error("Diagrams may not carry frontmatter.");if(/\bimg\s*:/.test($))throw Error("Diagrams may not embed images.");let N=F5($);if(!B5.test(N))throw Error(`Unsupported diagram type: ${N}`);let Z=S0.then(async()=>{if(!v0)Y.initialize({startOnLoad:!1,securityLevel:"strict",htmlLabels:!1}),v0=!0;let z=`%%{init: {"theme": "${X==="dark"?"dark":"default"}"}}%%
8
- ${$}`;return await Y.parse(z),(await Y.render(`cortex-mermaid-${U5()}`,z,_)).svg});S0=Z.catch(()=>{return});let G=await Z,J=document.createElement("div");return J.innerHTML=Q.sanitize(G,{USE_PROFILES:{svg:!0,svgFilters:!0}}),f0(J),_.replaceChildren(...J.childNodes),()=>{_.innerHTML=""}},async "vega-lite"(_,$,{scheme:X}){let Y=JSON.parse($),Q=M_(Y);if(Q)throw Error(Q);let[{default:N},Z]=await Promise.all([import("vega-embed"),import("vega")]),G=()=>Promise.reject(Error("Charts may only use inline data.")),J=document.createElement("div"),z=await N(J,Y,{actions:!1,renderer:"svg",mode:"vega-lite",loader:{...Z.loader(),load:G,sanitize:G},ast:!0,...X==="dark"?{theme:"dark"}:{},config:{background:"transparent"}});return f0(J),_.replaceChildren(J),()=>z.finalize()},async map(_,$){let X=L5(JSON.parse($)),{leaflet:Y,map:Q,dispose:N}=await L_(_,{...X,interactive:!0});for(let Z of X.markers){let G=Y.marker(Z.position).addTo(Q);if(Z.label){let J=document.createElement("span");J.textContent=Z.label,G.bindTooltip(J)}}return N}},H5={mermaid:"translate_media_pending_mermaid","vega-lite":"translate_media_pending_vega_lite",map:"translate_media_pending_map"};function m1(_){return H5[_]??"translate_media_pending"}function x1(_){return Object.keys({...g0,..._})}function c1(_,$){let{language:X,source:Y,context:Q,overrides:N,onError:Z}=$,G=_.appendChild(document.createElement("div")),J=N?.[X]??g0[X],z,V=!1;return(J?J(G,Y,Q):Promise.reject(Error(`No renderer for ${X}.`))).then((q)=>{if(V)q();else z=q},(q)=>{if(!V)Z(q instanceof Error?q.message:String(q))}),()=>{V=!0,z?.(),G.remove()}}var B5=/^(flowchart|graph|sequenceDiagram|stateDiagram(-v2)?|erDiagram|gantt|pie|classDiagram|journey|timeline|mindmap)$/;function F5(_){let $=_.split(`
9
- `).find((X)=>/\S/.test(X)&&!/^\s*%%/.test(X));return/^\s*(\S+)/.exec($??"")?.[1]??""}var S0=Promise.resolve(),v0=!1,T0=0;function U5(){return T0+=1,T0}var q5=new Set(["image","use","feImage"]);function f0(_){for(let $ of[_,..._.querySelectorAll("*")]){for(let X of[...$.attributes])if((X.name==="href"||X.name==="xlink:href")&&q5.has($.tagName)&&!X.value.trim().startsWith("#")||j_(X.value))$.removeAttribute(X.name);if($.tagName==="style"&&$.textContent)$.textContent=g1($.textContent)}}function L5(_){if(!_||typeof _!=="object")throw Error("A map needs a JSON object.");let $=_,X=$.zoom??10;if(typeof X!=="number"||X<0||X>22)throw Error("zoom must be 0 to 22.");let Y=$.markers??[];if(!Array.isArray(Y))throw Error("markers must be a list.");return{center:j0($.center,"center"),zoom:X,markers:Y.map((Q,N)=>{let Z=Q??{},G=Z.label;return{position:j0(Z.position,`markers[${N}].position`),label:typeof G==="string"?G:void 0}})}}function j0(_,$){let X=Array.isArray(_)?_:[],[Y,Q]=X;if(typeof Y!=="number"||typeof Q!=="number"||Math.abs(Y)>90||Math.abs(Q)>180)throw Error(`${$} must be [latitude, longitude].`);return{lat:Y,lng:Q}}function h1(_,$){if(_!=="system")return $(_??"light"),()=>{};let X=window.matchMedia("(prefers-color-scheme: dark)"),Y=()=>$(X.matches?"dark":"light");return Y(),X.addEventListener("change",Y),()=>X.removeEventListener("change",Y)}import O_ from"highlight.js/lib/core";import k5 from"highlight.js/lib/languages/javascript";import M5 from"highlight.js/lib/languages/json";import O5 from"highlight.js/lib/languages/sql";var m0=!1;function P5(){if(m0)return;m0=!0,O_.registerLanguage("javascript",k5),O_.registerLanguage("json",M5),O_.registerLanguage("cypher",O5)}function u1(_,$){if(!_)return"";return P5(),O_.getLanguage($)?O_.highlight(_,{language:$}).value:A5(_)}function A5(_){return _.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var x0={translate_new:"جديد",translate_history:"السجل",translate_back:"رجوع",translate_greeting:"بماذا يمكنني مساعدتك اليوم؟",translate_n_conversations:"{{count}} محادثات",translate_one_conversation:"محادثة واحدة",translate_no_threads_yet:"لا توجد محادثات بعد",translate_start_a_new_conversation:"ابدأ محادثة جديدة",translate_untitled:"بدون عنوان",translate_new_chat:"محادثة جديدة",translate_normal:"عادي",translate_debug:"تصحيح",translate_type_a_message:"اكتب رسالة...",translate_thinking:"جارٍ معالجة الطلب...",translate_completed:"مكتمل",translate_attach_files:"إرفاق ملفات",translate_drop_files_here:"أفلت ملفاتك هنا...",translate_remove_attachment:"إزالة المرفق",translate_attachment_rejected:"لا يمكن إرفاق هذا الملف",translate_attachment_caption:"من فضلك اطّلع على الملفات المرفقة.",translate_download:"تنزيل",translate_tool_status_0:"جارٍ جلب البيانات…",translate_tool_status_1:"جارٍ تحليل المعلومات…",translate_tool_status_2:"جارٍ معالجة الطلب…",translate_tool_status_3:"جارٍ تجميع النتائج…",translate_tool_status_4:"جارٍ تحضير الرد…",translate_tool_status_5:"جارٍ البحث…",translate_tool_status_6:"جارٍ فحص السجلات…",translate_tool_status_7:"جارٍ مراجعة التفاصيل…",translate_tool_status_8:"جارٍ إجراء الحسابات…",translate_tool_status_9:"جارٍ سحب المعلومات…",translate_tool_done_0:"تم جلب البيانات بنجاح",translate_tool_done_1:"تم التحليل بنجاح",translate_tool_done_2:"تمت معالجة الطلب بنجاح",translate_tool_done_3:"تم تجميع النتائج بنجاح",translate_tool_done_4:"تم تحضير الرد بنجاح",translate_tool_done_5:"تم البحث بنجاح",translate_tool_done_6:"تم فحص السجلات بنجاح",translate_tool_done_7:"تمت المراجعة بنجاح",translate_tool_done_8:"تمت الحسابات بنجاح",translate_tool_done_9:"تم استرجاع المعلومات بنجاح",translate_rows_read:"{{count}} صفوف",translate_one_more_step:"وخطوة أخرى",translate_n_more_steps:"و{{count}} خطوات أخرى",translate_tool_error:"حدث خطأ",translate_attachment_status:"جارٍ قراءة الملف المرفق…",translate_attachment_done:"تمت قراءة الملف المرفق",translate_graph_0:"جارٍ استكشاف الروابط...",translate_graph_1:"جارٍ رسم الخريطة...",translate_graph_2:"جارٍ اكتشاف العلاقات...",translate_graph_3:"جارٍ تتبع الروابط...",translate_graph_4:"جارٍ التنقل في المعرفة...",translate_graph_5:"جارٍ كشف الرؤى...",translate_graph_6:"جارٍ ربط النقاط...",translate_graph_7:"جارٍ تتبع المسار...",translate_graph_8:"جارٍ تجميع الأجزاء...",translate_graph_9:"جارٍ بناء الصورة...",translate_code_0:"جارٍ حساب الأرقام...",translate_code_1:"جارٍ معالجة البيانات...",translate_code_2:"جارٍ تنفيذ طلبك...",translate_code_3:"جارٍ تحليل الأرقام...",translate_code_4:"جارٍ تجميع كل شيء...",translate_code_5:"جارٍ تحليل النتائج...",translate_code_6:"جارٍ العمل خلف الكواليس...",translate_code_7:"جارٍ ترتيب التفاصيل...",translate_code_8:"جارٍ تحضير إجابتك...",translate_code_9:"أوشك على الانتهاء...",translate_reasoning_0:"جارٍ التفكير...",translate_reasoning_1:"جارٍ دراسة الخيارات...",translate_reasoning_2:"جارٍ تقييم الاحتمالات...",translate_reasoning_3:"جارٍ التأمل في هذا...",translate_reasoning_4:"جارٍ إيجاد الحل...",translate_reasoning_5:"جارٍ ترتيب الأفكار...",translate_reasoning_6:"جارٍ التمعن في الأمر...",translate_reasoning_7:"جارٍ إيجاد أفضل طريقة...",translate_reasoning_8:"جارٍ تنظيم أفكاري...",translate_reasoning_9:"أوشك على الانتهاء...",translate_running:"قيد التنفيذ",translate_aborted:"تم الإلغاء",translate_input:"المدخلات",translate_output:"المخرجات",translate_calling:"جارٍ الاستدعاء",translate_input_ready:"المدخلات جاهزة",translate_needs_approval:"بحاجة إلى موافقة",translate_approved:"تمت الموافقة",translate_responded:"تم الرد",translate_declined:"تم الرفض",translate_approve:"موافقة",translate_deny:"رفض",translate_approval_prompt:"يريد المساعد تنفيذ إجراء. هل تسمح بذلك؟",translate_error:"خطأ",translate_approval_requested:"طلب موافقة",translate_approval_response:"رد الموافقة",translate_waiting_for_approval:"في انتظار الموافقة لتنفيذ هذه الأداة.",translate_tool_approved:"تمت الموافقة.",translate_tool_response_received:"تم استلام الرد.",translate_tokens:"رمز",translate_fresh:"جديد",translate_cache_read:"قراءة من الذاكرة",translate_cache_write:"كتابة في الذاكرة",translate_n_percent_cached:"{{percent}}٪ مخزّن مؤقتًا",translate_text:"نص",translate_reasoning:"الاستنتاج",translate_read:"قراءة",translate_write:"كتابة",translate_total:"الإجمالي",translate_request:"الطلب",translate_response:"الرد",translate_step_n:"الخطوة {{number}}",translate_inspect_llm_requests:"فحص طلبات النموذج",translate_loading:"جارٍ التحميل…",translate_no_llm_requests:"لا توجد طلبات نموذج مسجّلة لهذه الرسالة.",translate_unhandled_type:"نوع غير مدعوم:",translate_client_tool_title:"أكمل هذه الخطوة للمتابعة",translate_client_tool_loading:"جارٍ تجهيز خطوة آمنة...",translate_client_tool_failed:"تعذّر تحميل هذه الخطوة",translate_client_tool_retry:"حاول مرة أخرى",translate_client_tool_cancel:"إلغاء",translate_location_hint:"انقر على الخريطة لتثبيت الدبوس",translate_location_locate:"استخدم موقعي",translate_location_locating:"جارٍ تحديد موقعك",translate_location_locate_failed:"موقعك غير متاح",translate_location_map_failed:"تعذّر تحميل الخريطة",translate_location_send_failed:"تعذّر الإرسال، حاول مرة أخرى",translate_location_skip:"ليس الآن",translate_location_send:"إرسال",translate_location_shared:"تمت مشاركة الموقع",translate_location_not_shared:"لم تتم مشاركة الموقع",translate_trigger_fired:"تم التشغيل بواسطة",translate_trigger_payload:"الحمولة",translate_messages_disabled:"يعمل هذا الوكيل من مشغّلاته فقط.",translate_streaming:"جارٍ البث",translate_done:"تم",translate_no_reasoning:"لا يوجد تفكير مسجّل.",translate_copy:"نسخ إلى الحافظة",translate_copied:"تم النسخ",translate_media_pending_mermaid:"جارٍ رسم المخطط",translate_media_pending_vega_lite:"جارٍ رسم الرسم البياني",translate_media_pending_map:"جارٍ رسم الخريطة",translate_media_cut_off:"انقطع هذا المقطع قبل اكتماله.",translate_media_failed:"تعذر عرض هذا المقطع.",translate_media_source:"المصدر",translate_media_pending:"جارٍ الرسم",translate_image_unavailable:"الصورة غير متاحة",translate_image_unavailable_alt:"الصورة غير متاحة: {{alt}}",translate_send:"إرسال"};var c0={translate_new:"New",translate_history:"History",translate_back:"Back",translate_greeting:"What can I help you with today?",translate_n_conversations:"{{count}} conversations",translate_one_conversation:"1 conversation",translate_no_threads_yet:"No threads yet",translate_start_a_new_conversation:"Start a new conversation",translate_untitled:"Untitled",translate_new_chat:"New Chat",translate_normal:"Normal",translate_debug:"Debug",translate_type_a_message:"Type a message...",translate_thinking:"Thinking things through...",translate_completed:"Completed",translate_attach_files:"Attach files",translate_drop_files_here:"Drop your files here...",translate_remove_attachment:"Remove attachment",translate_attachment_rejected:"This file cannot be attached",translate_attachment_caption:"Please take a look at the attached files.",translate_download:"Download",translate_tool_status_0:"Fetching data...",translate_tool_status_1:"Analyzing information...",translate_tool_status_2:"Processing request...",translate_tool_status_3:"Gathering results...",translate_tool_status_4:"Preparing response...",translate_tool_status_5:"Looking things up...",translate_tool_status_6:"Checking records...",translate_tool_status_7:"Reviewing details...",translate_tool_status_8:"Running calculations...",translate_tool_status_9:"Pulling information...",translate_tool_done_0:"Data fetched successfully",translate_tool_done_1:"Analysis completed successfully",translate_tool_done_2:"Request processed successfully",translate_tool_done_3:"Results gathered successfully",translate_tool_done_4:"Response prepared successfully",translate_tool_done_5:"Lookup completed successfully",translate_tool_done_6:"Records checked successfully",translate_tool_done_7:"Review completed successfully",translate_tool_done_8:"Calculations completed successfully",translate_tool_done_9:"Information retrieved successfully",translate_rows_read:"{{count}} rows",translate_one_more_step:"and 1 more step",translate_n_more_steps:"and {{count}} more steps",translate_tool_error:"Something went wrong",translate_attachment_status:"Reading the attached file...",translate_attachment_done:"Finished reading the file",translate_graph_0:"Exploring connections...",translate_graph_1:"Mapping out the links...",translate_graph_2:"Discovering relationships...",translate_graph_3:"Tracing the connections...",translate_graph_4:"Navigating the knowledge...",translate_graph_5:"Uncovering insights...",translate_graph_6:"Connecting the dots...",translate_graph_7:"Following the trail...",translate_graph_8:"Piecing things together...",translate_graph_9:"Building the picture...",translate_code_0:"Running the numbers...",translate_code_1:"Working through the data...",translate_code_2:"Processing your request...",translate_code_3:"Crunching the figures...",translate_code_4:"Putting it all together...",translate_code_5:"Analyzing the results...",translate_code_6:"Working behind the scenes...",translate_code_7:"Sorting through the details...",translate_code_8:"Preparing your answer...",translate_code_9:"Almost ready...",translate_reasoning_0:"Thinking it through...",translate_reasoning_1:"Considering the options...",translate_reasoning_2:"Weighing the possibilities...",translate_reasoning_3:"Reflecting on this...",translate_reasoning_4:"Working it out...",translate_reasoning_5:"Putting thoughts together...",translate_reasoning_6:"Mulling it over...",translate_reasoning_7:"Finding the best approach...",translate_reasoning_8:"Organizing my thoughts...",translate_reasoning_9:"Almost there...",translate_running:"Running",translate_aborted:"Aborted",translate_input:"Input",translate_output:"Output",translate_calling:"Calling",translate_input_ready:"Input ready",translate_needs_approval:"Needs approval",translate_approved:"Approved",translate_responded:"Responded",translate_declined:"Declined",translate_approve:"Approve",translate_deny:"Deny",translate_approval_prompt:"The assistant wants to take an action. Allow it?",translate_error:"Error",translate_approval_requested:"Approval requested",translate_approval_response:"Approval response",translate_waiting_for_approval:"Waiting for approval to execute this tool.",translate_tool_approved:"Approved.",translate_tool_response_received:"Response received.",translate_tokens:"tokens",translate_fresh:"Fresh",translate_cache_read:"Cache read",translate_cache_write:"Cache write",translate_n_percent_cached:"{{percent}}% cached",translate_text:"Text",translate_reasoning:"Reasoning",translate_read:"Read",translate_write:"Write",translate_total:"Total",translate_request:"Request",translate_response:"Response",translate_step_n:"Step {{number}}",translate_inspect_llm_requests:"Inspect LLM requests",translate_loading:"loading…",translate_no_llm_requests:"No LLM requests recorded for this message.",translate_unhandled_type:"Unhandled type:",translate_client_tool_title:"Complete this step to continue",translate_client_tool_loading:"Preparing a secure step...",translate_client_tool_failed:"This step could not be loaded",translate_client_tool_retry:"Try again",translate_client_tool_cancel:"Cancel",translate_location_hint:"Tap the map to drop a pin",translate_location_locate:"Use my location",translate_location_locating:"Finding your location",translate_location_locate_failed:"Your location is not available",translate_location_map_failed:"The map could not be loaded",translate_location_send_failed:"Could not send, try again",translate_location_skip:"Not now",translate_location_send:"Send",translate_location_shared:"Location shared",translate_location_not_shared:"Location not shared",translate_trigger_fired:"Triggered by",translate_trigger_payload:"Payload",translate_messages_disabled:"This agent only runs from its triggers.",translate_streaming:"Streaming",translate_done:"Done",translate_no_reasoning:"No reasoning provided.",translate_copy:"Copy to clipboard",translate_copied:"Copied",translate_media_pending_mermaid:"Drawing diagram",translate_media_pending_vega_lite:"Drawing chart",translate_media_pending_map:"Drawing map",translate_media_cut_off:"This block was cut off before it finished.",translate_media_failed:"Could not render this block.",translate_media_source:"Source",translate_media_pending:"Drawing",translate_image_unavailable:"Image unavailable",translate_image_unavailable_alt:"Image unavailable: {{alt}}",translate_send:"Send"};var y5={en:c0,ar:x0};function l1(_){return _&&e_.includes(_)?_:e_[0]}function p1(_,$,X){let Y=y5[_][$];if(!X)return Y;return Y.replace(/\{\{\s*(\w+)\s*\}\}/g,(Q,N)=>(N in X)?String(X[N]):Q)}function P_(_,$,X){return _===1?$:X}function N_(_){if(typeof _==="string"){let $=_.trim();if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return _;try{return N_(JSON.parse($))}catch{return _}}if(Array.isArray(_))return _.map(($)=>N_($));if(_!==null&&typeof _==="object"){let $={};for(let[X,Y]of Object.entries(_))$[X]=N_(Y);return $}return _}function d1(_,$){if(Array.isArray(_)){let X=_;return{kind:"container",open:"[",close:"]",summary:h0(X.length,"item","items"),entries:X.map((Y,Q)=>({key:null,value:Y,path:`${$}[${Q}]`}))}}if(_!==null&&typeof _==="object"){let X=Object.entries(_);return{kind:"container",open:"{",close:"}",summary:h0(X.length,"property","properties"),entries:X.map(([Y,Q])=>({key:Y,value:Q,path:`${$}.${Y}`}))}}return{kind:"primitive",text:w5(_),className:I5(_)}}function h0(_,$,X){return`${_} ${_===1?$:X}`}function w5(_){if(_===null||_===void 0)return"null";if(typeof _==="string")return JSON.stringify(_);if(typeof _==="number"||typeof _==="boolean")return String(_);return JSON.stringify(_)??"null"}function I5(_){if(_===null||_===void 0)return"cortex-json-tree__null";if(typeof _==="string")return"cortex-json-tree__string";if(typeof _==="number")return"cortex-json-tree__number";if(typeof _==="boolean")return"cortex-json-tree__boolean";return""}function n1(_){if(!_)return null;try{return JSON.parse(_)}catch{return _}}function i1(_){if(!_)return"";try{return JSON.stringify(JSON.parse(_),null,2)}catch{return _}}function Z_(_,$){if(_===void 0||typeof _==="string"||Array.isArray(_))return _;let X=_;return X[$]??X.en??Object.values(X)[0]}function u(_,$,X=Date.now()){let Y=new Date(_);if(Number.isNaN(Y.getTime()))return"";let Q=Y.toDateString()===new Date(X).toDateString();return new Intl.DateTimeFormat($,{...Q?{}:{dateStyle:"medium"},timeStyle:"short"}).format(Y)}function r1(_,$){let X=URL.createObjectURL(_),Y=document.createElement("a");Y.href=X,Y.download=$,Y.click(),URL.revokeObjectURL(X)}class o{onUpdate;fullText="";displayedLength=0;animationFrameId=null;isDone=!1;releases=[];static DRAIN_FRACTION=0.03;static MIN_CHARS_PER_FRAME=1;static DONE_DRAIN_FRACTION=0.1;static FADE_WINDOW_MS=500;constructor(_){this.onUpdate=_}seed(_){this.fullText=_,this.displayedLength=_.length,this.releases=[],this.onUpdate(_,[])}update(_,$){if(this.fullText=_,this.isDone=$,this.displayedLength=Math.min(this.displayedLength,this.fullText.length),this.releases=this.releases.filter((X)=>X.from<this.displayedLength),$&&this.displayedLength>=this.fullText.length){this.onUpdate(this.fullText,[]),this.stopAnimation();return}if(!this.animationFrameId)this.scheduleFrame()}destroy(){this.stopAnimation()}scheduleFrame(){this.animationFrameId=requestAnimationFrame((_)=>this.tick(_))}tick(_){let $=this.fullText.length-this.displayedLength;if($<=0){this.animationFrameId=null;return}let X=this.isDone?o.DONE_DRAIN_FRACTION:o.DRAIN_FRACTION,Y=Math.max(o.MIN_CHARS_PER_FRAME,Math.ceil($*X));if(this.releases=this.releases.filter((Q)=>_-Q.at<o.FADE_WINDOW_MS),this.releases.push({from:this.displayedLength,at:_}),this.displayedLength=Math.min(this.fullText.length,this.displayedLength+Y),this.onUpdate(this.fullText.substring(0,this.displayedLength),this.releases.map((Q)=>({length:this.displayedLength-Q.from,age:_-Q.at}))),this.displayedLength<this.fullText.length)this.scheduleFrame();else this.animationFrameId=null}stopAnimation(){if(this.animationFrameId)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}}var b5=2;function o1(_){let $=!1,X=!1,Y=!1,Q=!1,N=!1,Z=!1,G,J=new Set,z=0,V=!1;function W(){if($&&z===0)return!1;if(z+=1,!$)$=!0,_.setRunning(!0);return!0}function q(H){if(z-=1,H)V=!0;else if(z===0&&!V)$=!1,_.setRunning(!1)}async function L(H,D){for(let K=0;K<b5;K+=1){let O=await _.refreshMessages().catch(()=>{return});if(!_.isAlive())return!1;if(!O)continue;if(!r(O).some((T)=>T.id===H.id))return!0;if(await _.deliver(D).then(()=>!0,()=>!1))return!0}return!1}async function U(H,D){let K;try{let Q_=D({toolCallId:H.id,toolName:H.name,input:H.input},{threadId:_.threadId});if(Q_===null||Q_===void 0)return;K=await Promise.resolve(Q_)}catch{J.delete(H.id);return}if(K===null||K===void 0)return;if(!_.isAlive())return;let O=W(),C={toolCallId:H.id,tool:H.name,output:K},T=await _.deliver(C).then(()=>!0,()=>L(H,C));if(O)q(T);if(!T)J.delete(H.id)}function k(H){let D=r(H),K=_.onToolCall();if(!K)return D.length>0;for(let O of D){if(O.state!=="input-complete"||J.has(O.id))continue;J.add(O.id),U(O,K)}return D.length>0}async function M(H){let D=Q;if(Q=!1,!D&&$){if(k(H()))return;if(Y)_.reloadThreads().catch(()=>{});else _.setRunning(!1)}if(G===void 0&&(Z||D))return;G=void 0;let K=await _.refreshMessages();if(!D&&$&&K)k(K)}return{chunkArrived(){X=!0},transcriptCarried(H){if(Z=!0,G!==void 0&&G<=H)G=void 0},transcriptUpdated(H){if(!N){_.refreshMessages();return}G=Math.max(G??0,Date.parse(H))},streamFailed(){if(Y=!0,X)_.onTurnFinished();else _.onSendFailed()},loadingChanged(H,D){if(H){N=!0,Y=!1,Z=!1;return}if(!N)return;N=!1,_.onTurnFinished(),M(D)},hydrated(H,D){if(D)return;setTimeout(()=>{if(_.isAlive())k(H)},0)},sendStarted(){_.setRunning(!0),$=!0,X=!1},abortConfirmed(){Q=!0,_.setRunning(!1)}}}function A_(_){if(_.input.total<=0)return null;return Math.round(_.input.cacheRead/_.input.total*100)}import{createContext as u0,useContext as l0}from"react";var a1=u0(void 0);function B(){let _=l0(a1);if(!_)throw Error("useCortex must be used inside <CortexChatWidget>");return _}var g_={messages:[],isAgentWorking:!1,isLoadingMessages:!1,hasPendingToolCalls:!1},m_=u0(g_);function x_(){return l0(m_)}import{useEffect as C5,useState as S5}from"react";function p0(_,$){let[X,Y]=S5();return C5(()=>{return Y(void 0),I1(_,Y)},[_,$]),X}import{useRef as c5}from"react";import{useRef as v5,useState as T5,useSyncExternalStore as f5}from"react";function d0(_,$){let X=v5($);X.current=$;let[Y]=T5(()=>B1({api:_,ensureThread:()=>X.current()})),Q=f5(Y.subscribe,Y.getState,Y.getState);return{store:Y,value:{items:Q,...F1(Q),accept:Y.accept,remove:Y.remove,consumeReady:Y.consumeReady}}}import{useEffect as j5,useRef as g5}from"react";function n0(_,$){let X=g5(void 0);j5(()=>{if($===X.current)return;_.clear(X.current),X.current=$},[$,_])}import{useRef as i0}from"react";function r0(_){let $=i0([]),X=i0(void 0);function Y(){let N=_.selectedRef.current;if(N)return Promise.resolve(N.id);return X.current??=_.api.createThread().then((Z)=>{return X.current=void 0,_.onCreated(Z),Z.id},(Z)=>{throw X.current=void 0,Z}),X.current}async function Q(N,Z=[]){let G=_.sessionRef.current;if(G){await G.send(N,Z);return}$.current.push({prompt:N,attachments:Z});try{await Y()}catch(J){throw $.current=[],J}}return{ensureThread:Y,send:Q,pendingSendRef:$}}import{useRef as m5,useState as x5}from"react";function o0(_){let[$,X]=x5(),Y=$?.thread,Q=Y?_.threads?.find((z)=>z.id===Y.id)??Y:void 0,N=m5(Q);N.current=Q;function Z(z,V){if(N.current?.id===z.id&&_.hasSession())return;let W=N.current;if(N.current=z,X({thread:z,mode:V,epoch:0}),W&&W.id!==z.id)_.getHooks()?.onThreadDeselected?.(W);_.getHooks()?.onThreadSelected?.(z)}function G(){let z=N.current;if(!z&&!_.hasSession())return;if(N.current=void 0,X(void 0),z)_.getHooks()?.onThreadDeselected?.(z)}function J(z,V){X((W)=>({thread:z,mode:"reload",epoch:(W?.epoch??0)+1,initialMessages:V}))}return{session:$,selected:Q,selectedRef:N,select:Z,deselect:G,remount:J}}function a0(_){let{api:$,threads:X}=_,Y=c5(void 0),Q=o0({threads:X.threads,getHooks:_.getHooks,hasSession:()=>Y.current!==void 0}),N=r0({api:$,sessionRef:Y,selectedRef:Q.selectedRef,onCreated:(z)=>{X.upsert(z),Q.select(z,"skip")}}),Z=d0($,N.ensureThread);n0(Z.store,Q.selected?.id);async function G(z){if(Q.selectedRef.current?.id===z)Q.deselect();await X.remove(z)}function J(z){Q.select(z,"load")}return{sessionRef:Y,selection:Q,queue:Z,deleteThread:G,openThread:J,...N}}import{useEffect as h5,useRef as u5}from"react";function t0(_){let $=u5(_);$.current=_,h5(()=>{$.current.onMount();let X=!1,Y=w1({getConfig:()=>$.current.getConfig(),onEvent:(Q)=>$.current.onEvent(Q),onOpen:()=>{if(X)$.current.onReconnect();X=!0}});return()=>Y.close()},[])}function s0(_){let{threads:$,selectedRef:X,sessionRef:Y}=_;function Q(Z){$.applyEvent(Z);let G=X.current?.id;switch(Z.type){case"thread:deleted":if(G===Z.payload.threadId)_.deselect();break;case"thread:run-started":if(G===Z.payload.thread.id)Y.current?.reattach(Z.payload.thread);break;case"thread:messages-updated":Y.current?.transcriptUpdated(Z.payload.thread.id,Z.payload.thread.updatedAt);break}}function N(){_.onReconnect(),$.reload().then((Z)=>{let G=X.current;if(!G)return;Y.current?.reattach(Z.find((J)=>J.id===G.id)??G)})}return{onEvent:Q,onReconnect:N}}function e0(_){return{abort:async()=>{await _.current?.abort()},addToolResult:($,X,Y)=>_.current?.addToolResult($,X,Y)??Promise.resolve(),respondToApproval:($,X)=>_.current?.respondToApproval($,X)??Promise.resolve()}}import{useState as l5}from"react";function _6(_){let[$,X]=l5();async function Y(){let J=T_(await _.listThreads());return X(J),J}function Q(J){X((z)=>k_(z??[],J))}function N(J,z){X((V)=>{let W=V?.find((q)=>q.id===J);return W?k_(V??[],{...W,isRunning:z}):V})}async function Z(J){await _.deleteThread(J),X((z)=>z?f_(z,J):z)}function G(J){X((z)=>{let V=b1(z??[],J);return z||V.length?V:z})}return{threads:$,reload:Y,upsert:Q,setRunning:N,remove:Z,applyEvent:G}}import{useState as $6}from"react";function X6(){let[_,$]=$6("chat"),[X,Y]=$6(!1);return{screen:_,sidebarOpen:X,showChat:()=>{$("chat"),Y(!1)},openHistory:()=>$("threads"),closeHistory:()=>$("chat"),toggleSidebar:()=>Y((Q)=>!Q),closeSidebar:()=>Y(!1)}}function F(..._){return _.filter(Boolean).join(" ")}import{jsx as l,jsxs as Y6}from"react/jsx-runtime";function Q6({onToggleSidebar:_,onToggleDebug:$,onOpenHistory:X}){let{config:Y,locale:Q,t:N,debugMode:Z,selectedThread:G}=B();return Y6("div",{className:"cortex-widget__chat-header",children:[l("button",{onClick:_,className:"cortex-widget__sidebar-toggle-btn",children:l("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l("path",{d:"M2.5 4h11M2.5 8h11M2.5 12h11",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}),l("div",{className:"cortex-widget__chat-title-wrap",children:l("p",{className:"cortex-widget__chat-title",children:G?.title??Z_(Y.agentName,Q)??N("translate_new_chat")})}),Y.showDebugButton&&l("button",{onClick:$,className:F("cortex-widget__debug-btn",Z?"cortex-widget__debug-btn--on":"cortex-widget__debug-btn--off"),children:Z?N("translate_debug"):N("translate_normal")}),l("button",{type:"button",onClick:X,"aria-label":N("translate_history"),className:"cortex-widget__history-btn",children:Y6("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[l("circle",{cx:"8",cy:"8",r:"5.75",stroke:"currentColor",strokeWidth:"1.3"}),l("path",{d:"M8 5v3l2 1.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})}var I={bubble:"M13.5 7.6c0 2.4-2.5 4.4-5.5 4.4-.6 0-1.2-.08-1.7-.23L3 13l.8-2.3C3 9.8 2.5 8.7 2.5 7.6 2.5 5.2 5 3.2 8 3.2s5.5 2 5.5 4.4Z",chevronDown:"M3 4.5L6 7.5L9 4.5",chevronDownLarge:"m5.75 8.25 4.25 4.25 4.25-4.25",file:["M4 1.5h5.172a2 2 0 0 1 1.414.586l2.328 2.328a2 2 0 0 1 .586 1.414V12.5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2Z","M9.5 1.5v2a2 2 0 0 0 2 2h2"]};import{forwardRef as a5,useEffect as t5,useImperativeHandle as s5,useRef as V6,useState as e5}from"react";import{useState as p5}from"react";function N6(_,$){let[X,Y]=p5(!1);return{dragging:X,onDragOver:(Q)=>{if(Q.preventDefault(),_)Y(!0)},onDragLeave:(Q)=>{if(!Q.currentTarget.contains(Q.relatedTarget))Y(!1)},onDrop:(Q)=>{if(Q.preventDefault(),Y(!1),_)$([...Q.dataTransfer.files])},onPaste:(Q)=>{let N=Q.clipboardData.files;if(!_||!N.length)return;Q.preventDefault(),$([...N])}}}import{jsx as p,jsxs as t1}from"react/jsx-runtime";function Z6(){let{queue:_,t:$}=B();if(!_.items.length)return null;return p("div",{className:"cortex-attachment-queue",children:_.items.map((X)=>t1("div",{className:F("cortex-attachment-chip",X.status==="error"&&"cortex-attachment-chip--error"),title:X.status==="error"?$("translate_attachment_rejected"):"",children:[X.status==="uploading"||X.status==="deleting"?t1("svg",{className:"cortex-attachment-chip__spinner",viewBox:"0 0 16 16",fill:"none",children:[p("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",className:"cortex-attachment-chip__spinner-track"}),p("path",{d:"M14 8a6 6 0 0 0-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):t1("svg",{viewBox:"0 0 16 16",className:"cortex-attachment-chip__icon",fill:"none",children:[p("path",{d:I.file[0],stroke:"currentColor",strokeWidth:"1.25"}),p("path",{d:I.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),p("span",{className:"cortex-attachment-chip__name",children:X.filename}),p("button",{type:"button",onClick:()=>_.remove(X.localId),className:"cortex-attachment-chip__remove",disabled:X.status==="deleting","aria-label":$("translate_remove_attachment"),children:p("svg",{viewBox:"0 0 16 16",fill:"none",children:p("path",{d:"M4.5 4.5l7 7m0-7l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]},X.localId))})}import{useRef as d5}from"react";import{jsx as __,jsxs as G6,Fragment as i5}from"react/jsx-runtime";var n5=_1.join(",");function J6({attachmentsEnabled:_,canSend:$,onSend:X}){let{t:Y,queue:Q}=B(),N=d5(null);return G6("div",{className:"cortex-widget__input-actions",children:[_&&G6(i5,{children:[__("button",{type:"button",onClick:()=>N.current?.click(),className:"cortex-widget__attach-btn","aria-label":Y("translate_attach_files"),children:__("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:__("path",{d:"M10.5 5.5 6.2 9.8a1.4 1.4 0 0 0 2 2l4.6-4.6a2.8 2.8 0 0 0-4-4L4.2 7.8a4.2 4.2 0 0 0 6 6l4-4",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),__("input",{ref:N,type:"file",multiple:!0,accept:n5,onChange:(Z)=>{Q.accept([...Z.target.files??[]]),Z.target.value=""},className:"cortex-widget__file-input"})]}),__("button",{onClick:X,"aria-label":Y("translate_send"),className:F("cortex-widget__send-btn",!$&&"cortex-widget__send-btn--empty",$&&"cortex-widget__send-btn--ready"),disabled:!$,children:__("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__send-icon",children:__("path",{d:"M3 8h10M9 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}import{useLayoutEffect as r5}from"react";import{jsx as o5}from"react/jsx-runtime";function z6(_){let{t:$}=B();r5(()=>{let Y=_.inputRef.current;if(!Y)return;Y.style.height="0px",Y.style.height=`${Y.scrollHeight}px`},[_.inputRef,_.value]);function X(Y){if(Y.key==="Enter"&&!Y.shiftKey)Y.preventDefault(),_.onSubmit()}return o5("textarea",{ref:_.inputRef,onKeyDown:X,onPaste:_.onPaste,value:_.value,onChange:(Y)=>_.onChange(Y.target.value),placeholder:_.dragging?$("translate_drop_files_here"):_.disabled?"":$("translate_type_a_message"),disabled:_.disabled,rows:1,className:F("cortex-widget__textarea",_.disabled&&"cortex-widget__textarea--disabled")})}import{jsx as G_,jsxs as s1}from"react/jsx-runtime";var K6=a5(function($,X){let{t:Y,queue:Q,send:N,abort:Z,capabilities:G}=B(),{isAgentWorking:J}=x_(),z=G?.attachments??!1,[V,W]=e5(""),q=N6(z,Q.accept),L=V6(null);s5(X,()=>({focusInput:()=>L.current?.focus()}));let U=V6(J);t5(()=>{if(U.current&&!J)L.current?.focus();U.current=J},[J]);let k=!Q.busy&&(Boolean(V.trim())||Q.hasReady);function M(){if(J||!k)return;let H=V.trim()||Y("translate_attachment_caption"),D=Q.consumeReady();W(""),N(H,D.map((K)=>K.summary))}return s1("div",{className:"cortex-widget__input-area",onDragOver:q.onDragOver,onDragLeave:q.onDragLeave,onDrop:q.onDrop,children:[G_(Z6,{}),s1("div",{className:F("cortex-widget__input-box",J&&"cortex-widget__input-box--disabled",!J&&"cortex-widget__input-box--enabled",q.dragging&&"cortex-widget__input-box--dragging"),children:[G_(z6,{inputRef:L,value:V,onChange:W,onSubmit:M,onPaste:q.onPaste,disabled:J,dragging:q.dragging}),J?s1("button",{onClick:()=>void Z(),className:"cortex-stop-btn",children:[G_("span",{className:"cortex-stop-btn__ring"}),G_("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"cortex-stop-btn__icon",children:G_("rect",{x:"1",y:"1",width:"10",height:"10",rx:"2.5",fill:"currentColor"})})]}):G_(J6,{attachmentsEnabled:z,canSend:k,onSend:M})]})]})});import{jsx as W6}from"react/jsx-runtime";function c_({capabilities:_,composerRef:$}){let{t:X}=B();if(_===void 0)return null;return _.messages===!1?W6("p",{className:"cortex-widget__messages-disabled",children:X("translate_messages_disabled")}):W6(K6,{ref:$})}import{jsx as h,jsxs as D6}from"react/jsx-runtime";function H6(_){let{locale:$,t:X,threads:Y,send:Q,capabilities:N}=B(),Z=N?.messages===!1,G=N!==void 0,J=Z_(N?.suggestions,$),z=Z_(N?.greeting,$)||X("translate_greeting");return D6("div",{className:"cortex-widget__landing",children:[h("div",{className:"cortex-widget__landing-icon",children:h("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",children:h("path",{d:I.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),h("p",{className:"cortex-widget__landing-greeting",children:z}),G&&!Z&&!!J?.length&&h("div",{className:"cortex-widget__landing-chips",children:J.map((V,W)=>h("button",{type:"button",onClick:()=>void Q(V.prompt),className:"cortex-widget__landing-chip",children:V.title},W))}),h(c_,{capabilities:N}),!!Y?.length&&h("div",{className:"cortex-widget__landing-recent",children:Y.slice(0,2).map((V)=>{let W=u(V.updatedAt,$);return D6("button",{type:"button",onClick:()=>_.onThreadSelected(V),className:"cortex-widget__landing-recent-item",children:[h("p",{className:"cortex-widget__landing-recent-title",children:V.title??X("translate_untitled")}),W&&h("p",{className:"cortex-widget__landing-recent-time",children:W})]},V.id)})})]})}import{useCallback as r_,useEffect as o_,useMemo as S8,useRef as C_,useState as N0}from"react";import{jsx as h_,jsxs as B6}from"react/jsx-runtime";function F6(){let{t:_}=B();return B6("div",{className:"cortex-widget__working",children:[B6("div",{className:"cortex-widget__working-dots",children:[h_("span",{className:"cortex-working-dot"}),h_("span",{className:"cortex-working-dot"}),h_("span",{className:"cortex-working-dot"})]}),h_("span",{className:"cortex-widget__working-text",children:_("translate_thinking")})]})}import{memo as b8}from"react";import{Fragment as y8}from"react";import{useRef as _8,useState as $8}from"react";import{jsx as J_,jsxs as X8}from"react/jsx-runtime";function j({value:_,className:$}){let{t:X}=B(),[Y,Q]=$8(!1),N=_8(null);async function Z(G){G.stopPropagation(),G.preventDefault();try{if(await navigator.clipboard.writeText(_),Q(!0),N.current)clearTimeout(N.current);N.current=setTimeout(()=>Q(!1),1500)}catch{}}return J_("span",{className:F("cortex-copy-btn",$),children:J_("button",{className:F("cortex-copy-btn__button",Y&&"cortex-copy-btn__button--copied"),onClick:(G)=>void Z(G),"aria-label":Y?X("translate_copied"):X("translate_copy"),type:"button",children:Y?J_("svg",{className:"cortex-copy-btn__icon cortex-copy-btn__icon--check",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:J_("path",{d:"M5 13l4 4L19 7",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):X8("svg",{className:"cortex-copy-btn__icon",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:[J_("rect",{x:"9",y:"9",width:"12",height:"12",rx:"2",stroke:"currentColor",strokeWidth:"2"}),J_("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})})})}import{jsx as u_,jsxs as U6}from"react/jsx-runtime";function q6(){let{t:_}=B();return U6("div",{className:"cortex-aborted-flag",children:[u_("span",{className:"cortex-aborted-flag__line"}),U6("span",{className:"cortex-aborted-flag__label",children:[u_("svg",{className:"cortex-aborted-flag__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:u_("path",{d:"M6 1.5v5M6 8.75v.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})}),_("translate_aborted")]}),u_("span",{className:"cortex-aborted-flag__line"})]})}import{jsx as z_,jsxs as L6}from"react/jsx-runtime";function k6(_){let{api:$,t:X}=B();async function Y(Q){let{blob:N,name:Z}=await $.downloadAttachment(Q);r1(N,Z)}return z_("div",{className:F("cortex-message-attachments",_.isUser&&"cortex-message-attachments--user"),children:_.attachments.map((Q)=>L6("button",{type:"button",onClick:()=>void Y(Q.id),className:"cortex-message-attachment","aria-label":`${X("translate_download")}: ${Q.filename}`,children:[L6("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__icon",fill:"none",children:[z_("path",{d:I.file[0],stroke:"currentColor",strokeWidth:"1.25"}),z_("path",{d:I.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),z_("span",{className:"cortex-message-attachment__name",children:Q.filename}),z_("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__dl-icon",fill:"none",children:z_("path",{d:"M8 3v7m0 0L5.5 7.5M8 10l2.5-2.5M3 13h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},Q.id))})}import{useRef as N8,useState as E_}from"react";import{useMemo as Y8,useState as Q8}from"react";import{jsx as f,jsxs as $_,Fragment as l_}from"react/jsx-runtime";function a({data:_,expandDepth:$,className:X}){let Y=Y8(()=>N_(_),[_]),[Q,N]=Q8({});function Z(J,z){return Q[J]??z>=$}function G(J,z){N((V)=>({...V,[J]:!Z(J,z)}))}return f("div",{className:F("cortex-json-tree",X),children:f(M6,{value:Y,path:"$",depth:0,isCollapsed:Z,toggle:G})})}function M6({value:_,path:$,depth:X,isCollapsed:Y,toggle:Q}){let N=d1(_,$);if(N.kind==="primitive")return f("span",{className:N.className,children:N.text});if(N.entries.length===0)return $_("span",{className:"cortex-json-tree__bracket",children:[N.open,N.close]});let Z=Y($,X);function G(J){Q($,X),J.stopPropagation()}return $_(l_,{children:[$_("span",{className:"cortex-json-tree__toggle",onClick:G,role:"button",children:[f("span",{className:F("cortex-json-tree__arrow",Z&&"cortex-json-tree__arrow--collapsed"),children:"▾"}),f("span",{className:"cortex-json-tree__bracket",children:N.open})]}),Z?$_(l_,{children:[f("span",{className:"cortex-json-tree__collapsed-hint",onClick:G,role:"button",children:N.summary}),f("span",{className:"cortex-json-tree__bracket",children:N.close})]}):$_(l_,{children:[f("div",{className:"cortex-json-tree__indent",children:N.entries.map((J,z)=>$_("div",{className:"cortex-json-tree__line",children:[J.key!==null&&$_(l_,{children:[f("span",{className:"cortex-json-tree__key",children:`"${J.key}"`}),f("span",{className:"cortex-json-tree__colon",children:": "})]}),f(M6,{value:J.value,path:J.path,depth:X+1,isCollapsed:Y,toggle:Q}),z<N.entries.length-1&&f("span",{className:"cortex-json-tree__comma",children:","})]},J.path))}),f("span",{className:"cortex-json-tree__bracket",children:N.close})]})]})}function E(_){return _.toLocaleString("en-US")}import{jsx as V_,jsxs as K_}from"react/jsx-runtime";function O6({usage:_}){let{t:$}=B();return K_("div",{className:"cortex-llm-inspector__usage-rows",children:[K_("div",{className:"cortex-llm-inspector__usage-row",children:[V_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_input")}),V_("span",{className:"cortex-llm-inspector__usage-val",children:E(_.input.total)}),K_("span",{className:"cortex-llm-inspector__usage-detail",children:[$("translate_fresh")," ",E(_.input.noCache)," · ",$("translate_read")," ",E(_.input.cacheRead)," · ",$("translate_write")," ",E(_.input.cacheWrite)]})]}),K_("div",{className:"cortex-llm-inspector__usage-row",children:[V_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_output")}),V_("span",{className:"cortex-llm-inspector__usage-val",children:E(_.output.total)}),K_("span",{className:"cortex-llm-inspector__usage-detail",children:[$("translate_text")," ",E(_.output.text)," · ",$("translate_reasoning")," ",E(_.output.reasoning)]})]}),K_("div",{className:"cortex-llm-inspector__usage-row cortex-llm-inspector__usage-row--total",children:[V_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_total")}),V_("span",{className:"cortex-llm-inspector__usage-val",children:E(_.total)})]})]})}import{jsx as P6,jsxs as p_}from"react/jsx-runtime";function A6({usage:_}){let $=A_(_);return p_("span",{className:"cortex-llm-inspector__step-metrics",children:[p_("span",{className:"cortex-llm-inspector__metric",children:[P6("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--input"}),E(_.input.total)]}),p_("span",{className:"cortex-llm-inspector__metric",children:[P6("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--output"}),E(_.output.total)]}),$!==null&&p_("span",{className:"cortex-llm-inspector__cache-pct",children:[$,"%"]})]})}import{jsx as y,jsxs as t}from"react/jsx-runtime";function E6({messageId:_}){let{t:$,api:X}=B(),[Y,Q]=E_(!1),[N,Z]=E_(!1),[G,J]=E_([]),[z,V]=E_(null),[W,q]=E_({}),L=N8(!1);async function U(){if(!L.current){Z(!0);try{J(await X.listLlmRequests(_))}finally{Z(!1),L.current=!0}}Q((K)=>!K)}function k(K){V((O)=>O===K?null:K)}function M(K){return W[K]??"prompt"}function H(K,O){q((C)=>({...C,[K]:O}))}function D(K){return M(K.id)==="prompt"?K.prompt:K.output}return t("div",{className:F("cortex-llm-inspector",Y&&"cortex-llm-inspector--open"),children:[t("button",{className:"cortex-llm-inspector__trigger",onClick:()=>void U(),children:[y("svg",{className:"cortex-llm-inspector__icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:y("path",{d:"M6 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8ZM0 6a6 6 0 1 1 10.89 3.477l4.817 4.816a1 1 0 0 1-1.414 1.414l-4.816-4.816A6 6 0 0 1 0 6Z",fill:"currentColor"})}),y("span",{children:$("translate_inspect_llm_requests")}),N?y("span",{className:"cortex-llm-inspector__loading",children:$("translate_loading")}):G.length>0?y("span",{className:"cortex-llm-inspector__badge",children:G.length}):null,y("svg",{className:"cortex-llm-inspector__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:y("path",{d:I.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),y("div",{className:"cortex-llm-inspector__panel-wrapper",children:y("div",{className:"cortex-llm-inspector__panel-inner",children:t("div",{className:"cortex-llm-inspector__panel",children:[G.length===0&&!N&&y("div",{className:"cortex-llm-inspector__empty",children:$("translate_no_llm_requests")}),G.map((K,O)=>t("div",{className:F("cortex-llm-inspector__step",z===K.id&&"cortex-llm-inspector__step--expanded"),children:[t("button",{className:"cortex-llm-inspector__step-header",onClick:()=>k(K.id),children:[y("span",{className:"cortex-llm-inspector__step-label",children:$("translate_step_n",{number:O+1})}),K.tokenUsage&&y(A6,{usage:K.tokenUsage}),y("svg",{className:"cortex-llm-inspector__step-chevron",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:y("path",{d:I.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),y("div",{className:"cortex-llm-inspector__step-body-wrapper",children:y("div",{className:"cortex-llm-inspector__step-body-inner",children:t("div",{className:"cortex-llm-inspector__step-body",children:[K.tokenUsage&&y(O6,{usage:K.tokenUsage}),t("div",{className:"cortex-llm-inspector__tabs",children:[y("button",{className:F("cortex-llm-inspector__tab",M(K.id)==="prompt"&&"cortex-llm-inspector__tab--active"),onClick:()=>H(K.id,"prompt"),children:$("translate_request")}),y("button",{className:F("cortex-llm-inspector__tab",M(K.id)==="response"&&"cortex-llm-inspector__tab--active"),onClick:()=>H(K.id,"response"),children:$("translate_response")})]}),t("div",{className:"cortex-llm-inspector__json-pane",children:[y(j,{className:"cortex-llm-inspector__json-copy",value:i1(D(K))}),y(a,{data:n1(D(K)),expandDepth:2})]})]})})})]},K.id))]})})})]})}import{useState as Z8}from"react";import{jsx as P,jsxs as b}from"react/jsx-runtime";function R6({usage:_,modelId:$}){let{t:X}=B(),[Y,Q]=Z8(!1),N=A_(_)??0;return b("div",{className:F("cortex-token-usage",Y&&"cortex-token-usage--expanded"),children:[b("button",{className:"cortex-token-usage__summary",onClick:()=>Q((Z)=>!Z),children:[b("span",{className:"cortex-token-usage__total",children:[P("span",{className:"cortex-token-usage__total-number",children:E(_.total)}),P("span",{className:"cortex-token-usage__total-label",children:X("translate_tokens")})]}),$?P("span",{className:"cortex-token-usage__model",children:$}):null,b("span",{className:"cortex-token-usage__pills",children:[b("span",{className:"cortex-token-usage__pill",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),E(_.input.total)]}),b("span",{className:"cortex-token-usage__pill",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),E(_.output.total)]})]}),N>0&&b("span",{className:"cortex-token-usage__cache-badge",children:[N,"%"]}),P("svg",{className:"cortex-token-usage__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:P("path",{d:I.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),P("div",{className:"cortex-token-usage__details",children:P("div",{className:"cortex-token-usage__details-inner",children:b("div",{className:"cortex-token-usage__columns",children:[b("div",{className:"cortex-token-usage__col",children:[b("div",{className:"cortex-token-usage__col-header",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),P("span",{className:"cortex-token-usage__col-label",children:X("translate_input")}),P("span",{className:"cortex-token-usage__col-total",children:E(_.input.total)})]}),b("div",{className:"cortex-token-usage__rows",children:[_.input.noCache?b("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:X("translate_fresh")}),P("span",{className:"cortex-token-usage__row-value",children:E(_.input.noCache)})]}):null,_.input.cacheRead?b("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:X("translate_cache_read")}),P("span",{className:"cortex-token-usage__row-value",children:E(_.input.cacheRead)})]}):null,_.input.cacheWrite?b("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:X("translate_cache_write")}),P("span",{className:"cortex-token-usage__row-value",children:E(_.input.cacheWrite)})]}):null]}),N>0&&b("div",{className:"cortex-token-usage__cache-bar-row",children:[P("div",{className:"cortex-token-usage__cache-bar",children:P("div",{className:"cortex-token-usage__cache-fill",style:{width:`${N}%`}})}),P("span",{className:"cortex-token-usage__cache-label",children:X("translate_n_percent_cached",{percent:N})})]})]}),b("div",{className:"cortex-token-usage__col",children:[b("div",{className:"cortex-token-usage__col-header",children:[P("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),P("span",{className:"cortex-token-usage__col-label",children:X("translate_output")}),P("span",{className:"cortex-token-usage__col-total",children:E(_.output.total)})]}),b("div",{className:"cortex-token-usage__rows",children:[_.output.text?b("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:X("translate_text")}),P("span",{className:"cortex-token-usage__row-value",children:E(_.output.text)})]}):null,_.output.reasoning?b("div",{className:"cortex-token-usage__row",children:[P("span",{className:"cortex-token-usage__row-label",children:X("translate_reasoning")}),P("span",{className:"cortex-token-usage__row-value",children:E(_.output.reasoning)})]}):null]})]})]})})})]})}import{jsx as y6,jsxs as G8}from"react/jsx-runtime";function w6({messageId:_,isAssistant:$,metadata:X}){let{tokenUsage:Y}=X;if(!Y&&!$)return null;return G8("div",{className:"cortex-message-debug-zone",children:[Y&&y6(R6,{usage:Y,modelId:X.modelId}),$&&y6(E6,{messageId:_})]})}import{jsx as g,jsxs as R_}from"react/jsx-runtime";function I6(_){let{reasoningPart:$,streaming:X=!1}=_,{t:Y}=B();return R_("details",{className:"cortex-reasoning-details",children:[R_("summary",{className:"cortex-reasoning-details__summary",children:[R_("div",{className:"cortex-reasoning-details__header",children:[g("span",{className:"cortex-reasoning-details__icon",children:R_("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:[g("path",{d:"M10 2C6.686 2 4 4.686 4 8c0 1.655.672 3.154 1.757 4.243.362.363.576.858.576 1.371V14.5a1 1 0 0 0 1 1h5.334a1 1 0 0 0 1-1v-.886c0-.513.214-1.008.576-1.371A5.978 5.978 0 0 0 16 8c0-3.314-2.686-6-6-6Z",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),g("path",{d:"M7.5 17.5h5M8.5 8a2 2 0 0 1 2-2",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})]})}),g("div",{className:"cortex-reasoning-details__title-group",children:R_("div",{className:"cortex-reasoning-details__title-row",children:[g("div",{className:"cortex-reasoning-details__title",children:Y("translate_reasoning")}),g("span",{className:F("cortex-reasoning-details__badge",X?"cortex-reasoning-details__badge--streaming":"cortex-reasoning-details__badge--done"),children:X?Y("translate_streaming"):Y("translate_done")})]})})]}),g("span",{className:"cortex-reasoning-details__chevron","aria-hidden":"true",children:g("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:g("path",{d:I.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),g("div",{className:"cortex-reasoning-details__body",children:g("div",{className:"cortex-reasoning-details__content",children:g("pre",{className:"cortex-reasoning-details__pre",children:$.content.trim()?$.content:Y("translate_no_reasoning")})})})]})}import{useEffect as T6,useMemo as H8,useRef as _0,useState as B8}from"react";import{useEffect as J8,useState as b6}from"react";import{jsx as e1,jsxs as z8}from"react/jsx-runtime";function C6(_){let{id:$,alt:X,attachment:Y}=_,{api:Q,t:N}=B(),[Z,G]=b6(),[J,z]=b6(!1);if(J8(()=>{let V,W=!1;return G(void 0),z(!1),Q.downloadAttachment($).then(({blob:q})=>{if(W)return;V=URL.createObjectURL(q),G(V)},()=>{if(!W)z(!0)}),()=>{if(W=!0,V)URL.revokeObjectURL(V)}},[Q,$]),J)return e1("p",{className:"cortex-attachment-image__caption",children:X?N("translate_image_unavailable_alt",{alt:X}):N("translate_image_unavailable")});if(!Z)return null;return z8("figure",{className:"cortex-attachment-image",children:[e1("img",{src:Z,alt:X}),Y&&e1("figcaption",{className:"cortex-attachment-image__caption",children:Y.filename})]})}import{useEffect as V8,useRef as K8,useState as S6}from"react";import{jsx as d,jsxs as d_}from"react/jsx-runtime";function W8(_){let{t:$}=B();if(!_.pending&&!_.debugMode)return null;return d_("div",{className:"cortex-media-block__head",children:[_.debugMode&&d("span",{className:"cortex-media-block__lang",children:_.language}),_.pending&&d("span",{className:"cortex-media-block__pending",children:$(m1(_.language))}),_.debugMode&&_.closed&&d_("span",{className:"cortex-media-block__actions",children:[_.onToggleSource&&d("button",{type:"button",className:"cortex-media-block__action","aria-pressed":_.sourceShown,onClick:_.onToggleSource,children:$("translate_media_source")}),d(j,{value:_.source})]})]})}function D8(_){let{debugMode:$,t:X}=B();return d("div",{className:"cortex-media-block__body",children:d_("p",{className:"cortex-media-block__error",children:[_.cutOff?X("translate_media_cut_off"):X("translate_media_failed"),!_.cutOff&&$&&` ${_.reason}`]})})}function v6(_){let{language:$,source:X,closed:Y,streaming:Q}=_,{config:N,debugMode:Z,scheme:G}=B(),J=K8(null),[z,V]=S6(),[W,q]=S6(!1);V8(()=>{V(void 0);let M=J.current;if(!Y||!G||!M)return;return c1(M,{language:$,source:X,context:{scheme:G},overrides:N.mediaRenderers,onError:V})},[$,X,Y,G,N.mediaRenderers]);let L=!Y&&!Q,U=L||Boolean(z);return d_("div",{className:"cortex-media-block",children:[d(W8,{language:$,source:X,pending:!Y&&Q,closed:Y,debugMode:Z,sourceShown:W,onToggleSource:U?void 0:()=>q((M)=>!M)}),U&&d(D8,{cutOff:L,reason:z}),d("div",{ref:J,hidden:U,className:F("cortex-media-block__body",`cortex-media-block__body--${$}`)}),Z&&(U||W)&&d("pre",{className:"cortex-media-block__source",children:X})]})}import{jsx as y_}from"react/jsx-runtime";function f6(_){let{role:$,textPart:X,streaming:Y=!1,attachments:Q=[]}=_,{config:N}=B(),Z=$==="assistant"&&Y?"":X.content,[G,J]=B8({text:Z,fading:[]}),z=_0(Z),V=_0(null),W=_0(!0);T6(()=>{function U(k,M){z.current=k,J((H)=>H.text===k&&!H.fading.length&&!M.length?H:{text:k,fading:M})}if($!=="assistant"||!Y){V.current?.destroy(),V.current=null,U(X.content,[]),W.current=!1;return}if(!V.current)V.current=new o(U),V.current.seed(z.current);if(W.current){W.current=!1,V.current.seed(X.content);return}V.current.update(X.content,!1)},[$,Y,X]),T6(()=>()=>{V.current?.destroy(),V.current=null},[]);let q=H8(()=>{let U=$==="assistant"?S1(G.text,x1(N.mediaRenderers)):[{kind:"markdown",text:G.text}];return U.map((k,M)=>k.kind==="markdown"?{...k,html:{__html:C1(k.text,M===U.length-1?G.fading:[])}}:k)},[$,G,N.mediaRenderers]),L=Y||G.text!==X.content;return y_("div",{className:F("cortex-text-part",$==="assistant"&&"cortex-text-part--assistant",$==="user"&&"cortex-text-part--user"),children:y_("div",{className:F("cortex-text-bubble",$==="assistant"&&"cortex-text-bubble--assistant",$==="user"&&"cortex-text-bubble--user"),children:q.map((U,k)=>{switch(U.kind){case"markdown":return y_("div",{dangerouslySetInnerHTML:U.html},k);case"media":return y_(v6,{...U,streaming:L},k);case"attachment":return y_(C6,{id:U.id,alt:U.alt,attachment:Q.find((M)=>M.id.toLowerCase()===U.id)},k)}})})})}import{jsx as v,jsxs as s}from"react/jsx-runtime";function j6({toolCallPart:_}){let{t:$}=B(),{state:X,approval:Y}=_,Q=_.output,N=Z1(_);if(X==="complete")return s("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--success",children:[s("div",{className:"cortex-debug-tool__section-bar",children:[v("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--success",children:$("translate_output")}),v("span",{className:"cortex-debug-tool__section-lang",children:"json"}),v(j,{value:N})]}),v("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:v(a,{data:Q,expandDepth:2})})]});if(X==="error")return s("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--error",children:[s("div",{className:"cortex-debug-tool__section-bar",children:[v("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--error",children:$("translate_error")}),v(j,{value:N})]}),v("pre",{dir:"ltr",className:"cortex-debug-tool__error-pre",children:N})]});if(X==="approval-requested")return s("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[s("div",{className:"cortex-debug-tool__section-bar",children:[v("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:$("translate_approval_requested")}),v("span",{className:"cortex-debug-tool__section-lang",children:Y?.id})]}),v("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:$("translate_waiting_for_approval")})]});if(X==="approval-responded")return s("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[s("div",{className:"cortex-debug-tool__section-bar",children:[v("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:$("translate_approval_response")}),v("span",{className:"cortex-debug-tool__section-lang",children:Y?.id})]}),v("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:$(Y?.approved?"translate_tool_approved":"translate_tool_response_received")})]});return null}import{jsx as F8,jsxs as U8}from"react/jsx-runtime";function g6({toolCallPart:_}){let{t:$}=B(),X=N1(_);return U8("span",{className:F("cortex-debug-tool__state",X.modifier&&`cortex-debug-tool__state--${X.modifier}`),children:[X.pulse&&F8("span",{className:F("cortex-debug-tool__pulse",X.pulse==="violet"&&"cortex-debug-tool__pulse--violet")}),$(X.labelKey)]})}import{jsx as S,jsxs as n}from"react/jsx-runtime";function m6({toolCallPart:_}){let{t:$}=B(),{codeSnippets:X,remainingInput:Y,remainingInputText:Q}=G1(_.input);return n("details",{className:"cortex-debug-tool","data-state":_.state,children:[S("summary",{className:"cortex-debug-tool__summary",children:n("div",{className:"cortex-debug-tool__header",children:[n("div",{className:"cortex-debug-tool__meta",children:[S("div",{className:"cortex-debug-tool__title-row",children:S("span",{className:"cortex-debug-tool__name",title:_.name,children:_.name})}),S("div",{className:"cortex-debug-tool__id-row",children:S("span",{className:"cortex-debug-tool__id",children:_.id})})]}),n("div",{className:"cortex-debug-tool__actions",children:[S(g6,{toolCallPart:_}),S("svg",{className:"cortex-debug-tool__chevron",width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:S("path",{d:I.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"cortex-debug-tool__body",children:[X.map((N)=>n("div",{className:"cortex-debug-tool__section",children:[n("div",{className:"cortex-debug-tool__section-bar",children:[S("span",{className:"cortex-debug-tool__section-label",children:N.key}),S("span",{className:"cortex-debug-tool__section-lang",children:N.lang}),S(j,{value:N.value})]}),S("pre",{dir:"ltr",className:"cortex-debug-tool__pre",children:S("code",{className:"hljs",dangerouslySetInnerHTML:{__html:u1(N.value,N.lang)}})})]},N.key)),!!Y&&n("div",{className:"cortex-debug-tool__section",children:[n("div",{className:"cortex-debug-tool__section-bar",children:[S("span",{className:"cortex-debug-tool__section-label",children:$("translate_input")}),S("span",{className:"cortex-debug-tool__section-lang",children:"json"}),S(j,{value:Q})]}),S("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:S(a,{data:Y,expandDepth:2})})]}),S(j6,{toolCallPart:_})]})]})}import{useEffect as q8,useRef as L8,useState as x6}from"react";import{jsx as w_,jsxs as c6}from"react/jsx-runtime";function I_({activity:_,className:$}){let{t:X}=B(),Y=z1(_),[Q,N]=x6(0),[Z,G]=x6("idle"),J=L8(Y.length);return J.current=Y.length,q8(()=>{let z,V;function W(){z=setTimeout(()=>{G("exiting"),z=setTimeout(()=>{N((q)=>(q+1)%J.current),G("enter-start"),V=requestAnimationFrame(()=>{G("entering"),z=setTimeout(()=>{G("idle"),W()},300)})},300)},2000)}return W(),()=>{if(z)clearTimeout(z);if(V)cancelAnimationFrame(V)}},[]),c6("div",{className:F("cortex-subtle-activity",$),children:[c6("div",{className:"cortex-subtle-activity__dots",children:[w_("span",{className:"cortex-subtle-activity__dot"}),w_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d1"}),w_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d2"})]}),w_("div",{className:"cortex-subtle-activity__label-mask",children:w_("span",{className:F("cortex-subtle-activity__label",`cortex-subtle-activity__label--${Z}`),children:X(Y[Q])})})]})}import{useEffect as d6,useRef as $0,useState as p6}from"react";import{useEffect as h6,useRef as n_,useState as u6}from"react";import{jsx as w,jsxs as x}from"react/jsx-runtime";function l6({toolCallPart:_,setOutput:$}){let{t:X}=B(),{state:Y,id:Q,input:N}=_;if(Y==="complete"||Y==="error"){let Z=E1(_.output);return Z?w(M8,{position:Z}):x("div",{className:"cortex-tool-pill",children:[w("span",{className:"cortex-tool-pill__icon",children:w("svg",{className:F("cortex-tool-pill__svg cortex-tool-pill__svg--visible",Y==="error"&&"cortex-tool-pill__svg--error"),viewBox:"0 0 20 20",fill:"none",children:w("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}),w("span",{className:"cortex-tool-pill__title",children:X("translate_location_not_shared")})]})}if(Y!=="input-complete")return null;return w(k8,{center:A1(N),submit:$},Q)}function k8({center:_,submit:$}){let{t:X}=B(),Y=n_(null),Q=n_(void 0),[N,Z]=u6(S_),G=n_({center:_,submit:$});G.current={center:_,submit:$},h6(()=>{let z=Y.current;if(!z)return;let V=O1(z,{center:G.current.center,onState:Z,submit:(W)=>G.current.submit(W)});return Q.current=V,V.start(),()=>{if(V.dispose(),Q.current===V)Q.current=void 0}},[]);let J=R1(N);return x("div",{className:"cortex-location-input",children:[x("div",{className:"cortex-location-input__map",children:[w("div",{className:"cortex-location-input__canvas",ref:Y}),w("button",{type:"button",className:"cortex-location-input__locate","aria-label":X("translate_location_locate"),title:X("translate_location_locate"),disabled:N.locating||N.submitting,onClick:()=>Q.current?.locate(),children:w(O8,{})})]}),x("div",{className:"cortex-location-input__foot",children:[N.position&&!N.deliveryFailed?w("span",{className:"cortex-location-input__coords",children:v_(N.position)}):x("span",{className:F("cortex-location-input__hint",J.failed&&"cortex-location-input__hint--failed"),children:[N.locating&&w("span",{className:"cortex-location-input__spinner"}),X(J.key)]}),x("span",{className:"cortex-location-input__actions",children:[w("button",{type:"button",className:"cortex-location-input__skip",disabled:N.submitting,onClick:()=>Q.current?.cancel(),children:X("translate_location_skip")}),w("button",{type:"button",className:"cortex-location-input__send",disabled:!N.position||N.submitting,onClick:()=>Q.current?.confirm(),children:X("translate_location_send")})]})]})]})}function M8({position:_}){let{t:$}=B(),X=n_(null),[Y,Q]=u6(!1),{lat:N,lng:Z}=_;return h6(()=>{let G=X.current;if(!G)return;return Q(!1),P1(G,{lat:N,lng:Z},()=>Q(!0))},[N,Z]),x("div",{className:"cortex-location-input cortex-location-input--settled",children:[x("div",{className:"cortex-location-input__map cortex-location-input__map--still",children:[w("div",{className:"cortex-location-input__canvas",ref:X,hidden:Y}),Y&&w("span",{className:"cortex-location-input__still-failed",children:$("translate_location_map_failed")})]}),x("div",{className:"cortex-location-input__body",children:[x("span",{className:"cortex-location-input__title",children:[w("svg",{viewBox:"0 0 20 20",fill:"none",children:w("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),$("translate_location_shared")]}),w("span",{className:"cortex-location-input__coords",children:v_(_)})]})]})}function O8(){return x("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:[w("circle",{cx:"10",cy:"10",r:"5.5"}),w("circle",{cx:"10",cy:"10",r:"1.6",fill:"currentColor",stroke:"none"}),w("path",{d:"M10 1.5v3M10 15.5v3M1.5 10h3M15.5 10h3"})]})}import{jsx as R,jsxs as W_}from"react/jsx-runtime";var P8=new Map([[k0,l6]]);function n6({message:_,toolCallPart:$,agentWorking:X}){let{config:Y,addToolResult:Q}=B(),N=$.state==="input-complete"&&!X,Z=$.state==="approval-requested"&&!X,G=Y.toolComponents?.[$.name]??(N||m($.state)?P8.get($.name):void 0);return R("div",{className:"cortex-tool-call-animated",children:G?R(G,{toolCallPart:$,message:_,setOutput:(J)=>Q($.id,$.name,J)}):N?R(A8,{toolCallPart:$}):R(i6,{toolCallPart:$,asking:Z})})}function A8({toolCallPart:_}){let{api:$,t:X,addToolResult:Y,selectedThread:Q,config:N}=B(),Z=Q?.id,[G,J]=p6({phase:"initiating"}),[z]=p6(N.trustSameOriginEmbeds),V=$0(void 0),W=$0({api:$,addToolResult:Y,toolName:_.name});if(W.current={api:$,addToolResult:Y,toolName:_.name},d6(()=>{if(!Z)return;let L=k1({initiate:()=>W.current.api.initiateToolCall(Z,_.id),onState:J,submit:(k)=>W.current.addToolResult(_.id,W.current.toolName,k)});V.current=L,L.start();let U=(k)=>L.handleMessage(k);return window.addEventListener("message",U),()=>{if(window.removeEventListener("message",U),L.dispose(),V.current===L)V.current=void 0}},[_.id,Z]),!Z||G.phase==="unavailable"||G.phase==="settling")return R(i6,{toolCallPart:_});let q=W_("div",{className:"cortex-client-tool-embed",children:[W_("div",{className:"cortex-client-tool-embed__bar",children:[R("span",{children:X("translate_client_tool_title")}),R("button",{type:"button",className:"cortex-client-tool-embed__cancel",onClick:()=>V.current?.cancel(),children:X("translate_client_tool_cancel")})]}),G.phase==="embedded"?R("iframe",{className:"cortex-client-tool-embed__frame",src:G.embedUrl,sandbox:U1(G.embedUrl,window.location.origin,z),title:X("translate_client_tool_title"),ref:(L)=>V.current?.setSource(L?.contentWindow),onLoad:(L)=>{if(!q1(G.embedUrl,window.location.origin,z)&&L1(L.currentTarget,window.location.origin))V.current?.terminate()}}):G.phase==="error"?W_("div",{className:"cortex-client-tool-embed__status",children:[R("span",{children:X("translate_client_tool_failed")}),R("button",{type:"button",className:"cortex-client-tool-embed__retry",onClick:()=>void V.current?.start(),children:X("translate_client_tool_retry")})]}):R("div",{className:"cortex-client-tool-embed__status",children:X("translate_client_tool_loading")})]});return G.phase==="embedded"&&G.surface==="modal"?R(E8,{label:X("translate_client_tool_title"),onCancel:()=>V.current?.cancel(),children:q}):q}function E8({label:_,onCancel:$,children:X}){let Y=$0(null);return d6(()=>{let Q=Y.current;return Q?.showModal(),()=>Q?.close()},[]),R("dialog",{ref:Y,className:"cortex-client-tool-embed-dialog","aria-label":_,onCancel:(Q)=>{Q.preventDefault(),$()},children:X})}function i6({toolCallPart:_,asking:$=!1}){let{t:X,locale:Y,respondToApproval:Q}=B(),{state:N,active:Z,gated:G,titleKey:J,statement:z,rowCount:V}=F_(_),W=D0(_);return W_("div",{className:F("cortex-tool-pill",G&&"cortex-tool-pill--gated",$&&"cortex-tool-pill--asking"),children:[W_("span",{className:"cortex-tool-pill__icon",children:[$&&R("span",{className:"cortex-tool-pill__dot"}),R("span",{className:F("cortex-tool-pill__spinner",Z&&"cortex-tool-pill__spinner--visible")}),R("svg",{className:F("cortex-tool-pill__svg","cortex-tool-pill__svg--check",N==="complete"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:R("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),R("svg",{className:F("cortex-tool-pill__svg","cortex-tool-pill__svg--error",N==="error"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:R("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})]}),R("span",{className:F("cortex-tool-pill__title",N==="error"&&"cortex-tool-pill__title--error",N==="starting"&&z&&"cortex-tool-pill__title--pending"),children:$?J1(_,Y)??X("translate_approval_prompt"):z??X(J)}),V!==void 0&&R("span",{className:"cortex-tool-pill__meta",children:X("translate_rows_read",{count:V})}),$&&W_("span",{className:"cortex-tool-pill__actions",children:[R("button",{type:"button",className:"cortex-tool-pill__action cortex-tool-pill__action--approve",onClick:()=>void Q(W,!0),children:X("translate_approve")}),R("button",{type:"button",className:"cortex-tool-pill__action",onClick:()=>void Q(W,!1),children:X("translate_deny")})]})]})}import{jsx as X0}from"react/jsx-runtime";function r6({message:_,toolCallPart:$,agentWorking:X}){if(!m($.state)&&!F_($).statement){if($.name==="queryGraph")return X0(I_,{activity:"graph"});if($.name==="executeCode")return X0(I_,{activity:"code"})}return X0(n6,{toolCallPart:$,message:_,agentWorking:X})}import{jsx as D_,jsxs as R8}from"react/jsx-runtime";function o6(_){let{message:$,part:X,debugMode:Y,animate:Q,streaming:N,agentWorking:Z,attachments:G}=_,{t:J}=B();function z(){switch(X.type){case"text":return D_(f6,{textPart:X,role:$.role,streaming:N,attachments:G});case"thinking":return Y?D_(I6,{reasoningPart:X,streaming:N}):D_(I_,{activity:"reasoning",className:"cortex-reasoning-animated"});case"tool-call":return Y?D_(m6,{toolCallPart:X}):D_(r6,{toolCallPart:X,message:$,agentWorking:Z});default:return R8("p",{className:"cortex-unhandled-type",children:[J("translate_unhandled_type")," ",X.type]})}}return D_("div",{className:F("cortex-message-part",Q&&"cortex-message-part--animated"),children:z()})}import{jsx as i,jsxs as Y0}from"react/jsx-runtime";function w8({isUser:_,clipboardText:$,createdAt:X}){let{locale:Y}=B();return Y0("div",{className:F("cortex-message-actions",_&&"cortex-message-actions--user"),children:[$&&i(j,{value:$}),X&&i("time",{className:"cortex-message-actions__time",dateTime:X,children:u(X,Y)})]})}function I8({count:_,animate:$,onOpen:X}){let{t:Y}=B();return i("button",{type:"button",className:F("cortex-tool-fold",$&&"cortex-message-part--animated"),onClick:X,children:Y(P_(_,"translate_one_more_step","translate_n_more_steps"),{count:_})})}function a6(_){let{message:$,parts:X,metadata:Y,debugMode:Q,animate:N,isStreaming:Z,agentWorking:G,closesTurn:J,fold:z,onOpenRun:V}=_,W=$.role==="assistant",q=$.role==="user",L=Z?X.length-1:-1,U=Y?.attachments??[],k=X.map((K)=>K.type).lastIndexOf("text"),M=(q||W)&&!Z&&k>=0,H=k<X.length-1?k:-1,D=M&&i(w8,{isUser:q,clipboardText:V1(X),createdAt:Y?.createdAt});return Y0("div",{className:"cortex-message-parts",children:[X.map((K,O)=>{let C=z?.get(K);return Y0(y8,{children:[i(o6,{part:K,message:$,debugMode:Q,animate:N,streaming:O===L,agentWorking:G,attachments:U}),C?.kind==="more"&&i(I8,{count:C.count,animate:N,onOpen:()=>V(C.runId)}),O===H&&D]},$.parts.indexOf(K))}),U.length>0&&i(k6,{attachments:U,isUser:q}),Y?.isAborted&&i(q6,{}),H===-1&&D,Q&&Y&&J&&i(w6,{messageId:$.id,isAssistant:W,metadata:Y})]})}import{jsx as X_,jsxs as Q0}from"react/jsx-runtime";function t6({firing:_,debugMode:$}){let{t:X,locale:Y}=B();return Q0("div",{className:F("cortex-trigger-block",$&&"cortex-trigger-block--debug"),children:[Q0("div",{className:"cortex-trigger-block__head",children:[X_("svg",{className:"cortex-trigger-block__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:X_("path",{d:"M6.75 1 2.5 6.75h3l-.25 4.25L9.5 5.25h-3z",fill:"currentColor"})}),$&&X_("span",{children:X("translate_trigger_fired")}),X_("span",{className:"cortex-trigger-block__name",children:_.name}),X_("time",{className:"cortex-trigger-block__time",dateTime:_.firedAt,children:u(_.firedAt,Y)})]}),$&&Q0("details",{className:"cortex-trigger-block__payload",children:[X_("summary",{children:X("translate_trigger_payload")}),X_(a,{data:_.payload,expandDepth:2})]})]})}import{jsx as b_}from"react/jsx-runtime";var s6=b8(function($){let{message:X,metadata:Y,isStreaming:Q,agentWorking:N,closesTurn:Z,debugMode:G,animate:J,fold:z,onOpenRun:V}=$,W=U_(X.parts,{debugMode:G,isStreaming:Q,fold:z});if(Y?.trigger)return b_("div",{className:"cortex-message",children:b_(t6,{firing:Y.trigger,debugMode:G})});if(W.length===0&&!Y?.attachments?.length)return b_("div",{className:"cortex-message"});return b_("div",{className:"cortex-message",children:b_(a6,{message:X,parts:W,metadata:Y,debugMode:G,animate:J,isStreaming:Q,agentWorking:N,closesTurn:Z,fold:z,onOpenRun:V})})});import{jsx as i_}from"react/jsx-runtime";var C8=[{role:"user",lines:[13,9]},{role:"assistant",lines:[16,18,12]},{role:"user",lines:[11]},{role:"assistant",lines:[14,15]}];function e6(){return i_("div",{className:"cortex-widget__messages-skeleton",children:C8.map((_,$)=>i_("div",{className:`cortex-widget__msg-skel cortex-widget__msg-skel--${_.role}`,children:i_("div",{className:`cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--${_.role}`,children:_.lines.map((X)=>i_("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:`${X}rem`}},X))})},$))})}import{jsx as Y_,jsxs as g8,Fragment as j8}from"react/jsx-runtime";function v8(_){let $=C_(null),X=C_(null),Y=C_(!0),Q=C_(!0),N=C_(!1),Z=r_(()=>{if(N.current)return;N.current=!0,queueMicrotask(()=>{N.current=!1;let V=$.current;if(!V)return;V.scrollTop=V.scrollHeight,Q.current=!0,Y.current=!1})},[]);o_(()=>{let V=X.current;if(!_||!$.current||!V)return;if(Z(),typeof ResizeObserver>"u")return;let W=0,q=new ResizeObserver(([L])=>{let U=L?.contentRect.height??0,k=U>W;if(W=U,k&&(Y.current||Q.current))Z()});return q.observe(V),()=>q.disconnect()},[_,Z]);let G=r_(()=>{Y.current=!0},[]),J=r_(()=>{if(Y.current)Z()},[Z]);function z(){let V=$.current;if(V)Q.current=V.scrollHeight-V.scrollTop-V.clientHeight<100}return{containerRef:$,contentRef:X,onScroll:z,pin:G,settlePinned:J}}function T8({pin:_,settlePinned:$},X,Y){let[Q,N]=N0(!1);o_(()=>{N(!1),_(),queueMicrotask(()=>N(!0))},[X,_]);let Z=Y[Y.length-1],G=Z?.role==="user"?Z.id:void 0;return o_(()=>{if(G)_()},[G,_]),o_(()=>{$()},[Y,$]),Q}function f8(_,$,X){let{config:Y}=B(),[Q,N]=N0(new Set),Z=r_((V)=>N((W)=>new Set(W).add(V)),[]),[G]=N0(W1),J=Y.toolComponents;return{folds:S8(()=>G(_,{agentWorking:$,debugMode:X,opened:Q,foldable:(V)=>!J?.[V.name]}),[G,_,$,X,Q,J]),openRun:Z}}function _2(_){let{selectedThread:$}=B(),{messages:X,isAgentWorking:Y,isLoadingMessages:Q,hasPendingToolCalls:N}=x_(),{capabilities:Z,composerRef:G}=_,J=!Q||Y,z=v8(J),V=T8(z,$?.id,X),W=Y?K1(X)?.id:void 0,{folds:q,openRun:L}=f8(X,Y,_.debugMode);return g8(j8,{children:[!J?Y_(e6,{}):Y_("div",{className:_.className,children:Y_("div",{ref:z.containerRef,className:"cortex-message-list",onScroll:z.onScroll,children:Y_("div",{ref:z.contentRef,className:"cortex-message-list__content",children:X.map((U,k)=>Y_(s6,{message:U,metadata:U.metadata,isStreaming:U.id===W,agentWorking:Y,fold:q.get(U.id),onOpenRun:L,closesTurn:U.role==="assistant"&&X[k+1]?.role!=="assistant",debugMode:_.debugMode,animate:V},U.id))})})}),Y&&!N&&Y_(F6,{}),!N&&Y_(c_,{capabilities:Z,composerRef:G})]})}import{jsx as a_,jsxs as m8}from"react/jsx-runtime";function $2(_){let{debugMode:$,selectedThread:X}=B(),{screens:Y}=_;return m8("div",{className:F("cortex-widget__screen",Y.screen==="chat"&&"cortex-widget__screen--active",Y.screen!=="chat"&&"cortex-widget__screen--right"),children:[a_(Q6,{onToggleSidebar:Y.toggleSidebar,onToggleDebug:_.onToggleDebug,onOpenHistory:Y.openHistory}),X?a_(_2,{className:"cortex-widget__messages",debugMode:$,capabilities:_.capabilities,composerRef:_.composerRef}):a_(H6,{onThreadSelected:_.onThreadSelected}),a_("div",{className:"cortex-widget__sidebar-backdrop",onClick:Y.closeSidebar})]})}import{useState as l8}from"react";import{useEffect as Z0,useRef as N2,useState as G0}from"react";import{useChat as u8}from"@tanstack/ai-react";import{useEffect as x8,useLayoutEffect as c8,useState as h8}from"react";function X2(_,{sessionRef:$,pendingSendRef:X}){let[Y]=h8(_);return c8(()=>{return $.current=Y,()=>{if($.current===Y)$.current=void 0}},[Y,$]),x8(()=>{if(!X.current.length)return;let Q=setTimeout(()=>{let N=X.current;X.current=[],(async()=>{for(let{prompt:Z,attachments:G}of N)await Y.send(Z,G)})()});return()=>clearTimeout(Q)},[Y,X]),Y}import{useRef as Y2}from"react";function Q2(_){let $=Y2(_);$.current=_;let X=Y2(Promise.resolve(void 0));async function Y(Q){let N=$.current;if(!N.isAlive()||Q!==N.threadId)return;return H1({api:N.api,threadId:Q,isStale:()=>!$.current.isAlive(),isStreaming:()=>$.current.isStreaming(),setMessages:(Z)=>$.current.setMessages(Z)})}return function(N){return X.current=X.current.then(()=>Y(N)),X.current}}function Z2(_){let{thread:$,api:X}=_,Y=N2(!0),[Q,N]=G0(!1),Z=N2(null),G=Q2({api:X,threadId:$.id,isAlive:()=>Y.current,isStreaming:()=>Z.current.chat.isLoading,setMessages:(D)=>Z.current.chat.setMessages(D)}),[J]=G0(()=>o1({threadId:$.id,isAlive:()=>Y.current,onToolCall:()=>Z.current.props.configRef.current.hooks?.onToolCall,deliver:(D)=>Z.current.chat.addToolResult(D),setRunning:(D)=>Z.current.props.setRunning($.id,D),reloadThreads:()=>Z.current.props.reloadThreads(),refreshMessages:()=>G($.id),onTurnFinished:()=>Z.current.props.onTurnFinished(),onSendFailed:()=>Z.current.props.onSendFailed()})),[z]=G0(()=>D1({api:X,thread:{id:$.id,isRunning:$.isRunning},mode:_.mode,localMessages:()=>Z.current.chat.messages,onHydrated:(D)=>{if(Y.current)J.hydrated(D,$.isRunning)},onTranscriptCarried:(D)=>{if(Y.current)J.transcriptCarried(D)},setLoadingMessages:(D)=>{if(Y.current)N(D)}})),V=u8({threadId:$.id,persistence:!0,initialMessages:_.initialMessages,connection:z,onChunk:()=>{if(Y.current)J.chunkArrived()},onError:()=>{if(Y.current)J.streamFailed()}});Z.current={chat:V,props:_};async function W(D,K){J.sendStarted();let O={id:q_(),role:"user",parts:[{type:"text",content:D}],metadata:{createdAt:new Date().toISOString(),attachments:K}};await Z.current.chat.append(O)}async function q(){if(!Z.current.chat.isLoading)return;let{aborted:D}=await X.abortStream($.id).catch(()=>({aborted:!1}));if(!Y.current)return;if(D)J.abortConfirmed();Z.current.chat.stop()}function L(D,K,O){return Z.current.chat.addToolResult({toolCallId:D,tool:K,output:O}).catch((C)=>{throw G($.id),C})}function U(D,K){return M1(Z.current.chat,D,K)}function k(D){if(Z.current.chat.isLoading)return;if(D.isRunning){Z.current.props.remount(D,Z.current.chat.messages);return}G(D.id)}Z0(()=>{return Y.current=!0,()=>{Y.current=!1}},[]),X2(()=>({threadId:$.id,send:W,abort:q,addToolResult:L,respondToApproval:U,reattach:k,transcriptUpdated:(D,K)=>{if(D===$.id)J.transcriptUpdated(K)}}),{sessionRef:_.sessionRef,pendingSendRef:_.pendingSendRef});let{messages:M,isLoading:H}=V;return Z0(()=>{J.loadingChanged(H,()=>Z.current.chat.messages)},[J,H]),Z0(()=>{Z.current.props.publish({messages:M,isAgentWorking:H,isLoadingMessages:Q,hasPendingToolCalls:!H&&r(M).length>0})},[M,H,Q]),null}import{jsx as G2,jsxs as p8}from"react/jsx-runtime";function J2({selection:_,threads:$,children:X,...Y}){let{session:Q}=_,[N,Z]=l8();if(!Q)return G2(m_.Provider,{value:g_,children:X});let G=`${Q.thread.id}:${Q.epoch}`,J=N&&(N.key===G||Q.mode==="reload")?N.value:g_;return p8(m_.Provider,{value:J,children:[G2(Z2,{thread:Q.thread,mode:Q.mode,initialMessages:Q.initialMessages,setRunning:$.setRunning,reloadThreads:$.reload,remount:_.remount,publish:(z)=>Z({key:G,value:z}),...Y},G),X]})}import{useSyncExternalStore as d8}from"react";function z2(_){return d8(($)=>{let X=window.matchMedia(_);return X.addEventListener("change",$),()=>X.removeEventListener("change",$)},()=>window.matchMedia(_).matches,()=>!1)}import{jsx as A,jsxs as c,Fragment as n8}from"react/jsx-runtime";function V2(_){let{locale:$,t:X,threads:Y,selectedThread:Q,deleteThread:N}=B(),Z=Y?.length??0;return c("div",{className:_.className,"aria-hidden":_.hidden||void 0,inert:_.hidden||void 0,children:[c("div",{className:"cortex-widget__threads-header",children:[A("button",{type:"button",onClick:()=>_.onBackRequested(),"aria-label":X("translate_back"),className:"cortex-widget__back-btn",children:A("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",className:"cortex-widget__back-icon",children:A("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("div",{children:[A("h2",{className:"cortex-widget__threads-title",children:X("translate_history")}),A("p",{className:"cortex-widget__threads-count",children:X(P_(Z,"translate_one_conversation","translate_n_conversations"),{count:Z})})]}),c("button",{onClick:()=>_.onNewChatRequested(),className:"cortex-widget__new-chat-btn",children:[A("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:A("path",{d:"M8 3v10M3 8h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})}),X("translate_new")]})]}),A("div",{className:"cortex-widget__threads-list",children:Y===void 0?[1,2,3,4].map((G)=>c("div",{className:"cortex-widget__thread-skeleton",children:[A("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-icon"}),A("div",{className:"cortex-widget__thread-skeleton-lines",children:A("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-line",style:{width:`${40+G*12}%`}})})]},G)):c(n8,{children:[Y.map((G)=>{let J=G.id===Q?.id,z=u(G.updatedAt,$);return c("button",{onClick:()=>_.onThreadSelected(G),className:F("cortex-widget__thread-item",J&&"cortex-widget__thread-item--active"),children:[A("div",{className:F("cortex-widget__thread-icon",J&&"cortex-widget__thread-icon--active"),children:A("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:A("path",{d:I.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("div",{className:"cortex-widget__thread-info",children:[c("div",{className:"cortex-widget__thread-title-row",children:[A("p",{className:F("cortex-widget__thread-title",J&&"cortex-widget__thread-title--active"),children:G.title??X("translate_untitled")}),G.isRunning&&c("span",{className:F("cortex-widget__thread-running",J&&"cortex-widget__thread-running--active"),children:[A("span",{className:"cortex-widget__thread-running-dot"}),X("translate_running")]})]}),z&&A("p",{className:"cortex-widget__thread-time",children:z})]}),A("span",{role:"button",tabIndex:0,onClick:(V)=>{V.stopPropagation(),N(G.id)},onKeyDown:(V)=>{if(V.key!=="Enter"&&V.key!==" ")return;V.preventDefault(),V.stopPropagation(),N(G.id)},className:F("cortex-widget__thread-delete",J&&"cortex-widget__thread-delete--active"),children:A("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:A("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})})}),A("svg",{className:F("cortex-widget__thread-arrow",J&&"cortex-widget__thread-arrow--active"),width:"10",height:"10",viewBox:"0 0 16 16",fill:"none",children:A("path",{d:"M6 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},G.id)}),!Y.length&&c("div",{className:"cortex-widget__threads-empty",children:[A("div",{className:"cortex-widget__threads-empty-icon",children:A("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__threads-empty-svg",children:A("path",{d:I.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),A("p",{className:"cortex-widget__threads-empty-title",children:X("translate_no_threads_yet")}),A("p",{className:"cortex-widget__threads-empty-subtitle",children:X("translate_start_a_new_conversation")}),A("button",{onClick:()=>_.onNewChatRequested(),className:"cortex-widget__new-chat-btn cortex-widget__new-chat-btn--empty-state",children:X("translate_new_chat")})]})]})})]})}import{jsx as W2,jsxs as r8}from"react/jsx-runtime";var i8="(max-width: 768px)";function K2(_){_.preventDefault()}function D2(_){let{screens:$}=_,X=z2(i8),Y=_.viewMode==="full"?X&&!$.sidebarOpen:$.screen!=="threads";return W2("div",{className:F("cortex-widget",_.className),"data-cortex-theme":_.theme,children:r8("div",{className:F("cortex-widget__container",_.viewMode==="full"&&"cortex-widget__container--full",$.sidebarOpen&&"cortex-widget__container--sidebar-open"),onDragOver:K2,onDrop:K2,children:[W2(V2,{className:F("cortex-widget__screen",$.screen==="threads"&&"cortex-widget__screen--active",$.screen!=="threads"&&"cortex-widget__screen--left"),hidden:Y,onThreadSelected:_.onThreadSelected,onNewChatRequested:_.onNewChat,onBackRequested:$.closeHistory}),_.children]})})}import{jsx as s_}from"react/jsx-runtime";function a8({config:_,className:$}){let X=H2(_);X.current=_;let[Y]=t_(()=>Q1(()=>X.current.transport)),Q=_6(Y),[N,Z]=t_(!1),[G,J]=t_();o8(()=>h1(_.theme,J),[_.theme]);let z=X6(),[V,W]=t_(0),q=p0(Y,V),L=H2(null),U=a0({api:Y,threads:Q,getHooks:()=>X.current.hooks}),{sessionRef:k,selection:M,queue:H,send:D,pendingSendRef:K}=U,{selected:O,selectedRef:C}=M,T=s0({threads:Q,selectedRef:C,sessionRef:k,deselect:M.deselect,onReconnect:()=>W((e)=>e+1)});t0({getConfig:()=>X.current,onEvent:T.onEvent,onMount:()=>void Q.reload(),onReconnect:T.onReconnect});let Q_=l1(_.locale),B2={config:_,locale:Q_,t:(e,k2)=>p1(Q_,e,k2),api:Y,debugMode:N,scheme:G,capabilities:q,threads:Q.threads,selectedThread:O,deleteThread:U.deleteThread,send:D,...e0(k),queue:H.value};function F2(){H.store.discardConsumed(),setTimeout(()=>L.current?.focusInput())}function U2(){H.store.restoreConsumed(C.current?.id)}function J0(e){U.openThread(e),z.showChat()}function q2(){M.deselect(),z.showChat()}function L2(){Z((e)=>!e)}return s_(a1.Provider,{value:B2,children:s_(D2,{className:$,theme:_.theme,viewMode:_.viewMode??"helper",screens:z,onThreadSelected:J0,onNewChat:q2,children:s_(J2,{selection:M,threads:Q,api:Y,configRef:X,sessionRef:k,pendingSendRef:K,onTurnFinished:F2,onSendFailed:U2,children:s_($2,{screens:z,capabilities:q,composerRef:L,onToggleDebug:L2,onThreadSelected:J0})})})})}export{a8 as CortexChatWidget};
6
+ `),closed:z});Q=null}let G=j0(),J=_.split(`
7
+ `);for(let[z,V]of J.entries()){let W=G(V);if(Q){if(W==="close")Z(!0);else Q.source.push(V);continue}if(W==="open"&&z===J.length-1)break;let U=F5(V,W,$);if(!U){Y.push(V);continue}if(N(),U.kind==="media")Q={language:U.language,source:[]};else X.push(U)}return Z(!1),N(),X}function F5(_,$,X){if($==="open"){let Q=_.replace(B5,"").trim().split(/\s+/)[0],N=X.find((Z)=>Z===Q);return N?{kind:"media",language:N}:void 0}let Y=$==="outside"?H5.exec(_):null;return Y?{kind:"attachment",alt:Y[1]??"",id:(Y[2]??"").toLowerCase()}:void 0}var x0=new Set(["flatten","fold","density","impute","regression","loess","quantile","sample"]),q5=`Use Vega-Lite JSON with inline \`data.values\` only, at most 200 rows, and no \`url\` anywhere. Compute folds, trend lines and densities yourself. For several series, write one row per series and x value, or keep one row per x value and draw a layer per series (color by \`datum\`) when that would exceed the row limit. These keys are refused anywhere in the spec: ${[...x0,"params","selection"].join(", ")}. Expressions in \`calculate\`, \`filter\` and \`labelExpr\` may use only datum fields, literals, operators and simple math or date-part functions (no format or timeFormat), so put formatted values in the rows or use an axis \`format\`.`;function h0(_,$){if(_==="url")return"Charts may only use inline data and no URLs.";if(_==="sequence"||_==="graticule")return"Charts may only use inline data.";if(x0.has(_))return"Charts may not use transforms that generate rows.";if(_==="params"||_==="selection"||_==="signals"||_==="on")return"Charts may not be interactive.";if(_==="expr")return"Charts may not carry expressions.";if(U5.has(_)&&typeof $==="string"&&!L5($))return"Charts may only use simple expressions over datum.";if(_==="usermeta")return"Charts may not carry usermeta.";if(typeof $==="string"&&h_($))return"Charts may not reference URLs.";if((_==="width"||_==="height")&&O5($)>4000)return"Charts may be at most 4000 pixels wide or tall.";return}var U5=new Set(["calculate","filter","test","signal","labelExpr"]),g0=new Set(["abs","ceil","floor","round","min","max","sqrt","pow","log","exp","year","month","date","day","hours","minutes","toNumber","toString","toDate","isValid","isNaN","if","indexof","length"]);function L5(_){if(_.length>500||/[\\`]/.test(_))return!1;let $=_.replace(/'[^']*'|"[^"]*"/g,'""');for(let[,Y]of $.matchAll(/([A-Za-z_$][\w$]*)\s*\(/g))if(!g0.has(Y??""))return!1;let X=$.replace(/(datum|parent)(\s*\.[\w$]+|\s*\[\s*""\s*\])+|\b\d[\w.]*/g,"").matchAll(/[A-Za-z_$][\w$]*/g);for(let[Y]of X)if(!g0.has(Y)&&!["true","false","null"].includes(Y))return!1;return!0}function O5(_){if(typeof _==="number")return _;let $=_?.step;return typeof $==="number"?$:0}function m0(_,$){let X=_?.features,Y=Array.isArray(_)?_.length:Array.isArray(X)?X.length:-1;if(Y<0)return h0($,_)??m1(g1(_,$),E_);return Y>200?"Charts may hold at most 200 rows.":void 0}function E_(_,$=""){if($==="values")return m0(_,$);if($==="datasets")return m1(g1(_),m0);return h0($,_)??m1(g1(_,$),(X,Y)=>E_(X,Y))}function g1(_,$=""){if(Array.isArray(_))return _.map((X)=>[$,X]);return _&&typeof _==="object"?Object.entries(_):[]}function m1(_,$){for(let[X,Y]of _){let Q=$(Y,X);if(Q)return Q}return}var c0=/url\(([^)]*)\)/gi,x1="src|image|image-set|-webkit-image-set|cross-fade|element",h1=new RegExp(String.raw`\b(url|${x1})\(`,"i"),P5=new RegExp(String.raw`\b(${x1})\(`,"i"),M5=new RegExp(String.raw`\b(${x1})\([^)]*\)`,"gi"),k5=/\\([0-9a-f]{1,6})\s?|\\(.)/gi;function A5(_){return _.replace(k5,($,X,Y)=>{if(!X)return Y??"";let Q=parseInt(X,16),N=Q===0||Q>=55296&&Q<=57343||Q>1114111;return String.fromCodePoint(N?65533:Q)})}function u0(_){return _.trim().replace(/^(['"])(.*)\1$/s,"$2").trim()}function h_(_){if(_.includes("\\")||P5.test(_))return!0;for(let[,$]of _.matchAll(c0))if(!u0($??"").startsWith("#"))return!0;return!1}function c1(_){return A5(_).replace(M5,"none").replace(c0,($,X)=>u0(X).startsWith("#")?$:"none")}var r0={async mermaid(_,$,{scheme:X}){let[{default:Y},{default:Q}]=await Promise.all([import("mermaid"),import("dompurify")]);if(h1.test($)||$.includes("\\"))throw Error("Diagrams may not reference URLs.");if(/%%\{/.test($))throw Error("Diagrams may not carry init directives.");if(/^\s*---\s*$/m.test($))throw Error("Diagrams may not carry frontmatter.");if(/\bimg\s*:/.test($))throw Error("Diagrams may not embed images.");let N=y5($);if(!R5.test(N))throw Error(`Unsupported diagram type: ${N}`);let Z=p0.then(async()=>{if(!l0)Y.initialize({startOnLoad:!1,securityLevel:"strict",htmlLabels:!1}),l0=!0;let z=`%%{init: {"theme": "${X==="dark"?"dark":"default"}"}}%%
8
+ ${$}`;return await Y.parse(z),(await Y.render(`cortex-mermaid-${I5()}`,z,_)).svg});p0=Z.catch(()=>{return});let G=await Z,J=document.createElement("div");return J.innerHTML=Q.sanitize(G,{USE_PROFILES:{svg:!0,svgFilters:!0}}),n0(J),_.replaceChildren(...J.childNodes),()=>{_.innerHTML=""}},async "vega-lite"(_,$,{scheme:X}){let Y=JSON.parse($),Q=E_(Y);if(Q)throw Error(Q);let[{default:N},Z]=await Promise.all([import("vega-embed"),import("vega")]),G=()=>Promise.reject(Error("Charts may only use inline data.")),J=document.createElement("div"),z=await N(J,Y,{actions:!1,renderer:"svg",mode:"vega-lite",loader:{...Z.loader(),load:G,sanitize:G},ast:!0,...X==="dark"?{theme:"dark"}:{},config:{background:"transparent"}});return n0(J),_.replaceChildren(J),()=>z.finalize()},async map(_,$){let X=C5(JSON.parse($)),{leaflet:Y,map:Q,dispose:N}=await k_(_,{...X,interactive:!0});for(let Z of X.markers){let G=Y.marker(Z.position).addTo(Q);if(Z.label){let J=document.createElement("span");J.textContent=Z.label,G.bindTooltip(J)}}return N}},E5={mermaid:"translate_media_pending_mermaid","vega-lite":"translate_media_pending_vega_lite",map:"translate_media_pending_map"};function u1(_){return E5[_]??"translate_media_pending"}function p1(_){return Object.keys({...r0,..._})}function l1(_,$){let{language:X,source:Y,context:Q,overrides:N,onError:Z}=$,G=_.appendChild(document.createElement("div")),J=N?.[X]??r0[X],z,V=!1;return(J?J(G,Y,Q):Promise.reject(Error(`No renderer for ${X}.`))).then((U)=>{if(V)U();else z=U},(U)=>{if(!V)Z(U instanceof Error?U.message:String(U))}),()=>{V=!0,z?.(),G.remove()}}var R5=/^(flowchart|graph|sequenceDiagram|stateDiagram(-v2)?|erDiagram|gantt|pie|classDiagram|journey|timeline|mindmap)$/;function y5(_){let $=_.split(`
9
+ `).find((X)=>/\S/.test(X)&&!/^\s*%%/.test(X));return/^\s*(\S+)/.exec($??"")?.[1]??""}var p0=Promise.resolve(),l0=!1,d0=0;function I5(){return d0+=1,d0}var w5=new Set(["image","use","feImage"]);function n0(_){for(let $ of[_,..._.querySelectorAll("*")]){for(let X of[...$.attributes])if((X.name==="href"||X.name==="xlink:href")&&w5.has($.tagName)&&!X.value.trim().startsWith("#")||h_(X.value))$.removeAttribute(X.name);if($.tagName==="style"&&$.textContent)$.textContent=c1($.textContent)}}function C5(_){if(!_||typeof _!=="object")throw Error("A map needs a JSON object.");let $=_,X=$.zoom??10;if(typeof X!=="number"||X<0||X>22)throw Error("zoom must be 0 to 22.");let Y=$.markers??[];if(!Array.isArray(Y))throw Error("markers must be a list.");return{center:i0($.center,"center"),zoom:X,markers:Y.map((Q,N)=>{let Z=Q??{},G=Z.label;return{position:i0(Z.position,`markers[${N}].position`),label:typeof G==="string"?G:void 0}})}}function i0(_,$){let X=Array.isArray(_)?_:[],[Y,Q]=X;if(typeof Y!=="number"||typeof Q!=="number"||Math.abs(Y)>90||Math.abs(Q)>180)throw Error(`${$} must be [latitude, longitude].`);return{lat:Y,lng:Q}}function d1(_,$){if(_!=="system")return $(_??"light"),()=>{};let X=window.matchMedia("(prefers-color-scheme: dark)"),Y=()=>$(X.matches?"dark":"light");return Y(),X.addEventListener("change",Y),()=>X.removeEventListener("change",Y)}import R_ from"highlight.js/lib/core";import b5 from"highlight.js/lib/languages/javascript";import S5 from"highlight.js/lib/languages/json";import T5 from"highlight.js/lib/languages/sql";var o0=!1;function v5(){if(o0)return;o0=!0,R_.registerLanguage("javascript",b5),R_.registerLanguage("json",S5),R_.registerLanguage("cypher",T5)}function n1(_,$){if(!_)return"";return v5(),R_.getLanguage($)?R_.highlight(_,{language:$}).value:f5(_)}function f5(_){return _.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var a0={translate_new:"جديد",translate_history:"السجل",translate_back:"رجوع",translate_greeting:"بماذا يمكنني مساعدتك اليوم؟",translate_n_conversations:"{{count}} محادثات",translate_one_conversation:"محادثة واحدة",translate_no_threads_yet:"لا توجد محادثات بعد",translate_start_a_new_conversation:"ابدأ محادثة جديدة",translate_untitled:"بدون عنوان",translate_new_chat:"محادثة جديدة",translate_normal:"عادي",translate_debug:"تصحيح",translate_type_a_message:"اكتب رسالة...",translate_completed:"مكتمل",translate_attach_files:"إرفاق ملفات",translate_drop_files_here:"أفلت ملفاتك هنا...",translate_remove_attachment:"إزالة المرفق",translate_attachment_rejected:"لا يمكن إرفاق هذا الملف",translate_attachment_caption:"من فضلك اطّلع على الملفات المرفقة.",translate_download:"تنزيل",translate_tool_status_0:"جارٍ جلب البيانات…",translate_tool_status_1:"جارٍ تحليل المعلومات…",translate_tool_status_2:"جارٍ معالجة الطلب…",translate_tool_status_3:"جارٍ تجميع النتائج…",translate_tool_status_4:"جارٍ تحضير الرد…",translate_tool_status_5:"جارٍ البحث…",translate_tool_status_6:"جارٍ فحص السجلات…",translate_tool_status_7:"جارٍ مراجعة التفاصيل…",translate_tool_status_8:"جارٍ إجراء الحسابات…",translate_tool_status_9:"جارٍ سحب المعلومات…",translate_tool_done_0:"تم جلب البيانات بنجاح",translate_tool_done_1:"تم التحليل بنجاح",translate_tool_done_2:"تمت معالجة الطلب بنجاح",translate_tool_done_3:"تم تجميع النتائج بنجاح",translate_tool_done_4:"تم تحضير الرد بنجاح",translate_tool_done_5:"تم البحث بنجاح",translate_tool_done_6:"تم فحص السجلات بنجاح",translate_tool_done_7:"تمت المراجعة بنجاح",translate_tool_done_8:"تمت الحسابات بنجاح",translate_tool_done_9:"تم استرجاع المعلومات بنجاح",translate_rows_read:"{{count}} صفوف",translate_one_more_step:"وخطوة أخرى",translate_n_more_steps:"و{{count}} خطوات أخرى",translate_tool_error:"حدث خطأ",translate_attachment_status:"جارٍ قراءة الملف المرفق…",translate_attachment_done:"تمت قراءة الملف المرفق",translate_graph_0:"جارٍ استكشاف الروابط...",translate_graph_1:"جارٍ رسم الخريطة...",translate_graph_2:"جارٍ اكتشاف العلاقات...",translate_graph_3:"جارٍ تتبع الروابط...",translate_graph_4:"جارٍ التنقل في المعرفة...",translate_graph_5:"جارٍ كشف الرؤى...",translate_graph_6:"جارٍ ربط النقاط...",translate_graph_7:"جارٍ تتبع المسار...",translate_graph_8:"جارٍ تجميع الأجزاء...",translate_graph_9:"جارٍ بناء الصورة...",translate_code_0:"جارٍ حساب الأرقام...",translate_code_1:"جارٍ معالجة البيانات...",translate_code_2:"جارٍ تنفيذ طلبك...",translate_code_3:"جارٍ تحليل الأرقام...",translate_code_4:"جارٍ تجميع كل شيء...",translate_code_5:"جارٍ تحليل النتائج...",translate_code_6:"جارٍ العمل خلف الكواليس...",translate_code_7:"جارٍ ترتيب التفاصيل...",translate_code_8:"جارٍ تحضير إجابتك...",translate_code_9:"أوشك على الانتهاء...",translate_reasoning_0:"جارٍ التفكير...",translate_reasoning_1:"جارٍ دراسة الخيارات...",translate_reasoning_2:"جارٍ تقييم الاحتمالات...",translate_reasoning_3:"جارٍ التأمل في هذا...",translate_reasoning_4:"جارٍ إيجاد الحل...",translate_reasoning_5:"جارٍ ترتيب الأفكار...",translate_reasoning_6:"جارٍ التمعن في الأمر...",translate_reasoning_7:"جارٍ إيجاد أفضل طريقة...",translate_reasoning_8:"جارٍ تنظيم أفكاري...",translate_reasoning_9:"أوشك على الانتهاء...",translate_running:"قيد التنفيذ",translate_aborted:"تم الإلغاء",translate_input:"المدخلات",translate_output:"المخرجات",translate_calling:"جارٍ الاستدعاء",translate_input_ready:"المدخلات جاهزة",translate_needs_approval:"بحاجة إلى موافقة",translate_approved:"تمت الموافقة",translate_responded:"تم الرد",translate_declined:"تم الرفض",translate_approve:"موافقة",translate_deny:"رفض",translate_approval_prompt:"يريد المساعد تنفيذ إجراء. هل تسمح بذلك؟",translate_error:"خطأ",translate_approval_requested:"طلب موافقة",translate_approval_response:"رد الموافقة",translate_waiting_for_approval:"في انتظار الموافقة لتنفيذ هذه الأداة.",translate_tool_approved:"تمت الموافقة.",translate_tool_response_received:"تم استلام الرد.",translate_tokens:"رمز",translate_fresh:"جديد",translate_cache_read:"قراءة من الذاكرة",translate_cache_write:"كتابة في الذاكرة",translate_n_percent_cached:"{{percent}}٪ مخزّن مؤقتًا",translate_text:"نص",translate_reasoning:"الاستنتاج",translate_read:"قراءة",translate_write:"كتابة",translate_total:"الإجمالي",translate_request:"الطلب",translate_response:"الرد",translate_step_n:"الخطوة {{number}}",translate_inspect_llm_requests:"فحص طلبات النموذج",translate_loading:"جارٍ التحميل…",translate_no_llm_requests:"لا توجد طلبات نموذج مسجّلة لهذه الرسالة.",translate_unhandled_type:"نوع غير مدعوم:",translate_client_tool_title:"أكمل هذه الخطوة للمتابعة",translate_client_tool_loading:"جارٍ تجهيز خطوة آمنة...",translate_client_tool_failed:"تعذّر تحميل هذه الخطوة",translate_client_tool_retry:"حاول مرة أخرى",translate_client_tool_cancel:"إلغاء",translate_location_hint:"انقر على الخريطة لتثبيت الدبوس",translate_location_locate:"استخدم موقعي",translate_location_locating:"جارٍ تحديد موقعك",translate_location_locate_failed:"موقعك غير متاح",translate_location_map_failed:"تعذّر تحميل الخريطة",translate_location_send_failed:"تعذّر الإرسال، حاول مرة أخرى",translate_location_skip:"ليس الآن",translate_location_send:"إرسال",translate_location_shared:"تمت مشاركة الموقع",translate_location_not_shared:"لم تتم مشاركة الموقع",translate_trigger_fired:"تم التشغيل بواسطة",translate_trigger_payload:"الحمولة",translate_messages_disabled:"يعمل هذا الوكيل من مشغّلاته فقط.",translate_streaming:"جارٍ البث",translate_done:"تم",translate_no_reasoning:"لا يوجد تفكير مسجّل.",translate_copy:"نسخ إلى الحافظة",translate_copied:"تم النسخ",translate_media_pending_mermaid:"جارٍ رسم المخطط",translate_media_pending_vega_lite:"جارٍ رسم الرسم البياني",translate_media_pending_map:"جارٍ رسم الخريطة",translate_media_cut_off:"انقطع هذا المقطع قبل اكتماله.",translate_media_failed:"تعذر عرض هذا المقطع.",translate_media_source:"المصدر",translate_media_pending:"جارٍ الرسم",translate_image_unavailable:"الصورة غير متاحة",translate_image_unavailable_alt:"الصورة غير متاحة: {{alt}}",translate_send:"إرسال"};var t0={translate_new:"New",translate_history:"History",translate_back:"Back",translate_greeting:"What can I help you with today?",translate_n_conversations:"{{count}} conversations",translate_one_conversation:"1 conversation",translate_no_threads_yet:"No threads yet",translate_start_a_new_conversation:"Start a new conversation",translate_untitled:"Untitled",translate_new_chat:"New Chat",translate_normal:"Normal",translate_debug:"Debug",translate_type_a_message:"Type a message...",translate_completed:"Completed",translate_attach_files:"Attach files",translate_drop_files_here:"Drop your files here...",translate_remove_attachment:"Remove attachment",translate_attachment_rejected:"This file cannot be attached",translate_attachment_caption:"Please take a look at the attached files.",translate_download:"Download",translate_tool_status_0:"Fetching data...",translate_tool_status_1:"Analyzing information...",translate_tool_status_2:"Processing request...",translate_tool_status_3:"Gathering results...",translate_tool_status_4:"Preparing response...",translate_tool_status_5:"Looking things up...",translate_tool_status_6:"Checking records...",translate_tool_status_7:"Reviewing details...",translate_tool_status_8:"Running calculations...",translate_tool_status_9:"Pulling information...",translate_tool_done_0:"Data fetched successfully",translate_tool_done_1:"Analysis completed successfully",translate_tool_done_2:"Request processed successfully",translate_tool_done_3:"Results gathered successfully",translate_tool_done_4:"Response prepared successfully",translate_tool_done_5:"Lookup completed successfully",translate_tool_done_6:"Records checked successfully",translate_tool_done_7:"Review completed successfully",translate_tool_done_8:"Calculations completed successfully",translate_tool_done_9:"Information retrieved successfully",translate_rows_read:"{{count}} rows",translate_one_more_step:"and 1 more step",translate_n_more_steps:"and {{count}} more steps",translate_tool_error:"Something went wrong",translate_attachment_status:"Reading the attached file...",translate_attachment_done:"Finished reading the file",translate_graph_0:"Exploring connections...",translate_graph_1:"Mapping out the links...",translate_graph_2:"Discovering relationships...",translate_graph_3:"Tracing the connections...",translate_graph_4:"Navigating the knowledge...",translate_graph_5:"Uncovering insights...",translate_graph_6:"Connecting the dots...",translate_graph_7:"Following the trail...",translate_graph_8:"Piecing things together...",translate_graph_9:"Building the picture...",translate_code_0:"Running the numbers...",translate_code_1:"Working through the data...",translate_code_2:"Processing your request...",translate_code_3:"Crunching the figures...",translate_code_4:"Putting it all together...",translate_code_5:"Analyzing the results...",translate_code_6:"Working behind the scenes...",translate_code_7:"Sorting through the details...",translate_code_8:"Preparing your answer...",translate_code_9:"Almost ready...",translate_reasoning_0:"Thinking it through...",translate_reasoning_1:"Considering the options...",translate_reasoning_2:"Weighing the possibilities...",translate_reasoning_3:"Reflecting on this...",translate_reasoning_4:"Working it out...",translate_reasoning_5:"Putting thoughts together...",translate_reasoning_6:"Mulling it over...",translate_reasoning_7:"Finding the best approach...",translate_reasoning_8:"Organizing my thoughts...",translate_reasoning_9:"Almost there...",translate_running:"Running",translate_aborted:"Aborted",translate_input:"Input",translate_output:"Output",translate_calling:"Calling",translate_input_ready:"Input ready",translate_needs_approval:"Needs approval",translate_approved:"Approved",translate_responded:"Responded",translate_declined:"Declined",translate_approve:"Approve",translate_deny:"Deny",translate_approval_prompt:"The assistant wants to take an action. Allow it?",translate_error:"Error",translate_approval_requested:"Approval requested",translate_approval_response:"Approval response",translate_waiting_for_approval:"Waiting for approval to execute this tool.",translate_tool_approved:"Approved.",translate_tool_response_received:"Response received.",translate_tokens:"tokens",translate_fresh:"Fresh",translate_cache_read:"Cache read",translate_cache_write:"Cache write",translate_n_percent_cached:"{{percent}}% cached",translate_text:"Text",translate_reasoning:"Reasoning",translate_read:"Read",translate_write:"Write",translate_total:"Total",translate_request:"Request",translate_response:"Response",translate_step_n:"Step {{number}}",translate_inspect_llm_requests:"Inspect LLM requests",translate_loading:"loading…",translate_no_llm_requests:"No LLM requests recorded for this message.",translate_unhandled_type:"Unhandled type:",translate_client_tool_title:"Complete this step to continue",translate_client_tool_loading:"Preparing a secure step...",translate_client_tool_failed:"This step could not be loaded",translate_client_tool_retry:"Try again",translate_client_tool_cancel:"Cancel",translate_location_hint:"Tap the map to drop a pin",translate_location_locate:"Use my location",translate_location_locating:"Finding your location",translate_location_locate_failed:"Your location is not available",translate_location_map_failed:"The map could not be loaded",translate_location_send_failed:"Could not send, try again",translate_location_skip:"Not now",translate_location_send:"Send",translate_location_shared:"Location shared",translate_location_not_shared:"Location not shared",translate_trigger_fired:"Triggered by",translate_trigger_payload:"Payload",translate_messages_disabled:"This agent only runs from its triggers.",translate_streaming:"Streaming",translate_done:"Done",translate_no_reasoning:"No reasoning provided.",translate_copy:"Copy to clipboard",translate_copied:"Copied",translate_media_pending_mermaid:"Drawing diagram",translate_media_pending_vega_lite:"Drawing chart",translate_media_pending_map:"Drawing map",translate_media_cut_off:"This block was cut off before it finished.",translate_media_failed:"Could not render this block.",translate_media_source:"Source",translate_media_pending:"Drawing",translate_image_unavailable:"Image unavailable",translate_image_unavailable_alt:"Image unavailable: {{alt}}",translate_send:"Send"};var m5={en:t0,ar:a0};function i1(_){return _&&X1.includes(_)?_:X1[0]}function r1(_,$,X){let Y=m5[_][$];if(!X)return Y;return Y.replace(/\{\{\s*(\w+)\s*\}\}/g,(Q,N)=>(N in X)?String(X[N]):Q)}function y_(_,$,X){return _===1?$:X}function z_(_){if(typeof _==="string"){let $=_.trim();if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return _;try{return z_(JSON.parse($))}catch{return _}}if(Array.isArray(_))return _.map(($)=>z_($));if(_!==null&&typeof _==="object"){let $={};for(let[X,Y]of Object.entries(_))$[X]=z_(Y);return $}return _}function o1(_,$){if(Array.isArray(_)){let X=_;return{kind:"container",open:"[",close:"]",summary:s0(X.length,"item","items"),entries:X.map((Y,Q)=>({key:null,value:Y,path:`${$}[${Q}]`}))}}if(_!==null&&typeof _==="object"){let X=Object.entries(_);return{kind:"container",open:"{",close:"}",summary:s0(X.length,"property","properties"),entries:X.map(([Y,Q])=>({key:Y,value:Q,path:`${$}.${Y}`}))}}return{kind:"primitive",text:x5(_),className:h5(_)}}function s0(_,$,X){return`${_} ${_===1?$:X}`}function x5(_){if(_===null||_===void 0)return"null";if(typeof _==="string")return JSON.stringify(_);if(typeof _==="number"||typeof _==="boolean")return String(_);return JSON.stringify(_)??"null"}function h5(_){if(_===null||_===void 0)return"cortex-json-tree__null";if(typeof _==="string")return"cortex-json-tree__string";if(typeof _==="number")return"cortex-json-tree__number";if(typeof _==="boolean")return"cortex-json-tree__boolean";return""}function a1(_){if(!_)return null;try{return JSON.parse(_)}catch{return _}}function t1(_){if(!_)return"";try{return JSON.stringify(JSON.parse(_),null,2)}catch{return _}}function V_(_,$){if(_===void 0||typeof _==="string"||Array.isArray(_))return _;let X=_;return X[$]??X.en??Object.values(X)[0]}function l(_,$,X=Date.now()){let Y=new Date(_);if(Number.isNaN(Y.getTime()))return"";let Q=Y.toDateString()===new Date(X).toDateString();return new Intl.DateTimeFormat($,{...Q?{}:{dateStyle:"medium"},timeStyle:"short"}).format(Y)}function s1(_,$){let X=URL.createObjectURL(_),Y=document.createElement("a");Y.href=X,Y.download=$,Y.click(),URL.revokeObjectURL(X)}class t{onUpdate;fullText="";displayedLength=0;animationFrameId=null;isDone=!1;releases=[];static DRAIN_FRACTION=0.03;static MIN_CHARS_PER_FRAME=1;static DONE_DRAIN_FRACTION=0.1;static FADE_WINDOW_MS=500;constructor(_){this.onUpdate=_}seed(_){this.fullText=_,this.displayedLength=_.length,this.releases=[],this.onUpdate(_,[])}update(_,$){if(this.fullText=_,this.isDone=$,this.displayedLength=Math.min(this.displayedLength,this.fullText.length),this.releases=this.releases.filter((X)=>X.from<this.displayedLength),$&&this.displayedLength>=this.fullText.length){this.onUpdate(this.fullText,[]),this.stopAnimation();return}if(!this.animationFrameId)this.scheduleFrame()}destroy(){this.stopAnimation()}scheduleFrame(){this.animationFrameId=requestAnimationFrame((_)=>this.tick(_))}tick(_){let $=this.fullText.length-this.displayedLength;if($<=0){this.animationFrameId=null;return}let X=this.isDone?t.DONE_DRAIN_FRACTION:t.DRAIN_FRACTION,Y=Math.max(t.MIN_CHARS_PER_FRAME,Math.ceil($*X));if(this.releases=this.releases.filter((Q)=>_-Q.at<t.FADE_WINDOW_MS),this.releases.push({from:this.displayedLength,at:_}),this.displayedLength=Math.min(this.fullText.length,this.displayedLength+Y),this.onUpdate(this.fullText.substring(0,this.displayedLength),this.releases.map((Q)=>({length:this.displayedLength-Q.from,age:_-Q.at}))),this.displayedLength<this.fullText.length)this.scheduleFrame();else this.animationFrameId=null}stopAnimation(){if(this.animationFrameId)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}}var e1=new WeakMap;function _0(_,$){let X=_.closest(".cortex-widget__screen"),Y=X?.querySelector(".cortex-message-list");if(!X||!Y||!_.value.trim())return;let Q=getComputedStyle(_),N=_.getBoundingClientRect(),Z=(G)=>parseFloat(Q[`padding${G}`])+parseFloat(Q[`border${G}Width`]);e1.set(X,{text:$,textarea:_,from:new DOMRect(N.left+Z("Left"),N.top+Z("Top"),N.width-Z("Left")-Z("Right"),N.height-Z("Top")-Z("Bottom")),rtl:Q.direction==="rtl",scrollTop:Y.scrollTop})}function $0(_,$){let X=_.closest(".cortex-widget__screen"),Y=X?e1.get(X):void 0;if(!X||!Y)return;e1.delete(X);let Q=_.querySelectorAll(":scope > .cortex-message"),N=Q[Q.length-1]?.querySelector(".cortex-text-bubble--user"),Z=_.closest(".cortex-message-list");if(!N||!Z||Y.text!==$||!Y.textarea.isConnected)return;N.closest(".cortex-message-part")?.getAnimations().forEach((D)=>D.finish()),c_(Z);let G=N.getBoundingClientRect(),J=X.getBoundingClientRect(),z=getComputedStyle(N),V=parseFloat(z.paddingTop)+parseFloat(z.borderTopWidth),W=Y.rtl?parseFloat(z.paddingRight)+parseFloat(z.borderRightWidth):parseFloat(z.paddingLeft)+parseFloat(z.borderLeftWidth),U=Y.rtl?Y.from.right+W-G.width:Y.from.left-W,B=Z.scrollTop-Y.scrollTop;if(B)_.style.setProperty("--cortex-slide",`${B}px`),_.classList.remove("cortex-message-list__content--settling"),_.offsetWidth,_.classList.add("cortex-message-list__content--settling"),_.getAnimations()[0]?.finished.then(()=>_.classList.remove("cortex-message-list__content--settling"),()=>{return});let F=N.cloneNode(!0);F.classList.add("cortex-send-flight"),F.setAttribute("aria-hidden","true"),Object.assign(F.style,{left:`${G.left-J.left}px`,top:`${G.top-J.top}px`,width:`${G.width}px`}),F.style.setProperty("--cortex-fly-x",`${U-G.left}px`),F.style.setProperty("--cortex-fly-y",`${Y.from.top-V-G.top}px`),N.style.visibility="hidden",X.append(F);let O=Z.scrollTop,P=()=>{F.style.top=`${G.top-J.top-(Z.scrollTop-O)}px`};Z.addEventListener("scroll",P,{passive:!0}),$6(F).then(()=>{Z.removeEventListener("scroll",P),N.style.visibility="",F.remove()})}function c_(_){_.scrollTop=_6(_)}function X0(_){return _6(_)-_.scrollTop}function _6(_){let $=_.querySelector(".cortex-message-list__content");if(!$)return _.scrollHeight-_.clientHeight;let X=getComputedStyle(_);return $.offsetHeight+parseFloat(X.paddingTop)+parseFloat(X.paddingBottom)-_.clientHeight}function Y0(_){let $=!1,X=_.parentElement,Y=typeof ResizeObserver>"u"?void 0:new ResizeObserver(Q);Y?.observe(X);function Q(){let N=X.querySelector(":scope > .cortex-working-thinking, :scope > .cortex-message > .cortex-message-parts > [data-cortex-frontier]");if(!N)return!1;return _.style.setProperty("--cortex-avatar-y",`${c5(N,X)-_.offsetHeight/2}px`),!0}return{sync(N){if(N===$){if(N)Q();return}if(N){if(!Q())return;_.classList.remove("cortex-working-avatar--leaving"),_.offsetWidth,_.classList.add("cortex-working-avatar--shown"),$=!0;return}$=!1,_.classList.add("cortex-working-avatar--leaving"),$6(_,!0).then(()=>{if($)return;_.classList.remove("cortex-working-avatar--shown","cortex-working-avatar--leaving")})},dispose(){Y?.disconnect()}}}function c5(_,$){let X=_.querySelector(".cortex-text-bubble");if(!X)return e0(_,$)+_.offsetHeight/2;let Y=getComputedStyle(X);return e0(X,$)+parseFloat(Y.paddingTop)+parseFloat(Y.borderTopWidth)+parseFloat(Y.lineHeight)/2}function e0(_,$){let X=0;for(let Y=_;Y instanceof HTMLElement&&Y!==$;)X+=Y.offsetTop,Y=Y.offsetParent;return X}function $6(_,$=!1){return Promise.allSettled(_.getAnimations({subtree:$}).map((X)=>X.finished))}var u5=2;function Q0(_){let $=!1,X=!1,Y=!1,Q=!1,N=!1,Z=!1,G,J=new Set,z=0,V=!1;function W(){if($&&z===0)return!1;if(z+=1,!$)$=!0,_.setRunning(!0);return!0}function U(D){if(z-=1,D)V=!0;else if(z===0&&!V)$=!1,_.setRunning(!1)}async function B(D,H){for(let K=0;K<u5;K+=1){let M=await _.refreshMessages().catch(()=>{return});if(!_.isAlive())return!1;if(!M)continue;if(!a(M).some((R)=>R.id===D.id))return!0;if(await _.deliver(H).then(()=>!0,()=>!1))return!0}return!1}async function F(D,H){let K;try{let p=H({toolCallId:D.id,toolName:D.name,input:D.input},{threadId:_.threadId});if(p===null||p===void 0)return;K=await Promise.resolve(p)}catch{J.delete(D.id);return}if(K===null||K===void 0)return;if(!_.isAlive())return;let M=W(),k={toolCallId:D.id,tool:D.name,output:K},R=await _.deliver(k).then(()=>!0,()=>B(D,k));if(M)U(R);if(!R)J.delete(D.id)}function O(D){let H=a(D),K=_.onToolCall();if(!K)return H.length>0;for(let M of H){if(M.state!=="input-complete"||J.has(M.id))continue;J.add(M.id),F(M,K)}return H.length>0}async function P(D){let H=Q;if(Q=!1,!H&&$){if(O(D()))return;if(Y)_.reloadThreads().catch(()=>{});else _.setRunning(!1)}if(G===void 0&&(Z||H))return;G=void 0;let K=await _.refreshMessages();if(!H&&$&&K)O(K)}return{chunkArrived(){X=!0},transcriptCarried(D){if(Z=!0,G!==void 0&&G<=D)G=void 0},transcriptUpdated(D){if(!N){_.refreshMessages();return}G=Math.max(G??0,Date.parse(D))},streamFailed(){if(Y=!0,X)_.onTurnFinished();else _.onSendFailed()},loadingChanged(D,H){if(D){N=!0,Y=!1,Z=!1;return}if(!N)return;N=!1,_.onTurnFinished(),P(H)},hydrated(D,H){if(H)return;setTimeout(()=>{if(_.isAlive())O(D)},0)},sendStarted(){_.setRunning(!0),$=!0,X=!1},abortConfirmed(){Q=!0,_.setRunning(!1)}}}function I_(_){if(_.input.total<=0)return null;return Math.round(_.input.cacheRead/_.input.total*100)}import{createContext as X6,useContext as Y6}from"react";var N0=X6(void 0);function L(){let _=Y6(N0);if(!_)throw Error("useCortex must be used inside <CortexChatWidget>");return _}var u_={messages:[],isAgentWorking:!1,isLoadingMessages:!1,hasPendingToolCalls:!1},p_=X6(u_);function l_(){return Y6(p_)}import{useEffect as p5,useState as l5}from"react";function Q6(_,$){let[X,Y]=l5();return p5(()=>{return Y(void 0),T1(_,Y)},[_,$]),X}import{useRef as s5}from"react";import{useRef as d5,useState as n5,useSyncExternalStore as i5}from"react";function N6(_,$){let X=d5($);X.current=$;let[Y]=n5(()=>L1({api:_,ensureThread:()=>X.current()})),Q=i5(Y.subscribe,Y.getState,Y.getState);return{store:Y,value:{items:Q,...O1(Q),accept:Y.accept,remove:Y.remove,consumeReady:Y.consumeReady}}}import{useEffect as r5,useRef as o5}from"react";function Z6(_,$){let X=o5(void 0);r5(()=>{if($===X.current)return;_.clear(X.current),X.current=$},[$,_])}import{useRef as G6}from"react";function J6(_){let $=G6([]),X=G6(void 0);function Y(){let N=_.selectedRef.current;if(N)return Promise.resolve(N.id);return X.current??=_.api.createThread().then((Z)=>{return X.current=void 0,_.onCreated(Z),Z.id},(Z)=>{throw X.current=void 0,Z}),X.current}async function Q(N,Z=[]){let G=_.sessionRef.current;if(G){await G.send(N,Z);return}$.current.push({prompt:N,attachments:Z});try{await Y()}catch(J){throw $.current=[],J}}return{ensureThread:Y,send:Q,pendingSendRef:$}}import{useRef as a5,useState as t5}from"react";function z6(_){let[$,X]=t5(),Y=$?.thread,Q=Y?_.threads?.find((z)=>z.id===Y.id)??Y:void 0,N=a5(Q);N.current=Q;function Z(z,V){if(N.current?.id===z.id&&_.hasSession())return;let W=N.current;if(N.current=z,X({thread:z,mode:V,epoch:0}),W&&W.id!==z.id)_.getHooks()?.onThreadDeselected?.(W);_.getHooks()?.onThreadSelected?.(z)}function G(){let z=N.current;if(!z&&!_.hasSession())return;if(N.current=void 0,X(void 0),z)_.getHooks()?.onThreadDeselected?.(z)}function J(z,V){X((W)=>({thread:z,mode:"reload",epoch:(W?.epoch??0)+1,initialMessages:V}))}return{session:$,selected:Q,selectedRef:N,select:Z,deselect:G,remount:J}}function V6(_){let{api:$,threads:X}=_,Y=s5(void 0),Q=z6({threads:X.threads,getHooks:_.getHooks,hasSession:()=>Y.current!==void 0}),N=J6({api:$,sessionRef:Y,selectedRef:Q.selectedRef,onCreated:(z)=>{X.upsert(z),Q.select(z,"skip")}}),Z=N6($,N.ensureThread);Z6(Z.store,Q.selected?.id);async function G(z){if(Q.selectedRef.current?.id===z)Q.deselect();await X.remove(z)}function J(z){Q.select(z,"load")}return{sessionRef:Y,selection:Q,queue:Z,deleteThread:G,openThread:J,...N}}import{useEffect as e5,useRef as _8}from"react";function K6(_){let $=_8(_);$.current=_,e5(()=>{$.current.onMount();let X=!1,Y=S1({getConfig:()=>$.current.getConfig(),onEvent:(Q)=>$.current.onEvent(Q),onOpen:()=>{if(X)$.current.onReconnect();X=!0}});return()=>Y.close()},[])}function W6(_){let{threads:$,selectedRef:X,sessionRef:Y}=_;function Q(Z){$.applyEvent(Z);let G=X.current?.id;switch(Z.type){case"thread:deleted":if(G===Z.payload.threadId)_.deselect();break;case"thread:run-started":if(G===Z.payload.thread.id)Y.current?.reattach(Z.payload.thread);break;case"thread:messages-updated":Y.current?.transcriptUpdated(Z.payload.thread.id,Z.payload.thread.updatedAt);break}}function N(){_.onReconnect(),$.reload().then((Z)=>{let G=X.current;if(!G)return;Y.current?.reattach(Z.find((J)=>J.id===G.id)??G)})}return{onEvent:Q,onReconnect:N}}function D6(_){return{abort:async()=>{await _.current?.abort()},addToolResult:($,X,Y)=>_.current?.addToolResult($,X,Y)??Promise.resolve(),respondToApproval:($,X)=>_.current?.respondToApproval($,X)??Promise.resolve()}}import{useState as $8}from"react";function H6(_){let[$,X]=$8();async function Y(){let J=m_(await _.listThreads());return X(J),J}function Q(J){X((z)=>A_(z??[],J))}function N(J,z){X((V)=>{let W=V?.find((U)=>U.id===J);return W?A_(V??[],{...W,isRunning:z}):V})}async function Z(J){await _.deleteThread(J),X((z)=>z?x_(z,J):z)}function G(J){X((z)=>{let V=v1(z??[],J);return z||V.length?V:z})}return{threads:$,reload:Y,upsert:Q,setRunning:N,remove:Z,applyEvent:G}}import{useState as B6}from"react";function F6(){let[_,$]=B6("chat"),[X,Y]=B6(!1);return{screen:_,sidebarOpen:X,showChat:()=>{$("chat"),Y(!1)},openHistory:()=>$("threads"),closeHistory:()=>$("chat"),toggleSidebar:()=>Y((Q)=>!Q),closeSidebar:()=>Y(!1)}}function q(..._){return _.filter(Boolean).join(" ")}import{jsx as d,jsxs as q6}from"react/jsx-runtime";function U6({onToggleSidebar:_,onToggleDebug:$,onOpenHistory:X}){let{config:Y,locale:Q,t:N,debugMode:Z,selectedThread:G}=L();return q6("div",{className:"cortex-widget__chat-header",children:[d("button",{onClick:_,className:"cortex-widget__sidebar-toggle-btn",children:d("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:d("path",{d:"M2.5 4h11M2.5 8h11M2.5 12h11",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}),d("div",{className:"cortex-widget__chat-title-wrap",children:d("p",{className:"cortex-widget__chat-title",children:G?.title??V_(Y.agentName,Q)??N("translate_new_chat")})}),Y.showDebugButton&&d("button",{onClick:$,className:q("cortex-widget__debug-btn",Z?"cortex-widget__debug-btn--on":"cortex-widget__debug-btn--off"),children:Z?N("translate_debug"):N("translate_normal")}),d("button",{type:"button",onClick:X,"aria-label":N("translate_history"),className:"cortex-widget__history-btn",children:q6("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[d("circle",{cx:"8",cy:"8",r:"5.75",stroke:"currentColor",strokeWidth:"1.3"}),d("path",{d:"M8 5v3l2 1.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})}var b={bubble:"M13.5 7.6c0 2.4-2.5 4.4-5.5 4.4-.6 0-1.2-.08-1.7-.23L3 13l.8-2.3C3 9.8 2.5 8.7 2.5 7.6 2.5 5.2 5 3.2 8 3.2s5.5 2 5.5 4.4Z",chevronDown:"M3 4.5L6 7.5L9 4.5",chevronDownLarge:"m5.75 8.25 4.25 4.25 4.25-4.25",file:["M4 1.5h5.172a2 2 0 0 1 1.414.586l2.328 2.328a2 2 0 0 1 .586 1.414V12.5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2Z","M9.5 1.5v2a2 2 0 0 0 2 2h2"]};import{forwardRef as J8,useEffect as z8,useImperativeHandle as V8,useRef as A6,useState as K8}from"react";import{useState as X8}from"react";function L6(_,$){let[X,Y]=X8(!1);return{dragging:X,onDragOver:(Q)=>{if(Q.preventDefault(),_)Y(!0)},onDragLeave:(Q)=>{if(!Q.currentTarget.contains(Q.relatedTarget))Y(!1)},onDrop:(Q)=>{if(Q.preventDefault(),Y(!1),_)$([...Q.dataTransfer.files])},onPaste:(Q)=>{let N=Q.clipboardData.files;if(!_||!N.length)return;Q.preventDefault(),$([...N])}}}import{jsx as n,jsxs as Z0}from"react/jsx-runtime";function O6(){let{queue:_,t:$}=L();if(!_.items.length)return null;return n("div",{className:"cortex-attachment-queue",children:_.items.map((X)=>Z0("div",{className:q("cortex-attachment-chip",X.status==="error"&&"cortex-attachment-chip--error"),title:X.status==="error"?$("translate_attachment_rejected"):"",children:[X.status==="uploading"||X.status==="deleting"?Z0("svg",{className:"cortex-attachment-chip__spinner",viewBox:"0 0 16 16",fill:"none",children:[n("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",className:"cortex-attachment-chip__spinner-track"}),n("path",{d:"M14 8a6 6 0 0 0-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):Z0("svg",{viewBox:"0 0 16 16",className:"cortex-attachment-chip__icon",fill:"none",children:[n("path",{d:b.file[0],stroke:"currentColor",strokeWidth:"1.25"}),n("path",{d:b.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),n("span",{className:"cortex-attachment-chip__name",children:X.filename}),n("button",{type:"button",onClick:()=>_.remove(X.localId),className:"cortex-attachment-chip__remove",disabled:X.status==="deleting","aria-label":$("translate_remove_attachment"),children:n("svg",{viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M4.5 4.5l7 7m0-7l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]},X.localId))})}import{useRef as Y8}from"react";import{jsx as X_,jsxs as P6,Fragment as N8}from"react/jsx-runtime";var Q8=Y1.join(",");function M6({attachmentsEnabled:_,canSend:$,onSend:X}){let{t:Y,queue:Q}=L(),N=Y8(null);return P6("div",{className:"cortex-widget__input-actions",children:[_&&P6(N8,{children:[X_("button",{type:"button",onClick:()=>N.current?.click(),className:"cortex-widget__attach-btn","aria-label":Y("translate_attach_files"),children:X_("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:X_("path",{d:"M10.5 5.5 6.2 9.8a1.4 1.4 0 0 0 2 2l4.6-4.6a2.8 2.8 0 0 0-4-4L4.2 7.8a4.2 4.2 0 0 0 6 6l4-4",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),X_("input",{ref:N,type:"file",multiple:!0,accept:Q8,onChange:(Z)=>{Q.accept([...Z.target.files??[]]),Z.target.value=""},className:"cortex-widget__file-input"})]}),X_("button",{onClick:X,"aria-label":Y("translate_send"),className:q("cortex-widget__send-btn",!$&&"cortex-widget__send-btn--empty",$&&"cortex-widget__send-btn--ready"),disabled:!$,children:X_("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__send-icon",children:X_("path",{d:"M3 8h10M9 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}import{useLayoutEffect as Z8}from"react";import{jsx as G8}from"react/jsx-runtime";function k6(_){let{t:$}=L();Z8(()=>{let Y=_.inputRef.current;if(!Y)return;Y.style.height="0px",Y.style.height=`${Y.scrollHeight}px`},[_.inputRef,_.value]);function X(Y){if(Y.key==="Enter"&&!Y.shiftKey)Y.preventDefault(),_.onSubmit()}return G8("textarea",{ref:_.inputRef,onKeyDown:X,onPaste:_.onPaste,value:_.value,onChange:(Y)=>_.onChange(Y.target.value),placeholder:_.dragging?$("translate_drop_files_here"):_.disabled?"":$("translate_type_a_message"),disabled:_.disabled,rows:1,className:q("cortex-widget__textarea",_.disabled&&"cortex-widget__textarea--disabled")})}import{jsx as K_,jsxs as G0}from"react/jsx-runtime";var E6=J8(function($,X){let{t:Y,queue:Q,send:N,abort:Z,capabilities:G}=L(),{isAgentWorking:J}=l_(),z=G?.attachments??!1,[V,W]=K8(""),U=L6(z,Q.accept),B=A6(null);V8(X,()=>({focusInput:()=>B.current?.focus()}));let F=A6(J);z8(()=>{if(F.current&&!J)B.current?.focus();F.current=J},[J]);let O=!Q.busy&&(Boolean(V.trim())||Q.hasReady);function P(){if(J||!O)return;let D=V.trim()||Y("translate_attachment_caption"),H=Q.consumeReady();if(B.current)_0(B.current,D);W(""),N(D,H.map((K)=>K.summary))}return G0("div",{className:"cortex-widget__input-area",onDragOver:U.onDragOver,onDragLeave:U.onDragLeave,onDrop:U.onDrop,children:[K_(O6,{}),G0("div",{className:q("cortex-widget__input-box",J&&"cortex-widget__input-box--disabled",!J&&"cortex-widget__input-box--enabled",U.dragging&&"cortex-widget__input-box--dragging"),children:[K_(k6,{inputRef:B,value:V,onChange:W,onSubmit:P,onPaste:U.onPaste,disabled:J,dragging:U.dragging}),J?G0("button",{onClick:()=>void Z(),className:"cortex-stop-btn",children:[K_("span",{className:"cortex-stop-btn__ring"}),K_("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"cortex-stop-btn__icon",children:K_("rect",{x:"1",y:"1",width:"10",height:"10",rx:"2.5",fill:"currentColor"})})]}):K_(M6,{attachmentsEnabled:z,canSend:O,onSend:P})]})]})});import{jsx as R6}from"react/jsx-runtime";function d_({capabilities:_,composerRef:$}){let{t:X}=L();if(_===void 0)return null;return _.messages===!1?R6("p",{className:"cortex-widget__messages-disabled",children:X("translate_messages_disabled")}):R6(E6,{ref:$})}import{jsx as u,jsxs as y6}from"react/jsx-runtime";function I6(_){let{locale:$,t:X,threads:Y,send:Q,capabilities:N}=L(),Z=N?.messages===!1,G=N!==void 0,J=V_(N?.suggestions,$),z=V_(N?.greeting,$)||X("translate_greeting");return y6("div",{className:"cortex-widget__landing",children:[u("div",{className:"cortex-widget__landing-icon",children:u("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",children:u("path",{d:b.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),u("p",{className:"cortex-widget__landing-greeting",children:z}),G&&!Z&&!!J?.length&&u("div",{className:"cortex-widget__landing-chips",children:J.map((V,W)=>u("button",{type:"button",onClick:()=>void Q(V.prompt),className:"cortex-widget__landing-chip",children:V.title},W))}),u(d_,{capabilities:N}),!!Y?.length&&u("div",{className:"cortex-widget__landing-recent",children:Y.slice(0,2).map((V)=>{let W=l(V.updatedAt,$);return y6("button",{type:"button",onClick:()=>_.onThreadSelected(V),className:"cortex-widget__landing-recent-item",children:[u("p",{className:"cortex-widget__landing-recent-title",children:V.title??X("translate_untitled")}),W&&u("p",{className:"cortex-widget__landing-recent-time",children:W})]},V.id)})})]})}import{useCallback as v_,useEffect as H0,useLayoutEffect as B0,useMemo as l8,useRef as Z_,useState as F0}from"react";import{memo as u8}from"react";import{Fragment as x8}from"react";import{useRef as W8,useState as D8}from"react";import{jsx as W_,jsxs as H8}from"react/jsx-runtime";function g({value:_,className:$}){let{t:X}=L(),[Y,Q]=D8(!1),N=W8(null);async function Z(G){G.stopPropagation(),G.preventDefault();try{if(await navigator.clipboard.writeText(_),Q(!0),N.current)clearTimeout(N.current);N.current=setTimeout(()=>Q(!1),1500)}catch{}}return W_("span",{className:q("cortex-copy-btn",$),children:W_("button",{className:q("cortex-copy-btn__button",Y&&"cortex-copy-btn__button--copied"),onClick:(G)=>void Z(G),"aria-label":Y?X("translate_copied"):X("translate_copy"),type:"button",children:Y?W_("svg",{className:"cortex-copy-btn__icon cortex-copy-btn__icon--check",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:W_("path",{d:"M5 13l4 4L19 7",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):H8("svg",{className:"cortex-copy-btn__icon",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:[W_("rect",{x:"9",y:"9",width:"12",height:"12",rx:"2",stroke:"currentColor",strokeWidth:"2"}),W_("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})})})}import{jsx as n_,jsxs as w6}from"react/jsx-runtime";function C6(){let{t:_}=L();return w6("div",{className:"cortex-aborted-flag",children:[n_("span",{className:"cortex-aborted-flag__line"}),w6("span",{className:"cortex-aborted-flag__label",children:[n_("svg",{className:"cortex-aborted-flag__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n_("path",{d:"M6 1.5v5M6 8.75v.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})}),_("translate_aborted")]}),n_("span",{className:"cortex-aborted-flag__line"})]})}import{jsx as D_,jsxs as b6}from"react/jsx-runtime";function S6(_){let{api:$,t:X}=L();async function Y(Q){let{blob:N,name:Z}=await $.downloadAttachment(Q);s1(N,Z)}return D_("div",{className:q("cortex-message-attachments",_.isUser&&"cortex-message-attachments--user"),children:_.attachments.map((Q)=>b6("button",{type:"button",onClick:()=>void Y(Q.id),className:"cortex-message-attachment","aria-label":`${X("translate_download")}: ${Q.filename}`,children:[b6("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__icon",fill:"none",children:[D_("path",{d:b.file[0],stroke:"currentColor",strokeWidth:"1.25"}),D_("path",{d:b.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),D_("span",{className:"cortex-message-attachment__name",children:Q.filename}),D_("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__dl-icon",fill:"none",children:D_("path",{d:"M8 3v7m0 0L5.5 7.5M8 10l2.5-2.5M3 13h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},Q.id))})}import{useRef as q8,useState as w_}from"react";import{useMemo as B8,useState as F8}from"react";import{jsx as j,jsxs as Y_,Fragment as i_}from"react/jsx-runtime";function s({data:_,expandDepth:$,className:X}){let Y=B8(()=>z_(_),[_]),[Q,N]=F8({});function Z(J,z){return Q[J]??z>=$}function G(J,z){N((V)=>({...V,[J]:!Z(J,z)}))}return j("div",{className:q("cortex-json-tree",X),children:j(T6,{value:Y,path:"$",depth:0,isCollapsed:Z,toggle:G})})}function T6({value:_,path:$,depth:X,isCollapsed:Y,toggle:Q}){let N=o1(_,$);if(N.kind==="primitive")return j("span",{className:N.className,children:N.text});if(N.entries.length===0)return Y_("span",{className:"cortex-json-tree__bracket",children:[N.open,N.close]});let Z=Y($,X);function G(J){Q($,X),J.stopPropagation()}return Y_(i_,{children:[Y_("span",{className:"cortex-json-tree__toggle",onClick:G,role:"button",children:[j("span",{className:q("cortex-json-tree__arrow",Z&&"cortex-json-tree__arrow--collapsed"),children:"▾"}),j("span",{className:"cortex-json-tree__bracket",children:N.open})]}),Z?Y_(i_,{children:[j("span",{className:"cortex-json-tree__collapsed-hint",onClick:G,role:"button",children:N.summary}),j("span",{className:"cortex-json-tree__bracket",children:N.close})]}):Y_(i_,{children:[j("div",{className:"cortex-json-tree__indent",children:N.entries.map((J,z)=>Y_("div",{className:"cortex-json-tree__line",children:[J.key!==null&&Y_(i_,{children:[j("span",{className:"cortex-json-tree__key",children:`"${J.key}"`}),j("span",{className:"cortex-json-tree__colon",children:": "})]}),j(T6,{value:J.value,path:J.path,depth:X+1,isCollapsed:Y,toggle:Q}),z<N.entries.length-1&&j("span",{className:"cortex-json-tree__comma",children:","})]},J.path))}),j("span",{className:"cortex-json-tree__bracket",children:N.close})]})]})}function y(_){return _.toLocaleString("en-US")}import{jsx as H_,jsxs as B_}from"react/jsx-runtime";function v6({usage:_}){let{t:$}=L();return B_("div",{className:"cortex-llm-inspector__usage-rows",children:[B_("div",{className:"cortex-llm-inspector__usage-row",children:[H_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_input")}),H_("span",{className:"cortex-llm-inspector__usage-val",children:y(_.input.total)}),B_("span",{className:"cortex-llm-inspector__usage-detail",children:[$("translate_fresh")," ",y(_.input.noCache)," · ",$("translate_read")," ",y(_.input.cacheRead)," · ",$("translate_write")," ",y(_.input.cacheWrite)]})]}),B_("div",{className:"cortex-llm-inspector__usage-row",children:[H_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_output")}),H_("span",{className:"cortex-llm-inspector__usage-val",children:y(_.output.total)}),B_("span",{className:"cortex-llm-inspector__usage-detail",children:[$("translate_text")," ",y(_.output.text)," · ",$("translate_reasoning")," ",y(_.output.reasoning)]})]}),B_("div",{className:"cortex-llm-inspector__usage-row cortex-llm-inspector__usage-row--total",children:[H_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_total")}),H_("span",{className:"cortex-llm-inspector__usage-val",children:y(_.total)})]})]})}import{jsx as f6,jsxs as r_}from"react/jsx-runtime";function j6({usage:_}){let $=I_(_);return r_("span",{className:"cortex-llm-inspector__step-metrics",children:[r_("span",{className:"cortex-llm-inspector__metric",children:[f6("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--input"}),y(_.input.total)]}),r_("span",{className:"cortex-llm-inspector__metric",children:[f6("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--output"}),y(_.output.total)]}),$!==null&&r_("span",{className:"cortex-llm-inspector__cache-pct",children:[$,"%"]})]})}import{jsx as w,jsxs as e}from"react/jsx-runtime";function g6({messageId:_}){let{t:$,api:X}=L(),[Y,Q]=w_(!1),[N,Z]=w_(!1),[G,J]=w_([]),[z,V]=w_(null),[W,U]=w_({}),B=q8(!1);async function F(){if(!B.current){Z(!0);try{J(await X.listLlmRequests(_))}finally{Z(!1),B.current=!0}}Q((K)=>!K)}function O(K){V((M)=>M===K?null:K)}function P(K){return W[K]??"prompt"}function D(K,M){U((k)=>({...k,[K]:M}))}function H(K){return P(K.id)==="prompt"?K.prompt:K.output}return e("div",{className:q("cortex-llm-inspector",Y&&"cortex-llm-inspector--open"),children:[e("button",{className:"cortex-llm-inspector__trigger",onClick:()=>void F(),children:[w("svg",{className:"cortex-llm-inspector__icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:w("path",{d:"M6 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8ZM0 6a6 6 0 1 1 10.89 3.477l4.817 4.816a1 1 0 0 1-1.414 1.414l-4.816-4.816A6 6 0 0 1 0 6Z",fill:"currentColor"})}),w("span",{children:$("translate_inspect_llm_requests")}),N?w("span",{className:"cortex-llm-inspector__loading",children:$("translate_loading")}):G.length>0?w("span",{className:"cortex-llm-inspector__badge",children:G.length}):null,w("svg",{className:"cortex-llm-inspector__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:w("path",{d:b.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),w("div",{className:"cortex-llm-inspector__panel-wrapper",children:w("div",{className:"cortex-llm-inspector__panel-inner",children:e("div",{className:"cortex-llm-inspector__panel",children:[G.length===0&&!N&&w("div",{className:"cortex-llm-inspector__empty",children:$("translate_no_llm_requests")}),G.map((K,M)=>e("div",{className:q("cortex-llm-inspector__step",z===K.id&&"cortex-llm-inspector__step--expanded"),children:[e("button",{className:"cortex-llm-inspector__step-header",onClick:()=>O(K.id),children:[w("span",{className:"cortex-llm-inspector__step-label",children:$("translate_step_n",{number:M+1})}),K.tokenUsage&&w(j6,{usage:K.tokenUsage}),w("svg",{className:"cortex-llm-inspector__step-chevron",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:w("path",{d:b.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),w("div",{className:"cortex-llm-inspector__step-body-wrapper",children:w("div",{className:"cortex-llm-inspector__step-body-inner",children:e("div",{className:"cortex-llm-inspector__step-body",children:[K.tokenUsage&&w(v6,{usage:K.tokenUsage}),e("div",{className:"cortex-llm-inspector__tabs",children:[w("button",{className:q("cortex-llm-inspector__tab",P(K.id)==="prompt"&&"cortex-llm-inspector__tab--active"),onClick:()=>D(K.id,"prompt"),children:$("translate_request")}),w("button",{className:q("cortex-llm-inspector__tab",P(K.id)==="response"&&"cortex-llm-inspector__tab--active"),onClick:()=>D(K.id,"response"),children:$("translate_response")})]}),e("div",{className:"cortex-llm-inspector__json-pane",children:[w(g,{className:"cortex-llm-inspector__json-copy",value:t1(H(K))}),w(s,{data:a1(H(K)),expandDepth:2})]})]})})})]},K.id))]})})})]})}import{useState as U8}from"react";import{jsx as A,jsxs as S}from"react/jsx-runtime";function m6({usage:_,modelId:$}){let{t:X}=L(),[Y,Q]=U8(!1),N=I_(_)??0;return S("div",{className:q("cortex-token-usage",Y&&"cortex-token-usage--expanded"),children:[S("button",{className:"cortex-token-usage__summary",onClick:()=>Q((Z)=>!Z),children:[S("span",{className:"cortex-token-usage__total",children:[A("span",{className:"cortex-token-usage__total-number",children:y(_.total)}),A("span",{className:"cortex-token-usage__total-label",children:X("translate_tokens")})]}),$?A("span",{className:"cortex-token-usage__model",children:$}):null,S("span",{className:"cortex-token-usage__pills",children:[S("span",{className:"cortex-token-usage__pill",children:[A("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),y(_.input.total)]}),S("span",{className:"cortex-token-usage__pill",children:[A("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),y(_.output.total)]})]}),N>0&&S("span",{className:"cortex-token-usage__cache-badge",children:[N,"%"]}),A("svg",{className:"cortex-token-usage__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:A("path",{d:b.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),A("div",{className:"cortex-token-usage__details",children:A("div",{className:"cortex-token-usage__details-inner",children:S("div",{className:"cortex-token-usage__columns",children:[S("div",{className:"cortex-token-usage__col",children:[S("div",{className:"cortex-token-usage__col-header",children:[A("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),A("span",{className:"cortex-token-usage__col-label",children:X("translate_input")}),A("span",{className:"cortex-token-usage__col-total",children:y(_.input.total)})]}),S("div",{className:"cortex-token-usage__rows",children:[_.input.noCache?S("div",{className:"cortex-token-usage__row",children:[A("span",{className:"cortex-token-usage__row-label",children:X("translate_fresh")}),A("span",{className:"cortex-token-usage__row-value",children:y(_.input.noCache)})]}):null,_.input.cacheRead?S("div",{className:"cortex-token-usage__row",children:[A("span",{className:"cortex-token-usage__row-label",children:X("translate_cache_read")}),A("span",{className:"cortex-token-usage__row-value",children:y(_.input.cacheRead)})]}):null,_.input.cacheWrite?S("div",{className:"cortex-token-usage__row",children:[A("span",{className:"cortex-token-usage__row-label",children:X("translate_cache_write")}),A("span",{className:"cortex-token-usage__row-value",children:y(_.input.cacheWrite)})]}):null]}),N>0&&S("div",{className:"cortex-token-usage__cache-bar-row",children:[A("div",{className:"cortex-token-usage__cache-bar",children:A("div",{className:"cortex-token-usage__cache-fill",style:{width:`${N}%`}})}),A("span",{className:"cortex-token-usage__cache-label",children:X("translate_n_percent_cached",{percent:N})})]})]}),S("div",{className:"cortex-token-usage__col",children:[S("div",{className:"cortex-token-usage__col-header",children:[A("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),A("span",{className:"cortex-token-usage__col-label",children:X("translate_output")}),A("span",{className:"cortex-token-usage__col-total",children:y(_.output.total)})]}),S("div",{className:"cortex-token-usage__rows",children:[_.output.text?S("div",{className:"cortex-token-usage__row",children:[A("span",{className:"cortex-token-usage__row-label",children:X("translate_text")}),A("span",{className:"cortex-token-usage__row-value",children:y(_.output.text)})]}):null,_.output.reasoning?S("div",{className:"cortex-token-usage__row",children:[A("span",{className:"cortex-token-usage__row-label",children:X("translate_reasoning")}),A("span",{className:"cortex-token-usage__row-value",children:y(_.output.reasoning)})]}):null]})]})]})})})]})}import{jsx as x6,jsxs as L8}from"react/jsx-runtime";function h6({messageId:_,isAssistant:$,metadata:X}){let{tokenUsage:Y}=X;if(!Y&&!$)return null;return L8("div",{className:"cortex-message-debug-zone",children:[Y&&x6(m6,{usage:Y,modelId:X.modelId}),$&&x6(g6,{messageId:_})]})}import{jsx as m,jsxs as C_}from"react/jsx-runtime";function c6(_){let{reasoningPart:$,streaming:X=!1}=_,{t:Y}=L();return C_("details",{className:"cortex-reasoning-details",children:[C_("summary",{className:"cortex-reasoning-details__summary",children:[C_("div",{className:"cortex-reasoning-details__header",children:[m("span",{className:"cortex-reasoning-details__icon",children:C_("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:[m("path",{d:"M10 2C6.686 2 4 4.686 4 8c0 1.655.672 3.154 1.757 4.243.362.363.576.858.576 1.371V14.5a1 1 0 0 0 1 1h5.334a1 1 0 0 0 1-1v-.886c0-.513.214-1.008.576-1.371A5.978 5.978 0 0 0 16 8c0-3.314-2.686-6-6-6Z",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),m("path",{d:"M7.5 17.5h5M8.5 8a2 2 0 0 1 2-2",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})]})}),m("div",{className:"cortex-reasoning-details__title-group",children:C_("div",{className:"cortex-reasoning-details__title-row",children:[m("div",{className:"cortex-reasoning-details__title",children:Y("translate_reasoning")}),m("span",{className:q("cortex-reasoning-details__badge",X?"cortex-reasoning-details__badge--streaming":"cortex-reasoning-details__badge--done"),children:X?Y("translate_streaming"):Y("translate_done")})]})})]}),m("span",{className:"cortex-reasoning-details__chevron","aria-hidden":"true",children:m("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:m("path",{d:b.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),m("div",{className:"cortex-reasoning-details__body",children:m("div",{className:"cortex-reasoning-details__content",children:m("pre",{className:"cortex-reasoning-details__pre",children:$.content.trim()?$.content:Y("translate_no_reasoning")})})})]})}import{useEffect as n6,useMemo as R8,useRef as z0,useState as y8}from"react";import{useEffect as O8,useState as u6}from"react";import{jsx as J0,jsxs as P8}from"react/jsx-runtime";function p6(_){let{id:$,alt:X,attachment:Y}=_,{api:Q,t:N}=L(),[Z,G]=u6(),[J,z]=u6(!1);if(O8(()=>{let V,W=!1;return G(void 0),z(!1),Q.downloadAttachment($).then(({blob:U})=>{if(W)return;V=URL.createObjectURL(U),G(V)},()=>{if(!W)z(!0)}),()=>{if(W=!0,V)URL.revokeObjectURL(V)}},[Q,$]),J)return J0("p",{className:"cortex-attachment-image__caption",children:X?N("translate_image_unavailable_alt",{alt:X}):N("translate_image_unavailable")});if(!Z)return null;return P8("figure",{className:"cortex-attachment-image",children:[J0("img",{src:Z,alt:X}),Y&&J0("figcaption",{className:"cortex-attachment-image__caption",children:Y.filename})]})}import{useEffect as M8,useRef as k8,useState as l6}from"react";import{jsx as i,jsxs as o_}from"react/jsx-runtime";function A8(_){let{t:$}=L();if(!_.pending&&!_.debugMode)return null;return o_("div",{className:"cortex-media-block__head",children:[_.debugMode&&i("span",{className:"cortex-media-block__lang",children:_.language}),_.pending&&i("span",{className:"cortex-media-block__pending",children:$(u1(_.language))}),_.debugMode&&_.closed&&o_("span",{className:"cortex-media-block__actions",children:[_.onToggleSource&&i("button",{type:"button",className:"cortex-media-block__action","aria-pressed":_.sourceShown,onClick:_.onToggleSource,children:$("translate_media_source")}),i(g,{value:_.source})]})]})}function E8(_){let{debugMode:$,t:X}=L();return i("div",{className:"cortex-media-block__body",children:o_("p",{className:"cortex-media-block__error",children:[_.cutOff?X("translate_media_cut_off"):X("translate_media_failed"),!_.cutOff&&$&&` ${_.reason}`]})})}function d6(_){let{language:$,source:X,closed:Y,streaming:Q}=_,{config:N,debugMode:Z,scheme:G}=L(),J=k8(null),[z,V]=l6(),[W,U]=l6(!1);M8(()=>{V(void 0);let P=J.current;if(!Y||!G||!P)return;return l1(P,{language:$,source:X,context:{scheme:G},overrides:N.mediaRenderers,onError:V})},[$,X,Y,G,N.mediaRenderers]);let B=!Y&&!Q,F=B||Boolean(z);return o_("div",{className:"cortex-media-block",children:[i(A8,{language:$,source:X,pending:!Y&&Q,closed:Y,debugMode:Z,sourceShown:W,onToggleSource:F?void 0:()=>U((P)=>!P)}),F&&i(E8,{cutOff:B,reason:z}),i("div",{ref:J,hidden:F,className:q("cortex-media-block__body",`cortex-media-block__body--${$}`)}),Z&&(F||W)&&i("pre",{className:"cortex-media-block__source",children:X})]})}import{jsx as b_}from"react/jsx-runtime";function i6(_){let{role:$,textPart:X,streaming:Y=!1,attachments:Q=[]}=_,{config:N}=L(),Z=$==="assistant"&&Y?"":X.content,[G,J]=y8({text:Z,fading:[]}),z=z0(Z),V=z0(null),W=z0(!0);n6(()=>{function F(O,P){z.current=O,J((D)=>D.text===O&&!D.fading.length&&!P.length?D:{text:O,fading:P})}if($!=="assistant"||!Y){V.current?.destroy(),V.current=null,F(X.content,[]),W.current=!1;return}if(!V.current)V.current=new t(F),V.current.seed(z.current);if(W.current){W.current=!1,V.current.seed(X.content);return}V.current.update(X.content,!1)},[$,Y,X]),n6(()=>()=>{V.current?.destroy(),V.current=null},[]);let U=R8(()=>{let F=$==="assistant"?j1(G.text,p1(N.mediaRenderers)):[{kind:"markdown",text:G.text}];return F.map((O,P)=>O.kind==="markdown"?{...O,html:{__html:f1(O.text,P===F.length-1?G.fading:[])}}:O)},[$,G,N.mediaRenderers]),B=Y||G.text!==X.content;return b_("div",{className:q("cortex-text-part",$==="assistant"&&"cortex-text-part--assistant",$==="user"&&"cortex-text-part--user"),children:b_("div",{className:q("cortex-text-bubble",$==="assistant"&&"cortex-text-bubble--assistant",$==="user"&&"cortex-text-bubble--user"),children:U.map((F,O)=>{switch(F.kind){case"markdown":return b_("div",{dangerouslySetInnerHTML:F.html},O);case"media":return b_(d6,{...F,streaming:B},O);case"attachment":return b_(p6,{id:F.id,alt:F.alt,attachment:Q.find((P)=>P.id.toLowerCase()===F.id)},O)}})})})}import{jsx as f,jsxs as __}from"react/jsx-runtime";function r6({toolCallPart:_}){let{t:$}=L(),{state:X,approval:Y}=_,Q=_.output,N=z1(_);if(X==="complete")return __("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--success",children:[__("div",{className:"cortex-debug-tool__section-bar",children:[f("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--success",children:$("translate_output")}),f("span",{className:"cortex-debug-tool__section-lang",children:"json"}),f(g,{value:N})]}),f("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:f(s,{data:Q,expandDepth:2})})]});if(X==="error")return __("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--error",children:[__("div",{className:"cortex-debug-tool__section-bar",children:[f("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--error",children:$("translate_error")}),f(g,{value:N})]}),f("pre",{dir:"ltr",className:"cortex-debug-tool__error-pre",children:N})]});if(X==="approval-requested")return __("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[__("div",{className:"cortex-debug-tool__section-bar",children:[f("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:$("translate_approval_requested")}),f("span",{className:"cortex-debug-tool__section-lang",children:Y?.id})]}),f("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:$("translate_waiting_for_approval")})]});if(X==="approval-responded")return __("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[__("div",{className:"cortex-debug-tool__section-bar",children:[f("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:$("translate_approval_response")}),f("span",{className:"cortex-debug-tool__section-lang",children:Y?.id})]}),f("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:$(Y?.approved?"translate_tool_approved":"translate_tool_response_received")})]});return null}import{jsx as I8,jsxs as w8}from"react/jsx-runtime";function o6({toolCallPart:_}){let{t:$}=L(),X=J1(_);return w8("span",{className:q("cortex-debug-tool__state",X.modifier&&`cortex-debug-tool__state--${X.modifier}`),children:[X.pulse&&I8("span",{className:q("cortex-debug-tool__pulse",X.pulse==="violet"&&"cortex-debug-tool__pulse--violet")}),$(X.labelKey)]})}import{jsx as T,jsxs as r}from"react/jsx-runtime";function a6({toolCallPart:_}){let{t:$}=L(),{codeSnippets:X,remainingInput:Y,remainingInputText:Q}=V1(_.input);return r("details",{className:"cortex-debug-tool","data-state":_.state,children:[T("summary",{className:"cortex-debug-tool__summary",children:r("div",{className:"cortex-debug-tool__header",children:[r("div",{className:"cortex-debug-tool__meta",children:[T("div",{className:"cortex-debug-tool__title-row",children:T("span",{className:"cortex-debug-tool__name",title:_.name,children:_.name})}),T("div",{className:"cortex-debug-tool__id-row",children:T("span",{className:"cortex-debug-tool__id",children:_.id})})]}),r("div",{className:"cortex-debug-tool__actions",children:[T(o6,{toolCallPart:_}),T("svg",{className:"cortex-debug-tool__chevron",width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:T("path",{d:b.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),r("div",{className:"cortex-debug-tool__body",children:[X.map((N)=>r("div",{className:"cortex-debug-tool__section",children:[r("div",{className:"cortex-debug-tool__section-bar",children:[T("span",{className:"cortex-debug-tool__section-label",children:N.key}),T("span",{className:"cortex-debug-tool__section-lang",children:N.lang}),T(g,{value:N.value})]}),T("pre",{dir:"ltr",className:"cortex-debug-tool__pre",children:T("code",{className:"hljs",dangerouslySetInnerHTML:{__html:n1(N.value,N.lang)}})})]},N.key)),!!Y&&r("div",{className:"cortex-debug-tool__section",children:[r("div",{className:"cortex-debug-tool__section-bar",children:[T("span",{className:"cortex-debug-tool__section-label",children:$("translate_input")}),T("span",{className:"cortex-debug-tool__section-lang",children:"json"}),T(g,{value:Q})]}),T("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:T(s,{data:Y,expandDepth:2})})]}),T(r6,{toolCallPart:_})]})]})}import{useEffect as C8,useRef as b8,useState as t6}from"react";import{jsx as S_,jsxs as s6}from"react/jsx-runtime";function Q_({activity:_,className:$}){let{t:X}=L(),Y=W1(_),[Q,N]=t6(0),[Z,G]=t6("idle"),J=b8(Y.length);return J.current=Y.length,C8(()=>{let z,V;function W(){z=setTimeout(()=>{G("exiting"),z=setTimeout(()=>{N((U)=>(U+1)%J.current),G("enter-start"),V=requestAnimationFrame(()=>{G("entering"),z=setTimeout(()=>{G("idle"),W()},300)})},300)},2000)}return W(),()=>{if(z)clearTimeout(z);if(V)cancelAnimationFrame(V)}},[]),s6("div",{className:q("cortex-subtle-activity",$),children:[s6("div",{className:"cortex-subtle-activity__dots",children:[S_("span",{className:"cortex-subtle-activity__dot"}),S_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d1"}),S_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d2"})]}),S_("div",{className:"cortex-subtle-activity__label-mask",children:S_("span",{className:q("cortex-subtle-activity__label",`cortex-subtle-activity__label--${Z}`),children:X(Y[Q])})})]})}import{useEffect as Y2,useRef as V0,useState as X2}from"react";import{useEffect as e6,useRef as a_,useState as _2}from"react";import{jsx as C,jsxs as x}from"react/jsx-runtime";function $2({toolCallPart:_,setOutput:$}){let{t:X}=L(),{state:Y,id:Q,input:N}=_;if(Y==="complete"||Y==="error"){let Z=w1(_.output);return Z?C(T8,{position:Z}):x("div",{className:"cortex-tool-pill",children:[C("span",{className:"cortex-tool-pill__icon",children:C("svg",{className:q("cortex-tool-pill__svg cortex-tool-pill__svg--visible",Y==="error"&&"cortex-tool-pill__svg--error"),viewBox:"0 0 20 20",fill:"none",children:C("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}),C("span",{className:"cortex-tool-pill__title",children:X("translate_location_not_shared")})]})}if(Y!=="input-complete")return null;return C(S8,{center:I1(N),submit:$},Q)}function S8({center:_,submit:$}){let{t:X}=L(),Y=a_(null),Q=a_(void 0),[N,Z]=_2(j_),G=a_({center:_,submit:$});G.current={center:_,submit:$},e6(()=>{let z=Y.current;if(!z)return;let V=R1(z,{center:G.current.center,onState:Z,submit:(W)=>G.current.submit(W)});return Q.current=V,V.start(),()=>{if(V.dispose(),Q.current===V)Q.current=void 0}},[]);let J=C1(N);return x("div",{className:"cortex-location-input",children:[x("div",{className:"cortex-location-input__map",children:[C("div",{className:"cortex-location-input__canvas",ref:Y}),C("button",{type:"button",className:"cortex-location-input__locate","aria-label":X("translate_location_locate"),title:X("translate_location_locate"),disabled:N.locating||N.submitting,onClick:()=>Q.current?.locate(),children:C(v8,{})})]}),x("div",{className:"cortex-location-input__foot",children:[N.position&&!N.deliveryFailed?C("span",{className:"cortex-location-input__coords",children:g_(N.position)}):x("span",{className:q("cortex-location-input__hint",J.failed&&"cortex-location-input__hint--failed"),children:[N.locating&&C("span",{className:"cortex-location-input__spinner"}),X(J.key)]}),x("span",{className:"cortex-location-input__actions",children:[C("button",{type:"button",className:"cortex-location-input__skip",disabled:N.submitting,onClick:()=>Q.current?.cancel(),children:X("translate_location_skip")}),C("button",{type:"button",className:"cortex-location-input__send",disabled:!N.position||N.submitting,onClick:()=>Q.current?.confirm(),children:X("translate_location_send")})]})]})]})}function T8({position:_}){let{t:$}=L(),X=a_(null),[Y,Q]=_2(!1),{lat:N,lng:Z}=_;return e6(()=>{let G=X.current;if(!G)return;return Q(!1),y1(G,{lat:N,lng:Z},()=>Q(!0))},[N,Z]),x("div",{className:"cortex-location-input cortex-location-input--settled",children:[x("div",{className:"cortex-location-input__map cortex-location-input__map--still",children:[C("div",{className:"cortex-location-input__canvas",ref:X,hidden:Y}),Y&&C("span",{className:"cortex-location-input__still-failed",children:$("translate_location_map_failed")})]}),x("div",{className:"cortex-location-input__body",children:[x("span",{className:"cortex-location-input__title",children:[C("svg",{viewBox:"0 0 20 20",fill:"none",children:C("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),$("translate_location_shared")]}),C("span",{className:"cortex-location-input__coords",children:g_(_)})]})]})}function v8(){return x("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:[C("circle",{cx:"10",cy:"10",r:"5.5"}),C("circle",{cx:"10",cy:"10",r:"1.6",fill:"currentColor",stroke:"none"}),C("path",{d:"M10 1.5v3M10 15.5v3M1.5 10h3M15.5 10h3"})]})}import{jsx as I,jsxs as F_}from"react/jsx-runtime";var f8=new Map([[f_,$2]]);function Q2({message:_,toolCallPart:$,agentWorking:X}){let{config:Y,addToolResult:Q}=L(),N=$.state==="input-complete"&&!X,Z=$.state==="approval-requested"&&!X,G=Y.toolComponents?.[$.name]??(N||v($.state)?f8.get($.name):void 0);return I("div",{className:"cortex-tool-call-animated",children:G?I(G,{toolCallPart:$,message:_,setOutput:(J)=>Q($.id,$.name,J)}):N?I(j8,{toolCallPart:$}):I(N2,{toolCallPart:$,asking:Z})})}function j8({toolCallPart:_}){let{api:$,t:X,addToolResult:Y,selectedThread:Q,config:N}=L(),Z=Q?.id,[G,J]=X2({phase:"initiating"}),[z]=X2(N.trustSameOriginEmbeds),V=V0(void 0),W=V0({api:$,addToolResult:Y,toolName:_.name});if(W.current={api:$,addToolResult:Y,toolName:_.name},Y2(()=>{if(!Z)return;let B=A1({initiate:()=>W.current.api.initiateToolCall(Z,_.id),onState:J,submit:(O)=>W.current.addToolResult(_.id,W.current.toolName,O)});V.current=B,B.start();let F=(O)=>B.handleMessage(O);return window.addEventListener("message",F),()=>{if(window.removeEventListener("message",F),B.dispose(),V.current===B)V.current=void 0}},[_.id,Z]),!Z||G.phase==="unavailable"||G.phase==="settling")return I(N2,{toolCallPart:_});let U=F_("div",{className:"cortex-client-tool-embed",children:[F_("div",{className:"cortex-client-tool-embed__bar",children:[I("span",{children:X("translate_client_tool_title")}),I("button",{type:"button",className:"cortex-client-tool-embed__cancel",onClick:()=>V.current?.cancel(),children:X("translate_client_tool_cancel")})]}),G.phase==="embedded"?I("iframe",{className:"cortex-client-tool-embed__frame",src:G.embedUrl,sandbox:P1(G.embedUrl,window.location.origin,z),title:X("translate_client_tool_title"),ref:(B)=>V.current?.setSource(B?.contentWindow),onLoad:(B)=>{if(!M1(G.embedUrl,window.location.origin,z)&&k1(B.currentTarget,window.location.origin))V.current?.terminate()}}):G.phase==="error"?F_("div",{className:"cortex-client-tool-embed__status",children:[I("span",{children:X("translate_client_tool_failed")}),I("button",{type:"button",className:"cortex-client-tool-embed__retry",onClick:()=>void V.current?.start(),children:X("translate_client_tool_retry")})]}):I("div",{className:"cortex-client-tool-embed__status",children:X("translate_client_tool_loading")})]});return G.phase==="embedded"&&G.surface==="modal"?I(g8,{label:X("translate_client_tool_title"),onCancel:()=>V.current?.cancel(),children:U}):U}function g8({label:_,onCancel:$,children:X}){let Y=V0(null);return Y2(()=>{let Q=Y.current;return Q?.showModal(),()=>Q?.close()},[]),I("dialog",{ref:Y,className:"cortex-client-tool-embed-dialog","aria-label":_,onCancel:(Q)=>{Q.preventDefault(),$()},children:X})}function N2({toolCallPart:_,asking:$=!1}){let{t:X,locale:Y,respondToApproval:Q}=L(),{state:N,active:Z,gated:G,titleKey:J,statement:z,rowCount:V}=P_(_),W=A0(_);return F_("div",{className:q("cortex-tool-pill",G&&"cortex-tool-pill--gated",$&&"cortex-tool-pill--asking"),children:[F_("span",{className:"cortex-tool-pill__icon",children:[$&&I("span",{className:"cortex-tool-pill__dot"}),I("span",{className:q("cortex-tool-pill__spinner",Z&&"cortex-tool-pill__spinner--visible")}),I("svg",{className:q("cortex-tool-pill__svg","cortex-tool-pill__svg--check",N==="complete"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:I("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),I("svg",{className:q("cortex-tool-pill__svg","cortex-tool-pill__svg--error",N==="error"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:I("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})]}),I("span",{className:q("cortex-tool-pill__title",N==="error"&&"cortex-tool-pill__title--error",N==="starting"&&z&&"cortex-tool-pill__title--pending"),children:$?K1(_,Y)??X("translate_approval_prompt"):z??X(J)}),V!==void 0&&I("span",{className:"cortex-tool-pill__meta",children:X("translate_rows_read",{count:V})}),$&&F_("span",{className:"cortex-tool-pill__actions",children:[I("button",{type:"button",className:"cortex-tool-pill__action cortex-tool-pill__action--approve",onClick:()=>void Q(W,!0),children:X("translate_approve")}),I("button",{type:"button",className:"cortex-tool-pill__action",onClick:()=>void Q(W,!1),children:X("translate_deny")})]})]})}import{jsx as K0}from"react/jsx-runtime";function Z2({message:_,toolCallPart:$,agentWorking:X}){if(!v($.state)&&!P_($).statement){if($.name==="queryGraph")return K0(Q_,{activity:"graph"});if($.name==="executeCode")return K0(Q_,{activity:"code"})}return K0(Q2,{toolCallPart:$,message:_,agentWorking:X})}import{jsx as q_,jsxs as m8}from"react/jsx-runtime";function G2(_){let{message:$,part:X,debugMode:Y,animate:Q,streaming:N,agentWorking:Z,attachments:G}=_,{t:J}=L();function z(){switch(X.type){case"text":return q_(i6,{textPart:X,role:$.role,streaming:N,attachments:G});case"thinking":return Y?q_(c6,{reasoningPart:X,streaming:N}):q_(Q_,{activity:"reasoning",className:"cortex-reasoning-animated"});case"tool-call":return Y?q_(a6,{toolCallPart:X}):q_(Z2,{toolCallPart:X,message:$,agentWorking:Z});default:return m8("p",{className:"cortex-unhandled-type",children:[J("translate_unhandled_type")," ",X.type]})}}return q_("div",{className:q("cortex-message-part",Q&&"cortex-message-part--animated",_.folded&&"cortex-message-part--folded"),"data-cortex-frontier":_.frontier?"":void 0,children:z()})}import{jsx as o,jsxs as W0}from"react/jsx-runtime";function h8({isUser:_,clipboardText:$,createdAt:X}){let{locale:Y}=L();return W0("div",{className:q("cortex-message-actions",_&&"cortex-message-actions--user"),children:[$&&o(g,{value:$}),X&&o("time",{className:"cortex-message-actions__time",dateTime:X,children:l(X,Y)})]})}function c8({count:_,animate:$,onOpen:X}){let{t:Y}=L();return o("button",{type:"button",className:q("cortex-tool-fold",$&&"cortex-message-part--animated"),onClick:X,children:Y(y_(_,"translate_one_more_step","translate_n_more_steps"),{count:_})})}function J2(_){let{message:$,parts:X,metadata:Y,debugMode:Q,animate:N,isStreaming:Z,agentWorking:G,closesTurn:J,fold:z,onOpenRun:V,frontier:W}=_,U=$.role==="assistant",B=$.role==="user",F=Z?X.length-1:-1,O=Y?.attachments??[],P=X.filter((R)=>z?.get(R)?.kind!=="hidden"),D=P.filter((R)=>R.type==="text").at(-1),H=D?X.indexOf(D):-1,K=(B||U)&&!Z&&H>=0,M=D!==P.at(-1)?H:-1,k=K&&o(h8,{isUser:B,clipboardText:D1(X),createdAt:Y?.createdAt});return W0("div",{className:"cortex-message-parts",children:[X.map((R,p)=>{let G_=z?.get(R);return W0(x8,{children:[o(G2,{part:R,message:$,debugMode:Q,animate:N,streaming:p===F,agentWorking:G,attachments:O,frontier:R===W,folded:G_?.kind==="hidden"}),G_?.kind==="more"&&o(c8,{count:G_.count,animate:N,onOpen:()=>V(G_.runId)}),p===M&&k]},$.parts.indexOf(R))}),O.length>0&&o(S6,{attachments:O,isUser:B}),Y?.isAborted&&o(C6,{}),M===-1&&k,Q&&Y&&J&&o(h6,{messageId:$.id,isAssistant:U,metadata:Y})]})}import{jsx as N_,jsxs as D0}from"react/jsx-runtime";function z2({firing:_,debugMode:$}){let{t:X,locale:Y}=L();return D0("div",{className:q("cortex-trigger-block",$&&"cortex-trigger-block--debug"),children:[D0("div",{className:"cortex-trigger-block__head",children:[N_("svg",{className:"cortex-trigger-block__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:N_("path",{d:"M6.75 1 2.5 6.75h3l-.25 4.25L9.5 5.25h-3z",fill:"currentColor"})}),$&&N_("span",{children:X("translate_trigger_fired")}),N_("span",{className:"cortex-trigger-block__name",children:_.name}),N_("time",{className:"cortex-trigger-block__time",dateTime:_.firedAt,children:l(_.firedAt,Y)})]}),$&&D0("details",{className:"cortex-trigger-block__payload",children:[N_("summary",{children:X("translate_trigger_payload")}),N_(s,{data:_.payload,expandDepth:2})]})]})}import{jsx as T_}from"react/jsx-runtime";var V2=u8(function($){let{message:X,metadata:Y,isStreaming:Q,agentWorking:N,closesTurn:Z,debugMode:G,animate:J,fold:z,onOpenRun:V,workingTurn:W,frontier:U}=$,B=J_(X.parts,{debugMode:G,isStreaming:Q});if(Y?.trigger)return T_("div",{className:"cortex-message",children:T_(z2,{firing:Y.trigger,debugMode:G})});if(B.length===0&&!Y?.attachments?.length)return T_("div",{className:"cortex-message"});return T_("div",{className:q("cortex-message",W&&"cortex-message--working-turn"),children:T_(J2,{message:X,parts:B,metadata:Y,debugMode:G,animate:J,isStreaming:Q,agentWorking:N,closesTurn:Z,fold:z,onOpenRun:V,frontier:U})})});import{jsx as t_}from"react/jsx-runtime";var p8=[{role:"user",lines:[13,9]},{role:"assistant",lines:[16,18,12]},{role:"user",lines:[11]},{role:"assistant",lines:[14,15]}];function K2(){return t_("div",{className:"cortex-widget__messages-skeleton",children:p8.map((_,$)=>t_("div",{className:`cortex-widget__msg-skel cortex-widget__msg-skel--${_.role}`,children:t_("div",{className:`cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--${_.role}`,children:_.lines.map((X)=>t_("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:`${X}rem`}},X))})},$))})}import{jsx as h,jsxs as s_,Fragment as o8}from"react/jsx-runtime";function d8(_){let $=Z_(null),X=Z_(null),Y=Z_(!0),Q=Z_(!0),N=Z_(!1),Z=v_(()=>{if(N.current)return;N.current=!0,queueMicrotask(()=>{N.current=!1;let V=$.current;if(!V)return;c_(V),Q.current=!0,Y.current=!1})},[]);H0(()=>{let V=X.current;if(!_||!$.current||!V)return;if(Z(),typeof ResizeObserver>"u")return;let W=0,U=new ResizeObserver(([B])=>{let F=B?.contentRect.height??0,O=F>W;if(W=F,O&&(Y.current||Q.current))Z()});return U.observe(V),()=>U.disconnect()},[_,Z]);let G=v_(()=>{Y.current=!0},[]),J=v_(()=>{if(Y.current)Z()},[Z]);function z(){let V=$.current;if(V)Q.current=X0(V)<100}return{containerRef:$,contentRef:X,onScroll:z,pin:G,settlePinned:J}}function n8({pin:_,settlePinned:$,contentRef:X},Y,Q){let[N,Z]=F0(!1);H0(()=>{Z(!1),_(),queueMicrotask(()=>Z(!0))},[Y,_]);let G=Q[Q.length-1],J=G?.role==="user"?G.id:void 0,z=J?G?.parts.find((V)=>V.type==="text")?.content:void 0;return B0(()=>{if(!J)return;_();let V=X.current;if(V&&z!==void 0)$0(V,z)},[J,z,_,X]),H0(()=>{$()},[Q,$]),N}function i8(_,$,X,Y){let[Q,N]=F0(new Set),Z=v_((z)=>N((V)=>new Set(V).add(z)),[]),[G]=F0(F1);return{folds:l8(()=>G(_,{agentWorking:$,debugMode:X,opened:Q,foldable:Y}),[G,_,$,X,Q,Y]),openRun:Z}}function r8({working:_}){let $=Z_(null),X=Z_(void 0);return B0(()=>{let Y=$.current;if(!Y)return;let Q=Y0(Y);return X.current=Q,()=>{Q.dispose(),X.current=void 0}},[]),B0(()=>X.current?.sync(_)),s_("div",{ref:$,className:"cortex-working-avatar","aria-hidden":"true",children:[s_("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h("path",{d:"M9.94 15.5a2 2 0 0 0-1.44-1.44l-6.13-1.58a.5.5 0 0 1 0-.96L8.5 9.94A2 2 0 0 0 9.94 8.5l1.58-6.14a.5.5 0 0 1 .96 0l1.58 6.14a2 2 0 0 0 1.44 1.44l6.14 1.58a.5.5 0 0 1 0 .96l-6.14 1.58a2 2 0 0 0-1.44 1.44l-1.58 6.14a.5.5 0 0 1-.96 0z"}),h("path",{d:"M20 3v4M22 5h-4M4 17v2M5 18H3"})]}),h("span",{className:"cortex-working-avatar__ring"})]})}function W2(_){let{config:$,selectedThread:X}=L(),{messages:Y,isAgentWorking:Q,isLoadingMessages:N,hasPendingToolCalls:Z}=l_(),{capabilities:G,composerRef:J,debugMode:z}=_,V=!N||Q,W=d8(V),U=n8(W,X?.id,Y),B=Q?O_(Y)?.id:void 0,F=$.toolComponents,O=v_((k)=>H1(k,F),[F]),{folds:P,openRun:D}=i8(Y,Q,z,O),H=Y.map((k)=>k.role).lastIndexOf("user"),K=Q&&!z,M=K?B1(Y,{foldable:O}):void 0;return s_(o8,{children:[!V?h(K2,{}):h("div",{className:_.className,children:h("div",{ref:W.containerRef,className:"cortex-message-list",onScroll:W.onScroll,children:s_("div",{ref:W.contentRef,className:"cortex-message-list__content",children:[Y.map((k,R)=>h(V2,{message:k,metadata:k.metadata,isStreaming:k.id===B,agentWorking:Q,fold:P.get(k.id),onOpenRun:D,closesTurn:k.role==="assistant"&&Y[R+1]?.role!=="assistant",debugMode:z,animate:U,workingTurn:K&&R>H,frontier:k.id===B?M:void 0},k.id)),Q&&!M&&h("div",{className:"cortex-working-thinking","data-cortex-frontier":"",children:h(Q_,{activity:"reasoning"})}),h(r8,{working:Q},X?.id)]})})}),!Z&&h(d_,{capabilities:G,composerRef:J})]})}import{jsx as e_,jsxs as a8}from"react/jsx-runtime";function D2(_){let{debugMode:$,selectedThread:X}=L(),{screens:Y}=_;return a8("div",{className:q("cortex-widget__screen",Y.screen==="chat"&&"cortex-widget__screen--active",Y.screen!=="chat"&&"cortex-widget__screen--right"),children:[e_(U6,{onToggleSidebar:Y.toggleSidebar,onToggleDebug:_.onToggleDebug,onOpenHistory:Y.openHistory}),X?e_(W2,{className:"cortex-widget__messages",debugMode:$,capabilities:_.capabilities,composerRef:_.composerRef}):e_(I6,{onThreadSelected:_.onThreadSelected}),e_("div",{className:"cortex-widget__sidebar-backdrop",onClick:Y.closeSidebar})]})}import{useState as $4}from"react";import{useEffect as q0,useRef as q2,useState as U0}from"react";import{useChat as _4}from"@tanstack/ai-react";import{useEffect as t8,useLayoutEffect as s8,useState as e8}from"react";function H2(_,{sessionRef:$,pendingSendRef:X}){let[Y]=e8(_);return s8(()=>{return $.current=Y,()=>{if($.current===Y)$.current=void 0}},[Y,$]),t8(()=>{if(!X.current.length)return;let Q=setTimeout(()=>{let N=X.current;X.current=[],(async()=>{for(let{prompt:Z,attachments:G}of N)await Y.send(Z,G)})()});return()=>clearTimeout(Q)},[Y,X]),Y}import{useRef as B2}from"react";function F2(_){let $=B2(_);$.current=_;let X=B2(Promise.resolve(void 0));async function Y(Q){let N=$.current;if(!N.isAlive()||Q!==N.threadId)return;return U1({api:N.api,threadId:Q,isStale:()=>!$.current.isAlive(),isStreaming:()=>$.current.isStreaming(),setMessages:(Z)=>$.current.setMessages(Z)})}return function(N){return X.current=X.current.then(()=>Y(N)),X.current}}function U2(_){let{thread:$,api:X}=_,Y=q2(!0),[Q,N]=U0(!1),Z=q2(null),G=F2({api:X,threadId:$.id,isAlive:()=>Y.current,isStreaming:()=>Z.current.chat.isLoading,setMessages:(H)=>Z.current.chat.setMessages(H)}),[J]=U0(()=>Q0({threadId:$.id,isAlive:()=>Y.current,onToolCall:()=>Z.current.props.configRef.current.hooks?.onToolCall,deliver:(H)=>Z.current.chat.addToolResult(H),setRunning:(H)=>Z.current.props.setRunning($.id,H),reloadThreads:()=>Z.current.props.reloadThreads(),refreshMessages:()=>G($.id),onTurnFinished:()=>Z.current.props.onTurnFinished(),onSendFailed:()=>Z.current.props.onSendFailed()})),[z]=U0(()=>q1({api:X,thread:{id:$.id,isRunning:$.isRunning},mode:_.mode,localMessages:()=>Z.current.chat.messages,onHydrated:(H)=>{if(Y.current)J.hydrated(H,$.isRunning)},onTranscriptCarried:(H)=>{if(Y.current)J.transcriptCarried(H)},setLoadingMessages:(H)=>{if(Y.current)N(H)}})),V=_4({threadId:$.id,persistence:!0,initialMessages:_.initialMessages,connection:z,onChunk:()=>{if(Y.current)J.chunkArrived()},onError:()=>{if(Y.current)J.streamFailed()}});Z.current={chat:V,props:_};async function W(H,K){J.sendStarted();let M={id:M_(),role:"user",parts:[{type:"text",content:H}],metadata:{createdAt:new Date().toISOString(),attachments:K}};await Z.current.chat.append(M)}async function U(){if(!Z.current.chat.isLoading)return;let{aborted:H}=await X.abortStream($.id).catch(()=>({aborted:!1}));if(!Y.current)return;if(H)J.abortConfirmed();Z.current.chat.stop()}function B(H,K,M){return Z.current.chat.addToolResult({toolCallId:H,tool:K,output:M}).catch((k)=>{throw G($.id),k})}function F(H,K){return E1(Z.current.chat,H,K)}function O(H){if(Z.current.chat.isLoading)return;if(H.isRunning){Z.current.props.remount(H,Z.current.chat.messages);return}G(H.id)}q0(()=>{return Y.current=!0,()=>{Y.current=!1}},[]),H2(()=>({threadId:$.id,send:W,abort:U,addToolResult:B,respondToApproval:F,reattach:O,transcriptUpdated:(H,K)=>{if(H===$.id)J.transcriptUpdated(K)}}),{sessionRef:_.sessionRef,pendingSendRef:_.pendingSendRef});let{messages:P,isLoading:D}=V;return q0(()=>{J.loadingChanged(D,()=>Z.current.chat.messages)},[J,D]),q0(()=>{Z.current.props.publish({messages:P,isAgentWorking:D,isLoadingMessages:Q,hasPendingToolCalls:!D&&a(P).length>0})},[P,D,Q]),null}import{jsx as L2,jsxs as X4}from"react/jsx-runtime";function O2({selection:_,threads:$,children:X,...Y}){let{session:Q}=_,[N,Z]=$4();if(!Q)return L2(p_.Provider,{value:u_,children:X});let G=`${Q.thread.id}:${Q.epoch}`,J=N&&(N.key===G||Q.mode==="reload")?N.value:u_;return X4(p_.Provider,{value:J,children:[L2(U2,{thread:Q.thread,mode:Q.mode,initialMessages:Q.initialMessages,setRunning:$.setRunning,reloadThreads:$.reload,remount:_.remount,publish:(z)=>Z({key:G,value:z}),...Y},G),X]})}import{useSyncExternalStore as Y4}from"react";function P2(_){return Y4(($)=>{let X=window.matchMedia(_);return X.addEventListener("change",$),()=>X.removeEventListener("change",$)},()=>window.matchMedia(_).matches,()=>!1)}import{jsx as E,jsxs as c,Fragment as Q4}from"react/jsx-runtime";function M2(_){let{locale:$,t:X,threads:Y,selectedThread:Q,deleteThread:N}=L(),Z=Y?.length??0;return c("div",{className:_.className,"aria-hidden":_.hidden||void 0,inert:_.hidden||void 0,children:[c("div",{className:"cortex-widget__threads-header",children:[E("button",{type:"button",onClick:()=>_.onBackRequested(),"aria-label":X("translate_back"),className:"cortex-widget__back-btn",children:E("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",className:"cortex-widget__back-icon",children:E("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("div",{children:[E("h2",{className:"cortex-widget__threads-title",children:X("translate_history")}),E("p",{className:"cortex-widget__threads-count",children:X(y_(Z,"translate_one_conversation","translate_n_conversations"),{count:Z})})]}),c("button",{onClick:()=>_.onNewChatRequested(),className:"cortex-widget__new-chat-btn",children:[E("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:E("path",{d:"M8 3v10M3 8h10",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})}),X("translate_new")]})]}),E("div",{className:"cortex-widget__threads-list",children:Y===void 0?[1,2,3,4].map((G)=>c("div",{className:"cortex-widget__thread-skeleton",children:[E("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-icon"}),E("div",{className:"cortex-widget__thread-skeleton-lines",children:E("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-line",style:{width:`${40+G*12}%`}})})]},G)):c(Q4,{children:[Y.map((G)=>{let J=G.id===Q?.id,z=l(G.updatedAt,$);return c("button",{onClick:()=>_.onThreadSelected(G),className:q("cortex-widget__thread-item",J&&"cortex-widget__thread-item--active"),children:[E("div",{className:q("cortex-widget__thread-icon",J&&"cortex-widget__thread-icon--active"),children:E("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:E("path",{d:b.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("div",{className:"cortex-widget__thread-info",children:[c("div",{className:"cortex-widget__thread-title-row",children:[E("p",{className:q("cortex-widget__thread-title",J&&"cortex-widget__thread-title--active"),children:G.title??X("translate_untitled")}),G.isRunning&&c("span",{className:q("cortex-widget__thread-running",J&&"cortex-widget__thread-running--active"),children:[E("span",{className:"cortex-widget__thread-running-dot"}),X("translate_running")]})]}),z&&E("p",{className:"cortex-widget__thread-time",children:z})]}),E("span",{role:"button",tabIndex:0,onClick:(V)=>{V.stopPropagation(),N(G.id)},onKeyDown:(V)=>{if(V.key!=="Enter"&&V.key!==" ")return;V.preventDefault(),V.stopPropagation(),N(G.id)},className:q("cortex-widget__thread-delete",J&&"cortex-widget__thread-delete--active"),children:E("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:E("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})})}),E("svg",{className:q("cortex-widget__thread-arrow",J&&"cortex-widget__thread-arrow--active"),width:"10",height:"10",viewBox:"0 0 16 16",fill:"none",children:E("path",{d:"M6 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},G.id)}),!Y.length&&c("div",{className:"cortex-widget__threads-empty",children:[E("div",{className:"cortex-widget__threads-empty-icon",children:E("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__threads-empty-svg",children:E("path",{d:b.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),E("p",{className:"cortex-widget__threads-empty-title",children:X("translate_no_threads_yet")}),E("p",{className:"cortex-widget__threads-empty-subtitle",children:X("translate_start_a_new_conversation")}),E("button",{onClick:()=>_.onNewChatRequested(),className:"cortex-widget__new-chat-btn cortex-widget__new-chat-btn--empty-state",children:X("translate_new_chat")})]})]})})]})}import{jsx as A2,jsxs as Z4}from"react/jsx-runtime";var N4="(max-width: 768px)";function k2(_){_.preventDefault()}function E2(_){let{screens:$}=_,X=P2(N4),Y=_.viewMode==="full"?X&&!$.sidebarOpen:$.screen!=="threads";return A2("div",{className:q("cortex-widget",_.className),"data-cortex-theme":_.theme,children:Z4("div",{className:q("cortex-widget__container",_.viewMode==="full"&&"cortex-widget__container--full",$.sidebarOpen&&"cortex-widget__container--sidebar-open"),onDragOver:k2,onDrop:k2,children:[A2(M2,{className:q("cortex-widget__screen",$.screen==="threads"&&"cortex-widget__screen--active",$.screen!=="threads"&&"cortex-widget__screen--left"),hidden:Y,onThreadSelected:_.onThreadSelected,onNewChatRequested:_.onNewChat,onBackRequested:$.closeHistory}),_.children]})})}import{jsx as $1}from"react/jsx-runtime";function J4({config:_,className:$}){let X=R2(_);X.current=_;let[Y]=_1(()=>G1(()=>X.current.transport)),Q=H6(Y),[N,Z]=_1(!1),[G,J]=_1();G4(()=>d1(_.theme,J),[_.theme]);let z=F6(),[V,W]=_1(0),U=Q6(Y,V),B=R2(null),F=V6({api:Y,threads:Q,getHooks:()=>X.current.hooks}),{sessionRef:O,selection:P,queue:D,send:H,pendingSendRef:K}=F,{selected:M,selectedRef:k}=P,R=W6({threads:Q,selectedRef:k,sessionRef:O,deselect:P.deselect,onReconnect:()=>W(($_)=>$_+1)});K6({getConfig:()=>X.current,onEvent:R.onEvent,onMount:()=>void Q.reload(),onReconnect:R.onReconnect});let p=i1(_.locale),G_={config:_,locale:p,t:($_,b2)=>r1(p,$_,b2),api:Y,debugMode:N,scheme:G,capabilities:U,threads:Q.threads,selectedThread:M,deleteThread:F.deleteThread,send:H,...D6(O),queue:D.value};function y2(){D.store.discardConsumed(),setTimeout(()=>B.current?.focusInput())}function I2(){D.store.restoreConsumed(k.current?.id)}function L0($_){F.openThread($_),z.showChat()}function w2(){P.deselect(),z.showChat()}function C2(){Z(($_)=>!$_)}return $1(N0.Provider,{value:G_,children:$1(E2,{className:$,theme:_.theme,viewMode:_.viewMode??"helper",screens:z,onThreadSelected:L0,onNewChat:w2,children:$1(O2,{selection:P,threads:Q,api:Y,configRef:X,sessionRef:O,pendingSendRef:K,onTurnFinished:y2,onSendFailed:I2,children:$1(D2,{screens:z,capabilities:U,composerRef:B,onToggleDebug:C2,onThreadSelected:L0})})})})}export{J4 as CortexChatWidget};
package/dist/styles.css CHANGED
@@ -333,71 +333,6 @@
333
333
  overflow: hidden;
334
334
  }
335
335
 
336
- @keyframes cortex-working-slide-in {
337
- from {
338
- opacity: 0;
339
- transform: translateY(6px);
340
- }
341
- to {
342
- opacity: 1;
343
- transform: translateY(0);
344
- }
345
- }
346
- @keyframes cortex-dot-wave {
347
- 0%, 60%, 100% {
348
- transform: translateY(0) scale(1);
349
- opacity: 0.45;
350
- }
351
- 30% {
352
- transform: translateY(-5px) scale(1.2);
353
- opacity: 1;
354
- }
355
- }
356
- @keyframes cortex-working-shimmer {
357
- 0% {
358
- background-position: -200% center;
359
- }
360
- 100% {
361
- background-position: 200% center;
362
- }
363
- }
364
- .cortex-widget__working {
365
- flex-shrink: 0;
366
- padding: 0.5rem 1rem;
367
- display: flex;
368
- align-items: center;
369
- gap: 0.5rem;
370
- animation: cortex-working-slide-in 0.25s ease-out both;
371
- }
372
-
373
- .cortex-widget__working-dots {
374
- display: flex;
375
- align-items: center;
376
- gap: 4px;
377
- }
378
-
379
- .cortex-working-dot {
380
- display: block;
381
- width: 6px;
382
- height: 6px;
383
- border-radius: 9999px;
384
- background: var(--cortex-color-success);
385
- animation: cortex-dot-wave 1.4s ease-in-out infinite;
386
- }
387
- .cortex-working-dot:nth-child(2) {
388
- animation-delay: 0.15s;
389
- }
390
- .cortex-working-dot:nth-child(3) {
391
- animation-delay: 0.3s;
392
- }
393
-
394
- .cortex-widget__working-text {
395
- font-size: 0.75rem;
396
- font-weight: 500;
397
- letter-spacing: 0.01em;
398
- color: var(--cortex-color-success);
399
- }
400
-
401
336
  .cortex-widget__container--full {
402
337
  display: flex;
403
338
  flex-direction: row;
@@ -444,9 +379,6 @@
444
379
  .cortex-widget__container--full .cortex-widget__input-area {
445
380
  padding: 0.75rem 2rem 1.25rem;
446
381
  }
447
- .cortex-widget__container--full .cortex-widget__working {
448
- padding: 0.5rem 2rem;
449
- }
450
382
  @media (max-width: 768px) {
451
383
  .cortex-widget__container--full > .cortex-widget__screen:first-child {
452
384
  position: fixed;
@@ -496,9 +428,6 @@
496
428
  .cortex-widget__container--full .cortex-widget__input-area {
497
429
  padding: 0.75rem;
498
430
  }
499
- .cortex-widget__container--full .cortex-widget__working {
500
- padding: 0.5rem 1rem;
501
- }
502
431
  }
503
432
 
504
433
  @media (max-width: 768px) {
@@ -1201,22 +1130,167 @@ cortex-llm-usage-chips {
1201
1130
  .cortex-message-list {
1202
1131
  height: 100%;
1203
1132
  overflow-y: auto;
1133
+ overflow-x: hidden;
1204
1134
  width: 100%;
1205
1135
  padding: 1rem;
1206
1136
  }
1207
1137
 
1208
1138
  .cortex-message-list__content {
1139
+ position: relative;
1209
1140
  display: flex;
1210
1141
  flex-direction: column;
1211
1142
  gap: 0.5rem;
1212
1143
  }
1144
+ .cortex-message-list__content--settling {
1145
+ animation: cortex-content-settle 420ms cubic-bezier(0.76, 0, 0.24, 1) both;
1146
+ }
1147
+
1148
+ @keyframes cortex-content-settle {
1149
+ from {
1150
+ translate: 0 var(--cortex-slide);
1151
+ }
1152
+ }
1153
+ .cortex-widget__screen > .cortex-send-flight {
1154
+ position: absolute;
1155
+ z-index: 2;
1156
+ margin: 0;
1157
+ max-width: none;
1158
+ pointer-events: none;
1159
+ animation: cortex-send-fade 80ms linear both, cortex-send-fly 420ms cubic-bezier(0.76, 0, 0.24, 1) both;
1160
+ }
1161
+
1162
+ @keyframes cortex-send-fade {
1163
+ from {
1164
+ opacity: 0;
1165
+ }
1166
+ }
1167
+ @keyframes cortex-send-fly {
1168
+ from {
1169
+ translate: var(--cortex-fly-x) var(--cortex-fly-y);
1170
+ }
1171
+ }
1172
+ .cortex-working-thinking {
1173
+ padding-inline-start: 2rem;
1174
+ --cortex-reveal-from: -1rem;
1175
+ --cortex-reveal-mask: linear-gradient(to right, #000 40%, rgb(0 0 0 / 0.35) 60%);
1176
+ --cortex-reveal-start: 100%;
1177
+ --cortex-reveal-end: 0%;
1178
+ animation: cortex-part-reveal 700ms cubic-bezier(0.22, 1, 0.36, 1) backwards;
1179
+ }
1180
+ [dir=rtl] .cortex-working-thinking {
1181
+ --cortex-reveal-from: 1rem;
1182
+ --cortex-reveal-mask: linear-gradient(to left, #000 40%, rgb(0 0 0 / 0.35) 60%);
1183
+ --cortex-reveal-start: 0%;
1184
+ --cortex-reveal-end: 100%;
1185
+ }
1186
+
1187
+ .cortex-working-avatar {
1188
+ position: absolute;
1189
+ top: 0;
1190
+ inset-inline-start: 0;
1191
+ z-index: 1;
1192
+ width: 1.5rem;
1193
+ height: 1.5rem;
1194
+ display: flex;
1195
+ align-items: center;
1196
+ justify-content: center;
1197
+ border-radius: 9999px;
1198
+ background: var(--cortex-color-accent);
1199
+ color: var(--cortex-color-primary-foreground);
1200
+ translate: 0 var(--cortex-avatar-y, 0);
1201
+ visibility: hidden;
1202
+ pointer-events: none;
1203
+ }
1204
+ .cortex-working-avatar svg {
1205
+ width: 0.875rem;
1206
+ height: 0.875rem;
1207
+ }
1208
+ .cortex-working-avatar--shown {
1209
+ visibility: visible;
1210
+ transition: translate 420ms cubic-bezier(0.76, 0, 0.24, 1);
1211
+ animation: cortex-avatar-in 700ms cubic-bezier(0.16, 1, 0.3, 1) both;
1212
+ }
1213
+ .cortex-working-avatar--leaving {
1214
+ animation: cortex-avatar-out 360ms cubic-bezier(0.5, 0, 0.75, 0) 120ms both;
1215
+ }
1216
+
1217
+ .cortex-working-avatar__ring {
1218
+ position: absolute;
1219
+ inset: -0.25rem;
1220
+ border-radius: 9999px;
1221
+ border: 1.5px solid transparent;
1222
+ border-top-color: var(--cortex-color-accent);
1223
+ border-right-color: color-mix(in oklab, var(--cortex-color-accent) 40%, transparent);
1224
+ }
1225
+ .cortex-working-avatar--shown .cortex-working-avatar__ring {
1226
+ animation: cortex-tool-spin 1s linear infinite;
1227
+ }
1228
+ .cortex-working-avatar--leaving .cortex-working-avatar__ring {
1229
+ animation: cortex-avatar-ring-out 220ms ease-out both;
1230
+ }
1213
1231
 
1232
+ @keyframes cortex-avatar-in {
1233
+ from {
1234
+ opacity: 0;
1235
+ transform: translateY(2.5rem) scale(0.7);
1236
+ }
1237
+ }
1238
+ @keyframes cortex-avatar-out {
1239
+ to {
1240
+ opacity: 0;
1241
+ transform: scale(0.4);
1242
+ }
1243
+ }
1244
+ @keyframes cortex-avatar-ring-out {
1245
+ to {
1246
+ opacity: 0;
1247
+ }
1248
+ }
1214
1249
  .cortex-message {
1215
1250
  min-width: 0;
1251
+ transition: margin-block-start 420ms cubic-bezier(0.76, 0, 0.24, 1);
1216
1252
  }
1217
1253
  .cortex-message:empty {
1218
1254
  display: none;
1219
1255
  }
1256
+ .cortex-message:has(.cortex-message-part--folded):not(:has(.cortex-message-part:not(.cortex-message-part--folded))) {
1257
+ margin-block-start: -0.5rem;
1258
+ transition-delay: 600ms;
1259
+ }
1260
+
1261
+ .cortex-text-bubble--assistant,
1262
+ .cortex-subtle-activity,
1263
+ .cortex-tool-pill:not(.cortex-tool-pill--gated),
1264
+ .cortex-tool-pill:not(.cortex-tool-pill--gated) .cortex-tool-pill__icon {
1265
+ transition: translate 420ms cubic-bezier(0.76, 0, 0.24, 1) 160ms;
1266
+ }
1267
+
1268
+ .cortex-message--working-turn .cortex-text-bubble--assistant,
1269
+ .cortex-message--working-turn .cortex-subtle-activity,
1270
+ .cortex-message--working-turn .cortex-tool-pill:not(.cortex-tool-pill--gated),
1271
+ .cortex-message--working-turn .cortex-tool-pill:not(.cortex-tool-pill--gated) .cortex-tool-pill__icon {
1272
+ transition-delay: 0s;
1273
+ }
1274
+ .cortex-message--working-turn .cortex-text-bubble--assistant,
1275
+ .cortex-message--working-turn .cortex-subtle-activity {
1276
+ translate: 2rem;
1277
+ }
1278
+ [dir=rtl] .cortex-message--working-turn .cortex-text-bubble--assistant,
1279
+ [dir=rtl] .cortex-message--working-turn .cortex-subtle-activity {
1280
+ translate: -2rem;
1281
+ }
1282
+ .cortex-message--working-turn .cortex-tool-pill:not(.cortex-tool-pill--gated) {
1283
+ translate: 0.875rem;
1284
+ }
1285
+ [dir=rtl] .cortex-message--working-turn .cortex-tool-pill:not(.cortex-tool-pill--gated) {
1286
+ translate: -0.875rem;
1287
+ }
1288
+ .cortex-message--working-turn .cortex-tool-pill:not(.cortex-tool-pill--gated) .cortex-tool-pill__icon {
1289
+ translate: -0.5rem;
1290
+ }
1291
+ [dir=rtl] .cortex-message--working-turn .cortex-tool-pill:not(.cortex-tool-pill--gated) .cortex-tool-pill__icon {
1292
+ translate: 0.5rem;
1293
+ }
1220
1294
 
1221
1295
  .cortex-message-parts {
1222
1296
  width: 100%;
@@ -1259,25 +1333,68 @@ cortex-llm-usage-chips {
1259
1333
  }
1260
1334
 
1261
1335
  .cortex-message-part {
1262
- display: block;
1336
+ display: grid;
1337
+ grid-template-columns: minmax(0, 1fr);
1338
+ grid-template-rows: 1fr;
1263
1339
  min-width: 0;
1340
+ transition: grid-template-rows 420ms cubic-bezier(0.76, 0, 0.24, 1), margin-block-end 420ms cubic-bezier(0.76, 0, 0.24, 1), opacity 300ms ease, visibility 0s, overflow 0s 420ms allow-discrete;
1341
+ }
1342
+ .cortex-message-part > * {
1343
+ min-height: 0;
1264
1344
  }
1265
1345
  .cortex-message-part:empty {
1266
1346
  display: none;
1267
1347
  }
1348
+ .cortex-message-part--folded {
1349
+ grid-template-rows: 0fr;
1350
+ margin-block-end: -0.5rem;
1351
+ opacity: 0;
1352
+ overflow: clip;
1353
+ visibility: hidden;
1354
+ transition-delay: 600ms, 600ms, 600ms, 1020ms, 0s;
1355
+ }
1356
+
1357
+ [data-cortex-frontier] .cortex-tool-pill__spinner {
1358
+ visibility: hidden;
1359
+ }
1360
+ [data-cortex-frontier] .cortex-subtle-activity__dots {
1361
+ display: none;
1362
+ }
1268
1363
 
1269
1364
  .cortex-message-part--animated {
1270
- animation: cortex-part-fade-in-up 0.2s cubic-bezier(0.34, 1.56, 0.64, 1) both;
1365
+ --cortex-reveal-from: -1rem;
1366
+ --cortex-reveal-mask: linear-gradient(to right, #000 40%, rgb(0 0 0 / 0.35) 60%);
1367
+ --cortex-reveal-start: 100%;
1368
+ --cortex-reveal-end: 0%;
1369
+ animation: cortex-part-reveal 700ms cubic-bezier(0.22, 1, 0.36, 1) backwards;
1370
+ }
1371
+ [dir=rtl] .cortex-message-part--animated {
1372
+ --cortex-reveal-from: 1rem;
1373
+ --cortex-reveal-mask: linear-gradient(to left, #000 40%, rgb(0 0 0 / 0.35) 60%);
1374
+ --cortex-reveal-start: 0%;
1375
+ --cortex-reveal-end: 100%;
1271
1376
  }
1272
1377
 
1273
- @keyframes cortex-part-fade-in-up {
1378
+ @keyframes cortex-part-reveal {
1274
1379
  from {
1275
1380
  opacity: 0;
1276
- transform: translateY(30px);
1381
+ transform: translateX(var(--cortex-reveal-from));
1382
+ filter: blur(5px);
1383
+ mask-image: var(--cortex-reveal-mask);
1384
+ mask-size: 300% 100%;
1385
+ mask-repeat: no-repeat;
1386
+ mask-position: var(--cortex-reveal-start) 0;
1277
1387
  }
1278
- to {
1388
+ 40% {
1279
1389
  opacity: 1;
1280
- transform: translateY(0);
1390
+ }
1391
+ to {
1392
+ transform: none;
1393
+ filter: none;
1394
+ mask-image: var(--cortex-reveal-mask);
1395
+ mask-size: 300% 100%;
1396
+ mask-repeat: no-repeat;
1397
+ mask-position: var(--cortex-reveal-end) 0;
1281
1398
  }
1282
1399
  }
1283
1400
  .cortex-unhandled-type {
@@ -3375,7 +3492,9 @@ html[dir=ltr] .cortex-llm-inspector__trigger {
3375
3492
  .cortex-widget *::before,
3376
3493
  .cortex-widget *::after {
3377
3494
  animation-duration: 0.01ms !important;
3495
+ animation-delay: 0s !important;
3378
3496
  animation-iteration-count: 1 !important;
3379
3497
  transition-duration: 0.01ms !important;
3498
+ transition-delay: 0s !important;
3380
3499
  }
3381
3500
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@m6d/cortex-react",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "React chat widget SDK for cortex servers",
5
5
  "license": "MIT",
6
6
  "sideEffects": [