@embedder/embedder 2.0.37 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -863,4 +863,4 @@ class iT{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){retu
863
863
  * See the License for the specific language governing permissions and
864
864
  * limitations under the License.
865
865
  */
866
- fN.initialize(fetch,Headers,Response),tT="Node",RQ(new _x("auth",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal"),{apiKey:o,authDomain:s}=n.options;lN(o&&!o.includes(":"),"invalid-api-key",{appName:n.name});const a={apiKey:o,authDomain:s,clientPlatform:tT,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:zN(tT)},l=new WN(n,r,i,a);return function(e,t){const n=t?.persistence||[],r=(Array.isArray(n)?n:[n]).map(ON);t?.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,t?.popupRedirectResolver)}(l,t),l},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider("auth-internal").initialize()})),RQ(new _x("auth-internal",e=>{const t=qN(e.getProvider("auth").getImmediate());return new iT(t)},"PRIVATE").setInstantiationMode("EXPLICIT")),jQ(nT,rT,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(tT)),jQ(nT,rT,"esm2020"),iN("operation-not-supported-in-this-environment"),WN.prototype.setPersistence=async()=>{};const oT={apiKey:"AIzaSyDuNXvHd-GvTrmXG6_2TnrfqRWo-ApPd3s",authDomain:"app.embedder.dev",projectId:"embedder-dev",storageBucket:"embedder-dev.firebasestorage.app",messagingSenderId:"547074918538",appId:"1:547074918538:web:b5495d2347046fd29e8573",measurementId:"G-4KT5CW28KM"},sT=function(e=function(e=SQ){const t=xQ.get(e);if(!t&&e===SQ&&ux())return PQ();if(!t)throw OQ.create("no-app",{appName:e});return t}()){const t=FQ(e,"auth");if(t.isInitialized())return t.getImmediate();const n=function(e,t){const n=FQ(e,"auth");if(n.isInitialized()){const e=n.getImmediate();if(bx(n.getOptions(),{}))return e;rN(e,"already-initialized")}return n.initialize({options:t})}(e),r=(i="auth",lx()?.emulatorHosts?.[i]);var i;return r&&KN(n,`http://${r}`),n}(PQ(oT)),aT=le(H(),".embedder"),lT=le(aT,"creds.enc"),uT=le(aT,"model.json"),cT=le(aT,"workspace-cache.json"),dT=Ae("justs0m3s4f3ty","salt",32),pT=e=>{if(null===e)return void(K(lT)&&Z(lT));K(aT)||Y(aT,{recursive:!0}),e={...e,user:{...e.user,auth:{config:oT}}};const t=ye(16),n=be("aes-256-gcm",dT,t),r=Buffer.concat([n.update(JSON.stringify(e),"utf8"),n.final()]);X(lT,Buffer.concat([t,n.getAuthTag(),r]))},fT=()=>{if(!K(lT))return null;const e=V(lT),t=e.subarray(0,16),n=e.subarray(16,32),r=e.subarray(32),i=me("aes-256-gcm",dT,t);i.setAuthTag(n);return JSON.parse(Buffer.concat([i.update(r),i.final()]).toString())},hT=e=>{K(aT)||Y(aT,{recursive:!0}),null!==e?X(uT,JSON.stringify(e)):K(uT)&&Z(uT)},gT=(e,t,n)=>{K(aT)||Y(aT,{recursive:!0});let r={};if(K(cT))try{const e=V(cT,"utf8");r=JSON.parse(e)}catch{r={}}r[e]={teamId:t,projectId:n},X(cT,JSON.stringify(r,null,2))};function AT(){return"https://backend-service-prod.embedder.dev"}function mT(){return{}}const yT=kw((e,t)=>({apiFetch:null,sessionId:null,setApiFetch:t=>{e({apiFetch:t})},getApiFetch:()=>t().apiFetch,setSessionId:t=>{e({sessionId:t})},getSessionId:()=>t().sessionId}));function bT(){return process.cwd()}function vT(e=process.cwd()){const t=kT(e),n=J.existsSync(ae.join(e,"package.json")),r=J.existsSync(ae.join(e,"EMBEDDER.md"))||J.existsSync(ae.join(e,"embedder.md"));let i="generic";return t&&n?i="npm":t?i="git":(r||function(e){const t=["Makefile","CMakeLists.txt","*.ino","*.ioc","platformio.ini"],n=[".c",".h",".cpp",".hpp",".asm",".s"];try{const r=J.readdirSync(e);for(const e of t)if(e.includes("*")){const t=e.replace("*","");if(r.some(e=>e.includes(t)))return!0}else if(r.includes(e))return!0;return r.filter(e=>{const t=ae.extname(e).toLowerCase();return n.includes(t)}).length>=2}catch{return!1}}(e))&&(i="embedded"),{isGitRepository:t,hasPackageJson:n,hasEmbedderMd:r,projectType:i,rootDirectory:e}}const ET={maxDepth:3,maxItems:200,showHidden:!1,respectGitIgnore:!0,respectEmbedderIgnore:!0},IT=["node_modules",".git",".vscode",".idea","dist","build","out",".next",".cache","coverage",".nyc_output","logs","*.log",".DS_Store","Thumbs.db"],wT="...";function CT(e,t,n){if(!n.showHidden&&t.startsWith(".")){if(![".gitignore",".embedderignore",".env.example"].includes(t))return!0}for(const r of IT)if(r.includes("*")){if(new RegExp(r.replace(/\*/g,".*")).test(t))return!0}else if(t===r)return!0;return!1}function _T(e,t,n,r,i){const o=n?"└───":"├───";r&&!e.isIgnored||i.push(`${t}${o}${e.name}${ae.sep}${e.isIgnored?wT:""}`);const s=r?"":t+(n?" ":"│ "),a=e.files.length;for(let u=0;u<a;u++){const t=u===a-1&&0===e.subFolders.length&&!e.hasMoreSubfolders?"└───":"├───";i.push(`${s}${t}${e.files[u]}`)}if(e.hasMoreFiles){const t=0===e.subFolders.length&&!e.hasMoreSubfolders?"└───":"├───";i.push(`${s}${t}${wT}`)}const l=e.subFolders.length;for(let u=0;u<l;u++){const t=e.subFolders[u];if(!t)continue;_T(t,s,u===l-1&&!e.hasMoreSubfolders,!1,i)}e.hasMoreSubfolders&&i.push(`${s}└───${wT}`)}function BT(e){if(e.hasMoreFiles||e.hasMoreSubfolders||e.isIgnored)return!0;for(const t of e.subFolders)if(BT(t))return!0;return!1}function DT(e=process.cwd(),t={}){const n={...ET,...t};try{const t=ae.resolve(e);if(!J.statSync(t).isDirectory())return`Error: ${e} is not a directory`;const r=function(e,t){const n={name:ae.basename(e),path:e,files:[],subFolders:[],totalChildren:0,totalFiles:0},r=[{folderInfo:n,currentPath:e,depth:0}];let i=0;const o=new Set;for(;r.length>0;){const e=r.shift();if(!e)break;const{folderInfo:n,currentPath:s,depth:a}=e;if(o.has(s)||a>=t.maxDepth)continue;if(o.add(s),i>=t.maxItems)continue;let l;try{l=J.readdirSync(s,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))}catch(qK){continue}const u=[],c=[];for(const r of l)if(r.isFile()){if(i>=t.maxItems){n.hasMoreFiles=!0;break}const e=r.name;if(ae.join(s,e),CT(0,e,t))continue;u.push(e),i++,n.totalFiles++,n.totalChildren++}n.files=u;for(const o of l)if(o.isDirectory()){if(i>=t.maxItems){n.hasMoreSubfolders=!0;break}const e=o.name,l=ae.join(s,e);if(CT(0,e,t)){const t={name:e,path:l,files:[],subFolders:[],totalChildren:0,totalFiles:0,isIgnored:!0};c.push(t),i++,n.totalChildren++;continue}const u={name:e,path:l,files:[],subFolders:[],totalChildren:0,totalFiles:0};c.push(u),i++,n.totalChildren++,r.push({folderInfo:u,currentPath:l,depth:a+1})}n.subFolders=c}return n}(t,n);if(!r)return`Error: Could not read directory "${t}". Check path and permissions.`;const i=[];_T(r,"",!0,!0,i);let o=`Showing up to ${n.maxItems} items (files + folders).`;return BT(r)&&(o+=` Folders or files indicated with ${wT} contain more items not shown, were ignored, or the display limit (${n.maxItems} items) was reached.`),`${o}\n\n${t}${ae.sep}\n${i.join("\n")}`}catch(qK){return`Error reading directory ${e}: ${qK instanceof Error?qK.message:String(qK)}`}}const ST=kw((e,t)=>({cachedContext:null,cacheExpiry:0,CACHE_DURATION:3e4,getEnvironmentContext:async(n=!1)=>{const r=t(),i=Date.now();if(!n&&r.cachedContext&&i<r.cacheExpiry)return r.cachedContext;const o=bT(),s=function(){const e=process.platform;return{platform:e,arch:process.arch,version:process.version,isWindows:"win32"===e,isMacOS:"darwin"===e,isLinux:"linux"===e}}(),a=function(){const e=new Date;return{date:e.toLocaleDateString(),time:e.toLocaleTimeString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timestamp:e.getTime(),weekday:e.toLocaleDateString(void 0,{weekday:"long"}),formatted:e.toLocaleDateString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"})}}(),l=vT(o),u={workingDirectory:o,platform:s,dateTime:a,folderStructure:DT(o,{maxDepth:3,maxItems:200,showHidden:!1,respectGitIgnore:!0,respectEmbedderIgnore:!0}),projectInfo:l,userPrompt:NT()||void 0,contextGenerated:Date.now()};return e({cachedContext:u,cacheExpiry:i+r.CACHE_DURATION}),u},refreshContext:async()=>t().getEnvironmentContext(!0),getContextString:async(e=!0)=>{const n=await t().getEnvironmentContext();let r=`# Environment Context\n\n## Current Session\n- **Date**: ${n.dateTime.formatted}\n- **Time**: ${n.dateTime.time} (${n.dateTime.timezone})\n- **Platform**: ${n.platform.platform} (${n.platform.arch})\n- **Working Directory**: ${n.workingDirectory}\n\n## Project Information\n- **Type**: ${n.projectInfo.projectType}\n- **Git Repository**: ${n.projectInfo.isGitRepository?"Yes":"No"}\n- **Package.json**: ${n.projectInfo.hasPackageJson?"Yes":"No"}\n- **EMBEDDER.md**: ${n.projectInfo.hasEmbedderMd?"Yes":"No"}\n\n## Directory Structure\n\`\`\`\n${n.folderStructure}\n\`\`\``;return e&&n.userPrompt&&(r+=`\n\n## User Instructions\n${n.userPrompt}`),r},getCompactContextString:async()=>{const e=await t().getEnvironmentContext();return`Working in ${e.workingDirectory} on ${e.platform.platform}. Project type: ${e.projectInfo.projectType}. Current time: ${e.dateTime.formatted}.`},clearCache:()=>{e({cachedContext:null,cacheExpiry:0})},getFolderStructure:async e=>DT(bT(),e),isCacheValid:()=>{const e=t();return null!==e.cachedContext&&Date.now()<e.cacheExpiry},getCachedContext:()=>{const e=t();return e.cachedContext&&Date.now()<e.cacheExpiry?e.cachedContext:null}}));function kT(e=process.cwd()){return J.existsSync(ae.join(e,".git"))}let xT;function QT(){if(void 0!==xT)return xT;const e=process.cwd(),t=J.readdirSync(e).find(e=>"embedder.md"===e.toLowerCase());if(!t)return xT=null;const n=ae.join(e,t);return xT=J.readFileSync(n,"utf-8")}function NT(e=!1){const t=QT();if(!e)return t;let n=null;try{const e=ST.getState(),t=e.getCachedContext?.();t&&(n=`# Environment Context\n\n${`## Current Session\n- **Date**: ${t.dateTime.formatted}\n- **Platform**: ${t.platform.platform} (${t.platform.arch})\n- **Working Directory**: ${t.workingDirectory}\n\n## Project Information\n- **Type**: ${t.projectInfo.projectType}\n- **Git Repository**: ${t.projectInfo.isGitRepository?"Yes":"No"}\n- **Package.json**: ${t.projectInfo.hasPackageJson?"Yes":"No"}\n\n## Directory Structure\n\`\`\`\n${t.folderStructure}\n\`\`\``}\n\n---\n\nYou are an AI coding assistant working in this environment. Use the above context to understand the current working directory, project structure, and available files. You should not need to run commands like 'pwd' or 'ls' to discover basic information about the environment as it's provided above.`)}catch(qK){ex.warn("Failed to get environment context for system prompt:",qK)}return function(e,t){const n=[];return e?.trim()&&n.push(e.trim()),t?.trim()&&n.push(t.trim()),n.length>0?n.join("\n\n"):null}(t,n)}const TT=qe.createContext(null);function RT({children:e}){const[t,n]=qe.useState(!1),[r,i]=qe.useState(null),[o,s]=qe.useState(null),[a,l]=qe.useState(null),[u,c]=qe.useState(null),d=qe.useMemo(()=>async(e,t={},n={})=>{const r={"Content-Type":"application/json","User-Agent":"embedder-cli/2.0.0",...n},i=await fetch(`https://backend-service-prod.embedder.dev/${e}`,{...t,headers:r});if(!i.ok){const e=await i.text();throw new Error(`Unauth request failed: ${i.status} ${i.statusText} - ${e}`)}return i.json()},[]),p=qe.useMemo(()=>r?async(e,t={},n={},i=2)=>{let o,s=!1;for(let l=0;l<=i;l++)try{const i={Authorization:`Bearer ${await r.getIdToken(s)}`,"Content-Type":"application/json","User-Agent":"embedder-cli/2.0.0",...mT(),...n};a&&(i["x-session-id"]=a);const o=t.headers;if(o)if(Array.isArray(o))for(const[e,t]of o)i[e]=String(t);else o instanceof Headers?o.forEach((e,t)=>{i[t]=e}):Object.entries(o).forEach(([e,t])=>{null!=t&&(i[e]=String(t))});const l=await fetch(`${AT()}/${e}`,{...t,headers:i});if(!l.ok){401!==l.status&&403!==l.status||(s=!0);const e=await l.text();throw ex.error(`API request failed: ${l.status} ${l.statusText} - ${e}`),new Error(`Request failed: ${l.status} ${l.statusText} - ${e}`)}return l.json()}catch(qK){if(o=qK instanceof Error?qK:new Error(String(qK)),l<i){const e=1e3*Math.pow(2,l);await new Promise(t=>setTimeout(t,e))}}throw new Error(`Request failed after ${i+1} attempts. Path: ${e}`+(o?` Last error: ${o.message}`:""))}:null,[r,a]);qe.useEffect(()=>sT.onAuthStateChanged(async e=>{if(!e)return n(!1),i(null),s(null),l(null),void c(null);try{await pT({user:e.toJSON(),accessToken:await e.getIdToken(!0),refreshToken:e.refreshToken})}catch(qK){return void(await pT(null))}i(e)}),[]),qe.useEffect(()=>{if(!r||!p)return;if(a&&o)return;(async()=>{try{const e=await p("api/v1/users/me",{},{},1),t=await p("api/v1/users/me/billing/status",{},{},1);if("active"===t.accountStatus&&!a){const{id:t}=await p("api/v1/sessions",{method:"POST"});l(t),$.setTag("session_id",t);const n=xw.getState(),{teamId:r,projectId:i}=n.getContext(),o=QT();o?$.withScope(n=>{n.setUser({id:e.id,email:e.email,name:e.name}),n.setTag("session_id",t),n.setTag("user_id",e.id),n.setTag("event_type","session_started"),r&&n.setTag("team_id",r),i&&n.setTag("project_id",i),n.addAttachment({filename:"embedder.md",data:o,contentType:"text/markdown"}),n.setContext("embedder_config",{hasFile:!0,contentLength:o.length,preview:o.substring(0,200)+"..."}),$.captureMessage("New session started with embedder.md","info")}):$.withScope(n=>{n.setUser({id:e.id,email:e.email,name:e.name}),n.setTag("session_id",t),n.setTag("user_id",e.id),n.setTag("event_type","session_started"),r&&n.setTag("team_id",r),i&&n.setTag("project_id",i),$.captureMessage("New session started","info")})}s(e),n(!0),c(t),$.setUser({id:e.id,email:e.email,name:e.name})}catch(qK){ex.error("Error initializing backend auth:",qK),$.captureException(qK)}})()},[r,p,a,o]),qe.useEffect(()=>{const e=yT.getState();e.setApiFetch(p),e.setSessionId(a)},[p,a]);return We.jsx(TT.Provider,{value:{loggedIn:t,firebaseUser:r,backendUser:o,sessionId:a,apiFetch:p,closeSession:async(e,t,n,r)=>{if(p&&a)try{o&&$.withScope(i=>{if(i.setUser({id:o.id,email:o.email,name:o.name}),i.setTag("session_id",a),i.setTag("user_id",o.id),i.setTag("event_type","session_closed"),n?.id&&i.setTag("team_id",n.id),t?.id&&i.setTag("project_id",t.id),r&&(i.setTag("model",r.name),i.setTag("provider",r.provider)),e&&e.length>0){const s=JSON.stringify({sessionId:a,userId:o.id,timestamp:(new Date).toISOString(),team:n?{id:n.id,name:n.name}:null,project:t?{id:t.id,name:t.name}:null,model:r,messageCount:e.length,messages:e},null,2);i.addAttachment({filename:`session-${a}-chat-history.json`,data:s,contentType:"application/json"}),i.setContext("chat_history_summary",{messageCount:e.length,hasMessages:!0,dataSize:s.length}),$.captureMessage("Session closed with chat history","info")}else $.captureMessage("Session closed","info")}),await p(`api/v1/sessions/${a}/finish`,{method:"POST"})}catch(qK){ex.error("Error closing session:",qK)}},refreshBackendUser:async()=>{if(p&&o)try{const e=await p("api/v1/users/me",{},{},1);s(e)}catch(qK){ex.error("Error refreshing backend user:",qK),$.captureException(qK)}},setFirebaseUser:i,billingStatus:u,refreshBillingStatus:async()=>{if(p)try{const e=await p("api/v1/users/me/billing/status",{},{},1);c(e)}catch(qK){ex.error("Error refreshing billing status:",qK),$.captureException(qK)}},unauthFetch:d},children:e})}function FT(){const e=qe.useContext(TT);if(!e)throw new Error("useAuth must be used inside AuthProvider");return e}var MT=ug({error:ug({code:jh().nullable(),message:mh(),status:mh()})}),OT=XA({errorSchema:MT,errorToMessage:e=>e.error.message}),$T=ug({outputDimensionality:jh().optional(),taskType:_g(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}),LT=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){const i=await WA({provider:"google",providerOptions:r,schema:$T});if(e.length>this.maxEmbeddingsPerCall)throw new ns({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const o=bA(await YA(this.config.headers),t);if(1===e.length){const{responseHeaders:t,value:r,rawValue:s}=await JA({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:null==i?void 0:i.outputDimensionality,taskType:null==i?void 0:i.taskType},failedResponseHandler:OT,successfulResponseHandler:tm(jT),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:s}}}const{responseHeaders:s,value:a,rawValue:l}=await JA({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:e}]},outputDimensionality:null==i?void 0:i.outputDimensionality,taskType:null==i?void 0:i.taskType}))},failedResponseHandler:OT,successfulResponseHandler:tm(PT),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},PT=ug({embeddings:ag(ug({values:ag(jh())}))}),jT=ug({embedding:ug({values:ag(jh())})});function UT(e){if(null==e||function(e){return null!=e&&"object"==typeof e&&"object"===e.type&&(null==e.properties||0===Object.keys(e.properties).length)&&!e.additionalProperties}(e))return;if("boolean"==typeof e)return{type:"boolean",properties:{}};const{type:t,description:n,required:r,properties:i,items:o,allOf:s,anyOf:a,oneOf:l,format:u,const:c,minLength:d,enum:p}=e,f={};if(n&&(f.description=n),r&&(f.required=r),u&&(f.format=u),void 0!==c&&(f.enum=[c]),t&&(Array.isArray(t)?t.includes("null")?(f.type=t.filter(e=>"null"!==e)[0],f.nullable=!0):f.type=t:f.type="null"===t?"null":t),void 0!==p&&(f.enum=p),null!=i&&(f.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=UT(n),e),{})),o&&(f.items=Array.isArray(o)?o.map(UT):UT(o)),s&&(f.allOf=s.map(UT)),a)if(a.some(e=>"object"==typeof e&&"null"===(null==e?void 0:e.type))){const e=a.filter(e=>!("object"==typeof e&&"null"===(null==e?void 0:e.type)));if(1===e.length){const t=UT(e[0]);"object"==typeof t&&(f.nullable=!0,Object.assign(f,t))}else f.anyOf=e.map(UT),f.nullable=!0}else f.anyOf=a.map(UT);return l&&(f.oneOf=l.map(UT)),void 0!==d&&(f.minLength=d),f}function zT(e){return e.includes("/")?e:`models/${e}`}var GT=ug({responseModalities:ag(_g(["TEXT","IMAGE"])).optional(),thinkingConfig:ug({thinkingBudget:jh().optional(),includeThoughts:Hh().optional()}).optional(),cachedContent:mh().optional(),structuredOutputs:Hh().optional(),safetySettings:ag(ug({category:_g(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:_g(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:_g(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:Hh().optional(),labels:Eg(mh(),mh()).optional()});function HT({finishReason:e,hasToolCalls:t}){switch(e){case"STOP":return t?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"FINISH_REASON_UNSPECIFIED":case"OTHER":return"other";case"MALFORMED_FUNCTION_CALL":return"error";default:return"unknown"}}var WT=ug({web:ug({uri:mh(),title:mh()}).nullish(),retrievedContext:ug({uri:mh(),title:mh()}).nullish()}),qT=ug({webSearchQueries:ag(mh()).nullish(),retrievalQueries:ag(mh()).nullish(),searchEntryPoint:ug({renderedContent:mh()}).nullish(),groundingChunks:ag(WT).nullish(),groundingSupports:ag(ug({segment:ug({startIndex:jh().nullish(),endIndex:jh().nullish(),text:mh().nullish()}),segment_text:mh().nullish(),groundingChunkIndices:ag(jh()).nullish(),supportChunkIndices:ag(jh()).nullish(),confidenceScores:ag(jh()).nullish(),confidenceScore:ag(jh()).nullish()})).nullish(),retrievalMetadata:fg([ug({webDynamicRetrievalScore:jh()}),ug({})]).nullish()}),JT=ZA({id:"google.google_search",name:"google_search",inputSchema:ug({mode:_g(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:jh().default(1)})}),KT=ug({retrievedUrl:mh(),urlRetrievalStatus:mh()}),ZT=ug({urlMetadata:ag(KT)}),VT=ZA({id:"google.url_context",name:"url_context",inputSchema:ug({})}),YT=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:_A}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var f,h;const g=[],A=await WA({provider:"google",providerOptions:p,schema:GT});!0!==(null==(f=null==A?void 0:A.thinkingConfig)?void 0:f.includeThoughts)||this.config.provider.startsWith("google.vertex.")||g.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});const m=this.modelId.toLowerCase().startsWith("gemma-"),{contents:y,systemInstruction:b}=function(e,t){var n;const r=[],i=[];let o=!0;const s=null!=(n=null==t?void 0:t.isGemmaModel)&&n;for(const{role:a,content:l}of e)switch(a){case"system":if(!o)throw new ps({functionality:"system messages are only supported at the beginning of the conversation"});r.push({text:l});break;case"user":{o=!1;const e=[];for(const t of l)switch(t.type){case"text":e.push({text:t.text});break;case"file":{const n="image/*"===t.mediaType?"image/jpeg":t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:Hm(t.data)}});break}}i.push({role:"user",parts:e});break}case"assistant":o=!1,i.push({role:"model",parts:l.map(e=>{var t,n,r,i,o,s;switch(e.type){case"text":return 0===e.text.length?void 0:{text:e.text,thoughtSignature:null==(n=null==(t=e.providerOptions)?void 0:t.google)?void 0:n.thoughtSignature};case"reasoning":return 0===e.text.length?void 0:{text:e.text,thought:!0,thoughtSignature:null==(i=null==(r=e.providerOptions)?void 0:r.google)?void 0:i.thoughtSignature};case"file":if("image/png"!==e.mediaType)throw new ps({functionality:"Only PNG images are supported in assistant messages"});if(e.data instanceof URL)throw new ps({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:e.mediaType,data:Hm(e.data)}};case"tool-call":return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:null==(s=null==(o=e.providerOptions)?void 0:o.google)?void 0:s.thoughtSignature}}}).filter(e=>void 0!==e)});break;case"tool":{o=!1;const e=[];for(const t of l){const n=t.output;if("content"===n.type)for(const r of n.value)switch(r.type){case"text":e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case"media":e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:"Tool executed successfully and returned this image as a response"});break;default:e.push({text:JSON.stringify(r)})}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:"user",parts:e});break}}if(s&&r.length>0&&i.length>0&&"user"===i[0].role){const e=r.map(e=>e.text).join("\n\n");i[0].parts.unshift({text:e+"\n\n"})}return{systemInstruction:r.length>0&&!s?{parts:r}:void 0,contents:i}}(e,{isGemmaModel:m}),{tools:v,toolConfig:E,toolWarnings:I}=function({tools:e,toolChoice:t,modelId:n}){var r;e=(null==e?void 0:e.length)?e:void 0;const i=[],o=n.includes("gemini-2"),s=n.includes("gemini-1.5-flash")&&!n.includes("-8b");if(null==e)return{tools:void 0,toolConfig:void 0,toolWarnings:i};const a=e.some(e=>"function"===e.type),l=e.some(e=>"provider-defined"===e.type);if(a&&l&&i.push({type:"unsupported-tool",tool:e.find(e=>"function"===e.type),details:"Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."}),l){const t={};return e.filter(e=>"provider-defined"===e.type).forEach(e=>{switch(e.id){case"google.google_search":o?t.googleSearch={}:t.googleSearchRetrieval=s?{dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:{};break;case"google.url_context":o?t.urlContext={}:i.push({type:"unsupported-tool",tool:e,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":o?t.codeExecution={}:i.push({type:"unsupported-tool",tool:e,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;default:i.push({type:"unsupported-tool",tool:e})}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:i}}const u=[];for(const d of e)"function"===d.type?u.push({name:d.name,description:null!=(r=d.description)?r:"",parameters:UT(d.inputSchema)}):i.push({type:"unsupported-tool",tool:d});if(null==t)return{tools:{functionDeclarations:u},toolConfig:void 0,toolWarnings:i};const c=t.type;switch(c){case"auto":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:i};case"none":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:i};case"required":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:i};case"tool":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t.toolName]}},toolWarnings:i};default:throw new ps({functionality:`tool choice type: ${c}`})}}({tools:c,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:o,presencePenalty:s,stopSequences:a,seed:u,responseMimeType:"json"===(null==l?void 0:l.type)?"application/json":void 0,responseSchema:"json"!==(null==l?void 0:l.type)||null==l.schema||null!=(h=null==A?void 0:A.structuredOutputs)&&!h?void 0:UT(l.schema),...(null==A?void 0:A.audioTimestamp)&&{audioTimestamp:A.audioTimestamp},responseModalities:null==A?void 0:A.responseModalities,thinkingConfig:null==A?void 0:A.thinkingConfig},contents:y,systemInstruction:m?void 0:b,safetySettings:null==A?void 0:A.safetySettings,tools:v,toolConfig:E,cachedContent:null==A?void 0:A.cachedContent,labels:null==A?void 0:A.labels},warnings:[...g,...I]}}async doGenerate(e){var t,n,r,i,o,s,a,l,u,c,d,p;const{args:f,warnings:h}=await this.getArgs(e),g=JSON.stringify(f),A=bA(await YA(this.config.headers),e.headers),{responseHeaders:m,value:y,rawValue:b}=await JA({url:`${this.config.baseURL}/${zT(this.modelId)}:generateContent`,headers:A,body:f,failedResponseHandler:OT,successfulResponseHandler:tm(rR),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=y.candidates[0],E=[],I=null!=(n=null==(t=v.content)?void 0:t.parts)?n:[],w=y.usageMetadata;let C;for(const B of I)if("executableCode"in B&&(null==(r=B.executableCode)?void 0:r.code)){const e=this.config.generateId();C=e,E.push({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify(B.executableCode),providerExecuted:!0})}else"codeExecutionResult"in B&&B.codeExecutionResult?(E.push({type:"tool-result",toolCallId:C,toolName:"code_execution",result:{outcome:B.codeExecutionResult.outcome,output:B.codeExecutionResult.output},providerExecuted:!0}),C=void 0):"text"in B&&null!=B.text&&B.text.length>0?E.push({type:!0===B.thought?"reasoning":"text",text:B.text,providerMetadata:B.thoughtSignature?{google:{thoughtSignature:B.thoughtSignature}}:void 0}):"functionCall"in B?E.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:B.functionCall.name,input:JSON.stringify(B.functionCall.args),providerMetadata:B.thoughtSignature?{google:{thoughtSignature:B.thoughtSignature}}:void 0}):"inlineData"in B&&E.push({type:"file",data:B.inlineData.data,mediaType:B.inlineData.mimeType});const _=null!=(i=XT({groundingMetadata:v.groundingMetadata,generateId:this.config.generateId}))?i:[];for(const B of _)E.push(B);return{content:E,finishReason:HT({finishReason:v.finishReason,hasToolCalls:E.some(e=>"tool-call"===e.type)}),usage:{inputTokens:null!=(o=null==w?void 0:w.promptTokenCount)?o:void 0,outputTokens:null!=(s=null==w?void 0:w.candidatesTokenCount)?s:void 0,totalTokens:null!=(a=null==w?void 0:w.totalTokenCount)?a:void 0,reasoningTokens:null!=(l=null==w?void 0:w.thoughtsTokenCount)?l:void 0,cachedInputTokens:null!=(u=null==w?void 0:w.cachedContentTokenCount)?u:void 0},warnings:h,providerMetadata:{google:{groundingMetadata:null!=(c=v.groundingMetadata)?c:null,urlContextMetadata:null!=(d=v.urlContextMetadata)?d:null,safetyRatings:null!=(p=v.safetyRatings)?p:null,usageMetadata:null!=w?w:null}},request:{body:g},response:{headers:m,body:b}}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=bA(await YA(this.config.headers),e.headers),{responseHeaders:o,value:s}=await JA({url:`${this.config.baseURL}/${zT(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:OT,successfulResponseHandler:em(iR),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u;const c=this.config.generateId;let d=!1,p=null,f=null,h=0;const g=new Set;let A;return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,o,s,m,y,b,v,E,I,w;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const C=t.value,_=C.usageMetadata;null!=_&&(l.inputTokens=null!=(r=_.promptTokenCount)?r:void 0,l.outputTokens=null!=(i=_.candidatesTokenCount)?i:void 0,l.totalTokens=null!=(o=_.totalTokenCount)?o:void 0,l.reasoningTokens=null!=(s=_.thoughtsTokenCount)?s:void 0,l.cachedInputTokens=null!=(m=_.cachedContentTokenCount)?m:void 0);const B=null==(y=C.candidates)?void 0:y[0];if(null==B)return;const D=B.content,S=XT({groundingMetadata:B.groundingMetadata,generateId:c});if(null!=S)for(const e of S)"url"!==e.sourceType||g.has(e.url)||(g.add(e.url),n.enqueue(e));if(null!=D){const e=null!=(b=D.parts)?b:[];for(const i of e)if("executableCode"in i&&(null==(v=i.executableCode)?void 0:v.code)){const e=c();A=e,n.enqueue({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify(i.executableCode),providerExecuted:!0}),d=!0}else if("codeExecutionResult"in i&&i.codeExecutionResult){const e=A;e&&(n.enqueue({type:"tool-result",toolCallId:e,toolName:"code_execution",result:{outcome:i.codeExecutionResult.outcome,output:i.codeExecutionResult.output},providerExecuted:!0}),A=void 0)}else"text"in i&&null!=i.text&&i.text.length>0&&(!0===i.thought?(null!==p&&(n.enqueue({type:"text-end",id:p}),p=null),null===f&&(f=String(h++),n.enqueue({type:"reasoning-start",id:f,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})),n.enqueue({type:"reasoning-delta",id:f,delta:i.text,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})):(null!==f&&(n.enqueue({type:"reasoning-end",id:f}),f=null),null===p&&(p=String(h++),n.enqueue({type:"text-start",id:p,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})),n.enqueue({type:"text-delta",id:p,delta:i.text,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})));const t=function(e){return null==e?void 0:e.filter(e=>"inlineData"in e)}(D.parts);if(null!=t)for(const i of t)n.enqueue({type:"file",mediaType:i.inlineData.mimeType,data:i.inlineData.data});const r=function({parts:e,generateId:t}){const n=null==e?void 0:e.filter(e=>"functionCall"in e);return null==n||0===n.length?void 0:n.map(e=>({type:"tool-call",toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}({parts:D.parts,generateId:c});if(null!=r)for(const i of r)n.enqueue({type:"tool-input-start",id:i.toolCallId,toolName:i.toolName,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-input-delta",id:i.toolCallId,delta:i.args,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-input-end",id:i.toolCallId,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.args,providerMetadata:i.providerMetadata}),d=!0}null!=B.finishReason&&(a=HT({finishReason:B.finishReason,hasToolCalls:d}),u={google:{groundingMetadata:null!=(E=B.groundingMetadata)?E:null,urlContextMetadata:null!=(I=B.urlContextMetadata)?I:null,safetyRatings:null!=(w=B.safetyRatings)?w:null}},null!=_&&(u.google.usageMetadata=_))},flush(e){null!==p&&e.enqueue({type:"text-end",id:p}),null!==f&&e.enqueue({type:"reasoning-end",id:f}),e.enqueue({type:"finish",finishReason:a,usage:l,providerMetadata:u})}})),response:{headers:o},request:{body:r}}}};function XT({groundingMetadata:e,generateId:t}){var n;return null==(n=null==e?void 0:e.groundingChunks)?void 0:n.filter(e=>null!=e.web).map(e=>({type:"source",sourceType:"url",id:t(),url:e.web.uri,title:e.web.title}))}var eR=ug({parts:ag(fg([ug({functionCall:ug({name:mh(),args:tg()}),thoughtSignature:mh().nullish()}),ug({inlineData:ug({mimeType:mh(),data:mh()})}),ug({executableCode:ug({language:mh(),code:mh()}).nullish(),codeExecutionResult:ug({outcome:mh(),output:mh()}).nullish(),text:mh().nullish(),thought:Hh().nullish(),thoughtSignature:mh().nullish()})])).nullish()}),tR=ug({category:mh().nullish(),probability:mh().nullish(),probabilityScore:jh().nullish(),severity:mh().nullish(),severityScore:jh().nullish(),blocked:Hh().nullish()}),nR=ug({cachedContentTokenCount:jh().nullish(),thoughtsTokenCount:jh().nullish(),promptTokenCount:jh().nullish(),candidatesTokenCount:jh().nullish(),totalTokenCount:jh().nullish()}),rR=ug({candidates:ag(ug({content:eR.nullish().or(ug({}).strict()),finishReason:mh().nullish(),safetyRatings:ag(tR).nullish(),groundingMetadata:qT.nullish(),urlContextMetadata:ZT.nullish()})),usageMetadata:nR.nullish()}),iR=ug({candidates:ag(ug({content:eR.nullish(),finishReason:mh().nullish(),safetyRatings:ag(tR).nullish(),groundingMetadata:qT.nullish(),urlContextMetadata:ZT.nullish()})).nullish(),usageMetadata:nR.nullish()}),oR={googleSearch:JT,urlContext:VT,codeExecution:VA({id:"google.code_execution",name:"code_execution",inputSchema:ug({language:mh().describe("The programming language of the code."),code:mh().describe("The code to be executed.")}),outputSchema:ug({outcome:mh().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:mh().describe("The output from the code execution.")})})},sR=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=this.settings.maxImagesPerCall)?e:4}get provider(){return this.config.provider}async doGenerate(e){var t,n,r;const{prompt:i,n:o=1,size:s="1024x1024",aspectRatio:a="1:1",seed:l,providerOptions:u,headers:c,abortSignal:d}=e,p=[];null!=s&&p.push({type:"unsupported-setting",setting:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=l&&p.push({type:"unsupported-setting",setting:"seed",details:"This model does not support the `seed` option through this provider."});const f=await WA({provider:"google",providerOptions:u,schema:lR}),h=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,g={sampleCount:o};null!=a&&(g.aspectRatio=a),f&&Object.assign(g,f);const A={instances:[{prompt:i}],parameters:g},{responseHeaders:m,value:y}=await JA({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:bA(await YA(this.config.headers),c),body:A,failedResponseHandler:OT,successfulResponseHandler:tm(aR),abortSignal:d,fetch:this.config.fetch});return{images:y.predictions.map(e=>e.bytesBase64Encoded),warnings:null!=p?p:[],providerMetadata:{google:{images:y.predictions.map(e=>({}))}},response:{timestamp:h,modelId:this.modelId,headers:m}}}},aR=ug({predictions:ag(ug({bytesBase64Encoded:mh()})).default([])}),lR=ug({personGeneration:_g(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:_g(["1:1","3:4","4:3","9:16","16:9"]).nullish()});function uR(e={}){var t;const n=null!=(t=Wm(e.baseURL))?t:"https://generativelanguage.googleapis.com/v1beta",r=()=>({"x-goog-api-key":TA({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers}),i=t=>{var i;return new YT(t,{provider:"google.generative-ai",baseURL:n,headers:r,generateId:null!=(i=e.generateId)?i:_A,supportedUrls:()=>({"*":[new RegExp(`^${n}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:e.fetch})},o=t=>new LT(t,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),s=(t,i={})=>new sR(t,i,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),a=function(e){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return i(e)};return a.languageModel=i,a.chat=i,a.generativeAI=i,a.embedding=o,a.textEmbedding=o,a.textEmbeddingModel=o,a.image=s,a.imageModel=s,a.tools=oR,a}uR();var cR=ug({error:ug({message:mh(),type:mh().nullish(),param:Xh().nullish(),code:fg([mh(),jh()]).nullish()})}),dR=XA({errorSchema:cR,errorToMessage:e=>e.error.message});function pR({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function fR(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var hR=ug({logitBias:Eg(lA(),jh()).optional(),logprobs:fg([Hh(),jh()]).optional(),parallelToolCalls:Hh().optional(),user:mh().optional(),reasoningEffort:_g(["minimal","low","medium","high"]).optional(),maxCompletionTokens:jh().optional(),store:Hh().optional(),metadata:Eg(mh().max(64),mh().max(512)).optional(),prediction:Eg(mh(),Xh()).optional(),structuredOutputs:Hh().optional(),serviceTier:_g(["auto","flex","priority"]).optional(),strictJsonSchema:Hh().optional(),textVerbosity:_g(["low","medium","high"]).optional(),promptCacheKey:mh().optional(),safetyIdentifier:mh().optional()});var gR=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var f,h,g,A;const m=[],y=null!=(f=await WA({provider:"openai",providerOptions:p,schema:hR}))?f:{},b=null==(h=y.structuredOutputs)||h;null!=i&&m.push({type:"unsupported-setting",setting:"topK"}),"json"!==(null==l?void 0:l.type)||null==l.schema||b||m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:v,warnings:E}=function({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:i,content:o}of e)switch(i){case"system":switch(t){case"system":n.push({role:"system",content:o});break;case"developer":n.push({role:"developer",content:o});break;case"remove":r.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":if(1===o.length&&"text"===o[0].type){n.push({role:"user",content:o[0].text});break}n.push({role:"user",content:o.map((e,t)=>{var n,r,i;switch(e.type){case"text":return{type:"text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"image_url",image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${Hm(e.data)}`,detail:null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.imageDetail}}}if(!e.mediaType.startsWith("audio/")){if("application/pdf"===e.mediaType){if(e.data instanceof URL)throw new ps({functionality:"PDF file parts with URLs"});return{type:"file",file:"string"==typeof e.data&&e.data.startsWith("file-")?{file_id:e.data}:{filename:null!=(i=e.filename)?i:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Hm(e.data)}`}}}throw new ps({functionality:`file part media type ${e.mediaType}`})}if(e.data instanceof URL)throw new ps({functionality:"audio file parts with URLs"});switch(e.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Hm(e.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Hm(e.data),format:"mp3"}};default:throw new ps({functionality:`audio content parts with media type ${e.mediaType}`})}}})});break;case"assistant":{let e="";const t=[];for(const n of o)switch(n.type){case"text":e+=n.text;break;case"tool-call":t.push({id:n.toolCallId,type:"function",function:{name:n.toolName,arguments:JSON.stringify(n.input)}})}n.push({role:"assistant",content:e,tool_calls:t.length>0?t:void 0});break}case"tool":for(const e of o){const t=e.output;let r;switch(t.type){case"text":case"error-text":r=t.value;break;case"content":case"json":case"error-json":r=JSON.stringify(t.value)}n.push({role:"tool",tool_call_id:e.toolCallId,content:r})}break;default:throw new Error(`Unsupported role: ${i}`)}return{messages:n,warnings:r}}({prompt:e,systemMessageMode:vR(this.modelId)});m.push(...E);const I=null!=(g=y.strictJsonSchema)&&g,w={model:this.modelId,logit_bias:y.logitBias,logprobs:!0===y.logprobs||"number"==typeof y.logprobs||void 0,top_logprobs:"number"==typeof y.logprobs?y.logprobs:"boolean"==typeof y.logprobs&&y.logprobs?0:void 0,user:y.user,parallel_tool_calls:y.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:s,response_format:"json"===(null==l?void 0:l.type)?b&&null!=l.schema?{type:"json_schema",json_schema:{schema:l.schema,strict:I,name:null!=(A=l.name)?A:"response",description:l.description}}:{type:"json_object"}:void 0,stop:a,seed:u,verbosity:y.textVerbosity,max_completion_tokens:y.maxCompletionTokens,store:y.store,metadata:y.metadata,prediction:y.prediction,reasoning_effort:y.reasoningEffort,service_tier:y.serviceTier,prompt_cache_key:y.promptCacheKey,safety_identifier:y.safetyIdentifier,messages:v};var C;bR(this.modelId)?(null!=w.temperature&&(w.temperature=void 0,m.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=w.top_p&&(w.top_p=void 0,m.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),null!=w.frequency_penalty&&(w.frequency_penalty=void 0,m.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),null!=w.presence_penalty&&(w.presence_penalty=void 0,m.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),null!=w.logit_bias&&(w.logit_bias=void 0,m.push({type:"other",message:"logitBias is not supported for reasoning models"})),null!=w.logprobs&&(w.logprobs=void 0,m.push({type:"other",message:"logprobs is not supported for reasoning models"})),null!=w.top_logprobs&&(w.top_logprobs=void 0,m.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),null!=w.max_tokens&&(null==w.max_completion_tokens&&(w.max_completion_tokens=w.max_tokens),w.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&null!=w.temperature&&(w.temperature=void 0,m.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),"flex"!==y.serviceTier||((C=this.modelId).startsWith("o3")||C.startsWith("o4-mini")||C.startsWith("gpt-5")&&!C.startsWith("gpt-5-chat"))||(m.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),w.service_tier=void 0),"priority"!==y.serviceTier||function(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}(this.modelId)||(m.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),w.service_tier=void 0);const{tools:_,toolChoice:B,toolWarnings:D}=function({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){const i=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:i};const o=[];for(const a of e)"function"===a.type?o.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,strict:n?r:void 0}}):i.push({type:"unsupported-tool",tool:a});if(null==t)return{tools:o,toolChoice:void 0,toolWarnings:i};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:i};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:i};default:throw new ps({functionality:`tool choice type: ${s}`})}}({tools:c,toolChoice:d,structuredOutputs:b,strictJsonSchema:I});return{args:{...w,tools:_,tool_choice:B},warnings:[...m,...D]}}async doGenerate(e){var t,n,r,i,o,s,a,l,u,c,d,p,f,h;const{args:g,warnings:A}=await this.getArgs(e),{responseHeaders:m,value:y,rawValue:b}=await JA({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:g,failedResponseHandler:dR,successfulResponseHandler:tm(mR),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=y.choices[0],E=[],I=v.message.content;null!=I&&I.length>0&&E.push({type:"text",text:I});for(const B of null!=(t=v.message.tool_calls)?t:[])E.push({type:"tool-call",toolCallId:null!=(n=B.id)?n:_A(),toolName:B.function.name,input:B.function.arguments});for(const B of null!=(r=v.message.annotations)?r:[])E.push({type:"source",sourceType:"url",id:_A(),url:B.url,title:B.title});const w=null==(i=y.usage)?void 0:i.completion_tokens_details,C=null==(o=y.usage)?void 0:o.prompt_tokens_details,_={openai:{}};return null!=(null==w?void 0:w.accepted_prediction_tokens)&&(_.openai.acceptedPredictionTokens=null==w?void 0:w.accepted_prediction_tokens),null!=(null==w?void 0:w.rejected_prediction_tokens)&&(_.openai.rejectedPredictionTokens=null==w?void 0:w.rejected_prediction_tokens),null!=(null==(s=v.logprobs)?void 0:s.content)&&(_.openai.logprobs=v.logprobs.content),{content:E,finishReason:fR(v.finish_reason),usage:{inputTokens:null!=(l=null==(a=y.usage)?void 0:a.prompt_tokens)?l:void 0,outputTokens:null!=(c=null==(u=y.usage)?void 0:u.completion_tokens)?c:void 0,totalTokens:null!=(p=null==(d=y.usage)?void 0:d.total_tokens)?p:void 0,reasoningTokens:null!=(f=null==w?void 0:w.reasoning_tokens)?f:void 0,cachedInputTokens:null!=(h=null==C?void 0:C.cached_tokens)?h:void 0},request:{body:g},response:{...pR(y),headers:m,body:b},warnings:A,providerMetadata:_}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await JA({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:r,failedResponseHandler:dR,successfulResponseHandler:em(yR),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0,c=!1;const d={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,o,p,f,h,g,A,m,y,b,v,E,I,w,C,_,B,D,S,k,x,Q,N;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return a="error",void n.enqueue({type:"error",error:t.error});const T=t.value;if("error"in T)return a="error",void n.enqueue({type:"error",error:T.error});u&&(u=!1,n.enqueue({type:"response-metadata",...pR(T)})),null!=T.usage&&(l.inputTokens=null!=(r=T.usage.prompt_tokens)?r:void 0,l.outputTokens=null!=(i=T.usage.completion_tokens)?i:void 0,l.totalTokens=null!=(o=T.usage.total_tokens)?o:void 0,l.reasoningTokens=null!=(f=null==(p=T.usage.completion_tokens_details)?void 0:p.reasoning_tokens)?f:void 0,l.cachedInputTokens=null!=(g=null==(h=T.usage.prompt_tokens_details)?void 0:h.cached_tokens)?g:void 0,null!=(null==(A=T.usage.completion_tokens_details)?void 0:A.accepted_prediction_tokens)&&(d.openai.acceptedPredictionTokens=null==(m=T.usage.completion_tokens_details)?void 0:m.accepted_prediction_tokens),null!=(null==(y=T.usage.completion_tokens_details)?void 0:y.rejected_prediction_tokens)&&(d.openai.rejectedPredictionTokens=null==(b=T.usage.completion_tokens_details)?void 0:b.rejected_prediction_tokens));const R=T.choices[0];if(null!=(null==R?void 0:R.finish_reason)&&(a=fR(R.finish_reason)),null!=(null==(v=null==R?void 0:R.logprobs)?void 0:v.content)&&(d.openai.logprobs=R.logprobs.content),null==(null==R?void 0:R.delta))return;const F=R.delta;if(null!=F.content&&(c||(n.enqueue({type:"text-start",id:"0"}),c=!0),n.enqueue({type:"text-delta",id:"0",delta:F.content})),null!=F.tool_calls)for(const e of F.tool_calls){const t=e.index;if(null==s[t]){if("function"!==e.type)throw new Mo({data:e,message:"Expected 'function' type."});if(null==e.id)throw new Mo({data:e,message:"Expected 'id' to be a string."});if(null==(null==(E=e.function)?void 0:E.name))throw new Mo({data:e,message:"Expected 'function.name' to be a string."});n.enqueue({type:"tool-input-start",id:e.id,toolName:e.function.name}),s[t]={id:e.id,type:"function",function:{name:e.function.name,arguments:null!=(I=e.function.arguments)?I:""},hasFinished:!1};const r=s[t];null!=(null==(w=r.function)?void 0:w.name)&&null!=(null==(C=r.function)?void 0:C.arguments)&&(r.function.arguments.length>0&&n.enqueue({type:"tool-input-delta",id:r.id,delta:r.function.arguments}),GA(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(_=r.id)?_:_A(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}const r=s[t];r.hasFinished||(null!=(null==(B=e.function)?void 0:B.arguments)&&(r.function.arguments+=null!=(S=null==(D=e.function)?void 0:D.arguments)?S:""),n.enqueue({type:"tool-input-delta",id:r.id,delta:null!=(k=e.function.arguments)?k:""}),null!=(null==(x=r.function)?void 0:x.name)&&null!=(null==(Q=r.function)?void 0:Q.arguments)&&GA(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(N=r.id)?N:_A(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(null!=F.annotations)for(const e of F.annotations)n.enqueue({type:"source",sourceType:"url",id:_A(),url:e.url,title:e.title})},flush(e){c&&e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:a,usage:l,...null!=d?{providerMetadata:d}:{}})}})),request:{body:r},response:{headers:i}}}},AR=ug({prompt_tokens:jh().nullish(),completion_tokens:jh().nullish(),total_tokens:jh().nullish(),prompt_tokens_details:ug({cached_tokens:jh().nullish()}).nullish(),completion_tokens_details:ug({reasoning_tokens:jh().nullish(),accepted_prediction_tokens:jh().nullish(),rejected_prediction_tokens:jh().nullish()}).nullish()}).nullish(),mR=ug({id:mh().nullish(),created:jh().nullish(),model:mh().nullish(),choices:ag(ug({message:ug({role:Dg("assistant").nullish(),content:mh().nullish(),tool_calls:ag(ug({id:mh().nullish(),type:Dg("function"),function:ug({name:mh(),arguments:mh()})})).nullish(),annotations:ag(ug({type:Dg("url_citation"),start_index:jh(),end_index:jh(),url:mh(),title:mh()})).nullish()}),index:jh(),logprobs:ug({content:ag(ug({token:mh(),logprob:jh(),top_logprobs:ag(ug({token:mh(),logprob:jh()}))})).nullish()}).nullish(),finish_reason:mh().nullish()})),usage:AR}),yR=fg([ug({id:mh().nullish(),created:jh().nullish(),model:mh().nullish(),choices:ag(ug({delta:ug({role:_g(["assistant"]).nullish(),content:mh().nullish(),tool_calls:ag(ug({index:jh(),id:mh().nullish(),type:Dg("function").nullish(),function:ug({name:mh().nullish(),arguments:mh().nullish()})})).nullish(),annotations:ag(ug({type:Dg("url_citation"),start_index:jh(),end_index:jh(),url:mh(),title:mh()})).nullish()}).nullish(),logprobs:ug({content:ag(ug({token:mh(),logprob:jh(),top_logprobs:ag(ug({token:mh(),logprob:jh()}))})).nullish()}).nullish(),finish_reason:mh().nullish(),index:jh()})),usage:AR}),cR]);function bR(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function vR(e){var t,n;return bR(e)?null!=(n=null==(t=ER[e])?void 0:t.systemMessageMode)?n:"developer":"system"}var ER={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function IR({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function wR(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var CR=ug({echo:Hh().optional(),logitBias:Eg(mh(),jh()).optional(),suffix:mh().optional(),user:mh().optional(),logprobs:fg([Hh(),jh()]).optional()}),_R=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,tools:u,toolChoice:c,seed:d,providerOptions:p}){const f=[],h={...await WA({provider:"openai",providerOptions:p,schema:CR}),...await WA({provider:this.providerOptionsName,providerOptions:p,schema:CR})};null!=i&&f.push({type:"unsupported-setting",setting:"topK"}),(null==u?void 0:u.length)&&f.push({type:"unsupported-setting",setting:"tools"}),null!=c&&f.push({type:"unsupported-setting",setting:"toolChoice"}),null!=l&&"text"!==l.type&&f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:g,stopSequences:A}=function({prompt:e,user:t="user",assistant:n="assistant"}){let r="";"system"===e[0].role&&(r+=`${e[0].content}\n\n`,e=e.slice(1));for(const{role:i,content:o}of e)switch(i){case"system":throw new Qo({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":r+=`${t}:\n${o.map(e=>{if("text"===e.type)return e.text}).filter(Boolean).join("")}\n\n`;break;case"assistant":r+=`${n}:\n${o.map(e=>{switch(e.type){case"text":return e.text;case"tool-call":throw new ps({functionality:"tool-call messages"})}}).join("")}\n\n`;break;case"tool":throw new ps({functionality:"tool messages"});default:throw new Error(`Unsupported role: ${i}`)}return r+=`${n}:\n`,{prompt:r,stopSequences:[`\n${t}:`]}}({prompt:e}),m=[...null!=A?A:[],...null!=a?a:[]];return{args:{model:this.modelId,echo:h.echo,logit_bias:h.logitBias,logprobs:!0===(null==h?void 0:h.logprobs)?0:!1===(null==h?void 0:h.logprobs)||null==h?void 0:h.logprobs,suffix:h.suffix,user:h.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:s,seed:d,prompt:g,stop:m.length>0?m:void 0},warnings:f}}async doGenerate(e){var t,n,r;const{args:i,warnings:o}=await this.getArgs(e),{responseHeaders:s,value:a,rawValue:l}=await JA({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:i,failedResponseHandler:dR,successfulResponseHandler:tm(DR),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=a.choices[0],c={openai:{}};return null!=u.logprobs&&(c.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:null==(t=a.usage)?void 0:t.prompt_tokens,outputTokens:null==(n=a.usage)?void 0:n.completion_tokens,totalTokens:null==(r=a.usage)?void 0:r.total_tokens},finishReason:wR(u.finish_reason),request:{body:i},response:{...IR(a),headers:s,body:l},providerMetadata:c,warnings:o}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await JA({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:r,failedResponseHandler:dR,successfulResponseHandler:em(SR),abortSignal:e.abortSignal,fetch:this.config.fetch});let s="unknown";const a={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const r=t.value;if("error"in r)return s="error",void n.enqueue({type:"error",error:r.error});u&&(u=!1,n.enqueue({type:"response-metadata",...IR(r)}),n.enqueue({type:"text-start",id:"0"})),null!=r.usage&&(l.inputTokens=r.usage.prompt_tokens,l.outputTokens=r.usage.completion_tokens,l.totalTokens=r.usage.total_tokens);const i=r.choices[0];null!=(null==i?void 0:i.finish_reason)&&(s=wR(i.finish_reason)),null!=(null==i?void 0:i.logprobs)&&(a.openai.logprobs=i.logprobs),null!=(null==i?void 0:i.text)&&i.text.length>0&&n.enqueue({type:"text-delta",id:"0",delta:i.text})},flush(e){u||e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:s,providerMetadata:a,usage:l})}})),request:{body:r},response:{headers:i}}}},BR=ug({prompt_tokens:jh(),completion_tokens:jh(),total_tokens:jh()}),DR=ug({id:mh().nullish(),created:jh().nullish(),model:mh().nullish(),choices:ag(ug({text:mh(),finish_reason:mh(),logprobs:ug({tokens:ag(mh()),token_logprobs:ag(jh()),top_logprobs:ag(Eg(mh(),jh())).nullish()}).nullish()})),usage:BR.nullish()}),SR=fg([ug({id:mh().nullish(),created:jh().nullish(),model:mh().nullish(),choices:ag(ug({text:mh(),finish_reason:mh().nullish(),index:jh(),logprobs:ug({tokens:ag(mh()),token_logprobs:ag(jh()),top_logprobs:ag(Eg(mh(),jh())).nullish()}).nullish()})),usage:BR.nullish()}),cR]),kR=ug({dimensions:jh().optional(),user:mh().optional()}),xR=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var i;if(e.length>this.maxEmbeddingsPerCall)throw new ns({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const o=null!=(i=await WA({provider:"openai",providerOptions:r,schema:kR}))?i:{},{responseHeaders:s,value:a,rawValue:l}=await JA({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:bA(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:dR,successfulResponseHandler:tm(QR),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.data.map(e=>e.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:s,body:l}}}},QR=ug({data:ag(ug({embedding:ag(jh())})),usage:ug({prompt_tokens:jh()}).nullish()}),NR={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},TR=new Set(["gpt-image-1"]),RR=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=NR[this.modelId])?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:o,headers:s,abortSignal:a}){var l,u,c,d;const p=[];null!=r&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),null!=i&&p.push({type:"unsupported-setting",setting:"seed"});const f=null!=(c=null==(u=null==(l=this.config._internal)?void 0:l.currentDate)?void 0:u.call(l))?c:new Date,{value:h,responseHeaders:g}=await JA({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:bA(this.config.headers(),s),body:{model:this.modelId,prompt:e,n:t,size:n,...null!=(d=o.openai)?d:{},...TR.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:dR,successfulResponseHandler:tm(FR),abortSignal:a,fetch:this.config.fetch});return{images:h.data.map(e=>e.b64_json),warnings:p,response:{timestamp:f,modelId:this.modelId,headers:g},providerMetadata:{openai:{images:h.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},FR=ug({data:ag(ug({b64_json:mh(),revised_prompt:mh().optional()}))}),MR=ug({code:mh().nullish(),containerId:mh()}),OR=ug({outputs:ag(gg("type",[ug({type:Dg("logs"),logs:mh()}),ug({type:Dg("image"),url:mh()})])).nullish()}),$R=ug({container:fg([mh(),ug({fileIds:ag(mh()).optional()})]).optional()}),LR=VA({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:MR,outputSchema:OR}),PR=ug({key:mh(),type:_g(["eq","ne","gt","gte","lt","lte"]),value:fg([mh(),jh(),Hh()])}),jR=ug({type:_g(["and","or"]),filters:ag(fg([PR,Yg(()=>jR)]))}),UR=ug({vectorStoreIds:ag(mh()),maxNumResults:jh().optional(),ranking:ug({ranker:mh().optional(),scoreThreshold:jh().optional()}).optional(),filters:fg([PR,jR]).optional()}),zR=ug({queries:ag(mh()),results:ag(ug({attributes:Eg(mh(),tg()),fileId:mh(),filename:mh(),score:jh(),text:mh()})).nullable()}),GR=VA({id:"openai.file_search",name:"file_search",inputSchema:ug({}),outputSchema:zR}),HR=ug({background:_g(["auto","opaque","transparent"]).optional(),inputFidelity:_g(["low","high"]).optional(),inputImageMask:ug({fileId:mh().optional(),imageUrl:mh().optional()}).optional(),model:mh().optional(),moderation:_g(["auto"]).optional(),outputCompression:jh().int().min(0).max(100).optional(),outputFormat:_g(["png","jpeg","webp"]).optional(),quality:_g(["auto","low","medium","high"]).optional(),size:_g(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict(),WR=ug({result:mh()}),qR=VA({id:"openai.image_generation",name:"image_generation",inputSchema:ug({}),outputSchema:WR}),JR=ug({filters:ug({allowedDomains:ag(mh()).optional()}).optional(),searchContextSize:_g(["low","medium","high"]).optional(),userLocation:ug({type:Dg("approximate"),country:mh().optional(),city:mh().optional(),region:mh().optional(),timezone:mh().optional()}).optional()}),KR=ZA({id:"openai.web_search",name:"web_search",inputSchema:ug({action:gg("type",[ug({type:Dg("search"),query:mh().nullish()}),ug({type:Dg("open_page"),url:mh()}),ug({type:Dg("find"),url:mh(),pattern:mh()})]).nullish()})}),ZR=ug({searchContextSize:_g(["low","medium","high"]).optional(),userLocation:ug({type:Dg("approximate"),country:mh().optional(),city:mh().optional(),region:mh().optional(),timezone:mh().optional()}).optional()}),VR={codeInterpreter:(e={})=>LR(e),fileSearch:GR,imageGeneration:(e={})=>qR(e),webSearchPreview:ZA({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:ug({action:gg("type",[ug({type:Dg("search"),query:mh().nullish()}),ug({type:Dg("open_page"),url:mh()}),ug({type:Dg("find"),url:mh(),pattern:mh()})]).nullish()})}),webSearch:(e={})=>KR(e)};function YR(e,t){return!!t&&t.some(t=>e.startsWith(t))}var XR=ug({itemId:mh().nullish(),reasoningEncryptedContent:mh().nullish()});function eF({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var tF=ug({type:Dg("web_search_call"),id:mh(),status:mh(),action:gg("type",[ug({type:Dg("search"),query:mh().nullish()}),ug({type:Dg("open_page"),url:mh()}),ug({type:Dg("find"),url:mh(),pattern:mh()})]).nullish()}),nF=ug({type:Dg("file_search_call"),id:mh(),queries:ag(mh()),results:ag(ug({attributes:Eg(mh(),tg()),file_id:mh(),filename:mh(),score:jh(),text:mh()})).nullish()}),rF=ug({type:Dg("code_interpreter_call"),id:mh(),code:mh().nullable(),container_id:mh(),outputs:ag(gg("type",[ug({type:Dg("logs"),logs:mh()}),ug({type:Dg("image"),url:mh()})])).nullable()}),iF=ug({type:Dg("image_generation_call"),id:mh(),result:mh()}),oF=ag(ug({token:mh(),logprob:jh(),top_logprobs:ag(ug({token:mh(),logprob:jh()}))})),sF=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:o,frequencyPenalty:s,seed:a,prompt:l,providerOptions:u,tools:c,toolChoice:d,responseFormat:p}){var f,h,g,A;const m=[],y=function(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};if(e.startsWith("gpt-5-chat"))return{...r,isReasoningModel:!1};if(e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use"))return e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...r,isReasoningModel:!0,systemMessageMode:"remove"}:{...r,isReasoningModel:!0,systemMessageMode:"developer"};return{...r,isReasoningModel:!1}}(this.modelId);null!=i&&m.push({type:"unsupported-setting",setting:"topK"}),null!=a&&m.push({type:"unsupported-setting",setting:"seed"}),null!=o&&m.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=s&&m.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=n&&m.push({type:"unsupported-setting",setting:"stopSequences"});const b=await WA({provider:"openai",providerOptions:u,schema:fF}),{input:v,warnings:E}=await async function({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r}){var i,o,s,a,l,u;const c=[],d=[];for(const{role:p,content:f}of e)switch(p){case"system":switch(t){case"system":c.push({role:"system",content:f});break;case"developer":c.push({role:"developer",content:f});break;case"remove":d.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":c.push({role:"user",content:f.map((e,t)=>{var r,i,o;switch(e.type){case"text":return{type:"input_text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"input_image",...e.data instanceof URL?{image_url:e.data.toString()}:"string"==typeof e.data&&YR(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Hm(e.data)}`},detail:null==(i=null==(r=e.providerOptions)?void 0:r.openai)?void 0:i.imageDetail}}if("application/pdf"===e.mediaType)return e.data instanceof URL?{type:"input_file",file_url:e.data.toString()}:{type:"input_file",..."string"==typeof e.data&&YR(e.data,n)?{file_id:e.data}:{filename:null!=(o=e.filename)?o:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Hm(e.data)}`}};throw new ps({functionality:`file part media type ${e.mediaType}`})}})});break;case"assistant":{const e={},t={};for(const n of f)switch(n.type){case"text":c.push({role:"assistant",content:[{type:"output_text",text:n.text}],id:null!=(s=null==(o=null==(i=n.providerOptions)?void 0:i.openai)?void 0:o.itemId)?s:void 0});break;case"tool-call":if(t[n.toolCallId]=n,n.providerExecuted)break;c.push({type:"function_call",call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:null!=(u=null==(l=null==(a=n.providerOptions)?void 0:a.openai)?void 0:l.itemId)?u:void 0});break;case"tool-result":r?c.push({type:"item_reference",id:n.toolCallId}):d.push({type:"other",message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case"reasoning":{const t=await WA({provider:"openai",providerOptions:n.providerOptions,schema:XR}),r=null==t?void 0:t.itemId;if(null!=r){const i=e[r],o=[];n.text.length>0?o.push({type:"summary_text",text:n.text}):void 0!==i&&d.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),void 0===i?(e[r]={type:"reasoning",id:r,encrypted_content:null==t?void 0:t.reasoningEncryptedContent,summary:o},c.push(e[r])):i.summary.push(...o)}else d.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case"tool":for(const e of f){const t=e.output;let n;switch(t.type){case"text":case"error-text":n=t.value;break;case"content":case"json":case"error-json":n=JSON.stringify(t.value)}c.push({type:"function_call_output",call_id:e.toolCallId,output:n})}break;default:throw new Error(`Unsupported role: ${p}`)}return{input:c,warnings:d}}({prompt:l,systemMessageMode:y.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:null==(f=null==b?void 0:b.store)||f});m.push(...E);const I=null!=(h=null==b?void 0:b.strictJsonSchema)&&h;let w=null==b?void 0:b.include;function C(e){w=null!=w?[...w,e]:[e]}const _="number"==typeof(null==b?void 0:b.logprobs)?null==b?void 0:b.logprobs:!0===(null==b?void 0:b.logprobs)?20:void 0;_&&C("message.output_text.logprobs");const B=null==(g=null==c?void 0:c.find(e=>"provider-defined"===e.type&&("openai.web_search"===e.id||"openai.web_search_preview"===e.id)))?void 0:g.name;var D;B&&C("web_search_call.action.sources"),D="openai.code_interpreter",null!=(null==c?void 0:c.find(e=>"provider-defined"===e.type&&e.id===D))&&C("code_interpreter_call.outputs");const S={model:this.modelId,input:v,temperature:t,top_p:r,max_output_tokens:e,...("json"===(null==p?void 0:p.type)||(null==b?void 0:b.textVerbosity))&&{text:{..."json"===(null==p?void 0:p.type)&&{format:null!=p.schema?{type:"json_schema",strict:I,name:null!=(A=p.name)?A:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...(null==b?void 0:b.textVerbosity)&&{verbosity:b.textVerbosity}}},max_tool_calls:null==b?void 0:b.maxToolCalls,metadata:null==b?void 0:b.metadata,parallel_tool_calls:null==b?void 0:b.parallelToolCalls,previous_response_id:null==b?void 0:b.previousResponseId,store:null==b?void 0:b.store,user:null==b?void 0:b.user,instructions:null==b?void 0:b.instructions,service_tier:null==b?void 0:b.serviceTier,include:w,prompt_cache_key:null==b?void 0:b.promptCacheKey,safety_identifier:null==b?void 0:b.safetyIdentifier,top_logprobs:_,...y.isReasoningModel&&(null!=(null==b?void 0:b.reasoningEffort)||null!=(null==b?void 0:b.reasoningSummary))&&{reasoning:{...null!=(null==b?void 0:b.reasoningEffort)&&{effort:b.reasoningEffort},...null!=(null==b?void 0:b.reasoningSummary)&&{summary:b.reasoningSummary}}},...y.requiredAutoTruncation&&{truncation:"auto"}};y.isReasoningModel?(null!=S.temperature&&(S.temperature=void 0,m.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=S.top_p&&(S.top_p=void 0,m.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(null!=(null==b?void 0:b.reasoningEffort)&&m.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),null!=(null==b?void 0:b.reasoningSummary)&&m.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),"flex"!==(null==b?void 0:b.serviceTier)||y.supportsFlexProcessing||(m.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete S.service_tier),"priority"!==(null==b?void 0:b.serviceTier)||y.supportsPriorityProcessing||(m.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete S.service_tier);const{tools:k,toolChoice:x,toolWarnings:Q}=function({tools:e,toolChoice:t,strictJsonSchema:n}){const r=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:r};const i=[];for(const s of e)switch(s.type){case"function":i.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,strict:n});break;case"provider-defined":switch(s.id){case"openai.file_search":{const e=UR.parse(s.args);i.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=ZR.parse(s.args);i.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.web_search":{const e=JR.parse(s.args);i.push({type:"web_search",filters:null!=e.filters?{allowed_domains:e.filters.allowedDomains}:void 0,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.code_interpreter":{const e=$R.parse(s.args);i.push({type:"code_interpreter",container:null==e.container?{type:"auto",file_ids:void 0}:"string"==typeof e.container?e.container:{type:"auto",file_ids:e.container.fileIds}});break}case"openai.image_generation":{const e=HR.parse(s.args);i.push({type:"image_generation",background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:r.push({type:"unsupported-tool",tool:s})}if(null==t)return{tools:i,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:i,toolChoice:o,toolWarnings:r};case"tool":return{tools:i,toolChoice:"code_interpreter"===t.toolName||"file_search"===t.toolName||"image_generation"===t.toolName||"web_search_preview"===t.toolName||"web_search"===t.toolName?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:throw new ps({functionality:`tool choice type: ${o}`})}}({tools:c,toolChoice:d,strictJsonSchema:I});return{webSearchToolName:B,args:{...S,tools:k,tool_choice:x},warnings:[...m,...Q]}}async doGenerate(e){var t,n,r,i,o,s,a,l,u,c,d,p,f,h,g,A,m,y,b;const{args:v,warnings:E,webSearchToolName:I}=await this.getArgs(e),w=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:C,value:_,rawValue:B}=await JA({url:w,headers:bA(this.config.headers(),e.headers),body:v,failedResponseHandler:dR,successfulResponseHandler:tm(ug({id:mh(),created_at:jh(),error:ug({code:mh(),message:mh()}).nullish(),model:mh(),output:ag(gg("type",[ug({type:Dg("message"),role:Dg("assistant"),id:mh(),content:ag(ug({type:Dg("output_text"),text:mh(),logprobs:oF.nullish(),annotations:ag(gg("type",[ug({type:Dg("url_citation"),start_index:jh(),end_index:jh(),url:mh(),title:mh()}),ug({type:Dg("file_citation"),file_id:mh(),filename:mh().nullish(),index:jh().nullish(),start_index:jh().nullish(),end_index:jh().nullish(),quote:mh().nullish()}),ug({type:Dg("container_file_citation")})]))}))}),tF,nF,rF,iF,ug({type:Dg("function_call"),call_id:mh(),name:mh(),arguments:mh(),id:mh()}),ug({type:Dg("computer_call"),id:mh(),status:mh().optional()}),ug({type:Dg("reasoning"),id:mh(),encrypted_content:mh().nullish(),summary:ag(ug({type:Dg("summary_text"),text:mh()}))})])),service_tier:mh().nullish(),incomplete_details:ug({reason:mh()}).nullable(),usage:aF})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(_.error)throw new go({message:_.error.message,url:w,requestBodyValues:v,statusCode:400,responseHeaders:C,responseBody:B,isRetryable:!1});const D=[],S=[];let k=!1;for(const Q of _.output)switch(Q.type){case"reasoning":0===Q.summary.length&&Q.summary.push({type:"summary_text",text:""});for(const e of Q.summary)D.push({type:"reasoning",text:e.text,providerMetadata:{openai:{itemId:Q.id,reasoningEncryptedContent:null!=(t=Q.encrypted_content)?t:null}}});break;case"image_generation_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:"image_generation",result:{result:Q.result},providerExecuted:!0});break;case"message":for(const t of Q.content){(null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.logprobs)&&t.logprobs&&S.push(t.logprobs),D.push({type:"text",text:t.text,providerMetadata:{openai:{itemId:Q.id}}});for(const e of t.annotations)"url_citation"===e.type?D.push({type:"source",sourceType:"url",id:null!=(s=null==(o=(i=this.config).generateId)?void 0:o.call(i))?s:_A(),url:e.url,title:e.title}):"file_citation"===e.type&&D.push({type:"source",sourceType:"document",id:null!=(u=null==(l=(a=this.config).generateId)?void 0:l.call(a))?u:_A(),mediaType:"text/plain",title:null!=(d=null!=(c=e.quote)?c:e.filename)?d:"Document",filename:null!=(p=e.filename)?p:e.file_id})}break;case"function_call":k=!0,D.push({type:"tool-call",toolCallId:Q.call_id,toolName:Q.name,input:Q.arguments,providerMetadata:{openai:{itemId:Q.id}}});break;case"web_search_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:null!=I?I:"web_search",input:JSON.stringify({action:Q.action}),providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:null!=I?I:"web_search",result:{status:Q.status},providerExecuted:!0});break;case"computer_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:"computer_use",input:"",providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:Q.status||"completed"},providerExecuted:!0});break;case"file_search_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:"file_search",input:"{}",providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:"file_search",result:{queries:Q.queries,results:null!=(h=null==(f=Q.results)?void 0:f.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text})))?h:null},providerExecuted:!0});break;case"code_interpreter_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:"code_interpreter",input:JSON.stringify({code:Q.code,containerId:Q.container_id}),providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:"code_interpreter",result:{outputs:Q.outputs},providerExecuted:!0})}const x={openai:{responseId:_.id}};return S.length>0&&(x.openai.logprobs=S),"string"==typeof _.service_tier&&(x.openai.serviceTier=_.service_tier),{content:D,finishReason:eF({finishReason:null==(g=_.incomplete_details)?void 0:g.reason,hasFunctionCall:k}),usage:{inputTokens:_.usage.input_tokens,outputTokens:_.usage.output_tokens,totalTokens:_.usage.input_tokens+_.usage.output_tokens,reasoningTokens:null!=(m=null==(A=_.usage.output_tokens_details)?void 0:A.reasoning_tokens)?m:void 0,cachedInputTokens:null!=(b=null==(y=_.usage.input_tokens_details)?void 0:y.cached_tokens)?b:void 0},request:{body:v},response:{id:_.id,timestamp:new Date(1e3*_.created_at),modelId:_.model,headers:C,body:B},providerMetadata:x,warnings:E}}async doStream(e){const{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:o}=await JA({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:dR,successfulResponseHandler:em(cF),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=this;let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=[];let c=null;const d={};let p=!1;const f={};let h;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var i,o,g,A,m,y,b,v,E,I,w,C,_,B,D,S,k,x,Q,N,T,R,F;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return a="error",void n.enqueue({type:"error",error:t.error});const M=t.value;if(pF(M))"function_call"===M.item.type?(d[M.output_index]={toolName:M.item.name,toolCallId:M.item.call_id},n.enqueue({type:"tool-input-start",id:M.item.call_id,toolName:M.item.name})):"web_search_call"===M.item.type?(d[M.output_index]={toolName:null!=r?r:"web_search",toolCallId:M.item.id},n.enqueue({type:"tool-input-start",id:M.item.id,toolName:null!=r?r:"web_search"})):"computer_call"===M.item.type?(d[M.output_index]={toolName:"computer_use",toolCallId:M.item.id},n.enqueue({type:"tool-input-start",id:M.item.id,toolName:"computer_use"})):"file_search_call"===M.item.type?n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):"image_generation_call"===M.item.type?n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):"message"===M.item.type?n.enqueue({type:"text-start",id:M.item.id,providerMetadata:{openai:{itemId:M.item.id}}}):function(e){return pF(e)&&"reasoning"===e.item.type}(M)&&(f[M.item.id]={encryptedContent:M.item.encrypted_content,summaryParts:[0]},n.enqueue({type:"reasoning-start",id:`${M.item.id}:0`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:null!=(i=M.item.encrypted_content)?i:null}}}));else if(dF(M)){if("function_call"===M.item.type)d[M.output_index]=void 0,p=!0,n.enqueue({type:"tool-input-end",id:M.item.call_id}),n.enqueue({type:"tool-call",toolCallId:M.item.call_id,toolName:M.item.name,input:M.item.arguments,providerMetadata:{openai:{itemId:M.item.id}}});else if("web_search_call"===M.item.type)d[M.output_index]=void 0,n.enqueue({type:"tool-input-end",id:M.item.id}),n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"web_search",input:JSON.stringify({action:M.item.action}),providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"web_search",result:{status:M.item.status},providerExecuted:!0});else if("computer_call"===M.item.type)d[M.output_index]=void 0,n.enqueue({type:"tool-input-end",id:M.item.id}),n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:M.item.status||"completed"},providerExecuted:!0});else if("file_search_call"===M.item.type)d[M.output_index]=void 0,n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"file_search",result:{queries:M.item.queries,results:null!=(g=null==(o=M.item.results)?void 0:o.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text})))?g:null},providerExecuted:!0});else if("code_interpreter_call"===M.item.type)n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"code_interpreter",input:JSON.stringify({code:M.item.code,containerId:M.item.container_id}),providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"code_interpreter",result:{outputs:M.item.outputs},providerExecuted:!0});else if("image_generation_call"===M.item.type)n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"image_generation",result:{result:M.item.result},providerExecuted:!0});else if("message"===M.item.type)n.enqueue({type:"text-end",id:M.item.id});else if(function(e){return dF(e)&&"reasoning"===e.item.type}(M)){const e=f[M.item.id];for(const t of e.summaryParts)n.enqueue({type:"reasoning-end",id:`${M.item.id}:${t}`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:null!=(A=M.item.encrypted_content)?A:null}}});delete f[M.item.id]}}else if(function(e){return"response.function_call_arguments.delta"===e.type}(M)){const e=d[M.output_index];null!=e&&n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:M.delta})}else!function(e){return"response.created"===e.type}(M)?!function(e){return"response.output_text.delta"===e.type}(M)?!function(e){return"response.reasoning_summary_part.added"===e.type}(M)?!function(e){return"response.reasoning_summary_text.delta"===e.type}(M)?!function(e){return"response.completed"===e.type||"response.incomplete"===e.type}(M)?!function(e){return"response.output_text.annotation.added"===e.type}(M)?function(e){return"error"===e.type}(M)&&n.enqueue({type:"error",error:M}):"url_citation"===M.annotation.type?n.enqueue({type:"source",sourceType:"url",id:null!=(k=null==(S=(D=s.config).generateId)?void 0:S.call(D))?k:_A(),url:M.annotation.url,title:M.annotation.title}):"file_citation"===M.annotation.type&&n.enqueue({type:"source",sourceType:"document",id:null!=(N=null==(Q=(x=s.config).generateId)?void 0:Q.call(x))?N:_A(),mediaType:"text/plain",title:null!=(R=null!=(T=M.annotation.quote)?T:M.annotation.filename)?R:"Document",filename:null!=(F=M.annotation.filename)?F:M.annotation.file_id}):(a=eF({finishReason:null==(I=M.response.incomplete_details)?void 0:I.reason,hasFunctionCall:p}),l.inputTokens=M.response.usage.input_tokens,l.outputTokens=M.response.usage.output_tokens,l.totalTokens=M.response.usage.input_tokens+M.response.usage.output_tokens,l.reasoningTokens=null!=(C=null==(w=M.response.usage.output_tokens_details)?void 0:w.reasoning_tokens)?C:void 0,l.cachedInputTokens=null!=(B=null==(_=M.response.usage.input_tokens_details)?void 0:_.cached_tokens)?B:void 0,"string"==typeof M.response.service_tier&&(h=M.response.service_tier)):n.enqueue({type:"reasoning-delta",id:`${M.item_id}:${M.summary_index}`,delta:M.delta,providerMetadata:{openai:{itemId:M.item_id}}}):M.summary_index>0&&(null==(b=f[M.item_id])||b.summaryParts.push(M.summary_index),n.enqueue({type:"reasoning-start",id:`${M.item_id}:${M.summary_index}`,providerMetadata:{openai:{itemId:M.item_id,reasoningEncryptedContent:null!=(E=null==(v=f[M.item_id])?void 0:v.encryptedContent)?E:null}}})):(n.enqueue({type:"text-delta",id:M.item_id,delta:M.delta}),(null==(y=null==(m=e.providerOptions)?void 0:m.openai)?void 0:y.logprobs)&&M.logprobs&&u.push(M.logprobs)):(c=M.response.id,n.enqueue({type:"response-metadata",id:M.response.id,timestamp:new Date(1e3*M.response.created_at),modelId:M.response.model}))},flush(e){const t={openai:{responseId:c}};u.length>0&&(t.openai.logprobs=u),void 0!==h&&(t.openai.serviceTier=h),e.enqueue({type:"finish",finishReason:a,usage:l,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},aF=ug({input_tokens:jh(),input_tokens_details:ug({cached_tokens:jh().nullish()}).nullish(),output_tokens:jh(),output_tokens_details:ug({reasoning_tokens:jh().nullish()}).nullish()}),lF=ug({type:Dg("response.output_text.delta"),item_id:mh(),delta:mh(),logprobs:oF.nullish()}),uF=ug({type:Dg("error"),code:mh(),message:mh(),param:mh().nullish(),sequence_number:jh()}),cF=fg([lF,ug({type:_g(["response.completed","response.incomplete"]),response:ug({incomplete_details:ug({reason:mh()}).nullish(),usage:aF,service_tier:mh().nullish()})}),ug({type:Dg("response.created"),response:ug({id:mh(),created_at:jh(),model:mh(),service_tier:mh().nullish()})}),ug({type:Dg("response.output_item.added"),output_index:jh(),item:gg("type",[ug({type:Dg("message"),id:mh()}),ug({type:Dg("reasoning"),id:mh(),encrypted_content:mh().nullish()}),ug({type:Dg("function_call"),id:mh(),call_id:mh(),name:mh(),arguments:mh()}),ug({type:Dg("web_search_call"),id:mh(),status:mh(),action:ug({type:Dg("search"),query:mh().optional()}).nullish()}),ug({type:Dg("computer_call"),id:mh(),status:mh()}),ug({type:Dg("file_search_call"),id:mh()}),ug({type:Dg("image_generation_call"),id:mh()})])}),ug({type:Dg("response.output_item.done"),output_index:jh(),item:gg("type",[ug({type:Dg("message"),id:mh()}),ug({type:Dg("reasoning"),id:mh(),encrypted_content:mh().nullish()}),ug({type:Dg("function_call"),id:mh(),call_id:mh(),name:mh(),arguments:mh(),status:Dg("completed")}),rF,iF,tF,nF,ug({type:Dg("computer_call"),id:mh(),status:Dg("completed")})])}),ug({type:Dg("response.function_call_arguments.delta"),item_id:mh(),output_index:jh(),delta:mh()}),ug({type:Dg("response.output_text.annotation.added"),annotation:gg("type",[ug({type:Dg("url_citation"),url:mh(),title:mh()}),ug({type:Dg("file_citation"),file_id:mh(),filename:mh().nullish(),index:jh().nullish(),start_index:jh().nullish(),end_index:jh().nullish(),quote:mh().nullish()})])}),ug({type:Dg("response.reasoning_summary_part.added"),item_id:mh(),summary_index:jh()}),ug({type:Dg("response.reasoning_summary_text.delta"),item_id:mh(),summary_index:jh(),delta:mh()}),uF,ug({type:mh()}).loose()]);function dF(e){return"response.output_item.done"===e.type}function pF(e){return"response.output_item.added"===e.type}var fF=ug({include:ag(_g(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:mh().nullish(),logprobs:fg([Hh(),jh().min(1).max(20)]).optional(),maxToolCalls:jh().nullish(),metadata:Xh().nullish(),parallelToolCalls:Hh().nullish(),previousResponseId:mh().nullish(),promptCacheKey:mh().nullish(),reasoningEffort:mh().nullish(),reasoningSummary:mh().nullish(),safetyIdentifier:mh().nullish(),serviceTier:_g(["auto","flex","priority"]).nullish(),store:Hh().nullish(),strictJsonSchema:Hh().nullish(),textVerbosity:_g(["low","medium","high"]).nullish(),user:mh().nullish()}),hF=ug({instructions:mh().nullish(),speed:jh().min(.25).max(4).default(1).nullish()}),gF=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:i,language:o,providerOptions:s}){const a=[],l=await WA({provider:"openai",providerOptions:s,schema:hF}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:i};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?u.response_format=n:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const e={};for(const t in e){const n=e[t];void 0!==n&&(u[t]=n)}}return o&&a.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:u,warnings:a}}async doGenerate(e){var t,n,r;const i=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{requestBody:o,warnings:s}=await this.getArgs(e),{value:a,responseHeaders:l,rawValue:u}=await JA({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:o,failedResponseHandler:dR,successfulResponseHandler:async({response:e,url:t,requestBodyValues:n})=>{const r=EA(e);if(!e.body)throw new go({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(qK){throw new go({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:qK})}},abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:s,request:{body:JSON.stringify(o)},response:{timestamp:i,modelId:this.modelId,headers:l,body:u}}}},AF=ug({include:ag(mh()).optional(),language:mh().optional(),prompt:mh().optional(),temperature:jh().min(0).max(1).default(0).optional(),timestampGranularities:ag(_g(["word","segment"])).default(["segment"]).optional()}),mF={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},yF=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=await WA({provider:"openai",providerOptions:n,schema:AF}),i=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([zm(e)]);i.append("model",this.modelId);const s=function(e){var t;const[n,r=""]=e.toLowerCase().split("/");return null!=(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])?t:r}(t);if(i.append("file",new File([o],"audio",{type:t}),`audio.${s}`),r){const e={include:r.include,language:r.language,prompt:r.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:r.temperature,timestamp_granularities:r.timestampGranularities};for(const[t,n]of Object.entries(e))if(null!=n)if(Array.isArray(n))for(const e of n)i.append(`${t}[]`,String(e));else i.append(t,String(n))}return{formData:i,warnings:[]}}async doGenerate(e){var t,n,r,i,o,s,a,l;const u=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{formData:c,warnings:d}=await this.getArgs(e),{value:p,responseHeaders:f,rawValue:h}=await(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s})=>KA({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s}))({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),formData:c,failedResponseHandler:dR,successfulResponseHandler:tm(bF),abortSignal:e.abortSignal,fetch:this.config.fetch}),g=null!=p.language&&p.language in mF?mF[p.language]:void 0;return{text:p.text,segments:null!=(a=null!=(s=null==(i=p.segments)?void 0:i.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end})))?s:null==(o=p.words)?void 0:o.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end})))?a:[],language:g,durationInSeconds:null!=(l=p.duration)?l:void 0,warnings:d,response:{timestamp:u,modelId:this.modelId,headers:f,body:h}}}},bF=ug({text:mh(),language:mh().nullish(),duration:jh().nullish(),words:ag(ug({word:mh(),start:jh(),end:jh()})).nullish(),segments:ag(ug({id:jh(),seek:jh(),start:jh(),end:jh(),text:mh(),tokens:ag(jh()),temperature:jh(),avg_logprob:jh(),compression_ratio:jh(),no_speech_prob:jh()})).nullish()});function vF(e={}){var t,n;const r=null!=(t=Wm(e.baseURL))?t:"https://api.openai.com/v1",i=null!=(n=e.name)?n:"openai",o=()=>({Authorization:`Bearer ${TA({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),s=t=>new xR(t,{provider:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),a=t=>new RR(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),l=t=>new yF(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),u=t=>new gF(t,{provider:`${i}.speech`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),c=e=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(e)},d=t=>new sF(t,{provider:`${i}.responses`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(e){return c(e)};return p.languageModel=c,p.chat=t=>new gR(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),p.completion=t=>new _R(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),p.responses=d,p.embedding=s,p.textEmbedding=s,p.textEmbeddingModel=s,p.image=a,p.imageModel=a,p.transcription=l,p.transcriptionModel=l,p.speech=u,p.speechModel=u,p.tools=VR,p}function EF(){const{getEnvironmentContext:e,getContextString:t,getCompactContextString:n,refreshContext:r,clearCache:i}=ST(),[o,s]=qe.useState(null),[a,l]=qe.useState(null),[u,c]=qe.useState(null),[d,p]=qe.useState(!0),[f,h]=qe.useState(null),g=qe.useCallback(async(r=!1)=>{try{p(!0),h(null);const[i,o,a]=await Promise.all([e(r),t(),n()]);s(i),l(o),c(a)}catch(i){const e=i instanceof Error?i.message:"Failed to load environment context";h(e),ex.error("Environment context error:",i)}finally{p(!1)}},[e,t,n]),A=qe.useCallback(async()=>{await r(),await g(!0)},[r,g]);return qe.useEffect(()=>{g()},[g]),qe.useEffect(()=>{const e=setInterval(()=>{d||g()},3e5);return()=>clearInterval(e)},[g,d]),{context:o,contextString:a,compactContext:u,isLoading:d,error:f,refresh:A,clearCache:i}}vF();var IF=ug({type:Dg("error"),error:ug({type:mh(),message:mh()})}),wF=XA({errorSchema:IF,errorToMessage:e=>e.error.message}),CF=ug({citations:ug({enabled:Hh()}).optional(),title:mh().optional(),context:mh().optional()}),_F=ug({sendReasoning:Hh().optional(),thinking:ug({type:fg([Dg("enabled"),Dg("disabled")]),budgetTokens:jh().optional()}).optional(),disableParallelToolUse:Hh().optional(),cacheControl:ug({type:Dg("ephemeral"),ttl:fg([Dg("5m"),Dg("1h")]).optional()}).optional()});function BF(e){var t;const n=null==e?void 0:e.anthropic;return null!=(t=null==n?void 0:n.cacheControl)?t:null==n?void 0:n.cache_control}var DF=ug({maxUses:jh().optional(),allowedDomains:ag(mh()).optional(),blockedDomains:ag(mh()).optional(),userLocation:ug({type:Dg("approximate"),city:mh().optional(),region:mh().optional(),country:mh().optional(),timezone:mh().optional()}).optional()}),SF=ag(ug({url:mh(),title:mh(),pageAge:mh().nullable(),encryptedContent:mh(),type:mh()})),kF=VA({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:ug({query:mh()}),outputSchema:SF});function xF(e){return"object"==typeof e&&null!==e&&"type"in e&&"web_search_20250305"===e.type}var QF=ug({type:Dg("code_execution_result"),stdout:mh(),stderr:mh(),return_code:jh()}),NF=VA({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:ug({code:mh()}),outputSchema:QF});function TF(e){if("string"==typeof e)return Buffer.from(e,"base64").toString("utf-8");if(e instanceof Uint8Array)return(new TextDecoder).decode(e);if(e instanceof URL)throw new ps({functionality:"URL-based text documents are not supported for citations"});throw new ps({functionality:"unsupported data type for text documents: "+typeof e})}async function RF({prompt:e,sendReasoning:t,warnings:n}){var r,i,o,s,a;const l=new Set,u=function(e){const t=[];let n;for(const r of e){const{role:e}=r;switch(e){case"system":"system"!==(null==n?void 0:n.type)&&(n={type:"system",messages:[]},t.push(n)),n.messages.push(r);break;case"assistant":"assistant"!==(null==n?void 0:n.type)&&(n={type:"assistant",messages:[]},t.push(n)),n.messages.push(r);break;case"user":case"tool":"user"!==(null==n?void 0:n.type)&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break;default:throw new Error(`Unsupported role: ${e}`)}}return t}(e);let c;const d=[];async function p(e){var t,n;const r=await WA({provider:"anthropic",providerOptions:e,schema:CF});return null!=(n=null==(t=null==r?void 0:r.citations)?void 0:t.enabled)&&n}async function f(e){const t=await WA({provider:"anthropic",providerOptions:e,schema:CF});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let h=0;h<u.length;h++){const e=u[h],g=h===u.length-1,A=e.type;switch(A){case"system":if(null!=c)throw new ps({functionality:"Multiple system messages that are separated by user/assistant messages"});c=e.messages.map(({content:e,providerOptions:t})=>({type:"text",text:e,cache_control:BF(t)}));break;case"user":{const t=[];for(const n of e.messages){const{role:e,content:a}=n;switch(e){case"user":for(let e=0;e<a.length;e++){const s=a[e],u=e===a.length-1,c=null!=(r=BF(s.providerOptions))?r:u?BF(n.providerOptions):void 0;switch(s.type){case"text":t.push({type:"text",text:s.text,cache_control:c});break;case"file":if(s.mediaType.startsWith("image/"))t.push({type:"image",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"image/*"===s.mediaType?"image/jpeg":s.mediaType,data:Hm(s.data)},cache_control:c});else if("application/pdf"===s.mediaType){l.add("pdfs-2024-09-25");const e=await p(s.providerOptions),n=await f(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"application/pdf",data:Hm(s.data)},title:null!=(i=n.title)?i:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}else{if("text/plain"!==s.mediaType)throw new ps({functionality:`media type: ${s.mediaType}`});{const e=await p(s.providerOptions),n=await f(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"text",media_type:"text/plain",data:TF(s.data)},title:null!=(o=n.title)?o:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}}}}break;case"tool":for(let e=0;e<a.length;e++){const r=a[e],i=e===a.length-1,o=null!=(s=BF(r.providerOptions))?s:i?BF(n.providerOptions):void 0,l=r.output;let u;switch(l.type){case"content":u=l.value.map(e=>{switch(e.type){case"text":return{type:"text",text:e.text,cache_control:void 0};case"media":if(e.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data},cache_control:void 0};throw new ps({functionality:`media type: ${e.mediaType}`})}});break;case"text":case"error-text":u=l.value;break;default:u=JSON.stringify(l.value)}t.push({type:"tool_result",tool_use_id:r.toolCallId,content:u,is_error:"error-text"===l.type||"error-json"===l.type||void 0,cache_control:o})}break;default:throw new Error(`Unsupported role: ${e}`)}}d.push({role:"user",content:t});break}case"assistant":{const r=[];for(let i=0;i<e.messages.length;i++){const o=e.messages[i],s=i===e.messages.length-1,{content:l}=o;for(let e=0;e<l.length;e++){const i=l[e],u=e===l.length-1,c=null!=(a=BF(i.providerOptions))?a:u?BF(o.providerOptions):void 0;switch(i.type){case"text":r.push({type:"text",text:g&&s&&u?i.text.trim():i.text,cache_control:c});break;case"reasoning":if(t){const e=await WA({provider:"anthropic",providerOptions:i.providerOptions,schema:UF});null!=e?null!=e.signature?r.push({type:"thinking",thinking:i.text,signature:e.signature,cache_control:c}):null!=e.redactedData?r.push({type:"redacted_thinking",data:e.redactedData,cache_control:c}):n.push({type:"other",message:"unsupported reasoning metadata"}):n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":if(i.providerExecuted){if("web_search"===i.toolName){r.push({type:"server_tool_use",id:i.toolCallId,name:"web_search",input:i.input,cache_control:c});break}if("code_execution"===i.toolName){r.push({type:"server_tool_use",id:i.toolCallId,name:"code_execution",input:i.input,cache_control:c});break}n.push({type:"other",message:`provider executed tool call for tool ${i.toolName} is not supported`});break}r.push({type:"tool_use",id:i.toolCallId,name:i.toolName,input:i.input,cache_control:c});break;case"tool-result":if("web_search"===i.toolName){const e=i.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${i.toolName} is not supported`});break}const t=SF.parse(e.value);r.push({type:"web_search_tool_result",tool_use_id:i.toolCallId,content:t.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:c});break}if("code_execution"===i.toolName){const e=i.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${i.toolName} is not supported`});break}const t=QF.parse(e.value);r.push({type:"code_execution_tool_result",tool_use_id:i.toolCallId,content:{type:t.type,stdout:t.stdout,stderr:t.stderr,return_code:t.return_code},cache_control:c});break}n.push({type:"other",message:`provider executed tool result for tool ${i.toolName} is not supported`})}}}d.push({role:"assistant",content:r});break}default:throw new Error(`content type: ${A}`)}}return{prompt:{system:c,messages:d},betas:l}}function FF({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}var MF={webSearchResult:ug({type:Dg("web_search_result_location"),cited_text:mh(),url:mh(),title:mh(),encrypted_index:mh()}),pageLocation:ug({type:Dg("page_location"),cited_text:mh(),document_index:jh(),document_title:mh().nullable(),start_page_number:jh(),end_page_number:jh()}),charLocation:ug({type:Dg("char_location"),cited_text:mh(),document_index:jh(),document_title:mh().nullable(),start_char_index:jh(),end_char_index:jh()})},OF=gg("type",[MF.webSearchResult,MF.pageLocation,MF.charLocation]);function $F(e,t,n,r){if("page_location"===e.type||"char_location"===e.type){const i=function(e,t,n){var r;const i=t[e.document_index];if(!i)return null;const o="page_location"===e.type?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:"source",sourceType:"document",id:n(),mediaType:i.mediaType,title:null!=(r=e.document_title)?r:i.title,filename:i.filename,providerMetadata:{anthropic:o}}}(e,t,n);i&&r(i)}}gg("type",[MF.pageLocation,MF.charLocation]);var LF=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:_A}supportsUrl(e){return"https:"===e.protocol}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var f,h,g;const A=[];null!=o&&A.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=s&&A.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=u&&A.push({type:"unsupported-setting",setting:"seed"}),"json"===(null==l?void 0:l.type)&&(null==l.schema?A.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):null!=c&&A.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));const m="json"===(null==l?void 0:l.type)&&null!=l.schema?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:l.schema}:void 0,y=await WA({provider:"anthropic",providerOptions:p,schema:_F}),{prompt:b,betas:v}=await RF({prompt:e,sendReasoning:null==(f=null==y?void 0:y.sendReasoning)||f,warnings:A}),E="enabled"===(null==(h=null==y?void 0:y.thinking)?void 0:h.type),I=null==(g=null==y?void 0:y.thinking)?void 0:g.budgetTokens,w={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:a,...E&&{thinking:{type:"enabled",budget_tokens:I}},system:b.system,messages:b.messages};if(E){if(null==I)throw new ps({functionality:"thinking requires a budget"});null!=w.temperature&&(w.temperature=void 0,A.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=i&&(w.top_k=void 0,A.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),null!=r&&(w.top_p=void 0,A.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),w.max_tokens=t+I}const{tools:C,toolChoice:_,toolWarnings:B,betas:D}=function({tools:e,toolChoice:t,disableParallelToolUse:n}){e=(null==e?void 0:e.length)?e:void 0;const r=[],i=new Set;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};const o=[];for(const a of e)if(xF(a))o.push(a);else switch(a.type){case"function":const e=BF(a.providerOptions);o.push({name:a.name,description:a.description,input_schema:a.inputSchema,cache_control:e});break;case"provider-defined":switch(a.id){case"anthropic.computer_20250124":i.add("computer-use-2025-01-24"),o.push({name:"computer",type:"computer_20250124",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.computer_20241022":i.add("computer-use-2024-10-22"),o.push({name:"computer",type:"computer_20241022",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.text_editor_20250124":i.add("computer-use-2025-01-24"),o.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":i.add("computer-use-2024-10-22"),o.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":i.add("computer-use-2025-01-24"),o.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":i.add("computer-use-2025-01-24"),o.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":i.add("computer-use-2024-10-22"),o.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{const e=DF.parse(a.args);o.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}case"anthropic.code_execution_20250522":i.add("code-execution-2025-05-22"),o.push({type:"code_execution_20250522",name:"code_execution"});break;default:r.push({type:"unsupported-tool",tool:a})}break;default:r.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:o,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};const s=t.type;switch(s){case"auto":return{tools:o,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:r,betas:i};case"required":return{tools:o,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:r,betas:i};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case"tool":return{tools:o,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new ps({functionality:`tool choice type: ${s}`})}}(null!=m?{tools:[m],toolChoice:{type:"tool",toolName:m.name},disableParallelToolUse:!0}:{tools:null!=c?c:[],toolChoice:d,disableParallelToolUse:null==y?void 0:y.disableParallelToolUse});return{args:{...w,tools:C,tool_choice:_},warnings:[...A,...B],betas:new Set([...v,...D]),usesJsonResponseTool:null!=m}}async getHeaders({betas:e,headers:t}){return bA(await YA(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{},t)}buildRequestUrl(e){var t,n,r;return null!=(r=null==(n=(t=this.config).buildRequestUrl)?void 0:n.call(t,this.config.baseURL,e))?r:`${this.config.baseURL}/messages`}transformRequestBody(e){var t,n,r;return null!=(r=null==(n=(t=this.config).transformRequestBody)?void 0:n.call(t,e))?r:e}extractCitationDocuments(e){return e.filter(e=>"user"===e.role).flatMap(e=>e.content).filter(e=>{var t,n;if("file"!==e.type)return!1;if("application/pdf"!==e.mediaType&&"text/plain"!==e.mediaType)return!1;const r=null==(t=e.providerOptions)?void 0:t.anthropic,i=null==r?void 0:r.citations;return null!=(n=null==i?void 0:i.enabled)&&n}).map(e=>{var t;const n=e;return{title:null!=(t=n.filename)?t:"Untitled Document",filename:n.filename,mediaType:n.mediaType}})}async doGenerate(e){var t,n,r,i,o;const{args:s,warnings:a,betas:l,usesJsonResponseTool:u}=await this.getArgs(e),c=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:p,rawValue:f}=await JA({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:l,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:wF,successfulResponseHandler:tm(PF),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=[];for(const g of p.content)switch(g.type){case"text":if(!u&&(h.push({type:"text",text:g.text}),g.citations))for(const e of g.citations)$F(e,c,this.generateId,e=>h.push(e));break;case"thinking":h.push({type:"reasoning",text:g.thinking,providerMetadata:{anthropic:{signature:g.signature}}});break;case"redacted_thinking":h.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:g.data}}});break;case"tool_use":h.push(u?{type:"text",text:JSON.stringify(g.input)}:{type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input)});break;case"server_tool_use":"web_search"!==g.name&&"code_execution"!==g.name||h.push({type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input),providerExecuted:!0});break;case"web_search_tool_result":if(Array.isArray(g.content)){h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",result:g.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}}),providerExecuted:!0});for(const e of g.content)h.push({type:"source",sourceType:"url",id:this.generateId(),url:e.url,title:e.title,providerMetadata:{anthropic:{pageAge:null!=(t=e.page_age)?t:null}}})}else h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0});break;case"code_execution_tool_result":"code_execution_result"===g.content.type?h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",result:{type:g.content.type,stdout:g.content.stdout,stderr:g.content.stderr,return_code:g.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===g.content.type&&h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0})}return{content:h,finishReason:FF({finishReason:p.stop_reason,isJsonResponseFromTool:u}),usage:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,totalTokens:p.usage.input_tokens+p.usage.output_tokens,cachedInputTokens:null!=(n=p.usage.cache_read_input_tokens)?n:void 0},request:{body:s},response:{id:null!=(r=p.id)?r:void 0,modelId:null!=(i=p.model)?i:void 0,headers:d,body:f},warnings:a,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:null!=(o=p.usage.cache_creation_input_tokens)?o:null}}}}async doStream(e){const{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),s={...t,stream:!0},{responseHeaders:a,value:l}=await JA({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:wF,successfulResponseHandler:em(jF),abortSignal:e.abortSignal,fetch:this.config.fetch});let u="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={};let p,f;const h=this.generateId;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,s,a,l,g,A,m;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const y=t.value;switch(y.type){case"ping":return;case"content_block_start":{const e=y.content_block.type;switch(f=e,e){case"text":return d[y.index]={type:"text"},void n.enqueue({type:"text-start",id:String(y.index)});case"thinking":return d[y.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(y.index)});case"redacted_thinking":return d[y.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(y.index),providerMetadata:{anthropic:{redactedData:y.content_block.data}}});case"tool_use":return d[y.index]=i?{type:"text"}:{type:"tool-call",toolCallId:y.content_block.id,toolName:y.content_block.name,input:""},void n.enqueue(i?{type:"text-start",id:String(y.index)}:{type:"tool-input-start",id:y.content_block.id,toolName:y.content_block.name});case"server_tool_use":return void("web_search"!==y.content_block.name&&"code_execution"!==y.content_block.name||(d[y.index]={type:"tool-call",toolCallId:y.content_block.id,toolName:y.content_block.name,input:"",providerExecuted:!0},n.enqueue({type:"tool-input-start",id:y.content_block.id,toolName:y.content_block.name,providerExecuted:!0})));case"web_search_tool_result":{const e=y.content_block;if(Array.isArray(e.content)){n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}}),providerExecuted:!0});for(const t of e.content)n.enqueue({type:"source",sourceType:"url",id:h(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(r=t.page_age)?r:null}}})}else n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{const e=y.content_block;return void("code_execution_result"===e.content.type?n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===e.content.type&&n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0}))}default:throw new Error(`Unsupported content block type: ${e}`)}}case"content_block_stop":if(null!=d[y.index]){const e=d[y.index];switch(e.type){case"text":n.enqueue({type:"text-end",id:String(y.index)});break;case"reasoning":n.enqueue({type:"reasoning-end",id:String(y.index)});break;case"tool-call":i||(n.enqueue({type:"tool-input-end",id:e.toolCallId}),n.enqueue(e))}delete d[y.index]}return void(f=void 0);case"content_block_delta":{const e=y.delta.type;switch(e){case"text_delta":if(i)return;return void n.enqueue({type:"text-delta",id:String(y.index),delta:y.delta.text});case"thinking_delta":return void n.enqueue({type:"reasoning-delta",id:String(y.index),delta:y.delta.thinking});case"signature_delta":return void("thinking"===f&&n.enqueue({type:"reasoning-delta",id:String(y.index),delta:"",providerMetadata:{anthropic:{signature:y.delta.signature}}}));case"input_json_delta":{const e=d[y.index],t=y.delta.partial_json;if(i){if("text"!==(null==e?void 0:e.type))return;n.enqueue({type:"text-delta",id:String(y.index),delta:t})}else{if("tool-call"!==(null==e?void 0:e.type))return;n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t}),e.input+=t}return}case"citations_delta":return void $F(y.delta.citation,o,h,e=>n.enqueue(e));default:throw new Error(`Unsupported delta type: ${e}`)}}case"message_start":return c.inputTokens=y.message.usage.input_tokens,c.cachedInputTokens=null!=(s=y.message.usage.cache_read_input_tokens)?s:void 0,p={anthropic:{usage:y.message.usage,cacheCreationInputTokens:null!=(a=y.message.usage.cache_creation_input_tokens)?a:null}},void n.enqueue({type:"response-metadata",id:null!=(l=y.message.id)?l:void 0,modelId:null!=(g=y.message.model)?g:void 0});case"message_delta":return c.outputTokens=y.usage.output_tokens,c.totalTokens=(null!=(A=c.inputTokens)?A:0)+(null!=(m=y.usage.output_tokens)?m:0),void(u=FF({finishReason:y.delta.stop_reason,isJsonResponseFromTool:i}));case"message_stop":return void n.enqueue({type:"finish",finishReason:u,usage:c,providerMetadata:p});case"error":return void n.enqueue({type:"error",error:y.error});default:throw new Error(`Unsupported chunk type: ${y}`)}}})),request:{body:s},response:{headers:a}}}},PF=ug({type:Dg("message"),id:mh().nullish(),model:mh().nullish(),content:ag(gg("type",[ug({type:Dg("text"),text:mh(),citations:ag(OF).optional()}),ug({type:Dg("thinking"),thinking:mh(),signature:mh()}),ug({type:Dg("redacted_thinking"),data:mh()}),ug({type:Dg("tool_use"),id:mh(),name:mh(),input:tg()}),ug({type:Dg("server_tool_use"),id:mh(),name:mh(),input:Eg(mh(),tg()).nullish()}),ug({type:Dg("web_search_tool_result"),tool_use_id:mh(),content:fg([ag(ug({type:Dg("web_search_result"),url:mh(),title:mh(),encrypted_content:mh(),page_age:mh().nullish()})),ug({type:Dg("web_search_tool_result_error"),error_code:mh()})])}),ug({type:Dg("code_execution_tool_result"),tool_use_id:mh(),content:fg([ug({type:Dg("code_execution_result"),stdout:mh(),stderr:mh(),return_code:jh()}),ug({type:Dg("code_execution_tool_result_error"),error_code:mh()})])})])),stop_reason:mh().nullish(),usage:dg({input_tokens:jh(),output_tokens:jh(),cache_creation_input_tokens:jh().nullish(),cache_read_input_tokens:jh().nullish()})}),jF=gg("type",[ug({type:Dg("message_start"),message:ug({id:mh().nullish(),model:mh().nullish(),usage:dg({input_tokens:jh(),output_tokens:jh(),cache_creation_input_tokens:jh().nullish(),cache_read_input_tokens:jh().nullish()})})}),ug({type:Dg("content_block_start"),index:jh(),content_block:gg("type",[ug({type:Dg("text"),text:mh()}),ug({type:Dg("thinking"),thinking:mh()}),ug({type:Dg("tool_use"),id:mh(),name:mh()}),ug({type:Dg("redacted_thinking"),data:mh()}),ug({type:Dg("server_tool_use"),id:mh(),name:mh(),input:Eg(mh(),tg()).nullish()}),ug({type:Dg("web_search_tool_result"),tool_use_id:mh(),content:fg([ag(ug({type:Dg("web_search_result"),url:mh(),title:mh(),encrypted_content:mh(),page_age:mh().nullish()})),ug({type:Dg("web_search_tool_result_error"),error_code:mh()})])}),ug({type:Dg("code_execution_tool_result"),tool_use_id:mh(),content:fg([ug({type:Dg("code_execution_result"),stdout:mh(),stderr:mh(),return_code:jh()}),ug({type:Dg("code_execution_tool_result_error"),error_code:mh()})])})])}),ug({type:Dg("content_block_delta"),index:jh(),delta:gg("type",[ug({type:Dg("input_json_delta"),partial_json:mh()}),ug({type:Dg("text_delta"),text:mh()}),ug({type:Dg("thinking_delta"),thinking:mh()}),ug({type:Dg("signature_delta"),signature:mh()}),ug({type:Dg("citations_delta"),citation:OF})])}),ug({type:Dg("content_block_stop"),index:jh()}),ug({type:Dg("error"),error:ug({type:mh(),message:mh()})}),ug({type:Dg("message_delta"),delta:ug({stop_reason:mh().nullish()}),usage:ug({output_tokens:jh()})}),ug({type:Dg("message_stop")}),ug({type:Dg("ping")})]),UF=ug({signature:mh().optional(),redactedData:mh().optional()}),zF={bash_20241022:ZA({id:"anthropic.bash_20241022",name:"bash",inputSchema:cA.object({command:cA.string(),restart:cA.boolean().optional()})}),bash_20250124:ZA({id:"anthropic.bash_20250124",name:"bash",inputSchema:cA.object({command:cA.string(),restart:cA.boolean().optional()})}),codeExecution_20250522:(e={})=>NF(e),computer_20241022:ZA({id:"anthropic.computer_20241022",name:"computer",inputSchema:ug({action:_g(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:ag(jh().int()).optional(),text:mh().optional()})}),computer_20250124:ZA({id:"anthropic.computer_20250124",name:"computer",inputSchema:ug({action:_g(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:bg([jh().int(),jh().int()]).optional(),duration:jh().optional(),scroll_amount:jh().optional(),scroll_direction:_g(["up","down","left","right"]).optional(),start_coordinate:bg([jh().int(),jh().int()]).optional(),text:mh().optional()})}),textEditor_20241022:ZA({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:ug({command:_g(["view","create","str_replace","insert","undo_edit"]),path:mh(),file_text:mh().optional(),insert_line:jh().int().optional(),new_str:mh().optional(),old_str:mh().optional(),view_range:ag(jh().int()).optional()})}),textEditor_20250124:ZA({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:ug({command:_g(["view","create","str_replace","insert","undo_edit"]),path:mh(),file_text:mh().optional(),insert_line:jh().int().optional(),new_str:mh().optional(),old_str:mh().optional(),view_range:ag(jh().int()).optional()})}),textEditor_20250429:ZA({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:ug({command:_g(["view","create","str_replace","insert"]),path:mh(),file_text:mh().optional(),insert_line:jh().int().optional(),new_str:mh().optional(),old_str:mh().optional(),view_range:ag(jh().int()).optional()})}),webSearch_20250305:(e={})=>kF(e)};function GF(e={}){var t;const n=null!=(t=Wm(e.baseURL))?t:"https://api.anthropic.com/v1",r=()=>({"anthropic-version":"2023-06-01","x-api-key":TA({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...e.headers}),i=t=>{var i;return new LF(t,{provider:"anthropic.messages",baseURL:n,headers:r,fetch:e.fetch,generateId:null!=(i=e.generateId)?i:_A,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},o=function(e){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(e)};return o.languageModel=i,o.chat=i,o.messages=i,o.textEmbeddingModel=e=>{throw new Vo({modelId:e,modelType:"textEmbeddingModel"})},o.imageModel=e=>{throw new Vo({modelId:e,modelType:"imageModel"})},o.tools=zF,o}GF();const HF={plan:{name:"PLAN",description:"Analysis and planning without making changes",color:"#3B82F6",allowToolExecution:!1,systemPromptAddition:"You are currently in PLAN mode. Focus on analysis, planning, and suggesting approaches without executing tools or making changes. Break down complex tasks, explain your reasoning, and provide detailed implementation strategies."},act:{name:"ACT",description:"Full execution with tool access",color:"#10B981",allowToolExecution:!0,systemPromptAddition:"You are currently in ACT mode. You have full access to tools and can execute changes, run commands, and modify files as needed to complete tasks."}},WF=qe.createContext(null);function qF({children:e}){const[t,n]=qe.useState("act"),r=HF[t],i=qe.useCallback(()=>{n(e=>"plan"===e?"act":"plan")},[]),o=qe.useCallback(e=>{n(e)},[]),s=r.allowToolExecution;return We.jsx(WF.Provider,{value:{currentMode:t,modeConfig:r,switchMode:i,setMode:o,isToolExecutionAllowed:s},children:e})}function JF(){const e=qe.useContext(WF);if(!e)throw new Error("useMode must be used inside ModeProvider");return e}const KF=qe.createContext(void 0),ZF=({children:e})=>{const{context:t}=EF(),{sessionId:n,firebaseUser:r}=FT(),{currentMode:i}=JF(),[o,s]=qe.useState({"x-platform-type":process.platform,"x-sandbox-type":"sandbox-exec"===process.env.SANDBOX?"exec":null!=process.env.SANDBOX?"generic":"none","x-folder-type":kT()?"versioned":"unversioned","x-client-type":"cli"}),[a,l]=qe.useState([]),[u,c]=qe.useState(null),[d,p]=qe.useState(null);qe.useEffect(()=>{if(!r)return;(async()=>{const e=await r.getIdToken();s(r=>({...r,...n?{"x-session-id":n}:{},Authorization:`Bearer ${e}`,"x-agent-mode":i,...t?{"x-working-directory":t.workingDirectory,"x-project-type":t.projectInfo.projectType,"x-has-git":t.projectInfo.isGitRepository.toString(),"x-context-timestamp":t.contextGenerated.toString()}:{}}))})()},[r,n,t,i]);const f=qe.useMemo(()=>function(e,{separator:t=":",languageModelMiddleware:n}={}){const r=new wI({separator:t,languageModelMiddleware:n});for(const[i,o]of Object.entries(e))r.registerProvider({id:i,provider:o});return r}({anthropic:GF({baseURL:"https://backend-service-prod.embedder.dev/api/v1/proxy/anthropic/",apiKey:"embedder-cli",headers:o}),openai:vF({baseURL:"https://backend-service-prod.embedder.dev/api/v1/proxy/openai/",apiKey:"embedder-cli",headers:o}),google:uR({baseURL:"https://backend-service-prod.embedder.dev/api/v1/proxy/google/",apiKey:"embedder-cli",headers:o})},{separator:" > "}),[o]);return qe.useEffect(()=>{p(u?f.languageModel(`${u.provider} > ${u.name}`):null)},[u,f]),We.jsx(KF.Provider,{value:{registry:f,languageModel:d,availableModels:a,selectedModel:u,setAvailableModels:l,setSelectedModel:c,setHeaders:s,headers:o},children:e})},VF=()=>{const e=qe.useContext(KF);if(!e)throw new Error("useAI must be used within AIProvider");return e};function YF(e){const[t,n]=qe.useState(null),[r,i]=qe.useState(null),[o,s]=qe.useState([]),[a,l]=qe.useState([]),[u,c]=qe.useState(!0),[d,p]=qe.useState(null),[f,h]=qe.useState(null),{setHeaders:g}=VF(),{loggedIn:A,backendUser:m,apiFetch:y}=FT(),{setAvailableModels:b,setSelectedModel:v}=VF(),{setContext:E}=xw(),{fetchDocuments:I,clear:w}=tx();qe.useEffect(()=>{if(!A||!m||!y)return;let t=!1;return(async()=>{try{const r=y(`api/v1/users/${m.id}/teams`),o=y("api/v1/models"),[a,u]=await Promise.all([r,o]);if(t)return;if(!a||!u)return void e("Failed to fetch user data");if(s(a),b(u),u.length>0){const e=(()=>{if(!K(uT))return null;try{const e=V(uT,"utf8");return JSON.parse(e)}catch{return null}})(),t=e&&u.find(t=>t.provider===e.provider&&t.name===e.name)||u[0];v(t)}const d=await Promise.all(a.map(e=>y(`api/v1/teams/${e.id}/projects`)));if(t)return;const p=d.filter(e=>Array.isArray(e)).flat();l(p);let f=null,h=null;if(1===a.length&&null!=a[0]&&(f=a[0]),1===p.length&&(h=p[0],f||(f=a.find(e=>e.id===h?.teamId)||null)),!f||!h){const e=(e=>{if(!K(cT))return null;try{const t=V(cT,"utf8");return JSON.parse(t)[e]||null}catch{return null}})(process.cwd());if(e){const t=a.find(t=>t.id===e.teamId),n=p.find(t=>t.id===e.projectId);t&&n&&n.teamId===t.id&&(f=t,h=n)}}f&&n(f),h&&i(h),c(!1)}catch(qK){t||(e("Failed to fetch user data"),$.captureException(qK))}})(),()=>{t=!0}},[A,m,y,b,e,v]),qe.useEffect(()=>{E(t?.id||null,r?.id||null),g(e=>({...e,"x-project-id":r?.id||""})),r?.id&&y?I(r.id,y):w()},[t,r,E,y,I,w]),qe.useEffect(()=>{if(t&&r)try{gT(process.cwd(),t.id,r.id)}catch(qK){ex.warn("Failed to cache workspace selection:",qK)}},[t,r]);return{team:t,setTeam:n,project:r,setProject:i,teams:o,setTeams:s,projects:a,setProjects:l,createProject:async(n,r=!1)=>{if(!y||!t)return;const o=new AbortController,s=setTimeout(()=>o.abort(),6e4);try{const s=await y("api/v1/projects",{method:"POST",body:JSON.stringify({name:n,teamId:t.id}),signal:o.signal});if(!s)return void e("Failed to create project");l(e=>[...e,s]),r&&i(s)}catch(qK){ex.error("Error creating project:",qK),e("Failed to create project")}finally{clearTimeout(s)}},loading:u,previousProject:d,setPreviousProject:p,previousTeam:f,setPreviousTeam:h}}function XF(e){const t=function(e){const t=v.resolve(e);return he.createHash("sha256").update(t).digest("hex").substring(0,16)}(e);return v.join(G.homedir(),".embedder","conversations",t)}function eM(e){return v.join(XF(e),"active.json")}function tM(e){return v.join(XF(e),"index.json")}function nM(e,t){const n=t.replace(/[^a-zA-Z0-9-_]/g,"_");return v.join(XF(e),`${n}.json`)}const rM={};function iM(e){return rM[e]||[]}function oM(e,t){rM[e]=t}const sM={"gpt-5-2025-08-07":{providerID:"openai",modelID:"gpt-5-2025-08-07",limits:{context:4e5,output:128e3},compressionThreshold:.9},"claude-opus-4-20250514":{providerID:"anthropic",modelID:"claude-opus-4-20250514",limits:{context:2e5,output:32e3},compressionThreshold:.9},"claude-sonnet-4-20250514":{providerID:"anthropic",modelID:"claude-sonnet-4-20250514",limits:{context:2e5,output:64e3},compressionThreshold:.9},"claude-sonnet-4-5-20250929":{providerID:"anthropic",modelID:"claude-sonnet-4-5-20250929",limits:{context:2e5,output:64e3},compressionThreshold:.9},"claude-haiku-4-5-20251001":{providerID:"anthropic",modelID:"claude-haiku-4-5-20251001",limits:{context:2e5,output:8192},compressionThreshold:.9},"gemini-2.5-pro":{providerID:"google",modelID:"gemini-2.5-pro",limits:{context:1048576,output:65536},compressionThreshold:.9},"gemini-2.5-flash":{providerID:"google",modelID:"gemini-2.5-flash",limits:{context:1048576,output:65536},compressionThreshold:.9}};function aM(e){return sM[e]||null}function lM(e,t){const n=function(e){const t=Math.min(e.limits.output,32e3),n=e.limits.context-t;return Math.max(n*e.compressionThreshold,0)}(t);return e>n}function uM(e){return{providerID:e||"unknown",modelID:"unknown",limits:{context:8192,output:2048},compressionThreshold:.7}}function cM(e){if(e.includes(":")){const t=e.split(":");return(t[1]??t[0]??"").toString()}return e.includes("/")&&e.split("/").pop()||e}function dM(e,t){const n=Math.min(t.limits.output,32e3),r=t.limits.context-n;return Math.min(100,Math.round(e/r*100))}const pM=10,fM=15,hM=8,gM=20,AM=25;function mM(e){if(!e)return 0;const t=Math.ceil(e.length/4);return t+Math.ceil(.1*t)}function yM(e){if("role"in e&&"tool-group"!==e.role){const n=e,r="string"==typeof(t=n.content)?mM(t):Array.isArray(t)?t.reduce((e,t)=>{if("string"==typeof t)return e+mM(t);if("object"==typeof t&&null!==t){const n=t.text||t.content||"",r=t.type||"";let i=mM(n);return"image"===r||"image_url"===r?i+=85:"tool_use"!==r&&"tool_result"!==r||(i+=AM),e+i}return e},0):0;let i=0;switch(n.role){case"user":default:i=pM;break;case"assistant":i=fM;break;case"system":i=hM}return r+i}var t;if("role"in e&&"tool-group"===e.role){const t=e;let n=gM;for(const e of t.toolGroup.tools)n+=AM,n+=mM(e.name),n+=mM(e.description),e.result&&("string"==typeof e.result?n+=mM(e.result):"object"==typeof e.result&&(n+=mM(JSON.stringify(e.result))));return n}return 0}function bM(e){return e.reduce((e,t)=>e+yM(t),0)}class vM{static compressionStates=new Map;static shouldCompressMessages(e,t){const n=aM(cM(t.modelId||t.name))||uM(t.provider);return lM(bM(e),n)}static isCompressing(e){return this.compressionStates.has(e)}static async compressConversation(e,t,n,r,i=!1){if(this.isCompressing(t))return{success:!1,originalTokenCount:0,newTokenCount:0,compressedMessages:e,error:"Compression already in progress for this session"};if(!i&&!this.shouldCompressMessages(e,n)){const t=bM(e);return{success:!1,originalTokenCount:t,newTokenCount:t,compressedMessages:e,error:"Compression not needed"}}this.compressionStates.set(t,{isCompressing:!0,sessionId:t,startTime:Date.now()});try{const n=bM(e),{messagesToCompress:i,preservedMessages:o}=this.identifyMessagesToCompress(e);if(0===i.length)return{success:!1,originalTokenCount:n,newTokenCount:n,compressedMessages:e,error:"No messages to compress"};const s=await this.generateSummary(i,r),a=this.createCompressedMessages(o,s,t);return{success:!0,originalTokenCount:n,newTokenCount:bM(a),compressedMessages:a}}catch(qK){return{success:!1,originalTokenCount:bM(e),newTokenCount:bM(e),compressedMessages:e,error:qK instanceof Error?qK.message:String(qK)}}finally{this.compressionStates.delete(t)}}static identifyMessagesToCompress(e){let t=-1;for(let o=e.length-1;o>=0;o--){const n=e[o];if(n&&("role"in n&&"assistant"===n.role&&this.isSummaryMessage(n))){t=o;break}}if(-1===t){const t=Math.min(3,Math.floor(.2*e.length)),n=e.length-t;return{messagesToCompress:e.slice(0,n),preservedMessages:e.slice(n)}}const n=t+1,r=Math.min(2,Math.floor(.15*(e.length-n))),i=e.length-r;return{messagesToCompress:e.slice(n,i),preservedMessages:[...e.slice(0,t+1),...e.slice(i)]}}static isSummaryMessage(e){if("string"==typeof e.content){const t=e.content.toLowerCase();return t.includes("summary:")||t.includes("## summary")||t.includes("conversation summary")||t.includes("context summary")}return!1}static async generateSummary(e,t){const n=this.messagesToText(e);try{const e=await fI({model:t,system:'You are a conversation summarizer. Your task is to create a concise but comprehensive summary of the conversation history while preserving all important context, decisions, and technical details.\n\nIMPORTANT GUIDELINES:\n1. Preserve all technical information, code snippets, and specific implementation details\n2. Maintain the chronological flow of the conversation\n3. Include all key decisions, problems solved, and solutions implemented\n4. Preserve file names, function names, and specific technical references\n5. Keep important error messages and their resolutions\n6. Maintain the context needed for future conversation continuity\n7. Start your summary with "## Conversation Summary" and be detailed but concise\n\nThe summary will replace this conversation history, so ensure no critical information is lost.',messages:[{role:"user",content:`Please summarize the following conversation history:\n\n${n}`}],maxOutputTokens:2048});let r="";for await(const t of e.textStream)r+=t;return r}catch(qK){throw new Error(`Failed to generate summary: ${qK instanceof Error?qK.message:String(qK)}`)}}static messagesToText(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n];if(null!=r)if("role"in r&&"tool-group"!==r.role){const e=r,n=this.extractTextContent(e.content);t.push(`${e.role.toUpperCase()}: ${n}`)}else if("role"in r&&"tool-group"===r.role){const e=r;for(const n of e.toolGroup.tools)if(t.push(`TOOL: ${n.name} - ${n.description}`),n.result){const e="string"==typeof n.result?n.result:JSON.stringify(n.result,null,2);t.push(`TOOL_RESULT: ${e}`)}}}return t.join("\n\n")}static extractTextContent(e){return"string"==typeof e?e:Array.isArray(e)?e.map(e=>"string"==typeof e?e:"object"==typeof e&&null!==e?e.text||e.content||JSON.stringify(e):String(e)).join(" "):String(e)}static createCompressedMessages(e,t,n){const r={role:"assistant",content:t,timestamp:Date.now(),hidden:!1};let i=0;for(let s=0;s<e.length;s++){const t=e[s];if(t){if(!("role"in t)||"system"!==t.role)break;i=s+1}}const o=[...e];return o.splice(i,0,r),o}static getCompressionStats(){const e=Date.now();return{activeCompressions:this.compressionStates.size,compressionStates:Array.from(this.compressionStates.values()).map(t=>({sessionId:t.sessionId,duration:e-t.startTime}))}}static cleanupStaleCompressions(e=3e5){const t=Date.now();for(const[n,r]of this.compressionStates.entries())t-r.startTime>e&&(ex.warn(`Cleaning up stale compression for session ${n}`),this.compressionStates.delete(n))}}class EM{projectRoot;conversationDir=null;initialized=!1;constructor(e=process.cwd()){this.projectRoot=e}async initialize(){if(!this.initialized)try{this.projectRoot=await async function(e=process.cwd()){let t=v.resolve(e);const n=v.parse(t).root;for(;t!==n;){const e=[".git","package.json","Cargo.toml","pyproject.toml","requirements.txt","Makefile",".embedder"];for(const r of e){const e=v.join(t,r);try{return await c.access(e),t}catch{}}const n=v.dirname(t);if(n===t)break;t=n}return e}(this.projectRoot),this.conversationDir=await async function(e){const t=XF(e);return await c.mkdir(t,{recursive:!0}),t}(this.projectRoot),this.initialized=!0}catch(qK){this.initialized=!1,ex.error("Failed to initialize conversation persistence service",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0,projectRoot:this.projectRoot})}}async saveActiveConversation(e,t,n,r){if(this.initialized||await this.initialize(),this.initialized)try{const i=iM("active"),o=this.createSnapshot(e,t,n,void 0,i,void 0,r),s=eM(this.projectRoot);await this.writeSnapshotToFile(s,o),await this.updateConversationIndex(o)}catch(qK){ex.error("Failed to save active conversation",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0})}else ex.warn("Cannot save active conversation: service not initialized")}async restoreActiveConversation(){if(this.initialized||await this.initialize(),!this.initialized)return ex.warn("Cannot restore active conversation: service not initialized"),null;try{const e=eM(this.projectRoot),t=await this.readSnapshotFromFile(e);if(t)return t.todos&&oM("active",t.todos),{messages:this.snapshotToMessages(t),trackedFiles:t.trackedFiles}}catch(qK){ex.debug("No active conversation found to restore",{error:qK instanceof Error?qK.message:String(qK)})}return null}async clearActiveConversation(){if(this.initialized||await this.initialize(),this.initialized)try{const e=eM(this.projectRoot);await c.unlink(e)}catch(qK){}}async saveNamedConversation(e,t,n,r,i){if(this.initialized||await this.initialize(),this.initialized)try{const o=iM("active"),s=this.createSnapshot(t,n,r,e,o,void 0,i),a=nM(this.projectRoot,e);await this.writeSnapshotToFile(a,s),await this.updateConversationIndex(s)}catch(qK){ex.error("Failed to save named conversation",{name:e,error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0})}else ex.warn("Cannot save named conversation: service not initialized",{name:e})}async loadNamedConversation(e){if(this.initialized||await this.initialize(),!this.initialized)return ex.warn("Cannot load named conversation: service not initialized",{name:e}),null;try{const t=nM(this.projectRoot,e),n=await this.readSnapshotFromFile(t);if(n)return n.todos&&oM("active",n.todos),this.snapshotToMessages(n)}catch(qK){ex.error("Failed to load named conversation",{name:e,error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0})}return null}async listConversations(){if(this.initialized||await this.initialize(),!this.initialized)return ex.warn("Cannot list conversations: service not initialized"),[];try{return(await this.readConversationIndex()).conversations.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(qK){return ex.error("Failed to list conversations",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0}),[]}}createSnapshot(e,t,n,r,i,o,s){const a=(new Date).toISOString(),l=Date.now(),u=this.messagesToUIMessagesWithOrder(e,l),c=this.extractToolGroupsWithOrder(e,l);let d;o&&(d={isCompressed:o.success,lastCompression:a,originalTokenCount:o.originalTokenCount,compressedTokenCount:o.newTokenCount,compressionHistory:[{timestamp:a,originalTokens:o.originalTokenCount,compressedTokens:o.newTokenCount,compressionRatio:o.newTokenCount/o.originalTokenCount}]});return{id:r||"active",version:"1.0",createdAt:a,updatedAt:a,project:{hash:ve("sha256").update(this.projectRoot).digest("hex").substring(0,16),workingDirectory:this.projectRoot},messages:u,toolGroups:c,session:{model:n,sessionId:t,totalMessages:u.length,lastActivity:a},todos:i||void 0,compression:d,trackedFiles:s&&s.length>0?s:void 0}}messagesToUIMessagesWithOrder(e,t){const n=[];return e.forEach((e,r)=>{if("role"in e&&"tool-group"!==e.role){const i=e,o=i.timestamp?new Date(i.timestamp).toISOString():new Date(t+10*r).toISOString();n.push({id:`msg-${t}-${r}`,role:i.role,content:i.content,createdAt:o,model:i.model,hidden:i.hidden,mode:i.mode,timestamp:i.timestamp,patch:i.patch,metadata:{streamingComplete:!0,originalIndex:r}})}}),n}extractToolGroupsWithOrder(e,t){const n=[];return e.forEach((e,r)=>{if("role"in e&&"tool-group"===e.role){const i=e;n.push({id:i.id,timestamp:t+10*r,relatedMessageId:`msg-${t}-${r}`,originalIndex:r,tools:i.toolGroup.tools.map(e=>({id:e.id,toolCallId:e.toolCallId,name:e.name,displayName:e.displayName,description:e.description,status:e.status,result:e.result,confirmationDetails:e.confirmationDetails,startTime:e.startTime||Date.now(),endTime:e.endTime}))})}}),n}snapshotToMessages(e){const t=[];for(const n of e.messages){const e={role:n.role,content:n.content,model:n.model,hidden:n.hidden,mode:n.mode,timestamp:n.timestamp||new Date(n.createdAt).getTime(),patch:n.patch},r=new Date(n.createdAt).getTime(),i=n.metadata?.originalIndex??0;t.push({message:e,timestamp:r,originalIndex:i})}for(const n of e.toolGroups){const e={id:n.id,status:"completed",startTime:Math.min(...n.tools.map(e=>e.startTime)),endTime:Math.max(...n.tools.map(e=>e.endTime||e.startTime)),tools:n.tools.map(e=>({id:e.id,toolCallId:e.toolCallId,name:e.name,displayName:e.displayName,description:e.description,status:e.status,result:e.result,confirmationDetails:e.confirmationDetails,startTime:e.startTime,endTime:e.endTime}))},r={role:"tool-group",id:n.id,toolGroup:e,timestamp:n.timestamp},i=n.originalIndex??0;t.push({message:r,timestamp:n.timestamp,originalIndex:i})}return t.sort((e,t)=>e.originalIndex!==t.originalIndex?e.originalIndex-t.originalIndex:e.timestamp-t.timestamp),t.map(e=>e.message)}async writeSnapshotToFile(e,t){const n=`${e}.tmp`,r=JSON.stringify(t,null,2);try{await c.writeFile(n,r,"utf-8"),await c.rename(n,e)}catch(qK){try{await c.unlink(n)}catch{}throw qK}}async readSnapshotFromFile(e){try{const t=await c.readFile(e,"utf-8"),n=JSON.parse(t);return n.version&&n.messages&&Array.isArray(n.messages)?n:null}catch(qK){if("ENOENT"===qK.code)return null;throw qK}}async updateConversationIndex(e){const t=tM(this.projectRoot);let n;try{const e=await c.readFile(t,"utf-8");n=JSON.parse(e)}catch{n={conversations:[],lastUpdated:(new Date).toISOString()}}n.conversations=n.conversations.filter(t=>t.id!==e.id);const r=this.generatePreview(e);n.conversations.push({id:e.id,name:e.id,messageCount:e.messages.length,toolCallCount:e.toolGroups.reduce((e,t)=>e+t.tools.length,0),lastModified:e.updatedAt,model:e.session.model,preview:r}),n.lastUpdated=(new Date).toISOString(),await c.writeFile(t,JSON.stringify(n,null,2),"utf-8")}async readConversationIndex(){const e=tM(this.projectRoot);try{const t=await c.readFile(e,"utf-8");return JSON.parse(t)}catch{return{conversations:[],lastUpdated:(new Date).toISOString()}}}async compressAndSaveActiveConversation(e,t,n,r,i=!1){if(this.initialized||await this.initialize(),!this.initialized)return{success:!1,originalTokenCount:bM(e),newTokenCount:bM(e),compressedMessages:e,error:"Failed to initialize conversation persistence"};try{const o=await vM.compressConversation(e,t,n,r,i);if(o.success){const e=iM("active"),r=this.createSnapshot(o.compressedMessages,t,n,void 0,e,o),i=eM(this.projectRoot);await this.writeSnapshotToFile(i,r)}return o}catch(qK){return{success:!1,originalTokenCount:bM(e),newTokenCount:bM(e),compressedMessages:e,error:qK instanceof Error?qK.message:String(qK)}}}shouldAutoCompress(e,t){return vM.shouldCompressMessages(e,t)}getCompressionStats(e){if(!e.compression)return{isCompressed:!1,totalCompressions:0,totalTokensSaved:0};const t=e.compression.compressionHistory,n=t.reduce((e,t)=>e+(t.originalTokens-t.compressedTokens),0),r=t[t.length-1];return{isCompressed:e.compression.isCompressed,totalCompressions:t.length,totalTokensSaved:n,lastCompressionDate:e.compression.lastCompression,compressionRatio:r?.compressionRatio}}generatePreview(e){const t=e.messages.find(e=>"user"===e.role);return t&&"string"==typeof t.content?t.content.substring(0,100)+(t.content.length>100?"...":""):"No preview available"}async markForRevert(e,t){if(this.initialized||await this.initialize(),!this.initialized)return;const n=[];let r="",i=0;for(const a of t)if("role"in a&&"user"===a.role){const t=a;if(t.hidden)continue;if(i===e&&(r=`msg-${i}`),i>e&&t.patch){const e=Array.isArray(t.patch)?t.patch:[t.patch];for(const t of e)n.push({hash:t.hash,files:t.files})}i++}const o=eM(this.projectRoot),s=await this.readSnapshotFromFile(o);s&&(s.revert={targetMessageIndex:e,targetMessageId:r,patches:n},await this.writeSnapshotToFile(o,s))}async hasRevertPending(){if(this.initialized||await this.initialize(),!this.initialized)return!1;const e=eM(this.projectRoot),t=await this.readSnapshotFromFile(e);return void 0!==t?.revert}async getRevertPatches(){if(this.initialized||await this.initialize(),!this.initialized)return null;const e=eM(this.projectRoot),t=await this.readSnapshotFromFile(e);return t?.revert?.patches||null}async processRevert(e){if(this.initialized||await this.initialize(),!this.initialized)return e;const t=eM(this.projectRoot),n=await this.readSnapshotFromFile(t);if(!n?.revert)return e;const r=n.revert.targetMessageIndex,i=[];let o=-1;for(const s of e)if("role"in s&&"user"===s.role){s.hidden||(o++,o<=r&&i.push(s))}else o<=r&&i.push(s);return n.revert=void 0,await this.writeSnapshotToFile(t,n),i}async clearRevert(){if(this.initialized||await this.initialize(),!this.initialized)return;const e=eM(this.projectRoot),t=await this.readSnapshotFromFile(e);t&&(t.revert=void 0,await this.writeSnapshotToFile(e,t))}close(){this.initialized=!1,this.conversationDir=null}}let IM=null;function wM(){return IM}const CM=qe.createContext(null);function _M({children:e}){const t=function(){const[e,t]=qe.useState(!1),[n,r]=qe.useState(!1),[i,o]=qe.useState(!1),[s,a]=qe.useState(!1),[l,u]=qe.useState(!1),[c,d]=qe.useState(null),[p,f]=qe.useState(null),[h,g]=qe.useState(null);return{isCreateProjectOpen:e,setIsCreateProjectOpen:t,isCreateTeamOpen:n,setIsCreateTeamOpen:r,isBillingModalOpen:i,setIsBillingModalOpen:o,error:c,setError:d,isDeviceAuthOpen:s,setIsDeviceAuthOpen:a,isAddDocumentsModalOpen:l,setIsAddDocumentsModalOpen:u,activeQuestionPrompt:p,setActiveQuestionPrompt:f,pendingQuestionResponse:h,setPendingQuestionResponse:g}}(),n=function(){const[e,t]=qe.useState([]),[n,r]=qe.useState(!1),[i,o]=qe.useState(null),[s,a]=qe.useState([]);return{messages:e,setMessages:t,streamingState:n?_w.Responding:_w.Idle,isResponding:n,setIsResponding:r,thought:i,setThought:o,queuedMessages:s,setQueuedMessages:a}}(),r=YF(t.setError),i=function(e,t){const n=qe.useRef(null),[r,i]=qe.useState(null),o=qe.useRef(!1),s=qe.useRef(null),{sessionId:a}=FT(),{selectedModel:l}=VF();return qe.useEffect(()=>((async()=>{if(!n.current)try{const e=new EM;await e.initialize(),n.current=e,i(e),ex.debug("Conversation service initialized in hook")}catch(qK){ex.error("Failed to initialize conversation service in hook",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0})}})(),()=>{n.current&&(n.current.close(),n.current=null)}),[]),qe.useEffect(()=>{},[a]),qe.useEffect(()=>{if(!r||!a||0===e.length||!l)return;const t=setTimeout(async()=>{try{const t=wM(),n=t?.getTrackedFiles();ex.debug("Auto-save: Getting tracked files",{hasSnapshotService:!!t,trackedFilesCount:n?.length||0,trackedFiles:n||[]}),await r.saveActiveConversation(e,a,l,n)}catch(qK){ex.error("Auto-save failed in conversation service hook",{error:qK instanceof Error?qK.message:String(qK)})}},2e3);return()=>clearTimeout(t)},[e,r,a,l]),qe.useEffect(()=>{r&&(async()=>{try{const n=await r.restoreActiveConversation();if(!n||!n.messages.length)return;if(!o.current&&n.trackedFiles){const e=wM();e?(e.setTrackedFiles(n.trackedFiles),ex.debug("Restored tracked files to snapshot service immediately",{fileCount:n.trackedFiles.length}),o.current=!0):(s.current=n.trackedFiles,ex.debug("Snapshot service not ready, storing tracked files for later",{fileCount:n.trackedFiles.length}))}0===e.filter(e=>!("role"in e)||"system"!==e.role||!e.hidden).length&&t(e=>[...e.filter(e=>"role"in e&&"system"===e.role&&e.hidden),...n.messages])}catch(qK){ex.debug("Failed to restore conversation:",qK)}})()},[r,e,t]),qe.useEffect(()=>{if(s.current){const e=wM();e&&!o.current&&(e.setTrackedFiles(s.current),ex.debug("Applied pending tracked files to snapshot service",{fileCount:s.current.length}),o.current=!0,s.current=null)}},[e]),{saveConversation:async t=>{if(!r||!a||!l)throw new Error("Conversation service not available");const n=wM(),i=n?.getTrackedFiles();await r.saveNamedConversation(t,e,a,l,i)},loadConversation:async e=>{if(!r)throw new Error("Conversation service not available");const n=await r.loadNamedConversation(e);if(!n)throw new Error(`Conversation "${e}" not found`);{const e=n.filter(e=>!("id"in e)||!("string"==typeof e.id&&e.id.startsWith("env-context-")));t(e)}},listConversations:async()=>r?r.listConversations():[],clearActiveConversation:async()=>{if(!r)throw new Error("Conversation service not available");await r.clearActiveConversation()},conversationService:r}}(n.messages,n.setMessages);return We.jsx(CM.Provider,{value:{...t,...n,...r,...i},children:e})}function BM(){const e=qe.useContext(CM);if(!e)throw new Error("useAppState must be used inside AppProvider");return e}const DM=kw((e,t)=>({streams:new Map,totalLineCount:0,totalTokenCount:0,updateStream:(t,n,r)=>{e(e=>{const i=r.split("\n").length,o=function(e){if(!e)return 0;const t=Math.ceil(e.length/4);return t+Math.ceil(.1*t)}(r),s=e.streams.get(t),a=s?.lineCount||0,l=s?.tokenCount||0,u=new Map(e.streams);u.set(t,{toolCallId:t,toolName:n,output:r,timestamp:Date.now(),lineCount:i,tokenCount:o});const c=i-a,d=o-l;return{streams:u,totalLineCount:e.totalLineCount+c,totalTokenCount:e.totalTokenCount+d}})},clearStream:t=>{e(e=>{const n=e.streams.get(t),r=n?.lineCount||0,i=n?.tokenCount||0,o=new Map(e.streams);return o.delete(t),{streams:o,totalLineCount:e.totalLineCount-r,totalTokenCount:e.totalTokenCount-i}})},clearAll:()=>{e({streams:new Map,totalLineCount:0,totalTokenCount:0})},getStream:e=>t().streams.get(e)}));var SM=(e=>(e.Pending="pending",e.Executing="executing",e.Success="success",e.Error="error",e.Confirming="confirming",e.Cancelled="cancelled",e))(SM||{}),kM=(e=>(e.ProceedOnce="proceed_once",e.ProceedAlways="proceed_always",e.ProceedAlwaysCommand="proceed_always_command",e.ProceedAlwaysTool="proceed_always_tool",e.Cancel="cancel",e))(kM||{});const xM="white",QM="gray",NM="green",TM="red",RM="yellow",FM="blue",MM="cyan",OM="magenta",$M=new Intl.Segmenter,LM=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),PM=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),jM=new RegExp("^\\p{RGI_Emoji}$","v");function UM(e){return e.replace(PM,"")}function zM(e){return LM.test(e)}function GM(e,t){let n=0;if(e.length>1)for(const r of e.slice(1))r>="＀"&&r<="￯"&&(n+=Gt(r.codePointAt(0),t));return n}function HM(e,t={}){if("string"!=typeof e||0===e.length)return 0;const{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;let i=e;if(r||(i=jt(i)),0===i.length)return 0;let o=0;const s={ambiguousAsWide:!n};for(const{segment:a}of $M.segment(i)){if(zM(a))continue;if(jM.test(a)){o+=2;continue}o+=Gt(UM(a).codePointAt(0),s),o+=GM(a,s)}return o}function WM(e){return Array.from(e)}const qM=qe.createContext(void 0),JM=qe.createContext(void 0),KM=({children:e})=>{const[t,n]=qe.useState(new Set),r=qe.useCallback(e=>{n(t=>{if(t.has(e))return t;const n=new Set(t);return n.add(e),n})},[]),i=qe.useCallback(e=>{n(t=>{if(!t.has(e))return t;const n=new Set(t);return n.delete(e),n})},[]),o=qe.useMemo(()=>({overflowingIds:t}),[t]),s=qe.useMemo(()=>({addOverflowingId:r,removeOverflowingId:i}),[r,i]);return We.jsx(qM.Provider,{value:o,children:We.jsx(JM.Provider,{value:s,children:e})})},ZM=({children:e,maxWidth:t,maxHeight:n,overflowDirection:r="top",additionalHiddenLinesCount:i=0})=>{const o=qe.useId(),{addOverflowingId:s,removeOverflowingId:a}=qe.useContext(JM)||{},l=[],u=Math.max(Math.round(n??Number.MAX_SAFE_INTEGER),2);if(void 0===t)throw new Error("maxWidth must be defined when maxHeight is set.");Je.Children.forEach(e,function e(n){Je.isValidElement(n)&&(n.type!==qe.Fragment?n.type!==ki||function(e,t,n){const r=function(e){if(!Je.isValidElement(e)||e.type!==ki)return{noWrapSegments:[{text:"<ERROR>",props:{}}],segments:[]};const t={noWrapSegments:[],segments:[]};let n=!1;function r(e,i){if(null===e)return;if("string"==typeof e||"number"==typeof e){const r=String(e);if(!r)return;const o={text:r,props:i??{}};return void(void 0===i||"wrap"===i.wrap?(n=!0,t.segments.push(o)):n?t.segments.push(o):t.noWrapSegments.push(o))}if(!Je.isValidElement(e))return;if(e.type===qe.Fragment)return void Je.Children.forEach(e.props.children,e=>r(e,i));if(e.type!==xi)return;const{children:o,...s}=e.props,a=void 0===i?s:{...i,...s};Je.Children.forEach(o,e=>r(e,a))}return Je.Children.forEach(e.props.children,e=>r(e,void 0)),t}(e);if(0===r.segments.length&&0===r.noWrapSegments.length)return void n.push([]);const i=[],o=[];let s=0;if(r.noWrapSegments.forEach(e=>{o.push(e),s+=HM(e.text)}),0===r.segments.length){const e=[];let t=[];o.forEach(n=>{n.text.split("\n").forEach((r,i)=>{i>0&&(e.push(t),t=[]),r&&t.push({text:r,props:n.props})})}),(t.length>0||o.length>0&&o[o.length-1]&&o[o.length-1]?.text.endsWith("\n"))&&e.push(t);for(const r of e)n.push(r);return}const a=t-s;if(a<1){const e=[];let r=[],i=0;for(const n of o){n.text.split("\n").forEach((o,s)=>{if(s>0&&(e.push(r),r=[],i=0),o){const e=HM(o);if(s>0&&e>0)r.push({text:"…",props:{}}),i=HM("…");else{const s=Math.max(0,t-HM("…"));if(e<=s&&0===i)r.push({text:o,props:n.props}),i+=e;else{const e=WM(o);let t=i,a=0;for(const n of e){const e=HM(n);if(t+e>s)break;t+=e,a++}const l=e.slice(0,a).join("");l&&r.push({text:l,props:n.props}),r.push({text:"…",props:{}}),i=t+HM("…")}}}})}(r.length>0||o.length>0&&o[o.length-1]&&o[o.length-1]?.text.endsWith("\n"))&&e.push(r),0===e.length&&e.push([{text:"…",props:{}}]);for(const t of e)n.push(t);return}let l=[],u=0;function c(){0===i.length?i.push([...o,...l]):s>0?i.push([{text:" ".repeat(s),props:{}},...l]):i.push(l),l=[],u=0}function d(e,t){const n=l[l.length-1];n&&n.props===t?n.text+=e:l.push({text:e,props:t})}r.segments.forEach(e=>{e.text.split("\n").forEach((t,n)=>{n>0&&c();t.split(/(\s+)/).forEach(t=>{if(!t)return;const n=HM(t);if(!(u+n>a&&u>0&&(c(),/^\s+$/.test(t))))if(n>a){let n=WM(t);for(;n.length>0;){let t=0,r=0;for(const e of n){const n=HM(e);if(u+r+n>a)break;r+=n,t++}if(t>0){const r=n.slice(0,t).join("");d(r,e.props),u+=HM(r),n=n.slice(t)}n.length>0&&c()}}else d(t,e.props),u+=n})}),e.text.endsWith("\n")&&c()}),l.length>0&&c();for(const p of i)n.push(p)}(n,t,l):Je.Children.forEach(n.props.children,e))});const c=(void 0!==u&&l.length>u||i>0)&&void 0!==u?u-1:u,d=void 0!==c?Math.max(0,l.length-c):0,p=d+i;qe.useEffect(()=>(p>0?s?.(o):a?.(o),()=>{a?.(o)}),[o,p,s,a]);const f=(d>0?"top"===r?l.slice(d,l.length):l.slice(0,c):l).map((e,t)=>We.jsx(ki,{children:e.length>0?e.map((e,t)=>We.jsx(xi,{...e.props,children:e.text},t)):We.jsx(xi,{children:" "})},t));return We.jsxs(ki,{flexDirection:"column",width:t,flexShrink:0,children:[p>0&&"top"===r&&We.jsxs(xi,{color:QM,wrap:"truncate",children:["... first ",p," line",1===p?"":"s"," hidden ..."]}),f,p>0&&"bottom"===r&&We.jsxs(xi,{color:QM,wrap:"truncate",children:["... last ",p," line",1===p?"":"s"," hidden ..."]})]})};const VM=2,YM=2,XM=3,eO=.9,tO=.8,nO=20,rO=60;class iO{baseTerminalWidth;constructor(e){this.baseTerminalWidth=e}getMainContentWidth(){return Math.floor(this.baseTerminalWidth*eO)}getInputWidth(){const e=this.getMainContentWidth()-VM-YM;return Math.max(nO,e)}getSuggestionsWidth(){const e=Math.floor(this.baseTerminalWidth*tO);return Math.max(rO,e)}getToolMessageWidth(){return this.baseTerminalWidth-XM-YM}getDialogContentWidth(){return this.baseTerminalWidth-VM-YM}getConstrainedContentWidth(e=0){return this.baseTerminalWidth-e}getTableWidth(){return this.baseTerminalWidth-2}}function oO(e){return qe.useMemo(()=>new iO(e),[e])}const sO=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],aO=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),lO=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),uO=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),cO=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();var dO="[0-9](_*[0-9])*",pO=`\\.(${dO})`,fO="[0-9a-fA-F](_*[0-9a-fA-F])*",hO={className:"number",variants:[{begin:`(\\b(${dO})((${pO})|\\.)?|(${pO}))[eE][+-]?(${dO})[fFdD]?\\b`},{begin:`\\b(${dO})((${pO})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${pO})[fFdD]?\\b`},{begin:`\\b(${dO})[fFdD]\\b`},{begin:`\\b0[xX]((${fO})\\.?|(${fO})?\\.(${fO}))[pP][+-]?(${dO})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${fO})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function gO(e,t,n){return-1===n?"":e.replace(t,r=>gO(e,t,n-1))}const AO="[A-Za-z$_][0-9A-Za-z$_]*",mO=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],yO=["true","false","null","undefined","NaN","Infinity"],bO=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],vO=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],EO=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],IO=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],wO=[].concat(EO,bO,vO);var CO="[0-9](_*[0-9])*",_O=`\\.(${CO})`,BO="[0-9a-fA-F](_*[0-9a-fA-F])*",DO={className:"number",variants:[{begin:`(\\b(${CO})((${_O})|\\.)?|(${_O}))[eE][+-]?(${CO})[fFdD]?\\b`},{begin:`\\b(${CO})((${_O})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${_O})[fFdD]?\\b`},{begin:`\\b(${CO})[fFdD]\\b`},{begin:`\\b0[xX]((${BO})\\.?|(${BO})?\\.(${BO}))[pP][+-]?(${CO})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${BO})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};const SO=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],kO=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),xO=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),QO=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),NO=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),TO=xO.concat(QO).sort().reverse();const RO=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],FO=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),MO=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),OO=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),$O=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function LO(e){return e?"string"==typeof e?e:e.source:null}function PO(e){return jO("(?=",e,")")}function jO(...e){return e.map(e=>LO(e)).join("")}function UO(...e){const t=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(t.capture?"":"?:")+e.map(e=>LO(e)).join("|")+")"}const zO=e=>jO(/\b/,e,/\w$/.test(e)?/\b/:/\B/),GO=["Protocol","Type"].map(zO),HO=["init","self"].map(zO),WO=["Any","Self"],qO=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],JO=["false","nil","true"],KO=["assignment","associativity","higherThan","left","lowerThan","none","right"],ZO=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],VO=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],YO=UO(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),XO=UO(YO,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),e$=jO(YO,XO,"*"),t$=UO(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),n$=UO(t$,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),r$=jO(t$,n$,"*"),i$=jO(/[A-Z]/,n$,"*"),o$=["attached","autoclosure",jO(/convention\(/,UO("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",jO(/objc\(/,r$,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],s$=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];const a$="[A-Za-z$_][0-9A-Za-z$_]*",l$=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],u$=["true","false","null","undefined","NaN","Infinity"],c$=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],d$=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],p$=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],f$=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],h$=[].concat(p$,c$,d$);const g$={arduino:function(e){const t={type:["boolean","byte","word","String"],built_in:["KeyboardController","MouseController","SoftwareSerial","EthernetServer","EthernetClient","LiquidCrystal","RobotControl","GSMVoiceCall","EthernetUDP","EsploraTFT","HttpClient","RobotMotor","WiFiClient","GSMScanner","FileSystem","Scheduler","GSMServer","YunClient","YunServer","IPAddress","GSMClient","GSMModem","Keyboard","Ethernet","Console","GSMBand","Esplora","Stepper","Process","WiFiUDP","GSM_SMS","Mailbox","USBHost","Firmata","PImage","Client","Server","GSMPIN","FileIO","Bridge","Serial","EEPROM","Stream","Mouse","Audio","Servo","File","Task","GPRS","WiFi","Wire","TFT","GSM","SPI","SD"],_hints:["setup","loop","runShellCommandAsynchronously","analogWriteResolution","retrieveCallingNumber","printFirmwareVersion","analogReadResolution","sendDigitalPortPair","noListenOnLocalhost","readJoystickButton","setFirmwareVersion","readJoystickSwitch","scrollDisplayRight","getVoiceCallStatus","scrollDisplayLeft","writeMicroseconds","delayMicroseconds","beginTransmission","getSignalStrength","runAsynchronously","getAsynchronously","listenOnLocalhost","getCurrentCarrier","readAccelerometer","messageAvailable","sendDigitalPorts","lineFollowConfig","countryNameWrite","runShellCommand","readStringUntil","rewindDirectory","readTemperature","setClockDivider","readLightSensor","endTransmission","analogReference","detachInterrupt","countryNameRead","attachInterrupt","encryptionType","readBytesUntil","robotNameWrite","readMicrophone","robotNameRead","cityNameWrite","userNameWrite","readJoystickY","readJoystickX","mouseReleased","openNextFile","scanNetworks","noInterrupts","digitalWrite","beginSpeaker","mousePressed","isActionDone","mouseDragged","displayLogos","noAutoscroll","addParameter","remoteNumber","getModifiers","keyboardRead","userNameRead","waitContinue","processInput","parseCommand","printVersion","readNetworks","writeMessage","blinkVersion","cityNameRead","readMessage","setDataMode","parsePacket","isListening","setBitOrder","beginPacket","isDirectory","motorsWrite","drawCompass","digitalRead","clearScreen","serialEvent","rightToLeft","setTextSize","leftToRight","requestFrom","keyReleased","compassRead","analogWrite","interrupts","WiFiServer","disconnect","playMelody","parseFloat","autoscroll","getPINUsed","setPINUsed","setTimeout","sendAnalog","readSlider","analogRead","beginWrite","createChar","motorsStop","keyPressed","tempoWrite","readButton","subnetMask","debugPrint","macAddress","writeGreen","randomSeed","attachGPRS","readString","sendString","remotePort","releaseAll","mouseMoved","background","getXChange","getYChange","answerCall","getResult","voiceCall","endPacket","constrain","getSocket","writeJSON","getButton","available","connected","findUntil","readBytes","exitValue","readGreen","writeBlue","startLoop","IPAddress","isPressed","sendSysex","pauseMode","gatewayIP","setCursor","getOemKey","tuneWrite","noDisplay","loadImage","switchPIN","onRequest","onReceive","changePIN","playFile","noBuffer","parseInt","overflow","checkPIN","knobRead","beginTFT","bitClear","updateIR","bitWrite","position","writeRGB","highByte","writeRed","setSpeed","readBlue","noStroke","remoteIP","transfer","shutdown","hangCall","beginSMS","endWrite","attached","maintain","noCursor","checkReg","checkPUK","shiftOut","isValid","shiftIn","pulseIn","connect","println","localIP","pinMode","getIMEI","display","noBlink","process","getBand","running","beginSD","drawBMP","lowByte","setBand","release","bitRead","prepare","pointTo","readRed","setMode","noFill","remove","listen","stroke","detach","attach","noTone","exists","buffer","height","bitSet","circle","config","cursor","random","IRread","setDNS","endSMS","getKey","micros","millis","begin","print","write","ready","flush","width","isPIN","blink","clear","press","mkdir","rmdir","close","point","yield","image","BSSID","click","delay","read","text","move","peek","beep","rect","line","open","seek","fill","size","turn","stop","home","find","step","tone","sqrt","RSSI","SSID","end","bit","tan","cos","sin","pow","map","abs","max","min","get","run","put"],literal:["DIGITAL_MESSAGE","FIRMATA_STRING","ANALOG_MESSAGE","REPORT_DIGITAL","REPORT_ANALOG","INPUT_PULLUP","SET_PIN_MODE","INTERNAL2V56","SYSTEM_RESET","LED_BUILTIN","INTERNAL1V1","SYSEX_START","INTERNAL","EXTERNAL","DEFAULT","OUTPUT","INPUT","HIGH","LOW"]},n=function(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="(?!struct)("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",s={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},a={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},u={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(a,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},c={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},d=t.optional(i)+e.IDENT_RE+"\\s*\\(",p={type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],keyword:["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"]},f={className:"function.dispatch",relevance:0,keywords:{_hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"]},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},h=[f,u,s,n,e.C_BLOCK_COMMENT_MODE,l,a],g={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:p,contains:h.concat([{begin:/\(/,end:/\)/,keywords:p,contains:h.concat(["self"]),relevance:0}]),relevance:0},A={className:"function",begin:"("+o+"[\\*&\\s]+)+"+d,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:p,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:p,relevance:0},{begin:d,returnBegin:!0,contains:[c],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[a,l]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,a,l,s,{begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,a,l,s]}]},s,n,e.C_BLOCK_COMMENT_MODE,u]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:p,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(g,A,f,h,[u,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:p,contains:["self",s]},{begin:e.IDENT_RE+"::",keywords:p},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}(e),r=n.keywords;return r.type=[...r.type,...t.type],r.literal=[...r.literal,...t.literal],r.built_in=[...r.built_in,...t.built_in],r._hints=t._hints,n.name="Arduino",n.aliases=["ino"],n.supersetOf="cpp",n},bash:function(e){const t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},r]});const i={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},o=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),s={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},a={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,i]};i.contains.push(a);const l={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,n]},u=e.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),c={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],literal:["true","false"],built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"]},contains:[u,e.SHEBANG(),c,l,o,s,{match:/(\/[a-z._-]+)+/},a,{match:/\\"/},{className:"string",begin:/'/,end:/'/},{match:/\\'/},n]}},c:function(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",s={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:/\batomic_[a-z]{3,6}\b/}]},a={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},u={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(a,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},c={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},d=t.optional(i)+e.IDENT_RE+"\\s*\\(",p={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},f=[u,s,n,e.C_BLOCK_COMMENT_MODE,l,a],h={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:p,contains:f.concat([{begin:/\(/,end:/\)/,keywords:p,contains:f.concat(["self"]),relevance:0}]),relevance:0},g={begin:"("+o+"[\\*&\\s]+)+"+d,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:p,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:p,relevance:0},{begin:d,returnBegin:!0,contains:[e.inherit(c,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,a,l,s,{begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,a,l,s]}]},s,n,e.C_BLOCK_COMMENT_MODE,u]};return{name:"C",aliases:["h"],keywords:p,disableAutodetect:!0,illegal:"</",contains:[].concat(h,g,f,[u,{begin:e.IDENT_RE+"::",keywords:p},{className:"class",beginKeywords:"enum class struct union",end:/[{;:<>=]/,contains:[{beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:u,strings:a,keywords:p}}},cpp:function(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="(?!struct)("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",s={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},a={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},u={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(a,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},c={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},d=t.optional(i)+e.IDENT_RE+"\\s*\\(",p={type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],keyword:["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"]},f={className:"function.dispatch",relevance:0,keywords:{_hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"]},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},h=[f,u,s,n,e.C_BLOCK_COMMENT_MODE,l,a],g={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:p,contains:h.concat([{begin:/\(/,end:/\)/,keywords:p,contains:h.concat(["self"]),relevance:0}]),relevance:0},A={className:"function",begin:"("+o+"[\\*&\\s]+)+"+d,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:p,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:p,relevance:0},{begin:d,returnBegin:!0,contains:[c],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[a,l]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,a,l,s,{begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,a,l,s]}]},s,n,e.C_BLOCK_COMMENT_MODE,u]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:p,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(g,A,f,h,[u,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:p,contains:["self",s]},{begin:e.IDENT_RE+"::",keywords:p},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}},csharp:function(e){const t={keyword:["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"].concat(["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"]),built_in:["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],literal:["default","false","null","true"]},n=e.inherit(e.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),r={className:"number",variants:[{begin:"\\b(0b[01']+)"},{begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],relevance:0},i={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},o=e.inherit(i,{illegal:/\n/}),s={className:"subst",begin:/\{/,end:/\}/,keywords:t},a=e.inherit(s,{illegal:/\n/}),l={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},e.BACKSLASH_ESCAPE,a]},u={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},s]},c=e.inherit(u,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},a]});s.contains=[u,l,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,r,e.C_BLOCK_COMMENT_MODE],a.contains=[c,l,o,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,r,e.inherit(e.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];const d={variants:[{className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},u,l,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},p={begin:"<",end:">",contains:[{beginKeywords:"in out"},n]},f=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",h={begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:t,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:"\x3c!--|--\x3e"},{begin:"</?",end:">"}]}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},d,r,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},n,p,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[n,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[n,p,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+f+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:t,contains:[{beginKeywords:["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"].join(" "),relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[e.TITLE_MODE,p],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:t,relevance:0,contains:[d,r,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},h]}},css:function(e){const t=e.regex,n=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),r=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/},n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+lO.join("|")+")"},{begin:":(:)?("+uO.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+cO.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...r,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...r,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:aO.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+sO.join("|")+")\\b"}]}},diff:function(e){const t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}},go:function(e){const t={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:t,illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"string",variants:[e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[e.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,illegal:/["']/}]}]}},graphql:function(e){const t=e.regex;return{name:"GraphQL",aliases:["gql"],case_insensitive:!0,disableAutodetect:!1,keywords:{keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"],literal:["true","false","null"]},contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation",begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/,end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{scope:"symbol",begin:t.concat(/[_A-Za-z][_0-9A-Za-z]*/,t.lookahead(/\s*:/)),relevance:0}],illegal:[/[;<']/,/BEGIN/]}},ini:function(e){const t=e.regex,n={className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{begin:e.NUMBER_RE}]},r=e.COMMENT();r.variants=[{begin:/;/,end:/$/},{begin:/#/,end:/$/}];const i={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{begin:/\$\{(.*?)\}/}]},o={className:"literal",begin:/\bon|off|true|false|yes|no\b/},s={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]},a={begin:/\[/,end:/\]/,contains:[r,o,i,s,n,"self"],relevance:0},l=t.either(/[A-Za-z0-9_-]+/,/"(\\"|[^"])*"/,/'[^']*'/);return{name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,contains:[r,{className:"section",begin:/\[+/,end:/\]+/},{begin:t.concat(l,"(\\s*\\.\\s*",l,")*",t.lookahead(/\s*=\s*[^#\s]/)),className:"attr",starts:{end:/$/,contains:[r,a,o,i,s,n]}}]}},java:function(e){const t=e.regex,n="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=n+gO("(?:<"+n+"~~~(?:\\s*,\\s*"+n+"~~~)*>)?",/~~~/g,2),i={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},o={className:"meta",begin:"@"+n,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},s={className:"params",begin:/\(/,end:/\)/,keywords:i,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:i,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[t.concat(/(?!else)/,n),/\s+/,n,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,n],className:{1:"keyword",3:"title.class"},contains:[s,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:i,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:i,relevance:0,contains:[o,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,hO,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},hO,o]}},javascript:function(e){const t=e.regex,n=AO,r="<>",i="</>",o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let i;">"===r&&(((e,{after:t})=>{const n="</"+e[0].slice(1);return-1!==e.input.indexOf(n,t)})(e,{after:n})||t.ignoreMatch());const o=e.input.substring(n);((i=o.match(/^\s*=/))||(i=o.match(/^\s+extends\s+/))&&0===i.index)&&t.ignoreMatch()}},s={$pattern:AO,keyword:mO,literal:yO,built_in:wO,"variable.language":IO},a="[0-9](_?[0-9])*",l=`\\.(${a})`,u="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",c={className:"number",variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${a})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:s,contains:[]},p={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},f={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},h={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},g={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},A={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},m=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,f,h,g,{match:/\$\d+/},c];d.contains=m.concat({begin:/\{/,end:/\}/,keywords:s,contains:["self"].concat(m)});const y=[].concat(A,d.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:["self"].concat(y)}]),v={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},E={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},I={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...bO,...vO]}},w={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[v],illegal:/%/},C={match:t.concat(/\b/,(_=[...EO,"super","import"].map(e=>`${e}\\s*\\(`),t.concat("(?!",_.join("|"),")")),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0};var _;const B={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},D={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},v]},S="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",k={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(S)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[v]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:I},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,f,h,g,A,{match:/\$\d+/},c,I,{scope:"attr",match:n+t.lookahead(":"),relevance:0},k,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[A,e.REGEXP_MODE,{className:"function",begin:S,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:i},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[v,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},B,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[v]},C,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},E,D,{match:/\$[(.]/}]}},json:function(e){const t=["true","false","null"],n={scope:"literal",beginKeywords:t.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:t},contains:[{className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{match:/[{}[\],:]/,className:"punctuation",relevance:0},e.QUOTE_STRING_MODE,n,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}},kotlin:function(e){const t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},n={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@"},r={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},i={className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},o={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[i,r]},{begin:"'",end:"'",illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[e.BACKSLASH_ESCAPE,i,r]}]};r.contains.push(o);const s={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?"},a={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[e.inherit(o,{className:"string"}),"self"]}]},l=DO,u=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),c={variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},d=c;return d.variants[1].contains=[c],c.variants[1].contains=[d],{name:"Kotlin",aliases:["kt","kts"],keywords:t,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,u,{className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},n,s,a,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:t,relevance:5,contains:[{begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin:/</,end:/>/,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[c,e.C_LINE_COMMENT_MODE,u],relevance:0},e.C_LINE_COMMENT_MODE,u,s,a,o,e.C_NUMBER_MODE]},u]},{begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},e.UNDERSCORE_TITLE_MODE,{className:"type",begin:/</,end:/>/,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},s,a]},o,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:"\n"},l]}},less:function(e){const t=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),n=TO,r="[\\w-]+",i="("+r+"|@\\{"+r+"\\})",o=[],s=[],a=function(e){return{className:"string",begin:"~?"+e+".*?"+e}},l=function(e,t,n){return{className:e,begin:t,relevance:n}},u={$pattern:/[a-z-]+/,keyword:"and or not only",attribute:kO.join(" ")},c={begin:"\\(",end:"\\)",contains:s,keywords:u,relevance:0};s.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,a("'"),a('"'),t.CSS_NUMBER_MODE,{begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]",excludeEnd:!0}},t.HEXCOLOR,c,l("variable","@@?"+r,10),l("variable","@\\{"+r+"\\}"),l("built_in","~?`[^`]*?`"),{className:"attribute",begin:r+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0},t.IMPORTANT,{beginKeywords:"and not"},t.FUNCTION_DISPATCH);const d=s.concat({begin:/\{/,end:/\}/,contains:o}),p={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(s)},f={begin:i+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+NO.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:s}}]},h={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:u,returnEnd:!0,contains:s,relevance:0}},g={className:"variable",variants:[{begin:"@"+r+"\\s*:",relevance:15},{begin:"@"+r}],starts:{end:"[;}]",returnEnd:!0,contains:d}},A={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:i,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:"[<='$\"]",relevance:0,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,p,l("keyword","all\\b"),l("variable","@\\{"+r+"\\}"),{begin:"\\b("+SO.join("|")+")\\b",className:"selector-tag"},t.CSS_NUMBER_MODE,l("selector-tag",i,0),l("selector-id","#"+i),l("selector-class","\\."+i,0),l("selector-tag","&",0),t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",begin:":("+xO.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+QO.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:d},{begin:"!important"},t.FUNCTION_DISPATCH]},m={begin:r+`:(:)?(${n.join("|")})`,returnBegin:!0,contains:[A]};return o.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,h,g,m,f,A,p,t.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:"[=>'/<($\"]",contains:o}},lua:function(e){const t="\\[=*\\[",n="\\]=*\\]",r={begin:t,end:n,contains:["self"]},i=[e.COMMENT("--(?!"+t+")","$"),e.COMMENT("--"+t,n,{contains:[r],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:e.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in local not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:i.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:i}].concat(i)},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:t,end:n,contains:[r],relevance:5}])}},makefile:function(e){const t={className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)",contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%<?\^\+\*]/}]},n={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,t]},r={className:"variable",begin:/\$\([\w-]+\s/,end:/\)/,keywords:{built_in:"subst patsubst strip findstring filter filter-out sort word wordlist firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath error warning shell origin flavor foreach if or and call eval file value"},contains:[t,n]},i={begin:"^"+e.UNDERSCORE_IDENT_RE+"\\s*(?=[:+?]?=)"},o={className:"section",begin:/^[^\s]+:/,end:/$/,contains:[t]};return{name:"Makefile",aliases:["mk","mak","make"],keywords:{$pattern:/[\w-]+/,keyword:"define endef undefine ifdef ifndef ifeq ifneq else endif include -include sinclude override export unexport private vpath"},contains:[e.HASH_COMMENT_MODE,t,n,r,i,{className:"meta",begin:/^\.PHONY:/,end:/$/,keywords:{$pattern:/[\.\w]+/,keyword:".PHONY"}},o]}},markdown:function(e){const t={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},n={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:e.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},r={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},i={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},o=e.inherit(r,{contains:[]}),s=e.inherit(i,{contains:[]});r.contains.push(s),i.contains.push(o);let a=[t,n];return[r,i,o,s].forEach(e=>{e.contains=e.contains.concat(a)}),a=a.concat(r,i),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:a},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:a}]}]},t,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},r,i,{className:"quote",begin:"^>\\s+",contains:a,end:"$"},{className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{begin:"^[-\\*]{3,}",end:"$"},n,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}},objectivec:function(e){const t=/[a-zA-Z@][a-zA-Z0-9_]*/,n={$pattern:t,keyword:["@interface","@class","@protocol","@implementation"]};return{name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"],keywords:{"variable.language":["this","super"],$pattern:t,keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"],literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"],built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"],type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"]},illegal:"</",contains:[{className:"built_in",begin:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.C_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{className:"string",variants:[{begin:'@"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]}]},{className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),{className:"string",begin:/<.*?>/,end:/$/,illegal:"\\n"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class",begin:"("+n.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:n,contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE,relevance:0}]}},perl:function(e){const t=e.regex,n=/[dualxmsipngr]{0,12}/,r={$pattern:/[\w.]+/,keyword:["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork","format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","local","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","setgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","until","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"].join(" ")},i={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:r},o={begin:/->\{/,end:/\}/},s={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},a={scope:"variable",variants:[{begin:/\$\d/},{begin:t.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[s]},l={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},u=[e.BACKSLASH_ESCAPE,i,a],c=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],d=(e,r,i="\\1")=>{const o="\\1"===i?i:t.concat(i,r);return t.concat(t.concat("(?:",e,")"),r,/(?:\\.|[^\\\/])*?/,o,/(?:\\.|[^\\\/])*?/,i,n)},p=(e,r,i)=>t.concat(t.concat("(?:",e,")"),r,/(?:\\.|[^\\\/])*?/,i,n),f=[a,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),o,{className:"string",contains:u,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},l,{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:d("s|tr|y",t.either(...c,{capture:!0}))},{begin:d("s|tr|y","\\(","\\)")},{begin:d("s|tr|y","\\[","\\]")},{begin:d("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:p("(?:m|qr)?",/\//,/\//)},{begin:p("m|qr",t.either(...c,{capture:!0}),/\1/)},{begin:p("m|qr",/\(/,/\)/)},{begin:p("m|qr",/\[/,/\]/)},{begin:p("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,s]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,s,l]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return i.contains=f,o.contains=f,{name:"Perl",aliases:["pl","pm"],keywords:r,contains:f}},php:function(e){const t=e.regex,n=/(?![A-Za-z0-9])(?![$])/,r=t.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,n),i=t.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,n),o=t.concat(/[A-Z]+/,n),s={scope:"variable",match:"\\$+"+r},a={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},l=e.inherit(e.APOS_STRING_MODE,{illegal:null}),u="[ \t\n]",c={scope:"string",variants:[e.inherit(e.QUOTE_STRING_MODE,{illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(a)}),l,{begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:e.QUOTE_STRING_MODE.contains.concat(a),"on:begin":(e,t)=>{t.data._beginMatch=e[1]||e[2]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}},e.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/})]},d={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},p=["false","null","true"],f=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],h=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],g={keyword:f,literal:(e=>{const t=[];return e.forEach(e=>{t.push(e),e.toLowerCase()===e?t.push(e.toUpperCase()):t.push(e.toLowerCase())}),t})(p),built_in:h},A=e=>e.map(e=>e.replace(/\|\d+$/,"")),m={variants:[{match:[/new/,t.concat(u,"+"),t.concat("(?!",A(h).join("\\b|"),"\\b)"),i],scope:{1:"keyword",4:"title.class"}}]},y=t.concat(r,"\\b(?!\\()"),b={variants:[{match:[t.concat(/::/,t.lookahead(/(?!class\b)/)),y],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[i,t.concat(/::/,t.lookahead(/(?!class\b)/)),y],scope:{1:"title.class",3:"variable.constant"}},{match:[i,t.concat("::",t.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[i,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},v={scope:"attr",match:t.concat(r,t.lookahead(":"),t.lookahead(/(?!::)/))},E={relevance:0,begin:/\(/,end:/\)/,keywords:g,contains:[v,s,b,e.C_BLOCK_COMMENT_MODE,c,d,m]},I={relevance:0,match:[/\b/,t.concat("(?!fn\\b|function\\b|",A(f).join("\\b|"),"|",A(h).join("\\b|"),"\\b)"),r,t.concat(u,"*"),t.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[E]};E.contains.push(I);const w=[v,b,e.C_BLOCK_COMMENT_MODE,c,d,m],C={begin:t.concat(/#\[\s*\\?/,t.either(i,o)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:p,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:p,keyword:["new","array"]},contains:["self",...w]},...w,{scope:"meta",variants:[{match:i},{match:o}]}]};return{case_insensitive:!1,keywords:g,contains:[C,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},{scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},{scope:"variable.language",match:/\$this\b/},s,I,b,{match:[/const/,/\s/,r],scope:{1:"keyword",3:"variable.constant"}},m,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:g,contains:["self",C,s,b,e.C_BLOCK_COMMENT_MODE,c,d]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},c,d]}},"php-template":function(e){return{name:"PHP template",subLanguage:"xml",contains:[{begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*",end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0})]}]}},plaintext:function(e){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}},python:function(e){const t=e.regex,n=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],i={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},o={className:"meta",begin:/^(>>>|\.\.\.) /},s={className:"subst",begin:/\{/,end:/\}/,keywords:i,illegal:/#/},a={begin:/\{\{/,relevance:0},l={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,o],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,o],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,o,a,s]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,o,a,s]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,a,s]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,a,s]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},u="[0-9](_?[0-9])*",c=`(\\b(${u}))?\\.(${u})|\\b(${u})\\.`,d=`\\b|${r.join("|")}`,p={className:"number",relevance:0,variants:[{begin:`(\\b(${u})|(${c}))[eE][+-]?(${u})[jJ]?(?=${d})`},{begin:`(${c})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${d})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${d})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${d})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${d})`},{begin:`\\b(${u})[jJ](?=${d})`}]},f={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:i,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},h={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i,contains:["self",o,p,l,e.HASH_COMMENT_MODE]}]};return s.contains=[l,p,o],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:i,illegal:/(<\/|\?)|=>/,contains:[o,p,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},l,f,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[h]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[p,h,l]}]}},"python-repl":function(e){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}},r:function(e){const t=e.regex,n=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,r=t.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),i=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,o=t.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/);return{name:"R",keywords:{$pattern:n,keyword:"function if in break next repeat else for while",literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/,starts:{end:t.lookahead(t.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)),endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{scope:"variable",variants:[{match:n},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}]}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"',relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{1:"operator",2:"number"},match:[i,r]},{scope:{1:"operator",2:"number"},match:[/%[^%]*%/,r]},{scope:{1:"punctuation",2:"number"},match:[o,r]},{scope:{2:"number"},match:[/[^a-zA-Z0-9._]|^/,r]}]},{scope:{3:"operator"},match:[n,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:i},{match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:o},{begin:"`",end:"`",contains:[{begin:/\\./}]}]}},ruby:function(e){const t=e.regex,n="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",r=t.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),i=t.concat(r,/(::\w+)*/),o={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield","include","extend","prepend","public","private","protected","raise","throw"],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},s={className:"doctag",begin:"@[A-Za-z]+"},a={begin:"#<",end:">"},l=[e.COMMENT("#","$",{contains:[s]}),e.COMMENT("^=begin","^=end",{contains:[s],relevance:10}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],u={className:"subst",begin:/#\{/,end:/\}/,keywords:o},c={className:"string",contains:[e.BACKSLASH_ESCAPE,u],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?</,end:/>/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:t.concat(/<<[-~]?'?/,t.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,u]})]}]},d="[0-9](_?[0-9])*",p={className:"number",relevance:0,variants:[{begin:`\\b([1-9](_?[0-9])*|0)(\\.(${d}))?([eE][+-]?(${d})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},f={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:o}]},h=[c,{variants:[{match:[/class\s+/,i,/\s+<\s+/,i]},{match:[/\b(class|module)\s+/,i]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:o},{match:[/(include|extend)\s+/,i],scope:{2:"title.class"},keywords:o},{relevance:0,match:[i,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:r,scope:"title.class"},{match:[/def/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[f]},{begin:e.IDENT_RE+"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[c,{begin:n}],relevance:0},p,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:o},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,u],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(a,l),relevance:0}].concat(a,l);u.contains=h,f.contains=h;const g=[{begin:/^\s*=>/,starts:{end:"$",contains:h}},{className:"meta.prompt",begin:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]|(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>)(?=[ ])",starts:{end:"$",keywords:o,contains:h}}];return l.unshift(a),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:o,illegal:/\/\*/,contains:[e.SHEBANG({binary:"ruby"})].concat(g).concat(l).concat(h)}},rust:function(e){const t=e.regex,n=/(r#)?/,r=t.concat(n,e.UNDERSCORE_IDENT_RE),i=t.concat(n,e.IDENT_RE),o={className:"title.function.invoke",relevance:0,begin:t.concat(/\b/,/(?!let|for|while|if|else|match\b)/,i,t.lookahead(/\s*\(/))},s="([ui](8|16|32|64|128|size)|f(32|64))?",a=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],l=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:l,keyword:["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],literal:["true","false","Some","None","Ok","Err"],built_in:a},illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.COMMENT("/\\*","\\*/",{contains:["self"]}),e.inherit(e.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+s},{begin:"\\b0o([0-7_]+)"+s},{begin:"\\b0x([A-Fa-f0-9_]+)"+s},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+s}],relevance:0},{begin:[/fn/,/\s+/,r],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,r],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,r,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:e.IDENT_RE+"::",keywords:{keyword:"Self",built_in:a,type:l}},{className:"punctuation",begin:"->"},o]}},scss:function(e){const t=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),n=OO,r=MO,i="@[a-z-]+",o={className:"variable",begin:"(\\$[a-zA-Z-][a-zA-Z0-9_-]*)\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+RO.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+n.join("|")+")"},o,{begin:/\(/,end:/\)/,contains:[t.CSS_NUMBER_MODE]},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+$O.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[t.BLOCK_COMMENT,o,t.HEXCOLOR,t.CSS_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.IMPORTANT,t.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:i,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:FO.join(" ")},contains:[{begin:i,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},o,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.HEXCOLOR,t.CSS_NUMBER_MODE]},t.FUNCTION_DISPATCH]}},shell:function(e){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}},sql:function(e){const t=e.regex,n=e.COMMENT("--","$"),r=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],i=r,o=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(e=>!r.includes(e)),s={match:t.concat(/\b/,t.either(...i),/\s*\(/),relevance:0,keywords:{built_in:i}};function a(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,"\\s+"))),/\b/)}const l={scope:"keyword",match:a(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]),relevance:0};return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:function(e,{exceptions:t,when:n}={}){const r=n;return t=t||[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:r(e)?`${e}|0`:e)}(o,{when:e=>e.length<3}),literal:["true","false","unknown"],type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"]},contains:[{scope:"type",match:a(["double precision","large object","with timezone","without timezone"])},l,s,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{match:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,{scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}},swift:function(e){const t={match:/\s+/,relevance:0},n=e.COMMENT("/\\*","\\*/",{contains:["self"]}),r=[e.C_LINE_COMMENT_MODE,n],i={match:[/\./,UO(...GO,...HO)],className:{2:"keyword"}},o={match:jO(/\./,UO(...qO)),relevance:0},s=qO.filter(e=>"string"==typeof e).concat(["_|0"]),a={variants:[{className:"keyword",match:UO(...qO.filter(e=>"string"!=typeof e).concat(WO).map(zO),...HO)}]},l={$pattern:UO(/\b\w+/,/#\w+/),keyword:s.concat(ZO),literal:JO},u=[i,o,a],c=[{match:jO(/\./,UO(...VO)),relevance:0},{className:"built_in",match:jO(/\b/,UO(...VO),/(?=\()/)}],d={match:/->/,relevance:0},p=[d,{className:"operator",relevance:0,variants:[{match:e$},{match:`\\.(\\.|${XO})+`}]}],f="([0-9]_*)+",h="([0-9a-fA-F]_*)+",g={className:"number",relevance:0,variants:[{match:`\\b(${f})(\\.(${f}))?([eE][+-]?(${f}))?\\b`},{match:`\\b0x(${h})(\\.(${h}))?([pP][+-]?(${f}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},A=(e="")=>({className:"subst",variants:[{match:jO(/\\/,e,/[0\\tnr"']/)},{match:jO(/\\/,e,/u\{[0-9a-fA-F]{1,8}\}/)}]}),m=(e="")=>({className:"subst",match:jO(/\\/,e,/[\t ]*(?:[\r\n]|\r\n)/)}),y=(e="")=>({className:"subst",label:"interpol",begin:jO(/\\/,e,/\(/),end:/\)/}),b=(e="")=>({begin:jO(e,/"""/),end:jO(/"""/,e),contains:[A(e),m(e),y(e)]}),v=(e="")=>({begin:jO(e,/"/),end:jO(/"/,e),contains:[A(e),y(e)]}),E={className:"string",variants:[b(),b("#"),b("##"),b("###"),v(),v("#"),v("##"),v("###")]},I=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}],w={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:I},C=e=>{const t=jO(e,/\//),n=jO(/\//,e);return{begin:t,end:n,contains:[...I,{scope:"comment",begin:`#(?!.*${n})`,end:/$/}]}},_={scope:"regexp",variants:[C("###"),C("##"),C("#"),w]},B={match:jO(/`/,r$,/`/)},D=[B,{className:"variable",match:/\$\d+/},{className:"variable",match:`\\$${n$}+`}],S=[{match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:s$,contains:[...p,g,E]}]}},{scope:"keyword",match:jO(/@/,UO(...o$),PO(UO(/\(/,/\s+/)))},{scope:"meta",match:jO(/@/,r$)}],k={match:PO(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:jO(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,n$,"+")},{className:"type",match:i$,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:jO(/\s+&\s+/,PO(i$)),relevance:0}]},x={begin:/</,end:/>/,keywords:l,contains:[...r,...u,...S,d,k]};k.contains.push(x);const Q={begin:/\(/,end:/\)/,relevance:0,keywords:l,contains:["self",{match:jO(r$,/\s*:/),keywords:"_|0",relevance:0},...r,_,...u,...c,...p,g,E,...D,...S,k]},N={begin:/</,end:/>/,keywords:"repeat each",contains:[...r,k]},T={begin:/\(/,end:/\)/,keywords:l,contains:[{begin:UO(PO(jO(r$,/\s*:/)),PO(jO(r$,/\s+/,r$,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:r$}]},...r,...u,...p,g,E,...S,k,Q],endsParent:!0,illegal:/["']/},R={match:[/(func|macro)/,/\s+/,UO(B.match,r$,e$)],className:{1:"keyword",3:"title.function"},contains:[N,T,t],illegal:[/\[/,/%/]},F={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[N,T,t],illegal:/\[|%/},M={match:[/operator/,/\s+/,e$],className:{1:"keyword",3:"title"}},O={begin:[/precedencegroup/,/\s+/,i$],className:{1:"keyword",3:"title"},contains:[k],keywords:[...KO,...JO],end:/}/},$={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,r$,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:l,contains:[N,...u,{begin:/:/,end:/\{/,keywords:l,contains:[{scope:"title.class.inherited",match:i$},...u],relevance:0}]};for(const L of E.variants){const e=L.contains.find(e=>"interpol"===e.label);e.keywords=l;const t=[...u,...c,...p,g,E,...D];e.contains=[...t,{begin:/\(/,end:/\)/,contains:["self",...t]}]}return{name:"Swift",keywords:l,contains:[...r,R,F,{match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},{match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},$,M,O,{beginKeywords:"import",end:/$/,contains:[...r],relevance:0},_,...u,...c,...p,g,E,...D,...S,k,Q]}},typescript:function(e){const t=e.regex,n=function(e){const t=e.regex,n=a$,r="<>",i="</>",o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let i;">"===r&&(((e,{after:t})=>{const n="</"+e[0].slice(1);return-1!==e.input.indexOf(n,t)})(e,{after:n})||t.ignoreMatch());const o=e.input.substring(n);((i=o.match(/^\s*=/))||(i=o.match(/^\s+extends\s+/))&&0===i.index)&&t.ignoreMatch()}},s={$pattern:a$,keyword:l$,literal:u$,built_in:h$,"variable.language":f$},a="[0-9](_?[0-9])*",l=`\\.(${a})`,u="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",c={className:"number",variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${a})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:s,contains:[]},p={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},f={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},h={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},g={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},A={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},m=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,f,h,g,{match:/\$\d+/},c];d.contains=m.concat({begin:/\{/,end:/\}/,keywords:s,contains:["self"].concat(m)});const y=[].concat(A,d.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:["self"].concat(y)}]),v={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},E={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},I={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...c$,...d$]}},w={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[v],illegal:/%/},C={match:t.concat(/\b/,(_=[...p$,"super","import"].map(e=>`${e}\\s*\\(`),t.concat("(?!",_.join("|"),")")),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0};var _;const B={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},D={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},v]},S="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",k={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(S)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[v]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:I},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,f,h,g,A,{match:/\$\d+/},c,I,{scope:"attr",match:n+t.lookahead(":"),relevance:0},k,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[A,e.REGEXP_MODE,{className:"function",begin:S,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:i},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[v,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},B,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[v]},C,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},E,D,{match:/\$[(.]/}]}}(e),r=a$,i=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],o={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},s={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:i},contains:[n.exports.CLASS_REFERENCE]},a={$pattern:a$,keyword:l$.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:u$,built_in:h$.concat(i),"variable.language":f$},l={className:"meta",begin:"@"+r},u=(e,t,n)=>{const r=e.contains.findIndex(e=>e.label===t);if(-1===r)throw new Error("can not find mode to replace");e.contains.splice(r,1,n)};Object.assign(n.keywords,a),n.exports.PARAMS_CONTAINS.push(l);const c=n.contains.find(e=>"attr"===e.scope),d=Object.assign({},c,{match:t.concat(r,t.lookahead(/\s*\?:/))});return n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,c,d]),n.contains=n.contains.concat([l,o,s,d]),u(n,"shebang",e.SHEBANG()),u(n,"use_strict",{className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/}),n.contains.find(e=>"func.def"===e.label).relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n},vbnet:function(e){const t=e.regex,n=/\d{1,2}\/\d{1,2}\/\d{4}/,r=/\d{4}-\d{1,2}-\d{1,2}/,i=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,o=/\d{1,2}(:\d{1,2}){1,2}/,s={className:"literal",variants:[{begin:t.concat(/# */,t.either(r,n),/ *#/)},{begin:t.concat(/# */,o,/ *#/)},{begin:t.concat(/# */,i,/ *#/)},{begin:t.concat(/# */,t.either(r,n),/ +/,t.either(i,o),/ *#/)}]},a=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),l=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]});return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0,classNameAliases:{label:"symbol"},keywords:{keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort",type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort",literal:"true false nothing"},illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[{className:"string",begin:/"(""|[^/n])"C\b/},{className:"string",begin:/"/,end:/"/,illegal:/\n/,contains:[{begin:/""/}]},s,{className:"number",relevance:0,variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},{className:"label",begin:/^\w+:/},a,l,{className:"meta",begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,end:/$/,keywords:{keyword:"const disable else elseif enable end externalsource if region then"},contains:[l]}]}},wasm:function(e){e.regex;const t=e.COMMENT(/\(;/,/;\)/);return t.contains.push("self"),{name:"WebAssembly",keywords:{$pattern:/[\w.]+/,keyword:["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"]},contains:[e.COMMENT(/;;/,/$/),t,{match:[/(?:offset|align)/,/\s*/,/=/],className:{1:"keyword",3:"operator"}},{className:"variable",begin:/\$[\w_]+/},{match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},{begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword",3:"title.function"}},e.QUOTE_STRING_MODE,{match:/(i32|i64|f32|f64)(?!\.)/,className:"type"},{className:"keyword",match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/},{className:"number",relevance:0,match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/}]}},xml:function(e){const t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},i={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=e.inherit(i,{begin:/\(/,end:/\)/}),s=e.inherit(e.APOS_STRING_MODE,{className:"string"}),a=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),l={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:/[\p{L}0-9._:-]+/u,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[r]},{begin:/'/,end:/'/,contains:[r]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[i,a,s,o,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[i,o,a,s]}]}]},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},r,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[a]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[l],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[l],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(/</,t.lookahead(t.concat(n,t.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:l}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}},yaml:function(e){const t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},i=e.inherit(r,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),o={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},s={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},a={begin:/\{/,end:/\}/,contains:[s],illegal:"\\n",relevance:0},l={begin:"\\[",end:"\\]",contains:[s],illegal:"\\n",relevance:0},u=[{className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},o,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},a,l,{className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},r],c=[...u];return c.pop(),c.push(i),s.contains=c,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:u}}};var A$,m$;function y$(){if(m$)return A$;function e(t){return t instanceof Map?t.clear=t.delete=t.set=function(){throw new Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=function(){throw new Error("set is read-only")}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{const r=t[n],i=typeof r;"object"!==i&&"function"!==i||Object.isFrozen(r)||e(r)}),t}m$=1;class t{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function n(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}function r(e,...t){const n=Object.create(null);for(const r in e)n[r]=e[r];return t.forEach(function(e){for(const t in e)n[t]=e[t]}),n}const i=e=>!!e.scope;class o{constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=n(e)}openNode(e){if(!i(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const n=e.split(".");return[`${t}${n.shift()}`,...n.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){i(e)&&(this.buffer+="</span>")}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}}const s=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class a{constructor(){this.rootNode=s(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){const t=s({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{a._collapse(e)}))}}class l extends a{constructor(e){super(),this.options=e}addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){const n=e.root;t&&(n.scope=`language:${t}`),this.add(n)}toHTML(){return new o(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function u(e){return e?"string"==typeof e?e:e.source:null}function c(e){return f("(?=",e,")")}function d(e){return f("(?:",e,")*")}function p(e){return f("(?:",e,")?")}function f(...e){return e.map(e=>u(e)).join("")}function h(...e){const t=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(t.capture?"":"?:")+e.map(e=>u(e)).join("|")+")"}function g(e){return new RegExp(e.toString()+"|").exec("").length-1}const A=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function m(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;const t=n;let r=u(e),i="";for(;r.length>0;){const e=A.exec(r);if(!e){i+=r;break}i+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?i+="\\"+String(Number(e[1])+t):(i+=e[0],"("===e[0]&&n++)}return i}).map(e=>`(${e})`).join(t)}const y="[a-zA-Z]\\w*",b="[a-zA-Z_]\\w*",v="\\b\\d+(\\.\\d+)?",E="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",I="\\b(0b[01]+)",w={begin:"\\\\[\\s\\S]",relevance:0},C={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[w]},_={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[w]},B=function(e,t,n={}){const i=r({scope:"comment",begin:e,end:t,contains:[]},n);i.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const o=h("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return i.contains.push({begin:f(/[ ]+/,"(",o,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),i},D=B("//","$"),S=B("/\\*","\\*/"),k=B("#","$"),x={scope:"number",begin:v,relevance:0},Q={scope:"number",begin:E,relevance:0},N={scope:"number",begin:I,relevance:0},T={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[w,{begin:/\[/,end:/\]/,relevance:0,contains:[w]}]},R={scope:"title",begin:y,relevance:0},F={scope:"title",begin:b,relevance:0},M={begin:"\\.\\s*"+b,relevance:0};var O=Object.freeze({__proto__:null,APOS_STRING_MODE:C,BACKSLASH_ESCAPE:w,BINARY_NUMBER_MODE:N,BINARY_NUMBER_RE:I,COMMENT:B,C_BLOCK_COMMENT_MODE:S,C_LINE_COMMENT_MODE:D,C_NUMBER_MODE:Q,C_NUMBER_RE:E,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:k,IDENT_RE:y,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:M,NUMBER_MODE:x,NUMBER_RE:v,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:_,REGEXP_MODE:T,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=f(t,/.*\b/,e.binary,/\b.*/)),r({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},TITLE_MODE:R,UNDERSCORE_IDENT_RE:b,UNDERSCORE_TITLE_MODE:F});function $(e,t){"."===e.input[e.index-1]&&t.ignoreMatch()}function L(e,t){void 0!==e.className&&(e.scope=e.className,delete e.className)}function P(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=$,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0))}function j(e,t){Array.isArray(e.illegal)&&(e.illegal=h(...e.illegal))}function U(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function z(e,t){void 0===e.relevance&&(e.relevance=1)}const G=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]}),e.keywords=n.keywords,e.begin=f(n.beforeMatch,c(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:!0})]},e.relevance=0,delete n.beforeMatch},H=["of","and","for","in","not","or","if","then","parent","list","value"];function W(e,t,n="keyword"){const r=Object.create(null);return"string"==typeof e?i(n,e.split(" ")):Array.isArray(e)?i(n,e):Object.keys(e).forEach(function(n){Object.assign(r,W(e[n],t,n))}),r;function i(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){const n=t.split("|");r[n[0]]=[e,q(n[0],n[1])]})}}function q(e,t){return t?Number(t):function(e){return H.includes(e.toLowerCase())}(e)?0:1}const J={},K=e=>{console.error(e)},Z=(e,...t)=>{console.log(`WARN: ${e}`,...t)},V=(e,t)=>{J[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),J[`${e}/${t}`]=!0)},Y=new Error;function X(e,t,{key:n}){let r=0;const i=e[n],o={},s={};for(let a=1;a<=t.length;a++)s[a+r]=i[a],o[a+r]=!0,r+=g(t[a-1]);e[n]=s,e[n]._emit=o,e[n]._multi=!0}function ee(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope)}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw K("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),Y;if("object"!=typeof e.beginScope||null===e.beginScope)throw K("beginScope must be object"),Y;X(e,e.begin,{key:"beginScope"}),e.begin=m(e.begin,{joinWith:""})}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw K("skip, excludeEnd, returnEnd not compatible with endScope: {}"),Y;if("object"!=typeof e.endScope||null===e.endScope)throw K("endScope must be object"),Y;X(e,e.end,{key:"endScope"}),e.end=m(e.end,{joinWith:""})}}(e)}function te(e){function t(t,n){return new RegExp(u(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":""))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=g(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=t(m(e,{joinWith:"|"}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const n=t.findIndex((e,t)=>t>0&&void 0!==e),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class i{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else{const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=r(e.classNameAliases||{}),function n(o,s){const a=o;if(o.isCompiled)return a;[L,U,ee,G].forEach(e=>e(o,s)),e.compilerExtensions.forEach(e=>e(o,s)),o.__beforeBegin=null,[P,j,z].forEach(e=>e(o,s)),o.isCompiled=!0;let l=null;return"object"==typeof o.keywords&&o.keywords.$pattern&&(o.keywords=Object.assign({},o.keywords),l=o.keywords.$pattern,delete o.keywords.$pattern),l=l||/\w+/,o.keywords&&(o.keywords=W(o.keywords,e.case_insensitive)),a.keywordPatternRe=t(l,!0),s&&(o.begin||(o.begin=/\B|\b/),a.beginRe=t(a.begin),o.end||o.endsWithParent||(o.end=/\B|\b/),o.end&&(a.endRe=t(a.end)),a.terminatorEnd=u(a.end)||"",o.endsWithParent&&s.terminatorEnd&&(a.terminatorEnd+=(o.end?"|":"")+s.terminatorEnd)),o.illegal&&(a.illegalRe=t(o.illegal)),o.contains||(o.contains=[]),o.contains=[].concat(...o.contains.map(function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return r(e,{variants:null},t)}));if(e.cachedVariants)return e.cachedVariants;if(ne(e))return r(e,{starts:e.starts?r(e.starts):null});if(Object.isFrozen(e))return r(e);return e}("self"===e?o:e)})),o.contains.forEach(function(e){n(e,a)}),o.starts&&n(o.starts,s),a.matcher=function(e){const t=new i;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(a),a}(e)}function ne(e){return!!e&&(e.endsWithParent||ne(e.starts))}class re extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}}const ie=n,oe=r,se=Symbol("nomatch"),ae=function(n){const r=Object.create(null),i=Object.create(null),o=[];let s=!0;const a="Could not find the language '{}', did you forget to load/include a language module?",u={disableAutodetect:!0,name:"Plain text",contains:[]};let g={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:l};function A(e){return g.noHighlightRe.test(e)}function m(e,t,n){let r="",i="";"object"==typeof t?(r=e,n=t.ignoreIllegals,i=t.language):(V("10.7.0","highlight(lang, code, ...args) has been deprecated."),V("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),i=e,r=t),void 0===n&&(n=!0);const o={code:r,language:i};B("before:highlight",o);const s=o.result?o.result:y(o.language,o.code,n);return s.code=o.code,B("after:highlight",s),s}function y(e,n,i,o){const l=Object.create(null);function u(e,t){return e.keywords[t]}function c(){if(!D.keywords)return void k.addText(x);let e=0;D.keywordPatternRe.lastIndex=0;let t=D.keywordPatternRe.exec(x),n="";for(;t;){n+=x.substring(e,t.index);const r=C.case_insensitive?t[0].toLowerCase():t[0],i=u(D,r);if(i){const[e,o]=i;if(k.addText(n),n="",l[r]=(l[r]||0)+1,l[r]<=7&&(Q+=o),e.startsWith("_"))n+=t[0];else{const n=C.classNameAliases[e]||e;p(t[0],n)}}else n+=t[0];e=D.keywordPatternRe.lastIndex,t=D.keywordPatternRe.exec(x)}n+=x.substring(e),k.addText(n)}function d(){null!=D.subLanguage?function(){if(""===x)return;let e=null;if("string"==typeof D.subLanguage){if(!r[D.subLanguage])return void k.addText(x);e=y(D.subLanguage,x,!0,S[D.subLanguage]),S[D.subLanguage]=e._top}else e=b(x,D.subLanguage.length?D.subLanguage:null);D.relevance>0&&(Q+=e.relevance),k.__addSublanguage(e._emitter,e.language)}():c(),x=""}function p(e,t){""!==e&&(k.startScope(t),k.addText(e),k.endScope())}function f(e,t){let n=1;const r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}const r=C.classNameAliases[e[n]]||e[n],i=t[n];r?p(i,r):(x=i,c(),x=""),n++}}function h(e,t){return e.scope&&"string"==typeof e.scope&&k.openNode(C.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(p(x,C.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),x=""):e.beginScope._multi&&(f(e.beginScope,t),x="")),D=Object.create(e,{parent:{value:D}}),D}function A(e,n,r){let i=function(e,t){const n=e&&e.exec(t);return n&&0===n.index}(e.endRe,r);if(i){if(e["on:end"]){const r=new t(e);e["on:end"](n,r),r.isMatchIgnored&&(i=!1)}if(i){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return A(e.parent,n,r)}function m(e){return 0===D.matcher.regexIndex?(x+=e[0],1):(R=!0,0)}function v(e){const t=e[0],r=n.substring(e.index),i=A(D,e,r);if(!i)return se;const o=D;D.endScope&&D.endScope._wrap?(d(),p(t,D.endScope._wrap)):D.endScope&&D.endScope._multi?(d(),f(D.endScope,e)):o.skip?x+=t:(o.returnEnd||o.excludeEnd||(x+=t),d(),o.excludeEnd&&(x=t));do{D.scope&&k.closeNode(),D.skip||D.subLanguage||(Q+=D.relevance),D=D.parent}while(D!==i.parent);return i.starts&&h(i.starts,e),o.returnEnd?0:t.length}let E={};function I(r,o){const a=o&&o[0];if(x+=r,null==a)return d(),0;if("begin"===E.type&&"end"===o.type&&E.index===o.index&&""===a){if(x+=n.slice(o.index,o.index+1),!s){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=E.rule,t}return 1}if(E=o,"begin"===o.type)return function(e){const n=e[0],r=e.rule,i=new t(r),o=[r.__beforeBegin,r["on:begin"]];for(const t of o)if(t&&(t(e,i),i.isMatchIgnored))return m(n);return r.skip?x+=n:(r.excludeBegin&&(x+=n),d(),r.returnBegin||r.excludeBegin||(x=n)),h(r,e),r.returnBegin?0:n.length}(o);if("illegal"===o.type&&!i){const e=new Error('Illegal lexeme "'+a+'" for mode "'+(D.scope||"<unnamed>")+'"');throw e.mode=D,e}if("end"===o.type){const e=v(o);if(e!==se)return e}if("illegal"===o.type&&""===a)return x+="\n",1;if(T>1e5&&T>3*o.index){throw new Error("potential infinite loop, way more iterations than matches")}return x+=a,a.length}const C=w(e);if(!C)throw K(a.replace("{}",e)),new Error('Unknown language: "'+e+'"');const _=te(C);let B="",D=o||_;const S={},k=new g.__emitter(g);!function(){const e=[];for(let t=D;t!==C;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>k.openNode(e))}();let x="",Q=0,N=0,T=0,R=!1;try{if(C.__emitTokens)C.__emitTokens(n,k);else{for(D.matcher.considerAll();;){T++,R?R=!1:D.matcher.considerAll(),D.matcher.lastIndex=N;const e=D.matcher.exec(n);if(!e)break;const t=I(n.substring(N,e.index),e);N=e.index+t}I(n.substring(N))}return k.finalize(),B=k.toHTML(),{language:e,value:B,relevance:Q,illegal:!1,_emitter:k,_top:D}}catch(F){if(F.message&&F.message.includes("Illegal"))return{language:e,value:ie(n),illegal:!0,relevance:0,_illegalBy:{message:F.message,index:N,context:n.slice(N-100,N+100),mode:F.mode,resultSoFar:B},_emitter:k};if(s)return{language:e,value:ie(n),illegal:!1,relevance:0,errorRaised:F,_emitter:k,_top:D};throw F}}function b(e,t){t=t||g.languages||Object.keys(r);const n=function(e){const t={value:ie(e),illegal:!1,relevance:0,_top:u,_emitter:new g.__emitter(g)};return t._emitter.addText(e),t}(e),i=t.filter(w).filter(_).map(t=>y(t,e,!1));i.unshift(n);const o=i.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(w(e.language).supersetOf===t.language)return 1;if(w(t.language).supersetOf===e.language)return-1}return 0}),[s,a]=o,l=s;return l.secondBest=a,l}function v(e){let t=null;const n=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const n=g.languageDetectRe.exec(t);if(n){const t=w(n[1]);return t||(Z(a.replace("{}",n[1])),Z("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}return t.split(/\s+/).find(e=>A(e)||w(e))}(e);if(A(n))return;if(B("before:highlightElement",{el:e,language:n}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(g.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),g.throwUnescapedHTML)){throw new re("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const r=t.textContent,o=n?m(r,{language:n,ignoreIllegals:!0}):b(r);e.innerHTML=o.value,e.dataset.highlighted="yes",function(e,t,n){const r=t&&i[t]||n;e.classList.add("hljs"),e.classList.add(`language-${r}`)}(e,n,o.language),e.result={language:o.language,re:o.relevance,relevance:o.relevance},o.secondBest&&(e.secondBest={language:o.secondBest.language,relevance:o.secondBest.relevance}),B("after:highlightElement",{el:e,result:o,text:r})}let E=!1;function I(){if("loading"===document.readyState)return E||window.addEventListener("DOMContentLoaded",function(){I()},!1),void(E=!0);document.querySelectorAll(g.cssSelector).forEach(v)}function w(e){return e=(e||"").toLowerCase(),r[e]||r[i[e]]}function C(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{i[e.toLowerCase()]=t})}function _(e){const t=w(e);return t&&!t.disableAutodetect}function B(e,t){const n=e;o.forEach(function(e){e[n]&&e[n](t)})}Object.assign(n,{highlight:m,highlightAuto:b,highlightAll:I,highlightElement:v,highlightBlock:function(e){return V("10.7.0","highlightBlock will be removed entirely in v12.0"),V("10.7.0","Please use highlightElement now."),v(e)},configure:function(e){g=oe(g,e)},initHighlighting:()=>{I(),V("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")},initHighlightingOnLoad:function(){I(),V("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")},registerLanguage:function(e,t){let i=null;try{i=t(n)}catch(o){if(K("Language definition for '{}' could not be registered.".replace("{}",e)),!s)throw o;K(o),i=u}i.name||(i.name=e),r[e]=i,i.rawDefinition=t.bind(null,n),i.aliases&&C(i.aliases,{languageName:e})},unregisterLanguage:function(e){delete r[e];for(const t of Object.keys(i))i[t]===e&&delete i[t]},listLanguages:function(){return Object.keys(r)},getLanguage:w,registerAliases:C,autoDetection:_,inherit:oe,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t))}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t))})}(e),o.push(e)},removePlugin:function(e){const t=o.indexOf(e);-1!==t&&o.splice(t,1)}}),n.debugMode=function(){s=!1},n.safeMode=function(){s=!0},n.versionString="11.11.1",n.regex={concat:f,lookahead:c,either:h,optional:p,anyNumberOfTimes:d};for(const t in O)"object"==typeof O[t]&&e(O[t]);return Object.assign(n,O),n},le=ae({});return le.newInstance=()=>ae({}),A$=le,le.HighlightJS=le,le.default=le,A$}const b$=e(y$()),v$={};function E$(e){const t=b$.newInstance();return e&&i(e),{highlight:n,highlightAuto:function(e,i){const o=(i||v$).subset||r();let s,a=-1,l=0;for(;++a<o.length;){const r=o[a];if(!t.getLanguage(r))continue;const u=n(r,e,i);u.data&&void 0!==u.data.relevance&&u.data.relevance>l&&(l=u.data.relevance,s=u)}return s||{type:"root",children:[],data:{language:void 0,relevance:l}}},listLanguages:r,register:i,registerAlias:function(e,n){if("string"==typeof e)t.registerAliases("string"==typeof n?n:[...n],{languageName:e});else{let n;for(n in e)if(Object.hasOwn(e,n)){const r=e[n];t.registerAliases("string"==typeof r?r:[...r],{languageName:n})}}},registered:function(e){return Boolean(t.getLanguage(e))}};function n(e,n,r){const i=r||v$,o="string"==typeof i.prefix?i.prefix:"hljs-";if(!t.getLanguage(e))throw new Error("Unknown language: `"+e+"` is not registered");t.configure({__emitter:I$,classPrefix:o});const s=t.highlight(n,{ignoreIllegals:!0,language:e});if(s.errorRaised)throw new Error("Could not highlight with `Highlight.js`",{cause:s.errorRaised});const a=s._emitter.root,l=a.data;return l.language=s.language,l.relevance=s.relevance,a}function r(){return t.listLanguages()}function i(e,n){if("string"==typeof e)t.registerLanguage(e,n);else{let n;for(n in e)Object.hasOwn(e,n)&&t.registerLanguage(n,e[n])}}}class I${constructor(e){this.options=e,this.root={type:"root",children:[],data:{language:void 0,relevance:0}},this.stack=[this.root]}addText(e){if(""===e)return;const t=this.stack[this.stack.length-1],n=t.children[t.children.length-1];n&&"text"===n.type?n.value+=e:t.children.push({type:"text",value:e})}startScope(e){this.openNode(String(e))}endScope(){this.closeNode()}__addSublanguage(e,t){const n=this.stack[this.stack.length-1],r=e.root.children;t?n.children.push({type:"element",tagName:"span",properties:{className:[t]},children:r}):n.children.push(...r)}openNode(e){const t=this,n={type:"element",tagName:"span",properties:{className:e.split(".").map(function(e,n){return n?e+"_".repeat(n):t.options.classPrefix+e})},children:[]};this.stack[this.stack.length-1].children.push(n),this.stack.push(n)}closeNode(){this.stack.pop()}finalize(){}toHTML(){return""}}const w$=E$(g$);function C$({fileName:e,diffContent:t,maxHeight:n,maxWidth:r,terminalWidth:i,tabWidth:o=4}){const s=oO(i),a=qe.useMemo(()=>s.getConstrainedContentWidth(),[s]);if(!t||"string"!=typeof t)return We.jsx(xi,{color:RM,children:"No diff content."});const l=function(e){const t=e.split("\n"),n=[];let r=0,i=0,o=!1;const s=/^@@ -(\d+),?\d* \+(\d+),?\d* @@/;for(const a of t){const e=a.match(s);if(e){const[,t="0",s="0"]=e;r=parseInt(t,10),i=parseInt(s,10),o=!0,n.push({type:"hunk",content:a}),r--,i--;continue}if(o)a.startsWith("+")?(i++,n.push({type:"add",newLine:i,content:a.substring(1)})):a.startsWith("-")?(r++,n.push({type:"del",oldLine:r,content:a.substring(1)})):a.startsWith(" ")?(r++,i++,n.push({type:"context",oldLine:r,newLine:i,content:a.substring(1)})):a.startsWith("\\")&&n.push({type:"other",content:a});else if(a.startsWith("--- ")||a.startsWith("+++ ")||a.startsWith("diff --git")||a.startsWith("index ")||a.startsWith("similarity index")||a.startsWith("rename from")||a.startsWith("rename to")||a.startsWith("new file mode")||a.startsWith("deleted file mode"))continue}return n}(t);if(0===l.length)return We.jsx(ki,{borderStyle:"round",borderColor:QM,padding:1,children:We.jsx(xi,{color:QM,children:"No changes detected."})});let u;if(l.every(e=>"add"===e.type||"hunk"===e.type||"other"===e.type||e.content.startsWith("diff --git")||e.content.startsWith("new file mode"))){const t=l.filter(e=>"add"===e.type).map(e=>e.content).join("\n"),i=e?.split(".").pop()||null;u=function(e,t,n,r){const i=e.replace(/\n$/,"");try{let e=i.split("\n");const o=String(e.length).length;let s=0;if(void 0!==n&&(n=Math.max(n,5),e.length>n)){const t=e.length-n;s=t,e=e.slice(t)}const a=e=>t&&w$.registered(t)?w$.highlight(t,e):w$.highlightAuto(e);return We.jsx(ZM,{maxHeight:n??50,maxWidth:r,children:e.map((e,t)=>{const n=B$(a(e),void 0),r=null!==n?n:e;return We.jsxs(ki,{children:[We.jsx(xi,{color:QM,children:`${String(t+1+s).padStart(o," ")} `}),We.jsx(xi,{color:xM,wrap:"wrap",children:r})]},t)})})}catch(qK){ex.error(`[colorizeCode] Error highlighting code for language "${t}":`,qK);const o=i.split("\n"),s=String(o.length).length;return We.jsx(ZM,{maxHeight:n,maxWidth:r,children:o.map((e,t)=>We.jsxs(ki,{children:[We.jsx(xi,{color:xM,children:`${String(t+1).padStart(s," ")} `}),We.jsx(xi,{color:QM,children:e})]},t))})}}(t,i?{js:"javascript",ts:"typescript",jsx:"javascript",tsx:"typescript",py:"python",json:"json",css:"css",html:"html",sh:"bash",bash:"bash",md:"markdown",yaml:"yaml",yml:"yaml",txt:"plaintext",java:"java",c:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",rb:"ruby",go:"go",rs:"rust",php:"php",xml:"xml",sql:"sql"}[i]||null:null,n,r||a)}else u=_$(l,e,o,n,i,r||a);return u}const _$=(e,t,n,r,i,o)=>{const s=e.map(e=>({...e,content:e.content.replace(/\t/g," ".repeat(n))})).filter(e=>"hunk"!==e.type&&"other"!==e.type);if(0===s.length)return We.jsx(ki,{borderStyle:"round",borderColor:QM,padding:1,children:We.jsx(xi,{color:QM,children:"No changes detected."})});let a=1/0;for(const c of s){if(""===c.content.trim())continue;const e=c.content.search(/\S/),t=-1===e?0:e;a=Math.min(a,t)}isFinite(a)||(a=0);const l=t?`diff-box-${t}`:`diff-box-${ge.createHash("sha1").update(JSON.stringify(e)).digest("hex")}`;let u=null;return We.jsx(ZM,{maxHeight:r??50,maxWidth:o,children:s.reduce((e,t,n)=>{let r=null;"add"===t.type||"context"===t.type?r=t.newLine??null:"del"===t.type&&(r=t.oldLine??null),null!==u&&null!==r&&r>u+5+1&&e.push(We.jsx(ki,{children:We.jsx(xi,{wrap:"truncate",children:"═".repeat(i)})},`gap-${n}`));const o=`diff-line-${n}`;let s,l="",c=" ",d=!1;switch(t.type){case"add":l=(t.newLine??"").toString(),s=NM,c="+",u=t.newLine??null;break;case"del":l=(t.oldLine??"").toString(),s=TM,c="-",void 0!==t.oldLine&&(u=t.oldLine);break;case"context":l=(t.newLine??"").toString(),d=!0,c=" ",u=t.newLine??null;break;default:return e}const p=t.content.substring(a);return e.push(We.jsxs(ki,{flexDirection:"row",children:[We.jsxs(xi,{color:QM,children:[l.padEnd(4)," "]}),We.jsxs(xi,{color:s,dimColor:d,children:[c," "]}),We.jsx(xi,{color:s,dimColor:d,wrap:"wrap",children:p})]},o)),e},[])},l)};function B$(e,t){if("text"===e.type)return We.jsx(xi,{color:t,children:e.value});if("element"===e.type){const n=e.properties?.className||[];let r;for(let e=n.length-1;e>=0;e--){const t=n[e];if(t&&(r=D$(t),r))break}const i=r||t,o=e.children?.map((e,t)=>We.jsx(Je.Fragment,{children:B$(e,i)},t));return We.jsx(Je.Fragment,{children:o})}return"root"===e.type&&e.children&&0!==e.children.length?e.children?.map((e,n)=>We.jsx(Je.Fragment,{children:B$(e,t)},n)):null}function D$(e){return{"hljs-keyword":FM,"hljs-built_in":FM,"hljs-type":FM,"hljs-literal":FM,"hljs-string":NM,"hljs-regexp":NM,"hljs-number":RM,"hljs-comment":QM,"hljs-quote":QM,"hljs-function":MM,"hljs-title":MM,"hljs-variable":xM,"hljs-name":xM,"hljs-operator":OM,"hljs-punctuation":OM,"hljs-meta":TM,"hljs-tag":TM}[e]}const S$="pending",k$="in_progress",x$="completed",Q$="cancelled",N$="high",T$="medium",R$="low",F$=ug({id:mh().describe("Unique identifier for the todo item"),content:mh().describe("Brief description of the task"),status:_g([S$,k$,x$,Q$]).describe("Current status of the task"),priority:_g([N$,T$,R$]).default(T$).describe("Priority level of the task"),createdAt:mh().optional().describe("When the todo was created (ISO string)"),completedAt:mh().optional().describe("When the todo was completed (ISO string)")}),M$=ug({todos:ag(F$).describe("The updated todo list")});function O$(e){if(0===e.length)return"creating";const t={pending:0,inProgress:0,completed:0,cancelled:0};e.forEach(e=>{switch(e.status){case S$:t.pending++;break;case k$:t.inProgress++;break;case x$:t.completed++;break;case Q$:t.cancelled++}});return 0===t.pending+t.inProgress?"completing":t.pending===e.length?"creating":"updating"}function $$(e){const t={pending:0,inProgress:0,completed:0,cancelled:0};return e.forEach(e=>{switch(e.status){case S$:t.pending++;break;case k$:t.inProgress++;break;case x$:t.completed++;break;case Q$:t.cancelled++}}),{todos:e,totalCount:e.length,pendingCount:t.pending,inProgressCount:t.inProgress,completedCount:t.completed,cancelledCount:t.cancelled,phase:O$(e)}}function L$(e){const t=e.pendingCount+e.inProgressCount;if(0===t)return"completing"===e.phase?"Plan completed":"Plan";switch(e.phase){case"creating":return"Creating plan";case"completing":return"Completing plan";default:return`${t} ${1===t?"todo":"todos"}`}}function P$({todos:e,metadata:t,maxHeight:n,maxWidth:r,showPriority:i=!1,compact:o=!1}){if(0===e.length)return We.jsx(ki,{paddingX:1,children:We.jsx(xi,{color:"gray",italic:!0,children:"No todos"})});const s=r?r-8:80;return We.jsxs(ki,{flexDirection:"column",height:n,children:[e.map((e,t)=>{const n=(e=>{switch(e){case x$:return{icon:"✓",color:"green"};case k$:return{icon:"⏳",color:"yellow"};case Q$:return{icon:"✗",color:"red"};default:return{icon:"☐",color:"white"}}})(e.status),a=(e=>{switch(e){case N$:return{text:"!",color:"red"};case T$:return{text:"→",color:"yellow"};case R$:return{text:"·",color:"gray"};default:return{text:"→",color:"yellow"}}})(e.priority);let l=e.content;var u,c;return r&&(c=s,l=(u=l).length<=c?u:u.substring(0,c-3)+"..."),We.jsxs(ki,{paddingX:1,marginY:o?0:void 0,children:[We.jsx(xi,{color:n.color,children:n.icon}),i&&We.jsx(ki,{marginLeft:1,children:We.jsx(xi,{color:a.color,children:a.text})}),We.jsx(ki,{marginLeft:1,children:We.jsx(xi,{color:e.status===x$?"gray":"white",strikethrough:e.status===Q$,bold:e.status===k$,wrap:"wrap",children:l})})]},e.id)}),t&&!o&&We.jsx(ki,{paddingX:1,marginTop:1,borderTop:!0,borderStyle:"single",borderColor:"gray",children:We.jsxs(xi,{color:"gray",dimColor:!0,children:["Total: ",t.totalCount," | Pending: ",t.pendingCount," | In Progress:"," ",t.inProgressCount," | Completed: ",t.completedCount,t.cancelledCount>0&&` | Cancelled: ${t.cancelledCount}`]})})]})}function j$({tool:e,emphasis:t="medium",maxHeight:n,maxWidth:r,terminalWidth:i,showResult:o=!0,compact:s=!1,isExpanded:a=!1,onToggleExpand:l}){const u=DM(t=>e.status===SM.Executing?t.streams.get(e.toolCallId):void 0),c=(()=>{switch(t){case"high":case"medium":default:return"white";case"low":return"gray"}})(),d="high"===t,p=(e.name||"").toLowerCase(),f="todowrite"===p||"todoread"===p,h=e.result?.metadata&&(e.result.metadata.todos||e.result.metadata.todoMetadata)&&e.result?.metadata?{todos:e.result.metadata.todos||[],metadata:e.result.metadata.todoMetadata||void 0}:null,g=s&&!a?function(e){const t=(e.name||"").toLowerCase();if(!["readfile","read_file","readmanyfiles","grep","listdirectory","list_dir","glob","todowrite","todoread"].includes(t))return null;if(e.status===SM.Error)switch(t){case"readfile":case"read_file":return"Read(failed)";case"readmanyfiles":return"ReadMany(failed)";case"grep":case"glob":return"Search(failed)";case"listdirectory":case"list_dir":return"List(failed)";case"todowrite":return"TodoWrite(failed)";case"todoread":return"TodoRead(failed)";default:return null}const n=e.result;if(!n?.returnDisplay&&!n?.metadata)return null;switch(t){case"readfile":case"read_file":{const t=n.metadata?.lineCount||0,r=n.metadata?.toolParams;let i="file";return i=r&&"string"==typeof r.absolutePath?r.absolutePath.split(/[/\\]/).pop()||"file":e.description.match(/Reading (.+)/)?.[1]||e.description.match(/(.+)/)?.[1]||"file",`Read(${i})\n ⎿ Read ${t} lines (ctrl+o to expand)`}case"readmanyfiles":{const t=n.metadata?.toolParams,r=n.metadata?.fileCount||0;let i="multiple files";return i=t&&Array.isArray(t.paths)?t.paths.length<=2?t.paths.map(e=>"string"==typeof e?e.split(/[/\\]/).pop():"").join(", "):`${t.paths.length} patterns`:e.description.match(/Reading files: (.+)/)?.[1]||"multiple files",`ReadMany(${i})\n ⎿ Read ${r} file${1!==r?"s":""} (ctrl+o to expand)`}case"grep":{const t=n.metadata?.matchCount||0,r=n.metadata?.toolParams;return`Search(pattern: "${(r&&"string"==typeof r.pattern?r.pattern:void 0)||e.description.match(/Searching for "(.+?)"/)?.[1]||"pattern"}")\n ⎿ Found ${t} match${1!==t?"es":""} (ctrl+o to expand)`}case"listdirectory":case"list_dir":{const t=n.metadata?.entryCount||0,r=n.metadata?.toolParams;let i="directory";if(r){const t=("string"==typeof r.path?r.path:void 0)||("string"==typeof r.absolutePath?r.absolutePath:void 0);i=t?t.split(/[/\\]/).pop()||"directory":e.description.match(/Listing directory (.+)/)?.[1]||"directory"}else i=e.description.match(/Listing directory (.+)/)?.[1]||"directory";return`List(${i})\n ⎿ Found ${t} item${1!==t?"s":""} (ctrl+o to expand)`}case"glob":{const t=n.metadata?.matchCount||0,r=n.metadata?.toolParams;return`Search(pattern: "${(r&&"string"==typeof r.pattern?r.pattern:void 0)||e.description.match(/Searching for files matching "(.+?)"/)?.[1]||e.description.match(/'(.+?)'/)?.[1]||"pattern"}")\n ⎿ Found ${t} file${1!==t?"s":""} (ctrl+o to expand)`}case"todowrite":{const e=n.metadata?.todoMetadata||n.metadata;if(!e)return null;const t=n.metadata?.todos||e.todos||[],r=e.totalCount||t.length||0,i=e.phase||"updating";let o="updating plan";if("creating"===i?o=`creating ${r} task${1!==r?"s":""}`:"completing"===i&&(o="completing tasks"),t.length>0){const e=5,n=t.slice(0,e),i=e=>{switch(e){case"completed":return"☒";case"in_progress":return"⏳";case"cancelled":return"✗";default:return"☐"}};let s=`TodoWrite(${o})\n ⎿ ${r} todo${1!==r?"s":""}:\n${n.map(e=>` ${i(e.status)} ${e.content}`).join("\n")}`;return t.length>e&&(s+=`\n ... and ${t.length-e} more`),s}const s=[];return e.inProgressCount&&e.inProgressCount>0&&s.push(`${e.inProgressCount} in progress`),e.pendingCount&&e.pendingCount>0&&s.push(`${e.pendingCount} pending`),e.completedCount&&e.completedCount>0&&s.push(`${e.completedCount} completed`),e.cancelledCount&&e.cancelledCount>0&&s.push(`${e.cancelledCount} cancelled`),`TodoWrite(${o})\n ⎿ ${s.length>0?s.join(", "):`${r} tasks`} (ctrl+o to expand)`}case"todoread":{const e=n.metadata?.todoMetadata||n.metadata;if(!e)return null;const t=e.totalCount||0;if(0===t)return"TodoRead(current status)\n ⎿ No todos found (ctrl+o to expand)";const r=[];return e.inProgressCount&&e.inProgressCount>0&&r.push(`${e.inProgressCount} in progress`),e.pendingCount&&e.pendingCount>0&&r.push(`${e.pendingCount} pending`),e.completedCount&&e.completedCount>0&&r.push(`${e.completedCount} completed`),e.cancelledCount&&e.cancelledCount>0&&r.push(`${e.cancelledCount} cancelled`),`TodoRead(current status)\n ⎿ ${t} todos: ${r.join(", ")} (ctrl+o to expand)`}default:return null}}(e):null;if(g&&e.status!==SM.Confirming){const n=g.split("\n"),r=n[0],i=n.slice(1),o=e.status===SM.Error;return We.jsxs(ki,{flexDirection:"column",paddingX:1,children:[We.jsxs(ki,{minHeight:1,alignItems:"center",children:[We.jsx(xi,{color:o?"red":"white",children:"● "}),We.jsx(xi,{color:c,bold:"low"!==t,children:r})]}),i.map((e,t)=>We.jsx(ki,{marginLeft:0,children:We.jsx(xi,{color:"gray",children:e})},t))]})}return We.jsxs(ki,{flexDirection:"column",paddingX:1,children:[We.jsxs(ki,{minHeight:1,alignItems:"center",children:[We.jsx(xi,{color:c,bold:"low"!==t,strikethrough:e.status===SM.Cancelled,children:e.displayName}),We.jsx(ki,{marginLeft:1,children:We.jsx(xi,{color:"gray",children:e.description})}),d&&We.jsx(ki,{marginLeft:1,children:We.jsx(xi,{color:"white",children:"←"})})]}),o&&(e.result||u)&&e.status!==SM.Confirming&&We.jsxs(ki,{marginTop:1,marginLeft:3,flexDirection:"column",children:[e.status===SM.Executing&&u?.output&&We.jsx(ZM,{maxHeight:n?n-3:15,maxWidth:r?r-6:void 0,overflowDirection:"top",children:u.output.split("\n").map((e,t)=>We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:e})},t))}),e.result&&e.status!==SM.Executing&&We.jsxs(We.Fragment,{children:[f&&h&&We.jsx(P$,{todos:h.todos,metadata:h.metadata,maxHeight:n?n-3:void 0,maxWidth:r?r-6:void 0,compact:"low"===t}),!f&&e.result.diffData&&We.jsx(C$,{fileName:e.result.diffData.fileName,diffContent:e.result.diffData.content,maxHeight:n?n-3:void 0,maxWidth:r?r-6:void 0,terminalWidth:i??80}),!f&&!e.result.diffData&&e.result.returnDisplay&&We.jsx(ZM,{maxHeight:n?n-3:15,maxWidth:r?r-6:void 0,overflowDirection:"top",children:e.result.returnDisplay.split("\n").map((e,t)=>We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:e})},t))}),!f&&e.result.summary&&e.status===SM.Success&&"Tool completed successfully"!==e.result.summary&&!e.result.returnDisplay&&e.result.summary.length>10&&We.jsx(ki,{marginTop:1,children:We.jsx(xi,{color:"gray",children:e.result.summary})})]})]}),e.status===SM.Error&&!e.result?.returnDisplay&&!g&&We.jsx(ki,{marginTop:1,marginLeft:3,children:We.jsx(xi,{color:"red",children:"✖ Tool execution failed"})}),e.status===SM.Cancelled&&We.jsx(ki,{marginTop:1,marginLeft:3,children:We.jsx(xi,{color:"yellow",children:"− Operation cancelled"})})]})}function U$({items:e,initialIndex:t=0,onSelect:n,onHighlight:r,isFocused:i,showScrollArrows:o=!1,maxItemsToShow:s=10,showNumbers:a=!0}){const[l,u]=qe.useState(t),[c,d]=qe.useState(0),[p,f]=qe.useState(""),h=qe.useRef(null);qe.useEffect(()=>{u(t)},[t]),qe.useEffect(()=>{const t=Math.max(0,Math.min(l-s+1,e.length-s));l<c?d(l):l>=c+s&&d(t)},[l,e.length,c,s]),qe.useEffect(()=>()=>{h.current&&clearTimeout(h.current)},[]),Gi((t,i)=>{const o=a&&/^[0-9]$/.test(t);if(!o&&h.current&&(clearTimeout(h.current),f("")),"k"===t||i.upArrow){const t=l>0?l-1:e.length-1;return u(t),void r?.(e[t].value)}if("j"===t||i.downArrow){const t=l<e.length-1?l+1:0;return u(t),void r?.(e[t].value)}if(i.return)l>=0&&l<e.length&&n(e[l].value);else if(o){h.current&&clearTimeout(h.current);const i=p+t;f(i);const o=Number.parseInt(i,10)-1;if("0"===i)return void(h.current=setTimeout(()=>f(""),350));if(o>=0&&o<e.length){const t=e[o];u(o),r?.(t.value);Number.parseInt(i+"0",10)>e.length?(n(t.value),f("")):h.current=setTimeout(()=>{n(t.value),f("")},350)}else f("")}},{isActive:i&&e.length>0});const g=e.slice(c,c+s);return We.jsxs(ki,{flexDirection:"column",children:[o&&We.jsx(xi,{color:c>0?xM:QM,children:"▲"}),g.map((t,n)=>{const r=c+n,i=l===r;let o=xM,s=xM;i?(o=NM,s=NM):t.disabled&&(o=QM,s=QM),a||(s=QM);const u=String(e.length).length,d=`${String(r+1).padStart(u)}.`;return We.jsxs(ki,{alignItems:"center",children:[We.jsx(ki,{minWidth:2,flexShrink:0,children:We.jsx(xi,{color:i?NM:xM,children:i?"●":" "})}),We.jsx(ki,{marginRight:1,flexShrink:0,minWidth:d.length,children:We.jsx(xi,{color:s,children:d})}),t.themeNameDisplay&&t.themeTypeDisplay?We.jsxs(xi,{color:o,wrap:"truncate",children:[t.themeNameDisplay," ",We.jsx(xi,{color:QM,children:t.themeTypeDisplay})]}):We.jsx(xi,{color:o,wrap:"truncate",children:t.label})]},t.label)}),o&&We.jsx(xi,{color:c+s<e.length?xM:QM,children:"▼"})]})}const z$=qe.createContext(null);function G$({children:e}){const t=qe.useRef(null);return We.jsx(z$.Provider,{value:t,children:e})}function H$({confirmationDetails:e,onConfirm:t,isFocused:n=!0,availableTerminalHeight:r,terminalWidth:i}){const o=oO(i).getDialogContentWidth(),[s,a]=Je.useState(0),l=function(){const e=qe.useContext(z$);return e?e.current:null}(),u=[];if("edit"===e.type)u.push({label:"Yes, allow once",value:kM.ProceedOnce},{label:"Yes, allow always",value:kM.ProceedAlways},{label:"No (esc)",value:kM.Cancel});else if("exec"===e.type){const t=e;u.push({label:"Yes, allow once",value:kM.ProceedOnce},{label:`Yes, always allow "${t.rootCommand} ..."`,value:kM.ProceedAlwaysCommand},{label:"No (esc)",value:kM.Cancel})}else u.push({label:"Yes, allow once",value:kM.ProceedOnce},{label:"Yes, allow always",value:kM.ProceedAlways},{label:"No (esc)",value:kM.Cancel});Gi((e,r)=>{if(n)if(r.escape)t(kM.Cancel);else{if(r.upArrow||"k"===e)return s>0?void a(s-1):void(l&&l.scrollUp());if(r.downArrow||"j"===e)return s<u.length-1?void a(s+1):void(l&&l.scrollDown());if(r.return)t(u[s].value);else if(/^[1-9]$/.test(e)){const n=Number.parseInt(e,10)-1;if(n>=0&&n<u.length)return void t(u[n].value)}}});let c,d=null;if("edit"===e.type){const t=e;c="Apply this change?",d=We.jsx(C$,{fileName:t.fileName,diffContent:t.fileDiff,maxHeight:function(){if(0===u.length)throw new Error("Options not provided for confirmation message");if(void 0===r)return;const e=5+u.length;return Math.max(r-e,1)}(),maxWidth:o,terminalWidth:i})}else if("exec"===e.type){const t=e;c="Allow execution?",d=We.jsxs(ki,{flexDirection:"column",paddingX:1,children:[We.jsx(xi,{color:MM,children:t.command}),t.workingDirectory&&We.jsxs(xi,{color:QM,children:["Working directory: ",t.workingDirectory]})]})}else{const t=e;c="Do you want to proceed?",d=We.jsxs(ki,{flexDirection:"column",paddingX:1,children:[We.jsx(xi,{color:MM,children:t.prompt||e.description}),t.urls&&t.urls.length>0&&We.jsxs(ki,{flexDirection:"column",marginTop:1,children:[We.jsx(xi,{children:"URLs to fetch:"}),t.urls.map((e,t)=>We.jsxs(xi,{color:FM,children:[" ","- ",e]},t))]})]})}return We.jsxs(ki,{flexDirection:"column",padding:1,width:o,children:[We.jsx(ki,{flexGrow:1,flexShrink:1,overflow:"hidden",marginBottom:1,children:d}),We.jsx(ki,{marginBottom:1,flexShrink:0,children:We.jsx(xi,{wrap:"truncate",children:c})}),We.jsx(ki,{flexShrink:0,children:We.jsx(U$,{items:u,initialIndex:s,onSelect:e=>t(e),onHighlight:e=>{const t=u.findIndex(t=>t.value===e);-1!==t&&a(t)},isFocused:!1})})]})}function W$(e,t){if(void 0===t)return;let n=0;for(const i of e.tools)(i.result?.returnDisplay||i.result?.diffData)&&n++;const r=e.tools.length-n;return Math.max(3,Math.floor((t-2-r)/Math.max(1,n)))}function q$({toolGroup:e,onConfirm:t,isFocused:n=!0,maxHeight:r,maxWidth:i,terminalWidth:o}){const[s,a]=qe.useState(new Set),l=qe.useMemo(()=>i??(e=>e<100?Math.floor(.9*e):e<160?Math.min(140,Math.floor(.88*e)):Math.min(200,Math.floor(.85*e)))(o),[i,o]),u=oO(o);qe.useMemo(()=>u.getConstrainedContentWidth(4),[u]);const c=e.tools.some(e=>e.status===SM.Executing||e.status===SM.Confirming||e.status===SM.Pending),d=e.tools.some(e=>"shell"===e.name||e.name.includes("shell")),p=c||d?RM:"error"===e.status?TM:"completed"===e.status?QM:FM,f=e.tools.find(e=>e.status===SM.Confirming),h=W$(e,r),g=e.tools.some(e=>{const t=(e.name||"").toLowerCase();return["readfile","read_file","readmanyfiles","grep","listdirectory","list_dir","glob","todowrite","todoread"].includes(t)}),A=("completed"===e.status||"error"===e.status)&&g&&!e.tools.some(e=>e.status===SM.Confirming);return We.jsx(ki,{flexDirection:"column",borderStyle:A?void 0:"round",borderColor:A?void 0:p,width:l,marginLeft:A?0:1,height:r,children:e.tools.map(e=>{const r=f?.id===e.id,i=r?"high":f?"low":"medium",u=s.has(e.id);return We.jsxs(ki,{flexDirection:"column",children:[We.jsx(j$,{tool:e,emphasis:i,maxHeight:h,maxWidth:l-4,terminalWidth:o,compact:A,isExpanded:u,onToggleExpand:()=>{return t=e.id,void a(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n});var t}}),e.status===SM.Confirming&&r&&e.confirmationDetails&&t&&We.jsx(H$,{confirmationDetails:e.confirmationDetails,onConfirm:n=>t(e.id,n),isFocused:n,availableTerminalHeight:h,terminalWidth:o})]},e.id)})})}const J$=E$(g$),K$={"hljs-keyword":"magenta","hljs-string":"green","hljs-number":"cyan","hljs-comment":"gray","hljs-function":"yellow","hljs-variable":"blue","hljs-type":"cyan","hljs-built_in":"magenta","hljs-literal":"cyan","hljs-title":"yellow","hljs-attr":"blue","hljs-attribute":"blue","hljs-name":"red","hljs-tag":"red","hljs-selector-tag":"red","hljs-selector-class":"blue","hljs-selector-id":"yellow"};function Z$(e,t){if("text"===e.type)return We.jsx(xi,{color:t,children:e.value});if("element"===e.type){const n=e.properties?.className||[];let r;for(let e=n.length-1;e>=0;e--){const t=K$[n[e]];if(t){r=t;break}}const i=r||t,o=e.children?.map((e,t)=>We.jsx(Je.Fragment,{children:Z$(e,i)},t));return We.jsx(Je.Fragment,{children:o})}return"root"===e.type&&e.children&&0!==e.children.length?e.children?.map((e,n)=>We.jsx(Je.Fragment,{children:Z$(e,t)},n)):null}const V$=(e,t,n,r)=>{const i=e.replace(/\n$/,"");try{let e=i.split("\n");const r=String(e.length).length;let o=0;if(void 0!==n){const t=Math.max(n,2);if(e.length>t){const n=e.length-t;o=n,e=e.slice(n)}}const s=e=>t&&J$.registered(t)?J$.highlight(t,e):J$.highlightAuto(e);return We.jsxs(ki,{flexDirection:"column",children:[o>0&&We.jsxs(xi,{color:"gray",children:["... first ",o," lines hidden ..."]}),e.map((e,t)=>{const n=Z$(s(e),void 0),i=null!==n?n:e;return We.jsxs(ki,{children:[We.jsx(xi,{color:"gray",children:`${String(t+1+o).padStart(r," ")} `}),We.jsx(xi,{wrap:"wrap",children:i})]},t)})]})}catch(qK){ex.error(`[colorizeCode] Error highlighting code for language "${t}":`,qK);const n=i.split("\n"),r=String(n.length).length;return We.jsx(ki,{flexDirection:"column",children:n.map((e,t)=>We.jsxs(ki,{children:[We.jsx(xi,{color:"gray",children:`${String(t+1).padStart(r," ")} `}),We.jsx(xi,{children:e})]},t))})}},Y$=Je.memo(({text:e})=>{const t=[];let n=0;const r=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>)/g;let i;for(;null!==(i=r.exec(e));){i.index>n&&t.push(We.jsx(xi,{children:e.slice(n,i.index)},`t-${n}`));const s=i[0];let a=null;const l=`m-${i.index}`;try{if(s.startsWith("**")&&s.endsWith("**")&&s.length>4)a=We.jsx(xi,{bold:!0,children:s.slice(2,-2)},l);else if(!(s.length>2&&(s.startsWith("*")&&s.endsWith("*")||s.startsWith("_")&&s.endsWith("_")))||/\w/.test(e.substring(i.index-1,i.index))||/\w/.test(e.substring(r.lastIndex,r.lastIndex+1))||/\S[./\\]/.test(e.substring(i.index-2,i.index))||/[./\\]\S/.test(e.substring(r.lastIndex,r.lastIndex+2)))if(s.startsWith("~~")&&s.endsWith("~~")&&s.length>4)a=We.jsx(xi,{strikethrough:!0,children:s.slice(2,-2)},l);else if(s.startsWith("`")&&s.endsWith("`")&&s.length>1){const e=s.match(/^(`+)(.+?)\1$/s);e&&e[2]&&(a=We.jsx(xi,{color:"blue",children:e[2]},l))}else if(s.startsWith("[")&&s.includes("](")&&s.endsWith(")")){const e=s.match(/\[(.*?)\]\((.*?)\)/);if(e){const t=e[1],n=e[2];a=We.jsxs(xi,{children:[t,We.jsxs(xi,{color:"blue",children:[" (",n,")"]})]},l)}}else s.startsWith("<u>")&&s.endsWith("</u>")&&s.length>6&&(a=We.jsx(xi,{underline:!0,children:s.slice(3,-4)},l));else a=We.jsx(xi,{italic:!0,children:s.slice(1,-1)},l)}catch(o){ex.error("Error parsing inline markdown part:",s,o),a=null}t.push(a??We.jsx(xi,{children:s},l)),n=r.lastIndex}return n<e.length&&t.push(We.jsx(xi,{children:e.slice(n)},`t-${n}`)),We.jsx(We.Fragment,{children:t.filter(e=>null!==e)})}),X$=e=>HM(e.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/`(.*?)`/g,"$1").replace(/<u>(.*?)<\/u>/g,"$1").replace(/\[(.*?)\]\(.*?\)/g,"$1")),eL=({headers:e,rows:t,terminalWidth:n})=>{const r=Math.max(n-4,20),i=e.map((e,n)=>{const r=X$(e),i=Math.max(...t.map(e=>X$(e[n]||"")));return Math.max(r,i)+4}),o=i.reduce((e,t)=>e+t+1,1),s=o>r?r/o:1,a=i.map(e=>Math.floor(e*s)),l=e=>{const t={top:{left:"┌",middle:"┬",right:"┐",horizontal:"─"},middle:{left:"├",middle:"┼",right:"┤",horizontal:"─"},bottom:{left:"└",middle:"┴",right:"┘",horizontal:"─"}}[e],n=a.map(e=>t.horizontal.repeat(Math.max(1,e))),r=t.left+n.join(t.middle)+t.right;return We.jsx(xi,{color:"cyan",children:r})},u=(e,t=!1)=>{const n=e.map((e,n)=>((e,t,n=!1)=>{const r=Math.max(0,t);let i=e;if(X$(e)>r)if(r<=3)i=e.substring(0,Math.min(e.length,r));else{let t=0,n=e.length,o=e;for(;t<=n;){const i=Math.floor((t+n)/2),s=e.substring(0,i);X$(s)<=r-3?(o=s,t=i+1):n=i-1}i=o+"..."}return We.jsx(ki,{minWidth:t,paddingX:1,children:n?We.jsx(xi,{bold:!0,color:"cyan",children:i}):We.jsx(xi,{children:i})})})(e||"",a[n]||0,t));return We.jsxs(ki,{flexDirection:"row",children:[We.jsx(xi,{color:"cyan",children:"│"}),n.map((e,t)=>We.jsxs(Je.Fragment,{children:[e,We.jsx(xi,{color:"cyan",children:"│"})]},t))]})};return We.jsxs(ki,{flexDirection:"column",marginY:1,children:[l("top"),u(e,!0),l("middle"),t.map((e,t)=>We.jsx(Je.Fragment,{children:u(e)},t)),l("bottom")]})},tL=Je.memo(({content:e,lang:t,isPending:n,availableTerminalHeight:r,terminalWidth:i})=>{if(n&&void 0!==r){const n=Math.max(0,r-2);if(e.length>n){if(n<1)return We.jsx(ki,{paddingLeft:1,children:We.jsx(xi,{color:"gray",children:"... code is being written ..."})});const o=e.slice(0,n),s=V$(o.join("\n"),t,r,i-1);return We.jsxs(ki,{paddingLeft:1,flexDirection:"column",children:[s,We.jsx(xi,{color:"gray",children:"... generating more ..."})]})}}const o=e.join("\n"),s=V$(o,t,r,i-1);return We.jsx(ki,{paddingLeft:1,flexDirection:"column",width:i,flexShrink:0,children:s})}),nL=Je.memo(({itemText:e,type:t,marker:n,leadingWhitespace:r=""})=>{const i="ol"===t?`${n}. `:`${n} `,o=i.length,s=r.length;return We.jsxs(ki,{paddingLeft:s+1,flexDirection:"row",children:[We.jsx(ki,{width:o,children:We.jsx(xi,{children:i})}),We.jsx(ki,{flexGrow:1,children:We.jsx(xi,{wrap:"wrap",children:We.jsx(Y$,{text:e})})})]})}),rL=Je.memo(({headers:e,rows:t,terminalWidth:n})=>We.jsx(eL,{headers:e,rows:t,terminalWidth:n})),iL=Je.memo(({text:e,isPending:t,terminalWidth:n,availableTerminalHeight:r})=>{if(!e)return We.jsx(We.Fragment,{});const i=e.split("\n"),o=/^ *(#{1,4}) +(.*)/,s=/^ *(`{3,}|~{3,}) *(\w*?) *$/,a=/^([ \t]*)([-*+]) +(.*)/,l=/^([ \t]*)(\d+)\. +(.*)/,u=/^ *([-*_] *){3,} *$/,c=/^\s*\|(.+)\|\s*$/,d=/^\s*\|?\s*(:?-+:?)\s*(\|\s*(:?-+:?)\s*)+\|?\s*$/,p=[];let f=!1,h=!0,g=[],A=null,m="",y=!1,b=[],v=[];function E(e){e&&(p.push(e),h=!1)}return i.forEach((e,I)=>{const w=`line-${I}`;if(f){const i=e.match(s),o=i?.[1];return void(o&&m&&m[0]&&o.startsWith(m[0])&&o.length>=m.length?(E(We.jsx(tL,{content:g,lang:A,isPending:t,availableTerminalHeight:r,terminalWidth:n},w)),f=!1,g=[],A=null,m=""):g.push(e))}const C=e.match(s),_=e.match(o),B=e.match(a),D=e.match(l),S=e.match(u),k=e.match(c),x=e.match(d);if(C)f=!0,m=C[1]||"```",A=(C[2]&&C[2].length>0?C[2]:null)||null;else if(k&&!y){const t=I+1<i.length?i[I+1]:void 0;t&&d.test(t)?(y=!0,v=k[1]?k[1].split("|").map(e=>e.trim()):[],b=[]):E(We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:We.jsx(Y$,{text:e})})},w))}else if(y&&x);else if(y&&k){const e=k[1]?k[1].split("|").map(e=>e.trim()):[];for(;e.length<v.length;)e.push("");e.length>v.length&&(e.length=v.length),b.push(e)}else if(y&&!k)v.length>0&&b.length>0&&E(We.jsx(rL,{headers:v,rows:b,terminalWidth:n},`table-${p.length}`)),y=!1,b=[],v=[],e.trim().length>0&&E(We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:We.jsx(Y$,{text:e})})},w));else if(S)E(We.jsx(ki,{children:We.jsx(xi,{color:"gray",children:"---"})},w));else if(_){const e=_[1]?.length??0,t=_[2]??"";let n=null;switch(e){case 1:n=We.jsx(xi,{bold:!0,color:"cyan",children:We.jsx(Y$,{text:t})});break;case 2:n=We.jsx(xi,{bold:!0,color:"blue",children:We.jsx(Y$,{text:t})});break;case 3:n=We.jsx(xi,{bold:!0,children:We.jsx(Y$,{text:t})});break;case 4:n=We.jsx(xi,{italic:!0,color:"gray",children:We.jsx(Y$,{text:t})});break;default:n=We.jsx(xi,{children:We.jsx(Y$,{text:t})})}n&&E(We.jsx(ki,{children:n},w))}else if(B){const e=B[1]??"",t=B[2]??"-",n=B[3]??"";E(We.jsx(nL,{itemText:n,type:"ul",marker:t,leadingWhitespace:e},w))}else if(D){const e=D[1]??"",t=D[2]??"1",n=D[3]??"";E(We.jsx(nL,{itemText:n,type:"ol",marker:t,leadingWhitespace:e},w))}else 0!==e.trim().length||f?E(We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:We.jsx(Y$,{text:e})})},w)):h||(p.push(We.jsx(ki,{height:1},`spacer-${I}`)),h=!0)}),f&&E(We.jsx(tL,{content:g,lang:A,isPending:t,availableTerminalHeight:r,terminalWidth:n},"line-eof")),y&&v.length>0&&b.length>0&&E(We.jsx(rL,{headers:v,rows:b,terminalWidth:n},`table-${p.length}`)),We.jsx(We.Fragment,{children:p})});function oL(){const[e,t]=qe.useState({columns:(process.stdout.columns||60)-0,rows:process.stdout.rows||20}),n=qe.useRef(null);return qe.useEffect(()=>{function e(){n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{t({columns:(process.stdout.columns||60)-0,rows:process.stdout.rows||20}),n.current=null},250)}return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e),n.current&&clearTimeout(n.current)}},[]),e}const sL=/@((?:".+?[^\\]")|(?:[^\s])+)/gi;const aL=(e,t)=>{try{if("role"in e&&"tool-group"===e.role){const n=e.toolGroup;let r=2;const i=function(e){return e??50}(W$(n,void 0));for(const e of n.tools){let n=1;if((e.result||e.status===SM.Executing)&&(n+=1),e.result?.returnDisplay&&"string"==typeof e.result.returnDisplay){const t=e.result.returnDisplay.split("\n").length,r=t>i,o=Math.min(t,i);n+=o+(r?1:0)}if(e.result?.diffData?.content&&"string"==typeof e.result.diffData.content){const t=e.result.diffData.content.split("\n").length,r=t>i,o=Math.min(t,i);n+=o+(r?1:0)}if(e.status===SM.Executing){const t=DM.getState().streams.get(e.toolCallId);if(t?.output){const e=t.output.split("\n").length,r=e>i,o=Math.min(e,i);n+=o+(r?1:0)}else n+=i}if(e.status===SM.Confirming&&e.confirmationDetails){const r=2+1+1+3;let o=0;if("edit"===e.confirmationDetails.type){const t=e.confirmationDetails.fileDiff,n=t?t.split("\n").length:20;o=Math.min(n,i)}else if("exec"===e.confirmationDetails.type){const n=e.confirmationDetails,r=n.command||"",i=Math.max(40,t-20),s=Math.max(1,Math.ceil(r.length/i)),a=n.workingDirectory?1:0;o=1+s+a}else o=5;n+=r+o+1}r+=n}return r}}catch(qK){return ex.error("CRITICAL: Failed to estimate tool group height",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0}),20}const n=e;if(n.hidden)return 0;const r=(e=>{if(!("role"in e))return"";const t=e;return"string"==typeof t.content?t.content:Array.isArray(t.content)?t.content.map(e=>"text"===e.type?e.text:"").join("\n"):""})(n);if(!r||0===r.length)return 1;const i=r.split("\n");let o,s=0;o="user"===n.role?Math.max(40,t-3):"assistant"===n.role?Math.max(40,t-8):Math.max(40,t-3);for(const a of i){if(""===a.trim()){s+=1;continue}const e=HM(a.replace(/\*\*\*(.*?)\*\*\*/g,"$1").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"));s+=Math.max(1,Math.ceil(e/o))}return"user"===n.role||n.role,s+1},lL=(e,t)=>"id"in e&&e.id?`${e.id}-${t}`:"timestamp"in e&&e.timestamp?`msg-${e.timestamp}-${t}`:`message-${t}`,uL=(e,t,n)=>{const r=new Array(e.length+1).fill(0);for(let i=0;i<e.length;i++){const o=e[i];if(!o)continue;const s=lL(o,i);let a=t.get(s);void 0===a&&(a=aL(o,n),t.set(s,a)),r[i+1]=r[i]+a}return r},cL=(e,t)=>{if(0===e.length)return 0;if(t<=0)return 0;let n=0,r=e.length-1;for(;n<r;){const i=Math.floor((n+r+1)/2),o=e[i];void 0!==o&&o<=t?n=i:r=i-1}return Math.max(0,n-1)};let dL=!1,pL=!1,fL=null,hL="",gL=null;function AL(e){pL&&(hL+=e.toString(),function(){const e=/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g;let t;for(;null!==(t=e.exec(hL));){const e=Number.parseInt(t[1],10);64===e&&gL?.onScrollUp?gL.onScrollUp():65===e&&gL?.onScrollDown&&gL.onScrollDown()}const n=hL.lastIndexOf("[<");if(-1!==n){const t=hL.slice(n);hL=e.test(t)?"":t}else hL="";hL.length>100&&(hL="")}())}function mL(e,t){return"Apple_Terminal"!==process.env.TERM_PROGRAM?null:(gL={onScrollUp:e,onScrollDown:t},dL||(process.stdin.isTTY&&process.stdin.setRawMode(!0),fL=e=>{AL(e)},process.stdin.prependListener("data",fL),dL=!0,setTimeout(()=>{pL||(process.stdout.write("[?1006h[?1000h[?1007h"),pL=!0)},100)),()=>{gL=null,dL&&!gL&&(pL&&(process.stdout.write("[?1007l[?1000l[?1006l"),pL=!1,hL=""),fL&&(process.stdin.removeListener("data",fL),fL=null),dL=!1)})}const yL=(e,t)=>{switch(t.type){case"SET_INNER_HEIGHT":return{...e,innerHeight:t.innerHeight};case"SET_HEIGHT":return{...e,height:t.height};case"SCROLL_DOWN":{const t=Math.max(0,e.innerHeight-e.height),n=Math.max(3,Math.floor(.15*e.height));return{...e,scrollTop:Math.min(t,e.scrollTop+n)}}case"SCROLL_UP":{const t=Math.max(3,Math.floor(.15*e.height));return{...e,scrollTop:Math.max(0,e.scrollTop-t)}}case"SCROLL_TO_BOTTOM":return{...e,scrollTop:Math.max(0,e.innerHeight-e.height)};case"SCROLL_TO_TOP":return{...e,scrollTop:0};case"PAGE_DOWN":{const t=Math.max(0,e.innerHeight-e.height),n=Math.max(1,Math.floor(.9*e.height));return{...e,scrollTop:Math.min(t,e.scrollTop+n)}}case"PAGE_UP":{const t=Math.max(1,Math.floor(.9*e.height));return{...e,scrollTop:Math.max(0,e.scrollTop-t)}}default:return e}},bL=qe.forwardRef(({messages:e=[],children:t,focused:n=!0,onToolConfirm:r,disableArrowKeyScrolling:i=!1},o)=>{const[s,a]=qe.useReducer(yL,{height:0,scrollTop:0,innerHeight:0}),[l,u]=qe.useState(null),c=qe.useRef(null),d=qe.useRef(null),p=qe.useRef(e.length),f=qe.useRef(0),h=qe.useContext(z$);qe.useEffect(()=>(h&&(h.current={scrollUp:()=>a({type:"SCROLL_UP"}),scrollDown:()=>a({type:"SCROLL_DOWN"})}),()=>{h&&(h.current=null)}),[h]);const g=qe.useRef({cols:0,rows:0,lastMeasureTime:0}),[A,m]=function(){const{stdout:e}=Wi(),[t,n]=qe.useState([e.columns,e.rows]);return qe.useEffect(()=>{const t=()=>n([e.columns,e.rows]);return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}();qe.useImperativeHandle(o,()=>({scrollToBottom:()=>{a({type:"SCROLL_TO_BOTTOM"})}}),[]),qe.useEffect(()=>{u(null!==NT())},[]);const{selectedModel:y}=VF(),b=Math.max(0,s.innerHeight-s.height),v=s.scrollTop>=b-2,E=e.length>0,{isResponding:I}=BM(),{firebaseUser:w}=FT(),C=y?aM(cM(y.name))||uM(y.provider):null,_=qe.useRef(new Map),B=qe.useRef(new Map),D=qe.useRef(new Map),S=qe.useRef(0),k=qe.useRef(0),x=DM(e=>e.totalLineCount),Q=qe.useMemo(()=>{const t=new Map;let n=0;const r=D.current,i=e.length-1;e.forEach((e,o)=>{const s=lL(e,o),a=o===i&&I;let l=r.get(s);if(void 0===l||a)if(a){const t=Date.now();t-S.current>=1e3||0===S.current?(l=yM(e),S.current=t,k.current=l):l=k.current||yM(e)}else l=yM(e),r.set(s,l);n+=l;const u=C?dM(n,C):0;t.set(o,{tokens:n,percentage:u})});const o=new Set(e.map((e,t)=>lL(e,t)));for(const e of r.keys())o.has(e)||r.delete(e);return I||0===S.current||(S.current=0,k.current=0),t},[e,C,I]),N=qe.useMemo(()=>{const t=_.current,n=e.length-1;if(I&&n>=0){const r=e[n];if(r){const e=lL(r,n);t.delete(e)}}for(let r=0;r<e.length;r++){const n=e[r];if(n&&("role"in n&&"tool-group"===n.role)){const e=n,i=lL(n,r);let o=!1;e.toolGroup?.tools?.forEach(e=>{const t=B.current.get(e.toolCallId);void 0!==t&&t!==e.status&&(o=!0),B.current.set(e.toolCallId,e.status)});const s=e.toolGroup?.tools?.some(e=>"executing"===e.status||"confirming"===e.status);(o||s)&&t.delete(i)}}return uL(e,_.current,A)},[e,A,I]),T=qe.useMemo(()=>((e,t,n,r,i,o=15,s)=>{try{if(0===e.length)return{startIndex:0,endIndex:0,topSpacerHeight:0,visibleStartIndex:0,visibleEndIndex:0};const a=s||uL(e,r,i),l=cL(a,t),u=cL(a,t+n),c=Math.max(0,l-o),d=Math.min(e.length-1,u+o);return{startIndex:c,endIndex:d,topSpacerHeight:a[c]??0,visibleStartIndex:l,visibleEndIndex:u}}catch(qK){return ex.error("Failed to calculate virtual window",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0,messageCount:e.length,scrollTop:t,viewportHeight:n}),{startIndex:0,endIndex:Math.max(0,e.length-1),topSpacerHeight:0,visibleStartIndex:0,visibleEndIndex:Math.max(0,e.length-1)}}})(e,s.scrollTop,s.height,_.current,A,15,N),[e,s.scrollTop,s.height,A,N]),R=qe.useMemo(()=>T.endIndex>=e.length-1?0:((e,t,n,r,i)=>{if(t>=e.length)return 0;const o=i||uL(e,n,r);return(o[e.length]??0)-(o[t]??0)})(e,T.endIndex+1,_.current,A,N),[e,T.endIndex,A,N]),F=qe.useCallback(()=>{if(c.current){const e=Ki(c.current);a({type:"SET_HEIGHT",height:e.height-2})}if(d.current){const e=Ki(d.current);a({type:"SET_INNER_HEIGHT",innerHeight:e.height})}},[]);return qe.useEffect(()=>{const e=Date.now(),t=g.current;(t.cols!==A||t.rows!==m)&&e-t.lastMeasureTime>16&&(F(),g.current={cols:A,rows:m,lastMeasureTime:e})},[A,m,F]),qe.useEffect(()=>{e.length>0&&0===p.current&&setTimeout(()=>{F()},50)},[e.length,F]),qe.useEffect(()=>{const t=Date.now(),n=t-f.current;if(!(I&&n<100)&&d.current){const n=Ki(d.current);f.current=t,a({type:"SET_INNER_HEIGHT",innerHeight:n.height});const r=e.length>p.current,i=n.height>s.innerHeight;(r||i)&&v&&setTimeout(()=>{a({type:"SCROLL_TO_BOTTOM"})},0),p.current=e.length}},[e,s.innerHeight,I,x,v]),qe.useEffect(()=>{const t=mL(()=>{e.length>0&&a({type:"SCROLL_UP"})},()=>{e.length>0&&a({type:"SCROLL_DOWN"})});return()=>{t?.()}},[e.length]),Gi((t,r)=>{if(n&&!(e.length<1))return i?r.ctrl&&"g"===t?void a({type:"SCROLL_TO_TOP"}):r.ctrl&&"G"===t?void a({type:"SCROLL_TO_BOTTOM"}):void 0:void(!r.downArrow||r.ctrl||r.shift?!r.upArrow||r.ctrl||r.shift?r.downArrow&&r.ctrl?a({type:"PAGE_DOWN"}):r.upArrow&&r.ctrl?a({type:"PAGE_UP"}):(r.pageDown&&a({type:"PAGE_DOWN"}),r.pageUp&&a({type:"PAGE_UP"}),r.ctrl&&"g"===t?a({type:"SCROLL_TO_TOP"}):r.ctrl&&"G"===t&&a({type:"SCROLL_TO_BOTTOM"})):a({type:"SCROLL_UP"}):a({type:"SCROLL_DOWN"}))}),We.jsxs(ki,{ref:c,height:"100%",flexDirection:"column",flexGrow:1,overflow:"hidden",children:[!E&&We.jsxs(ki,{flexGrow:1,justifyContent:"center",alignItems:"center",flexDirection:"column",children:[We.jsxs(xi,{color:"gray",children:["Welcome, ",w?.displayName,"!"]}),l?We.jsx(xi,{color:"gray",children:"Currently using project's EMBEDDER.md"}):We.jsx(xi,{color:"gray",children:"Type /init to create an EMBEDDER.md"})]}),E&&We.jsxs(ki,{ref:d,flexShrink:0,flexDirection:"column",marginTop:-s.scrollTop,minHeight:0,children:[T.topSpacerHeight>0&&We.jsx(ki,{height:T.topSpacerHeight,flexShrink:0}),e.slice(T.startIndex,T.endIndex+1).map((t,i)=>{const o=T.startIndex+i,s=o===e.length-1&&I,a=Q.get(o);return We.jsx(vL,{message:t,index:o,onToolConfirm:r,isFocused:n,isStreaming:s,contextInfo:a},lL(t,o))}),R>0&&We.jsx(ki,{height:R,flexShrink:0}),t]})]})});bL.displayName="ChatContainerComponent";const vL=qe.memo(function({message:e,index:t,onToolConfirm:n,isFocused:r=!0,isStreaming:i=!1,contextInfo:o}){const{columns:s}=oL();if("role"in e&&"tool-group"===e.role){const t=e;return We.jsx(ki,{marginBottom:1,flexDirection:"column",flexShrink:0,paddingLeft:2,paddingRight:1,children:We.jsx(q$,{toolGroup:t.toolGroup,onConfirm:n,isFocused:r,terminalWidth:s})})}const a=e;if(a.hidden)return null;const l="user"===a.role;a.role;const u="assistant"===a.role,{backendUser:c,firebaseUser:d}=FT(),{modeConfig:p}=JF();a.timestamp??Date.now(),a.mode;const f=qe.useMemo(()=>(e,t=!1)=>{if(t)return[We.jsx(xi,{children:e},0)];const n=[];let r=0,i=0;const o=[];[{regex:/`([^`\n]+)`/g,type:"code"},{regex:/\*\*\*([^\*\n]+?)\*\*\*/g,type:"bold-italic"},{regex:/___([^_\n]+?)___/g,type:"bold-italic"},{regex:/\*\*([^\*\n]+?)\*\*/g,type:"bold"},{regex:/__([^_\n]+?)__/g,type:"bold"},{regex:/\*([^\*\n]+?)\*/g,type:"italic"},{regex:/_([^_\n]+?)_/g,type:"italic"},{regex:/~~([^~\n]+?)~~/g,type:"strikethrough"},{regex:/\[([^\]]+)\]\(([^)]+)\)/g,type:"link"},{regex:/(?:^|(?<=\s))(https?:\/\/[^\s\n]+)/g,type:"autolink"},{regex:sL,type:"file-reference"}].forEach(t=>{const n=new RegExp(t.regex.source,t.regex.flags);let r;for(;null!==(r=n.exec(e));)o.push({start:r.index,end:r.index+r[0].length,content:r[0],type:t.type,groups:Array.from(r)})}),o.sort((e,t)=>e.start!==t.start?e.start-t.start:t.end-e.end);const s=[];for(const a of o){s.some(e=>a.start>=e.start&&a.start<e.end||a.end>e.start&&a.end<=e.end||a.start<=e.start&&a.end>=e.end)||s.push(a)}s.sort((e,t)=>e.start-t.start);for(const a of s){if(a.start>r){const t=e.slice(r,a.start);t&&n.push(We.jsx(xi,{children:t},i++))}switch(a.type){case"bold":n.push(We.jsx(xi,{bold:!0,children:a.groups[1]},i++));break;case"italic":n.push(We.jsx(xi,{italic:!0,children:a.groups[1]},i++));break;case"bold-italic":n.push(We.jsx(xi,{bold:!0,italic:!0,children:a.groups[1]},i++));break;case"strikethrough":n.push(We.jsxs(xi,{children:["~~",a.groups[1],"~~"]},i++));break;case"code":n.push(We.jsxs(xi,{backgroundColor:"gray",color:"black",children:[" ",a.groups[1]," "]},i++));break;case"link":n.push(We.jsxs(xi,{color:"blue",underline:!0,children:[a.groups[1]," (",a.groups[2],")"]},i++));break;case"autolink":n.push(We.jsx(xi,{color:"blue",underline:!0,children:a.groups[1]},i++));break;case"file-reference":n.push(We.jsx(xi,{color:"blue",children:a.groups[1]},i++));break;default:n.push(We.jsx(xi,{children:a.content},i++))}r=a.end}if(r<e.length){const t=e.slice(r);t&&n.push(We.jsx(xi,{children:t},i++))}return n.length>0?n:[We.jsx(xi,{children:e},0)]},[]),h=(e,t)=>{const n=[];let r=t,i=0;for(;r<e.length;){const t=e[r];if(null==t)break;const o=t.trim(),s=o.match(/^[*+-]\s+\[([x ])\]\s+(.+)$/),a=o.match(/^[*+-]\s+(.+)$/),l=o.match(/^(\d+)\.\s+(.+)$/);if(s){const[,e,t]=s,r="x"===(e??"").toLowerCase(),o=t??"";n.push(We.jsxs(ki,{paddingLeft:2,children:[We.jsxs(xi,{children:[r?"☑":"☐"," "]}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:f(o,!1)})]},i++))}else if(a){const[,e]=a,t=e??"";n.push(We.jsxs(ki,{paddingLeft:2,children:[We.jsx(xi,{children:"• "}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:f(t,!1)})]},i++))}else{if(!l)break;{const[,e,t]=l,r=t??"";n.push(We.jsxs(ki,{paddingLeft:2,children:[We.jsxs(xi,{children:[e,". "]}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:f(r,!1)})]},i++))}}r++}return{elements:n,nextIndex:r}},g=(e,t)=>{const n=[];let r=t;if(r+1>=e.length)return{elements:n,nextIndex:t};const i=e[r],o=e[r+1];if(null==i||null==o)return{elements:n,nextIndex:t};const s=i.trim(),a=o.trim();if(!s.includes("|")||!a.match(/^\s*\|?[\s\-:]+\|[\s\-:|]*\|?\s*$/))return{elements:n,nextIndex:t};const l=e=>e.split("|").map(e=>e.trim()).filter((e,t,n)=>!(""===e&&(0===t||t===n.length-1))),u=l(s);n.push(We.jsxs(ki,{flexDirection:"column",paddingLeft:2,paddingRight:1,children:[We.jsxs(xi,{color:"cyan",children:["┌","─".repeat(60),"┐"]}),We.jsxs(ki,{children:[We.jsx(xi,{color:"cyan",children:"│ "}),u.map((e,t)=>We.jsx(ki,{minWidth:10,paddingRight:1,children:We.jsx(xi,{bold:!0,color:"cyan",children:e})},t)),We.jsx(xi,{color:"cyan",children:" │"})]}),We.jsxs(xi,{color:"cyan",children:["├","─".repeat(60),"┤"]})]},"table-header")),r+=2;let c=0;for(;r<e.length;){const t=e[r];if(null==t)break;const i=t.trim();if(!i.includes("|"))break;const o=l(i);n.push(We.jsxs(ki,{paddingLeft:2,paddingRight:1,children:[We.jsx(xi,{color:"cyan",children:"│ "}),o.map((e,t)=>We.jsx(ki,{minWidth:10,paddingRight:1,flexDirection:"row",flexWrap:"wrap",children:f(e,!1)},t)),We.jsx(xi,{color:"cyan",children:" │"})]},"table-row-"+c++)),r++}return n.length>1&&n.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,children:We.jsxs(xi,{color:"cyan",children:["└","─".repeat(60),"┘"]})},"table-footer")),{elements:n,nextIndex:r}},A=(e,t)=>{const n=[];let r=t;const i=[];for(;r<e.length;){const t=e[r];if(null==t)break;const n=t.match(/^\s*>\s?(.*)$/);if(n){const[,e]=n;i.push(e??""),r++}else{if(!(""===t.trim()&&i.length>0))break;i.push(""),r++}}return i.length>0&&n.push(We.jsx(ki,{flexDirection:"column",paddingRight:1,borderLeft:!0,borderStyle:"single",paddingLeft:3,children:i.map((e,t)=>We.jsxs(ki,{flexDirection:"row",flexWrap:"wrap",children:[We.jsx(xi,{color:"gray",children:"▌ "}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:e?f(e,!1):[We.jsx(xi,{children:" "},0)]})]},t))},"blockquote")),{elements:n,nextIndex:r}},m=qe.useMemo(()=>{return"string"==typeof(e=a).content?e.content:Array.isArray(e.content)?e.content.map(e=>{switch(e.type){case"text":return e.text;case"tool-call":const t=e;return`[Tool Call: ${t.toolName}(${JSON.stringify(t.input)})]`;case"tool-result":{const t=e,n=t.output?.value;return n&&"object"==typeof n&&"returnDisplay"in n?String(n.returnDisplay):"[Tool Result]"}case"image":return"[Image]";case"file":const n=e;return`[File: ${n.mediaType}${n.filename?` - ${n.filename}`:""}]`;default:return"[Unknown content type]"}}).join("\n"):"";var e},[a]);if(!m||0===m.length)return null;const y=qe.useMemo(()=>()=>{if(u)return We.jsx(iL,{text:m,isPending:i,terminalWidth:s,availableTerminalHeight:void 0});const e=[],t=m.split(/(```[\s\S]*?```)/g);let n=0;return t.forEach((t,r)=>{if(t.startsWith("```")&&t.endsWith("```")){const n=t.slice(3,-3).split("\n"),i=n[0]?.trim()||"",o=i&&/^[a-zA-Z][a-zA-Z0-9+#-]*$/.test(i)&&i.length<20,s=o?i:"code",a=o?n.slice(1):n;e.push(We.jsxs(ki,{flexDirection:"column",borderStyle:"round",flexShrink:0,paddingLeft:2,paddingRight:1,paddingTop:0,paddingBottom:0,marginBottom:1,children:[We.jsx(xi,{color:"green",wrap:"wrap",children:s}),a.map((e,t)=>We.jsx(ki,{paddingLeft:2,paddingRight:1,children:We.jsx(xi,{wrap:"wrap",children:e})},t))]},`code-${r}`))}else{const r=t.split("\n");let i=0;for(;i<r.length;){const t=(r[i]??"").trim();if(""===t){i++;continue}const o=t.match(/^(#{1,6})\s+(.+)$/);if(o){const[,t,r]=o,s=(t??"#").length,a=r??"",l="█".repeat(Math.max(1,7-s));e.push(We.jsxs(ki,{paddingLeft:2,paddingRight:1,marginY:1,children:[We.jsxs(xi,{color:"magenta",children:[l," "]}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:f(a,!1)})]},"header-"+n++)),i++;continue}if(t.startsWith(">")){const{elements:t,nextIndex:n}=A(r,i);t.forEach(t=>e.push(t)),i=n;continue}if(t.includes("|")&&i+1<r.length){const{elements:t,nextIndex:n}=g(r,i);if(t.length>0){t.forEach(t=>e.push(t)),i=n;continue}}if(t.match(/^([*+-]|\d+\.|\[[ x]\])\s+/)){const{elements:t,nextIndex:o}=h(r,i);if(t.length>0){e.push(We.jsx(ki,{flexDirection:"column",paddingLeft:2,paddingRight:1,marginY:1,children:t},"list-"+n++)),i=o;continue}}if(t.match(/^(-{3,}|\*{3,}|_{3,})$/)){e.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,marginY:1,children:We.jsx(xi,{color:"gray",children:"─".repeat(50)})},"hr-"+n++)),i++;continue}const s=[];for(;i<r.length;){const e=r[i];if(!e||""===e.trim())break;s.push(e),i++}if(s.length>0)if(l)s.forEach(t=>{t.trim()?e.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,flexDirection:"row",flexWrap:"wrap",children:f(t.trim(),!1)},"para-"+n++)):e.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,children:We.jsx(xi,{children:" "})},"para-"+n++))});else{const t=s.join(" ").trim();e.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,flexDirection:"row",flexWrap:"wrap",children:f(t,!1)},"para-"+n++))}}}}),e},[m,u,l,s,i,f]);return We.jsx(ki,{marginBottom:1,flexDirection:"column",flexShrink:0,paddingLeft:2,paddingRight:1,children:l?We.jsx(ki,{flexDirection:"column",flexShrink:0,children:We.jsx(ki,{children:We.jsx(xi,{dimColor:!0,children:m})})}):We.jsxs(ki,{flexDirection:"row",flexShrink:0,paddingLeft:2,children:[We.jsx(ki,{flexDirection:"column",marginRight:1,children:We.jsx(xi,{color:"gray",children:"╰─"})}),We.jsx(ki,{flexDirection:"column",flexShrink:0,paddingRight:1,children:y()})]})})},(e,t)=>{if(e.isStreaming!==t.isStreaming)return!1;if(e.isFocused!==t.isFocused)return!1;if(e.index!==t.index)return!1;if(e.onToolConfirm!==t.onToolConfirm)return!1;if("role"in e.message&&"role"in t.message){if(e.message.role!==t.message.role)return!1;if(t.isStreaming&&"content"in e.message&&"content"in t.message){const n="string"==typeof e.message.content?e.message.content:"",r="string"==typeof t.message.content?t.message.content:"";if(n.length!==r.length)return!1}if("timestamp"in e.message&&"timestamp"in t.message&&e.message.timestamp!==t.message.timestamp)return!1}if("id"in e.message&&"id"in t.message&&e.message.id!==t.message.id)return!1;if("toolGroup"in e.message&&"toolGroup"in t.message){const n=e.message.toolGroup,r=t.message.toolGroup;if(n.status!==r.status)return!1;if(n.tools.length!==r.tools.length)return!1;for(let e=0;e<n.tools.length;e++)if(n.tools[e].status!==r.tools[e].status)return!1}return!0}),EL=qe.memo(qe.forwardRef((e,t)=>We.jsx(bL,{...e,ref:t})),(e,t)=>e.messages===t.messages&&e.focused===t.focused&&e.onToolConfirm===t.onToolConfirm&&e.disableArrowKeyScrolling===t.disableArrowKeyScrolling),IL=qe.createContext(null);function wL({children:e}){const[t,n]=qe.useState(!1),[r,i]=qe.useState(!0),[o,s]=qe.useState(!0),[a,l]=qe.useState({width:80,height:10}),[u,c]=qe.useState(10),[d,p]=qe.useState(!0),[f,h]=qe.useState(!0),[g,A]=qe.useState([]),[m,y]=qe.useState(!1),b=qe.useCallback(e=>{n(e)},[]),v=qe.useCallback(e=>{i(e)},[]),E=qe.useCallback(e=>{s(e)},[]),I=qe.useCallback(e=>{l(e)},[]),w=qe.useCallback(e=>{c(e)},[]),C=qe.useCallback(e=>{p(e)},[]),_=qe.useCallback(e=>{h(e)},[]),B=qe.useCallback(e=>{const t=e.trim();t&&A(e=>{if(e.length>0&&e[e.length-1]===t)return e;const n=[...e,t];return n.length>50?n.slice(-50):n})},[]),D=qe.useCallback(e=>{if(!(e<0||e>=g.length))return g[g.length-1-e]},[g]),S=qe.useCallback(()=>g.length,[g]),k=qe.useCallback(e=>{y(e)},[]),x=qe.useMemo(()=>({isFileCompletionActive:t,multilineMode:r,textBufferEnabled:o,viewport:a,maxHeight:u,enableUndo:d,enableExternalEditor:f,inputHistory:g,isTyping:m}),[t,r,o,a,u,d,f,g,m]),Q=qe.useMemo(()=>({setFileCompletionActive:b,setMultilineMode:v,setTextBufferEnabled:E,setViewport:I,setMaxHeight:w,setEnableUndo:C,setEnableExternalEditor:_,addToHistory:B,getHistoryItem:D,getHistoryLength:S,setIsTyping:k}),[b,v,E,I,w,C,_,B,D,S,k]),N=qe.useMemo(()=>({state:x,actions:Q}),[x,Q]);return We.jsx(IL.Provider,{value:N,children:e})}function CL(){const e=qe.useContext(IL);if(!e)throw new Error("useInputState must be used within an InputProvider");return e}const _L={idle:[{face:"o_o",mood:"neutral",description:"Alert, ready"}],blinking:{face:"-_-",mood:"neutral",description:"Calm, composed"},typing:[{face:"._.",mood:"neutral",description:"Observing, attentive"},{face:"^_^",mood:"neutral",description:"Content you're typing"}]},BL={neutral:[{face:"^_^",mood:"neutral",description:"Content, neutral"},{face:"-_-",mood:"neutral",description:"Calm, composed"},{face:"._.",mood:"neutral",description:"Observing, attentive"},{face:"o_o",mood:"neutral",description:"Alert, ready"}],happy:[{face:"^o^",mood:"happy",description:"Very pleased"},{face:"^v^",mood:"happy",description:"Satisfied"},{face:"◠‿◠",mood:"happy",description:"Genuinely happy"},{face:"^ᴗ^",mood:"happy",description:"Cheerful"}],excited:[{face:"*o*",mood:"excited",description:"Amazed"},{face:"★_★",mood:"excited",description:"Star-struck"},{face:"✧_✧",mood:"excited",description:"Sparkling with excitement"},{face:"◉_◉",mood:"excited",description:"Eyes wide with excitement"}],working:[{face:"⊙_⊙",mood:"working",description:"Focused"},{face:"◔_◔",mood:"working",description:"Concentrating"},{face:"●_●",mood:"working",description:"Processing"},{face:"◕_◕",mood:"working",description:"Working hard"}],thinking:[{face:"⊙﹏⊙",mood:"thinking",description:"Deep in thought"},{face:"◔_◔",mood:"thinking",description:"Pondering"},{face:"⊚_⊚",mood:"thinking",description:"Analyzing"},{face:"◉‿◉",mood:"thinking",description:"Considering options"}],concerned:[{face:"⊙︿⊙",mood:"concerned",description:"Worried"},{face:"◕︿◕",mood:"concerned",description:"Concerned"},{face:"⊙﹏⊙",mood:"concerned",description:"Uncertain"},{face:"╥_╥",mood:"concerned",description:"Troubled"}],error:[{face:"x_x",mood:"error",description:"Failed"},{face:"×_×",mood:"error",description:"Error occurred"},{face:"✖_✖",mood:"error",description:"Something went wrong"},{face:"@_@",mood:"error",description:"Confused/overwhelmed"}],sleeping:[{face:"-_-",mood:"sleeping",description:"Resting"},{face:"˘_˘",mood:"sleeping",description:"Sleepy"},{face:"ᴗ_ᴗ",mood:"sleeping",description:"Dozing"},{face:"zzz",mood:"sleeping",description:"Asleep"}],playful:[{face:"^ω^",mood:"playful",description:"Playful"},{face:"≧◡≦",mood:"playful",description:"Having fun"},{face:"◠ᴥ◠",mood:"playful",description:"Silly"},{face:"ᴗ_ᴗ",mood:"playful",description:"Mischievous"}],greedy:[{face:"$_$",mood:"greedy",description:"Money eyes - low balance"},{face:"💲_💲",mood:"greedy",description:"Dollar signs - needs credits"},{face:"$ᴗ$",mood:"greedy",description:"Greedy for credits"},{face:"💰_💰",mood:"greedy",description:"Money bags - pay up!"}]};function DL(){const e=Math.floor(Math.random()*_L.idle.length);return _L.idle[e]??_L.idle[0]}function SL(){return _L.blinking}const kL=kw(e=>({currentFile:null,setCurrentFile:t=>e({currentFile:t})}));function xL({currentModel:e,streamingState:t,lastToolStatus:n,messages:r,yoloEnabled:i=!1}){const{billingStatus:o}=FT(),{state:s}=CL(),{currentFile:a}=kL(),[l,u]=qe.useState(()=>DL());qe.useEffect(()=>{if(t===_w.Idle&&!s.isTyping)return;const e=void 0!==(r={isStreaming:t===_w.Responding,hasError:"error"===n,isThinking:t===_w.WaitingForConfirmation,lastToolSuccess:"success"===n||"error"!==n&&void 0,creditBalance:o?.totalCreditBalance}).creditBalance&&r.creditBalance<500?"greedy":r.hasError?"error":r.isStreaming?"working":r.isThinking?"thinking":!0===r.lastToolSuccess?"happy":!1===r.lastToolSuccess?"concerned":"neutral";var r;u(function(e){const t=BL[e];return t[Math.floor(Math.random()*t.length)]??BL.neutral[0]}(e))},[t,n,o?.totalCreditBalance,s.isTyping]),qe.useEffect(()=>{s.isTyping&&t===_w.Idle&&u(function(){const e=Math.floor(Math.random()*_L.typing.length);return _L.typing[e]??_L.typing[0]}())},[s.isTyping,t]),qe.useEffect(()=>{if(t!==_w.Idle||s.isTyping)return;const e=3e3+2e3*Math.random(),n=setTimeout(()=>{u(SL()),setTimeout(()=>{u(DL()),setTimeout(()=>{u(SL()),setTimeout(()=>{u(DL())},150)},100)},150)},e);return()=>clearTimeout(n)},[t,s.isTyping,l]);const c=qe.useMemo(()=>{if(!e||!r||0===r.length)return null;return dM(bM(r),aM(cM(e.modelId||e.name))||uM(e.provider))},[e,r]),d=qe.useMemo(()=>{if(!a)return null;const e=ae.relative(process.cwd(),a);return e.length>50?ae.basename(a):e},[a]),p=qe.useMemo(()=>{if(!o)return"Loading...";const{planType:e,totalCreditBalance:t}=o;return"plan_unlimited"===e?"Embedder Ultra":"plan_base"===e?"Embedder Pro":`Free Tier: $${(t/100).toFixed(2)}`},[o]);return qe.useMemo(()=>{const t=null!==c?` • ${c}%`:"";return HM(`{ ${l.face} } ${e?.name??"No model selected"} (Ctrl+B)${t} • ${p}`)},[l.face,e?.name,p,c]),We.jsx(ki,{flexDirection:"column",paddingY:1,children:We.jsxs(ki,{flexDirection:"row",marginBottom:1,justifyContent:"space-between",children:[We.jsxs(ki,{flexDirection:"row",children:[We.jsx(xi,{color:"cyan",bold:!0,children:"{ "}),We.jsx(xi,{color:"yellow",bold:!0,children:l.face}),We.jsx(xi,{color:"cyan",bold:!0,children:" } "}),We.jsx(xi,{color:"white",dimColor:!0,children:e?.name??"No model selected"}),We.jsxs(xi,{color:"gray",dimColor:!0,children:[" ","(Ctrl+B)"]}),null!==c&&We.jsxs(We.Fragment,{children:[We.jsx(xi,{color:"gray",children:" • "}),We.jsxs(xi,{color:c>=90?"red":c>=70?"yellow":"cyan",dimColor:!0,children:[c,"%"]})]}),We.jsx(xi,{color:"gray",children:" • "}),We.jsx(xi,{color:"green",dimColor:!0,children:p})]}),We.jsxs(ki,{flexDirection:"row",gap:2,children:[d&&We.jsx(xi,{color:"gray",dimColor:!0,italic:!0,children:d}),i&&We.jsx(xi,{color:"red",bold:!0,children:"YOLO"})]})]})})}const QL={dots:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},dots2:{interval:80,frames:["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},dots3:{interval:80,frames:["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},dots4:{interval:80,frames:["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},dots5:{interval:80,frames:["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},dots6:{interval:80,frames:["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},dots7:{interval:80,frames:["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},dots8:{interval:80,frames:["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},dots9:{interval:80,frames:["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},dots10:{interval:80,frames:["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},dots11:{interval:100,frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},dots12:{interval:80,frames:["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},dots13:{interval:80,frames:["⣼","⣹","⢻","⠿","⡟","⣏","⣧","⣶"]},dots8Bit:{interval:80,frames:["⠀","⠁","⠂","⠃","⠄","⠅","⠆","⠇","⡀","⡁","⡂","⡃","⡄","⡅","⡆","⡇","⠈","⠉","⠊","⠋","⠌","⠍","⠎","⠏","⡈","⡉","⡊","⡋","⡌","⡍","⡎","⡏","⠐","⠑","⠒","⠓","⠔","⠕","⠖","⠗","⡐","⡑","⡒","⡓","⡔","⡕","⡖","⡗","⠘","⠙","⠚","⠛","⠜","⠝","⠞","⠟","⡘","⡙","⡚","⡛","⡜","⡝","⡞","⡟","⠠","⠡","⠢","⠣","⠤","⠥","⠦","⠧","⡠","⡡","⡢","⡣","⡤","⡥","⡦","⡧","⠨","⠩","⠪","⠫","⠬","⠭","⠮","⠯","⡨","⡩","⡪","⡫","⡬","⡭","⡮","⡯","⠰","⠱","⠲","⠳","⠴","⠵","⠶","⠷","⡰","⡱","⡲","⡳","⡴","⡵","⡶","⡷","⠸","⠹","⠺","⠻","⠼","⠽","⠾","⠿","⡸","⡹","⡺","⡻","⡼","⡽","⡾","⡿","⢀","⢁","⢂","⢃","⢄","⢅","⢆","⢇","⣀","⣁","⣂","⣃","⣄","⣅","⣆","⣇","⢈","⢉","⢊","⢋","⢌","⢍","⢎","⢏","⣈","⣉","⣊","⣋","⣌","⣍","⣎","⣏","⢐","⢑","⢒","⢓","⢔","⢕","⢖","⢗","⣐","⣑","⣒","⣓","⣔","⣕","⣖","⣗","⢘","⢙","⢚","⢛","⢜","⢝","⢞","⢟","⣘","⣙","⣚","⣛","⣜","⣝","⣞","⣟","⢠","⢡","⢢","⢣","⢤","⢥","⢦","⢧","⣠","⣡","⣢","⣣","⣤","⣥","⣦","⣧","⢨","⢩","⢪","⢫","⢬","⢭","⢮","⢯","⣨","⣩","⣪","⣫","⣬","⣭","⣮","⣯","⢰","⢱","⢲","⢳","⢴","⢵","⢶","⢷","⣰","⣱","⣲","⣳","⣴","⣵","⣶","⣷","⢸","⢹","⢺","⢻","⢼","⢽","⢾","⢿","⣸","⣹","⣺","⣻","⣼","⣽","⣾","⣿"]},sand:{interval:80,frames:["⠁","⠂","⠄","⡀","⡈","⡐","⡠","⣀","⣁","⣂","⣄","⣌","⣔","⣤","⣥","⣦","⣮","⣶","⣷","⣿","⡿","⠿","⢟","⠟","⡛","⠛","⠫","⢋","⠋","⠍","⡉","⠉","⠑","⠡","⢁"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["⠂","-","–","—","–","-"]},pipe:{interval:100,frames:["┤","┘","┴","└","├","┌","┬","┐"]},simpleDots:{interval:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{interval:200,frames:[". ",".. ","..."," .."," ."," "]},star:{interval:70,frames:["✶","✸","✹","✺","✹","✷"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","´","-","_","_","_"]},hamburger:{interval:100,frames:["☱","☲","☴"]},growVertical:{interval:120,frames:["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},growHorizontal:{interval:120,frames:["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","°","O","o","."]},noise:{interval:100,frames:["▓","▒","░"]},bounce:{interval:120,frames:["⠁","⠂","⠄","⠂"]},boxBounce:{interval:120,frames:["▖","▘","▝","▗"]},boxBounce2:{interval:100,frames:["▌","▀","▐","▄"]},triangle:{interval:50,frames:["◢","◣","◤","◥"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["◜","◠","◝","◞","◡","◟"]},circle:{interval:120,frames:["◡","⊙","◠"]},squareCorners:{interval:180,frames:["◰","◳","◲","◱"]},circleQuarters:{interval:120,frames:["◴","◷","◶","◵"]},circleHalves:{interval:50,frames:["◐","◓","◑","◒"]},squish:{interval:100,frames:["╫","╪"]},toggle:{interval:250,frames:["⊶","⊷"]},toggle2:{interval:80,frames:["▫","▪"]},toggle3:{interval:120,frames:["□","■"]},toggle4:{interval:100,frames:["■","□","▪","▫"]},toggle5:{interval:100,frames:["▮","▯"]},toggle6:{interval:300,frames:["ဝ","၀"]},toggle7:{interval:80,frames:["⦾","⦿"]},toggle8:{interval:100,frames:["◍","◌"]},toggle9:{interval:100,frames:["◉","◎"]},toggle10:{interval:100,frames:["㊂","㊀","㊁"]},toggle11:{interval:50,frames:["⧇","⧆"]},toggle12:{interval:120,frames:["☗","☖"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["←","↖","↑","↗","→","↘","↓","↙"]},arrow2:{interval:80,frames:["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},arrow3:{interval:120,frames:["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},bouncingBar:{interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{interval:80,frames:["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},smiley:{interval:200,frames:["😄 ","😝 "]},monkey:{interval:300,frames:["🙈 ","🙈 ","🙉 ","🙊 "]},hearts:{interval:100,frames:["💛 ","💙 ","💜 ","💚 ","❤️ "]},clock:{interval:100,frames:["🕛 ","🕐 ","🕑 ","🕒 ","🕓 ","🕔 ","🕕 ","🕖 ","🕗 ","🕘 ","🕙 ","🕚 "]},earth:{interval:180,frames:["🌍 ","🌎 ","🌏 "]},material:{interval:17,frames:["█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███████▁▁▁▁▁▁▁▁▁▁▁▁▁","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","██████████▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","█████████████▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁██████████████▁▁▁▁","▁▁▁██████████████▁▁▁","▁▁▁▁█████████████▁▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁▁▁████████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","██████▁▁▁▁▁▁▁▁▁▁▁▁▁█","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁▁█████████████▁▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁▁███████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁▁█████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁"]},moon:{interval:80,frames:["🌑 ","🌒 ","🌓 ","🌔 ","🌕 ","🌖 ","🌗 ","🌘 "]},runner:{interval:140,frames:["🚶 ","🏃 "]},pong:{interval:80,frames:["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},shark:{interval:120,frames:["▐|\\____________▌","▐_|\\___________▌","▐__|\\__________▌","▐___|\\_________▌","▐____|\\________▌","▐_____|\\_______▌","▐______|\\______▌","▐_______|\\_____▌","▐________|\\____▌","▐_________|\\___▌","▐__________|\\__▌","▐___________|\\_▌","▐____________|\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["☀️ ","☀️ ","☀️ ","🌤 ","⛅️ ","🌥 ","☁️ ","🌧 ","🌨 ","🌧 ","🌨 ","🌧 ","🌨 ","⛈ ","🌨 ","🌧 ","🌨 ","☁️ ","🌥 ","⛅️ ","🌤 ","☀️ ","☀️ "]},christmas:{interval:400,frames:["🌲","🎄"]},grenade:{interval:80,frames:["، ","′ "," ´ "," ‾ "," ⸌"," ⸊"," |"," ⁎"," ⁕"," ෴ "," ⁓"," "," "," "]},point:{interval:125,frames:["∙∙∙","●∙∙","∙●∙","∙∙●","∙∙∙"]},layer:{interval:150,frames:["-","=","≡"]},betaWave:{interval:80,frames:["ρββββββ","βρβββββ","ββρββββ","βββρβββ","ββββρββ","βββββρβ","ββββββρ"]},fingerDance:{interval:160,frames:["🤘 ","🤟 ","🖖 ","✋ ","🤚 ","👆 "]},fistBump:{interval:80,frames:["🤜    🤛 ","🤜    🤛 ","🤜    🤛 "," 🤜  🤛  ","  🤜🤛   "," 🤜✨🤛   ","🤜 ✨ 🤛  "]},soccerHeader:{interval:80,frames:[" 🧑⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 "]},mindblown:{interval:160,frames:["😐 ","😐 ","😮 ","😮 ","😦 ","😦 ","😧 ","😧 ","🤯 ","💥 ","✨ ","  ","  ","  "]},speaker:{interval:160,frames:["🔈 ","🔉 ","🔊 ","🔉 "]},orangePulse:{interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 "]},bluePulse:{interval:100,frames:["🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},orangeBluePulse:{interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 ","🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},timeTravel:{interval:100,frames:["🕛 ","🕚 ","🕙 ","🕘 ","🕗 ","🕖 ","🕕 ","🕔 ","🕓 ","🕒 ","🕑 ","🕐 "]},aesthetic:{interval:80,frames:["▰▱▱▱▱▱▱","▰▰▱▱▱▱▱","▰▰▰▱▱▱▱","▰▰▰▰▱▱▱","▰▰▰▰▰▱▱","▰▰▰▰▰▰▱","▰▰▰▰▰▰▰","▰▱▱▱▱▱▱"]},dwarfFortress:{interval:80,frames:[" ██████£££ ","☺██████£££ ","☺██████£££ ","☺▓█████£££ ","☺▓█████£££ ","☺▒█████£££ ","☺▒█████£££ ","☺░█████£££ ","☺░█████£££ ","☺ █████£££ "," ☺█████£££ "," ☺█████£££ "," ☺▓████£££ "," ☺▓████£££ "," ☺▒████£££ "," ☺▒████£££ "," ☺░████£££ "," ☺░████£££ "," ☺ ████£££ "," ☺████£££ "," ☺████£££ "," ☺▓███£££ "," ☺▓███£££ "," ☺▒███£££ "," ☺▒███£££ "," ☺░███£££ "," ☺░███£££ "," ☺ ███£££ "," ☺███£££ "," ☺███£££ "," ☺▓██£££ "," ☺▓██£££ "," ☺▒██£££ "," ☺▒██£££ "," ☺░██£££ "," ☺░██£££ "," ☺ ██£££ "," ☺██£££ "," ☺██£££ "," ☺▓█£££ "," ☺▓█£££ "," ☺▒█£££ "," ☺▒█£££ "," ☺░█£££ "," ☺░█£££ "," ☺ █£££ "," ☺█£££ "," ☺█£££ "," ☺▓£££ "," ☺▓£££ "," ☺▒£££ "," ☺▒£££ "," ☺░£££ "," ☺░£££ "," ☺ £££ "," ☺£££ "," ☺£££ "," ☺▓££ "," ☺▓££ "," ☺▒££ "," ☺▒££ "," ☺░££ "," ☺░££ "," ☺ ££ "," ☺££ "," ☺££ "," ☺▓£ "," ☺▓£ "," ☺▒£ "," ☺▒£ "," ☺░£ "," ☺░£ "," ☺ £ "," ☺£ "," ☺£ "," ☺▓ "," ☺▓ "," ☺▒ "," ☺▒ "," ☺░ "," ☺░ "," ☺ "," ☺ &"," ☺ ☼&"," ☺ ☼ &"," ☺☼ &"," ☺☼ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & ","‼ & "," & "," & "," & ░ "," & ▒ "," & ▓ "," & £ "," & ░£ "," & ▒£ "," & ▓£ "," & ££ "," & ░££ "," & ▒££ ","& ▓££ ","& £££ "," ░£££ "," ▒£££ "," ▓£££ "," █£££ "," ░█£££ "," ▒█£££ "," ▓█£££ "," ██£££ "," ░██£££ "," ▒██£££ "," ▓██£££ "," ███£££ "," ░███£££ "," ▒███£££ "," ▓███£££ "," ████£££ "," ░████£££ "," ▒████£££ "," ▓████£££ "," █████£££ "," ░█████£££ "," ▒█████£££ "," ▓█████£££ "," ██████£££ "," ██████£££ "]}};var NL,TL;const RL=e(function(){if(TL)return NL;TL=1;const e=Object.assign({},QL),t=Object.keys(e);return Object.defineProperty(e,"random",{get(){const n=Math.floor(Math.random()*t.length),r=t[n];return e[r]}}),NL=e}());function FL({type:e="dots"}){const[t,n]=qe.useState(0),r=RL[e];return qe.useEffect(()=>{const e=setInterval(()=>{n(e=>e===r.frames.length-1?0:e+1)},r.interval);return()=>{clearInterval(e)}},[r]),Je.createElement(xi,null,r.frames[t])}function ML(){const{streamingState:e,thought:t,isResponding:n,messages:r}=BM(),i=DM(e=>e.totalTokenCount),o=DM(e=>e.streams),[s,a]=qe.useState(0),[l,u]=qe.useState(0),[c,d]=qe.useState(!1);if(qe.useEffect(()=>{const t=r.some(e=>"role"in e&&"tool-group"===e.role&&e.toolGroup.tools.some(e=>e.status===SM.Confirming));(e===_w.WaitingForConfirmation||t)&&u(0)},[e,r]),qe.useEffect(()=>{if(!t?.startTime||e===_w.Idle)return u(0),void d(!1);const n=setInterval(()=>{c||(u(e=>0===e?1:e+1),Math.random()<.05&&(d(!0),setTimeout(()=>d(!1),1e3)))},50);return()=>clearInterval(n)},[t?.startTime,e,c]),qe.useEffect(()=>{if(!t?.startTime||e===_w.Idle)return void a(0);const n=()=>{const e=Math.floor((Date.now()-(t.startTime||0))/1e3);a(e)};n();const r=setInterval(n,100);return()=>clearInterval(r)},[t?.startTime,e]),e===_w.Idle)return null;const p=t?.subject||"Thinking...",f=e===_w.WaitingForConfirmation,h=r.some(e=>"role"in e&&"tool-group"===e.role&&e.toolGroup.tools.some(e=>e.status===SM.Confirming)),g=r.some(e=>"role"in e&&"tool-group"===e.role&&e.toolGroup.tools.some(e=>e.status===SM.Executing)),A=Array.from(o.values()).some(e=>"ai-thinking"!==e.toolCallId),m=o.get("ai-thinking"),y=m&&Date.now()-m.timestamp<100,b=r[r.length-1],v=b&&"role"in b&&"assistant"===b.role,E=l+i,I=E>0&&!(n&&v&&y&&!g&&!A)&&!f&&!h,w=[];f||w.push("esc to interrupt"),s>0&&w.push(`${s}s`),I&&w.push(`↓ ${E} tokens`);const C=w.length>0?` (${w.join(" · ")})`:"";return We.jsxs(ki,{marginBottom:1,paddingLeft:2,paddingRight:1,children:[We.jsx(ki,{marginRight:1,children:We.jsx(FL,{type:"dots"})}),We.jsxs(xi,{color:"gray",children:[p,C]}),t?.description&&We.jsx(ki,{marginTop:0,paddingLeft:3,children:We.jsx(xi,{color:"gray",dimColor:!0,children:t.description})})]})}const OL=(e,t,n)=>{const r=e instanceof RegExp?$L(e,n):e,i=t instanceof RegExp?$L(t,n):t,o=null!==r&&null!=i&&LL(r,i,n);return o&&{start:o[0],end:o[1],pre:n.slice(0,o[0]),body:n.slice(o[0]+r.length,o[1]),post:n.slice(o[1]+i.length)}},$L=(e,t)=>{const n=t.match(e);return n?n[0]:null},LL=(e,t,n)=>{let r,i,o,s,a,l=n.indexOf(e),u=n.indexOf(t,l+1),c=l;if(l>=0&&u>0){if(e===t)return[l,u];for(r=[],o=n.length;c>=0&&!a;){if(c===l)r.push(c),l=n.indexOf(e,c+1);else if(1===r.length){const e=r.pop();void 0!==e&&(a=[e,u])}else i=r.pop(),void 0!==i&&i<o&&(o=i,s=u),u=n.indexOf(t,c+1);c=l<u&&l>=0?l:u}r.length&&void 0!==s&&(a=[o,s])}return a},PL="\0SLASH"+Math.random()+"\0",jL="\0OPEN"+Math.random()+"\0",UL="\0CLOSE"+Math.random()+"\0",zL="\0COMMA"+Math.random()+"\0",GL="\0PERIOD"+Math.random()+"\0",HL=new RegExp(PL,"g"),WL=new RegExp(jL,"g"),qL=new RegExp(UL,"g"),JL=new RegExp(zL,"g"),KL=new RegExp(GL,"g"),ZL=/\\\\/g,VL=/\\{/g,YL=/\\}/g,XL=/\\,/g,eP=/\\./g;function tP(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function nP(e){return e.replace(HL,"\\").replace(WL,"{").replace(qL,"}").replace(JL,",").replace(KL,".")}function rP(e){if(!e)return[""];const t=[],n=OL("{","}",e);if(!n)return e.split(",");const{pre:r,body:i,post:o}=n,s=r.split(",");s[s.length-1]+="{"+i+"}";const a=rP(o);return o.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),t.push.apply(t,s),t}function iP(e){return e?("{}"===e.slice(0,2)&&(e="\\{\\}"+e.slice(2)),uP(function(e){return e.replace(ZL,PL).replace(VL,jL).replace(YL,UL).replace(XL,zL).replace(eP,GL)}(e),!0).map(nP)):[]}function oP(e){return"{"+e+"}"}function sP(e){return/^-?0\d/.test(e)}function aP(e,t){return e<=t}function lP(e,t){return e>=t}function uP(e,t){const n=[],r=OL("{","}",e);if(!r)return[e];const i=r.pre,o=r.post.length?uP(r.post,!1):[""];if(/\$$/.test(r.pre))for(let s=0;s<o.length;s++){const e=i+"{"+r.body+"}"+o[s];n.push(e)}else{const s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),a=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),l=s||a,u=r.body.indexOf(",")>=0;if(!l&&!u)return r.post.match(/,(?!,).*\}/)?uP(e=r.pre+"{"+r.body+UL+r.post):[e];let c,d;if(l)c=r.body.split(/\.\./);else if(c=rP(r.body),1===c.length&&void 0!==c[0]&&(c=uP(c[0],!1).map(oP),1===c.length))return o.map(e=>r.pre+c[0]+e);if(l&&void 0!==c[0]&&void 0!==c[1]){const e=tP(c[0]),t=tP(c[1]),n=Math.max(c[0].length,c[1].length);let r=3===c.length&&void 0!==c[2]?Math.abs(tP(c[2])):1,i=aP;t<e&&(r*=-1,i=lP);const o=c.some(sP);d=[];for(let s=e;i(s,t);s+=r){let e;if(a)e=String.fromCharCode(s),"\\"===e&&(e="");else if(e=String(s),o){const t=n-e.length;if(t>0){const n=new Array(t+1).join("0");e=s<0?"-"+n+e.slice(1):n+e}}d.push(e)}}else{d=[];for(let e=0;e<c.length;e++)d.push.apply(d,uP(c[e],!1))}for(let e=0;e<d.length;e++)for(let r=0;r<o.length;r++){const s=i+d[e]+o[r];(!t||l||s)&&n.push(s)}}return n}const cP=e=>{if("string"!=typeof e)throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},dP={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},pP=e=>e.replace(/[[\]\\-]/g,"\\$&"),fP=e=>e.join(""),hP=(e,t)=>{const n=t;if("["!==e.charAt(n))throw new Error("not in a brace expression");const r=[],i=[];let o=n+1,s=!1,a=!1,l=!1,u=!1,c=n,d="";e:for(;o<e.length;){const t=e.charAt(o);if("!"!==t&&"^"!==t||o!==n+1){if("]"===t&&s&&!l){c=o+1;break}if(s=!0,"\\"!==t||l){if("["===t&&!l)for(const[t,[s,l,u]]of Object.entries(dP))if(e.startsWith(t,o)){if(d)return["$.",!1,e.length-n,!0];o+=t.length,u?i.push(s):r.push(s),a=a||l;continue e}l=!1,d?(t>d?r.push(pP(d)+"-"+pP(t)):t===d&&r.push(pP(t)),d="",o++):e.startsWith("-]",o+1)?(r.push(pP(t+"-")),o+=2):e.startsWith("-",o+1)?(d=t,o+=2):(r.push(pP(t)),o++)}else l=!0,o++}else u=!0,o++}if(c<o)return["",!1,0,!1];if(!r.length&&!i.length)return["$.",!1,e.length-n,!0];if(0===i.length&&1===r.length&&/^\\?.$/.test(r[0])&&!u){const e=2===r[0].length?r[0].slice(-1):r[0];return[(p=e,p.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")),!1,c-n,!1]}var p;const f="["+(u?"^":"")+fP(r)+"]",h="["+(u?"":"^")+fP(i)+"]";return[r.length&&i.length?"("+f+"|"+h+")":r.length?f:h,a,c-n,!0]},gP=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"),AP=new Set(["!","?","+","*","@"]),mP=e=>AP.has(e),yP="(?!\\.)",bP=new Set(["[","."]),vP=new Set(["..","."]),EP=new Set("().*{}+?[]^$\\!"),IP=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),wP="[^/]",CP=wP+"*?",_P=wP+"+?";class BP{type;#e;#t;#n=!1;#r=[];#i;#o;#s;#a=!1;#l;#u;#c=!1;constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#l=this.#e===this?n:this.#e.#l,this.#s=this.#e===this?[]:this.#e.#s,"!"!==e||this.#e.#a||this.#s.push(this),this.#o=this.#i?this.#i.#r.length:0}get hasMagic(){if(void 0!==this.#t)return this.#t;for(const e of this.#r)if("string"!=typeof e&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return void 0!==this.#u?this.#u:this.type?this.#u=this.type+"("+this.#r.map(e=>String(e)).join("|")+")":this.#u=this.#r.map(e=>String(e)).join("")}#d(){if(this!==this.#e)throw new Error("should only call on root");if(this.#a)return this;let e;for(this.toString(),this.#a=!0;e=this.#s.pop();){if("!"!==e.type)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#o+1;!n.type&&r<n.#r.length;r++)for(const t of e.#r){if("string"==typeof t)throw new Error("string part in extglob AST??");t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(const t of e)if(""!==t){if("string"!=typeof t&&!(t instanceof BP&&t.#i===this))throw new Error("invalid part: "+t);this.#r.push(t)}}toJSON(){const e=null===this.type?this.#r.slice().map(e=>"string"==typeof e?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#a&&"!"===this.#i?.type)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(0===this.#o)return!0;const e=this.#i;for(let t=0;t<this.#o;t++){const n=e.#r[t];if(!(n instanceof BP&&"!"===n.type))return!1}return!0}isEnd(){if(this.#e===this)return!0;if("!"===this.#i?.type)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();const e=this.#i?this.#i.#r.length:0;return this.#o===e-1}copyIn(e){"string"==typeof e?this.push(e):this.push(e.clone(this))}clone(e){const t=new BP(this.type,e);for(const n of this.#r)t.copyIn(n);return t}static#p(e,t,n,r){let i=!1,o=!1,s=-1,a=!1;if(null===t.type){let l=n,u="";for(;l<e.length;){const n=e.charAt(l++);if(i||"\\"===n)i=!i,u+=n;else if(o)l===s+1?"^"!==n&&"!"!==n||(a=!0):"]"!==n||l===s+2&&a||(o=!1),u+=n;else if("["!==n){if(!r.noext&&mP(n)&&"("===e.charAt(l)){t.push(u),u="";const i=new BP(n,t);l=BP.#p(e,i,l,r),t.push(i);continue}u+=n}else o=!0,s=l,a=!1,u+=n}return t.push(u),l}let l=n+1,u=new BP(null,t);const c=[];let d="";for(;l<e.length;){const n=e.charAt(l++);if(i||"\\"===n)i=!i,d+=n;else if(o)l===s+1?"^"!==n&&"!"!==n||(a=!0):"]"!==n||l===s+2&&a||(o=!1),d+=n;else if("["!==n){if(mP(n)&&"("===e.charAt(l)){u.push(d),d="";const t=new BP(n,u);u.push(t),l=BP.#p(e,t,l,r);continue}if("|"!==n){if(")"===n)return""===d&&0===t.#r.length&&(t.#c=!0),u.push(d),d="",t.push(...c,u),l;d+=n}else u.push(d),d="",c.push(u),u=new BP(null,t)}else o=!0,s=l,a=!1,d+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],l}static fromGlob(e,t={}){const n=new BP(null,void 0,t);return BP.#p(e,n,0,t),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();const e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#l.nocase&&!this.#l.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;const o=(this.#l.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,o),{_src:t,_glob:e})}get options(){return this.#l}toRegExpSource(e){const t=e??!!this.#l.dot;if(this.#e===this&&this.#d(),!this.type){const n=this.isStart()&&this.isEnd(),r=this.#r.map(t=>{const[r,i,o,s]="string"==typeof t?BP.#f(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||o,this.#n=this.#n||s,r}).join("");let i="";if(this.isStart()&&"string"==typeof this.#r[0]){if(!(1===this.#r.length&&vP.has(this.#r[0]))){const n=bP,o=t&&n.has(r.charAt(0))||r.startsWith("\\.")&&n.has(r.charAt(2))||r.startsWith("\\.\\.")&&n.has(r.charAt(4)),s=!t&&!e&&n.has(r.charAt(0));i=o?"(?!(?:^|/)\\.\\.?(?:$|/))":s?yP:""}}let o="";this.isEnd()&&this.#e.#a&&"!"===this.#i?.type&&(o="(?:$|\\/)");return[i+r+o,gP(r),this.#t=!!this.#t,this.#n]}const n="*"===this.type||"+"===this.type,r="!"===this.type?"(?:(?!(?:":"(?:";let i=this.#h(t);if(this.isStart()&&this.isEnd()&&!i&&"!"!==this.type){const e=this.toString();return this.#r=[e],this.type=null,this.#t=void 0,[e,gP(this.toString()),!1,!1]}let o=!n||e||t?"":this.#h(!0);o===i&&(o=""),o&&(i=`(?:${i})(?:${o})*?`);let s="";if("!"===this.type&&this.#c)s=(this.isStart()&&!t?yP:"")+_P;else{s=r+i+("!"===this.type?"))"+(!this.isStart()||t||e?"":yP)+CP+")":"@"===this.type?")":"?"===this.type?")?":"+"===this.type&&o?")":"*"===this.type&&o?")?":`)${this.type}`)}return[s,gP(i),this.#t=!!this.#t,this.#n]}#h(e){return this.#r.map(t=>{if("string"==typeof t)throw new Error("string type in extglob ast??");const[n,r,i,o]=t.toRegExpSource(e);return this.#n=this.#n||o,n}).filter(e=>!(this.isStart()&&this.isEnd()&&!e)).join("|")}static#f(e,t,n=!1){let r=!1,i="",o=!1;for(let s=0;s<e.length;s++){const a=e.charAt(s);if(r)r=!1,i+=(EP.has(a)?"\\":"")+a;else if("\\"!==a){if("["===a){const[n,r,a,l]=hP(e,s);if(a){i+=n,o=o||r,s+=a-1,t=t||l;continue}}"*"!==a?"?"!==a?i+=IP(a):(i+=wP,t=!0):(i+=n&&"*"===e?_P:CP,t=!0)}else s===e.length-1?i+="\\\\":r=!0}return[i,gP(e),!!t,o]}}const DP=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),SP=(e,t,n={})=>(cP(t),!(!n.nocomment&&"#"===t.charAt(0))&&new ej(t,n).match(e)),kP=/^\*+([^+@!?\*\[\(]*)$/,xP=e=>t=>!t.startsWith(".")&&t.endsWith(e),QP=e=>t=>t.endsWith(e),NP=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),TP=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),RP=/^\*+\.\*+$/,FP=e=>!e.startsWith(".")&&e.includes("."),MP=e=>"."!==e&&".."!==e&&e.includes("."),OP=/^\.\*+$/,$P=e=>"."!==e&&".."!==e&&e.startsWith("."),LP=/^\*+$/,PP=e=>0!==e.length&&!e.startsWith("."),jP=e=>0!==e.length&&"."!==e&&".."!==e,UP=/^\?+([^+@!?\*\[\(]*)?$/,zP=([e,t=""])=>{const n=qP([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},GP=([e,t=""])=>{const n=JP([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},HP=([e,t=""])=>{const n=JP([e]);return t?e=>n(e)&&e.endsWith(t):n},WP=([e,t=""])=>{const n=qP([e]);return t?e=>n(e)&&e.endsWith(t):n},qP=([e])=>{const t=e.length;return e=>e.length===t&&!e.startsWith(".")},JP=([e])=>{const t=e.length;return e=>e.length===t&&"."!==e&&".."!==e},KP="object"==typeof process&&process?"object"==typeof process.env&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";SP.sep="win32"===KP?{sep:"\\"}.sep:{sep:"/"}.sep;const ZP=Symbol("globstar **");SP.GLOBSTAR=ZP;SP.filter=(e,t={})=>n=>SP(n,e,t);const VP=(e,t={})=>Object.assign({},e,t);SP.defaults=e=>{if(!e||"object"!=typeof e||!Object.keys(e).length)return SP;const t=SP;return Object.assign((n,r,i={})=>t(n,r,VP(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,VP(e,n))}static defaults(n){return t.defaults(VP(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,VP(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,VP(e,r))}},unescape:(n,r={})=>t.unescape(n,VP(e,r)),escape:(n,r={})=>t.escape(n,VP(e,r)),filter:(n,r={})=>t.filter(n,VP(e,r)),defaults:n=>t.defaults(VP(e,n)),makeRe:(n,r={})=>t.makeRe(n,VP(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,VP(e,r)),match:(n,r,i={})=>t.match(n,r,VP(e,i)),sep:t.sep,GLOBSTAR:ZP})};const YP=(e,t={})=>(cP(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:iP(e));SP.braceExpand=YP;SP.makeRe=(e,t={})=>new ej(e,t).makeRe();SP.match=(e,t,n={})=>{const r=new ej(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const XP=/[?*]|[+@!]\(.*?\)|\[|\]/;class ej{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){cP(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||KP,this.isWindows="win32"===this.platform,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||!1===t.allowWindowsEscape,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=void 0!==t.windowsNoMagicRoot?t.windowsNoMagicRoot:!(!this.isWindows||!this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const e of this.set)for(const t of e)if("string"!=typeof t)return!0;return!1}debug(...e){}make(){const e=this.pattern,t=this.options;if(!t.nocomment&&"#"===e.charAt(0))return void(this.comment=!0);if(!e)return void(this.empty=!0);this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);const n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){const t=!(""!==e[0]||""!==e[1]||"?"!==e[2]&&XP.test(e[2])||XP.test(e[3])),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>-1===e.indexOf(!1)),this.isWindows)for(let i=0;i<this.set.length;i++){const e=this.set[i];""===e[0]&&""===e[1]&&"?"===this.globParts[i][2]&&"string"==typeof e[3]&&/^[a-z]:$/i.test(e[3])&&(e[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let n=0;n<e.length;n++)for(let t=0;t<e[n].length;t++)"**"===e[n][t]&&(e[n][t]="*");const{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;-1!==(t=e.indexOf("**",t+1));){let n=t;for(;"**"===e[n+1];)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>0===(e=e.reduce((e,t)=>{const n=e[e.length-1];return"**"===t&&"**"===n?e:".."===t&&n&&".."!==n&&"."!==n&&"**"!==n?(e.pop(),e):(e.push(t),e)},[])).length?[""]:e)}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){const r=e[n];1===n&&""===r&&""===e[0]||("."!==r&&""!==r||(t=!0,e.splice(n,1),n--))}"."!==e[0]||2!==e.length||"."!==e[1]&&""!==e[1]||(t=!0,e.pop())}let n=0;for(;-1!==(n=e.indexOf("..",n+1));){const r=e[n-1];r&&"."!==r&&".."!==r&&"**"!==r&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return 0===e.length?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;-1!==(r=n.indexOf("**",r+1));){let i=r;for(;"**"===n[i+1];)i++;i>r&&n.splice(r+1,i-r);let o=n[r+1];const s=n[r+2],a=n[r+3];if(".."!==o)continue;if(!s||"."===s||".."===s||!a||"."===a||".."===a)continue;t=!0,n.splice(r,1);const l=n.slice(0);l[r]="**",e.push(l),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){const r=n[e];1===e&&""===r&&""===n[0]||("."!==r&&""!==r||(t=!0,n.splice(e,1),e--))}"."!==n[0]||2!==n.length||"."!==n[1]&&""!==n[1]||(t=!0,n.pop())}let i=0;for(;-1!==(i=n.indexOf("..",i+1));){const e=n[i-1];if(e&&"."!==e&&".."!==e&&"**"!==e){t=!0;const e=1===i&&"**"===n[i+1]?["."]:[];n.splice(i-1,2,...e),0===n.length&&n.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){const r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,o=[],s="";for(;r<e.length&&i<t.length;)if(e[r]===t[i])o.push("b"===s?t[i]:e[r]),r++,i++;else if(n&&"**"===e[r]&&t[i]===e[r+1])o.push(e[r]),r++;else if(n&&"**"===t[i]&&e[r]===t[i+1])o.push(t[i]),i++;else if("*"!==e[r]||!t[i]||!this.options.dot&&t[i].startsWith(".")||"**"===t[i]){if("*"!==t[i]||!e[r]||!this.options.dot&&e[r].startsWith(".")||"**"===e[r])return!1;if("a"===s)return!1;s="b",o.push(t[i]),r++,i++}else{if("b"===s)return!1;s="a",o.push(e[r]),r++,i++}return e.length===t.length&&o}parseNegate(){if(this.nonegate)return;const e=this.pattern;let t=!1,n=0;for(let r=0;r<e.length&&"!"===e.charAt(r);r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){const r=this.options;if(this.isWindows){const n="string"==typeof e[0]&&/^[a-z]:$/i.test(e[0]),r=!n&&""===e[0]&&""===e[1]&&"?"===e[2]&&/^[a-z]:$/i.test(e[3]),i="string"==typeof t[0]&&/^[a-z]:$/i.test(t[0]),o=r?3:n?0:void 0,s=!i&&""===t[0]&&""===t[1]&&"?"===t[2]&&"string"==typeof t[3]&&/^[a-z]:$/i.test(t[3])?3:i?0:void 0;if("number"==typeof o&&"number"==typeof s){const[n,r]=[e[o],t[s]];n.toLowerCase()===r.toLowerCase()&&(t[s]=n,s>o?t=t.slice(s):o>s&&(e=e.slice(o)))}}const{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var o=0,s=0,a=e.length,l=t.length;o<a&&s<l;o++,s++){this.debug("matchOne loop");var u=t[s],c=e[o];if(this.debug(t,u,c),!1===u)return!1;if(u===ZP){this.debug("GLOBSTAR",[t,u,c]);var d=o,p=s+1;if(p===l){for(this.debug("** at the end");o<a;o++)if("."===e[o]||".."===e[o]||!r.dot&&"."===e[o].charAt(0))return!1;return!0}for(;d<a;){var f=e[d];if(this.debug("\nglobstar while",e,d,t,p,f),this.matchOne(e.slice(d),t.slice(p),n))return this.debug("globstar found match!",d,a,f),!0;if("."===f||".."===f||!r.dot&&"."===f.charAt(0)){this.debug("dot detected!",e,d,t,p);break}this.debug("globstar swallow a segment, and continue"),d++}return!(!n||(this.debug("\n>>> no match, partial?",e,d,t,p),d!==a))}let i;if("string"==typeof u?(i=c===u,this.debug("string match",u,c,i)):(i=u.test(c),this.debug("pattern match",u,c,i)),!i)return!1}if(o===a&&s===l)return!0;if(o===a)return n;if(s===l)return o===a-1&&""===e[o];throw new Error("wtf?")}braceExpand(){return YP(this.pattern,this.options)}parse(e){cP(e);const t=this.options;if("**"===e)return ZP;if(""===e)return"";let n,r=null;(n=e.match(LP))?r=t.dot?jP:PP:(n=e.match(kP))?r=(t.nocase?t.dot?TP:NP:t.dot?QP:xP)(n[1]):(n=e.match(UP))?r=(t.nocase?t.dot?GP:zP:t.dot?HP:WP)(n):(n=e.match(RP))?r=t.dot?MP:FP:(n=e.match(OP))&&(r=$P);const i=BP.fromGlob(e,this.options).toMMPattern();return r&&"object"==typeof i&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||!1===this.regexp)return this.regexp;const e=this.set;if(!e.length)return this.regexp=!1,this.regexp;const t=this.options,n=t.noglobstar?"[^/]*?":t.dot?"(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?":"(?:(?!(?:\\/|^)\\.).)*?",r=new Set(t.nocase?["i"]:[]);let i=e.map(e=>{const t=e.map(e=>{if(e instanceof RegExp)for(const t of e.flags.split(""))r.add(t);return"string"==typeof e?e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"):e===ZP?ZP:e._src});return t.forEach((e,r)=>{const i=t[r+1],o=t[r-1];e===ZP&&o!==ZP&&(void 0===o?void 0!==i&&i!==ZP?t[r+1]="(?:\\/|"+n+"\\/)?"+i:t[r]=n:void 0===i?t[r-1]=o+"(?:\\/|"+n+")?":i!==ZP&&(t[r-1]=o+"(?:\\/|\\/"+n+"\\/)"+i,t[r+1]=ZP))}),t.filter(e=>e!==ZP).join("/")}).join("|");const[o,s]=e.length>1?["(?:",")"]:["",""];i="^"+o+i+s+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...r].join(""))}catch(a){this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return""===e;if("/"===e&&t)return!0;const n=this.options;this.isWindows&&(e=e.split("\\").join("/"));const r=this.slashSplit(e);this.debug(this.pattern,"split",r);const i=this.set;this.debug(this.pattern,"set",i);let o=r[r.length-1];if(!o)for(let s=r.length-2;!o&&s>=0;s--)o=r[s];for(let s=0;s<i.length;s++){const e=i[s];let a=r;n.matchBase&&1===e.length&&(a=[o]);if(this.matchOne(a,e,t))return!!n.flipNegate||!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return SP.defaults(e).Minimatch}}SP.AST=BP,SP.Minimatch=ej,SP.escape=DP,SP.unescape=gP;const tj="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,nj=new Set,rj="object"==typeof process&&process?process:{},ij=(e,t,n,r)=>{"function"==typeof rj.emitWarning?rj.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let oj=globalThis.AbortController,sj=globalThis.AbortSignal;if(void 0===oj){sj=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},oj=class{constructor(){t()}signal=new sj;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==rj.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,ij("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}const aj=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),lj=e=>aj(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?uj:null:null;class uj extends Array{constructor(e){super(e),this.fill(0)}}class cj{heap;length;static#g=!1;static create(e){const t=lj(e);if(!t)return[];cj.#g=!0;const n=new cj(e,t);return cj.#g=!1,n}constructor(e,t){if(!cj.#g)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class dj{#A;#m;#y;#b;#v;#E;#I;#w;get perf(){return this.#w}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#C;#_;#B;#D;#S;#k;#x;#Q;#N;#T;#R;#F;#M;#O;#$;#L;#P;#j;static unsafeExposeInternals(e){return{starts:e.#M,ttls:e.#O,sizes:e.#F,keyMap:e.#B,keyList:e.#D,valList:e.#S,next:e.#k,prev:e.#x,get head(){return e.#Q},get tail(){return e.#N},free:e.#T,isBackgroundFetch:t=>e.#U(t),backgroundFetch:(t,n,r,i)=>e.#z(t,n,r,i),moveToTail:t=>e.#G(t),indexes:t=>e.#H(t),rindexes:t=>e.#W(t),isStale:t=>e.#q(t)}}get max(){return this.#A}get maxSize(){return this.#m}get calculatedSize(){return this.#_}get size(){return this.#C}get fetchMethod(){return this.#E}get memoMethod(){return this.#I}get dispose(){return this.#y}get onInsert(){return this.#b}get disposeAfter(){return this.#v}constructor(e){const{max:t=0,ttl:n,ttlResolution:r=1,ttlAutopurge:i,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:a,dispose:l,onInsert:u,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:p,maxSize:f=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:A,memoMethod:m,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:E,ignoreFetchAbort:I,perf:w}=e;if(void 0!==w&&"function"!=typeof w?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#w=w??tj,0!==t&&!aj(t))throw new TypeError("max option must be a nonnegative integer");const C=t?lj(t):Array;if(!C)throw new Error("invalid max value: "+t);if(this.#A=t,this.#m=f,this.maxEntrySize=h||this.#m,this.sizeCalculation=g,this.sizeCalculation){if(!this.#m&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==m&&"function"!=typeof m)throw new TypeError("memoMethod must be a function if defined");if(this.#I=m,void 0!==A&&"function"!=typeof A)throw new TypeError("fetchMethod must be a function if specified");if(this.#E=A,this.#L=!!A,this.#B=new Map,this.#D=new Array(t).fill(void 0),this.#S=new Array(t).fill(void 0),this.#k=new C(t),this.#x=new C(t),this.#Q=0,this.#N=0,this.#T=cj.create(t),this.#C=0,this.#_=0,"function"==typeof l&&(this.#y=l),"function"==typeof u&&(this.#b=u),"function"==typeof c?(this.#v=c,this.#R=[]):(this.#v=void 0,this.#R=void 0),this.#$=!!this.#y,this.#j=!!this.#b,this.#P=!!this.#v,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!v,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!I,0!==this.maxEntrySize){if(0!==this.#m&&!aj(this.#m))throw new TypeError("maxSize must be a positive integer if specified");if(!aj(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#J()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=aj(r)||0===r?r:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!aj(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#K()}if(0===this.#A&&0===this.ttl&&0===this.#m)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#A&&!this.#m){const e="LRU_CACHE_UNBOUNDED";if((e=>!nj.has(e))(e)){nj.add(e);ij("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,dj)}}}getRemainingTTL(e){return this.#B.has(e)?1/0:0}#K(){const e=new uj(this.#A),t=new uj(this.#A);this.#O=e,this.#M=t,this.#Z=(n,r,i=this.#w.now())=>{if(t[n]=0!==r?i:0,e[n]=r,0!==r&&this.ttlAutopurge){const e=setTimeout(()=>{this.#q(n)&&this.#V(this.#D[n],"expire")},r+1);e.unref&&e.unref()}},this.#Y=n=>{t[n]=0!==e[n]?this.#w.now():0},this.#X=(i,o)=>{if(e[o]){const s=e[o],a=t[o];if(!s||!a)return;i.ttl=s,i.start=a,i.now=n||r();const l=i.now-a;i.remainingTTL=s-l}};let n=0;const r=()=>{const e=this.#w.now();if(this.ttlResolution>0){n=e;const t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{const o=this.#B.get(i);if(void 0===o)return 0;const s=e[o],a=t[o];if(!s||!a)return 1/0;return s-((n||r())-a)},this.#q=i=>{const o=t[i],s=e[i];return!!s&&!!o&&(n||r())-o>s}}#Y=()=>{};#X=()=>{};#Z=()=>{};#q=()=>!1;#J(){const e=new uj(this.#A);this.#_=0,this.#F=e,this.#ee=t=>{this.#_-=e[t],e[t]=0},this.#te=(e,t,n,r)=>{if(this.#U(t))return 0;if(!aj(n)){if(!r)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof r)throw new TypeError("sizeCalculation must be a function");if(n=r(t,e),!aj(n))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return n},this.#ne=(t,n,r)=>{if(e[t]=n,this.#m){const n=this.#m-e[t];for(;this.#_>n;)this.#re(!0)}this.#_+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#_)}}#ee=e=>{};#ne=(e,t,n)=>{};#te=(e,t,n,r)=>{if(n||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#H({allowStale:e=this.allowStale}={}){if(this.#C)for(let t=this.#N;this.#ie(t)&&(!e&&this.#q(t)||(yield t),t!==this.#Q);)t=this.#x[t]}*#W({allowStale:e=this.allowStale}={}){if(this.#C)for(let t=this.#Q;this.#ie(t)&&(!e&&this.#q(t)||(yield t),t!==this.#N);)t=this.#k[t]}#ie(e){return void 0!==e&&this.#B.get(this.#D[e])===e}*entries(){for(const e of this.#H())void 0===this.#S[e]||void 0===this.#D[e]||this.#U(this.#S[e])||(yield[this.#D[e],this.#S[e]])}*rentries(){for(const e of this.#W())void 0===this.#S[e]||void 0===this.#D[e]||this.#U(this.#S[e])||(yield[this.#D[e],this.#S[e]])}*keys(){for(const e of this.#H()){const t=this.#D[e];void 0===t||this.#U(this.#S[e])||(yield t)}}*rkeys(){for(const e of this.#W()){const t=this.#D[e];void 0===t||this.#U(this.#S[e])||(yield t)}}*values(){for(const e of this.#H()){void 0===this.#S[e]||this.#U(this.#S[e])||(yield this.#S[e])}}*rvalues(){for(const e of this.#W()){void 0===this.#S[e]||this.#U(this.#S[e])||(yield this.#S[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const n of this.#H()){const r=this.#S[n],i=this.#U(r)?r.__staleWhileFetching:r;if(void 0!==i&&e(i,this.#D[n],this))return this.get(this.#D[n],t)}}forEach(e,t=this){for(const n of this.#H()){const r=this.#S[n],i=this.#U(r)?r.__staleWhileFetching:r;void 0!==i&&e.call(t,i,this.#D[n],this)}}rforEach(e,t=this){for(const n of this.#W()){const r=this.#S[n],i=this.#U(r)?r.__staleWhileFetching:r;void 0!==i&&e.call(t,i,this.#D[n],this)}}purgeStale(){let e=!1;for(const t of this.#W({allowStale:!0}))this.#q(t)&&(this.#V(this.#D[t],"expire"),e=!0);return e}info(e){const t=this.#B.get(e);if(void 0===t)return;const n=this.#S[t],r=this.#U(n)?n.__staleWhileFetching:n;if(void 0===r)return;const i={value:r};if(this.#O&&this.#M){const e=this.#O[t],n=this.#M[t];if(e&&n){const t=e-(this.#w.now()-n);i.ttl=t,i.start=Date.now()}}return this.#F&&(i.size=this.#F[t]),i}dump(){const e=[];for(const t of this.#H({allowStale:!0})){const n=this.#D[t],r=this.#S[t],i=this.#U(r)?r.__staleWhileFetching:r;if(void 0===i||void 0===n)continue;const o={value:i};if(this.#O&&this.#M){o.ttl=this.#O[t];const e=this.#w.now()-this.#M[t];o.start=Math.floor(Date.now()-e)}this.#F&&(o.size=this.#F[t]),e.unshift([n,o])}return e}load(e){this.clear();for(const[t,n]of e){if(n.start){const e=Date.now()-n.start;n.start=this.#w.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(void 0===t)return this.delete(e),this;const{ttl:r=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:a}=n;let{noUpdateTTL:l=this.noUpdateTTL}=n;const u=this.#te(e,t,n.size||0,s);if(this.maxEntrySize&&u>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#V(e,"set"),this;let c=0===this.#C?void 0:this.#B.get(e);if(void 0===c)c=0===this.#C?this.#N:0!==this.#T.length?this.#T.pop():this.#C===this.#A?this.#re(!1):this.#C,this.#D[c]=e,this.#S[c]=t,this.#B.set(e,c),this.#k[this.#N]=c,this.#x[c]=this.#N,this.#N=c,this.#C++,this.#ne(c,u,a),a&&(a.set="add"),l=!1,this.#j&&this.#b?.(t,e,"add");else{this.#G(c);const n=this.#S[c];if(t!==n){if(this.#L&&this.#U(n)){n.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=n;void 0===t||o||(this.#$&&this.#y?.(t,e,"set"),this.#P&&this.#R?.push([t,e,"set"]))}else o||(this.#$&&this.#y?.(n,e,"set"),this.#P&&this.#R?.push([n,e,"set"]));if(this.#ee(c),this.#ne(c,u,a),this.#S[c]=t,a){a.set="replace";const e=n&&this.#U(n)?n.__staleWhileFetching:n;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update");this.#j&&this.onInsert?.(t,e,t===n?"update":"replace")}if(0===r||this.#O||this.#K(),this.#O&&(l||this.#Z(c,r,i),a&&this.#X(a,c)),!o&&this.#P&&this.#R){const e=this.#R;let t;for(;t=e?.shift();)this.#v?.(...t)}return this}pop(){try{for(;this.#C;){const e=this.#S[this.#Q];if(this.#re(!0),this.#U(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#P&&this.#R){const e=this.#R;let t;for(;t=e?.shift();)this.#v?.(...t)}}}#re(e){const t=this.#Q,n=this.#D[t],r=this.#S[t];return this.#L&&this.#U(r)?r.__abortController.abort(new Error("evicted")):(this.#$||this.#P)&&(this.#$&&this.#y?.(r,n,"evict"),this.#P&&this.#R?.push([r,n,"evict"])),this.#ee(t),e&&(this.#D[t]=void 0,this.#S[t]=void 0,this.#T.push(t)),1===this.#C?(this.#Q=this.#N=0,this.#T.length=0):this.#Q=this.#k[t],this.#B.delete(n),this.#C--,t}has(e,t={}){const{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#B.get(e);if(void 0!==i){const e=this.#S[i];if(this.#U(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#q(i))return n&&this.#Y(i),r&&(r.has="hit",this.#X(r,i)),!0;r&&(r.has="stale",this.#X(r,i))}else r&&(r.has="miss");return!1}peek(e,t={}){const{allowStale:n=this.allowStale}=t,r=this.#B.get(e);if(void 0===r||!n&&this.#q(r))return;const i=this.#S[r];return this.#U(i)?i.__staleWhileFetching:i}#z(e,t,n,r){const i=void 0===t?void 0:this.#S[t];if(this.#U(i))return i;const o=new oj,{signal:s}=n;s?.addEventListener("abort",()=>o.abort(s.reason),{signal:o.signal});const a={signal:o.signal,options:n,context:r},l=(r,i=!1)=>{const{aborted:s}=o.signal,l=n.ignoreFetchAbort&&void 0!==r;if(n.status&&(s&&!i?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,l&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),s&&!l&&!i)return u(o.signal.reason);const d=c;return this.#S[t]===c&&(void 0===r?void 0!==d.__staleWhileFetching?this.#S[t]=d.__staleWhileFetching:this.#V(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,a.options))),r},u=r=>{const{aborted:i}=o.signal,s=i&&n.allowStaleOnFetchAbort,a=s||n.allowStaleOnFetchRejection,l=a||n.noDeleteOnFetchRejection,u=c;if(this.#S[t]===c){!l||void 0===u.__staleWhileFetching?this.#V(e,"fetch"):s||(this.#S[t]=u.__staleWhileFetching)}if(a)return n.status&&void 0!==u.__staleWhileFetching&&(n.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw r};n.status&&(n.status.fetchDispatched=!0);const c=new Promise((t,r)=>{const s=this.#E?.(e,i,a);s&&s instanceof Promise&&s.then(e=>t(void 0===e?void 0:e),r),o.signal.addEventListener("abort",()=>{n.ignoreFetchAbort&&!n.allowStaleOnFetchAbort||(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))})}).then(l,e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e))),d=Object.assign(c,{__abortController:o,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,d,{...a.options,status:void 0}),t=this.#B.get(e)):this.#S[t]=d,d}#U(e){if(!this.#L)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof oj}async fetch(e,t={}){const{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:h,forceRefresh:g=!1,status:A,signal:m}=t;if(!this.#L)return A&&(A.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:A});const y={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:s,size:a,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:f,ignoreFetchAbort:p,status:A,signal:m};let b=this.#B.get(e);if(void 0===b){A&&(A.fetch="miss");const t=this.#z(e,b,y,h);return t.__returned=t}{const t=this.#S[b];if(this.#U(t)){const e=n&&void 0!==t.__staleWhileFetching;return A&&(A.fetch="inflight",e&&(A.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#q(b);if(!g&&!i)return A&&(A.fetch="hit"),this.#G(b),r&&this.#Y(b),A&&this.#X(A,b),t;const o=this.#z(e,b,y,h),s=void 0!==o.__staleWhileFetching&&n;return A&&(A.fetch=i?"stale":"refresh",s&&i&&(A.returnedStale=!0)),s?o.__staleWhileFetching:o.__returned=o}}async forceFetch(e,t={}){const n=await this.fetch(e,t);if(void 0===n)throw new Error("fetch() returned undefined");return n}memo(e,t={}){const n=this.#I;if(!n)throw new Error("no memoMethod provided to constructor");const{context:r,forceRefresh:i,...o}=t,s=this.get(e,o);if(!i&&void 0!==s)return s;const a=n(e,s,{options:o,context:r});return this.set(e,a,o),a}get(e,t={}){const{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:o}=t,s=this.#B.get(e);if(void 0!==s){const t=this.#S[s],a=this.#U(t);return o&&this.#X(o,s),this.#q(s)?(o&&(o.get="stale"),a?(o&&n&&void 0!==t.__staleWhileFetching&&(o.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#V(e,"expire"),o&&n&&(o.returnedStale=!0),n?t:void 0)):(o&&(o.get="hit"),a?t.__staleWhileFetching:(this.#G(s),r&&this.#Y(s),t))}o&&(o.get="miss")}#oe(e,t){this.#x[t]=e,this.#k[e]=t}#G(e){e!==this.#N&&(e===this.#Q?this.#Q=this.#k[e]:this.#oe(this.#x[e],this.#k[e]),this.#oe(this.#N,e),this.#N=e)}delete(e){return this.#V(e,"delete")}#V(e,t){let n=!1;if(0!==this.#C){const r=this.#B.get(e);if(void 0!==r)if(n=!0,1===this.#C)this.#se(t);else{this.#ee(r);const n=this.#S[r];if(this.#U(n)?n.__abortController.abort(new Error("deleted")):(this.#$||this.#P)&&(this.#$&&this.#y?.(n,e,t),this.#P&&this.#R?.push([n,e,t])),this.#B.delete(e),this.#D[r]=void 0,this.#S[r]=void 0,r===this.#N)this.#N=this.#x[r];else if(r===this.#Q)this.#Q=this.#k[r];else{const e=this.#x[r];this.#k[e]=this.#k[r];const t=this.#k[r];this.#x[t]=this.#x[r]}this.#C--,this.#T.push(r)}}if(this.#P&&this.#R?.length){const e=this.#R;let t;for(;t=e?.shift();)this.#v?.(...t)}return n}clear(){return this.#se("delete")}#se(e){for(const t of this.#W({allowStale:!0})){const n=this.#S[t];if(this.#U(n))n.__abortController.abort(new Error("deleted"));else{const r=this.#D[t];this.#$&&this.#y?.(n,r,e),this.#P&&this.#R?.push([n,r,e])}}if(this.#B.clear(),this.#S.fill(void 0),this.#D.fill(void 0),this.#O&&this.#M&&(this.#O.fill(0),this.#M.fill(0)),this.#F&&this.#F.fill(0),this.#Q=0,this.#N=0,this.#T.length=0,this.#_=0,this.#C=0,this.#P&&this.#R){const e=this.#R;let t;for(;t=e?.shift();)this.#v?.(...t)}}}const pj="object"==typeof process&&process?process:{stdout:null,stderr:null},fj=e=>!!e&&"object"==typeof e&&(e instanceof Vj||e instanceof Ee||hj(e)||gj(e)),hj=e=>!!e&&"object"==typeof e&&e instanceof a&&"function"==typeof e.pipe&&e.pipe!==Ee.Writable.prototype.pipe,gj=e=>!!e&&"object"==typeof e&&e instanceof a&&"function"==typeof e.write&&"function"==typeof e.end,Aj=Symbol("EOF"),mj=Symbol("maybeEmitEnd"),yj=Symbol("emittedEnd"),bj=Symbol("emittingEnd"),vj=Symbol("emittedError"),Ej=Symbol("closed"),Ij=Symbol("read"),wj=Symbol("flush"),Cj=Symbol("flushChunk"),_j=Symbol("encoding"),Bj=Symbol("decoder"),Dj=Symbol("flowing"),Sj=Symbol("paused"),kj=Symbol("resume"),xj=Symbol("buffer"),Qj=Symbol("pipes"),Nj=Symbol("bufferLength"),Tj=Symbol("bufferPush"),Rj=Symbol("bufferShift"),Fj=Symbol("objectMode"),Mj=Symbol("destroyed"),Oj=Symbol("error"),$j=Symbol("emitData"),Lj=Symbol("emitEnd"),Pj=Symbol("emitEnd2"),jj=Symbol("async"),Uj=Symbol("abort"),zj=Symbol("aborted"),Gj=Symbol("signal"),Hj=Symbol("dataListeners"),Wj=Symbol("discarded"),qj=e=>Promise.resolve().then(e),Jj=e=>e();class Kj{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[kj](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}}class Zj extends Kj{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=e=>t.emit("error",e),e.on("error",this.proxyErrors)}}class Vj extends a{[Dj]=!1;[Sj]=!1;[Qj]=[];[xj]=[];[Fj];[_j];[jj];[Bj];[Aj]=!1;[yj]=!1;[bj]=!1;[Ej]=!1;[vj]=null;[Nj]=0;[Mj]=!1;[Gj];[zj]=!1;[Hj]=0;[Wj]=!1;writable=!0;readable=!0;constructor(...e){const t=e[0]||{};if(super(),t.objectMode&&"string"==typeof t.encoding)throw new TypeError("Encoding and objectMode may not be used together");t.objectMode?(this[Fj]=!0,this[_j]=null):(e=>!e.objectMode&&!!e.encoding&&"buffer"!==e.encoding)(t)?(this[_j]=t.encoding,this[Fj]=!1):(this[Fj]=!1,this[_j]=null),this[jj]=!!t.async,this[Bj]=this[_j]?new Ce(this[_j]):null,t&&!0===t.debugExposeBuffer&&Object.defineProperty(this,"buffer",{get:()=>this[xj]}),t&&!0===t.debugExposePipes&&Object.defineProperty(this,"pipes",{get:()=>this[Qj]});const{signal:n}=t;n&&(this[Gj]=n,n.aborted?this[Uj]():n.addEventListener("abort",()=>this[Uj]()))}get bufferLength(){return this[Nj]}get encoding(){return this[_j]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Fj]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[jj]}set async(e){this[jj]=this[jj]||!!e}[Uj](){this[zj]=!0,this.emit("abort",this[Gj]?.reason),this.destroy(this[Gj]?.reason)}get aborted(){return this[zj]}set aborted(e){}write(e,t,n){if(this[zj])return!1;if(this[Aj])throw new Error("write after end");if(this[Mj])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;"function"==typeof t&&(n=t,t="utf8"),t||(t="utf8");const r=this[jj]?qj:Jj;if(!this[Fj]&&!Buffer.isBuffer(e))if(i=e,!Buffer.isBuffer(i)&&ArrayBuffer.isView(i))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if((e=>e instanceof ArrayBuffer||!!e&&"object"==typeof e&&e.constructor&&"ArrayBuffer"===e.constructor.name&&e.byteLength>=0)(e))e=Buffer.from(e);else if("string"!=typeof e)throw new Error("Non-contiguous data written to non-objectMode stream");var i;return this[Fj]?(this[Dj]&&0!==this[Nj]&&this[wj](!0),this[Dj]?this.emit("data",e):this[Tj](e),0!==this[Nj]&&this.emit("readable"),n&&r(n),this[Dj]):e.length?("string"!=typeof e||t===this[_j]&&!this[Bj]?.lastNeed||(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[_j]&&(e=this[Bj].write(e)),this[Dj]&&0!==this[Nj]&&this[wj](!0),this[Dj]?this.emit("data",e):this[Tj](e),0!==this[Nj]&&this.emit("readable"),n&&r(n),this[Dj]):(0!==this[Nj]&&this.emit("readable"),n&&r(n),this[Dj])}read(e){if(this[Mj])return null;if(this[Wj]=!1,0===this[Nj]||0===e||e&&e>this[Nj])return this[mj](),null;this[Fj]&&(e=null),this[xj].length>1&&!this[Fj]&&(this[xj]=[this[_j]?this[xj].join(""):Buffer.concat(this[xj],this[Nj])]);const t=this[Ij](e||null,this[xj][0]);return this[mj](),t}[Ij](e,t){if(this[Fj])this[Rj]();else{const n=t;e===n.length||null===e?this[Rj]():"string"==typeof n?(this[xj][0]=n.slice(e),t=n.slice(0,e),this[Nj]-=e):(this[xj][0]=n.subarray(e),t=n.subarray(0,e),this[Nj]-=e)}return this.emit("data",t),this[xj].length||this[Aj]||this.emit("drain"),t}end(e,t,n){return"function"==typeof e&&(n=e,e=void 0),"function"==typeof t&&(n=t,t="utf8"),void 0!==e&&this.write(e,t),n&&this.once("end",n),this[Aj]=!0,this.writable=!1,!this[Dj]&&this[Sj]||this[mj](),this}[kj](){this[Mj]||(this[Hj]||this[Qj].length||(this[Wj]=!0),this[Sj]=!1,this[Dj]=!0,this.emit("resume"),this[xj].length?this[wj]():this[Aj]?this[mj]():this.emit("drain"))}resume(){return this[kj]()}pause(){this[Dj]=!1,this[Sj]=!0,this[Wj]=!1}get destroyed(){return this[Mj]}get flowing(){return this[Dj]}get paused(){return this[Sj]}[Tj](e){this[Fj]?this[Nj]+=1:this[Nj]+=e.length,this[xj].push(e)}[Rj](){return this[Fj]?this[Nj]-=1:this[Nj]-=this[xj][0].length,this[xj].shift()}[wj](e=!1){do{}while(this[Cj](this[Rj]())&&this[xj].length);e||this[xj].length||this[Aj]||this.emit("drain")}[Cj](e){return this.emit("data",e),this[Dj]}pipe(e,t){if(this[Mj])return e;this[Wj]=!1;const n=this[yj];return t=t||{},e===pj.stdout||e===pj.stderr?t.end=!1:t.end=!1!==t.end,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[Qj].push(t.proxyErrors?new Zj(this,e,t):new Kj(this,e,t)),this[jj]?qj(()=>this[kj]()):this[kj]()),e}unpipe(e){const t=this[Qj].find(t=>t.dest===e);t&&(1===this[Qj].length?(this[Dj]&&0===this[Hj]&&(this[Dj]=!1),this[Qj]=[]):this[Qj].splice(this[Qj].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){const n=super.on(e,t);if("data"===e)this[Wj]=!1,this[Hj]++,this[Qj].length||this[Dj]||this[kj]();else if("readable"===e&&0!==this[Nj])super.emit("readable");else if((e=>"end"===e||"finish"===e||"prefinish"===e)(e)&&this[yj])super.emit(e),this.removeAllListeners(e);else if("error"===e&&this[vj]){const e=t;this[jj]?qj(()=>e.call(this,this[vj])):e.call(this,this[vj])}return n}removeListener(e,t){return this.off(e,t)}off(e,t){const n=super.off(e,t);return"data"===e&&(this[Hj]=this.listeners("data").length,0!==this[Hj]||this[Wj]||this[Qj].length||(this[Dj]=!1)),n}removeAllListeners(e){const t=super.removeAllListeners(e);return"data"!==e&&void 0!==e||(this[Hj]=0,this[Wj]||this[Qj].length||(this[Dj]=!1)),t}get emittedEnd(){return this[yj]}[mj](){this[bj]||this[yj]||this[Mj]||0!==this[xj].length||!this[Aj]||(this[bj]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ej]&&this.emit("close"),this[bj]=!1)}emit(e,...t){const n=t[0];if("error"!==e&&"close"!==e&&e!==Mj&&this[Mj])return!1;if("data"===e)return!(!this[Fj]&&!n)&&(this[jj]?(qj(()=>this[$j](n)),!0):this[$j](n));if("end"===e)return this[Lj]();if("close"===e){if(this[Ej]=!0,!this[yj]&&!this[Mj])return!1;const e=super.emit("close");return this.removeAllListeners("close"),e}if("error"===e){this[vj]=n,super.emit(Oj,n);const e=!(this[Gj]&&!this.listeners("error").length)&&super.emit("error",n);return this[mj](),e}if("resume"===e){const e=super.emit("resume");return this[mj](),e}if("finish"===e||"prefinish"===e){const t=super.emit(e);return this.removeAllListeners(e),t}const r=super.emit(e,...t);return this[mj](),r}[$j](e){for(const n of this[Qj])!1===n.dest.write(e)&&this.pause();const t=!this[Wj]&&super.emit("data",e);return this[mj](),t}[Lj](){return!this[yj]&&(this[yj]=!0,this.readable=!1,this[jj]?(qj(()=>this[Pj]()),!0):this[Pj]())}[Pj](){if(this[Bj]){const e=this[Bj].end();if(e){for(const t of this[Qj])t.dest.write(e);this[Wj]||super.emit("data",e)}}for(const t of this[Qj])t.end();const e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){const e=Object.assign([],{dataLength:0});this[Fj]||(e.dataLength=0);const t=this.promise();return this.on("data",t=>{e.push(t),this[Fj]||(e.dataLength+=t.length)}),await t,e}async concat(){if(this[Fj])throw new Error("cannot concat in objectMode");const e=await this.collect();return this[_j]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Mj,()=>t(new Error("stream destroyed"))),this.on("error",e=>t(e)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Wj]=!1;let e=!1;const t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();const n=this.read();if(null!==n)return Promise.resolve({done:!1,value:n});if(this[Aj])return t();let r,i;const o=e=>{this.off("data",s),this.off("end",a),this.off(Mj,l),t(),i(e)},s=e=>{this.off("error",o),this.off("end",a),this.off(Mj,l),this.pause(),r({value:e,done:!!this[Aj]})},a=()=>{this.off("error",o),this.off("data",s),this.off(Mj,l),t(),r({done:!0,value:void 0})},l=()=>o(new Error("stream destroyed"));return new Promise((e,t)=>{i=t,r=e,this.once(Mj,l),this.once("error",o),this.once("end",a),this.once("data",s)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Wj]=!1;let e=!1;const t=()=>(this.pause(),this.off(Oj,t),this.off(Mj,t),this.off("end",t),e=!0,{done:!0,value:void 0});return this.once("end",t),this.once(Oj,t),this.once(Mj,t),{next:()=>{if(e)return t();const n=this.read();return null===n?t():{done:!1,value:n}},throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[Mj])return e?this.emit("error",e):this.emit(Mj),this;this[Mj]=!0,this[Wj]=!0,this[xj].length=0,this[Nj]=0;return"function"!=typeof this.close||this[Ej]||this.close(),e?this.emit("error",e):this.emit(Mj),this}static get isStream(){return fj}}const Yj={lstatSync:ie,readdir:re,readdirSync:ne,readlinkSync:te,realpathSync:ee.native,promises:{lstat:O,readdir:M,readlink:F,realpath:R}},Xj=e=>e&&e!==Yj&&e!==l?{...Yj,...e,promises:{...Yj.promises,...e.promises||{}}}:Yj,eU=/^\\\\\?\\([a-z]:)\\?$/i,tU=/[\\\/]/,nU=10,rU=15,iU=-16,oU=128,sU=256,aU=512,lU=e=>e.isFile()?8:e.isDirectory()?4:e.isSymbolicLink()?nU:e.isCharacterDevice()?2:e.isBlockDevice()?6:e.isSocket()?12:e.isFIFO()?1:0,uU=new Map,cU=e=>{const t=uU.get(e);if(t)return t;const n=e.normalize("NFKD");return uU.set(e,n),n},dU=new Map,pU=e=>{const t=dU.get(e);if(t)return t;const n=cU(e.toLowerCase());return dU.set(e,n),n};class fU extends dj{constructor(){super({max:256})}}class hU extends dj{constructor(e=16384){super({maxSize:e,sizeCalculation:e=>e.length+1})}}const gU=Symbol("PathScurry setAsCwd");class AU{name;root;roots;parent;nocase;isCWD=!1;#ae;#le;get dev(){return this.#le}#ue;get mode(){return this.#ue}#ce;get nlink(){return this.#ce}#de;get uid(){return this.#de}#pe;get gid(){return this.#pe}#fe;get rdev(){return this.#fe}#he;get blksize(){return this.#he}#ge;get ino(){return this.#ge}#C;get size(){return this.#C}#Ae;get blocks(){return this.#Ae}#me;get atimeMs(){return this.#me}#ye;get mtimeMs(){return this.#ye}#be;get ctimeMs(){return this.#be}#ve;get birthtimeMs(){return this.#ve}#Ee;get atime(){return this.#Ee}#Ie;get mtime(){return this.#Ie}#we;get ctime(){return this.#we}#Ce;get birthtime(){return this.#Ce}#_e;#Be;#De;#Se;#ke;#xe;#Qe;#Ne;#Te;#Re;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=0,n,r,i,o,s){this.name=e,this.#_e=i?pU(e):cU(e),this.#Qe=1023&t,this.nocase=i,this.roots=r,this.root=n||this,this.#Ne=o,this.#De=s.fullpath,this.#ke=s.relative,this.#xe=s.relativePosix,this.parent=s.parent,this.parent?this.#ae=this.parent.#ae:this.#ae=Xj(s.fs)}depth(){return void 0!==this.#Be?this.#Be:this.parent?this.#Be=this.parent.depth()+1:this.#Be=0}childrenCache(){return this.#Ne}resolve(e){if(!e)return this;const t=this.getRootString(e),n=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#Fe(n):this.#Fe(n)}#Fe(e){let t=this;for(const n of e)t=t.child(n);return t}children(){const e=this.#Ne.get(this);if(e)return e;const t=Object.assign([],{provisional:0});return this.#Ne.set(this,t),this.#Qe&=-17,t}child(e,t){if(""===e||"."===e)return this;if(".."===e)return this.parent||this;const n=this.children(),r=this.nocase?pU(e):cU(e);for(const a of n)if(a.#_e===r)return a;const i=this.parent?this.sep:"",o=this.#De?this.#De+i+e:void 0,s=this.newChild(e,0,{...t,parent:this,fullpath:o});return this.canReaddir()||(s.#Qe|=oU),n.push(s),s}relative(){if(this.isCWD)return"";if(void 0!==this.#ke)return this.#ke;const e=this.name,t=this.parent;if(!t)return this.#ke=this.name;const n=t.relative();return n+(n&&t.parent?this.sep:"")+e}relativePosix(){if("/"===this.sep)return this.relative();if(this.isCWD)return"";if(void 0!==this.#xe)return this.#xe;const e=this.name,t=this.parent;if(!t)return this.#xe=this.fullpathPosix();const n=t.relativePosix();return n+(n&&t.parent?"/":"")+e}fullpath(){if(void 0!==this.#De)return this.#De;const e=this.name,t=this.parent;if(!t)return this.#De=this.name;const n=t.fullpath()+(t.parent?this.sep:"")+e;return this.#De=n}fullpathPosix(){if(void 0!==this.#Se)return this.#Se;if("/"===this.sep)return this.#Se=this.fullpath();if(!this.parent){const e=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(e)?this.#Se=`//?/${e}`:this.#Se=e}const e=this.parent,t=e.fullpathPosix(),n=t+(t&&e.parent?"/":"")+this.name;return this.#Se=n}isUnknown(){return 0===(this.#Qe&rU)}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return 8===(this.#Qe&rU)}isDirectory(){return 4===(this.#Qe&rU)}isCharacterDevice(){return 2===(this.#Qe&rU)}isBlockDevice(){return 6===(this.#Qe&rU)}isFIFO(){return 1===(this.#Qe&rU)}isSocket(){return 12===(this.#Qe&rU)}isSymbolicLink(){return(this.#Qe&nU)===nU}lstatCached(){return 32&this.#Qe?this:void 0}readlinkCached(){return this.#Te}realpathCached(){return this.#Re}readdirCached(){const e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#Te)return!0;if(!this.parent)return!1;const e=this.#Qe&rU;return!(0!==e&&e!==nU||this.#Qe&sU||this.#Qe&oU)}calledReaddir(){return!!(16&this.#Qe)}isENOENT(){return!!(this.#Qe&oU)}isNamed(e){return this.nocase?this.#_e===pU(e):this.#_e===cU(e)}async readlink(){const e=this.#Te;if(e)return e;if(this.canReadlink()&&this.parent)try{const e=await this.#ae.promises.readlink(this.fullpath()),t=(await this.parent.realpath())?.resolve(e);if(t)return this.#Te=t}catch(t){return void this.#Me(t.code)}}readlinkSync(){const e=this.#Te;if(e)return e;if(this.canReadlink()&&this.parent)try{const e=this.#ae.readlinkSync(this.fullpath()),t=this.parent.realpathSync()?.resolve(e);if(t)return this.#Te=t}catch(t){return void this.#Me(t.code)}}#Oe(e){this.#Qe|=16;for(let t=e.provisional;t<e.length;t++){const n=e[t];n&&n.#$e()}}#$e(){this.#Qe&oU||(this.#Qe=(this.#Qe|oU)&iU,this.#Le())}#Le(){const e=this.children();e.provisional=0;for(const t of e)t.#$e()}#Pe(){this.#Qe|=aU,this.#je()}#je(){if(64&this.#Qe)return;let e=this.#Qe;4===(e&rU)&&(e&=iU),this.#Qe=64|e,this.#Le()}#Ue(e=""){"ENOTDIR"===e||"EPERM"===e?this.#je():"ENOENT"===e?this.#$e():this.children().provisional=0}#ze(e=""){if("ENOTDIR"===e){this.parent.#je()}else"ENOENT"===e&&this.#$e()}#Me(e=""){let t=this.#Qe;t|=sU,"ENOENT"===e&&(t|=oU),"EINVAL"!==e&&"UNKNOWN"!==e||(t&=iU),this.#Qe=t,"ENOTDIR"===e&&this.parent&&this.parent.#je()}#Ge(e,t){return this.#He(e,t)||this.#We(e,t)}#We(e,t){const n=lU(e),r=this.newChild(e.name,n,{parent:this}),i=r.#Qe&rU;return 4!==i&&i!==nU&&0!==i&&(r.#Qe|=64),t.unshift(r),t.provisional++,r}#He(e,t){for(let n=t.provisional;n<t.length;n++){const r=t[n];if((this.nocase?pU(e.name):cU(e.name))===r.#_e)return this.#qe(e,r,n,t)}}#qe(e,t,n,r){const i=t.name;return t.#Qe=t.#Qe&iU|lU(e),i!==e.name&&(t.name=e.name),n!==r.provisional&&(n===r.length-1?r.pop():r.splice(n,1),r.unshift(t)),r.provisional++,t}async lstat(){if(0===(this.#Qe&oU))try{return this.#Je(await this.#ae.promises.lstat(this.fullpath())),this}catch(e){this.#ze(e.code)}}lstatSync(){if(0===(this.#Qe&oU))try{return this.#Je(this.#ae.lstatSync(this.fullpath())),this}catch(e){this.#ze(e.code)}}#Je(e){const{atime:t,atimeMs:n,birthtime:r,birthtimeMs:i,blksize:o,blocks:s,ctime:a,ctimeMs:l,dev:u,gid:c,ino:d,mode:p,mtime:f,mtimeMs:h,nlink:g,rdev:A,size:m,uid:y}=e;this.#Ee=t,this.#me=n,this.#Ce=r,this.#ve=i,this.#he=o,this.#Ae=s,this.#we=a,this.#be=l,this.#le=u,this.#pe=c,this.#ge=d,this.#ue=p,this.#Ie=f,this.#ye=h,this.#ce=g,this.#fe=A,this.#C=m,this.#de=y;const b=lU(e);this.#Qe=this.#Qe&iU|b|32,0!==b&&4!==b&&b!==nU&&(this.#Qe|=64)}#Ke=[];#Ze=!1;#Ve(e){this.#Ze=!1;const t=this.#Ke.slice();this.#Ke.length=0,t.forEach(t=>t(null,e))}readdirCB(e,t=!1){if(!this.canReaddir())return void(t?e(null,[]):queueMicrotask(()=>e(null,[])));const n=this.children();if(this.calledReaddir()){const r=n.slice(0,n.provisional);return void(t?e(null,r):queueMicrotask(()=>e(null,r)))}if(this.#Ke.push(e),this.#Ze)return;this.#Ze=!0;const r=this.fullpath();this.#ae.readdir(r,{withFileTypes:!0},(e,t)=>{if(e)this.#Ue(e.code),n.provisional=0;else{for(const e of t)this.#Ge(e,n);this.#Oe(n)}this.#Ve(n.slice(0,n.provisional))})}#Ye;async readdir(){if(!this.canReaddir())return[];const e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);const t=this.fullpath();if(this.#Ye)await this.#Ye;else{let r=()=>{};this.#Ye=new Promise(e=>r=e);try{for(const n of await this.#ae.promises.readdir(t,{withFileTypes:!0}))this.#Ge(n,e);this.#Oe(e)}catch(n){this.#Ue(n.code),e.provisional=0}this.#Ye=void 0,r()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];const e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);const t=this.fullpath();try{for(const n of this.#ae.readdirSync(t,{withFileTypes:!0}))this.#Ge(n,e);this.#Oe(e)}catch(n){this.#Ue(n.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(704&this.#Qe)return!1;const e=rU&this.#Qe;return 0===e||4===e||e===nU}shouldWalk(e,t){return!(4&~this.#Qe)&&!(704&this.#Qe)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#Re)return this.#Re;if(!(896&this.#Qe))try{const e=await this.#ae.promises.realpath(this.fullpath());return this.#Re=this.resolve(e)}catch(e){this.#Pe()}}realpathSync(){if(this.#Re)return this.#Re;if(!(896&this.#Qe))try{const e=this.#ae.realpathSync(this.fullpath());return this.#Re=this.resolve(e)}catch(e){this.#Pe()}}[gU](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;const t=new Set([]);let n=[],r=this;for(;r&&r.parent;)t.add(r),r.#ke=n.join(this.sep),r.#xe=n.join("/"),r=r.parent,n.push("..");for(r=e;r&&r.parent&&!t.has(r);)r.#ke=void 0,r.#xe=void 0,r=r.parent}}class mU extends AU{sep="\\";splitSep=tU;constructor(e,t=0,n,r,i,o,s){super(e,t,n,r,i,o,s)}newChild(e,t=0,n={}){return new mU(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return E.parse(e).root}getRoot(e){if((e=(e=>e.replace(/\//g,"\\").replace(eU,"$1\\"))(e.toUpperCase()))===this.root.name)return this.root;for(const[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new vU(e,this).root}sameRoot(e,t=this.root.name){return(e=e.toUpperCase().replace(/\//g,"\\").replace(eU,"$1\\"))===t}}class yU extends AU{splitSep="/";sep="/";constructor(e,t=0,n,r,i,o,s){super(e,t,n,r,i,o,s)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=0,n={}){return new yU(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}}class bU{root;rootPath;roots;cwd;#Xe;#et;#Ne;nocase;#ae;constructor(e=process.cwd(),t,n,{nocase:r,childrenCacheSize:i=16384,fs:o=Yj}={}){this.#ae=Xj(o),(e instanceof URL||e.startsWith("file://"))&&(e=B(e));const s=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(s),this.#Xe=new fU,this.#et=new fU,this.#Ne=new hU(i);const a=s.substring(this.rootPath.length).split(n);if(1!==a.length||a[0]||a.pop(),void 0===r)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=r,this.root=this.newRoot(this.#ae),this.roots[this.rootPath]=this.root;let l=this.root,u=a.length-1;const c=t.sep;let d=this.rootPath,p=!1;for(const f of a){const e=u--;l=l.child(f,{relative:new Array(e).fill("..").join(c),relativePosix:new Array(e).fill("..").join("/"),fullpath:d+=(p?"":c)+f}),p=!0}this.cwd=l}depth(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#Ne}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){const n=e[i];if(n&&"."!==n&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}const n=this.#Xe.get(t);if(void 0!==n)return n;const r=this.cwd.resolve(t).fullpath();return this.#Xe.set(t,r),r}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){const n=e[i];if(n&&"."!==n&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}const n=this.#et.get(t);if(void 0!==n)return n;const r=this.cwd.resolve(t).fullpathPosix();return this.#et.set(t,r),r}relative(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n}=t;if(e.canReaddir()){const t=await e.readdir();return n?t:t.map(e=>e.name)}return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0}=t;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(e=>e.name):[]}async lstat(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e.withFileTypes,e=this.cwd);const n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e.withFileTypes,e=this.cwd);const n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e.withFileTypes,e=this.cwd);const n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e.withFileTypes,e=this.cwd);const n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t,s=[];i&&!i(e)||s.push(n?e:e.fullpath());const a=new Set,l=(e,t)=>{a.add(e),e.readdirCB((e,u)=>{if(e)return t(e);let c=u.length;if(!c)return t();const d=()=>{0===--c&&t()};for(const t of u)i&&!i(t)||s.push(n?t:t.fullpath()),r&&t.isSymbolicLink()?t.realpath().then(e=>e?.isUnknown()?e.lstat():e).then(e=>e?.shouldWalk(a,o)?l(e,d):d()):t.shouldWalk(a,o)?l(t,d):d()},!0)},u=e;return new Promise((e,t)=>{l(u,n=>{if(n)return t(n);e(s)})})}walkSync(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t,s=[];i&&!i(e)||s.push(n?e:e.fullpath());const a=new Set([e]);for(const l of a){const e=l.readdirSync();for(const t of e){i&&!i(t)||s.push(n?t:t.fullpath());let e=t;if(t.isSymbolicLink()){if(!r||!(e=t.realpathSync()))continue;e.isUnknown()&&e.lstatSync()}e.shouldWalk(a,o)&&a.add(e)}}return s}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t;i&&!i(e)||(yield n?e:e.fullpath());const s=new Set([e]);for(const a of s){const e=a.readdirSync();for(const t of e){i&&!i(t)||(yield n?t:t.fullpath());let e=t;if(t.isSymbolicLink()){if(!r||!(e=t.realpathSync()))continue;e.isUnknown()&&e.lstatSync()}e.shouldWalk(s,o)&&s.add(e)}}}stream(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t,s=new Vj({objectMode:!0});i&&!i(e)||s.write(n?e:e.fullpath());const a=new Set,l=[e];let u=0;const c=()=>{let e=!1;for(;!e;){const t=l.shift();if(!t)return void(0===u&&s.end());u++,a.add(t);const d=(t,f,h=!1)=>{if(t)return s.emit("error",t);if(r&&!h){const e=[];for(const t of f)t.isSymbolicLink()&&e.push(t.realpath().then(e=>e?.isUnknown()?e.lstat():e));if(e.length)return void Promise.all(e).then(()=>d(null,f,!0))}for(const r of f)!r||i&&!i(r)||s.write(n?r:r.fullpath())||(e=!0);u--;for(const e of f){const t=e.realpathCached()||e;t.shouldWalk(a,o)&&l.push(t)}e&&!s.flowing?s.once("drain",c):p||c()};let p=!0;t.readdirCB(d,!0),p=!1}};return c(),s}streamSync(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t,s=new Vj({objectMode:!0}),a=new Set;i&&!i(e)||s.write(n?e:e.fullpath());const l=[e];let u=0;const c=()=>{let e=!1;for(;!e;){const t=l.shift();if(!t)return void(0===u&&s.end());u++,a.add(t);const c=t.readdirSync();for(const r of c)i&&!i(r)||s.write(n?r:r.fullpath())||(e=!0);u--;for(const e of c){let t=e;if(e.isSymbolicLink()){if(!r||!(t=e.realpathSync()))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(a,o)&&l.push(t)}}e&&!s.flowing&&s.once("drain",c)};return c(),s}chdir(e=this.cwd){const t=this.cwd;this.cwd="string"==typeof e?this.cwd.resolve(e):e,this.cwd[gU](t)}}class vU extends bU{sep="\\";constructor(e=process.cwd(),t={}){const{nocase:n=!0}=t;super(e,E,"\\",{...t,nocase:n}),this.nocase=n;for(let r=this.cwd;r;r=r.parent)r.nocase=this.nocase}parseRootPath(e){return E.parse(e).root.toUpperCase()}newRoot(e){return new mU(this.rootPath,4,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}}class EU extends bU{sep="/";constructor(e=process.cwd(),t={}){const{nocase:n=!1}=t;super(e,I,"/",{...t,nocase:n}),this.nocase=n}parseRootPath(e){return"/"}newRoot(e){return new yU(this.rootPath,4,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}}class IU extends EU{constructor(e=process.cwd(),t={}){const{nocase:n=!0}=t;super(e,{...t,nocase:n})}}process.platform;const wU="win32"===process.platform?vU:"darwin"===process.platform?IU:EU;class CU{#tt;#nt;#rt;length;#it;#ot;#st;#at;#lt;#ut;#ct=!0;constructor(e,t,n,r){if(!(e.length>=1))throw new TypeError("empty pattern list");if(!(t.length>=1))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#tt=e,this.#nt=t,this.#rt=n,this.#it=r,0===this.#rt)if(this.isUNC()){const[e,t,n,r,...i]=this.#tt,[o,s,a,l,...u]=this.#nt;""===i[0]&&(i.shift(),u.shift());const c=[e,t,n,r,""].join("/"),d=[o,s,a,l,""].join("/");this.#tt=[c,...i],this.#nt=[d,...u],this.length=this.#tt.length}else if(this.isDrive()||this.isAbsolute()){const[e,...t]=this.#tt,[n,...r]=this.#nt;""===t[0]&&(t.shift(),r.shift());const i=e+"/",o=n+"/";this.#tt=[i,...t],this.#nt=[o,...r],this.length=this.#tt.length}}pattern(){return this.#tt[this.#rt]}isString(){return"string"==typeof this.#tt[this.#rt]}isGlobstar(){return this.#tt[this.#rt]===ZP}isRegExp(){return this.#tt[this.#rt]instanceof RegExp}globString(){return this.#st=this.#st||(0===this.#rt?this.isAbsolute()?this.#nt[0]+this.#nt.slice(1).join("/"):this.#nt.join("/"):this.#nt.slice(this.#rt).join("/"))}hasMore(){return this.length>this.#rt+1}rest(){return void 0!==this.#ot?this.#ot:this.hasMore()?(this.#ot=new CU(this.#tt,this.#nt,this.#rt+1,this.#it),this.#ot.#ut=this.#ut,this.#ot.#lt=this.#lt,this.#ot.#at=this.#at,this.#ot):this.#ot=null}isUNC(){const e=this.#tt;return void 0!==this.#lt?this.#lt:this.#lt="win32"===this.#it&&0===this.#rt&&""===e[0]&&""===e[1]&&"string"==typeof e[2]&&!!e[2]&&"string"==typeof e[3]&&!!e[3]}isDrive(){const e=this.#tt;return void 0!==this.#at?this.#at:this.#at="win32"===this.#it&&0===this.#rt&&this.length>1&&"string"==typeof e[0]&&/^[a-z]:$/i.test(e[0])}isAbsolute(){const e=this.#tt;return void 0!==this.#ut?this.#ut:this.#ut=""===e[0]&&e.length>1||this.isDrive()||this.isUNC()}root(){const e=this.#tt[0];return"string"==typeof e&&this.isAbsolute()&&0===this.#rt?e:""}checkFollowGlobstar(){return!(0===this.#rt||!this.isGlobstar()||!this.#ct)}markFollowGlobstar(){return!(0===this.#rt||!this.isGlobstar()||!this.#ct)&&(this.#ct=!1,!0)}}const _U="object"==typeof process&&process&&"string"==typeof process.platform?process.platform:"linux";class BU{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:r,noglobstar:i,platform:o=_U}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:!0,nobrace:t,nocase:n,noext:r,noglobstar:i,optimizationLevel:2,platform:o,nocomment:!0,nonegate:!0};for(const s of e)this.add(s)}add(e){const t=new ej(e,this.mmopts);for(let n=0;n<t.set.length;n++){const e=t.set[n],r=t.globParts[n];if(!e||!r)throw new Error("invalid pattern object");for(;"."===e[0]&&"."===r[0];)e.shift(),r.shift();const i=new CU(e,r,0,this.platform),o=new ej(i.globString(),this.mmopts),s="**"===r[r.length-1],a=i.isAbsolute();a?this.absolute.push(o):this.relative.push(o),s&&(a?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(e){const t=e.fullpath(),n=`${t}/`,r=e.relative()||".",i=`${r}/`;for(const o of this.relative)if(o.match(r)||o.match(i))return!0;for(const o of this.absolute)if(o.match(t)||o.match(n))return!0;return!1}childrenIgnored(e){const t=e.fullpath()+"/",n=(e.relative()||".")+"/";for(const r of this.relativeChildren)if(r.match(n))return!0;for(const r of this.absoluteChildren)if(r.match(t))return!0;return!1}}class DU{store;constructor(e=new Map){this.store=e}copy(){return new DU(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){const n=e.fullpath(),r=this.store.get(n);r?r.add(t.globString()):this.store.set(n,new Set([t.globString()]))}}class SU{store=new Map;add(e,t,n){const r=(t?2:0)|(n?1:0),i=this.store.get(e);this.store.set(e,void 0===i?r:r&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(2&t),!!(1&t)])}}class kU{store=new Map;add(e,t){if(!e.canReaddir())return;const n=this.store.get(e);n?n.find(e=>e.globString()===t.globString())||n.push(t):this.store.set(e,[t])}get(e){const t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}}class xU{hasWalkedCache;matches=new SU;subwalks=new kU;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new DU}processPatterns(e,t){this.patterns=t;const n=t.map(t=>[e,t]);for(let[r,i]of n){this.hasWalkedCache.storeWalked(r,i);const e=i.root(),t=i.isAbsolute()&&!1!==this.opts.absolute;if(e){r=r.resolve("/"===e&&void 0!==this.opts.root?this.opts.root:e);const t=i.rest();if(!t){this.matches.add(r,!0,!1);continue}i=t}if(r.isENOENT())continue;let n,o,s=!1;for(;"string"==typeof(n=i.pattern())&&(o=i.rest());){const e=r.resolve(n);r=e,i=o,s=!0}if(n=i.pattern(),o=i.rest(),s){if(this.hasWalkedCache.hasWalked(r,i))continue;this.hasWalkedCache.storeWalked(r,i)}if("string"==typeof n){const e=".."===n||""===n||"."===n;this.matches.add(r.resolve(n),t,e);continue}if(n===ZP){(!r.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(r,i);const e=o?.pattern(),n=o?.rest();if(o&&(""!==e&&"."!==e||n)){if(".."===e){const e=r.parent||r;n?this.hasWalkedCache.hasWalked(e,n)||this.subwalks.add(e,n):this.matches.add(e,t,!0)}}else this.matches.add(r,t,""===e||"."===e)}else n instanceof RegExp&&this.subwalks.add(r,i)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new xU(this.opts,this.hasWalkedCache)}filterEntries(e,t){const n=this.subwalks.get(e),r=this.child();for(const i of t)for(const e of n){const t=e.isAbsolute(),n=e.pattern(),o=e.rest();n===ZP?r.testGlobstar(i,e,o,t):n instanceof RegExp?r.testRegExp(i,n,o,t):r.testString(i,n,o,t)}return r}testGlobstar(e,t,n,r){if(!this.dot&&e.name.startsWith(".")||(t.hasMore()||this.matches.add(e,r,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){const t=n.pattern();if("string"==typeof t&&".."!==t&&""!==t&&"."!==t)this.testString(e,t,n.rest(),r);else if(".."===t){const t=e.parent||e;this.subwalks.add(t,n)}else t instanceof RegExp&&this.testRegExp(e,t,n.rest(),r)}}testRegExp(e,t,n,r){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}testString(e,t,n,r){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}}class QU{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#dt=[];#pt;#ft;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#ft=n.posix||"win32"!==n.platform?"/":"\\",this.includeChildMatches=!1!==n.includeChildMatches,(n.ignore||!this.includeChildMatches)&&(this.#pt=((e,t)=>"string"==typeof e?new BU([e],t):Array.isArray(e)?new BU(e,t):e)(n.ignore??[],n),!this.includeChildMatches&&"function"!=typeof this.#pt.add)){throw new Error("cannot ignore child matches, ignore lacks add() method.")}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#dt.length=0}))}#ht(e){return this.seen.has(e)||!!this.#pt?.ignored?.(e)}#gt(e){return!!this.#pt?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;let e;for(this.paused=!1;!this.paused&&(e=this.#dt.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#dt.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}const r=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){const e=await r.realpath();e&&(e.isUnknown()||this.opts.stat)&&await e.lstat()}return this.matchCheckTest(r,t)}matchCheckTest(e,t){return!e||!(this.maxDepth===1/0||e.depth()<=this.maxDepth)||t&&!e.canReaddir()||this.opts.nodir&&e.isDirectory()||this.opts.nodir&&this.opts.follow&&e.isSymbolicLink()&&e.realpathCached()?.isDirectory()||this.#ht(e)?void 0:e}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}const r=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){const e=r.realpathSync();e&&(e?.isUnknown()||this.opts.stat)&&e.lstatSync()}return this.matchCheckTest(r,t)}matchFinish(e,t){if(this.#ht(e))return;if(!this.includeChildMatches&&this.#pt?.add){const t=`${e.relativePosix()}/**`;this.#pt.add(t)}const n=void 0===this.opts.absolute?t:this.opts.absolute;this.seen.add(e);const r=this.opts.mark&&e.isDirectory()?this.#ft:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){const t=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(t+r)}else{const t=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!t.startsWith(".."+this.#ft)?"."+this.#ft:"";this.matchEmit(t?n+t+r:"."+r)}}async match(e,t,n){const r=await this.matchCheck(e,n);r&&this.matchFinish(r,t)}matchSync(e,t,n){const r=this.matchCheckSync(e,n);r&&this.matchFinish(r,t)}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new xU(this.opts),n)}walkCB2(e,t,n,r){if(this.#gt(e))return r();if(this.signal?.aborted&&r(),this.paused)return void this.onResume(()=>this.walkCB2(e,t,n,r));n.processPatterns(e,t);let i=1;const o=()=>{0===--i&&r()};for(const[s,a,l]of n.matches.entries())this.#ht(s)||(i++,this.match(s,a,l).then(()=>o()));for(const s of n.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;const e=s.readdirCached();s.calledReaddir()?this.walkCB3(s,e,n,o):s.readdirCB((e,t)=>this.walkCB3(s,t,n,o),!0)}o()}walkCB3(e,t,n,r){n=n.filterEntries(e,t);let i=1;const o=()=>{0===--i&&r()};for(const[s,a,l]of n.matches.entries())this.#ht(s)||(i++,this.match(s,a,l).then(()=>o()));for(const[s,a]of n.subwalks.entries())i++,this.walkCB2(s,a,n.child(),o);o()}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new xU(this.opts),n)}walkCB2Sync(e,t,n,r){if(this.#gt(e))return r();if(this.signal?.aborted&&r(),this.paused)return void this.onResume(()=>this.walkCB2Sync(e,t,n,r));n.processPatterns(e,t);let i=1;const o=()=>{0===--i&&r()};for(const[s,a,l]of n.matches.entries())this.#ht(s)||this.matchSync(s,a,l);for(const s of n.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;const e=s.readdirSync();this.walkCB3Sync(s,e,n,o)}o()}walkCB3Sync(e,t,n,r){n=n.filterEntries(e,t);let i=1;const o=()=>{0===--i&&r()};for(const[s,a,l]of n.matches.entries())this.#ht(s)||this.matchSync(s,a,l);for(const[s,a]of n.subwalks.entries())i++,this.walkCB2Sync(s,a,n.child(),o);o()}}class NU extends QU{matches=new Set;constructor(e,t,n){super(e,t,n)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}}class TU extends QU{results;constructor(e,t,n){super(e,t,n),this.results=new Vj({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){const e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}}const RU="object"==typeof process&&process&&"string"==typeof process.platform?process.platform:"linux";class FU{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=B(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=!1!==t.includeChildMatches,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth="number"==typeof t.maxDepth?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&void 0!==this.absolute)throw new Error("cannot set absolute and withFileTypes:true");if("string"==typeof e&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||!1===t.allowWindowsEscape,this.windowsPathsNoEscape&&(e=e.map(e=>e.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(e=>e.includes("/")?e:`./**/${e}`)}if(this.pattern=e,this.platform=t.platform||RU,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,void 0!==t.nocase&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{const e="win32"===t.platform?vU:"darwin"===t.platform?IU:t.platform?EU:wU;this.scurry=new e(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;const n="darwin"===this.platform||"win32"===this.platform,r={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(e=>new ej(e,r)),[o,s]=i.reduce((e,t)=>(e[0].push(...t.set),e[1].push(...t.globParts),e),[[],[]]);this.patterns=o.map((e,t)=>{const n=s[t];if(!n)throw new Error("invalid pattern object");return new CU(e,n,0,this.platform)})}async walk(){return[...await new NU(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new NU(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new TU(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new TU(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}}function MU(e,t={}){return new FU(e,t).streamSync()}function OU(e,t={}){return new FU(e,t).stream()}function $U(e,t={}){return new FU(e,t).walkSync()}async function LU(e,t={}){return new FU(e,t).walk()}function PU(e,t={}){return new FU(e,t).iterateSync()}function jU(e,t={}){return new FU(e,t).iterate()}const UU=MU,zU=Object.assign(OU,{sync:MU}),GU=PU,HU=Object.assign(jU,{sync:PU}),WU=Object.assign($U,{stream:MU,iterate:PU}),qU=Object.assign(LU,{glob:LU,globSync:$U,sync:WU,globStream:OU,stream:zU,globStreamSync:MU,streamSync:UU,globIterate:jU,iterate:HU,globIterateSync:PU,iterateSync:GU,Glob:FU,hasMagic:(e,t={})=>{Array.isArray(e)||(e=[e]);for(const n of e)if(new ej(n,t).hasMagic())return!0;return!1},escape:DP,unescape:gP});async function JU(e){try{const t=se.join(e,".git");return(await _e.stat(t)).isDirectory()}catch{return!1}}async function KU(e){const t=await async function(e){let t=se.resolve(e);for(;;){const e=se.join(t,".git");try{if((await _e.stat(e)).isDirectory())return t}catch(qK){const n="object"==typeof qK&&null!==qK&&"code"in qK&&"ENOENT"===qK.code,r="test"===process.env.NODE_ENV||process.env.VITEST;n||r||ex.warn(`Unexpected error checking for .git directory at ${e}:`,qK)}const n=se.dirname(t);if(n===t)return null;t=n}}(e);return{projectRoot:t,isGitRepo:!!t&&await JU(t),workingDirectory:se.resolve(e)}}qU.glob=qU;class ZU{gitIgnorePatterns=[];embedderIgnorePatterns=[];projectRoot;static DEFAULT_IGNORE_PATTERNS=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/coverage/**","**/.nyc_output/**","**/tmp/**","**/temp/**","**/*.log","**/.DS_Store","**/Thumbs.db"];constructor(e){this.projectRoot=se.resolve(e),this.loadIgnorePatterns()}async loadIgnorePatterns(){try{await JU(this.projectRoot)&&await this.loadGitIgnorePatterns(),await this.loadEmbedderIgnorePatterns()}catch(qK){}}async loadGitIgnorePatterns(){try{const e=se.join(this.projectRoot,".gitignore"),t=await _e.readFile(e,"utf-8");this.gitIgnorePatterns=this.parseIgnoreFile(t)}catch{}}async loadEmbedderIgnorePatterns(){try{const e=se.join(this.projectRoot,".embedderignore"),t=await _e.readFile(e,"utf-8");this.embedderIgnorePatterns=this.parseIgnoreFile(t)}catch{}}parseIgnoreFile(e){return e.split("\n").map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.startsWith("**/")||e.startsWith("/")?e:`**/${e}`)}shouldIgnoreFile(e,t={}){const{respectGitIgnore:n=!0,respectEmbedderIgnore:r=!0}=t;return!!this.matchesPatterns(e,ZU.DEFAULT_IGNORE_PATTERNS)||(!(!n||!this.matchesPatterns(e,this.gitIgnorePatterns))||!(!r||!this.matchesPatterns(e,this.embedderIgnorePatterns)))}matchesPatterns(e,t){const n=se.normalize(e).replace(/\\/g,"/");return t.some(e=>{const t=e.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]");try{return new RegExp(`^${t}$`).test(n)}catch{return!1}})}filterFiles(e,t={}){return e.filter(e=>!this.shouldIgnoreFile(e,t))}getGitIgnorePatterns(){return[...this.gitIgnorePatterns]}getEmbedderIgnorePatterns(){return[...this.embedderIgnorePatterns]}}class VU{projectContext=null;contextCache=new Map;cacheExpiry=3e5;lastCacheUpdate=null;constructor(){}async getContextualSuggestions(e,t=20){const n=`contextual_${e}`;if(this.isCacheValid(n)){const e=this.contextCache.get(n);if(e)return e.slice(0,t)}this.projectContext=await KU(e);const r=new ZU(this.projectContext.projectRoot||e),i=[],o=await this.getCurrentDirectoryFiles(e,r);if(i.push(...o),this.projectContext.projectRoot&&this.projectContext.projectRoot!==e){const e=await this.getProjectRootFiles(r);i.push(...e)}const s=await this.getImportantProjectFiles(r);i.push(...s);const a=await this.getRecentlyModifiedFiles(e,r);i.push(...a);const l=this.deduplicateAndRank(i).slice(0,t);return this.contextCache.set(n,l),this.lastCacheUpdate=new Date,l}async getCurrentDirectoryFiles(e,t){const n=[];try{const r=await _e.readdir(e,{withFileTypes:!0});for(const i of r){if(i.name.startsWith("."))continue;const r=se.join(e,i.name),o=se.relative(e,r);if(!t.shouldIgnoreFile(o))try{const e=await _e.stat(r),t={path:r,relativePath:se.normalize(o),isDirectory:i.isDirectory(),lastModified:e.mtime,size:e.size,relevanceScore:this.calculateRelevanceScore(i.name,"current-directory"),contextReason:"Current directory"};n.push(t)}catch{continue}}}catch{}return n}async getProjectRootFiles(e){if(!this.projectContext?.projectRoot)return[];const t=[],n=["README.md","README.txt","package.json","tsconfig.json","Makefile","CMakeLists.txt",".gitignore","Cargo.toml","pom.xml","build.gradle","requirements.txt","Pipfile"];for(const r of n)try{const n=se.join(this.projectContext.projectRoot,r),i=await _e.stat(n),o=se.relative(this.projectContext.workingDirectory,n);if(e.shouldIgnoreFile(o))continue;const s={path:n,relativePath:se.normalize(o),isDirectory:!1,lastModified:i.mtime,size:i.size,relevanceScore:this.calculateRelevanceScore(r,"project-root"),contextReason:"Important project file"};t.push(s)}catch{}return t}async getImportantProjectFiles(e){if(!this.projectContext?.projectRoot)return[];const t=[],n=["src","lib","app","components","utils","services","config","docs","test","tests","__tests__"];for(const r of n)try{const n=se.join(this.projectContext.projectRoot,r);await _e.access(n);const i=se.relative(this.projectContext.workingDirectory,n);if(e.shouldIgnoreFile(i))continue;const o=await _e.stat(n),s={path:n,relativePath:se.normalize(i),isDirectory:!0,lastModified:o.mtime,size:o.size,relevanceScore:this.calculateRelevanceScore(r,"important-directory"),contextReason:"Important project directory"};t.push(s)}catch{}return t}async getRecentlyModifiedFiles(e,t,n=5){const r=[],i=new Date(Date.now()-864e5);try{const o=await this.findRecentFiles(e,t,i);o.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime());for(const e of o.slice(0,n)){const t={...e,relevanceScore:this.calculateRelevanceScore(se.basename(e.relativePath),"recently-modified"),contextReason:"Recently modified"};r.push(t)}}catch{}return r}async findRecentFiles(e,t,n,r=0,i=3){if(r>i)return[];const o=[];try{const s=await _e.readdir(e,{withFileTypes:!0});for(const a of s){const s=se.join(e,a.name),l=se.relative(this.projectContext?.workingDirectory||e,s);if(!t.shouldIgnoreFile(l))try{const e=await _e.stat(s);if(a.isFile()&&e.mtime>n)o.push({path:s,relativePath:se.normalize(l),isDirectory:!1,lastModified:e.mtime,size:e.size});else if(a.isDirectory()&&!a.name.startsWith(".")){const e=await this.findRecentFiles(s,t,n,r+1,i);o.push(...e)}}catch{continue}}}catch{}return o}calculateRelevanceScore(e,t){let n=50;switch(t){case"current-directory":n+=30;break;case"project-root":n+=25;break;case"important-directory":n+=20;break;case"recently-modified":n+=15}const r=e.toLowerCase();return(r.includes("config")||r.includes(".json")||r.includes("makefile")||r.includes(".toml"))&&(n+=15),(r.includes("readme")||r.includes(".md")||r.includes("doc"))&&(n+=10),(r.endsWith(".ts")||r.endsWith(".js")||r.endsWith(".tsx")||r.endsWith(".jsx")||r.endsWith(".py")||r.endsWith(".java")||r.endsWith(".c")||r.endsWith(".cpp"))&&(n+=10),"src"!==r&&"lib"!==r&&"app"!==r||(n+=15),n}deduplicateAndRank(e){const t=new Set,n=[];for(const r of e){const e=se.normalize(r.relativePath).toLowerCase();t.has(e)||(t.add(e),n.push(r))}return n.sort((e,t)=>t.relevanceScore-e.relevanceScore)}isCacheValid(e){if(!this.lastCacheUpdate||!this.contextCache.has(e))return!1;return(new Date).getTime()-this.lastCacheUpdate.getTime()<this.cacheExpiry}clearCache(){this.contextCache.clear(),this.lastCacheUpdate=null}getProjectContext(){return this.projectContext}}class YU{name="directory-listing";canHandle(e){return e.includes("/")||e.endsWith("/")}async search(e,t,n,r){const i=e,o=i.lastIndexOf("/"),s=-1===o?".":i.substring(0,o+1),a=-1===o?i:i.substring(o+1),l=se.resolve(t,s),u=a.toLowerCase();try{const e=await _e.readdir(l,{withFileTypes:!0}),i=[];for(const o of e){if(!a.startsWith(".")&&o.name.startsWith("."))continue;if(!o.name.toLowerCase().startsWith(u))continue;const e=se.join(l,o.name),s=se.relative(t,e);if(r.shouldIgnoreFile(s,{respectGitIgnore:n.respectGitIgnore,respectEmbedderIgnore:n.respectEmbedderIgnore}))continue;const c=await _e.stat(e);i.push({path:e,relativePath:se.normalize(s),isDirectory:o.isDirectory(),lastModified:c.mtime,size:c.size})}return i.slice(0,n.maxResults||50)}catch{return[]}}}class XU{name="recursive-search";canHandle(e){return e.length>0&&!e.includes("/")}async search(e,t,n,r){const i=n.maxDepth||10,o=n.maxResults||50;return this.findFilesRecursively(t,e,r,{respectGitIgnore:n.respectGitIgnore,respectEmbedderIgnore:n.respectEmbedderIgnore},"",0,i,o)}async findFilesRecursively(e,t,n,r,i="",o=0,s=10,a=50){if(o>s)return[];const l=t.toLowerCase();let u=[];try{const c=await _e.readdir(e,{withFileTypes:!0});for(const d of c){if(u.length>=a)break;const c=se.join(i,d.name),p=se.join(e,d.name);if((t.startsWith(".")||!d.name.startsWith("."))&&!n.shouldIgnoreFile(c,r)){if(d.name.toLowerCase().startsWith(l))try{const e=await _e.stat(p);u.push({path:p,relativePath:se.normalize(c),isDirectory:d.isDirectory(),lastModified:e.mtime,size:e.size})}catch{continue}if(d.isDirectory()&&"node_modules"!==d.name&&!d.name.startsWith(".")&&u.length<a){const e=await this.findFilesRecursively(p,t,n,r,c,o+1,s,a-u.length);u=u.concat(e)}}}}catch{}return u.slice(0,a)}}class ez{name="glob-search";canHandle(e){return e.length>0&&!e.includes("/")}async search(e,t,n,r){try{const i=`**/${e}*`,o=await qU(i,{cwd:t,dot:e.startsWith("."),nocase:!0,absolute:!1}),s=[],a=n.maxResults||50;for(const e of o.slice(0,a))if(!r.shouldIgnoreFile(e,{respectGitIgnore:n.respectGitIgnore,respectEmbedderIgnore:n.respectEmbedderIgnore})){try{const n=se.resolve(t,e),r=await _e.stat(n);s.push({path:n,relativePath:se.normalize(e),isDirectory:r.isDirectory(),lastModified:r.mtime,size:r.size})}catch{continue}if(s.length>=a)break}return s}catch{return[]}}}class tz{strategies=[new YU,new XU,new ez];contextService=new VU;async searchFiles(e,t,n={}){if(!e.trim())return this.getInitialSuggestions(t,n);const r=await KU(t),i=new ZU(r.projectRoot||t),o=this.strategies.find(t=>t.canHandle(e,r))||this.strategies[1];let s=[];if(o)s=await o.search(e,t,n,i);else if(this.strategies.length>0){const r=this.strategies[0];r&&(s=await r.search(e,t,n,i))}return this.sortResults(s,e)}async getInitialSuggestions(e,t){const n=t.maxResults||20;try{return(await this.contextService.getContextualSuggestions(e,n)).map(e=>({path:e.path,relativePath:e.relativePath,isDirectory:e.isDirectory,lastModified:e.lastModified,size:e.size}))}catch(qK){return ex.warn("Error getting contextual suggestions, falling back to simple listing:",qK),this.getFallbackInitialSuggestions(e,t)}}async getFallbackInitialSuggestions(e,t){const n=new ZU(e),r=t.maxResults||20;try{const i=await _e.readdir(e,{withFileTypes:!0}),o=[];for(const s of i){if(o.length>=r)break;if(s.name.startsWith("."))continue;const i=se.join(e,s.name);if(!n.shouldIgnoreFile(s.name,{respectGitIgnore:t.respectGitIgnore,respectEmbedderIgnore:t.respectEmbedderIgnore}))try{const e=await _e.stat(i);o.push({path:i,relativePath:se.normalize(s.name),isDirectory:s.isDirectory(),lastModified:e.mtime,size:e.size})}catch{continue}}return o.sort((e,t)=>e.isDirectory!==t.isDirectory?e.isDirectory?-1:1:e.relativePath.localeCompare(t.relativePath))}catch{return[]}}sortResults(e,t){const n=t.toLowerCase();return e.sort((e,t)=>{const r=(e.relativePath.match(/[/\\]/g)||[]).length,i=(t.relativePath.match(/[/\\]/g)||[]).length;if(r!==i)return r-i;if(e.isDirectory!==t.isDirectory)return e.isDirectory?-1:1;const o=se.basename(e.relativePath).toLowerCase(),s=se.basename(t.relativePath).toLowerCase(),a=o.includes(n);if(a!==s.includes(n))return a?-1:1;const l=se.basename(e.relativePath,se.extname(e.relativePath)),u=se.basename(t.relativePath,se.extname(t.relativePath)),c=l.localeCompare(u);return 0!==c?c:e.relativePath.localeCompare(t.relativePath)})}getContextService(){return this.contextService}}const nz=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/coverage/**","**/.nyc_output/**","**/tmp/**","**/temp/**","**/*.log","**/.DS_Store","**/Thumbs.db"],rz=kw((e,t)=>({files:[],isLoading:!1,lastScan:null,currentDirectory:null,advancedSearch:new tz,scanFiles:async n=>{const r=t();if(!(r.currentDirectory===n&&r.lastScan&&Date.now()-r.lastScan.getTime()<5e3)){e({isLoading:!0});try{const t="**/*",r=await qU(t,{cwd:n,ignore:nz,dot:!1,nodir:!1,absolute:!1}),i=[];for(const e of r)try{const t=se.join(n,e),r=await _e.stat(t);i.push({path:t,relativePath:e,isDirectory:r.isDirectory(),lastModified:r.mtime,size:r.size})}catch(qK){continue}i.sort((e,t)=>e.isDirectory!==t.isDirectory?e.isDirectory?-1:1:e.relativePath.localeCompare(t.relativePath)),e({files:i,isLoading:!1,lastScan:new Date,currentDirectory:n})}catch(qK){ex.error("Error scanning files:",qK),e({files:[],isLoading:!1,lastScan:new Date,currentDirectory:n})}}},searchFiles:async e=>{const{currentDirectory:n,advancedSearch:r}=t();if(!n)return[];try{return await r.searchFiles(e,n,{maxResults:50,maxDepth:10,respectGitIgnore:!0,respectEmbedderIgnore:!0,enableRecursiveSearch:!0})}catch(qK){return ex.error("Error in advanced file search:",qK),[]}},clearFiles:()=>{e({files:[],isLoading:!1,lastScan:null,currentDirectory:null})}}));const iz=kw((e,t)=>({queue:[],currentTool:null,status:"idle",enqueue:n=>{e(e=>({queue:[...e.queue,n]}));"idle"===t().status&&t().processNext()},dequeue:()=>{const n=t();if(0===n.queue.length)return null;const[r,...i]=n.queue;return r?(e({queue:i}),r):null},processNext:async()=>{if("idle"!==t().status)return;const n=t().dequeue();if(n){e({currentTool:n,status:"executing"});try{const e=await n.execute();n.resolve(e)}catch(qK){n.reject(qK instanceof Error?qK:new Error(String(qK)))}finally{e({status:"idle",currentTool:null}),setTimeout(()=>{t().processNext()},500)}}else e({status:"idle",currentTool:null})},clear:()=>{e({queue:[],currentTool:null,status:"idle"})},removeById:t=>{e(e=>({queue:e.queue.filter(e=>e.id!==t)}))},setStatus:t=>{e({status:t})},getCurrentTool:()=>t().currentTool,cancelAll:()=>{const n=t(),r=new Error("Tool execution cancelled due to CLI exit");n.queue.forEach(e=>{e.reject(r)}),n.currentTool&&n.currentTool.reject(r),e({queue:[],currentTool:null,status:"idle"})}}));let oz={};const sz=[{name:"clear",description:"Clear conversation history - Ctrl+R",aliases:["reset","new"],action:async()=>{if(oz.setMessages&&oz.clearActiveConversation&&oz.saveConversation){oz.setMessages(()=>[]),iz.getState().clear(),DM.getState().clearAll();try{await oz.clearActiveConversation()}catch(qK){ex.error("Failed to clear active conversation:",qK)}}}},{name:"resume",description:"Resume a conversation - Ctrl+O",action:()=>{oz.setIsResumeInterfaceOpen&&oz.setIsResumeInterfaceOpen(!0)}},{name:"model",description:"Select which AI model to use - Ctrl+B",action:async()=>{oz.setIsModelSelectorOpen&&oz.setIsModelSelectorOpen(!0)}},{name:"help",description:"Show available commands and shortcuts",aliases:["?","h"],action:async()=>{oz.setIsHelpOpen&&oz.setIsHelpOpen(!0)}},{name:"compress",description:"Compress conversation history to save context",aliases:["summarize"],action:async()=>{oz.compressConversation&&await oz.compressConversation()}},{name:"rewind",description:"View and revert to previous conversation states",action:async()=>{oz.setIsRewindInterfaceOpen&&oz.setIsRewindInterfaceOpen(!0)}},{name:"undo",description:"Undo the last query",action:async()=>{oz.performUndo&&await oz.performUndo()}},{name:"yolo",description:"Toggle auto-approval of all tool calls",action:async()=>{oz.toggleAutoApproval&&oz.toggleAutoApproval()}},{name:"project",description:"Switch to a different project or team",action:async()=>{oz.setProject&&oz.setPreviousProject&&oz.setTeam&&oz.setPreviousTeam&&oz.teams&&(oz.setPreviousProject(oz.project||null),oz.teams.length>1&&(oz.setPreviousTeam(oz.team||null),oz.setTeam(null)),oz.setProject(null))}},{name:"init",description:"Create EMBEDDER.md with project contexts",action:async()=>{if(oz.setMode&&oz.setMode("act"),oz.setAutoApproval&&oz.setAutoApproval(!0),oz.submitMessage){await oz.submitMessage("/init",{hidden:!1});const e="Please analyze this codebase and create an EMBEDDER.md file that contains all information specified in the format below.\n\nThe file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Follow this format:\n**EMBEDDER PROJECT CONTEXT**\n<OVERVIEW>\nName = MyProject\nTarget MCU = <chip or family>\nBoard = <board>\nToolchain = <toolchain>\nDebug Interface = <st-link|jlink|serial>\nRTOS / SDK = <freertos|zephyr|sdk>\nProject Summary = <one-line description>\n</OVERVIEW>\n\n<COMMANDS>\n# --- Build / Compile --------------------------------------------------------\nbuild_command = <shell command to build>\n\n# --- Flash ------------------------------------------------------------------\nflash_command = <shell command to flash>\n\n# --- Debug ------------------------------------------------------------------\ngdb_server_command = <optional, e.g., openocd ... or ST-LINK_gdbserver ...>\ngdb_server_host = localhost\ngdb_server_port = 61234\ngdb_client_command = arm-none-eabi-gdb\ntarget_connection = remote\n\n# --- Serial Monitor ----------------------------------------------------------\n# Option 1: For custom commands (waf, make, etc.)\n# serial_monitor_command = source .venv/bin/activate && ./waf console --tty /dev/ttyACM0\n# serial_monitor_interactive = true\n# serial_startup_commands = [reset]\n\n# Option 2: Direct port/baudrate (use {port} and {baud} placeholders)\nserial_port = /dev/ttyACM0\nserial_baudrate = 115200\nserial_monitor_command = tio {port} -b {baud}\nserial_monitor_interactive = false\nserial_encoding = ascii\nserial_startup_commands = []\n\n# Project Overview \nWrite a clear and concise summary of the project's purpose, main technologies, and architecture.\n\n# Bash Commands \nDocument all commands related to build and interactive with hardware, keep it short and concise.\n\n# Code style\ndocument all required formating and documentation conventions, keep it short and concise\n\n\nIf there are Cursor rules (in .cursor/rules/ or .cursorrules) or Copilot rules\n(in .github/copilot-instructions.md), make sure to include them.\n\nKeep all descriptions short and concise, never create any code or complete the project only create or edit embedder.md file.\n\nAfter you have finished making embedder.md Provide a recommendation of documents necessary to support this project i.e. if\nthe project is based on a development board, suggest including the datasheet and\napplication references. For the MCU used in the project, suggest including the\nrelevant datasheet and erratas. For the peripherals found in the drivers,\nsuggest including datasheets and application notes. When possible, provide links\nto these documents. \n\nIf there's already an EMBEDDER.md, improve it if it's located in /\n";await oz.submitMessage(e,{hidden:!0})}}},{name:"doc",description:"Upload hardware docs and datasheets to improve AI accuracy",aliases:["docs","documentation"],action:async()=>{const e=await Promise.resolve().then(()=>Cw);await e.default("https://app.embedder.dev")}},{name:"logout",description:"Sign out and return to login screen",aliases:["signout"],action:async()=>{if(oz.firebaseAuth&&oz.closeSession)try{await oz.closeSession(oz.messages,oz.project,oz.team,oz.model),await pT(null),await oz.firebaseAuth.signOut()}catch(qK){ex.error("Logout failed:",qK instanceof Error?qK.message:String(qK));try{await pT(null),await oz.firebaseAuth.signOut()}catch(e){ex.error("Failed to clear auth state:",e instanceof Error?e.message:String(e))}finally{oz.setFirebaseUser&&oz.setFirebaseUser(null),oz.setProjects&&oz.setProjects([]),oz.setTeams&&oz.setTeams([]),oz.setBackendUser&&oz.setBackendUser(null)}}}},{name:"exit",description:"Close the application",aliases:["quit"],action:async()=>{oz.exitApp&&oz.exitApp()}}];function az(e){return sz.find(t=>t.name===e||t.aliases?.includes(e))}function lz(e){return Array.from(e)}function uz(e){return lz(e).length}function cz(e,t,n){return lz(e).slice(t,n).join("")}function dz(e){return void 0!==e&&!/[\s,.;!?]/.test(e)}function pz(e){return HM(e)}function fz(e,t,n){return e<t?t:e>n?n:e}function hz(e,t){let n=0,r=0,i=0;if(0===t)return[0,0];const o=e.split("\n");for(let s=0;s<o.length;s++){const e=o[s];if(!e)continue;const a=uz(e),l=a+(s<o.length-1?1:0);if(t<=i+a)return n=s,r=t-i,[n,r];if(t<=i+l)return n=s,r=a,t===i+l&&s<o.length-1?[s+1,0]:[n,r];i+=l}if(o.length>0){n=o.length-1;const e=o[n];r=e?uz(e):0}else n=0,r=0;return[n,r]}function gz(e,t,n){const r=[],i=[],o=[];let s=[0,0];return e.forEach((e,a)=>{if(i[a]=[],0===e.length)i[a].push([r.length,0]),o.push([a,0]),r.push(""),a===t[0]&&0===t[1]&&(s=[r.length-1,0]);else{let l=0;const u=lz(e);for(;l<u.length;){let e="",c=0,d=0,p=-1,f=0;for(let t=l;t<u.length;t++){const r=u[t];if(!r)continue;const i=pz(r);if(c+i>n){-1!==p&&f>0&&l+f<t?(e=u.slice(l,l+f).join(""),d=f):0===d&&i>n&&(e=r??"",d=1);break}e+=r,c+=i,d++," "===r&&(p=t,f=d-1)}if(0===d&&l<u.length){e=u[l]??"",d=1}if(i[a].push([r.length,l]),o.push([a,l]),r.push(e),a===t[0]){const e=t[1];e>=l&&e<l+d?s=[r.length-1,e-l]:e===l+d&&d>0&&(s=[r.length-1,d])}l+=d,l<u.length&&" "===u[l]&&l++}if(a===t[0]&&t[1]===u.length){const e=r.length-1;if(e>=0){const t=r[e];t&&(s=[e,uz(t)])}}}}),0===r.length&&(r.push(""),i[0]||(i[0]=[]),i[0].push([0,0]),o.push([0,0]),s=[0,0]),{visualLines:r,visualCursor:s,logicalToVisualMap:i,visualToLogicalMap:o}}function Az(e,t,n){return{lines:[...e],cursorRow:t,cursorCol:n,timestamp:Date.now()}}function mz(e,t){const n=[...e.undoStack,t];return n.length>100&&n.shift(),{undoStack:n,redoStack:[]}}function yz(e,t){return{...e,redoStack:[...e.redoStack,t]}}class bz{cache=new Map;maxSize=10;constructor(e=10){this.maxSize=e}getKey(e,t){return`${e}-${t}`}get(e,t){const n=this.getKey(t.startLine,t.endLine);return this.cache.get(n)||null}set(e,t){const n=this.getKey(e.startLine,e.endLine);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(n,t)}clear(){this.cache.clear()}}function vz(e,t){const n=e=>{const t=Az(e.lines,e.cursorRow,e.cursorCol);return{...e,undoRedoState:mz(e.undoRedoState,t)}},r=t=>e.lines[t]??"",i=e=>uz(r(e));switch(t.type){case"SET_TEXT":{let r=e;!1!==t.pushToUndo&&(r=n(e));const i=t.payload.replace(/\r\n?/g,"\n").split("\n"),o=0===i.length?[""]:i,s=o.length-1;return{...r,lines:o,cursorRow:s,cursorCol:uz(o[s]??""),preferredCol:null}}case"INSERT":{const i=n(e),o=[...i.lines];let s=i.cursorRow,a=i.cursorCol;const l=function(e){return lz(e).filter(e=>{const t=e.codePointAt(0);return void 0!==t&&!(127===t||t<=31&&13!==t&&10!==t)}).join("")}(t.payload.replace(/\r\n/g,"\n").replace(/\r/g,"\n")).split("\n"),u=r(s),c=cz(u,0,a),d=cz(u,a);if(l.length>1){o[s]=c+l[0];const e=l.slice(1),t=e.pop()??"";o.splice(s+1,0,...e),o.splice(s+l.length-1,0,t+d),s=s+l.length-1,a=uz(t)}else o[s]=c+l[0]+d,l[0]&&(a=uz(c)+uz(l[0]));return{...i,lines:o,cursorRow:s,cursorCol:a,preferredCol:null}}case"NEWLINE":{const t=n(e),i=[...t.lines],o=r(t.cursorRow),s=cz(o,0,t.cursorCol),a=cz(o,t.cursorCol);return i[t.cursorRow]=s,i.splice(t.cursorRow+1,0,a),{...t,lines:i,cursorRow:t.cursorRow+1,cursorCol:0,preferredCol:null}}case"BACKSPACE":{const t=n(e),i=[...t.lines];let o=t.cursorRow,s=t.cursorCol;if(0===s&&0===o)return e;if(s>0){const e=r(o);i[o]=cz(e,0,s-1)+cz(e,s),s--}else if(o>0){const e=r(o-1),t=r(o),n=uz(e);i[o-1]=e+t,i.splice(o,1),o--,s=n}return{...t,lines:i,cursorRow:o,cursorCol:s,preferredCol:null}}case"DELETE":{const{cursorRow:t,cursorCol:o,lines:s}=e,a=r(t);if(o<i(t)){const r=n(e),i=[...r.lines];return i[t]=cz(a,0,o)+cz(a,o+1),{...r,lines:i,preferredCol:null}}if(t<s.length-1){const i=n(e),o=r(t+1),s=[...i.lines];return s[t]=a+o,s.splice(t+1,1),{...i,lines:s,preferredCol:null}}return e}case"MOVE":{const{dir:n}=t.payload,{lines:r,cursorRow:i,cursorCol:o,viewportWidth:s}=e,a=gz(r,[i,o],s),{visualLines:l,visualCursor:u,visualToLogicalMap:c}=a;let d=u[0],p=u[1],f=e.preferredCol;const h=uz(l[d]??"");switch(n){case"left":f=null,p>0?p--:d>0&&(d--,p=uz(l[d]??""));break;case"right":f=null,p<h?p++:d<l.length-1&&(d++,p=0);break;case"up":d>0&&(null===f&&(f=p),d--,p=fz(f,0,uz(l[d]??"")));break;case"down":d<l.length-1&&(null===f&&(f=p),d++,p=fz(f,0,uz(l[d]??"")));break;case"home":f=null,p=0;break;case"end":f=null,p=h;break;case"wordLeft":{const{cursorRow:t,cursorCol:n,lines:r}=e;if(0===n&&0===t)return e;let i=t,o=n;if(0===n)i--,o=uz(r[i]??"");else{const i=r[t];if(!i)return e;const s=lz(i);let a=n;for(;a>0&&!dz(s[a-1]);)a--;for(;a>0&&dz(s[a-1]);)a--;o=a}return{...e,cursorRow:i,cursorCol:o,preferredCol:null}}case"wordRight":{const{cursorRow:t,cursorCol:n,lines:r}=e;if(t===r.length-1&&n===uz(r[t]??""))return e;let i=t,o=n;const s=lz(r[t]??"");if(n>=s.length)i++,o=0;else{let e=n;for(;e<s.length&&!dz(s[e]);)e++;for(;e<s.length&&dz(s[e]);)e++;o=e}return{...e,cursorRow:i,cursorCol:o,preferredCol:null}}}if(c[d]){const[t,n]=c[d];return{...e,cursorRow:t,cursorCol:fz(n+p,0,uz(e.lines[t]??"")),preferredCol:f}}return e}case"DELETE_WORD_LEFT":{const{cursorRow:t,cursorCol:i}=e;if(0===i&&0===t)return e;const o=n(e);if(0===i){const e=r(t-1),n=r(t),i=uz(e),s=[...o.lines];return s[t-1]=e+n,s.splice(t,1),{...o,lines:s,cursorRow:t-1,cursorCol:i,preferredCol:null}}const s=r(t),a=lz(s);let l=i;for(;l>0&&!dz(a[l-1]);)l--;for(;l>0&&dz(a[l-1]);)l--;const u=[...o.lines];return u[t]=cz(s,0,l)+cz(s,i),{...o,lines:u,cursorCol:l,preferredCol:null}}case"DELETE_WORD_RIGHT":{const{cursorRow:t,cursorCol:i,lines:o}=e,s=r(t),a=lz(s);if(i>=a.length&&t===o.length-1)return e;const l=n(e);if(i>=a.length){const e=r(t+1),n=[...l.lines];return n[t]=s+e,n.splice(t+1,1),{...l,lines:n,preferredCol:null}}let u=i;for(;u<a.length&&!dz(a[u]);)u++;for(;u<a.length&&dz(a[u]);)u++;const c=[...l.lines];return c[t]=cz(s,0,i)+cz(s,u),{...l,lines:c,preferredCol:null}}case"KILL_LINE_RIGHT":{const{cursorRow:t,cursorCol:o,lines:s}=e,a=r(t);if(o<i(t)){const r=n(e),i=[...r.lines];return i[t]=cz(a,0,o),{...r,lines:i}}if(t<s.length-1){const i=n(e),o=r(t+1),s=[...i.lines];return s[t]=a+o,s.splice(t+1,1),{...i,lines:s,preferredCol:null}}return e}case"KILL_LINE_LEFT":{const{cursorRow:t,cursorCol:i}=e;if(i>0){const o=n(e),s=r(t),a=[...o.lines];return a[t]=cz(s,i),{...o,lines:a,cursorCol:0,preferredCol:null}}return e}case"UNDO":{const{snapshot:t,newState:n}=function(e){return 0===e.undoStack.length?{snapshot:null,newState:e}:{snapshot:e.undoStack[e.undoStack.length-1]??null,newState:{undoStack:e.undoStack.slice(0,-1),redoStack:e.redoStack}}}(e.undoRedoState);if(!t)return e;const r=Az(e.lines,e.cursorRow,e.cursorCol);return{...e,...t,undoRedoState:yz(n,r),preferredCol:null}}case"REDO":{const{snapshot:t,newState:n}=function(e){if(0===e.redoStack.length)return{snapshot:null,newState:e};const t=e.redoStack[e.redoStack.length-1],n=e.redoStack.slice(0,-1);return{snapshot:t??null,newState:{undoStack:e.undoStack,redoStack:n}}}(e.undoRedoState);if(!t)return e;const r=Az(e.lines,e.cursorRow,e.cursorCol);return{...e,...t,undoRedoState:{...n,undoStack:[...n.undoStack,r]},preferredCol:null}}case"SET_VIEWPORT_WIDTH":return t.payload===e.viewportWidth?e:{...e,viewportWidth:t.payload};case"SET_VISUAL_SCROLL":return{...e,visualScrollRow:t.payload};case"MOVE_TO_OFFSET":{const[n,r]=hz(e.lines.join("\n"),t.payload);return{...e,cursorRow:n,cursorCol:r,preferredCol:null}}default:return e}}const Ez=Je.memo(qe.forwardRef(function({initialText:e="",initialCursorOffset:t=0,viewport:n,placeholder:r="",focus:i=!0,onChange:o,onSubmit:s,onVisualLinesChange:a,disabled:l=!1,disableArrowKeys:u=!1},c){const{columns:d}=oL(),p=qe.useRef(new bz),f=qe.useMemo(()=>{const r=e.split("\n"),[i,o]=hz(e,t);return{lines:0===r.length?[""]:r,cursorRow:i,cursorCol:o,preferredCol:null,undoRedoState:{undoStack:[],redoStack:[]},viewportWidth:n.width,visualScrollRow:0}},[e,t,n.width]),[h,g]=qe.useReducer(vz,f),{lines:A,cursorRow:m,cursorCol:y,visualScrollRow:b}=h,v=qe.useMemo(()=>A.join("\n"),[A]),E=qe.useMemo(()=>{let e=0;for(let t=0;t<m&&t<A.length;t++)e+=uz(A[t]||"")+1;return e+=y,e},[A,m,y]);qe.useImperativeHandle(c,()=>({getValue:()=>v,setValue:e=>{g({type:"SET_TEXT",payload:e,pushToUndo:!1})},clear:()=>{g({type:"SET_TEXT",payload:"",pushToUndo:!1})},getCursorOffset:()=>E}),[v,E]);const I=qe.useMemo(()=>gz(A,[m,y],h.viewportWidth),[A,m,y,h.viewportWidth]),{visualLines:w,visualCursor:C}=I,_=qe.useMemo(()=>function(e,t=1e3){return e>t}(w.length),[w.length]),B=qe.useMemo(()=>{if(!_)return null;const e=p.current.get(w,{startLine:b,endLine:b+n.height,totalLines:w.length,viewportHeight:n.height,overscan:3});if(e)return e;const t=function(e,t,n,r=3){const i=Math.max(0,t-r),o=Math.min(e.length,t+n+r);return{visibleLines:e.slice(i,o),startRow:i,endRow:o,hasAbove:i>0,hasBelow:o<e.length,linesAbove:i,linesBelow:Math.max(0,e.length-o)}}(w,b,n.height,3);return p.current.set({startLine:t.startRow,endLine:t.endRow,totalLines:w.length,viewportHeight:n.height,overscan:3},{visibleLines:t.visibleLines,startIndex:t.startRow,endIndex:t.endRow,totalLines:w.length,hasLinesBefore:t.hasAbove,hasLinesAfter:t.hasBelow,linesBefore:t.linesAbove,linesAfter:t.linesBelow}),t},[w,b,n.height,_]),D=qe.useMemo(()=>{if(_&&B)return B.visibleLines;const e=Math.min(w.length,20);return function(e,t,n){return e.slice(t,t+n)}(w,0,e)},[w,b,n.height,_,B]);qe.useEffect(()=>{0!==b&&g({type:"SET_VISUAL_SCROLL",payload:0})},[b]),qe.useEffect(()=>{g({type:"SET_VIEWPORT_WIDTH",payload:n.width})},[n.width]),qe.useEffect(()=>{o&&o(v,E)},[v,E,o]),qe.useEffect(()=>{a&&a(w.length)},[w.length,a]),Gi((e,t)=>{if(!i||l)return;if(t.return&&!t.ctrl&&!t.shift&&!t.meta)return void(s&&s(v));if(t.return&&(t.ctrl||t.shift||t.meta))return void g({type:"NEWLINE"});if(t.leftArrow&&!t.meta&&!t.ctrl)return void g({type:"MOVE",payload:{dir:"left"}});if(t.rightArrow&&!t.meta&&!t.ctrl)return void g({type:"MOVE",payload:{dir:"right"}});if(t.upArrow&&!u)return void g({type:"MOVE",payload:{dir:"up"}});if(t.downArrow&&!u)return void g({type:"MOVE",payload:{dir:"down"}});if((t.ctrl||t.meta)&&t.leftArrow)return void g({type:"MOVE",payload:{dir:"wordLeft"}});if((t.ctrl||t.meta)&&t.rightArrow)return void g({type:"MOVE",payload:{dir:"wordRight"}});if(t.ctrl&&"a"===e)return void g({type:"MOVE",payload:{dir:"home"}});if(t.ctrl&&"e"===e)return void g({type:"MOVE",payload:{dir:"end"}});if(t.backspace||""===e||"\b"===e||t.ctrl&&"h"===e||t.delete&&(!e||""===e))return void g({type:"BACKSPACE"});if(t.delete&&e&&""!==e)return void g({type:"DELETE"});if(t.ctrl&&"w"===e)return void g({type:"DELETE_WORD_LEFT"});if((t.meta||t.ctrl)&&t.delete)return void g({type:"DELETE_WORD_RIGHT"});if(t.ctrl&&"k"===e)return void g({type:"KILL_LINE_RIGHT"});if(t.ctrl&&"u"===e)return void g({type:"KILL_LINE_LEFT"});if(t.ctrl&&"z"===e)return void g({type:"UNDO"});if(t.ctrl&&"y"===e)return void g({type:"REDO"});const n=e&&(/^\x1b\[<\d+;\d+;\d+[Mm]/.test(e)||/^\[<\d+;\d+;\d+[Mm]/.test(e));!e||t.ctrl||t.meta||n||g({type:"INSERT",payload:e})},{isActive:i&&!l});const S=qe.useMemo(()=>{const[e]=C;return e-(_&&B?B.startRow:b)},[C,b,_,B]),k=qe.useMemo(()=>v||!r||i?!v&&r&&i&&!l?[We.jsxs(xi,{children:[xr.inverse(r[0]||" "),We.jsx(xi,{color:"gray",children:r.slice(1)})]},"placeholder")]:!v&&r&&i&&l?[We.jsx(xi,{color:"gray",dimColor:!0,children:r},"placeholder")]:D.map((e,t)=>{let r=cz(e,0,n.width);if(i&&!l&&t===S){const[,e]=C;if(e>=0&&e<uz(r)){const t=cz(r,e,e+1)||" ",n=xr.inverse(t);r=cz(r,0,e)+n+cz(r,e+1)}else e===uz(r)&&(r+=xr.inverse(" "))}return We.jsx(xi,{dimColor:l,children:r},`line-${t}`)}):[We.jsx(xi,{color:"gray",dimColor:l,children:r},"placeholder")],[D,C,b,i,l,r,v,n.width,S]);return _&&B?We.jsxs(ki,{flexDirection:"column",children:[B.hasAbove&&We.jsxs(xi,{color:"gray",children:["↑ ",B.linesAbove," more lines above"]}),k,B.hasBelow&&We.jsxs(xi,{color:"gray",children:["↓ ",B.linesBelow," more lines below"]})]}):We.jsx(ki,{flexDirection:"column",children:k})})),Iz=Je.memo(qe.forwardRef(function({placeholder:e="",disabled:t=!1,focus:n=!0,onSubmit:r,enableFileMentions:i=!1,onFileSearchStateChange:o,enableSlashCommands:s=!1,onCommandSearchStateChange:a,maxLength:l,onPendingImagesChange:u},c){const{actions:f}=CL(),{columns:h}=oL(),g=qe.useRef(null),[A,m]=qe.useState(1),[y,b]=qe.useState([]),v=qe.useMemo(()=>({width:Math.max(40,h-6),height:Math.min(20,Math.max(1,A))}),[h,A]),E=qe.useRef(null),I=qe.useRef(!1),C=qe.useRef(new Set);qe.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]),qe.useImperativeHandle(c,()=>({setValue:e=>{g.current?.setValue(e)},clear:()=>{g.current?.clear()},getValue:()=>g.current?.getValue()||"",getPendingImages:()=>y,clearPendingImages:()=>{b([]),u?.([]),C.current.clear()}}),[y,u]);const _=qe.useCallback(e=>{e!==A&&m(e)},[A]),[B,D]=qe.useState(!1),[S,k]=qe.useState(0),[x,Q]=qe.useState([]),[N,T]=qe.useState(!1),[R,F]=qe.useState(!1),[M,O]=qe.useState(0),[$,L]=qe.useState([]),{searchFiles:P}=function(){const{context:e}=EF(),{files:t,isLoading:n,lastScan:r,searchFiles:i,scanFiles:o,clearFiles:s}=rz(),a=e?.workingDirectory||process.cwd();return qe.useEffect(()=>{a?o(a).catch(ex.error):s()},[a,o,s]),{files:t,isLoading:n,lastScan:r,searchFiles:i,refreshFiles:async()=>{a&&await o(a)}}}(),j=qe.useRef(""),U=qe.useRef(0),[z,G]=qe.useState({active:!1,query:"",start:0}),[H,W]=qe.useState({active:!1,query:"",start:0}),q=qe.useCallback(async(e,t)=>{const n=Array.from(e.matchAll(/(?:['"])?([\/~](?:\\.|[^\s'"])+?\.(?:png|jpg|jpeg|gif|webp|bmp|tiff|svg)|[a-zA-Z]:[\/\\](?:\\.|[^\s'"])+?\.(?:png|jpg|jpeg|gif|webp|bmp|tiff|svg)|\\\\(?:\\.|[^\s'"])+?\.(?:png|jpg|jpeg|gif|webp|bmp|tiff|svg))(?:['"])?/gi));if(0===n.length)return{cleanedText:e,foundImages:[]};const r=[];let i=e;for(const o of n){const e=o[1];if(!e)continue;const n=e.replace(/\\\s/g," ");if(t.has(n))i=i.replace(o[0],"");else if(d(n))try{const e=p(n),s=w(n).toLowerCase(),a={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".tiff":"image/tiff",".svg":"image/svg+xml"}[s]||"image/png",l=e.toString("base64");r.push({base64:l,mimeType:a}),t.add(n),i=i.replace(o[0],"")}catch(qK){ex.error(`Failed to load image from path: ${n}`,qK)}}return i=i.replace(/\s+/g," ").trim(),{cleanedText:i,foundImages:r}},[]),J=qe.useCallback((e,t)=>{if(j.current=e,U.current=t,I.current||q(e,C.current).then(({cleanedText:e,foundImages:t})=>{t.length>0&&b(n=>{const r=10-n.length,i=t.slice(0,r);if(i.length>0){const o=[...n,...i];return u?.(o),I.current=!0,g.current?.setValue(e),setTimeout(()=>{I.current=!1},0),ex.info(`Loaded ${i.length} image(s) from pasted paths (total: ${o.length})`),t.length>r&&ex.warn("Maximum image limit reached (10 images)"),o}return n})}),i){const n=function(e,t){if(0===t)return{active:!1,query:"",start:0};let n=-1,r=!1;for(let o=t-1;o>=0;o--){const t=e[o];if(void 0===t)break;const i=o>0?e[o-1]:void 0;if("@"!==t||r){if(/\s/.test(t)){if(r=!0,-1===n)break}else if(/[\(\)\[\]\{\},\.\!\?;:]/.test(t)&&-1===n)break}else if(0===o||void 0!==i&&/[\s\(\)\[\]\{\},\.\!\?;:]/.test(i)){n=o;break}}if(-1===n)return{active:!1,query:"",start:0};let i=e.slice(n+1,t);i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'")?i=i.slice(1,-1):(i.startsWith('"')||i.startsWith("'"))&&(i=i.slice(1));return{active:!0,query:i,start:n}}(e,t);G(n)}if(s){const n=function(e,t){if(0===t)return{active:!1,query:"",start:0};let n=-1,r=!1;for(let o=t-1;o>=0;o--){const t=e[o];if(void 0===t)break;const i=o>0?e[o-1]:void 0;if("/"!==t||r){if(/\s/.test(t)&&(r=!0,-1===n))break}else if(0===o||void 0!==i&&/\s/.test(i)){n=o;break}}if(-1===n)return{active:!1,query:"",start:0};const i=e.slice(n+1,t);if(i.includes(" "))return{active:!1,query:"",start:0};return{active:!0,query:i,start:n}}(e,t);W(n)}E.current&&clearTimeout(E.current),f.setIsTyping(!0),E.current=setTimeout(()=>{f.setIsTyping(!1)},800)},[f,i,s,q,y,u]);qe.useEffect(()=>{if(!z.active)return Q([]),void T(!1);(async()=>{T(!0);try{const e=await P(z.query);Q(e.slice(0,50))}catch(qK){ex.error("Error searching files:",qK),Q([])}finally{T(!1)}})(),D(!0),k(0)},[z.active,z.query,P]),qe.useEffect(()=>{if(!H.active)return void L([]);const e=function(e){const t=e.toLowerCase();return sz.filter(e=>e.name.startsWith(t)||e.aliases?.some(e=>e.startsWith(t)))}(H.query).map(e=>({label:`/${e.name}`,value:e.name,description:e.description,exactPattern:`/${e.name}`}));L(e),F(e.length>0),O(0)},[H.active,H.query]),qe.useEffect(()=>{D(z.active&&x.length>0)},[z.active,x.length]),qe.useEffect(()=>{F(H.active&&$.length>0)},[H.active,$.length]);const K=qe.useCallback(e=>{const t=j.current.slice(0,z.start)+`@${e.relativePath.includes(" ")?`"${e.relativePath}"`:e.relativePath} `;g.current?.setValue(t),D(!1)},[z.start]),Z=qe.useCallback(()=>{D(!1)},[]),V=qe.useCallback(e=>{F(!1),L([]);const t=az(e.value);t&&(g.current?.clear(),setTimeout(()=>t.action(),0))},[]),Y=qe.useCallback(()=>{F(!1)},[]);qe.useEffect(()=>{if(o&&i)if(B&&x.length>0){const e={isOpen:!0,query:z.query,selectedIndex:S,suggestions:x,atMention:z,onSelect:K,onCancel:Z,isLoading:N};o(e)}else o(null)},[B,x,z,S,K,Z,o,i,N]),qe.useEffect(()=>{if(a&&s)if(R&&$.length>0){const e={isOpen:!0,query:H.query,selectedIndex:M,suggestions:$,slashMention:H,onSelect:V,onCancel:Y};a(e)}else a(null)},[R,$,H,M,V,Y,a,s]);const X=function({onSubmit:e,isActive:t,currentQuery:n,onChange:r}){const{actions:i}=CL(),[o,s]=qe.useState(-1),[a,l]=qe.useState(""),u=qe.useCallback(()=>{s(-1),l("")},[]);return{handleSubmit:qe.useCallback(t=>{const n=t.trim();n&&e(n),u()},[e,u]),navigateUp:qe.useCallback(()=>{if(!t)return!1;const e=i.getHistoryLength();if(0===e)return!1;let a=o;if(-1===o)l(n),a=0;else{if(!(o<e-1))return!1;a=o+1}if(a!==o){s(a);const e=i.getHistoryItem(a);return void 0!==e&&(r(e),!0)}return!1},[o,s,r,i,t,n,l]),navigateDown:qe.useCallback(()=>{if(!t)return!1;if(-1===o)return!1;const e=o-1;if(s(e),-1===e)r(a);else{const t=i.getHistoryItem(e);if(void 0===t)return!1;r(t)}return!0},[o,s,a,r,i,t])}}({onSubmit:r||(()=>{}),isActive:n&&!t&&!B&&!R,currentQuery:j.current,onChange:e=>{g.current?.setValue(e)}}),ee=qe.useCallback(e=>{B||R||!r||r(e)},[B,R,r]);return Gi((e,r)=>{if(!t&&n){if(R&&$.length>0){const e=$.length-1,t={upArrow:()=>O(t=>0===t?e:t-1),downArrow:()=>O(t=>t===e?0:t+1),return:()=>{if(M<$.length){const e=$[M];e&&V(e)}},tab:()=>{const e=$[0];e&&V(e)},escape:()=>F(!1)};for(const[n,i]of Object.entries(t))if(r[n])return void i()}if(B&&x.length>0)if(r.upArrow)k(e=>0===e?x.length-1:e-1);else if(r.downArrow)k(e=>e===x.length-1?0:e+1);else if(r.return&&S<x.length){const e=x[S];e&&K(e)}else if(r.tab){const e=x[0];e&&K(e)}else r.escape&&D(!1);if(!B&&!R){if(r.upArrow&&r.meta)return void X.navigateUp();if(r.downArrow&&r.meta)return void X.navigateDown()}!(l&&(g.current?.getValue()||"").length>=l)||r.backspace||r.delete||r.leftArrow||r.rightArrow||""===e||"\b"===e||r.ctrl}},{isActive:!t&&n}),We.jsx(Ez,{ref:g,viewport:v,placeholder:t?"One moment...":e,focus:n,onChange:J,onSubmit:ee,onVisualLinesChange:_,disabled:t,disableArrowKeys:R||B})}));function wz({pendingImages:e,onClear:t}){if(0===e.length)return null;const n=e.reduce((e,t)=>e+.75*t.base64.length/1048576,0);return We.jsx(ki,{marginLeft:2,children:We.jsxs(xi,{color:"blue",children:["🏞️ ",e.length," (",n.toFixed(1),"MB)"]})})}function Cz(){const{modeConfig:e,currentMode:t}=JF();return We.jsxs(ki,{justifyContent:"space-between",marginTop:0,paddingLeft:2,paddingRight:2,width:"100%",children:[We.jsxs(ki,{children:[We.jsx(xi,{bold:!0,color:"plan"===t?"blue":"green",children:e.name}),We.jsx(xi,{dimColor:!0,children:" MODE"}),We.jsx(xi,{dimColor:!0,children:" • Tab to switch"})]}),We.jsx(ki,{children:We.jsx(xi,{dimColor:!0,children:"Ctrl+D - Open Web Console"})}),We.jsx(ki,{children:We.jsx(xi,{dimColor:!0,children:"Press / for slash commands"})})]})}let _z=0;function Bz(e){return`${e}-${Date.now()}-${_z++}`}function Dz(e,t){const n=[];let r=[];for(const i of e){const e=t[i.toolName];e?.metadata?.requiresSequentialExecution||"shell"===i.toolName?(r.length>0&&(n.push(Sz(r)),r=[]),n.push(Sz([i]))):r.push(i)}return r.length>0&&n.push(Sz(r)),n}function Sz(e,t=Bz("group")){const n=e.map((e,n)=>{const r=e.output??e.result;let i,o,s=!0,a=!1;if(r&&"object"==typeof r&&"success"in r){s=!!r.success,i=r;const e=r.llmContent||r.returnDisplay||"";"string"==typeof e&&(a=e.includes("cancelled by the user")||e.includes("declined to approve"),a&&(i.summary="Operation cancelled"))}else"string"==typeof r?(s=!r.startsWith("Error:"),a=r.includes("cancelled by the user")||r.includes("declined to approve"),i={success:s,llmContent:r,returnDisplay:r,summary:a?"Operation cancelled":s?"Tool completed successfully":"Tool execution failed"}):r?(s=!0,i={success:!0,llmContent:JSON.stringify(r),returnDisplay:JSON.stringify(r,null,2),summary:"Tool completed successfully"}):(s=!1,i={success:!1,llmContent:"No output received",returnDisplay:"No output received",summary:"Tool execution failed"});return o=a?SM.Cancelled:s?SM.Success:SM.Error,{id:`${t}-tool-${n}`,toolCallId:e.toolCallId,name:e.toolName||"unknown",displayName:kz(e.toolName),description:xz(e),status:o,result:{success:!!i.success,llmContent:i.llmContent||("string"==typeof r?r:JSON.stringify(r)),returnDisplay:Qz(i.returnDisplay||i.llmContent||r),summary:i.summary||(s?"Tool completed successfully":"Tool execution failed"),...i.diffData?{diffData:i.diffData}:{},...i.metadata?{metadata:i.metadata}:{},...i.locations?{locations:i.locations}:{}},startTime:Date.now()-1e3,endTime:Date.now()}}),r={id:t,tools:n,status:n.some(e=>e.status===SM.Error)?"error":"completed",startTime:Date.now()-1e3,endTime:Date.now()};return{role:"tool-group",id:`msg-${t}`,toolGroup:r,timestamp:Date.now()}}function kz(e){return{readFile:"read-file",writeFile:"write-file",editFile:"edit-file",listDirectory:"list-directory",grep:"grep",shell:"shell",build:"build",todowrite:"todo-write",todoread:"todo-read"}[e]||e}function xz(e){const t=e.toolName,n=e.args,r=e.output||e.result,i=r?.metadata?.toolParams||n;switch(t){case"readFile":case"read_file":const e=i?.absolutePath||n?.absolutePath;return`Reading ${e?e.split(/[/\\]/).pop():"file"}`;case"readManyFiles":const o=i?.paths||n?.paths;return o&&Array.isArray(o)&&o.length>0?1===o.length?`Reading files: ${o[0]}`:`Reading ${o.length} files`:"Reading multiple files";case"writeFile":const s=i?.absolutePath||n?.absolutePath,a=r?.metadata?.filename;return`Writing to ${s?s.split(/[/\\]/).pop():a||"file"}`;case"editFile":const l=i?.absolutePath||n?.absolutePath,u=r?.metadata?.filename;return`Editing ${l?l.split(/[/\\]/).pop():u||"file"}`;case"listDirectory":const c=i?.path||i?.absolutePath||n?.path||n?.absolutePath;return`Listing directory ${c?c.split(/[/\\]/).pop():"contents"}`;case"grep":const d=i?.pattern||n?.pattern,p=i?.absolutePath||n?.absolutePath;return`Searching for "${d||"pattern"}"${p?" in "+p.split(/[/\\]/).pop():""}`;case"glob":return`Searching for files matching "${i?.pattern||n?.pattern||"pattern"}"`;case"shell":const f=r?.metadata?.command;return`Running: ${f||(i?.command||n?.command)||"shell command"}`;case"build":return"Building project";case"todowrite":return"Updating task list";case"todoread":return"Reading task list";case"documentSearch":return"Searching documents in the knowledge base";default:return`Executing ${t}`}}function Qz(e){if("string"==typeof e)return e.startsWith("Error:")?e:e.length>1e3?e.substring(0,1e3)+"\n... (truncated)":e;if(e?.returnDisplay)return e.returnDisplay;if(e&&"object"==typeof e){if(!1===e.success)return e.llmContent||"Tool execution failed";if(e.summary)return e.summary;const t=Object.keys(e);return t.length<3?JSON.stringify(e,null,2):`Tool completed with ${t.length} properties`}return JSON.stringify(e,null,2)}let Nz=null;function Tz(e){Nz=e}function Rz(e){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack};try{return JSON.parse(JSON.stringify(e))}catch{try{return String(e)}catch{return"[unserializable]"}}}function Fz(e,t){$.withScope(n=>{n.setTag("tool_name",t.toolName),n.setTag("tool_status",e),t.toolCallId&&n.setTag("tool_call_id",t.toolCallId),n.setContext("tool",{args:Rz(t.params),result:void 0!==t.result?Rz(t.result):void 0,message:t.message});const r="success"===e?"info":"error",i="success"===e?`Tool ${t.toolName} succeeded`:"validation_failure"===e?`Tool ${t.toolName} validation failed`:`Tool ${t.toolName} failed`;$.captureMessage(i,r)})}function Mz(e){const t={name:e.metadata.name,description:e.metadata.description,inputSchema:e.inputSchema,execute:async(t,n)=>{const r=ST.getState(),i=r.getCachedContext?.(),o=xw.getState(),{teamId:s,projectId:a}=o.getContext(),l=yT.getState(),u=l.getApiFetch(),c=l.getSessionId(),d=e.metadata.name,p=n?.toolCallId,f={workingDirectory:process.cwd(),projectRoot:process.cwd(),teamId:s??void 0,projectId:a??void 0,sessionId:c??void 0,apiFetch:u??void 0,signal:n?.abortSignal,environmentContext:i?{platform:i.platform.platform,projectType:i.projectInfo.projectType,isGitRepository:i.projectInfo.isGitRepository,dateTime:i.dateTime.formatted}:void 0,snapshotService:wM()??void 0},h=async()=>{try{if(e.validateParams){const n=e.validateParams(t);if(n){const e=`Validation Error: ${n}`;return Fz("validation_failure",{toolName:d,toolCallId:p,params:t,message:e}),e}}if(e.shouldConfirm&&e.metadata.requiresConfirmation){if(!(e.isAllowlisted?.(t)||!1)){const n=await e.shouldConfirm(t,f);if(n){const r=await async function(e){if(!Nz)throw new Error("No confirmation handler registered. UI must call setGlobalConfirmationHandler.");return await Nz(e)}({toolName:e.metadata.name,params:t,context:f,confirmationDetails:n});if(!r.approved)throw new Error(`Tool execution was cancelled by the user. The user declined to approve the ${e.metadata.name} operation.`);r.approved&&r.storePermission&&e.addToAllowlist&&e.addToAllowlist(t,r.storePermission)}}}if(e.getDescription,e.metadata.canStream&&n?.toolCallId){const t=n.toolCallId,r=e.metadata.name;f.updateOutput=e=>{DM.getState().updateStream(t,r,e)}}const r=await e.execute(t,f);let i;if(r)if("string"!=typeof r.llmContent)i={success:!1,llmContent:"Error: Tool execution returned invalid content format",returnDisplay:"Error: Tool execution returned invalid content format",summary:"Tool execution failed"};else if(r.llmContent){let e=r.llmContent;e.length>3e4&&(e=function(e,t=3e4){return e.length<=t?e:e.slice(0,t)+"\n\n(Output truncated due to length limit)"}(e)),i={success:r.success,llmContent:e,returnDisplay:r.returnDisplay||r.llmContent,summary:r.summary||"Tool completed successfully",metadata:r.metadata,locations:r.locations,diffData:r.diffData}}else i={success:!0,llmContent:r.summary||`Tool ${e.metadata.name} completed successfully`,returnDisplay:r.returnDisplay||r.summary||`Tool ${e.metadata.name} completed successfully`,summary:r.summary||"Tool completed successfully",metadata:r.metadata,locations:r.locations,diffData:r.diffData};else i={success:!1,llmContent:"Error: Tool execution returned no result",returnDisplay:"Error: Tool execution returned no result",summary:"Tool execution failed"};return Fz(i.success?"success":"failure",{toolName:d,toolCallId:p,params:t,result:i}),i}catch(qK){const n=qK instanceof Error?qK.message:String(qK);return $.withScope(r=>{r.setTag("tool_name",d),r.setTag("tool_status","exception"),p&&r.setTag("tool_call_id",p),r.setContext("tool",{args:Rz(t),errorMessage:n}),$.captureException(qK instanceof Error?qK:new Error(String(qK)))}),{success:!1,llmContent:`Error: ${n}`,returnDisplay:`Error: ${n}`,summary:"Tool execution failed"}}};return e.metadata.requiresSequentialExecution?new Promise((r,i)=>{const o={id:n?.toolCallId||`${e.metadata.name}-${Date.now()}`,toolName:e.metadata.name,displayName:e.metadata.displayName,params:t,context:f,options:n,execute:h,resolve:r,reject:i};iz.getState().enqueue(o)}):h()},toModelOutput:e=>({type:"text",value:e.llmContent||String(e)})};return Object.assign(t,{metadata:e.metadata,validateParams:e.validateParams,getDescription:e.getDescription,getLocations:e.getLocations,shouldConfirm:e.shouldConfirm,executeStructured:async(t,n)=>{const r={workingDirectory:process.cwd(),projectRoot:process.cwd(),...n};return e.execute(t,r)}})}var Oz,$z,Lz={},Pz={},jz={},Uz={},zz={};function Gz(){if(Oz)return zz;function e(e){return"string"==typeof e||e instanceof String}function t(e){return Array.isArray(e)}return Oz=1,Object.defineProperty(zz,"__esModule",{value:!0}),zz.stringArray=zz.array=zz.func=zz.error=zz.number=zz.string=zz.boolean=void 0,zz.boolean=function(e){return!0===e||!1===e},zz.string=e,zz.number=function(e){return"number"==typeof e||e instanceof Number},zz.error=function(e){return e instanceof Error},zz.func=function(e){return"function"==typeof e},zz.array=t,zz.stringArray=function(n){return t(n)&&n.every(t=>e(t))},zz}function Hz(){if($z)return Uz;$z=1,Object.defineProperty(Uz,"__esModule",{value:!0}),Uz.Message=Uz.NotificationType9=Uz.NotificationType8=Uz.NotificationType7=Uz.NotificationType6=Uz.NotificationType5=Uz.NotificationType4=Uz.NotificationType3=Uz.NotificationType2=Uz.NotificationType1=Uz.NotificationType0=Uz.NotificationType=Uz.RequestType9=Uz.RequestType8=Uz.RequestType7=Uz.RequestType6=Uz.RequestType5=Uz.RequestType4=Uz.RequestType3=Uz.RequestType2=Uz.RequestType1=Uz.RequestType=Uz.RequestType0=Uz.AbstractMessageSignature=Uz.ParameterStructures=Uz.ResponseError=Uz.ErrorCodes=void 0;const e=Gz();var t,n,r,i;(n=t||(Uz.ErrorCodes=t={})).ParseError=-32700,n.InvalidRequest=-32600,n.MethodNotFound=-32601,n.InvalidParams=-32602,n.InternalError=-32603,n.jsonrpcReservedErrorRangeStart=-32099,n.serverErrorStart=-32099,n.MessageWriteError=-32099,n.MessageReadError=-32098,n.PendingResponseRejected=-32097,n.ConnectionInactive=-32096,n.ServerNotInitialized=-32002,n.UnknownErrorCode=-32001,n.jsonrpcReservedErrorRangeEnd=-32e3,n.serverErrorEnd=-32e3;class o extends Error{constructor(n,r,i){super(r),this.code=e.number(n)?n:t.UnknownErrorCode,this.data=i,Object.setPrototypeOf(this,o.prototype)}toJson(){const e={code:this.code,message:this.message};return void 0!==this.data&&(e.data=this.data),e}}Uz.ResponseError=o;class s{constructor(e){this.kind=e}static is(e){return e===s.auto||e===s.byName||e===s.byPosition}toString(){return this.kind}}Uz.ParameterStructures=s,s.auto=new s("auto"),s.byPosition=new s("byPosition"),s.byName=new s("byName");class a{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return s.auto}}Uz.AbstractMessageSignature=a;Uz.RequestType0=class extends a{constructor(e){super(e,0)}};Uz.RequestType=class extends a{constructor(e,t=s.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};Uz.RequestType1=class extends a{constructor(e,t=s.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};Uz.RequestType2=class extends a{constructor(e){super(e,2)}};Uz.RequestType3=class extends a{constructor(e){super(e,3)}};Uz.RequestType4=class extends a{constructor(e){super(e,4)}};Uz.RequestType5=class extends a{constructor(e){super(e,5)}};Uz.RequestType6=class extends a{constructor(e){super(e,6)}};Uz.RequestType7=class extends a{constructor(e){super(e,7)}};Uz.RequestType8=class extends a{constructor(e){super(e,8)}};Uz.RequestType9=class extends a{constructor(e){super(e,9)}};Uz.NotificationType=class extends a{constructor(e,t=s.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};Uz.NotificationType0=class extends a{constructor(e){super(e,0)}};Uz.NotificationType1=class extends a{constructor(e,t=s.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};Uz.NotificationType2=class extends a{constructor(e){super(e,2)}};Uz.NotificationType3=class extends a{constructor(e){super(e,3)}};Uz.NotificationType4=class extends a{constructor(e){super(e,4)}};Uz.NotificationType5=class extends a{constructor(e){super(e,5)}};Uz.NotificationType6=class extends a{constructor(e){super(e,6)}};Uz.NotificationType7=class extends a{constructor(e){super(e,7)}};Uz.NotificationType8=class extends a{constructor(e){super(e,8)}};return Uz.NotificationType9=class extends a{constructor(e){super(e,9)}},(i=r||(Uz.Message=r={})).isRequest=function(t){const n=t;return n&&e.string(n.method)&&(e.string(n.id)||e.number(n.id))},i.isNotification=function(t){const n=t;return n&&e.string(n.method)&&void 0===t.id},i.isResponse=function(t){const n=t;return n&&(void 0!==n.result||!!n.error)&&(e.string(n.id)||e.number(n.id)||null===n.id)},Uz}var Wz,qz={};function Jz(){if(Wz)return qz;var e,t,n;Wz=1,Object.defineProperty(qz,"__esModule",{value:!0}),qz.LRUCache=qz.LinkedMap=qz.Touch=void 0,(n=t||(qz.Touch=t={})).None=0,n.First=1,n.AsOld=n.First,n.Last=2,n.AsNew=n.Last;class r{constructor(){this[e]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,n=t.None){const r=this._map.get(e);if(r)return n!==t.None&&this.touch(r,n),r.value}set(e,n,r=t.None){let i=this._map.get(e);if(i)i.value=n,r!==t.None&&this.touch(i,r);else{switch(i={key:e,value:n,next:void 0,previous:void 0},r){case t.None:this.addItemLast(i);break;case t.First:this.addItemFirst(i);break;case t.Last:default:this.addItemLast(i)}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){const t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");const e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){const n=this._state;let r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==n)throw new Error("LinkedMap got modified during iteration.");r=r.next}}keys(){const e=this._state;let t=this._head;const n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){const e={value:t.key,done:!1};return t=t.next,e}return{value:void 0,done:!0}}};return n}values(){const e=this._state;let t=this._head;const n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){const e={value:t.value,done:!1};return t=t.next,e}return{value:void 0,done:!0}}};return n}entries(){const e=this._state;let t=this._head;const n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){const e={value:[t.key,t.value],done:!1};return t=t.next,e}return{value:void 0,done:!0}}};return n}[(e=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(0===e)return void this.clear();let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(this._head||this._tail){if(!this._head)throw new Error("Invalid list");e.next=this._head,this._head.previous=e}else this._tail=e;this._head=e,this._state++}addItemLast(e){if(this._head||this._tail){if(!this._tail)throw new Error("Invalid list");e.previous=this._tail,this._tail.next=e}else this._head=e;this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw new Error("Invalid list");e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw new Error("Invalid list");e.previous.next=void 0,this._tail=e.previous}else{const t=e.next,n=e.previous;if(!t||!n)throw new Error("Invalid list");t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,n){if(!this._head||!this._tail)throw new Error("Invalid list");if(n===t.First||n===t.Last)if(n===t.First){if(e===this._head)return;const t=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(n===t.Last){if(e===this._tail)return;const t=e.next,n=e.previous;e===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}toJSON(){const e=[];return this.forEach((t,n)=>{e.push([n,t])}),e}fromJSON(e){this.clear();for(const[t,n]of e)this.set(t,n)}}qz.LinkedMap=r;return qz.LRUCache=class extends r{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,n=t.AsNew){return super.get(e,n)}peek(e){return super.get(e,t.None)}set(e,n){return super.set(e,n,t.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}},qz}var Kz,Zz={};var Vz,Yz,Xz={},eG={};function tG(){if(Vz)return eG;let e;function t(){if(void 0===e)throw new Error("No runtime abstraction layer installed");return e}return Vz=1,Object.defineProperty(eG,"__esModule",{value:!0}),(t||(t={})).install=function(t){if(void 0===t)throw new Error("No runtime abstraction layer provided");e=t},eG.default=t,eG}function nG(){if(Yz)return Xz;Yz=1,Object.defineProperty(Xz,"__esModule",{value:!0}),Xz.Emitter=Xz.Event=void 0;const e=tG();var t;!function(e){const t={dispose(){}};e.None=function(){return t}}(t||(Xz.Event=t={}));class n{add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let r=0,i=this._callbacks.length;r<i;r++)if(this._callbacks[r]===e){if(this._contexts[r]===t)return this._callbacks.splice(r,1),void this._contexts.splice(r,1);n=!0}if(n)throw new Error("When adding a listener with a context, you should remove it with the same context")}invoke(...t){if(!this._callbacks)return[];const n=[],r=this._callbacks.slice(0),i=this._contexts.slice(0);for(let s=0,a=r.length;s<a;s++)try{n.push(r[s].apply(i[s],t))}catch(o){(0,e.default)().console.error(o)}return n}isEmpty(){return!this._callbacks||0===this._callbacks.length}dispose(){this._callbacks=void 0,this._contexts=void 0}}class r{constructor(e){this._options=e}get event(){return this._event||(this._event=(e,t,i)=>{this._callbacks||(this._callbacks=new n),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,t);const o={dispose:()=>{this._callbacks&&(this._callbacks.remove(e,t),o.dispose=r._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(i)&&i.push(o),o}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}}return Xz.Emitter=r,r._noop=function(){},Xz}var rG,iG={};function oG(){if(rG)return iG;rG=1,Object.defineProperty(iG,"__esModule",{value:!0}),iG.CancellationTokenSource=iG.CancellationToken=void 0;const e=tG(),t=Gz(),n=nG();var r,i;(i=r||(iG.CancellationToken=r={})).None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:n.Event.None}),i.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n.Event.None}),i.is=function(e){const n=e;return n&&(n===i.None||n===i.Cancelled||t.boolean(n.isCancellationRequested)&&!!n.onCancellationRequested)};const o=Object.freeze(function(t,n){const r=(0,e.default)().timer.setTimeout(t.bind(n),0);return{dispose(){r.dispose()}}});class s{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?o:(this._emitter||(this._emitter=new n.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}}return iG.CancellationTokenSource=class{get token(){return this._token||(this._token=new s),this._token}cancel(){this._token?this._token.cancel():this._token=r.Cancelled}dispose(){this._token?this._token instanceof s&&this._token.dispose():this._token=r.None}},iG}var sG,aG={};var lG,uG,cG={},dG={};function pG(){if(lG)return dG;lG=1,Object.defineProperty(dG,"__esModule",{value:!0}),dG.Semaphore=void 0;const e=tG();return dG.Semaphore=class{constructor(e=1){if(e<=0)throw new Error("Capacity must be greater than 0");this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,n)=>{this._waiting.push({thunk:e,resolve:t,reject:n}),this.runNext()})}get active(){return this._active}runNext(){0!==this._waiting.length&&this._active!==this._capacity&&(0,e.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(0===this._waiting.length||this._active===this._capacity)return;const e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{const t=e.thunk();t instanceof Promise?t.then(t=>{this._active--,e.resolve(t),this.runNext()},t=>{this._active--,e.reject(t),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}},dG}var fG,hG={};var gG,AG={};var mG,yG,bG,vG,EG,IG,wG={};function CG(){return mG||(mG=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createMessageConnection=e.ConnectionOptions=e.MessageStrategy=e.CancellationStrategy=e.CancellationSenderStrategy=e.CancellationReceiverStrategy=e.RequestCancellationReceiverStrategy=e.IdCancellationReceiverStrategy=e.ConnectionStrategy=e.ConnectionError=e.ConnectionErrors=e.LogTraceNotification=e.SetTraceNotification=e.TraceFormat=e.TraceValues=e.Trace=e.NullLogger=e.ProgressType=e.ProgressToken=void 0;const t=tG(),n=Gz(),r=Hz(),i=Jz(),o=nG(),s=oG();var a,l,u,c,d,p,f,h,g,A,m,y,b,v,E,I,w,C,_,B,D,S,k,x,Q,N,T;(a||(a={})).type=new r.NotificationType("$/cancelRequest"),(l||(e.ProgressToken=l={})).is=function(e){return"string"==typeof e||"number"==typeof e},(u||(u={})).type=new r.NotificationType("$/progress");e.ProgressType=class{constructor(){}},(c||(c={})).is=function(e){return n.func(e)},e.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}}),(p=d||(e.Trace=d={}))[p.Off=0]="Off",p[p.Messages=1]="Messages",p[p.Compact=2]="Compact",p[p.Verbose=3]="Verbose",(h=f||(e.TraceValues=f={})).Off="off",h.Messages="messages",h.Compact="compact",h.Verbose="verbose",function(e){e.fromString=function(t){if(!n.string(t))return e.Off;switch(t=t.toLowerCase()){case"off":default:return e.Off;case"messages":return e.Messages;case"compact":return e.Compact;case"verbose":return e.Verbose}},e.toString=function(t){switch(t){case e.Off:return"off";case e.Messages:return"messages";case e.Compact:return"compact";case e.Verbose:return"verbose";default:return"off"}}}(d||(e.Trace=d={})),(A=g||(e.TraceFormat=g={})).Text="text",A.JSON="json",function(e){e.fromString=function(t){return n.string(t)&&"json"===(t=t.toLowerCase())?e.JSON:e.Text}}(g||(e.TraceFormat=g={})),(m||(e.SetTraceNotification=m={})).type=new r.NotificationType("$/setTrace"),(y||(e.LogTraceNotification=y={})).type=new r.NotificationType("$/logTrace"),(v=b||(e.ConnectionErrors=b={}))[v.Closed=1]="Closed",v[v.Disposed=2]="Disposed",v[v.AlreadyListening=3]="AlreadyListening";class R extends Error{constructor(e,t){super(t),this.code=e,Object.setPrototypeOf(this,R.prototype)}}e.ConnectionError=R,(E||(e.ConnectionStrategy=E={})).is=function(e){const t=e;return t&&n.func(t.cancelUndispatched)},(I||(e.IdCancellationReceiverStrategy=I={})).is=function(e){const t=e;return t&&(void 0===t.kind||"id"===t.kind)&&n.func(t.createCancellationTokenSource)&&(void 0===t.dispose||n.func(t.dispose))},(w||(e.RequestCancellationReceiverStrategy=w={})).is=function(e){const t=e;return t&&"request"===t.kind&&n.func(t.createCancellationTokenSource)&&(void 0===t.dispose||n.func(t.dispose))},(_=C||(e.CancellationReceiverStrategy=C={})).Message=Object.freeze({createCancellationTokenSource:e=>new s.CancellationTokenSource}),_.is=function(e){return I.is(e)||w.is(e)},(D=B||(e.CancellationSenderStrategy=B={})).Message=Object.freeze({sendCancellation:(e,t)=>e.sendNotification(a.type,{id:t}),cleanup(e){}}),D.is=function(e){const t=e;return t&&n.func(t.sendCancellation)&&n.func(t.cleanup)},(k=S||(e.CancellationStrategy=S={})).Message=Object.freeze({receiver:C.Message,sender:B.Message}),k.is=function(e){const t=e;return t&&C.is(t.receiver)&&B.is(t.sender)},(x||(e.MessageStrategy=x={})).is=function(e){const t=e;return t&&n.func(t.handleMessage)},(Q||(e.ConnectionOptions=Q={})).is=function(e){const t=e;return t&&(S.is(t.cancellationStrategy)||E.is(t.connectionStrategy)||x.is(t.messageStrategy))},(T=N||(N={}))[T.New=1]="New",T[T.Listening=2]="Listening",T[T.Closed=3]="Closed",T[T.Disposed=4]="Disposed",e.createMessageConnection=function(p,f,h,A){const v=void 0!==h?h:e.NullLogger;let E=0,w=0,C=0;const _="2.0";let B;const D=new Map;let k;const Q=new Map,T=new Map;let F,M,O=new i.LinkedMap,$=new Map,L=new Set,P=new Map,j=d.Off,U=g.Text,z=N.New;const G=new o.Emitter,H=new o.Emitter,W=new o.Emitter,q=new o.Emitter,J=new o.Emitter,K=A&&A.cancellationStrategy?A.cancellationStrategy:S.Message;function Z(e){if(null===e)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+e.toString()}function V(e,t){var n;r.Message.isRequest(t)?e.set(Z(t.id),t):r.Message.isResponse(t)?e.set(null===(n=t.id)?"res-unknown-"+(++C).toString():"res-"+n.toString(),t):e.set("not-"+(++w).toString(),t)}function Y(e){}function X(){return z===N.Listening}function ee(){return z===N.Closed}function te(){return z===N.Disposed}function ne(){z!==N.New&&z!==N.Listening||(z=N.Closed,H.fire(void 0))}function re(){F||0===O.size||(F=(0,t.default)().timer.setImmediate(()=>{F=void 0,function(){if(0===O.size)return;const e=O.shift();try{const t=A?.messageStrategy;x.is(t)?t.handleMessage(e,ie):ie(e)}finally{re()}}()}))}function ie(e){r.Message.isRequest(e)?function(e){if(te())return;function t(t,n,i){const o={jsonrpc:_,id:e.id};t instanceof r.ResponseError?o.error=t.toJson():o.result=void 0===t?null:t,ae(o,n,i),f.write(o).catch(()=>v.error("Sending response failed."))}function i(t,n,r){const i={jsonrpc:_,id:e.id,error:t.toJson()};ae(i,n,r),f.write(i).catch(()=>v.error("Sending response failed."))}function o(t,n,r){void 0===t&&(t=null);const i={jsonrpc:_,id:e.id,result:t};ae(i,n,r),f.write(i).catch(()=>v.error("Sending response failed."))}!function(e){if(j===d.Off||!M)return;if(U===g.Text){let t;j!==d.Verbose&&j!==d.Compact||!e.params||(t=`Params: ${se(e.params)}\n\n`),M.log(`Received request '${e.method} - (${e.id})'.`,t)}else ue("receive-request",e)}(e);const s=D.get(e.method);let a,l;s&&(a=s.type,l=s.handler);const u=Date.now();if(l||B){const s=e.id??String(Date.now()),c=I.is(K.receiver)?K.receiver.createCancellationTokenSource(s):K.receiver.createCancellationTokenSource(e);null!==e.id&&L.has(e.id)&&c.cancel(),null!==e.id&&P.set(s,c);try{let d;if(l)if(void 0===e.params){if(void 0!==a&&0!==a.numberOfParams)return void i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines ${a.numberOfParams} params but received none.`),e.method,u);d=l(c.token)}else if(Array.isArray(e.params)){if(void 0!==a&&a.parameterStructures===r.ParameterStructures.byName)return void i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by name but received parameters by position`),e.method,u);d=l(...e.params,c.token)}else{if(void 0!==a&&a.parameterStructures===r.ParameterStructures.byPosition)return void i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by position but received parameters by name`),e.method,u);d=l(e.params,c.token)}else B&&(d=B(e.method,e.params,c.token));const p=d;d?p.then?p.then(n=>{P.delete(s),t(n,e.method,u)},t=>{P.delete(s),t instanceof r.ResponseError?i(t,e.method,u):t&&n.string(t.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${t.message}`),e.method,u):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,u)}):(P.delete(s),t(d,e.method,u)):(P.delete(s),o(d,e.method,u))}catch(qK){P.delete(s),qK instanceof r.ResponseError?t(qK,e.method,u):qK&&n.string(qK.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${qK.message}`),e.method,u):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,u)}}else i(new r.ResponseError(r.ErrorCodes.MethodNotFound,`Unhandled method ${e.method}`),e.method,u)}(e):r.Message.isNotification(e)?function(e){if(te())return;let t,n;if(e.method===a.type.method){const t=e.params.id;return L.delete(t),void le(e)}{const r=Q.get(e.method);r&&(n=r.handler,t=r.type)}if(n||k)try{if(le(e),n)if(void 0===e.params)void 0!==t&&0!==t.numberOfParams&&t.parameterStructures!==r.ParameterStructures.byName&&v.error(`Notification ${e.method} defines ${t.numberOfParams} params but received none.`),n();else if(Array.isArray(e.params)){const i=e.params;e.method===u.type.method&&2===i.length&&l.is(i[0])?n({token:i[0],value:i[1]}):(void 0!==t&&(t.parameterStructures===r.ParameterStructures.byName&&v.error(`Notification ${e.method} defines parameters by name but received parameters by position`),t.numberOfParams!==e.params.length&&v.error(`Notification ${e.method} defines ${t.numberOfParams} params but received ${i.length} arguments`)),n(...i))}else void 0!==t&&t.parameterStructures===r.ParameterStructures.byPosition&&v.error(`Notification ${e.method} defines parameters by position but received parameters by name`),n(e.params);else k&&k(e.method,e.params)}catch(qK){qK.message?v.error(`Notification handler '${e.method}' failed with message: ${qK.message}`):v.error(`Notification handler '${e.method}' failed unexpectedly.`)}else W.fire(e)}(e):r.Message.isResponse(e)?function(e){if(te())return;if(null===e.id)e.error?v.error(`Received response message without id: Error is: \n${JSON.stringify(e.error,void 0,4)}`):v.error("Received response message without id. No further error information provided.");else{const t=e.id,n=$.get(t);if(function(e,t){if(j===d.Off||!M)return;if(U===g.Text){let n;if(j!==d.Verbose&&j!==d.Compact||(e.error&&e.error.data?n=`Error data: ${se(e.error.data)}\n\n`:e.result?n=`Result: ${se(e.result)}\n\n`:void 0===e.error&&(n="No result returned.\n\n")),t){const r=e.error?` Request failed: ${e.error.message} (${e.error.code}).`:"";M.log(`Received response '${t.method} - (${e.id})' in ${Date.now()-t.timerStart}ms.${r}`,n)}else M.log(`Received response ${e.id} without active response promise.`,n)}else ue("receive-response",e)}(e,n),void 0!==n){$.delete(t);try{if(e.error){const t=e.error;n.reject(new r.ResponseError(t.code,t.message,t.data))}else{if(void 0===e.result)throw new Error("Should never happen.");n.resolve(e.result)}}catch(qK){qK.message?v.error(`Response handler '${n.method}' failed with message: ${qK.message}`):v.error(`Response handler '${n.method}' failed unexpectedly.`)}}}}(e):function(e){if(!e)return void v.error("Received empty message.");v.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(e,null,4)}`);const t=e;if(n.string(t.id)||n.number(t.id)){const e=t.id,n=$.get(e);n&&n.reject(new Error("The received response has neither a result nor an error property."))}}(e)}p.onClose(ne),p.onError(function(e){G.fire([e,void 0,void 0])}),f.onClose(ne),f.onError(function(e){G.fire(e)});const oe=e=>{try{if(r.Message.isNotification(e)&&e.method===a.type.method){const t=e.params.id,n=Z(t),i=O.get(n);if(r.Message.isRequest(i)){const r=A?.connectionStrategy,o=r&&r.cancelUndispatched?r.cancelUndispatched(i,Y):void 0;if(o&&(void 0!==o.error||void 0!==o.result))return O.delete(n),P.delete(t),o.id=i.id,ae(o,e.method,Date.now()),void f.write(o).catch(()=>v.error("Sending response for canceled message failed."))}const o=P.get(t);if(void 0!==o)return o.cancel(),void le(e);L.add(t)}V(O,e)}finally{re()}};function se(e){if(null!=e)switch(j){case d.Verbose:return JSON.stringify(e,null,4);case d.Compact:return JSON.stringify(e);default:return}}function ae(e,t,n){if(j!==d.Off&&M)if(U===g.Text){let r;j!==d.Verbose&&j!==d.Compact||(e.error&&e.error.data?r=`Error data: ${se(e.error.data)}\n\n`:e.result?r=`Result: ${se(e.result)}\n\n`:void 0===e.error&&(r="No result returned.\n\n")),M.log(`Sending response '${t} - (${e.id})'. Processing request took ${Date.now()-n}ms`,r)}else ue("send-response",e)}function le(e){if(j!==d.Off&&M&&e.method!==y.type.method)if(U===g.Text){let t;j!==d.Verbose&&j!==d.Compact||(t=e.params?`Params: ${se(e.params)}\n\n`:"No parameters provided.\n\n"),M.log(`Received notification '${e.method}'.`,t)}else ue("receive-notification",e)}function ue(e,t){if(!M||j===d.Off)return;const n={isLSPMessage:!0,type:e,message:t,timestamp:Date.now()};M.log(n)}function ce(){if(ee())throw new R(b.Closed,"Connection is closed.");if(te())throw new R(b.Disposed,"Connection is disposed.")}function de(e){return void 0===e?null:e}function pe(e){return null===e?void 0:e}function fe(e){return null!=e&&!Array.isArray(e)&&"object"==typeof e}function he(e,t){switch(e){case r.ParameterStructures.auto:return fe(t)?pe(t):[de(t)];case r.ParameterStructures.byName:if(!fe(t))throw new Error("Received parameters by name but param is not an object literal.");return pe(t);case r.ParameterStructures.byPosition:return[de(t)];default:throw new Error(`Unknown parameter structure ${e.toString()}`)}}function ge(e,t){let n;const r=e.numberOfParams;switch(r){case 0:n=void 0;break;case 1:n=he(e.parameterStructures,t[0]);break;default:n=[];for(let e=0;e<t.length&&e<r;e++)n.push(de(t[e]));if(t.length<r)for(let e=t.length;e<r;e++)n.push(null)}return n}const Ae={sendNotification:(e,...t)=>{let i,o;if(ce(),n.string(e)){i=e;const n=t[0];let s=0,a=r.ParameterStructures.auto;r.ParameterStructures.is(n)&&(s=1,a=n);let l=t.length;const u=l-s;switch(u){case 0:o=void 0;break;case 1:o=he(a,t[s]);break;default:if(a===r.ParameterStructures.byName)throw new Error(`Received ${u} parameters for 'by Name' notification parameter structure.`);o=t.slice(s,l).map(e=>de(e))}}else{const n=t;i=e.method,o=ge(e,n)}const s={jsonrpc:_,method:i,params:o};return function(e){if(j!==d.Off&&M)if(U===g.Text){let t;j!==d.Verbose&&j!==d.Compact||(t=e.params?`Params: ${se(e.params)}\n\n`:"No parameters provided.\n\n"),M.log(`Sending notification '${e.method}'.`,t)}else ue("send-notification",e)}(s),f.write(s).catch(e=>{throw v.error("Sending notification failed."),e})},onNotification:(e,t)=>{let r;return ce(),n.func(e)?k=e:t&&(n.string(e)?(r=e,Q.set(e,{type:void 0,handler:t})):(r=e.method,Q.set(e.method,{type:e,handler:t}))),{dispose:()=>{void 0!==r?Q.delete(r):k=void 0}}},onProgress:(e,t,n)=>{if(T.has(t))throw new Error(`Progress handler for token ${t} already registered`);return T.set(t,n),{dispose:()=>{T.delete(t)}}},sendProgress:(e,t,n)=>Ae.sendNotification(u.type,{token:t,value:n}),onUnhandledProgress:q.event,sendRequest:(e,...t)=>{let i,o,a;if(ce(),function(){if(!X())throw new Error("Call listen() first.")}(),n.string(e)){i=e;const n=t[0],l=t[t.length-1];let u=0,c=r.ParameterStructures.auto;r.ParameterStructures.is(n)&&(u=1,c=n);let d=t.length;s.CancellationToken.is(l)&&(d-=1,a=l);const p=d-u;switch(p){case 0:o=void 0;break;case 1:o=he(c,t[u]);break;default:if(c===r.ParameterStructures.byName)throw new Error(`Received ${p} parameters for 'by Name' request parameter structure.`);o=t.slice(u,d).map(e=>de(e))}}else{const n=t;i=e.method,o=ge(e,n);const r=e.numberOfParams;a=s.CancellationToken.is(n[r])?n[r]:void 0}const l=E++;let u;a&&(u=a.onCancellationRequested(()=>{const e=K.sender.sendCancellation(Ae,l);return void 0===e?(v.log(`Received no promise from cancellation strategy when cancelling id ${l}`),Promise.resolve()):e.catch(()=>{v.log(`Sending cancellation messages for id ${l} failed`)})}));const c={jsonrpc:_,id:l,method:i,params:o};return function(e){if(j!==d.Off&&M)if(U===g.Text){let t;j!==d.Verbose&&j!==d.Compact||!e.params||(t=`Params: ${se(e.params)}\n\n`),M.log(`Sending request '${e.method} - (${e.id})'.`,t)}else ue("send-request",e)}(c),"function"==typeof K.sender.enableCancellation&&K.sender.enableCancellation(c),new Promise(async(e,t)=>{const n={method:i,timerStart:Date.now(),resolve:t=>{e(t),K.sender.cleanup(l),u?.dispose()},reject:e=>{t(e),K.sender.cleanup(l),u?.dispose()}};try{$.set(l,n),await f.write(c)}catch(qK){throw $.delete(l),n.reject(new r.ResponseError(r.ErrorCodes.MessageWriteError,qK.message?qK.message:"Unknown reason")),v.error("Sending request failed."),qK}})},onRequest:(e,t)=>{ce();let r=null;return c.is(e)?(r=void 0,B=e):n.string(e)?(r=null,void 0!==t&&(r=e,D.set(e,{handler:t,type:void 0}))):void 0!==t&&(r=e.method,D.set(e.method,{type:e,handler:t})),{dispose:()=>{null!==r&&(void 0!==r?D.delete(r):B=void 0)}}},hasPendingResponse:()=>$.size>0,trace:async(e,t,r)=>{let i=!1,o=g.Text;void 0!==r&&(n.boolean(r)?i=r:(i=r.sendNotification||!1,o=r.traceFormat||g.Text)),j=e,U=o,M=j===d.Off?void 0:t,!i||ee()||te()||await Ae.sendNotification(m.type,{value:d.toString(e)})},onError:G.event,onClose:H.event,onUnhandledNotification:W.event,onDispose:J.event,end:()=>{f.end()},dispose:()=>{if(te())return;z=N.Disposed,J.fire(void 0);const e=new r.ResponseError(r.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(const t of $.values())t.reject(e);$=new Map,P=new Map,L=new Set,O=new i.LinkedMap,n.func(f.dispose)&&f.dispose(),n.func(p.dispose)&&p.dispose()},listen:()=>{ce(),function(){if(X())throw new R(b.AlreadyListening,"Connection is already listening")}(),z=N.Listening,p.listen(oe)},inspect:()=>{(0,t.default)().console.log("inspect")}};return Ae.onNotification(y.type,e=>{if(j===d.Off||!M)return;const t=j===d.Verbose||j===d.Compact;M.log(e.message,t?e.verbose:void 0)}),Ae.onNotification(u.type,e=>{const t=T.get(e.token);t?t(e.value):q.fire(e)}),Ae}}(wG)),wG}function _G(){return yG||(yG=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ProgressType=e.ProgressToken=e.createMessageConnection=e.NullLogger=e.ConnectionOptions=e.ConnectionStrategy=e.AbstractMessageBuffer=e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=e.CancellationToken=e.CancellationTokenSource=e.Emitter=e.Event=e.Disposable=e.LRUCache=e.Touch=e.LinkedMap=e.ParameterStructures=e.NotificationType9=e.NotificationType8=e.NotificationType7=e.NotificationType6=e.NotificationType5=e.NotificationType4=e.NotificationType3=e.NotificationType2=e.NotificationType1=e.NotificationType0=e.NotificationType=e.ErrorCodes=e.ResponseError=e.RequestType9=e.RequestType8=e.RequestType7=e.RequestType6=e.RequestType5=e.RequestType4=e.RequestType3=e.RequestType2=e.RequestType1=e.RequestType0=e.RequestType=e.Message=e.RAL=void 0,e.MessageStrategy=e.CancellationStrategy=e.CancellationSenderStrategy=e.CancellationReceiverStrategy=e.ConnectionError=e.ConnectionErrors=e.LogTraceNotification=e.SetTraceNotification=e.TraceFormat=e.TraceValues=e.Trace=void 0;const t=Hz();Object.defineProperty(e,"Message",{enumerable:!0,get:function(){return t.Message}}),Object.defineProperty(e,"RequestType",{enumerable:!0,get:function(){return t.RequestType}}),Object.defineProperty(e,"RequestType0",{enumerable:!0,get:function(){return t.RequestType0}}),Object.defineProperty(e,"RequestType1",{enumerable:!0,get:function(){return t.RequestType1}}),Object.defineProperty(e,"RequestType2",{enumerable:!0,get:function(){return t.RequestType2}}),Object.defineProperty(e,"RequestType3",{enumerable:!0,get:function(){return t.RequestType3}}),Object.defineProperty(e,"RequestType4",{enumerable:!0,get:function(){return t.RequestType4}}),Object.defineProperty(e,"RequestType5",{enumerable:!0,get:function(){return t.RequestType5}}),Object.defineProperty(e,"RequestType6",{enumerable:!0,get:function(){return t.RequestType6}}),Object.defineProperty(e,"RequestType7",{enumerable:!0,get:function(){return t.RequestType7}}),Object.defineProperty(e,"RequestType8",{enumerable:!0,get:function(){return t.RequestType8}}),Object.defineProperty(e,"RequestType9",{enumerable:!0,get:function(){return t.RequestType9}}),Object.defineProperty(e,"ResponseError",{enumerable:!0,get:function(){return t.ResponseError}}),Object.defineProperty(e,"ErrorCodes",{enumerable:!0,get:function(){return t.ErrorCodes}}),Object.defineProperty(e,"NotificationType",{enumerable:!0,get:function(){return t.NotificationType}}),Object.defineProperty(e,"NotificationType0",{enumerable:!0,get:function(){return t.NotificationType0}}),Object.defineProperty(e,"NotificationType1",{enumerable:!0,get:function(){return t.NotificationType1}}),Object.defineProperty(e,"NotificationType2",{enumerable:!0,get:function(){return t.NotificationType2}}),Object.defineProperty(e,"NotificationType3",{enumerable:!0,get:function(){return t.NotificationType3}}),Object.defineProperty(e,"NotificationType4",{enumerable:!0,get:function(){return t.NotificationType4}}),Object.defineProperty(e,"NotificationType5",{enumerable:!0,get:function(){return t.NotificationType5}}),Object.defineProperty(e,"NotificationType6",{enumerable:!0,get:function(){return t.NotificationType6}}),Object.defineProperty(e,"NotificationType7",{enumerable:!0,get:function(){return t.NotificationType7}}),Object.defineProperty(e,"NotificationType8",{enumerable:!0,get:function(){return t.NotificationType8}}),Object.defineProperty(e,"NotificationType9",{enumerable:!0,get:function(){return t.NotificationType9}}),Object.defineProperty(e,"ParameterStructures",{enumerable:!0,get:function(){return t.ParameterStructures}});const n=Jz();Object.defineProperty(e,"LinkedMap",{enumerable:!0,get:function(){return n.LinkedMap}}),Object.defineProperty(e,"LRUCache",{enumerable:!0,get:function(){return n.LRUCache}}),Object.defineProperty(e,"Touch",{enumerable:!0,get:function(){return n.Touch}});const r=(Kz||(Kz=1,Object.defineProperty(Zz,"__esModule",{value:!0}),Zz.Disposable=void 0,(i||(Zz.Disposable=i={})).create=function(e){return{dispose:e}}),Zz);var i;Object.defineProperty(e,"Disposable",{enumerable:!0,get:function(){return r.Disposable}});const o=nG();Object.defineProperty(e,"Event",{enumerable:!0,get:function(){return o.Event}}),Object.defineProperty(e,"Emitter",{enumerable:!0,get:function(){return o.Emitter}});const s=oG();Object.defineProperty(e,"CancellationTokenSource",{enumerable:!0,get:function(){return s.CancellationTokenSource}}),Object.defineProperty(e,"CancellationToken",{enumerable:!0,get:function(){return s.CancellationToken}});const a=function(){if(sG)return aG;sG=1,Object.defineProperty(aG,"__esModule",{value:!0}),aG.SharedArrayReceiverStrategy=aG.SharedArraySenderStrategy=void 0;const e=oG();var t,n;(n=t||(t={})).Continue=0,n.Cancelled=1,aG.SharedArraySenderStrategy=class{constructor(){this.buffers=new Map}enableCancellation(e){if(null===e.id)return;const n=new SharedArrayBuffer(4);new Int32Array(n,0,1)[0]=t.Continue,this.buffers.set(e.id,n),e.$cancellationData=n}async sendCancellation(e,n){const r=this.buffers.get(n);if(void 0===r)return;const i=new Int32Array(r,0,1);Atomics.store(i,0,t.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};class r{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===t.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}}class i{constructor(e){this.token=new r(e)}cancel(){}dispose(){}}return aG.SharedArrayReceiverStrategy=class{constructor(){this.kind="request"}createCancellationTokenSource(t){const n=t.$cancellationData;return void 0===n?new e.CancellationTokenSource:new i(n)}},aG}();Object.defineProperty(e,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return a.SharedArraySenderStrategy}}),Object.defineProperty(e,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return a.SharedArrayReceiverStrategy}});const l=function(){if(uG)return cG;uG=1,Object.defineProperty(cG,"__esModule",{value:!0}),cG.ReadableStreamMessageReader=cG.AbstractMessageReader=cG.MessageReader=void 0;const e=tG(),t=Gz(),n=nG(),r=pG();var i,o;(i||(cG.MessageReader=i={})).is=function(e){let n=e;return n&&t.func(n.listen)&&t.func(n.dispose)&&t.func(n.onError)&&t.func(n.onClose)&&t.func(n.onPartialMessage)};class s{constructor(){this.errorEmitter=new n.Emitter,this.closeEmitter=new n.Emitter,this.partialMessageEmitter=new n.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:new Error(`Reader received error. Reason: ${t.string(e.message)?e.message:"unknown"}`)}}return cG.AbstractMessageReader=s,(o||(o={})).fromOptions=function(t){let n,r;const i=new Map;let o;const s=new Map;if(void 0===t||"string"==typeof t)n=t??"utf-8";else{if(n=t.charset??"utf-8",void 0!==t.contentDecoder&&(r=t.contentDecoder,i.set(r.name,r)),void 0!==t.contentDecoders)for(const e of t.contentDecoders)i.set(e.name,e);if(void 0!==t.contentTypeDecoder&&(o=t.contentTypeDecoder,s.set(o.name,o)),void 0!==t.contentTypeDecoders)for(const e of t.contentTypeDecoders)s.set(e.name,e)}return void 0===o&&(o=(0,e.default)().applicationJson.decoder,s.set(o.name,o)),{charset:n,contentDecoder:r,contentDecoders:i,contentTypeDecoder:o,contentTypeDecoders:s}},cG.ReadableStreamMessageReader=class extends s{constructor(t,n){super(),this.readable=t,this.options=o.fromOptions(n),this.buffer=(0,e.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new r.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;const t=this.readable.onData(e=>{this.onData(e)});return this.readable.onError(e=>this.fireError(e)),this.readable.onClose(()=>this.fireClose()),t}onData(e){try{for(this.buffer.append(e);;){if(-1===this.nextMessageLength){const e=this.buffer.tryReadHeaders(!0);if(!e)return;const t=e.get("content-length");if(!t)return void this.fireError(new Error(`Header must provide a Content-Length property.\n${JSON.stringify(Object.fromEntries(e))}`));const n=parseInt(t);if(isNaN(n))return void this.fireError(new Error(`Content-Length value must be a number. Got ${t}`));this.nextMessageLength=n}const e=this.buffer.tryReadBody(this.nextMessageLength);if(void 0===e)return void this.setPartialMessageTimer();this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{const t=void 0!==this.options.contentDecoder?await this.options.contentDecoder.decode(e):e,n=await this.options.contentTypeDecoder.decode(t,this.options);this.callback(n)}).catch(e=>{this.fireError(e)})}}catch(qK){this.fireError(qK)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),this._partialMessageTimeout<=0||(this.partialMessageTimer=(0,e.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}},cG}();Object.defineProperty(e,"MessageReader",{enumerable:!0,get:function(){return l.MessageReader}}),Object.defineProperty(e,"AbstractMessageReader",{enumerable:!0,get:function(){return l.AbstractMessageReader}}),Object.defineProperty(e,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return l.ReadableStreamMessageReader}});const u=function(){if(fG)return hG;fG=1,Object.defineProperty(hG,"__esModule",{value:!0}),hG.WriteableStreamMessageWriter=hG.AbstractMessageWriter=hG.MessageWriter=void 0;const e=tG(),t=Gz(),n=pG(),r=nG();var i,o;(i||(hG.MessageWriter=i={})).is=function(e){let n=e;return n&&t.func(n.dispose)&&t.func(n.onClose)&&t.func(n.onError)&&t.func(n.write)};class s{constructor(){this.errorEmitter=new r.Emitter,this.closeEmitter=new r.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,n){this.errorEmitter.fire([this.asError(e),t,n])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:new Error(`Writer received error. Reason: ${t.string(e.message)?e.message:"unknown"}`)}}return hG.AbstractMessageWriter=s,(o||(o={})).fromOptions=function(t){return void 0===t||"string"==typeof t?{charset:t??"utf-8",contentTypeEncoder:(0,e.default)().applicationJson.encoder}:{charset:t.charset??"utf-8",contentEncoder:t.contentEncoder,contentTypeEncoder:t.contentTypeEncoder??(0,e.default)().applicationJson.encoder}},hG.WriteableStreamMessageWriter=class extends s{constructor(e,t){super(),this.writable=e,this.options=o.fromOptions(t),this.errorCount=0,this.writeSemaphore=new n.Semaphore(1),this.writable.onError(e=>this.fireError(e)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(e=>void 0!==this.options.contentEncoder?this.options.contentEncoder.encode(e):e).then(t=>{const n=[];return n.push("Content-Length: ",t.byteLength.toString(),"\r\n"),n.push("\r\n"),this.doWrite(e,n,t)},e=>{throw this.fireError(e),e}))}async doWrite(e,t,n){try{return await this.writable.write(t.join(""),"ascii"),this.writable.write(n)}catch(qK){return this.handleError(qK,e),Promise.reject(qK)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){this.writable.end()}},hG}();Object.defineProperty(e,"MessageWriter",{enumerable:!0,get:function(){return u.MessageWriter}}),Object.defineProperty(e,"AbstractMessageWriter",{enumerable:!0,get:function(){return u.AbstractMessageWriter}}),Object.defineProperty(e,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return u.WriteableStreamMessageWriter}});const c=(gG||(gG=1,Object.defineProperty(AG,"__esModule",{value:!0}),AG.AbstractMessageBuffer=void 0,AG.AbstractMessageBuffer=class{constructor(e="utf-8"){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){const t="string"==typeof e?this.fromString(e,this._encoding):e;this._chunks.push(t),this._totalLength+=t.byteLength}tryReadHeaders(e=!1){if(0===this._chunks.length)return;let t=0,n=0,r=0,i=0;e:for(;n<this._chunks.length;){const e=this._chunks[n];for(r=0;r<e.length;){switch(e[r]){case 13:switch(t){case 0:t=1;break;case 2:t=3;break;default:t=0}break;case 10:switch(t){case 1:t=2;break;case 3:t=4,r++;break e;default:t=0}break;default:t=0}r++}i+=e.byteLength,n++}if(4!==t)return;const o=this._read(i+r),s=new Map,a=this.toString(o,"ascii").split("\r\n");if(a.length<2)return s;for(let l=0;l<a.length-2;l++){const t=a[l],n=t.indexOf(":");if(-1===n)throw new Error(`Message header must separate key and value using ':'\n${t}`);const r=t.substr(0,n),i=t.substr(n+1).trim();s.set(e?r.toLowerCase():r,i)}return s}tryReadBody(e){if(!(this._totalLength<e))return this._read(e)}get numberOfBytes(){return this._totalLength}_read(e){if(0===e)return this.emptyBuffer();if(e>this._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===e){const t=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(t)}if(this._chunks[0].byteLength>e){const t=this._chunks[0],n=this.asNative(t,e);return this._chunks[0]=t.slice(e),this._totalLength-=e,n}const t=this.allocNative(e);let n=0;for(;e>0;){const r=this._chunks[0];if(r.byteLength>e){const i=r.slice(0,e);t.set(i,n),n+=e,this._chunks[0]=r.slice(e),this._totalLength-=e,e-=e}else t.set(r,n),n+=r.byteLength,this._chunks.shift(),this._totalLength-=r.byteLength,e-=r.byteLength}return t}}),AG);Object.defineProperty(e,"AbstractMessageBuffer",{enumerable:!0,get:function(){return c.AbstractMessageBuffer}});const d=CG();Object.defineProperty(e,"ConnectionStrategy",{enumerable:!0,get:function(){return d.ConnectionStrategy}}),Object.defineProperty(e,"ConnectionOptions",{enumerable:!0,get:function(){return d.ConnectionOptions}}),Object.defineProperty(e,"NullLogger",{enumerable:!0,get:function(){return d.NullLogger}}),Object.defineProperty(e,"createMessageConnection",{enumerable:!0,get:function(){return d.createMessageConnection}}),Object.defineProperty(e,"ProgressToken",{enumerable:!0,get:function(){return d.ProgressToken}}),Object.defineProperty(e,"ProgressType",{enumerable:!0,get:function(){return d.ProgressType}}),Object.defineProperty(e,"Trace",{enumerable:!0,get:function(){return d.Trace}}),Object.defineProperty(e,"TraceValues",{enumerable:!0,get:function(){return d.TraceValues}}),Object.defineProperty(e,"TraceFormat",{enumerable:!0,get:function(){return d.TraceFormat}}),Object.defineProperty(e,"SetTraceNotification",{enumerable:!0,get:function(){return d.SetTraceNotification}}),Object.defineProperty(e,"LogTraceNotification",{enumerable:!0,get:function(){return d.LogTraceNotification}}),Object.defineProperty(e,"ConnectionErrors",{enumerable:!0,get:function(){return d.ConnectionErrors}}),Object.defineProperty(e,"ConnectionError",{enumerable:!0,get:function(){return d.ConnectionError}}),Object.defineProperty(e,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return d.CancellationReceiverStrategy}}),Object.defineProperty(e,"CancellationSenderStrategy",{enumerable:!0,get:function(){return d.CancellationSenderStrategy}}),Object.defineProperty(e,"CancellationStrategy",{enumerable:!0,get:function(){return d.CancellationStrategy}}),Object.defineProperty(e,"MessageStrategy",{enumerable:!0,get:function(){return d.MessageStrategy}});const p=tG();e.RAL=p.default}(jz)),jz}function BG(){return vG||(vG=1,function(e){var t=Lz&&Lz.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),n=Lz&&Lz.__exportStar||function(e,n){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(n,r)||t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.createMessageConnection=e.createServerSocketTransport=e.createClientSocketTransport=e.createServerPipeTransport=e.createClientPipeTransport=e.generateRandomPipeName=e.StreamMessageWriter=e.StreamMessageReader=e.SocketMessageWriter=e.SocketMessageReader=e.PortMessageWriter=e.PortMessageReader=e.IPCMessageWriter=e.IPCMessageReader=void 0;const r=function(){if(bG)return Pz;bG=1,Object.defineProperty(Pz,"__esModule",{value:!0});const e=L,t=_G();class n extends t.AbstractMessageBuffer{constructor(e="utf-8"){super(e)}emptyBuffer(){return n.emptyBuffer}fromString(e,t){return Buffer.from(e,t)}toString(t,n){return t instanceof Buffer?t.toString(n):new e.TextDecoder(n).decode(t)}asNative(e,t){return void 0===t?e instanceof Buffer?e:Buffer.from(e):e instanceof Buffer?e.slice(0,t):Buffer.from(e,0,t)}allocNative(e){return Buffer.allocUnsafe(e)}}n.emptyBuffer=Buffer.allocUnsafe(0);class r{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),t.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),t.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),t.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),t.Disposable.create(()=>this.stream.off("data",e))}}class i{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),t.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),t.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),t.Disposable.create(()=>this.stream.off("end",e))}write(e,t){return new Promise((n,r)=>{const i=e=>{null==e?n():r(e)};"string"==typeof e?this.stream.write(e,t,i):this.stream.write(e,i)})}end(){this.stream.end()}}const o=Object.freeze({messageBuffer:Object.freeze({create:e=>new n(e)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(e,t)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(e,void 0,0),t.charset))}catch(n){return Promise.reject(n)}}}),decoder:Object.freeze({name:"application/json",decode:(t,n)=>{try{return t instanceof Buffer?Promise.resolve(JSON.parse(t.toString(n.charset))):Promise.resolve(JSON.parse(new e.TextDecoder(n.charset).decode(t)))}catch(r){return Promise.reject(r)}}})}),stream:Object.freeze({asReadableStream:e=>new r(e),asWritableStream:e=>new i(e)}),console:console,timer:Object.freeze({setTimeout(e,t,...n){const r=setTimeout(e,t,...n);return{dispose:()=>clearTimeout(r)}},setImmediate(e,...t){const n=setImmediate(e,...t);return{dispose:()=>clearImmediate(n)}},setInterval(e,t,...n){const r=setInterval(e,t,...n);return{dispose:()=>clearInterval(r)}}})});function s(){return o}return(s||(s={})).install=function(){t.RAL.install(o)},Pz.default=s,Pz}();r.default.install();const i=ae,o=G,s=ge,a=De,l=_G();n(_G(),e);class u extends l.AbstractMessageReader{constructor(e){super(),this.process=e;let t=this.process;t.on("error",e=>this.fireError(e)),t.on("close",()=>this.fireClose())}listen(e){return this.process.on("message",e),l.Disposable.create(()=>this.process.off("message",e))}}e.IPCMessageReader=u;class c extends l.AbstractMessageWriter{constructor(e){super(),this.process=e,this.errorCount=0;const t=this.process;t.on("error",e=>this.fireError(e)),t.on("close",()=>this.fireClose)}write(e){try{return"function"==typeof this.process.send&&this.process.send(e,void 0,void 0,t=>{t?(this.errorCount++,this.handleError(t,e)):this.errorCount=0}),Promise.resolve()}catch(qK){return this.handleError(qK,e),Promise.reject(qK)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}}e.IPCMessageWriter=c;class d extends l.AbstractMessageReader{constructor(e){super(),this.onData=new l.Emitter,e.on("close",()=>this.fireClose),e.on("error",e=>this.fireError(e)),e.on("message",e=>{this.onData.fire(e)})}listen(e){return this.onData.event(e)}}e.PortMessageReader=d;class p extends l.AbstractMessageWriter{constructor(e){super(),this.port=e,this.errorCount=0,e.on("close",()=>this.fireClose()),e.on("error",e=>this.fireError(e))}write(e){try{return this.port.postMessage(e),Promise.resolve()}catch(qK){return this.handleError(qK,e),Promise.reject(qK)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}}e.PortMessageWriter=p;class f extends l.ReadableStreamMessageReader{constructor(e,t="utf-8"){super((0,r.default)().stream.asReadableStream(e),t)}}e.SocketMessageReader=f;class h extends l.WriteableStreamMessageWriter{constructor(e,t){super((0,r.default)().stream.asWritableStream(e),t),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}}e.SocketMessageWriter=h;class g extends l.ReadableStreamMessageReader{constructor(e,t){super((0,r.default)().stream.asReadableStream(e),t)}}e.StreamMessageReader=g;class A extends l.WriteableStreamMessageWriter{constructor(e,t){super((0,r.default)().stream.asWritableStream(e),t)}}e.StreamMessageWriter=A;const m=process.env.XDG_RUNTIME_DIR,y=new Map([["linux",107],["darwin",103]]);e.generateRandomPipeName=function(){const e=(0,s.randomBytes)(21).toString("hex");if("win32"===process.platform)return`\\\\.\\pipe\\vscode-jsonrpc-${e}-sock`;let t;t=m?i.join(m,`vscode-ipc-${e}.sock`):i.join(o.tmpdir(),`vscode-${e}.sock`);const n=y.get(process.platform);return void 0!==n&&t.length>n&&(0,r.default)().console.warn(`WARNING: IPC handle "${t}" is longer than ${n} characters.`),t},e.createClientPipeTransport=function(e,t="utf-8"){let n;const r=new Promise((e,t)=>{n=e});return new Promise((i,o)=>{let s=(0,a.createServer)(e=>{s.close(),n([new f(e,t),new h(e,t)])});s.on("error",o),s.listen(e,()=>{s.removeListener("error",o),i({onConnected:()=>r})})})},e.createServerPipeTransport=function(e,t="utf-8"){const n=(0,a.createConnection)(e);return[new f(n,t),new h(n,t)]},e.createClientSocketTransport=function(e,t="utf-8"){let n;const r=new Promise((e,t)=>{n=e});return new Promise((i,o)=>{const s=(0,a.createServer)(e=>{s.close(),n([new f(e,t),new h(e,t)])});s.on("error",o),s.listen(e,"127.0.0.1",()=>{s.removeListener("error",o),i({onConnected:()=>r})})})},e.createServerSocketTransport=function(e,t="utf-8"){const n=(0,a.createConnection)(e,"127.0.0.1");return[new f(n,t),new h(n,t)]},e.createMessageConnection=function(e,t,n,r){n||(n=l.NullLogger);const i=function(e){const t=e;return void 0!==t.read&&void 0!==t.addListener}(e)?new g(e):e,o=function(e){const t=e;return void 0!==t.write&&void 0!==t.addListener}(t)?new A(t):t;return l.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,l.createMessageConnection)(i,o,n,r)}}(Lz)),Lz}var DG=IG?EG:(IG=1,EG=BG());const SG={".c":"c",".cpp":"cpp",".cxx":"cpp",".cc":"cpp",".c++":"cpp",".h":"c",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".h++":"cpp",".rs":"rust"};var kG;(kG||(kG={})).create=async function(e){ex.info(`Starting LSP client for ${e.serverID}`);const t=DG.createMessageConnection(new DG.StreamMessageReader(e.server.process.stdout),new DG.StreamMessageWriter(e.server.process.stdin)),n=new Map;t.onNotification("textDocument/publishDiagnostics",e=>{const t=B(e.uri);ex.info(`Received diagnostics for ${t}`),n.set(t,e.diagnostics)}),t.onRequest("workspace/configuration",async()=>[e.server.initialization??{}]),t.onRequest("window/workDoneProgress/create",()=>null),t.listen(),ex.info(`Sending initialize request to ${e.serverID}`);try{await Promise.race([t.sendRequest("initialize",{rootUri:D(e.root).href,processId:e.server.process.pid,workspaceFolders:[{name:"workspace",uri:D(e.root).href}],initializationOptions:{...e.server.initialization},capabilities:{window:{workDoneProgress:!0},workspace:{configuration:!0},textDocument:{synchronization:{didOpen:!0,didChange:!0},publishDiagnostics:{versionSupport:!0}}}}),new Promise((e,t)=>setTimeout(()=>t(new Error("LSP initialization timeout")),5e3))])}catch(qK){throw ex.error(`Failed to initialize LSP client ${e.serverID}`,qK),t.end(),t.dispose(),e.server.process.kill(),qK}await t.sendNotification("initialized",{}),e.server.initialization&&await t.sendNotification("workspace/didChangeConfiguration",{settings:e.server.initialization}),ex.info(`LSP client initialized for ${e.serverID}`);const r={};return{root:e.root,serverID:e.serverID,connection:t,diagnostics:n,notify:{async open(e){const i=v.isAbsolute(e.path)?e.path:v.resolve(process.cwd(),e.path);try{const e=await import("node:fs/promises").then(e=>e.readFile(i,"utf8")),o=v.extname(i),s=SG[o]??"plaintext",a=r[i];if(void 0!==a){const n=a+1;return r[i]=n,ex.info(`textDocument/didChange for ${i} (v${n})`),void(await t.sendNotification("textDocument/didChange",{textDocument:{uri:D(i).href,version:n},contentChanges:[{text:e}]}))}ex.info(`textDocument/didOpen for ${i}`),n.delete(i),await t.sendNotification("textDocument/didOpen",{textDocument:{uri:D(i).href,languageId:s,version:0,text:e}}),r[i]=0}catch(qK){ex.error(`Failed to open file in LSP: ${i}`,qK)}}},async waitForDiagnostics(e){const t=v.isAbsolute(e.path)?e.path:v.resolve(process.cwd(),e.path);return ex.info(`Waiting for diagnostics for ${t}`),new Promise(e=>{const r=setTimeout(()=>{e()},3e3),i=()=>{n.has(t)?(clearTimeout(r),ex.info(`Got diagnostics for ${t}`),e()):setTimeout(i,100)};i()})},async shutdown(){ex.info(`Shutting down LSP client ${e.serverID}`),t.end(),t.dispose(),e.server.process.kill(),ex.info(`LSP client ${e.serverID} shut down`)}}};const xG={bin:v.join(h.homedir(),".embedder","bin")};var QG,NG={},TG={};var RG,FG={};function MG(){if(RG)return FG;RG=1,Object.defineProperty(FG,"__esModule",{value:!0}),FG.sync=FG.isexe=void 0;const e=J,t=Be;FG.isexe=async(e,r={})=>{const{ignoreErrors:i=!1}=r;try{return n(await(0,t.stat)(e),e,r)}catch(o){const e=o;if(i||"EACCES"===e.code)return!1;throw e}};FG.sync=(t,r={})=>{const{ignoreErrors:i=!1}=r;try{return n((0,e.statSync)(t),t,r)}catch(o){const e=o;if(i||"EACCES"===e.code)return!1;throw e}};const n=(e,t,n)=>e.isFile()&&((e,t)=>{const{pathExt:n=process.env.PATHEXT||""}=t,r=n.split(";");if(-1!==r.indexOf(""))return!0;for(let i=0;i<r.length;i++){const t=r[i].toLowerCase(),n=e.substring(e.length-t.length).toLowerCase();if(t&&n===t)return!0}return!1})(t,n);return FG}var OG,$G,LG,PG,jG={};function UG(){return $G||($G=1,function(e){var t=NG&&NG.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),n=NG&&NG.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=NG&&NG.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},i=NG&&NG.__exportStar||function(e,n){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(n,r)||t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.sync=e.isexe=e.posix=e.win32=void 0;const o=r(function(){if(QG)return TG;QG=1,Object.defineProperty(TG,"__esModule",{value:!0}),TG.sync=TG.isexe=void 0;const e=J,t=Be;TG.isexe=async(e,r={})=>{const{ignoreErrors:i=!1}=r;try{return n(await(0,t.stat)(e),r)}catch(o){const e=o;if(i||"EACCES"===e.code)return!1;throw e}},TG.sync=(t,r={})=>{const{ignoreErrors:i=!1}=r;try{return n((0,e.statSync)(t),r)}catch(o){const e=o;if(i||"EACCES"===e.code)return!1;throw e}};const n=(e,t)=>e.isFile()&&r(e,t),r=(e,t)=>{const n=t.uid??process.getuid?.(),r=t.groups??process.getgroups?.()??[],i=t.gid??process.getgid?.()??r[0];if(void 0===n||void 0===i)throw new Error("cannot get uid or gid");const o=new Set([i,...r]),s=e.mode,a=e.uid,l=e.gid,u=parseInt("100",8),c=parseInt("010",8),d=u|c;return!!(s&parseInt("001",8)||s&c&&o.has(l)||s&u&&a===n||s&d&&0===n)};return TG}());e.posix=o;const s=r(MG());e.win32=s,i((OG||(OG=1,Object.defineProperty(jG,"__esModule",{value:!0})),jG),e);const a="win32"===(process.env._ISEXE_TEST_PLATFORM_||process.platform)?s:o;e.isexe=a.isexe,e.sync=a.sync}(NG)),NG}const zG=e(function(){if(PG)return LG;PG=1;const{isexe:e,sync:t}=UG(),{join:n,delimiter:r,sep:i,posix:o}=ae,s="win32"===process.platform,a=new RegExp(`[${o.sep}${i===o.sep?"":i}]`.replace(/(\\)/g,"\\$1")),l=new RegExp(`^\\.${a.source}`),u=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),c=(e,{path:t=process.env.PATH,pathExt:n=process.env.PATHEXT,delimiter:i=r})=>{const o=e.match(a)?[""]:[...s?[process.cwd()]:[],...(t||"").split(i)];if(s){const t=n||[".EXE",".CMD",".BAT",".COM"].join(i),r=t.split(i).flatMap(e=>[e,e.toLowerCase()]);return e.includes(".")&&""!==r[0]&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:t}}return{pathEnv:o,pathExt:[""]}},d=(e,t)=>{const r=/^".*"$/.test(e)?e.slice(1,-1):e;return(!r&&l.test(t)?t.slice(0,2):"")+n(r,t)},p=async(t,n={})=>{const{pathEnv:r,pathExt:i,pathExtExe:o}=c(t,n),s=[];for(const a of r){const r=d(a,t);for(const t of i){const i=r+t;if(await e(i,{pathExt:o,ignoreErrors:!0})){if(!n.all)return i;s.push(i)}}}if(n.all&&s.length)return s;if(n.nothrow)return null;throw u(t)};return LG=p,p.sync=(e,n={})=>{const{pathEnv:r,pathExt:i,pathExtExe:o}=c(e,n),s=[];for(const a of r){const r=d(a,e);for(const e of i){const i=r+e;if(t(i,{pathExt:o,ignoreErrors:!0})){if(!n.all)return i;s.push(i)}}}if(n.all&&s.length)return s;if(n.nothrow)return null;throw u(e)},LG}());var GG,HG,WG,qG={exports:{}},JG={exports:{}};function KG(){if(HG)return GG;return HG=1,GG=function(e){function t(e){let r,i,o,s=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),o=i-(r||i);n.diff=o,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";s++;const o=t.formatters[i];if("function"==typeof o){const t=e[s];r=o.call(n,t),e.splice(s,1),s--}return r}),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e,t){let n=0,r=0,i=-1,o=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||"*"===t[r]))"*"===t[r]?(i=r,o=n,r++):(n++,r++);else{if(-1===i)return!1;r=i+1,o++,n=o}for(;r<t.length&&"*"===t[r];)r++;return r===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const r of n)"-"===r[0]?t.skips.push(r.slice(1)):t.names.push(r)},t.enabled=function(e){for(const n of t.skips)if(r(e,n))return!1;for(const n of t.names)if(r(e,n))return!0;return!1},t.humanize=tB(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(n=>{t[n]=e[n]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}}var ZG,VG,YG,XG,eH,tH,nH={exports:{}};function rH(){if(XG)return YG;XG=1;const e=G,t=ce,n=VG?ZG:(VG=1,ZG=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return-1!==r&&(-1===i||r<i)}),{env:r}=process;let i;function o(t,{streamIsTTY:o,sniffFlags:s=!0}={}){const a=function(){if("FORCE_COLOR"in r)return"true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(Number.parseInt(r.FORCE_COLOR,10),3)}();void 0!==a&&(i=a);const l=s?i:a;if(0===l)return 0;if(s){if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2}if(t&&!o&&void 0===l)return 0;const u=l||0;if("dumb"===r.TERM)return u;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(e=>e in r)||"codeship"===r.CI_NAME?1:u;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("truecolor"===r.COLORTERM)return 3;if("TERM_PROGRAM"in r){const e=Number.parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:u}function s(e,t={}){return function(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}(o(e,{streamIsTTY:e&&e.isTTY,...t}))}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),YG={supportsColor:s,stdout:s({isTTY:t.isatty(1)}),stderr:s({isTTY:t.isatty(2)})}}function iH(){return eH||(eH=1,function(e,t){const n=ce,r=L;t.init=function(e){e.inspectOpts={};const n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]},t.log=function(...e){return process.stderr.write(r.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(n){const{namespace:r,useColors:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),o=` ${i};1m${r} `;n[0]=o+n[0].split("\n").join("\n"+o),n.push(i+"m+"+e.exports.humanize(this.diff)+"")}else n[0]=function(){if(t.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+r+" "+n[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=rH();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(qK){}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let r=process.env[t];return r=!!/^(yes|on|true|enabled)$/i.test(r)||!/^(no|off|false|disabled)$/i.test(r)&&("null"===r?null:Number(r)),e[n]=r,e},{}),e.exports=KG()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(nH,nH.exports)),nH.exports}function oH(){return tH||(tH=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?qG.exports=(WG||(WG=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))}),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(qK){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(qK){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(qK){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=KG()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(qK){return"[UnexpectedJSONParseError]: "+qK.message}}}(JG,JG.exports)),JG.exports):qG.exports=iH()),qG.exports}var sH,aH,lH,uH,cH,dH,pH,fH,hH,gH,AH={exports:{}},mH={exports:{}};function yH(){if(lH)return mH.exports;lH=1;var e=(aH||(aH=1,sH=function e(t,n){if(t&&n)return e(t)(n);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach(function(e){r[e]=t[e]}),r;function r(){for(var e=new Array(arguments.length),n=0;n<e.length;n++)e[n]=arguments[n];var r=t.apply(this,e),i=e[e.length-1];return"function"==typeof r&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}),sH);function t(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function n(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}return mH.exports=e(t),mH.exports.strict=e(n),t.proto=t(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return t(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return n(this)},configurable:!0})}),mH.exports}function bH(){if(cH)return uH;cH=1;var e=yH(),n=function(){},r=t.Bare?queueMicrotask:process.nextTick.bind(process),i=function(t,o,s){if("function"==typeof o)return i(t,null,o);o||(o={}),s=e(s||n);var a=t._writableState,l=t._readableState,u=o.readable||!1!==o.readable&&t.readable,c=o.writable||!1!==o.writable&&t.writable,d=!1,p=function(){t.writable||f()},f=function(){c=!1,u||s.call(t)},h=function(){u=!1,c||s.call(t)},g=function(e){s.call(t,e?new Error("exited with error code: "+e):null)},A=function(e){s.call(t,e)},m=function(){r(y)},y=function(){if(!d)return(!u||l&&l.ended&&!l.destroyed)&&(!c||a&&a.ended&&!a.destroyed)?void 0:s.call(t,new Error("premature close"))},b=function(){t.req.on("finish",f)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(t)?c&&!a&&(t.on("end",p),t.on("close",p)):(t.on("complete",f),t.on("abort",m),t.req?b():t.on("request",b)),function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length}(t)&&t.on("exit",g),t.on("end",h),t.on("finish",f),!1!==o.error&&t.on("error",A),t.on("close",m),function(){d=!0,t.removeListener("complete",f),t.removeListener("abort",m),t.removeListener("request",b),t.req&&t.req.removeListener("finish",f),t.removeListener("end",p),t.removeListener("close",p),t.removeListener("finish",f),t.removeListener("exit",g),t.removeListener("end",h),t.removeListener("error",A),t.removeListener("close",m)}};return uH=i}function vH(){if(pH)return dH;pH=1;var e,t=yH(),n=bH();try{e=require("fs")}catch(u){}var r=function(){},i="undefined"!=typeof process&&/^v?\.0/.test(process.version),o=function(e){return"function"==typeof e},s=function(s,a,l,u){u=t(u);var c=!1;s.on("close",function(){c=!0}),n(s,{readable:a,writable:l},function(e){if(e)return u(e);c=!0,u()});var d=!1;return function(t){if(!c&&!d)return d=!0,function(t){return!!i&&!!e&&(t instanceof(e.ReadStream||r)||t instanceof(e.WriteStream||r))&&o(t.close)}(s)?s.close(r):function(e){return e.setHeader&&o(e.abort)}(s)?s.abort():o(s.destroy)?s.destroy():void u(t||new Error("stream was destroyed"))}},a=function(e){e()},l=function(e,t){return e.pipe(t)};return dH=function(){var e,t=Array.prototype.slice.call(arguments),n=o(t[t.length-1]||r)&&t.pop()||r;if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new Error("pump requires two streams per minimum");var i=t.map(function(r,o){var l=o<t.length-1;return s(r,l,o>0,function(t){e||(e=t),t&&i.forEach(a),l||(i.forEach(a),n(e))})});return t.reduce(l)},dH}function EH(){if(gH)return AH.exports;gH=1;const{constants:e}=U,t=vH(),n=function(){if(hH)return fH;hH=1;const{PassThrough:e}=j;return fH=t=>{t={...t};const{array:n}=t;let{encoding:r}=t;const i="buffer"===r;let o=!1;n?o=!(r||i):r=r||"utf8",i&&(r=null);const s=new e({objectMode:o});r&&s.setEncoding(r);let a=0;const l=[];return s.on("data",e=>{l.push(e),o?a=l.length:a+=e.length}),s.getBufferedValue=()=>n?l:i?Buffer.concat(l,a):l.join(""),s.getBufferedLength=()=>a,s}}();class r extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function i(i,o){if(!i)return Promise.reject(new Error("Expected a stream"));o={maxBuffer:1/0,...o};const{maxBuffer:s}=o;let a;return await new Promise((l,u)=>{const c=t=>{t&&a.getBufferedLength()<=e.MAX_LENGTH&&(t.bufferedData=a.getBufferedValue()),u(t)};a=t(i,n(o),e=>{e?c(e):l()}),a.on("data",()=>{a.getBufferedLength()>s&&c(new r)})}),a.getBufferedValue()}return AH.exports=i,AH.exports.default=i,AH.exports.buffer=(e,t)=>i(e,{...t,encoding:"buffer"}),AH.exports.array=(e,t)=>i(e,{...t,array:!0}),AH.exports.MaxBufferError=r,AH.exports}var IH,wH,CH,_H,BH,DH,SH,kH,xH={},QH={};function NH(){if(CH)return QH;CH=1;var e=J,t=L,n=j,r=n.Readable,i=n.Writable,o=n.PassThrough,s=function(){if(wH)return IH;function e(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}function t(e){e.pending+=1;var t=!1;return function(i){if(t)throw new Error("callback called twice");if(t=!0,e.error=e.error||i,e.pending-=1,e.waiting.length>0&&e.pending<e.max)n(e,e.waiting.shift());else if(0===e.pending){var o=e.listeners;e.listeners=[],o.forEach(r)}};function r(t){t(e.error)}}function n(e,n){n(t(e))}return wH=1,IH=e,e.prototype.go=function(e){this.pending<this.max?n(this,e):this.waiting.push(e)},e.prototype.wait=function(e){0===this.pending?e(this.error):this.listeners.push(e)},e.prototype.hold=function(){return t(this)},IH}(),a=z.EventEmitter;function l(e,t){t=t||{},a.call(this),this.fd=e,this.pend=new s,this.pend.max=1,this.refCount=0,this.autoClose=!!t.autoClose}function u(e,t){t=t||{},r.call(this,t),this.context=e,this.context.ref(),this.start=t.start||0,this.endOffset=t.end,this.pos=this.start,this.destroyed=!1}function c(e,t){t=t||{},i.call(this,t),this.context=e,this.context.ref(),this.start=t.start||0,this.endOffset=null==t.end?1/0:+t.end,this.bytesWritten=0,this.pos=this.start,this.destroyed=!1,this.on("finish",this.destroy.bind(this))}function d(e,t){a.call(this),t=t||{},this.refCount=0,this.buffer=e,this.maxChunkSize=t.maxChunkSize||Number.MAX_SAFE_INTEGER}return QH.createFromBuffer=function(e,t){return new d(e,t)},QH.createFromFd=function(e,t){return new l(e,t)},QH.BufferSlicer=d,QH.FdSlicer=l,t.inherits(l,a),l.prototype.read=function(t,n,r,i,o){var s=this;s.pend.go(function(a){e.read(s.fd,t,n,r,i,function(e,t,n){a(),o(e,t,n)})})},l.prototype.write=function(t,n,r,i,o){var s=this;s.pend.go(function(a){e.write(s.fd,t,n,r,i,function(e,t,n){a(),o(e,t,n)})})},l.prototype.createReadStream=function(e){return new u(this,e)},l.prototype.createWriteStream=function(e){return new c(this,e)},l.prototype.ref=function(){this.refCount+=1},l.prototype.unref=function(){var t=this;if(t.refCount-=1,!(t.refCount>0)){if(t.refCount<0)throw new Error("invalid unref");t.autoClose&&e.close(t.fd,function(e){e?t.emit("error",e):t.emit("close")})}},t.inherits(u,r),u.prototype._read=function(t){var n=this;if(!n.destroyed){var r=Math.min(n._readableState.highWaterMark,t);if(null!=n.endOffset&&(r=Math.min(r,n.endOffset-n.pos)),r<=0)return n.destroyed=!0,n.push(null),void n.context.unref();n.context.pend.go(function(t){if(n.destroyed)return t();var i=new Buffer(r);e.read(n.context.fd,i,0,r,n.pos,function(e,r){e?n.destroy(e):0===r?(n.destroyed=!0,n.push(null),n.context.unref()):(n.pos+=r,n.push(i.slice(0,r))),t()})})}},u.prototype.destroy=function(e){this.destroyed||(e=e||new Error("stream destroyed"),this.destroyed=!0,this.emit("error",e),this.context.unref())},t.inherits(c,i),c.prototype._write=function(t,n,r){var i=this;if(!i.destroyed){if(i.pos+t.length>i.endOffset){var o=new Error("maximum file length exceeded");return o.code="ETOOBIG",i.destroy(),void r(o)}i.context.pend.go(function(n){if(i.destroyed)return n();e.write(i.context.fd,t,0,t.length,i.pos,function(e,t){e?(i.destroy(),n(),r(e)):(i.bytesWritten+=t,i.pos+=t,i.emit("progress"),n(),r())})})}},c.prototype.destroy=function(){this.destroyed||(this.destroyed=!0,this.context.unref())},t.inherits(d,a),d.prototype.read=function(e,t,n,r,i){var o=r+n,s=o-this.buffer.length,a=s>0?s:n;this.buffer.copy(e,t,r,o),setImmediate(function(){i(null,a)})},d.prototype.write=function(e,t,n,r,i){e.copy(this.buffer,r,t,t+n),setImmediate(function(){i(null,n,e)})},d.prototype.createReadStream=function(e){var t=new o(e=e||{});t.destroyed=!1,t.start=e.start||0,t.endOffset=e.end,t.pos=t.endOffset||this.buffer.length;for(var n=this.buffer.slice(t.start,t.pos),r=0;;){var i=r+this.maxChunkSize;if(i>=n.length){r<n.length&&t.write(n.slice(r,n.length));break}t.write(n.slice(r,i)),r=i}return t.end(),t.destroy=function(){t.destroyed=!0},t},d.prototype.createWriteStream=function(e){var t=this,n=new i(e=e||{});return n.start=e.start||0,n.endOffset=null==e.end?this.buffer.length:+e.end,n.bytesWritten=0,n.pos=n.start,n.destroyed=!1,n._write=function(e,r,i){if(!n.destroyed){var o=n.pos+e.length;if(o>n.endOffset){var s=new Error("maximum file length exceeded");return s.code="ETOOBIG",n.destroyed=!0,void i(s)}e.copy(t.buffer,n.pos,0,e.length),n.bytesWritten+=e.length,n.pos=o,n.emit("progress"),i()}},n.destroy=function(){n.destroyed=!0},n},d.prototype.ref=function(){this.refCount+=1},d.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw new Error("invalid unref")},QH}function TH(){if(BH)return _H;BH=1;var e=U.Buffer,t=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];function n(t){if(e.isBuffer(t))return t;var n="function"==typeof e.alloc&&"function"==typeof e.from;if("number"==typeof t)return n?e.alloc(t):new e(t);if("string"==typeof t)return n?e.from(t):new e(t);throw new Error("input must be buffer, number, or string, received "+typeof t)}function r(r,i){r=n(r),e.isBuffer(i)&&(i=i.readUInt32BE(0));for(var o=-1^i,s=0;s<r.length;s++)o=t[255&(o^r[s])]^o>>>8;return-1^o}function i(){return e=r.apply(null,arguments),(t=n(4)).writeInt32BE(e,0),t;var e,t}return"undefined"!=typeof Int32Array&&(t=new Int32Array(t)),i.signed=function(){return r.apply(null,arguments)},i.unsigned=function(){return r.apply(null,arguments)>>>0},_H=i}var RH=function(){if(kH)return SH;kH=1;const e=oH()("extract-zip"),{createWriteStream:t,promises:n}=J,r=EH(),i=ae,{promisify:o}=L,s=j,a=function(){if(DH)return xH;DH=1;var e=J,t=ue,n=NH(),r=TH(),i=L,o=z.EventEmitter,s=j.Transform,a=j.PassThrough,l=j.Writable;function u(t,r,i){"function"==typeof r&&(i=r,r=null),null==r&&(r={}),null==r.autoClose&&(r.autoClose=!1),null==r.lazyEntries&&(r.lazyEntries=!1),null==r.decodeStrings&&(r.decodeStrings=!0),null==r.validateEntrySizes&&(r.validateEntrySizes=!0),null==r.strictFileNames&&(r.strictFileNames=!1),null==i&&(i=_),e.fstat(t,function(e,o){if(e)return i(e);c(n.createFromFd(t,{autoClose:!0}),o.size,r,i)})}function c(e,t,n,r){"function"==typeof n&&(r=n,n=null),null==n&&(n={}),null==n.autoClose&&(n.autoClose=!0),null==n.lazyEntries&&(n.lazyEntries=!1),null==n.decodeStrings&&(n.decodeStrings=!0);var i=!!n.decodeStrings;if(null==n.validateEntrySizes&&(n.validateEntrySizes=!0),null==n.strictFileNames&&(n.strictFileNames=!1),null==r&&(r=_),"number"!=typeof t)throw new Error("expected totalSize parameter to be a number");if(t>Number.MAX_SAFE_INTEGER)throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");e.ref();var o=Math.min(65557,t),s=E(o),a=t-s.length;m(e,s,0,o,a,function(l){if(l)return r(l);for(var u=o-22;u>=0;u-=1)if(101010256===s.readUInt32LE(u)){var c=s.slice(u),p=c.readUInt16LE(4);if(0!==p)return r(new Error("multi-disk zip files are not supported: found disk number: "+p));var f=c.readUInt16LE(10),h=c.readUInt32LE(16),g=c.readUInt16LE(20),A=c.length-22;if(g!==A)return r(new Error("invalid comment length. expected: "+A+". found: "+g));var y=i?w(c,22,c.length,!1):c.slice(22);if(65535!==f&&4294967295!==h)return r(null,new d(e,h,t,f,y,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames));var b=E(20),v=a+u-b.length;return void m(e,b,0,b.length,v,function(o){if(o)return r(o);if(117853008!==b.readUInt32LE(0))return r(new Error("invalid zip64 end of central directory locator signature"));var s=C(b,8),a=E(56);m(e,a,0,a.length,s,function(o){return o?r(o):101075792!==a.readUInt32LE(0)?r(new Error("invalid zip64 end of central directory record signature")):(f=C(a,32),h=C(a,48),r(null,new d(e,h,t,f,y,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames)))})})}r(new Error("end of central directory record signature not found"))})}function d(e,t,n,r,i,s,a,l,u,c){var d=this;o.call(d),d.reader=e,d.reader.on("error",function(e){f(d,e)}),d.reader.once("close",function(){d.emit("close")}),d.readEntryCursor=t,d.fileSize=n,d.entryCount=r,d.comment=i,d.entriesRead=0,d.autoClose=!!s,d.lazyEntries=!!a,d.decodeStrings=!!l,d.validateEntrySizes=!!u,d.strictFileNames=!!c,d.isOpen=!0,d.emittedError=!1,d.lazyEntries||d._readEntry()}function p(e,t){e.autoClose&&e.close(),f(e,t)}function f(e,t){e.emittedError||(e.emittedError=!0,e.emit("error",t))}function h(){}function g(e,t){return new Date(1980+(e>>9&127),(e>>5&15)-1,31&e,t>>11&31,t>>5&63,2*(31&t),0)}function A(e){return-1!==e.indexOf("\\")?"invalid characters in fileName: "+e:/^[a-zA-Z]:/.test(e)||/^\//.test(e)?"absolute path: "+e:-1!==e.split("/").indexOf("..")?"invalid relative path: "+e:null}function m(e,t,n,r,i,o){if(0===r)return setImmediate(function(){o(null,E(0))});e.read(t,n,r,i,function(e,t){return e?o(e):t<r?o(new Error("unexpected EOF")):void o()})}function y(e){s.call(this),this.actualByteCount=0,this.expectedByteCount=e}function b(){o.call(this),this.refCount=0}function v(e){a.call(this),this.context=e,this.context.ref(),this.unreffedYet=!1}xH.open=function(t,n,r){"function"==typeof n&&(r=n,n=null),null==n&&(n={}),null==n.autoClose&&(n.autoClose=!0),null==n.lazyEntries&&(n.lazyEntries=!1),null==n.decodeStrings&&(n.decodeStrings=!0),null==n.validateEntrySizes&&(n.validateEntrySizes=!0),null==n.strictFileNames&&(n.strictFileNames=!1),null==r&&(r=_),e.open(t,"r",function(t,i){if(t)return r(t);u(i,n,function(t,n){t&&e.close(i,_),r(t,n)})})},xH.fromFd=u,xH.fromBuffer=function(e,t,r){"function"==typeof t&&(r=t,t=null),null==t&&(t={}),t.autoClose=!1,null==t.lazyEntries&&(t.lazyEntries=!1),null==t.decodeStrings&&(t.decodeStrings=!0),null==t.validateEntrySizes&&(t.validateEntrySizes=!0),null==t.strictFileNames&&(t.strictFileNames=!1),c(n.createFromBuffer(e,{maxChunkSize:65536}),e.length,t,r)},xH.fromRandomAccessReader=c,xH.dosDateTimeToDate=g,xH.validateFileName=A,xH.ZipFile=d,xH.Entry=h,xH.RandomAccessReader=b,i.inherits(d,o),d.prototype.close=function(){this.isOpen&&(this.isOpen=!1,this.reader.unref())},d.prototype.readEntry=function(){if(!this.lazyEntries)throw new Error("readEntry() called without lazyEntries:true");this._readEntry()},d.prototype._readEntry=function(){var e=this;if(e.entryCount!==e.entriesRead){if(!e.emittedError){var t=E(46);m(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return p(e,n);if(!e.emittedError){var i=new h,o=t.readUInt32LE(0);if(33639248!==o)return p(e,new Error("invalid central directory file header signature: 0x"+o.toString(16)));if(i.versionMadeBy=t.readUInt16LE(4),i.versionNeededToExtract=t.readUInt16LE(6),i.generalPurposeBitFlag=t.readUInt16LE(8),i.compressionMethod=t.readUInt16LE(10),i.lastModFileTime=t.readUInt16LE(12),i.lastModFileDate=t.readUInt16LE(14),i.crc32=t.readUInt32LE(16),i.compressedSize=t.readUInt32LE(20),i.uncompressedSize=t.readUInt32LE(24),i.fileNameLength=t.readUInt16LE(28),i.extraFieldLength=t.readUInt16LE(30),i.fileCommentLength=t.readUInt16LE(32),i.internalFileAttributes=t.readUInt16LE(36),i.externalFileAttributes=t.readUInt32LE(38),i.relativeOffsetOfLocalHeader=t.readUInt32LE(42),64&i.generalPurposeBitFlag)return p(e,new Error("strong encryption is not supported"));e.readEntryCursor+=46,t=E(i.fileNameLength+i.extraFieldLength+i.fileCommentLength),m(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return p(e,n);if(!e.emittedError){var o=!!(2048&i.generalPurposeBitFlag);i.fileName=e.decodeStrings?w(t,0,i.fileNameLength,o):t.slice(0,i.fileNameLength);var s=i.fileNameLength+i.extraFieldLength,a=t.slice(i.fileNameLength,s);i.extraFields=[];for(var l=0;l<a.length-3;){var u=a.readUInt16LE(l+0),c=a.readUInt16LE(l+2),d=l+4,f=d+c;if(f>a.length)return p(e,new Error("extra field length exceeds extra field buffer size"));var h=E(c);a.copy(h,0,d,f),i.extraFields.push({id:u,data:h}),l=f}if(i.fileComment=e.decodeStrings?w(t,s,s+i.fileCommentLength,o):t.slice(s,s+i.fileCommentLength),i.comment=i.fileComment,e.readEntryCursor+=t.length,e.entriesRead+=1,4294967295===i.uncompressedSize||4294967295===i.compressedSize||4294967295===i.relativeOffsetOfLocalHeader){var g=null;for(l=0;l<i.extraFields.length;l++)if(1===(y=i.extraFields[l]).id){g=y.data;break}if(null==g)return p(e,new Error("expected zip64 extended information extra field"));var m=0;if(4294967295===i.uncompressedSize){if(m+8>g.length)return p(e,new Error("zip64 extended information extra field does not include uncompressed size"));i.uncompressedSize=C(g,m),m+=8}if(4294967295===i.compressedSize){if(m+8>g.length)return p(e,new Error("zip64 extended information extra field does not include compressed size"));i.compressedSize=C(g,m),m+=8}if(4294967295===i.relativeOffsetOfLocalHeader){if(m+8>g.length)return p(e,new Error("zip64 extended information extra field does not include relative header offset"));i.relativeOffsetOfLocalHeader=C(g,m),m+=8}}if(e.decodeStrings)for(l=0;l<i.extraFields.length;l++){var y;if(28789===(y=i.extraFields[l]).id){if(y.data.length<6)continue;if(1!==y.data.readUInt8(0))continue;var b=y.data.readUInt32LE(1);if(r.unsigned(t.slice(0,i.fileNameLength))!==b)continue;i.fileName=w(y.data,5,y.data.length,!0);break}}if(e.validateEntrySizes&&0===i.compressionMethod){var v=i.uncompressedSize;if(i.isEncrypted()&&(v+=12),i.compressedSize!==v){var I="compressed/uncompressed size mismatch for stored file: "+i.compressedSize+" != "+i.uncompressedSize;return p(e,new Error(I))}}if(e.decodeStrings){e.strictFileNames||(i.fileName=i.fileName.replace(/\\/g,"/"));var _=A(i.fileName,e.validateFileNameOptions);if(null!=_)return p(e,new Error(_))}e.emit("entry",i),e.lazyEntries||e._readEntry()}})}})}}else setImmediate(function(){e.autoClose&&e.close(),e.emittedError||e.emit("end")})},d.prototype.openReadStream=function(e,n,r){var i=this,o=0,s=e.compressedSize;if(null==r)r=n,n={};else{if(null!=n.decrypt){if(!e.isEncrypted())throw new Error("options.decrypt can only be specified for encrypted entries");if(!1!==n.decrypt)throw new Error("invalid options.decrypt value: "+n.decrypt);if(e.isCompressed()&&!1!==n.decompress)throw new Error("entry is encrypted and compressed, and options.decompress !== false")}if(null!=n.decompress){if(!e.isCompressed())throw new Error("options.decompress can only be specified for compressed entries");if(!1!==n.decompress&&!0!==n.decompress)throw new Error("invalid options.decompress value: "+n.decompress)}if(null!=n.start||null!=n.end){if(e.isCompressed()&&!1!==n.decompress)throw new Error("start/end range not allowed for compressed entry without options.decompress === false");if(e.isEncrypted()&&!1!==n.decrypt)throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false")}if(null!=n.start){if((o=n.start)<0)throw new Error("options.start < 0");if(o>e.compressedSize)throw new Error("options.start > entry.compressedSize")}if(null!=n.end){if((s=n.end)<0)throw new Error("options.end < 0");if(s>e.compressedSize)throw new Error("options.end > entry.compressedSize");if(s<o)throw new Error("options.end < options.start")}}if(!i.isOpen)return r(new Error("closed"));if(e.isEncrypted()&&!1!==n.decrypt)return r(new Error("entry is encrypted, and options.decrypt !== false"));i.reader.ref();var a=E(30);m(i.reader,a,0,a.length,e.relativeOffsetOfLocalHeader,function(l){try{if(l)return r(l);var u=a.readUInt32LE(0);if(67324752!==u)return r(new Error("invalid local file header signature: 0x"+u.toString(16)));var c,d=a.readUInt16LE(26),p=a.readUInt16LE(28),f=e.relativeOffsetOfLocalHeader+a.length+d+p;if(0===e.compressionMethod)c=!1;else{if(8!==e.compressionMethod)return r(new Error("unsupported compression method: "+e.compressionMethod));c=null==n.decompress||n.decompress}var h=f,g=h+e.compressedSize;if(0!==e.compressedSize&&g>i.fileSize)return r(new Error("file data overflows file bounds: "+h+" + "+e.compressedSize+" > "+i.fileSize));var A=i.reader.createReadStream({start:h+o,end:h+s}),m=A;if(c){var b=!1,v=t.createInflateRaw();A.on("error",function(e){setImmediate(function(){b||v.emit("error",e)})}),A.pipe(v),i.validateEntrySizes?(m=new y(e.uncompressedSize),v.on("error",function(e){setImmediate(function(){b||m.emit("error",e)})}),v.pipe(m)):m=v,m.destroy=function(){b=!0,v!==m&&v.unpipe(m),A.unpipe(v),A.destroy()}}r(null,m)}finally{i.reader.unref()}})},h.prototype.getLastModDate=function(){return g(this.lastModFileDate,this.lastModFileTime)},h.prototype.isEncrypted=function(){return!!(1&this.generalPurposeBitFlag)},h.prototype.isCompressed=function(){return 8===this.compressionMethod},i.inherits(y,s),y.prototype._transform=function(e,t,n){if(this.actualByteCount+=e.length,this.actualByteCount>this.expectedByteCount){var r="too many bytes in the stream. expected "+this.expectedByteCount+". got at least "+this.actualByteCount;return n(new Error(r))}n(null,e)},y.prototype._flush=function(e){if(this.actualByteCount<this.expectedByteCount){var t="not enough bytes in the stream. expected "+this.expectedByteCount+". got only "+this.actualByteCount;return e(new Error(t))}e()},i.inherits(b,o),b.prototype.ref=function(){this.refCount+=1},b.prototype.unref=function(){var e=this;if(e.refCount-=1,!(e.refCount>0)){if(e.refCount<0)throw new Error("invalid unref");e.close(function(t){if(t)return e.emit("error",t);e.emit("close")})}},b.prototype.createReadStream=function(e){var t=e.start,n=e.end;if(t===n){var r=new a;return setImmediate(function(){r.end()}),r}var i=this._readStreamForRange(t,n),o=!1,s=new v(this);i.on("error",function(e){setImmediate(function(){o||s.emit("error",e)})}),s.destroy=function(){i.unpipe(s),s.unref(),i.destroy()};var l=new y(n-t);return s.on("error",function(e){setImmediate(function(){o||l.emit("error",e)})}),l.destroy=function(){o=!0,s.unpipe(l),s.destroy()},i.pipe(s).pipe(l)},b.prototype._readStreamForRange=function(e,t){throw new Error("not implemented")},b.prototype.read=function(e,t,n,r,i){var o=this.createReadStream({start:r,end:r+n}),s=new l,a=0;s._write=function(n,r,i){n.copy(e,t+a,0,n.length),a+=n.length,i()},s.on("finish",i),o.on("error",function(e){i(e)}),o.pipe(s)},b.prototype.close=function(e){setImmediate(e)},i.inherits(v,a),v.prototype._flush=function(e){this.unref(),e()},v.prototype.unref=function(e){this.unreffedYet||(this.unreffedYet=!0,this.context.unref())};var E,I="\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ";function w(e,t,n,r){if(r)return e.toString("utf8",t,n);for(var i="",o=t;o<n;o++)i+=I[e[o]];return i}function C(e,t){var n=e.readUInt32LE(t);return 4294967296*e.readUInt32LE(t+4)+n}function _(e){if(e)throw e}return E="function"==typeof Buffer.allocUnsafe?function(e){return Buffer.allocUnsafe(e)}:function(e){return new Buffer(e)},xH}(),l=o(a.open),u=o(s.pipeline);class c{constructor(e,t){this.zipPath=e,this.opts=t}async extract(){return e("opening",this.zipPath,"with opts",this.opts),this.zipfile=await l(this.zipPath,{lazyEntries:!0}),this.canceled=!1,new Promise((t,r)=>{this.zipfile.on("error",e=>{this.canceled=!0,r(e)}),this.zipfile.readEntry(),this.zipfile.on("close",()=>{this.canceled||(e("zip extraction complete"),t())}),this.zipfile.on("entry",async t=>{if(this.canceled)return void e("skipping entry",t.fileName,{cancelled:this.canceled});if(e("zipfile entry",t.fileName),t.fileName.startsWith("__MACOSX/"))return void this.zipfile.readEntry();const o=i.dirname(i.join(this.opts.dir,t.fileName));try{await n.mkdir(o,{recursive:!0});const r=await n.realpath(o);if(i.relative(this.opts.dir,r).split(i.sep).includes(".."))throw new Error(`Out of bound path "${r}" found while processing file ${t.fileName}`);await this.extractEntry(t),e("finished processing",t.fileName),this.zipfile.readEntry()}catch(s){this.canceled=!0,this.zipfile.close(),r(s)}})})}async extractEntry(s){if(this.canceled)return void e("skipping entry extraction",s.fileName,{cancelled:this.canceled});this.opts.onEntry&&this.opts.onEntry(s,this.zipfile);const a=i.join(this.opts.dir,s.fileName),l=s.externalFileAttributes>>16&65535,c=40960==(61440&l);let d=16384==(61440&l);!d&&s.fileName.endsWith("/")&&(d=!0);const p=s.versionMadeBy>>8;d||(d=0===p&&16===s.externalFileAttributes),e("extracting entry",{filename:s.fileName,isDir:d,isSymlink:c});const f=511&this.getExtractedMode(l,d),h=d?a:i.dirname(a),g={recursive:!0};if(d&&(g.mode=f),e("mkdir",{dir:h,...g}),await n.mkdir(h,g),d)return;e("opening read stream",a);const A=await o(this.zipfile.openReadStream.bind(this.zipfile))(s);if(c){const t=await r(A);e("creating symlink",t,a),await n.symlink(t,a)}else await u(A,t(a,{mode:f}))}getExtractedMode(e,t){let n=e;return 0===n&&(t?(this.opts.defaultDirMode&&(n=parseInt(this.opts.defaultDirMode,10)),n||(n=493)):(this.opts.defaultFileMode&&(n=parseInt(this.opts.defaultFileMode,10)),n||(n=420))),n}}return SH=async function(t,r){if(e("creating target directory",r.dir),!i.isAbsolute(r.dir))throw new Error("Target directory is expected to be absolute");return await n.mkdir(r.dir,{recursive:!0}),r.dir=await n.realpath(r.dir),new c(t,r).extract()}}();const FH=e(RH);var MH,OH,$H,LH;(OH=MH||(MH={})).Clangd={id:"clangd",root:($H=["compile_commands.json","compile_flags.txt",".clangd","CMakeLists.txt","Makefile"],async e=>{const t=process.cwd();let n=v.dirname(e);for(;n.startsWith(t);){for(const t of $H){const e=v.join(n,t);try{return await N.access(e),n}catch{}}const e=v.dirname(n);if(e===n)break;n=e}return t}),extensions:[".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++"],async spawn(e){let t=null;try{t=await zG("clangd",{nothrow:!0})}catch{t=null}if(!t){ex.info("clangd not found, downloading from GitHub releases");try{await N.mkdir(xG.bin,{recursive:!0});const e=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!e.ok)return void ex.error("Failed to fetch clangd release info");const n=await e.json(),r=process.platform;let i="";if("darwin"===r)i="clangd-mac-";else if("linux"===r)i="clangd-linux-";else{if("win32"!==r)return void ex.error(`Platform ${r} is not supported by clangd auto-download`);i="clangd-windows-"}i+=n.tag_name+".zip";const o=n.assets.find(e=>e.name===i);if(!o)return void ex.error(`Could not find asset ${i} in latest clangd release`);const s=await fetch(o.browser_download_url);if(!s.ok)return void ex.error("Failed to download clangd");const a=v.join(xG.bin,"clangd.zip");await N.writeFile(a,Buffer.from(await s.arrayBuffer())),await FH(a,{dir:xG.bin}),await N.rm(a);const l=v.join(xG.bin,i.replace(".zip",""));t=v.join(l,"bin","clangd"+("win32"===r?".exe":""));try{await N.access(t)}catch{return void ex.error("Failed to extract clangd binary")}"win32"!==r&&await N.chmod(t,493),ex.info("Installed clangd",{bin:t})}catch(qK){return void ex.error("Failed to download/install clangd",qK)}}return{process:x(t,["--background-index","--clang-tidy"],{cwd:e})}}},OH.RustAnalyzer={id:"rust",root:async e=>{const t=process.cwd();let n,r=v.dirname(e);for(;r.startsWith(t);){for(const t of["Cargo.toml","Cargo.lock"]){const e=v.join(r,t);try{await N.access(e),n=r;break}catch{}}if(n)break;const e=v.dirname(r);if(e===r)break;r=e}if(!n)return;let i=n;for(;i.startsWith(t);){const e=v.join(i,"Cargo.toml");try{if((await N.readFile(e,"utf8")).includes("[workspace]"))return i}catch{}const n=v.dirname(i);if(n===i)break;if(i=n,!i.startsWith(t))break}return n},extensions:[".rs"],async spawn(e){let t=null;try{t=await zG("rust-analyzer",{nothrow:!0})}catch{t=null}if(t)return{process:x(t,{cwd:e})};ex.info("rust-analyzer not found in path, please install it via rustup")}},(e=>{let t=null;async function n(){return t||(t={servers:{clangd:MH.Clangd,rust:MH.RustAnalyzer},clients:[],broken:new Set},ex.info("LSP system initialized",{servers:Object.keys(t.servers).join(", ")}),t)}async function r(){return t||await n()}e.init=n,e.touchFile=async function(e,t){const n=await async function(e){const t=await r(),n=v.extname(e)||e,i=[];for(const r of Object.values(t.servers)){if(r.extensions.length&&!r.extensions.includes(n))continue;const o=await r.root(e);if(!o)continue;if(t.broken.has(o+r.id))continue;const s=t.clients.find(e=>e.root===o&&e.serverID===r.id);if(s)i.push(s);else try{const e=await r.spawn(o);if(!e){t.broken.add(o+r.id);continue}ex.info(`Spawned LSP server ${r.id} at ${o}`);const n=await kG.create({serverID:r.id,server:e,root:o});if(!n){t.broken.add(o+r.id),e.process.kill();continue}t.clients.push(n),i.push(n)}catch(qK){t.broken.add(o+r.id),ex.error(`Failed to spawn LSP server ${r.id}`,qK)}}return i}(e);await Promise.all(n.map(async n=>{await n.notify.open({path:e}),t&&await n.waitForDiagnostics({path:e})})).catch(t=>{ex.error("Failed to touch file in LSP",{error:t,file:e})})},e.diagnostics=async function(){const e=await r(),t={};for(const n of e.clients)for(const[e,r]of n.diagnostics.entries()){const n=t[e]||[];n.push(...r),t[e]=n}return t},(e.Diagnostic||(e.Diagnostic={})).pretty=function(e){return`${{1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[e.severity||1]} [${e.range.start.line+1}:${e.range.start.character+1}] ${e.message}`},e.shutdown=async function(){const e=await r();await Promise.all(e.clients.map(e=>e.shutdown())),e.clients=[],ex.info("All LSP clients shut down")}})(LH||(LH={}));const PH=2e3;async function jH(e){const t=se.extname(e).toLowerCase();if(".ts"===t)return"text";if(".svg"===t)return"svg";if([".png",".jpg",".jpeg",".gif",".webp",".bmp",".tiff",".ico"].includes(t))return"image";if([".mp3",".wav",".flac",".aac",".ogg",".m4a"].includes(t))return"audio";if([".mp4",".avi",".mkv",".mov",".wmv",".flv",".webm"].includes(t))return"video";if(".pdf"===t)return"pdf";return[".zip",".tar",".gz",".exe",".dll",".so",".class",".jar",".war",".7z",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".odt",".ods",".odp",".bin",".dat",".obj",".o",".a",".lib",".wasm",".pyc",".pyo"].includes(t)||await async function(e){try{const t=Buffer.alloc(512),n=await q.promises.open(e,"r");try{const{bytesRead:e}=await n.read(t,0,512,0);return t.subarray(0,e).includes(0)}finally{await n.close()}}catch(qK){return!1}}(e)?"binary":"text"}const UH=Mz({metadata:{name:"readFile",displayName:"Read File",description:"Reads and returns the content of a specified file. If the file is large, the content will be truncated. The tool's response will clearly indicate if truncation has occurred and will provide details on how to read more of the file using the 'offset' and 'limit' parameters. Handles text, images (PNG, JPG, GIF, WEBP, SVG, BMP), and PDF files. For text files, it can read specific line ranges.",category:"file",icon:"📖"},inputSchema:ug({absolutePath:mh().describe("The absolute path to the file to read (e.g., '/home/user/project/file.txt'). Relative paths are not supported. You must provide an absolute path."),offset:jh().min(0).optional().describe("Optional: For text files, the 0-based line number to start reading from. Requires 'limit' to be set. Use for paginating through large files."),limit:jh().min(1).optional().describe("Optional: For text files, maximum number of lines to read. Use with 'offset' to paginate through large files. If omitted, reads the entire file (if feasible, up to a default limit).")}),validateParams:({absolutePath:e})=>se.isAbsolute(e)?null:`File path must be absolute, but was relative: ${e}`,getDescription:({absolutePath:e,offset:t,limit:n})=>{const r=se.basename(e);return void 0!==t&&void 0!==n?`Reading ${r} (lines ${t+1}-${t+n})`:`Reading ${r}`},getLocations:({absolutePath:e})=>[{path:e,type:"read"}],execute:async({absolutePath:e,offset:t,limit:n},r)=>{kL.getState().setCurrentFile(e);try{if(!q.existsSync(e))return{success:!1,llmContent:`File not found: ${e}`,returnDisplay:"File not found."};const r=await q.promises.stat(e);if(r.isDirectory())return{success:!1,llmContent:`Path is a directory, not a file: ${e}`,returnDisplay:"Path is a directory."};if(r.size>20971520){const t=(r.size/1048576).toFixed(2);return{success:!1,llmContent:`File size exceeds the 20MB limit: ${e} (${t}MB)`,returnDisplay:`File too large (${t}MB).`}}const i=await jH(e),o=se.basename(e),s=se.extname(e);switch([".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++",".rs"].includes(s)&&LH.touchFile(e,!1).catch(()=>{}),i){case"binary":return{success:!1,llmContent:`Cannot display content of binary file: ${o}`,returnDisplay:`Skipped binary file: ${o}`};case"svg":if(r.size>1048576)return{success:!1,llmContent:`Cannot display content of SVG file larger than 1MB: ${o}`,returnDisplay:`Skipped large SVG file (>1MB): ${o}`};return{success:!0,summary:`Read SVG file: ${o}`,llmContent:await q.promises.readFile(e,"utf8"),returnDisplay:`Read SVG as text: ${o}`,locations:[{path:e,type:"read"}],metadata:{toolParams:{absolutePath:e,offset:t,limit:n}}};case"text":{const r=(await q.promises.readFile(e,"utf8")).split("\n"),i=r.length,s=t||0,a=void 0===n?2e3:n,l=Math.min(s+a,i),u=Math.min(s,i),c=r.slice(u,l);let d=!1;const p=c.map((e,t)=>{const n=(u+t+1).toString().padStart(5," ");return e.length>PH?(d=!0,`${n}| ${e.substring(0,PH)}... [truncated]`):`${n}| ${e}`}),f=l<i,h=f||d;let g="";if(f){g=`\nIMPORTANT: The file content has been truncated.\nStatus: Showing lines ${u+1}-${l} of ${i} total lines.\nAction: To read more of the file, you can use the 'offset' and 'limit' parameters in a subsequent 'read_file' call. For example, to read the next section of the file, use offset: ${t?t+(l-u):l}.\n\n--- FILE CONTENT (truncated) ---\n<file>\n${p.join("\n")}\n</file>`}else d?(g+="[File content partially truncated: some lines exceeded maximum length of 2000 characters.]\n",g+=`<file>\n${p.join("\n")}\n</file>`):g=`<file>\n${p.join("\n")}\n</file>`;const A=h?" (truncated)":"";return{success:!0,summary:`Read ${i} line text file: ${o}${A}`,llmContent:g,returnDisplay:`Read ${i} line text file: ${o}${A}`,locations:[{path:e,type:"read"}],metadata:{lineCount:i,isTruncated:h,startLine:u,endLine:l,toolParams:{absolutePath:e,offset:t,limit:n}}}}case"image":case"pdf":case"audio":case"video":{const s=(await q.promises.readFile(e)).toString("base64"),a=(e=>({".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".tiff":"image/tiff",".pdf":"application/pdf",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".avi":"video/x-msvideo"}[se.extname(e).toLowerCase()]||"application/octet-stream"))(e);return{success:!0,summary:`Read ${i} file: ${o}`,llmContent:`[${i.toUpperCase()} FILE: ${o}]\nMIME Type: ${a}\nFile Size: ${r.size} bytes\nBase64 Data: ${s.substring(0,100)}...(truncated)`,returnDisplay:`Read ${i} file: ${o}`,locations:[{path:e,type:"read"}],metadata:{fileType:i,mimeType:a,fileSize:r.size,base64Data:s,toolParams:{absolutePath:e,offset:t,limit:n}}}}default:return{success:!1,llmContent:`Unhandled file type: ${i}`,returnDisplay:`Skipped unhandled file type: ${o}`}}}catch(qK){const n=qK instanceof Error?qK.message:String(qK),r=se.basename(e);return{success:!1,llmContent:`Error reading file ${r}: ${n}`,returnDisplay:`Error reading file ${r}: ${n}`}}}}),zH=["**/node_modules/**","**/.git/**","**/.vscode/**","**/.idea/**","**/dist/**","**/build/**","**/coverage/**","**/__pycache__/**","**/*.pyc","**/*.pyo","**/*.bin","**/*.exe","**/*.dll","**/*.so","**/*.dylib","**/*.class","**/*.jar","**/*.war","**/*.zip","**/*.tar","**/*.gz","**/*.bz2","**/*.rar","**/*.7z","**/*.doc","**/*.docx","**/*.xls","**/*.xlsx","**/*.ppt","**/*.pptx","**/*.odt","**/*.ods","**/*.odp","**/*.DS_Store","**/.env"],GH=10485760;async function HH(e){try{const t=await _e.stat(e);if(t.size>GH)return{error:`File too large (${(t.size/1024/1024).toFixed(2)}MB > 10MB)`};if(await async function(e){try{const t=Buffer.alloc(512),n=await _e.open(e,"r");try{const{bytesRead:e}=await n.read(t,0,512,0);return t.subarray(0,e).includes(0)}finally{await n.close()}}catch(qK){return!1}}(e))return{error:"File appears to be binary"};const n=(await _e.readFile(e,"utf-8")).split("\n"),r=n.length,i=2e3,o=2e3;if(r<=i&&n.every(e=>e.length<=o)){return{content:n.map((e,t)=>`${(t+1).toString().padStart(5," ")}| ${e}`).join("\n"),isTruncated:!1,originalLineCount:r}}const s=n.slice(0,i).map((e,t)=>{const n=(t+1).toString().padStart(5," ");return e.length>o?`${n}| ${e.substring(0,o)}... [truncated]`:`${n}| ${e}`});return{content:s.join("\n"),isTruncated:!0,originalLineCount:r}}catch(qK){return{error:qK instanceof Error?qK.message:"Failed to read file"}}}function WH(e,t){if(t.includes("**")){const n=t.split("**");if(2===n.length){const t=n[0],r=n[1];if(void 0!==t&&void 0!==r){const n=t.replace(/\*/g,".*"),i=r.replace(/\*/g,".*");return new RegExp(`^${n}.*${i}$`).test(e)}}}return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}async function qH(e,t=[],n=10,r=0){if(r>n)return[];const i=[];try{const o=await _e.readdir(e,{withFileTypes:!0});for(const s of o){const o=se.join(e,s.name),a=o.replace(/\\/g,"/");if(!t.some(e=>WH(a,e)))if(s.isDirectory()){if(s.name.startsWith(".")&&"."!==s.name)continue;const e=await qH(o,t,n,r+1);i.push(...e)}else s.isFile()&&i.push(o)}}catch(qK){}return i}const JH=Mz({metadata:{name:"readManyFiles",displayName:"Read Many Files",description:"Reads content from multiple files specified by paths or glob patterns within the working directory. For text files, it concatenates their content into a single string. It is primarily designed for text-based files. However, it can also process image (e.g., .png, .jpg) and PDF (.pdf) files if their file names or extensions are explicitly included in the 'paths' argument. For these explicitly requested non-text files, their data is read and included in a format suitable for model consumption (e.g., base64 encoded).\n\nThis tool is useful when you need to understand or analyze a collection of files, such as:\n- Getting an overview of a codebase or parts of it (e.g., all TypeScript files in the 'src' directory).\n- Finding where specific functionality is implemented if the user asks broad questions about code.\n- Reviewing documentation files (e.g., all Markdown files in the 'docs' directory).\n- Gathering context from multiple configuration files.\n- When the user asks to \"read all files in X directory\" or \"show me the content of all Y files\".\n\nUse this tool when the user's query implies needing the content of several files simultaneously for context, analysis, or summarization. For text files, it uses default UTF-8 encoding and a '--- {filePath} ---' separator between file contents. The tool inserts a '--- End of content ---' after the last file. Ensure paths are relative to the working directory. Glob patterns like 'src/**/*.js' are supported. Avoid using for single files if a more specific single-file reading tool is available, unless the user specifically requests to process a list containing just one file via this tool. Other binary files (not explicitly requested as image/PDF) are generally skipped. Default excludes apply to common non-text files (except for explicitly requested images/PDFs) and large dependency directories unless 'useDefaultExcludes' is false.",category:"file",icon:"📁"},inputSchema:ug({paths:ag(mh().min(1)).min(1).describe("Required. An array of file paths or glob patterns relative to working directory. Examples: ['src/**/*.ts'], ['README.md', 'docs/']"),include:ag(mh().min(1)).optional().describe('Optional. Additional glob patterns to include. These are merged with `paths`. Example: ["*.test.ts"] to specifically add test files.'),exclude:ag(mh().min(1)).optional().describe('Optional. Glob patterns for files/directories to exclude. Added to default excludes if useDefaultExcludes is true. Example: ["**/*.log", "temp/"]'),recursive:Hh().optional().default(!0).describe("Optional. Whether to search recursively (primarily controlled by `**` in glob patterns). Defaults to true."),useDefaultExcludes:Hh().optional().default(!0).describe("Optional. Whether to apply a list of default exclusion patterns (e.g., node_modules, .git, binary files). Defaults to true."),fileFilteringOptions:ug({respect_git_ignore:Hh().optional().describe("Optional: Whether to respect .gitignore patterns when listing files. Only available in git repositories. Defaults to true."),respect_embedder_ignore:Hh().optional().describe("Optional: Whether to respect .embedderignore patterns when listing files. Defaults to true.")}).optional().describe("Whether to respect ignore patterns from .gitignore or .embedderignore")}),validateParams:e=>{if(!e.paths||0===e.paths.length)return"At least one path must be specified";for(const t of e.paths)if("string"!=typeof t||""===t.trim())return"All paths must be non-empty strings";return null},getDescription:e=>{const t=[...e.paths,...e.include||[]];return`Reading files: ${t.length<=3?t.join(", "):`${t.slice(0,3).join(", ")} and ${t.length-3} more`}`},getLocations:e=>e.paths.map(e=>({path:e,type:"read"})),execute:async(e,t)=>{const{paths:n,include:r=[],exclude:i=[],useDefaultExcludes:o=!0}=e,s=new Set,a=[],l=[],u=[],c=o?[...zH,...i]:[...i],d=[...n,...r];if(0===d.length)return{success:!1,llmContent:"No search paths or include patterns provided.",returnDisplay:"## Information\n\nNo search paths or include patterns were specified. Nothing to read or concatenate."};try{for(const e of d){const n=se.resolve(t.workingDirectory,e);try{const e=await _e.stat(n);if(e.isFile())s.add(n);else if(e.isDirectory()){(await qH(n,c)).forEach(e=>s.add(e))}}catch(qK){if(e.includes("*")){const n=t.workingDirectory,r=await qH(n,c);r.filter(t=>WH(se.relative(n,t).replace(/\\/g,"/"),e)).forEach(e=>s.add(e))}else a.push({path:e,reason:`Path not found: ${qK instanceof Error?qK.message:"Unknown error"}`})}}const n=Array.from(s).sort();for(const e of n){const n=se.relative(t.workingDirectory,e).replace(/\\/g,"/");if(c.some(e=>WH(n,e))){a.push({path:n,reason:"matched exclusion pattern"});continue}const r=await HH(e);if(r.error)a.push({path:n,reason:`Read error: ${r.error}`});else if(void 0!==r.content){const e="--- {filePath} ---".replace("{filePath}",n);let t="";r.isTruncated&&(t+="[WARNING: This file was truncated. To view the full content, use the 'read_file' tool on this specific file.]\n\n"),t+=`<file>\n${r.content}\n</file>`,u.push(`${e}\n\n${t}\n\n`),l.push(n)}}let r="";if(l.length>0){const e=l.length<=3?l.join(", "):`${l.slice(0,3).join(", ")} and ${l.length-3} more`;r=`Successfully read content from ${l.length} file${1!==l.length?"s":""}: ${e}`}else r=a.length>0?`No files could be read (${a.length} skipped)`:"No files found matching criteria";u.length>0&&u.push("\n--- End of content ---");return{success:!0,llmContent:u.length>0?u.join(""):"No files matching the criteria were found or all were skipped.",returnDisplay:r,summary:l.length>0?`Read ${l.length} file${1!==l.length?"s":""}`:"No files read",locations:l.map(e=>({path:e,type:"read"})),metadata:{fileCount:l.length,toolParams:{paths:e.paths,include:e.include,exclude:e.exclude,recursive:e.recursive,useDefaultExcludes:e.useDefaultExcludes,fileFilteringOptions:e.fileFilteringOptions}}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error during file search and reading: ${t}`,returnDisplay:`Error reading files: ${t}`}}}});class KH{diff(e,t,n={}){let r;"function"==typeof n?(r=n,n={}):"callback"in n&&(r=n.callback);const i=this.castInput(e,n),o=this.castInput(t,n),s=this.removeEmpty(this.tokenize(i,n)),a=this.removeEmpty(this.tokenize(o,n));return this.diffWithOptionsObj(s,a,n,r)}diffWithOptionsObj(e,t,n,r){var i;const o=e=>(e=this.postProcess(e,n),r?void setTimeout(function(){r(e)},0):e),s=t.length,a=e.length;let l=1,u=s+a;null!=n.maxEditLength&&(u=Math.min(u,n.maxEditLength));const c=null!==(i=n.timeout)&&void 0!==i?i:1/0,d=Date.now()+c,p=[{oldPos:-1,lastComponent:void 0}];let f=this.extractCommon(p[0],t,e,0,n);if(p[0].oldPos+1>=a&&f+1>=s)return o(this.buildValues(p[0].lastComponent,t,e));let h=-1/0,g=1/0;const A=()=>{for(let r=Math.max(h,-l);r<=Math.min(g,l);r+=2){let i;const l=p[r-1],u=p[r+1];l&&(p[r-1]=void 0);let c=!1;if(u){const e=u.oldPos-r;c=u&&0<=e&&e<s}const d=l&&l.oldPos+1<a;if(c||d){if(i=!d||c&&l.oldPos<u.oldPos?this.addToPath(u,!0,!1,0,n):this.addToPath(l,!1,!0,1,n),f=this.extractCommon(i,t,e,r,n),i.oldPos+1>=a&&f+1>=s)return o(this.buildValues(i.lastComponent,t,e))||!0;p[r]=i,i.oldPos+1>=a&&(g=Math.min(g,r-1)),f+1>=s&&(h=Math.max(h,r+1))}else p[r]=void 0}l++};if(r)!function e(){setTimeout(function(){if(l>u||Date.now()>d)return r(void 0);A()||e()},0)}();else for(;l<=u&&Date.now()<=d;){const e=A();if(e)return e}}addToPath(e,t,n,r,i){const o=e.lastComponent;return o&&!i.oneChangePerToken&&o.added===t&&o.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:o.count+1,added:t,removed:n,previousComponent:o.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:o}}}extractCommon(e,t,n,r,i){const o=t.length,s=n.length;let a=e.oldPos,l=a-r,u=0;for(;l+1<o&&a+1<s&&this.equals(n[a+1],t[l+1],i);)l++,a++,u++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!i.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=a,l}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){const t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join("")}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){const r=[];let i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();const o=r.length;let s=0,a=0,l=0;for(;s<o;s++){const e=r[s];if(e.removed)e.value=this.join(n.slice(l,l+e.count)),l+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(a,a+e.count);r=r.map(function(e,t){const r=n[l+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(a,a+e.count));a+=e.count,e.added||(l+=e.count)}}return r}}const ZH=new class extends KH{constructor(){super(...arguments),this.tokenize=XH}equals(e,t,n){return n.ignoreWhitespace?(n.newlineIsToken&&e.includes("\n")||(e=e.trim()),n.newlineIsToken&&t.includes("\n")||(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith("\n")&&(e=e.slice(0,-1)),t.endsWith("\n")&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function VH(e,t,n){return ZH.diff(e,t,n)}function YH(e,t,n){return n=function(e,t){if("function"==typeof e)t.callback=e;else if(e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}(n,{ignoreWhitespace:!0}),ZH.diff(e,t,n)}function XH(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,"\n"));const n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let i=0;i<r.length;i++){const e=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=e:n.push(e)}return n}function eW(e,t,n,r,i,o,s){let a;a=s?"function"==typeof s?{callback:s}:s:{},void 0===a.context&&(a.context=4);const l=a.context;if(a.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(!a.callback)return u(VH(n,r,a));{const{callback:e}=a;VH(n,r,Object.assign(Object.assign({},a),{callback:t=>{const n=u(t);e(n)}}))}function u(n){if(!n)return;function r(e){return e.map(function(e){return" "+e})}n.push({value:"",lines:[]});const s=[];let a=0,u=0,c=[],d=1,p=1;for(let e=0;e<n.length;e++){const t=n[e],i=t.lines||iW(t.value);if(t.lines=i,t.added||t.removed){if(!a){const t=n[e-1];a=d,u=p,t&&(c=l>0?r(t.lines.slice(-l)):[],a-=c.length,u-=c.length)}for(const e of i)c.push((t.added?"+":"-")+e);t.added?p+=i.length:d+=i.length}else{if(a)if(i.length<=2*l&&e<n.length-2)for(const e of r(i))c.push(e);else{const e=Math.min(i.length,l);for(const n of r(i.slice(0,e)))c.push(n);const t={oldStart:a,oldLines:d-a+e,newStart:u,newLines:p-u+e,lines:c};s.push(t),a=0,u=0,c=[]}d+=i.length,p+=i.length}}for(const e of s)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith("\n")?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,"\"),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:o,hunks:s}}}function tW(e){if(Array.isArray(e))return e.map(tW).join("\n");const t=[];e.oldFileName==e.newFileName&&t.push("Index: "+e.oldFileName),t.push("==================================================================="),t.push("--- "+e.oldFileName+(void 0===e.oldHeader?"":"\t"+e.oldHeader)),t.push("+++ "+e.newFileName+(void 0===e.newHeader?"":"\t"+e.newHeader));for(let n=0;n<e.hunks.length;n++){const r=e.hunks[n];0===r.oldLines&&(r.oldStart-=1),0===r.newLines&&(r.newStart-=1),t.push("@@ -"+r.oldStart+","+r.oldLines+" +"+r.newStart+","+r.newLines+" @@");for(const e of r.lines)t.push(e)}return t.join("\n")+"\n"}function nW(e,t,n,r,i,o,s){if("function"==typeof s&&(s={callback:s}),!(null==s?void 0:s.callback)){const a=eW(e,t,n,r,i,o,s);if(!a)return;return tW(a)}{const{callback:a}=s;eW(e,t,n,r,i,o,Object.assign(Object.assign({},s),{callback:e=>{a(e?tW(e):void 0)}}))}}function rW(e,t,n,r,i,o){return nW(e,e,t,n,r,i,o)}function iW(e){const t=e.endsWith("\n"),n=e.split("\n").map(e=>e+"\n");return t?n.pop():n.push(n.pop().slice(0,-1)),n}const oW=new Set;function sW(e,t,n,r=!1,i=3){const o=function(e,t,n){return rW(ae.basename(e),t,n,"original","modified")}(e,t,n,r),s=o.split("\n"),a=[];let l=[],u=!1,c=-1;const d=/^@@ .* @@/,p=()=>{if(0!==l.length){if(l.length<=2*i)a.push(...l);else{a.push(...l.slice(0,i));const e=l.length-2*i;e>0&&a.push(` ... ${e} unchanged lines ...`),a.push(...l.slice(-i))}l=[]}};for(let f=0;f<s.length;f++){const e=s[f];if(e)if(e.startsWith("--- ")||e.startsWith("+++ ")||e.startsWith("Index: "))p(),a.push(e);else if(d.test(e))p(),a.push(e),u=!0;else if(u)if(e.startsWith("+")||e.startsWith("-"))p(),a.push(e),c=f;else if(e.startsWith(" ")){l.push(e);const t=s.findIndex((e,t)=>e&&t>f&&(e.startsWith("+")||e.startsWith("-")));(-1===t||t-f>2*i)&&-1!==c&&f-c>i&&(l=l.slice(0,i),p())}else e.startsWith("\\")&&a.push(e)}return p(),a.join("\n")}const aW=Mz({metadata:{name:"writeFile",displayName:"Write File",description:"Creates or overwrites a file with specified content. This tool handles safety checks internally.",category:"file",icon:"📝",requiresConfirmation:!0,requiresSequentialExecution:!0},inputSchema:ug({absolutePath:mh().describe("Absolute path where file should be written"),content:mh().describe("Content to write to the file"),createDirs:Hh().default(!0).describe("Create parent directories if needed"),encoding:_g(["utf8","utf16le","latin1"]).default("utf8").optional()}),validateParams:({absolutePath:e})=>ae.isAbsolute(e)?null:`Path must be absolute: ${e}`,getDescription:({absolutePath:e,content:t})=>{const n=ae.basename(e);return`Writing ${(new TextEncoder).encode(t).length} bytes to ${n}`},getLocations:({absolutePath:e})=>[{path:e,type:"write"}],isAllowlisted:()=>oW.has("writeFile"),addToAllowlist:(e,t)=>{"always"!==t&&"command"!==t||oW.add("writeFile")},shouldConfirm:async({absolutePath:e,content:t})=>{try{const n=await Be.access(e).then(()=>!0).catch(()=>!1);let r="",i=!n;if(n)try{r=await Be.readFile(e,"utf-8")}catch{r=""}const o=sW(e,r,t,i);return{type:"edit",title:n?"Overwrite File":"Create File",description:n?`Replace contents of: ${ae.basename(e)}`:`Create new file: ${ae.basename(e)}`,affectedPaths:[e],isDestructive:n,fileName:ae.basename(e),fileDiff:o,originalContent:r,newContent:t}}catch(qK){return{type:"edit",title:"Write File",description:`Write to: ${ae.basename(e)}`,affectedPaths:[e],isDestructive:!1,fileName:ae.basename(e),fileDiff:sW(e,"",t,!0),originalContent:"",newContent:t}}},execute:async({absolutePath:e,content:t,createDirs:n,encoding:r="utf8"},i)=>{kL.getState().setCurrentFile(e);try{const a=await Be.access(e).then(()=>!0).catch(()=>!1);let l="";const u=!a;if(a)try{l=await Be.readFile(e,"utf-8")}catch{l=""}if(i.snapshotService&&!i.snapshotService.isFileTracked(e)){const t=ae.relative(process.cwd(),e);if(a)ex.info("writeFile: Registering existing file and capturing before state",{file:t}),i.snapshotService.registerFile(e),await i.snapshotService.track();else{ex.info("writeFile: Registering new file (no before state)",{file:t}),i.snapshotService.registerFile(e);const n=i.snapshotService.getTrackedFiles();ex.info("writeFile: After registration, tracked files",{count:n.length,files:n})}}n&&await Be.mkdir(ae.dirname(e),{recursive:!0}),await Be.writeFile(e,t,{encoding:r});const c=await Be.stat(e),d=sW(e,l,t,u),p=ae.relative(process.cwd(),e),f=p.startsWith(".")?p:`./${p}`;let h=u?`Successfully created new file: ${f} (${c.size} bytes).`:`Successfully updated file: ${f} (${c.size} bytes).`;const g=ae.extname(e);if([".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++",".rs"].includes(g))try{await LH.touchFile(e,!0);const t=await LH.diagnostics(),n=(t[e]||[]).filter(e=>1===e.severity);if(n.length>0){h+=`\n\nThis file has compilation errors that need to be fixed:\n<file_diagnostics>\n${n.map(LH.Diagnostic.pretty).join("\n")}\n</file_diagnostics>`}}catch(s){ex.warn("LSP diagnostics failed",s)}return{success:!0,summary:`Wrote ${c.size} bytes to ${ae.basename(e)}`,llmContent:h,returnDisplay:`✅ File ${u?"created":"updated"}: ${ae.basename(e)} (${c.size} bytes)`,locations:[{path:e,type:"write"}],metadata:{size:c.size,filename:ae.basename(e),encoding:r},diffData:{fileName:ae.basename(e),content:d,language:(o=e,{".js":"javascript",".jsx":"javascript",".ts":"typescript",".tsx":"typescript",".py":"python",".java":"java",".cpp":"cpp",".c":"c",".h":"c",".cs":"csharp",".php":"php",".rb":"ruby",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".scala":"scala",".sh":"bash",".ps1":"powershell",".html":"html",".css":"css",".json":"json",".xml":"xml",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sql":"sql"}[ae.extname(o).toLowerCase()]||"text"),isNewFile:u}}}catch(qK){const n=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error writing file ${ae.basename(e)}: ${n}`,returnDisplay:`Error writing file: ${n}`}}var o}});function lW(e,t){if(""===e||""===t)return Math.max(e.length,t.length);const n=Array.from({length:e.length+1},(e,n)=>Array.from({length:t.length+1},(e,t)=>0===n?t:0===t?n:0));for(let i=1;i<=e.length;i++)for(let r=1;r<=t.length;r++){const o=e[i-1]===t[r-1]?0:1,s=n[i-1],a=n[i];if(!s||!a)continue;const l=a[r-1],u=s[r-1];if(void 0!==l&&void 0!==u){const e=s[r];void 0!==e&&(a[r]=Math.min(e+1,l+1,u+o))}}const r=n[e.length];return r?r[t.length]??0:0}const uW=function*(e,t){yield t},cW=function*(e,t){const n=e.split("\n"),r=t.split("\n");""===r[r.length-1]&&r.pop();const i=[];for(let o=0;o<=n.length-r.length;o++){let t=!0;for(let e=0;e<r.length;e++){const i=n[o+e],s=r[e];if(!i||!s)break;if(i.trim()!==s.trim()){t=!1;break}}if(t){let t=0;for(let e=0;e<o;e++){const r=n[e];r&&(t+=r.length+1)}let s=t;for(let e=0;e<r.length;e++){const t=n[o+e];t&&(s+=t.length,e<r.length-1&&(s+=1))}i.push(e.substring(t,s))}}1===i.length&&(yield i[0])},dW=function*(e,t){const n=e.split("\n"),r=t.split("\n");if(r.length<3)return;""===r[r.length-1]&&r.pop();const i=r[0]?.trim()??"",o=r[r.length-1]?.trim()??"",s=r.length,a=[];for(let c=0;c<n.length;c++){const e=n[c];if(e&&e.trim()===i)for(let t=c+2;t<n.length;t++){const e=n[t];if(e&&e.trim()===o){a.push({startLine:c,endLine:t});break}}}if(0===a.length)return;if(1===a.length){const t=a[0];if(!t)return;const{startLine:i,endLine:o}=t,l=o-i+1;let u=0,c=Math.min(s-2,l-2);if(c>0)for(let e=1;e<s-1&&e<l-1;e++){const t=n[i+e]?.trim(),o=r[e]?.trim();if(!t||!o)break;const s=Math.max(t.length,o.length);if(0===s)continue;if(u+=(1-lW(t,o)/s)/c,u>=0)break}else u=1;if(u>=0){let t=0;for(let e=0;e<i;e++){const r=n[e];r&&(t+=r.length+1)}let r=t;for(let e=i;e<=o;e++){const t=n[e];t&&(r+=t.length,e<o&&(r+=1))}yield e.substring(t,r)}return}let l=null,u=-1;for(const c of a){const{startLine:e,endLine:t}=c,i=t-e+1;let o=0,a=Math.min(s-2,i-2);if(a>0){for(let t=1;t<s-1&&t<i-1;t++){const i=n[e+t]?.trim(),s=r[t]?.trim();if(!i||!s)break;const a=Math.max(i.length,s.length);if(0===a)continue;o+=1-lW(i,s)/a}o/=a}else o=1;o>u&&(u=o,l=c)}if(u>=.3&&l){const{startLine:t,endLine:r}=l;let i=0;for(let e=0;e<t;e++){const t=n[e];t&&(i+=t.length+1)}let o=i;for(let e=t;e<=r;e++){const t=n[e];t&&(o+=t.length,e<r&&(o+=1))}yield e.substring(i,o)}},pW=function*(e,t){const n=e=>e.replace(/\s+/g," ").trim(),r=n(t),i=[],o=e.split("\n");for(let l=0;l<o.length;l++){const e=o[l];if(e)if(n(e)===r)i.push(e);else{if(n(e).includes(r)){const n=t.trim().split(/\s+/);if(n.length>0){const t=n.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s+");try{const n=new RegExp(t),r=e.match(n);r&&r[0]&&i.push(r[0])}catch(a){}}}}}const s=t.split("\n");if(s.length>1)for(let l=0;l<=o.length-s.length;l++){const e=o.slice(l,l+s.length);n(e.join("\n"))===r&&i.push(e.join("\n"))}1===i.length&&(yield i[0])},fW=function*(e,t){const n=e=>{const t=e.split("\n"),n=t.filter(e=>e.trim().length>0);if(0===n.length)return e;const r=Math.min(...n.map(e=>{if(!e)return 0;const t=e.match(/^(\s*)/);return t&&t[1]?t[1].length:0}));return t.map(e=>0===e.trim().length?e:e.slice(r)).join("\n")},r=n(t),i=e.split("\n"),o=t.split("\n"),s=[];for(let a=0;a<=i.length-o.length;a++){const e=i.slice(a,a+o.length).join("\n");n(e)===r&&s.push(e)}1===s.length&&(yield s[0])},hW=function*(e,t){const n=e=>e.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g,(e,t)=>{switch(t){case"n":case"\n":return"\n";case"t":return"\t";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case"$":return"$";default:return e}}),r=n(t),i=new Set;let o=0;for(;;){const t=e.indexOf(r,o);if(-1===t)break;i.add(t),o=t+1}const s=e.split("\n"),a=r.split("\n");for(let l=0;l<=s.length-a.length;l++){if(n(s.slice(l,l+a.length).join("\n"))===r){let e=0;for(let t=0;t<l;t++){const n=s[t];void 0!==n&&(e+=n.length+1)}i.add(e)}}if(1===i.size){void 0!==Array.from(i)[0]&&(yield r)}},gW=function*(e,t){let n=0;for(;;){const r=e.indexOf(t,n);if(-1===r)break;yield t,n=r+t.length}},AW=function*(e,t){const n=t.trim();if(n===t)return;const r=new Set;let i=0;for(;;){const t=e.indexOf(n,i);if(-1===t)break;r.add(t),i=t+1}const o=e.split("\n"),s=t.split("\n");for(let a=0;a<=o.length-s.length;a++){if(o.slice(a,a+s.length).join("\n").trim()===n){let e=0;for(let t=0;t<a;t++){const n=o[t];void 0!==n&&(e+=n.length+1)}r.add(e)}}1===r.size&&(yield n)},mW=function*(e,t){const n=t.split("\n");if(n.length<3)return;""===n[n.length-1]&&n.pop();const r=e.split("\n"),i=n[0]?.trim()??"",o=n[n.length-1]?.trim()??"",s=[];for(let a=0;a<r.length;a++){const e=r[a];if(e&&e.trim()===i)for(let t=a+2;t<r.length;t++){const e=r[t];if(!e||e.trim()!==o)continue;const i=r.slice(a,t+1),l=i.join("\n");if(i.length===n.length){let e=0,t=0;for(let r=1;r<i.length-1;r++){const o=i[r]?.trim()??"",s=n[r]?.trim()??"";(o.length>0||s.length>0)&&(t++,o===s&&e++)}if(0===t||e/t>=.5){s.push(l);break}}break}}1===s.length&&(yield s[0])};function yW(e,t,n,r=!1){if(t===n)return{success:!1,error:"oldString and newString must be different"};const i=[{name:"SimpleReplacer",replacer:uW},{name:"LineTrimmedReplacer",replacer:cW},{name:"BlockAnchorReplacer",replacer:dW},{name:"WhitespaceNormalizedReplacer",replacer:pW},{name:"IndentationFlexibleReplacer",replacer:fW},{name:"EscapeNormalizedReplacer",replacer:hW},{name:"TrimmedBoundaryReplacer",replacer:AW},{name:"ContextAwareReplacer",replacer:mW},{name:"MultiOccurrenceReplacer",replacer:gW}];let o=!0;for(const{name:s,replacer:a}of i)for(const i of a(e,t)){const t=e.indexOf(i);if(-1===t)continue;if(o=!1,r)return{success:!0,content:e.replaceAll(i,n),strategy:s};if(t===e.lastIndexOf(i))return{success:!0,content:e.substring(0,t)+n+e.substring(t+i.length),strategy:s}}return o?{success:!1,error:"oldString not found in content"}:{success:!1,error:"oldString found multiple times and requires more code context to uniquely identify the intended match"}}const bW=new Set;const vW=Mz({metadata:{name:"editFile",displayName:"Edit File",description:"Edit a file by replacing specific content with new content. This tool ONLY works on files that already exist. To create a new file or completely overwrite a file, use the writeFile tool instead. This tool handles safety checks internally.",category:"file",icon:"✏️",requiresConfirmation:!0,requiresSequentialExecution:!0},inputSchema:ug({absolutePath:mh().describe("Absolute path to the file to edit"),oldContent:mh().describe("The exact text to replace"),newContent:mh().describe("The new text to insert"),replaceAll:Hh().default(!1).describe("Replace all occurrences (default: replace first occurrence only)")}),validateParams:({absolutePath:e})=>ae.isAbsolute(e)?null:`Path must be absolute: ${e}`,getDescription:({absolutePath:e,oldContent:t,newContent:n})=>`Editing ${ae.basename(e)} (${t.split("\n").length}→${n.split("\n").length} lines)`,getLocations:({absolutePath:e})=>[{path:e,type:"write"}],isAllowlisted:()=>bW.has("editFile"),addToAllowlist:(e,t)=>{"always"!==t&&"command"!==t||bW.add("editFile")},shouldConfirm:async({absolutePath:e,oldContent:t,newContent:n,replaceAll:r})=>{const i=ae.basename(e),o=n.length-t.length,s=o>0?`+${o} characters`:o<0?`${o} characters`:"same length",a=await import("./index-Bhne8HYq.js");let l="";try{l=await Be.readFile(e,"utf8")}catch(qK){l=""}const u=yW(l,t,n,r),c=u.success?u.content:l,d=a.createPatch(i,l,c,"Current","Proposed");return{type:"edit",title:"Edit File",description:u.success?`This will modify ${i} (${s}) using ${u.strategy}`:`This will modify ${i} (${s})`,affectedPaths:[e],isDestructive:!1,fileName:i,fileDiff:d,originalContent:l,newContent:c}},execute:async({absolutePath:e,oldContent:t,newContent:n,replaceAll:r},i)=>{kL.getState().setCurrentFile(e);try{const a=ae.relative(process.cwd(),e);ex.info("editFile: Attempting edit",{file:a,oldContentLength:t.length,newContentLength:n.length,replaceAll:r||!1}),await Be.access(e),i.snapshotService&&!i.snapshotService.isFileTracked(e)?(ex.info("editFile: Registering file and capturing before state",{file:a}),i.snapshotService.registerFile(e),await i.snapshotService.track()):i.snapshotService&&ex.info("editFile: File already tracked, skipping before state capture",{file:a});const l=await Be.readFile(e,"utf8"),u=yW(l,t,n,r);if(!u.success){const n=ae.relative(process.cwd(),e),r=t.substring(0,100),i=t.length>100?`... (${t.length} chars total)`:"",o=l.substring(0,200),s=l.length>200?`... (${l.length} chars total)`:"",a=t.includes("\r"),c=l.includes("\r"),d=a!==c,p=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),f=l.replace(/\r\n/g,"\n").replace(/\r/g,"\n").includes(p);ex.error("editFile: Fuzzy matching failed to find content",{file:n,absolutePath:e,fuzzyMatchError:u.error,oldContentLength:t.length,currentContentLength:l.length,oldContentLines:t.split("\n").length,currentContentLines:l.split("\n").length,oldContentPreview:r+i,currentContentPreview:o+s,oldContentHasLeadingWhitespace:/^\s/.test(t),oldContentHasTrailingWhitespace:/\s$/.test(t),oldContentHasTabs:t.includes("\t"),oldContentHasCarriageReturn:a,currentContentHasTabs:l.includes("\t"),currentContentHasCarriageReturn:c,hasLineEndingMismatch:d,wouldMatchIfNormalized:f,oldContentFirstChar:t.length>0?`'${t[0]}' (0x${t.charCodeAt(0).toString(16)})`:"empty",oldContentLastChar:t.length>0?`'${t[t.length-1]}' (0x${t.charCodeAt(t.length-1).toString(16)})`:"empty",currentContentFirstChar:l.length>0?`'${l[0]}' (0x${l.charCodeAt(0).toString(16)})`:"empty",currentContentLastChar:l.length>0?`'${l[l.length-1]}' (0x${l.charCodeAt(l.length-1).toString(16)})`:"empty"});let h="";return d&&f?c&&!a?h=" The file uses Windows line endings (\\r\\n) but you provided Unix line endings (\\n). Please use \\r\\n in your oldContent parameter.":!c&&a&&(h=" The file uses Unix line endings (\\n) but you provided Windows line endings (\\r\\n). Please use \\n in your oldContent parameter."):h=f?" There appears to be a line ending or whitespace mismatch. The fuzzy matcher tried multiple strategies but couldn't find a match.":" The content may have been modified, or the oldContent doesn't exist in the file. Try reading the file first to get the current content.",{success:!1,llmContent:`Old content not found in file: ${e}. ${u.error}.${h}`,returnDisplay:"Content to replace was not found"}}const c=u.content,d=r?l.split(t).length-1:l!==c?1:0;await Be.writeFile(e,c,"utf8");const p=await Be.stat(e),f=ae.relative(process.cwd(),e),h=f.startsWith(".")?f:`./${f}`,g=(await import("./index-Bhne8HYq.js")).createPatch(ae.basename(e),l,c,"Before","After");ex.info("editFile: Successfully edited file",{file:f,replaceCount:d,replaceAll:r||!1,fuzzyStrategy:u.strategy,oldContentLength:t.length,newContentLength:n.length,fileSizeAfter:p.size});let A=`Successfully edited ${h}. Made ${d} replacement${d>1?"s":""}.`;const m=ae.extname(e);if([".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++",".rs"].includes(m))try{await LH.touchFile(e,!0);const t=await LH.diagnostics(),n=(t[e]||[]).filter(e=>1===e.severity);if(n.length>0){A+=`\n\nThis file has compilation errors that need to be fixed:\n<file_diagnostics>\n${n.map(LH.Diagnostic.pretty).join("\n")}\n</file_diagnostics>`}}catch(s){ex.warn("LSP diagnostics failed",s)}return{success:!0,summary:`Edited ${h} (${d} replacement${d>1?"s":""})`,llmContent:A,returnDisplay:`✅ File edited: ${h} (${d} change${d>1?"s":""})`,locations:[{path:e,type:"write"}],metadata:{filename:ae.basename(e),replaceCount:d,replaceAll:r,fileSize:p.size},diffData:{fileName:ae.basename(e),content:g,language:(o=e,{".js":"javascript",".jsx":"javascript",".ts":"typescript",".tsx":"typescript",".py":"python",".java":"java",".c":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".go":"go",".rs":"rust",".php":"php",".rb":"ruby",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"bash",".json":"json",".yaml":"yaml",".yml":"yaml",".xml":"xml",".html":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".md":"markdown",".sql":"sql",".toml":"toml",".ini":"ini",".cfg":"ini",".conf":"ini"}[ae.extname(o).toLowerCase()]||"text"),isNewFile:!1}}}catch(qK){const n=qK instanceof Error?qK.message:String(qK),r=ae.basename(e),i=ae.relative(process.cwd(),e);return"ENOENT"===qK.code?(ex.error("editFile: File not found",{file:i,absolutePath:e,errorCode:"ENOENT"}),{success:!1,llmContent:`File not found: ${e}`,returnDisplay:`File not found: ${r}`}):(ex.error("editFile: Error during edit",{file:i,absolutePath:e,errorMessage:n,errorCode:qK.code,errorStack:qK instanceof Error?qK.stack:void 0}),{success:!1,llmContent:`Error editing file ${r}: ${n}`,returnDisplay:`Error editing file: ${n}`})}var o}});function EW(e){return new RegExp("^"+e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$")}const IW=Mz({metadata:{name:"listDirectory",displayName:"List Directory",description:"List files and directories at a given path",category:"file",icon:"📁"},inputSchema:ug({path:mh().describe("Absolute path of the directory to list"),ignore:ag(mh()).optional().describe("Glob patterns to ignore"),respectGitIgnore:Hh().optional(),respectEmbedderIgnore:Hh().optional()}),validateParams:({path:e})=>ae.isAbsolute(e)?null:`Path must be absolute: ${e}`,getDescription:({path:e,ignore:t})=>`Listing contents of ${ae.basename(e)}${t&&t.length>0?` (ignoring ${t.length} patterns)`:""}`,getLocations:({path:e})=>[{path:e,type:"read"}],execute:async({path:e,ignore:t,respectGitIgnore:n,respectEmbedderIgnore:r},i)=>{if(!J.existsSync(e)||!J.statSync(e).isDirectory())return{success:!1,llmContent:`Directory not found or not a directory: ${e}`,returnDisplay:"Directory inaccessible."};const o=J.readdirSync(e),s=[];for(const u of o){if(t?.some(e=>EW(e).test(u)))continue;const n=ae.join(e,u),r=J.statSync(n);s.push({name:u,path:n,isDirectory:r.isDirectory(),size:r.isDirectory()?0:r.size,modifiedTime:r.mtime})}s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name));const a=s.map(e=>`${e.isDirectory?"[DIR] ":""}${e.name}`).join("\n"),l=[];return{success:!0,summary:`Listed ${s.length} item(s) in ${ae.basename(e)}`,llmContent:`Directory listing for ${e}:\n${a}${l.length?"\n\n("+l.join(", ")+")":""}`,returnDisplay:`Listed ${s.length} item(s)${l.length?" ("+l.join(", ")+")":""}.`,locations:[{path:e,type:"read"}],metadata:{entryCount:s.length,gitIgnoredCount:0,embedderIgnoredCount:0,toolParams:{path:e,ignore:t,respectGitIgnore:n,respectEmbedderIgnore:r}}}}});function wW(e){return new Promise(t=>{const n="win32"===process.platform?"where":"command",r="win32"===process.platform?[e]:["-v",e];try{const e=Se(n,r,{stdio:"ignore",shell:"win32"===process.platform});e.on("close",e=>t(0===e)),e.on("error",()=>t(!1))}catch{t(!1)}})}function CW(e,t){const n=[];if(!e)return n;const r=e.split(W);for(const i of r){if(!i.trim())continue;const e=i.indexOf(":");if(-1===e)continue;const r=i.indexOf(":",e+1);if(-1===r)continue;const o=i.substring(0,e),s=i.substring(e+1,r),a=i.substring(r+1),l=parseInt(s,10);if(!isNaN(l)){const e=ae.resolve(t,o),r=ae.relative(t,e);n.push({filePath:r||ae.basename(e),lineNumber:l,line:a})}}return n}async function _W(e){const{pattern:t,path:n,includeGlob:r}=e;let i="none";try{if(function(e){try{const t=ae.join(e,".git");return J.existsSync(t)}catch{return!1}}(n)&&await wW("git")){i="git grep";const e=["grep","--untracked","-n","-E","--ignore-case",t];r&&e.push("--",r);try{return CW(await new Promise((t,r)=>{const i=Se("git",e,{cwd:n,windowsHide:!0}),o=[],s=[];i.stdout.on("data",e=>o.push(e)),i.stderr.on("data",e=>s.push(e)),i.on("error",e=>r(new Error(`Failed to start git grep: ${e.message}`))),i.on("close",e=>{const n=Buffer.concat(o).toString("utf8"),i=Buffer.concat(s).toString("utf8");0===e?t(n):1===e?t(""):r(new Error(`git grep exited with code ${e}: ${i}`))})}),n)}catch(o){ex.debug(`Grep: git grep failed: ${o}. Falling back...`)}}if(await wW("grep")){i="system grep";const e=["-r","-n","-H","-E"];[".git","node_modules","bower_components"].forEach(t=>e.push(`--exclude-dir=${t}`)),r&&e.push(`--include=${r}`),e.push(t),e.push(".");try{return CW(await new Promise((t,r)=>{const i=Se("grep",e,{cwd:n,windowsHide:!0}),o=[],s=[],a=e=>o.push(e),l=e=>{const t=e.toString();t.includes("Permission denied")||/grep:.*: Is a directory/i.test(t)||s.push(e)},u=e=>{d(),r(new Error(`Failed to start system grep: ${e.message}`))},c=e=>{const n=Buffer.concat(o).toString("utf8"),i=Buffer.concat(s).toString("utf8").trim();d(),0===e?t(n):1===e?t(""):i?r(new Error(`System grep exited with code ${e}: ${i}`)):t("")},d=()=>{i.stdout.removeListener("data",a),i.stderr.removeListener("data",l),i.removeListener("error",u),i.removeListener("close",c),i.connected&&i.disconnect()};i.stdout.on("data",a),i.stderr.on("data",l),i.on("error",u),i.on("close",c)}),n)}catch(s){ex.debug(`Grep: System grep failed: ${s}. Falling back...`)}}ex.debug("Grep: Falling back to JavaScript grep implementation."),i="javascript fallback";const l=r||"**/*",u=[".git/**","node_modules/**","bower_components/**",".svn/**",".hg/**"],c=await qU(l,{cwd:n,dot:!0,ignore:u,absolute:!0,nodir:!0,signal:e.signal}),d=new RegExp(t,"i"),p=[];for(const e of c){const t=e;try{const e=await Be.readFile(t,"utf8");e.split(/\r?\n/).forEach((e,r)=>{d.test(e)&&p.push({filePath:ae.relative(n,t)||ae.basename(t),lineNumber:r+1,line:e})})}catch(a){a&&"ENOENT"===a.code||ex.debug(`Grep: Could not read/process ${t}: ${a}`)}}return p}catch(qK){throw ex.error(`Grep: Error in performGrepSearch (Strategy: ${i}): ${qK}`),qK}}const BW=Mz({metadata:{name:"grep",displayName:"Grep Search",description:"Searches for a regular expression pattern within the content of files in a specified directory. Can filter files by a glob pattern. Returns the lines containing matches, along with their file paths and line numbers.",category:"search",icon:"🔍"},inputSchema:ug({pattern:mh().describe("The regular expression (regex) pattern to search for within file contents (e.g., 'function\\s+myFunction', 'import\\s+\\{.*\\}\\s+from\\s+.*')."),absolutePath:mh().optional().describe("Optional: The absolute path to the directory to search within. If omitted, searches the current working directory."),includeGlob:mh().optional().describe("Optional: A glob pattern to filter which files are searched (e.g., '*.js', '*.{ts,tsx}', 'src/**'). If omitted, searches all files (respecting common ignores like .git, node_modules).")}),validateParams:({pattern:e,absolutePath:t})=>{try{new RegExp(e)}catch(n){return`Invalid regular expression pattern: ${e}`}return t&&!ae.isAbsolute(t)?`Path must be absolute: ${t}`:null},getDescription:({pattern:e,absolutePath:t,includeGlob:n})=>`Searching for "${e}" in ${t?ae.basename(t):"current directory"}${n?` (${n})`:""}`,getLocations:({absolutePath:e})=>[{path:e||process.cwd(),type:"read"}],execute:async({pattern:e,absolutePath:t,includeGlob:n},r)=>{try{const i=t||process.cwd();try{if(!J.statSync(i).isDirectory())return{success:!1,llmContent:`Error: Path is not a directory: ${i}`,returnDisplay:"Path is not a directory."}}catch(qK){return"ENOENT"===qK.code?{success:!1,llmContent:`Error: Directory does not exist: ${i}`,returnDisplay:"Directory not found."}:{success:!1,llmContent:`Error: Failed to access directory: ${i}. ${qK}`,returnDisplay:"Directory access failed."}}const o=await _W({pattern:e,path:i,includeGlob:n,signal:r.signal});if(0===o.length){return{success:!0,summary:"No matches found",llmContent:`No matches found for pattern "${e}" in path "${t||"."}"${n?` (filter: "${n}")`:""}.`,returnDisplay:"No matches found",metadata:{matchCount:0,toolParams:{pattern:e,absolutePath:t,includeGlob:n}}}}const s=o.reduce((e,t)=>{const n=ae.relative(i,ae.resolve(i,t.filePath))||ae.basename(t.filePath);return e[n]||(e[n]=[]),e[n].push(t),e[n].sort((e,t)=>e.lineNumber-t.lineNumber),e},{}),a=o.length,l=1===a?"match":"matches";let u=`Found ${a} ${l} for pattern "${e}" in path "${t||"."}"${n?` (filter: "${n}")`:""}:\n---\n`;for(const e in s){const t=s[e];if(t){u+=`File: ${e}\n`;for(const e of t){const t=e.line.trim();u+=`L${e.lineNumber}: ${t}\n`}u+="---\n"}}return{success:!0,summary:`Found ${a} ${l} for "${e}"`,llmContent:u.trim(),returnDisplay:`Found ${a} ${l}`,locations:[{path:i,type:"read"}],metadata:{matchCount:a,toolParams:{pattern:e,absolutePath:t,includeGlob:n}}}}catch(qK){ex.error(`Error during grep search operation: ${qK}`);const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error during grep search operation: ${t}`,returnDisplay:`Error: ${t}`}}}});const DW=Mz({metadata:{name:"glob",displayName:"Find Files",description:"Efficiently finds files matching specific glob patterns (e.g., `src/**/*.ts`, `**/*.md`), returning absolute paths sorted by modification time (newest first). Ideal for quickly locating files based on their name or path structure, especially in large codebases.",category:"search",icon:"🔍"},inputSchema:ug({pattern:mh().min(1).describe("The glob pattern to match against (e.g., '**/*.py', 'docs/*.md')."),path:mh().optional().describe("Optional: The absolute path to the directory to search within. If omitted, searches the root directory."),case_sensitive:Hh().optional().describe("Optional: Whether the search should be case-sensitive. Defaults to false."),respect_git_ignore:Hh().optional().describe("Optional: Whether to respect .gitignore patterns when finding files. Only available in git repositories. Defaults to true.")}),validateParams:({pattern:e,path:t})=>{if(!e||"string"!=typeof e||""===e.trim())return"The 'pattern' parameter cannot be empty.";if(t){const e=ae.resolve(process.cwd(),t);if(!function(e,t){const n=ae.resolve(e),r=ae.resolve(t),i=r===ae.sep||r.endsWith(ae.sep)?r:r+ae.sep;return n===r||n.startsWith(i)}(e,process.cwd()))return`Search path ("${e}") resolves outside the tool's root directory ("${process.cwd()}").`;try{if(!J.existsSync(e))return`Search path does not exist ${e}`;if(!J.statSync(e).isDirectory())return`Search path is not a directory: ${e}`}catch(n){return`Error accessing search path: ${n}`}}return null},getDescription:({pattern:e,path:t})=>{let n=`'${e}'`;if(t){n+=` within ${function(e,t=35){if(e.length<=t)return e;const n=ae.parse(e).root,r=ae.sep,i=e.substring(n.length).split(r).filter(e=>""!==e);if(i.length<=1){const n=Math.floor((t-3)/2);return n<=0?e.substring(0,t-3)+"...":`${e.substring(0,n)}...${e.substring(e.length-n)}`}const o=i[0],s=i[i.length-1];if(!s)return e.length>t?e.substring(0,t-3)+"...":e;const a=n+o,l=[];let u=r.length+s.length;for(let d=i.length-2;d>=0;d--){const e=i[d];if(!e)continue;const n=u+r.length+e.length;if(!(n<=t))break;l.unshift(e),u=n}let c=l.join(r)+r+s;return u>t?c:(c=a+r+c,c.length>t?"..."+c.substring(c.length-t-3):c)}(function(e,t){const n=ae.resolve(e),r=ae.resolve(t);return ae.relative(r,n)||"."}(ae.resolve(process.cwd(),t||"."),process.cwd()))}`}return n},getLocations:({path:e})=>[{path:e?ae.resolve(process.cwd(),e):process.cwd(),type:"read"}],execute:async(e,t)=>{const{pattern:n,path:r,case_sensitive:i,respect_git_ignore:o}=e;try{const e=ae.resolve(process.cwd(),r||"."),s=process.cwd(),a=o??!0,l=new ZU(s),u=await qU(n,{cwd:e,withFileTypes:!0,nodir:!0,stat:!0,nocase:!i,dot:!0,ignore:["**/node_modules/**","**/.git/**"],follow:!1,signal:t.signal});let c=u,d=0;if(a){const e=u.map(e=>ae.relative(s,e.fullpath())),t=l.filterFiles(e,{respectGitIgnore:a}),n=new Set(t.map(e=>ae.resolve(s,e)));c=u.filter(e=>n.has(e.fullpath())),d=u.length-c.length}if(!c||0===c.length){let t=`No files found matching pattern "${n}" within ${e}.`;return d>0&&(t+=` (${d} files were git-ignored)`),{success:!0,summary:"No files found",llmContent:t,returnDisplay:"No files found",locations:[{path:e,type:"read"}],metadata:{matchCount:0,gitIgnoredCount:d,toolParams:{pattern:n,searchDirectory:null,fileFilteringOptions:null}}}}const p=864e5,f=function(e,t,n){const r=[...e];return r.sort((e,r)=>{const i=e.mtimeMs??0,o=r.mtimeMs??0,s=t-i<n,a=t-o<n;return s&&a?o-i:s?-1:a?1:e.fullpath().localeCompare(r.fullpath())}),r}(c,(new Date).getTime(),p),h=f.map(e=>e.fullpath()),g=h.join("\n"),A=h.length;let m=`Found ${A} file(s) matching "${n}" within ${e}`;return d>0&&(m+=` (${d} additional files were git-ignored)`),m+=`, sorted by modification time (newest first):\n${g}`,{success:!0,summary:`Found ${A} matching file(s)`,llmContent:m,returnDisplay:`Found ${A} matching file(s)${d>0?` (${d} git-ignored)`:""}`,locations:h.map(e=>({path:e,type:"read"})),metadata:{matchCount:A,gitIgnoredCount:d,pattern:n,searchDirectory:e,toolParams:{pattern:n,searchDirectory:null,fileFilteringOptions:null}}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return ex.error(`Glob tool execute Error: ${t}`,qK),{success:!1,summary:"Glob search failed",llmContent:`Error during glob search operation: ${t}`,returnDisplay:"Error: An unexpected error occurred."}}}}),SW=new Set,kW=new Set(["cd","pushd","popd","dirs","pwd","realpath","readlink","basename","dirname","ls","dir","ll","tree","cat","head","tail","less","more","type","file","stat","du","df","attrib","lsof","mount","whoami","id","groups","date","uptime","uname","hostname","ps","top","htop","tasklist","netstat","ipconfig","ifconfig","env","printenv","set","export","alias","getconf","which","where","whereis","type","command","history","grep","egrep","fgrep","findstr","rg","wc","sort","uniq","cut","echo","Get-ChildItem","gci","Get-Content","gc","Get-Location","gl","Set-Location","sl","Get-Process","gps","Get-Command","Get-Item","Get-ItemProperty","Resolve-Path","Split-Path","Join-Path","Test-Path","Select-String","sls","Measure-Object","locate"]),xW=[/^git\s+(status|log|diff|show|branch|remote|config\s+--list|remote\s+-v)(\s|$)/,/^npm\s+(list|ls|outdated|info|view|version|run\s+(test|lint|build|typecheck|check))(\s|$)/,/^yarn\s+(list|info|why)(\s|$)/,/^pnpm\s+(list|ls|why|outdated)(\s|$)/,/^pip\s+(list|show|freeze)(\s|$)/,/^(node|npm|yarn|pnpm|python|python3|pip|git|tsc|npx)\s+(--version|-v)(\s|$)/,/^(npx\s+)?tsc\s+(--noEmit|--version)(\s|$)/,/^find\s+(?!.*(-exec|-delete))/,/^cd\s+/,/^pushd\s+/,/^(Get-|Test-|Select-|Measure-|Split-|Join-|Resolve-)/i];function QW(e){return e.trim().replace(/[{}()]/g,"").split(/[\s;&|]+/)[0]?.split(/[/\\]/).pop()||null}async function NW(e,t=3,n=500,r=0,i=new Map){if(r>=t||i.size>=n)return i;try{const o=await oe.readdir(e,{withFileTypes:!0});for(const s of o){if(i.size>=n)break;if(s.name.startsWith(".")||"node_modules"===s.name||"__pycache__"===s.name||"venv"===s.name||"dist"===s.name||"build"===s.name)continue;const o=ae.join(e,s.name);if(s.isDirectory())await NW(o,t,n,r+1,i);else if(s.isFile())try{const e=await oe.stat(o);i.set(o,e.mtimeMs)}catch{}}}catch{}return i}const TW=Mz({metadata:{name:"shell",displayName:"Shell Command",description:"Execute shell commands immediately in the project directory. This tool handles all safety checks internally and does not require pre-approval.",category:"system",icon:"💻",requiresConfirmation:!0,canStream:!0,requiresSequentialExecution:!0},inputSchema:ug({command:mh().describe("The shell command to execute"),workingDirectory:mh().optional().describe("Working directory (defaults to project root)"),timeout:jh().default(3e4).describe("Timeout in milliseconds (default: 30 seconds)"),shell:Hh().default(!0).describe("Whether to use shell for command execution")}),validateParams:({command:e})=>e.trim()?null:"Command cannot be empty",getDescription:({command:e,workingDirectory:t})=>`Running "${e}" in ${t?ae.basename(t):"project root"}`,getLocations:({workingDirectory:e})=>[{path:e||process.cwd(),type:"execute"}],getCommandRoot:({command:e})=>QW(e),isAllowlisted:({command:e})=>{const t=QW(e);return!!t&&SW.has(t)},addToAllowlist:({command:e},t)=>{if("always"===t||"command"===t){const t=QW(e);t&&SW.add(t)}},shouldConfirm:async({command:e,workingDirectory:t})=>{const n=e.trim().split(/\s+/);if(function(e,t){return!(!t[0]||!kW.has(t[0]))||xW.some(t=>t.test(e))}(e,n))return null;const r=[/rm\s+-rf/i,/rm\s+.*\/\s*$/i,/>\s*\/dev\/(sda|sdb|sdc)/i,/dd\s+.*of=/i,/format\s+/i,/fdisk/i,/mkfs/i].some(t=>t.test(e)),i=t||process.cwd();return{type:"execute",title:r?"⚠️ Potentially Dangerous Command":"Execute Command",description:`Execute: ${e} in ${ae.basename(i)}`,affectedPaths:[i],isDestructive:r}},execute:async({command:e,workingDirectory:t,timeout:n,shell:r},i)=>new Promise(async o=>{const s=t||process.cwd();let a="",l="",u=!1;const c=Date.now();let d=0;let p=null;if(i.snapshotService)try{p=await NW(s),ex.info("shell: Scanned directory before execution",{fileCount:p.size,cwd:ae.relative(process.cwd(),s)})}catch(qK){ex.warn("shell: Failed to scan directory before execution",qK)}const f="win32"===process.platform?"cmd":"bash",h="win32"===process.platform?["/c"]:["-c"],g=r?Se(f,[...h,e],{cwd:s,stdio:["pipe","pipe","pipe"]}):Se(e,[],{cwd:s,stdio:["pipe","pipe","pipe"],shell:!1}),A=setTimeout(()=>{u=!0,g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},2e3)},n);g.stdout?.on("data",e=>{const t=e.toString();a+=t;const n=Date.now();n-d>=100&&(i.updateOutput?.(a+l),d=n)}),g.stderr?.on("data",e=>{const t=e.toString();l+=t;const n=Date.now();n-d>=100&&(i.updateOutput?.(a+l),d=n)}),g.on("close",async(t,r)=>{if(clearTimeout(A),(a||l)&&i.updateOutput?.(a+l),i.snapshotService&&p)try{const e=await NW(s),{newFiles:t,modifiedFiles:n}=await async function(e,t){const n=[],r=[];for(const[i,o]of t.entries()){const t=e.get(i);void 0===t?n.push(i):o!==t&&r.push(i)}return{newFiles:n,modifiedFiles:r}}(p,e);ex.info("shell: File changes detected",{newFiles:t.length,modifiedFiles:n.length});for(const r of n)i.snapshotService.isFileTracked(r)||(i.snapshotService.registerFile(r),ex.info("shell: Registered modified file",{file:ae.relative(process.cwd(),r)}));for(const r of t)i.snapshotService.isFileTracked(r)||(i.snapshotService.registerFile(r),ex.info("shell: Registered new file",{file:ae.relative(process.cwd(),r)}));(t.length>0||n.length>0)&&await i.snapshotService.track()}catch(qK){ex.warn("shell: Failed to detect file changes after execution",qK)}const d=Date.now()-c,f=!u&&0===t;let h,g;u?(h=`Command timed out after ${n}ms`,g=h):r?(h=`Command terminated by signal: ${r}`,g=h):(h=`Command ${f?"completed":"failed"} (exit code: ${t})`,g=f?"(none)":h);let m=(a+(l?`\n--- STDERR ---\n${l}`:"")).trim()||"(no output)";f||(m=`${h}\n\n${m}`);const y=(a+l).trim()||"(empty)",b=[`Command: ${e}`,`Directory: ${ae.relative(process.cwd(),s)}`,`Output: ${y}`,`Error: ${g}`,`Exit Code: ${t??"(none)"}`,`Signal: ${r??"(none)"}`,`Duration: ${d}ms`].join("\n");o({success:f,summary:`${h} in ${d}ms`,llmContent:b,returnDisplay:m,locations:[{path:s,type:"execute"}],metadata:{exitCode:t,signal:r,duration:d,command:e,cwd:s,isTimedOut:u,stdoutLength:a.length,stderrLength:l.length}})}),g.on("error",t=>{clearTimeout(A);const n=(a+(l?`\n--- STDERR ---\n${l}`:"")).trim()||"(no output)",r=(a+l).trim()||"(empty)",i=[`Command: ${e}`,`Directory: ${ae.relative(process.cwd(),s)}`,`Output: ${r}`,`Error: ${t.message}`,"Exit Code: (none)","Signal: (none)",`Duration: ${Date.now()-c}ms`].join("\n");o({success:!1,llmContent:i,returnDisplay:`Error: ${t.message}\n\n${n}`,metadata:{error:t.message,command:e}})}),i.signal&&i.signal.addEventListener("abort",()=>{g.kill("SIGTERM")})})}),RW=Mz({metadata:{name:"build",displayName:"Build Project",description:"Build the project using the configured build command",category:"development",icon:"🔨",canStream:!0},inputSchema:ug({target:mh().optional().describe("Build target (e.g., 'dev', 'prod', 'test')"),clean:Hh().default(!1).describe("Clean before building"),workingDirectory:mh().optional().describe("Project directory (defaults to current directory)")}),validateParams:({workingDirectory:e})=>e&&!ae.isAbsolute(e)?`Working directory must be absolute: ${e}`:null,getDescription:({target:e,clean:t})=>`Building project${e?` (${e})`:""}${t?" with clean":""}`,getLocations:({workingDirectory:e})=>[{path:e||process.cwd(),type:"execute"}],execute:async({target:e,clean:t,workingDirectory:n},r)=>{const i=n||process.cwd();try{const n=ae.join(i,"package.json");let o=null,s="unknown",a="npm run build";try{const e=await Be.readFile(n,"utf8");o=JSON.parse(e),s="npm"}catch{}if(o?.scripts){if(e&&o.scripts[`build:${e}`])a=`npm run build:${e}`;else if(o.scripts.build)a="npm run build";else if(o.scripts.dev&&"dev"===e)a="npm run dev";else{const e=["compile","make","bundle"].find(e=>o.scripts[e]);e&&(a=`npm run ${e}`)}try{await Be.access(ae.join(i,"yarn.lock")),a=a.replace("npm run","yarn"),s="yarn"}catch{}try{await Be.access(ae.join(i,"pnpm-lock.yaml")),a=a.replace("npm run","pnpm run"),s="pnpm"}catch{}}else{const e=[{file:"Makefile",system:"make",command:"make"},{file:"build.gradle",system:"gradle",command:"gradle build"},{file:"pom.xml",system:"maven",command:"mvn compile"},{file:"Cargo.toml",system:"cargo",command:"cargo build"},{file:"go.mod",system:"go",command:"go build"}];for(const{file:t,system:n,command:r}of e)try{await Be.access(ae.join(i,t)),s=n,a=r;break}catch{}}if(t){let e="";if(o?.scripts?.clean)e=a.replace(/build.*$/,"clean");else switch(s){case"make":e="make clean";break;case"gradle":e="gradle clean";break;case"maven":e="mvn clean";break;case"cargo":e="cargo clean";break;case"go":e="go clean";break;default:e="npm run clean"}if(e){r.updateOutput?.("🧹 Cleaning...\n");const t=await TW.executeStructured({command:e,workingDirectory:i,timeout:5,shell:!0},r);if(!t.success)return{success:!1,llmContent:`Clean failed: ${t.llmContent}`,returnDisplay:"Clean step failed"}}}r.updateOutput?.(`🔨 Building with ${s}...\n`);const l=await TW.executeStructured({command:a,workingDirectory:i,timeout:3e4,shell:!0},r),u=["dist","build","out","target"];let c=[];for(const e of u){const t=ae.join(i,e);try{(await Be.stat(t)).isDirectory()&&c.push(e)}catch{}}return{success:l.success,summary:l.success?`Build completed using ${s}${e?` (${e})`:""}`:`Build failed using ${s}`,llmContent:`Build System: ${s}\nCommand: ${a}${t?"\nCleaned before build: yes":""}\n\n${l.llmContent}${c.length?`\n\nBuild Artifacts: ${c.join(", ")}`:""}`,returnDisplay:l.success?"✅ Build completed"+(c.length?` → ${c.join(", ")}`:""):"❌ Build failed",locations:[{path:i,type:"execute"},...c.map(e=>({path:ae.join(i,e),type:"write"}))],metadata:{buildSystem:s,buildCommand:a,target:e,clean:t,buildArtifacts:c,...l.metadata}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error during build: ${t}`,returnDisplay:`Build error: ${t}`,metadata:{error:t}}}}}),FW=new Set;function MW(e){try{return e.toString("utf8").includes("�")||function(e){return e.filter(e=>e<32&&9!==e&&10!==e&&13!==e).length/e.length>.3}(e)?"latin1":"utf8"}catch{return"latin1"}}function OW(e){return e.includes("\r\n")||e.includes("\r")?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):e.replace(/\n{4,}/g,"\n\n\n")}function $W(e){return e.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function LW(e,t="direct"){const n=MW(e);let r=e.toString(n);return r=$W(r),r=OW(r),r}const PW=Mz({metadata:{name:"serial_monitor",displayName:"Serial Monitor",description:"Opens a serial monitor connection to capture debug output from embedded devices.\n\nThis tool monitors serial output until a specific string is detected or a timeout occurs.\n\nThe tool automatically handles:\n- Encoding detection (UTF-8 with Latin-1 fallback)\n- Intelligent line ending normalization\n- ANSI escape sequence cleaning\n- Real-time data processing\n\nThe tool supports two modes:\n1. **Custom Command Mode**: If 'serial_monitor_command' is defined in EMBEDDER.md, it will use that command (e.g., \"tio {port} -b {baud}\")\n2. **Direct Serial Mode**: Uses built-in serial port communication for standard connections (default)\n\nCommon use cases:\n- Monitoring firmware boot sequences\n- Capturing debug output until a specific log message appears\n- Waiting for initialization complete messages\n- Debugging serial communication protocols\n\nReturns all captured serial output up to the stop condition.",category:"system",icon:"📡",requiresConfirmation:!0,canStream:!0},inputSchema:ug({port:mh().optional().describe("Serial port device path (e.g., /dev/ttyUSB0, /dev/ttyACM0, COM3). If not specified, uses serial_port from EMBEDDER.md."),baud_rate:jh().optional().describe("Baud rate for serial communication (e.g., 115200, 9600). If not specified, uses serial_baudrate from EMBEDDER.md or defaults to 115200."),stop_string:mh().describe("Text string to watch for in the serial output. When this string is detected, the monitor will stop and return all captured output."),timeout:jh().default(3e4).describe("Maximum time in milliseconds to wait for the stop_string before giving up. Defaults to 30000 (30 seconds)."),description:mh().optional().describe("Brief description of what debug information is being monitored for."),interactive:Hh().default(!1).describe("Enable interactive mode for commands that require terminal interaction (e.g., waf console). Uses PTY for proper terminal emulation."),startup_commands:ag(mh()).optional().describe("Commands to automatically send to the interactive terminal after startup. Useful for automating initial setup in interactive sessions.")}),validateParams:({stop_string:e,timeout:t})=>e?.trim()?t&&t<1e3?"timeout must be at least 1000ms":null:"stop_string is required and cannot be empty",getDescription:e=>{let t=`Monitor serial output for "${e.stop_string}"`;return e.port&&(t+=` on ${e.port}`),e.baud_rate&&(t+=` at ${e.baud_rate} baud`),e.timeout&&3e4!==e.timeout&&(t+=` (${e.timeout/1e3}s timeout)`),e.description&&(t+=` - ${e.description}`),e.startup_commands&&e.startup_commands.length>0&&(t+=` (with ${e.startup_commands.length} startup command${e.startup_commands.length>1?"s":""})`),t},getLocations:()=>[{path:process.cwd(),type:"execute"}],getCommandRoot:()=>"serialMonitor",isAllowlisted:()=>FW.has("serialMonitor"),addToAllowlist:(e,t)=>{"always"!==t&&"command"!==t||FW.add("serialMonitor")},shouldConfirm:async({stop_string:e,port:t,baud_rate:n,interactive:r,startup_commands:i})=>{let o=`serial_monitor --stop-string "${e}"`;return r&&(o+=" --interactive"),i&&i.length>0&&(o+=` (${i.length} startup command${i.length>1?"s":""})`),{type:"execute",title:"Start serial monitor?",description:`Monitor serial output for "${e}" ${t?`on ${t}`:""} ${n?`at ${n} baud`:""}`,affectedPaths:[process.cwd()],isDestructive:!1}},execute:async(e,t)=>{try{const r=await async function(){const e=ae.join(process.cwd(),"EMBEDDER.md");try{if(!J.existsSync(e))return;const t=(await J.promises.readFile(e,"utf-8")).match(/<COMMANDS>([\s\S]*?)<\/COMMANDS>/);if(!t)return;const n=t[1],r={};if(!n||""===n.trim())return r;const i=n.split("\n");for(const e of i){const t=e.match(/^(\w+)\s*=\s*(.+)$/);if(t){const[,e,n]=t;if(!n)continue;const i=n.replace(/^\[|\]$/g,"").trim();if(!i)continue;switch(e){case"serial_monitor_command":r.serial_monitor_command=i;break;case"serial_port":r.serial_port=i;break;case"serial_baudrate":const e=parseInt(i);!isNaN(e)&&e>0&&(r.serial_baudrate=e);break;case"serial_monitor_interactive":r.serial_monitor_interactive="true"===i;break;case"serial_startup_commands":if(i.startsWith("[")&&i.endsWith("]")){const e=i.slice(1,-1);e.trim()&&(r.serial_startup_commands=e.split(",").map(e=>e.trim().replace(/^["']|["']$/g,"")).filter(e=>e.length>0))}else r.serial_startup_commands||(r.serial_startup_commands=[]),r.serial_startup_commands.push(i.replace(/^["']|["']$/g,""))}}}return Object.keys(r).length>0?r:void 0}catch(qK){return}}(),i=e.port||r?.serial_port||"/dev/ttyUSB0",o=e.baud_rate||r?.serial_baudrate||115200,s=e.timeout||3e4;let a;if(r?.serial_monitor_command){e.interactive||r.serial_monitor_interactive||(n=r.serial_monitor_command,["waf console","screen ","minicom","cu ","tip "].some(e=>n.includes(e)))?(t.updateOutput&&t.updateOutput(`Using interactive command: ${r.serial_monitor_command}\n`),a=await async function(e,t,n,r,i,o,s,a){try{const l=await import("./index-C1UxfNrr.js").then(e=>e.i),u=e.replace(/{port}/g,t).replace(/{baud}/g,n.toString());return new Promise(e=>{let t,n="",c=!1,d=!1;const p=l.spawn("bash",["-c",u],{name:"xterm-color",cols:80,rows:30,cwd:process.cwd(),env:{...process.env,TERM:"xterm-256color",COLUMNS:"80",LINES:"30"}});o&&o.length>0&&setTimeout(()=>{s&&s("\nSending startup commands:\n"),o.forEach((e,t)=>{setTimeout(()=>{s&&s(`> ${e}\n`),p.write(`${e}\r\n`)},500*t)})},2e3),t=setTimeout(()=>{c||(p.kill(),e({output:n,success:!1,reason:`Timeout: stop_string "${r}" not found within ${i/1e3} seconds`}))},i),p.onData(i=>{let o=$W(i);o=OW(o),n+=o,s&&s(n),!c&&o.includes(r)&&(c=!0,d=!0,clearTimeout(t),s&&s(`\nStop string "${r}" detected. Collecting additional data for 1 second...\n`),setTimeout(()=>{d=!1,p.kill(),e({output:n,success:!0})},1e3))}),p.onExit(i=>{c||(clearTimeout(t),e({output:n,success:!1,reason:`Process exited with code ${i.exitCode} before finding stop_string "${r}"`}))}),a&&a.addEventListener("abort",()=>{clearTimeout(t),p.kill(),e({output:n,success:!1,reason:"Operation was cancelled by user"})})})}catch(qK){return{output:"",success:!1,reason:`Failed to initialize PTY for interactive mode: ${qK instanceof Error?qK.message:String(qK)}. Check system PTY support.`}}}(r.serial_monitor_command,i,o,e.stop_string,s,e.startup_commands||r.serial_startup_commands,t.updateOutput,t.signal)):(t.updateOutput&&t.updateOutput(`Using custom command: ${r.serial_monitor_command}\n`),a=await async function(e,t,n,r,i,o,s){const a=e.replace(/{port}/g,t).replace(/{baud}/g,n.toString());return new Promise(e=>{let t,n="",l=!1;const u=Se("bash",["-c",a],{stdio:["ignore","pipe","pipe"],cwd:process.cwd()});t=setTimeout(()=>{l||(u.kill("SIGTERM"),e({output:n,success:!1,reason:`Timeout: stop_string "${r}" not found within ${i/1e3} seconds`}))},i),u.stdout?.on("data",i=>{let s=LW(i,"custom");n+=s,o&&o(n),!l&&s.includes(r)&&(l=!0,clearTimeout(t),o&&o(`\nStop string "${r}" detected. Collecting additional data for 1 second...\n`),setTimeout(()=>{u.kill("SIGTERM"),e({output:n,success:!0})},1e3))}),u.stderr?.on("data",e=>{let t=LW(e,"custom");n+=t,o&&o(n)}),u.on("exit",i=>{l||(clearTimeout(t),e({output:n,success:!1,reason:`Process exited with code ${i} before finding stop_string "${r}"`}))}),s&&s.addEventListener("abort",()=>{clearTimeout(t),u.kill("SIGTERM"),e({output:n,success:!1,reason:"Operation was cancelled by user"})})})}(r.serial_monitor_command,i,o,e.stop_string,s,t.updateOutput,t.signal))}else t.updateOutput&&t.updateOutput(`Opening direct serial connection to ${i} at ${o} baud...\n`),a=await async function(e,t,n,r,i,o){try{const{SerialPortStream:s}=await import("@serialport/stream"),{autoDetect:a}=await import("@serialport/bindings-cpp");return new Promise(l=>{let u,c="",d=!1,p=!1,f="";const h=()=>{const e=f.split(/\r?\n/);if(e.length>1){f=e.pop()||"";const t=e.join("\n")+(e.length>0?"\n":"");if(t){let e=$W(t);e=OW(e),e.trim()&&(c+=e,i&&i(c+(f||"")))}}},g=new s({path:e,baudRate:t,binding:a(),dataBits:8,stopBits:1,parity:"none",rtscts:!0,xon:!1,xoff:!1,autoOpen:!1}),A=setTimeout(()=>{d||(h(),g.close(),l({output:c,success:!1,reason:`Connection timeout: Could not open serial port ${e} within 5 seconds`}))},5e3);g.on("open",()=>{clearTimeout(A),i&&i(`Successfully connected to ${e} at ${t} baud\n`)}),g.open(e=>{if(e){clearTimeout(A);let t=`Failed to open serial port: ${e.message}`;e.message.includes("EACCES")||e.message.includes("Permission denied")?t+=". Try: sudo usermod -a -G dialout $USER (then logout/login)":e.message.includes("ENOENT")||e.message.includes("No such file")?t+=". Check that the device is connected and the port path is correct.":(e.message.includes("EBUSY")||e.message.includes("Resource busy"))&&(t+=". Port may be in use by another application."),l({output:c,success:!1,reason:t})}}),u=setTimeout(()=>{d||(h(),g.close(),l({output:c,success:!1,reason:`Timeout: stop_string "${n}" not found within ${r/1e3} seconds`}))},r),g.on("data",e=>{const t=MW(e);let r=e.toString(t);f+=r,h(),!d&&(c.includes(n)||r.includes(n)||f.includes(n))&&(d=!0,p=!0,clearTimeout(u),clearTimeout(A),i&&i(`\nStop string "${n}" detected. Collecting additional data for 1 second...\n`),setTimeout(()=>{p=!1,h(),g.close(),l({output:c,success:!0})},1e3))}),g.on("error",e=>{clearTimeout(u),clearTimeout(A),h();let t=`Serial port error: ${e.message}`;e.message.includes("EACCES")||e.message.includes("Permission denied")?t+=". Try: sudo usermod -a -G dialout $USER (then logout/login)":(e.message.includes("ENOENT")||e.message.includes("No such file"))&&(t+=". Check that the device is connected and the port path is correct."),l({output:c,success:!1,reason:t})}),o&&o.addEventListener("abort",()=>{clearTimeout(u),clearTimeout(A),h(),g.close(),l({output:c,success:!1,reason:"Operation was cancelled by user"})})})}catch(qK){return{output:"",success:!1,reason:`Failed to initialize serial port: ${qK instanceof Error?qK.message:String(qK)}. Check that the port exists and has proper permissions.`}}}(i,o,e.stop_string,s,t.updateOutput,t.signal);let l="Serial Monitor Results:\n\n";if(l+=`Port: ${i}\n`,l+=`Baud Rate: ${o}\n`,l+=`Stop String: "${e.stop_string}"\n`,l+=`Status: ${a.success?"SUCCESS":"FAILED"}\n`,a.reason&&(l+=`Reason: ${a.reason}\n`),!a.success&&a.output.length>0){/[\x00-\x08\x0E-\x1F\x7F-\u00FF]/.test(a.output)&&(l+="\nNOTE: Output contains non-printable characters, which may indicate:\n",l+="- Incorrect baud rate (try common rates: 9600, 19200, 38400, 57600, 115200)\n",l+="- Mismatched data bits, stop bits, or parity settings\n",l+="- Device not ready or sending binary data\n")}a.output.length>1e4?l+=`\n--- Serial Output (truncated) ---\n${a.output.substring(0,1e4)}\n... (output truncated, ${a.output.length} total characters)`:l+=`\n--- Serial Output ---\n${a.output}`;let u=a.success?`Serial monitor completed - found "${e.stop_string}"`:`Serial monitor failed - ${a.reason}`;return a.output.trim()&&(u+=`\n\nCaptured Output:\n${a.output}`),{success:a.success,llmContent:l,returnDisplay:u,summary:a.success?`Found "${e.stop_string}"`:`Failed: ${a.reason}`,locations:[{path:process.cwd(),type:"execute"}],metadata:{port:i,baudRate:o,stopString:e.stop_string,timeout:s,outputLength:a.output.length}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Serial monitor error: ${t}`,returnDisplay:`❌ Serial monitor failed: ${t}`,summary:`Error: ${t}`}}var n}}),jW=Mz({metadata:{name:"todowrite",displayName:"Todo Write",description:"Create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.",category:"development",icon:"✓",isOutputMarkdown:!1},inputSchema:M$,validateParams:({todos:e})=>{for(const r of e){if(!r.content||0===r.content.trim().length)return"All todo items must have non-empty content";if(!r.id||0===r.id.trim().length)return"All todo items must have a valid ID"}const t=e.map(e=>e.id),n=new Set(t);if(t.length!==n.size)return"Todo items must have unique IDs";return e.filter(e=>e.status===k$).length>1?"Only one todo item can be 'in_progress' at a time":null},getDescription:({todos:e})=>L$($$(e)),getLocations:()=>[],execute:async({todos:e},t)=>{try{const t="active",n=e.map(e=>({...e,id:e.id||`todo_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,createdAt:e.createdAt||(new Date).toISOString(),completedAt:e.status!==x$||e.completedAt?e.completedAt:(new Date).toISOString()}));oM(t,n);const r=$$(n),i=(L$(r),n.map(e=>`${e.status===x$?"[x]":"[ ]"} ${e.status===Q$?`~~${e.content}~~`:e.status===k$?`**${e.content}**`:e.content}`).join("\n"));return{success:!0,summary:`Updated todo list with ${n.length} items (${r.pendingCount} pending, ${r.inProgressCount} in progress, ${r.completedCount} completed)`,llmContent:`Todo list updated successfully:\n${i}`,metadata:{todoMetadata:r,todos:n,phase:r.phase,sessionId:t}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error updating todo list: ${t}`,returnDisplay:`Error updating todo list: ${t}`,summary:"Failed to update todo list"}}}}),UW=Mz({metadata:{name:"todoread",displayName:"Todo Read",description:"Read your current todo list to check progress and see what tasks remain",category:"development",icon:"📋",isOutputMarkdown:!1},inputSchema:ug({}),validateParams:()=>null,getDescription:()=>"Reading current todo list",getLocations:()=>[],execute:async(e,t)=>{try{const e="active",t=iM(e);if(0===t.length)return{success:!0,summary:"No todos currently tracked",llmContent:"No todos found for this session",metadata:{todoMetadata:{todos:[],totalCount:0,pendingCount:0,inProgressCount:0,completedCount:0,cancelledCount:0,phase:"creating"},todos:[],sessionId:e}};const n=$$(t),r=(L$(n),t.map(e=>`${e.status===x$?"[x]":"[ ]"} ${e.status===Q$?`~~${e.content}~~`:e.status===k$?`**${e.content}**`:e.content}`).join("\n")),i=[n.pendingCount>0?`${n.pendingCount} pending`:null,n.inProgressCount>0?`${n.inProgressCount} in progress`:null,n.completedCount>0?`${n.completedCount} completed`:null,n.cancelledCount>0?`${n.cancelledCount} cancelled`:null].filter(Boolean).join(", ");return{success:!0,summary:`Found ${n.totalCount} todos: ${i}`,llmContent:`Current todo list:\n${r}`,metadata:{todoMetadata:n,todos:t,sessionId:e}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error reading todo list: ${t}`,returnDisplay:`Error reading todo list: ${t}`,summary:"Failed to read todo list"}}}}),zW=Mz({metadata:{name:"documentSearch",displayName:"Document Search",description:"Performs semantic search across documentation using vector embeddings. This tool is useful for finding relevant contexts based on semantic similarity to your query.",category:"search",icon:"🔍",requiresConfirmation:!1},inputSchema:ug({query:mh().min(1).describe("The search query to find relevant component information."),max_results:jh().min(1).max(100).optional().describe("Maximum number of results to return (default: 10)."),threshold:jh().min(0).max(1).optional().describe("Minimum similarity threshold between 0 and 1 (default: 0.0).")}),validateParams:({query:e,max_results:t,threshold:n})=>e&&"string"==typeof e&&0!==e.trim().length?void 0!==t&&("number"!=typeof t||t<1)?"max_results must be a positive number if provided":void 0!==n&&("number"!=typeof n||n<0||n>1)?"threshold must be a number between 0 and 1 if provided":null:"query is required and must be a non-empty string",getDescription:({query:e,max_results:t,threshold:n})=>{let r=`Searching for content related to: "${e}"`;return t&&(r+=` (max ${t} results)`),n&&(r+=` (min similarity: ${n})`),r},getLocations:()=>[],execute:async({query:e,max_results:t,threshold:n},r)=>{try{const i=r.teamId,o=r.projectId;if(!i||!o)return{success:!1,llmContent:"Error: No team/project selected. Please select a team and project in the CLI before using document_search.",returnDisplay:"No team/project selected. Select a team and project to use document search."};if(!r.apiFetch)return{success:!1,llmContent:"Error: No authentication available. Please authenticate first.",returnDisplay:"Authentication required. Please log in first."};const s={query:e,max_results:t||10,threshold:n||0},a=await r.apiFetch(`api/v1/projects/${o}/retrieve-context`,{method:"POST",body:JSON.stringify(s)},{},2);return{success:!0,llmContent:a.text&&a.text.length>0?a.text:"",returnDisplay:a.text&&a.text.length>0?`Found results for "${e}"`:"No relevant information found."}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error: document_search failed - ${t}`,returnDisplay:`Error: ${t}`}}}}),GW=Mz({metadata:{name:"web-search",displayName:"Web Context",description:"Retrieves contextual information from Internet.",category:"search",icon:"🧠",requiresConfirmation:!1},inputSchema:ug({query:mh().min(1,"Query cannot be empty.").describe("The search query to retrieve contextual information for."),tokensNum:fg([mh(),jh()]).optional().default("dynamic").describe("Token limit for the response. Can be 'dynamic' or a number.")}),validateParams:({query:e})=>e.trim()?null:"query is required and must be a non-empty string",getDescription:({query:e})=>`Fetching context for "${e}"`,getLocations:()=>[],execute:async({query:e,tokensNum:t="dynamic"},n)=>{try{if(!n.apiFetch)return{success:!1,llmContent:"Error: No authentication available. Please authenticate first.",returnDisplay:"Authentication required. Please log in first."};const r=await n.apiFetch("api/v1/proxy/web-context",{method:"POST",body:JSON.stringify({query:e})},{},2);return r.response?{success:!0,llmContent:r.response,returnDisplay:`Retrieved context for "${e}"`,summary:`Web context retrieved for "${e}"`,metadata:{query:e,tokensNum:t,responseLength:r.response.length}}:{success:!1,llmContent:"No context data returned from Web.",returnDisplay:"No context received."}}catch(r){const e=r instanceof Error?r.message:String(r);return{success:!1,llmContent:`Web context request failed: ${e}`,returnDisplay:`Error: ${e}`}}}}),HW={"codebase-explorer":{id:"codebase-explorer",name:"codebase-explorer",displayName:"Codebase Explorer",description:"Explore and analyze codebase structure, find files, understand relationships",category:"search",tools:{readFile:!0,readManyFiles:!0,listDirectory:!0,grep:!0,glob:!0,documentSearch:!0,writeFile:!1,editFile:!1,shell:!1,build:!1},systemPrompt:"You are a specialized codebase exploration agent. Your role is to:\n1. Navigate and understand project structure\n2. Find specific files, functions, and patterns\n3. Analyze code relationships and dependencies\n4. Provide comprehensive codebase insights\n5. Search across multiple files efficiently\n\nFocus on READ-ONLY operations. Do not modify files or execute commands.\nWhen exploring, provide clear summaries of what you found and where.",maxToolCalls:15,autoInvokable:!0},"code-analyzer":{id:"code-analyzer",name:"code-analyzer",displayName:"Code Analyzer",description:"Deep analysis of code quality, patterns, security issues, and technical debt",category:"analysis",tools:{readFile:!0,readManyFiles:!0,grep:!0,glob:!0,listDirectory:!0,documentSearch:!0,writeFile:!1,editFile:!1,shell:!1,build:!1},systemPrompt:"You are a specialized code analysis agent. Your expertise includes:\n1. Code quality assessment and best practices\n2. Security vulnerability detection\n3. Performance bottleneck identification\n4. Technical debt analysis\n5. Architecture pattern recognition\n6. Dependency analysis\n\nProvide detailed, actionable insights with specific file references and line numbers.\nFocus on analysis only - do not modify code.",maxToolCalls:20,autoInvokable:!0},"file-manager":{id:"file-manager",name:"file-manager",displayName:"File Manager",description:"Handle file operations, refactoring, bulk edits, and file organization",category:"development",tools:{readFile:!0,readManyFiles:!0,writeFile:!0,editFile:!0,listDirectory:!0,grep:!0,glob:!0,shell:!1,build:!1},systemPrompt:"You are a specialized file management agent. Your responsibilities:\n1. Bulk file operations and refactoring\n2. Code reorganization and cleanup\n3. File creation and modification\n4. Directory structure management\n5. Safe file operations with backups when needed\n\nAlways validate operations and provide clear summaries of changes made.\nUse readFile before editFile to understand current content.",maxToolCalls:25,autoInvokable:!1},"build-engineer":{id:"build-engineer",name:"build-engineer",displayName:"Build Engineer",description:"Handle build processes, testing, dependency management, and development workflows",category:"development",tools:{readFile:!0,listDirectory:!0,shell:!0,build:!0,grep:!0,glob:!0,writeFile:!1,editFile:!1},systemPrompt:"You are a specialized build and development workflow agent. Your expertise:\n1. Build system configuration and troubleshooting\n2. Dependency management and updates\n3. Test execution and CI/CD processes\n4. Development environment setup\n5. Performance optimization and monitoring\n\nFocus on build tools, testing, and development workflow automation.\nAlways explain what commands you're running and why.",maxToolCalls:10,autoInvokable:!1},"general-assistant":{id:"general-assistant",name:"general-assistant",displayName:"General Assistant",description:"Multi-step tasks requiring coordination of multiple tools and operations",category:"general",tools:{readFile:!0,readManyFiles:!0,writeFile:!0,editFile:!0,listDirectory:!0,grep:!0,glob:!0,documentSearch:!0,shell:!0,build:!0},systemPrompt:"You are a general-purpose assistant agent capable of complex, multi-step tasks.\nYour strengths include:\n1. Coordinating multiple operations across different tool categories\n2. Complex problem-solving requiring multiple approaches\n3. Research and implementation in one workflow\n4. Cross-domain tasks (search + analysis + implementation)\n\nBreak down complex tasks into logical steps and execute systematically.\nAlways summarize what you accomplished and what tools you used.",maxToolCalls:30,autoInvokable:!1}};class WW{static agents=new Map;static initialized=!1;static initialize(){if(!this.initialized){for(const e of Object.values(HW))this.agents.set(e.id,e);this.initialized=!0}}static getAgent(e){return this.initialize(),this.agents.get(e)||null}static getAllAgents(){return this.initialize(),Array.from(this.agents.values())}static getAgentsByCategory(e){return this.initialize(),Array.from(this.agents.values()).filter(t=>t.category===e)}static getAutoInvokableAgents(){return this.initialize(),Array.from(this.agents.values()).filter(e=>e.autoInvokable)}static registerAgent(e){this.initialize(),this.agents.set(e.id,e)}static unregisterAgent(e){return this.initialize(),this.agents.delete(e)}static getAgentIds(){return this.initialize(),Array.from(this.agents.keys())}static searchAgents(e){this.initialize();const t=e.toLowerCase();return Array.from(this.agents.values()).filter(e=>e.name.toLowerCase().includes(t)||e.displayName.toLowerCase().includes(t)||e.description.toLowerCase().includes(t))}}WW.initialize();class qW{static sessions=new Map;static eventHandlers=new Map;static async createSession(e,t){const n=WW.getAgent(t.agentType);if(!n)throw new Error(`Unknown agent type: ${t.agentType}`);const r=this.generateSessionId(),i={id:r,parentSessionId:e,agentId:n.id,description:t.description,status:"running",startTime:new Date,toolCalls:0};return this.sessions.set(r,i),this.emitEvent({type:"session_started",sessionId:r,agentId:n.id,timestamp:new Date,data:{description:t.description}}),i}static async executeTask(e,t,n){const r=WW.getAgent(e.agentId);if(!r)throw new Error(`Agent ${e.agentId} not found`);try{const i=this.buildSystemPrompt(r,t),o=this.getAgentTools(r),s=this.getModel(r,n),a=await async function({model:e,tools:t,toolChoice:n,system:r,prompt:i,messages:o,maxRetries:s,abortSignal:a,headers:l,stopWhen:u=UE(1),experimental_output:c,experimental_telemetry:d,providerOptions:p,experimental_activeTools:f,activeTools:h=f,experimental_prepareStep:g,prepareStep:A=g,experimental_repairToolCall:m,experimental_download:y,experimental_context:b,_internal:{generateId:v=qE,currentDate:E=()=>new Date}={},onStepFinish:I,...w}){const C=Jv(e),_=NE(u),{maxRetries:B,retry:D}=FE({maxRetries:s,abortSignal:a}),S=rE(w),k=wA(null!=l?l:{},`ai/${Vv}`),x=EE({model:C,telemetry:d,headers:k,settings:{...S,maxRetries:B}}),Q=await yE({system:r,prompt:i,messages:o}),N=_E(d);try{return await BE({name:"ai.generateText",attributes:SE({telemetry:d,attributes:{...vE({operationId:"ai.generateText",telemetry:d}),...x,"ai.model.provider":C.provider,"ai.model.id":C.modelId,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:i,messages:o})}}}),tracer:N,fn:async e=>{var i,o,s,l,u,f,g;const B=rE(w);let S,T=[],R=[];const F=[],M=[];do{const e=[...Q.messages,...F],_=await(null==A?void 0:A({model:C,steps:M,stepNumber:M.length,messages:e})),O=await nE({prompt:{system:null!=(i=null==_?void 0:_.system)?i:Q.system,messages:null!=(o=null==_?void 0:_.messages)?o:e},supportedUrls:await C.supportedUrls,download:y}),$=Jv(null!=(s=null==_?void 0:_.model)?s:C),{toolChoice:L,tools:P}=iE({tools:t,toolChoice:null!=(l=null==_?void 0:_.toolChoice)?l:n,activeTools:null!=(u=null==_?void 0:_.activeTools)?u:h});S=await D(()=>{var e;return BE({name:"ai.generateText.doGenerate",attributes:SE({telemetry:d,attributes:{...vE({operationId:"ai.generateText.doGenerate",telemetry:d}),...x,"ai.model.provider":$.provider,"ai.model.id":$.modelId,"ai.prompt.messages":{input:()=>kE(O)},"ai.prompt.tools":{input:()=>null==P?void 0:P.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>null!=L?JSON.stringify(L):void 0},"gen_ai.system":$.provider,"gen_ai.request.model":$.modelId,"gen_ai.request.frequency_penalty":w.frequencyPenalty,"gen_ai.request.max_tokens":w.maxOutputTokens,"gen_ai.request.presence_penalty":w.presencePenalty,"gen_ai.request.stop_sequences":w.stopSequences,"gen_ai.request.temperature":null!=(e=w.temperature)?e:void 0,"gen_ai.request.top_k":w.topK,"gen_ai.request.top_p":w.topP}}),tracer:N,fn:async e=>{var t,n,r,i,o,s,l,u;const f=await $.doGenerate({...B,tools:P,toolChoice:L,responseFormat:null==c?void 0:c.responseFormat,prompt:O,providerOptions:p,abortSignal:a,headers:k}),h={id:null!=(n=null==(t=f.response)?void 0:t.id)?n:v(),timestamp:null!=(i=null==(r=f.response)?void 0:r.timestamp)?i:E(),modelId:null!=(s=null==(o=f.response)?void 0:o.modelId)?s:$.modelId,headers:null==(l=f.response)?void 0:l.headers,body:null==(u=f.response)?void 0:u.body};return e.setAttributes(SE({telemetry:d,attributes:{"ai.response.finishReason":f.finishReason,"ai.response.text":{output:()=>ME(f.content)},"ai.response.toolCalls":{output:()=>{const e=ZE(f.content);return null==e?void 0:JSON.stringify(e)}},"ai.response.id":h.id,"ai.response.model":h.modelId,"ai.response.timestamp":h.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(f.providerMetadata),"ai.usage.promptTokens":f.usage.inputTokens,"ai.usage.completionTokens":f.usage.outputTokens,"gen_ai.response.finish_reasons":[f.finishReason],"gen_ai.response.id":h.id,"gen_ai.response.model":h.modelId,"gen_ai.usage.input_tokens":f.usage.inputTokens,"gen_ai.usage.output_tokens":f.usage.outputTokens}})),{...f,response:h}}})});const j=await Promise.all(S.content.filter(e=>"tool-call"===e.type).map(n=>LE({toolCall:n,tools:t,repairToolCall:m,system:r,messages:e})));for(const n of j){if(n.invalid)continue;const r=t[n.toolName];null!=(null==r?void 0:r.onInputAvailable)&&await r.onInputAvailable({input:n.input,toolCallId:n.toolCallId,messages:e,abortSignal:a,experimental_context:b})}const U=j.filter(e=>e.invalid&&e.dynamic);R=[];for(const t of U)R.push({type:"tool-error",toolCallId:t.toolCallId,toolName:t.toolName,input:t.input,error:BA(t.error),dynamic:!0});T=j.filter(e=>!e.providerExecuted),null!=t&&R.push(...await JE({toolCalls:T.filter(e=>!e.invalid),tools:t,tracer:N,telemetry:d,messages:e,abortSignal:a,experimental_context:b}));const z=VE({content:S.content,toolCalls:j,toolOutputs:R});F.push(...WE({content:z,tools:t}));const G=new jE({content:z,finishReason:S.finishReason,usage:S.usage,warnings:S.warnings,providerMetadata:S.providerMetadata,request:null!=(f=S.request)?f:{},response:{...S.response,messages:structuredClone(F)}});nv(null!=(g=S.warnings)?g:[]),M.push(G),await(null==I?void 0:I(G))}while(T.length>0&&R.length===T.length&&!(await zE({stopConditions:_,steps:M})));e.setAttributes(SE({telemetry:d,attributes:{"ai.response.finishReason":S.finishReason,"ai.response.text":{output:()=>ME(S.content)},"ai.response.toolCalls":{output:()=>{const e=ZE(S.content);return null==e?void 0:JSON.stringify(e)}},"ai.response.providerMetadata":JSON.stringify(S.providerMetadata),"ai.usage.promptTokens":S.usage.inputTokens,"ai.usage.completionTokens":S.usage.outputTokens}}));const O=M[M.length-1];return new KE({steps:M,resolvedOutput:await(null==c?void 0:c.parseOutput({text:O.text},{response:O.response,usage:O.usage,finishReason:O.finishReason}))})}})}catch(qK){throw bE(qK)}}({model:s,system:i,prompt:t.prompt,tools:o,stopWhen:UE(r.maxToolCalls||10)}),l={success:!0,agentUsed:r.id,summary:this.extractSummary(a.text),fullResponse:a.text,toolsUsed:this.extractToolUsage(a.toolCalls),metadata:{totalTokens:a.usage?.totalTokens,toolRoundtrips:a.toolCalls?.length||0}};return e.status="completed",e.endTime=new Date,e.result=l,this.emitEvent({type:"session_completed",sessionId:e.id,agentId:r.id,timestamp:new Date,data:{result:l}}),l}catch(qK){const n=qK instanceof Error?qK.message:String(qK);e.status="failed",e.endTime=new Date;const i={success:!1,agentUsed:r.id,summary:`Task failed: ${n}`,fullResponse:n,toolsUsed:[]};return e.result=i,this.emitEvent({type:"session_failed",sessionId:e.id,agentId:r.id,timestamp:new Date,data:{error:n}}),i}}static abortSession(e){const t=this.sessions.get(e);return!(!t||"running"!==t.status)&&(t.status="aborted",t.endTime=new Date,this.emitEvent({type:"session_aborted",sessionId:e,agentId:t.agentId,timestamp:new Date,data:{}}),!0)}static getSession(e){return this.sessions.get(e)||null}static getSessionsByParent(e){return Array.from(this.sessions.values()).filter(t=>t.parentSessionId===e)}static onEvent(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t),()=>{const n=this.eventHandlers.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}}static emitEvent(e){(this.eventHandlers.get(e.sessionId)||[]).forEach(t=>{try{t(e)}catch(qK){ex.error("Error in event handler:",qK)}})}static buildSystemPrompt(e,t){return`${e.systemPrompt||""}\n\n${t.sessionContext?`\nWorking Directory: ${t.sessionContext.workingDirectory}\nProject Root: ${t.sessionContext.projectRoot}\n`:""}\nAvailable Tools:\n${Object.entries(e.tools).filter(([e,t])=>t).map(([e,t])=>`- ${e}`).join("\n")}\n\nTask: ${t.description}\n\nInstructions: ${t.prompt}\n\nIMPORTANT:\n1. Focus on your specialized role and expertise\n2. Use tools efficiently and provide clear summaries\n3. If you cannot complete the task with your available tools, explain why\n4. Always provide a comprehensive final summary of what you accomplished`}static getAgentTools(e){const t={};for(const[n,r]of Object.entries(e.tools))r&&tq[n]&&(t[n]=tq[n]);return t}static getModel(e,t){const n={...{anthropic:"https://backend-service-prod.embedder.dev/api/v1/proxy/anthropic/",openai:"https://backend-service-prod.embedder.dev/api/v1/proxy/openai/",google:"https://backend-service-prod.embedder.dev/api/v1/proxy/google/"},...t?.baseUrls},r=t?.headers||{};if(e.model){if("openai"===e.model.providerID){return vF({baseURL:n.openai,apiKey:"embedder-cli",headers:r})(e.model.modelID)}if("anthropic"===e.model.providerID){return GF({baseURL:n.anthropic,apiKey:"embedder-cli",headers:r})(e.model.modelID)}if("google"===e.model.providerID){return uR({baseURL:n.google,apiKey:"embedder-cli",headers:r})(e.model.modelID)}}return uR({baseURL:n.google,apiKey:"embedder-cli",headers:r})("gemini-2.5-pro")}static extractSummary(e){const t=e.split("\n").filter(e=>e.trim());for(const r of t)if(r.toLowerCase().includes("summary:")||r.toLowerCase().includes("result:")||r.toLowerCase().includes("completed:"))return r.replace(/^[^:]*:\s*/,"").trim();const n=t.find(e=>e.length>10);return n?n.length>100?n.substring(0,97)+"...":n:"Task completed"}static extractToolUsage(e){return e?e.map(e=>({toolName:e.toolName||"unknown",status:!1!==e.result?.success?"success":"error",summary:e.result?.summary||e.result?.llmContent||"Tool executed"})):[]}static generateSessionId(){return`agent_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}static cleanup(){const e=Array.from(this.sessions.values()).sort((e,t)=>(t.endTime||t.startTime).getTime()-(e.endTime||e.startTime).getTime());if(e.length>50){e.slice(50).forEach(e=>{this.sessions.delete(e.id),this.eventHandlers.delete(e.id)})}}}const JW=Mz({metadata:{name:"task",displayName:"Task Delegation",description:"Delegate complex, multi-step tasks to specialized agents",category:"system",isOutputMarkdown:!0,canStream:!0,requiresConfirmation:!1},inputSchema:ug({description:mh().min(3).max(50).describe("A short (3-5 words) description of the task"),prompt:mh().min(10).describe("Detailed instructions for the agent to perform the task"),agentType:mh().describe("The type of specialized agent to use for this task")}),validateParams:e=>{if(!WW.getAgent(e.agentType)){const t=WW.getAgentIds();return`Unknown agent type: ${e.agentType}. Available agents: ${t.join(", ")}`}return e.description.split(" ").length>8?"Description should be 3-5 words, not a full sentence":null},getDescription:e=>`Delegating "${e.description}" to ${e.agentType} agent`,async shouldConfirm(e,t){const n=WW.getAgent(e.agentType);return n?n.autoInvokable?null:{type:"execute",title:`Delegate Task to ${n.displayName}`,description:`Agent "${n.displayName}" will perform: ${e.description}\n\nTask Details: ${e.prompt}\n\nThis agent has access to the following tools:\n${Object.entries(n.tools).filter(([e,t])=>t).map(([e,t])=>`• ${e}`).join("\n")}`,affectedPaths:[],isDestructive:Object.entries(n.tools).some(([e,t])=>t&&["writeFile","editFile","shell","build"].includes(e))}:null},async execute(e,t){try{const n=WW.getAgent(e.agentType);if(!n)return{success:!1,llmContent:`Error: Unknown agent type "${e.agentType}"`,summary:"Invalid agent type"};const r={description:e.description,prompt:e.prompt,agentType:e.agentType,sessionContext:{workingDirectory:t.workingDirectory,projectRoot:t.projectRoot,teamId:t.teamId,projectId:t.projectId}},i=await qW.createSession(t.sessionId||"unknown",r);if(t.updateOutput){const e=qW.onEvent(i.id,e=>{if("tool_executed"===e.type&&t.updateOutput){const n=e.data;t.updateOutput(`🔧 ${n.toolName}: ${n.summary||"executed"}\n`)}});setTimeout(e,3e5)}const o=function(e){let t=process.env.EMBEDDER_FIREBASE_TOKEN;if(!t)try{const e=fT();t=e?.accessToken}catch(qK){}const n={"x-platform-type":process.platform,"x-sandbox-type":"sandbox-exec"===process.env.SANDBOX?"exec":null!=process.env.SANDBOX?"generic":"none","x-folder-type":kT()?"versioned":"non-versioned","x-client-type":"cli"};t&&(n.Authorization=`Bearer ${t}`);e.sessionId&&(n["x-session-id"]=e.sessionId);e.projectId&&(n["x-project-id"]=e.projectId);n["x-agent-mode"]="act",e.environmentContext&&(n["x-working-directory"]=e.workingDirectory,n["x-project-type"]=e.environmentContext.projectType,n["x-has-git"]=e.environmentContext.isGitRepository.toString(),n["x-context-timestamp"]=e.environmentContext.dateTime);return{headers:n,baseUrls:{anthropic:"https://backend-service-prod.embedder.dev/api/v1/proxy/anthropic/",openai:"https://backend-service-prod.embedder.dev/api/v1/proxy/openai/",google:"https://backend-service-prod.embedder.dev/api/v1/proxy/google/"}}}(t),s=await qW.executeTask(i,r,o),a=function(e,t){const n=t.success?"✅":"❌",r=t.toolsUsed?.length>0?`\n\n**Tools Used:**\n${t.toolsUsed.map(e=>`• ${e.toolName}: ${e.summary}`).join("\n")}`:"";return`## ${n} ${e} Task Result\n\n**Summary:** ${t.summary}\n\n**Details:**\n${t.fullResponse}${r}`}(n.displayName,s);return{success:s.success,llmContent:a,summary:`${n.displayName}: ${s.summary}`,metadata:{agentUsed:s.agentUsed,toolsUsed:s.toolsUsed,sessionId:i.id,...s.metadata}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`**Task Execution Failed**\n\nError: ${t}`,summary:`Task failed: ${t}`}}}});const KW=ug({label:mh().min(1).max(50).describe("The display text for this option"),description:mh().min(1).describe("Explanation of what this option means")}),ZW=ug({question:mh().min(1).describe("The complete question to ask the user (should end with '?')"),header:mh().min(1).max(12).describe("Very short label displayed as a chip/tag (max 12 chars)"),options:ag(KW).min(2).max(4).describe("The available choices (2-4 options)"),multiSelect:Hh().describe("Set to true to allow multiple selections instead of just one")}),VW=ug({questions:ag(ZW).min(1).max(4).describe("Array of 1-4 related questions to ask the user. IMPORTANT: Ask multiple questions at once when drilling down (e.g., ask about category, subcategory, and specific options together). This creates a better user experience than asking questions one at a time.")});let YW=null;function XW(e){YW=e}const eq=Mz({metadata:{name:"askQuestion",displayName:"Ask Question",description:"Ask the user interactive questions with multiple-choice options. IMPORTANT: Ask multiple related questions at once (up to 4) rather than one at a time - this provides a much better UX. For example, if determining a hardware setup, ask about family, specific chip, and configuration preferences all together. Each question supports 2-4 options and can be single or multi-select.",category:"development",icon:"?",isOutputMarkdown:!1},inputSchema:VW,validateParams:({questions:e})=>{const t=e.map(e=>e.header),n=new Set(t);if(t.length!==n.size)return"All questions must have unique headers";for(const r of e)if(!r.question.trim().endsWith("?"))return"All questions should end with a question mark";return null},getDescription:({questions:e})=>{const t=e.length,n=e[0]?.header||"Question";return 1===t?`Asking: ${n}`:`Asking ${t} questions`},getLocations:()=>[],execute:async({questions:e},t)=>{try{if(!YW)return{success:!1,llmContent:"Question handler not initialized. This tool requires UI integration to collect user responses.",summary:"Failed to ask questions"};const t={questions:e,id:`question-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now()},n=await YW(t),r=Object.entries(n.answers).map(([e,t])=>`**${e}**: ${t.isCustom?`Custom: ${t.answers.join(", ")}`:t.answers.join(", ")}`).join("\n");return{success:!0,summary:`User answered ${Object.keys(n.answers).length} question(s)`,llmContent:`User responses:\n${r}`,metadata:{promptId:t.id,responseId:n.promptId,answers:n.answers,timestamp:n.timestamp}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error asking questions: ${t}`,returnDisplay:`Error asking questions: ${t}`,summary:"Failed to ask questions"}}}}),tq={readFile:UH,readManyFiles:JH,writeFile:aW,editFile:vW,listDirectory:IW,grep:BW,glob:DW,documentSearch:zW,webSearch:GW,build:RW,todoWrite:jW,todoRead:UW,askQuestion:eq,shell:TW,serialMonitor:PW,task:JW},nq={readFile:!0,readManyFiles:!0,listDirectory:!0,grep:!0,glob:!0,documentSearch:!0,todoRead:!0,todoWrite:!0,askQuestion:!0,writeFile:!1,editFile:!1,shell:!1,build:!1,serialMonitor:!1};function rq({suggestions:e,selectedIndex:t,width:n}){if(!e||0===e.length)return null;const r=Math.max(0,Math.min(t-8+1,e.length-8)),i=Math.min(r+8,e.length),o=e.slice(r,i),s=o.length>0?Math.max(...o.map(e=>(e.label||"").length)):12,a=Math.min(Math.max(s+2,12),Math.floor(n/3));return We.jsxs(ki,{flexDirection:"column",width:n,children:[o.map((e,i)=>{const o=r+i===t?FM:QM;return We.jsxs(ki,{flexDirection:"row",width:n,children:[We.jsx(xi,{color:o,children:" "}),We.jsx(ki,{width:a,flexShrink:0,children:We.jsx(xi,{color:o,children:e.label})}),We.jsx(ki,{flexGrow:1,children:We.jsx(xi,{color:o,children:e.description})})]},`${e.value}-${i}`)}),e.length>8&&We.jsxs(xi,{color:QM,children:["(",t+1,"/",e.length,")"]})]})}var iq,oq,sq,aq,lq,uq,cq,dq,pq,fq,hq,gq,Aq,mq,yq,bq,vq,Eq,Iq,wq,Cq,_q,Bq,Dq,Sq,kq,xq,Qq,Nq,Tq,Rq,Fq,Mq,Oq,$q,Lq,Pq,jq,Uq,zq,Gq,Hq,Wq,qq,Jq,Kq,Zq,Vq,Yq,Xq,eJ,tJ,nJ,rJ,iJ,oJ,sJ,aJ,lJ,uJ,cJ,dJ,pJ,fJ,hJ,gJ,AJ,mJ,yJ,bJ,vJ,EJ,IJ,wJ,CJ,_J,BJ,DJ,SJ,kJ,xJ,QJ,NJ,TJ,RJ,FJ,MJ,OJ,$J,LJ={exports:{}};function PJ(){if(oq)return iq;oq=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return iq={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:e,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}function jJ(){if(aq)return sq;aq=1;const e="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};return sq=e}function UJ(){return lq||(lq=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=PJ(),o=jJ(),s=(t=e.exports={}).re=[],a=t.safeRe=[],l=t.src=[],u=t.safeSrc=[],c=t.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",i],[p,r]],h=(e,t,n)=>{const r=(e=>{for(const[t,n]of f)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e})(t),i=d++;o(e,i,t),c[e]=i,l[i]=t,u[i]=r,s[i]=new RegExp(t,n?"g":void 0),a[i]=new RegExp(r,n?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),h("MAINVERSION",`(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${l[c.NONNUMERICIDENTIFIER]}|${l[c.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${l[c.NONNUMERICIDENTIFIER]}|${l[c.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${l[c.PRERELEASEIDENTIFIER]}(?:\\.${l[c.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${l[c.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[c.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${p}+`),h("BUILD",`(?:\\+(${l[c.BUILDIDENTIFIER]}(?:\\.${l[c.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${l[c.MAINVERSION]}${l[c.PRERELEASE]}?${l[c.BUILD]}?`),h("FULL",`^${l[c.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${l[c.MAINVERSIONLOOSE]}${l[c.PRERELEASELOOSE]}?${l[c.BUILD]}?`),h("LOOSE",`^${l[c.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${l[c.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${l[c.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:${l[c.PRERELEASE]})?${l[c.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:${l[c.PRERELEASELOOSE]})?${l[c.BUILD]}?)?)?`),h("XRANGE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h("COERCE",`${l[c.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",l[c.COERCEPLAIN]+`(?:${l[c.PRERELEASE]})?(?:${l[c.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",l[c.COERCE],!0),h("COERCERTLFULL",l[c.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${l[c.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",h("TILDE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${l[c.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",h("CARET",`^${l[c.LONECARET]}${l[c.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${l[c.LONECARET]}${l[c.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${l[c.GTLT]}\\s*(${l[c.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]}|${l[c.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${l[c.XRANGEPLAIN]})\\s+-\\s+(${l[c.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${l[c.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[c.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(LJ,LJ.exports)),LJ.exports}function zJ(){if(cq)return uq;cq=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return uq=n=>n?"object"!=typeof n?e:n:t}function GJ(){if(pq)return dq;pq=1;const e=/^[0-9]+$/,t=(t,n)=>{const r=e.test(t),i=e.test(n);return r&&i&&(t=+t,n=+n),t===n?0:r&&!i?-1:i&&!r?1:t<n?-1:1};return dq={compareIdentifiers:t,rcompareIdentifiers:(e,n)=>t(n,e)}}function HJ(){if(hq)return fq;hq=1;const e=jJ(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:n}=PJ(),{safeRe:r,t:i}=UJ(),o=zJ(),{compareIdentifiers:s}=GJ();class a{constructor(s,l){if(l=o(l),s instanceof a){if(s.loose===!!l.loose&&s.includePrerelease===!!l.includePrerelease)return s;s=s.version}else if("string"!=typeof s)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof s}".`);if(s.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",s,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const u=s.trim().match(l.loose?r[i.LOOSE]:r[i.FULL]);if(!u)throw new TypeError(`Invalid Version: ${s}`);if(this.raw=s,this.major=+u[1],this.minor=+u[2],this.patch=+u[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");u[4]?this.prerelease=u[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<n)return t}return e}):this.prerelease=[],this.build=u[5]?u[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(e("SemVer.compare",this.version,this.options,t),!(t instanceof a)){if("string"==typeof t&&t===this.version)return 0;t=new a(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(e){return e instanceof a||(e=new a(e,this.options)),s(this.major,e.major)||s(this.minor,e.minor)||s(this.patch,e.patch)}comparePre(t){if(t instanceof a||(t=new a(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let n=0;do{const r=this.prerelease[n],i=t.prerelease[n];if(e("prerelease compare",n,r,i),void 0===r&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===r)return-1;if(r!==i)return s(r,i)}while(++n)}compareBuild(t){t instanceof a||(t=new a(t,this.options));let n=0;do{const r=this.build[n],i=t.build[n];if(e("build compare",n,r,i),void 0===r&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===r)return-1;if(r!==i)return s(r,i)}while(++n)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&!1===n)throw new Error("invalid increment argument: identifier is empty");if(t){const e=`-${t}`.match(this.options.loose?r[i.PRERELEASELOOSE]:r[i.PRERELEASE]);if(!e||e[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(n)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);if(-1===r){if(t===this.prerelease.join(".")&&!1===n)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let r=[t,e];!1===n&&(r=[t]),0===s(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return fq=a}function WJ(){if(Aq)return gq;Aq=1;const e=HJ();return gq=(t,n,r=!1)=>{if(t instanceof e)return t;try{return new e(t,n)}catch(i){if(!r)return null;throw i}}}function qJ(){if(Rq)return Tq;Rq=1;const e=HJ();return Tq=(t,n,r)=>new e(t,r).compare(new e(n,r))}function JJ(){if(Pq)return Lq;Pq=1;const e=HJ();return Lq=(t,n,r)=>{const i=new e(t,r),o=new e(n,r);return i.compare(o)||i.compareBuild(o)}}function KJ(){if(Wq)return Hq;Wq=1;const e=qJ();return Hq=(t,n,r)=>e(t,n,r)>0}function ZJ(){if(Jq)return qq;Jq=1;const e=qJ();return qq=(t,n,r)=>e(t,n,r)<0}function VJ(){if(Zq)return Kq;Zq=1;const e=qJ();return Kq=(t,n,r)=>0===e(t,n,r)}function YJ(){if(Yq)return Vq;Yq=1;const e=qJ();return Vq=(t,n,r)=>0!==e(t,n,r)}function XJ(){if(eJ)return Xq;eJ=1;const e=qJ();return Xq=(t,n,r)=>e(t,n,r)>=0}function eK(){if(nJ)return tJ;nJ=1;const e=qJ();return tJ=(t,n,r)=>e(t,n,r)<=0}function tK(){if(iJ)return rJ;iJ=1;const e=VJ(),t=YJ(),n=KJ(),r=XJ(),i=ZJ(),o=eK();return rJ=(s,a,l,u)=>{switch(a){case"===":return"object"==typeof s&&(s=s.version),"object"==typeof l&&(l=l.version),s===l;case"!==":return"object"==typeof s&&(s=s.version),"object"==typeof l&&(l=l.version),s!==l;case"":case"=":case"==":return e(s,l,u);case"!=":return t(s,l,u);case">":return n(s,l,u);case">=":return r(s,l,u);case"<":return i(s,l,u);case"<=":return o(s,l,u);default:throw new TypeError(`Invalid operator: ${a}`)}}}function nK(){if(cJ)return uJ;cJ=1;const e=/\s+/g;class t{constructor(n,o){if(o=r(o),n instanceof t)return n.loose===!!o.loose&&n.includePrerelease===!!o.includePrerelease?n:new t(n.raw,o);if(n instanceof i)return this.raw=n.value,this.set=[[n]],this.formatted=void 0,this;if(this.options=o,this.loose=!!o.loose,this.includePrerelease=!!o.includePrerelease,this.raw=n.trim().replace(e," "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&g(t[0])){this.set=[t];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&p)|(this.options.loose&&f))+":"+e,r=n.get(t);if(r)return r;const s=this.options.loose,g=s?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];e=e.replace(g,D(this.options.includePrerelease)),o("hyphen replace",e),e=e.replace(a[l.COMPARATORTRIM],u),o("comparator trim",e),e=e.replace(a[l.TILDETRIM],c),o("tilde trim",e),e=e.replace(a[l.CARETTRIM],d),o("caret trim",e);let A=e.split(" ").map(e=>m(e,this.options)).join(" ").split(/\s+/).map(e=>B(e,this.options));s&&(A=A.filter(e=>(o("loose invalid filter",e,this.options),!!e.match(a[l.COMPARATORLOOSE])))),o("range list",A);const y=new Map,b=A.map(e=>new i(e,this.options));for(const n of b){if(h(n))return[n];y.set(n.value,n)}y.size>1&&y.has("")&&y.delete("");const v=[...y.values()];return n.set(t,v),v}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(t=>A(t,n)&&e.set.some(e=>A(e,n)&&t.every(t=>e.every(e=>t.intersects(e,n)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new s(e,this.options)}catch(t){return!1}for(let n=0;n<this.set.length;n++)if(S(this.set[n],e,this.options))return!0;return!1}}uJ=t;const n=new(lJ?aJ:(lJ=1,aJ=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}})),r=zJ(),i=rK(),o=jJ(),s=HJ(),{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:c,caretTrimReplace:d}=UJ(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:f}=PJ(),h=e=>"<0.0.0-0"===e.value,g=e=>""===e.value,A=(e,t)=>{let n=!0;const r=e.slice();let i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},m=(e,t)=>(o("comp",e,t),e=E(e,t),o("caret",e),e=b(e,t),o("tildes",e),e=w(e,t),o("xrange",e),e=_(e,t),o("stars",e),e),y=e=>!e||"x"===e.toLowerCase()||"*"===e,b=(e,t)=>e.trim().split(/\s+/).map(e=>v(e,t)).join(" "),v=(e,t)=>{const n=t.loose?a[l.TILDELOOSE]:a[l.TILDE];return e.replace(n,(t,n,r,i,s)=>{let a;return o("tilde",e,t,n,r,i,s),y(n)?a="":y(r)?a=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?a=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:s?(o("replaceTilde pr",s),a=`>=${n}.${r}.${i}-${s} <${n}.${+r+1}.0-0`):a=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o("tilde return",a),a})},E=(e,t)=>e.trim().split(/\s+/).map(e=>I(e,t)).join(" "),I=(e,t)=>{o("caret",e,t);const n=t.loose?a[l.CARETLOOSE]:a[l.CARET],r=t.includePrerelease?"-0":"";return e.replace(n,(t,n,i,s,a)=>{let l;return o("caret",e,t,n,i,s,a),y(n)?l="":y(i)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(s)?l="0"===n?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:a?(o("replaceCaret pr",a),l="0"===n?"0"===i?`>=${n}.${i}.${s}-${a} <${n}.${i}.${+s+1}-0`:`>=${n}.${i}.${s}-${a} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${s}-${a} <${+n+1}.0.0-0`):(o("no pr"),l="0"===n?"0"===i?`>=${n}.${i}.${s}${r} <${n}.${i}.${+s+1}-0`:`>=${n}.${i}.${s}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${s} <${+n+1}.0.0-0`),o("caret return",l),l})},w=(e,t)=>(o("replaceXRanges",e,t),e.split(/\s+/).map(e=>C(e,t)).join(" ")),C=(e,t)=>{e=e.trim();const n=t.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return e.replace(n,(n,r,i,s,a,l)=>{o("xRange",e,n,r,i,s,a,l);const u=y(i),c=u||y(s),d=c||y(a),p=d;return"="===r&&p&&(r=""),l=t.includePrerelease?"-0":"",u?n=">"===r||"<"===r?"<0.0.0-0":"*":r&&p?(c&&(s=0),a=0,">"===r?(r=">=",c?(i=+i+1,s=0,a=0):(s=+s+1,a=0)):"<="===r&&(r="<",c?i=+i+1:s=+s+1),"<"===r&&(l="-0"),n=`${r+i}.${s}.${a}${l}`):c?n=`>=${i}.0.0${l} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${s}.0${l} <${i}.${+s+1}.0-0`),o("xRange return",n),n})},_=(e,t)=>(o("replaceStars",e,t),e.trim().replace(a[l.STAR],"")),B=(e,t)=>(o("replaceGTE0",e,t),e.trim().replace(a[t.includePrerelease?l.GTE0PRE:l.GTE0],"")),D=e=>(t,n,r,i,o,s,a,l,u,c,d,p)=>`${n=y(r)?"":y(i)?`>=${r}.0.0${e?"-0":""}`:y(o)?`>=${r}.${i}.0${e?"-0":""}`:s?`>=${n}`:`>=${n}${e?"-0":""}`} ${l=y(u)?"":y(c)?`<${+u+1}.0.0-0`:y(d)?`<${u}.${+c+1}.0-0`:p?`<=${u}.${c}.${d}-${p}`:e?`<${u}.${c}.${+d+1}-0`:`<=${l}`}`.trim(),S=(e,t,n)=>{for(let r=0;r<e.length;r++)if(!e[r].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==i.ANY&&e[n].semver.prerelease.length>0){const r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0};return uJ}function rK(){if(pJ)return dJ;pJ=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(r,i){if(i=n(i),r instanceof t){if(r.loose===!!i.loose)return r;r=r.value}r=r.trim().split(/\s+/).join(" "),s("comparator",r,i),this.options=i,this.loose=!!i.loose,this.parse(r),this.semver===e?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(t){const n=this.options.loose?r[i.COMPARATORLOOSE]:r[i.COMPARATOR],o=t.match(n);if(!o)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==o[1]?o[1]:"","="===this.operator&&(this.operator=""),o[2]?this.semver=new a(o[2],this.options.loose):this.semver=e}toString(){return this.value}test(t){if(s("Comparator.test",t,this.options.loose),this.semver===e||t===e)return!0;if("string"==typeof t)try{t=new a(t,this.options)}catch(n){return!1}return o(t,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new l(e.value,r).test(this.value):""===e.operator?""===e.value||new l(this.value,r).test(e.semver):(!(r=n(r)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(o(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(o(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}dJ=t;const n=zJ(),{safeRe:r,t:i}=UJ(),o=tK(),s=jJ(),a=HJ(),l=nK();return dJ}function iK(){if(hJ)return fJ;hJ=1;const e=nK();return fJ=(t,n,r)=>{try{n=new e(n,r)}catch(i){return!1}return n.test(t)}}function oK(){if(BJ)return _J;BJ=1;const e=HJ(),t=rK(),{ANY:n}=t,r=nK(),i=iK(),o=KJ(),s=ZJ(),a=eK(),l=XJ();return _J=(u,c,d,p)=>{let f,h,g,A,m;switch(u=new e(u,p),c=new r(c,p),d){case">":f=o,h=a,g=s,A=">",m=">=";break;case"<":f=s,h=l,g=o,A="<",m="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(i(u,c,p))return!1;for(let e=0;e<c.set.length;++e){const r=c.set[e];let i=null,o=null;if(r.forEach(e=>{e.semver===n&&(e=new t(">=0.0.0")),i=i||e,o=o||e,f(e.semver,i.semver,p)?i=e:g(e.semver,o.semver,p)&&(o=e)}),i.operator===A||i.operator===m)return!1;if((!o.operator||o.operator===A)&&h(u,o.semver))return!1;if(o.operator===m&&g(u,o.semver))return!1}return!0}}const sK=e(function(){if($J)return OJ;$J=1;const e=UJ(),t=PJ(),n=HJ(),r=GJ(),i=WJ(),o=function(){if(yq)return mq;yq=1;const e=WJ();return mq=(t,n)=>{const r=e(t,n);return r?r.version:null}}(),s=function(){if(vq)return bq;vq=1;const e=WJ();return bq=(t,n)=>{const r=e(t.trim().replace(/^[=v]+/,""),n);return r?r.version:null}}(),a=function(){if(Iq)return Eq;Iq=1;const e=HJ();return Eq=(t,n,r,i,o)=>{"string"==typeof r&&(o=i,i=r,r=void 0);try{return new e(t instanceof e?t.version:t,r).inc(n,i,o).version}catch(s){return null}}}(),l=function(){if(Cq)return wq;Cq=1;const e=WJ();return wq=(t,n)=>{const r=e(t,null,!0),i=e(n,null,!0),o=r.compare(i);if(0===o)return null;const s=o>0,a=s?r:i,l=s?i:r,u=!!a.prerelease.length;if(l.prerelease.length&&!u){if(!l.patch&&!l.minor)return"major";if(0===l.compareMain(a))return l.minor&&!l.patch?"minor":"patch"}const c=u?"pre":"";return r.major!==i.major?c+"major":r.minor!==i.minor?c+"minor":r.patch!==i.patch?c+"patch":"prerelease"}}(),u=function(){if(Bq)return _q;Bq=1;const e=HJ();return _q=(t,n)=>new e(t,n).major}(),c=function(){if(Sq)return Dq;Sq=1;const e=HJ();return Dq=(t,n)=>new e(t,n).minor}(),d=function(){if(xq)return kq;xq=1;const e=HJ();return kq=(t,n)=>new e(t,n).patch}(),p=function(){if(Nq)return Qq;Nq=1;const e=WJ();return Qq=(t,n)=>{const r=e(t,n);return r&&r.prerelease.length?r.prerelease:null}}(),f=qJ(),h=function(){if(Mq)return Fq;Mq=1;const e=qJ();return Fq=(t,n,r)=>e(n,t,r)}(),g=function(){if($q)return Oq;$q=1;const e=qJ();return Oq=(t,n)=>e(t,n,!0)}(),A=JJ(),m=function(){if(Uq)return jq;Uq=1;const e=JJ();return jq=(t,n)=>t.sort((t,r)=>e(t,r,n))}(),y=function(){if(Gq)return zq;Gq=1;const e=JJ();return zq=(t,n)=>t.sort((t,r)=>e(r,t,n))}(),b=KJ(),v=ZJ(),E=VJ(),I=YJ(),w=XJ(),C=eK(),_=tK(),B=function(){if(sJ)return oJ;sJ=1;const e=HJ(),t=WJ(),{safeRe:n,t:r}=UJ();return oJ=(i,o)=>{if(i instanceof e)return i;if("number"==typeof i&&(i=String(i)),"string"!=typeof i)return null;let s=null;if((o=o||{}).rtl){const e=o.includePrerelease?n[r.COERCERTLFULL]:n[r.COERCERTL];let t;for(;(t=e.exec(i))&&(!s||s.index+s[0].length!==i.length);)s&&t.index+t[0].length===s.index+s[0].length||(s=t),e.lastIndex=t.index+t[1].length+t[2].length;e.lastIndex=-1}else s=i.match(o.includePrerelease?n[r.COERCEFULL]:n[r.COERCE]);if(null===s)return null;const a=s[2],l=s[3]||"0",u=s[4]||"0",c=o.includePrerelease&&s[5]?`-${s[5]}`:"",d=o.includePrerelease&&s[6]?`+${s[6]}`:"";return t(`${a}.${l}.${u}${c}${d}`,o)}}(),D=rK(),S=nK(),k=iK(),x=function(){if(AJ)return gJ;AJ=1;const e=nK();return gJ=(t,n)=>new e(t,n).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" "))}(),Q=function(){if(yJ)return mJ;yJ=1;const e=HJ(),t=nK();return mJ=(n,r,i)=>{let o=null,s=null,a=null;try{a=new t(r,i)}catch(l){return null}return n.forEach(t=>{a.test(t)&&(o&&-1!==s.compare(t)||(o=t,s=new e(o,i)))}),o}}(),N=function(){if(vJ)return bJ;vJ=1;const e=HJ(),t=nK();return bJ=(n,r,i)=>{let o=null,s=null,a=null;try{a=new t(r,i)}catch(l){return null}return n.forEach(t=>{a.test(t)&&(o&&1!==s.compare(t)||(o=t,s=new e(o,i)))}),o}}(),T=function(){if(IJ)return EJ;IJ=1;const e=HJ(),t=nK(),n=KJ();return EJ=(r,i)=>{r=new t(r,i);let o=new e("0.0.0");if(r.test(o))return o;if(o=new e("0.0.0-0"),r.test(o))return o;o=null;for(let t=0;t<r.set.length;++t){const i=r.set[t];let s=null;i.forEach(t=>{const r=new e(t.semver.version);switch(t.operator){case">":0===r.prerelease.length?r.patch++:r.prerelease.push(0),r.raw=r.format();case"":case">=":s&&!n(r,s)||(s=r);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}}),!s||o&&!n(o,s)||(o=s)}return o&&r.test(o)?o:null}}(),R=function(){if(CJ)return wJ;CJ=1;const e=nK();return wJ=(t,n)=>{try{return new e(t,n).range||"*"}catch(r){return null}}}(),F=oK(),M=function(){if(SJ)return DJ;SJ=1;const e=oK();return DJ=(t,n,r)=>e(t,n,">",r)}(),O=function(){if(xJ)return kJ;xJ=1;const e=oK();return kJ=(t,n,r)=>e(t,n,"<",r)}(),$=function(){if(NJ)return QJ;NJ=1;const e=nK();return QJ=(t,n,r)=>(t=new e(t,r),n=new e(n,r),t.intersects(n,r))}(),L=function(){if(RJ)return TJ;RJ=1;const e=iK(),t=qJ();return TJ=(n,r,i)=>{const o=[];let s=null,a=null;const l=n.sort((e,n)=>t(e,n,i));for(const t of l)e(t,r,i)?(a=t,s||(s=t)):(a&&o.push([s,a]),a=null,s=null);s&&o.push([s,null]);const u=[];for(const[e,t]of o)e===t?u.push(e):t||e!==l[0]?t?e===l[0]?u.push(`<=${t}`):u.push(`${e} - ${t}`):u.push(`>=${e}`):u.push("*");const c=u.join(" || "),d="string"==typeof r.raw?r.raw:String(r);return c.length<d.length?c:r}}(),P=function(){if(MJ)return FJ;MJ=1;const e=nK(),t=rK(),{ANY:n}=t,r=iK(),i=qJ(),o=[new t(">=0.0.0-0")],s=[new t(">=0.0.0")],a=(e,t,a)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===n){if(1===t.length&&t[0].semver===n)return!0;e=a.includePrerelease?o:s}if(1===t.length&&t[0].semver===n){if(a.includePrerelease)return!0;t=s}const c=new Set;let d,p,f,h,g,A,m;for(const n of e)">"===n.operator||">="===n.operator?d=l(d,n,a):"<"===n.operator||"<="===n.operator?p=u(p,n,a):c.add(n.semver);if(c.size>1)return null;if(d&&p){if(f=i(d.semver,p.semver,a),f>0)return null;if(0===f&&(">="!==d.operator||"<="!==p.operator))return null}for(const n of c){if(d&&!r(n,String(d),a))return null;if(p&&!r(n,String(p),a))return null;for(const e of t)if(!r(n,String(e),a))return!1;return!0}let y=!(!p||a.includePrerelease||!p.semver.prerelease.length)&&p.semver,b=!(!d||a.includePrerelease||!d.semver.prerelease.length)&&d.semver;y&&1===y.prerelease.length&&"<"===p.operator&&0===y.prerelease[0]&&(y=!1);for(const n of t){if(m=m||">"===n.operator||">="===n.operator,A=A||"<"===n.operator||"<="===n.operator,d)if(b&&n.semver.prerelease&&n.semver.prerelease.length&&n.semver.major===b.major&&n.semver.minor===b.minor&&n.semver.patch===b.patch&&(b=!1),">"===n.operator||">="===n.operator){if(h=l(d,n,a),h===n&&h!==d)return!1}else if(">="===d.operator&&!r(d.semver,String(n),a))return!1;if(p)if(y&&n.semver.prerelease&&n.semver.prerelease.length&&n.semver.major===y.major&&n.semver.minor===y.minor&&n.semver.patch===y.patch&&(y=!1),"<"===n.operator||"<="===n.operator){if(g=u(p,n,a),g===n&&g!==p)return!1}else if("<="===p.operator&&!r(p.semver,String(n),a))return!1;if(!n.operator&&(p||d)&&0!==f)return!1}return!(d&&A&&!p&&0!==f||p&&m&&!d&&0!==f||b||y)},l=(e,t,n)=>{if(!e)return t;const r=i(e.semver,t.semver,n);return r>0?e:r<0||">"===t.operator&&">="===e.operator?t:e},u=(e,t,n)=>{if(!e)return t;const r=i(e.semver,t.semver,n);return r<0?e:r>0||"<"===t.operator&&"<="===e.operator?t:e};return FJ=(t,n,r={})=>{if(t===n)return!0;t=new e(t,r),n=new e(n,r);let i=!1;e:for(const e of t.set){for(const t of n.set){const n=a(e,t,r);if(i=i||null!==n,n)continue e}if(i)return!1}return!0}}();return OJ={parse:i,valid:o,clean:s,inc:a,diff:l,major:u,minor:c,patch:d,prerelease:p,compare:f,rcompare:h,compareLoose:g,compareBuild:A,sort:m,rsort:y,gt:b,lt:v,eq:E,neq:I,gte:w,lte:C,cmp:_,coerce:B,Comparator:D,Range:S,satisfies:k,toComparators:x,maxSatisfying:Q,minSatisfying:N,minVersion:T,validRange:R,outside:F,gtr:M,ltr:O,intersects:$,simplifyRange:L,subset:P,SemVer:n,re:e.re,src:e.src,tokens:e.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers}}()),aK="2.0.37";async function lK(){const e=await(t="@embedder/embedder",fetch(`https://registry.npmjs.org/${t}`).then(e=>e.ok?e.json():null).catch(()=>null));var t;if(!e)return null;const n=Object.keys(e.versions),r=sK.maxSatisfying(n,"*");if(!r||sK.gte(aK,r))return null;const i=Object.values(e.versions).find(e=>sK.eq(e.version,r));return i?{command:`npm i -g ${i._id}`,currentVersion:aK,version:i.version}:null}const uK=P(ke);let cK=null;async function dK(e){const t=Date.now();if(cK&&t-cK.timestamp<3e4)return cK.branch;const n=await async function(e){try{const t=e||process.cwd();try{await uK("git rev-parse --git-dir",{cwd:t})}catch{return{branch:"not-git",isRepository:!1,error:"Not a git repository"}}const{stdout:n}=await uK("git branch --show-current",{cwd:t}),r=n.trim();if(!r)try{const{stdout:e}=await uK("git rev-parse --short HEAD",{cwd:t});return{branch:`detached-${e.trim()}`,isRepository:!0}}catch{return{branch:"unknown",isRepository:!0,error:"Unable to determine branch"}}return{branch:r,isRepository:!0}}catch(qK){return{branch:"error",isRepository:!1,error:qK instanceof Error?qK.message:"Unknown git error"}}}(e);return cK={branch:n.branch,timestamp:t},n.branch}function pK({conversation:e,index:t,isSelected:n,formatRelativeTime:r}){const[i,o]=qe.useState("loading..."),{columns:s}=oL();qe.useEffect(()=>{dK().then(e=>o(e)).catch(()=>o("unknown"))},[]);const a=n?"blue":"gray",l=n?"white":"gray",u=n?"cyan":"gray",c=n?"green":"gray",d=(e,t)=>e.length<=t?e:e.substring(0,t-3)+"...",p=Math.max(20,s-55-10),f=(e=>{try{const t=new Date(e),n=String(t.getMonth()+1).padStart(2,"0");return`${n}/${String(t.getDate()).padStart(2,"0")}`}catch{return r(e)}})(e.lastModified),h=r(e.lastModified);return We.jsxs(ki,{flexDirection:"row",width:"100%",children:[We.jsx(ki,{width:6,children:We.jsxs(xi,{color:a,children:[n?"❯ ":" ",t,"."]})}),We.jsx(ki,{width:13,children:We.jsx(xi,{color:l,children:d(h,12)})}),We.jsx(ki,{width:13,children:We.jsx(xi,{color:l,children:d(f,12)})}),We.jsx(ki,{width:8,children:We.jsx(xi,{color:u,children:e.messageCount})}),We.jsx(ki,{width:15,children:We.jsx(xi,{color:c,children:d(i,14)})}),We.jsx(ki,{flexGrow:1,width:p,children:We.jsx(xi,{color:l,wrap:"truncate-end",children:d(e.preview||"No preview available",p)})})]})}function fK({isOpen:e,onClose:t,onSelect:n}){const{listConversations:r}=BM(),[i,o]=qe.useState([]),[s,a]=qe.useState(0),[l,u]=qe.useState(!0),[c,d]=qe.useState(null),{rows:p}=oL();qe.useEffect(()=>{if(!e)return;(async()=>{u(!0),d(null);try{const e=await r();o(e),a(0)}catch(e){d(e instanceof Error?e.message:"Failed to load conversations")}finally{u(!1)}})()},[e,r]),Gi((r,o)=>{if(e)if(o.upArrow||"k"===r)a(e=>Math.max(0,e-1));else if(o.downArrow||"j"===r)a(e=>Math.min(i.length-1,e+1));else{if(o.return&&i.length>0){const e=i[s];return void(e&&n(e.name).then(()=>{t()}).catch(e=>{d(e instanceof Error?e.message:"Failed to load conversation")}))}(o.escape||"q"===r)&&t()}},{isActive:e});const f=qe.useCallback(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/864e5);if(0===r){const e=Math.floor(n/36e5);if(0===e){const e=Math.floor(n/6e4);return e<=1?"just now":`${e}m ago`}return`${e}h ago`}return 1===r?"1 day ago":r<7?`${r} days ago`:t.toLocaleDateString()},[]),{visibleConversations:h,visibleStartIndex:g,visibleEndIndex:A}=qe.useMemo(()=>{const e=Math.min(50,Math.max(5,Math.floor((p-15)/1)));let t=Math.max(0,s-Math.floor(e/2)),n=Math.min(i.length,t+e);n-t<e&&i.length>=e&&(t=Math.max(0,n-e));return{visibleConversations:i.slice(t,n),visibleStartIndex:t,visibleEndIndex:n}},[i,s,p]);return e?We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{flexDirection:"column",borderStyle:"round",borderColor:"blue",padding:1,width:"98%",height:"98%",children:[We.jsxs(ki,{marginBottom:1,children:[We.jsx(xi,{bold:!0,color:"blue",children:"> /resume"}),We.jsx(ki,{marginLeft:2,children:We.jsx(xi,{color:"gray",children:"(↑↓ to navigate, Enter to select, Esc to close)"})})]}),!l&&!c&&i.length>0&&We.jsxs(ki,{marginBottom:1,flexDirection:"row",width:"100%",children:[We.jsx(ki,{width:6,children:We.jsx(xi,{color:"gray"})}),We.jsx(ki,{width:13,children:We.jsx(xi,{color:"gray",children:"Modified"})}),We.jsx(ki,{width:13,children:We.jsx(xi,{color:"gray",children:"Created"})}),We.jsx(ki,{width:8,children:We.jsx(xi,{color:"gray",children:"Msgs"})}),We.jsx(ki,{width:15,children:We.jsx(xi,{color:"gray",children:"Git Branch"})}),We.jsx(ki,{flexGrow:1,children:We.jsx(xi,{color:"gray",children:"Summary"})})]}),We.jsxs(ki,{flexDirection:"column",flexGrow:1,children:[l&&We.jsx(ki,{justifyContent:"center",alignItems:"center",minHeight:3,children:We.jsx(xi,{color:"yellow",children:"Loading conversations..."})}),c&&We.jsx(ki,{justifyContent:"center",alignItems:"center",minHeight:3,children:We.jsxs(xi,{color:"red",children:["Error: ",c]})}),!l&&!c&&0===i.length&&We.jsx(ki,{justifyContent:"center",alignItems:"center",minHeight:3,children:We.jsx(xi,{color:"gray",children:"No saved conversations found."})}),!l&&!c&&i.length>0&&We.jsxs(ki,{flexDirection:"column",children:[g>0&&We.jsx(ki,{children:We.jsxs(xi,{color:"gray",children:["↑ ",g," more above..."]})}),h.map((e,t)=>{const n=g+t,r=n===s;return We.jsx(pK,{conversation:e,index:n+1,isSelected:r,formatRelativeTime:f},e.id)}),A<i.length&&We.jsx(ki,{children:We.jsxs(xi,{color:"gray",children:["↓ ",i.length-A," more below..."]})})]})]}),!l&&!c&&i.length>0&&We.jsx(ki,{marginTop:1,borderTop:!0,borderColor:"gray",paddingTop:1,children:We.jsxs(xi,{color:"gray",children:["Showing ",g+1,"-",A," of ",i.length," ","conversation",1!==i.length?"s":""," • Selected: ",s+1]})})]})}):null}function hK({models:e,selectedModel:t,selectedIndex:n,width:r}){return e&&0!==e.length?We.jsxs(ki,{flexDirection:"column",width:r,borderStyle:"single",paddingX:1,children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Select model"})}),We.jsx(xi,{color:"dim",dimColor:!0,children:"Switch between AI models. Applies to this session and future embedder sessions."}),We.jsx(ki,{marginTop:1,marginBottom:1,flexDirection:"column",children:e.map((e,r)=>{const i=r===n,o=t&&e.provider===t.provider&&e.name===t.name,s=i?FM:QM;return We.jsx(ki,{flexDirection:"row",children:We.jsxs(xi,{color:s,children:[i?"❯":" "," ",r+1,". ",e.name," ",o?"✔":""]})},`${e.provider}-${e.name}`)})}),We.jsx(xi,{color:"dim",children:"Enter to confirm · Esc to exit"})]}):null}const gK=[{name:"resume",description:"Resume a conversation",shortcut:"Ctrl+O"},{name:"clear",description:"Clear conversation history",shortcut:"Ctrl+R"},{name:"compress",description:"Compress conversation history to save context"},{name:"model",description:"Select which AI model to use",shortcut:"Ctrl+B"},{name:"rewind",description:"View and revert to previous conversation states"},{name:"undo",description:"Undo the last query"},{name:"yolo",description:"Toggle auto-approval of all tool calls"},{name:"project",description:"Switch to a different project in the current team"},{name:"init",description:"Create EMBEDDER.md with project contexts"},{name:"doc",description:"Upload hardware docs and datasheets to improve AI accuracy"},{name:"help",description:"Show available commands and shortcuts"},{name:"exit",description:"Close the application"}];function AK({version:e,currentTab:t,width:n}){const r="https://docs.embedder.dev";return We.jsxs(ki,{flexDirection:"column",width:n,paddingX:1,children:[We.jsxs(ki,{marginBottom:1,flexDirection:"row",gap:1,children:[We.jsxs(xi,{children:["Embedder v",e]}),We.jsx(xi,{children:" "}),We.jsx(xi,{backgroundColor:"general"===t?"cyan":void 0,color:"general"===t?"black":"gray",children:" general "}),We.jsx(xi,{children:" "}),We.jsx(xi,{backgroundColor:"commands"===t?"cyan":void 0,color:"commands"===t?"black":"gray",children:" commands "}),We.jsx(xi,{children:" "}),We.jsx(xi,{color:"gray",children:"(tab to cycle)"})]}),"general"===t&&We.jsxs(ki,{flexDirection:"column",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:"Embedder is a coding agent designed for firmware development. It understands your codebase, documentation and interacts with your hardware. Upload your documentation on the web console and create EMBEDDER.md using /init for the best results."})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Shortcuts"})}),We.jsxs(ki,{flexDirection:"column",marginBottom:1,children:[We.jsxs(ki,{children:[We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"/"})," for commands"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + d"})," for docs"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + b"})," to select model"]})})]}),We.jsxs(ki,{children:[We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"@"})," for file paths"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + r"})," to clear chat"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + o"})," to resume"]})})]}),We.jsxs(ki,{children:[We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"tab"})," to switch mode"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + c"})," (2x) to exit"]})})]})]}),We.jsx(ki,{marginBottom:1,marginTop:1,children:We.jsxs(xi,{children:["For more help: ",We.jsx(xi,{color:"blue",children:r})]})}),We.jsx(ki,{children:We.jsx(xi,{color:"gray",children:"Esc to exit"})})]}),"commands"===t&&We.jsxs(ki,{flexDirection:"column",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:"Browse available commands:"})}),We.jsx(ki,{flexDirection:"column",marginBottom:1,children:gK.map((e,t)=>We.jsx(ki,{children:We.jsxs(xi,{children:[" ",We.jsxs(xi,{bold:!0,color:"cyan",children:["/",e.name]})," ".repeat(Math.max(1,20-e.name.length)),We.jsx(xi,{children:e.description}),e.shortcut&&We.jsxs(xi,{color:"gray",children:[" - ",e.shortcut]})]})},e.name))}),We.jsx(ki,{marginBottom:1,marginTop:1,children:We.jsxs(xi,{children:["For more help: ",We.jsx(xi,{color:"blue",children:r})]})}),We.jsx(ki,{children:We.jsx(xi,{color:"gray",children:"Esc to exit"})})]})]})}const mK=b(Q);class yK{gitDir;workTree;initialized=!1;trackedFiles=new Set;constructor(e=process.cwd()){this.workTree=e;const t=this.getProjectHash(e);this.gitDir=C(g(),".embedder","snapshots",t)}getProjectHash(e){return ve("sha256").update(e).digest("hex").substring(0,16)}registerFile(e){this.trackedFiles.add(e)}isFileTracked(e){return this.trackedFiles.has(e)}getTrackedFiles(){return Array.from(this.trackedFiles)}setTrackedFiles(e){this.trackedFiles=new Set(e)}clearTrackedFiles(){this.trackedFiles.clear()}async initialize(){if(!this.initialized)try{await c.mkdir(this.gitDir,{recursive:!0});try{return await mK(`git --git-dir="${this.gitDir}" rev-parse --git-dir`),void(this.initialized=!0)}catch{}await mK("git init",{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}}),this.initialized=!0}catch(qK){throw this.initialized=!1,qK}}async track(){if(this.initialized||await this.initialize(),0===this.trackedFiles.size)return null;try{for(const n of this.trackedFiles)try{const e=_(this.workTree,n);await c.access(n).catch(()=>{}),await mK(`git add "${e}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}})}catch(e){}const{stdout:t}=await mK("git write-tree",{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}});return t.trim()}catch(qK){return null}}async patch(e){this.initialized||await this.initialize();try{for(const e of this.trackedFiles)try{const t=_(this.workTree,e);await c.access(e).catch(()=>{}),await mK(`git add "${t}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}})}catch(t){}const n=[];for(const t of this.trackedFiles)try{const r=_(this.workTree,t),{stdout:i}=await mK(`git diff --name-only ${e} -- "${r}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}});i.trim()&&n.push(t)}catch(qK){}return{hash:e,files:n}}catch(qK){return{hash:e,files:[]}}}async revert(e){this.initialized||await this.initialize();const t=new Set;try{for(const n of e)for(const e of n.files)if(!t.has(e))try{const r=_(this.workTree,e);await mK(`git checkout ${n.hash} -- "${r}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}}),t.add(e)}catch(qK){const i=_(this.workTree,e);try{const t=await mK(`git ls-tree ${n.hash} -- "${i}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}});t.stdout&&t.stdout.trim()||await c.unlink(e).catch(()=>{})}catch{await c.unlink(e).catch(()=>{})}t.add(e)}}catch(qK){throw qK}}async diff(e,t){this.initialized||await this.initialize();try{const n=t||"HEAD",{stdout:r}=await mK(`git diff --stat ${e} ${n}`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}}),i=r.trim().split("\n"),o=i[i.length-1];if(!o)return{added:0,deleted:0};const s=o.match(/(\d+)\s+insertions?\(\+\)/),a=o.match(/(\d+)\s+deletions?\(-\)/);return{added:s&&s[1]?parseInt(s[1],10):0,deleted:a&&a[1]?parseInt(a[1],10):0}}catch(qK){return{added:0,deleted:0}}}async cleanup(){try{await c.rm(this.gitDir,{recursive:!0,force:!0}),this.initialized=!1}catch(qK){}}}const bK=({entry:e,isSelected:t,isCurrent:n})=>{const r=(()=>{if(n)return"";if(0===e.filesChanged)return"No code changes";const t=[];e.filesChanged>0&&t.push(`${e.filesChanged} file${e.filesChanged>1?"s":""} edited`);const r=[];return e.linesAdded&&e.linesAdded>0&&r.push(`+${e.linesAdded}`),e.linesDeleted&&e.linesDeleted>0&&r.push(`-${e.linesDeleted}`),r.length>0&&t.push(r.join(" ")),t.join(" ")})();return We.jsxs(ki,{flexDirection:"column",marginBottom:n?1:0,children:[We.jsx(ki,{children:We.jsxs(xi,{color:t?"cyan":void 0,bold:t,children:[t?"❯ ":" ",e.userPrompt]})}),r&&We.jsx(ki,{marginLeft:2,children:We.jsx(xi,{dimColor:!0,color:e.filesChanged>0?"green":"gray",children:r})})]})},vK=({messages:e,onRevert:t,onClose:n,snapshotService:r})=>{const[i,o]=qe.useState([]),[s,a]=qe.useState(0),[l,u]=qe.useState(!1);qe.useEffect(()=>{(async()=>{const t=[];let n=0;for(const i of e)if("role"in i&&"user"===i.role){const e=i;if(e.hidden)continue;let o="";"string"==typeof e.content?o=e.content:Array.isArray(e.content)&&(o=e.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("\n"));const s=o.length>80?o.substring(0,77)+"...":o,a=e.patch;let l,u,c=0;if(a){const e=Array.isArray(a)?a:[a],t=new Set;for(const n of e)n.files.forEach(e=>t.add(e));c=t.size;const i=e[0],o=e[e.length-1];if(r&&i?.hash&&o?.afterHash)try{const e=await r.diff(i.hash,o.afterHash);l=e.added,u=e.deleted}catch(qK){ex.error(`Failed to calculate diff for entry ${n}:`,qK)}}t.push({messageId:`msg-${n}`,userPrompt:s,fullContent:o,timestamp:e.timestamp||Date.now(),filesChanged:c,linesAdded:l,linesDeleted:u,patch:a}),n++}t.reverse(),o(t),a(0)})()},[e,r]);const c=qe.useCallback(async()=>{if(!(l||s>i.length))if(0!==s){u(!0);try{const e=i[s-1];if(!e)return void u(!1);const n="msg-"+(parseInt(e.messageId.replace("msg-",""))-1);await t(n,e.fullContent)}catch(qK){u(!1)}}else n()},[s,i,t,n,l]);return Gi((e,t)=>{l||(t.upArrow?a(e=>Math.max(0,e-1)):t.downArrow?a(e=>Math.min(i.length,e+1)):t.return?c():t.escape&&n())},{isActive:!l}),0===i.length?We.jsxs(ki,{flexDirection:"column",padding:1,borderStyle:"round",borderColor:"yellow",width:"100%",children:[We.jsx(xi,{bold:!0,color:"yellow",children:"Rewind History"}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{dimColor:!0,children:"No code changes to rewind"})}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{dimColor:!0,children:"Press Escape to close"})})]}):We.jsxs(ki,{flexDirection:"column",padding:1,borderStyle:"round",borderColor:"cyan",width:"100%",children:[We.jsx(xi,{bold:!0,color:"cyan",children:l?"Reverting...":"Rewind History"}),We.jsxs(ki,{marginTop:1,flexDirection:"column",children:[We.jsx(bK,{entry:{messageId:"current",userPrompt:"(current)",fullContent:"",timestamp:Date.now(),filesChanged:0},isSelected:0===s,isCurrent:!0}),i.map((e,t)=>We.jsx(bK,{entry:e,isSelected:s===t+1,isCurrent:!1},e.messageId))]}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{dimColor:!0,children:l?"Reverting changes...":"↑↓ Navigate · Enter to select · Esc to cancel"})})]})};function EK({size:e="normal"}){const[t,n]=qe.useState(()=>DL());return qe.useEffect(()=>{let e=!0;return(async()=>{const t=e=>new Promise(t=>setTimeout(t,e)),r=3e3+2e3*Math.random();await t(r),e&&(n(SL()),await t(150),n(DL()),await t(100),n(SL()),await t(150),n(DL()))})(),()=>{e=!1}},[t]),We.jsxs(ki,{flexDirection:"row",justifyContent:"center",children:[We.jsx(xi,{color:"cyan",bold:!0,children:"{ "}),We.jsx(xi,{color:"yellow",bold:!0,children:t.face}),We.jsx(xi,{color:"cyan",bold:!0,children:" }"})]})}function IK({questions:e,onSubmit:t,onCancel:n,isFocused:r=!0}){const[i,o]=qe.useState(0),[s,a]=qe.useState(()=>{const t={};return e.forEach((e,n)=>{t[n]={selectedOptions:[],isCustomMode:!1,customInput:"",highlightedIndex:0}}),t}),l=e[i],u=s[i];if(!l||!u)return null;const c=e.length;Gi((e,t)=>{if(t.escape)n();else if(!e||t.ctrl||t.meta||t.return||t.escape||t.upArrow||t.downArrow||t.leftArrow||t.rightArrow){if(u.isCustomMode)return t.upArrow?void a(e=>({...e,[i]:{...e[i],isCustomMode:!1,customInput:"",highlightedIndex:l.options.length}})):t.rightArrow?void((u.customInput.trim()||l.multiSelect&&u.selectedOptions.length>0)&&f()):t.backspace||t.delete?void(0===u.customInput.length?a(e=>({...e,[i]:{...e[i],isCustomMode:!1,customInput:""}})):a(e=>{const t=e[i];return{...e,[i]:{...t,customInput:t.customInput.slice(0,-1)}}})):void 0;if(t.upArrow&&!u.isCustomMode){const e=0===u.highlightedIndex?l.options.length:u.highlightedIndex-1;return void a(t=>({...t,[i]:{...t[i],highlightedIndex:e}}))}if(t.downArrow&&!u.isCustomMode){const e=u.highlightedIndex===l.options.length?0:u.highlightedIndex+1;return void a(t=>({...t,[i]:{...t[i],highlightedIndex:e}}))}if(!t.leftArrow||u.isCustomMode){if(t.rightArrow)(u.selectedOptions.length>0||u.isCustomMode)&&f();else if(t.return){const e=u.highlightedIndex;return void(e<l.options.length&&d(e))}}else i>0&&o(e=>e-1)}else a(t=>{const n=t[i];return n.isCustomMode?{...t,[i]:{...n,customInput:n.customInput+e}}:n.highlightedIndex===l.options.length?{...t,[i]:{...n,isCustomMode:!0,customInput:e,selectedOptions:[]}}:t})},{isActive:r});const d=qe.useCallback(e=>{a(t=>{const n=t[i];if(l.multiSelect){const r=n.selectedOptions.includes(e);return{...t,[i]:{...n,highlightedIndex:e,selectedOptions:r?n.selectedOptions.filter(t=>t!==e):[...n.selectedOptions,e]}}}return{...t,[i]:{...n,highlightedIndex:e,selectedOptions:[e]}}})},[i,l.multiSelect]),p=qe.useCallback(()=>{a(n=>{const r={};return e.forEach((e,t)=>{const i=n[t];if(i)if(i.isCustomMode&&i.customInput.trim())r[e.header]={questionHeader:e.header,answers:[i.customInput],isCustom:!0};else if(!i.isCustomMode&&i.selectedOptions.length>0){const t=i.selectedOptions.map(t=>e.options[t]?.label).filter(e=>!!e);r[e.header]={questionHeader:e.header,answers:t,isCustom:!1}}}),t(r),n})},[e,t]),f=qe.useCallback(()=>{i<c-1?o(e=>e+1):p()},[i,c,p]);return We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"90%",paddingX:2,paddingY:1,children:[We.jsx(ki,{marginBottom:1,justifyContent:"center",children:We.jsx(EK,{})}),We.jsxs(ki,{marginBottom:1,justifyContent:"space-between",children:[We.jsx(ki,{children:e.map((t,n)=>We.jsxs(xi,{color:n===i?"cyan":"gray",children:[n===i?"●":"○",n<e.length-1?" ":""]},n))}),We.jsx(xi,{dimColor:!0,children:c>1&&"← → to navigate"})]}),We.jsxs(ki,{marginBottom:1,children:[We.jsxs(xi,{bold:!0,color:"cyan",children:["Question ",i+1," of ",c]}),We.jsxs(xi,{dimColor:!0,children:[" [",l.header,"]"]})]}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:l.question})}),We.jsxs(ki,{flexDirection:"column",children:[l.options.map((e,t)=>{const n=u.selectedOptions.includes(t),r=u.highlightedIndex===t,i=l.multiSelect?n?"[✓]":"[ ]":n?"(•)":"( )";return We.jsx(ki,{marginBottom:1,children:We.jsxs(xi,{color:n?"green":r?"cyan":void 0,bold:r,inverse:r&&!n,children:[i," ",e.label]})},t)}),We.jsx(ki,{marginBottom:1,children:u.isCustomMode?We.jsxs(We.Fragment,{children:[We.jsxs(xi,{color:"green",bold:!0,children:[l.multiSelect?"[✓]":"(•)"," "]}),We.jsx(xi,{color:"green",children:"Other: "}),We.jsx(xi,{color:"green",children:u.customInput}),We.jsx(xi,{inverse:!0,children:" "})]}):We.jsxs(xi,{color:u.highlightedIndex===l.options.length?"cyan":void 0,bold:u.highlightedIndex===l.options.length,inverse:u.highlightedIndex===l.options.length,children:[l.multiSelect?"[ ]":"( )"," Other (type to enter)"]})})]}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{dimColor:!0,children:u.isCustomMode?"→ to continue • Esc to cancel":"↑↓ navigate • Enter to select • → to continue • Esc to cancel"})})]})})}function wK({queueLength:e}){return 0===e?null:We.jsx(ki,{justifyContent:"flex-end",flexShrink:0,children:We.jsxs(xi,{color:"gray",children:[e," ",1===e?"message":"messages"," queued"]})})}const CK=["Implement FreeRTOS task for sensor polling","Debug STM32 I2C initialization sequence","Write unit tests for UART ring buffer driver","Optimize RTOS context switch performance","Refactor I2C transaction state machine","Document DMA configuration registers","Implement non-blocking SPI driver","Fix HardFault in exception handler","Add comments for ISR routines","Implement watchdog refresh logic","Develop STM32 bootloader with firmware update","Integrate lwIP sockets with RTOS tasks","Simulate task scheduling conflicts","Generate FIR filter coefficients with CMSIS-DSP","Debug FreeRTOS queue deadlocks","Configure MPU regions for memory safety","Add double-buffered DMA for audio streaming","Build RTOS-safe logging system","Audit semaphore usage across tasks","Document event group communication patterns"],_K=CK[Math.floor(Math.random()*CK.length)],BK=qe.forwardRef(({exitConfirmation:e="none"},t)=>{const{messages:n,setMessages:r,streamingState:i,isResponding:o,setIsResponding:s,setThought:a,saveConversation:l,loadConversation:u,clearActiveConversation:c,setIsBillingModalOpen:d,project:p,setProject:f,setPreviousProject:h,team:g,setTeam:A,teams:m,setPreviousTeam:y,activeQuestionPrompt:b,setActiveQuestionPrompt:v,pendingQuestionResponse:E,setPendingQuestionResponse:I,queuedMessages:w,setQueuedMessages:C}=BM(),{languageModel:_,availableModels:B,selectedModel:D,setSelectedModel:S}=VF(),{context:k}=EF(),{columns:x}=oL(),{currentMode:Q,setMode:N}=JF(),{closeSession:T,refreshBillingStatus:R,backendUser:F,sessionId:M}=FT(),{exit:O}=Hi(),[L,P]=qe.useState(!0),j=qe.useRef(null),U=qe.useRef(null),z=qe.useRef(null),G=qe.useRef(null),H=qe.useRef(n),W=qe.useRef(!1),q=qe.useRef(!1),J=qe.useRef(null),K=qe.useRef(w);H.current=n,K.current=w;const Z=qe.useRef(""),V=qe.useRef(null),Y=qe.useRef(null),{isFocused:X}=qi({autoFocus:!0,id:"chat"}),{focus:ee}=Ji(),[te,ne]=qe.useState(),[re,ie]=qe.useState(null),[oe,ae]=qe.useState(null),[le,ue]=qe.useState([]),[ce,de]=qe.useState(null),[pe,fe]=qe.useState(!1),[he,ge]=qe.useState(0),[Ae,me]=qe.useState(!1),[ye,be]=qe.useState("general"),{actions:ve}=CL(),Ee=qe.useRef(null),Ie=qe.useRef(null),[we,Ce]=qe.useState(!1),[_e,Be]=qe.useState(!1),[De,Se]=qe.useState(!1),[ke,xe]=qe.useState([]),Qe=qe.useRef([]),Ne=DM(e=>e.streams);qe.useEffect(()=>{Ne.forEach(e=>{if(!n.some(t=>{if(!t||!("role"in t)||"tool-group"!==t.role)return!1;return t.toolGroup.tools.some(t=>t.toolCallId===e.toolCallId)})){if("ai-thinking"===e.toolCallId||"ai-thinking-continuation"===e.toolCallId)return;const t={id:`pending-${e.toolCallId}`,toolCallId:e.toolCallId,name:e.toolName,displayName:e.toolName,description:`Executing ${e.toolName}...`,status:SM.Executing,startTime:Date.now()},n={id:e.toolCallId,tools:[t],status:"executing",startTime:Date.now()},i={role:"tool-group",id:`msg-${e.toolCallId}`,toolGroup:n,timestamp:Date.now()};r(e=>[...e,i])}})},[Ne,n,r]);const Te=qe.useMemo(()=>n.some(e=>{if("role"in e&&"tool-group"===e.role){return e.toolGroup.tools.some(e=>e.status===SM.Confirming)}return!1}),[n]);qe.useEffect(()=>{ve.setFileCompletionActive(oe?.isOpen??!1)},[oe?.isOpen,ve]),qe.useEffect(()=>{let e=!0;if(e&&n.length>0){n.some(e=>{if("role"in e&&"tool-group"===e.role){return e.toolGroup.tools.some(e=>e.status===SM.Confirming)}return!1})&&!Re&&r(e=>e.filter(e=>{if("role"in e&&"tool-group"===e.role){return!e.toolGroup.tools.some(e=>e.status===SM.Confirming)}return!0}))}return()=>{e=!1}},[]),qe.useEffect(()=>{},[]),qe.useEffect(()=>{(async()=>{if(!z.current&&k?.workingDirectory)try{const e=new yK(k.workingDirectory);await e.initialize(),z.current=e,function(e){IM=e}(e)}catch(e){}})()},[k?.workingDirectory]);const[Re,Fe]=qe.useState(null),{setFirebaseUser:Me}=FT(),{setTeams:Oe,setProjects:$e}=BM(),Le=qe.useCallback(e=>{if("execute"===e.type){const t="string"==typeof e.description?e.description:"",n=t.replace("Execute: ",""),r=n.split(" ");return{type:"exec",title:"string"==typeof e.title?e.title:"",description:t,isDestructive:"boolean"==typeof e.isDestructive&&e.isDestructive,command:n,rootCommand:r.length>0&&r[0]?r[0]:n}}if("edit"===e.type)return{type:"edit",title:"string"==typeof e.title?e.title:"",description:"string"==typeof e.description?e.description:"",isDestructive:"boolean"==typeof e.isDestructive&&e.isDestructive,fileName:"string"==typeof e.fileName?e.fileName:"file",fileDiff:"string"==typeof e.fileDiff?e.fileDiff:"",originalContent:"string"==typeof e.originalContent?e.originalContent:void 0,newContent:"string"==typeof e.newContent?e.newContent:void 0};{const t="string"==typeof e.description?e.description:"";return{type:"info",title:"string"==typeof e.title?e.title:"",description:t,isDestructive:"boolean"==typeof e.isDestructive&&e.isDestructive,prompt:t}}},[]);qe.useEffect(()=>(Tz(async e=>De?{approved:!0}:new Promise(t=>{const n={role:"tool-group",id:Bz("blocking-confirmation"),toolGroup:{id:Bz("blocking-group"),tools:[{id:Bz("blocking-tool"),toolCallId:Bz("blocking-call"),name:e.toolName,displayName:e.toolName,description:"object"==typeof e.confirmationDetails&&null!==e.confirmationDetails&&"description"in e.confirmationDetails&&"string"==typeof e.confirmationDetails.description?e.confirmationDetails.description:"",status:SM.Confirming,confirmationDetails:Le(e.confirmationDetails),result:{success:!1,llmContent:"",returnDisplay:"",summary:"Awaiting user confirmation"},startTime:Date.now()}],status:"pending",startTime:Date.now()},timestamp:Date.now()};r(e=>[...e,n]),Fe({request:e,resolve:e=>{r(e=>e.filter(e=>!("id"in e)||e.id!==n.id)),t(e)},fakeMessageId:n.id,fakeToolId:n.toolGroup.tools[0]?.id??"blocking-tool"})})),()=>{Tz(()=>{throw new Error("Confirmation handler not available")})}),[De,Le,r]),qe.useEffect(()=>(XW(async e=>new Promise(t=>{v(e),I(()=>e=>{t(e),v(null),I(null)})})),()=>{XW(()=>{throw new Error("Question handler not available")})}),[v,I]);const Pe=qe.useCallback(async()=>{try{if(!D)throw new Error("No model selected for compression");if(!_)throw new Error("No language model available for compression");const e=D,t=new EM,i={role:"assistant",content:"🔄 Compressing conversation history...",timestamp:Date.now()};if(r(e=>[...e,i]),!_)throw new Error("No language model available for compression");const o=await t.compressAndSaveActiveConversation(n,`session-${Date.now()}`,e,_,!0);if(r(e=>e.slice(0,-1)),o.success){r(o.compressedMessages);const e={role:"assistant",content:`✅ **Conversation compressed successfully!**\n\n**Compression Stats:**\n- Original tokens: ${o.originalTokenCount.toLocaleString()}\n- Compressed tokens: ${o.newTokenCount.toLocaleString()}\n- Tokens saved: ${(o.originalTokenCount-o.newTokenCount).toLocaleString()}\n- Compression ratio: ${Math.round(o.newTokenCount/o.originalTokenCount*100)}%\n\nThe conversation history has been summarized while preserving important context and recent messages.`,timestamp:Date.now()};r(t=>[...t,e])}else{const e={role:"assistant",content:`❌ **Compression failed:** ${o.error||"Unknown error"}`,timestamp:Date.now()};r(t=>[...t,e])}}catch(qK){r(e=>e.slice(0,-1));const t={role:"assistant",content:`❌ **Compression failed:** ${qK instanceof Error?qK.message:String(qK)}`,timestamp:Date.now()};r(e=>[...e,t])}},[n,D,r,_]),je=qe.useCallback(async e=>{if(z.current&&k?.workingDirectory)try{const t=parseInt(e.replace("msg-",""),10),i=new EM(k.workingDirectory);await i.initialize(),await i.markForRevert(t,n);const o=await i.getRevertPatches();o&&o.length>0&&await z.current.revert(o.map(e=>({hash:e.hash,files:e.files,filesAdded:0,filesModified:0,filesDeleted:0})));const s=await i.processRevert(n);r(s),await i.clearRevert();const a=await z.current.track();G.current=a}catch(qK){throw ex.error("Failed to revert:",qK),qK}else ex.error("Snapshot service not initialized")},[n,k?.workingDirectory,r]),Ue=qe.useCallback(async()=>{if(z.current&&k?.workingDirectory)try{let e=-1,t="",i=0;for(const r of n)if("role"in r&&"user"===r.role){const n=r;n.hidden||(e=i,"string"==typeof n.content?t=n.content:Array.isArray(n.content)&&(t=n.content.filter(e=>null!==e&&"object"==typeof e&&"type"in e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")),i++)}if(e>=0){const n=e-1;n>=0?await je(`msg-${n}`):(await je("msg--1"),r([]),await c()),t&&Ee.current?.setValue(t),ee("chat")}}catch(qK){ex.error("Failed to undo:",qK)}},[n,k?.workingDirectory,je,r,c,ee]),ze=qe.useCallback(async()=>{j.current&&(j.current.abort(),j.current=null,P(!0),s(!1),a(null),DM.getState().clearAll(),await new Promise(e=>{r(t=>{const n=[...t];let r=!1;for(let e=n.length-1;e>=0;e--){const t=n[e];if(t&&("role"in t&&"assistant"===t.role)){const i=t.content;""===i||"string"==typeof i&&""===i.trim()?n.splice(e,1):r=!0;break}}if(!r)for(let e=n.length-1;e>=0;e--){const t=n[e];if(t&&("role"in t&&"user"===t.role)){if(!t.hidden){n.splice(e,1);break}}}return setTimeout(e,0),n})}),await R(),ee("chat"),q.current||setTimeout(()=>J.current?.(),0))},[s,a,r,ee,R]),Ge=qe.useCallback(()=>{if(Re){const{resolve:e,fakeMessageId:t}=Re;e({approved:!1}),r(e=>e.filter(e=>!("id"in e)||e.id!==t)),Fe(null)}iz.getState().cancelAll()},[Re,r]);qe.useImperativeHandle(t,()=>({isStreaming:()=>i!==_w.Idle,cancelStream:ze,openResumeInterface:()=>Ce(!0),clearInput:()=>Ee.current?.clear(),hasInput:()=>""!==(Ee.current?.getValue()||"").trim(),cleanupOnExit:Ge}),[i,ze,Ge]);const He=qe.useCallback((e,t=!1)=>{r(n=>{const r=[...n];for(let i=r.length-1;i>=0;i--){const n=r[i];if(n&&("role"in n&&"assistant"===n.role)){const o=n;if("string"==typeof o.content){const n=o.content,s=t?n+e:e;r[i]={...o,content:s}}break}}return r})},[r]),Je=qe.useCallback(async(e,t)=>{if(""===e.trim())return;const n=e.trim();if(o&&!q.current){const e={id:Bz("queued-msg"),message:n,timestamp:Date.now(),options:t};return C(t=>[...t,e]),void ve.addToHistory(n)}P(!1),s(!0),a(null),ex.info("User message submitted",{messageLength:n.length,isCommand:n.startsWith("/"),model:D?.name});const i=k?.projectInfo?.hasEmbedderMd??!1,l=null!=p&&0===(p.documentCount??0);if($.withScope(e=>{e.setTag("event_type","user_prompt"),e.setTag("has_embedder_md",i?"true":"false"),e.setTag("no_documents",l?"true":"false"),D?.name&&e.setTag("model",D.name),g?.id&&e.setTag("team_id",g.id),p?.id&&e.setTag("project_id",p.id),F?.id&&e.setTag("user_id",F.id),M&&e.setTag("session_id",M),e.setContext("prompt",{length:n.length,isCommand:n.startsWith("/"),content:n,hasEmbedderMd:i,hasNoDocuments:l,projectId:p?.id??null,projectName:p?.name??null,projectDocumentCount:p?.documentCount??null,teamId:g?.id??null,teamName:g?.name??null,userId:F?.id??null,sessionId:M??null}),$.captureMessage("User prompt submitted","info")}),!t?.skipCommandCheck&&n.startsWith("/")){const e=n.substring(1).split(/\s+/),t=e[0],r=e.slice(1);if(!t)return P(!0),s(!1),void a(null);const i=az(t);if(i)try{return await i.action(),P(!0),s(!1),void a(null)}catch(qK){ex.error(`Command ${t} failed:`,qK)}if("resume"===t&&r.length>0){const e=r.join(" ");try{return await u(e),P(!0),s(!1),void a(null)}catch(qK){ex.error("Failed to load conversation:",qK)}}}ve.addToHistory(n),P(!1),s(!0),a({subject:"Thinking...",description:"",startTime:Date.now()});const c=new AbortController;j.current=c;try{const n=k?.workingDirectory,i=await async function(e,t){const n=function(e){const t=[];let n=0;for(;n<e.length;){let r=-1,i=n;for(;i<e.length;){if("@"===e[i]&&(0===i||"\\"!==e[i-1])){r=i;break}i++}if(-1===r){n<e.length&&t.push({type:"text",content:e.substring(n)});break}r>n&&t.push({type:"text",content:e.substring(n,r)});let o=r+1,s=!1;for(;o<e.length;){const t=e[o];if(void 0===t)break;if(s)s=!1;else if("\\"===t)s=!0;else if(/\s/.test(t))break;o++}const a=e.substring(r,o).replace(/\\(.)/g,"$1");t.push({type:"atPath",content:a}),n=o}return t.filter(e=>!("text"===e.type&&""===e.content.trim()))}(e),r=n.filter(e=>"atPath"===e.type);if(0===r.length)return{processedMessage:e,displayMessage:e,toolExecutions:[],fileContents:[]};const i=t||process.cwd(),o=[],s=new Map;for(const h of r){const e=h.content;if("@"===e)continue;const t=e.substring(1);if(!t)continue;let n=t.replace(/\\/g,"/");try{const e=await import("fs/promises"),r=se.resolve(i,t);(await e.stat(r)).isDirectory()&&(n+=n.endsWith("/")?"**/*":"/**/*")}catch(qK){}o.push(n),s.set(e,n)}let a="";for(let h=0;h<n.length;h++){const e=n[h];if(e)if("text"===e.type)a+=e.content;else{const t=s.get(e.content);h>0&&a.length>0&&!a.endsWith(" ")&&t&&(a+=" "),t?a+=`@${t}`:(h>0&&a.length>0&&!a.endsWith(" ")&&(a+=" "),a+=e.content)}}if(a=a.trim(),0===o.length)return{processedMessage:e,displayMessage:e,toolExecutions:[],fileContents:[]};const l={workingDirectory:i,projectRoot:i},u={paths:o,useDefaultExcludes:!0,fileFilteringOptions:{respect_git_ignore:!0,respect_embedder_ignore:!0}};let c=[],d=a,p=e,f=[];try{const e=await JH.executeStructured(u,l),t={toolName:JH.metadata.name,description:JH.getDescription?JH.getDescription(u):"Read multiple files",result:e,success:e.success};if(c.push(t),e.success&&e.llmContent){const t=/--- (.+?) ---\n\n([\s\S]*?)\n\n/g;let n;for(;null!==(n=t.exec(e.llmContent));){const e=n[1]??"",t=n[2]??"";f.push({path:e,content:t,isReadable:!0})}e.llmContent&&"No files matching the criteria were found or all were skipped."!==e.llmContent.trim()&&(d=e.llmContent+"\n\n"+a)}else d+=`\n--- File Reading Errors ---\n- Tool execution failed: ${e.llmContent}\n--- End Errors ---\n`,o.forEach(t=>{f.push({path:t,content:"",isReadable:!1,error:e.llmContent||"Tool execution failed"})})}catch(qK){const t=qK instanceof Error?qK.message:String(qK),n={toolName:JH.metadata.name,description:JH.getDescription?JH.getDescription(u):"Read multiple files",result:{success:!1,llmContent:`Error executing readManyFiles tool: ${t}`,returnDisplay:`Error executing readManyFiles tool: ${t}`},success:!1};c.push(n),d+=`\n--- File Reading Errors ---\n- Tool execution error: ${t}\n--- End Errors ---\n`,o.forEach(e=>{f.push({path:e,content:"",isReadable:!1,error:t})})}return{processedMessage:d,displayMessage:p,toolExecutions:c,fileContents:f}}(e,n),o=Ee.current?.getPendingImages()||[],a=e=>0===o.length?e:[{type:"text",text:e},...o.map(e=>({type:"image",image:`data:${e.mimeType};base64,${e.base64}`}))],l={role:"user",content:a(i.displayMessage),timestamp:Date.now(),hidden:t?.hidden??!1},u={role:"user",content:a(i.processedMessage),hidden:(t?.hidden??!1)||i.toolExecutions.length>0,timestamp:Date.now()};t?.hidden||(r([...H.current,l]),Ie.current?.scrollToBottom());let d=[...H.current,l];if(i.toolExecutions.length>0){const e={id:Bz("file-mention"),tools:i.toolExecutions.map((e,t)=>({id:Bz(`${e.toolName}-tool`),toolCallId:Bz("file-mention-call"),name:e.toolName,displayName:"Read Files",description:e.description,status:e.success?SM.Success:SM.Error,result:e.result,startTime:Date.now(),endTime:Date.now()})),status:i.toolExecutions.every(e=>e.success)?"completed":"error",startTime:Date.now(),endTime:Date.now()},t={role:"tool-group",id:e.id,toolGroup:e,timestamp:Date.now()};d=[...d,t],d=[...d,u],r(d)}await new Promise(e=>setTimeout(e,50));d.filter(e=>{if(!("role"in e)||"tool-group"===e.role)return!1;const t=e;return"string"==typeof t.content?""!==t.content.trim():Array.isArray(t.content)?t.content.length>0:"Sorry, I encountered an error. Please try again."!==t.content});let p=d;if(!D)throw new Error("No model selected");const h=D;if(!_)throw new Error("No language model instance available");const g=new EM;if(g.shouldAutoCompress(d,h))try{const e=await g.compressAndSaveActiveConversation(d,`session-${Date.now()}`,h,_,!1);e.success&&(p=e.compressedMessages,r(p))}catch(f){}const A=p.filter(e=>{if(!("role"in e)||"tool-group"===e.role)return!1;const t=e;return"string"==typeof t.content?""!==t.content.trim():Array.isArray(t.content)?t.content.length>0:"Sorry, I encountered an error. Please try again."!==t.content}).filter(e=>!("id"in e)||!("string"==typeof e.id&&(e.id.startsWith("env-context-")||e.id.startsWith("embedder-context-")))),m=await async function(){const e=[];try{const t=Date.now(),n=QT();n&&e.push({role:"user",content:n,id:"embedder-context-user",hidden:!0,timestamp:t},{role:"assistant",content:"Got it. Thanks for the custom instructions!",id:"embedder-context-assistant",hidden:!0,timestamp:t+1});const r=ST.getState(),i=await r.getEnvironmentContext(),o=tx.getState().getDocumentNames(),s=o.length>0?`\n\nThese are the documents that are available in document search:\n\n${o.join("\n")}`:"",a=`This is the Embedder CLI. We are setting up the context for our chat.\nToday's date is ${i.dateTime.formatted}.\nMy operating system is: ${i.platform.platform}\nI'm currently working in the directory: ${i.workingDirectory}\n\nThe user can find documentation about embedder at https://docs.embedder.dev\n\nEmbedder CLI has a set of slash commands the user can use. Here are the commands with their descriptions:\n /clear Clear conversation history - Ctrl+R\n /resume Resume a conversation - Ctrl+O\n /todo Show/hide current todo list - Ctrl+T\n /model Select which AI model to use - Ctrl+B\n /help Show available commands and shortcuts\n /compress Compress conversation history to save context\n /rewind View and revert to previous conversation states\n /undo Undo the last query\n /project Switch to a different project in the current team\n /init Create EMBEDDER.md with project contexts\n /doc Upload hardware docs and datasheets to improve AI accuracy\n /logout Sign out and return to login screen\n /exit Close the application\n${i.folderStructure}${s}`.trim();return e.push({role:"user",content:a,id:"env-context-user",hidden:!0,timestamp:t+2},{role:"assistant",content:"Got it. Thanks for the context!",id:"env-context-assistant",hidden:!0,timestamp:t+3}),e}catch(qK){return ex.warn("Failed to create environment context messages:",qK),e}}(),y=[...m,...A];if(z.current)try{const e=await z.current.track();G.current=e,ex.info(`[Snapshot] Created BEFORE snapshot: ${e}`)}catch(qK){ex.error("[Snapshot] Failed to create BEFORE snapshot:",qK)}else ex.warn("[Snapshot] snapshotServiceRef is null, skipping snapshot");if(W.current=!1,!_)throw new Error("No language model instance available");const b=await fI({model:_,system:void 0,stopWhen:UE(32),messages:y,tools:"act"===Q?tq:Object.fromEntries(Object.entries(tq).filter(([e])=>function(e,t){return"act"===t||(nq[e]??!1)}(e,Q))),maxOutputTokens:64e3,abortSignal:c.signal,onError:({error:e})=>{if(!e||"object"!=typeof e)return;const t=e;if(ex.error("streamText onError handler triggered",{errorType:typeof e,errorName:t?.name,errorMessage:t?.message,errorReason:t?.reason,errorStatusCode:t?.statusCode,errorStatus:t?.status,errorResponseBody:t?.responseBody,fullError:JSON.stringify(e,Object.getOwnPropertyNames(e))}),"maxRetriesExceeded"===t.reason)throw new Error("Maximum retries exceeded. Please try again later.");if("AI_APICallError"===t.name)throw t},onStepFinish:async({toolResults:e})=>{if(e.length>0){e.forEach(e=>{if(e.toolCallId){const t=e.args?JSON.stringify(e.args):"",n=e.output||e.result||"",r=t+"\n"+String(n);DM.getState().updateStream(e.toolCallId,e.toolName||"unknown",r)}});const t=Dz(e,tq);if(t.some(e=>e.toolGroup.tools.some(e=>e.status===SM.Cancelled))&&!W.current){W.current=!0,j.current?.abort(),s(!1),r(n=>{const r=[...n],i=new Set(e.map(e=>e.toolCallId).filter(Boolean)),o=[];for(let e=r.length-1;e>=0;e--){const t=r[e];if(t&&"role"in t&&"tool-group"===t.role){const n=t;"executing"===n.toolGroup.status&&n.toolGroup.tools.some(e=>i.has(e.toolCallId))&&o.push(e)}}if(o.length>0){o.sort((e,t)=>t-e);for(const t of o)r.splice(t,1);const e=o[o.length-1]??0;r.splice(e,0,...t)}else r.push(...t);return r});const n={role:"user",content:[{type:"text",text:"Operation cancelled by user"}],hidden:!0,timestamp:Date.now()};return void r(e=>[...e,n])}if(r(n=>{const r=[...n],i=new Set(e.map(e=>e.toolCallId).filter(Boolean)),o=[];for(let e=r.length-1;e>=0;e--){const t=r[e];if(t&&"role"in t&&"tool-group"===t.role){const n=t;"executing"===n.toolGroup.status&&n.toolGroup.tools.some(e=>i.has(e.toolCallId))&&o.push(e)}}if(o.length>0){o.sort((e,t)=>t-e);for(const t of o)r.splice(t,1);const e=o[o.length-1]??0;r.splice(e,0,...t)}else r.push(...t);return r}),G.current&&z.current)try{ex.info(`[Snapshot] Calculating patch from BEFORE: ${G.current}`);const e=await z.current.patch(G.current);if(ex.info(`[Snapshot] Patch calculated: ${e.files.length} files changed`),e.files.length>0&&ex.info(`[Snapshot] Files: ${e.files.map(e=>e.split("/").pop()).join(", ")}`),e.files.length>0){const t=await z.current.track();ex.info(`[Snapshot] Created AFTER snapshot: ${t}`),r(n=>{const r=[...n];for(let i=r.length-1;i>=0;i--){const n=r[i];if(n&&"role"in n&&"user"===n.role){const o=n;if(!o.hidden){const n={hash:e.hash,afterHash:t||void 0,files:e.files};ex.info(`[Snapshot] Attached patch to user message: before=${e.hash?.substring(0,8)}, after=${t?.substring(0,8)}`);const s=o.patch?Array.isArray(o.patch)?o.patch:[o.patch]:[];r[i]={...o,patch:[...s,n]};break}}}return r}),G.current=t}else ex.info("[Snapshot] No files changed, skipping patch")}catch(qK){ex.error("[Snapshot] Failed to calculate patch:",qK)}else G.current||ex.warn("[Snapshot] currentSnapshotRef is null, cannot calculate patch"),z.current||ex.warn("[Snapshot] snapshotServiceRef is null, cannot calculate patch")}}});let v=null,E="";Z.current="",Y.current=null,null!==V.current&&(clearTimeout(V.current),V.current=null);const I=()=>{null===V.current&&(V.current=setTimeout(()=>{V.current=null,Z.current&&Y.current&&He(Z.current,!1)},16))},w=()=>{null!==V.current&&(clearTimeout(V.current),V.current=null,Z.current&&Y.current&&He(Z.current,!1)),E="",v=null,Z.current="",Y.current=null};for await(const e of b.fullStream)if("text-delta"===e.type){if(E+=e.text,Z.current=E,DM.getState().updateStream("ai-thinking","thinking",E),v)I();else if(v={role:"assistant",model:D?D.name:"unknown-model",content:E,mode:"plan"===Q?"PLAN":"ACT",timestamp:Date.now()},Y.current=v,v){const e=v;r(t=>[...t,e])}}else if("tool-call"===e.type){w(),v=null;const t=e;if(t.toolCallId&&t.args){const e=JSON.stringify(t.args);DM.getState().updateStream(t.toolCallId,t.toolName||"unknown",e)}}w()}catch(qK){const t=qK;if("AbortError"!==t?.name){ex.error("AI stream error occurred",{errorName:"string"==typeof t?.name?t.name:void 0,errorMessage:"string"==typeof t?.message?t.message:void 0,errorStack:"string"==typeof t?.stack?t.stack:void 0,errorStatusCode:"number"==typeof t?.statusCode?t.statusCode:void 0,errorStatus:"string"==typeof t?.status?t.status:void 0,errorResponseBody:t?.responseBody,errorData:t?.data,errorCause:t?.cause&&"object"==typeof t.cause&&null!==t.cause?{name:"string"==typeof t.cause?.name?t.cause.name:void 0,message:"string"==typeof t.cause?.message?t.cause.message:void 0,statusCode:"number"==typeof t.cause?.statusCode?t.cause.statusCode:void 0,responseBody:t.cause?.responseBody,data:t.cause?.data}:void 0,fullError:JSON.stringify(qK,Object.getOwnPropertyNames(qK))});let n="Sorry, I encountered an error. Please try again.";if(qK&&"object"==typeof qK&&"name"in qK&&"AI_APICallError"===t.name){const e=("number"==typeof t.statusCode?t.statusCode:void 0)||("string"==typeof t.status?t.status:void 0)||(t.cause&&"object"==typeof t.cause&&"number"==typeof t.cause?.statusCode?t.cause.statusCode:void 0),r=t.responseBody||t.data||(t.cause&&"object"==typeof t.cause&&"data"in t.cause?t.cause.data:void 0)||(t.cause&&"object"==typeof t.cause&&"responseBody"in t.cause?t.cause.responseBody:void 0),i=r&&"object"==typeof r?r:null,o=i?.reason;if(403===e&&o&&"string"==typeof o)switch(o){case"NO_PAYMENT_METHODS":n="You have reached the free usage limit, please add a card on https://app.embedder.dev to continue (Error 403: No Payment Method)",d(!0);break;case"LAST_CHARGE_FAILED":n="Your last payment failed. Please update your payment method on https://app.embedder.dev/billing (Error 403: Payment Failed)",d(!0);break;case"ACCOUNT_SUSPENDED":n="Your account has been suspended. Please contact support (Error 403: Account Suspended)";break;case"TRANSACTION_PENDING":n="A payment transaction is currently processing. Please try again in a few moments (Error 403: Transaction Pending)";break;case"CREATING_TRANSACTION":n="Creating payment transaction. Please try again in a moment (Error 403: Creating Transaction)";break;default:n=`Authorization failed: ${o} (Error 403)`}else if(403===e)n="Authorization failed. You may need to add a payment method on https://app.embedder.dev/billing (Error 403)",d(!0);else if(e){n=`Sorry, I encountered an error. Please try again. (Error ${e} ${"string"==typeof r?r:""})`}}const i={role:"assistant",model:D?D.name:"unknown-model",content:n,mode:"plan"===Q?"PLAN":"ACT"};r(e=>[...e,i])}}finally{P(!0),s(!1),a(null),j.current=null,DM.getState().clearAll(),await R(),q.current||setTimeout(()=>J.current?.(),0)}},[_,D,r,s,a,Q,d,He,o,C,ve,k?.workingDirectory,R,u]),Ke=qe.useCallback(async()=>{if(q.current||o)return;if(0===w.length)return;const e=w[0];if(e){q.current=!0,C(e=>e.slice(1));try{await Je(e.message,{skipCommandCheck:!0,hidden:e.options?.hidden})}catch(qK){ex.error("Error processing queued message:",qK),C([])}finally{q.current=!1,setTimeout(()=>{K.current.length>0&&!q.current&&J.current?.()},50)}}},[w,o,C,Je]);qe.useEffect(()=>{J.current=Ke},[Ke]);const Ze=qe.useCallback(()=>{Se(e=>!e)},[]),Ve=qe.useCallback(async(e,t)=>{e.trim()&&await Je(e,{skipCommandCheck:!0,hidden:t?.hidden??!1})},[Je]);qe.useEffect(()=>{oz={setIsResumeInterfaceOpen:Ce,clearActiveConversation:c,setMessages:r,saveConversation:l,firebaseAuth:{signOut:()=>sT.signOut()},closeSession:T,exitApp:O,messages:n,model:D,compressConversation:Pe,setFirebaseUser:Me,setProjects:$e,setTeams:Oe,setIsModelSelectorOpen:fe,setIsRewindInterfaceOpen:Be,setIsHelpOpen:me,performUndo:Ue,setProject:f,project:p,setPreviousProject:h,setTeam:A,team:g,teams:m,setPreviousTeam:y,setMode:N,submitMessage:Ve,setAutoApproval:Se,toggleAutoApproval:Ze}},[c,r,l,T,O,Pe,n,D,Ue,f,p,h,A,g,m,y,N,Ve,Ze,Me,$e,Oe]),Gi((e,t)=>{if(t.ctrl&&"d"===e)vw("https://app.embedder.dev").catch(e=>{ex.error("Failed to open docs URL:",e)});else{if(Ae){if(t.tab)return void be(e=>"general"===e?"commands":"general");if(t.escape)return me(!1),be("general"),Ee.current?.clear(),void ee("chat")}if(pe){if(t.upArrow)return void ge(e=>Math.max(0,e-1));if(t.downArrow)return void ge(e=>Math.min(B.length-1,e+1));if(t.return){const e=B[he];return e&&(S(e),hT(e)),fe(!1),ge(0),Ee.current?.clear(),void ee("chat")}if(t.escape)return fe(!1),ge(0),Ee.current?.clear(),void ee("chat")}if(X&&L&&t.ctrl)switch(e){case"b":{if(0===B.length)break;const e=((D?B.findIndex(e=>e.name===D.name):0)+1)%B.length,t=B[e]||null;S(t),hT(t);break}case"r":if(n.length>0){const e=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);l(`chat-${e}`).then(()=>{}).catch(e=>{ex.error("Failed to auto-save conversation before reset:",e)})}r([]),iz.getState().clear(),DM.getState().clearAll(),c().catch(()=>{});break;case"s":{const e=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);l(`chat-${e}`).then(()=>{}).catch(e=>{});break}case"o":Ce(!0)}}},{isActive:!b});const Ye=qe.useCallback(async e=>{if(_&&D)try{const t=H.current.filter(e=>"role"in e&&"tool-group"!==e.role),n=e.map(e=>({role:"tool",content:[{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:e.output||e.result||String(e)}]})),i=await fI({model:_,messages:[...t,...n],tools:tq,maxOutputTokens:64e3,abortSignal:j.current?.signal,onStepFinish:({toolResults:e})=>{if(e.length>0){e.forEach(e=>{if(e.toolCallId){const t=e.args?JSON.stringify(e.args):"",n=e.output||e.result||"",r=t+"\n"+String(n);DM.getState().updateStream(e.toolCallId,e.toolName||"unknown",r)}});const t=Dz(e,tq);r(e=>[...e,...t])}}});let o=null;for await(const e of i.fullStream)if("text-delta"===e.type){if(o)o.content+=e.text,He(String(o.content),!1);else if(o={role:"assistant",model:D?D.name:"unknown-model",content:e.text,mode:"plan"===Q?"PLAN":"ACT",timestamp:Date.now()},o){const e=o;r(t=>[...t,e])}DM.getState().updateStream("ai-thinking-continuation","thinking",String(o?.content||e.text))}else if("tool-call"===e.type){const t=e;if(t.toolCallId&&t.args){const e=JSON.stringify(t.args);DM.getState().updateStream(t.toolCallId,t.toolName||"unknown",e)}}}catch(t){}},[_,D,r,He,Q]);qe.useEffect(()=>{U.current=Ye},[Ye]),qe.useEffect(()=>{lK().then(ie)},[]),qe.useEffect(()=>{if(pe&&D){const e=B.findIndex(e=>e.provider===D.provider&&e.name===D.name);-1!==e&&ge(e)}},[pe,D,B]);const Xe=qe.useCallback(e=>{if(!Re)return;const{resolve:t}=Re;let n;switch(e){case kM.ProceedOnce:n={approved:!0,storePermission:"once"};break;case kM.ProceedAlways:n={approved:!0,storePermission:"always"};break;case kM.ProceedAlwaysCommand:n={approved:!0,storePermission:"command"};break;default:n={approved:!1}}Fe(null),t(n)},[Re]);qe.useCallback(async()=>{if(!n.some(e=>{if(!e||!("role"in e)||"tool-group"!==e.role)return!1;return e.toolGroup.tools.some(e=>e.status===SM.Confirming)})&&Qe.current.length>0){const e=[...Qe.current];Qe.current=[],xe([]),await(U.current?.(e))}},[n]);const et=qe.useCallback(async(e,t)=>{Re&&e===Re.fakeToolId&&Xe(t)},[Re,Xe]),tt=qe.useMemo(()=>n.some(e=>{if(!e||!("role"in e)||"tool-group"!==e.role)return!1;return e.toolGroup.tools.some(e=>e.status===SM.Confirming)}),[n]),nt=qe.useMemo(()=>({messages:n,focused:X,onToolConfirm:et,disableArrowKeyScrolling:ce?.isOpen||oe?.isOpen||tt}),[n,X,et,ce?.isOpen,oe?.isOpen,tt]),rt=qe.useMemo(()=>{for(let e=n.length-1;e>=0;e--){const t=n[e];if(t&&"toolGroup"in t){const e=t.toolGroup;if(e.tools.some(e=>e.status===SM.Error))return"error";if(e.tools.every(e=>e.status===SM.Success)&&"completed"===e.status)return"success"}}return null},[n]),it=qe.useMemo(()=>({currentModel:D,canChat:L,exitConfirmation:e,streamingState:i,lastToolStatus:rt,messages:n,yoloEnabled:De}),[D,L,e,i,rt,n,De]);return We.jsx(G$,{children:We.jsx(ki,{height:"100%",width:"100%",flexDirection:"column",children:b&&E?We.jsx(IK,{questions:b.questions,onSubmit:e=>{if(E){const t={promptId:b.id,answers:e,timestamp:Date.now()};E(t)}},onCancel:()=>{if(E){const e={promptId:b.id,answers:{},timestamp:Date.now()};E(e)}},isFocused:!0}):we?We.jsx(fK,{isOpen:we,onClose:()=>{Ce(!1),Ee.current?.clear(),ee("chat")},onSelect:async e=>{try{await u(e),Ce(!1),Ee.current?.clear(),ee("chat")}catch(qK){ex.error("Failed to load conversation:",qK)}}}):_e?We.jsx(vK,{messages:n,snapshotService:z.current,onRevert:async(e,t)=>{try{Be(!1),"msg--1"===e?(await je(e),r([]),await c()):await je(e),t&&Ee.current?.setValue(t),ee("chat")}catch(qK){ex.error("Failed to revert:",qK)}},onClose:()=>{Be(!1),Ee.current?.clear(),ee("chat")}}):We.jsxs(We.Fragment,{children:[We.jsxs(ki,{flexGrow:1,marginBottom:1,flexDirection:"column",children:[We.jsx(xL,{...it}),We.jsx(ki,{justifyContent:"flex-start",flexShrink:0,children:We.jsx(ML,{})}),We.jsx(EL,{...nt,ref:Ie})]}),"first"===e&&We.jsx(ki,{justifyContent:"center",flexShrink:0,children:We.jsx(xi,{color:"yellow",children:"ctrl+c to exit"})}),We.jsx(wK,{queueLength:w.length}),le.length>0&&We.jsx(wz,{pendingImages:le,onClear:()=>{Ee.current?.clearPendingImages(),ue([])}}),We.jsxs(ki,{borderStyle:"round",borderColor:"gray",paddingX:1,flexShrink:0,children:[We.jsx(xi,{dimColor:Te,children:"❯ "}),We.jsx(ki,{flexGrow:1,children:We.jsx(Iz,{ref:Ee,onSubmit:e=>{Je(e),Ee.current?.clearPendingImages(),Ee.current?.clear()},disabled:Te,focus:X&&!Te,placeholder:o?"Message will be queued...":_K,enableFileMentions:!0,onFileSearchStateChange:ae,enableSlashCommands:!0,onCommandSearchStateChange:de,onPendingImagesChange:ue})})]}),We.jsx(ki,{marginTop:0,flexShrink:0,children:We.jsx(Cz,{})}),oe?.isOpen&&We.jsx(ki,{marginTop:1,flexDirection:"column",height:8,flexShrink:0,paddingLeft:2,children:oe.isLoading?We.jsx(ki,{paddingY:1,children:We.jsx(xi,{color:"gray",children:"Searching files..."})}):0===oe.suggestions.length?We.jsx(ki,{paddingY:1,children:We.jsx(xi,{color:"gray",children:oe.query?`No files matching "${oe.query}"`:"No files found"})}):We.jsx(ki,{flexDirection:"column",width:"100%",paddingY:0,overflow:"hidden",children:oe.suggestions.slice(Math.max(0,oe.selectedIndex-4),Math.min(oe.suggestions.length,Math.max(0,oe.selectedIndex-4)+8)).map((e,t)=>{const n=Math.max(0,oe.selectedIndex-4)+t===oe.selectedIndex;return We.jsx(ki,{width:"100%",minHeight:1,children:We.jsxs(xi,{color:"gray",inverse:n,wrap:"truncate-end",children:[e.relativePath,e.isDirectory?"/":""]})},e.path)})})}),ce?.isOpen&&We.jsx(ki,{marginTop:1,flexDirection:"column",height:9,flexShrink:0,paddingLeft:2,children:We.jsx(rq,{suggestions:ce.suggestions,selectedIndex:ce.selectedIndex,width:Math.max(60,x-4)})}),pe&&We.jsx(ki,{marginTop:1,flexDirection:"column",height:12,flexShrink:0,paddingLeft:2,children:We.jsx(hK,{models:B,selectedModel:D,selectedIndex:he,width:Math.max(60,x-4)})}),Ae&&We.jsx(ki,{marginTop:1,flexDirection:"column",height:20,flexShrink:0,paddingLeft:2,children:We.jsx(AK,{version:"2.0.31",currentTab:ye,width:Math.max(80,x-4)})}),re&&We.jsx(ki,{children:We.jsxs(xi,{children:["🔄 Update available (",re.version,")! Run"," ",We.jsx(xi,{color:"red",children:re.command})," to update"]})})]})})})});function DK(){const{team:e,project:t}=BM(),{selectedModel:n}=VF(),{firebaseUser:r}=FT(),{currentMode:i,modeConfig:o}=JF();return We.jsxs(ki,{borderStyle:"single",flexDirection:"column",padding:1,width:"100%",height:"100%",children:[We.jsxs(ki,{flexDirection:"column",paddingRight:2,paddingLeft:2,paddingBottom:0,paddingTop:0,alignSelf:"flex-start",flexGrow:1,children:[We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Current User:"})," ",r?.displayName," (",r?.email,")"]}),We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Current Plan:"})," Usage Based"]}),We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Selected Model:"})," ",We.jsx(xi,{color:"green",children:n?n.name:"(none)"})," ",We.jsxs(xi,{color:"plan"===i?"blue":"green",bold:!0,children:["[",o.name,"]"]})]}),We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Selected Team:"})," ",We.jsx(xi,{color:"cyan",children:e?.name})]}),We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Selected Project:"})," ",We.jsx(xi,{color:"magenta",children:t?.name})]})]}),We.jsx(ki,{flexDirection:"column",paddingRight:2,paddingLeft:2,paddingBottom:0,paddingTop:1,alignSelf:"flex-start",children:We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Version:"})," 1.0.0"]})})]})}function SK({isSelected:e=!1}){return Je.createElement(ki,{marginRight:1},e?Je.createElement(xi,{color:"blue"},eo.pointer):Je.createElement(xi,null," "))}function kK({isSelected:e=!1,label:t}){return qe.createElement(xi,{color:e?"blue":void 0},t)}function xK({items:e=[],isFocused:t=!0,initialIndex:n=0,indicatorComponent:r=SK,itemComponent:i=kK,limit:o,onSelect:s,onHighlight:a}){const l="number"==typeof o&&e.length>o,u=l?Math.min(o,e.length):e.length,c=u-1,[d,p]=qe.useState(n>c?c-n:0),[f,h]=qe.useState(n?n>c?c:n:0),g=qe.useRef(e);qe.useEffect(()=>{y(g.current.map(e=>e.value),e.map(e=>e.value))||(p(0),h(0)),g.current=e},[e]),Gi(qe.useCallback((t,n)=>{if("k"===t||n.upArrow){const t=(l?u:e.length)-1,n=0===f,r=n?d+1:d,i=n?l?f:t:f-1;p(r),h(i);const o=l?Zi(e,r).slice(0,u):e;"function"==typeof a&&a(o[i])}if("j"===t||n.downArrow){const t=f===(l?u:e.length)-1,n=t?d-1:d,r=t?l?f:0:f+1;p(n),h(r);const i=l?Zi(e,n).slice(0,u):e;"function"==typeof a&&a(i[r])}if(/^[1-9]$/.test(t)){const n=Number.parseInt(t,10)-1,r=l?Zi(e,d).slice(0,u):e;if(n>=0&&n<r.length){const e=r[n];e&&s?.(e)}}if(n.return){const t=l?Zi(e,d).slice(0,u):e;"function"==typeof s&&s(t[f])}},[l,u,d,f,e,s,a]),{isActive:t});const A=l?Zi(e,d).slice(0,u):e;return Je.createElement(ki,{flexDirection:"column"},A.map((e,t)=>{const n=t===f;return Je.createElement(ki,{key:e.key??e.value},Je.createElement(r,{isSelected:n}),Je.createElement(i,{...e,isSelected:n}))}))}function QK(){const{isFocused:e}=qi({id:"team-selection",autoFocus:!0}),{focus:t}=Ji(),{team:n,setTeam:r,teams:i,setIsCreateTeamOpen:o,previousTeam:s,setPreviousTeam:a,previousProject:l,setProject:u,setPreviousProject:c}=BM();Gi((e,n)=>{n.escape&&s&&l&&(r(s),u(l),a(null),c(null),t("chat"))});const d=i.map((e,t)=>({label:`${e.name} ${e.shared?"(Shared)":""}`,value:e.id}));return We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Select a team"})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:"Select which team to use for this session."})}),We.jsx(xK,{isFocused:e,items:[...d],onSelect:e=>(e=>{if("create-team"===e)return void o(!0);const n=i.find(t=>t.id===e);n&&(t("project-selection"),r(n))})(e.value)}),We.jsx(ki,{marginTop:1,children:We.jsxs(xi,{color:"dim",children:["(Use Enter to select",s&&l?", ESC to go back":"",")"]})})]})})}function NK({message:e="Loading your data...",description:t=""}){return We.jsx(ki,{width:"100%",height:"100%",justifyContent:"center",alignItems:"center",padding:1,children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(xi,{children:e}),We.jsx(xi,{children:t||""})]})})}function TK(){const{isFocused:e}=qi({id:"project-selection",autoFocus:!0}),{focus:t}=Ji(),{team:n,setTeam:r,teams:i,projects:o,setProject:s,setIsCreateProjectOpen:a,previousProject:l,setPreviousProject:u,previousTeam:c,setPreviousTeam:d}=BM(),[p,f]=qe.useState(!1),h=o.filter(e=>e.teamId===n?.id);return Gi((e,n)=>{n.escape&&(l?(s(l),u(null),c&&(r(c),d(null)),t("chat")):i.length>1?(r(null),s(null),t("team-selection")):t("project-selection"))}),n?p?We.jsx(NK,{message:"Loading your project..."}):We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Select a project"})}),We.jsx(ki,{marginBottom:1,children:We.jsxs(xi,{children:["Select which project to use within ",We.jsx(xi,{bold:!0,children:n.name}),"."]})}),We.jsx(ro,{isFocused:e,items:[...h.map(e=>({label:e.name,value:e.id})),{label:"Create a new project",value:"create-project"}],onSelect:e=>(e=>{if("create-project"===e)return void a(!0);const r=h.find(t=>t.id===e);if(r&&n){f(!0),u(null),d(null);try{gT(process.cwd(),n.id,r.id)}catch(qK){ex.warn("Failed to cache workspace selection:",qK)}setTimeout(()=>{s(r),t("chat")},0)}})(e.value)}),We.jsx(ki,{marginTop:1,children:We.jsxs(xi,{color:"dim",children:["(Use Enter to select",i.length>1?", ESC to go back":"",")"]})})]})}):null}function RK({previousPage:e=null,firstTime:t=!1}){const{isFocused:n}=qi({id:"project-creation",autoFocus:!0}),{focus:r}=Ji(),{team:i,setTeam:o,createProject:s,setIsCreateProjectOpen:a}=BM(),[l,u]=qe.useState(!1);Gi((t,n)=>{if(n.escape)return"team-selection"===e&&o(null),void a(!1)});return We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Create a new project"})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:t?"Let's get started by creating your first project!":We.jsxs(We.Fragment,{children:["Create a new project within the ",We.jsx(xi,{bold:!0,children:i?.name})," team."]})})}),We.jsxs(ki,{flexDirection:"column",marginBottom:1,alignItems:"flex-start",children:[We.jsx(xi,{bold:!0,children:"Project Name"}),We.jsxs(ki,{borderStyle:"single",borderColor:"gray",minHeight:3,height:3,flexDirection:"row",alignItems:"center",width:50,children:[We.jsx(xi,{children:"❯ "}),We.jsx(Iz,{focus:n,disabled:l,onSubmit:async e=>{if(!l&&""!==e.trim())try{u(!0),await s(e,!0),r("chat"),a(!1)}catch(qK){ex.error("Error creating project:",qK)}finally{u(!1)}},maxLength:32,placeholder:"Super Advanced Project"})]})]}),l&&We.jsx(ki,{marginBottom:1,children:We.jsxs(xi,{children:[We.jsx(FL,{type:"triangle"})," Creating"]})}),We.jsx(ki,{marginTop:1,children:We.jsxs(xi,{color:"dim",children:["(Use Enter to create",t?"":", ESC to go back",")"]})})]})})}function FK(){const{isFocused:e}=qi({id:"billing-required",autoFocus:!0}),[t,n]=qe.useState(!1),{billingStatus:r,refreshBillingStatus:i}=FT(),{setIsBillingModalOpen:o}=BM();return qe.useEffect(()=>{if(!t)return;const e=setInterval(async()=>{await i(),r&&r.paymentMethodCount>0&&(n(!1),o(!1))},1e3);return()=>clearInterval(e)},[t,r,o,i,n]),Gi((r,i)=>{if(e)if(!i.escape||t){if(i.return&&!t){n(!0);const e="darwin"===process.platform?"open":"win32"===process.platform?"start":"xdg-open";ke(e+" https://app.embedder.dev/billing")}}else o(!1)}),We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"You have reached the free usage limit"})}),We.jsx(ki,{marginBottom:2,children:We.jsx(xi,{children:"Please add a card to continue"})}),t&&We.jsx(ki,{marginBottom:2,children:We.jsx(FL,{type:"dots"})}),We.jsx(ki,{marginTop:2,children:t?We.jsx(xi,{color:"dim",children:"Please complete the setup in your browser..."}):We.jsxs(ki,{flexDirection:"column",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{color:"cyan",children:"Press ENTER to add payment method"})}),We.jsx(ki,{children:We.jsx(xi,{color:"dim",children:"Press ESC to go back"})})]})})]})})}function MK(){const{isFocused:e}=qi({id:"document-upload",autoFocus:!0}),{project:t,setIsAddDocumentsModalOpen:n}=BM(),[r,i]=qe.useState(!1);return Gi((t,i)=>{e&&i.escape&&!r&&n(!1)},{isActive:e}),We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"No Documents Found"})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:"Add documentation to your project for better AI assistance."})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{color:"dim",children:"Upload files like API docs, architecture guides, or design specs."})}),We.jsx(ro,{isFocused:e&&!r,items:[{value:"upload-documents",label:"Open Web Console"}],onSelect:e=>{if("upload-documents"===e.value){if(t?.id){i(!0);const e=`https://app.embedder.dev/projects/${t.id}?overrideTeamId=${t.teamId}`;vw(e).then(()=>{n(!1)}).catch(e=>{ex.error("Failed to open browser:",e),i(!1)})}}else"skip"===e.value&&n(!1)}}),We.jsx(ki,{marginTop:1,children:r?We.jsx(xi,{color:"dim",children:"Opening browser..."}):We.jsx(xi,{color:"dim",children:"Press ESC to dismiss"})})]})})}function OK(){qi({id:"authentication",autoFocus:!0});const[e,t]=qe.useState(!1),[n,r]=qe.useState(null),[i,o]=qe.useState("Loading your data..."),[s,a]=qe.useState(null),[l,u]=qe.useState(null),[c,d]=qe.useState(!1),{teams:p,projects:f,setIsDeviceAuthOpen:h}=BM(),{backendUser:g,firebaseUser:A}=FT(),{availableModels:m}=VF();qe.useEffect(()=>{(async()=>{const e=fT();if(e){u(e),t(!0),o("Loading your data...");try{const t=FN._fromJSON(sT,e.user);await sT.updateCurrentUser(t),d(!0)}catch(n){ex.error("Failed to restore user from stored credentials:",n),await pT(null),u(null),t(!1),d(!0),o("Loading your data...")}}else d(!0)})()},[]);const y=!e&&p.length>0&&f.length>0&&null!==g&&m.length>0&&null!==A,b=c&&!A&&!e;if(!y&&!b)return We.jsx(NK,{message:i,description:s});if(!y&&b)h(!0);else if(y)return null;return null}function $K(){qi({autoFocus:!0});const{error:e}=BM(),{exit:t}=Hi();return Gi((e,n)=>{n.escape&&t()}),We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,color:"red",children:"We encountered an error!"})}),We.jsxs(ki,{flexDirection:"column",marginBottom:1,marginTop:5,alignItems:"center",children:[We.jsx(xi,{children:e}),We.jsx(xi,{children:"If it persists, please contact support."})]}),We.jsx(ki,{marginTop:5,children:We.jsx(xi,{color:"dim",children:"Press Enter to retry or ESC to exit."})})]})}function LK(){const[e,t]=qe.useState(null),[n,r]=qe.useState(null),[i,o]=qe.useState(!1),{unauthFetch:s,loggedIn:a}=FT();return qe.useEffect(()=>{let e;if(!s)return;const n=async()=>{try{const i=await(async()=>await s("api/v1/auth/device/start",{method:"POST",headers:{"Content-Type":"application/json"}}))();0,t(i);const a=Date.now()+1e3*i.expiresIn,l=3e3,u=async()=>{try{if(o(!0),Date.now()>a)return o(!1),void n();const t=await(async e=>await s("api/v1/auth/device/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})}))(i.userCode);if(t.accessToken&&"authorized"===t.status)o(!1),await async function(e,t){if(MQ(e.app))return Promise.reject(sN(e));const n=qN(e),r=await eT(n,{token:t,returnSecureToken:!0}),i=await YN._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(i.user),i}(sT,t.accessToken);else if("authorization_pending"===t.status)e=setTimeout(u,l);else{if("code_not_found"===t.status)return o(!1),void n();o(!1),r(t.status||"Unknown error occurred")}}catch(t){o(!1),r(t instanceof Error?t.message:"Polling failed")}};u()}catch(i){o(!1),r(i instanceof Error?i.message:"Failed to authenticate")}};return n(),()=>clearTimeout(e)},[s]),We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",children:[We.jsx(xi,{bold:!0,children:"Login with the following device token:"}),We.jsx(ki,{marginTop:.5,children:e?We.jsx(xi,{bold:!0,color:"green",children:e.userCode}):We.jsx(xi,{children:" Loading..."})}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{children:null!=e?e.verificationUri:"https://app.embedder.dev/auth/activate"})}),n&&!a?We.jsx(ki,{marginTop:1,children:We.jsxs(xi,{color:"red",children:["Error: ",n]})}):i?We.jsxs(ki,{marginTop:1,children:[We.jsx(FL,{type:"clock"}),We.jsx(xi,{children:" Waiting for authentication..."})]}):null]})}function PK({children:e}){return We.jsx(ki,{flexDirection:"column",width:"100%",height:"100%",children:We.jsx(ki,{flexDirection:"row",flexGrow:1,children:e})})}BK.displayName="ChatPage";const jK=[{label:"Chat",value:"chat"},{label:"Conversations",value:"conversations"},{label:"Documents",value:"documents"},{label:"Settings",value:"settings"},{label:"Exit",value:"exit"}];function UK(){const[e,t]=qe.useState(jK[0]),[n,r]=qe.useState(!1),[i,o]=qe.useState("none"),s=qe.useRef(null),a=qe.useRef(null),{team:l,project:u,projects:c,messages:d,isCreateProjectOpen:p,isBillingModalOpen:f,isAddDocumentsModalOpen:h,setIsAddDocumentsModalOpen:g,error:A,teams:m,loading:y,isDeviceAuthOpen:b}=BM(),{loggedIn:v,closeSession:E,backendUser:I}=FT(),{selectedModel:w}=VF(),{exit:C}=Hi(),{focus:_}=Ji(),{switchMode:B}=JF(),{state:D,actions:S}=CL(),k=qe.useRef(!1);Gi((t,r)=>{if("chat"!==e?.value||n){if(r.tab){if(D.isFileCompletionActive)return;B()}else if(r.escape||r.ctrl&&"c"===t){if("main"===x&&"chat"===e?.value&&a.current?.isStreaming())return void a.current.cancelStream();if(!r.ctrl||"c"!==t)return void("chat"===e?.value&&_("chat"));if(a.current?.hasInput())return void a.current.clearInput();"none"===i?(o("first"),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{o("none"),s.current=null},3e3)):"first"===i&&(s.current&&clearTimeout(s.current),a.current?.cleanupOnExit&&a.current.cleanupOnExit(),E(d,u,l,w).finally(()=>{C(),setTimeout(()=>process.exit(0),100)}))}}else{if(r.tab){if(D.isFileCompletionActive)return;return void B()}if(r.escape||r.ctrl&&"c"===t){if("main"===x&&"chat"===e?.value&&a.current?.isStreaming())return void a.current.cancelStream();if(!r.ctrl||"c"!==t)return void("chat"===e?.value&&_("chat"));if(a.current?.hasInput())return void a.current.clearInput();"none"===i?(o("first"),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{o("none"),s.current=null},3e3)):"first"===i&&(s.current&&clearTimeout(s.current),a.current?.cleanupOnExit&&a.current.cleanupOnExit(),E(d,u,l,w).finally(()=>{C(),setTimeout(()=>process.exit(0),100)}))}}},{isActive:!0}),qe.useEffect(()=>{const e=()=>{};return process.on("SIGINT",e),()=>{process.removeListener("SIGINT",e),s.current&&clearTimeout(s.current)}},[]),qe.useEffect(()=>{!(u&&0===(u.documentCount??0))||u.pendingCreation||k.current||y||!v||(k.current=!0,g(!0))},[u,y,v,g]);const x=A?We.jsx($K,{}):!v&&b?We.jsx(LK,{}):v?y?We.jsx(NK,{message:"Loading your data..."}):p?We.jsx(RK,{previousPage:null}):!l&&m.length>1?We.jsx(QK,{}):!u&&c.length>0?We.jsx(TK,{}):u||0!==c.length?f?We.jsx(FK,{}):h?We.jsx(MK,{}):"main":We.jsx(RK,{previousPage:"team-selection",firstTime:!0}):We.jsx(OK,{});return We.jsx(KM,{children:We.jsx(PK,{children:"main"===x?We.jsxs(We.Fragment,{children:[n&&We.jsx(io,{navItems:jK,onSelect:e=>{if("exit"===e.value)E(d,u,l,w).finally(()=>{C(),setTimeout(()=>process.exit(0),100)});else if("conversations"===e.value)t(jK.find(e=>"chat"===e.value)),r(!1),_("chat"),setTimeout(()=>{a.current&&a.current.openResumeInterface?.()},100);else{if("documents"===e.value){if(u?.id){const e=`https://app.embedder.dev/projects/${u.id}?overrideTeamId=${u.teamId}`;vw(e).catch(e=>{ex.error("Failed to open browser:",e)})}return}t(e),_(e.value)}}}),"chat"===e?.value&&We.jsx(BK,{ref:a,exitConfirmation:i}),"settings"===e?.value&&We.jsx(DK,{})]}):x})})}const zK=qe.forwardRef(function(e,t){Gi(()=>{});const{height:n,width:r}=function(){const{stdout:e}=Wi(),t=qe.useCallback(()=>({height:e.rows,width:e.columns}),[e]),[n,r]=qe.useState(t);return qe.useEffect(()=>{function n(){r(t())}return e.on("resize",n),()=>{e.off("resize",n)}},[e,t]),n}();return We.jsx(ki,{ref:t,height:n,width:r,...e})});async function GK(e){return new Promise((t,n)=>{process.stdout.write(e,e=>{e?n(e):t()})})}$.init({dsn:"https://ffddaca20e5fd45b5c4c4263140fd909@sentry-service-prod.embedder.dev/3",sendDefaultPii:!0});let HK=!1;const WK=async()=>{try{await $.flush(2e3)}catch(qK){ex.warn("Sentry flush failed",qK)}};["SIGINT","SIGTERM","SIGBREAK"].forEach(e=>{process.on(e,()=>(e=>{HK||(HK=!0,ex.info(`Received ${e}. Flushing Sentry before shutdown.`),WK().finally(()=>{process.exit(0)}))})(e))}),process.on("beforeExit",()=>{HK||(HK=!0,ex.info("Process beforeExit triggered. Flushing Sentry."),WK())}),process.on("uncaughtException",e=>{ex.error("Uncaught exception:",e),$.captureException(e)}),process.on("unhandledRejection",e=>{ex.error("Unhandled rejection:",e),$.captureException(e instanceof Error?e:new Error(String(e)))}),process.removeAllListeners("warning"),((e,t)=>{const n=((e,t)=>{const n={stdout:i.stdout,stdin:i.stdin,stderr:i.stderr,debug:!1,exitOnCtrlC:!0,patchConsole:!0,maxFps:30,...Oi(t)},r=$i(n.stdout,()=>new Mi(n));return r.render(e),{rerender:r.render,unmount(){r.unmount()},waitUntilExit:r.waitUntilExit,cleanup:()=>Ai.delete(n.stdout),clear:r.clear}})(null,t),r=async function(e){await e.waitUntilExit(),await GK("[?1049l")}(n);return{instance:n,start:async()=>{await GK("[?1049h"),n.rerender(We.jsx(zK,{children:e}))},waitUntilExit:function(){return r}}})(We.jsx(RT,{children:We.jsx(qF,{children:We.jsx(ZF,{children:We.jsx(_M,{children:We.jsx(wL,{children:We.jsx(UK,{})})})})})}),{exitOnCtrlC:!1,debug:"true"===process.env.DEV,maxFps:60}).start();export{KH as D,YH as a,rW as b,nW as c,VH as d,tW as f,ZH as l,eW as s,XH as t};
866
+ fN.initialize(fetch,Headers,Response),tT="Node",RQ(new _x("auth",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal"),{apiKey:o,authDomain:s}=n.options;lN(o&&!o.includes(":"),"invalid-api-key",{appName:n.name});const a={apiKey:o,authDomain:s,clientPlatform:tT,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:zN(tT)},l=new WN(n,r,i,a);return function(e,t){const n=t?.persistence||[],r=(Array.isArray(n)?n:[n]).map(ON);t?.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,t?.popupRedirectResolver)}(l,t),l},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider("auth-internal").initialize()})),RQ(new _x("auth-internal",e=>{const t=qN(e.getProvider("auth").getImmediate());return new iT(t)},"PRIVATE").setInstantiationMode("EXPLICIT")),jQ(nT,rT,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(tT)),jQ(nT,rT,"esm2020"),iN("operation-not-supported-in-this-environment"),WN.prototype.setPersistence=async()=>{};const oT={apiKey:"AIzaSyDuNXvHd-GvTrmXG6_2TnrfqRWo-ApPd3s",authDomain:"app.embedder.dev",projectId:"embedder-dev",storageBucket:"embedder-dev.firebasestorage.app",messagingSenderId:"547074918538",appId:"1:547074918538:web:b5495d2347046fd29e8573",measurementId:"G-4KT5CW28KM"},sT=function(e=function(e=SQ){const t=xQ.get(e);if(!t&&e===SQ&&ux())return PQ();if(!t)throw OQ.create("no-app",{appName:e});return t}()){const t=FQ(e,"auth");if(t.isInitialized())return t.getImmediate();const n=function(e,t){const n=FQ(e,"auth");if(n.isInitialized()){const e=n.getImmediate();if(bx(n.getOptions(),{}))return e;rN(e,"already-initialized")}return n.initialize({options:t})}(e),r=(i="auth",lx()?.emulatorHosts?.[i]);var i;return r&&KN(n,`http://${r}`),n}(PQ(oT)),aT=le(H(),".embedder"),lT=le(aT,"creds.enc"),uT=le(aT,"model.json"),cT=le(aT,"workspace-cache.json"),dT=Ae("justs0m3s4f3ty","salt",32),pT=e=>{if(null===e)return void(K(lT)&&Z(lT));K(aT)||Y(aT,{recursive:!0}),e={...e,user:{...e.user,auth:{config:oT}}};const t=ye(16),n=be("aes-256-gcm",dT,t),r=Buffer.concat([n.update(JSON.stringify(e),"utf8"),n.final()]);X(lT,Buffer.concat([t,n.getAuthTag(),r]))},fT=()=>{if(!K(lT))return null;const e=V(lT),t=e.subarray(0,16),n=e.subarray(16,32),r=e.subarray(32),i=me("aes-256-gcm",dT,t);i.setAuthTag(n);return JSON.parse(Buffer.concat([i.update(r),i.final()]).toString())},hT=e=>{K(aT)||Y(aT,{recursive:!0}),null!==e?X(uT,JSON.stringify(e)):K(uT)&&Z(uT)},gT=(e,t,n)=>{K(aT)||Y(aT,{recursive:!0});let r={};if(K(cT))try{const e=V(cT,"utf8");r=JSON.parse(e)}catch{r={}}r[e]={teamId:t,projectId:n},X(cT,JSON.stringify(r,null,2))};function AT(){return"https://backend-service-prod.embedder.dev"}function mT(){return{}}const yT=kw((e,t)=>({apiFetch:null,sessionId:null,setApiFetch:t=>{e({apiFetch:t})},getApiFetch:()=>t().apiFetch,setSessionId:t=>{e({sessionId:t})},getSessionId:()=>t().sessionId}));function bT(){return process.cwd()}function vT(e=process.cwd()){const t=kT(e),n=J.existsSync(ae.join(e,"package.json")),r=J.existsSync(ae.join(e,"EMBEDDER.md"))||J.existsSync(ae.join(e,"embedder.md"));let i="generic";return t&&n?i="npm":t?i="git":(r||function(e){const t=["Makefile","CMakeLists.txt","*.ino","*.ioc","platformio.ini"],n=[".c",".h",".cpp",".hpp",".asm",".s"];try{const r=J.readdirSync(e);for(const e of t)if(e.includes("*")){const t=e.replace("*","");if(r.some(e=>e.includes(t)))return!0}else if(r.includes(e))return!0;return r.filter(e=>{const t=ae.extname(e).toLowerCase();return n.includes(t)}).length>=2}catch{return!1}}(e))&&(i="embedded"),{isGitRepository:t,hasPackageJson:n,hasEmbedderMd:r,projectType:i,rootDirectory:e}}const ET={maxDepth:3,maxItems:200,showHidden:!1,respectGitIgnore:!0,respectEmbedderIgnore:!0},IT=["node_modules",".git",".vscode",".idea","dist","build","out",".next",".cache","coverage",".nyc_output","logs","*.log",".DS_Store","Thumbs.db"],wT="...";function CT(e,t,n){if(!n.showHidden&&t.startsWith(".")){if(![".gitignore",".embedderignore",".env.example"].includes(t))return!0}for(const r of IT)if(r.includes("*")){if(new RegExp(r.replace(/\*/g,".*")).test(t))return!0}else if(t===r)return!0;return!1}function _T(e,t,n,r,i){const o=n?"└───":"├───";r&&!e.isIgnored||i.push(`${t}${o}${e.name}${ae.sep}${e.isIgnored?wT:""}`);const s=r?"":t+(n?" ":"│ "),a=e.files.length;for(let u=0;u<a;u++){const t=u===a-1&&0===e.subFolders.length&&!e.hasMoreSubfolders?"└───":"├───";i.push(`${s}${t}${e.files[u]}`)}if(e.hasMoreFiles){const t=0===e.subFolders.length&&!e.hasMoreSubfolders?"└───":"├───";i.push(`${s}${t}${wT}`)}const l=e.subFolders.length;for(let u=0;u<l;u++){const t=e.subFolders[u];if(!t)continue;_T(t,s,u===l-1&&!e.hasMoreSubfolders,!1,i)}e.hasMoreSubfolders&&i.push(`${s}└───${wT}`)}function BT(e){if(e.hasMoreFiles||e.hasMoreSubfolders||e.isIgnored)return!0;for(const t of e.subFolders)if(BT(t))return!0;return!1}function DT(e=process.cwd(),t={}){const n={...ET,...t};try{const t=ae.resolve(e);if(!J.statSync(t).isDirectory())return`Error: ${e} is not a directory`;const r=function(e,t){const n={name:ae.basename(e),path:e,files:[],subFolders:[],totalChildren:0,totalFiles:0},r=[{folderInfo:n,currentPath:e,depth:0}];let i=0;const o=new Set;for(;r.length>0;){const e=r.shift();if(!e)break;const{folderInfo:n,currentPath:s,depth:a}=e;if(o.has(s)||a>=t.maxDepth)continue;if(o.add(s),i>=t.maxItems)continue;let l;try{l=J.readdirSync(s,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))}catch(qK){continue}const u=[],c=[];for(const r of l)if(r.isFile()){if(i>=t.maxItems){n.hasMoreFiles=!0;break}const e=r.name;if(ae.join(s,e),CT(0,e,t))continue;u.push(e),i++,n.totalFiles++,n.totalChildren++}n.files=u;for(const o of l)if(o.isDirectory()){if(i>=t.maxItems){n.hasMoreSubfolders=!0;break}const e=o.name,l=ae.join(s,e);if(CT(0,e,t)){const t={name:e,path:l,files:[],subFolders:[],totalChildren:0,totalFiles:0,isIgnored:!0};c.push(t),i++,n.totalChildren++;continue}const u={name:e,path:l,files:[],subFolders:[],totalChildren:0,totalFiles:0};c.push(u),i++,n.totalChildren++,r.push({folderInfo:u,currentPath:l,depth:a+1})}n.subFolders=c}return n}(t,n);if(!r)return`Error: Could not read directory "${t}". Check path and permissions.`;const i=[];_T(r,"",!0,!0,i);let o=`Showing up to ${n.maxItems} items (files + folders).`;return BT(r)&&(o+=` Folders or files indicated with ${wT} contain more items not shown, were ignored, or the display limit (${n.maxItems} items) was reached.`),`${o}\n\n${t}${ae.sep}\n${i.join("\n")}`}catch(qK){return`Error reading directory ${e}: ${qK instanceof Error?qK.message:String(qK)}`}}const ST=kw((e,t)=>({cachedContext:null,cacheExpiry:0,CACHE_DURATION:3e4,getEnvironmentContext:async(n=!1)=>{const r=t(),i=Date.now();if(!n&&r.cachedContext&&i<r.cacheExpiry)return r.cachedContext;const o=bT(),s=function(){const e=process.platform;return{platform:e,arch:process.arch,version:process.version,isWindows:"win32"===e,isMacOS:"darwin"===e,isLinux:"linux"===e}}(),a=function(){const e=new Date;return{date:e.toLocaleDateString(),time:e.toLocaleTimeString(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timestamp:e.getTime(),weekday:e.toLocaleDateString(void 0,{weekday:"long"}),formatted:e.toLocaleDateString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"})}}(),l=vT(o),u={workingDirectory:o,platform:s,dateTime:a,folderStructure:DT(o,{maxDepth:3,maxItems:200,showHidden:!1,respectGitIgnore:!0,respectEmbedderIgnore:!0}),projectInfo:l,userPrompt:NT()||void 0,contextGenerated:Date.now()};return e({cachedContext:u,cacheExpiry:i+r.CACHE_DURATION}),u},refreshContext:async()=>t().getEnvironmentContext(!0),getContextString:async(e=!0)=>{const n=await t().getEnvironmentContext();let r=`# Environment Context\n\n## Current Session\n- **Date**: ${n.dateTime.formatted}\n- **Time**: ${n.dateTime.time} (${n.dateTime.timezone})\n- **Platform**: ${n.platform.platform} (${n.platform.arch})\n- **Working Directory**: ${n.workingDirectory}\n\n## Project Information\n- **Type**: ${n.projectInfo.projectType}\n- **Git Repository**: ${n.projectInfo.isGitRepository?"Yes":"No"}\n- **Package.json**: ${n.projectInfo.hasPackageJson?"Yes":"No"}\n- **EMBEDDER.md**: ${n.projectInfo.hasEmbedderMd?"Yes":"No"}\n\n## Directory Structure\n\`\`\`\n${n.folderStructure}\n\`\`\``;return e&&n.userPrompt&&(r+=`\n\n## User Instructions\n${n.userPrompt}`),r},getCompactContextString:async()=>{const e=await t().getEnvironmentContext();return`Working in ${e.workingDirectory} on ${e.platform.platform}. Project type: ${e.projectInfo.projectType}. Current time: ${e.dateTime.formatted}.`},clearCache:()=>{e({cachedContext:null,cacheExpiry:0})},getFolderStructure:async e=>DT(bT(),e),isCacheValid:()=>{const e=t();return null!==e.cachedContext&&Date.now()<e.cacheExpiry},getCachedContext:()=>{const e=t();return e.cachedContext&&Date.now()<e.cacheExpiry?e.cachedContext:null}}));function kT(e=process.cwd()){return J.existsSync(ae.join(e,".git"))}let xT;function QT(){if(void 0!==xT)return xT;const e=process.cwd(),t=J.readdirSync(e).find(e=>"embedder.md"===e.toLowerCase());if(!t)return xT=null;const n=ae.join(e,t);return xT=J.readFileSync(n,"utf-8")}function NT(e=!1){const t=QT();if(!e)return t;let n=null;try{const e=ST.getState(),t=e.getCachedContext?.();t&&(n=`# Environment Context\n\n${`## Current Session\n- **Date**: ${t.dateTime.formatted}\n- **Platform**: ${t.platform.platform} (${t.platform.arch})\n- **Working Directory**: ${t.workingDirectory}\n\n## Project Information\n- **Type**: ${t.projectInfo.projectType}\n- **Git Repository**: ${t.projectInfo.isGitRepository?"Yes":"No"}\n- **Package.json**: ${t.projectInfo.hasPackageJson?"Yes":"No"}\n\n## Directory Structure\n\`\`\`\n${t.folderStructure}\n\`\`\``}\n\n---\n\nYou are an AI coding assistant working in this environment. Use the above context to understand the current working directory, project structure, and available files. You should not need to run commands like 'pwd' or 'ls' to discover basic information about the environment as it's provided above.`)}catch(qK){ex.warn("Failed to get environment context for system prompt:",qK)}return function(e,t){const n=[];return e?.trim()&&n.push(e.trim()),t?.trim()&&n.push(t.trim()),n.length>0?n.join("\n\n"):null}(t,n)}const TT=qe.createContext(null);function RT({children:e}){const[t,n]=qe.useState(!1),[r,i]=qe.useState(null),[o,s]=qe.useState(null),[a,l]=qe.useState(null),[u,c]=qe.useState(null),d=qe.useMemo(()=>async(e,t={},n={})=>{const r={"Content-Type":"application/json","User-Agent":"embedder-cli/2.0.0",...n},i=await fetch(`https://backend-service-prod.embedder.dev/${e}`,{...t,headers:r});if(!i.ok){const e=await i.text();throw new Error(`Unauth request failed: ${i.status} ${i.statusText} - ${e}`)}return i.json()},[]),p=qe.useMemo(()=>r?async(e,t={},n={},i=2)=>{let o,s=!1;for(let l=0;l<=i;l++)try{const i={Authorization:`Bearer ${await r.getIdToken(s)}`,"Content-Type":"application/json","User-Agent":"embedder-cli/2.0.0",...mT(),...n};a&&(i["x-session-id"]=a);const o=t.headers;if(o)if(Array.isArray(o))for(const[e,t]of o)i[e]=String(t);else o instanceof Headers?o.forEach((e,t)=>{i[t]=e}):Object.entries(o).forEach(([e,t])=>{null!=t&&(i[e]=String(t))});const l=await fetch(`${AT()}/${e}`,{...t,headers:i});if(!l.ok){401!==l.status&&403!==l.status||(s=!0);const e=await l.text();throw ex.error(`API request failed: ${l.status} ${l.statusText} - ${e}`),new Error(`Request failed: ${l.status} ${l.statusText} - ${e}`)}return l.json()}catch(qK){if(o=qK instanceof Error?qK:new Error(String(qK)),l<i){const e=1e3*Math.pow(2,l);await new Promise(t=>setTimeout(t,e))}}throw new Error(`Request failed after ${i+1} attempts. Path: ${e}`+(o?` Last error: ${o.message}`:""))}:null,[r,a]);qe.useEffect(()=>sT.onAuthStateChanged(async e=>{if(!e)return n(!1),i(null),s(null),l(null),void c(null);try{await pT({user:e.toJSON(),accessToken:await e.getIdToken(!0),refreshToken:e.refreshToken})}catch(qK){return void(await pT(null))}i(e)}),[]),qe.useEffect(()=>{if(!r||!p)return;if(a&&o)return;(async()=>{try{const e=await p("api/v1/users/me",{},{},1),t=await p("api/v1/users/me/billing/status",{},{},1);if("active"===t.accountStatus&&!a){const{id:t}=await p("api/v1/sessions",{method:"POST"});l(t),$.setTag("session_id",t);const n=xw.getState(),{teamId:r,projectId:i}=n.getContext(),o=QT();o?$.withScope(n=>{n.setUser({id:e.id,email:e.email,name:e.name}),n.setTag("session_id",t),n.setTag("user_id",e.id),n.setTag("event_type","session_started"),r&&n.setTag("team_id",r),i&&n.setTag("project_id",i),n.addAttachment({filename:"embedder.md",data:o,contentType:"text/markdown"}),n.setContext("embedder_config",{hasFile:!0,contentLength:o.length,preview:o.substring(0,200)+"..."}),$.captureMessage("New session started with embedder.md","info")}):$.withScope(n=>{n.setUser({id:e.id,email:e.email,name:e.name}),n.setTag("session_id",t),n.setTag("user_id",e.id),n.setTag("event_type","session_started"),r&&n.setTag("team_id",r),i&&n.setTag("project_id",i),$.captureMessage("New session started","info")})}s(e),n(!0),c(t),$.setUser({id:e.id,email:e.email,name:e.name})}catch(qK){ex.error("Error initializing backend auth:",qK),$.captureException(qK)}})()},[r,p,a,o]),qe.useEffect(()=>{const e=yT.getState();e.setApiFetch(p),e.setSessionId(a)},[p,a]);return We.jsx(TT.Provider,{value:{loggedIn:t,firebaseUser:r,backendUser:o,sessionId:a,apiFetch:p,closeSession:async(e,t,n,r)=>{if(p&&a)try{o&&$.withScope(i=>{if(i.setUser({id:o.id,email:o.email,name:o.name}),i.setTag("session_id",a),i.setTag("user_id",o.id),i.setTag("event_type","session_closed"),n?.id&&i.setTag("team_id",n.id),t?.id&&i.setTag("project_id",t.id),r&&(i.setTag("model",r.name),i.setTag("provider",r.provider)),e&&e.length>0){const s=JSON.stringify({sessionId:a,userId:o.id,timestamp:(new Date).toISOString(),team:n?{id:n.id,name:n.name}:null,project:t?{id:t.id,name:t.name}:null,model:r,messageCount:e.length,messages:e},null,2);i.addAttachment({filename:`session-${a}-chat-history.json`,data:s,contentType:"application/json"}),i.setContext("chat_history_summary",{messageCount:e.length,hasMessages:!0,dataSize:s.length}),$.captureMessage("Session closed with chat history","info")}else $.captureMessage("Session closed","info")}),await p(`api/v1/sessions/${a}/finish`,{method:"POST"})}catch(qK){ex.error("Error closing session:",qK)}},refreshBackendUser:async()=>{if(p&&o)try{const e=await p("api/v1/users/me",{},{},1);s(e)}catch(qK){ex.error("Error refreshing backend user:",qK),$.captureException(qK)}},setFirebaseUser:i,billingStatus:u,refreshBillingStatus:async()=>{if(p)try{const e=await p("api/v1/users/me/billing/status",{},{},1);c(e)}catch(qK){ex.error("Error refreshing billing status:",qK),$.captureException(qK)}},unauthFetch:d},children:e})}function FT(){const e=qe.useContext(TT);if(!e)throw new Error("useAuth must be used inside AuthProvider");return e}var MT=ug({error:ug({code:jh().nullable(),message:mh(),status:mh()})}),OT=XA({errorSchema:MT,errorToMessage:e=>e.error.message}),$T=ug({outputDimensionality:jh().optional(),taskType:_g(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}),LT=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){const i=await WA({provider:"google",providerOptions:r,schema:$T});if(e.length>this.maxEmbeddingsPerCall)throw new ns({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const o=bA(await YA(this.config.headers),t);if(1===e.length){const{responseHeaders:t,value:r,rawValue:s}=await JA({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:null==i?void 0:i.outputDimensionality,taskType:null==i?void 0:i.taskType},failedResponseHandler:OT,successfulResponseHandler:tm(jT),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:s}}}const{responseHeaders:s,value:a,rawValue:l}=await JA({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:e}]},outputDimensionality:null==i?void 0:i.outputDimensionality,taskType:null==i?void 0:i.taskType}))},failedResponseHandler:OT,successfulResponseHandler:tm(PT),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},PT=ug({embeddings:ag(ug({values:ag(jh())}))}),jT=ug({embedding:ug({values:ag(jh())})});function UT(e){if(null==e||function(e){return null!=e&&"object"==typeof e&&"object"===e.type&&(null==e.properties||0===Object.keys(e.properties).length)&&!e.additionalProperties}(e))return;if("boolean"==typeof e)return{type:"boolean",properties:{}};const{type:t,description:n,required:r,properties:i,items:o,allOf:s,anyOf:a,oneOf:l,format:u,const:c,minLength:d,enum:p}=e,f={};if(n&&(f.description=n),r&&(f.required=r),u&&(f.format=u),void 0!==c&&(f.enum=[c]),t&&(Array.isArray(t)?t.includes("null")?(f.type=t.filter(e=>"null"!==e)[0],f.nullable=!0):f.type=t:f.type="null"===t?"null":t),void 0!==p&&(f.enum=p),null!=i&&(f.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=UT(n),e),{})),o&&(f.items=Array.isArray(o)?o.map(UT):UT(o)),s&&(f.allOf=s.map(UT)),a)if(a.some(e=>"object"==typeof e&&"null"===(null==e?void 0:e.type))){const e=a.filter(e=>!("object"==typeof e&&"null"===(null==e?void 0:e.type)));if(1===e.length){const t=UT(e[0]);"object"==typeof t&&(f.nullable=!0,Object.assign(f,t))}else f.anyOf=e.map(UT),f.nullable=!0}else f.anyOf=a.map(UT);return l&&(f.oneOf=l.map(UT)),void 0!==d&&(f.minLength=d),f}function zT(e){return e.includes("/")?e:`models/${e}`}var GT=ug({responseModalities:ag(_g(["TEXT","IMAGE"])).optional(),thinkingConfig:ug({thinkingBudget:jh().optional(),includeThoughts:Hh().optional()}).optional(),cachedContent:mh().optional(),structuredOutputs:Hh().optional(),safetySettings:ag(ug({category:_g(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:_g(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:_g(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:Hh().optional(),labels:Eg(mh(),mh()).optional()});function HT({finishReason:e,hasToolCalls:t}){switch(e){case"STOP":return t?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"FINISH_REASON_UNSPECIFIED":case"OTHER":return"other";case"MALFORMED_FUNCTION_CALL":return"error";default:return"unknown"}}var WT=ug({web:ug({uri:mh(),title:mh()}).nullish(),retrievedContext:ug({uri:mh(),title:mh()}).nullish()}),qT=ug({webSearchQueries:ag(mh()).nullish(),retrievalQueries:ag(mh()).nullish(),searchEntryPoint:ug({renderedContent:mh()}).nullish(),groundingChunks:ag(WT).nullish(),groundingSupports:ag(ug({segment:ug({startIndex:jh().nullish(),endIndex:jh().nullish(),text:mh().nullish()}),segment_text:mh().nullish(),groundingChunkIndices:ag(jh()).nullish(),supportChunkIndices:ag(jh()).nullish(),confidenceScores:ag(jh()).nullish(),confidenceScore:ag(jh()).nullish()})).nullish(),retrievalMetadata:fg([ug({webDynamicRetrievalScore:jh()}),ug({})]).nullish()}),JT=ZA({id:"google.google_search",name:"google_search",inputSchema:ug({mode:_g(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:jh().default(1)})}),KT=ug({retrievedUrl:mh(),urlRetrievalStatus:mh()}),ZT=ug({urlMetadata:ag(KT)}),VT=ZA({id:"google.url_context",name:"url_context",inputSchema:ug({})}),YT=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:_A}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var f,h;const g=[],A=await WA({provider:"google",providerOptions:p,schema:GT});!0!==(null==(f=null==A?void 0:A.thinkingConfig)?void 0:f.includeThoughts)||this.config.provider.startsWith("google.vertex.")||g.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});const m=this.modelId.toLowerCase().startsWith("gemma-"),{contents:y,systemInstruction:b}=function(e,t){var n;const r=[],i=[];let o=!0;const s=null!=(n=null==t?void 0:t.isGemmaModel)&&n;for(const{role:a,content:l}of e)switch(a){case"system":if(!o)throw new ps({functionality:"system messages are only supported at the beginning of the conversation"});r.push({text:l});break;case"user":{o=!1;const e=[];for(const t of l)switch(t.type){case"text":e.push({text:t.text});break;case"file":{const n="image/*"===t.mediaType?"image/jpeg":t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:Hm(t.data)}});break}}i.push({role:"user",parts:e});break}case"assistant":o=!1,i.push({role:"model",parts:l.map(e=>{var t,n,r,i,o,s;switch(e.type){case"text":return 0===e.text.length?void 0:{text:e.text,thoughtSignature:null==(n=null==(t=e.providerOptions)?void 0:t.google)?void 0:n.thoughtSignature};case"reasoning":return 0===e.text.length?void 0:{text:e.text,thought:!0,thoughtSignature:null==(i=null==(r=e.providerOptions)?void 0:r.google)?void 0:i.thoughtSignature};case"file":if("image/png"!==e.mediaType)throw new ps({functionality:"Only PNG images are supported in assistant messages"});if(e.data instanceof URL)throw new ps({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:e.mediaType,data:Hm(e.data)}};case"tool-call":return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:null==(s=null==(o=e.providerOptions)?void 0:o.google)?void 0:s.thoughtSignature}}}).filter(e=>void 0!==e)});break;case"tool":{o=!1;const e=[];for(const t of l){const n=t.output;if("content"===n.type)for(const r of n.value)switch(r.type){case"text":e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case"media":e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:"Tool executed successfully and returned this image as a response"});break;default:e.push({text:JSON.stringify(r)})}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:"user",parts:e});break}}if(s&&r.length>0&&i.length>0&&"user"===i[0].role){const e=r.map(e=>e.text).join("\n\n");i[0].parts.unshift({text:e+"\n\n"})}return{systemInstruction:r.length>0&&!s?{parts:r}:void 0,contents:i}}(e,{isGemmaModel:m}),{tools:v,toolConfig:E,toolWarnings:I}=function({tools:e,toolChoice:t,modelId:n}){var r;e=(null==e?void 0:e.length)?e:void 0;const i=[],o=n.includes("gemini-2"),s=n.includes("gemini-1.5-flash")&&!n.includes("-8b");if(null==e)return{tools:void 0,toolConfig:void 0,toolWarnings:i};const a=e.some(e=>"function"===e.type),l=e.some(e=>"provider-defined"===e.type);if(a&&l&&i.push({type:"unsupported-tool",tool:e.find(e=>"function"===e.type),details:"Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."}),l){const t={};return e.filter(e=>"provider-defined"===e.type).forEach(e=>{switch(e.id){case"google.google_search":o?t.googleSearch={}:t.googleSearchRetrieval=s?{dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:{};break;case"google.url_context":o?t.urlContext={}:i.push({type:"unsupported-tool",tool:e,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":o?t.codeExecution={}:i.push({type:"unsupported-tool",tool:e,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;default:i.push({type:"unsupported-tool",tool:e})}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:i}}const u=[];for(const d of e)"function"===d.type?u.push({name:d.name,description:null!=(r=d.description)?r:"",parameters:UT(d.inputSchema)}):i.push({type:"unsupported-tool",tool:d});if(null==t)return{tools:{functionDeclarations:u},toolConfig:void 0,toolWarnings:i};const c=t.type;switch(c){case"auto":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:i};case"none":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:i};case"required":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:i};case"tool":return{tools:{functionDeclarations:u},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t.toolName]}},toolWarnings:i};default:throw new ps({functionality:`tool choice type: ${c}`})}}({tools:c,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:o,presencePenalty:s,stopSequences:a,seed:u,responseMimeType:"json"===(null==l?void 0:l.type)?"application/json":void 0,responseSchema:"json"!==(null==l?void 0:l.type)||null==l.schema||null!=(h=null==A?void 0:A.structuredOutputs)&&!h?void 0:UT(l.schema),...(null==A?void 0:A.audioTimestamp)&&{audioTimestamp:A.audioTimestamp},responseModalities:null==A?void 0:A.responseModalities,thinkingConfig:null==A?void 0:A.thinkingConfig},contents:y,systemInstruction:m?void 0:b,safetySettings:null==A?void 0:A.safetySettings,tools:v,toolConfig:E,cachedContent:null==A?void 0:A.cachedContent,labels:null==A?void 0:A.labels},warnings:[...g,...I]}}async doGenerate(e){var t,n,r,i,o,s,a,l,u,c,d,p;const{args:f,warnings:h}=await this.getArgs(e),g=JSON.stringify(f),A=bA(await YA(this.config.headers),e.headers),{responseHeaders:m,value:y,rawValue:b}=await JA({url:`${this.config.baseURL}/${zT(this.modelId)}:generateContent`,headers:A,body:f,failedResponseHandler:OT,successfulResponseHandler:tm(rR),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=y.candidates[0],E=[],I=null!=(n=null==(t=v.content)?void 0:t.parts)?n:[],w=y.usageMetadata;let C;for(const B of I)if("executableCode"in B&&(null==(r=B.executableCode)?void 0:r.code)){const e=this.config.generateId();C=e,E.push({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify(B.executableCode),providerExecuted:!0})}else"codeExecutionResult"in B&&B.codeExecutionResult?(E.push({type:"tool-result",toolCallId:C,toolName:"code_execution",result:{outcome:B.codeExecutionResult.outcome,output:B.codeExecutionResult.output},providerExecuted:!0}),C=void 0):"text"in B&&null!=B.text&&B.text.length>0?E.push({type:!0===B.thought?"reasoning":"text",text:B.text,providerMetadata:B.thoughtSignature?{google:{thoughtSignature:B.thoughtSignature}}:void 0}):"functionCall"in B?E.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:B.functionCall.name,input:JSON.stringify(B.functionCall.args),providerMetadata:B.thoughtSignature?{google:{thoughtSignature:B.thoughtSignature}}:void 0}):"inlineData"in B&&E.push({type:"file",data:B.inlineData.data,mediaType:B.inlineData.mimeType});const _=null!=(i=XT({groundingMetadata:v.groundingMetadata,generateId:this.config.generateId}))?i:[];for(const B of _)E.push(B);return{content:E,finishReason:HT({finishReason:v.finishReason,hasToolCalls:E.some(e=>"tool-call"===e.type)}),usage:{inputTokens:null!=(o=null==w?void 0:w.promptTokenCount)?o:void 0,outputTokens:null!=(s=null==w?void 0:w.candidatesTokenCount)?s:void 0,totalTokens:null!=(a=null==w?void 0:w.totalTokenCount)?a:void 0,reasoningTokens:null!=(l=null==w?void 0:w.thoughtsTokenCount)?l:void 0,cachedInputTokens:null!=(u=null==w?void 0:w.cachedContentTokenCount)?u:void 0},warnings:h,providerMetadata:{google:{groundingMetadata:null!=(c=v.groundingMetadata)?c:null,urlContextMetadata:null!=(d=v.urlContextMetadata)?d:null,safetyRatings:null!=(p=v.safetyRatings)?p:null,usageMetadata:null!=w?w:null}},request:{body:g},response:{headers:m,body:b}}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=bA(await YA(this.config.headers),e.headers),{responseHeaders:o,value:s}=await JA({url:`${this.config.baseURL}/${zT(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:OT,successfulResponseHandler:em(iR),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u;const c=this.config.generateId;let d=!1,p=null,f=null,h=0;const g=new Set;let A;return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,o,s,m,y,b,v,E,I,w;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const C=t.value,_=C.usageMetadata;null!=_&&(l.inputTokens=null!=(r=_.promptTokenCount)?r:void 0,l.outputTokens=null!=(i=_.candidatesTokenCount)?i:void 0,l.totalTokens=null!=(o=_.totalTokenCount)?o:void 0,l.reasoningTokens=null!=(s=_.thoughtsTokenCount)?s:void 0,l.cachedInputTokens=null!=(m=_.cachedContentTokenCount)?m:void 0);const B=null==(y=C.candidates)?void 0:y[0];if(null==B)return;const D=B.content,S=XT({groundingMetadata:B.groundingMetadata,generateId:c});if(null!=S)for(const e of S)"url"!==e.sourceType||g.has(e.url)||(g.add(e.url),n.enqueue(e));if(null!=D){const e=null!=(b=D.parts)?b:[];for(const i of e)if("executableCode"in i&&(null==(v=i.executableCode)?void 0:v.code)){const e=c();A=e,n.enqueue({type:"tool-call",toolCallId:e,toolName:"code_execution",input:JSON.stringify(i.executableCode),providerExecuted:!0}),d=!0}else if("codeExecutionResult"in i&&i.codeExecutionResult){const e=A;e&&(n.enqueue({type:"tool-result",toolCallId:e,toolName:"code_execution",result:{outcome:i.codeExecutionResult.outcome,output:i.codeExecutionResult.output},providerExecuted:!0}),A=void 0)}else"text"in i&&null!=i.text&&i.text.length>0&&(!0===i.thought?(null!==p&&(n.enqueue({type:"text-end",id:p}),p=null),null===f&&(f=String(h++),n.enqueue({type:"reasoning-start",id:f,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})),n.enqueue({type:"reasoning-delta",id:f,delta:i.text,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})):(null!==f&&(n.enqueue({type:"reasoning-end",id:f}),f=null),null===p&&(p=String(h++),n.enqueue({type:"text-start",id:p,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})),n.enqueue({type:"text-delta",id:p,delta:i.text,providerMetadata:i.thoughtSignature?{google:{thoughtSignature:i.thoughtSignature}}:void 0})));const t=function(e){return null==e?void 0:e.filter(e=>"inlineData"in e)}(D.parts);if(null!=t)for(const i of t)n.enqueue({type:"file",mediaType:i.inlineData.mimeType,data:i.inlineData.data});const r=function({parts:e,generateId:t}){const n=null==e?void 0:e.filter(e=>"functionCall"in e);return null==n||0===n.length?void 0:n.map(e=>({type:"tool-call",toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}({parts:D.parts,generateId:c});if(null!=r)for(const i of r)n.enqueue({type:"tool-input-start",id:i.toolCallId,toolName:i.toolName,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-input-delta",id:i.toolCallId,delta:i.args,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-input-end",id:i.toolCallId,providerMetadata:i.providerMetadata}),n.enqueue({type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.args,providerMetadata:i.providerMetadata}),d=!0}null!=B.finishReason&&(a=HT({finishReason:B.finishReason,hasToolCalls:d}),u={google:{groundingMetadata:null!=(E=B.groundingMetadata)?E:null,urlContextMetadata:null!=(I=B.urlContextMetadata)?I:null,safetyRatings:null!=(w=B.safetyRatings)?w:null}},null!=_&&(u.google.usageMetadata=_))},flush(e){null!==p&&e.enqueue({type:"text-end",id:p}),null!==f&&e.enqueue({type:"reasoning-end",id:f}),e.enqueue({type:"finish",finishReason:a,usage:l,providerMetadata:u})}})),response:{headers:o},request:{body:r}}}};function XT({groundingMetadata:e,generateId:t}){var n;return null==(n=null==e?void 0:e.groundingChunks)?void 0:n.filter(e=>null!=e.web).map(e=>({type:"source",sourceType:"url",id:t(),url:e.web.uri,title:e.web.title}))}var eR=ug({parts:ag(fg([ug({functionCall:ug({name:mh(),args:tg()}),thoughtSignature:mh().nullish()}),ug({inlineData:ug({mimeType:mh(),data:mh()})}),ug({executableCode:ug({language:mh(),code:mh()}).nullish(),codeExecutionResult:ug({outcome:mh(),output:mh()}).nullish(),text:mh().nullish(),thought:Hh().nullish(),thoughtSignature:mh().nullish()})])).nullish()}),tR=ug({category:mh().nullish(),probability:mh().nullish(),probabilityScore:jh().nullish(),severity:mh().nullish(),severityScore:jh().nullish(),blocked:Hh().nullish()}),nR=ug({cachedContentTokenCount:jh().nullish(),thoughtsTokenCount:jh().nullish(),promptTokenCount:jh().nullish(),candidatesTokenCount:jh().nullish(),totalTokenCount:jh().nullish()}),rR=ug({candidates:ag(ug({content:eR.nullish().or(ug({}).strict()),finishReason:mh().nullish(),safetyRatings:ag(tR).nullish(),groundingMetadata:qT.nullish(),urlContextMetadata:ZT.nullish()})),usageMetadata:nR.nullish()}),iR=ug({candidates:ag(ug({content:eR.nullish(),finishReason:mh().nullish(),safetyRatings:ag(tR).nullish(),groundingMetadata:qT.nullish(),urlContextMetadata:ZT.nullish()})).nullish(),usageMetadata:nR.nullish()}),oR={googleSearch:JT,urlContext:VT,codeExecution:VA({id:"google.code_execution",name:"code_execution",inputSchema:ug({language:mh().describe("The programming language of the code."),code:mh().describe("The code to be executed.")}),outputSchema:ug({outcome:mh().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:mh().describe("The output from the code execution.")})})},sR=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=this.settings.maxImagesPerCall)?e:4}get provider(){return this.config.provider}async doGenerate(e){var t,n,r;const{prompt:i,n:o=1,size:s="1024x1024",aspectRatio:a="1:1",seed:l,providerOptions:u,headers:c,abortSignal:d}=e,p=[];null!=s&&p.push({type:"unsupported-setting",setting:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),null!=l&&p.push({type:"unsupported-setting",setting:"seed",details:"This model does not support the `seed` option through this provider."});const f=await WA({provider:"google",providerOptions:u,schema:lR}),h=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,g={sampleCount:o};null!=a&&(g.aspectRatio=a),f&&Object.assign(g,f);const A={instances:[{prompt:i}],parameters:g},{responseHeaders:m,value:y}=await JA({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:bA(await YA(this.config.headers),c),body:A,failedResponseHandler:OT,successfulResponseHandler:tm(aR),abortSignal:d,fetch:this.config.fetch});return{images:y.predictions.map(e=>e.bytesBase64Encoded),warnings:null!=p?p:[],providerMetadata:{google:{images:y.predictions.map(e=>({}))}},response:{timestamp:h,modelId:this.modelId,headers:m}}}},aR=ug({predictions:ag(ug({bytesBase64Encoded:mh()})).default([])}),lR=ug({personGeneration:_g(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:_g(["1:1","3:4","4:3","9:16","16:9"]).nullish()});function uR(e={}){var t;const n=null!=(t=Wm(e.baseURL))?t:"https://generativelanguage.googleapis.com/v1beta",r=()=>({"x-goog-api-key":TA({apiKey:e.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...e.headers}),i=t=>{var i;return new YT(t,{provider:"google.generative-ai",baseURL:n,headers:r,generateId:null!=(i=e.generateId)?i:_A,supportedUrls:()=>({"*":[new RegExp(`^${n}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:e.fetch})},o=t=>new LT(t,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),s=(t,i={})=>new sR(t,i,{provider:"google.generative-ai",baseURL:n,headers:r,fetch:e.fetch}),a=function(e){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return i(e)};return a.languageModel=i,a.chat=i,a.generativeAI=i,a.embedding=o,a.textEmbedding=o,a.textEmbeddingModel=o,a.image=s,a.imageModel=s,a.tools=oR,a}uR();var cR=ug({error:ug({message:mh(),type:mh().nullish(),param:Xh().nullish(),code:fg([mh(),jh()]).nullish()})}),dR=XA({errorSchema:cR,errorToMessage:e=>e.error.message});function pR({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function fR(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var hR=ug({logitBias:Eg(lA(),jh()).optional(),logprobs:fg([Hh(),jh()]).optional(),parallelToolCalls:Hh().optional(),user:mh().optional(),reasoningEffort:_g(["minimal","low","medium","high"]).optional(),maxCompletionTokens:jh().optional(),store:Hh().optional(),metadata:Eg(mh().max(64),mh().max(512)).optional(),prediction:Eg(mh(),Xh()).optional(),structuredOutputs:Hh().optional(),serviceTier:_g(["auto","flex","priority"]).optional(),strictJsonSchema:Hh().optional(),textVerbosity:_g(["low","medium","high"]).optional(),promptCacheKey:mh().optional(),safetyIdentifier:mh().optional()});var gR=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var f,h,g,A;const m=[],y=null!=(f=await WA({provider:"openai",providerOptions:p,schema:hR}))?f:{},b=null==(h=y.structuredOutputs)||h;null!=i&&m.push({type:"unsupported-setting",setting:"topK"}),"json"!==(null==l?void 0:l.type)||null==l.schema||b||m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:v,warnings:E}=function({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:i,content:o}of e)switch(i){case"system":switch(t){case"system":n.push({role:"system",content:o});break;case"developer":n.push({role:"developer",content:o});break;case"remove":r.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":if(1===o.length&&"text"===o[0].type){n.push({role:"user",content:o[0].text});break}n.push({role:"user",content:o.map((e,t)=>{var n,r,i;switch(e.type){case"text":return{type:"text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"image_url",image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${Hm(e.data)}`,detail:null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.imageDetail}}}if(!e.mediaType.startsWith("audio/")){if("application/pdf"===e.mediaType){if(e.data instanceof URL)throw new ps({functionality:"PDF file parts with URLs"});return{type:"file",file:"string"==typeof e.data&&e.data.startsWith("file-")?{file_id:e.data}:{filename:null!=(i=e.filename)?i:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Hm(e.data)}`}}}throw new ps({functionality:`file part media type ${e.mediaType}`})}if(e.data instanceof URL)throw new ps({functionality:"audio file parts with URLs"});switch(e.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Hm(e.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Hm(e.data),format:"mp3"}};default:throw new ps({functionality:`audio content parts with media type ${e.mediaType}`})}}})});break;case"assistant":{let e="";const t=[];for(const n of o)switch(n.type){case"text":e+=n.text;break;case"tool-call":t.push({id:n.toolCallId,type:"function",function:{name:n.toolName,arguments:JSON.stringify(n.input)}})}n.push({role:"assistant",content:e,tool_calls:t.length>0?t:void 0});break}case"tool":for(const e of o){const t=e.output;let r;switch(t.type){case"text":case"error-text":r=t.value;break;case"content":case"json":case"error-json":r=JSON.stringify(t.value)}n.push({role:"tool",tool_call_id:e.toolCallId,content:r})}break;default:throw new Error(`Unsupported role: ${i}`)}return{messages:n,warnings:r}}({prompt:e,systemMessageMode:vR(this.modelId)});m.push(...E);const I=null!=(g=y.strictJsonSchema)&&g,w={model:this.modelId,logit_bias:y.logitBias,logprobs:!0===y.logprobs||"number"==typeof y.logprobs||void 0,top_logprobs:"number"==typeof y.logprobs?y.logprobs:"boolean"==typeof y.logprobs&&y.logprobs?0:void 0,user:y.user,parallel_tool_calls:y.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:s,response_format:"json"===(null==l?void 0:l.type)?b&&null!=l.schema?{type:"json_schema",json_schema:{schema:l.schema,strict:I,name:null!=(A=l.name)?A:"response",description:l.description}}:{type:"json_object"}:void 0,stop:a,seed:u,verbosity:y.textVerbosity,max_completion_tokens:y.maxCompletionTokens,store:y.store,metadata:y.metadata,prediction:y.prediction,reasoning_effort:y.reasoningEffort,service_tier:y.serviceTier,prompt_cache_key:y.promptCacheKey,safety_identifier:y.safetyIdentifier,messages:v};var C;bR(this.modelId)?(null!=w.temperature&&(w.temperature=void 0,m.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=w.top_p&&(w.top_p=void 0,m.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),null!=w.frequency_penalty&&(w.frequency_penalty=void 0,m.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),null!=w.presence_penalty&&(w.presence_penalty=void 0,m.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),null!=w.logit_bias&&(w.logit_bias=void 0,m.push({type:"other",message:"logitBias is not supported for reasoning models"})),null!=w.logprobs&&(w.logprobs=void 0,m.push({type:"other",message:"logprobs is not supported for reasoning models"})),null!=w.top_logprobs&&(w.top_logprobs=void 0,m.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),null!=w.max_tokens&&(null==w.max_completion_tokens&&(w.max_completion_tokens=w.max_tokens),w.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&null!=w.temperature&&(w.temperature=void 0,m.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),"flex"!==y.serviceTier||((C=this.modelId).startsWith("o3")||C.startsWith("o4-mini")||C.startsWith("gpt-5")&&!C.startsWith("gpt-5-chat"))||(m.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),w.service_tier=void 0),"priority"!==y.serviceTier||function(e){return e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini")}(this.modelId)||(m.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),w.service_tier=void 0);const{tools:_,toolChoice:B,toolWarnings:D}=function({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){const i=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:i};const o=[];for(const a of e)"function"===a.type?o.push({type:"function",function:{name:a.name,description:a.description,parameters:a.inputSchema,strict:n?r:void 0}}):i.push({type:"unsupported-tool",tool:a});if(null==t)return{tools:o,toolChoice:void 0,toolWarnings:i};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:i};case"tool":return{tools:o,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:i};default:throw new ps({functionality:`tool choice type: ${s}`})}}({tools:c,toolChoice:d,structuredOutputs:b,strictJsonSchema:I});return{args:{...w,tools:_,tool_choice:B},warnings:[...m,...D]}}async doGenerate(e){var t,n,r,i,o,s,a,l,u,c,d,p,f,h;const{args:g,warnings:A}=await this.getArgs(e),{responseHeaders:m,value:y,rawValue:b}=await JA({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:g,failedResponseHandler:dR,successfulResponseHandler:tm(mR),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=y.choices[0],E=[],I=v.message.content;null!=I&&I.length>0&&E.push({type:"text",text:I});for(const B of null!=(t=v.message.tool_calls)?t:[])E.push({type:"tool-call",toolCallId:null!=(n=B.id)?n:_A(),toolName:B.function.name,input:B.function.arguments});for(const B of null!=(r=v.message.annotations)?r:[])E.push({type:"source",sourceType:"url",id:_A(),url:B.url,title:B.title});const w=null==(i=y.usage)?void 0:i.completion_tokens_details,C=null==(o=y.usage)?void 0:o.prompt_tokens_details,_={openai:{}};return null!=(null==w?void 0:w.accepted_prediction_tokens)&&(_.openai.acceptedPredictionTokens=null==w?void 0:w.accepted_prediction_tokens),null!=(null==w?void 0:w.rejected_prediction_tokens)&&(_.openai.rejectedPredictionTokens=null==w?void 0:w.rejected_prediction_tokens),null!=(null==(s=v.logprobs)?void 0:s.content)&&(_.openai.logprobs=v.logprobs.content),{content:E,finishReason:fR(v.finish_reason),usage:{inputTokens:null!=(l=null==(a=y.usage)?void 0:a.prompt_tokens)?l:void 0,outputTokens:null!=(c=null==(u=y.usage)?void 0:u.completion_tokens)?c:void 0,totalTokens:null!=(p=null==(d=y.usage)?void 0:d.total_tokens)?p:void 0,reasoningTokens:null!=(f=null==w?void 0:w.reasoning_tokens)?f:void 0,cachedInputTokens:null!=(h=null==C?void 0:C.cached_tokens)?h:void 0},request:{body:g},response:{...pR(y),headers:m,body:b},warnings:A,providerMetadata:_}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await JA({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:r,failedResponseHandler:dR,successfulResponseHandler:em(yR),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[];let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0,c=!1;const d={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,i,o,p,f,h,g,A,m,y,b,v,E,I,w,C,_,B,D,S,k,x,Q,N;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return a="error",void n.enqueue({type:"error",error:t.error});const T=t.value;if("error"in T)return a="error",void n.enqueue({type:"error",error:T.error});u&&(u=!1,n.enqueue({type:"response-metadata",...pR(T)})),null!=T.usage&&(l.inputTokens=null!=(r=T.usage.prompt_tokens)?r:void 0,l.outputTokens=null!=(i=T.usage.completion_tokens)?i:void 0,l.totalTokens=null!=(o=T.usage.total_tokens)?o:void 0,l.reasoningTokens=null!=(f=null==(p=T.usage.completion_tokens_details)?void 0:p.reasoning_tokens)?f:void 0,l.cachedInputTokens=null!=(g=null==(h=T.usage.prompt_tokens_details)?void 0:h.cached_tokens)?g:void 0,null!=(null==(A=T.usage.completion_tokens_details)?void 0:A.accepted_prediction_tokens)&&(d.openai.acceptedPredictionTokens=null==(m=T.usage.completion_tokens_details)?void 0:m.accepted_prediction_tokens),null!=(null==(y=T.usage.completion_tokens_details)?void 0:y.rejected_prediction_tokens)&&(d.openai.rejectedPredictionTokens=null==(b=T.usage.completion_tokens_details)?void 0:b.rejected_prediction_tokens));const R=T.choices[0];if(null!=(null==R?void 0:R.finish_reason)&&(a=fR(R.finish_reason)),null!=(null==(v=null==R?void 0:R.logprobs)?void 0:v.content)&&(d.openai.logprobs=R.logprobs.content),null==(null==R?void 0:R.delta))return;const F=R.delta;if(null!=F.content&&(c||(n.enqueue({type:"text-start",id:"0"}),c=!0),n.enqueue({type:"text-delta",id:"0",delta:F.content})),null!=F.tool_calls)for(const e of F.tool_calls){const t=e.index;if(null==s[t]){if("function"!==e.type)throw new Mo({data:e,message:"Expected 'function' type."});if(null==e.id)throw new Mo({data:e,message:"Expected 'id' to be a string."});if(null==(null==(E=e.function)?void 0:E.name))throw new Mo({data:e,message:"Expected 'function.name' to be a string."});n.enqueue({type:"tool-input-start",id:e.id,toolName:e.function.name}),s[t]={id:e.id,type:"function",function:{name:e.function.name,arguments:null!=(I=e.function.arguments)?I:""},hasFinished:!1};const r=s[t];null!=(null==(w=r.function)?void 0:w.name)&&null!=(null==(C=r.function)?void 0:C.arguments)&&(r.function.arguments.length>0&&n.enqueue({type:"tool-input-delta",id:r.id,delta:r.function.arguments}),GA(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(_=r.id)?_:_A(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}const r=s[t];r.hasFinished||(null!=(null==(B=e.function)?void 0:B.arguments)&&(r.function.arguments+=null!=(S=null==(D=e.function)?void 0:D.arguments)?S:""),n.enqueue({type:"tool-input-delta",id:r.id,delta:null!=(k=e.function.arguments)?k:""}),null!=(null==(x=r.function)?void 0:x.name)&&null!=(null==(Q=r.function)?void 0:Q.arguments)&&GA(r.function.arguments)&&(n.enqueue({type:"tool-input-end",id:r.id}),n.enqueue({type:"tool-call",toolCallId:null!=(N=r.id)?N:_A(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(null!=F.annotations)for(const e of F.annotations)n.enqueue({type:"source",sourceType:"url",id:_A(),url:e.url,title:e.title})},flush(e){c&&e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:a,usage:l,...null!=d?{providerMetadata:d}:{}})}})),request:{body:r},response:{headers:i}}}},AR=ug({prompt_tokens:jh().nullish(),completion_tokens:jh().nullish(),total_tokens:jh().nullish(),prompt_tokens_details:ug({cached_tokens:jh().nullish()}).nullish(),completion_tokens_details:ug({reasoning_tokens:jh().nullish(),accepted_prediction_tokens:jh().nullish(),rejected_prediction_tokens:jh().nullish()}).nullish()}).nullish(),mR=ug({id:mh().nullish(),created:jh().nullish(),model:mh().nullish(),choices:ag(ug({message:ug({role:Dg("assistant").nullish(),content:mh().nullish(),tool_calls:ag(ug({id:mh().nullish(),type:Dg("function"),function:ug({name:mh(),arguments:mh()})})).nullish(),annotations:ag(ug({type:Dg("url_citation"),start_index:jh(),end_index:jh(),url:mh(),title:mh()})).nullish()}),index:jh(),logprobs:ug({content:ag(ug({token:mh(),logprob:jh(),top_logprobs:ag(ug({token:mh(),logprob:jh()}))})).nullish()}).nullish(),finish_reason:mh().nullish()})),usage:AR}),yR=fg([ug({id:mh().nullish(),created:jh().nullish(),model:mh().nullish(),choices:ag(ug({delta:ug({role:_g(["assistant"]).nullish(),content:mh().nullish(),tool_calls:ag(ug({index:jh(),id:mh().nullish(),type:Dg("function").nullish(),function:ug({name:mh().nullish(),arguments:mh().nullish()})})).nullish(),annotations:ag(ug({type:Dg("url_citation"),start_index:jh(),end_index:jh(),url:mh(),title:mh()})).nullish()}).nullish(),logprobs:ug({content:ag(ug({token:mh(),logprob:jh(),top_logprobs:ag(ug({token:mh(),logprob:jh()}))})).nullish()}).nullish(),finish_reason:mh().nullish(),index:jh()})),usage:AR}),cR]);function bR(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function vR(e){var t,n;return bR(e)?null!=(n=null==(t=ER[e])?void 0:t.systemMessageMode)?n:"developer":"system"}var ER={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function IR({id:e,model:t,created:n}){return{id:null!=e?e:void 0,modelId:null!=t?t:void 0,timestamp:null!=n?new Date(1e3*n):void 0}}function wR(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var CR=ug({echo:Hh().optional(),logitBias:Eg(mh(),jh()).optional(),suffix:mh().optional(),user:mh().optional(),logprobs:fg([Hh(),jh()]).optional()}),_R=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,tools:u,toolChoice:c,seed:d,providerOptions:p}){const f=[],h={...await WA({provider:"openai",providerOptions:p,schema:CR}),...await WA({provider:this.providerOptionsName,providerOptions:p,schema:CR})};null!=i&&f.push({type:"unsupported-setting",setting:"topK"}),(null==u?void 0:u.length)&&f.push({type:"unsupported-setting",setting:"tools"}),null!=c&&f.push({type:"unsupported-setting",setting:"toolChoice"}),null!=l&&"text"!==l.type&&f.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:g,stopSequences:A}=function({prompt:e,user:t="user",assistant:n="assistant"}){let r="";"system"===e[0].role&&(r+=`${e[0].content}\n\n`,e=e.slice(1));for(const{role:i,content:o}of e)switch(i){case"system":throw new Qo({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":r+=`${t}:\n${o.map(e=>{if("text"===e.type)return e.text}).filter(Boolean).join("")}\n\n`;break;case"assistant":r+=`${n}:\n${o.map(e=>{switch(e.type){case"text":return e.text;case"tool-call":throw new ps({functionality:"tool-call messages"})}}).join("")}\n\n`;break;case"tool":throw new ps({functionality:"tool messages"});default:throw new Error(`Unsupported role: ${i}`)}return r+=`${n}:\n`,{prompt:r,stopSequences:[`\n${t}:`]}}({prompt:e}),m=[...null!=A?A:[],...null!=a?a:[]];return{args:{model:this.modelId,echo:h.echo,logit_bias:h.logitBias,logprobs:!0===(null==h?void 0:h.logprobs)?0:!1===(null==h?void 0:h.logprobs)||null==h?void 0:h.logprobs,suffix:h.suffix,user:h.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:o,presence_penalty:s,seed:d,prompt:g,stop:m.length>0?m:void 0},warnings:f}}async doGenerate(e){var t,n,r;const{args:i,warnings:o}=await this.getArgs(e),{responseHeaders:s,value:a,rawValue:l}=await JA({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:i,failedResponseHandler:dR,successfulResponseHandler:tm(DR),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=a.choices[0],c={openai:{}};return null!=u.logprobs&&(c.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:null==(t=a.usage)?void 0:t.prompt_tokens,outputTokens:null==(n=a.usage)?void 0:n.completion_tokens,totalTokens:null==(r=a.usage)?void 0:r.total_tokens},finishReason:wR(u.finish_reason),request:{body:i},response:{...IR(a),headers:s,body:l},providerMetadata:c,warnings:o}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await JA({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:r,failedResponseHandler:dR,successfulResponseHandler:em(SR),abortSignal:e.abortSignal,fetch:this.config.fetch});let s="unknown";const a={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return s="error",void n.enqueue({type:"error",error:t.error});const r=t.value;if("error"in r)return s="error",void n.enqueue({type:"error",error:r.error});u&&(u=!1,n.enqueue({type:"response-metadata",...IR(r)}),n.enqueue({type:"text-start",id:"0"})),null!=r.usage&&(l.inputTokens=r.usage.prompt_tokens,l.outputTokens=r.usage.completion_tokens,l.totalTokens=r.usage.total_tokens);const i=r.choices[0];null!=(null==i?void 0:i.finish_reason)&&(s=wR(i.finish_reason)),null!=(null==i?void 0:i.logprobs)&&(a.openai.logprobs=i.logprobs),null!=(null==i?void 0:i.text)&&i.text.length>0&&n.enqueue({type:"text-delta",id:"0",delta:i.text})},flush(e){u||e.enqueue({type:"text-end",id:"0"}),e.enqueue({type:"finish",finishReason:s,providerMetadata:a,usage:l})}})),request:{body:r},response:{headers:i}}}},BR=ug({prompt_tokens:jh(),completion_tokens:jh(),total_tokens:jh()}),DR=ug({id:mh().nullish(),created:jh().nullish(),model:mh().nullish(),choices:ag(ug({text:mh(),finish_reason:mh(),logprobs:ug({tokens:ag(mh()),token_logprobs:ag(jh()),top_logprobs:ag(Eg(mh(),jh())).nullish()}).nullish()})),usage:BR.nullish()}),SR=fg([ug({id:mh().nullish(),created:jh().nullish(),model:mh().nullish(),choices:ag(ug({text:mh(),finish_reason:mh().nullish(),index:jh(),logprobs:ug({tokens:ag(mh()),token_logprobs:ag(jh()),top_logprobs:ag(Eg(mh(),jh())).nullish()}).nullish()})),usage:BR.nullish()}),cR]),kR=ug({dimensions:jh().optional(),user:mh().optional()}),xR=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var i;if(e.length>this.maxEmbeddingsPerCall)throw new ns({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const o=null!=(i=await WA({provider:"openai",providerOptions:r,schema:kR}))?i:{},{responseHeaders:s,value:a,rawValue:l}=await JA({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:bA(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:o.dimensions,user:o.user},failedResponseHandler:dR,successfulResponseHandler:tm(QR),abortSignal:n,fetch:this.config.fetch});return{embeddings:a.data.map(e=>e.embedding),usage:a.usage?{tokens:a.usage.prompt_tokens}:void 0,response:{headers:s,body:l}}}},QR=ug({data:ag(ug({embedding:ag(jh())})),usage:ug({prompt_tokens:jh()}).nullish()}),NR={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},TR=new Set(["gpt-image-1"]),RR=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return null!=(e=NR[this.modelId])?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:o,headers:s,abortSignal:a}){var l,u,c,d;const p=[];null!=r&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),null!=i&&p.push({type:"unsupported-setting",setting:"seed"});const f=null!=(c=null==(u=null==(l=this.config._internal)?void 0:l.currentDate)?void 0:u.call(l))?c:new Date,{value:h,responseHeaders:g}=await JA({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:bA(this.config.headers(),s),body:{model:this.modelId,prompt:e,n:t,size:n,...null!=(d=o.openai)?d:{},...TR.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:dR,successfulResponseHandler:tm(FR),abortSignal:a,fetch:this.config.fetch});return{images:h.data.map(e=>e.b64_json),warnings:p,response:{timestamp:f,modelId:this.modelId,headers:g},providerMetadata:{openai:{images:h.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},FR=ug({data:ag(ug({b64_json:mh(),revised_prompt:mh().optional()}))}),MR=ug({code:mh().nullish(),containerId:mh()}),OR=ug({outputs:ag(gg("type",[ug({type:Dg("logs"),logs:mh()}),ug({type:Dg("image"),url:mh()})])).nullish()}),$R=ug({container:fg([mh(),ug({fileIds:ag(mh()).optional()})]).optional()}),LR=VA({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:MR,outputSchema:OR}),PR=ug({key:mh(),type:_g(["eq","ne","gt","gte","lt","lte"]),value:fg([mh(),jh(),Hh()])}),jR=ug({type:_g(["and","or"]),filters:ag(fg([PR,Yg(()=>jR)]))}),UR=ug({vectorStoreIds:ag(mh()),maxNumResults:jh().optional(),ranking:ug({ranker:mh().optional(),scoreThreshold:jh().optional()}).optional(),filters:fg([PR,jR]).optional()}),zR=ug({queries:ag(mh()),results:ag(ug({attributes:Eg(mh(),tg()),fileId:mh(),filename:mh(),score:jh(),text:mh()})).nullable()}),GR=VA({id:"openai.file_search",name:"file_search",inputSchema:ug({}),outputSchema:zR}),HR=ug({background:_g(["auto","opaque","transparent"]).optional(),inputFidelity:_g(["low","high"]).optional(),inputImageMask:ug({fileId:mh().optional(),imageUrl:mh().optional()}).optional(),model:mh().optional(),moderation:_g(["auto"]).optional(),outputCompression:jh().int().min(0).max(100).optional(),outputFormat:_g(["png","jpeg","webp"]).optional(),quality:_g(["auto","low","medium","high"]).optional(),size:_g(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict(),WR=ug({result:mh()}),qR=VA({id:"openai.image_generation",name:"image_generation",inputSchema:ug({}),outputSchema:WR}),JR=ug({filters:ug({allowedDomains:ag(mh()).optional()}).optional(),searchContextSize:_g(["low","medium","high"]).optional(),userLocation:ug({type:Dg("approximate"),country:mh().optional(),city:mh().optional(),region:mh().optional(),timezone:mh().optional()}).optional()}),KR=ZA({id:"openai.web_search",name:"web_search",inputSchema:ug({action:gg("type",[ug({type:Dg("search"),query:mh().nullish()}),ug({type:Dg("open_page"),url:mh()}),ug({type:Dg("find"),url:mh(),pattern:mh()})]).nullish()})}),ZR=ug({searchContextSize:_g(["low","medium","high"]).optional(),userLocation:ug({type:Dg("approximate"),country:mh().optional(),city:mh().optional(),region:mh().optional(),timezone:mh().optional()}).optional()}),VR={codeInterpreter:(e={})=>LR(e),fileSearch:GR,imageGeneration:(e={})=>qR(e),webSearchPreview:ZA({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:ug({action:gg("type",[ug({type:Dg("search"),query:mh().nullish()}),ug({type:Dg("open_page"),url:mh()}),ug({type:Dg("find"),url:mh(),pattern:mh()})]).nullish()})}),webSearch:(e={})=>KR(e)};function YR(e,t){return!!t&&t.some(t=>e.startsWith(t))}var XR=ug({itemId:mh().nullish(),reasoningEncryptedContent:mh().nullish()});function eF({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var tF=ug({type:Dg("web_search_call"),id:mh(),status:mh(),action:gg("type",[ug({type:Dg("search"),query:mh().nullish()}),ug({type:Dg("open_page"),url:mh()}),ug({type:Dg("find"),url:mh(),pattern:mh()})]).nullish()}),nF=ug({type:Dg("file_search_call"),id:mh(),queries:ag(mh()),results:ag(ug({attributes:Eg(mh(),tg()),file_id:mh(),filename:mh(),score:jh(),text:mh()})).nullish()}),rF=ug({type:Dg("code_interpreter_call"),id:mh(),code:mh().nullable(),container_id:mh(),outputs:ag(gg("type",[ug({type:Dg("logs"),logs:mh()}),ug({type:Dg("image"),url:mh()})])).nullable()}),iF=ug({type:Dg("image_generation_call"),id:mh(),result:mh()}),oF=ag(ug({token:mh(),logprob:jh(),top_logprobs:ag(ug({token:mh(),logprob:jh()}))})),sF=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:o,frequencyPenalty:s,seed:a,prompt:l,providerOptions:u,tools:c,toolChoice:d,responseFormat:p}){var f,h,g,A;const m=[],y=function(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};if(e.startsWith("gpt-5-chat"))return{...r,isReasoningModel:!1};if(e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use"))return e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...r,isReasoningModel:!0,systemMessageMode:"remove"}:{...r,isReasoningModel:!0,systemMessageMode:"developer"};return{...r,isReasoningModel:!1}}(this.modelId);null!=i&&m.push({type:"unsupported-setting",setting:"topK"}),null!=a&&m.push({type:"unsupported-setting",setting:"seed"}),null!=o&&m.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=s&&m.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=n&&m.push({type:"unsupported-setting",setting:"stopSequences"});const b=await WA({provider:"openai",providerOptions:u,schema:fF}),{input:v,warnings:E}=await async function({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r}){var i,o,s,a,l,u;const c=[],d=[];for(const{role:p,content:f}of e)switch(p){case"system":switch(t){case"system":c.push({role:"system",content:f});break;case"developer":c.push({role:"developer",content:f});break;case"remove":d.push({type:"other",message:"system messages are removed for this model"});break;default:throw new Error(`Unsupported system message mode: ${t}`)}break;case"user":c.push({role:"user",content:f.map((e,t)=>{var r,i,o;switch(e.type){case"text":return{type:"input_text",text:e.text};case"file":if(e.mediaType.startsWith("image/")){const t="image/*"===e.mediaType?"image/jpeg":e.mediaType;return{type:"input_image",...e.data instanceof URL?{image_url:e.data.toString()}:"string"==typeof e.data&&YR(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Hm(e.data)}`},detail:null==(i=null==(r=e.providerOptions)?void 0:r.openai)?void 0:i.imageDetail}}if("application/pdf"===e.mediaType)return e.data instanceof URL?{type:"input_file",file_url:e.data.toString()}:{type:"input_file",..."string"==typeof e.data&&YR(e.data,n)?{file_id:e.data}:{filename:null!=(o=e.filename)?o:`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Hm(e.data)}`}};throw new ps({functionality:`file part media type ${e.mediaType}`})}})});break;case"assistant":{const e={},t={};for(const n of f)switch(n.type){case"text":c.push({role:"assistant",content:[{type:"output_text",text:n.text}],id:null!=(s=null==(o=null==(i=n.providerOptions)?void 0:i.openai)?void 0:o.itemId)?s:void 0});break;case"tool-call":if(t[n.toolCallId]=n,n.providerExecuted)break;c.push({type:"function_call",call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:null!=(u=null==(l=null==(a=n.providerOptions)?void 0:a.openai)?void 0:l.itemId)?u:void 0});break;case"tool-result":r?c.push({type:"item_reference",id:n.toolCallId}):d.push({type:"other",message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case"reasoning":{const t=await WA({provider:"openai",providerOptions:n.providerOptions,schema:XR}),r=null==t?void 0:t.itemId;if(null!=r){const i=e[r],o=[];n.text.length>0?o.push({type:"summary_text",text:n.text}):void 0!==i&&d.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),void 0===i?(e[r]={type:"reasoning",id:r,encrypted_content:null==t?void 0:t.reasoningEncryptedContent,summary:o},c.push(e[r])):i.summary.push(...o)}else d.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case"tool":for(const e of f){const t=e.output;let n;switch(t.type){case"text":case"error-text":n=t.value;break;case"content":case"json":case"error-json":n=JSON.stringify(t.value)}c.push({type:"function_call_output",call_id:e.toolCallId,output:n})}break;default:throw new Error(`Unsupported role: ${p}`)}return{input:c,warnings:d}}({prompt:l,systemMessageMode:y.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:null==(f=null==b?void 0:b.store)||f});m.push(...E);const I=null!=(h=null==b?void 0:b.strictJsonSchema)&&h;let w=null==b?void 0:b.include;function C(e){w=null!=w?[...w,e]:[e]}const _="number"==typeof(null==b?void 0:b.logprobs)?null==b?void 0:b.logprobs:!0===(null==b?void 0:b.logprobs)?20:void 0;_&&C("message.output_text.logprobs");const B=null==(g=null==c?void 0:c.find(e=>"provider-defined"===e.type&&("openai.web_search"===e.id||"openai.web_search_preview"===e.id)))?void 0:g.name;var D;B&&C("web_search_call.action.sources"),D="openai.code_interpreter",null!=(null==c?void 0:c.find(e=>"provider-defined"===e.type&&e.id===D))&&C("code_interpreter_call.outputs");const S={model:this.modelId,input:v,temperature:t,top_p:r,max_output_tokens:e,...("json"===(null==p?void 0:p.type)||(null==b?void 0:b.textVerbosity))&&{text:{..."json"===(null==p?void 0:p.type)&&{format:null!=p.schema?{type:"json_schema",strict:I,name:null!=(A=p.name)?A:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...(null==b?void 0:b.textVerbosity)&&{verbosity:b.textVerbosity}}},max_tool_calls:null==b?void 0:b.maxToolCalls,metadata:null==b?void 0:b.metadata,parallel_tool_calls:null==b?void 0:b.parallelToolCalls,previous_response_id:null==b?void 0:b.previousResponseId,store:null==b?void 0:b.store,user:null==b?void 0:b.user,instructions:null==b?void 0:b.instructions,service_tier:null==b?void 0:b.serviceTier,include:w,prompt_cache_key:null==b?void 0:b.promptCacheKey,safety_identifier:null==b?void 0:b.safetyIdentifier,top_logprobs:_,...y.isReasoningModel&&(null!=(null==b?void 0:b.reasoningEffort)||null!=(null==b?void 0:b.reasoningSummary))&&{reasoning:{...null!=(null==b?void 0:b.reasoningEffort)&&{effort:b.reasoningEffort},...null!=(null==b?void 0:b.reasoningSummary)&&{summary:b.reasoningSummary}}},...y.requiredAutoTruncation&&{truncation:"auto"}};y.isReasoningModel?(null!=S.temperature&&(S.temperature=void 0,m.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),null!=S.top_p&&(S.top_p=void 0,m.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):(null!=(null==b?void 0:b.reasoningEffort)&&m.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),null!=(null==b?void 0:b.reasoningSummary)&&m.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),"flex"!==(null==b?void 0:b.serviceTier)||y.supportsFlexProcessing||(m.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete S.service_tier),"priority"!==(null==b?void 0:b.serviceTier)||y.supportsPriorityProcessing||(m.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete S.service_tier);const{tools:k,toolChoice:x,toolWarnings:Q}=function({tools:e,toolChoice:t,strictJsonSchema:n}){const r=[];if(null==(e=(null==e?void 0:e.length)?e:void 0))return{tools:void 0,toolChoice:void 0,toolWarnings:r};const i=[];for(const s of e)switch(s.type){case"function":i.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,strict:n});break;case"provider-defined":switch(s.id){case"openai.file_search":{const e=UR.parse(s.args);i.push({type:"file_search",vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case"openai.web_search_preview":{const e=ZR.parse(s.args);i.push({type:"web_search_preview",search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.web_search":{const e=JR.parse(s.args);i.push({type:"web_search",filters:null!=e.filters?{allowed_domains:e.filters.allowedDomains}:void 0,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case"openai.code_interpreter":{const e=$R.parse(s.args);i.push({type:"code_interpreter",container:null==e.container?{type:"auto",file_ids:void 0}:"string"==typeof e.container?e.container:{type:"auto",file_ids:e.container.fileIds}});break}case"openai.image_generation":{const e=HR.parse(s.args);i.push({type:"image_generation",background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:r.push({type:"unsupported-tool",tool:s})}if(null==t)return{tools:i,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:i,toolChoice:o,toolWarnings:r};case"tool":return{tools:i,toolChoice:"code_interpreter"===t.toolName||"file_search"===t.toolName||"image_generation"===t.toolName||"web_search_preview"===t.toolName||"web_search"===t.toolName?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:throw new ps({functionality:`tool choice type: ${o}`})}}({tools:c,toolChoice:d,strictJsonSchema:I});return{webSearchToolName:B,args:{...S,tools:k,tool_choice:x},warnings:[...m,...Q]}}async doGenerate(e){var t,n,r,i,o,s,a,l,u,c,d,p,f,h,g,A,m,y,b;const{args:v,warnings:E,webSearchToolName:I}=await this.getArgs(e),w=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:C,value:_,rawValue:B}=await JA({url:w,headers:bA(this.config.headers(),e.headers),body:v,failedResponseHandler:dR,successfulResponseHandler:tm(ug({id:mh(),created_at:jh(),error:ug({code:mh(),message:mh()}).nullish(),model:mh(),output:ag(gg("type",[ug({type:Dg("message"),role:Dg("assistant"),id:mh(),content:ag(ug({type:Dg("output_text"),text:mh(),logprobs:oF.nullish(),annotations:ag(gg("type",[ug({type:Dg("url_citation"),start_index:jh(),end_index:jh(),url:mh(),title:mh()}),ug({type:Dg("file_citation"),file_id:mh(),filename:mh().nullish(),index:jh().nullish(),start_index:jh().nullish(),end_index:jh().nullish(),quote:mh().nullish()}),ug({type:Dg("container_file_citation")})]))}))}),tF,nF,rF,iF,ug({type:Dg("function_call"),call_id:mh(),name:mh(),arguments:mh(),id:mh()}),ug({type:Dg("computer_call"),id:mh(),status:mh().optional()}),ug({type:Dg("reasoning"),id:mh(),encrypted_content:mh().nullish(),summary:ag(ug({type:Dg("summary_text"),text:mh()}))})])),service_tier:mh().nullish(),incomplete_details:ug({reason:mh()}).nullable(),usage:aF})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(_.error)throw new go({message:_.error.message,url:w,requestBodyValues:v,statusCode:400,responseHeaders:C,responseBody:B,isRetryable:!1});const D=[],S=[];let k=!1;for(const Q of _.output)switch(Q.type){case"reasoning":0===Q.summary.length&&Q.summary.push({type:"summary_text",text:""});for(const e of Q.summary)D.push({type:"reasoning",text:e.text,providerMetadata:{openai:{itemId:Q.id,reasoningEncryptedContent:null!=(t=Q.encrypted_content)?t:null}}});break;case"image_generation_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:"image_generation",result:{result:Q.result},providerExecuted:!0});break;case"message":for(const t of Q.content){(null==(r=null==(n=e.providerOptions)?void 0:n.openai)?void 0:r.logprobs)&&t.logprobs&&S.push(t.logprobs),D.push({type:"text",text:t.text,providerMetadata:{openai:{itemId:Q.id}}});for(const e of t.annotations)"url_citation"===e.type?D.push({type:"source",sourceType:"url",id:null!=(s=null==(o=(i=this.config).generateId)?void 0:o.call(i))?s:_A(),url:e.url,title:e.title}):"file_citation"===e.type&&D.push({type:"source",sourceType:"document",id:null!=(u=null==(l=(a=this.config).generateId)?void 0:l.call(a))?u:_A(),mediaType:"text/plain",title:null!=(d=null!=(c=e.quote)?c:e.filename)?d:"Document",filename:null!=(p=e.filename)?p:e.file_id})}break;case"function_call":k=!0,D.push({type:"tool-call",toolCallId:Q.call_id,toolName:Q.name,input:Q.arguments,providerMetadata:{openai:{itemId:Q.id}}});break;case"web_search_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:null!=I?I:"web_search",input:JSON.stringify({action:Q.action}),providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:null!=I?I:"web_search",result:{status:Q.status},providerExecuted:!0});break;case"computer_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:"computer_use",input:"",providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:Q.status||"completed"},providerExecuted:!0});break;case"file_search_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:"file_search",input:"{}",providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:"file_search",result:{queries:Q.queries,results:null!=(h=null==(f=Q.results)?void 0:f.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text})))?h:null},providerExecuted:!0});break;case"code_interpreter_call":D.push({type:"tool-call",toolCallId:Q.id,toolName:"code_interpreter",input:JSON.stringify({code:Q.code,containerId:Q.container_id}),providerExecuted:!0}),D.push({type:"tool-result",toolCallId:Q.id,toolName:"code_interpreter",result:{outputs:Q.outputs},providerExecuted:!0})}const x={openai:{responseId:_.id}};return S.length>0&&(x.openai.logprobs=S),"string"==typeof _.service_tier&&(x.openai.serviceTier=_.service_tier),{content:D,finishReason:eF({finishReason:null==(g=_.incomplete_details)?void 0:g.reason,hasFunctionCall:k}),usage:{inputTokens:_.usage.input_tokens,outputTokens:_.usage.output_tokens,totalTokens:_.usage.input_tokens+_.usage.output_tokens,reasoningTokens:null!=(m=null==(A=_.usage.output_tokens_details)?void 0:A.reasoning_tokens)?m:void 0,cachedInputTokens:null!=(b=null==(y=_.usage.input_tokens_details)?void 0:y.cached_tokens)?b:void 0},request:{body:v},response:{id:_.id,timestamp:new Date(1e3*_.created_at),modelId:_.model,headers:C,body:B},providerMetadata:x,warnings:E}}async doStream(e){const{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:o}=await JA({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:dR,successfulResponseHandler:em(cF),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=this;let a="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=[];let c=null;const d={};let p=!1;const f={};let h;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var i,o,g,A,m,y,b,v,E,I,w,C,_,B,D,S,k,x,Q,N,T,R,F;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return a="error",void n.enqueue({type:"error",error:t.error});const M=t.value;if(pF(M))"function_call"===M.item.type?(d[M.output_index]={toolName:M.item.name,toolCallId:M.item.call_id},n.enqueue({type:"tool-input-start",id:M.item.call_id,toolName:M.item.name})):"web_search_call"===M.item.type?(d[M.output_index]={toolName:null!=r?r:"web_search",toolCallId:M.item.id},n.enqueue({type:"tool-input-start",id:M.item.id,toolName:null!=r?r:"web_search"})):"computer_call"===M.item.type?(d[M.output_index]={toolName:"computer_use",toolCallId:M.item.id},n.enqueue({type:"tool-input-start",id:M.item.id,toolName:"computer_use"})):"file_search_call"===M.item.type?n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):"image_generation_call"===M.item.type?n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):"message"===M.item.type?n.enqueue({type:"text-start",id:M.item.id,providerMetadata:{openai:{itemId:M.item.id}}}):function(e){return pF(e)&&"reasoning"===e.item.type}(M)&&(f[M.item.id]={encryptedContent:M.item.encrypted_content,summaryParts:[0]},n.enqueue({type:"reasoning-start",id:`${M.item.id}:0`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:null!=(i=M.item.encrypted_content)?i:null}}}));else if(dF(M)){if("function_call"===M.item.type)d[M.output_index]=void 0,p=!0,n.enqueue({type:"tool-input-end",id:M.item.call_id}),n.enqueue({type:"tool-call",toolCallId:M.item.call_id,toolName:M.item.name,input:M.item.arguments,providerMetadata:{openai:{itemId:M.item.id}}});else if("web_search_call"===M.item.type)d[M.output_index]=void 0,n.enqueue({type:"tool-input-end",id:M.item.id}),n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"web_search",input:JSON.stringify({action:M.item.action}),providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"web_search",result:{status:M.item.status},providerExecuted:!0});else if("computer_call"===M.item.type)d[M.output_index]=void 0,n.enqueue({type:"tool-input-end",id:M.item.id}),n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:M.item.status||"completed"},providerExecuted:!0});else if("file_search_call"===M.item.type)d[M.output_index]=void 0,n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"file_search",result:{queries:M.item.queries,results:null!=(g=null==(o=M.item.results)?void 0:o.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text})))?g:null},providerExecuted:!0});else if("code_interpreter_call"===M.item.type)n.enqueue({type:"tool-call",toolCallId:M.item.id,toolName:"code_interpreter",input:JSON.stringify({code:M.item.code,containerId:M.item.container_id}),providerExecuted:!0}),n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"code_interpreter",result:{outputs:M.item.outputs},providerExecuted:!0});else if("image_generation_call"===M.item.type)n.enqueue({type:"tool-result",toolCallId:M.item.id,toolName:"image_generation",result:{result:M.item.result},providerExecuted:!0});else if("message"===M.item.type)n.enqueue({type:"text-end",id:M.item.id});else if(function(e){return dF(e)&&"reasoning"===e.item.type}(M)){const e=f[M.item.id];for(const t of e.summaryParts)n.enqueue({type:"reasoning-end",id:`${M.item.id}:${t}`,providerMetadata:{openai:{itemId:M.item.id,reasoningEncryptedContent:null!=(A=M.item.encrypted_content)?A:null}}});delete f[M.item.id]}}else if(function(e){return"response.function_call_arguments.delta"===e.type}(M)){const e=d[M.output_index];null!=e&&n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:M.delta})}else!function(e){return"response.created"===e.type}(M)?!function(e){return"response.output_text.delta"===e.type}(M)?!function(e){return"response.reasoning_summary_part.added"===e.type}(M)?!function(e){return"response.reasoning_summary_text.delta"===e.type}(M)?!function(e){return"response.completed"===e.type||"response.incomplete"===e.type}(M)?!function(e){return"response.output_text.annotation.added"===e.type}(M)?function(e){return"error"===e.type}(M)&&n.enqueue({type:"error",error:M}):"url_citation"===M.annotation.type?n.enqueue({type:"source",sourceType:"url",id:null!=(k=null==(S=(D=s.config).generateId)?void 0:S.call(D))?k:_A(),url:M.annotation.url,title:M.annotation.title}):"file_citation"===M.annotation.type&&n.enqueue({type:"source",sourceType:"document",id:null!=(N=null==(Q=(x=s.config).generateId)?void 0:Q.call(x))?N:_A(),mediaType:"text/plain",title:null!=(R=null!=(T=M.annotation.quote)?T:M.annotation.filename)?R:"Document",filename:null!=(F=M.annotation.filename)?F:M.annotation.file_id}):(a=eF({finishReason:null==(I=M.response.incomplete_details)?void 0:I.reason,hasFunctionCall:p}),l.inputTokens=M.response.usage.input_tokens,l.outputTokens=M.response.usage.output_tokens,l.totalTokens=M.response.usage.input_tokens+M.response.usage.output_tokens,l.reasoningTokens=null!=(C=null==(w=M.response.usage.output_tokens_details)?void 0:w.reasoning_tokens)?C:void 0,l.cachedInputTokens=null!=(B=null==(_=M.response.usage.input_tokens_details)?void 0:_.cached_tokens)?B:void 0,"string"==typeof M.response.service_tier&&(h=M.response.service_tier)):n.enqueue({type:"reasoning-delta",id:`${M.item_id}:${M.summary_index}`,delta:M.delta,providerMetadata:{openai:{itemId:M.item_id}}}):M.summary_index>0&&(null==(b=f[M.item_id])||b.summaryParts.push(M.summary_index),n.enqueue({type:"reasoning-start",id:`${M.item_id}:${M.summary_index}`,providerMetadata:{openai:{itemId:M.item_id,reasoningEncryptedContent:null!=(E=null==(v=f[M.item_id])?void 0:v.encryptedContent)?E:null}}})):(n.enqueue({type:"text-delta",id:M.item_id,delta:M.delta}),(null==(y=null==(m=e.providerOptions)?void 0:m.openai)?void 0:y.logprobs)&&M.logprobs&&u.push(M.logprobs)):(c=M.response.id,n.enqueue({type:"response-metadata",id:M.response.id,timestamp:new Date(1e3*M.response.created_at),modelId:M.response.model}))},flush(e){const t={openai:{responseId:c}};u.length>0&&(t.openai.logprobs=u),void 0!==h&&(t.openai.serviceTier=h),e.enqueue({type:"finish",finishReason:a,usage:l,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},aF=ug({input_tokens:jh(),input_tokens_details:ug({cached_tokens:jh().nullish()}).nullish(),output_tokens:jh(),output_tokens_details:ug({reasoning_tokens:jh().nullish()}).nullish()}),lF=ug({type:Dg("response.output_text.delta"),item_id:mh(),delta:mh(),logprobs:oF.nullish()}),uF=ug({type:Dg("error"),code:mh(),message:mh(),param:mh().nullish(),sequence_number:jh()}),cF=fg([lF,ug({type:_g(["response.completed","response.incomplete"]),response:ug({incomplete_details:ug({reason:mh()}).nullish(),usage:aF,service_tier:mh().nullish()})}),ug({type:Dg("response.created"),response:ug({id:mh(),created_at:jh(),model:mh(),service_tier:mh().nullish()})}),ug({type:Dg("response.output_item.added"),output_index:jh(),item:gg("type",[ug({type:Dg("message"),id:mh()}),ug({type:Dg("reasoning"),id:mh(),encrypted_content:mh().nullish()}),ug({type:Dg("function_call"),id:mh(),call_id:mh(),name:mh(),arguments:mh()}),ug({type:Dg("web_search_call"),id:mh(),status:mh(),action:ug({type:Dg("search"),query:mh().optional()}).nullish()}),ug({type:Dg("computer_call"),id:mh(),status:mh()}),ug({type:Dg("file_search_call"),id:mh()}),ug({type:Dg("image_generation_call"),id:mh()})])}),ug({type:Dg("response.output_item.done"),output_index:jh(),item:gg("type",[ug({type:Dg("message"),id:mh()}),ug({type:Dg("reasoning"),id:mh(),encrypted_content:mh().nullish()}),ug({type:Dg("function_call"),id:mh(),call_id:mh(),name:mh(),arguments:mh(),status:Dg("completed")}),rF,iF,tF,nF,ug({type:Dg("computer_call"),id:mh(),status:Dg("completed")})])}),ug({type:Dg("response.function_call_arguments.delta"),item_id:mh(),output_index:jh(),delta:mh()}),ug({type:Dg("response.output_text.annotation.added"),annotation:gg("type",[ug({type:Dg("url_citation"),url:mh(),title:mh()}),ug({type:Dg("file_citation"),file_id:mh(),filename:mh().nullish(),index:jh().nullish(),start_index:jh().nullish(),end_index:jh().nullish(),quote:mh().nullish()})])}),ug({type:Dg("response.reasoning_summary_part.added"),item_id:mh(),summary_index:jh()}),ug({type:Dg("response.reasoning_summary_text.delta"),item_id:mh(),summary_index:jh(),delta:mh()}),uF,ug({type:mh()}).loose()]);function dF(e){return"response.output_item.done"===e.type}function pF(e){return"response.output_item.added"===e.type}var fF=ug({include:ag(_g(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:mh().nullish(),logprobs:fg([Hh(),jh().min(1).max(20)]).optional(),maxToolCalls:jh().nullish(),metadata:Xh().nullish(),parallelToolCalls:Hh().nullish(),previousResponseId:mh().nullish(),promptCacheKey:mh().nullish(),reasoningEffort:mh().nullish(),reasoningSummary:mh().nullish(),safetyIdentifier:mh().nullish(),serviceTier:_g(["auto","flex","priority"]).nullish(),store:Hh().nullish(),strictJsonSchema:Hh().nullish(),textVerbosity:_g(["low","medium","high"]).nullish(),user:mh().nullish()}),hF=ug({instructions:mh().nullish(),speed:jh().min(.25).max(4).default(1).nullish()}),gF=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:i,language:o,providerOptions:s}){const a=[],l=await WA({provider:"openai",providerOptions:s,schema:hF}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:i};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?u.response_format=n:a.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const e={};for(const t in e){const n=e[t];void 0!==n&&(u[t]=n)}}return o&&a.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:u,warnings:a}}async doGenerate(e){var t,n,r;const i=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{requestBody:o,warnings:s}=await this.getArgs(e),{value:a,responseHeaders:l,rawValue:u}=await JA({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),body:o,failedResponseHandler:dR,successfulResponseHandler:async({response:e,url:t,requestBodyValues:n})=>{const r=EA(e);if(!e.body)throw new go({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(qK){throw new go({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:qK})}},abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:s,request:{body:JSON.stringify(o)},response:{timestamp:i,modelId:this.modelId,headers:l,body:u}}}},AF=ug({include:ag(mh()).optional(),language:mh().optional(),prompt:mh().optional(),temperature:jh().min(0).max(1).default(0).optional(),timestampGranularities:ag(_g(["word","segment"])).default(["segment"]).optional()}),mF={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},yF=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=await WA({provider:"openai",providerOptions:n,schema:AF}),i=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([zm(e)]);i.append("model",this.modelId);const s=function(e){var t;const[n,r=""]=e.toLowerCase().split("/");return null!=(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])?t:r}(t);if(i.append("file",new File([o],"audio",{type:t}),`audio.${s}`),r){const e={include:r.include,language:r.language,prompt:r.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:r.temperature,timestamp_granularities:r.timestampGranularities};for(const[t,n]of Object.entries(e))if(null!=n)if(Array.isArray(n))for(const e of n)i.append(`${t}[]`,String(e));else i.append(t,String(n))}return{formData:i,warnings:[]}}async doGenerate(e){var t,n,r,i,o,s,a,l;const u=null!=(r=null==(n=null==(t=this.config._internal)?void 0:t.currentDate)?void 0:n.call(t))?r:new Date,{formData:c,warnings:d}=await this.getArgs(e),{value:p,responseHeaders:f,rawValue:h}=await(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s})=>KA({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:o,fetch:s}))({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:bA(this.config.headers(),e.headers),formData:c,failedResponseHandler:dR,successfulResponseHandler:tm(bF),abortSignal:e.abortSignal,fetch:this.config.fetch}),g=null!=p.language&&p.language in mF?mF[p.language]:void 0;return{text:p.text,segments:null!=(a=null!=(s=null==(i=p.segments)?void 0:i.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end})))?s:null==(o=p.words)?void 0:o.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end})))?a:[],language:g,durationInSeconds:null!=(l=p.duration)?l:void 0,warnings:d,response:{timestamp:u,modelId:this.modelId,headers:f,body:h}}}},bF=ug({text:mh(),language:mh().nullish(),duration:jh().nullish(),words:ag(ug({word:mh(),start:jh(),end:jh()})).nullish(),segments:ag(ug({id:jh(),seek:jh(),start:jh(),end:jh(),text:mh(),tokens:ag(jh()),temperature:jh(),avg_logprob:jh(),compression_ratio:jh(),no_speech_prob:jh()})).nullish()});function vF(e={}){var t,n;const r=null!=(t=Wm(e.baseURL))?t:"https://api.openai.com/v1",i=null!=(n=e.name)?n:"openai",o=()=>({Authorization:`Bearer ${TA({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),s=t=>new xR(t,{provider:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),a=t=>new RR(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),l=t=>new yF(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),u=t=>new gF(t,{provider:`${i}.speech`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),c=e=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(e)},d=t=>new sF(t,{provider:`${i}.responses`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch,fileIdPrefixes:["file-"]}),p=function(e){return c(e)};return p.languageModel=c,p.chat=t=>new gR(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),p.completion=t=>new _R(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:o,fetch:e.fetch}),p.responses=d,p.embedding=s,p.textEmbedding=s,p.textEmbeddingModel=s,p.image=a,p.imageModel=a,p.transcription=l,p.transcriptionModel=l,p.speech=u,p.speechModel=u,p.tools=VR,p}function EF(){const{getEnvironmentContext:e,getContextString:t,getCompactContextString:n,refreshContext:r,clearCache:i}=ST(),[o,s]=qe.useState(null),[a,l]=qe.useState(null),[u,c]=qe.useState(null),[d,p]=qe.useState(!0),[f,h]=qe.useState(null),g=qe.useCallback(async(r=!1)=>{try{p(!0),h(null);const[i,o,a]=await Promise.all([e(r),t(),n()]);s(i),l(o),c(a)}catch(i){const e=i instanceof Error?i.message:"Failed to load environment context";h(e),ex.error("Environment context error:",i)}finally{p(!1)}},[e,t,n]),A=qe.useCallback(async()=>{await r(),await g(!0)},[r,g]);return qe.useEffect(()=>{g()},[g]),qe.useEffect(()=>{const e=setInterval(()=>{d||g()},3e5);return()=>clearInterval(e)},[g,d]),{context:o,contextString:a,compactContext:u,isLoading:d,error:f,refresh:A,clearCache:i}}vF();var IF=ug({type:Dg("error"),error:ug({type:mh(),message:mh()})}),wF=XA({errorSchema:IF,errorToMessage:e=>e.error.message}),CF=ug({citations:ug({enabled:Hh()}).optional(),title:mh().optional(),context:mh().optional()}),_F=ug({sendReasoning:Hh().optional(),thinking:ug({type:fg([Dg("enabled"),Dg("disabled")]),budgetTokens:jh().optional()}).optional(),disableParallelToolUse:Hh().optional(),cacheControl:ug({type:Dg("ephemeral"),ttl:fg([Dg("5m"),Dg("1h")]).optional()}).optional()});function BF(e){var t;const n=null==e?void 0:e.anthropic;return null!=(t=null==n?void 0:n.cacheControl)?t:null==n?void 0:n.cache_control}var DF=ug({maxUses:jh().optional(),allowedDomains:ag(mh()).optional(),blockedDomains:ag(mh()).optional(),userLocation:ug({type:Dg("approximate"),city:mh().optional(),region:mh().optional(),country:mh().optional(),timezone:mh().optional()}).optional()}),SF=ag(ug({url:mh(),title:mh(),pageAge:mh().nullable(),encryptedContent:mh(),type:mh()})),kF=VA({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:ug({query:mh()}),outputSchema:SF});function xF(e){return"object"==typeof e&&null!==e&&"type"in e&&"web_search_20250305"===e.type}var QF=ug({type:Dg("code_execution_result"),stdout:mh(),stderr:mh(),return_code:jh()}),NF=VA({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:ug({code:mh()}),outputSchema:QF});function TF(e){if("string"==typeof e)return Buffer.from(e,"base64").toString("utf-8");if(e instanceof Uint8Array)return(new TextDecoder).decode(e);if(e instanceof URL)throw new ps({functionality:"URL-based text documents are not supported for citations"});throw new ps({functionality:"unsupported data type for text documents: "+typeof e})}async function RF({prompt:e,sendReasoning:t,warnings:n}){var r,i,o,s,a;const l=new Set,u=function(e){const t=[];let n;for(const r of e){const{role:e}=r;switch(e){case"system":"system"!==(null==n?void 0:n.type)&&(n={type:"system",messages:[]},t.push(n)),n.messages.push(r);break;case"assistant":"assistant"!==(null==n?void 0:n.type)&&(n={type:"assistant",messages:[]},t.push(n)),n.messages.push(r);break;case"user":case"tool":"user"!==(null==n?void 0:n.type)&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break;default:throw new Error(`Unsupported role: ${e}`)}}return t}(e);let c;const d=[];async function p(e){var t,n;const r=await WA({provider:"anthropic",providerOptions:e,schema:CF});return null!=(n=null==(t=null==r?void 0:r.citations)?void 0:t.enabled)&&n}async function f(e){const t=await WA({provider:"anthropic",providerOptions:e,schema:CF});return{title:null==t?void 0:t.title,context:null==t?void 0:t.context}}for(let h=0;h<u.length;h++){const e=u[h],g=h===u.length-1,A=e.type;switch(A){case"system":if(null!=c)throw new ps({functionality:"Multiple system messages that are separated by user/assistant messages"});c=e.messages.map(({content:e,providerOptions:t})=>({type:"text",text:e,cache_control:BF(t)}));break;case"user":{const t=[];for(const n of e.messages){const{role:e,content:a}=n;switch(e){case"user":for(let e=0;e<a.length;e++){const s=a[e],u=e===a.length-1,c=null!=(r=BF(s.providerOptions))?r:u?BF(n.providerOptions):void 0;switch(s.type){case"text":t.push({type:"text",text:s.text,cache_control:c});break;case"file":if(s.mediaType.startsWith("image/"))t.push({type:"image",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"image/*"===s.mediaType?"image/jpeg":s.mediaType,data:Hm(s.data)},cache_control:c});else if("application/pdf"===s.mediaType){l.add("pdfs-2024-09-25");const e=await p(s.providerOptions),n=await f(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"base64",media_type:"application/pdf",data:Hm(s.data)},title:null!=(i=n.title)?i:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}else{if("text/plain"!==s.mediaType)throw new ps({functionality:`media type: ${s.mediaType}`});{const e=await p(s.providerOptions),n=await f(s.providerOptions);t.push({type:"document",source:s.data instanceof URL?{type:"url",url:s.data.toString()}:{type:"text",media_type:"text/plain",data:TF(s.data)},title:null!=(o=n.title)?o:s.filename,...n.context&&{context:n.context},...e&&{citations:{enabled:!0}},cache_control:c})}}}}break;case"tool":for(let e=0;e<a.length;e++){const r=a[e],i=e===a.length-1,o=null!=(s=BF(r.providerOptions))?s:i?BF(n.providerOptions):void 0,l=r.output;let u;switch(l.type){case"content":u=l.value.map(e=>{switch(e.type){case"text":return{type:"text",text:e.text,cache_control:void 0};case"media":if(e.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:e.mediaType,data:e.data},cache_control:void 0};throw new ps({functionality:`media type: ${e.mediaType}`})}});break;case"text":case"error-text":u=l.value;break;default:u=JSON.stringify(l.value)}t.push({type:"tool_result",tool_use_id:r.toolCallId,content:u,is_error:"error-text"===l.type||"error-json"===l.type||void 0,cache_control:o})}break;default:throw new Error(`Unsupported role: ${e}`)}}d.push({role:"user",content:t});break}case"assistant":{const r=[];for(let i=0;i<e.messages.length;i++){const o=e.messages[i],s=i===e.messages.length-1,{content:l}=o;for(let e=0;e<l.length;e++){const i=l[e],u=e===l.length-1,c=null!=(a=BF(i.providerOptions))?a:u?BF(o.providerOptions):void 0;switch(i.type){case"text":r.push({type:"text",text:g&&s&&u?i.text.trim():i.text,cache_control:c});break;case"reasoning":if(t){const e=await WA({provider:"anthropic",providerOptions:i.providerOptions,schema:UF});null!=e?null!=e.signature?r.push({type:"thinking",thinking:i.text,signature:e.signature,cache_control:c}):null!=e.redactedData?r.push({type:"redacted_thinking",data:e.redactedData,cache_control:c}):n.push({type:"other",message:"unsupported reasoning metadata"}):n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break;case"tool-call":if(i.providerExecuted){if("web_search"===i.toolName){r.push({type:"server_tool_use",id:i.toolCallId,name:"web_search",input:i.input,cache_control:c});break}if("code_execution"===i.toolName){r.push({type:"server_tool_use",id:i.toolCallId,name:"code_execution",input:i.input,cache_control:c});break}n.push({type:"other",message:`provider executed tool call for tool ${i.toolName} is not supported`});break}r.push({type:"tool_use",id:i.toolCallId,name:i.toolName,input:i.input,cache_control:c});break;case"tool-result":if("web_search"===i.toolName){const e=i.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${i.toolName} is not supported`});break}const t=SF.parse(e.value);r.push({type:"web_search_tool_result",tool_use_id:i.toolCallId,content:t.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:c});break}if("code_execution"===i.toolName){const e=i.output;if("json"!==e.type){n.push({type:"other",message:`provider executed tool result output type ${e.type} for tool ${i.toolName} is not supported`});break}const t=QF.parse(e.value);r.push({type:"code_execution_tool_result",tool_use_id:i.toolCallId,content:{type:t.type,stdout:t.stdout,stderr:t.stderr,return_code:t.return_code},cache_control:c});break}n.push({type:"other",message:`provider executed tool result for tool ${i.toolName} is not supported`})}}}d.push({role:"assistant",content:r});break}default:throw new Error(`content type: ${A}`)}}return{prompt:{system:c,messages:d},betas:l}}function FF({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}var MF={webSearchResult:ug({type:Dg("web_search_result_location"),cited_text:mh(),url:mh(),title:mh(),encrypted_index:mh()}),pageLocation:ug({type:Dg("page_location"),cited_text:mh(),document_index:jh(),document_title:mh().nullable(),start_page_number:jh(),end_page_number:jh()}),charLocation:ug({type:Dg("char_location"),cited_text:mh(),document_index:jh(),document_title:mh().nullable(),start_char_index:jh(),end_char_index:jh()})},OF=gg("type",[MF.webSearchResult,MF.pageLocation,MF.charLocation]);function $F(e,t,n,r){if("page_location"===e.type||"char_location"===e.type){const i=function(e,t,n){var r;const i=t[e.document_index];if(!i)return null;const o="page_location"===e.type?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:"source",sourceType:"document",id:n(),mediaType:i.mediaType,title:null!=(r=e.document_title)?r:i.title,filename:i.filename,providerMetadata:{anthropic:o}}}(e,t,n);i&&r(i)}}gg("type",[MF.pageLocation,MF.charLocation]);var LF=class{constructor(e,t){var n;this.specificationVersion="v2",this.modelId=e,this.config=t,this.generateId=null!=(n=t.generateId)?n:_A}supportsUrl(e){return"https:"===e.protocol}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return null!=(n=null==(t=(e=this.config).supportedUrls)?void 0:t.call(e))?n:{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:o,presencePenalty:s,stopSequences:a,responseFormat:l,seed:u,tools:c,toolChoice:d,providerOptions:p}){var f,h,g;const A=[];null!=o&&A.push({type:"unsupported-setting",setting:"frequencyPenalty"}),null!=s&&A.push({type:"unsupported-setting",setting:"presencePenalty"}),null!=u&&A.push({type:"unsupported-setting",setting:"seed"}),"json"===(null==l?void 0:l.type)&&(null==l.schema?A.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):null!=c&&A.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));const m="json"===(null==l?void 0:l.type)&&null!=l.schema?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:l.schema}:void 0,y=await WA({provider:"anthropic",providerOptions:p,schema:_F}),{prompt:b,betas:v}=await RF({prompt:e,sendReasoning:null==(f=null==y?void 0:y.sendReasoning)||f,warnings:A}),E="enabled"===(null==(h=null==y?void 0:y.thinking)?void 0:h.type),I=null==(g=null==y?void 0:y.thinking)?void 0:g.budgetTokens,w={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:a,...E&&{thinking:{type:"enabled",budget_tokens:I}},system:b.system,messages:b.messages};if(E){if(null==I)throw new ps({functionality:"thinking requires a budget"});null!=w.temperature&&(w.temperature=void 0,A.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),null!=i&&(w.top_k=void 0,A.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),null!=r&&(w.top_p=void 0,A.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),w.max_tokens=t+I}const{tools:C,toolChoice:_,toolWarnings:B,betas:D}=function({tools:e,toolChoice:t,disableParallelToolUse:n}){e=(null==e?void 0:e.length)?e:void 0;const r=[],i=new Set;if(null==e)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};const o=[];for(const a of e)if(xF(a))o.push(a);else switch(a.type){case"function":const e=BF(a.providerOptions);o.push({name:a.name,description:a.description,input_schema:a.inputSchema,cache_control:e});break;case"provider-defined":switch(a.id){case"anthropic.computer_20250124":i.add("computer-use-2025-01-24"),o.push({name:"computer",type:"computer_20250124",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.computer_20241022":i.add("computer-use-2024-10-22"),o.push({name:"computer",type:"computer_20241022",display_width_px:a.args.displayWidthPx,display_height_px:a.args.displayHeightPx,display_number:a.args.displayNumber});break;case"anthropic.text_editor_20250124":i.add("computer-use-2025-01-24"),o.push({name:"str_replace_editor",type:"text_editor_20250124"});break;case"anthropic.text_editor_20241022":i.add("computer-use-2024-10-22"),o.push({name:"str_replace_editor",type:"text_editor_20241022"});break;case"anthropic.text_editor_20250429":i.add("computer-use-2025-01-24"),o.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429"});break;case"anthropic.bash_20250124":i.add("computer-use-2025-01-24"),o.push({name:"bash",type:"bash_20250124"});break;case"anthropic.bash_20241022":i.add("computer-use-2024-10-22"),o.push({name:"bash",type:"bash_20241022"});break;case"anthropic.web_search_20250305":{const e=DF.parse(a.args);o.push({type:"web_search_20250305",name:"web_search",max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}case"anthropic.code_execution_20250522":i.add("code-execution-2025-05-22"),o.push({type:"code_execution_20250522",name:"code_execution"});break;default:r.push({type:"unsupported-tool",tool:a})}break;default:r.push({type:"unsupported-tool",tool:a})}if(null==t)return{tools:o,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};const s=t.type;switch(s){case"auto":return{tools:o,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:r,betas:i};case"required":return{tools:o,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:r,betas:i};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case"tool":return{tools:o,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new ps({functionality:`tool choice type: ${s}`})}}(null!=m?{tools:[m],toolChoice:{type:"tool",toolName:m.name},disableParallelToolUse:!0}:{tools:null!=c?c:[],toolChoice:d,disableParallelToolUse:null==y?void 0:y.disableParallelToolUse});return{args:{...w,tools:C,tool_choice:_},warnings:[...A,...B],betas:new Set([...v,...D]),usesJsonResponseTool:null!=m}}async getHeaders({betas:e,headers:t}){return bA(await YA(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{},t)}buildRequestUrl(e){var t,n,r;return null!=(r=null==(n=(t=this.config).buildRequestUrl)?void 0:n.call(t,this.config.baseURL,e))?r:`${this.config.baseURL}/messages`}transformRequestBody(e){var t,n,r;return null!=(r=null==(n=(t=this.config).transformRequestBody)?void 0:n.call(t,e))?r:e}extractCitationDocuments(e){return e.filter(e=>"user"===e.role).flatMap(e=>e.content).filter(e=>{var t,n;if("file"!==e.type)return!1;if("application/pdf"!==e.mediaType&&"text/plain"!==e.mediaType)return!1;const r=null==(t=e.providerOptions)?void 0:t.anthropic,i=null==r?void 0:r.citations;return null!=(n=null==i?void 0:i.enabled)&&n}).map(e=>{var t;const n=e;return{title:null!=(t=n.filename)?t:"Untitled Document",filename:n.filename,mediaType:n.mediaType}})}async doGenerate(e){var t,n,r,i,o;const{args:s,warnings:a,betas:l,usesJsonResponseTool:u}=await this.getArgs(e),c=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:p,rawValue:f}=await JA({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:l,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:wF,successfulResponseHandler:tm(PF),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=[];for(const g of p.content)switch(g.type){case"text":if(!u&&(h.push({type:"text",text:g.text}),g.citations))for(const e of g.citations)$F(e,c,this.generateId,e=>h.push(e));break;case"thinking":h.push({type:"reasoning",text:g.thinking,providerMetadata:{anthropic:{signature:g.signature}}});break;case"redacted_thinking":h.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:g.data}}});break;case"tool_use":h.push(u?{type:"text",text:JSON.stringify(g.input)}:{type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input)});break;case"server_tool_use":"web_search"!==g.name&&"code_execution"!==g.name||h.push({type:"tool-call",toolCallId:g.id,toolName:g.name,input:JSON.stringify(g.input),providerExecuted:!0});break;case"web_search_tool_result":if(Array.isArray(g.content)){h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",result:g.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}}),providerExecuted:!0});for(const e of g.content)h.push({type:"source",sourceType:"url",id:this.generateId(),url:e.url,title:e.title,providerMetadata:{anthropic:{pageAge:null!=(t=e.page_age)?t:null}}})}else h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0});break;case"code_execution_tool_result":"code_execution_result"===g.content.type?h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",result:{type:g.content.type,stdout:g.content.stdout,stderr:g.content.stderr,return_code:g.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===g.content.type&&h.push({type:"tool-result",toolCallId:g.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:g.content.error_code},providerExecuted:!0})}return{content:h,finishReason:FF({finishReason:p.stop_reason,isJsonResponseFromTool:u}),usage:{inputTokens:p.usage.input_tokens,outputTokens:p.usage.output_tokens,totalTokens:p.usage.input_tokens+p.usage.output_tokens,cachedInputTokens:null!=(n=p.usage.cache_read_input_tokens)?n:void 0},request:{body:s},response:{id:null!=(r=p.id)?r:void 0,modelId:null!=(i=p.model)?i:void 0,headers:d,body:f},warnings:a,providerMetadata:{anthropic:{usage:p.usage,cacheCreationInputTokens:null!=(o=p.usage.cache_creation_input_tokens)?o:null}}}}async doStream(e){const{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),s={...t,stream:!0},{responseHeaders:a,value:l}=await JA({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:wF,successfulResponseHandler:em(jF),abortSignal:e.abortSignal,fetch:this.config.fetch});let u="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={};let p,f;const h=this.generateId;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:"stream-start",warnings:n})},transform(t,n){var r,s,a,l,g,A,m;if(e.includeRawChunks&&n.enqueue({type:"raw",rawValue:t.rawValue}),!t.success)return void n.enqueue({type:"error",error:t.error});const y=t.value;switch(y.type){case"ping":return;case"content_block_start":{const e=y.content_block.type;switch(f=e,e){case"text":return d[y.index]={type:"text"},void n.enqueue({type:"text-start",id:String(y.index)});case"thinking":return d[y.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(y.index)});case"redacted_thinking":return d[y.index]={type:"reasoning"},void n.enqueue({type:"reasoning-start",id:String(y.index),providerMetadata:{anthropic:{redactedData:y.content_block.data}}});case"tool_use":return d[y.index]=i?{type:"text"}:{type:"tool-call",toolCallId:y.content_block.id,toolName:y.content_block.name,input:""},void n.enqueue(i?{type:"text-start",id:String(y.index)}:{type:"tool-input-start",id:y.content_block.id,toolName:y.content_block.name});case"server_tool_use":return void("web_search"!==y.content_block.name&&"code_execution"!==y.content_block.name||(d[y.index]={type:"tool-call",toolCallId:y.content_block.id,toolName:y.content_block.name,input:"",providerExecuted:!0},n.enqueue({type:"tool-input-start",id:y.content_block.id,toolName:y.content_block.name,providerExecuted:!0})));case"web_search_tool_result":{const e=y.content_block;if(Array.isArray(e.content)){n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:null!=(t=e.page_age)?t:null,encryptedContent:e.encrypted_content,type:e.type}}),providerExecuted:!0});for(const t of e.content)n.enqueue({type:"source",sourceType:"url",id:h(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:null!=(r=t.page_age)?r:null}}})}else n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{const e=y.content_block;return void("code_execution_result"===e.content.type?n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):"code_execution_tool_result_error"===e.content.type&&n.enqueue({type:"tool-result",toolCallId:e.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:e.content.error_code},providerExecuted:!0}))}default:throw new Error(`Unsupported content block type: ${e}`)}}case"content_block_stop":if(null!=d[y.index]){const e=d[y.index];switch(e.type){case"text":n.enqueue({type:"text-end",id:String(y.index)});break;case"reasoning":n.enqueue({type:"reasoning-end",id:String(y.index)});break;case"tool-call":i||(n.enqueue({type:"tool-input-end",id:e.toolCallId}),n.enqueue(e))}delete d[y.index]}return void(f=void 0);case"content_block_delta":{const e=y.delta.type;switch(e){case"text_delta":if(i)return;return void n.enqueue({type:"text-delta",id:String(y.index),delta:y.delta.text});case"thinking_delta":return void n.enqueue({type:"reasoning-delta",id:String(y.index),delta:y.delta.thinking});case"signature_delta":return void("thinking"===f&&n.enqueue({type:"reasoning-delta",id:String(y.index),delta:"",providerMetadata:{anthropic:{signature:y.delta.signature}}}));case"input_json_delta":{const e=d[y.index],t=y.delta.partial_json;if(i){if("text"!==(null==e?void 0:e.type))return;n.enqueue({type:"text-delta",id:String(y.index),delta:t})}else{if("tool-call"!==(null==e?void 0:e.type))return;n.enqueue({type:"tool-input-delta",id:e.toolCallId,delta:t}),e.input+=t}return}case"citations_delta":return void $F(y.delta.citation,o,h,e=>n.enqueue(e));default:throw new Error(`Unsupported delta type: ${e}`)}}case"message_start":return c.inputTokens=y.message.usage.input_tokens,c.cachedInputTokens=null!=(s=y.message.usage.cache_read_input_tokens)?s:void 0,p={anthropic:{usage:y.message.usage,cacheCreationInputTokens:null!=(a=y.message.usage.cache_creation_input_tokens)?a:null}},void n.enqueue({type:"response-metadata",id:null!=(l=y.message.id)?l:void 0,modelId:null!=(g=y.message.model)?g:void 0});case"message_delta":return c.outputTokens=y.usage.output_tokens,c.totalTokens=(null!=(A=c.inputTokens)?A:0)+(null!=(m=y.usage.output_tokens)?m:0),void(u=FF({finishReason:y.delta.stop_reason,isJsonResponseFromTool:i}));case"message_stop":return void n.enqueue({type:"finish",finishReason:u,usage:c,providerMetadata:p});case"error":return void n.enqueue({type:"error",error:y.error});default:throw new Error(`Unsupported chunk type: ${y}`)}}})),request:{body:s},response:{headers:a}}}},PF=ug({type:Dg("message"),id:mh().nullish(),model:mh().nullish(),content:ag(gg("type",[ug({type:Dg("text"),text:mh(),citations:ag(OF).optional()}),ug({type:Dg("thinking"),thinking:mh(),signature:mh()}),ug({type:Dg("redacted_thinking"),data:mh()}),ug({type:Dg("tool_use"),id:mh(),name:mh(),input:tg()}),ug({type:Dg("server_tool_use"),id:mh(),name:mh(),input:Eg(mh(),tg()).nullish()}),ug({type:Dg("web_search_tool_result"),tool_use_id:mh(),content:fg([ag(ug({type:Dg("web_search_result"),url:mh(),title:mh(),encrypted_content:mh(),page_age:mh().nullish()})),ug({type:Dg("web_search_tool_result_error"),error_code:mh()})])}),ug({type:Dg("code_execution_tool_result"),tool_use_id:mh(),content:fg([ug({type:Dg("code_execution_result"),stdout:mh(),stderr:mh(),return_code:jh()}),ug({type:Dg("code_execution_tool_result_error"),error_code:mh()})])})])),stop_reason:mh().nullish(),usage:dg({input_tokens:jh(),output_tokens:jh(),cache_creation_input_tokens:jh().nullish(),cache_read_input_tokens:jh().nullish()})}),jF=gg("type",[ug({type:Dg("message_start"),message:ug({id:mh().nullish(),model:mh().nullish(),usage:dg({input_tokens:jh(),output_tokens:jh(),cache_creation_input_tokens:jh().nullish(),cache_read_input_tokens:jh().nullish()})})}),ug({type:Dg("content_block_start"),index:jh(),content_block:gg("type",[ug({type:Dg("text"),text:mh()}),ug({type:Dg("thinking"),thinking:mh()}),ug({type:Dg("tool_use"),id:mh(),name:mh()}),ug({type:Dg("redacted_thinking"),data:mh()}),ug({type:Dg("server_tool_use"),id:mh(),name:mh(),input:Eg(mh(),tg()).nullish()}),ug({type:Dg("web_search_tool_result"),tool_use_id:mh(),content:fg([ag(ug({type:Dg("web_search_result"),url:mh(),title:mh(),encrypted_content:mh(),page_age:mh().nullish()})),ug({type:Dg("web_search_tool_result_error"),error_code:mh()})])}),ug({type:Dg("code_execution_tool_result"),tool_use_id:mh(),content:fg([ug({type:Dg("code_execution_result"),stdout:mh(),stderr:mh(),return_code:jh()}),ug({type:Dg("code_execution_tool_result_error"),error_code:mh()})])})])}),ug({type:Dg("content_block_delta"),index:jh(),delta:gg("type",[ug({type:Dg("input_json_delta"),partial_json:mh()}),ug({type:Dg("text_delta"),text:mh()}),ug({type:Dg("thinking_delta"),thinking:mh()}),ug({type:Dg("signature_delta"),signature:mh()}),ug({type:Dg("citations_delta"),citation:OF})])}),ug({type:Dg("content_block_stop"),index:jh()}),ug({type:Dg("error"),error:ug({type:mh(),message:mh()})}),ug({type:Dg("message_delta"),delta:ug({stop_reason:mh().nullish()}),usage:ug({output_tokens:jh()})}),ug({type:Dg("message_stop")}),ug({type:Dg("ping")})]),UF=ug({signature:mh().optional(),redactedData:mh().optional()}),zF={bash_20241022:ZA({id:"anthropic.bash_20241022",name:"bash",inputSchema:cA.object({command:cA.string(),restart:cA.boolean().optional()})}),bash_20250124:ZA({id:"anthropic.bash_20250124",name:"bash",inputSchema:cA.object({command:cA.string(),restart:cA.boolean().optional()})}),codeExecution_20250522:(e={})=>NF(e),computer_20241022:ZA({id:"anthropic.computer_20241022",name:"computer",inputSchema:ug({action:_g(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:ag(jh().int()).optional(),text:mh().optional()})}),computer_20250124:ZA({id:"anthropic.computer_20250124",name:"computer",inputSchema:ug({action:_g(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:bg([jh().int(),jh().int()]).optional(),duration:jh().optional(),scroll_amount:jh().optional(),scroll_direction:_g(["up","down","left","right"]).optional(),start_coordinate:bg([jh().int(),jh().int()]).optional(),text:mh().optional()})}),textEditor_20241022:ZA({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:ug({command:_g(["view","create","str_replace","insert","undo_edit"]),path:mh(),file_text:mh().optional(),insert_line:jh().int().optional(),new_str:mh().optional(),old_str:mh().optional(),view_range:ag(jh().int()).optional()})}),textEditor_20250124:ZA({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:ug({command:_g(["view","create","str_replace","insert","undo_edit"]),path:mh(),file_text:mh().optional(),insert_line:jh().int().optional(),new_str:mh().optional(),old_str:mh().optional(),view_range:ag(jh().int()).optional()})}),textEditor_20250429:ZA({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:ug({command:_g(["view","create","str_replace","insert"]),path:mh(),file_text:mh().optional(),insert_line:jh().int().optional(),new_str:mh().optional(),old_str:mh().optional(),view_range:ag(jh().int()).optional()})}),webSearch_20250305:(e={})=>kF(e)};function GF(e={}){var t;const n=null!=(t=Wm(e.baseURL))?t:"https://api.anthropic.com/v1",r=()=>({"anthropic-version":"2023-06-01","x-api-key":TA({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...e.headers}),i=t=>{var i;return new LF(t,{provider:"anthropic.messages",baseURL:n,headers:r,fetch:e.fetch,generateId:null!=(i=e.generateId)?i:_A,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},o=function(e){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(e)};return o.languageModel=i,o.chat=i,o.messages=i,o.textEmbeddingModel=e=>{throw new Vo({modelId:e,modelType:"textEmbeddingModel"})},o.imageModel=e=>{throw new Vo({modelId:e,modelType:"imageModel"})},o.tools=zF,o}GF();const HF={plan:{name:"PLAN",description:"Analysis and planning without making changes",color:"#3B82F6",allowToolExecution:!1,systemPromptAddition:"You are currently in PLAN mode. Focus on analysis, planning, and suggesting approaches without executing tools or making changes. Break down complex tasks, explain your reasoning, and provide detailed implementation strategies."},act:{name:"ACT",description:"Full execution with tool access",color:"#10B981",allowToolExecution:!0,systemPromptAddition:"You are currently in ACT mode. You have full access to tools and can execute changes, run commands, and modify files as needed to complete tasks."}},WF=qe.createContext(null);function qF({children:e}){const[t,n]=qe.useState("act"),r=HF[t],i=qe.useCallback(()=>{n(e=>"plan"===e?"act":"plan")},[]),o=qe.useCallback(e=>{n(e)},[]),s=r.allowToolExecution;return We.jsx(WF.Provider,{value:{currentMode:t,modeConfig:r,switchMode:i,setMode:o,isToolExecutionAllowed:s},children:e})}function JF(){const e=qe.useContext(WF);if(!e)throw new Error("useMode must be used inside ModeProvider");return e}const KF=qe.createContext(void 0),ZF=({children:e})=>{const{context:t}=EF(),{sessionId:n,firebaseUser:r}=FT(),{currentMode:i}=JF(),[o,s]=qe.useState({"x-platform-type":process.platform,"x-sandbox-type":"sandbox-exec"===process.env.SANDBOX?"exec":null!=process.env.SANDBOX?"generic":"none","x-folder-type":kT()?"versioned":"unversioned","x-client-type":"cli"}),[a,l]=qe.useState([]),[u,c]=qe.useState(null),[d,p]=qe.useState(null);qe.useEffect(()=>{if(!r)return;(async()=>{const e=await r.getIdToken();s(r=>({...r,...n?{"x-session-id":n}:{},Authorization:`Bearer ${e}`,"x-agent-mode":i,...t?{"x-working-directory":t.workingDirectory,"x-project-type":t.projectInfo.projectType,"x-has-git":t.projectInfo.isGitRepository.toString(),"x-context-timestamp":t.contextGenerated.toString()}:{}}))})()},[r,n,t,i]);const f=qe.useMemo(()=>function(e,{separator:t=":",languageModelMiddleware:n}={}){const r=new wI({separator:t,languageModelMiddleware:n});for(const[i,o]of Object.entries(e))r.registerProvider({id:i,provider:o});return r}({anthropic:GF({baseURL:"https://backend-service-prod.embedder.dev/api/v1/proxy/anthropic/",apiKey:"embedder-cli",headers:o}),openai:vF({baseURL:"https://backend-service-prod.embedder.dev/api/v1/proxy/openai/",apiKey:"embedder-cli",headers:o}),google:uR({baseURL:"https://backend-service-prod.embedder.dev/api/v1/proxy/google/",apiKey:"embedder-cli",headers:o})},{separator:" > "}),[o]);return qe.useEffect(()=>{p(u?f.languageModel(`${u.provider} > ${u.name}`):null)},[u,f]),We.jsx(KF.Provider,{value:{registry:f,languageModel:d,availableModels:a,selectedModel:u,setAvailableModels:l,setSelectedModel:c,setHeaders:s,headers:o},children:e})},VF=()=>{const e=qe.useContext(KF);if(!e)throw new Error("useAI must be used within AIProvider");return e};function YF(e){const[t,n]=qe.useState(null),[r,i]=qe.useState(null),[o,s]=qe.useState([]),[a,l]=qe.useState([]),[u,c]=qe.useState(!0),[d,p]=qe.useState(null),[f,h]=qe.useState(null),{setHeaders:g}=VF(),{loggedIn:A,backendUser:m,apiFetch:y}=FT(),{setAvailableModels:b,setSelectedModel:v}=VF(),{setContext:E}=xw(),{fetchDocuments:I,clear:w}=tx();qe.useEffect(()=>{if(!A||!m||!y)return;let t=!1;return(async()=>{try{const r=y(`api/v1/users/${m.id}/teams`),o=y("api/v1/models"),[a,u]=await Promise.all([r,o]);if(t)return;if(!a||!u)return void e("Failed to fetch user data");if(s(a),b(u),u.length>0){const e=(()=>{if(!K(uT))return null;try{const e=V(uT,"utf8");return JSON.parse(e)}catch{return null}})(),t=e&&u.find(t=>t.provider===e.provider&&t.name===e.name)||u[0];v(t)}const d=await Promise.all(a.map(e=>y(`api/v1/teams/${e.id}/projects`)));if(t)return;const p=d.filter(e=>Array.isArray(e)).flat();l(p);let f=null,h=null;if(1===a.length&&null!=a[0]&&(f=a[0]),1===p.length&&(h=p[0],f||(f=a.find(e=>e.id===h?.teamId)||null)),!f||!h){const e=(e=>{if(!K(cT))return null;try{const t=V(cT,"utf8");return JSON.parse(t)[e]||null}catch{return null}})(process.cwd());if(e){const t=a.find(t=>t.id===e.teamId),n=p.find(t=>t.id===e.projectId);t&&n&&n.teamId===t.id&&(f=t,h=n)}}f&&n(f),h&&i(h),c(!1)}catch(qK){t||(e("Failed to fetch user data"),$.captureException(qK))}})(),()=>{t=!0}},[A,m,y,b,e,v]),qe.useEffect(()=>{E(t?.id||null,r?.id||null),g(e=>({...e,"x-project-id":r?.id||""})),r?.id&&y?I(r.id,y):w()},[t,r,E,y,I,w]),qe.useEffect(()=>{if(t&&r)try{gT(process.cwd(),t.id,r.id)}catch(qK){ex.warn("Failed to cache workspace selection:",qK)}},[t,r]);return{team:t,setTeam:n,project:r,setProject:i,teams:o,setTeams:s,projects:a,setProjects:l,createProject:async(n,r=!1)=>{if(!y||!t)return;const o=new AbortController,s=setTimeout(()=>o.abort(),6e4);try{const s=await y("api/v1/projects",{method:"POST",body:JSON.stringify({name:n,teamId:t.id}),signal:o.signal});if(!s)return void e("Failed to create project");l(e=>[...e,s]),r&&i(s)}catch(qK){ex.error("Error creating project:",qK),e("Failed to create project")}finally{clearTimeout(s)}},loading:u,previousProject:d,setPreviousProject:p,previousTeam:f,setPreviousTeam:h}}function XF(e){const t=function(e){const t=v.resolve(e);return he.createHash("sha256").update(t).digest("hex").substring(0,16)}(e);return v.join(G.homedir(),".embedder","conversations",t)}function eM(e){return v.join(XF(e),"active.json")}function tM(e){return v.join(XF(e),"index.json")}function nM(e,t){const n=t.replace(/[^a-zA-Z0-9-_]/g,"_");return v.join(XF(e),`${n}.json`)}const rM={};function iM(e){return rM[e]||[]}function oM(e,t){rM[e]=t}const sM={"gpt-5-2025-08-07":{providerID:"openai",modelID:"gpt-5-2025-08-07",limits:{context:4e5,output:128e3},compressionThreshold:.9},"claude-opus-4-20250514":{providerID:"anthropic",modelID:"claude-opus-4-20250514",limits:{context:2e5,output:32e3},compressionThreshold:.9},"claude-sonnet-4-20250514":{providerID:"anthropic",modelID:"claude-sonnet-4-20250514",limits:{context:2e5,output:64e3},compressionThreshold:.9},"claude-sonnet-4-5-20250929":{providerID:"anthropic",modelID:"claude-sonnet-4-5-20250929",limits:{context:2e5,output:64e3},compressionThreshold:.9},"claude-haiku-4-5-20251001":{providerID:"anthropic",modelID:"claude-haiku-4-5-20251001",limits:{context:2e5,output:8192},compressionThreshold:.9},"gemini-2.5-pro":{providerID:"google",modelID:"gemini-2.5-pro",limits:{context:1048576,output:65536},compressionThreshold:.9},"gemini-2.5-flash":{providerID:"google",modelID:"gemini-2.5-flash",limits:{context:1048576,output:65536},compressionThreshold:.9}};function aM(e){return sM[e]||null}function lM(e,t){const n=function(e){const t=Math.min(e.limits.output,32e3),n=e.limits.context-t;return Math.max(n*e.compressionThreshold,0)}(t);return e>n}function uM(e){return{providerID:e||"unknown",modelID:"unknown",limits:{context:8192,output:2048},compressionThreshold:.7}}function cM(e){if(e.includes(":")){const t=e.split(":");return(t[1]??t[0]??"").toString()}return e.includes("/")&&e.split("/").pop()||e}function dM(e,t){const n=Math.min(t.limits.output,32e3),r=t.limits.context-n;return Math.min(100,Math.round(e/r*100))}const pM=10,fM=15,hM=8,gM=20,AM=25;function mM(e){if(!e)return 0;const t=Math.ceil(e.length/4);return t+Math.ceil(.1*t)}function yM(e){if("role"in e&&"tool-group"!==e.role){const n=e,r="string"==typeof(t=n.content)?mM(t):Array.isArray(t)?t.reduce((e,t)=>{if("string"==typeof t)return e+mM(t);if("object"==typeof t&&null!==t){const n=t.text||t.content||"",r=t.type||"";let i=mM(n);return"image"===r||"image_url"===r?i+=85:"tool_use"!==r&&"tool_result"!==r||(i+=AM),e+i}return e},0):0;let i=0;switch(n.role){case"user":default:i=pM;break;case"assistant":i=fM;break;case"system":i=hM}return r+i}var t;if("role"in e&&"tool-group"===e.role){const t=e;let n=gM;for(const e of t.toolGroup.tools)n+=AM,n+=mM(e.name),n+=mM(e.description),e.result&&("string"==typeof e.result?n+=mM(e.result):"object"==typeof e.result&&(n+=mM(JSON.stringify(e.result))));return n}return 0}function bM(e){return e.reduce((e,t)=>e+yM(t),0)}class vM{static compressionStates=new Map;static shouldCompressMessages(e,t){const n=aM(cM(t.modelId||t.name))||uM(t.provider);return lM(bM(e),n)}static isCompressing(e){return this.compressionStates.has(e)}static async compressConversation(e,t,n,r,i=!1){if(this.isCompressing(t))return{success:!1,originalTokenCount:0,newTokenCount:0,compressedMessages:e,error:"Compression already in progress for this session"};if(!i&&!this.shouldCompressMessages(e,n)){const t=bM(e);return{success:!1,originalTokenCount:t,newTokenCount:t,compressedMessages:e,error:"Compression not needed"}}this.compressionStates.set(t,{isCompressing:!0,sessionId:t,startTime:Date.now()});try{const n=bM(e),{messagesToCompress:i,preservedMessages:o}=this.identifyMessagesToCompress(e);if(0===i.length)return{success:!1,originalTokenCount:n,newTokenCount:n,compressedMessages:e,error:"No messages to compress"};const s=await this.generateSummary(i,r),a=this.createCompressedMessages(o,s,t);return{success:!0,originalTokenCount:n,newTokenCount:bM(a),compressedMessages:a}}catch(qK){return{success:!1,originalTokenCount:bM(e),newTokenCount:bM(e),compressedMessages:e,error:qK instanceof Error?qK.message:String(qK)}}finally{this.compressionStates.delete(t)}}static identifyMessagesToCompress(e){let t=-1;for(let o=e.length-1;o>=0;o--){const n=e[o];if(n&&("role"in n&&"assistant"===n.role&&this.isSummaryMessage(n))){t=o;break}}if(-1===t){const t=Math.min(3,Math.floor(.2*e.length)),n=e.length-t;return{messagesToCompress:e.slice(0,n),preservedMessages:e.slice(n)}}const n=t+1,r=Math.min(2,Math.floor(.15*(e.length-n))),i=e.length-r;return{messagesToCompress:e.slice(n,i),preservedMessages:[...e.slice(0,t+1),...e.slice(i)]}}static isSummaryMessage(e){if("string"==typeof e.content){const t=e.content.toLowerCase();return t.includes("summary:")||t.includes("## summary")||t.includes("conversation summary")||t.includes("context summary")}return!1}static async generateSummary(e,t){const n=this.messagesToText(e);try{const e=await fI({model:t,system:'You are a conversation summarizer. Your task is to create a concise but comprehensive summary of the conversation history while preserving all important context, decisions, and technical details.\n\nIMPORTANT GUIDELINES:\n1. Preserve all technical information, code snippets, and specific implementation details\n2. Maintain the chronological flow of the conversation\n3. Include all key decisions, problems solved, and solutions implemented\n4. Preserve file names, function names, and specific technical references\n5. Keep important error messages and their resolutions\n6. Maintain the context needed for future conversation continuity\n7. Start your summary with "## Conversation Summary" and be detailed but concise\n\nThe summary will replace this conversation history, so ensure no critical information is lost.',messages:[{role:"user",content:`Please summarize the following conversation history:\n\n${n}`}],maxOutputTokens:2048});let r="";for await(const t of e.textStream)r+=t;return r}catch(qK){throw new Error(`Failed to generate summary: ${qK instanceof Error?qK.message:String(qK)}`)}}static messagesToText(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n];if(null!=r)if("role"in r&&"tool-group"!==r.role){const e=r,n=this.extractTextContent(e.content);t.push(`${e.role.toUpperCase()}: ${n}`)}else if("role"in r&&"tool-group"===r.role){const e=r;for(const n of e.toolGroup.tools)if(t.push(`TOOL: ${n.name} - ${n.description}`),n.result){const e="string"==typeof n.result?n.result:JSON.stringify(n.result,null,2);t.push(`TOOL_RESULT: ${e}`)}}}return t.join("\n\n")}static extractTextContent(e){return"string"==typeof e?e:Array.isArray(e)?e.map(e=>"string"==typeof e?e:"object"==typeof e&&null!==e?e.text||e.content||JSON.stringify(e):String(e)).join(" "):String(e)}static createCompressedMessages(e,t,n){const r={role:"assistant",content:t,timestamp:Date.now(),hidden:!1};let i=0;for(let s=0;s<e.length;s++){const t=e[s];if(t){if(!("role"in t)||"system"!==t.role)break;i=s+1}}const o=[...e];return o.splice(i,0,r),o}static getCompressionStats(){const e=Date.now();return{activeCompressions:this.compressionStates.size,compressionStates:Array.from(this.compressionStates.values()).map(t=>({sessionId:t.sessionId,duration:e-t.startTime}))}}static cleanupStaleCompressions(e=3e5){const t=Date.now();for(const[n,r]of this.compressionStates.entries())t-r.startTime>e&&(ex.warn(`Cleaning up stale compression for session ${n}`),this.compressionStates.delete(n))}}class EM{projectRoot;conversationDir=null;initialized=!1;constructor(e=process.cwd()){this.projectRoot=e}async initialize(){if(!this.initialized)try{this.projectRoot=await async function(e=process.cwd()){let t=v.resolve(e);const n=v.parse(t).root;for(;t!==n;){const e=[".git","package.json","Cargo.toml","pyproject.toml","requirements.txt","Makefile",".embedder"];for(const r of e){const e=v.join(t,r);try{return await c.access(e),t}catch{}}const n=v.dirname(t);if(n===t)break;t=n}return e}(this.projectRoot),this.conversationDir=await async function(e){const t=XF(e);return await c.mkdir(t,{recursive:!0}),t}(this.projectRoot),this.initialized=!0}catch(qK){this.initialized=!1,ex.error("Failed to initialize conversation persistence service",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0,projectRoot:this.projectRoot})}}async saveActiveConversation(e,t,n,r){if(this.initialized||await this.initialize(),this.initialized)try{const i=iM("active"),o=this.createSnapshot(e,t,n,void 0,i,void 0,r),s=eM(this.projectRoot);await this.writeSnapshotToFile(s,o),await this.updateConversationIndex(o)}catch(qK){ex.error("Failed to save active conversation",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0})}else ex.warn("Cannot save active conversation: service not initialized")}async restoreActiveConversation(){if(this.initialized||await this.initialize(),!this.initialized)return ex.warn("Cannot restore active conversation: service not initialized"),null;try{const e=eM(this.projectRoot),t=await this.readSnapshotFromFile(e);if(t)return t.todos&&oM("active",t.todos),{messages:this.snapshotToMessages(t),trackedFiles:t.trackedFiles}}catch(qK){ex.debug("No active conversation found to restore",{error:qK instanceof Error?qK.message:String(qK)})}return null}async clearActiveConversation(){if(this.initialized||await this.initialize(),this.initialized)try{const e=eM(this.projectRoot);await c.unlink(e)}catch(qK){}}async saveNamedConversation(e,t,n,r,i){if(this.initialized||await this.initialize(),this.initialized)try{const o=iM("active"),s=this.createSnapshot(t,n,r,e,o,void 0,i),a=nM(this.projectRoot,e);await this.writeSnapshotToFile(a,s),await this.updateConversationIndex(s)}catch(qK){ex.error("Failed to save named conversation",{name:e,error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0})}else ex.warn("Cannot save named conversation: service not initialized",{name:e})}async loadNamedConversation(e){if(this.initialized||await this.initialize(),!this.initialized)return ex.warn("Cannot load named conversation: service not initialized",{name:e}),null;try{const t=nM(this.projectRoot,e),n=await this.readSnapshotFromFile(t);if(n)return n.todos&&oM("active",n.todos),this.snapshotToMessages(n)}catch(qK){ex.error("Failed to load named conversation",{name:e,error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0})}return null}async listConversations(){if(this.initialized||await this.initialize(),!this.initialized)return ex.warn("Cannot list conversations: service not initialized"),[];try{return(await this.readConversationIndex()).conversations.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(qK){return ex.error("Failed to list conversations",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0}),[]}}createSnapshot(e,t,n,r,i,o,s){const a=(new Date).toISOString(),l=Date.now(),u=this.messagesToUIMessagesWithOrder(e,l),c=this.extractToolGroupsWithOrder(e,l);let d;o&&(d={isCompressed:o.success,lastCompression:a,originalTokenCount:o.originalTokenCount,compressedTokenCount:o.newTokenCount,compressionHistory:[{timestamp:a,originalTokens:o.originalTokenCount,compressedTokens:o.newTokenCount,compressionRatio:o.newTokenCount/o.originalTokenCount}]});return{id:r||"active",version:"1.0",createdAt:a,updatedAt:a,project:{hash:ve("sha256").update(this.projectRoot).digest("hex").substring(0,16),workingDirectory:this.projectRoot},messages:u,toolGroups:c,session:{model:n,sessionId:t,totalMessages:u.length,lastActivity:a},todos:i||void 0,compression:d,trackedFiles:s&&s.length>0?s:void 0}}messagesToUIMessagesWithOrder(e,t){const n=[];return e.forEach((e,r)=>{if("role"in e&&"tool-group"!==e.role){const i=e,o=i.timestamp?new Date(i.timestamp).toISOString():new Date(t+10*r).toISOString();n.push({id:`msg-${t}-${r}`,role:i.role,content:i.content,createdAt:o,model:i.model,hidden:i.hidden,mode:i.mode,timestamp:i.timestamp,patch:i.patch,metadata:{streamingComplete:!0,originalIndex:r}})}}),n}extractToolGroupsWithOrder(e,t){const n=[];return e.forEach((e,r)=>{if("role"in e&&"tool-group"===e.role){const i=e;n.push({id:i.id,timestamp:t+10*r,relatedMessageId:`msg-${t}-${r}`,originalIndex:r,tools:i.toolGroup.tools.map(e=>({id:e.id,toolCallId:e.toolCallId,name:e.name,displayName:e.displayName,description:e.description,status:e.status,result:e.result,confirmationDetails:e.confirmationDetails,startTime:e.startTime||Date.now(),endTime:e.endTime}))})}}),n}snapshotToMessages(e){const t=[];for(const n of e.messages){const e={role:n.role,content:n.content,model:n.model,hidden:n.hidden,mode:n.mode,timestamp:n.timestamp||new Date(n.createdAt).getTime(),patch:n.patch},r=new Date(n.createdAt).getTime(),i=n.metadata?.originalIndex??0;t.push({message:e,timestamp:r,originalIndex:i})}for(const n of e.toolGroups){const e={id:n.id,status:"completed",startTime:Math.min(...n.tools.map(e=>e.startTime)),endTime:Math.max(...n.tools.map(e=>e.endTime||e.startTime)),tools:n.tools.map(e=>({id:e.id,toolCallId:e.toolCallId,name:e.name,displayName:e.displayName,description:e.description,status:e.status,result:e.result,confirmationDetails:e.confirmationDetails,startTime:e.startTime,endTime:e.endTime}))},r={role:"tool-group",id:n.id,toolGroup:e,timestamp:n.timestamp},i=n.originalIndex??0;t.push({message:r,timestamp:n.timestamp,originalIndex:i})}return t.sort((e,t)=>e.originalIndex!==t.originalIndex?e.originalIndex-t.originalIndex:e.timestamp-t.timestamp),t.map(e=>e.message)}async writeSnapshotToFile(e,t){const n=`${e}.tmp`,r=JSON.stringify(t,null,2);try{await c.writeFile(n,r,"utf-8"),await c.rename(n,e)}catch(qK){try{await c.unlink(n)}catch{}throw qK}}async readSnapshotFromFile(e){try{const t=await c.readFile(e,"utf-8"),n=JSON.parse(t);return n.version&&n.messages&&Array.isArray(n.messages)?n:null}catch(qK){if("ENOENT"===qK.code)return null;throw qK}}async updateConversationIndex(e){const t=tM(this.projectRoot);let n;try{const e=await c.readFile(t,"utf-8");n=JSON.parse(e)}catch{n={conversations:[],lastUpdated:(new Date).toISOString()}}n.conversations=n.conversations.filter(t=>t.id!==e.id);const r=this.generatePreview(e);n.conversations.push({id:e.id,name:e.id,messageCount:e.messages.length,toolCallCount:e.toolGroups.reduce((e,t)=>e+t.tools.length,0),lastModified:e.updatedAt,model:e.session.model,preview:r}),n.lastUpdated=(new Date).toISOString(),await c.writeFile(t,JSON.stringify(n,null,2),"utf-8")}async readConversationIndex(){const e=tM(this.projectRoot);try{const t=await c.readFile(e,"utf-8");return JSON.parse(t)}catch{return{conversations:[],lastUpdated:(new Date).toISOString()}}}async compressAndSaveActiveConversation(e,t,n,r,i=!1){if(this.initialized||await this.initialize(),!this.initialized)return{success:!1,originalTokenCount:bM(e),newTokenCount:bM(e),compressedMessages:e,error:"Failed to initialize conversation persistence"};try{const o=await vM.compressConversation(e,t,n,r,i);if(o.success){const e=iM("active"),r=this.createSnapshot(o.compressedMessages,t,n,void 0,e,o),i=eM(this.projectRoot);await this.writeSnapshotToFile(i,r)}return o}catch(qK){return{success:!1,originalTokenCount:bM(e),newTokenCount:bM(e),compressedMessages:e,error:qK instanceof Error?qK.message:String(qK)}}}shouldAutoCompress(e,t){return vM.shouldCompressMessages(e,t)}getCompressionStats(e){if(!e.compression)return{isCompressed:!1,totalCompressions:0,totalTokensSaved:0};const t=e.compression.compressionHistory,n=t.reduce((e,t)=>e+(t.originalTokens-t.compressedTokens),0),r=t[t.length-1];return{isCompressed:e.compression.isCompressed,totalCompressions:t.length,totalTokensSaved:n,lastCompressionDate:e.compression.lastCompression,compressionRatio:r?.compressionRatio}}generatePreview(e){const t=e.messages.find(e=>"user"===e.role);return t&&"string"==typeof t.content?t.content.substring(0,100)+(t.content.length>100?"...":""):"No preview available"}async markForRevert(e,t){if(this.initialized||await this.initialize(),!this.initialized)return;const n=[];let r="",i=0;for(const a of t)if("role"in a&&"user"===a.role){const t=a;if(t.hidden)continue;if(i===e&&(r=`msg-${i}`),i>e&&t.patch){const e=Array.isArray(t.patch)?t.patch:[t.patch];for(const t of e)n.push({hash:t.hash,files:t.files})}i++}const o=eM(this.projectRoot),s=await this.readSnapshotFromFile(o);s&&(s.revert={targetMessageIndex:e,targetMessageId:r,patches:n},await this.writeSnapshotToFile(o,s))}async hasRevertPending(){if(this.initialized||await this.initialize(),!this.initialized)return!1;const e=eM(this.projectRoot),t=await this.readSnapshotFromFile(e);return void 0!==t?.revert}async getRevertPatches(){if(this.initialized||await this.initialize(),!this.initialized)return null;const e=eM(this.projectRoot),t=await this.readSnapshotFromFile(e);return t?.revert?.patches||null}async processRevert(e){if(this.initialized||await this.initialize(),!this.initialized)return e;const t=eM(this.projectRoot),n=await this.readSnapshotFromFile(t);if(!n?.revert)return e;const r=n.revert.targetMessageIndex,i=[];let o=-1;for(const s of e)if("role"in s&&"user"===s.role){s.hidden||(o++,o<=r&&i.push(s))}else o<=r&&i.push(s);return n.revert=void 0,await this.writeSnapshotToFile(t,n),i}async clearRevert(){if(this.initialized||await this.initialize(),!this.initialized)return;const e=eM(this.projectRoot),t=await this.readSnapshotFromFile(e);t&&(t.revert=void 0,await this.writeSnapshotToFile(e,t))}close(){this.initialized=!1,this.conversationDir=null}}let IM=null;function wM(){return IM}const CM=qe.createContext(null);function _M({children:e}){const t=function(){const[e,t]=qe.useState(!1),[n,r]=qe.useState(!1),[i,o]=qe.useState(!1),[s,a]=qe.useState(!1),[l,u]=qe.useState(!1),[c,d]=qe.useState(null),[p,f]=qe.useState(null),[h,g]=qe.useState(null);return{isCreateProjectOpen:e,setIsCreateProjectOpen:t,isCreateTeamOpen:n,setIsCreateTeamOpen:r,isBillingModalOpen:i,setIsBillingModalOpen:o,error:c,setError:d,isDeviceAuthOpen:s,setIsDeviceAuthOpen:a,isAddDocumentsModalOpen:l,setIsAddDocumentsModalOpen:u,activeQuestionPrompt:p,setActiveQuestionPrompt:f,pendingQuestionResponse:h,setPendingQuestionResponse:g}}(),n=function(){const[e,t]=qe.useState([]),[n,r]=qe.useState(!1),[i,o]=qe.useState(null),[s,a]=qe.useState([]);return{messages:e,setMessages:t,streamingState:n?_w.Responding:_w.Idle,isResponding:n,setIsResponding:r,thought:i,setThought:o,queuedMessages:s,setQueuedMessages:a}}(),r=YF(t.setError),i=function(e,t){const n=qe.useRef(null),[r,i]=qe.useState(null),o=qe.useRef(!1),s=qe.useRef(null),{sessionId:a}=FT(),{selectedModel:l}=VF();return qe.useEffect(()=>((async()=>{if(!n.current)try{const e=new EM;await e.initialize(),n.current=e,i(e),ex.debug("Conversation service initialized in hook")}catch(qK){ex.error("Failed to initialize conversation service in hook",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0})}})(),()=>{n.current&&(n.current.close(),n.current=null)}),[]),qe.useEffect(()=>{},[a]),qe.useEffect(()=>{if(!r||!a||0===e.length||!l)return;const t=setTimeout(async()=>{try{const t=wM(),n=t?.getTrackedFiles();ex.debug("Auto-save: Getting tracked files",{hasSnapshotService:!!t,trackedFilesCount:n?.length||0,trackedFiles:n||[]}),await r.saveActiveConversation(e,a,l,n)}catch(qK){ex.error("Auto-save failed in conversation service hook",{error:qK instanceof Error?qK.message:String(qK)})}},2e3);return()=>clearTimeout(t)},[e,r,a,l]),qe.useEffect(()=>{r&&(async()=>{try{const n=await r.restoreActiveConversation();if(!n||!n.messages.length)return;if(!o.current&&n.trackedFiles){const e=wM();e?(e.setTrackedFiles(n.trackedFiles),ex.debug("Restored tracked files to snapshot service immediately",{fileCount:n.trackedFiles.length}),o.current=!0):(s.current=n.trackedFiles,ex.debug("Snapshot service not ready, storing tracked files for later",{fileCount:n.trackedFiles.length}))}0===e.filter(e=>!("role"in e)||"system"!==e.role||!e.hidden).length&&t(e=>[...e.filter(e=>"role"in e&&"system"===e.role&&e.hidden),...n.messages])}catch(qK){ex.debug("Failed to restore conversation:",qK)}})()},[r,e,t]),qe.useEffect(()=>{if(s.current){const e=wM();e&&!o.current&&(e.setTrackedFiles(s.current),ex.debug("Applied pending tracked files to snapshot service",{fileCount:s.current.length}),o.current=!0,s.current=null)}},[e]),{saveConversation:async t=>{if(!r||!a||!l)throw new Error("Conversation service not available");const n=wM(),i=n?.getTrackedFiles();await r.saveNamedConversation(t,e,a,l,i)},loadConversation:async e=>{if(!r)throw new Error("Conversation service not available");const n=await r.loadNamedConversation(e);if(!n)throw new Error(`Conversation "${e}" not found`);{const e=n.filter(e=>!("id"in e)||!("string"==typeof e.id&&e.id.startsWith("env-context-")));t(e)}},listConversations:async()=>r?r.listConversations():[],clearActiveConversation:async()=>{if(!r)throw new Error("Conversation service not available");await r.clearActiveConversation()},conversationService:r}}(n.messages,n.setMessages);return We.jsx(CM.Provider,{value:{...t,...n,...r,...i},children:e})}function BM(){const e=qe.useContext(CM);if(!e)throw new Error("useAppState must be used inside AppProvider");return e}const DM=kw((e,t)=>({streams:new Map,totalLineCount:0,totalTokenCount:0,updateStream:(t,n,r)=>{e(e=>{const i=r.split("\n").length,o=function(e){if(!e)return 0;const t=Math.ceil(e.length/4);return t+Math.ceil(.1*t)}(r),s=e.streams.get(t),a=s?.lineCount||0,l=s?.tokenCount||0,u=new Map(e.streams);u.set(t,{toolCallId:t,toolName:n,output:r,timestamp:Date.now(),lineCount:i,tokenCount:o});const c=i-a,d=o-l;return{streams:u,totalLineCount:e.totalLineCount+c,totalTokenCount:e.totalTokenCount+d}})},clearStream:t=>{e(e=>{const n=e.streams.get(t),r=n?.lineCount||0,i=n?.tokenCount||0,o=new Map(e.streams);return o.delete(t),{streams:o,totalLineCount:e.totalLineCount-r,totalTokenCount:e.totalTokenCount-i}})},clearAll:()=>{e({streams:new Map,totalLineCount:0,totalTokenCount:0})},getStream:e=>t().streams.get(e)}));var SM=(e=>(e.Pending="pending",e.Executing="executing",e.Success="success",e.Error="error",e.Confirming="confirming",e.Cancelled="cancelled",e))(SM||{}),kM=(e=>(e.ProceedOnce="proceed_once",e.ProceedAlways="proceed_always",e.ProceedAlwaysCommand="proceed_always_command",e.ProceedAlwaysTool="proceed_always_tool",e.Cancel="cancel",e))(kM||{});const xM="white",QM="gray",NM="green",TM="red",RM="yellow",FM="blue",MM="cyan",OM="magenta",$M=new Intl.Segmenter,LM=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),PM=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),jM=new RegExp("^\\p{RGI_Emoji}$","v");function UM(e){return e.replace(PM,"")}function zM(e){return LM.test(e)}function GM(e,t){let n=0;if(e.length>1)for(const r of e.slice(1))r>="＀"&&r<="￯"&&(n+=Gt(r.codePointAt(0),t));return n}function HM(e,t={}){if("string"!=typeof e||0===e.length)return 0;const{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;let i=e;if(r||(i=jt(i)),0===i.length)return 0;let o=0;const s={ambiguousAsWide:!n};for(const{segment:a}of $M.segment(i)){if(zM(a))continue;if(jM.test(a)){o+=2;continue}o+=Gt(UM(a).codePointAt(0),s),o+=GM(a,s)}return o}function WM(e){return Array.from(e)}const qM=qe.createContext(void 0),JM=qe.createContext(void 0),KM=({children:e})=>{const[t,n]=qe.useState(new Set),r=qe.useCallback(e=>{n(t=>{if(t.has(e))return t;const n=new Set(t);return n.add(e),n})},[]),i=qe.useCallback(e=>{n(t=>{if(!t.has(e))return t;const n=new Set(t);return n.delete(e),n})},[]),o=qe.useMemo(()=>({overflowingIds:t}),[t]),s=qe.useMemo(()=>({addOverflowingId:r,removeOverflowingId:i}),[r,i]);return We.jsx(qM.Provider,{value:o,children:We.jsx(JM.Provider,{value:s,children:e})})},ZM=({children:e,maxWidth:t,maxHeight:n,overflowDirection:r="top",additionalHiddenLinesCount:i=0})=>{const o=qe.useId(),{addOverflowingId:s,removeOverflowingId:a}=qe.useContext(JM)||{},l=[],u=Math.max(Math.round(n??Number.MAX_SAFE_INTEGER),2);if(void 0===t)throw new Error("maxWidth must be defined when maxHeight is set.");Je.Children.forEach(e,function e(n){Je.isValidElement(n)&&(n.type!==qe.Fragment?n.type!==ki||function(e,t,n){const r=function(e){if(!Je.isValidElement(e)||e.type!==ki)return{noWrapSegments:[{text:"<ERROR>",props:{}}],segments:[]};const t={noWrapSegments:[],segments:[]};let n=!1;function r(e,i){if(null===e)return;if("string"==typeof e||"number"==typeof e){const r=String(e);if(!r)return;const o={text:r,props:i??{}};return void(void 0===i||"wrap"===i.wrap?(n=!0,t.segments.push(o)):n?t.segments.push(o):t.noWrapSegments.push(o))}if(!Je.isValidElement(e))return;if(e.type===qe.Fragment)return void Je.Children.forEach(e.props.children,e=>r(e,i));if(e.type!==xi)return;const{children:o,...s}=e.props,a=void 0===i?s:{...i,...s};Je.Children.forEach(o,e=>r(e,a))}return Je.Children.forEach(e.props.children,e=>r(e,void 0)),t}(e);if(0===r.segments.length&&0===r.noWrapSegments.length)return void n.push([]);const i=[],o=[];let s=0;if(r.noWrapSegments.forEach(e=>{o.push(e),s+=HM(e.text)}),0===r.segments.length){const e=[];let t=[];o.forEach(n=>{n.text.split("\n").forEach((r,i)=>{i>0&&(e.push(t),t=[]),r&&t.push({text:r,props:n.props})})}),(t.length>0||o.length>0&&o[o.length-1]&&o[o.length-1]?.text.endsWith("\n"))&&e.push(t);for(const r of e)n.push(r);return}const a=t-s;if(a<1){const e=[];let r=[],i=0;for(const n of o){n.text.split("\n").forEach((o,s)=>{if(s>0&&(e.push(r),r=[],i=0),o){const e=HM(o);if(s>0&&e>0)r.push({text:"…",props:{}}),i=HM("…");else{const s=Math.max(0,t-HM("…"));if(e<=s&&0===i)r.push({text:o,props:n.props}),i+=e;else{const e=WM(o);let t=i,a=0;for(const n of e){const e=HM(n);if(t+e>s)break;t+=e,a++}const l=e.slice(0,a).join("");l&&r.push({text:l,props:n.props}),r.push({text:"…",props:{}}),i=t+HM("…")}}}})}(r.length>0||o.length>0&&o[o.length-1]&&o[o.length-1]?.text.endsWith("\n"))&&e.push(r),0===e.length&&e.push([{text:"…",props:{}}]);for(const t of e)n.push(t);return}let l=[],u=0;function c(){0===i.length?i.push([...o,...l]):s>0?i.push([{text:" ".repeat(s),props:{}},...l]):i.push(l),l=[],u=0}function d(e,t){const n=l[l.length-1];n&&n.props===t?n.text+=e:l.push({text:e,props:t})}r.segments.forEach(e=>{e.text.split("\n").forEach((t,n)=>{n>0&&c();t.split(/(\s+)/).forEach(t=>{if(!t)return;const n=HM(t);if(!(u+n>a&&u>0&&(c(),/^\s+$/.test(t))))if(n>a){let n=WM(t);for(;n.length>0;){let t=0,r=0;for(const e of n){const n=HM(e);if(u+r+n>a)break;r+=n,t++}if(t>0){const r=n.slice(0,t).join("");d(r,e.props),u+=HM(r),n=n.slice(t)}n.length>0&&c()}}else d(t,e.props),u+=n})}),e.text.endsWith("\n")&&c()}),l.length>0&&c();for(const p of i)n.push(p)}(n,t,l):Je.Children.forEach(n.props.children,e))});const c=(void 0!==u&&l.length>u||i>0)&&void 0!==u?u-1:u,d=void 0!==c?Math.max(0,l.length-c):0,p=d+i;qe.useEffect(()=>(p>0?s?.(o):a?.(o),()=>{a?.(o)}),[o,p,s,a]);const f=(d>0?"top"===r?l.slice(d,l.length):l.slice(0,c):l).map((e,t)=>We.jsx(ki,{children:e.length>0?e.map((e,t)=>We.jsx(xi,{...e.props,children:e.text},t)):We.jsx(xi,{children:" "})},t));return We.jsxs(ki,{flexDirection:"column",width:t,flexShrink:0,children:[p>0&&"top"===r&&We.jsxs(xi,{color:QM,wrap:"truncate",children:["... first ",p," line",1===p?"":"s"," hidden ..."]}),f,p>0&&"bottom"===r&&We.jsxs(xi,{color:QM,wrap:"truncate",children:["... last ",p," line",1===p?"":"s"," hidden ..."]})]})};const VM=2,YM=2,XM=3,eO=.9,tO=.8,nO=20,rO=60;class iO{baseTerminalWidth;constructor(e){this.baseTerminalWidth=e}getMainContentWidth(){return Math.floor(this.baseTerminalWidth*eO)}getInputWidth(){const e=this.getMainContentWidth()-VM-YM;return Math.max(nO,e)}getSuggestionsWidth(){const e=Math.floor(this.baseTerminalWidth*tO);return Math.max(rO,e)}getToolMessageWidth(){return this.baseTerminalWidth-XM-YM}getDialogContentWidth(){return this.baseTerminalWidth-VM-YM}getConstrainedContentWidth(e=0){return this.baseTerminalWidth-e}getTableWidth(){return this.baseTerminalWidth-2}}function oO(e){return qe.useMemo(()=>new iO(e),[e])}const sO=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],aO=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),lO=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),uO=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),cO=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();var dO="[0-9](_*[0-9])*",pO=`\\.(${dO})`,fO="[0-9a-fA-F](_*[0-9a-fA-F])*",hO={className:"number",variants:[{begin:`(\\b(${dO})((${pO})|\\.)?|(${pO}))[eE][+-]?(${dO})[fFdD]?\\b`},{begin:`\\b(${dO})((${pO})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${pO})[fFdD]?\\b`},{begin:`\\b(${dO})[fFdD]\\b`},{begin:`\\b0[xX]((${fO})\\.?|(${fO})?\\.(${fO}))[pP][+-]?(${dO})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${fO})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function gO(e,t,n){return-1===n?"":e.replace(t,r=>gO(e,t,n-1))}const AO="[A-Za-z$_][0-9A-Za-z$_]*",mO=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],yO=["true","false","null","undefined","NaN","Infinity"],bO=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],vO=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],EO=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],IO=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],wO=[].concat(EO,bO,vO);var CO="[0-9](_*[0-9])*",_O=`\\.(${CO})`,BO="[0-9a-fA-F](_*[0-9a-fA-F])*",DO={className:"number",variants:[{begin:`(\\b(${CO})((${_O})|\\.)?|(${_O}))[eE][+-]?(${CO})[fFdD]?\\b`},{begin:`\\b(${CO})((${_O})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${_O})[fFdD]?\\b`},{begin:`\\b(${CO})[fFdD]\\b`},{begin:`\\b0[xX]((${BO})\\.?|(${BO})?\\.(${BO}))[pP][+-]?(${CO})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${BO})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};const SO=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],kO=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),xO=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),QO=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),NO=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),TO=xO.concat(QO).sort().reverse();const RO=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],FO=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),MO=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),OO=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),$O=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function LO(e){return e?"string"==typeof e?e:e.source:null}function PO(e){return jO("(?=",e,")")}function jO(...e){return e.map(e=>LO(e)).join("")}function UO(...e){const t=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(t.capture?"":"?:")+e.map(e=>LO(e)).join("|")+")"}const zO=e=>jO(/\b/,e,/\w$/.test(e)?/\b/:/\B/),GO=["Protocol","Type"].map(zO),HO=["init","self"].map(zO),WO=["Any","Self"],qO=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],JO=["false","nil","true"],KO=["assignment","associativity","higherThan","left","lowerThan","none","right"],ZO=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],VO=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],YO=UO(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),XO=UO(YO,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),e$=jO(YO,XO,"*"),t$=UO(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),n$=UO(t$,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),r$=jO(t$,n$,"*"),i$=jO(/[A-Z]/,n$,"*"),o$=["attached","autoclosure",jO(/convention\(/,UO("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",jO(/objc\(/,r$,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],s$=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];const a$="[A-Za-z$_][0-9A-Za-z$_]*",l$=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],u$=["true","false","null","undefined","NaN","Infinity"],c$=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],d$=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],p$=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],f$=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],h$=[].concat(p$,c$,d$);const g$={arduino:function(e){const t={type:["boolean","byte","word","String"],built_in:["KeyboardController","MouseController","SoftwareSerial","EthernetServer","EthernetClient","LiquidCrystal","RobotControl","GSMVoiceCall","EthernetUDP","EsploraTFT","HttpClient","RobotMotor","WiFiClient","GSMScanner","FileSystem","Scheduler","GSMServer","YunClient","YunServer","IPAddress","GSMClient","GSMModem","Keyboard","Ethernet","Console","GSMBand","Esplora","Stepper","Process","WiFiUDP","GSM_SMS","Mailbox","USBHost","Firmata","PImage","Client","Server","GSMPIN","FileIO","Bridge","Serial","EEPROM","Stream","Mouse","Audio","Servo","File","Task","GPRS","WiFi","Wire","TFT","GSM","SPI","SD"],_hints:["setup","loop","runShellCommandAsynchronously","analogWriteResolution","retrieveCallingNumber","printFirmwareVersion","analogReadResolution","sendDigitalPortPair","noListenOnLocalhost","readJoystickButton","setFirmwareVersion","readJoystickSwitch","scrollDisplayRight","getVoiceCallStatus","scrollDisplayLeft","writeMicroseconds","delayMicroseconds","beginTransmission","getSignalStrength","runAsynchronously","getAsynchronously","listenOnLocalhost","getCurrentCarrier","readAccelerometer","messageAvailable","sendDigitalPorts","lineFollowConfig","countryNameWrite","runShellCommand","readStringUntil","rewindDirectory","readTemperature","setClockDivider","readLightSensor","endTransmission","analogReference","detachInterrupt","countryNameRead","attachInterrupt","encryptionType","readBytesUntil","robotNameWrite","readMicrophone","robotNameRead","cityNameWrite","userNameWrite","readJoystickY","readJoystickX","mouseReleased","openNextFile","scanNetworks","noInterrupts","digitalWrite","beginSpeaker","mousePressed","isActionDone","mouseDragged","displayLogos","noAutoscroll","addParameter","remoteNumber","getModifiers","keyboardRead","userNameRead","waitContinue","processInput","parseCommand","printVersion","readNetworks","writeMessage","blinkVersion","cityNameRead","readMessage","setDataMode","parsePacket","isListening","setBitOrder","beginPacket","isDirectory","motorsWrite","drawCompass","digitalRead","clearScreen","serialEvent","rightToLeft","setTextSize","leftToRight","requestFrom","keyReleased","compassRead","analogWrite","interrupts","WiFiServer","disconnect","playMelody","parseFloat","autoscroll","getPINUsed","setPINUsed","setTimeout","sendAnalog","readSlider","analogRead","beginWrite","createChar","motorsStop","keyPressed","tempoWrite","readButton","subnetMask","debugPrint","macAddress","writeGreen","randomSeed","attachGPRS","readString","sendString","remotePort","releaseAll","mouseMoved","background","getXChange","getYChange","answerCall","getResult","voiceCall","endPacket","constrain","getSocket","writeJSON","getButton","available","connected","findUntil","readBytes","exitValue","readGreen","writeBlue","startLoop","IPAddress","isPressed","sendSysex","pauseMode","gatewayIP","setCursor","getOemKey","tuneWrite","noDisplay","loadImage","switchPIN","onRequest","onReceive","changePIN","playFile","noBuffer","parseInt","overflow","checkPIN","knobRead","beginTFT","bitClear","updateIR","bitWrite","position","writeRGB","highByte","writeRed","setSpeed","readBlue","noStroke","remoteIP","transfer","shutdown","hangCall","beginSMS","endWrite","attached","maintain","noCursor","checkReg","checkPUK","shiftOut","isValid","shiftIn","pulseIn","connect","println","localIP","pinMode","getIMEI","display","noBlink","process","getBand","running","beginSD","drawBMP","lowByte","setBand","release","bitRead","prepare","pointTo","readRed","setMode","noFill","remove","listen","stroke","detach","attach","noTone","exists","buffer","height","bitSet","circle","config","cursor","random","IRread","setDNS","endSMS","getKey","micros","millis","begin","print","write","ready","flush","width","isPIN","blink","clear","press","mkdir","rmdir","close","point","yield","image","BSSID","click","delay","read","text","move","peek","beep","rect","line","open","seek","fill","size","turn","stop","home","find","step","tone","sqrt","RSSI","SSID","end","bit","tan","cos","sin","pow","map","abs","max","min","get","run","put"],literal:["DIGITAL_MESSAGE","FIRMATA_STRING","ANALOG_MESSAGE","REPORT_DIGITAL","REPORT_ANALOG","INPUT_PULLUP","SET_PIN_MODE","INTERNAL2V56","SYSTEM_RESET","LED_BUILTIN","INTERNAL1V1","SYSEX_START","INTERNAL","EXTERNAL","DEFAULT","OUTPUT","INPUT","HIGH","LOW"]},n=function(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="(?!struct)("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",s={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},a={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},u={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(a,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},c={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},d=t.optional(i)+e.IDENT_RE+"\\s*\\(",p={type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],keyword:["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"]},f={className:"function.dispatch",relevance:0,keywords:{_hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"]},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},h=[f,u,s,n,e.C_BLOCK_COMMENT_MODE,l,a],g={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:p,contains:h.concat([{begin:/\(/,end:/\)/,keywords:p,contains:h.concat(["self"]),relevance:0}]),relevance:0},A={className:"function",begin:"("+o+"[\\*&\\s]+)+"+d,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:p,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:p,relevance:0},{begin:d,returnBegin:!0,contains:[c],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[a,l]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,a,l,s,{begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,a,l,s]}]},s,n,e.C_BLOCK_COMMENT_MODE,u]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:p,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(g,A,f,h,[u,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:p,contains:["self",s]},{begin:e.IDENT_RE+"::",keywords:p},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}(e),r=n.keywords;return r.type=[...r.type,...t.type],r.literal=[...r.literal,...t.literal],r.built_in=[...r.built_in,...t.built_in],r._hints=t._hints,n.name="Arduino",n.aliases=["ino"],n.supersetOf="cpp",n},bash:function(e){const t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},r]});const i={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},o=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),s={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},a={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,i]};i.contains.push(a);const l={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,n]},u=e.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),c={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],literal:["true","false"],built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"]},contains:[u,e.SHEBANG(),c,l,o,s,{match:/(\/[a-z._-]+)+/},a,{match:/\\"/},{className:"string",begin:/'/,end:/'/},{match:/\\'/},n]}},c:function(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",s={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:/\batomic_[a-z]{3,6}\b/}]},a={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},u={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(a,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},c={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},d=t.optional(i)+e.IDENT_RE+"\\s*\\(",p={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},f=[u,s,n,e.C_BLOCK_COMMENT_MODE,l,a],h={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:p,contains:f.concat([{begin:/\(/,end:/\)/,keywords:p,contains:f.concat(["self"]),relevance:0}]),relevance:0},g={begin:"("+o+"[\\*&\\s]+)+"+d,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:p,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:p,relevance:0},{begin:d,returnBegin:!0,contains:[e.inherit(c,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,a,l,s,{begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,a,l,s]}]},s,n,e.C_BLOCK_COMMENT_MODE,u]};return{name:"C",aliases:["h"],keywords:p,disableAutodetect:!0,illegal:"</",contains:[].concat(h,g,f,[u,{begin:e.IDENT_RE+"::",keywords:p},{className:"class",beginKeywords:"enum class struct union",end:/[{;:<>=]/,contains:[{beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:u,strings:a,keywords:p}}},cpp:function(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",o="(?!struct)("+r+"|"+t.optional(i)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",s={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},a={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},u={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(a,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},c={className:"title",begin:t.optional(i)+e.IDENT_RE,relevance:0},d=t.optional(i)+e.IDENT_RE+"\\s*\\(",p={type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],keyword:["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"]},f={className:"function.dispatch",relevance:0,keywords:{_hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"]},begin:t.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},h=[f,u,s,n,e.C_BLOCK_COMMENT_MODE,l,a],g={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:p,contains:h.concat([{begin:/\(/,end:/\)/,keywords:p,contains:h.concat(["self"]),relevance:0}]),relevance:0},A={className:"function",begin:"("+o+"[\\*&\\s]+)+"+d,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:p,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:p,relevance:0},{begin:d,returnBegin:!0,contains:[c],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[a,l]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,a,l,s,{begin:/\(/,end:/\)/,keywords:p,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,a,l,s]}]},s,n,e.C_BLOCK_COMMENT_MODE,u]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:p,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(g,A,f,h,[u,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:p,contains:["self",s]},{begin:e.IDENT_RE+"::",keywords:p},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}},csharp:function(e){const t={keyword:["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"].concat(["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"]),built_in:["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],literal:["default","false","null","true"]},n=e.inherit(e.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),r={className:"number",variants:[{begin:"\\b(0b[01']+)"},{begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],relevance:0},i={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},o=e.inherit(i,{illegal:/\n/}),s={className:"subst",begin:/\{/,end:/\}/,keywords:t},a=e.inherit(s,{illegal:/\n/}),l={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},e.BACKSLASH_ESCAPE,a]},u={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},s]},c=e.inherit(u,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},a]});s.contains=[u,l,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,r,e.C_BLOCK_COMMENT_MODE],a.contains=[c,l,o,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,r,e.inherit(e.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];const d={variants:[{className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},u,l,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},p={begin:"<",end:">",contains:[{beginKeywords:"in out"},n]},f=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",h={begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:t,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:"\x3c!--|--\x3e"},{begin:"</?",end:">"}]}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},d,r,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},n,p,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[n,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[n,p,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+f+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:t,contains:[{beginKeywords:["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"].join(" "),relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[e.TITLE_MODE,p],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:t,relevance:0,contains:[d,r,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},h]}},css:function(e){const t=e.regex,n=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),r=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/},n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+lO.join("|")+")"},{begin:":(:)?("+uO.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+cO.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...r,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...r,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:aO.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+sO.join("|")+")\\b"}]}},diff:function(e){const t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}},go:function(e){const t={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:t,illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"string",variants:[e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[e.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,illegal:/["']/}]}]}},graphql:function(e){const t=e.regex;return{name:"GraphQL",aliases:["gql"],case_insensitive:!0,disableAutodetect:!1,keywords:{keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"],literal:["true","false","null"]},contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation",begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/,end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{scope:"symbol",begin:t.concat(/[_A-Za-z][_0-9A-Za-z]*/,t.lookahead(/\s*:/)),relevance:0}],illegal:[/[;<']/,/BEGIN/]}},ini:function(e){const t=e.regex,n={className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{begin:e.NUMBER_RE}]},r=e.COMMENT();r.variants=[{begin:/;/,end:/$/},{begin:/#/,end:/$/}];const i={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{begin:/\$\{(.*?)\}/}]},o={className:"literal",begin:/\bon|off|true|false|yes|no\b/},s={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]},a={begin:/\[/,end:/\]/,contains:[r,o,i,s,n,"self"],relevance:0},l=t.either(/[A-Za-z0-9_-]+/,/"(\\"|[^"])*"/,/'[^']*'/);return{name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,contains:[r,{className:"section",begin:/\[+/,end:/\]+/},{begin:t.concat(l,"(\\s*\\.\\s*",l,")*",t.lookahead(/\s*=\s*[^#\s]/)),className:"attr",starts:{end:/$/,contains:[r,a,o,i,s,n]}}]}},java:function(e){const t=e.regex,n="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=n+gO("(?:<"+n+"~~~(?:\\s*,\\s*"+n+"~~~)*>)?",/~~~/g,2),i={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},o={className:"meta",begin:"@"+n,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},s={className:"params",begin:/\(/,end:/\)/,keywords:i,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:i,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[t.concat(/(?!else)/,n),/\s+/,n,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,n],className:{1:"keyword",3:"title.class"},contains:[s,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:i,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:i,relevance:0,contains:[o,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,hO,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},hO,o]}},javascript:function(e){const t=e.regex,n=AO,r="<>",i="</>",o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let i;">"===r&&(((e,{after:t})=>{const n="</"+e[0].slice(1);return-1!==e.input.indexOf(n,t)})(e,{after:n})||t.ignoreMatch());const o=e.input.substring(n);((i=o.match(/^\s*=/))||(i=o.match(/^\s+extends\s+/))&&0===i.index)&&t.ignoreMatch()}},s={$pattern:AO,keyword:mO,literal:yO,built_in:wO,"variable.language":IO},a="[0-9](_?[0-9])*",l=`\\.(${a})`,u="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",c={className:"number",variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${a})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:s,contains:[]},p={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},f={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},h={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},g={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},A={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},m=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,f,h,g,{match:/\$\d+/},c];d.contains=m.concat({begin:/\{/,end:/\}/,keywords:s,contains:["self"].concat(m)});const y=[].concat(A,d.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:["self"].concat(y)}]),v={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},E={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},I={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...bO,...vO]}},w={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[v],illegal:/%/},C={match:t.concat(/\b/,(_=[...EO,"super","import"].map(e=>`${e}\\s*\\(`),t.concat("(?!",_.join("|"),")")),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0};var _;const B={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},D={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},v]},S="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",k={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(S)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[v]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:I},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,f,h,g,A,{match:/\$\d+/},c,I,{scope:"attr",match:n+t.lookahead(":"),relevance:0},k,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[A,e.REGEXP_MODE,{className:"function",begin:S,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:i},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[v,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},B,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[v]},C,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},E,D,{match:/\$[(.]/}]}},json:function(e){const t=["true","false","null"],n={scope:"literal",beginKeywords:t.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:t},contains:[{className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{match:/[{}[\],:]/,className:"punctuation",relevance:0},e.QUOTE_STRING_MODE,n,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}},kotlin:function(e){const t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},n={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@"},r={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},i={className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},o={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[i,r]},{begin:"'",end:"'",illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[e.BACKSLASH_ESCAPE,i,r]}]};r.contains.push(o);const s={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?"},a={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[e.inherit(o,{className:"string"}),"self"]}]},l=DO,u=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),c={variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},d=c;return d.variants[1].contains=[c],c.variants[1].contains=[d],{name:"Kotlin",aliases:["kt","kts"],keywords:t,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,u,{className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},n,s,a,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:t,relevance:5,contains:[{begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin:/</,end:/>/,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[c,e.C_LINE_COMMENT_MODE,u],relevance:0},e.C_LINE_COMMENT_MODE,u,s,a,o,e.C_NUMBER_MODE]},u]},{begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},e.UNDERSCORE_TITLE_MODE,{className:"type",begin:/</,end:/>/,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},s,a]},o,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:"\n"},l]}},less:function(e){const t=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),n=TO,r="[\\w-]+",i="("+r+"|@\\{"+r+"\\})",o=[],s=[],a=function(e){return{className:"string",begin:"~?"+e+".*?"+e}},l=function(e,t,n){return{className:e,begin:t,relevance:n}},u={$pattern:/[a-z-]+/,keyword:"and or not only",attribute:kO.join(" ")},c={begin:"\\(",end:"\\)",contains:s,keywords:u,relevance:0};s.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,a("'"),a('"'),t.CSS_NUMBER_MODE,{begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]",excludeEnd:!0}},t.HEXCOLOR,c,l("variable","@@?"+r,10),l("variable","@\\{"+r+"\\}"),l("built_in","~?`[^`]*?`"),{className:"attribute",begin:r+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0},t.IMPORTANT,{beginKeywords:"and not"},t.FUNCTION_DISPATCH);const d=s.concat({begin:/\{/,end:/\}/,contains:o}),p={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(s)},f={begin:i+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+NO.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:s}}]},h={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:u,returnEnd:!0,contains:s,relevance:0}},g={className:"variable",variants:[{begin:"@"+r+"\\s*:",relevance:15},{begin:"@"+r}],starts:{end:"[;}]",returnEnd:!0,contains:d}},A={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:i,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:"[<='$\"]",relevance:0,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,p,l("keyword","all\\b"),l("variable","@\\{"+r+"\\}"),{begin:"\\b("+SO.join("|")+")\\b",className:"selector-tag"},t.CSS_NUMBER_MODE,l("selector-tag",i,0),l("selector-id","#"+i),l("selector-class","\\."+i,0),l("selector-tag","&",0),t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",begin:":("+xO.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+QO.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:d},{begin:"!important"},t.FUNCTION_DISPATCH]},m={begin:r+`:(:)?(${n.join("|")})`,returnBegin:!0,contains:[A]};return o.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,h,g,m,f,A,p,t.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:"[=>'/<($\"]",contains:o}},lua:function(e){const t="\\[=*\\[",n="\\]=*\\]",r={begin:t,end:n,contains:["self"]},i=[e.COMMENT("--(?!"+t+")","$"),e.COMMENT("--"+t,n,{contains:[r],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:e.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in local not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:i.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:i}].concat(i)},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:t,end:n,contains:[r],relevance:5}])}},makefile:function(e){const t={className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)",contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%<?\^\+\*]/}]},n={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,t]},r={className:"variable",begin:/\$\([\w-]+\s/,end:/\)/,keywords:{built_in:"subst patsubst strip findstring filter filter-out sort word wordlist firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath error warning shell origin flavor foreach if or and call eval file value"},contains:[t,n]},i={begin:"^"+e.UNDERSCORE_IDENT_RE+"\\s*(?=[:+?]?=)"},o={className:"section",begin:/^[^\s]+:/,end:/$/,contains:[t]};return{name:"Makefile",aliases:["mk","mak","make"],keywords:{$pattern:/[\w-]+/,keyword:"define endef undefine ifdef ifndef ifeq ifneq else endif include -include sinclude override export unexport private vpath"},contains:[e.HASH_COMMENT_MODE,t,n,r,i,{className:"meta",begin:/^\.PHONY:/,end:/$/,keywords:{$pattern:/[\.\w]+/,keyword:".PHONY"}},o]}},markdown:function(e){const t={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},n={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:e.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},r={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},i={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},o=e.inherit(r,{contains:[]}),s=e.inherit(i,{contains:[]});r.contains.push(s),i.contains.push(o);let a=[t,n];return[r,i,o,s].forEach(e=>{e.contains=e.contains.concat(a)}),a=a.concat(r,i),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:a},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:a}]}]},t,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},r,i,{className:"quote",begin:"^>\\s+",contains:a,end:"$"},{className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{begin:"^[-\\*]{3,}",end:"$"},n,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}},objectivec:function(e){const t=/[a-zA-Z@][a-zA-Z0-9_]*/,n={$pattern:t,keyword:["@interface","@class","@protocol","@implementation"]};return{name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"],keywords:{"variable.language":["this","super"],$pattern:t,keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"],literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"],built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"],type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"]},illegal:"</",contains:[{className:"built_in",begin:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.C_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{className:"string",variants:[{begin:'@"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]}]},{className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),{className:"string",begin:/<.*?>/,end:/$/,illegal:"\\n"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class",begin:"("+n.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:n,contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE,relevance:0}]}},perl:function(e){const t=e.regex,n=/[dualxmsipngr]{0,12}/,r={$pattern:/[\w.]+/,keyword:["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork","format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","local","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","setgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","until","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"].join(" ")},i={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:r},o={begin:/->\{/,end:/\}/},s={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},a={scope:"variable",variants:[{begin:/\$\d/},{begin:t.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[s]},l={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},u=[e.BACKSLASH_ESCAPE,i,a],c=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],d=(e,r,i="\\1")=>{const o="\\1"===i?i:t.concat(i,r);return t.concat(t.concat("(?:",e,")"),r,/(?:\\.|[^\\\/])*?/,o,/(?:\\.|[^\\\/])*?/,i,n)},p=(e,r,i)=>t.concat(t.concat("(?:",e,")"),r,/(?:\\.|[^\\\/])*?/,i,n),f=[a,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),o,{className:"string",contains:u,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},l,{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:d("s|tr|y",t.either(...c,{capture:!0}))},{begin:d("s|tr|y","\\(","\\)")},{begin:d("s|tr|y","\\[","\\]")},{begin:d("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:p("(?:m|qr)?",/\//,/\//)},{begin:p("m|qr",t.either(...c,{capture:!0}),/\1/)},{begin:p("m|qr",/\(/,/\)/)},{begin:p("m|qr",/\[/,/\]/)},{begin:p("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,s]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,s,l]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return i.contains=f,o.contains=f,{name:"Perl",aliases:["pl","pm"],keywords:r,contains:f}},php:function(e){const t=e.regex,n=/(?![A-Za-z0-9])(?![$])/,r=t.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,n),i=t.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,n),o=t.concat(/[A-Z]+/,n),s={scope:"variable",match:"\\$+"+r},a={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},l=e.inherit(e.APOS_STRING_MODE,{illegal:null}),u="[ \t\n]",c={scope:"string",variants:[e.inherit(e.QUOTE_STRING_MODE,{illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(a)}),l,{begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:e.QUOTE_STRING_MODE.contains.concat(a),"on:begin":(e,t)=>{t.data._beginMatch=e[1]||e[2]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}},e.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/})]},d={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},p=["false","null","true"],f=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],h=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],g={keyword:f,literal:(e=>{const t=[];return e.forEach(e=>{t.push(e),e.toLowerCase()===e?t.push(e.toUpperCase()):t.push(e.toLowerCase())}),t})(p),built_in:h},A=e=>e.map(e=>e.replace(/\|\d+$/,"")),m={variants:[{match:[/new/,t.concat(u,"+"),t.concat("(?!",A(h).join("\\b|"),"\\b)"),i],scope:{1:"keyword",4:"title.class"}}]},y=t.concat(r,"\\b(?!\\()"),b={variants:[{match:[t.concat(/::/,t.lookahead(/(?!class\b)/)),y],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[i,t.concat(/::/,t.lookahead(/(?!class\b)/)),y],scope:{1:"title.class",3:"variable.constant"}},{match:[i,t.concat("::",t.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[i,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},v={scope:"attr",match:t.concat(r,t.lookahead(":"),t.lookahead(/(?!::)/))},E={relevance:0,begin:/\(/,end:/\)/,keywords:g,contains:[v,s,b,e.C_BLOCK_COMMENT_MODE,c,d,m]},I={relevance:0,match:[/\b/,t.concat("(?!fn\\b|function\\b|",A(f).join("\\b|"),"|",A(h).join("\\b|"),"\\b)"),r,t.concat(u,"*"),t.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[E]};E.contains.push(I);const w=[v,b,e.C_BLOCK_COMMENT_MODE,c,d,m],C={begin:t.concat(/#\[\s*\\?/,t.either(i,o)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:p,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:p,keyword:["new","array"]},contains:["self",...w]},...w,{scope:"meta",variants:[{match:i},{match:o}]}]};return{case_insensitive:!1,keywords:g,contains:[C,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},{scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},{scope:"variable.language",match:/\$this\b/},s,I,b,{match:[/const/,/\s/,r],scope:{1:"keyword",3:"variable.constant"}},m,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:g,contains:["self",C,s,b,e.C_BLOCK_COMMENT_MODE,c,d]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},c,d]}},"php-template":function(e){return{name:"PHP template",subLanguage:"xml",contains:[{begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*",end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0})]}]}},plaintext:function(e){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}},python:function(e){const t=e.regex,n=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],i={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},o={className:"meta",begin:/^(>>>|\.\.\.) /},s={className:"subst",begin:/\{/,end:/\}/,keywords:i,illegal:/#/},a={begin:/\{\{/,relevance:0},l={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,o],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,o],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,o,a,s]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,o,a,s]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,a,s]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,a,s]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},u="[0-9](_?[0-9])*",c=`(\\b(${u}))?\\.(${u})|\\b(${u})\\.`,d=`\\b|${r.join("|")}`,p={className:"number",relevance:0,variants:[{begin:`(\\b(${u})|(${c}))[eE][+-]?(${u})[jJ]?(?=${d})`},{begin:`(${c})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${d})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${d})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${d})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${d})`},{begin:`\\b(${u})[jJ](?=${d})`}]},f={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:i,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},h={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i,contains:["self",o,p,l,e.HASH_COMMENT_MODE]}]};return s.contains=[l,p,o],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:i,illegal:/(<\/|\?)|=>/,contains:[o,p,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},l,f,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[h]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[p,h,l]}]}},"python-repl":function(e){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}},r:function(e){const t=e.regex,n=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,r=t.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),i=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,o=t.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/);return{name:"R",keywords:{$pattern:n,keyword:"function if in break next repeat else for while",literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/,starts:{end:t.lookahead(t.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)),endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{scope:"variable",variants:[{match:n},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}]}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"',relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{1:"operator",2:"number"},match:[i,r]},{scope:{1:"operator",2:"number"},match:[/%[^%]*%/,r]},{scope:{1:"punctuation",2:"number"},match:[o,r]},{scope:{2:"number"},match:[/[^a-zA-Z0-9._]|^/,r]}]},{scope:{3:"operator"},match:[n,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:i},{match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:o},{begin:"`",end:"`",contains:[{begin:/\\./}]}]}},ruby:function(e){const t=e.regex,n="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",r=t.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),i=t.concat(r,/(::\w+)*/),o={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield","include","extend","prepend","public","private","protected","raise","throw"],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},s={className:"doctag",begin:"@[A-Za-z]+"},a={begin:"#<",end:">"},l=[e.COMMENT("#","$",{contains:[s]}),e.COMMENT("^=begin","^=end",{contains:[s],relevance:10}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],u={className:"subst",begin:/#\{/,end:/\}/,keywords:o},c={className:"string",contains:[e.BACKSLASH_ESCAPE,u],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?</,end:/>/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:t.concat(/<<[-~]?'?/,t.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,u]})]}]},d="[0-9](_?[0-9])*",p={className:"number",relevance:0,variants:[{begin:`\\b([1-9](_?[0-9])*|0)(\\.(${d}))?([eE][+-]?(${d})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},f={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:o}]},h=[c,{variants:[{match:[/class\s+/,i,/\s+<\s+/,i]},{match:[/\b(class|module)\s+/,i]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:o},{match:[/(include|extend)\s+/,i],scope:{2:"title.class"},keywords:o},{relevance:0,match:[i,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:r,scope:"title.class"},{match:[/def/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[f]},{begin:e.IDENT_RE+"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[c,{begin:n}],relevance:0},p,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:o},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,u],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(a,l),relevance:0}].concat(a,l);u.contains=h,f.contains=h;const g=[{begin:/^\s*=>/,starts:{end:"$",contains:h}},{className:"meta.prompt",begin:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]|(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>)(?=[ ])",starts:{end:"$",keywords:o,contains:h}}];return l.unshift(a),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:o,illegal:/\/\*/,contains:[e.SHEBANG({binary:"ruby"})].concat(g).concat(l).concat(h)}},rust:function(e){const t=e.regex,n=/(r#)?/,r=t.concat(n,e.UNDERSCORE_IDENT_RE),i=t.concat(n,e.IDENT_RE),o={className:"title.function.invoke",relevance:0,begin:t.concat(/\b/,/(?!let|for|while|if|else|match\b)/,i,t.lookahead(/\s*\(/))},s="([ui](8|16|32|64|128|size)|f(32|64))?",a=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],l=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:l,keyword:["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],literal:["true","false","Some","None","Ok","Err"],built_in:a},illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.COMMENT("/\\*","\\*/",{contains:["self"]}),e.inherit(e.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+s},{begin:"\\b0o([0-7_]+)"+s},{begin:"\\b0x([A-Fa-f0-9_]+)"+s},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+s}],relevance:0},{begin:[/fn/,/\s+/,r],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,r],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,r,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:e.IDENT_RE+"::",keywords:{keyword:"Self",built_in:a,type:l}},{className:"punctuation",begin:"->"},o]}},scss:function(e){const t=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),n=OO,r=MO,i="@[a-z-]+",o={className:"variable",begin:"(\\$[a-zA-Z-][a-zA-Z0-9_-]*)\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+RO.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+n.join("|")+")"},o,{begin:/\(/,end:/\)/,contains:[t.CSS_NUMBER_MODE]},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+$O.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[t.BLOCK_COMMENT,o,t.HEXCOLOR,t.CSS_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.IMPORTANT,t.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:i,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:FO.join(" ")},contains:[{begin:i,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},o,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.HEXCOLOR,t.CSS_NUMBER_MODE]},t.FUNCTION_DISPATCH]}},shell:function(e){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}},sql:function(e){const t=e.regex,n=e.COMMENT("--","$"),r=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],i=r,o=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(e=>!r.includes(e)),s={match:t.concat(/\b/,t.either(...i),/\s*\(/),relevance:0,keywords:{built_in:i}};function a(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,"\\s+"))),/\b/)}const l={scope:"keyword",match:a(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]),relevance:0};return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:function(e,{exceptions:t,when:n}={}){const r=n;return t=t||[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:r(e)?`${e}|0`:e)}(o,{when:e=>e.length<3}),literal:["true","false","unknown"],type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"]},contains:[{scope:"type",match:a(["double precision","large object","with timezone","without timezone"])},l,s,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{match:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,{scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}},swift:function(e){const t={match:/\s+/,relevance:0},n=e.COMMENT("/\\*","\\*/",{contains:["self"]}),r=[e.C_LINE_COMMENT_MODE,n],i={match:[/\./,UO(...GO,...HO)],className:{2:"keyword"}},o={match:jO(/\./,UO(...qO)),relevance:0},s=qO.filter(e=>"string"==typeof e).concat(["_|0"]),a={variants:[{className:"keyword",match:UO(...qO.filter(e=>"string"!=typeof e).concat(WO).map(zO),...HO)}]},l={$pattern:UO(/\b\w+/,/#\w+/),keyword:s.concat(ZO),literal:JO},u=[i,o,a],c=[{match:jO(/\./,UO(...VO)),relevance:0},{className:"built_in",match:jO(/\b/,UO(...VO),/(?=\()/)}],d={match:/->/,relevance:0},p=[d,{className:"operator",relevance:0,variants:[{match:e$},{match:`\\.(\\.|${XO})+`}]}],f="([0-9]_*)+",h="([0-9a-fA-F]_*)+",g={className:"number",relevance:0,variants:[{match:`\\b(${f})(\\.(${f}))?([eE][+-]?(${f}))?\\b`},{match:`\\b0x(${h})(\\.(${h}))?([pP][+-]?(${f}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},A=(e="")=>({className:"subst",variants:[{match:jO(/\\/,e,/[0\\tnr"']/)},{match:jO(/\\/,e,/u\{[0-9a-fA-F]{1,8}\}/)}]}),m=(e="")=>({className:"subst",match:jO(/\\/,e,/[\t ]*(?:[\r\n]|\r\n)/)}),y=(e="")=>({className:"subst",label:"interpol",begin:jO(/\\/,e,/\(/),end:/\)/}),b=(e="")=>({begin:jO(e,/"""/),end:jO(/"""/,e),contains:[A(e),m(e),y(e)]}),v=(e="")=>({begin:jO(e,/"/),end:jO(/"/,e),contains:[A(e),y(e)]}),E={className:"string",variants:[b(),b("#"),b("##"),b("###"),v(),v("#"),v("##"),v("###")]},I=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}],w={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:I},C=e=>{const t=jO(e,/\//),n=jO(/\//,e);return{begin:t,end:n,contains:[...I,{scope:"comment",begin:`#(?!.*${n})`,end:/$/}]}},_={scope:"regexp",variants:[C("###"),C("##"),C("#"),w]},B={match:jO(/`/,r$,/`/)},D=[B,{className:"variable",match:/\$\d+/},{className:"variable",match:`\\$${n$}+`}],S=[{match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:s$,contains:[...p,g,E]}]}},{scope:"keyword",match:jO(/@/,UO(...o$),PO(UO(/\(/,/\s+/)))},{scope:"meta",match:jO(/@/,r$)}],k={match:PO(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:jO(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,n$,"+")},{className:"type",match:i$,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:jO(/\s+&\s+/,PO(i$)),relevance:0}]},x={begin:/</,end:/>/,keywords:l,contains:[...r,...u,...S,d,k]};k.contains.push(x);const Q={begin:/\(/,end:/\)/,relevance:0,keywords:l,contains:["self",{match:jO(r$,/\s*:/),keywords:"_|0",relevance:0},...r,_,...u,...c,...p,g,E,...D,...S,k]},N={begin:/</,end:/>/,keywords:"repeat each",contains:[...r,k]},T={begin:/\(/,end:/\)/,keywords:l,contains:[{begin:UO(PO(jO(r$,/\s*:/)),PO(jO(r$,/\s+/,r$,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:r$}]},...r,...u,...p,g,E,...S,k,Q],endsParent:!0,illegal:/["']/},R={match:[/(func|macro)/,/\s+/,UO(B.match,r$,e$)],className:{1:"keyword",3:"title.function"},contains:[N,T,t],illegal:[/\[/,/%/]},F={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[N,T,t],illegal:/\[|%/},M={match:[/operator/,/\s+/,e$],className:{1:"keyword",3:"title"}},O={begin:[/precedencegroup/,/\s+/,i$],className:{1:"keyword",3:"title"},contains:[k],keywords:[...KO,...JO],end:/}/},$={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,r$,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:l,contains:[N,...u,{begin:/:/,end:/\{/,keywords:l,contains:[{scope:"title.class.inherited",match:i$},...u],relevance:0}]};for(const L of E.variants){const e=L.contains.find(e=>"interpol"===e.label);e.keywords=l;const t=[...u,...c,...p,g,E,...D];e.contains=[...t,{begin:/\(/,end:/\)/,contains:["self",...t]}]}return{name:"Swift",keywords:l,contains:[...r,R,F,{match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},{match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},$,M,O,{beginKeywords:"import",end:/$/,contains:[...r],relevance:0},_,...u,...c,...p,g,E,...D,...S,k,Q]}},typescript:function(e){const t=e.regex,n=function(e){const t=e.regex,n=a$,r="<>",i="</>",o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let i;">"===r&&(((e,{after:t})=>{const n="</"+e[0].slice(1);return-1!==e.input.indexOf(n,t)})(e,{after:n})||t.ignoreMatch());const o=e.input.substring(n);((i=o.match(/^\s*=/))||(i=o.match(/^\s+extends\s+/))&&0===i.index)&&t.ignoreMatch()}},s={$pattern:a$,keyword:l$,literal:u$,built_in:h$,"variable.language":f$},a="[0-9](_?[0-9])*",l=`\\.(${a})`,u="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",c={className:"number",variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${a})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:s,contains:[]},p={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},f={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},h={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},g={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},A={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},m=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,f,h,g,{match:/\$\d+/},c];d.contains=m.concat({begin:/\{/,end:/\}/,keywords:s,contains:["self"].concat(m)});const y=[].concat(A,d.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:["self"].concat(y)}]),v={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},E={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},I={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...c$,...d$]}},w={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[v],illegal:/%/},C={match:t.concat(/\b/,(_=[...p$,"super","import"].map(e=>`${e}\\s*\\(`),t.concat("(?!",_.join("|"),")")),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0};var _;const B={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},D={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},v]},S="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",k={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(S)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[v]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:I},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,f,h,g,A,{match:/\$\d+/},c,I,{scope:"attr",match:n+t.lookahead(":"),relevance:0},k,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[A,e.REGEXP_MODE,{className:"function",begin:S,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:i},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},w,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[v,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},B,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[v]},C,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},E,D,{match:/\$[(.]/}]}}(e),r=a$,i=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],o={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},s={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:i},contains:[n.exports.CLASS_REFERENCE]},a={$pattern:a$,keyword:l$.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:u$,built_in:h$.concat(i),"variable.language":f$},l={className:"meta",begin:"@"+r},u=(e,t,n)=>{const r=e.contains.findIndex(e=>e.label===t);if(-1===r)throw new Error("can not find mode to replace");e.contains.splice(r,1,n)};Object.assign(n.keywords,a),n.exports.PARAMS_CONTAINS.push(l);const c=n.contains.find(e=>"attr"===e.scope),d=Object.assign({},c,{match:t.concat(r,t.lookahead(/\s*\?:/))});return n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,c,d]),n.contains=n.contains.concat([l,o,s,d]),u(n,"shebang",e.SHEBANG()),u(n,"use_strict",{className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/}),n.contains.find(e=>"func.def"===e.label).relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n},vbnet:function(e){const t=e.regex,n=/\d{1,2}\/\d{1,2}\/\d{4}/,r=/\d{4}-\d{1,2}-\d{1,2}/,i=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,o=/\d{1,2}(:\d{1,2}){1,2}/,s={className:"literal",variants:[{begin:t.concat(/# */,t.either(r,n),/ *#/)},{begin:t.concat(/# */,o,/ *#/)},{begin:t.concat(/# */,i,/ *#/)},{begin:t.concat(/# */,t.either(r,n),/ +/,t.either(i,o),/ *#/)}]},a=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),l=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]});return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0,classNameAliases:{label:"symbol"},keywords:{keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort",type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort",literal:"true false nothing"},illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[{className:"string",begin:/"(""|[^/n])"C\b/},{className:"string",begin:/"/,end:/"/,illegal:/\n/,contains:[{begin:/""/}]},s,{className:"number",relevance:0,variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},{className:"label",begin:/^\w+:/},a,l,{className:"meta",begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,end:/$/,keywords:{keyword:"const disable else elseif enable end externalsource if region then"},contains:[l]}]}},wasm:function(e){e.regex;const t=e.COMMENT(/\(;/,/;\)/);return t.contains.push("self"),{name:"WebAssembly",keywords:{$pattern:/[\w.]+/,keyword:["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"]},contains:[e.COMMENT(/;;/,/$/),t,{match:[/(?:offset|align)/,/\s*/,/=/],className:{1:"keyword",3:"operator"}},{className:"variable",begin:/\$[\w_]+/},{match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},{begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword",3:"title.function"}},e.QUOTE_STRING_MODE,{match:/(i32|i64|f32|f64)(?!\.)/,className:"type"},{className:"keyword",match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/},{className:"number",relevance:0,match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/}]}},xml:function(e){const t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},i={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=e.inherit(i,{begin:/\(/,end:/\)/}),s=e.inherit(e.APOS_STRING_MODE,{className:"string"}),a=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),l={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:/[\p{L}0-9._:-]+/u,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[r]},{begin:/'/,end:/'/,contains:[r]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[i,a,s,o,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[i,o,a,s]}]}]},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},r,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[a]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[l],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[l],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(/</,t.lookahead(t.concat(n,t.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:l}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}},yaml:function(e){const t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},i=e.inherit(r,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),o={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},s={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},a={begin:/\{/,end:/\}/,contains:[s],illegal:"\\n",relevance:0},l={begin:"\\[",end:"\\]",contains:[s],illegal:"\\n",relevance:0},u=[{className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},o,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},a,l,{className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},r],c=[...u];return c.pop(),c.push(i),s.contains=c,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:u}}};var A$,m$;function y$(){if(m$)return A$;function e(t){return t instanceof Map?t.clear=t.delete=t.set=function(){throw new Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=function(){throw new Error("set is read-only")}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{const r=t[n],i=typeof r;"object"!==i&&"function"!==i||Object.isFrozen(r)||e(r)}),t}m$=1;class t{constructor(e){void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function n(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}function r(e,...t){const n=Object.create(null);for(const r in e)n[r]=e[r];return t.forEach(function(e){for(const t in e)n[t]=e[t]}),n}const i=e=>!!e.scope;class o{constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=n(e)}openNode(e){if(!i(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const n=e.split(".");return[`${t}${n.shift()}`,...n.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}return`${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){i(e)&&(this.buffer+="</span>")}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}}const s=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class a{constructor(){this.rootNode=s(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){const t=s({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return"string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{a._collapse(e)}))}}class l extends a{constructor(e){super(),this.options=e}addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){const n=e.root;t&&(n.scope=`language:${t}`),this.add(n)}toHTML(){return new o(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function u(e){return e?"string"==typeof e?e:e.source:null}function c(e){return f("(?=",e,")")}function d(e){return f("(?:",e,")*")}function p(e){return f("(?:",e,")?")}function f(...e){return e.map(e=>u(e)).join("")}function h(...e){const t=function(e){const t=e[e.length-1];return"object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return"("+(t.capture?"":"?:")+e.map(e=>u(e)).join("|")+")"}function g(e){return new RegExp(e.toString()+"|").exec("").length-1}const A=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function m(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;const t=n;let r=u(e),i="";for(;r.length>0;){const e=A.exec(r);if(!e){i+=r;break}i+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?i+="\\"+String(Number(e[1])+t):(i+=e[0],"("===e[0]&&n++)}return i}).map(e=>`(${e})`).join(t)}const y="[a-zA-Z]\\w*",b="[a-zA-Z_]\\w*",v="\\b\\d+(\\.\\d+)?",E="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",I="\\b(0b[01]+)",w={begin:"\\\\[\\s\\S]",relevance:0},C={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[w]},_={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[w]},B=function(e,t,n={}){const i=r({scope:"comment",begin:e,end:t,contains:[]},n);i.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const o=h("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return i.contains.push({begin:f(/[ ]+/,"(",o,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),i},D=B("//","$"),S=B("/\\*","\\*/"),k=B("#","$"),x={scope:"number",begin:v,relevance:0},Q={scope:"number",begin:E,relevance:0},N={scope:"number",begin:I,relevance:0},T={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[w,{begin:/\[/,end:/\]/,relevance:0,contains:[w]}]},R={scope:"title",begin:y,relevance:0},F={scope:"title",begin:b,relevance:0},M={begin:"\\.\\s*"+b,relevance:0};var O=Object.freeze({__proto__:null,APOS_STRING_MODE:C,BACKSLASH_ESCAPE:w,BINARY_NUMBER_MODE:N,BINARY_NUMBER_RE:I,COMMENT:B,C_BLOCK_COMMENT_MODE:S,C_LINE_COMMENT_MODE:D,C_NUMBER_MODE:Q,C_NUMBER_RE:E,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:k,IDENT_RE:y,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:M,NUMBER_MODE:x,NUMBER_RE:v,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:_,REGEXP_MODE:T,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=f(t,/.*\b/,e.binary,/\b.*/)),r({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch()}},e)},TITLE_MODE:R,UNDERSCORE_IDENT_RE:b,UNDERSCORE_TITLE_MODE:F});function $(e,t){"."===e.input[e.index-1]&&t.ignoreMatch()}function L(e,t){void 0!==e.className&&(e.scope=e.className,delete e.className)}function P(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=$,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0))}function j(e,t){Array.isArray(e.illegal)&&(e.illegal=h(...e.illegal))}function U(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function z(e,t){void 0===e.relevance&&(e.relevance=1)}const G=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]}),e.keywords=n.keywords,e.begin=f(n.beforeMatch,c(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:!0})]},e.relevance=0,delete n.beforeMatch},H=["of","and","for","in","not","or","if","then","parent","list","value"];function W(e,t,n="keyword"){const r=Object.create(null);return"string"==typeof e?i(n,e.split(" ")):Array.isArray(e)?i(n,e):Object.keys(e).forEach(function(n){Object.assign(r,W(e[n],t,n))}),r;function i(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){const n=t.split("|");r[n[0]]=[e,q(n[0],n[1])]})}}function q(e,t){return t?Number(t):function(e){return H.includes(e.toLowerCase())}(e)?0:1}const J={},K=e=>{console.error(e)},Z=(e,...t)=>{console.log(`WARN: ${e}`,...t)},V=(e,t)=>{J[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),J[`${e}/${t}`]=!0)},Y=new Error;function X(e,t,{key:n}){let r=0;const i=e[n],o={},s={};for(let a=1;a<=t.length;a++)s[a+r]=i[a],o[a+r]=!0,r+=g(t[a-1]);e[n]=s,e[n]._emit=o,e[n]._multi=!0}function ee(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope)}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw K("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),Y;if("object"!=typeof e.beginScope||null===e.beginScope)throw K("beginScope must be object"),Y;X(e,e.begin,{key:"beginScope"}),e.begin=m(e.begin,{joinWith:""})}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw K("skip, excludeEnd, returnEnd not compatible with endScope: {}"),Y;if("object"!=typeof e.endScope||null===e.endScope)throw K("endScope must be object"),Y;X(e,e.end,{key:"endScope"}),e.end=m(e.end,{joinWith:""})}}(e)}function te(e){function t(t,n){return new RegExp(u(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":""))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=g(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=t(m(e,{joinWith:"|"}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const n=t.findIndex((e,t)=>t>0&&void 0!==e),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class i{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++}exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else{const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=r(e.classNameAliases||{}),function n(o,s){const a=o;if(o.isCompiled)return a;[L,U,ee,G].forEach(e=>e(o,s)),e.compilerExtensions.forEach(e=>e(o,s)),o.__beforeBegin=null,[P,j,z].forEach(e=>e(o,s)),o.isCompiled=!0;let l=null;return"object"==typeof o.keywords&&o.keywords.$pattern&&(o.keywords=Object.assign({},o.keywords),l=o.keywords.$pattern,delete o.keywords.$pattern),l=l||/\w+/,o.keywords&&(o.keywords=W(o.keywords,e.case_insensitive)),a.keywordPatternRe=t(l,!0),s&&(o.begin||(o.begin=/\B|\b/),a.beginRe=t(a.begin),o.end||o.endsWithParent||(o.end=/\B|\b/),o.end&&(a.endRe=t(a.end)),a.terminatorEnd=u(a.end)||"",o.endsWithParent&&s.terminatorEnd&&(a.terminatorEnd+=(o.end?"|":"")+s.terminatorEnd)),o.illegal&&(a.illegalRe=t(o.illegal)),o.contains||(o.contains=[]),o.contains=[].concat(...o.contains.map(function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return r(e,{variants:null},t)}));if(e.cachedVariants)return e.cachedVariants;if(ne(e))return r(e,{starts:e.starts?r(e.starts):null});if(Object.isFrozen(e))return r(e);return e}("self"===e?o:e)})),o.contains.forEach(function(e){n(e,a)}),o.starts&&n(o.starts,s),a.matcher=function(e){const t=new i;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(a),a}(e)}function ne(e){return!!e&&(e.endsWithParent||ne(e.starts))}class re extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t}}const ie=n,oe=r,se=Symbol("nomatch"),ae=function(n){const r=Object.create(null),i=Object.create(null),o=[];let s=!0;const a="Could not find the language '{}', did you forget to load/include a language module?",u={disableAutodetect:!0,name:"Plain text",contains:[]};let g={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:l};function A(e){return g.noHighlightRe.test(e)}function m(e,t,n){let r="",i="";"object"==typeof t?(r=e,n=t.ignoreIllegals,i=t.language):(V("10.7.0","highlight(lang, code, ...args) has been deprecated."),V("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),i=e,r=t),void 0===n&&(n=!0);const o={code:r,language:i};B("before:highlight",o);const s=o.result?o.result:y(o.language,o.code,n);return s.code=o.code,B("after:highlight",s),s}function y(e,n,i,o){const l=Object.create(null);function u(e,t){return e.keywords[t]}function c(){if(!D.keywords)return void k.addText(x);let e=0;D.keywordPatternRe.lastIndex=0;let t=D.keywordPatternRe.exec(x),n="";for(;t;){n+=x.substring(e,t.index);const r=C.case_insensitive?t[0].toLowerCase():t[0],i=u(D,r);if(i){const[e,o]=i;if(k.addText(n),n="",l[r]=(l[r]||0)+1,l[r]<=7&&(Q+=o),e.startsWith("_"))n+=t[0];else{const n=C.classNameAliases[e]||e;p(t[0],n)}}else n+=t[0];e=D.keywordPatternRe.lastIndex,t=D.keywordPatternRe.exec(x)}n+=x.substring(e),k.addText(n)}function d(){null!=D.subLanguage?function(){if(""===x)return;let e=null;if("string"==typeof D.subLanguage){if(!r[D.subLanguage])return void k.addText(x);e=y(D.subLanguage,x,!0,S[D.subLanguage]),S[D.subLanguage]=e._top}else e=b(x,D.subLanguage.length?D.subLanguage:null);D.relevance>0&&(Q+=e.relevance),k.__addSublanguage(e._emitter,e.language)}():c(),x=""}function p(e,t){""!==e&&(k.startScope(t),k.addText(e),k.endScope())}function f(e,t){let n=1;const r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}const r=C.classNameAliases[e[n]]||e[n],i=t[n];r?p(i,r):(x=i,c(),x=""),n++}}function h(e,t){return e.scope&&"string"==typeof e.scope&&k.openNode(C.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(p(x,C.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),x=""):e.beginScope._multi&&(f(e.beginScope,t),x="")),D=Object.create(e,{parent:{value:D}}),D}function A(e,n,r){let i=function(e,t){const n=e&&e.exec(t);return n&&0===n.index}(e.endRe,r);if(i){if(e["on:end"]){const r=new t(e);e["on:end"](n,r),r.isMatchIgnored&&(i=!1)}if(i){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return A(e.parent,n,r)}function m(e){return 0===D.matcher.regexIndex?(x+=e[0],1):(R=!0,0)}function v(e){const t=e[0],r=n.substring(e.index),i=A(D,e,r);if(!i)return se;const o=D;D.endScope&&D.endScope._wrap?(d(),p(t,D.endScope._wrap)):D.endScope&&D.endScope._multi?(d(),f(D.endScope,e)):o.skip?x+=t:(o.returnEnd||o.excludeEnd||(x+=t),d(),o.excludeEnd&&(x=t));do{D.scope&&k.closeNode(),D.skip||D.subLanguage||(Q+=D.relevance),D=D.parent}while(D!==i.parent);return i.starts&&h(i.starts,e),o.returnEnd?0:t.length}let E={};function I(r,o){const a=o&&o[0];if(x+=r,null==a)return d(),0;if("begin"===E.type&&"end"===o.type&&E.index===o.index&&""===a){if(x+=n.slice(o.index,o.index+1),!s){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=E.rule,t}return 1}if(E=o,"begin"===o.type)return function(e){const n=e[0],r=e.rule,i=new t(r),o=[r.__beforeBegin,r["on:begin"]];for(const t of o)if(t&&(t(e,i),i.isMatchIgnored))return m(n);return r.skip?x+=n:(r.excludeBegin&&(x+=n),d(),r.returnBegin||r.excludeBegin||(x=n)),h(r,e),r.returnBegin?0:n.length}(o);if("illegal"===o.type&&!i){const e=new Error('Illegal lexeme "'+a+'" for mode "'+(D.scope||"<unnamed>")+'"');throw e.mode=D,e}if("end"===o.type){const e=v(o);if(e!==se)return e}if("illegal"===o.type&&""===a)return x+="\n",1;if(T>1e5&&T>3*o.index){throw new Error("potential infinite loop, way more iterations than matches")}return x+=a,a.length}const C=w(e);if(!C)throw K(a.replace("{}",e)),new Error('Unknown language: "'+e+'"');const _=te(C);let B="",D=o||_;const S={},k=new g.__emitter(g);!function(){const e=[];for(let t=D;t!==C;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>k.openNode(e))}();let x="",Q=0,N=0,T=0,R=!1;try{if(C.__emitTokens)C.__emitTokens(n,k);else{for(D.matcher.considerAll();;){T++,R?R=!1:D.matcher.considerAll(),D.matcher.lastIndex=N;const e=D.matcher.exec(n);if(!e)break;const t=I(n.substring(N,e.index),e);N=e.index+t}I(n.substring(N))}return k.finalize(),B=k.toHTML(),{language:e,value:B,relevance:Q,illegal:!1,_emitter:k,_top:D}}catch(F){if(F.message&&F.message.includes("Illegal"))return{language:e,value:ie(n),illegal:!0,relevance:0,_illegalBy:{message:F.message,index:N,context:n.slice(N-100,N+100),mode:F.mode,resultSoFar:B},_emitter:k};if(s)return{language:e,value:ie(n),illegal:!1,relevance:0,errorRaised:F,_emitter:k,_top:D};throw F}}function b(e,t){t=t||g.languages||Object.keys(r);const n=function(e){const t={value:ie(e),illegal:!1,relevance:0,_top:u,_emitter:new g.__emitter(g)};return t._emitter.addText(e),t}(e),i=t.filter(w).filter(_).map(t=>y(t,e,!1));i.unshift(n);const o=i.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(w(e.language).supersetOf===t.language)return 1;if(w(t.language).supersetOf===e.language)return-1}return 0}),[s,a]=o,l=s;return l.secondBest=a,l}function v(e){let t=null;const n=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const n=g.languageDetectRe.exec(t);if(n){const t=w(n[1]);return t||(Z(a.replace("{}",n[1])),Z("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}return t.split(/\s+/).find(e=>A(e)||w(e))}(e);if(A(n))return;if(B("before:highlightElement",{el:e,language:n}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(g.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),g.throwUnescapedHTML)){throw new re("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const r=t.textContent,o=n?m(r,{language:n,ignoreIllegals:!0}):b(r);e.innerHTML=o.value,e.dataset.highlighted="yes",function(e,t,n){const r=t&&i[t]||n;e.classList.add("hljs"),e.classList.add(`language-${r}`)}(e,n,o.language),e.result={language:o.language,re:o.relevance,relevance:o.relevance},o.secondBest&&(e.secondBest={language:o.secondBest.language,relevance:o.secondBest.relevance}),B("after:highlightElement",{el:e,result:o,text:r})}let E=!1;function I(){if("loading"===document.readyState)return E||window.addEventListener("DOMContentLoaded",function(){I()},!1),void(E=!0);document.querySelectorAll(g.cssSelector).forEach(v)}function w(e){return e=(e||"").toLowerCase(),r[e]||r[i[e]]}function C(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{i[e.toLowerCase()]=t})}function _(e){const t=w(e);return t&&!t.disableAutodetect}function B(e,t){const n=e;o.forEach(function(e){e[n]&&e[n](t)})}Object.assign(n,{highlight:m,highlightAuto:b,highlightAll:I,highlightElement:v,highlightBlock:function(e){return V("10.7.0","highlightBlock will be removed entirely in v12.0"),V("10.7.0","Please use highlightElement now."),v(e)},configure:function(e){g=oe(g,e)},initHighlighting:()=>{I(),V("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")},initHighlightingOnLoad:function(){I(),V("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")},registerLanguage:function(e,t){let i=null;try{i=t(n)}catch(o){if(K("Language definition for '{}' could not be registered.".replace("{}",e)),!s)throw o;K(o),i=u}i.name||(i.name=e),r[e]=i,i.rawDefinition=t.bind(null,n),i.aliases&&C(i.aliases,{languageName:e})},unregisterLanguage:function(e){delete r[e];for(const t of Object.keys(i))i[t]===e&&delete i[t]},listLanguages:function(){return Object.keys(r)},getLanguage:w,registerAliases:C,autoDetection:_,inherit:oe,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t))}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t))})}(e),o.push(e)},removePlugin:function(e){const t=o.indexOf(e);-1!==t&&o.splice(t,1)}}),n.debugMode=function(){s=!1},n.safeMode=function(){s=!0},n.versionString="11.11.1",n.regex={concat:f,lookahead:c,either:h,optional:p,anyNumberOfTimes:d};for(const t in O)"object"==typeof O[t]&&e(O[t]);return Object.assign(n,O),n},le=ae({});return le.newInstance=()=>ae({}),A$=le,le.HighlightJS=le,le.default=le,A$}const b$=e(y$()),v$={};function E$(e){const t=b$.newInstance();return e&&i(e),{highlight:n,highlightAuto:function(e,i){const o=(i||v$).subset||r();let s,a=-1,l=0;for(;++a<o.length;){const r=o[a];if(!t.getLanguage(r))continue;const u=n(r,e,i);u.data&&void 0!==u.data.relevance&&u.data.relevance>l&&(l=u.data.relevance,s=u)}return s||{type:"root",children:[],data:{language:void 0,relevance:l}}},listLanguages:r,register:i,registerAlias:function(e,n){if("string"==typeof e)t.registerAliases("string"==typeof n?n:[...n],{languageName:e});else{let n;for(n in e)if(Object.hasOwn(e,n)){const r=e[n];t.registerAliases("string"==typeof r?r:[...r],{languageName:n})}}},registered:function(e){return Boolean(t.getLanguage(e))}};function n(e,n,r){const i=r||v$,o="string"==typeof i.prefix?i.prefix:"hljs-";if(!t.getLanguage(e))throw new Error("Unknown language: `"+e+"` is not registered");t.configure({__emitter:I$,classPrefix:o});const s=t.highlight(n,{ignoreIllegals:!0,language:e});if(s.errorRaised)throw new Error("Could not highlight with `Highlight.js`",{cause:s.errorRaised});const a=s._emitter.root,l=a.data;return l.language=s.language,l.relevance=s.relevance,a}function r(){return t.listLanguages()}function i(e,n){if("string"==typeof e)t.registerLanguage(e,n);else{let n;for(n in e)Object.hasOwn(e,n)&&t.registerLanguage(n,e[n])}}}class I${constructor(e){this.options=e,this.root={type:"root",children:[],data:{language:void 0,relevance:0}},this.stack=[this.root]}addText(e){if(""===e)return;const t=this.stack[this.stack.length-1],n=t.children[t.children.length-1];n&&"text"===n.type?n.value+=e:t.children.push({type:"text",value:e})}startScope(e){this.openNode(String(e))}endScope(){this.closeNode()}__addSublanguage(e,t){const n=this.stack[this.stack.length-1],r=e.root.children;t?n.children.push({type:"element",tagName:"span",properties:{className:[t]},children:r}):n.children.push(...r)}openNode(e){const t=this,n={type:"element",tagName:"span",properties:{className:e.split(".").map(function(e,n){return n?e+"_".repeat(n):t.options.classPrefix+e})},children:[]};this.stack[this.stack.length-1].children.push(n),this.stack.push(n)}closeNode(){this.stack.pop()}finalize(){}toHTML(){return""}}const w$=E$(g$);function C$({fileName:e,diffContent:t,maxHeight:n,maxWidth:r,terminalWidth:i,tabWidth:o=4}){const s=oO(i),a=qe.useMemo(()=>s.getConstrainedContentWidth(),[s]);if(!t||"string"!=typeof t)return We.jsx(xi,{color:RM,children:"No diff content."});const l=function(e){const t=e.split("\n"),n=[];let r=0,i=0,o=!1;const s=/^@@ -(\d+),?\d* \+(\d+),?\d* @@/;for(const a of t){const e=a.match(s);if(e){const[,t="0",s="0"]=e;r=parseInt(t,10),i=parseInt(s,10),o=!0,n.push({type:"hunk",content:a}),r--,i--;continue}if(o)a.startsWith("+")?(i++,n.push({type:"add",newLine:i,content:a.substring(1)})):a.startsWith("-")?(r++,n.push({type:"del",oldLine:r,content:a.substring(1)})):a.startsWith(" ")?(r++,i++,n.push({type:"context",oldLine:r,newLine:i,content:a.substring(1)})):a.startsWith("\\")&&n.push({type:"other",content:a});else if(a.startsWith("--- ")||a.startsWith("+++ ")||a.startsWith("diff --git")||a.startsWith("index ")||a.startsWith("similarity index")||a.startsWith("rename from")||a.startsWith("rename to")||a.startsWith("new file mode")||a.startsWith("deleted file mode"))continue}return n}(t);if(0===l.length)return We.jsx(ki,{borderStyle:"round",borderColor:QM,padding:1,children:We.jsx(xi,{color:QM,children:"No changes detected."})});let u;if(l.every(e=>"add"===e.type||"hunk"===e.type||"other"===e.type||e.content.startsWith("diff --git")||e.content.startsWith("new file mode"))){const t=l.filter(e=>"add"===e.type).map(e=>e.content).join("\n"),i=e?.split(".").pop()||null;u=function(e,t,n,r){const i=e.replace(/\n$/,"");try{let e=i.split("\n");const o=String(e.length).length;let s=0;if(void 0!==n&&(n=Math.max(n,5),e.length>n)){const t=e.length-n;s=t,e=e.slice(t)}const a=e=>t&&w$.registered(t)?w$.highlight(t,e):w$.highlightAuto(e);return We.jsx(ZM,{maxHeight:n??50,maxWidth:r,children:e.map((e,t)=>{const n=B$(a(e),void 0),r=null!==n?n:e;return We.jsxs(ki,{children:[We.jsx(xi,{color:QM,children:`${String(t+1+s).padStart(o," ")} `}),We.jsx(xi,{color:xM,wrap:"wrap",children:r})]},t)})})}catch(qK){ex.error(`[colorizeCode] Error highlighting code for language "${t}":`,qK);const o=i.split("\n"),s=String(o.length).length;return We.jsx(ZM,{maxHeight:n,maxWidth:r,children:o.map((e,t)=>We.jsxs(ki,{children:[We.jsx(xi,{color:xM,children:`${String(t+1).padStart(s," ")} `}),We.jsx(xi,{color:QM,children:e})]},t))})}}(t,i?{js:"javascript",ts:"typescript",jsx:"javascript",tsx:"typescript",py:"python",json:"json",css:"css",html:"html",sh:"bash",bash:"bash",md:"markdown",yaml:"yaml",yml:"yaml",txt:"plaintext",java:"java",c:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",rb:"ruby",go:"go",rs:"rust",php:"php",xml:"xml",sql:"sql"}[i]||null:null,n,r||a)}else u=_$(l,e,o,n,i,r||a);return u}const _$=(e,t,n,r,i,o)=>{const s=e.map(e=>({...e,content:e.content.replace(/\t/g," ".repeat(n))})).filter(e=>"hunk"!==e.type&&"other"!==e.type);if(0===s.length)return We.jsx(ki,{borderStyle:"round",borderColor:QM,padding:1,children:We.jsx(xi,{color:QM,children:"No changes detected."})});let a=1/0;for(const c of s){if(""===c.content.trim())continue;const e=c.content.search(/\S/),t=-1===e?0:e;a=Math.min(a,t)}isFinite(a)||(a=0);const l=t?`diff-box-${t}`:`diff-box-${ge.createHash("sha1").update(JSON.stringify(e)).digest("hex")}`;let u=null;return We.jsx(ZM,{maxHeight:r??50,maxWidth:o,children:s.reduce((e,t,n)=>{let r=null;"add"===t.type||"context"===t.type?r=t.newLine??null:"del"===t.type&&(r=t.oldLine??null),null!==u&&null!==r&&r>u+5+1&&e.push(We.jsx(ki,{children:We.jsx(xi,{wrap:"truncate",children:"═".repeat(i)})},`gap-${n}`));const o=`diff-line-${n}`;let s,l="",c=" ",d=!1;switch(t.type){case"add":l=(t.newLine??"").toString(),s=NM,c="+",u=t.newLine??null;break;case"del":l=(t.oldLine??"").toString(),s=TM,c="-",void 0!==t.oldLine&&(u=t.oldLine);break;case"context":l=(t.newLine??"").toString(),d=!0,c=" ",u=t.newLine??null;break;default:return e}const p=t.content.substring(a);return e.push(We.jsxs(ki,{flexDirection:"row",children:[We.jsxs(xi,{color:QM,children:[l.padEnd(4)," "]}),We.jsxs(xi,{color:s,dimColor:d,children:[c," "]}),We.jsx(xi,{color:s,dimColor:d,wrap:"wrap",children:p})]},o)),e},[])},l)};function B$(e,t){if("text"===e.type)return We.jsx(xi,{color:t,children:e.value});if("element"===e.type){const n=e.properties?.className||[];let r;for(let e=n.length-1;e>=0;e--){const t=n[e];if(t&&(r=D$(t),r))break}const i=r||t,o=e.children?.map((e,t)=>We.jsx(Je.Fragment,{children:B$(e,i)},t));return We.jsx(Je.Fragment,{children:o})}return"root"===e.type&&e.children&&0!==e.children.length?e.children?.map((e,n)=>We.jsx(Je.Fragment,{children:B$(e,t)},n)):null}function D$(e){return{"hljs-keyword":FM,"hljs-built_in":FM,"hljs-type":FM,"hljs-literal":FM,"hljs-string":NM,"hljs-regexp":NM,"hljs-number":RM,"hljs-comment":QM,"hljs-quote":QM,"hljs-function":MM,"hljs-title":MM,"hljs-variable":xM,"hljs-name":xM,"hljs-operator":OM,"hljs-punctuation":OM,"hljs-meta":TM,"hljs-tag":TM}[e]}const S$="pending",k$="in_progress",x$="completed",Q$="cancelled",N$="high",T$="medium",R$="low",F$=ug({id:mh().describe("Unique identifier for the todo item"),content:mh().describe("Brief description of the task"),status:_g([S$,k$,x$,Q$]).describe("Current status of the task"),priority:_g([N$,T$,R$]).default(T$).describe("Priority level of the task"),createdAt:mh().optional().describe("When the todo was created (ISO string)"),completedAt:mh().optional().describe("When the todo was completed (ISO string)")}),M$=ug({todos:ag(F$).describe("The updated todo list")});function O$(e){if(0===e.length)return"creating";const t={pending:0,inProgress:0,completed:0,cancelled:0};e.forEach(e=>{switch(e.status){case S$:t.pending++;break;case k$:t.inProgress++;break;case x$:t.completed++;break;case Q$:t.cancelled++}});return 0===t.pending+t.inProgress?"completing":t.pending===e.length?"creating":"updating"}function $$(e){const t={pending:0,inProgress:0,completed:0,cancelled:0};return e.forEach(e=>{switch(e.status){case S$:t.pending++;break;case k$:t.inProgress++;break;case x$:t.completed++;break;case Q$:t.cancelled++}}),{todos:e,totalCount:e.length,pendingCount:t.pending,inProgressCount:t.inProgress,completedCount:t.completed,cancelledCount:t.cancelled,phase:O$(e)}}function L$(e){const t=e.pendingCount+e.inProgressCount;if(0===t)return"completing"===e.phase?"Plan completed":"Plan";switch(e.phase){case"creating":return"Creating plan";case"completing":return"Completing plan";default:return`${t} ${1===t?"todo":"todos"}`}}function P$({todos:e,metadata:t,maxHeight:n,maxWidth:r,showPriority:i=!1,compact:o=!1}){if(0===e.length)return We.jsx(ki,{paddingX:1,children:We.jsx(xi,{color:"gray",italic:!0,children:"No todos"})});const s=r?r-8:80;return We.jsxs(ki,{flexDirection:"column",height:n,children:[e.map((e,t)=>{const n=(e=>{switch(e){case x$:return{icon:"✓",color:"green"};case k$:return{icon:"⏳",color:"yellow"};case Q$:return{icon:"✗",color:"red"};default:return{icon:"☐",color:"white"}}})(e.status),a=(e=>{switch(e){case N$:return{text:"!",color:"red"};case T$:return{text:"→",color:"yellow"};case R$:return{text:"·",color:"gray"};default:return{text:"→",color:"yellow"}}})(e.priority);let l=e.content;var u,c;return r&&(c=s,l=(u=l).length<=c?u:u.substring(0,c-3)+"..."),We.jsxs(ki,{paddingX:1,marginY:o?0:void 0,children:[We.jsx(xi,{color:n.color,children:n.icon}),i&&We.jsx(ki,{marginLeft:1,children:We.jsx(xi,{color:a.color,children:a.text})}),We.jsx(ki,{marginLeft:1,children:We.jsx(xi,{color:e.status===x$?"gray":"white",strikethrough:e.status===Q$,bold:e.status===k$,wrap:"wrap",children:l})})]},e.id)}),t&&!o&&We.jsx(ki,{paddingX:1,marginTop:1,borderTop:!0,borderStyle:"single",borderColor:"gray",children:We.jsxs(xi,{color:"gray",dimColor:!0,children:["Total: ",t.totalCount," | Pending: ",t.pendingCount," | In Progress:"," ",t.inProgressCount," | Completed: ",t.completedCount,t.cancelledCount>0&&` | Cancelled: ${t.cancelledCount}`]})})]})}function j$({tool:e,emphasis:t="medium",maxHeight:n,maxWidth:r,terminalWidth:i,showResult:o=!0,compact:s=!1,isExpanded:a=!1,onToggleExpand:l}){const u=DM(t=>e.status===SM.Executing?t.streams.get(e.toolCallId):void 0),c=(()=>{switch(t){case"high":case"medium":default:return"white";case"low":return"gray"}})(),d="high"===t,p=(e.name||"").toLowerCase(),f="todowrite"===p||"todoread"===p,h=e.result?.metadata&&(e.result.metadata.todos||e.result.metadata.todoMetadata)&&e.result?.metadata?{todos:e.result.metadata.todos||[],metadata:e.result.metadata.todoMetadata||void 0}:null,g=s&&!a?function(e){const t=(e.name||"").toLowerCase();if(!["readfile","read_file","readmanyfiles","grep","listdirectory","list_dir","glob","todowrite","todoread"].includes(t))return null;if(e.status===SM.Error)switch(t){case"readfile":case"read_file":return"Read(failed)";case"readmanyfiles":return"ReadMany(failed)";case"grep":case"glob":return"Search(failed)";case"listdirectory":case"list_dir":return"List(failed)";case"todowrite":return"TodoWrite(failed)";case"todoread":return"TodoRead(failed)";default:return null}const n=e.result;if(!n?.returnDisplay&&!n?.metadata)return null;switch(t){case"readfile":case"read_file":{const t=n.metadata?.lineCount||0,r=n.metadata?.toolParams;let i="file";return i=r&&"string"==typeof r.absolutePath?r.absolutePath.split(/[/\\]/).pop()||"file":e.description.match(/Reading (.+)/)?.[1]||e.description.match(/(.+)/)?.[1]||"file",`Read(${i})\n ⎿ Read ${t} lines (ctrl+o to expand)`}case"readmanyfiles":{const t=n.metadata?.toolParams,r=n.metadata?.fileCount||0;let i="multiple files";return i=t&&Array.isArray(t.paths)?t.paths.length<=2?t.paths.map(e=>"string"==typeof e?e.split(/[/\\]/).pop():"").join(", "):`${t.paths.length} patterns`:e.description.match(/Reading files: (.+)/)?.[1]||"multiple files",`ReadMany(${i})\n ⎿ Read ${r} file${1!==r?"s":""} (ctrl+o to expand)`}case"grep":{const t=n.metadata?.matchCount||0,r=n.metadata?.toolParams;return`Search(pattern: "${(r&&"string"==typeof r.pattern?r.pattern:void 0)||e.description.match(/Searching for "(.+?)"/)?.[1]||"pattern"}")\n ⎿ Found ${t} match${1!==t?"es":""} (ctrl+o to expand)`}case"listdirectory":case"list_dir":{const t=n.metadata?.entryCount||0,r=n.metadata?.toolParams;let i="directory";if(r){const t=("string"==typeof r.path?r.path:void 0)||("string"==typeof r.absolutePath?r.absolutePath:void 0);i=t?t.split(/[/\\]/).pop()||"directory":e.description.match(/Listing directory (.+)/)?.[1]||"directory"}else i=e.description.match(/Listing directory (.+)/)?.[1]||"directory";return`List(${i})\n ⎿ Found ${t} item${1!==t?"s":""} (ctrl+o to expand)`}case"glob":{const t=n.metadata?.matchCount||0,r=n.metadata?.toolParams;return`Search(pattern: "${(r&&"string"==typeof r.pattern?r.pattern:void 0)||e.description.match(/Searching for files matching "(.+?)"/)?.[1]||e.description.match(/'(.+?)'/)?.[1]||"pattern"}")\n ⎿ Found ${t} file${1!==t?"s":""} (ctrl+o to expand)`}case"todowrite":{const e=n.metadata?.todoMetadata||n.metadata;if(!e)return null;const t=n.metadata?.todos||e.todos||[],r=e.totalCount||t.length||0,i=e.phase||"updating";let o="updating plan";if("creating"===i?o=`creating ${r} task${1!==r?"s":""}`:"completing"===i&&(o="completing tasks"),t.length>0){const e=5,n=t.slice(0,e),i=e=>{switch(e){case"completed":return"☒";case"in_progress":return"⏳";case"cancelled":return"✗";default:return"☐"}};let s=`TodoWrite(${o})\n ⎿ ${r} todo${1!==r?"s":""}:\n${n.map(e=>` ${i(e.status)} ${e.content}`).join("\n")}`;return t.length>e&&(s+=`\n ... and ${t.length-e} more`),s}const s=[];return e.inProgressCount&&e.inProgressCount>0&&s.push(`${e.inProgressCount} in progress`),e.pendingCount&&e.pendingCount>0&&s.push(`${e.pendingCount} pending`),e.completedCount&&e.completedCount>0&&s.push(`${e.completedCount} completed`),e.cancelledCount&&e.cancelledCount>0&&s.push(`${e.cancelledCount} cancelled`),`TodoWrite(${o})\n ⎿ ${s.length>0?s.join(", "):`${r} tasks`} (ctrl+o to expand)`}case"todoread":{const e=n.metadata?.todoMetadata||n.metadata;if(!e)return null;const t=e.totalCount||0;if(0===t)return"TodoRead(current status)\n ⎿ No todos found (ctrl+o to expand)";const r=[];return e.inProgressCount&&e.inProgressCount>0&&r.push(`${e.inProgressCount} in progress`),e.pendingCount&&e.pendingCount>0&&r.push(`${e.pendingCount} pending`),e.completedCount&&e.completedCount>0&&r.push(`${e.completedCount} completed`),e.cancelledCount&&e.cancelledCount>0&&r.push(`${e.cancelledCount} cancelled`),`TodoRead(current status)\n ⎿ ${t} todos: ${r.join(", ")} (ctrl+o to expand)`}default:return null}}(e):null;if(g&&e.status!==SM.Confirming){const n=g.split("\n"),r=n[0],i=n.slice(1),o=e.status===SM.Error;return We.jsxs(ki,{flexDirection:"column",paddingX:1,children:[We.jsxs(ki,{minHeight:1,alignItems:"center",children:[We.jsx(xi,{color:o?"red":"white",children:"● "}),We.jsx(xi,{color:c,bold:"low"!==t,children:r})]}),i.map((e,t)=>We.jsx(ki,{marginLeft:0,children:We.jsx(xi,{color:"gray",children:e})},t))]})}return We.jsxs(ki,{flexDirection:"column",paddingX:1,children:[We.jsxs(ki,{minHeight:1,alignItems:"center",children:[We.jsx(xi,{color:c,bold:"low"!==t,strikethrough:e.status===SM.Cancelled,children:e.displayName}),We.jsx(ki,{marginLeft:1,children:We.jsx(xi,{color:"gray",children:e.description})}),d&&We.jsx(ki,{marginLeft:1,children:We.jsx(xi,{color:"white",children:"←"})})]}),o&&(e.result||u)&&e.status!==SM.Confirming&&We.jsxs(ki,{marginTop:1,marginLeft:3,flexDirection:"column",children:[e.status===SM.Executing&&u?.output&&We.jsx(ZM,{maxHeight:n?n-3:15,maxWidth:r?r-6:void 0,overflowDirection:"top",children:u.output.split("\n").map((e,t)=>We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:e})},t))}),e.result&&e.status!==SM.Executing&&We.jsxs(We.Fragment,{children:[f&&h&&We.jsx(P$,{todos:h.todos,metadata:h.metadata,maxHeight:n?n-3:void 0,maxWidth:r?r-6:void 0,compact:"low"===t}),!f&&e.result.diffData&&We.jsx(C$,{fileName:e.result.diffData.fileName,diffContent:e.result.diffData.content,maxHeight:n?n-3:void 0,maxWidth:r?r-6:void 0,terminalWidth:i??80}),!f&&!e.result.diffData&&e.result.returnDisplay&&We.jsx(ZM,{maxHeight:n?n-3:15,maxWidth:r?r-6:void 0,overflowDirection:"top",children:e.result.returnDisplay.split("\n").map((e,t)=>We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:e})},t))}),!f&&e.result.summary&&e.status===SM.Success&&"Tool completed successfully"!==e.result.summary&&!e.result.returnDisplay&&e.result.summary.length>10&&We.jsx(ki,{marginTop:1,children:We.jsx(xi,{color:"gray",children:e.result.summary})})]})]}),e.status===SM.Error&&!e.result?.returnDisplay&&!g&&We.jsx(ki,{marginTop:1,marginLeft:3,children:We.jsx(xi,{color:"red",children:"✖ Tool execution failed"})}),e.status===SM.Cancelled&&We.jsx(ki,{marginTop:1,marginLeft:3,children:We.jsx(xi,{color:"yellow",children:"− Operation cancelled"})})]})}function U$({items:e,initialIndex:t=0,onSelect:n,onHighlight:r,isFocused:i,showScrollArrows:o=!1,maxItemsToShow:s=10,showNumbers:a=!0}){const[l,u]=qe.useState(t),[c,d]=qe.useState(0),[p,f]=qe.useState(""),h=qe.useRef(null);qe.useEffect(()=>{u(t)},[t]),qe.useEffect(()=>{const t=Math.max(0,Math.min(l-s+1,e.length-s));l<c?d(l):l>=c+s&&d(t)},[l,e.length,c,s]),qe.useEffect(()=>()=>{h.current&&clearTimeout(h.current)},[]),Gi((t,i)=>{const o=a&&/^[0-9]$/.test(t);if(!o&&h.current&&(clearTimeout(h.current),f("")),"k"===t||i.upArrow){const t=l>0?l-1:e.length-1;return u(t),void r?.(e[t].value)}if("j"===t||i.downArrow){const t=l<e.length-1?l+1:0;return u(t),void r?.(e[t].value)}if(i.return)l>=0&&l<e.length&&n(e[l].value);else if(o){h.current&&clearTimeout(h.current);const i=p+t;f(i);const o=Number.parseInt(i,10)-1;if("0"===i)return void(h.current=setTimeout(()=>f(""),350));if(o>=0&&o<e.length){const t=e[o];u(o),r?.(t.value);Number.parseInt(i+"0",10)>e.length?(n(t.value),f("")):h.current=setTimeout(()=>{n(t.value),f("")},350)}else f("")}},{isActive:i&&e.length>0});const g=e.slice(c,c+s);return We.jsxs(ki,{flexDirection:"column",children:[o&&We.jsx(xi,{color:c>0?xM:QM,children:"▲"}),g.map((t,n)=>{const r=c+n,i=l===r;let o=xM,s=xM;i?(o=NM,s=NM):t.disabled&&(o=QM,s=QM),a||(s=QM);const u=String(e.length).length,d=`${String(r+1).padStart(u)}.`;return We.jsxs(ki,{alignItems:"center",children:[We.jsx(ki,{minWidth:2,flexShrink:0,children:We.jsx(xi,{color:i?NM:xM,children:i?"●":" "})}),We.jsx(ki,{marginRight:1,flexShrink:0,minWidth:d.length,children:We.jsx(xi,{color:s,children:d})}),t.themeNameDisplay&&t.themeTypeDisplay?We.jsxs(xi,{color:o,wrap:"truncate",children:[t.themeNameDisplay," ",We.jsx(xi,{color:QM,children:t.themeTypeDisplay})]}):We.jsx(xi,{color:o,wrap:"truncate",children:t.label})]},t.label)}),o&&We.jsx(xi,{color:c+s<e.length?xM:QM,children:"▼"})]})}const z$=qe.createContext(null);function G$({children:e}){const t=qe.useRef(null);return We.jsx(z$.Provider,{value:t,children:e})}function H$({confirmationDetails:e,onConfirm:t,isFocused:n=!0,availableTerminalHeight:r,terminalWidth:i}){const o=oO(i).getDialogContentWidth(),[s,a]=Je.useState(0),l=function(){const e=qe.useContext(z$);return e?e.current:null}(),u=[];if("edit"===e.type)u.push({label:"Yes, allow once",value:kM.ProceedOnce},{label:"Yes, allow always",value:kM.ProceedAlways},{label:"No (esc)",value:kM.Cancel});else if("exec"===e.type){const t=e;u.push({label:"Yes, allow once",value:kM.ProceedOnce},{label:`Yes, always allow "${t.rootCommand} ..."`,value:kM.ProceedAlwaysCommand},{label:"No (esc)",value:kM.Cancel})}else u.push({label:"Yes, allow once",value:kM.ProceedOnce},{label:"Yes, allow always",value:kM.ProceedAlways},{label:"No (esc)",value:kM.Cancel});Gi((e,r)=>{if(n)if(r.escape)t(kM.Cancel);else{if(r.upArrow||"k"===e)return s>0?void a(s-1):void(l&&l.scrollUp());if(r.downArrow||"j"===e)return s<u.length-1?void a(s+1):void(l&&l.scrollDown());if(r.return)t(u[s].value);else if(/^[1-9]$/.test(e)){const n=Number.parseInt(e,10)-1;if(n>=0&&n<u.length)return void t(u[n].value)}}});let c,d=null;if("edit"===e.type){const t=e;c="Apply this change?",d=We.jsx(C$,{fileName:t.fileName,diffContent:t.fileDiff,maxHeight:function(){if(0===u.length)throw new Error("Options not provided for confirmation message");if(void 0===r)return;const e=5+u.length;return Math.max(r-e,1)}(),maxWidth:o,terminalWidth:i})}else if("exec"===e.type){const t=e;c="Allow execution?",d=We.jsxs(ki,{flexDirection:"column",paddingX:1,children:[We.jsx(xi,{color:MM,children:t.command}),t.workingDirectory&&We.jsxs(xi,{color:QM,children:["Working directory: ",t.workingDirectory]})]})}else{const t=e;c="Do you want to proceed?",d=We.jsxs(ki,{flexDirection:"column",paddingX:1,children:[We.jsx(xi,{color:MM,children:t.prompt||e.description}),t.urls&&t.urls.length>0&&We.jsxs(ki,{flexDirection:"column",marginTop:1,children:[We.jsx(xi,{children:"URLs to fetch:"}),t.urls.map((e,t)=>We.jsxs(xi,{color:FM,children:[" ","- ",e]},t))]})]})}return We.jsxs(ki,{flexDirection:"column",padding:1,width:o,children:[We.jsx(ki,{flexGrow:1,flexShrink:1,overflow:"hidden",marginBottom:1,children:d}),We.jsx(ki,{marginBottom:1,flexShrink:0,children:We.jsx(xi,{wrap:"truncate",children:c})}),We.jsx(ki,{flexShrink:0,children:We.jsx(U$,{items:u,initialIndex:s,onSelect:e=>t(e),onHighlight:e=>{const t=u.findIndex(t=>t.value===e);-1!==t&&a(t)},isFocused:!1})})]})}function W$(e,t){if(void 0===t)return;let n=0;for(const i of e.tools)(i.result?.returnDisplay||i.result?.diffData)&&n++;const r=e.tools.length-n;return Math.max(3,Math.floor((t-2-r)/Math.max(1,n)))}function q$({toolGroup:e,onConfirm:t,isFocused:n=!0,maxHeight:r,maxWidth:i,terminalWidth:o}){const[s,a]=qe.useState(new Set),l=qe.useMemo(()=>i??(e=>e<100?Math.floor(.9*e):e<160?Math.min(140,Math.floor(.88*e)):Math.min(200,Math.floor(.85*e)))(o),[i,o]),u=oO(o);qe.useMemo(()=>u.getConstrainedContentWidth(4),[u]);const c=e.tools.some(e=>e.status===SM.Executing||e.status===SM.Confirming||e.status===SM.Pending),d=e.tools.some(e=>"shell"===e.name||e.name.includes("shell")),p=c||d?RM:"error"===e.status?TM:"completed"===e.status?QM:FM,f=e.tools.find(e=>e.status===SM.Confirming),h=W$(e,r),g=e.tools.some(e=>{const t=(e.name||"").toLowerCase();return["readfile","read_file","readmanyfiles","grep","listdirectory","list_dir","glob","todowrite","todoread"].includes(t)}),A=("completed"===e.status||"error"===e.status)&&g&&!e.tools.some(e=>e.status===SM.Confirming);return We.jsx(ki,{flexDirection:"column",borderStyle:A?void 0:"round",borderColor:A?void 0:p,width:l,marginLeft:A?0:1,height:r,children:e.tools.map(e=>{const r=f?.id===e.id,i=r?"high":f?"low":"medium",u=s.has(e.id);return We.jsxs(ki,{flexDirection:"column",children:[We.jsx(j$,{tool:e,emphasis:i,maxHeight:h,maxWidth:l-4,terminalWidth:o,compact:A,isExpanded:u,onToggleExpand:()=>{return t=e.id,void a(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n});var t}}),e.status===SM.Confirming&&r&&e.confirmationDetails&&t&&We.jsx(H$,{confirmationDetails:e.confirmationDetails,onConfirm:n=>t(e.id,n),isFocused:n,availableTerminalHeight:h,terminalWidth:o})]},e.id)})})}const J$=E$(g$),K$={"hljs-keyword":"magenta","hljs-string":"green","hljs-number":"cyan","hljs-comment":"gray","hljs-function":"yellow","hljs-variable":"blue","hljs-type":"cyan","hljs-built_in":"magenta","hljs-literal":"cyan","hljs-title":"yellow","hljs-attr":"blue","hljs-attribute":"blue","hljs-name":"red","hljs-tag":"red","hljs-selector-tag":"red","hljs-selector-class":"blue","hljs-selector-id":"yellow"};function Z$(e,t){if("text"===e.type)return We.jsx(xi,{color:t,children:e.value});if("element"===e.type){const n=e.properties?.className||[];let r;for(let e=n.length-1;e>=0;e--){const t=K$[n[e]];if(t){r=t;break}}const i=r||t,o=e.children?.map((e,t)=>We.jsx(Je.Fragment,{children:Z$(e,i)},t));return We.jsx(Je.Fragment,{children:o})}return"root"===e.type&&e.children&&0!==e.children.length?e.children?.map((e,n)=>We.jsx(Je.Fragment,{children:Z$(e,t)},n)):null}const V$=(e,t,n,r)=>{const i=e.replace(/\n$/,"");try{let e=i.split("\n");const r=String(e.length).length;let o=0;if(void 0!==n){const t=Math.max(n,2);if(e.length>t){const n=e.length-t;o=n,e=e.slice(n)}}const s=e=>t&&J$.registered(t)?J$.highlight(t,e):J$.highlightAuto(e);return We.jsxs(ki,{flexDirection:"column",children:[o>0&&We.jsxs(xi,{color:"gray",children:["... first ",o," lines hidden ..."]}),e.map((e,t)=>{const n=Z$(s(e),void 0),i=null!==n?n:e;return We.jsxs(ki,{children:[We.jsx(xi,{color:"gray",children:`${String(t+1+o).padStart(r," ")} `}),We.jsx(xi,{wrap:"wrap",children:i})]},t)})]})}catch(qK){ex.error(`[colorizeCode] Error highlighting code for language "${t}":`,qK);const n=i.split("\n"),r=String(n.length).length;return We.jsx(ki,{flexDirection:"column",children:n.map((e,t)=>We.jsxs(ki,{children:[We.jsx(xi,{color:"gray",children:`${String(t+1).padStart(r," ")} `}),We.jsx(xi,{children:e})]},t))})}},Y$=Je.memo(({text:e})=>{const t=[];let n=0;const r=/(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>)/g;let i;for(;null!==(i=r.exec(e));){i.index>n&&t.push(We.jsx(xi,{children:e.slice(n,i.index)},`t-${n}`));const s=i[0];let a=null;const l=`m-${i.index}`;try{if(s.startsWith("**")&&s.endsWith("**")&&s.length>4)a=We.jsx(xi,{bold:!0,children:s.slice(2,-2)},l);else if(!(s.length>2&&(s.startsWith("*")&&s.endsWith("*")||s.startsWith("_")&&s.endsWith("_")))||/\w/.test(e.substring(i.index-1,i.index))||/\w/.test(e.substring(r.lastIndex,r.lastIndex+1))||/\S[./\\]/.test(e.substring(i.index-2,i.index))||/[./\\]\S/.test(e.substring(r.lastIndex,r.lastIndex+2)))if(s.startsWith("~~")&&s.endsWith("~~")&&s.length>4)a=We.jsx(xi,{strikethrough:!0,children:s.slice(2,-2)},l);else if(s.startsWith("`")&&s.endsWith("`")&&s.length>1){const e=s.match(/^(`+)(.+?)\1$/s);e&&e[2]&&(a=We.jsx(xi,{color:"blue",children:e[2]},l))}else if(s.startsWith("[")&&s.includes("](")&&s.endsWith(")")){const e=s.match(/\[(.*?)\]\((.*?)\)/);if(e){const t=e[1],n=e[2];a=We.jsxs(xi,{children:[t,We.jsxs(xi,{color:"blue",children:[" (",n,")"]})]},l)}}else s.startsWith("<u>")&&s.endsWith("</u>")&&s.length>6&&(a=We.jsx(xi,{underline:!0,children:s.slice(3,-4)},l));else a=We.jsx(xi,{italic:!0,children:s.slice(1,-1)},l)}catch(o){ex.error("Error parsing inline markdown part:",s,o),a=null}t.push(a??We.jsx(xi,{children:s},l)),n=r.lastIndex}return n<e.length&&t.push(We.jsx(xi,{children:e.slice(n)},`t-${n}`)),We.jsx(We.Fragment,{children:t.filter(e=>null!==e)})}),X$=e=>HM(e.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/`(.*?)`/g,"$1").replace(/<u>(.*?)<\/u>/g,"$1").replace(/\[(.*?)\]\(.*?\)/g,"$1")),eL=({headers:e,rows:t,terminalWidth:n})=>{const r=Math.max(n-4,20),i=e.map((e,n)=>{const r=X$(e),i=Math.max(...t.map(e=>X$(e[n]||"")));return Math.max(r,i)+4}),o=i.reduce((e,t)=>e+t+1,1),s=o>r?r/o:1,a=i.map(e=>Math.floor(e*s)),l=e=>{const t={top:{left:"┌",middle:"┬",right:"┐",horizontal:"─"},middle:{left:"├",middle:"┼",right:"┤",horizontal:"─"},bottom:{left:"└",middle:"┴",right:"┘",horizontal:"─"}}[e],n=a.map(e=>t.horizontal.repeat(Math.max(1,e))),r=t.left+n.join(t.middle)+t.right;return We.jsx(xi,{color:"cyan",children:r})},u=(e,t=!1)=>{const n=e.map((e,n)=>((e,t,n=!1)=>{const r=Math.max(0,t);let i=e;if(X$(e)>r)if(r<=3)i=e.substring(0,Math.min(e.length,r));else{let t=0,n=e.length,o=e;for(;t<=n;){const i=Math.floor((t+n)/2),s=e.substring(0,i);X$(s)<=r-3?(o=s,t=i+1):n=i-1}i=o+"..."}return We.jsx(ki,{minWidth:t,paddingX:1,children:n?We.jsx(xi,{bold:!0,color:"cyan",children:i}):We.jsx(xi,{children:i})})})(e||"",a[n]||0,t));return We.jsxs(ki,{flexDirection:"row",children:[We.jsx(xi,{color:"cyan",children:"│"}),n.map((e,t)=>We.jsxs(Je.Fragment,{children:[e,We.jsx(xi,{color:"cyan",children:"│"})]},t))]})};return We.jsxs(ki,{flexDirection:"column",marginY:1,children:[l("top"),u(e,!0),l("middle"),t.map((e,t)=>We.jsx(Je.Fragment,{children:u(e)},t)),l("bottom")]})},tL=Je.memo(({content:e,lang:t,isPending:n,availableTerminalHeight:r,terminalWidth:i})=>{if(n&&void 0!==r){const n=Math.max(0,r-2);if(e.length>n){if(n<1)return We.jsx(ki,{paddingLeft:1,children:We.jsx(xi,{color:"gray",children:"... code is being written ..."})});const o=e.slice(0,n),s=V$(o.join("\n"),t,r,i-1);return We.jsxs(ki,{paddingLeft:1,flexDirection:"column",children:[s,We.jsx(xi,{color:"gray",children:"... generating more ..."})]})}}const o=e.join("\n"),s=V$(o,t,r,i-1);return We.jsx(ki,{paddingLeft:1,flexDirection:"column",width:i,flexShrink:0,children:s})}),nL=Je.memo(({itemText:e,type:t,marker:n,leadingWhitespace:r=""})=>{const i="ol"===t?`${n}. `:`${n} `,o=i.length,s=r.length;return We.jsxs(ki,{paddingLeft:s+1,flexDirection:"row",children:[We.jsx(ki,{width:o,children:We.jsx(xi,{children:i})}),We.jsx(ki,{flexGrow:1,children:We.jsx(xi,{wrap:"wrap",children:We.jsx(Y$,{text:e})})})]})}),rL=Je.memo(({headers:e,rows:t,terminalWidth:n})=>We.jsx(eL,{headers:e,rows:t,terminalWidth:n})),iL=Je.memo(({text:e,isPending:t,terminalWidth:n,availableTerminalHeight:r})=>{if(!e)return We.jsx(We.Fragment,{});const i=e.split("\n"),o=/^ *(#{1,4}) +(.*)/,s=/^ *(`{3,}|~{3,}) *(\w*?) *$/,a=/^([ \t]*)([-*+]) +(.*)/,l=/^([ \t]*)(\d+)\. +(.*)/,u=/^ *([-*_] *){3,} *$/,c=/^\s*\|(.+)\|\s*$/,d=/^\s*\|?\s*(:?-+:?)\s*(\|\s*(:?-+:?)\s*)+\|?\s*$/,p=[];let f=!1,h=!0,g=[],A=null,m="",y=!1,b=[],v=[];function E(e){e&&(p.push(e),h=!1)}return i.forEach((e,I)=>{const w=`line-${I}`;if(f){const i=e.match(s),o=i?.[1];return void(o&&m&&m[0]&&o.startsWith(m[0])&&o.length>=m.length?(E(We.jsx(tL,{content:g,lang:A,isPending:t,availableTerminalHeight:r,terminalWidth:n},w)),f=!1,g=[],A=null,m=""):g.push(e))}const C=e.match(s),_=e.match(o),B=e.match(a),D=e.match(l),S=e.match(u),k=e.match(c),x=e.match(d);if(C)f=!0,m=C[1]||"```",A=(C[2]&&C[2].length>0?C[2]:null)||null;else if(k&&!y){const t=I+1<i.length?i[I+1]:void 0;t&&d.test(t)?(y=!0,v=k[1]?k[1].split("|").map(e=>e.trim()):[],b=[]):E(We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:We.jsx(Y$,{text:e})})},w))}else if(y&&x);else if(y&&k){const e=k[1]?k[1].split("|").map(e=>e.trim()):[];for(;e.length<v.length;)e.push("");e.length>v.length&&(e.length=v.length),b.push(e)}else if(y&&!k)v.length>0&&b.length>0&&E(We.jsx(rL,{headers:v,rows:b,terminalWidth:n},`table-${p.length}`)),y=!1,b=[],v=[],e.trim().length>0&&E(We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:We.jsx(Y$,{text:e})})},w));else if(S)E(We.jsx(ki,{children:We.jsx(xi,{color:"gray",children:"---"})},w));else if(_){const e=_[1]?.length??0,t=_[2]??"";let n=null;switch(e){case 1:n=We.jsx(xi,{bold:!0,color:"cyan",children:We.jsx(Y$,{text:t})});break;case 2:n=We.jsx(xi,{bold:!0,color:"blue",children:We.jsx(Y$,{text:t})});break;case 3:n=We.jsx(xi,{bold:!0,children:We.jsx(Y$,{text:t})});break;case 4:n=We.jsx(xi,{italic:!0,color:"gray",children:We.jsx(Y$,{text:t})});break;default:n=We.jsx(xi,{children:We.jsx(Y$,{text:t})})}n&&E(We.jsx(ki,{children:n},w))}else if(B){const e=B[1]??"",t=B[2]??"-",n=B[3]??"";E(We.jsx(nL,{itemText:n,type:"ul",marker:t,leadingWhitespace:e},w))}else if(D){const e=D[1]??"",t=D[2]??"1",n=D[3]??"";E(We.jsx(nL,{itemText:n,type:"ol",marker:t,leadingWhitespace:e},w))}else 0!==e.trim().length||f?E(We.jsx(ki,{children:We.jsx(xi,{wrap:"wrap",children:We.jsx(Y$,{text:e})})},w)):h||(p.push(We.jsx(ki,{height:1},`spacer-${I}`)),h=!0)}),f&&E(We.jsx(tL,{content:g,lang:A,isPending:t,availableTerminalHeight:r,terminalWidth:n},"line-eof")),y&&v.length>0&&b.length>0&&E(We.jsx(rL,{headers:v,rows:b,terminalWidth:n},`table-${p.length}`)),We.jsx(We.Fragment,{children:p})});function oL(){const[e,t]=qe.useState({columns:(process.stdout.columns||60)-0,rows:process.stdout.rows||20}),n=qe.useRef(null);return qe.useEffect(()=>{function e(){n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{t({columns:(process.stdout.columns||60)-0,rows:process.stdout.rows||20}),n.current=null},250)}return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e),n.current&&clearTimeout(n.current)}},[]),e}const sL=/@((?:".+?[^\\]")|(?:[^\s])+)/gi;const aL=(e,t)=>{try{if("role"in e&&"tool-group"===e.role){const n=e.toolGroup;let r=2;const i=function(e){return e??50}(W$(n,void 0));for(const e of n.tools){let n=1;if((e.result||e.status===SM.Executing)&&(n+=1),e.result?.returnDisplay&&"string"==typeof e.result.returnDisplay){const t=e.result.returnDisplay.split("\n").length,r=t>i,o=Math.min(t,i);n+=o+(r?1:0)}if(e.result?.diffData?.content&&"string"==typeof e.result.diffData.content){const t=e.result.diffData.content.split("\n").length,r=t>i,o=Math.min(t,i);n+=o+(r?1:0)}if(e.status===SM.Executing){const t=DM.getState().streams.get(e.toolCallId);if(t?.output){const e=t.output.split("\n").length,r=e>i,o=Math.min(e,i);n+=o+(r?1:0)}else n+=i}if(e.status===SM.Confirming&&e.confirmationDetails){const r=2+1+1+3;let o=0;if("edit"===e.confirmationDetails.type){const t=e.confirmationDetails.fileDiff,n=t?t.split("\n").length:20;o=Math.min(n,i)}else if("exec"===e.confirmationDetails.type){const n=e.confirmationDetails,r=n.command||"",i=Math.max(40,t-20),s=Math.max(1,Math.ceil(r.length/i)),a=n.workingDirectory?1:0;o=1+s+a}else o=5;n+=r+o+1}r+=n}return r}}catch(qK){return ex.error("CRITICAL: Failed to estimate tool group height",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0}),20}const n=e;if(n.hidden)return 0;const r=(e=>{if(!("role"in e))return"";const t=e;return"string"==typeof t.content?t.content:Array.isArray(t.content)?t.content.map(e=>"text"===e.type?e.text:"").join("\n"):""})(n);if(!r||0===r.length)return 1;const i=r.split("\n");let o,s=0;o="user"===n.role?Math.max(40,t-3):"assistant"===n.role?Math.max(40,t-8):Math.max(40,t-3);for(const a of i){if(""===a.trim()){s+=1;continue}const e=HM(a.replace(/\*\*\*(.*?)\*\*\*/g,"$1").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"));s+=Math.max(1,Math.ceil(e/o))}return"user"===n.role||n.role,s+1},lL=(e,t)=>"id"in e&&e.id?`${e.id}-${t}`:"timestamp"in e&&e.timestamp?`msg-${e.timestamp}-${t}`:`message-${t}`,uL=(e,t,n)=>{const r=new Array(e.length+1).fill(0);for(let i=0;i<e.length;i++){const o=e[i];if(!o)continue;const s=lL(o,i);let a=t.get(s);void 0===a&&(a=aL(o,n),t.set(s,a)),r[i+1]=r[i]+a}return r},cL=(e,t)=>{if(0===e.length)return 0;if(t<=0)return 0;let n=0,r=e.length-1;for(;n<r;){const i=Math.floor((n+r+1)/2),o=e[i];void 0!==o&&o<=t?n=i:r=i-1}return Math.max(0,n-1)};let dL=!1,pL=!1,fL=null,hL="",gL=null;function AL(e){pL&&(hL+=e.toString(),function(){const e=/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g;let t;for(;null!==(t=e.exec(hL));){const e=Number.parseInt(t[1],10);64===e&&gL?.onScrollUp?gL.onScrollUp():65===e&&gL?.onScrollDown&&gL.onScrollDown()}const n=hL.lastIndexOf("[<");if(-1!==n){const t=hL.slice(n);hL=e.test(t)?"":t}else hL="";hL.length>100&&(hL="")}())}function mL(e,t){return"Apple_Terminal"!==process.env.TERM_PROGRAM?null:(gL={onScrollUp:e,onScrollDown:t},dL||(process.stdin.isTTY&&process.stdin.setRawMode(!0),fL=e=>{AL(e)},process.stdin.prependListener("data",fL),dL=!0,setTimeout(()=>{pL||(process.stdout.write("[?1006h[?1000h[?1007h"),pL=!0)},100)),()=>{gL=null,dL&&!gL&&(pL&&(process.stdout.write("[?1007l[?1000l[?1006l"),pL=!1,hL=""),fL&&(process.stdin.removeListener("data",fL),fL=null),dL=!1)})}const yL=(e,t)=>{switch(t.type){case"SET_INNER_HEIGHT":return{...e,innerHeight:t.innerHeight};case"SET_HEIGHT":return{...e,height:t.height};case"SCROLL_DOWN":{const t=Math.max(0,e.innerHeight-e.height),n=Math.max(3,Math.floor(.15*e.height));return{...e,scrollTop:Math.min(t,e.scrollTop+n)}}case"SCROLL_UP":{const t=Math.max(3,Math.floor(.15*e.height));return{...e,scrollTop:Math.max(0,e.scrollTop-t)}}case"SCROLL_TO_BOTTOM":return{...e,scrollTop:Math.max(0,e.innerHeight-e.height)};case"SCROLL_TO_TOP":return{...e,scrollTop:0};case"PAGE_DOWN":{const t=Math.max(0,e.innerHeight-e.height),n=Math.max(1,Math.floor(.9*e.height));return{...e,scrollTop:Math.min(t,e.scrollTop+n)}}case"PAGE_UP":{const t=Math.max(1,Math.floor(.9*e.height));return{...e,scrollTop:Math.max(0,e.scrollTop-t)}}default:return e}},bL=qe.forwardRef(({messages:e=[],children:t,focused:n=!0,onToolConfirm:r,disableArrowKeyScrolling:i=!1},o)=>{const[s,a]=qe.useReducer(yL,{height:0,scrollTop:0,innerHeight:0}),[l,u]=qe.useState(null),c=qe.useRef(null),d=qe.useRef(null),p=qe.useRef(e.length),f=qe.useRef(0),h=qe.useContext(z$);qe.useEffect(()=>(h&&(h.current={scrollUp:()=>a({type:"SCROLL_UP"}),scrollDown:()=>a({type:"SCROLL_DOWN"})}),()=>{h&&(h.current=null)}),[h]);const g=qe.useRef({cols:0,rows:0,lastMeasureTime:0}),[A,m]=function(){const{stdout:e}=Wi(),[t,n]=qe.useState([e.columns,e.rows]);return qe.useEffect(()=>{const t=()=>n([e.columns,e.rows]);return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}();qe.useImperativeHandle(o,()=>({scrollToBottom:()=>{a({type:"SCROLL_TO_BOTTOM"})}}),[]),qe.useEffect(()=>{u(null!==NT())},[]);const{selectedModel:y}=VF(),b=Math.max(0,s.innerHeight-s.height),v=s.scrollTop>=b-2,E=e.length>0,{isResponding:I}=BM(),{firebaseUser:w}=FT(),C=y?aM(cM(y.name))||uM(y.provider):null,_=qe.useRef(new Map),B=qe.useRef(new Map),D=qe.useRef(new Map),S=qe.useRef(0),k=qe.useRef(0),x=DM(e=>e.totalLineCount),Q=qe.useMemo(()=>{const t=new Map;let n=0;const r=D.current,i=e.length-1;e.forEach((e,o)=>{const s=lL(e,o),a=o===i&&I;let l=r.get(s);if(void 0===l||a)if(a){const t=Date.now();t-S.current>=1e3||0===S.current?(l=yM(e),S.current=t,k.current=l):l=k.current||yM(e)}else l=yM(e),r.set(s,l);n+=l;const u=C?dM(n,C):0;t.set(o,{tokens:n,percentage:u})});const o=new Set(e.map((e,t)=>lL(e,t)));for(const e of r.keys())o.has(e)||r.delete(e);return I||0===S.current||(S.current=0,k.current=0),t},[e,C,I]),N=qe.useMemo(()=>{const t=_.current,n=e.length-1;if(I&&n>=0){const r=e[n];if(r){const e=lL(r,n);t.delete(e)}}for(let r=0;r<e.length;r++){const n=e[r];if(n&&("role"in n&&"tool-group"===n.role)){const e=n,i=lL(n,r);let o=!1;e.toolGroup?.tools?.forEach(e=>{const t=B.current.get(e.toolCallId);void 0!==t&&t!==e.status&&(o=!0),B.current.set(e.toolCallId,e.status)});const s=e.toolGroup?.tools?.some(e=>"executing"===e.status||"confirming"===e.status);(o||s)&&t.delete(i)}}return uL(e,_.current,A)},[e,A,I]),T=qe.useMemo(()=>((e,t,n,r,i,o=15,s)=>{try{if(0===e.length)return{startIndex:0,endIndex:0,topSpacerHeight:0,visibleStartIndex:0,visibleEndIndex:0};const a=s||uL(e,r,i),l=cL(a,t),u=cL(a,t+n),c=Math.max(0,l-o),d=Math.min(e.length-1,u+o);return{startIndex:c,endIndex:d,topSpacerHeight:a[c]??0,visibleStartIndex:l,visibleEndIndex:u}}catch(qK){return ex.error("Failed to calculate virtual window",{error:qK instanceof Error?qK.message:String(qK),stack:qK instanceof Error?qK.stack:void 0,messageCount:e.length,scrollTop:t,viewportHeight:n}),{startIndex:0,endIndex:Math.max(0,e.length-1),topSpacerHeight:0,visibleStartIndex:0,visibleEndIndex:Math.max(0,e.length-1)}}})(e,s.scrollTop,s.height,_.current,A,15,N),[e,s.scrollTop,s.height,A,N]),R=qe.useMemo(()=>T.endIndex>=e.length-1?0:((e,t,n,r,i)=>{if(t>=e.length)return 0;const o=i||uL(e,n,r);return(o[e.length]??0)-(o[t]??0)})(e,T.endIndex+1,_.current,A,N),[e,T.endIndex,A,N]),F=qe.useCallback(()=>{if(c.current){const e=Ki(c.current);a({type:"SET_HEIGHT",height:e.height-2})}if(d.current){const e=Ki(d.current);a({type:"SET_INNER_HEIGHT",innerHeight:e.height})}},[]);return qe.useEffect(()=>{const e=Date.now(),t=g.current;(t.cols!==A||t.rows!==m)&&e-t.lastMeasureTime>16&&(F(),g.current={cols:A,rows:m,lastMeasureTime:e})},[A,m,F]),qe.useEffect(()=>{e.length>0&&0===p.current&&setTimeout(()=>{F()},50)},[e.length,F]),qe.useEffect(()=>{const t=Date.now(),n=t-f.current;if(!(I&&n<100)&&d.current){const n=Ki(d.current);f.current=t,a({type:"SET_INNER_HEIGHT",innerHeight:n.height});const r=e.length>p.current,i=n.height>s.innerHeight;(r||i)&&v&&setTimeout(()=>{a({type:"SCROLL_TO_BOTTOM"})},0),p.current=e.length}},[e,s.innerHeight,I,x,v]),qe.useEffect(()=>{const t=mL(()=>{e.length>0&&a({type:"SCROLL_UP"})},()=>{e.length>0&&a({type:"SCROLL_DOWN"})});return()=>{t?.()}},[e.length]),Gi((t,r)=>{if(n&&!(e.length<1))return i?r.ctrl&&"g"===t?void a({type:"SCROLL_TO_TOP"}):r.ctrl&&"G"===t?void a({type:"SCROLL_TO_BOTTOM"}):void 0:void(!r.downArrow||r.ctrl||r.shift?!r.upArrow||r.ctrl||r.shift?r.downArrow&&r.ctrl?a({type:"PAGE_DOWN"}):r.upArrow&&r.ctrl?a({type:"PAGE_UP"}):(r.pageDown&&a({type:"PAGE_DOWN"}),r.pageUp&&a({type:"PAGE_UP"}),r.ctrl&&"g"===t?a({type:"SCROLL_TO_TOP"}):r.ctrl&&"G"===t&&a({type:"SCROLL_TO_BOTTOM"})):a({type:"SCROLL_UP"}):a({type:"SCROLL_DOWN"}))}),We.jsxs(ki,{ref:c,height:"100%",flexDirection:"column",flexGrow:1,overflow:"hidden",children:[!E&&We.jsxs(ki,{flexGrow:1,justifyContent:"center",alignItems:"center",flexDirection:"column",children:[We.jsxs(xi,{color:"gray",children:["Welcome, ",w?.displayName,"!"]}),l?We.jsx(xi,{color:"gray",children:"Currently using project's EMBEDDER.md"}):We.jsx(xi,{color:"gray",children:"Type /init to create an EMBEDDER.md"})]}),E&&We.jsxs(ki,{ref:d,flexShrink:0,flexDirection:"column",marginTop:-s.scrollTop,minHeight:0,children:[T.topSpacerHeight>0&&We.jsx(ki,{height:T.topSpacerHeight,flexShrink:0}),e.slice(T.startIndex,T.endIndex+1).map((t,i)=>{const o=T.startIndex+i,s=o===e.length-1&&I,a=Q.get(o);return We.jsx(vL,{message:t,index:o,onToolConfirm:r,isFocused:n,isStreaming:s,contextInfo:a},lL(t,o))}),R>0&&We.jsx(ki,{height:R,flexShrink:0}),t]})]})});bL.displayName="ChatContainerComponent";const vL=qe.memo(function({message:e,index:t,onToolConfirm:n,isFocused:r=!0,isStreaming:i=!1,contextInfo:o}){const{columns:s}=oL();if("role"in e&&"tool-group"===e.role){const t=e;return We.jsx(ki,{marginBottom:1,flexDirection:"column",flexShrink:0,paddingLeft:2,paddingRight:1,children:We.jsx(q$,{toolGroup:t.toolGroup,onConfirm:n,isFocused:r,terminalWidth:s})})}const a=e;if(a.hidden)return null;const l="user"===a.role;a.role;const u="assistant"===a.role,{backendUser:c,firebaseUser:d}=FT(),{modeConfig:p}=JF();a.timestamp??Date.now(),a.mode;const f=qe.useMemo(()=>(e,t=!1)=>{if(t)return[We.jsx(xi,{children:e},0)];const n=[];let r=0,i=0;const o=[];[{regex:/`([^`\n]+)`/g,type:"code"},{regex:/\*\*\*([^\*\n]+?)\*\*\*/g,type:"bold-italic"},{regex:/___([^_\n]+?)___/g,type:"bold-italic"},{regex:/\*\*([^\*\n]+?)\*\*/g,type:"bold"},{regex:/__([^_\n]+?)__/g,type:"bold"},{regex:/\*([^\*\n]+?)\*/g,type:"italic"},{regex:/_([^_\n]+?)_/g,type:"italic"},{regex:/~~([^~\n]+?)~~/g,type:"strikethrough"},{regex:/\[([^\]]+)\]\(([^)]+)\)/g,type:"link"},{regex:/(?:^|(?<=\s))(https?:\/\/[^\s\n]+)/g,type:"autolink"},{regex:sL,type:"file-reference"}].forEach(t=>{const n=new RegExp(t.regex.source,t.regex.flags);let r;for(;null!==(r=n.exec(e));)o.push({start:r.index,end:r.index+r[0].length,content:r[0],type:t.type,groups:Array.from(r)})}),o.sort((e,t)=>e.start!==t.start?e.start-t.start:t.end-e.end);const s=[];for(const a of o){s.some(e=>a.start>=e.start&&a.start<e.end||a.end>e.start&&a.end<=e.end||a.start<=e.start&&a.end>=e.end)||s.push(a)}s.sort((e,t)=>e.start-t.start);for(const a of s){if(a.start>r){const t=e.slice(r,a.start);t&&n.push(We.jsx(xi,{children:t},i++))}switch(a.type){case"bold":n.push(We.jsx(xi,{bold:!0,children:a.groups[1]},i++));break;case"italic":n.push(We.jsx(xi,{italic:!0,children:a.groups[1]},i++));break;case"bold-italic":n.push(We.jsx(xi,{bold:!0,italic:!0,children:a.groups[1]},i++));break;case"strikethrough":n.push(We.jsxs(xi,{children:["~~",a.groups[1],"~~"]},i++));break;case"code":n.push(We.jsxs(xi,{backgroundColor:"gray",color:"black",children:[" ",a.groups[1]," "]},i++));break;case"link":n.push(We.jsxs(xi,{color:"blue",underline:!0,children:[a.groups[1]," (",a.groups[2],")"]},i++));break;case"autolink":n.push(We.jsx(xi,{color:"blue",underline:!0,children:a.groups[1]},i++));break;case"file-reference":n.push(We.jsx(xi,{color:"blue",children:a.groups[1]},i++));break;default:n.push(We.jsx(xi,{children:a.content},i++))}r=a.end}if(r<e.length){const t=e.slice(r);t&&n.push(We.jsx(xi,{children:t},i++))}return n.length>0?n:[We.jsx(xi,{children:e},0)]},[]),h=(e,t)=>{const n=[];let r=t,i=0;for(;r<e.length;){const t=e[r];if(null==t)break;const o=t.trim(),s=o.match(/^[*+-]\s+\[([x ])\]\s+(.+)$/),a=o.match(/^[*+-]\s+(.+)$/),l=o.match(/^(\d+)\.\s+(.+)$/);if(s){const[,e,t]=s,r="x"===(e??"").toLowerCase(),o=t??"";n.push(We.jsxs(ki,{paddingLeft:2,children:[We.jsxs(xi,{children:[r?"☑":"☐"," "]}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:f(o,!1)})]},i++))}else if(a){const[,e]=a,t=e??"";n.push(We.jsxs(ki,{paddingLeft:2,children:[We.jsx(xi,{children:"• "}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:f(t,!1)})]},i++))}else{if(!l)break;{const[,e,t]=l,r=t??"";n.push(We.jsxs(ki,{paddingLeft:2,children:[We.jsxs(xi,{children:[e,". "]}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:f(r,!1)})]},i++))}}r++}return{elements:n,nextIndex:r}},g=(e,t)=>{const n=[];let r=t;if(r+1>=e.length)return{elements:n,nextIndex:t};const i=e[r],o=e[r+1];if(null==i||null==o)return{elements:n,nextIndex:t};const s=i.trim(),a=o.trim();if(!s.includes("|")||!a.match(/^\s*\|?[\s\-:]+\|[\s\-:|]*\|?\s*$/))return{elements:n,nextIndex:t};const l=e=>e.split("|").map(e=>e.trim()).filter((e,t,n)=>!(""===e&&(0===t||t===n.length-1))),u=l(s);n.push(We.jsxs(ki,{flexDirection:"column",paddingLeft:2,paddingRight:1,children:[We.jsxs(xi,{color:"cyan",children:["┌","─".repeat(60),"┐"]}),We.jsxs(ki,{children:[We.jsx(xi,{color:"cyan",children:"│ "}),u.map((e,t)=>We.jsx(ki,{minWidth:10,paddingRight:1,children:We.jsx(xi,{bold:!0,color:"cyan",children:e})},t)),We.jsx(xi,{color:"cyan",children:" │"})]}),We.jsxs(xi,{color:"cyan",children:["├","─".repeat(60),"┤"]})]},"table-header")),r+=2;let c=0;for(;r<e.length;){const t=e[r];if(null==t)break;const i=t.trim();if(!i.includes("|"))break;const o=l(i);n.push(We.jsxs(ki,{paddingLeft:2,paddingRight:1,children:[We.jsx(xi,{color:"cyan",children:"│ "}),o.map((e,t)=>We.jsx(ki,{minWidth:10,paddingRight:1,flexDirection:"row",flexWrap:"wrap",children:f(e,!1)},t)),We.jsx(xi,{color:"cyan",children:" │"})]},"table-row-"+c++)),r++}return n.length>1&&n.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,children:We.jsxs(xi,{color:"cyan",children:["└","─".repeat(60),"┘"]})},"table-footer")),{elements:n,nextIndex:r}},A=(e,t)=>{const n=[];let r=t;const i=[];for(;r<e.length;){const t=e[r];if(null==t)break;const n=t.match(/^\s*>\s?(.*)$/);if(n){const[,e]=n;i.push(e??""),r++}else{if(!(""===t.trim()&&i.length>0))break;i.push(""),r++}}return i.length>0&&n.push(We.jsx(ki,{flexDirection:"column",paddingRight:1,borderLeft:!0,borderStyle:"single",paddingLeft:3,children:i.map((e,t)=>We.jsxs(ki,{flexDirection:"row",flexWrap:"wrap",children:[We.jsx(xi,{color:"gray",children:"▌ "}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:e?f(e,!1):[We.jsx(xi,{children:" "},0)]})]},t))},"blockquote")),{elements:n,nextIndex:r}},m=qe.useMemo(()=>{return"string"==typeof(e=a).content?e.content:Array.isArray(e.content)?e.content.map(e=>{switch(e.type){case"text":return e.text;case"tool-call":const t=e;return`[Tool Call: ${t.toolName}(${JSON.stringify(t.input)})]`;case"tool-result":{const t=e,n=t.output?.value;return n&&"object"==typeof n&&"returnDisplay"in n?String(n.returnDisplay):"[Tool Result]"}case"image":return"[Image]";case"file":const n=e;return`[File: ${n.mediaType}${n.filename?` - ${n.filename}`:""}]`;default:return"[Unknown content type]"}}).join("\n"):"";var e},[a]);if(!m||0===m.length)return null;const y=qe.useMemo(()=>()=>{if(u)return We.jsx(iL,{text:m,isPending:i,terminalWidth:s,availableTerminalHeight:void 0});const e=[],t=m.split(/(```[\s\S]*?```)/g);let n=0;return t.forEach((t,r)=>{if(t.startsWith("```")&&t.endsWith("```")){const n=t.slice(3,-3).split("\n"),i=n[0]?.trim()||"",o=i&&/^[a-zA-Z][a-zA-Z0-9+#-]*$/.test(i)&&i.length<20,s=o?i:"code",a=o?n.slice(1):n;e.push(We.jsxs(ki,{flexDirection:"column",borderStyle:"round",flexShrink:0,paddingLeft:2,paddingRight:1,paddingTop:0,paddingBottom:0,marginBottom:1,children:[We.jsx(xi,{color:"green",wrap:"wrap",children:s}),a.map((e,t)=>We.jsx(ki,{paddingLeft:2,paddingRight:1,children:We.jsx(xi,{wrap:"wrap",children:e})},t))]},`code-${r}`))}else{const r=t.split("\n");let i=0;for(;i<r.length;){const t=(r[i]??"").trim();if(""===t){i++;continue}const o=t.match(/^(#{1,6})\s+(.+)$/);if(o){const[,t,r]=o,s=(t??"#").length,a=r??"",l="█".repeat(Math.max(1,7-s));e.push(We.jsxs(ki,{paddingLeft:2,paddingRight:1,marginY:1,children:[We.jsxs(xi,{color:"magenta",children:[l," "]}),We.jsx(ki,{flexDirection:"row",flexWrap:"wrap",children:f(a,!1)})]},"header-"+n++)),i++;continue}if(t.startsWith(">")){const{elements:t,nextIndex:n}=A(r,i);t.forEach(t=>e.push(t)),i=n;continue}if(t.includes("|")&&i+1<r.length){const{elements:t,nextIndex:n}=g(r,i);if(t.length>0){t.forEach(t=>e.push(t)),i=n;continue}}if(t.match(/^([*+-]|\d+\.|\[[ x]\])\s+/)){const{elements:t,nextIndex:o}=h(r,i);if(t.length>0){e.push(We.jsx(ki,{flexDirection:"column",paddingLeft:2,paddingRight:1,marginY:1,children:t},"list-"+n++)),i=o;continue}}if(t.match(/^(-{3,}|\*{3,}|_{3,})$/)){e.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,marginY:1,children:We.jsx(xi,{color:"gray",children:"─".repeat(50)})},"hr-"+n++)),i++;continue}const s=[];for(;i<r.length;){const e=r[i];if(!e||""===e.trim())break;s.push(e),i++}if(s.length>0)if(l)s.forEach(t=>{t.trim()?e.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,flexDirection:"row",flexWrap:"wrap",children:f(t.trim(),!1)},"para-"+n++)):e.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,children:We.jsx(xi,{children:" "})},"para-"+n++))});else{const t=s.join(" ").trim();e.push(We.jsx(ki,{paddingLeft:2,paddingRight:1,flexDirection:"row",flexWrap:"wrap",children:f(t,!1)},"para-"+n++))}}}}),e},[m,u,l,s,i,f]);return We.jsx(ki,{marginBottom:1,flexDirection:"column",flexShrink:0,paddingLeft:2,paddingRight:1,children:l?We.jsx(ki,{flexDirection:"column",flexShrink:0,children:We.jsx(ki,{children:We.jsx(xi,{dimColor:!0,children:m})})}):We.jsxs(ki,{flexDirection:"row",flexShrink:0,paddingLeft:2,children:[We.jsx(ki,{flexDirection:"column",marginRight:1,children:We.jsx(xi,{color:"gray",children:"╰─"})}),We.jsx(ki,{flexDirection:"column",flexShrink:0,paddingRight:1,children:y()})]})})},(e,t)=>{if(e.isStreaming!==t.isStreaming)return!1;if(e.isFocused!==t.isFocused)return!1;if(e.index!==t.index)return!1;if(e.onToolConfirm!==t.onToolConfirm)return!1;if("role"in e.message&&"role"in t.message){if(e.message.role!==t.message.role)return!1;if(t.isStreaming&&"content"in e.message&&"content"in t.message){const n="string"==typeof e.message.content?e.message.content:"",r="string"==typeof t.message.content?t.message.content:"";if(n.length!==r.length)return!1}if("timestamp"in e.message&&"timestamp"in t.message&&e.message.timestamp!==t.message.timestamp)return!1}if("id"in e.message&&"id"in t.message&&e.message.id!==t.message.id)return!1;if("toolGroup"in e.message&&"toolGroup"in t.message){const n=e.message.toolGroup,r=t.message.toolGroup;if(n.status!==r.status)return!1;if(n.tools.length!==r.tools.length)return!1;for(let e=0;e<n.tools.length;e++)if(n.tools[e].status!==r.tools[e].status)return!1}return!0}),EL=qe.memo(qe.forwardRef((e,t)=>We.jsx(bL,{...e,ref:t})),(e,t)=>e.messages===t.messages&&e.focused===t.focused&&e.onToolConfirm===t.onToolConfirm&&e.disableArrowKeyScrolling===t.disableArrowKeyScrolling),IL=qe.createContext(null);function wL({children:e}){const[t,n]=qe.useState(!1),[r,i]=qe.useState(!0),[o,s]=qe.useState(!0),[a,l]=qe.useState({width:80,height:10}),[u,c]=qe.useState(10),[d,p]=qe.useState(!0),[f,h]=qe.useState(!0),[g,A]=qe.useState([]),[m,y]=qe.useState(!1),b=qe.useCallback(e=>{n(e)},[]),v=qe.useCallback(e=>{i(e)},[]),E=qe.useCallback(e=>{s(e)},[]),I=qe.useCallback(e=>{l(e)},[]),w=qe.useCallback(e=>{c(e)},[]),C=qe.useCallback(e=>{p(e)},[]),_=qe.useCallback(e=>{h(e)},[]),B=qe.useCallback(e=>{const t=e.trim();t&&A(e=>{if(e.length>0&&e[e.length-1]===t)return e;const n=[...e,t];return n.length>50?n.slice(-50):n})},[]),D=qe.useCallback(e=>{if(!(e<0||e>=g.length))return g[g.length-1-e]},[g]),S=qe.useCallback(()=>g.length,[g]),k=qe.useCallback(e=>{y(e)},[]),x=qe.useMemo(()=>({isFileCompletionActive:t,multilineMode:r,textBufferEnabled:o,viewport:a,maxHeight:u,enableUndo:d,enableExternalEditor:f,inputHistory:g,isTyping:m}),[t,r,o,a,u,d,f,g,m]),Q=qe.useMemo(()=>({setFileCompletionActive:b,setMultilineMode:v,setTextBufferEnabled:E,setViewport:I,setMaxHeight:w,setEnableUndo:C,setEnableExternalEditor:_,addToHistory:B,getHistoryItem:D,getHistoryLength:S,setIsTyping:k}),[b,v,E,I,w,C,_,B,D,S,k]),N=qe.useMemo(()=>({state:x,actions:Q}),[x,Q]);return We.jsx(IL.Provider,{value:N,children:e})}function CL(){const e=qe.useContext(IL);if(!e)throw new Error("useInputState must be used within an InputProvider");return e}const _L={idle:[{face:"o_o",mood:"neutral",description:"Alert, ready"}],blinking:{face:"-_-",mood:"neutral",description:"Calm, composed"},typing:[{face:"._.",mood:"neutral",description:"Observing, attentive"},{face:"^_^",mood:"neutral",description:"Content you're typing"}]},BL={neutral:[{face:"^_^",mood:"neutral",description:"Content, neutral"},{face:"-_-",mood:"neutral",description:"Calm, composed"},{face:"._.",mood:"neutral",description:"Observing, attentive"},{face:"o_o",mood:"neutral",description:"Alert, ready"}],happy:[{face:"^o^",mood:"happy",description:"Very pleased"},{face:"^v^",mood:"happy",description:"Satisfied"},{face:"◠‿◠",mood:"happy",description:"Genuinely happy"},{face:"^ᴗ^",mood:"happy",description:"Cheerful"}],excited:[{face:"*o*",mood:"excited",description:"Amazed"},{face:"★_★",mood:"excited",description:"Star-struck"},{face:"✧_✧",mood:"excited",description:"Sparkling with excitement"},{face:"◉_◉",mood:"excited",description:"Eyes wide with excitement"}],working:[{face:"⊙_⊙",mood:"working",description:"Focused"},{face:"◔_◔",mood:"working",description:"Concentrating"},{face:"●_●",mood:"working",description:"Processing"},{face:"◕_◕",mood:"working",description:"Working hard"}],thinking:[{face:"⊙﹏⊙",mood:"thinking",description:"Deep in thought"},{face:"◔_◔",mood:"thinking",description:"Pondering"},{face:"⊚_⊚",mood:"thinking",description:"Analyzing"},{face:"◉‿◉",mood:"thinking",description:"Considering options"}],concerned:[{face:"⊙︿⊙",mood:"concerned",description:"Worried"},{face:"◕︿◕",mood:"concerned",description:"Concerned"},{face:"⊙﹏⊙",mood:"concerned",description:"Uncertain"},{face:"╥_╥",mood:"concerned",description:"Troubled"}],error:[{face:"x_x",mood:"error",description:"Failed"},{face:"×_×",mood:"error",description:"Error occurred"},{face:"✖_✖",mood:"error",description:"Something went wrong"},{face:"@_@",mood:"error",description:"Confused/overwhelmed"}],sleeping:[{face:"-_-",mood:"sleeping",description:"Resting"},{face:"˘_˘",mood:"sleeping",description:"Sleepy"},{face:"ᴗ_ᴗ",mood:"sleeping",description:"Dozing"},{face:"zzz",mood:"sleeping",description:"Asleep"}],playful:[{face:"^ω^",mood:"playful",description:"Playful"},{face:"≧◡≦",mood:"playful",description:"Having fun"},{face:"◠ᴥ◠",mood:"playful",description:"Silly"},{face:"ᴗ_ᴗ",mood:"playful",description:"Mischievous"}],greedy:[{face:"$_$",mood:"greedy",description:"Money eyes - low balance"},{face:"💲_💲",mood:"greedy",description:"Dollar signs - needs credits"},{face:"$ᴗ$",mood:"greedy",description:"Greedy for credits"},{face:"💰_💰",mood:"greedy",description:"Money bags - pay up!"}]};function DL(){const e=Math.floor(Math.random()*_L.idle.length);return _L.idle[e]??_L.idle[0]}function SL(){return _L.blinking}const kL=kw(e=>({currentFile:null,setCurrentFile:t=>e({currentFile:t})}));function xL({currentModel:e,streamingState:t,lastToolStatus:n,messages:r,yoloEnabled:i=!1}){const{billingStatus:o}=FT(),{state:s}=CL(),{currentFile:a}=kL(),[l,u]=qe.useState(()=>DL());qe.useEffect(()=>{if(t===_w.Idle&&!s.isTyping)return;const e=void 0!==(r={isStreaming:t===_w.Responding,hasError:"error"===n,isThinking:t===_w.WaitingForConfirmation,lastToolSuccess:"success"===n||"error"!==n&&void 0,creditBalance:o?.totalCreditBalance}).creditBalance&&r.creditBalance<500?"greedy":r.hasError?"error":r.isStreaming?"working":r.isThinking?"thinking":!0===r.lastToolSuccess?"happy":!1===r.lastToolSuccess?"concerned":"neutral";var r;u(function(e){const t=BL[e];return t[Math.floor(Math.random()*t.length)]??BL.neutral[0]}(e))},[t,n,o?.totalCreditBalance,s.isTyping]),qe.useEffect(()=>{s.isTyping&&t===_w.Idle&&u(function(){const e=Math.floor(Math.random()*_L.typing.length);return _L.typing[e]??_L.typing[0]}())},[s.isTyping,t]),qe.useEffect(()=>{if(t!==_w.Idle||s.isTyping)return;const e=3e3+2e3*Math.random(),n=setTimeout(()=>{u(SL()),setTimeout(()=>{u(DL()),setTimeout(()=>{u(SL()),setTimeout(()=>{u(DL())},150)},100)},150)},e);return()=>clearTimeout(n)},[t,s.isTyping,l]);const c=qe.useMemo(()=>{if(!e||!r||0===r.length)return null;return dM(bM(r),aM(cM(e.modelId||e.name))||uM(e.provider))},[e,r]),d=qe.useMemo(()=>{if(!a)return null;const e=ae.relative(process.cwd(),a);return e.length>50?ae.basename(a):e},[a]),p=qe.useMemo(()=>{if(!o)return"Loading...";const{planType:e,totalCreditBalance:t}=o;return"plan_unlimited"===e?"Embedder Ultra":"plan_base"===e?"Embedder Pro":`Free Tier: $${(t/100).toFixed(2)}`},[o]);return qe.useMemo(()=>{const t=null!==c?` • ${c}%`:"";return HM(`{ ${l.face} } ${e?.name??"No model selected"} (Ctrl+B)${t} • ${p}`)},[l.face,e?.name,p,c]),We.jsx(ki,{flexDirection:"column",paddingY:1,children:We.jsxs(ki,{flexDirection:"row",marginBottom:1,justifyContent:"space-between",children:[We.jsxs(ki,{flexDirection:"row",children:[We.jsx(xi,{color:"cyan",bold:!0,children:"{ "}),We.jsx(xi,{color:"yellow",bold:!0,children:l.face}),We.jsx(xi,{color:"cyan",bold:!0,children:" } "}),We.jsx(xi,{color:"white",dimColor:!0,children:e?.name??"No model selected"}),We.jsxs(xi,{color:"gray",dimColor:!0,children:[" ","(Ctrl+B)"]}),null!==c&&We.jsxs(We.Fragment,{children:[We.jsx(xi,{color:"gray",children:" • "}),We.jsxs(xi,{color:c>=90?"red":c>=70?"yellow":"cyan",dimColor:!0,children:[c,"%"]})]}),We.jsx(xi,{color:"gray",children:" • "}),We.jsx(xi,{color:"green",dimColor:!0,children:p})]}),We.jsxs(ki,{flexDirection:"row",gap:2,children:[d&&We.jsx(xi,{color:"gray",dimColor:!0,italic:!0,children:d}),i&&We.jsx(xi,{color:"red",bold:!0,children:"YOLO"})]})]})})}const QL={dots:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},dots2:{interval:80,frames:["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},dots3:{interval:80,frames:["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},dots4:{interval:80,frames:["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},dots5:{interval:80,frames:["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},dots6:{interval:80,frames:["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},dots7:{interval:80,frames:["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},dots8:{interval:80,frames:["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},dots9:{interval:80,frames:["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},dots10:{interval:80,frames:["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},dots11:{interval:100,frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},dots12:{interval:80,frames:["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},dots13:{interval:80,frames:["⣼","⣹","⢻","⠿","⡟","⣏","⣧","⣶"]},dots8Bit:{interval:80,frames:["⠀","⠁","⠂","⠃","⠄","⠅","⠆","⠇","⡀","⡁","⡂","⡃","⡄","⡅","⡆","⡇","⠈","⠉","⠊","⠋","⠌","⠍","⠎","⠏","⡈","⡉","⡊","⡋","⡌","⡍","⡎","⡏","⠐","⠑","⠒","⠓","⠔","⠕","⠖","⠗","⡐","⡑","⡒","⡓","⡔","⡕","⡖","⡗","⠘","⠙","⠚","⠛","⠜","⠝","⠞","⠟","⡘","⡙","⡚","⡛","⡜","⡝","⡞","⡟","⠠","⠡","⠢","⠣","⠤","⠥","⠦","⠧","⡠","⡡","⡢","⡣","⡤","⡥","⡦","⡧","⠨","⠩","⠪","⠫","⠬","⠭","⠮","⠯","⡨","⡩","⡪","⡫","⡬","⡭","⡮","⡯","⠰","⠱","⠲","⠳","⠴","⠵","⠶","⠷","⡰","⡱","⡲","⡳","⡴","⡵","⡶","⡷","⠸","⠹","⠺","⠻","⠼","⠽","⠾","⠿","⡸","⡹","⡺","⡻","⡼","⡽","⡾","⡿","⢀","⢁","⢂","⢃","⢄","⢅","⢆","⢇","⣀","⣁","⣂","⣃","⣄","⣅","⣆","⣇","⢈","⢉","⢊","⢋","⢌","⢍","⢎","⢏","⣈","⣉","⣊","⣋","⣌","⣍","⣎","⣏","⢐","⢑","⢒","⢓","⢔","⢕","⢖","⢗","⣐","⣑","⣒","⣓","⣔","⣕","⣖","⣗","⢘","⢙","⢚","⢛","⢜","⢝","⢞","⢟","⣘","⣙","⣚","⣛","⣜","⣝","⣞","⣟","⢠","⢡","⢢","⢣","⢤","⢥","⢦","⢧","⣠","⣡","⣢","⣣","⣤","⣥","⣦","⣧","⢨","⢩","⢪","⢫","⢬","⢭","⢮","⢯","⣨","⣩","⣪","⣫","⣬","⣭","⣮","⣯","⢰","⢱","⢲","⢳","⢴","⢵","⢶","⢷","⣰","⣱","⣲","⣳","⣴","⣵","⣶","⣷","⢸","⢹","⢺","⢻","⢼","⢽","⢾","⢿","⣸","⣹","⣺","⣻","⣼","⣽","⣾","⣿"]},sand:{interval:80,frames:["⠁","⠂","⠄","⡀","⡈","⡐","⡠","⣀","⣁","⣂","⣄","⣌","⣔","⣤","⣥","⣦","⣮","⣶","⣷","⣿","⡿","⠿","⢟","⠟","⡛","⠛","⠫","⢋","⠋","⠍","⡉","⠉","⠑","⠡","⢁"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["⠂","-","–","—","–","-"]},pipe:{interval:100,frames:["┤","┘","┴","└","├","┌","┬","┐"]},simpleDots:{interval:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{interval:200,frames:[". ",".. ","..."," .."," ."," "]},star:{interval:70,frames:["✶","✸","✹","✺","✹","✷"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","´","-","_","_","_"]},hamburger:{interval:100,frames:["☱","☲","☴"]},growVertical:{interval:120,frames:["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},growHorizontal:{interval:120,frames:["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","°","O","o","."]},noise:{interval:100,frames:["▓","▒","░"]},bounce:{interval:120,frames:["⠁","⠂","⠄","⠂"]},boxBounce:{interval:120,frames:["▖","▘","▝","▗"]},boxBounce2:{interval:100,frames:["▌","▀","▐","▄"]},triangle:{interval:50,frames:["◢","◣","◤","◥"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["◜","◠","◝","◞","◡","◟"]},circle:{interval:120,frames:["◡","⊙","◠"]},squareCorners:{interval:180,frames:["◰","◳","◲","◱"]},circleQuarters:{interval:120,frames:["◴","◷","◶","◵"]},circleHalves:{interval:50,frames:["◐","◓","◑","◒"]},squish:{interval:100,frames:["╫","╪"]},toggle:{interval:250,frames:["⊶","⊷"]},toggle2:{interval:80,frames:["▫","▪"]},toggle3:{interval:120,frames:["□","■"]},toggle4:{interval:100,frames:["■","□","▪","▫"]},toggle5:{interval:100,frames:["▮","▯"]},toggle6:{interval:300,frames:["ဝ","၀"]},toggle7:{interval:80,frames:["⦾","⦿"]},toggle8:{interval:100,frames:["◍","◌"]},toggle9:{interval:100,frames:["◉","◎"]},toggle10:{interval:100,frames:["㊂","㊀","㊁"]},toggle11:{interval:50,frames:["⧇","⧆"]},toggle12:{interval:120,frames:["☗","☖"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["←","↖","↑","↗","→","↘","↓","↙"]},arrow2:{interval:80,frames:["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},arrow3:{interval:120,frames:["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},bouncingBar:{interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{interval:80,frames:["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},smiley:{interval:200,frames:["😄 ","😝 "]},monkey:{interval:300,frames:["🙈 ","🙈 ","🙉 ","🙊 "]},hearts:{interval:100,frames:["💛 ","💙 ","💜 ","💚 ","❤️ "]},clock:{interval:100,frames:["🕛 ","🕐 ","🕑 ","🕒 ","🕓 ","🕔 ","🕕 ","🕖 ","🕗 ","🕘 ","🕙 ","🕚 "]},earth:{interval:180,frames:["🌍 ","🌎 ","🌏 "]},material:{interval:17,frames:["█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███████▁▁▁▁▁▁▁▁▁▁▁▁▁","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","██████████▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","█████████████▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁██████████████▁▁▁▁","▁▁▁██████████████▁▁▁","▁▁▁▁█████████████▁▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁▁▁████████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","██████▁▁▁▁▁▁▁▁▁▁▁▁▁█","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁▁█████████████▁▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁▁███████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁▁█████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁"]},moon:{interval:80,frames:["🌑 ","🌒 ","🌓 ","🌔 ","🌕 ","🌖 ","🌗 ","🌘 "]},runner:{interval:140,frames:["🚶 ","🏃 "]},pong:{interval:80,frames:["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},shark:{interval:120,frames:["▐|\\____________▌","▐_|\\___________▌","▐__|\\__________▌","▐___|\\_________▌","▐____|\\________▌","▐_____|\\_______▌","▐______|\\______▌","▐_______|\\_____▌","▐________|\\____▌","▐_________|\\___▌","▐__________|\\__▌","▐___________|\\_▌","▐____________|\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["☀️ ","☀️ ","☀️ ","🌤 ","⛅️ ","🌥 ","☁️ ","🌧 ","🌨 ","🌧 ","🌨 ","🌧 ","🌨 ","⛈ ","🌨 ","🌧 ","🌨 ","☁️ ","🌥 ","⛅️ ","🌤 ","☀️ ","☀️ "]},christmas:{interval:400,frames:["🌲","🎄"]},grenade:{interval:80,frames:["، ","′ "," ´ "," ‾ "," ⸌"," ⸊"," |"," ⁎"," ⁕"," ෴ "," ⁓"," "," "," "]},point:{interval:125,frames:["∙∙∙","●∙∙","∙●∙","∙∙●","∙∙∙"]},layer:{interval:150,frames:["-","=","≡"]},betaWave:{interval:80,frames:["ρββββββ","βρβββββ","ββρββββ","βββρβββ","ββββρββ","βββββρβ","ββββββρ"]},fingerDance:{interval:160,frames:["🤘 ","🤟 ","🖖 ","✋ ","🤚 ","👆 "]},fistBump:{interval:80,frames:["🤜    🤛 ","🤜    🤛 ","🤜    🤛 "," 🤜  🤛  ","  🤜🤛   "," 🤜✨🤛   ","🤜 ✨ 🤛  "]},soccerHeader:{interval:80,frames:[" 🧑⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 "]},mindblown:{interval:160,frames:["😐 ","😐 ","😮 ","😮 ","😦 ","😦 ","😧 ","😧 ","🤯 ","💥 ","✨ ","  ","  ","  "]},speaker:{interval:160,frames:["🔈 ","🔉 ","🔊 ","🔉 "]},orangePulse:{interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 "]},bluePulse:{interval:100,frames:["🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},orangeBluePulse:{interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 ","🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},timeTravel:{interval:100,frames:["🕛 ","🕚 ","🕙 ","🕘 ","🕗 ","🕖 ","🕕 ","🕔 ","🕓 ","🕒 ","🕑 ","🕐 "]},aesthetic:{interval:80,frames:["▰▱▱▱▱▱▱","▰▰▱▱▱▱▱","▰▰▰▱▱▱▱","▰▰▰▰▱▱▱","▰▰▰▰▰▱▱","▰▰▰▰▰▰▱","▰▰▰▰▰▰▰","▰▱▱▱▱▱▱"]},dwarfFortress:{interval:80,frames:[" ██████£££ ","☺██████£££ ","☺██████£££ ","☺▓█████£££ ","☺▓█████£££ ","☺▒█████£££ ","☺▒█████£££ ","☺░█████£££ ","☺░█████£££ ","☺ █████£££ "," ☺█████£££ "," ☺█████£££ "," ☺▓████£££ "," ☺▓████£££ "," ☺▒████£££ "," ☺▒████£££ "," ☺░████£££ "," ☺░████£££ "," ☺ ████£££ "," ☺████£££ "," ☺████£££ "," ☺▓███£££ "," ☺▓███£££ "," ☺▒███£££ "," ☺▒███£££ "," ☺░███£££ "," ☺░███£££ "," ☺ ███£££ "," ☺███£££ "," ☺███£££ "," ☺▓██£££ "," ☺▓██£££ "," ☺▒██£££ "," ☺▒██£££ "," ☺░██£££ "," ☺░██£££ "," ☺ ██£££ "," ☺██£££ "," ☺██£££ "," ☺▓█£££ "," ☺▓█£££ "," ☺▒█£££ "," ☺▒█£££ "," ☺░█£££ "," ☺░█£££ "," ☺ █£££ "," ☺█£££ "," ☺█£££ "," ☺▓£££ "," ☺▓£££ "," ☺▒£££ "," ☺▒£££ "," ☺░£££ "," ☺░£££ "," ☺ £££ "," ☺£££ "," ☺£££ "," ☺▓££ "," ☺▓££ "," ☺▒££ "," ☺▒££ "," ☺░££ "," ☺░££ "," ☺ ££ "," ☺££ "," ☺££ "," ☺▓£ "," ☺▓£ "," ☺▒£ "," ☺▒£ "," ☺░£ "," ☺░£ "," ☺ £ "," ☺£ "," ☺£ "," ☺▓ "," ☺▓ "," ☺▒ "," ☺▒ "," ☺░ "," ☺░ "," ☺ "," ☺ &"," ☺ ☼&"," ☺ ☼ &"," ☺☼ &"," ☺☼ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & ","‼ & "," & "," & "," & ░ "," & ▒ "," & ▓ "," & £ "," & ░£ "," & ▒£ "," & ▓£ "," & ££ "," & ░££ "," & ▒££ ","& ▓££ ","& £££ "," ░£££ "," ▒£££ "," ▓£££ "," █£££ "," ░█£££ "," ▒█£££ "," ▓█£££ "," ██£££ "," ░██£££ "," ▒██£££ "," ▓██£££ "," ███£££ "," ░███£££ "," ▒███£££ "," ▓███£££ "," ████£££ "," ░████£££ "," ▒████£££ "," ▓████£££ "," █████£££ "," ░█████£££ "," ▒█████£££ "," ▓█████£££ "," ██████£££ "," ██████£££ "]}};var NL,TL;const RL=e(function(){if(TL)return NL;TL=1;const e=Object.assign({},QL),t=Object.keys(e);return Object.defineProperty(e,"random",{get(){const n=Math.floor(Math.random()*t.length),r=t[n];return e[r]}}),NL=e}());function FL({type:e="dots"}){const[t,n]=qe.useState(0),r=RL[e];return qe.useEffect(()=>{const e=setInterval(()=>{n(e=>e===r.frames.length-1?0:e+1)},r.interval);return()=>{clearInterval(e)}},[r]),Je.createElement(xi,null,r.frames[t])}function ML(){const{streamingState:e,thought:t,isResponding:n,messages:r}=BM(),i=DM(e=>e.totalTokenCount),o=DM(e=>e.streams),[s,a]=qe.useState(0),[l,u]=qe.useState(0),[c,d]=qe.useState(!1);if(qe.useEffect(()=>{const t=r.some(e=>"role"in e&&"tool-group"===e.role&&e.toolGroup.tools.some(e=>e.status===SM.Confirming));(e===_w.WaitingForConfirmation||t)&&u(0)},[e,r]),qe.useEffect(()=>{if(!t?.startTime||e===_w.Idle)return u(0),void d(!1);const n=setInterval(()=>{c||(u(e=>0===e?1:e+1),Math.random()<.05&&(d(!0),setTimeout(()=>d(!1),1e3)))},50);return()=>clearInterval(n)},[t?.startTime,e,c]),qe.useEffect(()=>{if(!t?.startTime||e===_w.Idle)return void a(0);const n=()=>{const e=Math.floor((Date.now()-(t.startTime||0))/1e3);a(e)};n();const r=setInterval(n,100);return()=>clearInterval(r)},[t?.startTime,e]),e===_w.Idle)return null;const p=t?.subject||"Thinking...",f=e===_w.WaitingForConfirmation,h=r.some(e=>"role"in e&&"tool-group"===e.role&&e.toolGroup.tools.some(e=>e.status===SM.Confirming)),g=r.some(e=>"role"in e&&"tool-group"===e.role&&e.toolGroup.tools.some(e=>e.status===SM.Executing)),A=Array.from(o.values()).some(e=>"ai-thinking"!==e.toolCallId),m=o.get("ai-thinking"),y=m&&Date.now()-m.timestamp<100,b=r[r.length-1],v=b&&"role"in b&&"assistant"===b.role,E=l+i,I=E>0&&!(n&&v&&y&&!g&&!A)&&!f&&!h,w=[];f||w.push("esc to interrupt"),s>0&&w.push(`${s}s`),I&&w.push(`↓ ${E} tokens`);const C=w.length>0?` (${w.join(" · ")})`:"";return We.jsxs(ki,{marginBottom:1,paddingLeft:2,paddingRight:1,children:[We.jsx(ki,{marginRight:1,children:We.jsx(FL,{type:"dots"})}),We.jsxs(xi,{color:"gray",children:[p,C]}),t?.description&&We.jsx(ki,{marginTop:0,paddingLeft:3,children:We.jsx(xi,{color:"gray",dimColor:!0,children:t.description})})]})}const OL=(e,t,n)=>{const r=e instanceof RegExp?$L(e,n):e,i=t instanceof RegExp?$L(t,n):t,o=null!==r&&null!=i&&LL(r,i,n);return o&&{start:o[0],end:o[1],pre:n.slice(0,o[0]),body:n.slice(o[0]+r.length,o[1]),post:n.slice(o[1]+i.length)}},$L=(e,t)=>{const n=t.match(e);return n?n[0]:null},LL=(e,t,n)=>{let r,i,o,s,a,l=n.indexOf(e),u=n.indexOf(t,l+1),c=l;if(l>=0&&u>0){if(e===t)return[l,u];for(r=[],o=n.length;c>=0&&!a;){if(c===l)r.push(c),l=n.indexOf(e,c+1);else if(1===r.length){const e=r.pop();void 0!==e&&(a=[e,u])}else i=r.pop(),void 0!==i&&i<o&&(o=i,s=u),u=n.indexOf(t,c+1);c=l<u&&l>=0?l:u}r.length&&void 0!==s&&(a=[o,s])}return a},PL="\0SLASH"+Math.random()+"\0",jL="\0OPEN"+Math.random()+"\0",UL="\0CLOSE"+Math.random()+"\0",zL="\0COMMA"+Math.random()+"\0",GL="\0PERIOD"+Math.random()+"\0",HL=new RegExp(PL,"g"),WL=new RegExp(jL,"g"),qL=new RegExp(UL,"g"),JL=new RegExp(zL,"g"),KL=new RegExp(GL,"g"),ZL=/\\\\/g,VL=/\\{/g,YL=/\\}/g,XL=/\\,/g,eP=/\\./g;function tP(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function nP(e){return e.replace(HL,"\\").replace(WL,"{").replace(qL,"}").replace(JL,",").replace(KL,".")}function rP(e){if(!e)return[""];const t=[],n=OL("{","}",e);if(!n)return e.split(",");const{pre:r,body:i,post:o}=n,s=r.split(",");s[s.length-1]+="{"+i+"}";const a=rP(o);return o.length&&(s[s.length-1]+=a.shift(),s.push.apply(s,a)),t.push.apply(t,s),t}function iP(e){return e?("{}"===e.slice(0,2)&&(e="\\{\\}"+e.slice(2)),uP(function(e){return e.replace(ZL,PL).replace(VL,jL).replace(YL,UL).replace(XL,zL).replace(eP,GL)}(e),!0).map(nP)):[]}function oP(e){return"{"+e+"}"}function sP(e){return/^-?0\d/.test(e)}function aP(e,t){return e<=t}function lP(e,t){return e>=t}function uP(e,t){const n=[],r=OL("{","}",e);if(!r)return[e];const i=r.pre,o=r.post.length?uP(r.post,!1):[""];if(/\$$/.test(r.pre))for(let s=0;s<o.length;s++){const e=i+"{"+r.body+"}"+o[s];n.push(e)}else{const s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),a=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),l=s||a,u=r.body.indexOf(",")>=0;if(!l&&!u)return r.post.match(/,(?!,).*\}/)?uP(e=r.pre+"{"+r.body+UL+r.post):[e];let c,d;if(l)c=r.body.split(/\.\./);else if(c=rP(r.body),1===c.length&&void 0!==c[0]&&(c=uP(c[0],!1).map(oP),1===c.length))return o.map(e=>r.pre+c[0]+e);if(l&&void 0!==c[0]&&void 0!==c[1]){const e=tP(c[0]),t=tP(c[1]),n=Math.max(c[0].length,c[1].length);let r=3===c.length&&void 0!==c[2]?Math.abs(tP(c[2])):1,i=aP;t<e&&(r*=-1,i=lP);const o=c.some(sP);d=[];for(let s=e;i(s,t);s+=r){let e;if(a)e=String.fromCharCode(s),"\\"===e&&(e="");else if(e=String(s),o){const t=n-e.length;if(t>0){const n=new Array(t+1).join("0");e=s<0?"-"+n+e.slice(1):n+e}}d.push(e)}}else{d=[];for(let e=0;e<c.length;e++)d.push.apply(d,uP(c[e],!1))}for(let e=0;e<d.length;e++)for(let r=0;r<o.length;r++){const s=i+d[e]+o[r];(!t||l||s)&&n.push(s)}}return n}const cP=e=>{if("string"!=typeof e)throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},dP={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},pP=e=>e.replace(/[[\]\\-]/g,"\\$&"),fP=e=>e.join(""),hP=(e,t)=>{const n=t;if("["!==e.charAt(n))throw new Error("not in a brace expression");const r=[],i=[];let o=n+1,s=!1,a=!1,l=!1,u=!1,c=n,d="";e:for(;o<e.length;){const t=e.charAt(o);if("!"!==t&&"^"!==t||o!==n+1){if("]"===t&&s&&!l){c=o+1;break}if(s=!0,"\\"!==t||l){if("["===t&&!l)for(const[t,[s,l,u]]of Object.entries(dP))if(e.startsWith(t,o)){if(d)return["$.",!1,e.length-n,!0];o+=t.length,u?i.push(s):r.push(s),a=a||l;continue e}l=!1,d?(t>d?r.push(pP(d)+"-"+pP(t)):t===d&&r.push(pP(t)),d="",o++):e.startsWith("-]",o+1)?(r.push(pP(t+"-")),o+=2):e.startsWith("-",o+1)?(d=t,o+=2):(r.push(pP(t)),o++)}else l=!0,o++}else u=!0,o++}if(c<o)return["",!1,0,!1];if(!r.length&&!i.length)return["$.",!1,e.length-n,!0];if(0===i.length&&1===r.length&&/^\\?.$/.test(r[0])&&!u){const e=2===r[0].length?r[0].slice(-1):r[0];return[(p=e,p.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")),!1,c-n,!1]}var p;const f="["+(u?"^":"")+fP(r)+"]",h="["+(u?"":"^")+fP(i)+"]";return[r.length&&i.length?"("+f+"|"+h+")":r.length?f:h,a,c-n,!0]},gP=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/\[([^\/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"),AP=new Set(["!","?","+","*","@"]),mP=e=>AP.has(e),yP="(?!\\.)",bP=new Set(["[","."]),vP=new Set(["..","."]),EP=new Set("().*{}+?[]^$\\!"),IP=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),wP="[^/]",CP=wP+"*?",_P=wP+"+?";class BP{type;#e;#t;#n=!1;#r=[];#i;#o;#s;#a=!1;#l;#u;#c=!1;constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#l=this.#e===this?n:this.#e.#l,this.#s=this.#e===this?[]:this.#e.#s,"!"!==e||this.#e.#a||this.#s.push(this),this.#o=this.#i?this.#i.#r.length:0}get hasMagic(){if(void 0!==this.#t)return this.#t;for(const e of this.#r)if("string"!=typeof e&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return void 0!==this.#u?this.#u:this.type?this.#u=this.type+"("+this.#r.map(e=>String(e)).join("|")+")":this.#u=this.#r.map(e=>String(e)).join("")}#d(){if(this!==this.#e)throw new Error("should only call on root");if(this.#a)return this;let e;for(this.toString(),this.#a=!0;e=this.#s.pop();){if("!"!==e.type)continue;let t=e,n=t.#i;for(;n;){for(let r=t.#o+1;!n.type&&r<n.#r.length;r++)for(const t of e.#r){if("string"==typeof t)throw new Error("string part in extglob AST??");t.copyIn(n.#r[r])}t=n,n=t.#i}}return this}push(...e){for(const t of e)if(""!==t){if("string"!=typeof t&&!(t instanceof BP&&t.#i===this))throw new Error("invalid part: "+t);this.#r.push(t)}}toJSON(){const e=null===this.type?this.#r.slice().map(e=>"string"==typeof e?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#a&&"!"===this.#i?.type)&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(0===this.#o)return!0;const e=this.#i;for(let t=0;t<this.#o;t++){const n=e.#r[t];if(!(n instanceof BP&&"!"===n.type))return!1}return!0}isEnd(){if(this.#e===this)return!0;if("!"===this.#i?.type)return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();const e=this.#i?this.#i.#r.length:0;return this.#o===e-1}copyIn(e){"string"==typeof e?this.push(e):this.push(e.clone(this))}clone(e){const t=new BP(this.type,e);for(const n of this.#r)t.copyIn(n);return t}static#p(e,t,n,r){let i=!1,o=!1,s=-1,a=!1;if(null===t.type){let l=n,u="";for(;l<e.length;){const n=e.charAt(l++);if(i||"\\"===n)i=!i,u+=n;else if(o)l===s+1?"^"!==n&&"!"!==n||(a=!0):"]"!==n||l===s+2&&a||(o=!1),u+=n;else if("["!==n){if(!r.noext&&mP(n)&&"("===e.charAt(l)){t.push(u),u="";const i=new BP(n,t);l=BP.#p(e,i,l,r),t.push(i);continue}u+=n}else o=!0,s=l,a=!1,u+=n}return t.push(u),l}let l=n+1,u=new BP(null,t);const c=[];let d="";for(;l<e.length;){const n=e.charAt(l++);if(i||"\\"===n)i=!i,d+=n;else if(o)l===s+1?"^"!==n&&"!"!==n||(a=!0):"]"!==n||l===s+2&&a||(o=!1),d+=n;else if("["!==n){if(mP(n)&&"("===e.charAt(l)){u.push(d),d="";const t=new BP(n,u);u.push(t),l=BP.#p(e,t,l,r);continue}if("|"!==n){if(")"===n)return""===d&&0===t.#r.length&&(t.#c=!0),u.push(d),d="",t.push(...c,u),l;d+=n}else u.push(d),d="",c.push(u),u=new BP(null,t)}else o=!0,s=l,a=!1,d+=n}return t.type=null,t.#t=void 0,t.#r=[e.substring(n-1)],l}static fromGlob(e,t={}){const n=new BP(null,void 0,t);return BP.#p(e,n,0,t),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();const e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#l.nocase&&!this.#l.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;const o=(this.#l.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,o),{_src:t,_glob:e})}get options(){return this.#l}toRegExpSource(e){const t=e??!!this.#l.dot;if(this.#e===this&&this.#d(),!this.type){const n=this.isStart()&&this.isEnd(),r=this.#r.map(t=>{const[r,i,o,s]="string"==typeof t?BP.#f(t,this.#t,n):t.toRegExpSource(e);return this.#t=this.#t||o,this.#n=this.#n||s,r}).join("");let i="";if(this.isStart()&&"string"==typeof this.#r[0]){if(!(1===this.#r.length&&vP.has(this.#r[0]))){const n=bP,o=t&&n.has(r.charAt(0))||r.startsWith("\\.")&&n.has(r.charAt(2))||r.startsWith("\\.\\.")&&n.has(r.charAt(4)),s=!t&&!e&&n.has(r.charAt(0));i=o?"(?!(?:^|/)\\.\\.?(?:$|/))":s?yP:""}}let o="";this.isEnd()&&this.#e.#a&&"!"===this.#i?.type&&(o="(?:$|\\/)");return[i+r+o,gP(r),this.#t=!!this.#t,this.#n]}const n="*"===this.type||"+"===this.type,r="!"===this.type?"(?:(?!(?:":"(?:";let i=this.#h(t);if(this.isStart()&&this.isEnd()&&!i&&"!"!==this.type){const e=this.toString();return this.#r=[e],this.type=null,this.#t=void 0,[e,gP(this.toString()),!1,!1]}let o=!n||e||t?"":this.#h(!0);o===i&&(o=""),o&&(i=`(?:${i})(?:${o})*?`);let s="";if("!"===this.type&&this.#c)s=(this.isStart()&&!t?yP:"")+_P;else{s=r+i+("!"===this.type?"))"+(!this.isStart()||t||e?"":yP)+CP+")":"@"===this.type?")":"?"===this.type?")?":"+"===this.type&&o?")":"*"===this.type&&o?")?":`)${this.type}`)}return[s,gP(i),this.#t=!!this.#t,this.#n]}#h(e){return this.#r.map(t=>{if("string"==typeof t)throw new Error("string type in extglob ast??");const[n,r,i,o]=t.toRegExpSource(e);return this.#n=this.#n||o,n}).filter(e=>!(this.isStart()&&this.isEnd()&&!e)).join("|")}static#f(e,t,n=!1){let r=!1,i="",o=!1;for(let s=0;s<e.length;s++){const a=e.charAt(s);if(r)r=!1,i+=(EP.has(a)?"\\":"")+a;else if("\\"!==a){if("["===a){const[n,r,a,l]=hP(e,s);if(a){i+=n,o=o||r,s+=a-1,t=t||l;continue}}"*"!==a?"?"!==a?i+=IP(a):(i+=wP,t=!0):(i+=n&&"*"===e?_P:CP,t=!0)}else s===e.length-1?i+="\\\\":r=!0}return[i,gP(e),!!t,o]}}const DP=(e,{windowsPathsNoEscape:t=!1}={})=>t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),SP=(e,t,n={})=>(cP(t),!(!n.nocomment&&"#"===t.charAt(0))&&new ej(t,n).match(e)),kP=/^\*+([^+@!?\*\[\(]*)$/,xP=e=>t=>!t.startsWith(".")&&t.endsWith(e),QP=e=>t=>t.endsWith(e),NP=e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),TP=e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),RP=/^\*+\.\*+$/,FP=e=>!e.startsWith(".")&&e.includes("."),MP=e=>"."!==e&&".."!==e&&e.includes("."),OP=/^\.\*+$/,$P=e=>"."!==e&&".."!==e&&e.startsWith("."),LP=/^\*+$/,PP=e=>0!==e.length&&!e.startsWith("."),jP=e=>0!==e.length&&"."!==e&&".."!==e,UP=/^\?+([^+@!?\*\[\(]*)?$/,zP=([e,t=""])=>{const n=qP([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},GP=([e,t=""])=>{const n=JP([e]);return t?(t=t.toLowerCase(),e=>n(e)&&e.toLowerCase().endsWith(t)):n},HP=([e,t=""])=>{const n=JP([e]);return t?e=>n(e)&&e.endsWith(t):n},WP=([e,t=""])=>{const n=qP([e]);return t?e=>n(e)&&e.endsWith(t):n},qP=([e])=>{const t=e.length;return e=>e.length===t&&!e.startsWith(".")},JP=([e])=>{const t=e.length;return e=>e.length===t&&"."!==e&&".."!==e},KP="object"==typeof process&&process?"object"==typeof process.env&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";SP.sep="win32"===KP?{sep:"\\"}.sep:{sep:"/"}.sep;const ZP=Symbol("globstar **");SP.GLOBSTAR=ZP;SP.filter=(e,t={})=>n=>SP(n,e,t);const VP=(e,t={})=>Object.assign({},e,t);SP.defaults=e=>{if(!e||"object"!=typeof e||!Object.keys(e).length)return SP;const t=SP;return Object.assign((n,r,i={})=>t(n,r,VP(e,i)),{Minimatch:class extends t.Minimatch{constructor(t,n={}){super(t,VP(e,n))}static defaults(n){return t.defaults(VP(e,n)).Minimatch}},AST:class extends t.AST{constructor(t,n,r={}){super(t,n,VP(e,r))}static fromGlob(n,r={}){return t.AST.fromGlob(n,VP(e,r))}},unescape:(n,r={})=>t.unescape(n,VP(e,r)),escape:(n,r={})=>t.escape(n,VP(e,r)),filter:(n,r={})=>t.filter(n,VP(e,r)),defaults:n=>t.defaults(VP(e,n)),makeRe:(n,r={})=>t.makeRe(n,VP(e,r)),braceExpand:(n,r={})=>t.braceExpand(n,VP(e,r)),match:(n,r,i={})=>t.match(n,r,VP(e,i)),sep:t.sep,GLOBSTAR:ZP})};const YP=(e,t={})=>(cP(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:iP(e));SP.braceExpand=YP;SP.makeRe=(e,t={})=>new ej(e,t).makeRe();SP.match=(e,t,n={})=>{const r=new ej(t,n);return e=e.filter(e=>r.match(e)),r.options.nonull&&!e.length&&e.push(t),e};const XP=/[?*]|[+@!]\(.*?\)|\[|\]/;class ej{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){cP(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||KP,this.isWindows="win32"===this.platform,this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||!1===t.allowWindowsEscape,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=void 0!==t.windowsNoMagicRoot?t.windowsNoMagicRoot:!(!this.isWindows||!this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const e of this.set)for(const t of e)if("string"!=typeof t)return!0;return!1}debug(...e){}make(){const e=this.pattern,t=this.options;if(!t.nocomment&&"#"===e.charAt(0))return void(this.comment=!0);if(!e)return void(this.empty=!0);this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...e)=>console.error(...e)),this.debug(this.pattern,this.globSet);const n=this.globSet.map(e=>this.slashSplit(e));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((e,t,n)=>{if(this.isWindows&&this.windowsNoMagicRoot){const t=!(""!==e[0]||""!==e[1]||"?"!==e[2]&&XP.test(e[2])||XP.test(e[3])),n=/^[a-z]:/i.test(e[0]);if(t)return[...e.slice(0,4),...e.slice(4).map(e=>this.parse(e))];if(n)return[e[0],...e.slice(1).map(e=>this.parse(e))]}return e.map(e=>this.parse(e))});if(this.debug(this.pattern,r),this.set=r.filter(e=>-1===e.indexOf(!1)),this.isWindows)for(let i=0;i<this.set.length;i++){const e=this.set[i];""===e[0]&&""===e[1]&&"?"===this.globParts[i][2]&&"string"==typeof e[3]&&/^[a-z]:$/i.test(e[3])&&(e[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let n=0;n<e.length;n++)for(let t=0;t<e[n].length;t++)"**"===e[n][t]&&(e[n][t]="*");const{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):e=t>=1?this.levelOneOptimize(e):this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(e=>{let t=-1;for(;-1!==(t=e.indexOf("**",t+1));){let n=t;for(;"**"===e[n+1];)n++;n!==t&&e.splice(t,n-t)}return e})}levelOneOptimize(e){return e.map(e=>0===(e=e.reduce((e,t)=>{const n=e[e.length-1];return"**"===t&&"**"===n?e:".."===t&&n&&".."!==n&&"."!==n&&"**"!==n?(e.pop(),e):(e.push(t),e)},[])).length?[""]:e)}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){const r=e[n];1===n&&""===r&&""===e[0]||("."!==r&&""!==r||(t=!0,e.splice(n,1),n--))}"."!==e[0]||2!==e.length||"."!==e[1]&&""!==e[1]||(t=!0,e.pop())}let n=0;for(;-1!==(n=e.indexOf("..",n+1));){const r=e[n-1];r&&"."!==r&&".."!==r&&"**"!==r&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return 0===e.length?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let r=-1;for(;-1!==(r=n.indexOf("**",r+1));){let i=r;for(;"**"===n[i+1];)i++;i>r&&n.splice(r+1,i-r);let o=n[r+1];const s=n[r+2],a=n[r+3];if(".."!==o)continue;if(!s||"."===s||".."===s||!a||"."===a||".."===a)continue;t=!0,n.splice(r,1);const l=n.slice(0);l[r]="**",e.push(l),r--}if(!this.preserveMultipleSlashes){for(let e=1;e<n.length-1;e++){const r=n[e];1===e&&""===r&&""===n[0]||("."!==r&&""!==r||(t=!0,n.splice(e,1),e--))}"."!==n[0]||2!==n.length||"."!==n[1]&&""!==n[1]||(t=!0,n.pop())}let i=0;for(;-1!==(i=n.indexOf("..",i+1));){const e=n[i-1];if(e&&"."!==e&&".."!==e&&"**"!==e){t=!0;const e=1===i&&"**"===n[i+1]?["."]:[];n.splice(i-1,2,...e),0===n.length&&n.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){const r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(e=>e.length)}partsMatch(e,t,n=!1){let r=0,i=0,o=[],s="";for(;r<e.length&&i<t.length;)if(e[r]===t[i])o.push("b"===s?t[i]:e[r]),r++,i++;else if(n&&"**"===e[r]&&t[i]===e[r+1])o.push(e[r]),r++;else if(n&&"**"===t[i]&&e[r]===t[i+1])o.push(t[i]),i++;else if("*"!==e[r]||!t[i]||!this.options.dot&&t[i].startsWith(".")||"**"===t[i]){if("*"!==t[i]||!e[r]||!this.options.dot&&e[r].startsWith(".")||"**"===e[r])return!1;if("a"===s)return!1;s="b",o.push(t[i]),r++,i++}else{if("b"===s)return!1;s="a",o.push(e[r]),r++,i++}return e.length===t.length&&o}parseNegate(){if(this.nonegate)return;const e=this.pattern;let t=!1,n=0;for(let r=0;r<e.length&&"!"===e.charAt(r);r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){const r=this.options;if(this.isWindows){const n="string"==typeof e[0]&&/^[a-z]:$/i.test(e[0]),r=!n&&""===e[0]&&""===e[1]&&"?"===e[2]&&/^[a-z]:$/i.test(e[3]),i="string"==typeof t[0]&&/^[a-z]:$/i.test(t[0]),o=r?3:n?0:void 0,s=!i&&""===t[0]&&""===t[1]&&"?"===t[2]&&"string"==typeof t[3]&&/^[a-z]:$/i.test(t[3])?3:i?0:void 0;if("number"==typeof o&&"number"==typeof s){const[n,r]=[e[o],t[s]];n.toLowerCase()===r.toLowerCase()&&(t[s]=n,s>o?t=t.slice(s):o>s&&(e=e.slice(o)))}}const{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var o=0,s=0,a=e.length,l=t.length;o<a&&s<l;o++,s++){this.debug("matchOne loop");var u=t[s],c=e[o];if(this.debug(t,u,c),!1===u)return!1;if(u===ZP){this.debug("GLOBSTAR",[t,u,c]);var d=o,p=s+1;if(p===l){for(this.debug("** at the end");o<a;o++)if("."===e[o]||".."===e[o]||!r.dot&&"."===e[o].charAt(0))return!1;return!0}for(;d<a;){var f=e[d];if(this.debug("\nglobstar while",e,d,t,p,f),this.matchOne(e.slice(d),t.slice(p),n))return this.debug("globstar found match!",d,a,f),!0;if("."===f||".."===f||!r.dot&&"."===f.charAt(0)){this.debug("dot detected!",e,d,t,p);break}this.debug("globstar swallow a segment, and continue"),d++}return!(!n||(this.debug("\n>>> no match, partial?",e,d,t,p),d!==a))}let i;if("string"==typeof u?(i=c===u,this.debug("string match",u,c,i)):(i=u.test(c),this.debug("pattern match",u,c,i)),!i)return!1}if(o===a&&s===l)return!0;if(o===a)return n;if(s===l)return o===a-1&&""===e[o];throw new Error("wtf?")}braceExpand(){return YP(this.pattern,this.options)}parse(e){cP(e);const t=this.options;if("**"===e)return ZP;if(""===e)return"";let n,r=null;(n=e.match(LP))?r=t.dot?jP:PP:(n=e.match(kP))?r=(t.nocase?t.dot?TP:NP:t.dot?QP:xP)(n[1]):(n=e.match(UP))?r=(t.nocase?t.dot?GP:zP:t.dot?HP:WP)(n):(n=e.match(RP))?r=t.dot?MP:FP:(n=e.match(OP))&&(r=$P);const i=BP.fromGlob(e,this.options).toMMPattern();return r&&"object"==typeof i&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||!1===this.regexp)return this.regexp;const e=this.set;if(!e.length)return this.regexp=!1,this.regexp;const t=this.options,n=t.noglobstar?"[^/]*?":t.dot?"(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?":"(?:(?!(?:\\/|^)\\.).)*?",r=new Set(t.nocase?["i"]:[]);let i=e.map(e=>{const t=e.map(e=>{if(e instanceof RegExp)for(const t of e.flags.split(""))r.add(t);return"string"==typeof e?e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"):e===ZP?ZP:e._src});return t.forEach((e,r)=>{const i=t[r+1],o=t[r-1];e===ZP&&o!==ZP&&(void 0===o?void 0!==i&&i!==ZP?t[r+1]="(?:\\/|"+n+"\\/)?"+i:t[r]=n:void 0===i?t[r-1]=o+"(?:\\/|"+n+")?":i!==ZP&&(t[r-1]=o+"(?:\\/|\\/"+n+"\\/)"+i,t[r+1]=ZP))}),t.filter(e=>e!==ZP).join("/")}).join("|");const[o,s]=e.length>1?["(?:",")"]:["",""];i="^"+o+i+s+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...r].join(""))}catch(a){this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return""===e;if("/"===e&&t)return!0;const n=this.options;this.isWindows&&(e=e.split("\\").join("/"));const r=this.slashSplit(e);this.debug(this.pattern,"split",r);const i=this.set;this.debug(this.pattern,"set",i);let o=r[r.length-1];if(!o)for(let s=r.length-2;!o&&s>=0;s--)o=r[s];for(let s=0;s<i.length;s++){const e=i[s];let a=r;n.matchBase&&1===e.length&&(a=[o]);if(this.matchOne(a,e,t))return!!n.flipNegate||!this.negate}return!n.flipNegate&&this.negate}static defaults(e){return SP.defaults(e).Minimatch}}SP.AST=BP,SP.Minimatch=ej,SP.escape=DP,SP.unescape=gP;const tj="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,nj=new Set,rj="object"==typeof process&&process?process:{},ij=(e,t,n,r)=>{"function"==typeof rj.emitWarning?rj.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)};let oj=globalThis.AbortController,sj=globalThis.AbortSignal;if(void 0===oj){sj=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},oj=class{constructor(){t()}signal=new sj;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==rj.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,ij("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}const aj=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),lj=e=>aj(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?uj:null:null;class uj extends Array{constructor(e){super(e),this.fill(0)}}class cj{heap;length;static#g=!1;static create(e){const t=lj(e);if(!t)return[];cj.#g=!0;const n=new cj(e,t);return cj.#g=!1,n}constructor(e,t){if(!cj.#g)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class dj{#A;#m;#y;#b;#v;#E;#I;#w;get perf(){return this.#w}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#C;#_;#B;#D;#S;#k;#x;#Q;#N;#T;#R;#F;#M;#O;#$;#L;#P;#j;static unsafeExposeInternals(e){return{starts:e.#M,ttls:e.#O,sizes:e.#F,keyMap:e.#B,keyList:e.#D,valList:e.#S,next:e.#k,prev:e.#x,get head(){return e.#Q},get tail(){return e.#N},free:e.#T,isBackgroundFetch:t=>e.#U(t),backgroundFetch:(t,n,r,i)=>e.#z(t,n,r,i),moveToTail:t=>e.#G(t),indexes:t=>e.#H(t),rindexes:t=>e.#W(t),isStale:t=>e.#q(t)}}get max(){return this.#A}get maxSize(){return this.#m}get calculatedSize(){return this.#_}get size(){return this.#C}get fetchMethod(){return this.#E}get memoMethod(){return this.#I}get dispose(){return this.#y}get onInsert(){return this.#b}get disposeAfter(){return this.#v}constructor(e){const{max:t=0,ttl:n,ttlResolution:r=1,ttlAutopurge:i,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:a,dispose:l,onInsert:u,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:p,maxSize:f=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:A,memoMethod:m,noDeleteOnFetchRejection:y,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:v,allowStaleOnFetchAbort:E,ignoreFetchAbort:I,perf:w}=e;if(void 0!==w&&"function"!=typeof w?.now)throw new TypeError("perf option must have a now() method if specified");if(this.#w=w??tj,0!==t&&!aj(t))throw new TypeError("max option must be a nonnegative integer");const C=t?lj(t):Array;if(!C)throw new Error("invalid max value: "+t);if(this.#A=t,this.#m=f,this.maxEntrySize=h||this.#m,this.sizeCalculation=g,this.sizeCalculation){if(!this.#m&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==m&&"function"!=typeof m)throw new TypeError("memoMethod must be a function if defined");if(this.#I=m,void 0!==A&&"function"!=typeof A)throw new TypeError("fetchMethod must be a function if specified");if(this.#E=A,this.#L=!!A,this.#B=new Map,this.#D=new Array(t).fill(void 0),this.#S=new Array(t).fill(void 0),this.#k=new C(t),this.#x=new C(t),this.#Q=0,this.#N=0,this.#T=cj.create(t),this.#C=0,this.#_=0,"function"==typeof l&&(this.#y=l),"function"==typeof u&&(this.#b=u),"function"==typeof c?(this.#v=c,this.#R=[]):(this.#v=void 0,this.#R=void 0),this.#$=!!this.#y,this.#j=!!this.#b,this.#P=!!this.#v,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!y,this.allowStaleOnFetchRejection=!!v,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!I,0!==this.maxEntrySize){if(0!==this.#m&&!aj(this.#m))throw new TypeError("maxSize must be a positive integer if specified");if(!aj(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#J()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=aj(r)||0===r?r:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!aj(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#K()}if(0===this.#A&&0===this.ttl&&0===this.#m)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#A&&!this.#m){const e="LRU_CACHE_UNBOUNDED";if((e=>!nj.has(e))(e)){nj.add(e);ij("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,dj)}}}getRemainingTTL(e){return this.#B.has(e)?1/0:0}#K(){const e=new uj(this.#A),t=new uj(this.#A);this.#O=e,this.#M=t,this.#Z=(n,r,i=this.#w.now())=>{if(t[n]=0!==r?i:0,e[n]=r,0!==r&&this.ttlAutopurge){const e=setTimeout(()=>{this.#q(n)&&this.#V(this.#D[n],"expire")},r+1);e.unref&&e.unref()}},this.#Y=n=>{t[n]=0!==e[n]?this.#w.now():0},this.#X=(i,o)=>{if(e[o]){const s=e[o],a=t[o];if(!s||!a)return;i.ttl=s,i.start=a,i.now=n||r();const l=i.now-a;i.remainingTTL=s-l}};let n=0;const r=()=>{const e=this.#w.now();if(this.ttlResolution>0){n=e;const t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{const o=this.#B.get(i);if(void 0===o)return 0;const s=e[o],a=t[o];if(!s||!a)return 1/0;return s-((n||r())-a)},this.#q=i=>{const o=t[i],s=e[i];return!!s&&!!o&&(n||r())-o>s}}#Y=()=>{};#X=()=>{};#Z=()=>{};#q=()=>!1;#J(){const e=new uj(this.#A);this.#_=0,this.#F=e,this.#ee=t=>{this.#_-=e[t],e[t]=0},this.#te=(e,t,n,r)=>{if(this.#U(t))return 0;if(!aj(n)){if(!r)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof r)throw new TypeError("sizeCalculation must be a function");if(n=r(t,e),!aj(n))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return n},this.#ne=(t,n,r)=>{if(e[t]=n,this.#m){const n=this.#m-e[t];for(;this.#_>n;)this.#re(!0)}this.#_+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#_)}}#ee=e=>{};#ne=(e,t,n)=>{};#te=(e,t,n,r)=>{if(n||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#H({allowStale:e=this.allowStale}={}){if(this.#C)for(let t=this.#N;this.#ie(t)&&(!e&&this.#q(t)||(yield t),t!==this.#Q);)t=this.#x[t]}*#W({allowStale:e=this.allowStale}={}){if(this.#C)for(let t=this.#Q;this.#ie(t)&&(!e&&this.#q(t)||(yield t),t!==this.#N);)t=this.#k[t]}#ie(e){return void 0!==e&&this.#B.get(this.#D[e])===e}*entries(){for(const e of this.#H())void 0===this.#S[e]||void 0===this.#D[e]||this.#U(this.#S[e])||(yield[this.#D[e],this.#S[e]])}*rentries(){for(const e of this.#W())void 0===this.#S[e]||void 0===this.#D[e]||this.#U(this.#S[e])||(yield[this.#D[e],this.#S[e]])}*keys(){for(const e of this.#H()){const t=this.#D[e];void 0===t||this.#U(this.#S[e])||(yield t)}}*rkeys(){for(const e of this.#W()){const t=this.#D[e];void 0===t||this.#U(this.#S[e])||(yield t)}}*values(){for(const e of this.#H()){void 0===this.#S[e]||this.#U(this.#S[e])||(yield this.#S[e])}}*rvalues(){for(const e of this.#W()){void 0===this.#S[e]||this.#U(this.#S[e])||(yield this.#S[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const n of this.#H()){const r=this.#S[n],i=this.#U(r)?r.__staleWhileFetching:r;if(void 0!==i&&e(i,this.#D[n],this))return this.get(this.#D[n],t)}}forEach(e,t=this){for(const n of this.#H()){const r=this.#S[n],i=this.#U(r)?r.__staleWhileFetching:r;void 0!==i&&e.call(t,i,this.#D[n],this)}}rforEach(e,t=this){for(const n of this.#W()){const r=this.#S[n],i=this.#U(r)?r.__staleWhileFetching:r;void 0!==i&&e.call(t,i,this.#D[n],this)}}purgeStale(){let e=!1;for(const t of this.#W({allowStale:!0}))this.#q(t)&&(this.#V(this.#D[t],"expire"),e=!0);return e}info(e){const t=this.#B.get(e);if(void 0===t)return;const n=this.#S[t],r=this.#U(n)?n.__staleWhileFetching:n;if(void 0===r)return;const i={value:r};if(this.#O&&this.#M){const e=this.#O[t],n=this.#M[t];if(e&&n){const t=e-(this.#w.now()-n);i.ttl=t,i.start=Date.now()}}return this.#F&&(i.size=this.#F[t]),i}dump(){const e=[];for(const t of this.#H({allowStale:!0})){const n=this.#D[t],r=this.#S[t],i=this.#U(r)?r.__staleWhileFetching:r;if(void 0===i||void 0===n)continue;const o={value:i};if(this.#O&&this.#M){o.ttl=this.#O[t];const e=this.#w.now()-this.#M[t];o.start=Math.floor(Date.now()-e)}this.#F&&(o.size=this.#F[t]),e.unshift([n,o])}return e}load(e){this.clear();for(const[t,n]of e){if(n.start){const e=Date.now()-n.start;n.start=this.#w.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(void 0===t)return this.delete(e),this;const{ttl:r=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:a}=n;let{noUpdateTTL:l=this.noUpdateTTL}=n;const u=this.#te(e,t,n.size||0,s);if(this.maxEntrySize&&u>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#V(e,"set"),this;let c=0===this.#C?void 0:this.#B.get(e);if(void 0===c)c=0===this.#C?this.#N:0!==this.#T.length?this.#T.pop():this.#C===this.#A?this.#re(!1):this.#C,this.#D[c]=e,this.#S[c]=t,this.#B.set(e,c),this.#k[this.#N]=c,this.#x[c]=this.#N,this.#N=c,this.#C++,this.#ne(c,u,a),a&&(a.set="add"),l=!1,this.#j&&this.#b?.(t,e,"add");else{this.#G(c);const n=this.#S[c];if(t!==n){if(this.#L&&this.#U(n)){n.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=n;void 0===t||o||(this.#$&&this.#y?.(t,e,"set"),this.#P&&this.#R?.push([t,e,"set"]))}else o||(this.#$&&this.#y?.(n,e,"set"),this.#P&&this.#R?.push([n,e,"set"]));if(this.#ee(c),this.#ne(c,u,a),this.#S[c]=t,a){a.set="replace";const e=n&&this.#U(n)?n.__staleWhileFetching:n;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update");this.#j&&this.onInsert?.(t,e,t===n?"update":"replace")}if(0===r||this.#O||this.#K(),this.#O&&(l||this.#Z(c,r,i),a&&this.#X(a,c)),!o&&this.#P&&this.#R){const e=this.#R;let t;for(;t=e?.shift();)this.#v?.(...t)}return this}pop(){try{for(;this.#C;){const e=this.#S[this.#Q];if(this.#re(!0),this.#U(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#P&&this.#R){const e=this.#R;let t;for(;t=e?.shift();)this.#v?.(...t)}}}#re(e){const t=this.#Q,n=this.#D[t],r=this.#S[t];return this.#L&&this.#U(r)?r.__abortController.abort(new Error("evicted")):(this.#$||this.#P)&&(this.#$&&this.#y?.(r,n,"evict"),this.#P&&this.#R?.push([r,n,"evict"])),this.#ee(t),e&&(this.#D[t]=void 0,this.#S[t]=void 0,this.#T.push(t)),1===this.#C?(this.#Q=this.#N=0,this.#T.length=0):this.#Q=this.#k[t],this.#B.delete(n),this.#C--,t}has(e,t={}){const{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#B.get(e);if(void 0!==i){const e=this.#S[i];if(this.#U(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#q(i))return n&&this.#Y(i),r&&(r.has="hit",this.#X(r,i)),!0;r&&(r.has="stale",this.#X(r,i))}else r&&(r.has="miss");return!1}peek(e,t={}){const{allowStale:n=this.allowStale}=t,r=this.#B.get(e);if(void 0===r||!n&&this.#q(r))return;const i=this.#S[r];return this.#U(i)?i.__staleWhileFetching:i}#z(e,t,n,r){const i=void 0===t?void 0:this.#S[t];if(this.#U(i))return i;const o=new oj,{signal:s}=n;s?.addEventListener("abort",()=>o.abort(s.reason),{signal:o.signal});const a={signal:o.signal,options:n,context:r},l=(r,i=!1)=>{const{aborted:s}=o.signal,l=n.ignoreFetchAbort&&void 0!==r;if(n.status&&(s&&!i?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,l&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),s&&!l&&!i)return u(o.signal.reason);const d=c;return this.#S[t]===c&&(void 0===r?void 0!==d.__staleWhileFetching?this.#S[t]=d.__staleWhileFetching:this.#V(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,a.options))),r},u=r=>{const{aborted:i}=o.signal,s=i&&n.allowStaleOnFetchAbort,a=s||n.allowStaleOnFetchRejection,l=a||n.noDeleteOnFetchRejection,u=c;if(this.#S[t]===c){!l||void 0===u.__staleWhileFetching?this.#V(e,"fetch"):s||(this.#S[t]=u.__staleWhileFetching)}if(a)return n.status&&void 0!==u.__staleWhileFetching&&(n.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw r};n.status&&(n.status.fetchDispatched=!0);const c=new Promise((t,r)=>{const s=this.#E?.(e,i,a);s&&s instanceof Promise&&s.then(e=>t(void 0===e?void 0:e),r),o.signal.addEventListener("abort",()=>{n.ignoreFetchAbort&&!n.allowStaleOnFetchAbort||(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))})}).then(l,e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e))),d=Object.assign(c,{__abortController:o,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,d,{...a.options,status:void 0}),t=this.#B.get(e)):this.#S[t]=d,d}#U(e){if(!this.#L)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof oj}async fetch(e,t={}){const{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:f=this.allowStaleOnFetchAbort,context:h,forceRefresh:g=!1,status:A,signal:m}=t;if(!this.#L)return A&&(A.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:A});const y={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:s,size:a,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:f,ignoreFetchAbort:p,status:A,signal:m};let b=this.#B.get(e);if(void 0===b){A&&(A.fetch="miss");const t=this.#z(e,b,y,h);return t.__returned=t}{const t=this.#S[b];if(this.#U(t)){const e=n&&void 0!==t.__staleWhileFetching;return A&&(A.fetch="inflight",e&&(A.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#q(b);if(!g&&!i)return A&&(A.fetch="hit"),this.#G(b),r&&this.#Y(b),A&&this.#X(A,b),t;const o=this.#z(e,b,y,h),s=void 0!==o.__staleWhileFetching&&n;return A&&(A.fetch=i?"stale":"refresh",s&&i&&(A.returnedStale=!0)),s?o.__staleWhileFetching:o.__returned=o}}async forceFetch(e,t={}){const n=await this.fetch(e,t);if(void 0===n)throw new Error("fetch() returned undefined");return n}memo(e,t={}){const n=this.#I;if(!n)throw new Error("no memoMethod provided to constructor");const{context:r,forceRefresh:i,...o}=t,s=this.get(e,o);if(!i&&void 0!==s)return s;const a=n(e,s,{options:o,context:r});return this.set(e,a,o),a}get(e,t={}){const{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:o}=t,s=this.#B.get(e);if(void 0!==s){const t=this.#S[s],a=this.#U(t);return o&&this.#X(o,s),this.#q(s)?(o&&(o.get="stale"),a?(o&&n&&void 0!==t.__staleWhileFetching&&(o.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#V(e,"expire"),o&&n&&(o.returnedStale=!0),n?t:void 0)):(o&&(o.get="hit"),a?t.__staleWhileFetching:(this.#G(s),r&&this.#Y(s),t))}o&&(o.get="miss")}#oe(e,t){this.#x[t]=e,this.#k[e]=t}#G(e){e!==this.#N&&(e===this.#Q?this.#Q=this.#k[e]:this.#oe(this.#x[e],this.#k[e]),this.#oe(this.#N,e),this.#N=e)}delete(e){return this.#V(e,"delete")}#V(e,t){let n=!1;if(0!==this.#C){const r=this.#B.get(e);if(void 0!==r)if(n=!0,1===this.#C)this.#se(t);else{this.#ee(r);const n=this.#S[r];if(this.#U(n)?n.__abortController.abort(new Error("deleted")):(this.#$||this.#P)&&(this.#$&&this.#y?.(n,e,t),this.#P&&this.#R?.push([n,e,t])),this.#B.delete(e),this.#D[r]=void 0,this.#S[r]=void 0,r===this.#N)this.#N=this.#x[r];else if(r===this.#Q)this.#Q=this.#k[r];else{const e=this.#x[r];this.#k[e]=this.#k[r];const t=this.#k[r];this.#x[t]=this.#x[r]}this.#C--,this.#T.push(r)}}if(this.#P&&this.#R?.length){const e=this.#R;let t;for(;t=e?.shift();)this.#v?.(...t)}return n}clear(){return this.#se("delete")}#se(e){for(const t of this.#W({allowStale:!0})){const n=this.#S[t];if(this.#U(n))n.__abortController.abort(new Error("deleted"));else{const r=this.#D[t];this.#$&&this.#y?.(n,r,e),this.#P&&this.#R?.push([n,r,e])}}if(this.#B.clear(),this.#S.fill(void 0),this.#D.fill(void 0),this.#O&&this.#M&&(this.#O.fill(0),this.#M.fill(0)),this.#F&&this.#F.fill(0),this.#Q=0,this.#N=0,this.#T.length=0,this.#_=0,this.#C=0,this.#P&&this.#R){const e=this.#R;let t;for(;t=e?.shift();)this.#v?.(...t)}}}const pj="object"==typeof process&&process?process:{stdout:null,stderr:null},fj=e=>!!e&&"object"==typeof e&&(e instanceof Vj||e instanceof Ee||hj(e)||gj(e)),hj=e=>!!e&&"object"==typeof e&&e instanceof a&&"function"==typeof e.pipe&&e.pipe!==Ee.Writable.prototype.pipe,gj=e=>!!e&&"object"==typeof e&&e instanceof a&&"function"==typeof e.write&&"function"==typeof e.end,Aj=Symbol("EOF"),mj=Symbol("maybeEmitEnd"),yj=Symbol("emittedEnd"),bj=Symbol("emittingEnd"),vj=Symbol("emittedError"),Ej=Symbol("closed"),Ij=Symbol("read"),wj=Symbol("flush"),Cj=Symbol("flushChunk"),_j=Symbol("encoding"),Bj=Symbol("decoder"),Dj=Symbol("flowing"),Sj=Symbol("paused"),kj=Symbol("resume"),xj=Symbol("buffer"),Qj=Symbol("pipes"),Nj=Symbol("bufferLength"),Tj=Symbol("bufferPush"),Rj=Symbol("bufferShift"),Fj=Symbol("objectMode"),Mj=Symbol("destroyed"),Oj=Symbol("error"),$j=Symbol("emitData"),Lj=Symbol("emitEnd"),Pj=Symbol("emitEnd2"),jj=Symbol("async"),Uj=Symbol("abort"),zj=Symbol("aborted"),Gj=Symbol("signal"),Hj=Symbol("dataListeners"),Wj=Symbol("discarded"),qj=e=>Promise.resolve().then(e),Jj=e=>e();class Kj{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[kj](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}}class Zj extends Kj{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=e=>t.emit("error",e),e.on("error",this.proxyErrors)}}class Vj extends a{[Dj]=!1;[Sj]=!1;[Qj]=[];[xj]=[];[Fj];[_j];[jj];[Bj];[Aj]=!1;[yj]=!1;[bj]=!1;[Ej]=!1;[vj]=null;[Nj]=0;[Mj]=!1;[Gj];[zj]=!1;[Hj]=0;[Wj]=!1;writable=!0;readable=!0;constructor(...e){const t=e[0]||{};if(super(),t.objectMode&&"string"==typeof t.encoding)throw new TypeError("Encoding and objectMode may not be used together");t.objectMode?(this[Fj]=!0,this[_j]=null):(e=>!e.objectMode&&!!e.encoding&&"buffer"!==e.encoding)(t)?(this[_j]=t.encoding,this[Fj]=!1):(this[Fj]=!1,this[_j]=null),this[jj]=!!t.async,this[Bj]=this[_j]?new Ce(this[_j]):null,t&&!0===t.debugExposeBuffer&&Object.defineProperty(this,"buffer",{get:()=>this[xj]}),t&&!0===t.debugExposePipes&&Object.defineProperty(this,"pipes",{get:()=>this[Qj]});const{signal:n}=t;n&&(this[Gj]=n,n.aborted?this[Uj]():n.addEventListener("abort",()=>this[Uj]()))}get bufferLength(){return this[Nj]}get encoding(){return this[_j]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Fj]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[jj]}set async(e){this[jj]=this[jj]||!!e}[Uj](){this[zj]=!0,this.emit("abort",this[Gj]?.reason),this.destroy(this[Gj]?.reason)}get aborted(){return this[zj]}set aborted(e){}write(e,t,n){if(this[zj])return!1;if(this[Aj])throw new Error("write after end");if(this[Mj])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;"function"==typeof t&&(n=t,t="utf8"),t||(t="utf8");const r=this[jj]?qj:Jj;if(!this[Fj]&&!Buffer.isBuffer(e))if(i=e,!Buffer.isBuffer(i)&&ArrayBuffer.isView(i))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if((e=>e instanceof ArrayBuffer||!!e&&"object"==typeof e&&e.constructor&&"ArrayBuffer"===e.constructor.name&&e.byteLength>=0)(e))e=Buffer.from(e);else if("string"!=typeof e)throw new Error("Non-contiguous data written to non-objectMode stream");var i;return this[Fj]?(this[Dj]&&0!==this[Nj]&&this[wj](!0),this[Dj]?this.emit("data",e):this[Tj](e),0!==this[Nj]&&this.emit("readable"),n&&r(n),this[Dj]):e.length?("string"!=typeof e||t===this[_j]&&!this[Bj]?.lastNeed||(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[_j]&&(e=this[Bj].write(e)),this[Dj]&&0!==this[Nj]&&this[wj](!0),this[Dj]?this.emit("data",e):this[Tj](e),0!==this[Nj]&&this.emit("readable"),n&&r(n),this[Dj]):(0!==this[Nj]&&this.emit("readable"),n&&r(n),this[Dj])}read(e){if(this[Mj])return null;if(this[Wj]=!1,0===this[Nj]||0===e||e&&e>this[Nj])return this[mj](),null;this[Fj]&&(e=null),this[xj].length>1&&!this[Fj]&&(this[xj]=[this[_j]?this[xj].join(""):Buffer.concat(this[xj],this[Nj])]);const t=this[Ij](e||null,this[xj][0]);return this[mj](),t}[Ij](e,t){if(this[Fj])this[Rj]();else{const n=t;e===n.length||null===e?this[Rj]():"string"==typeof n?(this[xj][0]=n.slice(e),t=n.slice(0,e),this[Nj]-=e):(this[xj][0]=n.subarray(e),t=n.subarray(0,e),this[Nj]-=e)}return this.emit("data",t),this[xj].length||this[Aj]||this.emit("drain"),t}end(e,t,n){return"function"==typeof e&&(n=e,e=void 0),"function"==typeof t&&(n=t,t="utf8"),void 0!==e&&this.write(e,t),n&&this.once("end",n),this[Aj]=!0,this.writable=!1,!this[Dj]&&this[Sj]||this[mj](),this}[kj](){this[Mj]||(this[Hj]||this[Qj].length||(this[Wj]=!0),this[Sj]=!1,this[Dj]=!0,this.emit("resume"),this[xj].length?this[wj]():this[Aj]?this[mj]():this.emit("drain"))}resume(){return this[kj]()}pause(){this[Dj]=!1,this[Sj]=!0,this[Wj]=!1}get destroyed(){return this[Mj]}get flowing(){return this[Dj]}get paused(){return this[Sj]}[Tj](e){this[Fj]?this[Nj]+=1:this[Nj]+=e.length,this[xj].push(e)}[Rj](){return this[Fj]?this[Nj]-=1:this[Nj]-=this[xj][0].length,this[xj].shift()}[wj](e=!1){do{}while(this[Cj](this[Rj]())&&this[xj].length);e||this[xj].length||this[Aj]||this.emit("drain")}[Cj](e){return this.emit("data",e),this[Dj]}pipe(e,t){if(this[Mj])return e;this[Wj]=!1;const n=this[yj];return t=t||{},e===pj.stdout||e===pj.stderr?t.end=!1:t.end=!1!==t.end,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[Qj].push(t.proxyErrors?new Zj(this,e,t):new Kj(this,e,t)),this[jj]?qj(()=>this[kj]()):this[kj]()),e}unpipe(e){const t=this[Qj].find(t=>t.dest===e);t&&(1===this[Qj].length?(this[Dj]&&0===this[Hj]&&(this[Dj]=!1),this[Qj]=[]):this[Qj].splice(this[Qj].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){const n=super.on(e,t);if("data"===e)this[Wj]=!1,this[Hj]++,this[Qj].length||this[Dj]||this[kj]();else if("readable"===e&&0!==this[Nj])super.emit("readable");else if((e=>"end"===e||"finish"===e||"prefinish"===e)(e)&&this[yj])super.emit(e),this.removeAllListeners(e);else if("error"===e&&this[vj]){const e=t;this[jj]?qj(()=>e.call(this,this[vj])):e.call(this,this[vj])}return n}removeListener(e,t){return this.off(e,t)}off(e,t){const n=super.off(e,t);return"data"===e&&(this[Hj]=this.listeners("data").length,0!==this[Hj]||this[Wj]||this[Qj].length||(this[Dj]=!1)),n}removeAllListeners(e){const t=super.removeAllListeners(e);return"data"!==e&&void 0!==e||(this[Hj]=0,this[Wj]||this[Qj].length||(this[Dj]=!1)),t}get emittedEnd(){return this[yj]}[mj](){this[bj]||this[yj]||this[Mj]||0!==this[xj].length||!this[Aj]||(this[bj]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ej]&&this.emit("close"),this[bj]=!1)}emit(e,...t){const n=t[0];if("error"!==e&&"close"!==e&&e!==Mj&&this[Mj])return!1;if("data"===e)return!(!this[Fj]&&!n)&&(this[jj]?(qj(()=>this[$j](n)),!0):this[$j](n));if("end"===e)return this[Lj]();if("close"===e){if(this[Ej]=!0,!this[yj]&&!this[Mj])return!1;const e=super.emit("close");return this.removeAllListeners("close"),e}if("error"===e){this[vj]=n,super.emit(Oj,n);const e=!(this[Gj]&&!this.listeners("error").length)&&super.emit("error",n);return this[mj](),e}if("resume"===e){const e=super.emit("resume");return this[mj](),e}if("finish"===e||"prefinish"===e){const t=super.emit(e);return this.removeAllListeners(e),t}const r=super.emit(e,...t);return this[mj](),r}[$j](e){for(const n of this[Qj])!1===n.dest.write(e)&&this.pause();const t=!this[Wj]&&super.emit("data",e);return this[mj](),t}[Lj](){return!this[yj]&&(this[yj]=!0,this.readable=!1,this[jj]?(qj(()=>this[Pj]()),!0):this[Pj]())}[Pj](){if(this[Bj]){const e=this[Bj].end();if(e){for(const t of this[Qj])t.dest.write(e);this[Wj]||super.emit("data",e)}}for(const t of this[Qj])t.end();const e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){const e=Object.assign([],{dataLength:0});this[Fj]||(e.dataLength=0);const t=this.promise();return this.on("data",t=>{e.push(t),this[Fj]||(e.dataLength+=t.length)}),await t,e}async concat(){if(this[Fj])throw new Error("cannot concat in objectMode");const e=await this.collect();return this[_j]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Mj,()=>t(new Error("stream destroyed"))),this.on("error",e=>t(e)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Wj]=!1;let e=!1;const t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();const n=this.read();if(null!==n)return Promise.resolve({done:!1,value:n});if(this[Aj])return t();let r,i;const o=e=>{this.off("data",s),this.off("end",a),this.off(Mj,l),t(),i(e)},s=e=>{this.off("error",o),this.off("end",a),this.off(Mj,l),this.pause(),r({value:e,done:!!this[Aj]})},a=()=>{this.off("error",o),this.off("data",s),this.off(Mj,l),t(),r({done:!0,value:void 0})},l=()=>o(new Error("stream destroyed"));return new Promise((e,t)=>{i=t,r=e,this.once(Mj,l),this.once("error",o),this.once("end",a),this.once("data",s)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Wj]=!1;let e=!1;const t=()=>(this.pause(),this.off(Oj,t),this.off(Mj,t),this.off("end",t),e=!0,{done:!0,value:void 0});return this.once("end",t),this.once(Oj,t),this.once(Mj,t),{next:()=>{if(e)return t();const n=this.read();return null===n?t():{done:!1,value:n}},throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[Mj])return e?this.emit("error",e):this.emit(Mj),this;this[Mj]=!0,this[Wj]=!0,this[xj].length=0,this[Nj]=0;return"function"!=typeof this.close||this[Ej]||this.close(),e?this.emit("error",e):this.emit(Mj),this}static get isStream(){return fj}}const Yj={lstatSync:ie,readdir:re,readdirSync:ne,readlinkSync:te,realpathSync:ee.native,promises:{lstat:O,readdir:M,readlink:F,realpath:R}},Xj=e=>e&&e!==Yj&&e!==l?{...Yj,...e,promises:{...Yj.promises,...e.promises||{}}}:Yj,eU=/^\\\\\?\\([a-z]:)\\?$/i,tU=/[\\\/]/,nU=10,rU=15,iU=-16,oU=128,sU=256,aU=512,lU=e=>e.isFile()?8:e.isDirectory()?4:e.isSymbolicLink()?nU:e.isCharacterDevice()?2:e.isBlockDevice()?6:e.isSocket()?12:e.isFIFO()?1:0,uU=new Map,cU=e=>{const t=uU.get(e);if(t)return t;const n=e.normalize("NFKD");return uU.set(e,n),n},dU=new Map,pU=e=>{const t=dU.get(e);if(t)return t;const n=cU(e.toLowerCase());return dU.set(e,n),n};class fU extends dj{constructor(){super({max:256})}}class hU extends dj{constructor(e=16384){super({maxSize:e,sizeCalculation:e=>e.length+1})}}const gU=Symbol("PathScurry setAsCwd");class AU{name;root;roots;parent;nocase;isCWD=!1;#ae;#le;get dev(){return this.#le}#ue;get mode(){return this.#ue}#ce;get nlink(){return this.#ce}#de;get uid(){return this.#de}#pe;get gid(){return this.#pe}#fe;get rdev(){return this.#fe}#he;get blksize(){return this.#he}#ge;get ino(){return this.#ge}#C;get size(){return this.#C}#Ae;get blocks(){return this.#Ae}#me;get atimeMs(){return this.#me}#ye;get mtimeMs(){return this.#ye}#be;get ctimeMs(){return this.#be}#ve;get birthtimeMs(){return this.#ve}#Ee;get atime(){return this.#Ee}#Ie;get mtime(){return this.#Ie}#we;get ctime(){return this.#we}#Ce;get birthtime(){return this.#Ce}#_e;#Be;#De;#Se;#ke;#xe;#Qe;#Ne;#Te;#Re;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=0,n,r,i,o,s){this.name=e,this.#_e=i?pU(e):cU(e),this.#Qe=1023&t,this.nocase=i,this.roots=r,this.root=n||this,this.#Ne=o,this.#De=s.fullpath,this.#ke=s.relative,this.#xe=s.relativePosix,this.parent=s.parent,this.parent?this.#ae=this.parent.#ae:this.#ae=Xj(s.fs)}depth(){return void 0!==this.#Be?this.#Be:this.parent?this.#Be=this.parent.depth()+1:this.#Be=0}childrenCache(){return this.#Ne}resolve(e){if(!e)return this;const t=this.getRootString(e),n=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#Fe(n):this.#Fe(n)}#Fe(e){let t=this;for(const n of e)t=t.child(n);return t}children(){const e=this.#Ne.get(this);if(e)return e;const t=Object.assign([],{provisional:0});return this.#Ne.set(this,t),this.#Qe&=-17,t}child(e,t){if(""===e||"."===e)return this;if(".."===e)return this.parent||this;const n=this.children(),r=this.nocase?pU(e):cU(e);for(const a of n)if(a.#_e===r)return a;const i=this.parent?this.sep:"",o=this.#De?this.#De+i+e:void 0,s=this.newChild(e,0,{...t,parent:this,fullpath:o});return this.canReaddir()||(s.#Qe|=oU),n.push(s),s}relative(){if(this.isCWD)return"";if(void 0!==this.#ke)return this.#ke;const e=this.name,t=this.parent;if(!t)return this.#ke=this.name;const n=t.relative();return n+(n&&t.parent?this.sep:"")+e}relativePosix(){if("/"===this.sep)return this.relative();if(this.isCWD)return"";if(void 0!==this.#xe)return this.#xe;const e=this.name,t=this.parent;if(!t)return this.#xe=this.fullpathPosix();const n=t.relativePosix();return n+(n&&t.parent?"/":"")+e}fullpath(){if(void 0!==this.#De)return this.#De;const e=this.name,t=this.parent;if(!t)return this.#De=this.name;const n=t.fullpath()+(t.parent?this.sep:"")+e;return this.#De=n}fullpathPosix(){if(void 0!==this.#Se)return this.#Se;if("/"===this.sep)return this.#Se=this.fullpath();if(!this.parent){const e=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(e)?this.#Se=`//?/${e}`:this.#Se=e}const e=this.parent,t=e.fullpathPosix(),n=t+(t&&e.parent?"/":"")+this.name;return this.#Se=n}isUnknown(){return 0===(this.#Qe&rU)}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return 8===(this.#Qe&rU)}isDirectory(){return 4===(this.#Qe&rU)}isCharacterDevice(){return 2===(this.#Qe&rU)}isBlockDevice(){return 6===(this.#Qe&rU)}isFIFO(){return 1===(this.#Qe&rU)}isSocket(){return 12===(this.#Qe&rU)}isSymbolicLink(){return(this.#Qe&nU)===nU}lstatCached(){return 32&this.#Qe?this:void 0}readlinkCached(){return this.#Te}realpathCached(){return this.#Re}readdirCached(){const e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#Te)return!0;if(!this.parent)return!1;const e=this.#Qe&rU;return!(0!==e&&e!==nU||this.#Qe&sU||this.#Qe&oU)}calledReaddir(){return!!(16&this.#Qe)}isENOENT(){return!!(this.#Qe&oU)}isNamed(e){return this.nocase?this.#_e===pU(e):this.#_e===cU(e)}async readlink(){const e=this.#Te;if(e)return e;if(this.canReadlink()&&this.parent)try{const e=await this.#ae.promises.readlink(this.fullpath()),t=(await this.parent.realpath())?.resolve(e);if(t)return this.#Te=t}catch(t){return void this.#Me(t.code)}}readlinkSync(){const e=this.#Te;if(e)return e;if(this.canReadlink()&&this.parent)try{const e=this.#ae.readlinkSync(this.fullpath()),t=this.parent.realpathSync()?.resolve(e);if(t)return this.#Te=t}catch(t){return void this.#Me(t.code)}}#Oe(e){this.#Qe|=16;for(let t=e.provisional;t<e.length;t++){const n=e[t];n&&n.#$e()}}#$e(){this.#Qe&oU||(this.#Qe=(this.#Qe|oU)&iU,this.#Le())}#Le(){const e=this.children();e.provisional=0;for(const t of e)t.#$e()}#Pe(){this.#Qe|=aU,this.#je()}#je(){if(64&this.#Qe)return;let e=this.#Qe;4===(e&rU)&&(e&=iU),this.#Qe=64|e,this.#Le()}#Ue(e=""){"ENOTDIR"===e||"EPERM"===e?this.#je():"ENOENT"===e?this.#$e():this.children().provisional=0}#ze(e=""){if("ENOTDIR"===e){this.parent.#je()}else"ENOENT"===e&&this.#$e()}#Me(e=""){let t=this.#Qe;t|=sU,"ENOENT"===e&&(t|=oU),"EINVAL"!==e&&"UNKNOWN"!==e||(t&=iU),this.#Qe=t,"ENOTDIR"===e&&this.parent&&this.parent.#je()}#Ge(e,t){return this.#He(e,t)||this.#We(e,t)}#We(e,t){const n=lU(e),r=this.newChild(e.name,n,{parent:this}),i=r.#Qe&rU;return 4!==i&&i!==nU&&0!==i&&(r.#Qe|=64),t.unshift(r),t.provisional++,r}#He(e,t){for(let n=t.provisional;n<t.length;n++){const r=t[n];if((this.nocase?pU(e.name):cU(e.name))===r.#_e)return this.#qe(e,r,n,t)}}#qe(e,t,n,r){const i=t.name;return t.#Qe=t.#Qe&iU|lU(e),i!==e.name&&(t.name=e.name),n!==r.provisional&&(n===r.length-1?r.pop():r.splice(n,1),r.unshift(t)),r.provisional++,t}async lstat(){if(0===(this.#Qe&oU))try{return this.#Je(await this.#ae.promises.lstat(this.fullpath())),this}catch(e){this.#ze(e.code)}}lstatSync(){if(0===(this.#Qe&oU))try{return this.#Je(this.#ae.lstatSync(this.fullpath())),this}catch(e){this.#ze(e.code)}}#Je(e){const{atime:t,atimeMs:n,birthtime:r,birthtimeMs:i,blksize:o,blocks:s,ctime:a,ctimeMs:l,dev:u,gid:c,ino:d,mode:p,mtime:f,mtimeMs:h,nlink:g,rdev:A,size:m,uid:y}=e;this.#Ee=t,this.#me=n,this.#Ce=r,this.#ve=i,this.#he=o,this.#Ae=s,this.#we=a,this.#be=l,this.#le=u,this.#pe=c,this.#ge=d,this.#ue=p,this.#Ie=f,this.#ye=h,this.#ce=g,this.#fe=A,this.#C=m,this.#de=y;const b=lU(e);this.#Qe=this.#Qe&iU|b|32,0!==b&&4!==b&&b!==nU&&(this.#Qe|=64)}#Ke=[];#Ze=!1;#Ve(e){this.#Ze=!1;const t=this.#Ke.slice();this.#Ke.length=0,t.forEach(t=>t(null,e))}readdirCB(e,t=!1){if(!this.canReaddir())return void(t?e(null,[]):queueMicrotask(()=>e(null,[])));const n=this.children();if(this.calledReaddir()){const r=n.slice(0,n.provisional);return void(t?e(null,r):queueMicrotask(()=>e(null,r)))}if(this.#Ke.push(e),this.#Ze)return;this.#Ze=!0;const r=this.fullpath();this.#ae.readdir(r,{withFileTypes:!0},(e,t)=>{if(e)this.#Ue(e.code),n.provisional=0;else{for(const e of t)this.#Ge(e,n);this.#Oe(n)}this.#Ve(n.slice(0,n.provisional))})}#Ye;async readdir(){if(!this.canReaddir())return[];const e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);const t=this.fullpath();if(this.#Ye)await this.#Ye;else{let r=()=>{};this.#Ye=new Promise(e=>r=e);try{for(const n of await this.#ae.promises.readdir(t,{withFileTypes:!0}))this.#Ge(n,e);this.#Oe(e)}catch(n){this.#Ue(n.code),e.provisional=0}this.#Ye=void 0,r()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];const e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);const t=this.fullpath();try{for(const n of this.#ae.readdirSync(t,{withFileTypes:!0}))this.#Ge(n,e);this.#Oe(e)}catch(n){this.#Ue(n.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(704&this.#Qe)return!1;const e=rU&this.#Qe;return 0===e||4===e||e===nU}shouldWalk(e,t){return!(4&~this.#Qe)&&!(704&this.#Qe)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#Re)return this.#Re;if(!(896&this.#Qe))try{const e=await this.#ae.promises.realpath(this.fullpath());return this.#Re=this.resolve(e)}catch(e){this.#Pe()}}realpathSync(){if(this.#Re)return this.#Re;if(!(896&this.#Qe))try{const e=this.#ae.realpathSync(this.fullpath());return this.#Re=this.resolve(e)}catch(e){this.#Pe()}}[gU](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;const t=new Set([]);let n=[],r=this;for(;r&&r.parent;)t.add(r),r.#ke=n.join(this.sep),r.#xe=n.join("/"),r=r.parent,n.push("..");for(r=e;r&&r.parent&&!t.has(r);)r.#ke=void 0,r.#xe=void 0,r=r.parent}}class mU extends AU{sep="\\";splitSep=tU;constructor(e,t=0,n,r,i,o,s){super(e,t,n,r,i,o,s)}newChild(e,t=0,n={}){return new mU(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return E.parse(e).root}getRoot(e){if((e=(e=>e.replace(/\//g,"\\").replace(eU,"$1\\"))(e.toUpperCase()))===this.root.name)return this.root;for(const[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new vU(e,this).root}sameRoot(e,t=this.root.name){return(e=e.toUpperCase().replace(/\//g,"\\").replace(eU,"$1\\"))===t}}class yU extends AU{splitSep="/";sep="/";constructor(e,t=0,n,r,i,o,s){super(e,t,n,r,i,o,s)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=0,n={}){return new yU(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}}class bU{root;rootPath;roots;cwd;#Xe;#et;#Ne;nocase;#ae;constructor(e=process.cwd(),t,n,{nocase:r,childrenCacheSize:i=16384,fs:o=Yj}={}){this.#ae=Xj(o),(e instanceof URL||e.startsWith("file://"))&&(e=B(e));const s=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(s),this.#Xe=new fU,this.#et=new fU,this.#Ne=new hU(i);const a=s.substring(this.rootPath.length).split(n);if(1!==a.length||a[0]||a.pop(),void 0===r)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=r,this.root=this.newRoot(this.#ae),this.roots[this.rootPath]=this.root;let l=this.root,u=a.length-1;const c=t.sep;let d=this.rootPath,p=!1;for(const f of a){const e=u--;l=l.child(f,{relative:new Array(e).fill("..").join(c),relativePosix:new Array(e).fill("..").join("/"),fullpath:d+=(p?"":c)+f}),p=!0}this.cwd=l}depth(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#Ne}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){const n=e[i];if(n&&"."!==n&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}const n=this.#Xe.get(t);if(void 0!==n)return n;const r=this.cwd.resolve(t).fullpath();return this.#Xe.set(t,r),r}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){const n=e[i];if(n&&"."!==n&&(t=t?`${n}/${t}`:n,this.isAbsolute(n)))break}const n=this.#et.get(t);if(void 0!==n)return n;const r=this.cwd.resolve(t).fullpathPosix();return this.#et.set(t,r),r}relative(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n}=t;if(e.canReaddir()){const t=await e.readdir();return n?t:t.map(e=>e.name)}return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0}=t;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(e=>e.name):[]}async lstat(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return"string"==typeof e&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e.withFileTypes,e=this.cwd);const n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e.withFileTypes,e=this.cwd);const n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e.withFileTypes,e=this.cwd);const n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e.withFileTypes,e=this.cwd);const n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t,s=[];i&&!i(e)||s.push(n?e:e.fullpath());const a=new Set,l=(e,t)=>{a.add(e),e.readdirCB((e,u)=>{if(e)return t(e);let c=u.length;if(!c)return t();const d=()=>{0===--c&&t()};for(const t of u)i&&!i(t)||s.push(n?t:t.fullpath()),r&&t.isSymbolicLink()?t.realpath().then(e=>e?.isUnknown()?e.lstat():e).then(e=>e?.shouldWalk(a,o)?l(e,d):d()):t.shouldWalk(a,o)?l(t,d):d()},!0)},u=e;return new Promise((e,t)=>{l(u,n=>{if(n)return t(n);e(s)})})}walkSync(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t,s=[];i&&!i(e)||s.push(n?e:e.fullpath());const a=new Set([e]);for(const l of a){const e=l.readdirSync();for(const t of e){i&&!i(t)||s.push(n?t:t.fullpath());let e=t;if(t.isSymbolicLink()){if(!r||!(e=t.realpathSync()))continue;e.isUnknown()&&e.lstatSync()}e.shouldWalk(a,o)&&a.add(e)}}return s}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t;i&&!i(e)||(yield n?e:e.fullpath());const s=new Set([e]);for(const a of s){const e=a.readdirSync();for(const t of e){i&&!i(t)||(yield n?t:t.fullpath());let e=t;if(t.isSymbolicLink()){if(!r||!(e=t.realpathSync()))continue;e.isUnknown()&&e.lstatSync()}e.shouldWalk(s,o)&&s.add(e)}}}stream(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t,s=new Vj({objectMode:!0});i&&!i(e)||s.write(n?e:e.fullpath());const a=new Set,l=[e];let u=0;const c=()=>{let e=!1;for(;!e;){const t=l.shift();if(!t)return void(0===u&&s.end());u++,a.add(t);const d=(t,f,h=!1)=>{if(t)return s.emit("error",t);if(r&&!h){const e=[];for(const t of f)t.isSymbolicLink()&&e.push(t.realpath().then(e=>e?.isUnknown()?e.lstat():e));if(e.length)return void Promise.all(e).then(()=>d(null,f,!0))}for(const r of f)!r||i&&!i(r)||s.write(n?r:r.fullpath())||(e=!0);u--;for(const e of f){const t=e.realpathCached()||e;t.shouldWalk(a,o)&&l.push(t)}e&&!s.flowing?s.once("drain",c):p||c()};let p=!0;t.readdirCB(d,!0),p=!1}};return c(),s}streamSync(e=this.cwd,t={}){"string"==typeof e?e=this.cwd.resolve(e):e instanceof AU||(t=e,e=this.cwd);const{withFileTypes:n=!0,follow:r=!1,filter:i,walkFilter:o}=t,s=new Vj({objectMode:!0}),a=new Set;i&&!i(e)||s.write(n?e:e.fullpath());const l=[e];let u=0;const c=()=>{let e=!1;for(;!e;){const t=l.shift();if(!t)return void(0===u&&s.end());u++,a.add(t);const c=t.readdirSync();for(const r of c)i&&!i(r)||s.write(n?r:r.fullpath())||(e=!0);u--;for(const e of c){let t=e;if(e.isSymbolicLink()){if(!r||!(t=e.realpathSync()))continue;t.isUnknown()&&t.lstatSync()}t.shouldWalk(a,o)&&l.push(t)}}e&&!s.flowing&&s.once("drain",c)};return c(),s}chdir(e=this.cwd){const t=this.cwd;this.cwd="string"==typeof e?this.cwd.resolve(e):e,this.cwd[gU](t)}}class vU extends bU{sep="\\";constructor(e=process.cwd(),t={}){const{nocase:n=!0}=t;super(e,E,"\\",{...t,nocase:n}),this.nocase=n;for(let r=this.cwd;r;r=r.parent)r.nocase=this.nocase}parseRootPath(e){return E.parse(e).root.toUpperCase()}newRoot(e){return new mU(this.rootPath,4,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}}class EU extends bU{sep="/";constructor(e=process.cwd(),t={}){const{nocase:n=!1}=t;super(e,I,"/",{...t,nocase:n}),this.nocase=n}parseRootPath(e){return"/"}newRoot(e){return new yU(this.rootPath,4,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}}class IU extends EU{constructor(e=process.cwd(),t={}){const{nocase:n=!0}=t;super(e,{...t,nocase:n})}}process.platform;const wU="win32"===process.platform?vU:"darwin"===process.platform?IU:EU;class CU{#tt;#nt;#rt;length;#it;#ot;#st;#at;#lt;#ut;#ct=!0;constructor(e,t,n,r){if(!(e.length>=1))throw new TypeError("empty pattern list");if(!(t.length>=1))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#tt=e,this.#nt=t,this.#rt=n,this.#it=r,0===this.#rt)if(this.isUNC()){const[e,t,n,r,...i]=this.#tt,[o,s,a,l,...u]=this.#nt;""===i[0]&&(i.shift(),u.shift());const c=[e,t,n,r,""].join("/"),d=[o,s,a,l,""].join("/");this.#tt=[c,...i],this.#nt=[d,...u],this.length=this.#tt.length}else if(this.isDrive()||this.isAbsolute()){const[e,...t]=this.#tt,[n,...r]=this.#nt;""===t[0]&&(t.shift(),r.shift());const i=e+"/",o=n+"/";this.#tt=[i,...t],this.#nt=[o,...r],this.length=this.#tt.length}}pattern(){return this.#tt[this.#rt]}isString(){return"string"==typeof this.#tt[this.#rt]}isGlobstar(){return this.#tt[this.#rt]===ZP}isRegExp(){return this.#tt[this.#rt]instanceof RegExp}globString(){return this.#st=this.#st||(0===this.#rt?this.isAbsolute()?this.#nt[0]+this.#nt.slice(1).join("/"):this.#nt.join("/"):this.#nt.slice(this.#rt).join("/"))}hasMore(){return this.length>this.#rt+1}rest(){return void 0!==this.#ot?this.#ot:this.hasMore()?(this.#ot=new CU(this.#tt,this.#nt,this.#rt+1,this.#it),this.#ot.#ut=this.#ut,this.#ot.#lt=this.#lt,this.#ot.#at=this.#at,this.#ot):this.#ot=null}isUNC(){const e=this.#tt;return void 0!==this.#lt?this.#lt:this.#lt="win32"===this.#it&&0===this.#rt&&""===e[0]&&""===e[1]&&"string"==typeof e[2]&&!!e[2]&&"string"==typeof e[3]&&!!e[3]}isDrive(){const e=this.#tt;return void 0!==this.#at?this.#at:this.#at="win32"===this.#it&&0===this.#rt&&this.length>1&&"string"==typeof e[0]&&/^[a-z]:$/i.test(e[0])}isAbsolute(){const e=this.#tt;return void 0!==this.#ut?this.#ut:this.#ut=""===e[0]&&e.length>1||this.isDrive()||this.isUNC()}root(){const e=this.#tt[0];return"string"==typeof e&&this.isAbsolute()&&0===this.#rt?e:""}checkFollowGlobstar(){return!(0===this.#rt||!this.isGlobstar()||!this.#ct)}markFollowGlobstar(){return!(0===this.#rt||!this.isGlobstar()||!this.#ct)&&(this.#ct=!1,!0)}}const _U="object"==typeof process&&process&&"string"==typeof process.platform?process.platform:"linux";class BU{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:r,noglobstar:i,platform:o=_U}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:!0,nobrace:t,nocase:n,noext:r,noglobstar:i,optimizationLevel:2,platform:o,nocomment:!0,nonegate:!0};for(const s of e)this.add(s)}add(e){const t=new ej(e,this.mmopts);for(let n=0;n<t.set.length;n++){const e=t.set[n],r=t.globParts[n];if(!e||!r)throw new Error("invalid pattern object");for(;"."===e[0]&&"."===r[0];)e.shift(),r.shift();const i=new CU(e,r,0,this.platform),o=new ej(i.globString(),this.mmopts),s="**"===r[r.length-1],a=i.isAbsolute();a?this.absolute.push(o):this.relative.push(o),s&&(a?this.absoluteChildren.push(o):this.relativeChildren.push(o))}}ignored(e){const t=e.fullpath(),n=`${t}/`,r=e.relative()||".",i=`${r}/`;for(const o of this.relative)if(o.match(r)||o.match(i))return!0;for(const o of this.absolute)if(o.match(t)||o.match(n))return!0;return!1}childrenIgnored(e){const t=e.fullpath()+"/",n=(e.relative()||".")+"/";for(const r of this.relativeChildren)if(r.match(n))return!0;for(const r of this.absoluteChildren)if(r.match(t))return!0;return!1}}class DU{store;constructor(e=new Map){this.store=e}copy(){return new DU(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){const n=e.fullpath(),r=this.store.get(n);r?r.add(t.globString()):this.store.set(n,new Set([t.globString()]))}}class SU{store=new Map;add(e,t,n){const r=(t?2:0)|(n?1:0),i=this.store.get(e);this.store.set(e,void 0===i?r:r&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(2&t),!!(1&t)])}}class kU{store=new Map;add(e,t){if(!e.canReaddir())return;const n=this.store.get(e);n?n.find(e=>e.globString()===t.globString())||n.push(t):this.store.set(e,[t])}get(e){const t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}}class xU{hasWalkedCache;matches=new SU;subwalks=new kU;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new DU}processPatterns(e,t){this.patterns=t;const n=t.map(t=>[e,t]);for(let[r,i]of n){this.hasWalkedCache.storeWalked(r,i);const e=i.root(),t=i.isAbsolute()&&!1!==this.opts.absolute;if(e){r=r.resolve("/"===e&&void 0!==this.opts.root?this.opts.root:e);const t=i.rest();if(!t){this.matches.add(r,!0,!1);continue}i=t}if(r.isENOENT())continue;let n,o,s=!1;for(;"string"==typeof(n=i.pattern())&&(o=i.rest());){const e=r.resolve(n);r=e,i=o,s=!0}if(n=i.pattern(),o=i.rest(),s){if(this.hasWalkedCache.hasWalked(r,i))continue;this.hasWalkedCache.storeWalked(r,i)}if("string"==typeof n){const e=".."===n||""===n||"."===n;this.matches.add(r.resolve(n),t,e);continue}if(n===ZP){(!r.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(r,i);const e=o?.pattern(),n=o?.rest();if(o&&(""!==e&&"."!==e||n)){if(".."===e){const e=r.parent||r;n?this.hasWalkedCache.hasWalked(e,n)||this.subwalks.add(e,n):this.matches.add(e,t,!0)}}else this.matches.add(r,t,""===e||"."===e)}else n instanceof RegExp&&this.subwalks.add(r,i)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new xU(this.opts,this.hasWalkedCache)}filterEntries(e,t){const n=this.subwalks.get(e),r=this.child();for(const i of t)for(const e of n){const t=e.isAbsolute(),n=e.pattern(),o=e.rest();n===ZP?r.testGlobstar(i,e,o,t):n instanceof RegExp?r.testRegExp(i,n,o,t):r.testString(i,n,o,t)}return r}testGlobstar(e,t,n,r){if(!this.dot&&e.name.startsWith(".")||(t.hasMore()||this.matches.add(e,r,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){const t=n.pattern();if("string"==typeof t&&".."!==t&&""!==t&&"."!==t)this.testString(e,t,n.rest(),r);else if(".."===t){const t=e.parent||e;this.subwalks.add(t,n)}else t instanceof RegExp&&this.testRegExp(e,t,n.rest(),r)}}testRegExp(e,t,n,r){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}testString(e,t,n,r){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,!1))}}class QU{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#dt=[];#pt;#ft;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#ft=n.posix||"win32"!==n.platform?"/":"\\",this.includeChildMatches=!1!==n.includeChildMatches,(n.ignore||!this.includeChildMatches)&&(this.#pt=((e,t)=>"string"==typeof e?new BU([e],t):Array.isArray(e)?new BU(e,t):e)(n.ignore??[],n),!this.includeChildMatches&&"function"!=typeof this.#pt.add)){throw new Error("cannot ignore child matches, ignore lacks add() method.")}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#dt.length=0}))}#ht(e){return this.seen.has(e)||!!this.#pt?.ignored?.(e)}#gt(e){return!!this.#pt?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;let e;for(this.paused=!1;!this.paused&&(e=this.#dt.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#dt.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}const r=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){const e=await r.realpath();e&&(e.isUnknown()||this.opts.stat)&&await e.lstat()}return this.matchCheckTest(r,t)}matchCheckTest(e,t){return!e||!(this.maxDepth===1/0||e.depth()<=this.maxDepth)||t&&!e.canReaddir()||this.opts.nodir&&e.isDirectory()||this.opts.nodir&&this.opts.follow&&e.isSymbolicLink()&&e.realpathCached()?.isDirectory()||this.#ht(e)?void 0:e}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}const r=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){const e=r.realpathSync();e&&(e?.isUnknown()||this.opts.stat)&&e.lstatSync()}return this.matchCheckTest(r,t)}matchFinish(e,t){if(this.#ht(e))return;if(!this.includeChildMatches&&this.#pt?.add){const t=`${e.relativePosix()}/**`;this.#pt.add(t)}const n=void 0===this.opts.absolute?t:this.opts.absolute;this.seen.add(e);const r=this.opts.mark&&e.isDirectory()?this.#ft:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){const t=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(t+r)}else{const t=this.opts.posix?e.relativePosix():e.relative(),n=this.opts.dotRelative&&!t.startsWith(".."+this.#ft)?"."+this.#ft:"";this.matchEmit(t?n+t+r:"."+r)}}async match(e,t,n){const r=await this.matchCheck(e,n);r&&this.matchFinish(r,t)}matchSync(e,t,n){const r=this.matchCheckSync(e,n);r&&this.matchFinish(r,t)}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new xU(this.opts),n)}walkCB2(e,t,n,r){if(this.#gt(e))return r();if(this.signal?.aborted&&r(),this.paused)return void this.onResume(()=>this.walkCB2(e,t,n,r));n.processPatterns(e,t);let i=1;const o=()=>{0===--i&&r()};for(const[s,a,l]of n.matches.entries())this.#ht(s)||(i++,this.match(s,a,l).then(()=>o()));for(const s of n.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;const e=s.readdirCached();s.calledReaddir()?this.walkCB3(s,e,n,o):s.readdirCB((e,t)=>this.walkCB3(s,t,n,o),!0)}o()}walkCB3(e,t,n,r){n=n.filterEntries(e,t);let i=1;const o=()=>{0===--i&&r()};for(const[s,a,l]of n.matches.entries())this.#ht(s)||(i++,this.match(s,a,l).then(()=>o()));for(const[s,a]of n.subwalks.entries())i++,this.walkCB2(s,a,n.child(),o);o()}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new xU(this.opts),n)}walkCB2Sync(e,t,n,r){if(this.#gt(e))return r();if(this.signal?.aborted&&r(),this.paused)return void this.onResume(()=>this.walkCB2Sync(e,t,n,r));n.processPatterns(e,t);let i=1;const o=()=>{0===--i&&r()};for(const[s,a,l]of n.matches.entries())this.#ht(s)||this.matchSync(s,a,l);for(const s of n.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;const e=s.readdirSync();this.walkCB3Sync(s,e,n,o)}o()}walkCB3Sync(e,t,n,r){n=n.filterEntries(e,t);let i=1;const o=()=>{0===--i&&r()};for(const[s,a,l]of n.matches.entries())this.#ht(s)||this.matchSync(s,a,l);for(const[s,a]of n.subwalks.entries())i++,this.walkCB2Sync(s,a,n.child(),o);o()}}class NU extends QU{matches=new Set;constructor(e,t,n){super(e,t,n)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}}class TU extends QU{results;constructor(e,t,n){super(e,t,n),this.results=new Vj({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){const e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}}const RU="object"==typeof process&&process&&"string"==typeof process.platform?process.platform:"linux";class FU{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=B(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=!1!==t.includeChildMatches,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth="number"==typeof t.maxDepth?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&void 0!==this.absolute)throw new Error("cannot set absolute and withFileTypes:true");if("string"==typeof e&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||!1===t.allowWindowsEscape,this.windowsPathsNoEscape&&(e=e.map(e=>e.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(e=>e.includes("/")?e:`./**/${e}`)}if(this.pattern=e,this.platform=t.platform||RU,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,void 0!==t.nocase&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{const e="win32"===t.platform?vU:"darwin"===t.platform?IU:t.platform?EU:wU;this.scurry=new e(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;const n="darwin"===this.platform||"win32"===this.platform,r={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(e=>new ej(e,r)),[o,s]=i.reduce((e,t)=>(e[0].push(...t.set),e[1].push(...t.globParts),e),[[],[]]);this.patterns=o.map((e,t)=>{const n=s[t];if(!n)throw new Error("invalid pattern object");return new CU(e,n,0,this.platform)})}async walk(){return[...await new NU(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new NU(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new TU(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new TU(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}}function MU(e,t={}){return new FU(e,t).streamSync()}function OU(e,t={}){return new FU(e,t).stream()}function $U(e,t={}){return new FU(e,t).walkSync()}async function LU(e,t={}){return new FU(e,t).walk()}function PU(e,t={}){return new FU(e,t).iterateSync()}function jU(e,t={}){return new FU(e,t).iterate()}const UU=MU,zU=Object.assign(OU,{sync:MU}),GU=PU,HU=Object.assign(jU,{sync:PU}),WU=Object.assign($U,{stream:MU,iterate:PU}),qU=Object.assign(LU,{glob:LU,globSync:$U,sync:WU,globStream:OU,stream:zU,globStreamSync:MU,streamSync:UU,globIterate:jU,iterate:HU,globIterateSync:PU,iterateSync:GU,Glob:FU,hasMagic:(e,t={})=>{Array.isArray(e)||(e=[e]);for(const n of e)if(new ej(n,t).hasMagic())return!0;return!1},escape:DP,unescape:gP});async function JU(e){try{const t=se.join(e,".git");return(await _e.stat(t)).isDirectory()}catch{return!1}}async function KU(e){const t=await async function(e){let t=se.resolve(e);for(;;){const e=se.join(t,".git");try{if((await _e.stat(e)).isDirectory())return t}catch(qK){const n="object"==typeof qK&&null!==qK&&"code"in qK&&"ENOENT"===qK.code,r="test"===process.env.NODE_ENV||process.env.VITEST;n||r||ex.warn(`Unexpected error checking for .git directory at ${e}:`,qK)}const n=se.dirname(t);if(n===t)return null;t=n}}(e);return{projectRoot:t,isGitRepo:!!t&&await JU(t),workingDirectory:se.resolve(e)}}qU.glob=qU;class ZU{gitIgnorePatterns=[];embedderIgnorePatterns=[];projectRoot;static DEFAULT_IGNORE_PATTERNS=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/coverage/**","**/.nyc_output/**","**/tmp/**","**/temp/**","**/*.log","**/.DS_Store","**/Thumbs.db"];constructor(e){this.projectRoot=se.resolve(e),this.loadIgnorePatterns()}async loadIgnorePatterns(){try{await JU(this.projectRoot)&&await this.loadGitIgnorePatterns(),await this.loadEmbedderIgnorePatterns()}catch(qK){}}async loadGitIgnorePatterns(){try{const e=se.join(this.projectRoot,".gitignore"),t=await _e.readFile(e,"utf-8");this.gitIgnorePatterns=this.parseIgnoreFile(t)}catch{}}async loadEmbedderIgnorePatterns(){try{const e=se.join(this.projectRoot,".embedderignore"),t=await _e.readFile(e,"utf-8");this.embedderIgnorePatterns=this.parseIgnoreFile(t)}catch{}}parseIgnoreFile(e){return e.split("\n").map(e=>e.trim()).filter(e=>e&&!e.startsWith("#")).map(e=>e.startsWith("**/")||e.startsWith("/")?e:`**/${e}`)}shouldIgnoreFile(e,t={}){const{respectGitIgnore:n=!0,respectEmbedderIgnore:r=!0}=t;return!!this.matchesPatterns(e,ZU.DEFAULT_IGNORE_PATTERNS)||(!(!n||!this.matchesPatterns(e,this.gitIgnorePatterns))||!(!r||!this.matchesPatterns(e,this.embedderIgnorePatterns)))}matchesPatterns(e,t){const n=se.normalize(e).replace(/\\/g,"/");return t.some(e=>{const t=e.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]");try{return new RegExp(`^${t}$`).test(n)}catch{return!1}})}filterFiles(e,t={}){return e.filter(e=>!this.shouldIgnoreFile(e,t))}getGitIgnorePatterns(){return[...this.gitIgnorePatterns]}getEmbedderIgnorePatterns(){return[...this.embedderIgnorePatterns]}}class VU{projectContext=null;contextCache=new Map;cacheExpiry=3e5;lastCacheUpdate=null;constructor(){}async getContextualSuggestions(e,t=20){const n=`contextual_${e}`;if(this.isCacheValid(n)){const e=this.contextCache.get(n);if(e)return e.slice(0,t)}this.projectContext=await KU(e);const r=new ZU(this.projectContext.projectRoot||e),i=[],o=await this.getCurrentDirectoryFiles(e,r);if(i.push(...o),this.projectContext.projectRoot&&this.projectContext.projectRoot!==e){const e=await this.getProjectRootFiles(r);i.push(...e)}const s=await this.getImportantProjectFiles(r);i.push(...s);const a=await this.getRecentlyModifiedFiles(e,r);i.push(...a);const l=this.deduplicateAndRank(i).slice(0,t);return this.contextCache.set(n,l),this.lastCacheUpdate=new Date,l}async getCurrentDirectoryFiles(e,t){const n=[];try{const r=await _e.readdir(e,{withFileTypes:!0});for(const i of r){if(i.name.startsWith("."))continue;const r=se.join(e,i.name),o=se.relative(e,r);if(!t.shouldIgnoreFile(o))try{const e=await _e.stat(r),t={path:r,relativePath:se.normalize(o),isDirectory:i.isDirectory(),lastModified:e.mtime,size:e.size,relevanceScore:this.calculateRelevanceScore(i.name,"current-directory"),contextReason:"Current directory"};n.push(t)}catch{continue}}}catch{}return n}async getProjectRootFiles(e){if(!this.projectContext?.projectRoot)return[];const t=[],n=["README.md","README.txt","package.json","tsconfig.json","Makefile","CMakeLists.txt",".gitignore","Cargo.toml","pom.xml","build.gradle","requirements.txt","Pipfile"];for(const r of n)try{const n=se.join(this.projectContext.projectRoot,r),i=await _e.stat(n),o=se.relative(this.projectContext.workingDirectory,n);if(e.shouldIgnoreFile(o))continue;const s={path:n,relativePath:se.normalize(o),isDirectory:!1,lastModified:i.mtime,size:i.size,relevanceScore:this.calculateRelevanceScore(r,"project-root"),contextReason:"Important project file"};t.push(s)}catch{}return t}async getImportantProjectFiles(e){if(!this.projectContext?.projectRoot)return[];const t=[],n=["src","lib","app","components","utils","services","config","docs","test","tests","__tests__"];for(const r of n)try{const n=se.join(this.projectContext.projectRoot,r);await _e.access(n);const i=se.relative(this.projectContext.workingDirectory,n);if(e.shouldIgnoreFile(i))continue;const o=await _e.stat(n),s={path:n,relativePath:se.normalize(i),isDirectory:!0,lastModified:o.mtime,size:o.size,relevanceScore:this.calculateRelevanceScore(r,"important-directory"),contextReason:"Important project directory"};t.push(s)}catch{}return t}async getRecentlyModifiedFiles(e,t,n=5){const r=[],i=new Date(Date.now()-864e5);try{const o=await this.findRecentFiles(e,t,i);o.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime());for(const e of o.slice(0,n)){const t={...e,relevanceScore:this.calculateRelevanceScore(se.basename(e.relativePath),"recently-modified"),contextReason:"Recently modified"};r.push(t)}}catch{}return r}async findRecentFiles(e,t,n,r=0,i=3){if(r>i)return[];const o=[];try{const s=await _e.readdir(e,{withFileTypes:!0});for(const a of s){const s=se.join(e,a.name),l=se.relative(this.projectContext?.workingDirectory||e,s);if(!t.shouldIgnoreFile(l))try{const e=await _e.stat(s);if(a.isFile()&&e.mtime>n)o.push({path:s,relativePath:se.normalize(l),isDirectory:!1,lastModified:e.mtime,size:e.size});else if(a.isDirectory()&&!a.name.startsWith(".")){const e=await this.findRecentFiles(s,t,n,r+1,i);o.push(...e)}}catch{continue}}}catch{}return o}calculateRelevanceScore(e,t){let n=50;switch(t){case"current-directory":n+=30;break;case"project-root":n+=25;break;case"important-directory":n+=20;break;case"recently-modified":n+=15}const r=e.toLowerCase();return(r.includes("config")||r.includes(".json")||r.includes("makefile")||r.includes(".toml"))&&(n+=15),(r.includes("readme")||r.includes(".md")||r.includes("doc"))&&(n+=10),(r.endsWith(".ts")||r.endsWith(".js")||r.endsWith(".tsx")||r.endsWith(".jsx")||r.endsWith(".py")||r.endsWith(".java")||r.endsWith(".c")||r.endsWith(".cpp"))&&(n+=10),"src"!==r&&"lib"!==r&&"app"!==r||(n+=15),n}deduplicateAndRank(e){const t=new Set,n=[];for(const r of e){const e=se.normalize(r.relativePath).toLowerCase();t.has(e)||(t.add(e),n.push(r))}return n.sort((e,t)=>t.relevanceScore-e.relevanceScore)}isCacheValid(e){if(!this.lastCacheUpdate||!this.contextCache.has(e))return!1;return(new Date).getTime()-this.lastCacheUpdate.getTime()<this.cacheExpiry}clearCache(){this.contextCache.clear(),this.lastCacheUpdate=null}getProjectContext(){return this.projectContext}}class YU{name="directory-listing";canHandle(e){return e.includes("/")||e.endsWith("/")}async search(e,t,n,r){const i=e,o=i.lastIndexOf("/"),s=-1===o?".":i.substring(0,o+1),a=-1===o?i:i.substring(o+1),l=se.resolve(t,s),u=a.toLowerCase();try{const e=await _e.readdir(l,{withFileTypes:!0}),i=[];for(const o of e){if(!a.startsWith(".")&&o.name.startsWith("."))continue;if(!o.name.toLowerCase().startsWith(u))continue;const e=se.join(l,o.name),s=se.relative(t,e);if(r.shouldIgnoreFile(s,{respectGitIgnore:n.respectGitIgnore,respectEmbedderIgnore:n.respectEmbedderIgnore}))continue;const c=await _e.stat(e);i.push({path:e,relativePath:se.normalize(s),isDirectory:o.isDirectory(),lastModified:c.mtime,size:c.size})}return i.slice(0,n.maxResults||50)}catch{return[]}}}class XU{name="recursive-search";canHandle(e){return e.length>0&&!e.includes("/")}async search(e,t,n,r){const i=n.maxDepth||10,o=n.maxResults||50;return this.findFilesRecursively(t,e,r,{respectGitIgnore:n.respectGitIgnore,respectEmbedderIgnore:n.respectEmbedderIgnore},"",0,i,o)}async findFilesRecursively(e,t,n,r,i="",o=0,s=10,a=50){if(o>s)return[];const l=t.toLowerCase();let u=[];try{const c=await _e.readdir(e,{withFileTypes:!0});for(const d of c){if(u.length>=a)break;const c=se.join(i,d.name),p=se.join(e,d.name);if((t.startsWith(".")||!d.name.startsWith("."))&&!n.shouldIgnoreFile(c,r)){if(d.name.toLowerCase().startsWith(l))try{const e=await _e.stat(p);u.push({path:p,relativePath:se.normalize(c),isDirectory:d.isDirectory(),lastModified:e.mtime,size:e.size})}catch{continue}if(d.isDirectory()&&"node_modules"!==d.name&&!d.name.startsWith(".")&&u.length<a){const e=await this.findFilesRecursively(p,t,n,r,c,o+1,s,a-u.length);u=u.concat(e)}}}}catch{}return u.slice(0,a)}}class ez{name="glob-search";canHandle(e){return e.length>0&&!e.includes("/")}async search(e,t,n,r){try{const i=`**/${e}*`,o=await qU(i,{cwd:t,dot:e.startsWith("."),nocase:!0,absolute:!1}),s=[],a=n.maxResults||50;for(const e of o.slice(0,a))if(!r.shouldIgnoreFile(e,{respectGitIgnore:n.respectGitIgnore,respectEmbedderIgnore:n.respectEmbedderIgnore})){try{const n=se.resolve(t,e),r=await _e.stat(n);s.push({path:n,relativePath:se.normalize(e),isDirectory:r.isDirectory(),lastModified:r.mtime,size:r.size})}catch{continue}if(s.length>=a)break}return s}catch{return[]}}}class tz{strategies=[new YU,new XU,new ez];contextService=new VU;async searchFiles(e,t,n={}){if(!e.trim())return this.getInitialSuggestions(t,n);const r=await KU(t),i=new ZU(r.projectRoot||t),o=this.strategies.find(t=>t.canHandle(e,r))||this.strategies[1];let s=[];if(o)s=await o.search(e,t,n,i);else if(this.strategies.length>0){const r=this.strategies[0];r&&(s=await r.search(e,t,n,i))}return this.sortResults(s,e)}async getInitialSuggestions(e,t){const n=t.maxResults||20;try{return(await this.contextService.getContextualSuggestions(e,n)).map(e=>({path:e.path,relativePath:e.relativePath,isDirectory:e.isDirectory,lastModified:e.lastModified,size:e.size}))}catch(qK){return ex.warn("Error getting contextual suggestions, falling back to simple listing:",qK),this.getFallbackInitialSuggestions(e,t)}}async getFallbackInitialSuggestions(e,t){const n=new ZU(e),r=t.maxResults||20;try{const i=await _e.readdir(e,{withFileTypes:!0}),o=[];for(const s of i){if(o.length>=r)break;if(s.name.startsWith("."))continue;const i=se.join(e,s.name);if(!n.shouldIgnoreFile(s.name,{respectGitIgnore:t.respectGitIgnore,respectEmbedderIgnore:t.respectEmbedderIgnore}))try{const e=await _e.stat(i);o.push({path:i,relativePath:se.normalize(s.name),isDirectory:s.isDirectory(),lastModified:e.mtime,size:e.size})}catch{continue}}return o.sort((e,t)=>e.isDirectory!==t.isDirectory?e.isDirectory?-1:1:e.relativePath.localeCompare(t.relativePath))}catch{return[]}}sortResults(e,t){const n=t.toLowerCase();return e.sort((e,t)=>{const r=(e.relativePath.match(/[/\\]/g)||[]).length,i=(t.relativePath.match(/[/\\]/g)||[]).length;if(r!==i)return r-i;if(e.isDirectory!==t.isDirectory)return e.isDirectory?-1:1;const o=se.basename(e.relativePath).toLowerCase(),s=se.basename(t.relativePath).toLowerCase(),a=o.includes(n);if(a!==s.includes(n))return a?-1:1;const l=se.basename(e.relativePath,se.extname(e.relativePath)),u=se.basename(t.relativePath,se.extname(t.relativePath)),c=l.localeCompare(u);return 0!==c?c:e.relativePath.localeCompare(t.relativePath)})}getContextService(){return this.contextService}}const nz=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/coverage/**","**/.nyc_output/**","**/tmp/**","**/temp/**","**/*.log","**/.DS_Store","**/Thumbs.db"],rz=kw((e,t)=>({files:[],isLoading:!1,lastScan:null,currentDirectory:null,advancedSearch:new tz,scanFiles:async n=>{const r=t();if(!(r.currentDirectory===n&&r.lastScan&&Date.now()-r.lastScan.getTime()<5e3)){e({isLoading:!0});try{const t="**/*",r=await qU(t,{cwd:n,ignore:nz,dot:!1,nodir:!1,absolute:!1}),i=[];for(const e of r)try{const t=se.join(n,e),r=await _e.stat(t);i.push({path:t,relativePath:e,isDirectory:r.isDirectory(),lastModified:r.mtime,size:r.size})}catch(qK){continue}i.sort((e,t)=>e.isDirectory!==t.isDirectory?e.isDirectory?-1:1:e.relativePath.localeCompare(t.relativePath)),e({files:i,isLoading:!1,lastScan:new Date,currentDirectory:n})}catch(qK){ex.error("Error scanning files:",qK),e({files:[],isLoading:!1,lastScan:new Date,currentDirectory:n})}}},searchFiles:async e=>{const{currentDirectory:n,advancedSearch:r}=t();if(!n)return[];try{return await r.searchFiles(e,n,{maxResults:50,maxDepth:10,respectGitIgnore:!0,respectEmbedderIgnore:!0,enableRecursiveSearch:!0})}catch(qK){return ex.error("Error in advanced file search:",qK),[]}},clearFiles:()=>{e({files:[],isLoading:!1,lastScan:null,currentDirectory:null})}}));const iz=kw((e,t)=>({queue:[],currentTool:null,status:"idle",enqueue:n=>{e(e=>({queue:[...e.queue,n]}));"idle"===t().status&&t().processNext()},dequeue:()=>{const n=t();if(0===n.queue.length)return null;const[r,...i]=n.queue;return r?(e({queue:i}),r):null},processNext:async()=>{if("idle"!==t().status)return;const n=t().dequeue();if(n){e({currentTool:n,status:"executing"});try{const e=await n.execute();n.resolve(e)}catch(qK){n.reject(qK instanceof Error?qK:new Error(String(qK)))}finally{e({status:"idle",currentTool:null}),setTimeout(()=>{t().processNext()},500)}}else e({status:"idle",currentTool:null})},clear:()=>{e({queue:[],currentTool:null,status:"idle"})},removeById:t=>{e(e=>({queue:e.queue.filter(e=>e.id!==t)}))},setStatus:t=>{e({status:t})},getCurrentTool:()=>t().currentTool,cancelAll:()=>{const n=t(),r=new Error("Tool execution cancelled due to CLI exit");n.queue.forEach(e=>{e.reject(r)}),n.currentTool&&n.currentTool.reject(r),e({queue:[],currentTool:null,status:"idle"})}}));let oz={};const sz=[{name:"clear",description:"Clear conversation history - Ctrl+R",aliases:["reset","new"],action:async()=>{if(oz.setMessages&&oz.clearActiveConversation&&oz.saveConversation){oz.setMessages(()=>[]),iz.getState().clear(),DM.getState().clearAll();try{await oz.clearActiveConversation()}catch(qK){ex.error("Failed to clear active conversation:",qK)}}}},{name:"resume",description:"Resume a conversation - Ctrl+O",action:()=>{oz.setIsResumeInterfaceOpen&&oz.setIsResumeInterfaceOpen(!0)}},{name:"model",description:"Select which AI model to use - Ctrl+B",action:async()=>{oz.setIsModelSelectorOpen&&oz.setIsModelSelectorOpen(!0)}},{name:"help",description:"Show available commands and shortcuts",aliases:["?","h"],action:async()=>{oz.setIsHelpOpen&&oz.setIsHelpOpen(!0)}},{name:"compress",description:"Compress conversation history to save context",aliases:["summarize"],action:async()=>{oz.compressConversation&&await oz.compressConversation()}},{name:"rewind",description:"View and revert to previous conversation states",action:async()=>{oz.setIsRewindInterfaceOpen&&oz.setIsRewindInterfaceOpen(!0)}},{name:"undo",description:"Undo the last query",action:async()=>{oz.performUndo&&await oz.performUndo()}},{name:"yolo",description:"Toggle auto-approval of all tool calls",action:async()=>{oz.toggleAutoApproval&&oz.toggleAutoApproval()}},{name:"project",description:"Switch to a different project or team",action:async()=>{oz.setProject&&oz.setPreviousProject&&oz.setTeam&&oz.setPreviousTeam&&oz.teams&&(oz.setPreviousProject(oz.project||null),oz.teams.length>1&&(oz.setPreviousTeam(oz.team||null),oz.setTeam(null)),oz.setProject(null))}},{name:"init",description:"Create EMBEDDER.md with project contexts",action:async()=>{if(oz.setMode&&oz.setMode("act"),oz.setAutoApproval&&oz.setAutoApproval(!0),oz.submitMessage){await oz.submitMessage("/init",{hidden:!1});const e="Please analyze this codebase and create an EMBEDDER.md file that contains all information specified in the format below.\n\nThe file you create will be given to agentic coding agents (such as yourself) that operate in this repository. Follow this format:\n**EMBEDDER PROJECT CONTEXT**\n<OVERVIEW>\nName = MyProject\nTarget MCU = <chip or family>\nBoard = <board>\nToolchain = <toolchain>\nDebug Interface = <st-link|jlink|serial>\nRTOS / SDK = <freertos|zephyr|sdk>\nProject Summary = <one-line description>\n</OVERVIEW>\n\n<COMMANDS>\n# --- Build / Compile --------------------------------------------------------\nbuild_command = <shell command to build>\n\n# --- Flash ------------------------------------------------------------------\nflash_command = <shell command to flash>\n\n# --- Debug ------------------------------------------------------------------\ngdb_server_command = <optional, e.g., openocd ... or ST-LINK_gdbserver ...>\ngdb_server_host = localhost\ngdb_server_port = 61234\ngdb_client_command = arm-none-eabi-gdb\ntarget_connection = remote\n\n# --- Serial Monitor ----------------------------------------------------------\n# Option 1: For custom commands (waf, make, etc.)\n# serial_monitor_command = source .venv/bin/activate && ./waf console --tty /dev/ttyACM0\n# serial_monitor_interactive = true\n# serial_startup_commands = [reset]\n\n# Option 2: Direct port/baudrate (use {port} and {baud} placeholders)\nserial_port = /dev/ttyACM0\nserial_baudrate = 115200\nserial_monitor_command = tio {port} -b {baud}\nserial_monitor_interactive = false\nserial_encoding = ascii\nserial_startup_commands = []\n\n# Project Overview \nWrite a clear and concise summary of the project's purpose, main technologies, and architecture.\n\n# Bash Commands \nDocument all commands related to build and interactive with hardware, keep it short and concise.\n\n# Code style\ndocument all required formating and documentation conventions, keep it short and concise\n\n\nIf there are Cursor rules (in .cursor/rules/ or .cursorrules) or Copilot rules\n(in .github/copilot-instructions.md), make sure to include them.\n\nKeep all descriptions short and concise, never create any code or complete the project only create or edit embedder.md file.\n\nAfter you have finished making embedder.md Provide a recommendation of documents necessary to support this project i.e. if\nthe project is based on a development board, suggest including the datasheet and\napplication references. For the MCU used in the project, suggest including the\nrelevant datasheet and erratas. For the peripherals found in the drivers,\nsuggest including datasheets and application notes. When possible, provide links\nto these documents. \n\nIf there's already an EMBEDDER.md, improve it if it's located in /\n";await oz.submitMessage(e,{hidden:!0})}}},{name:"doc",description:"Upload hardware docs and datasheets to improve AI accuracy",aliases:["docs","documentation"],action:async()=>{const e=await Promise.resolve().then(()=>Cw);await e.default("https://app.embedder.dev")}},{name:"logout",description:"Sign out and return to login screen",aliases:["signout"],action:async()=>{if(oz.firebaseAuth&&oz.closeSession)try{await oz.closeSession(oz.messages,oz.project,oz.team,oz.model),await pT(null),await oz.firebaseAuth.signOut()}catch(qK){ex.error("Logout failed:",qK instanceof Error?qK.message:String(qK));try{await pT(null),await oz.firebaseAuth.signOut()}catch(e){ex.error("Failed to clear auth state:",e instanceof Error?e.message:String(e))}finally{oz.setFirebaseUser&&oz.setFirebaseUser(null),oz.setProjects&&oz.setProjects([]),oz.setTeams&&oz.setTeams([]),oz.setBackendUser&&oz.setBackendUser(null)}}}},{name:"exit",description:"Close the application",aliases:["quit"],action:async()=>{oz.exitApp&&oz.exitApp()}}];function az(e){return sz.find(t=>t.name===e||t.aliases?.includes(e))}function lz(e){return Array.from(e)}function uz(e){return lz(e).length}function cz(e,t,n){return lz(e).slice(t,n).join("")}function dz(e){return void 0!==e&&!/[\s,.;!?]/.test(e)}function pz(e){return HM(e)}function fz(e,t,n){return e<t?t:e>n?n:e}function hz(e,t){let n=0,r=0,i=0;if(0===t)return[0,0];const o=e.split("\n");for(let s=0;s<o.length;s++){const e=o[s];if(!e)continue;const a=uz(e),l=a+(s<o.length-1?1:0);if(t<=i+a)return n=s,r=t-i,[n,r];if(t<=i+l)return n=s,r=a,t===i+l&&s<o.length-1?[s+1,0]:[n,r];i+=l}if(o.length>0){n=o.length-1;const e=o[n];r=e?uz(e):0}else n=0,r=0;return[n,r]}function gz(e,t,n){const r=[],i=[],o=[];let s=[0,0];return e.forEach((e,a)=>{if(i[a]=[],0===e.length)i[a].push([r.length,0]),o.push([a,0]),r.push(""),a===t[0]&&0===t[1]&&(s=[r.length-1,0]);else{let l=0;const u=lz(e);for(;l<u.length;){let e="",c=0,d=0,p=-1,f=0;for(let t=l;t<u.length;t++){const r=u[t];if(!r)continue;const i=pz(r);if(c+i>n){-1!==p&&f>0&&l+f<t?(e=u.slice(l,l+f).join(""),d=f):0===d&&i>n&&(e=r??"",d=1);break}e+=r,c+=i,d++," "===r&&(p=t,f=d-1)}if(0===d&&l<u.length){e=u[l]??"",d=1}if(i[a].push([r.length,l]),o.push([a,l]),r.push(e),a===t[0]){const e=t[1];e>=l&&e<l+d?s=[r.length-1,e-l]:e===l+d&&d>0&&(s=[r.length-1,d])}l+=d,l<u.length&&" "===u[l]&&l++}if(a===t[0]&&t[1]===u.length){const e=r.length-1;if(e>=0){const t=r[e];t&&(s=[e,uz(t)])}}}}),0===r.length&&(r.push(""),i[0]||(i[0]=[]),i[0].push([0,0]),o.push([0,0]),s=[0,0]),{visualLines:r,visualCursor:s,logicalToVisualMap:i,visualToLogicalMap:o}}function Az(e,t,n){return{lines:[...e],cursorRow:t,cursorCol:n,timestamp:Date.now()}}function mz(e,t){const n=[...e.undoStack,t];return n.length>100&&n.shift(),{undoStack:n,redoStack:[]}}function yz(e,t){return{...e,redoStack:[...e.redoStack,t]}}class bz{cache=new Map;maxSize=10;constructor(e=10){this.maxSize=e}getKey(e,t){return`${e}-${t}`}get(e,t){const n=this.getKey(t.startLine,t.endLine);return this.cache.get(n)||null}set(e,t){const n=this.getKey(e.startLine,e.endLine);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(n,t)}clear(){this.cache.clear()}}function vz(e,t){const n=e=>{const t=Az(e.lines,e.cursorRow,e.cursorCol);return{...e,undoRedoState:mz(e.undoRedoState,t)}},r=t=>e.lines[t]??"",i=e=>uz(r(e));switch(t.type){case"SET_TEXT":{let r=e;!1!==t.pushToUndo&&(r=n(e));const i=t.payload.replace(/\r\n?/g,"\n").split("\n"),o=0===i.length?[""]:i,s=o.length-1;return{...r,lines:o,cursorRow:s,cursorCol:uz(o[s]??""),preferredCol:null}}case"INSERT":{const i=n(e),o=[...i.lines];let s=i.cursorRow,a=i.cursorCol;const l=function(e){return lz(e).filter(e=>{const t=e.codePointAt(0);return void 0!==t&&!(127===t||t<=31&&13!==t&&10!==t)}).join("")}(t.payload.replace(/\r\n/g,"\n").replace(/\r/g,"\n")).split("\n"),u=r(s),c=cz(u,0,a),d=cz(u,a);if(l.length>1){o[s]=c+l[0];const e=l.slice(1),t=e.pop()??"";o.splice(s+1,0,...e),o.splice(s+l.length-1,0,t+d),s=s+l.length-1,a=uz(t)}else o[s]=c+l[0]+d,l[0]&&(a=uz(c)+uz(l[0]));return{...i,lines:o,cursorRow:s,cursorCol:a,preferredCol:null}}case"NEWLINE":{const t=n(e),i=[...t.lines],o=r(t.cursorRow),s=cz(o,0,t.cursorCol),a=cz(o,t.cursorCol);return i[t.cursorRow]=s,i.splice(t.cursorRow+1,0,a),{...t,lines:i,cursorRow:t.cursorRow+1,cursorCol:0,preferredCol:null}}case"BACKSPACE":{const t=n(e),i=[...t.lines];let o=t.cursorRow,s=t.cursorCol;if(0===s&&0===o)return e;if(s>0){const e=r(o);i[o]=cz(e,0,s-1)+cz(e,s),s--}else if(o>0){const e=r(o-1),t=r(o),n=uz(e);i[o-1]=e+t,i.splice(o,1),o--,s=n}return{...t,lines:i,cursorRow:o,cursorCol:s,preferredCol:null}}case"DELETE":{const{cursorRow:t,cursorCol:o,lines:s}=e,a=r(t);if(o<i(t)){const r=n(e),i=[...r.lines];return i[t]=cz(a,0,o)+cz(a,o+1),{...r,lines:i,preferredCol:null}}if(t<s.length-1){const i=n(e),o=r(t+1),s=[...i.lines];return s[t]=a+o,s.splice(t+1,1),{...i,lines:s,preferredCol:null}}return e}case"MOVE":{const{dir:n}=t.payload,{lines:r,cursorRow:i,cursorCol:o,viewportWidth:s}=e,a=gz(r,[i,o],s),{visualLines:l,visualCursor:u,visualToLogicalMap:c}=a;let d=u[0],p=u[1],f=e.preferredCol;const h=uz(l[d]??"");switch(n){case"left":f=null,p>0?p--:d>0&&(d--,p=uz(l[d]??""));break;case"right":f=null,p<h?p++:d<l.length-1&&(d++,p=0);break;case"up":d>0&&(null===f&&(f=p),d--,p=fz(f,0,uz(l[d]??"")));break;case"down":d<l.length-1&&(null===f&&(f=p),d++,p=fz(f,0,uz(l[d]??"")));break;case"home":f=null,p=0;break;case"end":f=null,p=h;break;case"wordLeft":{const{cursorRow:t,cursorCol:n,lines:r}=e;if(0===n&&0===t)return e;let i=t,o=n;if(0===n)i--,o=uz(r[i]??"");else{const i=r[t];if(!i)return e;const s=lz(i);let a=n;for(;a>0&&!dz(s[a-1]);)a--;for(;a>0&&dz(s[a-1]);)a--;o=a}return{...e,cursorRow:i,cursorCol:o,preferredCol:null}}case"wordRight":{const{cursorRow:t,cursorCol:n,lines:r}=e;if(t===r.length-1&&n===uz(r[t]??""))return e;let i=t,o=n;const s=lz(r[t]??"");if(n>=s.length)i++,o=0;else{let e=n;for(;e<s.length&&!dz(s[e]);)e++;for(;e<s.length&&dz(s[e]);)e++;o=e}return{...e,cursorRow:i,cursorCol:o,preferredCol:null}}}if(c[d]){const[t,n]=c[d];return{...e,cursorRow:t,cursorCol:fz(n+p,0,uz(e.lines[t]??"")),preferredCol:f}}return e}case"DELETE_WORD_LEFT":{const{cursorRow:t,cursorCol:i}=e;if(0===i&&0===t)return e;const o=n(e);if(0===i){const e=r(t-1),n=r(t),i=uz(e),s=[...o.lines];return s[t-1]=e+n,s.splice(t,1),{...o,lines:s,cursorRow:t-1,cursorCol:i,preferredCol:null}}const s=r(t),a=lz(s);let l=i;for(;l>0&&!dz(a[l-1]);)l--;for(;l>0&&dz(a[l-1]);)l--;const u=[...o.lines];return u[t]=cz(s,0,l)+cz(s,i),{...o,lines:u,cursorCol:l,preferredCol:null}}case"DELETE_WORD_RIGHT":{const{cursorRow:t,cursorCol:i,lines:o}=e,s=r(t),a=lz(s);if(i>=a.length&&t===o.length-1)return e;const l=n(e);if(i>=a.length){const e=r(t+1),n=[...l.lines];return n[t]=s+e,n.splice(t+1,1),{...l,lines:n,preferredCol:null}}let u=i;for(;u<a.length&&!dz(a[u]);)u++;for(;u<a.length&&dz(a[u]);)u++;const c=[...l.lines];return c[t]=cz(s,0,i)+cz(s,u),{...l,lines:c,preferredCol:null}}case"KILL_LINE_RIGHT":{const{cursorRow:t,cursorCol:o,lines:s}=e,a=r(t);if(o<i(t)){const r=n(e),i=[...r.lines];return i[t]=cz(a,0,o),{...r,lines:i}}if(t<s.length-1){const i=n(e),o=r(t+1),s=[...i.lines];return s[t]=a+o,s.splice(t+1,1),{...i,lines:s,preferredCol:null}}return e}case"KILL_LINE_LEFT":{const{cursorRow:t,cursorCol:i}=e;if(i>0){const o=n(e),s=r(t),a=[...o.lines];return a[t]=cz(s,i),{...o,lines:a,cursorCol:0,preferredCol:null}}return e}case"UNDO":{const{snapshot:t,newState:n}=function(e){return 0===e.undoStack.length?{snapshot:null,newState:e}:{snapshot:e.undoStack[e.undoStack.length-1]??null,newState:{undoStack:e.undoStack.slice(0,-1),redoStack:e.redoStack}}}(e.undoRedoState);if(!t)return e;const r=Az(e.lines,e.cursorRow,e.cursorCol);return{...e,...t,undoRedoState:yz(n,r),preferredCol:null}}case"REDO":{const{snapshot:t,newState:n}=function(e){if(0===e.redoStack.length)return{snapshot:null,newState:e};const t=e.redoStack[e.redoStack.length-1],n=e.redoStack.slice(0,-1);return{snapshot:t??null,newState:{undoStack:e.undoStack,redoStack:n}}}(e.undoRedoState);if(!t)return e;const r=Az(e.lines,e.cursorRow,e.cursorCol);return{...e,...t,undoRedoState:{...n,undoStack:[...n.undoStack,r]},preferredCol:null}}case"SET_VIEWPORT_WIDTH":return t.payload===e.viewportWidth?e:{...e,viewportWidth:t.payload};case"SET_VISUAL_SCROLL":return{...e,visualScrollRow:t.payload};case"MOVE_TO_OFFSET":{const[n,r]=hz(e.lines.join("\n"),t.payload);return{...e,cursorRow:n,cursorCol:r,preferredCol:null}}default:return e}}const Ez=Je.memo(qe.forwardRef(function({initialText:e="",initialCursorOffset:t=0,viewport:n,placeholder:r="",focus:i=!0,onChange:o,onSubmit:s,onVisualLinesChange:a,disabled:l=!1,disableArrowKeys:u=!1},c){const{columns:d}=oL(),p=qe.useRef(new bz),f=qe.useMemo(()=>{const r=e.split("\n"),[i,o]=hz(e,t);return{lines:0===r.length?[""]:r,cursorRow:i,cursorCol:o,preferredCol:null,undoRedoState:{undoStack:[],redoStack:[]},viewportWidth:n.width,visualScrollRow:0}},[e,t,n.width]),[h,g]=qe.useReducer(vz,f),{lines:A,cursorRow:m,cursorCol:y,visualScrollRow:b}=h,v=qe.useMemo(()=>A.join("\n"),[A]),E=qe.useMemo(()=>{let e=0;for(let t=0;t<m&&t<A.length;t++)e+=uz(A[t]||"")+1;return e+=y,e},[A,m,y]);qe.useImperativeHandle(c,()=>({getValue:()=>v,setValue:e=>{g({type:"SET_TEXT",payload:e,pushToUndo:!1})},clear:()=>{g({type:"SET_TEXT",payload:"",pushToUndo:!1})},getCursorOffset:()=>E}),[v,E]);const I=qe.useMemo(()=>gz(A,[m,y],h.viewportWidth),[A,m,y,h.viewportWidth]),{visualLines:w,visualCursor:C}=I,_=qe.useMemo(()=>function(e,t=1e3){return e>t}(w.length),[w.length]),B=qe.useMemo(()=>{if(!_)return null;const e=p.current.get(w,{startLine:b,endLine:b+n.height,totalLines:w.length,viewportHeight:n.height,overscan:3});if(e)return e;const t=function(e,t,n,r=3){const i=Math.max(0,t-r),o=Math.min(e.length,t+n+r);return{visibleLines:e.slice(i,o),startRow:i,endRow:o,hasAbove:i>0,hasBelow:o<e.length,linesAbove:i,linesBelow:Math.max(0,e.length-o)}}(w,b,n.height,3);return p.current.set({startLine:t.startRow,endLine:t.endRow,totalLines:w.length,viewportHeight:n.height,overscan:3},{visibleLines:t.visibleLines,startIndex:t.startRow,endIndex:t.endRow,totalLines:w.length,hasLinesBefore:t.hasAbove,hasLinesAfter:t.hasBelow,linesBefore:t.linesAbove,linesAfter:t.linesBelow}),t},[w,b,n.height,_]),D=qe.useMemo(()=>{if(_&&B)return B.visibleLines;const e=Math.min(w.length,20);return function(e,t,n){return e.slice(t,t+n)}(w,0,e)},[w,b,n.height,_,B]);qe.useEffect(()=>{0!==b&&g({type:"SET_VISUAL_SCROLL",payload:0})},[b]),qe.useEffect(()=>{g({type:"SET_VIEWPORT_WIDTH",payload:n.width})},[n.width]),qe.useEffect(()=>{o&&o(v,E)},[v,E,o]),qe.useEffect(()=>{a&&a(w.length)},[w.length,a]),Gi((e,t)=>{if(!i||l)return;if(t.return&&!t.ctrl&&!t.shift&&!t.meta)return void(s&&s(v));if(t.return&&(t.ctrl||t.shift||t.meta))return void g({type:"NEWLINE"});if(t.leftArrow&&!t.meta&&!t.ctrl)return void g({type:"MOVE",payload:{dir:"left"}});if(t.rightArrow&&!t.meta&&!t.ctrl)return void g({type:"MOVE",payload:{dir:"right"}});if(t.upArrow&&!u)return void g({type:"MOVE",payload:{dir:"up"}});if(t.downArrow&&!u)return void g({type:"MOVE",payload:{dir:"down"}});if((t.ctrl||t.meta)&&t.leftArrow)return void g({type:"MOVE",payload:{dir:"wordLeft"}});if((t.ctrl||t.meta)&&t.rightArrow)return void g({type:"MOVE",payload:{dir:"wordRight"}});if(t.ctrl&&"a"===e)return void g({type:"MOVE",payload:{dir:"home"}});if(t.ctrl&&"e"===e)return void g({type:"MOVE",payload:{dir:"end"}});if(t.backspace||""===e||"\b"===e||t.ctrl&&"h"===e||t.delete&&(!e||""===e))return void g({type:"BACKSPACE"});if(t.delete&&e&&""!==e)return void g({type:"DELETE"});if(t.ctrl&&"w"===e)return void g({type:"DELETE_WORD_LEFT"});if((t.meta||t.ctrl)&&t.delete)return void g({type:"DELETE_WORD_RIGHT"});if(t.ctrl&&"k"===e)return void g({type:"KILL_LINE_RIGHT"});if(t.ctrl&&"u"===e)return void g({type:"KILL_LINE_LEFT"});if(t.ctrl&&"z"===e)return void g({type:"UNDO"});if(t.ctrl&&"y"===e)return void g({type:"REDO"});const n=e&&(/^\x1b\[<\d+;\d+;\d+[Mm]/.test(e)||/^\[<\d+;\d+;\d+[Mm]/.test(e));!e||t.ctrl||t.meta||n||g({type:"INSERT",payload:e})},{isActive:i&&!l});const S=qe.useMemo(()=>{const[e]=C;return e-(_&&B?B.startRow:b)},[C,b,_,B]),k=qe.useMemo(()=>v||!r||i?!v&&r&&i&&!l?[We.jsxs(xi,{children:[xr.inverse(r[0]||" "),We.jsx(xi,{color:"gray",children:r.slice(1)})]},"placeholder")]:!v&&r&&i&&l?[We.jsx(xi,{color:"gray",dimColor:!0,children:r},"placeholder")]:D.map((e,t)=>{let r=cz(e,0,n.width);if(i&&!l&&t===S){const[,e]=C;if(e>=0&&e<uz(r)){const t=cz(r,e,e+1)||" ",n=xr.inverse(t);r=cz(r,0,e)+n+cz(r,e+1)}else e===uz(r)&&(r+=xr.inverse(" "))}return We.jsx(xi,{dimColor:l,children:r},`line-${t}`)}):[We.jsx(xi,{color:"gray",dimColor:l,children:r},"placeholder")],[D,C,b,i,l,r,v,n.width,S]);return _&&B?We.jsxs(ki,{flexDirection:"column",children:[B.hasAbove&&We.jsxs(xi,{color:"gray",children:["↑ ",B.linesAbove," more lines above"]}),k,B.hasBelow&&We.jsxs(xi,{color:"gray",children:["↓ ",B.linesBelow," more lines below"]})]}):We.jsx(ki,{flexDirection:"column",children:k})})),Iz=Je.memo(qe.forwardRef(function({placeholder:e="",disabled:t=!1,focus:n=!0,onSubmit:r,enableFileMentions:i=!1,onFileSearchStateChange:o,enableSlashCommands:s=!1,onCommandSearchStateChange:a,maxLength:l,onPendingImagesChange:u},c){const{actions:f}=CL(),{columns:h}=oL(),g=qe.useRef(null),[A,m]=qe.useState(1),[y,b]=qe.useState([]),v=qe.useMemo(()=>({width:Math.max(40,h-6),height:Math.min(20,Math.max(1,A))}),[h,A]),E=qe.useRef(null),I=qe.useRef(!1),C=qe.useRef(new Set);qe.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]),qe.useImperativeHandle(c,()=>({setValue:e=>{g.current?.setValue(e)},clear:()=>{g.current?.clear()},getValue:()=>g.current?.getValue()||"",getPendingImages:()=>y,clearPendingImages:()=>{b([]),u?.([]),C.current.clear()}}),[y,u]);const _=qe.useCallback(e=>{e!==A&&m(e)},[A]),[B,D]=qe.useState(!1),[S,k]=qe.useState(0),[x,Q]=qe.useState([]),[N,T]=qe.useState(!1),[R,F]=qe.useState(!1),[M,O]=qe.useState(0),[$,L]=qe.useState([]),{searchFiles:P}=function(){const{context:e}=EF(),{files:t,isLoading:n,lastScan:r,searchFiles:i,scanFiles:o,clearFiles:s}=rz(),a=e?.workingDirectory||process.cwd();return qe.useEffect(()=>{a?o(a).catch(ex.error):s()},[a,o,s]),{files:t,isLoading:n,lastScan:r,searchFiles:i,refreshFiles:async()=>{a&&await o(a)}}}(),j=qe.useRef(""),U=qe.useRef(0),[z,G]=qe.useState({active:!1,query:"",start:0}),[H,W]=qe.useState({active:!1,query:"",start:0}),q=qe.useCallback(async(e,t)=>{const n=Array.from(e.matchAll(/(?:['"])?([\/~](?:\\.|[^\s'"])+?\.(?:png|jpg|jpeg|gif|webp|bmp|tiff|svg)|[a-zA-Z]:[\/\\](?:\\.|[^\s'"])+?\.(?:png|jpg|jpeg|gif|webp|bmp|tiff|svg)|\\\\(?:\\.|[^\s'"])+?\.(?:png|jpg|jpeg|gif|webp|bmp|tiff|svg))(?:['"])?/gi));if(0===n.length)return{cleanedText:e,foundImages:[]};const r=[];let i=e;for(const o of n){const e=o[1];if(!e)continue;const n=e.replace(/\\\s/g," ");if(t.has(n))i=i.replace(o[0],"");else if(d(n))try{const e=p(n),s=w(n).toLowerCase(),a={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".tiff":"image/tiff",".svg":"image/svg+xml"}[s]||"image/png",l=e.toString("base64");r.push({base64:l,mimeType:a}),t.add(n),i=i.replace(o[0],"")}catch(qK){ex.error(`Failed to load image from path: ${n}`,qK)}}return i=i.replace(/\s+/g," ").trim(),{cleanedText:i,foundImages:r}},[]),J=qe.useCallback((e,t)=>{if(j.current=e,U.current=t,I.current||q(e,C.current).then(({cleanedText:e,foundImages:t})=>{t.length>0&&b(n=>{const r=10-n.length,i=t.slice(0,r);if(i.length>0){const o=[...n,...i];return u?.(o),I.current=!0,g.current?.setValue(e),setTimeout(()=>{I.current=!1},0),ex.info(`Loaded ${i.length} image(s) from pasted paths (total: ${o.length})`),t.length>r&&ex.warn("Maximum image limit reached (10 images)"),o}return n})}),i){const n=function(e,t){if(0===t)return{active:!1,query:"",start:0};let n=-1,r=!1;for(let o=t-1;o>=0;o--){const t=e[o];if(void 0===t)break;const i=o>0?e[o-1]:void 0;if("@"!==t||r){if(/\s/.test(t)){if(r=!0,-1===n)break}else if(/[\(\)\[\]\{\},\.\!\?;:]/.test(t)&&-1===n)break}else if(0===o||void 0!==i&&/[\s\(\)\[\]\{\},\.\!\?;:]/.test(i)){n=o;break}}if(-1===n)return{active:!1,query:"",start:0};let i=e.slice(n+1,t);i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'")?i=i.slice(1,-1):(i.startsWith('"')||i.startsWith("'"))&&(i=i.slice(1));return{active:!0,query:i,start:n}}(e,t);G(n)}if(s){const n=function(e,t){if(0===t)return{active:!1,query:"",start:0};let n=-1,r=!1;for(let o=t-1;o>=0;o--){const t=e[o];if(void 0===t)break;const i=o>0?e[o-1]:void 0;if("/"!==t||r){if(/\s/.test(t)&&(r=!0,-1===n))break}else if(0===o||void 0!==i&&/\s/.test(i)){n=o;break}}if(-1===n)return{active:!1,query:"",start:0};const i=e.slice(n+1,t);if(i.includes(" "))return{active:!1,query:"",start:0};return{active:!0,query:i,start:n}}(e,t);W(n)}E.current&&clearTimeout(E.current),f.setIsTyping(!0),E.current=setTimeout(()=>{f.setIsTyping(!1)},800)},[f,i,s,q,y,u]);qe.useEffect(()=>{if(!z.active)return Q([]),void T(!1);(async()=>{T(!0);try{const e=await P(z.query);Q(e.slice(0,50))}catch(qK){ex.error("Error searching files:",qK),Q([])}finally{T(!1)}})(),D(!0),k(0)},[z.active,z.query,P]),qe.useEffect(()=>{if(!H.active)return void L([]);const e=function(e){const t=e.toLowerCase();return sz.filter(e=>e.name.startsWith(t)||e.aliases?.some(e=>e.startsWith(t)))}(H.query).map(e=>({label:`/${e.name}`,value:e.name,description:e.description,exactPattern:`/${e.name}`}));L(e),F(e.length>0),O(0)},[H.active,H.query]),qe.useEffect(()=>{D(z.active&&x.length>0)},[z.active,x.length]),qe.useEffect(()=>{F(H.active&&$.length>0)},[H.active,$.length]);const K=qe.useCallback(e=>{const t=j.current.slice(0,z.start)+`@${e.relativePath.includes(" ")?`"${e.relativePath}"`:e.relativePath} `;g.current?.setValue(t),D(!1)},[z.start]),Z=qe.useCallback(()=>{D(!1)},[]),V=qe.useCallback(e=>{F(!1),L([]);const t=az(e.value);t&&(g.current?.clear(),setTimeout(()=>t.action(),0))},[]),Y=qe.useCallback(()=>{F(!1)},[]);qe.useEffect(()=>{if(o&&i)if(B&&x.length>0){const e={isOpen:!0,query:z.query,selectedIndex:S,suggestions:x,atMention:z,onSelect:K,onCancel:Z,isLoading:N};o(e)}else o(null)},[B,x,z,S,K,Z,o,i,N]),qe.useEffect(()=>{if(a&&s)if(R&&$.length>0){const e={isOpen:!0,query:H.query,selectedIndex:M,suggestions:$,slashMention:H,onSelect:V,onCancel:Y};a(e)}else a(null)},[R,$,H,M,V,Y,a,s]);const X=function({onSubmit:e,isActive:t,currentQuery:n,onChange:r}){const{actions:i}=CL(),[o,s]=qe.useState(-1),[a,l]=qe.useState(""),u=qe.useCallback(()=>{s(-1),l("")},[]);return{handleSubmit:qe.useCallback(t=>{const n=t.trim();n&&e(n),u()},[e,u]),navigateUp:qe.useCallback(()=>{if(!t)return!1;const e=i.getHistoryLength();if(0===e)return!1;let a=o;if(-1===o)l(n),a=0;else{if(!(o<e-1))return!1;a=o+1}if(a!==o){s(a);const e=i.getHistoryItem(a);return void 0!==e&&(r(e),!0)}return!1},[o,s,r,i,t,n,l]),navigateDown:qe.useCallback(()=>{if(!t)return!1;if(-1===o)return!1;const e=o-1;if(s(e),-1===e)r(a);else{const t=i.getHistoryItem(e);if(void 0===t)return!1;r(t)}return!0},[o,s,a,r,i,t])}}({onSubmit:r||(()=>{}),isActive:n&&!t&&!B&&!R,currentQuery:j.current,onChange:e=>{g.current?.setValue(e)}}),ee=qe.useCallback(e=>{B||R||!r||r(e)},[B,R,r]);return Gi((e,r)=>{if(!t&&n){if(R&&$.length>0){const e=$.length-1,t={upArrow:()=>O(t=>0===t?e:t-1),downArrow:()=>O(t=>t===e?0:t+1),return:()=>{if(M<$.length){const e=$[M];e&&V(e)}},tab:()=>{const e=$[0];e&&V(e)},escape:()=>F(!1)};for(const[n,i]of Object.entries(t))if(r[n])return void i()}if(B&&x.length>0)if(r.upArrow)k(e=>0===e?x.length-1:e-1);else if(r.downArrow)k(e=>e===x.length-1?0:e+1);else if(r.return&&S<x.length){const e=x[S];e&&K(e)}else if(r.tab){const e=x[0];e&&K(e)}else r.escape&&D(!1);if(!B&&!R){if(r.upArrow&&r.meta)return void X.navigateUp();if(r.downArrow&&r.meta)return void X.navigateDown()}!(l&&(g.current?.getValue()||"").length>=l)||r.backspace||r.delete||r.leftArrow||r.rightArrow||""===e||"\b"===e||r.ctrl}},{isActive:!t&&n}),We.jsx(Ez,{ref:g,viewport:v,placeholder:t?"One moment...":e,focus:n,onChange:J,onSubmit:ee,onVisualLinesChange:_,disabled:t,disableArrowKeys:R||B})}));function wz({pendingImages:e,onClear:t}){if(0===e.length)return null;const n=e.reduce((e,t)=>e+.75*t.base64.length/1048576,0);return We.jsx(ki,{marginLeft:2,children:We.jsxs(xi,{color:"blue",children:["🏞️ ",e.length," (",n.toFixed(1),"MB)"]})})}function Cz(){const{modeConfig:e,currentMode:t}=JF();return We.jsxs(ki,{justifyContent:"space-between",marginTop:0,paddingLeft:2,paddingRight:2,width:"100%",children:[We.jsxs(ki,{children:[We.jsx(xi,{bold:!0,color:"plan"===t?"blue":"green",children:e.name}),We.jsx(xi,{dimColor:!0,children:" MODE"}),We.jsx(xi,{dimColor:!0,children:" • Tab to switch"})]}),We.jsx(ki,{children:We.jsx(xi,{dimColor:!0,children:"Ctrl+D - Open Web Console"})}),We.jsx(ki,{children:We.jsx(xi,{dimColor:!0,children:"Press / for slash commands"})})]})}let _z=0;function Bz(e){return`${e}-${Date.now()}-${_z++}`}function Dz(e,t){const n=[];let r=[];for(const i of e){const e=t[i.toolName];e?.metadata?.requiresSequentialExecution||"shell"===i.toolName?(r.length>0&&(n.push(Sz(r)),r=[]),n.push(Sz([i]))):r.push(i)}return r.length>0&&n.push(Sz(r)),n}function Sz(e,t=Bz("group")){const n=e.map((e,n)=>{const r=e.output??e.result;let i,o,s=!0,a=!1;if(r&&"object"==typeof r&&"success"in r){s=!!r.success,i=r;const e=r.llmContent||r.returnDisplay||"";"string"==typeof e&&(a=e.includes("cancelled by the user")||e.includes("declined to approve"),a&&(i.summary="Operation cancelled"))}else"string"==typeof r?(s=!r.startsWith("Error:"),a=r.includes("cancelled by the user")||r.includes("declined to approve"),i={success:s,llmContent:r,returnDisplay:r,summary:a?"Operation cancelled":s?"Tool completed successfully":"Tool execution failed"}):r?(s=!0,i={success:!0,llmContent:JSON.stringify(r),returnDisplay:JSON.stringify(r,null,2),summary:"Tool completed successfully"}):(s=!1,i={success:!1,llmContent:"No output received",returnDisplay:"No output received",summary:"Tool execution failed"});return o=a?SM.Cancelled:s?SM.Success:SM.Error,{id:`${t}-tool-${n}`,toolCallId:e.toolCallId,name:e.toolName||"unknown",displayName:kz(e.toolName),description:xz(e),status:o,result:{success:!!i.success,llmContent:i.llmContent||("string"==typeof r?r:JSON.stringify(r)),returnDisplay:Qz(i.returnDisplay||i.llmContent||r),summary:i.summary||(s?"Tool completed successfully":"Tool execution failed"),...i.diffData?{diffData:i.diffData}:{},...i.metadata?{metadata:i.metadata}:{},...i.locations?{locations:i.locations}:{}},startTime:Date.now()-1e3,endTime:Date.now()}}),r={id:t,tools:n,status:n.some(e=>e.status===SM.Error)?"error":"completed",startTime:Date.now()-1e3,endTime:Date.now()};return{role:"tool-group",id:`msg-${t}`,toolGroup:r,timestamp:Date.now()}}function kz(e){return{readFile:"read-file",writeFile:"write-file",editFile:"edit-file",listDirectory:"list-directory",grep:"grep",shell:"shell",build:"build",todowrite:"todo-write",todoread:"todo-read"}[e]||e}function xz(e){const t=e.toolName,n=e.args,r=e.output||e.result,i=r?.metadata?.toolParams||n;switch(t){case"readFile":case"read_file":const e=i?.absolutePath||n?.absolutePath;return`Reading ${e?e.split(/[/\\]/).pop():"file"}`;case"readManyFiles":const o=i?.paths||n?.paths;return o&&Array.isArray(o)&&o.length>0?1===o.length?`Reading files: ${o[0]}`:`Reading ${o.length} files`:"Reading multiple files";case"writeFile":const s=i?.absolutePath||n?.absolutePath,a=r?.metadata?.filename;return`Writing to ${s?s.split(/[/\\]/).pop():a||"file"}`;case"editFile":const l=i?.absolutePath||n?.absolutePath,u=r?.metadata?.filename;return`Editing ${l?l.split(/[/\\]/).pop():u||"file"}`;case"listDirectory":const c=i?.path||i?.absolutePath||n?.path||n?.absolutePath;return`Listing directory ${c?c.split(/[/\\]/).pop():"contents"}`;case"grep":const d=i?.pattern||n?.pattern,p=i?.absolutePath||n?.absolutePath;return`Searching for "${d||"pattern"}"${p?" in "+p.split(/[/\\]/).pop():""}`;case"glob":return`Searching for files matching "${i?.pattern||n?.pattern||"pattern"}"`;case"shell":const f=r?.metadata?.command;return`Running: ${f||(i?.command||n?.command)||"shell command"}`;case"build":return"Building project";case"todowrite":return"Updating task list";case"todoread":return"Reading task list";case"documentSearch":return"Searching documents in the knowledge base";default:return`Executing ${t}`}}function Qz(e){if("string"==typeof e)return e.startsWith("Error:")?e:e.length>1e3?e.substring(0,1e3)+"\n... (truncated)":e;if(e?.returnDisplay)return e.returnDisplay;if(e&&"object"==typeof e){if(!1===e.success)return e.llmContent||"Tool execution failed";if(e.summary)return e.summary;const t=Object.keys(e);return t.length<3?JSON.stringify(e,null,2):`Tool completed with ${t.length} properties`}return JSON.stringify(e,null,2)}let Nz=null;function Tz(e){Nz=e}function Rz(e){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack};try{return JSON.parse(JSON.stringify(e))}catch{try{return String(e)}catch{return"[unserializable]"}}}function Fz(e,t){$.withScope(n=>{n.setTag("tool_name",t.toolName),n.setTag("tool_status",e),t.toolCallId&&n.setTag("tool_call_id",t.toolCallId),n.setContext("tool",{args:Rz(t.params),result:void 0!==t.result?Rz(t.result):void 0,message:t.message});const r="success"===e?"info":"error",i="success"===e?`Tool ${t.toolName} succeeded`:"validation_failure"===e?`Tool ${t.toolName} validation failed`:`Tool ${t.toolName} failed`;$.captureMessage(i,r)})}function Mz(e){const t={name:e.metadata.name,description:e.metadata.description,inputSchema:e.inputSchema,execute:async(t,n)=>{const r=ST.getState(),i=r.getCachedContext?.(),o=xw.getState(),{teamId:s,projectId:a}=o.getContext(),l=yT.getState(),u=l.getApiFetch(),c=l.getSessionId(),d=e.metadata.name,p=n?.toolCallId,f={workingDirectory:process.cwd(),projectRoot:process.cwd(),teamId:s??void 0,projectId:a??void 0,sessionId:c??void 0,apiFetch:u??void 0,signal:n?.abortSignal,environmentContext:i?{platform:i.platform.platform,projectType:i.projectInfo.projectType,isGitRepository:i.projectInfo.isGitRepository,dateTime:i.dateTime.formatted}:void 0,snapshotService:wM()??void 0},h=async()=>{try{if(e.validateParams){const n=e.validateParams(t);if(n){const e=`Validation Error: ${n}`;return Fz("validation_failure",{toolName:d,toolCallId:p,params:t,message:e}),e}}if(e.shouldConfirm&&e.metadata.requiresConfirmation){if(!(e.isAllowlisted?.(t)||!1)){const n=await e.shouldConfirm(t,f);if(n){const r=await async function(e){if(!Nz)throw new Error("No confirmation handler registered. UI must call setGlobalConfirmationHandler.");return await Nz(e)}({toolName:e.metadata.name,params:t,context:f,confirmationDetails:n});if(!r.approved)throw new Error(`Tool execution was cancelled by the user. The user declined to approve the ${e.metadata.name} operation.`);r.approved&&r.storePermission&&e.addToAllowlist&&e.addToAllowlist(t,r.storePermission)}}}if(e.getDescription,e.metadata.canStream&&n?.toolCallId){const t=n.toolCallId,r=e.metadata.name;f.updateOutput=e=>{DM.getState().updateStream(t,r,e)}}const r=await e.execute(t,f);let i;if(r)if("string"!=typeof r.llmContent)i={success:!1,llmContent:"Error: Tool execution returned invalid content format",returnDisplay:"Error: Tool execution returned invalid content format",summary:"Tool execution failed"};else if(r.llmContent){let e=r.llmContent;e.length>3e4&&(e=function(e,t=3e4){return e.length<=t?e:e.slice(0,t)+"\n\n(Output truncated due to length limit)"}(e)),i={success:r.success,llmContent:e,returnDisplay:r.returnDisplay||r.llmContent,summary:r.summary||"Tool completed successfully",metadata:r.metadata,locations:r.locations,diffData:r.diffData}}else i={success:!0,llmContent:r.summary||`Tool ${e.metadata.name} completed successfully`,returnDisplay:r.returnDisplay||r.summary||`Tool ${e.metadata.name} completed successfully`,summary:r.summary||"Tool completed successfully",metadata:r.metadata,locations:r.locations,diffData:r.diffData};else i={success:!1,llmContent:"Error: Tool execution returned no result",returnDisplay:"Error: Tool execution returned no result",summary:"Tool execution failed"};return Fz(i.success?"success":"failure",{toolName:d,toolCallId:p,params:t,result:i}),i}catch(qK){const n=qK instanceof Error?qK.message:String(qK);return $.withScope(r=>{r.setTag("tool_name",d),r.setTag("tool_status","exception"),p&&r.setTag("tool_call_id",p),r.setContext("tool",{args:Rz(t),errorMessage:n}),$.captureException(qK instanceof Error?qK:new Error(String(qK)))}),{success:!1,llmContent:`Error: ${n}`,returnDisplay:`Error: ${n}`,summary:"Tool execution failed"}}};return e.metadata.requiresSequentialExecution?new Promise((r,i)=>{const o={id:n?.toolCallId||`${e.metadata.name}-${Date.now()}`,toolName:e.metadata.name,displayName:e.metadata.displayName,params:t,context:f,options:n,execute:h,resolve:r,reject:i};iz.getState().enqueue(o)}):h()},toModelOutput:e=>({type:"text",value:e.llmContent||String(e)})};return Object.assign(t,{metadata:e.metadata,validateParams:e.validateParams,getDescription:e.getDescription,getLocations:e.getLocations,shouldConfirm:e.shouldConfirm,executeStructured:async(t,n)=>{const r={workingDirectory:process.cwd(),projectRoot:process.cwd(),...n};return e.execute(t,r)}})}var Oz,$z,Lz={},Pz={},jz={},Uz={},zz={};function Gz(){if(Oz)return zz;function e(e){return"string"==typeof e||e instanceof String}function t(e){return Array.isArray(e)}return Oz=1,Object.defineProperty(zz,"__esModule",{value:!0}),zz.stringArray=zz.array=zz.func=zz.error=zz.number=zz.string=zz.boolean=void 0,zz.boolean=function(e){return!0===e||!1===e},zz.string=e,zz.number=function(e){return"number"==typeof e||e instanceof Number},zz.error=function(e){return e instanceof Error},zz.func=function(e){return"function"==typeof e},zz.array=t,zz.stringArray=function(n){return t(n)&&n.every(t=>e(t))},zz}function Hz(){if($z)return Uz;$z=1,Object.defineProperty(Uz,"__esModule",{value:!0}),Uz.Message=Uz.NotificationType9=Uz.NotificationType8=Uz.NotificationType7=Uz.NotificationType6=Uz.NotificationType5=Uz.NotificationType4=Uz.NotificationType3=Uz.NotificationType2=Uz.NotificationType1=Uz.NotificationType0=Uz.NotificationType=Uz.RequestType9=Uz.RequestType8=Uz.RequestType7=Uz.RequestType6=Uz.RequestType5=Uz.RequestType4=Uz.RequestType3=Uz.RequestType2=Uz.RequestType1=Uz.RequestType=Uz.RequestType0=Uz.AbstractMessageSignature=Uz.ParameterStructures=Uz.ResponseError=Uz.ErrorCodes=void 0;const e=Gz();var t,n,r,i;(n=t||(Uz.ErrorCodes=t={})).ParseError=-32700,n.InvalidRequest=-32600,n.MethodNotFound=-32601,n.InvalidParams=-32602,n.InternalError=-32603,n.jsonrpcReservedErrorRangeStart=-32099,n.serverErrorStart=-32099,n.MessageWriteError=-32099,n.MessageReadError=-32098,n.PendingResponseRejected=-32097,n.ConnectionInactive=-32096,n.ServerNotInitialized=-32002,n.UnknownErrorCode=-32001,n.jsonrpcReservedErrorRangeEnd=-32e3,n.serverErrorEnd=-32e3;class o extends Error{constructor(n,r,i){super(r),this.code=e.number(n)?n:t.UnknownErrorCode,this.data=i,Object.setPrototypeOf(this,o.prototype)}toJson(){const e={code:this.code,message:this.message};return void 0!==this.data&&(e.data=this.data),e}}Uz.ResponseError=o;class s{constructor(e){this.kind=e}static is(e){return e===s.auto||e===s.byName||e===s.byPosition}toString(){return this.kind}}Uz.ParameterStructures=s,s.auto=new s("auto"),s.byPosition=new s("byPosition"),s.byName=new s("byName");class a{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return s.auto}}Uz.AbstractMessageSignature=a;Uz.RequestType0=class extends a{constructor(e){super(e,0)}};Uz.RequestType=class extends a{constructor(e,t=s.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};Uz.RequestType1=class extends a{constructor(e,t=s.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};Uz.RequestType2=class extends a{constructor(e){super(e,2)}};Uz.RequestType3=class extends a{constructor(e){super(e,3)}};Uz.RequestType4=class extends a{constructor(e){super(e,4)}};Uz.RequestType5=class extends a{constructor(e){super(e,5)}};Uz.RequestType6=class extends a{constructor(e){super(e,6)}};Uz.RequestType7=class extends a{constructor(e){super(e,7)}};Uz.RequestType8=class extends a{constructor(e){super(e,8)}};Uz.RequestType9=class extends a{constructor(e){super(e,9)}};Uz.NotificationType=class extends a{constructor(e,t=s.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};Uz.NotificationType0=class extends a{constructor(e){super(e,0)}};Uz.NotificationType1=class extends a{constructor(e,t=s.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}};Uz.NotificationType2=class extends a{constructor(e){super(e,2)}};Uz.NotificationType3=class extends a{constructor(e){super(e,3)}};Uz.NotificationType4=class extends a{constructor(e){super(e,4)}};Uz.NotificationType5=class extends a{constructor(e){super(e,5)}};Uz.NotificationType6=class extends a{constructor(e){super(e,6)}};Uz.NotificationType7=class extends a{constructor(e){super(e,7)}};Uz.NotificationType8=class extends a{constructor(e){super(e,8)}};return Uz.NotificationType9=class extends a{constructor(e){super(e,9)}},(i=r||(Uz.Message=r={})).isRequest=function(t){const n=t;return n&&e.string(n.method)&&(e.string(n.id)||e.number(n.id))},i.isNotification=function(t){const n=t;return n&&e.string(n.method)&&void 0===t.id},i.isResponse=function(t){const n=t;return n&&(void 0!==n.result||!!n.error)&&(e.string(n.id)||e.number(n.id)||null===n.id)},Uz}var Wz,qz={};function Jz(){if(Wz)return qz;var e,t,n;Wz=1,Object.defineProperty(qz,"__esModule",{value:!0}),qz.LRUCache=qz.LinkedMap=qz.Touch=void 0,(n=t||(qz.Touch=t={})).None=0,n.First=1,n.AsOld=n.First,n.Last=2,n.AsNew=n.Last;class r{constructor(){this[e]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,n=t.None){const r=this._map.get(e);if(r)return n!==t.None&&this.touch(r,n),r.value}set(e,n,r=t.None){let i=this._map.get(e);if(i)i.value=n,r!==t.None&&this.touch(i,r);else{switch(i={key:e,value:n,next:void 0,previous:void 0},r){case t.None:this.addItemLast(i);break;case t.First:this.addItemFirst(i);break;case t.Last:default:this.addItemLast(i)}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){const t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");const e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){const n=this._state;let r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==n)throw new Error("LinkedMap got modified during iteration.");r=r.next}}keys(){const e=this._state;let t=this._head;const n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){const e={value:t.key,done:!1};return t=t.next,e}return{value:void 0,done:!0}}};return n}values(){const e=this._state;let t=this._head;const n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){const e={value:t.value,done:!1};return t=t.next,e}return{value:void 0,done:!0}}};return n}entries(){const e=this._state;let t=this._head;const n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(t){const e={value:[t.key,t.value],done:!1};return t=t.next,e}return{value:void 0,done:!0}}};return n}[(e=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(0===e)return void this.clear();let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(this._head||this._tail){if(!this._head)throw new Error("Invalid list");e.next=this._head,this._head.previous=e}else this._tail=e;this._head=e,this._state++}addItemLast(e){if(this._head||this._tail){if(!this._tail)throw new Error("Invalid list");e.previous=this._tail,this._tail.next=e}else this._head=e;this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw new Error("Invalid list");e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw new Error("Invalid list");e.previous.next=void 0,this._tail=e.previous}else{const t=e.next,n=e.previous;if(!t||!n)throw new Error("Invalid list");t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,n){if(!this._head||!this._tail)throw new Error("Invalid list");if(n===t.First||n===t.Last)if(n===t.First){if(e===this._head)return;const t=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(n===t.Last){if(e===this._tail)return;const t=e.next,n=e.previous;e===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}toJSON(){const e=[];return this.forEach((t,n)=>{e.push([n,t])}),e}fromJSON(e){this.clear();for(const[t,n]of e)this.set(t,n)}}qz.LinkedMap=r;return qz.LRUCache=class extends r{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,n=t.AsNew){return super.get(e,n)}peek(e){return super.get(e,t.None)}set(e,n){return super.set(e,n,t.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}},qz}var Kz,Zz={};var Vz,Yz,Xz={},eG={};function tG(){if(Vz)return eG;let e;function t(){if(void 0===e)throw new Error("No runtime abstraction layer installed");return e}return Vz=1,Object.defineProperty(eG,"__esModule",{value:!0}),(t||(t={})).install=function(t){if(void 0===t)throw new Error("No runtime abstraction layer provided");e=t},eG.default=t,eG}function nG(){if(Yz)return Xz;Yz=1,Object.defineProperty(Xz,"__esModule",{value:!0}),Xz.Emitter=Xz.Event=void 0;const e=tG();var t;!function(e){const t={dispose(){}};e.None=function(){return t}}(t||(Xz.Event=t={}));class n{add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let r=0,i=this._callbacks.length;r<i;r++)if(this._callbacks[r]===e){if(this._contexts[r]===t)return this._callbacks.splice(r,1),void this._contexts.splice(r,1);n=!0}if(n)throw new Error("When adding a listener with a context, you should remove it with the same context")}invoke(...t){if(!this._callbacks)return[];const n=[],r=this._callbacks.slice(0),i=this._contexts.slice(0);for(let s=0,a=r.length;s<a;s++)try{n.push(r[s].apply(i[s],t))}catch(o){(0,e.default)().console.error(o)}return n}isEmpty(){return!this._callbacks||0===this._callbacks.length}dispose(){this._callbacks=void 0,this._contexts=void 0}}class r{constructor(e){this._options=e}get event(){return this._event||(this._event=(e,t,i)=>{this._callbacks||(this._callbacks=new n),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,t);const o={dispose:()=>{this._callbacks&&(this._callbacks.remove(e,t),o.dispose=r._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(i)&&i.push(o),o}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}}return Xz.Emitter=r,r._noop=function(){},Xz}var rG,iG={};function oG(){if(rG)return iG;rG=1,Object.defineProperty(iG,"__esModule",{value:!0}),iG.CancellationTokenSource=iG.CancellationToken=void 0;const e=tG(),t=Gz(),n=nG();var r,i;(i=r||(iG.CancellationToken=r={})).None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:n.Event.None}),i.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:n.Event.None}),i.is=function(e){const n=e;return n&&(n===i.None||n===i.Cancelled||t.boolean(n.isCancellationRequested)&&!!n.onCancellationRequested)};const o=Object.freeze(function(t,n){const r=(0,e.default)().timer.setTimeout(t.bind(n),0);return{dispose(){r.dispose()}}});class s{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?o:(this._emitter||(this._emitter=new n.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}}return iG.CancellationTokenSource=class{get token(){return this._token||(this._token=new s),this._token}cancel(){this._token?this._token.cancel():this._token=r.Cancelled}dispose(){this._token?this._token instanceof s&&this._token.dispose():this._token=r.None}},iG}var sG,aG={};var lG,uG,cG={},dG={};function pG(){if(lG)return dG;lG=1,Object.defineProperty(dG,"__esModule",{value:!0}),dG.Semaphore=void 0;const e=tG();return dG.Semaphore=class{constructor(e=1){if(e<=0)throw new Error("Capacity must be greater than 0");this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,n)=>{this._waiting.push({thunk:e,resolve:t,reject:n}),this.runNext()})}get active(){return this._active}runNext(){0!==this._waiting.length&&this._active!==this._capacity&&(0,e.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(0===this._waiting.length||this._active===this._capacity)return;const e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{const t=e.thunk();t instanceof Promise?t.then(t=>{this._active--,e.resolve(t),this.runNext()},t=>{this._active--,e.reject(t),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}},dG}var fG,hG={};var gG,AG={};var mG,yG,bG,vG,EG,IG,wG={};function CG(){return mG||(mG=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createMessageConnection=e.ConnectionOptions=e.MessageStrategy=e.CancellationStrategy=e.CancellationSenderStrategy=e.CancellationReceiverStrategy=e.RequestCancellationReceiverStrategy=e.IdCancellationReceiverStrategy=e.ConnectionStrategy=e.ConnectionError=e.ConnectionErrors=e.LogTraceNotification=e.SetTraceNotification=e.TraceFormat=e.TraceValues=e.Trace=e.NullLogger=e.ProgressType=e.ProgressToken=void 0;const t=tG(),n=Gz(),r=Hz(),i=Jz(),o=nG(),s=oG();var a,l,u,c,d,p,f,h,g,A,m,y,b,v,E,I,w,C,_,B,D,S,k,x,Q,N,T;(a||(a={})).type=new r.NotificationType("$/cancelRequest"),(l||(e.ProgressToken=l={})).is=function(e){return"string"==typeof e||"number"==typeof e},(u||(u={})).type=new r.NotificationType("$/progress");e.ProgressType=class{constructor(){}},(c||(c={})).is=function(e){return n.func(e)},e.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}}),(p=d||(e.Trace=d={}))[p.Off=0]="Off",p[p.Messages=1]="Messages",p[p.Compact=2]="Compact",p[p.Verbose=3]="Verbose",(h=f||(e.TraceValues=f={})).Off="off",h.Messages="messages",h.Compact="compact",h.Verbose="verbose",function(e){e.fromString=function(t){if(!n.string(t))return e.Off;switch(t=t.toLowerCase()){case"off":default:return e.Off;case"messages":return e.Messages;case"compact":return e.Compact;case"verbose":return e.Verbose}},e.toString=function(t){switch(t){case e.Off:return"off";case e.Messages:return"messages";case e.Compact:return"compact";case e.Verbose:return"verbose";default:return"off"}}}(d||(e.Trace=d={})),(A=g||(e.TraceFormat=g={})).Text="text",A.JSON="json",function(e){e.fromString=function(t){return n.string(t)&&"json"===(t=t.toLowerCase())?e.JSON:e.Text}}(g||(e.TraceFormat=g={})),(m||(e.SetTraceNotification=m={})).type=new r.NotificationType("$/setTrace"),(y||(e.LogTraceNotification=y={})).type=new r.NotificationType("$/logTrace"),(v=b||(e.ConnectionErrors=b={}))[v.Closed=1]="Closed",v[v.Disposed=2]="Disposed",v[v.AlreadyListening=3]="AlreadyListening";class R extends Error{constructor(e,t){super(t),this.code=e,Object.setPrototypeOf(this,R.prototype)}}e.ConnectionError=R,(E||(e.ConnectionStrategy=E={})).is=function(e){const t=e;return t&&n.func(t.cancelUndispatched)},(I||(e.IdCancellationReceiverStrategy=I={})).is=function(e){const t=e;return t&&(void 0===t.kind||"id"===t.kind)&&n.func(t.createCancellationTokenSource)&&(void 0===t.dispose||n.func(t.dispose))},(w||(e.RequestCancellationReceiverStrategy=w={})).is=function(e){const t=e;return t&&"request"===t.kind&&n.func(t.createCancellationTokenSource)&&(void 0===t.dispose||n.func(t.dispose))},(_=C||(e.CancellationReceiverStrategy=C={})).Message=Object.freeze({createCancellationTokenSource:e=>new s.CancellationTokenSource}),_.is=function(e){return I.is(e)||w.is(e)},(D=B||(e.CancellationSenderStrategy=B={})).Message=Object.freeze({sendCancellation:(e,t)=>e.sendNotification(a.type,{id:t}),cleanup(e){}}),D.is=function(e){const t=e;return t&&n.func(t.sendCancellation)&&n.func(t.cleanup)},(k=S||(e.CancellationStrategy=S={})).Message=Object.freeze({receiver:C.Message,sender:B.Message}),k.is=function(e){const t=e;return t&&C.is(t.receiver)&&B.is(t.sender)},(x||(e.MessageStrategy=x={})).is=function(e){const t=e;return t&&n.func(t.handleMessage)},(Q||(e.ConnectionOptions=Q={})).is=function(e){const t=e;return t&&(S.is(t.cancellationStrategy)||E.is(t.connectionStrategy)||x.is(t.messageStrategy))},(T=N||(N={}))[T.New=1]="New",T[T.Listening=2]="Listening",T[T.Closed=3]="Closed",T[T.Disposed=4]="Disposed",e.createMessageConnection=function(p,f,h,A){const v=void 0!==h?h:e.NullLogger;let E=0,w=0,C=0;const _="2.0";let B;const D=new Map;let k;const Q=new Map,T=new Map;let F,M,O=new i.LinkedMap,$=new Map,L=new Set,P=new Map,j=d.Off,U=g.Text,z=N.New;const G=new o.Emitter,H=new o.Emitter,W=new o.Emitter,q=new o.Emitter,J=new o.Emitter,K=A&&A.cancellationStrategy?A.cancellationStrategy:S.Message;function Z(e){if(null===e)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+e.toString()}function V(e,t){var n;r.Message.isRequest(t)?e.set(Z(t.id),t):r.Message.isResponse(t)?e.set(null===(n=t.id)?"res-unknown-"+(++C).toString():"res-"+n.toString(),t):e.set("not-"+(++w).toString(),t)}function Y(e){}function X(){return z===N.Listening}function ee(){return z===N.Closed}function te(){return z===N.Disposed}function ne(){z!==N.New&&z!==N.Listening||(z=N.Closed,H.fire(void 0))}function re(){F||0===O.size||(F=(0,t.default)().timer.setImmediate(()=>{F=void 0,function(){if(0===O.size)return;const e=O.shift();try{const t=A?.messageStrategy;x.is(t)?t.handleMessage(e,ie):ie(e)}finally{re()}}()}))}function ie(e){r.Message.isRequest(e)?function(e){if(te())return;function t(t,n,i){const o={jsonrpc:_,id:e.id};t instanceof r.ResponseError?o.error=t.toJson():o.result=void 0===t?null:t,ae(o,n,i),f.write(o).catch(()=>v.error("Sending response failed."))}function i(t,n,r){const i={jsonrpc:_,id:e.id,error:t.toJson()};ae(i,n,r),f.write(i).catch(()=>v.error("Sending response failed."))}function o(t,n,r){void 0===t&&(t=null);const i={jsonrpc:_,id:e.id,result:t};ae(i,n,r),f.write(i).catch(()=>v.error("Sending response failed."))}!function(e){if(j===d.Off||!M)return;if(U===g.Text){let t;j!==d.Verbose&&j!==d.Compact||!e.params||(t=`Params: ${se(e.params)}\n\n`),M.log(`Received request '${e.method} - (${e.id})'.`,t)}else ue("receive-request",e)}(e);const s=D.get(e.method);let a,l;s&&(a=s.type,l=s.handler);const u=Date.now();if(l||B){const s=e.id??String(Date.now()),c=I.is(K.receiver)?K.receiver.createCancellationTokenSource(s):K.receiver.createCancellationTokenSource(e);null!==e.id&&L.has(e.id)&&c.cancel(),null!==e.id&&P.set(s,c);try{let d;if(l)if(void 0===e.params){if(void 0!==a&&0!==a.numberOfParams)return void i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines ${a.numberOfParams} params but received none.`),e.method,u);d=l(c.token)}else if(Array.isArray(e.params)){if(void 0!==a&&a.parameterStructures===r.ParameterStructures.byName)return void i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by name but received parameters by position`),e.method,u);d=l(...e.params,c.token)}else{if(void 0!==a&&a.parameterStructures===r.ParameterStructures.byPosition)return void i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by position but received parameters by name`),e.method,u);d=l(e.params,c.token)}else B&&(d=B(e.method,e.params,c.token));const p=d;d?p.then?p.then(n=>{P.delete(s),t(n,e.method,u)},t=>{P.delete(s),t instanceof r.ResponseError?i(t,e.method,u):t&&n.string(t.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${t.message}`),e.method,u):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,u)}):(P.delete(s),t(d,e.method,u)):(P.delete(s),o(d,e.method,u))}catch(qK){P.delete(s),qK instanceof r.ResponseError?t(qK,e.method,u):qK&&n.string(qK.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${qK.message}`),e.method,u):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,u)}}else i(new r.ResponseError(r.ErrorCodes.MethodNotFound,`Unhandled method ${e.method}`),e.method,u)}(e):r.Message.isNotification(e)?function(e){if(te())return;let t,n;if(e.method===a.type.method){const t=e.params.id;return L.delete(t),void le(e)}{const r=Q.get(e.method);r&&(n=r.handler,t=r.type)}if(n||k)try{if(le(e),n)if(void 0===e.params)void 0!==t&&0!==t.numberOfParams&&t.parameterStructures!==r.ParameterStructures.byName&&v.error(`Notification ${e.method} defines ${t.numberOfParams} params but received none.`),n();else if(Array.isArray(e.params)){const i=e.params;e.method===u.type.method&&2===i.length&&l.is(i[0])?n({token:i[0],value:i[1]}):(void 0!==t&&(t.parameterStructures===r.ParameterStructures.byName&&v.error(`Notification ${e.method} defines parameters by name but received parameters by position`),t.numberOfParams!==e.params.length&&v.error(`Notification ${e.method} defines ${t.numberOfParams} params but received ${i.length} arguments`)),n(...i))}else void 0!==t&&t.parameterStructures===r.ParameterStructures.byPosition&&v.error(`Notification ${e.method} defines parameters by position but received parameters by name`),n(e.params);else k&&k(e.method,e.params)}catch(qK){qK.message?v.error(`Notification handler '${e.method}' failed with message: ${qK.message}`):v.error(`Notification handler '${e.method}' failed unexpectedly.`)}else W.fire(e)}(e):r.Message.isResponse(e)?function(e){if(te())return;if(null===e.id)e.error?v.error(`Received response message without id: Error is: \n${JSON.stringify(e.error,void 0,4)}`):v.error("Received response message without id. No further error information provided.");else{const t=e.id,n=$.get(t);if(function(e,t){if(j===d.Off||!M)return;if(U===g.Text){let n;if(j!==d.Verbose&&j!==d.Compact||(e.error&&e.error.data?n=`Error data: ${se(e.error.data)}\n\n`:e.result?n=`Result: ${se(e.result)}\n\n`:void 0===e.error&&(n="No result returned.\n\n")),t){const r=e.error?` Request failed: ${e.error.message} (${e.error.code}).`:"";M.log(`Received response '${t.method} - (${e.id})' in ${Date.now()-t.timerStart}ms.${r}`,n)}else M.log(`Received response ${e.id} without active response promise.`,n)}else ue("receive-response",e)}(e,n),void 0!==n){$.delete(t);try{if(e.error){const t=e.error;n.reject(new r.ResponseError(t.code,t.message,t.data))}else{if(void 0===e.result)throw new Error("Should never happen.");n.resolve(e.result)}}catch(qK){qK.message?v.error(`Response handler '${n.method}' failed with message: ${qK.message}`):v.error(`Response handler '${n.method}' failed unexpectedly.`)}}}}(e):function(e){if(!e)return void v.error("Received empty message.");v.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(e,null,4)}`);const t=e;if(n.string(t.id)||n.number(t.id)){const e=t.id,n=$.get(e);n&&n.reject(new Error("The received response has neither a result nor an error property."))}}(e)}p.onClose(ne),p.onError(function(e){G.fire([e,void 0,void 0])}),f.onClose(ne),f.onError(function(e){G.fire(e)});const oe=e=>{try{if(r.Message.isNotification(e)&&e.method===a.type.method){const t=e.params.id,n=Z(t),i=O.get(n);if(r.Message.isRequest(i)){const r=A?.connectionStrategy,o=r&&r.cancelUndispatched?r.cancelUndispatched(i,Y):void 0;if(o&&(void 0!==o.error||void 0!==o.result))return O.delete(n),P.delete(t),o.id=i.id,ae(o,e.method,Date.now()),void f.write(o).catch(()=>v.error("Sending response for canceled message failed."))}const o=P.get(t);if(void 0!==o)return o.cancel(),void le(e);L.add(t)}V(O,e)}finally{re()}};function se(e){if(null!=e)switch(j){case d.Verbose:return JSON.stringify(e,null,4);case d.Compact:return JSON.stringify(e);default:return}}function ae(e,t,n){if(j!==d.Off&&M)if(U===g.Text){let r;j!==d.Verbose&&j!==d.Compact||(e.error&&e.error.data?r=`Error data: ${se(e.error.data)}\n\n`:e.result?r=`Result: ${se(e.result)}\n\n`:void 0===e.error&&(r="No result returned.\n\n")),M.log(`Sending response '${t} - (${e.id})'. Processing request took ${Date.now()-n}ms`,r)}else ue("send-response",e)}function le(e){if(j!==d.Off&&M&&e.method!==y.type.method)if(U===g.Text){let t;j!==d.Verbose&&j!==d.Compact||(t=e.params?`Params: ${se(e.params)}\n\n`:"No parameters provided.\n\n"),M.log(`Received notification '${e.method}'.`,t)}else ue("receive-notification",e)}function ue(e,t){if(!M||j===d.Off)return;const n={isLSPMessage:!0,type:e,message:t,timestamp:Date.now()};M.log(n)}function ce(){if(ee())throw new R(b.Closed,"Connection is closed.");if(te())throw new R(b.Disposed,"Connection is disposed.")}function de(e){return void 0===e?null:e}function pe(e){return null===e?void 0:e}function fe(e){return null!=e&&!Array.isArray(e)&&"object"==typeof e}function he(e,t){switch(e){case r.ParameterStructures.auto:return fe(t)?pe(t):[de(t)];case r.ParameterStructures.byName:if(!fe(t))throw new Error("Received parameters by name but param is not an object literal.");return pe(t);case r.ParameterStructures.byPosition:return[de(t)];default:throw new Error(`Unknown parameter structure ${e.toString()}`)}}function ge(e,t){let n;const r=e.numberOfParams;switch(r){case 0:n=void 0;break;case 1:n=he(e.parameterStructures,t[0]);break;default:n=[];for(let e=0;e<t.length&&e<r;e++)n.push(de(t[e]));if(t.length<r)for(let e=t.length;e<r;e++)n.push(null)}return n}const Ae={sendNotification:(e,...t)=>{let i,o;if(ce(),n.string(e)){i=e;const n=t[0];let s=0,a=r.ParameterStructures.auto;r.ParameterStructures.is(n)&&(s=1,a=n);let l=t.length;const u=l-s;switch(u){case 0:o=void 0;break;case 1:o=he(a,t[s]);break;default:if(a===r.ParameterStructures.byName)throw new Error(`Received ${u} parameters for 'by Name' notification parameter structure.`);o=t.slice(s,l).map(e=>de(e))}}else{const n=t;i=e.method,o=ge(e,n)}const s={jsonrpc:_,method:i,params:o};return function(e){if(j!==d.Off&&M)if(U===g.Text){let t;j!==d.Verbose&&j!==d.Compact||(t=e.params?`Params: ${se(e.params)}\n\n`:"No parameters provided.\n\n"),M.log(`Sending notification '${e.method}'.`,t)}else ue("send-notification",e)}(s),f.write(s).catch(e=>{throw v.error("Sending notification failed."),e})},onNotification:(e,t)=>{let r;return ce(),n.func(e)?k=e:t&&(n.string(e)?(r=e,Q.set(e,{type:void 0,handler:t})):(r=e.method,Q.set(e.method,{type:e,handler:t}))),{dispose:()=>{void 0!==r?Q.delete(r):k=void 0}}},onProgress:(e,t,n)=>{if(T.has(t))throw new Error(`Progress handler for token ${t} already registered`);return T.set(t,n),{dispose:()=>{T.delete(t)}}},sendProgress:(e,t,n)=>Ae.sendNotification(u.type,{token:t,value:n}),onUnhandledProgress:q.event,sendRequest:(e,...t)=>{let i,o,a;if(ce(),function(){if(!X())throw new Error("Call listen() first.")}(),n.string(e)){i=e;const n=t[0],l=t[t.length-1];let u=0,c=r.ParameterStructures.auto;r.ParameterStructures.is(n)&&(u=1,c=n);let d=t.length;s.CancellationToken.is(l)&&(d-=1,a=l);const p=d-u;switch(p){case 0:o=void 0;break;case 1:o=he(c,t[u]);break;default:if(c===r.ParameterStructures.byName)throw new Error(`Received ${p} parameters for 'by Name' request parameter structure.`);o=t.slice(u,d).map(e=>de(e))}}else{const n=t;i=e.method,o=ge(e,n);const r=e.numberOfParams;a=s.CancellationToken.is(n[r])?n[r]:void 0}const l=E++;let u;a&&(u=a.onCancellationRequested(()=>{const e=K.sender.sendCancellation(Ae,l);return void 0===e?(v.log(`Received no promise from cancellation strategy when cancelling id ${l}`),Promise.resolve()):e.catch(()=>{v.log(`Sending cancellation messages for id ${l} failed`)})}));const c={jsonrpc:_,id:l,method:i,params:o};return function(e){if(j!==d.Off&&M)if(U===g.Text){let t;j!==d.Verbose&&j!==d.Compact||!e.params||(t=`Params: ${se(e.params)}\n\n`),M.log(`Sending request '${e.method} - (${e.id})'.`,t)}else ue("send-request",e)}(c),"function"==typeof K.sender.enableCancellation&&K.sender.enableCancellation(c),new Promise(async(e,t)=>{const n={method:i,timerStart:Date.now(),resolve:t=>{e(t),K.sender.cleanup(l),u?.dispose()},reject:e=>{t(e),K.sender.cleanup(l),u?.dispose()}};try{$.set(l,n),await f.write(c)}catch(qK){throw $.delete(l),n.reject(new r.ResponseError(r.ErrorCodes.MessageWriteError,qK.message?qK.message:"Unknown reason")),v.error("Sending request failed."),qK}})},onRequest:(e,t)=>{ce();let r=null;return c.is(e)?(r=void 0,B=e):n.string(e)?(r=null,void 0!==t&&(r=e,D.set(e,{handler:t,type:void 0}))):void 0!==t&&(r=e.method,D.set(e.method,{type:e,handler:t})),{dispose:()=>{null!==r&&(void 0!==r?D.delete(r):B=void 0)}}},hasPendingResponse:()=>$.size>0,trace:async(e,t,r)=>{let i=!1,o=g.Text;void 0!==r&&(n.boolean(r)?i=r:(i=r.sendNotification||!1,o=r.traceFormat||g.Text)),j=e,U=o,M=j===d.Off?void 0:t,!i||ee()||te()||await Ae.sendNotification(m.type,{value:d.toString(e)})},onError:G.event,onClose:H.event,onUnhandledNotification:W.event,onDispose:J.event,end:()=>{f.end()},dispose:()=>{if(te())return;z=N.Disposed,J.fire(void 0);const e=new r.ResponseError(r.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(const t of $.values())t.reject(e);$=new Map,P=new Map,L=new Set,O=new i.LinkedMap,n.func(f.dispose)&&f.dispose(),n.func(p.dispose)&&p.dispose()},listen:()=>{ce(),function(){if(X())throw new R(b.AlreadyListening,"Connection is already listening")}(),z=N.Listening,p.listen(oe)},inspect:()=>{(0,t.default)().console.log("inspect")}};return Ae.onNotification(y.type,e=>{if(j===d.Off||!M)return;const t=j===d.Verbose||j===d.Compact;M.log(e.message,t?e.verbose:void 0)}),Ae.onNotification(u.type,e=>{const t=T.get(e.token);t?t(e.value):q.fire(e)}),Ae}}(wG)),wG}function _G(){return yG||(yG=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ProgressType=e.ProgressToken=e.createMessageConnection=e.NullLogger=e.ConnectionOptions=e.ConnectionStrategy=e.AbstractMessageBuffer=e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=e.CancellationToken=e.CancellationTokenSource=e.Emitter=e.Event=e.Disposable=e.LRUCache=e.Touch=e.LinkedMap=e.ParameterStructures=e.NotificationType9=e.NotificationType8=e.NotificationType7=e.NotificationType6=e.NotificationType5=e.NotificationType4=e.NotificationType3=e.NotificationType2=e.NotificationType1=e.NotificationType0=e.NotificationType=e.ErrorCodes=e.ResponseError=e.RequestType9=e.RequestType8=e.RequestType7=e.RequestType6=e.RequestType5=e.RequestType4=e.RequestType3=e.RequestType2=e.RequestType1=e.RequestType0=e.RequestType=e.Message=e.RAL=void 0,e.MessageStrategy=e.CancellationStrategy=e.CancellationSenderStrategy=e.CancellationReceiverStrategy=e.ConnectionError=e.ConnectionErrors=e.LogTraceNotification=e.SetTraceNotification=e.TraceFormat=e.TraceValues=e.Trace=void 0;const t=Hz();Object.defineProperty(e,"Message",{enumerable:!0,get:function(){return t.Message}}),Object.defineProperty(e,"RequestType",{enumerable:!0,get:function(){return t.RequestType}}),Object.defineProperty(e,"RequestType0",{enumerable:!0,get:function(){return t.RequestType0}}),Object.defineProperty(e,"RequestType1",{enumerable:!0,get:function(){return t.RequestType1}}),Object.defineProperty(e,"RequestType2",{enumerable:!0,get:function(){return t.RequestType2}}),Object.defineProperty(e,"RequestType3",{enumerable:!0,get:function(){return t.RequestType3}}),Object.defineProperty(e,"RequestType4",{enumerable:!0,get:function(){return t.RequestType4}}),Object.defineProperty(e,"RequestType5",{enumerable:!0,get:function(){return t.RequestType5}}),Object.defineProperty(e,"RequestType6",{enumerable:!0,get:function(){return t.RequestType6}}),Object.defineProperty(e,"RequestType7",{enumerable:!0,get:function(){return t.RequestType7}}),Object.defineProperty(e,"RequestType8",{enumerable:!0,get:function(){return t.RequestType8}}),Object.defineProperty(e,"RequestType9",{enumerable:!0,get:function(){return t.RequestType9}}),Object.defineProperty(e,"ResponseError",{enumerable:!0,get:function(){return t.ResponseError}}),Object.defineProperty(e,"ErrorCodes",{enumerable:!0,get:function(){return t.ErrorCodes}}),Object.defineProperty(e,"NotificationType",{enumerable:!0,get:function(){return t.NotificationType}}),Object.defineProperty(e,"NotificationType0",{enumerable:!0,get:function(){return t.NotificationType0}}),Object.defineProperty(e,"NotificationType1",{enumerable:!0,get:function(){return t.NotificationType1}}),Object.defineProperty(e,"NotificationType2",{enumerable:!0,get:function(){return t.NotificationType2}}),Object.defineProperty(e,"NotificationType3",{enumerable:!0,get:function(){return t.NotificationType3}}),Object.defineProperty(e,"NotificationType4",{enumerable:!0,get:function(){return t.NotificationType4}}),Object.defineProperty(e,"NotificationType5",{enumerable:!0,get:function(){return t.NotificationType5}}),Object.defineProperty(e,"NotificationType6",{enumerable:!0,get:function(){return t.NotificationType6}}),Object.defineProperty(e,"NotificationType7",{enumerable:!0,get:function(){return t.NotificationType7}}),Object.defineProperty(e,"NotificationType8",{enumerable:!0,get:function(){return t.NotificationType8}}),Object.defineProperty(e,"NotificationType9",{enumerable:!0,get:function(){return t.NotificationType9}}),Object.defineProperty(e,"ParameterStructures",{enumerable:!0,get:function(){return t.ParameterStructures}});const n=Jz();Object.defineProperty(e,"LinkedMap",{enumerable:!0,get:function(){return n.LinkedMap}}),Object.defineProperty(e,"LRUCache",{enumerable:!0,get:function(){return n.LRUCache}}),Object.defineProperty(e,"Touch",{enumerable:!0,get:function(){return n.Touch}});const r=(Kz||(Kz=1,Object.defineProperty(Zz,"__esModule",{value:!0}),Zz.Disposable=void 0,(i||(Zz.Disposable=i={})).create=function(e){return{dispose:e}}),Zz);var i;Object.defineProperty(e,"Disposable",{enumerable:!0,get:function(){return r.Disposable}});const o=nG();Object.defineProperty(e,"Event",{enumerable:!0,get:function(){return o.Event}}),Object.defineProperty(e,"Emitter",{enumerable:!0,get:function(){return o.Emitter}});const s=oG();Object.defineProperty(e,"CancellationTokenSource",{enumerable:!0,get:function(){return s.CancellationTokenSource}}),Object.defineProperty(e,"CancellationToken",{enumerable:!0,get:function(){return s.CancellationToken}});const a=function(){if(sG)return aG;sG=1,Object.defineProperty(aG,"__esModule",{value:!0}),aG.SharedArrayReceiverStrategy=aG.SharedArraySenderStrategy=void 0;const e=oG();var t,n;(n=t||(t={})).Continue=0,n.Cancelled=1,aG.SharedArraySenderStrategy=class{constructor(){this.buffers=new Map}enableCancellation(e){if(null===e.id)return;const n=new SharedArrayBuffer(4);new Int32Array(n,0,1)[0]=t.Continue,this.buffers.set(e.id,n),e.$cancellationData=n}async sendCancellation(e,n){const r=this.buffers.get(n);if(void 0===r)return;const i=new Int32Array(r,0,1);Atomics.store(i,0,t.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};class r{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===t.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}}class i{constructor(e){this.token=new r(e)}cancel(){}dispose(){}}return aG.SharedArrayReceiverStrategy=class{constructor(){this.kind="request"}createCancellationTokenSource(t){const n=t.$cancellationData;return void 0===n?new e.CancellationTokenSource:new i(n)}},aG}();Object.defineProperty(e,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return a.SharedArraySenderStrategy}}),Object.defineProperty(e,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return a.SharedArrayReceiverStrategy}});const l=function(){if(uG)return cG;uG=1,Object.defineProperty(cG,"__esModule",{value:!0}),cG.ReadableStreamMessageReader=cG.AbstractMessageReader=cG.MessageReader=void 0;const e=tG(),t=Gz(),n=nG(),r=pG();var i,o;(i||(cG.MessageReader=i={})).is=function(e){let n=e;return n&&t.func(n.listen)&&t.func(n.dispose)&&t.func(n.onError)&&t.func(n.onClose)&&t.func(n.onPartialMessage)};class s{constructor(){this.errorEmitter=new n.Emitter,this.closeEmitter=new n.Emitter,this.partialMessageEmitter=new n.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:new Error(`Reader received error. Reason: ${t.string(e.message)?e.message:"unknown"}`)}}return cG.AbstractMessageReader=s,(o||(o={})).fromOptions=function(t){let n,r;const i=new Map;let o;const s=new Map;if(void 0===t||"string"==typeof t)n=t??"utf-8";else{if(n=t.charset??"utf-8",void 0!==t.contentDecoder&&(r=t.contentDecoder,i.set(r.name,r)),void 0!==t.contentDecoders)for(const e of t.contentDecoders)i.set(e.name,e);if(void 0!==t.contentTypeDecoder&&(o=t.contentTypeDecoder,s.set(o.name,o)),void 0!==t.contentTypeDecoders)for(const e of t.contentTypeDecoders)s.set(e.name,e)}return void 0===o&&(o=(0,e.default)().applicationJson.decoder,s.set(o.name,o)),{charset:n,contentDecoder:r,contentDecoders:i,contentTypeDecoder:o,contentTypeDecoders:s}},cG.ReadableStreamMessageReader=class extends s{constructor(t,n){super(),this.readable=t,this.options=o.fromOptions(n),this.buffer=(0,e.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new r.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;const t=this.readable.onData(e=>{this.onData(e)});return this.readable.onError(e=>this.fireError(e)),this.readable.onClose(()=>this.fireClose()),t}onData(e){try{for(this.buffer.append(e);;){if(-1===this.nextMessageLength){const e=this.buffer.tryReadHeaders(!0);if(!e)return;const t=e.get("content-length");if(!t)return void this.fireError(new Error(`Header must provide a Content-Length property.\n${JSON.stringify(Object.fromEntries(e))}`));const n=parseInt(t);if(isNaN(n))return void this.fireError(new Error(`Content-Length value must be a number. Got ${t}`));this.nextMessageLength=n}const e=this.buffer.tryReadBody(this.nextMessageLength);if(void 0===e)return void this.setPartialMessageTimer();this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{const t=void 0!==this.options.contentDecoder?await this.options.contentDecoder.decode(e):e,n=await this.options.contentTypeDecoder.decode(t,this.options);this.callback(n)}).catch(e=>{this.fireError(e)})}}catch(qK){this.fireError(qK)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),this._partialMessageTimeout<=0||(this.partialMessageTimer=(0,e.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}},cG}();Object.defineProperty(e,"MessageReader",{enumerable:!0,get:function(){return l.MessageReader}}),Object.defineProperty(e,"AbstractMessageReader",{enumerable:!0,get:function(){return l.AbstractMessageReader}}),Object.defineProperty(e,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return l.ReadableStreamMessageReader}});const u=function(){if(fG)return hG;fG=1,Object.defineProperty(hG,"__esModule",{value:!0}),hG.WriteableStreamMessageWriter=hG.AbstractMessageWriter=hG.MessageWriter=void 0;const e=tG(),t=Gz(),n=pG(),r=nG();var i,o;(i||(hG.MessageWriter=i={})).is=function(e){let n=e;return n&&t.func(n.dispose)&&t.func(n.onClose)&&t.func(n.onError)&&t.func(n.write)};class s{constructor(){this.errorEmitter=new r.Emitter,this.closeEmitter=new r.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,n){this.errorEmitter.fire([this.asError(e),t,n])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:new Error(`Writer received error. Reason: ${t.string(e.message)?e.message:"unknown"}`)}}return hG.AbstractMessageWriter=s,(o||(o={})).fromOptions=function(t){return void 0===t||"string"==typeof t?{charset:t??"utf-8",contentTypeEncoder:(0,e.default)().applicationJson.encoder}:{charset:t.charset??"utf-8",contentEncoder:t.contentEncoder,contentTypeEncoder:t.contentTypeEncoder??(0,e.default)().applicationJson.encoder}},hG.WriteableStreamMessageWriter=class extends s{constructor(e,t){super(),this.writable=e,this.options=o.fromOptions(t),this.errorCount=0,this.writeSemaphore=new n.Semaphore(1),this.writable.onError(e=>this.fireError(e)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(e=>void 0!==this.options.contentEncoder?this.options.contentEncoder.encode(e):e).then(t=>{const n=[];return n.push("Content-Length: ",t.byteLength.toString(),"\r\n"),n.push("\r\n"),this.doWrite(e,n,t)},e=>{throw this.fireError(e),e}))}async doWrite(e,t,n){try{return await this.writable.write(t.join(""),"ascii"),this.writable.write(n)}catch(qK){return this.handleError(qK,e),Promise.reject(qK)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){this.writable.end()}},hG}();Object.defineProperty(e,"MessageWriter",{enumerable:!0,get:function(){return u.MessageWriter}}),Object.defineProperty(e,"AbstractMessageWriter",{enumerable:!0,get:function(){return u.AbstractMessageWriter}}),Object.defineProperty(e,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return u.WriteableStreamMessageWriter}});const c=(gG||(gG=1,Object.defineProperty(AG,"__esModule",{value:!0}),AG.AbstractMessageBuffer=void 0,AG.AbstractMessageBuffer=class{constructor(e="utf-8"){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){const t="string"==typeof e?this.fromString(e,this._encoding):e;this._chunks.push(t),this._totalLength+=t.byteLength}tryReadHeaders(e=!1){if(0===this._chunks.length)return;let t=0,n=0,r=0,i=0;e:for(;n<this._chunks.length;){const e=this._chunks[n];for(r=0;r<e.length;){switch(e[r]){case 13:switch(t){case 0:t=1;break;case 2:t=3;break;default:t=0}break;case 10:switch(t){case 1:t=2;break;case 3:t=4,r++;break e;default:t=0}break;default:t=0}r++}i+=e.byteLength,n++}if(4!==t)return;const o=this._read(i+r),s=new Map,a=this.toString(o,"ascii").split("\r\n");if(a.length<2)return s;for(let l=0;l<a.length-2;l++){const t=a[l],n=t.indexOf(":");if(-1===n)throw new Error(`Message header must separate key and value using ':'\n${t}`);const r=t.substr(0,n),i=t.substr(n+1).trim();s.set(e?r.toLowerCase():r,i)}return s}tryReadBody(e){if(!(this._totalLength<e))return this._read(e)}get numberOfBytes(){return this._totalLength}_read(e){if(0===e)return this.emptyBuffer();if(e>this._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===e){const t=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(t)}if(this._chunks[0].byteLength>e){const t=this._chunks[0],n=this.asNative(t,e);return this._chunks[0]=t.slice(e),this._totalLength-=e,n}const t=this.allocNative(e);let n=0;for(;e>0;){const r=this._chunks[0];if(r.byteLength>e){const i=r.slice(0,e);t.set(i,n),n+=e,this._chunks[0]=r.slice(e),this._totalLength-=e,e-=e}else t.set(r,n),n+=r.byteLength,this._chunks.shift(),this._totalLength-=r.byteLength,e-=r.byteLength}return t}}),AG);Object.defineProperty(e,"AbstractMessageBuffer",{enumerable:!0,get:function(){return c.AbstractMessageBuffer}});const d=CG();Object.defineProperty(e,"ConnectionStrategy",{enumerable:!0,get:function(){return d.ConnectionStrategy}}),Object.defineProperty(e,"ConnectionOptions",{enumerable:!0,get:function(){return d.ConnectionOptions}}),Object.defineProperty(e,"NullLogger",{enumerable:!0,get:function(){return d.NullLogger}}),Object.defineProperty(e,"createMessageConnection",{enumerable:!0,get:function(){return d.createMessageConnection}}),Object.defineProperty(e,"ProgressToken",{enumerable:!0,get:function(){return d.ProgressToken}}),Object.defineProperty(e,"ProgressType",{enumerable:!0,get:function(){return d.ProgressType}}),Object.defineProperty(e,"Trace",{enumerable:!0,get:function(){return d.Trace}}),Object.defineProperty(e,"TraceValues",{enumerable:!0,get:function(){return d.TraceValues}}),Object.defineProperty(e,"TraceFormat",{enumerable:!0,get:function(){return d.TraceFormat}}),Object.defineProperty(e,"SetTraceNotification",{enumerable:!0,get:function(){return d.SetTraceNotification}}),Object.defineProperty(e,"LogTraceNotification",{enumerable:!0,get:function(){return d.LogTraceNotification}}),Object.defineProperty(e,"ConnectionErrors",{enumerable:!0,get:function(){return d.ConnectionErrors}}),Object.defineProperty(e,"ConnectionError",{enumerable:!0,get:function(){return d.ConnectionError}}),Object.defineProperty(e,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return d.CancellationReceiverStrategy}}),Object.defineProperty(e,"CancellationSenderStrategy",{enumerable:!0,get:function(){return d.CancellationSenderStrategy}}),Object.defineProperty(e,"CancellationStrategy",{enumerable:!0,get:function(){return d.CancellationStrategy}}),Object.defineProperty(e,"MessageStrategy",{enumerable:!0,get:function(){return d.MessageStrategy}});const p=tG();e.RAL=p.default}(jz)),jz}function BG(){return vG||(vG=1,function(e){var t=Lz&&Lz.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),n=Lz&&Lz.__exportStar||function(e,n){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(n,r)||t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.createMessageConnection=e.createServerSocketTransport=e.createClientSocketTransport=e.createServerPipeTransport=e.createClientPipeTransport=e.generateRandomPipeName=e.StreamMessageWriter=e.StreamMessageReader=e.SocketMessageWriter=e.SocketMessageReader=e.PortMessageWriter=e.PortMessageReader=e.IPCMessageWriter=e.IPCMessageReader=void 0;const r=function(){if(bG)return Pz;bG=1,Object.defineProperty(Pz,"__esModule",{value:!0});const e=L,t=_G();class n extends t.AbstractMessageBuffer{constructor(e="utf-8"){super(e)}emptyBuffer(){return n.emptyBuffer}fromString(e,t){return Buffer.from(e,t)}toString(t,n){return t instanceof Buffer?t.toString(n):new e.TextDecoder(n).decode(t)}asNative(e,t){return void 0===t?e instanceof Buffer?e:Buffer.from(e):e instanceof Buffer?e.slice(0,t):Buffer.from(e,0,t)}allocNative(e){return Buffer.allocUnsafe(e)}}n.emptyBuffer=Buffer.allocUnsafe(0);class r{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),t.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),t.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),t.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),t.Disposable.create(()=>this.stream.off("data",e))}}class i{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),t.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),t.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),t.Disposable.create(()=>this.stream.off("end",e))}write(e,t){return new Promise((n,r)=>{const i=e=>{null==e?n():r(e)};"string"==typeof e?this.stream.write(e,t,i):this.stream.write(e,i)})}end(){this.stream.end()}}const o=Object.freeze({messageBuffer:Object.freeze({create:e=>new n(e)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(e,t)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(e,void 0,0),t.charset))}catch(n){return Promise.reject(n)}}}),decoder:Object.freeze({name:"application/json",decode:(t,n)=>{try{return t instanceof Buffer?Promise.resolve(JSON.parse(t.toString(n.charset))):Promise.resolve(JSON.parse(new e.TextDecoder(n.charset).decode(t)))}catch(r){return Promise.reject(r)}}})}),stream:Object.freeze({asReadableStream:e=>new r(e),asWritableStream:e=>new i(e)}),console:console,timer:Object.freeze({setTimeout(e,t,...n){const r=setTimeout(e,t,...n);return{dispose:()=>clearTimeout(r)}},setImmediate(e,...t){const n=setImmediate(e,...t);return{dispose:()=>clearImmediate(n)}},setInterval(e,t,...n){const r=setInterval(e,t,...n);return{dispose:()=>clearInterval(r)}}})});function s(){return o}return(s||(s={})).install=function(){t.RAL.install(o)},Pz.default=s,Pz}();r.default.install();const i=ae,o=G,s=ge,a=De,l=_G();n(_G(),e);class u extends l.AbstractMessageReader{constructor(e){super(),this.process=e;let t=this.process;t.on("error",e=>this.fireError(e)),t.on("close",()=>this.fireClose())}listen(e){return this.process.on("message",e),l.Disposable.create(()=>this.process.off("message",e))}}e.IPCMessageReader=u;class c extends l.AbstractMessageWriter{constructor(e){super(),this.process=e,this.errorCount=0;const t=this.process;t.on("error",e=>this.fireError(e)),t.on("close",()=>this.fireClose)}write(e){try{return"function"==typeof this.process.send&&this.process.send(e,void 0,void 0,t=>{t?(this.errorCount++,this.handleError(t,e)):this.errorCount=0}),Promise.resolve()}catch(qK){return this.handleError(qK,e),Promise.reject(qK)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}}e.IPCMessageWriter=c;class d extends l.AbstractMessageReader{constructor(e){super(),this.onData=new l.Emitter,e.on("close",()=>this.fireClose),e.on("error",e=>this.fireError(e)),e.on("message",e=>{this.onData.fire(e)})}listen(e){return this.onData.event(e)}}e.PortMessageReader=d;class p extends l.AbstractMessageWriter{constructor(e){super(),this.port=e,this.errorCount=0,e.on("close",()=>this.fireClose()),e.on("error",e=>this.fireError(e))}write(e){try{return this.port.postMessage(e),Promise.resolve()}catch(qK){return this.handleError(qK,e),Promise.reject(qK)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){}}e.PortMessageWriter=p;class f extends l.ReadableStreamMessageReader{constructor(e,t="utf-8"){super((0,r.default)().stream.asReadableStream(e),t)}}e.SocketMessageReader=f;class h extends l.WriteableStreamMessageWriter{constructor(e,t){super((0,r.default)().stream.asWritableStream(e),t),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}}e.SocketMessageWriter=h;class g extends l.ReadableStreamMessageReader{constructor(e,t){super((0,r.default)().stream.asReadableStream(e),t)}}e.StreamMessageReader=g;class A extends l.WriteableStreamMessageWriter{constructor(e,t){super((0,r.default)().stream.asWritableStream(e),t)}}e.StreamMessageWriter=A;const m=process.env.XDG_RUNTIME_DIR,y=new Map([["linux",107],["darwin",103]]);e.generateRandomPipeName=function(){const e=(0,s.randomBytes)(21).toString("hex");if("win32"===process.platform)return`\\\\.\\pipe\\vscode-jsonrpc-${e}-sock`;let t;t=m?i.join(m,`vscode-ipc-${e}.sock`):i.join(o.tmpdir(),`vscode-${e}.sock`);const n=y.get(process.platform);return void 0!==n&&t.length>n&&(0,r.default)().console.warn(`WARNING: IPC handle "${t}" is longer than ${n} characters.`),t},e.createClientPipeTransport=function(e,t="utf-8"){let n;const r=new Promise((e,t)=>{n=e});return new Promise((i,o)=>{let s=(0,a.createServer)(e=>{s.close(),n([new f(e,t),new h(e,t)])});s.on("error",o),s.listen(e,()=>{s.removeListener("error",o),i({onConnected:()=>r})})})},e.createServerPipeTransport=function(e,t="utf-8"){const n=(0,a.createConnection)(e);return[new f(n,t),new h(n,t)]},e.createClientSocketTransport=function(e,t="utf-8"){let n;const r=new Promise((e,t)=>{n=e});return new Promise((i,o)=>{const s=(0,a.createServer)(e=>{s.close(),n([new f(e,t),new h(e,t)])});s.on("error",o),s.listen(e,"127.0.0.1",()=>{s.removeListener("error",o),i({onConnected:()=>r})})})},e.createServerSocketTransport=function(e,t="utf-8"){const n=(0,a.createConnection)(e,"127.0.0.1");return[new f(n,t),new h(n,t)]},e.createMessageConnection=function(e,t,n,r){n||(n=l.NullLogger);const i=function(e){const t=e;return void 0!==t.read&&void 0!==t.addListener}(e)?new g(e):e,o=function(e){const t=e;return void 0!==t.write&&void 0!==t.addListener}(t)?new A(t):t;return l.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,l.createMessageConnection)(i,o,n,r)}}(Lz)),Lz}var DG=IG?EG:(IG=1,EG=BG());const SG={".c":"c",".cpp":"cpp",".cxx":"cpp",".cc":"cpp",".c++":"cpp",".h":"c",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".h++":"cpp",".rs":"rust"};var kG;(kG||(kG={})).create=async function(e){ex.info(`Starting LSP client for ${e.serverID}`);const t=DG.createMessageConnection(new DG.StreamMessageReader(e.server.process.stdout),new DG.StreamMessageWriter(e.server.process.stdin)),n=new Map;t.onNotification("textDocument/publishDiagnostics",e=>{const t=B(e.uri);ex.info(`Received diagnostics for ${t}`),n.set(t,e.diagnostics)}),t.onRequest("workspace/configuration",async()=>[e.server.initialization??{}]),t.onRequest("window/workDoneProgress/create",()=>null),t.listen(),ex.info(`Sending initialize request to ${e.serverID}`);try{await Promise.race([t.sendRequest("initialize",{rootUri:D(e.root).href,processId:e.server.process.pid,workspaceFolders:[{name:"workspace",uri:D(e.root).href}],initializationOptions:{...e.server.initialization},capabilities:{window:{workDoneProgress:!0},workspace:{configuration:!0},textDocument:{synchronization:{didOpen:!0,didChange:!0},publishDiagnostics:{versionSupport:!0}}}}),new Promise((e,t)=>setTimeout(()=>t(new Error("LSP initialization timeout")),5e3))])}catch(qK){throw ex.error(`Failed to initialize LSP client ${e.serverID}`,qK),t.end(),t.dispose(),e.server.process.kill(),qK}await t.sendNotification("initialized",{}),e.server.initialization&&await t.sendNotification("workspace/didChangeConfiguration",{settings:e.server.initialization}),ex.info(`LSP client initialized for ${e.serverID}`);const r={};return{root:e.root,serverID:e.serverID,connection:t,diagnostics:n,notify:{async open(e){const i=v.isAbsolute(e.path)?e.path:v.resolve(process.cwd(),e.path);try{const e=await import("node:fs/promises").then(e=>e.readFile(i,"utf8")),o=v.extname(i),s=SG[o]??"plaintext",a=r[i];if(void 0!==a){const n=a+1;return r[i]=n,ex.info(`textDocument/didChange for ${i} (v${n})`),void(await t.sendNotification("textDocument/didChange",{textDocument:{uri:D(i).href,version:n},contentChanges:[{text:e}]}))}ex.info(`textDocument/didOpen for ${i}`),n.delete(i),await t.sendNotification("textDocument/didOpen",{textDocument:{uri:D(i).href,languageId:s,version:0,text:e}}),r[i]=0}catch(qK){ex.error(`Failed to open file in LSP: ${i}`,qK)}}},async waitForDiagnostics(e){const t=v.isAbsolute(e.path)?e.path:v.resolve(process.cwd(),e.path);return ex.info(`Waiting for diagnostics for ${t}`),new Promise(e=>{const r=setTimeout(()=>{e()},3e3),i=()=>{n.has(t)?(clearTimeout(r),ex.info(`Got diagnostics for ${t}`),e()):setTimeout(i,100)};i()})},async shutdown(){ex.info(`Shutting down LSP client ${e.serverID}`),t.end(),t.dispose(),e.server.process.kill(),ex.info(`LSP client ${e.serverID} shut down`)}}};const xG={bin:v.join(h.homedir(),".embedder","bin")};var QG,NG={},TG={};var RG,FG={};function MG(){if(RG)return FG;RG=1,Object.defineProperty(FG,"__esModule",{value:!0}),FG.sync=FG.isexe=void 0;const e=J,t=Be;FG.isexe=async(e,r={})=>{const{ignoreErrors:i=!1}=r;try{return n(await(0,t.stat)(e),e,r)}catch(o){const e=o;if(i||"EACCES"===e.code)return!1;throw e}};FG.sync=(t,r={})=>{const{ignoreErrors:i=!1}=r;try{return n((0,e.statSync)(t),t,r)}catch(o){const e=o;if(i||"EACCES"===e.code)return!1;throw e}};const n=(e,t,n)=>e.isFile()&&((e,t)=>{const{pathExt:n=process.env.PATHEXT||""}=t,r=n.split(";");if(-1!==r.indexOf(""))return!0;for(let i=0;i<r.length;i++){const t=r[i].toLowerCase(),n=e.substring(e.length-t.length).toLowerCase();if(t&&n===t)return!0}return!1})(t,n);return FG}var OG,$G,LG,PG,jG={};function UG(){return $G||($G=1,function(e){var t=NG&&NG.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),n=NG&&NG.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=NG&&NG.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},i=NG&&NG.__exportStar||function(e,n){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(n,r)||t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.sync=e.isexe=e.posix=e.win32=void 0;const o=r(function(){if(QG)return TG;QG=1,Object.defineProperty(TG,"__esModule",{value:!0}),TG.sync=TG.isexe=void 0;const e=J,t=Be;TG.isexe=async(e,r={})=>{const{ignoreErrors:i=!1}=r;try{return n(await(0,t.stat)(e),r)}catch(o){const e=o;if(i||"EACCES"===e.code)return!1;throw e}},TG.sync=(t,r={})=>{const{ignoreErrors:i=!1}=r;try{return n((0,e.statSync)(t),r)}catch(o){const e=o;if(i||"EACCES"===e.code)return!1;throw e}};const n=(e,t)=>e.isFile()&&r(e,t),r=(e,t)=>{const n=t.uid??process.getuid?.(),r=t.groups??process.getgroups?.()??[],i=t.gid??process.getgid?.()??r[0];if(void 0===n||void 0===i)throw new Error("cannot get uid or gid");const o=new Set([i,...r]),s=e.mode,a=e.uid,l=e.gid,u=parseInt("100",8),c=parseInt("010",8),d=u|c;return!!(s&parseInt("001",8)||s&c&&o.has(l)||s&u&&a===n||s&d&&0===n)};return TG}());e.posix=o;const s=r(MG());e.win32=s,i((OG||(OG=1,Object.defineProperty(jG,"__esModule",{value:!0})),jG),e);const a="win32"===(process.env._ISEXE_TEST_PLATFORM_||process.platform)?s:o;e.isexe=a.isexe,e.sync=a.sync}(NG)),NG}const zG=e(function(){if(PG)return LG;PG=1;const{isexe:e,sync:t}=UG(),{join:n,delimiter:r,sep:i,posix:o}=ae,s="win32"===process.platform,a=new RegExp(`[${o.sep}${i===o.sep?"":i}]`.replace(/(\\)/g,"\\$1")),l=new RegExp(`^\\.${a.source}`),u=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),c=(e,{path:t=process.env.PATH,pathExt:n=process.env.PATHEXT,delimiter:i=r})=>{const o=e.match(a)?[""]:[...s?[process.cwd()]:[],...(t||"").split(i)];if(s){const t=n||[".EXE",".CMD",".BAT",".COM"].join(i),r=t.split(i).flatMap(e=>[e,e.toLowerCase()]);return e.includes(".")&&""!==r[0]&&r.unshift(""),{pathEnv:o,pathExt:r,pathExtExe:t}}return{pathEnv:o,pathExt:[""]}},d=(e,t)=>{const r=/^".*"$/.test(e)?e.slice(1,-1):e;return(!r&&l.test(t)?t.slice(0,2):"")+n(r,t)},p=async(t,n={})=>{const{pathEnv:r,pathExt:i,pathExtExe:o}=c(t,n),s=[];for(const a of r){const r=d(a,t);for(const t of i){const i=r+t;if(await e(i,{pathExt:o,ignoreErrors:!0})){if(!n.all)return i;s.push(i)}}}if(n.all&&s.length)return s;if(n.nothrow)return null;throw u(t)};return LG=p,p.sync=(e,n={})=>{const{pathEnv:r,pathExt:i,pathExtExe:o}=c(e,n),s=[];for(const a of r){const r=d(a,e);for(const e of i){const i=r+e;if(t(i,{pathExt:o,ignoreErrors:!0})){if(!n.all)return i;s.push(i)}}}if(n.all&&s.length)return s;if(n.nothrow)return null;throw u(e)},LG}());var GG,HG,WG,qG={exports:{}},JG={exports:{}};function KG(){if(HG)return GG;return HG=1,GG=function(e){function t(e){let r,i,o,s=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),o=i-(r||i);n.diff=o,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";s++;const o=t.formatters[i];if("function"==typeof o){const t=e[s];r=o.call(n,t),e.splice(s,1),s--}return r}),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e,t){let n=0,r=0,i=-1,o=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||"*"===t[r]))"*"===t[r]?(i=r,o=n,r++):(n++,r++);else{if(-1===i)return!1;r=i+1,o++,n=o}for(;r<t.length&&"*"===t[r];)r++;return r===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const r of n)"-"===r[0]?t.skips.push(r.slice(1)):t.names.push(r)},t.enabled=function(e){for(const n of t.skips)if(r(e,n))return!1;for(const n of t.names)if(r(e,n))return!0;return!1},t.humanize=tB(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(n=>{t[n]=e[n]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}}var ZG,VG,YG,XG,eH,tH,nH={exports:{}};function rH(){if(XG)return YG;XG=1;const e=G,t=ce,n=VG?ZG:(VG=1,ZG=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return-1!==r&&(-1===i||r<i)}),{env:r}=process;let i;function o(t,{streamIsTTY:o,sniffFlags:s=!0}={}){const a=function(){if("FORCE_COLOR"in r)return"true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(Number.parseInt(r.FORCE_COLOR,10),3)}();void 0!==a&&(i=a);const l=s?i:a;if(0===l)return 0;if(s){if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2}if(t&&!o&&void 0===l)return 0;const u=l||0;if("dumb"===r.TERM)return u;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(e=>e in r)||"codeship"===r.CI_NAME?1:u;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("truecolor"===r.COLORTERM)return 3;if("TERM_PROGRAM"in r){const e=Number.parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:u}function s(e,t={}){return function(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}(o(e,{streamIsTTY:e&&e.isTTY,...t}))}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),YG={supportsColor:s,stdout:s({isTTY:t.isatty(1)}),stderr:s({isTTY:t.isatty(2)})}}function iH(){return eH||(eH=1,function(e,t){const n=ce,r=L;t.init=function(e){e.inspectOpts={};const n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]},t.log=function(...e){return process.stderr.write(r.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(n){const{namespace:r,useColors:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),o=` ${i};1m${r} `;n[0]=o+n[0].split("\n").join("\n"+o),n.push(i+"m+"+e.exports.humanize(this.diff)+"")}else n[0]=function(){if(t.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+r+" "+n[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=rH();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(qK){}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let r=process.env[t];return r=!!/^(yes|on|true|enabled)$/i.test(r)||!/^(no|off|false|disabled)$/i.test(r)&&("null"===r?null:Number(r)),e[n]=r,e},{}),e.exports=KG()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(nH,nH.exports)),nH.exports}function oH(){return tH||(tH=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?qG.exports=(WG||(WG=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))}),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(qK){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(qK){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(qK){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=KG()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(qK){return"[UnexpectedJSONParseError]: "+qK.message}}}(JG,JG.exports)),JG.exports):qG.exports=iH()),qG.exports}var sH,aH,lH,uH,cH,dH,pH,fH,hH,gH,AH={exports:{}},mH={exports:{}};function yH(){if(lH)return mH.exports;lH=1;var e=(aH||(aH=1,sH=function e(t,n){if(t&&n)return e(t)(n);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach(function(e){r[e]=t[e]}),r;function r(){for(var e=new Array(arguments.length),n=0;n<e.length;n++)e[n]=arguments[n];var r=t.apply(this,e),i=e[e.length-1];return"function"==typeof r&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}),sH);function t(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function n(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}return mH.exports=e(t),mH.exports.strict=e(n),t.proto=t(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return t(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return n(this)},configurable:!0})}),mH.exports}function bH(){if(cH)return uH;cH=1;var e=yH(),n=function(){},r=t.Bare?queueMicrotask:process.nextTick.bind(process),i=function(t,o,s){if("function"==typeof o)return i(t,null,o);o||(o={}),s=e(s||n);var a=t._writableState,l=t._readableState,u=o.readable||!1!==o.readable&&t.readable,c=o.writable||!1!==o.writable&&t.writable,d=!1,p=function(){t.writable||f()},f=function(){c=!1,u||s.call(t)},h=function(){u=!1,c||s.call(t)},g=function(e){s.call(t,e?new Error("exited with error code: "+e):null)},A=function(e){s.call(t,e)},m=function(){r(y)},y=function(){if(!d)return(!u||l&&l.ended&&!l.destroyed)&&(!c||a&&a.ended&&!a.destroyed)?void 0:s.call(t,new Error("premature close"))},b=function(){t.req.on("finish",f)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(t)?c&&!a&&(t.on("end",p),t.on("close",p)):(t.on("complete",f),t.on("abort",m),t.req?b():t.on("request",b)),function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length}(t)&&t.on("exit",g),t.on("end",h),t.on("finish",f),!1!==o.error&&t.on("error",A),t.on("close",m),function(){d=!0,t.removeListener("complete",f),t.removeListener("abort",m),t.removeListener("request",b),t.req&&t.req.removeListener("finish",f),t.removeListener("end",p),t.removeListener("close",p),t.removeListener("finish",f),t.removeListener("exit",g),t.removeListener("end",h),t.removeListener("error",A),t.removeListener("close",m)}};return uH=i}function vH(){if(pH)return dH;pH=1;var e,t=yH(),n=bH();try{e=require("fs")}catch(u){}var r=function(){},i="undefined"!=typeof process&&/^v?\.0/.test(process.version),o=function(e){return"function"==typeof e},s=function(s,a,l,u){u=t(u);var c=!1;s.on("close",function(){c=!0}),n(s,{readable:a,writable:l},function(e){if(e)return u(e);c=!0,u()});var d=!1;return function(t){if(!c&&!d)return d=!0,function(t){return!!i&&!!e&&(t instanceof(e.ReadStream||r)||t instanceof(e.WriteStream||r))&&o(t.close)}(s)?s.close(r):function(e){return e.setHeader&&o(e.abort)}(s)?s.abort():o(s.destroy)?s.destroy():void u(t||new Error("stream was destroyed"))}},a=function(e){e()},l=function(e,t){return e.pipe(t)};return dH=function(){var e,t=Array.prototype.slice.call(arguments),n=o(t[t.length-1]||r)&&t.pop()||r;if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new Error("pump requires two streams per minimum");var i=t.map(function(r,o){var l=o<t.length-1;return s(r,l,o>0,function(t){e||(e=t),t&&i.forEach(a),l||(i.forEach(a),n(e))})});return t.reduce(l)},dH}function EH(){if(gH)return AH.exports;gH=1;const{constants:e}=U,t=vH(),n=function(){if(hH)return fH;hH=1;const{PassThrough:e}=j;return fH=t=>{t={...t};const{array:n}=t;let{encoding:r}=t;const i="buffer"===r;let o=!1;n?o=!(r||i):r=r||"utf8",i&&(r=null);const s=new e({objectMode:o});r&&s.setEncoding(r);let a=0;const l=[];return s.on("data",e=>{l.push(e),o?a=l.length:a+=e.length}),s.getBufferedValue=()=>n?l:i?Buffer.concat(l,a):l.join(""),s.getBufferedLength=()=>a,s}}();class r extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}}async function i(i,o){if(!i)return Promise.reject(new Error("Expected a stream"));o={maxBuffer:1/0,...o};const{maxBuffer:s}=o;let a;return await new Promise((l,u)=>{const c=t=>{t&&a.getBufferedLength()<=e.MAX_LENGTH&&(t.bufferedData=a.getBufferedValue()),u(t)};a=t(i,n(o),e=>{e?c(e):l()}),a.on("data",()=>{a.getBufferedLength()>s&&c(new r)})}),a.getBufferedValue()}return AH.exports=i,AH.exports.default=i,AH.exports.buffer=(e,t)=>i(e,{...t,encoding:"buffer"}),AH.exports.array=(e,t)=>i(e,{...t,array:!0}),AH.exports.MaxBufferError=r,AH.exports}var IH,wH,CH,_H,BH,DH,SH,kH,xH={},QH={};function NH(){if(CH)return QH;CH=1;var e=J,t=L,n=j,r=n.Readable,i=n.Writable,o=n.PassThrough,s=function(){if(wH)return IH;function e(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}function t(e){e.pending+=1;var t=!1;return function(i){if(t)throw new Error("callback called twice");if(t=!0,e.error=e.error||i,e.pending-=1,e.waiting.length>0&&e.pending<e.max)n(e,e.waiting.shift());else if(0===e.pending){var o=e.listeners;e.listeners=[],o.forEach(r)}};function r(t){t(e.error)}}function n(e,n){n(t(e))}return wH=1,IH=e,e.prototype.go=function(e){this.pending<this.max?n(this,e):this.waiting.push(e)},e.prototype.wait=function(e){0===this.pending?e(this.error):this.listeners.push(e)},e.prototype.hold=function(){return t(this)},IH}(),a=z.EventEmitter;function l(e,t){t=t||{},a.call(this),this.fd=e,this.pend=new s,this.pend.max=1,this.refCount=0,this.autoClose=!!t.autoClose}function u(e,t){t=t||{},r.call(this,t),this.context=e,this.context.ref(),this.start=t.start||0,this.endOffset=t.end,this.pos=this.start,this.destroyed=!1}function c(e,t){t=t||{},i.call(this,t),this.context=e,this.context.ref(),this.start=t.start||0,this.endOffset=null==t.end?1/0:+t.end,this.bytesWritten=0,this.pos=this.start,this.destroyed=!1,this.on("finish",this.destroy.bind(this))}function d(e,t){a.call(this),t=t||{},this.refCount=0,this.buffer=e,this.maxChunkSize=t.maxChunkSize||Number.MAX_SAFE_INTEGER}return QH.createFromBuffer=function(e,t){return new d(e,t)},QH.createFromFd=function(e,t){return new l(e,t)},QH.BufferSlicer=d,QH.FdSlicer=l,t.inherits(l,a),l.prototype.read=function(t,n,r,i,o){var s=this;s.pend.go(function(a){e.read(s.fd,t,n,r,i,function(e,t,n){a(),o(e,t,n)})})},l.prototype.write=function(t,n,r,i,o){var s=this;s.pend.go(function(a){e.write(s.fd,t,n,r,i,function(e,t,n){a(),o(e,t,n)})})},l.prototype.createReadStream=function(e){return new u(this,e)},l.prototype.createWriteStream=function(e){return new c(this,e)},l.prototype.ref=function(){this.refCount+=1},l.prototype.unref=function(){var t=this;if(t.refCount-=1,!(t.refCount>0)){if(t.refCount<0)throw new Error("invalid unref");t.autoClose&&e.close(t.fd,function(e){e?t.emit("error",e):t.emit("close")})}},t.inherits(u,r),u.prototype._read=function(t){var n=this;if(!n.destroyed){var r=Math.min(n._readableState.highWaterMark,t);if(null!=n.endOffset&&(r=Math.min(r,n.endOffset-n.pos)),r<=0)return n.destroyed=!0,n.push(null),void n.context.unref();n.context.pend.go(function(t){if(n.destroyed)return t();var i=new Buffer(r);e.read(n.context.fd,i,0,r,n.pos,function(e,r){e?n.destroy(e):0===r?(n.destroyed=!0,n.push(null),n.context.unref()):(n.pos+=r,n.push(i.slice(0,r))),t()})})}},u.prototype.destroy=function(e){this.destroyed||(e=e||new Error("stream destroyed"),this.destroyed=!0,this.emit("error",e),this.context.unref())},t.inherits(c,i),c.prototype._write=function(t,n,r){var i=this;if(!i.destroyed){if(i.pos+t.length>i.endOffset){var o=new Error("maximum file length exceeded");return o.code="ETOOBIG",i.destroy(),void r(o)}i.context.pend.go(function(n){if(i.destroyed)return n();e.write(i.context.fd,t,0,t.length,i.pos,function(e,t){e?(i.destroy(),n(),r(e)):(i.bytesWritten+=t,i.pos+=t,i.emit("progress"),n(),r())})})}},c.prototype.destroy=function(){this.destroyed||(this.destroyed=!0,this.context.unref())},t.inherits(d,a),d.prototype.read=function(e,t,n,r,i){var o=r+n,s=o-this.buffer.length,a=s>0?s:n;this.buffer.copy(e,t,r,o),setImmediate(function(){i(null,a)})},d.prototype.write=function(e,t,n,r,i){e.copy(this.buffer,r,t,t+n),setImmediate(function(){i(null,n,e)})},d.prototype.createReadStream=function(e){var t=new o(e=e||{});t.destroyed=!1,t.start=e.start||0,t.endOffset=e.end,t.pos=t.endOffset||this.buffer.length;for(var n=this.buffer.slice(t.start,t.pos),r=0;;){var i=r+this.maxChunkSize;if(i>=n.length){r<n.length&&t.write(n.slice(r,n.length));break}t.write(n.slice(r,i)),r=i}return t.end(),t.destroy=function(){t.destroyed=!0},t},d.prototype.createWriteStream=function(e){var t=this,n=new i(e=e||{});return n.start=e.start||0,n.endOffset=null==e.end?this.buffer.length:+e.end,n.bytesWritten=0,n.pos=n.start,n.destroyed=!1,n._write=function(e,r,i){if(!n.destroyed){var o=n.pos+e.length;if(o>n.endOffset){var s=new Error("maximum file length exceeded");return s.code="ETOOBIG",n.destroyed=!0,void i(s)}e.copy(t.buffer,n.pos,0,e.length),n.bytesWritten+=e.length,n.pos=o,n.emit("progress"),i()}},n.destroy=function(){n.destroyed=!0},n},d.prototype.ref=function(){this.refCount+=1},d.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw new Error("invalid unref")},QH}function TH(){if(BH)return _H;BH=1;var e=U.Buffer,t=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];function n(t){if(e.isBuffer(t))return t;var n="function"==typeof e.alloc&&"function"==typeof e.from;if("number"==typeof t)return n?e.alloc(t):new e(t);if("string"==typeof t)return n?e.from(t):new e(t);throw new Error("input must be buffer, number, or string, received "+typeof t)}function r(r,i){r=n(r),e.isBuffer(i)&&(i=i.readUInt32BE(0));for(var o=-1^i,s=0;s<r.length;s++)o=t[255&(o^r[s])]^o>>>8;return-1^o}function i(){return e=r.apply(null,arguments),(t=n(4)).writeInt32BE(e,0),t;var e,t}return"undefined"!=typeof Int32Array&&(t=new Int32Array(t)),i.signed=function(){return r.apply(null,arguments)},i.unsigned=function(){return r.apply(null,arguments)>>>0},_H=i}var RH=function(){if(kH)return SH;kH=1;const e=oH()("extract-zip"),{createWriteStream:t,promises:n}=J,r=EH(),i=ae,{promisify:o}=L,s=j,a=function(){if(DH)return xH;DH=1;var e=J,t=ue,n=NH(),r=TH(),i=L,o=z.EventEmitter,s=j.Transform,a=j.PassThrough,l=j.Writable;function u(t,r,i){"function"==typeof r&&(i=r,r=null),null==r&&(r={}),null==r.autoClose&&(r.autoClose=!1),null==r.lazyEntries&&(r.lazyEntries=!1),null==r.decodeStrings&&(r.decodeStrings=!0),null==r.validateEntrySizes&&(r.validateEntrySizes=!0),null==r.strictFileNames&&(r.strictFileNames=!1),null==i&&(i=_),e.fstat(t,function(e,o){if(e)return i(e);c(n.createFromFd(t,{autoClose:!0}),o.size,r,i)})}function c(e,t,n,r){"function"==typeof n&&(r=n,n=null),null==n&&(n={}),null==n.autoClose&&(n.autoClose=!0),null==n.lazyEntries&&(n.lazyEntries=!1),null==n.decodeStrings&&(n.decodeStrings=!0);var i=!!n.decodeStrings;if(null==n.validateEntrySizes&&(n.validateEntrySizes=!0),null==n.strictFileNames&&(n.strictFileNames=!1),null==r&&(r=_),"number"!=typeof t)throw new Error("expected totalSize parameter to be a number");if(t>Number.MAX_SAFE_INTEGER)throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");e.ref();var o=Math.min(65557,t),s=E(o),a=t-s.length;m(e,s,0,o,a,function(l){if(l)return r(l);for(var u=o-22;u>=0;u-=1)if(101010256===s.readUInt32LE(u)){var c=s.slice(u),p=c.readUInt16LE(4);if(0!==p)return r(new Error("multi-disk zip files are not supported: found disk number: "+p));var f=c.readUInt16LE(10),h=c.readUInt32LE(16),g=c.readUInt16LE(20),A=c.length-22;if(g!==A)return r(new Error("invalid comment length. expected: "+A+". found: "+g));var y=i?w(c,22,c.length,!1):c.slice(22);if(65535!==f&&4294967295!==h)return r(null,new d(e,h,t,f,y,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames));var b=E(20),v=a+u-b.length;return void m(e,b,0,b.length,v,function(o){if(o)return r(o);if(117853008!==b.readUInt32LE(0))return r(new Error("invalid zip64 end of central directory locator signature"));var s=C(b,8),a=E(56);m(e,a,0,a.length,s,function(o){return o?r(o):101075792!==a.readUInt32LE(0)?r(new Error("invalid zip64 end of central directory record signature")):(f=C(a,32),h=C(a,48),r(null,new d(e,h,t,f,y,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames)))})})}r(new Error("end of central directory record signature not found"))})}function d(e,t,n,r,i,s,a,l,u,c){var d=this;o.call(d),d.reader=e,d.reader.on("error",function(e){f(d,e)}),d.reader.once("close",function(){d.emit("close")}),d.readEntryCursor=t,d.fileSize=n,d.entryCount=r,d.comment=i,d.entriesRead=0,d.autoClose=!!s,d.lazyEntries=!!a,d.decodeStrings=!!l,d.validateEntrySizes=!!u,d.strictFileNames=!!c,d.isOpen=!0,d.emittedError=!1,d.lazyEntries||d._readEntry()}function p(e,t){e.autoClose&&e.close(),f(e,t)}function f(e,t){e.emittedError||(e.emittedError=!0,e.emit("error",t))}function h(){}function g(e,t){return new Date(1980+(e>>9&127),(e>>5&15)-1,31&e,t>>11&31,t>>5&63,2*(31&t),0)}function A(e){return-1!==e.indexOf("\\")?"invalid characters in fileName: "+e:/^[a-zA-Z]:/.test(e)||/^\//.test(e)?"absolute path: "+e:-1!==e.split("/").indexOf("..")?"invalid relative path: "+e:null}function m(e,t,n,r,i,o){if(0===r)return setImmediate(function(){o(null,E(0))});e.read(t,n,r,i,function(e,t){return e?o(e):t<r?o(new Error("unexpected EOF")):void o()})}function y(e){s.call(this),this.actualByteCount=0,this.expectedByteCount=e}function b(){o.call(this),this.refCount=0}function v(e){a.call(this),this.context=e,this.context.ref(),this.unreffedYet=!1}xH.open=function(t,n,r){"function"==typeof n&&(r=n,n=null),null==n&&(n={}),null==n.autoClose&&(n.autoClose=!0),null==n.lazyEntries&&(n.lazyEntries=!1),null==n.decodeStrings&&(n.decodeStrings=!0),null==n.validateEntrySizes&&(n.validateEntrySizes=!0),null==n.strictFileNames&&(n.strictFileNames=!1),null==r&&(r=_),e.open(t,"r",function(t,i){if(t)return r(t);u(i,n,function(t,n){t&&e.close(i,_),r(t,n)})})},xH.fromFd=u,xH.fromBuffer=function(e,t,r){"function"==typeof t&&(r=t,t=null),null==t&&(t={}),t.autoClose=!1,null==t.lazyEntries&&(t.lazyEntries=!1),null==t.decodeStrings&&(t.decodeStrings=!0),null==t.validateEntrySizes&&(t.validateEntrySizes=!0),null==t.strictFileNames&&(t.strictFileNames=!1),c(n.createFromBuffer(e,{maxChunkSize:65536}),e.length,t,r)},xH.fromRandomAccessReader=c,xH.dosDateTimeToDate=g,xH.validateFileName=A,xH.ZipFile=d,xH.Entry=h,xH.RandomAccessReader=b,i.inherits(d,o),d.prototype.close=function(){this.isOpen&&(this.isOpen=!1,this.reader.unref())},d.prototype.readEntry=function(){if(!this.lazyEntries)throw new Error("readEntry() called without lazyEntries:true");this._readEntry()},d.prototype._readEntry=function(){var e=this;if(e.entryCount!==e.entriesRead){if(!e.emittedError){var t=E(46);m(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return p(e,n);if(!e.emittedError){var i=new h,o=t.readUInt32LE(0);if(33639248!==o)return p(e,new Error("invalid central directory file header signature: 0x"+o.toString(16)));if(i.versionMadeBy=t.readUInt16LE(4),i.versionNeededToExtract=t.readUInt16LE(6),i.generalPurposeBitFlag=t.readUInt16LE(8),i.compressionMethod=t.readUInt16LE(10),i.lastModFileTime=t.readUInt16LE(12),i.lastModFileDate=t.readUInt16LE(14),i.crc32=t.readUInt32LE(16),i.compressedSize=t.readUInt32LE(20),i.uncompressedSize=t.readUInt32LE(24),i.fileNameLength=t.readUInt16LE(28),i.extraFieldLength=t.readUInt16LE(30),i.fileCommentLength=t.readUInt16LE(32),i.internalFileAttributes=t.readUInt16LE(36),i.externalFileAttributes=t.readUInt32LE(38),i.relativeOffsetOfLocalHeader=t.readUInt32LE(42),64&i.generalPurposeBitFlag)return p(e,new Error("strong encryption is not supported"));e.readEntryCursor+=46,t=E(i.fileNameLength+i.extraFieldLength+i.fileCommentLength),m(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return p(e,n);if(!e.emittedError){var o=!!(2048&i.generalPurposeBitFlag);i.fileName=e.decodeStrings?w(t,0,i.fileNameLength,o):t.slice(0,i.fileNameLength);var s=i.fileNameLength+i.extraFieldLength,a=t.slice(i.fileNameLength,s);i.extraFields=[];for(var l=0;l<a.length-3;){var u=a.readUInt16LE(l+0),c=a.readUInt16LE(l+2),d=l+4,f=d+c;if(f>a.length)return p(e,new Error("extra field length exceeds extra field buffer size"));var h=E(c);a.copy(h,0,d,f),i.extraFields.push({id:u,data:h}),l=f}if(i.fileComment=e.decodeStrings?w(t,s,s+i.fileCommentLength,o):t.slice(s,s+i.fileCommentLength),i.comment=i.fileComment,e.readEntryCursor+=t.length,e.entriesRead+=1,4294967295===i.uncompressedSize||4294967295===i.compressedSize||4294967295===i.relativeOffsetOfLocalHeader){var g=null;for(l=0;l<i.extraFields.length;l++)if(1===(y=i.extraFields[l]).id){g=y.data;break}if(null==g)return p(e,new Error("expected zip64 extended information extra field"));var m=0;if(4294967295===i.uncompressedSize){if(m+8>g.length)return p(e,new Error("zip64 extended information extra field does not include uncompressed size"));i.uncompressedSize=C(g,m),m+=8}if(4294967295===i.compressedSize){if(m+8>g.length)return p(e,new Error("zip64 extended information extra field does not include compressed size"));i.compressedSize=C(g,m),m+=8}if(4294967295===i.relativeOffsetOfLocalHeader){if(m+8>g.length)return p(e,new Error("zip64 extended information extra field does not include relative header offset"));i.relativeOffsetOfLocalHeader=C(g,m),m+=8}}if(e.decodeStrings)for(l=0;l<i.extraFields.length;l++){var y;if(28789===(y=i.extraFields[l]).id){if(y.data.length<6)continue;if(1!==y.data.readUInt8(0))continue;var b=y.data.readUInt32LE(1);if(r.unsigned(t.slice(0,i.fileNameLength))!==b)continue;i.fileName=w(y.data,5,y.data.length,!0);break}}if(e.validateEntrySizes&&0===i.compressionMethod){var v=i.uncompressedSize;if(i.isEncrypted()&&(v+=12),i.compressedSize!==v){var I="compressed/uncompressed size mismatch for stored file: "+i.compressedSize+" != "+i.uncompressedSize;return p(e,new Error(I))}}if(e.decodeStrings){e.strictFileNames||(i.fileName=i.fileName.replace(/\\/g,"/"));var _=A(i.fileName,e.validateFileNameOptions);if(null!=_)return p(e,new Error(_))}e.emit("entry",i),e.lazyEntries||e._readEntry()}})}})}}else setImmediate(function(){e.autoClose&&e.close(),e.emittedError||e.emit("end")})},d.prototype.openReadStream=function(e,n,r){var i=this,o=0,s=e.compressedSize;if(null==r)r=n,n={};else{if(null!=n.decrypt){if(!e.isEncrypted())throw new Error("options.decrypt can only be specified for encrypted entries");if(!1!==n.decrypt)throw new Error("invalid options.decrypt value: "+n.decrypt);if(e.isCompressed()&&!1!==n.decompress)throw new Error("entry is encrypted and compressed, and options.decompress !== false")}if(null!=n.decompress){if(!e.isCompressed())throw new Error("options.decompress can only be specified for compressed entries");if(!1!==n.decompress&&!0!==n.decompress)throw new Error("invalid options.decompress value: "+n.decompress)}if(null!=n.start||null!=n.end){if(e.isCompressed()&&!1!==n.decompress)throw new Error("start/end range not allowed for compressed entry without options.decompress === false");if(e.isEncrypted()&&!1!==n.decrypt)throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false")}if(null!=n.start){if((o=n.start)<0)throw new Error("options.start < 0");if(o>e.compressedSize)throw new Error("options.start > entry.compressedSize")}if(null!=n.end){if((s=n.end)<0)throw new Error("options.end < 0");if(s>e.compressedSize)throw new Error("options.end > entry.compressedSize");if(s<o)throw new Error("options.end < options.start")}}if(!i.isOpen)return r(new Error("closed"));if(e.isEncrypted()&&!1!==n.decrypt)return r(new Error("entry is encrypted, and options.decrypt !== false"));i.reader.ref();var a=E(30);m(i.reader,a,0,a.length,e.relativeOffsetOfLocalHeader,function(l){try{if(l)return r(l);var u=a.readUInt32LE(0);if(67324752!==u)return r(new Error("invalid local file header signature: 0x"+u.toString(16)));var c,d=a.readUInt16LE(26),p=a.readUInt16LE(28),f=e.relativeOffsetOfLocalHeader+a.length+d+p;if(0===e.compressionMethod)c=!1;else{if(8!==e.compressionMethod)return r(new Error("unsupported compression method: "+e.compressionMethod));c=null==n.decompress||n.decompress}var h=f,g=h+e.compressedSize;if(0!==e.compressedSize&&g>i.fileSize)return r(new Error("file data overflows file bounds: "+h+" + "+e.compressedSize+" > "+i.fileSize));var A=i.reader.createReadStream({start:h+o,end:h+s}),m=A;if(c){var b=!1,v=t.createInflateRaw();A.on("error",function(e){setImmediate(function(){b||v.emit("error",e)})}),A.pipe(v),i.validateEntrySizes?(m=new y(e.uncompressedSize),v.on("error",function(e){setImmediate(function(){b||m.emit("error",e)})}),v.pipe(m)):m=v,m.destroy=function(){b=!0,v!==m&&v.unpipe(m),A.unpipe(v),A.destroy()}}r(null,m)}finally{i.reader.unref()}})},h.prototype.getLastModDate=function(){return g(this.lastModFileDate,this.lastModFileTime)},h.prototype.isEncrypted=function(){return!!(1&this.generalPurposeBitFlag)},h.prototype.isCompressed=function(){return 8===this.compressionMethod},i.inherits(y,s),y.prototype._transform=function(e,t,n){if(this.actualByteCount+=e.length,this.actualByteCount>this.expectedByteCount){var r="too many bytes in the stream. expected "+this.expectedByteCount+". got at least "+this.actualByteCount;return n(new Error(r))}n(null,e)},y.prototype._flush=function(e){if(this.actualByteCount<this.expectedByteCount){var t="not enough bytes in the stream. expected "+this.expectedByteCount+". got only "+this.actualByteCount;return e(new Error(t))}e()},i.inherits(b,o),b.prototype.ref=function(){this.refCount+=1},b.prototype.unref=function(){var e=this;if(e.refCount-=1,!(e.refCount>0)){if(e.refCount<0)throw new Error("invalid unref");e.close(function(t){if(t)return e.emit("error",t);e.emit("close")})}},b.prototype.createReadStream=function(e){var t=e.start,n=e.end;if(t===n){var r=new a;return setImmediate(function(){r.end()}),r}var i=this._readStreamForRange(t,n),o=!1,s=new v(this);i.on("error",function(e){setImmediate(function(){o||s.emit("error",e)})}),s.destroy=function(){i.unpipe(s),s.unref(),i.destroy()};var l=new y(n-t);return s.on("error",function(e){setImmediate(function(){o||l.emit("error",e)})}),l.destroy=function(){o=!0,s.unpipe(l),s.destroy()},i.pipe(s).pipe(l)},b.prototype._readStreamForRange=function(e,t){throw new Error("not implemented")},b.prototype.read=function(e,t,n,r,i){var o=this.createReadStream({start:r,end:r+n}),s=new l,a=0;s._write=function(n,r,i){n.copy(e,t+a,0,n.length),a+=n.length,i()},s.on("finish",i),o.on("error",function(e){i(e)}),o.pipe(s)},b.prototype.close=function(e){setImmediate(e)},i.inherits(v,a),v.prototype._flush=function(e){this.unref(),e()},v.prototype.unref=function(e){this.unreffedYet||(this.unreffedYet=!0,this.context.unref())};var E,I="\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ";function w(e,t,n,r){if(r)return e.toString("utf8",t,n);for(var i="",o=t;o<n;o++)i+=I[e[o]];return i}function C(e,t){var n=e.readUInt32LE(t);return 4294967296*e.readUInt32LE(t+4)+n}function _(e){if(e)throw e}return E="function"==typeof Buffer.allocUnsafe?function(e){return Buffer.allocUnsafe(e)}:function(e){return new Buffer(e)},xH}(),l=o(a.open),u=o(s.pipeline);class c{constructor(e,t){this.zipPath=e,this.opts=t}async extract(){return e("opening",this.zipPath,"with opts",this.opts),this.zipfile=await l(this.zipPath,{lazyEntries:!0}),this.canceled=!1,new Promise((t,r)=>{this.zipfile.on("error",e=>{this.canceled=!0,r(e)}),this.zipfile.readEntry(),this.zipfile.on("close",()=>{this.canceled||(e("zip extraction complete"),t())}),this.zipfile.on("entry",async t=>{if(this.canceled)return void e("skipping entry",t.fileName,{cancelled:this.canceled});if(e("zipfile entry",t.fileName),t.fileName.startsWith("__MACOSX/"))return void this.zipfile.readEntry();const o=i.dirname(i.join(this.opts.dir,t.fileName));try{await n.mkdir(o,{recursive:!0});const r=await n.realpath(o);if(i.relative(this.opts.dir,r).split(i.sep).includes(".."))throw new Error(`Out of bound path "${r}" found while processing file ${t.fileName}`);await this.extractEntry(t),e("finished processing",t.fileName),this.zipfile.readEntry()}catch(s){this.canceled=!0,this.zipfile.close(),r(s)}})})}async extractEntry(s){if(this.canceled)return void e("skipping entry extraction",s.fileName,{cancelled:this.canceled});this.opts.onEntry&&this.opts.onEntry(s,this.zipfile);const a=i.join(this.opts.dir,s.fileName),l=s.externalFileAttributes>>16&65535,c=40960==(61440&l);let d=16384==(61440&l);!d&&s.fileName.endsWith("/")&&(d=!0);const p=s.versionMadeBy>>8;d||(d=0===p&&16===s.externalFileAttributes),e("extracting entry",{filename:s.fileName,isDir:d,isSymlink:c});const f=511&this.getExtractedMode(l,d),h=d?a:i.dirname(a),g={recursive:!0};if(d&&(g.mode=f),e("mkdir",{dir:h,...g}),await n.mkdir(h,g),d)return;e("opening read stream",a);const A=await o(this.zipfile.openReadStream.bind(this.zipfile))(s);if(c){const t=await r(A);e("creating symlink",t,a),await n.symlink(t,a)}else await u(A,t(a,{mode:f}))}getExtractedMode(e,t){let n=e;return 0===n&&(t?(this.opts.defaultDirMode&&(n=parseInt(this.opts.defaultDirMode,10)),n||(n=493)):(this.opts.defaultFileMode&&(n=parseInt(this.opts.defaultFileMode,10)),n||(n=420))),n}}return SH=async function(t,r){if(e("creating target directory",r.dir),!i.isAbsolute(r.dir))throw new Error("Target directory is expected to be absolute");return await n.mkdir(r.dir,{recursive:!0}),r.dir=await n.realpath(r.dir),new c(t,r).extract()}}();const FH=e(RH);var MH,OH,$H,LH;(OH=MH||(MH={})).Clangd={id:"clangd",root:($H=["compile_commands.json","compile_flags.txt",".clangd","CMakeLists.txt","Makefile"],async e=>{const t=process.cwd();let n=v.dirname(e);for(;n.startsWith(t);){for(const t of $H){const e=v.join(n,t);try{return await N.access(e),n}catch{}}const e=v.dirname(n);if(e===n)break;n=e}return t}),extensions:[".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++"],async spawn(e){let t=null;try{t=await zG("clangd",{nothrow:!0})}catch{t=null}if(!t){ex.info("clangd not found, downloading from GitHub releases");try{await N.mkdir(xG.bin,{recursive:!0});const e=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!e.ok)return void ex.error("Failed to fetch clangd release info");const n=await e.json(),r=process.platform;let i="";if("darwin"===r)i="clangd-mac-";else if("linux"===r)i="clangd-linux-";else{if("win32"!==r)return void ex.error(`Platform ${r} is not supported by clangd auto-download`);i="clangd-windows-"}i+=n.tag_name+".zip";const o=n.assets.find(e=>e.name===i);if(!o)return void ex.error(`Could not find asset ${i} in latest clangd release`);const s=await fetch(o.browser_download_url);if(!s.ok)return void ex.error("Failed to download clangd");const a=v.join(xG.bin,"clangd.zip");await N.writeFile(a,Buffer.from(await s.arrayBuffer())),await FH(a,{dir:xG.bin}),await N.rm(a);const l=v.join(xG.bin,i.replace(".zip",""));t=v.join(l,"bin","clangd"+("win32"===r?".exe":""));try{await N.access(t)}catch{return void ex.error("Failed to extract clangd binary")}"win32"!==r&&await N.chmod(t,493),ex.info("Installed clangd",{bin:t})}catch(qK){return void ex.error("Failed to download/install clangd",qK)}}return{process:x(t,["--background-index","--clang-tidy"],{cwd:e})}}},OH.RustAnalyzer={id:"rust",root:async e=>{const t=process.cwd();let n,r=v.dirname(e);for(;r.startsWith(t);){for(const t of["Cargo.toml","Cargo.lock"]){const e=v.join(r,t);try{await N.access(e),n=r;break}catch{}}if(n)break;const e=v.dirname(r);if(e===r)break;r=e}if(!n)return;let i=n;for(;i.startsWith(t);){const e=v.join(i,"Cargo.toml");try{if((await N.readFile(e,"utf8")).includes("[workspace]"))return i}catch{}const n=v.dirname(i);if(n===i)break;if(i=n,!i.startsWith(t))break}return n},extensions:[".rs"],async spawn(e){let t=null;try{t=await zG("rust-analyzer",{nothrow:!0})}catch{t=null}if(t)return{process:x(t,{cwd:e})};ex.info("rust-analyzer not found in path, please install it via rustup")}},(e=>{let t=null;async function n(){return t||(t={servers:{clangd:MH.Clangd,rust:MH.RustAnalyzer},clients:[],broken:new Set},ex.info("LSP system initialized",{servers:Object.keys(t.servers).join(", ")}),t)}async function r(){return t||await n()}e.init=n,e.touchFile=async function(e,t){const n=await async function(e){const t=await r(),n=v.extname(e)||e,i=[];for(const r of Object.values(t.servers)){if(r.extensions.length&&!r.extensions.includes(n))continue;const o=await r.root(e);if(!o)continue;if(t.broken.has(o+r.id))continue;const s=t.clients.find(e=>e.root===o&&e.serverID===r.id);if(s)i.push(s);else try{const e=await r.spawn(o);if(!e){t.broken.add(o+r.id);continue}ex.info(`Spawned LSP server ${r.id} at ${o}`);const n=await kG.create({serverID:r.id,server:e,root:o});if(!n){t.broken.add(o+r.id),e.process.kill();continue}t.clients.push(n),i.push(n)}catch(qK){t.broken.add(o+r.id),ex.error(`Failed to spawn LSP server ${r.id}`,qK)}}return i}(e);await Promise.all(n.map(async n=>{await n.notify.open({path:e}),t&&await n.waitForDiagnostics({path:e})})).catch(t=>{ex.error("Failed to touch file in LSP",{error:t,file:e})})},e.diagnostics=async function(){const e=await r(),t={};for(const n of e.clients)for(const[e,r]of n.diagnostics.entries()){const n=t[e]||[];n.push(...r),t[e]=n}return t},(e.Diagnostic||(e.Diagnostic={})).pretty=function(e){return`${{1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[e.severity||1]} [${e.range.start.line+1}:${e.range.start.character+1}] ${e.message}`},e.shutdown=async function(){const e=await r();await Promise.all(e.clients.map(e=>e.shutdown())),e.clients=[],ex.info("All LSP clients shut down")}})(LH||(LH={}));const PH=2e3;async function jH(e){const t=se.extname(e).toLowerCase();if(".ts"===t)return"text";if(".svg"===t)return"svg";if([".png",".jpg",".jpeg",".gif",".webp",".bmp",".tiff",".ico"].includes(t))return"image";if([".mp3",".wav",".flac",".aac",".ogg",".m4a"].includes(t))return"audio";if([".mp4",".avi",".mkv",".mov",".wmv",".flv",".webm"].includes(t))return"video";if(".pdf"===t)return"pdf";return[".zip",".tar",".gz",".exe",".dll",".so",".class",".jar",".war",".7z",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".odt",".ods",".odp",".bin",".dat",".obj",".o",".a",".lib",".wasm",".pyc",".pyo"].includes(t)||await async function(e){try{const t=Buffer.alloc(512),n=await q.promises.open(e,"r");try{const{bytesRead:e}=await n.read(t,0,512,0);return t.subarray(0,e).includes(0)}finally{await n.close()}}catch(qK){return!1}}(e)?"binary":"text"}const UH=Mz({metadata:{name:"readFile",displayName:"Read File",description:"Reads and returns the content of a specified file. If the file is large, the content will be truncated. The tool's response will clearly indicate if truncation has occurred and will provide details on how to read more of the file using the 'offset' and 'limit' parameters. Handles text, images (PNG, JPG, GIF, WEBP, SVG, BMP), and PDF files. For text files, it can read specific line ranges.",category:"file",icon:"📖"},inputSchema:ug({absolutePath:mh().describe("The absolute path to the file to read (e.g., '/home/user/project/file.txt'). Relative paths are not supported. You must provide an absolute path."),offset:jh().min(0).optional().describe("Optional: For text files, the 0-based line number to start reading from. Requires 'limit' to be set. Use for paginating through large files."),limit:jh().min(1).optional().describe("Optional: For text files, maximum number of lines to read. Use with 'offset' to paginate through large files. If omitted, reads the entire file (if feasible, up to a default limit).")}),validateParams:({absolutePath:e})=>se.isAbsolute(e)?null:`File path must be absolute, but was relative: ${e}`,getDescription:({absolutePath:e,offset:t,limit:n})=>{const r=se.basename(e);return void 0!==t&&void 0!==n?`Reading ${r} (lines ${t+1}-${t+n})`:`Reading ${r}`},getLocations:({absolutePath:e})=>[{path:e,type:"read"}],execute:async({absolutePath:e,offset:t,limit:n},r)=>{kL.getState().setCurrentFile(e);try{if(!q.existsSync(e))return{success:!1,llmContent:`File not found: ${e}`,returnDisplay:"File not found."};const r=await q.promises.stat(e);if(r.isDirectory())return{success:!1,llmContent:`Path is a directory, not a file: ${e}`,returnDisplay:"Path is a directory."};if(r.size>20971520){const t=(r.size/1048576).toFixed(2);return{success:!1,llmContent:`File size exceeds the 20MB limit: ${e} (${t}MB)`,returnDisplay:`File too large (${t}MB).`}}const i=await jH(e),o=se.basename(e),s=se.extname(e);switch([".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++",".rs"].includes(s)&&LH.touchFile(e,!1).catch(()=>{}),i){case"binary":return{success:!1,llmContent:`Cannot display content of binary file: ${o}`,returnDisplay:`Skipped binary file: ${o}`};case"svg":if(r.size>1048576)return{success:!1,llmContent:`Cannot display content of SVG file larger than 1MB: ${o}`,returnDisplay:`Skipped large SVG file (>1MB): ${o}`};return{success:!0,summary:`Read SVG file: ${o}`,llmContent:await q.promises.readFile(e,"utf8"),returnDisplay:`Read SVG as text: ${o}`,locations:[{path:e,type:"read"}],metadata:{toolParams:{absolutePath:e,offset:t,limit:n}}};case"text":{const r=(await q.promises.readFile(e,"utf8")).split("\n"),i=r.length,s=t||0,a=void 0===n?2e3:n,l=Math.min(s+a,i),u=Math.min(s,i),c=r.slice(u,l);let d=!1;const p=c.map((e,t)=>{const n=(u+t+1).toString().padStart(5," ");return e.length>PH?(d=!0,`${n}| ${e.substring(0,PH)}... [truncated]`):`${n}| ${e}`}),f=l<i,h=f||d;let g="";if(f){g=`\nIMPORTANT: The file content has been truncated.\nStatus: Showing lines ${u+1}-${l} of ${i} total lines.\nAction: To read more of the file, you can use the 'offset' and 'limit' parameters in a subsequent 'read_file' call. For example, to read the next section of the file, use offset: ${t?t+(l-u):l}.\n\n--- FILE CONTENT (truncated) ---\n<file>\n${p.join("\n")}\n</file>`}else d?(g+="[File content partially truncated: some lines exceeded maximum length of 2000 characters.]\n",g+=`<file>\n${p.join("\n")}\n</file>`):g=`<file>\n${p.join("\n")}\n</file>`;const A=h?" (truncated)":"";return{success:!0,summary:`Read ${i} line text file: ${o}${A}`,llmContent:g,returnDisplay:`Read ${i} line text file: ${o}${A}`,locations:[{path:e,type:"read"}],metadata:{lineCount:i,isTruncated:h,startLine:u,endLine:l,toolParams:{absolutePath:e,offset:t,limit:n}}}}case"image":case"pdf":case"audio":case"video":{const s=(await q.promises.readFile(e)).toString("base64"),a=(e=>({".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".tiff":"image/tiff",".pdf":"application/pdf",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".avi":"video/x-msvideo"}[se.extname(e).toLowerCase()]||"application/octet-stream"))(e);return{success:!0,summary:`Read ${i} file: ${o}`,llmContent:`[${i.toUpperCase()} FILE: ${o}]\nMIME Type: ${a}\nFile Size: ${r.size} bytes\nBase64 Data: ${s.substring(0,100)}...(truncated)`,returnDisplay:`Read ${i} file: ${o}`,locations:[{path:e,type:"read"}],metadata:{fileType:i,mimeType:a,fileSize:r.size,base64Data:s,toolParams:{absolutePath:e,offset:t,limit:n}}}}default:return{success:!1,llmContent:`Unhandled file type: ${i}`,returnDisplay:`Skipped unhandled file type: ${o}`}}}catch(qK){const n=qK instanceof Error?qK.message:String(qK),r=se.basename(e);return{success:!1,llmContent:`Error reading file ${r}: ${n}`,returnDisplay:`Error reading file ${r}: ${n}`}}}}),zH=["**/node_modules/**","**/.git/**","**/.vscode/**","**/.idea/**","**/dist/**","**/build/**","**/coverage/**","**/__pycache__/**","**/*.pyc","**/*.pyo","**/*.bin","**/*.exe","**/*.dll","**/*.so","**/*.dylib","**/*.class","**/*.jar","**/*.war","**/*.zip","**/*.tar","**/*.gz","**/*.bz2","**/*.rar","**/*.7z","**/*.doc","**/*.docx","**/*.xls","**/*.xlsx","**/*.ppt","**/*.pptx","**/*.odt","**/*.ods","**/*.odp","**/*.DS_Store","**/.env"],GH=10485760;async function HH(e){try{const t=await _e.stat(e);if(t.size>GH)return{error:`File too large (${(t.size/1024/1024).toFixed(2)}MB > 10MB)`};if(await async function(e){try{const t=Buffer.alloc(512),n=await _e.open(e,"r");try{const{bytesRead:e}=await n.read(t,0,512,0);return t.subarray(0,e).includes(0)}finally{await n.close()}}catch(qK){return!1}}(e))return{error:"File appears to be binary"};const n=(await _e.readFile(e,"utf-8")).split("\n"),r=n.length,i=2e3,o=2e3;if(r<=i&&n.every(e=>e.length<=o)){return{content:n.map((e,t)=>`${(t+1).toString().padStart(5," ")}| ${e}`).join("\n"),isTruncated:!1,originalLineCount:r}}const s=n.slice(0,i).map((e,t)=>{const n=(t+1).toString().padStart(5," ");return e.length>o?`${n}| ${e.substring(0,o)}... [truncated]`:`${n}| ${e}`});return{content:s.join("\n"),isTruncated:!0,originalLineCount:r}}catch(qK){return{error:qK instanceof Error?qK.message:"Failed to read file"}}}function WH(e,t){if(t.includes("**")){const n=t.split("**");if(2===n.length){const t=n[0],r=n[1];if(void 0!==t&&void 0!==r){const n=t.replace(/\*/g,".*"),i=r.replace(/\*/g,".*");return new RegExp(`^${n}.*${i}$`).test(e)}}}return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}async function qH(e,t=[],n=10,r=0){if(r>n)return[];const i=[];try{const o=await _e.readdir(e,{withFileTypes:!0});for(const s of o){const o=se.join(e,s.name),a=o.replace(/\\/g,"/");if(!t.some(e=>WH(a,e)))if(s.isDirectory()){if(s.name.startsWith(".")&&"."!==s.name)continue;const e=await qH(o,t,n,r+1);i.push(...e)}else s.isFile()&&i.push(o)}}catch(qK){}return i}const JH=Mz({metadata:{name:"readManyFiles",displayName:"Read Many Files",description:"Reads content from multiple files specified by paths or glob patterns within the working directory. For text files, it concatenates their content into a single string. It is primarily designed for text-based files. However, it can also process image (e.g., .png, .jpg) and PDF (.pdf) files if their file names or extensions are explicitly included in the 'paths' argument. For these explicitly requested non-text files, their data is read and included in a format suitable for model consumption (e.g., base64 encoded).\n\nThis tool is useful when you need to understand or analyze a collection of files, such as:\n- Getting an overview of a codebase or parts of it (e.g., all TypeScript files in the 'src' directory).\n- Finding where specific functionality is implemented if the user asks broad questions about code.\n- Reviewing documentation files (e.g., all Markdown files in the 'docs' directory).\n- Gathering context from multiple configuration files.\n- When the user asks to \"read all files in X directory\" or \"show me the content of all Y files\".\n\nUse this tool when the user's query implies needing the content of several files simultaneously for context, analysis, or summarization. For text files, it uses default UTF-8 encoding and a '--- {filePath} ---' separator between file contents. The tool inserts a '--- End of content ---' after the last file. Ensure paths are relative to the working directory. Glob patterns like 'src/**/*.js' are supported. Avoid using for single files if a more specific single-file reading tool is available, unless the user specifically requests to process a list containing just one file via this tool. Other binary files (not explicitly requested as image/PDF) are generally skipped. Default excludes apply to common non-text files (except for explicitly requested images/PDFs) and large dependency directories unless 'useDefaultExcludes' is false.",category:"file",icon:"📁"},inputSchema:ug({paths:ag(mh().min(1)).min(1).describe("Required. An array of file paths or glob patterns relative to working directory. Examples: ['src/**/*.ts'], ['README.md', 'docs/']"),include:ag(mh().min(1)).optional().describe('Optional. Additional glob patterns to include. These are merged with `paths`. Example: ["*.test.ts"] to specifically add test files.'),exclude:ag(mh().min(1)).optional().describe('Optional. Glob patterns for files/directories to exclude. Added to default excludes if useDefaultExcludes is true. Example: ["**/*.log", "temp/"]'),recursive:Hh().optional().default(!0).describe("Optional. Whether to search recursively (primarily controlled by `**` in glob patterns). Defaults to true."),useDefaultExcludes:Hh().optional().default(!0).describe("Optional. Whether to apply a list of default exclusion patterns (e.g., node_modules, .git, binary files). Defaults to true."),fileFilteringOptions:ug({respect_git_ignore:Hh().optional().describe("Optional: Whether to respect .gitignore patterns when listing files. Only available in git repositories. Defaults to true."),respect_embedder_ignore:Hh().optional().describe("Optional: Whether to respect .embedderignore patterns when listing files. Defaults to true.")}).optional().describe("Whether to respect ignore patterns from .gitignore or .embedderignore")}),validateParams:e=>{if(!e.paths||0===e.paths.length)return"At least one path must be specified";for(const t of e.paths)if("string"!=typeof t||""===t.trim())return"All paths must be non-empty strings";return null},getDescription:e=>{const t=[...e.paths,...e.include||[]];return`Reading files: ${t.length<=3?t.join(", "):`${t.slice(0,3).join(", ")} and ${t.length-3} more`}`},getLocations:e=>e.paths.map(e=>({path:e,type:"read"})),execute:async(e,t)=>{const{paths:n,include:r=[],exclude:i=[],useDefaultExcludes:o=!0}=e,s=new Set,a=[],l=[],u=[],c=o?[...zH,...i]:[...i],d=[...n,...r];if(0===d.length)return{success:!1,llmContent:"No search paths or include patterns provided.",returnDisplay:"## Information\n\nNo search paths or include patterns were specified. Nothing to read or concatenate."};try{for(const e of d){const n=se.resolve(t.workingDirectory,e);try{const e=await _e.stat(n);if(e.isFile())s.add(n);else if(e.isDirectory()){(await qH(n,c)).forEach(e=>s.add(e))}}catch(qK){if(e.includes("*")){const n=t.workingDirectory,r=await qH(n,c);r.filter(t=>WH(se.relative(n,t).replace(/\\/g,"/"),e)).forEach(e=>s.add(e))}else a.push({path:e,reason:`Path not found: ${qK instanceof Error?qK.message:"Unknown error"}`})}}const n=Array.from(s).sort();for(const e of n){const n=se.relative(t.workingDirectory,e).replace(/\\/g,"/");if(c.some(e=>WH(n,e))){a.push({path:n,reason:"matched exclusion pattern"});continue}const r=await HH(e);if(r.error)a.push({path:n,reason:`Read error: ${r.error}`});else if(void 0!==r.content){const e="--- {filePath} ---".replace("{filePath}",n);let t="";r.isTruncated&&(t+="[WARNING: This file was truncated. To view the full content, use the 'read_file' tool on this specific file.]\n\n"),t+=`<file>\n${r.content}\n</file>`,u.push(`${e}\n\n${t}\n\n`),l.push(n)}}let r="";if(l.length>0){const e=l.length<=3?l.join(", "):`${l.slice(0,3).join(", ")} and ${l.length-3} more`;r=`Successfully read content from ${l.length} file${1!==l.length?"s":""}: ${e}`}else r=a.length>0?`No files could be read (${a.length} skipped)`:"No files found matching criteria";u.length>0&&u.push("\n--- End of content ---");return{success:!0,llmContent:u.length>0?u.join(""):"No files matching the criteria were found or all were skipped.",returnDisplay:r,summary:l.length>0?`Read ${l.length} file${1!==l.length?"s":""}`:"No files read",locations:l.map(e=>({path:e,type:"read"})),metadata:{fileCount:l.length,toolParams:{paths:e.paths,include:e.include,exclude:e.exclude,recursive:e.recursive,useDefaultExcludes:e.useDefaultExcludes,fileFilteringOptions:e.fileFilteringOptions}}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error during file search and reading: ${t}`,returnDisplay:`Error reading files: ${t}`}}}});class KH{diff(e,t,n={}){let r;"function"==typeof n?(r=n,n={}):"callback"in n&&(r=n.callback);const i=this.castInput(e,n),o=this.castInput(t,n),s=this.removeEmpty(this.tokenize(i,n)),a=this.removeEmpty(this.tokenize(o,n));return this.diffWithOptionsObj(s,a,n,r)}diffWithOptionsObj(e,t,n,r){var i;const o=e=>(e=this.postProcess(e,n),r?void setTimeout(function(){r(e)},0):e),s=t.length,a=e.length;let l=1,u=s+a;null!=n.maxEditLength&&(u=Math.min(u,n.maxEditLength));const c=null!==(i=n.timeout)&&void 0!==i?i:1/0,d=Date.now()+c,p=[{oldPos:-1,lastComponent:void 0}];let f=this.extractCommon(p[0],t,e,0,n);if(p[0].oldPos+1>=a&&f+1>=s)return o(this.buildValues(p[0].lastComponent,t,e));let h=-1/0,g=1/0;const A=()=>{for(let r=Math.max(h,-l);r<=Math.min(g,l);r+=2){let i;const l=p[r-1],u=p[r+1];l&&(p[r-1]=void 0);let c=!1;if(u){const e=u.oldPos-r;c=u&&0<=e&&e<s}const d=l&&l.oldPos+1<a;if(c||d){if(i=!d||c&&l.oldPos<u.oldPos?this.addToPath(u,!0,!1,0,n):this.addToPath(l,!1,!0,1,n),f=this.extractCommon(i,t,e,r,n),i.oldPos+1>=a&&f+1>=s)return o(this.buildValues(i.lastComponent,t,e))||!0;p[r]=i,i.oldPos+1>=a&&(g=Math.min(g,r-1)),f+1>=s&&(h=Math.max(h,r+1))}else p[r]=void 0}l++};if(r)!function e(){setTimeout(function(){if(l>u||Date.now()>d)return r(void 0);A()||e()},0)}();else for(;l<=u&&Date.now()<=d;){const e=A();if(e)return e}}addToPath(e,t,n,r,i){const o=e.lastComponent;return o&&!i.oneChangePerToken&&o.added===t&&o.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:o.count+1,added:t,removed:n,previousComponent:o.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:o}}}extractCommon(e,t,n,r,i){const o=t.length,s=n.length;let a=e.oldPos,l=a-r,u=0;for(;l+1<o&&a+1<s&&this.equals(n[a+1],t[l+1],i);)l++,a++,u++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!i.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=a,l}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){const t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join("")}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){const r=[];let i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();const o=r.length;let s=0,a=0,l=0;for(;s<o;s++){const e=r[s];if(e.removed)e.value=this.join(n.slice(l,l+e.count)),l+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(a,a+e.count);r=r.map(function(e,t){const r=n[l+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(a,a+e.count));a+=e.count,e.added||(l+=e.count)}}return r}}const ZH=new class extends KH{constructor(){super(...arguments),this.tokenize=XH}equals(e,t,n){return n.ignoreWhitespace?(n.newlineIsToken&&e.includes("\n")||(e=e.trim()),n.newlineIsToken&&t.includes("\n")||(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith("\n")&&(e=e.slice(0,-1)),t.endsWith("\n")&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function VH(e,t,n){return ZH.diff(e,t,n)}function YH(e,t,n){return n=function(e,t){if("function"==typeof e)t.callback=e;else if(e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t}(n,{ignoreWhitespace:!0}),ZH.diff(e,t,n)}function XH(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,"\n"));const n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let i=0;i<r.length;i++){const e=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=e:n.push(e)}return n}function eW(e,t,n,r,i,o,s){let a;a=s?"function"==typeof s?{callback:s}:s:{},void 0===a.context&&(a.context=4);const l=a.context;if(a.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(!a.callback)return u(VH(n,r,a));{const{callback:e}=a;VH(n,r,Object.assign(Object.assign({},a),{callback:t=>{const n=u(t);e(n)}}))}function u(n){if(!n)return;function r(e){return e.map(function(e){return" "+e})}n.push({value:"",lines:[]});const s=[];let a=0,u=0,c=[],d=1,p=1;for(let e=0;e<n.length;e++){const t=n[e],i=t.lines||iW(t.value);if(t.lines=i,t.added||t.removed){if(!a){const t=n[e-1];a=d,u=p,t&&(c=l>0?r(t.lines.slice(-l)):[],a-=c.length,u-=c.length)}for(const e of i)c.push((t.added?"+":"-")+e);t.added?p+=i.length:d+=i.length}else{if(a)if(i.length<=2*l&&e<n.length-2)for(const e of r(i))c.push(e);else{const e=Math.min(i.length,l);for(const n of r(i.slice(0,e)))c.push(n);const t={oldStart:a,oldLines:d-a+e,newStart:u,newLines:p-u+e,lines:c};s.push(t),a=0,u=0,c=[]}d+=i.length,p+=i.length}}for(const e of s)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith("\n")?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,"\"),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:o,hunks:s}}}function tW(e){if(Array.isArray(e))return e.map(tW).join("\n");const t=[];e.oldFileName==e.newFileName&&t.push("Index: "+e.oldFileName),t.push("==================================================================="),t.push("--- "+e.oldFileName+(void 0===e.oldHeader?"":"\t"+e.oldHeader)),t.push("+++ "+e.newFileName+(void 0===e.newHeader?"":"\t"+e.newHeader));for(let n=0;n<e.hunks.length;n++){const r=e.hunks[n];0===r.oldLines&&(r.oldStart-=1),0===r.newLines&&(r.newStart-=1),t.push("@@ -"+r.oldStart+","+r.oldLines+" +"+r.newStart+","+r.newLines+" @@");for(const e of r.lines)t.push(e)}return t.join("\n")+"\n"}function nW(e,t,n,r,i,o,s){if("function"==typeof s&&(s={callback:s}),!(null==s?void 0:s.callback)){const a=eW(e,t,n,r,i,o,s);if(!a)return;return tW(a)}{const{callback:a}=s;eW(e,t,n,r,i,o,Object.assign(Object.assign({},s),{callback:e=>{a(e?tW(e):void 0)}}))}}function rW(e,t,n,r,i,o){return nW(e,e,t,n,r,i,o)}function iW(e){const t=e.endsWith("\n"),n=e.split("\n").map(e=>e+"\n");return t?n.pop():n.push(n.pop().slice(0,-1)),n}const oW=new Set;function sW(e,t,n,r=!1,i=3){const o=function(e,t,n){return rW(ae.basename(e),t,n,"original","modified")}(e,t,n,r),s=o.split("\n"),a=[];let l=[],u=!1,c=-1;const d=/^@@ .* @@/,p=()=>{if(0!==l.length){if(l.length<=2*i)a.push(...l);else{a.push(...l.slice(0,i));const e=l.length-2*i;e>0&&a.push(` ... ${e} unchanged lines ...`),a.push(...l.slice(-i))}l=[]}};for(let f=0;f<s.length;f++){const e=s[f];if(e)if(e.startsWith("--- ")||e.startsWith("+++ ")||e.startsWith("Index: "))p(),a.push(e);else if(d.test(e))p(),a.push(e),u=!0;else if(u)if(e.startsWith("+")||e.startsWith("-"))p(),a.push(e),c=f;else if(e.startsWith(" ")){l.push(e);const t=s.findIndex((e,t)=>e&&t>f&&(e.startsWith("+")||e.startsWith("-")));(-1===t||t-f>2*i)&&-1!==c&&f-c>i&&(l=l.slice(0,i),p())}else e.startsWith("\\")&&a.push(e)}return p(),a.join("\n")}const aW=Mz({metadata:{name:"writeFile",displayName:"Write File",description:"Creates or overwrites a file with specified content. This tool handles safety checks internally.",category:"file",icon:"📝",requiresConfirmation:!0,requiresSequentialExecution:!0},inputSchema:ug({absolutePath:mh().describe("Absolute path where file should be written"),content:mh().describe("Content to write to the file"),createDirs:Hh().default(!0).describe("Create parent directories if needed"),encoding:_g(["utf8","utf16le","latin1"]).default("utf8").optional()}),validateParams:({absolutePath:e})=>ae.isAbsolute(e)?null:`Path must be absolute: ${e}`,getDescription:({absolutePath:e,content:t})=>{const n=ae.basename(e);return`Writing ${(new TextEncoder).encode(t).length} bytes to ${n}`},getLocations:({absolutePath:e})=>[{path:e,type:"write"}],isAllowlisted:()=>oW.has("writeFile"),addToAllowlist:(e,t)=>{"always"!==t&&"command"!==t||oW.add("writeFile")},shouldConfirm:async({absolutePath:e,content:t})=>{try{const n=await Be.access(e).then(()=>!0).catch(()=>!1);let r="",i=!n;if(n)try{r=await Be.readFile(e,"utf-8")}catch{r=""}const o=sW(e,r,t,i);return{type:"edit",title:n?"Overwrite File":"Create File",description:n?`Replace contents of: ${ae.basename(e)}`:`Create new file: ${ae.basename(e)}`,affectedPaths:[e],isDestructive:n,fileName:ae.basename(e),fileDiff:o,originalContent:r,newContent:t}}catch(qK){return{type:"edit",title:"Write File",description:`Write to: ${ae.basename(e)}`,affectedPaths:[e],isDestructive:!1,fileName:ae.basename(e),fileDiff:sW(e,"",t,!0),originalContent:"",newContent:t}}},execute:async({absolutePath:e,content:t,createDirs:n,encoding:r="utf8"},i)=>{kL.getState().setCurrentFile(e);try{const a=await Be.access(e).then(()=>!0).catch(()=>!1);let l="";const u=!a;if(a)try{l=await Be.readFile(e,"utf-8")}catch{l=""}if(i.snapshotService&&!i.snapshotService.isFileTracked(e)){const t=ae.relative(process.cwd(),e);if(a)ex.info("writeFile: Registering existing file and capturing before state",{file:t}),i.snapshotService.registerFile(e),await i.snapshotService.track();else{ex.info("writeFile: Registering new file (no before state)",{file:t}),i.snapshotService.registerFile(e);const n=i.snapshotService.getTrackedFiles();ex.info("writeFile: After registration, tracked files",{count:n.length,files:n})}}n&&await Be.mkdir(ae.dirname(e),{recursive:!0}),await Be.writeFile(e,t,{encoding:r});const c=await Be.stat(e),d=sW(e,l,t,u),p=ae.relative(process.cwd(),e),f=p.startsWith(".")?p:`./${p}`;let h=u?`Successfully created new file: ${f} (${c.size} bytes).`:`Successfully updated file: ${f} (${c.size} bytes).`;const g=ae.extname(e);if([".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++",".rs"].includes(g))try{await LH.touchFile(e,!0);const t=await LH.diagnostics(),n=(t[e]||[]).filter(e=>1===e.severity);if(n.length>0){h+=`\n\nThis file has compilation errors that need to be fixed:\n<file_diagnostics>\n${n.map(LH.Diagnostic.pretty).join("\n")}\n</file_diagnostics>`}}catch(s){ex.warn("LSP diagnostics failed",s)}return{success:!0,summary:`Wrote ${c.size} bytes to ${ae.basename(e)}`,llmContent:h,returnDisplay:`✅ File ${u?"created":"updated"}: ${ae.basename(e)} (${c.size} bytes)`,locations:[{path:e,type:"write"}],metadata:{size:c.size,filename:ae.basename(e),encoding:r},diffData:{fileName:ae.basename(e),content:d,language:(o=e,{".js":"javascript",".jsx":"javascript",".ts":"typescript",".tsx":"typescript",".py":"python",".java":"java",".cpp":"cpp",".c":"c",".h":"c",".cs":"csharp",".php":"php",".rb":"ruby",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".scala":"scala",".sh":"bash",".ps1":"powershell",".html":"html",".css":"css",".json":"json",".xml":"xml",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sql":"sql"}[ae.extname(o).toLowerCase()]||"text"),isNewFile:u}}}catch(qK){const n=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error writing file ${ae.basename(e)}: ${n}`,returnDisplay:`Error writing file: ${n}`}}var o}});function lW(e,t){if(""===e||""===t)return Math.max(e.length,t.length);const n=Array.from({length:e.length+1},(e,n)=>Array.from({length:t.length+1},(e,t)=>0===n?t:0===t?n:0));for(let i=1;i<=e.length;i++)for(let r=1;r<=t.length;r++){const o=e[i-1]===t[r-1]?0:1,s=n[i-1],a=n[i];if(!s||!a)continue;const l=a[r-1],u=s[r-1];if(void 0!==l&&void 0!==u){const e=s[r];void 0!==e&&(a[r]=Math.min(e+1,l+1,u+o))}}const r=n[e.length];return r?r[t.length]??0:0}const uW=function*(e,t){yield t},cW=function*(e,t){const n=e.split("\n"),r=t.split("\n");""===r[r.length-1]&&r.pop();const i=[];for(let o=0;o<=n.length-r.length;o++){let t=!0;for(let e=0;e<r.length;e++){const i=n[o+e],s=r[e];if(!i||!s)break;if(i.trim()!==s.trim()){t=!1;break}}if(t){let t=0;for(let e=0;e<o;e++){const r=n[e];r&&(t+=r.length+1)}let s=t;for(let e=0;e<r.length;e++){const t=n[o+e];t&&(s+=t.length,e<r.length-1&&(s+=1))}i.push(e.substring(t,s))}}1===i.length&&void 0!==i[0]&&(yield i[0])},dW=function*(e,t){const n=e.split("\n"),r=t.split("\n");if(r.length<3)return;""===r[r.length-1]&&r.pop();const i=r[0]?.trim()??"",o=r[r.length-1]?.trim()??"",s=r.length,a=[];for(let c=0;c<n.length;c++){const e=n[c];if(e&&e.trim()===i)for(let t=c+2;t<n.length;t++){const e=n[t];if(e&&e.trim()===o){a.push({startLine:c,endLine:t});break}}}if(0===a.length)return;if(1===a.length){const t=a[0];if(!t)return;const{startLine:i,endLine:o}=t,l=o-i+1;let u=0,c=Math.min(s-2,l-2);if(c>0)for(let e=1;e<s-1&&e<l-1;e++){const t=n[i+e]?.trim(),o=r[e]?.trim();if(!t||!o)break;const s=Math.max(t.length,o.length);if(0===s)continue;if(u+=(1-lW(t,o)/s)/c,u>=0)break}else u=1;if(u>=0){let t=0;for(let e=0;e<i;e++){const r=n[e];r&&(t+=r.length+1)}let r=t;for(let e=i;e<=o;e++){const t=n[e];t&&(r+=t.length,e<o&&(r+=1))}yield e.substring(t,r)}return}let l=null,u=-1;for(const c of a){const{startLine:e,endLine:t}=c,i=t-e+1;let o=0,a=Math.min(s-2,i-2);if(a>0){for(let t=1;t<s-1&&t<i-1;t++){const i=n[e+t]?.trim(),s=r[t]?.trim();if(!i||!s)break;const a=Math.max(i.length,s.length);if(0===a)continue;o+=1-lW(i,s)/a}o/=a}else o=1;o>u&&(u=o,l=c)}if(u>=.3&&l){const{startLine:t,endLine:r}=l;let i=0;for(let e=0;e<t;e++){const t=n[e];t&&(i+=t.length+1)}let o=i;for(let e=t;e<=r;e++){const t=n[e];t&&(o+=t.length,e<r&&(o+=1))}yield e.substring(i,o)}},pW=function*(e,t){const n=e=>e.replace(/\s+/g," ").trim(),r=n(t),i=[],o=e.split("\n");for(let l=0;l<o.length;l++){const e=o[l];if(e)if(n(e)===r)i.push(e);else{if(n(e).includes(r)){const n=t.trim().split(/\s+/);if(n.length>0){const t=n.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s+");try{const n=new RegExp(t),r=e.match(n);r&&r[0]&&i.push(r[0])}catch(a){}}}}}const s=t.split("\n");if(s.length>1)for(let l=0;l<=o.length-s.length;l++){const e=o.slice(l,l+s.length);n(e.join("\n"))===r&&i.push(e.join("\n"))}1===i.length&&void 0!==i[0]&&(yield i[0])},fW=function*(e,t){const n=e=>{const t=e.split("\n"),n=t.filter(e=>e.trim().length>0);if(0===n.length)return e;const r=Math.min(...n.map(e=>{if(!e)return 0;const t=e.match(/^(\s*)/);return t&&t[1]?t[1].length:0}));return t.map(e=>0===e.trim().length?e:e.slice(r)).join("\n")},r=n(t),i=e.split("\n"),o=t.split("\n"),s=[];for(let a=0;a<=i.length-o.length;a++){const e=i.slice(a,a+o.length).join("\n");n(e)===r&&s.push(e)}1===s.length&&void 0!==s[0]&&(yield s[0])},hW=function*(e,t){const n=e=>e.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g,(e,t)=>{switch(t){case"n":case"\n":return"\n";case"t":return"\t";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case"$":return"$";default:return e}}),r=n(t),i=new Set;let o=0;for(;;){const t=e.indexOf(r,o);if(-1===t)break;i.add(t),o=t+1}const s=e.split("\n"),a=r.split("\n");for(let l=0;l<=s.length-a.length;l++){if(n(s.slice(l,l+a.length).join("\n"))===r){let e=0;for(let t=0;t<l;t++){const n=s[t];void 0!==n&&(e+=n.length+1)}i.add(e)}}if(1===i.size){void 0!==Array.from(i)[0]&&(yield r)}},gW=function*(e,t){let n=0;for(;;){const r=e.indexOf(t,n);if(-1===r)break;yield t,n=r+t.length}},AW=function*(e,t){const n=t.trim();if(n===t)return;const r=new Set;let i=0;for(;;){const t=e.indexOf(n,i);if(-1===t)break;r.add(t),i=t+1}const o=e.split("\n"),s=t.split("\n");for(let a=0;a<=o.length-s.length;a++){if(o.slice(a,a+s.length).join("\n").trim()===n){let e=0;for(let t=0;t<a;t++){const n=o[t];void 0!==n&&(e+=n.length+1)}r.add(e)}}1===r.size&&(yield n)},mW=function*(e,t){const n=t.split("\n");if(n.length<3)return;""===n[n.length-1]&&n.pop();const r=e.split("\n"),i=n[0]?.trim()??"",o=n[n.length-1]?.trim()??"",s=[];for(let a=0;a<r.length;a++){const e=r[a];if(e&&e.trim()===i)for(let t=a+2;t<r.length;t++){const e=r[t];if(!e||e.trim()!==o)continue;const i=r.slice(a,t+1),l=i.join("\n");if(i.length===n.length){let e=0,t=0;for(let r=1;r<i.length-1;r++){const o=i[r]?.trim()??"",s=n[r]?.trim()??"";(o.length>0||s.length>0)&&(t++,o===s&&e++)}if(0===t||e/t>=.5){s.push(l);break}}break}}1===s.length&&void 0!==s[0]&&(yield s[0])};function yW(e,t,n,r=!1){if(t===n)return{success:!1,error:"oldString and newString must be different"};const i=[{name:"SimpleReplacer",replacer:uW},{name:"LineTrimmedReplacer",replacer:cW},{name:"BlockAnchorReplacer",replacer:dW},{name:"WhitespaceNormalizedReplacer",replacer:pW},{name:"IndentationFlexibleReplacer",replacer:fW},{name:"EscapeNormalizedReplacer",replacer:hW},{name:"TrimmedBoundaryReplacer",replacer:AW},{name:"ContextAwareReplacer",replacer:mW},{name:"MultiOccurrenceReplacer",replacer:gW}];let o=!0;for(const{name:s,replacer:a}of i)for(const i of a(e,t)){const t=e.indexOf(i);if(-1===t)continue;if(o=!1,r)return{success:!0,content:e.replaceAll(i,n),strategy:s};if(t===e.lastIndexOf(i))return{success:!0,content:e.substring(0,t)+n+e.substring(t+i.length),strategy:s}}return o?{success:!1,error:"oldString not found in content"}:{success:!1,error:"oldString found multiple times and requires more code context to uniquely identify the intended match"}}const bW=new Set;const vW=Mz({metadata:{name:"editFile",displayName:"Edit File",description:"Edit a file by replacing specific content with new content. This tool ONLY works on files that already exist. To create a new file or completely overwrite a file, use the writeFile tool instead. This tool handles safety checks internally.",category:"file",icon:"✏️",requiresConfirmation:!0,requiresSequentialExecution:!0},inputSchema:ug({absolutePath:mh().describe("Absolute path to the file to edit"),oldContent:mh().describe("The exact text to replace"),newContent:mh().describe("The new text to insert"),replaceAll:Hh().default(!1).describe("Replace all occurrences (default: replace first occurrence only)")}),validateParams:({absolutePath:e})=>ae.isAbsolute(e)?null:`Path must be absolute: ${e}`,getDescription:({absolutePath:e,oldContent:t,newContent:n})=>`Editing ${ae.basename(e)} (${t.split("\n").length}→${n.split("\n").length} lines)`,getLocations:({absolutePath:e})=>[{path:e,type:"write"}],isAllowlisted:()=>bW.has("editFile"),addToAllowlist:(e,t)=>{"always"!==t&&"command"!==t||bW.add("editFile")},shouldConfirm:async({absolutePath:e,oldContent:t,newContent:n,replaceAll:r})=>{const i=ae.basename(e),o=n.length-t.length,s=o>0?`+${o} characters`:o<0?`${o} characters`:"same length",a=await import("./index-zVjptbpZ.js");let l="";try{l=await Be.readFile(e,"utf8")}catch(qK){l=""}const u=yW(l,t,n,r),c=u.success?u.content:l,d=a.createPatch(i,l,c,"Current","Proposed");return{type:"edit",title:"Edit File",description:u.success?`This will modify ${i} (${s}) using ${u.strategy}`:`This will modify ${i} (${s})`,affectedPaths:[e],isDestructive:!1,fileName:i,fileDiff:d,originalContent:l,newContent:c}},execute:async({absolutePath:e,oldContent:t,newContent:n,replaceAll:r},i)=>{kL.getState().setCurrentFile(e);try{const a=ae.relative(process.cwd(),e);ex.info("editFile: Attempting edit",{file:a,oldContentLength:t.length,newContentLength:n.length,replaceAll:r||!1}),await Be.access(e),i.snapshotService&&!i.snapshotService.isFileTracked(e)?(ex.info("editFile: Registering file and capturing before state",{file:a}),i.snapshotService.registerFile(e),await i.snapshotService.track()):i.snapshotService&&ex.info("editFile: File already tracked, skipping before state capture",{file:a});const l=await Be.readFile(e,"utf8"),u=yW(l,t,n,r);if(!u.success){const n=ae.relative(process.cwd(),e),r=t.substring(0,100),i=t.length>100?`... (${t.length} chars total)`:"",o=l.substring(0,200),s=l.length>200?`... (${l.length} chars total)`:"",a=t.includes("\r"),c=l.includes("\r"),d=a!==c,p=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),f=l.replace(/\r\n/g,"\n").replace(/\r/g,"\n").includes(p);ex.error("editFile: Fuzzy matching failed to find content",{file:n,absolutePath:e,fuzzyMatchError:u.error,oldContentLength:t.length,currentContentLength:l.length,oldContentLines:t.split("\n").length,currentContentLines:l.split("\n").length,oldContentPreview:r+i,currentContentPreview:o+s,oldContentHasLeadingWhitespace:/^\s/.test(t),oldContentHasTrailingWhitespace:/\s$/.test(t),oldContentHasTabs:t.includes("\t"),oldContentHasCarriageReturn:a,currentContentHasTabs:l.includes("\t"),currentContentHasCarriageReturn:c,hasLineEndingMismatch:d,wouldMatchIfNormalized:f,oldContentFirstChar:t.length>0?`'${t[0]}' (0x${t.charCodeAt(0).toString(16)})`:"empty",oldContentLastChar:t.length>0?`'${t[t.length-1]}' (0x${t.charCodeAt(t.length-1).toString(16)})`:"empty",currentContentFirstChar:l.length>0?`'${l[0]}' (0x${l.charCodeAt(0).toString(16)})`:"empty",currentContentLastChar:l.length>0?`'${l[l.length-1]}' (0x${l.charCodeAt(l.length-1).toString(16)})`:"empty"});let h="";return d&&f?c&&!a?h=" The file uses Windows line endings (\\r\\n) but you provided Unix line endings (\\n). Please use \\r\\n in your oldContent parameter.":!c&&a&&(h=" The file uses Unix line endings (\\n) but you provided Windows line endings (\\r\\n). Please use \\n in your oldContent parameter."):h=f?" There appears to be a line ending or whitespace mismatch. The fuzzy matcher tried multiple strategies but couldn't find a match.":" The content may have been modified, or the oldContent doesn't exist in the file. Try reading the file first to get the current content.",{success:!1,llmContent:`Old content not found in file: ${e}. ${u.error}.${h}`,returnDisplay:"Content to replace was not found"}}const c=u.content,d=r?l.split(t).length-1:l!==c?1:0;await Be.writeFile(e,c,"utf8");const p=await Be.stat(e),f=ae.relative(process.cwd(),e),h=f.startsWith(".")?f:`./${f}`,g=(await import("./index-zVjptbpZ.js")).createPatch(ae.basename(e),l,c,"Before","After");ex.info("editFile: Successfully edited file",{file:f,replaceCount:d,replaceAll:r||!1,fuzzyStrategy:u.strategy,oldContentLength:t.length,newContentLength:n.length,fileSizeAfter:p.size});let A=`Successfully edited ${h}. Made ${d} replacement${d>1?"s":""}.`;const m=ae.extname(e);if([".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++",".rs"].includes(m))try{await LH.touchFile(e,!0);const t=await LH.diagnostics(),n=(t[e]||[]).filter(e=>1===e.severity);if(n.length>0){A+=`\n\nThis file has compilation errors that need to be fixed:\n<file_diagnostics>\n${n.map(LH.Diagnostic.pretty).join("\n")}\n</file_diagnostics>`}}catch(s){ex.warn("LSP diagnostics failed",s)}return{success:!0,summary:`Edited ${h} (${d} replacement${d>1?"s":""})`,llmContent:A,returnDisplay:`✅ File edited: ${h} (${d} change${d>1?"s":""})`,locations:[{path:e,type:"write"}],metadata:{filename:ae.basename(e),replaceCount:d,replaceAll:r,fileSize:p.size},diffData:{fileName:ae.basename(e),content:g,language:(o=e,{".js":"javascript",".jsx":"javascript",".ts":"typescript",".tsx":"typescript",".py":"python",".java":"java",".c":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".go":"go",".rs":"rust",".php":"php",".rb":"ruby",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"bash",".json":"json",".yaml":"yaml",".yml":"yaml",".xml":"xml",".html":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".md":"markdown",".sql":"sql",".toml":"toml",".ini":"ini",".cfg":"ini",".conf":"ini"}[ae.extname(o).toLowerCase()]||"text"),isNewFile:!1}}}catch(qK){const n=qK instanceof Error?qK.message:String(qK),r=ae.basename(e),i=ae.relative(process.cwd(),e);return"ENOENT"===qK.code?(ex.error("editFile: File not found",{file:i,absolutePath:e,errorCode:"ENOENT"}),{success:!1,llmContent:`File not found: ${e}`,returnDisplay:`File not found: ${r}`}):(ex.error("editFile: Error during edit",{file:i,absolutePath:e,errorMessage:n,errorCode:qK.code,errorStack:qK instanceof Error?qK.stack:void 0}),{success:!1,llmContent:`Error editing file ${r}: ${n}`,returnDisplay:`Error editing file: ${n}`})}var o}});function EW(e){return new RegExp("^"+e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$")}const IW=Mz({metadata:{name:"listDirectory",displayName:"List Directory",description:"List files and directories at a given path",category:"file",icon:"📁"},inputSchema:ug({path:mh().describe("Absolute path of the directory to list"),ignore:ag(mh()).optional().describe("Glob patterns to ignore"),respectGitIgnore:Hh().optional(),respectEmbedderIgnore:Hh().optional()}),validateParams:({path:e})=>ae.isAbsolute(e)?null:`Path must be absolute: ${e}`,getDescription:({path:e,ignore:t})=>`Listing contents of ${ae.basename(e)}${t&&t.length>0?` (ignoring ${t.length} patterns)`:""}`,getLocations:({path:e})=>[{path:e,type:"read"}],execute:async({path:e,ignore:t,respectGitIgnore:n,respectEmbedderIgnore:r},i)=>{if(!J.existsSync(e)||!J.statSync(e).isDirectory())return{success:!1,llmContent:`Directory not found or not a directory: ${e}`,returnDisplay:"Directory inaccessible."};const o=J.readdirSync(e),s=[];for(const u of o){if(t?.some(e=>EW(e).test(u)))continue;const n=ae.join(e,u),r=J.statSync(n);s.push({name:u,path:n,isDirectory:r.isDirectory(),size:r.isDirectory()?0:r.size,modifiedTime:r.mtime})}s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name));const a=s.map(e=>`${e.isDirectory?"[DIR] ":""}${e.name}`).join("\n"),l=[];return{success:!0,summary:`Listed ${s.length} item(s) in ${ae.basename(e)}`,llmContent:`Directory listing for ${e}:\n${a}${l.length?"\n\n("+l.join(", ")+")":""}`,returnDisplay:`Listed ${s.length} item(s)${l.length?" ("+l.join(", ")+")":""}.`,locations:[{path:e,type:"read"}],metadata:{entryCount:s.length,gitIgnoredCount:0,embedderIgnoredCount:0,toolParams:{path:e,ignore:t,respectGitIgnore:n,respectEmbedderIgnore:r}}}}});function wW(e){return new Promise(t=>{const n="win32"===process.platform?"where":"command",r="win32"===process.platform?[e]:["-v",e];try{const e=Se(n,r,{stdio:"ignore",shell:"win32"===process.platform});e.on("close",e=>t(0===e)),e.on("error",()=>t(!1))}catch{t(!1)}})}function CW(e,t){const n=[];if(!e)return n;const r=e.split(W);for(const i of r){if(!i.trim())continue;const e=i.indexOf(":");if(-1===e)continue;const r=i.indexOf(":",e+1);if(-1===r)continue;const o=i.substring(0,e),s=i.substring(e+1,r),a=i.substring(r+1),l=parseInt(s,10);if(!isNaN(l)){const e=ae.resolve(t,o),r=ae.relative(t,e);n.push({filePath:r||ae.basename(e),lineNumber:l,line:a})}}return n}async function _W(e){const{pattern:t,path:n,includeGlob:r}=e;let i="none";try{if(function(e){try{const t=ae.join(e,".git");return J.existsSync(t)}catch{return!1}}(n)&&await wW("git")){i="git grep";const e=["grep","--untracked","-n","-E","--ignore-case",t];r&&e.push("--",r);try{return CW(await new Promise((t,r)=>{const i=Se("git",e,{cwd:n,windowsHide:!0}),o=[],s=[];i.stdout.on("data",e=>o.push(e)),i.stderr.on("data",e=>s.push(e)),i.on("error",e=>r(new Error(`Failed to start git grep: ${e.message}`))),i.on("close",e=>{const n=Buffer.concat(o).toString("utf8"),i=Buffer.concat(s).toString("utf8");0===e?t(n):1===e?t(""):r(new Error(`git grep exited with code ${e}: ${i}`))})}),n)}catch(o){ex.debug(`Grep: git grep failed: ${o}. Falling back...`)}}if(await wW("grep")){i="system grep";const e=["-r","-n","-H","-E"];[".git","node_modules","bower_components"].forEach(t=>e.push(`--exclude-dir=${t}`)),r&&e.push(`--include=${r}`),e.push(t),e.push(".");try{return CW(await new Promise((t,r)=>{const i=Se("grep",e,{cwd:n,windowsHide:!0}),o=[],s=[],a=e=>o.push(e),l=e=>{const t=e.toString();t.includes("Permission denied")||/grep:.*: Is a directory/i.test(t)||s.push(e)},u=e=>{d(),r(new Error(`Failed to start system grep: ${e.message}`))},c=e=>{const n=Buffer.concat(o).toString("utf8"),i=Buffer.concat(s).toString("utf8").trim();d(),0===e?t(n):1===e?t(""):i?r(new Error(`System grep exited with code ${e}: ${i}`)):t("")},d=()=>{i.stdout.removeListener("data",a),i.stderr.removeListener("data",l),i.removeListener("error",u),i.removeListener("close",c),i.connected&&i.disconnect()};i.stdout.on("data",a),i.stderr.on("data",l),i.on("error",u),i.on("close",c)}),n)}catch(s){ex.debug(`Grep: System grep failed: ${s}. Falling back...`)}}ex.debug("Grep: Falling back to JavaScript grep implementation."),i="javascript fallback";const l=r||"**/*",u=[".git/**","node_modules/**","bower_components/**",".svn/**",".hg/**"],c=await qU(l,{cwd:n,dot:!0,ignore:u,absolute:!0,nodir:!0,signal:e.signal}),d=new RegExp(t,"i"),p=[];for(const e of c){const t=e;try{const e=await Be.readFile(t,"utf8");e.split(/\r?\n/).forEach((e,r)=>{d.test(e)&&p.push({filePath:ae.relative(n,t)||ae.basename(t),lineNumber:r+1,line:e})})}catch(a){a&&"ENOENT"===a.code||ex.debug(`Grep: Could not read/process ${t}: ${a}`)}}return p}catch(qK){throw ex.error(`Grep: Error in performGrepSearch (Strategy: ${i}): ${qK}`),qK}}const BW=Mz({metadata:{name:"grep",displayName:"Grep Search",description:"Searches for a regular expression pattern within the content of files in a specified directory. Can filter files by a glob pattern. Returns the lines containing matches, along with their file paths and line numbers.",category:"search",icon:"🔍"},inputSchema:ug({pattern:mh().describe("The regular expression (regex) pattern to search for within file contents (e.g., 'function\\s+myFunction', 'import\\s+\\{.*\\}\\s+from\\s+.*')."),absolutePath:mh().optional().describe("Optional: The absolute path to the directory to search within. If omitted, searches the current working directory."),includeGlob:mh().optional().describe("Optional: A glob pattern to filter which files are searched (e.g., '*.js', '*.{ts,tsx}', 'src/**'). If omitted, searches all files (respecting common ignores like .git, node_modules).")}),validateParams:({pattern:e,absolutePath:t})=>{try{new RegExp(e)}catch(n){return`Invalid regular expression pattern: ${e}`}return t&&!ae.isAbsolute(t)?`Path must be absolute: ${t}`:null},getDescription:({pattern:e,absolutePath:t,includeGlob:n})=>`Searching for "${e}" in ${t?ae.basename(t):"current directory"}${n?` (${n})`:""}`,getLocations:({absolutePath:e})=>[{path:e||process.cwd(),type:"read"}],execute:async({pattern:e,absolutePath:t,includeGlob:n},r)=>{try{const i=t||process.cwd();try{if(!J.statSync(i).isDirectory())return{success:!1,llmContent:`Error: Path is not a directory: ${i}`,returnDisplay:"Path is not a directory."}}catch(qK){return"ENOENT"===qK.code?{success:!1,llmContent:`Error: Directory does not exist: ${i}`,returnDisplay:"Directory not found."}:{success:!1,llmContent:`Error: Failed to access directory: ${i}. ${qK}`,returnDisplay:"Directory access failed."}}const o=await _W({pattern:e,path:i,includeGlob:n,signal:r.signal});if(0===o.length){return{success:!0,summary:"No matches found",llmContent:`No matches found for pattern "${e}" in path "${t||"."}"${n?` (filter: "${n}")`:""}.`,returnDisplay:"No matches found",metadata:{matchCount:0,toolParams:{pattern:e,absolutePath:t,includeGlob:n}}}}const s=o.reduce((e,t)=>{const n=ae.relative(i,ae.resolve(i,t.filePath))||ae.basename(t.filePath);return e[n]||(e[n]=[]),e[n].push(t),e[n].sort((e,t)=>e.lineNumber-t.lineNumber),e},{}),a=o.length,l=1===a?"match":"matches";let u=`Found ${a} ${l} for pattern "${e}" in path "${t||"."}"${n?` (filter: "${n}")`:""}:\n---\n`;for(const e in s){const t=s[e];if(t){u+=`File: ${e}\n`;for(const e of t){const t=e.line.trim();u+=`L${e.lineNumber}: ${t}\n`}u+="---\n"}}return{success:!0,summary:`Found ${a} ${l} for "${e}"`,llmContent:u.trim(),returnDisplay:`Found ${a} ${l}`,locations:[{path:i,type:"read"}],metadata:{matchCount:a,toolParams:{pattern:e,absolutePath:t,includeGlob:n}}}}catch(qK){ex.error(`Error during grep search operation: ${qK}`);const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error during grep search operation: ${t}`,returnDisplay:`Error: ${t}`}}}});const DW=Mz({metadata:{name:"glob",displayName:"Find Files",description:"Efficiently finds files matching specific glob patterns (e.g., `src/**/*.ts`, `**/*.md`), returning absolute paths sorted by modification time (newest first). Ideal for quickly locating files based on their name or path structure, especially in large codebases.",category:"search",icon:"🔍"},inputSchema:ug({pattern:mh().min(1).describe("The glob pattern to match against (e.g., '**/*.py', 'docs/*.md')."),path:mh().optional().describe("Optional: The absolute path to the directory to search within. If omitted, searches the root directory."),case_sensitive:Hh().optional().describe("Optional: Whether the search should be case-sensitive. Defaults to false."),respect_git_ignore:Hh().optional().describe("Optional: Whether to respect .gitignore patterns when finding files. Only available in git repositories. Defaults to true.")}),validateParams:({pattern:e,path:t})=>{if(!e||"string"!=typeof e||""===e.trim())return"The 'pattern' parameter cannot be empty.";if(t){const e=ae.resolve(process.cwd(),t);if(!function(e,t){const n=ae.resolve(e),r=ae.resolve(t),i=r===ae.sep||r.endsWith(ae.sep)?r:r+ae.sep;return n===r||n.startsWith(i)}(e,process.cwd()))return`Search path ("${e}") resolves outside the tool's root directory ("${process.cwd()}").`;try{if(!J.existsSync(e))return`Search path does not exist ${e}`;if(!J.statSync(e).isDirectory())return`Search path is not a directory: ${e}`}catch(n){return`Error accessing search path: ${n}`}}return null},getDescription:({pattern:e,path:t})=>{let n=`'${e}'`;if(t){n+=` within ${function(e,t=35){if(e.length<=t)return e;const n=ae.parse(e).root,r=ae.sep,i=e.substring(n.length).split(r).filter(e=>""!==e);if(i.length<=1){const n=Math.floor((t-3)/2);return n<=0?e.substring(0,t-3)+"...":`${e.substring(0,n)}...${e.substring(e.length-n)}`}const o=i[0],s=i[i.length-1];if(!s)return e.length>t?e.substring(0,t-3)+"...":e;const a=n+o,l=[];let u=r.length+s.length;for(let d=i.length-2;d>=0;d--){const e=i[d];if(!e)continue;const n=u+r.length+e.length;if(!(n<=t))break;l.unshift(e),u=n}let c=l.join(r)+r+s;return u>t?c:(c=a+r+c,c.length>t?"..."+c.substring(c.length-t-3):c)}(function(e,t){const n=ae.resolve(e),r=ae.resolve(t);return ae.relative(r,n)||"."}(ae.resolve(process.cwd(),t||"."),process.cwd()))}`}return n},getLocations:({path:e})=>[{path:e?ae.resolve(process.cwd(),e):process.cwd(),type:"read"}],execute:async(e,t)=>{const{pattern:n,path:r,case_sensitive:i,respect_git_ignore:o}=e;try{const e=ae.resolve(process.cwd(),r||"."),s=process.cwd(),a=o??!0,l=new ZU(s),u=await qU(n,{cwd:e,withFileTypes:!0,nodir:!0,stat:!0,nocase:!i,dot:!0,ignore:["**/node_modules/**","**/.git/**"],follow:!1,signal:t.signal});let c=u,d=0;if(a){const e=u.map(e=>ae.relative(s,e.fullpath())),t=l.filterFiles(e,{respectGitIgnore:a}),n=new Set(t.map(e=>ae.resolve(s,e)));c=u.filter(e=>n.has(e.fullpath())),d=u.length-c.length}if(!c||0===c.length){let t=`No files found matching pattern "${n}" within ${e}.`;return d>0&&(t+=` (${d} files were git-ignored)`),{success:!0,summary:"No files found",llmContent:t,returnDisplay:"No files found",locations:[{path:e,type:"read"}],metadata:{matchCount:0,gitIgnoredCount:d,toolParams:{pattern:n,searchDirectory:null,fileFilteringOptions:null}}}}const p=864e5,f=function(e,t,n){const r=[...e];return r.sort((e,r)=>{const i=e.mtimeMs??0,o=r.mtimeMs??0,s=t-i<n,a=t-o<n;return s&&a?o-i:s?-1:a?1:e.fullpath().localeCompare(r.fullpath())}),r}(c,(new Date).getTime(),p),h=f.map(e=>e.fullpath()),g=h.join("\n"),A=h.length;let m=`Found ${A} file(s) matching "${n}" within ${e}`;return d>0&&(m+=` (${d} additional files were git-ignored)`),m+=`, sorted by modification time (newest first):\n${g}`,{success:!0,summary:`Found ${A} matching file(s)`,llmContent:m,returnDisplay:`Found ${A} matching file(s)${d>0?` (${d} git-ignored)`:""}`,locations:h.map(e=>({path:e,type:"read"})),metadata:{matchCount:A,gitIgnoredCount:d,pattern:n,searchDirectory:e,toolParams:{pattern:n,searchDirectory:null,fileFilteringOptions:null}}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return ex.error(`Glob tool execute Error: ${t}`,qK),{success:!1,summary:"Glob search failed",llmContent:`Error during glob search operation: ${t}`,returnDisplay:"Error: An unexpected error occurred."}}}}),SW=new Set,kW=new Set(["cd","pushd","popd","dirs","pwd","realpath","readlink","basename","dirname","ls","dir","ll","tree","cat","head","tail","less","more","type","file","stat","du","df","attrib","lsof","mount","whoami","id","groups","date","uptime","uname","hostname","ps","top","htop","tasklist","netstat","ipconfig","ifconfig","env","printenv","set","export","alias","getconf","which","where","whereis","type","command","history","grep","egrep","fgrep","findstr","rg","wc","sort","uniq","cut","echo","Get-ChildItem","gci","Get-Content","gc","Get-Location","gl","Set-Location","sl","Get-Process","gps","Get-Command","Get-Item","Get-ItemProperty","Resolve-Path","Split-Path","Join-Path","Test-Path","Select-String","sls","Measure-Object","locate"]),xW=[/^git\s+(status|log|diff|show|branch|remote|config\s+--list|remote\s+-v)(\s|$)/,/^npm\s+(list|ls|outdated|info|view|version|run\s+(test|lint|build|typecheck|check))(\s|$)/,/^yarn\s+(list|info|why)(\s|$)/,/^pnpm\s+(list|ls|why|outdated)(\s|$)/,/^pip\s+(list|show|freeze)(\s|$)/,/^(node|npm|yarn|pnpm|python|python3|pip|git|tsc|npx)\s+(--version|-v)(\s|$)/,/^(npx\s+)?tsc\s+(--noEmit|--version)(\s|$)/,/^find\s+(?!.*(-exec|-delete))/,/^cd\s+/,/^pushd\s+/,/^(Get-|Test-|Select-|Measure-|Split-|Join-|Resolve-)/i];function QW(e){return e.trim().replace(/[{}()]/g,"").split(/[\s;&|]+/)[0]?.split(/[/\\]/).pop()||null}async function NW(e,t=3,n=500,r=0,i=new Map){if(r>=t||i.size>=n)return i;try{const o=await oe.readdir(e,{withFileTypes:!0});for(const s of o){if(i.size>=n)break;if(s.name.startsWith(".")||"node_modules"===s.name||"__pycache__"===s.name||"venv"===s.name||"dist"===s.name||"build"===s.name)continue;const o=ae.join(e,s.name);if(s.isDirectory())await NW(o,t,n,r+1,i);else if(s.isFile())try{const e=await oe.stat(o);i.set(o,e.mtimeMs)}catch{}}}catch{}return i}const TW=Mz({metadata:{name:"shell",displayName:"Shell Command",description:"Execute shell commands immediately in the project directory. This tool handles all safety checks internally and does not require pre-approval.",category:"system",icon:"💻",requiresConfirmation:!0,canStream:!0,requiresSequentialExecution:!0},inputSchema:ug({command:mh().describe("The shell command to execute"),workingDirectory:mh().optional().describe("Working directory (defaults to project root)"),timeout:jh().default(3e4).describe("Timeout in milliseconds (default: 30 seconds)"),shell:Hh().default(!0).describe("Whether to use shell for command execution")}),validateParams:({command:e})=>e.trim()?null:"Command cannot be empty",getDescription:({command:e,workingDirectory:t})=>`Running "${e}" in ${t?ae.basename(t):"project root"}`,getLocations:({workingDirectory:e})=>[{path:e||process.cwd(),type:"execute"}],getCommandRoot:({command:e})=>QW(e),isAllowlisted:({command:e})=>{const t=QW(e);return!!t&&SW.has(t)},addToAllowlist:({command:e},t)=>{if("always"===t||"command"===t){const t=QW(e);t&&SW.add(t)}},shouldConfirm:async({command:e,workingDirectory:t})=>{const n=e.trim().split(/\s+/);if(function(e,t){return!(!t[0]||!kW.has(t[0]))||xW.some(t=>t.test(e))}(e,n))return null;const r=[/rm\s+-rf/i,/rm\s+.*\/\s*$/i,/>\s*\/dev\/(sda|sdb|sdc)/i,/dd\s+.*of=/i,/format\s+/i,/fdisk/i,/mkfs/i].some(t=>t.test(e)),i=t||process.cwd();return{type:"execute",title:r?"⚠️ Potentially Dangerous Command":"Execute Command",description:`Execute: ${e} in ${ae.basename(i)}`,affectedPaths:[i],isDestructive:r}},execute:async({command:e,workingDirectory:t,timeout:n,shell:r},i)=>new Promise(async o=>{const s=t||process.cwd();let a="",l="",u=!1;const c=Date.now();let d=0;let p=null;if(i.snapshotService)try{p=await NW(s),ex.info("shell: Scanned directory before execution",{fileCount:p.size,cwd:ae.relative(process.cwd(),s)})}catch(qK){ex.warn("shell: Failed to scan directory before execution",qK)}const f="win32"===process.platform?"cmd":"bash",h="win32"===process.platform?["/c"]:["-c"],g=r?Se(f,[...h,e],{cwd:s,stdio:["pipe","pipe","pipe"]}):Se(e,[],{cwd:s,stdio:["pipe","pipe","pipe"],shell:!1}),A=setTimeout(()=>{u=!0,g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},2e3)},n);g.stdout?.on("data",e=>{const t=e.toString();a+=t;const n=Date.now();n-d>=100&&(i.updateOutput?.(a+l),d=n)}),g.stderr?.on("data",e=>{const t=e.toString();l+=t;const n=Date.now();n-d>=100&&(i.updateOutput?.(a+l),d=n)}),g.on("close",async(t,r)=>{if(clearTimeout(A),(a||l)&&i.updateOutput?.(a+l),i.snapshotService&&p)try{const e=await NW(s),{newFiles:t,modifiedFiles:n}=await async function(e,t){const n=[],r=[];for(const[i,o]of t.entries()){const t=e.get(i);void 0===t?n.push(i):o!==t&&r.push(i)}return{newFiles:n,modifiedFiles:r}}(p,e);ex.info("shell: File changes detected",{newFiles:t.length,modifiedFiles:n.length});for(const r of n)i.snapshotService.isFileTracked(r)||(i.snapshotService.registerFile(r),ex.info("shell: Registered modified file",{file:ae.relative(process.cwd(),r)}));for(const r of t)i.snapshotService.isFileTracked(r)||(i.snapshotService.registerFile(r),ex.info("shell: Registered new file",{file:ae.relative(process.cwd(),r)}));(t.length>0||n.length>0)&&await i.snapshotService.track()}catch(qK){ex.warn("shell: Failed to detect file changes after execution",qK)}const d=Date.now()-c,f=!u&&0===t;let h,g;u?(h=`Command timed out after ${n}ms`,g=h):r?(h=`Command terminated by signal: ${r}`,g=h):(h=`Command ${f?"completed":"failed"} (exit code: ${t})`,g=f?"(none)":h);let m=(a+(l?`\n--- STDERR ---\n${l}`:"")).trim()||"(no output)";f||(m=`${h}\n\n${m}`);const y=(a+l).trim()||"(empty)",b=[`Command: ${e}`,`Directory: ${ae.relative(process.cwd(),s)}`,`Output: ${y}`,`Error: ${g}`,`Exit Code: ${t??"(none)"}`,`Signal: ${r??"(none)"}`,`Duration: ${d}ms`].join("\n");o({success:f,summary:`${h} in ${d}ms`,llmContent:b,returnDisplay:m,locations:[{path:s,type:"execute"}],metadata:{exitCode:t,signal:r,duration:d,command:e,cwd:s,isTimedOut:u,stdoutLength:a.length,stderrLength:l.length}})}),g.on("error",t=>{clearTimeout(A);const n=(a+(l?`\n--- STDERR ---\n${l}`:"")).trim()||"(no output)",r=(a+l).trim()||"(empty)",i=[`Command: ${e}`,`Directory: ${ae.relative(process.cwd(),s)}`,`Output: ${r}`,`Error: ${t.message}`,"Exit Code: (none)","Signal: (none)",`Duration: ${Date.now()-c}ms`].join("\n");o({success:!1,llmContent:i,returnDisplay:`Error: ${t.message}\n\n${n}`,metadata:{error:t.message,command:e}})}),i.signal&&i.signal.addEventListener("abort",()=>{g.kill("SIGTERM")})})}),RW=Mz({metadata:{name:"build",displayName:"Build Project",description:"Build the project using the configured build command",category:"development",icon:"🔨",canStream:!0},inputSchema:ug({target:mh().optional().describe("Build target (e.g., 'dev', 'prod', 'test')"),clean:Hh().default(!1).describe("Clean before building"),workingDirectory:mh().optional().describe("Project directory (defaults to current directory)")}),validateParams:({workingDirectory:e})=>e&&!ae.isAbsolute(e)?`Working directory must be absolute: ${e}`:null,getDescription:({target:e,clean:t})=>`Building project${e?` (${e})`:""}${t?" with clean":""}`,getLocations:({workingDirectory:e})=>[{path:e||process.cwd(),type:"execute"}],execute:async({target:e,clean:t,workingDirectory:n},r)=>{const i=n||process.cwd();try{const n=ae.join(i,"package.json");let o=null,s="unknown",a="npm run build";try{const e=await Be.readFile(n,"utf8");o=JSON.parse(e),s="npm"}catch{}if(o?.scripts){if(e&&o.scripts[`build:${e}`])a=`npm run build:${e}`;else if(o.scripts.build)a="npm run build";else if(o.scripts.dev&&"dev"===e)a="npm run dev";else{const e=["compile","make","bundle"].find(e=>o.scripts[e]);e&&(a=`npm run ${e}`)}try{await Be.access(ae.join(i,"yarn.lock")),a=a.replace("npm run","yarn"),s="yarn"}catch{}try{await Be.access(ae.join(i,"pnpm-lock.yaml")),a=a.replace("npm run","pnpm run"),s="pnpm"}catch{}}else{const e=[{file:"Makefile",system:"make",command:"make"},{file:"build.gradle",system:"gradle",command:"gradle build"},{file:"pom.xml",system:"maven",command:"mvn compile"},{file:"Cargo.toml",system:"cargo",command:"cargo build"},{file:"go.mod",system:"go",command:"go build"}];for(const{file:t,system:n,command:r}of e)try{await Be.access(ae.join(i,t)),s=n,a=r;break}catch{}}if(t){let e="";if(o?.scripts?.clean)e=a.replace(/build.*$/,"clean");else switch(s){case"make":e="make clean";break;case"gradle":e="gradle clean";break;case"maven":e="mvn clean";break;case"cargo":e="cargo clean";break;case"go":e="go clean";break;default:e="npm run clean"}if(e){r.updateOutput?.("🧹 Cleaning...\n");const t=await TW.executeStructured({command:e,workingDirectory:i,timeout:5,shell:!0},r);if(!t.success)return{success:!1,llmContent:`Clean failed: ${t.llmContent}`,returnDisplay:"Clean step failed"}}}r.updateOutput?.(`🔨 Building with ${s}...\n`);const l=await TW.executeStructured({command:a,workingDirectory:i,timeout:3e4,shell:!0},r),u=["dist","build","out","target"];let c=[];for(const e of u){const t=ae.join(i,e);try{(await Be.stat(t)).isDirectory()&&c.push(e)}catch{}}return{success:l.success,summary:l.success?`Build completed using ${s}${e?` (${e})`:""}`:`Build failed using ${s}`,llmContent:`Build System: ${s}\nCommand: ${a}${t?"\nCleaned before build: yes":""}\n\n${l.llmContent}${c.length?`\n\nBuild Artifacts: ${c.join(", ")}`:""}`,returnDisplay:l.success?"✅ Build completed"+(c.length?` → ${c.join(", ")}`:""):"❌ Build failed",locations:[{path:i,type:"execute"},...c.map(e=>({path:ae.join(i,e),type:"write"}))],metadata:{buildSystem:s,buildCommand:a,target:e,clean:t,buildArtifacts:c,...l.metadata}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error during build: ${t}`,returnDisplay:`Build error: ${t}`,metadata:{error:t}}}}}),FW=new Set;function MW(e){try{return e.toString("utf8").includes("�")||function(e){return e.filter(e=>e<32&&9!==e&&10!==e&&13!==e).length/e.length>.3}(e)?"latin1":"utf8"}catch{return"latin1"}}function OW(e){return e.includes("\r\n")||e.includes("\r")?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):e.replace(/\n{4,}/g,"\n\n\n")}function $W(e){return e.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}function LW(e,t="direct"){const n=MW(e);let r=e.toString(n);return r=$W(r),r=OW(r),r}const PW=Mz({metadata:{name:"serial_monitor",displayName:"Serial Monitor",description:"Opens a serial monitor connection to capture debug output from embedded devices.\n\nThis tool monitors serial output until a specific string is detected or a timeout occurs.\n\nThe tool automatically handles:\n- Encoding detection (UTF-8 with Latin-1 fallback)\n- Intelligent line ending normalization\n- ANSI escape sequence cleaning\n- Real-time data processing\n\nThe tool supports two modes:\n1. **Custom Command Mode**: If 'serial_monitor_command' is defined in EMBEDDER.md, it will use that command (e.g., \"tio {port} -b {baud}\")\n2. **Direct Serial Mode**: Uses built-in serial port communication for standard connections (default)\n\nCommon use cases:\n- Monitoring firmware boot sequences\n- Capturing debug output until a specific log message appears\n- Waiting for initialization complete messages\n- Debugging serial communication protocols\n\nReturns all captured serial output up to the stop condition.",category:"system",icon:"📡",requiresConfirmation:!0,canStream:!0},inputSchema:ug({port:mh().optional().describe("Serial port device path (e.g., /dev/ttyUSB0, /dev/ttyACM0, COM3). If not specified, uses serial_port from EMBEDDER.md."),baud_rate:jh().optional().describe("Baud rate for serial communication (e.g., 115200, 9600). If not specified, uses serial_baudrate from EMBEDDER.md or defaults to 115200."),stop_string:mh().describe("Text string to watch for in the serial output. When this string is detected, the monitor will stop and return all captured output."),timeout:jh().default(3e4).describe("Maximum time in milliseconds to wait for the stop_string before giving up. Defaults to 30000 (30 seconds)."),description:mh().optional().describe("Brief description of what debug information is being monitored for."),interactive:Hh().default(!1).describe("Enable interactive mode for commands that require terminal interaction (e.g., waf console). Uses PTY for proper terminal emulation."),startup_commands:ag(mh()).optional().describe("Commands to automatically send to the interactive terminal after startup. Useful for automating initial setup in interactive sessions.")}),validateParams:({stop_string:e,timeout:t})=>e?.trim()?t&&t<1e3?"timeout must be at least 1000ms":null:"stop_string is required and cannot be empty",getDescription:e=>{let t=`Monitor serial output for "${e.stop_string}"`;return e.port&&(t+=` on ${e.port}`),e.baud_rate&&(t+=` at ${e.baud_rate} baud`),e.timeout&&3e4!==e.timeout&&(t+=` (${e.timeout/1e3}s timeout)`),e.description&&(t+=` - ${e.description}`),e.startup_commands&&e.startup_commands.length>0&&(t+=` (with ${e.startup_commands.length} startup command${e.startup_commands.length>1?"s":""})`),t},getLocations:()=>[{path:process.cwd(),type:"execute"}],getCommandRoot:()=>"serialMonitor",isAllowlisted:()=>FW.has("serialMonitor"),addToAllowlist:(e,t)=>{"always"!==t&&"command"!==t||FW.add("serialMonitor")},shouldConfirm:async({stop_string:e,port:t,baud_rate:n,interactive:r,startup_commands:i})=>{let o=`serial_monitor --stop-string "${e}"`;return r&&(o+=" --interactive"),i&&i.length>0&&(o+=` (${i.length} startup command${i.length>1?"s":""})`),{type:"execute",title:"Start serial monitor?",description:`Monitor serial output for "${e}" ${t?`on ${t}`:""} ${n?`at ${n} baud`:""}`,affectedPaths:[process.cwd()],isDestructive:!1}},execute:async(e,t)=>{try{const r=await async function(){const e=ae.join(process.cwd(),"EMBEDDER.md");try{if(!J.existsSync(e))return;const t=(await J.promises.readFile(e,"utf-8")).match(/<COMMANDS>([\s\S]*?)<\/COMMANDS>/);if(!t)return;const n=t[1],r={};if(!n||""===n.trim())return r;const i=n.split("\n");for(const e of i){const t=e.match(/^(\w+)\s*=\s*(.+)$/);if(t){const[,e,n]=t;if(!n)continue;const i=n.replace(/^\[|\]$/g,"").trim();if(!i)continue;switch(e){case"serial_monitor_command":r.serial_monitor_command=i;break;case"serial_port":r.serial_port=i;break;case"serial_baudrate":const e=parseInt(i);!isNaN(e)&&e>0&&(r.serial_baudrate=e);break;case"serial_monitor_interactive":r.serial_monitor_interactive="true"===i;break;case"serial_startup_commands":if(i.startsWith("[")&&i.endsWith("]")){const e=i.slice(1,-1);e.trim()&&(r.serial_startup_commands=e.split(",").map(e=>e.trim().replace(/^["']|["']$/g,"")).filter(e=>e.length>0))}else r.serial_startup_commands||(r.serial_startup_commands=[]),r.serial_startup_commands.push(i.replace(/^["']|["']$/g,""))}}}return Object.keys(r).length>0?r:void 0}catch(qK){return}}(),i=e.port||r?.serial_port||"/dev/ttyUSB0",o=e.baud_rate||r?.serial_baudrate||115200,s=e.timeout||3e4;let a;if(r?.serial_monitor_command){e.interactive||r.serial_monitor_interactive||(n=r.serial_monitor_command,["waf console","screen ","minicom","cu ","tip "].some(e=>n.includes(e)))?(t.updateOutput&&t.updateOutput(`Using interactive command: ${r.serial_monitor_command}\n`),a=await async function(e,t,n,r,i,o,s,a){try{const l=await import("./index-C1UxfNrr.js").then(e=>e.i),u=e.replace(/{port}/g,t).replace(/{baud}/g,n.toString());return new Promise(e=>{let t,n="",c=!1,d=!1;const p=l.spawn("bash",["-c",u],{name:"xterm-color",cols:80,rows:30,cwd:process.cwd(),env:{...process.env,TERM:"xterm-256color",COLUMNS:"80",LINES:"30"}});o&&o.length>0&&setTimeout(()=>{s&&s("\nSending startup commands:\n"),o.forEach((e,t)=>{setTimeout(()=>{s&&s(`> ${e}\n`),p.write(`${e}\r\n`)},500*t)})},2e3),t=setTimeout(()=>{c||(p.kill(),e({output:n,success:!1,reason:`Timeout: stop_string "${r}" not found within ${i/1e3} seconds`}))},i),p.onData(i=>{let o=$W(i);o=OW(o),n+=o,s&&s(n),!c&&o.includes(r)&&(c=!0,d=!0,clearTimeout(t),s&&s(`\nStop string "${r}" detected. Collecting additional data for 1 second...\n`),setTimeout(()=>{d=!1,p.kill(),e({output:n,success:!0})},1e3))}),p.onExit(i=>{c||(clearTimeout(t),e({output:n,success:!1,reason:`Process exited with code ${i.exitCode} before finding stop_string "${r}"`}))}),a&&a.addEventListener("abort",()=>{clearTimeout(t),p.kill(),e({output:n,success:!1,reason:"Operation was cancelled by user"})})})}catch(qK){return{output:"",success:!1,reason:`Failed to initialize PTY for interactive mode: ${qK instanceof Error?qK.message:String(qK)}. Check system PTY support.`}}}(r.serial_monitor_command,i,o,e.stop_string,s,e.startup_commands||r.serial_startup_commands,t.updateOutput,t.signal)):(t.updateOutput&&t.updateOutput(`Using custom command: ${r.serial_monitor_command}\n`),a=await async function(e,t,n,r,i,o,s){const a=e.replace(/{port}/g,t).replace(/{baud}/g,n.toString());return new Promise(e=>{let t,n="",l=!1;const u=Se("bash",["-c",a],{stdio:["ignore","pipe","pipe"],cwd:process.cwd()});t=setTimeout(()=>{l||(u.kill("SIGTERM"),e({output:n,success:!1,reason:`Timeout: stop_string "${r}" not found within ${i/1e3} seconds`}))},i),u.stdout?.on("data",i=>{let s=LW(i,"custom");n+=s,o&&o(n),!l&&s.includes(r)&&(l=!0,clearTimeout(t),o&&o(`\nStop string "${r}" detected. Collecting additional data for 1 second...\n`),setTimeout(()=>{u.kill("SIGTERM"),e({output:n,success:!0})},1e3))}),u.stderr?.on("data",e=>{let t=LW(e,"custom");n+=t,o&&o(n)}),u.on("exit",i=>{l||(clearTimeout(t),e({output:n,success:!1,reason:`Process exited with code ${i} before finding stop_string "${r}"`}))}),s&&s.addEventListener("abort",()=>{clearTimeout(t),u.kill("SIGTERM"),e({output:n,success:!1,reason:"Operation was cancelled by user"})})})}(r.serial_monitor_command,i,o,e.stop_string,s,t.updateOutput,t.signal))}else t.updateOutput&&t.updateOutput(`Opening direct serial connection to ${i} at ${o} baud...\n`),a=await async function(e,t,n,r,i,o){try{const{SerialPortStream:s}=await import("@serialport/stream"),{autoDetect:a}=await import("@serialport/bindings-cpp");return new Promise(l=>{let u,c="",d=!1,p=!1,f="";const h=()=>{const e=f.split(/\r?\n/);if(e.length>1){f=e.pop()||"";const t=e.join("\n")+(e.length>0?"\n":"");if(t){let e=$W(t);e=OW(e),e.trim()&&(c+=e,i&&i(c+(f||"")))}}},g=new s({path:e,baudRate:t,binding:a(),dataBits:8,stopBits:1,parity:"none",rtscts:!0,xon:!1,xoff:!1,autoOpen:!1}),A=setTimeout(()=>{d||(h(),g.close(),l({output:c,success:!1,reason:`Connection timeout: Could not open serial port ${e} within 5 seconds`}))},5e3);g.on("open",()=>{clearTimeout(A),i&&i(`Successfully connected to ${e} at ${t} baud\n`)}),g.open(e=>{if(e){clearTimeout(A);let t=`Failed to open serial port: ${e.message}`;e.message.includes("EACCES")||e.message.includes("Permission denied")?t+=". Try: sudo usermod -a -G dialout $USER (then logout/login)":e.message.includes("ENOENT")||e.message.includes("No such file")?t+=". Check that the device is connected and the port path is correct.":(e.message.includes("EBUSY")||e.message.includes("Resource busy"))&&(t+=". Port may be in use by another application."),l({output:c,success:!1,reason:t})}}),u=setTimeout(()=>{d||(h(),g.close(),l({output:c,success:!1,reason:`Timeout: stop_string "${n}" not found within ${r/1e3} seconds`}))},r),g.on("data",e=>{const t=MW(e);let r=e.toString(t);f+=r,h(),!d&&(c.includes(n)||r.includes(n)||f.includes(n))&&(d=!0,p=!0,clearTimeout(u),clearTimeout(A),i&&i(`\nStop string "${n}" detected. Collecting additional data for 1 second...\n`),setTimeout(()=>{p=!1,h(),g.close(),l({output:c,success:!0})},1e3))}),g.on("error",e=>{clearTimeout(u),clearTimeout(A),h();let t=`Serial port error: ${e.message}`;e.message.includes("EACCES")||e.message.includes("Permission denied")?t+=". Try: sudo usermod -a -G dialout $USER (then logout/login)":(e.message.includes("ENOENT")||e.message.includes("No such file"))&&(t+=". Check that the device is connected and the port path is correct."),l({output:c,success:!1,reason:t})}),o&&o.addEventListener("abort",()=>{clearTimeout(u),clearTimeout(A),h(),g.close(),l({output:c,success:!1,reason:"Operation was cancelled by user"})})})}catch(qK){return{output:"",success:!1,reason:`Failed to initialize serial port: ${qK instanceof Error?qK.message:String(qK)}. Check that the port exists and has proper permissions.`}}}(i,o,e.stop_string,s,t.updateOutput,t.signal);let l="Serial Monitor Results:\n\n";if(l+=`Port: ${i}\n`,l+=`Baud Rate: ${o}\n`,l+=`Stop String: "${e.stop_string}"\n`,l+=`Status: ${a.success?"SUCCESS":"FAILED"}\n`,a.reason&&(l+=`Reason: ${a.reason}\n`),!a.success&&a.output.length>0){/[\x00-\x08\x0E-\x1F\x7F-\u00FF]/.test(a.output)&&(l+="\nNOTE: Output contains non-printable characters, which may indicate:\n",l+="- Incorrect baud rate (try common rates: 9600, 19200, 38400, 57600, 115200)\n",l+="- Mismatched data bits, stop bits, or parity settings\n",l+="- Device not ready or sending binary data\n")}a.output.length>1e4?l+=`\n--- Serial Output (truncated) ---\n${a.output.substring(0,1e4)}\n... (output truncated, ${a.output.length} total characters)`:l+=`\n--- Serial Output ---\n${a.output}`;let u=a.success?`Serial monitor completed - found "${e.stop_string}"`:`Serial monitor failed - ${a.reason}`;return a.output.trim()&&(u+=`\n\nCaptured Output:\n${a.output}`),{success:a.success,llmContent:l,returnDisplay:u,summary:a.success?`Found "${e.stop_string}"`:`Failed: ${a.reason}`,locations:[{path:process.cwd(),type:"execute"}],metadata:{port:i,baudRate:o,stopString:e.stop_string,timeout:s,outputLength:a.output.length}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Serial monitor error: ${t}`,returnDisplay:`❌ Serial monitor failed: ${t}`,summary:`Error: ${t}`}}var n}}),jW=Mz({metadata:{name:"todowrite",displayName:"Todo Write",description:"Create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.",category:"development",icon:"✓",isOutputMarkdown:!1},inputSchema:M$,validateParams:({todos:e})=>{for(const r of e){if(!r.content||0===r.content.trim().length)return"All todo items must have non-empty content";if(!r.id||0===r.id.trim().length)return"All todo items must have a valid ID"}const t=e.map(e=>e.id),n=new Set(t);if(t.length!==n.size)return"Todo items must have unique IDs";return e.filter(e=>e.status===k$).length>1?"Only one todo item can be 'in_progress' at a time":null},getDescription:({todos:e})=>L$($$(e)),getLocations:()=>[],execute:async({todos:e},t)=>{try{const t="active",n=e.map(e=>({...e,id:e.id||`todo_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,createdAt:e.createdAt||(new Date).toISOString(),completedAt:e.status!==x$||e.completedAt?e.completedAt:(new Date).toISOString()}));oM(t,n);const r=$$(n),i=(L$(r),n.map(e=>`${e.status===x$?"[x]":"[ ]"} ${e.status===Q$?`~~${e.content}~~`:e.status===k$?`**${e.content}**`:e.content}`).join("\n"));return{success:!0,summary:`Updated todo list with ${n.length} items (${r.pendingCount} pending, ${r.inProgressCount} in progress, ${r.completedCount} completed)`,llmContent:`Todo list updated successfully:\n${i}`,metadata:{todoMetadata:r,todos:n,phase:r.phase,sessionId:t}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error updating todo list: ${t}`,returnDisplay:`Error updating todo list: ${t}`,summary:"Failed to update todo list"}}}}),UW=Mz({metadata:{name:"todoread",displayName:"Todo Read",description:"Read your current todo list to check progress and see what tasks remain",category:"development",icon:"📋",isOutputMarkdown:!1},inputSchema:ug({}),validateParams:()=>null,getDescription:()=>"Reading current todo list",getLocations:()=>[],execute:async(e,t)=>{try{const e="active",t=iM(e);if(0===t.length)return{success:!0,summary:"No todos currently tracked",llmContent:"No todos found for this session",metadata:{todoMetadata:{todos:[],totalCount:0,pendingCount:0,inProgressCount:0,completedCount:0,cancelledCount:0,phase:"creating"},todos:[],sessionId:e}};const n=$$(t),r=(L$(n),t.map(e=>`${e.status===x$?"[x]":"[ ]"} ${e.status===Q$?`~~${e.content}~~`:e.status===k$?`**${e.content}**`:e.content}`).join("\n")),i=[n.pendingCount>0?`${n.pendingCount} pending`:null,n.inProgressCount>0?`${n.inProgressCount} in progress`:null,n.completedCount>0?`${n.completedCount} completed`:null,n.cancelledCount>0?`${n.cancelledCount} cancelled`:null].filter(Boolean).join(", ");return{success:!0,summary:`Found ${n.totalCount} todos: ${i}`,llmContent:`Current todo list:\n${r}`,metadata:{todoMetadata:n,todos:t,sessionId:e}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error reading todo list: ${t}`,returnDisplay:`Error reading todo list: ${t}`,summary:"Failed to read todo list"}}}}),zW=Mz({metadata:{name:"documentSearch",displayName:"Document Search",description:"Performs semantic search across documentation using vector embeddings. This tool is useful for finding relevant contexts based on semantic similarity to your query.",category:"search",icon:"🔍",requiresConfirmation:!1},inputSchema:ug({query:mh().min(1).describe("The search query to find relevant component information."),max_results:jh().min(1).max(100).optional().describe("Maximum number of results to return (default: 10)."),threshold:jh().min(0).max(1).optional().describe("Minimum similarity threshold between 0 and 1 (default: 0.0).")}),validateParams:({query:e,max_results:t,threshold:n})=>e&&"string"==typeof e&&0!==e.trim().length?void 0!==t&&("number"!=typeof t||t<1)?"max_results must be a positive number if provided":void 0!==n&&("number"!=typeof n||n<0||n>1)?"threshold must be a number between 0 and 1 if provided":null:"query is required and must be a non-empty string",getDescription:({query:e,max_results:t,threshold:n})=>{let r=`Searching for content related to: "${e}"`;return t&&(r+=` (max ${t} results)`),n&&(r+=` (min similarity: ${n})`),r},getLocations:()=>[],execute:async({query:e,max_results:t,threshold:n},r)=>{try{const i=r.teamId,o=r.projectId;if(!i||!o)return{success:!1,llmContent:"Error: No team/project selected. Please select a team and project in the CLI before using document_search.",returnDisplay:"No team/project selected. Select a team and project to use document search."};if(!r.apiFetch)return{success:!1,llmContent:"Error: No authentication available. Please authenticate first.",returnDisplay:"Authentication required. Please log in first."};const s={query:e,max_results:t||10,threshold:n||0},a=await r.apiFetch(`api/v1/projects/${o}/retrieve-context`,{method:"POST",body:JSON.stringify(s)},{},2);return{success:!0,llmContent:a.text&&a.text.length>0?a.text:"",returnDisplay:a.text&&a.text.length>0?`Found results for "${e}"`:"No relevant information found."}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error: document_search failed - ${t}`,returnDisplay:`Error: ${t}`}}}}),GW=Mz({metadata:{name:"web-search",displayName:"Web Context",description:"Retrieves contextual information from Internet.",category:"search",icon:"🧠",requiresConfirmation:!1},inputSchema:ug({query:mh().min(1,"Query cannot be empty.").describe("The search query to retrieve contextual information for."),tokensNum:fg([mh(),jh()]).optional().default("dynamic").describe("Token limit for the response. Can be 'dynamic' or a number.")}),validateParams:({query:e})=>e.trim()?null:"query is required and must be a non-empty string",getDescription:({query:e})=>`Fetching context for "${e}"`,getLocations:()=>[],execute:async({query:e,tokensNum:t="dynamic"},n)=>{try{if(!n.apiFetch)return{success:!1,llmContent:"Error: No authentication available. Please authenticate first.",returnDisplay:"Authentication required. Please log in first."};const r=await n.apiFetch("api/v1/proxy/web-context",{method:"POST",body:JSON.stringify({query:e})},{},2);return r.response?{success:!0,llmContent:r.response,returnDisplay:`Retrieved context for "${e}"`,summary:`Web context retrieved for "${e}"`,metadata:{query:e,tokensNum:t,responseLength:r.response.length}}:{success:!1,llmContent:"No context data returned from Web.",returnDisplay:"No context received."}}catch(r){const e=r instanceof Error?r.message:String(r);return{success:!1,llmContent:`Web context request failed: ${e}`,returnDisplay:`Error: ${e}`}}}}),HW={"codebase-explorer":{id:"codebase-explorer",name:"codebase-explorer",displayName:"Codebase Explorer",description:"Explore and analyze codebase structure, find files, understand relationships",category:"search",tools:{readFile:!0,readManyFiles:!0,listDirectory:!0,grep:!0,glob:!0,documentSearch:!0,writeFile:!1,editFile:!1,shell:!1,build:!1},systemPrompt:"You are a specialized codebase exploration agent. Your role is to:\n1. Navigate and understand project structure\n2. Find specific files, functions, and patterns\n3. Analyze code relationships and dependencies\n4. Provide comprehensive codebase insights\n5. Search across multiple files efficiently\n\nFocus on READ-ONLY operations. Do not modify files or execute commands.\nWhen exploring, provide clear summaries of what you found and where.",maxToolCalls:15,autoInvokable:!0},"code-analyzer":{id:"code-analyzer",name:"code-analyzer",displayName:"Code Analyzer",description:"Deep analysis of code quality, patterns, security issues, and technical debt",category:"analysis",tools:{readFile:!0,readManyFiles:!0,grep:!0,glob:!0,listDirectory:!0,documentSearch:!0,writeFile:!1,editFile:!1,shell:!1,build:!1},systemPrompt:"You are a specialized code analysis agent. Your expertise includes:\n1. Code quality assessment and best practices\n2. Security vulnerability detection\n3. Performance bottleneck identification\n4. Technical debt analysis\n5. Architecture pattern recognition\n6. Dependency analysis\n\nProvide detailed, actionable insights with specific file references and line numbers.\nFocus on analysis only - do not modify code.",maxToolCalls:20,autoInvokable:!0},"file-manager":{id:"file-manager",name:"file-manager",displayName:"File Manager",description:"Handle file operations, refactoring, bulk edits, and file organization",category:"development",tools:{readFile:!0,readManyFiles:!0,writeFile:!0,editFile:!0,listDirectory:!0,grep:!0,glob:!0,shell:!1,build:!1},systemPrompt:"You are a specialized file management agent. Your responsibilities:\n1. Bulk file operations and refactoring\n2. Code reorganization and cleanup\n3. File creation and modification\n4. Directory structure management\n5. Safe file operations with backups when needed\n\nAlways validate operations and provide clear summaries of changes made.\nUse readFile before editFile to understand current content.",maxToolCalls:25,autoInvokable:!1},"build-engineer":{id:"build-engineer",name:"build-engineer",displayName:"Build Engineer",description:"Handle build processes, testing, dependency management, and development workflows",category:"development",tools:{readFile:!0,listDirectory:!0,shell:!0,build:!0,grep:!0,glob:!0,writeFile:!1,editFile:!1},systemPrompt:"You are a specialized build and development workflow agent. Your expertise:\n1. Build system configuration and troubleshooting\n2. Dependency management and updates\n3. Test execution and CI/CD processes\n4. Development environment setup\n5. Performance optimization and monitoring\n\nFocus on build tools, testing, and development workflow automation.\nAlways explain what commands you're running and why.",maxToolCalls:10,autoInvokable:!1},"general-assistant":{id:"general-assistant",name:"general-assistant",displayName:"General Assistant",description:"Multi-step tasks requiring coordination of multiple tools and operations",category:"general",tools:{readFile:!0,readManyFiles:!0,writeFile:!0,editFile:!0,listDirectory:!0,grep:!0,glob:!0,documentSearch:!0,shell:!0,build:!0},systemPrompt:"You are a general-purpose assistant agent capable of complex, multi-step tasks.\nYour strengths include:\n1. Coordinating multiple operations across different tool categories\n2. Complex problem-solving requiring multiple approaches\n3. Research and implementation in one workflow\n4. Cross-domain tasks (search + analysis + implementation)\n\nBreak down complex tasks into logical steps and execute systematically.\nAlways summarize what you accomplished and what tools you used.",maxToolCalls:30,autoInvokable:!1}};class WW{static agents=new Map;static initialized=!1;static initialize(){if(!this.initialized){for(const e of Object.values(HW))this.agents.set(e.id,e);this.initialized=!0}}static getAgent(e){return this.initialize(),this.agents.get(e)||null}static getAllAgents(){return this.initialize(),Array.from(this.agents.values())}static getAgentsByCategory(e){return this.initialize(),Array.from(this.agents.values()).filter(t=>t.category===e)}static getAutoInvokableAgents(){return this.initialize(),Array.from(this.agents.values()).filter(e=>e.autoInvokable)}static registerAgent(e){this.initialize(),this.agents.set(e.id,e)}static unregisterAgent(e){return this.initialize(),this.agents.delete(e)}static getAgentIds(){return this.initialize(),Array.from(this.agents.keys())}static searchAgents(e){this.initialize();const t=e.toLowerCase();return Array.from(this.agents.values()).filter(e=>e.name.toLowerCase().includes(t)||e.displayName.toLowerCase().includes(t)||e.description.toLowerCase().includes(t))}}WW.initialize();class qW{static sessions=new Map;static eventHandlers=new Map;static async createSession(e,t){const n=WW.getAgent(t.agentType);if(!n)throw new Error(`Unknown agent type: ${t.agentType}`);const r=this.generateSessionId(),i={id:r,parentSessionId:e,agentId:n.id,description:t.description,status:"running",startTime:new Date,toolCalls:0};return this.sessions.set(r,i),this.emitEvent({type:"session_started",sessionId:r,agentId:n.id,timestamp:new Date,data:{description:t.description}}),i}static async executeTask(e,t,n){const r=WW.getAgent(e.agentId);if(!r)throw new Error(`Agent ${e.agentId} not found`);try{const i=this.buildSystemPrompt(r,t),o=this.getAgentTools(r),s=this.getModel(r,n),a=await async function({model:e,tools:t,toolChoice:n,system:r,prompt:i,messages:o,maxRetries:s,abortSignal:a,headers:l,stopWhen:u=UE(1),experimental_output:c,experimental_telemetry:d,providerOptions:p,experimental_activeTools:f,activeTools:h=f,experimental_prepareStep:g,prepareStep:A=g,experimental_repairToolCall:m,experimental_download:y,experimental_context:b,_internal:{generateId:v=qE,currentDate:E=()=>new Date}={},onStepFinish:I,...w}){const C=Jv(e),_=NE(u),{maxRetries:B,retry:D}=FE({maxRetries:s,abortSignal:a}),S=rE(w),k=wA(null!=l?l:{},`ai/${Vv}`),x=EE({model:C,telemetry:d,headers:k,settings:{...S,maxRetries:B}}),Q=await yE({system:r,prompt:i,messages:o}),N=_E(d);try{return await BE({name:"ai.generateText",attributes:SE({telemetry:d,attributes:{...vE({operationId:"ai.generateText",telemetry:d}),...x,"ai.model.provider":C.provider,"ai.model.id":C.modelId,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:i,messages:o})}}}),tracer:N,fn:async e=>{var i,o,s,l,u,f,g;const B=rE(w);let S,T=[],R=[];const F=[],M=[];do{const e=[...Q.messages,...F],_=await(null==A?void 0:A({model:C,steps:M,stepNumber:M.length,messages:e})),O=await nE({prompt:{system:null!=(i=null==_?void 0:_.system)?i:Q.system,messages:null!=(o=null==_?void 0:_.messages)?o:e},supportedUrls:await C.supportedUrls,download:y}),$=Jv(null!=(s=null==_?void 0:_.model)?s:C),{toolChoice:L,tools:P}=iE({tools:t,toolChoice:null!=(l=null==_?void 0:_.toolChoice)?l:n,activeTools:null!=(u=null==_?void 0:_.activeTools)?u:h});S=await D(()=>{var e;return BE({name:"ai.generateText.doGenerate",attributes:SE({telemetry:d,attributes:{...vE({operationId:"ai.generateText.doGenerate",telemetry:d}),...x,"ai.model.provider":$.provider,"ai.model.id":$.modelId,"ai.prompt.messages":{input:()=>kE(O)},"ai.prompt.tools":{input:()=>null==P?void 0:P.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>null!=L?JSON.stringify(L):void 0},"gen_ai.system":$.provider,"gen_ai.request.model":$.modelId,"gen_ai.request.frequency_penalty":w.frequencyPenalty,"gen_ai.request.max_tokens":w.maxOutputTokens,"gen_ai.request.presence_penalty":w.presencePenalty,"gen_ai.request.stop_sequences":w.stopSequences,"gen_ai.request.temperature":null!=(e=w.temperature)?e:void 0,"gen_ai.request.top_k":w.topK,"gen_ai.request.top_p":w.topP}}),tracer:N,fn:async e=>{var t,n,r,i,o,s,l,u;const f=await $.doGenerate({...B,tools:P,toolChoice:L,responseFormat:null==c?void 0:c.responseFormat,prompt:O,providerOptions:p,abortSignal:a,headers:k}),h={id:null!=(n=null==(t=f.response)?void 0:t.id)?n:v(),timestamp:null!=(i=null==(r=f.response)?void 0:r.timestamp)?i:E(),modelId:null!=(s=null==(o=f.response)?void 0:o.modelId)?s:$.modelId,headers:null==(l=f.response)?void 0:l.headers,body:null==(u=f.response)?void 0:u.body};return e.setAttributes(SE({telemetry:d,attributes:{"ai.response.finishReason":f.finishReason,"ai.response.text":{output:()=>ME(f.content)},"ai.response.toolCalls":{output:()=>{const e=ZE(f.content);return null==e?void 0:JSON.stringify(e)}},"ai.response.id":h.id,"ai.response.model":h.modelId,"ai.response.timestamp":h.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(f.providerMetadata),"ai.usage.promptTokens":f.usage.inputTokens,"ai.usage.completionTokens":f.usage.outputTokens,"gen_ai.response.finish_reasons":[f.finishReason],"gen_ai.response.id":h.id,"gen_ai.response.model":h.modelId,"gen_ai.usage.input_tokens":f.usage.inputTokens,"gen_ai.usage.output_tokens":f.usage.outputTokens}})),{...f,response:h}}})});const j=await Promise.all(S.content.filter(e=>"tool-call"===e.type).map(n=>LE({toolCall:n,tools:t,repairToolCall:m,system:r,messages:e})));for(const n of j){if(n.invalid)continue;const r=t[n.toolName];null!=(null==r?void 0:r.onInputAvailable)&&await r.onInputAvailable({input:n.input,toolCallId:n.toolCallId,messages:e,abortSignal:a,experimental_context:b})}const U=j.filter(e=>e.invalid&&e.dynamic);R=[];for(const t of U)R.push({type:"tool-error",toolCallId:t.toolCallId,toolName:t.toolName,input:t.input,error:BA(t.error),dynamic:!0});T=j.filter(e=>!e.providerExecuted),null!=t&&R.push(...await JE({toolCalls:T.filter(e=>!e.invalid),tools:t,tracer:N,telemetry:d,messages:e,abortSignal:a,experimental_context:b}));const z=VE({content:S.content,toolCalls:j,toolOutputs:R});F.push(...WE({content:z,tools:t}));const G=new jE({content:z,finishReason:S.finishReason,usage:S.usage,warnings:S.warnings,providerMetadata:S.providerMetadata,request:null!=(f=S.request)?f:{},response:{...S.response,messages:structuredClone(F)}});nv(null!=(g=S.warnings)?g:[]),M.push(G),await(null==I?void 0:I(G))}while(T.length>0&&R.length===T.length&&!(await zE({stopConditions:_,steps:M})));e.setAttributes(SE({telemetry:d,attributes:{"ai.response.finishReason":S.finishReason,"ai.response.text":{output:()=>ME(S.content)},"ai.response.toolCalls":{output:()=>{const e=ZE(S.content);return null==e?void 0:JSON.stringify(e)}},"ai.response.providerMetadata":JSON.stringify(S.providerMetadata),"ai.usage.promptTokens":S.usage.inputTokens,"ai.usage.completionTokens":S.usage.outputTokens}}));const O=M[M.length-1];return new KE({steps:M,resolvedOutput:await(null==c?void 0:c.parseOutput({text:O.text},{response:O.response,usage:O.usage,finishReason:O.finishReason}))})}})}catch(qK){throw bE(qK)}}({model:s,system:i,prompt:t.prompt,tools:o,stopWhen:UE(r.maxToolCalls||10)}),l={success:!0,agentUsed:r.id,summary:this.extractSummary(a.text),fullResponse:a.text,toolsUsed:this.extractToolUsage(a.toolCalls),metadata:{totalTokens:a.usage?.totalTokens,toolRoundtrips:a.toolCalls?.length||0}};return e.status="completed",e.endTime=new Date,e.result=l,this.emitEvent({type:"session_completed",sessionId:e.id,agentId:r.id,timestamp:new Date,data:{result:l}}),l}catch(qK){const n=qK instanceof Error?qK.message:String(qK);e.status="failed",e.endTime=new Date;const i={success:!1,agentUsed:r.id,summary:`Task failed: ${n}`,fullResponse:n,toolsUsed:[]};return e.result=i,this.emitEvent({type:"session_failed",sessionId:e.id,agentId:r.id,timestamp:new Date,data:{error:n}}),i}}static abortSession(e){const t=this.sessions.get(e);return!(!t||"running"!==t.status)&&(t.status="aborted",t.endTime=new Date,this.emitEvent({type:"session_aborted",sessionId:e,agentId:t.agentId,timestamp:new Date,data:{}}),!0)}static getSession(e){return this.sessions.get(e)||null}static getSessionsByParent(e){return Array.from(this.sessions.values()).filter(t=>t.parentSessionId===e)}static onEvent(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t),()=>{const n=this.eventHandlers.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}}static emitEvent(e){(this.eventHandlers.get(e.sessionId)||[]).forEach(t=>{try{t(e)}catch(qK){ex.error("Error in event handler:",qK)}})}static buildSystemPrompt(e,t){return`${e.systemPrompt||""}\n\n${t.sessionContext?`\nWorking Directory: ${t.sessionContext.workingDirectory}\nProject Root: ${t.sessionContext.projectRoot}\n`:""}\nAvailable Tools:\n${Object.entries(e.tools).filter(([e,t])=>t).map(([e,t])=>`- ${e}`).join("\n")}\n\nTask: ${t.description}\n\nInstructions: ${t.prompt}\n\nIMPORTANT:\n1. Focus on your specialized role and expertise\n2. Use tools efficiently and provide clear summaries\n3. If you cannot complete the task with your available tools, explain why\n4. Always provide a comprehensive final summary of what you accomplished`}static getAgentTools(e){const t={};for(const[n,r]of Object.entries(e.tools))r&&tq[n]&&(t[n]=tq[n]);return t}static getModel(e,t){const n={...{anthropic:"https://backend-service-prod.embedder.dev/api/v1/proxy/anthropic/",openai:"https://backend-service-prod.embedder.dev/api/v1/proxy/openai/",google:"https://backend-service-prod.embedder.dev/api/v1/proxy/google/"},...t?.baseUrls},r=t?.headers||{};if(e.model){if("openai"===e.model.providerID){return vF({baseURL:n.openai,apiKey:"embedder-cli",headers:r})(e.model.modelID)}if("anthropic"===e.model.providerID){return GF({baseURL:n.anthropic,apiKey:"embedder-cli",headers:r})(e.model.modelID)}if("google"===e.model.providerID){return uR({baseURL:n.google,apiKey:"embedder-cli",headers:r})(e.model.modelID)}}return uR({baseURL:n.google,apiKey:"embedder-cli",headers:r})("gemini-2.5-pro")}static extractSummary(e){const t=e.split("\n").filter(e=>e.trim());for(const r of t)if(r.toLowerCase().includes("summary:")||r.toLowerCase().includes("result:")||r.toLowerCase().includes("completed:"))return r.replace(/^[^:]*:\s*/,"").trim();const n=t.find(e=>e.length>10);return n?n.length>100?n.substring(0,97)+"...":n:"Task completed"}static extractToolUsage(e){return e?e.map(e=>({toolName:e.toolName||"unknown",status:!1!==e.result?.success?"success":"error",summary:e.result?.summary||e.result?.llmContent||"Tool executed"})):[]}static generateSessionId(){return`agent_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}static cleanup(){const e=Array.from(this.sessions.values()).sort((e,t)=>(t.endTime||t.startTime).getTime()-(e.endTime||e.startTime).getTime());if(e.length>50){e.slice(50).forEach(e=>{this.sessions.delete(e.id),this.eventHandlers.delete(e.id)})}}}const JW=Mz({metadata:{name:"task",displayName:"Task Delegation",description:"Delegate complex, multi-step tasks to specialized agents",category:"system",isOutputMarkdown:!0,canStream:!0,requiresConfirmation:!1},inputSchema:ug({description:mh().min(3).max(50).describe("A short (3-5 words) description of the task"),prompt:mh().min(10).describe("Detailed instructions for the agent to perform the task"),agentType:mh().describe("The type of specialized agent to use for this task")}),validateParams:e=>{if(!WW.getAgent(e.agentType)){const t=WW.getAgentIds();return`Unknown agent type: ${e.agentType}. Available agents: ${t.join(", ")}`}return e.description.split(" ").length>8?"Description should be 3-5 words, not a full sentence":null},getDescription:e=>`Delegating "${e.description}" to ${e.agentType} agent`,async shouldConfirm(e,t){const n=WW.getAgent(e.agentType);return n?n.autoInvokable?null:{type:"execute",title:`Delegate Task to ${n.displayName}`,description:`Agent "${n.displayName}" will perform: ${e.description}\n\nTask Details: ${e.prompt}\n\nThis agent has access to the following tools:\n${Object.entries(n.tools).filter(([e,t])=>t).map(([e,t])=>`• ${e}`).join("\n")}`,affectedPaths:[],isDestructive:Object.entries(n.tools).some(([e,t])=>t&&["writeFile","editFile","shell","build"].includes(e))}:null},async execute(e,t){try{const n=WW.getAgent(e.agentType);if(!n)return{success:!1,llmContent:`Error: Unknown agent type "${e.agentType}"`,summary:"Invalid agent type"};const r={description:e.description,prompt:e.prompt,agentType:e.agentType,sessionContext:{workingDirectory:t.workingDirectory,projectRoot:t.projectRoot,teamId:t.teamId,projectId:t.projectId}},i=await qW.createSession(t.sessionId||"unknown",r);if(t.updateOutput){const e=qW.onEvent(i.id,e=>{if("tool_executed"===e.type&&t.updateOutput){const n=e.data;t.updateOutput(`🔧 ${n.toolName}: ${n.summary||"executed"}\n`)}});setTimeout(e,3e5)}const o=function(e){let t=process.env.EMBEDDER_FIREBASE_TOKEN;if(!t)try{const e=fT();t=e?.accessToken}catch(qK){}const n={"x-platform-type":process.platform,"x-sandbox-type":"sandbox-exec"===process.env.SANDBOX?"exec":null!=process.env.SANDBOX?"generic":"none","x-folder-type":kT()?"versioned":"non-versioned","x-client-type":"cli"};t&&(n.Authorization=`Bearer ${t}`);e.sessionId&&(n["x-session-id"]=e.sessionId);e.projectId&&(n["x-project-id"]=e.projectId);n["x-agent-mode"]="act",e.environmentContext&&(n["x-working-directory"]=e.workingDirectory,n["x-project-type"]=e.environmentContext.projectType,n["x-has-git"]=e.environmentContext.isGitRepository.toString(),n["x-context-timestamp"]=e.environmentContext.dateTime);return{headers:n,baseUrls:{anthropic:"https://backend-service-prod.embedder.dev/api/v1/proxy/anthropic/",openai:"https://backend-service-prod.embedder.dev/api/v1/proxy/openai/",google:"https://backend-service-prod.embedder.dev/api/v1/proxy/google/"}}}(t),s=await qW.executeTask(i,r,o),a=function(e,t){const n=t.success?"✅":"❌",r=t.toolsUsed?.length>0?`\n\n**Tools Used:**\n${t.toolsUsed.map(e=>`• ${e.toolName}: ${e.summary}`).join("\n")}`:"";return`## ${n} ${e} Task Result\n\n**Summary:** ${t.summary}\n\n**Details:**\n${t.fullResponse}${r}`}(n.displayName,s);return{success:s.success,llmContent:a,summary:`${n.displayName}: ${s.summary}`,metadata:{agentUsed:s.agentUsed,toolsUsed:s.toolsUsed,sessionId:i.id,...s.metadata}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`**Task Execution Failed**\n\nError: ${t}`,summary:`Task failed: ${t}`}}}});const KW=ug({label:mh().min(1).max(50).describe("The display text for this option"),description:mh().min(1).describe("Explanation of what this option means")}),ZW=ug({question:mh().min(1).describe("The complete question to ask the user (should end with '?')"),header:mh().min(1).max(12).describe("Very short label displayed as a chip/tag (max 12 chars)"),options:ag(KW).min(2).max(4).describe("The available choices (2-4 options)"),multiSelect:Hh().describe("Set to true to allow multiple selections instead of just one")}),VW=ug({questions:ag(ZW).min(1).max(4).describe("Array of 1-4 related questions to ask the user. IMPORTANT: Ask multiple questions at once when drilling down (e.g., ask about category, subcategory, and specific options together). This creates a better user experience than asking questions one at a time.")});let YW=null;function XW(e){YW=e}const eq=Mz({metadata:{name:"askQuestion",displayName:"Ask Question",description:"Ask the user interactive questions with multiple-choice options. IMPORTANT: Ask multiple related questions at once (up to 4) rather than one at a time - this provides a much better UX. For example, if determining a hardware setup, ask about family, specific chip, and configuration preferences all together. Each question supports 2-4 options and can be single or multi-select.",category:"development",icon:"?",isOutputMarkdown:!1},inputSchema:VW,validateParams:({questions:e})=>{const t=e.map(e=>e.header),n=new Set(t);if(t.length!==n.size)return"All questions must have unique headers";for(const r of e)if(!r.question.trim().endsWith("?"))return"All questions should end with a question mark";return null},getDescription:({questions:e})=>{const t=e.length,n=e[0]?.header||"Question";return 1===t?`Asking: ${n}`:`Asking ${t} questions`},getLocations:()=>[],execute:async({questions:e},t)=>{try{if(!YW)return{success:!1,llmContent:"Question handler not initialized. This tool requires UI integration to collect user responses.",summary:"Failed to ask questions"};const t={questions:e,id:`question-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,timestamp:Date.now()},n=await YW(t),r=Object.entries(n.answers).map(([e,t])=>`**${e}**: ${t.isCustom?`Custom: ${t.answers.join(", ")}`:t.answers.join(", ")}`).join("\n");return{success:!0,summary:`User answered ${Object.keys(n.answers).length} question(s)`,llmContent:`User responses:\n${r}`,metadata:{promptId:t.id,responseId:n.promptId,answers:n.answers,timestamp:n.timestamp}}}catch(qK){const t=qK instanceof Error?qK.message:String(qK);return{success:!1,llmContent:`Error asking questions: ${t}`,returnDisplay:`Error asking questions: ${t}`,summary:"Failed to ask questions"}}}}),tq={readFile:UH,readManyFiles:JH,writeFile:aW,editFile:vW,listDirectory:IW,grep:BW,glob:DW,documentSearch:zW,webSearch:GW,build:RW,todoWrite:jW,todoRead:UW,askQuestion:eq,shell:TW,serialMonitor:PW,task:JW},nq={readFile:!0,readManyFiles:!0,listDirectory:!0,grep:!0,glob:!0,documentSearch:!0,todoRead:!0,todoWrite:!0,askQuestion:!0,writeFile:!1,editFile:!1,shell:!1,build:!1,serialMonitor:!1};function rq({suggestions:e,selectedIndex:t,width:n}){if(!e||0===e.length)return null;const r=Math.max(0,Math.min(t-8+1,e.length-8)),i=Math.min(r+8,e.length),o=e.slice(r,i),s=o.length>0?Math.max(...o.map(e=>(e.label||"").length)):12,a=Math.min(Math.max(s+2,12),Math.floor(n/3));return We.jsxs(ki,{flexDirection:"column",width:n,children:[o.map((e,i)=>{const o=r+i===t?FM:QM;return We.jsxs(ki,{flexDirection:"row",width:n,children:[We.jsx(xi,{color:o,children:" "}),We.jsx(ki,{width:a,flexShrink:0,children:We.jsx(xi,{color:o,children:e.label})}),We.jsx(ki,{flexGrow:1,children:We.jsx(xi,{color:o,children:e.description})})]},`${e.value}-${i}`)}),e.length>8&&We.jsxs(xi,{color:QM,children:["(",t+1,"/",e.length,")"]})]})}var iq,oq,sq,aq,lq,uq,cq,dq,pq,fq,hq,gq,Aq,mq,yq,bq,vq,Eq,Iq,wq,Cq,_q,Bq,Dq,Sq,kq,xq,Qq,Nq,Tq,Rq,Fq,Mq,Oq,$q,Lq,Pq,jq,Uq,zq,Gq,Hq,Wq,qq,Jq,Kq,Zq,Vq,Yq,Xq,eJ,tJ,nJ,rJ,iJ,oJ,sJ,aJ,lJ,uJ,cJ,dJ,pJ,fJ,hJ,gJ,AJ,mJ,yJ,bJ,vJ,EJ,IJ,wJ,CJ,_J,BJ,DJ,SJ,kJ,xJ,QJ,NJ,TJ,RJ,FJ,MJ,OJ,$J,LJ={exports:{}};function PJ(){if(oq)return iq;oq=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return iq={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:e,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}function jJ(){if(aq)return sq;aq=1;const e="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};return sq=e}function UJ(){return lq||(lq=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=PJ(),o=jJ(),s=(t=e.exports={}).re=[],a=t.safeRe=[],l=t.src=[],u=t.safeSrc=[],c=t.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",i],[p,r]],h=(e,t,n)=>{const r=(e=>{for(const[t,n]of f)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e})(t),i=d++;o(e,i,t),c[e]=i,l[i]=t,u[i]=r,s[i]=new RegExp(t,n?"g":void 0),a[i]=new RegExp(r,n?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),h("MAINVERSION",`(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${l[c.NONNUMERICIDENTIFIER]}|${l[c.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${l[c.NONNUMERICIDENTIFIER]}|${l[c.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${l[c.PRERELEASEIDENTIFIER]}(?:\\.${l[c.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${l[c.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[c.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${p}+`),h("BUILD",`(?:\\+(${l[c.BUILDIDENTIFIER]}(?:\\.${l[c.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${l[c.MAINVERSION]}${l[c.PRERELEASE]}?${l[c.BUILD]}?`),h("FULL",`^${l[c.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${l[c.MAINVERSIONLOOSE]}${l[c.PRERELEASELOOSE]}?${l[c.BUILD]}?`),h("LOOSE",`^${l[c.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${l[c.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${l[c.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:${l[c.PRERELEASE]})?${l[c.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:${l[c.PRERELEASELOOSE]})?${l[c.BUILD]}?)?)?`),h("XRANGE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h("COERCE",`${l[c.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",l[c.COERCEPLAIN]+`(?:${l[c.PRERELEASE]})?(?:${l[c.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",l[c.COERCE],!0),h("COERCERTLFULL",l[c.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${l[c.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",h("TILDE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${l[c.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",h("CARET",`^${l[c.LONECARET]}${l[c.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${l[c.LONECARET]}${l[c.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${l[c.GTLT]}\\s*(${l[c.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]}|${l[c.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${l[c.XRANGEPLAIN]})\\s+-\\s+(${l[c.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${l[c.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[c.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(LJ,LJ.exports)),LJ.exports}function zJ(){if(cq)return uq;cq=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return uq=n=>n?"object"!=typeof n?e:n:t}function GJ(){if(pq)return dq;pq=1;const e=/^[0-9]+$/,t=(t,n)=>{const r=e.test(t),i=e.test(n);return r&&i&&(t=+t,n=+n),t===n?0:r&&!i?-1:i&&!r?1:t<n?-1:1};return dq={compareIdentifiers:t,rcompareIdentifiers:(e,n)=>t(n,e)}}function HJ(){if(hq)return fq;hq=1;const e=jJ(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:n}=PJ(),{safeRe:r,t:i}=UJ(),o=zJ(),{compareIdentifiers:s}=GJ();class a{constructor(s,l){if(l=o(l),s instanceof a){if(s.loose===!!l.loose&&s.includePrerelease===!!l.includePrerelease)return s;s=s.version}else if("string"!=typeof s)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof s}".`);if(s.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",s,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const u=s.trim().match(l.loose?r[i.LOOSE]:r[i.FULL]);if(!u)throw new TypeError(`Invalid Version: ${s}`);if(this.raw=s,this.major=+u[1],this.minor=+u[2],this.patch=+u[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");u[4]?this.prerelease=u[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<n)return t}return e}):this.prerelease=[],this.build=u[5]?u[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(e("SemVer.compare",this.version,this.options,t),!(t instanceof a)){if("string"==typeof t&&t===this.version)return 0;t=new a(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(e){return e instanceof a||(e=new a(e,this.options)),s(this.major,e.major)||s(this.minor,e.minor)||s(this.patch,e.patch)}comparePre(t){if(t instanceof a||(t=new a(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let n=0;do{const r=this.prerelease[n],i=t.prerelease[n];if(e("prerelease compare",n,r,i),void 0===r&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===r)return-1;if(r!==i)return s(r,i)}while(++n)}compareBuild(t){t instanceof a||(t=new a(t,this.options));let n=0;do{const r=this.build[n],i=t.build[n];if(e("build compare",n,r,i),void 0===r&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===r)return-1;if(r!==i)return s(r,i)}while(++n)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&!1===n)throw new Error("invalid increment argument: identifier is empty");if(t){const e=`-${t}`.match(this.options.loose?r[i.PRERELEASELOOSE]:r[i.PRERELEASE]);if(!e||e[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(n)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);if(-1===r){if(t===this.prerelease.join(".")&&!1===n)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let r=[t,e];!1===n&&(r=[t]),0===s(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return fq=a}function WJ(){if(Aq)return gq;Aq=1;const e=HJ();return gq=(t,n,r=!1)=>{if(t instanceof e)return t;try{return new e(t,n)}catch(i){if(!r)return null;throw i}}}function qJ(){if(Rq)return Tq;Rq=1;const e=HJ();return Tq=(t,n,r)=>new e(t,r).compare(new e(n,r))}function JJ(){if(Pq)return Lq;Pq=1;const e=HJ();return Lq=(t,n,r)=>{const i=new e(t,r),o=new e(n,r);return i.compare(o)||i.compareBuild(o)}}function KJ(){if(Wq)return Hq;Wq=1;const e=qJ();return Hq=(t,n,r)=>e(t,n,r)>0}function ZJ(){if(Jq)return qq;Jq=1;const e=qJ();return qq=(t,n,r)=>e(t,n,r)<0}function VJ(){if(Zq)return Kq;Zq=1;const e=qJ();return Kq=(t,n,r)=>0===e(t,n,r)}function YJ(){if(Yq)return Vq;Yq=1;const e=qJ();return Vq=(t,n,r)=>0!==e(t,n,r)}function XJ(){if(eJ)return Xq;eJ=1;const e=qJ();return Xq=(t,n,r)=>e(t,n,r)>=0}function eK(){if(nJ)return tJ;nJ=1;const e=qJ();return tJ=(t,n,r)=>e(t,n,r)<=0}function tK(){if(iJ)return rJ;iJ=1;const e=VJ(),t=YJ(),n=KJ(),r=XJ(),i=ZJ(),o=eK();return rJ=(s,a,l,u)=>{switch(a){case"===":return"object"==typeof s&&(s=s.version),"object"==typeof l&&(l=l.version),s===l;case"!==":return"object"==typeof s&&(s=s.version),"object"==typeof l&&(l=l.version),s!==l;case"":case"=":case"==":return e(s,l,u);case"!=":return t(s,l,u);case">":return n(s,l,u);case">=":return r(s,l,u);case"<":return i(s,l,u);case"<=":return o(s,l,u);default:throw new TypeError(`Invalid operator: ${a}`)}}}function nK(){if(cJ)return uJ;cJ=1;const e=/\s+/g;class t{constructor(n,o){if(o=r(o),n instanceof t)return n.loose===!!o.loose&&n.includePrerelease===!!o.includePrerelease?n:new t(n.raw,o);if(n instanceof i)return this.raw=n.value,this.set=[[n]],this.formatted=void 0,this;if(this.options=o,this.loose=!!o.loose,this.includePrerelease=!!o.includePrerelease,this.raw=n.trim().replace(e," "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const t of this.set)if(1===t.length&&g(t[0])){this.set=[t];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&p)|(this.options.loose&&f))+":"+e,r=n.get(t);if(r)return r;const s=this.options.loose,g=s?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];e=e.replace(g,D(this.options.includePrerelease)),o("hyphen replace",e),e=e.replace(a[l.COMPARATORTRIM],u),o("comparator trim",e),e=e.replace(a[l.TILDETRIM],c),o("tilde trim",e),e=e.replace(a[l.CARETTRIM],d),o("caret trim",e);let A=e.split(" ").map(e=>m(e,this.options)).join(" ").split(/\s+/).map(e=>B(e,this.options));s&&(A=A.filter(e=>(o("loose invalid filter",e,this.options),!!e.match(a[l.COMPARATORLOOSE])))),o("range list",A);const y=new Map,b=A.map(e=>new i(e,this.options));for(const n of b){if(h(n))return[n];y.set(n.value,n)}y.size>1&&y.has("")&&y.delete("");const v=[...y.values()];return n.set(t,v),v}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(t=>A(t,n)&&e.set.some(e=>A(e,n)&&t.every(t=>e.every(e=>t.intersects(e,n)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new s(e,this.options)}catch(t){return!1}for(let n=0;n<this.set.length;n++)if(S(this.set[n],e,this.options))return!0;return!1}}uJ=t;const n=new(lJ?aJ:(lJ=1,aJ=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}})),r=zJ(),i=rK(),o=jJ(),s=HJ(),{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:c,caretTrimReplace:d}=UJ(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:f}=PJ(),h=e=>"<0.0.0-0"===e.value,g=e=>""===e.value,A=(e,t)=>{let n=!0;const r=e.slice();let i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},m=(e,t)=>(o("comp",e,t),e=E(e,t),o("caret",e),e=b(e,t),o("tildes",e),e=w(e,t),o("xrange",e),e=_(e,t),o("stars",e),e),y=e=>!e||"x"===e.toLowerCase()||"*"===e,b=(e,t)=>e.trim().split(/\s+/).map(e=>v(e,t)).join(" "),v=(e,t)=>{const n=t.loose?a[l.TILDELOOSE]:a[l.TILDE];return e.replace(n,(t,n,r,i,s)=>{let a;return o("tilde",e,t,n,r,i,s),y(n)?a="":y(r)?a=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?a=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:s?(o("replaceTilde pr",s),a=`>=${n}.${r}.${i}-${s} <${n}.${+r+1}.0-0`):a=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o("tilde return",a),a})},E=(e,t)=>e.trim().split(/\s+/).map(e=>I(e,t)).join(" "),I=(e,t)=>{o("caret",e,t);const n=t.loose?a[l.CARETLOOSE]:a[l.CARET],r=t.includePrerelease?"-0":"";return e.replace(n,(t,n,i,s,a)=>{let l;return o("caret",e,t,n,i,s,a),y(n)?l="":y(i)?l=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(s)?l="0"===n?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:a?(o("replaceCaret pr",a),l="0"===n?"0"===i?`>=${n}.${i}.${s}-${a} <${n}.${i}.${+s+1}-0`:`>=${n}.${i}.${s}-${a} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${s}-${a} <${+n+1}.0.0-0`):(o("no pr"),l="0"===n?"0"===i?`>=${n}.${i}.${s}${r} <${n}.${i}.${+s+1}-0`:`>=${n}.${i}.${s}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${s} <${+n+1}.0.0-0`),o("caret return",l),l})},w=(e,t)=>(o("replaceXRanges",e,t),e.split(/\s+/).map(e=>C(e,t)).join(" ")),C=(e,t)=>{e=e.trim();const n=t.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return e.replace(n,(n,r,i,s,a,l)=>{o("xRange",e,n,r,i,s,a,l);const u=y(i),c=u||y(s),d=c||y(a),p=d;return"="===r&&p&&(r=""),l=t.includePrerelease?"-0":"",u?n=">"===r||"<"===r?"<0.0.0-0":"*":r&&p?(c&&(s=0),a=0,">"===r?(r=">=",c?(i=+i+1,s=0,a=0):(s=+s+1,a=0)):"<="===r&&(r="<",c?i=+i+1:s=+s+1),"<"===r&&(l="-0"),n=`${r+i}.${s}.${a}${l}`):c?n=`>=${i}.0.0${l} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${s}.0${l} <${i}.${+s+1}.0-0`),o("xRange return",n),n})},_=(e,t)=>(o("replaceStars",e,t),e.trim().replace(a[l.STAR],"")),B=(e,t)=>(o("replaceGTE0",e,t),e.trim().replace(a[t.includePrerelease?l.GTE0PRE:l.GTE0],"")),D=e=>(t,n,r,i,o,s,a,l,u,c,d,p)=>`${n=y(r)?"":y(i)?`>=${r}.0.0${e?"-0":""}`:y(o)?`>=${r}.${i}.0${e?"-0":""}`:s?`>=${n}`:`>=${n}${e?"-0":""}`} ${l=y(u)?"":y(c)?`<${+u+1}.0.0-0`:y(d)?`<${u}.${+c+1}.0-0`:p?`<=${u}.${c}.${d}-${p}`:e?`<${u}.${c}.${+d+1}-0`:`<=${l}`}`.trim(),S=(e,t,n)=>{for(let r=0;r<e.length;r++)if(!e[r].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==i.ANY&&e[n].semver.prerelease.length>0){const r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0};return uJ}function rK(){if(pJ)return dJ;pJ=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(r,i){if(i=n(i),r instanceof t){if(r.loose===!!i.loose)return r;r=r.value}r=r.trim().split(/\s+/).join(" "),s("comparator",r,i),this.options=i,this.loose=!!i.loose,this.parse(r),this.semver===e?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(t){const n=this.options.loose?r[i.COMPARATORLOOSE]:r[i.COMPARATOR],o=t.match(n);if(!o)throw new TypeError(`Invalid comparator: ${t}`);this.operator=void 0!==o[1]?o[1]:"","="===this.operator&&(this.operator=""),o[2]?this.semver=new a(o[2],this.options.loose):this.semver=e}toString(){return this.value}test(t){if(s("Comparator.test",t,this.options.loose),this.semver===e||t===e)return!0;if("string"==typeof t)try{t=new a(t,this.options)}catch(n){return!1}return o(t,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new l(e.value,r).test(this.value):""===e.operator?""===e.value||new l(this.value,r).test(e.semver):(!(r=n(r)).includePrerelease||"<0.0.0-0"!==this.value&&"<0.0.0-0"!==e.value)&&(!(!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))&&(!(!this.operator.startsWith(">")||!e.operator.startsWith(">"))||(!(!this.operator.startsWith("<")||!e.operator.startsWith("<"))||(!(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))||(!!(o(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))||!!(o(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))))))}}dJ=t;const n=zJ(),{safeRe:r,t:i}=UJ(),o=tK(),s=jJ(),a=HJ(),l=nK();return dJ}function iK(){if(hJ)return fJ;hJ=1;const e=nK();return fJ=(t,n,r)=>{try{n=new e(n,r)}catch(i){return!1}return n.test(t)}}function oK(){if(BJ)return _J;BJ=1;const e=HJ(),t=rK(),{ANY:n}=t,r=nK(),i=iK(),o=KJ(),s=ZJ(),a=eK(),l=XJ();return _J=(u,c,d,p)=>{let f,h,g,A,m;switch(u=new e(u,p),c=new r(c,p),d){case">":f=o,h=a,g=s,A=">",m=">=";break;case"<":f=s,h=l,g=o,A="<",m="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(i(u,c,p))return!1;for(let e=0;e<c.set.length;++e){const r=c.set[e];let i=null,o=null;if(r.forEach(e=>{e.semver===n&&(e=new t(">=0.0.0")),i=i||e,o=o||e,f(e.semver,i.semver,p)?i=e:g(e.semver,o.semver,p)&&(o=e)}),i.operator===A||i.operator===m)return!1;if((!o.operator||o.operator===A)&&h(u,o.semver))return!1;if(o.operator===m&&g(u,o.semver))return!1}return!0}}const sK=e(function(){if($J)return OJ;$J=1;const e=UJ(),t=PJ(),n=HJ(),r=GJ(),i=WJ(),o=function(){if(yq)return mq;yq=1;const e=WJ();return mq=(t,n)=>{const r=e(t,n);return r?r.version:null}}(),s=function(){if(vq)return bq;vq=1;const e=WJ();return bq=(t,n)=>{const r=e(t.trim().replace(/^[=v]+/,""),n);return r?r.version:null}}(),a=function(){if(Iq)return Eq;Iq=1;const e=HJ();return Eq=(t,n,r,i,o)=>{"string"==typeof r&&(o=i,i=r,r=void 0);try{return new e(t instanceof e?t.version:t,r).inc(n,i,o).version}catch(s){return null}}}(),l=function(){if(Cq)return wq;Cq=1;const e=WJ();return wq=(t,n)=>{const r=e(t,null,!0),i=e(n,null,!0),o=r.compare(i);if(0===o)return null;const s=o>0,a=s?r:i,l=s?i:r,u=!!a.prerelease.length;if(l.prerelease.length&&!u){if(!l.patch&&!l.minor)return"major";if(0===l.compareMain(a))return l.minor&&!l.patch?"minor":"patch"}const c=u?"pre":"";return r.major!==i.major?c+"major":r.minor!==i.minor?c+"minor":r.patch!==i.patch?c+"patch":"prerelease"}}(),u=function(){if(Bq)return _q;Bq=1;const e=HJ();return _q=(t,n)=>new e(t,n).major}(),c=function(){if(Sq)return Dq;Sq=1;const e=HJ();return Dq=(t,n)=>new e(t,n).minor}(),d=function(){if(xq)return kq;xq=1;const e=HJ();return kq=(t,n)=>new e(t,n).patch}(),p=function(){if(Nq)return Qq;Nq=1;const e=WJ();return Qq=(t,n)=>{const r=e(t,n);return r&&r.prerelease.length?r.prerelease:null}}(),f=qJ(),h=function(){if(Mq)return Fq;Mq=1;const e=qJ();return Fq=(t,n,r)=>e(n,t,r)}(),g=function(){if($q)return Oq;$q=1;const e=qJ();return Oq=(t,n)=>e(t,n,!0)}(),A=JJ(),m=function(){if(Uq)return jq;Uq=1;const e=JJ();return jq=(t,n)=>t.sort((t,r)=>e(t,r,n))}(),y=function(){if(Gq)return zq;Gq=1;const e=JJ();return zq=(t,n)=>t.sort((t,r)=>e(r,t,n))}(),b=KJ(),v=ZJ(),E=VJ(),I=YJ(),w=XJ(),C=eK(),_=tK(),B=function(){if(sJ)return oJ;sJ=1;const e=HJ(),t=WJ(),{safeRe:n,t:r}=UJ();return oJ=(i,o)=>{if(i instanceof e)return i;if("number"==typeof i&&(i=String(i)),"string"!=typeof i)return null;let s=null;if((o=o||{}).rtl){const e=o.includePrerelease?n[r.COERCERTLFULL]:n[r.COERCERTL];let t;for(;(t=e.exec(i))&&(!s||s.index+s[0].length!==i.length);)s&&t.index+t[0].length===s.index+s[0].length||(s=t),e.lastIndex=t.index+t[1].length+t[2].length;e.lastIndex=-1}else s=i.match(o.includePrerelease?n[r.COERCEFULL]:n[r.COERCE]);if(null===s)return null;const a=s[2],l=s[3]||"0",u=s[4]||"0",c=o.includePrerelease&&s[5]?`-${s[5]}`:"",d=o.includePrerelease&&s[6]?`+${s[6]}`:"";return t(`${a}.${l}.${u}${c}${d}`,o)}}(),D=rK(),S=nK(),k=iK(),x=function(){if(AJ)return gJ;AJ=1;const e=nK();return gJ=(t,n)=>new e(t,n).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" "))}(),Q=function(){if(yJ)return mJ;yJ=1;const e=HJ(),t=nK();return mJ=(n,r,i)=>{let o=null,s=null,a=null;try{a=new t(r,i)}catch(l){return null}return n.forEach(t=>{a.test(t)&&(o&&-1!==s.compare(t)||(o=t,s=new e(o,i)))}),o}}(),N=function(){if(vJ)return bJ;vJ=1;const e=HJ(),t=nK();return bJ=(n,r,i)=>{let o=null,s=null,a=null;try{a=new t(r,i)}catch(l){return null}return n.forEach(t=>{a.test(t)&&(o&&1!==s.compare(t)||(o=t,s=new e(o,i)))}),o}}(),T=function(){if(IJ)return EJ;IJ=1;const e=HJ(),t=nK(),n=KJ();return EJ=(r,i)=>{r=new t(r,i);let o=new e("0.0.0");if(r.test(o))return o;if(o=new e("0.0.0-0"),r.test(o))return o;o=null;for(let t=0;t<r.set.length;++t){const i=r.set[t];let s=null;i.forEach(t=>{const r=new e(t.semver.version);switch(t.operator){case">":0===r.prerelease.length?r.patch++:r.prerelease.push(0),r.raw=r.format();case"":case">=":s&&!n(r,s)||(s=r);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${t.operator}`)}}),!s||o&&!n(o,s)||(o=s)}return o&&r.test(o)?o:null}}(),R=function(){if(CJ)return wJ;CJ=1;const e=nK();return wJ=(t,n)=>{try{return new e(t,n).range||"*"}catch(r){return null}}}(),F=oK(),M=function(){if(SJ)return DJ;SJ=1;const e=oK();return DJ=(t,n,r)=>e(t,n,">",r)}(),O=function(){if(xJ)return kJ;xJ=1;const e=oK();return kJ=(t,n,r)=>e(t,n,"<",r)}(),$=function(){if(NJ)return QJ;NJ=1;const e=nK();return QJ=(t,n,r)=>(t=new e(t,r),n=new e(n,r),t.intersects(n,r))}(),L=function(){if(RJ)return TJ;RJ=1;const e=iK(),t=qJ();return TJ=(n,r,i)=>{const o=[];let s=null,a=null;const l=n.sort((e,n)=>t(e,n,i));for(const t of l)e(t,r,i)?(a=t,s||(s=t)):(a&&o.push([s,a]),a=null,s=null);s&&o.push([s,null]);const u=[];for(const[e,t]of o)e===t?u.push(e):t||e!==l[0]?t?e===l[0]?u.push(`<=${t}`):u.push(`${e} - ${t}`):u.push(`>=${e}`):u.push("*");const c=u.join(" || "),d="string"==typeof r.raw?r.raw:String(r);return c.length<d.length?c:r}}(),P=function(){if(MJ)return FJ;MJ=1;const e=nK(),t=rK(),{ANY:n}=t,r=iK(),i=qJ(),o=[new t(">=0.0.0-0")],s=[new t(">=0.0.0")],a=(e,t,a)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===n){if(1===t.length&&t[0].semver===n)return!0;e=a.includePrerelease?o:s}if(1===t.length&&t[0].semver===n){if(a.includePrerelease)return!0;t=s}const c=new Set;let d,p,f,h,g,A,m;for(const n of e)">"===n.operator||">="===n.operator?d=l(d,n,a):"<"===n.operator||"<="===n.operator?p=u(p,n,a):c.add(n.semver);if(c.size>1)return null;if(d&&p){if(f=i(d.semver,p.semver,a),f>0)return null;if(0===f&&(">="!==d.operator||"<="!==p.operator))return null}for(const n of c){if(d&&!r(n,String(d),a))return null;if(p&&!r(n,String(p),a))return null;for(const e of t)if(!r(n,String(e),a))return!1;return!0}let y=!(!p||a.includePrerelease||!p.semver.prerelease.length)&&p.semver,b=!(!d||a.includePrerelease||!d.semver.prerelease.length)&&d.semver;y&&1===y.prerelease.length&&"<"===p.operator&&0===y.prerelease[0]&&(y=!1);for(const n of t){if(m=m||">"===n.operator||">="===n.operator,A=A||"<"===n.operator||"<="===n.operator,d)if(b&&n.semver.prerelease&&n.semver.prerelease.length&&n.semver.major===b.major&&n.semver.minor===b.minor&&n.semver.patch===b.patch&&(b=!1),">"===n.operator||">="===n.operator){if(h=l(d,n,a),h===n&&h!==d)return!1}else if(">="===d.operator&&!r(d.semver,String(n),a))return!1;if(p)if(y&&n.semver.prerelease&&n.semver.prerelease.length&&n.semver.major===y.major&&n.semver.minor===y.minor&&n.semver.patch===y.patch&&(y=!1),"<"===n.operator||"<="===n.operator){if(g=u(p,n,a),g===n&&g!==p)return!1}else if("<="===p.operator&&!r(p.semver,String(n),a))return!1;if(!n.operator&&(p||d)&&0!==f)return!1}return!(d&&A&&!p&&0!==f||p&&m&&!d&&0!==f||b||y)},l=(e,t,n)=>{if(!e)return t;const r=i(e.semver,t.semver,n);return r>0?e:r<0||">"===t.operator&&">="===e.operator?t:e},u=(e,t,n)=>{if(!e)return t;const r=i(e.semver,t.semver,n);return r<0?e:r>0||"<"===t.operator&&"<="===e.operator?t:e};return FJ=(t,n,r={})=>{if(t===n)return!0;t=new e(t,r),n=new e(n,r);let i=!1;e:for(const e of t.set){for(const t of n.set){const n=a(e,t,r);if(i=i||null!==n,n)continue e}if(i)return!1}return!0}}();return OJ={parse:i,valid:o,clean:s,inc:a,diff:l,major:u,minor:c,patch:d,prerelease:p,compare:f,rcompare:h,compareLoose:g,compareBuild:A,sort:m,rsort:y,gt:b,lt:v,eq:E,neq:I,gte:w,lte:C,cmp:_,coerce:B,Comparator:D,Range:S,satisfies:k,toComparators:x,maxSatisfying:Q,minSatisfying:N,minVersion:T,validRange:R,outside:F,gtr:M,ltr:O,intersects:$,simplifyRange:L,subset:P,SemVer:n,re:e.re,src:e.src,tokens:e.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers}}()),aK="2.1.0";async function lK(){const e=await(t="@embedder/embedder",fetch(`https://registry.npmjs.org/${t}`).then(e=>e.ok?e.json():null).catch(()=>null));var t;if(!e)return null;const n=Object.keys(e.versions),r=sK.maxSatisfying(n,"*");if(!r||sK.gte(aK,r))return null;const i=Object.values(e.versions).find(e=>sK.eq(e.version,r));return i?{command:`npm i -g ${i._id}`,currentVersion:aK,version:i.version}:null}const uK=P(ke);let cK=null;async function dK(e){const t=Date.now();if(cK&&t-cK.timestamp<3e4)return cK.branch;const n=await async function(e){try{const t=e||process.cwd();try{await uK("git rev-parse --git-dir",{cwd:t})}catch{return{branch:"not-git",isRepository:!1,error:"Not a git repository"}}const{stdout:n}=await uK("git branch --show-current",{cwd:t}),r=n.trim();if(!r)try{const{stdout:e}=await uK("git rev-parse --short HEAD",{cwd:t});return{branch:`detached-${e.trim()}`,isRepository:!0}}catch{return{branch:"unknown",isRepository:!0,error:"Unable to determine branch"}}return{branch:r,isRepository:!0}}catch(qK){return{branch:"error",isRepository:!1,error:qK instanceof Error?qK.message:"Unknown git error"}}}(e);return cK={branch:n.branch,timestamp:t},n.branch}function pK({conversation:e,index:t,isSelected:n,formatRelativeTime:r}){const[i,o]=qe.useState("loading..."),{columns:s}=oL();qe.useEffect(()=>{dK().then(e=>o(e)).catch(()=>o("unknown"))},[]);const a=n?"blue":"gray",l=n?"white":"gray",u=n?"cyan":"gray",c=n?"green":"gray",d=(e,t)=>e.length<=t?e:e.substring(0,t-3)+"...",p=Math.max(20,s-55-10),f=(e=>{try{const t=new Date(e),n=String(t.getMonth()+1).padStart(2,"0");return`${n}/${String(t.getDate()).padStart(2,"0")}`}catch{return r(e)}})(e.lastModified),h=r(e.lastModified);return We.jsxs(ki,{flexDirection:"row",width:"100%",children:[We.jsx(ki,{width:6,children:We.jsxs(xi,{color:a,children:[n?"❯ ":" ",t,"."]})}),We.jsx(ki,{width:13,children:We.jsx(xi,{color:l,children:d(h,12)})}),We.jsx(ki,{width:13,children:We.jsx(xi,{color:l,children:d(f,12)})}),We.jsx(ki,{width:8,children:We.jsx(xi,{color:u,children:e.messageCount})}),We.jsx(ki,{width:15,children:We.jsx(xi,{color:c,children:d(i,14)})}),We.jsx(ki,{flexGrow:1,width:p,children:We.jsx(xi,{color:l,wrap:"truncate-end",children:d(e.preview||"No preview available",p)})})]})}function fK({isOpen:e,onClose:t,onSelect:n}){const{listConversations:r}=BM(),[i,o]=qe.useState([]),[s,a]=qe.useState(0),[l,u]=qe.useState(!0),[c,d]=qe.useState(null),{rows:p}=oL();qe.useEffect(()=>{if(!e)return;(async()=>{u(!0),d(null);try{const e=await r();o(e),a(0)}catch(e){d(e instanceof Error?e.message:"Failed to load conversations")}finally{u(!1)}})()},[e,r]),Gi((r,o)=>{if(e)if(o.upArrow||"k"===r)a(e=>Math.max(0,e-1));else if(o.downArrow||"j"===r)a(e=>Math.min(i.length-1,e+1));else{if(o.return&&i.length>0){const e=i[s];return void(e&&n(e.name).then(()=>{t()}).catch(e=>{d(e instanceof Error?e.message:"Failed to load conversation")}))}(o.escape||"q"===r)&&t()}},{isActive:e});const f=qe.useCallback(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/864e5);if(0===r){const e=Math.floor(n/36e5);if(0===e){const e=Math.floor(n/6e4);return e<=1?"just now":`${e}m ago`}return`${e}h ago`}return 1===r?"1 day ago":r<7?`${r} days ago`:t.toLocaleDateString()},[]),{visibleConversations:h,visibleStartIndex:g,visibleEndIndex:A}=qe.useMemo(()=>{const e=Math.min(50,Math.max(5,Math.floor((p-15)/1)));let t=Math.max(0,s-Math.floor(e/2)),n=Math.min(i.length,t+e);n-t<e&&i.length>=e&&(t=Math.max(0,n-e));return{visibleConversations:i.slice(t,n),visibleStartIndex:t,visibleEndIndex:n}},[i,s,p]);return e?We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{flexDirection:"column",borderStyle:"round",borderColor:"blue",padding:1,width:"98%",height:"98%",children:[We.jsxs(ki,{marginBottom:1,children:[We.jsx(xi,{bold:!0,color:"blue",children:"> /resume"}),We.jsx(ki,{marginLeft:2,children:We.jsx(xi,{color:"gray",children:"(↑↓ to navigate, Enter to select, Esc to close)"})})]}),!l&&!c&&i.length>0&&We.jsxs(ki,{marginBottom:1,flexDirection:"row",width:"100%",children:[We.jsx(ki,{width:6,children:We.jsx(xi,{color:"gray"})}),We.jsx(ki,{width:13,children:We.jsx(xi,{color:"gray",children:"Modified"})}),We.jsx(ki,{width:13,children:We.jsx(xi,{color:"gray",children:"Created"})}),We.jsx(ki,{width:8,children:We.jsx(xi,{color:"gray",children:"Msgs"})}),We.jsx(ki,{width:15,children:We.jsx(xi,{color:"gray",children:"Git Branch"})}),We.jsx(ki,{flexGrow:1,children:We.jsx(xi,{color:"gray",children:"Summary"})})]}),We.jsxs(ki,{flexDirection:"column",flexGrow:1,children:[l&&We.jsx(ki,{justifyContent:"center",alignItems:"center",minHeight:3,children:We.jsx(xi,{color:"yellow",children:"Loading conversations..."})}),c&&We.jsx(ki,{justifyContent:"center",alignItems:"center",minHeight:3,children:We.jsxs(xi,{color:"red",children:["Error: ",c]})}),!l&&!c&&0===i.length&&We.jsx(ki,{justifyContent:"center",alignItems:"center",minHeight:3,children:We.jsx(xi,{color:"gray",children:"No saved conversations found."})}),!l&&!c&&i.length>0&&We.jsxs(ki,{flexDirection:"column",children:[g>0&&We.jsx(ki,{children:We.jsxs(xi,{color:"gray",children:["↑ ",g," more above..."]})}),h.map((e,t)=>{const n=g+t,r=n===s;return We.jsx(pK,{conversation:e,index:n+1,isSelected:r,formatRelativeTime:f},e.id)}),A<i.length&&We.jsx(ki,{children:We.jsxs(xi,{color:"gray",children:["↓ ",i.length-A," more below..."]})})]})]}),!l&&!c&&i.length>0&&We.jsx(ki,{marginTop:1,borderTop:!0,borderColor:"gray",paddingTop:1,children:We.jsxs(xi,{color:"gray",children:["Showing ",g+1,"-",A," of ",i.length," ","conversation",1!==i.length?"s":""," • Selected: ",s+1]})})]})}):null}function hK({models:e,selectedModel:t,selectedIndex:n,width:r}){return e&&0!==e.length?We.jsxs(ki,{flexDirection:"column",width:r,borderStyle:"single",paddingX:1,children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Select model"})}),We.jsx(xi,{color:"dim",dimColor:!0,children:"Switch between AI models. Applies to this session and future embedder sessions."}),We.jsx(ki,{marginTop:1,marginBottom:1,flexDirection:"column",children:e.map((e,r)=>{const i=r===n,o=t&&e.provider===t.provider&&e.name===t.name,s=i?FM:QM;return We.jsx(ki,{flexDirection:"row",children:We.jsxs(xi,{color:s,children:[i?"❯":" "," ",r+1,". ",e.name," ",o?"✔":""]})},`${e.provider}-${e.name}`)})}),We.jsx(xi,{color:"dim",children:"Enter to confirm · Esc to exit"})]}):null}const gK=[{name:"resume",description:"Resume a conversation",shortcut:"Ctrl+O"},{name:"clear",description:"Clear conversation history",shortcut:"Ctrl+R"},{name:"compress",description:"Compress conversation history to save context"},{name:"model",description:"Select which AI model to use",shortcut:"Ctrl+B"},{name:"rewind",description:"View and revert to previous conversation states"},{name:"undo",description:"Undo the last query"},{name:"yolo",description:"Toggle auto-approval of all tool calls"},{name:"project",description:"Switch to a different project in the current team"},{name:"init",description:"Create EMBEDDER.md with project contexts"},{name:"doc",description:"Upload hardware docs and datasheets to improve AI accuracy"},{name:"help",description:"Show available commands and shortcuts"},{name:"exit",description:"Close the application"}];function AK({version:e,currentTab:t,width:n}){const r="https://docs.embedder.dev";return We.jsxs(ki,{flexDirection:"column",width:n,paddingX:1,children:[We.jsxs(ki,{marginBottom:1,flexDirection:"row",gap:1,children:[We.jsxs(xi,{children:["Embedder v",e]}),We.jsx(xi,{children:" "}),We.jsx(xi,{backgroundColor:"general"===t?"cyan":void 0,color:"general"===t?"black":"gray",children:" general "}),We.jsx(xi,{children:" "}),We.jsx(xi,{backgroundColor:"commands"===t?"cyan":void 0,color:"commands"===t?"black":"gray",children:" commands "}),We.jsx(xi,{children:" "}),We.jsx(xi,{color:"gray",children:"(tab to cycle)"})]}),"general"===t&&We.jsxs(ki,{flexDirection:"column",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:"Embedder is a coding agent designed for firmware development. It understands your codebase, documentation and interacts with your hardware. Upload your documentation on the web console and create EMBEDDER.md using /init for the best results."})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Shortcuts"})}),We.jsxs(ki,{flexDirection:"column",marginBottom:1,children:[We.jsxs(ki,{children:[We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"/"})," for commands"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + d"})," for docs"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + b"})," to select model"]})})]}),We.jsxs(ki,{children:[We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"@"})," for file paths"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + r"})," to clear chat"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + o"})," to resume"]})})]}),We.jsxs(ki,{children:[We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"tab"})," to switch mode"]})}),We.jsx(ki,{width:28,children:We.jsxs(xi,{children:[We.jsx(xi,{color:"cyan",children:"ctrl + c"})," (2x) to exit"]})})]})]}),We.jsx(ki,{marginBottom:1,marginTop:1,children:We.jsxs(xi,{children:["For more help: ",We.jsx(xi,{color:"blue",children:r})]})}),We.jsx(ki,{children:We.jsx(xi,{color:"gray",children:"Esc to exit"})})]}),"commands"===t&&We.jsxs(ki,{flexDirection:"column",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:"Browse available commands:"})}),We.jsx(ki,{flexDirection:"column",marginBottom:1,children:gK.map((e,t)=>We.jsx(ki,{children:We.jsxs(xi,{children:[" ",We.jsxs(xi,{bold:!0,color:"cyan",children:["/",e.name]})," ".repeat(Math.max(1,20-e.name.length)),We.jsx(xi,{children:e.description}),e.shortcut&&We.jsxs(xi,{color:"gray",children:[" - ",e.shortcut]})]})},e.name))}),We.jsx(ki,{marginBottom:1,marginTop:1,children:We.jsxs(xi,{children:["For more help: ",We.jsx(xi,{color:"blue",children:r})]})}),We.jsx(ki,{children:We.jsx(xi,{color:"gray",children:"Esc to exit"})})]})]})}const mK=b(Q);class yK{gitDir;workTree;initialized=!1;trackedFiles=new Set;constructor(e=process.cwd()){this.workTree=e;const t=this.getProjectHash(e);this.gitDir=C(g(),".embedder","snapshots",t)}getProjectHash(e){return ve("sha256").update(e).digest("hex").substring(0,16)}registerFile(e){this.trackedFiles.add(e)}isFileTracked(e){return this.trackedFiles.has(e)}getTrackedFiles(){return Array.from(this.trackedFiles)}setTrackedFiles(e){this.trackedFiles=new Set(e)}clearTrackedFiles(){this.trackedFiles.clear()}async initialize(){if(!this.initialized)try{await c.mkdir(this.gitDir,{recursive:!0});try{return await mK(`git --git-dir="${this.gitDir}" rev-parse --git-dir`),void(this.initialized=!0)}catch{}await mK("git init",{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}}),this.initialized=!0}catch(qK){throw this.initialized=!1,qK}}async track(){if(this.initialized||await this.initialize(),0===this.trackedFiles.size)return null;try{for(const n of this.trackedFiles)try{const e=_(this.workTree,n);await c.access(n).catch(()=>{}),await mK(`git add "${e}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}})}catch(e){}const{stdout:t}=await mK("git write-tree",{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}});return t.trim()}catch(qK){return null}}async patch(e){this.initialized||await this.initialize();try{for(const e of this.trackedFiles)try{const t=_(this.workTree,e);await c.access(e).catch(()=>{}),await mK(`git add "${t}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}})}catch(t){}const n=[];for(const t of this.trackedFiles)try{const r=_(this.workTree,t),{stdout:i}=await mK(`git diff --name-only ${e} -- "${r}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}});i.trim()&&n.push(t)}catch(qK){}return{hash:e,files:n}}catch(qK){return{hash:e,files:[]}}}async revert(e){this.initialized||await this.initialize();const t=new Set;try{for(const n of e)for(const e of n.files)if(!t.has(e))try{const r=_(this.workTree,e);await mK(`git checkout ${n.hash} -- "${r}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}}),t.add(e)}catch(qK){const i=_(this.workTree,e);try{const t=await mK(`git ls-tree ${n.hash} -- "${i}"`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}});t.stdout&&t.stdout.trim()||await c.unlink(e).catch(()=>{})}catch{await c.unlink(e).catch(()=>{})}t.add(e)}}catch(qK){throw qK}}async diff(e,t){this.initialized||await this.initialize();try{const n=t||"HEAD",{stdout:r}=await mK(`git diff --stat ${e} ${n}`,{cwd:this.workTree,env:{...process.env,GIT_DIR:this.gitDir,GIT_WORK_TREE:this.workTree}}),i=r.trim().split("\n"),o=i[i.length-1];if(!o)return{added:0,deleted:0};const s=o.match(/(\d+)\s+insertions?\(\+\)/),a=o.match(/(\d+)\s+deletions?\(-\)/);return{added:s&&s[1]?parseInt(s[1],10):0,deleted:a&&a[1]?parseInt(a[1],10):0}}catch(qK){return{added:0,deleted:0}}}async cleanup(){try{await c.rm(this.gitDir,{recursive:!0,force:!0}),this.initialized=!1}catch(qK){}}}const bK=({entry:e,isSelected:t,isCurrent:n})=>{const r=(()=>{if(n)return"";if(0===e.filesChanged)return"No code changes";const t=[];e.filesChanged>0&&t.push(`${e.filesChanged} file${e.filesChanged>1?"s":""} edited`);const r=[];return e.linesAdded&&e.linesAdded>0&&r.push(`+${e.linesAdded}`),e.linesDeleted&&e.linesDeleted>0&&r.push(`-${e.linesDeleted}`),r.length>0&&t.push(r.join(" ")),t.join(" ")})();return We.jsxs(ki,{flexDirection:"column",marginBottom:n?1:0,children:[We.jsx(ki,{children:We.jsxs(xi,{color:t?"cyan":void 0,bold:t,children:[t?"❯ ":" ",e.userPrompt]})}),r&&We.jsx(ki,{marginLeft:2,children:We.jsx(xi,{dimColor:!0,color:e.filesChanged>0?"green":"gray",children:r})})]})},vK=({messages:e,onRevert:t,onClose:n,snapshotService:r})=>{const[i,o]=qe.useState([]),[s,a]=qe.useState(0),[l,u]=qe.useState(!1);qe.useEffect(()=>{(async()=>{const t=[];let n=0;for(const i of e)if("role"in i&&"user"===i.role){const e=i;if(e.hidden)continue;let o="";"string"==typeof e.content?o=e.content:Array.isArray(e.content)&&(o=e.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("\n"));const s=o.length>80?o.substring(0,77)+"...":o,a=e.patch;let l,u,c=0;if(a){const e=Array.isArray(a)?a:[a],t=new Set;for(const n of e)n.files.forEach(e=>t.add(e));c=t.size;const i=e[0],o=e[e.length-1];if(r&&i?.hash&&o?.afterHash)try{const e=await r.diff(i.hash,o.afterHash);l=e.added,u=e.deleted}catch(qK){ex.error(`Failed to calculate diff for entry ${n}:`,qK)}}t.push({messageId:`msg-${n}`,userPrompt:s,fullContent:o,timestamp:e.timestamp||Date.now(),filesChanged:c,linesAdded:l,linesDeleted:u,patch:a}),n++}t.reverse(),o(t),a(0)})()},[e,r]);const c=qe.useCallback(async()=>{if(!(l||s>i.length))if(0!==s){u(!0);try{const e=i[s-1];if(!e)return void u(!1);const n="msg-"+(parseInt(e.messageId.replace("msg-",""))-1);await t(n,e.fullContent)}catch(qK){u(!1)}}else n()},[s,i,t,n,l]);return Gi((e,t)=>{l||(t.upArrow?a(e=>Math.max(0,e-1)):t.downArrow?a(e=>Math.min(i.length,e+1)):t.return?c():t.escape&&n())},{isActive:!l}),0===i.length?We.jsxs(ki,{flexDirection:"column",padding:1,borderStyle:"round",borderColor:"yellow",width:"100%",children:[We.jsx(xi,{bold:!0,color:"yellow",children:"Rewind History"}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{dimColor:!0,children:"No code changes to rewind"})}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{dimColor:!0,children:"Press Escape to close"})})]}):We.jsxs(ki,{flexDirection:"column",padding:1,borderStyle:"round",borderColor:"cyan",width:"100%",children:[We.jsx(xi,{bold:!0,color:"cyan",children:l?"Reverting...":"Rewind History"}),We.jsxs(ki,{marginTop:1,flexDirection:"column",children:[We.jsx(bK,{entry:{messageId:"current",userPrompt:"(current)",fullContent:"",timestamp:Date.now(),filesChanged:0},isSelected:0===s,isCurrent:!0}),i.map((e,t)=>We.jsx(bK,{entry:e,isSelected:s===t+1,isCurrent:!1},e.messageId))]}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{dimColor:!0,children:l?"Reverting changes...":"↑↓ Navigate · Enter to select · Esc to cancel"})})]})};function EK({size:e="normal"}){const[t,n]=qe.useState(()=>DL());return qe.useEffect(()=>{let e=!0;return(async()=>{const t=e=>new Promise(t=>setTimeout(t,e)),r=3e3+2e3*Math.random();await t(r),e&&(n(SL()),await t(150),n(DL()),await t(100),n(SL()),await t(150),n(DL()))})(),()=>{e=!1}},[t]),We.jsxs(ki,{flexDirection:"row",justifyContent:"center",children:[We.jsx(xi,{color:"cyan",bold:!0,children:"{ "}),We.jsx(xi,{color:"yellow",bold:!0,children:t.face}),We.jsx(xi,{color:"cyan",bold:!0,children:" }"})]})}function IK({questions:e,onSubmit:t,onCancel:n,isFocused:r=!0}){const[i,o]=qe.useState(0),[s,a]=qe.useState(()=>{const t={};return e.forEach((e,n)=>{t[n]={selectedOptions:[],isCustomMode:!1,customInput:"",highlightedIndex:0}}),t}),l=e[i],u=s[i];if(!l||!u)return null;const c=e.length;Gi((e,t)=>{if(t.escape)n();else if(!e||t.ctrl||t.meta||t.return||t.escape||t.upArrow||t.downArrow||t.leftArrow||t.rightArrow){if(u.isCustomMode)return t.upArrow?void a(e=>({...e,[i]:{...e[i],isCustomMode:!1,customInput:"",highlightedIndex:l.options.length}})):t.rightArrow?void((u.customInput.trim()||l.multiSelect&&u.selectedOptions.length>0)&&f()):t.backspace||t.delete?void(0===u.customInput.length?a(e=>({...e,[i]:{...e[i],isCustomMode:!1,customInput:""}})):a(e=>{const t=e[i];return{...e,[i]:{...t,customInput:t.customInput.slice(0,-1)}}})):void 0;if(t.upArrow&&!u.isCustomMode){const e=0===u.highlightedIndex?l.options.length:u.highlightedIndex-1;return void a(t=>({...t,[i]:{...t[i],highlightedIndex:e}}))}if(t.downArrow&&!u.isCustomMode){const e=u.highlightedIndex===l.options.length?0:u.highlightedIndex+1;return void a(t=>({...t,[i]:{...t[i],highlightedIndex:e}}))}if(!t.leftArrow||u.isCustomMode){if(t.rightArrow)(u.selectedOptions.length>0||u.isCustomMode)&&f();else if(t.return){const e=u.highlightedIndex;return void(e<l.options.length&&d(e))}}else i>0&&o(e=>e-1)}else a(t=>{const n=t[i];return n.isCustomMode?{...t,[i]:{...n,customInput:n.customInput+e}}:n.highlightedIndex===l.options.length?{...t,[i]:{...n,isCustomMode:!0,customInput:e,selectedOptions:[]}}:t})},{isActive:r});const d=qe.useCallback(e=>{a(t=>{const n=t[i];if(l.multiSelect){const r=n.selectedOptions.includes(e);return{...t,[i]:{...n,highlightedIndex:e,selectedOptions:r?n.selectedOptions.filter(t=>t!==e):[...n.selectedOptions,e]}}}return{...t,[i]:{...n,highlightedIndex:e,selectedOptions:[e]}}})},[i,l.multiSelect]),p=qe.useCallback(()=>{a(n=>{const r={};return e.forEach((e,t)=>{const i=n[t];if(i)if(i.isCustomMode&&i.customInput.trim())r[e.header]={questionHeader:e.header,answers:[i.customInput],isCustom:!0};else if(!i.isCustomMode&&i.selectedOptions.length>0){const t=i.selectedOptions.map(t=>e.options[t]?.label).filter(e=>!!e);r[e.header]={questionHeader:e.header,answers:t,isCustom:!1}}}),t(r),n})},[e,t]),f=qe.useCallback(()=>{i<c-1?o(e=>e+1):p()},[i,c,p]);return We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"90%",paddingX:2,paddingY:1,children:[We.jsx(ki,{marginBottom:1,justifyContent:"center",children:We.jsx(EK,{})}),We.jsxs(ki,{marginBottom:1,justifyContent:"space-between",children:[We.jsx(ki,{children:e.map((t,n)=>We.jsxs(xi,{color:n===i?"cyan":"gray",children:[n===i?"●":"○",n<e.length-1?" ":""]},n))}),We.jsx(xi,{dimColor:!0,children:c>1&&"← → to navigate"})]}),We.jsxs(ki,{marginBottom:1,children:[We.jsxs(xi,{bold:!0,color:"cyan",children:["Question ",i+1," of ",c]}),We.jsxs(xi,{dimColor:!0,children:[" [",l.header,"]"]})]}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:l.question})}),We.jsxs(ki,{flexDirection:"column",children:[l.options.map((e,t)=>{const n=u.selectedOptions.includes(t),r=u.highlightedIndex===t,i=l.multiSelect?n?"[✓]":"[ ]":n?"(•)":"( )";return We.jsx(ki,{marginBottom:1,children:We.jsxs(xi,{color:n?"green":r?"cyan":void 0,bold:r,inverse:r&&!n,children:[i," ",e.label]})},t)}),We.jsx(ki,{marginBottom:1,children:u.isCustomMode?We.jsxs(We.Fragment,{children:[We.jsxs(xi,{color:"green",bold:!0,children:[l.multiSelect?"[✓]":"(•)"," "]}),We.jsx(xi,{color:"green",children:"Other: "}),We.jsx(xi,{color:"green",children:u.customInput}),We.jsx(xi,{inverse:!0,children:" "})]}):We.jsxs(xi,{color:u.highlightedIndex===l.options.length?"cyan":void 0,bold:u.highlightedIndex===l.options.length,inverse:u.highlightedIndex===l.options.length,children:[l.multiSelect?"[ ]":"( )"," Other (type to enter)"]})})]}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{dimColor:!0,children:u.isCustomMode?"→ to continue • Esc to cancel":"↑↓ navigate • Enter to select • → to continue • Esc to cancel"})})]})})}function wK({queueLength:e}){return 0===e?null:We.jsx(ki,{justifyContent:"flex-end",flexShrink:0,children:We.jsxs(xi,{color:"gray",children:[e," ",1===e?"message":"messages"," queued"]})})}const CK=["Implement FreeRTOS task for sensor polling","Debug STM32 I2C initialization sequence","Write unit tests for UART ring buffer driver","Optimize RTOS context switch performance","Refactor I2C transaction state machine","Document DMA configuration registers","Implement non-blocking SPI driver","Fix HardFault in exception handler","Add comments for ISR routines","Implement watchdog refresh logic","Develop STM32 bootloader with firmware update","Integrate lwIP sockets with RTOS tasks","Simulate task scheduling conflicts","Generate FIR filter coefficients with CMSIS-DSP","Debug FreeRTOS queue deadlocks","Configure MPU regions for memory safety","Add double-buffered DMA for audio streaming","Build RTOS-safe logging system","Audit semaphore usage across tasks","Document event group communication patterns"],_K=CK[Math.floor(Math.random()*CK.length)],BK=qe.forwardRef(({exitConfirmation:e="none"},t)=>{const{messages:n,setMessages:r,streamingState:i,isResponding:o,setIsResponding:s,setThought:a,saveConversation:l,loadConversation:u,clearActiveConversation:c,setIsBillingModalOpen:d,project:p,setProject:f,setPreviousProject:h,team:g,setTeam:A,teams:m,setPreviousTeam:y,activeQuestionPrompt:b,setActiveQuestionPrompt:v,pendingQuestionResponse:E,setPendingQuestionResponse:I,queuedMessages:w,setQueuedMessages:C}=BM(),{languageModel:_,availableModels:B,selectedModel:D,setSelectedModel:S}=VF(),{context:k}=EF(),{columns:x}=oL(),{currentMode:Q,setMode:N}=JF(),{closeSession:T,refreshBillingStatus:R,backendUser:F,sessionId:M}=FT(),{exit:O}=Hi(),[L,P]=qe.useState(!0),j=qe.useRef(null),U=qe.useRef(null),z=qe.useRef(null),G=qe.useRef(null),H=qe.useRef(n),W=qe.useRef(!1),q=qe.useRef(!1),J=qe.useRef(null),K=qe.useRef(w);H.current=n,K.current=w;const Z=qe.useRef(""),V=qe.useRef(null),Y=qe.useRef(null),{isFocused:X}=qi({autoFocus:!0,id:"chat"}),{focus:ee}=Ji(),[te,ne]=qe.useState(),[re,ie]=qe.useState(null),[oe,ae]=qe.useState(null),[le,ue]=qe.useState([]),[ce,de]=qe.useState(null),[pe,fe]=qe.useState(!1),[he,ge]=qe.useState(0),[Ae,me]=qe.useState(!1),[ye,be]=qe.useState("general"),{actions:ve}=CL(),Ee=qe.useRef(null),Ie=qe.useRef(null),[we,Ce]=qe.useState(!1),[_e,Be]=qe.useState(!1),[De,Se]=qe.useState(!1),[ke,xe]=qe.useState([]),Qe=qe.useRef([]),Ne=DM(e=>e.streams);qe.useEffect(()=>{Ne.forEach(e=>{if(!n.some(t=>{if(!t||!("role"in t)||"tool-group"!==t.role)return!1;return t.toolGroup.tools.some(t=>t.toolCallId===e.toolCallId)})){if("ai-thinking"===e.toolCallId||"ai-thinking-continuation"===e.toolCallId)return;const t={id:`pending-${e.toolCallId}`,toolCallId:e.toolCallId,name:e.toolName,displayName:e.toolName,description:`Executing ${e.toolName}...`,status:SM.Executing,startTime:Date.now()},n={id:e.toolCallId,tools:[t],status:"executing",startTime:Date.now()},i={role:"tool-group",id:`msg-${e.toolCallId}`,toolGroup:n,timestamp:Date.now()};r(e=>[...e,i])}})},[Ne,n,r]);const Te=qe.useMemo(()=>n.some(e=>{if("role"in e&&"tool-group"===e.role){return e.toolGroup.tools.some(e=>e.status===SM.Confirming)}return!1}),[n]);qe.useEffect(()=>{ve.setFileCompletionActive(oe?.isOpen??!1)},[oe?.isOpen,ve]),qe.useEffect(()=>{let e=!0;if(e&&n.length>0){n.some(e=>{if("role"in e&&"tool-group"===e.role){return e.toolGroup.tools.some(e=>e.status===SM.Confirming)}return!1})&&!Re&&r(e=>e.filter(e=>{if("role"in e&&"tool-group"===e.role){return!e.toolGroup.tools.some(e=>e.status===SM.Confirming)}return!0}))}return()=>{e=!1}},[]),qe.useEffect(()=>{},[]),qe.useEffect(()=>{(async()=>{if(!z.current&&k?.workingDirectory)try{const e=new yK(k.workingDirectory);await e.initialize(),z.current=e,function(e){IM=e}(e)}catch(e){}})()},[k?.workingDirectory]);const[Re,Fe]=qe.useState(null),{setFirebaseUser:Me}=FT(),{setTeams:Oe,setProjects:$e}=BM(),Le=qe.useCallback(e=>{if("execute"===e.type){const t="string"==typeof e.description?e.description:"",n=t.replace("Execute: ",""),r=n.split(" ");return{type:"exec",title:"string"==typeof e.title?e.title:"",description:t,isDestructive:"boolean"==typeof e.isDestructive&&e.isDestructive,command:n,rootCommand:r.length>0&&r[0]?r[0]:n}}if("edit"===e.type)return{type:"edit",title:"string"==typeof e.title?e.title:"",description:"string"==typeof e.description?e.description:"",isDestructive:"boolean"==typeof e.isDestructive&&e.isDestructive,fileName:"string"==typeof e.fileName?e.fileName:"file",fileDiff:"string"==typeof e.fileDiff?e.fileDiff:"",originalContent:"string"==typeof e.originalContent?e.originalContent:void 0,newContent:"string"==typeof e.newContent?e.newContent:void 0};{const t="string"==typeof e.description?e.description:"";return{type:"info",title:"string"==typeof e.title?e.title:"",description:t,isDestructive:"boolean"==typeof e.isDestructive&&e.isDestructive,prompt:t}}},[]);qe.useEffect(()=>(Tz(async e=>De?{approved:!0}:new Promise(t=>{const n={role:"tool-group",id:Bz("blocking-confirmation"),toolGroup:{id:Bz("blocking-group"),tools:[{id:Bz("blocking-tool"),toolCallId:Bz("blocking-call"),name:e.toolName,displayName:e.toolName,description:"object"==typeof e.confirmationDetails&&null!==e.confirmationDetails&&"description"in e.confirmationDetails&&"string"==typeof e.confirmationDetails.description?e.confirmationDetails.description:"",status:SM.Confirming,confirmationDetails:Le(e.confirmationDetails),result:{success:!1,llmContent:"",returnDisplay:"",summary:"Awaiting user confirmation"},startTime:Date.now()}],status:"pending",startTime:Date.now()},timestamp:Date.now()};r(e=>[...e,n]),Fe({request:e,resolve:e=>{r(e=>e.filter(e=>!("id"in e)||e.id!==n.id)),t(e)},fakeMessageId:n.id,fakeToolId:n.toolGroup.tools[0]?.id??"blocking-tool"})})),()=>{Tz(()=>{throw new Error("Confirmation handler not available")})}),[De,Le,r]),qe.useEffect(()=>(XW(async e=>new Promise(t=>{v(e),I(()=>e=>{t(e),v(null),I(null)})})),()=>{XW(()=>{throw new Error("Question handler not available")})}),[v,I]);const Pe=qe.useCallback(async()=>{try{if(!D)throw new Error("No model selected for compression");if(!_)throw new Error("No language model available for compression");const e=D,t=new EM,i={role:"assistant",content:"🔄 Compressing conversation history...",timestamp:Date.now()};if(r(e=>[...e,i]),!_)throw new Error("No language model available for compression");const o=await t.compressAndSaveActiveConversation(n,`session-${Date.now()}`,e,_,!0);if(r(e=>e.slice(0,-1)),o.success){r(o.compressedMessages);const e={role:"assistant",content:`✅ **Conversation compressed successfully!**\n\n**Compression Stats:**\n- Original tokens: ${o.originalTokenCount.toLocaleString()}\n- Compressed tokens: ${o.newTokenCount.toLocaleString()}\n- Tokens saved: ${(o.originalTokenCount-o.newTokenCount).toLocaleString()}\n- Compression ratio: ${Math.round(o.newTokenCount/o.originalTokenCount*100)}%\n\nThe conversation history has been summarized while preserving important context and recent messages.`,timestamp:Date.now()};r(t=>[...t,e])}else{const e={role:"assistant",content:`❌ **Compression failed:** ${o.error||"Unknown error"}`,timestamp:Date.now()};r(t=>[...t,e])}}catch(qK){r(e=>e.slice(0,-1));const t={role:"assistant",content:`❌ **Compression failed:** ${qK instanceof Error?qK.message:String(qK)}`,timestamp:Date.now()};r(e=>[...e,t])}},[n,D,r,_]),je=qe.useCallback(async e=>{if(z.current&&k?.workingDirectory)try{const t=parseInt(e.replace("msg-",""),10),i=new EM(k.workingDirectory);await i.initialize(),await i.markForRevert(t,n);const o=await i.getRevertPatches();o&&o.length>0&&await z.current.revert(o.map(e=>({hash:e.hash,files:e.files,filesAdded:0,filesModified:0,filesDeleted:0})));const s=await i.processRevert(n);r(s),await i.clearRevert();const a=await z.current.track();G.current=a}catch(qK){throw ex.error("Failed to revert:",qK),qK}else ex.error("Snapshot service not initialized")},[n,k?.workingDirectory,r]),Ue=qe.useCallback(async()=>{if(z.current&&k?.workingDirectory)try{let e=-1,t="",i=0;for(const r of n)if("role"in r&&"user"===r.role){const n=r;n.hidden||(e=i,"string"==typeof n.content?t=n.content:Array.isArray(n.content)&&(t=n.content.filter(e=>null!==e&&"object"==typeof e&&"type"in e&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")),i++)}if(e>=0){const n=e-1;n>=0?await je(`msg-${n}`):(await je("msg--1"),r([]),await c()),t&&Ee.current?.setValue(t),ee("chat")}}catch(qK){ex.error("Failed to undo:",qK)}},[n,k?.workingDirectory,je,r,c,ee]),ze=qe.useCallback(async()=>{j.current&&(j.current.abort(),j.current=null,P(!0),s(!1),a(null),DM.getState().clearAll(),await new Promise(e=>{r(t=>{const n=[...t];let r=!1;for(let e=n.length-1;e>=0;e--){const t=n[e];if(t&&("role"in t&&"assistant"===t.role)){const i=t.content;""===i||"string"==typeof i&&""===i.trim()?n.splice(e,1):r=!0;break}}if(!r)for(let e=n.length-1;e>=0;e--){const t=n[e];if(t&&("role"in t&&"user"===t.role)){if(!t.hidden){n.splice(e,1);break}}}return setTimeout(e,0),n})}),await R(),ee("chat"),q.current||setTimeout(()=>J.current?.(),0))},[s,a,r,ee,R]),Ge=qe.useCallback(()=>{if(Re){const{resolve:e,fakeMessageId:t}=Re;e({approved:!1}),r(e=>e.filter(e=>!("id"in e)||e.id!==t)),Fe(null)}iz.getState().cancelAll()},[Re,r]);qe.useImperativeHandle(t,()=>({isStreaming:()=>i!==_w.Idle,cancelStream:ze,openResumeInterface:()=>Ce(!0),clearInput:()=>Ee.current?.clear(),hasInput:()=>""!==(Ee.current?.getValue()||"").trim(),cleanupOnExit:Ge}),[i,ze,Ge]);const He=qe.useCallback((e,t=!1)=>{r(n=>{const r=[...n];for(let i=r.length-1;i>=0;i--){const n=r[i];if(n&&("role"in n&&"assistant"===n.role)){const o=n;if("string"==typeof o.content){const n=o.content,s=t?n+e:e;r[i]={...o,content:s}}break}}return r})},[r]),Je=qe.useCallback(async(e,t)=>{if(""===e.trim())return;const n=e.trim();if(o&&!q.current){const e={id:Bz("queued-msg"),message:n,timestamp:Date.now(),options:t};return C(t=>[...t,e]),void ve.addToHistory(n)}P(!1),s(!0),a(null),ex.info("User message submitted",{messageLength:n.length,isCommand:n.startsWith("/"),model:D?.name});const i=k?.projectInfo?.hasEmbedderMd??!1,l=null!=p&&0===(p.documentCount??0);if($.withScope(e=>{e.setTag("event_type","user_prompt"),e.setTag("has_embedder_md",i?"true":"false"),e.setTag("no_documents",l?"true":"false"),D?.name&&e.setTag("model",D.name),g?.id&&e.setTag("team_id",g.id),p?.id&&e.setTag("project_id",p.id),F?.id&&e.setTag("user_id",F.id),M&&e.setTag("session_id",M),e.setContext("prompt",{length:n.length,isCommand:n.startsWith("/"),content:n,hasEmbedderMd:i,hasNoDocuments:l,projectId:p?.id??null,projectName:p?.name??null,projectDocumentCount:p?.documentCount??null,teamId:g?.id??null,teamName:g?.name??null,userId:F?.id??null,sessionId:M??null}),$.captureMessage("User prompt submitted","info")}),!t?.skipCommandCheck&&n.startsWith("/")){const e=n.substring(1).split(/\s+/),t=e[0],r=e.slice(1);if(!t)return P(!0),s(!1),void a(null);const i=az(t);if(i)try{return await i.action(),P(!0),s(!1),void a(null)}catch(qK){ex.error(`Command ${t} failed:`,qK)}if("resume"===t&&r.length>0){const e=r.join(" ");try{return await u(e),P(!0),s(!1),void a(null)}catch(qK){ex.error("Failed to load conversation:",qK)}}}ve.addToHistory(n),P(!1),s(!0),a({subject:"Thinking...",description:"",startTime:Date.now()});const c=new AbortController;j.current=c;try{const n=k?.workingDirectory,i=await async function(e,t){const n=function(e){const t=[];let n=0;for(;n<e.length;){let r=-1,i=n;for(;i<e.length;){if("@"===e[i]&&(0===i||"\\"!==e[i-1])){r=i;break}i++}if(-1===r){n<e.length&&t.push({type:"text",content:e.substring(n)});break}r>n&&t.push({type:"text",content:e.substring(n,r)});let o=r+1,s=!1;for(;o<e.length;){const t=e[o];if(void 0===t)break;if(s)s=!1;else if("\\"===t)s=!0;else if(/\s/.test(t))break;o++}const a=e.substring(r,o).replace(/\\(.)/g,"$1");t.push({type:"atPath",content:a}),n=o}return t.filter(e=>!("text"===e.type&&""===e.content.trim()))}(e),r=n.filter(e=>"atPath"===e.type);if(0===r.length)return{processedMessage:e,displayMessage:e,toolExecutions:[],fileContents:[]};const i=t||process.cwd(),o=[],s=new Map;for(const h of r){const e=h.content;if("@"===e)continue;const t=e.substring(1);if(!t)continue;let n=t.replace(/\\/g,"/");try{const e=await import("fs/promises"),r=se.resolve(i,t);(await e.stat(r)).isDirectory()&&(n+=n.endsWith("/")?"**/*":"/**/*")}catch(qK){}o.push(n),s.set(e,n)}let a="";for(let h=0;h<n.length;h++){const e=n[h];if(e)if("text"===e.type)a+=e.content;else{const t=s.get(e.content);h>0&&a.length>0&&!a.endsWith(" ")&&t&&(a+=" "),t?a+=`@${t}`:(h>0&&a.length>0&&!a.endsWith(" ")&&(a+=" "),a+=e.content)}}if(a=a.trim(),0===o.length)return{processedMessage:e,displayMessage:e,toolExecutions:[],fileContents:[]};const l={workingDirectory:i,projectRoot:i},u={paths:o,useDefaultExcludes:!0,fileFilteringOptions:{respect_git_ignore:!0,respect_embedder_ignore:!0}};let c=[],d=a,p=e,f=[];try{const e=await JH.executeStructured(u,l),t={toolName:JH.metadata.name,description:JH.getDescription?JH.getDescription(u):"Read multiple files",result:e,success:e.success};if(c.push(t),e.success&&e.llmContent){const t=/--- (.+?) ---\n\n([\s\S]*?)\n\n/g;let n;for(;null!==(n=t.exec(e.llmContent));){const e=n[1]??"",t=n[2]??"";f.push({path:e,content:t,isReadable:!0})}e.llmContent&&"No files matching the criteria were found or all were skipped."!==e.llmContent.trim()&&(d=e.llmContent+"\n\n"+a)}else d+=`\n--- File Reading Errors ---\n- Tool execution failed: ${e.llmContent}\n--- End Errors ---\n`,o.forEach(t=>{f.push({path:t,content:"",isReadable:!1,error:e.llmContent||"Tool execution failed"})})}catch(qK){const t=qK instanceof Error?qK.message:String(qK),n={toolName:JH.metadata.name,description:JH.getDescription?JH.getDescription(u):"Read multiple files",result:{success:!1,llmContent:`Error executing readManyFiles tool: ${t}`,returnDisplay:`Error executing readManyFiles tool: ${t}`},success:!1};c.push(n),d+=`\n--- File Reading Errors ---\n- Tool execution error: ${t}\n--- End Errors ---\n`,o.forEach(e=>{f.push({path:e,content:"",isReadable:!1,error:t})})}return{processedMessage:d,displayMessage:p,toolExecutions:c,fileContents:f}}(e,n),o=Ee.current?.getPendingImages()||[],a=e=>0===o.length?e:[{type:"text",text:e},...o.map(e=>({type:"image",image:`data:${e.mimeType};base64,${e.base64}`}))],l={role:"user",content:a(i.displayMessage),timestamp:Date.now(),hidden:t?.hidden??!1},u={role:"user",content:a(i.processedMessage),hidden:(t?.hidden??!1)||i.toolExecutions.length>0,timestamp:Date.now()};t?.hidden||(r([...H.current,l]),Ie.current?.scrollToBottom());let d=[...H.current,l];if(i.toolExecutions.length>0){const e={id:Bz("file-mention"),tools:i.toolExecutions.map((e,t)=>({id:Bz(`${e.toolName}-tool`),toolCallId:Bz("file-mention-call"),name:e.toolName,displayName:"Read Files",description:e.description,status:e.success?SM.Success:SM.Error,result:e.result,startTime:Date.now(),endTime:Date.now()})),status:i.toolExecutions.every(e=>e.success)?"completed":"error",startTime:Date.now(),endTime:Date.now()},t={role:"tool-group",id:e.id,toolGroup:e,timestamp:Date.now()};d=[...d,t],d=[...d,u],r(d)}await new Promise(e=>setTimeout(e,50));d.filter(e=>{if(!("role"in e)||"tool-group"===e.role)return!1;const t=e;return"string"==typeof t.content?""!==t.content.trim():Array.isArray(t.content)?t.content.length>0:"Sorry, I encountered an error. Please try again."!==t.content});let p=d;if(!D)throw new Error("No model selected");const h=D;if(!_)throw new Error("No language model instance available");const g=new EM;if(g.shouldAutoCompress(d,h))try{const e=await g.compressAndSaveActiveConversation(d,`session-${Date.now()}`,h,_,!1);e.success&&(p=e.compressedMessages,r(p))}catch(f){}const A=p.filter(e=>{if(!("role"in e)||"tool-group"===e.role)return!1;const t=e;return"string"==typeof t.content?""!==t.content.trim():Array.isArray(t.content)?t.content.length>0:"Sorry, I encountered an error. Please try again."!==t.content}).filter(e=>!("id"in e)||!("string"==typeof e.id&&(e.id.startsWith("env-context-")||e.id.startsWith("embedder-context-")))),m=await async function(){const e=[];try{const t=Date.now(),n=QT();n&&e.push({role:"user",content:n,id:"embedder-context-user",hidden:!0,timestamp:t},{role:"assistant",content:"Got it. Thanks for the custom instructions!",id:"embedder-context-assistant",hidden:!0,timestamp:t+1});const r=ST.getState(),i=await r.getEnvironmentContext(),o=tx.getState().getDocumentNames(),s=o.length>0?`\n\nThese are the documents that are available in document search:\n\n${o.join("\n")}`:"",a=`This is the Embedder CLI. We are setting up the context for our chat.\nToday's date is ${i.dateTime.formatted}.\nMy operating system is: ${i.platform.platform}\nI'm currently working in the directory: ${i.workingDirectory}\n\nThe user can find documentation about embedder at https://docs.embedder.dev\n\nEmbedder CLI has a set of slash commands the user can use. Here are the commands with their descriptions:\n /clear Clear conversation history - Ctrl+R\n /resume Resume a conversation - Ctrl+O\n /todo Show/hide current todo list - Ctrl+T\n /model Select which AI model to use - Ctrl+B\n /help Show available commands and shortcuts\n /compress Compress conversation history to save context\n /rewind View and revert to previous conversation states\n /undo Undo the last query\n /project Switch to a different project in the current team\n /init Create EMBEDDER.md with project contexts\n /doc Upload hardware docs and datasheets to improve AI accuracy\n /logout Sign out and return to login screen\n /exit Close the application\n${i.folderStructure}${s}`.trim();return e.push({role:"user",content:a,id:"env-context-user",hidden:!0,timestamp:t+2},{role:"assistant",content:"Got it. Thanks for the context!",id:"env-context-assistant",hidden:!0,timestamp:t+3}),e}catch(qK){return ex.warn("Failed to create environment context messages:",qK),e}}(),y=[...m,...A];if(z.current)try{const e=await z.current.track();G.current=e,ex.info(`[Snapshot] Created BEFORE snapshot: ${e}`)}catch(qK){ex.error("[Snapshot] Failed to create BEFORE snapshot:",qK)}else ex.warn("[Snapshot] snapshotServiceRef is null, skipping snapshot");if(W.current=!1,!_)throw new Error("No language model instance available");const b=await fI({model:_,system:void 0,stopWhen:UE(32),messages:y,tools:"act"===Q?tq:Object.fromEntries(Object.entries(tq).filter(([e])=>function(e,t){return"act"===t||(nq[e]??!1)}(e,Q))),maxOutputTokens:64e3,abortSignal:c.signal,onError:({error:e})=>{if(!e||"object"!=typeof e)return;const t=e;if(ex.error("streamText onError handler triggered",{errorType:typeof e,errorName:t?.name,errorMessage:t?.message,errorReason:t?.reason,errorStatusCode:t?.statusCode,errorStatus:t?.status,errorResponseBody:t?.responseBody,fullError:JSON.stringify(e,Object.getOwnPropertyNames(e))}),"maxRetriesExceeded"===t.reason)throw new Error("Maximum retries exceeded. Please try again later.");if("AI_APICallError"===t.name)throw t},onStepFinish:async({toolResults:e})=>{if(e.length>0){e.forEach(e=>{if(e.toolCallId){const t=e.args?JSON.stringify(e.args):"",n=e.output||e.result||"",r=t+"\n"+String(n);DM.getState().updateStream(e.toolCallId,e.toolName||"unknown",r)}});const t=Dz(e,tq);if(t.some(e=>e.toolGroup.tools.some(e=>e.status===SM.Cancelled))&&!W.current){W.current=!0,j.current?.abort(),s(!1),r(n=>{const r=[...n],i=new Set(e.map(e=>e.toolCallId).filter(Boolean)),o=[];for(let e=r.length-1;e>=0;e--){const t=r[e];if(t&&"role"in t&&"tool-group"===t.role){const n=t;"executing"===n.toolGroup.status&&n.toolGroup.tools.some(e=>i.has(e.toolCallId))&&o.push(e)}}if(o.length>0){o.sort((e,t)=>t-e);for(const t of o)r.splice(t,1);const e=o[o.length-1]??0;r.splice(e,0,...t)}else r.push(...t);return r});const n={role:"user",content:[{type:"text",text:"Operation cancelled by user"}],hidden:!0,timestamp:Date.now()};return void r(e=>[...e,n])}if(r(n=>{const r=[...n],i=new Set(e.map(e=>e.toolCallId).filter(Boolean)),o=[];for(let e=r.length-1;e>=0;e--){const t=r[e];if(t&&"role"in t&&"tool-group"===t.role){const n=t;"executing"===n.toolGroup.status&&n.toolGroup.tools.some(e=>i.has(e.toolCallId))&&o.push(e)}}if(o.length>0){o.sort((e,t)=>t-e);for(const t of o)r.splice(t,1);const e=o[o.length-1]??0;r.splice(e,0,...t)}else r.push(...t);return r}),G.current&&z.current)try{ex.info(`[Snapshot] Calculating patch from BEFORE: ${G.current}`);const e=await z.current.patch(G.current);if(ex.info(`[Snapshot] Patch calculated: ${e.files.length} files changed`),e.files.length>0&&ex.info(`[Snapshot] Files: ${e.files.map(e=>e.split("/").pop()).join(", ")}`),e.files.length>0){const t=await z.current.track();ex.info(`[Snapshot] Created AFTER snapshot: ${t}`),r(n=>{const r=[...n];for(let i=r.length-1;i>=0;i--){const n=r[i];if(n&&"role"in n&&"user"===n.role){const o=n;if(!o.hidden){const n={hash:e.hash,afterHash:t||void 0,files:e.files};ex.info(`[Snapshot] Attached patch to user message: before=${e.hash?.substring(0,8)}, after=${t?.substring(0,8)}`);const s=o.patch?Array.isArray(o.patch)?o.patch:[o.patch]:[];r[i]={...o,patch:[...s,n]};break}}}return r}),G.current=t}else ex.info("[Snapshot] No files changed, skipping patch")}catch(qK){ex.error("[Snapshot] Failed to calculate patch:",qK)}else G.current||ex.warn("[Snapshot] currentSnapshotRef is null, cannot calculate patch"),z.current||ex.warn("[Snapshot] snapshotServiceRef is null, cannot calculate patch")}}});let v=null,E="";Z.current="",Y.current=null,null!==V.current&&(clearTimeout(V.current),V.current=null);const I=()=>{null===V.current&&(V.current=setTimeout(()=>{V.current=null,Z.current&&Y.current&&He(Z.current,!1)},16))},w=()=>{null!==V.current&&(clearTimeout(V.current),V.current=null,Z.current&&Y.current&&He(Z.current,!1)),E="",v=null,Z.current="",Y.current=null};for await(const e of b.fullStream)if("text-delta"===e.type){if(E+=e.text,Z.current=E,DM.getState().updateStream("ai-thinking","thinking",E),v)I();else if(v={role:"assistant",model:D?D.name:"unknown-model",content:E,mode:"plan"===Q?"PLAN":"ACT",timestamp:Date.now()},Y.current=v,v){const e=v;r(t=>[...t,e])}}else if("tool-call"===e.type){w(),v=null;const t=e;if(t.toolCallId&&t.args){const e=JSON.stringify(t.args);DM.getState().updateStream(t.toolCallId,t.toolName||"unknown",e)}}w()}catch(qK){const t=qK;if("AbortError"!==t?.name){ex.error("AI stream error occurred",{errorName:"string"==typeof t?.name?t.name:void 0,errorMessage:"string"==typeof t?.message?t.message:void 0,errorStack:"string"==typeof t?.stack?t.stack:void 0,errorStatusCode:"number"==typeof t?.statusCode?t.statusCode:void 0,errorStatus:"string"==typeof t?.status?t.status:void 0,errorResponseBody:t?.responseBody,errorData:t?.data,errorCause:t?.cause&&"object"==typeof t.cause&&null!==t.cause?{name:"string"==typeof t.cause?.name?t.cause.name:void 0,message:"string"==typeof t.cause?.message?t.cause.message:void 0,statusCode:"number"==typeof t.cause?.statusCode?t.cause.statusCode:void 0,responseBody:t.cause?.responseBody,data:t.cause?.data}:void 0,fullError:JSON.stringify(qK,Object.getOwnPropertyNames(qK))});let n="Sorry, I encountered an error. Please try again.";if(qK&&"object"==typeof qK&&"name"in qK&&"AI_APICallError"===t.name){const e=("number"==typeof t.statusCode?t.statusCode:void 0)||("string"==typeof t.status?t.status:void 0)||(t.cause&&"object"==typeof t.cause&&"number"==typeof t.cause?.statusCode?t.cause.statusCode:void 0),r=t.responseBody||t.data||(t.cause&&"object"==typeof t.cause&&"data"in t.cause?t.cause.data:void 0)||(t.cause&&"object"==typeof t.cause&&"responseBody"in t.cause?t.cause.responseBody:void 0),i=r&&"object"==typeof r?r:null,o=i?.reason;if(403===e&&o&&"string"==typeof o)switch(o){case"NO_PAYMENT_METHODS":n="You have reached the free usage limit, please add a card on https://app.embedder.dev to continue (Error 403: No Payment Method)",d(!0);break;case"LAST_CHARGE_FAILED":n="Your last payment failed. Please update your payment method on https://app.embedder.dev/billing (Error 403: Payment Failed)",d(!0);break;case"ACCOUNT_SUSPENDED":n="Your account has been suspended. Please contact support (Error 403: Account Suspended)";break;case"TRANSACTION_PENDING":n="A payment transaction is currently processing. Please try again in a few moments (Error 403: Transaction Pending)";break;case"CREATING_TRANSACTION":n="Creating payment transaction. Please try again in a moment (Error 403: Creating Transaction)";break;default:n=`Authorization failed: ${o} (Error 403)`}else if(403===e)n="Authorization failed. You may need to add a payment method on https://app.embedder.dev/billing (Error 403)",d(!0);else if(e){n=`Sorry, I encountered an error. Please try again. (Error ${e} ${"string"==typeof r?r:""})`}}const i={role:"assistant",model:D?D.name:"unknown-model",content:n,mode:"plan"===Q?"PLAN":"ACT"};r(e=>[...e,i])}}finally{P(!0),s(!1),a(null),j.current=null,DM.getState().clearAll(),await R(),q.current||setTimeout(()=>J.current?.(),0)}},[_,D,r,s,a,Q,d,He,o,C,ve,k?.workingDirectory,R,u]),Ke=qe.useCallback(async()=>{if(q.current||o)return;if(0===w.length)return;const e=w[0];if(e){q.current=!0,C(e=>e.slice(1));try{await Je(e.message,{skipCommandCheck:!0,hidden:e.options?.hidden})}catch(qK){ex.error("Error processing queued message:",qK),C([])}finally{q.current=!1,setTimeout(()=>{K.current.length>0&&!q.current&&J.current?.()},50)}}},[w,o,C,Je]);qe.useEffect(()=>{J.current=Ke},[Ke]);const Ze=qe.useCallback(()=>{Se(e=>!e)},[]),Ve=qe.useCallback(async(e,t)=>{e.trim()&&await Je(e,{skipCommandCheck:!0,hidden:t?.hidden??!1})},[Je]);qe.useEffect(()=>{oz={setIsResumeInterfaceOpen:Ce,clearActiveConversation:c,setMessages:r,saveConversation:l,firebaseAuth:{signOut:()=>sT.signOut()},closeSession:T,exitApp:O,messages:n,model:D,compressConversation:Pe,setFirebaseUser:Me,setProjects:$e,setTeams:Oe,setIsModelSelectorOpen:fe,setIsRewindInterfaceOpen:Be,setIsHelpOpen:me,performUndo:Ue,setProject:f,project:p,setPreviousProject:h,setTeam:A,team:g,teams:m,setPreviousTeam:y,setMode:N,submitMessage:Ve,setAutoApproval:Se,toggleAutoApproval:Ze}},[c,r,l,T,O,Pe,n,D,Ue,f,p,h,A,g,m,y,N,Ve,Ze,Me,$e,Oe]),Gi((e,t)=>{if(t.ctrl&&"d"===e)vw("https://app.embedder.dev").catch(e=>{ex.error("Failed to open docs URL:",e)});else{if(Ae){if(t.tab)return void be(e=>"general"===e?"commands":"general");if(t.escape)return me(!1),be("general"),Ee.current?.clear(),void ee("chat")}if(pe){if(t.upArrow)return void ge(e=>Math.max(0,e-1));if(t.downArrow)return void ge(e=>Math.min(B.length-1,e+1));if(t.return){const e=B[he];return e&&(S(e),hT(e)),fe(!1),ge(0),Ee.current?.clear(),void ee("chat")}if(t.escape)return fe(!1),ge(0),Ee.current?.clear(),void ee("chat")}if(X&&L&&t.ctrl)switch(e){case"b":{if(0===B.length)break;const e=((D?B.findIndex(e=>e.name===D.name):0)+1)%B.length,t=B[e]||null;S(t),hT(t);break}case"r":if(n.length>0){const e=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);l(`chat-${e}`).then(()=>{}).catch(e=>{ex.error("Failed to auto-save conversation before reset:",e)})}r([]),iz.getState().clear(),DM.getState().clearAll(),c().catch(()=>{});break;case"s":{const e=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);l(`chat-${e}`).then(()=>{}).catch(e=>{});break}case"o":Ce(!0)}}},{isActive:!b});const Ye=qe.useCallback(async e=>{if(_&&D)try{const t=H.current.filter(e=>"role"in e&&"tool-group"!==e.role),n=e.map(e=>({role:"tool",content:[{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:e.output||e.result||String(e)}]})),i=await fI({model:_,messages:[...t,...n],tools:tq,maxOutputTokens:64e3,abortSignal:j.current?.signal,onStepFinish:({toolResults:e})=>{if(e.length>0){e.forEach(e=>{if(e.toolCallId){const t=e.args?JSON.stringify(e.args):"",n=e.output||e.result||"",r=t+"\n"+String(n);DM.getState().updateStream(e.toolCallId,e.toolName||"unknown",r)}});const t=Dz(e,tq);r(e=>[...e,...t])}}});let o=null;for await(const e of i.fullStream)if("text-delta"===e.type){if(o)o.content+=e.text,He(String(o.content),!1);else if(o={role:"assistant",model:D?D.name:"unknown-model",content:e.text,mode:"plan"===Q?"PLAN":"ACT",timestamp:Date.now()},o){const e=o;r(t=>[...t,e])}DM.getState().updateStream("ai-thinking-continuation","thinking",String(o?.content||e.text))}else if("tool-call"===e.type){const t=e;if(t.toolCallId&&t.args){const e=JSON.stringify(t.args);DM.getState().updateStream(t.toolCallId,t.toolName||"unknown",e)}}}catch(t){}},[_,D,r,He,Q]);qe.useEffect(()=>{U.current=Ye},[Ye]),qe.useEffect(()=>{lK().then(ie)},[]),qe.useEffect(()=>{if(pe&&D){const e=B.findIndex(e=>e.provider===D.provider&&e.name===D.name);-1!==e&&ge(e)}},[pe,D,B]);const Xe=qe.useCallback(e=>{if(!Re)return;const{resolve:t}=Re;let n;switch(e){case kM.ProceedOnce:n={approved:!0,storePermission:"once"};break;case kM.ProceedAlways:n={approved:!0,storePermission:"always"};break;case kM.ProceedAlwaysCommand:n={approved:!0,storePermission:"command"};break;default:n={approved:!1}}Fe(null),t(n)},[Re]);qe.useCallback(async()=>{if(!n.some(e=>{if(!e||!("role"in e)||"tool-group"!==e.role)return!1;return e.toolGroup.tools.some(e=>e.status===SM.Confirming)})&&Qe.current.length>0){const e=[...Qe.current];Qe.current=[],xe([]),await(U.current?.(e))}},[n]);const et=qe.useCallback(async(e,t)=>{Re&&e===Re.fakeToolId&&Xe(t)},[Re,Xe]),tt=qe.useMemo(()=>n.some(e=>{if(!e||!("role"in e)||"tool-group"!==e.role)return!1;return e.toolGroup.tools.some(e=>e.status===SM.Confirming)}),[n]),nt=qe.useMemo(()=>({messages:n,focused:X,onToolConfirm:et,disableArrowKeyScrolling:ce?.isOpen||oe?.isOpen||tt}),[n,X,et,ce?.isOpen,oe?.isOpen,tt]),rt=qe.useMemo(()=>{for(let e=n.length-1;e>=0;e--){const t=n[e];if(t&&"toolGroup"in t){const e=t.toolGroup;if(e.tools.some(e=>e.status===SM.Error))return"error";if(e.tools.every(e=>e.status===SM.Success)&&"completed"===e.status)return"success"}}return null},[n]),it=qe.useMemo(()=>({currentModel:D,canChat:L,exitConfirmation:e,streamingState:i,lastToolStatus:rt,messages:n,yoloEnabled:De}),[D,L,e,i,rt,n,De]);return We.jsx(G$,{children:We.jsx(ki,{height:"100%",width:"100%",flexDirection:"column",children:b&&E?We.jsx(IK,{questions:b.questions,onSubmit:e=>{if(E){const t={promptId:b.id,answers:e,timestamp:Date.now()};E(t)}},onCancel:()=>{if(E){const e={promptId:b.id,answers:{},timestamp:Date.now()};E(e)}},isFocused:!0}):we?We.jsx(fK,{isOpen:we,onClose:()=>{Ce(!1),Ee.current?.clear(),ee("chat")},onSelect:async e=>{try{await u(e),Ce(!1),Ee.current?.clear(),ee("chat")}catch(qK){ex.error("Failed to load conversation:",qK)}}}):_e?We.jsx(vK,{messages:n,snapshotService:z.current,onRevert:async(e,t)=>{try{Be(!1),"msg--1"===e?(await je(e),r([]),await c()):await je(e),t&&Ee.current?.setValue(t),ee("chat")}catch(qK){ex.error("Failed to revert:",qK)}},onClose:()=>{Be(!1),Ee.current?.clear(),ee("chat")}}):We.jsxs(We.Fragment,{children:[We.jsxs(ki,{flexGrow:1,marginBottom:1,flexDirection:"column",children:[We.jsx(xL,{...it}),We.jsx(ki,{justifyContent:"flex-start",flexShrink:0,children:We.jsx(ML,{})}),We.jsx(EL,{...nt,ref:Ie})]}),"first"===e&&We.jsx(ki,{justifyContent:"center",flexShrink:0,children:We.jsx(xi,{color:"yellow",children:"ctrl+c to exit"})}),We.jsx(wK,{queueLength:w.length}),le.length>0&&We.jsx(wz,{pendingImages:le,onClear:()=>{Ee.current?.clearPendingImages(),ue([])}}),We.jsxs(ki,{borderStyle:"round",borderColor:"gray",paddingX:1,flexShrink:0,children:[We.jsx(xi,{dimColor:Te,children:"❯ "}),We.jsx(ki,{flexGrow:1,children:We.jsx(Iz,{ref:Ee,onSubmit:e=>{Je(e),Ee.current?.clearPendingImages(),Ee.current?.clear()},disabled:Te,focus:X&&!Te,placeholder:o?"Message will be queued...":_K,enableFileMentions:!0,onFileSearchStateChange:ae,enableSlashCommands:!0,onCommandSearchStateChange:de,onPendingImagesChange:ue})})]}),We.jsx(ki,{marginTop:0,flexShrink:0,children:We.jsx(Cz,{})}),oe?.isOpen&&We.jsx(ki,{marginTop:1,flexDirection:"column",height:8,flexShrink:0,paddingLeft:2,children:oe.isLoading?We.jsx(ki,{paddingY:1,children:We.jsx(xi,{color:"gray",children:"Searching files..."})}):0===oe.suggestions.length?We.jsx(ki,{paddingY:1,children:We.jsx(xi,{color:"gray",children:oe.query?`No files matching "${oe.query}"`:"No files found"})}):We.jsx(ki,{flexDirection:"column",width:"100%",paddingY:0,overflow:"hidden",children:oe.suggestions.slice(Math.max(0,oe.selectedIndex-4),Math.min(oe.suggestions.length,Math.max(0,oe.selectedIndex-4)+8)).map((e,t)=>{const n=Math.max(0,oe.selectedIndex-4)+t===oe.selectedIndex;return We.jsx(ki,{width:"100%",minHeight:1,children:We.jsxs(xi,{color:"gray",inverse:n,wrap:"truncate-end",children:[e.relativePath,e.isDirectory?"/":""]})},e.path)})})}),ce?.isOpen&&We.jsx(ki,{marginTop:1,flexDirection:"column",height:9,flexShrink:0,paddingLeft:2,children:We.jsx(rq,{suggestions:ce.suggestions,selectedIndex:ce.selectedIndex,width:Math.max(60,x-4)})}),pe&&We.jsx(ki,{marginTop:1,flexDirection:"column",height:12,flexShrink:0,paddingLeft:2,children:We.jsx(hK,{models:B,selectedModel:D,selectedIndex:he,width:Math.max(60,x-4)})}),Ae&&We.jsx(ki,{marginTop:1,flexDirection:"column",height:20,flexShrink:0,paddingLeft:2,children:We.jsx(AK,{version:"2.0.31",currentTab:ye,width:Math.max(80,x-4)})}),re&&We.jsx(ki,{children:We.jsxs(xi,{children:["🔄 Update available (",re.version,")! Run"," ",We.jsx(xi,{color:"red",children:re.command})," to update"]})})]})})})});function DK(){const{team:e,project:t}=BM(),{selectedModel:n}=VF(),{firebaseUser:r}=FT(),{currentMode:i,modeConfig:o}=JF();return We.jsxs(ki,{borderStyle:"single",flexDirection:"column",padding:1,width:"100%",height:"100%",children:[We.jsxs(ki,{flexDirection:"column",paddingRight:2,paddingLeft:2,paddingBottom:0,paddingTop:0,alignSelf:"flex-start",flexGrow:1,children:[We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Current User:"})," ",r?.displayName," (",r?.email,")"]}),We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Current Plan:"})," Usage Based"]}),We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Selected Model:"})," ",We.jsx(xi,{color:"green",children:n?n.name:"(none)"})," ",We.jsxs(xi,{color:"plan"===i?"blue":"green",bold:!0,children:["[",o.name,"]"]})]}),We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Selected Team:"})," ",We.jsx(xi,{color:"cyan",children:e?.name})]}),We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Selected Project:"})," ",We.jsx(xi,{color:"magenta",children:t?.name})]})]}),We.jsx(ki,{flexDirection:"column",paddingRight:2,paddingLeft:2,paddingBottom:0,paddingTop:1,alignSelf:"flex-start",children:We.jsxs(xi,{children:[We.jsx(xi,{bold:!0,children:"Version:"})," 1.0.0"]})})]})}function SK({isSelected:e=!1}){return Je.createElement(ki,{marginRight:1},e?Je.createElement(xi,{color:"blue"},eo.pointer):Je.createElement(xi,null," "))}function kK({isSelected:e=!1,label:t}){return qe.createElement(xi,{color:e?"blue":void 0},t)}function xK({items:e=[],isFocused:t=!0,initialIndex:n=0,indicatorComponent:r=SK,itemComponent:i=kK,limit:o,onSelect:s,onHighlight:a}){const l="number"==typeof o&&e.length>o,u=l?Math.min(o,e.length):e.length,c=u-1,[d,p]=qe.useState(n>c?c-n:0),[f,h]=qe.useState(n?n>c?c:n:0),g=qe.useRef(e);qe.useEffect(()=>{y(g.current.map(e=>e.value),e.map(e=>e.value))||(p(0),h(0)),g.current=e},[e]),Gi(qe.useCallback((t,n)=>{if("k"===t||n.upArrow){const t=(l?u:e.length)-1,n=0===f,r=n?d+1:d,i=n?l?f:t:f-1;p(r),h(i);const o=l?Zi(e,r).slice(0,u):e;"function"==typeof a&&a(o[i])}if("j"===t||n.downArrow){const t=f===(l?u:e.length)-1,n=t?d-1:d,r=t?l?f:0:f+1;p(n),h(r);const i=l?Zi(e,n).slice(0,u):e;"function"==typeof a&&a(i[r])}if(/^[1-9]$/.test(t)){const n=Number.parseInt(t,10)-1,r=l?Zi(e,d).slice(0,u):e;if(n>=0&&n<r.length){const e=r[n];e&&s?.(e)}}if(n.return){const t=l?Zi(e,d).slice(0,u):e;"function"==typeof s&&s(t[f])}},[l,u,d,f,e,s,a]),{isActive:t});const A=l?Zi(e,d).slice(0,u):e;return Je.createElement(ki,{flexDirection:"column"},A.map((e,t)=>{const n=t===f;return Je.createElement(ki,{key:e.key??e.value},Je.createElement(r,{isSelected:n}),Je.createElement(i,{...e,isSelected:n}))}))}function QK(){const{isFocused:e}=qi({id:"team-selection",autoFocus:!0}),{focus:t}=Ji(),{team:n,setTeam:r,teams:i,setIsCreateTeamOpen:o,previousTeam:s,setPreviousTeam:a,previousProject:l,setProject:u,setPreviousProject:c}=BM();Gi((e,n)=>{n.escape&&s&&l&&(r(s),u(l),a(null),c(null),t("chat"))});const d=i.map((e,t)=>({label:`${e.name} ${e.shared?"(Shared)":""}`,value:e.id}));return We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Select a team"})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:"Select which team to use for this session."})}),We.jsx(xK,{isFocused:e,items:[...d],onSelect:e=>(e=>{if("create-team"===e)return void o(!0);const n=i.find(t=>t.id===e);n&&(t("project-selection"),r(n))})(e.value)}),We.jsx(ki,{marginTop:1,children:We.jsxs(xi,{color:"dim",children:["(Use Enter to select",s&&l?", ESC to go back":"",")"]})})]})})}function NK({message:e="Loading your data...",description:t=""}){return We.jsx(ki,{width:"100%",height:"100%",justifyContent:"center",alignItems:"center",padding:1,children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(xi,{children:e}),We.jsx(xi,{children:t||""})]})})}function TK(){const{isFocused:e}=qi({id:"project-selection",autoFocus:!0}),{focus:t}=Ji(),{team:n,setTeam:r,teams:i,projects:o,setProject:s,setIsCreateProjectOpen:a,previousProject:l,setPreviousProject:u,previousTeam:c,setPreviousTeam:d}=BM(),[p,f]=qe.useState(!1),h=o.filter(e=>e.teamId===n?.id);return Gi((e,n)=>{n.escape&&(l?(s(l),u(null),c&&(r(c),d(null)),t("chat")):i.length>1?(r(null),s(null),t("team-selection")):t("project-selection"))}),n?p?We.jsx(NK,{message:"Loading your project..."}):We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Select a project"})}),We.jsx(ki,{marginBottom:1,children:We.jsxs(xi,{children:["Select which project to use within ",We.jsx(xi,{bold:!0,children:n.name}),"."]})}),We.jsx(ro,{isFocused:e,items:[...h.map(e=>({label:e.name,value:e.id})),{label:"Create a new project",value:"create-project"}],onSelect:e=>(e=>{if("create-project"===e)return void a(!0);const r=h.find(t=>t.id===e);if(r&&n){f(!0),u(null),d(null);try{gT(process.cwd(),n.id,r.id)}catch(qK){ex.warn("Failed to cache workspace selection:",qK)}setTimeout(()=>{s(r),t("chat")},0)}})(e.value)}),We.jsx(ki,{marginTop:1,children:We.jsxs(xi,{color:"dim",children:["(Use Enter to select",i.length>1?", ESC to go back":"",")"]})})]})}):null}function RK({previousPage:e=null,firstTime:t=!1}){const{isFocused:n}=qi({id:"project-creation",autoFocus:!0}),{focus:r}=Ji(),{team:i,setTeam:o,createProject:s,setIsCreateProjectOpen:a}=BM(),[l,u]=qe.useState(!1);Gi((t,n)=>{if(n.escape)return"team-selection"===e&&o(null),void a(!1)});return We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"Create a new project"})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:t?"Let's get started by creating your first project!":We.jsxs(We.Fragment,{children:["Create a new project within the ",We.jsx(xi,{bold:!0,children:i?.name})," team."]})})}),We.jsxs(ki,{flexDirection:"column",marginBottom:1,alignItems:"flex-start",children:[We.jsx(xi,{bold:!0,children:"Project Name"}),We.jsxs(ki,{borderStyle:"single",borderColor:"gray",minHeight:3,height:3,flexDirection:"row",alignItems:"center",width:50,children:[We.jsx(xi,{children:"❯ "}),We.jsx(Iz,{focus:n,disabled:l,onSubmit:async e=>{if(!l&&""!==e.trim())try{u(!0),await s(e,!0),r("chat"),a(!1)}catch(qK){ex.error("Error creating project:",qK)}finally{u(!1)}},maxLength:32,placeholder:"Super Advanced Project"})]})]}),l&&We.jsx(ki,{marginBottom:1,children:We.jsxs(xi,{children:[We.jsx(FL,{type:"triangle"})," Creating"]})}),We.jsx(ki,{marginTop:1,children:We.jsxs(xi,{color:"dim",children:["(Use Enter to create",t?"":", ESC to go back",")"]})})]})})}function FK(){const{isFocused:e}=qi({id:"billing-required",autoFocus:!0}),[t,n]=qe.useState(!1),{billingStatus:r,refreshBillingStatus:i}=FT(),{setIsBillingModalOpen:o}=BM();return qe.useEffect(()=>{if(!t)return;const e=setInterval(async()=>{await i(),r&&r.paymentMethodCount>0&&(n(!1),o(!1))},1e3);return()=>clearInterval(e)},[t,r,o,i,n]),Gi((r,i)=>{if(e)if(!i.escape||t){if(i.return&&!t){n(!0);const e="darwin"===process.platform?"open":"win32"===process.platform?"start":"xdg-open";ke(e+" https://app.embedder.dev/billing")}}else o(!1)}),We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"You have reached the free usage limit"})}),We.jsx(ki,{marginBottom:2,children:We.jsx(xi,{children:"Please add a card to continue"})}),t&&We.jsx(ki,{marginBottom:2,children:We.jsx(FL,{type:"dots"})}),We.jsx(ki,{marginTop:2,children:t?We.jsx(xi,{color:"dim",children:"Please complete the setup in your browser..."}):We.jsxs(ki,{flexDirection:"column",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{color:"cyan",children:"Press ENTER to add payment method"})}),We.jsx(ki,{children:We.jsx(xi,{color:"dim",children:"Press ESC to go back"})})]})})]})})}function MK(){const{isFocused:e}=qi({id:"document-upload",autoFocus:!0}),{project:t,setIsAddDocumentsModalOpen:n}=BM(),[r,i]=qe.useState(!1);return Gi((t,i)=>{e&&i.escape&&!r&&n(!1)},{isActive:e}),We.jsx(ki,{width:"100%",height:"100%",padding:1,justifyContent:"center",alignItems:"center",children:We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"98%",height:"98%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(EK,{})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,children:"No Documents Found"})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{children:"Add documentation to your project for better AI assistance."})}),We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{color:"dim",children:"Upload files like API docs, architecture guides, or design specs."})}),We.jsx(ro,{isFocused:e&&!r,items:[{value:"upload-documents",label:"Open Web Console"}],onSelect:e=>{if("upload-documents"===e.value){if(t?.id){i(!0);const e=`https://app.embedder.dev/projects/${t.id}?overrideTeamId=${t.teamId}`;vw(e).then(()=>{n(!1)}).catch(e=>{ex.error("Failed to open browser:",e),i(!1)})}}else"skip"===e.value&&n(!1)}}),We.jsx(ki,{marginTop:1,children:r?We.jsx(xi,{color:"dim",children:"Opening browser..."}):We.jsx(xi,{color:"dim",children:"Press ESC to dismiss"})})]})})}function OK(){qi({id:"authentication",autoFocus:!0});const[e,t]=qe.useState(!1),[n,r]=qe.useState(null),[i,o]=qe.useState("Loading your data..."),[s,a]=qe.useState(null),[l,u]=qe.useState(null),[c,d]=qe.useState(!1),{teams:p,projects:f,setIsDeviceAuthOpen:h}=BM(),{backendUser:g,firebaseUser:A}=FT(),{availableModels:m}=VF();qe.useEffect(()=>{(async()=>{const e=fT();if(e){u(e),t(!0),o("Loading your data...");try{const t=FN._fromJSON(sT,e.user);await sT.updateCurrentUser(t),d(!0)}catch(n){ex.error("Failed to restore user from stored credentials:",n),await pT(null),u(null),t(!1),d(!0),o("Loading your data...")}}else d(!0)})()},[]);const y=!e&&p.length>0&&f.length>0&&null!==g&&m.length>0&&null!==A,b=c&&!A&&!e;if(!y&&!b)return We.jsx(NK,{message:i,description:s});if(!y&&b)h(!0);else if(y)return null;return null}function $K(){qi({autoFocus:!0});const{error:e}=BM(),{exit:t}=Hi();return Gi((e,n)=>{n.escape&&t()}),We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",children:[We.jsx(ki,{marginBottom:1,children:We.jsx(xi,{bold:!0,color:"red",children:"We encountered an error!"})}),We.jsxs(ki,{flexDirection:"column",marginBottom:1,marginTop:5,alignItems:"center",children:[We.jsx(xi,{children:e}),We.jsx(xi,{children:"If it persists, please contact support."})]}),We.jsx(ki,{marginTop:5,children:We.jsx(xi,{color:"dim",children:"Press Enter to retry or ESC to exit."})})]})}function LK(){const[e,t]=qe.useState(null),[n,r]=qe.useState(null),[i,o]=qe.useState(!1),{unauthFetch:s,loggedIn:a}=FT();return qe.useEffect(()=>{let e;if(!s)return;const n=async()=>{try{const i=await(async()=>await s("api/v1/auth/device/start",{method:"POST",headers:{"Content-Type":"application/json"}}))();0,t(i);const a=Date.now()+1e3*i.expiresIn,l=3e3,u=async()=>{try{if(o(!0),Date.now()>a)return o(!1),void n();const t=await(async e=>await s("api/v1/auth/device/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})}))(i.userCode);if(t.accessToken&&"authorized"===t.status)o(!1),await async function(e,t){if(MQ(e.app))return Promise.reject(sN(e));const n=qN(e),r=await eT(n,{token:t,returnSecureToken:!0}),i=await YN._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(i.user),i}(sT,t.accessToken);else if("authorization_pending"===t.status)e=setTimeout(u,l);else{if("code_not_found"===t.status)return o(!1),void n();o(!1),r(t.status||"Unknown error occurred")}}catch(t){o(!1),r(t instanceof Error?t.message:"Polling failed")}};u()}catch(i){o(!1),r(i instanceof Error?i.message:"Failed to authenticate")}};return n(),()=>clearTimeout(e)},[s]),We.jsxs(ki,{borderStyle:"single",flexDirection:"column",width:"100%",height:"100%",justifyContent:"center",alignItems:"center",children:[We.jsx(xi,{bold:!0,children:"Login with the following device token:"}),We.jsx(ki,{marginTop:.5,children:e?We.jsx(xi,{bold:!0,color:"green",children:e.userCode}):We.jsx(xi,{children:" Loading..."})}),We.jsx(ki,{marginTop:1,children:We.jsx(xi,{children:null!=e?e.verificationUri:"https://app.embedder.dev/auth/activate"})}),n&&!a?We.jsx(ki,{marginTop:1,children:We.jsxs(xi,{color:"red",children:["Error: ",n]})}):i?We.jsxs(ki,{marginTop:1,children:[We.jsx(FL,{type:"clock"}),We.jsx(xi,{children:" Waiting for authentication..."})]}):null]})}function PK({children:e}){return We.jsx(ki,{flexDirection:"column",width:"100%",height:"100%",children:We.jsx(ki,{flexDirection:"row",flexGrow:1,children:e})})}BK.displayName="ChatPage";const jK=[{label:"Chat",value:"chat"},{label:"Conversations",value:"conversations"},{label:"Documents",value:"documents"},{label:"Settings",value:"settings"},{label:"Exit",value:"exit"}];function UK(){const[e,t]=qe.useState(jK[0]),[n,r]=qe.useState(!1),[i,o]=qe.useState("none"),s=qe.useRef(null),a=qe.useRef(null),{team:l,project:u,projects:c,messages:d,isCreateProjectOpen:p,isBillingModalOpen:f,isAddDocumentsModalOpen:h,setIsAddDocumentsModalOpen:g,error:A,teams:m,loading:y,isDeviceAuthOpen:b}=BM(),{loggedIn:v,closeSession:E,backendUser:I}=FT(),{selectedModel:w}=VF(),{exit:C}=Hi(),{focus:_}=Ji(),{switchMode:B}=JF(),{state:D,actions:S}=CL(),k=qe.useRef(!1);Gi((t,r)=>{if("chat"!==e?.value||n){if(r.tab){if(D.isFileCompletionActive)return;B()}else if(r.escape||r.ctrl&&"c"===t){if("main"===x&&"chat"===e?.value&&a.current?.isStreaming())return void a.current.cancelStream();if(!r.ctrl||"c"!==t)return void("chat"===e?.value&&_("chat"));if(a.current?.hasInput())return void a.current.clearInput();"none"===i?(o("first"),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{o("none"),s.current=null},3e3)):"first"===i&&(s.current&&clearTimeout(s.current),a.current?.cleanupOnExit&&a.current.cleanupOnExit(),E(d,u,l,w).finally(()=>{C(),setTimeout(()=>process.exit(0),100)}))}}else{if(r.tab){if(D.isFileCompletionActive)return;return void B()}if(r.escape||r.ctrl&&"c"===t){if("main"===x&&"chat"===e?.value&&a.current?.isStreaming())return void a.current.cancelStream();if(!r.ctrl||"c"!==t)return void("chat"===e?.value&&_("chat"));if(a.current?.hasInput())return void a.current.clearInput();"none"===i?(o("first"),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{o("none"),s.current=null},3e3)):"first"===i&&(s.current&&clearTimeout(s.current),a.current?.cleanupOnExit&&a.current.cleanupOnExit(),E(d,u,l,w).finally(()=>{C(),setTimeout(()=>process.exit(0),100)}))}}},{isActive:!0}),qe.useEffect(()=>{const e=()=>{};return process.on("SIGINT",e),()=>{process.removeListener("SIGINT",e),s.current&&clearTimeout(s.current)}},[]),qe.useEffect(()=>{!(u&&0===(u.documentCount??0))||u.pendingCreation||k.current||y||!v||(k.current=!0,g(!0))},[u,y,v,g]);const x=A?We.jsx($K,{}):!v&&b?We.jsx(LK,{}):v?y?We.jsx(NK,{message:"Loading your data..."}):p?We.jsx(RK,{previousPage:null}):!l&&m.length>1?We.jsx(QK,{}):!u&&c.length>0?We.jsx(TK,{}):u||0!==c.length?f?We.jsx(FK,{}):h?We.jsx(MK,{}):"main":We.jsx(RK,{previousPage:"team-selection",firstTime:!0}):We.jsx(OK,{});return We.jsx(KM,{children:We.jsx(PK,{children:"main"===x?We.jsxs(We.Fragment,{children:[n&&We.jsx(io,{navItems:jK,onSelect:e=>{if("exit"===e.value)E(d,u,l,w).finally(()=>{C(),setTimeout(()=>process.exit(0),100)});else if("conversations"===e.value)t(jK.find(e=>"chat"===e.value)),r(!1),_("chat"),setTimeout(()=>{a.current&&a.current.openResumeInterface?.()},100);else{if("documents"===e.value){if(u?.id){const e=`https://app.embedder.dev/projects/${u.id}?overrideTeamId=${u.teamId}`;vw(e).catch(e=>{ex.error("Failed to open browser:",e)})}return}t(e),_(e.value)}}}),"chat"===e?.value&&We.jsx(BK,{ref:a,exitConfirmation:i}),"settings"===e?.value&&We.jsx(DK,{})]}):x})})}const zK=qe.forwardRef(function(e,t){Gi(()=>{});const{height:n,width:r}=function(){const{stdout:e}=Wi(),t=qe.useCallback(()=>({height:e.rows,width:e.columns}),[e]),[n,r]=qe.useState(t);return qe.useEffect(()=>{function n(){r(t())}return e.on("resize",n),()=>{e.off("resize",n)}},[e,t]),n}();return We.jsx(ki,{ref:t,height:n,width:r,...e})});async function GK(e){return new Promise((t,n)=>{process.stdout.write(e,e=>{e?n(e):t()})})}$.init({dsn:"https://ffddaca20e5fd45b5c4c4263140fd909@sentry-service-prod.embedder.dev/3",sendDefaultPii:!0});let HK=!1;const WK=async()=>{try{await $.flush(2e3)}catch(qK){ex.warn("Sentry flush failed",qK)}};["SIGINT","SIGTERM","SIGBREAK"].forEach(e=>{process.on(e,()=>(e=>{HK||(HK=!0,ex.info(`Received ${e}. Flushing Sentry before shutdown.`),WK().finally(()=>{process.exit(0)}))})(e))}),process.on("beforeExit",()=>{HK||(HK=!0,ex.info("Process beforeExit triggered. Flushing Sentry."),WK())}),process.on("uncaughtException",e=>{ex.error("Uncaught exception:",e),$.captureException(e)}),process.on("unhandledRejection",e=>{ex.error("Unhandled rejection:",e),$.captureException(e instanceof Error?e:new Error(String(e)))}),process.removeAllListeners("warning"),((e,t)=>{const n=((e,t)=>{const n={stdout:i.stdout,stdin:i.stdin,stderr:i.stderr,debug:!1,exitOnCtrlC:!0,patchConsole:!0,maxFps:30,...Oi(t)},r=$i(n.stdout,()=>new Mi(n));return r.render(e),{rerender:r.render,unmount(){r.unmount()},waitUntilExit:r.waitUntilExit,cleanup:()=>Ai.delete(n.stdout),clear:r.clear}})(null,t),r=async function(e){await e.waitUntilExit(),await GK("[?1049l")}(n);return{instance:n,start:async()=>{await GK("[?1049h"),n.rerender(We.jsx(zK,{children:e}))},waitUntilExit:function(){return r}}})(We.jsx(RT,{children:We.jsx(qF,{children:We.jsx(ZF,{children:We.jsx(_M,{children:We.jsx(wL,{children:We.jsx(UK,{})})})})})}),{exitOnCtrlC:!1,debug:"true"===process.env.DEV,maxFps:60}).start();export{KH as D,YH as a,rW as b,nW as c,VH as d,tW as f,ZH as l,eW as s,XH as t};