@m6d/cortex-react 0.13.0 → 0.14.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 +22 -22
- package/dist/index.d.ts +11 -5
- package/dist/index.js +11 -11
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -39,7 +39,7 @@ Each widget is self-contained, so one page can render several widgets with diffe
|
|
|
39
39
|
| `viewMode` | `'helper' \| 'full'` | Compact panel or full layout with a sidebar (default: `'helper'`) |
|
|
40
40
|
| `theme` | `'light' \| 'dark' \| 'system'` | Color scheme (default: `'light'`) |
|
|
41
41
|
| `agentName` | `string \| { en, ar }` | Header title while no thread is selected (optional) |
|
|
42
|
-
| `
|
|
42
|
+
| `thread` | `string` | A thread id to open on mount (optional) |
|
|
43
43
|
| `mediaRenderers` | `Record<string, MediaRenderer>` | Replace or add the media fences the assistant can draw (optional) |
|
|
44
44
|
| `trustSameOriginEmbeds` | `boolean` | Allow embedded tool pages served from this page's own origin (default: `false`) |
|
|
45
45
|
| `hooks.onToolCall` | `(toolCall, context) => unknown` | Answers a client tool; return `undefined` for tools you do not own (optional) |
|
|
@@ -47,7 +47,7 @@ Each widget is self-contained, so one page can render several widgets with diffe
|
|
|
47
47
|
| `hooks.onThreadDeselected` | `(thread) => void \| Promise<void>` | Runs when a thread closes (optional) |
|
|
48
48
|
| `toolComponents` | `Record<string, ComponentType<CortexToolComponentInputs>>` | Custom React components for tool rendering (optional) |
|
|
49
49
|
|
|
50
|
-
`transport.getHeaders` returns the headers every call carries, usually a bearer `Authorization`. Called straight from another origin, the engine accepts only `Authorization` and the headers the widget sets itself; route anything else through a same-origin proxy. The WebSocket takes its `token` query param from a bearer `Authorization` header when there is one.
|
|
50
|
+
`transport.getHeaders` returns the headers every call carries, usually a bearer `Authorization`. Called straight from another origin, the engine accepts only `Authorization` and the headers the widget sets itself; route anything else through a same-origin proxy. The WebSocket takes its `token` query param from a bearer `Authorization` header when there is one. The debug toggle shows only when Cortex offers this caller the debug view: always to a console operator, and to everyone only where the engine runs with `ENGINE_DEBUG=true`. Anyone else gets only what the widget's normal view draws, and so does a `toolComponents` entry for one of the agent's server tools: the model's line for the user as the call's input, and only whether it failed (or a dataset read's row count) as its output.
|
|
51
51
|
|
|
52
52
|
## Custom parts
|
|
53
53
|
|
|
@@ -110,19 +110,19 @@ for typing your own rows and chips.
|
|
|
110
110
|
|
|
111
111
|
One header serves both screens; `screen` says which is showing.
|
|
112
112
|
|
|
113
|
-
| Field | Type | Description
|
|
114
|
-
| -------------- | --------------------- |
|
|
115
|
-
| `screen` | `'chat' \| 'threads'` | Which screen the header is on
|
|
116
|
-
| `viewMode` | `'helper' \| 'full'` | The configured view mode
|
|
117
|
-
| `title` | `string \| null` | The open thread's title; `null` on a new chat
|
|
118
|
-
| `agentName` | `string \| undefined` | `agentName` in the widget's locale
|
|
119
|
-
| `threadCount` | `number \| undefined` | How many conversations the history lists; undefined while it loads
|
|
120
|
-
| `isWorking` | `boolean` | The agent is answering
|
|
121
|
-
| `debug` | `{ shown, on }` | Whether
|
|
122
|
-
| `newChat` | `() => void` | Starts a new chat
|
|
123
|
-
| `openHistory` | `() => void` | Shows the history: its screen, or the sidebar in full mode
|
|
124
|
-
| `closeHistory` | `() => void` | Returns to the open chat
|
|
125
|
-
| `toggleDebug` | `() => void` | Switches debug mode
|
|
113
|
+
| Field | Type | Description |
|
|
114
|
+
| -------------- | --------------------- | -------------------------------------------------------------------- |
|
|
115
|
+
| `screen` | `'chat' \| 'threads'` | Which screen the header is on |
|
|
116
|
+
| `viewMode` | `'helper' \| 'full'` | The configured view mode |
|
|
117
|
+
| `title` | `string \| null` | The open thread's title; `null` on a new chat |
|
|
118
|
+
| `agentName` | `string \| undefined` | `agentName` in the widget's locale |
|
|
119
|
+
| `threadCount` | `number \| undefined` | How many conversations the history lists; undefined while it loads |
|
|
120
|
+
| `isWorking` | `boolean` | The agent is answering |
|
|
121
|
+
| `debug` | `{ shown, on }` | Whether Cortex offers the debug view, and whether it is on |
|
|
122
|
+
| `newChat` | `() => void` | Starts a new chat; absent until Cortex confirms the caller may write |
|
|
123
|
+
| `openHistory` | `() => void` | Shows the history: its screen, or the sidebar in full mode |
|
|
124
|
+
| `closeHistory` | `() => void` | Returns to the open chat |
|
|
125
|
+
| `toggleDebug` | `() => void` | Switches debug mode |
|
|
126
126
|
|
|
127
127
|
### `landing`
|
|
128
128
|
|
|
@@ -143,13 +143,13 @@ landing for it.
|
|
|
143
143
|
|
|
144
144
|
The history's list. Its header is the `header` slot.
|
|
145
145
|
|
|
146
|
-
| Field | Type | Description
|
|
147
|
-
| ------------------ | --------------------------------- |
|
|
148
|
-
| `threads` | `ThreadSummary[] \| undefined` | Newest first; `undefined` while the first load is out
|
|
149
|
-
| `selectedThreadId` | `string \| undefined` | The open thread's id; `undefined` on a new chat
|
|
150
|
-
| `openThread` | `(thread: ThreadSummary) => void` | Opens a thread
|
|
151
|
-
| `deleteThread` | `(threadId: string) => void` | Deletes a thread
|
|
152
|
-
| `newChat` | `() => void` | Starts a new chat
|
|
146
|
+
| Field | Type | Description |
|
|
147
|
+
| ------------------ | --------------------------------- | -------------------------------------------------------------------- |
|
|
148
|
+
| `threads` | `ThreadSummary[] \| undefined` | Newest first; `undefined` while the first load is out |
|
|
149
|
+
| `selectedThreadId` | `string \| undefined` | The open thread's id; `undefined` on a new chat |
|
|
150
|
+
| `openThread` | `(thread: ThreadSummary) => void` | Opens a thread |
|
|
151
|
+
| `deleteThread` | `(threadId: string) => void` | Deletes a thread; absent until Cortex confirms the caller may write |
|
|
152
|
+
| `newChat` | `() => void` | Starts a new chat; absent until Cortex confirms the caller may write |
|
|
153
153
|
|
|
154
154
|
## Theming
|
|
155
155
|
|
package/dist/index.d.ts
CHANGED
|
@@ -121,7 +121,11 @@ export type CortexConfig = {
|
|
|
121
121
|
* or a map keyed by locale (`{ en: 'Support', ar: 'الدعم' }`).
|
|
122
122
|
*/
|
|
123
123
|
agentName?: Localized<string>;
|
|
124
|
-
|
|
124
|
+
/**
|
|
125
|
+
* A thread to open when the widget mounts, by id, once the thread list holds
|
|
126
|
+
* it: a deep link into one conversation, such as the console's inspector.
|
|
127
|
+
*/
|
|
128
|
+
thread?: string;
|
|
125
129
|
/**
|
|
126
130
|
* Render embedded tool pages served from this page's own origin with their
|
|
127
131
|
* full identity — which, same-origin, means no effective sandbox at all: such
|
|
@@ -149,12 +153,13 @@ export type CortexHeaderContext = {
|
|
|
149
153
|
/** How many conversations the history lists; undefined while the first load is out. */
|
|
150
154
|
threadCount: number | undefined;
|
|
151
155
|
isWorking: boolean;
|
|
152
|
-
/** Whether
|
|
156
|
+
/** Whether Cortex offers this caller the debug view, and whether it is on. */
|
|
153
157
|
debug: {
|
|
154
158
|
shown: boolean;
|
|
155
159
|
on: boolean;
|
|
156
160
|
};
|
|
157
|
-
|
|
161
|
+
/** Absent until the handshake says the caller may write; an operator inspecting a thread only reads. */
|
|
162
|
+
newChat?: () => void;
|
|
158
163
|
/** Shows the history: the history screen, or in full mode the sidebar where it is hidden. */
|
|
159
164
|
openHistory: () => void;
|
|
160
165
|
/** Returns to the open chat from wherever `openHistory` went. */
|
|
@@ -192,8 +197,9 @@ export type CortexThreadListContext = {
|
|
|
192
197
|
/** The open thread's id; undefined on a new chat. */
|
|
193
198
|
selectedThreadId: string | undefined;
|
|
194
199
|
openThread: (thread: ThreadSummary) => void;
|
|
195
|
-
|
|
196
|
-
|
|
200
|
+
/** Both absent until the handshake says the caller may write; an operator inspecting a thread only reads. */
|
|
201
|
+
deleteThread?: (threadId: string) => void;
|
|
202
|
+
newChat?: () => void;
|
|
197
203
|
};
|
|
198
204
|
/** Each part of the widget a consumer can draw itself, with the context it receives. */
|
|
199
205
|
export type CortexSlotContexts<View> = {
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var I5=Object.create;var{getPrototypeOf:y5,defineProperty:Q6,getOwnPropertyNames:S5}=Object;var C5=Object.prototype.hasOwnProperty;var M_=(_,$,Z)=>{Z=_!=null?I5(y5(_)):{};let Q=$||!_||!_.__esModule?Q6(Z,"default",{value:_,enumerable:!0}):Z;for(let X of S5(_))if(!C5.call(Q,X))Q6(Q,X,{get:()=>_[X],enumerable:!0});return Q};var A_=((_)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(_,{get:($,Z)=>(typeof require<"u"?require:$)[Z]}):_)(function(_){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+_+'" is not supported')});import{useEffect as h3,useRef as E5,useState as k1}from"react";var S1=["en","ar"];var x_=["image/png","image/jpeg","image/webp","application/pdf"],X6=10485760;var C1=5;function J6(_){if(!x_.some(($)=>$===_.type))return"type";if(_.size>10485760)return"size";if(_.name.length>255)return"name";return"ok"}var Y6=["executeCode","queryDataset","describeDataset"],b1="approvalTitle";function G1(_){return _.metadata?.cortex??void 0}function w1(_){return{..._,role:_.role==="trigger"?"user":_.role}}var G6="clientToolAnswers";function V6(_){return _.approval?.id??`approval_${_.id}`}var T1="X-Cortex-Timezone";function v1(_){let $=_.getHeaders();return $ instanceof Promise?$.then(z6):Promise.resolve(z6($))}function z6(_){let $={..._},Z=b5(),Q=Object.keys($).some((X)=>X.toLowerCase()===T1.toLowerCase());if(Z&&!Q)$[T1]=Z;return $}function b5(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function w5(_,$){let Z=_.baseUrl;return(typeof Z==="string"?Z:Z()).replace(/\/$/,"")+$}function T5(_){let $=_?.match(/filename\*\s*=\s*[^']*'[^']*'([^;\r\n]+)/i)?.[1]?.trim().replace(/^"|"$/g,"");if($)try{return decodeURIComponent($)}catch{}return _?.match(/filename\s*=\s*"?([^";\r\n]+)"?/i)?.[1]}function j1(_){function $(){return v1(_())}function Z(X){return w5(_(),X)}async function Q(X,J){let Y=new Headers(await $());if(new Headers(J?.headers).forEach((V,K)=>{Y.set(K,V)}),J?.body instanceof FormData)Y.delete("Content-Type");else if(!Y.has("Content-Type"))Y.set("Content-Type","application/json");let G=await fetch(Z(X),{...J,headers:Y});if(!G.ok)throw Error(`HTTP ${G.status}: ${G.statusText}`);let z=await G.text();return z?JSON.parse(z):void 0}return{getCapabilities(){return Q("/capabilities")},listThreads(){return Q("/threads")},createThread(){let X=_().threadBody;return Q("/threads",{method:"POST",...X&&{body:JSON.stringify(X)}})},deleteThread(X){return Q(`/threads/${X}`,{method:"DELETE"})},listMessages(X){return Q(`/threads/${X}/messages`)},listLlmRequests(X,J){return Q(`/threads/${X}/messages/${J}/llm-requests`)},abortStream(X){return Q(`/chat/${X}/abort`,{method:"POST"})},initiateToolCall(X,J){return Q(`/chat/${X}/tools/${J}/initiate`,{method:"POST"})},uploadAttachment(X,J){let Y=new FormData;return Y.append("file",J),Q(`/threads/${X}/files`,{method:"POST",body:Y})},deleteAttachment(X){return Q(`/files/${X}`,{method:"DELETE"})},async downloadAttachment(X){let J=await fetch(Z(`/files/${X}`),{headers:await $()});if(!J.ok)throw Error(`HTTP ${J.status}: ${J.statusText}`);return{blob:await J.blob(),name:T5(J.headers.get("Content-Disposition"))??X}},resolveHeaders:$,resolveUrl:Z}}function E_(_,$){if(_===void 0||typeof _==="string"||Array.isArray(_))return _;let Z=_;return Z[$]??Z.en??Object.values(Z)[0]}var K6={translate_history:"السجل",translate_back:"رجوع",translate_greeting:"بماذا يمكنني مساعدتك اليوم؟",translate_conversations:{zero:"لا محادثات",one:"محادثة واحدة",two:"محادثتان",few:"{{count}} محادثات",many:"{{count}} محادثة",other:"{{count}} محادثة"},translate_no_threads_yet:"لا توجد محادثات بعد",translate_start_a_new_conversation:"ابدأ محادثة جديدة",translate_untitled:"بدون عنوان",translate_new_chat:"محادثة جديدة",translate_normal:"عادي",translate_debug:"تصحيح",translate_type_a_message:"اكتب رسالة...",translate_completed:"مكتمل",translate_attach_files:"إرفاق ملفات",translate_drop_files_here:"أفلت ملفاتك هنا...",translate_remove_attachment:"إزالة المرفق",translate_attachment_rejected:"لا يمكن إرفاق هذا الملف",translate_attachment_rejected_type:"يمكن إرفاق ملفات {{types}} فقط",translate_attachment_rejected_size:"الحد الأقصى لحجم الملف {{size}} ميغابايت",translate_attachment_rejected_name:"اسم الملف طويل جدًا",translate_attachment_rejected_count:{zero:"لا يمكن إرفاق ملفات بالرسالة",one:"يمكن إرفاق ملف واحد كحد أقصى لكل رسالة",two:"يمكن إرفاق ملفين كحد أقصى لكل رسالة",few:"يمكن إرفاق {{count}} ملفات كحد أقصى لكل رسالة",many:"يمكن إرفاق {{count}} ملفًا كحد أقصى لكل رسالة",other:"يمكن إرفاق {{count}} ملف كحد أقصى لكل رسالة"},translate_attachment_caption:"من فضلك اطّلع على الملفات المرفقة.",translate_download:"تنزيل",translate_tool_status:"جارٍ تنفيذ خطوة…",translate_tool_done:"اكتملت الخطوة",translate_tool_cancelled:"أُلغيت الخطوة",translate_rows:{zero:"لا صفوف",one:"صف واحد",two:"صفان",few:"{{count}} صفوف",many:"{{count}} صفًا",other:"{{count}} صف"},translate_more_steps:{zero:"ولا خطوات أخرى",one:"وخطوة أخرى",two:"وخطوتان أخريان",few:"و{{count}} خطوات أخرى",many:"و{{count}} خطوة أخرى",other:"و{{count}} خطوة أخرى"},translate_tool_error:"حدث خطأ",translate_attachment_status:"جارٍ قراءة الملف المرفق…",translate_attachment_done:"تمت قراءة الملف المرفق",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_error:"خطأ",translate_approval_pending:"وافق على الطلب أعلاه أو ارفضه أولًا.",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_access_refused:"لم يقبل هذا الوكيل تسجيل دخولك.",translate_agent_unreachable:"تعذّر الوصول إلى هذا الوكيل الآن. نعيد المحاولة...",translate_agent_missing:"هذا الوكيل غير متاح.",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_pending_report:"جارٍ كتابة التقرير",translate_media_cut_off:"انقطع هذا المقطع قبل اكتماله.",translate_media_failed:"تعذر عرض هذا المقطع.",translate_media_source:"المصدر",translate_media_pending:"جارٍ الرسم",translate_media_mermaid:"مخطط",translate_media_vega_lite:"رسم بياني",translate_media_map:"خريطة",translate_media_report:"تقرير",translate_media:"معاينة",translate_image_unavailable:"الصورة غير متاحة",translate_image_unavailable_alt:"الصورة غير متاحة: {{alt}}",translate_image:"صورة",translate_send:"إرسال",translate_stop:"إيقاف",translate_delete_conversation:"حذف المحادثة",translate_table:"جدول",translate_expand:"توسيع {{name}}",translate_table_export:"تصدير إلى Excel",translate_close:"إغلاق",translate_approval_needed:"بحاجة إلى موافقتك",translate_approval_action:"تنفيذ {{tool}}",translate_approved_failed:"تمت الموافقة لكنه فشل",translate_approval_cancelled:"لم يُتخذ قرار"};var W6={translate_history:"History",translate_back:"Back",translate_greeting:"What can I help you with today?",translate_conversations:{one:"1 conversation",other:"{{count}} conversations"},translate_no_threads_yet:"No threads yet",translate_start_a_new_conversation:"Start a new conversation",translate_untitled:"Untitled",translate_new_chat:"New Chat",translate_normal:"Normal",translate_debug:"Debug",translate_type_a_message:"Type a message...",translate_completed:"Completed",translate_attach_files:"Attach files",translate_drop_files_here:"Drop your files here...",translate_remove_attachment:"Remove attachment",translate_attachment_rejected:"This file cannot be attached",translate_attachment_rejected_type:"Only {{types}} files can be attached",translate_attachment_rejected_size:"Files can be up to {{size}} MB",translate_attachment_rejected_name:"The file name is too long",translate_attachment_rejected_count:{one:"Up to 1 file per message",other:"Up to {{count}} files per message"},translate_attachment_caption:"Please take a look at the attached files.",translate_download:"Download",translate_tool_status:"Running a step...",translate_tool_done:"Step completed",translate_tool_cancelled:"Step cancelled",translate_rows:{one:"1 row",other:"{{count}} rows"},translate_more_steps:{one:"and 1 more step",other:"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_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_error:"Error",translate_approval_pending:"Approve or deny the request above first.",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_access_refused:"This agent did not accept your sign-in.",translate_agent_unreachable:"This agent cannot be reached right now. Trying again...",translate_agent_missing:"This agent is not available.",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_pending_report:"Writing report",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_media_mermaid:"Diagram",translate_media_vega_lite:"Chart",translate_media_map:"Map",translate_media_report:"Report",translate_media:"Preview",translate_image_unavailable:"Image unavailable",translate_image_unavailable_alt:"Image unavailable: {{alt}}",translate_image:"Image",translate_send:"Send",translate_stop:"Stop",translate_delete_conversation:"Delete conversation",translate_table:"Table",translate_expand:"Expand {{name}}",translate_table_export:"Export to Excel",translate_close:"Close",translate_approval_needed:"Needs your approval",translate_approval_action:"Run {{tool}}",translate_approved_failed:"Approved, but it failed",translate_approval_cancelled:"Not decided"};var f5={en:W6,ar:K6};function f1(_){return _&&S1.includes(_)?_:S1[0]}function o(_,$,Z){let Q=f5[_][$],X=typeof Q==="string"?Q:Q[new Intl.PluralRules(_).select(Number(Z?.count))]??Q.other;if(!Z)return X;return X.replace(/\{\{\s*(\w+)\s*\}\}/g,(J,Y)=>(Y in Z)?String(Z[Y]):J)}function g1(_,$,Z){let Q=_!==void 0&&_.messages!==!1;return{greeting:_===void 0?"":E_(_.greeting,$)||o($,"translate_greeting"),suggestions:Q&&E_(_.suggestions,$)||[],send:(X)=>{if(Q)Z(X)}}}var g5=["completed","cancelled","failed"],V1="requestLocation";function N6(_,$,Z){if($!==Z)return null;if(typeof _!=="object"||_===null)return null;let Q=_;if(Q.type!=="cortex:client-tool")return null;let X=g5.find((Y)=>Y===Q.status);if(!X)return null;let J=Q.reference;return{type:"cortex:client-tool",status:X,...typeof J==="string"?{reference:J}:{},...Q.result!==void 0?{result:Q.result}:{}}}var m5=new Set(["complete","error"]);function p(_){return m5.has(_)}function z_(_){return(x5(_)?.parts??[]).filter((Z)=>Z.type==="tool-call"&&!p(Z.state))}function m1(_){for(let $=_.length-1;$>=0;$-=1){let Z=_[$];if(Z?.parts.some((X)=>X.type==="tool-call"&&X.state==="approval-requested"))return!0;if(Z?.role==="user")return!1}return!1}function h_(_){let $=_.at(-1);if($?.role!=="assistant")return;let Z=$.parts.at(-1),Q=Z?.type==="tool-call"||Z?.type==="tool-result",X=$.parts.every((J)=>J.type!=="tool-call"||p(J.state));return Q&&X?void 0:$}function x5(_){for(let $=_.length-1;$>=0;$-=1){let Z=_[$];if(Z?.role==="assistant")return Z}return}var h5={complete:"success",error:"error","approval-requested":"approval","approval-responded":"approval","awaiting-input":"pending","input-streaming":"pending","input-complete":"pending"},u5={"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 x1(_){let{state:$,approval:Z}=_;return{modifier:h5[$],labelKey:Z?.approved===!1?"translate_declined":$==="approval-responded"&&Z?.approved?"translate_approved":u5[$],pulse:$==="awaiting-input"||$==="input-streaming"?"default":$==="approval-requested"?"violet":void 0}}function h1(_){let $=_.output;if($===void 0||$===null)return"";if(typeof $==="string")return $;return JSON.stringify($,null,2)}var H6={code:"javascript"};function u1(_){let $=_&&typeof _==="object"?_:null,Z=$?Object.entries(H6).flatMap(([X,J])=>{let Y=$[X];return typeof Y==="string"?[{key:X,lang:J,value:Y.replace(/\\n/g,`
|
|
2
|
-
`)}]:[]}):[],Q=_;if($){let X=Object.fromEntries(Object.entries($).filter(([J])=>!Object.hasOwn(
|
|
1
|
+
var w5=Object.create;var{getPrototypeOf:T5,defineProperty:Q6,getOwnPropertyNames:v5}=Object;var j5=Object.prototype.hasOwnProperty;var M_=(_,$,Z)=>{Z=_!=null?w5(T5(_)):{};let Q=$||!_||!_.__esModule?Q6(Z,"default",{value:_,enumerable:!0}):Z;for(let X of v5(_))if(!j5.call(Q,X))Q6(Q,X,{get:()=>_[X],enumerable:!0});return Q};var A_=((_)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(_,{get:($,Z)=>(typeof require<"u"?require:$)[Z]}):_)(function(_){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+_+'" is not supported')});import{useEffect as d3,useRef as y5,useState as k1}from"react";var S1=["en","ar"];var x_=["image/png","image/jpeg","image/webp","application/pdf"],J6=10485760;var C1=5;function Y6(_){if(!x_.some(($)=>$===_.type))return"type";if(_.size>10485760)return"size";if(_.name.length>255)return"name";return"ok"}var G6=["executeCode","queryDataset","describeDataset"],X6="approvalTitle";function V6(_){if(!_||typeof _!=="object"||!(X6 in _))return;let $=_[X6];return typeof $==="string"&&$.trim()?$.trim():void 0}function G1(_){return _.metadata?.cortex??void 0}function b1(_){return{..._,role:_.role==="trigger"?"user":_.role}}var z6="clientToolAnswers";function K6(_){return _.approval?.id??`approval_${_.id}`}var w1="X-Cortex-Timezone",W6="X-Cortex-Operator",N6="X-Cortex-Inspect";function T1(_){let $=_.getHeaders();return $ instanceof Promise?$.then(H6):Promise.resolve(H6($))}function H6(_){let $={..._},Z=f5(),Q=Object.keys($).some((X)=>X.toLowerCase()===w1.toLowerCase());if(Z&&!Q)$[w1]=Z;return $}function f5(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function g5(_,$){let Z=_.baseUrl;return(typeof Z==="string"?Z:Z()).replace(/\/$/,"")+$}function m5(_){let $=_?.match(/filename\*\s*=\s*[^']*'[^']*'([^;\r\n]+)/i)?.[1]?.trim().replace(/^"|"$/g,"");if($)try{return decodeURIComponent($)}catch{}return _?.match(/filename\s*=\s*"?([^";\r\n]+)"?/i)?.[1]}function v1(_){function $(){return T1(_())}function Z(X){return g5(_(),X)}async function Q(X,J){let Y=new Headers(await $());if(new Headers(J?.headers).forEach((z,K)=>{Y.set(K,z)}),J?.body instanceof FormData)Y.delete("Content-Type");else if(!Y.has("Content-Type"))Y.set("Content-Type","application/json");let G=await fetch(Z(X),{...J,headers:Y});if(!G.ok)throw Error(`HTTP ${G.status}: ${G.statusText}`);let V=await G.text();return V?JSON.parse(V):void 0}return{getCapabilities(){return Q("/capabilities")},listThreads(){return Q("/threads")},createThread(){let X=_().threadBody;return Q("/threads",{method:"POST",...X&&{body:JSON.stringify(X)}})},deleteThread(X){return Q(`/threads/${X}`,{method:"DELETE"})},listMessages(X){return Q(`/threads/${X}/messages`)},listLlmRequests(X,J){return Q(`/threads/${X}/messages/${J}/llm-requests`)},abortStream(X){return Q(`/chat/${X}/abort`,{method:"POST"})},initiateToolCall(X,J){return Q(`/chat/${X}/tools/${J}/initiate`,{method:"POST"})},uploadAttachment(X,J){let Y=new FormData;return Y.append("file",J),Q(`/threads/${X}/files`,{method:"POST",body:Y})},deleteAttachment(X){return Q(`/files/${X}`,{method:"DELETE"})},async downloadAttachment(X){let J=await fetch(Z(`/files/${X}`),{headers:await $()});if(!J.ok)throw Error(`HTTP ${J.status}: ${J.statusText}`);return{blob:await J.blob(),name:m5(J.headers.get("Content-Disposition"))??X}},resolveHeaders:$,resolveUrl:Z}}function E_(_,$){if(_===void 0||typeof _==="string"||Array.isArray(_))return _;let Z=_;return Z[$]??Z.en??Object.values(Z)[0]}var q6={translate_history:"السجل",translate_back:"رجوع",translate_greeting:"بماذا يمكنني مساعدتك اليوم؟",translate_conversations:{zero:"لا محادثات",one:"محادثة واحدة",two:"محادثتان",few:"{{count}} محادثات",many:"{{count}} محادثة",other:"{{count}} محادثة"},translate_no_threads_yet:"لا توجد محادثات بعد",translate_start_a_new_conversation:"ابدأ محادثة جديدة",translate_untitled:"بدون عنوان",translate_new_chat:"محادثة جديدة",translate_normal:"عادي",translate_debug:"تصحيح",translate_type_a_message:"اكتب رسالة...",translate_completed:"مكتمل",translate_attach_files:"إرفاق ملفات",translate_drop_files_here:"أفلت ملفاتك هنا...",translate_remove_attachment:"إزالة المرفق",translate_attachment_rejected:"لا يمكن إرفاق هذا الملف",translate_attachment_rejected_type:"يمكن إرفاق ملفات {{types}} فقط",translate_attachment_rejected_size:"الحد الأقصى لحجم الملف {{size}} ميغابايت",translate_attachment_rejected_name:"اسم الملف طويل جدًا",translate_attachment_rejected_count:{zero:"لا يمكن إرفاق ملفات بالرسالة",one:"يمكن إرفاق ملف واحد كحد أقصى لكل رسالة",two:"يمكن إرفاق ملفين كحد أقصى لكل رسالة",few:"يمكن إرفاق {{count}} ملفات كحد أقصى لكل رسالة",many:"يمكن إرفاق {{count}} ملفًا كحد أقصى لكل رسالة",other:"يمكن إرفاق {{count}} ملف كحد أقصى لكل رسالة"},translate_attachment_caption:"من فضلك اطّلع على الملفات المرفقة.",translate_download:"تنزيل",translate_tool_status:"جارٍ تنفيذ خطوة…",translate_tool_done:"اكتملت الخطوة",translate_tool_cancelled:"أُلغيت الخطوة",translate_rows:{zero:"لا صفوف",one:"صف واحد",two:"صفان",few:"{{count}} صفوف",many:"{{count}} صفًا",other:"{{count}} صف"},translate_more_steps:{zero:"ولا خطوات أخرى",one:"وخطوة أخرى",two:"وخطوتان أخريان",few:"و{{count}} خطوات أخرى",many:"و{{count}} خطوة أخرى",other:"و{{count}} خطوة أخرى"},translate_tool_error:"حدث خطأ",translate_attachment_status:"جارٍ قراءة الملف المرفق…",translate_attachment_done:"تمت قراءة الملف المرفق",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_error:"خطأ",translate_approval_pending:"وافق على الطلب أعلاه أو ارفضه أولًا.",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_read_only:"أنت تطّلع على هذه المحادثة. لا يمكن إرسال شيء من هنا.",translate_access_refused:"لم يقبل هذا الوكيل تسجيل دخولك.",translate_agent_unreachable:"تعذّر الوصول إلى هذا الوكيل الآن. نعيد المحاولة...",translate_agent_missing:"هذا الوكيل غير متاح.",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_pending_report:"جارٍ كتابة التقرير",translate_media_cut_off:"انقطع هذا المقطع قبل اكتماله.",translate_media_failed:"تعذر عرض هذا المقطع.",translate_media_source:"المصدر",translate_media_pending:"جارٍ الرسم",translate_media_mermaid:"مخطط",translate_media_vega_lite:"رسم بياني",translate_media_map:"خريطة",translate_media_report:"تقرير",translate_media:"معاينة",translate_image_unavailable:"الصورة غير متاحة",translate_image_unavailable_alt:"الصورة غير متاحة: {{alt}}",translate_image:"صورة",translate_send:"إرسال",translate_stop:"إيقاف",translate_delete_conversation:"حذف المحادثة",translate_table:"جدول",translate_expand:"توسيع {{name}}",translate_table_export:"تصدير إلى Excel",translate_close:"إغلاق",translate_approval_needed:"بحاجة إلى موافقتك",translate_approval_action:"تنفيذ {{tool}}",translate_approved_failed:"تمت الموافقة لكنه فشل",translate_approval_cancelled:"لم يُتخذ قرار"};var B6={translate_history:"History",translate_back:"Back",translate_greeting:"What can I help you with today?",translate_conversations:{one:"1 conversation",other:"{{count}} conversations"},translate_no_threads_yet:"No threads yet",translate_start_a_new_conversation:"Start a new conversation",translate_untitled:"Untitled",translate_new_chat:"New Chat",translate_normal:"Normal",translate_debug:"Debug",translate_type_a_message:"Type a message...",translate_completed:"Completed",translate_attach_files:"Attach files",translate_drop_files_here:"Drop your files here...",translate_remove_attachment:"Remove attachment",translate_attachment_rejected:"This file cannot be attached",translate_attachment_rejected_type:"Only {{types}} files can be attached",translate_attachment_rejected_size:"Files can be up to {{size}} MB",translate_attachment_rejected_name:"The file name is too long",translate_attachment_rejected_count:{one:"Up to 1 file per message",other:"Up to {{count}} files per message"},translate_attachment_caption:"Please take a look at the attached files.",translate_download:"Download",translate_tool_status:"Running a step...",translate_tool_done:"Step completed",translate_tool_cancelled:"Step cancelled",translate_rows:{one:"1 row",other:"{{count}} rows"},translate_more_steps:{one:"and 1 more step",other:"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_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_error:"Error",translate_approval_pending:"Approve or deny the request above first.",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_read_only:"You're viewing this conversation. Nothing can be sent from here.",translate_access_refused:"This agent did not accept your sign-in.",translate_agent_unreachable:"This agent cannot be reached right now. Trying again...",translate_agent_missing:"This agent is not available.",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_pending_report:"Writing report",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_media_mermaid:"Diagram",translate_media_vega_lite:"Chart",translate_media_map:"Map",translate_media_report:"Report",translate_media:"Preview",translate_image_unavailable:"Image unavailable",translate_image_unavailable_alt:"Image unavailable: {{alt}}",translate_image:"Image",translate_send:"Send",translate_stop:"Stop",translate_delete_conversation:"Delete conversation",translate_table:"Table",translate_expand:"Expand {{name}}",translate_table_export:"Export to Excel",translate_close:"Close",translate_approval_needed:"Needs your approval",translate_approval_action:"Run {{tool}}",translate_approved_failed:"Approved, but it failed",translate_approval_cancelled:"Not decided"};var u5={en:B6,ar:q6};function j1(_){return _&&S1.includes(_)?_:S1[0]}function a(_,$,Z){let Q=u5[_][$],X=typeof Q==="string"?Q:Q[new Intl.PluralRules(_).select(Number(Z?.count))]??Q.other;if(!Z)return X;return X.replace(/\{\{\s*(\w+)\s*\}\}/g,(J,Y)=>(Y in Z)?String(Z[Y]):J)}function f1(_,$,Z){let Q=_!==void 0&&_.messages!==!1;return{greeting:_===void 0?"":E_(_.greeting,$)||a($,"translate_greeting"),suggestions:Q&&E_(_.suggestions,$)||[],send:(X)=>{if(Q)Z(X)}}}var c5=["completed","cancelled","failed"],V1="requestLocation";function D6(_,$,Z){if($!==Z)return null;if(typeof _!=="object"||_===null)return null;let Q=_;if(Q.type!=="cortex:client-tool")return null;let X=c5.find((Y)=>Y===Q.status);if(!X)return null;let J=Q.reference;return{type:"cortex:client-tool",status:X,...typeof J==="string"?{reference:J}:{},...Q.result!==void 0?{result:Q.result}:{}}}var p5=new Set(["complete","error"]);function p(_){return p5.has(_)}function z_(_){return(d5(_)?.parts??[]).filter((Z)=>Z.type==="tool-call"&&!p(Z.state))}function g1(_){for(let $=_.length-1;$>=0;$-=1){let Z=_[$];if(Z?.parts.some((X)=>X.type==="tool-call"&&X.state==="approval-requested"))return!0;if(Z?.role==="user")return!1}return!1}function h_(_){let $=_.at(-1);if($?.role!=="assistant")return;let Z=$.parts.at(-1),Q=Z?.type==="tool-call"||Z?.type==="tool-result",X=$.parts.every((J)=>J.type!=="tool-call"||p(J.state));return Q&&X?void 0:$}function d5(_){for(let $=_.length-1;$>=0;$-=1){let Z=_[$];if(Z?.role==="assistant")return Z}return}var l5={complete:"success",error:"error","approval-requested":"approval","approval-responded":"approval","awaiting-input":"pending","input-streaming":"pending","input-complete":"pending"},i5={"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 m1(_){let{state:$,approval:Z}=_;return{modifier:l5[$],labelKey:Z?.approved===!1?"translate_declined":$==="approval-responded"&&Z?.approved?"translate_approved":i5[$],pulse:$==="awaiting-input"||$==="input-streaming"?"default":$==="approval-requested"?"violet":void 0}}function x1(_){let $=_.output;if($===void 0||$===null)return"";if(typeof $==="string")return $;return JSON.stringify($,null,2)}var U6={code:"javascript"};function h1(_){let $=_&&typeof _==="object"?_:null,Z=$?Object.entries(U6).flatMap(([X,J])=>{let Y=$[X];return typeof Y==="string"?[{key:X,lang:J,value:Y.replace(/\\n/g,`
|
|
2
|
+
`)}]:[]}):[],Q=_;if($){let X=Object.fromEntries(Object.entries($).filter(([J])=>!Object.hasOwn(U6,J)));Q=Object.keys(X).length>0?X:null}return{codeSnippets:Z,remainingInput:Q,remainingInputText:Q?JSON.stringify(Q,null,2):""}}var n5=10,r5={"awaiting-input":"starting","input-streaming":"starting","input-complete":"processing","approval-requested":"approval","approval-responded":"processing",complete:"complete",error:"error"};function o5(_){if(!G6.some((Q)=>Q===_.name))return;let $=_.input;if(!$||typeof $!=="object"||!("status"in $))return;let Z=$.status;return typeof Z==="string"&&Z.trim()?Z.trim():void 0}function a5(_){let $=_.output;if(typeof $==="string")try{$=JSON.parse($)}catch{return}if(!$||typeof $!=="object")return;if("error"in $&&$.error===!0)return"failed";if(!G1(_)?.embed||!("status"in $))return;let Z=$.status;return Z==="failed"||Z==="cancelled"?Z:void 0}function s5(_){let $=_.output;if(!$||typeof $!=="object"||!("rowCount"in $))return;let Z=$.rowCount;return typeof Z==="number"?Z:void 0}function t5(_,$,Z){if(Z==="declined")return"translate_declined";if(Z==="cancelled")return"translate_tool_cancelled";if($==="error")return"translate_tool_error";if($==="approval")return"translate_needs_approval";return`translate_${_.name==="readAttachment"?"attachment":"tool"}_${$==="complete"?"done":"status"}`}function Z_(_){let $=_.approval?.approved===!1?"declined":_.state==="complete"?a5(_):void 0,Z=$?"error":r5[_.state]??"processing";return{state:Z,active:Z==="starting"||Z==="processing",gated:_.approval!==void 0||_.state==="approval-requested",titleKey:t5(_,Z,$),statement:o5(_),rows:Z==="complete"?s5(_):void 0}}function u1(_,$){let Z=_.approval?.approved,{state:Q}=Z_(_),X=Z===void 0?_.state==="approval-requested"?"pending":"cancelled":!Z?"declined":Q==="error"?"failed":"approved";return{sentence:V6(_.input)??a($,"translate_approval_action",{tool:_8(_.name)}),decision:X,decisionKey:e5[X]}}var e5={pending:void 0,approved:"translate_approved",declined:"translate_declined",failed:"translate_approved_failed",cancelled:"translate_approval_cancelled"};function _8(_){let $=_.replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/[_\-.]+/g," ").trim().toLowerCase();return $.charAt(0).toUpperCase()+$.slice(1)}function c1(_){return Array.from({length:n5},($,Z)=>`translate_${_}_${Z}`)}function R_(_,$){return _.filter((Z,Q)=>{if(Z.type==="tool-result")return!1;if($.debugMode)return!0;if(Z.type==="text"&&!Z.content.trim())return!1;let X=Q===_.length-1;return Z.type!=="thinking"||$.isStreaming&&X})}function p1(_,$){return _.length>0||Boolean($?.attachments?.length||$?.isAborted)}function d1(_){return _.filter(($)=>$.type==="text").map(($)=>$.content).join(`
|
|
3
3
|
|
|
4
|
-
`)}function i1(_,$){if($&&_.name in $)return!1;return _.name!==V1||!p(_.state)}function q6(_,$){if(_.type!=="tool-call")return!0;return!p(_.state)&&!_.approval&&$.foldable(_)}function n1(_,$){let Z=h_(_);if(!Z)return;let Q=R_(Z.parts,{debugMode:!1,isStreaming:!0}),X=Q.at(-1);if(X&&q6(X,$))return X;return Q.filter((J)=>J.type==="tool-call"&&q6(J,$)).at(-1)}function r1(){let _=new Map;return($,Z)=>{let Q=new Map;for(let[X,J]of s5($,Z)){let Y=_.get(X);Q.set(X,Y&&e5(Y,J)?Y:J)}return _=Q,Q}}function s5(_,$){let Z=new Map;if($.debugMode)return Z;let X=$.agentWorking||z_(_).length>0?t5(_):_,J=[];function Y(){let G=J[0]?.part.id;if(J.length>1&&G&&!$.opened.has(G))for(let[z,{messageId:V,part:K}]of J.entries()){let W=Z.get(V)??new Map;Z.set(V,W);let N=z===J.length-1;W.set(K,N?{kind:"more",count:J.length-1,runId:G}:{kind:"hidden"})}J=[]}for(let G of X){if(G.role!=="assistant"){Y();continue}let z=R_(G.parts,{debugMode:!1,isStreaming:!1});for(let V of z)if(V.type==="tool-call"&&p(V.state)&&$.foldable(V))J.push({messageId:G.id,part:V});else Y()}return Y(),Z}function t5(_){let $=_.map((Z)=>Z.role).lastIndexOf("user");return $<0?[]:_.slice(0,$)}function e5(_,$){if(_.size!==$.size)return!1;for(let[Z,Q]of _){let X=$.get(Z);if(!X||X.kind!==Q.kind)return!1;if(Q.kind==="more"&&X.kind==="more"){if(Q.count!==X.count||Q.runId!==X.runId)return!1}}return!0}import{EventType as U6}from"@tanstack/ai";import{fetchServerSentEvents as B6}from"@tanstack/ai-client";function _8(_){for(let $=_.length-1;$>=0;$-=1){let Z=_[$],Q="parts"in Z&&Z.parts.some((X)=>X.type==="tool-result"||X.type==="tool-call"&&X.state==="approval-responded");if(Z.role==="user"||Q)return _.slice($,$+1)}return _.slice(-1)}function $8(_){if(_.state==="approval-responded"){let $=_.approval?.approved;if($===void 0)return null;return{toolCallId:_.id,output:null,state:$?"approved":"denied"}}if(!p(_.state))return null;return{toolCallId:_.id,output:_.output??null,state:_.state==="error"?"error":"complete"}}function Z8(_){let[$]=_;if(!$||$.role!=="assistant"||!("parts"in $))return null;let Z=$.parts.flatMap((Q)=>{let X=Q.type==="tool-call"?$8(Q):null;return X?[X]:[]});return Z.length>0?Z:null}async function Q8(_){if(_.status!==409)return;let $=await _.clone().json().catch(()=>{return});return $!==null&&typeof $==="object"&&"outcome"in $&&$.outcome==="dropped"&&"reason"in $&&$.reason==="approval_pending"?"approval_pending":void 0}async function*D6(_,$,Z){for await(let Q of _){if(Q.type!==U6.MESSAGES_SNAPSHOT){yield Q;continue}let X=$.localMessages(),J=X.findIndex((G)=>G.id===Z),Y=J===-1?[]:X.slice(J+1).filter((G)=>G.role==="user");$.onTranscriptCarried?.(Q.timestamp??Date.now()),yield{...Q,messages:[...Q.messages,...Y]}}}function a1(_){let{api:$,thread:Z}=_,Q=Object.assign(async(N,q)=>{let H=await fetch(N,q),U=await Q8(H);if(U)_.onRefused?.(U);return H},fetch),X=async()=>({headers:await $.resolveHeaders(),fetchClient:Q}),J=0;async function*Y(N){J+=1,_.onStreamStarted?.();try{yield*N}finally{J-=1}}let G=B6(()=>$.resolveUrl("/chat"),X),z=function(N,q,H,U){let E=_8(N),M=Z8(E),R=M?G.connect([],{...q,[G6]:M},H,U):G.connect(E,q,H,U);return Y(D6(R,_,N.at(-1)?.id))},V=B6(()=>$.resolveUrl(`/chat/${Z.id}/stream`),X),K=[];async function*W(N,q){yield{type:U6.MESSAGES_SNAPSHOT,timestamp:Date.now(),messages:K},yield*D6(V.joinRun(N,q),_,K.at(-1)?.id)}return{connect:z,joinRun:(N,q)=>Y(W(N,q)),streaming:()=>J>0,hydrate:async()=>{let N=await X8(_);return K=N.messages,N}}}async function X8(_){let{api:$,thread:Z,mode:Q}=_,X=Z.isRunning?{runId:Z.id}:null;if(Q==="skip")return{messages:[],activeRun:X,interrupts:null};if(Q==="load")_.setLoadingMessages?.(!0);try{let Y=(await $.listMessages(Z.id)).map(w1);return _.onHydrated?.(Y),{messages:Y,activeRun:X,interrupts:null}}finally{_.setLoadingMessages?.(!1)}}async function o1(_){if(_.isStale?.()||_.isStreaming())return;try{let $=await _.api.listMessages(_.threadId);if(_.isStale?.()||_.isStreaming())return;let Z=$.map(w1);return _.setMessages(Z),Z}catch{return}}function u_(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let _=crypto.getRandomValues(new Uint8Array(16));_[6]=_[6]&15|64,_[8]=_[8]&63|128;let $=Array.from(_,(Z)=>Z.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}var J8={type:"translate_attachment_rejected_type",size:"translate_attachment_rejected_size",name:"translate_attachment_rejected_name",count:"translate_attachment_rejected_count"};function s1(_,$){if(!_.refusal)return o($,"translate_attachment_rejected");return o($,J8[_.refusal],{types:new Intl.ListFormat($).format(x_.map((Z)=>Z.slice(Z.indexOf("/")+1).toUpperCase())),size:X6/1024/1024,count:C1})}function t1(_){let{api:$}=_,Z=new Set,Q=new Set,X=[],J=[],Y=Promise.resolve();function G(){return X}function z(P){return Z.add(P),()=>{Z.delete(P)}}function V(P){X=P;for(let D of Z)D()}function K(P,D){V(X.map((L)=>L.localId===P?{...L,...D}:L))}function W(P){if(Q.delete(P))return;K(P,{status:"error"})}async function N(P,D,L){if(Q.delete(P))return;let O;try{O=await $.uploadAttachment(D,L)}catch{W(P);return}if(Q.delete(P)){$.deleteAttachment(O.id).catch(()=>{});return}K(P,{status:"ready",attachmentId:O.id,summary:O})}function q(P){let D=[];for(let L of P){let O=J6(L),k=X.filter((m_)=>m_.status!=="error").length>=C1,b=O!=="ok"?O:k?"count":void 0,h=u_();if(V([...X,b?{localId:h,filename:L.name,status:"error",refusal:b}:{localId:h,filename:L.name,status:"uploading"}]),!b)D.push({localId:h,file:L})}if(!D.length)return;_.ensureThread().then((L)=>{for(let{localId:O,file:k}of D){if(Q.delete(O))continue;K(O,{threadId:L}),Y=Y.then(()=>N(O,L,k)).catch(()=>{})}},()=>{for(let{localId:L}of D)W(L)})}function H(P){let D=X.find((L)=>L.localId===P);if(!D)return;if(D.status==="uploading"){Q.add(P),V(X.filter((L)=>L.localId!==P));return}if(D.attachmentId){K(P,{status:"deleting"}),$.deleteAttachment(D.attachmentId).then(()=>V(X.filter((L)=>L.localId!==P)),()=>K(P,{status:"error"}));return}V(X.filter((L)=>L.localId!==P))}function U(P){let D=[];for(let L of X){if(L.threadId!==void 0&&L.threadId!==P){D.push(L);continue}if(L.status==="uploading")Q.add(L.localId);else if(L.status==="ready"&&L.threadId===P&&L.attachmentId)$.deleteAttachment(L.attachmentId).catch(()=>{})}V(D)}function E(){let P=X.flatMap((D)=>D.status==="ready"&&D.summary?[{...D,status:"ready",summary:D.summary}]:[]);return V(X.filter((D)=>D.status!=="ready")),J=P,P}function M(P){let D=J;if(J=[],D.some((L)=>L.threadId!==P))return;V([...D.map((L)=>({...L,status:"error"})),...X])}function R(){J=[]}return{getState:G,subscribe:z,accept:q,remove:H,clear:U,consumeReady:E,restoreConsumed:M,discardConsumed:R}}function e1(_){return{uploading:_.some(($)=>$.status==="uploading"),busy:_.some(($)=>$.status==="uploading"||$.status==="deleting"),hasReady:_.some(($)=>$.status==="ready")}}function _0(_,$,Z){try{return new URL(_).origin===$&&!Z?"allow-scripts allow-forms allow-popups":"allow-scripts allow-forms allow-popups allow-same-origin"}catch{return"allow-scripts allow-forms allow-popups"}}function $0(_,$,Z){try{return Z===!0&&new URL(_).origin===$}catch{return!1}}function Z0(_,$){try{return _.contentWindow?.location.origin===$}catch{return!1}}function Q0(_){let $=!1,Z=!1,Q,X;function J(z){if(!$)_.onState(z)}function Y(){if($)return;Z=!1,J({phase:"error"})}function G(z){if($||Z)return;Z=!0,J({phase:"settling"});try{let V=_.submit(z);if(V instanceof Promise)V.catch(Y)}catch{Y()}}return{async start(){J({phase:"initiating"});try{let z=await _.initiate();if(!/^https?:$/.test(new URL(z.embedUrl).protocol)){J({phase:"error"});return}Q=z.embedOrigin,J({phase:"embedded",embedUrl:z.embedUrl,surface:z.surface,embedOrigin:z.embedOrigin})}catch(z){let V=z instanceof Error?z.message:"";J({phase:/HTTP 404/.test(V)?"unavailable":"error"})}},setSource(z){if(z!==null&&z!==void 0)X=z},handleMessage(z){if(!Q)return;if(X===void 0||z.source!==X)return;let V=N6(z.data,z.origin,Q);if(!V)return;G({status:V.status,reference:V.reference,result:V.result})},cancel(){G({status:"cancelled"})},terminate(){if($||Z)return;Q=void 0,X=void 0,J({phase:"error"})},dispose(){$=!0}}}function X0(_,$,Z){let Q=_.interrupts.find((X)=>X.id===$);if(!Q||!("resolveInterrupt"in Q))return _.addToolApprovalResponse({id:$,approved:Z});return Q.resolveInterrupt({approved:Z}),Promise.resolve()}async function c_(_,$){let Z=await import("leaflet"),Q=!$.interactive,X=Z.map(_,{center:$.center,zoom:$.zoom,zoomControl:!Q,dragging:!Q,scrollWheelZoom:!Q,doubleClickZoom:!Q,touchZoom:!Q,boxZoom:!Q,keyboard:!Q});Z.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'}).addTo(X);let J=new ResizeObserver(()=>X.invalidateSize());return J.observe(_),{leaflet:Z,map:X,dispose(){J.disconnect(),X.remove()}}}var z1={position:void 0,locating:!1,locateFailed:!1,mapFailed:!1,submitting:!1,deliveryFailed:!1},Y8={center:{lat:20,lng:0},zoom:2},G8=13,L6=16,V8=1e4;function J0(_,$){let Z=z1,Q=!1,X=!1,J,Y,G,z=0;function V(q){if(Z={...Z,...q},!Q)$.onState(Z)}function K(){let q=Z.position;if(!J||!q)return;let{leaflet:H,map:U}=J;if(Y)Y.setLatLng(q);else{let E=H.marker(q,{draggable:!Z.submitting}).addTo(U);E.on("dragend",()=>{let{lat:M,lng:R}=E.getLatLng();W({lat:M,lng:F6(R)})}),Y=E}G?.remove(),G=q.accuracy?H.circle(q,{radius:q.accuracy}).addTo(U):void 0}function W(q){if(Z.submitting)return;z+=1,V({position:q,locating:!1,locateFailed:!1}),K()}function N(q){if(Q||X)return;X=!0,z+=1,Y?.dragging?.disable(),V({submitting:!0,locating:!1,deliveryFailed:!1});let H=()=>{X=!1,Y?.dragging?.enable(),V({submitting:!1,deliveryFailed:!0})};try{let U=$.submit(q);if(U instanceof Promise)U.catch(H)}catch{H()}}return{async start(){let q=$.center?{center:$.center,zoom:G8}:Y8,H;try{H=await c_(_,{...q,interactive:!0})}catch{V({mapFailed:!0});return}if(Q){H.dispose();return}J=H,H.map.on("click",(U)=>W({lat:U.latlng.lat,lng:F6(U.latlng.lng)})),K()},locate(){if(Z.locating||Z.submitting)return;if(!navigator.geolocation){V({locateFailed:!0});return}z+=1;let q=z;V({locating:!0,locateFailed:!1}),navigator.geolocation.getCurrentPosition(({coords:H})=>{if(Q||q!==z)return;let U={lat:H.latitude,lng:H.longitude,accuracy:Math.round(H.accuracy)};W(U),J?.map.setView(U,L6)},()=>{if(q===z)V({locating:!1,locateFailed:!0})},{enableHighAccuracy:!0,timeout:V8})},confirm(){if(Z.position)N({status:"completed",result:Z.position})},cancel(){N({status:"cancelled"})},dispose(){Q=!0,J?.dispose()}}}function Y0(_,$,Z){let Q=!1,X;return c_(_,{center:$,zoom:L6,interactive:!1}).then((J)=>{if(Q){J.dispose();return}X=J.dispose,J.leaflet.marker($).addTo(J.map)},()=>{if(!Q)Z()}),()=>{Q=!0,X?.()}}function F6(_){if(_>=-180&&_<=180)return _;return((_+180)%360+360)%360-180}function O6(_){if(!_||typeof _!=="object")return!1;let{lat:$,lng:Z}=_;return typeof $==="number"&&typeof Z==="number"&&Math.abs($)<=90&&Math.abs(Z)<=180}function G0(_){let $=_&&typeof _==="object"?_.center:void 0;return O6($)?$:void 0}function V0(_){if(!_||typeof _!=="object")return;let{status:$,result:Z}=_;if($!=="completed"||!O6(Z))return;let{accuracy:Q}=Z;return{...Z,...typeof Q==="number"?{accuracy:Q}:{}}}function K1(_){let $=`${_.lat.toFixed(4)}, ${_.lng.toFixed(4)}`;return _.accuracy?`${$} ±${_.accuracy} m`:$}function z0(_){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}}var K0=30000;function W0(_){return Math.min(1000*2**(_-1),K0)}var z8=1e4;function N0(_){let $,Z,Q=0,X=!1,J=!1;function Y(){let{wsUrl:z,transport:V}=_.getConfig();if(z===!1)return;let K=K8(z,V.baseUrl);v1(V).then((W)=>{if(X)return;$=new WebSocket(W8(K,W)),$.addEventListener("open",()=>{J=!0;let N=$;setTimeout(()=>{if($===N&&!X)Q=0},z8),_.onOpen?.()}),$.addEventListener("message",(N)=>{let q=N.data;if(typeof q!=="string")return;let H;try{H=JSON.parse(q)}catch{return}_.onEvent(H)}),$.addEventListener("close",()=>{J=!1,G()})}).catch(G)}function G(){if(X||Z)return;Q+=1,Z=setTimeout(()=>{Z=void 0,Y()},W0(Q))}return Y(),{close(){X=!0,J=!1,clearTimeout(Z),$?.close()},isOpen(){return J}}}function K8(_,$){if(_)return _;let Z=typeof $==="string"?$:$(),Q=new URL(Z,window.location.origin);return Q.protocol=Q.protocol==="https:"?"wss:":"ws:",Q.pathname=Q.pathname.replace(/\/$/,"")+"/ws",Q.toString()}function W8(_,$){let Z=$.Authorization??$.authorization;if(!Z?.startsWith("Bearer "))return _;let Q=new URL(_,window.location.origin);if(Q.searchParams.has("token"))return Q.toString();return Q.searchParams.set("token",Z.slice(7)),Q.toString()}var H0={unreachable:"translate_agent_unreachable",refused:"translate_access_refused",missing:"translate_agent_missing"};function N8(_){let $=_ instanceof Error?/^HTTP (\d+)\b/.exec(_.message)?.[1]:void 0;if($==="401")return"refused";if($==="404")return"missing";return"unreachable"}function p_(_,$,Z=W0){let Q=!1,X,J=0;function Y(){_().then((G)=>{if(!Q)$.onAnswered(G)},(G)=>{if(Q)return;let z=N8(G);if($.onMissed?.(z),z==="missing")return;J+=1,X=setTimeout(Y,z==="refused"?K0:Z(J))})}return Y(),function(){Q=!0,clearTimeout(X)}}function q0(_){return[..._].sort(($,Z)=>{let Q=Date.parse(Z.updatedAt)-Date.parse($.updatedAt);if(Q!==0)return Q;return Date.parse(Z.createdAt)-Date.parse($.createdAt)})}function d_(_,$){let Z=[..._],Q=Z.findIndex((X)=>X.id===$.id);if(Q===-1)Z.push($);else Z[Q]={...Z[Q],...$};return q0(Z)}function W1(_,$){return _.filter((Z)=>Z.id!==$)}function B0(_,$,Z){return _.map((Q)=>Q.id===$?{...Q,title:Z}:Q)}var H8=[0,1000,2000,3000,4000];function D0(_){let $=_.delays??H8,Z=!1,Q;function X(){let G=_.selected();return!Z&&!_.socketOpen()&&G?.id===_.threadId&&!G.title}async function J(G){if(!X())return;let V=(await _.listThreads().catch(()=>{return}))?.find((K)=>K.id===_.threadId)?.title;if(!X())return;if(V)_.setTitle(V);else Y(G+1)}function Y(G){let z=$[G];if(z!==void 0)Q=setTimeout(()=>void J(G),z)}return Y(0),function(){Z=!0,clearTimeout(Q)}}function U0(_,$){switch($.type){case"thread:deleted":return W1(_,$.payload.threadId);case"thread:created":case"thread:title-updated":case"thread:run-started":case"thread:run-finished":case"thread:messages-updated":return d_(_,$.payload.thread);default:return _}}function F0(){let _=new Map,$=new Map,Z=0;function Q(X){if(X.type==="thread:run-started")return _.set(X.payload.thread.id,X.payload.runId),!0;if(X.type!=="thread:run-finished")return!0;let J=_.get(X.payload.thread.id);return J===void 0||J===X.payload.runId}return{admits(X){let J=Q(X);if(J&&"thread"in X.payload)$.set(X.payload.thread.id,++Z);return J},running(X,J){return $.set(X,++Z),(Y)=>{let G=Y?.find((z)=>z.id===X);return Y&&G?d_(Y,{...G,isRunning:J}):Y}},async read(X){_.clear();let J=++Z,Y=q0(await X());function G(z){return Y.map((V)=>{let K=$.get(V.id)??0,W=K>J?z?.find((N)=>N.id===V.id):void 0;if(K<J)$.set(V.id,J);return W?{...V,isRunning:W.isRunning}:V})}return{listed:Y,show:G}}}}import{marked as q8}from"marked";import B8 from"dompurify";function l_(_,$=[]){if(!_)return"";let Z=document.createElement("template");if(Z.innerHTML=q8.parse(_,{async:!1}).replace(/<table>/g,'<div style="overflow-x:auto"><table style="width:max-content">').replace(/<\/table>/g,"</table></div>").replace(/<(t[hd])([\s>])/g,'<$1 style="padding:0.5rem 1rem"$2'),U8(Z.content),$.length)F8(Z.content,$);return B8.sanitize(Z.innerHTML,{FORBID_TAGS:["img","picture","source"]})}var D8=/[\p{Script=Arabic}\p{Script=Hebrew}]/u;function U8(_){for(let $ of Array.from(_.children))if($.localName!=="div")$.setAttribute("dir","auto");_.querySelectorAll("table").forEach(($)=>{let Z=/\p{L}/u.exec($.textContent??"")?.[0];if(!Z)return;let Q=D8.test(Z)?"rtl":"ltr";if($.setAttribute("dir",Q),$.parentElement?.childElementCount===1)$.parentElement.setAttribute("dir",Q)}),_.querySelectorAll("th, td").forEach(($)=>$.setAttribute("dir","auto")),_.querySelectorAll("pre").forEach(($)=>$.setAttribute("dir","ltr"))}function F8(_,$){let Z=[...$].sort((J,Y)=>J.length-Y.length),Q=Z[Z.length-1]?.length??0,X=0;for(let J of L8(_)){if(X>=Q)break;J.replaceWith(...O8(J.data,X,Z)),X+=J.data.length}}function L8(_){let $=document.createTreeWalker(_,4),Z=[];for(let Q=$.nextNode();Q;Q=$.nextNode())if(Q.data.trim())Z.push(Q);return Z.reverse()}function O8(_,$,Z){let Q=[],X=_.length;for(let J of Z){if(J.length<=$)continue;if(X<=0)break;let Y=Math.min(X,J.length-$);if(Y<X&&/[\uDC00-\uDFFF]/.test(_[X-Y]))Y+=1;let G=document.createElement("span");G.className="cortex-stream-fade",G.style.animationDelay=`-${J.age}ms`,G.textContent=_.slice(X-Y,X),Q.unshift(G),X-=Y,$+=Y}if(X>0)Q.unshift(document.createTextNode(_.slice(0,X)));return Q}import{marked as E6}from"marked";var P6=/^ {0,3}(`{3,}|~{3,})(.*)$/;function M6(){let _=null;return($)=>{let Z=P6.exec($),Q=Z?.[1],X=Z?.[2]??"";if(Q){let J=Q.charAt(0);if(_){if(J===_.marker&&Q.length>=_.length&&X.trim()==="")return _=null,"close";return"inside"}if(J==="`"&&X.includes("`"))return"outside";return _={marker:J,length:Q.length},"open"}return _?"inside":"outside"}}function A6(_){return P6.exec(_)?.[2]?.trim().split(/\s+/)[0]??""}var P8=/^\s*!\[([^\]]*)\]\(attachment#([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)\s*$/i;function L0(_,$){let Z=[],Q=[],X=null;function J(V=!1){if(Q.length)Z.push(...A8(Q.join(`
|
|
5
|
-
`),
|
|
6
|
-
`),closed:
|
|
7
|
-
`);for(let[
|
|
4
|
+
`)}function l1(_,$){if($&&_.name in $)return!1;return _.name!==V1||!p(_.state)}function F6(_,$){if(_.type!=="tool-call")return!0;return!p(_.state)&&!_.approval&&$.foldable(_)}function i1(_,$){let Z=h_(_);if(!Z)return;let Q=R_(Z.parts,{debugMode:!1,isStreaming:!0}),X=Q.at(-1);if(X&&F6(X,$))return X;return Q.filter((J)=>J.type==="tool-call"&&F6(J,$)).at(-1)}function n1(){let _=new Map;return($,Z)=>{let Q=new Map;for(let[X,J]of $8($,Z)){let Y=_.get(X);Q.set(X,Y&&Q8(Y,J)?Y:J)}return _=Q,Q}}function $8(_,$){let Z=new Map;if($.debugMode)return Z;let X=$.agentWorking||z_(_).length>0?Z8(_):_,J=[];function Y(){let G=J[0]?.part.id;if(J.length>1&&G&&!$.opened.has(G))for(let[V,{messageId:z,part:K}]of J.entries()){let W=Z.get(z)??new Map;Z.set(z,W);let N=V===J.length-1;W.set(K,N?{kind:"more",count:J.length-1,runId:G}:{kind:"hidden"})}J=[]}for(let G of X){if(G.role!=="assistant"){Y();continue}let V=R_(G.parts,{debugMode:!1,isStreaming:!1});for(let z of V)if(z.type==="tool-call"&&p(z.state)&&$.foldable(z))J.push({messageId:G.id,part:z});else Y()}return Y(),Z}function Z8(_){let $=_.map((Z)=>Z.role).lastIndexOf("user");return $<0?[]:_.slice(0,$)}function Q8(_,$){if(_.size!==$.size)return!1;for(let[Z,Q]of _){let X=$.get(Z);if(!X||X.kind!==Q.kind)return!1;if(Q.kind==="more"&&X.kind==="more"){if(Q.count!==X.count||Q.runId!==X.runId)return!1}}return!0}import{EventType as P6}from"@tanstack/ai";import{fetchServerSentEvents as L6}from"@tanstack/ai-client";function X8(_){for(let $=_.length-1;$>=0;$-=1){let Z=_[$],Q="parts"in Z&&Z.parts.some((X)=>X.type==="tool-result"||X.type==="tool-call"&&X.state==="approval-responded");if(Z.role==="user"||Q)return _.slice($,$+1)}return _.slice(-1)}function J8(_){if(_.state==="approval-responded"){let $=_.approval?.approved;if($===void 0)return null;return{toolCallId:_.id,output:null,state:$?"approved":"denied"}}if(!p(_.state))return null;return{toolCallId:_.id,output:_.output??null,state:_.state==="error"?"error":"complete"}}function Y8(_){let[$]=_;if(!$||$.role!=="assistant"||!("parts"in $))return null;let Z=$.parts.flatMap((Q)=>{let X=Q.type==="tool-call"?J8(Q):null;return X?[X]:[]});return Z.length>0?Z:null}async function G8(_){if(_.status!==409)return;let $=await _.clone().json().catch(()=>{return});return $!==null&&typeof $==="object"&&"outcome"in $&&$.outcome==="dropped"&&"reason"in $&&$.reason==="approval_pending"?"approval_pending":void 0}async function*O6(_,$,Z){for await(let Q of _){if(Q.type!==P6.MESSAGES_SNAPSHOT){yield Q;continue}let X=$.localMessages(),J=X.findIndex((G)=>G.id===Z),Y=J===-1?[]:X.slice(J+1).filter((G)=>G.role==="user");$.onTranscriptCarried?.(Q.timestamp??Date.now()),yield{...Q,messages:[...Q.messages,...Y]}}}function r1(_){let{api:$,thread:Z}=_,Q=Object.assign(async(N,H)=>{let q=await fetch(N,H),U=await G8(q);if(U)_.onRefused?.(U);return q},fetch),X=async()=>({headers:await $.resolveHeaders(),fetchClient:Q}),J=0;async function*Y(N){J+=1,_.onStreamStarted?.();try{yield*N}finally{J-=1}}let G=L6(()=>$.resolveUrl("/chat"),X),V=function(N,H,q,U){let E=X8(N),M=Y8(E),R=M?G.connect([],{...H,[z6]:M},q,U):G.connect(E,H,q,U);return Y(O6(R,_,N.at(-1)?.id))},z=L6(()=>$.resolveUrl(`/chat/${Z.id}/stream`),X),K=[];async function*W(N,H){yield{type:P6.MESSAGES_SNAPSHOT,timestamp:Date.now(),messages:K},yield*O6(z.joinRun(N,H),_,K.at(-1)?.id)}return{connect:V,joinRun:(N,H)=>Y(W(N,H)),streaming:()=>J>0,hydrate:async()=>{let N=await V8(_);return K=N.messages,N}}}async function V8(_){let{api:$,thread:Z,mode:Q}=_,X=Z.isRunning?{runId:Z.id}:null;if(Q==="skip")return{messages:[],activeRun:X,interrupts:null};if(Q==="load")_.setLoadingMessages?.(!0);try{let Y=(await $.listMessages(Z.id)).map(b1);return _.onHydrated?.(Y),{messages:Y,activeRun:X,interrupts:null}}finally{_.setLoadingMessages?.(!1)}}async function o1(_){if(_.isStale?.()||_.isStreaming())return;try{let $=await _.api.listMessages(_.threadId);if(_.isStale?.()||_.isStreaming())return;let Z=$.map(b1);return _.setMessages(Z),Z}catch{return}}function u_(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let _=crypto.getRandomValues(new Uint8Array(16));_[6]=_[6]&15|64,_[8]=_[8]&63|128;let $=Array.from(_,(Z)=>Z.toString(16).padStart(2,"0")).join("");return`${$.slice(0,8)}-${$.slice(8,12)}-${$.slice(12,16)}-${$.slice(16,20)}-${$.slice(20)}`}var z8={type:"translate_attachment_rejected_type",size:"translate_attachment_rejected_size",name:"translate_attachment_rejected_name",count:"translate_attachment_rejected_count"};function a1(_,$){if(!_.refusal)return a($,"translate_attachment_rejected");return a($,z8[_.refusal],{types:new Intl.ListFormat($).format(x_.map((Z)=>Z.slice(Z.indexOf("/")+1).toUpperCase())),size:J6/1024/1024,count:C1})}function s1(_){let{api:$}=_,Z=new Set,Q=new Set,X=[],J=[],Y=Promise.resolve();function G(){return X}function V(P){return Z.add(P),()=>{Z.delete(P)}}function z(P){X=P;for(let D of Z)D()}function K(P,D){z(X.map((L)=>L.localId===P?{...L,...D}:L))}function W(P){if(Q.delete(P))return;K(P,{status:"error"})}async function N(P,D,L){if(Q.delete(P))return;let O;try{O=await $.uploadAttachment(D,L)}catch{W(P);return}if(Q.delete(P)){$.deleteAttachment(O.id).catch(()=>{});return}K(P,{status:"ready",attachmentId:O.id,summary:O})}function H(P){let D=[];for(let L of P){let O=Y6(L),k=X.filter((m_)=>m_.status!=="error").length>=C1,b=O!=="ok"?O:k?"count":void 0,x=u_();if(z([...X,b?{localId:x,filename:L.name,status:"error",refusal:b}:{localId:x,filename:L.name,status:"uploading"}]),!b)D.push({localId:x,file:L})}if(!D.length)return;_.ensureThread().then((L)=>{for(let{localId:O,file:k}of D){if(Q.delete(O))continue;K(O,{threadId:L}),Y=Y.then(()=>N(O,L,k)).catch(()=>{})}},()=>{for(let{localId:L}of D)W(L)})}function q(P){let D=X.find((L)=>L.localId===P);if(!D)return;if(D.status==="uploading"){Q.add(P),z(X.filter((L)=>L.localId!==P));return}if(D.attachmentId){K(P,{status:"deleting"}),$.deleteAttachment(D.attachmentId).then(()=>z(X.filter((L)=>L.localId!==P)),()=>K(P,{status:"error"}));return}z(X.filter((L)=>L.localId!==P))}function U(P){let D=[];for(let L of X){if(L.threadId!==void 0&&L.threadId!==P){D.push(L);continue}if(L.status==="uploading")Q.add(L.localId);else if(L.status==="ready"&&L.threadId===P&&L.attachmentId)$.deleteAttachment(L.attachmentId).catch(()=>{})}z(D)}function E(){let P=X.flatMap((D)=>D.status==="ready"&&D.summary?[{...D,status:"ready",summary:D.summary}]:[]);return z(X.filter((D)=>D.status!=="ready")),J=P,P}function M(P){let D=J;if(J=[],D.some((L)=>L.threadId!==P))return;z([...D.map((L)=>({...L,status:"error"})),...X])}function R(){J=[]}return{getState:G,subscribe:V,accept:H,remove:q,clear:U,consumeReady:E,restoreConsumed:M,discardConsumed:R}}function t1(_){return{uploading:_.some(($)=>$.status==="uploading"),busy:_.some(($)=>$.status==="uploading"||$.status==="deleting"),hasReady:_.some(($)=>$.status==="ready")}}function e1(_,$,Z){try{return new URL(_).origin===$&&!Z?"allow-scripts allow-forms allow-popups":"allow-scripts allow-forms allow-popups allow-same-origin"}catch{return"allow-scripts allow-forms allow-popups"}}function _0(_,$,Z){try{return Z===!0&&new URL(_).origin===$}catch{return!1}}function $0(_,$){try{return _.contentWindow?.location.origin===$}catch{return!1}}function Z0(_){let $=!1,Z=!1,Q,X;function J(V){if(!$)_.onState(V)}function Y(){if($)return;Z=!1,J({phase:"error"})}function G(V){if($||Z)return;Z=!0,J({phase:"settling"});try{let z=_.submit(V);if(z instanceof Promise)z.catch(Y)}catch{Y()}}return{async start(){J({phase:"initiating"});try{let V=await _.initiate();if(!/^https?:$/.test(new URL(V.embedUrl).protocol)){J({phase:"error"});return}Q=V.embedOrigin,J({phase:"embedded",embedUrl:V.embedUrl,surface:V.surface,embedOrigin:V.embedOrigin})}catch(V){let z=V instanceof Error?V.message:"";J({phase:/HTTP 404/.test(z)?"unavailable":"error"})}},setSource(V){if(V!==null&&V!==void 0)X=V},handleMessage(V){if(!Q)return;if(X===void 0||V.source!==X)return;let z=D6(V.data,V.origin,Q);if(!z)return;G({status:z.status,reference:z.reference,result:z.result})},cancel(){G({status:"cancelled"})},terminate(){if($||Z)return;Q=void 0,X=void 0,J({phase:"error"})},dispose(){$=!0}}}function Q0(_,$,Z){let Q=_.interrupts.find((X)=>X.id===$);if(!Q||!("resolveInterrupt"in Q))return _.addToolApprovalResponse({id:$,approved:Z});return Q.resolveInterrupt({approved:Z}),Promise.resolve()}async function c_(_,$){let Z=await import("leaflet"),Q=!$.interactive,X=Z.map(_,{center:$.center,zoom:$.zoom,zoomControl:!Q,dragging:!Q,scrollWheelZoom:!Q,doubleClickZoom:!Q,touchZoom:!Q,boxZoom:!Q,keyboard:!Q});Z.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png",{attribution:'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'}).addTo(X);let J=new ResizeObserver(()=>X.invalidateSize());return J.observe(_),{leaflet:Z,map:X,dispose(){J.disconnect(),X.remove()}}}var z1={position:void 0,locating:!1,locateFailed:!1,mapFailed:!1,submitting:!1,deliveryFailed:!1},K8={center:{lat:20,lng:0},zoom:2},W8=13,A6=16,N8=1e4;function X0(_,$){let Z=z1,Q=!1,X=!1,J,Y,G,V=0;function z(H){if(Z={...Z,...H},!Q)$.onState(Z)}function K(){let H=Z.position;if(!J||!H)return;let{leaflet:q,map:U}=J;if(Y)Y.setLatLng(H);else{let E=q.marker(H,{draggable:!Z.submitting}).addTo(U);E.on("dragend",()=>{let{lat:M,lng:R}=E.getLatLng();W({lat:M,lng:M6(R)})}),Y=E}G?.remove(),G=H.accuracy?q.circle(H,{radius:H.accuracy}).addTo(U):void 0}function W(H){if(Z.submitting)return;V+=1,z({position:H,locating:!1,locateFailed:!1}),K()}function N(H){if(Q||X)return;X=!0,V+=1,Y?.dragging?.disable(),z({submitting:!0,locating:!1,deliveryFailed:!1});let q=()=>{X=!1,Y?.dragging?.enable(),z({submitting:!1,deliveryFailed:!0})};try{let U=$.submit(H);if(U instanceof Promise)U.catch(q)}catch{q()}}return{async start(){let H=$.center?{center:$.center,zoom:W8}:K8,q;try{q=await c_(_,{...H,interactive:!0})}catch{z({mapFailed:!0});return}if(Q){q.dispose();return}J=q,q.map.on("click",(U)=>W({lat:U.latlng.lat,lng:M6(U.latlng.lng)})),K()},locate(){if(Z.locating||Z.submitting)return;if(!navigator.geolocation){z({locateFailed:!0});return}V+=1;let H=V;z({locating:!0,locateFailed:!1}),navigator.geolocation.getCurrentPosition(({coords:q})=>{if(Q||H!==V)return;let U={lat:q.latitude,lng:q.longitude,accuracy:Math.round(q.accuracy)};W(U),J?.map.setView(U,A6)},()=>{if(H===V)z({locating:!1,locateFailed:!0})},{enableHighAccuracy:!0,timeout:N8})},confirm(){if(Z.position)N({status:"completed",result:Z.position})},cancel(){N({status:"cancelled"})},dispose(){Q=!0,J?.dispose()}}}function J0(_,$,Z){let Q=!1,X;return c_(_,{center:$,zoom:A6,interactive:!1}).then((J)=>{if(Q){J.dispose();return}X=J.dispose,J.leaflet.marker($).addTo(J.map)},()=>{if(!Q)Z()}),()=>{Q=!0,X?.()}}function M6(_){if(_>=-180&&_<=180)return _;return((_+180)%360+360)%360-180}function E6(_){if(!_||typeof _!=="object")return!1;let{lat:$,lng:Z}=_;return typeof $==="number"&&typeof Z==="number"&&Math.abs($)<=90&&Math.abs(Z)<=180}function Y0(_){let $=_&&typeof _==="object"?_.center:void 0;return E6($)?$:void 0}function G0(_){if(!_||typeof _!=="object")return;let{status:$,result:Z}=_;if($!=="completed"||!E6(Z))return;let{accuracy:Q}=Z;return{...Z,...typeof Q==="number"?{accuracy:Q}:{}}}function K1(_){let $=`${_.lat.toFixed(4)}, ${_.lng.toFixed(4)}`;return _.accuracy?`${$} ±${_.accuracy} m`:$}function V0(_){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}}var z0=30000;function K0(_){return Math.min(1000*2**(_-1),z0)}var H8=1e4;function W0(_){let $,Z,Q=0,X=!1,J=!1;function Y(){let{wsUrl:V,transport:z}=_.getConfig();if(V===!1)return;let K=q8(V,z.baseUrl);T1(z).then((W)=>{if(X)return;$=new WebSocket(B8(K,W)),$.addEventListener("open",()=>{J=!0;let N=$;setTimeout(()=>{if($===N&&!X)Q=0},H8),_.onOpen?.()}),$.addEventListener("message",(N)=>{let H=N.data;if(typeof H!=="string")return;let q;try{q=JSON.parse(H)}catch{return}_.onEvent(q)}),$.addEventListener("close",()=>{J=!1,G()})}).catch(G)}function G(){if(X||Z)return;Q+=1,Z=setTimeout(()=>{Z=void 0,Y()},K0(Q))}return Y(),{close(){X=!0,J=!1,clearTimeout(Z),$?.close()},isOpen(){return J}}}function q8(_,$){if(_)return _;let Z=typeof $==="string"?$:$(),Q=new URL(Z,window.location.origin);return Q.protocol=Q.protocol==="https:"?"wss:":"ws:",Q.pathname=Q.pathname.replace(/\/$/,"")+"/ws",Q.toString()}function B8(_,$){let Z=(Y)=>Object.entries($).find(([G])=>G.toLowerCase()===Y.toLowerCase())?.[1],Q=Z("Authorization"),X=Object.entries({token:Q?.startsWith("Bearer ")?Q.slice(7):void 0,operator:Z(W6),inspect:Z(N6)}).filter((Y)=>Boolean(Y[1]));if(X.length===0)return _;let J=new URL(_,window.location.origin);for(let[Y,G]of X)if(!J.searchParams.has(Y))J.searchParams.set(Y,G);return J.toString()}var N0={unreachable:"translate_agent_unreachable",refused:"translate_access_refused",missing:"translate_agent_missing"};function D8(_){let $=_ instanceof Error?/^HTTP (\d+)\b/.exec(_.message)?.[1]:void 0;if($==="401")return"refused";if($==="404")return"missing";return"unreachable"}function p_(_,$,Z=K0){let Q=!1,X,J=0;function Y(){_().then((G)=>{if(!Q)$.onAnswered(G)},(G)=>{if(Q)return;let V=D8(G);if($.onMissed?.(V),V==="missing")return;J+=1,X=setTimeout(Y,V==="refused"?z0:Z(J))})}return Y(),function(){Q=!0,clearTimeout(X)}}function H0(_){return[..._].sort(($,Z)=>{let Q=Date.parse(Z.updatedAt)-Date.parse($.updatedAt);if(Q!==0)return Q;return Date.parse(Z.createdAt)-Date.parse($.createdAt)})}function d_(_,$){let Z=[..._],Q=Z.findIndex((X)=>X.id===$.id);if(Q===-1)Z.push($);else Z[Q]={...Z[Q],...$};return H0(Z)}function W1(_,$){return _.filter((Z)=>Z.id!==$)}function q0(_,$,Z){return _.map((Q)=>Q.id===$?{...Q,title:Z}:Q)}var U8=[0,1000,2000,3000,4000];function B0(_){let $=_.delays??U8,Z=!1,Q;function X(){let G=_.selected();return!Z&&!_.socketOpen()&&G?.id===_.threadId&&!G.title}async function J(G){if(!X())return;let z=(await _.listThreads().catch(()=>{return}))?.find((K)=>K.id===_.threadId)?.title;if(!X())return;if(z)_.setTitle(z);else Y(G+1)}function Y(G){let V=$[G];if(V!==void 0)Q=setTimeout(()=>void J(G),V)}return Y(0),function(){Z=!0,clearTimeout(Q)}}function D0(_,$){switch($.type){case"thread:deleted":return W1(_,$.payload.threadId);case"thread:created":case"thread:title-updated":case"thread:run-started":case"thread:run-finished":case"thread:messages-updated":return d_(_,$.payload.thread);default:return _}}function U0(){let _=new Map,$=new Map,Z=0;function Q(X){if(X.type==="thread:run-started")return _.set(X.payload.thread.id,X.payload.runId),!0;if(X.type!=="thread:run-finished")return!0;let J=_.get(X.payload.thread.id);return J===void 0||J===X.payload.runId}return{admits(X){let J=Q(X);if(J&&"thread"in X.payload)$.set(X.payload.thread.id,++Z);return J},running(X,J){return $.set(X,++Z),(Y)=>{let G=Y?.find((V)=>V.id===X);return Y&&G?d_(Y,{...G,isRunning:J}):Y}},async read(X){_.clear();let J=++Z,Y=H0(await X());function G(V){return Y.map((z)=>{let K=$.get(z.id)??0,W=K>J?V?.find((N)=>N.id===z.id):void 0;if(K<J)$.set(z.id,J);return W?{...z,isRunning:W.isRunning}:z})}return{listed:Y,show:G}}}}import{marked as F8}from"marked";import L8 from"dompurify";function l_(_,$=[]){if(!_)return"";let Z=document.createElement("template");if(Z.innerHTML=F8.parse(_,{async:!1}).replace(/<table>/g,'<div style="overflow-x:auto"><table style="width:max-content">').replace(/<\/table>/g,"</table></div>").replace(/<(t[hd])([\s>])/g,'<$1 style="padding:0.5rem 1rem"$2'),P8(Z.content),$.length)M8(Z.content,$);return L8.sanitize(Z.innerHTML,{FORBID_TAGS:["img","picture","source"]})}var O8=/[\p{Script=Arabic}\p{Script=Hebrew}]/u;function P8(_){for(let $ of Array.from(_.children))if($.localName!=="div")$.setAttribute("dir","auto");_.querySelectorAll("table").forEach(($)=>{let Z=/\p{L}/u.exec($.textContent??"")?.[0];if(!Z)return;let Q=O8.test(Z)?"rtl":"ltr";if($.setAttribute("dir",Q),$.parentElement?.childElementCount===1)$.parentElement.setAttribute("dir",Q)}),_.querySelectorAll("th, td").forEach(($)=>$.setAttribute("dir","auto")),_.querySelectorAll("pre").forEach(($)=>$.setAttribute("dir","ltr"))}function M8(_,$){let Z=[...$].sort((J,Y)=>J.length-Y.length),Q=Z[Z.length-1]?.length??0,X=0;for(let J of A8(_)){if(X>=Q)break;J.replaceWith(...E8(J.data,X,Z)),X+=J.data.length}}function A8(_){let $=document.createTreeWalker(_,4),Z=[];for(let Q=$.nextNode();Q;Q=$.nextNode())if(Q.data.trim())Z.push(Q);return Z.reverse()}function E8(_,$,Z){let Q=[],X=_.length;for(let J of Z){if(J.length<=$)continue;if(X<=0)break;let Y=Math.min(X,J.length-$);if(Y<X&&/[\uDC00-\uDFFF]/.test(_.charAt(X-Y)))Y+=1;let G=document.createElement("span");G.className="cortex-stream-fade",G.style.animationDelay=`-${J.age}ms`,G.textContent=_.slice(X-Y,X),Q.unshift(G),X-=Y,$+=Y}if(X>0)Q.unshift(document.createTextNode(_.slice(0,X)));return Q}import{marked as y6}from"marked";var R6=/^ {0,3}(`{3,}|~{3,})(.*)$/;function k6(){let _=null;return($)=>{let Z=R6.exec($),Q=Z?.[1],X=Z?.[2]??"";if(Q){let J=Q.charAt(0);if(_){if(J===_.marker&&Q.length>=_.length&&X.trim()==="")return _=null,"close";return"inside"}if(J==="`"&&X.includes("`"))return"outside";return _={marker:J,length:Q.length},"open"}return _?"inside":"outside"}}function I6(_){return R6.exec(_)?.[2]?.trim().split(/\s+/)[0]??""}var R8=/^\s*!\[([^\]]*)\]\(attachment#([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)\s*$/i;function F0(_,$){let Z=[],Q=[],X=null;function J(z=!1){if(Q.length)Z.push(...I8(Q.join(`
|
|
5
|
+
`),z));Q=[]}function Y(z){if(X)Z.push({kind:"media",...X,source:X.source.join(`
|
|
6
|
+
`),closed:z});X=null}let G=k6(),V=_.split(`
|
|
7
|
+
`);for(let[z,K]of V.entries()){let W=G(K);if(X){if(W==="close")Y(!0);else X.source.push(K);continue}if(W==="open"&&z===V.length-1)break;let N=k8(K,W,$);if(!N){Q.push(K);continue}if(J(),N.kind==="media")X={language:N.language,source:[]};else Z.push(N)}return Y(!1),J(!0),Z}function k8(_,$,Z){if($==="open"){let X=I6(_),J=Z.find((Y)=>Y===X);return J?{kind:"media",language:J}:void 0}let Q=$==="outside"?R8.exec(_):null;return Q?{kind:"attachment",alt:Q[1]??"",id:(Q[2]??"").toLowerCase()}:void 0}function I8(_,$){let Z=y6.lexer(_);if(!Z.some((K)=>K.type==="table"))return[{kind:"markdown",text:_}];let Q=[];y6.walkTokens(Z,(K)=>{if(K.type==="def")Q.push(K.raw.trim())});let X=Q.join(`
|
|
8
8
|
`),J=(K)=>X?`${X}
|
|
9
9
|
|
|
10
|
-
${K}`:K,Y=[],G="";function
|
|
11
|
-
`));return($.textContent??"").trim()}function
|
|
10
|
+
${K}`:K,Y=[],G="";function V(){if(G.trim())Y.push({kind:"markdown",text:J(G)});G=""}let z=Z.filter((K)=>K.type!=="def");for(let[K,W]of z.entries()){if(W.type!=="table"){G+=W.raw;continue}V();let N=z.slice(K+1).some((H)=>H.raw.trim()!=="");Y.push({kind:"table",text:J(W.raw.trimEnd()),closed:N||!$})}return V(),Y}var y8=/^-?(?:0|[1-9]\d*)(?:\.\d*[1-9])?$/;function S8(_){return y8.test(_)&&_!=="-0"&&_.replace(/[-.]/g,"").replace(/^0/,"").length<=15}var C8=32767,S6=new TextEncoder;function L0(_){return Array.from(_.rows,($)=>Array.from($.cells,b8))}function b8(_){let $=_.cloneNode(!0);if($ instanceof Element)$.querySelectorAll("br").forEach((Z)=>Z.replaceWith(`
|
|
11
|
+
`));return($.textContent??"").trim()}function O0(_){return new Blob([m8(j8(_))],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})}function w8(_){return _.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g,"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/_(x[0-9a-f]{4}_)/gi,"_x005F_$1")}function T8(_){let $="";for(let Z=_+1;Z>0;Z=Math.floor((Z-1)/26))$=String.fromCharCode(65+(Z-1)%26)+$;return $}function v8(_){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${_.map((Z,Q)=>{let X=Z.map((J,Y)=>{let G=`${T8(Y)}${Q+1}`,V=Q===0?' s="1"':"";return Q>0&&S8(J)?`<c r="${G}"${V}><v>${J}</v></c>`:`<c r="${G}"${V} t="inlineStr"><is><t xml:space="preserve">${w8(J.slice(0,C8))}</t></is></c>`}).join("");return`<row r="${Q+1}">${X}</row>`}).join("")}</sheetData></worksheet>`}function j8(_){return[{name:"[Content_Types].xml",text:'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>'},{name:"_rels/.rels",text:'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>'},{name:"xl/workbook.xml",text:'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>'},{name:"xl/_rels/workbook.xml.rels",text:'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>'},{name:"xl/styles.xml",text:'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border/></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>'},{name:"xl/worksheets/sheet1.xml",text:v8(_)}]}var f8=Array.from({length:256},(_,$)=>{let Z=$;for(let Q=0;Q<8;Q++)Z=Z&1?3988292384^Z>>>1:Z>>>1;return Z>>>0});function g8(_){let $=4294967295;for(let Z of _)$=(f8[($^Z)&255]??0)^$>>>8;return($^4294967295)>>>0}function m8(_){let $=[],Z=[],Q=0;for(let z of _){let K=S6.encode(z.name),W=S6.encode(z.text),N=g8(W),H=new DataView(new ArrayBuffer(30));H.setUint32(0,67324752,!0),H.setUint16(4,20,!0),H.setUint16(6,2048,!0),H.setUint32(14,N,!0),H.setUint32(18,W.length,!0),H.setUint32(22,W.length,!0),H.setUint16(26,K.length,!0),$.push(new Uint8Array(H.buffer),K,W);let q=new DataView(new ArrayBuffer(46));q.setUint32(0,33639248,!0),q.setUint16(4,20,!0),q.setUint16(6,20,!0),q.setUint16(8,2048,!0),q.setUint32(16,N,!0),q.setUint32(20,W.length,!0),q.setUint32(24,W.length,!0),q.setUint16(28,K.length,!0),q.setUint32(42,Q,!0),Z.push(new Uint8Array(q.buffer),K),Q+=30+K.length+W.length}let X=Z.reduce((z,K)=>z+K.length,0),J=new DataView(new ArrayBuffer(22));J.setUint32(0,101010256,!0),J.setUint16(8,_.length,!0),J.setUint16(10,_.length,!0),J.setUint32(12,X,!0),J.setUint32(16,Q,!0);let Y=[...$,...Z,new Uint8Array(J.buffer)],G=new Uint8Array(Y.reduce((z,K)=>z+K.length,0)),V=0;for(let z of Y)G.set(z,V),V+=z.length;return G}var w6=new Set(["flatten","fold","density","impute","regression","loess","quantile","sample"]),x8=`Use Vega-Lite JSON with inline \`data.values\` only, at most 200 rows, and no \`url\` anywhere. Compute folds, trend lines and densities yourself. For several series, write one row per series and x value, or keep one row per x value and draw a layer per series (color by \`datum\`) when that would exceed the row limit. These keys are refused anywhere in the spec: ${[...w6,"params","selection"].join(", ")}. Expressions in \`calculate\`, \`filter\` and \`labelExpr\` may use only datum fields, literals, operators and simple math or date-part functions (no format or timeFormat), so put formatted values in the rows or use an axis \`format\`.`;function T6(_,$){if(_==="url")return"Charts may only use inline data and no URLs.";if(_==="sequence"||_==="graticule")return"Charts may only use inline data.";if(w6.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(h8.has(_)&&typeof $==="string"&&!u8($))return"Charts may only use simple expressions over datum.";if(_==="usermeta")return"Charts may not carry usermeta.";if(typeof $==="string"&&N1($))return"Charts may not reference URLs.";if((_==="width"||_==="height")&&c8($)>4000)return"Charts may be at most 4000 pixels wide or tall.";return}var h8=new Set(["calculate","filter","test","signal","labelExpr"]),C6=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 u8(_){if(_.length>500||/[\\`]/.test(_))return!1;let $=_.replace(/'[^']*'|"[^"]*"/g,'""');for(let[,Q]of $.matchAll(/([A-Za-z_$][\w$]*)\s*\(/g))if(!C6.has(Q??""))return!1;let Z=$.replace(/(datum|parent)(\s*\.[\w$]+|\s*\[\s*""\s*\])+|\b\d[\w.]*/g,"").matchAll(/[A-Za-z_$][\w$]*/g);for(let[Q]of Z)if(!C6.has(Q)&&!["true","false","null"].includes(Q))return!1;return!0}function c8(_){if(typeof _==="number")return _;let $=_?.step;return typeof $==="number"?$:0}function b6(_,$){let Z=_?.features,Q=Array.isArray(_)?_.length:Array.isArray(Z)?Z.length:-1;if(Q<0)return T6($,_)??M0(P0(_,$),i_);return Q>200?"Charts may hold at most 200 rows.":void 0}function i_(_,$=""){if($==="values")return b6(_,$);if($==="datasets")return M0(P0(_),b6);return T6($,_)??M0(P0(_,$),(Z,Q)=>i_(Z,Q))}function P0(_,$=""){if(Array.isArray(_))return _.map((Z)=>[$,Z]);return _&&typeof _==="object"?Object.entries(_):[]}function M0(_,$){for(let[Z,Q]of _){let X=$(Q,Z);if(X)return X}return}var v6=/url\(([^)]*)\)/gi,A0="src|image|image-set|-webkit-image-set|cross-fade|element",E0=new RegExp(String.raw`\b(url|${A0})\(`,"i"),p8=new RegExp(String.raw`\b(${A0})\(`,"i"),d8=new RegExp(String.raw`\b(${A0})\([^)]*\)`,"gi"),l8=/\\([0-9a-f]{1,6})\s?|\\(.)/gi,i8=/@import[^;]*;?/gi;function n8(_){return _.replace(l8,($,Z,Q)=>{if(!Z)return Q??"";let X=parseInt(Z,16),J=X===0||X>=55296&&X<=57343||X>1114111;return String.fromCodePoint(J?65533:X)})}function j6(_){return _.trim().replace(/^(['"])(.*)\1$/s,"$2").trim()}function N1(_){if(_.includes("\\")||p8.test(_))return!0;for(let[,$]of _.matchAll(v6))if(!j6($??"").startsWith("#"))return!0;return!1}function R0(_){return n8(_).replaceAll("\\"," ").replace(i8," ").replace(d8,"none").replace(v6,($,Z)=>j6(Z).startsWith("#")?$:"none")}var r8=new Set(["src","srcset","poster","background","action","formaction","ping"]);function n_(_){for(let $ of[_,..._.querySelectorAll("*")]){for(let Z of[...$.attributes])if(r8.has(Z.name)||(Z.name==="href"||Z.name==="xlink:href")&&$.localName!=="a"&&!Z.value.trim().startsWith("#")||N1(Z.value))$.removeAttribute(Z.name);if($.localName==="style"&&$.textContent)$.textContent=R0($.textContent)}}var o8=`
|
|
12
12
|
@layer {
|
|
13
13
|
:host {
|
|
14
14
|
display: block !important;
|
|
@@ -186,6 +186,6 @@ ${K}`:K,Y=[],G="";function z(){if(G.trim())Y.push({kind:"markdown",text:J(G)});G
|
|
|
186
186
|
display: block;
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
|
-
`,
|
|
190
|
-
${$}`;return await Q.parse(
|
|
191
|
-
`).find((Z)=>/\S/.test(Z)&&!/^\s*%%/.test(Z));return/^\s*(\S+)/.exec($??"")?.[1]??""}function I0(_){return _===void 0||_==="container"}var $4=["row","column","facet"];function h6(_){let $=_.encoding,Z=typeof $==="object"&&$!==null&&$4.some((Q)=>(Q in $));return(("mark"in _)||("layer"in _))&&I0(_.width)&&!Z}function Z4(_){let $={..._};if(I0($.width))delete $.width;if(I0($.height))delete $.height;return $}function Q4(_,$){let Z=Z4(_);if($<=0||!h6(_))return Z;return{...Z,width:$,height:Z.height??Math.round(Math.min(480,Math.max(200,$/2))),autosize:Z.autosize??{type:"fit",contains:"padding"}}}var X4="vg-tooltip-element";function u6(_){let $=_.getRootNode();return _.closest("dialog")??($ instanceof ShadowRoot?u6($.host):null)}var j6=Promise.resolve(),f6=!1,g6=0;function J4(){return g6+=1,g6}function Y4(_){if(!_||typeof _!=="object")throw Error("A map needs a JSON object.");let $=_,Z=$.zoom??10;if(typeof Z!=="number"||Z<0||Z>22)throw Error("zoom must be 0 to 22.");let Q=$.markers??[];if(!Array.isArray(Q))throw Error("markers must be a list.");return{center:m6($.center,"center"),zoom:Z,markers:Q.map((X,J)=>{let Y=X??{},G=Y.label;return{position:m6(Y.position,`markers[${J}].position`),label:typeof G==="string"?G:void 0}})}}function m6(_,$){let Z=Array.isArray(_)?_:[],[Q,X]=Z;if(typeof Q!=="number"||typeof X!=="number"||Math.abs(Q)>90||Math.abs(X)>180)throw Error(`${$} must be [latitude, longitude].`);return{lat:Q,lng:X}}function S0(_,$){if(_!=="system")return $(_??"light"),()=>{};let Z=window.matchMedia("(prefers-color-scheme: dark)"),Q=()=>$(Z.matches?"dark":"light");return Q(),Z.addEventListener("change",Q),()=>Z.removeEventListener("change",Q)}import B1 from"highlight.js/lib/core";import G4 from"highlight.js/lib/languages/javascript";import V4 from"highlight.js/lib/languages/json";var c6=!1;function z4(){if(c6)return;c6=!0,B1.registerLanguage("javascript",G4),B1.registerLanguage("json",V4)}function C0(_,$){if(!_)return"";return z4(),B1.getLanguage($)?B1.highlight(_,{language:$}).value:K4(_)}function K4(_){return _.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function k_(_){if(typeof _==="string"){let $=_.trim();if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return _;try{return k_(JSON.parse($))}catch{return _}}if(Array.isArray(_))return _.map(($)=>k_($));if(_!==null&&typeof _==="object"){let $={};for(let[Z,Q]of Object.entries(_))$[Z]=k_(Q);return $}return _}function b0(_,$){if(Array.isArray(_)){let Z=_;return{kind:"container",open:"[",close:"]",summary:p6(Z.length,"item","items"),entries:Z.map((Q,X)=>({key:null,value:Q,path:`${$}[${X}]`}))}}if(_!==null&&typeof _==="object"){let Z=Object.entries(_);return{kind:"container",open:"{",close:"}",summary:p6(Z.length,"property","properties"),entries:Z.map(([Q,X])=>({key:Q,value:X,path:`${$}.${Q}`}))}}return{kind:"primitive",text:W4(_),className:N4(_)}}function p6(_,$,Z){return`${_} ${_===1?$:Z}`}function W4(_){if(_===null||_===void 0)return"null";if(typeof _==="string")return JSON.stringify(_);if(typeof _==="number"||typeof _==="boolean")return String(_);return JSON.stringify(_)??"null"}function N4(_){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 w0(_){if(!_)return null;try{return JSON.parse(_)}catch{return _}}function T0(_){if(!_)return"";try{return JSON.stringify(JSON.parse(_),null,2)}catch{return _}}function Q_(_,$,Z=Date.now()){let Q=new Date(_);if(Number.isNaN(Q.getTime()))return"";let X=Q.toDateString()===new Date(Z).toDateString();return new Intl.DateTimeFormat($,{...X?{}:{dateStyle:"medium"},timeStyle:"short"}).format(Q)}function r_(_,$){let Z=URL.createObjectURL(_),Q=document.createElement("a");Q.href=Z,Q.download=$,document.body.append(Q),Q.click(),Q.remove(),setTimeout(()=>URL.revokeObjectURL(Z),40000)}class K_{onUpdate;fullText="";displayedLength=0;animationFrameId=null;isDone=!1;releases=[];static DRAIN_FRACTION=0.03;static MIN_CHARS_PER_FRAME=1;static DONE_DRAIN_FRACTION=0.1;static FADE_WINDOW_MS=500;constructor(_){this.onUpdate=_}seed(_){this.fullText=_,this.displayedLength=_.length,this.releases=[],this.onUpdate(_,[])}update(_,$){if(this.fullText=_,this.isDone=$,this.displayedLength=Math.min(this.displayedLength,this.fullText.length),this.releases=this.releases.filter((Z)=>Z.from<this.displayedLength),$&&this.displayedLength>=this.fullText.length){this.onUpdate(this.fullText,[]),this.stopAnimation();return}if(!this.animationFrameId)this.scheduleFrame()}destroy(){this.stopAnimation()}scheduleFrame(){this.animationFrameId=requestAnimationFrame((_)=>this.tick(_))}tick(_){let $=this.fullText.length-this.displayedLength;if($<=0){this.animationFrameId=null;return}let Z=this.isDone?K_.DONE_DRAIN_FRACTION:K_.DRAIN_FRACTION,Q=Math.max(K_.MIN_CHARS_PER_FRAME,Math.ceil($*Z));if(this.releases=this.releases.filter((X)=>_-X.at<K_.FADE_WINDOW_MS),this.releases.push({from:this.displayedLength,at:_}),this.displayedLength=Math.min(this.fullText.length,this.displayedLength+Q),this.onUpdate(this.fullText.substring(0,this.displayedLength),this.releases.map((X)=>({length:this.displayedLength-X.from,age:_-X.at}))),this.displayedLength<this.fullText.length)this.scheduleFrame();else this.animationFrameId=null}stopAnimation(){if(this.animationFrameId)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}}var v0=new WeakMap;function j0(_,$){let Z=_.closest(".cortex-widget__screen"),Q=Z?.querySelector(".cortex-message-list");if(!Z||!Q||!_.value.trim())return;let X=getComputedStyle(_),J=_.getBoundingClientRect(),Y=(G)=>parseFloat(X[`padding${G}`])+parseFloat(X[`border${G}Width`]);v0.set(Z,{text:$,textarea:_,from:new DOMRect(J.left+Y("Left"),J.top+Y("Top"),J.width-Y("Left")-Y("Right"),J.height-Y("Top")-Y("Bottom")),rtl:X.direction==="rtl",scrollTop:Q.scrollTop})}function f0(_,$){let Z=_.closest(".cortex-widget__screen"),Q=Z?v0.get(Z):void 0;if(!Z||!Q)return;v0.delete(Z);let X=_.querySelectorAll(":scope > .cortex-message"),J=X[X.length-1]?.querySelector(".cortex-text-bubble--user"),Y=_.closest(".cortex-message-list");if(!J||!Y||Q.text!==$||!Q.textarea.isConnected)return;J.closest(".cortex-message-part")?.getAnimations().forEach((M)=>M.finish()),D1(Y);let G=J.getBoundingClientRect(),z=Z.getBoundingClientRect(),V=getComputedStyle(J),K=parseFloat(V.paddingTop)+parseFloat(V.borderTopWidth),W=Q.rtl?parseFloat(V.paddingRight)+parseFloat(V.borderRightWidth):parseFloat(V.paddingLeft)+parseFloat(V.borderLeftWidth),N=Q.rtl?Q.from.right+W-G.width:Q.from.left-W,q=Y.scrollTop-Q.scrollTop;if(q)_.style.setProperty("--cortex-slide",`${q}px`),_.classList.remove("cortex-message-list__content--settling"),_.offsetWidth,_.classList.add("cortex-message-list__content--settling"),_.getAnimations()[0]?.finished.then(()=>_.classList.remove("cortex-message-list__content--settling"),()=>{return});let H=J.cloneNode(!0);H.classList.add("cortex-send-flight"),H.setAttribute("aria-hidden","true"),Object.assign(H.style,{left:`${G.left-z.left}px`,top:`${G.top-z.top}px`,width:`${G.width}px`}),H.style.setProperty("--cortex-fly-x",`${N-G.left}px`),H.style.setProperty("--cortex-fly-y",`${Q.from.top-K-G.top}px`),J.style.visibility="hidden",Z.append(H);let U=Y.scrollTop,E=()=>{H.style.top=`${G.top-z.top-(Y.scrollTop-U)}px`};Y.addEventListener("scroll",E,{passive:!0}),i6(H).then(()=>{Y.removeEventListener("scroll",E),J.style.visibility="",H.remove()})}function D1(_){_.scrollTop=l6(_)}function g0(_){return l6(_)-_.scrollTop}function l6(_){let $=_.querySelector(".cortex-message-list__content");if(!$)return _.scrollHeight-_.clientHeight;let Z=getComputedStyle(_);return $.offsetHeight+parseFloat(Z.paddingTop)+parseFloat(Z.paddingBottom)-_.clientHeight}function m0(_){let $=!1,Z=_.parentElement,Q=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{if($)X()});Q?.observe(Z);function X(){let J=Z.querySelector(":scope > .cortex-working-thinking, :scope > .cortex-message > .cortex-message-parts > [data-cortex-frontier]");if(!J)return!1;return _.style.setProperty("--cortex-avatar-y",`${H4(J,Z)-_.offsetHeight/2}px`),!0}return{sync(J){if(J===$){if(J)X();return}if(J){if(!X())return;_.classList.remove("cortex-working-avatar--leaving"),_.offsetWidth,_.classList.add("cortex-working-avatar--shown"),$=!0;return}$=!1;let[,Y="0px"]=getComputedStyle(_).translate.split(" ");_.style.setProperty("--cortex-avatar-y",Y),_.classList.add("cortex-working-avatar--leaving"),i6(_,!0).then(()=>{if($)return;_.classList.remove("cortex-working-avatar--shown","cortex-working-avatar--leaving")})},dispose(){Q?.disconnect()}}}function H4(_,$){let Z=_.querySelector(".cortex-text-bubble");if(!Z)return d6(_,$)+_.offsetHeight/2;let Q=getComputedStyle(Z);return d6(Z,$)+parseFloat(Q.paddingTop)+parseFloat(Q.borderTopWidth)+parseFloat(Q.lineHeight)/2}function d6(_,$){let Z=0;for(let Q=_;Q instanceof HTMLElement&&Q!==$;)Z+=Q.offsetTop,Q=Q.offsetParent;return Z}function i6(_,$=!1){return Promise.allSettled(_.getAnimations({subtree:$}).map((Z)=>Z.finished))}import{EventType as q4}from"@tanstack/ai";function x0(_){return _.refusal==="approval_pending"?"translate_approval_pending":"translate_error"}var B4=2;function h0(_){let $=!1,Z=!1,Q=!1,X,J,Y,G,z=!1,V=!1,K,W,N=new Set,q=0,H=!1,U=new Set,E=new Set,M,R=new Map,P=0,D=0,L=0;async function O(A){let I=Symbol("delivery");U.add(I);try{if(await A(),M&&await M.over)E.add(I);if(E.has(I))throw Error("The answer did not reach Cortex")}finally{U.delete(I),E.delete(I)}}function k(){if($&&q===0)return!1;if(q+=1,!$)$=!0,_.setRunning(!0);return!0}function b(A){if(q-=1,A)H=!0;else if(q===0&&!H)$=!1,_.setRunning(!1)}async function h(){let A=P,I=++D,w=()=>P!==A||L>I||!_.isAlive(),m=await _.refreshMessages(w).catch(()=>{return});if(!m||w())return!1;L=I;let P_=new Set(z_(m).map((c)=>c.id));for(let c of R.keys())if(!P_.has(c))R.delete(c);if($)V_(m);let q_=[...R.values()];if(q_.some((c)=>c.failedResends>=B4))return!1;for(let c of q_)if(!await O(()=>_.deliver(c.answer)).then(()=>!0,()=>!1))return c.failedResends+=1,h();return!0}async function m_(A,I){let w;try{let c=I({toolCallId:A.id,toolName:A.name,input:A.input},{threadId:_.threadId});if(c===null||c===void 0)return;w=await Promise.resolve(c)}catch{N.delete(A.id);return}if(w===null||w===void 0)return;if(!_.isAlive())return;let m=k(),P_={toolCallId:A.id,tool:A.name,output:w};R.set(A.id,{answer:P_,failedResends:0});let q_=await O(()=>_.deliver(P_)).then(()=>!0,h);if(m)b(q_)}function V_(A){let I=z_(A),w=_.onToolCall();if(!w)return I.length>0;for(let m of I){if(m.state!=="input-complete"||N.has(m.id))continue;N.add(m.id),m_(m,w)}return I.length>0}async function I1(A){if(Q)_.reloadThreads().catch(()=>{});else _.setRunning(!1);if($&&!z&&V_(A()))return;if(W===void 0&&K!==void 0)return;W=void 0,await h()}return{chunkArrived(A){if(Z=!0,U.clear(),A.type===q4.RUN_ERROR&&A.code!=="aborted")X={reason:A.message||void 0}},transcriptCarried(A){if(K=A,W!==void 0&&W<=A)W=void 0},transcriptUpdated(A){let I=Date.parse(A);if(K!==void 0&&I<=K)return;if(!V){h();return}W=Math.max(W??0,I)},streamFailed(){Q=!0;let A=U.size>0;for(let m of U)E.add(m);if(U.clear(),z)return;if(Z)_.onTurnFinished();else _.onSendFailed();if(J){if(_.setTurnFailed({reason:void 0,refusal:J}),G!==void 0)_.returnDraft(G);return}let w=X??($&&!A&&!Z?{reason:void 0}:void 0);if(w)_.setTurnFailed(w)},loadingChanged(A,I){if(A){V=!0;return}if(!V)return;V=!1,_.onTurnFinished(),I1(I)},hydrated(A,I){if(I)return;setTimeout(()=>{if(_.isAlive())V_(A)},0)},deliverAnswer(A){let I=k(),w=O(A).catch(async(m)=>{throw await h(),m});return w.then(()=>{if(I)b(!0)},()=>{if(I)b(!1)}),w},interruptStateChanged(A){if(A.resuming){if(M)return;let I=()=>{},w=new Promise((m)=>{I=m});M={errorsAtStart:A.interruptErrors.length,over:w,end:I};return}M?.end(A.interruptErrors.length>M.errorsAtStart),M=void 0},readBack:h,streamStarted(){if($)_.setRunning(!0);P+=1,Q=!1,X=void 0,J=void 0,G=Y,Y=void 0,K=void 0,z=!1,_.setTurnFailed(void 0)},sendStarted(A){P+=1,Y=A,_.returnDraft(void 0),$=!0,Z=!1},sendRefused(A){J=A},abortConfirmed(){z=!0}}}function a_(_){if(_.input.total<=0)return null;return Math.round(_.input.cacheRead/_.input.total*100)}import{createContext as n6,useContext as r6}from"react";var u0=n6(void 0);function F(){let _=r6(u0);if(!_)throw Error("useCortex must be used inside <CortexChatWidget>");return _}var c0={messages:[],isAgentWorking:!1,isLoadingMessages:!1,hasPendingToolCalls:!1,awaitsApproval:!1,returnedDraft:void 0,turnFailure:void 0},p0=n6(c0);function I_(){return r6(p0)}import{useEffect as D4,useState as a6}from"react";function o6(_,$){let[Z,Q]=a6(),[X,J]=a6();return D4(()=>{return Q(void 0),J(void 0),p_(()=>_.getCapabilities(),{onAnswered:(Y)=>{Q(Y),J(void 0)},onMissed:J})},[_,$]),{capabilities:Z,unanswered:X}}import{useRef as E4}from"react";import{useRef as U4,useState as F4,useSyncExternalStore as L4}from"react";function s6(_,$){let Z=U4($);Z.current=$;let[Q]=F4(()=>t1({api:_,ensureThread:()=>Z.current()})),X=L4(Q.subscribe,Q.getState,Q.getState);return{store:Q,value:{items:X,...e1(X),accept:Q.accept,remove:Q.remove,consumeReady:Q.consumeReady}}}import{useEffect as O4,useRef as P4}from"react";function t6(_,$){let Z=P4(void 0);O4(()=>{if($===Z.current)return;_.clear(Z.current),Z.current=$},[$,_])}import{useRef as e6}from"react";function _2(_){let $=e6([]),Z=e6(void 0);function Q(){let J=_.selectedRef.current;if(J)return Promise.resolve(J.id);return Z.current??=_.api.createThread().then((Y)=>{return Z.current=void 0,_.onCreated(Y),Y.id},(Y)=>{throw Z.current=void 0,Y}),Z.current}async function X(J,Y=[]){let G=_.sessionRef.current;if(G){await G.send(J,Y);return}$.current.push({prompt:J,attachments:Y});try{await Q()}catch(z){throw $.current=[],z}}return{ensureThread:Q,send:X,pendingSendRef:$}}import{useRef as M4,useState as A4}from"react";function $2(_){let[$,Z]=A4(),Q=$?.thread,X=Q?_.threads?.find((V)=>V.id===Q.id)??Q:void 0,J=M4(X);J.current=X;function Y(V,K){if(J.current?.id===V.id&&_.hasSession())return;let W=J.current;if(J.current=V,Z({thread:V,mode:K,epoch:0}),W&&W.id!==V.id)_.getHooks()?.onThreadDeselected?.(W);_.getHooks()?.onThreadSelected?.(V)}function G(){let V=J.current;if(!V&&!_.hasSession())return;if(J.current=void 0,Z(void 0),V)_.getHooks()?.onThreadDeselected?.(V)}function z(V,K){Z((W)=>({thread:V,mode:"reload",epoch:(W?.epoch??0)+1,initialMessages:K}))}return{session:$,selected:X,selectedRef:J,select:Y,deselect:G,remount:z}}function Z2(_){let{api:$,threads:Z}=_,Q=E4(void 0),X=$2({threads:Z.threads,getHooks:_.getHooks,hasSession:()=>Q.current!==void 0}),J=_2({api:$,sessionRef:Q,selectedRef:X.selectedRef,onCreated:(V)=>{Z.upsert(V),X.select(V,"skip")}}),Y=s6($,J.ensureThread);t6(Y.store,X.selected?.id);async function G(V){if(X.selectedRef.current?.id===V)X.deselect();await Z.remove(V)}function z(V){X.select(V,"load")}return{sessionRef:Q,selection:X,queue:Y,deleteThread:G,openThread:z,...J}}import{useEffect as R4,useRef as Q2}from"react";function X2(_){let $=Q2(_);$.current=_;let Z=Q2(void 0);return R4(()=>{let Q=!1,X=N0({getConfig:()=>$.current.getConfig(),onEvent:(J)=>$.current.onEvent(J),onOpen:()=>{if(Q)$.current.onReconnect();Q=!0}});return Z.current=X,()=>{X.close(),Z.current=void 0}},[]),{isOpen:()=>Z.current?.isOpen()??!1}}function J2(_){let{threads:$,selectedRef:Z,sessionRef:Q}=_;function X(Y){$.applyEvent(Y);let G=Z.current?.id;switch(Y.type){case"thread:deleted":if(G===Y.payload.threadId)_.deselect();break;case"thread:run-started":if(G===Y.payload.thread.id)Q.current?.reattach(Y.payload.thread);break;case"thread:messages-updated":case"thread:run-finished":Q.current?.transcriptUpdated(Y.payload.thread.id,Y.payload.thread.updatedAt);break}}function J(){_.onReconnect(),$.reload().then((Y)=>{let G=Z.current;if(!Y||!G)return;Q.current?.reattach(Y.find((z)=>z.id===G.id)??G)})}return{onEvent:X,onReconnect:J}}function Y2(_){return{abort:async()=>{await _.current?.abort()},addToolResult:($,Z,Q)=>_.current?.addToolResult($,Z,Q)??Promise.resolve(),respondToApproval:($,Z)=>_.current?.respondToApproval($,Z)??Promise.resolve()}}import{useEffect as G2,useRef as k4,useState as V2}from"react";function z2(_){let[$,Z]=V2(),[Q]=V2(F0),X=k4(void 0);G2(()=>()=>X.current?.(),[]),G2(()=>p_(()=>Q.read(()=>_.listThreads()),{onAnswered:({show:W})=>Z(W),onMissed:(W)=>{if(W!=="unreachable")Z((N)=>N??[])}}),[_,Q]);async function J(){let W=await Q.read(()=>_.listThreads()).catch(()=>{return});if(W)Z(W.show);return W?.listed}function Y(W){Z((N)=>d_(N??[],W))}function G(W,N){Z(Q.running(W,N))}function z(W,N){X.current?.();let q=W()?.id;if(!q)return;X.current=D0({threadId:q,listThreads:()=>_.listThreads(),selected:W,socketOpen:N,setTitle:(H)=>Z((U)=>U&&B0(U,q,H))})}async function V(W){await _.deleteThread(W),Z((N)=>N?W1(N,W):N)}function K(W){if(!Q.admits(W))return;Z((N)=>{let q=U0(N??[],W);return N||q.length?q:N})}return{threads:$,reload:J,upsert:Y,setRunning:G,followTitle:z,remove:V,applyEvent:K}}import{useState as K2}from"react";function W2(_){let[$,Z]=K2("chat"),[Q,X]=K2(!1);return{screen:$,sidebarOpen:Q,showChat:()=>{Z("chat"),X(!1)},openHistory:()=>_==="full"?X(!0):Z("threads"),closeHistory:()=>_==="full"?X(!1):Z("chat"),closeSidebar:()=>X(!1)}}import{forwardRef as T4,useEffect as v4,useImperativeHandle as j4,useRef as U2,useState as F2}from"react";function B(..._){return _.filter(Boolean).join(" ")}import{useState as I4}from"react";function N2(_,$){let[Z,Q]=I4(!1);return{dragging:Z,onDragOver:(X)=>{if(X.preventDefault(),_)Q(!0)},onDragLeave:(X)=>{if(!X.currentTarget.contains(X.relatedTarget))Q(!1)},onDrop:(X)=>{if(X.preventDefault(),Q(!1),_)$([...X.dataTransfer.files])},onPaste:(X)=>{let J=X.clipboardData.files;if(!_||!J.length)return;X.preventDefault(),$([...J])}}}var f={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{jsx as n,jsxs as o_}from"react/jsx-runtime";function H2(){let{queue:_,t:$,locale:Z}=F();if(!_.items.length)return null;return n("div",{className:"cortex-attachment-queue",children:_.items.map((Q)=>o_("div",{className:B("cortex-attachment-chip",Q.status==="error"&&"cortex-attachment-chip--error"),children:[Q.status==="uploading"||Q.status==="deleting"?o_("svg",{className:"cortex-attachment-chip__spinner",viewBox:"0 0 16 16",fill:"none",children:[n("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",className:"cortex-attachment-chip__spinner-track"}),n("path",{d:"M14 8a6 6 0 0 0-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):Q.status==="error"?o_("svg",{viewBox:"0 0 16 16",className:"cortex-attachment-chip__icon",fill:"none",children:[n("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"1.25"}),n("path",{d:"M8 4.75v4M8 10.75v.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})]}):o_("svg",{viewBox:"0 0 16 16",className:"cortex-attachment-chip__icon",fill:"none",children:[n("path",{d:f.file[0],stroke:"currentColor",strokeWidth:"1.25"}),n("path",{d:f.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),o_("span",{className:"cortex-attachment-chip__text",children:[n("span",{className:"cortex-attachment-chip__name",children:n("bdi",{children:Q.filename})}),Q.status==="error"&&n("span",{className:"cortex-attachment-chip__reason",children:s1(Q,Z)})]}),n("button",{type:"button",onClick:()=>_.remove(Q.localId),className:"cortex-attachment-chip__remove",disabled:Q.status==="deleting","aria-label":$("translate_remove_attachment"),children:n("svg",{viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M4.5 4.5l7 7m0-7l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]},Q.localId))})}import{useRef as y4}from"react";import{jsx as B_,jsxs as q2,Fragment as C4}from"react/jsx-runtime";var S4=x_.join(",");function B2({attachmentsEnabled:_,canSend:$,onSend:Z}){let{t:Q,queue:X}=F(),J=y4(null);return q2("div",{className:"cortex-widget__input-actions",children:[_&&q2(C4,{children:[B_("button",{type:"button",onClick:()=>J.current?.click(),className:"cortex-widget__attach-btn","aria-label":Q("translate_attach_files"),children:B_("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:B_("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"})})}),B_("input",{ref:J,type:"file",multiple:!0,accept:S4,onChange:(Y)=>{X.accept([...Y.target.files??[]]),Y.target.value=""},className:"cortex-widget__file-input"})]}),B_("button",{onClick:Z,"aria-label":Q("translate_send"),className:B("cortex-widget__send-btn",!$&&"cortex-widget__send-btn--empty",$&&"cortex-widget__send-btn--ready"),disabled:!$,children:B_("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__send-icon",children:B_("path",{d:"M3 8h10M9 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}import{useLayoutEffect as b4}from"react";import{jsx as w4}from"react/jsx-runtime";function D2(_){let{t:$}=F();b4(()=>{let Q=_.inputRef.current;if(!Q)return;Q.style.height="0px",Q.style.height=`${Q.scrollHeight}px`},[_.inputRef,_.value]);function Z(Q){if(Q.key==="Enter"&&!Q.shiftKey)Q.preventDefault(),_.onSubmit()}return w4("textarea",{ref:_.inputRef,onKeyDown:Z,onPaste:_.onPaste,value:_.value,onChange:(Q)=>_.onChange(Q.target.value),placeholder:_.dragging?$("translate_drop_files_here"):_.disabled?"":$("translate_type_a_message"),disabled:_.disabled,rows:1,className:B("cortex-widget__textarea",_.disabled&&"cortex-widget__textarea--disabled")})}import{jsx as y_,jsxs as d0}from"react/jsx-runtime";function f4(_){let[$,Z]=F2(_??""),[Q,X]=F2(_);if(_!==Q){if(X(_),_&&!$)Z(_)}return[$,Z]}var L2=T4(function($,Z){let{t:Q,queue:X,send:J,abort:Y,capabilities:G}=F(),{isAgentWorking:z,awaitsApproval:V,returnedDraft:K}=I_(),W=G?.attachments??!1,[N,q]=f4(K),H=N2(W,X.accept),U=U2(null);j4(Z,()=>({focusInput:()=>U.current?.focus()}));let E=U2(z);v4(()=>{if(E.current&&!z)U.current?.focus();E.current=z},[z]);let M=!V&&!X.busy&&(Boolean(N.trim())||X.hasReady);function R(){if(z||!M)return;let P=N.trim()||Q("translate_attachment_caption"),D=X.consumeReady();if(U.current)j0(U.current,P);q(""),J(P,D.map((L)=>L.summary))}return d0("div",{className:"cortex-widget__input-area",onDragOver:H.onDragOver,onDragLeave:H.onDragLeave,onDrop:H.onDrop,children:[y_(H2,{}),d0("div",{className:B("cortex-widget__input-box",z&&"cortex-widget__input-box--disabled",!z&&"cortex-widget__input-box--enabled",H.dragging&&"cortex-widget__input-box--dragging"),children:[y_(D2,{inputRef:U,value:N,onChange:q,onSubmit:R,onPaste:H.onPaste,disabled:z,dragging:H.dragging}),z?d0("button",{type:"button","aria-label":Q("translate_stop"),onClick:()=>void Y(),className:"cortex-stop-btn",children:[y_("span",{className:"cortex-stop-btn__ring"}),y_("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"cortex-stop-btn__icon",children:y_("rect",{x:"1",y:"1",width:"10",height:"10",rx:"2.5",fill:"currentColor"})})]}):y_(B2,{attachmentsEnabled:W,canSend:M,onSend:R})]})]})});import{jsx as l0}from"react/jsx-runtime";function U1({capabilities:_,composerRef:$}){let{t:Z,unanswered:Q}=F();if(_===void 0)return Q?l0("p",{className:"cortex-widget__messages-disabled",children:Z(H0[Q])}):null;return _.messages===!1?l0("p",{className:"cortex-widget__messages-disabled",children:Z("translate_messages_disabled")}):l0(L2,{ref:$})}import{jsx as u,jsxs as F1}from"react/jsx-runtime";function O2(_){let{t:$}=F(),Z=u("button",{type:"button",onClick:_.newChat,"aria-label":$("translate_new_chat"),title:$("translate_new_chat"),className:"cortex-widget__header-btn cortex-widget__new-btn",children:u("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:u("path",{d:"M8 3v10M3 8h10",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})});if(_.screen==="threads")return F1("div",{className:"cortex-widget__threads-header",children:[u("button",{type:"button",onClick:_.closeHistory,"aria-label":$("translate_back"),className:"cortex-widget__header-btn cortex-widget__back-btn",children:u("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",className:"cortex-widget__back-icon",children:u("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),F1("div",{children:[u("h2",{className:"cortex-widget__threads-title",children:$("translate_history")}),_.threadCount!==void 0&&u("p",{className:"cortex-widget__threads-count",children:$("translate_conversations",{count:_.threadCount})})]}),Z]});return F1("div",{className:"cortex-widget__chat-header",children:[u("button",{onClick:_.openHistory,className:"cortex-widget__sidebar-toggle-btn",children:u("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u("path",{d:"M2.5 4h11M2.5 8h11M2.5 12h11",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}),u("div",{className:"cortex-widget__chat-title-wrap",children:u("p",{className:"cortex-widget__chat-title",children:_.title??_.agentName??$("translate_new_chat")})}),_.debug.shown&&u("button",{onClick:_.toggleDebug,className:B("cortex-widget__debug-btn",_.debug.on?"cortex-widget__debug-btn--on":"cortex-widget__debug-btn--off"),children:_.debug.on?$("translate_debug"):$("translate_normal")}),Z,u("button",{type:"button",onClick:_.openHistory,"aria-label":$("translate_history"),title:$("translate_history"),className:"cortex-widget__header-btn cortex-widget__history-btn",children:F1("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[u("circle",{cx:"8",cy:"8",r:"5.75",stroke:"currentColor",strokeWidth:"1.3"}),u("path",{d:"M8 5v3l2 1.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})}import{jsx as X_,jsxs as P2}from"react/jsx-runtime";function M2(_){let{locale:$,t:Z}=F();return P2("div",{className:"cortex-widget__landing",children:[X_("div",{className:"cortex-widget__landing-icon",children:X_("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",children:X_("path",{d:f.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),X_("p",{className:"cortex-widget__landing-greeting",children:_.greeting}),!!_.suggestions.length&&X_("div",{className:"cortex-widget__landing-chips",children:_.suggestions.map((Q,X)=>X_("button",{type:"button",onClick:()=>_.send(Q.prompt),className:"cortex-widget__landing-chip",children:Q.title},X))}),_.composer,!!_.threads?.length&&X_("div",{className:"cortex-widget__landing-recent",children:_.threads.slice(0,2).map((Q)=>{let X=Q_(Q.updatedAt,$);return P2("button",{type:"button",onClick:()=>_.openThread(Q),className:"cortex-widget__landing-recent-item",children:[X_("p",{className:"cortex-widget__landing-recent-title",children:Q.title??Z("translate_untitled")}),X&&X_("p",{className:"cortex-widget__landing-recent-time",children:X})]},Q.id)})})]})}import{useCallback as X1,useEffect as s0,useLayoutEffect as t0,useMemo as A3,useRef as L_,useState as e0}from"react";import{memo as P3}from"react";import{Fragment as F3}from"react";import{useRef as g4,useState as m4}from"react";import{jsx as S_,jsxs as x4}from"react/jsx-runtime";function s({value:_,className:$}){let{t:Z}=F(),[Q,X]=m4(!1),J=g4(null);async function Y(G){G.stopPropagation(),G.preventDefault();try{if(await navigator.clipboard.writeText(_),X(!0),J.current)clearTimeout(J.current);J.current=setTimeout(()=>X(!1),1500)}catch{}}return S_("span",{className:B("cortex-copy-btn",$),children:S_("button",{className:B("cortex-copy-btn__button",Q&&"cortex-copy-btn__button--copied"),onClick:(G)=>void Y(G),"aria-label":Q?Z("translate_copied"):Z("translate_copy"),type:"button",children:Q?S_("svg",{className:"cortex-copy-btn__icon cortex-copy-btn__icon--check",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:S_("path",{d:"M5 13l4 4L19 7",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):x4("svg",{className:"cortex-copy-btn__icon",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:[S_("rect",{x:"9",y:"9",width:"12",height:"12",rx:"2",stroke:"currentColor",strokeWidth:"2"}),S_("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 L1,jsxs as A2}from"react/jsx-runtime";function O1({label:_}){return A2("div",{className:"cortex-aborted-flag",children:[L1("span",{className:"cortex-aborted-flag__line"}),A2("span",{className:"cortex-aborted-flag__label",children:[L1("svg",{className:"cortex-aborted-flag__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:L1("path",{d:"M6 1.5v5M6 8.75v.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})}),_]}),L1("span",{className:"cortex-aborted-flag__line"})]})}import{jsx as C_,jsxs as E2}from"react/jsx-runtime";function R2(_){let{api:$,t:Z}=F();async function Q(X){let{blob:J,name:Y}=await $.downloadAttachment(X);r_(J,Y)}return C_("div",{className:B("cortex-message-attachments",_.isUser&&"cortex-message-attachments--user"),children:_.attachments.map((X)=>E2("button",{type:"button",onClick:()=>void Q(X.id),className:"cortex-message-attachment","aria-label":`${Z("translate_download")}: ${X.filename}`,children:[E2("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__icon",fill:"none",children:[C_("path",{d:f.file[0],stroke:"currentColor",strokeWidth:"1.25"}),C_("path",{d:f.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),C_("span",{className:"cortex-message-attachment__name",children:X.filename}),C_("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__dl-icon",fill:"none",children:C_("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 c4,useState as s_}from"react";import{useMemo as h4,useState as u4}from"react";import{jsx as r,jsxs as D_,Fragment as P1}from"react/jsx-runtime";function W_({data:_,expandDepth:$,className:Z}){let Q=h4(()=>k_(_),[_]),[X,J]=u4({});function Y(z,V){return X[z]??V>=$}function G(z,V){J((K)=>({...K,[z]:!Y(z,V)}))}return r("div",{className:B("cortex-json-tree",Z),children:r(k2,{value:Q,path:"$",depth:0,isCollapsed:Y,toggle:G})})}function k2({value:_,path:$,depth:Z,isCollapsed:Q,toggle:X}){let J=b0(_,$);if(J.kind==="primitive")return r("span",{className:J.className,children:J.text});if(J.entries.length===0)return D_("span",{className:"cortex-json-tree__bracket",children:[J.open,J.close]});let Y=Q($,Z);function G(z){X($,Z),z.stopPropagation()}return D_(P1,{children:[D_("span",{className:"cortex-json-tree__toggle",onClick:G,role:"button",children:[r("span",{className:B("cortex-json-tree__arrow",Y&&"cortex-json-tree__arrow--collapsed"),children:"▾"}),r("span",{className:"cortex-json-tree__bracket",children:J.open})]}),Y?D_(P1,{children:[r("span",{className:"cortex-json-tree__collapsed-hint",onClick:G,role:"button",children:J.summary}),r("span",{className:"cortex-json-tree__bracket",children:J.close})]}):D_(P1,{children:[r("div",{className:"cortex-json-tree__indent",children:J.entries.map((z,V)=>D_("div",{className:"cortex-json-tree__line",children:[z.key!==null&&D_(P1,{children:[r("span",{className:"cortex-json-tree__key",children:`"${z.key}"`}),r("span",{className:"cortex-json-tree__colon",children:": "})]}),r(k2,{value:z.value,path:z.path,depth:Z+1,isCollapsed:Q,toggle:X}),V<J.entries.length-1&&r("span",{className:"cortex-json-tree__comma",children:","})]},z.path))}),r("span",{className:"cortex-json-tree__bracket",children:J.close})]})]})}function S(_){return _.toLocaleString("en-US")}import{jsx as b_,jsxs as w_}from"react/jsx-runtime";function I2({usage:_}){let{t:$}=F();return w_("div",{className:"cortex-llm-inspector__usage-rows",children:[w_("div",{className:"cortex-llm-inspector__usage-row",children:[b_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_input")}),b_("span",{className:"cortex-llm-inspector__usage-val",children:S(_.input.total)}),w_("span",{className:"cortex-llm-inspector__usage-detail",children:[$("translate_fresh")," ",S(_.input.noCache)," · ",$("translate_read")," ",S(_.input.cacheRead)," · ",$("translate_write")," ",S(_.input.cacheWrite)]})]}),w_("div",{className:"cortex-llm-inspector__usage-row",children:[b_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_output")}),b_("span",{className:"cortex-llm-inspector__usage-val",children:S(_.output.total)}),w_("span",{className:"cortex-llm-inspector__usage-detail",children:[$("translate_text")," ",S(_.output.text)," · ",$("translate_reasoning")," ",S(_.output.reasoning)]})]}),w_("div",{className:"cortex-llm-inspector__usage-row cortex-llm-inspector__usage-row--total",children:[b_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_total")}),b_("span",{className:"cortex-llm-inspector__usage-val",children:S(_.total)})]})]})}import{jsx as y2,jsxs as M1}from"react/jsx-runtime";function S2({usage:_}){let $=a_(_);return M1("span",{className:"cortex-llm-inspector__step-metrics",children:[M1("span",{className:"cortex-llm-inspector__metric",children:[y2("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--input"}),S(_.input.total)]}),M1("span",{className:"cortex-llm-inspector__metric",children:[y2("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--output"}),S(_.output.total)]}),$!==null&&M1("span",{className:"cortex-llm-inspector__cache-pct",children:[$,"%"]})]})}import{jsx as T,jsxs as N_}from"react/jsx-runtime";function C2({messageId:_}){let{t:$,api:Z,selectedThread:Q}=F(),[X,J]=s_(!1),[Y,G]=s_(!1),[z,V]=s_([]),[K,W]=s_(null),[N,q]=s_({}),H=c4(!1);async function U(){if(!H.current&&Q){G(!0);try{V(await Z.listLlmRequests(Q.id,_))}finally{G(!1),H.current=!0}}J((D)=>!D)}function E(D){W((L)=>L===D?null:D)}function M(D){return N[D]??"prompt"}function R(D,L){q((O)=>({...O,[D]:L}))}function P(D){return M(D.id)==="prompt"?D.prompt:D.output}return N_("div",{className:B("cortex-llm-inspector",X&&"cortex-llm-inspector--open"),children:[N_("button",{className:"cortex-llm-inspector__trigger",onClick:()=>void U(),children:[T("svg",{className:"cortex-llm-inspector__icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:T("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"})}),T("span",{children:$("translate_inspect_llm_requests")}),Y?T("span",{className:"cortex-llm-inspector__loading",children:$("translate_loading")}):z.length>0?T("span",{className:"cortex-llm-inspector__badge",children:z.length}):null,T("svg",{className:"cortex-llm-inspector__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:T("path",{d:f.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),T("div",{className:"cortex-llm-inspector__panel-wrapper",children:T("div",{className:"cortex-llm-inspector__panel-inner",children:N_("div",{className:"cortex-llm-inspector__panel",children:[z.length===0&&!Y&&T("div",{className:"cortex-llm-inspector__empty",children:$("translate_no_llm_requests")}),z.map((D,L)=>N_("div",{className:B("cortex-llm-inspector__step",K===D.id&&"cortex-llm-inspector__step--expanded"),children:[N_("button",{className:"cortex-llm-inspector__step-header",onClick:()=>E(D.id),children:[T("span",{className:"cortex-llm-inspector__step-label",children:$("translate_step_n",{number:L+1})}),D.tokenUsage&&T(S2,{usage:D.tokenUsage}),T("svg",{className:"cortex-llm-inspector__step-chevron",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:T("path",{d:f.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),T("div",{className:"cortex-llm-inspector__step-body-wrapper",children:T("div",{className:"cortex-llm-inspector__step-body-inner",children:N_("div",{className:"cortex-llm-inspector__step-body",children:[D.tokenUsage&&T(I2,{usage:D.tokenUsage}),N_("div",{className:"cortex-llm-inspector__tabs",children:[T("button",{className:B("cortex-llm-inspector__tab",M(D.id)==="prompt"&&"cortex-llm-inspector__tab--active"),onClick:()=>R(D.id,"prompt"),children:$("translate_request")}),T("button",{className:B("cortex-llm-inspector__tab",M(D.id)==="response"&&"cortex-llm-inspector__tab--active"),onClick:()=>R(D.id,"response"),children:$("translate_response")})]}),N_("div",{className:"cortex-llm-inspector__json-pane",children:[T(s,{className:"cortex-llm-inspector__json-copy",value:T0(P(D))}),T(W_,{data:w0(P(D)),expandDepth:2})]})]})})})]},D.id))]})})})]})}import{useState as p4}from"react";import{jsx as y,jsxs as g}from"react/jsx-runtime";function b2({usage:_,modelId:$}){let{t:Z}=F(),[Q,X]=p4(!1),J=a_(_)??0;return g("div",{className:B("cortex-token-usage",Q&&"cortex-token-usage--expanded"),children:[g("button",{className:"cortex-token-usage__summary",onClick:()=>X((Y)=>!Y),children:[g("span",{className:"cortex-token-usage__total",children:[y("span",{className:"cortex-token-usage__total-number",children:S(_.total)}),y("span",{className:"cortex-token-usage__total-label",children:Z("translate_tokens")})]}),$?y("span",{className:"cortex-token-usage__model",children:$}):null,g("span",{className:"cortex-token-usage__pills",children:[g("span",{className:"cortex-token-usage__pill",children:[y("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),S(_.input.total)]}),g("span",{className:"cortex-token-usage__pill",children:[y("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),S(_.output.total)]})]}),J>0&&g("span",{className:"cortex-token-usage__cache-badge",children:[J,"%"]}),y("svg",{className:"cortex-token-usage__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:y("path",{d:f.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),y("div",{className:"cortex-token-usage__details",children:y("div",{className:"cortex-token-usage__details-inner",children:g("div",{className:"cortex-token-usage__columns",children:[g("div",{className:"cortex-token-usage__col",children:[g("div",{className:"cortex-token-usage__col-header",children:[y("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),y("span",{className:"cortex-token-usage__col-label",children:Z("translate_input")}),y("span",{className:"cortex-token-usage__col-total",children:S(_.input.total)})]}),g("div",{className:"cortex-token-usage__rows",children:[_.input.noCache?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_fresh")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.input.noCache)})]}):null,_.input.cacheRead?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_cache_read")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.input.cacheRead)})]}):null,_.input.cacheWrite?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_cache_write")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.input.cacheWrite)})]}):null]}),J>0&&g("div",{className:"cortex-token-usage__cache-bar-row",children:[y("div",{className:"cortex-token-usage__cache-bar",children:y("div",{className:"cortex-token-usage__cache-fill",style:{width:`${J}%`}})}),y("span",{className:"cortex-token-usage__cache-label",children:Z("translate_n_percent_cached",{percent:J})})]})]}),g("div",{className:"cortex-token-usage__col",children:[g("div",{className:"cortex-token-usage__col-header",children:[y("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),y("span",{className:"cortex-token-usage__col-label",children:Z("translate_output")}),y("span",{className:"cortex-token-usage__col-total",children:S(_.output.total)})]}),g("div",{className:"cortex-token-usage__rows",children:[_.output.text?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_text")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.output.text)})]}):null,_.output.reasoning?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_reasoning")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.output.reasoning)})]}):null]})]})]})})})]})}import{jsx as w2,jsxs as d4}from"react/jsx-runtime";function T2({messageId:_,isAssistant:$,metadata:Z}){let{tokenUsage:Q}=Z;if(!Q&&!$)return null;return d4("div",{className:"cortex-message-debug-zone",children:[Q&&w2(b2,{usage:Q,modelId:Z.modelId}),$&&w2(C2,{messageId:_})]})}import{jsx as t,jsxs as t_}from"react/jsx-runtime";function v2(_){let{reasoningPart:$,streaming:Z=!1}=_,{t:Q}=F();return t_("details",{className:"cortex-reasoning-details",children:[t_("summary",{className:"cortex-reasoning-details__summary",children:[t_("div",{className:"cortex-reasoning-details__header",children:[t("span",{className:"cortex-reasoning-details__icon",children:t_("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:[t("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"}),t("path",{d:"M7.5 17.5h5M8.5 8a2 2 0 0 1 2-2",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})]})}),t("div",{className:"cortex-reasoning-details__title-group",children:t_("div",{className:"cortex-reasoning-details__title-row",children:[t("div",{className:"cortex-reasoning-details__title",children:Q("translate_reasoning")}),t("span",{className:B("cortex-reasoning-details__badge",Z?"cortex-reasoning-details__badge--streaming":"cortex-reasoning-details__badge--done"),children:Z?Q("translate_streaming"):Q("translate_done")})]})})]}),t("span",{className:"cortex-reasoning-details__chevron","aria-hidden":"true",children:t("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:t("path",{d:f.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),t("div",{className:"cortex-reasoning-details__body",children:t("div",{className:"cortex-reasoning-details__content",children:t("pre",{dir:"auto",className:"cortex-reasoning-details__pre",children:$.content.trim()?$.content:Q("translate_no_reasoning")})})})]})}import{useEffect as u2,useMemo as Q3,useRef as n0,useState as X3}from"react";import{useEffect as n4,useState as j2}from"react";import{useRef as l4,useState as i4}from"react";import{jsx as J_,jsxs as A1}from"react/jsx-runtime";function T_(_){let{label:$,ready:Z=!0,actions:Q,expanded:X,children:J}=_,{t:Y}=F(),G=l4(null),[z,V]=i4(!1);return A1("div",{className:"cortex-expandable",children:[Z&&A1("div",{className:"cortex-expandable__toolbar",role:"group","aria-label":$,children:[Q,J_("button",{type:"button",className:"cortex-expandable__action","aria-label":Y("translate_expand",{name:$}),title:Y("translate_expand",{name:$}),onClick:()=>{V(!0),G.current?.showModal()},children:J_("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:J_("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),J_("div",{className:"cortex-expandable__content",children:J}),A1("dialog",{ref:G,className:"cortex-expandable__dialog","aria-label":$,closedby:"any",onClose:()=>V(!1),children:[A1("div",{className:"cortex-expandable__head",children:[J_("span",{className:"cortex-expandable__title",children:$}),Q,J_("button",{type:"button",className:"cortex-expandable__action","aria-label":Y("translate_close"),title:Y("translate_close"),onClick:()=>G.current?.close(),children:J_("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:J_("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})})]}),z&&J_("div",{className:"cortex-expandable__body",children:X})]})]})}import{jsx as e_,jsxs as r4}from"react/jsx-runtime";function f2(_){let{id:$,alt:Z,attachment:Q}=_,{api:X,t:J}=F(),[Y,G]=j2(),[z,V]=j2(!1);if(n4(()=>{let K,W=!1;return G(void 0),V(!1),X.downloadAttachment($).then(({blob:N})=>{if(W)return;K=URL.createObjectURL(N),G(K)},()=>{if(!W)V(!0)}),()=>{if(W=!0,K)URL.revokeObjectURL(K)}},[X,$]),z)return e_("p",{className:"cortex-attachment-image__caption",children:Z?J("translate_image_unavailable_alt",{alt:Z}):J("translate_image_unavailable")});if(!Y)return null;return r4("figure",{className:"cortex-attachment-image",children:[e_(T_,{label:Q?.filename||Z||J("translate_image"),expanded:e_("img",{className:"cortex-attachment-image__expanded",src:Y,alt:Z}),children:e_("img",{src:Y,alt:Z})}),Q&&e_("figcaption",{className:"cortex-attachment-image__caption",children:Q.filename})]})}import{useEffect as a4,useRef as o4,useState as i0}from"react";import{jsx as d,jsxs as _1,Fragment as e4}from"react/jsx-runtime";function s4(_){let{t:$}=F();if(!_.pending&&!_.debugMode)return null;return _1("div",{className:"cortex-media-block__head",children:[_.debugMode&&d("span",{className:"cortex-media-block__lang",children:_.language}),_.pending&&d("span",{className:"cortex-media-block__pending",children:$(H1(_.language).pending)}),_.debugMode&&_.closed&&_1("span",{className:"cortex-media-block__actions",children:[_.onToggleSource&&d("button",{type:"button",className:"cortex-media-block__action","aria-pressed":_.sourceShown,onClick:_.onToggleSource,children:$("translate_media_source")}),d(s,{value:_.source})]})]})}function g2(_){let{debugMode:$,t:Z}=F();return d("div",{className:"cortex-media-block__body",children:_1("p",{className:"cortex-media-block__error",children:[_.cutOff?Z("translate_media_cut_off"):Z("translate_media_failed"),!_.cutOff&&$&&` ${_.reason}`]})})}function m2(_){let{language:$,source:Z,closed:Q,hidden:X,onError:J}=_,{config:Y,scheme:G,locale:z}=F(),V=o4(null);return a4(()=>{J(void 0);let K=V.current;if(!Q||!G||!K)return;return q1(K,{language:$,source:Z,context:{scheme:G,locale:z},overrides:Y.mediaRenderers,onError:J})},[$,Z,Q,G,z,Y.mediaRenderers,J]),d("div",{ref:V,hidden:X,className:B("cortex-media-block__body",`cortex-media-block__body--${$}`)})}function t4(_){let[$,Z]=i0();return _1(e4,{children:[$&&d(g2,{cutOff:!1,reason:$}),d(m2,{language:_.language,source:_.source,closed:!0,hidden:Boolean($),onError:Z})]})}function x2(_){let{language:$,source:Z,closed:Q,streaming:X}=_,{debugMode:J,t:Y}=F(),[G,z]=i0(),[V,K]=i0(!1),W=!Q&&!X,N=W||Boolean(G);return _1("div",{className:"cortex-media-block",children:[d(s4,{language:$,source:Z,pending:!Q&&X,closed:Q,debugMode:J,sourceShown:V,onToggleSource:N?void 0:()=>K((H)=>!H)}),N&&d(g2,{cutOff:W,reason:G}),d(T_,{label:Y(H1($).title),ready:Q&&!N,expanded:d(t4,{language:$,source:Z}),children:d(m2,{language:$,source:Z,closed:Q,hidden:N,onError:z})}),J&&(N||V)&&d("pre",{dir:"ltr",className:"cortex-media-block__source",children:Z})]})}import{useMemo as _3,useRef as $3}from"react";import{jsx as U_}from"react/jsx-runtime";var Z3="M8 2.5v7.5M5 7l3 3 3-3M2.75 11v1.25a1.25 1.25 0 0 0 1.25 1.25h8a1.25 1.25 0 0 0 1.25-1.25V11";function h2(_){let{t:$}=F(),Z=$3(null),Q=_3(()=>({__html:l_(_.text)}),[_.text]);function X(){let J=Z.current?.querySelector("table");if(J)r_(P0(O0(J)),"table.xlsx")}return U_("div",{className:"cortex-table-block",children:U_(T_,{label:$("translate_table"),ready:_.closed,actions:U_("button",{type:"button",className:"cortex-expandable__action","aria-label":$("translate_table_export"),title:$("translate_table_export"),onClick:X,children:U_("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:U_("path",{d:Z3,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),expanded:U_("div",{className:"cortex-table-block__expanded",dangerouslySetInnerHTML:Q}),children:U_("div",{ref:Z,dangerouslySetInnerHTML:Q})})})}import{jsx as v_}from"react/jsx-runtime";function c2(_){let{role:$,textPart:Z,streaming:Q=!1,attachments:X=[]}=_,{config:J}=F(),Y=$==="assistant"&&Q?"":Z.content,[G,z]=X3({text:Y,fading:[]}),V=n0(Y),K=n0(null),W=n0(!0);u2(()=>{function H(U,E){V.current=U,z((M)=>M.text===U&&!M.fading.length&&!E.length?M:{text:U,fading:E})}if($!=="assistant"||!Q){K.current?.destroy(),K.current=null,H(Z.content,[]),W.current=!1;return}if(!K.current)K.current=new K_(H),K.current.seed(V.current);if(W.current){W.current=!1,K.current.seed(Z.content);return}K.current.update(Z.content,!1)},[$,Q,Z]),u2(()=>()=>{K.current?.destroy(),K.current=null},[]);let N=Q3(()=>{let H=$==="assistant"?L0(G.text,y0(J.mediaRenderers)):[{kind:"markdown",text:G.text}];return H.map((U,E)=>U.kind==="markdown"?{...U,html:{__html:l_(U.text,E===H.length-1?G.fading:[])}}:U)},[$,G,J.mediaRenderers]),q=Q||G.text!==Z.content;return v_("div",{className:B("cortex-text-part",$==="assistant"&&"cortex-text-part--assistant",$==="user"&&"cortex-text-part--user"),children:v_("div",{className:B("cortex-text-bubble",$==="assistant"&&"cortex-text-bubble--assistant",$==="user"&&"cortex-text-bubble--user"),children:N.map((H,U)=>{switch(H.kind){case"markdown":return v_("div",{dangerouslySetInnerHTML:H.html},U);case"media":return v_(x2,{...H,streaming:q},U);case"table":return v_(h2,{text:H.text,closed:H.closed||!q},U);case"attachment":return v_(f2,{id:H.id,alt:H.alt,attachment:X.find((E)=>E.id.toLowerCase()===H.id)},U)}})})})}import{jsx as l,jsxs as H_}from"react/jsx-runtime";function p2({toolCallPart:_}){let{t:$}=F(),{state:Z,approval:Q}=_,X=_.output,J=h1(_);if(Z==="complete")return H_("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--success",children:[H_("div",{className:"cortex-debug-tool__section-bar",children:[l("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--success",children:$("translate_output")}),l("span",{className:"cortex-debug-tool__section-lang",children:"json"}),l(s,{value:J})]}),l("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:l(W_,{data:X,expandDepth:2})})]});if(Z==="error")return H_("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--error",children:[H_("div",{className:"cortex-debug-tool__section-bar",children:[l("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--error",children:$("translate_error")}),l(s,{value:J})]}),l("pre",{dir:"ltr",className:"cortex-debug-tool__error-pre",children:J})]});if(Z==="approval-requested")return H_("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[H_("div",{className:"cortex-debug-tool__section-bar",children:[l("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:$("translate_approval_requested")}),l("span",{className:"cortex-debug-tool__section-lang",children:Q?.id})]}),l("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:$("translate_waiting_for_approval")})]});if(Z==="approval-responded")return H_("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[H_("div",{className:"cortex-debug-tool__section-bar",children:[l("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:$("translate_approval_response")}),l("span",{className:"cortex-debug-tool__section-lang",children:Q?.id})]}),l("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:$(Q?.approved?"translate_tool_approved":"translate_tool_response_received")})]});return null}import{jsx as J3,jsxs as Y3}from"react/jsx-runtime";function d2({toolCallPart:_}){let{t:$}=F(),Z=x1(_);return Y3("span",{className:B("cortex-debug-tool__state",Z.modifier&&`cortex-debug-tool__state--${Z.modifier}`),children:[Z.pulse&&J3("span",{className:B("cortex-debug-tool__pulse",Z.pulse==="violet"&&"cortex-debug-tool__pulse--violet")}),$(Z.labelKey)]})}import{jsx as x,jsxs as Y_}from"react/jsx-runtime";function l2({toolCallPart:_}){let{t:$}=F(),{codeSnippets:Z,remainingInput:Q,remainingInputText:X}=u1(_.input);return Y_("details",{className:"cortex-debug-tool","data-state":_.state,children:[x("summary",{className:"cortex-debug-tool__summary",children:Y_("div",{className:"cortex-debug-tool__header",children:[Y_("div",{className:"cortex-debug-tool__meta",children:[x("div",{className:"cortex-debug-tool__title-row",children:x("span",{className:"cortex-debug-tool__name",title:_.name,children:_.name})}),x("div",{className:"cortex-debug-tool__id-row",children:x("span",{className:"cortex-debug-tool__id",children:_.id})})]}),Y_("div",{className:"cortex-debug-tool__actions",children:[x(d2,{toolCallPart:_}),x("svg",{className:"cortex-debug-tool__chevron",width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:x("path",{d:f.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),Y_("div",{className:"cortex-debug-tool__body",children:[Z.map((J)=>Y_("div",{className:"cortex-debug-tool__section",children:[Y_("div",{className:"cortex-debug-tool__section-bar",children:[x("span",{className:"cortex-debug-tool__section-label",children:J.key}),x("span",{className:"cortex-debug-tool__section-lang",children:J.lang}),x(s,{value:J.value})]}),x("pre",{dir:"ltr",className:"cortex-debug-tool__pre",children:x("code",{className:"hljs",dangerouslySetInnerHTML:{__html:C0(J.value,J.lang)}})})]},J.key)),!!Q&&Y_("div",{className:"cortex-debug-tool__section",children:[Y_("div",{className:"cortex-debug-tool__section-bar",children:[x("span",{className:"cortex-debug-tool__section-label",children:$("translate_input")}),x("span",{className:"cortex-debug-tool__section-lang",children:"json"}),x(s,{value:X})]}),x("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:x(W_,{data:Q,expandDepth:2})})]}),x(p2,{toolCallPart:_})]})]})}import{useEffect as G3,useRef as V3,useState as i2}from"react";import{jsx as $1,jsxs as n2}from"react/jsx-runtime";function j_({activity:_,className:$}){let{t:Z}=F(),Q=p1(_),[X,J]=i2(0),[Y,G]=i2("idle"),z=V3(Q.length);return z.current=Q.length,G3(()=>{let V,K;function W(){V=setTimeout(()=>{G("exiting"),V=setTimeout(()=>{J((N)=>(N+1)%z.current),G("enter-start"),K=requestAnimationFrame(()=>{G("entering"),V=setTimeout(()=>{G("idle"),W()},300)})},300)},2000)}return W(),()=>{if(V)clearTimeout(V);if(K)cancelAnimationFrame(K)}},[]),n2("div",{className:B("cortex-subtle-activity",$),children:[n2("div",{className:"cortex-subtle-activity__dots",children:[$1("span",{className:"cortex-subtle-activity__dot"}),$1("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d1"}),$1("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d2"})]}),$1("div",{className:"cortex-subtle-activity__label-mask",children:$1("span",{className:B("cortex-subtle-activity__label",`cortex-subtle-activity__label--${Y}`),children:Z(Q[X])})})]})}import{useEffect as e2,useRef as r0,useState as t2}from"react";import{jsx as e,jsxs as f_,Fragment as z3}from"react/jsx-runtime";function r2({toolCallPart:_,asking:$}){let{t:Z,locale:Q,respondToApproval:X}=F(),{sentence:J,decision:Y,decisionKey:G}=c1(_,Q),z=`cortex-approval-${_.id}`,V=V6(_),K=Y==="pending",{state:W,active:N}=Z_(_);function q(H){X(V,H).catch(()=>{})}return f_("div",{className:B("cortex-approval-card",K&&"cortex-approval-card--asking"),children:[K?f_(z3,{children:[f_("div",{className:"cortex-approval-card__head",children:[e("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:e("path",{d:"M8 1.75 2.75 3.75v4c0 3 2.2 5.3 5.25 6.5 3.05-1.2 5.25-3.5 5.25-6.5v-4L8 1.75Z",stroke:"currentColor",strokeWidth:"1.3",strokeLinejoin:"round"})}),Z("translate_approval_needed")]}),e("p",{className:"cortex-approval-card__sentence",id:z,children:J})]}):f_("div",{className:"cortex-approval-card__line",children:[f_("span",{className:"cortex-tool-pill__icon","aria-hidden":"true",children:[e("span",{className:B("cortex-tool-pill__spinner",N&&"cortex-tool-pill__spinner--visible")}),e("svg",{className:B("cortex-tool-pill__svg cortex-tool-pill__svg--check",W==="complete"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:e("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e("svg",{className:B("cortex-tool-pill__svg cortex-tool-pill__svg--error",W==="error"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:e("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})]}),G&&e("span",{className:"cortex-approval-card__decision",children:Z(G)}),e("span",{className:"cortex-approval-card__summary",children:J})]}),K&&$&&f_("div",{className:"cortex-approval-card__foot",children:[e("button",{type:"button",className:"cortex-approval-card__button cortex-approval-card__button--approve","aria-describedby":z,onClick:()=>q(!0),children:Z("translate_approve")}),e("button",{type:"button",className:"cortex-approval-card__button","aria-describedby":z,onClick:()=>q(!1),children:Z("translate_deny")})]})]})}import{useEffect as a2,useRef as E1,useState as o2}from"react";import{jsx as v,jsxs as __}from"react/jsx-runtime";function s2({toolCallPart:_,setOutput:$}){let{t:Z}=F(),{state:Q,id:X,input:J}=_;if(Q==="complete"||Q==="error"){let Y=V0(_.output);return Y?v(W3,{position:Y}):__("div",{className:"cortex-tool-pill",children:[v("span",{className:"cortex-tool-pill__icon",children:v("svg",{className:B("cortex-tool-pill__svg cortex-tool-pill__svg--visible",Q==="error"&&"cortex-tool-pill__svg--error"),viewBox:"0 0 20 20",fill:"none",children:v("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}),v("span",{className:"cortex-tool-pill__title",children:Z("translate_location_not_shared")})]})}if(Q!=="input-complete")return null;return v(K3,{center:G0(J),submit:$},X)}function K3({center:_,submit:$}){let{t:Z}=F(),Q=E1(null),X=E1(void 0),[J,Y]=o2(z1),G=E1({center:_,submit:$});G.current={center:_,submit:$},a2(()=>{let V=Q.current;if(!V)return;let K=J0(V,{center:G.current.center,onState:Y,submit:(W)=>G.current.submit(W)});return X.current=K,K.start(),()=>{if(K.dispose(),X.current===K)X.current=void 0}},[]);let z=z0(J);return __("div",{className:"cortex-location-input",children:[__("div",{className:"cortex-location-input__map",children:[v("div",{className:"cortex-location-input__canvas",ref:Q}),v("button",{type:"button",className:"cortex-location-input__locate","aria-label":Z("translate_location_locate"),title:Z("translate_location_locate"),disabled:J.locating||J.submitting,onClick:()=>X.current?.locate(),children:v(N3,{})})]}),__("div",{className:"cortex-location-input__foot",children:[J.position&&!J.deliveryFailed?v("span",{className:"cortex-location-input__coords",children:K1(J.position)}):__("span",{className:B("cortex-location-input__hint",z.failed&&"cortex-location-input__hint--failed"),children:[J.locating&&v("span",{className:"cortex-location-input__spinner"}),Z(z.key)]}),__("span",{className:"cortex-location-input__actions",children:[v("button",{type:"button",className:"cortex-location-input__skip",disabled:J.submitting,onClick:()=>X.current?.cancel(),children:Z("translate_location_skip")}),v("button",{type:"button",className:"cortex-location-input__send",disabled:!J.position||J.submitting,onClick:()=>X.current?.confirm(),children:Z("translate_location_send")})]})]})]})}function W3({position:_}){let{t:$}=F(),Z=E1(null),[Q,X]=o2(!1),{lat:J,lng:Y}=_;return a2(()=>{let G=Z.current;if(!G)return;return X(!1),Y0(G,{lat:J,lng:Y},()=>X(!0))},[J,Y]),__("div",{className:"cortex-location-input cortex-location-input--settled",children:[__("div",{className:"cortex-location-input__map cortex-location-input__map--still",children:[v("div",{className:"cortex-location-input__canvas",ref:Z,hidden:Q}),Q&&v("span",{className:"cortex-location-input__still-failed",children:$("translate_location_map_failed")})]}),__("div",{className:"cortex-location-input__body",children:[__("span",{className:"cortex-location-input__title",children:[v("svg",{viewBox:"0 0 20 20",fill:"none",children:v("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),$("translate_location_shared")]}),v("span",{className:"cortex-location-input__coords",children:K1(_)})]})]})}function N3(){return __("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:[v("circle",{cx:"10",cy:"10",r:"5.5"}),v("circle",{cx:"10",cy:"10",r:"1.6",fill:"currentColor",stroke:"none"}),v("path",{d:"M10 1.5v3M10 15.5v3M1.5 10h3M15.5 10h3"})]})}import{jsx as C,jsxs as Z1}from"react/jsx-runtime";var H3=new Map([[V1,s2]]);function _5({message:_,toolCallPart:$,agentWorking:Z}){let{config:Q,addToolResult:X}=F(),J=$.state==="input-complete"&&!Z,Y=J&&G1($)?.embed!==void 0,G=$.state==="approval-requested"&&!Z,z=Q.toolComponents?.[$.name]??(J||p($.state)?H3.get($.name):void 0);return C("div",{className:"cortex-tool-call-animated",children:z?C(z,{toolCallPart:$,message:_,setOutput:(V)=>X($.id,$.name,V)}):Y?C(q3,{toolCallPart:$}):C($5,{toolCallPart:$,asking:G})})}function q3({toolCallPart:_}){let{api:$,t:Z,addToolResult:Q,selectedThread:X,config:J}=F(),Y=X?.id,[G,z]=t2({phase:"initiating"}),[V]=t2(J.trustSameOriginEmbeds),K=r0(void 0),W=r0({api:$,addToolResult:Q,toolName:_.name});if(W.current={api:$,addToolResult:Q,toolName:_.name},e2(()=>{if(!Y)return;let q=Q0({initiate:()=>W.current.api.initiateToolCall(Y,_.id),onState:z,submit:(U)=>W.current.addToolResult(_.id,W.current.toolName,U)});K.current=q,q.start();let H=(U)=>q.handleMessage(U);return window.addEventListener("message",H),()=>{if(window.removeEventListener("message",H),q.dispose(),K.current===q)K.current=void 0}},[_.id,Y]),!Y||G.phase==="unavailable")return C($5,{toolCallPart:_,asking:!1});let N=Z1("div",{className:"cortex-client-tool-embed",children:[Z1("div",{className:"cortex-client-tool-embed__bar",children:[C("span",{children:Z("translate_client_tool_title")}),C("button",{type:"button",className:"cortex-client-tool-embed__cancel",onClick:()=>K.current?.cancel(),children:Z("translate_client_tool_cancel")})]}),G.phase==="embedded"?C("iframe",{className:"cortex-client-tool-embed__frame",src:G.embedUrl,sandbox:_0(G.embedUrl,window.location.origin,V),title:Z("translate_client_tool_title"),ref:(q)=>K.current?.setSource(q?.contentWindow),onLoad:(q)=>{if(!$0(G.embedUrl,window.location.origin,V)&&Z0(q.currentTarget,window.location.origin))K.current?.terminate()}}):G.phase==="error"?Z1("div",{className:"cortex-client-tool-embed__status",children:[C("span",{children:Z("translate_client_tool_failed")}),C("button",{type:"button",className:"cortex-client-tool-embed__retry",onClick:()=>void K.current?.start(),children:Z("translate_client_tool_retry")})]}):C("div",{className:"cortex-client-tool-embed__status",children:Z("translate_client_tool_loading")})]});return G.phase==="embedded"&&G.surface==="modal"?C(B3,{label:Z("translate_client_tool_title"),onCancel:()=>K.current?.cancel(),children:N}):N}function B3({label:_,onCancel:$,children:Z}){let Q=r0(null);return e2(()=>{let X=Q.current;return X?.showModal(),()=>X?.close()},[]),C("dialog",{ref:Q,className:"cortex-client-tool-embed-dialog","aria-label":_,onCancel:(X)=>{X.preventDefault(),$()},children:Z})}function $5({toolCallPart:_,asking:$}){return Z_(_).gated?C(r2,{toolCallPart:_,asking:$}):C(D3,{toolCallPart:_})}function D3({toolCallPart:_}){let{t:$}=F(),{state:Z,active:Q,titleKey:X,statement:J,rows:Y}=Z_(_);return Z1("div",{className:"cortex-tool-pill",children:[Z1("span",{className:"cortex-tool-pill__icon",children:[C("span",{className:B("cortex-tool-pill__spinner",Q&&"cortex-tool-pill__spinner--visible")}),C("svg",{className:B("cortex-tool-pill__svg","cortex-tool-pill__svg--check",Z==="complete"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:C("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),C("svg",{className:B("cortex-tool-pill__svg","cortex-tool-pill__svg--error",Z==="error"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:C("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})]}),C("span",{className:B("cortex-tool-pill__title",Z==="error"&&"cortex-tool-pill__title--error",Z==="starting"&&J&&"cortex-tool-pill__title--pending"),children:J??$(X)}),Y!==void 0&&C("span",{className:"cortex-tool-pill__meta",children:$("translate_rows",{count:Y})})]})}import{jsx as Z5}from"react/jsx-runtime";function Q5({message:_,toolCallPart:$,agentWorking:Z}){if(!p($.state)&&!Z_($).statement){if($.name==="executeCode")return Z5(j_,{activity:"code"})}return Z5(_5,{toolCallPart:$,message:_,agentWorking:Z})}import{jsx as g_,jsxs as U3}from"react/jsx-runtime";function X5(_){let{message:$,part:Z,debugMode:Q,animate:X,streaming:J,agentWorking:Y,attachments:G}=_,{t:z}=F();function V(){switch(Z.type){case"text":return g_(c2,{textPart:Z,role:$.role,streaming:J,attachments:G});case"thinking":return Q?g_(v2,{reasoningPart:Z,streaming:J}):g_(j_,{activity:"reasoning",className:"cortex-reasoning-animated"});case"tool-call":return Q?g_(l2,{toolCallPart:Z}):g_(Q5,{toolCallPart:Z,message:$,agentWorking:Y});default:return U3("p",{className:"cortex-unhandled-type",children:[z("translate_unhandled_type")," ",Z.type]})}}return g_("div",{className:B("cortex-message-part",X&&"cortex-message-part--animated",_.folded&&"cortex-message-part--folded"),"data-cortex-frontier":_.frontier?"":void 0,children:V()})}import{jsx as G_,jsxs as a0}from"react/jsx-runtime";function L3({isUser:_,clipboardText:$,createdAt:Z}){let{locale:Q}=F();return a0("div",{className:B("cortex-message-actions",_&&"cortex-message-actions--user"),children:[$&&G_(s,{value:$}),Z&&G_("time",{className:"cortex-message-actions__time",dateTime:Z,children:Q_(Z,Q)})]})}function O3({count:_,animate:$,onOpen:Z}){let{t:Q}=F();return G_("button",{type:"button",className:B("cortex-tool-fold",$&&"cortex-message-part--animated"),onClick:Z,children:Q("translate_more_steps",{count:_})})}function J5(_){let{message:$,parts:Z,metadata:Q,debugMode:X,animate:J,isStreaming:Y,agentWorking:G,closesTurn:z,fold:V,onOpenRun:K,frontier:W}=_,{t:N}=F(),q=$.role==="assistant",H=$.role==="user",U=Y?Z.length-1:-1,E=Q?.attachments??[],M=Z.filter((k)=>V?.get(k)?.kind!=="hidden"),R=M.filter((k)=>k.type==="text").at(-1),P=R?Z.indexOf(R):-1,D=(H||q)&&!Y&&P>=0,L=R!==M.at(-1)?P:-1,O=D&&G_(L3,{isUser:H,clipboardText:l1(Z),createdAt:Q?.createdAt});return a0("div",{className:"cortex-message-parts",children:[Z.map((k,b)=>{let h=V?.get(k);return a0(F3,{children:[G_(X5,{part:k,message:$,debugMode:X,animate:J,streaming:b===U,agentWorking:G,attachments:E,frontier:k===W,folded:h?.kind==="hidden"}),h?.kind==="more"&&G_(O3,{count:h.count,animate:J,onOpen:()=>K(h.runId)}),b===L&&O]},$.parts.indexOf(k))}),E.length>0&&G_(R2,{attachments:E,isUser:H}),Q?.isAborted&&G_(O1,{label:N("translate_aborted")}),L===-1&&O,X&&Q&&z&&G_(T2,{messageId:$.id,isAssistant:q,metadata:Q})]})}import{jsx as F_,jsxs as o0}from"react/jsx-runtime";function Y5({firing:_,debugMode:$}){let{t:Z,locale:Q}=F();return o0("div",{className:B("cortex-trigger-block",$&&"cortex-trigger-block--debug"),children:[o0("div",{className:"cortex-trigger-block__head",children:[F_("svg",{className:"cortex-trigger-block__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:F_("path",{d:"M6.75 1 2.5 6.75h3l-.25 4.25L9.5 5.25h-3z",fill:"currentColor"})}),$&&F_("span",{children:Z("translate_trigger_fired")}),F_("span",{className:"cortex-trigger-block__name",children:_.name}),F_("time",{className:"cortex-trigger-block__time",dateTime:_.firedAt,children:Q_(_.firedAt,Q)})]}),$&&o0("details",{className:"cortex-trigger-block__payload",children:[F_("summary",{children:Z("translate_trigger_payload")}),F_(W_,{data:_.payload,expandDepth:2})]})]})}import{jsx as Q1}from"react/jsx-runtime";var G5=P3(function($){let{message:Z,metadata:Q,isStreaming:X,agentWorking:J,closesTurn:Y,debugMode:G,animate:z,fold:V,onOpenRun:K,workingTurn:W,frontier:N}=$,q=R_(Z.parts,{debugMode:G,isStreaming:X});if(Q?.trigger)return Q1("div",{className:"cortex-message",children:Q1(Y5,{firing:Q.trigger,debugMode:G})});if(!d1(q,Q))return Q1("div",{className:"cortex-message"});return Q1("div",{className:B("cortex-message",W&&"cortex-message--working-turn"),children:Q1(J5,{message:Z,parts:q,metadata:Q,debugMode:G,animate:z,isStreaming:X,agentWorking:J,closesTurn:Y,fold:V,onOpenRun:K,frontier:N})})});import{jsx as R1}from"react/jsx-runtime";var M3=[{role:"user",lines:[13,9]},{role:"assistant",lines:[16,18,12]},{role:"user",lines:[11]},{role:"assistant",lines:[14,15]}];function V5(){return R1("div",{className:"cortex-widget__messages-skeleton",children:M3.map((_,$)=>R1("div",{className:`cortex-widget__msg-skel cortex-widget__msg-skel--${_.role}`,children:R1("div",{className:`cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--${_.role}`,children:_.lines.map((Z)=>R1("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:`${Z}rem`}},Z))})},$))})}import{jsx as a,jsxs as J1,Fragment as z5}from"react/jsx-runtime";function E3(_){let $=L_(null),Z=L_(null),Q=L_(!0),X=L_(!0),J=L_(!1),Y=X1(()=>{if(J.current)return;J.current=!0,queueMicrotask(()=>{J.current=!1;let K=$.current;if(!K)return;D1(K),X.current=!0,Q.current=!1})},[]);s0(()=>{let K=Z.current;if(!_||!$.current||!K)return;if(Y(),typeof ResizeObserver>"u")return;let W=0,N=new ResizeObserver(([q])=>{let H=q?.contentRect.height??0,U=H>W;if(W=H,U&&(Q.current||X.current))Y()});return N.observe(K),()=>N.disconnect()},[_,Y]);let G=X1(()=>{Q.current=!0},[]),z=X1(()=>{if(Q.current)Y()},[Y]);function V(){let K=$.current;if(K)X.current=g0(K)<100}return{containerRef:$,contentRef:Z,onScroll:V,pin:G,settlePinned:z}}function R3({pin:_,settlePinned:$,contentRef:Z},Q,X){let[J,Y]=e0(!1);s0(()=>{Y(!1),_(),queueMicrotask(()=>Y(!0))},[Q,_]);let G=X[X.length-1],z=G?.role==="user"?G.id:void 0,V=z?G?.parts.find((K)=>K.type==="text")?.content:void 0;return t0(()=>{if(!z)return;_();let K=Z.current;if(K&&V!==void 0)f0(K,V)},[z,V,_,Z]),s0(()=>{$()},[X,$]),J}function k3(_,$,Z,Q){let[X,J]=e0(new Set),Y=X1((V)=>J((K)=>new Set(K).add(V)),[]),[G]=e0(r1);return{folds:A3(()=>G(_,{agentWorking:$,debugMode:Z,opened:X,foldable:Q}),[G,_,$,Z,X,Q]),openRun:Y}}function I3({working:_}){let $=L_(null),Z=L_(void 0);return t0(()=>{let Q=$.current;if(!Q)return;let X=m0(Q);return Z.current=X,()=>{X.dispose(),Z.current=void 0}},[]),t0(()=>Z.current?.sync(_)),J1("div",{ref:$,className:"cortex-working-avatar","aria-hidden":"true",children:[J1("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("path",{d:"M9.94 15.5a2 2 0 0 0-1.44-1.44l-6.13-1.58a.5.5 0 0 1 0-.96L8.5 9.94A2 2 0 0 0 9.94 8.5l1.58-6.14a.5.5 0 0 1 .96 0l1.58 6.14a2 2 0 0 0 1.44 1.44l6.14 1.58a.5.5 0 0 1 0 .96l-6.14 1.58a2 2 0 0 0-1.44 1.44l-1.58 6.14a.5.5 0 0 1-.96 0z"}),a("path",{d:"M20 3v4M22 5h-4M4 17v2M5 18H3"})]}),a("span",{className:"cortex-working-avatar__ring"})]})}function K5(_){let{config:$,selectedThread:Z,t:Q}=F(),{messages:X,isAgentWorking:J,isLoadingMessages:Y,hasPendingToolCalls:G,turnFailure:z}=I_(),{capabilities:V,composerRef:K,debugMode:W}=_,N=!Y||J,q=E3(N),H=R3(q,Z?.id,X),U=J?h_(X)?.id:void 0,E=$.toolComponents,M=X1((k)=>i1(k,E),[E]),{folds:R,openRun:P}=k3(X,J,W,M),D=X.map((k)=>k.role).lastIndexOf("user"),L=J&&!W,O=L?n1(X,{foldable:M}):void 0;return J1(z5,{children:[!N?a(V5,{}):a("div",{className:_.className,children:a("div",{ref:q.containerRef,className:"cortex-message-list",onScroll:q.onScroll,children:J1("div",{ref:q.contentRef,className:"cortex-message-list__content",children:[X.map((k,b)=>a(G5,{message:k,metadata:k.metadata,isStreaming:k.id===U,agentWorking:J,fold:R.get(k.id),onOpenRun:P,closesTurn:k.role==="assistant"&&X[b+1]?.role!=="assistant",debugMode:W,animate:H,workingTurn:L&&b>D,frontier:k.id===U?O:void 0},k.id)),z&&J1(z5,{children:[a(O1,{label:Q(x0(z))}),$.showDebugButton&&z.reason&&a("p",{className:"cortex-aborted-flag__reason",children:z.reason})]}),J&&!O&&a("div",{className:"cortex-working-thinking","data-cortex-frontier":"",children:a(j_,{activity:"reasoning"})}),a(I3,{working:J},Z?.id)]})})}),!G&&a(U1,{capabilities:V,composerRef:K})]})}import{jsx as W5,jsxs as y3}from"react/jsx-runtime";function N5(_){let{debugMode:$,selectedThread:Z}=F(),{screens:Q}=_;return y3("div",{className:B("cortex-widget__screen",Q.screen==="chat"&&"cortex-widget__screen--active",Q.screen!=="chat"&&"cortex-widget__screen--right"),children:[_.header,Z?W5(K5,{className:"cortex-widget__messages",debugMode:$,capabilities:_.capabilities,composerRef:_.composerRef}):_.landing,W5("div",{className:"cortex-widget__sidebar-backdrop",onClick:Q.closeSidebar})]})}import{useState as T3}from"react";import{useEffect as _6,useRef as D5,useState as Y1}from"react";import{useChat as w3}from"@tanstack/ai-react";import{useEffect as S3,useLayoutEffect as C3,useState as b3}from"react";function H5(_,{sessionRef:$,pendingSendRef:Z}){let[Q]=b3(_);return C3(()=>{return $.current=Q,()=>{if($.current===Q)$.current=void 0}},[Q,$]),S3(()=>{if(!Z.current.length)return;let X=setTimeout(()=>{let J=Z.current;Z.current=[],(async()=>{for(let{prompt:Y,attachments:G}of J)await Q.send(Y,G)})()});return()=>clearTimeout(X)},[Q,Z]),Q}import{useRef as q5}from"react";function B5(_){let $=q5(_);$.current=_;let Z=q5(Promise.resolve(void 0));async function Q(X,J){let Y=$.current;if(!Y.isAlive()||X!==Y.threadId)return;return o1({api:Y.api,threadId:X,isStale:()=>!$.current.isAlive()||J(),isStreaming:()=>$.current.isStreaming(),setMessages:(G)=>$.current.setMessages(G)})}return function(J,Y){return Z.current=Z.current.then(()=>Q(J,Y)),Z.current}}function U5(_){let{thread:$,api:Z}=_,Q=D5(!0),[X,J]=Y1(!1),[Y,G]=Y1(),[z,V]=Y1(),K=D5(null),W=B5({api:Z,threadId:$.id,isAlive:()=>Q.current,isStreaming:()=>q.streaming(),setMessages:(O)=>K.current.chat.setMessages(O)}),[N]=Y1(()=>h0({threadId:$.id,isAlive:()=>Q.current,onToolCall:()=>K.current.props.configRef.current.hooks?.onToolCall,deliver:(O)=>K.current.chat.addToolResult(O),setRunning:(O)=>K.current.props.setRunning($.id,O),reloadThreads:()=>K.current.props.reloadThreads(),refreshMessages:(O)=>W($.id,O),onTurnFinished:()=>K.current.props.onTurnFinished(),onSendFailed:()=>K.current.props.onSendFailed(),setTurnFailed:(O)=>{if(Q.current)G(O)},returnDraft:(O)=>{if(Q.current)V(O)}})),[q]=Y1(()=>a1({api:Z,thread:{id:$.id,isRunning:$.isRunning},mode:_.mode,localMessages:()=>K.current.chat.messages,onHydrated:(O)=>{if(Q.current)N.hydrated(O,$.isRunning)},onTranscriptCarried:(O)=>{if(Q.current)N.transcriptCarried(O)},onStreamStarted:()=>{if(Q.current)N.streamStarted()},onRefused:(O)=>{if(Q.current)N.sendRefused(O)},setLoadingMessages:(O)=>{if(Q.current)J(O)}})),H=w3({threadId:$.id,persistence:!0,initialMessages:_.initialMessages,connection:q,onChunk:(O)=>{if(Q.current)N.chunkArrived(O)},onError:()=>{if(Q.current)N.streamFailed()},onInterruptStateChange:(O)=>{if(Q.current)N.interruptStateChanged(O)}});K.current={chat:H,props:_};async function U(O,k){N.sendStarted(O);let b={id:u_(),role:"user",parts:[{type:"text",content:O}],metadata:{createdAt:new Date().toISOString(),attachments:k}};await K.current.chat.append(b)}async function E(){if(!K.current.chat.isLoading)return;let{aborted:O}=await Z.abortStream($.id).catch(()=>({aborted:!1}));if(!Q.current)return;if(O)N.abortConfirmed();else K.current.chat.stop()}function M(O,k,b){return N.deliverAnswer(()=>K.current.chat.addToolResult({toolCallId:O,tool:k,output:b}))}function R(O,k){return N.deliverAnswer(()=>X0(K.current.chat,O,k))}function P(O){if(K.current.chat.isLoading)return;if(O.isRunning){K.current.props.remount(O,K.current.chat.messages);return}N.readBack()}_6(()=>{return Q.current=!0,()=>{Q.current=!1}},[]),H5(()=>({threadId:$.id,send:U,abort:E,addToolResult:M,respondToApproval:R,reattach:P,transcriptUpdated:(O,k)=>{if(O===$.id)N.transcriptUpdated(k)}}),{sessionRef:_.sessionRef,pendingSendRef:_.pendingSendRef});let{messages:D,isLoading:L}=H;return _6(()=>{N.loadingChanged(L,()=>K.current.chat.messages)},[N,L]),_6(()=>{K.current.props.publish({messages:D,isAgentWorking:L,isLoadingMessages:X,hasPendingToolCalls:!L&&z_(D).length>0,awaitsApproval:m1(D),returnedDraft:z,turnFailure:Y})},[D,L,X,Y,z]),null}import{jsx as v3,jsxs as j3}from"react/jsx-runtime";function F5({selection:_,threads:$,children:Z,...Q}){let{session:X}=_,[J,Y]=T3(),G=X&&`${X.thread.id}:${X.epoch}`,z=X&&J&&(J.key===G||X.mode==="reload")?J.value:c0;return j3(p0.Provider,{value:z,children:[X&&G&&v3(U5,{thread:X.thread,mode:X.mode,initialMessages:X.initialMessages,setRunning:$.setRunning,reloadThreads:$.reload,remount:_.remount,publish:(V)=>Y({key:G,value:V}),...Q},G),Z]})}import{jsx as j,jsxs as O_,Fragment as f3}from"react/jsx-runtime";function L5(_){let{locale:$,t:Z}=F(),{threads:Q}=_;return j("div",{className:"cortex-widget__threads-list",children:Q===void 0?[1,2,3,4].map((X)=>O_("div",{className:"cortex-widget__thread-skeleton",children:[j("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-icon"}),j("div",{className:"cortex-widget__thread-skeleton-lines",children:j("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-line",style:{width:`${40+X*12}%`}})})]},X)):O_(f3,{children:[Q.map((X)=>{let J=X.id===_.selectedThreadId,Y=Q_(X.updatedAt,$);return O_("div",{className:B("cortex-widget__thread-item",J&&"cortex-widget__thread-item--active"),children:[j("div",{className:B("cortex-widget__thread-icon",J&&"cortex-widget__thread-icon--active"),children:j("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:j("path",{d:f.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),O_("button",{type:"button",onClick:()=>_.openThread(X),className:"cortex-widget__thread-info",children:[O_("div",{className:"cortex-widget__thread-title-row",children:[j("p",{dir:"auto",className:B("cortex-widget__thread-title",J&&"cortex-widget__thread-title--active"),children:X.title??Z("translate_untitled")}),X.isRunning&&O_("span",{className:B("cortex-widget__thread-running",J&&"cortex-widget__thread-running--active"),children:[j("span",{className:"cortex-widget__thread-running-dot"}),Z("translate_running")]})]}),Y&&j("p",{className:"cortex-widget__thread-time",children:Y})]}),j("button",{type:"button","aria-label":Z("translate_delete_conversation"),onClick:()=>_.deleteThread(X.id),className:B("cortex-widget__thread-delete",J&&"cortex-widget__thread-delete--active"),children:j("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:j("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})})}),j("svg",{className:B("cortex-widget__thread-arrow",J&&"cortex-widget__thread-arrow--active"),width:"10",height:"10",viewBox:"0 0 16 16",fill:"none",children:j("path",{d:"M6 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},X.id)}),!Q.length&&O_("div",{className:"cortex-widget__threads-empty",children:[j("div",{className:"cortex-widget__threads-empty-icon",children:j("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__threads-empty-svg",children:j("path",{d:f.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),j("p",{className:"cortex-widget__threads-empty-title",children:Z("translate_no_threads_yet")}),j("p",{className:"cortex-widget__threads-empty-subtitle",children:Z("translate_start_a_new_conversation")}),j("button",{onClick:_.newChat,className:"cortex-widget__new-chat-btn cortex-widget__new-chat-btn--empty-state",children:Z("translate_new_chat")})]})]})})}import{useSyncExternalStore as g3}from"react";function O5(_){return g3(($)=>{let Z=window.matchMedia(_);return Z.addEventListener("change",$),()=>Z.removeEventListener("change",$)},()=>window.matchMedia(_).matches,()=>!1)}import{jsx as x3,jsxs as M5}from"react/jsx-runtime";var m3="(max-width: 768px)";function P5(_){_.preventDefault()}function A5(_){let{screens:$}=_,Z=O5(m3),Q=_.viewMode==="full"?Z&&!$.sidebarOpen:$.screen!=="threads";return x3("div",{className:B("cortex-widget",_.className),"data-cortex-theme":_.theme,children:M5("div",{className:B("cortex-widget__container",_.viewMode==="full"&&"cortex-widget__container--full",$.sidebarOpen&&"cortex-widget__container--sidebar-open"),onDragOver:P5,onDrop:P5,children:[M5("div",{className:B("cortex-widget__screen",$.screen==="threads"&&"cortex-widget__screen--active",$.screen!=="threads"&&"cortex-widget__screen--left"),"aria-hidden":Q||void 0,inert:Q||void 0,children:[_.header,_.threadList]}),_.children]})})}import{jsx as $_}from"react/jsx-runtime";var u3={header:O2,landing:M2,threadList:L5};function $6(_,$){return _?.[$]??u3[$]}function c3(_){let{isAgentWorking:$}=I_();return $_(_.component,{..._.context,isWorking:$})}function p3({config:_,className:$,slots:Z}){let Q=E5(_);Q.current=_;let[X]=k1(()=>j1(()=>Q.current.transport)),J=z2(X),[Y,G]=k1(!1),[z,V]=k1();h3(()=>S0(_.theme,V),[_.theme]);let K=_.viewMode??"helper",W=W2(K),[N,q]=k1(0),{capabilities:H,unanswered:U}=o6(X,N),E=E5(null),M=Z2({api:X,threads:J,getHooks:()=>Q.current.hooks}),{sessionRef:R,selection:P,queue:D,send:L,pendingSendRef:O}=M,{selected:k,selectedRef:b}=P,h=J2({threads:J,selectedRef:b,sessionRef:R,deselect:P.deselect,onReconnect:()=>q((i)=>i+1)}),m_=X2({getConfig:()=>Q.current,onEvent:h.onEvent,onReconnect:h.onReconnect}),V_=f1(_.locale),I1={config:_,locale:V_,t:(i,y1)=>o(V_,i,y1),api:X,debugMode:Y,scheme:z,capabilities:H,unanswered:U,selectedThread:k,send:L,...Y2(R),queue:D.value};function A(){D.store.discardConsumed(),setTimeout(()=>E.current?.focusInput()),J.followTitle(()=>b.current,m_.isOpen)}function I(){D.store.restoreConsumed(b.current?.id)}function w(i){M.openThread(i),W.showChat()}function m(){P.deselect(),W.showChat()}function P_(){G((i)=>!i)}function q_(i){let y1={screen:i,viewMode:K,title:k?.title??null,agentName:E_(_.agentName,V_),threadCount:J.threads?.length,debug:{shown:Boolean(_.showDebugButton),on:Y},newChat:m,openHistory:W.openHistory,closeHistory:W.closeHistory,toggleDebug:P_};return $_(c3,{component:$6(Z,"header"),context:y1})}let c=$6(Z,"landing"),Z6={...g1(H,V_,(i)=>void L(i)),threads:J.threads,composer:$_("div",{className:"cortex-widget__landing-composer",children:$_(U1,{capabilities:H})}),openThread:w,openHistory:W.openHistory},R5=$6(Z,"threadList"),k5={threads:J.threads,selectedThreadId:k?.id,openThread:w,deleteThread:(i)=>void M.deleteThread(i),newChat:m};return $_(u0.Provider,{value:I1,children:$_(F5,{selection:P,threads:J,api:X,configRef:Q,sessionRef:R,pendingSendRef:O,onTurnFinished:A,onSendFailed:I,children:$_(A5,{className:$,theme:_.theme,viewMode:K,screens:W,header:q_("threads"),threadList:$_(R5,{...k5}),children:$_(N5,{screens:W,capabilities:H,composerRef:E,header:q_("chat"),landing:$_(c,{...Z6})})})})})}export{p3 as CortexChatWidget};
|
|
189
|
+
`,a8=/(["'])(?:(?!\1)[^\n\r\f])*\1?|\/\*[\s\S]*?(?:\*\/|$)/g;function s8(_){return/:host|@(-[a-z]+-)?keyframes|@property/i.test(f6(_))}function f6(_){return _.replace(a8,($)=>$.startsWith("/*")?"":$)}async function g6(_){let{default:$}=await import("dompurify"),Z=$.sanitize(_,{FORCE_BODY:!0,RETURN_DOM_FRAGMENT:!0,USE_PROFILES:{html:!0,svg:!0,svgFilters:!0},FORBID_TAGS:["img","picture","source","video","audio","track","a","area","form","input","button","select","textarea","dialog","template","slot","marquee","animatecolor","animatemotion","animatetransform","image","feimage"],FORBID_ATTR:["popover","popovertarget","popovertargetaction"]}),Q=Z.ownerDocument.createElement("div");Q.append(Z);for(let X of Q.querySelectorAll("[style]"))e8(X);n_(Q);for(let X of Q.querySelectorAll("style"))if(s8(X.textContent??""))X.remove();return Q}var t8=/^(-[a-z]+-)?(animation|transition)/i;function e8(_){let $=f6(_.getAttribute("style")??"").split(";");_.setAttribute("style",$.filter((Z)=>!t8.test(Z.trim())).join(";"))}function m6(_,$,Z,Q){let X=document.createElement("style");X.textContent=o8,$.className="cortex-report",_.attachShadow({mode:"open"}).append(X,$);let J=[...$.querySelectorAll("figure[data-chart]")].map((Y)=>{let{box:G,spec:V}=_4(Y);return Z(G,V,()=>{let z=document.createElement("p");z.className="cortex-report-chart-failed",z.textContent=Q,G.append(z)})});return()=>{for(let Y of J)Y()}}function _4(_){let $=[..._.childNodes].filter((X)=>X.nodeName!=="FIGCAPTION"),Z=document.createElement("div");_.insertBefore(Z,$.find((X)=>X.textContent?.trim())??null);for(let X of $)X.remove();let Q=$.map((X)=>X.textContent).join("");return{box:Z,spec:$4.exec(Q)?.[2]??Q}}var $4=/^\s*(`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n\s*\1\s*$/;var p6={async mermaid(_,$,{scheme:Z}){let[{default:Q},{default:X}]=await Promise.all([import("mermaid"),import("dompurify")]);if(E0.test($)||$.includes("\\"))throw Error("Diagrams may not reference URLs.");if(/%%\{/.test($))throw Error("Diagrams may not carry init directives.");if(/^\s*---\s*$/m.test($))throw Error("Diagrams may not carry frontmatter.");if(/\bimg\s*:/.test($))throw Error("Diagrams may not embed images.");let J=X4($);if(!Q4.test(J))throw Error(`Unsupported diagram type: ${J}`);let Y=x6.then(async()=>{if(!h6)Q.initialize({startOnLoad:!1,securityLevel:"strict",htmlLabels:!1}),h6=!0;let z=`%%{init: {"theme": "${Z==="dark"?"dark":"default"}"}}%%
|
|
190
|
+
${$}`;return await Q.parse(z),(await Q.render(`cortex-mermaid-${z4()}`,z,_)).svg});x6=Y.catch(()=>{return});let G=await Y,V=document.createElement("div");return V.innerHTML=X.sanitize(G,{USE_PROFILES:{svg:!0,svgFilters:!0}}),n_(V),_.replaceChildren(...V.childNodes),()=>{_.innerHTML=""}},async "vega-lite"(_,$,{scheme:Z}){let Q=JSON.parse($),X=i_(Q);if(X)throw Error(X);if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error("A chart needs a JSON object.");let J=Q,[{default:Y},G]=await Promise.all([import("vega-embed"),import("vega")]),V=()=>Promise.reject(Error("Charts may only use inline data."));async function z(M){let R=document.createElement("div"),P=await Y(R,G4(J,M),{actions:!1,renderer:"svg",mode:"vega-lite",loader:{...G.loader(),load:V,sanitize:V},ast:!0,...Z==="dark"?{theme:"dark"}:{},config:{background:"transparent"}});return n_(R),{drawing:R,result:P,width:M}}let K=await z(_.clientWidth);_.replaceChildren(K.drawing);let W=!1,N,H=0;function q(){N??=(async()=>{let M=_.clientWidth;while(!W&&M>0&&M!==K.width&&M!==H){try{let R=await z(M);if(W){R.result.finalize();return}K.result.finalize(),K=R,_.replaceChildren(R.drawing)}catch{H=M}M=_.clientWidth}})().finally(()=>{N=void 0})}let U=new ResizeObserver(q);if(d6(J))U.observe(_);function E(){let M=document.getElementById(V4),R=l6(_)??document.body;if(M&&M.parentElement!==R)R.append(M)}return _.addEventListener("pointermove",E),()=>{W=!0,U.disconnect(),_.removeEventListener("pointermove",E),K.result.finalize()}},async map(_,$){let Z=K4(JSON.parse($)),{leaflet:Q,map:X,dispose:J}=await c_(_,{...Z,interactive:!0});for(let Y of Z.markers){let G=Q.marker(Y.position).addTo(X);if(Y.label){let V=document.createElement("span");V.textContent=Y.label,G.bindTooltip(V)}}return J},async report(_,$,Z){let Q=await g6($);return m6(_,Q,(X,J,Y)=>q1(X,{language:"vega-lite",source:J,context:Z,overrides:void 0,onError:Y}),a(Z.locale,"translate_media_failed"))}},Z4={mermaid:{title:"translate_media_mermaid",pending:"translate_media_pending_mermaid"},"vega-lite":{title:"translate_media_vega_lite",pending:"translate_media_pending_vega_lite"},map:{title:"translate_media_map",pending:"translate_media_pending_map"},report:{title:"translate_media_report",pending:"translate_media_pending_report"}};function H1(_){return Z4[_]??{title:"translate_media",pending:"translate_media_pending"}}function I0(_){return Object.keys({...p6,..._})}function q1(_,$){let{language:Z,source:Q,context:X,overrides:J,onError:Y}=$,G=_.appendChild(document.createElement("div")),V=J?.[Z]??p6[Z],z,K=!1;return(V?V(G,Q,X):Promise.reject(Error(`No renderer for ${Z}.`))).then((N)=>{if(K)N();else z=N},(N)=>{if(!K)Y(N instanceof Error?N.message:String(N))}),()=>{K=!0,z?.(),G.remove()}}var Q4=/^(flowchart|graph|sequenceDiagram|stateDiagram(-v2)?|erDiagram|gantt|pie|classDiagram|journey|timeline|mindmap)$/;function X4(_){let $=_.split(`
|
|
191
|
+
`).find((Z)=>/\S/.test(Z)&&!/^\s*%%/.test(Z));return/^\s*(\S+)/.exec($??"")?.[1]??""}function k0(_){return _===void 0||_==="container"}var J4=["row","column","facet"];function d6(_){let $=_.encoding,Z=typeof $==="object"&&$!==null&&J4.some((Q)=>(Q in $));return(("mark"in _)||("layer"in _))&&k0(_.width)&&!Z}function Y4(_){let $={..._};if(k0($.width))delete $.width;if(k0($.height))delete $.height;return $}function G4(_,$){let Z=Y4(_);if($<=0||!d6(_))return Z;return{...Z,width:$,height:Z.height??Math.round(Math.min(480,Math.max(200,$/2))),autosize:Z.autosize??{type:"fit",contains:"padding"}}}var V4="vg-tooltip-element";function l6(_){let $=_.getRootNode();return _.closest("dialog")??($ instanceof ShadowRoot?l6($.host):null)}var x6=Promise.resolve(),h6=!1,u6=0;function z4(){return u6+=1,u6}function K4(_){if(!_||typeof _!=="object")throw Error("A map needs a JSON object.");let $=_,Z=$.zoom??10;if(typeof Z!=="number"||Z<0||Z>22)throw Error("zoom must be 0 to 22.");let Q=$.markers??[];if(!Array.isArray(Q))throw Error("markers must be a list.");return{center:c6($.center,"center"),zoom:Z,markers:Q.map((X,J)=>{let Y=X??{},G=Y.label;return{position:c6(Y.position,`markers[${J}].position`),label:typeof G==="string"?G:void 0}})}}function c6(_,$){let Z=Array.isArray(_)?_:[],[Q,X]=Z;if(typeof Q!=="number"||typeof X!=="number"||Math.abs(Q)>90||Math.abs(X)>180)throw Error(`${$} must be [latitude, longitude].`);return{lat:Q,lng:X}}function y0(_,$){if(_!=="system")return $(_??"light"),()=>{};let Z=window.matchMedia("(prefers-color-scheme: dark)"),Q=()=>$(Z.matches?"dark":"light");return Q(),Z.addEventListener("change",Q),()=>Z.removeEventListener("change",Q)}import B1 from"highlight.js/lib/core";import W4 from"highlight.js/lib/languages/javascript";import N4 from"highlight.js/lib/languages/json";var i6=!1;function H4(){if(i6)return;i6=!0,B1.registerLanguage("javascript",W4),B1.registerLanguage("json",N4)}function S0(_,$){if(!_)return"";return H4(),B1.getLanguage($)?B1.highlight(_,{language:$}).value:q4(_)}function q4(_){return _.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function k_(_){if(typeof _==="string"){let $=_.trim();if(!($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")))return _;try{return k_(JSON.parse($))}catch{return _}}if(Array.isArray(_))return _.map(($)=>k_($));if(_!==null&&typeof _==="object"){let $={};for(let[Z,Q]of Object.entries(_))$[Z]=k_(Q);return $}return _}function C0(_,$){if(Array.isArray(_)){let Z=_;return{kind:"container",open:"[",close:"]",summary:n6(Z.length,"item","items"),entries:Z.map((Q,X)=>({key:null,value:Q,path:`${$}[${X}]`}))}}if(_!==null&&typeof _==="object"){let Z=Object.entries(_);return{kind:"container",open:"{",close:"}",summary:n6(Z.length,"property","properties"),entries:Z.map(([Q,X])=>({key:Q,value:X,path:`${$}.${Q}`}))}}return{kind:"primitive",text:B4(_),className:D4(_)}}function n6(_,$,Z){return`${_} ${_===1?$:Z}`}function B4(_){if(_===null||_===void 0)return"null";if(typeof _==="string")return JSON.stringify(_);if(typeof _==="number"||typeof _==="boolean")return String(_);return JSON.stringify(_)??"null"}function D4(_){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 b0(_){if(!_)return null;try{return JSON.parse(_)}catch{return _}}function w0(_){if(!_)return"";try{return JSON.stringify(JSON.parse(_),null,2)}catch{return _}}function Q_(_,$,Z=Date.now()){let Q=new Date(_);if(Number.isNaN(Q.getTime()))return"";let X=Q.toDateString()===new Date(Z).toDateString();return new Intl.DateTimeFormat($,{...X?{}:{dateStyle:"medium"},timeStyle:"short"}).format(Q)}function r_(_,$){let Z=URL.createObjectURL(_),Q=document.createElement("a");Q.href=Z,Q.download=$,document.body.append(Q),Q.click(),Q.remove(),setTimeout(()=>URL.revokeObjectURL(Z),40000)}class K_{onUpdate;fullText="";displayedLength=0;animationFrameId=null;isDone=!1;releases=[];static DRAIN_FRACTION=0.03;static MIN_CHARS_PER_FRAME=1;static DONE_DRAIN_FRACTION=0.1;static FADE_WINDOW_MS=500;constructor(_){this.onUpdate=_}seed(_){this.fullText=_,this.displayedLength=_.length,this.releases=[],this.onUpdate(_,[])}update(_,$){if(this.fullText=_,this.isDone=$,this.displayedLength=Math.min(this.displayedLength,this.fullText.length),this.releases=this.releases.filter((Z)=>Z.from<this.displayedLength),$&&this.displayedLength>=this.fullText.length){this.onUpdate(this.fullText,[]),this.stopAnimation();return}if(!this.animationFrameId)this.scheduleFrame()}destroy(){this.stopAnimation()}scheduleFrame(){this.animationFrameId=requestAnimationFrame((_)=>this.tick(_))}tick(_){let $=this.fullText.length-this.displayedLength;if($<=0){this.animationFrameId=null;return}let Z=this.isDone?K_.DONE_DRAIN_FRACTION:K_.DRAIN_FRACTION,Q=Math.max(K_.MIN_CHARS_PER_FRAME,Math.ceil($*Z));if(this.releases=this.releases.filter((X)=>_-X.at<K_.FADE_WINDOW_MS),this.releases.push({from:this.displayedLength,at:_}),this.displayedLength=Math.min(this.fullText.length,this.displayedLength+Q),this.onUpdate(this.fullText.substring(0,this.displayedLength),this.releases.map((X)=>({length:this.displayedLength-X.from,age:_-X.at}))),this.displayedLength<this.fullText.length)this.scheduleFrame();else this.animationFrameId=null}stopAnimation(){if(this.animationFrameId)cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null}}var T0=new WeakMap;function v0(_,$){let Z=_.closest(".cortex-widget__screen"),Q=Z?.querySelector(".cortex-message-list");if(!Z||!Q||!_.value.trim())return;let X=getComputedStyle(_),J=_.getBoundingClientRect(),Y=(G)=>parseFloat(X[`padding${G}`])+parseFloat(X[`border${G}Width`]);T0.set(Z,{text:$,textarea:_,from:new DOMRect(J.left+Y("Left"),J.top+Y("Top"),J.width-Y("Left")-Y("Right"),J.height-Y("Top")-Y("Bottom")),rtl:X.direction==="rtl",scrollTop:Q.scrollTop})}function j0(_,$){let Z=_.closest(".cortex-widget__screen"),Q=Z?T0.get(Z):void 0;if(!Z||!Q)return;T0.delete(Z);let X=_.querySelectorAll(":scope > .cortex-message"),J=X[X.length-1]?.querySelector(".cortex-text-bubble--user"),Y=_.closest(".cortex-message-list");if(!J||!Y||Q.text!==$||!Q.textarea.isConnected)return;J.closest(".cortex-message-part")?.getAnimations().forEach((M)=>M.finish()),D1(Y);let G=J.getBoundingClientRect(),V=Z.getBoundingClientRect(),z=getComputedStyle(J),K=parseFloat(z.paddingTop)+parseFloat(z.borderTopWidth),W=Q.rtl?parseFloat(z.paddingRight)+parseFloat(z.borderRightWidth):parseFloat(z.paddingLeft)+parseFloat(z.borderLeftWidth),N=Q.rtl?Q.from.right+W-G.width:Q.from.left-W,H=Y.scrollTop-Q.scrollTop;if(H)_.style.setProperty("--cortex-slide",`${H}px`),_.classList.remove("cortex-message-list__content--settling"),_.offsetWidth,_.classList.add("cortex-message-list__content--settling"),_.getAnimations()[0]?.finished.then(()=>_.classList.remove("cortex-message-list__content--settling"),()=>{return});let q=J.cloneNode(!0);q.classList.add("cortex-send-flight"),q.setAttribute("aria-hidden","true"),Object.assign(q.style,{left:`${G.left-V.left}px`,top:`${G.top-V.top}px`,width:`${G.width}px`}),q.style.setProperty("--cortex-fly-x",`${N-G.left}px`),q.style.setProperty("--cortex-fly-y",`${Q.from.top-K-G.top}px`),J.style.visibility="hidden",Z.append(q);let U=Y.scrollTop,E=()=>{q.style.top=`${G.top-V.top-(Y.scrollTop-U)}px`};Y.addEventListener("scroll",E,{passive:!0}),a6(q).then(()=>{Y.removeEventListener("scroll",E),J.style.visibility="",q.remove()})}function D1(_){_.scrollTop=o6(_)}function f0(_){return o6(_)-_.scrollTop}function o6(_){let $=_.querySelector(".cortex-message-list__content");if(!$)return _.scrollHeight-_.clientHeight;let Z=getComputedStyle(_);return $.offsetHeight+parseFloat(Z.paddingTop)+parseFloat(Z.paddingBottom)-_.clientHeight}function g0(_){let $=!1,Z=_.parentElement,Q=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{if($)X()});Q?.observe(Z);function X(){let J=Z.querySelector(":scope > .cortex-working-thinking, :scope > .cortex-message > .cortex-message-parts > [data-cortex-frontier]");if(!J)return!1;return _.style.setProperty("--cortex-avatar-y",`${U4(J,Z)-_.offsetHeight/2}px`),!0}return{sync(J){if(J===$){if(J)X();return}if(J){if(!X())return;_.classList.remove("cortex-working-avatar--leaving"),_.offsetWidth,_.classList.add("cortex-working-avatar--shown"),$=!0;return}$=!1;let[,Y="0px"]=getComputedStyle(_).translate.split(" ");_.style.setProperty("--cortex-avatar-y",Y),_.classList.add("cortex-working-avatar--leaving"),a6(_,!0).then(()=>{if($)return;_.classList.remove("cortex-working-avatar--shown","cortex-working-avatar--leaving")})},dispose(){Q?.disconnect()}}}function U4(_,$){let Z=_.querySelector(".cortex-text-bubble");if(!Z)return r6(_,$)+_.offsetHeight/2;let Q=getComputedStyle(Z);return r6(Z,$)+parseFloat(Q.paddingTop)+parseFloat(Q.borderTopWidth)+parseFloat(Q.lineHeight)/2}function r6(_,$){let Z=0;for(let Q=_;Q instanceof HTMLElement&&Q!==$;)Z+=Q.offsetTop,Q=Q.offsetParent;return Z}function a6(_,$=!1){return Promise.allSettled(_.getAnimations({subtree:$}).map((Z)=>Z.finished))}import{EventType as F4}from"@tanstack/ai";function m0(_){return _.refusal==="approval_pending"?"translate_approval_pending":"translate_error"}var L4=2;function x0(_){let $=!1,Z=!1,Q=!1,X,J,Y,G,V=!1,z=!1,K,W,N=new Set,H=0,q=!1,U=new Set,E=new Set,M,R=new Map,P=0,D=0,L=0;async function O(A){let I=Symbol("delivery");U.add(I);try{if(await A(),M&&await M.over)E.add(I);if(E.has(I))throw Error("The answer did not reach Cortex")}finally{U.delete(I),E.delete(I)}}function k(){if($&&H===0)return!1;if(H+=1,!$)$=!0,_.setRunning(!0);return!0}function b(A){if(H-=1,A)q=!0;else if(H===0&&!q)$=!1,_.setRunning(!1)}async function x(){let A=P,I=++D,w=()=>P!==A||L>I||!_.isAlive(),h=await _.refreshMessages(w).catch(()=>{return});if(!h||w())return!1;L=I;let q_=new Set(z_(h).map((c)=>c.id));for(let c of R.keys())if(!q_.has(c))R.delete(c);if($)V_(h);let P_=[...R.values()];if(P_.some((c)=>c.failedResends>=L4))return!1;for(let c of P_)if(!await O(()=>_.deliver(c.answer)).then(()=>!0,()=>!1))return c.failedResends+=1,x();return!0}async function m_(A,I){let w;try{let c=I({toolCallId:A.id,toolName:A.name,input:A.input},{threadId:_.threadId});if(c===null||c===void 0)return;w=await Promise.resolve(c)}catch{N.delete(A.id);return}if(w===null||w===void 0)return;if(!_.isAlive())return;let h=k(),q_={toolCallId:A.id,tool:A.name,output:w};R.set(A.id,{answer:q_,failedResends:0});let P_=await O(()=>_.deliver(q_)).then(()=>!0,x);if(h)b(P_)}function V_(A){let I=z_(A),w=_.onToolCall();if(!w)return I.length>0;for(let h of I){if(h.state!=="input-complete"||N.has(h.id))continue;N.add(h.id),m_(h,w)}return I.length>0}async function I1(A){if(Q)_.reloadThreads().catch(()=>{});else _.setRunning(!1);if($&&!V&&V_(A()))return;if(W===void 0&&K!==void 0)return;W=void 0,await x()}return{chunkArrived(A){if(Z=!0,U.clear(),A.type===F4.RUN_ERROR&&A.code!=="aborted")X={reason:A.message||void 0}},transcriptCarried(A){if(K=A,W!==void 0&&W<=A)W=void 0},transcriptUpdated(A){let I=Date.parse(A);if(K!==void 0&&I<=K)return;if(!z){x();return}W=Math.max(W??0,I)},streamFailed(){Q=!0;let A=U.size>0;for(let h of U)E.add(h);if(U.clear(),V)return;if(Z)_.onTurnFinished();else _.onSendFailed();if(J){if(_.setTurnFailed({reason:void 0,refusal:J}),G!==void 0)_.returnDraft(G);return}let w=X??($&&!A&&!Z?{reason:void 0}:void 0);if(w)_.setTurnFailed(w)},loadingChanged(A,I){if(A){z=!0;return}if(!z)return;z=!1,_.onTurnFinished(),I1(I)},hydrated(A,I){if(I)return;setTimeout(()=>{if(_.isAlive())V_(A)},0)},deliverAnswer(A){let I=k(),w=O(A).catch(async(h)=>{throw await x(),h});return w.then(()=>{if(I)b(!0)},()=>{if(I)b(!1)}),w},interruptStateChanged(A){if(A.resuming){if(M)return;let I=()=>{},w=new Promise((h)=>{I=h});M={errorsAtStart:A.interruptErrors.length,over:w,end:I};return}M?.end(A.interruptErrors.length>M.errorsAtStart),M=void 0},readBack:x,streamStarted(){if($)_.setRunning(!0);P+=1,Q=!1,X=void 0,J=void 0,G=Y,Y=void 0,K=void 0,V=!1,_.setTurnFailed(void 0)},sendStarted(A){P+=1,Y=A,_.returnDraft(void 0),$=!0,Z=!1},sendRefused(A){J=A},abortConfirmed(){V=!0}}}function o_(_){if(_.input.total<=0)return null;return Math.round(_.input.cacheRead/_.input.total*100)}import{createContext as s6,useContext as t6}from"react";var h0=s6(void 0);function F(){let _=t6(h0);if(!_)throw Error("useCortex must be used inside <CortexChatWidget>");return _}var u0={messages:[],isAgentWorking:!1,isLoadingMessages:!1,hasPendingToolCalls:!1,awaitsApproval:!1,returnedDraft:void 0,turnFailure:void 0},c0=s6(u0);function I_(){return t6(c0)}import{useEffect as O4,useState as e6}from"react";function _2(_,$){let[Z,Q]=e6(),[X,J]=e6();return O4(()=>{return Q(void 0),J(void 0),p_(()=>_.getCapabilities(),{onAnswered:(Y)=>{Q(Y),J(void 0)},onMissed:J})},[_,$]),{capabilities:Z,unanswered:X}}import{useRef as y4}from"react";import{useRef as P4,useState as M4,useSyncExternalStore as A4}from"react";function $2(_,$){let Z=P4($);Z.current=$;let[Q]=M4(()=>s1({api:_,ensureThread:()=>Z.current()})),X=A4(Q.subscribe,Q.getState,Q.getState);return{store:Q,value:{items:X,...t1(X),accept:Q.accept,remove:Q.remove,consumeReady:Q.consumeReady}}}import{useEffect as E4,useRef as R4}from"react";function Z2(_,$){let Z=R4(void 0);E4(()=>{if($===Z.current)return;_.clear(Z.current),Z.current=$},[$,_])}import{useRef as Q2}from"react";function X2(_){let $=Q2([]),Z=Q2(void 0);function Q(){let J=_.selectedRef.current;if(J)return Promise.resolve(J.id);return Z.current??=_.api.createThread().then((Y)=>{return Z.current=void 0,_.onCreated(Y),Y.id},(Y)=>{throw Z.current=void 0,Y}),Z.current}async function X(J,Y=[]){let G=_.sessionRef.current;if(G){await G.send(J,Y);return}$.current.push({prompt:J,attachments:Y});try{await Q()}catch(V){throw $.current=[],V}}return{ensureThread:Q,send:X,pendingSendRef:$}}import{useEffect as k4,useRef as p0,useState as I4}from"react";function J2(_){let[$,Z]=I4(),Q=$?.thread,X=Q?_.threads?.find((W)=>W.id===Q.id)??Q:void 0,J=p0(X);J.current=X;function Y(W,N){if(J.current?.id===W.id&&_.hasSession())return;let H=J.current;if(J.current=W,Z({thread:W,mode:N,epoch:0}),H&&H.id!==W.id)_.getHooks()?.onThreadDeselected?.(H);_.getHooks()?.onThreadSelected?.(W)}function G(){let W=J.current;if(!W&&!_.hasSession())return;if(J.current=void 0,Z(void 0),W)_.getHooks()?.onThreadDeselected?.(W)}let V=p0(_.initialThreadId),z=p0(Y);z.current=Y,k4(()=>{let W=_.threads?.find((N)=>N.id===V.current);if(!W)return;V.current=void 0,z.current(W,"load")},[_.threads]);function K(W,N){Z((H)=>({thread:W,mode:"reload",epoch:(H?.epoch??0)+1,initialMessages:N}))}return{session:$,selected:X,selectedRef:J,select:Y,deselect:G,remount:K}}function Y2(_){let{api:$,threads:Z}=_,Q=y4(void 0),X=J2({threads:Z.threads,getHooks:_.getHooks,hasSession:()=>Q.current!==void 0,initialThreadId:_.initialThreadId}),J=X2({api:$,sessionRef:Q,selectedRef:X.selectedRef,onCreated:(z)=>{Z.upsert(z),X.select(z,"skip")}}),Y=$2($,J.ensureThread);Z2(Y.store,X.selected?.id);async function G(z){if(X.selectedRef.current?.id===z)X.deselect();await Z.remove(z)}function V(z){X.select(z,"load")}return{sessionRef:Q,selection:X,queue:Y,deleteThread:G,openThread:V,...J}}import{useEffect as S4,useRef as G2}from"react";function V2(_){let $=G2(_);$.current=_;let Z=G2(void 0);return S4(()=>{let Q=!1,X=W0({getConfig:()=>$.current.getConfig(),onEvent:(J)=>$.current.onEvent(J),onOpen:()=>{if(Q)$.current.onReconnect();Q=!0}});return Z.current=X,()=>{X.close(),Z.current=void 0}},[]),{isOpen:()=>Z.current?.isOpen()??!1}}function z2(_){let{threads:$,selectedRef:Z,sessionRef:Q}=_;function X(Y){$.applyEvent(Y);let G=Z.current?.id;switch(Y.type){case"thread:deleted":if(G===Y.payload.threadId)_.deselect();break;case"thread:run-started":if(G===Y.payload.thread.id)Q.current?.reattach(Y.payload.thread);break;case"thread:messages-updated":case"thread:run-finished":Q.current?.transcriptUpdated(Y.payload.thread.id,Y.payload.thread.updatedAt);break}}function J(){_.onReconnect(),$.reload().then((Y)=>{let G=Z.current;if(!Y||!G)return;Q.current?.reattach(Y.find((V)=>V.id===G.id)??G)})}return{onEvent:X,onReconnect:J}}function K2(_){return{abort:async()=>{await _.current?.abort()},addToolResult:($,Z,Q)=>_.current?.addToolResult($,Z,Q)??Promise.resolve(),respondToApproval:($,Z)=>_.current?.respondToApproval($,Z)??Promise.resolve()}}import{useEffect as W2,useRef as C4,useState as N2}from"react";function H2(_){let[$,Z]=N2(),[Q]=N2(U0),X=C4(void 0);W2(()=>()=>X.current?.(),[]),W2(()=>p_(()=>Q.read(()=>_.listThreads()),{onAnswered:({show:W})=>Z(W),onMissed:(W)=>{if(W!=="unreachable")Z((N)=>N??[])}}),[_,Q]);async function J(){let W=await Q.read(()=>_.listThreads()).catch(()=>{return});if(W)Z(W.show);return W?.listed}function Y(W){Z((N)=>d_(N??[],W))}function G(W,N){Z(Q.running(W,N))}function V(W,N){X.current?.();let H=W()?.id;if(!H)return;X.current=B0({threadId:H,listThreads:()=>_.listThreads(),selected:W,socketOpen:N,setTitle:(q)=>Z((U)=>U&&q0(U,H,q))})}async function z(W){await _.deleteThread(W),Z((N)=>N?W1(N,W):N)}function K(W){if(!Q.admits(W))return;Z((N)=>{let H=D0(N??[],W);return N||H.length?H:N})}return{threads:$,reload:J,upsert:Y,setRunning:G,followTitle:V,remove:z,applyEvent:K}}import{useState as q2}from"react";function B2(_){let[$,Z]=q2("chat"),[Q,X]=q2(!1);return{screen:$,sidebarOpen:Q,showChat:()=>{Z("chat"),X(!1)},openHistory:()=>_==="full"?X(!0):Z("threads"),closeHistory:()=>_==="full"?X(!1):Z("chat"),closeSidebar:()=>X(!1)}}import{forwardRef as g4,useEffect as m4,useImperativeHandle as x4,useRef as P2,useState as M2}from"react";function B(..._){return _.filter(Boolean).join(" ")}import{useState as b4}from"react";function D2(_,$){let[Z,Q]=b4(!1);return{dragging:Z,onDragOver:(X)=>{if(X.preventDefault(),_)Q(!0)},onDragLeave:(X)=>{if(!X.currentTarget.contains(X.relatedTarget))Q(!1)},onDrop:(X)=>{if(X.preventDefault(),Q(!1),_)$([...X.dataTransfer.files])},onPaste:(X)=>{let J=X.clipboardData.files;if(!_||!J.length)return;X.preventDefault(),$([...J])}}}var f={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{jsx as n,jsxs as a_}from"react/jsx-runtime";function U2(){let{queue:_,t:$,locale:Z}=F();if(!_.items.length)return null;return n("div",{className:"cortex-attachment-queue",children:_.items.map((Q)=>a_("div",{className:B("cortex-attachment-chip",Q.status==="error"&&"cortex-attachment-chip--error"),children:[Q.status==="uploading"||Q.status==="deleting"?a_("svg",{className:"cortex-attachment-chip__spinner",viewBox:"0 0 16 16",fill:"none",children:[n("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"2",className:"cortex-attachment-chip__spinner-track"}),n("path",{d:"M14 8a6 6 0 0 0-6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):Q.status==="error"?a_("svg",{viewBox:"0 0 16 16",className:"cortex-attachment-chip__icon",fill:"none",children:[n("circle",{cx:"8",cy:"8",r:"6",stroke:"currentColor",strokeWidth:"1.25"}),n("path",{d:"M8 4.75v4M8 10.75v.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})]}):a_("svg",{viewBox:"0 0 16 16",className:"cortex-attachment-chip__icon",fill:"none",children:[n("path",{d:f.file[0],stroke:"currentColor",strokeWidth:"1.25"}),n("path",{d:f.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),a_("span",{className:"cortex-attachment-chip__text",children:[n("span",{className:"cortex-attachment-chip__name",children:n("bdi",{children:Q.filename})}),Q.status==="error"&&n("span",{className:"cortex-attachment-chip__reason",children:a1(Q,Z)})]}),n("button",{type:"button",onClick:()=>_.remove(Q.localId),className:"cortex-attachment-chip__remove",disabled:Q.status==="deleting","aria-label":$("translate_remove_attachment"),children:n("svg",{viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M4.5 4.5l7 7m0-7l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]},Q.localId))})}import{useRef as w4}from"react";import{jsx as B_,jsxs as F2,Fragment as v4}from"react/jsx-runtime";var T4=x_.join(",");function L2({attachmentsEnabled:_,canSend:$,onSend:Z}){let{t:Q,queue:X}=F(),J=w4(null);return F2("div",{className:"cortex-widget__input-actions",children:[_&&F2(v4,{children:[B_("button",{type:"button",onClick:()=>J.current?.click(),className:"cortex-widget__attach-btn","aria-label":Q("translate_attach_files"),children:B_("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:B_("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"})})}),B_("input",{ref:J,type:"file",multiple:!0,accept:T4,onChange:(Y)=>{X.accept([...Y.target.files??[]]),Y.target.value=""},className:"cortex-widget__file-input"})]}),B_("button",{onClick:Z,"aria-label":Q("translate_send"),className:B("cortex-widget__send-btn",!$&&"cortex-widget__send-btn--empty",$&&"cortex-widget__send-btn--ready"),disabled:!$,children:B_("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__send-icon",children:B_("path",{d:"M3 8h10M9 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}import{useLayoutEffect as j4}from"react";import{jsx as f4}from"react/jsx-runtime";function O2(_){let{t:$}=F();j4(()=>{let Q=_.inputRef.current;if(!Q)return;Q.style.height="0px",Q.style.height=`${Q.scrollHeight}px`},[_.inputRef,_.value]);function Z(Q){if(Q.key==="Enter"&&!Q.shiftKey)Q.preventDefault(),_.onSubmit()}return f4("textarea",{ref:_.inputRef,onKeyDown:Z,onPaste:_.onPaste,value:_.value,onChange:(Q)=>_.onChange(Q.target.value),placeholder:_.dragging?$("translate_drop_files_here"):_.disabled?"":$("translate_type_a_message"),disabled:_.disabled,rows:1,className:B("cortex-widget__textarea",_.disabled&&"cortex-widget__textarea--disabled")})}import{jsx as y_,jsxs as d0}from"react/jsx-runtime";function h4(_){let[$,Z]=M2(_??""),[Q,X]=M2(_);if(_!==Q){if(X(_),_&&!$)Z(_)}return[$,Z]}var A2=g4(function($,Z){let{t:Q,queue:X,send:J,abort:Y,capabilities:G}=F(),{isAgentWorking:V,awaitsApproval:z,returnedDraft:K}=I_(),W=G?.attachments??!1,[N,H]=h4(K),q=D2(W,X.accept),U=P2(null);x4(Z,()=>({focusInput:()=>U.current?.focus()}));let E=P2(V);m4(()=>{if(E.current&&!V)U.current?.focus();E.current=V},[V]);let M=!z&&!X.busy&&(Boolean(N.trim())||X.hasReady);function R(){if(V||!M)return;let P=N.trim()||Q("translate_attachment_caption"),D=X.consumeReady();if(U.current)v0(U.current,P);H(""),J(P,D.map((L)=>L.summary))}return d0("div",{className:"cortex-widget__input-area",onDragOver:q.onDragOver,onDragLeave:q.onDragLeave,onDrop:q.onDrop,children:[y_(U2,{}),d0("div",{className:B("cortex-widget__input-box",V&&"cortex-widget__input-box--disabled",!V&&"cortex-widget__input-box--enabled",q.dragging&&"cortex-widget__input-box--dragging"),children:[y_(O2,{inputRef:U,value:N,onChange:H,onSubmit:R,onPaste:q.onPaste,disabled:V,dragging:q.dragging}),V?d0("button",{type:"button","aria-label":Q("translate_stop"),onClick:()=>void Y(),className:"cortex-stop-btn",children:[y_("span",{className:"cortex-stop-btn__ring"}),y_("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"cortex-stop-btn__icon",children:y_("rect",{x:"1",y:"1",width:"10",height:"10",rx:"2.5",fill:"currentColor"})})]}):y_(L2,{attachmentsEnabled:W,canSend:M,onSend:R})]})]})});import{jsx as l0}from"react/jsx-runtime";function U1({capabilities:_,composerRef:$}){let{t:Z,unanswered:Q}=F();if(_===void 0)return Q?l0("p",{className:"cortex-widget__messages-disabled",children:Z(N0[Q])}):null;return _.messages===!1?l0("p",{className:"cortex-widget__messages-disabled",children:Z(_.readOnly?"translate_read_only":"translate_messages_disabled")}):l0(A2,{ref:$})}import{jsx as u,jsxs as F1}from"react/jsx-runtime";function E2(_){let{t:$}=F(),Z=_.newChat&&u("button",{type:"button",onClick:_.newChat,"aria-label":$("translate_new_chat"),title:$("translate_new_chat"),className:"cortex-widget__header-btn cortex-widget__new-btn",children:u("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:u("path",{d:"M8 3v10M3 8h10",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})});if(_.screen==="threads")return F1("div",{className:"cortex-widget__threads-header",children:[u("button",{type:"button",onClick:_.closeHistory,"aria-label":$("translate_back"),className:"cortex-widget__header-btn cortex-widget__back-btn",children:u("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",className:"cortex-widget__back-icon",children:u("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),F1("div",{children:[u("h2",{className:"cortex-widget__threads-title",children:$("translate_history")}),_.threadCount!==void 0&&u("p",{className:"cortex-widget__threads-count",children:$("translate_conversations",{count:_.threadCount})})]}),Z]});return F1("div",{className:"cortex-widget__chat-header",children:[u("button",{onClick:_.openHistory,className:"cortex-widget__sidebar-toggle-btn",children:u("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u("path",{d:"M2.5 4h11M2.5 8h11M2.5 12h11",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}),u("div",{className:"cortex-widget__chat-title-wrap",children:u("p",{className:"cortex-widget__chat-title",children:_.title??_.agentName??$("translate_new_chat")})}),_.debug.shown&&u("button",{onClick:_.toggleDebug,className:B("cortex-widget__debug-btn",_.debug.on?"cortex-widget__debug-btn--on":"cortex-widget__debug-btn--off"),children:_.debug.on?$("translate_debug"):$("translate_normal")}),Z,u("button",{type:"button",onClick:_.openHistory,"aria-label":$("translate_history"),title:$("translate_history"),className:"cortex-widget__header-btn cortex-widget__history-btn",children:F1("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:[u("circle",{cx:"8",cy:"8",r:"5.75",stroke:"currentColor",strokeWidth:"1.3"}),u("path",{d:"M8 5v3l2 1.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})}import{jsx as X_,jsxs as R2}from"react/jsx-runtime";function k2(_){let{locale:$,t:Z}=F();return R2("div",{className:"cortex-widget__landing",children:[X_("div",{className:"cortex-widget__landing-icon",children:X_("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",children:X_("path",{d:f.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),X_("p",{className:"cortex-widget__landing-greeting",children:_.greeting}),!!_.suggestions.length&&X_("div",{className:"cortex-widget__landing-chips",children:_.suggestions.map((Q,X)=>X_("button",{type:"button",onClick:()=>_.send(Q.prompt),className:"cortex-widget__landing-chip",children:Q.title},X))}),_.composer,!!_.threads?.length&&X_("div",{className:"cortex-widget__landing-recent",children:_.threads.slice(0,2).map((Q)=>{let X=Q_(Q.updatedAt,$);return R2("button",{type:"button",onClick:()=>_.openThread(Q),className:"cortex-widget__landing-recent-item",children:[X_("p",{className:"cortex-widget__landing-recent-title",children:Q.title??Z("translate_untitled")}),X&&X_("p",{className:"cortex-widget__landing-recent-time",children:X})]},Q.id)})})]})}import{useCallback as X1,useEffect as s0,useLayoutEffect as t0,useMemo as I3,useRef as L_,useState as e0}from"react";import{memo as R3}from"react";import{Fragment as M3}from"react";import{useRef as u4,useState as c4}from"react";import{jsx as S_,jsxs as p4}from"react/jsx-runtime";function s({value:_,className:$}){let{t:Z}=F(),[Q,X]=c4(!1),J=u4(null);async function Y(G){G.stopPropagation(),G.preventDefault();try{if(await navigator.clipboard.writeText(_),X(!0),J.current)clearTimeout(J.current);J.current=setTimeout(()=>X(!1),1500)}catch{}}return S_("span",{className:B("cortex-copy-btn",$),children:S_("button",{className:B("cortex-copy-btn__button",Q&&"cortex-copy-btn__button--copied"),onClick:(G)=>void Y(G),"aria-label":Q?Z("translate_copied"):Z("translate_copy"),type:"button",children:Q?S_("svg",{className:"cortex-copy-btn__icon cortex-copy-btn__icon--check",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:S_("path",{d:"M5 13l4 4L19 7",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):p4("svg",{className:"cortex-copy-btn__icon",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",children:[S_("rect",{x:"9",y:"9",width:"12",height:"12",rx:"2",stroke:"currentColor",strokeWidth:"2"}),S_("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 L1,jsxs as I2}from"react/jsx-runtime";function O1({label:_}){return I2("div",{className:"cortex-aborted-flag",children:[L1("span",{className:"cortex-aborted-flag__line"}),I2("span",{className:"cortex-aborted-flag__label",children:[L1("svg",{className:"cortex-aborted-flag__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:L1("path",{d:"M6 1.5v5M6 8.75v.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})}),_]}),L1("span",{className:"cortex-aborted-flag__line"})]})}import{jsx as C_,jsxs as y2}from"react/jsx-runtime";function S2(_){let{api:$,t:Z}=F();async function Q(X){let{blob:J,name:Y}=await $.downloadAttachment(X);r_(J,Y)}return C_("div",{className:B("cortex-message-attachments",_.isUser&&"cortex-message-attachments--user"),children:_.attachments.map((X)=>y2("button",{type:"button",onClick:()=>void Q(X.id),className:"cortex-message-attachment","aria-label":`${Z("translate_download")}: ${X.filename}`,children:[y2("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__icon",fill:"none",children:[C_("path",{d:f.file[0],stroke:"currentColor",strokeWidth:"1.25"}),C_("path",{d:f.file[1],stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round"})]}),C_("span",{className:"cortex-message-attachment__name",children:X.filename}),C_("svg",{viewBox:"0 0 16 16",className:"cortex-message-attachment__dl-icon",fill:"none",children:C_("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 i4,useState as s_}from"react";import{useMemo as d4,useState as l4}from"react";import{jsx as r,jsxs as D_,Fragment as P1}from"react/jsx-runtime";function W_({data:_,expandDepth:$,className:Z}){let Q=d4(()=>k_(_),[_]),[X,J]=l4({});function Y(V,z){return X[V]??z>=$}function G(V,z){J((K)=>({...K,[V]:!Y(V,z)}))}return r("div",{className:B("cortex-json-tree",Z),children:r(C2,{value:Q,path:"$",depth:0,isCollapsed:Y,toggle:G})})}function C2({value:_,path:$,depth:Z,isCollapsed:Q,toggle:X}){let J=C0(_,$);if(J.kind==="primitive")return r("span",{className:J.className,children:J.text});if(J.entries.length===0)return D_("span",{className:"cortex-json-tree__bracket",children:[J.open,J.close]});let Y=Q($,Z);function G(V){X($,Z),V.stopPropagation()}return D_(P1,{children:[D_("span",{className:"cortex-json-tree__toggle",onClick:G,role:"button",children:[r("span",{className:B("cortex-json-tree__arrow",Y&&"cortex-json-tree__arrow--collapsed"),children:"▾"}),r("span",{className:"cortex-json-tree__bracket",children:J.open})]}),Y?D_(P1,{children:[r("span",{className:"cortex-json-tree__collapsed-hint",onClick:G,role:"button",children:J.summary}),r("span",{className:"cortex-json-tree__bracket",children:J.close})]}):D_(P1,{children:[r("div",{className:"cortex-json-tree__indent",children:J.entries.map((V,z)=>D_("div",{className:"cortex-json-tree__line",children:[V.key!==null&&D_(P1,{children:[r("span",{className:"cortex-json-tree__key",children:`"${V.key}"`}),r("span",{className:"cortex-json-tree__colon",children:": "})]}),r(C2,{value:V.value,path:V.path,depth:Z+1,isCollapsed:Q,toggle:X}),z<J.entries.length-1&&r("span",{className:"cortex-json-tree__comma",children:","})]},V.path))}),r("span",{className:"cortex-json-tree__bracket",children:J.close})]})]})}function S(_){return _.toLocaleString("en-US")}import{jsx as b_,jsxs as w_}from"react/jsx-runtime";function b2({usage:_}){let{t:$}=F();return w_("div",{className:"cortex-llm-inspector__usage-rows",children:[w_("div",{className:"cortex-llm-inspector__usage-row",children:[b_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_input")}),b_("span",{className:"cortex-llm-inspector__usage-val",children:S(_.input.total)}),w_("span",{className:"cortex-llm-inspector__usage-detail",children:[$("translate_fresh")," ",S(_.input.noCache)," · ",$("translate_read")," ",S(_.input.cacheRead)," · ",$("translate_write")," ",S(_.input.cacheWrite)]})]}),w_("div",{className:"cortex-llm-inspector__usage-row",children:[b_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_output")}),b_("span",{className:"cortex-llm-inspector__usage-val",children:S(_.output.total)}),w_("span",{className:"cortex-llm-inspector__usage-detail",children:[$("translate_text")," ",S(_.output.text)," · ",$("translate_reasoning")," ",S(_.output.reasoning)]})]}),w_("div",{className:"cortex-llm-inspector__usage-row cortex-llm-inspector__usage-row--total",children:[b_("span",{className:"cortex-llm-inspector__usage-lbl",children:$("translate_total")}),b_("span",{className:"cortex-llm-inspector__usage-val",children:S(_.total)})]})]})}import{jsx as w2,jsxs as M1}from"react/jsx-runtime";function T2({usage:_}){let $=o_(_);return M1("span",{className:"cortex-llm-inspector__step-metrics",children:[M1("span",{className:"cortex-llm-inspector__metric",children:[w2("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--input"}),S(_.input.total)]}),M1("span",{className:"cortex-llm-inspector__metric",children:[w2("span",{className:"cortex-llm-inspector__dot cortex-llm-inspector__dot--output"}),S(_.output.total)]}),$!==null&&M1("span",{className:"cortex-llm-inspector__cache-pct",children:[$,"%"]})]})}import{jsx as T,jsxs as N_}from"react/jsx-runtime";function v2({messageId:_}){let{t:$,api:Z,selectedThread:Q}=F(),[X,J]=s_(!1),[Y,G]=s_(!1),[V,z]=s_([]),[K,W]=s_(null),[N,H]=s_({}),q=i4(!1);async function U(){if(!q.current&&Q){G(!0);try{z(await Z.listLlmRequests(Q.id,_))}finally{G(!1),q.current=!0}}J((D)=>!D)}function E(D){W((L)=>L===D?null:D)}function M(D){return N[D]??"prompt"}function R(D,L){H((O)=>({...O,[D]:L}))}function P(D){return M(D.id)==="prompt"?D.prompt:D.output}return N_("div",{className:B("cortex-llm-inspector",X&&"cortex-llm-inspector--open"),children:[N_("button",{className:"cortex-llm-inspector__trigger",onClick:()=>void U(),children:[T("svg",{className:"cortex-llm-inspector__icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:T("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"})}),T("span",{children:$("translate_inspect_llm_requests")}),Y?T("span",{className:"cortex-llm-inspector__loading",children:$("translate_loading")}):V.length>0?T("span",{className:"cortex-llm-inspector__badge",children:V.length}):null,T("svg",{className:"cortex-llm-inspector__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:T("path",{d:f.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),T("div",{className:"cortex-llm-inspector__panel-wrapper",children:T("div",{className:"cortex-llm-inspector__panel-inner",children:N_("div",{className:"cortex-llm-inspector__panel",children:[V.length===0&&!Y&&T("div",{className:"cortex-llm-inspector__empty",children:$("translate_no_llm_requests")}),V.map((D,L)=>N_("div",{className:B("cortex-llm-inspector__step",K===D.id&&"cortex-llm-inspector__step--expanded"),children:[N_("button",{className:"cortex-llm-inspector__step-header",onClick:()=>E(D.id),children:[T("span",{className:"cortex-llm-inspector__step-label",children:$("translate_step_n",{number:L+1})}),D.tokenUsage&&T(T2,{usage:D.tokenUsage}),T("svg",{className:"cortex-llm-inspector__step-chevron",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:T("path",{d:f.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),T("div",{className:"cortex-llm-inspector__step-body-wrapper",children:T("div",{className:"cortex-llm-inspector__step-body-inner",children:N_("div",{className:"cortex-llm-inspector__step-body",children:[D.tokenUsage&&T(b2,{usage:D.tokenUsage}),N_("div",{className:"cortex-llm-inspector__tabs",children:[T("button",{className:B("cortex-llm-inspector__tab",M(D.id)==="prompt"&&"cortex-llm-inspector__tab--active"),onClick:()=>R(D.id,"prompt"),children:$("translate_request")}),T("button",{className:B("cortex-llm-inspector__tab",M(D.id)==="response"&&"cortex-llm-inspector__tab--active"),onClick:()=>R(D.id,"response"),children:$("translate_response")})]}),N_("div",{className:"cortex-llm-inspector__json-pane",children:[T(s,{className:"cortex-llm-inspector__json-copy",value:w0(P(D))}),T(W_,{data:b0(P(D)),expandDepth:2})]})]})})})]},D.id))]})})})]})}import{useState as n4}from"react";import{jsx as y,jsxs as g}from"react/jsx-runtime";function j2({usage:_,modelId:$}){let{t:Z}=F(),[Q,X]=n4(!1),J=o_(_)??0;return g("div",{className:B("cortex-token-usage",Q&&"cortex-token-usage--expanded"),children:[g("button",{className:"cortex-token-usage__summary",onClick:()=>X((Y)=>!Y),children:[g("span",{className:"cortex-token-usage__total",children:[y("span",{className:"cortex-token-usage__total-number",children:S(_.total)}),y("span",{className:"cortex-token-usage__total-label",children:Z("translate_tokens")})]}),$?y("span",{className:"cortex-token-usage__model",children:$}):null,g("span",{className:"cortex-token-usage__pills",children:[g("span",{className:"cortex-token-usage__pill",children:[y("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),S(_.input.total)]}),g("span",{className:"cortex-token-usage__pill",children:[y("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),S(_.output.total)]})]}),J>0&&g("span",{className:"cortex-token-usage__cache-badge",children:[J,"%"]}),y("svg",{className:"cortex-token-usage__chevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:y("path",{d:f.chevronDown,stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),y("div",{className:"cortex-token-usage__details",children:y("div",{className:"cortex-token-usage__details-inner",children:g("div",{className:"cortex-token-usage__columns",children:[g("div",{className:"cortex-token-usage__col",children:[g("div",{className:"cortex-token-usage__col-header",children:[y("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--input"}),y("span",{className:"cortex-token-usage__col-label",children:Z("translate_input")}),y("span",{className:"cortex-token-usage__col-total",children:S(_.input.total)})]}),g("div",{className:"cortex-token-usage__rows",children:[_.input.noCache?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_fresh")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.input.noCache)})]}):null,_.input.cacheRead?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_cache_read")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.input.cacheRead)})]}):null,_.input.cacheWrite?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_cache_write")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.input.cacheWrite)})]}):null]}),J>0&&g("div",{className:"cortex-token-usage__cache-bar-row",children:[y("div",{className:"cortex-token-usage__cache-bar",children:y("div",{className:"cortex-token-usage__cache-fill",style:{width:`${J}%`}})}),y("span",{className:"cortex-token-usage__cache-label",children:Z("translate_n_percent_cached",{percent:J})})]})]}),g("div",{className:"cortex-token-usage__col",children:[g("div",{className:"cortex-token-usage__col-header",children:[y("span",{className:"cortex-token-usage__dot cortex-token-usage__dot--output"}),y("span",{className:"cortex-token-usage__col-label",children:Z("translate_output")}),y("span",{className:"cortex-token-usage__col-total",children:S(_.output.total)})]}),g("div",{className:"cortex-token-usage__rows",children:[_.output.text?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_text")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.output.text)})]}):null,_.output.reasoning?g("div",{className:"cortex-token-usage__row",children:[y("span",{className:"cortex-token-usage__row-label",children:Z("translate_reasoning")}),y("span",{className:"cortex-token-usage__row-value",children:S(_.output.reasoning)})]}):null]})]})]})})})]})}import{jsx as f2,jsxs as r4}from"react/jsx-runtime";function g2({messageId:_,isAssistant:$,metadata:Z}){let{tokenUsage:Q}=Z;if(!Q&&!$)return null;return r4("div",{className:"cortex-message-debug-zone",children:[Q&&f2(j2,{usage:Q,modelId:Z.modelId}),$&&f2(v2,{messageId:_})]})}import{jsx as t,jsxs as t_}from"react/jsx-runtime";function m2(_){let{reasoningPart:$,streaming:Z=!1}=_,{t:Q}=F();return t_("details",{className:"cortex-reasoning-details",children:[t_("summary",{className:"cortex-reasoning-details__summary",children:[t_("div",{className:"cortex-reasoning-details__header",children:[t("span",{className:"cortex-reasoning-details__icon",children:t_("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none","aria-hidden":"true",children:[t("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"}),t("path",{d:"M7.5 17.5h5M8.5 8a2 2 0 0 1 2-2",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})]})}),t("div",{className:"cortex-reasoning-details__title-group",children:t_("div",{className:"cortex-reasoning-details__title-row",children:[t("div",{className:"cortex-reasoning-details__title",children:Q("translate_reasoning")}),t("span",{className:B("cortex-reasoning-details__badge",Z?"cortex-reasoning-details__badge--streaming":"cortex-reasoning-details__badge--done"),children:Z?Q("translate_streaming"):Q("translate_done")})]})})]}),t("span",{className:"cortex-reasoning-details__chevron","aria-hidden":"true",children:t("svg",{width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:t("path",{d:f.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),t("div",{className:"cortex-reasoning-details__body",children:t("div",{className:"cortex-reasoning-details__content",children:t("pre",{dir:"auto",className:"cortex-reasoning-details__pre",children:$.content.trim()?$.content:Q("translate_no_reasoning")})})})]})}import{useEffect as l2,useMemo as G3,useRef as n0,useState as V3}from"react";import{useEffect as s4,useState as x2}from"react";import{useRef as o4,useState as a4}from"react";import{jsx as J_,jsxs as A1}from"react/jsx-runtime";function T_(_){let{label:$,ready:Z=!0,actions:Q,expanded:X,children:J}=_,{t:Y}=F(),G=o4(null),[V,z]=a4(!1);return A1("div",{className:"cortex-expandable",children:[Z&&A1("div",{className:"cortex-expandable__toolbar",role:"group","aria-label":$,children:[Q,J_("button",{type:"button",className:"cortex-expandable__action","aria-label":Y("translate_expand",{name:$}),title:Y("translate_expand",{name:$}),onClick:()=>{z(!0),G.current?.showModal()},children:J_("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:J_("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),J_("div",{className:"cortex-expandable__content",children:J}),A1("dialog",{ref:G,className:"cortex-expandable__dialog","aria-label":$,closedby:"any",onClose:()=>z(!1),children:[A1("div",{className:"cortex-expandable__head",children:[J_("span",{className:"cortex-expandable__title",children:$}),Q,J_("button",{type:"button",className:"cortex-expandable__action","aria-label":Y("translate_close"),title:Y("translate_close"),onClick:()=>G.current?.close(),children:J_("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:J_("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})})]}),V&&J_("div",{className:"cortex-expandable__body",children:X})]})]})}import{jsx as e_,jsxs as t4}from"react/jsx-runtime";function h2(_){let{id:$,alt:Z,attachment:Q}=_,{api:X,t:J}=F(),[Y,G]=x2(),[V,z]=x2(!1);if(s4(()=>{let K,W=!1;return G(void 0),z(!1),X.downloadAttachment($).then(({blob:N})=>{if(W)return;K=URL.createObjectURL(N),G(K)},()=>{if(!W)z(!0)}),()=>{if(W=!0,K)URL.revokeObjectURL(K)}},[X,$]),V)return e_("p",{className:"cortex-attachment-image__caption",children:Z?J("translate_image_unavailable_alt",{alt:Z}):J("translate_image_unavailable")});if(!Y)return null;return t4("figure",{className:"cortex-attachment-image",children:[e_(T_,{label:Q?.filename||Z||J("translate_image"),expanded:e_("img",{className:"cortex-attachment-image__expanded",src:Y,alt:Z}),children:e_("img",{src:Y,alt:Z})}),Q&&e_("figcaption",{className:"cortex-attachment-image__caption",children:Q.filename})]})}import{useEffect as e4,useRef as _3,useState as i0}from"react";import{jsx as d,jsxs as _1,Fragment as Q3}from"react/jsx-runtime";function $3(_){let{t:$}=F();if(!_.pending&&!_.debugMode)return null;return _1("div",{className:"cortex-media-block__head",children:[_.debugMode&&d("span",{className:"cortex-media-block__lang",children:_.language}),_.pending&&d("span",{className:"cortex-media-block__pending",children:$(H1(_.language).pending)}),_.debugMode&&_.closed&&_1("span",{className:"cortex-media-block__actions",children:[_.onToggleSource&&d("button",{type:"button",className:"cortex-media-block__action","aria-pressed":_.sourceShown,onClick:_.onToggleSource,children:$("translate_media_source")}),d(s,{value:_.source})]})]})}function u2(_){let{debugMode:$,t:Z}=F();return d("div",{className:"cortex-media-block__body",children:_1("p",{className:"cortex-media-block__error",children:[_.cutOff?Z("translate_media_cut_off"):Z("translate_media_failed"),!_.cutOff&&$&&` ${_.reason}`]})})}function c2(_){let{language:$,source:Z,closed:Q,hidden:X,onError:J}=_,{config:Y,scheme:G,locale:V}=F(),z=_3(null);return e4(()=>{J(void 0);let K=z.current;if(!Q||!G||!K)return;return q1(K,{language:$,source:Z,context:{scheme:G,locale:V},overrides:Y.mediaRenderers,onError:J})},[$,Z,Q,G,V,Y.mediaRenderers,J]),d("div",{ref:z,hidden:X,className:B("cortex-media-block__body",`cortex-media-block__body--${$}`)})}function Z3(_){let[$,Z]=i0();return _1(Q3,{children:[$&&d(u2,{cutOff:!1,reason:$}),d(c2,{language:_.language,source:_.source,closed:!0,hidden:Boolean($),onError:Z})]})}function p2(_){let{language:$,source:Z,closed:Q,streaming:X}=_,{debugMode:J,t:Y}=F(),[G,V]=i0(),[z,K]=i0(!1),W=!Q&&!X,N=W||Boolean(G);return _1("div",{className:"cortex-media-block",children:[d($3,{language:$,source:Z,pending:!Q&&X,closed:Q,debugMode:J,sourceShown:z,onToggleSource:N?void 0:()=>K((q)=>!q)}),N&&d(u2,{cutOff:W,reason:G}),d(T_,{label:Y(H1($).title),ready:Q&&!N,expanded:d(Z3,{language:$,source:Z}),children:d(c2,{language:$,source:Z,closed:Q,hidden:N,onError:V})}),J&&(N||z)&&d("pre",{dir:"ltr",className:"cortex-media-block__source",children:Z})]})}import{useMemo as X3,useRef as J3}from"react";import{jsx as U_}from"react/jsx-runtime";var Y3="M8 2.5v7.5M5 7l3 3 3-3M2.75 11v1.25a1.25 1.25 0 0 0 1.25 1.25h8a1.25 1.25 0 0 0 1.25-1.25V11";function d2(_){let{t:$}=F(),Z=J3(null),Q=X3(()=>({__html:l_(_.text)}),[_.text]);function X(){let J=Z.current?.querySelector("table");if(J)r_(O0(L0(J)),"table.xlsx")}return U_("div",{className:"cortex-table-block",children:U_(T_,{label:$("translate_table"),ready:_.closed,actions:U_("button",{type:"button",className:"cortex-expandable__action","aria-label":$("translate_table_export"),title:$("translate_table_export"),onClick:X,children:U_("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:U_("path",{d:Y3,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),expanded:U_("div",{className:"cortex-table-block__expanded",dangerouslySetInnerHTML:Q}),children:U_("div",{ref:Z,dangerouslySetInnerHTML:Q})})})}import{jsx as v_}from"react/jsx-runtime";function i2(_){let{role:$,textPart:Z,streaming:Q=!1,attachments:X=[]}=_,{config:J}=F(),Y=$==="assistant"&&Q?"":Z.content,[G,V]=V3({text:Y,fading:[]}),z=n0(Y),K=n0(null),W=n0(!0);l2(()=>{function q(U,E){z.current=U,V((M)=>M.text===U&&!M.fading.length&&!E.length?M:{text:U,fading:E})}if($!=="assistant"||!Q){K.current?.destroy(),K.current=null,q(Z.content,[]),W.current=!1;return}if(!K.current)K.current=new K_(q),K.current.seed(z.current);if(W.current){W.current=!1,K.current.seed(Z.content);return}K.current.update(Z.content,!1)},[$,Q,Z]),l2(()=>()=>{K.current?.destroy(),K.current=null},[]);let N=G3(()=>{let q=$==="assistant"?F0(G.text,I0(J.mediaRenderers)):[{kind:"markdown",text:G.text}];return q.map((U,E)=>U.kind==="markdown"?{...U,html:{__html:l_(U.text,E===q.length-1?G.fading:[])}}:U)},[$,G,J.mediaRenderers]),H=Q||G.text!==Z.content;return v_("div",{className:B("cortex-text-part",$==="assistant"&&"cortex-text-part--assistant",$==="user"&&"cortex-text-part--user"),children:v_("div",{className:B("cortex-text-bubble",$==="assistant"&&"cortex-text-bubble--assistant",$==="user"&&"cortex-text-bubble--user"),children:N.map((q,U)=>{switch(q.kind){case"markdown":return v_("div",{dangerouslySetInnerHTML:q.html},U);case"media":return v_(p2,{...q,streaming:H},U);case"table":return v_(d2,{text:q.text,closed:q.closed||!H},U);case"attachment":return v_(h2,{id:q.id,alt:q.alt,attachment:X.find((E)=>E.id.toLowerCase()===q.id)},U)}})})})}import{jsx as l,jsxs as H_}from"react/jsx-runtime";function n2({toolCallPart:_}){let{t:$}=F(),{state:Z,approval:Q}=_,X=_.output,J=x1(_);if(Z==="complete")return H_("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--success",children:[H_("div",{className:"cortex-debug-tool__section-bar",children:[l("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--success",children:$("translate_output")}),l("span",{className:"cortex-debug-tool__section-lang",children:"json"}),l(s,{value:J})]}),l("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:l(W_,{data:X,expandDepth:2})})]});if(Z==="error")return H_("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--error",children:[H_("div",{className:"cortex-debug-tool__section-bar",children:[l("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--error",children:$("translate_error")}),l(s,{value:J})]}),l("pre",{dir:"ltr",className:"cortex-debug-tool__error-pre",children:J})]});if(Z==="approval-requested")return H_("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[H_("div",{className:"cortex-debug-tool__section-bar",children:[l("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:$("translate_approval_requested")}),l("span",{className:"cortex-debug-tool__section-lang",children:Q?.id})]}),l("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:$("translate_waiting_for_approval")})]});if(Z==="approval-responded")return H_("div",{className:"cortex-debug-tool__section cortex-debug-tool__section--approval",children:[H_("div",{className:"cortex-debug-tool__section-bar",children:[l("span",{className:"cortex-debug-tool__section-label cortex-debug-tool__section-label--approval",children:$("translate_approval_response")}),l("span",{className:"cortex-debug-tool__section-lang",children:Q?.id})]}),l("div",{className:"cortex-debug-tool__message cortex-debug-tool__message--approval",children:$(Q?.approved?"translate_tool_approved":"translate_tool_response_received")})]});return null}import{jsx as z3,jsxs as K3}from"react/jsx-runtime";function r2({toolCallPart:_}){let{t:$}=F(),Z=m1(_);return K3("span",{className:B("cortex-debug-tool__state",Z.modifier&&`cortex-debug-tool__state--${Z.modifier}`),children:[Z.pulse&&z3("span",{className:B("cortex-debug-tool__pulse",Z.pulse==="violet"&&"cortex-debug-tool__pulse--violet")}),$(Z.labelKey)]})}import{jsx as m,jsxs as Y_}from"react/jsx-runtime";function o2({toolCallPart:_}){let{t:$}=F(),{codeSnippets:Z,remainingInput:Q,remainingInputText:X}=h1(_.input);return Y_("details",{className:"cortex-debug-tool","data-state":_.state,children:[m("summary",{className:"cortex-debug-tool__summary",children:Y_("div",{className:"cortex-debug-tool__header",children:[Y_("div",{className:"cortex-debug-tool__meta",children:[m("div",{className:"cortex-debug-tool__title-row",children:m("span",{className:"cortex-debug-tool__name",title:_.name,children:_.name})}),m("div",{className:"cortex-debug-tool__id-row",children:m("span",{className:"cortex-debug-tool__id",children:_.id})})]}),Y_("div",{className:"cortex-debug-tool__actions",children:[m(r2,{toolCallPart:_}),m("svg",{className:"cortex-debug-tool__chevron",width:"14",height:"14",viewBox:"0 0 20 20",fill:"none",children:m("path",{d:f.chevronDownLarge,stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),Y_("div",{className:"cortex-debug-tool__body",children:[Z.map((J)=>Y_("div",{className:"cortex-debug-tool__section",children:[Y_("div",{className:"cortex-debug-tool__section-bar",children:[m("span",{className:"cortex-debug-tool__section-label",children:J.key}),m("span",{className:"cortex-debug-tool__section-lang",children:J.lang}),m(s,{value:J.value})]}),m("pre",{dir:"ltr",className:"cortex-debug-tool__pre",children:m("code",{className:"hljs",dangerouslySetInnerHTML:{__html:S0(J.value,J.lang)}})})]},J.key)),!!Q&&Y_("div",{className:"cortex-debug-tool__section",children:[Y_("div",{className:"cortex-debug-tool__section-bar",children:[m("span",{className:"cortex-debug-tool__section-label",children:$("translate_input")}),m("span",{className:"cortex-debug-tool__section-lang",children:"json"}),m(s,{value:X})]}),m("div",{dir:"ltr",className:"cortex-debug-tool__tree",children:m(W_,{data:Q,expandDepth:2})})]}),m(n2,{toolCallPart:_})]})]})}import{useEffect as W3,useRef as N3,useState as a2}from"react";import{jsx as $1,jsxs as s2}from"react/jsx-runtime";function j_({activity:_,className:$}){let{t:Z}=F(),Q=c1(_),[X,J]=a2(0),[Y,G]=a2("idle"),V=N3(Q.length);return V.current=Q.length,W3(()=>{let z,K;function W(){z=setTimeout(()=>{G("exiting"),z=setTimeout(()=>{J((N)=>(N+1)%V.current),G("enter-start"),K=requestAnimationFrame(()=>{G("entering"),z=setTimeout(()=>{G("idle"),W()},300)})},300)},2000)}return W(),()=>{if(z)clearTimeout(z);if(K)cancelAnimationFrame(K)}},[]),s2("div",{className:B("cortex-subtle-activity",$),children:[s2("div",{className:"cortex-subtle-activity__dots",children:[$1("span",{className:"cortex-subtle-activity__dot"}),$1("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d1"}),$1("span",{className:"cortex-subtle-activity__dot cortex-subtle-activity__dot--d2"})]}),$1("div",{className:"cortex-subtle-activity__label-mask",children:$1("span",{className:B("cortex-subtle-activity__label",`cortex-subtle-activity__label--${Y}`),children:Z(Q[X])})})]})}import{useEffect as Q5,useRef as r0,useState as Z5}from"react";import{jsx as e,jsxs as f_,Fragment as H3}from"react/jsx-runtime";function t2({toolCallPart:_,asking:$}){let{t:Z,locale:Q,respondToApproval:X}=F(),{sentence:J,decision:Y,decisionKey:G}=u1(_,Q),V=`cortex-approval-${_.id}`,z=K6(_),K=Y==="pending",{state:W,active:N}=Z_(_);function H(q){X(z,q).catch(()=>{})}return f_("div",{className:B("cortex-approval-card",K&&"cortex-approval-card--asking"),children:[K?f_(H3,{children:[f_("div",{className:"cortex-approval-card__head",children:[e("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",children:e("path",{d:"M8 1.75 2.75 3.75v4c0 3 2.2 5.3 5.25 6.5 3.05-1.2 5.25-3.5 5.25-6.5v-4L8 1.75Z",stroke:"currentColor",strokeWidth:"1.3",strokeLinejoin:"round"})}),Z("translate_approval_needed")]}),e("p",{className:"cortex-approval-card__sentence",id:V,children:J})]}):f_("div",{className:"cortex-approval-card__line",children:[f_("span",{className:"cortex-tool-pill__icon","aria-hidden":"true",children:[e("span",{className:B("cortex-tool-pill__spinner",N&&"cortex-tool-pill__spinner--visible")}),e("svg",{className:B("cortex-tool-pill__svg cortex-tool-pill__svg--check",W==="complete"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:e("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),e("svg",{className:B("cortex-tool-pill__svg cortex-tool-pill__svg--error",W==="error"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:e("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})]}),G&&e("span",{className:"cortex-approval-card__decision",children:Z(G)}),e("span",{className:"cortex-approval-card__summary",children:J})]}),K&&$&&f_("div",{className:"cortex-approval-card__foot",children:[e("button",{type:"button",className:"cortex-approval-card__button cortex-approval-card__button--approve","aria-describedby":V,onClick:()=>H(!0),children:Z("translate_approve")}),e("button",{type:"button",className:"cortex-approval-card__button","aria-describedby":V,onClick:()=>H(!1),children:Z("translate_deny")})]})]})}import{useEffect as e2,useRef as E1,useState as _5}from"react";import{jsx as v,jsxs as __}from"react/jsx-runtime";function $5({toolCallPart:_,setOutput:$}){let{t:Z}=F(),{state:Q,id:X,input:J}=_;if(Q==="complete"||Q==="error"){let Y=G0(_.output);return Y?v(B3,{position:Y}):__("div",{className:"cortex-tool-pill",children:[v("span",{className:"cortex-tool-pill__icon",children:v("svg",{className:B("cortex-tool-pill__svg cortex-tool-pill__svg--visible",Q==="error"&&"cortex-tool-pill__svg--error"),viewBox:"0 0 20 20",fill:"none",children:v("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}),v("span",{className:"cortex-tool-pill__title",children:Z("translate_location_not_shared")})]})}if(Q!=="input-complete")return null;return v(q3,{center:Y0(J),submit:$},X)}function q3({center:_,submit:$}){let{t:Z}=F(),Q=E1(null),X=E1(void 0),[J,Y]=_5(z1),G=E1({center:_,submit:$});G.current={center:_,submit:$},e2(()=>{let z=Q.current;if(!z)return;let K=X0(z,{center:G.current.center,onState:Y,submit:(W)=>G.current.submit(W)});return X.current=K,K.start(),()=>{if(K.dispose(),X.current===K)X.current=void 0}},[]);let V=V0(J);return __("div",{className:"cortex-location-input",children:[__("div",{className:"cortex-location-input__map",children:[v("div",{className:"cortex-location-input__canvas",ref:Q}),v("button",{type:"button",className:"cortex-location-input__locate","aria-label":Z("translate_location_locate"),title:Z("translate_location_locate"),disabled:J.locating||J.submitting,onClick:()=>X.current?.locate(),children:v(D3,{})})]}),__("div",{className:"cortex-location-input__foot",children:[J.position&&!J.deliveryFailed?v("span",{className:"cortex-location-input__coords",children:K1(J.position)}):__("span",{className:B("cortex-location-input__hint",V.failed&&"cortex-location-input__hint--failed"),children:[J.locating&&v("span",{className:"cortex-location-input__spinner"}),Z(V.key)]}),__("span",{className:"cortex-location-input__actions",children:[v("button",{type:"button",className:"cortex-location-input__skip",disabled:J.submitting,onClick:()=>X.current?.cancel(),children:Z("translate_location_skip")}),v("button",{type:"button",className:"cortex-location-input__send",disabled:!J.position||J.submitting,onClick:()=>X.current?.confirm(),children:Z("translate_location_send")})]})]})]})}function B3({position:_}){let{t:$}=F(),Z=E1(null),[Q,X]=_5(!1),{lat:J,lng:Y}=_;return e2(()=>{let G=Z.current;if(!G)return;return X(!1),J0(G,{lat:J,lng:Y},()=>X(!0))},[J,Y]),__("div",{className:"cortex-location-input cortex-location-input--settled",children:[__("div",{className:"cortex-location-input__map cortex-location-input__map--still",children:[v("div",{className:"cortex-location-input__canvas",ref:Z,hidden:Q}),Q&&v("span",{className:"cortex-location-input__still-failed",children:$("translate_location_map_failed")})]}),__("div",{className:"cortex-location-input__body",children:[__("span",{className:"cortex-location-input__title",children:[v("svg",{viewBox:"0 0 20 20",fill:"none",children:v("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),$("translate_location_shared")]}),v("span",{className:"cortex-location-input__coords",children:K1(_)})]})]})}function D3(){return __("svg",{viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",children:[v("circle",{cx:"10",cy:"10",r:"5.5"}),v("circle",{cx:"10",cy:"10",r:"1.6",fill:"currentColor",stroke:"none"}),v("path",{d:"M10 1.5v3M10 15.5v3M1.5 10h3M15.5 10h3"})]})}import{jsx as C,jsxs as Z1}from"react/jsx-runtime";var U3=new Map([[V1,$5]]);function X5({message:_,toolCallPart:$,agentWorking:Z}){let{config:Q,addToolResult:X,capabilities:J}=F(),Y=J?.messages===!0,G=Y&&$.state==="input-complete"&&!Z,V=G&&G1($)?.embed!==void 0,z=Y&&$.state==="approval-requested"&&!Z,K=Q.toolComponents?.[$.name]??(G||p($.state)?U3.get($.name):void 0);return C("div",{className:"cortex-tool-call-animated",children:K?C(K,{toolCallPart:$,message:_,setOutput:(W)=>X($.id,$.name,W)}):V?C(F3,{toolCallPart:$}):C(J5,{toolCallPart:$,asking:z})})}function F3({toolCallPart:_}){let{api:$,t:Z,addToolResult:Q,selectedThread:X,config:J}=F(),Y=X?.id,[G,V]=Z5({phase:"initiating"}),[z]=Z5(J.trustSameOriginEmbeds),K=r0(void 0),W=r0({api:$,addToolResult:Q,toolName:_.name});if(W.current={api:$,addToolResult:Q,toolName:_.name},Q5(()=>{if(!Y)return;let H=Z0({initiate:()=>W.current.api.initiateToolCall(Y,_.id),onState:V,submit:(U)=>W.current.addToolResult(_.id,W.current.toolName,U)});K.current=H,H.start();let q=(U)=>H.handleMessage(U);return window.addEventListener("message",q),()=>{if(window.removeEventListener("message",q),H.dispose(),K.current===H)K.current=void 0}},[_.id,Y]),!Y||G.phase==="unavailable")return C(J5,{toolCallPart:_,asking:!1});let N=Z1("div",{className:"cortex-client-tool-embed",children:[Z1("div",{className:"cortex-client-tool-embed__bar",children:[C("span",{children:Z("translate_client_tool_title")}),C("button",{type:"button",className:"cortex-client-tool-embed__cancel",onClick:()=>K.current?.cancel(),children:Z("translate_client_tool_cancel")})]}),G.phase==="embedded"?C("iframe",{className:"cortex-client-tool-embed__frame",src:G.embedUrl,sandbox:e1(G.embedUrl,window.location.origin,z),title:Z("translate_client_tool_title"),ref:(H)=>K.current?.setSource(H?.contentWindow),onLoad:(H)=>{if(!_0(G.embedUrl,window.location.origin,z)&&$0(H.currentTarget,window.location.origin))K.current?.terminate()}}):G.phase==="error"?Z1("div",{className:"cortex-client-tool-embed__status",children:[C("span",{children:Z("translate_client_tool_failed")}),C("button",{type:"button",className:"cortex-client-tool-embed__retry",onClick:()=>void K.current?.start(),children:Z("translate_client_tool_retry")})]}):C("div",{className:"cortex-client-tool-embed__status",children:Z("translate_client_tool_loading")})]});return G.phase==="embedded"&&G.surface==="modal"?C(L3,{label:Z("translate_client_tool_title"),onCancel:()=>K.current?.cancel(),children:N}):N}function L3({label:_,onCancel:$,children:Z}){let Q=r0(null);return Q5(()=>{let X=Q.current;return X?.showModal(),()=>X?.close()},[]),C("dialog",{ref:Q,className:"cortex-client-tool-embed-dialog","aria-label":_,onCancel:(X)=>{X.preventDefault(),$()},children:Z})}function J5({toolCallPart:_,asking:$}){return Z_(_).gated?C(t2,{toolCallPart:_,asking:$}):C(O3,{toolCallPart:_})}function O3({toolCallPart:_}){let{t:$}=F(),{state:Z,active:Q,titleKey:X,statement:J,rows:Y}=Z_(_);return Z1("div",{className:"cortex-tool-pill",children:[Z1("span",{className:"cortex-tool-pill__icon",children:[C("span",{className:B("cortex-tool-pill__spinner",Q&&"cortex-tool-pill__spinner--visible")}),C("svg",{className:B("cortex-tool-pill__svg","cortex-tool-pill__svg--check",Z==="complete"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:C("path",{d:"M5.5 10.5 L8.5 13.5 L14.5 7",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),C("svg",{className:B("cortex-tool-pill__svg","cortex-tool-pill__svg--error",Z==="error"&&"cortex-tool-pill__svg--visible"),viewBox:"0 0 20 20",fill:"none",children:C("path",{d:"M6.5 6.5 L13.5 13.5 M13.5 6.5 L6.5 13.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})]}),C("span",{className:B("cortex-tool-pill__title",Z==="error"&&"cortex-tool-pill__title--error",Z==="starting"&&J&&"cortex-tool-pill__title--pending"),children:J??$(X)}),Y!==void 0&&C("span",{className:"cortex-tool-pill__meta",children:$("translate_rows",{count:Y})})]})}import{jsx as Y5}from"react/jsx-runtime";function G5({message:_,toolCallPart:$,agentWorking:Z}){if(!p($.state)&&!Z_($).statement){if($.name==="executeCode")return Y5(j_,{activity:"code"})}return Y5(X5,{toolCallPart:$,message:_,agentWorking:Z})}import{jsx as g_,jsxs as P3}from"react/jsx-runtime";function V5(_){let{message:$,part:Z,debugMode:Q,animate:X,streaming:J,agentWorking:Y,attachments:G}=_,{t:V}=F();function z(){switch(Z.type){case"text":return g_(i2,{textPart:Z,role:$.role,streaming:J,attachments:G});case"thinking":return Q?g_(m2,{reasoningPart:Z,streaming:J}):g_(j_,{activity:"reasoning",className:"cortex-reasoning-animated"});case"tool-call":return Q?g_(o2,{toolCallPart:Z}):g_(G5,{toolCallPart:Z,message:$,agentWorking:Y});default:return P3("p",{className:"cortex-unhandled-type",children:[V("translate_unhandled_type")," ",Z.type]})}}return g_("div",{className:B("cortex-message-part",X&&"cortex-message-part--animated",_.folded&&"cortex-message-part--folded"),"data-cortex-frontier":_.frontier?"":void 0,children:z()})}import{jsx as G_,jsxs as o0}from"react/jsx-runtime";function A3({isUser:_,clipboardText:$,createdAt:Z}){let{locale:Q}=F();return o0("div",{className:B("cortex-message-actions",_&&"cortex-message-actions--user"),children:[$&&G_(s,{value:$}),Z&&G_("time",{className:"cortex-message-actions__time",dateTime:Z,children:Q_(Z,Q)})]})}function E3({count:_,animate:$,onOpen:Z}){let{t:Q}=F();return G_("button",{type:"button",className:B("cortex-tool-fold",$&&"cortex-message-part--animated"),onClick:Z,children:Q("translate_more_steps",{count:_})})}function z5(_){let{message:$,parts:Z,metadata:Q,debugMode:X,animate:J,isStreaming:Y,agentWorking:G,closesTurn:V,fold:z,onOpenRun:K,frontier:W}=_,{t:N}=F(),H=$.role==="assistant",q=$.role==="user",U=Y?Z.length-1:-1,E=Q?.attachments??[],M=Z.filter((k)=>z?.get(k)?.kind!=="hidden"),R=M.filter((k)=>k.type==="text").at(-1),P=R?Z.indexOf(R):-1,D=(q||H)&&!Y&&P>=0,L=R!==M.at(-1)?P:-1,O=D&&G_(A3,{isUser:q,clipboardText:d1(Z),createdAt:Q?.createdAt});return o0("div",{className:"cortex-message-parts",children:[Z.map((k,b)=>{let x=z?.get(k);return o0(M3,{children:[G_(V5,{part:k,message:$,debugMode:X,animate:J,streaming:b===U,agentWorking:G,attachments:E,frontier:k===W,folded:x?.kind==="hidden"}),x?.kind==="more"&&G_(E3,{count:x.count,animate:J,onOpen:()=>K(x.runId)}),b===L&&O]},$.parts.indexOf(k))}),E.length>0&&G_(S2,{attachments:E,isUser:q}),Q?.isAborted&&G_(O1,{label:N("translate_aborted")}),L===-1&&O,X&&Q&&V&&G_(g2,{messageId:$.id,isAssistant:H,metadata:Q})]})}import{jsx as F_,jsxs as a0}from"react/jsx-runtime";function K5({firing:_,debugMode:$}){let{t:Z,locale:Q}=F();return a0("div",{className:B("cortex-trigger-block",$&&"cortex-trigger-block--debug"),children:[a0("div",{className:"cortex-trigger-block__head",children:[F_("svg",{className:"cortex-trigger-block__icon",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:F_("path",{d:"M6.75 1 2.5 6.75h3l-.25 4.25L9.5 5.25h-3z",fill:"currentColor"})}),$&&F_("span",{children:Z("translate_trigger_fired")}),F_("span",{className:"cortex-trigger-block__name",children:_.name}),F_("time",{className:"cortex-trigger-block__time",dateTime:_.firedAt,children:Q_(_.firedAt,Q)})]}),$&&a0("details",{className:"cortex-trigger-block__payload",children:[F_("summary",{children:Z("translate_trigger_payload")}),F_(W_,{data:_.payload,expandDepth:2})]})]})}import{jsx as Q1}from"react/jsx-runtime";var W5=R3(function($){let{message:Z,metadata:Q,isStreaming:X,agentWorking:J,closesTurn:Y,debugMode:G,animate:V,fold:z,onOpenRun:K,workingTurn:W,frontier:N}=$,H=R_(Z.parts,{debugMode:G,isStreaming:X});if(Q?.trigger)return Q1("div",{className:"cortex-message",children:Q1(K5,{firing:Q.trigger,debugMode:G})});if(!p1(H,Q))return Q1("div",{className:"cortex-message"});return Q1("div",{className:B("cortex-message",W&&"cortex-message--working-turn"),children:Q1(z5,{message:Z,parts:H,metadata:Q,debugMode:G,animate:V,isStreaming:X,agentWorking:J,closesTurn:Y,fold:z,onOpenRun:K,frontier:N})})});import{jsx as R1}from"react/jsx-runtime";var k3=[{role:"user",lines:[13,9]},{role:"assistant",lines:[16,18,12]},{role:"user",lines:[11]},{role:"assistant",lines:[14,15]}];function N5(){return R1("div",{className:"cortex-widget__messages-skeleton",children:k3.map((_,$)=>R1("div",{className:`cortex-widget__msg-skel cortex-widget__msg-skel--${_.role}`,children:R1("div",{className:`cortex-widget__msg-skel-bubble cortex-widget__msg-skel-bubble--${_.role}`,children:_.lines.map((Z)=>R1("div",{className:"cortex-skeleton cortex-widget__msg-skel-line",style:{width:`${Z}rem`}},Z))})},$))})}import{jsx as o,jsxs as J1,Fragment as H5}from"react/jsx-runtime";function y3(_){let $=L_(null),Z=L_(null),Q=L_(!0),X=L_(!0),J=L_(!1),Y=X1(()=>{if(J.current)return;J.current=!0,queueMicrotask(()=>{J.current=!1;let K=$.current;if(!K)return;D1(K),X.current=!0,Q.current=!1})},[]);s0(()=>{let K=Z.current;if(!_||!$.current||!K)return;if(Y(),typeof ResizeObserver>"u")return;let W=0,N=new ResizeObserver(([H])=>{let q=H?.contentRect.height??0,U=q>W;if(W=q,U&&(Q.current||X.current))Y()});return N.observe(K),()=>N.disconnect()},[_,Y]);let G=X1(()=>{Q.current=!0},[]),V=X1(()=>{if(Q.current)Y()},[Y]);function z(){let K=$.current;if(K)X.current=f0(K)<100}return{containerRef:$,contentRef:Z,onScroll:z,pin:G,settlePinned:V}}function S3({pin:_,settlePinned:$,contentRef:Z},Q,X){let[J,Y]=e0(!1);s0(()=>{Y(!1),_(),queueMicrotask(()=>Y(!0))},[Q,_]);let G=X[X.length-1],V=G?.role==="user"?G.id:void 0,z=V?G?.parts.find((K)=>K.type==="text")?.content:void 0;return t0(()=>{if(!V)return;_();let K=Z.current;if(K&&z!==void 0)j0(K,z)},[V,z,_,Z]),s0(()=>{$()},[X,$]),J}function C3(_,$,Z,Q){let[X,J]=e0(new Set),Y=X1((z)=>J((K)=>new Set(K).add(z)),[]),[G]=e0(n1);return{folds:I3(()=>G(_,{agentWorking:$,debugMode:Z,opened:X,foldable:Q}),[G,_,$,Z,X,Q]),openRun:Y}}function b3({working:_}){let $=L_(null),Z=L_(void 0);return t0(()=>{let Q=$.current;if(!Q)return;let X=g0(Q);return Z.current=X,()=>{X.dispose(),Z.current=void 0}},[]),t0(()=>Z.current?.sync(_)),J1("div",{ref:$,className:"cortex-working-avatar","aria-hidden":"true",children:[J1("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o("path",{d:"M9.94 15.5a2 2 0 0 0-1.44-1.44l-6.13-1.58a.5.5 0 0 1 0-.96L8.5 9.94A2 2 0 0 0 9.94 8.5l1.58-6.14a.5.5 0 0 1 .96 0l1.58 6.14a2 2 0 0 0 1.44 1.44l6.14 1.58a.5.5 0 0 1 0 .96l-6.14 1.58a2 2 0 0 0-1.44 1.44l-1.58 6.14a.5.5 0 0 1-.96 0z"}),o("path",{d:"M20 3v4M22 5h-4M4 17v2M5 18H3"})]}),o("span",{className:"cortex-working-avatar__ring"})]})}function q5(_){let{config:$,selectedThread:Z,t:Q}=F(),{messages:X,isAgentWorking:J,isLoadingMessages:Y,hasPendingToolCalls:G,turnFailure:V}=I_(),{capabilities:z,composerRef:K,debugMode:W}=_,N=!Y||J,H=y3(N),q=S3(H,Z?.id,X),U=J?h_(X)?.id:void 0,E=$.toolComponents,M=X1((k)=>l1(k,E),[E]),{folds:R,openRun:P}=C3(X,J,W,M),D=X.map((k)=>k.role).lastIndexOf("user"),L=J&&!W,O=L?i1(X,{foldable:M}):void 0;return J1(H5,{children:[!N?o(N5,{}):o("div",{className:_.className,children:o("div",{ref:H.containerRef,className:"cortex-message-list",onScroll:H.onScroll,children:J1("div",{ref:H.contentRef,className:"cortex-message-list__content",children:[X.map((k,b)=>o(W5,{message:k,metadata:k.metadata,isStreaming:k.id===U,agentWorking:J,fold:R.get(k.id),onOpenRun:P,closesTurn:k.role==="assistant"&&X[b+1]?.role!=="assistant",debugMode:W,animate:q,workingTurn:L&&b>D,frontier:k.id===U?O:void 0},k.id)),V&&J1(H5,{children:[o(O1,{label:Q(m0(V))}),z?.debug&&V.reason&&o("p",{className:"cortex-aborted-flag__reason",children:V.reason})]}),J&&!O&&o("div",{className:"cortex-working-thinking","data-cortex-frontier":"",children:o(j_,{activity:"reasoning"})}),o(b3,{working:J},Z?.id)]})})}),!G&&o(U1,{capabilities:z,composerRef:K})]})}import{jsx as B5,jsxs as w3}from"react/jsx-runtime";function D5(_){let{debugMode:$,selectedThread:Z}=F(),{screens:Q}=_;return w3("div",{className:B("cortex-widget__screen",Q.screen==="chat"&&"cortex-widget__screen--active",Q.screen!=="chat"&&"cortex-widget__screen--right"),children:[_.header,Z?B5(q5,{className:"cortex-widget__messages",debugMode:$,capabilities:_.capabilities,composerRef:_.composerRef}):_.landing,B5("div",{className:"cortex-widget__sidebar-backdrop",onClick:Q.closeSidebar})]})}import{useState as g3}from"react";import{useEffect as _6,useRef as O5,useState as Y1}from"react";import{useChat as f3}from"@tanstack/ai-react";import{useEffect as T3,useLayoutEffect as v3,useState as j3}from"react";function U5(_,{sessionRef:$,pendingSendRef:Z}){let[Q]=j3(_);return v3(()=>{return $.current=Q,()=>{if($.current===Q)$.current=void 0}},[Q,$]),T3(()=>{if(!Z.current.length)return;let X=setTimeout(()=>{let J=Z.current;Z.current=[],(async()=>{for(let{prompt:Y,attachments:G}of J)await Q.send(Y,G)})()});return()=>clearTimeout(X)},[Q,Z]),Q}import{useRef as F5}from"react";function L5(_){let $=F5(_);$.current=_;let Z=F5(Promise.resolve(void 0));async function Q(X,J){let Y=$.current;if(!Y.isAlive()||X!==Y.threadId)return;return o1({api:Y.api,threadId:X,isStale:()=>!$.current.isAlive()||J(),isStreaming:()=>$.current.isStreaming(),setMessages:(G)=>$.current.setMessages(G)})}return function(J,Y){return Z.current=Z.current.then(()=>Q(J,Y)),Z.current}}function P5(_){let{thread:$,api:Z}=_,Q=O5(!0),[X,J]=Y1(!1),[Y,G]=Y1(),[V,z]=Y1(),K=O5(null),W=L5({api:Z,threadId:$.id,isAlive:()=>Q.current,isStreaming:()=>H.streaming(),setMessages:(O)=>K.current.chat.setMessages(O)}),[N]=Y1(()=>x0({threadId:$.id,isAlive:()=>Q.current,onToolCall:()=>K.current.props.configRef.current.hooks?.onToolCall,deliver:(O)=>K.current.chat.addToolResult(O),setRunning:(O)=>K.current.props.setRunning($.id,O),reloadThreads:()=>K.current.props.reloadThreads(),refreshMessages:(O)=>W($.id,O),onTurnFinished:()=>K.current.props.onTurnFinished(),onSendFailed:()=>K.current.props.onSendFailed(),setTurnFailed:(O)=>{if(Q.current)G(O)},returnDraft:(O)=>{if(Q.current)z(O)}})),[H]=Y1(()=>r1({api:Z,thread:{id:$.id,isRunning:$.isRunning},mode:_.mode,localMessages:()=>K.current.chat.messages,onHydrated:(O)=>{if(Q.current)N.hydrated(O,$.isRunning)},onTranscriptCarried:(O)=>{if(Q.current)N.transcriptCarried(O)},onStreamStarted:()=>{if(Q.current)N.streamStarted()},onRefused:(O)=>{if(Q.current)N.sendRefused(O)},setLoadingMessages:(O)=>{if(Q.current)J(O)}})),q=f3({threadId:$.id,persistence:!0,initialMessages:_.initialMessages,connection:H,onChunk:(O)=>{if(Q.current)N.chunkArrived(O)},onError:()=>{if(Q.current)N.streamFailed()},onInterruptStateChange:(O)=>{if(Q.current)N.interruptStateChanged(O)}});K.current={chat:q,props:_};async function U(O,k){N.sendStarted(O);let b={id:u_(),role:"user",parts:[{type:"text",content:O}],metadata:{createdAt:new Date().toISOString(),attachments:k}};await K.current.chat.append(b)}async function E(){if(!K.current.chat.isLoading)return;let{aborted:O}=await Z.abortStream($.id).catch(()=>({aborted:!1}));if(!Q.current)return;if(O)N.abortConfirmed();else K.current.chat.stop()}function M(O,k,b){return N.deliverAnswer(()=>K.current.chat.addToolResult({toolCallId:O,tool:k,output:b}))}function R(O,k){return N.deliverAnswer(()=>Q0(K.current.chat,O,k))}function P(O){if(K.current.chat.isLoading)return;if(O.isRunning){K.current.props.remount(O,K.current.chat.messages);return}N.readBack()}_6(()=>{return Q.current=!0,()=>{Q.current=!1}},[]),U5(()=>({threadId:$.id,send:U,abort:E,addToolResult:M,respondToApproval:R,reattach:P,transcriptUpdated:(O,k)=>{if(O===$.id)N.transcriptUpdated(k)}}),{sessionRef:_.sessionRef,pendingSendRef:_.pendingSendRef});let{messages:D,isLoading:L}=q;return _6(()=>{N.loadingChanged(L,()=>K.current.chat.messages)},[N,L]),_6(()=>{K.current.props.publish({messages:D,isAgentWorking:L,isLoadingMessages:X,hasPendingToolCalls:!L&&z_(D).length>0,awaitsApproval:g1(D),returnedDraft:V,turnFailure:Y})},[D,L,X,Y,V]),null}import{jsx as m3,jsxs as x3}from"react/jsx-runtime";function M5({selection:_,threads:$,children:Z,...Q}){let{session:X}=_,[J,Y]=g3(),G=X&&`${X.thread.id}:${X.epoch}`,V=X&&J&&(J.key===G||X.mode==="reload")?J.value:u0;return x3(c0.Provider,{value:V,children:[X&&G&&m3(P5,{thread:X.thread,mode:X.mode,initialMessages:X.initialMessages,setRunning:$.setRunning,reloadThreads:$.reload,remount:_.remount,publish:(z)=>Y({key:G,value:z}),...Q},G),Z]})}import{jsx as j,jsxs as O_,Fragment as h3}from"react/jsx-runtime";function A5(_){let{locale:$,t:Z}=F(),{threads:Q,deleteThread:X}=_;return j("div",{className:"cortex-widget__threads-list",children:Q===void 0?[1,2,3,4].map((J)=>O_("div",{className:"cortex-widget__thread-skeleton",children:[j("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-icon"}),j("div",{className:"cortex-widget__thread-skeleton-lines",children:j("div",{className:"cortex-skeleton cortex-widget__thread-skeleton-line",style:{width:`${40+J*12}%`}})})]},J)):O_(h3,{children:[Q.map((J)=>{let Y=J.id===_.selectedThreadId,G=Q_(J.updatedAt,$);return O_("div",{className:B("cortex-widget__thread-item",Y&&"cortex-widget__thread-item--active"),children:[j("div",{className:B("cortex-widget__thread-icon",Y&&"cortex-widget__thread-icon--active"),children:j("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:j("path",{d:f.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),O_("button",{type:"button",onClick:()=>_.openThread(J),className:"cortex-widget__thread-info",children:[O_("div",{className:"cortex-widget__thread-title-row",children:[j("p",{dir:"auto",className:B("cortex-widget__thread-title",Y&&"cortex-widget__thread-title--active"),children:J.title??Z("translate_untitled")}),J.isRunning&&O_("span",{className:B("cortex-widget__thread-running",Y&&"cortex-widget__thread-running--active"),children:[j("span",{className:"cortex-widget__thread-running-dot"}),Z("translate_running")]})]}),G&&j("p",{className:"cortex-widget__thread-time",children:G})]}),X&&j("button",{type:"button","aria-label":Z("translate_delete_conversation"),onClick:()=>X(J.id),className:B("cortex-widget__thread-delete",Y&&"cortex-widget__thread-delete--active"),children:j("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"none",children:j("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})})}),j("svg",{className:B("cortex-widget__thread-arrow",Y&&"cortex-widget__thread-arrow--active"),width:"10",height:"10",viewBox:"0 0 16 16",fill:"none",children:j("path",{d:"M6 4l4 4-4 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]},J.id)}),!Q.length&&O_("div",{className:"cortex-widget__threads-empty",children:[j("div",{className:"cortex-widget__threads-empty-icon",children:j("svg",{width:"18",height:"18",viewBox:"0 0 16 16",fill:"none",className:"cortex-widget__threads-empty-svg",children:j("path",{d:f.bubble,stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})})}),j("p",{className:"cortex-widget__threads-empty-title",children:Z("translate_no_threads_yet")}),j("p",{className:"cortex-widget__threads-empty-subtitle",children:Z("translate_start_a_new_conversation")}),_.newChat&&j("button",{onClick:_.newChat,className:"cortex-widget__new-chat-btn cortex-widget__new-chat-btn--empty-state",children:Z("translate_new_chat")})]})]})})}import{useSyncExternalStore as u3}from"react";function E5(_){return u3(($)=>{let Z=window.matchMedia(_);return Z.addEventListener("change",$),()=>Z.removeEventListener("change",$)},()=>window.matchMedia(_).matches,()=>!1)}import{jsx as p3,jsxs as k5}from"react/jsx-runtime";var c3="(max-width: 768px)";function R5(_){_.preventDefault()}function I5(_){let{screens:$}=_,Z=E5(c3),Q=_.viewMode==="full"?Z&&!$.sidebarOpen:$.screen!=="threads";return p3("div",{className:B("cortex-widget",_.className),"data-cortex-theme":_.theme,children:k5("div",{className:B("cortex-widget__container",_.viewMode==="full"&&"cortex-widget__container--full",$.sidebarOpen&&"cortex-widget__container--sidebar-open"),onDragOver:R5,onDrop:R5,children:[k5("div",{className:B("cortex-widget__screen",$.screen==="threads"&&"cortex-widget__screen--active",$.screen!=="threads"&&"cortex-widget__screen--left"),"aria-hidden":Q||void 0,inert:Q||void 0,children:[_.header,_.threadList]}),_.children]})})}import{jsx as $_}from"react/jsx-runtime";var l3={header:E2,landing:k2,threadList:A5};function $6(_,$){return _?.[$]??l3[$]}function i3(_,$){return _?.readOnly===!1?$:void 0}function n3(_){let{isAgentWorking:$}=I_();return $_(_.component,{..._.context,isWorking:$})}function r3({config:_,className:$,slots:Z}){let Q=y5(_);Q.current=_;let[X]=k1(()=>v1(()=>Q.current.transport)),J=H2(X),[Y,G]=k1(!1),[V,z]=k1();d3(()=>y0(_.theme,z),[_.theme]);let K=_.viewMode??"helper",W=B2(K),[N,H]=k1(0),{capabilities:q,unanswered:U}=_2(X,N),E=y5(null),M=Y2({api:X,threads:J,getHooks:()=>Q.current.hooks,initialThreadId:_.thread}),{sessionRef:R,selection:P,queue:D,send:L,pendingSendRef:O}=M,{selected:k,selectedRef:b}=P,x=z2({threads:J,selectedRef:b,sessionRef:R,deselect:P.deselect,onReconnect:()=>H((i)=>i+1)}),m_=V2({getConfig:()=>Q.current,onEvent:x.onEvent,onReconnect:x.onReconnect}),V_=j1(_.locale),I1={config:_,locale:V_,t:(i,y1)=>a(V_,i,y1),api:X,debugMode:Y,scheme:V,capabilities:q,unanswered:U,selectedThread:k,send:L,...K2(R),queue:D.value};function A(){D.store.discardConsumed(),setTimeout(()=>E.current?.focusInput()),J.followTitle(()=>b.current,m_.isOpen)}function I(){D.store.restoreConsumed(b.current?.id)}function w(i){M.openThread(i),W.showChat()}function h(){P.deselect(),W.showChat()}let q_=i3(q,{newChat:h,deleteThread:(i)=>void M.deleteThread(i)});function P_(){G((i)=>!i)}function c(i){let y1={screen:i,viewMode:K,title:k?.title??null,agentName:E_(_.agentName,V_),threadCount:J.threads?.length,debug:{shown:Boolean(q?.debug),on:Y},newChat:q_?.newChat,openHistory:W.openHistory,closeHistory:W.closeHistory,toggleDebug:P_};return $_(n3,{component:$6(Z,"header"),context:y1})}let Z6=$6(Z,"landing"),S5={...f1(q,V_,(i)=>void L(i)),threads:J.threads,composer:$_("div",{className:"cortex-widget__landing-composer",children:$_(U1,{capabilities:q})}),openThread:w,openHistory:W.openHistory},C5=$6(Z,"threadList"),b5={threads:J.threads,selectedThreadId:k?.id,openThread:w,...q_};return $_(h0.Provider,{value:I1,children:$_(M5,{selection:P,threads:J,api:X,configRef:Q,sessionRef:R,pendingSendRef:O,onTurnFinished:A,onSendFailed:I,children:$_(I5,{className:$,theme:_.theme,viewMode:K,screens:W,header:c("threads"),threadList:$_(C5,{...b5}),children:$_(D5,{screens:W,capabilities:q,composerRef:E,header:c("chat"),landing:$_(Z6,{...S5})})})})})}export{r3 as CortexChatWidget};
|