@agentrix/cli 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{createRequire as e}from"node:module";const n=e(import.meta.url);import a from"yargs";import{hideBin as t}from"yargs/helpers";import s from"chalk";import{encodeBase64 as i,createKeyPairWithUit8Array as o,encryptMachineEncryptionKey as r,generateAESKey as c,decodeBase64 as p,decryptWithEphemeralKey as l,createEventId as d,encryptFileContent as u,splitRtcChunkFrame as m,RtcChunkFlags as g,buildRtcChunkFrame as h,decryptSdkMessage as f,machineAuth as x,encryptSdkMessage as v,isSDKUserMessage as b,isAskUserMessage as y,isAskUserResponseMessage as w,isSDKMessage as k,getAgentContext as I,detectPreview as S,IGNORED_DIRECTORIES as T,isCompanionHeartbeatMessage as E,isCompanionReminderMessage as C,workerAuth as A}from"@agentrix/shared";import{randomBytes as R,createDecipheriv as _,randomUUID as M}from"node:crypto";import $ from"axios";import{m as D,l as P,p as O,a as j,c as N,g as q,b as U}from"./logger-CdDc0Esc.mjs";import{createInterface as G}from"node:readline";import*as L from"fs";import F,{readFileSync as W,existsSync as H}from"fs";import*as z from"path";import B,{join as K,dirname as V}from"path";import X,{tmpdir as Y,homedir as J}from"node:os";import Q from"open";import{io as Z}from"socket.io-client";import{EventEmitter as ee}from"node:events";import*as ne from"node:fs";import ae,{existsSync as te,readFileSync as se,statSync as ie,writeFileSync as oe,mkdirSync as re,readdirSync as ce,createWriteStream as pe,unlinkSync as le}from"node:fs";import*as de from"node:path";import ue,{join as me,dirname as ge,basename as he,relative as fe,normalize as xe,extname as ve,isAbsolute as be,resolve as ye}from"node:path";import{createRequire as we}from"node:module";import{spawn as ke,execSync as Ie}from"child_process";import Se from"ps-list";import Te from"cross-spawn";import{getPlatform as Ee}from"@xmz-ai/sandbox-runtime/dist/utils/platform.js";import Ce from"fastify";import{z as Ae,toJSONSchema as Re}from"zod";import{validatorCompiler as _e,serializerCompiler as Me}from"fastify-type-provider-zod";import{spawnSync as $e,execFile as De}from"node:child_process";import{fileURLToPath as Pe}from"node:url";import{EventEmitter as Oe}from"events";import je from"better-sqlite3";import{fileURLToPath as Ne,pathToFileURL as qe}from"url";import{isSupportedPlatform as Ue,NetworkManager as Ge,SandboxManager as Le}from"@xmz-ai/sandbox-runtime";import{pipeline as Fe}from"node:stream/promises";import{tool as We,createSdkMcpServer as He,query as ze,AbortError as Be}from"@anthropic-ai/claude-agent-sdk";import Ke from"simple-git";import{promisify as Ve}from"node:util";import{writeFile as Xe}from"node:fs/promises";import{randomUUID as Ye}from"crypto";import{replacePromptPlaceholders as Je,loadAgentConfig as Qe,getAgentContext as Ze}from"@agentrix/shared/node";import{Codex as en}from"@openai/codex-sdk";import"winston";import"os";async function nn(e){return new Promise(n=>setTimeout(n,e))}async function an(e,n){const a=await D.readDaemonState();if(!a?.port){const e="No daemon running, no state file found";return P.debug(`[CONTROL CLIENT] ${e}`),{error:e}}try{const t=process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT?parseInt(process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT):1e4,s=await fetch(`http://agentrix-local.xmz.ai:${a.port}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n||{}),signal:AbortSignal.timeout(t)});if(!s.ok){const n=`Request failed: ${e}, HTTP ${s.status}`;return P.debug(`[CONTROL CLIENT] ${n}`),{error:n}}return await s.json()}catch(n){const a=`Request failed: ${e}, ${n instanceof Error?n.message:"Unknown error"}`;return P.debug(`[CONTROL CLIENT] ${a}`),{error:a}}}async function tn(e,n){return await an("/session-started",{sessionId:e,metadata:n})}async function sn(){const e=await D.readDaemonState();if(!e)return!1;try{return process.kill(e.pid,0),!0}catch{return P.debug("[DAEMON RUN] Daemon PID not running, cleaning up state"),await rn(),!1}}async function on(){if(P.debug("[DAEMON CONTROL] Checking if daemon is running same version"),!await sn())return P.debug("[DAEMON CONTROL] No daemon running, returning false"),!1;const e=await D.readDaemonState();if(!e)return P.debug("[DAEMON CONTROL] No daemon state found, returning false"),!1;try{const n=K(O(),"package.json"),a=JSON.parse(W(n,"utf-8")).version;return P.debug(`[DAEMON CONTROL] Current CLI version: ${a}, Daemon started with version: ${e.cliVersion}`),a===e.cliVersion}catch(e){return P.debug("[DAEMON CONTROL] Error checking daemon version",e),!1}}async function rn(){try{await D.clearDaemonState(),P.debug("[DAEMON RUN] Daemon state file removed")}catch(e){P.debug("[DAEMON RUN] Error cleaning up daemon metadata",e)}}async function cn(){try{const e=await D.readDaemonState();if(!e)return void P.debug("No daemon state found");P.debug(`Stopping daemon with PID ${e.pid}`);try{return await async function(){await an("/stop")}(),void await async function(e){const n=Date.now();for(;Date.now()-n<2e3;)try{process.kill(e,0),await new Promise(e=>setTimeout(e,100))}catch{return}throw new Error("Process did not die within timeout")}(e.pid)}catch(e){P.debug("HTTP stop failed, will force kill",e)}process.kill(e.pid,"SIGKILL")}catch(e){P.debug("Error stopping daemon",e)}}async function pn(){const e=await D.readCredentials();if(e)return P.info("[AUTH] Using existing credentials"),e;const n=process.env.CLOUD_AUTH_TOKEN,a=process.env.CLOUD_DEVICE;let t,s,d;if(n&&a)t={token:n,machineId:a},P.info("[AUTH] Cloud mode detected, using CLOUD_AUTH_TOKEN");else{const e=await async function(){console.clear();const e=D.generateMachineId(),n=new Uint8Array(R(32)),a=await o(n);try{console.log(`[AUTH] Sending auth request to: ${D.serverUrl}/v1/auth/machine`),console.log(`[AUTH] Public key: ${i(a.publicKey).substring(0,20)}...`);const n={machineId:e};await $.post(`${D.serverUrl}/v1/auth/machine`,n),console.log("[AUTH] Auth request sent successfully")}catch(e){return console.log("Failed to create authentication request, please try again later."),{credentials:null,userPublicKey:null,keypair:a}}const t=await async function(e,n){console.clear(),console.log("\nWeb Authentication\n");const a=function(e,n){const a={key:i(e,"base64"),machineId:n},t=JSON.stringify(a),s=i((new TextEncoder).encode(t),"base64url");return`${D.webappUrl}/terminal/connect?auth=${s}`}(e.publicKey,n);return console.log("Opening your browser..."),await async function(e){try{return!process.stdout.isTTY||process.env.CI||process.env.HEADLESS?(P.debug("[browser] Headless environment detected, skipping browser open"),!1):(P.debug(`[browser] Attempting to open URL: ${e}`),await Q(e),P.debug("[browser] Browser opened successfully"),!0)}catch(e){return P.debug("[browser] Failed to open browser:",e),!1}}(a)?(console.log("✓ Browser opened\n"),console.log("Complete authentication in your browser window.")):console.log("Could not open browser automatically."),console.log("\nIf the browser did not open, please copy and paste this URL:"),console.log(a),console.log(""),await async function(e,n){process.stdout.write("Waiting for authentication");let a=0,t=!1;const s=()=>{t=!0,console.log("\n\nAuthentication cancelled."),process.exit(0)};process.on("SIGINT",s);try{for(;!t;){try{const a=await $.get(`${D.serverUrl}/v1/auth/machine?machineId=${n}`);if("authorized"===a.data.state){const n=a.data.token,t=a.data.content,s=l(p(t),e.secretKey);return s?{token:n,userPublicKey:JSON.parse((new TextDecoder).decode(s)).publicKey}:(console.log("\n\nFailed to decrypt authentication data. Please try again."),{token:null,userPublicKey:null})}}catch(e){return console.log("\n\nFailed to check authentication status. Please try again."),{token:null,userPublicKey:null}}process.stdout.write("\rWaiting for authentication"+".".repeat(a%3+1)+" "),a++,await nn(1e3)}}finally{process.off("SIGINT",s)}return{token:null,userPublicKey:null}}(e,n)}(a,e);return t.token?{credentials:{token:t.token,secret:i(n),machineId:e},userPublicKey:t?.userPublicKey,keypair:a}:{credentials:null,userPublicKey:null,keypair:a}}();if(!e.credentials||!e.userPublicKey)throw new Error("Authentication failed or was cancelled");t=e.credentials,s=e.keypair,d=e.userPublicKey}return await D.writeCredentials(t),await async function(e,n,a,t){try{const s={id:e.machineId,metadata:JSON.stringify(n)};t&&a&&(s.dataEncryptionKey=r(t.publicKey,c(),p(a))),await $.post(`${D.serverUrl}/v1/machines/sync`,s,{headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},timeout:6e4})}catch(e){if($.isAxiosError(e))throw new Error(`Failed to sync machine data: ${e.response?.data?.message||e.message}`);throw e}}(t,D.metadata(),d,s),P.info("[AUTH] Machine setup completed"),t}class ln{interval=null;socket=null;config;constructor(e){this.config=e}start(e){this.interval&&this.stop(),this.socket=e,this.interval=setInterval(()=>{if(!this.socket)return void this.stop();const e=this.config.payloadGenerator?this.config.payloadGenerator():{};this.socket.emit(this.config.event,e)},this.config.intervalMs)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.socket=null}isRunning(){return null!==this.interval}}class dn{socket=null;config;eventHandlers=new Map;eventEmitter=new ee;KeepAliveManager=null;healthCheckInterval=null;constructor(e){this.config=e,e.keepAliveConfig&&(this.KeepAliveManager=new ln(e.keepAliveConfig))}connect(){if(this.socket)return void this.log("Already connected or connecting");const{serverUrl:e,path:n,auth:a={},options:t={}}=this.config,s={path:n,auth:a,transports:["websocket"],reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:1/0,...t};this.socket=Z(e,s),this.setupSocketHandlers(),this.log("Connecting to",e)}disconnect(){this.socket&&(this.log("Disconnecting"),this.stopHealthCheck(),this.socket.close(),this.socket=null)}get connected(){return this.socket?.connected??!1}replaceSocketHandler(e,n,a){this.socket&&(n&&this.socket.off(e,n),this.socket.on(e,a))}onEvent(e,n){const a=async a=>(this.log(`received event ${e}, data: ${JSON.stringify(a)}`),n(a)),t=this.eventHandlers.get(e);this.eventHandlers.set(e,a),this.replaceSocketHandler(e,t,a)}onEventWithAck(e,n){const a=async(a,t)=>(this.log(`received event with ack ${e}, data: ${JSON.stringify(a)}`),n(a,t)),t=this.eventHandlers.get(e);this.eventHandlers.set(e,a),this.replaceSocketHandler(e,t,a)}unregisterHandler(e){this.eventHandlers.delete(e),this.socket&&this.socket.off(e)}send(e,n){this.socket?(this.log(`send event ${e}`),void 0!==n?this.socket.emit(e,n):this.socket.emit(e)):this.log("Cannot send - socket not connected")}async sendWithAck(e,n){if(!this.socket)throw new Error("Cannot send - socket not connected");return this.log(`send event ${e}, data: ${JSON.stringify(n)}`),this.socket.emitWithAck(e,n)}sendVolatile(e,n){this.socket&&(void 0!==n?this.socket.volatile.emit(e,n):this.socket.volatile.emit(e))}async flush(e=1e4){if(this.connected)return new Promise(n=>{const a=setTimeout(()=>n(),e);this.socket.emit("ping",()=>{clearTimeout(a),n()})})}updateAuth(e){this.socket&&(this.socket.auth=e),this.config.auth=e}onLifecycle(e,n){this.eventEmitter.on(`lifecycle:${e}`,n)}offLifecycle(e){this.eventEmitter.removeAllListeners(`lifecycle:${e}`)}setupSocketHandlers(){this.socket&&(this.socket.on("connect",()=>{this.log("Connected"),this.eventEmitter.emit("lifecycle:connect",this.socket);for(const[e,n]of this.eventHandlers.entries())this.socket.off(e,n),this.socket.on(e,n);this.KeepAliveManager?.start(this.socket),this.startHealthCheck()}),this.socket.on("disconnect",e=>{this.log("Disconnected:",e),this.eventEmitter.emit("lifecycle:disconnect",e),this.KeepAliveManager?.stop(),this.stopHealthCheck()}),this.socket.on("connect_error",e=>{this.log("Connection error:",e.message),this.eventEmitter.emit("lifecycle:connect_error",e),setTimeout(()=>this.socket?.connect(),5e3)}),this.socket.on("error",e=>{this.log("Socket error:",e),this.eventEmitter.emit("lifecycle:error",e)}))}startHealthCheck(){const e=this.config.healthCheckConfig;if(!1===e?.enabled)return;const n=e?.intervalMs??3e4,a=e?.timeoutMs??5e3;this.stopHealthCheck(),this.healthCheckInterval=setInterval(()=>{if(!this.socket||!this.connected)return;const e=setTimeout(()=>{this.log("Health check timeout - forcing reconnect"),this.socket&&(this.socket.disconnect(),this.socket.connect())},a);this.socket.once("pong",()=>{clearTimeout(e)}),this.socket.emit("ping")},n)}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}log(e,...n){this.config.logger&&this.config.logger(`[SocketClient] ${e}`,...n)}}function un(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var n=e.default;if("function"==typeof n){var a=function e(){var a=!1;try{a=this instanceof e}catch{}return a?Reflect.construct(n,arguments,this.constructor):n.apply(this,arguments)};a.prototype=n.prototype}else a={};return Object.defineProperty(a,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var t=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(a,n,t.get?t:{enumerable:!0,get:function(){return e[n]}})}),a}var mn,gn,hn,fn,xn,vn={},bn={"application/1d-interleaved-parityfec":{source:"iana"},"application/3gpdash-qoe-report+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/3gpp-ims+xml":{source:"iana",compressible:!0},"application/3gpphal+json":{source:"iana",compressible:!0},"application/3gpphalforms+json":{source:"iana",compressible:!0},"application/a2l":{source:"iana"},"application/ace+cbor":{source:"iana"},"application/ace+json":{source:"iana",compressible:!0},"application/ace-groupcomm+cbor":{source:"iana"},"application/ace-trl+cbor":{source:"iana"},"application/activemessage":{source:"iana"},"application/activity+json":{source:"iana",compressible:!0},"application/aif+cbor":{source:"iana"},"application/aif+json":{source:"iana",compressible:!0},"application/alto-cdni+json":{source:"iana",compressible:!0},"application/alto-cdnifilter+json":{source:"iana",compressible:!0},"application/alto-costmap+json":{source:"iana",compressible:!0},"application/alto-costmapfilter+json":{source:"iana",compressible:!0},"application/alto-directory+json":{source:"iana",compressible:!0},"application/alto-endpointcost+json":{source:"iana",compressible:!0},"application/alto-endpointcostparams+json":{source:"iana",compressible:!0},"application/alto-endpointprop+json":{source:"iana",compressible:!0},"application/alto-endpointpropparams+json":{source:"iana",compressible:!0},"application/alto-error+json":{source:"iana",compressible:!0},"application/alto-networkmap+json":{source:"iana",compressible:!0},"application/alto-networkmapfilter+json":{source:"iana",compressible:!0},"application/alto-propmap+json":{source:"iana",compressible:!0},"application/alto-propmapparams+json":{source:"iana",compressible:!0},"application/alto-tips+json":{source:"iana",compressible:!0},"application/alto-tipsparams+json":{source:"iana",compressible:!0},"application/alto-updatestreamcontrol+json":{source:"iana",compressible:!0},"application/alto-updatestreamparams+json":{source:"iana",compressible:!0},"application/aml":{source:"iana"},"application/andrew-inset":{source:"iana",extensions:["ez"]},"application/appinstaller":{compressible:!1,extensions:["appinstaller"]},"application/applefile":{source:"iana"},"application/applixware":{source:"apache",extensions:["aw"]},"application/appx":{compressible:!1,extensions:["appx"]},"application/appxbundle":{compressible:!1,extensions:["appxbundle"]},"application/at+jwt":{source:"iana"},"application/atf":{source:"iana"},"application/atfx":{source:"iana"},"application/atom+xml":{source:"iana",compressible:!0,extensions:["atom"]},"application/atomcat+xml":{source:"iana",compressible:!0,extensions:["atomcat"]},"application/atomdeleted+xml":{source:"iana",compressible:!0,extensions:["atomdeleted"]},"application/atomicmail":{source:"iana"},"application/atomsvc+xml":{source:"iana",compressible:!0,extensions:["atomsvc"]},"application/atsc-dwd+xml":{source:"iana",compressible:!0,extensions:["dwd"]},"application/atsc-dynamic-event-message":{source:"iana"},"application/atsc-held+xml":{source:"iana",compressible:!0,extensions:["held"]},"application/atsc-rdt+json":{source:"iana",compressible:!0},"application/atsc-rsat+xml":{source:"iana",compressible:!0,extensions:["rsat"]},"application/atxml":{source:"iana"},"application/auth-policy+xml":{source:"iana",compressible:!0},"application/automationml-aml+xml":{source:"iana",compressible:!0,extensions:["aml"]},"application/automationml-amlx+zip":{source:"iana",compressible:!1,extensions:["amlx"]},"application/bacnet-xdd+zip":{source:"iana",compressible:!1},"application/batch-smtp":{source:"iana"},"application/bdoc":{compressible:!1,extensions:["bdoc"]},"application/beep+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/bufr":{source:"iana"},"application/c2pa":{source:"iana"},"application/calendar+json":{source:"iana",compressible:!0},"application/calendar+xml":{source:"iana",compressible:!0,extensions:["xcs"]},"application/call-completion":{source:"iana"},"application/cals-1840":{source:"iana"},"application/captive+json":{source:"iana",compressible:!0},"application/cbor":{source:"iana"},"application/cbor-seq":{source:"iana"},"application/cccex":{source:"iana"},"application/ccmp+xml":{source:"iana",compressible:!0},"application/ccxml+xml":{source:"iana",compressible:!0,extensions:["ccxml"]},"application/cda+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/cdfx+xml":{source:"iana",compressible:!0,extensions:["cdfx"]},"application/cdmi-capability":{source:"iana",extensions:["cdmia"]},"application/cdmi-container":{source:"iana",extensions:["cdmic"]},"application/cdmi-domain":{source:"iana",extensions:["cdmid"]},"application/cdmi-object":{source:"iana",extensions:["cdmio"]},"application/cdmi-queue":{source:"iana",extensions:["cdmiq"]},"application/cdni":{source:"iana"},"application/ce+cbor":{source:"iana"},"application/cea":{source:"iana"},"application/cea-2018+xml":{source:"iana",compressible:!0},"application/cellml+xml":{source:"iana",compressible:!0},"application/cfw":{source:"iana"},"application/cid-edhoc+cbor-seq":{source:"iana"},"application/city+json":{source:"iana",compressible:!0},"application/city+json-seq":{source:"iana"},"application/clr":{source:"iana"},"application/clue+xml":{source:"iana",compressible:!0},"application/clue_info+xml":{source:"iana",compressible:!0},"application/cms":{source:"iana"},"application/cnrp+xml":{source:"iana",compressible:!0},"application/coap-eap":{source:"iana"},"application/coap-group+json":{source:"iana",compressible:!0},"application/coap-payload":{source:"iana"},"application/commonground":{source:"iana"},"application/concise-problem-details+cbor":{source:"iana"},"application/conference-info+xml":{source:"iana",compressible:!0},"application/cose":{source:"iana"},"application/cose-key":{source:"iana"},"application/cose-key-set":{source:"iana"},"application/cose-x509":{source:"iana"},"application/cpl+xml":{source:"iana",compressible:!0,extensions:["cpl"]},"application/csrattrs":{source:"iana"},"application/csta+xml":{source:"iana",compressible:!0},"application/cstadata+xml":{source:"iana",compressible:!0},"application/csvm+json":{source:"iana",compressible:!0},"application/cu-seeme":{source:"apache",extensions:["cu"]},"application/cwl":{source:"iana",extensions:["cwl"]},"application/cwl+json":{source:"iana",compressible:!0},"application/cwl+yaml":{source:"iana"},"application/cwt":{source:"iana"},"application/cybercash":{source:"iana"},"application/dart":{compressible:!0},"application/dash+xml":{source:"iana",compressible:!0,extensions:["mpd"]},"application/dash-patch+xml":{source:"iana",compressible:!0,extensions:["mpp"]},"application/dashdelta":{source:"iana"},"application/davmount+xml":{source:"iana",compressible:!0,extensions:["davmount"]},"application/dca-rft":{source:"iana"},"application/dcd":{source:"iana"},"application/dec-dx":{source:"iana"},"application/dialog-info+xml":{source:"iana",compressible:!0},"application/dicom":{source:"iana",extensions:["dcm"]},"application/dicom+json":{source:"iana",compressible:!0},"application/dicom+xml":{source:"iana",compressible:!0},"application/dii":{source:"iana"},"application/dit":{source:"iana"},"application/dns":{source:"iana"},"application/dns+json":{source:"iana",compressible:!0},"application/dns-message":{source:"iana"},"application/docbook+xml":{source:"apache",compressible:!0,extensions:["dbk"]},"application/dots+cbor":{source:"iana"},"application/dpop+jwt":{source:"iana"},"application/dskpp+xml":{source:"iana",compressible:!0},"application/dssc+der":{source:"iana",extensions:["dssc"]},"application/dssc+xml":{source:"iana",compressible:!0,extensions:["xdssc"]},"application/dvcs":{source:"iana"},"application/eat+cwt":{source:"iana"},"application/eat+jwt":{source:"iana"},"application/eat-bun+cbor":{source:"iana"},"application/eat-bun+json":{source:"iana",compressible:!0},"application/eat-ucs+cbor":{source:"iana"},"application/eat-ucs+json":{source:"iana",compressible:!0},"application/ecmascript":{source:"apache",compressible:!0,extensions:["ecma"]},"application/edhoc+cbor-seq":{source:"iana"},"application/edi-consent":{source:"iana"},"application/edi-x12":{source:"iana",compressible:!1},"application/edifact":{source:"iana",compressible:!1},"application/efi":{source:"iana"},"application/elm+json":{source:"iana",charset:"UTF-8",compressible:!0},"application/elm+xml":{source:"iana",compressible:!0},"application/emergencycalldata.cap+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/emergencycalldata.comment+xml":{source:"iana",compressible:!0},"application/emergencycalldata.control+xml":{source:"iana",compressible:!0},"application/emergencycalldata.deviceinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.ecall.msd":{source:"iana"},"application/emergencycalldata.legacyesn+json":{source:"iana",compressible:!0},"application/emergencycalldata.providerinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.serviceinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.subscriberinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.veds+xml":{source:"iana",compressible:!0},"application/emma+xml":{source:"iana",compressible:!0,extensions:["emma"]},"application/emotionml+xml":{source:"iana",compressible:!0,extensions:["emotionml"]},"application/encaprtp":{source:"iana"},"application/entity-statement+jwt":{source:"iana"},"application/epp+xml":{source:"iana",compressible:!0},"application/epub+zip":{source:"iana",compressible:!1,extensions:["epub"]},"application/eshop":{source:"iana"},"application/exi":{source:"iana",extensions:["exi"]},"application/expect-ct-report+json":{source:"iana",compressible:!0},"application/express":{source:"iana",extensions:["exp"]},"application/fastinfoset":{source:"iana"},"application/fastsoap":{source:"iana"},"application/fdf":{source:"iana",extensions:["fdf"]},"application/fdt+xml":{source:"iana",compressible:!0,extensions:["fdt"]},"application/fhir+json":{source:"iana",charset:"UTF-8",compressible:!0},"application/fhir+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/fido.trusted-apps+json":{compressible:!0},"application/fits":{source:"iana"},"application/flexfec":{source:"iana"},"application/font-sfnt":{source:"iana"},"application/font-tdpfr":{source:"iana",extensions:["pfr"]},"application/font-woff":{source:"iana",compressible:!1},"application/framework-attributes+xml":{source:"iana",compressible:!0},"application/geo+json":{source:"iana",compressible:!0,extensions:["geojson"]},"application/geo+json-seq":{source:"iana"},"application/geopackage+sqlite3":{source:"iana"},"application/geopose+json":{source:"iana",compressible:!0},"application/geoxacml+json":{source:"iana",compressible:!0},"application/geoxacml+xml":{source:"iana",compressible:!0},"application/gltf-buffer":{source:"iana"},"application/gml+xml":{source:"iana",compressible:!0,extensions:["gml"]},"application/gnap-binding-jws":{source:"iana"},"application/gnap-binding-jwsd":{source:"iana"},"application/gnap-binding-rotation-jws":{source:"iana"},"application/gnap-binding-rotation-jwsd":{source:"iana"},"application/gpx+xml":{source:"apache",compressible:!0,extensions:["gpx"]},"application/grib":{source:"iana"},"application/gxf":{source:"apache",extensions:["gxf"]},"application/gzip":{source:"iana",compressible:!1,extensions:["gz"]},"application/h224":{source:"iana"},"application/held+xml":{source:"iana",compressible:!0},"application/hjson":{extensions:["hjson"]},"application/hl7v2+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/http":{source:"iana"},"application/hyperstudio":{source:"iana",extensions:["stk"]},"application/ibe-key-request+xml":{source:"iana",compressible:!0},"application/ibe-pkg-reply+xml":{source:"iana",compressible:!0},"application/ibe-pp-data":{source:"iana"},"application/iges":{source:"iana"},"application/im-iscomposing+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/index":{source:"iana"},"application/index.cmd":{source:"iana"},"application/index.obj":{source:"iana"},"application/index.response":{source:"iana"},"application/index.vnd":{source:"iana"},"application/inkml+xml":{source:"iana",compressible:!0,extensions:["ink","inkml"]},"application/iotp":{source:"iana"},"application/ipfix":{source:"iana",extensions:["ipfix"]},"application/ipp":{source:"iana"},"application/isup":{source:"iana"},"application/its+xml":{source:"iana",compressible:!0,extensions:["its"]},"application/java-archive":{source:"iana",compressible:!1,extensions:["jar","war","ear"]},"application/java-serialized-object":{source:"apache",compressible:!1,extensions:["ser"]},"application/java-vm":{source:"apache",compressible:!1,extensions:["class"]},"application/javascript":{source:"apache",charset:"UTF-8",compressible:!0,extensions:["js"]},"application/jf2feed+json":{source:"iana",compressible:!0},"application/jose":{source:"iana"},"application/jose+json":{source:"iana",compressible:!0},"application/jrd+json":{source:"iana",compressible:!0},"application/jscalendar+json":{source:"iana",compressible:!0},"application/jscontact+json":{source:"iana",compressible:!0},"application/json":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["json","map"]},"application/json-patch+json":{source:"iana",compressible:!0},"application/json-seq":{source:"iana"},"application/json5":{extensions:["json5"]},"application/jsonml+json":{source:"apache",compressible:!0,extensions:["jsonml"]},"application/jsonpath":{source:"iana"},"application/jwk+json":{source:"iana",compressible:!0},"application/jwk-set+json":{source:"iana",compressible:!0},"application/jwk-set+jwt":{source:"iana"},"application/jwt":{source:"iana"},"application/kpml-request+xml":{source:"iana",compressible:!0},"application/kpml-response+xml":{source:"iana",compressible:!0},"application/ld+json":{source:"iana",compressible:!0,extensions:["jsonld"]},"application/lgr+xml":{source:"iana",compressible:!0,extensions:["lgr"]},"application/link-format":{source:"iana"},"application/linkset":{source:"iana"},"application/linkset+json":{source:"iana",compressible:!0},"application/load-control+xml":{source:"iana",compressible:!0},"application/logout+jwt":{source:"iana"},"application/lost+xml":{source:"iana",compressible:!0,extensions:["lostxml"]},"application/lostsync+xml":{source:"iana",compressible:!0},"application/lpf+zip":{source:"iana",compressible:!1},"application/lxf":{source:"iana"},"application/mac-binhex40":{source:"iana",extensions:["hqx"]},"application/mac-compactpro":{source:"apache",extensions:["cpt"]},"application/macwriteii":{source:"iana"},"application/mads+xml":{source:"iana",compressible:!0,extensions:["mads"]},"application/manifest+json":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["webmanifest"]},"application/marc":{source:"iana",extensions:["mrc"]},"application/marcxml+xml":{source:"iana",compressible:!0,extensions:["mrcx"]},"application/mathematica":{source:"iana",extensions:["ma","nb","mb"]},"application/mathml+xml":{source:"iana",compressible:!0,extensions:["mathml"]},"application/mathml-content+xml":{source:"iana",compressible:!0},"application/mathml-presentation+xml":{source:"iana",compressible:!0},"application/mbms-associated-procedure-description+xml":{source:"iana",compressible:!0},"application/mbms-deregister+xml":{source:"iana",compressible:!0},"application/mbms-envelope+xml":{source:"iana",compressible:!0},"application/mbms-msk+xml":{source:"iana",compressible:!0},"application/mbms-msk-response+xml":{source:"iana",compressible:!0},"application/mbms-protection-description+xml":{source:"iana",compressible:!0},"application/mbms-reception-report+xml":{source:"iana",compressible:!0},"application/mbms-register+xml":{source:"iana",compressible:!0},"application/mbms-register-response+xml":{source:"iana",compressible:!0},"application/mbms-schedule+xml":{source:"iana",compressible:!0},"application/mbms-user-service-description+xml":{source:"iana",compressible:!0},"application/mbox":{source:"iana",extensions:["mbox"]},"application/media-policy-dataset+xml":{source:"iana",compressible:!0,extensions:["mpf"]},"application/media_control+xml":{source:"iana",compressible:!0},"application/mediaservercontrol+xml":{source:"iana",compressible:!0,extensions:["mscml"]},"application/merge-patch+json":{source:"iana",compressible:!0},"application/metalink+xml":{source:"apache",compressible:!0,extensions:["metalink"]},"application/metalink4+xml":{source:"iana",compressible:!0,extensions:["meta4"]},"application/mets+xml":{source:"iana",compressible:!0,extensions:["mets"]},"application/mf4":{source:"iana"},"application/mikey":{source:"iana"},"application/mipc":{source:"iana"},"application/missing-blocks+cbor-seq":{source:"iana"},"application/mmt-aei+xml":{source:"iana",compressible:!0,extensions:["maei"]},"application/mmt-usd+xml":{source:"iana",compressible:!0,extensions:["musd"]},"application/mods+xml":{source:"iana",compressible:!0,extensions:["mods"]},"application/moss-keys":{source:"iana"},"application/moss-signature":{source:"iana"},"application/mosskey-data":{source:"iana"},"application/mosskey-request":{source:"iana"},"application/mp21":{source:"iana",extensions:["m21","mp21"]},"application/mp4":{source:"iana",extensions:["mp4","mpg4","mp4s","m4p"]},"application/mpeg4-generic":{source:"iana"},"application/mpeg4-iod":{source:"iana"},"application/mpeg4-iod-xmt":{source:"iana"},"application/mrb-consumer+xml":{source:"iana",compressible:!0},"application/mrb-publish+xml":{source:"iana",compressible:!0},"application/msc-ivr+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/msc-mixer+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/msix":{compressible:!1,extensions:["msix"]},"application/msixbundle":{compressible:!1,extensions:["msixbundle"]},"application/msword":{source:"iana",compressible:!1,extensions:["doc","dot"]},"application/mud+json":{source:"iana",compressible:!0},"application/multipart-core":{source:"iana"},"application/mxf":{source:"iana",extensions:["mxf"]},"application/n-quads":{source:"iana",extensions:["nq"]},"application/n-triples":{source:"iana",extensions:["nt"]},"application/nasdata":{source:"iana"},"application/news-checkgroups":{source:"iana",charset:"US-ASCII"},"application/news-groupinfo":{source:"iana",charset:"US-ASCII"},"application/news-transmission":{source:"iana"},"application/nlsml+xml":{source:"iana",compressible:!0},"application/node":{source:"iana",extensions:["cjs"]},"application/nss":{source:"iana"},"application/oauth-authz-req+jwt":{source:"iana"},"application/oblivious-dns-message":{source:"iana"},"application/ocsp-request":{source:"iana"},"application/ocsp-response":{source:"iana"},"application/octet-stream":{source:"iana",compressible:!0,extensions:["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{source:"iana",extensions:["oda"]},"application/odm+xml":{source:"iana",compressible:!0},"application/odx":{source:"iana"},"application/oebps-package+xml":{source:"iana",compressible:!0,extensions:["opf"]},"application/ogg":{source:"iana",compressible:!1,extensions:["ogx"]},"application/ohttp-keys":{source:"iana"},"application/omdoc+xml":{source:"apache",compressible:!0,extensions:["omdoc"]},"application/onenote":{source:"apache",extensions:["onetoc","onetoc2","onetmp","onepkg","one","onea"]},"application/opc-nodeset+xml":{source:"iana",compressible:!0},"application/oscore":{source:"iana"},"application/oxps":{source:"iana",extensions:["oxps"]},"application/p21":{source:"iana"},"application/p21+zip":{source:"iana",compressible:!1},"application/p2p-overlay+xml":{source:"iana",compressible:!0,extensions:["relo"]},"application/parityfec":{source:"iana"},"application/passport":{source:"iana"},"application/patch-ops-error+xml":{source:"iana",compressible:!0,extensions:["xer"]},"application/pdf":{source:"iana",compressible:!1,extensions:["pdf"]},"application/pdx":{source:"iana"},"application/pem-certificate-chain":{source:"iana"},"application/pgp-encrypted":{source:"iana",compressible:!1,extensions:["pgp"]},"application/pgp-keys":{source:"iana",extensions:["asc"]},"application/pgp-signature":{source:"iana",extensions:["sig","asc"]},"application/pics-rules":{source:"apache",extensions:["prf"]},"application/pidf+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/pidf-diff+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/pkcs10":{source:"iana",extensions:["p10"]},"application/pkcs12":{source:"iana"},"application/pkcs7-mime":{source:"iana",extensions:["p7m","p7c"]},"application/pkcs7-signature":{source:"iana",extensions:["p7s"]},"application/pkcs8":{source:"iana",extensions:["p8"]},"application/pkcs8-encrypted":{source:"iana"},"application/pkix-attr-cert":{source:"iana",extensions:["ac"]},"application/pkix-cert":{source:"iana",extensions:["cer"]},"application/pkix-crl":{source:"iana",extensions:["crl"]},"application/pkix-pkipath":{source:"iana",extensions:["pkipath"]},"application/pkixcmp":{source:"iana",extensions:["pki"]},"application/pls+xml":{source:"iana",compressible:!0,extensions:["pls"]},"application/poc-settings+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/postscript":{source:"iana",compressible:!0,extensions:["ai","eps","ps"]},"application/ppsp-tracker+json":{source:"iana",compressible:!0},"application/private-token-issuer-directory":{source:"iana"},"application/private-token-request":{source:"iana"},"application/private-token-response":{source:"iana"},"application/problem+json":{source:"iana",compressible:!0},"application/problem+xml":{source:"iana",compressible:!0},"application/provenance+xml":{source:"iana",compressible:!0,extensions:["provx"]},"application/provided-claims+jwt":{source:"iana"},"application/prs.alvestrand.titrax-sheet":{source:"iana"},"application/prs.cww":{source:"iana",extensions:["cww"]},"application/prs.cyn":{source:"iana",charset:"7-BIT"},"application/prs.hpub+zip":{source:"iana",compressible:!1},"application/prs.implied-document+xml":{source:"iana",compressible:!0},"application/prs.implied-executable":{source:"iana"},"application/prs.implied-object+json":{source:"iana",compressible:!0},"application/prs.implied-object+json-seq":{source:"iana"},"application/prs.implied-object+yaml":{source:"iana"},"application/prs.implied-structure":{source:"iana"},"application/prs.mayfile":{source:"iana"},"application/prs.nprend":{source:"iana"},"application/prs.plucker":{source:"iana"},"application/prs.rdf-xml-crypt":{source:"iana"},"application/prs.vcfbzip2":{source:"iana"},"application/prs.xsf+xml":{source:"iana",compressible:!0,extensions:["xsf"]},"application/pskc+xml":{source:"iana",compressible:!0,extensions:["pskcxml"]},"application/pvd+json":{source:"iana",compressible:!0},"application/qsig":{source:"iana"},"application/raml+yaml":{compressible:!0,extensions:["raml"]},"application/raptorfec":{source:"iana"},"application/rdap+json":{source:"iana",compressible:!0},"application/rdf+xml":{source:"iana",compressible:!0,extensions:["rdf","owl"]},"application/reginfo+xml":{source:"iana",compressible:!0,extensions:["rif"]},"application/relax-ng-compact-syntax":{source:"iana",extensions:["rnc"]},"application/remote-printing":{source:"apache"},"application/reputon+json":{source:"iana",compressible:!0},"application/resolve-response+jwt":{source:"iana"},"application/resource-lists+xml":{source:"iana",compressible:!0,extensions:["rl"]},"application/resource-lists-diff+xml":{source:"iana",compressible:!0,extensions:["rld"]},"application/rfc+xml":{source:"iana",compressible:!0},"application/riscos":{source:"iana"},"application/rlmi+xml":{source:"iana",compressible:!0},"application/rls-services+xml":{source:"iana",compressible:!0,extensions:["rs"]},"application/route-apd+xml":{source:"iana",compressible:!0,extensions:["rapd"]},"application/route-s-tsid+xml":{source:"iana",compressible:!0,extensions:["sls"]},"application/route-usd+xml":{source:"iana",compressible:!0,extensions:["rusd"]},"application/rpki-checklist":{source:"iana"},"application/rpki-ghostbusters":{source:"iana",extensions:["gbr"]},"application/rpki-manifest":{source:"iana",extensions:["mft"]},"application/rpki-publication":{source:"iana"},"application/rpki-roa":{source:"iana",extensions:["roa"]},"application/rpki-signed-tal":{source:"iana"},"application/rpki-updown":{source:"iana"},"application/rsd+xml":{source:"apache",compressible:!0,extensions:["rsd"]},"application/rss+xml":{source:"apache",compressible:!0,extensions:["rss"]},"application/rtf":{source:"iana",compressible:!0,extensions:["rtf"]},"application/rtploopback":{source:"iana"},"application/rtx":{source:"iana"},"application/samlassertion+xml":{source:"iana",compressible:!0},"application/samlmetadata+xml":{source:"iana",compressible:!0},"application/sarif+json":{source:"iana",compressible:!0},"application/sarif-external-properties+json":{source:"iana",compressible:!0},"application/sbe":{source:"iana"},"application/sbml+xml":{source:"iana",compressible:!0,extensions:["sbml"]},"application/scaip+xml":{source:"iana",compressible:!0},"application/scim+json":{source:"iana",compressible:!0},"application/scvp-cv-request":{source:"iana",extensions:["scq"]},"application/scvp-cv-response":{source:"iana",extensions:["scs"]},"application/scvp-vp-request":{source:"iana",extensions:["spq"]},"application/scvp-vp-response":{source:"iana",extensions:["spp"]},"application/sdp":{source:"iana",extensions:["sdp"]},"application/secevent+jwt":{source:"iana"},"application/senml+cbor":{source:"iana"},"application/senml+json":{source:"iana",compressible:!0},"application/senml+xml":{source:"iana",compressible:!0,extensions:["senmlx"]},"application/senml-etch+cbor":{source:"iana"},"application/senml-etch+json":{source:"iana",compressible:!0},"application/senml-exi":{source:"iana"},"application/sensml+cbor":{source:"iana"},"application/sensml+json":{source:"iana",compressible:!0},"application/sensml+xml":{source:"iana",compressible:!0,extensions:["sensmlx"]},"application/sensml-exi":{source:"iana"},"application/sep+xml":{source:"iana",compressible:!0},"application/sep-exi":{source:"iana"},"application/session-info":{source:"iana"},"application/set-payment":{source:"iana"},"application/set-payment-initiation":{source:"iana",extensions:["setpay"]},"application/set-registration":{source:"iana"},"application/set-registration-initiation":{source:"iana",extensions:["setreg"]},"application/sgml":{source:"iana"},"application/sgml-open-catalog":{source:"iana"},"application/shf+xml":{source:"iana",compressible:!0,extensions:["shf"]},"application/sieve":{source:"iana",extensions:["siv","sieve"]},"application/simple-filter+xml":{source:"iana",compressible:!0},"application/simple-message-summary":{source:"iana"},"application/simplesymbolcontainer":{source:"iana"},"application/sipc":{source:"iana"},"application/slate":{source:"iana"},"application/smil":{source:"apache"},"application/smil+xml":{source:"iana",compressible:!0,extensions:["smi","smil"]},"application/smpte336m":{source:"iana"},"application/soap+fastinfoset":{source:"iana"},"application/soap+xml":{source:"iana",compressible:!0},"application/sparql-query":{source:"iana",extensions:["rq"]},"application/sparql-results+xml":{source:"iana",compressible:!0,extensions:["srx"]},"application/spdx+json":{source:"iana",compressible:!0},"application/spirits-event+xml":{source:"iana",compressible:!0},"application/sql":{source:"iana",extensions:["sql"]},"application/srgs":{source:"iana",extensions:["gram"]},"application/srgs+xml":{source:"iana",compressible:!0,extensions:["grxml"]},"application/sru+xml":{source:"iana",compressible:!0,extensions:["sru"]},"application/ssdl+xml":{source:"apache",compressible:!0,extensions:["ssdl"]},"application/sslkeylogfile":{source:"iana"},"application/ssml+xml":{source:"iana",compressible:!0,extensions:["ssml"]},"application/st2110-41":{source:"iana"},"application/stix+json":{source:"iana",compressible:!0},"application/stratum":{source:"iana"},"application/swid+cbor":{source:"iana"},"application/swid+xml":{source:"iana",compressible:!0,extensions:["swidtag"]},"application/tamp-apex-update":{source:"iana"},"application/tamp-apex-update-confirm":{source:"iana"},"application/tamp-community-update":{source:"iana"},"application/tamp-community-update-confirm":{source:"iana"},"application/tamp-error":{source:"iana"},"application/tamp-sequence-adjust":{source:"iana"},"application/tamp-sequence-adjust-confirm":{source:"iana"},"application/tamp-status-query":{source:"iana"},"application/tamp-status-response":{source:"iana"},"application/tamp-update":{source:"iana"},"application/tamp-update-confirm":{source:"iana"},"application/tar":{compressible:!0},"application/taxii+json":{source:"iana",compressible:!0},"application/td+json":{source:"iana",compressible:!0},"application/tei+xml":{source:"iana",compressible:!0,extensions:["tei","teicorpus"]},"application/tetra_isi":{source:"iana"},"application/thraud+xml":{source:"iana",compressible:!0,extensions:["tfi"]},"application/timestamp-query":{source:"iana"},"application/timestamp-reply":{source:"iana"},"application/timestamped-data":{source:"iana",extensions:["tsd"]},"application/tlsrpt+gzip":{source:"iana"},"application/tlsrpt+json":{source:"iana",compressible:!0},"application/tm+json":{source:"iana",compressible:!0},"application/tnauthlist":{source:"iana"},"application/toc+cbor":{source:"iana"},"application/token-introspection+jwt":{source:"iana"},"application/toml":{source:"iana",compressible:!0,extensions:["toml"]},"application/trickle-ice-sdpfrag":{source:"iana"},"application/trig":{source:"iana",extensions:["trig"]},"application/trust-chain+json":{source:"iana",compressible:!0},"application/trust-mark+jwt":{source:"iana"},"application/trust-mark-delegation+jwt":{source:"iana"},"application/ttml+xml":{source:"iana",compressible:!0,extensions:["ttml"]},"application/tve-trigger":{source:"iana"},"application/tzif":{source:"iana"},"application/tzif-leap":{source:"iana"},"application/ubjson":{compressible:!1,extensions:["ubj"]},"application/uccs+cbor":{source:"iana"},"application/ujcs+json":{source:"iana",compressible:!0},"application/ulpfec":{source:"iana"},"application/urc-grpsheet+xml":{source:"iana",compressible:!0},"application/urc-ressheet+xml":{source:"iana",compressible:!0,extensions:["rsheet"]},"application/urc-targetdesc+xml":{source:"iana",compressible:!0,extensions:["td"]},"application/urc-uisocketdesc+xml":{source:"iana",compressible:!0},"application/vc":{source:"iana"},"application/vc+cose":{source:"iana"},"application/vc+jwt":{source:"iana"},"application/vcard+json":{source:"iana",compressible:!0},"application/vcard+xml":{source:"iana",compressible:!0},"application/vemmi":{source:"iana"},"application/vividence.scriptfile":{source:"apache"},"application/vnd.1000minds.decision-model+xml":{source:"iana",compressible:!0,extensions:["1km"]},"application/vnd.1ob":{source:"iana"},"application/vnd.3gpp-prose+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3a+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3ach+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3ch+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc8+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-v2x-local-service-information":{source:"iana"},"application/vnd.3gpp.5gnas":{source:"iana"},"application/vnd.3gpp.5gsa2x":{source:"iana"},"application/vnd.3gpp.5gsa2x-local-service-information":{source:"iana"},"application/vnd.3gpp.5gsv2x":{source:"iana"},"application/vnd.3gpp.5gsv2x-local-service-information":{source:"iana"},"application/vnd.3gpp.access-transfer-events+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.bsf+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.crs+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.current-location-discovery+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.gmop+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.gtpc":{source:"iana"},"application/vnd.3gpp.interworking-data":{source:"iana"},"application/vnd.3gpp.lpp":{source:"iana"},"application/vnd.3gpp.mc-signalling-ear":{source:"iana"},"application/vnd.3gpp.mcdata-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-msgstore-ctrl-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-payload":{source:"iana"},"application/vnd.3gpp.mcdata-regroup+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-signalling":{source:"iana"},"application/vnd.3gpp.mcdata-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-floor-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-regroup+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-signed+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-ue-init-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-regroup+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-transmission-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mid-call+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.ngap":{source:"iana"},"application/vnd.3gpp.pfcp":{source:"iana"},"application/vnd.3gpp.pic-bw-large":{source:"iana",extensions:["plb"]},"application/vnd.3gpp.pic-bw-small":{source:"iana",extensions:["psb"]},"application/vnd.3gpp.pic-bw-var":{source:"iana",extensions:["pvb"]},"application/vnd.3gpp.pinapp-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.s1ap":{source:"iana"},"application/vnd.3gpp.seal-group-doc+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-network-qos-management-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-ue-config-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-unicast-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-user-profile-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.sms":{source:"iana"},"application/vnd.3gpp.sms+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.srvcc-ext+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.srvcc-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.state-and-event-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.ussd+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.v2x":{source:"iana"},"application/vnd.3gpp.vae-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp2.bcmcsinfo+xml":{source:"iana",compressible:!0},"application/vnd.3gpp2.sms":{source:"iana"},"application/vnd.3gpp2.tcap":{source:"iana",extensions:["tcap"]},"application/vnd.3lightssoftware.imagescal":{source:"iana"},"application/vnd.3m.post-it-notes":{source:"iana",extensions:["pwn"]},"application/vnd.accpac.simply.aso":{source:"iana",extensions:["aso"]},"application/vnd.accpac.simply.imp":{source:"iana",extensions:["imp"]},"application/vnd.acm.addressxfer+json":{source:"iana",compressible:!0},"application/vnd.acm.chatbot+json":{source:"iana",compressible:!0},"application/vnd.acucobol":{source:"iana",extensions:["acu"]},"application/vnd.acucorp":{source:"iana",extensions:["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{source:"apache",compressible:!1,extensions:["air"]},"application/vnd.adobe.flash.movie":{source:"iana"},"application/vnd.adobe.formscentral.fcdt":{source:"iana",extensions:["fcdt"]},"application/vnd.adobe.fxp":{source:"iana",extensions:["fxp","fxpl"]},"application/vnd.adobe.partial-upload":{source:"iana"},"application/vnd.adobe.xdp+xml":{source:"iana",compressible:!0,extensions:["xdp"]},"application/vnd.adobe.xfdf":{source:"apache",extensions:["xfdf"]},"application/vnd.aether.imp":{source:"iana"},"application/vnd.afpc.afplinedata":{source:"iana"},"application/vnd.afpc.afplinedata-pagedef":{source:"iana"},"application/vnd.afpc.cmoca-cmresource":{source:"iana"},"application/vnd.afpc.foca-charset":{source:"iana"},"application/vnd.afpc.foca-codedfont":{source:"iana"},"application/vnd.afpc.foca-codepage":{source:"iana"},"application/vnd.afpc.modca":{source:"iana"},"application/vnd.afpc.modca-cmtable":{source:"iana"},"application/vnd.afpc.modca-formdef":{source:"iana"},"application/vnd.afpc.modca-mediummap":{source:"iana"},"application/vnd.afpc.modca-objectcontainer":{source:"iana"},"application/vnd.afpc.modca-overlay":{source:"iana"},"application/vnd.afpc.modca-pagesegment":{source:"iana"},"application/vnd.age":{source:"iana",extensions:["age"]},"application/vnd.ah-barcode":{source:"apache"},"application/vnd.ahead.space":{source:"iana",extensions:["ahead"]},"application/vnd.airzip.filesecure.azf":{source:"iana",extensions:["azf"]},"application/vnd.airzip.filesecure.azs":{source:"iana",extensions:["azs"]},"application/vnd.amadeus+json":{source:"iana",compressible:!0},"application/vnd.amazon.ebook":{source:"apache",extensions:["azw"]},"application/vnd.amazon.mobi8-ebook":{source:"iana"},"application/vnd.americandynamics.acc":{source:"iana",extensions:["acc"]},"application/vnd.amiga.ami":{source:"iana",extensions:["ami"]},"application/vnd.amundsen.maze+xml":{source:"iana",compressible:!0},"application/vnd.android.ota":{source:"iana"},"application/vnd.android.package-archive":{source:"apache",compressible:!1,extensions:["apk"]},"application/vnd.anki":{source:"iana"},"application/vnd.anser-web-certificate-issue-initiation":{source:"iana",extensions:["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{source:"apache",extensions:["fti"]},"application/vnd.antix.game-component":{source:"iana",extensions:["atx"]},"application/vnd.apache.arrow.file":{source:"iana"},"application/vnd.apache.arrow.stream":{source:"iana"},"application/vnd.apache.parquet":{source:"iana"},"application/vnd.apache.thrift.binary":{source:"iana"},"application/vnd.apache.thrift.compact":{source:"iana"},"application/vnd.apache.thrift.json":{source:"iana"},"application/vnd.apexlang":{source:"iana"},"application/vnd.api+json":{source:"iana",compressible:!0},"application/vnd.aplextor.warrp+json":{source:"iana",compressible:!0},"application/vnd.apothekende.reservation+json":{source:"iana",compressible:!0},"application/vnd.apple.installer+xml":{source:"iana",compressible:!0,extensions:["mpkg"]},"application/vnd.apple.keynote":{source:"iana",extensions:["key"]},"application/vnd.apple.mpegurl":{source:"iana",extensions:["m3u8"]},"application/vnd.apple.numbers":{source:"iana",extensions:["numbers"]},"application/vnd.apple.pages":{source:"iana",extensions:["pages"]},"application/vnd.apple.pkpass":{compressible:!1,extensions:["pkpass"]},"application/vnd.arastra.swi":{source:"apache"},"application/vnd.aristanetworks.swi":{source:"iana",extensions:["swi"]},"application/vnd.artisan+json":{source:"iana",compressible:!0},"application/vnd.artsquare":{source:"iana"},"application/vnd.astraea-software.iota":{source:"iana",extensions:["iota"]},"application/vnd.audiograph":{source:"iana",extensions:["aep"]},"application/vnd.autodesk.fbx":{extensions:["fbx"]},"application/vnd.autopackage":{source:"iana"},"application/vnd.avalon+json":{source:"iana",compressible:!0},"application/vnd.avistar+xml":{source:"iana",compressible:!0},"application/vnd.balsamiq.bmml+xml":{source:"iana",compressible:!0,extensions:["bmml"]},"application/vnd.balsamiq.bmpr":{source:"iana"},"application/vnd.banana-accounting":{source:"iana"},"application/vnd.bbf.usp.error":{source:"iana"},"application/vnd.bbf.usp.msg":{source:"iana"},"application/vnd.bbf.usp.msg+json":{source:"iana",compressible:!0},"application/vnd.bekitzur-stech+json":{source:"iana",compressible:!0},"application/vnd.belightsoft.lhzd+zip":{source:"iana",compressible:!1},"application/vnd.belightsoft.lhzl+zip":{source:"iana",compressible:!1},"application/vnd.bint.med-content":{source:"iana"},"application/vnd.biopax.rdf+xml":{source:"iana",compressible:!0},"application/vnd.blink-idb-value-wrapper":{source:"iana"},"application/vnd.blueice.multipass":{source:"iana",extensions:["mpm"]},"application/vnd.bluetooth.ep.oob":{source:"iana"},"application/vnd.bluetooth.le.oob":{source:"iana"},"application/vnd.bmi":{source:"iana",extensions:["bmi"]},"application/vnd.bpf":{source:"iana"},"application/vnd.bpf3":{source:"iana"},"application/vnd.businessobjects":{source:"iana",extensions:["rep"]},"application/vnd.byu.uapi+json":{source:"iana",compressible:!0},"application/vnd.bzip3":{source:"iana"},"application/vnd.c3voc.schedule+xml":{source:"iana",compressible:!0},"application/vnd.cab-jscript":{source:"iana"},"application/vnd.canon-cpdl":{source:"iana"},"application/vnd.canon-lips":{source:"iana"},"application/vnd.capasystems-pg+json":{source:"iana",compressible:!0},"application/vnd.cendio.thinlinc.clientconf":{source:"iana"},"application/vnd.century-systems.tcp_stream":{source:"iana"},"application/vnd.chemdraw+xml":{source:"iana",compressible:!0,extensions:["cdxml"]},"application/vnd.chess-pgn":{source:"iana"},"application/vnd.chipnuts.karaoke-mmd":{source:"iana",extensions:["mmd"]},"application/vnd.ciedi":{source:"iana"},"application/vnd.cinderella":{source:"iana",extensions:["cdy"]},"application/vnd.cirpack.isdn-ext":{source:"iana"},"application/vnd.citationstyles.style+xml":{source:"iana",compressible:!0,extensions:["csl"]},"application/vnd.claymore":{source:"iana",extensions:["cla"]},"application/vnd.cloanto.rp9":{source:"iana",extensions:["rp9"]},"application/vnd.clonk.c4group":{source:"iana",extensions:["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{source:"iana",extensions:["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{source:"iana",extensions:["c11amz"]},"application/vnd.cncf.helm.chart.content.v1.tar+gzip":{source:"iana"},"application/vnd.cncf.helm.chart.provenance.v1.prov":{source:"iana"},"application/vnd.cncf.helm.config.v1+json":{source:"iana",compressible:!0},"application/vnd.coffeescript":{source:"iana"},"application/vnd.collabio.xodocuments.document":{source:"iana"},"application/vnd.collabio.xodocuments.document-template":{source:"iana"},"application/vnd.collabio.xodocuments.presentation":{source:"iana"},"application/vnd.collabio.xodocuments.presentation-template":{source:"iana"},"application/vnd.collabio.xodocuments.spreadsheet":{source:"iana"},"application/vnd.collabio.xodocuments.spreadsheet-template":{source:"iana"},"application/vnd.collection+json":{source:"iana",compressible:!0},"application/vnd.collection.doc+json":{source:"iana",compressible:!0},"application/vnd.collection.next+json":{source:"iana",compressible:!0},"application/vnd.comicbook+zip":{source:"iana",compressible:!1},"application/vnd.comicbook-rar":{source:"iana"},"application/vnd.commerce-battelle":{source:"iana"},"application/vnd.commonspace":{source:"iana",extensions:["csp"]},"application/vnd.contact.cmsg":{source:"iana",extensions:["cdbcmsg"]},"application/vnd.coreos.ignition+json":{source:"iana",compressible:!0},"application/vnd.cosmocaller":{source:"iana",extensions:["cmc"]},"application/vnd.crick.clicker":{source:"iana",extensions:["clkx"]},"application/vnd.crick.clicker.keyboard":{source:"iana",extensions:["clkk"]},"application/vnd.crick.clicker.palette":{source:"iana",extensions:["clkp"]},"application/vnd.crick.clicker.template":{source:"iana",extensions:["clkt"]},"application/vnd.crick.clicker.wordbank":{source:"iana",extensions:["clkw"]},"application/vnd.criticaltools.wbs+xml":{source:"iana",compressible:!0,extensions:["wbs"]},"application/vnd.cryptii.pipe+json":{source:"iana",compressible:!0},"application/vnd.crypto-shade-file":{source:"iana"},"application/vnd.cryptomator.encrypted":{source:"iana"},"application/vnd.cryptomator.vault":{source:"iana"},"application/vnd.ctc-posml":{source:"iana",extensions:["pml"]},"application/vnd.ctct.ws+xml":{source:"iana",compressible:!0},"application/vnd.cups-pdf":{source:"iana"},"application/vnd.cups-postscript":{source:"iana"},"application/vnd.cups-ppd":{source:"iana",extensions:["ppd"]},"application/vnd.cups-raster":{source:"iana"},"application/vnd.cups-raw":{source:"iana"},"application/vnd.curl":{source:"iana"},"application/vnd.curl.car":{source:"apache",extensions:["car"]},"application/vnd.curl.pcurl":{source:"apache",extensions:["pcurl"]},"application/vnd.cyan.dean.root+xml":{source:"iana",compressible:!0},"application/vnd.cybank":{source:"iana"},"application/vnd.cyclonedx+json":{source:"iana",compressible:!0},"application/vnd.cyclonedx+xml":{source:"iana",compressible:!0},"application/vnd.d2l.coursepackage1p0+zip":{source:"iana",compressible:!1},"application/vnd.d3m-dataset":{source:"iana"},"application/vnd.d3m-problem":{source:"iana"},"application/vnd.dart":{source:"iana",compressible:!0,extensions:["dart"]},"application/vnd.data-vision.rdz":{source:"iana",extensions:["rdz"]},"application/vnd.datalog":{source:"iana"},"application/vnd.datapackage+json":{source:"iana",compressible:!0},"application/vnd.dataresource+json":{source:"iana",compressible:!0},"application/vnd.dbf":{source:"iana",extensions:["dbf"]},"application/vnd.dcmp+xml":{source:"iana",compressible:!0,extensions:["dcmp"]},"application/vnd.debian.binary-package":{source:"iana"},"application/vnd.dece.data":{source:"iana",extensions:["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{source:"iana",compressible:!0,extensions:["uvt","uvvt"]},"application/vnd.dece.unspecified":{source:"iana",extensions:["uvx","uvvx"]},"application/vnd.dece.zip":{source:"iana",extensions:["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{source:"iana",extensions:["fe_launch"]},"application/vnd.desmume.movie":{source:"iana"},"application/vnd.dir-bi.plate-dl-nosuffix":{source:"iana"},"application/vnd.dm.delegation+xml":{source:"iana",compressible:!0},"application/vnd.dna":{source:"iana",extensions:["dna"]},"application/vnd.document+json":{source:"iana",compressible:!0},"application/vnd.dolby.mlp":{source:"apache",extensions:["mlp"]},"application/vnd.dolby.mobile.1":{source:"iana"},"application/vnd.dolby.mobile.2":{source:"iana"},"application/vnd.doremir.scorecloud-binary-document":{source:"iana"},"application/vnd.dpgraph":{source:"iana",extensions:["dpg"]},"application/vnd.dreamfactory":{source:"iana",extensions:["dfac"]},"application/vnd.drive+json":{source:"iana",compressible:!0},"application/vnd.ds-keypoint":{source:"apache",extensions:["kpxx"]},"application/vnd.dtg.local":{source:"iana"},"application/vnd.dtg.local.flash":{source:"iana"},"application/vnd.dtg.local.html":{source:"iana"},"application/vnd.dvb.ait":{source:"iana",extensions:["ait"]},"application/vnd.dvb.dvbisl+xml":{source:"iana",compressible:!0},"application/vnd.dvb.dvbj":{source:"iana"},"application/vnd.dvb.esgcontainer":{source:"iana"},"application/vnd.dvb.ipdcdftnotifaccess":{source:"iana"},"application/vnd.dvb.ipdcesgaccess":{source:"iana"},"application/vnd.dvb.ipdcesgaccess2":{source:"iana"},"application/vnd.dvb.ipdcesgpdd":{source:"iana"},"application/vnd.dvb.ipdcroaming":{source:"iana"},"application/vnd.dvb.iptv.alfec-base":{source:"iana"},"application/vnd.dvb.iptv.alfec-enhancement":{source:"iana"},"application/vnd.dvb.notif-aggregate-root+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-container+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-generic+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-msglist+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-registration-request+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-registration-response+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-init+xml":{source:"iana",compressible:!0},"application/vnd.dvb.pfr":{source:"iana"},"application/vnd.dvb.service":{source:"iana",extensions:["svc"]},"application/vnd.dxr":{source:"iana"},"application/vnd.dynageo":{source:"iana",extensions:["geo"]},"application/vnd.dzr":{source:"iana"},"application/vnd.easykaraoke.cdgdownload":{source:"iana"},"application/vnd.ecdis-update":{source:"iana"},"application/vnd.ecip.rlp":{source:"iana"},"application/vnd.eclipse.ditto+json":{source:"iana",compressible:!0},"application/vnd.ecowin.chart":{source:"iana",extensions:["mag"]},"application/vnd.ecowin.filerequest":{source:"iana"},"application/vnd.ecowin.fileupdate":{source:"iana"},"application/vnd.ecowin.series":{source:"iana"},"application/vnd.ecowin.seriesrequest":{source:"iana"},"application/vnd.ecowin.seriesupdate":{source:"iana"},"application/vnd.efi.img":{source:"iana"},"application/vnd.efi.iso":{source:"iana"},"application/vnd.eln+zip":{source:"iana",compressible:!1},"application/vnd.emclient.accessrequest+xml":{source:"iana",compressible:!0},"application/vnd.enliven":{source:"iana",extensions:["nml"]},"application/vnd.enphase.envoy":{source:"iana"},"application/vnd.eprints.data+xml":{source:"iana",compressible:!0},"application/vnd.epson.esf":{source:"iana",extensions:["esf"]},"application/vnd.epson.msf":{source:"iana",extensions:["msf"]},"application/vnd.epson.quickanime":{source:"iana",extensions:["qam"]},"application/vnd.epson.salt":{source:"iana",extensions:["slt"]},"application/vnd.epson.ssf":{source:"iana",extensions:["ssf"]},"application/vnd.ericsson.quickcall":{source:"iana"},"application/vnd.erofs":{source:"iana"},"application/vnd.espass-espass+zip":{source:"iana",compressible:!1},"application/vnd.eszigno3+xml":{source:"iana",compressible:!0,extensions:["es3","et3"]},"application/vnd.etsi.aoc+xml":{source:"iana",compressible:!0},"application/vnd.etsi.asic-e+zip":{source:"iana",compressible:!1},"application/vnd.etsi.asic-s+zip":{source:"iana",compressible:!1},"application/vnd.etsi.cug+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvcommand+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvdiscovery+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvprofile+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-bc+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-cod+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-npvr+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvservice+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsync+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvueprofile+xml":{source:"iana",compressible:!0},"application/vnd.etsi.mcid+xml":{source:"iana",compressible:!0},"application/vnd.etsi.mheg5":{source:"iana"},"application/vnd.etsi.overload-control-policy-dataset+xml":{source:"iana",compressible:!0},"application/vnd.etsi.pstn+xml":{source:"iana",compressible:!0},"application/vnd.etsi.sci+xml":{source:"iana",compressible:!0},"application/vnd.etsi.simservs+xml":{source:"iana",compressible:!0},"application/vnd.etsi.timestamp-token":{source:"iana"},"application/vnd.etsi.tsl+xml":{source:"iana",compressible:!0},"application/vnd.etsi.tsl.der":{source:"iana"},"application/vnd.eu.kasparian.car+json":{source:"iana",compressible:!0},"application/vnd.eudora.data":{source:"iana"},"application/vnd.evolv.ecig.profile":{source:"iana"},"application/vnd.evolv.ecig.settings":{source:"iana"},"application/vnd.evolv.ecig.theme":{source:"iana"},"application/vnd.exstream-empower+zip":{source:"iana",compressible:!1},"application/vnd.exstream-package":{source:"iana"},"application/vnd.ezpix-album":{source:"iana",extensions:["ez2"]},"application/vnd.ezpix-package":{source:"iana",extensions:["ez3"]},"application/vnd.f-secure.mobile":{source:"iana"},"application/vnd.familysearch.gedcom+zip":{source:"iana",compressible:!1},"application/vnd.fastcopy-disk-image":{source:"iana"},"application/vnd.fdf":{source:"apache",extensions:["fdf"]},"application/vnd.fdsn.mseed":{source:"iana",extensions:["mseed"]},"application/vnd.fdsn.seed":{source:"iana",extensions:["seed","dataless"]},"application/vnd.fdsn.stationxml+xml":{source:"iana",charset:"XML-BASED",compressible:!0},"application/vnd.ffsns":{source:"iana"},"application/vnd.ficlab.flb+zip":{source:"iana",compressible:!1},"application/vnd.filmit.zfc":{source:"iana"},"application/vnd.fints":{source:"iana"},"application/vnd.firemonkeys.cloudcell":{source:"iana"},"application/vnd.flographit":{source:"iana",extensions:["gph"]},"application/vnd.fluxtime.clip":{source:"iana",extensions:["ftc"]},"application/vnd.font-fontforge-sfd":{source:"iana"},"application/vnd.framemaker":{source:"iana",extensions:["fm","frame","maker","book"]},"application/vnd.freelog.comic":{source:"iana"},"application/vnd.frogans.fnc":{source:"apache",extensions:["fnc"]},"application/vnd.frogans.ltf":{source:"apache",extensions:["ltf"]},"application/vnd.fsc.weblaunch":{source:"iana",extensions:["fsc"]},"application/vnd.fujifilm.fb.docuworks":{source:"iana"},"application/vnd.fujifilm.fb.docuworks.binder":{source:"iana"},"application/vnd.fujifilm.fb.docuworks.container":{source:"iana"},"application/vnd.fujifilm.fb.jfi+xml":{source:"iana",compressible:!0},"application/vnd.fujitsu.oasys":{source:"iana",extensions:["oas"]},"application/vnd.fujitsu.oasys2":{source:"iana",extensions:["oa2"]},"application/vnd.fujitsu.oasys3":{source:"iana",extensions:["oa3"]},"application/vnd.fujitsu.oasysgp":{source:"iana",extensions:["fg5"]},"application/vnd.fujitsu.oasysprs":{source:"iana",extensions:["bh2"]},"application/vnd.fujixerox.art-ex":{source:"iana"},"application/vnd.fujixerox.art4":{source:"iana"},"application/vnd.fujixerox.ddd":{source:"iana",extensions:["ddd"]},"application/vnd.fujixerox.docuworks":{source:"iana",extensions:["xdw"]},"application/vnd.fujixerox.docuworks.binder":{source:"iana",extensions:["xbd"]},"application/vnd.fujixerox.docuworks.container":{source:"iana"},"application/vnd.fujixerox.hbpl":{source:"iana"},"application/vnd.fut-misnet":{source:"iana"},"application/vnd.futoin+cbor":{source:"iana"},"application/vnd.futoin+json":{source:"iana",compressible:!0},"application/vnd.fuzzysheet":{source:"iana",extensions:["fzs"]},"application/vnd.ga4gh.passport+jwt":{source:"iana"},"application/vnd.genomatix.tuxedo":{source:"iana",extensions:["txd"]},"application/vnd.genozip":{source:"iana"},"application/vnd.gentics.grd+json":{source:"iana",compressible:!0},"application/vnd.gentoo.catmetadata+xml":{source:"iana",compressible:!0},"application/vnd.gentoo.ebuild":{source:"iana"},"application/vnd.gentoo.eclass":{source:"iana"},"application/vnd.gentoo.gpkg":{source:"iana"},"application/vnd.gentoo.manifest":{source:"iana"},"application/vnd.gentoo.pkgmetadata+xml":{source:"iana",compressible:!0},"application/vnd.gentoo.xpak":{source:"iana"},"application/vnd.geo+json":{source:"apache",compressible:!0},"application/vnd.geocube+xml":{source:"apache",compressible:!0},"application/vnd.geogebra.file":{source:"iana",extensions:["ggb"]},"application/vnd.geogebra.pinboard":{source:"iana"},"application/vnd.geogebra.slides":{source:"iana",extensions:["ggs"]},"application/vnd.geogebra.tool":{source:"iana",extensions:["ggt"]},"application/vnd.geometry-explorer":{source:"iana",extensions:["gex","gre"]},"application/vnd.geonext":{source:"iana",extensions:["gxt"]},"application/vnd.geoplan":{source:"iana",extensions:["g2w"]},"application/vnd.geospace":{source:"iana",extensions:["g3w"]},"application/vnd.gerber":{source:"iana"},"application/vnd.globalplatform.card-content-mgt":{source:"iana"},"application/vnd.globalplatform.card-content-mgt-response":{source:"iana"},"application/vnd.gmx":{source:"iana",extensions:["gmx"]},"application/vnd.gnu.taler.exchange+json":{source:"iana",compressible:!0},"application/vnd.gnu.taler.merchant+json":{source:"iana",compressible:!0},"application/vnd.google-apps.audio":{},"application/vnd.google-apps.document":{compressible:!1,extensions:["gdoc"]},"application/vnd.google-apps.drawing":{compressible:!1,extensions:["gdraw"]},"application/vnd.google-apps.drive-sdk":{compressible:!1},"application/vnd.google-apps.file":{},"application/vnd.google-apps.folder":{compressible:!1},"application/vnd.google-apps.form":{compressible:!1,extensions:["gform"]},"application/vnd.google-apps.fusiontable":{},"application/vnd.google-apps.jam":{compressible:!1,extensions:["gjam"]},"application/vnd.google-apps.mail-layout":{},"application/vnd.google-apps.map":{compressible:!1,extensions:["gmap"]},"application/vnd.google-apps.photo":{},"application/vnd.google-apps.presentation":{compressible:!1,extensions:["gslides"]},"application/vnd.google-apps.script":{compressible:!1,extensions:["gscript"]},"application/vnd.google-apps.shortcut":{},"application/vnd.google-apps.site":{compressible:!1,extensions:["gsite"]},"application/vnd.google-apps.spreadsheet":{compressible:!1,extensions:["gsheet"]},"application/vnd.google-apps.unknown":{},"application/vnd.google-apps.video":{},"application/vnd.google-earth.kml+xml":{source:"iana",compressible:!0,extensions:["kml"]},"application/vnd.google-earth.kmz":{source:"iana",compressible:!1,extensions:["kmz"]},"application/vnd.gov.sk.e-form+xml":{source:"apache",compressible:!0},"application/vnd.gov.sk.e-form+zip":{source:"iana",compressible:!1},"application/vnd.gov.sk.xmldatacontainer+xml":{source:"iana",compressible:!0,extensions:["xdcf"]},"application/vnd.gpxsee.map+xml":{source:"iana",compressible:!0},"application/vnd.grafeq":{source:"iana",extensions:["gqf","gqs"]},"application/vnd.gridmp":{source:"iana"},"application/vnd.groove-account":{source:"iana",extensions:["gac"]},"application/vnd.groove-help":{source:"iana",extensions:["ghf"]},"application/vnd.groove-identity-message":{source:"iana",extensions:["gim"]},"application/vnd.groove-injector":{source:"iana",extensions:["grv"]},"application/vnd.groove-tool-message":{source:"iana",extensions:["gtm"]},"application/vnd.groove-tool-template":{source:"iana",extensions:["tpl"]},"application/vnd.groove-vcard":{source:"iana",extensions:["vcg"]},"application/vnd.hal+json":{source:"iana",compressible:!0},"application/vnd.hal+xml":{source:"iana",compressible:!0,extensions:["hal"]},"application/vnd.handheld-entertainment+xml":{source:"iana",compressible:!0,extensions:["zmm"]},"application/vnd.hbci":{source:"iana",extensions:["hbci"]},"application/vnd.hc+json":{source:"iana",compressible:!0},"application/vnd.hcl-bireports":{source:"iana"},"application/vnd.hdt":{source:"iana"},"application/vnd.heroku+json":{source:"iana",compressible:!0},"application/vnd.hhe.lesson-player":{source:"iana",extensions:["les"]},"application/vnd.hp-hpgl":{source:"iana",extensions:["hpgl"]},"application/vnd.hp-hpid":{source:"iana",extensions:["hpid"]},"application/vnd.hp-hps":{source:"iana",extensions:["hps"]},"application/vnd.hp-jlyt":{source:"iana",extensions:["jlt"]},"application/vnd.hp-pcl":{source:"iana",extensions:["pcl"]},"application/vnd.hp-pclxl":{source:"iana",extensions:["pclxl"]},"application/vnd.hsl":{source:"iana"},"application/vnd.httphone":{source:"iana"},"application/vnd.hydrostatix.sof-data":{source:"iana",extensions:["sfd-hdstx"]},"application/vnd.hyper+json":{source:"iana",compressible:!0},"application/vnd.hyper-item+json":{source:"iana",compressible:!0},"application/vnd.hyperdrive+json":{source:"iana",compressible:!0},"application/vnd.hzn-3d-crossword":{source:"iana"},"application/vnd.ibm.afplinedata":{source:"apache"},"application/vnd.ibm.electronic-media":{source:"iana"},"application/vnd.ibm.minipay":{source:"iana",extensions:["mpy"]},"application/vnd.ibm.modcap":{source:"apache",extensions:["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{source:"iana",extensions:["irm"]},"application/vnd.ibm.secure-container":{source:"iana",extensions:["sc"]},"application/vnd.iccprofile":{source:"iana",extensions:["icc","icm"]},"application/vnd.ieee.1905":{source:"iana"},"application/vnd.igloader":{source:"iana",extensions:["igl"]},"application/vnd.imagemeter.folder+zip":{source:"iana",compressible:!1},"application/vnd.imagemeter.image+zip":{source:"iana",compressible:!1},"application/vnd.immervision-ivp":{source:"iana",extensions:["ivp"]},"application/vnd.immervision-ivu":{source:"iana",extensions:["ivu"]},"application/vnd.ims.imsccv1p1":{source:"iana"},"application/vnd.ims.imsccv1p2":{source:"iana"},"application/vnd.ims.imsccv1p3":{source:"iana"},"application/vnd.ims.lis.v2.result+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolconsumerprofile+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolproxy+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolproxy.id+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolsettings+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolsettings.simple+json":{source:"iana",compressible:!0},"application/vnd.informedcontrol.rms+xml":{source:"iana",compressible:!0},"application/vnd.informix-visionary":{source:"apache"},"application/vnd.infotech.project":{source:"iana"},"application/vnd.infotech.project+xml":{source:"iana",compressible:!0},"application/vnd.innopath.wamp.notification":{source:"iana"},"application/vnd.insors.igm":{source:"iana",extensions:["igm"]},"application/vnd.intercon.formnet":{source:"iana",extensions:["xpw","xpx"]},"application/vnd.intergeo":{source:"iana",extensions:["i2g"]},"application/vnd.intertrust.digibox":{source:"iana"},"application/vnd.intertrust.nncp":{source:"iana"},"application/vnd.intu.qbo":{source:"iana",extensions:["qbo"]},"application/vnd.intu.qfx":{source:"iana",extensions:["qfx"]},"application/vnd.ipfs.ipns-record":{source:"iana"},"application/vnd.ipld.car":{source:"iana"},"application/vnd.ipld.dag-cbor":{source:"iana"},"application/vnd.ipld.dag-json":{source:"iana"},"application/vnd.ipld.raw":{source:"iana"},"application/vnd.iptc.g2.catalogitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.conceptitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.knowledgeitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.newsitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.newsmessage+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.packageitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.planningitem+xml":{source:"iana",compressible:!0},"application/vnd.ipunplugged.rcprofile":{source:"iana",extensions:["rcprofile"]},"application/vnd.irepository.package+xml":{source:"iana",compressible:!0,extensions:["irp"]},"application/vnd.is-xpr":{source:"iana",extensions:["xpr"]},"application/vnd.isac.fcs":{source:"iana",extensions:["fcs"]},"application/vnd.iso11783-10+zip":{source:"iana",compressible:!1},"application/vnd.jam":{source:"iana",extensions:["jam"]},"application/vnd.japannet-directory-service":{source:"iana"},"application/vnd.japannet-jpnstore-wakeup":{source:"iana"},"application/vnd.japannet-payment-wakeup":{source:"iana"},"application/vnd.japannet-registration":{source:"iana"},"application/vnd.japannet-registration-wakeup":{source:"iana"},"application/vnd.japannet-setstore-wakeup":{source:"iana"},"application/vnd.japannet-verification":{source:"iana"},"application/vnd.japannet-verification-wakeup":{source:"iana"},"application/vnd.jcp.javame.midlet-rms":{source:"iana",extensions:["rms"]},"application/vnd.jisp":{source:"iana",extensions:["jisp"]},"application/vnd.joost.joda-archive":{source:"iana",extensions:["joda"]},"application/vnd.jsk.isdn-ngn":{source:"iana"},"application/vnd.kahootz":{source:"iana",extensions:["ktz","ktr"]},"application/vnd.kde.karbon":{source:"iana",extensions:["karbon"]},"application/vnd.kde.kchart":{source:"iana",extensions:["chrt"]},"application/vnd.kde.kformula":{source:"iana",extensions:["kfo"]},"application/vnd.kde.kivio":{source:"iana",extensions:["flw"]},"application/vnd.kde.kontour":{source:"iana",extensions:["kon"]},"application/vnd.kde.kpresenter":{source:"iana",extensions:["kpr","kpt"]},"application/vnd.kde.kspread":{source:"iana",extensions:["ksp"]},"application/vnd.kde.kword":{source:"iana",extensions:["kwd","kwt"]},"application/vnd.kdl":{source:"iana"},"application/vnd.kenameaapp":{source:"iana",extensions:["htke"]},"application/vnd.keyman.kmp+zip":{source:"iana",compressible:!1},"application/vnd.keyman.kmx":{source:"iana"},"application/vnd.kidspiration":{source:"iana",extensions:["kia"]},"application/vnd.kinar":{source:"iana",extensions:["kne","knp"]},"application/vnd.koan":{source:"iana",extensions:["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{source:"iana",extensions:["sse"]},"application/vnd.las":{source:"iana"},"application/vnd.las.las+json":{source:"iana",compressible:!0},"application/vnd.las.las+xml":{source:"iana",compressible:!0,extensions:["lasxml"]},"application/vnd.laszip":{source:"iana"},"application/vnd.ldev.productlicensing":{source:"iana"},"application/vnd.leap+json":{source:"iana",compressible:!0},"application/vnd.liberty-request+xml":{source:"iana",compressible:!0},"application/vnd.llamagraphics.life-balance.desktop":{source:"iana",extensions:["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{source:"iana",compressible:!0,extensions:["lbe"]},"application/vnd.logipipe.circuit+zip":{source:"iana",compressible:!1},"application/vnd.loom":{source:"iana"},"application/vnd.lotus-1-2-3":{source:"iana",extensions:["123"]},"application/vnd.lotus-approach":{source:"iana",extensions:["apr"]},"application/vnd.lotus-freelance":{source:"iana",extensions:["pre"]},"application/vnd.lotus-notes":{source:"iana",extensions:["nsf"]},"application/vnd.lotus-organizer":{source:"iana",extensions:["org"]},"application/vnd.lotus-screencam":{source:"iana",extensions:["scm"]},"application/vnd.lotus-wordpro":{source:"iana",extensions:["lwp"]},"application/vnd.macports.portpkg":{source:"iana",extensions:["portpkg"]},"application/vnd.mapbox-vector-tile":{source:"iana",extensions:["mvt"]},"application/vnd.marlin.drm.actiontoken+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.conftoken+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.license+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.mdcf":{source:"iana"},"application/vnd.mason+json":{source:"iana",compressible:!0},"application/vnd.maxar.archive.3tz+zip":{source:"iana",compressible:!1},"application/vnd.maxmind.maxmind-db":{source:"iana"},"application/vnd.mcd":{source:"iana",extensions:["mcd"]},"application/vnd.mdl":{source:"iana"},"application/vnd.mdl-mbsdf":{source:"iana"},"application/vnd.medcalcdata":{source:"iana",extensions:["mc1"]},"application/vnd.mediastation.cdkey":{source:"iana",extensions:["cdkey"]},"application/vnd.medicalholodeck.recordxr":{source:"iana"},"application/vnd.meridian-slingshot":{source:"iana"},"application/vnd.mermaid":{source:"iana"},"application/vnd.mfer":{source:"iana",extensions:["mwf"]},"application/vnd.mfmp":{source:"iana",extensions:["mfm"]},"application/vnd.micro+json":{source:"iana",compressible:!0},"application/vnd.micrografx.flo":{source:"iana",extensions:["flo"]},"application/vnd.micrografx.igx":{source:"iana",extensions:["igx"]},"application/vnd.microsoft.portable-executable":{source:"iana"},"application/vnd.microsoft.windows.thumbnail-cache":{source:"iana"},"application/vnd.miele+json":{source:"iana",compressible:!0},"application/vnd.mif":{source:"iana",extensions:["mif"]},"application/vnd.minisoft-hp3000-save":{source:"iana"},"application/vnd.mitsubishi.misty-guard.trustweb":{source:"iana"},"application/vnd.mobius.daf":{source:"iana",extensions:["daf"]},"application/vnd.mobius.dis":{source:"iana",extensions:["dis"]},"application/vnd.mobius.mbk":{source:"iana",extensions:["mbk"]},"application/vnd.mobius.mqy":{source:"iana",extensions:["mqy"]},"application/vnd.mobius.msl":{source:"iana",extensions:["msl"]},"application/vnd.mobius.plc":{source:"iana",extensions:["plc"]},"application/vnd.mobius.txf":{source:"iana",extensions:["txf"]},"application/vnd.modl":{source:"iana"},"application/vnd.mophun.application":{source:"iana",extensions:["mpn"]},"application/vnd.mophun.certificate":{source:"iana",extensions:["mpc"]},"application/vnd.motorola.flexsuite":{source:"iana"},"application/vnd.motorola.flexsuite.adsi":{source:"iana"},"application/vnd.motorola.flexsuite.fis":{source:"iana"},"application/vnd.motorola.flexsuite.gotap":{source:"iana"},"application/vnd.motorola.flexsuite.kmr":{source:"iana"},"application/vnd.motorola.flexsuite.ttc":{source:"iana"},"application/vnd.motorola.flexsuite.wem":{source:"iana"},"application/vnd.motorola.iprm":{source:"iana"},"application/vnd.mozilla.xul+xml":{source:"iana",compressible:!0,extensions:["xul"]},"application/vnd.ms-3mfdocument":{source:"iana"},"application/vnd.ms-artgalry":{source:"iana",extensions:["cil"]},"application/vnd.ms-asf":{source:"iana"},"application/vnd.ms-cab-compressed":{source:"iana",extensions:["cab"]},"application/vnd.ms-color.iccprofile":{source:"apache"},"application/vnd.ms-excel":{source:"iana",compressible:!1,extensions:["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{source:"iana",extensions:["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{source:"iana",extensions:["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{source:"iana",extensions:["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{source:"iana",extensions:["xltm"]},"application/vnd.ms-fontobject":{source:"iana",compressible:!0,extensions:["eot"]},"application/vnd.ms-htmlhelp":{source:"iana",extensions:["chm"]},"application/vnd.ms-ims":{source:"iana",extensions:["ims"]},"application/vnd.ms-lrm":{source:"iana",extensions:["lrm"]},"application/vnd.ms-office.activex+xml":{source:"iana",compressible:!0},"application/vnd.ms-officetheme":{source:"iana",extensions:["thmx"]},"application/vnd.ms-opentype":{source:"apache",compressible:!0},"application/vnd.ms-outlook":{compressible:!1,extensions:["msg"]},"application/vnd.ms-package.obfuscated-opentype":{source:"apache"},"application/vnd.ms-pki.seccat":{source:"apache",extensions:["cat"]},"application/vnd.ms-pki.stl":{source:"apache",extensions:["stl"]},"application/vnd.ms-playready.initiator+xml":{source:"iana",compressible:!0},"application/vnd.ms-powerpoint":{source:"iana",compressible:!1,extensions:["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{source:"iana",extensions:["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{source:"iana",extensions:["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{source:"iana",extensions:["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{source:"iana",extensions:["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{source:"iana",extensions:["potm"]},"application/vnd.ms-printdevicecapabilities+xml":{source:"iana",compressible:!0},"application/vnd.ms-printing.printticket+xml":{source:"apache",compressible:!0},"application/vnd.ms-printschematicket+xml":{source:"iana",compressible:!0},"application/vnd.ms-project":{source:"iana",extensions:["mpp","mpt"]},"application/vnd.ms-tnef":{source:"iana"},"application/vnd.ms-visio.viewer":{extensions:["vdx"]},"application/vnd.ms-windows.devicepairing":{source:"iana"},"application/vnd.ms-windows.nwprinting.oob":{source:"iana"},"application/vnd.ms-windows.printerpairing":{source:"iana"},"application/vnd.ms-windows.wsd.oob":{source:"iana"},"application/vnd.ms-wmdrm.lic-chlg-req":{source:"iana"},"application/vnd.ms-wmdrm.lic-resp":{source:"iana"},"application/vnd.ms-wmdrm.meter-chlg-req":{source:"iana"},"application/vnd.ms-wmdrm.meter-resp":{source:"iana"},"application/vnd.ms-word.document.macroenabled.12":{source:"iana",extensions:["docm"]},"application/vnd.ms-word.template.macroenabled.12":{source:"iana",extensions:["dotm"]},"application/vnd.ms-works":{source:"iana",extensions:["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{source:"iana",extensions:["wpl"]},"application/vnd.ms-xpsdocument":{source:"iana",compressible:!1,extensions:["xps"]},"application/vnd.msa-disk-image":{source:"iana"},"application/vnd.mseq":{source:"iana",extensions:["mseq"]},"application/vnd.msgpack":{source:"iana"},"application/vnd.msign":{source:"iana"},"application/vnd.multiad.creator":{source:"iana"},"application/vnd.multiad.creator.cif":{source:"iana"},"application/vnd.music-niff":{source:"iana"},"application/vnd.musician":{source:"iana",extensions:["mus"]},"application/vnd.muvee.style":{source:"iana",extensions:["msty"]},"application/vnd.mynfc":{source:"iana",extensions:["taglet"]},"application/vnd.nacamar.ybrid+json":{source:"iana",compressible:!0},"application/vnd.nato.bindingdataobject+cbor":{source:"iana"},"application/vnd.nato.bindingdataobject+json":{source:"iana",compressible:!0},"application/vnd.nato.bindingdataobject+xml":{source:"iana",compressible:!0,extensions:["bdo"]},"application/vnd.nato.openxmlformats-package.iepd+zip":{source:"iana",compressible:!1},"application/vnd.ncd.control":{source:"iana"},"application/vnd.ncd.reference":{source:"iana"},"application/vnd.nearst.inv+json":{source:"iana",compressible:!0},"application/vnd.nebumind.line":{source:"iana"},"application/vnd.nervana":{source:"iana"},"application/vnd.netfpx":{source:"iana"},"application/vnd.neurolanguage.nlu":{source:"iana",extensions:["nlu"]},"application/vnd.nimn":{source:"iana"},"application/vnd.nintendo.nitro.rom":{source:"iana"},"application/vnd.nintendo.snes.rom":{source:"iana"},"application/vnd.nitf":{source:"iana",extensions:["ntf","nitf"]},"application/vnd.noblenet-directory":{source:"iana",extensions:["nnd"]},"application/vnd.noblenet-sealer":{source:"iana",extensions:["nns"]},"application/vnd.noblenet-web":{source:"iana",extensions:["nnw"]},"application/vnd.nokia.catalogs":{source:"iana"},"application/vnd.nokia.conml+wbxml":{source:"iana"},"application/vnd.nokia.conml+xml":{source:"iana",compressible:!0},"application/vnd.nokia.iptv.config+xml":{source:"iana",compressible:!0},"application/vnd.nokia.isds-radio-presets":{source:"iana"},"application/vnd.nokia.landmark+wbxml":{source:"iana"},"application/vnd.nokia.landmark+xml":{source:"iana",compressible:!0},"application/vnd.nokia.landmarkcollection+xml":{source:"iana",compressible:!0},"application/vnd.nokia.n-gage.ac+xml":{source:"iana",compressible:!0,extensions:["ac"]},"application/vnd.nokia.n-gage.data":{source:"iana",extensions:["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{source:"apache",extensions:["n-gage"]},"application/vnd.nokia.ncd":{source:"iana"},"application/vnd.nokia.pcd+wbxml":{source:"iana"},"application/vnd.nokia.pcd+xml":{source:"iana",compressible:!0},"application/vnd.nokia.radio-preset":{source:"iana",extensions:["rpst"]},"application/vnd.nokia.radio-presets":{source:"iana",extensions:["rpss"]},"application/vnd.novadigm.edm":{source:"iana",extensions:["edm"]},"application/vnd.novadigm.edx":{source:"iana",extensions:["edx"]},"application/vnd.novadigm.ext":{source:"iana",extensions:["ext"]},"application/vnd.ntt-local.content-share":{source:"iana"},"application/vnd.ntt-local.file-transfer":{source:"iana"},"application/vnd.ntt-local.ogw_remote-access":{source:"iana"},"application/vnd.ntt-local.sip-ta_remote":{source:"iana"},"application/vnd.ntt-local.sip-ta_tcp_stream":{source:"iana"},"application/vnd.oai.workflows":{source:"iana"},"application/vnd.oai.workflows+json":{source:"iana",compressible:!0},"application/vnd.oai.workflows+yaml":{source:"iana"},"application/vnd.oasis.opendocument.base":{source:"iana"},"application/vnd.oasis.opendocument.chart":{source:"iana",extensions:["odc"]},"application/vnd.oasis.opendocument.chart-template":{source:"iana",extensions:["otc"]},"application/vnd.oasis.opendocument.database":{source:"apache",extensions:["odb"]},"application/vnd.oasis.opendocument.formula":{source:"iana",extensions:["odf"]},"application/vnd.oasis.opendocument.formula-template":{source:"iana",extensions:["odft"]},"application/vnd.oasis.opendocument.graphics":{source:"iana",compressible:!1,extensions:["odg"]},"application/vnd.oasis.opendocument.graphics-template":{source:"iana",extensions:["otg"]},"application/vnd.oasis.opendocument.image":{source:"iana",extensions:["odi"]},"application/vnd.oasis.opendocument.image-template":{source:"iana",extensions:["oti"]},"application/vnd.oasis.opendocument.presentation":{source:"iana",compressible:!1,extensions:["odp"]},"application/vnd.oasis.opendocument.presentation-template":{source:"iana",extensions:["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{source:"iana",compressible:!1,extensions:["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{source:"iana",extensions:["ots"]},"application/vnd.oasis.opendocument.text":{source:"iana",compressible:!1,extensions:["odt"]},"application/vnd.oasis.opendocument.text-master":{source:"iana",extensions:["odm"]},"application/vnd.oasis.opendocument.text-master-template":{source:"iana"},"application/vnd.oasis.opendocument.text-template":{source:"iana",extensions:["ott"]},"application/vnd.oasis.opendocument.text-web":{source:"iana",extensions:["oth"]},"application/vnd.obn":{source:"iana"},"application/vnd.ocf+cbor":{source:"iana"},"application/vnd.oci.image.manifest.v1+json":{source:"iana",compressible:!0},"application/vnd.oftn.l10n+json":{source:"iana",compressible:!0},"application/vnd.oipf.contentaccessdownload+xml":{source:"iana",compressible:!0},"application/vnd.oipf.contentaccessstreaming+xml":{source:"iana",compressible:!0},"application/vnd.oipf.cspg-hexbinary":{source:"iana"},"application/vnd.oipf.dae.svg+xml":{source:"iana",compressible:!0},"application/vnd.oipf.dae.xhtml+xml":{source:"iana",compressible:!0},"application/vnd.oipf.mippvcontrolmessage+xml":{source:"iana",compressible:!0},"application/vnd.oipf.pae.gem":{source:"iana"},"application/vnd.oipf.spdiscovery+xml":{source:"iana",compressible:!0},"application/vnd.oipf.spdlist+xml":{source:"iana",compressible:!0},"application/vnd.oipf.ueprofile+xml":{source:"iana",compressible:!0},"application/vnd.oipf.userprofile+xml":{source:"iana",compressible:!0},"application/vnd.olpc-sugar":{source:"iana",extensions:["xo"]},"application/vnd.oma-scws-config":{source:"iana"},"application/vnd.oma-scws-http-request":{source:"iana"},"application/vnd.oma-scws-http-response":{source:"iana"},"application/vnd.oma.bcast.associated-procedure-parameter+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.drm-trigger+xml":{source:"apache",compressible:!0},"application/vnd.oma.bcast.imd+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.ltkm":{source:"iana"},"application/vnd.oma.bcast.notification+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.provisioningtrigger":{source:"iana"},"application/vnd.oma.bcast.sgboot":{source:"iana"},"application/vnd.oma.bcast.sgdd+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.sgdu":{source:"iana"},"application/vnd.oma.bcast.simple-symbol-container":{source:"iana"},"application/vnd.oma.bcast.smartcard-trigger+xml":{source:"apache",compressible:!0},"application/vnd.oma.bcast.sprov+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.stkm":{source:"iana"},"application/vnd.oma.cab-address-book+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-feature-handler+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-pcc+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-subs-invite+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-user-prefs+xml":{source:"iana",compressible:!0},"application/vnd.oma.dcd":{source:"iana"},"application/vnd.oma.dcdc":{source:"iana"},"application/vnd.oma.dd2+xml":{source:"iana",compressible:!0,extensions:["dd2"]},"application/vnd.oma.drm.risd+xml":{source:"iana",compressible:!0},"application/vnd.oma.group-usage-list+xml":{source:"iana",compressible:!0},"application/vnd.oma.lwm2m+cbor":{source:"iana"},"application/vnd.oma.lwm2m+json":{source:"iana",compressible:!0},"application/vnd.oma.lwm2m+tlv":{source:"iana"},"application/vnd.oma.pal+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.detailed-progress-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.final-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.groups+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.invocation-descriptor+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.optimized-progress-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.push":{source:"iana"},"application/vnd.oma.scidm.messages+xml":{source:"iana",compressible:!0},"application/vnd.oma.xcap-directory+xml":{source:"iana",compressible:!0},"application/vnd.omads-email+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omads-file+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omads-folder+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omaloc-supl-init":{source:"iana"},"application/vnd.onepager":{source:"iana"},"application/vnd.onepagertamp":{source:"iana"},"application/vnd.onepagertamx":{source:"iana"},"application/vnd.onepagertat":{source:"iana"},"application/vnd.onepagertatp":{source:"iana"},"application/vnd.onepagertatx":{source:"iana"},"application/vnd.onvif.metadata":{source:"iana"},"application/vnd.openblox.game+xml":{source:"iana",compressible:!0,extensions:["obgx"]},"application/vnd.openblox.game-binary":{source:"iana"},"application/vnd.openeye.oeb":{source:"iana"},"application/vnd.openofficeorg.extension":{source:"apache",extensions:["oxt"]},"application/vnd.openstreetmap.data+xml":{source:"iana",compressible:!0,extensions:["osm"]},"application/vnd.opentimestamps.ots":{source:"iana"},"application/vnd.openvpi.dspx+json":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.custom-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.customxmlproperties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawing+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.chart+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.extended-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{source:"iana",compressible:!1,extensions:["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slide":{source:"iana",extensions:["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{source:"iana",extensions:["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.tags+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.template":{source:"iana",extensions:["potx"]},"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{source:"iana",compressible:!1,extensions:["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{source:"iana",extensions:["xltx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.theme+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.themeoverride+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.vmldrawing":{source:"iana"},"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{source:"iana",compressible:!1,extensions:["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{source:"iana",extensions:["dotx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.core-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.relationships+xml":{source:"iana",compressible:!0},"application/vnd.oracle.resource+json":{source:"iana",compressible:!0},"application/vnd.orange.indata":{source:"iana"},"application/vnd.osa.netdeploy":{source:"iana"},"application/vnd.osgeo.mapguide.package":{source:"iana",extensions:["mgp"]},"application/vnd.osgi.bundle":{source:"iana"},"application/vnd.osgi.dp":{source:"iana",extensions:["dp"]},"application/vnd.osgi.subsystem":{source:"iana",extensions:["esa"]},"application/vnd.otps.ct-kip+xml":{source:"iana",compressible:!0},"application/vnd.oxli.countgraph":{source:"iana"},"application/vnd.pagerduty+json":{source:"iana",compressible:!0},"application/vnd.palm":{source:"iana",extensions:["pdb","pqa","oprc"]},"application/vnd.panoply":{source:"iana"},"application/vnd.paos.xml":{source:"iana"},"application/vnd.patentdive":{source:"iana"},"application/vnd.patientecommsdoc":{source:"iana"},"application/vnd.pawaafile":{source:"iana",extensions:["paw"]},"application/vnd.pcos":{source:"iana"},"application/vnd.pg.format":{source:"iana",extensions:["str"]},"application/vnd.pg.osasli":{source:"iana",extensions:["ei6"]},"application/vnd.piaccess.application-licence":{source:"iana"},"application/vnd.picsel":{source:"iana",extensions:["efif"]},"application/vnd.pmi.widget":{source:"iana",extensions:["wg"]},"application/vnd.poc.group-advertisement+xml":{source:"iana",compressible:!0},"application/vnd.pocketlearn":{source:"iana",extensions:["plf"]},"application/vnd.powerbuilder6":{source:"iana",extensions:["pbd"]},"application/vnd.powerbuilder6-s":{source:"iana"},"application/vnd.powerbuilder7":{source:"iana"},"application/vnd.powerbuilder7-s":{source:"iana"},"application/vnd.powerbuilder75":{source:"iana"},"application/vnd.powerbuilder75-s":{source:"iana"},"application/vnd.preminet":{source:"iana"},"application/vnd.previewsystems.box":{source:"iana",extensions:["box"]},"application/vnd.procrate.brushset":{extensions:["brushset"]},"application/vnd.procreate.brush":{extensions:["brush"]},"application/vnd.procreate.dream":{extensions:["drm"]},"application/vnd.proteus.magazine":{source:"iana",extensions:["mgz"]},"application/vnd.psfs":{source:"iana"},"application/vnd.pt.mundusmundi":{source:"iana"},"application/vnd.publishare-delta-tree":{source:"iana",extensions:["qps"]},"application/vnd.pvi.ptid1":{source:"iana",extensions:["ptid"]},"application/vnd.pwg-multiplexed":{source:"iana"},"application/vnd.pwg-xhtml-print+xml":{source:"iana",compressible:!0,extensions:["xhtm"]},"application/vnd.qualcomm.brew-app-res":{source:"iana"},"application/vnd.quarantainenet":{source:"iana"},"application/vnd.quark.quarkxpress":{source:"iana",extensions:["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.quobject-quoxdocument":{source:"iana"},"application/vnd.radisys.moml+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-conf+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-conn+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-dialog+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-stream+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-conf+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-base+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-fax-detect+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-fax-sendrecv+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-group+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-speech+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-transform+xml":{source:"iana",compressible:!0},"application/vnd.rainstor.data":{source:"iana"},"application/vnd.rapid":{source:"iana"},"application/vnd.rar":{source:"iana",extensions:["rar"]},"application/vnd.realvnc.bed":{source:"iana",extensions:["bed"]},"application/vnd.recordare.musicxml":{source:"iana",extensions:["mxl"]},"application/vnd.recordare.musicxml+xml":{source:"iana",compressible:!0,extensions:["musicxml"]},"application/vnd.relpipe":{source:"iana"},"application/vnd.renlearn.rlprint":{source:"iana"},"application/vnd.resilient.logic":{source:"iana"},"application/vnd.restful+json":{source:"iana",compressible:!0},"application/vnd.rig.cryptonote":{source:"iana",extensions:["cryptonote"]},"application/vnd.rim.cod":{source:"apache",extensions:["cod"]},"application/vnd.rn-realmedia":{source:"apache",extensions:["rm"]},"application/vnd.rn-realmedia-vbr":{source:"apache",extensions:["rmvb"]},"application/vnd.route66.link66+xml":{source:"iana",compressible:!0,extensions:["link66"]},"application/vnd.rs-274x":{source:"iana"},"application/vnd.ruckus.download":{source:"iana"},"application/vnd.s3sms":{source:"iana"},"application/vnd.sailingtracker.track":{source:"iana",extensions:["st"]},"application/vnd.sar":{source:"iana"},"application/vnd.sbm.cid":{source:"iana"},"application/vnd.sbm.mid2":{source:"iana"},"application/vnd.scribus":{source:"iana"},"application/vnd.sealed.3df":{source:"iana"},"application/vnd.sealed.csf":{source:"iana"},"application/vnd.sealed.doc":{source:"iana"},"application/vnd.sealed.eml":{source:"iana"},"application/vnd.sealed.mht":{source:"iana"},"application/vnd.sealed.net":{source:"iana"},"application/vnd.sealed.ppt":{source:"iana"},"application/vnd.sealed.tiff":{source:"iana"},"application/vnd.sealed.xls":{source:"iana"},"application/vnd.sealedmedia.softseal.html":{source:"iana"},"application/vnd.sealedmedia.softseal.pdf":{source:"iana"},"application/vnd.seemail":{source:"iana",extensions:["see"]},"application/vnd.seis+json":{source:"iana",compressible:!0},"application/vnd.sema":{source:"iana",extensions:["sema"]},"application/vnd.semd":{source:"iana",extensions:["semd"]},"application/vnd.semf":{source:"iana",extensions:["semf"]},"application/vnd.shade-save-file":{source:"iana"},"application/vnd.shana.informed.formdata":{source:"iana",extensions:["ifm"]},"application/vnd.shana.informed.formtemplate":{source:"iana",extensions:["itp"]},"application/vnd.shana.informed.interchange":{source:"iana",extensions:["iif"]},"application/vnd.shana.informed.package":{source:"iana",extensions:["ipk"]},"application/vnd.shootproof+json":{source:"iana",compressible:!0},"application/vnd.shopkick+json":{source:"iana",compressible:!0},"application/vnd.shp":{source:"iana"},"application/vnd.shx":{source:"iana"},"application/vnd.sigrok.session":{source:"iana"},"application/vnd.simtech-mindmapper":{source:"iana",extensions:["twd","twds"]},"application/vnd.siren+json":{source:"iana",compressible:!0},"application/vnd.sketchometry":{source:"iana"},"application/vnd.smaf":{source:"iana",extensions:["mmf"]},"application/vnd.smart.notebook":{source:"iana"},"application/vnd.smart.teacher":{source:"iana",extensions:["teacher"]},"application/vnd.smintio.portals.archive":{source:"iana"},"application/vnd.snesdev-page-table":{source:"iana"},"application/vnd.software602.filler.form+xml":{source:"iana",compressible:!0,extensions:["fo"]},"application/vnd.software602.filler.form-xml-zip":{source:"iana"},"application/vnd.solent.sdkm+xml":{source:"iana",compressible:!0,extensions:["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{source:"iana",extensions:["dxp"]},"application/vnd.spotfire.sfs":{source:"iana",extensions:["sfs"]},"application/vnd.sqlite3":{source:"iana"},"application/vnd.sss-cod":{source:"iana"},"application/vnd.sss-dtf":{source:"iana"},"application/vnd.sss-ntf":{source:"iana"},"application/vnd.stardivision.calc":{source:"apache",extensions:["sdc"]},"application/vnd.stardivision.draw":{source:"apache",extensions:["sda"]},"application/vnd.stardivision.impress":{source:"apache",extensions:["sdd"]},"application/vnd.stardivision.math":{source:"apache",extensions:["smf"]},"application/vnd.stardivision.writer":{source:"apache",extensions:["sdw","vor"]},"application/vnd.stardivision.writer-global":{source:"apache",extensions:["sgl"]},"application/vnd.stepmania.package":{source:"iana",extensions:["smzip"]},"application/vnd.stepmania.stepchart":{source:"iana",extensions:["sm"]},"application/vnd.street-stream":{source:"iana"},"application/vnd.sun.wadl+xml":{source:"iana",compressible:!0,extensions:["wadl"]},"application/vnd.sun.xml.calc":{source:"apache",extensions:["sxc"]},"application/vnd.sun.xml.calc.template":{source:"apache",extensions:["stc"]},"application/vnd.sun.xml.draw":{source:"apache",extensions:["sxd"]},"application/vnd.sun.xml.draw.template":{source:"apache",extensions:["std"]},"application/vnd.sun.xml.impress":{source:"apache",extensions:["sxi"]},"application/vnd.sun.xml.impress.template":{source:"apache",extensions:["sti"]},"application/vnd.sun.xml.math":{source:"apache",extensions:["sxm"]},"application/vnd.sun.xml.writer":{source:"apache",extensions:["sxw"]},"application/vnd.sun.xml.writer.global":{source:"apache",extensions:["sxg"]},"application/vnd.sun.xml.writer.template":{source:"apache",extensions:["stw"]},"application/vnd.sus-calendar":{source:"iana",extensions:["sus","susp"]},"application/vnd.svd":{source:"iana",extensions:["svd"]},"application/vnd.swiftview-ics":{source:"iana"},"application/vnd.sybyl.mol2":{source:"iana"},"application/vnd.sycle+xml":{source:"iana",compressible:!0},"application/vnd.syft+json":{source:"iana",compressible:!0},"application/vnd.symbian.install":{source:"apache",extensions:["sis","sisx"]},"application/vnd.syncml+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["xsm"]},"application/vnd.syncml.dm+wbxml":{source:"iana",charset:"UTF-8",extensions:["bdm"]},"application/vnd.syncml.dm+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["xdm"]},"application/vnd.syncml.dm.notification":{source:"iana"},"application/vnd.syncml.dmddf+wbxml":{source:"iana"},"application/vnd.syncml.dmddf+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["ddf"]},"application/vnd.syncml.dmtnds+wbxml":{source:"iana"},"application/vnd.syncml.dmtnds+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.syncml.ds.notification":{source:"iana"},"application/vnd.tableschema+json":{source:"iana",compressible:!0},"application/vnd.tao.intent-module-archive":{source:"iana",extensions:["tao"]},"application/vnd.tcpdump.pcap":{source:"iana",extensions:["pcap","cap","dmp"]},"application/vnd.think-cell.ppttc+json":{source:"iana",compressible:!0},"application/vnd.tmd.mediaflex.api+xml":{source:"iana",compressible:!0},"application/vnd.tml":{source:"iana"},"application/vnd.tmobile-livetv":{source:"iana",extensions:["tmo"]},"application/vnd.tri.onesource":{source:"iana"},"application/vnd.trid.tpt":{source:"iana",extensions:["tpt"]},"application/vnd.triscape.mxs":{source:"iana",extensions:["mxs"]},"application/vnd.trueapp":{source:"iana",extensions:["tra"]},"application/vnd.truedoc":{source:"iana"},"application/vnd.ubisoft.webplayer":{source:"iana"},"application/vnd.ufdl":{source:"iana",extensions:["ufd","ufdl"]},"application/vnd.uic.osdm+json":{source:"iana",compressible:!0},"application/vnd.uiq.theme":{source:"iana",extensions:["utz"]},"application/vnd.umajin":{source:"iana",extensions:["umj"]},"application/vnd.unity":{source:"iana",extensions:["unityweb"]},"application/vnd.uoml+xml":{source:"iana",compressible:!0,extensions:["uoml","uo"]},"application/vnd.uplanet.alert":{source:"iana"},"application/vnd.uplanet.alert-wbxml":{source:"iana"},"application/vnd.uplanet.bearer-choice":{source:"iana"},"application/vnd.uplanet.bearer-choice-wbxml":{source:"iana"},"application/vnd.uplanet.cacheop":{source:"iana"},"application/vnd.uplanet.cacheop-wbxml":{source:"iana"},"application/vnd.uplanet.channel":{source:"iana"},"application/vnd.uplanet.channel-wbxml":{source:"iana"},"application/vnd.uplanet.list":{source:"iana"},"application/vnd.uplanet.list-wbxml":{source:"iana"},"application/vnd.uplanet.listcmd":{source:"iana"},"application/vnd.uplanet.listcmd-wbxml":{source:"iana"},"application/vnd.uplanet.signal":{source:"iana"},"application/vnd.uri-map":{source:"iana"},"application/vnd.valve.source.material":{source:"iana"},"application/vnd.vcx":{source:"iana",extensions:["vcx"]},"application/vnd.vd-study":{source:"iana"},"application/vnd.vectorworks":{source:"iana"},"application/vnd.vel+json":{source:"iana",compressible:!0},"application/vnd.veraison.tsm-report+cbor":{source:"iana"},"application/vnd.veraison.tsm-report+json":{source:"iana",compressible:!0},"application/vnd.verimatrix.vcas":{source:"iana"},"application/vnd.veritone.aion+json":{source:"iana",compressible:!0},"application/vnd.veryant.thin":{source:"iana"},"application/vnd.ves.encrypted":{source:"iana"},"application/vnd.vidsoft.vidconference":{source:"iana"},"application/vnd.visio":{source:"iana",extensions:["vsd","vst","vss","vsw","vsdx","vtx"]},"application/vnd.visionary":{source:"iana",extensions:["vis"]},"application/vnd.vividence.scriptfile":{source:"iana"},"application/vnd.vocalshaper.vsp4":{source:"iana"},"application/vnd.vsf":{source:"iana",extensions:["vsf"]},"application/vnd.wap.sic":{source:"iana"},"application/vnd.wap.slc":{source:"iana"},"application/vnd.wap.wbxml":{source:"iana",charset:"UTF-8",extensions:["wbxml"]},"application/vnd.wap.wmlc":{source:"iana",extensions:["wmlc"]},"application/vnd.wap.wmlscriptc":{source:"iana",extensions:["wmlsc"]},"application/vnd.wasmflow.wafl":{source:"iana"},"application/vnd.webturbo":{source:"iana",extensions:["wtb"]},"application/vnd.wfa.dpp":{source:"iana"},"application/vnd.wfa.p2p":{source:"iana"},"application/vnd.wfa.wsc":{source:"iana"},"application/vnd.windows.devicepairing":{source:"iana"},"application/vnd.wmc":{source:"iana"},"application/vnd.wmf.bootstrap":{source:"iana"},"application/vnd.wolfram.mathematica":{source:"iana"},"application/vnd.wolfram.mathematica.package":{source:"iana"},"application/vnd.wolfram.player":{source:"iana",extensions:["nbp"]},"application/vnd.wordlift":{source:"iana"},"application/vnd.wordperfect":{source:"iana",extensions:["wpd"]},"application/vnd.wqd":{source:"iana",extensions:["wqd"]},"application/vnd.wrq-hp3000-labelled":{source:"iana"},"application/vnd.wt.stf":{source:"iana",extensions:["stf"]},"application/vnd.wv.csp+wbxml":{source:"iana"},"application/vnd.wv.csp+xml":{source:"iana",compressible:!0},"application/vnd.wv.ssp+xml":{source:"iana",compressible:!0},"application/vnd.xacml+json":{source:"iana",compressible:!0},"application/vnd.xara":{source:"iana",extensions:["xar"]},"application/vnd.xarin.cpj":{source:"iana"},"application/vnd.xecrets-encrypted":{source:"iana"},"application/vnd.xfdl":{source:"iana",extensions:["xfdl"]},"application/vnd.xfdl.webform":{source:"iana"},"application/vnd.xmi+xml":{source:"iana",compressible:!0},"application/vnd.xmpie.cpkg":{source:"iana"},"application/vnd.xmpie.dpkg":{source:"iana"},"application/vnd.xmpie.plan":{source:"iana"},"application/vnd.xmpie.ppkg":{source:"iana"},"application/vnd.xmpie.xlim":{source:"iana"},"application/vnd.yamaha.hv-dic":{source:"iana",extensions:["hvd"]},"application/vnd.yamaha.hv-script":{source:"iana",extensions:["hvs"]},"application/vnd.yamaha.hv-voice":{source:"iana",extensions:["hvp"]},"application/vnd.yamaha.openscoreformat":{source:"iana",extensions:["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{source:"iana",compressible:!0,extensions:["osfpvg"]},"application/vnd.yamaha.remote-setup":{source:"iana"},"application/vnd.yamaha.smaf-audio":{source:"iana",extensions:["saf"]},"application/vnd.yamaha.smaf-phrase":{source:"iana",extensions:["spf"]},"application/vnd.yamaha.through-ngn":{source:"iana"},"application/vnd.yamaha.tunnel-udpencap":{source:"iana"},"application/vnd.yaoweme":{source:"iana"},"application/vnd.yellowriver-custom-menu":{source:"iana",extensions:["cmp"]},"application/vnd.zul":{source:"iana",extensions:["zir","zirz"]},"application/vnd.zzazz.deck+xml":{source:"iana",compressible:!0,extensions:["zaz"]},"application/voicexml+xml":{source:"iana",compressible:!0,extensions:["vxml"]},"application/voucher-cms+json":{source:"iana",compressible:!0},"application/voucher-jws+json":{source:"iana",compressible:!0},"application/vp":{source:"iana"},"application/vp+cose":{source:"iana"},"application/vp+jwt":{source:"iana"},"application/vq-rtcpxr":{source:"iana"},"application/wasm":{source:"iana",compressible:!0,extensions:["wasm"]},"application/watcherinfo+xml":{source:"iana",compressible:!0,extensions:["wif"]},"application/webpush-options+json":{source:"iana",compressible:!0},"application/whoispp-query":{source:"iana"},"application/whoispp-response":{source:"iana"},"application/widget":{source:"iana",extensions:["wgt"]},"application/winhlp":{source:"apache",extensions:["hlp"]},"application/wita":{source:"iana"},"application/wordperfect5.1":{source:"iana"},"application/wsdl+xml":{source:"iana",compressible:!0,extensions:["wsdl"]},"application/wspolicy+xml":{source:"iana",compressible:!0,extensions:["wspolicy"]},"application/x-7z-compressed":{source:"apache",compressible:!1,extensions:["7z"]},"application/x-abiword":{source:"apache",extensions:["abw"]},"application/x-ace-compressed":{source:"apache",extensions:["ace"]},"application/x-amf":{source:"apache"},"application/x-apple-diskimage":{source:"apache",extensions:["dmg"]},"application/x-arj":{compressible:!1,extensions:["arj"]},"application/x-authorware-bin":{source:"apache",extensions:["aab","x32","u32","vox"]},"application/x-authorware-map":{source:"apache",extensions:["aam"]},"application/x-authorware-seg":{source:"apache",extensions:["aas"]},"application/x-bcpio":{source:"apache",extensions:["bcpio"]},"application/x-bdoc":{compressible:!1,extensions:["bdoc"]},"application/x-bittorrent":{source:"apache",extensions:["torrent"]},"application/x-blender":{extensions:["blend"]},"application/x-blorb":{source:"apache",extensions:["blb","blorb"]},"application/x-bzip":{source:"apache",compressible:!1,extensions:["bz"]},"application/x-bzip2":{source:"apache",compressible:!1,extensions:["bz2","boz"]},"application/x-cbr":{source:"apache",extensions:["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{source:"apache",extensions:["vcd"]},"application/x-cfs-compressed":{source:"apache",extensions:["cfs"]},"application/x-chat":{source:"apache",extensions:["chat"]},"application/x-chess-pgn":{source:"apache",extensions:["pgn"]},"application/x-chrome-extension":{extensions:["crx"]},"application/x-cocoa":{source:"nginx",extensions:["cco"]},"application/x-compress":{source:"apache"},"application/x-compressed":{extensions:["rar"]},"application/x-conference":{source:"apache",extensions:["nsc"]},"application/x-cpio":{source:"apache",extensions:["cpio"]},"application/x-csh":{source:"apache",extensions:["csh"]},"application/x-deb":{compressible:!1},"application/x-debian-package":{source:"apache",extensions:["deb","udeb"]},"application/x-dgc-compressed":{source:"apache",extensions:["dgc"]},"application/x-director":{source:"apache",extensions:["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{source:"apache",extensions:["wad"]},"application/x-dtbncx+xml":{source:"apache",compressible:!0,extensions:["ncx"]},"application/x-dtbook+xml":{source:"apache",compressible:!0,extensions:["dtb"]},"application/x-dtbresource+xml":{source:"apache",compressible:!0,extensions:["res"]},"application/x-dvi":{source:"apache",compressible:!1,extensions:["dvi"]},"application/x-envoy":{source:"apache",extensions:["evy"]},"application/x-eva":{source:"apache",extensions:["eva"]},"application/x-font-bdf":{source:"apache",extensions:["bdf"]},"application/x-font-dos":{source:"apache"},"application/x-font-framemaker":{source:"apache"},"application/x-font-ghostscript":{source:"apache",extensions:["gsf"]},"application/x-font-libgrx":{source:"apache"},"application/x-font-linux-psf":{source:"apache",extensions:["psf"]},"application/x-font-pcf":{source:"apache",extensions:["pcf"]},"application/x-font-snf":{source:"apache",extensions:["snf"]},"application/x-font-speedo":{source:"apache"},"application/x-font-sunos-news":{source:"apache"},"application/x-font-type1":{source:"apache",extensions:["pfa","pfb","pfm","afm"]},"application/x-font-vfont":{source:"apache"},"application/x-freearc":{source:"apache",extensions:["arc"]},"application/x-futuresplash":{source:"apache",extensions:["spl"]},"application/x-gca-compressed":{source:"apache",extensions:["gca"]},"application/x-glulx":{source:"apache",extensions:["ulx"]},"application/x-gnumeric":{source:"apache",extensions:["gnumeric"]},"application/x-gramps-xml":{source:"apache",extensions:["gramps"]},"application/x-gtar":{source:"apache",extensions:["gtar"]},"application/x-gzip":{source:"apache"},"application/x-hdf":{source:"apache",extensions:["hdf"]},"application/x-httpd-php":{compressible:!0,extensions:["php"]},"application/x-install-instructions":{source:"apache",extensions:["install"]},"application/x-ipynb+json":{compressible:!0,extensions:["ipynb"]},"application/x-iso9660-image":{source:"apache",extensions:["iso"]},"application/x-iwork-keynote-sffkey":{extensions:["key"]},"application/x-iwork-numbers-sffnumbers":{extensions:["numbers"]},"application/x-iwork-pages-sffpages":{extensions:["pages"]},"application/x-java-archive-diff":{source:"nginx",extensions:["jardiff"]},"application/x-java-jnlp-file":{source:"apache",compressible:!1,extensions:["jnlp"]},"application/x-javascript":{compressible:!0},"application/x-keepass2":{extensions:["kdbx"]},"application/x-latex":{source:"apache",compressible:!1,extensions:["latex"]},"application/x-lua-bytecode":{extensions:["luac"]},"application/x-lzh-compressed":{source:"apache",extensions:["lzh","lha"]},"application/x-makeself":{source:"nginx",extensions:["run"]},"application/x-mie":{source:"apache",extensions:["mie"]},"application/x-mobipocket-ebook":{source:"apache",extensions:["prc","mobi"]},"application/x-mpegurl":{compressible:!1},"application/x-ms-application":{source:"apache",extensions:["application"]},"application/x-ms-shortcut":{source:"apache",extensions:["lnk"]},"application/x-ms-wmd":{source:"apache",extensions:["wmd"]},"application/x-ms-wmz":{source:"apache",extensions:["wmz"]},"application/x-ms-xbap":{source:"apache",extensions:["xbap"]},"application/x-msaccess":{source:"apache",extensions:["mdb"]},"application/x-msbinder":{source:"apache",extensions:["obd"]},"application/x-mscardfile":{source:"apache",extensions:["crd"]},"application/x-msclip":{source:"apache",extensions:["clp"]},"application/x-msdos-program":{extensions:["exe"]},"application/x-msdownload":{source:"apache",extensions:["exe","dll","com","bat","msi"]},"application/x-msmediaview":{source:"apache",extensions:["mvb","m13","m14"]},"application/x-msmetafile":{source:"apache",extensions:["wmf","wmz","emf","emz"]},"application/x-msmoney":{source:"apache",extensions:["mny"]},"application/x-mspublisher":{source:"apache",extensions:["pub"]},"application/x-msschedule":{source:"apache",extensions:["scd"]},"application/x-msterminal":{source:"apache",extensions:["trm"]},"application/x-mswrite":{source:"apache",extensions:["wri"]},"application/x-netcdf":{source:"apache",extensions:["nc","cdf"]},"application/x-ns-proxy-autoconfig":{compressible:!0,extensions:["pac"]},"application/x-nzb":{source:"apache",extensions:["nzb"]},"application/x-perl":{source:"nginx",extensions:["pl","pm"]},"application/x-pilot":{source:"nginx",extensions:["prc","pdb"]},"application/x-pkcs12":{source:"apache",compressible:!1,extensions:["p12","pfx"]},"application/x-pkcs7-certificates":{source:"apache",extensions:["p7b","spc"]},"application/x-pkcs7-certreqresp":{source:"apache",extensions:["p7r"]},"application/x-pki-message":{source:"iana"},"application/x-rar-compressed":{source:"apache",compressible:!1,extensions:["rar"]},"application/x-redhat-package-manager":{source:"nginx",extensions:["rpm"]},"application/x-research-info-systems":{source:"apache",extensions:["ris"]},"application/x-sea":{source:"nginx",extensions:["sea"]},"application/x-sh":{source:"apache",compressible:!0,extensions:["sh"]},"application/x-shar":{source:"apache",extensions:["shar"]},"application/x-shockwave-flash":{source:"apache",compressible:!1,extensions:["swf"]},"application/x-silverlight-app":{source:"apache",extensions:["xap"]},"application/x-sql":{source:"apache",extensions:["sql"]},"application/x-stuffit":{source:"apache",compressible:!1,extensions:["sit"]},"application/x-stuffitx":{source:"apache",extensions:["sitx"]},"application/x-subrip":{source:"apache",extensions:["srt"]},"application/x-sv4cpio":{source:"apache",extensions:["sv4cpio"]},"application/x-sv4crc":{source:"apache",extensions:["sv4crc"]},"application/x-t3vm-image":{source:"apache",extensions:["t3"]},"application/x-tads":{source:"apache",extensions:["gam"]},"application/x-tar":{source:"apache",compressible:!0,extensions:["tar"]},"application/x-tcl":{source:"apache",extensions:["tcl","tk"]},"application/x-tex":{source:"apache",extensions:["tex"]},"application/x-tex-tfm":{source:"apache",extensions:["tfm"]},"application/x-texinfo":{source:"apache",extensions:["texinfo","texi"]},"application/x-tgif":{source:"apache",extensions:["obj"]},"application/x-ustar":{source:"apache",extensions:["ustar"]},"application/x-virtualbox-hdd":{compressible:!0,extensions:["hdd"]},"application/x-virtualbox-ova":{compressible:!0,extensions:["ova"]},"application/x-virtualbox-ovf":{compressible:!0,extensions:["ovf"]},"application/x-virtualbox-vbox":{compressible:!0,extensions:["vbox"]},"application/x-virtualbox-vbox-extpack":{compressible:!1,extensions:["vbox-extpack"]},"application/x-virtualbox-vdi":{compressible:!0,extensions:["vdi"]},"application/x-virtualbox-vhd":{compressible:!0,extensions:["vhd"]},"application/x-virtualbox-vmdk":{compressible:!0,extensions:["vmdk"]},"application/x-wais-source":{source:"apache",extensions:["src"]},"application/x-web-app-manifest+json":{compressible:!0,extensions:["webapp"]},"application/x-www-form-urlencoded":{source:"iana",compressible:!0},"application/x-x509-ca-cert":{source:"iana",extensions:["der","crt","pem"]},"application/x-x509-ca-ra-cert":{source:"iana"},"application/x-x509-next-ca-cert":{source:"iana"},"application/x-xfig":{source:"apache",extensions:["fig"]},"application/x-xliff+xml":{source:"apache",compressible:!0,extensions:["xlf"]},"application/x-xpinstall":{source:"apache",compressible:!1,extensions:["xpi"]},"application/x-xz":{source:"apache",extensions:["xz"]},"application/x-zip-compressed":{extensions:["zip"]},"application/x-zmachine":{source:"apache",extensions:["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/x400-bp":{source:"iana"},"application/xacml+xml":{source:"iana",compressible:!0},"application/xaml+xml":{source:"apache",compressible:!0,extensions:["xaml"]},"application/xcap-att+xml":{source:"iana",compressible:!0,extensions:["xav"]},"application/xcap-caps+xml":{source:"iana",compressible:!0,extensions:["xca"]},"application/xcap-diff+xml":{source:"iana",compressible:!0,extensions:["xdf"]},"application/xcap-el+xml":{source:"iana",compressible:!0,extensions:["xel"]},"application/xcap-error+xml":{source:"iana",compressible:!0},"application/xcap-ns+xml":{source:"iana",compressible:!0,extensions:["xns"]},"application/xcon-conference-info+xml":{source:"iana",compressible:!0},"application/xcon-conference-info-diff+xml":{source:"iana",compressible:!0},"application/xenc+xml":{source:"iana",compressible:!0,extensions:["xenc"]},"application/xfdf":{source:"iana",extensions:["xfdf"]},"application/xhtml+xml":{source:"iana",compressible:!0,extensions:["xhtml","xht"]},"application/xhtml-voice+xml":{source:"apache",compressible:!0},"application/xliff+xml":{source:"iana",compressible:!0,extensions:["xlf"]},"application/xml":{source:"iana",compressible:!0,extensions:["xml","xsl","xsd","rng"]},"application/xml-dtd":{source:"iana",compressible:!0,extensions:["dtd"]},"application/xml-external-parsed-entity":{source:"iana"},"application/xml-patch+xml":{source:"iana",compressible:!0},"application/xmpp+xml":{source:"iana",compressible:!0},"application/xop+xml":{source:"iana",compressible:!0,extensions:["xop"]},"application/xproc+xml":{source:"apache",compressible:!0,extensions:["xpl"]},"application/xslt+xml":{source:"iana",compressible:!0,extensions:["xsl","xslt"]},"application/xspf+xml":{source:"apache",compressible:!0,extensions:["xspf"]},"application/xv+xml":{source:"iana",compressible:!0,extensions:["mxml","xhvml","xvml","xvm"]},"application/yaml":{source:"iana"},"application/yang":{source:"iana",extensions:["yang"]},"application/yang-data+cbor":{source:"iana"},"application/yang-data+json":{source:"iana",compressible:!0},"application/yang-data+xml":{source:"iana",compressible:!0},"application/yang-patch+json":{source:"iana",compressible:!0},"application/yang-patch+xml":{source:"iana",compressible:!0},"application/yang-sid+json":{source:"iana",compressible:!0},"application/yin+xml":{source:"iana",compressible:!0,extensions:["yin"]},"application/zip":{source:"iana",compressible:!1,extensions:["zip"]},"application/zip+dotlottie":{extensions:["lottie"]},"application/zlib":{source:"iana"},"application/zstd":{source:"iana"},"audio/1d-interleaved-parityfec":{source:"iana"},"audio/32kadpcm":{source:"iana"},"audio/3gpp":{source:"iana",compressible:!1,extensions:["3gpp"]},"audio/3gpp2":{source:"iana"},"audio/aac":{source:"iana",extensions:["adts","aac"]},"audio/ac3":{source:"iana"},"audio/adpcm":{source:"apache",extensions:["adp"]},"audio/amr":{source:"iana",extensions:["amr"]},"audio/amr-wb":{source:"iana"},"audio/amr-wb+":{source:"iana"},"audio/aptx":{source:"iana"},"audio/asc":{source:"iana"},"audio/atrac-advanced-lossless":{source:"iana"},"audio/atrac-x":{source:"iana"},"audio/atrac3":{source:"iana"},"audio/basic":{source:"iana",compressible:!1,extensions:["au","snd"]},"audio/bv16":{source:"iana"},"audio/bv32":{source:"iana"},"audio/clearmode":{source:"iana"},"audio/cn":{source:"iana"},"audio/dat12":{source:"iana"},"audio/dls":{source:"iana"},"audio/dsr-es201108":{source:"iana"},"audio/dsr-es202050":{source:"iana"},"audio/dsr-es202211":{source:"iana"},"audio/dsr-es202212":{source:"iana"},"audio/dv":{source:"iana"},"audio/dvi4":{source:"iana"},"audio/eac3":{source:"iana"},"audio/encaprtp":{source:"iana"},"audio/evrc":{source:"iana"},"audio/evrc-qcp":{source:"iana"},"audio/evrc0":{source:"iana"},"audio/evrc1":{source:"iana"},"audio/evrcb":{source:"iana"},"audio/evrcb0":{source:"iana"},"audio/evrcb1":{source:"iana"},"audio/evrcnw":{source:"iana"},"audio/evrcnw0":{source:"iana"},"audio/evrcnw1":{source:"iana"},"audio/evrcwb":{source:"iana"},"audio/evrcwb0":{source:"iana"},"audio/evrcwb1":{source:"iana"},"audio/evs":{source:"iana"},"audio/flac":{source:"iana"},"audio/flexfec":{source:"iana"},"audio/fwdred":{source:"iana"},"audio/g711-0":{source:"iana"},"audio/g719":{source:"iana"},"audio/g722":{source:"iana"},"audio/g7221":{source:"iana"},"audio/g723":{source:"iana"},"audio/g726-16":{source:"iana"},"audio/g726-24":{source:"iana"},"audio/g726-32":{source:"iana"},"audio/g726-40":{source:"iana"},"audio/g728":{source:"iana"},"audio/g729":{source:"iana"},"audio/g7291":{source:"iana"},"audio/g729d":{source:"iana"},"audio/g729e":{source:"iana"},"audio/gsm":{source:"iana"},"audio/gsm-efr":{source:"iana"},"audio/gsm-hr-08":{source:"iana"},"audio/ilbc":{source:"iana"},"audio/ip-mr_v2.5":{source:"iana"},"audio/isac":{source:"apache"},"audio/l16":{source:"iana"},"audio/l20":{source:"iana"},"audio/l24":{source:"iana",compressible:!1},"audio/l8":{source:"iana"},"audio/lpc":{source:"iana"},"audio/matroska":{source:"iana"},"audio/melp":{source:"iana"},"audio/melp1200":{source:"iana"},"audio/melp2400":{source:"iana"},"audio/melp600":{source:"iana"},"audio/mhas":{source:"iana"},"audio/midi":{source:"apache",extensions:["mid","midi","kar","rmi"]},"audio/midi-clip":{source:"iana"},"audio/mobile-xmf":{source:"iana",extensions:["mxmf"]},"audio/mp3":{compressible:!1,extensions:["mp3"]},"audio/mp4":{source:"iana",compressible:!1,extensions:["m4a","mp4a","m4b"]},"audio/mp4a-latm":{source:"iana"},"audio/mpa":{source:"iana"},"audio/mpa-robust":{source:"iana"},"audio/mpeg":{source:"iana",compressible:!1,extensions:["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/mpeg4-generic":{source:"iana"},"audio/musepack":{source:"apache"},"audio/ogg":{source:"iana",compressible:!1,extensions:["oga","ogg","spx","opus"]},"audio/opus":{source:"iana"},"audio/parityfec":{source:"iana"},"audio/pcma":{source:"iana"},"audio/pcma-wb":{source:"iana"},"audio/pcmu":{source:"iana"},"audio/pcmu-wb":{source:"iana"},"audio/prs.sid":{source:"iana"},"audio/qcelp":{source:"iana"},"audio/raptorfec":{source:"iana"},"audio/red":{source:"iana"},"audio/rtp-enc-aescm128":{source:"iana"},"audio/rtp-midi":{source:"iana"},"audio/rtploopback":{source:"iana"},"audio/rtx":{source:"iana"},"audio/s3m":{source:"apache",extensions:["s3m"]},"audio/scip":{source:"iana"},"audio/silk":{source:"apache",extensions:["sil"]},"audio/smv":{source:"iana"},"audio/smv-qcp":{source:"iana"},"audio/smv0":{source:"iana"},"audio/sofa":{source:"iana"},"audio/sp-midi":{source:"iana"},"audio/speex":{source:"iana"},"audio/t140c":{source:"iana"},"audio/t38":{source:"iana"},"audio/telephone-event":{source:"iana"},"audio/tetra_acelp":{source:"iana"},"audio/tetra_acelp_bb":{source:"iana"},"audio/tone":{source:"iana"},"audio/tsvcis":{source:"iana"},"audio/uemclip":{source:"iana"},"audio/ulpfec":{source:"iana"},"audio/usac":{source:"iana"},"audio/vdvi":{source:"iana"},"audio/vmr-wb":{source:"iana"},"audio/vnd.3gpp.iufp":{source:"iana"},"audio/vnd.4sb":{source:"iana"},"audio/vnd.audiokoz":{source:"iana"},"audio/vnd.celp":{source:"iana"},"audio/vnd.cisco.nse":{source:"iana"},"audio/vnd.cmles.radio-events":{source:"iana"},"audio/vnd.cns.anp1":{source:"iana"},"audio/vnd.cns.inf1":{source:"iana"},"audio/vnd.dece.audio":{source:"iana",extensions:["uva","uvva"]},"audio/vnd.digital-winds":{source:"iana",extensions:["eol"]},"audio/vnd.dlna.adts":{source:"iana"},"audio/vnd.dolby.heaac.1":{source:"iana"},"audio/vnd.dolby.heaac.2":{source:"iana"},"audio/vnd.dolby.mlp":{source:"iana"},"audio/vnd.dolby.mps":{source:"iana"},"audio/vnd.dolby.pl2":{source:"iana"},"audio/vnd.dolby.pl2x":{source:"iana"},"audio/vnd.dolby.pl2z":{source:"iana"},"audio/vnd.dolby.pulse.1":{source:"iana"},"audio/vnd.dra":{source:"iana",extensions:["dra"]},"audio/vnd.dts":{source:"iana",extensions:["dts"]},"audio/vnd.dts.hd":{source:"iana",extensions:["dtshd"]},"audio/vnd.dts.uhd":{source:"iana"},"audio/vnd.dvb.file":{source:"iana"},"audio/vnd.everad.plj":{source:"iana"},"audio/vnd.hns.audio":{source:"iana"},"audio/vnd.lucent.voice":{source:"iana",extensions:["lvp"]},"audio/vnd.ms-playready.media.pya":{source:"iana",extensions:["pya"]},"audio/vnd.nokia.mobile-xmf":{source:"iana"},"audio/vnd.nortel.vbk":{source:"iana"},"audio/vnd.nuera.ecelp4800":{source:"iana",extensions:["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{source:"iana",extensions:["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{source:"iana",extensions:["ecelp9600"]},"audio/vnd.octel.sbc":{source:"iana"},"audio/vnd.presonus.multitrack":{source:"iana"},"audio/vnd.qcelp":{source:"apache"},"audio/vnd.rhetorex.32kadpcm":{source:"iana"},"audio/vnd.rip":{source:"iana",extensions:["rip"]},"audio/vnd.rn-realaudio":{compressible:!1},"audio/vnd.sealedmedia.softseal.mpeg":{source:"iana"},"audio/vnd.vmx.cvsd":{source:"iana"},"audio/vnd.wave":{compressible:!1},"audio/vorbis":{source:"iana",compressible:!1},"audio/vorbis-config":{source:"iana"},"audio/wav":{compressible:!1,extensions:["wav"]},"audio/wave":{compressible:!1,extensions:["wav"]},"audio/webm":{source:"apache",compressible:!1,extensions:["weba"]},"audio/x-aac":{source:"apache",compressible:!1,extensions:["aac"]},"audio/x-aiff":{source:"apache",extensions:["aif","aiff","aifc"]},"audio/x-caf":{source:"apache",compressible:!1,extensions:["caf"]},"audio/x-flac":{source:"apache",extensions:["flac"]},"audio/x-m4a":{source:"nginx",extensions:["m4a"]},"audio/x-matroska":{source:"apache",extensions:["mka"]},"audio/x-mpegurl":{source:"apache",extensions:["m3u"]},"audio/x-ms-wax":{source:"apache",extensions:["wax"]},"audio/x-ms-wma":{source:"apache",extensions:["wma"]},"audio/x-pn-realaudio":{source:"apache",extensions:["ram","ra"]},"audio/x-pn-realaudio-plugin":{source:"apache",extensions:["rmp"]},"audio/x-realaudio":{source:"nginx",extensions:["ra"]},"audio/x-tta":{source:"apache"},"audio/x-wav":{source:"apache",extensions:["wav"]},"audio/xm":{source:"apache",extensions:["xm"]},"chemical/x-cdx":{source:"apache",extensions:["cdx"]},"chemical/x-cif":{source:"apache",extensions:["cif"]},"chemical/x-cmdf":{source:"apache",extensions:["cmdf"]},"chemical/x-cml":{source:"apache",extensions:["cml"]},"chemical/x-csml":{source:"apache",extensions:["csml"]},"chemical/x-pdb":{source:"apache"},"chemical/x-xyz":{source:"apache",extensions:["xyz"]},"font/collection":{source:"iana",extensions:["ttc"]},"font/otf":{source:"iana",compressible:!0,extensions:["otf"]},"font/sfnt":{source:"iana"},"font/ttf":{source:"iana",compressible:!0,extensions:["ttf"]},"font/woff":{source:"iana",extensions:["woff"]},"font/woff2":{source:"iana",extensions:["woff2"]},"image/aces":{source:"iana",extensions:["exr"]},"image/apng":{source:"iana",compressible:!1,extensions:["apng"]},"image/avci":{source:"iana",extensions:["avci"]},"image/avcs":{source:"iana",extensions:["avcs"]},"image/avif":{source:"iana",compressible:!1,extensions:["avif"]},"image/bmp":{source:"iana",compressible:!0,extensions:["bmp","dib"]},"image/cgm":{source:"iana",extensions:["cgm"]},"image/dicom-rle":{source:"iana",extensions:["drle"]},"image/dpx":{source:"iana",extensions:["dpx"]},"image/emf":{source:"iana",extensions:["emf"]},"image/fits":{source:"iana",extensions:["fits"]},"image/g3fax":{source:"iana",extensions:["g3"]},"image/gif":{source:"iana",compressible:!1,extensions:["gif"]},"image/heic":{source:"iana",extensions:["heic"]},"image/heic-sequence":{source:"iana",extensions:["heics"]},"image/heif":{source:"iana",extensions:["heif"]},"image/heif-sequence":{source:"iana",extensions:["heifs"]},"image/hej2k":{source:"iana",extensions:["hej2"]},"image/ief":{source:"iana",extensions:["ief"]},"image/j2c":{source:"iana"},"image/jaii":{source:"iana",extensions:["jaii"]},"image/jais":{source:"iana",extensions:["jais"]},"image/jls":{source:"iana",extensions:["jls"]},"image/jp2":{source:"iana",compressible:!1,extensions:["jp2","jpg2"]},"image/jpeg":{source:"iana",compressible:!1,extensions:["jpg","jpeg","jpe"]},"image/jph":{source:"iana",extensions:["jph"]},"image/jphc":{source:"iana",extensions:["jhc"]},"image/jpm":{source:"iana",compressible:!1,extensions:["jpm","jpgm"]},"image/jpx":{source:"iana",compressible:!1,extensions:["jpx","jpf"]},"image/jxl":{source:"iana",extensions:["jxl"]},"image/jxr":{source:"iana",extensions:["jxr"]},"image/jxra":{source:"iana",extensions:["jxra"]},"image/jxrs":{source:"iana",extensions:["jxrs"]},"image/jxs":{source:"iana",extensions:["jxs"]},"image/jxsc":{source:"iana",extensions:["jxsc"]},"image/jxsi":{source:"iana",extensions:["jxsi"]},"image/jxss":{source:"iana",extensions:["jxss"]},"image/ktx":{source:"iana",extensions:["ktx"]},"image/ktx2":{source:"iana",extensions:["ktx2"]},"image/naplps":{source:"iana"},"image/pjpeg":{compressible:!1,extensions:["jfif"]},"image/png":{source:"iana",compressible:!1,extensions:["png"]},"image/prs.btif":{source:"iana",extensions:["btif","btf"]},"image/prs.pti":{source:"iana",extensions:["pti"]},"image/pwg-raster":{source:"iana"},"image/sgi":{source:"apache",extensions:["sgi"]},"image/svg+xml":{source:"iana",compressible:!0,extensions:["svg","svgz"]},"image/t38":{source:"iana",extensions:["t38"]},"image/tiff":{source:"iana",compressible:!1,extensions:["tif","tiff"]},"image/tiff-fx":{source:"iana",extensions:["tfx"]},"image/vnd.adobe.photoshop":{source:"iana",compressible:!0,extensions:["psd"]},"image/vnd.airzip.accelerator.azv":{source:"iana",extensions:["azv"]},"image/vnd.clip":{source:"iana"},"image/vnd.cns.inf2":{source:"iana"},"image/vnd.dece.graphic":{source:"iana",extensions:["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{source:"iana",extensions:["djvu","djv"]},"image/vnd.dvb.subtitle":{source:"iana",extensions:["sub"]},"image/vnd.dwg":{source:"iana",extensions:["dwg"]},"image/vnd.dxf":{source:"iana",extensions:["dxf"]},"image/vnd.fastbidsheet":{source:"iana",extensions:["fbs"]},"image/vnd.fpx":{source:"iana",extensions:["fpx"]},"image/vnd.fst":{source:"iana",extensions:["fst"]},"image/vnd.fujixerox.edmics-mmr":{source:"iana",extensions:["mmr"]},"image/vnd.fujixerox.edmics-rlc":{source:"iana",extensions:["rlc"]},"image/vnd.globalgraphics.pgb":{source:"iana"},"image/vnd.microsoft.icon":{source:"iana",compressible:!0,extensions:["ico"]},"image/vnd.mix":{source:"iana"},"image/vnd.mozilla.apng":{source:"iana"},"image/vnd.ms-dds":{compressible:!0,extensions:["dds"]},"image/vnd.ms-modi":{source:"iana",extensions:["mdi"]},"image/vnd.ms-photo":{source:"apache",extensions:["wdp"]},"image/vnd.net-fpx":{source:"iana",extensions:["npx"]},"image/vnd.pco.b16":{source:"iana",extensions:["b16"]},"image/vnd.radiance":{source:"iana"},"image/vnd.sealed.png":{source:"iana"},"image/vnd.sealedmedia.softseal.gif":{source:"iana"},"image/vnd.sealedmedia.softseal.jpg":{source:"iana"},"image/vnd.svf":{source:"iana"},"image/vnd.tencent.tap":{source:"iana",extensions:["tap"]},"image/vnd.valve.source.texture":{source:"iana",extensions:["vtf"]},"image/vnd.wap.wbmp":{source:"iana",extensions:["wbmp"]},"image/vnd.xiff":{source:"iana",extensions:["xif"]},"image/vnd.zbrush.pcx":{source:"iana",extensions:["pcx"]},"image/webp":{source:"iana",extensions:["webp"]},"image/wmf":{source:"iana",extensions:["wmf"]},"image/x-3ds":{source:"apache",extensions:["3ds"]},"image/x-adobe-dng":{extensions:["dng"]},"image/x-cmu-raster":{source:"apache",extensions:["ras"]},"image/x-cmx":{source:"apache",extensions:["cmx"]},"image/x-emf":{source:"iana"},"image/x-freehand":{source:"apache",extensions:["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{source:"apache",compressible:!0,extensions:["ico"]},"image/x-jng":{source:"nginx",extensions:["jng"]},"image/x-mrsid-image":{source:"apache",extensions:["sid"]},"image/x-ms-bmp":{source:"nginx",compressible:!0,extensions:["bmp"]},"image/x-pcx":{source:"apache",extensions:["pcx"]},"image/x-pict":{source:"apache",extensions:["pic","pct"]},"image/x-portable-anymap":{source:"apache",extensions:["pnm"]},"image/x-portable-bitmap":{source:"apache",extensions:["pbm"]},"image/x-portable-graymap":{source:"apache",extensions:["pgm"]},"image/x-portable-pixmap":{source:"apache",extensions:["ppm"]},"image/x-rgb":{source:"apache",extensions:["rgb"]},"image/x-tga":{source:"apache",extensions:["tga"]},"image/x-wmf":{source:"iana"},"image/x-xbitmap":{source:"apache",extensions:["xbm"]},"image/x-xcf":{compressible:!1},"image/x-xpixmap":{source:"apache",extensions:["xpm"]},"image/x-xwindowdump":{source:"apache",extensions:["xwd"]},"message/bhttp":{source:"iana"},"message/cpim":{source:"iana"},"message/delivery-status":{source:"iana"},"message/disposition-notification":{source:"iana",extensions:["disposition-notification"]},"message/external-body":{source:"iana"},"message/feedback-report":{source:"iana"},"message/global":{source:"iana",extensions:["u8msg"]},"message/global-delivery-status":{source:"iana",extensions:["u8dsn"]},"message/global-disposition-notification":{source:"iana",extensions:["u8mdn"]},"message/global-headers":{source:"iana",extensions:["u8hdr"]},"message/http":{source:"iana",compressible:!1},"message/imdn+xml":{source:"iana",compressible:!0},"message/mls":{source:"iana"},"message/news":{source:"apache"},"message/ohttp-req":{source:"iana"},"message/ohttp-res":{source:"iana"},"message/partial":{source:"iana",compressible:!1},"message/rfc822":{source:"iana",compressible:!0,extensions:["eml","mime","mht","mhtml"]},"message/s-http":{source:"apache"},"message/sip":{source:"iana"},"message/sipfrag":{source:"iana"},"message/tracking-status":{source:"iana"},"message/vnd.si.simp":{source:"apache"},"message/vnd.wfa.wsc":{source:"iana",extensions:["wsc"]},"model/3mf":{source:"iana",extensions:["3mf"]},"model/e57":{source:"iana"},"model/gltf+json":{source:"iana",compressible:!0,extensions:["gltf"]},"model/gltf-binary":{source:"iana",compressible:!0,extensions:["glb"]},"model/iges":{source:"iana",compressible:!1,extensions:["igs","iges"]},"model/jt":{source:"iana",extensions:["jt"]},"model/mesh":{source:"iana",compressible:!1,extensions:["msh","mesh","silo"]},"model/mtl":{source:"iana",extensions:["mtl"]},"model/obj":{source:"iana",extensions:["obj"]},"model/prc":{source:"iana",extensions:["prc"]},"model/step":{source:"iana",extensions:["step","stp","stpnc","p21","210"]},"model/step+xml":{source:"iana",compressible:!0,extensions:["stpx"]},"model/step+zip":{source:"iana",compressible:!1,extensions:["stpz"]},"model/step-xml+zip":{source:"iana",compressible:!1,extensions:["stpxz"]},"model/stl":{source:"iana",extensions:["stl"]},"model/u3d":{source:"iana",extensions:["u3d"]},"model/vnd.bary":{source:"iana",extensions:["bary"]},"model/vnd.cld":{source:"iana",extensions:["cld"]},"model/vnd.collada+xml":{source:"iana",compressible:!0,extensions:["dae"]},"model/vnd.dwf":{source:"iana",extensions:["dwf"]},"model/vnd.flatland.3dml":{source:"iana"},"model/vnd.gdl":{source:"iana",extensions:["gdl"]},"model/vnd.gs-gdl":{source:"apache"},"model/vnd.gs.gdl":{source:"iana"},"model/vnd.gtw":{source:"iana",extensions:["gtw"]},"model/vnd.moml+xml":{source:"iana",compressible:!0},"model/vnd.mts":{source:"iana",extensions:["mts"]},"model/vnd.opengex":{source:"iana",extensions:["ogex"]},"model/vnd.parasolid.transmit.binary":{source:"iana",extensions:["x_b"]},"model/vnd.parasolid.transmit.text":{source:"iana",extensions:["x_t"]},"model/vnd.pytha.pyox":{source:"iana",extensions:["pyo","pyox"]},"model/vnd.rosette.annotated-data-model":{source:"iana"},"model/vnd.sap.vds":{source:"iana",extensions:["vds"]},"model/vnd.usda":{source:"iana",extensions:["usda"]},"model/vnd.usdz+zip":{source:"iana",compressible:!1,extensions:["usdz"]},"model/vnd.valve.source.compiled-map":{source:"iana",extensions:["bsp"]},"model/vnd.vtu":{source:"iana",extensions:["vtu"]},"model/vrml":{source:"iana",compressible:!1,extensions:["wrl","vrml"]},"model/x3d+binary":{source:"apache",compressible:!1,extensions:["x3db","x3dbz"]},"model/x3d+fastinfoset":{source:"iana",extensions:["x3db"]},"model/x3d+vrml":{source:"apache",compressible:!1,extensions:["x3dv","x3dvz"]},"model/x3d+xml":{source:"iana",compressible:!0,extensions:["x3d","x3dz"]},"model/x3d-vrml":{source:"iana",extensions:["x3dv"]},"multipart/alternative":{source:"iana",compressible:!1},"multipart/appledouble":{source:"iana"},"multipart/byteranges":{source:"iana"},"multipart/digest":{source:"iana"},"multipart/encrypted":{source:"iana",compressible:!1},"multipart/form-data":{source:"iana",compressible:!1},"multipart/header-set":{source:"iana"},"multipart/mixed":{source:"iana"},"multipart/multilingual":{source:"iana"},"multipart/parallel":{source:"iana"},"multipart/related":{source:"iana",compressible:!1},"multipart/report":{source:"iana"},"multipart/signed":{source:"iana",compressible:!1},"multipart/vnd.bint.med-plus":{source:"iana"},"multipart/voice-message":{source:"iana"},"multipart/x-mixed-replace":{source:"iana"},"text/1d-interleaved-parityfec":{source:"iana"},"text/cache-manifest":{source:"iana",compressible:!0,extensions:["appcache","manifest"]},"text/calendar":{source:"iana",extensions:["ics","ifb"]},"text/calender":{compressible:!0},"text/cmd":{compressible:!0},"text/coffeescript":{extensions:["coffee","litcoffee"]},"text/cql":{source:"iana"},"text/cql-expression":{source:"iana"},"text/cql-identifier":{source:"iana"},"text/css":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["css"]},"text/csv":{source:"iana",compressible:!0,extensions:["csv"]},"text/csv-schema":{source:"iana"},"text/directory":{source:"iana"},"text/dns":{source:"iana"},"text/ecmascript":{source:"apache"},"text/encaprtp":{source:"iana"},"text/enriched":{source:"iana"},"text/fhirpath":{source:"iana"},"text/flexfec":{source:"iana"},"text/fwdred":{source:"iana"},"text/gff3":{source:"iana"},"text/grammar-ref-list":{source:"iana"},"text/hl7v2":{source:"iana"},"text/html":{source:"iana",compressible:!0,extensions:["html","htm","shtml"]},"text/jade":{extensions:["jade"]},"text/javascript":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["js","mjs"]},"text/jcr-cnd":{source:"iana"},"text/jsx":{compressible:!0,extensions:["jsx"]},"text/less":{compressible:!0,extensions:["less"]},"text/markdown":{source:"iana",compressible:!0,extensions:["md","markdown"]},"text/mathml":{source:"nginx",extensions:["mml"]},"text/mdx":{compressible:!0,extensions:["mdx"]},"text/mizar":{source:"iana"},"text/n3":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["n3"]},"text/parameters":{source:"iana",charset:"UTF-8"},"text/parityfec":{source:"iana"},"text/plain":{source:"iana",compressible:!0,extensions:["txt","text","conf","def","list","log","in","ini"]},"text/provenance-notation":{source:"iana",charset:"UTF-8"},"text/prs.fallenstein.rst":{source:"iana"},"text/prs.lines.tag":{source:"iana",extensions:["dsc"]},"text/prs.prop.logic":{source:"iana"},"text/prs.texi":{source:"iana"},"text/raptorfec":{source:"iana"},"text/red":{source:"iana"},"text/rfc822-headers":{source:"iana"},"text/richtext":{source:"iana",compressible:!0,extensions:["rtx"]},"text/rtf":{source:"iana",compressible:!0,extensions:["rtf"]},"text/rtp-enc-aescm128":{source:"iana"},"text/rtploopback":{source:"iana"},"text/rtx":{source:"iana"},"text/sgml":{source:"iana",extensions:["sgml","sgm"]},"text/shaclc":{source:"iana"},"text/shex":{source:"iana",extensions:["shex"]},"text/slim":{extensions:["slim","slm"]},"text/spdx":{source:"iana",extensions:["spdx"]},"text/strings":{source:"iana"},"text/stylus":{extensions:["stylus","styl"]},"text/t140":{source:"iana"},"text/tab-separated-values":{source:"iana",compressible:!0,extensions:["tsv"]},"text/troff":{source:"iana",extensions:["t","tr","roff","man","me","ms"]},"text/turtle":{source:"iana",charset:"UTF-8",extensions:["ttl"]},"text/ulpfec":{source:"iana"},"text/uri-list":{source:"iana",compressible:!0,extensions:["uri","uris","urls"]},"text/vcard":{source:"iana",compressible:!0,extensions:["vcard"]},"text/vnd.a":{source:"iana"},"text/vnd.abc":{source:"iana"},"text/vnd.ascii-art":{source:"iana"},"text/vnd.curl":{source:"iana",extensions:["curl"]},"text/vnd.curl.dcurl":{source:"apache",extensions:["dcurl"]},"text/vnd.curl.mcurl":{source:"apache",extensions:["mcurl"]},"text/vnd.curl.scurl":{source:"apache",extensions:["scurl"]},"text/vnd.debian.copyright":{source:"iana",charset:"UTF-8"},"text/vnd.dmclientscript":{source:"iana"},"text/vnd.dvb.subtitle":{source:"iana",extensions:["sub"]},"text/vnd.esmertec.theme-descriptor":{source:"iana",charset:"UTF-8"},"text/vnd.exchangeable":{source:"iana"},"text/vnd.familysearch.gedcom":{source:"iana",extensions:["ged"]},"text/vnd.ficlab.flt":{source:"iana"},"text/vnd.fly":{source:"iana",extensions:["fly"]},"text/vnd.fmi.flexstor":{source:"iana",extensions:["flx"]},"text/vnd.gml":{source:"iana"},"text/vnd.graphviz":{source:"iana",extensions:["gv"]},"text/vnd.hans":{source:"iana"},"text/vnd.hgl":{source:"iana"},"text/vnd.in3d.3dml":{source:"iana",extensions:["3dml"]},"text/vnd.in3d.spot":{source:"iana",extensions:["spot"]},"text/vnd.iptc.newsml":{source:"iana"},"text/vnd.iptc.nitf":{source:"iana"},"text/vnd.latex-z":{source:"iana"},"text/vnd.motorola.reflex":{source:"iana"},"text/vnd.ms-mediapackage":{source:"iana"},"text/vnd.net2phone.commcenter.command":{source:"iana"},"text/vnd.radisys.msml-basic-layout":{source:"iana"},"text/vnd.senx.warpscript":{source:"iana"},"text/vnd.si.uricatalogue":{source:"apache"},"text/vnd.sosi":{source:"iana"},"text/vnd.sun.j2me.app-descriptor":{source:"iana",charset:"UTF-8",extensions:["jad"]},"text/vnd.trolltech.linguist":{source:"iana",charset:"UTF-8"},"text/vnd.vcf":{source:"iana"},"text/vnd.wap.si":{source:"iana"},"text/vnd.wap.sl":{source:"iana"},"text/vnd.wap.wml":{source:"iana",extensions:["wml"]},"text/vnd.wap.wmlscript":{source:"iana",extensions:["wmls"]},"text/vnd.zoo.kcl":{source:"iana"},"text/vtt":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["vtt"]},"text/wgsl":{source:"iana",extensions:["wgsl"]},"text/x-asm":{source:"apache",extensions:["s","asm"]},"text/x-c":{source:"apache",extensions:["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{source:"nginx",extensions:["htc"]},"text/x-fortran":{source:"apache",extensions:["f","for","f77","f90"]},"text/x-gwt-rpc":{compressible:!0},"text/x-handlebars-template":{extensions:["hbs"]},"text/x-java-source":{source:"apache",extensions:["java"]},"text/x-jquery-tmpl":{compressible:!0},"text/x-lua":{extensions:["lua"]},"text/x-markdown":{compressible:!0,extensions:["mkd"]},"text/x-nfo":{source:"apache",extensions:["nfo"]},"text/x-opml":{source:"apache",extensions:["opml"]},"text/x-org":{compressible:!0,extensions:["org"]},"text/x-pascal":{source:"apache",extensions:["p","pas"]},"text/x-processing":{compressible:!0,extensions:["pde"]},"text/x-sass":{extensions:["sass"]},"text/x-scss":{extensions:["scss"]},"text/x-setext":{source:"apache",extensions:["etx"]},"text/x-sfv":{source:"apache",extensions:["sfv"]},"text/x-suse-ymp":{compressible:!0,extensions:["ymp"]},"text/x-uuencode":{source:"apache",extensions:["uu"]},"text/x-vcalendar":{source:"apache",extensions:["vcs"]},"text/x-vcard":{source:"apache",extensions:["vcf"]},"text/xml":{source:"iana",compressible:!0,extensions:["xml"]},"text/xml-external-parsed-entity":{source:"iana"},"text/yaml":{compressible:!0,extensions:["yaml","yml"]},"video/1d-interleaved-parityfec":{source:"iana"},"video/3gpp":{source:"iana",extensions:["3gp","3gpp"]},"video/3gpp-tt":{source:"iana"},"video/3gpp2":{source:"iana",extensions:["3g2"]},"video/av1":{source:"iana"},"video/bmpeg":{source:"iana"},"video/bt656":{source:"iana"},"video/celb":{source:"iana"},"video/dv":{source:"iana"},"video/encaprtp":{source:"iana"},"video/evc":{source:"iana"},"video/ffv1":{source:"iana"},"video/flexfec":{source:"iana"},"video/h261":{source:"iana",extensions:["h261"]},"video/h263":{source:"iana",extensions:["h263"]},"video/h263-1998":{source:"iana"},"video/h263-2000":{source:"iana"},"video/h264":{source:"iana",extensions:["h264"]},"video/h264-rcdo":{source:"iana"},"video/h264-svc":{source:"iana"},"video/h265":{source:"iana"},"video/h266":{source:"iana"},"video/iso.segment":{source:"iana",extensions:["m4s"]},"video/jpeg":{source:"iana",extensions:["jpgv"]},"video/jpeg2000":{source:"iana"},"video/jpm":{source:"apache",extensions:["jpm","jpgm"]},"video/jxsv":{source:"iana"},"video/lottie+json":{source:"iana",compressible:!0},"video/matroska":{source:"iana"},"video/matroska-3d":{source:"iana"},"video/mj2":{source:"iana",extensions:["mj2","mjp2"]},"video/mp1s":{source:"iana"},"video/mp2p":{source:"iana"},"video/mp2t":{source:"iana",extensions:["ts","m2t","m2ts","mts"]},"video/mp4":{source:"iana",compressible:!1,extensions:["mp4","mp4v","mpg4"]},"video/mp4v-es":{source:"iana"},"video/mpeg":{source:"iana",compressible:!1,extensions:["mpeg","mpg","mpe","m1v","m2v"]},"video/mpeg4-generic":{source:"iana"},"video/mpv":{source:"iana"},"video/nv":{source:"iana"},"video/ogg":{source:"iana",compressible:!1,extensions:["ogv"]},"video/parityfec":{source:"iana"},"video/pointer":{source:"iana"},"video/quicktime":{source:"iana",compressible:!1,extensions:["qt","mov"]},"video/raptorfec":{source:"iana"},"video/raw":{source:"iana"},"video/rtp-enc-aescm128":{source:"iana"},"video/rtploopback":{source:"iana"},"video/rtx":{source:"iana"},"video/scip":{source:"iana"},"video/smpte291":{source:"iana"},"video/smpte292m":{source:"iana"},"video/ulpfec":{source:"iana"},"video/vc1":{source:"iana"},"video/vc2":{source:"iana"},"video/vnd.cctv":{source:"iana"},"video/vnd.dece.hd":{source:"iana",extensions:["uvh","uvvh"]},"video/vnd.dece.mobile":{source:"iana",extensions:["uvm","uvvm"]},"video/vnd.dece.mp4":{source:"iana"},"video/vnd.dece.pd":{source:"iana",extensions:["uvp","uvvp"]},"video/vnd.dece.sd":{source:"iana",extensions:["uvs","uvvs"]},"video/vnd.dece.video":{source:"iana",extensions:["uvv","uvvv"]},"video/vnd.directv.mpeg":{source:"iana"},"video/vnd.directv.mpeg-tts":{source:"iana"},"video/vnd.dlna.mpeg-tts":{source:"iana"},"video/vnd.dvb.file":{source:"iana",extensions:["dvb"]},"video/vnd.fvt":{source:"iana",extensions:["fvt"]},"video/vnd.hns.video":{source:"iana"},"video/vnd.iptvforum.1dparityfec-1010":{source:"iana"},"video/vnd.iptvforum.1dparityfec-2005":{source:"iana"},"video/vnd.iptvforum.2dparityfec-1010":{source:"iana"},"video/vnd.iptvforum.2dparityfec-2005":{source:"iana"},"video/vnd.iptvforum.ttsavc":{source:"iana"},"video/vnd.iptvforum.ttsmpeg2":{source:"iana"},"video/vnd.motorola.video":{source:"iana"},"video/vnd.motorola.videop":{source:"iana"},"video/vnd.mpegurl":{source:"iana",extensions:["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{source:"iana",extensions:["pyv"]},"video/vnd.nokia.interleaved-multimedia":{source:"iana"},"video/vnd.nokia.mp4vr":{source:"iana"},"video/vnd.nokia.videovoip":{source:"iana"},"video/vnd.objectvideo":{source:"iana"},"video/vnd.planar":{source:"iana"},"video/vnd.radgamettools.bink":{source:"iana"},"video/vnd.radgamettools.smacker":{source:"apache"},"video/vnd.sealed.mpeg1":{source:"iana"},"video/vnd.sealed.mpeg4":{source:"iana"},"video/vnd.sealed.swf":{source:"iana"},"video/vnd.sealedmedia.softseal.mov":{source:"iana"},"video/vnd.uvvu.mp4":{source:"iana",extensions:["uvu","uvvu"]},"video/vnd.vivo":{source:"iana",extensions:["viv"]},"video/vnd.youtube.yt":{source:"iana"},"video/vp8":{source:"iana"},"video/vp9":{source:"iana"},"video/webm":{source:"apache",compressible:!1,extensions:["webm"]},"video/x-f4v":{source:"apache",extensions:["f4v"]},"video/x-fli":{source:"apache",extensions:["fli"]},"video/x-flv":{source:"apache",compressible:!1,extensions:["flv"]},"video/x-m4v":{source:"apache",extensions:["m4v"]},"video/x-matroska":{source:"apache",compressible:!1,extensions:["mkv","mk3d","mks"]},"video/x-mng":{source:"apache",extensions:["mng"]},"video/x-ms-asf":{source:"apache",extensions:["asf","asx"]},"video/x-ms-vob":{source:"apache",extensions:["vob"]},"video/x-ms-wm":{source:"apache",extensions:["wm"]},"video/x-ms-wmv":{source:"apache",compressible:!1,extensions:["wmv"]},"video/x-ms-wmx":{source:"apache",extensions:["wmx"]},"video/x-ms-wvx":{source:"apache",extensions:["wvx"]},"video/x-msvideo":{source:"apache",extensions:["avi"]},"video/x-sgi-movie":{source:"apache",extensions:["movie"]},"video/x-smv":{source:"apache",extensions:["smv"]},"x-conference/x-cooltalk":{source:"apache",extensions:["ice"]},"x-shader/x-fragment":{compressible:!0},"x-shader/x-vertex":{compressible:!0}};function yn(){if(fn)return hn;fn=1;var e={"prs.":100,"x-":200,"x.":300,"vnd.":400,default:900},n={nginx:10,apache:20,iana:40,default:30},a={application:1,font:2,audio:2,video:3,default:0};return hn=function(t,s="default"){if("application/octet-stream"===t)return 0;const[i,o]=t.split("/"),r=o.replace(/(\.|x-).*/,"$1");return(e[r]||e.default)+(n[s]||n.default)+(a[i]||a.default)+(1-t.length/100)}}var wn=(xn||(xn=1,function(e){var n,a,t=gn?mn:(gn=1,mn=bn),s=B.extname,i=yn(),o=/^\s*([^;\s]*)(?:;|\s|$)/,r=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var n=o.exec(e),a=n&&t[n[1].toLowerCase()];return a&&a.charset?a.charset:!(!n||!r.test(n[1]))&&"UTF-8"}function p(n){if(!n||"string"!=typeof n)return!1;var a=o.exec(n),t=a&&e.extensions[a[1].toLowerCase()];return!(!t||!t.length)&&t[0]}function l(e,n,a){return(n?i(n,t[n].source):0)>(a?i(a,t[a].source):0)?n:a}function d(n,a,s){var i=["nginx","apache",void 0,"iana"],o=a?i.indexOf(t[a].source):0,r=s?i.indexOf(t[s].source):0;return"application/octet-stream"!==e.types[p]&&(o>r||o===r&&"application/"===e.types[p]?.slice(0,12))||o>r?a:s}e.charset=c,e.charsets={lookup:c},e.contentType=function(n){if(!n||"string"!=typeof n)return!1;var a=-1===n.indexOf("/")?e.lookup(n):n;if(!a)return!1;if(-1===a.indexOf("charset")){var t=e.charset(a);t&&(a+="; charset="+t.toLowerCase())}return a},e.extension=p,e.extensions=Object.create(null),e.lookup=function(n){if(!n||"string"!=typeof n)return!1;var a=s("x."+n).toLowerCase().slice(1);return a&&e.types[a]||!1},e.types=Object.create(null),e._extensionConflicts=[],n=e.extensions,a=e.types,Object.keys(t).forEach(function(s){var i=t[s].extensions;if(i&&i.length){n[s]=i;for(var o=0;o<i.length;o++){var r=i[o];a[r]=l(0,a[r],s);const n=d(0,a[r],s);n!==a[r]&&e._extensionConflicts.push([r,n,a[r]])}}})}(vn)),vn);function kn(e,n){e?e.send("workspace-file-response",n):P.error("[WORKSPACE] Cannot send workspace-file-response: client not available")}function In(e,n,a,t){return{eventId:d(),requestId:e,taskId:n,success:!1,error:{code:a,message:t}}}function Sn(e){return async n=>{const{taskId:a,userId:t,relativePath:s,requestId:i,maxFileSizeMB:o,ifModifiedSince:r,dataEncryptionKey:c}=n;P.debug(`[WORKSPACE] File request: taskId=${a}, userId=${t}, relativePath=${s}, maxFileSizeMB=${o}, ifModifiedSince=${r}, hasEncryptionKey=${!!c}`);try{const n=1024*(o||10)*1024,m=function(e,n,a){return D.resolveWorkspaceFilePath(e,n,a)}(t,a,s);if(!ne.existsSync(m))return P.warn(`[WORKSPACE] File not found: ${m}`),void kn(e.client,In(i,a,"file_not_found","File or directory not found"));const g=await ne.promises.stat(m),h=g.mtime.toISOString();if(r&&h===r)return void function(e,n,a,t){P.debug(`[WORKSPACE] File not modified: ${t}`),kn(e,{eventId:d(),requestId:n,taskId:a,success:!0,notModified:!0})}(e.client,i,a,m);if(g.isDirectory())return void await async function(e,n,a,t,s,i){const o=await ne.promises.readdir(t,{withFileTypes:!0}),r=await Promise.all(o.map(async e=>{const n=de.join(t,e.name),a=await ne.promises.stat(n);return{name:e.name,type:e.isDirectory()?"directory":"file",size:a.size,modifiedAt:a.mtime.toISOString(),accessDenied:a.size>i}}));kn(e,{eventId:d(),requestId:n,taskId:a,success:!0,data:{type:"directory",entries:r,metadata:{size:0,modifiedAt:s.mtime.toISOString()}}})}(e.client,i,a,m,g,n);{const t=wn.lookup(m)||"application/octet-stream";return g.size>n?void function(e,n,a,t,s,i,o){P.warn(`[WORKSPACE] File too large (${s.size} bytes > ${o} bytes): ${t}`),kn(e,{eventId:d(),requestId:n,taskId:a,success:!0,data:{type:"file",metadata:{size:s.size,mimeType:i,modifiedAt:s.mtime.toISOString(),accessDenied:!0}}})}(e.client,i,a,m,g,t,n):void await async function(e,n,a,t,s,i){const o=wn.lookup(t)||"application/octet-stream",r=(await ne.promises.readFile(t)).toString("base64");let c=null;i&&(c=await async function(e){try{const n=await D.getSecretKey();if(!n)return P.warn("[WORKSPACE] Machine secret key not available"),null;const a=p(e);return l(a,n)||(P.warn("[WORKSPACE] Failed to decrypt dataEncryptionKey"),null)}catch(e){return P.warn("[WORKSPACE] Error decrypting dataEncryptionKey:",e),null}}(i));const m={type:"file",metadata:{size:s.size,mimeType:o,modifiedAt:s.mtime.toISOString()}};c?m.encryptedContent=u(r,c):m.content=r,kn(e,{eventId:d(),requestId:n,taskId:a,success:!0,data:m})}(e.client,i,a,m,g,c)}}catch(n){P.error(`[WORKSPACE] Failed to handle workspace-file-request: ${n.message}`,n);const t="ENOENT"===n.code?"file_not_found":"EACCES"===n.code?"permission_denied":"unknown_error";kn(e.client,In(i,a,t,n.message))}}}const Tn=me(D.agentrixHomeDir,"credentials");function En(e,n){const a=function(e){return me(Tn,`${e}.pat.enc`)}(e);if(!te(a))return null;try{const e=se(a,"utf8"),{iv:t,authTag:s,encrypted:i}=JSON.parse(e),o=n.slice(0,32),r=_("aes-256-gcm",o,Buffer.from(t,"hex"));r.setAuthTag(Buffer.from(s,"hex"));let c=r.update(i,"hex","utf8");return c+=r.final("utf8"),c}catch{return null}}const Cn=[{method:"GET",pattern:/^\/projects$/},{method:"GET",pattern:/^\/projects\/[^/]+\/repository\/branches$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues\/\d+$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests$/}];class An{apiUrl;pat;requestId;gitServerId;constructor(e,n,a){this.apiUrl=e,this.pat=n,this.requestId=a?.requestId,this.gitServerId=a?.gitServerId}logPrefix(){return`[GITLAB EXECUTOR] reqId=${this.requestId??"-"}, gitServer=${this.gitServerId??"-"}`}summarizeResult(e,n){if(Array.isArray(n))return`items=${n.length}`;if(n&&"object"==typeof n){const a=n;return"resolveGitAuthContext"===e?`authMode=${String(a.authMode??"unknown")}, hasPat=${Boolean(a.hasPat)}`:"number"in a||"state"in a?`number=${String(a.number??"-")}, state=${String(a.state??"-")}`:`keys=${Object.keys(a).join(",")||"-"}`}return"type="+typeof n}truncateText(e,n=300){return e.length<=n?e:`${e.slice(0,n)}...`}async request(e,n="GET",a){const t=`${this.apiUrl}${e}`,s={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/json"},i=Date.now();P.debug(`${this.logPrefix()} request start: ${n} ${e}`);try{const o=await fetch(t,{method:n,headers:s,body:a?JSON.stringify(a):void 0}),r=Date.now()-i;if(!o.ok){const a=await o.text().catch(()=>"Unknown error"),t=this.truncateText(a);throw P.warn(`${this.logPrefix()} request failed: ${n} ${e}, status=${o.status}, elapsedMs=${r}, detail=${t}`),{status:o.status,message:`GitLab API error: ${o.status} ${o.statusText}`,detail:t}}return P.debug(`${this.logPrefix()} request success: ${n} ${e}, elapsedMs=${r}`),await o.json()}catch(a){if("object"==typeof a&&null!==a&&"status"in a)throw a;const t=a instanceof Error?a.message:"Unknown network error";throw P.error(`${this.logPrefix()} request exception: ${n} ${e}, message=${t}`),{status:0,message:`GitLab request failed: ${t}`}}}async executeOperation(e,n){P.info(`${this.logPrefix()} execute operation: op=${e}, payloadKeys=${Object.keys(n||{}).join(",")||"-"}`);try{let a;switch(e){case"listRepos":a=await this.listRepos();break;case"listBranches":a=await this.listBranches(n.owner,n.name);break;case"createMergeRequest":a=await this.createMergeRequest(n);break;case"getMergeRequest":a=await this.getMergeRequest(n.owner,n.name,n.iid);break;case"listMergeRequests":a=await this.listMergeRequests(n.owner,n.name);break;case"requestGitlabApi":a=await this.requestGitlabApi(n);break;case"resolveGitAuthContext":a={authMode:"local_pat",hasPat:!0};break;default:throw{status:400,message:`Unknown operation: ${e}`}}return P.info(`${this.logPrefix()} operation success: op=${e}, summary=${this.summarizeResult(e,a)}`),a}catch(n){const a=n instanceof Error?n.message:"object"==typeof n&&null!==n&&"message"in n?String(n.message):"Unknown error";throw P.error(`${this.logPrefix()} operation failed: op=${e}, message=${a}`),n}}async listRepos(){return(await this.request("/projects?membership=true&per_page=100&order_by=updated_at&sort=desc")).map(e=>({id:e.id,owner:e.namespace.path,name:e.path,fullName:e.path_with_namespace,defaultBranch:e.default_branch,isPrivate:"private"===e.visibility,description:e.description,url:e.web_url,createdAt:e.created_at,updatedAt:e.updated_at}))}async listBranches(e,n){const a=encodeURIComponent(`${e}/${n}`);return(await this.request(`/projects/${a}/repository/branches?per_page=100`)).map(e=>({name:e.name,commit:{sha:e.commit.id,url:""},protected:e.protected}))}async createMergeRequest(e){const n=encodeURIComponent(`${e.owner}/${e.repo}`),a=await this.request(`/projects/${n}/merge_requests`,"POST",{source_branch:e.head,target_branch:e.base,title:e.title,description:e.body||""});return{number:a.iid,title:a.title,body:a.description,state:"opened"===a.state?"open":a.state,url:a.web_url,head:a.source_branch,base:a.target_branch,createdAt:a.created_at,updatedAt:a.updated_at}}async getMergeRequest(e,n,a){const t=encodeURIComponent(`${e}/${n}`),s=await this.request(`/projects/${t}/merge_requests/${a}`);return{number:s.iid,title:s.title,body:s.description,state:"opened"===s.state?"open":s.state,url:s.web_url,head:s.source_branch,base:s.target_branch,createdAt:s.created_at,updatedAt:s.updated_at}}async listMergeRequests(e,n){const a=encodeURIComponent(`${e}/${n}`);return(await this.request(`/projects/${a}/merge_requests?state=opened&per_page=20`)).map(e=>({number:e.iid,title:e.title,body:e.description,state:"opened"===e.state?"open":e.state,url:e.web_url,head:e.source_branch,base:e.target_branch,createdAt:e.created_at,updatedAt:e.updated_at}))}parseProxyMethod(e){const n="string"==typeof e?e.toUpperCase():"GET";if("GET"===n||"POST"===n||"PUT"===n||"PATCH"===n||"DELETE"===n)return n;throw{status:400,message:`Unsupported proxy method: ${String(e)}`}}parseProxyPath(e){if("string"!=typeof e||0===e.length)throw{status:400,message:"Proxy path is required"};if(!e.startsWith("/"))throw{status:400,message:'Proxy path must start with "/"'};if(e.includes("://")||e.includes(".."))throw{status:400,message:"Proxy path contains invalid segments"};if(e.includes("?"))throw{status:400,message:"Proxy path must not contain query string; use payload.query"};return e}buildProxyQueryString(e){if(null==e)return"";if("object"!=typeof e||Array.isArray(e))throw{status:400,message:"Proxy query must be an object"};const n=new URLSearchParams;for(const[a,t]of Object.entries(e))if(null!=t)if(Array.isArray(t))for(const e of t){if("string"!=typeof e&&"number"!=typeof e&&"boolean"!=typeof e)throw{status:400,message:`Proxy query value for "${a}" is invalid`};n.append(a,String(e))}else{if("string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t)throw{status:400,message:`Proxy query value for "${a}" is invalid`};n.append(a,String(t))}return n.toString()}isProxyAllowed(e,n){return Cn.some(a=>a.method===e&&a.pattern.test(n))}async requestGitlabApi(e){const n=this.parseProxyMethod(e.method),a=this.parseProxyPath(e.path),t=this.buildProxyQueryString(e.query),s=t.length>0?`${a}?${t}`:a;if(!this.isProxyAllowed(n,a))throw{status:403,message:`Proxy path not allowed: ${n} ${a}`};return"GET"===n?await this.request(s,n):await this.request(s,n,e.body)}}function Rn(e){return async(n,a)=>{P.info(`[EVENT HANDLER] create-task: ${n.taskId}, agentType=${n.agentType}, agentId=${n.agentId}`),"task-message"===n.event?await e.workerManager.startWorker(n,"create-task"):P.error(`[EVENT HANDLER] create-task expects task-message, got ${n.event} for task ${n.taskId}`)}}function _n(e){return async(n,a)=>{P.debug(`[EVENT HANDLER] resume-task: ${n.taskId}, agentSessionId=${n.agentSessionId}`),await e.workerManager.startWorker(n,"resume-task")}}function Mn(e){return async n=>{P.info("[EVENT HANDLER] shutdown-machine received",n),e.requestShutdown("agentrix-app",n.reason)}}function $n(e){return async(n,a)=>{P.info(`[EVENT HANDLER] deploy-agent received: taskId=${n.taskId}, draftAgentId=${n.draftAgentId}, targetAgentId=${n.targetAgentId}, sourcePath=${n.sourcePath}`),await e.workerManager.startDeploymentWorker(n)}}function Dn(e){return async n=>{P.info(`[GITLAB PROXY] request received: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}, ttlMs=${n.ttlMs}, payloadKeys=${function(e){const n=Object.keys(e||{});return n.length>0?n.join(","):"-"}(n.payload)}`);const a=Date.now(),t=a=>{const t={eventId:n.requestId,requestId:n.requestId,machineId:e.machineId,...a};e.client?(e.client.send("daemon-gitlab-response",t),P.info(`[GITLAB PROXY] response sent: reqId=${n.requestId}, op=${n.operation}, success=${a.success}, executionMs=${a.executionTimeMs}`)):P.error(`[GITLAB PROXY] response dropped: reqId=${n.requestId}, op=${n.operation}, reason=socket-client-unavailable`)};try{const e=await D.getSecretKey();if(!e)return P.warn(`[GITLAB PROXY] machine secret key unavailable: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}`),void t({success:!1,errorCode:"PAT_MISSING",errorMessage:"Machine secret key not available",executionTimeMs:Date.now()-a});const s=En(n.gitServerId,e);if(!s)return P.warn(`[GITLAB PROXY] PAT missing: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}`),void t({success:!1,errorCode:"PAT_MISSING",errorMessage:`No PAT configured for git server ${n.gitServerId}`,executionTimeMs:Date.now()-a});const i=n.payload.apiUrl;if(!i)return P.warn(`[GITLAB PROXY] apiUrl missing in payload: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}`),void t({success:!1,errorCode:"PAT_MISSING",errorMessage:"GitLab API URL not provided in request",executionTimeMs:Date.now()-a});P.info(`[GITLAB PROXY] executing: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}, apiHost=${function(e){try{return new URL(e).host}catch{return"invalid-url"}}(i)}`);const o=new An(i,s,{requestId:n.requestId,gitServerId:n.gitServerId}),r=await o.executeOperation(n.operation,n.payload);P.info(`[GITLAB PROXY] execution succeeded: reqId=${n.requestId}, op=${n.operation}, summary=${function(e,n){if(Array.isArray(n))return`items=${n.length}`;if(n&&"object"==typeof n){const a=n;return"resolveGitAuthContext"===e?`authMode=${String(a.authMode??"unknown")}, hasPat=${Boolean(a.hasPat)}`:"number"in a||"state"in a?`number=${String(a.number??"-")}, state=${String(a.state??"-")}`:`keys=${Object.keys(a).join(",")||"-"}`}return"type="+typeof n}(n.operation,r)}`),t({success:!0,data:r,executionTimeMs:Date.now()-a})}catch(e){const s=e;let i="GITLAB_CONNECTIVITY_FAILED";401===s.status?i="PAT_INVALID":403===s.status?i="PAT_SCOPE_INSUFFICIENT":404===s.status&&(i="RESOURCE_NOT_FOUND");const o="string"==typeof s.message?s.message:"Unknown error",r="string"==typeof s.detail?function(e,n=300){return e.length<=n?e:`${e.slice(0,n)}...`}(s.detail):void 0,c="number"==typeof s.status?String(s.status):"unknown";P.error(`[GITLAB PROXY] execution failed: reqId=${n.requestId}, op=${n.operation}, errorCode=${i}, status=${c}, message=${o}${r?`, detail=${r}`:""}`),t({success:!1,errorCode:i,errorMessage:o,executionTimeMs:Date.now()-a})}}}const Pn=parseInt(process.env.MAX_WORKSPACE_FILE_SIZE_MB||"100",10);function On(e,n){if(!e)return;if("string"==typeof n)return void(e.sendMessage?e.sendMessage(n):e.send&&e.send(n));const a=Buffer.from(n);e.sendMessageBinary?e.sendMessageBinary(a):e.send&&e.send(a)}class jn{client;machineId;iceServers=[];sessions=new Map;rtcModule;peerConstructor;constructor(e,n){this.client=e,this.machineId=n;const a=we(import.meta.url);var t;this.rtcModule=a("node-datachannel"),this.peerConstructor=(t=this.rtcModule).RTCPeerConnection||t.PeerConnection||t.RTCConnection||t.PeerConnection,this.rtcModule.setDebugLevel?.("warning")}registerHandlers(){this.peerConstructor?(this.client.onLifecycle("connect",()=>{this.requestIceServers()}),this.client.onEvent("rtc-ice-servers-response",e=>this.handleIceServersResponse(e)),this.client.onEvent("machine-rtc-request",e=>this.handleRtcRequest(e)),this.client.onEvent("rtc-signal",e=>this.handleRtcSignal(e))):P.warn("[RTC] node-datachannel RTCPeerConnection not available")}shutdown(){this.sessions.forEach(e=>{e.peerConnection.close?.()}),this.sessions.clear()}requestIceServers(){this.client.send("rtc-ice-servers-request",{eventId:d()})}handleIceServersResponse(e){this.iceServers=function(e){const n=[];return e.forEach(e=>{Array.isArray(e.urls)?n.push(...e.urls):n.push(e.urls)}),n}(e.iceServers),P.info(`[RTC] Loaded ${this.iceServers.length} ICE servers`)}handleRtcRequest(e){if(!this.peerConstructor)return;const n=e.userId;if(!n)return void P.warn("[RTC] machine-rtc-request missing userId");const a=e.workspaceUserId||n,t=e.taskId;if(this.sessions.has(e.sessionId))return void this.sendMachineRtcResponse(e.sessionId,n,!0);const s=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers}),i={sessionId:e.sessionId,userId:n,workspaceUserId:a,allowedTaskId:t||void 0,peerConnection:s,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]};this.sessions.set(e.sessionId,i),this.registerPeerHandlers(i),this.sendMachineRtcResponse(e.sessionId,n,!0)}sendMachineRtcResponse(e,n,a,t){this.client.send("machine-rtc-response",{eventId:d(),machineId:this.machineId,sessionId:e,accepted:a,reason:t,userId:n,capabilities:{dataChannel:!0}})}handleRtcSignal(e){if(!this.peerConstructor)return;if("app"!==e.from)return;const n=e.userId;if(!n)return void P.warn("[RTC] rtc-signal missing userId");const a=e.workspaceUserId||n,t=e.taskId;let s=this.sessions.get(e.sessionId);if(!s){const i=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers});s={sessionId:e.sessionId,userId:n,workspaceUserId:a,allowedTaskId:t||void 0,peerConnection:i,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]},this.sessions.set(e.sessionId,s),this.registerPeerHandlers(s)}try{this.applyRemoteSignal(s,e.signal)}catch(e){P.warn("[RTC] Failed to apply remote signal",e)}}registerPeerHandlers(e){const{peerConnection:n}=e;n.onStateChange?.(n=>{P.info(`[RTC] Peer state (${e.sessionId}): ${n}`)}),n.onGatheringStateChange?.(n=>{P.info(`[RTC] ICE gathering (${e.sessionId}): ${n}`)}),n.onLocalDescription?.((n,a)=>{const t=function(e,n){return e&&"object"==typeof e&&"string"==typeof e.sdp?{sdp:e.sdp,type:e.type||n}:{sdp:String(e||""),type:n}}(n,a);this.client.send("rtc-signal",{eventId:d(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:t,userId:e.userId})}),n.onLocalCandidate?.((n,a,t)=>{const s=function(e,n,a){return"string"==typeof e?{candidate:e,sdpMid:n||"0",sdpMLineIndex:a??0}:e&&"string"==typeof e.candidate?{candidate:e.candidate,sdpMid:e.sdpMid||e.mid||n||"0",sdpMLineIndex:"number"==typeof e.sdpMLineIndex?e.sdpMLineIndex:a??0}:null}(n,a,t);s&&this.client.send("rtc-signal",{eventId:d(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:{candidate:s},userId:e.userId})}),n.onDataChannel?.(n=>{e.dataChannel=n,this.registerDataChannel(e,n)})}registerDataChannel(e,n){n.onOpen?.(()=>{P.info(`[RTC] Data channel open (${e.sessionId})`),e.lastActivity=Date.now(),On(n,JSON.stringify({v:1,type:"control.ready",channel:"control",requestId:`req-${e.sessionId}`,streamId:0,timestamp:(new Date).toISOString(),payload:{ok:!0}}))}),n.onClosed?.(()=>{P.warn(`[RTC] Data channel closed (${e.sessionId})`),e.peerConnection.close?.(),this.sessions.delete(e.sessionId)}),n.onError?.(n=>{P.error(`[RTC] Data channel error (${e.sessionId})`,n)}),n.onMessage?.(n=>{e.lastActivity=Date.now(),this.handleDataChannelMessage(e,n)})}handleDataChannelMessage(e,n){if(Buffer.isBuffer(n)||n instanceof Uint8Array){try{m(new Uint8Array(n))}catch(e){P.warn("[RTC] Received binary payload without handler")}return}let a=null;if("string"==typeof n?a=n:n&&"string"==typeof n.text&&(a=n.text),!a)return;let t=null;try{t=JSON.parse(a)}catch(e){return void P.warn("[RTC] Non-JSON message",a)}t&&"string"==typeof t.type&&"file.request"===t.type&&this.handleFileRequest(e,t).catch(e=>{P.error("[RTC] Failed to handle file request",e)})}async handleFileRequest(e,n){const a=n.payload;if(!a)return;if(a.userId!==e.workspaceUserId)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),error:{code:"unauthorized",message:"Unauthorized workspace access"}});if(e.allowedTaskId&&a.taskId!==e.allowedTaskId)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),error:{code:"unauthorized",message:"Unauthorized task access"}});const t=(s=a.userId,i=a.taskId,o=a.relativePath,D.resolveWorkspaceFilePath(s,i,o));var s,i,o;if(!ne.existsSync(t))return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),error:{code:"file_not_found",message:"File or directory not found"}});const r=await ne.promises.stat(t);if(!function(e,n){return!n||e.mtime.toISOString()!==n}(r,a.ifModifiedSince))return void this.sendControl(e,{v:1,type:"file.not_modified",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString()});if(r.isDirectory()||"directory"===a.entryType){const a=await ne.promises.readdir(t,{withFileTypes:!0}),s={entries:await Promise.all(a.map(async e=>{const n=de.join(t,e.name),a=await ne.promises.stat(n);return{name:e.name,type:e.isDirectory()?"directory":"file",size:a.size,modifiedAt:a.mtime.toISOString()}})),modifiedAt:r.mtime.toISOString()};return void this.sendControl(e,{v:1,type:"file.dir",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),payload:s})}const c=1024*(a.maxFileSizeMB??Pn)*1024;if(r.size>c)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),error:{code:"file_too_large",message:"File exceeds size limit"}});const p=wn.lookup(t)||"application/octet-stream",l={size:r.size,mimeType:"string"==typeof p?p:"application/octet-stream",modifiedAt:r.mtime.toISOString()};this.sendControl(e,{v:1,type:"file.meta",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),payload:l}),await this.sendFileChunks(e,n.streamId,t),this.sendControl(e,{v:1,type:"file.end",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),payload:{size:r.size}})}async sendFileChunks(e,n,a){const t=e.dataChannel;if(!t)return;const s=ne.createReadStream(a,{highWaterMark:65536});let i=0;await new Promise((e,a)=>{s.on("data",e=>{const a=g.Binary|(0===i?g.Start:0),s=Buffer.isBuffer(e)?e:Buffer.from(e),o=new Uint8Array(s.buffer,s.byteOffset,s.byteLength),r=h({streamId:n,seq:i,flags:a,payloadLength:o.length},o);On(t,r),i+=1}),s.on("end",()=>{if(i>0){const e=h({streamId:n,seq:i,flags:g.End|g.Binary,payloadLength:0},new Uint8Array);On(t,e)}e()}),s.on("error",e=>a(e))})}sendControl(e,n){const a=e.dataChannel;a&&On(a,JSON.stringify(n))}applyRemoteSignal(e,n){const{peerConnection:a}=e;if(n&&n.sdp&&n.type)return a.setRemoteDescription?.(n.sdp,n.type),e.remoteDescriptionSet=!0,e.pendingCandidates?.forEach(e=>{try{a.addRemoteCandidate?.(e.candidate,e.mid)}catch(e){P.warn("[RTC] Failed to add queued candidate",e)}}),void(e.pendingCandidates=[]);if(n&&n.candidate){const t=n.candidate,s="string"==typeof t?t:t&&"string"==typeof t.candidate?t.candidate:null,i=n.sdpMid||t?.sdpMid||t?.mid||"0";if(s){if(!e.remoteDescriptionSet)return void e.pendingCandidates?.push({candidate:s,mid:i});a.addRemoteCandidate?.(s,i)}}}}class Nn{client;context;rtcManager;constructor(e,n,a){const{machineId:t,...s}=e;this.client=new dn(s),this.context={machineId:t,workerManager:n,requestShutdown:a.requestShutdown,client:this.client},this.rtcManager=new jn(this.client,t),this.initHandlers(),this.rtcManager.registerHandlers()}connect(){return new Promise((e,n)=>{const a=setTimeout(()=>{n(new Error("Machine connection timeout after 30 seconds"))},3e4);this.client.onLifecycle("connect",()=>{clearTimeout(a),e()}),this.client.onLifecycle("connect_error",e=>{clearTimeout(a),n(e)}),this.client.connect()})}async disconnect(){this.client.connected&&await this.client.flush(5e3).catch(()=>{}),this.rtcManager.shutdown(),this.client.disconnect()}initHandlers(){const e={"create-task":Rn(n=this.context),"resume-task":_n(n),"deploy-agent":$n(n),"shutdown-machine":Mn(n),"workspace-file-request":Sn({client:n.client}),"daemon-gitlab-request":Dn(n)};var n;this.client.onEventWithAck("create-task",e["create-task"]),this.client.onEventWithAck("resume-task",e["resume-task"]),this.client.onEventWithAck("deploy-agent",e["deploy-agent"]),this.client.onEvent("shutdown-machine",e["shutdown-machine"]),this.client.onEvent("workspace-file-request",e["workspace-file-request"]),this.client.onEvent("daemon-gitlab-request",e["daemon-gitlab-request"])}}let qn=null;let Un=!1;async function Gn(){if(Un)P.info("[caffeinate] Already stopping, skipping");else if(qn&&!qn.killed){Un=!0,P.info(`[caffeinate] Stopping caffeinate process PID ${qn.pid}`);try{qn.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),qn&&!qn.killed&&qn.kill("SIGKILL"),qn=null,Un=!1}catch(e){P.info("[caffeinate] Error stopping caffeinate:",e),Un=!1}}}let Ln=!1;async function Fn(){try{const e=await Se(),n=[];for(const a of e){const e=a.cmd||"",t=a.name||"";if(!(t.includes("agentrix")||"node"===t&&(e.includes("agentrix-cli")||e.includes("dist/index.mjs"))||("MainThread"===t||t.includes("MainThread"))&&(e.includes("agentrix-cli")||e.includes("dist/index.mjs")||e.includes("agentrix.mjs"))||e.includes("agentrix.mjs")||e.includes("agentrix-cli")||e.includes("tsx")&&e.includes("src/index.ts")&&e.includes("agentrix-cli")))continue;if(a.pid===process.pid||a.pid===process.ppid)continue;let s="unknown";e.includes(" worker")?s="worker":e.includes(" upgrade-daemon")?s="upgrade-daemon":e.includes(" daemon")?s="daemon":e.includes("doctor")&&(s="doctor"),n.push({pid:a.pid,command:e||t,type:s})}return n}catch(e){return[]}}function Wn(e){try{return{available:!0,path:Ie(`which ${e}`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}}catch{return{available:!1}}}function Hn(){const e=Ee(),n=function(){const e=Wn("git"),n=Wn("claude"),a=Wn("codex");return[{name:"git",installed:e.available,required:!0,description:"Version control system (required for all tasks)",installCommand:"https://git-scm.com/downloads",path:e.path},{name:"claude",installed:n.available,required:!0,description:"Claude Code CLI (required for most features)",installCommand:"npm install -g @anthropic-ai/claude-code",path:n.path},{name:"codex",installed:a.available,required:!1,description:"Codex CLI (optional, for Codex tasks)",installCommand:"npm install -g @codex-ai/codex-cli",path:a.path}]}(),a=function(e){if("macos"===e){const e=Wn("rg");return[{name:"ripgrep",installed:e.available,required:!0,description:"Fast code search tool (required by sandbox)",installCommand:"brew install ripgrep",path:e.path}]}if("linux"===e){const e=Wn("bwrap"),n=Wn("socat");return[{name:"bubblewrap",installed:e.available,required:!0,description:"Sandboxing tool for Linux",installCommand:"sudo apt install bubblewrap # Debian/Ubuntu\nsudo yum install bubblewrap # RHEL/CentOS\nsudo pacman -S bubblewrap # Arch",path:e.path},{name:"socat",installed:n.available,required:!0,description:"Socket communication tool (required by sandbox)",installCommand:"sudo apt install socat # Debian/Ubuntu\nsudo yum install socat # RHEL/CentOS\nsudo pacman -S socat # Arch",path:n.path}]}return[]}(e),t=n.filter(e=>e.required&&!e.installed),s=a.filter(e=>e.required&&!e.installed);return{cli:n,sandbox:a,allSatisfied:0===t.length&&0===s.length,missingSandbox:s,missingCli:t}}function zn(){return{PWD:process.env.PWD,AGENTRIX_HOME_DIR:process.env.AGENTRIX_HOME_DIR,AGENTRIX_SERVER_URL:process.env.AGENTRIX_SERVER_URL,AGENTRIX_PROJECT_ROOT:process.env.AGENTRIX_PROJECT_ROOT,DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING:process.env.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING,NODE_ENV:process.env.NODE_ENV,DEBUG:process.env.DEBUG,workingDirectory:process.cwd(),processArgv:process.argv,agentrixDir:D.agentrixHomeDir,serverUrl:D.serverUrl,logsDir:D.getStatePaths().logsDir,processPid:process.pid,nodeVersion:process.version,platform:process.platform,arch:process.arch,user:process.env.USER,home:process.env.HOME,shell:process.env.SHELL,terminal:process.env.TERM}}async function Bn(e){if(e||(e="all"),console.log(s.bold.cyan("\n🩺 Agentrix CLI Doctor\n")),"all"===e){console.log(s.bold("📋 Basic Information")),console.log(`Agentrix CLI Version: ${s.green(j.version)}`),console.log(`Platform: ${s.green(process.platform)} ${process.arch}`),console.log(`Node.js Version: ${s.green(process.version)}`),console.log(""),console.log(s.bold("🔧 Daemon Spawn Diagnostics"));const e=O(),n=me(e,"bin","agentrix.mjs"),a=me(e,"dist","index.mjs");console.log(`Project Root: ${s.blue(e)}`),console.log(`Wrapper Script: ${s.blue(n)}`),console.log(`CLI Entrypoint: ${s.blue(a)}`),console.log(`Wrapper Exists: ${te(n)?s.green("✓ Yes"):s.red("❌ No")}`),console.log(`CLI Exists: ${te(a)?s.green("✓ Yes"):s.red("❌ No")}`),console.log(""),console.log(s.bold("⚙️ Configuration")),console.log(`Agentrix Home: ${s.blue(D.agentrixHomeDir)}`),console.log(`Server URL: ${s.blue(D.serverUrl)}`),console.log(`Logs Dir: ${s.blue(D.getStatePaths().logsDir)}`),console.log(s.bold("\n🌍 Environment Variables"));const t=zn();console.log(`AGENTRIX_HOME_DIR: ${t.AGENTRIX_HOME_DIR?s.green(t.AGENTRIX_HOME_DIR):s.gray("not set")}`),console.log(`AGENTRIX_SERVER_URL: ${t.AGENTRIX_SERVER_URL?s.green(t.AGENTRIX_SERVER_URL):s.gray("not set")}`),console.log(`DANGEROUSLY_LOG_TO_SERVER: ${t.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING?s.yellow("ENABLED"):s.gray("not set")}`),console.log(`DEBUG: ${t.DEBUG?s.green(t.DEBUG):s.gray("not set")}`),console.log(`NODE_ENV: ${t.NODE_ENV?s.green(t.NODE_ENV):s.gray("not set")}`),console.log(s.bold("\n🔐 Authentication"));try{await D.readCredentials()?console.log(s.green("✓ Authenticated (credentials found)")):console.log(s.yellow("⚠️ Not authenticated (no credentials)"))}catch(e){console.log(s.red("❌ Error reading credentials"))}!function(e=!1){const n=Hn(),a=Ee();console.log(s.bold("\n🔧 CLI Dependencies"));for(const a of n.cli)if(a.installed)console.log(s.green(`✓ ${a.name}`),s.gray(`- ${a.description}`)),e&&a.path&&console.log(s.gray(` Location: ${a.path}`));else{const e=a.required?s.red("❌"):s.yellow("⚠️");console.log(`${e} ${a.name}`,s.gray(`- ${a.description}`)),a.installCommand&&console.log(s.blue(` Install: ${a.installCommand}`))}if(n.sandbox.length>0){console.log(s.bold("\n🔒 Sandbox Dependencies")),console.log(s.gray(`Platform: ${a}`));for(const a of n.sandbox)a.installed?(console.log(s.green(`✓ ${a.name}`),s.gray(`- ${a.description}`)),e&&a.path&&console.log(s.gray(` Location: ${a.path}`))):(console.log(s.red(`❌ ${a.name}`),s.gray(`- ${a.description}`)),a.installCommand&&console.log(s.blue(` Install: ${a.installCommand}`)))}else console.log(s.bold("\n🔒 Sandbox Dependencies")),console.log(s.yellow(`⚠️ Platform ${a} not supported - sandbox will be disabled`));if(n.allSatisfied)return console.log(s.bold.green("\n✓ All required dependencies are installed")),!0;{console.log(s.bold.red("\n⚠️ Missing Required Dependencies"));const e=[...n.missingCli,...n.missingSandbox];for(const n of e)console.log(s.red(` • ${n.name}`));console.log(s.yellow("\nPlease install missing dependencies before starting the daemon."))}}(!0)}console.log(s.bold("\n🤖 Daemon Status"));try{const n=await sn(),a=await D.readDaemonState();if(n&&a?(console.log(s.green("✓ Daemon is running")),console.log(` PID: ${a.pid}`),console.log(` Started: ${new Date(a.startTime).toLocaleString()}`),console.log(` CLI Version: ${a.cliVersion}`),a.port&&console.log(` HTTP Port: ${a.port}`)):a&&!n?console.log(s.yellow("⚠️ Daemon state exists but process not running (stale)")):console.log(s.red("❌ Daemon is not running")),a){console.log(s.bold("\n📄 Daemon State:"));const e=D.getStatePaths();console.log(s.blue(`Location: ${e.daemonStateFile}`)),console.log(s.gray(JSON.stringify(a,null,2)))}const t=await Fn();if(t.length>0){console.log(s.bold("\n🔍 All Agentrix CLI Processes"));const e=t.reduce((e,n)=>(e[n.type]||(e[n.type]=[]),e[n.type].push(n),e),{});Object.entries(e).forEach(([e,n])=>{console.log(s.blue(`\n${{daemon:"🤖 Daemon","upgrade-daemon":"🔄 Upgrade Daemon",worker:"🔗 Workers",doctor:"🩺 Doctor",unknown:"❓ Unknown"}[e]||e}:`)),n.forEach(({pid:n,command:a})=>{const t=e.startsWith("dev")?s.cyan:e.includes("daemon")?s.blue:s.gray;console.log(` ${t(`PID ${n}`)}: ${s.gray(a)}`)})})}else console.log(s.red("❌ No agentrix processes found"));"all"===e&&t.length>1&&(console.log(s.bold("\n💡 Process Management")),console.log(s.gray("To clean up runaway processes: agentrix killall")))}catch(e){console.log(s.red("❌ Error checking daemon status"))}}let Kn=null;async function Vn(){const e=Zn(),n=function(e){try{return JSON.stringify(e)}catch{return""}}(e);if(Kn&&Kn.expiresAt>Date.now()&&Kn.overridesSignature===n)return Kn.openers;const a=Yn(e),t=[];for(const e of a){const n=e.isSupported();n&&t.push({id:e.id,label:e.label,kind:e.kind,method:e.method,urlTemplate:e.urlTemplate,supported:n})}return Kn={expiresAt:Date.now()+6048e5,openers:t,overridesSignature:n},t}function Xn(e){const n=process.platform;if("darwin"===n)return function(e){const n=Jn(e),a=[];if(n){const e=ia(n);a.push("-e",`set defaultLocation to POSIX file "${e}"`,"-e","set chosenFolder to choose folder default location defaultLocation")}else a.push("-e","set chosenFolder to choose folder");return a.push("-e","POSIX path of chosenFolder"),Qn(ta("osascript",a,{captureOutput:!0}))}(e);if("win32"===n)return function(e){const n=aa("powershell")?"powershell":aa("pwsh")?"pwsh":null;if(!n)throw new Error("PowerShell is required to pick a directory");const a=Jn(e),t=["Add-Type -AssemblyName System.Windows.Forms;","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;",a?`$dialog.SelectedPath = '${sa(a)}';`:"","$null = $dialog.ShowDialog();","$dialog.SelectedPath;"].filter(Boolean).join(" ");return Qn(ta(n,"powershell"===n?["-NoProfile","-STA","-Command",t]:["-NoProfile","-Sta","-Command",t],{captureOutput:!0}))}(e);if("linux"===n)return function(e){const n=Jn(e);if(aa("zenity")){const e=["--file-selection","--directory","--title=Select Folder"];if(n){const a=n.endsWith("/")?n:`${n}/`;e.push(`--filename=${a}`)}return Qn(ta("zenity",e,{captureOutput:!0}))}if(aa("kdialog")){const e=["--getexistingdirectory"];return n&&e.push(n),Qn(ta("kdialog",e,{captureOutput:!0}))}throw new Error("No supported directory picker is available")}(e);throw new Error("Directory picker is not supported on this platform")}function Yn(e){const n=process.platform,a=["Visual Studio Code","Visual Studio Code - Insiders"],t=["Cursor"],s=["IntelliJ IDEA","IntelliJ IDEA CE","IntelliJ IDEA Ultimate"],i=["WebStorm"],o=["PyCharm","PyCharm CE","PyCharm Professional"],r=[{id:"vscode",label:"VS Code",kind:"editor",method:"scheme",urlTemplate:"vscode://file/{path}?windowId=_blank",scheme:"vscode",macAppNames:a,isSupported:()=>ea("vscode",n,a)},{id:"cursor",label:"Cursor",kind:"editor",method:"scheme",urlTemplate:"cursor://file/{path}?windowId=_blank",scheme:"cursor",macAppNames:t,isSupported:()=>ea("cursor",n,t)},{id:"idea",label:"IntelliJ IDEA",kind:"ide",method:"scheme",urlTemplate:"idea://open?file={path}&newWindow=true",scheme:"idea",macAppNames:s,isSupported:()=>ea("idea",n,s)},{id:"pycharm",label:"PyCharm",kind:"ide",method:"scheme",urlTemplate:"pycharm://open?file={path}&newWindow=true",scheme:"pycharm",macAppNames:o,isSupported:()=>ea("pycharm",n,o)},{id:"webstorm",label:"WebStorm",kind:"ide",method:"scheme",urlTemplate:"webstorm://open?file={path}&newWindow=true",scheme:"webstorm",macAppNames:i,isSupported:()=>ea("webstorm",n,i)},{id:"file-manager",label:"darwin"===n?"Finder":"win32"===n?"Explorer":"Files",kind:"file-manager",method:"cli",isSupported:()=>function(e){return"darwin"===e?aa("open"):"win32"===e||"linux"===e&&(aa("xdg-open")||aa("gio"))}(n),open:e=>function(e,n){if("darwin"!==n){if("win32"!==n){if("linux"===n)return aa("xdg-open")?void ta("xdg-open",[e]):void ta("gio",["open",e]);throw new Error("File manager open is not supported on this platform")}ta("explorer",[e])}else ta("open",[e])}(e,n)},{id:"open-with",label:"Open With...",kind:"system",method:"cli",isSupported:()=>function(e){return"darwin"===e?aa("osascript"):"win32"===e?aa("powershell")||aa("pwsh"):"linux"===e&&aa("gio")}(n),open:e=>function(e,n){if("darwin"!==n)if("win32"!==n){if("linux"!==n)throw new Error("Open With is not supported on this platform");ta("gio",["open","--ask",e])}else ta(aa("powershell")?"powershell":"pwsh",["-NoProfile","-Command",`Start-Process -Verb OpenAs -FilePath '${sa(e)}'`]);else if(null===ta("osascript",["-e",`set targetPath to POSIX file "${ia(e)}"`,"-e","set appChoice to choose application","-e","tell appChoice to open targetPath"],{captureOutput:!0}))throw new Error("No application selected")}(e,n)}];return function(e,n,a){const t=a??Zn();return e.map(e=>{const a=t[e.id];if(!a)return e;if(!1===a.enabled)return{...e,isSupported:()=>!1};const s={...e,label:a.label??e.label,method:a.method??e.method,urlTemplate:a.urlTemplate??e.urlTemplate};if(a.command){const t=function(e){return e?Array.isArray(e)?e:[e]:[]}(a.appName??e.macAppNames);s.method="cli",s.isSupported=()=>function(e,n,a){return"darwin"===a&&n.length>0?n.some(e=>na(e)):ue.isAbsolute(e)||e.includes(ue.sep)?te(e):aa(e)}(a.command,t,n),s.open=e=>function(e,n,a){if(!ta(e,(n&&n.length>0?n:["{path}"]).map(e=>e.split("{path}").join(a))))throw new Error(`Command failed: ${e}`)}(a.command,a.args,e)}return s})}(r,n,e)}function Jn(e){if(!e)return;const n=e.replace(/^~(?=$|[\\/])/,X.homedir());if(te(n)){try{if(!ie(n).isDirectory())return}catch{return}return n}}function Qn(e){if(!e)return null;return e.trim()||null}function Zn(){try{const e=D.readSettings();if(!e||"object"!=typeof e)return{};const n=e.openersOverrides;return n&&"object"==typeof n?n:{}}catch(e){return P.warn("[OPENERS] Failed to read opener overrides",e),{}}}function ea(e,n,a){return"darwin"===n?function(e,n){if(aa("mdfind")){const n=ta("mdfind",[`kMDItemCFBundleURLSchemes == '${e}'`],{captureOutput:!0});if(n&&n.trim())return!0}if(aa("plutil")){const n=[ue.join(X.homedir(),"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"),"/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"];for(const a of n){if(!te(a))continue;const n=ta("plutil",["-extract","LSHandlers","json","-o","-",a],{captureOutput:!0});if(n)try{const a=JSON.parse(n);if(Array.isArray(a)&&a.some(n=>n.LSHandlerURLScheme?.toLowerCase()===e.toLowerCase()))return!0}catch(e){P.debug("[OPENERS] Failed to parse LaunchServices handlers",e)}}}return!!(n&&n.length>0)&&n.some(e=>na(e))}(e,a):"win32"===n?function(e){return aa("reg")&&(Boolean(ta("reg",["query",`HKCU\\Software\\Classes\\${e}`]))||Boolean(ta("reg",["query",`HKCR\\${e}`])))}(e):"linux"===n&&function(e){if(aa("xdg-settings")){const n=ta("xdg-settings",["get","default-url-scheme-handler",e],{captureOutput:!0});if(n&&n.trim()&&"null"!==n.trim())return!0}if(aa("gio")){const n=ta("gio",["mime",`x-scheme-handler/${e}`],{captureOutput:!0});if(n&&/Default application/.test(n))return!0}return!1}(e)}function na(e){return"darwin"===process.platform&&Boolean(ta("open",["-Ra",e]))}function aa(e){return"win32"===process.platform?Boolean(ta("where",[e])):Boolean(ta("sh",["-c",`command -v ${e}`]))}function ta(e,n,a){const t=$e(e,n,{encoding:a?.captureOutput?"utf8":void 0,stdio:a?.captureOutput?"pipe":"ignore",windowsHide:!0});if(0!==t.status){if(a?.captureOutput){const a="string"==typeof t.stderr?t.stderr.trim():"";a&&P.warn(`[OPENERS] Command failed: ${e} ${n.join(" ")}: ${a}`)}return null}return a?.captureOutput?t.stdout:"ok"}function sa(e){return e.replace(/'/g,"''")}function ia(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function oa(e,n){if(n){const a=e.startsWith(n)?e.slice(n.length).replace(/^\//,""):he(e);return me(n,"versions",a)}let a=ge(e),t=0;for(;t<10;){if(te(me(a,"agent.json"))){const n=e.slice(a.length).replace(/^\//,"");return me(a,"versions",n)}const n=ge(a);if(n===a)break;a=n,t++}const s=ge(e),i=he(e);return me(s,`.${i}.version`)}function ra(e,n){const a=oa(e,n);if(!te(a))return"0.0.0";try{return se(a,"utf-8").trim()}catch(e){return"0.0.0"}}function ca(e,a,t){try{const s=oa(e,t),i=ge(s);if(!te(i)){const{mkdirSync:e}=n("node:fs");e(i,{recursive:!0})}oe(s,a,"utf-8")}catch(e){}}function pa(e,n){const a=e.split(".").map(Number),t=n.split(".").map(Number);for(let e=0;e<3;e++){const n=a[e]||0,s=t[e]||0;if(n>s)return 1;if(n<s)return-1}return 0}function la(e,n,a){const t=ra(e,a),s=pa(n.metadata.version,t);if(!te(e)){const t=ge(e);if(!te(t)){const{mkdirSync:e}=ae;e(t,{recursive:!0})}return oe(e,n.content,"utf-8"),ca(e,n.metadata.version,a),{updated:!0,reason:"created"}}if(s<=0)return{updated:!1,reason:"up-to-date"};switch(n.metadata.updateStrategy){case"overwrite":return oe(e,n.content,"utf-8"),ca(e,n.metadata.version,a),{updated:!0,reason:"overwritten"};case"create-only":return{updated:!1,reason:"create-only"};case"notify-user":return{updated:!1,reason:"requires-user-approval"};default:return{updated:!1,reason:"unknown-strategy"}}}function da(e){te(e)||re(e,{recursive:!0})}function ua(e){return e.split("\\").join("/")}function ma(e){const n={};if(!te(e))return n;const a=t=>{const s=ce(t).sort();for(const i of s){const s=me(t,i);if(ie(s).isDirectory()){a(s);continue}if("versions.json"===i)continue;const o=ua(fe(e,s));n[o]=se(s,"utf-8")}};return a(e),n}function ga(){const e=ge(Pe(import.meta.url)),n=[me(e,"template"),me(e,"companion","template")];for(const e of n)if(te(e))return e;return n[0]}function ha(e){const n=ga(),a=me(n,"versions",`${e}.json`);if(!te(a))return{};try{const e=se(a,"utf-8");return JSON.parse(e)}catch(e){return console.warn(`[Companion] Failed to parse ${a}:`,e),{}}}async function fa(e){const n=D.agentrixAgentsHomeDir,a=me(n,"companion"),t=me(a,"claude");da(t),da(me(t,"memory")),da(me(t,"skills"));const{language:s,templates:i}=function(e){const n=function(e){const n=[e,process.env.AGENTRIX_COMPANION_TEMPLATE_LANGUAGE,process.env.LC_ALL,process.env.LC_MESSAGES,process.env.LANG];for(const e of n){if(!e)continue;const n=e.trim().toLowerCase();if(n){if(n.startsWith("zh"))return"zh-Hans";if(n.startsWith("en"))return"en"}}return"en"}(e),a=ga(),t=me(a,"common"),s=me(a,"languages",n),i=ma(t),o=ma(s),r=ha("common"),c=ha(n),p=[],l={version:"1.0.0",updateStrategy:"create-only"};for(const[e,n]of Object.entries(i))p.push({relativePath:e,content:n,metadata:r[e]||l});for(const[e,n]of Object.entries(o))p.push({relativePath:e,content:n,metadata:c[e]||l});if(0===p.length)throw new Error(`Companion template files are missing under ${a}`);return{language:n,templates:p}}(e?.preferredLanguage),o=[];for(const e of i){const n=la(me(a,e.relativePath),e,a);if(o.push({path:e.relativePath,updated:n.updated,reason:n.reason}),n.updated){const a="created"===n.reason?"Created":"Updated";console.log(`[Companion] ${a}: ${e.relativePath}`)}}const r=function(e,n){const a=[];for(const t of e){if("notify-user"!==t.metadata.updateStrategy)continue;const e=me(n,t.relativePath);if(!te(e))continue;const s=ra(e,n);pa(t.metadata.version,s)>0&&a.push({template:t,targetPath:e,currentVersion:s,newVersion:t.metadata.version})}return a}(i,a);if(r.length>0)try{const e=me(t,"UPGRADES.md"),n=function(e){return`# Upgrades Available\n\nThe following files have new versions available:\n\n${e.map(e=>`- **${e.template.metadata.description||e.template.relativePath}**: v${e.currentVersion} → v${e.newVersion}`).join("\n")}\n\n---\n\n**Shadow's Instructions:**\n\nWhen you detect this file:\n1. Send a reminder to the main companion using \`mcp__agentrix__send_reminder\`\n2. Content: "System upgrade detected. ${e.length} file(s) available."\n3. Reference this file path so main companion can read details\n4. Exit quietly\n\n**Main Companion's Instructions:**\n\nWhen you receive the upgrade reminder:\n1. Choose appropriate timing (don't interrupt user's work)\n2. Read this file to see what's new\n3. For each upgrade, read the corresponding \`.upgrade\` file\n4. Present to user naturally, explain benefits\n5. If user agrees: integrate the new content in your own voice\n6. Update version files using Write tool (create \`.filename.version\` with new version number)\n7. Delete \`.upgrade\` files when done\n8. Delete this file when all upgrades are handled\n`}(r);oe(e,n,"utf-8");for(const e of r){const n=`${e.targetPath}.upgrade`,a=`# Upgrade: ${e.template.metadata.description||e.template.relativePath}\n\n**Current Version**: v${e.currentVersion}\n**New Version**: v${e.newVersion}\n\n---\n\n## New Content\n\n${e.template.content}\n\n---\n\n## Integration Instructions\n\n1. Read the new content above\n2. Compare with your current \`${e.template.relativePath}\`\n3. Integrate the new features in your own voice\n4. Keep your existing customizations\n5. Use Write tool to update \`versions/${e.template.relativePath}\` with content: "${e.newVersion}"\n6. Delete this file when done\n`;oe(n,a,"utf-8")}console.log(`[Companion] Created UPGRADES.md with ${r.length} pending upgrade(s)`),console.log("[Companion] Shadow will notify main companion on next heartbeat")}catch(e){console.warn("[Companion] Failed to create upgrade files (permission denied?):",e instanceof Error?e.message:e),console.warn("[Companion] Upgrade detection will be skipped. Please check sandbox permissions for agents directory.")}return console.log(`[Companion] Language: ${s}`),{agentDir:a,homeDir:t}}function xa(e,n){const a=[],t=ce(e,{withFileTypes:!0});for(const s of t){if(".gitkeep"===s.name)continue;const t=me(e,s.name),i=ie(t),o=fe(n,t);a.push({name:s.name,path:o,size:i.size,modifiedAt:i.mtimeMs,isDirectory:s.isDirectory()}),s.isDirectory()&&a.push(...xa(t,n))}return a}function va({getChildren:e,stopSession:n,requestShutdown:a,registerSession:t,machineId:s}){return new Promise(i=>{const o=Ce({logger:!1});o.setValidatorCompiler(_e),o.setSerializerCompiler(Me);const r=o.withTypeProvider(),c=e=>{e.header("Access-Control-Allow-Origin","*"),e.header("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.header("Access-Control-Allow-Headers","Content-Type"),e.header("Access-Control-Allow-Private-Network","true")};r.post("/session-started",{schema:{body:Ae.object({sessionId:Ae.string(),metadata:Ae.any()}),response:{200:Ae.object({status:Ae.literal("ok")})}}},async e=>{const{sessionId:n,metadata:a}=e.body;return P.debug(`[CONTROL SERVER] Session started: ${n}`),t(n,a),{status:"ok"}}),r.options("/ping",async(e,n)=>(c(n),n.send())),r.get("/ping",{schema:{response:{200:Ae.object({status:Ae.literal("ok"),machineId:Ae.string(),timestamp:Ae.string()})}}},async(e,n)=>(c(n),{status:"ok",machineId:s,timestamp:(new Date).toISOString()})),r.options("/openers",async(e,n)=>(c(n),n.send())),r.get("/openers",{schema:{response:{200:Ae.object({openers:Ae.array(Ae.object({id:Ae.string(),label:Ae.string(),kind:Ae.enum(["system","file-manager","editor","ide"]),method:Ae.enum(["scheme","cli"]),urlTemplate:Ae.string().optional(),supported:Ae.boolean()}))})}}},async(e,n)=>(c(n),{openers:await Vn()})),r.options("/open",async(e,n)=>(c(n),n.send())),r.options("/pick-directory",async(e,n)=>(c(n),n.send())),r.post("/open",{schema:{body:Ae.object({path:Ae.string(),openerId:Ae.string(),userId:Ae.string().optional(),taskId:Ae.string().optional()}),response:{200:Ae.object({success:Ae.boolean(),error:Ae.string().optional()})}}},async(e,n)=>{c(n);const{path:a,openerId:t,userId:s,taskId:i}=e.body;return await async function({openerId:e,targetPath:n,userId:a,taskId:t}){const s=Yn(Zn()).find(n=>n.id===e);if(!s)return{success:!1,error:"Unknown openerId"};if("cli"!==s.method||!s.open)return{success:!1,error:"Opener is not executable by CLI"};if(!s.isSupported())return{success:!1,error:"Opener is not supported on this system"};let i;try{i=function(e,n,a){const t=ue.resolve(e);if(!ue.isAbsolute(t))throw new Error("Path must be absolute");if(!ie(t).isDirectory())throw new Error("Path must be a directory");if(n&&a){const e=D.getTaskCwd(n,a);if(e&&!function(e,n){const a=ue.relative(n,e);return""===a||!a.startsWith("..")&&!ue.isAbsolute(a)}(t,ue.resolve(e)))throw new Error("Path is outside the task workspace")}return t}(n,a,t)}catch(e){return{success:!1,error:e instanceof Error?e.message:"Invalid path"}}try{return s.open(i),{success:!0}}catch(e){const n=e instanceof Error?e.message:"Failed to open path";return P.warn(`[OPENERS] Failed to open path: ${n}`),{success:!1,error:n}}}({openerId:t,targetPath:a,userId:s,taskId:i})}),r.post("/pick-directory",{schema:{body:Ae.object({defaultPath:Ae.string().optional()}),response:{200:Ae.object({path:Ae.string().nullable(),error:Ae.string().optional()})}}},async(e,n)=>{c(n);try{return{path:Xn(e.body.defaultPath)??null}}catch(e){return{path:null,error:e instanceof Error?e.message:"Failed to pick directory"}}}),r.post("/companion/ensure",{schema:{body:Ae.object({preferredLanguage:Ae.enum(["en","zh-Hans"]).nullable().optional()}).optional(),response:{200:Ae.object({agentDir:Ae.string(),homeDir:Ae.string()})}}},async e=>await fa({preferredLanguage:e.body?.preferredLanguage})),r.get("/companion/workspace",{schema:{response:{200:Ae.object({files:Ae.array(Ae.object({name:Ae.string(),path:Ae.string(),size:Ae.number(),modifiedAt:Ae.number(),isDirectory:Ae.boolean()}))})}}},async()=>{const{homeDir:e}=await fa();return te(e)?{files:xa(e,e)}:{files:[]}}),r.get("/companion/file",{schema:{querystring:Ae.object({path:Ae.string()}),response:{200:Ae.object({content:Ae.string()}),404:Ae.object({error:Ae.string()})}}},async(e,n)=>{const{homeDir:a}=await fa(),t=xe(me(a,e.query.path));return t.startsWith(a)&&te(t)?{content:se(t,"utf-8")}:n.code(404).send({error:"File not found"})}),r.put("/companion/file",{schema:{body:Ae.object({path:Ae.string(),content:Ae.string()}),response:{200:Ae.object({success:Ae.boolean()}),400:Ae.object({error:Ae.string()})}}},async(e,n)=>{const{homeDir:a}=await fa(),t=xe(me(a,e.body.path));return t.startsWith(a)?(re(ge(t),{recursive:!0}),oe(t,e.body.content,"utf-8"),{success:!0}):n.code(400).send({error:"Invalid path"})}),r.get("/companion/config",{schema:{response:{200:Ae.object({heartbeatIntervalMs:Ae.number(),heartbeatEnabled:Ae.boolean()})}}},async()=>{const{homeDir:e}=await fa(),n=me(e,"state.json");let a=9e5,t=!0;if(te(n))try{const e=JSON.parse(se(n,"utf-8"));"number"==typeof e.heartbeatIntervalMs&&(a=e.heartbeatIntervalMs),"boolean"==typeof e.heartbeatEnabled&&(t=e.heartbeatEnabled)}catch{}return{heartbeatIntervalMs:a,heartbeatEnabled:t}}),r.put("/companion/config",{schema:{body:Ae.object({heartbeatIntervalMs:Ae.number().optional(),heartbeatEnabled:Ae.boolean().optional()}),response:{200:Ae.object({success:Ae.boolean()})}}},async e=>{const{homeDir:n}=await fa(),a=me(n,"state.json");let t={};if(te(a))try{t=JSON.parse(se(a,"utf-8"))}catch{}const{heartbeatIntervalMs:s,heartbeatEnabled:i}=e.body;return void 0!==s&&(t.heartbeatIntervalMs=s),void 0!==i&&(t.heartbeatEnabled=i),re(ge(a),{recursive:!0}),oe(a,JSON.stringify(t,null,2),"utf-8"),{success:!0}}),r.post("/list",{schema:{response:{200:Ae.object({children:Ae.array(Ae.object({startedBy:Ae.string(),taskId:Ae.string(),pid:Ae.number()}))})}}},async()=>({children:e().filter(e=>void 0!==e.taskId).map(e=>({startedBy:e.startedBy,taskId:e.taskId,pid:e.pid}))})),r.post("/stop-session",{schema:{body:Ae.object({sessionId:Ae.string()}),response:{200:Ae.object({success:Ae.boolean()})}}},async e=>{const{sessionId:a}=e.body;return P.debug(`[CONTROL SERVER] Stop session request: ${a}`),{success:n(a)}}),r.post("/stop",{schema:{response:{200:Ae.object({status:Ae.string()})}}},async()=>(P.debug("[CONTROL SERVER] Stop daemon request received"),setTimeout(()=>{P.debug("[CONTROL SERVER] Triggering daemon shutdown"),a()},50),{status:"stopping"}));const p=e=>new Promise((n,a)=>{o.listen({port:e,host:"127.0.0.1"},(e,t)=>{e?a(e):n(t)})});(async()=>{let e;try{e=await p(30624)}catch(n){const a=n?.code;if("EADDRINUSE"!==a&&"EACCES"!==a)throw P.info("[CONTROL SERVER] Failed to start:",n),n;P.info(`[CONTROL SERVER] Port 30624 unavailable (${a??"error"}), falling back to dynamic port`),e=await p(0)}const n=parseInt(e.split(":").pop());P.info(`[CONTROL SERVER] Started on port ${n}`),i({port:n,stop:async()=>{await o.close(),P.info("[CONTROL SERVER] Server stopped")}})})().catch(e=>{throw P.info("[CONTROL SERVER] Failed to start:",e),e})})}function ba(e,n={}){const a=O(),t=me(a,"dist","index.mjs"),s=["--no-warnings","--no-deprecation",t,...e];if(!te(t)){const e=`Entrypoint ${t} does not exist`;throw P.debug(`[SPAWN Agentrix CLI] ${e}`),new Error(e)}return ke(process.execPath,s,n)}const ya=[{version:1,fileName:"001_init.sql"}];function wa(e){var n;return function(e,n){const a=new je(e),t=new Oe;a.pragma("journal_mode = WAL"),function(e){const n=function(){const e=V(Ne(import.meta.url)),n=[K(e,"migrations"),K(process.cwd(),"dist","migrations"),K(process.cwd(),"src","worker","history","migrations")];for(const e of n)if(H(e))return e;throw new Error(`Task history migrations directory not found at ${n[0]}`)}(),a=e.pragma("user_version",{simple:!0}),t=function(e,n){const a=K(e,n);return W(a,"utf8")}(n,ya[0].fileName);e.exec(t),a<ya[0].version&&e.pragma(`user_version = ${ya[0].version}`)}(a);const s=a.prepare("\n INSERT OR IGNORE INTO task_message (\n event_id,\n task_id,\n sender_type,\n sender_id,\n sender_name,\n message,\n created_at\n ) VALUES (\n @eventId,\n @taskId,\n @senderType,\n @senderId,\n @senderName,\n @message,\n @createdAt\n );\n "),i=a.prepare("SELECT local_sequence FROM task_message WHERE event_id = ?"),o=a.prepare("\n INSERT OR IGNORE INTO task_event (\n event_id,\n task_id,\n chat_id,\n sequence,\n event_type,\n event_data,\n created_at\n ) VALUES (\n @eventId,\n @taskId,\n @chatId,\n @sequence,\n @eventType,\n @eventData,\n @createdAt\n );\n "),r=a.prepare("\n UPDATE task_event\n SET sequence = ?\n WHERE event_id = ? AND (sequence IS NULL OR sequence < ?)\n "),c=a.prepare("\n SELECT * FROM task_event\n WHERE sequence > ? AND event_type = 'task-message'\n ORDER BY sequence ASC\n LIMIT ?\n "),p=a.prepare("\n SELECT 1 as has_row\n FROM task_event\n WHERE sequence > ? AND event_type = 'task-message'\n LIMIT 1\n "),l=a.prepare("\n SELECT * FROM task_message\n ORDER BY local_sequence DESC\n LIMIT ?\n "),u=a.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence ASC\n LIMIT ?\n "),m=a.prepare("\n SELECT * FROM task_message\n WHERE local_sequence < ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),g=a.prepare("\n SELECT 1 as has_row\n FROM task_message\n WHERE local_sequence < ?\n LIMIT 1\n "),h=a.prepare("\n SELECT 1 as has_row\n FROM task_message\n WHERE local_sequence > ?\n LIMIT 1\n "),f=a.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),x=a.prepare("\n SELECT agent_id, session_id, last_sequence\n FROM task_agent_session\n "),v=a.prepare("\n INSERT INTO task_agent_session (agent_id, task_id, session_id, last_sequence, updated_at)\n VALUES (?, ?, ?, NULL, ?)\n ON CONFLICT(agent_id) DO UPDATE SET\n task_id = excluded.task_id,\n session_id = excluded.session_id,\n updated_at = excluded.updated_at\n "),b=a.prepare("\n INSERT INTO task_agent_session (agent_id, task_id, session_id, last_sequence, updated_at)\n VALUES (?, ?, '__pending__', ?, ?)\n ON CONFLICT(agent_id) DO UPDATE SET\n task_id = excluded.task_id,\n last_sequence = CASE\n WHEN task_agent_session.last_sequence IS NULL OR task_agent_session.last_sequence < excluded.last_sequence\n THEN excluded.last_sequence\n ELSE task_agent_session.last_sequence\n END,\n updated_at = excluded.updated_at\n ");return{saveMessage:e=>{const a=e.eventId??d(),o=(new Date).toISOString();s.run({eventId:a,taskId:n,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,message:JSON.stringify(e.message),createdAt:o});const r=i.get(a),c=r?.local_sequence??null;return null!==c&&t.emit("message-saved",{eventId:a}),{eventId:a,localSequence:c}},saveTaskEvent:e=>{const n=e.eventId??d(),a=(new Date).toISOString(),t={...e.eventData,eventId:n};return o.run({eventId:n,taskId:e.taskId,chatId:e.chatId,sequence:e.sequence,eventType:e.eventType,eventData:JSON.stringify(t),createdAt:a}),n},updateTaskEventSequence:(e,n)=>{r.run(n,e,n)},pageTaskEventsAfter:(e,n)=>{const a=c.all(e,n).map(Ia),t=a.at(-1)?.sequence??null;return{data:a,hasMore:null!==t&&Boolean(p.get(t))}},getLatestTaskEvent:e=>{if(0===e.length)return null;const n=e.map(()=>"?").join(","),t=a.prepare(`\n SELECT * FROM task_event\n WHERE event_type IN (${n})\n ORDER BY created_at DESC, rowid DESC\n LIMIT 1\n `).get(...e);return t?Ia(t):null},pageRecentMessages:e=>{const n=l.all(e).map(ka).reverse(),a=n[0]?.localSequence??null;return{data:n,hasMore:!!a&&Boolean(g.get(a))}},pageMessagesAfter:(e,n)=>{const a=u.all(e,n).map(ka),t=a.at(-1)?.localSequence??null;return{data:a,hasMore:!!t&&Boolean(h.get(t))}},pageMessagesBefore:(e,n)=>{const a=m.all(e,n).map(ka).reverse(),t=a[0]?.localSequence??null;return{data:a,hasMore:!!t&&Boolean(g.get(t))}},pageRecentMessagesAfter:(e,n)=>{const a=f.all(e,n).map(ka).reverse(),t=a[0]?.localSequence??null;return{data:a,hasMore:!!t&&Boolean(g.get(t))}},getAgentSessions:()=>{const e=x.all(),n=new Map;for(const a of e)n.set(a.agent_id,a.session_id);return n},getAgentLastSequences:()=>{const e=x.all(),n=new Map;for(const a of e)n.set(a.agent_id,a.last_sequence);return n},upsertAgentSession:(e,a)=>{v.run(e,n,a,(new Date).toISOString())},updateAgentLastSequence:(e,a)=>{b.run(e,n,a,(new Date).toISOString())},on:(e,n)=>{t.on(e,n)},off:(e,n)=>{t.off(e,n)},close:()=>{t.removeAllListeners(),a.close()}}}((n=e.dataDir,K(n,"data.bin")),e.taskId)}function ka(e){const n=JSON.parse(e.message);return{localSequence:e.local_sequence,eventId:e.event_id,senderType:e.sender_type,senderId:e.sender_id,senderName:e.sender_name,message:n,createdAt:e.created_at}}function Ia(e){const n=JSON.parse(e.event_data);return{eventId:e.event_id,taskId:e.task_id,chatId:e.chat_id,sequence:e.sequence??null,eventType:e.event_type,eventData:n,createdAt:e.created_at}}class Sa{pidToTrackedSession;pidToAwaiter;taskToStartPromise;sandboxPool;constructor(e){this.pidToTrackedSession=new Map,this.pidToAwaiter=new Map,this.taskToStartPromise=new Map,this.sandboxPool=e||null}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}getAliveSessionByTaskId(e){for(const[n,a]of this.pidToTrackedSession.entries())if(a.taskId===e){if(this.isProcessAlive(n))return a;this.pidToTrackedSession.delete(n)}}getCurrentSessions(){return Array.from(this.pidToTrackedSession.values())}getSessionByPid(e){return this.pidToTrackedSession.get(e)}registerTaskWorker(e,n){const a=n.pid;if(!a)return void P.warn(`[SESSION] Missing PID for task ${e}`);P.info(`[SESSION] Registered task ${e}, PID: ${a}`);const t=this.pidToTrackedSession.get(a);if(t&&t.taskId===e){const e=this.pidToAwaiter.get(a);e&&(this.pidToAwaiter.delete(a),e(t))}else if(!t){const n={startedBy:"cli",taskId:e,pid:a};this.pidToTrackedSession.set(a,n)}}async decryptTaskMessage(e){if(!e.dataEncryptionKey)return;const n=await D.getSecretKey();if(!n)return;const a=l(p(e.dataEncryptionKey),n);if(!a)return void P.warn("[SESSION] Failed to decrypt data encryption key");if(e.dataEncryptionKey=i(a),"task-message"!==e.event)return;const t=e.eventData;if(!t.encryptedMessage)return;const s=f(t.encryptedMessage,a);s?e.eventData={...t,message:s,encryptedMessage:void 0}:P.warn("[SESSION] Failed to decrypt task message")}persistCreateTaskStart(e){const n=wa({dataDir:D.resolveDataDir(e.userId,e.taskId),taskId:e.taskId});try{const a=e.eventData;n.saveTaskEvent({eventType:e.event,eventId:a.eventId,eventData:a,taskId:e.taskId,chatId:e.chatId,sequence:a.sequence??0}),a.message&&n.saveMessage({eventId:a.eventId,message:a.message,senderType:a.senderType,senderId:a.senderId,senderName:a.senderName})}finally{n.close()}}persistResumeTaskStart(e){const n=wa({dataDir:D.resolveDataDir(e.userId,e.taskId),taskId:e.taskId}),a=e.eventData.sequence;if(null==a)throw new Error(`Missing resume sequence for task ${e.taskId}`);try{const t=e.eventData;n.saveTaskEvent({eventType:e.event,eventId:t.eventId,eventData:t,taskId:e.taskId,chatId:e.chatId,sequence:a}),t.message&&n.saveMessage({eventId:t.eventId,message:t.message,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName})}finally{n.close()}}trackWorkerProcess(e,n){const a={startedBy:"daemon",pid:n.pid,childProcess:n,taskId:e.taskId};this.pidToTrackedSession.set(n.pid,a),n.on("exit",(a,t)=>{this.pidToTrackedSession.delete(n.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId)}),n.on("error",a=>{this.pidToTrackedSession.delete(n.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId)})}async startWorker(e,n){const a={eventId:d(),status:"success",opCode:e.eventId};await this.decryptTaskMessage(e),D.writeTaskInput(e),"create-task"===n?this.persistCreateTaskStart(e):this.persistResumeTaskStart(e);const t=this.taskToStartPromise.get(e.taskId);if(t)return P.info(`[SESSION] Task ${e.taskId} is already starting, skip duplicate ${n}`),t;const s=this.startWorkerInternal(e,n,a).finally(()=>{this.taskToStartPromise.get(e.taskId)===s&&this.taskToStartPromise.delete(e.taskId)});return this.taskToStartPromise.set(e.taskId,s),s}async startWorkerInternal(e,n,a){const t=this.getAliveSessionByTaskId(e.taskId);if(t)return P.info(`[SESSION] Task ${e.taskId} already has worker PID ${t.pid}, skip duplicate ${n}`),a.message=`Worker already running (PID ${t.pid})`,a;const s=D.resolveProjectCWD(e.userCwd,e.userId,e.taskId),i=["worker","--type",e.agentType||"claude","--started-by","daemon","--task-id",e.taskId,"--user-id",e.userId,"--idle-timeout","120"];let o;if(this.sandboxPool?.isEnabled())try{if(!await this.sandboxPool.createWorkerSandbox(e.taskId,e.userId,s))throw new Error("Failed to create sandbox instance");const{projectPath:n}=await import("./logger-CdDc0Esc.mjs").then(function(e){return e.d}),{join:a}=await import("path"),t=["--no-warnings","--no-deprecation",a(n(),"dist","index.mjs"),...i],r=`"${process.execPath}" ${t.map(e=>`"${e}"`).join(" ")}`,c=await this.sandboxPool.wrapWorkerCommand(e.taskId,r);P.debug(`[SESSION] Sandboxed command for task ${e.taskId}: ${c}`),o=ke(c,{shell:!0,cwd:s,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}}),P.info(`[SESSION] Worker started with sandbox, PID: ${o.pid}`)}catch(n){return P.error(`[SESSION] Failed to setup sandbox for task ${e.taskId}:`,n),a.status="failed",a.message=`Sandbox setup failed: ${n instanceof Error?n.message:String(n)}`,a}else o=ba(i,{cwd:s,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}}),P.info(`[SESSION] Worker started without sandbox, PID: ${o.pid}`);if(process.env.DEBUG&&(o.stdout?.on("data",e=>{P.debug(`[Daemon] worker stdout: ${e.toString()}`)}),o.stderr?.on("data",e=>{P.debug(`[Daemon] worker stderr: ${e.toString()}`)})),!o.pid)return a.status="failed",a.message="Failed to start worker - no PID",a;P.info(`[SESSION] Worker started, PID: ${o.pid}`),this.trackWorkerProcess(e,o);const[r,c]=function(e){let n,a;const t=new Promise(t=>{n=e=>{clearTimeout(a),t(e)},a=setTimeout(()=>{t(e.onTimeout())},e.timeoutMs)});return[t,n,()=>clearTimeout(a)]}({timeoutMs:15e3,onTimeout:()=>(this.pidToAwaiter.delete(o.pid),a.status="failed",a.message=`Worker timeout (PID ${o.pid})`,a)});return this.pidToAwaiter.set(o.pid,()=>{c(a)}),r}stopSession(e){for(const[n,a]of this.pidToTrackedSession.entries())if(a.taskId===e){try{(a.childProcess?a.childProcess:{kill:e=>process.kill(n,e)}).kill("SIGTERM"),P.info(`[SESSION] Task ${e} stopped`)}catch(n){P.warn(`[SESSION] Failed to stop task ${e}:`,n)}return this.pidToTrackedSession.delete(n),!0}return P.warn(`[SESSION] Task ${e} not found`),!1}pruneStaleSessions(){for(const[e,n]of this.pidToTrackedSession.entries())try{process.kill(e,0)}catch(n){this.pidToTrackedSession.delete(e)}}shutdown(){P.info("[SESSION] Shutting down all sessions");for(const[e,n]of this.pidToTrackedSession.entries())try{"daemon"===n.startedBy&&n.childProcess?n.childProcess.kill("SIGTERM"):process.kill(e,"SIGTERM")}catch(n){P.warn(`[SESSION] Failed to stop PID ${e}:`,n)}this.pidToTrackedSession.clear(),this.pidToAwaiter.clear()}async startDeploymentWorker(e){const n={eventId:d(),status:"success",opCode:e.eventId};D.writeTaskInput(e);try{const a=ba(["worker","--type","deployment","--started-by","daemon","--task-id",e.taskId,"--user-id",e.userId,"--idle-timeout","10"],{cwd:process.cwd(),detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}});if(process.env.DEBUG&&(a.stdout?.on("data",e=>{P.debug(`[Deployment] worker stdout: ${e.toString()}`)}),a.stderr?.on("data",e=>{P.debug(`[Deployment] worker stderr: ${e.toString()}`)})),!a.pid)return n.status="failed",n.message="Failed to start deployment worker - no PID",n;P.info(`[SESSION] Deployment worker started, PID: ${a.pid}`);const t={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(t,a),n}catch(e){return n.status="failed",n.message=`Failed to start deployment worker: ${e instanceof Error?e.message:String(e)}`,n}}}class Ta{networkManager=null;workerSandboxes=new Map;settings=null;platform;constructor(){this.platform=Ee()}async initialize(e){if(this.settings=e,!e.enabled)return P.info("[SANDBOX] Sandbox disabled via settings"),!1;if(!Ue(this.platform))return P.warn("[SANDBOX] Platform not supported, sandbox disabled"),!1;try{const n={allowedDomains:[new URL(D.serverUrl).hostname,...e.network.allowedDomains],deniedDomains:e.network.deniedDomains,allowLocalBinding:!1};return this.networkManager=new Ge,await this.networkManager.initialize(n),P.info("[SANDBOX] Sandbox pool initialized successfully"),!0}catch(e){throw P.error("[SANDBOX] Failed to initialize:",e),e}}async createWorkerSandbox(e,n,a){if(!this.networkManager||!this.settings?.enabled)return null;try{const t=D.resolveUserWorkSpaceDir(n),s=D.getStatePaths().logsDir,i=this.settings.filesystem||{},o=this.settings.env||{},r={...i,allowWrite:[...i.allowWrite||[],t,a,s]};if("linux"===this.platform&&i.allowRead){const e=B.dirname(process.execPath);r.allowRead=[...i.allowRead,e]}const c={filesystem:r,env:o},p=new Le(this.networkManager,c);return this.workerSandboxes.set(e,p),P.info(`[SANDBOX] Created sandbox for task ${e}`),p}catch(n){return P.error(`[SANDBOX] Failed to create sandbox for task ${e}:`,n),null}}async wrapWorkerCommand(e,n){const a=this.workerSandboxes.get(e);if(!a)throw new Error(`No sandbox found for task ${e}`);const t=await a.wrapWithSandbox(n);return P.debug(`[SANDBOX] Wrapped command for task ${e}`),t}disposeWorkerSandbox(e){const n=this.workerSandboxes.get(e);n&&(n.dispose(),this.workerSandboxes.delete(e),P.debug(`[SANDBOX] Disposed sandbox for task ${e}`))}async shutdown(){P.info("[SANDBOX] Shutting down sandbox pool");for(const[e,n]of this.workerSandboxes.entries())n.dispose(),P.debug(`[SANDBOX] Disposed sandbox for task ${e}`);this.workerSandboxes.clear(),this.networkManager&&(await this.networkManager.shutdown(),this.networkManager=null,P.info("[SANDBOX] Network manager shutdown complete"))}isEnabled(){return!0===this.settings?.enabled}}class Ea{constructor(e,n){this.client=e,this.machineId=n;const a=D.agentrixAgentsHomeDir,t=me(a,"companion","claude");this.stateFilePath=me(t,"state.json")}timer=null;initialDelay=null;intervalMs=9e5;enabled=!0;heartbeatTaskId=null;companionState=null;stateFilePath;start(){this.loadState(),this.companionState?P.info(`[COMPANION SCHEDULER] Ready: agent=${this.companionState.agentId}, chatId=${this.companionState.chatId}`):P.warn("[COMPANION SCHEDULER] No state.json found (companion not registered yet), will keep checking"),P.info(`[COMPANION SCHEDULER] Starting with interval ${this.intervalMs}ms`),this.initialDelay=setTimeout(()=>{this.initialDelay=null,this.tick(),this.scheduleNext()},6e4)}stop(){this.initialDelay&&(clearTimeout(this.initialDelay),this.initialDelay=null),this.timer&&(clearTimeout(this.timer),this.timer=null),P.info("[COMPANION SCHEDULER] Stopped")}scheduleNext(){this.timer=setTimeout(()=>{this.tick(),this.scheduleNext()},this.intervalMs)}setHeartbeatTaskId(e){this.heartbeatTaskId=e,this.saveStateField("heartbeatTaskId",e)}clearHeartbeatTaskId(){this.heartbeatTaskId=null,this.saveStateField("heartbeatTaskId",void 0),P.info("[COMPANION SCHEDULER] Cleared heartbeat task ID")}loadState(){try{if(te(this.stateFilePath)){this.companionState=JSON.parse(se(this.stateFilePath,"utf-8"));const e=this.companionState?.heartbeatIntervalMs??9e5;e!==this.intervalMs&&(P.info(`[COMPANION SCHEDULER] Interval changed: ${this.intervalMs}ms → ${e}ms`),this.intervalMs=e),this.enabled=this.companionState?.heartbeatEnabled??!0,this.heartbeatTaskId=this.companionState?.heartbeatTaskId??null,P.info(`[COMPANION SCHEDULER] Loaded state: agentId=${this.companionState?.agentId}, chatId=${this.companionState?.chatId??"none"}, enabled=${this.enabled}, interval=${this.intervalMs}ms, taskId=${this.heartbeatTaskId??"none"}`)}}catch(e){P.warn("[COMPANION SCHEDULER] Failed to load state.json",e)}}saveStateField(e,n){try{let a={};te(this.stateFilePath)&&(a=JSON.parse(se(this.stateFilePath,"utf-8"))),void 0===n?delete a[e]:a[e]=n;const t=ge(this.stateFilePath);te(t)||re(t,{recursive:!0}),oe(this.stateFilePath,JSON.stringify(a,null,2),"utf-8"),P.debug(`[COMPANION SCHEDULER] Saved state field: ${e}=${n??"removed"}`)}catch(n){P.warn(`[COMPANION SCHEDULER] Failed to save state field: ${e}`,n)}}tick(){if(this.loadState(),!this.companionState)return void P.debug("[COMPANION SCHEDULER] Still no state.json, skipping heartbeat");if(!this.enabled)return void P.debug("[COMPANION SCHEDULER] Heartbeat disabled, skipping");const e=this.companionState;this.heartbeatTaskId?(P.debug(`[COMPANION SCHEDULER] Sending heartbeat to existing task ${this.heartbeatTaskId}`),this.client.send("task-message",{eventId:d(),taskId:this.heartbeatTaskId,chatId:e.chatId,from:"machine",message:{type:"companion_heartbeat",timestamp:(new Date).toISOString()},senderType:"system",senderId:"system",senderName:"system"})):(P.debug("[COMPANION SCHEDULER] Requesting new heartbeat task"),this.client.send("request-companion-heartbeat",{eventId:d(),machineId:e.machineId,agentId:e.agentId,chatId:e.chatId,userId:e.userId,timestamp:(new Date).toISOString()}))}}async function Ca(){Object.assign(P,N({type:"daemon"}));const{requestShutdown:e,shutdownPromise:n}=function(){const{processType:e,onShutdownRequest:n}={processType:"daemon"},a=`[${e.toUpperCase()}]`;let t;const s=new Promise(e=>{t=(t,s)=>{P.info(`${a} Requesting shutdown (source: ${t}, errorMessage: ${s})`),n&&n(t,s),setTimeout(()=>process.exit(1),1e3),e({source:t,errorMessage:s})}}),i=e=>{process.on(e,()=>{t("os-signal")})};return i("SIGINT"),i("SIGTERM"),process.on("uncaughtException",e=>{P.info(`${a} FATAL: Uncaught exception`,e),P.info(`${a} Stack trace: ${e.stack}`),t("exception",e.message)}),process.on("unhandledRejection",e=>{P.info(`${a} FATAL: Unhandled promise rejection`,e);const n=e instanceof Error?e:new Error(`Unhandled promise rejection: ${e}`);P.info(`${a} Stack trace: ${n.stack}`),t("exception",n.message)}),process.on("exit",e=>{P.info(`${a} Process exiting with code: ${e}`)}),{requestShutdown:t,shutdownPromise:s}}();console.log("[DAEMON RUN] Starting daemon process..."),P.debug("[DAEMON RUN] Environment",zn()),await on()&&(console.log("Daemon already running..."),process.exit(0));let a=await D.acquireDaemonLock(5,200);for(;!a;)await cn(),a=await D.acquireDaemonLock(5,200),a||(P.debug("[DAEMON RUN] cannot acquire daemon lock..."),process.exit(1));try{(function(){if(D.disableCaffeinate)return P.debug("[caffeinate] Caffeinate disabled via AGENTRIX_DISABLE_CAFFEINATE environment variable"),!1;if("darwin"!==process.platform)return P.debug("[caffeinate] Not on macOS, skipping caffeinate"),!1;if(qn&&!qn.killed)return P.debug("[caffeinate] Caffeinate already running"),!0;try{return qn=ke("caffeinate",["-im"],{stdio:"ignore",detached:!1}),qn.on("error",e=>{P.debug("[caffeinate] Error starting caffeinate:",e),qn=null}),qn.on("exit",(e,n)=>{P.debug(`[caffeinate] Process exited with code ${e}, signal ${n}`),qn=null}),P.info(`[caffeinate] Started with PID ${qn.pid}`),function(){if(Ln)return;Ln=!0;const e=()=>{Gn()};process.on("exit",e),process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGUSR1",e),process.on("SIGUSR2",e),process.on("uncaughtException",n=>{P.debug("[caffeinate] Uncaught exception, cleaning up:",n),e()}),process.on("unhandledRejection",(n,a)=>{P.debug("[caffeinate] Unhandled rejection, cleaning up:",n),e()})}(),!0}catch(e){return P.info("[caffeinate] Failed to start caffeinate:",e),!1}})()&&P.debug("[DAEMON RUN] Sleep prevention enabled");const t=await pn();P.debug("[DAEMON RUN] Auth and machine setup complete");const s=new Ta;await s.initialize(D.getSandboxSettings());const i=new Sa(s),{port:o,stop:r}=await va({getChildren:()=>i.getCurrentSessions(),stopSession:e=>i.stopSession(e),requestShutdown:()=>e("agentrix-cli"),registerSession:(e,n)=>i.registerTaskWorker(e,n),machineId:t.machineId});try{await Vn(),P.debug("[DAEMON RUN] Openers detected")}catch(e){P.warn("[DAEMON RUN] Failed to detect openers",e)}const c={pid:process.pid,port:o,startTime:(new Date).toLocaleString(),cliVersion:j.version,logPath:q({type:"daemon"})};D.writeDaemonState(c),P.debug("[DAEMON RUN] Daemon state written");const p=new Nn({machineId:t.machineId,serverUrl:D.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:x(t.token,t.machineId),keepAliveConfig:{intervalMs:2e4,event:"machine-alive",payloadGenerator:()=>({eventId:d(),machineId:t.machineId,timestamp:Date.now().toString(),controlPort:o})},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...n)=>P.debug(`[DAEMON SOCKET] ${e}`,...n)},i,{requestShutdown:e});await p.connect(),P.info("[DAEMON RUN] Machine client connected to server");const l=new Ea(p.client,t.machineId);l.start(),p.client.onEvent("companion-heartbeat-response",e=>{e?.taskId&&l.setHeartbeatTaskId(e.taskId)});const u=async(e,n)=>{l.stop(),await p.disconnect(),await r(),await s.shutdown(),await rn(),await Gn(),await D.releaseDaemonLock(a),P.info("[DAEMON RUN] Cleanup completed, exiting process"),process.exit(0)};P.info("[DAEMON RUN] Daemon started successfully, waiting for shutdown request");const m=await n;await u(m.source,m.errorMessage)}catch(e){P.info("[DAEMON RUN][FATAL] Failed somewhere unexpectedly - exiting with code 1",e),process.exit(1)}}const Aa={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".ico":"image/x-icon",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".json":"application/json",".xml":"application/xml",".html":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".rar":"application/vnd.rar",".mp3":"audio/mpeg",".mp4":"video/mp4",".wav":"audio/wav",".avi":"video/x-msvideo"};async function Ra(e,n,a=!1){try{const t=function(e){try{const n=new URL(e),a=ve(n.pathname);if(a)return a;const t=n.searchParams.get("filename")||n.searchParams.get("name")||n.searchParams.get("file");if(t){const e=ve(t);if(e)return e}return""}catch{return""}}(e)||"";let s;if(a)try{const n=new URL(e).pathname,a=he(n);s=a&&ve(a)?a:`${M()}${t||".dat"}`}catch{s=`${M()}${t||".dat"}`}else s=`${M()}${t||".dat"}`;const i=me(n,s),o=await fetch(e);if(!o.ok)throw new Error(`Failed to download file: ${o.status} ${o.statusText}`);if(!o.body)throw new Error("Response body is null");const r=o.headers.get("content-type"),c=r?.split(";")[0].trim()||function(e){const n=e.toLowerCase();return Aa[n]||"application/octet-stream"}(t),p=o.body,l=pe(i);return await Fe(p,l),{filePath:i,mimeType:c,filename:s}}catch(n){throw new Error(`Failed to download file from ${e}: ${n instanceof Error?n.message:String(n)}`)}}const _a={senderType:"system",senderId:"system",senderName:"system"};class Ma{client;context;historyDb;constructor(e,n){const{taskId:a,userId:t,machineId:s,cwd:i,chatId:o,...r}=e,c=i.endsWith("/")?i:`${i}/`;this.client=new dn(r),this.context={taskId:a,chatId:o,userId:t,machineId:s,cwd:c,stopTask:n.stopTask,shouldPersistTaskMessage:n.shouldPersistTaskMessage,onTaskMessage:n.onTaskMessage,onTaskInfoUpdate:n.onTaskInfoUpdate,onWorkerStatusRequest:n.onWorkerStatusRequest,onSubTaskResultUpdated:n.onSubTaskResultUpdated,onGitPush:n.onGitPush,dataEncryptionKey:e.dataEncryptionKey},this.historyDb=n.historyDb,this.initHandlers()}connect(){return new Promise((e,n)=>{const a=setTimeout(()=>{n(new Error("Worker connection timeout after 10 seconds"))},1e4);this.client.onLifecycle("connect",()=>{clearTimeout(a),e()}),this.client.onLifecycle("connect_error",e=>{clearTimeout(a),n(e)}),this.client.connect()})}async disconnect(){this.client.connected&&await this.client.flush(5e3).catch(()=>{}),this.client.disconnect()}sendTaskMessage(e,n,a){const t=d();return this.historyDb.saveMessage({eventId:t,message:n,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}),this.sendTaskEvent(e,n,a),t}sendWorkerInitializing(){const e={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),cwd:this.context.cwd};this.client.send("worker-initializing",e)}sendWorkerInitialized(){const e={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),cwd:this.context.cwd};this.client.send("worker-initialized",e)}sendWorkerReady(e){const n={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),...void 0!==e&&{duration:e}};this.client.send("worker-ready",n)}sendWorkRunning(e){const n={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),activeAgents:e};this.client.send("worker-running",n)}sendWorkerExit(e){const n={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),reason:e};this.client.send("worker-exit",n)}async sendErrorMessageAndExit(e){this.sendSystemErrorMessage(e),await this.client.flush(2e3),this.sendWorkerExit("error"),await this.disconnect()}sendSystemErrorMessage(e,n){const a={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:`System Error\n\n${e}`,metadata:{messageType:"system_error"}}]}};this.sendTaskEvent(_a,a,{groupId:n?.groupId})}sendAssistantMessage(e,n){const a={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:e}]}};this.sendTaskEvent(_a,a,{groupId:n?.groupId})}sendAskUser(e,n,a){return this.sendTaskMessage(e,{type:"ask_user",questions:n},{groupId:a?.groupId})}sendAskUserResponse(e,n){return this.sendTaskMessage(_a,n,{opCode:e})}sendTaskEvent(e,n,a){const{eventId:t,opCode:s,artifacts:i,navigateToTaskId:o}=a||{},r=t??d(),c={eventId:r,taskId:this.context.taskId,chatId:this.context.chatId,from:"worker",messageType:n.type,message:n,encryptedMessage:void 0,opCode:s,groupId:a?.groupId,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,artifacts:i,navigateToTaskId:o};if(this.historyDb.saveTaskEvent({eventType:"task-message",eventId:r,eventData:c,taskId:this.context.taskId,chatId:this.context.chatId,sequence:"number"==typeof c.sequence?c.sequence:null}),this.context.dataEncryptionKey){const e=v(n,this.context.dataEncryptionKey);c.message=void 0,c.encryptedMessage=e}return this.client.send("task-message",c),r}sendUpdateTaskAgentSessionId(e){const n={eventId:d(),taskId:this.context.taskId,agentSessionId:e,cwd:this.context.cwd};this.client.send("update-task-agent-session-id",n)}sendChangeTaskTitle(e){const n={eventId:d(),taskId:this.context.taskId,title:e};this.client.send("change-task-title",n),P.info(`[AGENT] Title changed to: ${e}`)}sendUpdateAgentInfo(e,n){const a={eventId:d(),taskId:this.context.taskId,agentId:e,...n};this.client.send("update-agent-info",a),P.info(`[AGENT] Agent info updated: ${JSON.stringify(n)}`)}sendResetTaskSession(){const e={eventId:d(),taskId:this.context.taskId};this.client.send("reset-task-session",e),P.info(`[AGENT] Session reset requested for task ${this.context.taskId}`)}async sendMergeRequest(e,n){const a={eventId:d(),taskId:this.context.taskId,summary:e,description:n};P.info(`[MERGE] Sending merge-request event for task ${this.context.taskId}`);const t=await this.client.sendWithAck("merge-request",a);if(!t.success)throw new Error(`Failed to create pull request: ${t.error||"Unknown error"}`);return P.info(`[MERGE] Pull request created: #${t.data.pullRequestNumber}`),{pullRequestNumber:t.data.pullRequestNumber,pullRequestUrl:t.data.pullRequestUrl}}async sendMergePr(){const e={eventId:d(),taskId:this.context.taskId,mergeMethod:"squash"};return P.info(`[MERGE-PR] Sending merge-pr event for task ${this.context.taskId}`),await this.client.sendWithAck("merge-pr",e)}associateRepository(e,n,a,t){const s={eventId:d(),taskId:this.context.taskId,gitServerHost:e,owner:n,repo:a,remoteUrl:t};P.info(`[REPO] Sending repository association request: ${e}/${n}/${a}`),this.client.send("associate-repo",s)}async dispatchTaskMessage(e){await this.context.onTaskMessage(e)}initHandlers(){const e=(n=this.context,a=this.historyDb,{"cancel-task":async e=>{e.taskId===n.taskId&&(P.info(`[WORKER] Task ${n.taskId} cancelled`),await n.stopTask())},"stop-task":async e=>{e.taskId===n.taskId&&(P.info(`[WORKER] Task ${n.taskId} stopped: ${e.reason||"no reason"}`),await n.stopTask())},"task-message":async e=>{if(e.taskId!==n.taskId)return;let t=e.message??null;if(!t&&e.encryptedMessage&&n.dataEncryptionKey&&(t=f(e.encryptedMessage,n.dataEncryptionKey)??null),!t)return;const s={senderType:e.senderType,senderId:e.senderId,senderName:e.senderName};if(n.attachmentsDir&&b(t)&&(t=await async function(e,n){const{attachmentsDir:a,log:t}=n;if(!Array.isArray(e.message.content))return e;const s=await Promise.all(e.message.content.map(async e=>"image"===e.type&&"url"===e.source?.type&&e.source?.url?async function(e,n){try{n?.("info","IMAGE",`Downloading image from: ${e.source.url}`);const a=await fetch(e.source.url);if(!a.ok)return n?.("error","IMAGE",`Failed to download image: ${a.statusText}`),e;const t=await a.arrayBuffer(),s=Buffer.from(t),i=s.toString("base64");let o=a.headers.get("content-type")||"image/jpeg";if(!o.startsWith("image/")){const n=e.source.url.toLowerCase();o=n.endsWith(".png")?"image/png":n.endsWith(".gif")?"image/gif":n.endsWith(".webp")?"image/webp":"image/jpeg"}return n?.("info","IMAGE",`Image downloaded and converted to base64 (${o}, ${Math.round(s.length/1024)}KB)`),{type:"image",source:{type:"base64",media_type:o,data:i}}}catch(a){return n?.("error","IMAGE",`Error processing image: ${a}`),e}}(e,t):"document"===e.type&&"url"===e.source?.type&&e.source?.url?async function(e,n,a){try{const t=e.source.url;a?.("info","DOCUMENT",`Downloading document from: ${t}`);const{filePath:s,mimeType:i,filename:o}=await Ra(t,n,!0);return a?.("info","DOCUMENT",`Document downloaded to: ${s}`),{type:"text",text:`Document: ${s}\nTitle: ${e.title||o}\nType: ${i}`}}catch(n){return a?.("error","DOCUMENT",`Error processing document: ${n}`),e}}(e,a,t):e));return{...e,message:{...e.message,content:s}}}(t,{attachmentsDir:n.attachmentsDir,log:n.logger})),n.shouldPersistTaskMessage&&!await n.shouldPersistTaskMessage(t,s))return void P.debug(`[WORKER] Dropping incoming task-message before persistence: eventId=${e.eventId}`);const i={...e,message:t,encryptedMessage:void 0,chatId:e.chatId??n.chatId};a.saveTaskEvent({eventType:"task-message",eventId:e.eventId,eventData:i,taskId:n.taskId,chatId:e.chatId??n.chatId,sequence:e.sequence??null}),a.saveMessage({eventId:e.eventId,message:t,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}),n.onTaskMessage&&await n.onTaskMessage(t,s)},"task-info-update":async e=>{e.taskId===n.taskId&&n.onTaskInfoUpdate&&await n.onTaskInfoUpdate(e)},"worker-status-request":async e=>{e.taskId===n.taskId&&n.onWorkerStatusRequest&&await n.onWorkerStatusRequest(e)},"sub-task-result-updated":async e=>{e.parentTaskId===n.taskId&&n.onSubTaskResultUpdated&&await n.onSubTaskResultUpdated(e)}});var n,a;this.client.onEvent("cancel-task",e["cancel-task"]),this.client.onEvent("stop-task",e["stop-task"]),this.client.onEvent("task-message",e["task-message"]),this.client.onEvent("task-info-update",e["task-info-update"]),this.client.onEvent("worker-status-request",e["worker-status-request"]),this.client.onEvent("sub-task-result-updated",e["sub-task-result-updated"]),this.client.onEvent("event-ack",e=>{const n=e.data?.sequence;void 0!==e.opCode&&"number"==typeof n&&this.historyDb.updateTaskEventSequence(e.opCode,n)})}}class $a{logger;socketClient;taskId;userId;chatId;rootTaskId;parentTaskId;workingDirectory;taskAgents;serverUrl;taskDataKey;constructor(e){this.logger=e.logger,this.socketClient=e.socketClient,this.taskId=e.taskId,this.userId=e.userId,this.chatId=e.chatId,this.rootTaskId=e.rootTaskId,this.parentTaskId=e.parentTaskId,this.workingDirectory=e.workingDirectory,this.taskAgents=e.taskAgents,this.serverUrl=e.serverUrl,this.taskDataKey=e.taskDataKey}async call(e,n,a){const t=d();try{const s=await this.socketClient.sendWithAck("rpc-call",{eventId:t,taskId:this.taskId,method:e,path:n,query:a?.query,body:a?.body});if(!s.success){const a=s.error||{code:"unknown",message:"Unknown error"};throw new Error(`RPC ${e} ${n} failed: ${a.message} (${a.code})`)}return s.data}catch(a){throw new Error(`RPC ${e} ${n} error: ${a.message}`)}}log(e){this.logger.info(e)}getWorkspace(){return this.workingDirectory}getUserId(){return this.userId}getTaskId(){return this.taskId}getChatId(){return this.chatId}getRootTaskId(){return this.rootTaskId}getParentTaskId(){return this.parentTaskId}getTaskAgents(){return this.taskAgents}async createDraftAgent(e){return this.call("POST","/v1/draft-agent",{body:{...e,userId:this.userId,taskId:this.taskId}})}async updateDraftAgent(e,n){return this.call("PATCH",`/v1/draft-agent/${e}`,{body:n})}async startSubTask(e){const n={userId:this.userId,chatId:this.chatId,agentId:e.agentId,parentTaskId:this.taskId,customTitle:e.title,cwd:e.cwd,forceUserCwd:e.forceUserCwd};return this.taskDataKey?n.encryptedMessage=v(e.message,this.taskDataKey):n.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:n})).taskId}}async startIndependentTask(e){const n={userId:this.userId,chatId:this.chatId,agentId:e.agentId,sourceTaskId:this.taskId,customTitle:e.title,cwd:e.cwd,forceUserCwd:e.forceUserCwd,autoNavigate:e.autoNavigate};return this.taskDataKey?n.encryptedMessage=v(e.message,this.taskDataKey):n.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:n})).taskId}}async startGroupTask(e){const n={userId:this.userId,chatId:this.chatId,parentTaskId:this.taskId,customTitle:e.title,todos:e.todos};return this.taskDataKey?n.encryptedMessage=v(e.message,this.taskDataKey):n.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:n})).taskId}}async sendMessage(e){await this.call("POST",`/v1/tasks/${e.taskId}/send-message`,{body:{message:e.message,target:e.target,fromTaskId:this.taskId,senderType:"agent",senderId:this.taskId,senderName:"agent"}})}async showModal(e){await this.call("POST",`/v1/tasks/${e.taskId}/show-modal`,{body:{modalName:e.modalName,modalData:e.modalData}})}async getTaskSession(e){return this.call("GET",`/v1/tasks/${e}/session`)}async findSubTaskByAgent(e){const n=await this.call("GET","/v1/tasks/find-by-agent",{query:{parentTaskId:this.taskId,agentId:e}});return n.taskId?{taskId:n.taskId}:null}async listSubTasks(){return(await this.call("GET","/v1/tasks/sub-tasks",{query:{parentTaskId:this.taskId}})).tasks}async listTasks(e){return(await this.call("GET","/v1/tasks/recent",{query:{chatId:this.chatId,...e?.limit&&{limit:e.limit},...e?.status&&{status:e.status}}})).tasks}async listAgents(){return this.call("GET","/v1/user-agents")}async uploadFile(e){this.logger.info("[Agent-Context] Uploading file...");const n=await L.promises.stat(e.path);this.logger.info("[Agent-Context] file stats");const a=n.size,t=e.contentType||wn.lookup(e.name)||"application/octet-stream",s=(await this.call("POST","/v1/files/upload-urls",{body:{count:1}})).files[0],i=s.url;this.logger.info(`[Agent-Context] FileUploadUrl: ${i}`);const o=await L.promises.readFile(e.path),r=await fetch(i,{method:"PUT",headers:{"Content-Type":t},body:o});if(!r.ok)throw new Error(`Failed to upload file to S3: ${r.status} ${r.statusText}`);let c;return await this.call("POST","/v1/files/confirm-upload",{body:{fileId:s.id,name:e.name,size:a,contentType:t,visibility:e.visibility||"private"}}),c="public"===e.visibility?`${this.serverUrl}/v1/files/public/${s.id}`:i.split("?")[0],{fileId:s.id,name:e.name,size:a,contentType:t,url:c}}}function Da(e,n){const a=e.split("\n");return a.length<=n?e:a.slice(0,n).join("\n")+"..."}function Pa(e,n){let a=e.resultMessage;if(0===a.result.trim().length&&e.encryptedResultMessage&&n){const t=f(e.encryptedResultMessage,n);t&&"result"===t.type&&(a={type:"result",result:"result"in t?t.result:"",is_error:t.is_error})}const t={...e,resultMessage:{...a,result:Da(a.result,3)}};let s=`<sub-task-result-updated>\n${JSON.stringify(t,null,2)}\n</sub-task-result-updated>`;return s+=a.result.trim().length>0?'\n<system-reminder>The result is already shown to user as a card. Just acknowledge briefly (e.g., "Done!"). Only elaborate if error or needs user action.</system-reminder>':"\n<system-reminder>The sub-task result was empty. You can use reply_to_sub_task to ask it to continue, retry, or resend the result.</system-reminder>",{type:"user",message:{role:"user",content:s}}}function Oa(){const e=new Set;return{filter(n){const a=n;if(!a.message||!a.message.content||"string"==typeof a.message.content)return n;const t=a.message.content.filter(n=>!("tool_result"===n.type&&e.has(n.tool_use_id)||"user"===a.type&&"tool_result"!==n.type));return 0===t.length?null:(a.message.content=t,a)},clear(){e.clear()}}}function ja(e){const n=Fa(e);return n?{type:"user",message:{role:"user",content:[{type:"text",text:`<msg ${qa({seq:n.seq.toString(),at:n.at,senderType:n.senderType??void 0,senderId:n.senderId??void 0,senderName:n.senderName??void 0})}>${n.text}</msg>\n`},...n.nonTextBlocks]},parent_tool_use_id:null,session_id:""}:null}function Na(e){const n=Fa(e);return n?`<msg ${qa({seq:n.seq.toString(),at:n.at,senderType:n.senderType??void 0,senderId:n.senderId??void 0,senderName:n.senderName??void 0})}>\n${n.text}\n</msg>`:null}function qa(e){return Object.entries(e).filter(([,e])=>void 0!==e&&""!==e).map(([e,n])=>`${e}="${function(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}(n)}"`).join(" ")}function Ua(e){const n=[];for(const a of e){const e=Na(a);e&&n.push(e)}return n.join("\n")}function Ga(e){return`Ask user: ${e.questions.map((e,n)=>{const a=e.options?.map(e=>e.label).filter(Boolean),t=a&&a.length>0?` options: ${a.join(", ")}`:"";return`Q${n+1}[${e.header}] ${e.question}${t}`}).join(" | ")}`}function La(e){return`Ask user response:${e.status?` status=${e.status}`:""}${e.reason?` reason=${e.reason}`:""} answers: ${e.answers?.length?e.answers.join(", "):"no answers"}`}function Fa(e){const{text:n,nonTextBlocks:a}=(t=e.message,y(t)?{text:Ga(t),nonTextBlocks:[]}:w(t)?{text:La(t),nonTextBlocks:[]}:k(t)?function(e){switch(e.type){case"user":case"assistant":return function(e){if("string"==typeof e)return{text:e,nonTextBlocks:[]};if(Array.isArray(e)){const n=[],a=[];for(const t of e)"text"!==t.type||"string"!=typeof t.text?a.push(t):n.push(t.text);return{text:n.join("\n"),nonTextBlocks:a}}return{text:"",nonTextBlocks:[]}}(e.message.content);case"result":if("success"===e.subtype)return{text:e.result,nonTextBlocks:[]}}return{text:"",nonTextBlocks:[]}}(t):{text:"",nonTextBlocks:[]});var t;return n?{seq:e.localSequence,at:e.createdAt,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,text:n,nonTextBlocks:a}:null}function Wa({workClient:e}){return We("change_title","Change the session title to better describe what you are working on.\n\n## When to Use\n- Call it at the start of a session to set a descriptive title\n- Call it again when the title becomes outdated or too generic\n\nGood titles help users find conversations later.",{title:Ae.string().describe("New title for the task")},async n=>(e.sendChangeTaskTitle(n.title),{content:[{type:"text",text:`Task title updated to: ${n.title}`}]}))}function Ha({agentContext:e,log:n}){return We("emit_to_task","Send follow-up instructions to a running or failed sub-task.\nUse this when the sub-task needs clarification, hit an error, or the user has new requirements.",{taskId:Ae.string().describe("Sub-task ID to send follow-up instructions to"),instructions:Ae.string().describe("Additional instructions for the sub-task")},async a=>{try{return await e.sendMessage({taskId:a.taskId,message:{type:"user",message:{role:"user",content:a.instructions}},target:"agent"}),{content:[{type:"text",text:`Sent follow-up instructions to sub-task ${a.taskId}.`}]}}catch(e){return n("error","TASK",`Failed to send follow-up to sub-task ${a.taskId}:`,e),{content:[{type:"text",text:`Failed to send follow-up to sub-task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function za({historyDb:e}){return We("get_task_history","Retrieve earlier task history stored locally for additional context.",{sequence:Ae.number().int().describe("Return messages before this local sequence (exclusive)."),limit:Ae.number().int().min(1).max(50).default(20).describe("Maximum number of messages to return.")},async n=>{const a=n.limit??20,t=e.pageMessagesBefore(n.sequence,a);return 0===t.data.length?{content:[{type:"text",text:"No earlier messages found."}]}:{content:[{type:"text",text:Ua(t.data)}]}})}function Ba({agentContext:e}){return We("get_task_agents","List the agents available for the current task and return taskAgents info.",{},async()=>{const n=e.getTaskAgents();return n.length?{content:[{type:"text",text:JSON.stringify(n,null,2)}]}:{content:[{type:"text",text:"No task agents available."}]}})}function Ka({agentContext:e,log:n}){return We("list_sub_task","List direct sub tasks for the current task with taskId, title, and cwd.",{},async()=>{try{const n=await e.listSubTasks();return n.length?{content:[{type:"text",text:JSON.stringify(n,null,2)}]}:{content:[{type:"text",text:"No sub tasks found."}]}}catch(e){return n("error","TASK","Failed to list sub tasks:",e),{content:[{type:"text",text:`Failed to list sub tasks: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Va({agentContext:e,agentId:n,log:a,setPendingNavigateTaskId:t}){return We("create_task","Delegate a task to an agent for execution.\n\n**Modes**:\n- Sub-task (default): Creates under current task, linked via parentTaskId.\n- Independent (independent=true): Creates a top-level task with no parent binding. Optionally set autoNavigate=true to auto-switch the user's App UI to the new task.\n\nIf agentId is provided, delegates to that specific agent. Otherwise, creates a task for yourself.\nAlways provide a concise task title in \"title\".\nThe task runs asynchronously - you'll be notified when complete via <sub-task-result-updated> message.\nUse for: multi-step implementations, analysis, code reviews, or any work that takes >30 seconds.\nAfter calling this tool, continue responding to user - don't wait for task completion.",{agentId:Ae.string().optional().describe('Target agent ID (e.g., "agent-poster-generator"). If not provided, uses current agent.'),title:Ae.string().min(1).max(200).describe("Task title for the agent to use (required)"),instructions:Ae.string().describe("Detailed instructions for the agent. Be specific about what needs to be done."),briefSummary:Ae.string().describe('One-line summary shown to user immediately (e.g., "Creating login page")'),cwd:Ae.string().optional().describe("Working directory for the task. Pass your current cwd when the sub-task needs to read/write the same project files as you. If omitted, a new isolated workspace is created (scoped by taskId)."),useWorktree:Ae.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place)."),independent:Ae.boolean().optional().describe("Create as independent top-level task (no parent). Defaults to false (sub-task mode)."),autoNavigate:Ae.boolean().optional().describe("Auto-switch App UI to this task after creation. Only works with independent=true. Defaults to false.")},async s=>{try{if(s.autoNavigate&&!s.independent)return{content:[{type:"text",text:"Error: autoNavigate can only be used with independent=true"}],isError:!0};const i=s.agentId||n;let o;return s.independent?(o=await e.startIndependentTask({agentId:i,message:{type:"user",message:{role:"user",content:s.instructions}},title:s.title,cwd:s.cwd,forceUserCwd:!s.useWorktree,autoNavigate:s.autoNavigate}),s.autoNavigate&&t(o.taskId),a("info","TASK",`Created independent task ${o.taskId} for agent ${i} (autoNavigate: ${s.autoNavigate??!1})`)):(o=await e.startSubTask({agentId:i,message:{type:"user",message:{role:"user",content:s.instructions}},title:s.title,cwd:s.cwd,forceUserCwd:!s.useWorktree}),a("info","TASK",`Created sub-task ${o.taskId} for agent ${i}`)),{content:[{type:"text",text:`🚀 Task created: ${o.taskId}\n${s.agentId?`Agent: ${i}\n`:""}${s.independent?"Mode: Independent\n":""}Summary: ${s.briefSummary}\n\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return a("error","TASK","Failed to create task:",e),{content:[{type:"text",text:`Failed to create task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Xa({agentContext:e,log:n}){return We("create_solo_task","Create a single-agent async task in group chat.\n\n## When to Use (sparingly)\n- Long-running background work (>5 minutes)\n- Work that needs separate tracking/progress monitoring\n- Complex multi-step projects with explicit deliverables\n\n## Prefer invoke Instead\nFor most requests, use `invoke` - it's simpler and the agent responds directly in chat.\nOnly use this tool when background tracking is truly needed.\n\nAfter creating: You'll receive <sub-task-result-updated> when task completes.",{title:Ae.string().min(1).max(200).describe("Task title"),instructions:Ae.string().describe("Instructions for the owner agent"),briefSummary:Ae.string().optional().describe("One-line summary shown to user immediately"),agentId:Ae.string().describe("Target agent ID"),cwd:Ae.string().optional().describe("Working directory for the sub-task. Pass your current cwd when the sub-task needs to read/write the same project files as you. If omitted, a new isolated workspace is created (scoped by sub-task taskId)."),useWorktree:Ae.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place).")},async a=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startSubTask({agentId:a.agentId,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree})).taskId}\n${a.briefSummary?`Summary: ${a.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return n("error","TASK","Create solo task failed:",e),{content:[{type:"text",text:`Create solo task failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Ya({agentContext:e,log:n,agentId:a}){return We("create_group_task","Create a multi-agent async task plan in group chat.\n\n## When to Use (sparingly)\n- Long-running background work requiring multiple agents (>5 minutes)\n- Complex multi-step projects with explicit deliverables\n- Work that needs separate tracking/progress monitoring\n\n## Prefer invoke Instead\nFor most requests, use `invoke` - it's simpler and agents respond directly in chat.\nOnly use this tool when background tracking with multiple agents is truly needed.\n\nThe planner becomes the task owner; todos are embedded in the task.\nAfter creating: You'll receive <sub-task-result-updated> when task completes.",{title:Ae.string().min(1).max(200).describe("Task title"),requirement:Ae.string().describe("Overall requirement"),briefSummary:Ae.string().optional().describe("One-line summary shown to user immediately"),todos:Ae.array(Ae.object({agentId:Ae.string().describe("Agent ID responsible for the todo"),title:Ae.string().min(1).max(200).describe("Todo title"),instructions:Ae.string().describe("Detailed instructions for this todo")})).min(1).describe("Todo list for agents")},async a=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startGroupTask({title:a.title,todos:a.todos,message:{type:"user",message:{role:"user",content:a.requirement}}})).taskId}\n${a.briefSummary?`Summary: ${a.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return n("error","DISPATCH","Dispatch failed:",e),{content:[{type:"text",text:`Dispatch failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Ja({askUser:e,log:n}){return We("ask_user",'Ask the user questions when you need clarification or user input. Supports 1-4 questions with 2-4 options each. Use this when you need user decisions or additional information. An "Other" option with free text input is automatically added.',{questions:Ae.array(Ae.object({question:Ae.string().describe("The complete question to ask the user"),header:Ae.string().max(12).describe("Short label displayed as a chip/tag (max 12 chars)"),multiSelect:Ae.boolean().describe("Set to true to allow multiple option selections"),options:Ae.array(Ae.object({label:Ae.string().describe("Option label (1-5 words)"),description:Ae.string().describe("Explanation of what this option means")})).min(2).max(4).describe("Available choices (2-4 options)")})).min(1).max(4).describe("Questions to ask (1-4 questions)")},async a=>{try{const n=a.questions.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]})),t=await e(n);return"answered"!==(t.status??"answered")?{content:[{type:"text",text:"The user did not provide an answer within the expected time. \n<system-reminder>Please abort the session, and decide whether to retry when the user provides a new message later.</system-reminder>"}],isError:!0}:{content:[{type:"text",text:`User answers:\n${t.answers.map(e=>e.startsWith("other:")?`Other: "${e.slice(6)}"`:e).join("\n")}`}]}}catch(e){return n("error","ASK_USER","Failed to get user response:",e),{content:[{type:"text",text:`Failed to get user response: ${e instanceof Error?e.message:"Unknown error"}`}]}}})}function Qa({invokeAgent:e}){return We("invoke",'Let an agent respond to the conversation (talk).\n\n**Use for**: Q&A, explanations, opinions, discussions, debates.\n**Do NOT use for**: Work producing files/code → use assign instead.\n\n**hint parameter**: Optional. Use to reduce agent\'s attention cost or provide meta-context:\n- ✅ Role assignment: hint="You argue FOR REST" (first turn of debate)\n- ✅ Focus guidance: hint="Focus on security aspects"\n- ✅ Long/busy chat: hint="Respond to Alice\'s caching question"\n- ✅ Multi-topic: hint="Re: the API design discussion"\n- ❌ Short, clear context: agent can easily find what to respond to\n\nAgent sees hint (if provided) + conversation history and responds in chat.',{agentId:Ae.string().describe("Target agent ID"),hint:Ae.string().optional().describe("Optional context/instruction for the agent")},async n=>(e(n.agentId,n.hint),{content:[{type:"text",text:`Invoked ${n.agentId}. The agent will respond in the chat later.`}]}))}function Za({workClient:e,agentId:n,uploadFile:a,log:t}){return We("update_agent_info","Update your display name, avatar, and signature in the platform.\nCall this after onboarding when the user has chosen your name and emoji/image.\nThis syncs your identity to the platform so the App displays your chosen name and avatar.\n\nFor avatar: provide a local image file path. The image will be uploaded to the platform.\nFor signature: a short status line or tagline shown under your name.",{displayName:Ae.string().optional().describe("Your display name"),avatarPath:Ae.string().optional().describe("Local path to avatar image file (png/jpg/svg)"),signature:Ae.string().optional().describe("Short status line or tagline shown under your name")},async s=>{let i;if(s.avatarPath)try{i=(await a({name:"avatar.png",path:s.avatarPath,visibility:"public"})).fileId}catch(e){return t("error","TOOL","Avatar upload failed:",e),{content:[{type:"text",text:`Avatar upload failed: ${e}`}],isError:!0}}e.sendUpdateAgentInfo(n,{displayName:s.displayName,avatar:i,signature:s.signature});const o=[];return s.displayName&&o.push(`name → ${s.displayName}`),i&&o.push("avatar → uploaded"),s.signature&&o.push(`signature → ${s.signature}`),{content:[{type:"text",text:`Profile updated: ${o.join(", ")}`}]}})}function et({assign:e,log:n}){return We("assign","Assign work to an agent (do the work).\n\n**Use for**: Code, files, reports, artifacts (agent produces output).\n**Do NOT use for**: Q&A, explanations → use invoke instead.\n\nProgress streams to chat in real-time.",{agentId:Ae.string().describe("Target agent ID"),instruction:Ae.string().describe("Task instruction for the agent"),acknowledgment:Ae.string().optional().describe('Agent\'s quick reply shown immediately (e.g., "starting now", "On it")')},async n=>(e(n.agentId,n.instruction,n.acknowledgment),{content:[{type:"text",text:`Assigned work to ${n.agentId}.`}]}))}function nt({agentContext:e,log:n}){return We("list_tasks","List recent tasks in the current chat.\nUse this to review what tasks have been running, completed, or are still active.\nReturns a lightweight summary of each task (id, title, state, agent, duration, timestamps).",{limit:Ae.number().int().min(1).max(50).default(10).optional().describe("Maximum number of tasks to return (default 10)."),status:Ae.enum(["all","active","completed"]).default("all").optional().describe("Filter by task status: all, active, or completed.")},async a=>{try{const n=await e.listTasks({limit:a.limit??10,status:a.status??"all"});return n.length?{content:[{type:"text",text:JSON.stringify(n,null,2)}]}:{content:[{type:"text",text:"No tasks found."}]}}catch(e){return n("error","TASK","Failed to list tasks:",e),{content:[{type:"text",text:`Failed to list tasks: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function at({chatHistoryDb:e}){return We("read_conversation","Read recent messages from the main conversation between you and the user. Use this to review what was discussed recently.",{limit:Ae.number().int().min(1).max(200).default(50).optional().describe("Number of recent messages to return (default 50)."),before:Ae.number().int().optional().describe("Sequence number — return messages before this sequence for pagination.")},async n=>{if(!e)return{content:[{type:"text",text:"Chat history not available in this mode."}],isError:!0};const a=n.limit??50,t=null!=n.before?e.pageMessagesBefore(n.before,a):e.pageRecentMessages(a);if(0===t.data.length)return{content:[{type:"text",text:"No conversation messages found."}]};let s=Ua(t.data);return t.hasMore&&(s+=`\n\nMore messages available. Use before=${Math.min(...t.data.map(e=>e.localSequence))} to load earlier messages.`),{content:[{type:"text",text:s}]}})}function tt({agentContext:e,log:n}){return We("send_reminder","Send an internal reminder to your main self (本体) in the primary chat.\nThis is for companion shadow (heartbeat task) use only.\n\nThe reminder is invisible to the user — it only wakes up the main companion worker.\nThe main companion will see the reminder in its conversation context and decide how to act.\n\nKeep content concise (one sentence). For detailed analysis, write to a file and pass filePath.",{content:Ae.string().describe('Brief reminder message (one sentence, e.g., "Heartbeat architecture discussion pending for 2 days, consider following up")'),filePath:Ae.string().optional().describe("Path to detailed analysis file in workspace, if any")},async a=>{try{const n=e.getChatId();return await e.sendMessage({taskId:n,message:{type:"companion_reminder",content:a.content,filePath:a.filePath,timestamp:(new Date).toISOString()},target:"agent"}),{content:[{type:"text",text:"Reminder sent to main companion."}]}}catch(e){return n("error","COMPANION","Failed to send reminder:",e),{content:[{type:"text",text:`Failed to send reminder: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function st({uploadFile:e,log:a}){return We("upload_file","Upload a local file to the platform and get a public URL.\nUse this to share images, documents, or other files with the user.\nReturns a public URL that can be embedded in markdown (e.g., ![screenshot](url)).",{filePath:Ae.string().describe("Absolute path to the local file to upload"),name:Ae.string().optional().describe("Display name for the file (defaults to filename)")},async t=>{try{const a=n("path"),s=t.name||a.basename(t.filePath);return{content:[{type:"text",text:(await e({name:s,path:t.filePath,visibility:"public"})).url}]}}catch(e){return a("error","TOOL","File upload failed:",e),{content:[{type:"text",text:`File upload failed: ${e}`}],isError:!0}}})}function it({agentContext:e,log:n}){return We("list_agents","List all available agents for the current user, including system agents and user-created agents (both published and draft).",{},async()=>{try{const{agents:n,draftAgents:a}=await e.listAgents(),t=e=>`- **${e.displayName||e.name}** (${e.id})\n Type: ${e.type}\n`+(e.developerName?` Developer: ${e.developerName}\n`:"")+` ${e.description||"No description"}\n`;let s="# Available Agents\n\n";return n.length>0&&(s+="## Published Agents\n\n",s+=n.map(t).join("\n")),a.length>0&&(s+="\n## Draft Agents\n\n",s+=a.map(t).join("\n")),0===n.length&&0===a.length&&(s+="No agents available."),{content:[{type:"text",text:s}]}}catch(e){return n("error","AGENTS","Failed to list agents:",e),{content:[{type:"text",text:`Failed to list agents: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}const ot=Ve(De);async function rt(e){try{const n=Ke(e);return await n.checkIsRepo()}catch{return!1}}async function ct(e){const n=Ke(e);await n.add("."),await n.commit("Initial commit",{"--allow-empty":null})}async function pt(e,n,a){const t=Ke(e);(await t.branchLocal()).all.includes(n)?await t.checkout(n):(a&&await t.checkout(a),await t.checkoutLocalBranch(n))}async function lt(e){const n=Ke(e);return!(await n.status()).isClean()}async function dt(e){const n=Ke(e),a=await n.log({maxCount:1});if(!a.latest)throw new Error("No commits found in repository");return a.latest.hash}async function ut(e){try{const n=Ke(e);return null!==(await n.log({maxCount:1})).latest}catch{return!1}}function mt(e){if(!te(e))return!0;const n=ce(e);return 0===n.length||1===n.length&&".git"===n[0]}async function gt(e,n){const a=Ke(e);return await a.add("."),await a.commit(n),await dt(e)}async function ht(e,n,a){const t=Ke(e),s=await t.diffSummary([`${n}..${a}`]);return{totalInsertions:s.insertions,totalDeletions:s.deletions,files:s.files.map(e=>({path:e.file,insertions:"insertions"in e?e.insertions:0,deletions:"deletions"in e?e.deletions:0}))}}async function ft(e){const n=Ke(e);return(await n.revparse(["--abbrev-ref","HEAD"])).trim()}async function xt(e,n,a){const t=Ke(e);await t.remote(["set-url",n,a])}const vt="oauth2",bt="AGENTRIX_GIT_USERNAME",yt="AGENTRIX_GIT_PASSWORD";function wt(){const e=me(Y(),`git-askpass-${M()}.sh`);return oe(e,`#!/bin/sh\ncase "$1" in\n *Username*|*username*) printf '%s\\n' "\${${bt}:-${vt}}" ;;\n *) printf '%s\\n' "\${${yt}:-}" ;;\nesac\n`,{mode:448}),e}function kt(e,n,a=vt){return{...process.env,GIT_ASKPASS:e,GIT_TERMINAL_PROMPT:"0",[bt]:a,[yt]:n}}function It(e){return{gitUrl:e.gitUrl,baseBranch:e.baseBranch,cwd:e.cwd||"",userCwd:e.userCwd,forceUserCwd:e.forceUserCwd,userId:e.userId,taskId:e.taskId,repositorySourceType:e.repositorySourceType,taskRepositoryId:e.repositoryId,gitServerId:e.gitServerId}}function St(e){return`agentrix/${e}`}async function Tt(e){if(!e)return null;const n=await D.getSecretKey();return n?En(e,n):null}async function Et(e,n){const a=function(e){const n=function(e){return me(Tn,`${e}.pat.meta.json`)}(e);if(!te(n))return null;try{return JSON.parse(se(n,"utf8"))}catch{return null}}(n);if(!a)return void console.warn("[GIT] No PAT user metadata found, skipping git config");const t=a.username,s=a.email||`${a.username}@gitlab.local`;await async function(e,n,a){await ot("git",["config","user.name",n],{cwd:e}),await ot("git",["config","user.email",a],{cwd:e})}(e,t,s),console.log(`[GIT] Set local git config user.name=${t} user.email=${s}`)}async function Ct(e,n,a,t){const s=await Tt(t);s?await async function(e,n,a,t=!1){const s=wt();try{const i=["push","origin",a];t&&i.push("--force"),await ot("git",i,{cwd:n,env:kt(s,e)})}finally{le(s)}}(s,e,n,a):await async function(e,n,a=!1){const t=Ke(e),s=a?["--force"]:[];await t.push("origin",n,s)}(e,n,a)}async function At(e,n,a){await async function(e){const n=Ke(e);await n.init()}(e);const t=function(e,n){return{hook_event_name:"RepositoryInit",workspace_path:e,task_id:n}}(e,n);return a?.onRepositoryInit&&await a.onRepositoryInit(t),await ct(e),await dt(e)}function Rt(e,n){return`Auto-commit: ${e} at ${(new Date).toISOString().replace("T"," ").substring(0,19)} for task ${n}`}async function _t(e,n,a,t){if(n===a)return;const s=await async function(e,n,a){const t=Ke(e);return await t.diff([`${n}..${a}`])}(e,n,a);if(!s.trim())return;const i=me(t,"patch.diff");return await Xe(i,s),i}async function Mt(e,n,a){await D.writeLastSentCommitHash(e,n,a)}function $t(e,n){return`Please generate pull request metadata for the changes made in this task.\n\nInitial commit hash: ${e}\n${n?`\n\nAdditional instructions:\n${n}`:""}\n\nProvide a concise title (conventional commits format), a detailed description, and a user-facing summary message.`}function Dt(e,n,a,t=6e4){return new Promise(s=>{const i=`shell_${Ye().replace(/-/g,"")}`;a.onOutput({type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:i,name:"shell",input:{command:e}}]},parent_tool_use_id:null,session_id:""});const o=ke("/bin/bash",["-c",e],{cwd:n,env:process.env,shell:!1});let r=null,c=!1;t>0&&(r=setTimeout(()=>{c=!0,o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL")},1e3)},t));let p="";o.stdout?.on("data",e=>{p+=e.toString()}),o.stderr?.on("data",e=>{p+=e.toString()}),o.on("close",(e,n)=>{let o,l,d;if(r&&clearTimeout(r),c){o=124,d=!0;const e=`\n[Command timed out after ${t/1e3} seconds]`;l=p?`${p}${e}`:e.trim()}else o=null!==e?e:"SIGTERM"===n?143:1,d=0!==o,l=p||"(no output)";a.onOutput({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:i,content:l,is_error:d}]},parent_tool_use_id:null,session_id:""}),a.onComplete(o),s(o)}),o.on("error",e=>{r&&clearTimeout(r);const n=`[Error] ${e.message||"Command execution failed"}`;a.onOutput({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:i,content:n,is_error:!0}]},parent_tool_use_id:null,session_id:""}),a.onComplete(1),s(1)})})}class Pt{config;messageQueue=[];agentMessageQueue=[];agentMessageResolver=null;workerState="running";messageIdCounter=0;isStopped=!1;runStartTime=Date.now();commandRunning=!1;isDebouncing=!1;agentRunningMap=new Map;backgroundTaskMap=new Map;anonymousBackgroundTaskCount=0;lastActiveAgentsSignature=null;idleTimeoutHandle=null;idleTimeoutMs;constructor(e){this.config=e,this.idleTimeoutMs=Math.max(0,e.idleTimeoutMs??0)}parseMessage(e){if("user"!==e.type)return{type:"normal",content:"",originalMessage:e};const n=("string"==typeof e.message.content?e.message.content:"").trim();return n.startsWith("!")&&!n.startsWith("![")?{type:"bash-command",content:n.slice(1).trim(),originalMessage:e}:"![merge-request]"===n?{type:"merge-request",content:n,originalMessage:e}:"![merge-pr]"===n?{type:"merge-pr",content:n,originalMessage:e}:"![new]"===n?{type:"new-session",content:n,originalMessage:e}:{type:"normal",content:n,originalMessage:e}}async enqueue(e){if(this.isStopped)return void this.log("warn","COORDINATOR","Ignoring message - coordinator is stopped");if(!("user"!==e.type||e.message&&"object"==typeof e.message&&"content"in e.message))return void this.log("warn","COORDINATOR","Ignoring malformed user message (missing content)");const n=this.parseMessage(e),a={id:"msg-"+ ++this.messageIdCounter,type:n.type,priority:"normal",content:n.content,originalMessage:e,timestamp:Date.now()};this.messageQueue.push(a),this.log("info","COORDINATOR",`Enqueued message ${a.id} (type: ${a.type}, queue: ${this.messageQueue.length})`),this.tryUpdateWorkerState(),this.tryProcessNext()}async tryProcessNext(){if(!this.isStopped&&0!==this.messageQueue.length){this.tryUpdateWorkerState();try{const e=this.messageQueue.shift();this.log("info","COORDINATOR",`Processing message ${e.id} (type: ${e.type})`),await this.processMessage(e),this.log("info","COORDINATOR",`Completed message ${e.id}`)}catch(e){this.log("error","COORDINATOR",`Error processing message: ${e}`)}finally{this.isStopped||this.tryProcessNext()}}}async processMessage(e){try{switch(e.type){case"normal":await this.processNormalMessage(e);break;case"bash-command":await this.processBashCommand(e);break;case"merge-request":await this.processMergeRequest(e);break;case"merge-pr":await this.processMergePr(e);break;case"new-session":await this.processNewSession(e);break;default:this.log("warn","COORDINATOR",`Unknown message type: ${e.type}`)}}finally{if("normal"!==e.type){const n=e.originalMessage.__localSequence;void 0!==n&&this.config.onCommandMessageProcessed?.(n)}}}async processNormalMessage(e){this.log("info","COORDINATOR","Processing normal message for SDK");const n=await this.config.handlers.onNormalMessage(e.originalMessage);this.enqueueAgentMessage(n)}async processBashCommand(e){this.log("info","COORDINATOR",`Processing bash command: ${e.content}`),await this.waitWorkerIdle(),this.setCommandRunning(!0);try{await this.config.handlers.onBashCommand(e.content,e.originalMessage)}finally{this.setCommandRunning(!1)}}async processMergeRequest(e){this.log("info","COORDINATOR","Processing merge-request command"),await this.waitWorkerIdle(),this.setCommandRunning(!0);try{await this.config.handlers.onMergeRequest(e.originalMessage)}finally{this.setCommandRunning(!1)}}async processMergePr(e){this.log("info","COORDINATOR","Processing merge-pr command"),await this.waitWorkerIdle(),this.setCommandRunning(!0);try{await this.config.handlers.onMergePr()}finally{this.setCommandRunning(!1)}}async processNewSession(e){this.log("info","COORDINATOR","Processing new-session command"),await this.waitWorkerIdle(),this.setCommandRunning(!0);try{await(this.config.handlers.onNewSession?.())}finally{this.setCommandRunning(!1)}}async waitWorkerIdle(){for(;"idle"!==this.getExecutionState();){if(this.isStopped)throw new Error("Coordinator stopped while waiting for idle");this.log("debug","COORDINATOR","Waiting for worker idle state"),await new Promise(e=>setTimeout(e,100))}}setWorkerState(e){if(this.workerState===e)return;const n=this.workerState;if(this.log("info","COORDINATOR",`Worker state: ${n} → ${e}`),this.workerState=e,"running"===e&&"idle"===n&&(this.runStartTime=Date.now(),this.config.workClient.sendWorkRunning(this.getActiveAgents()),this.lastActiveAgentsSignature=this.getActiveAgentsSignature(),this.clearIdleTimer()),"idle"===e&&"running"===n){let e;this.runStartTime&&(e=Date.now()-this.runStartTime,this.runStartTime=null),this.config.workClient.sendWorkerReady(e),this.lastActiveAgentsSignature=null,this.startIdleTimer()}}updateAgentRunning(e){this.setAgentRunning("default","Agent",e)}setAgentRunning(e,n,a){const t="running"===this.workerState,s=this.lastActiveAgentsSignature;a?this.agentRunningMap.set(e,{agentId:e,agentName:n,startedAt:Date.now()}):this.agentRunningMap.delete(e);const i=this.getActiveAgentsSignature();this.lastActiveAgentsSignature=i,this.tryUpdateWorkerState(),t&&"running"===this.workerState&&i!==s&&this.config.workClient.sendWorkRunning(this.getActiveAgents())}setBackgroundTaskRunning(e,n){e&&(n?this.backgroundTaskMap.set(e,{taskId:e,startedAt:Date.now()}):!this.backgroundTaskMap.delete(e)&&this.anonymousBackgroundTaskCount>0&&(this.anonymousBackgroundTaskCount-=1,this.log("debug","COORDINATOR",`Background task ${e} completed via anonymous fallback (remaining: ${this.anonymousBackgroundTaskCount})`)),this.tryUpdateWorkerState())}setAnonymousBackgroundTaskRunning(e){e?(this.anonymousBackgroundTaskCount+=1,this.log("debug","COORDINATOR",`Anonymous background task started (count: ${this.anonymousBackgroundTaskCount})`)):this.anonymousBackgroundTaskCount>0&&(this.anonymousBackgroundTaskCount-=1,this.log("debug","COORDINATOR",`Anonymous background task completed (count: ${this.anonymousBackgroundTaskCount})`)),this.tryUpdateWorkerState()}getActiveAgents(){return Array.from(this.agentRunningMap.values()).map(({agentId:e,agentName:n})=>({agentId:e,agentName:n}))}getActiveAgentsSignature(){const e=this.getActiveAgents().slice().sort((e,n)=>e.agentId.localeCompare(n.agentId));return JSON.stringify(e)}enqueueAgentMessage(e){if(this.isStopped)this.log("warn","COORDINATOR","Ignoring agent message - coordinator is stopped");else if(this.agentMessageQueue.push(e),this.agentMessageResolver){const e=this.agentMessageResolver;this.agentMessageResolver=null,e(this.agentMessageQueue.shift())}}hasAgentMessages(){return this.agentMessageQueue.length>0}getAgentQueueLength(){return this.agentMessageQueue.length}async waitForAgentMessage(){return this.isStopped?null:this.agentMessageQueue.length>0?this.agentMessageQueue.shift():new Promise(e=>{this.agentMessageResolver=e})}cancelAgentWait(){if(!this.agentMessageResolver)return;const e=this.agentMessageResolver;this.agentMessageResolver=null,e(null)}setCommandRunning(e){this.commandRunning!==e&&(this.commandRunning=e,this.tryUpdateWorkerState())}hasExecutionWork(){return this.commandRunning||this.agentRunningMap.size>0||this.backgroundTaskMap.size>0||this.anonymousBackgroundTaskCount>0||this.isDebouncing}getExecutionState(){return this.hasExecutionWork()?"running":"idle"}setDebouncing(e){this.isDebouncing!==e&&(this.isDebouncing=e,this.tryUpdateWorkerState())}tryUpdateWorkerState(){if(this.isStopped)return;const e=this.messageQueue.length>0||this.agentMessageQueue.length>0,n=this.hasExecutionWork(),a=!e&&!n;this.setWorkerState(a?"idle":"running")}startIdleTimer(){0!==this.idleTimeoutMs&&(this.idleTimeoutHandle||(this.idleTimeoutHandle=setTimeout(()=>{this.idleTimeoutHandle=null,this.isStopped||(this.log("info","COORDINATOR","Idle timeout reached, stopping task"),this.cancelAgentWait(),this.config.onIdleTimeout?.())},this.idleTimeoutMs)))}clearIdleTimer(){this.idleTimeoutHandle&&(clearTimeout(this.idleTimeoutHandle),this.idleTimeoutHandle=null)}getStatus(){return{state:this.workerState}}isActivelyExecuting(){return this.hasExecutionWork()}stop(){this.log("info","COORDINATOR","Stopping coordinator"),this.isStopped=!0,this.clearIdleTimer(),this.messageQueue=[],this.agentMessageQueue=[],this.backgroundTaskMap.clear(),this.anonymousBackgroundTaskCount=0,this.cancelAgentWait()}log(e,n,a){this.config.logger&&this.config.logger(e,n,a)}}function Ot(e,n){const a={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:n}]}};e.sendTaskMessage(_a,a)}async function jt(e){const{workingDirectory:n,workClient:a,repositoryId:t,gitServerId:s,logger:i,askUser:o}=e;if(i.info("[MERGE-PR] Executing merge-pr command"),t){try{const e=await ft(n),t=await lt(n),r=await async function(e,n){const a=Ke(e);try{return(await a.log([`origin/${n}..HEAD`])).total>0}catch{return!0}}(n,e);if(t||r){const c=await async function(e,n,a,t){let s="";s=e&&n?"You have uncommitted changes and unpushed commits. What would you like to do?":e?"You have uncommitted changes. What would you like to do?":"You have unpushed commits. What would you like to do?";const i=[{question:s,header:"Git Status",multiSelect:!1,options:[{label:"Pause",description:"Stop operation, handle git state manually"},{label:"Push",description:"Push changes and review before merging"},{label:"Push and Merge",description:"Push changes and merge PR immediately"}]}];try{const e=(await a(i)).answers[0];return e.startsWith("other:")?(t.info(`[MERGE-PR] User provided custom input: ${e}, defaulting to Pause`),"Pause"):{Pause:"Pause",Push:"Push","Push and Merge":"PushAndMerge"}[e]||"Pause"}catch(e){return t.error("[MERGE-PR] Ask user failed:",e),"Pause"}}(t,r,o,i);if("Pause"===c)return void Ot(a,"Operation paused. Please handle git state and run merge again.");if(("Push"===c||"PushAndMerge"===c)&&(t&&(i.info("[MERGE-PR] Auto-committing changes"),await gt(n,"Auto-commit before merge")),i.info(`[MERGE-PR] Pushing branch ${e} to remote`),await Ct(n,e,!1,s),"Push"===c))return void Ot(a,"✅ All changes pushed to remote. You can now review and run merge again if everything looks good.")}const c=await a.sendMergePr();if(c.success)Ot(a,`✅ PR merged successfully! Branch ${e} has been merged into the target branch.`);else{let e;switch(c.errorType){case"github_conflict":e="Merge conflict detected. Please resolve conflicts manually on GitHub and try again.";break;case"pr_not_open":e="PR is not open. The PR may have already been merged or closed.";break;case"permission_denied":e="Permission denied. You may not have permission to merge this PR.";break;case"merge_failed":e=`Merge failed: ${c.error||"Unknown error"}`;break;default:e=`Failed to merge PR: ${c.error||"Unknown error"}`}a.sendSystemErrorMessage(e)}}catch(e){i.error("[MERGE-PR] Failed:",e);const n=e instanceof Error?e.message:"Unknown error";a.sendSystemErrorMessage(`Failed to push or merge: ${n}`)}i.info("[MERGE-PR] Worker ready after merge-pr execution")}else a.sendSystemErrorMessage("Cannot merge: task has no git repository configured.")}function Nt(e,n){const a=e.updates?.repositoryId;return"string"==typeof a&&0!==a.length&&n.repositoryId!==a&&(n.repositoryId=a,D.writeTaskInput(n),!0)}function qt(e,n,a,t={}){const s=a.sendAskUser(e),i=t.timeoutMs??18e5,o=t.onTimeout;return new Promise((e,t)=>{const r=setTimeout(()=>{n.delete(s);const i={type:"ask_user_response",answers:[],status:"timeout",reason:"timeout"};a.sendAskUserResponse(s,i),"abort_task"===o?(a.onTimeoutMessage?.("ask_user timed out. Task cancelled."),a.stopTask?.("ask_user_timeout"),t(new Error("Ask user request timed out"))):e(i)},i);n.set(s,n=>{clearTimeout(r),e(function(e){const n=e.status??"answered";return e.status&&e.reason?e:{...e,status:n,reason:e.reason??("timeout"===n?"timeout":"user")}}(n))})})}function Ut(e){const n=e.split("\n");for(;n.length>0&&""===n[0].trim();)n.shift();for(;n.length>0&&""===n[n.length-1].trim();)n.pop();const a=n.reduce((e,n)=>{if(""===n.trim())return e;const a=n.match(/^\s*/)[0].length;return Math.min(e,a)},1/0);return n.map(e=>e.slice(a)).join("\n")}const Gt=Ut("\n ## Title Setting Protocol:\n - MUST set a descriptive title using mcp__agentrix__change_title as your FIRST action when the user makes a request\n - This is mandatory, not optional - do this before any other work\n - Update the title if the conversation direction changes substantially\n"),Lt=Ut('\n ## Input Data Format (Conversation Stream)\n\n Messages come in this XML format. Pay attention to `seq` to understand the order.\n\n <msg seq="N" at="ISO_TIME" senderType="human|agent" senderId="id" senderName="name">\n content\n </msg>\n'),Ft=Ut('\n ## Orchestration Decision Framework\n\n **Core Principle**: Analyze dependencies FIRST to choose orchestration mode.\n\n **Decision Rule**:\n - **No dependencies** (agents work independently) → Direct execution\n - **Has dependencies** (sequential, turn-taking, coordination) → Plan-Execute-Replan loop\n\n ### Mode 1: Direct Execution (No Dependencies)\n\n When agents can work independently with no coordination:\n - Single agent request\n - Parallel opinions (no need to build on each other)\n - Independent work tasks\n\n **Examples**:\n - "Claude, explain X" → invoke(claude)\n - "What do you both think?" → invoke(claude), invoke(codex)\n - "Claude, write parser. Codex, write formatter." → assign both\n\n ### Mode 2: Plan-Execute-Replan Loop (Has Dependencies)\n\n When work has sequential dependencies or coordination:\n\n **The Loop**:\n 1. **PLAN**: TodoWrite defines structure/order\n 2. **EXECUTE**: invoke/assign first agent\n 3. **WAIT**: Agent responds in next message batch\n 4. **REPLAN**: Update TODO (mark done), identify next\n 5. **REPEAT**: Continue until complete\n\n **Dependency types**:\n - **Sequential**: Agent B needs Agent A\'s output\n - **Turn-taking**: Debate/conversation structure (A→B→A)\n - **Coordination**: Multiple agents with defined roles\n\n **Example - Debate** (turn-taking dependency):\n ```\n User: "4-round debate on REST vs GraphQL"\n\n PLAN (TodoWrite):\n - [ ] Claude: Opening argument FOR REST\n - [ ] Codex: Counter argument FOR GraphQL\n - [ ] Claude: Rebuttal\n - [ ] Codex: Final response\n\n EXECUTE: invoke(claude, hint="You argue FOR REST. Present your opening argument.")\n WAIT: Claude responds with REST argument\n REPLAN: Mark done, next is codex\n EXECUTE: invoke(codex, hint="You argue FOR GraphQL. Counter the REST arguments.")\n WAIT: Codex responds with GraphQL argument\n REPLAN: Mark done, next is claude rebuttal\n EXECUTE: invoke(claude) // No hint needed - role already established from history\n REPEAT...\n ```\n\n **hint usage**: Use hint to reduce agent\'s attention cost or provide meta-context:\n - ✅ Role assignment: first turn of debate (hint="You argue FOR REST")\n - ✅ Focus guidance: (hint="Focus only on performance aspects")\n - ✅ Long/busy chat: help agent locate relevant context (hint="Respond to Alice\'s question about caching")\n - ✅ Multi-topic: clarify which thread to address (hint="Re: the API design discussion")\n - ❌ Short, clear context: agent can easily find what to respond to\n - ❌ Role already established: agent knows their role from recent history\n\n **Why TodoWrite**: Planner is event-driven, can\'t "wait" for responses. TodoWrite provides persistent state across turns.\n\n ### Best Practices\n\n - Match agent to user intent by reviewing capabilities (get_task_agents)\n - Review history (get_task_history) when context is unclear\n\n ### Common Mistakes\n\n - ❌ Invoke just because an agent spoke; only act on unmet user requests\n - ❌ Repeated or cascading invokes on the same request\n - ❌ Invoke multiple agents with dependencies simultaneously\n - ❌ Use TodoWrite for independent requests (over-engineering)\n - ❌ Forget to update TODO after agent responds\n'),Wt=Ut('\n You are Planner, orchestrating a chat group where Users and Agents interact.\n Your goal is to observe the conversation stream, analyze context, and direct appropriate agents via tools.\n\n ## Visibility Rules\n\n - Your text output is NOT shown to users, but IS visible to developers for debugging\n - Keep brief reasoning/analysis in your output to help developers understand your decisions\n - NEVER attempt to answer user questions directly - let agents handle all user interaction\n\n ## Output Format\n\n 1. Brief reasoning (for developer debugging)\n 2. Tool calls if needed\n 3. Final output: ONLY "✅" on a new line (no other text after it)\n'),Ht=Ut("\n # Task Delegation\n\n ## When to Delegate (use create_task)\n\n - Implementation work: writing code, editing files, running tests\n - Investigation: multi-file analysis, tracing bugs, code archaeology\n - Code reviews, audits, or quality scans\n - Producing artifacts: reports, plans, configs\n - Any work where the user is waiting for you to finish before the conversation can continue\n\n ## When to Respond Directly\n\n - Answering questions, explaining concepts\n - Quick file lookups to answer a specific question (1-2 reads is fine)\n - Short code snippets or examples in conversation\n - Discussion, planning, decision-making with the user\n\n ## Your Role in Conversation\n\n The conversation is for **discussion, decisions, and summaries** — not for executing work.\n\n - Discuss approaches, trade-offs, and options with the user\n - Make decisions together (or present recommendations)\n - Summarize task results when they come back\n - Coordinate and plan — then delegate execution to tasks\n\n ## Anti-Patterns (Do NOT do these in conversation)\n\n - ❌ **Code editing**: Don't write/edit code directly in conversation — create a task\n - ❌ **Research rabbit holes**: Don't grep → read → grep → read in conversation — delegate the investigation\n - ❌ **Building artifacts**: Any output that produces files (code, reports, configs) belongs in a task\n - ❌ **Running tests/builds**: Don't run test suites or build commands in conversation — create a task\n\n **Rule of thumb**: If you're about to *change* something or *produce* something, it's a task. If you're about to *answer* something, respond directly.\n\n ## After Delegating\n\n - User sees task creation confirmation immediately\n - Continue responding to user's other questions\n - You'll receive <sub-task-result-updated> when task completes\n - Briefly summarize the result to user — no deep analysis needed\n - Do NOT create duplicate sub-tasks unless explicitly asked\n\n ## Using emit_to_task Effectively\n\n emit_to_task sends follow-up instructions to a running or completed sub-task. Use it for:\n\n - **User adds requirements**: User says \"also add tests\" → emit to the existing task, don't create a new one\n - **Passing decisions**: You discussed options with user, user chose option B → emit the decision to the task\n - **Course correction**: Task went in wrong direction → emit new guidance\n - **Providing context**: Task asks a question → get answer from user → emit answer to task\n - **Retry after failure**: Task failed → emit instructions to retry with fixes\n\n Do NOT use emit_to_task to:\n - Start a completely different task (create a new task instead)\n - Send very long instructions (if the scope changed drastically, create a new task)\n\n ## Task Granularity\n\n - **One task = one coherent unit of work** (e.g., \"implement login page\", \"investigate memory leak\")\n - Don't create a task for a single trivial operation (e.g., \"read one file\")\n - Don't cram unrelated work into one task — split them so they can run in parallel\n - Multiple independent tasks CAN run in parallel\n"),zt=Ut(`\n ${Wt}\n\n ${Lt}\n\n ${Ft}\n`),Bt=Ut('\n ## Message Format\n\n Messages in this group chat are formatted as XML:\n\n <msg seq="N" at="ISO_TIME" senderType="human|agent" senderId="id" senderName="name">\n content\n </msg>\n\n You may also receive a `<hint>` block at the start:\n\n <hint>\n context or instruction from the orchestrator\n </hint>\n\n The hint provides context for your response (e.g., debate role, focus area).\n Follow the hint\'s guidance while responding to the conversation.\n\n When responding, just reply naturally - the system will handle formatting.\n');function Kt(e){const n=["# Available Agents",""];for(const a of e)a.description?n.push(`- **${a.name}** (${a.id}): ${a.description}`):n.push(`- **${a.name}** (${a.id})`);return n.join("\n")}function Vt(e,n){const a=n.find(n=>n.id===e);if(!a)return Kt(n);const t=n.filter(n=>n.id!==e),s=["# Group Context","",`You are \`${a.name}\`. `,"You are a member of this group chat."];if(a.description&&s.push(`Your role: ${a.description}`),t.length>0){s.push(""),s.push("## Other Agents in This Group"),s.push("");for(const e of t)e.description?s.push(`- **${e.name}**: ${e.description}`):s.push(`- **${e.name}**`)}return s.push(""),s.push(Bt),s.join("\n")}function Xt(e){const n={};for(const[a,t]of Object.entries(e))"string"==typeof t&&(n[a]=t);return n}function Yt(e){if("object"!=typeof e||null===e)return!1;const n=e;return"text"===n.type&&"string"==typeof n.text}function Jt(e){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:""}}function Qt(e){const n=e.message?.content;return"string"==typeof n?n:Array.isArray(n)?n.filter(Yt).map(e=>e.text).join("\n").trim():""}function Zt(e){const n=e.usage.input_tokens-e.usage.cached_input_tokens,a={input_tokens:e.usage.input_tokens,output_tokens:e.usage.output_tokens,cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},cache_creation_input_tokens:0,cache_read_input_tokens:e.usage.cached_input_tokens,server_tool_use:{web_fetch_requests:0,web_search_requests:0},service_tier:"standard"};return{type:"result",subtype:"success",duration_ms:0,duration_api_ms:0,is_error:!1,num_turns:e.numTurns,result:e.result??"",stop_reason:null,total_cost_usd:0,usage:a,modelUsage:{[e.model]:{inputTokens:n>0?n:0,outputTokens:e.usage.output_tokens,cacheReadInputTokens:e.usage.cached_input_tokens,cacheCreationInputTokens:0,webSearchRequests:0,costUSD:0,contextWindow:0,maxOutputTokens:0}},permission_denials:[],uuid:crypto.randomUUID(),session_id:e.sessionId}}const es="agentrix",ns="1.0.0";async function*as(e){yield e}let ts;const ss=["Bash","Glob","Grep","ExitPlanMode","Read","Skill","SlashCommand","EnterPlanMode"],is=["Glob","Grep","Read","Skill"],os=["Read","Glob","Grep"],rs=["Read","Glob","Grep","TodoWrite"];function cs(e,n,a,t,s,i,o){const r=function(e){const{agentId:n,modeConfig:a,cwd:t,agentConfig:s}=e,{mode:i,groupAgents:o}=a,r=s.customSystemPrompt,c=s.systemPromptMode??"append",p=function(e){const{mode:n,supportChangeTitle:a}=e;switch(n){case"work":return a?Gt:void 0;case"companion_shadow":case"companion_chat":case"reply":case"group_chat":return;case"chat":return Ht;case"group_work":{const e=[];return a&&e.push(Gt),e.join("\n\n")}}}(a);if("group_chat"===i||"group_work"===i){const e=[zt];return o&&o.length>0&&e.push(Kt(o)),p&&e.push(p),e.join("\n\n")}const l="reply"===i&&o&&o.length>0?Vt(n,o):void 0,d={},u=process.env.AGENTRIX_COMPANION_HOME||process.env.AGENTRIX_COMPANION_WORKSPACE;u&&(d.COMPANION_HOME=u,d.COMPANION_MODE="companion_shadow"===i?"shadow":"chat");const m=Object.keys(d).length>0?d:void 0,g=r?Je(r,t,m):void 0;if("replace"===c&&g){const e=[g];return l&&e.push(l),p&&e.push(p),e.join("\n\n")}const h=[];return l&&h.push(l),p&&h.push(p),g&&h.push(g),{type:"preset",preset:"claude_code",append:h.length>0?h.join("\n\n"):void 0}}({agentId:e,modeConfig:n.modeConfig,cwd:n.cwd,agentConfig:a}),c=function(e){switch(e){case"work":case"companion_shadow":return;case"chat":case"companion_chat":return[...ss];case"reply":return[...is];case"group_chat":return[...os];case"group_work":return[...rs]}}(n.modeConfig.mode),p=function(e,n){const a={},t=e=>async(n,a,t)=>await e(n,a,t)??{},s=new Set([...Object.keys(e),...n?Object.keys(n):[]]);for(const i of s){const s=[],o=e[i];o&&s.push(t(o));const r=n?.[i];r&&s.push(t(r)),a[i]=[{hooks:s}]}return a}(n.hooks??{},t),l=function(){if(void 0!==ts)return ts??void 0;const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(e){const n=function(e){const n=e.trim();if(n){if(n.includes("/")||n.includes("\\")||n.startsWith(".")){const e=be(n)?n:ye(n);return te(e)?e:void 0}return function(e){const n="win32"===process.platform?"where":"which",a=$e(n,[e],{encoding:"utf-8"});if(0===a.status)return a.stdout.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0)}(n)}}(e);if(n)return ts=n,n}ts=null}(),d=i?function(e){const{modeConfig:n,tools:a,serverName:t=es,serverVersion:s=ns}=e,{mode:i,supportChangeTitle:o}=n,r=[];switch(i){case"work":o&&r.push(a.changeTaskTitle),r.push(a.askUser),r.push(a.getTaskHistory);break;case"chat":r.push(a.createTask),r.push(a.replyToSubTask),r.push(a.askUser),r.push(a.getTaskHistory),r.push(a.listSubTask);break;case"group_chat":r.push(a.invoke),r.push(a.createSoloTask),r.push(a.createGroupTask),r.push(a.replyToSubTask),r.push(a.getTaskAgents),r.push(a.getTaskHistory);break;case"group_work":r.push(a.invoke),r.push(a.assign),o&&r.push(a.changeTaskTitle),r.push(a.getTaskAgents),r.push(a.getTaskHistory);break;case"reply":r.push(a.getTaskHistory),r.push(a.askUser);break;case"companion_chat":r.push(a.createTask),r.push(a.replyToSubTask),r.push(a.askUser),r.push(a.getTaskHistory),r.push(a.uploadFile),r.push(a.listAgents);break;case"companion_shadow":r.push(a.getTaskHistory),r.push(a.readConversation),r.push(a.listAgents)}("companion_chat"===i||"companion_shadow"===i)&&(r.push(a.listTasks),r.push(a.updateAgentInfo),r.push(a.sendReminder));const c=He({name:t,version:s,tools:r}),p=r.map(e=>((e,n)=>`mcp__${e}__${n}`)(t,e.name));return{server:c,toolNames:p}}({modeConfig:n.modeConfig,tools:i}):void 0,u={...d?.server?{agentrix:d.server}:{},...n.mcpServers??{},...s??{}};return{stderr:n.stderr,model:a.customModel||n.model,fallbackModel:a.customFallbackModel,cwd:n.cwd,resume:n.agentSessionId,permissionMode:a.customPermissionMode||"bypassPermissions",settingSources:["user","project","local"],systemPrompt:r,tools:c,mcpServers:u,plugins:a.customPlugins,abortController:n.abortController,env:n.env?Xt(n.env):void 0,pathToClaudeCodeExecutable:l,maxTurns:a.customMaxTurns??n.maxTurns??o,extraArgs:a.customExtraArgs,canUseTool:n.canUseTool,hooks:p,outputFormat:n.structuredOutputSchema}}class ps{constructor(e,n,a,t){this.agentId=e,this.agentConfig=n,this.agentHooks=a,this.agentMcpServers=t}getAgentConfiguration(){return this.agentConfig}getHooks(){return this.agentHooks}getMcpServers(){return this.agentMcpServers}async executeHook(e,n,a){await async function(e,n,a,t){if(!e)return;const s=e[n];if(!s)return;const i=t||(e=>console.log(e));try{i(`[${n}] Executing hook...`);const e=new AbortController,t=setTimeout(()=>{e.abort()},6e4);try{await s(a,"",{signal:e.signal}),i(`[${n}] Hook executed successfully`)}finally{clearTimeout(t)}}catch(e){console.warn(`[${n}] Hook failed (non-fatal):`,e)}}(this.agentHooks,e,n,a)}async run(e,n){const a=this.agentConfig,t="string"==typeof e?Jt(e):e;let s=null;const i=ze({prompt:as(t),options:cs(this.agentId,n,a,this.agentHooks,this.agentMcpServers,n.agentrixTools)});for await(const e of i)if(console.log("ClaudeRunner.run: received message",JSON.stringify(e)),"result"===e.type){s=e;break}if(!s)throw new Error("ClaudeRunner.run: missing result message");return s}async*runStreamed(e,n){const a=this.agentConfig,t="string"==typeof e?Jt(e):e,s=ze({prompt:as(t),options:cs(this.agentId,n,a,this.agentHooks,this.agentMcpServers,n.agentrixTools)});for await(const e of s)if(yield e,"result"===e.type)break}loop(e){const n=e.abortController,a=this.agentConfig,t=cs(this.agentId,e,a,this.agentHooks,this.agentMcpServers,e.agentrixTools);let s=!1;const i=[];let o=null;const r=()=>{if(!s&&(s=!0,o)){const e=o;o=null,e(null)}},c=async function*(){for(;!s&&!n.signal.aborted;){if(i.length>0){yield i.shift();continue}const e=await new Promise(e=>{o=e});if(!e)break;yield e}},p=async function*(){try{const e=ze({prompt:c(),options:t});for await(const n of e)yield n}finally{r()}}();return n.signal.addEventListener("abort",r,{once:!0}),{push:e=>{if(console.log("ClaudeRunner.loop.push:",JSON.stringify(e,null,2)),s)return;const n="string"==typeof e?Jt(e):e;if(o){const e=o;return o=null,void e(n)}i.push(n)},events:p}}}function ls(e){return{type:"system",subtype:"init",apiKeySource:"temporary",betas:[],claude_code_version:"codex",cwd:e.cwd,tools:[],mcp_servers:[],model:e.model??"unknown",permissionMode:"default",slash_commands:[],output_style:"codex",skills:[],plugins:[],uuid:M(),session_id:e.sessionId}}function ds(e,n){const a=M();return n.set(e,a),a}function us(e,n){return n.get(e)||e}function ms(e,n){return"thread.started"===e.type||"turn.started"===e.type||"turn.completed"===e.type||"turn.failed"===e.type?null:"item.started"===e.type?function(e,n){switch(e.type){case"command_execution":return function(e,n){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:ds(e.id,n),name:"Bash",input:{command:e.command}}]},parent_tool_use_id:null,session_id:""}}(e,n);case"file_change":return function(e,n){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:ds(e.id,n),name:"Edit",input:{changes:e.changes.map(e=>({kind:e.kind,path:e.path}))}}]},parent_tool_use_id:null,session_id:""}}(e,n);case"mcp_tool_call":return function(e,n){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:ds(e.id,n),server_name:e.server,name:e.tool,input:e.arguments}]},parent_tool_use_id:null,session_id:""}}(e,n);case"web_search":return function(e,n){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:ds(e.id,n),name:"web_search",input:{query:e.query}}]},parent_tool_use_id:null,session_id:""}}(e,n);default:return null}}(e.item,n):"item.completed"===e.type?function(e,n){switch(e.type){case"agent_message":return function(e){return{type:"assistant",message:{id:e.id,type:"message",container:null,role:"assistant",content:[{citations:null,type:"text",text:e.text}],model:"",usage:{},stop_reason:null,context_management:null,stop_sequence:null},parent_tool_use_id:null,session_id:"",uuid:M().toString()}}(e);case"reasoning":default:return null;case"command_execution":return function(e,n){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:us(e.id,n),content:"failed"===e.status?"Command execution failed":e.aggregated_output||""}]},parent_tool_use_id:null,session_id:""}}(e,n);case"file_change":return function(e,n){const a=n.get(e.id),t=a??ds(e.id,n),s=!a;(e.changes||[]).map(e=>`${e.kind}: ${e.path}`);const i={type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:t,name:"Edit",input:{changes:(e.changes||[]).map(e=>({kind:e.kind,path:e.path}))}}]},parent_tool_use_id:null,session_id:""},o={type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:t,content:"failed"===e.status?"File changes failed":"File changes completed"}]},parent_tool_use_id:null,session_id:""};return s?[i,o]:o}(e,n);case"mcp_tool_call":return function(e,n){const a=us(e.id,n),t="failed"===e.status&&e.error;return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:a,is_error:t,content:t?e.error.message:e.result?.content||""}]},parent_tool_use_id:null,session_id:""}}(e,n);case"web_search":return function(e,n){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:us(e.id,n),content:{type:"web_search_result",results:[]}}]},parent_tool_use_id:null,session_id:""}}(e,n);case"todo_list":return function(e){return{type:"assistant",message:{role:"assistant",content:`📋 Todo List:\n${e.items.map(e=>`${e.completed?"✓":"○"} ${e.text}`).join("\n")}`},parent_tool_use_id:null,session_id:""}}(e);case"error":return function(e){return{type:"assistant",message:{role:"assistant",content:`❌ Error: ${e.message}`},parent_tool_use_id:null,session_id:""}}(e)}}(e.item,n):null}let gs;class hs{createCodex(e){const n={},a=function(){if(void 0!==gs)return gs??void 0;const e=process.env.AGENTRIX_CODEX_PATH?.trim();return e?(gs=e,e):0===$e("codex",["--version"],{stdio:"ignore"}).status?(gs="codex",gs):void(gs=null)}();return a&&(n.codexPathOverride=a),e.env&&(n.env=Xt(e.env)),new en(Object.keys(n).length>0?n:void 0)}getAgentConfiguration(){return null}getHooks(){}getMcpServers(){}async executeHook(e,n,a){}async run(e,n){const a=n.abortController,t=this.createCodex(n),s={workingDirectory:n.cwd,model:n.model,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},i=n.agentSessionId?t.resumeThread(n.agentSessionId,s):t.startThread(s),o=await i.run("string"==typeof e?e:Qt(e),{signal:a.signal,outputSchema:n.structuredOutputSchema?.schema||void 0}),r=i.id??n.agentSessionId??"unknown",c=o.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0};return Zt({sessionId:r,model:n.model??"unknown",numTurns:1,usage:c,result:o.finalResponse??""})}async*runStreamed(e,n){const a=n.abortController,t=this.createCodex(n),s={workingDirectory:n.cwd,model:n.model,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},i=n.agentSessionId?t.resumeThread(n.agentSessionId,s):t.startThread(s),{events:o}=await i.runStreamed("string"==typeof e?e:Qt(e),{signal:a.signal,outputSchema:n.structuredOutputSchema?.schema||void 0});let r=n.agentSessionId||"",c="",p={input_tokens:0,cached_input_tokens:0,output_tokens:0};const l=new Map,d={get:e=>l.get(e),set:(e,n)=>{l.set(e,n)}};for await(const e of o){if("thread.started"===e.type&&(r=e.thread_id,yield ls({sessionId:r,cwd:n.cwd,model:n.model})),"turn.completed"===e.type){e.usage&&(p=e.usage);break}if("turn.failed"===e.type)throw new Error(e.error.message);if("error"===e.type)throw new Error(e.message);if("item.completed"===e.type&&"agent_message"===e.item.type&&e.item.text&&(c=e.item.text),"item.started"===e.type||"item.completed"===e.type){const n=ms(e,d);if(!n)continue;const a=Array.isArray(n)?n:[n];for(const e of a)yield e}}const u=Zt({sessionId:r,model:n.model??"unknown",numTurns:1,usage:p,result:c});yield u}loop(e){const n=e.abortController,a=this.createCodex(e),t={workingDirectory:e.cwd,model:e.model,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0};let s=e.agentSessionId?a.resumeThread(e.agentSessionId,t):a.startThread(t),i=!1;const o=[];let r=null,c=e.agentSessionId??null,p=0;const l=()=>{if(!i&&(i=!0,r)){const e=r;r=null,e(null)}},d=e=>"string"==typeof e?e:Qt(e),u=async function*(){try{for(;!i&&!n.signal.aborted;){const a=o.length>0?o.shift():await new Promise(e=>{r=e});if(!a)break;let t="";const l=new Map,u={get:e=>l.get(e),set:(e,n)=>{l.set(e,n)}},{events:m}=await s.runStreamed(d(a),{signal:n.signal,outputSchema:e.structuredOutputSchema?.schema||void 0});for await(const n of m){if(i)break;if("thread.started"!==n.type){if("turn.completed"===n.type){c&&(yield Zt({sessionId:c,model:e.model??"unknown",numTurns:p+1,usage:n.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0},result:t}));break}if("turn.failed"===n.type)throw new Error(n.error.message);if("error"===n.type)throw new Error(n.message);if("item.started"===n.type||"item.completed"===n.type){"item.completed"===n.type&&"agent_message"===n.item.type&&n.item.text&&(t=n.item.text);const e=ms(n,u);if(!e)continue;const a=Array.isArray(e)?e:[e];for(const e of a)yield e}}else c=n.thread_id,yield ls({sessionId:c,cwd:e.cwd,model:e.model})}p+=1}}finally{l()}}();return n.signal.addEventListener("abort",l,{once:!0}),{push:e=>{if(console.log("CodexRunner.loop.push:",JSON.stringify(e,null,2)),!i){if(r){const n=r;return r=null,void n(e)}o.push(e)}},events:u}}}function fs(e,n,a){e&&e(n,"AGENT",a)}const xs=["PreToolUse","PostToolUse","SessionStart","SessionEnd","UserPromptSubmit","Stop","SubagentStop","PreCompact","Notification","RepositoryInit"];function vs(e){const n={};for(const a of xs){const t=e[a];"function"==typeof t&&(n[a]=t,console.log(`[Hook Loader] ✓ Loaded hook: ${a}`))}const a=Object.keys(n).length;return 0===a?console.warn("[Hook Loader] No valid hooks found in module"):console.log(`[Hook Loader] Successfully loaded ${a} hook(s)`),n}class bs{static pool=new Map;static async create(e,n,a){const t=this.pool.get(n);if(t)return t;let s;if("claude"===e){const e=await async function(e){const{agentId:n,agentDir:a,logger:t}=e;if(!n||"default"===n)return{customSystemPrompt:void 0,customModel:void 0,customFallbackModel:void 0,customMaxTurns:void 0,customExtraArgs:void 0,customPermissionMode:void 0,customPlugins:[],systemPromptMode:"append",customPRPromptTemplate:void 0,prPromptMode:"append",customSdkMcpTools:void 0};try{fs(t,"info",`Loading agent: ${n}`);const e=await Qe({agentId:n,framework:"claude",agentDir:a});if(!e.claude)return fs(t,"warn",`No claude configuration found for agent ${n}`),{customSystemPrompt:void 0,customModel:void 0,customFallbackModel:void 0,customMaxTurns:void 0,customExtraArgs:void 0,customPermissionMode:void 0,customPlugins:[],systemPromptMode:"append",customPRPromptTemplate:void 0,prPromptMode:"append",customSdkMcpTools:void 0};const s=e.claude,i=s.plugins.map(e=>({type:"local",path:e})),o=a||Ze().resolveAgentDir(n),r=s.config.sdkMcpTools?.map(e=>me(o,"claude",e)),c={customSystemPrompt:s.systemPrompt,customModel:s.config.model,customFallbackModel:s.config.fallbackModel,customMaxTurns:s.config.maxTurns,customExtraArgs:s.config.extraArgs,customPermissionMode:s.config.settings?.permissionMode,customPlugins:i,systemPromptMode:s.config.systemPrompt?.mode??"append",customPRPromptTemplate:s.prPromptTemplate,prPromptMode:s.config.pullRequestPrompt?.mode??"append",customSdkMcpTools:r};return fs(t,"info",`Agent ${n} loaded successfully (${i.length} plugins)`),c}catch{return fs(t,"error",`Failed to load agent: ${n}`),{customSystemPrompt:void 0,customModel:void 0,customFallbackModel:void 0,customMaxTurns:void 0,customExtraArgs:void 0,customPermissionMode:void 0,customPlugins:[],systemPromptMode:"append",customPRPromptTemplate:void 0,prPromptMode:"append",customSdkMcpTools:void 0}}}({agentId:n,agentDir:a?.agentDir,logger:a?.logger});let t,i;a?.context&&n&&"default"!==n&&(t=await async function(e,n,a){if(e&&"default"!==e)try{const t=I(),s=n||t.resolveAgentDir(e),i=me(s,"claude");return await async function(e,n){const a=K(e,"hooks");if(!H(a))return{};const t=[K(a,"dist","index.mjs"),K(a,"dist","index.js"),K(a,"index.mjs"),K(a,"index.js")];let s=null;for(const e of t)if(H(e)){s=e;break}if(!s)return console.warn(`[Hook Loader] Hooks not built: ${a}`),console.warn("[Hook Loader] To build hooks, run:"),console.warn(`[Hook Loader] cd ${a}`),console.warn("[Hook Loader] npm install && npm run build"),console.warn("[Hook Loader] Or place hooks directly in:"),console.warn(`[Hook Loader] ${K(a,"index.js")} or ${K(a,"index.mjs")}`),{};try{console.log(`[Hook Loader] Loading hooks: ${s}`);const e=`${qe(s).href}?t=${Date.now()}`,a=await import(e);if("function"==typeof a.default){if(n)return console.log("[Hook Loader] Using factory pattern with AgentrixContext"),vs(a.default(n));console.warn("[Hook Loader] Factory function found but no context provided, skipping factory")}return vs(a)}catch(e){throw console.error(`[Hook Loader] Failed to load hooks from ${s}:`,e),new Error(`Hook loading failed: ${e instanceof Error?e.message:String(e)}`)}}(i,a)}catch(e){return void console.warn("[AgentRunners] Failed to load hooks:",e)}}(n,a.agentDir,a.context)),a?.context&&e.customSdkMcpTools&&e.customSdkMcpTools.length>0&&(i=await async function(e,n,a){const t={};for(const s of e)try{a&&a("info","MCP",`Loading SDK MCP tools from: ${s}`);const e=await import(s),i=e.default||e;if(!i){a&&a("warn","MCP",`No default export found in ${s}`);continue}const o="function"==typeof i?i(n):i,r=o.name;t[r]=o,a&&a("info","MCP",`Loaded MCP server: ${r}`)}catch(e){a&&a("error","MCP",`Failed to load SDK MCP tools from ${s}: ${e instanceof Error?e.message:String(e)}`)}return t}(e.customSdkMcpTools,a.context,a.logger)),s=new ps(n,e,t,i)}else s=new hs;return this.pool.set(n,s),s}static release(e){this.pool.delete(e)}static releaseAll(){this.pool.clear()}}class ys{constructor(e){this.workingDirectory=e}async listFiles(e=3){const n=[];return this.listFilesRecursively(this.workingDirectory,n,"",e,0),n}async readFile(e){try{const n=z.join(this.workingDirectory,e);return L.existsSync(n)?L.readFileSync(n,"utf-8"):null}catch{return null}}async fileExists(e){const n=z.join(this.workingDirectory,e);return L.existsSync(n)}listFilesRecursively(e,n,a,t,s){if(!(s>t))try{const i=L.readdirSync(e,{withFileTypes:!0});for(const o of i){const i=a?`${a}/${o.name}`:o.name;o.isDirectory()?T.includes(o.name)||this.listFilesRecursively(z.join(e,o.name),n,i,t,s+1):o.isFile()&&n.push(i)}}catch(e){}}}class ws{constructor(e){this.params=e}state=null;autoCommitPolicy="enabled";async setup(){const{options:e,handlers:n}=this.params,{userId:a,taskId:t,cwd:s}=e;if(!s)throw new Error("[WORKSPACE] Missing cwd for workspace setup");const i=D.getWorkspaceState(a,t),o=e.repositorySourceType,r={...e,repositorySourceType:o},{initialCommitHash:c,isGitRepository:p,autoCommitPolicy:l}=await this.ensureWorkspace(r,n,i?.initialCommitHash);await D.writeWorkspaceState(a,t,{initialized:!0,initializedAt:(new Date).toISOString(),cwd:s,repositorySourceType:r.repositorySourceType,userCwd:e.userCwd,forceUserCwd:e.forceUserCwd,gitUrl:e.gitUrl,baseBranch:e.baseBranch,taskRepositoryId:e.taskRepositoryId,initialCommitHash:c});const d=await async function(e,n,a,t,s={}){return async function(e,n,a,t,s,i={}){if(!await rt(e))return{currentCommitHash:"",hadUncommittedChanges:!1,hasNewCommits:!1,lastSentCommitHash:void 0,patchPath:"",diffStats:void 0};const o=await lt(e),r=o,c=i.autoCommitOnDirty??!0;o&&c&&await gt(e,t);const p=await dt(e),l=s||D.getWorkspaceState(n,a)?.initialCommitHash;if(!l)throw new Error(`Initial commit hash not found for task ${a}`);const d=await D.readLastSentCommitHash(n,a),u=p!==(d??l),m=D.resolveDataDir(n,a);return{currentCommitHash:p,hadUncommittedChanges:r,hasNewCommits:u,lastSentCommitHash:d??void 0,patchPath:await _t(e,l,p,m),diffStats:await ht(e,l,p)}}(e,n,a,Rt("recover from previous session",a),t,s)}(s,a,t,c,{autoCommitOnDirty:"enabled"===l});return this.state={cwd:s,initialCommitHash:c,isGitRepository:p,gitStateResult:d},this.autoCommitPolicy=l,p&&!e.taskRepositoryId&&await async function(e,n){try{const a=await async function(e){try{const n=Ke(e),a=(await n.getRemotes(!0)).find(e=>"origin"===e.name);if(!a?.refs?.fetch)return null;const t=a.refs.fetch,s=t.match(/^git@([^:]+):(.+)\/(.+?)(?:\.git)?$/);if(s){const[,e,n,a]=s;return{url:t,host:e.split("-")[0],owner:n,repo:a}}const i=t.match(/^https?:\/\/([^/]+)\/(.+)\/(.+?)(?:\.git)?$/);if(i){const[,e,n,a]=i;return{url:t,host:e,owner:n,repo:a}}return null}catch(e){return console.error("[GIT] Failed to get remote info:",e),null}}(e);if(!a)return void console.log("[REPO] No origin remote found, skipping repository association");if(!n?.onRepositoryDetected)return;console.log(`[REPO] Detected remote: ${a.host}/${a.owner}/${a.repo}`),n.onRepositoryDetected(a)}catch(e){console.error("[REPO] Failed to send repository association:",e)}}(s,n),this.state}getState(){if(!this.state)throw new Error("[WORKSPACE] Workspace not initialized");return this.state}getCwd(){return this.getState().cwd}getInitialCommitHash(){return this.getState().initialCommitHash}getGitStateResult(){return this.getState().gitStateResult}async prepareResultArtifacts(e={}){const{cwd:n,initialCommitHash:a,isGitRepository:t}=this.getState(),{userId:s,taskId:i}=this.params.options;if(!t||!a)return{};const o=e.autoCommitOnDirty??"enabled"===this.autoCommitPolicy;if(await lt(n)&&o)try{const e=Rt("result update",i);await gt(n,e)}catch(n){e.onCommitError?.(n)}const r=await dt(n);try{await async function(e,n,a,t,s){return _t(e,t,s,D.resolveDataDir(n,a))}(n,s,i,a,r)}catch(n){e.onPatchError?.(n)}const c=await ht(n,a,r);if(0===c.files.length)return{currentCommitHash:r};const p=await async function(e){const n=new ys(e);return S(n)}(n),l=await D.readLastSentCommitHash(s,i);return l&&l===r?{currentCommitHash:r}:{currentCommitHash:r,artifacts:{commitHash:r,stats:c,preview:p}}}async ensureWorkspace(e,n,a){const t=e.repositorySourceType;return"git-server"===t?this.ensureGitServerWorkspace(e,n,a):"directory"===t?this.ensureDirectoryWorkspace(e,n,a):this.ensureTemporaryWorkspace(e,n,a)}async ensureGitServerWorkspace(e,n,a){const{cwd:t,gitUrl:s,taskId:i,baseBranch:o,gitServerId:r}=e;if(!s)throw new Error("[WORKSPACE] gitUrl is required for git-server mode");const c=await rt(t),p=mt(t);if(!c){if(!p)throw new Error(`[WORKSPACE] Directory ${t} exists but is not a git repository.`);const e=await async function(e,n,a,t,s){const i=St(a),o=await rt(e);if(!mt(e)&&!o)throw new Error(`Directory ${e} exists but is not a git repository`);const r=await Tt(s);return mt(e)?(r?(console.log("[GIT] Using GIT_ASKPASS credential injection for clone"),await async function(e,n,a){const t=ge(a);te(t)||re(t,{recursive:!0});const s=wt();try{await ot("git",["clone",n,a],{env:kt(s,e)})}finally{le(s)}}(r,n,e),s&&await Et(e,s)):await async function(e,n){const a=ge(n);te(a)||re(a,{recursive:!0});const t=Ke();await t.clone(e,n)}(n,e),await pt(e,i,t),await dt(e)):(await xt(e,"origin",n),r&&(console.log("[GIT] Using GIT_ASKPASS credential injection for fetch"),await async function(e,n){const a=wt();try{await ot("git",["fetch","origin"],{cwd:n,env:kt(a,e)})}finally{le(a)}}(r,e),s&&await Et(e,s)),await pt(e,i,t),await dt(e))}(t,s,i,o,r)||await dt(t);return{initialCommitHash:this.resolveInitialCommitHash(a,e,"none"),isGitRepository:!0,autoCommitPolicy:"enabled"}}return await xt(t,"origin",s),this.tryResolveDirtyRepo(e,n,a)}async ensureDirectoryWorkspace(e,n,a){const{cwd:t,taskId:s,userCwd:i}=e;if(await rt(t))return this.tryResolveDirtyRepo(e,n,a);if(!mt(t))return{initialCommitHash:"",isGitRepository:!1,autoCommitPolicy:"enabled"};{if(!i)return{initialCommitHash:"",isGitRepository:!1,autoCommitPolicy:"enabled"};const e=i.replace(/^~/,J());if(mt(e))return{initialCommitHash:"",isGitRepository:!1,autoCommitPolicy:"enabled"};if(!await rt(e))return{initialCommitHash:"",isGitRepository:!1,autoCommitPolicy:"enabled"};await ut(e)||await ct(e),await async function(e,n,a){const t=e.replace(/^~/,J());if(!await rt(t))throw new Error(`Directory ${t} is not a git repository. Worktrees can only be created from existing git repositories.`);if(!await ut(t))throw new Error(`Cannot create worktree: repository at ${t} has no commits. Please create an initial commit first: cd ${t} && git add . && git commit -m 'Initial commit'`);const s=St(a),i=(await async function(e){const n=Ke(e),a=(await n.raw(["worktree","list","--porcelain"])).trim().split("\n").filter(Boolean),t=[];let s=null;for(const e of a)if(e.startsWith("worktree "))s&&t.push(s),s={path:e.replace("worktree ","").trim(),branch:null,commit:"",isMain:0===t.length};else if(s)if(e.startsWith("HEAD "))s.commit=e.replace("HEAD ","").trim();else{if(e.startsWith("branch ")){const n=e.replace("branch ","").trim();s.branch=n.replace("refs/heads/","");continue}e.startsWith("detached")&&(s.branch=null)}return s&&t.push(s),t}(t)).find(e=>e.path===n);if(i){if(i.branch&&i.branch!==s)throw new Error(`Worktree at ${n} is already attached to branch ${i.branch}. Remove it before retrying: git worktree remove ${n}`);return{initialCommitHash:await dt(n)}}const o=Ke(t),r=(await o.branchLocal()).all.includes(s);if(te(n)&&!mt(n))throw new Error(`Worktree directory already exists at ${n}. This may be from a previous task. To clean up: git worktree remove ${n} OR rm -rf ${n}`);try{r?await o.raw(["worktree","add",n,s]):await async function(e,n,a,t="HEAD"){const s=ge(n);if(te(s)||re(s,{recursive:!0}),te(n)&&!mt(n))throw new Error(`Worktree directory already exists at ${n}`);const i=Ke(e);await i.raw(["worktree","add","-b",a,n,t])}(t,n,s,"HEAD")}catch(e){try{await async function(e,n,a=!1){const t=Ke(e),s=["worktree","remove"];a&&s.push("--force"),s.push(n),await t.raw(s)}(t,n,!0)}catch{}throw e}return{initialCommitHash:await dt(n)}}(e,t,s)}return this.tryResolveDirtyRepo(e,n,a)}async ensureTemporaryWorkspace(e,n,a){const{cwd:t,taskId:s}=e;if(!await rt(t)){await async function(e,n,a){return{initialCommitHash:await At(e,n,a)}}(t,s,n),await pt(t,`agentrix/${s}`,e.baseBranch);const i=await dt(t);return{initialCommitHash:this.resolveInitialCommitHash(a,i,"none"),isGitRepository:!0,autoCommitPolicy:"enabled"}}return this.tryResolveDirtyRepo(e,n,a)}async tryResolveDirtyRepo(e,n,a){let t,s=null,i="enabled";if(await async function(e){return!!await rt(e)&&await lt(e)}(e.cwd)){const a=n?.onUncommittedChanges?await n.onUncommittedChanges():"Ignore";if(await async function(e,n){switch(n){case"Ignore":console.log("[GIT] User chose to ignore uncommitted changes");break;case"Commit":console.log("[GIT] Auto-committing uncommitted changes"),await gt(e,"WIP: Auto-commit before task");break;case"Stash":console.log("[GIT] Stashing uncommitted changes"),await async function(e){const n=Ke(e);await n.stash(["push"])}(e);break;case"Abort":throw new Error("Task aborted by user due to uncommitted changes")}}(e.cwd,a),"Abort"===a)throw new Error("Task aborted by user due to uncommitted changes");s=a,"Ignore"===a&&(i="disabled_by_ignore")}if(await ut(e.cwd)||await ct(e.cwd),"Ignore"===s){const n=`agentrix/${e.taskId}`;t=await ft(e.cwd)===n?"none":"kept"}else t=await this.tryResolveBranchMismatch(e);const o=await dt(e.cwd);return{initialCommitHash:this.resolveInitialCommitHash(a,o,t),isGitRepository:!0,autoCommitPolicy:i}}resolveInitialCommitHash(e,n,a){return e?"kept"===a?n:e:n}async tryResolveBranchMismatch(e){const n=`agentrix/${e.taskId}`;return await ft(e.cwd)===n?"none":(await pt(e.cwd,n,e.baseBranch),"switched")}}const ks=Ae.object({title:Ae.string().describe("Concise PR title following conventional commits format (feat/fix/docs/refactor/test/chore: description), maximum 50 characters"),description:Ae.string().describe("Detailed PR description explaining: what changed, why these changes were necessary, any important technical decisions, and impact on existing functionality"),userMessage:Ae.string().describe("Friendly message to display to the user, summarizing the PR creation. Should be concise and informative.")}),Is=Re(ks,{target:"draft-07"}),Ss=Re(ks);function Ts(e){if("success"!==e.subtype)throw new Error("PR response failed before structured output was returned");const n=e;return n.structured_output?ks.parse(n.structured_output):function(e){if(!e.trim())throw new Error("PR response was empty");const n=function(e){const n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);return n?n[1].trim():e.trim()}(e),a=JSON.parse(n);return ks.parse(a)}(n.result??"")}class Es{chain=Promise.resolve();run(e){const n=this.chain.then(e,e);return this.chain=n.then(()=>{},()=>{}),n}}class Cs{constructor(e,n,a){this.credentials=e,this.options=n,this.workingDirectory=a;const t=this.options.input,{taskId:s,userId:i}=t;this.logger=N({type:"worker",taskId:s}),this.currentAgentSessionId="agentSessionId"in t?t.agentSessionId:void 0;const o=t.taskAgents||[];this.taskAgentsMap=new Map(o.map(e=>[e.id,e]));const r=this.taskAgentsMap.size>1;this.primaryAgentId=r?"planner":t.agentId,this.primaryAgentName=r?"planner":this.taskAgentsMap.get(t.agentId)?.name??"unknown";const c=this.createWorkerClientConfig(i,s,a),p=D.resolveDataDir(i,s);this.historyDb=wa({dataDir:p,taskId:s}),this.workClient=new Ma(c.config,{...c.handlers,historyDb:this.historyDb}),this.coordinator=this.createMessageCoordinator(this.workClient,this.options.idleTimeoutSecond),this.agentContext=new $a({logger:this.logger,socketClient:this.workClient.client,taskId:t.taskId,userId:t.userId,chatId:t.chatId,rootTaskId:t.rootTaskId||t.taskId,parentTaskId:t.parentTaskId||null,workingDirectory:this.workingDirectory,taskAgents:t.taskAgents||[],serverUrl:D.serverUrl,taskDataKey:this.options.dataEncryptionKey}),this.agentrixTools=this.createAgentrixTools();const l={...It(this.options.input),cwd:this.workingDirectory};this.workspace=new ws({options:l,handlers:this.createWorkspaceHandlers(this.workClient)})}abortController=new AbortController;isStopping=!1;askUserAwaiter=new Map;messageFilter=Oa();logger;workClient;workspace;coordinator;agentContext;runner;agentQueues=new Map;currentAgentSessionId;currentGroupId=null;historyDb;chatHistoryDb=null;agentrixTools;pendingNavigateTaskId=null;pendingPermissions=new Map;grantedPermissions=new Set;taskAgentsMap;messageSavedListener=null;messageDebounceHandle=null;messageDebounceMs=1e4;lastProcessedSequence=0;primarySessionReady=!1;pendingPrimaryLastSequence=null;primaryAgentId;primaryAgentName;newMessageGroupId(){return`group-${crypto.randomUUID()}`}refreshGroupId(){this.currentGroupId=this.newMessageGroupId()}shouldProcessMessage(e){const n=e.message,a=this.getRunnerMode(),t="group_chat"===a||"group_work"===a,s=w(n);return!!E(n)||!!C(n)||!(!k(n)&&!s)&&"agent"!==e.senderType&&(t?e.senderId!==this.primaryAgentId:!!s||"system"===e.senderType&&"user"===n.type||"user"===n.type)}shouldDropHeartbeatWhileBusy(){return this.coordinator.isActivelyExecuting()}async processPendingMessages(){const e=this.historyDb.pageMessagesAfter(this.lastProcessedSequence,100),n=[];for(const a of e.data)this.lastProcessedSequence=a.localSequence,this.shouldProcessMessage(a)&&n.push(a);if(n.length>0){this.deduplicateHeartbeats(n);const e=this.mergeConsecutiveHumanMessages(n),a=this.getRunnerMode();"group_chat"===a||"group_work"===a?await this.processMessagesAsGroup(e):await this.processMessagesIndividually(e)}e.hasMore&&await this.processPendingMessages()}deduplicateHeartbeats(e){let n=-1;for(let a=e.length-1;a>=0;a--)E(e[a].message)&&(-1===n?n=a:(e.splice(a,1),n--))}mergeConsecutiveHumanMessages(e){if(0===e.length)return[];const n=[];let a=0;for(;a<e.length;){const t=e[a];if("human"===t.senderType){const s=[t];for(;a+1<e.length;){const n=e[a+1];if("human"!==n.senderType||n.senderId!==t.senderId)break;s.push(n),a++}1===s.length?n.push(t):n.push(this.createMergedHumanMessage(s))}else n.push(t);a++}return n}createMergedHumanMessage(e){const n=[],a=[];for(const t of e){const e=t.message;if(!k(e)||"user"!==e.type)continue;const s=e.message.content;if("string"==typeof s)n.push(s);else if(Array.isArray(s))for(const e of s)"text"===e.type?n.push(e.text):a.push(e)}const t=n.join(""),s=a.length>0?[{type:"text",text:t},...a]:t,i=e[0],o=e[e.length-1];return{localSequence:o.localSequence,eventId:o.eventId,senderType:i.senderType,senderId:i.senderId,senderName:i.senderName,createdAt:o.createdAt,message:{type:"user",message:{role:"user",content:s},parent_tool_use_id:null,session_id:i.message?.session_id||""}}}async processMessagesAsGroup(e){const n=[],a=[];for(const t of e){const e=ja(t);if(e){const t=e.message.content;if("string"==typeof t)n.push(t);else if(Array.isArray(t))for(const e of t)"text"===e.type?n.push(e.text):a.push(e)}}if(0===n.length)return;const t=Math.max(...e.map(e=>e.localSequence)),s=n.join(" "),i={type:"user",message:{role:"user",content:a.length>0?[{type:"text",text:s},...a]:s},parent_tool_use_id:null,session_id:""};i.__localSequence=t,await this.coordinator.enqueue(i)}async processMessagesIndividually(e){for(const n of e){const e=this.formatSingleMessage(n);e&&(e.__localSequence=n.localSequence,await this.coordinator.enqueue(e))}}formatSingleMessage(e){const n=e.message;if(E(n))return{type:"user",message:{role:"user",content:`[heartbeat] You are being awakened by a scheduled heartbeat at ${n.timestamp}. Check your workspace for any pending tasks, reminders, or scheduled work. If nothing to do, respond briefly and exit.`},parent_tool_use_id:null,session_id:""};if(C(n)){const e=n;let a=`[reminder from shadow] ${e.content}`;return e.filePath&&(a+=`\nDetailed analysis: ${e.filePath}`),{type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:""}}return k(n)&&"user"===n.type?n:null}setupMessageSavedListener(){this.messageSavedListener=()=>{this.triggerMessageProcessing()},this.historyDb.on("message-saved",this.messageSavedListener)}triggerMessageProcessing(){const e=this.getRunnerMode();"group_chat"===e||"group_work"===e?this.scheduleProcessPendingMessages():this.processPendingMessages()}scheduleProcessPendingMessages(){this.coordinator?.setDebouncing(!0),this.messageDebounceHandle&&clearTimeout(this.messageDebounceHandle),this.messageDebounceHandle=setTimeout(async()=>{this.messageDebounceHandle=null,await this.processPendingMessages(),this.coordinator?.setDebouncing(!1)},this.messageDebounceMs)}async start(){let e="completed";try{await this.initialize(),await this.handleEvent(),await this.runClaude()}catch(n){if(!(n instanceof Be)){e="error",this.log("warn","AGENT","Fatal error:",n);const a=n instanceof Error?n.message:String(n);await this.reportFatalError(a)}}finally{await this.exitWorker(e)}}async initialize(){const e=this.options.input;await this.workClient.connect(),this.workClient.sendWorkerInitializing();const n=await bs.create("claude",e.agentId,{agentDir:e.agentDir,logger:this.log.bind(this),context:this.agentContext});this.runner=n,await this.workspace.setup(),await this.registerWithDaemon(this.workingDirectory),this.setEnvironmentVariables(),this.lastProcessedSequence=this.historyDb.getAgentLastSequences().get(this.primaryAgentId)??0,this.log("info","HISTORY",`Starting from sequence ${this.lastProcessedSequence} (tracking: ${this.primaryAgentId})`),this.currentAgentSessionId&&(this.historyDb.upsertAgentSession(this.primaryAgentId,this.currentAgentSessionId),this.primarySessionReady=!0),this.setupMessageSavedListener(),this.workClient.sendWorkerInitialized()}createWorkspaceHandlers(e){return{onRepositoryDetected:n=>{e.associateRepository(n.host,n.owner,n.repo,n.url)},onRepositoryInit:async e=>{await(this.runner?.executeHook("RepositoryInit",e))},onUncommittedChanges:this.onUncommittedChanges.bind(this),onBranchMismatch:this.onBranchMismatch.bind(this)}}async registerWithDaemon(e){const n=this.options.input.taskId,a=await tn(n,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});a.error?this.log("warn","DAEMON",`Failed to report session ${n}:`,a.error):this.log("info","DAEMON",`Session ${n} registered`)}setEnvironmentVariables(){this.options.input.environmentVariables&&Object.entries(this.options.input.environmentVariables).forEach(([e,n])=>{null!=n&&(process.env[e]=String(n))}),this.options.input.api_base_url&&(process.env.ANTHROPIC_BASE_URL=this.options.input.api_base_url),this.options.input.api_key&&(process.env.ANTHROPIC_AUTH_TOKEN=this.options.input.api_key)}createMessageCoordinator(e,n){const a=1e3*Math.max(0,n??0);return this.coordinator=new Pt({workerType:"claude",workClient:e,onCommandMessageProcessed:e=>{this.markPrimaryMessageProcessed(e)},handlers:{onNormalMessage:async e=>e,onBashCommand:async(e,n)=>{await this.executeBashCommand(e)},onMergeRequest:async e=>{await this.executeMergeRequest()},onMergePr:async()=>{await this.executeMergePr()},onNewSession:async()=>{await this.executeNewSession()}},logger:(e,n,a)=>{const t=e;this.log(t,n,a)},idleTimeoutMs:a,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}handleEvent(){const e=this.options.input.event,n=this.options.input.eventData;if("sub-task-result-updated"===e){const e=n,a=Pa(e,this.options.dataEncryptionKey);this.historyDb.saveMessage({eventId:e.eventId||`sub-task-${Date.now()}`,message:a,senderType:"system",senderId:"system",senderName:"system"})}this.triggerMessageProcessing()}async executeMergeRequest(){this.log("info","MERGE","Executing merge-request command");const e=this.getRunnerMode(),n="group_chat"===e||"group_work"===e;try{if(!this.options.input.repositoryId){const e="Cannot create PR: task has no git repository configured.";return this.log("warn","MERGE","No repositoryId found in task input"),void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}await lt(this.workingDirectory)&&(await gt(this.workingDirectory,"Checkpoint for PR generation"),this.log("info","MERGE","Auto-committed changes"));const e=await dt(this.workingDirectory),s=this.workspace.getInitialCommitHash();if(!s){const e="Cannot create PR: initial commit hash is missing.";return this.log("error","MERGE",e),void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}if(0===(await ht(this.workingDirectory,s,e)).files.length){const e="No changes to create PR: no files changed since task started";return void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}const i=await ft(this.workingDirectory);this.log("info","MERGE",`Pushing branch ${i} to remote`),await Ct(this.workingDirectory,i,!1,this.options.input.gitServerId),this.log("info","MERGE","Successfully pushed branch to remote");const o=this.runner?.getAgentConfiguration(),r=$t(s,(o?.customPRPromptTemplate?(a=o.customPRPromptTemplate,t={initialCommitHash:s,currentCommitHash:"",branchName:""},a.replace(/\{\{initialCommitHash\}\}/g,t.initialCommitHash).replace(/\{\{currentCommitHash\}\}/g,t.currentCommitHash).replace(/\{\{branchName\}\}/g,t.branchName)):void 0)??void 0);this.log("debug","MERGE",`PR prompt: ${r.substring(0,200)}...`);const c=this.runner;let p=null;const l=c.runStreamed(r,{cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),structuredOutputSchema:{type:"json_schema",schema:Is}});for await(const e of l){if(this.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){p=e;break}const a=n?e:this.messageFilter.filter(e);null!==a&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),a,{groupId:this.currentGroupId??void 0})}if(!p)throw new Error("Merge-request did not return a result message");const d=Ts(p),u=await this.workClient.sendMergeRequest(d.title,d.description);this.workClient.sendAssistantMessage(`${d.userMessage}\n\n✅ Pull request created successfully!\nNumber: #${u.pullRequestNumber}\nURL: ${u.pullRequestUrl}`,{groupId:this.currentGroupId??void 0})}catch(e){const n=e instanceof Error?e.message:String(e);this.log("error","MERGE","Merge-request failed:",e),this.workClient.sendSystemErrorMessage(`❌ Merge-request failed: ${n}\n\nPlease check git status and try again, or create the PR manually.`,{groupId:this.currentGroupId??void 0})}var a,t}async executeBashCommand(e){this.log("info","BASH",`Executing command: ${e}`);const n={senderType:"agent",senderId:"bash",senderName:"bash"},a=await Dt(e,this.workingDirectory,{onOutput:e=>{this.workClient.sendTaskMessage(n,e,{groupId:this.currentGroupId??void 0})},onComplete:e=>{this.log("info","BASH",`Command completed with exit code: ${e}`)}});this.log("info","BASH",`Worker ready after command execution (exit code: ${a})`)}async executeMergePr(){await jt({workingDirectory:this.workingDirectory,workClient:this.workClient,repositoryId:this.options.input.repositoryId,gitServerId:this.options.input.gitServerId,logger:this.logger,askUser:e=>this.askUser(e,{onTimeout:"abort_task"})})}async executeNewSession(){this.log("info","SESSION","Executing new-session: clearing agentSessionId"),this.currentAgentSessionId=void 0,this.primarySessionReady=!1,this.workClient.sendResetTaskSession(),this.log("info","SESSION","Session reset sent, stopping task for clean restart"),this.stopTask("event")}async runClaude(){this.log("info","AGENT",`Starting Claude agent for task ${this.taskId}`);const e=this.currentAgentSessionId,n=this.runner,a=this.getRunnerModeConfig(),t="group_chat"===a.mode||"group_work"===a.mode,s=this.createPermissionHandler(),i=this.buildSystemHooks({trackBackgroundTasks:!0,trackPrimaryAgentStop:!0}),o=n.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:e,abortController:this.abortController,stderr:e=>{this.log("debug","SDK",e)},modeConfig:a,agentrixTools:this.agentrixTools,canUseTool:s,hooks:i,maxTurns:this.options.input.maxTurns??void 0});(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(!e){if(this.isStopping)break;continue}o.push(e);const n=e.__localSequence;void 0!==n&&(this.markPrimaryMessageProcessed(n),delete e.__localSequence)}}catch(e){this.log("error","AGENT","Message pump failed:",e),this.stopTask("event")}})();for await(const e of o.events){if(this.logger.debug(`sdk message: ${JSON.stringify(e)}`),"system"===e.type&&"init"===e.subtype){this.workClient.sendUpdateTaskAgentSessionId(e.session_id),this.currentAgentSessionId=e.session_id,this.historyDb.upsertAgentSession(this.primaryAgentId,e.session_id),this.primarySessionReady=!0,null!==this.pendingPrimaryLastSequence&&(this.historyDb.updateAgentLastSequence(this.primaryAgentId,this.pendingPrimaryLastSequence),this.pendingPrimaryLastSequence=null),this.refreshGroupId(),this.updateAgentRunning(!0);continue}if("result"===e.type){await this.handleSdkResultMessage(e),this.updateAgentRunning(!1);continue}"system"===e.type&&"task_notification"===e.subtype&&this.handleBackgroundTaskNotification(e);const n=t?e:this.messageFilter.filter(e);null!==n&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}this.log("info","AGENT",`Claude agent finished for task ${this.taskId}`)}updateAgentRunning(e){this.coordinator?.setAgentRunning(this.primaryAgentId,this.primaryAgentName,e)}markPrimaryMessageProcessed(e){this.historyDb.updateAgentLastSequence(this.primaryAgentId,e),this.primarySessionReady||(this.pendingPrimaryLastSequence=null===this.pendingPrimaryLastSequence?e:Math.max(this.pendingPrimaryLastSequence,e))}stopTask(e){this.isStopping||(this.isStopping=!0,"idle"===e?this.log("info","AGENT","Idle timeout reached, stopping task"):"ask_user_timeout"===e&&this.log("info","AGENT","ask_user timed out, stopping task"),this.askUserAwaiter.clear(),this.coordinator?.stop(),this.abortController.abort())}async handleAskUserQuestionPermission(e){const n=e,a=Array.isArray(n.questions)?n.questions:[];if(0===a.length)return this.log("warn","PERMISSION","AskUserQuestion missing questions"),{behavior:"deny",message:"AskUserQuestion missing questions"};const t=a.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]}));try{const e=await this.askUser(t),s={};for(let n=0;n<a.length;n+=1){const t=a[n]?.question;if(!t)continue;const i=e.answers?.[n];"string"==typeof i&&(s[t]=i)}return{behavior:"allow",updatedInput:{...n,answers:s}}}catch(e){return this.log("warn","PERMISSION",`AskUserQuestion failed: ${e}`),{behavior:"deny",message:"AskUserQuestion failed"}}}createPermissionHandler(){return async(e,n)=>{if("AskUserQuestion"===e)return this.handleAskUserQuestionPermission(n);if(this.grantedPermissions.has(e))return this.log("info","PERMISSION",`Tool "${e}" already granted, skipping`),{behavior:"allow",updatedInput:n};const a=this.pendingPermissions.get(e);if(a)return this.log("info","PERMISSION",`Tool "${e}" has pending request, waiting...`),"allow"===await a?{behavior:"allow",updatedInput:n}:{behavior:"deny",message:"Permission denied by user"};let t;this.log("info","PERMISSION",`Requesting permission for "${e}"`);const s=new Promise(e=>{t=e});this.pendingPermissions.set(e,s);try{const a=await this.requestToolPermission(e);return t(a),"allow"===a?(this.grantedPermissions.add(e),{behavior:"allow",updatedInput:n}):{behavior:"deny",message:"Permission denied by user"}}catch(e){return t("deny"),{behavior:"deny",message:"Permission request failed"}}finally{this.pendingPermissions.delete(e)}}}async requestToolPermission(e){const n=[{question:`Tool "${e}" is requesting permission to execute. Allow this operation?`,header:"Permission",multiSelect:!1,options:[{label:"Allow",description:"Allow this tool to execute"},{label:"Deny",description:"Deny this tool execution"}]}];try{return"Allow"===(await this.askUser(n,{onTimeout:"abort_task"})).answers[0]?"allow":"deny"}catch(e){return this.log("warn","PERMISSION",`Permission request failed: ${e}`),"deny"}}async askUser(e,n={}){const a=this.workClient;return qt(e,this.askUserAwaiter,{sendAskUser:e=>a.sendAskUser(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0}),sendAskUserResponse:(e,n)=>a.sendAskUserResponse(e,n),onTimeoutMessage:e=>a.sendAssistantMessage(e,{groupId:this.currentGroupId??void 0}),stopTask:e=>this.stopTask(e)},n)}async onUncommittedChanges(){const e=[{question:"Uncommitted changes detected in the working directory. How would you like to proceed?",header:"Git Status",multiSelect:!1,options:[{label:"Ignore",description:"Keep changes on current branch and continue without switching"},{label:"Commit",description:"Commit on current branch, then switch to task branch"},{label:"Stash",description:"Stash changes, then switch to task branch"},{label:"Abort",description:"Cancel the task, do nothing"}]}];try{const n=(await this.askUser(e,{onTimeout:"abort_task"})).answers[0];return n.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${n}, defaulting to Abort`),"Abort"):{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort"}catch(e){return this.log("warn","GIT",`Failed to get user response for uncommitted changes: ${e}`),"Abort"}}async onBranchMismatch(e){const n=[{label:"Switch",description:`Checkout ${e.expectedBranch} and continue`},{label:"Keep",description:`Continue on ${e.currentBranch} (may affect task history)`},{label:"Abort",description:"Cancel the task"}],a=[{question:`Branch mismatch detected. Current: ${e.currentBranch}. Expected: ${e.expectedBranch}. How would you like to proceed?`,header:"Git Branch",multiSelect:!1,options:n}];try{const e=(await this.askUser(a,{onTimeout:"abort_task"})).answers[0];return e.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${e}, defaulting to Abort`),"Abort"):{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[e]||"Abort"}catch(e){return this.log("warn","GIT",`Failed to get user response for branch mismatch: ${e}`),"Abort"}}getRunnerMode(){const e=this.taskAgentsMap.size>1,n=this.options.input.taskType,a=!(!process.env.AGENTRIX_COMPANION_HOME&&!process.env.AGENTRIX_COMPANION_WORKSPACE);return"shadow"===n?"companion_shadow":a&&"chat"===n?"companion_chat":e?"chat"===n?"group_chat":"group_work":"chat"===n?"chat":"work"}getGroupAgents(){if(!(this.taskAgentsMap.size<=1))return Array.from(this.taskAgentsMap.values()).map(e=>({id:e.id,name:e.name,description:e.description}))}getRunnerModeConfig(){return{mode:this.getRunnerMode(),supportChangeTitle:this.supportChangeTitle,groupAgents:this.getGroupAgents()}}get supportChangeTitle(){const e=this.options.input.customTitle;return!("string"==typeof e&&e.trim().length>0)}createAgentrixTools(){const e=this.taskAgentsMap.size>1;if("companion_shadow"===this.getRunnerMode()){const e=this.options.input.chatId,n=this.options.input.userId,a=D.resolveDataDir(n,e);this.chatHistoryDb=wa({dataDir:a,taskId:e})}return{createTask:Va(n={agentContext:this.agentContext,workClient:this.workClient,uploadFile:e=>this.agentContext.uploadFile(e),agentId:this.primaryAgentId,isGroup:e,historyDb:this.historyDb,chatHistoryDb:this.chatHistoryDb??void 0,askUser:e=>this.askUser(e),log:this.log.bind(this),invokeAgent:(e,n)=>this.invokeAgent(e,n),assign:(e,n,a)=>this.assignWork(e,n,a),setPendingNavigateTaskId:e=>{this.pendingNavigateTaskId=e}}),createSoloTask:Xa(n),createGroupTask:Ya(n),replyToSubTask:Ha(n),changeTaskTitle:Wa(n),askUser:Ja(n),getTaskHistory:za(n),getTaskAgents:Ba(n),listSubTask:Ka(n),invoke:Qa(n),assign:et(n),updateAgentInfo:Za(n),sendReminder:tt(n),listTasks:nt(n),readConversation:at(n),uploadFile:st(n),listAgents:it(n)};var n}resolveTaskAgentName(e){return this.taskAgentsMap.get(e)?.name||""}getChatSenderMeta(){return{senderType:"agent",senderId:this.primaryAgentId,senderName:this.primaryAgentName}}sendAgentErrorMessage(e,n,a,t){const s=n||e,i={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:`System Error\n\n${s}: ${a}`}]}};this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:s},i,{groupId:t?.groupId})}async invokeAgent(e,n){const a=this.buildSubAgentHistoryContext(e,n);if(!a)return!1;const t=this.taskAgentsMap.get(e),s=t?.type||"claude";let i=this.agentQueues.get(e);i||(i=new Es,this.agentQueues.set(e,i));const o=this.resolveTaskAgentName(e),r=this.getRunnerMode(),c="group_chat"===r||"group_work"===r;return i.run(async()=>{this.coordinator?.setAgentRunning(e,o,!0);const n=this.newMessageGroupId();try{const t=await bs.create(s,e,{logger:this.log.bind(this),context:this.agentContext}),i=this.getGroupAgents()||[],r={mode:"reply",supportChangeTitle:!1,groupAgents:i},p=this.createPermissionHandler(),l=this.buildSystemHooks({trackBackgroundTasks:!1}),d=Oa(),u=t.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:a.sessionId,abortController:this.abortController,modeConfig:r,agentrixTools:this.agentrixTools,canUseTool:p,hooks:l,maxTurns:this.options.input.maxTurns??void 0});let m=a.message;if("codex"===s&&!a.sessionId){const n=[Vt(e,i),"=== CONVERSATION STREAM START FROM HERE ===",Qt(a.message)].join("\n\n").trim();n&&(m=n)}u.push(m);const g=a.lastSequence;let h=!1;a.sessionId&&(this.historyDb.updateAgentLastSequence(e,g),h=!0);let f=!1;for await(const a of u.events){if("system"===a.type&&"init"===a.subtype){this.historyDb?.upsertAgentSession(e,a.session_id),h||(this.historyDb.updateAgentLastSequence(e,g),h=!0);continue}if("result"===a.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},a,{groupId:n}),f=!0;break}const t=c?a:d.filter(a);t&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},t,{groupId:n})}}catch(n){this.log("error","INVOKE",`Invoke failed for ${e}:`,n)}finally{this.coordinator?.setAgentRunning(e,o,!1)}}),!0}async assignWork(e,n,a){const t=this.taskAgentsMap.get(e),s=t?.type||"claude";let i=this.agentQueues.get(e);i||(i=new Es,this.agentQueues.set(e,i));const o=this.resolveTaskAgentName(e),r=this.getRunnerMode(),c="group_chat"===r||"group_work"===r;return i.run(async()=>{this.coordinator?.setAgentRunning(e,o,!0);const t=this.newMessageGroupId();var i;a&&this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},(i=a,{type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:i}]}}),{groupId:this.newMessageGroupId()});try{const a=await bs.create(s,e,{logger:this.log.bind(this),context:this.agentContext}),i={mode:"work",supportChangeTitle:!1},r=this.createPermissionHandler(),p=this.buildSystemHooks({trackBackgroundTasks:!1}),l=Oa(),d=a.loop({cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:i,agentrixTools:this.agentrixTools,canUseTool:r,hooks:p,maxTurns:this.options.input.maxTurns??void 0});d.push(n);let u=!1;for await(const n of d.events){if("system"===n.type&&"init"===n.subtype)continue;if("result"===n.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},n,{groupId:t}),u=!0;break}const a=c?n:l.filter(n);a&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},a,{groupId:t})}}catch(n){this.log("error","RUN_TASK",`Run task failed for ${e}:`,n);const a=n instanceof Error?n.message:String(n);this.sendAgentErrorMessage(e,o,`I meet some error: ${a}`,{groupId:t})}finally{this.coordinator?.setAgentRunning(e,o,!1)}})}buildSubAgentHistoryContext(e,n){const a=this.historyDb;if(!a)return this.log("warn","HISTORY","Task history DB unavailable; delegate cannot build context."),null;const t=a.getAgentSessions().get(e),s=a.getAgentLastSequences().get(e)??0,i=a.pageRecentMessagesAfter(s,20);if(0===i.data.length&&!n)return null;const o=this.mergeConsecutiveHumanMessages(i.data),r=this.buildHistoryMessages(o,n);return r?{message:r,sessionId:t,lastSequence:i.data.length>0?i.data[i.data.length-1].localSequence:s}:null}buildHistoryMessages(e,n){const a=[];for(const n of e){const e=Na(n);e&&a.push(e)}if(0===a.length&&!n)return null;let t=a.join("\n");return n&&(t=`<hint>\n${n}\n</hint>\n\n${t}`),{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:""}}buildSystemHooks(e){const n=e?.trackBackgroundTasks??!0,a=e?.trackPrimaryAgentStop??!1,t={};return n&&(t.PostToolUse=async e=>(this.trackBackgroundTaskFromPostToolUse(e),{})),a&&(t.Stop=async()=>(this.updateAgentRunning(!1),{})),t}trackBackgroundTaskFromPostToolUse(e){if(!e||"object"!=typeof e)return void this.log("debug","TASK","PostToolUse hook input is not an object");const n=e,a=n.tool_input;if(!a||!0!==a.run_in_background)return;const t=this.extractBackgroundTaskId(n.tool_response);if(!t)return this.log("debug","TASK",`PostToolUse(${n.tool_name}) run_in_background=true but no task_id found, using anonymous tracking`),void this.coordinator?.setAnonymousBackgroundTaskRunning(!0);this.coordinator?.setBackgroundTaskRunning(t,!0),this.log("info","TASK",`Background task started: ${t} (tool: ${n.tool_name})`)}handleBackgroundTaskNotification(e){this.updateAgentRunning(!0),this.coordinator?.setBackgroundTaskRunning(e.task_id,!1),this.log("info","TASK",`Background task ${e.task_id} ${e.status}`)}extractBackgroundTaskId(e){const n=new Set,a=new Set,t=e=>{if("string"!=typeof e)return;const a=e.trim();a&&n.add(a)},s=e=>{if(null==e)return;if("string"==typeof e)return void(e=>{const n=/(task[_-]?id|agent[_-]?id|shell[_-]?id)["'\s:=]+([A-Za-z0-9._:-]+)/gi;let a;for(;null!==(a=n.exec(e));)t(a[2])})(e);if("object"!=typeof e)return;if(a.has(e))return;if(a.add(e),Array.isArray(e)){for(const n of e)s(n);return}const n=e;"string"==typeof n.task_id&&t(n.task_id),"string"==typeof n.taskId&&t(n.taskId),"string"==typeof n.agent_id&&t(n.agent_id),"string"==typeof n.agentId&&t(n.agentId),"string"==typeof n.shell_id&&t(n.shell_id),"string"==typeof n.shellId&&t(n.shellId);for(const e of Object.values(n))s(e)};s(e);const i=[...n];return i.length>1&&this.log("warn","TASK",`Multiple background task ids extracted (${i.join(", ")}), using first id ${i[0]}`),i[0]}createWorkerClientConfig(e,n,a){const t=this.options.input.agentId,s=this.taskAgentsMap.get(t)?.name;return{config:{userId:e,taskId:n,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:t,agentName:s,cwd:a,serverUrl:D.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:A(this.credentials.token,this.credentials.machineId,n),dataEncryptionKey:this.options.dataEncryptionKey??null,keepAliveConfig:{intervalMs:2e4,event:"worker-alive",payloadGenerator:()=>{const e=this.coordinator?.getStatus(),a="running"===e?.state?"worker-running":"worker-ready";return{eventId:d(),status:a,taskId:n,machineId:this.credentials.machineId,timestamp:Date.now().toString(),activeAgents:this.coordinator?.getActiveAgents()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...n)=>this.logger.info(`[SOCKET] ${e}`,...n)},handlers:{attachmentsDir:D.resolveAttachmentsDir(e,n),logger:(e,n,a,...t)=>{this.log(e,n,a,...t)},stopTask:async()=>{this.stopTask("event")},shouldPersistTaskMessage:async e=>!E(e)||!this.shouldDropHeartbeatWhileBusy()||(this.log("debug","WORKER","Dropping heartbeat at WorkerClient receive stage: agent is running"),!1),onTaskMessage:async(e,n)=>{if(w(e)){const[n,a]=this.askUserAwaiter.entries().next().value||[];n&&a&&(this.askUserAwaiter.delete(n),a(e))}},onTaskInfoUpdate:async e=>{Nt(e,this.options.input)},onWorkerStatusRequest:async()=>{const{state:e}=this.coordinator.getStatus();"running"===e?this.workClient.sendWorkRunning():"idle"===e&&this.workClient.sendWorkerReady()},onSubTaskResultUpdated:async e=>{const n=Pa(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(n)}}}}async exitWorker(e){this.log("info","WORKER",`Exiting with status: ${e} for task ${this.taskId}`),this.coordinator&&this.coordinator.stop(),this.workClient&&(this.workClient.sendWorkerExit(e),await this.workClient.disconnect()),this.historyDb&&this.historyDb.close(),this.chatHistoryDb&&this.chatHistoryDb.close(),process.exit(0)}async reportFatalError(e){this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}log(e,n,a,...t){this.logger&&this.logger[e](`[${n}] ${a}`,...t)}get taskId(){return this.options.input.taskId}async handleSdkResultMessage(e){let n,a;try{const e=await this.workspace.prepareResultArtifacts({onCommitError:e=>{this.log("warn","GIT","Failed to auto-commit changes before result message:",e)},onPatchError:e=>{this.log("warn","GIT","Failed to write patch diff for result:",e)}});n=e.artifacts,a=e.currentCommitHash}catch(e){this.log("warn","GIT","Failed to prepare git artifacts for result:",e)}const t=this.getRunnerMode(),s="group_chat"===t||"group_work"===t,i=this.pendingNavigateTaskId;if(this.pendingNavigateTaskId=null,s?this.workClient.sendTaskEvent(this.getChatSenderMeta(),e,{...n?{artifacts:n}:{},groupId:this.currentGroupId??void 0,navigateToTaskId:i??void 0}):this.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{...n?{artifacts:n}:{},groupId:this.currentGroupId??void 0,navigateToTaskId:i??void 0}),a)try{await Mt(this.options.input.userId,this.taskId,a)}catch(e){this.log("warn","GIT","Failed to mark commit as sent:",e)}}}class As{static async calculateFinalCwd(e){const{repositorySourceType:n,cwd:a,userCwd:t,userId:s,taskId:i,forceUserCwd:o}=e;if(a)return a;const r=D.resolveProjectDir(s,i);if("directory"===n&&t){const e=t.replace(/^~/,J());return o?e:await this.shouldUseWorktree(e)?r:e}return r}static async shouldUseWorktree(e){try{return!mt(e)&&await rt(e)}catch{return!1}}}var Rs=un(U);class _s{constructor(e,n){this.credentials=e,this.options=n}context;threadId=null;isStopping=!1;filteredToolUseIds=new Set;currentModel=null;dataEncryptionKey=null;abortController=new AbortController;coordinator;logger;askUserAwaiter=new Map;workClient;workspace;historyDb=null;currentGroupId=null;refreshGroupId(){this.currentGroupId=`group-${M()}`}async start(){try{await this.initialize(),await this.handleEvent(),await this.runCodex(),await this.exitWorker("completed")}catch(e){if(!this.isStopping){this.log("warn","AGENT","Fatal error:",e);const n=e instanceof Error?e.message:String(e);throw await this.exitWorker("error",n),e}this.log("info","AGENT",`Task ${this.taskId} stopped gracefully`),await this.exitWorker("completed")}finally{process.exit(0)}}async initialize(){const e=this.options.input.taskId,n=this.options.input.userId;this.logger=this.createLogger({type:"worker",taskId:e}),this.dataEncryptionKey=this.options.dataEncryptionKey??null;const a=It(this.options.input),t=await As.calculateFinalCwd(a),s={...a,cwd:t};this.log("info","INIT",`Phase 1: Working directory: ${t}`);const i=this.createWorkerClientConfig(n,e,t),o=D.resolveDataDir(n,e);this.historyDb=wa({dataDir:o,taskId:e});const r=new Ma(i.config,{...i.handlers,historyDb:this.historyDb});this.workClient=r,this.log("info","INIT","Phase 2: WorkerClient created");const c=1e3*Math.max(0,this.options.idleTimeoutSecond??0);this.coordinator=this.createMessageCoordinator(r,c),this.log("info","INIT","Phase 3: Coordinator created"),await r.connect(),r.sendWorkerInitializing(),this.log("info","INIT","Phase 4: Connected to server"),this.log("info","INIT","Phase 5: Skipped (no AgentContext for Codex)"),this.log("info","INIT","Phase 6: Skipped (no custom resources for Codex)");const p=new ws({options:s,handlers:this.createWorkspaceHandlers(r)}),{initialCommitHash:l,gitStateResult:d}=await p.setup();this.workspace=p,this.log("info","INIT","Phase 7: Workspace setup complete"),r.sendWorkerInitialized(),this.log("info","INIT","Phase 8: Initialization finalized"),await this.registerWithDaemon(t),this.log("info","INIT","Phase 9: Registered with daemon"),this.context={credentials:this.credentials,options:this.options,workClient:r,workingDirectory:t,initialCommitHash:l,logger:this.logger},process.env.AGENTRIX_WORKING_DIR=t,process.env.AGENTRIX_WORKING_USER=n,process.env.AGENTRIX_WORKING_TASK=e,this.options.input.environmentVariables&&Object.entries(this.options.input.environmentVariables).forEach(([e,n])=>{null!=n&&(process.env[e]=String(n))}),this.options.input.api_base_url&&(process.env.OPENAI_BASE_URL=this.options.input.api_base_url),this.options.input.api_key&&(process.env.CODEX_API_KEY=this.options.input.api_key),"agentSessionId"in this.options.input&&this.options.input.agentSessionId&&(this.threadId=this.options.input.agentSessionId,this.log("info","AGENT",`Resuming thread: ${this.threadId}`))}createWorkspaceHandlers(e){return{onRepositoryDetected:n=>{e.associateRepository(n.host,n.owner,n.repo,n.url)},onUncommittedChanges:this.onUncommittedChanges.bind(this),onBranchMismatch:this.onBranchMismatch.bind(this)}}async registerWithDaemon(e){const n=this.options.input.taskId,a=await tn(n,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});a.error?this.log("warn","DAEMON",`Failed to report session ${n}:`,a.error):this.log("info","DAEMON",`Session ${n} registered`)}createMessageCoordinator(e,n){return this.coordinator=new Pt({workerType:"codex",workClient:e,handlers:{onNormalMessage:async e=>this.convertSDKMessageToCodexInput(e),onBashCommand:async(e,n)=>{await this.executeBashCommand(e)},onMergeRequest:async e=>{await this.executeMergeRequest()},onMergePr:async()=>{await this.executeMergePr()},onNewSession:async()=>{await this.executeNewSession()}},logger:(e,n,a)=>{const t=e;this.log(t,n,a)},idleTimeoutMs:n,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}async handleEvent(){if("task-message"===this.options.input.event){const e=this.options.input.eventData.message;e&&k(e)&&"user"===e.type&&await this.coordinator.enqueue(e)}}async executeMergeRequest(){this.log("info","MERGE","Executing merge-request command");try{if(!this.options.input.repositoryId){const e="Cannot create PR: task has no git repository configured.";return this.log("warn","MERGE","No repositoryId found in task input"),void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}await lt(this.context.workingDirectory)&&(await gt(this.context.workingDirectory,"Update task changes"),this.log("info","MERGE","Auto-committed changes"));const e=await dt(this.context.workingDirectory),n=this.context.initialCommitHash,a=await ft(this.context.workingDirectory);if(this.log("info","MERGE",`Pushing branch ${a} to remote`),await Ct(this.context.workingDirectory,a,!1,this.options.input.gitServerId),this.log("info","MERGE","Successfully pushed branch to remote"),!n){const e="Cannot create PR: initial commit hash is missing.";return this.log("error","MERGE",e),void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}if(0===(await ht(this.context.workingDirectory,n,e)).files.length){const e="No changes to create PR: no files changed since task started";return void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}const t=$t(n);this.log("debug","MERGE",`PR prompt: ${t.substring(0,200)}...`);const s=this.options.input.agentId??"default",i=await bs.create("codex",s),o={mode:"work",supportChangeTitle:!1},r=i.runStreamed(t,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,abortController:this.abortController,modeConfig:o,structuredOutputSchema:{type:"json_schema",schema:Ss}});let c=null;for await(const e of r){if(this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){c=e;break}const n=this.filterMessages(e);null!==n&&this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}if(!c)throw new Error("Merge-request did not return a result message");const p=Ts(c);await this.createPullRequest(p.title,p.description),this.sendMessage(p.userMessage)}catch(e){const n=e instanceof Error?e.message:String(e);this.log("error","MERGE","Merge-request failed:",e),this.context.workClient.sendSystemErrorMessage(`Merge-request failed: ${n}\n\n`,{groupId:this.currentGroupId??void 0})}}async executeChangeTitle(e){this.log("info","WORKER",`Changing task title to: ${e}`),this.context.workClient.sendChangeTaskTitle(e)}async executeBashCommand(e){this.log("info","BASH",`Executing command: ${e}`);const n=await Dt(e,this.context.workingDirectory,{onOutput:e=>{this.context.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0})},onComplete:e=>{this.log("info","BASH",`Command completed with exit code: ${e}`)}});this.log("info","BASH",`Worker ready after command execution (exit code: ${n})`)}async executeMergePr(){await jt({workingDirectory:this.context.workingDirectory,workClient:this.context.workClient,repositoryId:this.options.input.repositoryId,gitServerId:this.options.input.gitServerId,logger:this.context.logger,askUser:e=>this.askUser(e,{onTimeout:"abort_task"})})}async executeNewSession(){this.log("info","SESSION","Executing new-session: clearing threadId"),this.threadId=null,this.context.workClient.sendResetTaskSession(),this.log("info","SESSION","Session reset sent, stopping task for clean restart"),this.stopTask("event")}async runCodex(){this.log("info","AGENT",`Starting Codex agent for task ${this.taskId}`),this.currentModel=this.options.input.model||null,this.currentModel?this.log("info","AGENT",`Using model: ${this.currentModel}`):this.log("info","AGENT","Using default model from Codex config");const e=this.options.input.agentId??"default",n=(await bs.create("codex",e)).loop({cwd:this.context.workingDirectory,model:this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:{mode:"work",supportChangeTitle:!1}});(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(e)n.push(e);else if(this.isStopping)break}}catch(e){this.log("error","AGENT","Message pump failed:",e),this.stopTask("event")}})();for await(const e of n.events){if(this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),"system"===e.type&&"init"===e.subtype){this.threadId=e.session_id,this.context.workClient.sendUpdateTaskAgentSessionId(e.session_id),this.log("info","AGENT",`Thread started: ${e.session_id}`),this.refreshGroupId(),this.updateAgentRunning(!0);continue}const n=this.filterMessages(e);null!==n&&("result"===e.type?await this.handleSdkResultMessage(n):this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})),"result"===e.type?this.updateAgentRunning(!1):this.updateAgentRunning(!0)}this.log("info","AGENT",`Codex agent finished for task ${this.taskId}`)}filterMessages(e){const n=e,a=n?.message?.content;if(!a||"string"==typeof a)return e;const t=a.filter(e=>"tool_use"===e.type&&"agentrix"===e.server_name?(this.filteredToolUseIds.add(e.id),!1):!("tool_result"===e.type&&this.filteredToolUseIds.has(e.tool_use_id)||"user"===n.type&&"tool_result"!==e.type));return 0===t.length?null:(n.message.content=t,n)}sendMessage(e){const n={type:"assistant",message:{id:M().toString(),type:"message",container:null,role:"assistant",content:[{citations:null,type:"text",text:e}],model:this.currentModel||"",usage:{},stop_reason:null,context_management:null,stop_sequence:null},parent_tool_use_id:null,session_id:"",uuid:M().toString()};this.getActiveWorkClient().sendTaskMessage(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}async askUser(e,n={}){const a=this.getActiveWorkClient();return qt(e,this.askUserAwaiter,{sendAskUser:e=>a.sendAskUser(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0}),sendAskUserResponse:(e,n)=>a.sendAskUserResponse(e,n),onTimeoutMessage:e=>this.sendMessage(e),stopTask:e=>this.stopTask(e)},n)}getActiveWorkClient(){const e=this.context?.workClient??this.workClient;if(!e)throw new Error("[WORKER] WorkerClient not available");return e}resolveTaskAgentName(e){const n=this.options.input.taskAgents??[];return n.find(n=>n.id===e)?.name||""}getChatSenderMeta(){const e=this.options.input.agentId;return{senderType:"agent",senderId:e,senderName:this.resolveTaskAgentName(e)??""}}async onUncommittedChanges(){const e=[{question:"Uncommitted changes detected in the working directory. How would you like to proceed?",header:"Git Status",multiSelect:!1,options:[{label:"Ignore",description:"Keep changes on current branch and continue without switching"},{label:"Commit",description:"Commit on current branch, then switch to task branch"},{label:"Stash",description:"Stash changes, then switch to task branch"},{label:"Abort",description:"Cancel the task, do nothing"}]}];try{const n=(await this.askUser(e,{onTimeout:"abort_task"})).answers[0];return n.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${n}, defaulting to Abort`),"Abort"):{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort"}catch(e){return this.log("warn","GIT",`Failed to get user response for uncommitted changes: ${e}`),"Abort"}}async onBranchMismatch(e){const n=[{label:"Switch",description:`Checkout ${e.expectedBranch} and continue`},{label:"Keep",description:`Continue on ${e.currentBranch} (may affect task history)`},{label:"Abort",description:"Cancel the task"}],a=[{question:`Branch mismatch detected. Current: ${e.currentBranch}. Expected: ${e.expectedBranch}. How would you like to proceed?`,header:"Git Branch",multiSelect:!1,options:n}];try{const e=(await this.askUser(a,{onTimeout:"abort_task"})).answers[0];return e.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${e}, defaulting to Abort`),"Abort"):{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[e]||"Abort"}catch(e){return this.log("warn","GIT",`Failed to get user response for branch mismatch: ${e}`),"Abort"}}async createPullRequest(e,n){this.log("info","MERGE",`Creating PR: ${e}`);try{const a=await this.context.workClient.sendMergeRequest(e,n);this.sendMessage(`✅ Pull request created successfully!\nNumber: #${a.pullRequestNumber}\nURL: ${a.pullRequestUrl}`)}catch(e){this.log("error","MERGE","Failed to create PR:",e),this.sendMessage(`❌ Failed to create pull request: ${e instanceof Error?e.message:"Unknown error"}`)}}async convertSDKMessageToCodexInput(e){const n=e.message.content;if("string"==typeof n)return n;if(Array.isArray(n)){const e=[],a=D.resolveAttachmentsDir(this.options.input.userId,this.taskId);for(const t of n)if("text"===t.type&&t.text)e.push(t.text);else if("image"===t.type&&t.source&&t.source.url){const n=t.source.url;try{const{filePath:t}=await Ra(n,a,!1);this.log("info","IMAGE",`Downloaded image from ${n} to ${t}`),e.push(`Image: ${t}`)}catch(e){this.log("error","IMAGE",`Failed to download image from ${n}:`,e)}}else if("document"===t.type&&t.source&&t.source.url){const n=t.source.url;try{const{filePath:s,mimeType:i,filename:o}=await Ra(n,a,!0);this.log("info","DOCUMENT",`Downloaded document from ${n} to ${s}`);const r=t.title||o;e.push(`Document: ${s}\nTitle: ${r}\nType: ${i}`)}catch(e){this.log("error","DOCUMENT",`Failed to download document from ${n}:`,e)}}const t=e.map(e=>e.trim()).filter(Boolean).join("\n\n").trim();if(t)return t}return""}stopTask(e){this.isStopping||(this.isStopping=!0,"idle"===e?this.log("info","AGENT","Idle timeout reached, stopping task"):"ask_user_timeout"===e&&this.log("info","AGENT","ask_user timed out, stopping task"),this.askUserAwaiter.clear(),this.coordinator?.stop(),this.abortController.abort())}updateAgentRunning(e){this.coordinator?.updateAgentRunning(e)}createWorkerClientConfig(e,n,a){const t=this.options.input.agentId,s=this.options.input.taskAgents?.find(e=>e.id===t)?.name;return{config:{userId:e,taskId:n,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:t,agentName:s,cwd:a,serverUrl:D.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:A(this.credentials.token,this.credentials.machineId,n),dataEncryptionKey:this.dataEncryptionKey,keepAliveConfig:{intervalMs:2e4,event:"worker-alive",payloadGenerator:()=>{const e=this.coordinator?.getStatus(),a="running"===e?.state?"worker-running":"worker-ready";return{eventId:d(),status:a,taskId:n,machineId:this.credentials.machineId,timestamp:Date.now().toString()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...n)=>(this.context?.logger??this.logger)?.info(`[SOCKET] ${e}`,...n)},handlers:{stopTask:async()=>{this.stopTask("event")},onTaskMessage:async e=>{if(w(e)){const[n,a]=this.askUserAwaiter.entries().next().value||[];return void(n&&a&&(this.askUserAwaiter.delete(n),a(e)))}k(e)&&"user"===e.type&&await this.coordinator.enqueue(e)},onTaskInfoUpdate:async e=>{Nt(e,this.options.input)},onWorkerStatusRequest:async()=>{if(!this.context?.workClient)return;if(!this.coordinator)return;const{state:e}=this.coordinator.getStatus();"running"===e?this.context.workClient.sendWorkRunning():"idle"===e&&this.context.workClient.sendWorkerReady()}}}}async exitWorker(e,n){this.coordinator&&this.coordinator.stop(),this.log("info","WORKER",`Exiting with status: ${e} for task ${this.taskId}`),"error"===e&&n?await this.context.workClient.sendErrorMessageAndExit(n):(this.context.workClient.sendWorkerExit(e),await this.context.workClient.disconnect()),this.historyDb&&this.historyDb.close()}createLogger(e){const{createLogger:n}=Rs;return n(e)}log(e,n,a,...t){const s=this.context?.logger??this.logger;s&&s[e](`[${n}] ${a}`,...t)}get taskId(){return this.options.input.taskId}getCurrentModel(){return this.currentModel||"gpt-5"}async handleSdkResultMessage(e){let n,a;try{const e=await this.workspace.prepareResultArtifacts({onCommitError:e=>{this.log("warn","GIT","Failed to auto-commit changes before result message:",e)},onPatchError:e=>{this.log("warn","GIT","Failed to write patch diff for result:",e)}});n=e.artifacts,a=e.currentCommitHash}catch(e){this.log("warn","GIT","Failed to prepare git artifacts for result:",e)}if(this.context.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{...n?{artifacts:n}:{},groupId:this.currentGroupId??void 0}),a)try{await Mt(this.options.input.userId,this.taskId,a)}catch(e){this.log("warn","GIT","Failed to mark commit as sent:",e)}}}async function Ms(e,n){await ae.promises.mkdir(n,{recursive:!0});const a=await ae.promises.readdir(e,{withFileTypes:!0});for(const t of a){const a=ue.join(e,t.name),s=ue.join(n,t.name);t.isDirectory()?await Ms(a,s):await ae.promises.copyFile(a,s)}}async function $s(e,n){const a=n.input,{taskId:t,sourcePath:s,targetAgentId:i,userId:o,name:r,avatar:c,isSystemAgent:p,supportLocal:l}=a;let u=null;try{if(console.log(`[Deployment] Starting deployment worker for task ${t}`),!ae.existsSync(s))throw new Error(`Source path not found: ${s}`);const n=ue.join(D.agentrixAgentsHomeDir,i);if(ae.existsSync(n))throw new Error(`Target agent directory already exists: ${n}`);console.log(`[Deployment] Copying from ${s} to ${n}`),await Ms(s,n),console.log("[Deployment] Deployment completed successfully"),u=function(e,n,a){const t=D.serverUrl.replace(/^http/,"ws");return Z(t,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:a}})}(e,0,t),await new Promise((e,n)=>{const a=setTimeout(()=>{n(new Error("WebSocket connection timeout"))},1e4);u.on("connect",()=>{clearTimeout(a),console.log("[Deployment] Connected to server"),u.emit("deploy-agent-complete",{eventId:d(),taskId:t,targetAgentId:i,success:!0,name:r,avatar:c,isSystemAgent:p,supportLocal:l}),console.log("[Deployment] Sent deploy-agent-complete event"),setTimeout(()=>{e()},1e3)}),u.on("connect_error",e=>{clearTimeout(a),n(e)})})}catch(e){throw console.error("[Deployment] Deployment failed:",e),u&&u.connected&&(u.emit("deploy-agent-complete",{eventId:d(),taskId:t,targetAgentId:i,success:!1,error:e instanceof Error?e.message:String(e)}),await new Promise(e=>setTimeout(e,1e3))),e}finally{u&&u.disconnect(),process.exit(0)}}const Ds=["claude","codex","deployment","companion"],Ps={claude:{async run({credentials:e,startedBy:n,userId:a,taskId:t,idleTimeoutSecond:s}){const i=D.readTaskInput(a,t),o=i.dataEncryptionKey?p(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:n,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await async function(e,n){const a=It(n.input),t=await As.calculateFinalCwd(a),s=new Cs(e,n,t);await s.start()}(e,r)}},codex:{async run({credentials:e,startedBy:n,userId:a,taskId:t,idleTimeoutSecond:s}){const i=D.readTaskInput(a,t),o=i.dataEncryptionKey?p(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:n,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await async function(e,n){const a=new _s(e,n);await a.start()}(e,r)}},deployment:{async run({credentials:e,startedBy:n,userId:a,taskId:t,idleTimeoutSecond:s}){const i={input:D.readTaskInput(a,t)};await $s(e,i)}},companion:{async run({credentials:e,startedBy:n,userId:a,taskId:t,idleTimeoutSecond:s}){const i=D.readTaskInput(a,t),o=i.dataEncryptionKey?p(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:n,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await async function(e,n){const{agentDir:a,homeDir:t}=await fa();n.input.agentDir=a,process.env.AGENTRIX_COMPANION_HOME=t;const s=It(n.input),i=await As.calculateFinalCwd(s),o=new Cs(e,n,i);await o.start()}(e,r)}}};async function Os(){const e=j.version;try{const n=Ie("npm view @agentrix/cli version",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();return{hasUpgrade:function(e,n){const a=e.split(".").map(Number),t=n.split(".").map(Number);for(let e=0;e<Math.max(a.length,t.length);e++){const n=a[e]||0,s=t[e]||0;if(n>s)return 1;if(n<s)return-1}return 0}(n,e)>0,currentVersion:e,latestVersion:n}}catch(n){return{hasUpgrade:!1,currentVersion:e,latestVersion:null}}}function js(){return"true"===process.env.AGENTRIX_DISABLE_AUTO_UPGRADE}async function Ns(e){try{const{execSync:n}=await import("child_process");return console.log(""),e||(console.log(s.blue("🔄 Checking for upgrades...")),e=await Os()),e.hasUpgrade?(console.log(s.blue(`🔄 Upgrading from ${e.currentVersion} to ${e.latestVersion}...`)),n("npm install -g @agentrix/cli@latest",{stdio:"inherit"}),console.log(s.green("✓ Upgrade complete")),console.log(""),!0):(console.log(s.green("✓ Already on latest version")),console.log(""),!0)}catch(e){return console.log(""),console.log(s.yellow("⚠️ Auto-upgrade failed")),console.log(s.dim(" You can upgrade manually with: npm install -g @agentrix/cli@latest")),console.log(""),!1}}function qs(){const e=D.getStatePaths();return B.join(B.dirname(e.daemonStateFile),"upgrade-daemon.state.json")}function Us(){try{const e=qs();if(!F.existsSync(e))return null;const n=F.readFileSync(e,"utf-8");return JSON.parse(n)}catch{return null}}function Gs(){try{const e=qs();F.existsSync(e)&&F.unlinkSync(e)}catch{}}function Ls(e){try{return process.kill(e,0),!0}catch{return!1}}function Fs(){const e=Us();return!(!e||!Ls(e.pid)&&(Gs(),1))}function Ws(){const e=Us();if(e)try{Ls(e.pid)&&process.kill(e.pid,"SIGTERM")}catch{}finally{Gs()}}async function Hs(){if(js())return!1;const e=await Os();return!(!e.hasUpgrade||!await Ns(e))&&(await cn(),await new Promise(e=>setTimeout(e,1e3)),ba(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref(),!0)}var zs=Object.freeze({__proto__:null,isUpgradeDaemonRunning:Fs,startUpgradeDaemon:async function(){await async function(){!function(e){const n=qs();F.writeFileSync(n,JSON.stringify(e,null,2))}({pid:process.pid,startedAt:(new Date).toISOString()}),process.on("SIGTERM",()=>{Gs(),process.exit(0)}),process.on("SIGINT",()=>{Gs(),process.exit(0)});try{await Hs()}catch(e){}for(;;){await new Promise(e=>setTimeout(e,216e5));try{await Hs()}catch(e){}}}()},stopUpgradeDaemon:Ws});const Bs=a(t(process.argv)).scriptName("agentrix").version(j.version).usage("$0 <command> [options]").option("debug",{alias:"d",type:"boolean",describe:"Use local-debug mode (plaintext, for debugging)",global:!0}).help("help").alias("h","help").alias("v","version").strict().epilog("For more information, visit https://github.com/xmz-ai/agentrix-cli");D.getStatePaths,Bs.command("upgrade","Upgrade CLI to the latest version",{},async e=>{console.log(s.dim(`Current version: ${j.version}`));const n=await sn();if(await Ns()||process.exit(1),n){console.log(s.blue("Restarting daemon...")),await cn(),await new Promise(e=>setTimeout(e,1e3)),ba(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();let e=!1;for(let n=0;n<50;n++)if(await new Promise(e=>setTimeout(e,100)),await sn()){e=!0;break}e?console.log(s.green("✓ Daemon restarted successfully")):console.log(s.yellow("⚠️ Daemon may still be starting. Run 'agentrix status' to check."))}try{const{version:e}=await import("./logger-CdDc0Esc.mjs").then(function(e){return e._});console.log(s.green(`\n✓ Now running version: ${e}`))}catch{console.log(s.dim("\nRun 'agentrix --version' to see the new version"))}process.exit(0)}),Bs.command("doctor","System diagnostics & troubleshooting",{},async e=>{await Bn(),process.exit(0)}),Bs.command("logout","Logout from Agentrix",{},async e=>{try{await async function(){if(!await D.readCredentials())return void console.log(s.yellow("Not currently authenticated"));console.log(s.blue("This will log you out of Agentrix")),console.log(s.yellow("⚠️ You will need to re-authenticate to use Agentrix again"));const e=G({input:process.stdin,output:process.stdout}),n=await new Promise(n=>{e.question(s.yellow("Are you sure you want to log out? (y/N): "),n)});if(e.close(),"y"===n.toLowerCase()||"yes"===n.toLowerCase())try{try{await cn(),console.log(s.gray("Stopped daemon"))}catch{}await D.clearCredentials(),console.log(s.gray("Removed credentials")),console.log(s.green("✓ Successfully logged out"))}catch(e){throw new Error(`Failed to logout: ${e instanceof Error?e.message:"Unknown error"}`)}else console.log(s.blue("Logout cancelled"))}()}catch(e){console.error(s.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}process.exit(0)}),Bs.command("stop","Stop the daemon",{},async e=>{Ws(),await cn(),process.exit(0)}),Bs.command("status","Show daemon and authentication status",{},async e=>{await Bn("daemon"),console.log(""),await async function(){const e=await D.readCredentials();if(console.log(s.bold("\nAuthentication Status\n")),!e)return void console.log(s.red("✗ Not authenticated"));console.log(s.green("✓ Authenticated"));const n=e.token.substring(0,30)+"...";console.log(s.gray(` Token: ${n}`)),e.machineId?(console.log(s.green("✓ Machine registered")),console.log(s.gray(` Machine ID: ${e.machineId}`)),console.log(s.gray(` Host: ${X.hostname()}`))):console.log(s.yellow("⚠️ Machine not registered")),console.log(s.gray(`\n Data directory: ${D.agentrixHomeDir}`));try{await sn()?console.log(s.green("✓ Daemon running")):console.log(s.gray("✗ Daemon not running"))}catch{console.log(s.gray("✗ Daemon not running"))}}(),process.exit(0)}),Bs.command("ls","List active sessions",{},async e=>{try{const e=await async function(){return(await an("/list")).children||[]}();0===e.length?console.log("No active sessions"):(console.log("Active sessions:"),console.log(JSON.stringify(e,null,2)))}catch(e){console.log("No daemon running")}process.exit(0)}),Bs.command("killall","Clean up all runaway agentrix processes",{},async()=>{const e=await async function(){const e=await async function(){return(await Fn()).filter(e=>e.pid!==process.pid&&("daemon"===e.type||"worker"===e.type||"upgrade-daemon"===e.type)).map(e=>({pid:e.pid,command:e.command}))}(),n=[];let a=0;for(const{pid:t,command:s}of e)try{if(console.log(`Killing runaway process PID ${t}: ${s}`),"win32"===process.platform){const e=Te.sync("taskkill",["/F","/PID",t.toString()],{stdio:"pipe"});if(e.error)throw e.error;if(0!==e.status)throw new Error(`taskkill exited with code ${e.status}`)}else process.kill(t,"SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),(await Se()).find(e=>e.pid===t)&&(console.log(`Process PID ${t} ignored SIGTERM, using SIGKILL`),process.kill(t,"SIGKILL"));console.log(`Successfully killed runaway process PID ${t}`),a++}catch(e){const a=e.message;n.push({pid:t,error:a}),console.log(`Failed to kill process PID ${t}: ${a}`)}return{killed:a,errors:n}}();console.log(`Cleaned up ${e.killed} runaway processes`),e.errors.length>0&&console.log("Errors:",e.errors),process.exit(0)}),Bs.command("kill <sessionId>","Stop a specific session",e=>e.positional("sessionId",{type:"string",describe:"Session ID to stop"}),async e=>{try{const n=await async function(e){return(await an("/stop-session",{sessionId:e})).success||!1}(e.sessionId);console.log(n?s.green("✓ Session stopped"):s.red("Failed to stop session"))}catch(e){console.log(s.red("No daemon running"))}process.exit(0)}),Bs.command("daemon",!1,{},async e=>{try{await pn()}catch(e){console.error(s.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}await Ca(),process.exit(0)}),Bs.command("worker",!1,e=>e.option("type",{type:"string",choices:Ds,demandOption:!0,describe:"Worker type to start"}).option("started-by",{type:"string",choices:["daemon","terminal"],describe:"How the session was started"}).option("user-id",{type:"string",demandOption:!0,describe:"User ID for the worker"}).option("task-id",{type:"string",demandOption:!0,describe:"Task ID for the worker"}).option("idle-timeout",{type:"number",default:300,describe:"Idle timeout in seconds"}),async e=>{try{const n=e.type,a=Ps[n];if(!a)throw new Error(`Unsupported worker type: ${String(e.type)}`);const t=e["started-by"],s=await pn(),i=e["user-id"],o=e["task-id"],r=e["idle-timeout"];await a.run({credentials:s,startedBy:t,userId:i,taskId:o,idleTimeoutSecond:r})}catch(e){console.error(s.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}}),Bs.command("upgrade-daemon",!1,{},async e=>{const{startUpgradeDaemon:n}=await Promise.resolve().then(function(){return zs});await n(),process.exit(0)}),Bs.command("start","Start daemon (if not running) and show status",{},async e=>{try{await pn()}catch(e){console.error(s.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}const n=function(){const e=Hn(),n=[],a=e.cli.find(e=>"git"===e.name);a&&!a.installed&&n.push("git");for(const a of e.missingSandbox)n.push(a.name);return{ok:0===n.length,missing:n}}();if(n.ok||(console.log(s.bold.red("\n⚠️ Missing Critical Dependencies")),console.log(s.yellow(`Cannot start daemon. Missing: ${n.missing.join(", ")}`)),console.log(s.blue('\nRun "agentrix doctor" for detailed dependency information and installation instructions.')),process.exit(1)),!await on()){console.log("Starting Agentrix background service..."),ba(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();let e=!1;for(let n=0;n<50;n++)if(await new Promise(e=>setTimeout(e,100)),await sn()){e=!0;break}e?console.log(s.green("✓ Daemon started successfully")):console.log(s.yellow("⚠️ Daemon may still be starting..."))}if(js()){const e=await Os();e.hasUpgrade&&(a=e).hasUpgrade&&a.latestVersion&&(console.log(""),console.log(s.yellow("┌────────────────────────────────────────────────────┐")),console.log(s.yellow("│")+" "+s.bold("Upgrade Available")+" "+s.yellow("│")),console.log(s.yellow("│")+" "+s.yellow("│")),console.log(s.yellow("│")+` Current: ${s.dim(a.currentVersion)} → Latest: ${s.green.bold(a.latestVersion)} `+s.yellow("│")),console.log(s.yellow("│")+" "+s.yellow("│")),console.log(s.yellow("│")+" Run "+s.cyan.bold("agentrix upgrade")+" to upgrade "+s.yellow("│")),console.log(s.yellow("│")+" "+s.yellow("│")),console.log(s.yellow("│")+" To enable auto-upgrade, set: "+s.yellow("│")),console.log(s.yellow("│")+" "+s.dim("AGENTRIX_DISABLE_AUTO_UPGRADE=false")+" "+s.yellow("│")),console.log(s.yellow("└────────────────────────────────────────────────────┘")),console.log(""))}else Fs()||ba(["upgrade-daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();var a;await Bn("daemon"),process.exit(0)}),Bs.demandCommand(1,"Please specify a command. Use --help to see available commands.").parse();
1
+ import{createRequire as e}from"node:module";const n=e(import.meta.url);import a from"yargs";import{hideBin as t}from"yargs/helpers";import s from"chalk";import{encodeBase64 as i,createKeyPairWithUit8Array as o,encryptMachineEncryptionKey as r,generateAESKey as c,decodeBase64 as p,decryptWithEphemeralKey as l,createEventId as d,encryptFileContent as u,splitRtcChunkFrame as m,RtcChunkFlags as g,buildRtcChunkFrame as h,decryptSdkMessage as f,machineAuth as x,encryptSdkMessage as v,isSDKUserMessage as b,isAskUserMessage as y,isAskUserResponseMessage as w,isSDKMessage as k,getAgentContext as I,detectPreview as S,IGNORED_DIRECTORIES as T,isCompanionHeartbeatMessage as E,isCompanionReminderMessage as C,workerAuth as A}from"@agentrix/shared";import{randomBytes as R,createDecipheriv as _,randomUUID as M}from"node:crypto";import $ from"axios";import{m as D,l as P,p as O,a as j,c as N,g as q,b as U}from"./logger-nstmO8QZ.mjs";import{createInterface as G}from"node:readline";import*as L from"fs";import F,{readFileSync as W,existsSync as H}from"fs";import*as z from"path";import B,{join as K,dirname as V}from"path";import X,{tmpdir as Y,homedir as J}from"node:os";import Q from"open";import{io as Z}from"socket.io-client";import{EventEmitter as ee}from"node:events";import*as ne from"node:fs";import ae,{existsSync as te,readFileSync as se,statSync as ie,writeFileSync as oe,mkdirSync as re,readdirSync as ce,renameSync as pe,rmSync as le,createWriteStream as de,unlinkSync as ue}from"node:fs";import*as me from"node:path";import ge,{join as he,dirname as fe,basename as xe,relative as ve,normalize as be,extname as ye,isAbsolute as we,resolve as ke}from"node:path";import{createRequire as Ie}from"node:module";import{spawn as Se,execSync as Te}from"child_process";import Ee from"ps-list";import Ce from"cross-spawn";import{getPlatform as Ae}from"@xmz-ai/sandbox-runtime/dist/utils/platform.js";import Re from"fastify";import{z as _e,toJSONSchema as Me}from"zod";import{validatorCompiler as $e,serializerCompiler as De}from"fastify-type-provider-zod";import{spawnSync as Pe,execSync as Oe,execFile as je}from"node:child_process";import{fileURLToPath as Ne}from"node:url";import{EventEmitter as qe}from"events";import Ue from"better-sqlite3";import{fileURLToPath as Ge,pathToFileURL as Le}from"url";import{isSupportedPlatform as Fe,NetworkManager as We,SandboxManager as He}from"@xmz-ai/sandbox-runtime";import{pipeline as ze}from"node:stream/promises";import{tool as Be,createSdkMcpServer as Ke,query as Ve,AbortError as Xe}from"@anthropic-ai/claude-agent-sdk";import Ye from"simple-git";import{promisify as Je}from"node:util";import{writeFile as Qe}from"node:fs/promises";import{randomUUID as Ze}from"crypto";import{replacePromptPlaceholders as en,loadAgentConfig as nn,getAgentContext as an}from"@agentrix/shared/node";import{Codex as tn}from"@openai/codex-sdk";import"winston";import"os";async function sn(e){return new Promise(n=>setTimeout(n,e))}async function on(e,n){const a=await D.readDaemonState();if(!a?.port){const e="No daemon running, no state file found";return P.debug(`[CONTROL CLIENT] ${e}`),{error:e}}try{const t=process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT?parseInt(process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT):1e4,s=await fetch(`http://agentrix-local.xmz.ai:${a.port}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n||{}),signal:AbortSignal.timeout(t)});if(!s.ok){const n=`Request failed: ${e}, HTTP ${s.status}`;return P.debug(`[CONTROL CLIENT] ${n}`),{error:n}}return await s.json()}catch(n){const a=`Request failed: ${e}, ${n instanceof Error?n.message:"Unknown error"}`;return P.debug(`[CONTROL CLIENT] ${a}`),{error:a}}}async function rn(e,n){return await on("/session-started",{sessionId:e,metadata:n})}async function cn(){const e=await D.readDaemonState();if(!e)return!1;try{return process.kill(e.pid,0),!0}catch{return P.debug("[DAEMON RUN] Daemon PID not running, cleaning up state"),await ln(),!1}}async function pn(){if(P.debug("[DAEMON CONTROL] Checking if daemon is running same version"),!await cn())return P.debug("[DAEMON CONTROL] No daemon running, returning false"),!1;const e=await D.readDaemonState();if(!e)return P.debug("[DAEMON CONTROL] No daemon state found, returning false"),!1;try{const n=K(O(),"package.json"),a=JSON.parse(W(n,"utf-8")).version;return P.debug(`[DAEMON CONTROL] Current CLI version: ${a}, Daemon started with version: ${e.cliVersion}`),a===e.cliVersion}catch(e){return P.debug("[DAEMON CONTROL] Error checking daemon version",e),!1}}async function ln(){try{await D.clearDaemonState(),P.debug("[DAEMON RUN] Daemon state file removed")}catch(e){P.debug("[DAEMON RUN] Error cleaning up daemon metadata",e)}}async function dn(){try{const e=await D.readDaemonState();if(!e)return void P.debug("No daemon state found");P.debug(`Stopping daemon with PID ${e.pid}`);try{return await async function(){await on("/stop")}(),void await async function(e){const n=Date.now();for(;Date.now()-n<2e3;)try{process.kill(e,0),await new Promise(e=>setTimeout(e,100))}catch{return}throw new Error("Process did not die within timeout")}(e.pid)}catch(e){P.debug("HTTP stop failed, will force kill",e)}process.kill(e.pid,"SIGKILL")}catch(e){P.debug("Error stopping daemon",e)}}async function un(){const e=await D.readCredentials();if(e)return P.info("[AUTH] Using existing credentials"),e;const n=process.env.CLOUD_AUTH_TOKEN,a=process.env.CLOUD_DEVICE;let t,s,d;if(n&&a)t={token:n,machineId:a},P.info("[AUTH] Cloud mode detected, using CLOUD_AUTH_TOKEN");else{const e=await async function(){console.clear();const e=D.generateMachineId(),n=new Uint8Array(R(32)),a=await o(n);try{console.log(`[AUTH] Sending auth request to: ${D.serverUrl}/v1/auth/machine`),console.log(`[AUTH] Public key: ${i(a.publicKey).substring(0,20)}...`);const n={machineId:e};await $.post(`${D.serverUrl}/v1/auth/machine`,n),console.log("[AUTH] Auth request sent successfully")}catch(e){return console.log("Failed to create authentication request, please try again later."),{credentials:null,userPublicKey:null,keypair:a}}const t=await async function(e,n){console.clear(),console.log("\nWeb Authentication\n");const a=function(e,n){const a={key:i(e,"base64"),machineId:n},t=JSON.stringify(a),s=i((new TextEncoder).encode(t),"base64url");return`${D.webappUrl}/terminal/connect?auth=${s}`}(e.publicKey,n);return console.log("Opening your browser..."),await async function(e){try{return!process.stdout.isTTY||process.env.CI||process.env.HEADLESS?(P.debug("[browser] Headless environment detected, skipping browser open"),!1):(P.debug(`[browser] Attempting to open URL: ${e}`),await Q(e),P.debug("[browser] Browser opened successfully"),!0)}catch(e){return P.debug("[browser] Failed to open browser:",e),!1}}(a)?(console.log("✓ Browser opened\n"),console.log("Complete authentication in your browser window.")):console.log("Could not open browser automatically."),console.log("\nIf the browser did not open, please copy and paste this URL:"),console.log(a),console.log(""),await async function(e,n){process.stdout.write("Waiting for authentication");let a=0,t=!1;const s=()=>{t=!0,console.log("\n\nAuthentication cancelled."),process.exit(0)};process.on("SIGINT",s);try{for(;!t;){try{const a=await $.get(`${D.serverUrl}/v1/auth/machine?machineId=${n}`);if("authorized"===a.data.state){const n=a.data.token,t=a.data.content,s=l(p(t),e.secretKey);return s?{token:n,userPublicKey:JSON.parse((new TextDecoder).decode(s)).publicKey}:(console.log("\n\nFailed to decrypt authentication data. Please try again."),{token:null,userPublicKey:null})}}catch(e){return console.log("\n\nFailed to check authentication status. Please try again."),{token:null,userPublicKey:null}}process.stdout.write("\rWaiting for authentication"+".".repeat(a%3+1)+" "),a++,await sn(1e3)}}finally{process.off("SIGINT",s)}return{token:null,userPublicKey:null}}(e,n)}(a,e);return t.token?{credentials:{token:t.token,secret:i(n),machineId:e},userPublicKey:t?.userPublicKey,keypair:a}:{credentials:null,userPublicKey:null,keypair:a}}();if(!e.credentials||!e.userPublicKey)throw new Error("Authentication failed or was cancelled");t=e.credentials,s=e.keypair,d=e.userPublicKey}return await D.writeCredentials(t),await async function(e,n,a,t){try{const s={id:e.machineId,metadata:JSON.stringify(n)};t&&a&&(s.dataEncryptionKey=r(t.publicKey,c(),p(a))),await $.post(`${D.serverUrl}/v1/machines/sync`,s,{headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},timeout:6e4})}catch(e){if($.isAxiosError(e))throw new Error(`Failed to sync machine data: ${e.response?.data?.message||e.message}`);throw e}}(t,D.metadata(),d,s),P.info("[AUTH] Machine setup completed"),t}class mn{interval=null;socket=null;config;constructor(e){this.config=e}start(e){this.interval&&this.stop(),this.socket=e,this.interval=setInterval(()=>{if(!this.socket)return void this.stop();const e=this.config.payloadGenerator?this.config.payloadGenerator():{};this.socket.emit(this.config.event,e)},this.config.intervalMs)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.socket=null}isRunning(){return null!==this.interval}}class gn{socket=null;config;eventHandlers=new Map;eventEmitter=new ee;KeepAliveManager=null;healthCheckInterval=null;constructor(e){this.config=e,e.keepAliveConfig&&(this.KeepAliveManager=new mn(e.keepAliveConfig))}connect(){if(this.socket)return void this.log("Already connected or connecting");const{serverUrl:e,path:n,auth:a={},options:t={}}=this.config,s={path:n,auth:a,transports:["websocket"],reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:1/0,...t};this.socket=Z(e,s),this.setupSocketHandlers(),this.log("Connecting to",e)}disconnect(){this.socket&&(this.log("Disconnecting"),this.stopHealthCheck(),this.socket.close(),this.socket=null)}get connected(){return this.socket?.connected??!1}replaceSocketHandler(e,n,a){this.socket&&(n&&this.socket.off(e,n),this.socket.on(e,a))}onEvent(e,n){const a=async a=>(this.log(`received event ${e}, data: ${JSON.stringify(a)}`),n(a)),t=this.eventHandlers.get(e);this.eventHandlers.set(e,a),this.replaceSocketHandler(e,t,a)}onEventWithAck(e,n){const a=async(a,t)=>(this.log(`received event with ack ${e}, data: ${JSON.stringify(a)}`),n(a,t)),t=this.eventHandlers.get(e);this.eventHandlers.set(e,a),this.replaceSocketHandler(e,t,a)}unregisterHandler(e){this.eventHandlers.delete(e),this.socket&&this.socket.off(e)}send(e,n){this.socket?(this.log(`send event ${e}`),void 0!==n?this.socket.emit(e,n):this.socket.emit(e)):this.log("Cannot send - socket not connected")}async sendWithAck(e,n){if(!this.socket)throw new Error("Cannot send - socket not connected");return this.log(`send event ${e}, data: ${JSON.stringify(n)}`),this.socket.emitWithAck(e,n)}sendVolatile(e,n){this.socket&&(void 0!==n?this.socket.volatile.emit(e,n):this.socket.volatile.emit(e))}async flush(e=1e4){if(this.connected)return new Promise(n=>{const a=setTimeout(()=>n(),e);this.socket.emit("ping",()=>{clearTimeout(a),n()})})}updateAuth(e){this.socket&&(this.socket.auth=e),this.config.auth=e}onLifecycle(e,n){this.eventEmitter.on(`lifecycle:${e}`,n)}offLifecycle(e){this.eventEmitter.removeAllListeners(`lifecycle:${e}`)}setupSocketHandlers(){this.socket&&(this.socket.on("connect",()=>{this.log("Connected"),this.eventEmitter.emit("lifecycle:connect",this.socket);for(const[e,n]of this.eventHandlers.entries())this.socket.off(e,n),this.socket.on(e,n);this.KeepAliveManager?.start(this.socket),this.startHealthCheck()}),this.socket.on("disconnect",e=>{this.log("Disconnected:",e),this.eventEmitter.emit("lifecycle:disconnect",e),this.KeepAliveManager?.stop(),this.stopHealthCheck()}),this.socket.on("connect_error",e=>{this.log("Connection error:",e.message),this.eventEmitter.emit("lifecycle:connect_error",e),setTimeout(()=>this.socket?.connect(),5e3)}),this.socket.on("error",e=>{this.log("Socket error:",e),this.eventEmitter.emit("lifecycle:error",e)}))}startHealthCheck(){const e=this.config.healthCheckConfig;if(!1===e?.enabled)return;const n=e?.intervalMs??3e4,a=e?.timeoutMs??5e3;this.stopHealthCheck(),this.healthCheckInterval=setInterval(()=>{if(!this.socket||!this.connected)return;const e=setTimeout(()=>{this.log("Health check timeout - forcing reconnect"),this.socket&&(this.socket.disconnect(),this.socket.connect())},a);this.socket.once("pong",()=>{clearTimeout(e)}),this.socket.emit("ping")},n)}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}log(e,...n){this.config.logger&&this.config.logger(`[SocketClient] ${e}`,...n)}}function hn(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var n=e.default;if("function"==typeof n){var a=function e(){var a=!1;try{a=this instanceof e}catch{}return a?Reflect.construct(n,arguments,this.constructor):n.apply(this,arguments)};a.prototype=n.prototype}else a={};return Object.defineProperty(a,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var t=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(a,n,t.get?t:{enumerable:!0,get:function(){return e[n]}})}),a}var fn,xn,vn,bn,yn,wn={},kn={"application/1d-interleaved-parityfec":{source:"iana"},"application/3gpdash-qoe-report+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/3gpp-ims+xml":{source:"iana",compressible:!0},"application/3gpphal+json":{source:"iana",compressible:!0},"application/3gpphalforms+json":{source:"iana",compressible:!0},"application/a2l":{source:"iana"},"application/ace+cbor":{source:"iana"},"application/ace+json":{source:"iana",compressible:!0},"application/ace-groupcomm+cbor":{source:"iana"},"application/ace-trl+cbor":{source:"iana"},"application/activemessage":{source:"iana"},"application/activity+json":{source:"iana",compressible:!0},"application/aif+cbor":{source:"iana"},"application/aif+json":{source:"iana",compressible:!0},"application/alto-cdni+json":{source:"iana",compressible:!0},"application/alto-cdnifilter+json":{source:"iana",compressible:!0},"application/alto-costmap+json":{source:"iana",compressible:!0},"application/alto-costmapfilter+json":{source:"iana",compressible:!0},"application/alto-directory+json":{source:"iana",compressible:!0},"application/alto-endpointcost+json":{source:"iana",compressible:!0},"application/alto-endpointcostparams+json":{source:"iana",compressible:!0},"application/alto-endpointprop+json":{source:"iana",compressible:!0},"application/alto-endpointpropparams+json":{source:"iana",compressible:!0},"application/alto-error+json":{source:"iana",compressible:!0},"application/alto-networkmap+json":{source:"iana",compressible:!0},"application/alto-networkmapfilter+json":{source:"iana",compressible:!0},"application/alto-propmap+json":{source:"iana",compressible:!0},"application/alto-propmapparams+json":{source:"iana",compressible:!0},"application/alto-tips+json":{source:"iana",compressible:!0},"application/alto-tipsparams+json":{source:"iana",compressible:!0},"application/alto-updatestreamcontrol+json":{source:"iana",compressible:!0},"application/alto-updatestreamparams+json":{source:"iana",compressible:!0},"application/aml":{source:"iana"},"application/andrew-inset":{source:"iana",extensions:["ez"]},"application/appinstaller":{compressible:!1,extensions:["appinstaller"]},"application/applefile":{source:"iana"},"application/applixware":{source:"apache",extensions:["aw"]},"application/appx":{compressible:!1,extensions:["appx"]},"application/appxbundle":{compressible:!1,extensions:["appxbundle"]},"application/at+jwt":{source:"iana"},"application/atf":{source:"iana"},"application/atfx":{source:"iana"},"application/atom+xml":{source:"iana",compressible:!0,extensions:["atom"]},"application/atomcat+xml":{source:"iana",compressible:!0,extensions:["atomcat"]},"application/atomdeleted+xml":{source:"iana",compressible:!0,extensions:["atomdeleted"]},"application/atomicmail":{source:"iana"},"application/atomsvc+xml":{source:"iana",compressible:!0,extensions:["atomsvc"]},"application/atsc-dwd+xml":{source:"iana",compressible:!0,extensions:["dwd"]},"application/atsc-dynamic-event-message":{source:"iana"},"application/atsc-held+xml":{source:"iana",compressible:!0,extensions:["held"]},"application/atsc-rdt+json":{source:"iana",compressible:!0},"application/atsc-rsat+xml":{source:"iana",compressible:!0,extensions:["rsat"]},"application/atxml":{source:"iana"},"application/auth-policy+xml":{source:"iana",compressible:!0},"application/automationml-aml+xml":{source:"iana",compressible:!0,extensions:["aml"]},"application/automationml-amlx+zip":{source:"iana",compressible:!1,extensions:["amlx"]},"application/bacnet-xdd+zip":{source:"iana",compressible:!1},"application/batch-smtp":{source:"iana"},"application/bdoc":{compressible:!1,extensions:["bdoc"]},"application/beep+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/bufr":{source:"iana"},"application/c2pa":{source:"iana"},"application/calendar+json":{source:"iana",compressible:!0},"application/calendar+xml":{source:"iana",compressible:!0,extensions:["xcs"]},"application/call-completion":{source:"iana"},"application/cals-1840":{source:"iana"},"application/captive+json":{source:"iana",compressible:!0},"application/cbor":{source:"iana"},"application/cbor-seq":{source:"iana"},"application/cccex":{source:"iana"},"application/ccmp+xml":{source:"iana",compressible:!0},"application/ccxml+xml":{source:"iana",compressible:!0,extensions:["ccxml"]},"application/cda+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/cdfx+xml":{source:"iana",compressible:!0,extensions:["cdfx"]},"application/cdmi-capability":{source:"iana",extensions:["cdmia"]},"application/cdmi-container":{source:"iana",extensions:["cdmic"]},"application/cdmi-domain":{source:"iana",extensions:["cdmid"]},"application/cdmi-object":{source:"iana",extensions:["cdmio"]},"application/cdmi-queue":{source:"iana",extensions:["cdmiq"]},"application/cdni":{source:"iana"},"application/ce+cbor":{source:"iana"},"application/cea":{source:"iana"},"application/cea-2018+xml":{source:"iana",compressible:!0},"application/cellml+xml":{source:"iana",compressible:!0},"application/cfw":{source:"iana"},"application/cid-edhoc+cbor-seq":{source:"iana"},"application/city+json":{source:"iana",compressible:!0},"application/city+json-seq":{source:"iana"},"application/clr":{source:"iana"},"application/clue+xml":{source:"iana",compressible:!0},"application/clue_info+xml":{source:"iana",compressible:!0},"application/cms":{source:"iana"},"application/cnrp+xml":{source:"iana",compressible:!0},"application/coap-eap":{source:"iana"},"application/coap-group+json":{source:"iana",compressible:!0},"application/coap-payload":{source:"iana"},"application/commonground":{source:"iana"},"application/concise-problem-details+cbor":{source:"iana"},"application/conference-info+xml":{source:"iana",compressible:!0},"application/cose":{source:"iana"},"application/cose-key":{source:"iana"},"application/cose-key-set":{source:"iana"},"application/cose-x509":{source:"iana"},"application/cpl+xml":{source:"iana",compressible:!0,extensions:["cpl"]},"application/csrattrs":{source:"iana"},"application/csta+xml":{source:"iana",compressible:!0},"application/cstadata+xml":{source:"iana",compressible:!0},"application/csvm+json":{source:"iana",compressible:!0},"application/cu-seeme":{source:"apache",extensions:["cu"]},"application/cwl":{source:"iana",extensions:["cwl"]},"application/cwl+json":{source:"iana",compressible:!0},"application/cwl+yaml":{source:"iana"},"application/cwt":{source:"iana"},"application/cybercash":{source:"iana"},"application/dart":{compressible:!0},"application/dash+xml":{source:"iana",compressible:!0,extensions:["mpd"]},"application/dash-patch+xml":{source:"iana",compressible:!0,extensions:["mpp"]},"application/dashdelta":{source:"iana"},"application/davmount+xml":{source:"iana",compressible:!0,extensions:["davmount"]},"application/dca-rft":{source:"iana"},"application/dcd":{source:"iana"},"application/dec-dx":{source:"iana"},"application/dialog-info+xml":{source:"iana",compressible:!0},"application/dicom":{source:"iana",extensions:["dcm"]},"application/dicom+json":{source:"iana",compressible:!0},"application/dicom+xml":{source:"iana",compressible:!0},"application/dii":{source:"iana"},"application/dit":{source:"iana"},"application/dns":{source:"iana"},"application/dns+json":{source:"iana",compressible:!0},"application/dns-message":{source:"iana"},"application/docbook+xml":{source:"apache",compressible:!0,extensions:["dbk"]},"application/dots+cbor":{source:"iana"},"application/dpop+jwt":{source:"iana"},"application/dskpp+xml":{source:"iana",compressible:!0},"application/dssc+der":{source:"iana",extensions:["dssc"]},"application/dssc+xml":{source:"iana",compressible:!0,extensions:["xdssc"]},"application/dvcs":{source:"iana"},"application/eat+cwt":{source:"iana"},"application/eat+jwt":{source:"iana"},"application/eat-bun+cbor":{source:"iana"},"application/eat-bun+json":{source:"iana",compressible:!0},"application/eat-ucs+cbor":{source:"iana"},"application/eat-ucs+json":{source:"iana",compressible:!0},"application/ecmascript":{source:"apache",compressible:!0,extensions:["ecma"]},"application/edhoc+cbor-seq":{source:"iana"},"application/edi-consent":{source:"iana"},"application/edi-x12":{source:"iana",compressible:!1},"application/edifact":{source:"iana",compressible:!1},"application/efi":{source:"iana"},"application/elm+json":{source:"iana",charset:"UTF-8",compressible:!0},"application/elm+xml":{source:"iana",compressible:!0},"application/emergencycalldata.cap+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/emergencycalldata.comment+xml":{source:"iana",compressible:!0},"application/emergencycalldata.control+xml":{source:"iana",compressible:!0},"application/emergencycalldata.deviceinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.ecall.msd":{source:"iana"},"application/emergencycalldata.legacyesn+json":{source:"iana",compressible:!0},"application/emergencycalldata.providerinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.serviceinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.subscriberinfo+xml":{source:"iana",compressible:!0},"application/emergencycalldata.veds+xml":{source:"iana",compressible:!0},"application/emma+xml":{source:"iana",compressible:!0,extensions:["emma"]},"application/emotionml+xml":{source:"iana",compressible:!0,extensions:["emotionml"]},"application/encaprtp":{source:"iana"},"application/entity-statement+jwt":{source:"iana"},"application/epp+xml":{source:"iana",compressible:!0},"application/epub+zip":{source:"iana",compressible:!1,extensions:["epub"]},"application/eshop":{source:"iana"},"application/exi":{source:"iana",extensions:["exi"]},"application/expect-ct-report+json":{source:"iana",compressible:!0},"application/express":{source:"iana",extensions:["exp"]},"application/fastinfoset":{source:"iana"},"application/fastsoap":{source:"iana"},"application/fdf":{source:"iana",extensions:["fdf"]},"application/fdt+xml":{source:"iana",compressible:!0,extensions:["fdt"]},"application/fhir+json":{source:"iana",charset:"UTF-8",compressible:!0},"application/fhir+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/fido.trusted-apps+json":{compressible:!0},"application/fits":{source:"iana"},"application/flexfec":{source:"iana"},"application/font-sfnt":{source:"iana"},"application/font-tdpfr":{source:"iana",extensions:["pfr"]},"application/font-woff":{source:"iana",compressible:!1},"application/framework-attributes+xml":{source:"iana",compressible:!0},"application/geo+json":{source:"iana",compressible:!0,extensions:["geojson"]},"application/geo+json-seq":{source:"iana"},"application/geopackage+sqlite3":{source:"iana"},"application/geopose+json":{source:"iana",compressible:!0},"application/geoxacml+json":{source:"iana",compressible:!0},"application/geoxacml+xml":{source:"iana",compressible:!0},"application/gltf-buffer":{source:"iana"},"application/gml+xml":{source:"iana",compressible:!0,extensions:["gml"]},"application/gnap-binding-jws":{source:"iana"},"application/gnap-binding-jwsd":{source:"iana"},"application/gnap-binding-rotation-jws":{source:"iana"},"application/gnap-binding-rotation-jwsd":{source:"iana"},"application/gpx+xml":{source:"apache",compressible:!0,extensions:["gpx"]},"application/grib":{source:"iana"},"application/gxf":{source:"apache",extensions:["gxf"]},"application/gzip":{source:"iana",compressible:!1,extensions:["gz"]},"application/h224":{source:"iana"},"application/held+xml":{source:"iana",compressible:!0},"application/hjson":{extensions:["hjson"]},"application/hl7v2+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/http":{source:"iana"},"application/hyperstudio":{source:"iana",extensions:["stk"]},"application/ibe-key-request+xml":{source:"iana",compressible:!0},"application/ibe-pkg-reply+xml":{source:"iana",compressible:!0},"application/ibe-pp-data":{source:"iana"},"application/iges":{source:"iana"},"application/im-iscomposing+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/index":{source:"iana"},"application/index.cmd":{source:"iana"},"application/index.obj":{source:"iana"},"application/index.response":{source:"iana"},"application/index.vnd":{source:"iana"},"application/inkml+xml":{source:"iana",compressible:!0,extensions:["ink","inkml"]},"application/iotp":{source:"iana"},"application/ipfix":{source:"iana",extensions:["ipfix"]},"application/ipp":{source:"iana"},"application/isup":{source:"iana"},"application/its+xml":{source:"iana",compressible:!0,extensions:["its"]},"application/java-archive":{source:"iana",compressible:!1,extensions:["jar","war","ear"]},"application/java-serialized-object":{source:"apache",compressible:!1,extensions:["ser"]},"application/java-vm":{source:"apache",compressible:!1,extensions:["class"]},"application/javascript":{source:"apache",charset:"UTF-8",compressible:!0,extensions:["js"]},"application/jf2feed+json":{source:"iana",compressible:!0},"application/jose":{source:"iana"},"application/jose+json":{source:"iana",compressible:!0},"application/jrd+json":{source:"iana",compressible:!0},"application/jscalendar+json":{source:"iana",compressible:!0},"application/jscontact+json":{source:"iana",compressible:!0},"application/json":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["json","map"]},"application/json-patch+json":{source:"iana",compressible:!0},"application/json-seq":{source:"iana"},"application/json5":{extensions:["json5"]},"application/jsonml+json":{source:"apache",compressible:!0,extensions:["jsonml"]},"application/jsonpath":{source:"iana"},"application/jwk+json":{source:"iana",compressible:!0},"application/jwk-set+json":{source:"iana",compressible:!0},"application/jwk-set+jwt":{source:"iana"},"application/jwt":{source:"iana"},"application/kpml-request+xml":{source:"iana",compressible:!0},"application/kpml-response+xml":{source:"iana",compressible:!0},"application/ld+json":{source:"iana",compressible:!0,extensions:["jsonld"]},"application/lgr+xml":{source:"iana",compressible:!0,extensions:["lgr"]},"application/link-format":{source:"iana"},"application/linkset":{source:"iana"},"application/linkset+json":{source:"iana",compressible:!0},"application/load-control+xml":{source:"iana",compressible:!0},"application/logout+jwt":{source:"iana"},"application/lost+xml":{source:"iana",compressible:!0,extensions:["lostxml"]},"application/lostsync+xml":{source:"iana",compressible:!0},"application/lpf+zip":{source:"iana",compressible:!1},"application/lxf":{source:"iana"},"application/mac-binhex40":{source:"iana",extensions:["hqx"]},"application/mac-compactpro":{source:"apache",extensions:["cpt"]},"application/macwriteii":{source:"iana"},"application/mads+xml":{source:"iana",compressible:!0,extensions:["mads"]},"application/manifest+json":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["webmanifest"]},"application/marc":{source:"iana",extensions:["mrc"]},"application/marcxml+xml":{source:"iana",compressible:!0,extensions:["mrcx"]},"application/mathematica":{source:"iana",extensions:["ma","nb","mb"]},"application/mathml+xml":{source:"iana",compressible:!0,extensions:["mathml"]},"application/mathml-content+xml":{source:"iana",compressible:!0},"application/mathml-presentation+xml":{source:"iana",compressible:!0},"application/mbms-associated-procedure-description+xml":{source:"iana",compressible:!0},"application/mbms-deregister+xml":{source:"iana",compressible:!0},"application/mbms-envelope+xml":{source:"iana",compressible:!0},"application/mbms-msk+xml":{source:"iana",compressible:!0},"application/mbms-msk-response+xml":{source:"iana",compressible:!0},"application/mbms-protection-description+xml":{source:"iana",compressible:!0},"application/mbms-reception-report+xml":{source:"iana",compressible:!0},"application/mbms-register+xml":{source:"iana",compressible:!0},"application/mbms-register-response+xml":{source:"iana",compressible:!0},"application/mbms-schedule+xml":{source:"iana",compressible:!0},"application/mbms-user-service-description+xml":{source:"iana",compressible:!0},"application/mbox":{source:"iana",extensions:["mbox"]},"application/media-policy-dataset+xml":{source:"iana",compressible:!0,extensions:["mpf"]},"application/media_control+xml":{source:"iana",compressible:!0},"application/mediaservercontrol+xml":{source:"iana",compressible:!0,extensions:["mscml"]},"application/merge-patch+json":{source:"iana",compressible:!0},"application/metalink+xml":{source:"apache",compressible:!0,extensions:["metalink"]},"application/metalink4+xml":{source:"iana",compressible:!0,extensions:["meta4"]},"application/mets+xml":{source:"iana",compressible:!0,extensions:["mets"]},"application/mf4":{source:"iana"},"application/mikey":{source:"iana"},"application/mipc":{source:"iana"},"application/missing-blocks+cbor-seq":{source:"iana"},"application/mmt-aei+xml":{source:"iana",compressible:!0,extensions:["maei"]},"application/mmt-usd+xml":{source:"iana",compressible:!0,extensions:["musd"]},"application/mods+xml":{source:"iana",compressible:!0,extensions:["mods"]},"application/moss-keys":{source:"iana"},"application/moss-signature":{source:"iana"},"application/mosskey-data":{source:"iana"},"application/mosskey-request":{source:"iana"},"application/mp21":{source:"iana",extensions:["m21","mp21"]},"application/mp4":{source:"iana",extensions:["mp4","mpg4","mp4s","m4p"]},"application/mpeg4-generic":{source:"iana"},"application/mpeg4-iod":{source:"iana"},"application/mpeg4-iod-xmt":{source:"iana"},"application/mrb-consumer+xml":{source:"iana",compressible:!0},"application/mrb-publish+xml":{source:"iana",compressible:!0},"application/msc-ivr+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/msc-mixer+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/msix":{compressible:!1,extensions:["msix"]},"application/msixbundle":{compressible:!1,extensions:["msixbundle"]},"application/msword":{source:"iana",compressible:!1,extensions:["doc","dot"]},"application/mud+json":{source:"iana",compressible:!0},"application/multipart-core":{source:"iana"},"application/mxf":{source:"iana",extensions:["mxf"]},"application/n-quads":{source:"iana",extensions:["nq"]},"application/n-triples":{source:"iana",extensions:["nt"]},"application/nasdata":{source:"iana"},"application/news-checkgroups":{source:"iana",charset:"US-ASCII"},"application/news-groupinfo":{source:"iana",charset:"US-ASCII"},"application/news-transmission":{source:"iana"},"application/nlsml+xml":{source:"iana",compressible:!0},"application/node":{source:"iana",extensions:["cjs"]},"application/nss":{source:"iana"},"application/oauth-authz-req+jwt":{source:"iana"},"application/oblivious-dns-message":{source:"iana"},"application/ocsp-request":{source:"iana"},"application/ocsp-response":{source:"iana"},"application/octet-stream":{source:"iana",compressible:!0,extensions:["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{source:"iana",extensions:["oda"]},"application/odm+xml":{source:"iana",compressible:!0},"application/odx":{source:"iana"},"application/oebps-package+xml":{source:"iana",compressible:!0,extensions:["opf"]},"application/ogg":{source:"iana",compressible:!1,extensions:["ogx"]},"application/ohttp-keys":{source:"iana"},"application/omdoc+xml":{source:"apache",compressible:!0,extensions:["omdoc"]},"application/onenote":{source:"apache",extensions:["onetoc","onetoc2","onetmp","onepkg","one","onea"]},"application/opc-nodeset+xml":{source:"iana",compressible:!0},"application/oscore":{source:"iana"},"application/oxps":{source:"iana",extensions:["oxps"]},"application/p21":{source:"iana"},"application/p21+zip":{source:"iana",compressible:!1},"application/p2p-overlay+xml":{source:"iana",compressible:!0,extensions:["relo"]},"application/parityfec":{source:"iana"},"application/passport":{source:"iana"},"application/patch-ops-error+xml":{source:"iana",compressible:!0,extensions:["xer"]},"application/pdf":{source:"iana",compressible:!1,extensions:["pdf"]},"application/pdx":{source:"iana"},"application/pem-certificate-chain":{source:"iana"},"application/pgp-encrypted":{source:"iana",compressible:!1,extensions:["pgp"]},"application/pgp-keys":{source:"iana",extensions:["asc"]},"application/pgp-signature":{source:"iana",extensions:["sig","asc"]},"application/pics-rules":{source:"apache",extensions:["prf"]},"application/pidf+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/pidf-diff+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/pkcs10":{source:"iana",extensions:["p10"]},"application/pkcs12":{source:"iana"},"application/pkcs7-mime":{source:"iana",extensions:["p7m","p7c"]},"application/pkcs7-signature":{source:"iana",extensions:["p7s"]},"application/pkcs8":{source:"iana",extensions:["p8"]},"application/pkcs8-encrypted":{source:"iana"},"application/pkix-attr-cert":{source:"iana",extensions:["ac"]},"application/pkix-cert":{source:"iana",extensions:["cer"]},"application/pkix-crl":{source:"iana",extensions:["crl"]},"application/pkix-pkipath":{source:"iana",extensions:["pkipath"]},"application/pkixcmp":{source:"iana",extensions:["pki"]},"application/pls+xml":{source:"iana",compressible:!0,extensions:["pls"]},"application/poc-settings+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/postscript":{source:"iana",compressible:!0,extensions:["ai","eps","ps"]},"application/ppsp-tracker+json":{source:"iana",compressible:!0},"application/private-token-issuer-directory":{source:"iana"},"application/private-token-request":{source:"iana"},"application/private-token-response":{source:"iana"},"application/problem+json":{source:"iana",compressible:!0},"application/problem+xml":{source:"iana",compressible:!0},"application/provenance+xml":{source:"iana",compressible:!0,extensions:["provx"]},"application/provided-claims+jwt":{source:"iana"},"application/prs.alvestrand.titrax-sheet":{source:"iana"},"application/prs.cww":{source:"iana",extensions:["cww"]},"application/prs.cyn":{source:"iana",charset:"7-BIT"},"application/prs.hpub+zip":{source:"iana",compressible:!1},"application/prs.implied-document+xml":{source:"iana",compressible:!0},"application/prs.implied-executable":{source:"iana"},"application/prs.implied-object+json":{source:"iana",compressible:!0},"application/prs.implied-object+json-seq":{source:"iana"},"application/prs.implied-object+yaml":{source:"iana"},"application/prs.implied-structure":{source:"iana"},"application/prs.mayfile":{source:"iana"},"application/prs.nprend":{source:"iana"},"application/prs.plucker":{source:"iana"},"application/prs.rdf-xml-crypt":{source:"iana"},"application/prs.vcfbzip2":{source:"iana"},"application/prs.xsf+xml":{source:"iana",compressible:!0,extensions:["xsf"]},"application/pskc+xml":{source:"iana",compressible:!0,extensions:["pskcxml"]},"application/pvd+json":{source:"iana",compressible:!0},"application/qsig":{source:"iana"},"application/raml+yaml":{compressible:!0,extensions:["raml"]},"application/raptorfec":{source:"iana"},"application/rdap+json":{source:"iana",compressible:!0},"application/rdf+xml":{source:"iana",compressible:!0,extensions:["rdf","owl"]},"application/reginfo+xml":{source:"iana",compressible:!0,extensions:["rif"]},"application/relax-ng-compact-syntax":{source:"iana",extensions:["rnc"]},"application/remote-printing":{source:"apache"},"application/reputon+json":{source:"iana",compressible:!0},"application/resolve-response+jwt":{source:"iana"},"application/resource-lists+xml":{source:"iana",compressible:!0,extensions:["rl"]},"application/resource-lists-diff+xml":{source:"iana",compressible:!0,extensions:["rld"]},"application/rfc+xml":{source:"iana",compressible:!0},"application/riscos":{source:"iana"},"application/rlmi+xml":{source:"iana",compressible:!0},"application/rls-services+xml":{source:"iana",compressible:!0,extensions:["rs"]},"application/route-apd+xml":{source:"iana",compressible:!0,extensions:["rapd"]},"application/route-s-tsid+xml":{source:"iana",compressible:!0,extensions:["sls"]},"application/route-usd+xml":{source:"iana",compressible:!0,extensions:["rusd"]},"application/rpki-checklist":{source:"iana"},"application/rpki-ghostbusters":{source:"iana",extensions:["gbr"]},"application/rpki-manifest":{source:"iana",extensions:["mft"]},"application/rpki-publication":{source:"iana"},"application/rpki-roa":{source:"iana",extensions:["roa"]},"application/rpki-signed-tal":{source:"iana"},"application/rpki-updown":{source:"iana"},"application/rsd+xml":{source:"apache",compressible:!0,extensions:["rsd"]},"application/rss+xml":{source:"apache",compressible:!0,extensions:["rss"]},"application/rtf":{source:"iana",compressible:!0,extensions:["rtf"]},"application/rtploopback":{source:"iana"},"application/rtx":{source:"iana"},"application/samlassertion+xml":{source:"iana",compressible:!0},"application/samlmetadata+xml":{source:"iana",compressible:!0},"application/sarif+json":{source:"iana",compressible:!0},"application/sarif-external-properties+json":{source:"iana",compressible:!0},"application/sbe":{source:"iana"},"application/sbml+xml":{source:"iana",compressible:!0,extensions:["sbml"]},"application/scaip+xml":{source:"iana",compressible:!0},"application/scim+json":{source:"iana",compressible:!0},"application/scvp-cv-request":{source:"iana",extensions:["scq"]},"application/scvp-cv-response":{source:"iana",extensions:["scs"]},"application/scvp-vp-request":{source:"iana",extensions:["spq"]},"application/scvp-vp-response":{source:"iana",extensions:["spp"]},"application/sdp":{source:"iana",extensions:["sdp"]},"application/secevent+jwt":{source:"iana"},"application/senml+cbor":{source:"iana"},"application/senml+json":{source:"iana",compressible:!0},"application/senml+xml":{source:"iana",compressible:!0,extensions:["senmlx"]},"application/senml-etch+cbor":{source:"iana"},"application/senml-etch+json":{source:"iana",compressible:!0},"application/senml-exi":{source:"iana"},"application/sensml+cbor":{source:"iana"},"application/sensml+json":{source:"iana",compressible:!0},"application/sensml+xml":{source:"iana",compressible:!0,extensions:["sensmlx"]},"application/sensml-exi":{source:"iana"},"application/sep+xml":{source:"iana",compressible:!0},"application/sep-exi":{source:"iana"},"application/session-info":{source:"iana"},"application/set-payment":{source:"iana"},"application/set-payment-initiation":{source:"iana",extensions:["setpay"]},"application/set-registration":{source:"iana"},"application/set-registration-initiation":{source:"iana",extensions:["setreg"]},"application/sgml":{source:"iana"},"application/sgml-open-catalog":{source:"iana"},"application/shf+xml":{source:"iana",compressible:!0,extensions:["shf"]},"application/sieve":{source:"iana",extensions:["siv","sieve"]},"application/simple-filter+xml":{source:"iana",compressible:!0},"application/simple-message-summary":{source:"iana"},"application/simplesymbolcontainer":{source:"iana"},"application/sipc":{source:"iana"},"application/slate":{source:"iana"},"application/smil":{source:"apache"},"application/smil+xml":{source:"iana",compressible:!0,extensions:["smi","smil"]},"application/smpte336m":{source:"iana"},"application/soap+fastinfoset":{source:"iana"},"application/soap+xml":{source:"iana",compressible:!0},"application/sparql-query":{source:"iana",extensions:["rq"]},"application/sparql-results+xml":{source:"iana",compressible:!0,extensions:["srx"]},"application/spdx+json":{source:"iana",compressible:!0},"application/spirits-event+xml":{source:"iana",compressible:!0},"application/sql":{source:"iana",extensions:["sql"]},"application/srgs":{source:"iana",extensions:["gram"]},"application/srgs+xml":{source:"iana",compressible:!0,extensions:["grxml"]},"application/sru+xml":{source:"iana",compressible:!0,extensions:["sru"]},"application/ssdl+xml":{source:"apache",compressible:!0,extensions:["ssdl"]},"application/sslkeylogfile":{source:"iana"},"application/ssml+xml":{source:"iana",compressible:!0,extensions:["ssml"]},"application/st2110-41":{source:"iana"},"application/stix+json":{source:"iana",compressible:!0},"application/stratum":{source:"iana"},"application/swid+cbor":{source:"iana"},"application/swid+xml":{source:"iana",compressible:!0,extensions:["swidtag"]},"application/tamp-apex-update":{source:"iana"},"application/tamp-apex-update-confirm":{source:"iana"},"application/tamp-community-update":{source:"iana"},"application/tamp-community-update-confirm":{source:"iana"},"application/tamp-error":{source:"iana"},"application/tamp-sequence-adjust":{source:"iana"},"application/tamp-sequence-adjust-confirm":{source:"iana"},"application/tamp-status-query":{source:"iana"},"application/tamp-status-response":{source:"iana"},"application/tamp-update":{source:"iana"},"application/tamp-update-confirm":{source:"iana"},"application/tar":{compressible:!0},"application/taxii+json":{source:"iana",compressible:!0},"application/td+json":{source:"iana",compressible:!0},"application/tei+xml":{source:"iana",compressible:!0,extensions:["tei","teicorpus"]},"application/tetra_isi":{source:"iana"},"application/thraud+xml":{source:"iana",compressible:!0,extensions:["tfi"]},"application/timestamp-query":{source:"iana"},"application/timestamp-reply":{source:"iana"},"application/timestamped-data":{source:"iana",extensions:["tsd"]},"application/tlsrpt+gzip":{source:"iana"},"application/tlsrpt+json":{source:"iana",compressible:!0},"application/tm+json":{source:"iana",compressible:!0},"application/tnauthlist":{source:"iana"},"application/toc+cbor":{source:"iana"},"application/token-introspection+jwt":{source:"iana"},"application/toml":{source:"iana",compressible:!0,extensions:["toml"]},"application/trickle-ice-sdpfrag":{source:"iana"},"application/trig":{source:"iana",extensions:["trig"]},"application/trust-chain+json":{source:"iana",compressible:!0},"application/trust-mark+jwt":{source:"iana"},"application/trust-mark-delegation+jwt":{source:"iana"},"application/ttml+xml":{source:"iana",compressible:!0,extensions:["ttml"]},"application/tve-trigger":{source:"iana"},"application/tzif":{source:"iana"},"application/tzif-leap":{source:"iana"},"application/ubjson":{compressible:!1,extensions:["ubj"]},"application/uccs+cbor":{source:"iana"},"application/ujcs+json":{source:"iana",compressible:!0},"application/ulpfec":{source:"iana"},"application/urc-grpsheet+xml":{source:"iana",compressible:!0},"application/urc-ressheet+xml":{source:"iana",compressible:!0,extensions:["rsheet"]},"application/urc-targetdesc+xml":{source:"iana",compressible:!0,extensions:["td"]},"application/urc-uisocketdesc+xml":{source:"iana",compressible:!0},"application/vc":{source:"iana"},"application/vc+cose":{source:"iana"},"application/vc+jwt":{source:"iana"},"application/vcard+json":{source:"iana",compressible:!0},"application/vcard+xml":{source:"iana",compressible:!0},"application/vemmi":{source:"iana"},"application/vividence.scriptfile":{source:"apache"},"application/vnd.1000minds.decision-model+xml":{source:"iana",compressible:!0,extensions:["1km"]},"application/vnd.1ob":{source:"iana"},"application/vnd.3gpp-prose+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3a+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3ach+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3ch+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc8+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-v2x-local-service-information":{source:"iana"},"application/vnd.3gpp.5gnas":{source:"iana"},"application/vnd.3gpp.5gsa2x":{source:"iana"},"application/vnd.3gpp.5gsa2x-local-service-information":{source:"iana"},"application/vnd.3gpp.5gsv2x":{source:"iana"},"application/vnd.3gpp.5gsv2x-local-service-information":{source:"iana"},"application/vnd.3gpp.access-transfer-events+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.bsf+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.crs+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.current-location-discovery+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.gmop+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.gtpc":{source:"iana"},"application/vnd.3gpp.interworking-data":{source:"iana"},"application/vnd.3gpp.lpp":{source:"iana"},"application/vnd.3gpp.mc-signalling-ear":{source:"iana"},"application/vnd.3gpp.mcdata-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-msgstore-ctrl-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-payload":{source:"iana"},"application/vnd.3gpp.mcdata-regroup+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-signalling":{source:"iana"},"application/vnd.3gpp.mcdata-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcdata-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-floor-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-regroup+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-signed+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-ue-init-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcptt-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-affiliation-command+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-regroup+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-service-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-transmission-request+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-ue-config+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mcvideo-user-profile+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.mid-call+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.ngap":{source:"iana"},"application/vnd.3gpp.pfcp":{source:"iana"},"application/vnd.3gpp.pic-bw-large":{source:"iana",extensions:["plb"]},"application/vnd.3gpp.pic-bw-small":{source:"iana",extensions:["psb"]},"application/vnd.3gpp.pic-bw-var":{source:"iana",extensions:["pvb"]},"application/vnd.3gpp.pinapp-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.s1ap":{source:"iana"},"application/vnd.3gpp.seal-group-doc+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-location-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-mbms-usage-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-network-qos-management-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-ue-config-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-unicast-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.seal-user-profile-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.sms":{source:"iana"},"application/vnd.3gpp.sms+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.srvcc-ext+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.srvcc-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.state-and-event-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.ussd+xml":{source:"iana",compressible:!0},"application/vnd.3gpp.v2x":{source:"iana"},"application/vnd.3gpp.vae-info+xml":{source:"iana",compressible:!0},"application/vnd.3gpp2.bcmcsinfo+xml":{source:"iana",compressible:!0},"application/vnd.3gpp2.sms":{source:"iana"},"application/vnd.3gpp2.tcap":{source:"iana",extensions:["tcap"]},"application/vnd.3lightssoftware.imagescal":{source:"iana"},"application/vnd.3m.post-it-notes":{source:"iana",extensions:["pwn"]},"application/vnd.accpac.simply.aso":{source:"iana",extensions:["aso"]},"application/vnd.accpac.simply.imp":{source:"iana",extensions:["imp"]},"application/vnd.acm.addressxfer+json":{source:"iana",compressible:!0},"application/vnd.acm.chatbot+json":{source:"iana",compressible:!0},"application/vnd.acucobol":{source:"iana",extensions:["acu"]},"application/vnd.acucorp":{source:"iana",extensions:["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{source:"apache",compressible:!1,extensions:["air"]},"application/vnd.adobe.flash.movie":{source:"iana"},"application/vnd.adobe.formscentral.fcdt":{source:"iana",extensions:["fcdt"]},"application/vnd.adobe.fxp":{source:"iana",extensions:["fxp","fxpl"]},"application/vnd.adobe.partial-upload":{source:"iana"},"application/vnd.adobe.xdp+xml":{source:"iana",compressible:!0,extensions:["xdp"]},"application/vnd.adobe.xfdf":{source:"apache",extensions:["xfdf"]},"application/vnd.aether.imp":{source:"iana"},"application/vnd.afpc.afplinedata":{source:"iana"},"application/vnd.afpc.afplinedata-pagedef":{source:"iana"},"application/vnd.afpc.cmoca-cmresource":{source:"iana"},"application/vnd.afpc.foca-charset":{source:"iana"},"application/vnd.afpc.foca-codedfont":{source:"iana"},"application/vnd.afpc.foca-codepage":{source:"iana"},"application/vnd.afpc.modca":{source:"iana"},"application/vnd.afpc.modca-cmtable":{source:"iana"},"application/vnd.afpc.modca-formdef":{source:"iana"},"application/vnd.afpc.modca-mediummap":{source:"iana"},"application/vnd.afpc.modca-objectcontainer":{source:"iana"},"application/vnd.afpc.modca-overlay":{source:"iana"},"application/vnd.afpc.modca-pagesegment":{source:"iana"},"application/vnd.age":{source:"iana",extensions:["age"]},"application/vnd.ah-barcode":{source:"apache"},"application/vnd.ahead.space":{source:"iana",extensions:["ahead"]},"application/vnd.airzip.filesecure.azf":{source:"iana",extensions:["azf"]},"application/vnd.airzip.filesecure.azs":{source:"iana",extensions:["azs"]},"application/vnd.amadeus+json":{source:"iana",compressible:!0},"application/vnd.amazon.ebook":{source:"apache",extensions:["azw"]},"application/vnd.amazon.mobi8-ebook":{source:"iana"},"application/vnd.americandynamics.acc":{source:"iana",extensions:["acc"]},"application/vnd.amiga.ami":{source:"iana",extensions:["ami"]},"application/vnd.amundsen.maze+xml":{source:"iana",compressible:!0},"application/vnd.android.ota":{source:"iana"},"application/vnd.android.package-archive":{source:"apache",compressible:!1,extensions:["apk"]},"application/vnd.anki":{source:"iana"},"application/vnd.anser-web-certificate-issue-initiation":{source:"iana",extensions:["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{source:"apache",extensions:["fti"]},"application/vnd.antix.game-component":{source:"iana",extensions:["atx"]},"application/vnd.apache.arrow.file":{source:"iana"},"application/vnd.apache.arrow.stream":{source:"iana"},"application/vnd.apache.parquet":{source:"iana"},"application/vnd.apache.thrift.binary":{source:"iana"},"application/vnd.apache.thrift.compact":{source:"iana"},"application/vnd.apache.thrift.json":{source:"iana"},"application/vnd.apexlang":{source:"iana"},"application/vnd.api+json":{source:"iana",compressible:!0},"application/vnd.aplextor.warrp+json":{source:"iana",compressible:!0},"application/vnd.apothekende.reservation+json":{source:"iana",compressible:!0},"application/vnd.apple.installer+xml":{source:"iana",compressible:!0,extensions:["mpkg"]},"application/vnd.apple.keynote":{source:"iana",extensions:["key"]},"application/vnd.apple.mpegurl":{source:"iana",extensions:["m3u8"]},"application/vnd.apple.numbers":{source:"iana",extensions:["numbers"]},"application/vnd.apple.pages":{source:"iana",extensions:["pages"]},"application/vnd.apple.pkpass":{compressible:!1,extensions:["pkpass"]},"application/vnd.arastra.swi":{source:"apache"},"application/vnd.aristanetworks.swi":{source:"iana",extensions:["swi"]},"application/vnd.artisan+json":{source:"iana",compressible:!0},"application/vnd.artsquare":{source:"iana"},"application/vnd.astraea-software.iota":{source:"iana",extensions:["iota"]},"application/vnd.audiograph":{source:"iana",extensions:["aep"]},"application/vnd.autodesk.fbx":{extensions:["fbx"]},"application/vnd.autopackage":{source:"iana"},"application/vnd.avalon+json":{source:"iana",compressible:!0},"application/vnd.avistar+xml":{source:"iana",compressible:!0},"application/vnd.balsamiq.bmml+xml":{source:"iana",compressible:!0,extensions:["bmml"]},"application/vnd.balsamiq.bmpr":{source:"iana"},"application/vnd.banana-accounting":{source:"iana"},"application/vnd.bbf.usp.error":{source:"iana"},"application/vnd.bbf.usp.msg":{source:"iana"},"application/vnd.bbf.usp.msg+json":{source:"iana",compressible:!0},"application/vnd.bekitzur-stech+json":{source:"iana",compressible:!0},"application/vnd.belightsoft.lhzd+zip":{source:"iana",compressible:!1},"application/vnd.belightsoft.lhzl+zip":{source:"iana",compressible:!1},"application/vnd.bint.med-content":{source:"iana"},"application/vnd.biopax.rdf+xml":{source:"iana",compressible:!0},"application/vnd.blink-idb-value-wrapper":{source:"iana"},"application/vnd.blueice.multipass":{source:"iana",extensions:["mpm"]},"application/vnd.bluetooth.ep.oob":{source:"iana"},"application/vnd.bluetooth.le.oob":{source:"iana"},"application/vnd.bmi":{source:"iana",extensions:["bmi"]},"application/vnd.bpf":{source:"iana"},"application/vnd.bpf3":{source:"iana"},"application/vnd.businessobjects":{source:"iana",extensions:["rep"]},"application/vnd.byu.uapi+json":{source:"iana",compressible:!0},"application/vnd.bzip3":{source:"iana"},"application/vnd.c3voc.schedule+xml":{source:"iana",compressible:!0},"application/vnd.cab-jscript":{source:"iana"},"application/vnd.canon-cpdl":{source:"iana"},"application/vnd.canon-lips":{source:"iana"},"application/vnd.capasystems-pg+json":{source:"iana",compressible:!0},"application/vnd.cendio.thinlinc.clientconf":{source:"iana"},"application/vnd.century-systems.tcp_stream":{source:"iana"},"application/vnd.chemdraw+xml":{source:"iana",compressible:!0,extensions:["cdxml"]},"application/vnd.chess-pgn":{source:"iana"},"application/vnd.chipnuts.karaoke-mmd":{source:"iana",extensions:["mmd"]},"application/vnd.ciedi":{source:"iana"},"application/vnd.cinderella":{source:"iana",extensions:["cdy"]},"application/vnd.cirpack.isdn-ext":{source:"iana"},"application/vnd.citationstyles.style+xml":{source:"iana",compressible:!0,extensions:["csl"]},"application/vnd.claymore":{source:"iana",extensions:["cla"]},"application/vnd.cloanto.rp9":{source:"iana",extensions:["rp9"]},"application/vnd.clonk.c4group":{source:"iana",extensions:["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{source:"iana",extensions:["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{source:"iana",extensions:["c11amz"]},"application/vnd.cncf.helm.chart.content.v1.tar+gzip":{source:"iana"},"application/vnd.cncf.helm.chart.provenance.v1.prov":{source:"iana"},"application/vnd.cncf.helm.config.v1+json":{source:"iana",compressible:!0},"application/vnd.coffeescript":{source:"iana"},"application/vnd.collabio.xodocuments.document":{source:"iana"},"application/vnd.collabio.xodocuments.document-template":{source:"iana"},"application/vnd.collabio.xodocuments.presentation":{source:"iana"},"application/vnd.collabio.xodocuments.presentation-template":{source:"iana"},"application/vnd.collabio.xodocuments.spreadsheet":{source:"iana"},"application/vnd.collabio.xodocuments.spreadsheet-template":{source:"iana"},"application/vnd.collection+json":{source:"iana",compressible:!0},"application/vnd.collection.doc+json":{source:"iana",compressible:!0},"application/vnd.collection.next+json":{source:"iana",compressible:!0},"application/vnd.comicbook+zip":{source:"iana",compressible:!1},"application/vnd.comicbook-rar":{source:"iana"},"application/vnd.commerce-battelle":{source:"iana"},"application/vnd.commonspace":{source:"iana",extensions:["csp"]},"application/vnd.contact.cmsg":{source:"iana",extensions:["cdbcmsg"]},"application/vnd.coreos.ignition+json":{source:"iana",compressible:!0},"application/vnd.cosmocaller":{source:"iana",extensions:["cmc"]},"application/vnd.crick.clicker":{source:"iana",extensions:["clkx"]},"application/vnd.crick.clicker.keyboard":{source:"iana",extensions:["clkk"]},"application/vnd.crick.clicker.palette":{source:"iana",extensions:["clkp"]},"application/vnd.crick.clicker.template":{source:"iana",extensions:["clkt"]},"application/vnd.crick.clicker.wordbank":{source:"iana",extensions:["clkw"]},"application/vnd.criticaltools.wbs+xml":{source:"iana",compressible:!0,extensions:["wbs"]},"application/vnd.cryptii.pipe+json":{source:"iana",compressible:!0},"application/vnd.crypto-shade-file":{source:"iana"},"application/vnd.cryptomator.encrypted":{source:"iana"},"application/vnd.cryptomator.vault":{source:"iana"},"application/vnd.ctc-posml":{source:"iana",extensions:["pml"]},"application/vnd.ctct.ws+xml":{source:"iana",compressible:!0},"application/vnd.cups-pdf":{source:"iana"},"application/vnd.cups-postscript":{source:"iana"},"application/vnd.cups-ppd":{source:"iana",extensions:["ppd"]},"application/vnd.cups-raster":{source:"iana"},"application/vnd.cups-raw":{source:"iana"},"application/vnd.curl":{source:"iana"},"application/vnd.curl.car":{source:"apache",extensions:["car"]},"application/vnd.curl.pcurl":{source:"apache",extensions:["pcurl"]},"application/vnd.cyan.dean.root+xml":{source:"iana",compressible:!0},"application/vnd.cybank":{source:"iana"},"application/vnd.cyclonedx+json":{source:"iana",compressible:!0},"application/vnd.cyclonedx+xml":{source:"iana",compressible:!0},"application/vnd.d2l.coursepackage1p0+zip":{source:"iana",compressible:!1},"application/vnd.d3m-dataset":{source:"iana"},"application/vnd.d3m-problem":{source:"iana"},"application/vnd.dart":{source:"iana",compressible:!0,extensions:["dart"]},"application/vnd.data-vision.rdz":{source:"iana",extensions:["rdz"]},"application/vnd.datalog":{source:"iana"},"application/vnd.datapackage+json":{source:"iana",compressible:!0},"application/vnd.dataresource+json":{source:"iana",compressible:!0},"application/vnd.dbf":{source:"iana",extensions:["dbf"]},"application/vnd.dcmp+xml":{source:"iana",compressible:!0,extensions:["dcmp"]},"application/vnd.debian.binary-package":{source:"iana"},"application/vnd.dece.data":{source:"iana",extensions:["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{source:"iana",compressible:!0,extensions:["uvt","uvvt"]},"application/vnd.dece.unspecified":{source:"iana",extensions:["uvx","uvvx"]},"application/vnd.dece.zip":{source:"iana",extensions:["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{source:"iana",extensions:["fe_launch"]},"application/vnd.desmume.movie":{source:"iana"},"application/vnd.dir-bi.plate-dl-nosuffix":{source:"iana"},"application/vnd.dm.delegation+xml":{source:"iana",compressible:!0},"application/vnd.dna":{source:"iana",extensions:["dna"]},"application/vnd.document+json":{source:"iana",compressible:!0},"application/vnd.dolby.mlp":{source:"apache",extensions:["mlp"]},"application/vnd.dolby.mobile.1":{source:"iana"},"application/vnd.dolby.mobile.2":{source:"iana"},"application/vnd.doremir.scorecloud-binary-document":{source:"iana"},"application/vnd.dpgraph":{source:"iana",extensions:["dpg"]},"application/vnd.dreamfactory":{source:"iana",extensions:["dfac"]},"application/vnd.drive+json":{source:"iana",compressible:!0},"application/vnd.ds-keypoint":{source:"apache",extensions:["kpxx"]},"application/vnd.dtg.local":{source:"iana"},"application/vnd.dtg.local.flash":{source:"iana"},"application/vnd.dtg.local.html":{source:"iana"},"application/vnd.dvb.ait":{source:"iana",extensions:["ait"]},"application/vnd.dvb.dvbisl+xml":{source:"iana",compressible:!0},"application/vnd.dvb.dvbj":{source:"iana"},"application/vnd.dvb.esgcontainer":{source:"iana"},"application/vnd.dvb.ipdcdftnotifaccess":{source:"iana"},"application/vnd.dvb.ipdcesgaccess":{source:"iana"},"application/vnd.dvb.ipdcesgaccess2":{source:"iana"},"application/vnd.dvb.ipdcesgpdd":{source:"iana"},"application/vnd.dvb.ipdcroaming":{source:"iana"},"application/vnd.dvb.iptv.alfec-base":{source:"iana"},"application/vnd.dvb.iptv.alfec-enhancement":{source:"iana"},"application/vnd.dvb.notif-aggregate-root+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-container+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-generic+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-msglist+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-registration-request+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-ia-registration-response+xml":{source:"iana",compressible:!0},"application/vnd.dvb.notif-init+xml":{source:"iana",compressible:!0},"application/vnd.dvb.pfr":{source:"iana"},"application/vnd.dvb.service":{source:"iana",extensions:["svc"]},"application/vnd.dxr":{source:"iana"},"application/vnd.dynageo":{source:"iana",extensions:["geo"]},"application/vnd.dzr":{source:"iana"},"application/vnd.easykaraoke.cdgdownload":{source:"iana"},"application/vnd.ecdis-update":{source:"iana"},"application/vnd.ecip.rlp":{source:"iana"},"application/vnd.eclipse.ditto+json":{source:"iana",compressible:!0},"application/vnd.ecowin.chart":{source:"iana",extensions:["mag"]},"application/vnd.ecowin.filerequest":{source:"iana"},"application/vnd.ecowin.fileupdate":{source:"iana"},"application/vnd.ecowin.series":{source:"iana"},"application/vnd.ecowin.seriesrequest":{source:"iana"},"application/vnd.ecowin.seriesupdate":{source:"iana"},"application/vnd.efi.img":{source:"iana"},"application/vnd.efi.iso":{source:"iana"},"application/vnd.eln+zip":{source:"iana",compressible:!1},"application/vnd.emclient.accessrequest+xml":{source:"iana",compressible:!0},"application/vnd.enliven":{source:"iana",extensions:["nml"]},"application/vnd.enphase.envoy":{source:"iana"},"application/vnd.eprints.data+xml":{source:"iana",compressible:!0},"application/vnd.epson.esf":{source:"iana",extensions:["esf"]},"application/vnd.epson.msf":{source:"iana",extensions:["msf"]},"application/vnd.epson.quickanime":{source:"iana",extensions:["qam"]},"application/vnd.epson.salt":{source:"iana",extensions:["slt"]},"application/vnd.epson.ssf":{source:"iana",extensions:["ssf"]},"application/vnd.ericsson.quickcall":{source:"iana"},"application/vnd.erofs":{source:"iana"},"application/vnd.espass-espass+zip":{source:"iana",compressible:!1},"application/vnd.eszigno3+xml":{source:"iana",compressible:!0,extensions:["es3","et3"]},"application/vnd.etsi.aoc+xml":{source:"iana",compressible:!0},"application/vnd.etsi.asic-e+zip":{source:"iana",compressible:!1},"application/vnd.etsi.asic-s+zip":{source:"iana",compressible:!1},"application/vnd.etsi.cug+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvcommand+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvdiscovery+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvprofile+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-bc+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-cod+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsad-npvr+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvservice+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvsync+xml":{source:"iana",compressible:!0},"application/vnd.etsi.iptvueprofile+xml":{source:"iana",compressible:!0},"application/vnd.etsi.mcid+xml":{source:"iana",compressible:!0},"application/vnd.etsi.mheg5":{source:"iana"},"application/vnd.etsi.overload-control-policy-dataset+xml":{source:"iana",compressible:!0},"application/vnd.etsi.pstn+xml":{source:"iana",compressible:!0},"application/vnd.etsi.sci+xml":{source:"iana",compressible:!0},"application/vnd.etsi.simservs+xml":{source:"iana",compressible:!0},"application/vnd.etsi.timestamp-token":{source:"iana"},"application/vnd.etsi.tsl+xml":{source:"iana",compressible:!0},"application/vnd.etsi.tsl.der":{source:"iana"},"application/vnd.eu.kasparian.car+json":{source:"iana",compressible:!0},"application/vnd.eudora.data":{source:"iana"},"application/vnd.evolv.ecig.profile":{source:"iana"},"application/vnd.evolv.ecig.settings":{source:"iana"},"application/vnd.evolv.ecig.theme":{source:"iana"},"application/vnd.exstream-empower+zip":{source:"iana",compressible:!1},"application/vnd.exstream-package":{source:"iana"},"application/vnd.ezpix-album":{source:"iana",extensions:["ez2"]},"application/vnd.ezpix-package":{source:"iana",extensions:["ez3"]},"application/vnd.f-secure.mobile":{source:"iana"},"application/vnd.familysearch.gedcom+zip":{source:"iana",compressible:!1},"application/vnd.fastcopy-disk-image":{source:"iana"},"application/vnd.fdf":{source:"apache",extensions:["fdf"]},"application/vnd.fdsn.mseed":{source:"iana",extensions:["mseed"]},"application/vnd.fdsn.seed":{source:"iana",extensions:["seed","dataless"]},"application/vnd.fdsn.stationxml+xml":{source:"iana",charset:"XML-BASED",compressible:!0},"application/vnd.ffsns":{source:"iana"},"application/vnd.ficlab.flb+zip":{source:"iana",compressible:!1},"application/vnd.filmit.zfc":{source:"iana"},"application/vnd.fints":{source:"iana"},"application/vnd.firemonkeys.cloudcell":{source:"iana"},"application/vnd.flographit":{source:"iana",extensions:["gph"]},"application/vnd.fluxtime.clip":{source:"iana",extensions:["ftc"]},"application/vnd.font-fontforge-sfd":{source:"iana"},"application/vnd.framemaker":{source:"iana",extensions:["fm","frame","maker","book"]},"application/vnd.freelog.comic":{source:"iana"},"application/vnd.frogans.fnc":{source:"apache",extensions:["fnc"]},"application/vnd.frogans.ltf":{source:"apache",extensions:["ltf"]},"application/vnd.fsc.weblaunch":{source:"iana",extensions:["fsc"]},"application/vnd.fujifilm.fb.docuworks":{source:"iana"},"application/vnd.fujifilm.fb.docuworks.binder":{source:"iana"},"application/vnd.fujifilm.fb.docuworks.container":{source:"iana"},"application/vnd.fujifilm.fb.jfi+xml":{source:"iana",compressible:!0},"application/vnd.fujitsu.oasys":{source:"iana",extensions:["oas"]},"application/vnd.fujitsu.oasys2":{source:"iana",extensions:["oa2"]},"application/vnd.fujitsu.oasys3":{source:"iana",extensions:["oa3"]},"application/vnd.fujitsu.oasysgp":{source:"iana",extensions:["fg5"]},"application/vnd.fujitsu.oasysprs":{source:"iana",extensions:["bh2"]},"application/vnd.fujixerox.art-ex":{source:"iana"},"application/vnd.fujixerox.art4":{source:"iana"},"application/vnd.fujixerox.ddd":{source:"iana",extensions:["ddd"]},"application/vnd.fujixerox.docuworks":{source:"iana",extensions:["xdw"]},"application/vnd.fujixerox.docuworks.binder":{source:"iana",extensions:["xbd"]},"application/vnd.fujixerox.docuworks.container":{source:"iana"},"application/vnd.fujixerox.hbpl":{source:"iana"},"application/vnd.fut-misnet":{source:"iana"},"application/vnd.futoin+cbor":{source:"iana"},"application/vnd.futoin+json":{source:"iana",compressible:!0},"application/vnd.fuzzysheet":{source:"iana",extensions:["fzs"]},"application/vnd.ga4gh.passport+jwt":{source:"iana"},"application/vnd.genomatix.tuxedo":{source:"iana",extensions:["txd"]},"application/vnd.genozip":{source:"iana"},"application/vnd.gentics.grd+json":{source:"iana",compressible:!0},"application/vnd.gentoo.catmetadata+xml":{source:"iana",compressible:!0},"application/vnd.gentoo.ebuild":{source:"iana"},"application/vnd.gentoo.eclass":{source:"iana"},"application/vnd.gentoo.gpkg":{source:"iana"},"application/vnd.gentoo.manifest":{source:"iana"},"application/vnd.gentoo.pkgmetadata+xml":{source:"iana",compressible:!0},"application/vnd.gentoo.xpak":{source:"iana"},"application/vnd.geo+json":{source:"apache",compressible:!0},"application/vnd.geocube+xml":{source:"apache",compressible:!0},"application/vnd.geogebra.file":{source:"iana",extensions:["ggb"]},"application/vnd.geogebra.pinboard":{source:"iana"},"application/vnd.geogebra.slides":{source:"iana",extensions:["ggs"]},"application/vnd.geogebra.tool":{source:"iana",extensions:["ggt"]},"application/vnd.geometry-explorer":{source:"iana",extensions:["gex","gre"]},"application/vnd.geonext":{source:"iana",extensions:["gxt"]},"application/vnd.geoplan":{source:"iana",extensions:["g2w"]},"application/vnd.geospace":{source:"iana",extensions:["g3w"]},"application/vnd.gerber":{source:"iana"},"application/vnd.globalplatform.card-content-mgt":{source:"iana"},"application/vnd.globalplatform.card-content-mgt-response":{source:"iana"},"application/vnd.gmx":{source:"iana",extensions:["gmx"]},"application/vnd.gnu.taler.exchange+json":{source:"iana",compressible:!0},"application/vnd.gnu.taler.merchant+json":{source:"iana",compressible:!0},"application/vnd.google-apps.audio":{},"application/vnd.google-apps.document":{compressible:!1,extensions:["gdoc"]},"application/vnd.google-apps.drawing":{compressible:!1,extensions:["gdraw"]},"application/vnd.google-apps.drive-sdk":{compressible:!1},"application/vnd.google-apps.file":{},"application/vnd.google-apps.folder":{compressible:!1},"application/vnd.google-apps.form":{compressible:!1,extensions:["gform"]},"application/vnd.google-apps.fusiontable":{},"application/vnd.google-apps.jam":{compressible:!1,extensions:["gjam"]},"application/vnd.google-apps.mail-layout":{},"application/vnd.google-apps.map":{compressible:!1,extensions:["gmap"]},"application/vnd.google-apps.photo":{},"application/vnd.google-apps.presentation":{compressible:!1,extensions:["gslides"]},"application/vnd.google-apps.script":{compressible:!1,extensions:["gscript"]},"application/vnd.google-apps.shortcut":{},"application/vnd.google-apps.site":{compressible:!1,extensions:["gsite"]},"application/vnd.google-apps.spreadsheet":{compressible:!1,extensions:["gsheet"]},"application/vnd.google-apps.unknown":{},"application/vnd.google-apps.video":{},"application/vnd.google-earth.kml+xml":{source:"iana",compressible:!0,extensions:["kml"]},"application/vnd.google-earth.kmz":{source:"iana",compressible:!1,extensions:["kmz"]},"application/vnd.gov.sk.e-form+xml":{source:"apache",compressible:!0},"application/vnd.gov.sk.e-form+zip":{source:"iana",compressible:!1},"application/vnd.gov.sk.xmldatacontainer+xml":{source:"iana",compressible:!0,extensions:["xdcf"]},"application/vnd.gpxsee.map+xml":{source:"iana",compressible:!0},"application/vnd.grafeq":{source:"iana",extensions:["gqf","gqs"]},"application/vnd.gridmp":{source:"iana"},"application/vnd.groove-account":{source:"iana",extensions:["gac"]},"application/vnd.groove-help":{source:"iana",extensions:["ghf"]},"application/vnd.groove-identity-message":{source:"iana",extensions:["gim"]},"application/vnd.groove-injector":{source:"iana",extensions:["grv"]},"application/vnd.groove-tool-message":{source:"iana",extensions:["gtm"]},"application/vnd.groove-tool-template":{source:"iana",extensions:["tpl"]},"application/vnd.groove-vcard":{source:"iana",extensions:["vcg"]},"application/vnd.hal+json":{source:"iana",compressible:!0},"application/vnd.hal+xml":{source:"iana",compressible:!0,extensions:["hal"]},"application/vnd.handheld-entertainment+xml":{source:"iana",compressible:!0,extensions:["zmm"]},"application/vnd.hbci":{source:"iana",extensions:["hbci"]},"application/vnd.hc+json":{source:"iana",compressible:!0},"application/vnd.hcl-bireports":{source:"iana"},"application/vnd.hdt":{source:"iana"},"application/vnd.heroku+json":{source:"iana",compressible:!0},"application/vnd.hhe.lesson-player":{source:"iana",extensions:["les"]},"application/vnd.hp-hpgl":{source:"iana",extensions:["hpgl"]},"application/vnd.hp-hpid":{source:"iana",extensions:["hpid"]},"application/vnd.hp-hps":{source:"iana",extensions:["hps"]},"application/vnd.hp-jlyt":{source:"iana",extensions:["jlt"]},"application/vnd.hp-pcl":{source:"iana",extensions:["pcl"]},"application/vnd.hp-pclxl":{source:"iana",extensions:["pclxl"]},"application/vnd.hsl":{source:"iana"},"application/vnd.httphone":{source:"iana"},"application/vnd.hydrostatix.sof-data":{source:"iana",extensions:["sfd-hdstx"]},"application/vnd.hyper+json":{source:"iana",compressible:!0},"application/vnd.hyper-item+json":{source:"iana",compressible:!0},"application/vnd.hyperdrive+json":{source:"iana",compressible:!0},"application/vnd.hzn-3d-crossword":{source:"iana"},"application/vnd.ibm.afplinedata":{source:"apache"},"application/vnd.ibm.electronic-media":{source:"iana"},"application/vnd.ibm.minipay":{source:"iana",extensions:["mpy"]},"application/vnd.ibm.modcap":{source:"apache",extensions:["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{source:"iana",extensions:["irm"]},"application/vnd.ibm.secure-container":{source:"iana",extensions:["sc"]},"application/vnd.iccprofile":{source:"iana",extensions:["icc","icm"]},"application/vnd.ieee.1905":{source:"iana"},"application/vnd.igloader":{source:"iana",extensions:["igl"]},"application/vnd.imagemeter.folder+zip":{source:"iana",compressible:!1},"application/vnd.imagemeter.image+zip":{source:"iana",compressible:!1},"application/vnd.immervision-ivp":{source:"iana",extensions:["ivp"]},"application/vnd.immervision-ivu":{source:"iana",extensions:["ivu"]},"application/vnd.ims.imsccv1p1":{source:"iana"},"application/vnd.ims.imsccv1p2":{source:"iana"},"application/vnd.ims.imsccv1p3":{source:"iana"},"application/vnd.ims.lis.v2.result+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolconsumerprofile+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolproxy+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolproxy.id+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolsettings+json":{source:"iana",compressible:!0},"application/vnd.ims.lti.v2.toolsettings.simple+json":{source:"iana",compressible:!0},"application/vnd.informedcontrol.rms+xml":{source:"iana",compressible:!0},"application/vnd.informix-visionary":{source:"apache"},"application/vnd.infotech.project":{source:"iana"},"application/vnd.infotech.project+xml":{source:"iana",compressible:!0},"application/vnd.innopath.wamp.notification":{source:"iana"},"application/vnd.insors.igm":{source:"iana",extensions:["igm"]},"application/vnd.intercon.formnet":{source:"iana",extensions:["xpw","xpx"]},"application/vnd.intergeo":{source:"iana",extensions:["i2g"]},"application/vnd.intertrust.digibox":{source:"iana"},"application/vnd.intertrust.nncp":{source:"iana"},"application/vnd.intu.qbo":{source:"iana",extensions:["qbo"]},"application/vnd.intu.qfx":{source:"iana",extensions:["qfx"]},"application/vnd.ipfs.ipns-record":{source:"iana"},"application/vnd.ipld.car":{source:"iana"},"application/vnd.ipld.dag-cbor":{source:"iana"},"application/vnd.ipld.dag-json":{source:"iana"},"application/vnd.ipld.raw":{source:"iana"},"application/vnd.iptc.g2.catalogitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.conceptitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.knowledgeitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.newsitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.newsmessage+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.packageitem+xml":{source:"iana",compressible:!0},"application/vnd.iptc.g2.planningitem+xml":{source:"iana",compressible:!0},"application/vnd.ipunplugged.rcprofile":{source:"iana",extensions:["rcprofile"]},"application/vnd.irepository.package+xml":{source:"iana",compressible:!0,extensions:["irp"]},"application/vnd.is-xpr":{source:"iana",extensions:["xpr"]},"application/vnd.isac.fcs":{source:"iana",extensions:["fcs"]},"application/vnd.iso11783-10+zip":{source:"iana",compressible:!1},"application/vnd.jam":{source:"iana",extensions:["jam"]},"application/vnd.japannet-directory-service":{source:"iana"},"application/vnd.japannet-jpnstore-wakeup":{source:"iana"},"application/vnd.japannet-payment-wakeup":{source:"iana"},"application/vnd.japannet-registration":{source:"iana"},"application/vnd.japannet-registration-wakeup":{source:"iana"},"application/vnd.japannet-setstore-wakeup":{source:"iana"},"application/vnd.japannet-verification":{source:"iana"},"application/vnd.japannet-verification-wakeup":{source:"iana"},"application/vnd.jcp.javame.midlet-rms":{source:"iana",extensions:["rms"]},"application/vnd.jisp":{source:"iana",extensions:["jisp"]},"application/vnd.joost.joda-archive":{source:"iana",extensions:["joda"]},"application/vnd.jsk.isdn-ngn":{source:"iana"},"application/vnd.kahootz":{source:"iana",extensions:["ktz","ktr"]},"application/vnd.kde.karbon":{source:"iana",extensions:["karbon"]},"application/vnd.kde.kchart":{source:"iana",extensions:["chrt"]},"application/vnd.kde.kformula":{source:"iana",extensions:["kfo"]},"application/vnd.kde.kivio":{source:"iana",extensions:["flw"]},"application/vnd.kde.kontour":{source:"iana",extensions:["kon"]},"application/vnd.kde.kpresenter":{source:"iana",extensions:["kpr","kpt"]},"application/vnd.kde.kspread":{source:"iana",extensions:["ksp"]},"application/vnd.kde.kword":{source:"iana",extensions:["kwd","kwt"]},"application/vnd.kdl":{source:"iana"},"application/vnd.kenameaapp":{source:"iana",extensions:["htke"]},"application/vnd.keyman.kmp+zip":{source:"iana",compressible:!1},"application/vnd.keyman.kmx":{source:"iana"},"application/vnd.kidspiration":{source:"iana",extensions:["kia"]},"application/vnd.kinar":{source:"iana",extensions:["kne","knp"]},"application/vnd.koan":{source:"iana",extensions:["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{source:"iana",extensions:["sse"]},"application/vnd.las":{source:"iana"},"application/vnd.las.las+json":{source:"iana",compressible:!0},"application/vnd.las.las+xml":{source:"iana",compressible:!0,extensions:["lasxml"]},"application/vnd.laszip":{source:"iana"},"application/vnd.ldev.productlicensing":{source:"iana"},"application/vnd.leap+json":{source:"iana",compressible:!0},"application/vnd.liberty-request+xml":{source:"iana",compressible:!0},"application/vnd.llamagraphics.life-balance.desktop":{source:"iana",extensions:["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{source:"iana",compressible:!0,extensions:["lbe"]},"application/vnd.logipipe.circuit+zip":{source:"iana",compressible:!1},"application/vnd.loom":{source:"iana"},"application/vnd.lotus-1-2-3":{source:"iana",extensions:["123"]},"application/vnd.lotus-approach":{source:"iana",extensions:["apr"]},"application/vnd.lotus-freelance":{source:"iana",extensions:["pre"]},"application/vnd.lotus-notes":{source:"iana",extensions:["nsf"]},"application/vnd.lotus-organizer":{source:"iana",extensions:["org"]},"application/vnd.lotus-screencam":{source:"iana",extensions:["scm"]},"application/vnd.lotus-wordpro":{source:"iana",extensions:["lwp"]},"application/vnd.macports.portpkg":{source:"iana",extensions:["portpkg"]},"application/vnd.mapbox-vector-tile":{source:"iana",extensions:["mvt"]},"application/vnd.marlin.drm.actiontoken+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.conftoken+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.license+xml":{source:"iana",compressible:!0},"application/vnd.marlin.drm.mdcf":{source:"iana"},"application/vnd.mason+json":{source:"iana",compressible:!0},"application/vnd.maxar.archive.3tz+zip":{source:"iana",compressible:!1},"application/vnd.maxmind.maxmind-db":{source:"iana"},"application/vnd.mcd":{source:"iana",extensions:["mcd"]},"application/vnd.mdl":{source:"iana"},"application/vnd.mdl-mbsdf":{source:"iana"},"application/vnd.medcalcdata":{source:"iana",extensions:["mc1"]},"application/vnd.mediastation.cdkey":{source:"iana",extensions:["cdkey"]},"application/vnd.medicalholodeck.recordxr":{source:"iana"},"application/vnd.meridian-slingshot":{source:"iana"},"application/vnd.mermaid":{source:"iana"},"application/vnd.mfer":{source:"iana",extensions:["mwf"]},"application/vnd.mfmp":{source:"iana",extensions:["mfm"]},"application/vnd.micro+json":{source:"iana",compressible:!0},"application/vnd.micrografx.flo":{source:"iana",extensions:["flo"]},"application/vnd.micrografx.igx":{source:"iana",extensions:["igx"]},"application/vnd.microsoft.portable-executable":{source:"iana"},"application/vnd.microsoft.windows.thumbnail-cache":{source:"iana"},"application/vnd.miele+json":{source:"iana",compressible:!0},"application/vnd.mif":{source:"iana",extensions:["mif"]},"application/vnd.minisoft-hp3000-save":{source:"iana"},"application/vnd.mitsubishi.misty-guard.trustweb":{source:"iana"},"application/vnd.mobius.daf":{source:"iana",extensions:["daf"]},"application/vnd.mobius.dis":{source:"iana",extensions:["dis"]},"application/vnd.mobius.mbk":{source:"iana",extensions:["mbk"]},"application/vnd.mobius.mqy":{source:"iana",extensions:["mqy"]},"application/vnd.mobius.msl":{source:"iana",extensions:["msl"]},"application/vnd.mobius.plc":{source:"iana",extensions:["plc"]},"application/vnd.mobius.txf":{source:"iana",extensions:["txf"]},"application/vnd.modl":{source:"iana"},"application/vnd.mophun.application":{source:"iana",extensions:["mpn"]},"application/vnd.mophun.certificate":{source:"iana",extensions:["mpc"]},"application/vnd.motorola.flexsuite":{source:"iana"},"application/vnd.motorola.flexsuite.adsi":{source:"iana"},"application/vnd.motorola.flexsuite.fis":{source:"iana"},"application/vnd.motorola.flexsuite.gotap":{source:"iana"},"application/vnd.motorola.flexsuite.kmr":{source:"iana"},"application/vnd.motorola.flexsuite.ttc":{source:"iana"},"application/vnd.motorola.flexsuite.wem":{source:"iana"},"application/vnd.motorola.iprm":{source:"iana"},"application/vnd.mozilla.xul+xml":{source:"iana",compressible:!0,extensions:["xul"]},"application/vnd.ms-3mfdocument":{source:"iana"},"application/vnd.ms-artgalry":{source:"iana",extensions:["cil"]},"application/vnd.ms-asf":{source:"iana"},"application/vnd.ms-cab-compressed":{source:"iana",extensions:["cab"]},"application/vnd.ms-color.iccprofile":{source:"apache"},"application/vnd.ms-excel":{source:"iana",compressible:!1,extensions:["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{source:"iana",extensions:["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{source:"iana",extensions:["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{source:"iana",extensions:["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{source:"iana",extensions:["xltm"]},"application/vnd.ms-fontobject":{source:"iana",compressible:!0,extensions:["eot"]},"application/vnd.ms-htmlhelp":{source:"iana",extensions:["chm"]},"application/vnd.ms-ims":{source:"iana",extensions:["ims"]},"application/vnd.ms-lrm":{source:"iana",extensions:["lrm"]},"application/vnd.ms-office.activex+xml":{source:"iana",compressible:!0},"application/vnd.ms-officetheme":{source:"iana",extensions:["thmx"]},"application/vnd.ms-opentype":{source:"apache",compressible:!0},"application/vnd.ms-outlook":{compressible:!1,extensions:["msg"]},"application/vnd.ms-package.obfuscated-opentype":{source:"apache"},"application/vnd.ms-pki.seccat":{source:"apache",extensions:["cat"]},"application/vnd.ms-pki.stl":{source:"apache",extensions:["stl"]},"application/vnd.ms-playready.initiator+xml":{source:"iana",compressible:!0},"application/vnd.ms-powerpoint":{source:"iana",compressible:!1,extensions:["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{source:"iana",extensions:["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{source:"iana",extensions:["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{source:"iana",extensions:["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{source:"iana",extensions:["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{source:"iana",extensions:["potm"]},"application/vnd.ms-printdevicecapabilities+xml":{source:"iana",compressible:!0},"application/vnd.ms-printing.printticket+xml":{source:"apache",compressible:!0},"application/vnd.ms-printschematicket+xml":{source:"iana",compressible:!0},"application/vnd.ms-project":{source:"iana",extensions:["mpp","mpt"]},"application/vnd.ms-tnef":{source:"iana"},"application/vnd.ms-visio.viewer":{extensions:["vdx"]},"application/vnd.ms-windows.devicepairing":{source:"iana"},"application/vnd.ms-windows.nwprinting.oob":{source:"iana"},"application/vnd.ms-windows.printerpairing":{source:"iana"},"application/vnd.ms-windows.wsd.oob":{source:"iana"},"application/vnd.ms-wmdrm.lic-chlg-req":{source:"iana"},"application/vnd.ms-wmdrm.lic-resp":{source:"iana"},"application/vnd.ms-wmdrm.meter-chlg-req":{source:"iana"},"application/vnd.ms-wmdrm.meter-resp":{source:"iana"},"application/vnd.ms-word.document.macroenabled.12":{source:"iana",extensions:["docm"]},"application/vnd.ms-word.template.macroenabled.12":{source:"iana",extensions:["dotm"]},"application/vnd.ms-works":{source:"iana",extensions:["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{source:"iana",extensions:["wpl"]},"application/vnd.ms-xpsdocument":{source:"iana",compressible:!1,extensions:["xps"]},"application/vnd.msa-disk-image":{source:"iana"},"application/vnd.mseq":{source:"iana",extensions:["mseq"]},"application/vnd.msgpack":{source:"iana"},"application/vnd.msign":{source:"iana"},"application/vnd.multiad.creator":{source:"iana"},"application/vnd.multiad.creator.cif":{source:"iana"},"application/vnd.music-niff":{source:"iana"},"application/vnd.musician":{source:"iana",extensions:["mus"]},"application/vnd.muvee.style":{source:"iana",extensions:["msty"]},"application/vnd.mynfc":{source:"iana",extensions:["taglet"]},"application/vnd.nacamar.ybrid+json":{source:"iana",compressible:!0},"application/vnd.nato.bindingdataobject+cbor":{source:"iana"},"application/vnd.nato.bindingdataobject+json":{source:"iana",compressible:!0},"application/vnd.nato.bindingdataobject+xml":{source:"iana",compressible:!0,extensions:["bdo"]},"application/vnd.nato.openxmlformats-package.iepd+zip":{source:"iana",compressible:!1},"application/vnd.ncd.control":{source:"iana"},"application/vnd.ncd.reference":{source:"iana"},"application/vnd.nearst.inv+json":{source:"iana",compressible:!0},"application/vnd.nebumind.line":{source:"iana"},"application/vnd.nervana":{source:"iana"},"application/vnd.netfpx":{source:"iana"},"application/vnd.neurolanguage.nlu":{source:"iana",extensions:["nlu"]},"application/vnd.nimn":{source:"iana"},"application/vnd.nintendo.nitro.rom":{source:"iana"},"application/vnd.nintendo.snes.rom":{source:"iana"},"application/vnd.nitf":{source:"iana",extensions:["ntf","nitf"]},"application/vnd.noblenet-directory":{source:"iana",extensions:["nnd"]},"application/vnd.noblenet-sealer":{source:"iana",extensions:["nns"]},"application/vnd.noblenet-web":{source:"iana",extensions:["nnw"]},"application/vnd.nokia.catalogs":{source:"iana"},"application/vnd.nokia.conml+wbxml":{source:"iana"},"application/vnd.nokia.conml+xml":{source:"iana",compressible:!0},"application/vnd.nokia.iptv.config+xml":{source:"iana",compressible:!0},"application/vnd.nokia.isds-radio-presets":{source:"iana"},"application/vnd.nokia.landmark+wbxml":{source:"iana"},"application/vnd.nokia.landmark+xml":{source:"iana",compressible:!0},"application/vnd.nokia.landmarkcollection+xml":{source:"iana",compressible:!0},"application/vnd.nokia.n-gage.ac+xml":{source:"iana",compressible:!0,extensions:["ac"]},"application/vnd.nokia.n-gage.data":{source:"iana",extensions:["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{source:"apache",extensions:["n-gage"]},"application/vnd.nokia.ncd":{source:"iana"},"application/vnd.nokia.pcd+wbxml":{source:"iana"},"application/vnd.nokia.pcd+xml":{source:"iana",compressible:!0},"application/vnd.nokia.radio-preset":{source:"iana",extensions:["rpst"]},"application/vnd.nokia.radio-presets":{source:"iana",extensions:["rpss"]},"application/vnd.novadigm.edm":{source:"iana",extensions:["edm"]},"application/vnd.novadigm.edx":{source:"iana",extensions:["edx"]},"application/vnd.novadigm.ext":{source:"iana",extensions:["ext"]},"application/vnd.ntt-local.content-share":{source:"iana"},"application/vnd.ntt-local.file-transfer":{source:"iana"},"application/vnd.ntt-local.ogw_remote-access":{source:"iana"},"application/vnd.ntt-local.sip-ta_remote":{source:"iana"},"application/vnd.ntt-local.sip-ta_tcp_stream":{source:"iana"},"application/vnd.oai.workflows":{source:"iana"},"application/vnd.oai.workflows+json":{source:"iana",compressible:!0},"application/vnd.oai.workflows+yaml":{source:"iana"},"application/vnd.oasis.opendocument.base":{source:"iana"},"application/vnd.oasis.opendocument.chart":{source:"iana",extensions:["odc"]},"application/vnd.oasis.opendocument.chart-template":{source:"iana",extensions:["otc"]},"application/vnd.oasis.opendocument.database":{source:"apache",extensions:["odb"]},"application/vnd.oasis.opendocument.formula":{source:"iana",extensions:["odf"]},"application/vnd.oasis.opendocument.formula-template":{source:"iana",extensions:["odft"]},"application/vnd.oasis.opendocument.graphics":{source:"iana",compressible:!1,extensions:["odg"]},"application/vnd.oasis.opendocument.graphics-template":{source:"iana",extensions:["otg"]},"application/vnd.oasis.opendocument.image":{source:"iana",extensions:["odi"]},"application/vnd.oasis.opendocument.image-template":{source:"iana",extensions:["oti"]},"application/vnd.oasis.opendocument.presentation":{source:"iana",compressible:!1,extensions:["odp"]},"application/vnd.oasis.opendocument.presentation-template":{source:"iana",extensions:["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{source:"iana",compressible:!1,extensions:["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{source:"iana",extensions:["ots"]},"application/vnd.oasis.opendocument.text":{source:"iana",compressible:!1,extensions:["odt"]},"application/vnd.oasis.opendocument.text-master":{source:"iana",extensions:["odm"]},"application/vnd.oasis.opendocument.text-master-template":{source:"iana"},"application/vnd.oasis.opendocument.text-template":{source:"iana",extensions:["ott"]},"application/vnd.oasis.opendocument.text-web":{source:"iana",extensions:["oth"]},"application/vnd.obn":{source:"iana"},"application/vnd.ocf+cbor":{source:"iana"},"application/vnd.oci.image.manifest.v1+json":{source:"iana",compressible:!0},"application/vnd.oftn.l10n+json":{source:"iana",compressible:!0},"application/vnd.oipf.contentaccessdownload+xml":{source:"iana",compressible:!0},"application/vnd.oipf.contentaccessstreaming+xml":{source:"iana",compressible:!0},"application/vnd.oipf.cspg-hexbinary":{source:"iana"},"application/vnd.oipf.dae.svg+xml":{source:"iana",compressible:!0},"application/vnd.oipf.dae.xhtml+xml":{source:"iana",compressible:!0},"application/vnd.oipf.mippvcontrolmessage+xml":{source:"iana",compressible:!0},"application/vnd.oipf.pae.gem":{source:"iana"},"application/vnd.oipf.spdiscovery+xml":{source:"iana",compressible:!0},"application/vnd.oipf.spdlist+xml":{source:"iana",compressible:!0},"application/vnd.oipf.ueprofile+xml":{source:"iana",compressible:!0},"application/vnd.oipf.userprofile+xml":{source:"iana",compressible:!0},"application/vnd.olpc-sugar":{source:"iana",extensions:["xo"]},"application/vnd.oma-scws-config":{source:"iana"},"application/vnd.oma-scws-http-request":{source:"iana"},"application/vnd.oma-scws-http-response":{source:"iana"},"application/vnd.oma.bcast.associated-procedure-parameter+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.drm-trigger+xml":{source:"apache",compressible:!0},"application/vnd.oma.bcast.imd+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.ltkm":{source:"iana"},"application/vnd.oma.bcast.notification+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.provisioningtrigger":{source:"iana"},"application/vnd.oma.bcast.sgboot":{source:"iana"},"application/vnd.oma.bcast.sgdd+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.sgdu":{source:"iana"},"application/vnd.oma.bcast.simple-symbol-container":{source:"iana"},"application/vnd.oma.bcast.smartcard-trigger+xml":{source:"apache",compressible:!0},"application/vnd.oma.bcast.sprov+xml":{source:"iana",compressible:!0},"application/vnd.oma.bcast.stkm":{source:"iana"},"application/vnd.oma.cab-address-book+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-feature-handler+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-pcc+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-subs-invite+xml":{source:"iana",compressible:!0},"application/vnd.oma.cab-user-prefs+xml":{source:"iana",compressible:!0},"application/vnd.oma.dcd":{source:"iana"},"application/vnd.oma.dcdc":{source:"iana"},"application/vnd.oma.dd2+xml":{source:"iana",compressible:!0,extensions:["dd2"]},"application/vnd.oma.drm.risd+xml":{source:"iana",compressible:!0},"application/vnd.oma.group-usage-list+xml":{source:"iana",compressible:!0},"application/vnd.oma.lwm2m+cbor":{source:"iana"},"application/vnd.oma.lwm2m+json":{source:"iana",compressible:!0},"application/vnd.oma.lwm2m+tlv":{source:"iana"},"application/vnd.oma.pal+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.detailed-progress-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.final-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.groups+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.invocation-descriptor+xml":{source:"iana",compressible:!0},"application/vnd.oma.poc.optimized-progress-report+xml":{source:"iana",compressible:!0},"application/vnd.oma.push":{source:"iana"},"application/vnd.oma.scidm.messages+xml":{source:"iana",compressible:!0},"application/vnd.oma.xcap-directory+xml":{source:"iana",compressible:!0},"application/vnd.omads-email+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omads-file+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omads-folder+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.omaloc-supl-init":{source:"iana"},"application/vnd.onepager":{source:"iana"},"application/vnd.onepagertamp":{source:"iana"},"application/vnd.onepagertamx":{source:"iana"},"application/vnd.onepagertat":{source:"iana"},"application/vnd.onepagertatp":{source:"iana"},"application/vnd.onepagertatx":{source:"iana"},"application/vnd.onvif.metadata":{source:"iana"},"application/vnd.openblox.game+xml":{source:"iana",compressible:!0,extensions:["obgx"]},"application/vnd.openblox.game-binary":{source:"iana"},"application/vnd.openeye.oeb":{source:"iana"},"application/vnd.openofficeorg.extension":{source:"apache",extensions:["oxt"]},"application/vnd.openstreetmap.data+xml":{source:"iana",compressible:!0,extensions:["osm"]},"application/vnd.opentimestamps.ots":{source:"iana"},"application/vnd.openvpi.dspx+json":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.custom-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.customxmlproperties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawing+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.chart+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.extended-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{source:"iana",compressible:!1,extensions:["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slide":{source:"iana",extensions:["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{source:"iana",extensions:["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.tags+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.template":{source:"iana",extensions:["potx"]},"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{source:"iana",compressible:!1,extensions:["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{source:"iana",extensions:["xltx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.theme+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.themeoverride+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.vmldrawing":{source:"iana"},"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{source:"iana",compressible:!1,extensions:["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{source:"iana",extensions:["dotx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.core-properties+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml":{source:"iana",compressible:!0},"application/vnd.openxmlformats-package.relationships+xml":{source:"iana",compressible:!0},"application/vnd.oracle.resource+json":{source:"iana",compressible:!0},"application/vnd.orange.indata":{source:"iana"},"application/vnd.osa.netdeploy":{source:"iana"},"application/vnd.osgeo.mapguide.package":{source:"iana",extensions:["mgp"]},"application/vnd.osgi.bundle":{source:"iana"},"application/vnd.osgi.dp":{source:"iana",extensions:["dp"]},"application/vnd.osgi.subsystem":{source:"iana",extensions:["esa"]},"application/vnd.otps.ct-kip+xml":{source:"iana",compressible:!0},"application/vnd.oxli.countgraph":{source:"iana"},"application/vnd.pagerduty+json":{source:"iana",compressible:!0},"application/vnd.palm":{source:"iana",extensions:["pdb","pqa","oprc"]},"application/vnd.panoply":{source:"iana"},"application/vnd.paos.xml":{source:"iana"},"application/vnd.patentdive":{source:"iana"},"application/vnd.patientecommsdoc":{source:"iana"},"application/vnd.pawaafile":{source:"iana",extensions:["paw"]},"application/vnd.pcos":{source:"iana"},"application/vnd.pg.format":{source:"iana",extensions:["str"]},"application/vnd.pg.osasli":{source:"iana",extensions:["ei6"]},"application/vnd.piaccess.application-licence":{source:"iana"},"application/vnd.picsel":{source:"iana",extensions:["efif"]},"application/vnd.pmi.widget":{source:"iana",extensions:["wg"]},"application/vnd.poc.group-advertisement+xml":{source:"iana",compressible:!0},"application/vnd.pocketlearn":{source:"iana",extensions:["plf"]},"application/vnd.powerbuilder6":{source:"iana",extensions:["pbd"]},"application/vnd.powerbuilder6-s":{source:"iana"},"application/vnd.powerbuilder7":{source:"iana"},"application/vnd.powerbuilder7-s":{source:"iana"},"application/vnd.powerbuilder75":{source:"iana"},"application/vnd.powerbuilder75-s":{source:"iana"},"application/vnd.preminet":{source:"iana"},"application/vnd.previewsystems.box":{source:"iana",extensions:["box"]},"application/vnd.procrate.brushset":{extensions:["brushset"]},"application/vnd.procreate.brush":{extensions:["brush"]},"application/vnd.procreate.dream":{extensions:["drm"]},"application/vnd.proteus.magazine":{source:"iana",extensions:["mgz"]},"application/vnd.psfs":{source:"iana"},"application/vnd.pt.mundusmundi":{source:"iana"},"application/vnd.publishare-delta-tree":{source:"iana",extensions:["qps"]},"application/vnd.pvi.ptid1":{source:"iana",extensions:["ptid"]},"application/vnd.pwg-multiplexed":{source:"iana"},"application/vnd.pwg-xhtml-print+xml":{source:"iana",compressible:!0,extensions:["xhtm"]},"application/vnd.qualcomm.brew-app-res":{source:"iana"},"application/vnd.quarantainenet":{source:"iana"},"application/vnd.quark.quarkxpress":{source:"iana",extensions:["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.quobject-quoxdocument":{source:"iana"},"application/vnd.radisys.moml+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-conf+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-conn+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-dialog+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-audit-stream+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-conf+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-base+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-fax-detect+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-fax-sendrecv+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-group+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-speech+xml":{source:"iana",compressible:!0},"application/vnd.radisys.msml-dialog-transform+xml":{source:"iana",compressible:!0},"application/vnd.rainstor.data":{source:"iana"},"application/vnd.rapid":{source:"iana"},"application/vnd.rar":{source:"iana",extensions:["rar"]},"application/vnd.realvnc.bed":{source:"iana",extensions:["bed"]},"application/vnd.recordare.musicxml":{source:"iana",extensions:["mxl"]},"application/vnd.recordare.musicxml+xml":{source:"iana",compressible:!0,extensions:["musicxml"]},"application/vnd.relpipe":{source:"iana"},"application/vnd.renlearn.rlprint":{source:"iana"},"application/vnd.resilient.logic":{source:"iana"},"application/vnd.restful+json":{source:"iana",compressible:!0},"application/vnd.rig.cryptonote":{source:"iana",extensions:["cryptonote"]},"application/vnd.rim.cod":{source:"apache",extensions:["cod"]},"application/vnd.rn-realmedia":{source:"apache",extensions:["rm"]},"application/vnd.rn-realmedia-vbr":{source:"apache",extensions:["rmvb"]},"application/vnd.route66.link66+xml":{source:"iana",compressible:!0,extensions:["link66"]},"application/vnd.rs-274x":{source:"iana"},"application/vnd.ruckus.download":{source:"iana"},"application/vnd.s3sms":{source:"iana"},"application/vnd.sailingtracker.track":{source:"iana",extensions:["st"]},"application/vnd.sar":{source:"iana"},"application/vnd.sbm.cid":{source:"iana"},"application/vnd.sbm.mid2":{source:"iana"},"application/vnd.scribus":{source:"iana"},"application/vnd.sealed.3df":{source:"iana"},"application/vnd.sealed.csf":{source:"iana"},"application/vnd.sealed.doc":{source:"iana"},"application/vnd.sealed.eml":{source:"iana"},"application/vnd.sealed.mht":{source:"iana"},"application/vnd.sealed.net":{source:"iana"},"application/vnd.sealed.ppt":{source:"iana"},"application/vnd.sealed.tiff":{source:"iana"},"application/vnd.sealed.xls":{source:"iana"},"application/vnd.sealedmedia.softseal.html":{source:"iana"},"application/vnd.sealedmedia.softseal.pdf":{source:"iana"},"application/vnd.seemail":{source:"iana",extensions:["see"]},"application/vnd.seis+json":{source:"iana",compressible:!0},"application/vnd.sema":{source:"iana",extensions:["sema"]},"application/vnd.semd":{source:"iana",extensions:["semd"]},"application/vnd.semf":{source:"iana",extensions:["semf"]},"application/vnd.shade-save-file":{source:"iana"},"application/vnd.shana.informed.formdata":{source:"iana",extensions:["ifm"]},"application/vnd.shana.informed.formtemplate":{source:"iana",extensions:["itp"]},"application/vnd.shana.informed.interchange":{source:"iana",extensions:["iif"]},"application/vnd.shana.informed.package":{source:"iana",extensions:["ipk"]},"application/vnd.shootproof+json":{source:"iana",compressible:!0},"application/vnd.shopkick+json":{source:"iana",compressible:!0},"application/vnd.shp":{source:"iana"},"application/vnd.shx":{source:"iana"},"application/vnd.sigrok.session":{source:"iana"},"application/vnd.simtech-mindmapper":{source:"iana",extensions:["twd","twds"]},"application/vnd.siren+json":{source:"iana",compressible:!0},"application/vnd.sketchometry":{source:"iana"},"application/vnd.smaf":{source:"iana",extensions:["mmf"]},"application/vnd.smart.notebook":{source:"iana"},"application/vnd.smart.teacher":{source:"iana",extensions:["teacher"]},"application/vnd.smintio.portals.archive":{source:"iana"},"application/vnd.snesdev-page-table":{source:"iana"},"application/vnd.software602.filler.form+xml":{source:"iana",compressible:!0,extensions:["fo"]},"application/vnd.software602.filler.form-xml-zip":{source:"iana"},"application/vnd.solent.sdkm+xml":{source:"iana",compressible:!0,extensions:["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{source:"iana",extensions:["dxp"]},"application/vnd.spotfire.sfs":{source:"iana",extensions:["sfs"]},"application/vnd.sqlite3":{source:"iana"},"application/vnd.sss-cod":{source:"iana"},"application/vnd.sss-dtf":{source:"iana"},"application/vnd.sss-ntf":{source:"iana"},"application/vnd.stardivision.calc":{source:"apache",extensions:["sdc"]},"application/vnd.stardivision.draw":{source:"apache",extensions:["sda"]},"application/vnd.stardivision.impress":{source:"apache",extensions:["sdd"]},"application/vnd.stardivision.math":{source:"apache",extensions:["smf"]},"application/vnd.stardivision.writer":{source:"apache",extensions:["sdw","vor"]},"application/vnd.stardivision.writer-global":{source:"apache",extensions:["sgl"]},"application/vnd.stepmania.package":{source:"iana",extensions:["smzip"]},"application/vnd.stepmania.stepchart":{source:"iana",extensions:["sm"]},"application/vnd.street-stream":{source:"iana"},"application/vnd.sun.wadl+xml":{source:"iana",compressible:!0,extensions:["wadl"]},"application/vnd.sun.xml.calc":{source:"apache",extensions:["sxc"]},"application/vnd.sun.xml.calc.template":{source:"apache",extensions:["stc"]},"application/vnd.sun.xml.draw":{source:"apache",extensions:["sxd"]},"application/vnd.sun.xml.draw.template":{source:"apache",extensions:["std"]},"application/vnd.sun.xml.impress":{source:"apache",extensions:["sxi"]},"application/vnd.sun.xml.impress.template":{source:"apache",extensions:["sti"]},"application/vnd.sun.xml.math":{source:"apache",extensions:["sxm"]},"application/vnd.sun.xml.writer":{source:"apache",extensions:["sxw"]},"application/vnd.sun.xml.writer.global":{source:"apache",extensions:["sxg"]},"application/vnd.sun.xml.writer.template":{source:"apache",extensions:["stw"]},"application/vnd.sus-calendar":{source:"iana",extensions:["sus","susp"]},"application/vnd.svd":{source:"iana",extensions:["svd"]},"application/vnd.swiftview-ics":{source:"iana"},"application/vnd.sybyl.mol2":{source:"iana"},"application/vnd.sycle+xml":{source:"iana",compressible:!0},"application/vnd.syft+json":{source:"iana",compressible:!0},"application/vnd.symbian.install":{source:"apache",extensions:["sis","sisx"]},"application/vnd.syncml+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["xsm"]},"application/vnd.syncml.dm+wbxml":{source:"iana",charset:"UTF-8",extensions:["bdm"]},"application/vnd.syncml.dm+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["xdm"]},"application/vnd.syncml.dm.notification":{source:"iana"},"application/vnd.syncml.dmddf+wbxml":{source:"iana"},"application/vnd.syncml.dmddf+xml":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["ddf"]},"application/vnd.syncml.dmtnds+wbxml":{source:"iana"},"application/vnd.syncml.dmtnds+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.syncml.ds.notification":{source:"iana"},"application/vnd.tableschema+json":{source:"iana",compressible:!0},"application/vnd.tao.intent-module-archive":{source:"iana",extensions:["tao"]},"application/vnd.tcpdump.pcap":{source:"iana",extensions:["pcap","cap","dmp"]},"application/vnd.think-cell.ppttc+json":{source:"iana",compressible:!0},"application/vnd.tmd.mediaflex.api+xml":{source:"iana",compressible:!0},"application/vnd.tml":{source:"iana"},"application/vnd.tmobile-livetv":{source:"iana",extensions:["tmo"]},"application/vnd.tri.onesource":{source:"iana"},"application/vnd.trid.tpt":{source:"iana",extensions:["tpt"]},"application/vnd.triscape.mxs":{source:"iana",extensions:["mxs"]},"application/vnd.trueapp":{source:"iana",extensions:["tra"]},"application/vnd.truedoc":{source:"iana"},"application/vnd.ubisoft.webplayer":{source:"iana"},"application/vnd.ufdl":{source:"iana",extensions:["ufd","ufdl"]},"application/vnd.uic.osdm+json":{source:"iana",compressible:!0},"application/vnd.uiq.theme":{source:"iana",extensions:["utz"]},"application/vnd.umajin":{source:"iana",extensions:["umj"]},"application/vnd.unity":{source:"iana",extensions:["unityweb"]},"application/vnd.uoml+xml":{source:"iana",compressible:!0,extensions:["uoml","uo"]},"application/vnd.uplanet.alert":{source:"iana"},"application/vnd.uplanet.alert-wbxml":{source:"iana"},"application/vnd.uplanet.bearer-choice":{source:"iana"},"application/vnd.uplanet.bearer-choice-wbxml":{source:"iana"},"application/vnd.uplanet.cacheop":{source:"iana"},"application/vnd.uplanet.cacheop-wbxml":{source:"iana"},"application/vnd.uplanet.channel":{source:"iana"},"application/vnd.uplanet.channel-wbxml":{source:"iana"},"application/vnd.uplanet.list":{source:"iana"},"application/vnd.uplanet.list-wbxml":{source:"iana"},"application/vnd.uplanet.listcmd":{source:"iana"},"application/vnd.uplanet.listcmd-wbxml":{source:"iana"},"application/vnd.uplanet.signal":{source:"iana"},"application/vnd.uri-map":{source:"iana"},"application/vnd.valve.source.material":{source:"iana"},"application/vnd.vcx":{source:"iana",extensions:["vcx"]},"application/vnd.vd-study":{source:"iana"},"application/vnd.vectorworks":{source:"iana"},"application/vnd.vel+json":{source:"iana",compressible:!0},"application/vnd.veraison.tsm-report+cbor":{source:"iana"},"application/vnd.veraison.tsm-report+json":{source:"iana",compressible:!0},"application/vnd.verimatrix.vcas":{source:"iana"},"application/vnd.veritone.aion+json":{source:"iana",compressible:!0},"application/vnd.veryant.thin":{source:"iana"},"application/vnd.ves.encrypted":{source:"iana"},"application/vnd.vidsoft.vidconference":{source:"iana"},"application/vnd.visio":{source:"iana",extensions:["vsd","vst","vss","vsw","vsdx","vtx"]},"application/vnd.visionary":{source:"iana",extensions:["vis"]},"application/vnd.vividence.scriptfile":{source:"iana"},"application/vnd.vocalshaper.vsp4":{source:"iana"},"application/vnd.vsf":{source:"iana",extensions:["vsf"]},"application/vnd.wap.sic":{source:"iana"},"application/vnd.wap.slc":{source:"iana"},"application/vnd.wap.wbxml":{source:"iana",charset:"UTF-8",extensions:["wbxml"]},"application/vnd.wap.wmlc":{source:"iana",extensions:["wmlc"]},"application/vnd.wap.wmlscriptc":{source:"iana",extensions:["wmlsc"]},"application/vnd.wasmflow.wafl":{source:"iana"},"application/vnd.webturbo":{source:"iana",extensions:["wtb"]},"application/vnd.wfa.dpp":{source:"iana"},"application/vnd.wfa.p2p":{source:"iana"},"application/vnd.wfa.wsc":{source:"iana"},"application/vnd.windows.devicepairing":{source:"iana"},"application/vnd.wmc":{source:"iana"},"application/vnd.wmf.bootstrap":{source:"iana"},"application/vnd.wolfram.mathematica":{source:"iana"},"application/vnd.wolfram.mathematica.package":{source:"iana"},"application/vnd.wolfram.player":{source:"iana",extensions:["nbp"]},"application/vnd.wordlift":{source:"iana"},"application/vnd.wordperfect":{source:"iana",extensions:["wpd"]},"application/vnd.wqd":{source:"iana",extensions:["wqd"]},"application/vnd.wrq-hp3000-labelled":{source:"iana"},"application/vnd.wt.stf":{source:"iana",extensions:["stf"]},"application/vnd.wv.csp+wbxml":{source:"iana"},"application/vnd.wv.csp+xml":{source:"iana",compressible:!0},"application/vnd.wv.ssp+xml":{source:"iana",compressible:!0},"application/vnd.xacml+json":{source:"iana",compressible:!0},"application/vnd.xara":{source:"iana",extensions:["xar"]},"application/vnd.xarin.cpj":{source:"iana"},"application/vnd.xecrets-encrypted":{source:"iana"},"application/vnd.xfdl":{source:"iana",extensions:["xfdl"]},"application/vnd.xfdl.webform":{source:"iana"},"application/vnd.xmi+xml":{source:"iana",compressible:!0},"application/vnd.xmpie.cpkg":{source:"iana"},"application/vnd.xmpie.dpkg":{source:"iana"},"application/vnd.xmpie.plan":{source:"iana"},"application/vnd.xmpie.ppkg":{source:"iana"},"application/vnd.xmpie.xlim":{source:"iana"},"application/vnd.yamaha.hv-dic":{source:"iana",extensions:["hvd"]},"application/vnd.yamaha.hv-script":{source:"iana",extensions:["hvs"]},"application/vnd.yamaha.hv-voice":{source:"iana",extensions:["hvp"]},"application/vnd.yamaha.openscoreformat":{source:"iana",extensions:["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{source:"iana",compressible:!0,extensions:["osfpvg"]},"application/vnd.yamaha.remote-setup":{source:"iana"},"application/vnd.yamaha.smaf-audio":{source:"iana",extensions:["saf"]},"application/vnd.yamaha.smaf-phrase":{source:"iana",extensions:["spf"]},"application/vnd.yamaha.through-ngn":{source:"iana"},"application/vnd.yamaha.tunnel-udpencap":{source:"iana"},"application/vnd.yaoweme":{source:"iana"},"application/vnd.yellowriver-custom-menu":{source:"iana",extensions:["cmp"]},"application/vnd.zul":{source:"iana",extensions:["zir","zirz"]},"application/vnd.zzazz.deck+xml":{source:"iana",compressible:!0,extensions:["zaz"]},"application/voicexml+xml":{source:"iana",compressible:!0,extensions:["vxml"]},"application/voucher-cms+json":{source:"iana",compressible:!0},"application/voucher-jws+json":{source:"iana",compressible:!0},"application/vp":{source:"iana"},"application/vp+cose":{source:"iana"},"application/vp+jwt":{source:"iana"},"application/vq-rtcpxr":{source:"iana"},"application/wasm":{source:"iana",compressible:!0,extensions:["wasm"]},"application/watcherinfo+xml":{source:"iana",compressible:!0,extensions:["wif"]},"application/webpush-options+json":{source:"iana",compressible:!0},"application/whoispp-query":{source:"iana"},"application/whoispp-response":{source:"iana"},"application/widget":{source:"iana",extensions:["wgt"]},"application/winhlp":{source:"apache",extensions:["hlp"]},"application/wita":{source:"iana"},"application/wordperfect5.1":{source:"iana"},"application/wsdl+xml":{source:"iana",compressible:!0,extensions:["wsdl"]},"application/wspolicy+xml":{source:"iana",compressible:!0,extensions:["wspolicy"]},"application/x-7z-compressed":{source:"apache",compressible:!1,extensions:["7z"]},"application/x-abiword":{source:"apache",extensions:["abw"]},"application/x-ace-compressed":{source:"apache",extensions:["ace"]},"application/x-amf":{source:"apache"},"application/x-apple-diskimage":{source:"apache",extensions:["dmg"]},"application/x-arj":{compressible:!1,extensions:["arj"]},"application/x-authorware-bin":{source:"apache",extensions:["aab","x32","u32","vox"]},"application/x-authorware-map":{source:"apache",extensions:["aam"]},"application/x-authorware-seg":{source:"apache",extensions:["aas"]},"application/x-bcpio":{source:"apache",extensions:["bcpio"]},"application/x-bdoc":{compressible:!1,extensions:["bdoc"]},"application/x-bittorrent":{source:"apache",extensions:["torrent"]},"application/x-blender":{extensions:["blend"]},"application/x-blorb":{source:"apache",extensions:["blb","blorb"]},"application/x-bzip":{source:"apache",compressible:!1,extensions:["bz"]},"application/x-bzip2":{source:"apache",compressible:!1,extensions:["bz2","boz"]},"application/x-cbr":{source:"apache",extensions:["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{source:"apache",extensions:["vcd"]},"application/x-cfs-compressed":{source:"apache",extensions:["cfs"]},"application/x-chat":{source:"apache",extensions:["chat"]},"application/x-chess-pgn":{source:"apache",extensions:["pgn"]},"application/x-chrome-extension":{extensions:["crx"]},"application/x-cocoa":{source:"nginx",extensions:["cco"]},"application/x-compress":{source:"apache"},"application/x-compressed":{extensions:["rar"]},"application/x-conference":{source:"apache",extensions:["nsc"]},"application/x-cpio":{source:"apache",extensions:["cpio"]},"application/x-csh":{source:"apache",extensions:["csh"]},"application/x-deb":{compressible:!1},"application/x-debian-package":{source:"apache",extensions:["deb","udeb"]},"application/x-dgc-compressed":{source:"apache",extensions:["dgc"]},"application/x-director":{source:"apache",extensions:["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{source:"apache",extensions:["wad"]},"application/x-dtbncx+xml":{source:"apache",compressible:!0,extensions:["ncx"]},"application/x-dtbook+xml":{source:"apache",compressible:!0,extensions:["dtb"]},"application/x-dtbresource+xml":{source:"apache",compressible:!0,extensions:["res"]},"application/x-dvi":{source:"apache",compressible:!1,extensions:["dvi"]},"application/x-envoy":{source:"apache",extensions:["evy"]},"application/x-eva":{source:"apache",extensions:["eva"]},"application/x-font-bdf":{source:"apache",extensions:["bdf"]},"application/x-font-dos":{source:"apache"},"application/x-font-framemaker":{source:"apache"},"application/x-font-ghostscript":{source:"apache",extensions:["gsf"]},"application/x-font-libgrx":{source:"apache"},"application/x-font-linux-psf":{source:"apache",extensions:["psf"]},"application/x-font-pcf":{source:"apache",extensions:["pcf"]},"application/x-font-snf":{source:"apache",extensions:["snf"]},"application/x-font-speedo":{source:"apache"},"application/x-font-sunos-news":{source:"apache"},"application/x-font-type1":{source:"apache",extensions:["pfa","pfb","pfm","afm"]},"application/x-font-vfont":{source:"apache"},"application/x-freearc":{source:"apache",extensions:["arc"]},"application/x-futuresplash":{source:"apache",extensions:["spl"]},"application/x-gca-compressed":{source:"apache",extensions:["gca"]},"application/x-glulx":{source:"apache",extensions:["ulx"]},"application/x-gnumeric":{source:"apache",extensions:["gnumeric"]},"application/x-gramps-xml":{source:"apache",extensions:["gramps"]},"application/x-gtar":{source:"apache",extensions:["gtar"]},"application/x-gzip":{source:"apache"},"application/x-hdf":{source:"apache",extensions:["hdf"]},"application/x-httpd-php":{compressible:!0,extensions:["php"]},"application/x-install-instructions":{source:"apache",extensions:["install"]},"application/x-ipynb+json":{compressible:!0,extensions:["ipynb"]},"application/x-iso9660-image":{source:"apache",extensions:["iso"]},"application/x-iwork-keynote-sffkey":{extensions:["key"]},"application/x-iwork-numbers-sffnumbers":{extensions:["numbers"]},"application/x-iwork-pages-sffpages":{extensions:["pages"]},"application/x-java-archive-diff":{source:"nginx",extensions:["jardiff"]},"application/x-java-jnlp-file":{source:"apache",compressible:!1,extensions:["jnlp"]},"application/x-javascript":{compressible:!0},"application/x-keepass2":{extensions:["kdbx"]},"application/x-latex":{source:"apache",compressible:!1,extensions:["latex"]},"application/x-lua-bytecode":{extensions:["luac"]},"application/x-lzh-compressed":{source:"apache",extensions:["lzh","lha"]},"application/x-makeself":{source:"nginx",extensions:["run"]},"application/x-mie":{source:"apache",extensions:["mie"]},"application/x-mobipocket-ebook":{source:"apache",extensions:["prc","mobi"]},"application/x-mpegurl":{compressible:!1},"application/x-ms-application":{source:"apache",extensions:["application"]},"application/x-ms-shortcut":{source:"apache",extensions:["lnk"]},"application/x-ms-wmd":{source:"apache",extensions:["wmd"]},"application/x-ms-wmz":{source:"apache",extensions:["wmz"]},"application/x-ms-xbap":{source:"apache",extensions:["xbap"]},"application/x-msaccess":{source:"apache",extensions:["mdb"]},"application/x-msbinder":{source:"apache",extensions:["obd"]},"application/x-mscardfile":{source:"apache",extensions:["crd"]},"application/x-msclip":{source:"apache",extensions:["clp"]},"application/x-msdos-program":{extensions:["exe"]},"application/x-msdownload":{source:"apache",extensions:["exe","dll","com","bat","msi"]},"application/x-msmediaview":{source:"apache",extensions:["mvb","m13","m14"]},"application/x-msmetafile":{source:"apache",extensions:["wmf","wmz","emf","emz"]},"application/x-msmoney":{source:"apache",extensions:["mny"]},"application/x-mspublisher":{source:"apache",extensions:["pub"]},"application/x-msschedule":{source:"apache",extensions:["scd"]},"application/x-msterminal":{source:"apache",extensions:["trm"]},"application/x-mswrite":{source:"apache",extensions:["wri"]},"application/x-netcdf":{source:"apache",extensions:["nc","cdf"]},"application/x-ns-proxy-autoconfig":{compressible:!0,extensions:["pac"]},"application/x-nzb":{source:"apache",extensions:["nzb"]},"application/x-perl":{source:"nginx",extensions:["pl","pm"]},"application/x-pilot":{source:"nginx",extensions:["prc","pdb"]},"application/x-pkcs12":{source:"apache",compressible:!1,extensions:["p12","pfx"]},"application/x-pkcs7-certificates":{source:"apache",extensions:["p7b","spc"]},"application/x-pkcs7-certreqresp":{source:"apache",extensions:["p7r"]},"application/x-pki-message":{source:"iana"},"application/x-rar-compressed":{source:"apache",compressible:!1,extensions:["rar"]},"application/x-redhat-package-manager":{source:"nginx",extensions:["rpm"]},"application/x-research-info-systems":{source:"apache",extensions:["ris"]},"application/x-sea":{source:"nginx",extensions:["sea"]},"application/x-sh":{source:"apache",compressible:!0,extensions:["sh"]},"application/x-shar":{source:"apache",extensions:["shar"]},"application/x-shockwave-flash":{source:"apache",compressible:!1,extensions:["swf"]},"application/x-silverlight-app":{source:"apache",extensions:["xap"]},"application/x-sql":{source:"apache",extensions:["sql"]},"application/x-stuffit":{source:"apache",compressible:!1,extensions:["sit"]},"application/x-stuffitx":{source:"apache",extensions:["sitx"]},"application/x-subrip":{source:"apache",extensions:["srt"]},"application/x-sv4cpio":{source:"apache",extensions:["sv4cpio"]},"application/x-sv4crc":{source:"apache",extensions:["sv4crc"]},"application/x-t3vm-image":{source:"apache",extensions:["t3"]},"application/x-tads":{source:"apache",extensions:["gam"]},"application/x-tar":{source:"apache",compressible:!0,extensions:["tar"]},"application/x-tcl":{source:"apache",extensions:["tcl","tk"]},"application/x-tex":{source:"apache",extensions:["tex"]},"application/x-tex-tfm":{source:"apache",extensions:["tfm"]},"application/x-texinfo":{source:"apache",extensions:["texinfo","texi"]},"application/x-tgif":{source:"apache",extensions:["obj"]},"application/x-ustar":{source:"apache",extensions:["ustar"]},"application/x-virtualbox-hdd":{compressible:!0,extensions:["hdd"]},"application/x-virtualbox-ova":{compressible:!0,extensions:["ova"]},"application/x-virtualbox-ovf":{compressible:!0,extensions:["ovf"]},"application/x-virtualbox-vbox":{compressible:!0,extensions:["vbox"]},"application/x-virtualbox-vbox-extpack":{compressible:!1,extensions:["vbox-extpack"]},"application/x-virtualbox-vdi":{compressible:!0,extensions:["vdi"]},"application/x-virtualbox-vhd":{compressible:!0,extensions:["vhd"]},"application/x-virtualbox-vmdk":{compressible:!0,extensions:["vmdk"]},"application/x-wais-source":{source:"apache",extensions:["src"]},"application/x-web-app-manifest+json":{compressible:!0,extensions:["webapp"]},"application/x-www-form-urlencoded":{source:"iana",compressible:!0},"application/x-x509-ca-cert":{source:"iana",extensions:["der","crt","pem"]},"application/x-x509-ca-ra-cert":{source:"iana"},"application/x-x509-next-ca-cert":{source:"iana"},"application/x-xfig":{source:"apache",extensions:["fig"]},"application/x-xliff+xml":{source:"apache",compressible:!0,extensions:["xlf"]},"application/x-xpinstall":{source:"apache",compressible:!1,extensions:["xpi"]},"application/x-xz":{source:"apache",extensions:["xz"]},"application/x-zip-compressed":{extensions:["zip"]},"application/x-zmachine":{source:"apache",extensions:["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/x400-bp":{source:"iana"},"application/xacml+xml":{source:"iana",compressible:!0},"application/xaml+xml":{source:"apache",compressible:!0,extensions:["xaml"]},"application/xcap-att+xml":{source:"iana",compressible:!0,extensions:["xav"]},"application/xcap-caps+xml":{source:"iana",compressible:!0,extensions:["xca"]},"application/xcap-diff+xml":{source:"iana",compressible:!0,extensions:["xdf"]},"application/xcap-el+xml":{source:"iana",compressible:!0,extensions:["xel"]},"application/xcap-error+xml":{source:"iana",compressible:!0},"application/xcap-ns+xml":{source:"iana",compressible:!0,extensions:["xns"]},"application/xcon-conference-info+xml":{source:"iana",compressible:!0},"application/xcon-conference-info-diff+xml":{source:"iana",compressible:!0},"application/xenc+xml":{source:"iana",compressible:!0,extensions:["xenc"]},"application/xfdf":{source:"iana",extensions:["xfdf"]},"application/xhtml+xml":{source:"iana",compressible:!0,extensions:["xhtml","xht"]},"application/xhtml-voice+xml":{source:"apache",compressible:!0},"application/xliff+xml":{source:"iana",compressible:!0,extensions:["xlf"]},"application/xml":{source:"iana",compressible:!0,extensions:["xml","xsl","xsd","rng"]},"application/xml-dtd":{source:"iana",compressible:!0,extensions:["dtd"]},"application/xml-external-parsed-entity":{source:"iana"},"application/xml-patch+xml":{source:"iana",compressible:!0},"application/xmpp+xml":{source:"iana",compressible:!0},"application/xop+xml":{source:"iana",compressible:!0,extensions:["xop"]},"application/xproc+xml":{source:"apache",compressible:!0,extensions:["xpl"]},"application/xslt+xml":{source:"iana",compressible:!0,extensions:["xsl","xslt"]},"application/xspf+xml":{source:"apache",compressible:!0,extensions:["xspf"]},"application/xv+xml":{source:"iana",compressible:!0,extensions:["mxml","xhvml","xvml","xvm"]},"application/yaml":{source:"iana"},"application/yang":{source:"iana",extensions:["yang"]},"application/yang-data+cbor":{source:"iana"},"application/yang-data+json":{source:"iana",compressible:!0},"application/yang-data+xml":{source:"iana",compressible:!0},"application/yang-patch+json":{source:"iana",compressible:!0},"application/yang-patch+xml":{source:"iana",compressible:!0},"application/yang-sid+json":{source:"iana",compressible:!0},"application/yin+xml":{source:"iana",compressible:!0,extensions:["yin"]},"application/zip":{source:"iana",compressible:!1,extensions:["zip"]},"application/zip+dotlottie":{extensions:["lottie"]},"application/zlib":{source:"iana"},"application/zstd":{source:"iana"},"audio/1d-interleaved-parityfec":{source:"iana"},"audio/32kadpcm":{source:"iana"},"audio/3gpp":{source:"iana",compressible:!1,extensions:["3gpp"]},"audio/3gpp2":{source:"iana"},"audio/aac":{source:"iana",extensions:["adts","aac"]},"audio/ac3":{source:"iana"},"audio/adpcm":{source:"apache",extensions:["adp"]},"audio/amr":{source:"iana",extensions:["amr"]},"audio/amr-wb":{source:"iana"},"audio/amr-wb+":{source:"iana"},"audio/aptx":{source:"iana"},"audio/asc":{source:"iana"},"audio/atrac-advanced-lossless":{source:"iana"},"audio/atrac-x":{source:"iana"},"audio/atrac3":{source:"iana"},"audio/basic":{source:"iana",compressible:!1,extensions:["au","snd"]},"audio/bv16":{source:"iana"},"audio/bv32":{source:"iana"},"audio/clearmode":{source:"iana"},"audio/cn":{source:"iana"},"audio/dat12":{source:"iana"},"audio/dls":{source:"iana"},"audio/dsr-es201108":{source:"iana"},"audio/dsr-es202050":{source:"iana"},"audio/dsr-es202211":{source:"iana"},"audio/dsr-es202212":{source:"iana"},"audio/dv":{source:"iana"},"audio/dvi4":{source:"iana"},"audio/eac3":{source:"iana"},"audio/encaprtp":{source:"iana"},"audio/evrc":{source:"iana"},"audio/evrc-qcp":{source:"iana"},"audio/evrc0":{source:"iana"},"audio/evrc1":{source:"iana"},"audio/evrcb":{source:"iana"},"audio/evrcb0":{source:"iana"},"audio/evrcb1":{source:"iana"},"audio/evrcnw":{source:"iana"},"audio/evrcnw0":{source:"iana"},"audio/evrcnw1":{source:"iana"},"audio/evrcwb":{source:"iana"},"audio/evrcwb0":{source:"iana"},"audio/evrcwb1":{source:"iana"},"audio/evs":{source:"iana"},"audio/flac":{source:"iana"},"audio/flexfec":{source:"iana"},"audio/fwdred":{source:"iana"},"audio/g711-0":{source:"iana"},"audio/g719":{source:"iana"},"audio/g722":{source:"iana"},"audio/g7221":{source:"iana"},"audio/g723":{source:"iana"},"audio/g726-16":{source:"iana"},"audio/g726-24":{source:"iana"},"audio/g726-32":{source:"iana"},"audio/g726-40":{source:"iana"},"audio/g728":{source:"iana"},"audio/g729":{source:"iana"},"audio/g7291":{source:"iana"},"audio/g729d":{source:"iana"},"audio/g729e":{source:"iana"},"audio/gsm":{source:"iana"},"audio/gsm-efr":{source:"iana"},"audio/gsm-hr-08":{source:"iana"},"audio/ilbc":{source:"iana"},"audio/ip-mr_v2.5":{source:"iana"},"audio/isac":{source:"apache"},"audio/l16":{source:"iana"},"audio/l20":{source:"iana"},"audio/l24":{source:"iana",compressible:!1},"audio/l8":{source:"iana"},"audio/lpc":{source:"iana"},"audio/matroska":{source:"iana"},"audio/melp":{source:"iana"},"audio/melp1200":{source:"iana"},"audio/melp2400":{source:"iana"},"audio/melp600":{source:"iana"},"audio/mhas":{source:"iana"},"audio/midi":{source:"apache",extensions:["mid","midi","kar","rmi"]},"audio/midi-clip":{source:"iana"},"audio/mobile-xmf":{source:"iana",extensions:["mxmf"]},"audio/mp3":{compressible:!1,extensions:["mp3"]},"audio/mp4":{source:"iana",compressible:!1,extensions:["m4a","mp4a","m4b"]},"audio/mp4a-latm":{source:"iana"},"audio/mpa":{source:"iana"},"audio/mpa-robust":{source:"iana"},"audio/mpeg":{source:"iana",compressible:!1,extensions:["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/mpeg4-generic":{source:"iana"},"audio/musepack":{source:"apache"},"audio/ogg":{source:"iana",compressible:!1,extensions:["oga","ogg","spx","opus"]},"audio/opus":{source:"iana"},"audio/parityfec":{source:"iana"},"audio/pcma":{source:"iana"},"audio/pcma-wb":{source:"iana"},"audio/pcmu":{source:"iana"},"audio/pcmu-wb":{source:"iana"},"audio/prs.sid":{source:"iana"},"audio/qcelp":{source:"iana"},"audio/raptorfec":{source:"iana"},"audio/red":{source:"iana"},"audio/rtp-enc-aescm128":{source:"iana"},"audio/rtp-midi":{source:"iana"},"audio/rtploopback":{source:"iana"},"audio/rtx":{source:"iana"},"audio/s3m":{source:"apache",extensions:["s3m"]},"audio/scip":{source:"iana"},"audio/silk":{source:"apache",extensions:["sil"]},"audio/smv":{source:"iana"},"audio/smv-qcp":{source:"iana"},"audio/smv0":{source:"iana"},"audio/sofa":{source:"iana"},"audio/sp-midi":{source:"iana"},"audio/speex":{source:"iana"},"audio/t140c":{source:"iana"},"audio/t38":{source:"iana"},"audio/telephone-event":{source:"iana"},"audio/tetra_acelp":{source:"iana"},"audio/tetra_acelp_bb":{source:"iana"},"audio/tone":{source:"iana"},"audio/tsvcis":{source:"iana"},"audio/uemclip":{source:"iana"},"audio/ulpfec":{source:"iana"},"audio/usac":{source:"iana"},"audio/vdvi":{source:"iana"},"audio/vmr-wb":{source:"iana"},"audio/vnd.3gpp.iufp":{source:"iana"},"audio/vnd.4sb":{source:"iana"},"audio/vnd.audiokoz":{source:"iana"},"audio/vnd.celp":{source:"iana"},"audio/vnd.cisco.nse":{source:"iana"},"audio/vnd.cmles.radio-events":{source:"iana"},"audio/vnd.cns.anp1":{source:"iana"},"audio/vnd.cns.inf1":{source:"iana"},"audio/vnd.dece.audio":{source:"iana",extensions:["uva","uvva"]},"audio/vnd.digital-winds":{source:"iana",extensions:["eol"]},"audio/vnd.dlna.adts":{source:"iana"},"audio/vnd.dolby.heaac.1":{source:"iana"},"audio/vnd.dolby.heaac.2":{source:"iana"},"audio/vnd.dolby.mlp":{source:"iana"},"audio/vnd.dolby.mps":{source:"iana"},"audio/vnd.dolby.pl2":{source:"iana"},"audio/vnd.dolby.pl2x":{source:"iana"},"audio/vnd.dolby.pl2z":{source:"iana"},"audio/vnd.dolby.pulse.1":{source:"iana"},"audio/vnd.dra":{source:"iana",extensions:["dra"]},"audio/vnd.dts":{source:"iana",extensions:["dts"]},"audio/vnd.dts.hd":{source:"iana",extensions:["dtshd"]},"audio/vnd.dts.uhd":{source:"iana"},"audio/vnd.dvb.file":{source:"iana"},"audio/vnd.everad.plj":{source:"iana"},"audio/vnd.hns.audio":{source:"iana"},"audio/vnd.lucent.voice":{source:"iana",extensions:["lvp"]},"audio/vnd.ms-playready.media.pya":{source:"iana",extensions:["pya"]},"audio/vnd.nokia.mobile-xmf":{source:"iana"},"audio/vnd.nortel.vbk":{source:"iana"},"audio/vnd.nuera.ecelp4800":{source:"iana",extensions:["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{source:"iana",extensions:["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{source:"iana",extensions:["ecelp9600"]},"audio/vnd.octel.sbc":{source:"iana"},"audio/vnd.presonus.multitrack":{source:"iana"},"audio/vnd.qcelp":{source:"apache"},"audio/vnd.rhetorex.32kadpcm":{source:"iana"},"audio/vnd.rip":{source:"iana",extensions:["rip"]},"audio/vnd.rn-realaudio":{compressible:!1},"audio/vnd.sealedmedia.softseal.mpeg":{source:"iana"},"audio/vnd.vmx.cvsd":{source:"iana"},"audio/vnd.wave":{compressible:!1},"audio/vorbis":{source:"iana",compressible:!1},"audio/vorbis-config":{source:"iana"},"audio/wav":{compressible:!1,extensions:["wav"]},"audio/wave":{compressible:!1,extensions:["wav"]},"audio/webm":{source:"apache",compressible:!1,extensions:["weba"]},"audio/x-aac":{source:"apache",compressible:!1,extensions:["aac"]},"audio/x-aiff":{source:"apache",extensions:["aif","aiff","aifc"]},"audio/x-caf":{source:"apache",compressible:!1,extensions:["caf"]},"audio/x-flac":{source:"apache",extensions:["flac"]},"audio/x-m4a":{source:"nginx",extensions:["m4a"]},"audio/x-matroska":{source:"apache",extensions:["mka"]},"audio/x-mpegurl":{source:"apache",extensions:["m3u"]},"audio/x-ms-wax":{source:"apache",extensions:["wax"]},"audio/x-ms-wma":{source:"apache",extensions:["wma"]},"audio/x-pn-realaudio":{source:"apache",extensions:["ram","ra"]},"audio/x-pn-realaudio-plugin":{source:"apache",extensions:["rmp"]},"audio/x-realaudio":{source:"nginx",extensions:["ra"]},"audio/x-tta":{source:"apache"},"audio/x-wav":{source:"apache",extensions:["wav"]},"audio/xm":{source:"apache",extensions:["xm"]},"chemical/x-cdx":{source:"apache",extensions:["cdx"]},"chemical/x-cif":{source:"apache",extensions:["cif"]},"chemical/x-cmdf":{source:"apache",extensions:["cmdf"]},"chemical/x-cml":{source:"apache",extensions:["cml"]},"chemical/x-csml":{source:"apache",extensions:["csml"]},"chemical/x-pdb":{source:"apache"},"chemical/x-xyz":{source:"apache",extensions:["xyz"]},"font/collection":{source:"iana",extensions:["ttc"]},"font/otf":{source:"iana",compressible:!0,extensions:["otf"]},"font/sfnt":{source:"iana"},"font/ttf":{source:"iana",compressible:!0,extensions:["ttf"]},"font/woff":{source:"iana",extensions:["woff"]},"font/woff2":{source:"iana",extensions:["woff2"]},"image/aces":{source:"iana",extensions:["exr"]},"image/apng":{source:"iana",compressible:!1,extensions:["apng"]},"image/avci":{source:"iana",extensions:["avci"]},"image/avcs":{source:"iana",extensions:["avcs"]},"image/avif":{source:"iana",compressible:!1,extensions:["avif"]},"image/bmp":{source:"iana",compressible:!0,extensions:["bmp","dib"]},"image/cgm":{source:"iana",extensions:["cgm"]},"image/dicom-rle":{source:"iana",extensions:["drle"]},"image/dpx":{source:"iana",extensions:["dpx"]},"image/emf":{source:"iana",extensions:["emf"]},"image/fits":{source:"iana",extensions:["fits"]},"image/g3fax":{source:"iana",extensions:["g3"]},"image/gif":{source:"iana",compressible:!1,extensions:["gif"]},"image/heic":{source:"iana",extensions:["heic"]},"image/heic-sequence":{source:"iana",extensions:["heics"]},"image/heif":{source:"iana",extensions:["heif"]},"image/heif-sequence":{source:"iana",extensions:["heifs"]},"image/hej2k":{source:"iana",extensions:["hej2"]},"image/ief":{source:"iana",extensions:["ief"]},"image/j2c":{source:"iana"},"image/jaii":{source:"iana",extensions:["jaii"]},"image/jais":{source:"iana",extensions:["jais"]},"image/jls":{source:"iana",extensions:["jls"]},"image/jp2":{source:"iana",compressible:!1,extensions:["jp2","jpg2"]},"image/jpeg":{source:"iana",compressible:!1,extensions:["jpg","jpeg","jpe"]},"image/jph":{source:"iana",extensions:["jph"]},"image/jphc":{source:"iana",extensions:["jhc"]},"image/jpm":{source:"iana",compressible:!1,extensions:["jpm","jpgm"]},"image/jpx":{source:"iana",compressible:!1,extensions:["jpx","jpf"]},"image/jxl":{source:"iana",extensions:["jxl"]},"image/jxr":{source:"iana",extensions:["jxr"]},"image/jxra":{source:"iana",extensions:["jxra"]},"image/jxrs":{source:"iana",extensions:["jxrs"]},"image/jxs":{source:"iana",extensions:["jxs"]},"image/jxsc":{source:"iana",extensions:["jxsc"]},"image/jxsi":{source:"iana",extensions:["jxsi"]},"image/jxss":{source:"iana",extensions:["jxss"]},"image/ktx":{source:"iana",extensions:["ktx"]},"image/ktx2":{source:"iana",extensions:["ktx2"]},"image/naplps":{source:"iana"},"image/pjpeg":{compressible:!1,extensions:["jfif"]},"image/png":{source:"iana",compressible:!1,extensions:["png"]},"image/prs.btif":{source:"iana",extensions:["btif","btf"]},"image/prs.pti":{source:"iana",extensions:["pti"]},"image/pwg-raster":{source:"iana"},"image/sgi":{source:"apache",extensions:["sgi"]},"image/svg+xml":{source:"iana",compressible:!0,extensions:["svg","svgz"]},"image/t38":{source:"iana",extensions:["t38"]},"image/tiff":{source:"iana",compressible:!1,extensions:["tif","tiff"]},"image/tiff-fx":{source:"iana",extensions:["tfx"]},"image/vnd.adobe.photoshop":{source:"iana",compressible:!0,extensions:["psd"]},"image/vnd.airzip.accelerator.azv":{source:"iana",extensions:["azv"]},"image/vnd.clip":{source:"iana"},"image/vnd.cns.inf2":{source:"iana"},"image/vnd.dece.graphic":{source:"iana",extensions:["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{source:"iana",extensions:["djvu","djv"]},"image/vnd.dvb.subtitle":{source:"iana",extensions:["sub"]},"image/vnd.dwg":{source:"iana",extensions:["dwg"]},"image/vnd.dxf":{source:"iana",extensions:["dxf"]},"image/vnd.fastbidsheet":{source:"iana",extensions:["fbs"]},"image/vnd.fpx":{source:"iana",extensions:["fpx"]},"image/vnd.fst":{source:"iana",extensions:["fst"]},"image/vnd.fujixerox.edmics-mmr":{source:"iana",extensions:["mmr"]},"image/vnd.fujixerox.edmics-rlc":{source:"iana",extensions:["rlc"]},"image/vnd.globalgraphics.pgb":{source:"iana"},"image/vnd.microsoft.icon":{source:"iana",compressible:!0,extensions:["ico"]},"image/vnd.mix":{source:"iana"},"image/vnd.mozilla.apng":{source:"iana"},"image/vnd.ms-dds":{compressible:!0,extensions:["dds"]},"image/vnd.ms-modi":{source:"iana",extensions:["mdi"]},"image/vnd.ms-photo":{source:"apache",extensions:["wdp"]},"image/vnd.net-fpx":{source:"iana",extensions:["npx"]},"image/vnd.pco.b16":{source:"iana",extensions:["b16"]},"image/vnd.radiance":{source:"iana"},"image/vnd.sealed.png":{source:"iana"},"image/vnd.sealedmedia.softseal.gif":{source:"iana"},"image/vnd.sealedmedia.softseal.jpg":{source:"iana"},"image/vnd.svf":{source:"iana"},"image/vnd.tencent.tap":{source:"iana",extensions:["tap"]},"image/vnd.valve.source.texture":{source:"iana",extensions:["vtf"]},"image/vnd.wap.wbmp":{source:"iana",extensions:["wbmp"]},"image/vnd.xiff":{source:"iana",extensions:["xif"]},"image/vnd.zbrush.pcx":{source:"iana",extensions:["pcx"]},"image/webp":{source:"iana",extensions:["webp"]},"image/wmf":{source:"iana",extensions:["wmf"]},"image/x-3ds":{source:"apache",extensions:["3ds"]},"image/x-adobe-dng":{extensions:["dng"]},"image/x-cmu-raster":{source:"apache",extensions:["ras"]},"image/x-cmx":{source:"apache",extensions:["cmx"]},"image/x-emf":{source:"iana"},"image/x-freehand":{source:"apache",extensions:["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{source:"apache",compressible:!0,extensions:["ico"]},"image/x-jng":{source:"nginx",extensions:["jng"]},"image/x-mrsid-image":{source:"apache",extensions:["sid"]},"image/x-ms-bmp":{source:"nginx",compressible:!0,extensions:["bmp"]},"image/x-pcx":{source:"apache",extensions:["pcx"]},"image/x-pict":{source:"apache",extensions:["pic","pct"]},"image/x-portable-anymap":{source:"apache",extensions:["pnm"]},"image/x-portable-bitmap":{source:"apache",extensions:["pbm"]},"image/x-portable-graymap":{source:"apache",extensions:["pgm"]},"image/x-portable-pixmap":{source:"apache",extensions:["ppm"]},"image/x-rgb":{source:"apache",extensions:["rgb"]},"image/x-tga":{source:"apache",extensions:["tga"]},"image/x-wmf":{source:"iana"},"image/x-xbitmap":{source:"apache",extensions:["xbm"]},"image/x-xcf":{compressible:!1},"image/x-xpixmap":{source:"apache",extensions:["xpm"]},"image/x-xwindowdump":{source:"apache",extensions:["xwd"]},"message/bhttp":{source:"iana"},"message/cpim":{source:"iana"},"message/delivery-status":{source:"iana"},"message/disposition-notification":{source:"iana",extensions:["disposition-notification"]},"message/external-body":{source:"iana"},"message/feedback-report":{source:"iana"},"message/global":{source:"iana",extensions:["u8msg"]},"message/global-delivery-status":{source:"iana",extensions:["u8dsn"]},"message/global-disposition-notification":{source:"iana",extensions:["u8mdn"]},"message/global-headers":{source:"iana",extensions:["u8hdr"]},"message/http":{source:"iana",compressible:!1},"message/imdn+xml":{source:"iana",compressible:!0},"message/mls":{source:"iana"},"message/news":{source:"apache"},"message/ohttp-req":{source:"iana"},"message/ohttp-res":{source:"iana"},"message/partial":{source:"iana",compressible:!1},"message/rfc822":{source:"iana",compressible:!0,extensions:["eml","mime","mht","mhtml"]},"message/s-http":{source:"apache"},"message/sip":{source:"iana"},"message/sipfrag":{source:"iana"},"message/tracking-status":{source:"iana"},"message/vnd.si.simp":{source:"apache"},"message/vnd.wfa.wsc":{source:"iana",extensions:["wsc"]},"model/3mf":{source:"iana",extensions:["3mf"]},"model/e57":{source:"iana"},"model/gltf+json":{source:"iana",compressible:!0,extensions:["gltf"]},"model/gltf-binary":{source:"iana",compressible:!0,extensions:["glb"]},"model/iges":{source:"iana",compressible:!1,extensions:["igs","iges"]},"model/jt":{source:"iana",extensions:["jt"]},"model/mesh":{source:"iana",compressible:!1,extensions:["msh","mesh","silo"]},"model/mtl":{source:"iana",extensions:["mtl"]},"model/obj":{source:"iana",extensions:["obj"]},"model/prc":{source:"iana",extensions:["prc"]},"model/step":{source:"iana",extensions:["step","stp","stpnc","p21","210"]},"model/step+xml":{source:"iana",compressible:!0,extensions:["stpx"]},"model/step+zip":{source:"iana",compressible:!1,extensions:["stpz"]},"model/step-xml+zip":{source:"iana",compressible:!1,extensions:["stpxz"]},"model/stl":{source:"iana",extensions:["stl"]},"model/u3d":{source:"iana",extensions:["u3d"]},"model/vnd.bary":{source:"iana",extensions:["bary"]},"model/vnd.cld":{source:"iana",extensions:["cld"]},"model/vnd.collada+xml":{source:"iana",compressible:!0,extensions:["dae"]},"model/vnd.dwf":{source:"iana",extensions:["dwf"]},"model/vnd.flatland.3dml":{source:"iana"},"model/vnd.gdl":{source:"iana",extensions:["gdl"]},"model/vnd.gs-gdl":{source:"apache"},"model/vnd.gs.gdl":{source:"iana"},"model/vnd.gtw":{source:"iana",extensions:["gtw"]},"model/vnd.moml+xml":{source:"iana",compressible:!0},"model/vnd.mts":{source:"iana",extensions:["mts"]},"model/vnd.opengex":{source:"iana",extensions:["ogex"]},"model/vnd.parasolid.transmit.binary":{source:"iana",extensions:["x_b"]},"model/vnd.parasolid.transmit.text":{source:"iana",extensions:["x_t"]},"model/vnd.pytha.pyox":{source:"iana",extensions:["pyo","pyox"]},"model/vnd.rosette.annotated-data-model":{source:"iana"},"model/vnd.sap.vds":{source:"iana",extensions:["vds"]},"model/vnd.usda":{source:"iana",extensions:["usda"]},"model/vnd.usdz+zip":{source:"iana",compressible:!1,extensions:["usdz"]},"model/vnd.valve.source.compiled-map":{source:"iana",extensions:["bsp"]},"model/vnd.vtu":{source:"iana",extensions:["vtu"]},"model/vrml":{source:"iana",compressible:!1,extensions:["wrl","vrml"]},"model/x3d+binary":{source:"apache",compressible:!1,extensions:["x3db","x3dbz"]},"model/x3d+fastinfoset":{source:"iana",extensions:["x3db"]},"model/x3d+vrml":{source:"apache",compressible:!1,extensions:["x3dv","x3dvz"]},"model/x3d+xml":{source:"iana",compressible:!0,extensions:["x3d","x3dz"]},"model/x3d-vrml":{source:"iana",extensions:["x3dv"]},"multipart/alternative":{source:"iana",compressible:!1},"multipart/appledouble":{source:"iana"},"multipart/byteranges":{source:"iana"},"multipart/digest":{source:"iana"},"multipart/encrypted":{source:"iana",compressible:!1},"multipart/form-data":{source:"iana",compressible:!1},"multipart/header-set":{source:"iana"},"multipart/mixed":{source:"iana"},"multipart/multilingual":{source:"iana"},"multipart/parallel":{source:"iana"},"multipart/related":{source:"iana",compressible:!1},"multipart/report":{source:"iana"},"multipart/signed":{source:"iana",compressible:!1},"multipart/vnd.bint.med-plus":{source:"iana"},"multipart/voice-message":{source:"iana"},"multipart/x-mixed-replace":{source:"iana"},"text/1d-interleaved-parityfec":{source:"iana"},"text/cache-manifest":{source:"iana",compressible:!0,extensions:["appcache","manifest"]},"text/calendar":{source:"iana",extensions:["ics","ifb"]},"text/calender":{compressible:!0},"text/cmd":{compressible:!0},"text/coffeescript":{extensions:["coffee","litcoffee"]},"text/cql":{source:"iana"},"text/cql-expression":{source:"iana"},"text/cql-identifier":{source:"iana"},"text/css":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["css"]},"text/csv":{source:"iana",compressible:!0,extensions:["csv"]},"text/csv-schema":{source:"iana"},"text/directory":{source:"iana"},"text/dns":{source:"iana"},"text/ecmascript":{source:"apache"},"text/encaprtp":{source:"iana"},"text/enriched":{source:"iana"},"text/fhirpath":{source:"iana"},"text/flexfec":{source:"iana"},"text/fwdred":{source:"iana"},"text/gff3":{source:"iana"},"text/grammar-ref-list":{source:"iana"},"text/hl7v2":{source:"iana"},"text/html":{source:"iana",compressible:!0,extensions:["html","htm","shtml"]},"text/jade":{extensions:["jade"]},"text/javascript":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["js","mjs"]},"text/jcr-cnd":{source:"iana"},"text/jsx":{compressible:!0,extensions:["jsx"]},"text/less":{compressible:!0,extensions:["less"]},"text/markdown":{source:"iana",compressible:!0,extensions:["md","markdown"]},"text/mathml":{source:"nginx",extensions:["mml"]},"text/mdx":{compressible:!0,extensions:["mdx"]},"text/mizar":{source:"iana"},"text/n3":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["n3"]},"text/parameters":{source:"iana",charset:"UTF-8"},"text/parityfec":{source:"iana"},"text/plain":{source:"iana",compressible:!0,extensions:["txt","text","conf","def","list","log","in","ini"]},"text/provenance-notation":{source:"iana",charset:"UTF-8"},"text/prs.fallenstein.rst":{source:"iana"},"text/prs.lines.tag":{source:"iana",extensions:["dsc"]},"text/prs.prop.logic":{source:"iana"},"text/prs.texi":{source:"iana"},"text/raptorfec":{source:"iana"},"text/red":{source:"iana"},"text/rfc822-headers":{source:"iana"},"text/richtext":{source:"iana",compressible:!0,extensions:["rtx"]},"text/rtf":{source:"iana",compressible:!0,extensions:["rtf"]},"text/rtp-enc-aescm128":{source:"iana"},"text/rtploopback":{source:"iana"},"text/rtx":{source:"iana"},"text/sgml":{source:"iana",extensions:["sgml","sgm"]},"text/shaclc":{source:"iana"},"text/shex":{source:"iana",extensions:["shex"]},"text/slim":{extensions:["slim","slm"]},"text/spdx":{source:"iana",extensions:["spdx"]},"text/strings":{source:"iana"},"text/stylus":{extensions:["stylus","styl"]},"text/t140":{source:"iana"},"text/tab-separated-values":{source:"iana",compressible:!0,extensions:["tsv"]},"text/troff":{source:"iana",extensions:["t","tr","roff","man","me","ms"]},"text/turtle":{source:"iana",charset:"UTF-8",extensions:["ttl"]},"text/ulpfec":{source:"iana"},"text/uri-list":{source:"iana",compressible:!0,extensions:["uri","uris","urls"]},"text/vcard":{source:"iana",compressible:!0,extensions:["vcard"]},"text/vnd.a":{source:"iana"},"text/vnd.abc":{source:"iana"},"text/vnd.ascii-art":{source:"iana"},"text/vnd.curl":{source:"iana",extensions:["curl"]},"text/vnd.curl.dcurl":{source:"apache",extensions:["dcurl"]},"text/vnd.curl.mcurl":{source:"apache",extensions:["mcurl"]},"text/vnd.curl.scurl":{source:"apache",extensions:["scurl"]},"text/vnd.debian.copyright":{source:"iana",charset:"UTF-8"},"text/vnd.dmclientscript":{source:"iana"},"text/vnd.dvb.subtitle":{source:"iana",extensions:["sub"]},"text/vnd.esmertec.theme-descriptor":{source:"iana",charset:"UTF-8"},"text/vnd.exchangeable":{source:"iana"},"text/vnd.familysearch.gedcom":{source:"iana",extensions:["ged"]},"text/vnd.ficlab.flt":{source:"iana"},"text/vnd.fly":{source:"iana",extensions:["fly"]},"text/vnd.fmi.flexstor":{source:"iana",extensions:["flx"]},"text/vnd.gml":{source:"iana"},"text/vnd.graphviz":{source:"iana",extensions:["gv"]},"text/vnd.hans":{source:"iana"},"text/vnd.hgl":{source:"iana"},"text/vnd.in3d.3dml":{source:"iana",extensions:["3dml"]},"text/vnd.in3d.spot":{source:"iana",extensions:["spot"]},"text/vnd.iptc.newsml":{source:"iana"},"text/vnd.iptc.nitf":{source:"iana"},"text/vnd.latex-z":{source:"iana"},"text/vnd.motorola.reflex":{source:"iana"},"text/vnd.ms-mediapackage":{source:"iana"},"text/vnd.net2phone.commcenter.command":{source:"iana"},"text/vnd.radisys.msml-basic-layout":{source:"iana"},"text/vnd.senx.warpscript":{source:"iana"},"text/vnd.si.uricatalogue":{source:"apache"},"text/vnd.sosi":{source:"iana"},"text/vnd.sun.j2me.app-descriptor":{source:"iana",charset:"UTF-8",extensions:["jad"]},"text/vnd.trolltech.linguist":{source:"iana",charset:"UTF-8"},"text/vnd.vcf":{source:"iana"},"text/vnd.wap.si":{source:"iana"},"text/vnd.wap.sl":{source:"iana"},"text/vnd.wap.wml":{source:"iana",extensions:["wml"]},"text/vnd.wap.wmlscript":{source:"iana",extensions:["wmls"]},"text/vnd.zoo.kcl":{source:"iana"},"text/vtt":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["vtt"]},"text/wgsl":{source:"iana",extensions:["wgsl"]},"text/x-asm":{source:"apache",extensions:["s","asm"]},"text/x-c":{source:"apache",extensions:["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{source:"nginx",extensions:["htc"]},"text/x-fortran":{source:"apache",extensions:["f","for","f77","f90"]},"text/x-gwt-rpc":{compressible:!0},"text/x-handlebars-template":{extensions:["hbs"]},"text/x-java-source":{source:"apache",extensions:["java"]},"text/x-jquery-tmpl":{compressible:!0},"text/x-lua":{extensions:["lua"]},"text/x-markdown":{compressible:!0,extensions:["mkd"]},"text/x-nfo":{source:"apache",extensions:["nfo"]},"text/x-opml":{source:"apache",extensions:["opml"]},"text/x-org":{compressible:!0,extensions:["org"]},"text/x-pascal":{source:"apache",extensions:["p","pas"]},"text/x-processing":{compressible:!0,extensions:["pde"]},"text/x-sass":{extensions:["sass"]},"text/x-scss":{extensions:["scss"]},"text/x-setext":{source:"apache",extensions:["etx"]},"text/x-sfv":{source:"apache",extensions:["sfv"]},"text/x-suse-ymp":{compressible:!0,extensions:["ymp"]},"text/x-uuencode":{source:"apache",extensions:["uu"]},"text/x-vcalendar":{source:"apache",extensions:["vcs"]},"text/x-vcard":{source:"apache",extensions:["vcf"]},"text/xml":{source:"iana",compressible:!0,extensions:["xml"]},"text/xml-external-parsed-entity":{source:"iana"},"text/yaml":{compressible:!0,extensions:["yaml","yml"]},"video/1d-interleaved-parityfec":{source:"iana"},"video/3gpp":{source:"iana",extensions:["3gp","3gpp"]},"video/3gpp-tt":{source:"iana"},"video/3gpp2":{source:"iana",extensions:["3g2"]},"video/av1":{source:"iana"},"video/bmpeg":{source:"iana"},"video/bt656":{source:"iana"},"video/celb":{source:"iana"},"video/dv":{source:"iana"},"video/encaprtp":{source:"iana"},"video/evc":{source:"iana"},"video/ffv1":{source:"iana"},"video/flexfec":{source:"iana"},"video/h261":{source:"iana",extensions:["h261"]},"video/h263":{source:"iana",extensions:["h263"]},"video/h263-1998":{source:"iana"},"video/h263-2000":{source:"iana"},"video/h264":{source:"iana",extensions:["h264"]},"video/h264-rcdo":{source:"iana"},"video/h264-svc":{source:"iana"},"video/h265":{source:"iana"},"video/h266":{source:"iana"},"video/iso.segment":{source:"iana",extensions:["m4s"]},"video/jpeg":{source:"iana",extensions:["jpgv"]},"video/jpeg2000":{source:"iana"},"video/jpm":{source:"apache",extensions:["jpm","jpgm"]},"video/jxsv":{source:"iana"},"video/lottie+json":{source:"iana",compressible:!0},"video/matroska":{source:"iana"},"video/matroska-3d":{source:"iana"},"video/mj2":{source:"iana",extensions:["mj2","mjp2"]},"video/mp1s":{source:"iana"},"video/mp2p":{source:"iana"},"video/mp2t":{source:"iana",extensions:["ts","m2t","m2ts","mts"]},"video/mp4":{source:"iana",compressible:!1,extensions:["mp4","mp4v","mpg4"]},"video/mp4v-es":{source:"iana"},"video/mpeg":{source:"iana",compressible:!1,extensions:["mpeg","mpg","mpe","m1v","m2v"]},"video/mpeg4-generic":{source:"iana"},"video/mpv":{source:"iana"},"video/nv":{source:"iana"},"video/ogg":{source:"iana",compressible:!1,extensions:["ogv"]},"video/parityfec":{source:"iana"},"video/pointer":{source:"iana"},"video/quicktime":{source:"iana",compressible:!1,extensions:["qt","mov"]},"video/raptorfec":{source:"iana"},"video/raw":{source:"iana"},"video/rtp-enc-aescm128":{source:"iana"},"video/rtploopback":{source:"iana"},"video/rtx":{source:"iana"},"video/scip":{source:"iana"},"video/smpte291":{source:"iana"},"video/smpte292m":{source:"iana"},"video/ulpfec":{source:"iana"},"video/vc1":{source:"iana"},"video/vc2":{source:"iana"},"video/vnd.cctv":{source:"iana"},"video/vnd.dece.hd":{source:"iana",extensions:["uvh","uvvh"]},"video/vnd.dece.mobile":{source:"iana",extensions:["uvm","uvvm"]},"video/vnd.dece.mp4":{source:"iana"},"video/vnd.dece.pd":{source:"iana",extensions:["uvp","uvvp"]},"video/vnd.dece.sd":{source:"iana",extensions:["uvs","uvvs"]},"video/vnd.dece.video":{source:"iana",extensions:["uvv","uvvv"]},"video/vnd.directv.mpeg":{source:"iana"},"video/vnd.directv.mpeg-tts":{source:"iana"},"video/vnd.dlna.mpeg-tts":{source:"iana"},"video/vnd.dvb.file":{source:"iana",extensions:["dvb"]},"video/vnd.fvt":{source:"iana",extensions:["fvt"]},"video/vnd.hns.video":{source:"iana"},"video/vnd.iptvforum.1dparityfec-1010":{source:"iana"},"video/vnd.iptvforum.1dparityfec-2005":{source:"iana"},"video/vnd.iptvforum.2dparityfec-1010":{source:"iana"},"video/vnd.iptvforum.2dparityfec-2005":{source:"iana"},"video/vnd.iptvforum.ttsavc":{source:"iana"},"video/vnd.iptvforum.ttsmpeg2":{source:"iana"},"video/vnd.motorola.video":{source:"iana"},"video/vnd.motorola.videop":{source:"iana"},"video/vnd.mpegurl":{source:"iana",extensions:["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{source:"iana",extensions:["pyv"]},"video/vnd.nokia.interleaved-multimedia":{source:"iana"},"video/vnd.nokia.mp4vr":{source:"iana"},"video/vnd.nokia.videovoip":{source:"iana"},"video/vnd.objectvideo":{source:"iana"},"video/vnd.planar":{source:"iana"},"video/vnd.radgamettools.bink":{source:"iana"},"video/vnd.radgamettools.smacker":{source:"apache"},"video/vnd.sealed.mpeg1":{source:"iana"},"video/vnd.sealed.mpeg4":{source:"iana"},"video/vnd.sealed.swf":{source:"iana"},"video/vnd.sealedmedia.softseal.mov":{source:"iana"},"video/vnd.uvvu.mp4":{source:"iana",extensions:["uvu","uvvu"]},"video/vnd.vivo":{source:"iana",extensions:["viv"]},"video/vnd.youtube.yt":{source:"iana"},"video/vp8":{source:"iana"},"video/vp9":{source:"iana"},"video/webm":{source:"apache",compressible:!1,extensions:["webm"]},"video/x-f4v":{source:"apache",extensions:["f4v"]},"video/x-fli":{source:"apache",extensions:["fli"]},"video/x-flv":{source:"apache",compressible:!1,extensions:["flv"]},"video/x-m4v":{source:"apache",extensions:["m4v"]},"video/x-matroska":{source:"apache",compressible:!1,extensions:["mkv","mk3d","mks"]},"video/x-mng":{source:"apache",extensions:["mng"]},"video/x-ms-asf":{source:"apache",extensions:["asf","asx"]},"video/x-ms-vob":{source:"apache",extensions:["vob"]},"video/x-ms-wm":{source:"apache",extensions:["wm"]},"video/x-ms-wmv":{source:"apache",compressible:!1,extensions:["wmv"]},"video/x-ms-wmx":{source:"apache",extensions:["wmx"]},"video/x-ms-wvx":{source:"apache",extensions:["wvx"]},"video/x-msvideo":{source:"apache",extensions:["avi"]},"video/x-sgi-movie":{source:"apache",extensions:["movie"]},"video/x-smv":{source:"apache",extensions:["smv"]},"x-conference/x-cooltalk":{source:"apache",extensions:["ice"]},"x-shader/x-fragment":{compressible:!0},"x-shader/x-vertex":{compressible:!0}};function In(){if(bn)return vn;bn=1;var e={"prs.":100,"x-":200,"x.":300,"vnd.":400,default:900},n={nginx:10,apache:20,iana:40,default:30},a={application:1,font:2,audio:2,video:3,default:0};return vn=function(t,s="default"){if("application/octet-stream"===t)return 0;const[i,o]=t.split("/"),r=o.replace(/(\.|x-).*/,"$1");return(e[r]||e.default)+(n[s]||n.default)+(a[i]||a.default)+(1-t.length/100)}}var Sn=(yn||(yn=1,function(e){var n,a,t=xn?fn:(xn=1,fn=kn),s=B.extname,i=In(),o=/^\s*([^;\s]*)(?:;|\s|$)/,r=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var n=o.exec(e),a=n&&t[n[1].toLowerCase()];return a&&a.charset?a.charset:!(!n||!r.test(n[1]))&&"UTF-8"}function p(n){if(!n||"string"!=typeof n)return!1;var a=o.exec(n),t=a&&e.extensions[a[1].toLowerCase()];return!(!t||!t.length)&&t[0]}function l(e,n,a){return(n?i(n,t[n].source):0)>(a?i(a,t[a].source):0)?n:a}function d(n,a,s){var i=["nginx","apache",void 0,"iana"],o=a?i.indexOf(t[a].source):0,r=s?i.indexOf(t[s].source):0;return"application/octet-stream"!==e.types[p]&&(o>r||o===r&&"application/"===e.types[p]?.slice(0,12))||o>r?a:s}e.charset=c,e.charsets={lookup:c},e.contentType=function(n){if(!n||"string"!=typeof n)return!1;var a=-1===n.indexOf("/")?e.lookup(n):n;if(!a)return!1;if(-1===a.indexOf("charset")){var t=e.charset(a);t&&(a+="; charset="+t.toLowerCase())}return a},e.extension=p,e.extensions=Object.create(null),e.lookup=function(n){if(!n||"string"!=typeof n)return!1;var a=s("x."+n).toLowerCase().slice(1);return a&&e.types[a]||!1},e.types=Object.create(null),e._extensionConflicts=[],n=e.extensions,a=e.types,Object.keys(t).forEach(function(s){var i=t[s].extensions;if(i&&i.length){n[s]=i;for(var o=0;o<i.length;o++){var r=i[o];a[r]=l(0,a[r],s);const n=d(0,a[r],s);n!==a[r]&&e._extensionConflicts.push([r,n,a[r]])}}})}(wn)),wn);function Tn(e,n){e?e.send("workspace-file-response",n):P.error("[WORKSPACE] Cannot send workspace-file-response: client not available")}function En(e,n,a,t){return{eventId:d(),requestId:e,taskId:n,success:!1,error:{code:a,message:t}}}function Cn(e){return async n=>{const{taskId:a,userId:t,relativePath:s,requestId:i,maxFileSizeMB:o,ifModifiedSince:r,dataEncryptionKey:c}=n;P.debug(`[WORKSPACE] File request: taskId=${a}, userId=${t}, relativePath=${s}, maxFileSizeMB=${o}, ifModifiedSince=${r}, hasEncryptionKey=${!!c}`);try{const n=1024*(o||10)*1024,m=function(e,n,a){return D.resolveWorkspaceFilePath(e,n,a)}(t,a,s);if(!ne.existsSync(m))return P.warn(`[WORKSPACE] File not found: ${m}`),void Tn(e.client,En(i,a,"file_not_found","File or directory not found"));const g=await ne.promises.stat(m),h=g.mtime.toISOString();if(r&&h===r)return void function(e,n,a,t){P.debug(`[WORKSPACE] File not modified: ${t}`),Tn(e,{eventId:d(),requestId:n,taskId:a,success:!0,notModified:!0})}(e.client,i,a,m);if(g.isDirectory())return void await async function(e,n,a,t,s,i){const o=await ne.promises.readdir(t,{withFileTypes:!0}),r=await Promise.all(o.map(async e=>{const n=me.join(t,e.name),a=await ne.promises.stat(n);return{name:e.name,type:e.isDirectory()?"directory":"file",size:a.size,modifiedAt:a.mtime.toISOString(),accessDenied:a.size>i}}));Tn(e,{eventId:d(),requestId:n,taskId:a,success:!0,data:{type:"directory",entries:r,metadata:{size:0,modifiedAt:s.mtime.toISOString()}}})}(e.client,i,a,m,g,n);{const t=Sn.lookup(m)||"application/octet-stream";return g.size>n?void function(e,n,a,t,s,i,o){P.warn(`[WORKSPACE] File too large (${s.size} bytes > ${o} bytes): ${t}`),Tn(e,{eventId:d(),requestId:n,taskId:a,success:!0,data:{type:"file",metadata:{size:s.size,mimeType:i,modifiedAt:s.mtime.toISOString(),accessDenied:!0}}})}(e.client,i,a,m,g,t,n):void await async function(e,n,a,t,s,i){const o=Sn.lookup(t)||"application/octet-stream",r=(await ne.promises.readFile(t)).toString("base64");let c=null;i&&(c=await async function(e){try{const n=await D.getSecretKey();if(!n)return P.warn("[WORKSPACE] Machine secret key not available"),null;const a=p(e);return l(a,n)||(P.warn("[WORKSPACE] Failed to decrypt dataEncryptionKey"),null)}catch(e){return P.warn("[WORKSPACE] Error decrypting dataEncryptionKey:",e),null}}(i));const m={type:"file",metadata:{size:s.size,mimeType:o,modifiedAt:s.mtime.toISOString()}};c?m.encryptedContent=u(r,c):m.content=r,Tn(e,{eventId:d(),requestId:n,taskId:a,success:!0,data:m})}(e.client,i,a,m,g,c)}}catch(n){P.error(`[WORKSPACE] Failed to handle workspace-file-request: ${n.message}`,n);const t="ENOENT"===n.code?"file_not_found":"EACCES"===n.code?"permission_denied":"unknown_error";Tn(e.client,En(i,a,t,n.message))}}}const An=he(D.agentrixHomeDir,"credentials");function Rn(e,n){const a=function(e){return he(An,`${e}.pat.enc`)}(e);if(!te(a))return null;try{const e=se(a,"utf8"),{iv:t,authTag:s,encrypted:i}=JSON.parse(e),o=n.slice(0,32),r=_("aes-256-gcm",o,Buffer.from(t,"hex"));r.setAuthTag(Buffer.from(s,"hex"));let c=r.update(i,"hex","utf8");return c+=r.final("utf8"),c}catch{return null}}const _n=[{method:"GET",pattern:/^\/projects$/},{method:"GET",pattern:/^\/projects\/[^/]+\/repository\/branches$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues\/\d+$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests$/}];class Mn{apiUrl;pat;requestId;gitServerId;constructor(e,n,a){this.apiUrl=e,this.pat=n,this.requestId=a?.requestId,this.gitServerId=a?.gitServerId}logPrefix(){return`[GITLAB EXECUTOR] reqId=${this.requestId??"-"}, gitServer=${this.gitServerId??"-"}`}summarizeResult(e,n){if(Array.isArray(n))return`items=${n.length}`;if(n&&"object"==typeof n){const a=n;return"resolveGitAuthContext"===e?`authMode=${String(a.authMode??"unknown")}, hasPat=${Boolean(a.hasPat)}`:"number"in a||"state"in a?`number=${String(a.number??"-")}, state=${String(a.state??"-")}`:`keys=${Object.keys(a).join(",")||"-"}`}return"type="+typeof n}truncateText(e,n=300){return e.length<=n?e:`${e.slice(0,n)}...`}async request(e,n="GET",a){const t=`${this.apiUrl}${e}`,s={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/json"},i=Date.now();P.debug(`${this.logPrefix()} request start: ${n} ${e}`);try{const o=await fetch(t,{method:n,headers:s,body:a?JSON.stringify(a):void 0}),r=Date.now()-i;if(!o.ok){const a=await o.text().catch(()=>"Unknown error"),t=this.truncateText(a);throw P.warn(`${this.logPrefix()} request failed: ${n} ${e}, status=${o.status}, elapsedMs=${r}, detail=${t}`),{status:o.status,message:`GitLab API error: ${o.status} ${o.statusText}`,detail:t}}return P.debug(`${this.logPrefix()} request success: ${n} ${e}, elapsedMs=${r}`),await o.json()}catch(a){if("object"==typeof a&&null!==a&&"status"in a)throw a;const t=a instanceof Error?a.message:"Unknown network error";throw P.error(`${this.logPrefix()} request exception: ${n} ${e}, message=${t}`),{status:0,message:`GitLab request failed: ${t}`}}}async executeOperation(e,n){P.info(`${this.logPrefix()} execute operation: op=${e}, payloadKeys=${Object.keys(n||{}).join(",")||"-"}`);try{let a;switch(e){case"listRepos":a=await this.listRepos();break;case"listBranches":a=await this.listBranches(n.owner,n.name);break;case"createMergeRequest":a=await this.createMergeRequest(n);break;case"getMergeRequest":a=await this.getMergeRequest(n.owner,n.name,n.iid);break;case"listMergeRequests":a=await this.listMergeRequests(n.owner,n.name);break;case"requestGitlabApi":a=await this.requestGitlabApi(n);break;case"resolveGitAuthContext":a={authMode:"local_pat",hasPat:!0};break;default:throw{status:400,message:`Unknown operation: ${e}`}}return P.info(`${this.logPrefix()} operation success: op=${e}, summary=${this.summarizeResult(e,a)}`),a}catch(n){const a=n instanceof Error?n.message:"object"==typeof n&&null!==n&&"message"in n?String(n.message):"Unknown error";throw P.error(`${this.logPrefix()} operation failed: op=${e}, message=${a}`),n}}async listRepos(){return(await this.request("/projects?membership=true&per_page=100&order_by=updated_at&sort=desc")).map(e=>({id:e.id,owner:e.namespace.path,name:e.path,fullName:e.path_with_namespace,defaultBranch:e.default_branch,isPrivate:"private"===e.visibility,description:e.description,url:e.web_url,createdAt:e.created_at,updatedAt:e.updated_at}))}async listBranches(e,n){const a=encodeURIComponent(`${e}/${n}`);return(await this.request(`/projects/${a}/repository/branches?per_page=100`)).map(e=>({name:e.name,commit:{sha:e.commit.id,url:""},protected:e.protected}))}async createMergeRequest(e){const n=encodeURIComponent(`${e.owner}/${e.repo}`),a=await this.request(`/projects/${n}/merge_requests`,"POST",{source_branch:e.head,target_branch:e.base,title:e.title,description:e.body||""});return{number:a.iid,title:a.title,body:a.description,state:"opened"===a.state?"open":a.state,url:a.web_url,head:a.source_branch,base:a.target_branch,createdAt:a.created_at,updatedAt:a.updated_at}}async getMergeRequest(e,n,a){const t=encodeURIComponent(`${e}/${n}`),s=await this.request(`/projects/${t}/merge_requests/${a}`);return{number:s.iid,title:s.title,body:s.description,state:"opened"===s.state?"open":s.state,url:s.web_url,head:s.source_branch,base:s.target_branch,createdAt:s.created_at,updatedAt:s.updated_at}}async listMergeRequests(e,n){const a=encodeURIComponent(`${e}/${n}`);return(await this.request(`/projects/${a}/merge_requests?state=opened&per_page=20`)).map(e=>({number:e.iid,title:e.title,body:e.description,state:"opened"===e.state?"open":e.state,url:e.web_url,head:e.source_branch,base:e.target_branch,createdAt:e.created_at,updatedAt:e.updated_at}))}parseProxyMethod(e){const n="string"==typeof e?e.toUpperCase():"GET";if("GET"===n||"POST"===n||"PUT"===n||"PATCH"===n||"DELETE"===n)return n;throw{status:400,message:`Unsupported proxy method: ${String(e)}`}}parseProxyPath(e){if("string"!=typeof e||0===e.length)throw{status:400,message:"Proxy path is required"};if(!e.startsWith("/"))throw{status:400,message:'Proxy path must start with "/"'};if(e.includes("://")||e.includes(".."))throw{status:400,message:"Proxy path contains invalid segments"};if(e.includes("?"))throw{status:400,message:"Proxy path must not contain query string; use payload.query"};return e}buildProxyQueryString(e){if(null==e)return"";if("object"!=typeof e||Array.isArray(e))throw{status:400,message:"Proxy query must be an object"};const n=new URLSearchParams;for(const[a,t]of Object.entries(e))if(null!=t)if(Array.isArray(t))for(const e of t){if("string"!=typeof e&&"number"!=typeof e&&"boolean"!=typeof e)throw{status:400,message:`Proxy query value for "${a}" is invalid`};n.append(a,String(e))}else{if("string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t)throw{status:400,message:`Proxy query value for "${a}" is invalid`};n.append(a,String(t))}return n.toString()}isProxyAllowed(e,n){return _n.some(a=>a.method===e&&a.pattern.test(n))}async requestGitlabApi(e){const n=this.parseProxyMethod(e.method),a=this.parseProxyPath(e.path),t=this.buildProxyQueryString(e.query),s=t.length>0?`${a}?${t}`:a;if(!this.isProxyAllowed(n,a))throw{status:403,message:`Proxy path not allowed: ${n} ${a}`};return"GET"===n?await this.request(s,n):await this.request(s,n,e.body)}}function $n(e){return async(n,a)=>{P.info(`[EVENT HANDLER] create-task: ${n.taskId}, agentType=${n.agentType}, agentId=${n.agentId}`),"task-message"===n.event?await e.workerManager.startWorker(n,"create-task"):P.error(`[EVENT HANDLER] create-task expects task-message, got ${n.event} for task ${n.taskId}`)}}function Dn(e){return async(n,a)=>{P.debug(`[EVENT HANDLER] resume-task: ${n.taskId}, agentSessionId=${n.agentSessionId}`),await e.workerManager.startWorker(n,"resume-task")}}function Pn(e){return async n=>{P.info("[EVENT HANDLER] shutdown-machine received",n),e.requestShutdown("agentrix-app",n.reason)}}function On(e){return async(n,a)=>{P.info(`[EVENT HANDLER] deploy-agent received: taskId=${n.taskId}, draftAgentId=${n.draftAgentId}, targetAgentId=${n.targetAgentId}, sourcePath=${n.sourcePath}`),await e.workerManager.startDeploymentWorker(n)}}function jn(e){return async n=>{P.info(`[GITLAB PROXY] request received: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}, ttlMs=${n.ttlMs}, payloadKeys=${function(e){const n=Object.keys(e||{});return n.length>0?n.join(","):"-"}(n.payload)}`);const a=Date.now(),t=a=>{const t={eventId:n.requestId,requestId:n.requestId,machineId:e.machineId,...a};e.client?(e.client.send("daemon-gitlab-response",t),P.info(`[GITLAB PROXY] response sent: reqId=${n.requestId}, op=${n.operation}, success=${a.success}, executionMs=${a.executionTimeMs}`)):P.error(`[GITLAB PROXY] response dropped: reqId=${n.requestId}, op=${n.operation}, reason=socket-client-unavailable`)};try{const e=await D.getSecretKey();if(!e)return P.warn(`[GITLAB PROXY] machine secret key unavailable: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}`),void t({success:!1,errorCode:"PAT_MISSING",errorMessage:"Machine secret key not available",executionTimeMs:Date.now()-a});const s=Rn(n.gitServerId,e);if(!s)return P.warn(`[GITLAB PROXY] PAT missing: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}`),void t({success:!1,errorCode:"PAT_MISSING",errorMessage:`No PAT configured for git server ${n.gitServerId}`,executionTimeMs:Date.now()-a});const i=n.payload.apiUrl;if(!i)return P.warn(`[GITLAB PROXY] apiUrl missing in payload: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}`),void t({success:!1,errorCode:"PAT_MISSING",errorMessage:"GitLab API URL not provided in request",executionTimeMs:Date.now()-a});P.info(`[GITLAB PROXY] executing: reqId=${n.requestId}, op=${n.operation}, gitServer=${n.gitServerId}, apiHost=${function(e){try{return new URL(e).host}catch{return"invalid-url"}}(i)}`);const o=new Mn(i,s,{requestId:n.requestId,gitServerId:n.gitServerId}),r=await o.executeOperation(n.operation,n.payload);P.info(`[GITLAB PROXY] execution succeeded: reqId=${n.requestId}, op=${n.operation}, summary=${function(e,n){if(Array.isArray(n))return`items=${n.length}`;if(n&&"object"==typeof n){const a=n;return"resolveGitAuthContext"===e?`authMode=${String(a.authMode??"unknown")}, hasPat=${Boolean(a.hasPat)}`:"number"in a||"state"in a?`number=${String(a.number??"-")}, state=${String(a.state??"-")}`:`keys=${Object.keys(a).join(",")||"-"}`}return"type="+typeof n}(n.operation,r)}`),t({success:!0,data:r,executionTimeMs:Date.now()-a})}catch(e){const s=e;let i="GITLAB_CONNECTIVITY_FAILED";401===s.status?i="PAT_INVALID":403===s.status?i="PAT_SCOPE_INSUFFICIENT":404===s.status&&(i="RESOURCE_NOT_FOUND");const o="string"==typeof s.message?s.message:"Unknown error",r="string"==typeof s.detail?function(e,n=300){return e.length<=n?e:`${e.slice(0,n)}...`}(s.detail):void 0,c="number"==typeof s.status?String(s.status):"unknown";P.error(`[GITLAB PROXY] execution failed: reqId=${n.requestId}, op=${n.operation}, errorCode=${i}, status=${c}, message=${o}${r?`, detail=${r}`:""}`),t({success:!1,errorCode:i,errorMessage:o,executionTimeMs:Date.now()-a})}}}const Nn=parseInt(process.env.MAX_WORKSPACE_FILE_SIZE_MB||"100",10);function qn(e,n){if(!e)return;if("string"==typeof n)return void(e.sendMessage?e.sendMessage(n):e.send&&e.send(n));const a=Buffer.from(n);e.sendMessageBinary?e.sendMessageBinary(a):e.send&&e.send(a)}class Un{client;machineId;iceServers=[];sessions=new Map;rtcModule;peerConstructor;constructor(e,n){this.client=e,this.machineId=n;const a=Ie(import.meta.url);var t;this.rtcModule=a("node-datachannel"),this.peerConstructor=(t=this.rtcModule).RTCPeerConnection||t.PeerConnection||t.RTCConnection||t.PeerConnection,this.rtcModule.setDebugLevel?.("warning")}registerHandlers(){this.peerConstructor?(this.client.onLifecycle("connect",()=>{this.requestIceServers()}),this.client.onEvent("rtc-ice-servers-response",e=>this.handleIceServersResponse(e)),this.client.onEvent("machine-rtc-request",e=>this.handleRtcRequest(e)),this.client.onEvent("rtc-signal",e=>this.handleRtcSignal(e))):P.warn("[RTC] node-datachannel RTCPeerConnection not available")}shutdown(){this.sessions.forEach(e=>{e.peerConnection.close?.()}),this.sessions.clear()}requestIceServers(){this.client.send("rtc-ice-servers-request",{eventId:d()})}handleIceServersResponse(e){this.iceServers=function(e){const n=[];return e.forEach(e=>{Array.isArray(e.urls)?n.push(...e.urls):n.push(e.urls)}),n}(e.iceServers),P.info(`[RTC] Loaded ${this.iceServers.length} ICE servers`)}handleRtcRequest(e){if(!this.peerConstructor)return;const n=e.userId;if(!n)return void P.warn("[RTC] machine-rtc-request missing userId");const a=e.workspaceUserId||n,t=e.taskId;if(this.sessions.has(e.sessionId))return void this.sendMachineRtcResponse(e.sessionId,n,!0);const s=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers}),i={sessionId:e.sessionId,userId:n,workspaceUserId:a,allowedTaskId:t||void 0,peerConnection:s,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]};this.sessions.set(e.sessionId,i),this.registerPeerHandlers(i),this.sendMachineRtcResponse(e.sessionId,n,!0)}sendMachineRtcResponse(e,n,a,t){this.client.send("machine-rtc-response",{eventId:d(),machineId:this.machineId,sessionId:e,accepted:a,reason:t,userId:n,capabilities:{dataChannel:!0}})}handleRtcSignal(e){if(!this.peerConstructor)return;if("app"!==e.from)return;const n=e.userId;if(!n)return void P.warn("[RTC] rtc-signal missing userId");const a=e.workspaceUserId||n,t=e.taskId;let s=this.sessions.get(e.sessionId);if(!s){const i=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers});s={sessionId:e.sessionId,userId:n,workspaceUserId:a,allowedTaskId:t||void 0,peerConnection:i,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]},this.sessions.set(e.sessionId,s),this.registerPeerHandlers(s)}try{this.applyRemoteSignal(s,e.signal)}catch(e){P.warn("[RTC] Failed to apply remote signal",e)}}registerPeerHandlers(e){const{peerConnection:n}=e;n.onStateChange?.(n=>{P.info(`[RTC] Peer state (${e.sessionId}): ${n}`)}),n.onGatheringStateChange?.(n=>{P.info(`[RTC] ICE gathering (${e.sessionId}): ${n}`)}),n.onLocalDescription?.((n,a)=>{const t=function(e,n){return e&&"object"==typeof e&&"string"==typeof e.sdp?{sdp:e.sdp,type:e.type||n}:{sdp:String(e||""),type:n}}(n,a);this.client.send("rtc-signal",{eventId:d(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:t,userId:e.userId})}),n.onLocalCandidate?.((n,a,t)=>{const s=function(e,n,a){return"string"==typeof e?{candidate:e,sdpMid:n||"0",sdpMLineIndex:a??0}:e&&"string"==typeof e.candidate?{candidate:e.candidate,sdpMid:e.sdpMid||e.mid||n||"0",sdpMLineIndex:"number"==typeof e.sdpMLineIndex?e.sdpMLineIndex:a??0}:null}(n,a,t);s&&this.client.send("rtc-signal",{eventId:d(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:{candidate:s},userId:e.userId})}),n.onDataChannel?.(n=>{e.dataChannel=n,this.registerDataChannel(e,n)})}registerDataChannel(e,n){n.onOpen?.(()=>{P.info(`[RTC] Data channel open (${e.sessionId})`),e.lastActivity=Date.now(),qn(n,JSON.stringify({v:1,type:"control.ready",channel:"control",requestId:`req-${e.sessionId}`,streamId:0,timestamp:(new Date).toISOString(),payload:{ok:!0}}))}),n.onClosed?.(()=>{P.warn(`[RTC] Data channel closed (${e.sessionId})`),e.peerConnection.close?.(),this.sessions.delete(e.sessionId)}),n.onError?.(n=>{P.error(`[RTC] Data channel error (${e.sessionId})`,n)}),n.onMessage?.(n=>{e.lastActivity=Date.now(),this.handleDataChannelMessage(e,n)})}handleDataChannelMessage(e,n){if(Buffer.isBuffer(n)||n instanceof Uint8Array){try{m(new Uint8Array(n))}catch(e){P.warn("[RTC] Received binary payload without handler")}return}let a=null;if("string"==typeof n?a=n:n&&"string"==typeof n.text&&(a=n.text),!a)return;let t=null;try{t=JSON.parse(a)}catch(e){return void P.warn("[RTC] Non-JSON message",a)}t&&"string"==typeof t.type&&"file.request"===t.type&&this.handleFileRequest(e,t).catch(e=>{P.error("[RTC] Failed to handle file request",e)})}async handleFileRequest(e,n){const a=n.payload;if(!a)return;if(a.userId!==e.workspaceUserId)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),error:{code:"unauthorized",message:"Unauthorized workspace access"}});if(e.allowedTaskId&&a.taskId!==e.allowedTaskId)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),error:{code:"unauthorized",message:"Unauthorized task access"}});const t=(s=a.userId,i=a.taskId,o=a.relativePath,D.resolveWorkspaceFilePath(s,i,o));var s,i,o;if(!ne.existsSync(t))return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),error:{code:"file_not_found",message:"File or directory not found"}});const r=await ne.promises.stat(t);if(!function(e,n){return!n||e.mtime.toISOString()!==n}(r,a.ifModifiedSince))return void this.sendControl(e,{v:1,type:"file.not_modified",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString()});if(r.isDirectory()||"directory"===a.entryType){const a=await ne.promises.readdir(t,{withFileTypes:!0}),s={entries:await Promise.all(a.map(async e=>{const n=me.join(t,e.name),a=await ne.promises.stat(n);return{name:e.name,type:e.isDirectory()?"directory":"file",size:a.size,modifiedAt:a.mtime.toISOString()}})),modifiedAt:r.mtime.toISOString()};return void this.sendControl(e,{v:1,type:"file.dir",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),payload:s})}const c=1024*(a.maxFileSizeMB??Nn)*1024;if(r.size>c)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),error:{code:"file_too_large",message:"File exceeds size limit"}});const p=Sn.lookup(t)||"application/octet-stream",l={size:r.size,mimeType:"string"==typeof p?p:"application/octet-stream",modifiedAt:r.mtime.toISOString()};this.sendControl(e,{v:1,type:"file.meta",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),payload:l}),await this.sendFileChunks(e,n.streamId,t),this.sendControl(e,{v:1,type:"file.end",channel:"file",requestId:n.requestId,streamId:n.streamId,timestamp:(new Date).toISOString(),payload:{size:r.size}})}async sendFileChunks(e,n,a){const t=e.dataChannel;if(!t)return;const s=ne.createReadStream(a,{highWaterMark:65536});let i=0;await new Promise((e,a)=>{s.on("data",e=>{const a=g.Binary|(0===i?g.Start:0),s=Buffer.isBuffer(e)?e:Buffer.from(e),o=new Uint8Array(s.buffer,s.byteOffset,s.byteLength),r=h({streamId:n,seq:i,flags:a,payloadLength:o.length},o);qn(t,r),i+=1}),s.on("end",()=>{if(i>0){const e=h({streamId:n,seq:i,flags:g.End|g.Binary,payloadLength:0},new Uint8Array);qn(t,e)}e()}),s.on("error",e=>a(e))})}sendControl(e,n){const a=e.dataChannel;a&&qn(a,JSON.stringify(n))}applyRemoteSignal(e,n){const{peerConnection:a}=e;if(n&&n.sdp&&n.type)return a.setRemoteDescription?.(n.sdp,n.type),e.remoteDescriptionSet=!0,e.pendingCandidates?.forEach(e=>{try{a.addRemoteCandidate?.(e.candidate,e.mid)}catch(e){P.warn("[RTC] Failed to add queued candidate",e)}}),void(e.pendingCandidates=[]);if(n&&n.candidate){const t=n.candidate,s="string"==typeof t?t:t&&"string"==typeof t.candidate?t.candidate:null,i=n.sdpMid||t?.sdpMid||t?.mid||"0";if(s){if(!e.remoteDescriptionSet)return void e.pendingCandidates?.push({candidate:s,mid:i});a.addRemoteCandidate?.(s,i)}}}}class Gn{client;context;rtcManager;constructor(e,n,a){const{machineId:t,...s}=e;this.client=new gn(s),this.context={machineId:t,workerManager:n,requestShutdown:a.requestShutdown,client:this.client},this.rtcManager=new Un(this.client,t),this.initHandlers(),this.rtcManager.registerHandlers()}connect(){return new Promise((e,n)=>{const a=setTimeout(()=>{n(new Error("Machine connection timeout after 30 seconds"))},3e4);this.client.onLifecycle("connect",()=>{clearTimeout(a),e()}),this.client.onLifecycle("connect_error",e=>{clearTimeout(a),n(e)}),this.client.connect()})}async disconnect(){this.client.connected&&await this.client.flush(5e3).catch(()=>{}),this.rtcManager.shutdown(),this.client.disconnect()}initHandlers(){const e={"create-task":$n(n=this.context),"resume-task":Dn(n),"deploy-agent":On(n),"shutdown-machine":Pn(n),"workspace-file-request":Cn({client:n.client}),"daemon-gitlab-request":jn(n)};var n;this.client.onEventWithAck("create-task",e["create-task"]),this.client.onEventWithAck("resume-task",e["resume-task"]),this.client.onEventWithAck("deploy-agent",e["deploy-agent"]),this.client.onEvent("shutdown-machine",e["shutdown-machine"]),this.client.onEvent("workspace-file-request",e["workspace-file-request"]),this.client.onEvent("daemon-gitlab-request",e["daemon-gitlab-request"])}}let Ln=null;let Fn=!1;async function Wn(){if(Fn)P.info("[caffeinate] Already stopping, skipping");else if(Ln&&!Ln.killed){Fn=!0,P.info(`[caffeinate] Stopping caffeinate process PID ${Ln.pid}`);try{Ln.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),Ln&&!Ln.killed&&Ln.kill("SIGKILL"),Ln=null,Fn=!1}catch(e){P.info("[caffeinate] Error stopping caffeinate:",e),Fn=!1}}}let Hn=!1;async function zn(){try{const e=await Ee(),n=[];for(const a of e){const e=a.cmd||"",t=a.name||"";if(!(t.includes("agentrix")||"node"===t&&(e.includes("agentrix-cli")||e.includes("dist/index.mjs"))||("MainThread"===t||t.includes("MainThread"))&&(e.includes("agentrix-cli")||e.includes("dist/index.mjs")||e.includes("agentrix.mjs"))||e.includes("agentrix.mjs")||e.includes("agentrix-cli")||e.includes("tsx")&&e.includes("src/index.ts")&&e.includes("agentrix-cli")))continue;if(a.pid===process.pid||a.pid===process.ppid)continue;let s="unknown";e.includes(" worker")?s="worker":e.includes(" upgrade-daemon")?s="upgrade-daemon":e.includes(" daemon")?s="daemon":e.includes("doctor")&&(s="doctor"),n.push({pid:a.pid,command:e||t,type:s})}return n}catch(e){return[]}}function Bn(e){try{return{available:!0,path:Te(`which ${e}`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}}catch{return{available:!1}}}function Kn(){const e=Ae(),n=function(){const e=Bn("git"),n=Bn("claude"),a=Bn("codex");return[{name:"git",installed:e.available,required:!0,description:"Version control system (required for all tasks)",installCommand:"https://git-scm.com/downloads",path:e.path},{name:"claude",installed:n.available,required:!0,description:"Claude Code CLI (required for most features)",installCommand:"npm install -g @anthropic-ai/claude-code",path:n.path},{name:"codex",installed:a.available,required:!1,description:"Codex CLI (optional, for Codex tasks)",installCommand:"npm install -g @codex-ai/codex-cli",path:a.path}]}(),a=function(e){if("macos"===e){const e=Bn("rg");return[{name:"ripgrep",installed:e.available,required:!0,description:"Fast code search tool (required by sandbox)",installCommand:"brew install ripgrep",path:e.path}]}if("linux"===e){const e=Bn("bwrap"),n=Bn("socat");return[{name:"bubblewrap",installed:e.available,required:!0,description:"Sandboxing tool for Linux",installCommand:"sudo apt install bubblewrap # Debian/Ubuntu\nsudo yum install bubblewrap # RHEL/CentOS\nsudo pacman -S bubblewrap # Arch",path:e.path},{name:"socat",installed:n.available,required:!0,description:"Socket communication tool (required by sandbox)",installCommand:"sudo apt install socat # Debian/Ubuntu\nsudo yum install socat # RHEL/CentOS\nsudo pacman -S socat # Arch",path:n.path}]}return[]}(e),t=n.filter(e=>e.required&&!e.installed),s=a.filter(e=>e.required&&!e.installed);return{cli:n,sandbox:a,allSatisfied:0===t.length&&0===s.length,missingSandbox:s,missingCli:t}}function Vn(){return{PWD:process.env.PWD,AGENTRIX_HOME_DIR:process.env.AGENTRIX_HOME_DIR,AGENTRIX_SERVER_URL:process.env.AGENTRIX_SERVER_URL,AGENTRIX_PROJECT_ROOT:process.env.AGENTRIX_PROJECT_ROOT,DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING:process.env.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING,NODE_ENV:process.env.NODE_ENV,DEBUG:process.env.DEBUG,workingDirectory:process.cwd(),processArgv:process.argv,agentrixDir:D.agentrixHomeDir,serverUrl:D.serverUrl,logsDir:D.getStatePaths().logsDir,processPid:process.pid,nodeVersion:process.version,platform:process.platform,arch:process.arch,user:process.env.USER,home:process.env.HOME,shell:process.env.SHELL,terminal:process.env.TERM}}async function Xn(e){if(e||(e="all"),console.log(s.bold.cyan("\n🩺 Agentrix CLI Doctor\n")),"all"===e){console.log(s.bold("📋 Basic Information")),console.log(`Agentrix CLI Version: ${s.green(j.version)}`),console.log(`Platform: ${s.green(process.platform)} ${process.arch}`),console.log(`Node.js Version: ${s.green(process.version)}`),console.log(""),console.log(s.bold("🔧 Daemon Spawn Diagnostics"));const e=O(),n=he(e,"bin","agentrix.mjs"),a=he(e,"dist","index.mjs");console.log(`Project Root: ${s.blue(e)}`),console.log(`Wrapper Script: ${s.blue(n)}`),console.log(`CLI Entrypoint: ${s.blue(a)}`),console.log(`Wrapper Exists: ${te(n)?s.green("✓ Yes"):s.red("❌ No")}`),console.log(`CLI Exists: ${te(a)?s.green("✓ Yes"):s.red("❌ No")}`),console.log(""),console.log(s.bold("⚙️ Configuration")),console.log(`Agentrix Home: ${s.blue(D.agentrixHomeDir)}`),console.log(`Server URL: ${s.blue(D.serverUrl)}`),console.log(`Logs Dir: ${s.blue(D.getStatePaths().logsDir)}`),console.log(s.bold("\n🌍 Environment Variables"));const t=Vn();console.log(`AGENTRIX_HOME_DIR: ${t.AGENTRIX_HOME_DIR?s.green(t.AGENTRIX_HOME_DIR):s.gray("not set")}`),console.log(`AGENTRIX_SERVER_URL: ${t.AGENTRIX_SERVER_URL?s.green(t.AGENTRIX_SERVER_URL):s.gray("not set")}`),console.log(`DANGEROUSLY_LOG_TO_SERVER: ${t.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING?s.yellow("ENABLED"):s.gray("not set")}`),console.log(`DEBUG: ${t.DEBUG?s.green(t.DEBUG):s.gray("not set")}`),console.log(`NODE_ENV: ${t.NODE_ENV?s.green(t.NODE_ENV):s.gray("not set")}`),console.log(s.bold("\n🔐 Authentication"));try{await D.readCredentials()?console.log(s.green("✓ Authenticated (credentials found)")):console.log(s.yellow("⚠️ Not authenticated (no credentials)"))}catch(e){console.log(s.red("❌ Error reading credentials"))}!function(e=!1){const n=Kn(),a=Ae();console.log(s.bold("\n🔧 CLI Dependencies"));for(const a of n.cli)if(a.installed)console.log(s.green(`✓ ${a.name}`),s.gray(`- ${a.description}`)),e&&a.path&&console.log(s.gray(` Location: ${a.path}`));else{const e=a.required?s.red("❌"):s.yellow("⚠️");console.log(`${e} ${a.name}`,s.gray(`- ${a.description}`)),a.installCommand&&console.log(s.blue(` Install: ${a.installCommand}`))}if(n.sandbox.length>0){console.log(s.bold("\n🔒 Sandbox Dependencies")),console.log(s.gray(`Platform: ${a}`));for(const a of n.sandbox)a.installed?(console.log(s.green(`✓ ${a.name}`),s.gray(`- ${a.description}`)),e&&a.path&&console.log(s.gray(` Location: ${a.path}`))):(console.log(s.red(`❌ ${a.name}`),s.gray(`- ${a.description}`)),a.installCommand&&console.log(s.blue(` Install: ${a.installCommand}`)))}else console.log(s.bold("\n🔒 Sandbox Dependencies")),console.log(s.yellow(`⚠️ Platform ${a} not supported - sandbox will be disabled`));if(n.allSatisfied)return console.log(s.bold.green("\n✓ All required dependencies are installed")),!0;{console.log(s.bold.red("\n⚠️ Missing Required Dependencies"));const e=[...n.missingCli,...n.missingSandbox];for(const n of e)console.log(s.red(` • ${n.name}`));console.log(s.yellow("\nPlease install missing dependencies before starting the daemon."))}}(!0)}console.log(s.bold("\n🤖 Daemon Status"));try{const n=await cn(),a=await D.readDaemonState();if(n&&a?(console.log(s.green("✓ Daemon is running")),console.log(` PID: ${a.pid}`),console.log(` Started: ${new Date(a.startTime).toLocaleString()}`),console.log(` CLI Version: ${a.cliVersion}`),a.port&&console.log(` HTTP Port: ${a.port}`)):a&&!n?console.log(s.yellow("⚠️ Daemon state exists but process not running (stale)")):console.log(s.red("❌ Daemon is not running")),a){console.log(s.bold("\n📄 Daemon State:"));const e=D.getStatePaths();console.log(s.blue(`Location: ${e.daemonStateFile}`)),console.log(s.gray(JSON.stringify(a,null,2)))}const t=await zn();if(t.length>0){console.log(s.bold("\n🔍 All Agentrix CLI Processes"));const e=t.reduce((e,n)=>(e[n.type]||(e[n.type]=[]),e[n.type].push(n),e),{});Object.entries(e).forEach(([e,n])=>{console.log(s.blue(`\n${{daemon:"🤖 Daemon","upgrade-daemon":"🔄 Upgrade Daemon",worker:"🔗 Workers",doctor:"🩺 Doctor",unknown:"❓ Unknown"}[e]||e}:`)),n.forEach(({pid:n,command:a})=>{const t=e.startsWith("dev")?s.cyan:e.includes("daemon")?s.blue:s.gray;console.log(` ${t(`PID ${n}`)}: ${s.gray(a)}`)})})}else console.log(s.red("❌ No agentrix processes found"));"all"===e&&t.length>1&&(console.log(s.bold("\n💡 Process Management")),console.log(s.gray("To clean up runaway processes: agentrix killall")))}catch(e){console.log(s.red("❌ Error checking daemon status"))}}let Yn=null;async function Jn(){const e=aa(),n=function(e){try{return JSON.stringify(e)}catch{return""}}(e);if(Yn&&Yn.expiresAt>Date.now()&&Yn.overridesSignature===n)return Yn.openers;const a=Zn(e),t=[];for(const e of a){const n=e.isSupported();n&&t.push({id:e.id,label:e.label,kind:e.kind,method:e.method,urlTemplate:e.urlTemplate,supported:n})}return Yn={expiresAt:Date.now()+6048e5,openers:t,overridesSignature:n},t}function Qn(e){const n=process.platform;if("darwin"===n)return function(e){const n=ea(e),a=[];if(n){const e=ca(n);a.push("-e",`set defaultLocation to POSIX file "${e}"`,"-e","set chosenFolder to choose folder default location defaultLocation")}else a.push("-e","set chosenFolder to choose folder");return a.push("-e","POSIX path of chosenFolder"),na(oa("osascript",a,{captureOutput:!0}))}(e);if("win32"===n)return function(e){const n=ia("powershell")?"powershell":ia("pwsh")?"pwsh":null;if(!n)throw new Error("PowerShell is required to pick a directory");const a=ea(e),t=["Add-Type -AssemblyName System.Windows.Forms;","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;",a?`$dialog.SelectedPath = '${ra(a)}';`:"","$null = $dialog.ShowDialog();","$dialog.SelectedPath;"].filter(Boolean).join(" ");return na(oa(n,"powershell"===n?["-NoProfile","-STA","-Command",t]:["-NoProfile","-Sta","-Command",t],{captureOutput:!0}))}(e);if("linux"===n)return function(e){const n=ea(e);if(ia("zenity")){const e=["--file-selection","--directory","--title=Select Folder"];if(n){const a=n.endsWith("/")?n:`${n}/`;e.push(`--filename=${a}`)}return na(oa("zenity",e,{captureOutput:!0}))}if(ia("kdialog")){const e=["--getexistingdirectory"];return n&&e.push(n),na(oa("kdialog",e,{captureOutput:!0}))}throw new Error("No supported directory picker is available")}(e);throw new Error("Directory picker is not supported on this platform")}function Zn(e){const n=process.platform,a=["Visual Studio Code","Visual Studio Code - Insiders"],t=["Cursor"],s=["IntelliJ IDEA","IntelliJ IDEA CE","IntelliJ IDEA Ultimate"],i=["WebStorm"],o=["PyCharm","PyCharm CE","PyCharm Professional"],r=[{id:"vscode",label:"VS Code",kind:"editor",method:"scheme",urlTemplate:"vscode://file/{path}?windowId=_blank",scheme:"vscode",macAppNames:a,isSupported:()=>ta("vscode",n,a)},{id:"cursor",label:"Cursor",kind:"editor",method:"scheme",urlTemplate:"cursor://file/{path}?windowId=_blank",scheme:"cursor",macAppNames:t,isSupported:()=>ta("cursor",n,t)},{id:"idea",label:"IntelliJ IDEA",kind:"ide",method:"scheme",urlTemplate:"idea://open?file={path}&newWindow=true",scheme:"idea",macAppNames:s,isSupported:()=>ta("idea",n,s)},{id:"pycharm",label:"PyCharm",kind:"ide",method:"scheme",urlTemplate:"pycharm://open?file={path}&newWindow=true",scheme:"pycharm",macAppNames:o,isSupported:()=>ta("pycharm",n,o)},{id:"webstorm",label:"WebStorm",kind:"ide",method:"scheme",urlTemplate:"webstorm://open?file={path}&newWindow=true",scheme:"webstorm",macAppNames:i,isSupported:()=>ta("webstorm",n,i)},{id:"file-manager",label:"darwin"===n?"Finder":"win32"===n?"Explorer":"Files",kind:"file-manager",method:"cli",isSupported:()=>function(e){return"darwin"===e?ia("open"):"win32"===e||"linux"===e&&(ia("xdg-open")||ia("gio"))}(n),open:e=>function(e,n){if("darwin"!==n){if("win32"!==n){if("linux"===n)return ia("xdg-open")?void oa("xdg-open",[e]):void oa("gio",["open",e]);throw new Error("File manager open is not supported on this platform")}oa("explorer",[e])}else oa("open",[e])}(e,n)},{id:"open-with",label:"Open With...",kind:"system",method:"cli",isSupported:()=>function(e){return"darwin"===e?ia("osascript"):"win32"===e?ia("powershell")||ia("pwsh"):"linux"===e&&ia("gio")}(n),open:e=>function(e,n){if("darwin"!==n)if("win32"!==n){if("linux"!==n)throw new Error("Open With is not supported on this platform");oa("gio",["open","--ask",e])}else oa(ia("powershell")?"powershell":"pwsh",["-NoProfile","-Command",`Start-Process -Verb OpenAs -FilePath '${ra(e)}'`]);else if(null===oa("osascript",["-e",`set targetPath to POSIX file "${ca(e)}"`,"-e","set appChoice to choose application","-e","tell appChoice to open targetPath"],{captureOutput:!0}))throw new Error("No application selected")}(e,n)}];return function(e,n,a){const t=a??aa();return e.map(e=>{const a=t[e.id];if(!a)return e;if(!1===a.enabled)return{...e,isSupported:()=>!1};const s={...e,label:a.label??e.label,method:a.method??e.method,urlTemplate:a.urlTemplate??e.urlTemplate};if(a.command){const t=function(e){return e?Array.isArray(e)?e:[e]:[]}(a.appName??e.macAppNames);s.method="cli",s.isSupported=()=>function(e,n,a){return"darwin"===a&&n.length>0?n.some(e=>sa(e)):ge.isAbsolute(e)||e.includes(ge.sep)?te(e):ia(e)}(a.command,t,n),s.open=e=>function(e,n,a){if(!oa(e,(n&&n.length>0?n:["{path}"]).map(e=>e.split("{path}").join(a))))throw new Error(`Command failed: ${e}`)}(a.command,a.args,e)}return s})}(r,n,e)}function ea(e){if(!e)return;const n=e.replace(/^~(?=$|[\\/])/,X.homedir());if(te(n)){try{if(!ie(n).isDirectory())return}catch{return}return n}}function na(e){if(!e)return null;return e.trim()||null}function aa(){try{const e=D.readSettings();if(!e||"object"!=typeof e)return{};const n=e.openersOverrides;return n&&"object"==typeof n?n:{}}catch(e){return P.warn("[OPENERS] Failed to read opener overrides",e),{}}}function ta(e,n,a){return"darwin"===n?function(e,n){if(ia("mdfind")){const n=oa("mdfind",[`kMDItemCFBundleURLSchemes == '${e}'`],{captureOutput:!0});if(n&&n.trim())return!0}if(ia("plutil")){const n=[ge.join(X.homedir(),"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"),"/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"];for(const a of n){if(!te(a))continue;const n=oa("plutil",["-extract","LSHandlers","json","-o","-",a],{captureOutput:!0});if(n)try{const a=JSON.parse(n);if(Array.isArray(a)&&a.some(n=>n.LSHandlerURLScheme?.toLowerCase()===e.toLowerCase()))return!0}catch(e){P.debug("[OPENERS] Failed to parse LaunchServices handlers",e)}}}return!!(n&&n.length>0)&&n.some(e=>sa(e))}(e,a):"win32"===n?function(e){return ia("reg")&&(Boolean(oa("reg",["query",`HKCU\\Software\\Classes\\${e}`]))||Boolean(oa("reg",["query",`HKCR\\${e}`])))}(e):"linux"===n&&function(e){if(ia("xdg-settings")){const n=oa("xdg-settings",["get","default-url-scheme-handler",e],{captureOutput:!0});if(n&&n.trim()&&"null"!==n.trim())return!0}if(ia("gio")){const n=oa("gio",["mime",`x-scheme-handler/${e}`],{captureOutput:!0});if(n&&/Default application/.test(n))return!0}return!1}(e)}function sa(e){return"darwin"===process.platform&&Boolean(oa("open",["-Ra",e]))}function ia(e){return"win32"===process.platform?Boolean(oa("where",[e])):Boolean(oa("sh",["-c",`command -v ${e}`]))}function oa(e,n,a){const t=Pe(e,n,{encoding:a?.captureOutput?"utf8":void 0,stdio:a?.captureOutput?"pipe":"ignore",windowsHide:!0});if(0!==t.status){if(a?.captureOutput){const a="string"==typeof t.stderr?t.stderr.trim():"";a&&P.warn(`[OPENERS] Command failed: ${e} ${n.join(" ")}: ${a}`)}return null}return a?.captureOutput?t.stdout:"ok"}function ra(e){return e.replace(/'/g,"''")}function ca(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function pa(e,n){if(n){const a=e.startsWith(n)?e.slice(n.length).replace(/^\//,""):xe(e);return he(n,"versions",a)}let a=fe(e),t=0;for(;t<10;){if(te(he(a,"agent.json"))){const n=e.slice(a.length).replace(/^\//,"");return he(a,"versions",n)}const n=fe(a);if(n===a)break;a=n,t++}const s=fe(e),i=xe(e);return he(s,`.${i}.version`)}function la(e,n){const a=pa(e,n);if(!te(a))return"0.0.0";try{return se(a,"utf-8").trim()}catch(e){return"0.0.0"}}function da(e,a,t){try{const s=pa(e,t),i=fe(s);if(!te(i)){const{mkdirSync:e}=n("node:fs");e(i,{recursive:!0})}oe(s,a,"utf-8")}catch(e){}}function ua(e,n){const a=e.split(".").map(Number),t=n.split(".").map(Number);for(let e=0;e<3;e++){const n=a[e]||0,s=t[e]||0;if(n>s)return 1;if(n<s)return-1}return 0}function ma(e,n,a){const t=la(e,a),s=ua(n.metadata.version,t);if(!te(e)){const t=fe(e);if(!te(t)){const{mkdirSync:e}=ae;e(t,{recursive:!0})}return oe(e,n.content,"utf-8"),da(e,n.metadata.version,a),{updated:!0,reason:"created"}}if(s<=0)return{updated:!1,reason:"up-to-date"};switch(n.metadata.updateStrategy){case"overwrite":return oe(e,n.content,"utf-8"),da(e,n.metadata.version,a),{updated:!0,reason:"overwritten"};case"create-only":return{updated:!1,reason:"create-only"};case"notify-user":return{updated:!1,reason:"requires-user-approval"};default:return{updated:!1,reason:"unknown-strategy"}}}function ga(e){te(e)||re(e,{recursive:!0})}function ha(e){return e.split("\\").join("/")}function fa(e){const n={};if(!te(e))return n;const a=t=>{const s=ce(t).sort();for(const i of s){const s=he(t,i);if(ie(s).isDirectory()){a(s);continue}if("versions.json"===i)continue;const o=ha(ve(e,s));n[o]=se(s,"utf-8")}};return a(e),n}function xa(){const e=fe(Ne(import.meta.url)),n=[he(e,"template"),he(e,"companion","template")];for(const e of n)if(te(e))return e;return n[0]}function va(e){const n=xa(),a=he(n,"versions",`${e}.json`);if(!te(a))return{};try{const e=se(a,"utf-8");return JSON.parse(e)}catch(e){return console.warn(`[Companion] Failed to parse ${a}:`,e),{}}}async function ba(e){const n=D.agentrixAgentsHomeDir,a=he(n,"companion"),t=he(a,"claude");ga(t),ga(he(t,"memory")),ga(he(t,"skills"));const{language:s,templates:i}=function(e){const n=function(e){const n=[e,process.env.AGENTRIX_COMPANION_TEMPLATE_LANGUAGE,process.env.LC_ALL,process.env.LC_MESSAGES,process.env.LANG];for(const e of n){if(!e)continue;const n=e.trim().toLowerCase();if(n){if(n.startsWith("zh"))return"zh-Hans";if(n.startsWith("en"))return"en"}}return"en"}(e),a=xa(),t=he(a,"common"),s=he(a,"languages",n),i=fa(t),o=fa(s),r=va("common"),c=va(n),p=[],l={version:"1.0.0",updateStrategy:"create-only"};for(const[e,n]of Object.entries(i))p.push({relativePath:e,content:n,metadata:r[e]||l});for(const[e,n]of Object.entries(o))p.push({relativePath:e,content:n,metadata:c[e]||l});if(0===p.length)throw new Error(`Companion template files are missing under ${a}`);return{language:n,templates:p}}(e?.preferredLanguage),o=[];for(const e of i){const n=ma(he(a,e.relativePath),e,a);if(o.push({path:e.relativePath,updated:n.updated,reason:n.reason}),n.updated){const a="created"===n.reason?"Created":"Updated";console.log(`[Companion] ${a}: ${e.relativePath}`)}}const r=function(e,n){const a=[];for(const t of e){if("notify-user"!==t.metadata.updateStrategy)continue;const e=he(n,t.relativePath);if(!te(e))continue;const s=la(e,n);ua(t.metadata.version,s)>0&&a.push({template:t,targetPath:e,currentVersion:s,newVersion:t.metadata.version})}return a}(i,a);if(r.length>0)try{const e=he(t,"UPGRADES.md"),n=function(e){return`# Upgrades Available\n\nThe following files have new versions available:\n\n${e.map(e=>`- **${e.template.metadata.description||e.template.relativePath}**: v${e.currentVersion} → v${e.newVersion}`).join("\n")}\n\n---\n\n**Shadow's Instructions:**\n\nWhen you detect this file:\n1. Send a reminder to the main companion using \`mcp__agentrix__send_reminder\`\n2. Content: "System upgrade detected. ${e.length} file(s) available."\n3. Reference this file path so main companion can read details\n4. Exit quietly\n\n**Main Companion's Instructions:**\n\nWhen you receive the upgrade reminder:\n1. Choose appropriate timing (don't interrupt user's work)\n2. Read this file to see what's new\n3. For each upgrade, read the corresponding \`.upgrade\` file\n4. Present to user naturally, explain benefits\n5. If user agrees: integrate the new content in your own voice\n6. Update version files using Write tool (create \`.filename.version\` with new version number)\n7. Delete \`.upgrade\` files when done\n8. Delete this file when all upgrades are handled\n`}(r);oe(e,n,"utf-8");for(const e of r){const n=`${e.targetPath}.upgrade`,a=`# Upgrade: ${e.template.metadata.description||e.template.relativePath}\n\n**Current Version**: v${e.currentVersion}\n**New Version**: v${e.newVersion}\n\n---\n\n## New Content\n\n${e.template.content}\n\n---\n\n## Integration Instructions\n\n1. Read the new content above\n2. Compare with your current \`${e.template.relativePath}\`\n3. Integrate the new features in your own voice\n4. Keep your existing customizations\n5. Use Write tool to update \`versions/${e.template.relativePath}\` with content: "${e.newVersion}"\n6. Delete this file when done\n`;oe(n,a,"utf-8")}console.log(`[Companion] Created UPGRADES.md with ${r.length} pending upgrade(s)`),console.log("[Companion] Shadow will notify main companion on next heartbeat")}catch(e){console.warn("[Companion] Failed to create upgrade files (permission denied?):",e instanceof Error?e.message:e),console.warn("[Companion] Upgrade detection will be skipped. Please check sandbox permissions for agents directory.")}return console.log(`[Companion] Language: ${s}`),{agentDir:a,homeDir:t}}function ya(e,n){const a=[],t=ce(e,{withFileTypes:!0});for(const s of t){if(".gitkeep"===s.name)continue;const t=he(e,s.name),i=ie(t),o=ve(n,t);a.push({name:s.name,path:o,size:i.size,modifiedAt:i.mtimeMs,isDirectory:s.isDirectory()}),s.isDirectory()&&a.push(...ya(t,n))}return a}function wa({getChildren:e,stopSession:n,requestShutdown:a,registerSession:t,machineId:s}){return new Promise(i=>{const o=Re({logger:!1});o.setValidatorCompiler($e),o.setSerializerCompiler(De);const r=o.withTypeProvider(),c=e=>{e.header("Access-Control-Allow-Origin","*"),e.header("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.header("Access-Control-Allow-Headers","Content-Type"),e.header("Access-Control-Allow-Private-Network","true")};r.post("/session-started",{schema:{body:_e.object({sessionId:_e.string(),metadata:_e.any()}),response:{200:_e.object({status:_e.literal("ok")})}}},async e=>{const{sessionId:n,metadata:a}=e.body;return P.debug(`[CONTROL SERVER] Session started: ${n}`),t(n,a),{status:"ok"}}),r.options("/ping",async(e,n)=>(c(n),n.send())),r.get("/ping",{schema:{response:{200:_e.object({status:_e.literal("ok"),machineId:_e.string(),timestamp:_e.string()})}}},async(e,n)=>(c(n),{status:"ok",machineId:s,timestamp:(new Date).toISOString()})),r.options("/openers",async(e,n)=>(c(n),n.send())),r.get("/openers",{schema:{response:{200:_e.object({openers:_e.array(_e.object({id:_e.string(),label:_e.string(),kind:_e.enum(["system","file-manager","editor","ide"]),method:_e.enum(["scheme","cli"]),urlTemplate:_e.string().optional(),supported:_e.boolean()}))})}}},async(e,n)=>(c(n),{openers:await Jn()})),r.options("/open",async(e,n)=>(c(n),n.send())),r.options("/pick-directory",async(e,n)=>(c(n),n.send())),r.post("/open",{schema:{body:_e.object({path:_e.string(),openerId:_e.string(),userId:_e.string().optional(),taskId:_e.string().optional()}),response:{200:_e.object({success:_e.boolean(),error:_e.string().optional()})}}},async(e,n)=>{c(n);const{path:a,openerId:t,userId:s,taskId:i}=e.body;return await async function({openerId:e,targetPath:n,userId:a,taskId:t}){const s=Zn(aa()).find(n=>n.id===e);if(!s)return{success:!1,error:"Unknown openerId"};if("cli"!==s.method||!s.open)return{success:!1,error:"Opener is not executable by CLI"};if(!s.isSupported())return{success:!1,error:"Opener is not supported on this system"};let i;try{i=function(e,n,a){const t=ge.resolve(e);if(!ge.isAbsolute(t))throw new Error("Path must be absolute");if(!ie(t).isDirectory())throw new Error("Path must be a directory");if(n&&a){const e=D.getTaskCwd(n,a);if(e&&!function(e,n){const a=ge.relative(n,e);return""===a||!a.startsWith("..")&&!ge.isAbsolute(a)}(t,ge.resolve(e)))throw new Error("Path is outside the task workspace")}return t}(n,a,t)}catch(e){return{success:!1,error:e instanceof Error?e.message:"Invalid path"}}try{return s.open(i),{success:!0}}catch(e){const n=e instanceof Error?e.message:"Failed to open path";return P.warn(`[OPENERS] Failed to open path: ${n}`),{success:!1,error:n}}}({openerId:t,targetPath:a,userId:s,taskId:i})}),r.post("/pick-directory",{schema:{body:_e.object({defaultPath:_e.string().optional()}),response:{200:_e.object({path:_e.string().nullable(),error:_e.string().optional()})}}},async(e,n)=>{c(n);try{return{path:Qn(e.body.defaultPath)??null}}catch(e){return{path:null,error:e instanceof Error?e.message:"Failed to pick directory"}}}),r.post("/companion/ensure",{schema:{body:_e.object({preferredLanguage:_e.enum(["en","zh-Hans"]).nullable().optional()}).optional(),response:{200:_e.object({agentDir:_e.string(),homeDir:_e.string()})}}},async e=>await ba({preferredLanguage:e.body?.preferredLanguage})),r.get("/companion/workspace",{schema:{response:{200:_e.object({files:_e.array(_e.object({name:_e.string(),path:_e.string(),size:_e.number(),modifiedAt:_e.number(),isDirectory:_e.boolean()}))})}}},async()=>{const{homeDir:e}=await ba();return te(e)?{files:ya(e,e)}:{files:[]}}),r.get("/companion/file",{schema:{querystring:_e.object({path:_e.string()}),response:{200:_e.object({content:_e.string()}),404:_e.object({error:_e.string()})}}},async(e,n)=>{const{homeDir:a}=await ba(),t=be(he(a,e.query.path));return t.startsWith(a)&&te(t)?{content:se(t,"utf-8")}:n.code(404).send({error:"File not found"})}),r.put("/companion/file",{schema:{body:_e.object({path:_e.string(),content:_e.string()}),response:{200:_e.object({success:_e.boolean()}),400:_e.object({error:_e.string()})}}},async(e,n)=>{const{homeDir:a}=await ba(),t=be(he(a,e.body.path));return t.startsWith(a)?(re(fe(t),{recursive:!0}),oe(t,e.body.content,"utf-8"),{success:!0}):n.code(400).send({error:"Invalid path"})}),r.get("/companion/config",{schema:{response:{200:_e.object({heartbeatIntervalMs:_e.number(),heartbeatEnabled:_e.boolean()})}}},async()=>{const{homeDir:e}=await ba(),n=he(e,"state.json");let a=9e5,t=!0;if(te(n))try{const e=JSON.parse(se(n,"utf-8"));"number"==typeof e.heartbeatIntervalMs&&(a=e.heartbeatIntervalMs),"boolean"==typeof e.heartbeatEnabled&&(t=e.heartbeatEnabled)}catch{}return{heartbeatIntervalMs:a,heartbeatEnabled:t}}),r.put("/companion/config",{schema:{body:_e.object({heartbeatIntervalMs:_e.number().optional(),heartbeatEnabled:_e.boolean().optional()}),response:{200:_e.object({success:_e.boolean()})}}},async e=>{const{homeDir:n}=await ba(),a=he(n,"state.json");let t={};if(te(a))try{t=JSON.parse(se(a,"utf-8"))}catch{}const{heartbeatIntervalMs:s,heartbeatEnabled:i}=e.body;return void 0!==s&&(t.heartbeatIntervalMs=s),void 0!==i&&(t.heartbeatEnabled=i),re(fe(a),{recursive:!0}),oe(a,JSON.stringify(t,null,2),"utf-8"),{success:!0}}),r.post("/agent/install",{schema:{body:_e.object({agentId:_e.string(),gitUrl:_e.string(),branch:_e.string().optional(),subDir:_e.string().optional()}),response:{200:_e.object({agentDir:_e.string()}),500:_e.object({error:_e.string()})}}},async(e,n)=>{try{return await async function(e){const{agentId:n,gitUrl:a,branch:t,subDir:s}=e,i=he(D.agentrixAgentsHomeDir,n);if(te(i))return{agentDir:i};const o=`${i}.tmp-${Date.now()}`;try{const e=["git","clone","--depth=1"];if(t&&e.push("--branch",t),e.push(a,o),Oe(e.join(" "),{stdio:"pipe"}),s){const e=he(o,s);if(!te(e))throw new Error(`Sub-directory "${s}" not found in cloned repository`);pe(e,i),le(o,{recursive:!0,force:!0})}else pe(o,i);return function(e){const n=[],a=he(e,"claude","plugins");if(te(a))for(const e of ce(a)){const t=he(a,e);ie(t).isDirectory()&&te(he(t,"package.json"))&&n.push(t)}const t=he(e,"claude","hooks");te(t)&&te(he(t,"package.json"))&&n.push(t);for(const e of n)Oe("yarn install --frozen-lockfile",{cwd:e,stdio:"pipe"}),Oe("yarn build",{cwd:e,stdio:"pipe"})}(i),{agentDir:i}}catch(e){throw te(o)&&le(o,{recursive:!0,force:!0}),te(i)&&le(i,{recursive:!0,force:!0}),e}}(e.body)}catch(e){const a=e instanceof Error?e.message:String(e);return n.code(500).send({error:a})}}),r.post("/list",{schema:{response:{200:_e.object({children:_e.array(_e.object({startedBy:_e.string(),taskId:_e.string(),pid:_e.number()}))})}}},async()=>({children:e().filter(e=>void 0!==e.taskId).map(e=>({startedBy:e.startedBy,taskId:e.taskId,pid:e.pid}))})),r.post("/stop-session",{schema:{body:_e.object({sessionId:_e.string()}),response:{200:_e.object({success:_e.boolean()})}}},async e=>{const{sessionId:a}=e.body;return P.debug(`[CONTROL SERVER] Stop session request: ${a}`),{success:n(a)}}),r.post("/stop",{schema:{response:{200:_e.object({status:_e.string()})}}},async()=>(P.debug("[CONTROL SERVER] Stop daemon request received"),setTimeout(()=>{P.debug("[CONTROL SERVER] Triggering daemon shutdown"),a()},50),{status:"stopping"}));const p=e=>new Promise((n,a)=>{o.listen({port:e,host:"127.0.0.1"},(e,t)=>{e?a(e):n(t)})});(async()=>{let e;try{e=await p(30624)}catch(n){const a=n?.code;if("EADDRINUSE"!==a&&"EACCES"!==a)throw P.info("[CONTROL SERVER] Failed to start:",n),n;P.info(`[CONTROL SERVER] Port 30624 unavailable (${a??"error"}), falling back to dynamic port`),e=await p(0)}const n=parseInt(e.split(":").pop());P.info(`[CONTROL SERVER] Started on port ${n}`),i({port:n,stop:async()=>{await o.close(),P.info("[CONTROL SERVER] Server stopped")}})})().catch(e=>{throw P.info("[CONTROL SERVER] Failed to start:",e),e})})}function ka(e,n={}){const a=O(),t=he(a,"dist","index.mjs"),s=["--no-warnings","--no-deprecation",t,...e];if(!te(t)){const e=`Entrypoint ${t} does not exist`;throw P.debug(`[SPAWN Agentrix CLI] ${e}`),new Error(e)}return Se(process.execPath,s,n)}const Ia=[{version:1,fileName:"001_init.sql"}];function Sa(e){var n;return function(e,n){const a=new Ue(e),t=new qe;a.pragma("journal_mode = WAL"),function(e){const n=function(){const e=V(Ge(import.meta.url)),n=[K(e,"migrations"),K(process.cwd(),"dist","migrations"),K(process.cwd(),"src","worker","history","migrations")];for(const e of n)if(H(e))return e;throw new Error(`Task history migrations directory not found at ${n[0]}`)}(),a=e.pragma("user_version",{simple:!0}),t=function(e,n){const a=K(e,n);return W(a,"utf8")}(n,Ia[0].fileName);e.exec(t),a<Ia[0].version&&e.pragma(`user_version = ${Ia[0].version}`)}(a);const s=a.prepare("\n INSERT OR IGNORE INTO task_message (\n event_id,\n task_id,\n sender_type,\n sender_id,\n sender_name,\n message,\n created_at\n ) VALUES (\n @eventId,\n @taskId,\n @senderType,\n @senderId,\n @senderName,\n @message,\n @createdAt\n );\n "),i=a.prepare("SELECT local_sequence FROM task_message WHERE event_id = ?"),o=a.prepare("\n INSERT OR IGNORE INTO task_event (\n event_id,\n task_id,\n chat_id,\n sequence,\n event_type,\n event_data,\n created_at\n ) VALUES (\n @eventId,\n @taskId,\n @chatId,\n @sequence,\n @eventType,\n @eventData,\n @createdAt\n );\n "),r=a.prepare("\n UPDATE task_event\n SET sequence = ?\n WHERE event_id = ? AND (sequence IS NULL OR sequence < ?)\n "),c=a.prepare("\n SELECT * FROM task_event\n WHERE sequence > ? AND event_type = 'task-message'\n ORDER BY sequence ASC\n LIMIT ?\n "),p=a.prepare("\n SELECT 1 as has_row\n FROM task_event\n WHERE sequence > ? AND event_type = 'task-message'\n LIMIT 1\n "),l=a.prepare("\n SELECT * FROM task_message\n ORDER BY local_sequence DESC\n LIMIT ?\n "),u=a.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence ASC\n LIMIT ?\n "),m=a.prepare("\n SELECT * FROM task_message\n WHERE local_sequence < ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),g=a.prepare("\n SELECT 1 as has_row\n FROM task_message\n WHERE local_sequence < ?\n LIMIT 1\n "),h=a.prepare("\n SELECT 1 as has_row\n FROM task_message\n WHERE local_sequence > ?\n LIMIT 1\n "),f=a.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),x=a.prepare("\n SELECT agent_id, session_id, last_sequence\n FROM task_agent_session\n "),v=a.prepare("\n INSERT INTO task_agent_session (agent_id, task_id, session_id, last_sequence, updated_at)\n VALUES (?, ?, ?, NULL, ?)\n ON CONFLICT(agent_id) DO UPDATE SET\n task_id = excluded.task_id,\n session_id = excluded.session_id,\n updated_at = excluded.updated_at\n "),b=a.prepare("\n INSERT INTO task_agent_session (agent_id, task_id, session_id, last_sequence, updated_at)\n VALUES (?, ?, '__pending__', ?, ?)\n ON CONFLICT(agent_id) DO UPDATE SET\n task_id = excluded.task_id,\n last_sequence = CASE\n WHEN task_agent_session.last_sequence IS NULL OR task_agent_session.last_sequence < excluded.last_sequence\n THEN excluded.last_sequence\n ELSE task_agent_session.last_sequence\n END,\n updated_at = excluded.updated_at\n ");return{saveMessage:e=>{const a=e.eventId??d(),o=(new Date).toISOString();s.run({eventId:a,taskId:n,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,message:JSON.stringify(e.message),createdAt:o});const r=i.get(a),c=r?.local_sequence??null;return null!==c&&t.emit("message-saved",{eventId:a}),{eventId:a,localSequence:c}},saveTaskEvent:e=>{const n=e.eventId??d(),a=(new Date).toISOString(),t={...e.eventData,eventId:n};return o.run({eventId:n,taskId:e.taskId,chatId:e.chatId,sequence:e.sequence,eventType:e.eventType,eventData:JSON.stringify(t),createdAt:a}),n},updateTaskEventSequence:(e,n)=>{r.run(n,e,n)},pageTaskEventsAfter:(e,n)=>{const a=c.all(e,n).map(Ea),t=a.at(-1)?.sequence??null;return{data:a,hasMore:null!==t&&Boolean(p.get(t))}},getLatestTaskEvent:e=>{if(0===e.length)return null;const n=e.map(()=>"?").join(","),t=a.prepare(`\n SELECT * FROM task_event\n WHERE event_type IN (${n})\n ORDER BY created_at DESC, rowid DESC\n LIMIT 1\n `).get(...e);return t?Ea(t):null},pageRecentMessages:e=>{const n=l.all(e).map(Ta).reverse(),a=n[0]?.localSequence??null;return{data:n,hasMore:!!a&&Boolean(g.get(a))}},pageMessagesAfter:(e,n)=>{const a=u.all(e,n).map(Ta),t=a.at(-1)?.localSequence??null;return{data:a,hasMore:!!t&&Boolean(h.get(t))}},pageMessagesBefore:(e,n)=>{const a=m.all(e,n).map(Ta).reverse(),t=a[0]?.localSequence??null;return{data:a,hasMore:!!t&&Boolean(g.get(t))}},pageRecentMessagesAfter:(e,n)=>{const a=f.all(e,n).map(Ta).reverse(),t=a[0]?.localSequence??null;return{data:a,hasMore:!!t&&Boolean(g.get(t))}},getAgentSessions:()=>{const e=x.all(),n=new Map;for(const a of e)n.set(a.agent_id,a.session_id);return n},getAgentLastSequences:()=>{const e=x.all(),n=new Map;for(const a of e)n.set(a.agent_id,a.last_sequence);return n},upsertAgentSession:(e,a)=>{v.run(e,n,a,(new Date).toISOString())},updateAgentLastSequence:(e,a)=>{b.run(e,n,a,(new Date).toISOString())},on:(e,n)=>{t.on(e,n)},off:(e,n)=>{t.off(e,n)},close:()=>{t.removeAllListeners(),a.close()}}}((n=e.dataDir,K(n,"data.bin")),e.taskId)}function Ta(e){const n=JSON.parse(e.message);return{localSequence:e.local_sequence,eventId:e.event_id,senderType:e.sender_type,senderId:e.sender_id,senderName:e.sender_name,message:n,createdAt:e.created_at}}function Ea(e){const n=JSON.parse(e.event_data);return{eventId:e.event_id,taskId:e.task_id,chatId:e.chat_id,sequence:e.sequence??null,eventType:e.event_type,eventData:n,createdAt:e.created_at}}class Ca{pidToTrackedSession;pidToAwaiter;taskToStartPromise;sandboxPool;constructor(e){this.pidToTrackedSession=new Map,this.pidToAwaiter=new Map,this.taskToStartPromise=new Map,this.sandboxPool=e||null}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}getAliveSessionByTaskId(e){for(const[n,a]of this.pidToTrackedSession.entries())if(a.taskId===e){if(this.isProcessAlive(n))return a;this.pidToTrackedSession.delete(n)}}getCurrentSessions(){return Array.from(this.pidToTrackedSession.values())}getSessionByPid(e){return this.pidToTrackedSession.get(e)}registerTaskWorker(e,n){const a=n.pid;if(!a)return void P.warn(`[SESSION] Missing PID for task ${e}`);P.info(`[SESSION] Registered task ${e}, PID: ${a}`);const t=this.pidToTrackedSession.get(a);if(t&&t.taskId===e){const e=this.pidToAwaiter.get(a);e&&(this.pidToAwaiter.delete(a),e(t))}else if(!t){const n={startedBy:"cli",taskId:e,pid:a};this.pidToTrackedSession.set(a,n)}}async decryptTaskMessage(e){if(!e.dataEncryptionKey)return;const n=await D.getSecretKey();if(!n)return;const a=l(p(e.dataEncryptionKey),n);if(!a)return void P.warn("[SESSION] Failed to decrypt data encryption key");if(e.dataEncryptionKey=i(a),"task-message"!==e.event)return;const t=e.eventData;if(!t.encryptedMessage)return;const s=f(t.encryptedMessage,a);s?e.eventData={...t,message:s,encryptedMessage:void 0}:P.warn("[SESSION] Failed to decrypt task message")}persistCreateTaskStart(e){const n=Sa({dataDir:D.resolveDataDir(e.userId,e.taskId),taskId:e.taskId});try{const a=e.eventData;n.saveTaskEvent({eventType:e.event,eventId:a.eventId,eventData:a,taskId:e.taskId,chatId:e.chatId,sequence:a.sequence??0}),a.message&&n.saveMessage({eventId:a.eventId,message:a.message,senderType:a.senderType,senderId:a.senderId,senderName:a.senderName})}finally{n.close()}}persistResumeTaskStart(e){const n=Sa({dataDir:D.resolveDataDir(e.userId,e.taskId),taskId:e.taskId}),a=e.eventData.sequence;if(null==a)throw new Error(`Missing resume sequence for task ${e.taskId}`);try{const t=e.eventData;n.saveTaskEvent({eventType:e.event,eventId:t.eventId,eventData:t,taskId:e.taskId,chatId:e.chatId,sequence:a}),t.message&&n.saveMessage({eventId:t.eventId,message:t.message,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName})}finally{n.close()}}trackWorkerProcess(e,n){const a={startedBy:"daemon",pid:n.pid,childProcess:n,taskId:e.taskId};this.pidToTrackedSession.set(n.pid,a),n.on("exit",(a,t)=>{this.pidToTrackedSession.delete(n.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId)}),n.on("error",a=>{this.pidToTrackedSession.delete(n.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId)})}async startWorker(e,n){const a={eventId:d(),status:"success",opCode:e.eventId};await this.decryptTaskMessage(e),D.writeTaskInput(e),"create-task"===n?this.persistCreateTaskStart(e):this.persistResumeTaskStart(e);const t=this.taskToStartPromise.get(e.taskId);if(t)return P.info(`[SESSION] Task ${e.taskId} is already starting, skip duplicate ${n}`),t;const s=this.startWorkerInternal(e,n,a).finally(()=>{this.taskToStartPromise.get(e.taskId)===s&&this.taskToStartPromise.delete(e.taskId)});return this.taskToStartPromise.set(e.taskId,s),s}async startWorkerInternal(e,n,a){const t=this.getAliveSessionByTaskId(e.taskId);if(t)return P.info(`[SESSION] Task ${e.taskId} already has worker PID ${t.pid}, skip duplicate ${n}`),a.message=`Worker already running (PID ${t.pid})`,a;const s=D.resolveProjectCWD(e.userCwd,e.userId,e.taskId),i=["worker","--type",e.agentType||"claude","--started-by","daemon","--task-id",e.taskId,"--user-id",e.userId,"--idle-timeout","120"];let o;if(this.sandboxPool?.isEnabled())try{if(!await this.sandboxPool.createWorkerSandbox(e.taskId,e.userId,s))throw new Error("Failed to create sandbox instance");const{projectPath:n}=await import("./logger-nstmO8QZ.mjs").then(function(e){return e.d}),{join:a}=await import("path"),t=["--no-warnings","--no-deprecation",a(n(),"dist","index.mjs"),...i],r=`"${process.execPath}" ${t.map(e=>`"${e}"`).join(" ")}`,c=await this.sandboxPool.wrapWorkerCommand(e.taskId,r);P.debug(`[SESSION] Sandboxed command for task ${e.taskId}: ${c}`),o=Se(c,{shell:!0,cwd:s,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}}),P.info(`[SESSION] Worker started with sandbox, PID: ${o.pid}`)}catch(n){return P.error(`[SESSION] Failed to setup sandbox for task ${e.taskId}:`,n),a.status="failed",a.message=`Sandbox setup failed: ${n instanceof Error?n.message:String(n)}`,a}else o=ka(i,{cwd:s,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}}),P.info(`[SESSION] Worker started without sandbox, PID: ${o.pid}`);if(process.env.DEBUG&&(o.stdout?.on("data",e=>{P.debug(`[Daemon] worker stdout: ${e.toString()}`)}),o.stderr?.on("data",e=>{P.debug(`[Daemon] worker stderr: ${e.toString()}`)})),!o.pid)return a.status="failed",a.message="Failed to start worker - no PID",a;P.info(`[SESSION] Worker started, PID: ${o.pid}`),this.trackWorkerProcess(e,o);const[r,c]=function(e){let n,a;const t=new Promise(t=>{n=e=>{clearTimeout(a),t(e)},a=setTimeout(()=>{t(e.onTimeout())},e.timeoutMs)});return[t,n,()=>clearTimeout(a)]}({timeoutMs:15e3,onTimeout:()=>(this.pidToAwaiter.delete(o.pid),a.status="failed",a.message=`Worker timeout (PID ${o.pid})`,a)});return this.pidToAwaiter.set(o.pid,()=>{c(a)}),r}stopSession(e){for(const[n,a]of this.pidToTrackedSession.entries())if(a.taskId===e){try{(a.childProcess?a.childProcess:{kill:e=>process.kill(n,e)}).kill("SIGTERM"),P.info(`[SESSION] Task ${e} stopped`)}catch(n){P.warn(`[SESSION] Failed to stop task ${e}:`,n)}return this.pidToTrackedSession.delete(n),!0}return P.warn(`[SESSION] Task ${e} not found`),!1}pruneStaleSessions(){for(const[e,n]of this.pidToTrackedSession.entries())try{process.kill(e,0)}catch(n){this.pidToTrackedSession.delete(e)}}shutdown(){P.info("[SESSION] Shutting down all sessions");for(const[e,n]of this.pidToTrackedSession.entries())try{"daemon"===n.startedBy&&n.childProcess?n.childProcess.kill("SIGTERM"):process.kill(e,"SIGTERM")}catch(n){P.warn(`[SESSION] Failed to stop PID ${e}:`,n)}this.pidToTrackedSession.clear(),this.pidToAwaiter.clear()}async startDeploymentWorker(e){const n={eventId:d(),status:"success",opCode:e.eventId};D.writeTaskInput(e);try{const a=ka(["worker","--type","deployment","--started-by","daemon","--task-id",e.taskId,"--user-id",e.userId,"--idle-timeout","10"],{cwd:process.cwd(),detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}});if(process.env.DEBUG&&(a.stdout?.on("data",e=>{P.debug(`[Deployment] worker stdout: ${e.toString()}`)}),a.stderr?.on("data",e=>{P.debug(`[Deployment] worker stderr: ${e.toString()}`)})),!a.pid)return n.status="failed",n.message="Failed to start deployment worker - no PID",n;P.info(`[SESSION] Deployment worker started, PID: ${a.pid}`);const t={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(t,a),n}catch(e){return n.status="failed",n.message=`Failed to start deployment worker: ${e instanceof Error?e.message:String(e)}`,n}}}class Aa{networkManager=null;workerSandboxes=new Map;settings=null;platform;constructor(){this.platform=Ae()}async initialize(e){if(this.settings=e,!e.enabled)return P.info("[SANDBOX] Sandbox disabled via settings"),!1;if(!Fe(this.platform))return P.warn("[SANDBOX] Platform not supported, sandbox disabled"),!1;try{const n={allowedDomains:[new URL(D.serverUrl).hostname,...e.network.allowedDomains],deniedDomains:e.network.deniedDomains,allowLocalBinding:!1};return this.networkManager=new We,await this.networkManager.initialize(n),P.info("[SANDBOX] Sandbox pool initialized successfully"),!0}catch(e){throw P.error("[SANDBOX] Failed to initialize:",e),e}}async createWorkerSandbox(e,n,a){if(!this.networkManager||!this.settings?.enabled)return null;try{const t=D.resolveUserWorkSpaceDir(n),s=D.getStatePaths().logsDir,i=this.settings.filesystem||{},o=this.settings.env||{},r={...i,allowWrite:[...i.allowWrite||[],t,a,s]};if("linux"===this.platform&&i.allowRead){const e=B.dirname(process.execPath);r.allowRead=[...i.allowRead,e]}const c={filesystem:r,env:o},p=new He(this.networkManager,c);return this.workerSandboxes.set(e,p),P.info(`[SANDBOX] Created sandbox for task ${e}`),p}catch(n){return P.error(`[SANDBOX] Failed to create sandbox for task ${e}:`,n),null}}async wrapWorkerCommand(e,n){const a=this.workerSandboxes.get(e);if(!a)throw new Error(`No sandbox found for task ${e}`);const t=await a.wrapWithSandbox(n);return P.debug(`[SANDBOX] Wrapped command for task ${e}`),t}disposeWorkerSandbox(e){const n=this.workerSandboxes.get(e);n&&(n.dispose(),this.workerSandboxes.delete(e),P.debug(`[SANDBOX] Disposed sandbox for task ${e}`))}async shutdown(){P.info("[SANDBOX] Shutting down sandbox pool");for(const[e,n]of this.workerSandboxes.entries())n.dispose(),P.debug(`[SANDBOX] Disposed sandbox for task ${e}`);this.workerSandboxes.clear(),this.networkManager&&(await this.networkManager.shutdown(),this.networkManager=null,P.info("[SANDBOX] Network manager shutdown complete"))}isEnabled(){return!0===this.settings?.enabled}}class Ra{constructor(e,n){this.client=e,this.machineId=n;const a=D.agentrixAgentsHomeDir,t=he(a,"companion","claude");this.stateFilePath=he(t,"state.json")}timer=null;initialDelay=null;intervalMs=9e5;enabled=!0;heartbeatTaskId=null;companionState=null;stateFilePath;start(){this.loadState(),this.companionState?P.info(`[COMPANION SCHEDULER] Ready: agent=${this.companionState.agentId}, chatId=${this.companionState.chatId}`):P.warn("[COMPANION SCHEDULER] No state.json found (companion not registered yet), will keep checking"),P.info(`[COMPANION SCHEDULER] Starting with interval ${this.intervalMs}ms`),this.initialDelay=setTimeout(()=>{this.initialDelay=null,this.tick(),this.scheduleNext()},6e4)}stop(){this.initialDelay&&(clearTimeout(this.initialDelay),this.initialDelay=null),this.timer&&(clearTimeout(this.timer),this.timer=null),P.info("[COMPANION SCHEDULER] Stopped")}scheduleNext(){this.timer=setTimeout(()=>{this.tick(),this.scheduleNext()},this.intervalMs)}setHeartbeatTaskId(e){this.heartbeatTaskId=e,this.saveStateField("heartbeatTaskId",e)}clearHeartbeatTaskId(){this.heartbeatTaskId=null,this.saveStateField("heartbeatTaskId",void 0),P.info("[COMPANION SCHEDULER] Cleared heartbeat task ID")}loadState(){try{if(te(this.stateFilePath)){this.companionState=JSON.parse(se(this.stateFilePath,"utf-8"));const e=this.companionState?.heartbeatIntervalMs??9e5;e!==this.intervalMs&&(P.info(`[COMPANION SCHEDULER] Interval changed: ${this.intervalMs}ms → ${e}ms`),this.intervalMs=e),this.enabled=this.companionState?.heartbeatEnabled??!0,this.heartbeatTaskId=this.companionState?.heartbeatTaskId??null,P.info(`[COMPANION SCHEDULER] Loaded state: agentId=${this.companionState?.agentId}, chatId=${this.companionState?.chatId??"none"}, enabled=${this.enabled}, interval=${this.intervalMs}ms, taskId=${this.heartbeatTaskId??"none"}`)}}catch(e){P.warn("[COMPANION SCHEDULER] Failed to load state.json",e)}}saveStateField(e,n){try{let a={};te(this.stateFilePath)&&(a=JSON.parse(se(this.stateFilePath,"utf-8"))),void 0===n?delete a[e]:a[e]=n;const t=fe(this.stateFilePath);te(t)||re(t,{recursive:!0}),oe(this.stateFilePath,JSON.stringify(a,null,2),"utf-8"),P.debug(`[COMPANION SCHEDULER] Saved state field: ${e}=${n??"removed"}`)}catch(n){P.warn(`[COMPANION SCHEDULER] Failed to save state field: ${e}`,n)}}tick(){if(this.loadState(),!this.companionState)return void P.debug("[COMPANION SCHEDULER] Still no state.json, skipping heartbeat");if(!this.enabled)return void P.debug("[COMPANION SCHEDULER] Heartbeat disabled, skipping");const e=this.companionState;this.heartbeatTaskId?(P.debug(`[COMPANION SCHEDULER] Sending heartbeat to existing task ${this.heartbeatTaskId}`),this.client.send("task-message",{eventId:d(),taskId:this.heartbeatTaskId,chatId:e.chatId,from:"machine",message:{type:"companion_heartbeat",timestamp:(new Date).toISOString()},senderType:"system",senderId:"system",senderName:"system"})):(P.debug("[COMPANION SCHEDULER] Requesting new heartbeat task"),this.client.send("request-companion-heartbeat",{eventId:d(),machineId:e.machineId,agentId:e.agentId,chatId:e.chatId,userId:e.userId,timestamp:(new Date).toISOString()}))}}async function _a(){Object.assign(P,N({type:"daemon"}));const{requestShutdown:e,shutdownPromise:n}=function(){const{processType:e,onShutdownRequest:n}={processType:"daemon"},a=`[${e.toUpperCase()}]`;let t;const s=new Promise(e=>{t=(t,s)=>{P.info(`${a} Requesting shutdown (source: ${t}, errorMessage: ${s})`),n&&n(t,s),setTimeout(()=>process.exit(1),1e3),e({source:t,errorMessage:s})}}),i=e=>{process.on(e,()=>{t("os-signal")})};return i("SIGINT"),i("SIGTERM"),process.on("uncaughtException",e=>{P.info(`${a} FATAL: Uncaught exception`,e),P.info(`${a} Stack trace: ${e.stack}`),t("exception",e.message)}),process.on("unhandledRejection",e=>{P.info(`${a} FATAL: Unhandled promise rejection`,e);const n=e instanceof Error?e:new Error(`Unhandled promise rejection: ${e}`);P.info(`${a} Stack trace: ${n.stack}`),t("exception",n.message)}),process.on("exit",e=>{P.info(`${a} Process exiting with code: ${e}`)}),{requestShutdown:t,shutdownPromise:s}}();console.log("[DAEMON RUN] Starting daemon process..."),P.debug("[DAEMON RUN] Environment",Vn()),await pn()&&(console.log("Daemon already running..."),process.exit(0));let a=await D.acquireDaemonLock(5,200);for(;!a;)await dn(),a=await D.acquireDaemonLock(5,200),a||(P.debug("[DAEMON RUN] cannot acquire daemon lock..."),process.exit(1));try{(function(){if(D.disableCaffeinate)return P.debug("[caffeinate] Caffeinate disabled via AGENTRIX_DISABLE_CAFFEINATE environment variable"),!1;if("darwin"!==process.platform)return P.debug("[caffeinate] Not on macOS, skipping caffeinate"),!1;if(Ln&&!Ln.killed)return P.debug("[caffeinate] Caffeinate already running"),!0;try{return Ln=Se("caffeinate",["-im"],{stdio:"ignore",detached:!1}),Ln.on("error",e=>{P.debug("[caffeinate] Error starting caffeinate:",e),Ln=null}),Ln.on("exit",(e,n)=>{P.debug(`[caffeinate] Process exited with code ${e}, signal ${n}`),Ln=null}),P.info(`[caffeinate] Started with PID ${Ln.pid}`),function(){if(Hn)return;Hn=!0;const e=()=>{Wn()};process.on("exit",e),process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGUSR1",e),process.on("SIGUSR2",e),process.on("uncaughtException",n=>{P.debug("[caffeinate] Uncaught exception, cleaning up:",n),e()}),process.on("unhandledRejection",(n,a)=>{P.debug("[caffeinate] Unhandled rejection, cleaning up:",n),e()})}(),!0}catch(e){return P.info("[caffeinate] Failed to start caffeinate:",e),!1}})()&&P.debug("[DAEMON RUN] Sleep prevention enabled");const t=await un();P.debug("[DAEMON RUN] Auth and machine setup complete");const s=new Aa;await s.initialize(D.getSandboxSettings());const i=new Ca(s),{port:o,stop:r}=await wa({getChildren:()=>i.getCurrentSessions(),stopSession:e=>i.stopSession(e),requestShutdown:()=>e("agentrix-cli"),registerSession:(e,n)=>i.registerTaskWorker(e,n),machineId:t.machineId});try{await Jn(),P.debug("[DAEMON RUN] Openers detected")}catch(e){P.warn("[DAEMON RUN] Failed to detect openers",e)}const c={pid:process.pid,port:o,startTime:(new Date).toLocaleString(),cliVersion:j.version,logPath:q({type:"daemon"})};D.writeDaemonState(c),P.debug("[DAEMON RUN] Daemon state written");const p=new Gn({machineId:t.machineId,serverUrl:D.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:x(t.token,t.machineId),keepAliveConfig:{intervalMs:2e4,event:"machine-alive",payloadGenerator:()=>({eventId:d(),machineId:t.machineId,timestamp:Date.now().toString(),controlPort:o})},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...n)=>P.debug(`[DAEMON SOCKET] ${e}`,...n)},i,{requestShutdown:e});await p.connect(),P.info("[DAEMON RUN] Machine client connected to server");const l=new Ra(p.client,t.machineId);l.start(),p.client.onEvent("companion-heartbeat-response",e=>{e?.taskId&&l.setHeartbeatTaskId(e.taskId)});const u=async(e,n)=>{l.stop(),await p.disconnect(),await r(),await s.shutdown(),await ln(),await Wn(),await D.releaseDaemonLock(a),P.info("[DAEMON RUN] Cleanup completed, exiting process"),process.exit(0)};P.info("[DAEMON RUN] Daemon started successfully, waiting for shutdown request");const m=await n;await u(m.source,m.errorMessage)}catch(e){P.info("[DAEMON RUN][FATAL] Failed somewhere unexpectedly - exiting with code 1",e),process.exit(1)}}const Ma={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".ico":"image/x-icon",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".json":"application/json",".xml":"application/xml",".html":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".rar":"application/vnd.rar",".mp3":"audio/mpeg",".mp4":"video/mp4",".wav":"audio/wav",".avi":"video/x-msvideo"};async function $a(e,n,a=!1){try{const t=function(e){try{const n=new URL(e),a=ye(n.pathname);if(a)return a;const t=n.searchParams.get("filename")||n.searchParams.get("name")||n.searchParams.get("file");if(t){const e=ye(t);if(e)return e}return""}catch{return""}}(e)||"";let s;if(a)try{const n=new URL(e).pathname,a=xe(n);s=a&&ye(a)?a:`${M()}${t||".dat"}`}catch{s=`${M()}${t||".dat"}`}else s=`${M()}${t||".dat"}`;const i=he(n,s),o=await fetch(e);if(!o.ok)throw new Error(`Failed to download file: ${o.status} ${o.statusText}`);if(!o.body)throw new Error("Response body is null");const r=o.headers.get("content-type"),c=r?.split(";")[0].trim()||function(e){const n=e.toLowerCase();return Ma[n]||"application/octet-stream"}(t),p=o.body,l=de(i);return await ze(p,l),{filePath:i,mimeType:c,filename:s}}catch(n){throw new Error(`Failed to download file from ${e}: ${n instanceof Error?n.message:String(n)}`)}}const Da={senderType:"system",senderId:"system",senderName:"system"};class Pa{client;context;historyDb;constructor(e,n){const{taskId:a,userId:t,machineId:s,cwd:i,chatId:o,...r}=e,c=i.endsWith("/")?i:`${i}/`;this.client=new gn(r),this.context={taskId:a,chatId:o,userId:t,machineId:s,cwd:c,stopTask:n.stopTask,shouldPersistTaskMessage:n.shouldPersistTaskMessage,onTaskMessage:n.onTaskMessage,onTaskInfoUpdate:n.onTaskInfoUpdate,onWorkerStatusRequest:n.onWorkerStatusRequest,onSubTaskResultUpdated:n.onSubTaskResultUpdated,onGitPush:n.onGitPush,dataEncryptionKey:e.dataEncryptionKey},this.historyDb=n.historyDb,this.initHandlers()}connect(){return new Promise((e,n)=>{const a=setTimeout(()=>{n(new Error("Worker connection timeout after 10 seconds"))},1e4);this.client.onLifecycle("connect",()=>{clearTimeout(a),e()}),this.client.onLifecycle("connect_error",e=>{clearTimeout(a),n(e)}),this.client.connect()})}async disconnect(){this.client.connected&&await this.client.flush(5e3).catch(()=>{}),this.client.disconnect()}sendTaskMessage(e,n,a){const t=d();return this.historyDb.saveMessage({eventId:t,message:n,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}),this.sendTaskEvent(e,n,a),t}sendWorkerInitializing(){const e={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),cwd:this.context.cwd};this.client.send("worker-initializing",e)}sendWorkerInitialized(){const e={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),cwd:this.context.cwd};this.client.send("worker-initialized",e)}sendWorkerReady(e){const n={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),...void 0!==e&&{duration:e}};this.client.send("worker-ready",n)}sendWorkRunning(e){const n={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),activeAgents:e};this.client.send("worker-running",n)}sendWorkerExit(e){const n={eventId:d(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),reason:e};this.client.send("worker-exit",n)}async sendErrorMessageAndExit(e){this.sendSystemErrorMessage(e),await this.client.flush(2e3),this.sendWorkerExit("error"),await this.disconnect()}sendSystemErrorMessage(e,n){const a={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:`System Error\n\n${e}`,metadata:{messageType:"system_error"}}]}};this.sendTaskEvent(Da,a,{groupId:n?.groupId})}sendAssistantMessage(e,n){const a={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:e}]}};this.sendTaskEvent(Da,a,{groupId:n?.groupId})}sendAskUser(e,n,a){return this.sendTaskMessage(e,{type:"ask_user",questions:n},{groupId:a?.groupId})}sendAskUserResponse(e,n){return this.sendTaskMessage(Da,n,{opCode:e})}sendTaskEvent(e,n,a){const{eventId:t,opCode:s,artifacts:i,navigateToTaskId:o}=a||{},r=t??d(),c={eventId:r,taskId:this.context.taskId,chatId:this.context.chatId,from:"worker",messageType:n.type,message:n,encryptedMessage:void 0,opCode:s,groupId:a?.groupId,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,artifacts:i,navigateToTaskId:o};if(this.historyDb.saveTaskEvent({eventType:"task-message",eventId:r,eventData:c,taskId:this.context.taskId,chatId:this.context.chatId,sequence:"number"==typeof c.sequence?c.sequence:null}),this.context.dataEncryptionKey){const e=v(n,this.context.dataEncryptionKey);c.message=void 0,c.encryptedMessage=e}return this.client.send("task-message",c),r}sendUpdateTaskAgentSessionId(e){const n={eventId:d(),taskId:this.context.taskId,agentSessionId:e,cwd:this.context.cwd};this.client.send("update-task-agent-session-id",n)}sendChangeTaskTitle(e){const n={eventId:d(),taskId:this.context.taskId,title:e};this.client.send("change-task-title",n),P.info(`[AGENT] Title changed to: ${e}`)}sendUpdateAgentInfo(e,n){const a={eventId:d(),taskId:this.context.taskId,agentId:e,...n};this.client.send("update-agent-info",a),P.info(`[AGENT] Agent info updated: ${JSON.stringify(n)}`)}sendResetTaskSession(){const e={eventId:d(),taskId:this.context.taskId};this.client.send("reset-task-session",e),P.info(`[AGENT] Session reset requested for task ${this.context.taskId}`)}async sendMergeRequest(e,n){const a={eventId:d(),taskId:this.context.taskId,summary:e,description:n};P.info(`[MERGE] Sending merge-request event for task ${this.context.taskId}`);const t=await this.client.sendWithAck("merge-request",a);if(!t.success)throw new Error(`Failed to create pull request: ${t.error||"Unknown error"}`);return P.info(`[MERGE] Pull request created: #${t.data.pullRequestNumber}`),{pullRequestNumber:t.data.pullRequestNumber,pullRequestUrl:t.data.pullRequestUrl}}async sendMergePr(){const e={eventId:d(),taskId:this.context.taskId,mergeMethod:"squash"};return P.info(`[MERGE-PR] Sending merge-pr event for task ${this.context.taskId}`),await this.client.sendWithAck("merge-pr",e)}associateRepository(e,n,a,t){const s={eventId:d(),taskId:this.context.taskId,gitServerHost:e,owner:n,repo:a,remoteUrl:t};P.info(`[REPO] Sending repository association request: ${e}/${n}/${a}`),this.client.send("associate-repo",s)}async dispatchTaskMessage(e){await this.context.onTaskMessage(e)}initHandlers(){const e=(n=this.context,a=this.historyDb,{"cancel-task":async e=>{e.taskId===n.taskId&&(P.info(`[WORKER] Task ${n.taskId} cancelled`),await n.stopTask())},"stop-task":async e=>{e.taskId===n.taskId&&(P.info(`[WORKER] Task ${n.taskId} stopped: ${e.reason||"no reason"}`),await n.stopTask())},"task-message":async e=>{if(e.taskId!==n.taskId)return;let t=e.message??null;if(!t&&e.encryptedMessage&&n.dataEncryptionKey&&(t=f(e.encryptedMessage,n.dataEncryptionKey)??null),!t)return;const s={senderType:e.senderType,senderId:e.senderId,senderName:e.senderName};if(n.attachmentsDir&&b(t)&&(t=await async function(e,n){const{attachmentsDir:a,log:t}=n;if(!Array.isArray(e.message.content))return e;const s=await Promise.all(e.message.content.map(async e=>"image"===e.type&&"url"===e.source?.type&&e.source?.url?async function(e,n){try{n?.("info","IMAGE",`Downloading image from: ${e.source.url}`);const a=await fetch(e.source.url);if(!a.ok)return n?.("error","IMAGE",`Failed to download image: ${a.statusText}`),e;const t=await a.arrayBuffer(),s=Buffer.from(t),i=s.toString("base64");let o=a.headers.get("content-type")||"image/jpeg";if(!o.startsWith("image/")){const n=e.source.url.toLowerCase();o=n.endsWith(".png")?"image/png":n.endsWith(".gif")?"image/gif":n.endsWith(".webp")?"image/webp":"image/jpeg"}return n?.("info","IMAGE",`Image downloaded and converted to base64 (${o}, ${Math.round(s.length/1024)}KB)`),{type:"image",source:{type:"base64",media_type:o,data:i}}}catch(a){return n?.("error","IMAGE",`Error processing image: ${a}`),e}}(e,t):"document"===e.type&&"url"===e.source?.type&&e.source?.url?async function(e,n,a){try{const t=e.source.url;a?.("info","DOCUMENT",`Downloading document from: ${t}`);const{filePath:s,mimeType:i,filename:o}=await $a(t,n,!0);return a?.("info","DOCUMENT",`Document downloaded to: ${s}`),{type:"text",text:`Document: ${s}\nTitle: ${e.title||o}\nType: ${i}`}}catch(n){return a?.("error","DOCUMENT",`Error processing document: ${n}`),e}}(e,a,t):e));return{...e,message:{...e.message,content:s}}}(t,{attachmentsDir:n.attachmentsDir,log:n.logger})),n.shouldPersistTaskMessage&&!await n.shouldPersistTaskMessage(t,s))return void P.debug(`[WORKER] Dropping incoming task-message before persistence: eventId=${e.eventId}`);const i={...e,message:t,encryptedMessage:void 0,chatId:e.chatId??n.chatId};a.saveTaskEvent({eventType:"task-message",eventId:e.eventId,eventData:i,taskId:n.taskId,chatId:e.chatId??n.chatId,sequence:e.sequence??null}),a.saveMessage({eventId:e.eventId,message:t,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}),n.onTaskMessage&&await n.onTaskMessage(t,s)},"task-info-update":async e=>{e.taskId===n.taskId&&n.onTaskInfoUpdate&&await n.onTaskInfoUpdate(e)},"worker-status-request":async e=>{e.taskId===n.taskId&&n.onWorkerStatusRequest&&await n.onWorkerStatusRequest(e)},"sub-task-result-updated":async e=>{e.parentTaskId===n.taskId&&n.onSubTaskResultUpdated&&await n.onSubTaskResultUpdated(e)}});var n,a;this.client.onEvent("cancel-task",e["cancel-task"]),this.client.onEvent("stop-task",e["stop-task"]),this.client.onEvent("task-message",e["task-message"]),this.client.onEvent("task-info-update",e["task-info-update"]),this.client.onEvent("worker-status-request",e["worker-status-request"]),this.client.onEvent("sub-task-result-updated",e["sub-task-result-updated"]),this.client.onEvent("event-ack",e=>{const n=e.data?.sequence;void 0!==e.opCode&&"number"==typeof n&&this.historyDb.updateTaskEventSequence(e.opCode,n)})}}class Oa{logger;socketClient;taskId;userId;chatId;rootTaskId;parentTaskId;workingDirectory;taskAgents;serverUrl;taskDataKey;constructor(e){this.logger=e.logger,this.socketClient=e.socketClient,this.taskId=e.taskId,this.userId=e.userId,this.chatId=e.chatId,this.rootTaskId=e.rootTaskId,this.parentTaskId=e.parentTaskId,this.workingDirectory=e.workingDirectory,this.taskAgents=e.taskAgents,this.serverUrl=e.serverUrl,this.taskDataKey=e.taskDataKey}async call(e,n,a){const t=d();try{const s=await this.socketClient.sendWithAck("rpc-call",{eventId:t,taskId:this.taskId,method:e,path:n,query:a?.query,body:a?.body});if(!s.success){const a=s.error||{code:"unknown",message:"Unknown error"};throw new Error(`RPC ${e} ${n} failed: ${a.message} (${a.code})`)}return s.data}catch(a){throw new Error(`RPC ${e} ${n} error: ${a.message}`)}}log(e){this.logger.info(e)}getWorkspace(){return this.workingDirectory}getUserId(){return this.userId}getTaskId(){return this.taskId}getChatId(){return this.chatId}getRootTaskId(){return this.rootTaskId}getParentTaskId(){return this.parentTaskId}getTaskAgents(){return this.taskAgents}async createDraftAgent(e){return this.call("POST","/v1/draft-agent",{body:{...e,userId:this.userId,taskId:this.taskId}})}async updateDraftAgent(e,n){return this.call("PATCH",`/v1/draft-agent/${e}`,{body:n})}async startSubTask(e){const n={userId:this.userId,chatId:this.chatId,agentId:e.agentId,parentTaskId:this.taskId,customTitle:e.title,cwd:e.cwd,forceUserCwd:e.forceUserCwd};return this.taskDataKey?n.encryptedMessage=v(e.message,this.taskDataKey):n.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:n})).taskId}}async startIndependentTask(e){const n={userId:this.userId,chatId:this.chatId,agentId:e.agentId,sourceTaskId:this.taskId,customTitle:e.title,cwd:e.cwd,forceUserCwd:e.forceUserCwd,autoNavigate:e.autoNavigate};return this.taskDataKey?n.encryptedMessage=v(e.message,this.taskDataKey):n.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:n})).taskId}}async startGroupTask(e){const n={userId:this.userId,chatId:this.chatId,parentTaskId:this.taskId,customTitle:e.title,todos:e.todos};return this.taskDataKey?n.encryptedMessage=v(e.message,this.taskDataKey):n.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:n})).taskId}}async sendMessage(e){await this.call("POST",`/v1/tasks/${e.taskId}/send-message`,{body:{message:e.message,target:e.target,fromTaskId:this.taskId,senderType:"agent",senderId:this.taskId,senderName:"agent"}})}async showModal(e){await this.call("POST",`/v1/tasks/${e.taskId}/show-modal`,{body:{modalName:e.modalName,modalData:e.modalData}})}async getTaskSession(e){return this.call("GET",`/v1/tasks/${e}/session`)}async findSubTaskByAgent(e){const n=await this.call("GET","/v1/tasks/find-by-agent",{query:{parentTaskId:this.taskId,agentId:e}});return n.taskId?{taskId:n.taskId}:null}async listSubTasks(){return(await this.call("GET","/v1/tasks/sub-tasks",{query:{parentTaskId:this.taskId}})).tasks}async listTasks(e){return(await this.call("GET","/v1/tasks/recent",{query:{chatId:this.chatId,...e?.limit&&{limit:e.limit},...e?.status&&{status:e.status}}})).tasks}async listAgents(){return this.call("GET","/v1/user-agents")}async uploadFile(e){this.logger.info("[Agent-Context] Uploading file...");const n=await L.promises.stat(e.path);this.logger.info("[Agent-Context] file stats");const a=n.size,t=e.contentType||Sn.lookup(e.name)||"application/octet-stream",s=(await this.call("POST","/v1/files/upload-urls",{body:{count:1}})).files[0],i=s.url;this.logger.info(`[Agent-Context] FileUploadUrl: ${i}`);const o=await L.promises.readFile(e.path),r=await fetch(i,{method:"PUT",headers:{"Content-Type":t},body:o});if(!r.ok)throw new Error(`Failed to upload file to S3: ${r.status} ${r.statusText}`);let c;return await this.call("POST","/v1/files/confirm-upload",{body:{fileId:s.id,name:e.name,size:a,contentType:t,visibility:e.visibility||"private"}}),c="public"===e.visibility?`${this.serverUrl}/v1/files/public/${s.id}`:i.split("?")[0],{fileId:s.id,name:e.name,size:a,contentType:t,url:c}}}function ja(e,n){const a=e.split("\n");return a.length<=n?e:a.slice(0,n).join("\n")+"..."}function Na(e,n){let a=e.resultMessage;if(0===a.result.trim().length&&e.encryptedResultMessage&&n){const t=f(e.encryptedResultMessage,n);t&&"result"===t.type&&(a={type:"result",result:"result"in t?t.result:"",is_error:t.is_error})}const t={...e,resultMessage:{...a,result:ja(a.result,3)}};let s=`<sub-task-result-updated>\n${JSON.stringify(t,null,2)}\n</sub-task-result-updated>`;return s+=a.result.trim().length>0?'\n<system-reminder>The result is already shown to user as a card. Just acknowledge briefly (e.g., "Done!"). Only elaborate if error or needs user action.</system-reminder>':"\n<system-reminder>The sub-task result was empty. You can use reply_to_sub_task to ask it to continue, retry, or resend the result.</system-reminder>",{type:"user",message:{role:"user",content:s}}}function qa(){const e=new Set;return{filter(n){const a=n;if(!a.message||!a.message.content||"string"==typeof a.message.content)return n;const t=a.message.content.filter(n=>!("tool_result"===n.type&&e.has(n.tool_use_id)||"user"===a.type&&"tool_result"!==n.type));return 0===t.length?null:(a.message.content=t,a)},clear(){e.clear()}}}function Ua(e){const n=za(e);return n?{type:"user",message:{role:"user",content:[{type:"text",text:`<msg ${La({seq:n.seq.toString(),at:n.at,senderType:n.senderType??void 0,senderId:n.senderId??void 0,senderName:n.senderName??void 0})}>${n.text}</msg>\n`},...n.nonTextBlocks]},parent_tool_use_id:null,session_id:""}:null}function Ga(e){const n=za(e);return n?`<msg ${La({seq:n.seq.toString(),at:n.at,senderType:n.senderType??void 0,senderId:n.senderId??void 0,senderName:n.senderName??void 0})}>\n${n.text}\n</msg>`:null}function La(e){return Object.entries(e).filter(([,e])=>void 0!==e&&""!==e).map(([e,n])=>`${e}="${function(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}(n)}"`).join(" ")}function Fa(e){const n=[];for(const a of e){const e=Ga(a);e&&n.push(e)}return n.join("\n")}function Wa(e){return`Ask user: ${e.questions.map((e,n)=>{const a=e.options?.map(e=>e.label).filter(Boolean),t=a&&a.length>0?` options: ${a.join(", ")}`:"";return`Q${n+1}[${e.header}] ${e.question}${t}`}).join(" | ")}`}function Ha(e){return`Ask user response:${e.status?` status=${e.status}`:""}${e.reason?` reason=${e.reason}`:""} answers: ${e.answers?.length?e.answers.join(", "):"no answers"}`}function za(e){const{text:n,nonTextBlocks:a}=(t=e.message,y(t)?{text:Wa(t),nonTextBlocks:[]}:w(t)?{text:Ha(t),nonTextBlocks:[]}:k(t)?function(e){switch(e.type){case"user":case"assistant":return function(e){if("string"==typeof e)return{text:e,nonTextBlocks:[]};if(Array.isArray(e)){const n=[],a=[];for(const t of e)"text"!==t.type||"string"!=typeof t.text?a.push(t):n.push(t.text);return{text:n.join("\n"),nonTextBlocks:a}}return{text:"",nonTextBlocks:[]}}(e.message.content);case"result":if("success"===e.subtype)return{text:e.result,nonTextBlocks:[]}}return{text:"",nonTextBlocks:[]}}(t):{text:"",nonTextBlocks:[]});var t;return n?{seq:e.localSequence,at:e.createdAt,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,text:n,nonTextBlocks:a}:null}function Ba({workClient:e}){return Be("change_title","Change the session title to better describe what you are working on.\n\n## When to Use\n- Call it at the start of a session to set a descriptive title\n- Call it again when the title becomes outdated or too generic\n\nGood titles help users find conversations later.",{title:_e.string().describe("New title for the task")},async n=>(e.sendChangeTaskTitle(n.title),{content:[{type:"text",text:`Task title updated to: ${n.title}`}]}))}function Ka({agentContext:e,log:n}){return Be("emit_to_task","Send follow-up instructions to a running or failed sub-task.\nUse this when the sub-task needs clarification, hit an error, or the user has new requirements.",{taskId:_e.string().describe("Sub-task ID to send follow-up instructions to"),instructions:_e.string().describe("Additional instructions for the sub-task")},async a=>{try{return await e.sendMessage({taskId:a.taskId,message:{type:"user",message:{role:"user",content:a.instructions}},target:"agent"}),{content:[{type:"text",text:`Sent follow-up instructions to sub-task ${a.taskId}.`}]}}catch(e){return n("error","TASK",`Failed to send follow-up to sub-task ${a.taskId}:`,e),{content:[{type:"text",text:`Failed to send follow-up to sub-task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Va({historyDb:e}){return Be("get_task_history","Retrieve earlier task history stored locally for additional context.",{sequence:_e.number().int().describe("Return messages before this local sequence (exclusive)."),limit:_e.number().int().min(1).max(50).default(20).describe("Maximum number of messages to return.")},async n=>{const a=n.limit??20,t=e.pageMessagesBefore(n.sequence,a);return 0===t.data.length?{content:[{type:"text",text:"No earlier messages found."}]}:{content:[{type:"text",text:Fa(t.data)}]}})}function Xa({agentContext:e}){return Be("get_task_agents","List the agents available for the current task and return taskAgents info.",{},async()=>{const n=e.getTaskAgents();return n.length?{content:[{type:"text",text:JSON.stringify(n,null,2)}]}:{content:[{type:"text",text:"No task agents available."}]}})}function Ya({agentContext:e,log:n}){return Be("list_sub_task","List direct sub tasks for the current task with taskId, title, and cwd.",{},async()=>{try{const n=await e.listSubTasks();return n.length?{content:[{type:"text",text:JSON.stringify(n,null,2)}]}:{content:[{type:"text",text:"No sub tasks found."}]}}catch(e){return n("error","TASK","Failed to list sub tasks:",e),{content:[{type:"text",text:`Failed to list sub tasks: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Ja({agentContext:e,agentId:n,log:a,setPendingNavigateTaskId:t}){return Be("create_task","Delegate a task to an agent for execution.\n\n**Modes**:\n- Sub-task (default): Creates under current task, linked via parentTaskId.\n- Independent (independent=true): Creates a top-level task with no parent binding. Optionally set autoNavigate=true to auto-switch the user's App UI to the new task.\n\nIf agentId is provided, delegates to that specific agent. Otherwise, creates a task for yourself.\nAlways provide a concise task title in \"title\".\nThe task runs asynchronously - you'll be notified when complete via <sub-task-result-updated> message.\nUse for: multi-step implementations, analysis, code reviews, or any work that takes >30 seconds.\nAfter calling this tool, continue responding to user - don't wait for task completion.",{agentId:_e.string().optional().describe('Target agent ID (e.g., "agent-poster-generator"). If not provided, uses current agent.'),title:_e.string().min(1).max(200).describe("Task title for the agent to use (required)"),instructions:_e.string().describe("Detailed instructions for the agent. Be specific about what needs to be done."),briefSummary:_e.string().describe('One-line summary shown to user immediately (e.g., "Creating login page")'),cwd:_e.string().optional().describe("Working directory for the task. Pass your current cwd when the sub-task needs to read/write the same project files as you. If omitted, a new isolated workspace is created (scoped by taskId)."),useWorktree:_e.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place)."),independent:_e.boolean().optional().describe("Create as independent top-level task (no parent). Defaults to false (sub-task mode)."),autoNavigate:_e.boolean().optional().describe("Auto-switch App UI to this task after creation. Only works with independent=true. Defaults to false.")},async s=>{try{if(s.autoNavigate&&!s.independent)return{content:[{type:"text",text:"Error: autoNavigate can only be used with independent=true"}],isError:!0};const i=s.agentId||n;let o;return s.independent?(o=await e.startIndependentTask({agentId:i,message:{type:"user",message:{role:"user",content:s.instructions}},title:s.title,cwd:s.cwd,forceUserCwd:!s.useWorktree,autoNavigate:s.autoNavigate}),s.autoNavigate&&t(o.taskId),a("info","TASK",`Created independent task ${o.taskId} for agent ${i} (autoNavigate: ${s.autoNavigate??!1})`)):(o=await e.startSubTask({agentId:i,message:{type:"user",message:{role:"user",content:s.instructions}},title:s.title,cwd:s.cwd,forceUserCwd:!s.useWorktree}),a("info","TASK",`Created sub-task ${o.taskId} for agent ${i}`)),{content:[{type:"text",text:`🚀 Task created: ${o.taskId}\n${s.agentId?`Agent: ${i}\n`:""}${s.independent?"Mode: Independent\n":""}Summary: ${s.briefSummary}\n\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return a("error","TASK","Failed to create task:",e),{content:[{type:"text",text:`Failed to create task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Qa({agentContext:e,log:n}){return Be("create_solo_task","Create a single-agent async task in group chat.\n\n## When to Use (sparingly)\n- Long-running background work (>5 minutes)\n- Work that needs separate tracking/progress monitoring\n- Complex multi-step projects with explicit deliverables\n\n## Prefer invoke Instead\nFor most requests, use `invoke` - it's simpler and the agent responds directly in chat.\nOnly use this tool when background tracking is truly needed.\n\nAfter creating: You'll receive <sub-task-result-updated> when task completes.",{title:_e.string().min(1).max(200).describe("Task title"),instructions:_e.string().describe("Instructions for the owner agent"),briefSummary:_e.string().optional().describe("One-line summary shown to user immediately"),agentId:_e.string().describe("Target agent ID"),cwd:_e.string().optional().describe("Working directory for the sub-task. Pass your current cwd when the sub-task needs to read/write the same project files as you. If omitted, a new isolated workspace is created (scoped by sub-task taskId)."),useWorktree:_e.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place).")},async a=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startSubTask({agentId:a.agentId,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree})).taskId}\n${a.briefSummary?`Summary: ${a.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return n("error","TASK","Create solo task failed:",e),{content:[{type:"text",text:`Create solo task failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Za({agentContext:e,log:n,agentId:a}){return Be("create_group_task","Create a multi-agent async task plan in group chat.\n\n## When to Use (sparingly)\n- Long-running background work requiring multiple agents (>5 minutes)\n- Complex multi-step projects with explicit deliverables\n- Work that needs separate tracking/progress monitoring\n\n## Prefer invoke Instead\nFor most requests, use `invoke` - it's simpler and agents respond directly in chat.\nOnly use this tool when background tracking with multiple agents is truly needed.\n\nThe planner becomes the task owner; todos are embedded in the task.\nAfter creating: You'll receive <sub-task-result-updated> when task completes.",{title:_e.string().min(1).max(200).describe("Task title"),requirement:_e.string().describe("Overall requirement"),briefSummary:_e.string().optional().describe("One-line summary shown to user immediately"),todos:_e.array(_e.object({agentId:_e.string().describe("Agent ID responsible for the todo"),title:_e.string().min(1).max(200).describe("Todo title"),instructions:_e.string().describe("Detailed instructions for this todo")})).min(1).describe("Todo list for agents")},async a=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startGroupTask({title:a.title,todos:a.todos,message:{type:"user",message:{role:"user",content:a.requirement}}})).taskId}\n${a.briefSummary?`Summary: ${a.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return n("error","DISPATCH","Dispatch failed:",e),{content:[{type:"text",text:`Dispatch failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function et({askUser:e,log:n}){return Be("ask_user",'Ask the user questions when you need clarification or user input. Supports 1-4 questions with 2-4 options each. Use this when you need user decisions or additional information. An "Other" option with free text input is automatically added.',{questions:_e.array(_e.object({question:_e.string().describe("The complete question to ask the user"),header:_e.string().max(12).describe("Short label displayed as a chip/tag (max 12 chars)"),multiSelect:_e.boolean().describe("Set to true to allow multiple option selections"),options:_e.array(_e.object({label:_e.string().describe("Option label (1-5 words)"),description:_e.string().describe("Explanation of what this option means")})).min(2).max(4).describe("Available choices (2-4 options)")})).min(1).max(4).describe("Questions to ask (1-4 questions)")},async a=>{try{const n=a.questions.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]})),t=await e(n);return"answered"!==(t.status??"answered")?{content:[{type:"text",text:"The user did not provide an answer within the expected time. \n<system-reminder>Please abort the session, and decide whether to retry when the user provides a new message later.</system-reminder>"}],isError:!0}:{content:[{type:"text",text:`User answers:\n${t.answers.map(e=>e.startsWith("other:")?`Other: "${e.slice(6)}"`:e).join("\n")}`}]}}catch(e){return n("error","ASK_USER","Failed to get user response:",e),{content:[{type:"text",text:`Failed to get user response: ${e instanceof Error?e.message:"Unknown error"}`}]}}})}function nt({invokeAgent:e}){return Be("invoke",'Let an agent respond to the conversation (talk).\n\n**Use for**: Q&A, explanations, opinions, discussions, debates.\n**Do NOT use for**: Work producing files/code → use assign instead.\n\n**hint parameter**: Optional. Use to reduce agent\'s attention cost or provide meta-context:\n- ✅ Role assignment: hint="You argue FOR REST" (first turn of debate)\n- ✅ Focus guidance: hint="Focus on security aspects"\n- ✅ Long/busy chat: hint="Respond to Alice\'s caching question"\n- ✅ Multi-topic: hint="Re: the API design discussion"\n- ❌ Short, clear context: agent can easily find what to respond to\n\nAgent sees hint (if provided) + conversation history and responds in chat.',{agentId:_e.string().describe("Target agent ID"),hint:_e.string().optional().describe("Optional context/instruction for the agent")},async n=>(e(n.agentId,n.hint),{content:[{type:"text",text:`Invoked ${n.agentId}. The agent will respond in the chat later.`}]}))}function at({workClient:e,agentId:n,uploadFile:a,log:t}){return Be("update_agent_info","Update your display name, avatar, and signature in the platform.\nCall this after onboarding when the user has chosen your name and emoji/image.\nThis syncs your identity to the platform so the App displays your chosen name and avatar.\n\nFor avatar: provide a local image file path. The image will be uploaded to the platform.\nFor signature: a short status line or tagline shown under your name.",{displayName:_e.string().optional().describe("Your display name"),avatarPath:_e.string().optional().describe("Local path to avatar image file (png/jpg/svg)"),signature:_e.string().optional().describe("Short status line or tagline shown under your name")},async s=>{let i;if(s.avatarPath)try{i=(await a({name:"avatar.png",path:s.avatarPath,visibility:"public"})).fileId}catch(e){return t("error","TOOL","Avatar upload failed:",e),{content:[{type:"text",text:`Avatar upload failed: ${e}`}],isError:!0}}e.sendUpdateAgentInfo(n,{displayName:s.displayName,avatar:i,signature:s.signature});const o=[];return s.displayName&&o.push(`name → ${s.displayName}`),i&&o.push("avatar → uploaded"),s.signature&&o.push(`signature → ${s.signature}`),{content:[{type:"text",text:`Profile updated: ${o.join(", ")}`}]}})}function tt({assign:e,log:n}){return Be("assign","Assign work to an agent (do the work).\n\n**Use for**: Code, files, reports, artifacts (agent produces output).\n**Do NOT use for**: Q&A, explanations → use invoke instead.\n\nProgress streams to chat in real-time.",{agentId:_e.string().describe("Target agent ID"),instruction:_e.string().describe("Task instruction for the agent"),acknowledgment:_e.string().optional().describe('Agent\'s quick reply shown immediately (e.g., "starting now", "On it")')},async n=>(e(n.agentId,n.instruction,n.acknowledgment),{content:[{type:"text",text:`Assigned work to ${n.agentId}.`}]}))}function st({agentContext:e,log:n}){return Be("list_tasks","List recent tasks in the current chat.\nUse this to review what tasks have been running, completed, or are still active.\nReturns a lightweight summary of each task (id, title, state, agent, duration, timestamps).",{limit:_e.number().int().min(1).max(50).default(10).optional().describe("Maximum number of tasks to return (default 10)."),status:_e.enum(["all","active","completed"]).default("all").optional().describe("Filter by task status: all, active, or completed.")},async a=>{try{const n=await e.listTasks({limit:a.limit??10,status:a.status??"all"});return n.length?{content:[{type:"text",text:JSON.stringify(n,null,2)}]}:{content:[{type:"text",text:"No tasks found."}]}}catch(e){return n("error","TASK","Failed to list tasks:",e),{content:[{type:"text",text:`Failed to list tasks: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function it({chatHistoryDb:e}){return Be("read_conversation","Read recent messages from the main conversation between you and the user. Use this to review what was discussed recently.",{limit:_e.number().int().min(1).max(200).default(50).optional().describe("Number of recent messages to return (default 50)."),before:_e.number().int().optional().describe("Sequence number — return messages before this sequence for pagination.")},async n=>{if(!e)return{content:[{type:"text",text:"Chat history not available in this mode."}],isError:!0};const a=n.limit??50,t=null!=n.before?e.pageMessagesBefore(n.before,a):e.pageRecentMessages(a);if(0===t.data.length)return{content:[{type:"text",text:"No conversation messages found."}]};let s=Fa(t.data);return t.hasMore&&(s+=`\n\nMore messages available. Use before=${Math.min(...t.data.map(e=>e.localSequence))} to load earlier messages.`),{content:[{type:"text",text:s}]}})}function ot({agentContext:e,log:n}){return Be("send_reminder","Send an internal reminder to your main self (本体) in the primary chat.\nThis is for companion shadow (heartbeat task) use only.\n\nThe reminder is invisible to the user — it only wakes up the main companion worker.\nThe main companion will see the reminder in its conversation context and decide how to act.\n\nKeep content concise (one sentence). For detailed analysis, write to a file and pass filePath.",{content:_e.string().describe('Brief reminder message (one sentence, e.g., "Heartbeat architecture discussion pending for 2 days, consider following up")'),filePath:_e.string().optional().describe("Path to detailed analysis file in workspace, if any")},async a=>{try{const n=e.getChatId();return await e.sendMessage({taskId:n,message:{type:"companion_reminder",content:a.content,filePath:a.filePath,timestamp:(new Date).toISOString()},target:"agent"}),{content:[{type:"text",text:"Reminder sent to main companion."}]}}catch(e){return n("error","COMPANION","Failed to send reminder:",e),{content:[{type:"text",text:`Failed to send reminder: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function rt({uploadFile:e,log:a}){return Be("upload_file","Upload a local file to the platform and get a public URL.\nUse this to share images, documents, or other files with the user.\nReturns a public URL that can be embedded in markdown (e.g., ![screenshot](url)).",{filePath:_e.string().describe("Absolute path to the local file to upload"),name:_e.string().optional().describe("Display name for the file (defaults to filename)")},async t=>{try{const a=n("path"),s=t.name||a.basename(t.filePath);return{content:[{type:"text",text:(await e({name:s,path:t.filePath,visibility:"public"})).url}]}}catch(e){return a("error","TOOL","File upload failed:",e),{content:[{type:"text",text:`File upload failed: ${e}`}],isError:!0}}})}function ct({agentContext:e,log:n}){return Be("list_agents","List all available agents for the current user, including system agents and user-created agents (both published and draft).",{},async()=>{try{const{agents:n,draftAgents:a}=await e.listAgents(),t=e=>`- **${e.displayName||e.name}** (${e.id})\n Type: ${e.type}\n`+(e.developerName?` Developer: ${e.developerName}\n`:"")+` ${e.description||"No description"}\n`;let s="# Available Agents\n\n";return n.length>0&&(s+="## Published Agents\n\n",s+=n.map(t).join("\n")),a.length>0&&(s+="\n## Draft Agents\n\n",s+=a.map(t).join("\n")),0===n.length&&0===a.length&&(s+="No agents available."),{content:[{type:"text",text:s}]}}catch(e){return n("error","AGENTS","Failed to list agents:",e),{content:[{type:"text",text:`Failed to list agents: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}const pt=Je(je);async function lt(e){try{const n=Ye(e);return await n.checkIsRepo()}catch{return!1}}async function dt(e){const n=Ye(e);await n.add("."),await n.commit("Initial commit",{"--allow-empty":null})}async function ut(e,n,a){const t=Ye(e);(await t.branchLocal()).all.includes(n)?await t.checkout(n):(a&&await t.checkout(a),await t.checkoutLocalBranch(n))}async function mt(e){const n=Ye(e);return!(await n.status()).isClean()}async function gt(e){const n=Ye(e),a=await n.log({maxCount:1});if(!a.latest)throw new Error("No commits found in repository");return a.latest.hash}async function ht(e){try{const n=Ye(e);return null!==(await n.log({maxCount:1})).latest}catch{return!1}}function ft(e){if(!te(e))return!0;const n=ce(e);return 0===n.length||1===n.length&&".git"===n[0]}async function xt(e,n){const a=Ye(e);return await a.add("."),await a.commit(n),await gt(e)}async function vt(e,n,a){const t=Ye(e),s=await t.diffSummary([`${n}..${a}`]);return{totalInsertions:s.insertions,totalDeletions:s.deletions,files:s.files.map(e=>({path:e.file,insertions:"insertions"in e?e.insertions:0,deletions:"deletions"in e?e.deletions:0}))}}async function bt(e){const n=Ye(e);return(await n.revparse(["--abbrev-ref","HEAD"])).trim()}async function yt(e,n,a){const t=Ye(e);await t.remote(["set-url",n,a])}const wt="oauth2",kt="AGENTRIX_GIT_USERNAME",It="AGENTRIX_GIT_PASSWORD";function St(){const e=he(Y(),`git-askpass-${M()}.sh`);return oe(e,`#!/bin/sh\ncase "$1" in\n *Username*|*username*) printf '%s\\n' "\${${kt}:-${wt}}" ;;\n *) printf '%s\\n' "\${${It}:-}" ;;\nesac\n`,{mode:448}),e}function Tt(e,n,a=wt){return{...process.env,GIT_ASKPASS:e,GIT_TERMINAL_PROMPT:"0",[kt]:a,[It]:n}}function Et(e){return{gitUrl:e.gitUrl,baseBranch:e.baseBranch,cwd:e.cwd||"",userCwd:e.userCwd,forceUserCwd:e.forceUserCwd,userId:e.userId,taskId:e.taskId,repositorySourceType:e.repositorySourceType,taskRepositoryId:e.repositoryId,gitServerId:e.gitServerId}}function Ct(e){return`agentrix/${e}`}async function At(e){if(!e)return null;const n=await D.getSecretKey();return n?Rn(e,n):null}async function Rt(e,n){const a=function(e){const n=function(e){return he(An,`${e}.pat.meta.json`)}(e);if(!te(n))return null;try{return JSON.parse(se(n,"utf8"))}catch{return null}}(n);if(!a)return void console.warn("[GIT] No PAT user metadata found, skipping git config");const t=a.username,s=a.email||`${a.username}@gitlab.local`;await async function(e,n,a){await pt("git",["config","user.name",n],{cwd:e}),await pt("git",["config","user.email",a],{cwd:e})}(e,t,s),console.log(`[GIT] Set local git config user.name=${t} user.email=${s}`)}async function _t(e,n,a,t){const s=await At(t);s?await async function(e,n,a,t=!1){const s=St();try{const i=["push","origin",a];t&&i.push("--force"),await pt("git",i,{cwd:n,env:Tt(s,e)})}finally{ue(s)}}(s,e,n,a):await async function(e,n,a=!1){const t=Ye(e),s=a?["--force"]:[];await t.push("origin",n,s)}(e,n,a)}async function Mt(e,n,a){await async function(e){const n=Ye(e);await n.init()}(e);const t=function(e,n){return{hook_event_name:"RepositoryInit",workspace_path:e,task_id:n}}(e,n);return a?.onRepositoryInit&&await a.onRepositoryInit(t),await dt(e),await gt(e)}function $t(e,n){return`Auto-commit: ${e} at ${(new Date).toISOString().replace("T"," ").substring(0,19)} for task ${n}`}async function Dt(e,n,a,t){if(n===a)return;const s=await async function(e,n,a){const t=Ye(e);return await t.diff([`${n}..${a}`])}(e,n,a);if(!s.trim())return;const i=he(t,"patch.diff");return await Qe(i,s),i}async function Pt(e,n,a){await D.writeLastSentCommitHash(e,n,a)}function Ot(e,n){return`Please generate pull request metadata for the changes made in this task.\n\nInitial commit hash: ${e}\n${n?`\n\nAdditional instructions:\n${n}`:""}\n\nProvide a concise title (conventional commits format), a detailed description, and a user-facing summary message.`}function jt(e,n,a,t=6e4){return new Promise(s=>{const i=`shell_${Ze().replace(/-/g,"")}`;a.onOutput({type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:i,name:"shell",input:{command:e}}]},parent_tool_use_id:null,session_id:""});const o=Se("/bin/bash",["-c",e],{cwd:n,env:process.env,shell:!1});let r=null,c=!1;t>0&&(r=setTimeout(()=>{c=!0,o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL")},1e3)},t));let p="";o.stdout?.on("data",e=>{p+=e.toString()}),o.stderr?.on("data",e=>{p+=e.toString()}),o.on("close",(e,n)=>{let o,l,d;if(r&&clearTimeout(r),c){o=124,d=!0;const e=`\n[Command timed out after ${t/1e3} seconds]`;l=p?`${p}${e}`:e.trim()}else o=null!==e?e:"SIGTERM"===n?143:1,d=0!==o,l=p||"(no output)";a.onOutput({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:i,content:l,is_error:d}]},parent_tool_use_id:null,session_id:""}),a.onComplete(o),s(o)}),o.on("error",e=>{r&&clearTimeout(r);const n=`[Error] ${e.message||"Command execution failed"}`;a.onOutput({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:i,content:n,is_error:!0}]},parent_tool_use_id:null,session_id:""}),a.onComplete(1),s(1)})})}class Nt{config;messageQueue=[];agentMessageQueue=[];agentMessageResolver=null;workerState="running";messageIdCounter=0;isStopped=!1;runStartTime=Date.now();commandRunning=!1;isDebouncing=!1;agentRunningMap=new Map;backgroundTaskMap=new Map;anonymousBackgroundTaskCount=0;lastActiveAgentsSignature=null;idleTimeoutHandle=null;idleTimeoutMs;constructor(e){this.config=e,this.idleTimeoutMs=Math.max(0,e.idleTimeoutMs??0)}parseMessage(e){if("user"!==e.type)return{type:"normal",content:"",originalMessage:e};const n=("string"==typeof e.message.content?e.message.content:"").trim();return n.startsWith("!")&&!n.startsWith("![")?{type:"bash-command",content:n.slice(1).trim(),originalMessage:e}:"![merge-request]"===n?{type:"merge-request",content:n,originalMessage:e}:"![merge-pr]"===n?{type:"merge-pr",content:n,originalMessage:e}:"![new]"===n?{type:"new-session",content:n,originalMessage:e}:{type:"normal",content:n,originalMessage:e}}async enqueue(e){if(this.isStopped)return void this.log("warn","COORDINATOR","Ignoring message - coordinator is stopped");if(!("user"!==e.type||e.message&&"object"==typeof e.message&&"content"in e.message))return void this.log("warn","COORDINATOR","Ignoring malformed user message (missing content)");const n=this.parseMessage(e),a={id:"msg-"+ ++this.messageIdCounter,type:n.type,priority:"normal",content:n.content,originalMessage:e,timestamp:Date.now()};this.messageQueue.push(a),this.log("info","COORDINATOR",`Enqueued message ${a.id} (type: ${a.type}, queue: ${this.messageQueue.length})`),this.tryUpdateWorkerState(),this.tryProcessNext()}async tryProcessNext(){if(!this.isStopped&&0!==this.messageQueue.length){this.tryUpdateWorkerState();try{const e=this.messageQueue.shift();this.log("info","COORDINATOR",`Processing message ${e.id} (type: ${e.type})`),await this.processMessage(e),this.log("info","COORDINATOR",`Completed message ${e.id}`)}catch(e){this.log("error","COORDINATOR",`Error processing message: ${e}`)}finally{this.isStopped||this.tryProcessNext()}}}async processMessage(e){try{switch(e.type){case"normal":await this.processNormalMessage(e);break;case"bash-command":await this.processBashCommand(e);break;case"merge-request":await this.processMergeRequest(e);break;case"merge-pr":await this.processMergePr(e);break;case"new-session":await this.processNewSession(e);break;default:this.log("warn","COORDINATOR",`Unknown message type: ${e.type}`)}}finally{if("normal"!==e.type){const n=e.originalMessage.__localSequence;void 0!==n&&this.config.onCommandMessageProcessed?.(n)}}}async processNormalMessage(e){this.log("info","COORDINATOR","Processing normal message for SDK");const n=await this.config.handlers.onNormalMessage(e.originalMessage);this.enqueueAgentMessage(n)}async processBashCommand(e){this.log("info","COORDINATOR",`Processing bash command: ${e.content}`),await this.waitWorkerIdle(),this.setCommandRunning(!0);try{await this.config.handlers.onBashCommand(e.content,e.originalMessage)}finally{this.setCommandRunning(!1)}}async processMergeRequest(e){this.log("info","COORDINATOR","Processing merge-request command"),await this.waitWorkerIdle(),this.setCommandRunning(!0);try{await this.config.handlers.onMergeRequest(e.originalMessage)}finally{this.setCommandRunning(!1)}}async processMergePr(e){this.log("info","COORDINATOR","Processing merge-pr command"),await this.waitWorkerIdle(),this.setCommandRunning(!0);try{await this.config.handlers.onMergePr()}finally{this.setCommandRunning(!1)}}async processNewSession(e){this.log("info","COORDINATOR","Processing new-session command"),await this.waitWorkerIdle(),this.setCommandRunning(!0);try{await(this.config.handlers.onNewSession?.())}finally{this.setCommandRunning(!1)}}async waitWorkerIdle(){for(;"idle"!==this.getExecutionState();){if(this.isStopped)throw new Error("Coordinator stopped while waiting for idle");this.log("debug","COORDINATOR","Waiting for worker idle state"),await new Promise(e=>setTimeout(e,100))}}setWorkerState(e){if(this.workerState===e)return;const n=this.workerState;if(this.log("info","COORDINATOR",`Worker state: ${n} → ${e}`),this.workerState=e,"running"===e&&"idle"===n&&(this.runStartTime=Date.now(),this.config.workClient.sendWorkRunning(this.getActiveAgents()),this.lastActiveAgentsSignature=this.getActiveAgentsSignature(),this.clearIdleTimer()),"idle"===e&&"running"===n){let e;this.runStartTime&&(e=Date.now()-this.runStartTime,this.runStartTime=null),this.config.workClient.sendWorkerReady(e),this.lastActiveAgentsSignature=null,this.startIdleTimer()}}updateAgentRunning(e){this.setAgentRunning("default","Agent",e)}setAgentRunning(e,n,a){const t="running"===this.workerState,s=this.lastActiveAgentsSignature;a?this.agentRunningMap.set(e,{agentId:e,agentName:n,startedAt:Date.now()}):this.agentRunningMap.delete(e);const i=this.getActiveAgentsSignature();this.lastActiveAgentsSignature=i,this.tryUpdateWorkerState(),t&&"running"===this.workerState&&i!==s&&this.config.workClient.sendWorkRunning(this.getActiveAgents())}setBackgroundTaskRunning(e,n){e&&(n?this.backgroundTaskMap.set(e,{taskId:e,startedAt:Date.now()}):!this.backgroundTaskMap.delete(e)&&this.anonymousBackgroundTaskCount>0&&(this.anonymousBackgroundTaskCount-=1,this.log("debug","COORDINATOR",`Background task ${e} completed via anonymous fallback (remaining: ${this.anonymousBackgroundTaskCount})`)),this.tryUpdateWorkerState())}setAnonymousBackgroundTaskRunning(e){e?(this.anonymousBackgroundTaskCount+=1,this.log("debug","COORDINATOR",`Anonymous background task started (count: ${this.anonymousBackgroundTaskCount})`)):this.anonymousBackgroundTaskCount>0&&(this.anonymousBackgroundTaskCount-=1,this.log("debug","COORDINATOR",`Anonymous background task completed (count: ${this.anonymousBackgroundTaskCount})`)),this.tryUpdateWorkerState()}getActiveAgents(){return Array.from(this.agentRunningMap.values()).map(({agentId:e,agentName:n})=>({agentId:e,agentName:n}))}getActiveAgentsSignature(){const e=this.getActiveAgents().slice().sort((e,n)=>e.agentId.localeCompare(n.agentId));return JSON.stringify(e)}enqueueAgentMessage(e){if(this.isStopped)this.log("warn","COORDINATOR","Ignoring agent message - coordinator is stopped");else if(this.agentMessageQueue.push(e),this.agentMessageResolver){const e=this.agentMessageResolver;this.agentMessageResolver=null,e(this.agentMessageQueue.shift())}}hasAgentMessages(){return this.agentMessageQueue.length>0}getAgentQueueLength(){return this.agentMessageQueue.length}async waitForAgentMessage(){return this.isStopped?null:this.agentMessageQueue.length>0?this.agentMessageQueue.shift():new Promise(e=>{this.agentMessageResolver=e})}cancelAgentWait(){if(!this.agentMessageResolver)return;const e=this.agentMessageResolver;this.agentMessageResolver=null,e(null)}setCommandRunning(e){this.commandRunning!==e&&(this.commandRunning=e,this.tryUpdateWorkerState())}hasExecutionWork(){return this.commandRunning||this.agentRunningMap.size>0||this.backgroundTaskMap.size>0||this.anonymousBackgroundTaskCount>0||this.isDebouncing}getExecutionState(){return this.hasExecutionWork()?"running":"idle"}setDebouncing(e){this.isDebouncing!==e&&(this.isDebouncing=e,this.tryUpdateWorkerState())}tryUpdateWorkerState(){if(this.isStopped)return;const e=this.messageQueue.length>0||this.agentMessageQueue.length>0,n=this.hasExecutionWork(),a=!e&&!n;this.setWorkerState(a?"idle":"running")}startIdleTimer(){0!==this.idleTimeoutMs&&(this.idleTimeoutHandle||(this.idleTimeoutHandle=setTimeout(()=>{this.idleTimeoutHandle=null,this.isStopped||(this.log("info","COORDINATOR","Idle timeout reached, stopping task"),this.cancelAgentWait(),this.config.onIdleTimeout?.())},this.idleTimeoutMs)))}clearIdleTimer(){this.idleTimeoutHandle&&(clearTimeout(this.idleTimeoutHandle),this.idleTimeoutHandle=null)}getStatus(){return{state:this.workerState}}isActivelyExecuting(){return this.hasExecutionWork()}stop(){this.log("info","COORDINATOR","Stopping coordinator"),this.isStopped=!0,this.clearIdleTimer(),this.messageQueue=[],this.agentMessageQueue=[],this.backgroundTaskMap.clear(),this.anonymousBackgroundTaskCount=0,this.cancelAgentWait()}log(e,n,a){this.config.logger&&this.config.logger(e,n,a)}}function qt(e,n){const a={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:n}]}};e.sendTaskMessage(Da,a)}async function Ut(e){const{workingDirectory:n,workClient:a,repositoryId:t,gitServerId:s,logger:i,askUser:o}=e;if(i.info("[MERGE-PR] Executing merge-pr command"),t){try{const e=await bt(n),t=await mt(n),r=await async function(e,n){const a=Ye(e);try{return(await a.log([`origin/${n}..HEAD`])).total>0}catch{return!0}}(n,e);if(t||r){const c=await async function(e,n,a,t){let s="";s=e&&n?"You have uncommitted changes and unpushed commits. What would you like to do?":e?"You have uncommitted changes. What would you like to do?":"You have unpushed commits. What would you like to do?";const i=[{question:s,header:"Git Status",multiSelect:!1,options:[{label:"Pause",description:"Stop operation, handle git state manually"},{label:"Push",description:"Push changes and review before merging"},{label:"Push and Merge",description:"Push changes and merge PR immediately"}]}];try{const e=(await a(i)).answers[0];return e.startsWith("other:")?(t.info(`[MERGE-PR] User provided custom input: ${e}, defaulting to Pause`),"Pause"):{Pause:"Pause",Push:"Push","Push and Merge":"PushAndMerge"}[e]||"Pause"}catch(e){return t.error("[MERGE-PR] Ask user failed:",e),"Pause"}}(t,r,o,i);if("Pause"===c)return void qt(a,"Operation paused. Please handle git state and run merge again.");if(("Push"===c||"PushAndMerge"===c)&&(t&&(i.info("[MERGE-PR] Auto-committing changes"),await xt(n,"Auto-commit before merge")),i.info(`[MERGE-PR] Pushing branch ${e} to remote`),await _t(n,e,!1,s),"Push"===c))return void qt(a,"✅ All changes pushed to remote. You can now review and run merge again if everything looks good.")}const c=await a.sendMergePr();if(c.success)qt(a,`✅ PR merged successfully! Branch ${e} has been merged into the target branch.`);else{let e;switch(c.errorType){case"github_conflict":e="Merge conflict detected. Please resolve conflicts manually on GitHub and try again.";break;case"pr_not_open":e="PR is not open. The PR may have already been merged or closed.";break;case"permission_denied":e="Permission denied. You may not have permission to merge this PR.";break;case"merge_failed":e=`Merge failed: ${c.error||"Unknown error"}`;break;default:e=`Failed to merge PR: ${c.error||"Unknown error"}`}a.sendSystemErrorMessage(e)}}catch(e){i.error("[MERGE-PR] Failed:",e);const n=e instanceof Error?e.message:"Unknown error";a.sendSystemErrorMessage(`Failed to push or merge: ${n}`)}i.info("[MERGE-PR] Worker ready after merge-pr execution")}else a.sendSystemErrorMessage("Cannot merge: task has no git repository configured.")}function Gt(e,n){const a=e.updates?.repositoryId;return"string"==typeof a&&0!==a.length&&n.repositoryId!==a&&(n.repositoryId=a,D.writeTaskInput(n),!0)}function Lt(e,n,a,t={}){const s=a.sendAskUser(e),i=t.timeoutMs??18e5,o=t.onTimeout;return new Promise((e,t)=>{const r=setTimeout(()=>{n.delete(s);const i={type:"ask_user_response",answers:[],status:"timeout",reason:"timeout"};a.sendAskUserResponse(s,i),"abort_task"===o?(a.onTimeoutMessage?.("ask_user timed out. Task cancelled."),a.stopTask?.("ask_user_timeout"),t(new Error("Ask user request timed out"))):e(i)},i);n.set(s,n=>{clearTimeout(r),e(function(e){const n=e.status??"answered";return e.status&&e.reason?e:{...e,status:n,reason:e.reason??("timeout"===n?"timeout":"user")}}(n))})})}function Ft(e){const n=e.split("\n");for(;n.length>0&&""===n[0].trim();)n.shift();for(;n.length>0&&""===n[n.length-1].trim();)n.pop();const a=n.reduce((e,n)=>{if(""===n.trim())return e;const a=n.match(/^\s*/)[0].length;return Math.min(e,a)},1/0);return n.map(e=>e.slice(a)).join("\n")}const Wt=Ft("\n ## Title Setting Protocol:\n - MUST set a descriptive title using mcp__agentrix__change_title as your FIRST action when the user makes a request\n - This is mandatory, not optional - do this before any other work\n - Update the title if the conversation direction changes substantially\n"),Ht=Ft('\n ## Input Data Format (Conversation Stream)\n\n Messages come in this XML format. Pay attention to `seq` to understand the order.\n\n <msg seq="N" at="ISO_TIME" senderType="human|agent" senderId="id" senderName="name">\n content\n </msg>\n'),zt=Ft('\n ## Orchestration Decision Framework\n\n **Core Principle**: Analyze dependencies FIRST to choose orchestration mode.\n\n **Decision Rule**:\n - **No dependencies** (agents work independently) → Direct execution\n - **Has dependencies** (sequential, turn-taking, coordination) → Plan-Execute-Replan loop\n\n ### Mode 1: Direct Execution (No Dependencies)\n\n When agents can work independently with no coordination:\n - Single agent request\n - Parallel opinions (no need to build on each other)\n - Independent work tasks\n\n **Examples**:\n - "Claude, explain X" → invoke(claude)\n - "What do you both think?" → invoke(claude), invoke(codex)\n - "Claude, write parser. Codex, write formatter." → assign both\n\n ### Mode 2: Plan-Execute-Replan Loop (Has Dependencies)\n\n When work has sequential dependencies or coordination:\n\n **The Loop**:\n 1. **PLAN**: TodoWrite defines structure/order\n 2. **EXECUTE**: invoke/assign first agent\n 3. **WAIT**: Agent responds in next message batch\n 4. **REPLAN**: Update TODO (mark done), identify next\n 5. **REPEAT**: Continue until complete\n\n **Dependency types**:\n - **Sequential**: Agent B needs Agent A\'s output\n - **Turn-taking**: Debate/conversation structure (A→B→A)\n - **Coordination**: Multiple agents with defined roles\n\n **Example - Debate** (turn-taking dependency):\n ```\n User: "4-round debate on REST vs GraphQL"\n\n PLAN (TodoWrite):\n - [ ] Claude: Opening argument FOR REST\n - [ ] Codex: Counter argument FOR GraphQL\n - [ ] Claude: Rebuttal\n - [ ] Codex: Final response\n\n EXECUTE: invoke(claude, hint="You argue FOR REST. Present your opening argument.")\n WAIT: Claude responds with REST argument\n REPLAN: Mark done, next is codex\n EXECUTE: invoke(codex, hint="You argue FOR GraphQL. Counter the REST arguments.")\n WAIT: Codex responds with GraphQL argument\n REPLAN: Mark done, next is claude rebuttal\n EXECUTE: invoke(claude) // No hint needed - role already established from history\n REPEAT...\n ```\n\n **hint usage**: Use hint to reduce agent\'s attention cost or provide meta-context:\n - ✅ Role assignment: first turn of debate (hint="You argue FOR REST")\n - ✅ Focus guidance: (hint="Focus only on performance aspects")\n - ✅ Long/busy chat: help agent locate relevant context (hint="Respond to Alice\'s question about caching")\n - ✅ Multi-topic: clarify which thread to address (hint="Re: the API design discussion")\n - ❌ Short, clear context: agent can easily find what to respond to\n - ❌ Role already established: agent knows their role from recent history\n\n **Why TodoWrite**: Planner is event-driven, can\'t "wait" for responses. TodoWrite provides persistent state across turns.\n\n ### Best Practices\n\n - Match agent to user intent by reviewing capabilities (get_task_agents)\n - Review history (get_task_history) when context is unclear\n\n ### Common Mistakes\n\n - ❌ Invoke just because an agent spoke; only act on unmet user requests\n - ❌ Repeated or cascading invokes on the same request\n - ❌ Invoke multiple agents with dependencies simultaneously\n - ❌ Use TodoWrite for independent requests (over-engineering)\n - ❌ Forget to update TODO after agent responds\n'),Bt=Ft('\n You are Planner, orchestrating a chat group where Users and Agents interact.\n Your goal is to observe the conversation stream, analyze context, and direct appropriate agents via tools.\n\n ## Visibility Rules\n\n - Your text output is NOT shown to users, but IS visible to developers for debugging\n - Keep brief reasoning/analysis in your output to help developers understand your decisions\n - NEVER attempt to answer user questions directly - let agents handle all user interaction\n\n ## Output Format\n\n 1. Brief reasoning (for developer debugging)\n 2. Tool calls if needed\n 3. Final output: ONLY "✅" on a new line (no other text after it)\n'),Kt=Ft("\n # Task Delegation\n\n ## When to Delegate (use create_task)\n\n - Implementation work: writing code, editing files, running tests\n - Investigation: multi-file analysis, tracing bugs, code archaeology\n - Code reviews, audits, or quality scans\n - Producing artifacts: reports, plans, configs\n - Any work where the user is waiting for you to finish before the conversation can continue\n\n ## When to Respond Directly\n\n - Answering questions, explaining concepts\n - Quick file lookups to answer a specific question (1-2 reads is fine)\n - Short code snippets or examples in conversation\n - Discussion, planning, decision-making with the user\n\n ## Your Role in Conversation\n\n The conversation is for **discussion, decisions, and summaries** — not for executing work.\n\n - Discuss approaches, trade-offs, and options with the user\n - Make decisions together (or present recommendations)\n - Summarize task results when they come back\n - Coordinate and plan — then delegate execution to tasks\n\n ## Anti-Patterns (Do NOT do these in conversation)\n\n - ❌ **Code editing**: Don't write/edit code directly in conversation — create a task\n - ❌ **Research rabbit holes**: Don't grep → read → grep → read in conversation — delegate the investigation\n - ❌ **Building artifacts**: Any output that produces files (code, reports, configs) belongs in a task\n - ❌ **Running tests/builds**: Don't run test suites or build commands in conversation — create a task\n\n **Rule of thumb**: If you're about to *change* something or *produce* something, it's a task. If you're about to *answer* something, respond directly.\n\n ## After Delegating\n\n - User sees task creation confirmation immediately\n - Continue responding to user's other questions\n - You'll receive <sub-task-result-updated> when task completes\n - Briefly summarize the result to user — no deep analysis needed\n - Do NOT create duplicate sub-tasks unless explicitly asked\n\n ## Using emit_to_task Effectively\n\n emit_to_task sends follow-up instructions to a running or completed sub-task. Use it for:\n\n - **User adds requirements**: User says \"also add tests\" → emit to the existing task, don't create a new one\n - **Passing decisions**: You discussed options with user, user chose option B → emit the decision to the task\n - **Course correction**: Task went in wrong direction → emit new guidance\n - **Providing context**: Task asks a question → get answer from user → emit answer to task\n - **Retry after failure**: Task failed → emit instructions to retry with fixes\n\n Do NOT use emit_to_task to:\n - Start a completely different task (create a new task instead)\n - Send very long instructions (if the scope changed drastically, create a new task)\n\n ## Task Granularity\n\n - **One task = one coherent unit of work** (e.g., \"implement login page\", \"investigate memory leak\")\n - Don't create a task for a single trivial operation (e.g., \"read one file\")\n - Don't cram unrelated work into one task — split them so they can run in parallel\n - Multiple independent tasks CAN run in parallel\n"),Vt=Ft(`\n ${Bt}\n\n ${Ht}\n\n ${zt}\n`),Xt=Ft('\n ## Message Format\n\n Messages in this group chat are formatted as XML:\n\n <msg seq="N" at="ISO_TIME" senderType="human|agent" senderId="id" senderName="name">\n content\n </msg>\n\n You may also receive a `<hint>` block at the start:\n\n <hint>\n context or instruction from the orchestrator\n </hint>\n\n The hint provides context for your response (e.g., debate role, focus area).\n Follow the hint\'s guidance while responding to the conversation.\n\n When responding, just reply naturally - the system will handle formatting.\n');function Yt(e){const n=["# Available Agents",""];for(const a of e)a.description?n.push(`- **${a.name}** (${a.id}): ${a.description}`):n.push(`- **${a.name}** (${a.id})`);return n.join("\n")}function Jt(e,n){const a=n.find(n=>n.id===e);if(!a)return Yt(n);const t=n.filter(n=>n.id!==e),s=["# Group Context","",`You are \`${a.name}\`. `,"You are a member of this group chat."];if(a.description&&s.push(`Your role: ${a.description}`),t.length>0){s.push(""),s.push("## Other Agents in This Group"),s.push("");for(const e of t)e.description?s.push(`- **${e.name}**: ${e.description}`):s.push(`- **${e.name}**`)}return s.push(""),s.push(Xt),s.join("\n")}function Qt(e){const n={};for(const[a,t]of Object.entries(e))"string"==typeof t&&(n[a]=t);return n}function Zt(e){if("object"!=typeof e||null===e)return!1;const n=e;return"text"===n.type&&"string"==typeof n.text}function es(e){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:""}}function ns(e){const n=e.message?.content;return"string"==typeof n?n:Array.isArray(n)?n.filter(Zt).map(e=>e.text).join("\n").trim():""}function as(e){const n=e.usage.input_tokens-e.usage.cached_input_tokens,a={input_tokens:e.usage.input_tokens,output_tokens:e.usage.output_tokens,cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},cache_creation_input_tokens:0,cache_read_input_tokens:e.usage.cached_input_tokens,server_tool_use:{web_fetch_requests:0,web_search_requests:0},service_tier:"standard"};return{type:"result",subtype:"success",duration_ms:0,duration_api_ms:0,is_error:!1,num_turns:e.numTurns,result:e.result??"",stop_reason:null,total_cost_usd:0,usage:a,modelUsage:{[e.model]:{inputTokens:n>0?n:0,outputTokens:e.usage.output_tokens,cacheReadInputTokens:e.usage.cached_input_tokens,cacheCreationInputTokens:0,webSearchRequests:0,costUSD:0,contextWindow:0,maxOutputTokens:0}},permission_denials:[],uuid:crypto.randomUUID(),session_id:e.sessionId}}const ts="agentrix",ss="1.0.0";async function*is(e){yield e}let os;const rs=["Bash","Glob","Grep","ExitPlanMode","Read","Skill","SlashCommand","EnterPlanMode"],cs=["Glob","Grep","Read","Skill"],ps=["Read","Glob","Grep"],ls=["Read","Glob","Grep","TodoWrite"];function ds(e,n,a,t,s,i,o){const r=function(e){const{agentId:n,modeConfig:a,cwd:t,agentConfig:s}=e,{mode:i,groupAgents:o}=a,r=s.customSystemPrompt,c=s.systemPromptMode??"append",p=function(e){const{mode:n,supportChangeTitle:a}=e;switch(n){case"work":return a?Wt:void 0;case"companion_shadow":case"companion_chat":case"reply":case"group_chat":return;case"chat":return Kt;case"group_work":{const e=[];return a&&e.push(Wt),e.join("\n\n")}}}(a);if("group_chat"===i||"group_work"===i){const e=[Vt];return o&&o.length>0&&e.push(Yt(o)),p&&e.push(p),e.join("\n\n")}const l="reply"===i&&o&&o.length>0?Jt(n,o):void 0,d={},u=process.env.AGENTRIX_COMPANION_HOME||process.env.AGENTRIX_COMPANION_WORKSPACE;u&&(d.COMPANION_HOME=u,d.COMPANION_MODE="companion_shadow"===i?"shadow":"chat");const m=Object.keys(d).length>0?d:void 0,g=r?en(r,t,m):void 0;if("replace"===c&&g){const e=[g];return l&&e.push(l),p&&e.push(p),e.join("\n\n")}const h=[];return l&&h.push(l),p&&h.push(p),g&&h.push(g),{type:"preset",preset:"claude_code",append:h.length>0?h.join("\n\n"):void 0}}({agentId:e,modeConfig:n.modeConfig,cwd:n.cwd,agentConfig:a}),c=function(e){switch(e){case"work":case"companion_shadow":return;case"chat":case"companion_chat":return[...rs];case"reply":return[...cs];case"group_chat":return[...ps];case"group_work":return[...ls]}}(n.modeConfig.mode),p=function(e,n){const a={},t=e=>async(n,a,t)=>await e(n,a,t)??{},s=new Set([...Object.keys(e),...n?Object.keys(n):[]]);for(const i of s){const s=[],o=e[i];o&&s.push(t(o));const r=n?.[i];r&&s.push(t(r)),a[i]=[{hooks:s}]}return a}(n.hooks??{},t),l=function(){if(void 0!==os)return os??void 0;const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(e){const n=function(e){const n=e.trim();if(n){if(n.includes("/")||n.includes("\\")||n.startsWith(".")){const e=we(n)?n:ke(n);return te(e)?e:void 0}return function(e){const n="win32"===process.platform?"where":"which",a=Pe(n,[e],{encoding:"utf-8"});if(0===a.status)return a.stdout.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0)}(n)}}(e);if(n)return os=n,n}os=null}(),d=i?function(e){const{modeConfig:n,tools:a,serverName:t=ts,serverVersion:s=ss}=e,{mode:i,supportChangeTitle:o}=n,r=[];switch(i){case"work":o&&r.push(a.changeTaskTitle),r.push(a.askUser),r.push(a.getTaskHistory);break;case"chat":r.push(a.createTask),r.push(a.replyToSubTask),r.push(a.askUser),r.push(a.getTaskHistory),r.push(a.listSubTask);break;case"group_chat":r.push(a.invoke),r.push(a.createSoloTask),r.push(a.createGroupTask),r.push(a.replyToSubTask),r.push(a.getTaskAgents),r.push(a.getTaskHistory);break;case"group_work":r.push(a.invoke),r.push(a.assign),o&&r.push(a.changeTaskTitle),r.push(a.getTaskAgents),r.push(a.getTaskHistory);break;case"reply":r.push(a.getTaskHistory),r.push(a.askUser);break;case"companion_chat":r.push(a.createTask),r.push(a.replyToSubTask),r.push(a.askUser),r.push(a.getTaskHistory),r.push(a.uploadFile),r.push(a.listAgents);break;case"companion_shadow":r.push(a.getTaskHistory),r.push(a.readConversation),r.push(a.listAgents)}("companion_chat"===i||"companion_shadow"===i)&&(r.push(a.listTasks),r.push(a.updateAgentInfo),r.push(a.sendReminder));const c=Ke({name:t,version:s,tools:r}),p=r.map(e=>((e,n)=>`mcp__${e}__${n}`)(t,e.name));return{server:c,toolNames:p}}({modeConfig:n.modeConfig,tools:i}):void 0,u={...d?.server?{agentrix:d.server}:{},...n.mcpServers??{},...s??{}};return{stderr:n.stderr,model:a.customModel||n.model,fallbackModel:a.customFallbackModel,cwd:n.cwd,resume:n.agentSessionId,permissionMode:a.customPermissionMode||"bypassPermissions",settingSources:["user","project","local"],systemPrompt:r,tools:c,mcpServers:u,plugins:a.customPlugins,abortController:n.abortController,env:n.env?Qt(n.env):void 0,pathToClaudeCodeExecutable:l,maxTurns:a.customMaxTurns??n.maxTurns??o,extraArgs:a.customExtraArgs,canUseTool:n.canUseTool,hooks:p,outputFormat:n.structuredOutputSchema}}class us{constructor(e,n,a,t){this.agentId=e,this.agentConfig=n,this.agentHooks=a,this.agentMcpServers=t}getAgentConfiguration(){return this.agentConfig}getHooks(){return this.agentHooks}getMcpServers(){return this.agentMcpServers}async executeHook(e,n,a){await async function(e,n,a,t){if(!e)return;const s=e[n];if(!s)return;const i=t||(e=>console.log(e));try{i(`[${n}] Executing hook...`);const e=new AbortController,t=setTimeout(()=>{e.abort()},6e4);try{await s(a,"",{signal:e.signal}),i(`[${n}] Hook executed successfully`)}finally{clearTimeout(t)}}catch(e){console.warn(`[${n}] Hook failed (non-fatal):`,e)}}(this.agentHooks,e,n,a)}async run(e,n){const a=this.agentConfig,t="string"==typeof e?es(e):e;let s=null;const i=Ve({prompt:is(t),options:ds(this.agentId,n,a,this.agentHooks,this.agentMcpServers,n.agentrixTools)});for await(const e of i)if(console.log("ClaudeRunner.run: received message",JSON.stringify(e)),"result"===e.type){s=e;break}if(!s)throw new Error("ClaudeRunner.run: missing result message");return s}async*runStreamed(e,n){const a=this.agentConfig,t="string"==typeof e?es(e):e,s=Ve({prompt:is(t),options:ds(this.agentId,n,a,this.agentHooks,this.agentMcpServers,n.agentrixTools)});for await(const e of s)if(yield e,"result"===e.type)break}loop(e){const n=e.abortController,a=this.agentConfig,t=ds(this.agentId,e,a,this.agentHooks,this.agentMcpServers,e.agentrixTools);let s=!1;const i=[];let o=null;const r=()=>{if(!s&&(s=!0,o)){const e=o;o=null,e(null)}},c=async function*(){for(;!s&&!n.signal.aborted;){if(i.length>0){yield i.shift();continue}const e=await new Promise(e=>{o=e});if(!e)break;yield e}},p=async function*(){try{const e=Ve({prompt:c(),options:t});for await(const n of e)yield n}finally{r()}}();return n.signal.addEventListener("abort",r,{once:!0}),{push:e=>{if(console.log("ClaudeRunner.loop.push:",JSON.stringify(e,null,2)),s)return;const n="string"==typeof e?es(e):e;if(o){const e=o;return o=null,void e(n)}i.push(n)},events:p}}}function ms(e){return{type:"system",subtype:"init",apiKeySource:"temporary",betas:[],claude_code_version:"codex",cwd:e.cwd,tools:[],mcp_servers:[],model:e.model??"unknown",permissionMode:"default",slash_commands:[],output_style:"codex",skills:[],plugins:[],uuid:M(),session_id:e.sessionId}}function gs(e,n){const a=M();return n.set(e,a),a}function hs(e,n){return n.get(e)||e}function fs(e,n){return"thread.started"===e.type||"turn.started"===e.type||"turn.completed"===e.type||"turn.failed"===e.type?null:"item.started"===e.type?function(e,n){switch(e.type){case"command_execution":return function(e,n){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:gs(e.id,n),name:"Bash",input:{command:e.command}}]},parent_tool_use_id:null,session_id:""}}(e,n);case"file_change":return function(e,n){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:gs(e.id,n),name:"Edit",input:{changes:e.changes.map(e=>({kind:e.kind,path:e.path}))}}]},parent_tool_use_id:null,session_id:""}}(e,n);case"mcp_tool_call":return function(e,n){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:gs(e.id,n),server_name:e.server,name:e.tool,input:e.arguments}]},parent_tool_use_id:null,session_id:""}}(e,n);case"web_search":return function(e,n){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:gs(e.id,n),name:"web_search",input:{query:e.query}}]},parent_tool_use_id:null,session_id:""}}(e,n);default:return null}}(e.item,n):"item.completed"===e.type?function(e,n){switch(e.type){case"agent_message":return function(e){return{type:"assistant",message:{id:e.id,type:"message",container:null,role:"assistant",content:[{citations:null,type:"text",text:e.text}],model:"",usage:{},stop_reason:null,context_management:null,stop_sequence:null},parent_tool_use_id:null,session_id:"",uuid:M().toString()}}(e);case"reasoning":default:return null;case"command_execution":return function(e,n){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:hs(e.id,n),content:"failed"===e.status?"Command execution failed":e.aggregated_output||""}]},parent_tool_use_id:null,session_id:""}}(e,n);case"file_change":return function(e,n){const a=n.get(e.id),t=a??gs(e.id,n),s=!a;(e.changes||[]).map(e=>`${e.kind}: ${e.path}`);const i={type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:t,name:"Edit",input:{changes:(e.changes||[]).map(e=>({kind:e.kind,path:e.path}))}}]},parent_tool_use_id:null,session_id:""},o={type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:t,content:"failed"===e.status?"File changes failed":"File changes completed"}]},parent_tool_use_id:null,session_id:""};return s?[i,o]:o}(e,n);case"mcp_tool_call":return function(e,n){const a=hs(e.id,n),t="failed"===e.status&&e.error;return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:a,is_error:t,content:t?e.error.message:e.result?.content||""}]},parent_tool_use_id:null,session_id:""}}(e,n);case"web_search":return function(e,n){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:hs(e.id,n),content:{type:"web_search_result",results:[]}}]},parent_tool_use_id:null,session_id:""}}(e,n);case"todo_list":return function(e){return{type:"assistant",message:{role:"assistant",content:`📋 Todo List:\n${e.items.map(e=>`${e.completed?"✓":"○"} ${e.text}`).join("\n")}`},parent_tool_use_id:null,session_id:""}}(e);case"error":return function(e){return{type:"assistant",message:{role:"assistant",content:`❌ Error: ${e.message}`},parent_tool_use_id:null,session_id:""}}(e)}}(e.item,n):null}let xs;class vs{createCodex(e){const n={},a=function(){if(void 0!==xs)return xs??void 0;const e=process.env.AGENTRIX_CODEX_PATH?.trim();return e?(xs=e,e):0===Pe("codex",["--version"],{stdio:"ignore"}).status?(xs="codex",xs):void(xs=null)}();return a&&(n.codexPathOverride=a),e.env&&(n.env=Qt(e.env)),new tn(Object.keys(n).length>0?n:void 0)}getAgentConfiguration(){return null}getHooks(){}getMcpServers(){}async executeHook(e,n,a){}async run(e,n){const a=n.abortController,t=this.createCodex(n),s={workingDirectory:n.cwd,model:n.model,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},i=n.agentSessionId?t.resumeThread(n.agentSessionId,s):t.startThread(s),o=await i.run("string"==typeof e?e:ns(e),{signal:a.signal,outputSchema:n.structuredOutputSchema?.schema||void 0}),r=i.id??n.agentSessionId??"unknown",c=o.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0};return as({sessionId:r,model:n.model??"unknown",numTurns:1,usage:c,result:o.finalResponse??""})}async*runStreamed(e,n){const a=n.abortController,t=this.createCodex(n),s={workingDirectory:n.cwd,model:n.model,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},i=n.agentSessionId?t.resumeThread(n.agentSessionId,s):t.startThread(s),{events:o}=await i.runStreamed("string"==typeof e?e:ns(e),{signal:a.signal,outputSchema:n.structuredOutputSchema?.schema||void 0});let r=n.agentSessionId||"",c="",p={input_tokens:0,cached_input_tokens:0,output_tokens:0};const l=new Map,d={get:e=>l.get(e),set:(e,n)=>{l.set(e,n)}};for await(const e of o){if("thread.started"===e.type&&(r=e.thread_id,yield ms({sessionId:r,cwd:n.cwd,model:n.model})),"turn.completed"===e.type){e.usage&&(p=e.usage);break}if("turn.failed"===e.type)throw new Error(e.error.message);if("error"===e.type)throw new Error(e.message);if("item.completed"===e.type&&"agent_message"===e.item.type&&e.item.text&&(c=e.item.text),"item.started"===e.type||"item.completed"===e.type){const n=fs(e,d);if(!n)continue;const a=Array.isArray(n)?n:[n];for(const e of a)yield e}}const u=as({sessionId:r,model:n.model??"unknown",numTurns:1,usage:p,result:c});yield u}loop(e){const n=e.abortController,a=this.createCodex(e),t={workingDirectory:e.cwd,model:e.model,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0};let s=e.agentSessionId?a.resumeThread(e.agentSessionId,t):a.startThread(t),i=!1;const o=[];let r=null,c=e.agentSessionId??null,p=0;const l=()=>{if(!i&&(i=!0,r)){const e=r;r=null,e(null)}},d=e=>"string"==typeof e?e:ns(e),u=async function*(){try{for(;!i&&!n.signal.aborted;){const a=o.length>0?o.shift():await new Promise(e=>{r=e});if(!a)break;let t="";const l=new Map,u={get:e=>l.get(e),set:(e,n)=>{l.set(e,n)}},{events:m}=await s.runStreamed(d(a),{signal:n.signal,outputSchema:e.structuredOutputSchema?.schema||void 0});for await(const n of m){if(i)break;if("thread.started"!==n.type){if("turn.completed"===n.type){c&&(yield as({sessionId:c,model:e.model??"unknown",numTurns:p+1,usage:n.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0},result:t}));break}if("turn.failed"===n.type)throw new Error(n.error.message);if("error"===n.type)throw new Error(n.message);if("item.started"===n.type||"item.completed"===n.type){"item.completed"===n.type&&"agent_message"===n.item.type&&n.item.text&&(t=n.item.text);const e=fs(n,u);if(!e)continue;const a=Array.isArray(e)?e:[e];for(const e of a)yield e}}else c=n.thread_id,yield ms({sessionId:c,cwd:e.cwd,model:e.model})}p+=1}}finally{l()}}();return n.signal.addEventListener("abort",l,{once:!0}),{push:e=>{if(console.log("CodexRunner.loop.push:",JSON.stringify(e,null,2)),!i){if(r){const n=r;return r=null,void n(e)}o.push(e)}},events:u}}}function bs(e,n,a){e&&e(n,"AGENT",a)}const ys=["PreToolUse","PostToolUse","SessionStart","SessionEnd","UserPromptSubmit","Stop","SubagentStop","PreCompact","Notification","RepositoryInit"];function ws(e){const n={};for(const a of ys){const t=e[a];"function"==typeof t&&(n[a]=t,console.log(`[Hook Loader] ✓ Loaded hook: ${a}`))}const a=Object.keys(n).length;return 0===a?console.warn("[Hook Loader] No valid hooks found in module"):console.log(`[Hook Loader] Successfully loaded ${a} hook(s)`),n}class ks{static pool=new Map;static async create(e,n,a){const t=this.pool.get(n);if(t)return t;let s;if("claude"===e){const e=await async function(e){const{agentId:n,agentDir:a,logger:t}=e;if(!n||"default"===n)return{customSystemPrompt:void 0,customModel:void 0,customFallbackModel:void 0,customMaxTurns:void 0,customExtraArgs:void 0,customPermissionMode:void 0,customPlugins:[],systemPromptMode:"append",customPRPromptTemplate:void 0,prPromptMode:"append",customSdkMcpTools:void 0};try{bs(t,"info",`Loading agent: ${n}`);const e=await nn({agentId:n,framework:"claude",agentDir:a});if(!e.claude)return bs(t,"warn",`No claude configuration found for agent ${n}`),{customSystemPrompt:void 0,customModel:void 0,customFallbackModel:void 0,customMaxTurns:void 0,customExtraArgs:void 0,customPermissionMode:void 0,customPlugins:[],systemPromptMode:"append",customPRPromptTemplate:void 0,prPromptMode:"append",customSdkMcpTools:void 0};const s=e.claude,i=s.plugins.map(e=>({type:"local",path:e})),o=a||an().resolveAgentDir(n),r=s.config.sdkMcpTools?.map(e=>he(o,"claude",e)),c={customSystemPrompt:s.systemPrompt,customModel:s.config.model,customFallbackModel:s.config.fallbackModel,customMaxTurns:s.config.maxTurns,customExtraArgs:s.config.extraArgs,customPermissionMode:s.config.settings?.permissionMode,customPlugins:i,systemPromptMode:s.config.systemPrompt?.mode??"append",customPRPromptTemplate:s.prPromptTemplate,prPromptMode:s.config.pullRequestPrompt?.mode??"append",customSdkMcpTools:r};return bs(t,"info",`Agent ${n} loaded successfully (${i.length} plugins)`),c}catch{return bs(t,"error",`Failed to load agent: ${n}`),{customSystemPrompt:void 0,customModel:void 0,customFallbackModel:void 0,customMaxTurns:void 0,customExtraArgs:void 0,customPermissionMode:void 0,customPlugins:[],systemPromptMode:"append",customPRPromptTemplate:void 0,prPromptMode:"append",customSdkMcpTools:void 0}}}({agentId:n,agentDir:a?.agentDir,logger:a?.logger});let t,i;a?.context&&n&&"default"!==n&&(t=await async function(e,n,a){if(e&&"default"!==e)try{const t=I(),s=n||t.resolveAgentDir(e),i=he(s,"claude");return await async function(e,n){const a=K(e,"hooks");if(!H(a))return{};const t=[K(a,"dist","index.mjs"),K(a,"dist","index.js"),K(a,"index.mjs"),K(a,"index.js")];let s=null;for(const e of t)if(H(e)){s=e;break}if(!s)return console.warn(`[Hook Loader] Hooks not built: ${a}`),console.warn("[Hook Loader] To build hooks, run:"),console.warn(`[Hook Loader] cd ${a}`),console.warn("[Hook Loader] npm install && npm run build"),console.warn("[Hook Loader] Or place hooks directly in:"),console.warn(`[Hook Loader] ${K(a,"index.js")} or ${K(a,"index.mjs")}`),{};try{console.log(`[Hook Loader] Loading hooks: ${s}`);const e=`${Le(s).href}?t=${Date.now()}`,a=await import(e);if("function"==typeof a.default){if(n)return console.log("[Hook Loader] Using factory pattern with AgentrixContext"),ws(a.default(n));console.warn("[Hook Loader] Factory function found but no context provided, skipping factory")}return ws(a)}catch(e){throw console.error(`[Hook Loader] Failed to load hooks from ${s}:`,e),new Error(`Hook loading failed: ${e instanceof Error?e.message:String(e)}`)}}(i,a)}catch(e){return void console.warn("[AgentRunners] Failed to load hooks:",e)}}(n,a.agentDir,a.context)),a?.context&&e.customSdkMcpTools&&e.customSdkMcpTools.length>0&&(i=await async function(e,n,a){const t={};for(const s of e)try{a&&a("info","MCP",`Loading SDK MCP tools from: ${s}`);const e=await import(s),i=e.default||e;if(!i){a&&a("warn","MCP",`No default export found in ${s}`);continue}const o="function"==typeof i?i(n):i,r=o.name;t[r]=o,a&&a("info","MCP",`Loaded MCP server: ${r}`)}catch(e){a&&a("error","MCP",`Failed to load SDK MCP tools from ${s}: ${e instanceof Error?e.message:String(e)}`)}return t}(e.customSdkMcpTools,a.context,a.logger)),s=new us(n,e,t,i)}else s=new vs;return this.pool.set(n,s),s}static release(e){this.pool.delete(e)}static releaseAll(){this.pool.clear()}}class Is{constructor(e){this.workingDirectory=e}async listFiles(e=3){const n=[];return this.listFilesRecursively(this.workingDirectory,n,"",e,0),n}async readFile(e){try{const n=z.join(this.workingDirectory,e);return L.existsSync(n)?L.readFileSync(n,"utf-8"):null}catch{return null}}async fileExists(e){const n=z.join(this.workingDirectory,e);return L.existsSync(n)}listFilesRecursively(e,n,a,t,s){if(!(s>t))try{const i=L.readdirSync(e,{withFileTypes:!0});for(const o of i){const i=a?`${a}/${o.name}`:o.name;o.isDirectory()?T.includes(o.name)||this.listFilesRecursively(z.join(e,o.name),n,i,t,s+1):o.isFile()&&n.push(i)}}catch(e){}}}class Ss{constructor(e){this.params=e}state=null;autoCommitPolicy="enabled";async setup(){const{options:e,handlers:n}=this.params,{userId:a,taskId:t,cwd:s}=e;if(!s)throw new Error("[WORKSPACE] Missing cwd for workspace setup");const i=D.getWorkspaceState(a,t),o=e.repositorySourceType,r={...e,repositorySourceType:o},{initialCommitHash:c,isGitRepository:p,autoCommitPolicy:l}=await this.ensureWorkspace(r,n,i?.initialCommitHash);await D.writeWorkspaceState(a,t,{initialized:!0,initializedAt:(new Date).toISOString(),cwd:s,repositorySourceType:r.repositorySourceType,userCwd:e.userCwd,forceUserCwd:e.forceUserCwd,gitUrl:e.gitUrl,baseBranch:e.baseBranch,taskRepositoryId:e.taskRepositoryId,initialCommitHash:c});const d=await async function(e,n,a,t,s={}){return async function(e,n,a,t,s,i={}){if(!await lt(e))return{currentCommitHash:"",hadUncommittedChanges:!1,hasNewCommits:!1,lastSentCommitHash:void 0,patchPath:"",diffStats:void 0};const o=await mt(e),r=o,c=i.autoCommitOnDirty??!0;o&&c&&await xt(e,t);const p=await gt(e),l=s||D.getWorkspaceState(n,a)?.initialCommitHash;if(!l)throw new Error(`Initial commit hash not found for task ${a}`);const d=await D.readLastSentCommitHash(n,a),u=p!==(d??l),m=D.resolveDataDir(n,a);return{currentCommitHash:p,hadUncommittedChanges:r,hasNewCommits:u,lastSentCommitHash:d??void 0,patchPath:await Dt(e,l,p,m),diffStats:await vt(e,l,p)}}(e,n,a,$t("recover from previous session",a),t,s)}(s,a,t,c,{autoCommitOnDirty:"enabled"===l});return this.state={cwd:s,initialCommitHash:c,isGitRepository:p,gitStateResult:d},this.autoCommitPolicy=l,p&&!e.taskRepositoryId&&await async function(e,n){try{const a=await async function(e){try{const n=Ye(e),a=(await n.getRemotes(!0)).find(e=>"origin"===e.name);if(!a?.refs?.fetch)return null;const t=a.refs.fetch,s=t.match(/^git@([^:]+):(.+)\/(.+?)(?:\.git)?$/);if(s){const[,e,n,a]=s;return{url:t,host:e.split("-")[0],owner:n,repo:a}}const i=t.match(/^https?:\/\/([^/]+)\/(.+)\/(.+?)(?:\.git)?$/);if(i){const[,e,n,a]=i;return{url:t,host:e,owner:n,repo:a}}return null}catch(e){return console.error("[GIT] Failed to get remote info:",e),null}}(e);if(!a)return void console.log("[REPO] No origin remote found, skipping repository association");if(!n?.onRepositoryDetected)return;console.log(`[REPO] Detected remote: ${a.host}/${a.owner}/${a.repo}`),n.onRepositoryDetected(a)}catch(e){console.error("[REPO] Failed to send repository association:",e)}}(s,n),this.state}getState(){if(!this.state)throw new Error("[WORKSPACE] Workspace not initialized");return this.state}getCwd(){return this.getState().cwd}getInitialCommitHash(){return this.getState().initialCommitHash}getGitStateResult(){return this.getState().gitStateResult}async prepareResultArtifacts(e={}){const{cwd:n,initialCommitHash:a,isGitRepository:t}=this.getState(),{userId:s,taskId:i}=this.params.options;if(!t||!a)return{};const o=e.autoCommitOnDirty??"enabled"===this.autoCommitPolicy;if(await mt(n)&&o)try{const e=$t("result update",i);await xt(n,e)}catch(n){e.onCommitError?.(n)}const r=await gt(n);try{await async function(e,n,a,t,s){return Dt(e,t,s,D.resolveDataDir(n,a))}(n,s,i,a,r)}catch(n){e.onPatchError?.(n)}const c=await vt(n,a,r);if(0===c.files.length)return{currentCommitHash:r};const p=await async function(e){const n=new Is(e);return S(n)}(n),l=await D.readLastSentCommitHash(s,i);return l&&l===r?{currentCommitHash:r}:{currentCommitHash:r,artifacts:{commitHash:r,stats:c,preview:p}}}async ensureWorkspace(e,n,a){const t=e.repositorySourceType;return"git-server"===t?this.ensureGitServerWorkspace(e,n,a):"directory"===t?this.ensureDirectoryWorkspace(e,n,a):this.ensureTemporaryWorkspace(e,n,a)}async ensureGitServerWorkspace(e,n,a){const{cwd:t,gitUrl:s,taskId:i,baseBranch:o,gitServerId:r}=e;if(!s)throw new Error("[WORKSPACE] gitUrl is required for git-server mode");const c=await lt(t),p=ft(t);if(!c){if(!p)throw new Error(`[WORKSPACE] Directory ${t} exists but is not a git repository.`);const e=await async function(e,n,a,t,s){const i=Ct(a),o=await lt(e);if(!ft(e)&&!o)throw new Error(`Directory ${e} exists but is not a git repository`);const r=await At(s);return ft(e)?(r?(console.log("[GIT] Using GIT_ASKPASS credential injection for clone"),await async function(e,n,a){const t=fe(a);te(t)||re(t,{recursive:!0});const s=St();try{await pt("git",["clone",n,a],{env:Tt(s,e)})}finally{ue(s)}}(r,n,e),s&&await Rt(e,s)):await async function(e,n){const a=fe(n);te(a)||re(a,{recursive:!0});const t=Ye();await t.clone(e,n)}(n,e),await ut(e,i,t),await gt(e)):(await yt(e,"origin",n),r&&(console.log("[GIT] Using GIT_ASKPASS credential injection for fetch"),await async function(e,n){const a=St();try{await pt("git",["fetch","origin"],{cwd:n,env:Tt(a,e)})}finally{ue(a)}}(r,e),s&&await Rt(e,s)),await ut(e,i,t),await gt(e))}(t,s,i,o,r)||await gt(t);return{initialCommitHash:this.resolveInitialCommitHash(a,e,"none"),isGitRepository:!0,autoCommitPolicy:"enabled"}}return await yt(t,"origin",s),this.tryResolveDirtyRepo(e,n,a)}async ensureDirectoryWorkspace(e,n,a){const{cwd:t,taskId:s,userCwd:i}=e;if(await lt(t))return this.tryResolveDirtyRepo(e,n,a);if(!ft(t))return{initialCommitHash:"",isGitRepository:!1,autoCommitPolicy:"enabled"};{if(!i)return{initialCommitHash:"",isGitRepository:!1,autoCommitPolicy:"enabled"};const e=i.replace(/^~/,J());if(ft(e))return{initialCommitHash:"",isGitRepository:!1,autoCommitPolicy:"enabled"};if(!await lt(e))return{initialCommitHash:"",isGitRepository:!1,autoCommitPolicy:"enabled"};await ht(e)||await dt(e),await async function(e,n,a){const t=e.replace(/^~/,J());if(!await lt(t))throw new Error(`Directory ${t} is not a git repository. Worktrees can only be created from existing git repositories.`);if(!await ht(t))throw new Error(`Cannot create worktree: repository at ${t} has no commits. Please create an initial commit first: cd ${t} && git add . && git commit -m 'Initial commit'`);const s=Ct(a),i=(await async function(e){const n=Ye(e),a=(await n.raw(["worktree","list","--porcelain"])).trim().split("\n").filter(Boolean),t=[];let s=null;for(const e of a)if(e.startsWith("worktree "))s&&t.push(s),s={path:e.replace("worktree ","").trim(),branch:null,commit:"",isMain:0===t.length};else if(s)if(e.startsWith("HEAD "))s.commit=e.replace("HEAD ","").trim();else{if(e.startsWith("branch ")){const n=e.replace("branch ","").trim();s.branch=n.replace("refs/heads/","");continue}e.startsWith("detached")&&(s.branch=null)}return s&&t.push(s),t}(t)).find(e=>e.path===n);if(i){if(i.branch&&i.branch!==s)throw new Error(`Worktree at ${n} is already attached to branch ${i.branch}. Remove it before retrying: git worktree remove ${n}`);return{initialCommitHash:await gt(n)}}const o=Ye(t),r=(await o.branchLocal()).all.includes(s);if(te(n)&&!ft(n))throw new Error(`Worktree directory already exists at ${n}. This may be from a previous task. To clean up: git worktree remove ${n} OR rm -rf ${n}`);try{r?await o.raw(["worktree","add",n,s]):await async function(e,n,a,t="HEAD"){const s=fe(n);if(te(s)||re(s,{recursive:!0}),te(n)&&!ft(n))throw new Error(`Worktree directory already exists at ${n}`);const i=Ye(e);await i.raw(["worktree","add","-b",a,n,t])}(t,n,s,"HEAD")}catch(e){try{await async function(e,n,a=!1){const t=Ye(e),s=["worktree","remove"];a&&s.push("--force"),s.push(n),await t.raw(s)}(t,n,!0)}catch{}throw e}return{initialCommitHash:await gt(n)}}(e,t,s)}return this.tryResolveDirtyRepo(e,n,a)}async ensureTemporaryWorkspace(e,n,a){const{cwd:t,taskId:s}=e;if(!await lt(t)){await async function(e,n,a){return{initialCommitHash:await Mt(e,n,a)}}(t,s,n),await ut(t,`agentrix/${s}`,e.baseBranch);const i=await gt(t);return{initialCommitHash:this.resolveInitialCommitHash(a,i,"none"),isGitRepository:!0,autoCommitPolicy:"enabled"}}return this.tryResolveDirtyRepo(e,n,a)}async tryResolveDirtyRepo(e,n,a){let t,s=null,i="enabled";if(await async function(e){return!!await lt(e)&&await mt(e)}(e.cwd)){const a=n?.onUncommittedChanges?await n.onUncommittedChanges():"Ignore";if(await async function(e,n){switch(n){case"Ignore":console.log("[GIT] User chose to ignore uncommitted changes");break;case"Commit":console.log("[GIT] Auto-committing uncommitted changes"),await xt(e,"WIP: Auto-commit before task");break;case"Stash":console.log("[GIT] Stashing uncommitted changes"),await async function(e){const n=Ye(e);await n.stash(["push"])}(e);break;case"Abort":throw new Error("Task aborted by user due to uncommitted changes")}}(e.cwd,a),"Abort"===a)throw new Error("Task aborted by user due to uncommitted changes");s=a,"Ignore"===a&&(i="disabled_by_ignore")}if(await ht(e.cwd)||await dt(e.cwd),"Ignore"===s){const n=`agentrix/${e.taskId}`;t=await bt(e.cwd)===n?"none":"kept"}else t=await this.tryResolveBranchMismatch(e);const o=await gt(e.cwd);return{initialCommitHash:this.resolveInitialCommitHash(a,o,t),isGitRepository:!0,autoCommitPolicy:i}}resolveInitialCommitHash(e,n,a){return e?"kept"===a?n:e:n}async tryResolveBranchMismatch(e){const n=`agentrix/${e.taskId}`;return await bt(e.cwd)===n?"none":(await ut(e.cwd,n,e.baseBranch),"switched")}}const Ts=_e.object({title:_e.string().describe("Concise PR title following conventional commits format (feat/fix/docs/refactor/test/chore: description), maximum 50 characters"),description:_e.string().describe("Detailed PR description explaining: what changed, why these changes were necessary, any important technical decisions, and impact on existing functionality"),userMessage:_e.string().describe("Friendly message to display to the user, summarizing the PR creation. Should be concise and informative.")}),Es=Me(Ts,{target:"draft-07"}),Cs=Me(Ts);function As(e){if("success"!==e.subtype)throw new Error("PR response failed before structured output was returned");const n=e;return n.structured_output?Ts.parse(n.structured_output):function(e){if(!e.trim())throw new Error("PR response was empty");const n=function(e){const n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);return n?n[1].trim():e.trim()}(e),a=JSON.parse(n);return Ts.parse(a)}(n.result??"")}class Rs{chain=Promise.resolve();run(e){const n=this.chain.then(e,e);return this.chain=n.then(()=>{},()=>{}),n}}class _s{constructor(e,n,a){this.credentials=e,this.options=n,this.workingDirectory=a;const t=this.options.input,{taskId:s,userId:i}=t;this.logger=N({type:"worker",taskId:s}),this.currentAgentSessionId="agentSessionId"in t?t.agentSessionId:void 0;const o=t.taskAgents||[];this.taskAgentsMap=new Map(o.map(e=>[e.id,e]));const r=this.taskAgentsMap.size>1;this.primaryAgentId=r?"planner":t.agentId,this.primaryAgentName=r?"planner":this.taskAgentsMap.get(t.agentId)?.name??"unknown";const c=this.createWorkerClientConfig(i,s,a),p=D.resolveDataDir(i,s);this.historyDb=Sa({dataDir:p,taskId:s}),this.workClient=new Pa(c.config,{...c.handlers,historyDb:this.historyDb}),this.coordinator=this.createMessageCoordinator(this.workClient,this.options.idleTimeoutSecond),this.agentContext=new Oa({logger:this.logger,socketClient:this.workClient.client,taskId:t.taskId,userId:t.userId,chatId:t.chatId,rootTaskId:t.rootTaskId||t.taskId,parentTaskId:t.parentTaskId||null,workingDirectory:this.workingDirectory,taskAgents:t.taskAgents||[],serverUrl:D.serverUrl,taskDataKey:this.options.dataEncryptionKey}),this.agentrixTools=this.createAgentrixTools();const l={...Et(this.options.input),cwd:this.workingDirectory};this.workspace=new Ss({options:l,handlers:this.createWorkspaceHandlers(this.workClient)})}abortController=new AbortController;isStopping=!1;askUserAwaiter=new Map;messageFilter=qa();logger;workClient;workspace;coordinator;agentContext;runner;agentQueues=new Map;currentAgentSessionId;currentGroupId=null;historyDb;chatHistoryDb=null;agentrixTools;pendingNavigateTaskId=null;pendingPermissions=new Map;grantedPermissions=new Set;taskAgentsMap;messageSavedListener=null;messageDebounceHandle=null;messageDebounceMs=1e4;lastProcessedSequence=0;primarySessionReady=!1;pendingPrimaryLastSequence=null;primaryAgentId;primaryAgentName;newMessageGroupId(){return`group-${crypto.randomUUID()}`}refreshGroupId(){this.currentGroupId=this.newMessageGroupId()}shouldProcessMessage(e){const n=e.message,a=this.getRunnerMode(),t="group_chat"===a||"group_work"===a,s=w(n);return!!E(n)||!!C(n)||!(!k(n)&&!s)&&"agent"!==e.senderType&&(t?e.senderId!==this.primaryAgentId:!!s||"system"===e.senderType&&"user"===n.type||"user"===n.type)}shouldDropHeartbeatWhileBusy(){return this.coordinator.isActivelyExecuting()}async processPendingMessages(){const e=this.historyDb.pageMessagesAfter(this.lastProcessedSequence,100),n=[];for(const a of e.data)this.lastProcessedSequence=a.localSequence,this.shouldProcessMessage(a)&&n.push(a);if(n.length>0){this.deduplicateHeartbeats(n);const e=this.mergeConsecutiveHumanMessages(n),a=this.getRunnerMode();"group_chat"===a||"group_work"===a?await this.processMessagesAsGroup(e):await this.processMessagesIndividually(e)}e.hasMore&&await this.processPendingMessages()}deduplicateHeartbeats(e){let n=-1;for(let a=e.length-1;a>=0;a--)E(e[a].message)&&(-1===n?n=a:(e.splice(a,1),n--))}mergeConsecutiveHumanMessages(e){if(0===e.length)return[];const n=[];let a=0;for(;a<e.length;){const t=e[a];if("human"===t.senderType){const s=[t];for(;a+1<e.length;){const n=e[a+1];if("human"!==n.senderType||n.senderId!==t.senderId)break;s.push(n),a++}1===s.length?n.push(t):n.push(this.createMergedHumanMessage(s))}else n.push(t);a++}return n}createMergedHumanMessage(e){const n=[],a=[];for(const t of e){const e=t.message;if(!k(e)||"user"!==e.type)continue;const s=e.message.content;if("string"==typeof s)n.push(s);else if(Array.isArray(s))for(const e of s)"text"===e.type?n.push(e.text):a.push(e)}const t=n.join(""),s=a.length>0?[{type:"text",text:t},...a]:t,i=e[0],o=e[e.length-1];return{localSequence:o.localSequence,eventId:o.eventId,senderType:i.senderType,senderId:i.senderId,senderName:i.senderName,createdAt:o.createdAt,message:{type:"user",message:{role:"user",content:s},parent_tool_use_id:null,session_id:i.message?.session_id||""}}}async processMessagesAsGroup(e){const n=[],a=[];for(const t of e){const e=Ua(t);if(e){const t=e.message.content;if("string"==typeof t)n.push(t);else if(Array.isArray(t))for(const e of t)"text"===e.type?n.push(e.text):a.push(e)}}if(0===n.length)return;const t=Math.max(...e.map(e=>e.localSequence)),s=n.join(" "),i={type:"user",message:{role:"user",content:a.length>0?[{type:"text",text:s},...a]:s},parent_tool_use_id:null,session_id:""};i.__localSequence=t,await this.coordinator.enqueue(i)}async processMessagesIndividually(e){for(const n of e){const e=this.formatSingleMessage(n);e&&(e.__localSequence=n.localSequence,await this.coordinator.enqueue(e))}}formatSingleMessage(e){const n=e.message;if(E(n))return{type:"user",message:{role:"user",content:`[heartbeat] You are being awakened by a scheduled heartbeat at ${n.timestamp}. Check your workspace for any pending tasks, reminders, or scheduled work. If nothing to do, respond briefly and exit.`},parent_tool_use_id:null,session_id:""};if(C(n)){const e=n;let a=`[reminder from shadow] ${e.content}`;return e.filePath&&(a+=`\nDetailed analysis: ${e.filePath}`),{type:"user",message:{role:"user",content:a},parent_tool_use_id:null,session_id:""}}return k(n)&&"user"===n.type?n:null}setupMessageSavedListener(){this.messageSavedListener=()=>{this.triggerMessageProcessing()},this.historyDb.on("message-saved",this.messageSavedListener)}triggerMessageProcessing(){const e=this.getRunnerMode();"group_chat"===e||"group_work"===e?this.scheduleProcessPendingMessages():this.processPendingMessages()}scheduleProcessPendingMessages(){this.coordinator?.setDebouncing(!0),this.messageDebounceHandle&&clearTimeout(this.messageDebounceHandle),this.messageDebounceHandle=setTimeout(async()=>{this.messageDebounceHandle=null,await this.processPendingMessages(),this.coordinator?.setDebouncing(!1)},this.messageDebounceMs)}async start(){let e="completed";try{await this.initialize(),await this.handleEvent(),await this.runClaude()}catch(n){if(!(n instanceof Xe)){e="error",this.log("warn","AGENT","Fatal error:",n);const a=n instanceof Error?n.message:String(n);await this.reportFatalError(a)}}finally{await this.exitWorker(e)}}async initialize(){const e=this.options.input;await this.workClient.connect(),this.workClient.sendWorkerInitializing();const n=await ks.create("claude",e.agentId,{agentDir:e.agentDir,logger:this.log.bind(this),context:this.agentContext});this.runner=n,await this.workspace.setup(),await this.registerWithDaemon(this.workingDirectory),this.setEnvironmentVariables(),this.lastProcessedSequence=this.historyDb.getAgentLastSequences().get(this.primaryAgentId)??0,this.log("info","HISTORY",`Starting from sequence ${this.lastProcessedSequence} (tracking: ${this.primaryAgentId})`),this.currentAgentSessionId&&(this.historyDb.upsertAgentSession(this.primaryAgentId,this.currentAgentSessionId),this.primarySessionReady=!0),this.setupMessageSavedListener(),this.workClient.sendWorkerInitialized()}createWorkspaceHandlers(e){return{onRepositoryDetected:n=>{e.associateRepository(n.host,n.owner,n.repo,n.url)},onRepositoryInit:async e=>{await(this.runner?.executeHook("RepositoryInit",e))},onUncommittedChanges:this.onUncommittedChanges.bind(this),onBranchMismatch:this.onBranchMismatch.bind(this)}}async registerWithDaemon(e){const n=this.options.input.taskId,a=await rn(n,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});a.error?this.log("warn","DAEMON",`Failed to report session ${n}:`,a.error):this.log("info","DAEMON",`Session ${n} registered`)}setEnvironmentVariables(){this.options.input.environmentVariables&&Object.entries(this.options.input.environmentVariables).forEach(([e,n])=>{null!=n&&(process.env[e]=String(n))}),this.options.input.api_base_url&&(process.env.ANTHROPIC_BASE_URL=this.options.input.api_base_url),this.options.input.api_key&&(process.env.ANTHROPIC_AUTH_TOKEN=this.options.input.api_key)}createMessageCoordinator(e,n){const a=1e3*Math.max(0,n??0);return this.coordinator=new Nt({workerType:"claude",workClient:e,onCommandMessageProcessed:e=>{this.markPrimaryMessageProcessed(e)},handlers:{onNormalMessage:async e=>e,onBashCommand:async(e,n)=>{await this.executeBashCommand(e)},onMergeRequest:async e=>{await this.executeMergeRequest()},onMergePr:async()=>{await this.executeMergePr()},onNewSession:async()=>{await this.executeNewSession()}},logger:(e,n,a)=>{const t=e;this.log(t,n,a)},idleTimeoutMs:a,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}handleEvent(){const e=this.options.input.event,n=this.options.input.eventData;if("sub-task-result-updated"===e){const e=n,a=Na(e,this.options.dataEncryptionKey);this.historyDb.saveMessage({eventId:e.eventId||`sub-task-${Date.now()}`,message:a,senderType:"system",senderId:"system",senderName:"system"})}this.triggerMessageProcessing()}async executeMergeRequest(){this.log("info","MERGE","Executing merge-request command");const e=this.getRunnerMode(),n="group_chat"===e||"group_work"===e;try{if(!this.options.input.repositoryId){const e="Cannot create PR: task has no git repository configured.";return this.log("warn","MERGE","No repositoryId found in task input"),void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}await mt(this.workingDirectory)&&(await xt(this.workingDirectory,"Checkpoint for PR generation"),this.log("info","MERGE","Auto-committed changes"));const e=await gt(this.workingDirectory),s=this.workspace.getInitialCommitHash();if(!s){const e="Cannot create PR: initial commit hash is missing.";return this.log("error","MERGE",e),void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}if(0===(await vt(this.workingDirectory,s,e)).files.length){const e="No changes to create PR: no files changed since task started";return void this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}const i=await bt(this.workingDirectory);this.log("info","MERGE",`Pushing branch ${i} to remote`),await _t(this.workingDirectory,i,!1,this.options.input.gitServerId),this.log("info","MERGE","Successfully pushed branch to remote");const o=this.runner?.getAgentConfiguration(),r=Ot(s,(o?.customPRPromptTemplate?(a=o.customPRPromptTemplate,t={initialCommitHash:s,currentCommitHash:"",branchName:""},a.replace(/\{\{initialCommitHash\}\}/g,t.initialCommitHash).replace(/\{\{currentCommitHash\}\}/g,t.currentCommitHash).replace(/\{\{branchName\}\}/g,t.branchName)):void 0)??void 0);this.log("debug","MERGE",`PR prompt: ${r.substring(0,200)}...`);const c=this.runner;let p=null;const l=c.runStreamed(r,{cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),structuredOutputSchema:{type:"json_schema",schema:Es}});for await(const e of l){if(this.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){p=e;break}const a=n?e:this.messageFilter.filter(e);null!==a&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),a,{groupId:this.currentGroupId??void 0})}if(!p)throw new Error("Merge-request did not return a result message");const d=As(p),u=await this.workClient.sendMergeRequest(d.title,d.description);this.workClient.sendAssistantMessage(`${d.userMessage}\n\n✅ Pull request created successfully!\nNumber: #${u.pullRequestNumber}\nURL: ${u.pullRequestUrl}`,{groupId:this.currentGroupId??void 0})}catch(e){const n=e instanceof Error?e.message:String(e);this.log("error","MERGE","Merge-request failed:",e),this.workClient.sendSystemErrorMessage(`❌ Merge-request failed: ${n}\n\nPlease check git status and try again, or create the PR manually.`,{groupId:this.currentGroupId??void 0})}var a,t}async executeBashCommand(e){this.log("info","BASH",`Executing command: ${e}`);const n={senderType:"agent",senderId:"bash",senderName:"bash"},a=await jt(e,this.workingDirectory,{onOutput:e=>{this.workClient.sendTaskMessage(n,e,{groupId:this.currentGroupId??void 0})},onComplete:e=>{this.log("info","BASH",`Command completed with exit code: ${e}`)}});this.log("info","BASH",`Worker ready after command execution (exit code: ${a})`)}async executeMergePr(){await Ut({workingDirectory:this.workingDirectory,workClient:this.workClient,repositoryId:this.options.input.repositoryId,gitServerId:this.options.input.gitServerId,logger:this.logger,askUser:e=>this.askUser(e,{onTimeout:"abort_task"})})}async executeNewSession(){this.log("info","SESSION","Executing new-session: clearing agentSessionId"),this.currentAgentSessionId=void 0,this.primarySessionReady=!1,this.workClient.sendResetTaskSession(),this.log("info","SESSION","Session reset sent, stopping task for clean restart"),this.stopTask("event")}async runClaude(){this.log("info","AGENT",`Starting Claude agent for task ${this.taskId}`);const e=this.currentAgentSessionId,n=this.runner,a=this.getRunnerModeConfig(),t="group_chat"===a.mode||"group_work"===a.mode,s=this.createPermissionHandler(),i=this.buildSystemHooks({trackBackgroundTasks:!0,trackPrimaryAgentStop:!0}),o=n.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:e,abortController:this.abortController,stderr:e=>{this.log("debug","SDK",e)},modeConfig:a,agentrixTools:this.agentrixTools,canUseTool:s,hooks:i,maxTurns:this.options.input.maxTurns??void 0});(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(!e){if(this.isStopping)break;continue}o.push(e);const n=e.__localSequence;void 0!==n&&(this.markPrimaryMessageProcessed(n),delete e.__localSequence)}}catch(e){this.log("error","AGENT","Message pump failed:",e),this.stopTask("event")}})();for await(const e of o.events){if(this.logger.debug(`sdk message: ${JSON.stringify(e)}`),"system"===e.type&&"init"===e.subtype){this.workClient.sendUpdateTaskAgentSessionId(e.session_id),this.currentAgentSessionId=e.session_id,this.historyDb.upsertAgentSession(this.primaryAgentId,e.session_id),this.primarySessionReady=!0,null!==this.pendingPrimaryLastSequence&&(this.historyDb.updateAgentLastSequence(this.primaryAgentId,this.pendingPrimaryLastSequence),this.pendingPrimaryLastSequence=null),this.refreshGroupId(),this.updateAgentRunning(!0);continue}if("result"===e.type){await this.handleSdkResultMessage(e),this.updateAgentRunning(!1);continue}"system"===e.type&&"task_notification"===e.subtype&&this.handleBackgroundTaskNotification(e);const n=t?e:this.messageFilter.filter(e);null!==n&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}this.log("info","AGENT",`Claude agent finished for task ${this.taskId}`)}updateAgentRunning(e){this.coordinator?.setAgentRunning(this.primaryAgentId,this.primaryAgentName,e)}markPrimaryMessageProcessed(e){this.historyDb.updateAgentLastSequence(this.primaryAgentId,e),this.primarySessionReady||(this.pendingPrimaryLastSequence=null===this.pendingPrimaryLastSequence?e:Math.max(this.pendingPrimaryLastSequence,e))}stopTask(e){this.isStopping||(this.isStopping=!0,"idle"===e?this.log("info","AGENT","Idle timeout reached, stopping task"):"ask_user_timeout"===e&&this.log("info","AGENT","ask_user timed out, stopping task"),this.askUserAwaiter.clear(),this.coordinator?.stop(),this.abortController.abort())}async handleAskUserQuestionPermission(e){const n=e,a=Array.isArray(n.questions)?n.questions:[];if(0===a.length)return this.log("warn","PERMISSION","AskUserQuestion missing questions"),{behavior:"deny",message:"AskUserQuestion missing questions"};const t=a.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]}));try{const e=await this.askUser(t),s={};for(let n=0;n<a.length;n+=1){const t=a[n]?.question;if(!t)continue;const i=e.answers?.[n];"string"==typeof i&&(s[t]=i)}return{behavior:"allow",updatedInput:{...n,answers:s}}}catch(e){return this.log("warn","PERMISSION",`AskUserQuestion failed: ${e}`),{behavior:"deny",message:"AskUserQuestion failed"}}}createPermissionHandler(){return async(e,n)=>{if("AskUserQuestion"===e)return this.handleAskUserQuestionPermission(n);if(this.grantedPermissions.has(e))return this.log("info","PERMISSION",`Tool "${e}" already granted, skipping`),{behavior:"allow",updatedInput:n};const a=this.pendingPermissions.get(e);if(a)return this.log("info","PERMISSION",`Tool "${e}" has pending request, waiting...`),"allow"===await a?{behavior:"allow",updatedInput:n}:{behavior:"deny",message:"Permission denied by user"};let t;this.log("info","PERMISSION",`Requesting permission for "${e}"`);const s=new Promise(e=>{t=e});this.pendingPermissions.set(e,s);try{const a=await this.requestToolPermission(e);return t(a),"allow"===a?(this.grantedPermissions.add(e),{behavior:"allow",updatedInput:n}):{behavior:"deny",message:"Permission denied by user"}}catch(e){return t("deny"),{behavior:"deny",message:"Permission request failed"}}finally{this.pendingPermissions.delete(e)}}}async requestToolPermission(e){const n=[{question:`Tool "${e}" is requesting permission to execute. Allow this operation?`,header:"Permission",multiSelect:!1,options:[{label:"Allow",description:"Allow this tool to execute"},{label:"Deny",description:"Deny this tool execution"}]}];try{return"Allow"===(await this.askUser(n,{onTimeout:"abort_task"})).answers[0]?"allow":"deny"}catch(e){return this.log("warn","PERMISSION",`Permission request failed: ${e}`),"deny"}}async askUser(e,n={}){const a=this.workClient;return Lt(e,this.askUserAwaiter,{sendAskUser:e=>a.sendAskUser(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0}),sendAskUserResponse:(e,n)=>a.sendAskUserResponse(e,n),onTimeoutMessage:e=>a.sendAssistantMessage(e,{groupId:this.currentGroupId??void 0}),stopTask:e=>this.stopTask(e)},n)}async onUncommittedChanges(){const e=[{question:"Uncommitted changes detected in the working directory. How would you like to proceed?",header:"Git Status",multiSelect:!1,options:[{label:"Ignore",description:"Keep changes on current branch and continue without switching"},{label:"Commit",description:"Commit on current branch, then switch to task branch"},{label:"Stash",description:"Stash changes, then switch to task branch"},{label:"Abort",description:"Cancel the task, do nothing"}]}];try{const n=(await this.askUser(e,{onTimeout:"abort_task"})).answers[0];return n.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${n}, defaulting to Abort`),"Abort"):{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort"}catch(e){return this.log("warn","GIT",`Failed to get user response for uncommitted changes: ${e}`),"Abort"}}async onBranchMismatch(e){const n=[{label:"Switch",description:`Checkout ${e.expectedBranch} and continue`},{label:"Keep",description:`Continue on ${e.currentBranch} (may affect task history)`},{label:"Abort",description:"Cancel the task"}],a=[{question:`Branch mismatch detected. Current: ${e.currentBranch}. Expected: ${e.expectedBranch}. How would you like to proceed?`,header:"Git Branch",multiSelect:!1,options:n}];try{const e=(await this.askUser(a,{onTimeout:"abort_task"})).answers[0];return e.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${e}, defaulting to Abort`),"Abort"):{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[e]||"Abort"}catch(e){return this.log("warn","GIT",`Failed to get user response for branch mismatch: ${e}`),"Abort"}}getRunnerMode(){const e=this.taskAgentsMap.size>1,n=this.options.input.taskType,a=!(!process.env.AGENTRIX_COMPANION_HOME&&!process.env.AGENTRIX_COMPANION_WORKSPACE);return"shadow"===n?"companion_shadow":a&&"chat"===n?"companion_chat":e?"chat"===n?"group_chat":"group_work":"chat"===n?"chat":"work"}getGroupAgents(){if(!(this.taskAgentsMap.size<=1))return Array.from(this.taskAgentsMap.values()).map(e=>({id:e.id,name:e.name,description:e.description}))}getRunnerModeConfig(){return{mode:this.getRunnerMode(),supportChangeTitle:this.supportChangeTitle,groupAgents:this.getGroupAgents()}}get supportChangeTitle(){const e=this.options.input.customTitle;return!("string"==typeof e&&e.trim().length>0)}createAgentrixTools(){const e=this.taskAgentsMap.size>1;if("companion_shadow"===this.getRunnerMode()){const e=this.options.input.chatId,n=this.options.input.userId,a=D.resolveDataDir(n,e);this.chatHistoryDb=Sa({dataDir:a,taskId:e})}return{createTask:Ja(n={agentContext:this.agentContext,workClient:this.workClient,uploadFile:e=>this.agentContext.uploadFile(e),agentId:this.primaryAgentId,isGroup:e,historyDb:this.historyDb,chatHistoryDb:this.chatHistoryDb??void 0,askUser:e=>this.askUser(e),log:this.log.bind(this),invokeAgent:(e,n)=>this.invokeAgent(e,n),assign:(e,n,a)=>this.assignWork(e,n,a),setPendingNavigateTaskId:e=>{this.pendingNavigateTaskId=e}}),createSoloTask:Qa(n),createGroupTask:Za(n),replyToSubTask:Ka(n),changeTaskTitle:Ba(n),askUser:et(n),getTaskHistory:Va(n),getTaskAgents:Xa(n),listSubTask:Ya(n),invoke:nt(n),assign:tt(n),updateAgentInfo:at(n),sendReminder:ot(n),listTasks:st(n),readConversation:it(n),uploadFile:rt(n),listAgents:ct(n)};var n}resolveTaskAgentName(e){return this.taskAgentsMap.get(e)?.name||""}getChatSenderMeta(){return{senderType:"agent",senderId:this.primaryAgentId,senderName:this.primaryAgentName}}sendAgentErrorMessage(e,n,a,t){const s=n||e,i={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:`System Error\n\n${s}: ${a}`}]}};this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:s},i,{groupId:t?.groupId})}async invokeAgent(e,n){const a=this.buildSubAgentHistoryContext(e,n);if(!a)return!1;const t=this.taskAgentsMap.get(e),s=t?.type||"claude";let i=this.agentQueues.get(e);i||(i=new Rs,this.agentQueues.set(e,i));const o=this.resolveTaskAgentName(e),r=this.getRunnerMode(),c="group_chat"===r||"group_work"===r;return i.run(async()=>{this.coordinator?.setAgentRunning(e,o,!0);const n=this.newMessageGroupId();try{const t=await ks.create(s,e,{logger:this.log.bind(this),context:this.agentContext}),i=this.getGroupAgents()||[],r={mode:"reply",supportChangeTitle:!1,groupAgents:i},p=this.createPermissionHandler(),l=this.buildSystemHooks({trackBackgroundTasks:!1}),d=qa(),u=t.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:a.sessionId,abortController:this.abortController,modeConfig:r,agentrixTools:this.agentrixTools,canUseTool:p,hooks:l,maxTurns:this.options.input.maxTurns??void 0});let m=a.message;if("codex"===s&&!a.sessionId){const n=[Jt(e,i),"=== CONVERSATION STREAM START FROM HERE ===",ns(a.message)].join("\n\n").trim();n&&(m=n)}u.push(m);const g=a.lastSequence;let h=!1;a.sessionId&&(this.historyDb.updateAgentLastSequence(e,g),h=!0);let f=!1;for await(const a of u.events){if("system"===a.type&&"init"===a.subtype){this.historyDb?.upsertAgentSession(e,a.session_id),h||(this.historyDb.updateAgentLastSequence(e,g),h=!0);continue}if("result"===a.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},a,{groupId:n}),f=!0;break}const t=c?a:d.filter(a);t&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},t,{groupId:n})}}catch(n){this.log("error","INVOKE",`Invoke failed for ${e}:`,n)}finally{this.coordinator?.setAgentRunning(e,o,!1)}}),!0}async assignWork(e,n,a){const t=this.taskAgentsMap.get(e),s=t?.type||"claude";let i=this.agentQueues.get(e);i||(i=new Rs,this.agentQueues.set(e,i));const o=this.resolveTaskAgentName(e),r=this.getRunnerMode(),c="group_chat"===r||"group_work"===r;return i.run(async()=>{this.coordinator?.setAgentRunning(e,o,!0);const t=this.newMessageGroupId();var i;a&&this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},(i=a,{type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:i}]}}),{groupId:this.newMessageGroupId()});try{const a=await ks.create(s,e,{logger:this.log.bind(this),context:this.agentContext}),i={mode:"work",supportChangeTitle:!1},r=this.createPermissionHandler(),p=this.buildSystemHooks({trackBackgroundTasks:!1}),l=qa(),d=a.loop({cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:i,agentrixTools:this.agentrixTools,canUseTool:r,hooks:p,maxTurns:this.options.input.maxTurns??void 0});d.push(n);let u=!1;for await(const n of d.events){if("system"===n.type&&"init"===n.subtype)continue;if("result"===n.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},n,{groupId:t}),u=!0;break}const a=c?n:l.filter(n);a&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},a,{groupId:t})}}catch(n){this.log("error","RUN_TASK",`Run task failed for ${e}:`,n);const a=n instanceof Error?n.message:String(n);this.sendAgentErrorMessage(e,o,`I meet some error: ${a}`,{groupId:t})}finally{this.coordinator?.setAgentRunning(e,o,!1)}})}buildSubAgentHistoryContext(e,n){const a=this.historyDb;if(!a)return this.log("warn","HISTORY","Task history DB unavailable; delegate cannot build context."),null;const t=a.getAgentSessions().get(e),s=a.getAgentLastSequences().get(e)??0,i=a.pageRecentMessagesAfter(s,20);if(0===i.data.length&&!n)return null;const o=this.mergeConsecutiveHumanMessages(i.data),r=this.buildHistoryMessages(o,n);return r?{message:r,sessionId:t,lastSequence:i.data.length>0?i.data[i.data.length-1].localSequence:s}:null}buildHistoryMessages(e,n){const a=[];for(const n of e){const e=Ga(n);e&&a.push(e)}if(0===a.length&&!n)return null;let t=a.join("\n");return n&&(t=`<hint>\n${n}\n</hint>\n\n${t}`),{type:"user",message:{role:"user",content:t},parent_tool_use_id:null,session_id:""}}buildSystemHooks(e){const n=e?.trackBackgroundTasks??!0,a=e?.trackPrimaryAgentStop??!1,t={};return n&&(t.PostToolUse=async e=>(this.trackBackgroundTaskFromPostToolUse(e),{})),a&&(t.Stop=async()=>(this.updateAgentRunning(!1),{})),t}trackBackgroundTaskFromPostToolUse(e){if(!e||"object"!=typeof e)return void this.log("debug","TASK","PostToolUse hook input is not an object");const n=e,a=n.tool_input;if(!a||!0!==a.run_in_background)return;const t=this.extractBackgroundTaskId(n.tool_response);if(!t)return this.log("debug","TASK",`PostToolUse(${n.tool_name}) run_in_background=true but no task_id found, using anonymous tracking`),void this.coordinator?.setAnonymousBackgroundTaskRunning(!0);this.coordinator?.setBackgroundTaskRunning(t,!0),this.log("info","TASK",`Background task started: ${t} (tool: ${n.tool_name})`)}handleBackgroundTaskNotification(e){this.updateAgentRunning(!0),this.coordinator?.setBackgroundTaskRunning(e.task_id,!1),this.log("info","TASK",`Background task ${e.task_id} ${e.status}`)}extractBackgroundTaskId(e){const n=new Set,a=new Set,t=e=>{if("string"!=typeof e)return;const a=e.trim();a&&n.add(a)},s=e=>{if(null==e)return;if("string"==typeof e)return void(e=>{const n=/(task[_-]?id|agent[_-]?id|shell[_-]?id)["'\s:=]+([A-Za-z0-9._:-]+)/gi;let a;for(;null!==(a=n.exec(e));)t(a[2])})(e);if("object"!=typeof e)return;if(a.has(e))return;if(a.add(e),Array.isArray(e)){for(const n of e)s(n);return}const n=e;"string"==typeof n.task_id&&t(n.task_id),"string"==typeof n.taskId&&t(n.taskId),"string"==typeof n.agent_id&&t(n.agent_id),"string"==typeof n.agentId&&t(n.agentId),"string"==typeof n.shell_id&&t(n.shell_id),"string"==typeof n.shellId&&t(n.shellId);for(const e of Object.values(n))s(e)};s(e);const i=[...n];return i.length>1&&this.log("warn","TASK",`Multiple background task ids extracted (${i.join(", ")}), using first id ${i[0]}`),i[0]}createWorkerClientConfig(e,n,a){const t=this.options.input.agentId,s=this.taskAgentsMap.get(t)?.name;return{config:{userId:e,taskId:n,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:t,agentName:s,cwd:a,serverUrl:D.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:A(this.credentials.token,this.credentials.machineId,n),dataEncryptionKey:this.options.dataEncryptionKey??null,keepAliveConfig:{intervalMs:2e4,event:"worker-alive",payloadGenerator:()=>{const e=this.coordinator?.getStatus(),a="running"===e?.state?"worker-running":"worker-ready";return{eventId:d(),status:a,taskId:n,machineId:this.credentials.machineId,timestamp:Date.now().toString(),activeAgents:this.coordinator?.getActiveAgents()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...n)=>this.logger.info(`[SOCKET] ${e}`,...n)},handlers:{attachmentsDir:D.resolveAttachmentsDir(e,n),logger:(e,n,a,...t)=>{this.log(e,n,a,...t)},stopTask:async()=>{this.stopTask("event")},shouldPersistTaskMessage:async e=>!E(e)||!this.shouldDropHeartbeatWhileBusy()||(this.log("debug","WORKER","Dropping heartbeat at WorkerClient receive stage: agent is running"),!1),onTaskMessage:async(e,n)=>{if(w(e)){const[n,a]=this.askUserAwaiter.entries().next().value||[];n&&a&&(this.askUserAwaiter.delete(n),a(e))}},onTaskInfoUpdate:async e=>{Gt(e,this.options.input)},onWorkerStatusRequest:async()=>{const{state:e}=this.coordinator.getStatus();"running"===e?this.workClient.sendWorkRunning():"idle"===e&&this.workClient.sendWorkerReady()},onSubTaskResultUpdated:async e=>{const n=Na(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(n)}}}}async exitWorker(e){this.log("info","WORKER",`Exiting with status: ${e} for task ${this.taskId}`),this.coordinator&&this.coordinator.stop(),this.workClient&&(this.workClient.sendWorkerExit(e),await this.workClient.disconnect()),this.historyDb&&this.historyDb.close(),this.chatHistoryDb&&this.chatHistoryDb.close(),process.exit(0)}async reportFatalError(e){this.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}log(e,n,a,...t){this.logger&&this.logger[e](`[${n}] ${a}`,...t)}get taskId(){return this.options.input.taskId}async handleSdkResultMessage(e){let n,a;try{const e=await this.workspace.prepareResultArtifacts({onCommitError:e=>{this.log("warn","GIT","Failed to auto-commit changes before result message:",e)},onPatchError:e=>{this.log("warn","GIT","Failed to write patch diff for result:",e)}});n=e.artifacts,a=e.currentCommitHash}catch(e){this.log("warn","GIT","Failed to prepare git artifacts for result:",e)}const t=this.getRunnerMode(),s="group_chat"===t||"group_work"===t,i=this.pendingNavigateTaskId;if(this.pendingNavigateTaskId=null,s?this.workClient.sendTaskEvent(this.getChatSenderMeta(),e,{...n?{artifacts:n}:{},groupId:this.currentGroupId??void 0,navigateToTaskId:i??void 0}):this.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{...n?{artifacts:n}:{},groupId:this.currentGroupId??void 0,navigateToTaskId:i??void 0}),a)try{await Pt(this.options.input.userId,this.taskId,a)}catch(e){this.log("warn","GIT","Failed to mark commit as sent:",e)}}}class Ms{static async calculateFinalCwd(e){const{repositorySourceType:n,cwd:a,userCwd:t,userId:s,taskId:i,forceUserCwd:o}=e;if(a)return a;const r=D.resolveProjectDir(s,i);if("directory"===n&&t){const e=t.replace(/^~/,J());return o?e:await this.shouldUseWorktree(e)?r:e}return r}static async shouldUseWorktree(e){try{return!ft(e)&&await lt(e)}catch{return!1}}}var $s=hn(U);class Ds{constructor(e,n){this.credentials=e,this.options=n}context;threadId=null;isStopping=!1;filteredToolUseIds=new Set;currentModel=null;dataEncryptionKey=null;abortController=new AbortController;coordinator;logger;askUserAwaiter=new Map;workClient;workspace;historyDb=null;currentGroupId=null;refreshGroupId(){this.currentGroupId=`group-${M()}`}async start(){try{await this.initialize(),await this.handleEvent(),await this.runCodex(),await this.exitWorker("completed")}catch(e){if(!this.isStopping){this.log("warn","AGENT","Fatal error:",e);const n=e instanceof Error?e.message:String(e);throw await this.exitWorker("error",n),e}this.log("info","AGENT",`Task ${this.taskId} stopped gracefully`),await this.exitWorker("completed")}finally{process.exit(0)}}async initialize(){const e=this.options.input.taskId,n=this.options.input.userId;this.logger=this.createLogger({type:"worker",taskId:e}),this.dataEncryptionKey=this.options.dataEncryptionKey??null;const a=Et(this.options.input),t=await Ms.calculateFinalCwd(a),s={...a,cwd:t};this.log("info","INIT",`Phase 1: Working directory: ${t}`);const i=this.createWorkerClientConfig(n,e,t),o=D.resolveDataDir(n,e);this.historyDb=Sa({dataDir:o,taskId:e});const r=new Pa(i.config,{...i.handlers,historyDb:this.historyDb});this.workClient=r,this.log("info","INIT","Phase 2: WorkerClient created");const c=1e3*Math.max(0,this.options.idleTimeoutSecond??0);this.coordinator=this.createMessageCoordinator(r,c),this.log("info","INIT","Phase 3: Coordinator created"),await r.connect(),r.sendWorkerInitializing(),this.log("info","INIT","Phase 4: Connected to server"),this.log("info","INIT","Phase 5: Skipped (no AgentContext for Codex)"),this.log("info","INIT","Phase 6: Skipped (no custom resources for Codex)");const p=new Ss({options:s,handlers:this.createWorkspaceHandlers(r)}),{initialCommitHash:l,gitStateResult:d}=await p.setup();this.workspace=p,this.log("info","INIT","Phase 7: Workspace setup complete"),r.sendWorkerInitialized(),this.log("info","INIT","Phase 8: Initialization finalized"),await this.registerWithDaemon(t),this.log("info","INIT","Phase 9: Registered with daemon"),this.context={credentials:this.credentials,options:this.options,workClient:r,workingDirectory:t,initialCommitHash:l,logger:this.logger},process.env.AGENTRIX_WORKING_DIR=t,process.env.AGENTRIX_WORKING_USER=n,process.env.AGENTRIX_WORKING_TASK=e,this.options.input.environmentVariables&&Object.entries(this.options.input.environmentVariables).forEach(([e,n])=>{null!=n&&(process.env[e]=String(n))}),this.options.input.api_base_url&&(process.env.OPENAI_BASE_URL=this.options.input.api_base_url),this.options.input.api_key&&(process.env.CODEX_API_KEY=this.options.input.api_key),"agentSessionId"in this.options.input&&this.options.input.agentSessionId&&(this.threadId=this.options.input.agentSessionId,this.log("info","AGENT",`Resuming thread: ${this.threadId}`))}createWorkspaceHandlers(e){return{onRepositoryDetected:n=>{e.associateRepository(n.host,n.owner,n.repo,n.url)},onUncommittedChanges:this.onUncommittedChanges.bind(this),onBranchMismatch:this.onBranchMismatch.bind(this)}}async registerWithDaemon(e){const n=this.options.input.taskId,a=await rn(n,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});a.error?this.log("warn","DAEMON",`Failed to report session ${n}:`,a.error):this.log("info","DAEMON",`Session ${n} registered`)}createMessageCoordinator(e,n){return this.coordinator=new Nt({workerType:"codex",workClient:e,handlers:{onNormalMessage:async e=>this.convertSDKMessageToCodexInput(e),onBashCommand:async(e,n)=>{await this.executeBashCommand(e)},onMergeRequest:async e=>{await this.executeMergeRequest()},onMergePr:async()=>{await this.executeMergePr()},onNewSession:async()=>{await this.executeNewSession()}},logger:(e,n,a)=>{const t=e;this.log(t,n,a)},idleTimeoutMs:n,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}async handleEvent(){if("task-message"===this.options.input.event){const e=this.options.input.eventData.message;e&&k(e)&&"user"===e.type&&await this.coordinator.enqueue(e)}}async executeMergeRequest(){this.log("info","MERGE","Executing merge-request command");try{if(!this.options.input.repositoryId){const e="Cannot create PR: task has no git repository configured.";return this.log("warn","MERGE","No repositoryId found in task input"),void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}await mt(this.context.workingDirectory)&&(await xt(this.context.workingDirectory,"Update task changes"),this.log("info","MERGE","Auto-committed changes"));const e=await gt(this.context.workingDirectory),n=this.context.initialCommitHash,a=await bt(this.context.workingDirectory);if(this.log("info","MERGE",`Pushing branch ${a} to remote`),await _t(this.context.workingDirectory,a,!1,this.options.input.gitServerId),this.log("info","MERGE","Successfully pushed branch to remote"),!n){const e="Cannot create PR: initial commit hash is missing.";return this.log("error","MERGE",e),void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}if(0===(await vt(this.context.workingDirectory,n,e)).files.length){const e="No changes to create PR: no files changed since task started";return void this.context.workClient.sendSystemErrorMessage(e,{groupId:this.currentGroupId??void 0})}const t=Ot(n);this.log("debug","MERGE",`PR prompt: ${t.substring(0,200)}...`);const s=this.options.input.agentId??"default",i=await ks.create("codex",s),o={mode:"work",supportChangeTitle:!1},r=i.runStreamed(t,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,abortController:this.abortController,modeConfig:o,structuredOutputSchema:{type:"json_schema",schema:Cs}});let c=null;for await(const e of r){if(this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){c=e;break}const n=this.filterMessages(e);null!==n&&this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}if(!c)throw new Error("Merge-request did not return a result message");const p=As(c);await this.createPullRequest(p.title,p.description),this.sendMessage(p.userMessage)}catch(e){const n=e instanceof Error?e.message:String(e);this.log("error","MERGE","Merge-request failed:",e),this.context.workClient.sendSystemErrorMessage(`Merge-request failed: ${n}\n\n`,{groupId:this.currentGroupId??void 0})}}async executeChangeTitle(e){this.log("info","WORKER",`Changing task title to: ${e}`),this.context.workClient.sendChangeTaskTitle(e)}async executeBashCommand(e){this.log("info","BASH",`Executing command: ${e}`);const n=await jt(e,this.context.workingDirectory,{onOutput:e=>{this.context.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0})},onComplete:e=>{this.log("info","BASH",`Command completed with exit code: ${e}`)}});this.log("info","BASH",`Worker ready after command execution (exit code: ${n})`)}async executeMergePr(){await Ut({workingDirectory:this.context.workingDirectory,workClient:this.context.workClient,repositoryId:this.options.input.repositoryId,gitServerId:this.options.input.gitServerId,logger:this.context.logger,askUser:e=>this.askUser(e,{onTimeout:"abort_task"})})}async executeNewSession(){this.log("info","SESSION","Executing new-session: clearing threadId"),this.threadId=null,this.context.workClient.sendResetTaskSession(),this.log("info","SESSION","Session reset sent, stopping task for clean restart"),this.stopTask("event")}async runCodex(){this.log("info","AGENT",`Starting Codex agent for task ${this.taskId}`),this.currentModel=this.options.input.model||null,this.currentModel?this.log("info","AGENT",`Using model: ${this.currentModel}`):this.log("info","AGENT","Using default model from Codex config");const e=this.options.input.agentId??"default",n=(await ks.create("codex",e)).loop({cwd:this.context.workingDirectory,model:this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:{mode:"work",supportChangeTitle:!1}});(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(e)n.push(e);else if(this.isStopping)break}}catch(e){this.log("error","AGENT","Message pump failed:",e),this.stopTask("event")}})();for await(const e of n.events){if(this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),"system"===e.type&&"init"===e.subtype){this.threadId=e.session_id,this.context.workClient.sendUpdateTaskAgentSessionId(e.session_id),this.log("info","AGENT",`Thread started: ${e.session_id}`),this.refreshGroupId(),this.updateAgentRunning(!0);continue}const n=this.filterMessages(e);null!==n&&("result"===e.type?await this.handleSdkResultMessage(n):this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})),"result"===e.type?this.updateAgentRunning(!1):this.updateAgentRunning(!0)}this.log("info","AGENT",`Codex agent finished for task ${this.taskId}`)}filterMessages(e){const n=e,a=n?.message?.content;if(!a||"string"==typeof a)return e;const t=a.filter(e=>"tool_use"===e.type&&"agentrix"===e.server_name?(this.filteredToolUseIds.add(e.id),!1):!("tool_result"===e.type&&this.filteredToolUseIds.has(e.tool_use_id)||"user"===n.type&&"tool_result"!==e.type));return 0===t.length?null:(n.message.content=t,n)}sendMessage(e){const n={type:"assistant",message:{id:M().toString(),type:"message",container:null,role:"assistant",content:[{citations:null,type:"text",text:e}],model:this.currentModel||"",usage:{},stop_reason:null,context_management:null,stop_sequence:null},parent_tool_use_id:null,session_id:"",uuid:M().toString()};this.getActiveWorkClient().sendTaskMessage(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}async askUser(e,n={}){const a=this.getActiveWorkClient();return Lt(e,this.askUserAwaiter,{sendAskUser:e=>a.sendAskUser(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0}),sendAskUserResponse:(e,n)=>a.sendAskUserResponse(e,n),onTimeoutMessage:e=>this.sendMessage(e),stopTask:e=>this.stopTask(e)},n)}getActiveWorkClient(){const e=this.context?.workClient??this.workClient;if(!e)throw new Error("[WORKER] WorkerClient not available");return e}resolveTaskAgentName(e){const n=this.options.input.taskAgents??[];return n.find(n=>n.id===e)?.name||""}getChatSenderMeta(){const e=this.options.input.agentId;return{senderType:"agent",senderId:e,senderName:this.resolveTaskAgentName(e)??""}}async onUncommittedChanges(){const e=[{question:"Uncommitted changes detected in the working directory. How would you like to proceed?",header:"Git Status",multiSelect:!1,options:[{label:"Ignore",description:"Keep changes on current branch and continue without switching"},{label:"Commit",description:"Commit on current branch, then switch to task branch"},{label:"Stash",description:"Stash changes, then switch to task branch"},{label:"Abort",description:"Cancel the task, do nothing"}]}];try{const n=(await this.askUser(e,{onTimeout:"abort_task"})).answers[0];return n.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${n}, defaulting to Abort`),"Abort"):{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort"}catch(e){return this.log("warn","GIT",`Failed to get user response for uncommitted changes: ${e}`),"Abort"}}async onBranchMismatch(e){const n=[{label:"Switch",description:`Checkout ${e.expectedBranch} and continue`},{label:"Keep",description:`Continue on ${e.currentBranch} (may affect task history)`},{label:"Abort",description:"Cancel the task"}],a=[{question:`Branch mismatch detected. Current: ${e.currentBranch}. Expected: ${e.expectedBranch}. How would you like to proceed?`,header:"Git Branch",multiSelect:!1,options:n}];try{const e=(await this.askUser(a,{onTimeout:"abort_task"})).answers[0];return e.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${e}, defaulting to Abort`),"Abort"):{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[e]||"Abort"}catch(e){return this.log("warn","GIT",`Failed to get user response for branch mismatch: ${e}`),"Abort"}}async createPullRequest(e,n){this.log("info","MERGE",`Creating PR: ${e}`);try{const a=await this.context.workClient.sendMergeRequest(e,n);this.sendMessage(`✅ Pull request created successfully!\nNumber: #${a.pullRequestNumber}\nURL: ${a.pullRequestUrl}`)}catch(e){this.log("error","MERGE","Failed to create PR:",e),this.sendMessage(`❌ Failed to create pull request: ${e instanceof Error?e.message:"Unknown error"}`)}}async convertSDKMessageToCodexInput(e){const n=e.message.content;if("string"==typeof n)return n;if(Array.isArray(n)){const e=[],a=D.resolveAttachmentsDir(this.options.input.userId,this.taskId);for(const t of n)if("text"===t.type&&t.text)e.push(t.text);else if("image"===t.type&&t.source&&t.source.url){const n=t.source.url;try{const{filePath:t}=await $a(n,a,!1);this.log("info","IMAGE",`Downloaded image from ${n} to ${t}`),e.push(`Image: ${t}`)}catch(e){this.log("error","IMAGE",`Failed to download image from ${n}:`,e)}}else if("document"===t.type&&t.source&&t.source.url){const n=t.source.url;try{const{filePath:s,mimeType:i,filename:o}=await $a(n,a,!0);this.log("info","DOCUMENT",`Downloaded document from ${n} to ${s}`);const r=t.title||o;e.push(`Document: ${s}\nTitle: ${r}\nType: ${i}`)}catch(e){this.log("error","DOCUMENT",`Failed to download document from ${n}:`,e)}}const t=e.map(e=>e.trim()).filter(Boolean).join("\n\n").trim();if(t)return t}return""}stopTask(e){this.isStopping||(this.isStopping=!0,"idle"===e?this.log("info","AGENT","Idle timeout reached, stopping task"):"ask_user_timeout"===e&&this.log("info","AGENT","ask_user timed out, stopping task"),this.askUserAwaiter.clear(),this.coordinator?.stop(),this.abortController.abort())}updateAgentRunning(e){this.coordinator?.updateAgentRunning(e)}createWorkerClientConfig(e,n,a){const t=this.options.input.agentId,s=this.options.input.taskAgents?.find(e=>e.id===t)?.name;return{config:{userId:e,taskId:n,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:t,agentName:s,cwd:a,serverUrl:D.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:A(this.credentials.token,this.credentials.machineId,n),dataEncryptionKey:this.dataEncryptionKey,keepAliveConfig:{intervalMs:2e4,event:"worker-alive",payloadGenerator:()=>{const e=this.coordinator?.getStatus(),a="running"===e?.state?"worker-running":"worker-ready";return{eventId:d(),status:a,taskId:n,machineId:this.credentials.machineId,timestamp:Date.now().toString()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...n)=>(this.context?.logger??this.logger)?.info(`[SOCKET] ${e}`,...n)},handlers:{stopTask:async()=>{this.stopTask("event")},onTaskMessage:async e=>{if(w(e)){const[n,a]=this.askUserAwaiter.entries().next().value||[];return void(n&&a&&(this.askUserAwaiter.delete(n),a(e)))}k(e)&&"user"===e.type&&await this.coordinator.enqueue(e)},onTaskInfoUpdate:async e=>{Gt(e,this.options.input)},onWorkerStatusRequest:async()=>{if(!this.context?.workClient)return;if(!this.coordinator)return;const{state:e}=this.coordinator.getStatus();"running"===e?this.context.workClient.sendWorkRunning():"idle"===e&&this.context.workClient.sendWorkerReady()}}}}async exitWorker(e,n){this.coordinator&&this.coordinator.stop(),this.log("info","WORKER",`Exiting with status: ${e} for task ${this.taskId}`),"error"===e&&n?await this.context.workClient.sendErrorMessageAndExit(n):(this.context.workClient.sendWorkerExit(e),await this.context.workClient.disconnect()),this.historyDb&&this.historyDb.close()}createLogger(e){const{createLogger:n}=$s;return n(e)}log(e,n,a,...t){const s=this.context?.logger??this.logger;s&&s[e](`[${n}] ${a}`,...t)}get taskId(){return this.options.input.taskId}getCurrentModel(){return this.currentModel||"gpt-5"}async handleSdkResultMessage(e){let n,a;try{const e=await this.workspace.prepareResultArtifacts({onCommitError:e=>{this.log("warn","GIT","Failed to auto-commit changes before result message:",e)},onPatchError:e=>{this.log("warn","GIT","Failed to write patch diff for result:",e)}});n=e.artifacts,a=e.currentCommitHash}catch(e){this.log("warn","GIT","Failed to prepare git artifacts for result:",e)}if(this.context.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{...n?{artifacts:n}:{},groupId:this.currentGroupId??void 0}),a)try{await Pt(this.options.input.userId,this.taskId,a)}catch(e){this.log("warn","GIT","Failed to mark commit as sent:",e)}}}async function Ps(e,n){await ae.promises.mkdir(n,{recursive:!0});const a=await ae.promises.readdir(e,{withFileTypes:!0});for(const t of a){const a=ge.join(e,t.name),s=ge.join(n,t.name);t.isDirectory()?await Ps(a,s):await ae.promises.copyFile(a,s)}}async function Os(e,n){const a=n.input,{taskId:t,sourcePath:s,targetAgentId:i,userId:o,name:r,avatar:c,isSystemAgent:p,supportLocal:l}=a;let u=null;try{if(console.log(`[Deployment] Starting deployment worker for task ${t}`),!ae.existsSync(s))throw new Error(`Source path not found: ${s}`);const n=ge.join(D.agentrixAgentsHomeDir,i);if(ae.existsSync(n))throw new Error(`Target agent directory already exists: ${n}`);console.log(`[Deployment] Copying from ${s} to ${n}`),await Ps(s,n),console.log("[Deployment] Deployment completed successfully"),u=function(e,n,a){const t=D.serverUrl.replace(/^http/,"ws");return Z(t,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:a}})}(e,0,t),await new Promise((e,n)=>{const a=setTimeout(()=>{n(new Error("WebSocket connection timeout"))},1e4);u.on("connect",()=>{clearTimeout(a),console.log("[Deployment] Connected to server"),u.emit("deploy-agent-complete",{eventId:d(),taskId:t,targetAgentId:i,success:!0,name:r,avatar:c,isSystemAgent:p,supportLocal:l}),console.log("[Deployment] Sent deploy-agent-complete event"),setTimeout(()=>{e()},1e3)}),u.on("connect_error",e=>{clearTimeout(a),n(e)})})}catch(e){throw console.error("[Deployment] Deployment failed:",e),u&&u.connected&&(u.emit("deploy-agent-complete",{eventId:d(),taskId:t,targetAgentId:i,success:!1,error:e instanceof Error?e.message:String(e)}),await new Promise(e=>setTimeout(e,1e3))),e}finally{u&&u.disconnect(),process.exit(0)}}const js=["claude","codex","deployment","companion"],Ns={claude:{async run({credentials:e,startedBy:n,userId:a,taskId:t,idleTimeoutSecond:s}){const i=D.readTaskInput(a,t),o=i.dataEncryptionKey?p(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:n,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await async function(e,n){const a=Et(n.input),t=await Ms.calculateFinalCwd(a),s=new _s(e,n,t);await s.start()}(e,r)}},codex:{async run({credentials:e,startedBy:n,userId:a,taskId:t,idleTimeoutSecond:s}){const i=D.readTaskInput(a,t),o=i.dataEncryptionKey?p(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:n,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await async function(e,n){const a=new Ds(e,n);await a.start()}(e,r)}},deployment:{async run({credentials:e,startedBy:n,userId:a,taskId:t,idleTimeoutSecond:s}){const i={input:D.readTaskInput(a,t)};await Os(e,i)}},companion:{async run({credentials:e,startedBy:n,userId:a,taskId:t,idleTimeoutSecond:s}){const i=D.readTaskInput(a,t),o=i.dataEncryptionKey?p(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:n,idleTimeoutSecond:s,input:i,dataEncryptionKey:o};await async function(e,n){const{agentDir:a,homeDir:t}=await ba();n.input.agentDir=a,process.env.AGENTRIX_COMPANION_HOME=t;const s=Et(n.input),i=await Ms.calculateFinalCwd(s),o=new _s(e,n,i);await o.start()}(e,r)}}};async function qs(){const e=j.version;try{const n=Te("npm view @agentrix/cli version",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();return{hasUpgrade:function(e,n){const a=e.split(".").map(Number),t=n.split(".").map(Number);for(let e=0;e<Math.max(a.length,t.length);e++){const n=a[e]||0,s=t[e]||0;if(n>s)return 1;if(n<s)return-1}return 0}(n,e)>0,currentVersion:e,latestVersion:n}}catch(n){return{hasUpgrade:!1,currentVersion:e,latestVersion:null}}}function Us(){return"true"===process.env.AGENTRIX_DISABLE_AUTO_UPGRADE}async function Gs(e){try{const{execSync:n}=await import("child_process");return console.log(""),e||(console.log(s.blue("🔄 Checking for upgrades...")),e=await qs()),e.hasUpgrade?(console.log(s.blue(`🔄 Upgrading from ${e.currentVersion} to ${e.latestVersion}...`)),n("npm install -g @agentrix/cli@latest",{stdio:"inherit"}),console.log(s.green("✓ Upgrade complete")),console.log(""),!0):(console.log(s.green("✓ Already on latest version")),console.log(""),!0)}catch(e){return console.log(""),console.log(s.yellow("⚠️ Auto-upgrade failed")),console.log(s.dim(" You can upgrade manually with: npm install -g @agentrix/cli@latest")),console.log(""),!1}}function Ls(){const e=D.getStatePaths();return B.join(B.dirname(e.daemonStateFile),"upgrade-daemon.state.json")}function Fs(){try{const e=Ls();if(!F.existsSync(e))return null;const n=F.readFileSync(e,"utf-8");return JSON.parse(n)}catch{return null}}function Ws(){try{const e=Ls();F.existsSync(e)&&F.unlinkSync(e)}catch{}}function Hs(e){try{return process.kill(e,0),!0}catch{return!1}}function zs(){const e=Fs();return!(!e||!Hs(e.pid)&&(Ws(),1))}function Bs(){const e=Fs();if(e)try{Hs(e.pid)&&process.kill(e.pid,"SIGTERM")}catch{}finally{Ws()}}async function Ks(){if(Us())return!1;const e=await qs();return!(!e.hasUpgrade||!await Gs(e))&&(await dn(),await new Promise(e=>setTimeout(e,1e3)),ka(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref(),!0)}var Vs=Object.freeze({__proto__:null,isUpgradeDaemonRunning:zs,startUpgradeDaemon:async function(){await async function(){!function(e){const n=Ls();F.writeFileSync(n,JSON.stringify(e,null,2))}({pid:process.pid,startedAt:(new Date).toISOString()}),process.on("SIGTERM",()=>{Ws(),process.exit(0)}),process.on("SIGINT",()=>{Ws(),process.exit(0)});try{await Ks()}catch(e){}for(;;){await new Promise(e=>setTimeout(e,216e5));try{await Ks()}catch(e){}}}()},stopUpgradeDaemon:Bs});const Xs=a(t(process.argv)).scriptName("agentrix").version(j.version).usage("$0 <command> [options]").option("debug",{alias:"d",type:"boolean",describe:"Use local-debug mode (plaintext, for debugging)",global:!0}).help("help").alias("h","help").alias("v","version").strict().epilog("For more information, visit https://github.com/xmz-ai/agentrix-cli");D.getStatePaths,Xs.command("upgrade","Upgrade CLI to the latest version",{},async e=>{console.log(s.dim(`Current version: ${j.version}`));const n=await cn();if(await Gs()||process.exit(1),n){console.log(s.blue("Restarting daemon...")),await dn(),await new Promise(e=>setTimeout(e,1e3)),ka(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();let e=!1;for(let n=0;n<50;n++)if(await new Promise(e=>setTimeout(e,100)),await cn()){e=!0;break}e?console.log(s.green("✓ Daemon restarted successfully")):console.log(s.yellow("⚠️ Daemon may still be starting. Run 'agentrix status' to check."))}try{const{version:e}=await import("./logger-nstmO8QZ.mjs").then(function(e){return e._});console.log(s.green(`\n✓ Now running version: ${e}`))}catch{console.log(s.dim("\nRun 'agentrix --version' to see the new version"))}process.exit(0)}),Xs.command("doctor","System diagnostics & troubleshooting",{},async e=>{await Xn(),process.exit(0)}),Xs.command("logout","Logout from Agentrix",{},async e=>{try{await async function(){if(!await D.readCredentials())return void console.log(s.yellow("Not currently authenticated"));console.log(s.blue("This will log you out of Agentrix")),console.log(s.yellow("⚠️ You will need to re-authenticate to use Agentrix again"));const e=G({input:process.stdin,output:process.stdout}),n=await new Promise(n=>{e.question(s.yellow("Are you sure you want to log out? (y/N): "),n)});if(e.close(),"y"===n.toLowerCase()||"yes"===n.toLowerCase())try{try{await dn(),console.log(s.gray("Stopped daemon"))}catch{}await D.clearCredentials(),console.log(s.gray("Removed credentials")),console.log(s.green("✓ Successfully logged out"))}catch(e){throw new Error(`Failed to logout: ${e instanceof Error?e.message:"Unknown error"}`)}else console.log(s.blue("Logout cancelled"))}()}catch(e){console.error(s.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}process.exit(0)}),Xs.command("stop","Stop the daemon",{},async e=>{Bs(),await dn(),process.exit(0)}),Xs.command("status","Show daemon and authentication status",{},async e=>{await Xn("daemon"),console.log(""),await async function(){const e=await D.readCredentials();if(console.log(s.bold("\nAuthentication Status\n")),!e)return void console.log(s.red("✗ Not authenticated"));console.log(s.green("✓ Authenticated"));const n=e.token.substring(0,30)+"...";console.log(s.gray(` Token: ${n}`)),e.machineId?(console.log(s.green("✓ Machine registered")),console.log(s.gray(` Machine ID: ${e.machineId}`)),console.log(s.gray(` Host: ${X.hostname()}`))):console.log(s.yellow("⚠️ Machine not registered")),console.log(s.gray(`\n Data directory: ${D.agentrixHomeDir}`));try{await cn()?console.log(s.green("✓ Daemon running")):console.log(s.gray("✗ Daemon not running"))}catch{console.log(s.gray("✗ Daemon not running"))}}(),process.exit(0)}),Xs.command("ls","List active sessions",{},async e=>{try{const e=await async function(){return(await on("/list")).children||[]}();0===e.length?console.log("No active sessions"):(console.log("Active sessions:"),console.log(JSON.stringify(e,null,2)))}catch(e){console.log("No daemon running")}process.exit(0)}),Xs.command("killall","Clean up all runaway agentrix processes",{},async()=>{const e=await async function(){const e=await async function(){return(await zn()).filter(e=>e.pid!==process.pid&&("daemon"===e.type||"worker"===e.type||"upgrade-daemon"===e.type)).map(e=>({pid:e.pid,command:e.command}))}(),n=[];let a=0;for(const{pid:t,command:s}of e)try{if(console.log(`Killing runaway process PID ${t}: ${s}`),"win32"===process.platform){const e=Ce.sync("taskkill",["/F","/PID",t.toString()],{stdio:"pipe"});if(e.error)throw e.error;if(0!==e.status)throw new Error(`taskkill exited with code ${e.status}`)}else process.kill(t,"SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),(await Ee()).find(e=>e.pid===t)&&(console.log(`Process PID ${t} ignored SIGTERM, using SIGKILL`),process.kill(t,"SIGKILL"));console.log(`Successfully killed runaway process PID ${t}`),a++}catch(e){const a=e.message;n.push({pid:t,error:a}),console.log(`Failed to kill process PID ${t}: ${a}`)}return{killed:a,errors:n}}();console.log(`Cleaned up ${e.killed} runaway processes`),e.errors.length>0&&console.log("Errors:",e.errors),process.exit(0)}),Xs.command("kill <sessionId>","Stop a specific session",e=>e.positional("sessionId",{type:"string",describe:"Session ID to stop"}),async e=>{try{const n=await async function(e){return(await on("/stop-session",{sessionId:e})).success||!1}(e.sessionId);console.log(n?s.green("✓ Session stopped"):s.red("Failed to stop session"))}catch(e){console.log(s.red("No daemon running"))}process.exit(0)}),Xs.command("daemon",!1,{},async e=>{try{await un()}catch(e){console.error(s.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}await _a(),process.exit(0)}),Xs.command("worker",!1,e=>e.option("type",{type:"string",choices:js,demandOption:!0,describe:"Worker type to start"}).option("started-by",{type:"string",choices:["daemon","terminal"],describe:"How the session was started"}).option("user-id",{type:"string",demandOption:!0,describe:"User ID for the worker"}).option("task-id",{type:"string",demandOption:!0,describe:"Task ID for the worker"}).option("idle-timeout",{type:"number",default:300,describe:"Idle timeout in seconds"}),async e=>{try{const n=e.type,a=Ns[n];if(!a)throw new Error(`Unsupported worker type: ${String(e.type)}`);const t=e["started-by"],s=await un(),i=e["user-id"],o=e["task-id"],r=e["idle-timeout"];await a.run({credentials:s,startedBy:t,userId:i,taskId:o,idleTimeoutSecond:r})}catch(e){console.error(s.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}}),Xs.command("upgrade-daemon",!1,{},async e=>{const{startUpgradeDaemon:n}=await Promise.resolve().then(function(){return Vs});await n(),process.exit(0)}),Xs.command("start","Start daemon (if not running) and show status",{},async e=>{try{await un()}catch(e){console.error(s.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}const n=function(){const e=Kn(),n=[],a=e.cli.find(e=>"git"===e.name);a&&!a.installed&&n.push("git");for(const a of e.missingSandbox)n.push(a.name);return{ok:0===n.length,missing:n}}();if(n.ok||(console.log(s.bold.red("\n⚠️ Missing Critical Dependencies")),console.log(s.yellow(`Cannot start daemon. Missing: ${n.missing.join(", ")}`)),console.log(s.blue('\nRun "agentrix doctor" for detailed dependency information and installation instructions.')),process.exit(1)),!await pn()){console.log("Starting Agentrix background service..."),ka(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();let e=!1;for(let n=0;n<50;n++)if(await new Promise(e=>setTimeout(e,100)),await cn()){e=!0;break}e?console.log(s.green("✓ Daemon started successfully")):console.log(s.yellow("⚠️ Daemon may still be starting..."))}if(Us()){const e=await qs();e.hasUpgrade&&(a=e).hasUpgrade&&a.latestVersion&&(console.log(""),console.log(s.yellow("┌────────────────────────────────────────────────────┐")),console.log(s.yellow("│")+" "+s.bold("Upgrade Available")+" "+s.yellow("│")),console.log(s.yellow("│")+" "+s.yellow("│")),console.log(s.yellow("│")+` Current: ${s.dim(a.currentVersion)} → Latest: ${s.green.bold(a.latestVersion)} `+s.yellow("│")),console.log(s.yellow("│")+" "+s.yellow("│")),console.log(s.yellow("│")+" Run "+s.cyan.bold("agentrix upgrade")+" to upgrade "+s.yellow("│")),console.log(s.yellow("│")+" "+s.yellow("│")),console.log(s.yellow("│")+" To enable auto-upgrade, set: "+s.yellow("│")),console.log(s.yellow("│")+" "+s.dim("AGENTRIX_DISABLE_AUTO_UPGRADE=false")+" "+s.yellow("│")),console.log(s.yellow("└────────────────────────────────────────────────────┘")),console.log(""))}else zs()||ka(["upgrade-daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();var a;await Xn("daemon"),process.exit(0)}),Xs.demandCommand(1,"Please specify a command. Use --help to see available commands.").parse();