@m6d/cortex-react 0.1.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/README.md +30 -0
- package/dist/index.d.ts +121 -0
- package/dist/index.js +9 -0
- package/dist/styles.css +3372 -0
- package/dist/theme.css +71 -0
- package/package.json +77 -0
package/README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# @m6d/cortex-react
|
|
2
|
+
|
|
3
|
+
React chat widget for cortex servers: streaming messages, tool call visualization, composer attachments, syntax highlighting, and i18n. Same features and pixel parity as `@m6d/cortex-angular`.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```tsx
|
|
8
|
+
import { CortexChatWidget, type CortexReactConfig } from '@m6d/cortex-react';
|
|
9
|
+
import '@m6d/cortex-react/styles.css';
|
|
10
|
+
import '@m6d/cortex-react/theme.css';
|
|
11
|
+
|
|
12
|
+
const config = {
|
|
13
|
+
locale: 'en',
|
|
14
|
+
transport: {
|
|
15
|
+
baseUrl: '/api/agents/assistant',
|
|
16
|
+
getHeaders: () => ({ Authorization: `Bearer ${token}` }),
|
|
17
|
+
},
|
|
18
|
+
} satisfies CortexReactConfig;
|
|
19
|
+
|
|
20
|
+
export function Chat() {
|
|
21
|
+
return <CortexChatWidget config={config} className="block h-svh w-full" />;
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`CortexReactConfig` is the shared `CortexConfig` plus a React-only `toolComponents` slot (`Record<string, ComponentType<CortexToolComponentInputs>>`). Every other property, the client tools flow, and the media blocks are documented in [`packages/cortex-angular/README.md`](../cortex-angular/README.md); only the `toolComponents` and `injector` rows are Angular-specific.
|
|
26
|
+
|
|
27
|
+
## Requirements
|
|
28
|
+
|
|
29
|
+
- React 18 or later
|
|
30
|
+
- Peer dependencies: `@tanstack/ai`, `@tanstack/ai-client`, `@tanstack/ai-react`, `marked`, `dompurify`, `highlight.js`, plus the lazily loaded `mermaid`, `vega`, `vega-lite`, `vega-embed`, `leaflet` (and `leaflet/dist/leaflet.css` in your page for maps)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Generated by dts-bundle-generator v9.5.1
|
|
2
|
+
|
|
3
|
+
import { ToolCallPart, UIMessage } from '@tanstack/ai';
|
|
4
|
+
import { ComponentType } from 'react';
|
|
5
|
+
|
|
6
|
+
declare const LOCALES: readonly [
|
|
7
|
+
"en",
|
|
8
|
+
"ar"
|
|
9
|
+
];
|
|
10
|
+
export type Locale = (typeof LOCALES)[number];
|
|
11
|
+
export type ThreadSummary = {
|
|
12
|
+
id: string;
|
|
13
|
+
title: string | null;
|
|
14
|
+
createdAt: string;
|
|
15
|
+
updatedAt: string;
|
|
16
|
+
isRunning: boolean;
|
|
17
|
+
/** Present on a headless thread a trigger owns. Widgets never list these. */
|
|
18
|
+
trigger?: {
|
|
19
|
+
name: string;
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
export type CortexHeaders = Record<string, string>;
|
|
23
|
+
/**
|
|
24
|
+
* How the widget reaches its cortex server. `baseUrl` may be a thunk so a host
|
|
25
|
+
* with a reactive origin (an Angular Signal is itself a `() => string`) is read
|
|
26
|
+
* at the moment of each request rather than captured once.
|
|
27
|
+
*/
|
|
28
|
+
export type CortexTransport = {
|
|
29
|
+
baseUrl: string | (() => string);
|
|
30
|
+
getHeaders: () => CortexHeaders | Promise<CortexHeaders>;
|
|
31
|
+
};
|
|
32
|
+
export type ColorScheme = "light" | "dark";
|
|
33
|
+
export type MediaRenderContext = {
|
|
34
|
+
scheme: ColorScheme;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Draws a closed media fence's `source` into `host`, resolves once drawn, and
|
|
38
|
+
* returns the teardown. A consumer's `mediaRenderers` config entry has this
|
|
39
|
+
* shape too: one per fence language, replacing the built-in of the same name
|
|
40
|
+
* or adding a language of its own.
|
|
41
|
+
*/
|
|
42
|
+
export type MediaRenderer = (host: HTMLElement, source: string, context: MediaRenderContext) => Promise<() => void>;
|
|
43
|
+
export type MediaRenderers = Partial<Record<string, MediaRenderer>>;
|
|
44
|
+
/** One value for every locale, or a map keyed by locale ('en', 'ar'). */
|
|
45
|
+
export type Localized<T> = T | Partial<Record<Locale, T>>;
|
|
46
|
+
export type CortexViewMode = "helper" | "full";
|
|
47
|
+
export type CortexTheme = "light" | "dark" | "system";
|
|
48
|
+
export type CortexToolCallContext = {
|
|
49
|
+
threadId: string;
|
|
50
|
+
};
|
|
51
|
+
/** A tool the server left for the client to answer. */
|
|
52
|
+
export type CortexToolCall = {
|
|
53
|
+
toolCallId: string;
|
|
54
|
+
toolName: string;
|
|
55
|
+
input: unknown;
|
|
56
|
+
};
|
|
57
|
+
export type CortexHooks = {
|
|
58
|
+
onToolCall?: (toolCall: CortexToolCall, context: CortexToolCallContext) => unknown;
|
|
59
|
+
onThreadSelected?: (thread: ThreadSummary) => Promise<void> | void;
|
|
60
|
+
onThreadDeselected?: (thread: ThreadSummary) => Promise<void> | void;
|
|
61
|
+
};
|
|
62
|
+
/** What the widget hands a consumer-supplied tool component, in either SDK. */
|
|
63
|
+
export type CortexToolComponentInputs = {
|
|
64
|
+
toolCallPart: ToolCallPart;
|
|
65
|
+
message: UIMessage;
|
|
66
|
+
/** Answers the call. Rejects when the delivery failed, so a component can say so and let the user retry. */
|
|
67
|
+
setOutput: (output: unknown) => Promise<void>;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* The framework-neutral part of the widget's configuration. Each SDK extends it
|
|
71
|
+
* with its own `toolComponents` slot, which is the one field whose type is
|
|
72
|
+
* inherently framework-bound.
|
|
73
|
+
*/
|
|
74
|
+
export type CortexConfig = {
|
|
75
|
+
/** Defaults to `'en'`. */
|
|
76
|
+
locale?: Locale;
|
|
77
|
+
transport: CortexTransport;
|
|
78
|
+
/**
|
|
79
|
+
* WebSocket endpoint override, derived from `transport.baseUrl` by default.
|
|
80
|
+
* `false` disables the socket entirely (chat still works fully over SSE;
|
|
81
|
+
* only cross-tab notify events are lost) — required behind proxies that do
|
|
82
|
+
* not forward `/ws`, which would otherwise reconnect forever.
|
|
83
|
+
*/
|
|
84
|
+
wsUrl?: string | false;
|
|
85
|
+
viewMode?: CortexViewMode;
|
|
86
|
+
/** Color scheme; `'system'` follows the OS preference. Defaults to `'light'`. */
|
|
87
|
+
theme?: CortexTheme;
|
|
88
|
+
/**
|
|
89
|
+
* Replaces or extends the media fences the assistant's replies draw. Keyed by
|
|
90
|
+
* fence tag; `map` swaps the built-in Leaflet map for another provider.
|
|
91
|
+
*/
|
|
92
|
+
mediaRenderers?: MediaRenderers;
|
|
93
|
+
/**
|
|
94
|
+
* Chat header title while no thread is selected; defaults to a localized
|
|
95
|
+
* "New Chat". Like the other copy props, either one value for every locale
|
|
96
|
+
* or a map keyed by locale (`{ en: 'Support', ar: 'الدعم' }`).
|
|
97
|
+
*/
|
|
98
|
+
agentName?: Localized<string>;
|
|
99
|
+
showDebugButton?: boolean;
|
|
100
|
+
/**
|
|
101
|
+
* Render embedded tool pages served from this page's own origin with their
|
|
102
|
+
* full identity — which, same-origin, means no effective sandbox at all: such
|
|
103
|
+
* an embed can reach into the host page. By default they are refused
|
|
104
|
+
* (rendered inert), because embed URLs come from Control Center tool config,
|
|
105
|
+
* and whoever administers that is not necessarily whoever owns this site.
|
|
106
|
+
* Enable only when both are the same party and the embeds are this site's
|
|
107
|
+
* own pages — then a second origin just for embeds is no longer needed.
|
|
108
|
+
*/
|
|
109
|
+
trustSameOriginEmbeds?: boolean;
|
|
110
|
+
hooks?: CortexHooks;
|
|
111
|
+
};
|
|
112
|
+
export type CortexReactConfig = CortexConfig & {
|
|
113
|
+
toolComponents?: Record<string, ComponentType<CortexToolComponentInputs>>;
|
|
114
|
+
};
|
|
115
|
+
export declare function CortexChatWidget({ config, className, }: {
|
|
116
|
+
config: CortexReactConfig;
|
|
117
|
+
/** Sizing classes for the host. */
|
|
118
|
+
className?: string;
|
|
119
|
+
}): import("react").JSX.Element;
|
|
120
|
+
|
|
121
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
var B2=Object.create;var{getPrototypeOf:D2,defineProperty:Q0,getOwnPropertyNames:H2}=Object;var F2=Object.prototype.hasOwnProperty;var H_=(_,N,$)=>{$=_!=null?B2(D2(_)):{};let J=N||!_||!_.__esModule?Q0($,"default",{value:_,enumerable:!0}):$;for(let X of H2(_))if(!F2.call(J,X))Q0(J,X,{get:()=>_[X],enumerable:!0});return J};var F_=((_)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(_,{get:(N,$)=>(typeof require<"u"?require:N)[$]}):_)(function(_){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+_+'" is not supported')});import{useEffect as h8,useRef as V2,useState as _1}from"react";var J1=["en","ar"];var X1=["image/png","image/jpeg","image/webp","application/pdf"];var G0=5;function Z0(_,N){if(!X1.some(($)=>$===_))return"type";if(N>10485760)return"size";return"ok"}var V0="clientToolAnswers",Y1="X-Cortex-Timezone";function Q1(_){let N=_.getHeaders();return N instanceof Promise?N.then(z0):Promise.resolve(z0(N))}function z0(_){let N={..._},$=U2(),J=Object.keys(N).some((X)=>X.toLowerCase()===Y1.toLowerCase());if($&&!J)N[Y1]=$;return N}function U2(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function L2(_,N){let $=_.baseUrl;return(typeof $==="string"?$:$()).replace(/\/$/,"")+N}function k2(_){let N=_?.match(/filename\*\s*=\s*[^']*'[^']*'([^;\r\n]+)/i)?.[1]?.trim().replace(/^"|"$/g,"");if(N)try{return decodeURIComponent(N)}catch{}return _?.match(/filename\s*=\s*"?([^";\r\n]+)"?/i)?.[1]}function G1(_){function N(){return Q1(_())}function $(X){return L2(_(),X)}async function J(X,Y){let Q=new Headers(await N());if(new Headers(Y?.headers).forEach(function(G,z){Q.set(z,G)}),Y?.body instanceof FormData)Q.delete("Content-Type");else if(!Q.has("Content-Type"))Q.set("Content-Type","application/json");let Z=await fetch($(X),{...Y,headers:Q});if(!Z.ok)throw Error(`HTTP ${Z.status}: ${Z.statusText}`);let V=await Z.text();return V?JSON.parse(V):void 0}return{getCapabilities(){return J("/capabilities")},listThreads(){return J("/threads")},createThread(){return J("/threads",{method:"POST"})},deleteThread(X){return J(`/threads/${X}`,{method:"DELETE"})},listMessages(X){return J(`/threads/${X}/messages`)},listLlmRequests(X){return J(`/messages/${X}/llm-requests`)},abortStream(X){return J(`/chat/${X}/abort`,{method:"POST"})},initiateToolCall(X,Y){return J(`/chat/${X}/tools/${Y}/initiate`,{method:"POST"})},async uploadAttachment(X,Y){let Q=new FormData;return Q.append("file",Y),await J(`/threads/${X}/files`,{method:"POST",body:Q})},deleteAttachment(X){return J(`/files/${X}`,{method:"DELETE"})},async downloadAttachment(X){let Y=await fetch($(`/files/${X}`),{headers:await N()});if(!Y.ok)throw Error(`HTTP ${Y.status}: ${Y.statusText}`);return{blob:await Y.blob(),name:k2(Y.headers.get("Content-Disposition"))??X}},resolveHeaders:N,resolveUrl:$}}var O2={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 Z1(_){let{state:N,approval:$}=_;return{modifier:O2[N],labelKey:$?.approved===!1?"translate_declined":N==="approval-responded"&&$?.approved?"translate_approved":P2[N],pulse:N==="awaiting-input"||N==="input-streaming"?"default":N==="approval-requested"?"violet":void 0}}function V1(_){let N=_.output;if(N===void 0||N===null)return"";if(typeof N==="string")return N;return JSON.stringify(N,null,2)}var q0={code:"javascript",query:"cypher"};function z1(_){let N=_&&typeof _==="object"?_:null,$=N?Object.entries(q0).flatMap(([X,Y])=>{let Q=N[X];return typeof Q==="string"?[{key:X,lang:Y,value:Q.replace(/\\n/g,`
|
|
2
|
+
`)}]:[]}):[],J=_;if(N){let X=Object.fromEntries(Object.entries(N).filter(([Y])=>!Object.hasOwn(q0,Y)));J=Object.keys(X).length>0?X:null}return{codeSnippets:$,remainingInput:J,remainingInputText:J?JSON.stringify(J,null,2):""}}var K0=10,M2={"awaiting-input":"starting","input-streaming":"starting","input-complete":"processing","approval-requested":"approval","approval-responded":"processing",complete:"complete",error:"error"};function A2(_){let N=0;for(let $=0;$<_.length;$++)N=N*31+_.charCodeAt($)|0;return Math.abs(N)%K0}function E2(_){let N=_.input;if(!N||typeof N!=="object"||!("status"in N))return;let $=N.status;return typeof $==="string"&&$.trim()?$.trim():void 0}function R2(_){let N=_.output;if(typeof N==="string")try{N=JSON.parse(N)}catch{return!1}return!!N&&typeof N==="object"&&"error"in N&&N.error===!0}function y2(_){let N=_.output;if(!N||typeof N!=="object"||!("rowCount"in N))return;return typeof N.rowCount==="number"?N.rowCount:void 0}function w2(_,N,$){if($)return"translate_declined";if(N==="error")return"translate_tool_error";if(N==="approval")return"translate_needs_approval";let J=_.name==="readAttachment"?"attachment":"tool",X=J==="tool"?`_${A2(_.id)}`:"";return`translate_${J}_${N==="complete"?"done":"status"}${X}`}function U_(_){let N=_.approval?.approved===!1,J=N||_.state==="complete"&&R2(_)?"error":M2[_.state]??"processing";return{state:J,active:J==="starting"||J==="processing",gated:_.approval!==void 0,titleKey:w2(_,J,N),statement:E2(_),rowCount:J==="complete"?y2(_):void 0}}function q1(_,N){let $=_.metadata;if(!$||typeof $!=="object"||!("cortex"in $))return;return($.cortex??void 0)?.approval?.[N]||void 0}function K1(_){return Array.from({length:K0},(N,$)=>`translate_${_}_${$}`)}function L_(_,N){return _.filter(($,J)=>{if($.type==="tool-result")return!1;if(N.debugMode)return!0;if(N.fold?.get($)?.kind==="hidden")return!1;if($.type==="text"&&!$.content.trim())return!1;let X=J===_.length-1;return $.type!=="thinking"||N.isStreaming&&X})}function W1(_){return _.filter((N)=>N.type==="text").map((N)=>N.content).join(`
|
|
3
|
+
|
|
4
|
+
`)}var b2=new Set(["complete","error"]);function m(_){return b2.has(_)}function t(_){return(I2(_)?.parts??[]).filter(($)=>$.type==="tool-call"&&!m($.state))}function B1(_){let N=_.at(-1);if(N?.role!=="assistant")return;let $=N.parts.at(-1),J=$?.type==="tool-call"||$?.type==="tool-result",X=N.parts.every((Y)=>Y.type!=="tool-call"||m(Y.state));return J&&X?void 0:N}function I2(_){for(let N=_.length-1;N>=0;N-=1){let $=_[N];if($?.role==="assistant")return $}return}function D1(){let _=new Map;return(N,$)=>{let J=new Map;for(let[X,Y]of C2(N,$)){let Q=_.get(X);J.set(X,Q&&v2(Q,Y)?Q:Y)}return _=J,J}}function C2(_,N){let $=new Map;if(N.debugMode)return $;let X=N.agentWorking||t(_).length>0?S2(_):_,Y=[];function Q(){let Z=Y[0]?.part.id;if(Y.length>1&&Z&&!N.opened.has(Z))for(let[V,{messageId:G,part:z}]of Y.entries()){let q=$.get(G)??new Map;$.set(G,q);let U=V===Y.length-1;q.set(z,U?{kind:"more",count:Y.length-1,runId:Z}:{kind:"hidden"})}Y=[]}for(let Z of X){if(Z.role!=="assistant"){Q();continue}let V=L_(Z.parts,{debugMode:!1,isStreaming:!1});for(let G of V)if(G.type==="tool-call"&&m(G.state)&&N.foldable(G))Y.push({messageId:Z.id,part:G});else Q()}return Q(),$}function S2(_){let N=_.map(($)=>$.role).lastIndexOf("user");return N<0?[]:_.slice(0,N)}function v2(_,N){if(_.size!==N.size)return!1;for(let[$,J]of _){let X=N.get($);if(!X||X.kind!==J.kind)return!1;if(J.kind==="more"&&X.kind==="more"){if(J.count!==X.count||J.runId!==X.runId)return!1}}return!0}import{EventType as T2}from"@tanstack/ai";import{fetchServerSentEvents as W0}from"@tanstack/ai-client";function B0(_){let N=_.role==="trigger"?"user":_.role;return{id:_.id,role:N,parts:_.parts}}function f2(_){for(let N=_.length-1;N>=0;N-=1){let $=_[N],J="parts"in $&&$.parts.some((X)=>X.type==="tool-result"||X.type==="tool-call"&&X.state==="approval-responded");if($.role==="user"||J)return _.slice(N,N+1)}return _.slice(-1)}function g2(_){if(_.state==="approval-responded"){let N=_.approval?.approved;if(N===void 0)return null;return{toolCallId:_.id,output:null,state:N?"approved":"denied"}}if(!m(_.state))return null;return{toolCallId:_.id,output:_.output??null,state:_.state==="error"?"error":"complete"}}function j2(_){let[N]=_;if(!N||N.role!=="assistant"||!("parts"in N))return null;let $=N.parts.flatMap((J)=>{let X=J.type==="tool-call"?g2(J):null;return X?[X]:[]});return $.length>0?$:null}function S_(_){return new Map(_.flatMap((N)=>N.metadata?[[N.id,N.metadata]]:[]))}function H1(_){let{api:N,thread:$}=_,J=async()=>({headers:await N.resolveHeaders()}),X=W0(()=>N.resolveUrl("/chat"),J),Y=function(V,G,z,q){let U=f2(V),H=j2(U);return H?X.connect([],{...G,[V0]:H},z,q):X.connect(U,G,z,q)},Q=W0(()=>N.resolveUrl(`/chat/${$.id}/stream`),J),Z=[];return{connect:Y,async*joinRun(V,G){yield{type:T2.MESSAGES_SNAPSHOT,timestamp:Date.now(),messages:Z},yield*Q.joinRun(V,G)},hydrate:async()=>{let V=await m2(_);return Z=V.messages,V}}}async function m2(_){let{api:N,thread:$,mode:J}=_,X=$.isRunning?{runId:$.id}:null;if(J==="skip")return{messages:[],activeRun:X,interrupts:null};if(J==="load")_.setLoadingMessages?.(!0);try{let Y=await N.listMessages($.id),Q=Y.map(B0);return _.onHydrated?.(Y,Q),{messages:Q,activeRun:X,interrupts:null}}finally{_.setLoadingMessages?.(!1)}}async function F1(_){try{let N=await _.api.listMessages(_.threadId);if(_.isStale?.())return;if(_.absorbMetadata(S_(N)),_.isStreaming())return;let $=N.map(B0);return _.setMessages($),$}catch{return}}function k_(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let _=crypto.getRandomValues(new Uint8Array(16));_[6]=_[6]&15|64,_[8]=_[8]&63|128;let N=Array.from(_,($)=>$.toString(16).padStart(2,"0")).join("");return`${N.slice(0,8)}-${N.slice(8,12)}-${N.slice(12,16)}-${N.slice(16,20)}-${N.slice(20)}`}function U1(_){let{api:N}=_,$=new Set,J=new Set,X=[],Y=[];function Q(){return X}function Z(F){return $.add(F),()=>{$.delete(F)}}function V(F){X=F;for(let K of $)K()}function G(F,K){V(X.map((L)=>L.localId===F?{...L,...K}:L))}function z(F){if(J.delete(F))return;G(F,{status:"error"})}function q(F){let K=[];for(let L of F){let E=Z0(L.type,L.size)!=="ok"||X.filter((R)=>R.status!=="error").length>=G0,P=k_();if(V([...X,{localId:P,filename:L.name,status:E?"error":"uploading"}]),!E)K.push({localId:P,file:L})}if(!K.length)return;_.ensureThread().then((L)=>{for(let{localId:E,file:P}of K){if(J.delete(E))continue;G(E,{threadId:L}),N.uploadAttachment(L,P).then((R)=>{if(J.delete(E)){N.deleteAttachment(R.id).catch(()=>{});return}G(E,{status:"ready",attachmentId:R.id,summary:R})},()=>z(E))}},()=>{for(let{localId:L}of K)z(L)})}function U(F){let K=X.find((L)=>L.localId===F);if(!K)return;if(K.status==="uploading"){J.add(F),V(X.filter((L)=>L.localId!==F));return}if(K.attachmentId){G(F,{status:"deleting"}),N.deleteAttachment(K.attachmentId).then(()=>V(X.filter((L)=>L.localId!==F)),()=>G(F,{status:"error"}));return}V(X.filter((L)=>L.localId!==F))}function H(F){let K=[];for(let L of X){if(L.threadId!==void 0&&L.threadId!==F){K.push(L);continue}if(L.status==="uploading")J.add(L.localId);else if(L.status==="ready"&&L.threadId===F&&L.attachmentId)N.deleteAttachment(L.attachmentId).catch(()=>{})}V(K)}function k(){let F=X.flatMap((K)=>K.status==="ready"&&K.summary?[{...K,status:"ready",summary:K.summary}]:[]);return V(X.filter((K)=>K.status!=="ready")),Y=F,F}function W(F){let K=Y;if(Y=[],K.some((L)=>L.threadId!==F))return;V([...K.map((L)=>({...L,status:"error"})),...X])}function O(){Y=[]}return{getState:Q,subscribe:Z,accept:q,remove:U,clear:H,consumeReady:k,restoreConsumed:W,discardConsumed:O}}function L1(_){return{uploading:_.some((N)=>N.status==="uploading"),busy:_.some((N)=>N.status==="uploading"||N.status==="deleting"),hasReady:_.some((N)=>N.status==="ready")}}var c2=["completed","cancelled","failed"],D0="requestLocation";function H0(_,N,$){if(N!==$)return null;if(typeof _!=="object"||_===null)return null;let J=_;if(J.type!=="cortex:client-tool")return null;let X=c2.find((Q)=>Q===J.status);if(!X)return null;let Y=J.reference;return{type:"cortex:client-tool",status:X,...typeof Y==="string"?{reference:Y}:{},...J.result!==void 0?{result:J.result}:{}}}function k1(_,N,$){try{return new URL(_).origin===N&&!$?"allow-scripts allow-forms allow-popups":"allow-scripts allow-forms allow-popups allow-same-origin"}catch{return"allow-scripts allow-forms allow-popups"}}function O1(_,N,$){try{return $===!0&&new URL(_).origin===N}catch{return!1}}function P1(_,N){try{return _.contentWindow?.location.origin===N}catch{return!1}}function M1(_){let N=!1,$=!1,J,X;function Y(V){if(!N)_.onState(V)}function Q(){if(N)return;$=!1,Y({phase:"error"})}function Z(V){if(N||$)return;$=!0,Y({phase:"settling"});try{let G=_.submit(V);if(G instanceof Promise)G.catch(Q)}catch{Q()}}return{async start(){Y({phase:"initiating"});try{let V=await _.initiate();if(!V.embed){Y({phase:"unavailable"});return}if(!/^https?:$/.test(new URL(V.embedUrl).protocol)){Y({phase:"error"});return}J=V.embedOrigin,Y({phase:"embedded",embedUrl:V.embedUrl,surface:V.surface,embedOrigin:V.embedOrigin})}catch(V){let G=V instanceof Error?V.message:"";Y({phase:/HTTP 404/.test(G)?"unavailable":"error"})}},setSource(V){if(V!==null&&V!==void 0)X=V},handleMessage(V){if(!J)return;if(X===void 0||V.source!==X)return;let G=H0(V.data,V.origin,J);if(!G)return;Z({status:G.status,reference:G.reference,result:G.result})},cancel(){Z({status:"cancelled"})},terminate(){if(N||$)return;J=void 0,X=void 0,Y({phase:"error"})},dispose(){N=!0}}}function A1(_,N,$){let J=_.interrupts.find((X)=>X.id===N);if(!J||!("resolveInterrupt"in J))return _.addToolApprovalResponse({id:N,approved:$});return J.resolveInterrupt({approved:$}),Promise.resolve()}async function O_(_,N){let $=await import("leaflet"),J=!N.interactive,X=$.map(_,{center:N.center,zoom:N.zoom,zoomControl:!J,dragging:!J,scrollWheelZoom:!J,doubleClickZoom:!J,touchZoom:!J,boxZoom:!J,keyboard:!J});$.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'}).addTo(X);let Y=new ResizeObserver(()=>X.invalidateSize());return Y.observe(_),{leaflet:$,map:X,dispose(){Y.disconnect(),X.remove()}}}var v_={position:void 0,locating:!1,locateFailed:!1,mapFailed:!1,submitting:!1,deliveryFailed:!1},x2={center:{lat:20,lng:0},zoom:2},u2=13,U0=16,h2=1e4;function E1(_,N){let $=v_,J=!1,X=!1,Y,Q,Z,V=0;function G(H){if($={...$,...H},!J)N.onState($)}function z(){let H=$.position;if(!Y||!H)return;let{leaflet:k,map:W}=Y;if(Q)Q.setLatLng(H);else{let O=k.marker(H,{draggable:!$.submitting}).addTo(W);O.on("dragend",()=>{let{lat:F,lng:K}=O.getLatLng();q({lat:F,lng:F0(K)})}),Q=O}Z?.remove(),Z=H.accuracy?k.circle(H,{radius:H.accuracy}).addTo(W):void 0}function q(H){if($.submitting)return;V+=1,G({position:H,locating:!1,locateFailed:!1}),z()}function U(H){if(J||X)return;X=!0,V+=1,Q?.dragging?.disable(),G({submitting:!0,locating:!1,deliveryFailed:!1});let k=()=>{X=!1,Q?.dragging?.enable(),G({submitting:!1,deliveryFailed:!0})};try{let W=N.submit(H);if(W instanceof Promise)W.catch(k)}catch{k()}}return{async start(){let H=N.center?{center:N.center,zoom:u2}:x2,k;try{k=await O_(_,{...H,interactive:!0})}catch{G({mapFailed:!0});return}if(J){k.dispose();return}Y=k,k.map.on("click",(W)=>q({lat:W.latlng.lat,lng:F0(W.latlng.lng)})),z()},locate(){if($.locating||$.submitting)return;if(!navigator.geolocation){G({locateFailed:!0});return}V+=1;let H=V;G({locating:!0,locateFailed:!1}),navigator.geolocation.getCurrentPosition(({coords:k})=>{if(J||H!==V)return;let W={lat:k.latitude,lng:k.longitude,accuracy:Math.round(k.accuracy)};q(W),Y?.map.setView(W,U0)},()=>{if(H===V)G({locating:!1,locateFailed:!0})},{enableHighAccuracy:!0,timeout:h2})},confirm(){if($.position)U({status:"completed",result:$.position})},cancel(){U({status:"cancelled"})},dispose(){J=!0,Y?.dispose()}}}function R1(_,N,$){let J=!1,X;return O_(_,{center:N,zoom:U0,interactive:!1}).then((Y)=>{if(J){Y.dispose();return}X=Y.dispose,Y.leaflet.marker(N).addTo(Y.map)},()=>{if(!J)$()}),()=>{J=!0,X?.()}}function F0(_){if(_>=-180&&_<=180)return _;return((_+180)%360+360)%360-180}function L0(_){if(!_||typeof _!=="object")return!1;let{lat:N,lng:$}=_;return typeof N==="number"&&typeof $==="number"&&Math.abs(N)<=90&&Math.abs($)<=180}function y1(_){let N=_&&typeof _==="object"?_.center:void 0;return L0(N)?N:void 0}function w1(_){if(!_||typeof _!=="object")return;let{status:N,result:$}=_;if(N!=="completed"||!L0($))return;let{accuracy:J}=$;return{...$,...typeof J==="number"?{accuracy:J}:{}}}function T_(_){let N=`${_.lat.toFixed(4)}, ${_.lng.toFixed(4)}`;return _.accuracy?`${N} ±${_.accuracy} m`:N}function b1(_){return Math.min(1000*2**(_-1),30000)}var l2=1e4;function I1(_){let N,$,J=0,X=!1;function Y(){let{wsUrl:Z,transport:V}=_.getConfig();if(Z===!1)return;let G=p2(Z,V.baseUrl);Q1(V).then((z)=>{if(X)return;N=new WebSocket(n2(G,z)),N.addEventListener("open",()=>{let q=N;setTimeout(()=>{if(N===q&&!X)J=0},l2),_.onOpen?.()}),N.addEventListener("message",(q)=>{let U=q.data;if(typeof U!=="string")return;let H;try{H=JSON.parse(U)}catch{return}_.onEvent(H)}),N.addEventListener("close",Q)}).catch(Q)}function Q(){if(X||$)return;J+=1,$=setTimeout(()=>{$=void 0,Y()},b1(J))}return Y(),{close(){X=!0,clearTimeout($),N?.close()}}}function p2(_,N){if(_)return _;let $=typeof N==="string"?N:N(),J=new URL($,window.location.origin);return J.protocol=J.protocol==="https:"?"wss:":"ws:",J.pathname=J.pathname.replace(/\/$/,"")+"/ws",J.toString()}function n2(_,N){let $=N.Authorization??N.authorization;if(!$?.startsWith("Bearer "))return _;let J=new URL(_,window.location.origin);if(J.searchParams.has("token"))return J.toString();return J.searchParams.set("token",$.slice(7)),J.toString()}function C1(_,N,$=b1){let J=!1,X,Y=0;function Q(){_.getCapabilities().then((Z)=>{if(!J)N(Z)},()=>{if(J)return;Y+=1,X=setTimeout(Q,$(Y))})}return Q(),function(){J=!0,clearTimeout(X)}}function f_(_){return[..._].sort((N,$)=>{let J=Date.parse($.updatedAt)-Date.parse(N.updatedAt);if(J!==0)return J;return Date.parse($.createdAt)-Date.parse(N.createdAt)})}function P_(_,N){let $=[..._],J=$.findIndex((X)=>X.id===N.id);if(J===-1)$.push(N);else $[J]={...$[J],...N};return f_($)}function g_(_,N){return _.filter(($)=>$.id!==N)}function S1(_,N){switch(N.type){case"thread:deleted":return g_(_,N.payload.threadId);case"thread:created":case"thread:title-updated":case"thread:run-started":case"thread:run-finished":case"thread:messages-updated":return P_(_,N.payload.thread);default:return _}}import{marked as d2}from"marked";import i2 from"dompurify";function v1(_){if(!_)return"";let N=d2.parse(_,{async:!1});return N=N.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'),i2.sanitize(N,{FORBID_TAGS:["img","picture","source"]})}function k0(){let _=null;return(N)=>{let $=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(N),J=$?.[1],X=$?.[2]??"";if(J){let Y=J.charAt(0);if(_){if(Y===_.marker&&J.length>=_.length&&X.trim()==="")return _=null,"close";return"inside"}if(Y==="`"&&X.includes("`"))return"outside";return _={marker:Y,length:J.length},"open"}return _?"inside":"outside"}}var r2=/^\s*!\[([^\]]*)\]\(attachment#([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)\s*$/i,o2=/^\s*(`{3,}|~{3,})/;function T1(_,N){let $=[],J=[],X=null;function Y(){if(J.length)$.push({kind:"markdown",text:J.join(`
|
|
5
|
+
`)});J=[]}function Q(G){if(X)$.push({kind:"media",...X,source:X.source.join(`
|
|
6
|
+
`),closed:G});X=null}let Z=k0(),V=_.split(`
|
|
7
|
+
`);for(let[G,z]of V.entries()){let q=Z(z);if(X){if(q==="close")Q(!0);else X.source.push(z);continue}if(q==="open"&&G===V.length-1)break;let U=a2(z,q,N);if(!U){J.push(z);continue}if(Y(),U.kind==="media")X={language:U.language,source:[]};else $.push(U)}return Q(!1),Y(),$}function a2(_,N,$){if(N==="open"){let X=_.replace(o2,"").trim().split(/\s+/)[0],Y=$.find((Q)=>Q===X);return Y?{kind:"media",language:Y}:void 0}let J=N==="outside"?r2.exec(_):null;return J?{kind:"attachment",alt:J[1]??"",id:(J[2]??"").toLowerCase()}:void 0}var t2=new Set(["flatten","fold","density","impute","regression","loess","quantile","sample"]);function M0(_,N){if(_==="url")return"Charts may only use inline data and no URLs.";if(_==="sequence"||_==="graticule")return"Charts may only use inline data.";if(t2.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(s2.has(_)&&typeof N==="string"&&!e2(N))return"Charts may only use simple expressions over datum.";if(_==="usermeta")return"Charts may not carry usermeta.";if(typeof N==="string"&&j_(N))return"Charts may not reference URLs.";if((_==="width"||_==="height")&&_4(N)>4000)return"Charts may be at most 4000 pixels wide or tall.";return}var s2=new Set(["calculate","filter","test","signal","labelExpr"]),O0=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 e2(_){if(_.length>500||/[\\`]/.test(_))return!1;let N=_.replace(/'[^']*'|"[^"]*"/g,'""');for(let[,J]of N.matchAll(/([A-Za-z_$][\w$]*)\s*\(/g))if(!O0.has(J??""))return!1;let $=N.replace(/(datum|parent)(\s*\.[\w$]+|\s*\[\s*""\s*\])+|\b\d[\w.]*/g,"").matchAll(/[A-Za-z_$][\w$]*/g);for(let[J]of $)if(!O0.has(J)&&!["true","false","null"].includes(J))return!1;return!0}function _4(_){if(typeof _==="number")return _;let N=_?.step;return typeof N==="number"?N:0}function P0(_,N){let $=_?.features,J=Array.isArray(_)?_.length:Array.isArray($)?$.length:-1;if(J<0)return M0(N,_)??g1(f1(_,N),M_);return J>200?"Charts may hold at most 200 rows.":void 0}function M_(_,N=""){if(N==="values")return P0(_,N);if(N==="datasets")return g1(f1(_),P0);return M0(N,_)??g1(f1(_,N),($,J)=>M_($,J))}function f1(_,N=""){if(Array.isArray(_))return _.map(($)=>[N,$]);return _&&typeof _==="object"?Object.entries(_):[]}function g1(_,N){for(let[$,J]of _){let X=N(J,$);if(X)return X}return}var A0=/url\(([^)]*)\)/gi,j1=/\b(url|src|image|image-set|-webkit-image-set|cross-fade|element)\(/i,N4=/\b(src|image|image-set|-webkit-image-set|cross-fade|element)\(/i,$4=/\b(src|image|image-set|-webkit-image-set|cross-fade|element)\([^)]*\)/gi,J4=/\\([0-9a-f]{1,6})\s?|\\(.)/gi;function X4(_){return _.replace(J4,(N,$,J)=>{if(!$)return J??"";let X=parseInt($,16),Y=X===0||X>=55296&&X<=57343||X>1114111;return String.fromCodePoint(Y?65533:X)})}function E0(_){return _.trim().replace(/^(['"])(.*)\1$/s,"$2").trim()}function j_(_){if(_.includes("\\")||N4.test(_))return!0;for(let[,N]of _.matchAll(A0))if(!E0(N??"").startsWith("#"))return!0;return!1}function m1(_){return X4(_).replace($4,"none").replace(A0,(N,$)=>E0($).startsWith("#")?N:"none")}var C0={async mermaid(_,N,{scheme:$}){let[{default:J},{default:X}]=await Promise.all([import("mermaid"),import("dompurify")]);if(j1.test(N)||N.includes("\\"))throw Error("Diagrams may not reference URLs.");if(/%%\{/.test(N))throw Error("Diagrams may not carry init directives.");if(/^\s*---\s*$/m.test(N))throw Error("Diagrams may not carry frontmatter.");if(/\bimg\s*:/.test(N))throw Error("Diagrams may not embed images.");let Y=G4(N);if(!Q4.test(Y))throw Error(`Unsupported diagram type: ${Y}`);let Q=R0.then(async()=>{if(!y0)J.initialize({startOnLoad:!1,securityLevel:"strict",htmlLabels:!1}),y0=!0;let G=`%%{init: {"theme": "${$==="dark"?"dark":"default"}"}}%%
|
|
8
|
+
${N}`;return await J.parse(G),(await J.render(`cortex-mermaid-${Z4()}`,G,_)).svg});R0=Q.catch(()=>{return});let Z=await Q,V=document.createElement("div");return V.innerHTML=X.sanitize(Z,{USE_PROFILES:{svg:!0,svgFilters:!0}}),b0(V),_.replaceChildren(...V.childNodes),()=>{_.innerHTML=""}},async "vega-lite"(_,N,{scheme:$}){let J=JSON.parse(N),X=M_(J);if(X)throw Error(X);let[{default:Y},Q]=await Promise.all([import("vega-embed"),import("vega")]),Z=()=>Promise.reject(Error("Charts may only use inline data.")),V=document.createElement("div"),G=await Y(V,J,{actions:!1,renderer:"svg",mode:"vega-lite",loader:{...Q.loader(),load:Z,sanitize:Z},ast:!0,...$==="dark"?{theme:"dark"}:{},config:{background:"transparent"}});return b0(V),_.replaceChildren(V),()=>G.finalize()},async map(_,N){let $=z4(JSON.parse(N)),{leaflet:J,map:X,dispose:Y}=await O_(_,{...$,interactive:!0});for(let Q of $.markers){let Z=J.marker(Q.position).addTo(X);if(Q.label){let V=document.createElement("span");V.textContent=Q.label,Z.bindTooltip(V)}}return Y}};function c1(_){return Object.keys({...C0,..._})}function Y4(_,N,$,J,X){let Y=X?.[_]??C0[_];if(!Y)return Promise.reject(Error(`No renderer for ${_}.`));return Y(N,$,J)}function x1(_,N){let $=_.appendChild(document.createElement("div")),J,X=!1;return Y4(N.language,$,N.source,N.context,N.overrides).then((Y)=>{if(X)Y();else J=Y},(Y)=>{if(!X)N.onError(Y instanceof Error?Y.message:String(Y))}),()=>{X=!0,J?.(),$.remove()}}var Q4=/^(flowchart|graph|sequenceDiagram|stateDiagram(-v2)?|erDiagram|gantt|pie|classDiagram|journey|timeline|mindmap)$/;function G4(_){let N=_.split(`
|
|
9
|
+
`).find(($)=>/\S/.test($)&&!/^\s*%%/.test($));return/^\s*(\S+)/.exec(N??"")?.[1]??""}var R0=Promise.resolve(),y0=!1,w0=0;function Z4(){return w0+=1,w0}var V4=new Set(["image","use","feImage"]);function b0(_){for(let N of[_,..._.querySelectorAll("*")]){for(let $ of[...N.attributes])if(($.name==="href"||$.name==="xlink:href")&&V4.has(N.tagName)&&!$.value.trim().startsWith("#")||j_($.value))N.removeAttribute($.name);if(N.tagName==="style"&&N.textContent)N.textContent=m1(N.textContent)}}function z4(_){if(!_||typeof _!=="object")throw Error("A map needs a JSON object.");let N=_,$=N.zoom??10;if(typeof $!=="number"||$<0||$>22)throw Error("zoom must be 0 to 22.");let J=N.markers??[];if(!Array.isArray(J))throw Error("markers must be a list.");return{center:I0(N.center,"center"),zoom:$,markers:J.map((X,Y)=>{let Q=X??{},Z=Q.label;return{position:I0(Q.position,`markers[${Y}].position`),label:typeof Z==="string"?Z:void 0}})}}function I0(_,N){let $=Array.isArray(_)?_:[],[J,X]=$;if(typeof J!=="number"||typeof X!=="number"||Math.abs(J)>90||Math.abs(X)>180)throw Error(`${N} must be [latitude, longitude].`);return{lat:J,lng:X}}function u1(_,N){if(_!=="system")return N(_??"light"),()=>{};let $=window.matchMedia("(prefers-color-scheme: dark)"),J=()=>N($.matches?"dark":"light");return J(),$.addEventListener("change",J),()=>$.removeEventListener("change",J)}import A_ from"highlight.js/lib/core";import q4 from"highlight.js/lib/languages/javascript";import K4 from"highlight.js/lib/languages/json";import W4 from"highlight.js/lib/languages/sql";var S0=!1;function B4(){if(S0)return;S0=!0,A_.registerLanguage("javascript",q4),A_.registerLanguage("json",K4),A_.registerLanguage("cypher",W4)}function h1(_,N){if(!_)return"";return B4(),A_.getLanguage(N)?A_.highlight(_,{language:N}).value:D4(_)}function D4(_){return _.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var v0={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}}"};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_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}}"};var U4={en:T0,ar:v0};function l1(_){return _&&J1.includes(_)?_:J1[0]}function p1(_,N,$){let J=U4[_][N];if(!$)return J;return J.replace(/\{\{\s*(\w+)\s*\}\}/g,(X,Y)=>(Y in $)?String($[Y]):X)}function Q_(_){if(typeof _==="string"){let N=_.trim();if(!(N.startsWith("{")&&N.endsWith("}")||N.startsWith("[")&&N.endsWith("]")))return _;try{return Q_(JSON.parse(N))}catch{return _}}if(Array.isArray(_))return _.map((N)=>Q_(N));if(_!==null&&typeof _==="object"){let N={};for(let[$,J]of Object.entries(_))N[$]=Q_(J);return N}return _}function n1(_,N){if(Array.isArray(_)){let $=_;return{kind:"container",open:"[",close:"]",summary:f0($.length,"item","items"),entries:$.map((J,X)=>({key:null,value:J,path:`${N}[${X}]`}))}}if(_!==null&&typeof _==="object"){let $=Object.entries(_);return{kind:"container",open:"{",close:"}",summary:f0($.length,"property","properties"),entries:$.map(([J,X])=>({key:J,value:X,path:`${N}.${J}`}))}}return{kind:"primitive",text:L4(_),className:k4(_)}}function f0(_,N,$){return`${_} ${_===1?N:$}`}function L4(_){if(_===null||_===void 0)return"null";if(typeof _==="string")return JSON.stringify(_);if(typeof _==="number"||typeof _==="boolean")return String(_);return JSON.stringify(_)??"null"}function k4(_){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 m_(_){if(!_)return null;try{return JSON.parse(_)}catch{return _}}function c_(_){if(!_)return"";try{return JSON.stringify(JSON.parse(_),null,2)}catch{return _}}function G_(_,N){if(_===void 0||typeof _==="string"||Array.isArray(_))return _;let $=_;return $[N]??$.en??Object.values($)[0]}var d1=[["year",31536000000],["month",2592000000],["week",604800000],["day",86400000],["hour",3600000],["minute",60000],["second",1000]];function p(_,N,$=Date.now()){let J=Date.parse(_);if(Number.isNaN(J))return"";let X=J-$,[Y,Q]=d1.find(([,Z])=>Math.abs(X)>=Z)??d1[d1.length-1];return new Intl.RelativeTimeFormat(N,{numeric:"auto"}).format(Math.round(X/Q),Y)}function i1(_,N){let $=URL.createObjectURL(_),J=document.createElement("a");J.href=$,J.download=N,J.click(),URL.revokeObjectURL($)}class N_{onUpdate;fullText="";displayedLength=0;animationFrameId=null;isDone=!1;static DRAIN_FRACTION=0.03;static MIN_CHARS_PER_FRAME=1;static DONE_DRAIN_FRACTION=0.1;constructor(_){this.onUpdate=_}seed(_){this.fullText=_,this.displayedLength=_.length,this.onUpdate(_)}update(_,N){if(this.fullText=_,this.isDone=N,this.displayedLength=Math.min(this.displayedLength,this.fullText.length),N&&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 N=this.isDone?N_.DONE_DRAIN_FRACTION:N_.DRAIN_FRACTION,$=Math.max(N_.MIN_CHARS_PER_FRAME,Math.ceil(_*N));if(this.displayedLength=Math.min(this.fullText.length,this.displayedLength+$),this.onUpdate(this.fullText.substring(0,this.displayedLength)),this.displayedLength<this.fullText.length)this.scheduleFrame();else this.animationFrameId=null}stopAnimation(){if(this.animationFrameId)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}}var O4=2;function r1(_){let N=!1,$=!1,J=!1,X=!1,Y=!1,Q=new Set,Z=0,V=!1;function G(){if(N&&Z===0)return!1;if(Z+=1,!N)N=!0,_.setRunning(!0);return!0}function z(W){if(Z-=1,W)V=!0;else if(Z===0&&!V)N=!1,_.setRunning(!1)}async function q(W,O){for(let F=0;F<O4;F+=1){let K=await _.refreshMessages().catch(()=>{return});if(!_.isAlive())return!1;if(!K)continue;if(!t(K).some((L)=>L.id===W.id))return!0;if(await _.deliver(O).then(()=>!0,()=>!1))return!0}return!1}async function U(W,O){let F;try{let P=O({toolCallId:W.id,toolName:W.name,input:W.input},{threadId:_.threadId});if(P===null||P===void 0)return;F=await Promise.resolve(P)}catch{Q.delete(W.id);return}if(F===null||F===void 0)return;if(!_.isAlive())return;let K=G(),L={toolCallId:W.id,tool:W.name,output:F},E=await _.deliver(L).then(()=>!0,()=>q(W,L));if(K)z(E);if(!E)Q.delete(W.id)}function H(W){let O=t(W),F=_.onToolCall();if(!F)return O.length>0;for(let K of O){if(K.state!=="input-complete"||Q.has(K.id))continue;Q.add(K.id),U(K,F)}return O.length>0}async function k(W){if(X){X=!1;return}if(N){if(H(W()))return;if(J)_.reloadThreads().catch(()=>{});else _.setRunning(!1)}let O=await _.refreshMessages();if(N&&O)H(O)}return{chunkArrived(){$=!0},streamFailed(){if(J=!0,$)_.onTurnFinished();else _.onSendFailed()},loadingChanged(W,O){if(W){Y=!0,J=!1;return}if(!Y)return;Y=!1,_.onTurnFinished(),k(O)},hydrated(W,O){if(O)return;setTimeout(()=>{if(_.isAlive())H(W)},0)},sendStarted(){_.setRunning(!0),N=!0,$=!1},abortConfirmed(){X=!0,_.setRunning(!1)}}}function E_(_){if(_.input.total<=0)return null;return Math.round(_.input.cacheRead/_.input.total*100)}import{createContext as g0,useContext as j0}from"react";var o1=g0(void 0);function B(){let _=j0(o1);if(!_)throw Error("useCortex must be used inside <CortexChatWidget>");return _}var x_={messages:[],messageMetadata:new Map,isAgentWorking:!1,isLoadingMessages:!1,hasPendingToolCalls:!1},u_=g0(x_);function h_(){return j0(u_)}import{useEffect as P4,useState as M4}from"react";function m0(_,N){let[$,J]=M4();return P4(()=>{return J(void 0),C1(_,J)},[_,N]),$}import{useRef as C4}from"react";import{useRef as A4,useState as E4,useSyncExternalStore as R4}from"react";function c0(_,N){let $=A4(N);$.current=N;let[J]=E4(()=>U1({api:_,ensureThread:()=>$.current()})),X=R4(J.subscribe,J.getState,J.getState);return{store:J,value:{items:X,...L1(X),accept:J.accept,remove:J.remove,consumeReady:J.consumeReady}}}import{useEffect as y4,useRef as w4}from"react";function x0(_,N){let $=w4(void 0);y4(()=>{if(N===$.current)return;_.clear($.current),$.current=N},[N,_])}import{useRef as u0}from"react";function h0(_){let N=u0([]),$=u0(void 0);function J(){let Y=_.selectedRef.current;if(Y)return Promise.resolve(Y.id);return $.current??=_.api.createThread().then((Q)=>{return $.current=void 0,_.onCreated(Q),Q.id},(Q)=>{throw $.current=void 0,Q}),$.current}async function X(Y,Q=[]){let Z=_.sessionRef.current;if(Z){await Z.send(Y,Q);return}N.current.push({prompt:Y,attachments:Q});try{await J()}catch(V){throw N.current=[],V}}return{ensureThread:J,send:X,pendingSendRef:N}}import{useRef as b4,useState as I4}from"react";function l0(_){let[N,$]=I4(),J=N?.thread,X=J?_.threads?.find((G)=>G.id===J.id)??J:void 0,Y=b4(X);Y.current=X;function Q(G,z){if(Y.current?.id===G.id&&_.hasSession())return;let q=Y.current;if(Y.current=G,$({thread:G,mode:z,epoch:0}),q&&q.id!==G.id)_.getHooks()?.onThreadDeselected?.(q);_.getHooks()?.onThreadSelected?.(G)}function Z(){let G=Y.current;if(!G&&!_.hasSession())return;if(Y.current=void 0,$(void 0),G)_.getHooks()?.onThreadDeselected?.(G)}function V(G,z,q){$((U)=>({thread:G,mode:"reload",epoch:(U?.epoch??0)+1,initialMessages:z,initialMetadata:q}))}return{session:N,selected:X,selectedRef:Y,select:Q,deselect:Z,remount:V}}function p0(_){let{api:N,threads:$}=_,J=C4(void 0),X=l0({threads:$.threads,getHooks:_.getHooks,hasSession:()=>J.current!==void 0}),Y=h0({api:N,sessionRef:J,selectedRef:X.selectedRef,onCreated:(G)=>{$.upsert(G),X.select(G,"skip")}}),Q=c0(N,Y.ensureThread);x0(Q.store,X.selected?.id);async function Z(G){if(X.selectedRef.current?.id===G)X.deselect();await $.remove(G)}function V(G){X.select(G,"load")}return{sessionRef:J,selection:X,queue:Q,deleteThread:Z,openThread:V,...Y}}import{useEffect as S4,useRef as v4}from"react";function n0(_){let N=v4(_);N.current=_,S4(()=>{N.current.onMount();let $=!1,J=I1({getConfig:()=>N.current.getConfig(),onEvent:(X)=>N.current.onEvent(X),onOpen:()=>{if($)N.current.onReconnect();$=!0}});return()=>J.close()},[])}function d0(_){let{threads:N,selectedRef:$,sessionRef:J}=_;function X(Q){N.applyEvent(Q);let Z=$.current?.id;switch(Q.type){case"thread:deleted":if(Z===Q.payload.threadId)_.deselect();break;case"thread:run-started":if(Z===Q.payload.thread.id)J.current?.reattach(Q.payload.thread);break;case"thread:messages-updated":J.current?.refreshMessages(Q.payload.thread.id);break}}function Y(){_.onReconnect(),N.reload().then((Q)=>{let Z=$.current;if(!Z)return;J.current?.reattach(Q.find((V)=>V.id===Z.id)??Z)})}return{onEvent:X,onReconnect:Y}}function i0(_){return{abort:async()=>{await _.current?.abort()},addToolResult:(N,$,J)=>_.current?.addToolResult(N,$,J)??Promise.resolve(),respondToApproval:(N,$)=>_.current?.respondToApproval(N,$)??Promise.resolve()}}import{useState as T4}from"react";function r0(_){let[N,$]=T4();async function J(){let V=f_(await _.listThreads());return $(V),V}function X(V){$((G)=>P_(G??[],V))}function Y(V,G){$((z)=>{let q=z?.find((U)=>U.id===V);return q?P_(z??[],{...q,isRunning:G}):z})}async function Q(V){await _.deleteThread(V),$((G)=>G?g_(G,V):G)}function Z(V){$((G)=>{let z=S1(G??[],V);return G||z.length?z:G})}return{threads:N,reload:J,upsert:X,setRunning:Y,remove:Q,applyEvent:Z}}import{useState as o0}from"react";function a0(){let[_,N]=o0("chat"),[$,J]=o0(!1);return{screen:_,sidebarOpen:$,showChat:()=>{N("chat"),J(!1)},openHistory:()=>N("threads"),closeHistory:()=>N("chat"),toggleSidebar:()=>J((X)=>!X),closeSidebar:()=>J(!1)}}function D(..._){return _.filter(Boolean).join(" ")}import{jsx as n,jsxs as t0}from"react/jsx-runtime";function s0({onToggleSidebar:_,onToggleDebug:N,onOpenHistory:$}){let{config:J,locale:X,t:Y,debugMode:Q,selectedThread:Z}=B();return t0("div",{className:"cortex-widget__chat-header",children:[n("button",{onClick:_,className:"cortex-widget__sidebar-toggle-btn",children:n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2.5 4h11M2.5 8h11M2.5 12h11",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}),n("div",{className:"cortex-widget__chat-title-wrap",children:n("p",{className:"cortex-widget__chat-title",children:Z?.title??G_(J.agentName,X)??Y("translate_new_chat")})}),J.showDebugButton&&n("button",{onClick:N,className:D("cortex-widget__debug-btn",Q?"cortex-widget__debug-btn--on":"cortex-widget__debug-btn--off"),children:Q?Y("translate_debug"):Y("translate_normal")}),n("button",{type:"button",onClick:$,"aria-label":Y("translate_history"),className:"cortex-widget__history-btn",children:t0("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[n("circle",{cx:"8",cy:"8",r:"5.75",stroke:"currentColor",strokeWidth:"1.3"}),n("path",{d:"M8 5v3l2 1.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})}var C={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 u4,useEffect as h4,useImperativeHandle as l4,useRef as X6,useState as p4}from"react";import{useState as f4}from"react";function e0(_,N){let[$,J]=f4(!1);return{dragging:$,onDragOver:(X)=>{if(X.preventDefault(),_)J(!0)},onDragLeave:(X)=>{if(!X.currentTarget.contains(X.relatedTarget))J(!1)},onDrop:(X)=>{if(X.preventDefault(),J(!1),_)N([...X.dataTransfer.files])},onPaste:(X)=>{let Y=X.clipboardData.files;if(!_||!Y.length)return;X.preventDefault(),N([...Y])}}}import{jsx as d,jsxs as a1}from"react/jsx-runtime";function _6(){let{queue:_,t:N}=B();if(!_.items.length)return null;return d("div",{className:"cortex-attachment-queue",children:_.items.map(($)=>a1("div",{className:D("cortex-attachment-chip",$.status==="error"&&"cortex-attachment-chip--error"),title:$.status==="error"?N("translate_attachment_rejected"):"",children:[$.status==="uploading"||$.status==="deleting"?a1("svg",{className:"cortex-attachment-chip__spinner",viewBox:"0 0 16 16",fill:"none",children:[d("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",className:"cortex-attachment-chip__spinner-track"}),d("path",{d:"M14 8a6 6 0 0 0-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):a1("svg",{viewBox:"0 0 16 16",className:"cortex-attachment-chip__icon",fill:"none",children:[d("path",{d:C.file[0],stroke:"currentColor",strokeWidth:"1.25"}),d("path",{d:C.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),d("span",{className:"cortex-attachment-chip__name",children:$.filename}),d("button",{type:"button",onClick:()=>_.remove($.localId),className:"cortex-attachment-chip__remove",disabled:$.status==="deleting","aria-label":N("translate_remove_attachment"),children:d("svg",{viewBox:"0 0 16 16",fill:"none",children:d("path",{d:"M4.5 4.5l7 7m0-7l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]},$.localId))})}import{useRef as g4}from"react";import{jsx as $_,jsxs as N6,Fragment as m4}from"react/jsx-runtime";var j4=X1.join(",");function $6({attachmentsEnabled:_,canSend:N,onSend:$}){let{t:J,queue:X}=B(),Y=g4(null);return N6("div",{className:"cortex-widget__input-actions",children:[_?N6(m4,{children:[$_("button",{type:"button",onClick:()=>Y.current?.click(),className:"cortex-widget__attach-btn","aria-label":J("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:Y,type:"file",multiple:!0,accept:j4,onChange:(Q)=>{X.accept([...Q.target.files??[]]),Q.target.value=""},className:"cortex-widget__file-input"})]}):null,$_("button",{onClick:$,className:D("cortex-widget__send-btn",!N&&"cortex-widget__send-btn--empty",N&&"cortex-widget__send-btn--ready"),disabled:!N,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 c4}from"react";import{jsx as x4}from"react/jsx-runtime";function J6(_){let{t:N}=B();c4(()=>{let J=_.inputRef.current;if(!J)return;J.style.height="0px",J.style.height=`${J.scrollHeight}px`},[_.inputRef,_.value]);function $(J){if(J.key==="Enter"&&!J.shiftKey)J.preventDefault(),_.onSubmit()}return x4("textarea",{ref:_.inputRef,onKeyDown:$,onPaste:_.onPaste,value:_.value,onChange:(J)=>_.onChange(J.target.value),placeholder:_.dragging?N("translate_drop_files_here"):_.disabled?"":N("translate_type_a_message"),disabled:_.disabled,rows:1,className:D("cortex-widget__textarea",_.disabled&&"cortex-widget__textarea--disabled")})}import{jsx as Z_,jsxs as t1}from"react/jsx-runtime";var Y6=u4(function(N,$){let{t:J,queue:X,send:Y,abort:Q,capabilities:Z}=B(),{isAgentWorking:V}=h_(),G=Z?.attachments??!1,[z,q]=p4(""),U=e0(G,X.accept),H=X6(null);l4($,()=>({focusInput:()=>H.current?.focus()}));let k=X6(V);h4(()=>{if(k.current&&!V)H.current?.focus();k.current=V},[V]);let W=!X.busy&&(Boolean(z.trim())||X.hasReady);function O(){if(V||!W)return;let F=z.trim()||J("translate_attachment_caption"),K=X.consumeReady();q(""),Y(F,K.map((L)=>L.summary))}return t1("div",{className:"cortex-widget__input-area",onDragOver:U.onDragOver,onDragLeave:U.onDragLeave,onDrop:U.onDrop,children:[Z_(_6,{}),t1("div",{className:D("cortex-widget__input-box",V&&"cortex-widget__input-box--disabled",!V&&"cortex-widget__input-box--enabled",U.dragging&&"cortex-widget__input-box--dragging"),children:[Z_(J6,{inputRef:H,value:z,onChange:q,onSubmit:O,onPaste:U.onPaste,disabled:V,dragging:U.dragging}),V?t1("button",{onClick:()=>void Q(),className:"cortex-stop-btn",children:[Z_("span",{className:"cortex-stop-btn__ring"}),Z_("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"cortex-stop-btn__icon",children:Z_("rect",{x:"1",y:"1",width:"10",height:"10",rx:"2.5",fill:"currentColor"})})]}):Z_($6,{attachmentsEnabled:G,canSend:W,onSend:O})]})]})});import{jsx as Q6}from"react/jsx-runtime";function l_({capabilities:_,composerRef:N}){let{t:$}=B();if(_===void 0)return null;return _.messages===!1?Q6("p",{className:"cortex-widget__messages-disabled",children:$("translate_messages_disabled")}):Q6(Y6,{ref:N})}import{jsx as h,jsxs as G6}from"react/jsx-runtime";function Z6(_){let{locale:N,t:$,threads:J,send:X,capabilities:Y}=B(),Q=Y?.messages===!1,Z=Y!==void 0,V=G_(Y?.suggestions,N),G=G_(Y?.greeting,N)||$("translate_greeting");return G6("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:C.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),h("p",{className:"cortex-widget__landing-greeting",children:G}),Z&&!Q&&!!V?.length&&h("div",{className:"cortex-widget__landing-chips",children:V.map((z,q)=>h("button",{type:"button",onClick:()=>void X(z.prompt),className:"cortex-widget__landing-chip",children:z.title},q))}),h(l_,{capabilities:Y}),!!J?.length&&h("div",{className:"cortex-widget__landing-recent",children:J.slice(0,2).map((z)=>{let q=p(z.updatedAt,N);return G6("button",{type:"button",onClick:()=>_.onThreadSelected(z),className:"cortex-widget__landing-recent-item",children:[h("p",{className:"cortex-widget__landing-recent-title",children:z.title??$("translate_untitled")}),q&&h("p",{className:"cortex-widget__landing-recent-time",children:q})]},z.id)})})]})}import{useCallback as R8,useEffect as t_,useMemo as y8,useRef as D_,useState as o6}from"react";import{jsx as p_,jsxs as V6}from"react/jsx-runtime";function z6(){let{t:_}=B();return V6("div",{className:"cortex-widget__working",children:[V6("div",{className:"cortex-widget__working-dots",children:[p_("span",{className:"cortex-working-dot"}),p_("span",{className:"cortex-working-dot"}),p_("span",{className:"cortex-working-dot"})]}),p_("span",{className:"cortex-widget__working-text",children:_("translate_thinking")})]})}import{memo as A8}from"react";import{Fragment as k8,useState as O8}from"react";import{useRef as n4,useState as d4}from"react";import{jsx as V_,jsxs as i4}from"react/jsx-runtime";function g({value:_,className:N}){let{t:$}=B(),[J,X]=d4(!1),Y=n4(null);async function Q(Z){Z.stopPropagation(),Z.preventDefault();try{if(await navigator.clipboard.writeText(_),X(!0),Y.current)clearTimeout(Y.current);Y.current=setTimeout(()=>X(!1),1500)}catch{}}return V_("span",{className:D("cortex-copy-btn",N),children:V_("button",{className:D("cortex-copy-btn__button",J&&"cortex-copy-btn__button--copied"),onClick:(Z)=>void Q(Z),"aria-label":J?$("translate_copied"):$("translate_copy"),type:"button",children:J?V_("svg",{className:"cortex-copy-btn__icon cortex-copy-btn__icon--check",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:V_("path",{d:"M5 13l4 4L19 7",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):i4("svg",{className:"cortex-copy-btn__icon",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:[V_("rect",{x:"9",y:"9",width:"12",height:"12",rx:"2",stroke:"currentColor",strokeWidth:"2"}),V_("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 q6}from"react/jsx-runtime";function K6(){let{t:_}=B();return q6("div",{className:"cortex-aborted-flag",children:[n_("span",{className:"cortex-aborted-flag__line"}),q6("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 z_,jsxs as W6}from"react/jsx-runtime";function B6(_){let{api:N,t:$}=B();async function J(X){let{blob:Y,name:Q}=await N.downloadAttachment(X);i1(Y,Q)}return z_("div",{className:D("cortex-message-attachments",_.isUser&&"cortex-message-attachments--user"),children:_.attachments.map((X)=>W6("button",{type:"button",onClick:()=>void J(X.id),className:"cortex-message-attachment","aria-label":`${$("translate_download")}: ${X.filename}`,children:[W6("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__icon",fill:"none",children:[z_("path",{d:C.file[0],stroke:"currentColor",strokeWidth:"1.25"}),z_("path",{d:C.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),z_("span",{className:"cortex-message-attachment__name",children:X.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"})})]},X.id))})}import{useRef as a4,useState as R_}from"react";import{useMemo as r4,useState as o4}from"react";import{jsx as f,jsxs as J_,Fragment as d_}from"react/jsx-runtime";function i({data:_,expandDepth:N,className:$}){let J=r4(()=>Q_(_),[_]),[X,Y]=o4({});function Q(V,G){return X[V]??G>=N}function Z(V,G){Y((z)=>({...z,[V]:!Q(V,G)}))}return f("div",{className:D("cortex-json-tree",$),children:f(D6,{value:J,path:"$",depth:0,isCollapsed:Q,toggle:Z})})}function D6({value:_,path:N,depth:$,isCollapsed:J,toggle:X}){let Y=n1(_,N);if(Y.kind==="primitive")return f("span",{className:Y.className,children:Y.text});if(Y.entries.length===0)return J_("span",{className:"cortex-json-tree__bracket",children:[Y.open,Y.close]});let Q=J(N,$);function Z(V){X(N,$),V.stopPropagation()}return J_(d_,{children:[J_("span",{className:"cortex-json-tree__toggle",onClick:Z,role:"button",children:[f("span",{className:D("cortex-json-tree__arrow",Q&&"cortex-json-tree__arrow--collapsed"),children:"▾"}),f("span",{className:"cortex-json-tree__bracket",children:Y.open})]}),Q?J_(d_,{children:[f("span",{className:"cortex-json-tree__collapsed-hint",onClick:Z,role:"button",children:Y.summary}),f("span",{className:"cortex-json-tree__bracket",children:Y.close})]}):J_(d_,{children:[f("div",{className:"cortex-json-tree__indent",children:Y.entries.map((V,G)=>J_("div",{className:"cortex-json-tree__line",children:[V.key!==null&&J_(d_,{children:[f("span",{className:"cortex-json-tree__key",children:`"${V.key}"`}),f("span",{className:"cortex-json-tree__colon",children:": "})]}),f(D6,{value:V.value,path:V.path,depth:$+1,isCollapsed:J,toggle:X}),G<Y.entries.length-1&&f("span",{className:"cortex-json-tree__comma",children:","})]},V.path))}),f("span",{className:"cortex-json-tree__bracket",children:Y.close})]})]})}function y(_){return _.toLocaleString("en-US")}import{jsx as q_,jsxs as K_}from"react/jsx-runtime";function H6({usage:_}){let{t:N}=B();return K_("div",{className:"cortex-llm-inspector__usage-rows",children:[K_("div",{className:"cortex-llm-inspector__usage-row",children:[q_("span",{className:"cortex-llm-inspector__usage-lbl",children:N("translate_input")}),q_("span",{className:"cortex-llm-inspector__usage-val",children:y(_.input.total)}),K_("span",{className:"cortex-llm-inspector__usage-detail",children:[N("translate_fresh")," ",y(_.input.noCache)," · ",N("translate_read")," ",y(_.input.cacheRead)," · ",N("translate_write")," ",y(_.input.cacheWrite)]})]}),K_("div",{className:"cortex-llm-inspector__usage-row",children:[q_("span",{className:"cortex-llm-inspector__usage-lbl",children:N("translate_output")}),q_("span",{className:"cortex-llm-inspector__usage-val",children:y(_.output.total)}),K_("span",{className:"cortex-llm-inspector__usage-detail",children:[N("translate_text")," ",y(_.output.text)," · ",N("translate_reasoning")," ",y(_.output.reasoning)]})]}),K_("div",{className:"cortex-llm-inspector__usage-row cortex-llm-inspector__usage-row--total",children:[q_("span",{className:"cortex-llm-inspector__usage-lbl",children:N("translate_total")}),q_("span",{className:"cortex-llm-inspector__usage-val",children:y(_.total)})]})]})}import{jsx as F6,jsxs as i_}from"react/jsx-runtime";function U6({usage:_}){let N=E_(_);return i_("span",{className:"cortex-llm-inspector__step-metrics",children:[i_("span",{className:"cortex-llm-inspector__metric",children:[F6("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--input"}),y(_.input.total)]}),i_("span",{className:"cortex-llm-inspector__metric",children:[F6("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--output"}),y(_.output.total)]}),N!==null?i_("span",{className:"cortex-llm-inspector__cache-pct",children:[N,"%"]}):null]})}import{jsx as b,jsxs as s}from"react/jsx-runtime";function L6({messageId:_}){let{t:N,api:$}=B(),[J,X]=R_(!1),[Y,Q]=R_(!1),[Z,V]=R_([]),[G,z]=R_(null),[q,U]=R_({}),H=a4(!1);async function k(){if(!H.current){Q(!0);try{V(await $.listLlmRequests(_))}finally{Q(!1),H.current=!0}}X((K)=>!K)}function W(K){z((L)=>L===K?null:K)}function O(K){return q[K]??"prompt"}function F(K,L){U((E)=>({...E,[K]:L}))}return s("div",{className:D("cortex-llm-inspector",J&&"cortex-llm-inspector--open"),children:[s("button",{className:"cortex-llm-inspector__trigger",onClick:()=>void k(),children:[b("svg",{className:"cortex-llm-inspector__icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:b("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"})}),b("span",{children:N("translate_inspect_llm_requests")}),Y?b("span",{className:"cortex-llm-inspector__loading",children:N("translate_loading")}):Z.length>0?b("span",{className:"cortex-llm-inspector__badge",children:Z.length}):null,b("svg",{className:"cortex-llm-inspector__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:b("path",{d:C.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),b("div",{className:"cortex-llm-inspector__panel-wrapper",children:b("div",{className:"cortex-llm-inspector__panel-inner",children:s("div",{className:"cortex-llm-inspector__panel",children:[Z.length===0&&!Y?b("div",{className:"cortex-llm-inspector__empty",children:N("translate_no_llm_requests")}):null,Z.map((K,L)=>s("div",{className:D("cortex-llm-inspector__step",G===K.id&&"cortex-llm-inspector__step--expanded"),children:[s("button",{className:"cortex-llm-inspector__step-header",onClick:()=>W(K.id),children:[b("span",{className:"cortex-llm-inspector__step-label",children:N("translate_step_n",{number:L+1})}),K.tokenUsage?b(U6,{usage:K.tokenUsage}):null,b("svg",{className:"cortex-llm-inspector__step-chevron",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:b("path",{d:C.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),b("div",{className:"cortex-llm-inspector__step-body-wrapper",children:b("div",{className:"cortex-llm-inspector__step-body-inner",children:s("div",{className:"cortex-llm-inspector__step-body",children:[K.tokenUsage?b(H6,{usage:K.tokenUsage}):null,s("div",{className:"cortex-llm-inspector__tabs",children:[b("button",{className:D("cortex-llm-inspector__tab",O(K.id)==="prompt"&&"cortex-llm-inspector__tab--active"),onClick:()=>F(K.id,"prompt"),children:N("translate_request")}),b("button",{className:D("cortex-llm-inspector__tab",O(K.id)==="response"&&"cortex-llm-inspector__tab--active"),onClick:()=>F(K.id,"response"),children:N("translate_response")})]}),s("div",{className:"cortex-llm-inspector__json-pane",children:[b(g,{className:"cortex-llm-inspector__json-copy",value:O(K.id)==="prompt"?c_(K.prompt):c_(K.output)}),O(K.id)==="prompt"?b(i,{data:m_(K.prompt),expandDepth:2}):b(i,{data:m_(K.output),expandDepth:2})]})]})})})]},K.id))]})})})]})}import{useState as t4}from"react";import{jsx as M,jsxs as S}from"react/jsx-runtime";function k6({usage:_,modelId:N}){let{t:$}=B(),[J,X]=t4(!1),Y=E_(_)??0;return S("div",{className:D("cortex-token-usage",J&&"cortex-token-usage--expanded"),children:[S("button",{className:"cortex-token-usage__summary",onClick:()=>X((Q)=>!Q),children:[S("span",{className:"cortex-token-usage__total",children:[M("span",{className:"cortex-token-usage__total-number",children:y(_.total)}),M("span",{className:"cortex-token-usage__total-label",children:$("translate_tokens")})]}),N?M("span",{className:"cortex-token-usage__model",children:N}):null,S("span",{className:"cortex-token-usage__pills",children:[S("span",{className:"cortex-token-usage__pill",children:[M("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),y(_.input.total)]}),S("span",{className:"cortex-token-usage__pill",children:[M("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),y(_.output.total)]})]}),Y>0?S("span",{className:"cortex-token-usage__cache-badge",children:[Y,"%"]}):null,M("svg",{className:"cortex-token-usage__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:M("path",{d:C.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),M("div",{className:"cortex-token-usage__details",children:M("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:[M("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),M("span",{className:"cortex-token-usage__col-label",children:$("translate_input")}),M("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:[M("span",{className:"cortex-token-usage__row-label",children:$("translate_fresh")}),M("span",{className:"cortex-token-usage__row-value",children:y(_.input.noCache)})]}):null,_.input.cacheRead?S("div",{className:"cortex-token-usage__row",children:[M("span",{className:"cortex-token-usage__row-label",children:$("translate_cache_read")}),M("span",{className:"cortex-token-usage__row-value",children:y(_.input.cacheRead)})]}):null,_.input.cacheWrite?S("div",{className:"cortex-token-usage__row",children:[M("span",{className:"cortex-token-usage__row-label",children:$("translate_cache_write")}),M("span",{className:"cortex-token-usage__row-value",children:y(_.input.cacheWrite)})]}):null]}),Y>0?S("div",{className:"cortex-token-usage__cache-bar-row",children:[M("div",{className:"cortex-token-usage__cache-bar",children:M("div",{className:"cortex-token-usage__cache-fill",style:{width:`${Y}%`}})}),M("span",{className:"cortex-token-usage__cache-label",children:$("translate_n_percent_cached",{percent:Y})})]}):null]}),S("div",{className:"cortex-token-usage__col",children:[S("div",{className:"cortex-token-usage__col-header",children:[M("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),M("span",{className:"cortex-token-usage__col-label",children:$("translate_output")}),M("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:[M("span",{className:"cortex-token-usage__row-label",children:$("translate_text")}),M("span",{className:"cortex-token-usage__row-value",children:y(_.output.text)})]}):null,_.output.reasoning?S("div",{className:"cortex-token-usage__row",children:[M("span",{className:"cortex-token-usage__row-label",children:$("translate_reasoning")}),M("span",{className:"cortex-token-usage__row-value",children:y(_.output.reasoning)})]}):null]})]})]})})})]})}import{jsx as O6,jsxs as s4}from"react/jsx-runtime";function P6({messageId:_,isAssistant:N,metadata:$}){let J=$?.tokenUsage;if(!J&&!N)return null;return s4("div",{className:"cortex-message-debug-zone",children:[J&&O6(k6,{usage:J,modelId:$?.modelId}),N&&O6(L6,{messageId:_})]})}import{jsx as j,jsxs as y_}from"react/jsx-runtime";function M6(_){let{reasoningPart:N,streaming:$=!1}=_,{t:J}=B();return y_("details",{className:"cortex-reasoning-details",children:[y_("summary",{className:"cortex-reasoning-details__summary",children:[y_("div",{className:"cortex-reasoning-details__header",children:[j("span",{className:"cortex-reasoning-details__icon",children:y_("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:[j("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"}),j("path",{d:"M7.5 17.5h5M8.5 8a2 2 0 0 1 2-2",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})]})}),j("div",{className:"cortex-reasoning-details__title-group",children:y_("div",{className:"cortex-reasoning-details__title-row",children:[j("div",{className:"cortex-reasoning-details__title",children:J("translate_reasoning")}),j("span",{className:D("cortex-reasoning-details__badge",$?"cortex-reasoning-details__badge--streaming":"cortex-reasoning-details__badge--done"),children:$?J("translate_streaming"):J("translate_done")})]})})]}),j("span",{className:"cortex-reasoning-details__chevron","aria-hidden":"true",children:j("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:j("path",{d:C.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),j("div",{className:"cortex-reasoning-details__body",children:j("div",{className:"cortex-reasoning-details__content",children:j("pre",{className:"cortex-reasoning-details__pre",children:N.content.trim()?N.content:J("translate_no_reasoning")})})})]})}import{useEffect as w6,useMemo as G8,useRef as e1,useState as Z8}from"react";import{useEffect as e4,useState as A6}from"react";import{jsx as s1,jsxs as _8}from"react/jsx-runtime";function E6(_){let{id:N,alt:$,attachment:J}=_,{api:X,t:Y}=B(),[Q,Z]=A6(),[V,G]=A6(!1);if(e4(()=>{let z,q=!1;return Z(void 0),G(!1),X.downloadAttachment(N).then(({blob:U})=>{if(q)return;z=URL.createObjectURL(U),Z(z)},()=>{if(!q)G(!0)}),()=>{if(q=!0,z)URL.revokeObjectURL(z)}},[X,N]),V)return s1("p",{className:"cortex-attachment-image__caption",children:$?Y("translate_image_unavailable_alt",{alt:$}):Y("translate_image_unavailable")});if(!Q)return null;return _8("figure",{className:"cortex-attachment-image",children:[s1("img",{src:Q,alt:$}),J&&s1("figcaption",{className:"cortex-attachment-image__caption",children:J.filename})]})}import{useEffect as N8,useRef as $8,useState as R6}from"react";import{jsx as r,jsxs as r_}from"react/jsx-runtime";var J8={mermaid:"translate_media_pending_mermaid","vega-lite":"translate_media_pending_vega_lite",map:"translate_media_pending_map"};function X8(_){return J8[_]??"translate_media_pending"}function Y8(_){let{t:N}=B();if(!_.pending&&!_.debugMode)return null;return r_("div",{className:"cortex-media-block__head",children:[_.debugMode&&r("span",{className:"cortex-media-block__lang",children:_.language}),_.pending&&r("span",{className:"cortex-media-block__pending",children:N(X8(_.language))}),_.debugMode&&_.closed&&r_("span",{className:"cortex-media-block__actions",children:[_.onToggleSource&&r("button",{type:"button",className:"cortex-media-block__action","aria-pressed":_.sourceShown,onClick:_.onToggleSource,children:N("translate_media_source")}),r(g,{value:_.source})]})]})}function Q8(_){let{debugMode:N,t:$}=B();return r("div",{className:"cortex-media-block__body",children:r_("p",{className:"cortex-media-block__error",children:[_.cutOff?$("translate_media_cut_off"):$("translate_media_failed"),!_.cutOff&&N&&` ${_.reason}`]})})}function y6(_){let{language:N,source:$,closed:J,streaming:X}=_,{config:Y,debugMode:Q,scheme:Z}=B(),V=$8(null),[G,z]=R6(),[q,U]=R6(!1);N8(()=>{z(void 0);let O=V.current;if(!J||!Z||!O)return;return x1(O,{language:N,source:$,context:{scheme:Z},overrides:Y.mediaRenderers,onError:z})},[N,$,J,Z,Y.mediaRenderers]);let H=!J&&!X,k=H||Boolean(G);return r_("div",{className:"cortex-media-block",children:[r(Y8,{language:N,source:$,pending:!J&&X,closed:J,debugMode:Q,sourceShown:q,onToggleSource:k?void 0:()=>U((O)=>!O)}),k&&r(Q8,{cutOff:H,reason:G}),r("div",{ref:V,hidden:k,className:D("cortex-media-block__body",`cortex-media-block__body--${N}`)}),Q&&(k||q)&&r("pre",{className:"cortex-media-block__source",children:$})]})}import{jsx as w_}from"react/jsx-runtime";function b6(_){let{role:N,textPart:$,streaming:J=!1,attachments:X=[]}=_,{config:Y}=B(),Q=N==="assistant"&&J?"":$.content,[Z,V]=Z8(Q),G=e1(Q),z=e1(null),q=e1(!0);w6(()=>{function k(W){G.current=W,V(W)}if(N!=="assistant"||!J){z.current?.destroy(),z.current=null,k($.content),q.current=!1;return}if(!z.current)z.current=new N_(k),z.current.seed(G.current);if(q.current){q.current=!1,z.current.seed($.content);return}z.current.update($.content,!1)},[N,J,$]),w6(()=>()=>{z.current?.destroy(),z.current=null},[]);let U=G8(()=>{return(N==="assistant"?T1(Z,c1(Y.mediaRenderers)):[{kind:"markdown",text:Z}]).map((W)=>W.kind==="markdown"?{...W,html:{__html:v1(W.text)}}:W)},[N,Z,Y.mediaRenderers]),H=J||Z!==$.content;return w_("div",{className:D("cortex-text-part",N==="assistant"&&"cortex-text-part--assistant",N==="user"&&"cortex-text-part--user"),children:w_("div",{className:D("cortex-text-bubble",N==="assistant"&&"cortex-text-bubble--assistant",N==="user"&&"cortex-text-bubble--user"),children:U.map((k,W)=>{switch(k.kind){case"markdown":return w_("div",{dangerouslySetInnerHTML:k.html},W);case"media":return w_(y6,{...k,streaming:H},W);case"attachment":return w_(E6,{id:k.id,alt:k.alt,attachment:X.find((O)=>O.id.toLowerCase()===k.id)},W)}})})})}import{jsx as T,jsxs as e}from"react/jsx-runtime";function I6({toolCallPart:_}){let{t:N}=B(),{state:$,approval:J}=_,X=_.output,Y=V1(_);function Q(){if($==="complete")return e("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--success",children:[e("div",{className:"cortex-debug-tool__section-bar",children:[T("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--success",children:N("translate_output")}),T("span",{className:"cortex-debug-tool__section-lang",children:"json"}),T(g,{value:Y})]}),T("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:T(i,{data:X,expandDepth:2})})]});if($==="error")return e("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--error",children:[e("div",{className:"cortex-debug-tool__section-bar",children:[T("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--error",children:N("translate_error")}),T(g,{value:Y})]}),T("pre",{dir:"ltr",className:"cortex-debug-tool__error-pre",children:Y})]});if($==="approval-requested")return e("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[e("div",{className:"cortex-debug-tool__section-bar",children:[T("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:N("translate_approval_requested")}),T("span",{className:"cortex-debug-tool__section-lang",children:J?.id})]}),T("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:N("translate_waiting_for_approval")})]});if($==="approval-responded")return e("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[e("div",{className:"cortex-debug-tool__section-bar",children:[T("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:N("translate_approval_response")}),T("span",{className:"cortex-debug-tool__section-lang",children:J?.id})]}),T("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:N(J?.approved?"translate_tool_approved":"translate_tool_response_received")})]});return null}return Q()}import{jsx as V8,jsxs as z8}from"react/jsx-runtime";function C6({toolCallPart:_}){let{t:N}=B(),$=Z1(_);return z8("span",{className:D("cortex-debug-tool__state",$.modifier&&`cortex-debug-tool__state--${$.modifier}`),children:[$.pulse&&V8("span",{className:D("cortex-debug-tool__pulse",$.pulse==="violet"&&"cortex-debug-tool__pulse--violet")}),N($.labelKey)]})}import{jsx as v,jsxs as o}from"react/jsx-runtime";function S6({toolCallPart:_}){let{t:N}=B(),{codeSnippets:$,remainingInput:J,remainingInputText:X}=z1(_.input);return o("details",{className:"cortex-debug-tool","data-state":_.state,children:[v("summary",{className:"cortex-debug-tool__summary",children:o("div",{className:"cortex-debug-tool__header",children:[o("div",{className:"cortex-debug-tool__meta",children:[v("div",{className:"cortex-debug-tool__title-row",children:v("span",{className:"cortex-debug-tool__name",title:_.name,children:_.name})}),v("div",{className:"cortex-debug-tool__id-row",children:v("span",{className:"cortex-debug-tool__id",children:_.id})})]}),o("div",{className:"cortex-debug-tool__actions",children:[v(C6,{toolCallPart:_}),v("svg",{className:"cortex-debug-tool__chevron",width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:v("path",{d:C.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),o("div",{className:"cortex-debug-tool__body",children:[$.map((Y)=>o("div",{className:"cortex-debug-tool__section",children:[o("div",{className:"cortex-debug-tool__section-bar",children:[v("span",{className:"cortex-debug-tool__section-label",children:Y.key}),v("span",{className:"cortex-debug-tool__section-lang",children:Y.lang}),v(g,{value:Y.value})]}),v("pre",{dir:"ltr",className:"cortex-debug-tool__pre",children:v("code",{className:"hljs",dangerouslySetInnerHTML:{__html:h1(Y.value,Y.lang)}})})]},Y.key)),!!J&&o("div",{className:"cortex-debug-tool__section",children:[o("div",{className:"cortex-debug-tool__section-bar",children:[v("span",{className:"cortex-debug-tool__section-label",children:N("translate_input")}),v("span",{className:"cortex-debug-tool__section-lang",children:"json"}),v(g,{value:X})]}),v("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:v(i,{data:J,expandDepth:2})})]}),v(I6,{toolCallPart:_})]})]})}import{useEffect as q8,useRef as K8,useState as v6}from"react";import{jsx as b_,jsxs as T6}from"react/jsx-runtime";function I_({activity:_,className:N}){let{t:$}=B(),J=K1(_),[X,Y]=v6(0),[Q,Z]=v6("idle"),V=K8(J.length);return V.current=J.length,q8(()=>{let G,z;function q(){G=setTimeout(()=>{Z("exiting"),G=setTimeout(()=>{Y((U)=>(U+1)%V.current),Z("enter-start"),z=requestAnimationFrame(()=>{Z("entering"),G=setTimeout(()=>{Z("idle"),q()},300)})},300)},2000)}return q(),()=>{if(G)clearTimeout(G);if(z)cancelAnimationFrame(z)}},[]),T6("div",{className:D("cortex-subtle-activity",N),children:[T6("div",{className:"cortex-subtle-activity__dots",children:[b_("span",{className:"cortex-subtle-activity__dot"}),b_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d1"}),b_("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d2"})]}),b_("div",{className:"cortex-subtle-activity__label-mask",children:b_("span",{className:D("cortex-subtle-activity__label",`cortex-subtle-activity__label--${Q}`),children:$(J[X])})})]})}import{useEffect as x6,useRef as _0,useState as c6}from"react";import{useEffect as g6,useRef as o_,useState as j6}from"react";import{jsx as I,jsxs as c}from"react/jsx-runtime";function m6({toolCallPart:_,setOutput:N}){let{t:$}=B(),{state:J,id:X,input:Y}=_;if(J==="complete"||J==="error"){let Q=w1(_.output);return Q?I(B8,{position:Q}):c("div",{className:"cortex-tool-pill",children:[I("span",{className:"cortex-tool-pill__icon",children:I("svg",{className:D("cortex-tool-pill__svg cortex-tool-pill__svg--visible",J==="error"&&"cortex-tool-pill__svg--error"),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:"cortex-tool-pill__title",children:$("translate_location_not_shared")})]})}if(J!=="input-complete")return null;return I(W8,{center:y1(Y),submit:N},X)}function W8({center:_,submit:N}){let{t:$}=B(),J=o_(null),X=o_(void 0),[Y,Q]=j6(v_),Z=o_({center:_,submit:N});return Z.current={center:_,submit:N},g6(()=>{let V=J.current;if(!V)return;let G=E1(V,{center:Z.current.center,onState:Q,submit:(z)=>Z.current.submit(z)});return X.current=G,G.start(),()=>{if(G.dispose(),X.current===G)X.current=void 0}},[]),c("div",{className:"cortex-location-input",children:[c("div",{className:"cortex-location-input__map",children:[I("div",{className:"cortex-location-input__canvas",ref:J}),I("button",{type:"button",className:"cortex-location-input__locate","aria-label":$("translate_location_locate"),title:$("translate_location_locate"),disabled:Y.locating||Y.submitting,onClick:()=>X.current?.locate(),children:I(D8,{})})]}),c("div",{className:"cortex-location-input__foot",children:[Y.position&&!Y.deliveryFailed?I("span",{className:"cortex-location-input__coords",children:T_(Y.position)}):c("span",{className:D("cortex-location-input__hint",f6(Y).failed&&"cortex-location-input__hint--failed"),children:[Y.locating&&I("span",{className:"cortex-location-input__spinner"}),$(f6(Y).key)]}),c("span",{className:"cortex-location-input__actions",children:[I("button",{type:"button",className:"cortex-location-input__skip",disabled:Y.submitting,onClick:()=>X.current?.cancel(),children:$("translate_location_skip")}),I("button",{type:"button",className:"cortex-location-input__send",disabled:!Y.position||Y.submitting,onClick:()=>X.current?.confirm(),children:$("translate_location_send")})]})]})]})}function f6(_){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 B8({position:_}){let{t:N}=B(),$=o_(null),[J,X]=j6(!1),{lat:Y,lng:Q}=_;return g6(()=>{let Z=$.current;if(!Z)return;return X(!1),R1(Z,{lat:Y,lng:Q},()=>X(!0))},[Y,Q]),c("div",{className:"cortex-location-input cortex-location-input--settled",children:[c("div",{className:"cortex-location-input__map cortex-location-input__map--still",children:[I("div",{className:"cortex-location-input__canvas",ref:$,hidden:J}),J&&I("span",{className:"cortex-location-input__still-failed",children:N("translate_location_map_failed")})]}),c("div",{className:"cortex-location-input__body",children:[c("span",{className:"cortex-location-input__title",children:[I("svg",{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"})}),N("translate_location_shared")]}),I("span",{className:"cortex-location-input__coords",children:T_(_)})]})]})}function D8(){return c("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:[I("circle",{cx:"10",cy:"10",r:"5.5"}),I("circle",{cx:"10",cy:"10",r:"1.6",fill:"currentColor",stroke:"none"}),I("path",{d:"M10 1.5v3M10 15.5v3M1.5 10h3M15.5 10h3"})]})}import{jsx as w,jsxs as W_}from"react/jsx-runtime";var H8={[D0]:m6};function u6({message:_,toolCallPart:N,agentWorking:$}){let{config:J,addToolResult:X}=B(),Y=N.state==="input-complete"&&!$,Q=N.state==="approval-requested"&&!$,Z=J.toolComponents?.[N.name]??(Y||m(N.state)?H8[N.name]:void 0);return w("div",{className:"cortex-tool-call-animated",children:Z?w(Z,{toolCallPart:N,message:_,setOutput:(V)=>X(N.id,N.name,V)}):Y?w(F8,{toolCallPart:N}):w(h6,{toolCallPart:N,asking:Q})})}function F8({toolCallPart:_}){let{api:N,t:$,addToolResult:J,selectedThread:X,config:Y}=B(),Q=X?.id,[Z,V]=c6({phase:"initiating"}),[G]=c6(Y.trustSameOriginEmbeds),z=_0(void 0),q=_0({api:N,addToolResult:J,toolName:_.name});if(q.current={api:N,addToolResult:J,toolName:_.name},x6(()=>{if(!Q)return;let H=M1({initiate:()=>q.current.api.initiateToolCall(Q,_.id),onState:V,submit:(W)=>q.current.addToolResult(_.id,q.current.toolName,W)});z.current=H,H.start();let k=(W)=>H.handleMessage(W);return window.addEventListener("message",k),()=>{if(window.removeEventListener("message",k),H.dispose(),z.current===H)z.current=void 0}},[_.id,Q]),!Q||Z.phase==="unavailable"||Z.phase==="settling")return w(h6,{toolCallPart:_});let U=W_("div",{className:"cortex-client-tool-embed",children:[W_("div",{className:"cortex-client-tool-embed__bar",children:[w("span",{children:$("translate_client_tool_title")}),w("button",{type:"button",className:"cortex-client-tool-embed__cancel",onClick:()=>z.current?.cancel(),children:$("translate_client_tool_cancel")})]}),Z.phase==="embedded"?w("iframe",{className:"cortex-client-tool-embed__frame",src:Z.embedUrl,sandbox:k1(Z.embedUrl,window.location.origin,G),title:$("translate_client_tool_title"),ref:(H)=>z.current?.setSource(H?.contentWindow),onLoad:(H)=>{if(!O1(Z.embedUrl,window.location.origin,G)&&P1(H.currentTarget,window.location.origin))z.current?.terminate()}}):Z.phase==="error"?W_("div",{className:"cortex-client-tool-embed__status",children:[w("span",{children:$("translate_client_tool_failed")}),w("button",{type:"button",className:"cortex-client-tool-embed__retry",onClick:()=>void z.current?.start(),children:$("translate_client_tool_retry")})]}):w("div",{className:"cortex-client-tool-embed__status",children:$("translate_client_tool_loading")})]});return Z.phase==="embedded"&&Z.surface==="modal"?w(U8,{label:$("translate_client_tool_title"),onCancel:()=>z.current?.cancel(),children:U}):U}function U8({label:_,onCancel:N,children:$}){let J=_0(null);return x6(()=>{let X=J.current;return X?.showModal(),()=>X?.close()},[]),w("dialog",{ref:J,className:"cortex-client-tool-embed-dialog","aria-label":_,onCancel:(X)=>{X.preventDefault(),N()},children:$})}function h6({toolCallPart:_,asking:N=!1}){let{t:$,locale:J,respondToApproval:X}=B(),{state:Y,active:Q,gated:Z,titleKey:V,statement:G,rowCount:z}=U_(_),q=_.approval?.id??`approval_${_.id}`;return W_("div",{className:D("cortex-tool-pill",Z&&"cortex-tool-pill--gated",N&&"cortex-tool-pill--asking"),children:[W_("span",{className:"cortex-tool-pill__icon",children:[N?w("span",{className:"cortex-tool-pill__dot"}):null,w("span",{className:D("cortex-tool-pill__spinner",Q&&"cortex-tool-pill__spinner--visible")}),w("svg",{className:D("cortex-tool-pill__svg","cortex-tool-pill__svg--check",Y==="complete"&&"cortex-tool-pill__svg--visible"),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"})}),w("svg",{className:D("cortex-tool-pill__svg","cortex-tool-pill__svg--error",Y==="error"&&"cortex-tool-pill__svg--visible"),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:D("cortex-tool-pill__title",Y==="error"&&"cortex-tool-pill__title--error",Y==="starting"&&G&&"cortex-tool-pill__title--pending"),children:N?q1(_,J)??$("translate_approval_prompt"):G??$(V)}),z!==void 0?w("span",{className:"cortex-tool-pill__meta",children:$("translate_rows_read",{count:z})}):null,N?W_("span",{className:"cortex-tool-pill__actions",children:[w("button",{type:"button",className:"cortex-tool-pill__action cortex-tool-pill__action--approve",onClick:()=>void X(q,!0),children:$("translate_approve")}),w("button",{type:"button",className:"cortex-tool-pill__action",onClick:()=>void X(q,!1),children:$("translate_deny")})]}):null]})}import{jsx as N0}from"react/jsx-runtime";function l6({message:_,toolCallPart:N,agentWorking:$}){if(!m(N.state)&&!U_(N).statement){if(N.name==="queryGraph")return N0(I_,{activity:"graph"});if(N.name==="executeCode")return N0(I_,{activity:"code"})}return N0(u6,{toolCallPart:N,message:_,agentWorking:$})}import{jsx as B_,jsxs as L8}from"react/jsx-runtime";function p6(_){let{message:N,part:$,debugMode:J,animate:X,streaming:Y,agentWorking:Q,attachments:Z}=_,{t:V}=B();function G(){switch($.type){case"text":return B_(b6,{textPart:$,role:N.role,streaming:Y,attachments:Z});case"thinking":return J?B_(M6,{reasoningPart:$,streaming:Y}):B_(I_,{activity:"reasoning",className:"cortex-reasoning-animated"});case"tool-call":return J?B_(S6,{toolCallPart:$}):B_(l6,{toolCallPart:$,message:N,agentWorking:Q});default:return L8("p",{className:"cortex-unhandled-type",children:[V("translate_unhandled_type")," ",$.type]})}}return B_("div",{className:D("cortex-message-part",X&&"cortex-message-part--animated"),children:G()})}import{jsx as a,jsxs as $0}from"react/jsx-runtime";function P8({isUser:_,clipboardText:N,createdAt:$,revealedAt:J}){let{locale:X}=B();return $0("div",{className:D("cortex-message-actions",_&&"cortex-message-actions--user"),children:[N&&a(g,{value:N}),$&&a("time",{className:"cortex-message-actions__time",dateTime:$,children:p($,X,J)})]})}function M8({count:_,animate:N,onOpen:$}){let{t:J}=B();return a("button",{type:"button",className:D("cortex-tool-fold",N&&"cortex-message-part--animated"),onClick:$,children:J(_===1?"translate_one_more_step":"translate_n_more_steps",{count:_})})}function n6(_){let{message:N,parts:$,metadata:J,debugMode:X,animate:Y,isStreaming:Q,agentWorking:Z,closesTurn:V,fold:G,onOpenRun:z}=_,[q,U]=O8(Date.now),H=()=>U(Date.now()),k=N.role==="assistant",W=N.role==="user",O=Q?$.length-1:-1,F=J?.attachments??[],K=$.map((R)=>R.type).lastIndexOf("text"),L=(W||k)&&!Q&&K>=0,E=K<$.length-1?K:-1,P=L&&a(P8,{isUser:W,clipboardText:W1($),createdAt:J?.createdAt,revealedAt:q});return $0("div",{className:"cortex-message-parts",onMouseEnter:H,onFocus:H,children:[$.map((R,u)=>{let l=G?.get(R);return $0(k8,{children:[a(p6,{part:R,message:N,debugMode:X,animate:Y,streaming:u===O,agentWorking:Z,attachments:F}),l?.kind==="more"&&a(M8,{count:l.count,animate:Y,onOpen:()=>z(l.runId)}),u===E&&P]},N.parts.indexOf(R))}),F.length>0&&a(B6,{attachments:F,isUser:W}),J?.isAborted&&a(K6,{}),E===-1&&P,X&&J&&V&&a(P6,{messageId:N.id,isAssistant:k,metadata:J})]})}import{jsx as X_,jsxs as J0}from"react/jsx-runtime";function d6({firing:_,debugMode:N}){let{t:$,locale:J}=B();return J0("div",{className:N?"cortex-trigger-block cortex-trigger-block--debug":"cortex-trigger-block",children:[J0("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"})}),N&&X_("span",{children:$("translate_trigger_fired")}),X_("span",{className:"cortex-trigger-block__name",children:_.name}),X_("time",{className:"cortex-trigger-block__time",dateTime:_.firedAt,children:p(_.firedAt,J)})]}),N&&J0("details",{className:"cortex-trigger-block__payload",children:[X_("summary",{children:$("translate_trigger_payload")}),X_(i,{data:_.payload,expandDepth:2})]})]})}import{jsx as C_}from"react/jsx-runtime";var i6=A8(function(N){let{message:$,metadata:J,isStreaming:X,agentWorking:Y,closesTurn:Q,debugMode:Z,animate:V,fold:G,onOpenRun:z}=N,q=L_($.parts,{debugMode:Z,isStreaming:X,fold:G});if(J?.trigger)return C_("div",{className:"cortex-message",children:C_(d6,{firing:J.trigger,debugMode:Z})});if(q.length===0&&!J?.attachments?.length)return C_("div",{className:"cortex-message"});return C_("div",{className:"cortex-message",children:C_(n6,{message:$,parts:q,metadata:J,debugMode:Z,animate:V,isStreaming:X,agentWorking:Y,closesTurn:Q,fold:G,onOpenRun:z})})});import{jsx as a_}from"react/jsx-runtime";var E8=[{role:"user",lines:[13,9]},{role:"assistant",lines:[16,18,12]},{role:"user",lines:[11]},{role:"assistant",lines:[14,15]}];function r6(){return a_("div",{className:"cortex-widget__messages-skeleton",children:E8.map((_,N)=>a_("div",{className:`cortex-widget__msg-skel cortex-widget__msg-skel--${_.role}`,children:a_("div",{className:`cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--${_.role}`,children:_.lines.map(($)=>a_("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:`${$}rem`}},$))})},N))})}import{jsx as Y_,jsxs as S8,Fragment as C8}from"react/jsx-runtime";function w8(_,N,$){let J=D_(!0),X=D_(!0),Y=D_(!1);function Q(){if(Y.current)return;Y.current=!0,queueMicrotask(()=>{Y.current=!1;let Z=_.current;if(!Z)return;Z.scrollTop=Z.scrollHeight,X.current=!0,J.current=!1})}return t_(()=>{let Z=_.current,V=N.current;if(!$||!Z||!V)return;if(Q(),typeof ResizeObserver>"u")return;let G=0,z=new ResizeObserver(([q])=>{let U=q?.contentRect.height??0,H=U>G;if(G=U,H&&(J.current||X.current))Q()});return z.observe(V),()=>z.disconnect()},[$]),{settlePinned:()=>{if(J.current)Q()},pin:()=>{J.current=!0},onScroll:()=>{let Z=_.current;if(Z)X.current=Z.scrollHeight-Z.scrollTop-Z.clientHeight<100}}}function b8(_,N,$){let[J,X]=o6(!1);t_(()=>{X(!1),_.pin(),queueMicrotask(()=>X(!0))},[N]);let Y=$[$.length-1],Q=Y?.role==="user"?Y.id:void 0;return t_(()=>{if(Q)_.pin()},[Q]),t_(()=>{_.settlePinned()},[$]),J}function I8(_,N,$){let{config:J}=B(),[X,Y]=o6(new Set),Q=R8((z)=>Y((q)=>new Set(q).add(z)),[]),Z=D_(D1()).current,V=J.toolComponents;return{folds:y8(()=>Z(_,{agentWorking:N,debugMode:$,opened:X,foldable:(z)=>!V?.[z.name]}),[Z,_,N,$,X,V]),openRun:Q}}function a6(_){let{selectedThread:N}=B(),{messages:$,isAgentWorking:J,isLoadingMessages:X,hasPendingToolCalls:Y,messageMetadata:Q}=h_(),{capabilities:Z,composerRef:V}=_,G=D_(null),z=D_(null),q=!X||J,U=w8(G,z,q),H=b8(U,N?.id,$),k=J?B1($)?.id:void 0,{folds:W,openRun:O}=I8($,J,_.debugMode);return S8(C8,{children:[!q?Y_(r6,{}):Y_("div",{className:_.className,children:Y_("div",{ref:G,className:"cortex-message-list",onScroll:U.onScroll,children:Y_("div",{ref:z,className:"cortex-message-list__content",children:$.map((F,K)=>Y_(i6,{message:F,metadata:Q.get(F.id),isStreaming:F.id===k,agentWorking:J,fold:W.get(F.id),onOpenRun:O,closesTurn:F.role==="assistant"&&$[K+1]?.role!=="assistant",debugMode:_.debugMode,animate:H},F.id))})})}),J&&!Y&&Y_(z6,{}),!Y&&Y_(l_,{capabilities:Z,composerRef:V})]})}import{jsx as s_,jsxs as v8}from"react/jsx-runtime";function t6(_){let{debugMode:N,selectedThread:$}=B(),{screens:J}=_;return v8("div",{className:D("cortex-widget__screen",J.screen==="chat"&&"cortex-widget__screen--active",J.screen!=="chat"&&"cortex-widget__screen--right"),children:[s_(s0,{onToggleSidebar:J.toggleSidebar,onToggleDebug:_.onToggleDebug,onOpenHistory:J.openHistory}),$?s_(a6,{className:"cortex-widget__messages",debugMode:N,capabilities:_.capabilities,composerRef:_.composerRef}):s_(Z6,{onThreadSelected:_.onThreadSelected}),s_("div",{className:"cortex-widget__sidebar-backdrop",onClick:J.closeSidebar})]})}import{useState as m8}from"react";import{useEffect as X0,useRef as N2,useState as e_}from"react";import{useChat as j8}from"@tanstack/ai-react";import{useEffect as T8,useLayoutEffect as f8,useState as g8}from"react";function s6(_,N){let[$]=g8(_);return f8(()=>{return N.sessionRef.current=$,()=>{if(N.sessionRef.current===$)N.sessionRef.current=void 0}},[$]),T8(()=>{if(!N.pendingSendRef.current.length)return;let J=setTimeout(()=>{let X=N.pendingSendRef.current;N.pendingSendRef.current=[],(async()=>{for(let{prompt:Y,attachments:Q}of X)await $.send(Y,Q)})()});return()=>clearTimeout(J)},[$]),$}import{useRef as e6}from"react";function _2(_){let N=e6(_);N.current=_;let $=e6(Promise.resolve(void 0));async function J(X){let Y=N.current;if(!Y.isAlive()||X!==Y.threadId)return;return F1({api:Y.api,threadId:X,isStale:()=>!N.current.isAlive(),isStreaming:()=>N.current.isStreaming(),absorbMetadata:(Q)=>N.current.absorbMetadata(Q),setMessages:(Q)=>N.current.setMessages(Q)})}return function(Y){return $.current=$.current.then(()=>J(Y)),$.current}}function $2(_){let{thread:N,api:$}=_,J=N2(!0),[X,Y]=e_(!1),[Q,Z]=e_(()=>_.initialMetadata??new Map);function V(P){Z((R)=>new Map([...R,...P]))}let G=N2(null),z=_2({api:$,threadId:N.id,isAlive:()=>J.current,isStreaming:()=>G.current.chat.isLoading,absorbMetadata:V,setMessages:(P)=>G.current.chat.setMessages(P)}),[q]=e_(()=>r1({threadId:N.id,isAlive:()=>J.current,onToolCall:()=>G.current.props.configRef.current.hooks?.onToolCall,deliver:(P)=>G.current.chat.addToolResult(P),setRunning:(P)=>G.current.props.setRunning(N.id,P),reloadThreads:()=>G.current.props.reloadThreads(),refreshMessages:()=>z(N.id),onTurnFinished:()=>G.current.props.onTurnFinished(),onSendFailed:()=>G.current.props.onSendFailed()})),[U]=e_(()=>H1({api:$,thread:{id:N.id,isRunning:N.isRunning},mode:_.mode,onHydrated:(P,R)=>{if(!J.current)return;V(S_(P)),q.hydrated(R,N.isRunning)},setLoadingMessages:(P)=>{if(J.current)Y(P)}})),H=j8({threadId:N.id,persistence:!0,initialMessages:_.initialMessages,connection:U,onChunk:()=>{if(J.current)q.chunkArrived()},onError:()=>{if(J.current)q.streamFailed()}});G.current={chat:H,props:_,messageMetadata:Q};async function k(P,R){q.sendStarted();let u={id:k_(),role:"user",parts:[{type:"text",content:P}]},l={createdAt:new Date().toISOString(),attachments:R};Z(($1)=>new Map($1).set(u.id,l)),await G.current.chat.append(u)}async function W(){if(!G.current.chat.isLoading)return;let{aborted:P}=await $.abortStream(N.id).catch(()=>({aborted:!1}));if(!J.current)return;if(P)q.abortConfirmed();G.current.chat.stop()}function O(P,R,u){return G.current.chat.addToolResult({toolCallId:P,tool:R,output:u}).catch((l)=>{throw z(N.id),l})}function F(P,R){return A1(G.current.chat,P,R)}function K(P){if(G.current.chat.isLoading)return;if(P.isRunning){G.current.props.remount(P,G.current.chat.messages,G.current.messageMetadata);return}z(P.id)}X0(()=>{return J.current=!0,()=>{J.current=!1}},[]),s6(()=>({threadId:N.id,send:k,abort:W,addToolResult:O,respondToApproval:F,reattach:K,refreshMessages:(P)=>{z(P)}}),{sessionRef:_.sessionRef,pendingSendRef:_.pendingSendRef});let{messages:L,isLoading:E}=H;return X0(()=>{q.loadingChanged(E,()=>G.current.chat.messages)},[q,E]),X0(()=>{G.current.props.publish({messages:L,messageMetadata:Q,isAgentWorking:E,isLoadingMessages:X,hasPendingToolCalls:!E&&t(L).length>0})},[L,Q,E,X]),null}import{jsx as J2,jsxs as c8}from"react/jsx-runtime";function X2({selection:_,threads:N,children:$,...J}){let{session:X}=_,[Y,Q]=m8();if(!X)return J2(u_.Provider,{value:x_,children:$});let Z=`${X.thread.id}:${X.epoch}`,V=Y&&(Y.key===Z||X.mode==="reload")?Y.value:x_;return c8(u_.Provider,{value:V,children:[J2($2,{thread:X.thread,mode:X.mode,initialMessages:X.initialMessages,initialMetadata:X.initialMetadata,setRunning:N.setRunning,reloadThreads:N.reload,remount:_.remount,publish:(G)=>Q({key:Z,value:G}),...J},Z),$]})}import{jsx as A,jsxs as x,Fragment as x8}from"react/jsx-runtime";function Y2(_){let{locale:N,t:$,threads:J,selectedThread:X,deleteThread:Y}=B();return x("div",{className:_.className,children:[x("div",{className:"cortex-widget__threads-header",children:[A("button",{type:"button",onClick:()=>_.onBackRequested(),"aria-label":$("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"})})}),x("div",{children:[A("h2",{className:"cortex-widget__threads-title",children:$("translate_history")}),A("p",{className:"cortex-widget__threads-count",children:$(J?.length===1?"translate_one_conversation":"translate_n_conversations",{count:J?.length??0})})]}),x("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"})}),$("translate_new")]})]}),A("div",{className:"cortex-widget__threads-list",children:J===void 0?[1,2,3,4].map((Q)=>x("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+Q*12}%`}})})]},Q)):x(x8,{children:[J.map((Q)=>{let Z=Q.id===X?.id,V=p(Q.updatedAt,N);return x("button",{onClick:()=>_.onThreadSelected(Q),className:D("cortex-widget__thread-item",Z&&"cortex-widget__thread-item--active"),children:[A("div",{className:D("cortex-widget__thread-icon",Z&&"cortex-widget__thread-icon--active"),children:A("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:A("path",{d:C.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),x("div",{className:"cortex-widget__thread-info",children:[x("div",{className:"cortex-widget__thread-title-row",children:[A("p",{className:D("cortex-widget__thread-title",Z&&"cortex-widget__thread-title--active"),children:Q.title??$("translate_untitled")}),Q.isRunning&&x("span",{className:D("cortex-widget__thread-running",Z&&"cortex-widget__thread-running--active"),children:[A("span",{className:"cortex-widget__thread-running-dot"}),$("translate_running")]})]}),V&&A("p",{className:"cortex-widget__thread-time",children:V})]}),A("span",{role:"button",tabIndex:0,onClick:(G)=>{G.stopPropagation(),Y(Q.id)},onKeyDown:(G)=>{if(G.key!=="Enter"&&G.key!==" ")return;G.preventDefault(),G.stopPropagation(),Y(Q.id)},className:D("cortex-widget__thread-delete",Z&&"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:D("cortex-widget__thread-arrow",Z&&"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"})})]},Q.id)}),!J.length&&x("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:C.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),A("p",{className:"cortex-widget__threads-empty-title",children:$("translate_no_threads_yet")}),A("p",{className:"cortex-widget__threads-empty-subtitle",children:$("translate_start_a_new_conversation")}),A("button",{onClick:()=>_.onNewChatRequested(),className:"cortex-widget__new-chat-btn cortex-widget__new-chat-btn--empty-state",children:$("translate_new_chat")})]})]})})]})}import{jsx as G2,jsxs as u8}from"react/jsx-runtime";function Q2(_){_.preventDefault()}function Z2(_){let{screens:N}=_;return G2("div",{className:D("cortex-widget",_.className),"data-cortex-theme":_.theme,children:u8("div",{className:D("cortex-widget__container",_.viewMode==="full"&&"cortex-widget__container--full",N.sidebarOpen&&"cortex-widget__container--sidebar-open"),onDragOver:Q2,onDrop:Q2,children:[G2(Y2,{className:D("cortex-widget__screen",N.screen==="threads"&&"cortex-widget__screen--active",N.screen!=="threads"&&"cortex-widget__screen--left"),onThreadSelected:_.onThreadSelected,onNewChatRequested:_.onNewChat,onBackRequested:N.closeHistory}),_.children]})})}import{jsx as N1}from"react/jsx-runtime";function l8({config:_,className:N}){let $=V2(_);$.current=_;let[J]=_1(()=>G1(()=>$.current.transport)),X=r0(J),[Y,Q]=_1(!1),[Z,V]=_1();h8(()=>u1(_.theme,V),[_.theme]);let G=a0(),[z,q]=_1(0),U=m0(J,z),H=V2(null),k=p0({api:J,threads:X,getHooks:()=>$.current.hooks}),{sessionRef:W,selection:O,queue:F,send:K,pendingSendRef:L}=k,{selected:E,selectedRef:P}=O,R=d0({threads:X,selectedRef:P,sessionRef:W,deselect:O.deselect,onReconnect:()=>q((__)=>__+1)});n0({getConfig:()=>$.current,onEvent:R.onEvent,onMount:()=>void X.reload(),onReconnect:R.onReconnect});let u=l1(_.locale),l={config:_,locale:u,t:(__,W2)=>p1(u,__,W2),api:J,debugMode:Y,scheme:Z,capabilities:U,threads:X.threads,selectedThread:E,deleteThread:k.deleteThread,send:K,...i0(W),queue:F.value};function $1(){F.store.discardConsumed(),setTimeout(()=>H.current?.focusInput())}function z2(){F.store.restoreConsumed(P.current?.id)}function Y0(__){k.openThread(__),G.showChat()}function q2(){O.deselect(),G.showChat()}function K2(){Q((__)=>!__)}return N1(o1.Provider,{value:l,children:N1(Z2,{className:N,theme:_.theme,viewMode:_.viewMode??"helper",screens:G,onThreadSelected:Y0,onNewChat:q2,children:N1(X2,{selection:O,threads:X,api:J,configRef:$,sessionRef:W,pendingSendRef:L,onTurnFinished:$1,onSendFailed:z2,children:N1(t6,{screens:G,capabilities:U,composerRef:H,onToggleDebug:K2,onThreadSelected:Y0})})})})}export{l8 as CortexChatWidget};
|