@plusonelabs/cue 0.0.37 → 0.0.38
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.
|
Binary file
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url); global.__CUE_VERSION__ = '0.0.
|
|
2
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url); global.__CUE_VERSION__ = '0.0.38';
|
|
3
3
|
var DAe=Object.create;var oC=Object.defineProperty;var CAe=Object.getOwnPropertyDescriptor;var bAe=Object.getOwnPropertyNames;var IAe=Object.getPrototypeOf,SAe=Object.prototype.hasOwnProperty;var ut=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var T=(t,e)=>()=>(t&&(e=t(t=0)),e);var le=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),mi=(t,e)=>{for(var n in e)oC(t,n,{get:e[n],enumerable:!0})},VH=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of bAe(e))!SAe.call(t,a)&&a!==n&&oC(t,a,{get:()=>e[a],enumerable:!(i=CAe(e,a))||i.enumerable});return t};var xe=(t,e,n)=>(n=t!=null?DAe(IAe(t)):{},VH(e||!t||!t.__esModule?oC(n,"default",{value:t,enumerable:!0}):n,t)),JH=t=>VH(oC({},"__esModule",{value:!0}),t);import rC from"fs";import l_ from"path";function sf(){if(typeof global.__CUE_VERSION__<"u")return global.__CUE_VERSION__;try{let t=process.argv[1],e=l_.join(l_.dirname(t),"..","package.json");if(rC.existsSync(e)){let n=rC.readFileSync(e,"utf-8");return JSON.parse(n).version}}catch{}if(process.argv[1].includes("src/cli.tsx"))try{let t=l_.join(process.cwd(),"package.json");if(rC.existsSync(t)){let e=rC.readFileSync(t,"utf-8");return JSON.parse(e).version}}catch{}return"unknown"}var vv=T(()=>{"use strict"});function Ct(t,e,n,i,a){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!a)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!a:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?a.call(t,n):a?a.value=n:e.set(t,n),n}function Be(t,e,n,i){if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?i:n==="a"?i.call(t):i?i.value:e.get(t)}var lf=T(()=>{});var u_,ZH=T(()=>{u_=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return u_=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,i=>(+i^n()&15>>+i/4).toString(16))}});function id(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Ev,Xg=T(()=>{Ev=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var vt,ro,Po,uf,e2,t2,n2,i2,a2,o2,r2,s2,l2,Ic=T(()=>{Xg();vt=class extends Error{},ro=class t extends vt{constructor(e,n,i,a){super(`${t.makeMessage(e,n,i)}`),this.status=e,this.headers=a,this.requestID=a?.get("request-id"),this.error=n}static makeMessage(e,n,i){let a=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):i;return e&&a?`${e} ${a}`:e?`${e} status code (no body)`:a||"(no status code or body)"}static generate(e,n,i,a){if(!e||!a)return new uf({message:i,cause:Ev(n)});let o=n;return e===400?new t2(e,o,i,a):e===401?new n2(e,o,i,a):e===403?new i2(e,o,i,a):e===404?new a2(e,o,i,a):e===409?new o2(e,o,i,a):e===422?new r2(e,o,i,a):e===429?new s2(e,o,i,a):e>=500?new l2(e,o,i,a):new t(e,o,i,a)}},Po=class extends ro{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},uf=class extends ro{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},e2=class extends uf{constructor({message:e}={}){super({message:e??"Request timed out."})}},t2=class extends ro{},n2=class extends ro{},i2=class extends ro{},a2=class extends ro{},o2=class extends ro{},r2=class extends ro{},s2=class extends ro{},l2=class extends ro{}});function d_(t){return typeof t!="object"?{}:t??{}}function eG(t){if(!t)return!0;for(let e in t)return!1;return!0}function tG(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var wAe,XH,c_,p_,nG,sC,RA=T(()=>{Ic();wAe=/^[a-z][a-z0-9+.-]*:/i,XH=t=>wAe.test(t),c_=t=>(c_=Array.isArray,c_(t)),p_=c_;nG=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new vt(`${t} must be an integer`);if(e<0)throw new vt(`${t} must be a positive integer`);return e},sC=t=>{try{return JSON.parse(t)}catch{return}}});var iG,aG=T(()=>{iG=t=>new Promise(e=>setTimeout(e,t))});var cf,m_=T(()=>{cf="0.57.0"});function BAe(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function TAe(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let i=n.exec(navigator.userAgent);if(i){let a=i[1]||0,o=i[2]||0,l=i[3]||0;return{browser:e,version:`${a}.${o}.${l}`}}}return null}var lG,_Ae,oG,rG,sG,uG,f_=T(()=>{m_();lG=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";_Ae=()=>{let t=BAe();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cf,"X-Stainless-OS":rG(Deno.build.os),"X-Stainless-Arch":oG(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cf,"X-Stainless-OS":rG(globalThis.process.platform??"unknown"),"X-Stainless-Arch":oG(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=TAe();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cf,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};oG=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",rG=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),uG=()=>sG??(sG=_Ae())});function cG(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function A_(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function lC(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return A_({start(){},async pull(n){let{done:i,value:a}=await e.next();i?n.close():n.enqueue(a)},async cancel(){await e.return?.()}})}function Dv(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function pG(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}var u2=T(()=>{});var dG,mG=T(()=>{dG=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});function hG(t){let e=0;for(let a of t)e+=a.length;let n=new Uint8Array(e),i=0;for(let a of t)n.set(a,i),i+=a.length;return n}function Cv(t){let e;return(fG??(e=new globalThis.TextEncoder,fG=e.encode.bind(e)))(t)}function h_(t){let e;return(AG??(e=new globalThis.TextDecoder,AG=e.decode.bind(e)))(t)}var fG,AG,g_=T(()=>{});function NAe(t,e){for(let a=e??0;a<t.length;a++){if(t[a]===10)return{preceding:a,index:a+1,carriage:!1};if(t[a]===13)return{preceding:a,index:a+1,carriage:!0}}return null}function gG(t){for(let i=0;i<t.length-1;i++){if(t[i]===10&&t[i+1]===10||t[i]===13&&t[i+1]===13)return i+2;if(t[i]===13&&t[i+1]===10&&i+3<t.length&&t[i+2]===13&&t[i+3]===10)return i+4}return-1}var Fs,Ns,ad,y_=T(()=>{lf();g_();ad=class{constructor(){Fs.set(this,void 0),Ns.set(this,void 0),Ct(this,Fs,new Uint8Array,"f"),Ct(this,Ns,null,"f")}decode(e){if(e==null)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Cv(e):e;Ct(this,Fs,hG([Be(this,Fs,"f"),n]),"f");let i=[],a;for(;(a=NAe(Be(this,Fs,"f"),Be(this,Ns,"f")))!=null;){if(a.carriage&&Be(this,Ns,"f")==null){Ct(this,Ns,a.index,"f");continue}if(Be(this,Ns,"f")!=null&&(a.index!==Be(this,Ns,"f")+1||a.carriage)){i.push(h_(Be(this,Fs,"f").subarray(0,Be(this,Ns,"f")-1))),Ct(this,Fs,Be(this,Fs,"f").subarray(Be(this,Ns,"f")),"f"),Ct(this,Ns,null,"f");continue}let o=Be(this,Ns,"f")!==null?a.preceding-1:a.preceding,l=h_(Be(this,Fs,"f").subarray(0,o));i.push(l),Ct(this,Fs,Be(this,Fs,"f").subarray(a.index),"f"),Ct(this,Ns,null,"f")}return i}flush(){return Be(this,Fs,"f").length?this.decode(`
|
|
4
4
|
`):[]}};Fs=new WeakMap,Ns=new WeakMap;ad.NEWLINE_CHARS=new Set([`
|
|
5
5
|
`,"\r"]);ad.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function bv(){}function uC(t,e,n){return!e||cC[t]>cC[n]?bv:e[t].bind(e)}function so(t){let e=t.logger,n=t.logLevel??"off";if(!e)return RAe;let i=yG.get(e);if(i&&i[0]===n)return i[1];let a={error:uC("error",e,n),warn:uC("warn",e,n),info:uC("info",e,n),debug:uC("debug",e,n)};return yG.set(e,[n,a]),a}var cC,v_,RAe,yG,od,pC=T(()=>{RA();cC={off:0,error:200,warn:300,info:400,debug:500},v_=(t,e,n)=>{if(t){if(tG(cC,t))return t;so(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(cC))}`)}};RAe={error:bv,warn:bv,info:bv,debug:bv},yG=new WeakMap;od=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*kAe(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new vt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new vt("Attempted to iterate over a response with no body");let n=new E_,i=new ad,a=Dv(t.body);for await(let o of OAe(a))for(let l of i.decode(o)){let p=n.decode(l);p&&(yield p)}for(let o of i.flush()){let l=n.decode(o);l&&(yield l)}}async function*OAe(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let i=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?Cv(n):n,a=new Uint8Array(e.length+i.length);a.set(e),a.set(i,e.length),e=a;let o;for(;(o=gG(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}function UAe(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var Iv,Sc,E_,D_=T(()=>{lf();Ic();u2();y_();u2();Xg();RA();g_();pC();Ic();Sc=class t{constructor(e,n,i){this.iterator=e,Iv.set(this,void 0),this.controller=n,Ct(this,Iv,i,"f")}static fromSSEResponse(e,n,i){let a=!1,o=i?so(i):console;async function*l(){if(a)throw new vt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let p=!1;try{for await(let m of kAe(e,n)){if(m.event==="completion")try{yield JSON.parse(m.data)}catch(A){throw o.error("Could not parse message into JSON:",m.data),o.error("From chunk:",m.raw),A}if(m.event==="message_start"||m.event==="message_delta"||m.event==="message_stop"||m.event==="content_block_start"||m.event==="content_block_delta"||m.event==="content_block_stop")try{yield JSON.parse(m.data)}catch(A){throw o.error("Could not parse message into JSON:",m.data),o.error("From chunk:",m.raw),A}if(m.event!=="ping"&&m.event==="error")throw new ro(void 0,sC(m.data)??m.data,void 0,e.headers)}p=!0}catch(m){if(id(m))return;throw m}finally{p||n.abort()}}return new t(l,n,i)}static fromReadableStream(e,n,i){let a=!1;async function*o(){let p=new ad,m=Dv(e);for await(let A of m)for(let g of p.decode(A))yield g;for(let A of p.flush())yield A}async function*l(){if(a)throw new vt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let p=!1;try{for await(let m of o())p||m&&(yield JSON.parse(m));p=!0}catch(m){if(id(m))return;throw m}finally{p||n.abort()}}return new t(l,n,i)}[(Iv=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],i=this.iterator(),a=o=>({next:()=>{if(o.length===0){let l=i.next();e.push(l),n.push(l)}return o.shift()}});return[new t(()=>a(e),this.controller,Be(this,Iv,"f")),new t(()=>a(n),this.controller,Be(this,Iv,"f"))]}toReadableStream(){let e=this,n;return A_({async start(){n=e[Symbol.asyncIterator]()},async pull(i){try{let{value:a,done:o}=await n.next();if(o)return i.close();let l=Cv(JSON.stringify(a)+`
|
|
@@ -338,7 +338,7 @@ ${q}
|
|
|
338
338
|
\u{1F464} ${i.content}`))})},setShowStatus:()=>{},setShowDebug:()=>{},setShowConnectionStatus:()=>{},setShowClientSelector:()=>{},setShowModelSelector:()=>{},setShowProviderSelector:()=>{},setShowEnvironmentSelector:()=>{},setShowApiKeyInput:()=>{},setShowLoginInput:()=>{},setShowMobileAuth:()=>{},setShowLoginMethodSelector:()=>{},setShowFeedbackInput:()=>{},setChatTarget:()=>{},chatTarget:null,authService:t,anthropicService:null,conversationHistory:null,connectionStatus:null,isLoading:!1,setIsLoading:n=>{n||(process.stdout.write("\r"+" ".repeat(50)+`\r
|
|
339
339
|
`),console.log("Command execution completed"))},setLoadingMessage:n=>{process.stdout.write(`\r\u23FA ${n}...`)},setLoadingStartTime:()=>{},sessionId:"",clientId:""}}var Boe=T(()=>{"use strict";YL();kt();ZL();XL()});async function _oe(t,e,n){let{CueSessionManager:i}=await Promise.resolve().then(()=>(kt(),Ks)),{getCurrentProvider:a}=await Promise.resolve().then(()=>(d1(),ax)),o=t||a()||"cue";console.log(`\u{1F50D} Using provider: ${o}`);let l=new i,p={provider:o,model:n?.openaiModel};switch(o){case"openai":{let A=process.env.OPENAI_API_KEY;if(!A)throw new Error("OPENAI_API_KEY environment variable is required for OpenAI provider");console.log("\u{1F50D} Using direct OpenAI API"),p.openaiApiKey=A,p.model=n?.openaiModel||"gpt-4o";break}case"anthropic":{console.log("\u{1F50D} Using direct Anthropic API");let A=process.env.ANTHROPIC_API_KEY;if(!A)throw new Error("ANTHROPIC_API_KEY environment variable is required for Anthropic provider");p.anthropicApiKey=A;break}case"cue":default:{let A=e?.getAccessToken(),g=e?.getCueApiKey();if(!A&&!g){if(console.log("\u{1F50D} No Cue API key, falling back to direct Anthropic API"),!process.env.ANTHROPIC_API_KEY)throw new Error("No authentication available. Please set CUE_API_KEY, login, or provide ANTHROPIC_API_KEY")}else{let E=e?.getBaseUrl()||"http://localhost:8000";console.log(`\u{1F50D} Using Cue backend with ${A?"access token":"API key"}: ${(A||g)?.substring(0,15)+"..."}`),A?p.accessToken=A:g&&(p.cueApiKey=g),p.cueBaseUrl=E}break}}let{session:m}=await l.getOrCreateSession(n?.sessionId,p);return m}var Toe=T(()=>{"use strict"});var T6,uP=T(()=>{"use strict";kt();T6=class{constructor(e="cue"){this.serviceName=e;S.debug(`SessionBroadcaster initialized for ${e}`)}wsClient;clientId;authService;hasLoggedNotificationStatus=!1;setWebSocketClient(e,n){this.wsClient=e,this.clientId=n}async setupNotifications(e){this.authService=e;let n=ap();if(await n.initialize(e),!this.hasLoggedNotificationStatus){let i=n.isNotificationEnabled();S.debug(`[SessionBroadcaster-${this.serviceName}] Notification status: ${i?"ENABLED":"DISABLED"}`),this.hasLoggedNotificationStatus=!0}}async sendSessionStart(e,n,i,a=!1,o,l){if(!this.wsClient)return;let p={sessionInfo:{...i,cliClientType:this.serviceName},isResume:a,originalSessionId:l},m=tp(e,En.START,p,{targetClientId:n},o);S.debug(`Broadcasting session_start for ${e}`),await this.wsClient.send(m)}async sendSessionUpdate(e,n,i,a,o){if(!this.wsClient)return;let l={sessionId:e,content:i.content,contentType:i.contentType||(typeof i.content=="string"?"text":"content_parts"),role:i.role,type:i.type,uuid:i.uuid,messageId:i.messageId};i.messageId&&S.debug(`Including LLM messageId in session_update: ${i.messageId}`);let p=tp(e,En.UPDATE,l,{targetClientId:n,messageId:o},a),m=typeof i.content=="string"?i.content.slice(0,50):"content blocks";S.debug(`Broadcasting session_update for ${e}: ${m}`),await this.wsClient.send(p)}async sendSessionEnd(e,n,i="Session completed"){if(!this.wsClient)return;let a={sessionId:e,message:i},o=tp(e,En.END,a,{targetClientId:n});S.debug(`Broadcasting session_end for ${e}`),await this.wsClient.send(o);let l=ap();if(l.isNotificationEnabled()&&i){let p=`\u2705 ${this.serviceName==="claude_code"?"Claude Code":"CLI"} Session end`,m=typeof i=="string"?i.slice(0,200):"Session end";await l.sendNotification("responses",p,m,{sessionId:e,eventType:En.END,service:this.serviceName})&&S.info(`[Notifications] Sent completion notification for session ${e}`)}}async sendSessionTurnStart(e,n,i,a){if(!this.wsClient)return;let o=tp(e,En.TURN_START,i,{targetClientId:n},a);try{await this.wsClient.send(o),S.debug("Sent turn_start event",{sessionId:e,targetClientId:n,requestId:a})}catch(l){S.error("Failed to send turn_start",{error:l})}}async sendSessionTurnEnd(e,n,i,a){if(!this.wsClient)return;let o=tp(e,En.TURN_END,i,{targetClientId:n},a);try{await this.wsClient.send(o),S.debug("Sent turn_end event",{sessionId:e,targetClientId:n,requestId:a,hasToolCalls:i.hasToolCalls})}catch(l){S.error("Failed to send turn_end",{error:l})}}async sendAssistantNotification(e,n,i,a){let o=ap();if(!o.isNotificationEnabled()){S.debug("[Notifications] Skipping notification - not enabled");return}try{let l=i.split(`
|
|
340
340
|
`),p=l[0].length>100?l[0].substring(0,100)+"...":l[0];await o.sendNotification("responses",e,p,{sessionId:n,requestId:a,eventType:"assistant_complete",service:this.serviceName})&&S.info(`[Notifications] Sent assistant completion notification for session ${n}`)}catch(l){S.debug("[Notifications] Failed to send assistant notification:",{error:String(l)})}}async sendProgress(e,n,i,a){if(!this.wsClient)return;let o,l;typeof n=="string"?(o=n,l="text"):(n.type&&n.content,o=JSON.stringify(n),l="text");let p={sessionId:e,content:o,contentType:l,role:"assistant"},m=tp(e,En.UPDATE,p,{targetClientId:i},a);S.debug(`Broadcasting progress for ${e}`),await this.wsClient.send(m)}isConnected(){return this.wsClient!==null}sendAssistantMessageWithToolCalls(e,n,i,a,o){if(!this.wsClient){S.warn("SessionBroadcaster: Cannot send assistant message with tool_calls - no WebSocket connection");return}let l=[];i.content&&l.push({type:"text",text:i.content}),i.tool_calls&&i.tool_calls.length>0&&lS(i.tool_calls).forEach(g=>{l.push(g)});let p={sessionId:e,content:l.length>0?l:"",contentType:l.length>0?"content_parts":"text",role:"assistant",type:"assistant",uuid:a},m=tp(e,En.UPDATE,p,{targetClientId:n},o);S.debug("Broadcasting assistant message with tool_calls",{sessionId:e,tool_calls_count:i.tool_calls?.length||0,requestId:o,uuid:a}),this.wsClient.send(m)}sendToolResultMessage(e,n,i,a,o){if(!this.wsClient){S.warn("SessionBroadcaster: Cannot send tool result - no WebSocket connection");return}let l={sessionId:e,content:[{type:"tool_result",tool_use_id:i.tool_call_id,content:i.content,is_error:!1}],contentType:"content_parts",role:"user",type:"user",uuid:a},p=tp(e,En.UPDATE,l,{targetClientId:n},o);S.debug("Broadcasting tool result message",{sessionId:e,tool_call_id:i.tool_call_id,requestId:o,uuid:a}),this.wsClient.send(p)}}});import{randomUUID as Q6}from"crypto";var ox,Qoe=T(()=>{"use strict";kt();kt();uP();ox=class{sessionManager;broadcaster;activeStreams=new Map;sessionRequestContext=new Map;clientId="";constructor(){this.broadcaster=new T6("claude_code"),this.sessionManager=new qh(5,1440*60*1e3),S.debug("ClaudeHandler constructor called - new instance created")}async handleRun(e,n){return S.info("ClaudeHandler.handleRun - received options",{useStreaming:n.useStreaming,sessionId:n.sessionId,cwd:n.cwd,cwdStartsWithSlash:n.cwd?.startsWith("/"),cwdLength:n.cwd?.length,hasPrompt:!!n.prompt,requestId:e.request_id}),this.handleStreamingRun(e,n)}async handleStreamingRun(e,n){let{prompt:i,sessionId:a}=n,o=n.cwd;o&&!o.startsWith("/")&&!o.startsWith("~")&&!o.startsWith(".")&&(o="/"+o,S.debug("Fixed missing leading slash in cwd",{original:n.cwd,fixed:o}));let l=e.client_id,p=e.request_id;S.info("\u{1F680} Starting streaming Claude session",{sessionId:a,cwd:o,promptLength:i?.length,senderClientId:l,requestId:p});let m=null,{session:A,isNew:g,sessionId:E}=await this.sessionManager.getOrCreateSession(a,{cwd:o||process.cwd(),onSessionDetected:w=>{S.info("Session ID detected",{sessionId:w,originalId:E}),m=w;let _=a?a===w?"Resumed session from memory":"Resumed session from disk":"New session created";this.broadcaster.sendSessionStart(w,l||"",{sessionId:w,clientId:this.clientId,cwd:o||process.cwd(),cliClientType:ho.CLAUDE_CODE,messageCount:0,createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString()},a!==void 0,p,a),this.sendStatus(w,_,l,p)},onError:w=>{S.error("Session error",{error:w});let _=m||E;this.broadcaster.sendSessionUpdate(_,l||"",{content:`Error: ${w.message}`,contentType:"text",type:"status",uuid:Q6()},p)}});this.sessionRequestContext.set(E,{requestId:p,clientId:l});let b=m||E;this.sendStatus(b,"Processing your message...",l,p),this.broadcaster.sendSessionTurnStart(b,l||"",{message:i,requestId:p,clientId:l,timestamp:new Date().toISOString()},p),await A.sendMessage(i),this.sendStatus(b,"Thinking...",l,p);let D=A.getOutputStream();this.activeStreams.get(E)?S.debug("Stream processor already running for session",{sessionId:E,requestId:p,clientId:l}):(this.activeStreams.set(E,D),this.processStreamInBackground(D,E,()=>{let w=this.sessionRequestContext.get(E);return{sessionId:m,requestId:w?.requestId,clientId:w?.clientId}})),S.info("Streaming session started",{sessionId:E,realSessionId:m})}sendStatus(e,n,i,a){this.broadcaster.sendSessionUpdate(e,i||"",{content:n,contentType:"text",type:"status",uuid:Q6()},a)}processStreamMessage(e,n,i,a){if(e.type==="assistant"){let o=e,l=o.message.content,p=typeof l=="string"?"text":"content_parts";this.broadcaster.sendSessionUpdate(n,i||"",{content:l,contentType:p,type:"assistant",role:"assistant",messageId:o.message.id,uuid:o.uuid||Q6()},a)}else if(e.type==="system"){let o=e;o.subtype==="init"&&o.session_id?(S.debug("Detected Claude init message - sending as structured metadata",{sessionId:n,hasTools:!!o.tools,toolCount:o.tools?.length,model:o.model,cwd:o.cwd}),this.broadcaster.sendSessionUpdate(n,i||"",{content:o,contentType:"session_metadata",type:"system",subtype:"init",role:"system",uuid:o.uuid||Q6()},a)):this.broadcaster.sendSessionUpdate(n,i||"",{content:JSON.stringify(e),contentType:"text",type:"system",role:"system",uuid:o.uuid||Q6()},a)}}async processStreamInBackground(e,n,i){let a=!1,o="",l=!1,p="";try{for await(let m of e){let A=i(),g=A.sessionId||n;if(m.type==="assistant"){!a&&A.requestId&&(a=!0,this.sendStatus(g,"Claude is responding...",A.clientId,A.requestId));let E=m,b=E.message.content;p=E.uuid||"",typeof b=="string"?o=b:Array.isArray(b)&&(l=b.some(D=>D.type==="tool_use"),o=b.filter(D=>D.type==="text").map(D=>D.text||"").join(`
|
|
341
|
-
`)),this.processStreamMessage(m,g,A.clientId,A.requestId)}else m.type==="system"?this.processStreamMessage(m,g,A.clientId,A.requestId):m.type==="result"&&(S.debug("Message complete, session remains active, waiting for next message",{sessionId:g,result:m.result?.substring(0,100),requestId:A.requestId}),(o||l)&&(o&&!l&&await this.broadcaster.sendAssistantNotification("Claude responded",g,o,A.requestId),this.broadcaster.sendSessionTurnEnd(g,A.clientId||"",{message:o,uuid:p,hasToolCalls:l,tokenUsage:void 0,requestId:A.requestId,clientId:A.clientId,timestamp:new Date().toISOString()},A.requestId)),a=!1,o="",l=!1,p="",this.sendStatus(g,"Ready for next message",A.clientId,A.requestId))}S.info("Stream ended, session closed",{sessionId:i().sessionId||n})}catch(m){let A=i(),g=A.sessionId||n;S.error("Stream processing error",{error:String(m),sessionId:g}),this.broadcaster.sendSessionUpdate(g,A.clientId||"",{content:`Stream error: ${m}`,contentType:"text",type:"status",uuid:Q6()},A.requestId),this.activeStreams.delete(n)}}async handleStop(e){e?(this.activeStreams.has(e)&&(S.debug("Stopping active stream",{sessionId:e}),this.activeStreams.delete(e)),await this.sessionManager.closeSession(e),S.info(`Stopped Claude session: ${e}`)):S.info("Claude Code stop requested without sessionId")}async handleReset(e){e?(this.activeStreams.has(e)&&(S.debug("Stopping active stream for reset",{sessionId:e}),this.activeStreams.delete(e)),await this.sessionManager.closeSession(e),S.info(`Reset Claude session: ${e}`)):S.info("Claude Code reset requested without sessionId")}async handleDelete(e){S.info("\u{1F9F9} CLAUDE DELETE: Starting session cleanup",{sessionId:e,hasActiveStream:this.activeStreams.has(e),activeStreamsCount:this.activeStreams.size}),this.activeStreams.has(e)&&(S.debug("CLAUDE DELETE: Stopping active stream",{sessionId:e}),this.activeStreams.delete(e),S.info("CLAUDE DELETE: Active stream stopped",{sessionId:e})),S.debug("CLAUDE DELETE: Calling manager.deleteSession",{sessionId:e});let n=await this.sessionManager.deleteSession(e,!1);this.sessionRequestContext.delete(e),S.info("CLAUDE DELETE: Completed",{sessionId:e,success:n,remainingStreams:this.activeStreams.size})}setWebSocketClient(e,n){this.clientId=n,this.broadcaster.setWebSocketClient(e,n)}async setupNotifications(e){await this.broadcaster.setupNotifications(e)}getActiveSessions(){return this.sessionManager.getActiveSessions()}getBroadcaster(){return this.broadcaster}}});var rx,Foe=T(()=>{"use strict";kt();rx=class{clientId;broadcaster;sessionListeners=new Map;constructor(e,n){this.clientId=e,this.broadcaster=n}attachToSession(e,n){let i=e.getSessionId?.()||n.sessionId;if(this.sessionListeners.has(i)){S.debug("Event processor already attached to session",{sessionId:i});return}let a=p=>{S.info("CueEventProcessor: Received session event",{eventType:p.type,sessionId:p.sessionId,hasData:!!p.data,dataKeys:p.data?Object.keys(p.data):[]}),p.type==="turn_start"&&S.info("JSONL: turn_start event received",{sessionId:p.sessionId,message:p.data?.message,uuid:p.data?.uuid,cwd:p.data?.cwd}),this.handleStreamingEvent(p,n.senderClientId,n.requestId)},o=p=>{let m=e.getSessionId?.()||n.realSessionId||n.sessionId;S.debug("CueEventProcessor: Received message event",{role:p.role,hasContent:!!p.content,hasToolCalls:!!p.tool_calls,hasToolCallId:!!p.tool_call_id,sessionId:m})};e.on("session-event",a),e.on("session-message",o);let l=()=>{e.off("session-event",a),e.off("session-message",o)};this.sessionListeners.set(i,l),S.info("Event processor attached to session",{sessionId:i})}detachFromSession(e){let n=this.sessionListeners.get(e);n&&(n(),this.sessionListeners.delete(e),S.info("Event processor detached from session",{sessionId:e}))}detachAll(){for(let[e,n]of this.sessionListeners.entries())n();this.sessionListeners.clear(),S.info("Event processor detached from all sessions")}sendStatus(e,n){let i=n.realSessionId||n.sessionId||"";S.debug("Sending status update",{status:e,sessionId:i,clientId:n.senderClientId}),this.broadcaster.sendSessionUpdate(i,n.senderClientId||"",{content:e,contentType:"text",type:"status"},n.requestId)}sendError(e,n){let i=n.realSessionId||n.sessionId||"",a=e instanceof Error?e.message:e;S.error("Sending error update",{error:a,sessionId:i,clientId:n.senderClientId}),this.broadcaster.sendSessionUpdate(i,n.senderClientId||"",{content:`Error: ${a}`,contentType:"text",type:"status"},n.requestId)}async handleStreamingEvent(e,n,i){switch(S.debug("handleStreamingEvent called",{eventType:e.type,sessionId:e.sessionId,targetClientId:n,requestId:i,metadata:{...e.metadata}}),e.type){case"session_start":await this.handleSessionStartEvent(e,n,i);break;case"session_update":await this.handleSessionUpdateEvent(e,n,i);break;case"turn_start":await this.handleTurnStartEvent(e,n,i);break;case"turn_end":await this.handleTurnEndEvent(e,n,i);break}}async handleSessionStartEvent(e,n,i){let a=e.data,o=!a.isNew;S.info("session_start event",{...a,sessionId:e.sessionId,projectId:a.projectId,hasProjectId:!!a.projectId,clientId:this.clientId,targetClientId:n,cwd:a.cwd||"undefined"}),this.broadcaster.sendSessionStart(e.sessionId,n||"",{sessionId:e.sessionId,projectId:a.projectId,clientId:this.clientId||a.clientId,cwd:a.cwd,cliClientType:ho.CUE,messageCount:a.messageCount||0,createdAt:a.createdAt,lastActivityAt:a.lastActivityAt},o,i,a.originalSessionId)}async handleSessionUpdateEvent(e,n,i){let a=e.data;S.debug("handleSessionUpdateEvent: Received update data",{sessionId:e.sessionId,contentType:a.contentType,role:a.role,type:a.type,uuid:a.uuid,messageId:a.messageId,hasContent:!!a.content,contentIsArray:Array.isArray(a.content),contentLength:Array.isArray(a.content)||typeof a.content=="string"?a.content.length:0,contentPreview:typeof a.content=="string"?a.content.substring(0,100):Array.isArray(a.content)?`Array with ${a.content.length} items`:"unknown content type"}),this.broadcaster.sendSessionUpdate(e.sessionId,n||"",{content:a.content,contentType:a.contentType,type:a.type,role:a.role,uuid:a.uuid,messageId:a.messageId},i)}async handleTurnStartEvent(e,n,i){let a=e.data;this.broadcaster.sendSessionTurnStart(e.sessionId,n||"",a,i)}async handleTurnEndEvent(e,n,i){let a=e.data;S.debug("turn_end event received",{sessionId:e.sessionId,hasMessage:!!a.message,messageLength:a.message?.length,hasToolCalls:a.hasToolCalls}),a.message&&!a.hasToolCalls&&(S.info("Sending assistant notification",{sessionId:e.sessionId,messagePreview:a.message.substring(0,50)}),await this.broadcaster.sendAssistantNotification("Cue responded",e.sessionId,a.message,a.requestId)),this.broadcaster.sendSessionTurnEnd(e.sessionId,n||"",a,i)}}});var sx,Noe=T(()=>{"use strict";kt();uP();Foe();sx=class{sessionManager;broadcaster;authService;clientId;currentModel;eventProcessor;constructor(e,n){this.clientId=e,this.broadcaster=new T6("cue"),this.authService=n||u1(),this.sessionManager=new em(10,1440*60*1e3),this.eventProcessor=new rx(this.clientId,this.broadcaster)}async handleRun(e,n){S.info("CueHandler.handleRun - received options",{...n,hasPrompt:!!n.prompt,hasMessage:!!n.message,requestId:e.request_id});let i=this.extractPrompt(n);this.currentModel=n.model;let a={sessionId:n.sessionId||"",realSessionId:null,senderClientId:e.client_id,requestId:e.request_id,cwd:n.cwd,model:n.model,provider:n.provider};S.info("Starting direct Cue session",{...a,promptLength:i.length});let o=await this.createOrGetSession(n,a);this.eventProcessor.attachToSession(o.session,a),!o.isNew&&a.sessionId===o.sessionId&&this.handleExistingSession(o,a),await this.processMessage(o.session,i,o.sessionId,a),S.info("Direct session completed",{sessionId:a.realSessionId||o.sessionId,originalSessionId:a.sessionId,cwd:a.cwd})}extractPrompt(e){let n=e.prompt||e.message;if(!n)throw S.error("No prompt or message provided, throwing error"),new Error("No prompt or message provided");return n}async createOrGetSession(e,n){let i=this.getAuthCredentials(),a=hf(),o=Hv(),l=e.sessionId||o;return S.info("Creating/resuming Cue session",{sessionId:l,fromConfig:!e.sessionId&&!!o,projectId:a,hasProjectId:!!a,cwd:e.cwd,model:e.model,provider:e.provider}),await this.sessionManager.getOrCreateSession(l,{cwd:e.cwd,projectId:a,model:e.model,provider:e.provider,...i,useStreamingRunner:!0,onSessionDetected:p=>this.handleSessionDetected(p,l,n),onMessage:p=>this.handleSessionMessage(p,n),onError:p=>this.handleSessionError(p,n)})}getAuthCredentials(){return{accessToken:this.authService.getAccessToken()||void 0,cueApiKey:this.authService.getCueApiKey()||void 0,anthropicApiKey:this.authService.getAnthropicApiKey()||void 0,openaiApiKey:this.authService.getOpenAIApiKey()||void 0,cueBaseUrl:this.authService.getBaseUrl()||void 0}}handleSessionDetected(e,n,i){n===e?S.info(`\u{1F4C2} Resuming session: ${e}`,{sessionId:e,action:"resume"}):!n?S.info(`\u{1F195} Created new session: ${e}`,{sessionId:e,action:"create"}):S.info("Session ID detected",{sessionId:e,originalId:n,action:"detect"}),i.realSessionId=e;let l=this.determineSessionState(n,e),p=this.createSessionInfo(e,i);this.broadcaster.sendSessionStart(e,i.senderClientId||"",p,n!==void 0,i.requestId,n),i.sessionId=e,this.eventProcessor.sendStatus(l,i)}determineSessionState(e,n){return e?e===n?"Resumed session from memory":"Resumed session from disk":"New session created"}createSessionInfo(e,n){return{sessionId:e,clientId:n.senderClientId||"",cwd:n.cwd||process.cwd(),cliClientType:"cue",messageCount:0,createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString()}}handleSessionMessage(e,n){S.info("Received message from CueSession",{role:e.role,hasContent:!!e.content,timestamp:e.timestamp});let i=n.realSessionId||n.sessionId;this.eventProcessor.handleStreamingEvent({type:"session_update",sessionId:i,data:{sessionId:i,content:e.content,contentType:"content_parts",type:"assistant",role:"assistant",messageId:e.id,requestId:n.requestId,clientId:n.senderClientId,isPartial:!e.tokenUsage,model:e.model||this.currentModel},metadata:{callFrom:"handleSessionMessage"}},n.senderClientId,n.requestId)}handleSessionError(e,n){S.error("Session error",{error:e}),this.eventProcessor.sendError(e,n)}handleExistingSession(e,n){n.realSessionId=e.sessionId;let i=e.session.getInfo().messageCount;S.info(`\u{1F4DD} Resuming session ${e.sessionId}`,{sessionId:e.sessionId,loadedMessages:`Loading ${i} messages from history`});let a={sessionId:e.sessionId,clientId:n.senderClientId||"",cwd:n.cwd||process.cwd(),cliClientType:"cue",messageCount:i,createdAt:e.session.getInfo().createdAt.toISOString(),lastActivityAt:e.session.getInfo().lastActivityAt.toISOString()};this.broadcaster.sendSessionStart(e.sessionId,n.senderClientId||"",a,!0,n.requestId,n.sessionId),this.eventProcessor.sendStatus("Resumed session from memory",n)}async processMessage(e,n,i,a){a.sessionId=a.realSessionId||i,this.eventProcessor.sendStatus("Processing your message...",a);let o=await e.sendMessage(n);this.eventProcessor.sendStatus("Thinking...",a),await this.processStream(o,a)}async processStream(e,n){try{for await(let i of e)if(S.info("Processing message from stream",{role:i.role,hasContent:!!i.contentBlocks}),i.role==="assistant"){this.eventProcessor.sendStatus("Ready for next message",n);break}}catch(i){S.error("Stream processing error",{error:String(i),sessionId:n.sessionId}),this.eventProcessor.sendError(i instanceof Error?i:`Stream error: ${i}`,n)}}async handleStop(e){e&&(this.eventProcessor.detachFromSession(e),await this.sessionManager.closeSession(e),S.info(`Stopped session: ${e}`))}async handleReset(e,n){n&&(this.eventProcessor.detachFromSession(n),await this.sessionManager.closeSession(n),S.info(`Reset session: ${n}`))}async handleDelete(e){S.info("CUE DELETE: Starting session cleanup",{sessionId:e}),this.eventProcessor.detachFromSession(e),await this.sessionManager.deleteSession(e,!0)}setWebSocketClient(e,n){this.clientId=n,this.broadcaster.setWebSocketClient(e,n)}async setupNotifications(e){await this.broadcaster.setupNotifications(e)}getActiveSessions(){return this.sessionManager.getActiveSessions()}getBroadcaster(){return this.broadcaster}}});var lx,Roe=T(()=>{"use strict";kt();lx=class{wsClient;claudeHandler;cueHandler;constructor(e,n){this.claudeHandler=e,this.cueHandler=n}setWebSocketClient(e){this.wsClient=e,S.debug("SESSION DISCOVERY HANDLER: WebSocket client set",{hasClient:!!e,clientId:e?.config?.clientId})}async handleSessionDiscovery(e){S.debug("SESSION DISCOVERY: Handler called",{messageType:e.type,clientId:e.client_id,requestId:e.request_id,payloadAction:e.payload?.action});let n=e.payload;if(n?.action!=="request"){S.info("SESSION DISCOVERY: Ignoring non-request message",{action:n?.action});return}S.info("SESSION DISCOVERY: Processing request from:",{clientId:e.client_id,requestId:e.request_id});try{let{SessionDiscoveryService:i,getProjectsPathForClientType:a,CLI_CLIENT_TYPES:o}=await Promise.resolve().then(()=>(kt(),Ks)),l=n.cli_client_type||o.CLAUDE_CODE,p=a(l);S.debug("Session discovery using client type:",{clientType:l,projectsPath:p,requestedType:n.cli_client_type});let m=new i(p,l);S.info("SESSION DISCOVERY: Discovering sessions",{limit:n.limit||50,projectsPath:p,clientType:l,ourClientId:this.wsClient?.config.clientId});let A=await m.discoverSessions(n.limit||50,this.wsClient?.config.clientId,l),g=A.map(N=>({...N,status:"inactive"}));S.info("SESSION DISCOVERY: Found cold sessions from disk",{count:A.length,sessionIds:A.slice(0,5).map(N=>N.sessionId)});let E=[];if(this.claudeHandler&&l===o.CLAUDE_CODE)try{let N=this.claudeHandler.getActiveSessions();S.info("SESSION DISCOVERY: Found hot sessions from ClaudeHandler",{count:N.length,sessionIds:N.map(M=>M.sessionId)}),E=N.map(M=>{let z=M.lastActivityAt?new Date(M.lastActivityAt):new Date,re=new Date().getTime()-z.getTime()>3e4;return{sessionId:M.sessionId,clientId:this.wsClient?.config.clientId||"unknown",cwd:M.metadata?.cwd||process.cwd(),cliClientType:o.CLAUDE_CODE,messageCount:M.messageCount,createdAt:M.createdAt.toISOString(),lastActivityAt:M.lastActivityAt.toISOString(),status:re?"idle":"active",ownerClientId:this.wsClient?.config.clientId}})}catch(N){S.warn("Failed to get hot sessions from ClaudeHandler:",{error:String(N)})}else if(this.cueHandler&&l===o.CUE)try{let N=this.cueHandler.getActiveSessions();S.info("SESSION DISCOVERY: Found hot sessions from CueHandler",{count:N.length,sessionIds:N.map(M=>M.sessionId)}),E=N.map(M=>{let z=M.lastActivityAt?new Date(M.lastActivityAt):new Date,re=new Date().getTime()-z.getTime()>3e4;return{sessionId:M.sessionId,clientId:this.wsClient?.config.clientId||"unknown",cwd:M.cwd||process.cwd(),cliClientType:o.CUE,messageCount:M.messageCount||0,createdAt:M.createdAt?new Date(M.createdAt).toISOString():new Date().toISOString(),lastActivityAt:M.lastActivityAt?new Date(M.lastActivityAt).toISOString():new Date().toISOString(),status:re?"idle":"active",ownerClientId:this.wsClient?.config.clientId}})}catch(N){S.warn("Failed to get hot sessions from CueHandler:",{error:String(N)})}let b=new Set(E.map(N=>N.sessionId)),D=g.filter(N=>!b.has(N.sessionId)),x=[...E,...D];x.sort((N,M)=>{let z={active:3,idle:2,inactive:1},q=z[N.status||"inactive"],ae=z[M.status||"inactive"];if(q!==ae)return ae-q;let re=new Date(N.lastActivityAt||N.createdAt||0).getTime();return new Date(M.lastActivityAt||M.createdAt||0).getTime()-re});let w=x.slice(0,n.limit||50);if(S.info("SESSION DISCOVERY: Combined active and inactive sessions",{totalCount:w.length,activeCount:w.filter(N=>N.status==="active").length,idleCount:w.filter(N=>N.status==="idle").length,inactiveCount:w.filter(N=>N.status==="inactive").length,sessionIds:w.slice(0,5).map(N=>`${N.sessionId}(${N.status})`)}),!this.wsClient){S.error("WebSocket client not available for session discovery response");return}let _=w.map(N=>zl(N)),F=e.client_id;S.info("SESSION DISCOVERY: Preparing response",{recipientId:F,ourClientId:this.wsClient.config.clientId,sessionCount:w.length,requestId:e.request_id}),await this.wsClient.send({type:"session_discovery",payload:{action:"response",client_id:this.wsClient.config.clientId,sessions:_,sender:this.wsClient.config.clientId,target_client_id:F},request_id:e.request_id}),S.info("SESSION DISCOVERY: Response sent successfully",{sessionCount:w.length,toClient:F,requestId:e.request_id})}catch(i){S.error("Error handling session discovery request:",{error:i})}}async handleSessionHistory(e){let n=e.payload;if(n?.action!=="request")return;let i=n.session_id,a=n.limit||20,o=n.offset||0;S.debug("Received session history request",{sessionId:i,limit:a,offset:o,clientId:e.client_id,cliClientType:n.cli_client_type,fullPayload:n});try{let{SessionDiscoveryService:l,getProjectsPathForClientType:p,CLI_CLIENT_TYPES:m}=await Promise.resolve().then(()=>(kt(),Ks)),A=n.cli_client_type||m.CLAUDE_CODE,g=p(A);S.debug("Using client type for session history",{clientType:A,projectsPath:g,requestedType:n.cli_client_type});let E=i,D=await new l(g,A).getSessionHistory(E,a,o);if(S.debug("Found session history messages",{sessionId:i,count:D.length}),!this.wsClient){S.error("WebSocket client not available for session history response");return}let x=e.client_id;await this.wsClient.send({type:"session_history",payload:{action:"response",session_id:i,client_id:this.wsClient.config.clientId,messages:D,limit:a,offset:o,sender:this.wsClient.config.clientId,target_client_id:x},request_id:e.request_id}),S.debug("Session history response sent",{messagesCount:D.length})}catch(l){S.error("Error handling session history request:",{error:l,sessionId:i})}}async handleSessionDelete(e){let n=e.payload;if(n?.action!=="request"){S.debug("Ignoring non-request session delete message",{action:n?.action});return}let i=n.session_id;S.info("\u{1F4DD} SESSION DELETE: Request received",{sessionId:i,clientId:e.client_id,requestId:e.request_id});try{let{SessionDiscoveryService:a,getProjectsPathForClientType:o,CLI_CLIENT_TYPES:l}=await Promise.resolve().then(()=>(kt(),Ks)),p=n.cli_client_type||l.CLAUDE_CODE,m=o(p);S.debug("SESSION DELETE: Using project path",{clientType:p,projectsPath:m});let A=i;S.debug("SESSION DELETE: Starting deletion",{actualSessionId:A});let E=await new a(m,p).deleteSession(A);if(S.info("\u{1F5D1}\uFE0F SESSION DELETE: File deletion result",{sessionId:i,actualSessionId:A,success:E,projectsPath:m}),E?p===l.CLAUDE_CODE&&this.claudeHandler?(S.debug("SESSION DELETE: Notifying ClaudeHandler",{actualSessionId:A}),await this.claudeHandler.handleDelete(A),S.info("SESSION DELETE: ClaudeHandler notified",{actualSessionId:A})):p===l.CUE&&this.cueHandler?(S.debug("SESSION DELETE: Notifying CueHandler",{actualSessionId:A}),await this.cueHandler.handleDelete(A),S.info("SESSION DELETE: CueHandler notified",{actualSessionId:A})):S.debug(`SESSION DELETE: No ${p} handler available for cleanup`):S.warn("SESSION DELETE: Failed to delete session file",{sessionId:i,actualSessionId:A}),!this.wsClient){S.error("WebSocket client not available for session delete response");return}let b=e.client_id;await this.wsClient.send({type:"session_delete",payload:{action:"response",session_id:i,client_id:this.wsClient.config.clientId,success:E,sender:this.wsClient.config.clientId,target_client_id:b},request_id:e.request_id}),S.info("\u2705 SESSION DELETE: Response sent",{sessionId:i,success:E,recipientId:b,requestId:e.request_id})}catch(a){if(S.error("Error handling session delete request:",{error:a,sessionId:i}),this.wsClient){let o=e.client_id;await this.wsClient.send({type:"session_delete",payload:{action:"response",session_id:i,client_id:this.wsClient.config.clientId,success:!1,error:a instanceof Error?a.message:String(a),sender:this.wsClient.config.clientId,target_client_id:o},request_id:e.request_id})}}}}});import{randomUUID as d9e}from"crypto";function cx(t,e,n){return ux&&(S.debug("Cleaning up existing AgentControlRouter"),ux.cleanup()),S.debug("Creating new AgentControlRouter instance with all dependencies"),ux=new cP(t,e,n),ux}var cP,ux,pP=T(()=>{"use strict";kt();Qoe();Noe();Roe();cP=class{wsClient;clientId;authService;claudeHandler;cueHandler;sessionDiscoveryHandler;handlers=new Map;boundHandlers={};constructor(e,n,i){if(!e)throw new Error("WebSocketClient is required");if(!n)throw new Error("clientId is required");if(!i)throw new Error("AuthService is required");this.wsClient=e,this.clientId=n,this.authService=i,this.claudeHandler=new ox,this.cueHandler=new sx(this.clientId,this.authService),this.sessionDiscoveryHandler=new lx(this.claudeHandler,this.cueHandler),this.claudeHandler.setWebSocketClient(e,n),this.cueHandler.setWebSocketClient(e,n),this.sessionDiscoveryHandler.setWebSocketClient(e),this.initializeHandlers(),this.setupEventHandler(),this.setupNotifications()}async setupNotifications(){try{await this.claudeHandler.setupNotifications(this.authService),await this.cueHandler.setupNotifications(this.authService),S.debug("AgentControlRouter notifications configured")}catch(e){S.error("Failed to setup notifications",{error:e})}}initializeHandlers(){this.handlers.set(ho.CUE,{handleRun:async(e,n)=>{S.info("ROUTER: Calling CueHandler with parameters:",{message:n.parameters.message,prompt:n.parameters.prompt,sessionId:n.parameters.session_id,cwd:n.parameters.cwd,model:n.parameters.model,provider:n.parameters.provider,useStreaming:n.parameters.use_streaming,hasMessage:!!n.parameters.message,hasPrompt:!!n.parameters.prompt,rawPayload:n.parameters});let i={message:n.parameters.message,prompt:n.parameters.prompt,sessionId:n.parameters.session_id,cwd:n.parameters.cwd,model:n.parameters.model,provider:n.parameters.provider,useStreaming:n.parameters.use_streaming??!0};S.info("ROUTER: CueOptions object before calling handler:",i),await this.cueHandler.handleRun(e,i)},handleStop:async(e,n)=>{await this.cueHandler.handleStop(n.parameters.session_id)},handleReset:async(e,n)=>{await this.cueHandler.handleReset(e,n.parameters.session_id)}}),this.handlers.set(ho.CLAUDE_CODE,{handleRun:async(e,n)=>{let i=n.parameters.prompt||n.parameters.message;if(!i){await this.sendErrorResponse(e,"No prompt provided");return}n.parameters.use_streaming?S.info("STREAMING MODE ENABLED for Claude Code",{sessionId:n.parameters.session_id,cwd:n.parameters.cwd,fromClient:e.client_id,requestId:e.request_id}):S.info("Regular mode for Claude Code (no streaming)",{sessionId:n.parameters.session_id});try{await this.claudeHandler.handleRun(e,{prompt:i,sessionId:n.parameters.session_id,cwd:n.parameters.cwd,useStreaming:n.parameters.use_streaming})}catch(a){let o=a instanceof Error?a.message:String(a);await this.sendErrorResponse(e,o)}},handleStop:async(e,n)=>{await this.claudeHandler.handleStop(n.parameters.session_id)},handleReset:async(e,n)=>{await this.claudeHandler.handleReset(n.parameters.session_id)}})}cleanup(){S.debug("ROUTER: Cleaning up AgentControlRouter"),this.cleanupEventHandlers()}setupEventHandler(){S.debug("ROUTER: Setting up event handlers for WebSocket client",{clientId:this.clientId,wsClientId:this.wsClient.config?.clientId,eventTypes:Object.values(Tt)}),this.cleanupEventHandlers(),this.boundHandlers.agentControl=this.handleAgentControl.bind(this),this.boundHandlers.sessionDiscovery=this.handleSessionDiscovery.bind(this),this.boundHandlers.sessionHistory=this.handleSessionHistory.bind(this),this.boundHandlers.sessionDelete=this.handleSessionDelete.bind(this),this.wsClient.on(Tt.AGENT_CONTROL,this.boundHandlers.agentControl),this.wsClient.on(Tt.SESSION_DISCOVERY,this.boundHandlers.sessionDiscovery),this.wsClient.on(Tt.SESSION_HISTORY,this.boundHandlers.sessionHistory),this.wsClient.on(Tt.SESSION_DELETE,this.boundHandlers.sessionDelete),S.debug("ROUTER: Message handlers successfully registered on WebSocket client",{registeredTypes:[Tt.AGENT_CONTROL,Tt.SESSION_DISCOVERY,Tt.SESSION_HISTORY,Tt.SESSION_DELETE],clientId:this.clientId,wsClientId:this.wsClient.config?.clientId})}cleanupEventHandlers(){this.boundHandlers.agentControl&&this.wsClient.off(Tt.AGENT_CONTROL,this.boundHandlers.agentControl),this.boundHandlers.sessionDiscovery&&this.wsClient.off(Tt.SESSION_DISCOVERY,this.boundHandlers.sessionDiscovery),this.boundHandlers.sessionHistory&&this.wsClient.off(Tt.SESSION_HISTORY,this.boundHandlers.sessionHistory),this.boundHandlers.sessionDelete&&this.wsClient.off(Tt.SESSION_DELETE,this.boundHandlers.sessionDelete),this.boundHandlers={},S.debug("ROUTER: Cleaned up existing event handlers")}async handleAgentControl(e){let n=e.payload,{control_type:i,parameters:a}=n||{};if(!i||!a){S.error("Invalid agent_control message: missing control_type or parameters");return}let{cli_client_type:o}=a;if(!o){S.error("No cli_client_type specified in agent_control message");return}let l=e.payload?.target_client_id||e.payload?.recipient,p=this.wsClient?.config.clientId;if(S.info("AgentControl message routing",{control_type:i,cli_client_type:o,session_id:a.session_id,message_from:e.client_id,target_client_id:l,our_client_id:p,is_for_us:this.isMessageForUs(e),request_id:e.request_id}),!this.isMessageForUs(e)){S.info(`Message NOT for us - target: ${l}, our: ${p}`);return}S.info(`Message IS for us - processing ${i} for ${o}`);let m=this.handlers.get(o);if(!m){S.error(`No handler registered for cli_client_type: ${o}`),await this.sendErrorResponse(e,`Unsupported CLI client type: ${o}`);return}try{switch(i){case sD.RUN:await m.handleRun(e,n);break;case sD.STOP:await m.handleStop(e,n);break;case sD.RESET:await m.handleReset(e,n);break;default:S.error(`Unknown control_type: ${i}`),await this.sendErrorResponse(e,`Unknown control type: ${i}`)}}catch(A){S.error(`Error handling ${i} for ${o}:`,{error:A}),await this.sendErrorResponse(e,A instanceof Error?A.message:String(A))}}async handleSessionDiscovery(e){S.debug("ROUTER: Session discovery message received",{messageType:e.type,clientId:e.client_id,requestId:e.request_id,hasHandler:!0,hasWsClient:!!this.sessionDiscoveryHandler.wsClient}),await this.sessionDiscoveryHandler.handleSessionDiscovery(e)}async handleSessionHistory(e){await this.sessionDiscoveryHandler.handleSessionHistory(e)}async handleSessionDelete(e){S.debug("\u{1F4E8} SESSION DELETE: Message received in router",{sessionId:e.payload?.session_id,clientId:e.client_id,requestId:e.request_id}),await this.sessionDiscoveryHandler.handleSessionDelete(e)}isMessageForUs(e){let n=e.payload?.target_client_id||e.payload?.recipient,i=this.wsClient?.config.clientId;return!n||n==="all"||n===i}async sendErrorResponse(e,n){let i=e.client_id,a=e.request_id,o=e.payload?.parameters?.session_id||"unknown",l=e.payload?.parameters?.cli_client_type??ho.CUE,p;l===ho.CLAUDE_CODE?p=this.claudeHandler.getBroadcaster():l===ho.CUE&&(p=this.cueHandler.getBroadcaster()),p&&await p.sendSessionUpdate(o,i||"",{content:n,contentType:"text",type:"status",role:"system",uuid:d9e()},a)}},ux=null});var koe={};mi(koe,{handleBackgroundMode:()=>m9e});async function m9e(t){console.log(`\u{1F319} CLI running in background mode (session: ${t.resume||"new-session"})`),console.log(`\u{1F4CD} Working directory: ${process.cwd()}`),console.log(`\u{1F511} Environment check - CUE_API_KEY: ${process.env.CUE_API_KEY?"SET":"MISSING"}`),console.log(`\u{1F511} Environment check - CUE_ACCESS_TOKEN: ${process.env.CUE_ACCESS_TOKEN?"SET":"MISSING"}`),console.log(`\u{1F511} Environment check - ANTHROPIC_API_KEY: ${process.env.ANTHROPIC_API_KEY?"SET":"MISSING"}`),Nae();let e=t.clientId||t.resume;e||(console.error("\u274C No client ID provided - cannot establish WebSocket connection"),process.exit(1));try{console.log("Core modules loaded successfully");let{authService:n}=await FD();console.log(`\u{1F50C} Connecting to WebSocket with client ID: ${e}`),await n.connectWebSocket(e),console.log("Background CLI connected to WebSocket successfully");let i=process.env.ANTHROPIC_API_KEY?await _oe("anthropic"):null;console.log(i?"AI service available for background processing":"\u26A0\uFE0F No AI service - will echo messages only");let a=n.getWebSocketClient();a&&(console.log("\u{1F3A7} Setting up message handlers for background CLI"),S.info("Setting up AgentControlRouter in background mode",{clientId:e,hasWebSocket:!!a}),cx(a,e,n),S.info("CRITICAL: AgentControlRouter initialized in background mode"),console.log("Background CLI ready to process messages")),f9e(),console.log("Background CLI session started. Use Ctrl+C to exit.")}catch(n){console.error("\u274C Background mode startup failed:",n),process.exit(1)}}function f9e(){console.log("\u{1F4CD} Setting up heartbeat interval..."),setInterval(()=>{console.log(`\u{1F493} Background CLI heartbeat - ${new Date().toISOString()}`)},1e4),process.stdin.resume(),console.log("\u{1F4CD} Background mode setup complete, process will stay alive...")}var Ooe=T(()=>{"use strict";YL();Toe();pP();kt()});var Moe=le(px=>{"use strict";var A9e=Symbol.for("react.transitional.element"),h9e=Symbol.for("react.fragment");function Uoe(t,e,n){var i=null;if(n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),"key"in e){n={};for(var a in e)a!=="key"&&(n[a]=e[a])}else n=e;return e=n.ref,{$$typeof:A9e,type:t,key:i,ref:e!==void 0?e:null,props:n}}px.Fragment=h9e;px.jsx=Uoe;px.jsxs=Uoe});var Yoe=le(Zt=>{"use strict";var mP=Symbol.for("react.transitional.element"),g9e=Symbol.for("react.portal"),y9e=Symbol.for("react.fragment"),v9e=Symbol.for("react.strict_mode"),E9e=Symbol.for("react.profiler"),D9e=Symbol.for("react.consumer"),C9e=Symbol.for("react.context"),b9e=Symbol.for("react.forward_ref"),I9e=Symbol.for("react.suspense"),S9e=Symbol.for("react.memo"),Hoe=Symbol.for("react.lazy"),Loe=Symbol.iterator;function x9e(t){return t===null||typeof t!="object"?null:(t=Loe&&t[Loe]||t["@@iterator"],typeof t=="function"?t:null)}var Goe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},qoe=Object.assign,Koe={};function N6(t,e,n){this.props=t,this.context=e,this.refs=Koe,this.updater=n||Goe}N6.prototype.isReactComponent={};N6.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};N6.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Voe(){}Voe.prototype=N6.prototype;function fP(t,e,n){this.props=t,this.context=e,this.refs=Koe,this.updater=n||Goe}var AP=fP.prototype=new Voe;AP.constructor=fP;qoe(AP,N6.prototype);AP.isPureReactComponent=!0;var Poe=Array.isArray,Si={H:null,A:null,T:null,S:null,V:null},Joe=Object.prototype.hasOwnProperty;function hP(t,e,n,i,a,o){return n=o.ref,{$$typeof:mP,type:t,key:e,ref:n!==void 0?n:null,props:o}}function w9e(t,e){return hP(t.type,e,void 0,void 0,void 0,t.props)}function gP(t){return typeof t=="object"&&t!==null&&t.$$typeof===mP}function B9e(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var zoe=/\/+/g;function dP(t,e){return typeof t=="object"&&t!==null&&t.key!=null?B9e(""+t.key):e.toString(36)}function joe(){}function _9e(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(joe,joe):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function F6(t,e,n,i,a){var o=typeof t;(o==="undefined"||o==="boolean")&&(t=null);var l=!1;if(t===null)l=!0;else switch(o){case"bigint":case"string":case"number":l=!0;break;case"object":switch(t.$$typeof){case mP:case g9e:l=!0;break;case Hoe:return l=t._init,F6(l(t._payload),e,n,i,a)}}if(l)return a=a(t),l=i===""?"."+dP(t,0):i,Poe(a)?(n="",l!=null&&(n=l.replace(zoe,"$&/")+"/"),F6(a,e,n,"",function(A){return A})):a!=null&&(gP(a)&&(a=w9e(a,n+(a.key==null||t&&t.key===a.key?"":(""+a.key).replace(zoe,"$&/")+"/")+l)),e.push(a)),1;l=0;var p=i===""?".":i+":";if(Poe(t))for(var m=0;m<t.length;m++)i=t[m],o=p+dP(i,m),l+=F6(i,e,n,o,a);else if(m=x9e(t),typeof m=="function")for(t=m.call(t),m=0;!(i=t.next()).done;)i=i.value,o=p+dP(i,m++),l+=F6(i,e,n,o,a);else if(o==="object"){if(typeof t.then=="function")return F6(_9e(t),e,n,i,a);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return l}function dx(t,e,n){if(t==null)return t;var i=[],a=0;return F6(t,i,"","",function(o){return e.call(n,o,a++)}),i}function T9e(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var $oe=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)};function Q9e(){}Zt.Children={map:dx,forEach:function(t,e,n){dx(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return dx(t,function(){e++}),e},toArray:function(t){return dx(t,function(e){return e})||[]},only:function(t){if(!gP(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};Zt.Component=N6;Zt.Fragment=y9e;Zt.Profiler=E9e;Zt.PureComponent=fP;Zt.StrictMode=v9e;Zt.Suspense=I9e;Zt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Si;Zt.__COMPILER_RUNTIME={__proto__:null,c:function(t){return Si.H.useMemoCache(t)}};Zt.cache=function(t){return function(){return t.apply(null,arguments)}};Zt.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var i=qoe({},t.props),a=t.key,o=void 0;if(e!=null)for(l in e.ref!==void 0&&(o=void 0),e.key!==void 0&&(a=""+e.key),e)!Joe.call(e,l)||l==="key"||l==="__self"||l==="__source"||l==="ref"&&e.ref===void 0||(i[l]=e[l]);var l=arguments.length-2;if(l===1)i.children=n;else if(1<l){for(var p=Array(l),m=0;m<l;m++)p[m]=arguments[m+2];i.children=p}return hP(t.type,a,void 0,void 0,o,i)};Zt.createContext=function(t){return t={$$typeof:C9e,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:D9e,_context:t},t};Zt.createElement=function(t,e,n){var i,a={},o=null;if(e!=null)for(i in e.key!==void 0&&(o=""+e.key),e)Joe.call(e,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(a[i]=e[i]);var l=arguments.length-2;if(l===1)a.children=n;else if(1<l){for(var p=Array(l),m=0;m<l;m++)p[m]=arguments[m+2];a.children=p}if(t&&t.defaultProps)for(i in l=t.defaultProps,l)a[i]===void 0&&(a[i]=l[i]);return hP(t,o,void 0,void 0,null,a)};Zt.createRef=function(){return{current:null}};Zt.forwardRef=function(t){return{$$typeof:b9e,render:t}};Zt.isValidElement=gP;Zt.lazy=function(t){return{$$typeof:Hoe,_payload:{_status:-1,_result:t},_init:T9e}};Zt.memo=function(t,e){return{$$typeof:S9e,type:t,compare:e===void 0?null:e}};Zt.startTransition=function(t){var e=Si.T,n={};Si.T=n;try{var i=t(),a=Si.S;a!==null&&a(n,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(Q9e,$oe)}catch(o){$oe(o)}finally{Si.T=e}};Zt.unstable_useCacheRefresh=function(){return Si.H.useCacheRefresh()};Zt.use=function(t){return Si.H.use(t)};Zt.useActionState=function(t,e,n){return Si.H.useActionState(t,e,n)};Zt.useCallback=function(t,e){return Si.H.useCallback(t,e)};Zt.useContext=function(t){return Si.H.useContext(t)};Zt.useDebugValue=function(){};Zt.useDeferredValue=function(t,e){return Si.H.useDeferredValue(t,e)};Zt.useEffect=function(t,e,n){var i=Si.H;if(typeof n=="function")throw Error("useEffect CRUD overload is not enabled in this build of React.");return i.useEffect(t,e)};Zt.useId=function(){return Si.H.useId()};Zt.useImperativeHandle=function(t,e,n){return Si.H.useImperativeHandle(t,e,n)};Zt.useInsertionEffect=function(t,e){return Si.H.useInsertionEffect(t,e)};Zt.useLayoutEffect=function(t,e){return Si.H.useLayoutEffect(t,e)};Zt.useMemo=function(t,e){return Si.H.useMemo(t,e)};Zt.useOptimistic=function(t,e){return Si.H.useOptimistic(t,e)};Zt.useReducer=function(t,e,n){return Si.H.useReducer(t,e,n)};Zt.useRef=function(t){return Si.H.useRef(t)};Zt.useState=function(t){return Si.H.useState(t)};Zt.useSyncExternalStore=function(t,e,n){return Si.H.useSyncExternalStore(t,e,n)};Zt.useTransition=function(){return Si.H.useTransition()};Zt.version="19.1.1"});var Woe=le((qt,mx)=>{"use strict";process.env.NODE_ENV!=="production"&&(function(){function t(O,ne){Object.defineProperty(i.prototype,O,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",ne[0],ne[1])}})}function e(O){return O===null||typeof O!="object"?null:(O=Me&&O[Me]||O["@@iterator"],typeof O=="function"?O:null)}function n(O,ne){O=(O=O.constructor)&&(O.displayName||O.name)||"ReactClass";var Ne=O+"."+ne;Dt[Ne]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",ne,O),Dt[Ne]=!0)}function i(O,ne,Ne){this.props=O,this.context=ne,this.refs=Ko,this.updater=Ne||xt}function a(){}function o(O,ne,Ne){this.props=O,this.context=ne,this.refs=Ko,this.updater=Ne||xt}function l(O){return""+O}function p(O){try{l(O);var ne=!1}catch{ne=!0}if(ne){ne=console;var Ne=ne.error,je=typeof Symbol=="function"&&Symbol.toStringTag&&O[Symbol.toStringTag]||O.constructor.name||"Object";return Ne.call(ne,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",je),l(O)}}function m(O){if(O==null)return null;if(typeof O=="function")return O.$$typeof===$r?null:O.displayName||O.name||null;if(typeof O=="string")return O;switch(O){case De:return"Fragment";case ge:return"Profiler";case Xe:return"StrictMode";case He:return"Suspense";case Ke:return"SuspenseList";case _e:return"Activity"}if(typeof O=="object")switch(typeof O.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),O.$$typeof){case fe:return"Portal";case at:return(O.displayName||"Context")+".Provider";case Je:return(O._context.displayName||"Context")+".Consumer";case bt:var ne=O.render;return O=O.displayName,O||(O=ne.displayName||ne.name||"",O=O!==""?"ForwardRef("+O+")":"ForwardRef"),O;case Qt:return ne=O.displayName||null,ne!==null?ne:m(O.type)||"Memo";case Yt:ne=O._payload,O=O._init;try{return m(O(ne))}catch{}}return null}function A(O){if(O===De)return"<>";if(typeof O=="object"&&O!==null&&O.$$typeof===Yt)return"<...>";try{var ne=m(O);return ne?"<"+ne+">":"<...>"}catch{return"<...>"}}function g(){var O=dt.A;return O===null?null:O.getOwner()}function E(){return Error("react-stack-top-frame")}function b(O){if(Vo.call(O,"key")){var ne=Object.getOwnPropertyDescriptor(O,"key").get;if(ne&&ne.isReactWarning)return!1}return O.key!==void 0}function D(O,ne){function Ne(){yi||(yi=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",ne))}Ne.isReactWarning=!0,Object.defineProperty(O,"key",{get:Ne,configurable:!0})}function x(){var O=m(this.type);return Hr[O]||(Hr[O]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),O=this.props.ref,O!==void 0?O:null}function w(O,ne,Ne,je,ot,yt,lt,wt){return Ne=yt.ref,O={$$typeof:ve,type:O,key:ne,props:yt,_owner:ot},(Ne!==void 0?Ne:null)!==null?Object.defineProperty(O,"ref",{enumerable:!1,get:x}):Object.defineProperty(O,"ref",{enumerable:!1,value:null}),O._store={},Object.defineProperty(O._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(O,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(O,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:lt}),Object.defineProperty(O,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:wt}),Object.freeze&&(Object.freeze(O.props),Object.freeze(O)),O}function _(O,ne){return ne=w(O.type,ne,void 0,void 0,O._owner,O.props,O._debugStack,O._debugTask),O._store&&(ne._store.validated=O._store.validated),ne}function F(O){return typeof O=="object"&&O!==null&&O.$$typeof===ve}function N(O){var ne={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(Ne){return ne[Ne]})}function M(O,ne){return typeof O=="object"&&O!==null&&O.key!=null?(p(O.key),N(""+O.key)):ne.toString(36)}function z(){}function q(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(z,z):(O.status="pending",O.then(function(ne){O.status==="pending"&&(O.status="fulfilled",O.value=ne)},function(ne){O.status==="pending"&&(O.status="rejected",O.reason=ne)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function ae(O,ne,Ne,je,ot){var yt=typeof O;(yt==="undefined"||yt==="boolean")&&(O=null);var lt=!1;if(O===null)lt=!0;else switch(yt){case"bigint":case"string":case"number":lt=!0;break;case"object":switch(O.$$typeof){case ve:case fe:lt=!0;break;case Yt:return lt=O._init,ae(lt(O._payload),ne,Ne,je,ot)}}if(lt){lt=O,ot=ot(lt);var wt=je===""?"."+M(lt,0):je;return Es(ot)?(Ne="",wt!=null&&(Ne=wt.replace(yr,"$&/")+"/"),ae(ot,ne,Ne,"",function(Wo){return Wo})):ot!=null&&(F(ot)&&(ot.key!=null&&(lt&<.key===ot.key||p(ot.key)),Ne=_(ot,Ne+(ot.key==null||lt&<.key===ot.key?"":(""+ot.key).replace(yr,"$&/")+"/")+wt),je!==""&<!=null&&F(lt)&<.key==null&<._store&&!lt._store.validated&&(Ne._store.validated=2),ot=Ne),ne.push(ot)),1}if(lt=0,wt=je===""?".":je+":",Es(O))for(var At=0;At<O.length;At++)je=O[At],yt=wt+M(je,At),lt+=ae(je,ne,Ne,yt,ot);else if(At=e(O),typeof At=="function")for(At===O.entries&&(Oa||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Oa=!0),O=At.call(O),At=0;!(je=O.next()).done;)je=je.value,yt=wt+M(je,At++),lt+=ae(je,ne,Ne,yt,ot);else if(yt==="object"){if(typeof O.then=="function")return ae(q(O),ne,Ne,je,ot);throw ne=String(O),Error("Objects are not valid as a React child (found: "+(ne==="[object Object]"?"object with keys {"+Object.keys(O).join(", ")+"}":ne)+"). If you meant to render a collection of children, use an array instead.")}return lt}function re(O,ne,Ne){if(O==null)return O;var je=[],ot=0;return ae(O,je,"","",function(yt){return ne.call(Ne,yt,ot++)}),je}function Z(O){if(O._status===-1){var ne=O._result;ne=ne(),ne.then(function(Ne){(O._status===0||O._status===-1)&&(O._status=1,O._result=Ne)},function(Ne){(O._status===0||O._status===-1)&&(O._status=2,O._result=Ne)}),O._status===-1&&(O._status=0,O._result=ne)}if(O._status===1)return ne=O._result,ne===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
341
|
+
`)),this.processStreamMessage(m,g,A.clientId,A.requestId)}else m.type==="system"?this.processStreamMessage(m,g,A.clientId,A.requestId):m.type==="result"&&(S.debug("Message complete, session remains active, waiting for next message",{sessionId:g,result:m.result?.substring(0,100),requestId:A.requestId}),(o||l)&&(o&&!l&&await this.broadcaster.sendAssistantNotification("Claude responded",g,o,A.requestId),this.broadcaster.sendSessionTurnEnd(g,A.clientId||"",{message:o,uuid:p,hasToolCalls:l,tokenUsage:void 0,requestId:A.requestId,clientId:A.clientId,timestamp:new Date().toISOString()},A.requestId)),a=!1,o="",l=!1,p="",this.sendStatus(g,"Ready for next message",A.clientId,A.requestId))}S.info("Stream ended, session closed",{sessionId:i().sessionId||n})}catch(m){let A=i(),g=A.sessionId||n;S.error("Stream processing error",{error:String(m),sessionId:g}),this.broadcaster.sendSessionUpdate(g,A.clientId||"",{content:`Stream error: ${m}`,contentType:"text",type:"status",uuid:Q6()},A.requestId),this.activeStreams.delete(n)}}async handleStop(e){e?(this.activeStreams.has(e)&&(S.debug("Stopping active stream",{sessionId:e}),this.activeStreams.delete(e)),await this.sessionManager.closeSession(e),S.info(`Stopped Claude session: ${e}`)):S.info("Claude Code stop requested without sessionId")}async handleReset(e){e?(this.activeStreams.has(e)&&(S.debug("Stopping active stream for reset",{sessionId:e}),this.activeStreams.delete(e)),await this.sessionManager.closeSession(e),S.info(`Reset Claude session: ${e}`)):S.info("Claude Code reset requested without sessionId")}async handleDelete(e){S.info("\u{1F9F9} CLAUDE DELETE: Starting session cleanup",{sessionId:e,hasActiveStream:this.activeStreams.has(e),activeStreamsCount:this.activeStreams.size}),this.activeStreams.has(e)&&(S.debug("CLAUDE DELETE: Stopping active stream",{sessionId:e}),this.activeStreams.delete(e),S.info("CLAUDE DELETE: Active stream stopped",{sessionId:e})),S.debug("CLAUDE DELETE: Calling manager.deleteSession",{sessionId:e});let n=await this.sessionManager.deleteSession(e,!1);this.sessionRequestContext.delete(e),S.info("CLAUDE DELETE: Completed",{sessionId:e,success:n,remainingStreams:this.activeStreams.size})}setWebSocketClient(e,n){this.clientId=n,this.broadcaster.setWebSocketClient(e,n)}async setupNotifications(e){await this.broadcaster.setupNotifications(e)}getActiveSessions(){return this.sessionManager.getActiveSessions()}getBroadcaster(){return this.broadcaster}}});var rx,Foe=T(()=>{"use strict";kt();rx=class{clientId;broadcaster;sessionListeners=new Map;constructor(e,n){this.clientId=e,this.broadcaster=n}attachToSession(e,n){let i=e.getSessionId?.()||n.sessionId;if(this.sessionListeners.has(i)){S.debug("Event processor already attached to session",{sessionId:i});return}let a=p=>{S.info("CueEventProcessor: Received session event",{eventType:p.type,sessionId:p.sessionId,hasData:!!p.data,dataKeys:p.data?Object.keys(p.data):[]}),p.type==="turn_start"&&S.info("JSONL: turn_start event received",{sessionId:p.sessionId,message:p.data?.message,uuid:p.data?.uuid,cwd:p.data?.cwd}),this.handleStreamingEvent(p,n.senderClientId,n.requestId)},o=p=>{let m=e.getSessionId?.()||n.realSessionId||n.sessionId;S.debug("CueEventProcessor: Received message event",{role:p.role,hasContent:!!p.content,hasToolCalls:!!p.tool_calls,hasToolCallId:!!p.tool_call_id,sessionId:m})};e.on("session-event",a),e.on("session-message",o);let l=()=>{e.off("session-event",a),e.off("session-message",o)};this.sessionListeners.set(i,l),S.info("Event processor attached to session",{sessionId:i})}detachFromSession(e){let n=this.sessionListeners.get(e);n&&(n(),this.sessionListeners.delete(e),S.info("Event processor detached from session",{sessionId:e}))}detachAll(){for(let[e,n]of this.sessionListeners.entries())n();this.sessionListeners.clear(),S.info("Event processor detached from all sessions")}sendStatus(e,n){let i=n.realSessionId||n.sessionId||"";S.debug("Sending status update",{status:e,sessionId:i,clientId:n.senderClientId}),this.broadcaster.sendSessionUpdate(i,n.senderClientId||"",{content:e,contentType:"text",type:"status"},n.requestId)}sendError(e,n){let i=n.realSessionId||n.sessionId||"",a=e instanceof Error?e.message:e;S.error("Sending error update",{error:a,sessionId:i,clientId:n.senderClientId}),this.broadcaster.sendSessionUpdate(i,n.senderClientId||"",{content:`Error: ${a}`,contentType:"text",type:"status"},n.requestId)}async handleStreamingEvent(e,n,i){switch(S.debug("handleStreamingEvent called",{eventType:e.type,sessionId:e.sessionId,targetClientId:n,requestId:i,metadata:{...e.metadata}}),e.type){case"session_start":await this.handleSessionStartEvent(e,n,i);break;case"session_update":await this.handleSessionUpdateEvent(e,n,i);break;case"turn_start":await this.handleTurnStartEvent(e,n,i);break;case"turn_end":await this.handleTurnEndEvent(e,n,i);break}}async handleSessionStartEvent(e,n,i){let a=e.data,o=!a.isNew;S.info("session_start event",{...a,sessionId:e.sessionId,projectId:a.projectId,hasProjectId:!!a.projectId,clientId:this.clientId,targetClientId:n,cwd:a.cwd||"undefined"}),this.broadcaster.sendSessionStart(e.sessionId,n||"",{sessionId:e.sessionId,projectId:a.projectId,clientId:this.clientId,cwd:a.cwd,cliClientType:ho.CUE,messageCount:a.messageCount||0,createdAt:a.createdAt,lastActivityAt:a.lastActivityAt},o,i,a.originalSessionId)}async handleSessionUpdateEvent(e,n,i){let a=e.data;S.debug("handleSessionUpdateEvent: Received update data",{sessionId:e.sessionId,contentType:a.contentType,role:a.role,type:a.type,uuid:a.uuid,messageId:a.messageId,hasContent:!!a.content,contentIsArray:Array.isArray(a.content),contentLength:Array.isArray(a.content)||typeof a.content=="string"?a.content.length:0,contentPreview:typeof a.content=="string"?a.content.substring(0,100):Array.isArray(a.content)?`Array with ${a.content.length} items`:"unknown content type"}),this.broadcaster.sendSessionUpdate(e.sessionId,n||"",{content:a.content,contentType:a.contentType,type:a.type,role:a.role,uuid:a.uuid,messageId:a.messageId},i)}async handleTurnStartEvent(e,n,i){let a=e.data;this.broadcaster.sendSessionTurnStart(e.sessionId,n||"",a,i)}async handleTurnEndEvent(e,n,i){let a=e.data;S.debug("turn_end event received",{sessionId:e.sessionId,hasMessage:!!a.message,messageLength:a.message?.length,hasToolCalls:a.hasToolCalls}),a.message&&!a.hasToolCalls&&(S.info("Sending assistant notification",{sessionId:e.sessionId,messagePreview:a.message.substring(0,50)}),await this.broadcaster.sendAssistantNotification("Cue responded",e.sessionId,a.message,a.requestId)),this.broadcaster.sendSessionTurnEnd(e.sessionId,n||"",a,i)}}});var sx,Noe=T(()=>{"use strict";kt();uP();Foe();sx=class{sessionManager;broadcaster;authService;clientId;currentModel;eventProcessor;constructor(e,n){this.clientId=e,this.broadcaster=new T6("cue"),this.authService=n||u1(),this.sessionManager=new em(10,1440*60*1e3),this.eventProcessor=new rx(this.clientId,this.broadcaster)}async handleRun(e,n){S.info("CueHandler.handleRun - received options",{...n,hasPrompt:!!n.prompt,hasMessage:!!n.message,requestId:e.request_id});let i=this.extractPrompt(n);this.currentModel=n.model;let a={sessionId:n.sessionId||"",realSessionId:null,senderClientId:e.client_id,requestId:e.request_id,cwd:n.cwd,model:n.model,provider:n.provider};S.info("Starting direct Cue session",{...a,promptLength:i.length});let o=await this.createOrGetSession(n,a);this.eventProcessor.attachToSession(o.session,a),!o.isNew&&a.sessionId===o.sessionId&&this.handleExistingSession(o,a),await this.processMessage(o.session,i,o.sessionId,a),S.info("Direct session completed",{sessionId:a.realSessionId||o.sessionId,originalSessionId:a.sessionId,cwd:a.cwd})}extractPrompt(e){let n=e.prompt||e.message;if(!n)throw S.error("No prompt or message provided, throwing error"),new Error("No prompt or message provided");return n}async createOrGetSession(e,n){let i=this.getAuthCredentials(),a=hf(),o=Hv(),l=e.sessionId||o;return S.info("Creating/resuming Cue session",{sessionId:l,fromConfig:!e.sessionId&&!!o,projectId:a,hasProjectId:!!a,cwd:e.cwd,model:e.model,provider:e.provider}),await this.sessionManager.getOrCreateSession(l,{cwd:e.cwd,projectId:a,model:e.model,provider:e.provider,...i,useStreamingRunner:!0,onSessionDetected:p=>this.handleSessionDetected(p,l,n),onMessage:p=>this.handleSessionMessage(p,n),onError:p=>this.handleSessionError(p,n)})}getAuthCredentials(){return{accessToken:this.authService.getAccessToken()||void 0,cueApiKey:this.authService.getCueApiKey()||void 0,anthropicApiKey:this.authService.getAnthropicApiKey()||void 0,openaiApiKey:this.authService.getOpenAIApiKey()||void 0,cueBaseUrl:this.authService.getBaseUrl()||void 0}}handleSessionDetected(e,n,i){n===e?S.info(`\u{1F4C2} Resuming session: ${e}`,{sessionId:e,action:"resume"}):!n?S.info(`\u{1F195} Created new session: ${e}`,{sessionId:e,action:"create"}):S.info("Session ID detected",{sessionId:e,originalId:n,action:"detect"}),i.realSessionId=e;let l=this.determineSessionState(n,e),p=this.createSessionInfo(e,i);this.broadcaster.sendSessionStart(e,i.senderClientId||"",p,n!==void 0,i.requestId,n),i.sessionId=e,this.eventProcessor.sendStatus(l,i)}determineSessionState(e,n){return e?e===n?"Resumed session from memory":"Resumed session from disk":"New session created"}createSessionInfo(e,n){return{sessionId:e,clientId:this.clientId,cwd:n.cwd||process.cwd(),cliClientType:"cue",messageCount:0,createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString()}}handleSessionMessage(e,n){S.info("Received message from CueSession",{role:e.role,hasContent:!!e.content,timestamp:e.timestamp});let i=n.realSessionId||n.sessionId;this.eventProcessor.handleStreamingEvent({type:"session_update",sessionId:i,data:{sessionId:i,content:e.content,contentType:"content_parts",type:"assistant",role:"assistant",messageId:e.id,requestId:n.requestId,clientId:n.senderClientId,isPartial:!e.tokenUsage,model:e.model||this.currentModel},metadata:{callFrom:"handleSessionMessage"}},n.senderClientId,n.requestId)}handleSessionError(e,n){S.error("Session error",{error:e}),this.eventProcessor.sendError(e,n)}handleExistingSession(e,n){n.realSessionId=e.sessionId;let i=e.session.getInfo().messageCount;S.info(`\u{1F4DD} Resuming session ${e.sessionId}`,{sessionId:e.sessionId,loadedMessages:`Loading ${i} messages from history`});let a={sessionId:e.sessionId,clientId:this.clientId,cwd:n.cwd||process.cwd(),cliClientType:"cue",messageCount:i,createdAt:e.session.getInfo().createdAt.toISOString(),lastActivityAt:e.session.getInfo().lastActivityAt.toISOString()};this.broadcaster.sendSessionStart(e.sessionId,n.senderClientId||"",a,!0,n.requestId,n.sessionId),this.eventProcessor.sendStatus("Resumed session from memory",n)}async processMessage(e,n,i,a){a.sessionId=a.realSessionId||i,this.eventProcessor.sendStatus("Processing your message...",a);let o=await e.sendMessage(n);this.eventProcessor.sendStatus("Thinking...",a),await this.processStream(o,a)}async processStream(e,n){try{for await(let i of e)if(S.info("Processing message from stream",{role:i.role,hasContent:!!i.contentBlocks}),i.role==="assistant"){this.eventProcessor.sendStatus("Ready for next message",n);break}}catch(i){S.error("Stream processing error",{error:String(i),sessionId:n.sessionId}),this.eventProcessor.sendError(i instanceof Error?i:`Stream error: ${i}`,n)}}async handleStop(e){e&&(this.eventProcessor.detachFromSession(e),await this.sessionManager.closeSession(e),S.info(`Stopped session: ${e}`))}async handleReset(e,n){n&&(this.eventProcessor.detachFromSession(n),await this.sessionManager.closeSession(n),S.info(`Reset session: ${n}`))}async handleDelete(e){S.info("CUE DELETE: Starting session cleanup",{sessionId:e}),this.eventProcessor.detachFromSession(e),await this.sessionManager.deleteSession(e,!0)}setWebSocketClient(e,n){this.clientId=n,this.broadcaster.setWebSocketClient(e,n)}async setupNotifications(e){await this.broadcaster.setupNotifications(e)}getActiveSessions(){return this.sessionManager.getActiveSessions()}getBroadcaster(){return this.broadcaster}}});var lx,Roe=T(()=>{"use strict";kt();lx=class{wsClient;claudeHandler;cueHandler;constructor(e,n){this.claudeHandler=e,this.cueHandler=n}setWebSocketClient(e){this.wsClient=e,S.debug("SESSION DISCOVERY HANDLER: WebSocket client set",{hasClient:!!e,clientId:e?.config?.clientId})}async handleSessionDiscovery(e){S.debug("SESSION DISCOVERY: Handler called",{messageType:e.type,clientId:e.client_id,requestId:e.request_id,payloadAction:e.payload?.action});let n=e.payload;if(n?.action!=="request"){S.info("SESSION DISCOVERY: Ignoring non-request message",{action:n?.action});return}S.info("SESSION DISCOVERY: Processing request from:",{clientId:e.client_id,requestId:e.request_id});try{let{SessionDiscoveryService:i,getProjectsPathForClientType:a,CLI_CLIENT_TYPES:o}=await Promise.resolve().then(()=>(kt(),Ks)),l=n.cli_client_type||o.CLAUDE_CODE,p=a(l);S.debug("Session discovery using client type:",{clientType:l,projectsPath:p,requestedType:n.cli_client_type});let m=new i(p,l);S.info("SESSION DISCOVERY: Discovering sessions",{limit:n.limit||50,projectsPath:p,clientType:l,ourClientId:this.wsClient?.config.clientId});let A=await m.discoverSessions(n.limit||50,this.wsClient?.config.clientId,l),g=A.map(N=>({...N,status:"inactive"}));S.info("SESSION DISCOVERY: Found cold sessions from disk",{count:A.length,sessionIds:A.slice(0,5).map(N=>N.sessionId)});let E=[];if(this.claudeHandler&&l===o.CLAUDE_CODE)try{let N=this.claudeHandler.getActiveSessions();S.info("SESSION DISCOVERY: Found hot sessions from ClaudeHandler",{count:N.length,sessionIds:N.map(M=>M.sessionId)}),E=N.map(M=>{let z=M.lastActivityAt?new Date(M.lastActivityAt):new Date,re=new Date().getTime()-z.getTime()>3e4;return{sessionId:M.sessionId,clientId:this.wsClient?.config.clientId||"unknown",cwd:M.metadata?.cwd||process.cwd(),cliClientType:o.CLAUDE_CODE,messageCount:M.messageCount,createdAt:M.createdAt.toISOString(),lastActivityAt:M.lastActivityAt.toISOString(),status:re?"idle":"active",ownerClientId:this.wsClient?.config.clientId}})}catch(N){S.warn("Failed to get hot sessions from ClaudeHandler:",{error:String(N)})}else if(this.cueHandler&&l===o.CUE)try{let N=this.cueHandler.getActiveSessions();S.info("SESSION DISCOVERY: Found hot sessions from CueHandler",{count:N.length,sessionIds:N.map(M=>M.sessionId)}),E=N.map(M=>{let z=M.lastActivityAt?new Date(M.lastActivityAt):new Date,re=new Date().getTime()-z.getTime()>3e4;return{sessionId:M.sessionId,clientId:this.wsClient?.config.clientId||"unknown",cwd:M.cwd||process.cwd(),cliClientType:o.CUE,messageCount:M.messageCount||0,createdAt:M.createdAt?new Date(M.createdAt).toISOString():new Date().toISOString(),lastActivityAt:M.lastActivityAt?new Date(M.lastActivityAt).toISOString():new Date().toISOString(),status:re?"idle":"active",ownerClientId:this.wsClient?.config.clientId}})}catch(N){S.warn("Failed to get hot sessions from CueHandler:",{error:String(N)})}let b=new Set(E.map(N=>N.sessionId)),D=g.filter(N=>!b.has(N.sessionId)),x=[...E,...D];x.sort((N,M)=>{let z={active:3,idle:2,inactive:1},q=z[N.status||"inactive"],ae=z[M.status||"inactive"];if(q!==ae)return ae-q;let re=new Date(N.lastActivityAt||N.createdAt||0).getTime();return new Date(M.lastActivityAt||M.createdAt||0).getTime()-re});let w=x.slice(0,n.limit||50);if(S.info("SESSION DISCOVERY: Combined active and inactive sessions",{totalCount:w.length,activeCount:w.filter(N=>N.status==="active").length,idleCount:w.filter(N=>N.status==="idle").length,inactiveCount:w.filter(N=>N.status==="inactive").length,sessionIds:w.slice(0,5).map(N=>`${N.sessionId}(${N.status})`)}),!this.wsClient){S.error("WebSocket client not available for session discovery response");return}let _=w.map(N=>zl(N)),F=e.client_id;S.info("SESSION DISCOVERY: Preparing response",{recipientId:F,ourClientId:this.wsClient.config.clientId,sessionCount:w.length,requestId:e.request_id}),await this.wsClient.send({type:"session_discovery",payload:{action:"response",client_id:this.wsClient.config.clientId,sessions:_,sender:this.wsClient.config.clientId,target_client_id:F},request_id:e.request_id}),S.info("SESSION DISCOVERY: Response sent successfully",{sessionCount:w.length,toClient:F,requestId:e.request_id})}catch(i){S.error("Error handling session discovery request:",{error:i})}}async handleSessionHistory(e){let n=e.payload;if(n?.action!=="request")return;let i=n.session_id,a=n.limit||20,o=n.offset||0;S.debug("Received session history request",{sessionId:i,limit:a,offset:o,clientId:e.client_id,cliClientType:n.cli_client_type,fullPayload:n});try{let{SessionDiscoveryService:l,getProjectsPathForClientType:p,CLI_CLIENT_TYPES:m}=await Promise.resolve().then(()=>(kt(),Ks)),A=n.cli_client_type||m.CLAUDE_CODE,g=p(A);S.debug("Using client type for session history",{clientType:A,projectsPath:g,requestedType:n.cli_client_type});let E=i,D=await new l(g,A).getSessionHistory(E,a,o);if(S.debug("Found session history messages",{sessionId:i,count:D.length}),!this.wsClient){S.error("WebSocket client not available for session history response");return}let x=e.client_id;await this.wsClient.send({type:"session_history",payload:{action:"response",session_id:i,client_id:this.wsClient.config.clientId,messages:D,limit:a,offset:o,sender:this.wsClient.config.clientId,target_client_id:x},request_id:e.request_id}),S.debug("Session history response sent",{messagesCount:D.length})}catch(l){S.error("Error handling session history request:",{error:l,sessionId:i})}}async handleSessionDelete(e){let n=e.payload;if(n?.action!=="request"){S.debug("Ignoring non-request session delete message",{action:n?.action});return}let i=n.session_id;S.info("\u{1F4DD} SESSION DELETE: Request received",{sessionId:i,clientId:e.client_id,requestId:e.request_id});try{let{SessionDiscoveryService:a,getProjectsPathForClientType:o,CLI_CLIENT_TYPES:l}=await Promise.resolve().then(()=>(kt(),Ks)),p=n.cli_client_type||l.CLAUDE_CODE,m=o(p);S.debug("SESSION DELETE: Using project path",{clientType:p,projectsPath:m});let A=i;S.debug("SESSION DELETE: Starting deletion",{actualSessionId:A});let E=await new a(m,p).deleteSession(A);if(S.info("\u{1F5D1}\uFE0F SESSION DELETE: File deletion result",{sessionId:i,actualSessionId:A,success:E,projectsPath:m}),E?p===l.CLAUDE_CODE&&this.claudeHandler?(S.debug("SESSION DELETE: Notifying ClaudeHandler",{actualSessionId:A}),await this.claudeHandler.handleDelete(A),S.info("SESSION DELETE: ClaudeHandler notified",{actualSessionId:A})):p===l.CUE&&this.cueHandler?(S.debug("SESSION DELETE: Notifying CueHandler",{actualSessionId:A}),await this.cueHandler.handleDelete(A),S.info("SESSION DELETE: CueHandler notified",{actualSessionId:A})):S.debug(`SESSION DELETE: No ${p} handler available for cleanup`):S.warn("SESSION DELETE: Failed to delete session file",{sessionId:i,actualSessionId:A}),!this.wsClient){S.error("WebSocket client not available for session delete response");return}let b=e.client_id;await this.wsClient.send({type:"session_delete",payload:{action:"response",session_id:i,client_id:this.wsClient.config.clientId,success:E,sender:this.wsClient.config.clientId,target_client_id:b},request_id:e.request_id}),S.info("\u2705 SESSION DELETE: Response sent",{sessionId:i,success:E,recipientId:b,requestId:e.request_id})}catch(a){if(S.error("Error handling session delete request:",{error:a,sessionId:i}),this.wsClient){let o=e.client_id;await this.wsClient.send({type:"session_delete",payload:{action:"response",session_id:i,client_id:this.wsClient.config.clientId,success:!1,error:a instanceof Error?a.message:String(a),sender:this.wsClient.config.clientId,target_client_id:o},request_id:e.request_id})}}}}});import{randomUUID as d9e}from"crypto";function cx(t,e,n){return ux&&(S.debug("Cleaning up existing AgentControlRouter"),ux.cleanup()),S.debug("Creating new AgentControlRouter instance with all dependencies"),ux=new cP(t,e,n),ux}var cP,ux,pP=T(()=>{"use strict";kt();Qoe();Noe();Roe();cP=class{wsClient;clientId;authService;claudeHandler;cueHandler;sessionDiscoveryHandler;handlers=new Map;boundHandlers={};constructor(e,n,i){if(!e)throw new Error("WebSocketClient is required");if(!n)throw new Error("clientId is required");if(!i)throw new Error("AuthService is required");this.wsClient=e,this.clientId=n,this.authService=i,this.claudeHandler=new ox,this.cueHandler=new sx(this.clientId,this.authService),this.sessionDiscoveryHandler=new lx(this.claudeHandler,this.cueHandler),this.claudeHandler.setWebSocketClient(e,n),this.cueHandler.setWebSocketClient(e,n),this.sessionDiscoveryHandler.setWebSocketClient(e),this.initializeHandlers(),this.setupEventHandler(),this.setupNotifications()}async setupNotifications(){try{await this.claudeHandler.setupNotifications(this.authService),await this.cueHandler.setupNotifications(this.authService),S.debug("AgentControlRouter notifications configured")}catch(e){S.error("Failed to setup notifications",{error:e})}}initializeHandlers(){this.handlers.set(ho.CUE,{handleRun:async(e,n)=>{S.info("ROUTER: Calling CueHandler with parameters:",{message:n.parameters.message,prompt:n.parameters.prompt,sessionId:n.parameters.session_id,cwd:n.parameters.cwd,model:n.parameters.model,provider:n.parameters.provider,useStreaming:n.parameters.use_streaming,hasMessage:!!n.parameters.message,hasPrompt:!!n.parameters.prompt,rawPayload:n.parameters});let i={message:n.parameters.message,prompt:n.parameters.prompt,sessionId:n.parameters.session_id,cwd:n.parameters.cwd,model:n.parameters.model,provider:n.parameters.provider,useStreaming:n.parameters.use_streaming??!0};S.info("ROUTER: CueOptions object before calling handler:",i),await this.cueHandler.handleRun(e,i)},handleStop:async(e,n)=>{await this.cueHandler.handleStop(n.parameters.session_id)},handleReset:async(e,n)=>{await this.cueHandler.handleReset(e,n.parameters.session_id)}}),this.handlers.set(ho.CLAUDE_CODE,{handleRun:async(e,n)=>{let i=n.parameters.prompt||n.parameters.message;if(!i){await this.sendErrorResponse(e,"No prompt provided");return}n.parameters.use_streaming?S.info("STREAMING MODE ENABLED for Claude Code",{sessionId:n.parameters.session_id,cwd:n.parameters.cwd,fromClient:e.client_id,requestId:e.request_id}):S.info("Regular mode for Claude Code (no streaming)",{sessionId:n.parameters.session_id});try{await this.claudeHandler.handleRun(e,{prompt:i,sessionId:n.parameters.session_id,cwd:n.parameters.cwd,useStreaming:n.parameters.use_streaming})}catch(a){let o=a instanceof Error?a.message:String(a);await this.sendErrorResponse(e,o)}},handleStop:async(e,n)=>{await this.claudeHandler.handleStop(n.parameters.session_id)},handleReset:async(e,n)=>{await this.claudeHandler.handleReset(n.parameters.session_id)}})}cleanup(){S.debug("ROUTER: Cleaning up AgentControlRouter"),this.cleanupEventHandlers()}setupEventHandler(){S.debug("ROUTER: Setting up event handlers for WebSocket client",{clientId:this.clientId,wsClientId:this.wsClient.config?.clientId,eventTypes:Object.values(Tt)}),this.cleanupEventHandlers(),this.boundHandlers.agentControl=this.handleAgentControl.bind(this),this.boundHandlers.sessionDiscovery=this.handleSessionDiscovery.bind(this),this.boundHandlers.sessionHistory=this.handleSessionHistory.bind(this),this.boundHandlers.sessionDelete=this.handleSessionDelete.bind(this),this.wsClient.on(Tt.AGENT_CONTROL,this.boundHandlers.agentControl),this.wsClient.on(Tt.SESSION_DISCOVERY,this.boundHandlers.sessionDiscovery),this.wsClient.on(Tt.SESSION_HISTORY,this.boundHandlers.sessionHistory),this.wsClient.on(Tt.SESSION_DELETE,this.boundHandlers.sessionDelete),S.debug("ROUTER: Message handlers successfully registered on WebSocket client",{registeredTypes:[Tt.AGENT_CONTROL,Tt.SESSION_DISCOVERY,Tt.SESSION_HISTORY,Tt.SESSION_DELETE],clientId:this.clientId,wsClientId:this.wsClient.config?.clientId})}cleanupEventHandlers(){this.boundHandlers.agentControl&&this.wsClient.off(Tt.AGENT_CONTROL,this.boundHandlers.agentControl),this.boundHandlers.sessionDiscovery&&this.wsClient.off(Tt.SESSION_DISCOVERY,this.boundHandlers.sessionDiscovery),this.boundHandlers.sessionHistory&&this.wsClient.off(Tt.SESSION_HISTORY,this.boundHandlers.sessionHistory),this.boundHandlers.sessionDelete&&this.wsClient.off(Tt.SESSION_DELETE,this.boundHandlers.sessionDelete),this.boundHandlers={},S.debug("ROUTER: Cleaned up existing event handlers")}async handleAgentControl(e){let n=e.payload,{control_type:i,parameters:a}=n||{};if(!i||!a){S.error("Invalid agent_control message: missing control_type or parameters");return}let{cli_client_type:o}=a;if(!o){S.error("No cli_client_type specified in agent_control message");return}let l=e.payload?.target_client_id||e.payload?.recipient,p=this.wsClient?.config.clientId;if(S.info("AgentControl message routing",{control_type:i,cli_client_type:o,session_id:a.session_id,message_from:e.client_id,target_client_id:l,our_client_id:p,is_for_us:this.isMessageForUs(e),request_id:e.request_id}),!this.isMessageForUs(e)){S.info(`Message NOT for us - target: ${l}, our: ${p}`);return}S.info(`Message IS for us - processing ${i} for ${o}`);let m=this.handlers.get(o);if(!m){S.error(`No handler registered for cli_client_type: ${o}`),await this.sendErrorResponse(e,`Unsupported CLI client type: ${o}`);return}try{switch(i){case sD.RUN:await m.handleRun(e,n);break;case sD.STOP:await m.handleStop(e,n);break;case sD.RESET:await m.handleReset(e,n);break;default:S.error(`Unknown control_type: ${i}`),await this.sendErrorResponse(e,`Unknown control type: ${i}`)}}catch(A){S.error(`Error handling ${i} for ${o}:`,{error:A}),await this.sendErrorResponse(e,A instanceof Error?A.message:String(A))}}async handleSessionDiscovery(e){S.debug("ROUTER: Session discovery message received",{messageType:e.type,clientId:e.client_id,requestId:e.request_id,hasHandler:!0,hasWsClient:!!this.sessionDiscoveryHandler.wsClient}),await this.sessionDiscoveryHandler.handleSessionDiscovery(e)}async handleSessionHistory(e){await this.sessionDiscoveryHandler.handleSessionHistory(e)}async handleSessionDelete(e){S.debug("\u{1F4E8} SESSION DELETE: Message received in router",{sessionId:e.payload?.session_id,clientId:e.client_id,requestId:e.request_id}),await this.sessionDiscoveryHandler.handleSessionDelete(e)}isMessageForUs(e){let n=e.payload?.target_client_id||e.payload?.recipient,i=this.wsClient?.config.clientId;return!n||n==="all"||n===i}async sendErrorResponse(e,n){let i=e.client_id,a=e.request_id,o=e.payload?.parameters?.session_id||"unknown",l=e.payload?.parameters?.cli_client_type??ho.CUE,p;l===ho.CLAUDE_CODE?p=this.claudeHandler.getBroadcaster():l===ho.CUE&&(p=this.cueHandler.getBroadcaster()),p&&await p.sendSessionUpdate(o,i||"",{content:n,contentType:"text",type:"status",role:"system",uuid:d9e()},a)}},ux=null});var koe={};mi(koe,{handleBackgroundMode:()=>m9e});async function m9e(t){console.log(`\u{1F319} CLI running in background mode (session: ${t.resume||"new-session"})`),console.log(`\u{1F4CD} Working directory: ${process.cwd()}`),console.log(`\u{1F511} Environment check - CUE_API_KEY: ${process.env.CUE_API_KEY?"SET":"MISSING"}`),console.log(`\u{1F511} Environment check - CUE_ACCESS_TOKEN: ${process.env.CUE_ACCESS_TOKEN?"SET":"MISSING"}`),console.log(`\u{1F511} Environment check - ANTHROPIC_API_KEY: ${process.env.ANTHROPIC_API_KEY?"SET":"MISSING"}`),Nae();let e=t.clientId||t.resume;e||(console.error("\u274C No client ID provided - cannot establish WebSocket connection"),process.exit(1));try{console.log("Core modules loaded successfully");let{authService:n}=await FD();console.log(`\u{1F50C} Connecting to WebSocket with client ID: ${e}`),await n.connectWebSocket(e),console.log("Background CLI connected to WebSocket successfully");let i=process.env.ANTHROPIC_API_KEY?await _oe("anthropic"):null;console.log(i?"AI service available for background processing":"\u26A0\uFE0F No AI service - will echo messages only");let a=n.getWebSocketClient();a&&(console.log("\u{1F3A7} Setting up message handlers for background CLI"),S.info("Setting up AgentControlRouter in background mode",{clientId:e,hasWebSocket:!!a}),cx(a,e,n),S.info("CRITICAL: AgentControlRouter initialized in background mode"),console.log("Background CLI ready to process messages")),f9e(),console.log("Background CLI session started. Use Ctrl+C to exit.")}catch(n){console.error("\u274C Background mode startup failed:",n),process.exit(1)}}function f9e(){console.log("\u{1F4CD} Setting up heartbeat interval..."),setInterval(()=>{console.log(`\u{1F493} Background CLI heartbeat - ${new Date().toISOString()}`)},1e4),process.stdin.resume(),console.log("\u{1F4CD} Background mode setup complete, process will stay alive...")}var Ooe=T(()=>{"use strict";YL();Toe();pP();kt()});var Moe=le(px=>{"use strict";var A9e=Symbol.for("react.transitional.element"),h9e=Symbol.for("react.fragment");function Uoe(t,e,n){var i=null;if(n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),"key"in e){n={};for(var a in e)a!=="key"&&(n[a]=e[a])}else n=e;return e=n.ref,{$$typeof:A9e,type:t,key:i,ref:e!==void 0?e:null,props:n}}px.Fragment=h9e;px.jsx=Uoe;px.jsxs=Uoe});var Yoe=le(Zt=>{"use strict";var mP=Symbol.for("react.transitional.element"),g9e=Symbol.for("react.portal"),y9e=Symbol.for("react.fragment"),v9e=Symbol.for("react.strict_mode"),E9e=Symbol.for("react.profiler"),D9e=Symbol.for("react.consumer"),C9e=Symbol.for("react.context"),b9e=Symbol.for("react.forward_ref"),I9e=Symbol.for("react.suspense"),S9e=Symbol.for("react.memo"),Hoe=Symbol.for("react.lazy"),Loe=Symbol.iterator;function x9e(t){return t===null||typeof t!="object"?null:(t=Loe&&t[Loe]||t["@@iterator"],typeof t=="function"?t:null)}var Goe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},qoe=Object.assign,Koe={};function N6(t,e,n){this.props=t,this.context=e,this.refs=Koe,this.updater=n||Goe}N6.prototype.isReactComponent={};N6.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};N6.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Voe(){}Voe.prototype=N6.prototype;function fP(t,e,n){this.props=t,this.context=e,this.refs=Koe,this.updater=n||Goe}var AP=fP.prototype=new Voe;AP.constructor=fP;qoe(AP,N6.prototype);AP.isPureReactComponent=!0;var Poe=Array.isArray,Si={H:null,A:null,T:null,S:null,V:null},Joe=Object.prototype.hasOwnProperty;function hP(t,e,n,i,a,o){return n=o.ref,{$$typeof:mP,type:t,key:e,ref:n!==void 0?n:null,props:o}}function w9e(t,e){return hP(t.type,e,void 0,void 0,void 0,t.props)}function gP(t){return typeof t=="object"&&t!==null&&t.$$typeof===mP}function B9e(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var zoe=/\/+/g;function dP(t,e){return typeof t=="object"&&t!==null&&t.key!=null?B9e(""+t.key):e.toString(36)}function joe(){}function _9e(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(joe,joe):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function F6(t,e,n,i,a){var o=typeof t;(o==="undefined"||o==="boolean")&&(t=null);var l=!1;if(t===null)l=!0;else switch(o){case"bigint":case"string":case"number":l=!0;break;case"object":switch(t.$$typeof){case mP:case g9e:l=!0;break;case Hoe:return l=t._init,F6(l(t._payload),e,n,i,a)}}if(l)return a=a(t),l=i===""?"."+dP(t,0):i,Poe(a)?(n="",l!=null&&(n=l.replace(zoe,"$&/")+"/"),F6(a,e,n,"",function(A){return A})):a!=null&&(gP(a)&&(a=w9e(a,n+(a.key==null||t&&t.key===a.key?"":(""+a.key).replace(zoe,"$&/")+"/")+l)),e.push(a)),1;l=0;var p=i===""?".":i+":";if(Poe(t))for(var m=0;m<t.length;m++)i=t[m],o=p+dP(i,m),l+=F6(i,e,n,o,a);else if(m=x9e(t),typeof m=="function")for(t=m.call(t),m=0;!(i=t.next()).done;)i=i.value,o=p+dP(i,m++),l+=F6(i,e,n,o,a);else if(o==="object"){if(typeof t.then=="function")return F6(_9e(t),e,n,i,a);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return l}function dx(t,e,n){if(t==null)return t;var i=[],a=0;return F6(t,i,"","",function(o){return e.call(n,o,a++)}),i}function T9e(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var $oe=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)};function Q9e(){}Zt.Children={map:dx,forEach:function(t,e,n){dx(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return dx(t,function(){e++}),e},toArray:function(t){return dx(t,function(e){return e})||[]},only:function(t){if(!gP(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};Zt.Component=N6;Zt.Fragment=y9e;Zt.Profiler=E9e;Zt.PureComponent=fP;Zt.StrictMode=v9e;Zt.Suspense=I9e;Zt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Si;Zt.__COMPILER_RUNTIME={__proto__:null,c:function(t){return Si.H.useMemoCache(t)}};Zt.cache=function(t){return function(){return t.apply(null,arguments)}};Zt.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var i=qoe({},t.props),a=t.key,o=void 0;if(e!=null)for(l in e.ref!==void 0&&(o=void 0),e.key!==void 0&&(a=""+e.key),e)!Joe.call(e,l)||l==="key"||l==="__self"||l==="__source"||l==="ref"&&e.ref===void 0||(i[l]=e[l]);var l=arguments.length-2;if(l===1)i.children=n;else if(1<l){for(var p=Array(l),m=0;m<l;m++)p[m]=arguments[m+2];i.children=p}return hP(t.type,a,void 0,void 0,o,i)};Zt.createContext=function(t){return t={$$typeof:C9e,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:D9e,_context:t},t};Zt.createElement=function(t,e,n){var i,a={},o=null;if(e!=null)for(i in e.key!==void 0&&(o=""+e.key),e)Joe.call(e,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(a[i]=e[i]);var l=arguments.length-2;if(l===1)a.children=n;else if(1<l){for(var p=Array(l),m=0;m<l;m++)p[m]=arguments[m+2];a.children=p}if(t&&t.defaultProps)for(i in l=t.defaultProps,l)a[i]===void 0&&(a[i]=l[i]);return hP(t,o,void 0,void 0,null,a)};Zt.createRef=function(){return{current:null}};Zt.forwardRef=function(t){return{$$typeof:b9e,render:t}};Zt.isValidElement=gP;Zt.lazy=function(t){return{$$typeof:Hoe,_payload:{_status:-1,_result:t},_init:T9e}};Zt.memo=function(t,e){return{$$typeof:S9e,type:t,compare:e===void 0?null:e}};Zt.startTransition=function(t){var e=Si.T,n={};Si.T=n;try{var i=t(),a=Si.S;a!==null&&a(n,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(Q9e,$oe)}catch(o){$oe(o)}finally{Si.T=e}};Zt.unstable_useCacheRefresh=function(){return Si.H.useCacheRefresh()};Zt.use=function(t){return Si.H.use(t)};Zt.useActionState=function(t,e,n){return Si.H.useActionState(t,e,n)};Zt.useCallback=function(t,e){return Si.H.useCallback(t,e)};Zt.useContext=function(t){return Si.H.useContext(t)};Zt.useDebugValue=function(){};Zt.useDeferredValue=function(t,e){return Si.H.useDeferredValue(t,e)};Zt.useEffect=function(t,e,n){var i=Si.H;if(typeof n=="function")throw Error("useEffect CRUD overload is not enabled in this build of React.");return i.useEffect(t,e)};Zt.useId=function(){return Si.H.useId()};Zt.useImperativeHandle=function(t,e,n){return Si.H.useImperativeHandle(t,e,n)};Zt.useInsertionEffect=function(t,e){return Si.H.useInsertionEffect(t,e)};Zt.useLayoutEffect=function(t,e){return Si.H.useLayoutEffect(t,e)};Zt.useMemo=function(t,e){return Si.H.useMemo(t,e)};Zt.useOptimistic=function(t,e){return Si.H.useOptimistic(t,e)};Zt.useReducer=function(t,e,n){return Si.H.useReducer(t,e,n)};Zt.useRef=function(t){return Si.H.useRef(t)};Zt.useState=function(t){return Si.H.useState(t)};Zt.useSyncExternalStore=function(t,e,n){return Si.H.useSyncExternalStore(t,e,n)};Zt.useTransition=function(){return Si.H.useTransition()};Zt.version="19.1.1"});var Woe=le((qt,mx)=>{"use strict";process.env.NODE_ENV!=="production"&&(function(){function t(O,ne){Object.defineProperty(i.prototype,O,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",ne[0],ne[1])}})}function e(O){return O===null||typeof O!="object"?null:(O=Me&&O[Me]||O["@@iterator"],typeof O=="function"?O:null)}function n(O,ne){O=(O=O.constructor)&&(O.displayName||O.name)||"ReactClass";var Ne=O+"."+ne;Dt[Ne]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",ne,O),Dt[Ne]=!0)}function i(O,ne,Ne){this.props=O,this.context=ne,this.refs=Ko,this.updater=Ne||xt}function a(){}function o(O,ne,Ne){this.props=O,this.context=ne,this.refs=Ko,this.updater=Ne||xt}function l(O){return""+O}function p(O){try{l(O);var ne=!1}catch{ne=!0}if(ne){ne=console;var Ne=ne.error,je=typeof Symbol=="function"&&Symbol.toStringTag&&O[Symbol.toStringTag]||O.constructor.name||"Object";return Ne.call(ne,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",je),l(O)}}function m(O){if(O==null)return null;if(typeof O=="function")return O.$$typeof===$r?null:O.displayName||O.name||null;if(typeof O=="string")return O;switch(O){case De:return"Fragment";case ge:return"Profiler";case Xe:return"StrictMode";case He:return"Suspense";case Ke:return"SuspenseList";case _e:return"Activity"}if(typeof O=="object")switch(typeof O.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),O.$$typeof){case fe:return"Portal";case at:return(O.displayName||"Context")+".Provider";case Je:return(O._context.displayName||"Context")+".Consumer";case bt:var ne=O.render;return O=O.displayName,O||(O=ne.displayName||ne.name||"",O=O!==""?"ForwardRef("+O+")":"ForwardRef"),O;case Qt:return ne=O.displayName||null,ne!==null?ne:m(O.type)||"Memo";case Yt:ne=O._payload,O=O._init;try{return m(O(ne))}catch{}}return null}function A(O){if(O===De)return"<>";if(typeof O=="object"&&O!==null&&O.$$typeof===Yt)return"<...>";try{var ne=m(O);return ne?"<"+ne+">":"<...>"}catch{return"<...>"}}function g(){var O=dt.A;return O===null?null:O.getOwner()}function E(){return Error("react-stack-top-frame")}function b(O){if(Vo.call(O,"key")){var ne=Object.getOwnPropertyDescriptor(O,"key").get;if(ne&&ne.isReactWarning)return!1}return O.key!==void 0}function D(O,ne){function Ne(){yi||(yi=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",ne))}Ne.isReactWarning=!0,Object.defineProperty(O,"key",{get:Ne,configurable:!0})}function x(){var O=m(this.type);return Hr[O]||(Hr[O]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),O=this.props.ref,O!==void 0?O:null}function w(O,ne,Ne,je,ot,yt,lt,wt){return Ne=yt.ref,O={$$typeof:ve,type:O,key:ne,props:yt,_owner:ot},(Ne!==void 0?Ne:null)!==null?Object.defineProperty(O,"ref",{enumerable:!1,get:x}):Object.defineProperty(O,"ref",{enumerable:!1,value:null}),O._store={},Object.defineProperty(O._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(O,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(O,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:lt}),Object.defineProperty(O,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:wt}),Object.freeze&&(Object.freeze(O.props),Object.freeze(O)),O}function _(O,ne){return ne=w(O.type,ne,void 0,void 0,O._owner,O.props,O._debugStack,O._debugTask),O._store&&(ne._store.validated=O._store.validated),ne}function F(O){return typeof O=="object"&&O!==null&&O.$$typeof===ve}function N(O){var ne={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(Ne){return ne[Ne]})}function M(O,ne){return typeof O=="object"&&O!==null&&O.key!=null?(p(O.key),N(""+O.key)):ne.toString(36)}function z(){}function q(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(z,z):(O.status="pending",O.then(function(ne){O.status==="pending"&&(O.status="fulfilled",O.value=ne)},function(ne){O.status==="pending"&&(O.status="rejected",O.reason=ne)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function ae(O,ne,Ne,je,ot){var yt=typeof O;(yt==="undefined"||yt==="boolean")&&(O=null);var lt=!1;if(O===null)lt=!0;else switch(yt){case"bigint":case"string":case"number":lt=!0;break;case"object":switch(O.$$typeof){case ve:case fe:lt=!0;break;case Yt:return lt=O._init,ae(lt(O._payload),ne,Ne,je,ot)}}if(lt){lt=O,ot=ot(lt);var wt=je===""?"."+M(lt,0):je;return Es(ot)?(Ne="",wt!=null&&(Ne=wt.replace(yr,"$&/")+"/"),ae(ot,ne,Ne,"",function(Wo){return Wo})):ot!=null&&(F(ot)&&(ot.key!=null&&(lt&<.key===ot.key||p(ot.key)),Ne=_(ot,Ne+(ot.key==null||lt&<.key===ot.key?"":(""+ot.key).replace(yr,"$&/")+"/")+wt),je!==""&<!=null&&F(lt)&<.key==null&<._store&&!lt._store.validated&&(Ne._store.validated=2),ot=Ne),ne.push(ot)),1}if(lt=0,wt=je===""?".":je+":",Es(O))for(var At=0;At<O.length;At++)je=O[At],yt=wt+M(je,At),lt+=ae(je,ne,Ne,yt,ot);else if(At=e(O),typeof At=="function")for(At===O.entries&&(Oa||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Oa=!0),O=At.call(O),At=0;!(je=O.next()).done;)je=je.value,yt=wt+M(je,At++),lt+=ae(je,ne,Ne,yt,ot);else if(yt==="object"){if(typeof O.then=="function")return ae(q(O),ne,Ne,je,ot);throw ne=String(O),Error("Objects are not valid as a React child (found: "+(ne==="[object Object]"?"object with keys {"+Object.keys(O).join(", ")+"}":ne)+"). If you meant to render a collection of children, use an array instead.")}return lt}function re(O,ne,Ne){if(O==null)return O;var je=[],ot=0;return ae(O,je,"","",function(yt){return ne.call(Ne,yt,ot++)}),je}function Z(O){if(O._status===-1){var ne=O._result;ne=ne(),ne.then(function(Ne){(O._status===0||O._status===-1)&&(O._status=1,O._result=Ne)},function(Ne){(O._status===0||O._status===-1)&&(O._status=2,O._result=Ne)}),O._status===-1&&(O._status=0,O._result=ne)}if(O._status===1)return ne=O._result,ne===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
342
342
|
|
|
343
343
|
Your code should look like:
|
|
344
344
|
const MyComponent = lazy(() => import('./MyComponent'))
|