@agentrix/cli 0.16.0 → 0.17.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 t=e(import.meta.url);import n,{tmpdir as s,homedir as a}from"node:os";import*as i from"node:fs";import o,{existsSync as r,readFileSync as c,statSync as l,writeFileSync as p,renameSync as d,rmSync as u,readdirSync as m,mkdirSync as h,createWriteStream as g,unlinkSync as f}from"node:fs";import*as v from"node:path";import x,{join as y,dirname as b,basename as w,isAbsolute as k,resolve as I,relative as S,normalize as T,extname as E}from"node:path";import A from"yargs";import{hideBin as C}from"yargs/helpers";import $ from"chalk";import{encodeBase64 as _,createKeyPairWithUit8Array as P,encryptMachineEncryptionKey as M,generateAESKey as R,decodeBase64 as O,decryptWithEphemeralKey as D,createEventId as N,encryptFileContent as U,splitRtcChunkFrame as j,RtcChunkFlags as q,buildRtcChunkFrame as L,decryptSdkMessage as H,isSDKUserMessage as G,machineAuth as W,encryptSdkMessage as F,isAskUserMessage as B,isAskUserResponseMessage as z,isSDKMessage as K,decodeGitPath as V,getAgentContext as X,detectPreview as J,IGNORED_DIRECTORIES as Y,DEFAULT_WORKER_EXECUTION_MODE as Q,isCompanionHeartbeatMessage as Z,isCompanionReminderMessage as ee,workerAuth as te}from"@agentrix/shared";import{randomBytes as ne,randomUUID as se,timingSafeEqual as ae,createHash as ie}from"node:crypto";import oe from"axios";import{m as re,l as ce,p as le,a as pe,c as de,g as ue,b as me}from"./logger-BVnpkRi2.mjs";import{createInterface as he}from"node:readline";import*as ge from"fs";import fe,{readFileSync as ve,existsSync as xe,promises as ye}from"fs";import*as be from"path";import we,{join as ke,dirname as Ie}from"path";import Se from"open";import{io as Te}from"socket.io-client";import{EventEmitter as Ee}from"node:events";import{GitServerLocalStore as Ae,validateGitLabPatToken as Ce,deriveLocalGitServerEncryptionKey as $e,replacePromptPlaceholders as _e,loadAgentConfig as Pe,getAgentContext as Me,buildGitLabWebhookUrl as Re,buildGitLabWebhookEndpointPath as Oe}from"@agentrix/shared/node";import{createRequire as De}from"node:module";import{spawn as Ne,execSync as Ue}from"child_process";import je from"ps-list";import qe from"cross-spawn";import{getPlatform as Le}from"@xmz-ai/sandbox-runtime/dist/utils/platform.js";import He from"fastify";import{z as Ge,toJSONSchema as We}from"zod";import{validatorCompiler as Fe,serializerCompiler as Be}from"fastify-type-provider-zod";import{spawnSync as ze,execSync as Ke,execFile as Ve}from"node:child_process";import{createSdkMcpServer as Xe,query as Je,tool as Ye,AbortError as Qe}from"@anthropic-ai/claude-agent-sdk";import{EventEmitter as Ze}from"events";import et from"better-sqlite3";import{fileURLToPath as tt,pathToFileURL as nt}from"url";import{pipeline as st}from"node:stream/promises";import{isSupportedPlatform as at,NetworkManager as it,SandboxManager as ot}from"@xmz-ai/sandbox-runtime";import{Cron as rt}from"croner";import{readFile as ct}from"fs/promises";import lt from"simple-git";import{promisify as pt}from"node:util";import{mkdir as dt,writeFile as ut,readFile as mt}from"node:fs/promises";import{randomUUID as ht}from"crypto";import{Codex as gt}from"@openai/codex-sdk";import{stdin as ft,stdout as vt}from"node:process";import{createInterface as xt}from"node:readline/promises";import"winston";import"os";const yt=new Set(["AGENTRIX_CLAUDE_HOME","AGENTRIX_CODEX_HOME","AGENTRIX_CLAUDE_PATH","AGENTRIX_CODEX_PATH"]);function bt(e){return e.replace(/^~(?=\/|$)/,n.homedir())}function wt(e,t,n){const s=t.toLowerCase();"http_proxy"===s?(e.HTTP_PROXY=n,e.http_proxy=n):"https_proxy"===s?(e.HTTPS_PROXY=n,e.https_proxy=n):"no_proxy"===s?(e.NO_PROXY=n,e.no_proxy=n):"all_proxy"===s?(e.ALL_PROXY=n,e.all_proxy=n):"global_agent_http_proxy"===s&&(e.GLOBAL_AGENT_HTTP_PROXY=n,e.global_agent_http_proxy=n)}function kt(e,t,n){const s=n.trim();s&&("AGENTRIX_CLAUDE_HOME"===t?e.CLAUDE_CONFIG_DIR=bt(s):"AGENTRIX_CODEX_HOME"===t&&(e.CODEX_HOME=bt(s)))}async function It(e){return new Promise(t=>setTimeout(t,e))}async function St(e,t){const n=await re.readDaemonState();if(!n?.port){const e="No daemon running, no state file found";return ce.debug(`[CONTROL CLIENT] ${e}`),{error:e}}try{const s=process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT?parseInt(process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT):1e4,a=await fetch(`http://agentrix-local.xmz.ai:${n.port}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{}),signal:AbortSignal.timeout(s)});if(!a.ok){const t=await a.json().catch(()=>null),n=("string"==typeof t?.error?t.error:"string"==typeof t?.message?t.message:void 0)||`Request failed: ${e}, HTTP ${a.status}`;return ce.debug(`[CONTROL CLIENT] ${n}`),{error:n}}return await a.json()}catch(t){const n=`Request failed: ${e}, ${t instanceof Error?t.message:"Unknown error"}`;return ce.debug(`[CONTROL CLIENT] ${n}`),{error:n}}}async function Tt(e,t){return await St("/session-started",{sessionId:e,metadata:t})}async function Et(){const e=await re.readDaemonState();if(!e)return!1;try{return process.kill(e.pid,0),!0}catch{return ce.debug("[DAEMON RUN] Daemon PID not running, cleaning up state"),await Ct(),!1}}async function At(){if(ce.debug("[DAEMON CONTROL] Checking if daemon is running same version"),!await Et())return ce.debug("[DAEMON CONTROL] No daemon running, returning false"),!1;const e=await re.readDaemonState();if(!e)return ce.debug("[DAEMON CONTROL] No daemon state found, returning false"),!1;try{const t=ke(le(),"package.json"),n=JSON.parse(ve(t,"utf-8")).version;return ce.debug(`[DAEMON CONTROL] Current CLI version: ${n}, Daemon started with version: ${e.cliVersion}`),n===e.cliVersion}catch(e){return ce.debug("[DAEMON CONTROL] Error checking daemon version",e),!1}}async function Ct(){try{await re.clearDaemonState(),ce.debug("[DAEMON RUN] Daemon state file removed")}catch(e){ce.debug("[DAEMON RUN] Error cleaning up daemon metadata",e)}}async function $t(){try{const e=await re.readDaemonState();if(!e)return void ce.debug("No daemon state found");ce.debug(`Stopping daemon with PID ${e.pid}`);try{return await async function(){await St("/stop")}(),void await async function(e){const t=Date.now();for(;Date.now()-t<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){ce.debug("HTTP stop failed, will force kill",e)}process.kill(e.pid,"SIGKILL")}catch(e){ce.debug("Error stopping daemon",e)}}function _t(e){return`${e}\nRun \`agentrix logout\` and bind this machine again.`}function Pt(e,t){if(oe.isAxiosError(e)){const n=e.response?.data?.message;return"string"==typeof n&&n.length>0?n.includes("Machine binding revoked")?_t(n):`${t}: ${n}`:"string"==typeof e.message&&e.message.includes("Machine binding revoked")?_t(e.message):`${t}: ${e.message}`}return e instanceof Error&&e.message.includes("Machine binding revoked")?_t(e.message):e instanceof Error?`${t}: ${e.message}`:t}function Mt(){return _(new Uint8Array(ne(32)))}async function Rt(){const e=await re.readCredentials();if(e){if(await async function(e){try{await oe.get(`${re.serverUrl}/v1/machines/validate`,{headers:{Authorization:`Bearer ${e.token}`},timeout:15e3})}catch(e){throw new Error(Pt(e,"Stored machine credentials are no longer valid"))}}(e),!e.secret){const t={...e,secret:Mt()};return await re.writeCredentials(t),ce.info("[AUTH] Generated missing local auth secret"),t}return ce.info("[AUTH] Using existing credentials"),e}const t=process.env.CLOUD_AUTH_TOKEN;let n,s,a;if(t){const e=re.generateMachineId();n={token:t,secret:Mt(),machineId:e},ce.info(`[AUTH] Cloud mode detected, generated machine ID: ${e}`)}else{const e=await async function(){console.clear();const e=re.generateMachineId(),t=new Uint8Array(ne(32)),n=await P(t);try{console.log(`[AUTH] Sending auth request to: ${re.serverUrl}/v1/auth/machine`),console.log(`[AUTH] Public key: ${_(n.publicKey).substring(0,20)}...`);const t={machineId:e};await oe.post(`${re.serverUrl}/v1/auth/machine`,t),console.log("[AUTH] Auth request sent successfully")}catch(e){return console.log(Pt(e,"Failed to create authentication request, please try again later.")),{credentials:null,userPublicKey:null,keypair:n}}const s=await async function(e,t){console.clear(),console.log("\nWeb Authentication\n");const n=function(e,t){const n={key:_(e,"base64"),machineId:t},s=JSON.stringify(n),a=_((new TextEncoder).encode(s),"base64url");return`${re.webappUrl}/terminal/connect?auth=${a}`}(e.publicKey,t);return console.log("Opening your browser..."),await async function(e){try{return!process.stdout.isTTY||process.env.CI||process.env.HEADLESS?(ce.debug("[browser] Headless environment detected, skipping browser open"),!1):(ce.debug(`[browser] Attempting to open URL: ${e}`),await Se(e),ce.debug("[browser] Browser opened successfully"),!0)}catch(e){return ce.debug("[browser] Failed to open browser:",e),!1}}(n)?(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(n),console.log(""),await async function(e,t){process.stdout.write("Waiting for authentication");let n=0,s=!1;const a=()=>{s=!0,console.log("\n\nAuthentication cancelled."),process.exit(0)};process.on("SIGINT",a);try{for(;!s;){try{const n=await oe.get(`${re.serverUrl}/v1/auth/machine?machineId=${t}`);if("authorized"===n.data.state){const t=n.data.token,s=n.data.content,a=D(O(s),e.secretKey);return a?{token:t,userPublicKey:JSON.parse((new TextDecoder).decode(a)).publicKey}:(console.log("\n\nFailed to decrypt authentication data. Please try again."),{token:null,userPublicKey:null})}}catch(e){return console.log(`\n\n${Pt(e,"Failed to check authentication status. Please try again.")}`),{token:null,userPublicKey:null}}process.stdout.write("\rWaiting for authentication"+".".repeat(n%3+1)+" "),n++,await It(1e3)}}finally{process.off("SIGINT",a)}return{token:null,userPublicKey:null}}(e,t)}(n,e);return s.token?{credentials:{token:s.token,secret:_(t),machineId:e},userPublicKey:s?.userPublicKey,keypair:n}:{credentials:null,userPublicKey:null,keypair:n}}();if(!e.credentials||!e.userPublicKey)throw new Error("Authentication failed or was cancelled");n=e.credentials,s=e.keypair,a=e.userPublicKey}return await re.writeCredentials(n),await async function(e,t,n,s){try{const a={id:e.machineId,metadata:JSON.stringify(t)};s&&n&&(a.dataEncryptionKey=M(s.publicKey,R(),O(n))),await oe.post(`${re.serverUrl}/v1/machines/sync`,a,{headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},timeout:6e4})}catch(e){throw new Error(Pt(e,"Failed to sync machine data"))}}(n,re.metadata(),a,s),ce.info("[AUTH] Machine setup completed"),n}!function(e=process.env){!function(e=process.env,t){if(!t?.variables)return e;const n=!0===t.enabled;for(const[s,a]of Object.entries(t.variables)){const t=s.trim();if(!t)continue;const i=String(a),o=yt.has(t);(n||o)&&(e[t]=i,wt(e,t,i),kt(e,t,i))}}(e,function(e=process.env){const t=y(function(e=process.env){const t=e.AGENTRIX_HOME_DIR||e.AGENTRIX_DIR;return t?bt(t):y(n.homedir(),".agentrix")}(e),"settings.json");if(!r(t))return null;try{const e=c(t,"utf-8"),n=JSON.parse(e);return n?.daemonEnv||null}catch{return null}}(e))}();class Ot{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}}function Dt(e){if(!e||"object"!=typeof e)return String(e??"unknown error");const t=e,n=[];return t.message&&n.push(t.message),t.type&&n.push(`type=${t.type}`),void 0!==t.description&&n.push(`description=${JSON.stringify(t.description)}`),void 0!==t.data&&n.push(`data=${JSON.stringify(t.data)}`),void 0!==t.context&&n.push(`context=${JSON.stringify(t.context)}`),n.filter(Boolean).join(" ")||"unknown socket error"}class Nt{socket=null;config;eventHandlers=new Map;eventEmitter=new Ee;KeepAliveManager=null;healthCheckInterval=null;constructor(e){this.config=e,e.keepAliveConfig&&(this.KeepAliveManager=new Ot(e.keepAliveConfig))}connect(){if(this.socket)return void this.log("Already connected or connecting");const{serverUrl:e,path:t,auth:n={},options:s={}}=this.config,a={path:t,auth:n,transports:["websocket"],reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:1/0,...s};this.socket=Te(e,a),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,t,n){this.socket&&(t&&this.socket.off(e,t),this.socket.on(e,n))}onEvent(e,t){const n=async n=>(this.log(`received event ${e}, data: ${JSON.stringify(n)}`),t(n)),s=this.eventHandlers.get(e);this.eventHandlers.set(e,n),this.replaceSocketHandler(e,s,n)}onEventWithAck(e,t){const n=async(n,s)=>(this.log(`received event with ack ${e}, data: ${JSON.stringify(n)}`),t(n,s)),s=this.eventHandlers.get(e);this.eventHandlers.set(e,n),this.replaceSocketHandler(e,s,n)}unregisterHandler(e){this.eventHandlers.delete(e),this.socket&&this.socket.off(e)}send(e,t){this.socket?(this.log(`send event ${e}`),void 0!==t?this.socket.emit(e,t):this.socket.emit(e)):this.log("Cannot send - socket not connected")}async sendWithAck(e,t){if(!this.socket)throw new Error("Cannot send - socket not connected");return this.log(`send event ${e}, data: ${JSON.stringify(t)}`),this.socket.emitWithAck(e,t)}sendVolatile(e,t){this.socket&&(void 0!==t?this.socket.volatile.emit(e,t):this.socket.volatile.emit(e))}async flush(e=1e4){if(this.connected)return new Promise(t=>{const n=setTimeout(()=>t(),e);this.socket.emit("ping",()=>{clearTimeout(n),t()})})}updateAuth(e){this.socket&&(this.socket.auth=e),this.config.auth=e}onLifecycle(e,t){this.eventEmitter.on(`lifecycle:${e}`,t)}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,t]of this.eventHandlers.entries())this.socket.off(e,t),this.socket.on(e,t);this.KeepAliveManager?.start(this.socket),this.startHealthCheck()}),this.socket.on("disconnect",e=>{this.log(`Disconnected: ${e||"unknown"}`),this.eventEmitter.emit("lifecycle:disconnect",e),this.KeepAliveManager?.stop(),this.stopHealthCheck()}),this.socket.on("connect_error",e=>{this.log(`Connection error: ${Dt(e)}`),this.eventEmitter.emit("lifecycle:connect_error",e),setTimeout(()=>this.socket?.connect(),5e3)}),this.socket.on("error",e=>{this.log(`Socket error: ${Dt(e)}`),this.eventEmitter.emit("lifecycle:error",e)}))}startHealthCheck(){const e=this.config.healthCheckConfig;if(!1===e?.enabled)return;const t=e?.intervalMs??3e4,n=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())},n);this.socket.once("pong",()=>{clearTimeout(e)}),this.socket.emit("ping")},t)}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}log(e,...t){this.config.logger&&this.config.logger(`[SocketClient] ${e}`,...t)}}function Ut(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}),n}var jt,qt,Lt,Ht={},Gt={"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/activemessage":{source:"iana"},"application/activity+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-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/applefile":{source:"iana"},"application/applixware":{source:"apache",extensions:["aw"]},"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/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/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/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/cea":{source:"iana"},"application/cea-2018+xml":{source:"iana",compressible:!0},"application/cellml+xml":{source:"iana",compressible:!0},"application/cfw":{source:"iana"},"application/city+json":{source:"iana",compressible:!0},"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-group+json":{source:"iana",compressible:!0},"application/coap-payload":{source:"iana"},"application/commonground":{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/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/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"},"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/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/ecmascript":{source:"iana",compressible:!0,extensions:["es","ecma"]},"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.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/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/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/geoxacml+xml":{source:"iana",compressible:!0},"application/gltf-buffer":{source:"iana"},"application/gml+xml":{source:"iana",compressible:!0,extensions:["gml"]},"application/gpx+xml":{source:"apache",compressible:!0,extensions:["gpx"]},"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/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:"apache",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:"iana",charset:"UTF-8",compressible:!0,extensions:["js","mjs"]},"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/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/jwk+json":{source:"iana",compressible:!0},"application/jwk-set+json":{source:"iana",compressible:!0},"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/load-control+xml":{source:"iana",compressible:!0},"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:["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/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:!1,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/omdoc+xml":{source:"apache",compressible:!0,extensions:["omdoc"]},"application/onenote":{source:"apache",extensions:["onetoc","onetoc2","onetmp","onepkg"]},"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:["asc","sig"]},"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/problem+json":{source:"iana",compressible:!0},"application/problem+xml":{source:"iana",compressible:!0},"application/provenance+xml":{source:"iana",compressible:!0,extensions:["provx"]},"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.nprend":{source:"iana"},"application/prs.plucker":{source:"iana"},"application/prs.rdf-xml-crypt":{source:"iana"},"application/prs.xsf+xml":{source:"iana",compressible:!0},"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:"iana"},"application/reputon+json":{source:"iana",compressible:!0},"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-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-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:"iana"},"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"},"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/ssml+xml":{source:"iana",compressible:!0,extensions:["ssml"]},"application/stix+json":{source:"iana",compressible:!0},"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/tnauthlist":{source:"iana"},"application/token-introspection+jwt":{source:"iana"},"application/toml":{compressible:!0,extensions:["toml"]},"application/trickle-ice-sdpfrag":{source:"iana"},"application/trig":{source:"iana",extensions:["trig"]},"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/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/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.3gpp-prose+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3ch+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-v2x-local-service-information":{source:"iana"},"application/vnd.3gpp.5gnas":{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.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-payload":{source:"iana"},"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-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-affiliation-info+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-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.s1ap":{source:"iana"},"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.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.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:"iana",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:"iana"},"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.thrift.binary":{source:"iana"},"application/vnd.apache.thrift.compact":{source:"iana"},"application/vnd.apache.thrift.json":{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:"iana"},"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.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.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.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.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.datapackage+json":{source:"iana",compressible:!0},"application/vnd.dataresource+json":{source:"iana",compressible:!0},"application/vnd.dbf":{source:"iana",extensions:["dbf"]},"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.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.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:"iana",extensions:["fdf"]},"application/vnd.fdsn.mseed":{source:"iana",extensions:["mseed"]},"application/vnd.fdsn.seed":{source:"iana",extensions:["seed","dataless"]},"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.frogans.fnc":{source:"iana",extensions:["fnc"]},"application/vnd.frogans.ltf":{source:"iana",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.genomatix.tuxedo":{source:"iana",extensions:["txd"]},"application/vnd.gentics.grd+json":{source:"iana",compressible:!0},"application/vnd.geo+json":{source:"iana",compressible:!0},"application/vnd.geocube+xml":{source:"iana",compressible:!0},"application/vnd.geogebra.file":{source:"iana",extensions:["ggb"]},"application/vnd.geogebra.slides":{source:"iana"},"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.google-apps.document":{compressible:!1,extensions:["gdoc"]},"application/vnd.google-apps.presentation":{compressible:!1,extensions:["gslides"]},"application/vnd.google-apps.spreadsheet":{compressible:!1,extensions:["gsheet"]},"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:"iana",compressible:!0},"application/vnd.gov.sk.e-form+zip":{source:"iana",compressible:!1},"application/vnd.gov.sk.xmldatacontainer+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.hl7cda+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.hl7v2+xml":{source:"iana",charset:"UTF-8",compressible:!0},"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.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:"iana"},"application/vnd.ibm.electronic-media":{source:"iana"},"application/vnd.ibm.minipay":{source:"iana",extensions:["mpy"]},"application/vnd.ibm.modcap":{source:"iana",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:"iana"},"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.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.kenameaapp":{source:"iana",extensions:["htke"]},"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.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.medcalcdata":{source:"iana",extensions:["mc1"]},"application/vnd.mediastation.cdkey":{source:"iana",extensions:["cdkey"]},"application/vnd.meridian-slingshot":{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.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-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.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.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:"iana",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.oasis.opendocument.chart":{source:"iana",extensions:["odc"]},"application/vnd.oasis.opendocument.chart-template":{source:"iana",extensions:["otc"]},"application/vnd.oasis.opendocument.database":{source:"iana",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-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:"iana",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:"iana",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.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.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.proteus.magazine":{source:"iana",extensions:["mgz"]},"application/vnd.psfs":{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},"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.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.smaf":{source:"iana",extensions:["mmf"]},"application/vnd.smart.notebook":{source:"iana"},"application/vnd.smart.teacher":{source:"iana",extensions:["teacher"]},"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.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.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"]},"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.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"]},"application/vnd.visionary":{source:"iana",extensions:["vis"]},"application/vnd.vividence.scriptfile":{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.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.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.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.youtube.yt":{source:"iana"},"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/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-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-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-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-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/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/yang":{source:"iana",extensions:["yang"]},"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/yin+xml":{source:"iana",compressible:!0,extensions:["yin"]},"application/zip":{source:"iana",compressible:!1,extensions:["zip"]},"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"},"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/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/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/mobile-xmf":{source:"iana",extensions:["mxmf"]},"audio/mp3":{compressible:!1,extensions:["mp3"]},"audio/mp4":{source:"iana",compressible:!1,extensions:["m4a","mp4a"]},"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:"iana"},"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":{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"]},"image/cgm":{source:"iana",extensions:["cgm"]},"image/dicom-rle":{source:"iana",extensions:["drle"]},"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/hsj2":{source:"iana",extensions:["hsj2"]},"image/ief":{source:"iana",extensions:["ief"]},"image/jls":{source:"iana",extensions:["jls"]},"image/jp2":{source:"iana",compressible:!1,extensions:["jp2","jpg2"]},"image/jpeg":{source:"iana",compressible:!1,extensions:["jpeg","jpg","jpe"]},"image/jph":{source:"iana",extensions:["jph"]},"image/jphc":{source:"iana",extensions:["jhc"]},"image/jpm":{source:"iana",compressible:!1,extensions:["jpm"]},"image/jpx":{source:"iana",compressible:!1,extensions:["jpx","jpf"]},"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},"image/png":{source:"iana",compressible:!1,extensions:["png"]},"image/prs.btif":{source:"iana",extensions:["btif"]},"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.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:"apache",extensions:["webp"]},"image/wmf":{source:"iana",extensions:["wmf"]},"image/x-3ds":{source:"apache",extensions:["3ds"]},"image/x-cmu-raster":{source:"apache",extensions:["ras"]},"image/x-cmx":{source:"apache",extensions:["cmx"]},"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-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/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/news":{source:"iana"},"message/partial":{source:"iana",compressible:!1},"message/rfc822":{source:"iana",compressible:!0,extensions:["eml","mime"]},"message/s-http":{source:"iana"},"message/sip":{source:"iana"},"message/sipfrag":{source:"iana"},"message/tracking-status":{source:"iana"},"message/vnd.si.simp":{source:"iana"},"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/mesh":{source:"iana",compressible:!1,extensions:["msh","mesh","silo"]},"model/mtl":{source:"iana",extensions:["mtl"]},"model/obj":{source:"iana",extensions:["obj"]},"model/step":{source:"iana"},"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/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"},"model/vnd.rosette.annotated-data-model":{source:"iana"},"model/vnd.sap.vds":{source:"iana",extensions:["vds"]},"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:"iana"},"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/html":{source:"iana",compressible:!0,extensions:["html","htm","shtml"]},"text/jade":{extensions:["jade"]},"text/javascript":{source:"iana",compressible:!0},"text/jcr-cnd":{source:"iana"},"text/jsx":{compressible:!0,extensions:["jsx"]},"text/less":{compressible:!0,extensions:["less"]},"text/markdown":{source:"iana",compressible:!0,extensions:["markdown","md"]},"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/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.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:"iana"},"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.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/vtt":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["vtt"]},"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/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/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/mj2":{source:"iana",extensions:["mj2","mjp2"]},"video/mp1s":{source:"iana"},"video/mp2p":{source:"iana"},"video/mp2t":{source:"iana",extensions:["ts"]},"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.radgamettools.bink":{source:"iana"},"video/vnd.radgamettools.smacker":{source:"iana"},"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}},Wt=(Lt||(Lt=1,function(e){var t,n,s,a=qt?jt:(qt=1,jt=Gt),i=we.extname,o=/^\s*([^;\s]*)(?:;|\s|$)/,r=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var t=o.exec(e),n=t&&a[t[1].toLowerCase()];return n&&n.charset?n.charset:!(!t||!r.test(t[1]))&&"UTF-8"}e.charset=c,e.charsets={lookup:c},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var n=-1===t.indexOf("/")?e.lookup(t):t;if(!n)return!1;if(-1===n.indexOf("charset")){var s=e.charset(n);s&&(n+="; charset="+s.toLowerCase())}return n},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var n=o.exec(t),s=n&&e.extensions[n[1].toLowerCase()];return!(!s||!s.length)&&s[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var n=i("x."+t).toLowerCase().substr(1);return n&&e.types[n]||!1},e.types=Object.create(null),t=e.extensions,n=e.types,s=["nginx","apache",void 0,"iana"],Object.keys(a).forEach(function(e){var i=a[e],o=i.extensions;if(o&&o.length){t[e]=o;for(var r=0;r<o.length;r++){var c=o[r];if(n[c]){var l=s.indexOf(a[n[c]].source),p=s.indexOf(i.source);if("application/octet-stream"!==n[c]&&(l>p||l===p&&"application/"===n[c].substr(0,12)))continue}n[c]=e}}})}(Ht)),Ht);function Ft(e,t){e?e.send("workspace-file-response",t):ce.error("[WORKSPACE] Cannot send workspace-file-response: client not available")}function Bt(e,t,n,s){return{eventId:N(),requestId:e,taskId:t,success:!1,error:{code:n,message:s}}}function zt(e){return async t=>{const{taskId:n,userId:s,relativePath:a,requestId:o,maxFileSizeMB:r,ifModifiedSince:c,dataEncryptionKey:l}=t;ce.debug(`[WORKSPACE] File request: taskId=${n}, userId=${s}, relativePath=${a}, maxFileSizeMB=${r}, ifModifiedSince=${c}, hasEncryptionKey=${!!l}`);try{const t=1024*(r||10)*1024,p=function(e,t,n){return re.resolveWorkspaceFilePath(e,t,n)}(s,n,a);if(!i.existsSync(p))return ce.warn(`[WORKSPACE] File not found: ${p}`),void Ft(e.client,Bt(o,n,"file_not_found","File or directory not found"));const d=await i.promises.stat(p),u=d.mtime.toISOString();if(c&&u===c)return void function(e,t,n,s){ce.debug(`[WORKSPACE] File not modified: ${s}`),Ft(e,{eventId:N(),requestId:t,taskId:n,success:!0,notModified:!0})}(e.client,o,n,p);if(d.isDirectory())return void await async function(e,t,n,s,a,o){const r=await i.promises.readdir(s,{withFileTypes:!0}),c=await Promise.all(r.map(async e=>{const t=v.join(s,e.name),n=await i.promises.stat(t);return{name:e.name,type:e.isDirectory()?"directory":"file",size:n.size,modifiedAt:n.mtime.toISOString(),accessDenied:n.size>o}}));Ft(e,{eventId:N(),requestId:t,taskId:n,success:!0,data:{type:"directory",entries:c,metadata:{size:0,modifiedAt:a.mtime.toISOString()}}})}(e.client,o,n,p,d,t);{const s=Wt.lookup(p)||"application/octet-stream";return d.size>t?void function(e,t,n,s,a,i,o){ce.warn(`[WORKSPACE] File too large (${a.size} bytes > ${o} bytes): ${s}`),Ft(e,{eventId:N(),requestId:t,taskId:n,success:!0,data:{type:"file",metadata:{size:a.size,mimeType:i,modifiedAt:a.mtime.toISOString(),accessDenied:!0}}})}(e.client,o,n,p,d,s,t):void await async function(e,t,n,s,a,o){const r=Wt.lookup(s)||"application/octet-stream",c=(await i.promises.readFile(s)).toString("base64");let l=null;o&&(l=await async function(e){try{const t=await re.getSecretKey();if(!t)return ce.warn("[WORKSPACE] Machine secret key not available"),null;const n=O(e);return D(n,t)||(ce.warn("[WORKSPACE] Failed to decrypt dataEncryptionKey"),null)}catch(e){return ce.warn("[WORKSPACE] Error decrypting dataEncryptionKey:",e),null}}(o));const p={type:"file",metadata:{size:a.size,mimeType:r,modifiedAt:a.mtime.toISOString()}};l?p.encryptedContent=U(c,l):p.content=c,Ft(e,{eventId:N(),requestId:t,taskId:n,success:!0,data:p})}(e.client,o,n,p,d,l)}}catch(t){ce.error(`[WORKSPACE] Failed to handle workspace-file-request: ${t.message}`,t);const s="ENOENT"===t.code?"file_not_found":"EACCES"===t.code?"permission_denied":"unknown_error";Ft(e.client,Bt(o,n,s,t.message))}}}const Kt=new Ae({credentialsDir:y(re.agentrixHomeDir,"credentials")});async function Vt(){const e=await re.readCredentials();return e?.secret?$e(e.secret):null}function Xt(e,t){Kt.saveGitServerConfig(e,t)}function Jt(){return Kt.listGitServerIds()}function Yt(e){return Kt.loadGitServerConfig(e)}function Qt(e,t){return Kt.loadGitLabWebhookBridgeSecrets(e,t)}function Zt(e,t,n){Kt.saveGitLabWebhookBridgeSecrets(e,t,n)}function en(e,t){return Kt.ensureGitLabWebhookSecret(e,t)}function tn(e){return Kt.loadPatMeta(e)}function nn(e,t){Kt.savePatMeta(e,t)}function sn(e,t,n){Kt.savePat(e,t,n)}function an(e,t){return Kt.loadPat(e,t)}const on=100,rn=[{method:"GET",pattern:/^\/user$/},{method:"GET",pattern:/^\/projects$/},{method:"GET",pattern:/^\/projects\/[^/]+\/repository\/branches$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues$/},{method:"POST",pattern:/^\/projects\/[^/]+\/issues$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues\/\d+$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/issues\/\d+$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues\/\d+\/notes$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues\/\d+\/discussions$/},{method:"POST",pattern:/^\/projects\/[^/]+\/issues\/\d+\/discussions$/},{method:"POST",pattern:/^\/projects\/[^/]+\/issues\/\d+\/discussions\/[^/]+\/notes$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/changes$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/notes$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/approvals$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions\/[^/]+\/notes$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/approve$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions\/[^/]+$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions\/[^/]+\/notes\/\d+$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/merge$/}];class cn{apiUrl;pat;requestId;gitServerId;constructor(e,t,n){this.apiUrl=e,this.pat=t,this.requestId=n?.requestId,this.gitServerId=n?.gitServerId}logPrefix(){return`[GITLAB EXECUTOR] reqId=${this.requestId??"-"}, gitServer=${this.gitServerId??"-"}`}summarizeResult(e,t){if(Array.isArray(t))return`items=${t.length}`;if(t&&"object"==typeof t){const n=t;return"resolveGitAuthContext"===e?`authMode=${String(n.authMode??"unknown")}, hasPat=${Boolean(n.hasPat)}`:"id"in n&&"status"in n?`id=${String(n.id??"-")}, status=${String(n.status??"-")}`:"number"in n||"state"in n?`number=${String(n.number??"-")}, state=${String(n.state??"-")}`:`keys=${Object.keys(n).join(",")||"-"}`}return"type="+typeof t}truncateText(e,t=300){return e.length<=t?e:`${e.slice(0,t)}...`}async requestWithResponse(e,t="GET",n){const s=`${this.apiUrl}${e}`,a={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/json"},i=Date.now();ce.debug(`${this.logPrefix()} request start: ${t} ${e}`);try{const o=await fetch(s,{method:t,headers:a,body:n?JSON.stringify(n):void 0}),r=Date.now()-i;if(!o.ok){const n=await o.text().catch(()=>"Unknown error"),s=this.truncateText(n);throw ce.warn(`${this.logPrefix()} request failed: ${t} ${e}, status=${o.status}, elapsedMs=${r}, detail=${s}`),{status:o.status,message:`GitLab API error: ${o.status} ${o.statusText}`,detail:s}}return ce.debug(`${this.logPrefix()} request success: ${t} ${e}, elapsedMs=${r}`),{data:await o.json(),headers:o.headers}}catch(n){if("object"==typeof n&&null!==n&&"status"in n)throw n;const s=n instanceof Error?n.message:"Unknown network error";throw ce.error(`${this.logPrefix()} request exception: ${t} ${e}, message=${s}`),{status:0,message:`GitLab request failed: ${s}`}}}async requestForm(e,t){const n=`${this.apiUrl}${e}`,s={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/x-www-form-urlencoded"},a=Date.now();ce.debug(`${this.logPrefix()} form request start: POST ${e}`);try{const i=await fetch(n,{method:"POST",headers:s,body:t}),o=Date.now()-a;if(!i.ok){const t=await i.text().catch(()=>"Unknown error"),n=this.truncateText(t);throw ce.warn(`${this.logPrefix()} form request failed: POST ${e}, status=${i.status}, elapsedMs=${o}, detail=${n}`),{status:i.status,message:`GitLab API error: ${i.status} ${i.statusText}`,detail:n}}return ce.debug(`${this.logPrefix()} form request success: POST ${e}, elapsedMs=${o}`),await i.json()}catch(t){if("object"==typeof t&&null!==t&&"status"in t)throw t;const n=t instanceof Error?t.message:"Unknown network error";throw ce.error(`${this.logPrefix()} form request exception: POST ${e}, message=${n}`),{status:0,message:`GitLab request failed: ${n}`}}}async request(e,t="GET",n){const{data:s}=await this.requestWithResponse(e,t,n);return s}withQueryParams(e,t){const[n,s=""]=e.split("?"),a=new URLSearchParams(s);for(const[e,n]of Object.entries(t))a.set(e,String(n));const i=a.toString();return i?`${n}?${i}`:n}parseTotalPages(e){const t=e.get("x-total-pages");if(!t)return null;const n=Number.parseInt(t,10);return!Number.isFinite(n)||n<=0?null:n}async fetchRemainingPagesInBatches(e,t){const n=[];for(let s=2;s<=e;s+=4){const a=Math.min(s+4-1,e),i=Array.from({length:a-s+1},(e,t)=>s+t),o=await Promise.all(i.map(e=>t(e)));for(const e of o)n.push(...e)}return n}async requestPaginated(e){const t=this.withQueryParams(e,{per_page:on,page:1}),n=await this.requestWithResponse(t),s=[...n.data],a=this.parseTotalPages(n.headers);if(a&&a>1){const t=await this.fetchRemainingPagesInBatches(a,async t=>{const n=this.withQueryParams(e,{per_page:on,page:t});return this.request(n)});return s.push(...t),s}if(!a&&n.data.length===on){let t=2;for(;;){const n=this.withQueryParams(e,{per_page:on,page:t}),a=await this.request(n);if(0===a.length)break;if(s.push(...a),a.length<on)break;t+=1}}return s}async executeOperation(e,t){ce.info(`${this.logPrefix()} execute operation: op=${e}, payloadKeys=${Object.keys(t||{}).join(",")||"-"}`);try{let n;switch(e){case"listRepos":n=await this.listRepos();break;case"listBranches":n=await this.listBranches(t.owner,t.name);break;case"createMergeRequest":n=await this.createMergeRequest(t);break;case"getMergeRequest":n=await this.getMergeRequest(t.owner,t.name,t.iid);break;case"listMergeRequests":n=await this.listMergeRequests(t.owner,t.name);break;case"triggerPipeline":n=await this.triggerPipeline(t);break;case"ensurePipelineTriggerToken":n=await this.ensurePipelineTriggerToken(t);break;case"requestGitlabApi":n=await this.requestGitlabApi(t);break;case"resolveGitAuthContext":n={authMode:"local_pat",hasPat:!0};break;default:throw{status:400,message:`Unknown operation: ${e}`}}return ce.info(`${this.logPrefix()} operation success: op=${e}, summary=${this.summarizeResult(e,n)}`),n}catch(t){const n=t instanceof Error?t.message:"object"==typeof t&&null!==t&&"message"in t?String(t.message):"Unknown error";throw ce.error(`${this.logPrefix()} operation failed: op=${e}, message=${n}`),t}}async listRepos(){return(await this.requestPaginated("/projects?membership=true&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,t){const n=encodeURIComponent(`${e}/${t}`);return(await this.requestPaginated(`/projects/${n}/repository/branches`)).map(e=>({name:e.name,commit:{sha:e.commit.id,url:""},protected:e.protected}))}async createMergeRequest(e){const t=encodeURIComponent(`${e.owner}/${e.repo}`),n=await this.request(`/projects/${t}/merge_requests`,"POST",{source_branch:e.head,target_branch:e.base,title:e.title,description:e.body||""});return{number:n.iid,title:n.title,body:n.description,state:"opened"===n.state?"open":n.state,url:n.web_url,head:n.source_branch,base:n.target_branch,createdAt:n.created_at,updatedAt:n.updated_at}}async getMergeRequest(e,t,n){const s=encodeURIComponent(`${e}/${t}`),a=await this.request(`/projects/${s}/merge_requests/${n}`);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 listMergeRequests(e,t){const n=encodeURIComponent(`${e}/${t}`);return(await this.request(`/projects/${n}/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}))}parseNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw{status:400,message:`${t} is required`};return e.trim()}parseOptionalString(e,t){if(null!=e){if("string"!=typeof e||0===e.trim().length)throw{status:400,message:`${t} must be a non-empty string`};return e.trim()}}resolveProjectPath(e){if("number"==typeof e.projectId||"string"==typeof e.projectId){const t=String(e.projectId).trim();if(t.length>0)return encodeURIComponent(t)}const t=this.parseOptionalString(e.projectPath,"projectPath");if(t)return encodeURIComponent(t);const n=this.parseOptionalString(e.owner,"owner"),s=this.parseOptionalString(e.repo??e.name,"repo");if(!n||!s)throw{status:400,message:"projectId, projectPath, or owner + repo is required"};return encodeURIComponent(`${n}/${s}`)}parsePipelineVariables(e){if(null==e)return{};if("object"!=typeof e||Array.isArray(e))throw{status:400,message:"Pipeline variables must be an object"};const t={};for(const[n,s]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw{status:400,message:`Pipeline variable name is invalid: ${n}`};if(null!=s){if("string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s)throw{status:400,message:`Pipeline variable value for "${n}" is invalid`};t[n]=String(s)}}return t}isUsableTriggerToken(e){return"string"==typeof e&&e.length>=20&&!e.includes("*")}async resolvePipelineTriggerToken(e,t){const n=this.parseOptionalString(t.triggerToken,"triggerToken");if(n)return n;if(!0!==t.createTriggerIfMissing)throw{status:400,message:"triggerToken is required unless createTriggerIfMissing is true"};const s=this.parseOptionalString(t.triggerDescription,"triggerDescription")??"Agentrix webhook bridge",a=(await this.requestPaginated(`/projects/${e}/triggers`)).find(e=>e.description===s&&this.isUsableTriggerToken(e.token));if(a?.token)return a.token;const i=new URLSearchParams;i.set("description",s);const o=await this.requestForm(`/projects/${e}/triggers`,i);if(!this.isUsableTriggerToken(o.token))throw{status:502,message:"GitLab did not return a usable pipeline trigger token"};return o.token}async ensurePipelineTriggerToken(e){const t=this.resolveProjectPath(e);return{token:await this.resolvePipelineTriggerToken(t,{...e,createTriggerIfMissing:!0})}}async triggerPipeline(e){const t=this.resolveProjectPath(e),n=this.parseNonEmptyString(e.ref,"ref"),s=this.parsePipelineVariables(e.variables),a=await this.resolvePipelineTriggerToken(t,e),i=new URLSearchParams;i.set("token",a),i.set("ref",n);for(const[e,t]of Object.entries(s))i.set(`variables[${e}]`,t);const o=await this.requestForm(`/projects/${t}/trigger/pipeline`,i);return{id:o.id,iid:o.iid,projectId:o.project_id,ref:o.ref,sha:o.sha,status:o.status,source:o.source,url:o.web_url,createdAt:o.created_at,updatedAt:o.updated_at}}parseProxyMethod(e){const t="string"==typeof e?e.toUpperCase():"GET";if("GET"===t||"POST"===t||"PUT"===t||"PATCH"===t||"DELETE"===t)return t;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 t=new URLSearchParams;for(const[n,s]of Object.entries(e))if(null!=s)if(Array.isArray(s))for(const e of s){if("string"!=typeof e&&"number"!=typeof e&&"boolean"!=typeof e)throw{status:400,message:`Proxy query value for "${n}" is invalid`};t.append(n,String(e))}else{if("string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s)throw{status:400,message:`Proxy query value for "${n}" is invalid`};t.append(n,String(s))}return t.toString()}isProxyAllowed(e,t){return rn.some(n=>n.method===e&&n.pattern.test(t))}async requestGitlabApi(e){const t=this.parseProxyMethod(e.method),n=this.parseProxyPath(e.path),s=this.buildProxyQueryString(e.query),a=s.length>0?`${n}?${s}`:n;if(!this.isProxyAllowed(t,n))throw{status:403,message:`Proxy path not allowed: ${t} ${n}`};return"GET"===t?await this.request(a,t):await this.request(a,t,e.body)}}function ln(e){const t=e.replace(/\/+$/,"");return t.endsWith("/v1")?`${t}/models`:`${t}/v1/models`}function pn(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/+$/,"")}`}catch{return e}}function dn(e){return oe.isAxiosError(e)?{message:e.message,status:e.response?.status,code:e.code}:{message:e instanceof Error?e.message:String(e)}}async function un(e,t){if(!e.apiKey)throw new Error("missing api key");const n="anthropic"===t?{"x-api-key":e.apiKey,"anthropic-version":"2023-06-01"}:{Authorization:`Bearer ${e.apiKey}`},s=await oe.get(ln(e.baseUrl),{headers:n,timeout:1e4});return(s.data?.data||[]).map(e=>e&&"object"==typeof e&&"id"in e?String(e.id):null).filter(e=>Boolean(e))}async function mn(e){const t=function(e){try{const t=new URL(e).hostname.toLowerCase();if("api.anthropic.com"===t||t.endsWith(".anthropic.com"))return"anthropic";if("api.openai.com"===t||t.endsWith(".openai.com"))return"openai"}catch{return null}return null}(e.baseUrl),n=t?[t]:["anthropic","openai"];let s;for(const a of n){ce.info(`[MODELS] Requesting models: source=${e.source}, protocol=${a}, url=${pn(ln(e.baseUrl))}, officialProtocol=${t??"none"}`);try{const t=await un(e,a);return ce.info(`[MODELS] Models request succeeded: source=${e.source}, protocol=${a}, count=${t.length}`),t}catch(t){s=t;const n=dn(t);ce.warn(`[MODELS] Models request failed: source=${e.source}, protocol=${a}, status=${n.status??"-"}, code=${n.code??"-"}, message=${n.message}`)}}throw s instanceof Error?s:new Error("failed to fetch models")}function hn(e,t){const n=t.ANTHROPIC_MODEL||e?.model||process.env.ANTHROPIC_MODEL;if(!n)return;const s=n.toLowerCase();return"opus"===s?t.ANTHROPIC_DEFAULT_OPUS_MODEL||process.env.ANTHROPIC_DEFAULT_OPUS_MODEL||"claude-opus-4-5":"sonnet"===s?t.ANTHROPIC_DEFAULT_SONNET_MODEL||process.env.ANTHROPIC_DEFAULT_SONNET_MODEL||"claude-sonnet-4-5":"haiku"===s?t.ANTHROPIC_DEFAULT_HAIKU_MODEL||process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL||"claude-haiku-4-5":n}async function gn(e){const t=[];if(!e||"claude"===e){const e=function(){const e=function(e){if(!r(e))return null;try{return JSON.parse(c(e,"utf-8"))}catch{return null}}(y(re.claudeConfigDir,"settings.json")),t=e?.env||{},n=t.ANTHROPIC_BASE_URL||process.env.ANTHROPIC_BASE_URL||"https://api.anthropic.com",s=t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.ANTHROPIC_API_KEY;return s?{baseUrl:n,apiKey:s,source:"claude",defaultModel:hn(e,t)}:null}();e&&t.push(e)}if(!e||"codex"===e){const e=function(){const e=y(re.codexHomeDir,"config.toml");if(!r(e))return process.env.OPENAI_API_KEY?{baseUrl:process.env.OPENAI_BASE_URL||"https://api.openai.com",apiKey:process.env.OPENAI_API_KEY,source:"codex",defaultModel:process.env.OPENAI_MODEL}:null;const t=c(e,"utf-8"),n=t.match(/^model_provider\s*=\s*"([^"]+)"/m)?.[1]||"openai",s=t.match(/^model\s*=\s*"([^"]+)"/m)?.[1],a=t.match(new RegExp(`\\[model_providers\\.${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\]([\\s\\S]*?)(?=\\n\\[|$)`)),i=a?.[1]||"",o=i.match(/^\s*base_url\s*=\s*"([^"]+)"/m)?.[1]||process.env.OPENAI_BASE_URL||"https://api.openai.com",l=i.match(/^\s*env_key\s*=\s*"([^"]+)"/m)?.[1]||("agentrix"===n?"AGENTRIX_API_KEY":"OPENAI_API_KEY");return{baseUrl:o,apiKey:process.env[l],source:"codex",defaultModel:s}}();e&&t.push(e)}ce.info(`[MODELS] Listing available models: agentType=${e??"all"}, endpointCount=${t.length}, endpoints=${t.map(e=>`${e.source}:${pn(e.baseUrl)}:hasKey=${Boolean(e.apiKey)}:defaultModel=${e.defaultModel??"-"}`).join(",")||"-"}`);const n=new Set,s=[],a=t.find(e=>e.defaultModel)?.defaultModel;for(const e of t)try{for(const t of await mn(e))n.add(t)}catch(t){const n=dn(t);s.push({source:e.source,baseUrl:pn(e.baseUrl),message:n.message,status:n.status,code:n.code})}const i=Array.from(n).sort();return 0===i.length?ce.warn(`[MODELS] No models available: endpointCount=${t.length}, failures=${JSON.stringify(s)}`):ce.info(`[MODELS] Listed available models: count=${i.length}`),{models:i,defaultModel:a}}function fn(e,t){return{eventId:N(),status:"failed",opCode:e,message:t}}function vn(e){return async(t,n)=>{if(ce.info(`[EVENT HANDLER] create-task: ${t.taskId}, agentType=${t.agentType}, agentId=${t.agentId}`),"shadow"!==t.taskType&&e.onCompanionInteraction?.(t.chatId),"task-message"!==t.event)return ce.error(`[EVENT HANDLER] create-task expects task-message, got ${t.event} for task ${t.taskId}`),void n(fn(t.eventId,`create-task expects task-message, got ${t.event}`));try{const s=await e.workerManager.startWorker(t,"create-task");"success"!==s.status&&ce.error(`[EVENT HANDLER] create-task startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){ce.error(`[EVENT HANDLER] create-task startup threw for task ${t.taskId}:`,e),n(fn(t.eventId,e instanceof Error?e.message:"create-task startup failed"))}}}function xn(e){return async(t,n)=>{ce.debug(`[EVENT HANDLER] resume-task: ${t.taskId}, agentSessionId=${t.agentSessionId}`),"shadow"!==t.taskType&&e.onCompanionInteraction?.(t.chatId);try{const s=await e.workerManager.startWorker(t,"resume-task");"success"!==s.status&&ce.error(`[EVENT HANDLER] resume-task startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){ce.error(`[EVENT HANDLER] resume-task startup threw for task ${t.taskId}:`,e),n(fn(t.eventId,e instanceof Error?e.message:"resume-task startup failed"))}}}function yn(e){return async(t,n)=>{if(ce.info(`[EVENT HANDLER] list-models received: machineId=${t.machineId}, agentType=${t.agentType??"all"}, eventId=${t.eventId}`),t.machineId!==e.machineId)return ce.warn(`[EVENT HANDLER] list-models target mismatch: requested=${t.machineId}, current=${e.machineId}`),void n(fn(t.eventId,"list-models target machine mismatch"));try{const{models:e,defaultModel:s}=await gn(t.agentType);if(0===e.length&&!s)return ce.warn(`[EVENT HANDLER] list-models found no models and no default model: machineId=${t.machineId}, agentType=${t.agentType??"all"}`),void n(fn(t.eventId,"No models available from configured endpoints"));ce.info(`[EVENT HANDLER] list-models success: machineId=${t.machineId}, count=${e.length}, defaultModel=${s??"-"}`),n({eventId:N(),status:"success",opCode:t.eventId,data:{models:e,defaultModel:s}})}catch(e){ce.error(`[EVENT HANDLER] list-models failed: machineId=${t.machineId}, agentType=${t.agentType??"all"}:`,e),n(fn(t.eventId,e instanceof Error?e.message:"Failed to list models"))}}}function bn(e){return async t=>{ce.info("[EVENT HANDLER] shutdown-machine received",t),e.requestShutdown("agentrix-app",t.reason)}}function wn(e){return async(t,n)=>{ce.info(`[EVENT HANDLER] deploy-agent received: taskId=${t.taskId}, draftAgentId=${t.draftAgentId}, targetAgentId=${t.targetAgentId}, sourcePath=${t.sourcePath}`);try{const s=await e.workerManager.startDeploymentWorker(t);"success"!==s.status&&ce.error(`[EVENT HANDLER] deploy-agent startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){ce.error(`[EVENT HANDLER] deploy-agent startup threw for task ${t.taskId}:`,e),n(fn(t.eventId,e instanceof Error?e.message:"deploy-agent startup failed"))}}}function kn(e){return async(t,n)=>{ce.info(`[EVENT HANDLER] hive-publish received: taskId=${t.taskId}, name=${t.name}, repoDir=${t.repoDir}`);try{const s=await e.workerManager.startHivePublishWorker(t);"success"!==s.status&&ce.error(`[EVENT HANDLER] hive-publish startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){ce.error(`[EVENT HANDLER] hive-publish startup threw for task ${t.taskId}:`,e),n(fn(t.eventId,e instanceof Error?e.message:"hive-publish startup failed"))}}}function In(e){return async(t,n)=>{ce.info(`[EVENT HANDLER] hive-install received: taskId=${t.taskId}, name=${t.name}, hiveListingId=${t.hiveListingId}`);try{const s=await e.workerManager.startHiveInstallWorker(t);"success"!==s.status&&ce.error(`[EVENT HANDLER] hive-install startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){ce.error(`[EVENT HANDLER] hive-install startup threw for task ${t.taskId}:`,e),n(fn(t.eventId,e instanceof Error?e.message:"hive-install startup failed"))}}}function Sn(e){return async t=>{ce.info(`[EVENT HANDLER] stop-task: ${t.taskId}, reason=${t.reason||"n/a"}`),e.workerManager.stopSession(t.taskId)||ce.warn(`[EVENT HANDLER] stop-task failed, task not found: ${t.taskId}`)}}function Tn(e){return async t=>{ce.info(`[GITLAB PROXY] request received: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}, ttlMs=${t.ttlMs}, payloadKeys=${function(e){const t=Object.keys(e||{});return t.length>0?t.join(","):"-"}(t.payload)}`);const n=Date.now(),s=n=>{const s={eventId:t.requestId,requestId:t.requestId,machineId:e.machineId,...n};e.client?(e.client.send("daemon-gitlab-response",s),ce.info(`[GITLAB PROXY] response sent: reqId=${t.requestId}, op=${t.operation}, success=${n.success}, executionMs=${n.executionTimeMs}`)):ce.error(`[GITLAB PROXY] response dropped: reqId=${t.requestId}, op=${t.operation}, reason=socket-client-unavailable`)};try{const e=await Vt();if(!e)return ce.warn(`[GITLAB PROXY] git server encryption key unavailable: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),void s({success:!1,errorCode:"PAT_MISSING",errorMessage:"Git server encryption key not available",executionTimeMs:Date.now()-n});const a=an(t.gitServerId,e);if(!a)return ce.warn(`[GITLAB PROXY] PAT missing: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),void s({success:!1,errorCode:"PAT_MISSING",errorMessage:`No PAT configured for git server ${t.gitServerId}`,executionTimeMs:Date.now()-n});const i=t.payload.apiUrl;if(!i)return ce.warn(`[GITLAB PROXY] apiUrl missing in payload: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),void s({success:!1,errorCode:"PAT_MISSING",errorMessage:"GitLab API URL not provided in request",executionTimeMs:Date.now()-n});ce.info(`[GITLAB PROXY] executing: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}, apiHost=${function(e){try{return new URL(e).host}catch{return"invalid-url"}}(i)}`);const o=new cn(i,a,{requestId:t.requestId,gitServerId:t.gitServerId}),r=await o.executeOperation(t.operation,t.payload);ce.info(`[GITLAB PROXY] execution succeeded: reqId=${t.requestId}, op=${t.operation}, summary=${function(e,t){if(Array.isArray(t))return`items=${t.length}`;if(t&&"object"==typeof t){const n=t;return"resolveGitAuthContext"===e?`authMode=${String(n.authMode??"unknown")}, hasPat=${Boolean(n.hasPat)}`:"number"in n||"state"in n?`number=${String(n.number??"-")}, state=${String(n.state??"-")}`:`keys=${Object.keys(n).join(",")||"-"}`}return"type="+typeof t}(t.operation,r)}`),s({success:!0,data:r,executionTimeMs:Date.now()-n})}catch(e){const a=e;let i="GITLAB_CONNECTIVITY_FAILED";401===a.status?i="PAT_INVALID":403===a.status?i="PAT_SCOPE_INSUFFICIENT":404===a.status&&(i="RESOURCE_NOT_FOUND");const o="string"==typeof a.message?a.message:"Unknown error",r="string"==typeof a.detail?function(e,t=300){return e.length<=t?e:`${e.slice(0,t)}...`}(a.detail):void 0,c="number"==typeof a.status?String(a.status):"unknown";ce.error(`[GITLAB PROXY] execution failed: reqId=${t.requestId}, op=${t.operation}, errorCode=${i}, status=${c}, message=${o}${r?`, detail=${r}`:""}`),s({success:!1,errorCode:i,errorMessage:o,executionTimeMs:Date.now()-n})}}}const En=parseInt(process.env.MAX_WORKSPACE_FILE_SIZE_MB||"100",10);function An(e,t){if(!e)return;if("string"==typeof t)return void(e.sendMessage?e.sendMessage(t):e.send&&e.send(t));const n=Buffer.from(t);e.sendMessageBinary?e.sendMessageBinary(n):e.send&&e.send(n)}class Cn{client;machineId;iceServers=[];sessions=new Map;rtcModule;peerConstructor;constructor(e,t){this.client=e,this.machineId=t;const n=De(import.meta.url);var s;this.rtcModule=n("node-datachannel"),this.peerConstructor=(s=this.rtcModule).RTCPeerConnection||s.PeerConnection||s.RTCConnection||s.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))):ce.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:N()})}handleIceServersResponse(e){this.iceServers=function(e){const t=[];return e.forEach(e=>{Array.isArray(e.urls)?t.push(...e.urls):t.push(e.urls)}),t}(e.iceServers),ce.info(`[RTC] Loaded ${this.iceServers.length} ICE servers`)}handleRtcRequest(e){if(!this.peerConstructor)return;const t=e.userId;if(!t)return void ce.warn("[RTC] machine-rtc-request missing userId");const n=e.workspaceUserId||t,s=e.taskId;if(this.sessions.has(e.sessionId))return void this.sendMachineRtcResponse(e.sessionId,t,!0);const a=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers}),i={sessionId:e.sessionId,userId:t,workspaceUserId:n,allowedTaskId:s||void 0,peerConnection:a,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]};this.sessions.set(e.sessionId,i),this.registerPeerHandlers(i),this.sendMachineRtcResponse(e.sessionId,t,!0)}sendMachineRtcResponse(e,t,n,s){this.client.send("machine-rtc-response",{eventId:N(),machineId:this.machineId,sessionId:e,accepted:n,reason:s,userId:t,capabilities:{dataChannel:!0}})}handleRtcSignal(e){if(!this.peerConstructor)return;if("app"!==e.from)return;const t=e.userId;if(!t)return void ce.warn("[RTC] rtc-signal missing userId");const n=e.workspaceUserId||t,s=e.taskId;let a=this.sessions.get(e.sessionId);if(!a){const i=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers});a={sessionId:e.sessionId,userId:t,workspaceUserId:n,allowedTaskId:s||void 0,peerConnection:i,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]},this.sessions.set(e.sessionId,a),this.registerPeerHandlers(a)}try{this.applyRemoteSignal(a,e.signal)}catch(e){ce.warn("[RTC] Failed to apply remote signal",e)}}registerPeerHandlers(e){const{peerConnection:t}=e;t.onStateChange?.(t=>{ce.info(`[RTC] Peer state (${e.sessionId}): ${t}`)}),t.onGatheringStateChange?.(t=>{ce.info(`[RTC] ICE gathering (${e.sessionId}): ${t}`)}),t.onLocalDescription?.((t,n)=>{const s=function(e,t){return e&&"object"==typeof e&&"string"==typeof e.sdp?{sdp:e.sdp,type:e.type||t}:{sdp:String(e||""),type:t}}(t,n);this.client.send("rtc-signal",{eventId:N(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:s,userId:e.userId})}),t.onLocalCandidate?.((t,n,s)=>{const a=function(e,t,n){return"string"==typeof e?{candidate:e,sdpMid:t||"0",sdpMLineIndex:n??0}:e&&"string"==typeof e.candidate?{candidate:e.candidate,sdpMid:e.sdpMid||e.mid||t||"0",sdpMLineIndex:"number"==typeof e.sdpMLineIndex?e.sdpMLineIndex:n??0}:null}(t,n,s);a&&this.client.send("rtc-signal",{eventId:N(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:{candidate:a},userId:e.userId})}),t.onDataChannel?.(t=>{e.dataChannel=t,this.registerDataChannel(e,t)})}registerDataChannel(e,t){t.onOpen?.(()=>{ce.info(`[RTC] Data channel open (${e.sessionId})`),e.lastActivity=Date.now(),An(t,JSON.stringify({v:1,type:"control.ready",channel:"control",requestId:`req-${e.sessionId}`,streamId:0,timestamp:(new Date).toISOString(),payload:{ok:!0}}))}),t.onClosed?.(()=>{ce.warn(`[RTC] Data channel closed (${e.sessionId})`),e.peerConnection.close?.(),this.sessions.delete(e.sessionId)}),t.onError?.(t=>{ce.error(`[RTC] Data channel error (${e.sessionId})`,t)}),t.onMessage?.(t=>{e.lastActivity=Date.now(),this.handleDataChannelMessage(e,t)})}handleDataChannelMessage(e,t){if(Buffer.isBuffer(t)||t instanceof Uint8Array){try{j(new Uint8Array(t))}catch(e){ce.warn("[RTC] Received binary payload without handler")}return}let n=null;if("string"==typeof t?n=t:t&&"string"==typeof t.text&&(n=t.text),!n)return;let s=null;try{s=JSON.parse(n)}catch(e){return void ce.warn("[RTC] Non-JSON message",n)}s&&"string"==typeof s.type&&"file.request"===s.type&&this.handleFileRequest(e,s).catch(e=>{ce.error("[RTC] Failed to handle file request",e)})}async handleFileRequest(e,t){const n=t.payload;if(!n)return;if(n.userId!==e.workspaceUserId)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:"unauthorized",message:"Unauthorized workspace access"}});if(e.allowedTaskId&&n.taskId!==e.allowedTaskId)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:"unauthorized",message:"Unauthorized task access"}});const s=(a=n.userId,o=n.taskId,r=n.relativePath,re.resolveWorkspaceFilePath(a,o,r));var a,o,r;if(!i.existsSync(s))return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:"file_not_found",message:"File or directory not found"}});const c=await i.promises.stat(s);if(!function(e,t){return!t||e.mtime.toISOString()!==t}(c,n.ifModifiedSince))return void this.sendControl(e,{v:1,type:"file.not_modified",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString()});if(c.isDirectory()||"directory"===n.entryType){const n=await i.promises.readdir(s,{withFileTypes:!0}),a={entries:await Promise.all(n.map(async e=>{const t=v.join(s,e.name),n=await i.promises.stat(t);return{name:e.name,type:e.isDirectory()?"directory":"file",size:n.size,modifiedAt:n.mtime.toISOString()}})),modifiedAt:c.mtime.toISOString()};return void this.sendControl(e,{v:1,type:"file.dir",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:a})}const l=1024*(n.maxFileSizeMB??En)*1024;if(c.size>l)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:"file_too_large",message:"File exceeds size limit"}});const p=Wt.lookup(s)||"application/octet-stream",d={size:c.size,mimeType:"string"==typeof p?p:"application/octet-stream",modifiedAt:c.mtime.toISOString()};this.sendControl(e,{v:1,type:"file.meta",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:d}),await this.sendFileChunks(e,t.streamId,s),this.sendControl(e,{v:1,type:"file.end",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:{size:c.size}})}async sendFileChunks(e,t,n){const s=e.dataChannel;if(!s)return;const a=i.createReadStream(n,{highWaterMark:65536});let o=0;await new Promise((e,n)=>{a.on("data",e=>{const n=q.Binary|(0===o?q.Start:0),a=Buffer.isBuffer(e)?e:Buffer.from(e),i=new Uint8Array(a.buffer,a.byteOffset,a.byteLength),r=L({streamId:t,seq:o,flags:n,payloadLength:i.length},i);An(s,r),o+=1}),a.on("end",()=>{if(o>0){const e=L({streamId:t,seq:o,flags:q.End|q.Binary,payloadLength:0},new Uint8Array);An(s,e)}e()}),a.on("error",e=>n(e))})}sendControl(e,t){const n=e.dataChannel;n&&An(n,JSON.stringify(t))}applyRemoteSignal(e,t){const{peerConnection:n}=e;if(t&&t.sdp&&t.type)return n.setRemoteDescription?.(t.sdp,t.type),e.remoteDescriptionSet=!0,e.pendingCandidates?.forEach(e=>{try{n.addRemoteCandidate?.(e.candidate,e.mid)}catch(e){ce.warn("[RTC] Failed to add queued candidate",e)}}),void(e.pendingCandidates=[]);if(t&&t.candidate){const s=t.candidate,a="string"==typeof s?s:s&&"string"==typeof s.candidate?s.candidate:null,i=t.sdpMid||s?.sdpMid||s?.mid||"0";if(a){if(!e.remoteDescriptionSet)return void e.pendingCandidates?.push({candidate:a,mid:i});n.addRemoteCandidate?.(a,i)}}}}class $n{client;context;rtcManager;constructor(e,t,n){const{machineId:s,...a}=e;this.client=new Nt(a),this.context={machineId:s,workerManager:t,requestShutdown:n.requestShutdown,client:this.client},this.rtcManager=new Cn(this.client,s),this.initHandlers(),this.rtcManager.registerHandlers()}connect(){return new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("Machine connection timeout after 30 seconds"))},3e4);this.client.onLifecycle("connect",()=>{clearTimeout(n),e()}),this.client.onLifecycle("connect_error",e=>{clearTimeout(n),t(e)}),this.client.connect()})}async disconnect(){this.client.connected&&await this.client.flush(5e3).catch(()=>{}),this.rtcManager.shutdown(),this.client.disconnect()}setCompanionInteractionCallback(e){this.context.onCompanionInteraction=e}initHandlers(){const e={"create-task":vn(t=this.context),"resume-task":xn(t),"list-models":yn(t),"stop-task":Sn(t),"deploy-agent":wn(t),"hive-publish":kn(t),"hive-install":In(t),"shutdown-machine":bn(t),"workspace-file-request":zt({client:t.client}),"daemon-gitlab-request":Tn(t)};var t;this.client.onEventWithAck("create-task",e["create-task"]),this.client.onEventWithAck("resume-task",e["resume-task"]),this.client.onEventWithAck("list-models",e["list-models"]),this.client.onEvent("stop-task",e["stop-task"]),this.client.onEventWithAck("deploy-agent",e["deploy-agent"]),this.client.onEventWithAck("hive-publish",e["hive-publish"]),this.client.onEventWithAck("hive-install",e["hive-install"]),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 _n=null;let Pn=!1;async function Mn(){if(Pn)ce.info("[caffeinate] Already stopping, skipping");else if(_n&&!_n.killed){Pn=!0,ce.info(`[caffeinate] Stopping caffeinate process PID ${_n.pid}`);try{_n.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),_n&&!_n.killed&&_n.kill("SIGKILL"),_n=null,Pn=!1}catch(e){ce.info("[caffeinate] Error stopping caffeinate:",e),Pn=!1}}}let Rn=!1;function On(e){const{pid:t,name:n,cmd:s}=e;if(t===process.pid||t===process.ppid)return null;if(!(n.includes("agentrix")||"node"===n&&(s.includes("agentrix-cli")||s.includes("dist/index.mjs")||s.includes("dist\\index.mjs"))||("MainThread"===n||n.includes("MainThread"))&&(s.includes("agentrix-cli")||s.includes("dist/index.mjs")||s.includes("agentrix.mjs"))||s.includes("agentrix.mjs")||s.includes("agentrix-cli")||s.includes("tsx")&&s.includes("src/index.ts")&&s.includes("agentrix-cli")))return null;let a="unknown";const i=s.toLowerCase();return i.includes(" worker")?a="worker":i.includes(" upgrade-daemon")?a="upgrade-daemon":i.includes(" daemon")?a="daemon":i.includes("doctor")&&(a="doctor"),{pid:t,command:s||n,type:a}}async function Dn(){try{let e;e="win32"===process.platform?await async function(){try{const e=Ue("wmic process where \"name='node.exe'\" get ProcessId,CommandLine /format:csv",{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}),t=[],n=e.split("\n").map(e=>e.trim()).filter(Boolean);for(let e=1;e<n.length;e++){const s=n[e];if(!s)continue;const a=s.indexOf(",");if(-1===a)continue;const i=s.substring(a+1),o=i.lastIndexOf(",");if(-1===o)continue;const r=i.substring(0,o).trim(),c=i.substring(o+1).trim(),l=parseInt(c,10);isNaN(l)||t.push({pid:l,name:"node",cmd:r})}return t}catch(e){return[]}}():(await je()).map(e=>({pid:e.pid,name:e.name||"",cmd:e.cmd||""}));const t=[];for(const n of e){const e=On(n);e&&t.push(e)}return t}catch(e){return[]}}function Nn(e){try{const t="win32"===process.platform?"where":"which";return{available:!0,path:Ue(`${t} ${e}`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}}catch{return{available:!1}}}function Un(){const e=Le(),t=function(){const e=Nn("git"),t=Nn("claude"),n=Nn("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:t.available,required:!0,description:"Claude Code CLI (required for most features)",installCommand:"npm install -g @anthropic-ai/claude-code",path:t.path},{name:"codex",installed:n.available,required:!1,description:"Codex CLI (optional, for Codex tasks)",installCommand:"npm install -g @codex-ai/codex-cli",path:n.path}]}(),n=function(e){if("macos"===e){const e=Nn("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=Nn("bwrap"),t=Nn("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:t.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:t.path}]}return[]}(e),s=t.filter(e=>e.required&&!e.installed),a=n.filter(e=>e.required&&!e.installed);return{cli:t,sandbox:n,allSatisfied:0===s.length&&0===a.length,missingSandbox:a,missingCli:s}}function jn(){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:re.agentrixHomeDir,serverUrl:re.serverUrl,logsDir:re.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 qn(e){if(e||(e="all"),console.log($.bold.cyan("\n🩺 Agentrix CLI Doctor\n")),"all"===e){console.log($.bold("📋 Basic Information")),console.log(`Agentrix CLI Version: ${$.green(pe.version)}`),console.log(`Platform: ${$.green(process.platform)} ${process.arch}`),console.log(`Node.js Version: ${$.green(process.version)}`),console.log(""),console.log($.bold("🔧 Daemon Spawn Diagnostics"));const e=le(),t=y(e,"bin","agentrix.mjs"),n=y(e,"dist","index.mjs");console.log(`Project Root: ${$.blue(e)}`),console.log(`Wrapper Script: ${$.blue(t)}`),console.log(`CLI Entrypoint: ${$.blue(n)}`),console.log(`Wrapper Exists: ${r(t)?$.green("✓ Yes"):$.red("❌ No")}`),console.log(`CLI Exists: ${r(n)?$.green("✓ Yes"):$.red("❌ No")}`),console.log(""),console.log($.bold("⚙️ Configuration")),console.log(`Agentrix Home: ${$.blue(re.agentrixHomeDir)}`),console.log(`Server URL: ${$.blue(re.serverUrl)}`),console.log(`Logs Dir: ${$.blue(re.getStatePaths().logsDir)}`),console.log($.bold("\n🌍 Environment Variables"));const s=jn();console.log(`AGENTRIX_HOME_DIR: ${s.AGENTRIX_HOME_DIR?$.green(s.AGENTRIX_HOME_DIR):$.gray("not set")}`),console.log(`AGENTRIX_SERVER_URL: ${s.AGENTRIX_SERVER_URL?$.green(s.AGENTRIX_SERVER_URL):$.gray("not set")}`),console.log(`DANGEROUSLY_LOG_TO_SERVER: ${s.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING?$.yellow("ENABLED"):$.gray("not set")}`),console.log(`DEBUG: ${s.DEBUG?$.green(s.DEBUG):$.gray("not set")}`),console.log(`NODE_ENV: ${s.NODE_ENV?$.green(s.NODE_ENV):$.gray("not set")}`),console.log($.bold("\n🔐 Authentication"));try{await re.readCredentials()?console.log($.green("✓ Authenticated (credentials found)")):console.log($.yellow("⚠️ Not authenticated (no credentials)"))}catch(e){console.log($.red("❌ Error reading credentials"))}!function(e=!1){const t=Un(),n=Le();console.log($.bold("\n🔧 CLI Dependencies"));for(const n of t.cli)if(n.installed)console.log($.green(`✓ ${n.name}`),$.gray(`- ${n.description}`)),e&&n.path&&console.log($.gray(` Location: ${n.path}`));else{const e=n.required?$.red("❌"):$.yellow("⚠️");console.log(`${e} ${n.name}`,$.gray(`- ${n.description}`)),n.installCommand&&console.log($.blue(` Install: ${n.installCommand}`))}if(t.sandbox.length>0){console.log($.bold("\n🔒 Sandbox Dependencies")),console.log($.gray(`Platform: ${n}`));for(const n of t.sandbox)n.installed?(console.log($.green(`✓ ${n.name}`),$.gray(`- ${n.description}`)),e&&n.path&&console.log($.gray(` Location: ${n.path}`))):(console.log($.red(`❌ ${n.name}`),$.gray(`- ${n.description}`)),n.installCommand&&console.log($.blue(` Install: ${n.installCommand}`)))}else console.log($.bold("\n🔒 Sandbox Dependencies")),console.log($.yellow(`⚠️ Platform ${n} not supported - sandbox will be disabled`));if(t.allSatisfied)return console.log($.bold.green("\n✓ All required dependencies are installed")),!0;{console.log($.bold.red("\n⚠️ Missing Required Dependencies"));const e=[...t.missingCli,...t.missingSandbox];for(const t of e)console.log($.red(` • ${t.name}`));console.log($.yellow("\nPlease install missing dependencies before starting the daemon."))}}(!0)}console.log($.bold("\n🤖 Daemon Status"));try{const t=await Et(),n=await re.readDaemonState();if(t&&n?(console.log($.green("✓ Daemon is running")),console.log(` PID: ${n.pid}`),console.log(` Started: ${new Date(n.startTime).toLocaleString()}`),console.log(` CLI Version: ${n.cliVersion}`),n.port&&console.log(` HTTP Port: ${n.port}`)):n&&!t?console.log($.yellow("⚠️ Daemon state exists but process not running (stale)")):console.log($.red("❌ Daemon is not running")),n){console.log($.bold("\n📄 Daemon State:"));const e=re.getStatePaths();console.log($.blue(`Location: ${e.daemonStateFile}`)),console.log($.gray(JSON.stringify(n,null,2)))}const s=await Dn();if(s.length>0){console.log($.bold("\n🔍 All Agentrix CLI Processes"));const e=s.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});Object.entries(e).forEach(([e,t])=>{console.log($.blue(`\n${{daemon:"🤖 Daemon","upgrade-daemon":"🔄 Upgrade Daemon",worker:"🔗 Workers",doctor:"🩺 Doctor",unknown:"❓ Unknown"}[e]||e}:`)),t.forEach(({pid:t,command:n})=>{const s=e.startsWith("dev")?$.cyan:e.includes("daemon")?$.blue:$.gray;console.log(` ${s(`PID ${t}`)}: ${$.gray(n)}`)})})}else console.log($.red("❌ No agentrix processes found"));"all"===e&&s.length>1&&(console.log($.bold("\n💡 Process Management")),console.log($.gray("To clean up runaway processes: agentrix killall")))}catch(e){console.log($.red("❌ Error checking daemon status"))}}let Ln=null;async function Hn(){const e=zn(),t=function(e){try{return JSON.stringify(e)}catch{return""}}(e);if(Ln&&Ln.expiresAt>Date.now()&&Ln.overridesSignature===t)return Ln.openers;const n=Wn(e),s=[];for(const e of n){const t=e.isSupported();t&&s.push({id:e.id,label:e.label,kind:e.kind,method:e.method,urlTemplate:e.urlTemplate,supported:t})}return Ln={expiresAt:Date.now()+6048e5,openers:s,overridesSignature:t},s}function Gn(e){const t=process.platform;if("darwin"===t)return function(e){const t=Fn(e),n=[];if(t){const e=Qn(t);n.push("-e",`set defaultLocation to POSIX file "${e}"`,"-e","set chosenFolder to choose folder default location defaultLocation")}else n.push("-e","set chosenFolder to choose folder");return n.push("-e","POSIX path of chosenFolder"),Bn(Jn("osascript",n,{captureOutput:!0}))}(e);if("win32"===t)return function(e){const t=Xn("powershell")?"powershell":Xn("pwsh")?"pwsh":null;if(!t)throw new Error("PowerShell is required to pick a directory");const n=Fn(e),s=["Add-Type -AssemblyName System.Windows.Forms;","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;",n?`$dialog.SelectedPath = '${Yn(n)}';`:"","$null = $dialog.ShowDialog();","$dialog.SelectedPath;"].filter(Boolean).join(" ");return Bn(Jn(t,"powershell"===t?["-NoProfile","-STA","-Command",s]:["-NoProfile","-Sta","-Command",s],{captureOutput:!0}))}(e);if("linux"===t)return function(e){const t=Fn(e);if(Xn("zenity")){const e=["--file-selection","--directory","--title=Select Folder"];if(t){const n=t.endsWith("/")?t:`${t}/`;e.push(`--filename=${n}`)}return Bn(Jn("zenity",e,{captureOutput:!0}))}if(Xn("kdialog")){const e=["--getexistingdirectory"];return t&&e.push(t),Bn(Jn("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 Wn(e){const t=process.platform,n=["Visual Studio Code","Visual Studio Code - Insiders"],s=["Cursor"],a=["IntelliJ IDEA","IntelliJ IDEA CE","IntelliJ IDEA Ultimate"],i=["WebStorm"],o=["PyCharm","PyCharm CE","PyCharm Professional"],c=[{id:"vscode",label:"VS Code",kind:"editor",method:"scheme",urlTemplate:"vscode://file/{path}?windowId=_blank",scheme:"vscode",macAppNames:n,isSupported:()=>Kn("vscode",t,n)},{id:"cursor",label:"Cursor",kind:"editor",method:"scheme",urlTemplate:"cursor://file/{path}?windowId=_blank",scheme:"cursor",macAppNames:s,isSupported:()=>Kn("cursor",t,s)},{id:"idea",label:"IntelliJ IDEA",kind:"ide",method:"scheme",urlTemplate:"idea://open?file={path}&newWindow=true",scheme:"idea",macAppNames:a,isSupported:()=>Kn("idea",t,a)},{id:"pycharm",label:"PyCharm",kind:"ide",method:"scheme",urlTemplate:"pycharm://open?file={path}&newWindow=true",scheme:"pycharm",macAppNames:o,isSupported:()=>Kn("pycharm",t,o)},{id:"webstorm",label:"WebStorm",kind:"ide",method:"scheme",urlTemplate:"webstorm://open?file={path}&newWindow=true",scheme:"webstorm",macAppNames:i,isSupported:()=>Kn("webstorm",t,i)},{id:"file-manager",label:"darwin"===t?"Finder":"win32"===t?"Explorer":"Files",kind:"file-manager",method:"cli",isSupported:()=>function(e){return"darwin"===e?Xn("open"):"win32"===e||"linux"===e&&(Xn("xdg-open")||Xn("gio"))}(t),open:e=>function(e,t){if("darwin"!==t){if("win32"!==t){if("linux"===t)return Xn("xdg-open")?void Jn("xdg-open",[e]):void Jn("gio",["open",e]);throw new Error("File manager open is not supported on this platform")}Jn("explorer",[e])}else Jn("open",[e])}(e,t)},{id:"open-with",label:"Open With...",kind:"system",method:"cli",isSupported:()=>function(e){return"darwin"===e?Xn("osascript"):"win32"===e?Xn("powershell")||Xn("pwsh"):"linux"===e&&Xn("gio")}(t),open:e=>function(e,t){if("darwin"!==t)if("win32"!==t){if("linux"!==t)throw new Error("Open With is not supported on this platform");Jn("gio",["open","--ask",e])}else Jn(Xn("powershell")?"powershell":"pwsh",["-NoProfile","-Command",`Start-Process -Verb OpenAs -FilePath '${Yn(e)}'`]);else if(null===Jn("osascript",["-e",`set targetPath to POSIX file "${Qn(e)}"`,"-e","set appChoice to choose application","-e","tell appChoice to open targetPath"],{captureOutput:!0}))throw new Error("No application selected")}(e,t)}];return function(e,t,n){const s=n??zn();return e.map(e=>{const n=s[e.id];if(!n)return e;if(!1===n.enabled)return{...e,isSupported:()=>!1};const a={...e,label:n.label??e.label,method:n.method??e.method,urlTemplate:n.urlTemplate??e.urlTemplate};if(n.command){const s=function(e){return e?Array.isArray(e)?e:[e]:[]}(n.appName??e.macAppNames);a.method="cli",a.isSupported=()=>function(e,t,n){return"darwin"===n&&t.length>0?t.some(e=>Vn(e)):x.isAbsolute(e)||e.includes(x.sep)?r(e):Xn(e)}(n.command,s,t),a.open=e=>function(e,t,n){if(!Jn(e,(t&&t.length>0?t:["{path}"]).map(e=>e.split("{path}").join(n))))throw new Error(`Command failed: ${e}`)}(n.command,n.args,e)}return a})}(c,t,e)}function Fn(e){if(!e)return;const t=e.replace(/^~(?=$|[\\/])/,n.homedir());if(r(t)){try{if(!l(t).isDirectory())return}catch{return}return t}}function Bn(e){if(!e)return null;return e.trim()||null}function zn(){try{const e=re.readSettings();if(!e||"object"!=typeof e)return{};const t=e.openersOverrides;return t&&"object"==typeof t?t:{}}catch(e){return ce.warn("[OPENERS] Failed to read opener overrides",e),{}}}function Kn(e,t,s){return"darwin"===t?function(e,t){if(Xn("mdfind")){const t=Jn("mdfind",[`kMDItemCFBundleURLSchemes == '${e}'`],{captureOutput:!0});if(t&&t.trim())return!0}if(Xn("plutil")){const t=[x.join(n.homedir(),"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"),"/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"];for(const n of t){if(!r(n))continue;const t=Jn("plutil",["-extract","LSHandlers","json","-o","-",n],{captureOutput:!0});if(t)try{const n=JSON.parse(t);if(Array.isArray(n)&&n.some(t=>t.LSHandlerURLScheme?.toLowerCase()===e.toLowerCase()))return!0}catch(e){ce.debug("[OPENERS] Failed to parse LaunchServices handlers",e)}}}return!!(t&&t.length>0)&&t.some(e=>Vn(e))}(e,s):"win32"===t?function(e){return Xn("reg")&&(Boolean(Jn("reg",["query",`HKCU\\Software\\Classes\\${e}`]))||Boolean(Jn("reg",["query",`HKCR\\${e}`])))}(e):"linux"===t&&function(e){if(Xn("xdg-settings")){const t=Jn("xdg-settings",["get","default-url-scheme-handler",e],{captureOutput:!0});if(t&&t.trim()&&"null"!==t.trim())return!0}if(Xn("gio")){const t=Jn("gio",["mime",`x-scheme-handler/${e}`],{captureOutput:!0});if(t&&/Default application/.test(t))return!0}return!1}(e)}function Vn(e){return"darwin"===process.platform&&Boolean(Jn("open",["-Ra",e]))}function Xn(e){return"win32"===process.platform?Boolean(Jn("where",[e])):Boolean(Jn("sh",["-c",`command -v ${e}`]))}function Jn(e,t,n){const s=ze(e,t,{encoding:n?.captureOutput?"utf8":void 0,stdio:n?.captureOutput?"pipe":"ignore",windowsHide:!0});if(0!==s.status){if(n?.captureOutput){const n="string"==typeof s.stderr?s.stderr.trim():"";n&&ce.warn(`[OPENERS] Command failed: ${e} ${t.join(" ")}: ${n}`)}return null}return n?.captureOutput?s.stdout:"ok"}function Yn(e){return e.replace(/'/g,"''")}function Qn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Zn(e,t){if(t){const n=e.startsWith(t)?e.slice(t.length).replace(/^\//,""):w(e);return y(t,"versions",n)}let n=b(e),s=0;for(;s<10;){if(r(y(n,"agent.json"))){const t=e.slice(n.length).replace(/^\//,"");return y(n,"versions",t)}const t=b(n);if(t===n)break;n=t,s++}const a=b(e),i=w(e);return y(a,`.${i}.version`)}function es(e,t){const n=Zn(e,t);if(!r(n))return"0.0.0";try{return c(n,"utf-8").trim()}catch(e){return"0.0.0"}}function ts(e,t,n){try{const s=Zn(e,n),a=b(s);if(!r(a)){const{mkdirSync:e}=o;e(a,{recursive:!0})}p(s,t,"utf-8")}catch(e){}}function ns(e,t){const n=e.split(".").map(Number),s=t.split(".").map(Number);for(let e=0;e<3;e++){const t=n[e]||0,a=s[e]||0;if(t>a)return 1;if(t<a)return-1}return 0}function ss(e,t,n){const s=es(e,n),a=ns(t.metadata.version,s);if(!r(e)){const s=b(e);if(!r(s)){const{mkdirSync:e}=o;e(s,{recursive:!0})}return p(e,t.content,"utf-8"),ts(e,t.metadata.version,n),{updated:!0,reason:"created"}}if(a<=0)return{updated:!1,reason:"up-to-date"};switch(t.metadata.updateStrategy){case"overwrite":return p(e,t.content,"utf-8"),ts(e,t.metadata.version,n),{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"}}}async function as(e){const{agentId:t,gitUrl:n,branch:s,subDir:a}=e,i=y(re.agentrixAgentsHomeDir,t);if(r(i))return{agentDir:i};const o=`${i}.tmp-${Date.now()}`;try{const e=["git","clone","--depth=1"];if(s&&e.push("--branch",s),e.push(n,o),Ke(e.join(" "),{stdio:"pipe"}),a){const e=y(o,a);if(!r(e))throw new Error(`Sub-directory "${a}" not found in cloned repository`);d(e,i),u(o,{recursive:!0,force:!0})}else d(o,i);return is(i),{agentDir:i}}catch(e){throw r(o)&&u(o,{recursive:!0,force:!0}),r(i)&&u(i,{recursive:!0,force:!0}),e}}function is(e){const t=[],n=y(e,"claude","plugins");if(r(n))for(const e of m(n)){const s=y(n,e);l(s).isDirectory()&&r(y(s,"package.json"))&&t.push(s)}const s=y(e,"claude","hooks");r(s)&&r(y(s,"package.json"))&&t.push(s);for(const e of t)Ke("yarn install --frozen-lockfile",{cwd:e,stdio:"pipe"}),Ke("yarn build",{cwd:e,stdio:"pipe"})}function os(e){const t=e.split("\n");for(;t.length>0&&""===t[0].trim();)t.shift();for(;t.length>0&&""===t[t.length-1].trim();)t.pop();const n=t.reduce((e,t)=>{if(""===t.trim())return e;const n=t.match(/^\s*/)[0].length;return Math.min(e,n)},1/0);return t.map(e=>e.slice(n)).join("\n")}const rs=os("\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"),cs=os('\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'),ls=os('\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'),ps=os('\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'),ds=os("\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"),us=os(`\n ${ps}\n\n ${cs}\n\n ${ls}\n`),ms=os('\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 hs(e){const t=["# Available Agents",""];for(const n of e)n.description?t.push(`- **${n.name}** (${n.id}): ${n.description}`):t.push(`- **${n.name}** (${n.id})`);return t.join("\n")}function gs(e,t){const n=t.find(t=>t.id===e);if(!n)return hs(t);const s=t.filter(t=>t.id!==e),a=["# Group Context","",`You are \`${n.name}\`. `,"You are a member of this group chat."];if(n.description&&a.push(`Your role: ${n.description}`),s.length>0){a.push(""),a.push("## Other Agents in This Group"),a.push("");for(const e of s)e.description?a.push(`- **${e.name}**: ${e.description}`):a.push(`- **${e.name}**`)}return a.push(""),a.push(ms),a.join("\n")}function fs(e){const t={};for(const[n,s]of Object.entries(e))"string"==typeof s&&(t[n]=s);return t}function vs(e){if("object"!=typeof e||null===e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text}function xs(e){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:""}}function ys(e){const t=e.message?.content;return"string"==typeof t?t:Array.isArray(t)?t.filter(vs).map(e=>e.text).join("\n").trim():""}function bs(e){const t=e.usage.input_tokens-e.usage.cached_input_tokens,n={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:n,modelUsage:{[e.model]:{inputTokens:t>0?t: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,structured_output:e.structuredOutput}}function ws(e,t){if(!t)return;const n=e?.trim();if(!n)throw new Error("Structured output was requested but the agent returned an empty response");try{return JSON.parse(n)}catch(e){const t=n.length>200?`${n.slice(0,200)}...`:n;throw new Error(`Structured output was requested but the agent returned invalid JSON: ${e instanceof Error?e.message:"unknown error"}; response=${JSON.stringify(t)}`)}}const ks="agentrix",Is="1.0.0";async function*Ss(e){yield e}let Ts;const Es=["Bash","Glob","Grep","ExitPlanMode","Read","Skill","SlashCommand","EnterPlanMode"],As=["Glob","Grep","Read","Skill"],Cs=["Read","Glob","Grep"],$s=["Read","Glob","Grep","TodoWrite"];function _s(e,t,n,s,a,i,o){const c=function(e){const{agentId:t,modeConfig:n,cwd:s,agentConfig:a}=e,{mode:i,groupAgents:o}=n,r=a.customSystemPrompt,c=a.systemPromptMode??"append",l=function(e){const{mode:t,supportChangeTitle:n}=e;switch(t){case"work":return n?rs:void 0;case"companion_shadow":case"companion_chat":case"reply":case"group_chat":return;case"chat":return ds;case"group_work":{const e=[];return n&&e.push(rs),e.join("\n\n")}}}(n);if("group_chat"===i||"group_work"===i){const e=[us];return o&&o.length>0&&e.push(hs(o)),l&&e.push(l),e.join("\n\n")}const p="reply"===i&&o&&o.length>0?gs(t,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,h=r?_e(r,s,m):void 0;if("replace"===c&&h){const e=[h];return p&&e.push(p),l&&e.push(l),e.join("\n\n")}const g=[];return p&&g.push(p),l&&g.push(l),h&&g.push(h),{type:"preset",preset:"claude_code",append:g.length>0?g.join("\n\n"):void 0}}({agentId:e,modeConfig:t.modeConfig,cwd:t.cwd,agentConfig:n}),l=function(e){switch(e){case"work":case"companion_shadow":return;case"chat":case"companion_chat":return[...Es];case"reply":return[...As];case"group_chat":return[...Cs];case"group_work":return[...$s]}}(t.modeConfig.mode),p=function(e,t){const n={},s=e=>async(t,n,s)=>await e(t,n,s)??{},a=new Set([...Object.keys(e),...t?Object.keys(t):[]]);for(const i of a){const a=[],o=e[i];o&&a.push(s(o));const r=t?.[i];r&&a.push(s(r)),n[i]=[{hooks:a}]}return n}(t.hooks??{},s),d=function(){if(void 0!==Ts)return Ts??void 0;const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(e){const t=function(e){const t=e.trim();if(t){if(t.includes("/")||t.includes("\\")||t.startsWith(".")){const e=k(t)?t:I(t);return r(e)?e:void 0}return function(e){const t="win32"===process.platform?"where":"which",n=ze(t,[e],{encoding:"utf-8"});if(0===n.status)return n.stdout.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0)}(t)}}(e);if(t)return Ts=t,t}Ts=null}(),u=i?function(e){const{modeConfig:t,tools:n,allowAskUser:s=!0,visionModel:a,serverName:i=ks,serverVersion:o=Is}=e,{mode:r,supportChangeTitle:c}=t,l=[];switch(r){case"work":c&&l.push(n.changeTaskTitle),s&&l.push(n.askUser),l.push(n.getTaskHistory);break;case"chat":l.push(n.createTask),l.push(n.replyToSubTask),s&&l.push(n.askUser),l.push(n.getTaskHistory),l.push(n.listSubTask);break;case"group_chat":l.push(n.invoke),l.push(n.createSoloTask),l.push(n.createGroupTask),l.push(n.replyToSubTask),l.push(n.getTaskAgents),l.push(n.getTaskHistory);break;case"group_work":l.push(n.invoke),l.push(n.assign),c&&l.push(n.changeTaskTitle),l.push(n.getTaskAgents),l.push(n.getTaskHistory);break;case"reply":l.push(n.getTaskHistory),s&&l.push(n.askUser);break;case"companion_chat":l.push(n.createTask),l.push(n.replyToSubTask),s&&l.push(n.askUser),l.push(n.getTaskHistory),l.push(n.uploadFile),l.push(n.listAgents),l.push(n.scheduleTask);break;case"companion_shadow":l.push(n.getTaskHistory),l.push(n.readConversation),l.push(n.listAgents),l.push(n.scheduleTask)}("companion_chat"===r||"companion_shadow"===r)&&(l.push(n.listTasks),l.push(n.updateAgentInfo),l.push(n.sendReminder)),a&&"companion_shadow"!==r&&"reply"!==r&&l.push(n.analyzeImage);const p=Xe({name:i,version:o,tools:l}),d=l.map(e=>((e,t)=>`mcp__${e}__${t}`)(i,e.name));return{server:p,toolNames:d}}({modeConfig:t.modeConfig,tools:i,allowAskUser:t.allowAskUser,visionModel:t.visionModel}):void 0,m={...u?.server?{agentrix:u.server}:{},...t.mcpServers??{},...a??{}};return{stderr:t.stderr,model:t.model||n.customModel,fallbackModel:n.customFallbackModel,cwd:t.cwd,resume:t.agentSessionId,permissionMode:t.initialPermissionMode??n.customPermissionMode??"bypassPermissions",settingSources:["user","project","local"],systemPrompt:c,tools:l,mcpServers:m,plugins:n.customPlugins,abortController:t.abortController,env:t.env?fs(t.env):void 0,pathToClaudeCodeExecutable:d,maxTurns:n.customMaxTurns??t.maxTurns??o,extraArgs:n.customExtraArgs,canUseTool:t.canUseTool,hooks:p,outputFormat:t.structuredOutputSchema}}class Ps{constructor(e,t,n,s){this.agentId=e,this.agentConfig=t,this.agentHooks=n,this.agentMcpServers=s}getAgentConfiguration(){return this.agentConfig}getHooks(){return this.agentHooks}getMcpServers(){return this.agentMcpServers}async executeHook(e,t,n){await async function(e,t,n,s){if(!e)return;const a=e[t];if(!a)return;const i=s||(e=>console.log(e));try{i(`[${t}] Executing hook...`);const e=new AbortController,s=setTimeout(()=>{e.abort()},6e4);try{await a(n,"",{signal:e.signal}),i(`[${t}] Hook executed successfully`)}finally{clearTimeout(s)}}catch(e){console.warn(`[${t}] Hook failed (non-fatal):`,e)}}(this.agentHooks,e,t,n)}async run(e,t){const n=this.agentConfig,s="string"==typeof e?xs(e):e;let a=null;const i=Je({prompt:Ss(s),options:_s(this.agentId,t,n,this.agentHooks,this.agentMcpServers,t.agentrixTools)});for await(const e of i)if(console.log("ClaudeRunner.run: received message",JSON.stringify(e)),"result"===e.type){a=e;break}if(!a)throw new Error("ClaudeRunner.run: missing result message");return a}async*runStreamed(e,t){const n=this.agentConfig,s="string"==typeof e?xs(e):e,a=Je({prompt:Ss(s),options:_s(this.agentId,t,n,this.agentHooks,this.agentMcpServers,t.agentrixTools)});for await(const e of a)if(yield e,"result"===e.type)break}loop(e){const t=e.abortController,n=this.agentConfig,s=_s(this.agentId,e,n,this.agentHooks,this.agentMcpServers,e.agentrixTools);let a=!1;const i=[];let o=null,r=null;const c=()=>{if(!a&&(a=!0,o)){const e=o;o=null,e(null)}},l=async function*(){for(;!a&&!t.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=Je({prompt:l(),options:s});r=e;for await(const t of e)yield t}finally{r=null,c()}}();return t.signal.addEventListener("abort",c,{once:!0}),{push:e=>{if(console.log("ClaudeRunner.loop.push:",JSON.stringify(e,null,2)),a)return;const t="string"==typeof e?xs(e):e;if(o){const e=o;return o=null,void e(t)}i.push(t)},events:p,stop:c,setPermissionMode:async e=>{r&&await r.setPermissionMode(e)}}}}function Ms(e,t,n){e&&e(t,"AGENT",n)}function Rs(){return`Companion probe timed out after ${Math.round(45)}s`}function Os(e){return e instanceof Error&&e.message?e.message:String(e)}function Ds(e){return"string"==typeof e.result&&e.result.trim()?e.result:Array.isArray(e.permission_denials)&&e.permission_denials.length>0?String(e.permission_denials[0]):"error_max_turns"===e.subtype?"Companion probe exceeded max turns":"Companion probe failed"}async function Ns(){const e=y(re.agentrixHomeDir,"tmp","companion-probe");h(e,{recursive:!0});const t=new Ps("default",{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}),n=new AbortController;let s=!1;const a=setTimeout(()=>{s=!0,n.abort()},45e3);try{const a=await t.run("hi",{cwd:e,abortController:n,modeConfig:{mode:"chat",supportChangeTitle:!1}});return a.is_error?{success:!1,error:s?Rs():Ds(a)}:{success:!0}}catch(e){return{success:!1,error:s?Rs():Os(e)}}finally{clearTimeout(a)}}function Us(e){return e.split("\\").join("/")}function js(e,t){const n=y(t,"template","versions",`${e}.json`);if(!r(n))return{};try{const e=c(n,"utf-8");return JSON.parse(e)}catch(e){return console.warn(`[Companion] Failed to parse ${n}:`,e),{}}}async function qs(e){const t=re.agentrixAgentsHomeDir,n=y(t,"companion"),s=y(n,"claude");if(!r(y(n,"agent.json"))){const t=await Ns();if(!t.success)throw new Error(`Companion probe failed: ${t.error||"Unknown error"}`);const s=e?.credentials?.token;if(s)try{const e=await async function(e){const t=`${re.serverUrl}/v1/agents/${encodeURIComponent("companion")}/git-url`;try{const n=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});return n.ok?n.json():null}catch(e){return null}}(s);e&&(await as({agentId:"companion",gitUrl:e.gitUrl,branch:e.branch,subDir:e.subDir??"companion"}),console.log("[Companion] Installed from git"))}catch(e){console.warn("[Companion] Git install failed, will retry next boot:",e instanceof Error?e.message:e)}r(y(n,"agent.json"))||(console.log("[Companion] Falling back to public repo..."),await as({agentId:"companion",gitUrl:"https://github.com/xmz-ai/agentrix-agent",branch:"main",subDir:"companion"}))}var a;a=y(s,"memory"),r(a)||h(a,{recursive:!0});const{language:i,templates:o}=function(e,t){const n=function(e){const t=[e,process.env.AGENTRIX_COMPANION_TEMPLATE_LANGUAGE,process.env.LC_ALL,process.env.LC_MESSAGES,process.env.LANG];for(const e of t){if(!e)continue;const t=e.trim().toLowerCase();if(t){if(t.startsWith("zh"))return"zh-Hans";if(t.startsWith("en"))return"en"}}return"en"}(e),s=js("common",t),a=js(n,t),i=[],o={version:"1.0.0",updateStrategy:"create-only"};for(const[e,n]of Object.entries(s)){const s=y(t,e);r(s)&&i.push({relativePath:e,content:c(s,"utf-8"),metadata:n})}const p=function(e){const t={};if(!r(e))return t;const n=s=>{const a=m(s).sort();for(const i of a){const a=y(s,i);if(l(a).isDirectory()){n(a);continue}if("versions.json"===i)continue;const o=Us(S(e,a));t[o]=c(a,"utf-8")}};return n(e),t}(y(t,"template","languages",n));for(const[e,t]of Object.entries(p))i.push({relativePath:e,content:t,metadata:a[e]||o});if(0===i.length)throw new Error(`Companion template files are missing in ${t}`);return{language:n,templates:i}}(e?.preferredLanguage,n),d=[];for(const e of o){const t=ss(y(n,e.relativePath),e,n);if(d.push({path:e.relativePath,updated:t.updated,reason:t.reason}),t.updated){const n="created"===t.reason?"Created":"Updated";console.log(`[Companion] ${n}: ${e.relativePath}`)}}const u=function(e,t){const n=[];for(const s of e){if("notify-user"!==s.metadata.updateStrategy)continue;const e=y(t,s.relativePath);if(!r(e))continue;const a=es(e,t);ns(s.metadata.version,a)>0&&n.push({template:s,targetPath:e,currentVersion:a,newVersion:s.metadata.version})}return n}(o,n);if(u.length>0)try{const e=y(s,"UPGRADES.md"),t=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`}(u);p(e,t,"utf-8");for(const e of u){const t=`${e.targetPath}.upgrade`,n=`# 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`;p(t,n,"utf-8")}console.log(`[Companion] Created UPGRADES.md with ${u.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: ${i}`),{agentDir:n,homeDir:s}}function Ls(e){return!e||"object"!=typeof e||Array.isArray(e)?null:e}function Hs(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}function Gs(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Ws(e){const t=Ls(e.project);return t?{id:Gs(t.id),path:Hs(t.path),path_with_namespace:Hs(t.path_with_namespace),default_branch:Hs(t.default_branch),web_url:Hs(t.web_url)}:null}function Fs(e){return Hs(e.event_type)||Hs(e.object_kind)||"unknown"}async function Bs({gitServerId:e,payload:t,config:n,pat:s}){const a=Fs(t),i=function(e,t,n){if("issue"!==Fs(t))return null;const s=Ws(t),a=function(e){const t=Ls(e.object_attributes);return t?{iid:Gs(t.iid),title:Hs(t.title),url:Hs(t.url),action:Hs(t.action),state:Hs(t.state)}:null}(t);if(!s?.path_with_namespace||!a?.iid)return null;const i=n.ref||s.default_branch;if(!i)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes project.default_branch"};const{owner:o,name:r}=function(e){const t=e.split("/").filter(Boolean);if(t.length<2)return{owner:"",name:e};const n=t[t.length-1];return{owner:t.slice(0,-1).join("/"),name:n}}(s.path_with_namespace),c=function(e,t){switch(e){case"open":case"opened":return"opened";case"reopen":case"reopened":return"reopened";case"close":case"closed":return"closed";case"update":case"updated":case"edit":case"edited":return"edited";default:return"opened"===t?"opened":"closed"===t?"closed":e||"unknown"}}(a.action,a.state),l={AGENTRIX_EVENT_NAME:"issue",AGENTRIX_EVENT_ACTION:c,AGENTRIX_ISSUE_NUMBER:String(a.iid),AGENTRIX_GIT_SERVER_ID:e,AGENTRIX_PROVIDER:"gitlab",AGENTRIX_REPOSITORY_OWNER:o,AGENTRIX_REPOSITORY_NAME:r,AGENTRIX_TRIGGER_SOURCE:"agentrix_daemon_webhook"};a.title&&(l.AGENTRIX_ISSUE_TITLE=a.title);const p=function(e,t){return t.url?t.url:e.web_url&&"number"==typeof t.iid?`${e.web_url}/-/issues/${t.iid}`:void 0}(s,a);p&&(l.AGENTRIX_ISSUE_URL=p);const d={ref:i,variables:l};return s.id?d.projectId=s.id:d.projectPath=s.path_with_namespace,n.triggerToken&&(d.triggerToken=n.triggerToken),void 0!==n.createTriggerIfMissing&&(d.createTriggerIfMissing=n.createTriggerIfMissing),{operationPayload:d,action:c}}(e,t,n);if(!i)return{status:"ignored",eventType:a,reason:"unsupported_event"};if(!n.apiUrl)throw{status:400,message:"GitLab API URL is required"};const o=new cn(n.apiUrl,s,{gitServerId:e});let r;try{r=await o.executeOperation("triggerPipeline",i.operationPayload)}catch(e){const t=function(e){const t=e;return{message:"string"==typeof t?.message?t.message:e instanceof Error?e.message:"Failed to trigger GitLab pipeline",detail:"string"==typeof t?.detail?t.detail:void 0,upstreamStatus:"number"==typeof t?.status?t.status:void 0}}(e);return{status:"failed",eventType:a,action:i.action,reason:"pipeline_trigger_failed",errorMessage:t.message,errorDetail:t.detail,upstreamStatus:t.upstreamStatus}}return{status:"triggered",eventType:a,action:i.action,pipeline:r}}function zs(e,t){const n=[],s=m(e,{withFileTypes:!0});for(const a of s){if(".gitkeep"===a.name)continue;const s=y(e,a.name),i=l(s),o=S(t,s);n.push({name:a.name,path:o,size:i.size,modifiedAt:i.mtimeMs,isDirectory:a.isDirectory()}),a.isDirectory()&&n.push(...zs(s,t))}return n}function Ks(e){return Array.isArray(e)?e[0]:e}function Vs(e){const{getChildren:t,stopSession:n,requestShutdown:s,registerSession:a,credentials:i,getSocketClient:o}=e;return new Promise(d=>{const u=re.getDaemonControlHost(),m=re.getDaemonWebhookHost(),g=He({logger:!1});g.removeContentTypeParser("application/json"),g.addContentTypeParser("application/json",{parseAs:"string"},(e,t,n)=>{const s="string"==typeof t?t:t.toString("utf8");if(0!==s.trim().length)try{n(null,JSON.parse(s))}catch(e){const t=e instanceof Error?e:new Error("Invalid JSON body");t.statusCode=400,n(t,void 0)}else n(null,{})}),g.setValidatorCompiler(Fe),g.setSerializerCompiler(Be);const f=g.withTypeProvider(),v=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")};f.post("/session-started",{schema:{body:Ge.object({sessionId:Ge.string(),metadata:Ge.any()}),response:{200:Ge.object({status:Ge.literal("ok")})}}},async e=>{const{sessionId:t,metadata:n}=e.body;return ce.debug(`[CONTROL SERVER] Session started: ${t}`),a(t,n),{status:"ok"}}),f.options("/ping",async(e,t)=>(v(t),t.send())),f.get("/ping",{schema:{response:{200:Ge.object({status:Ge.literal("ok"),machineId:Ge.string(),timestamp:Ge.string(),controlHost:Ge.string(),webhookHost:Ge.string()})}}},async(e,t)=>(v(t),{status:"ok",machineId:i.machineId,timestamp:(new Date).toISOString(),controlHost:u,webhookHost:m})),f.options("/openers",async(e,t)=>(v(t),t.send())),f.get("/openers",{schema:{response:{200:Ge.object({openers:Ge.array(Ge.object({id:Ge.string(),label:Ge.string(),kind:Ge.enum(["system","file-manager","editor","ide"]),method:Ge.enum(["scheme","cli"]),urlTemplate:Ge.string().optional(),supported:Ge.boolean()}))})}}},async(e,t)=>(v(t),{openers:await Hn()})),f.options("/open",async(e,t)=>(v(t),t.send())),f.options("/pick-directory",async(e,t)=>(v(t),t.send())),f.post("/open",{schema:{body:Ge.object({path:Ge.string(),openerId:Ge.string(),userId:Ge.string().optional(),taskId:Ge.string().optional()}),response:{200:Ge.object({success:Ge.boolean(),error:Ge.string().optional()})}}},async(e,t)=>{v(t);const{path:n,openerId:s,userId:a,taskId:i}=e.body;return await async function({openerId:e,targetPath:t,userId:n,taskId:s}){const a=Wn(zn()).find(t=>t.id===e);if(!a)return{success:!1,error:"Unknown openerId"};if("cli"!==a.method||!a.open)return{success:!1,error:"Opener is not executable by CLI"};if(!a.isSupported())return{success:!1,error:"Opener is not supported on this system"};let i;try{i=function(e,t,n){const s=x.resolve(e);if(!x.isAbsolute(s))throw new Error("Path must be absolute");if(!l(s).isDirectory())throw new Error("Path must be a directory");if(t&&n){const e=re.getTaskCwd(t,n);if(e&&!function(e,t){const n=x.relative(t,e);return""===n||!n.startsWith("..")&&!x.isAbsolute(n)}(s,x.resolve(e)))throw new Error("Path is outside the task workspace")}return s}(t,n,s)}catch(e){return{success:!1,error:e instanceof Error?e.message:"Invalid path"}}try{return a.open(i),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Failed to open path";return ce.warn(`[OPENERS] Failed to open path: ${t}`),{success:!1,error:t}}}({openerId:s,targetPath:n,userId:a,taskId:i})}),f.post("/pick-directory",{schema:{body:Ge.object({defaultPath:Ge.string().optional()}),response:{200:Ge.object({path:Ge.string().nullable(),error:Ge.string().optional()})}}},async(e,t)=>{v(t);try{return{path:Gn(e.body.defaultPath)??null}}catch(e){return{path:null,error:e instanceof Error?e.message:"Failed to pick directory"}}}),f.post("/companion/ensure",{schema:{body:Ge.object({preferredLanguage:Ge.enum(["en","zh-Hans"]).nullable().optional()}).optional(),response:{200:Ge.object({agentDir:Ge.string()})}}},async e=>await qs({preferredLanguage:e.body?.preferredLanguage,credentials:i})),f.post("/companion/probe",{schema:{response:{200:Ge.object({success:Ge.boolean(),error:Ge.string().optional()})}}},async()=>await Ns()),f.get("/companion/workspace",{schema:{response:{200:Ge.object({files:Ge.array(Ge.object({name:Ge.string(),path:Ge.string(),size:Ge.number(),modifiedAt:Ge.number(),isDirectory:Ge.boolean()}))})}}},async()=>{const{homeDir:e}=await qs({credentials:i});return r(e)?{files:zs(e,e)}:{files:[]}}),f.get("/companion/file",{schema:{querystring:Ge.object({path:Ge.string()}),response:{200:Ge.object({content:Ge.string()}),404:Ge.object({error:Ge.string()})}}},async(e,t)=>{const{homeDir:n}=await qs({credentials:i}),s=T(y(n,e.query.path));return s.startsWith(n)&&r(s)?{content:c(s,"utf-8")}:t.code(404).send({error:"File not found"})}),f.put("/companion/file",{schema:{body:Ge.object({path:Ge.string(),content:Ge.string()}),response:{200:Ge.object({success:Ge.boolean()}),400:Ge.object({error:Ge.string()})}}},async(e,t)=>{const{homeDir:n}=await qs({credentials:i}),s=T(y(n,e.body.path));return s.startsWith(n)?(h(b(s),{recursive:!0}),p(s,e.body.content,"utf-8"),{success:!0}):t.code(400).send({error:"Invalid path"})}),f.get("/companion/config",{schema:{response:{200:Ge.object({heartbeatIntervalMs:Ge.number(),heartbeatEnabled:Ge.boolean(),lastHeartbeatTimestamp:Ge.string().nullable(),lastHeartbeatDate:Ge.string().nullable(),lastInteractionTimestamp:Ge.string().nullable()})}}},async()=>{const{homeDir:e}=await qs({credentials:i}),t=y(e,"state.json");let n=9e5,s=!1,a=null,o=null,l=null;if(r(t))try{const e=JSON.parse(c(t,"utf-8"));"number"==typeof e.heartbeatIntervalMs&&(n=e.heartbeatIntervalMs),"boolean"==typeof e.heartbeatEnabled&&(s=e.heartbeatEnabled),"string"==typeof e.lastHeartbeatTimestamp&&(a=e.lastHeartbeatTimestamp),"string"==typeof e.lastHeartbeatDate&&(o=e.lastHeartbeatDate),"string"==typeof e.lastInteractionTimestamp&&(l=e.lastInteractionTimestamp)}catch{}return{heartbeatIntervalMs:n,heartbeatEnabled:s,lastHeartbeatTimestamp:a,lastHeartbeatDate:o,lastInteractionTimestamp:l}}),f.put("/companion/config",{schema:{body:Ge.object({heartbeatIntervalMs:Ge.number().optional(),heartbeatEnabled:Ge.boolean().optional()}),response:{200:Ge.object({success:Ge.boolean()})}}},async e=>{const{homeDir:t}=await qs({credentials:i}),n=y(t,"state.json");let s={};if(r(n))try{s=JSON.parse(c(n,"utf-8"))}catch{}const{heartbeatIntervalMs:a,heartbeatEnabled:o}=e.body;return void 0!==a&&(s.heartbeatIntervalMs=a),void 0!==o&&(s.heartbeatEnabled=o),h(b(n),{recursive:!0}),p(n,JSON.stringify(s,null,2),"utf-8"),{success:!0}}),f.post("/agent/install",{schema:{body:Ge.object({agentId:Ge.string(),gitUrl:Ge.string(),branch:Ge.string().optional(),subDir:Ge.string().optional()}),response:{200:Ge.object({agentDir:Ge.string()}),500:Ge.object({error:Ge.string()})}}},async(e,t)=>{try{return await as(e.body)}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(500).send({error:n})}}),f.post("/git-server/register",{schema:{body:Ge.object({id:Ge.string().min(1),name:Ge.string().min(1),baseUrl:Ge.string().url(),apiUrl:Ge.string().url()}),response:{200:Ge.object({gitServer:Ge.object({id:Ge.string(),type:Ge.string(),name:Ge.string(),baseUrl:Ge.string(),apiUrl:Ge.string()}),machineId:Ge.string()}),502:Ge.object({error:Ge.string()})}}},async(e,t)=>{try{const n=await fetch(`${re.serverUrl}/v1/git-servers/machine-register`,{method:"POST",headers:{Authorization:`Bearer ${i.token}`,"Content-Type":"application/json"},body:JSON.stringify({...e.body,machineId:i.machineId}),signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>null);if(!n.ok){const a="string"==typeof s?.message?s.message:`API request failed with HTTP ${n.status}`;return ce.warn(`[GIT SERVER] register failed: id=${e.body.id}, message=${a}`),t.code(502).send({error:a})}return t.send(s)}catch(n){const s=function(e){return e instanceof Error?e.message:"Unknown error"}(n);return ce.warn(`[GIT SERVER] register failed: id=${e.body.id}, message=${s}`),t.code(502).send({error:s})}}),f.post("/webhooks/gitlab/:gitServerId",{schema:{params:Ge.object({gitServerId:Ge.string()}),body:Ge.record(Ge.string(),Ge.unknown()),response:{200:Ge.object({status:Ge.enum(["triggered","ignored","failed"]),eventType:Ge.string(),action:Ge.string().optional(),pipeline:Ge.unknown().optional(),reason:Ge.string().optional(),errorMessage:Ge.string().optional(),errorDetail:Ge.string().optional(),upstreamStatus:Ge.number().optional()}),400:Ge.object({error:Ge.string()}),401:Ge.object({error:Ge.string()}),403:Ge.object({error:Ge.string()}),404:Ge.object({error:Ge.string()}),502:Ge.object({error:Ge.string()}),500:Ge.object({error:Ge.string()})}}},async(e,t)=>{const n=se(),s=Date.now(),a=function(e){const t=e.event_type??e.object_kind;return"string"==typeof t?t:"unknown"}(e.body),i="issue"===a?function(e){const t=Ws(e);return t?.id?String(t.id):t?.path_with_namespace??null}(e.body):null,r=e.ip||"-",c="string"==typeof e.headers["user-agent"]?e.headers["user-agent"]:"-",l=(a,i)=>{const o=Date.now()-s,r=function(e){if(!e||"object"!=typeof e)return"type="+typeof e;const t=e;if("string"==typeof t.error)return`error=${t.error}`;const n=String(t.status??"-"),s=String(t.eventType??"-"),a=String(t.action??"-"),i=String(t.reason??"-"),o=String(t.upstreamStatus??"-"),r=String(t.errorMessage??"-"),c=function(e){if(!e||"object"!=typeof e)return"-";const t=e,n=t.id??t.iid??"-",s=t.status??"-",a=t.ref??"-",i=t.web_url??t.webUrl??"-";return`id=${String(n)}, status=${String(s)}, ref=${String(a)}, webUrl=${String(i)}`}(t.pipeline);return`status=${n}, eventType=${s}, action=${a}, reason=${i}, upstreamStatus=${o}, errorMessage=${r}, pipeline=${c}`}(i);return ce[a>=400?"warn":"info"](`[GITLAB WEBHOOK] response: hookId=${n}, gitServer=${e.params.gitServerId}, statusCode=${a}, elapsedMs=${o}, ${r}`),t.code(a).send(i)};ce.info(`[GITLAB WEBHOOK] request received: hookId=${n}, gitServer=${e.params.gitServerId}, eventType=${a}, projectKey=${i??"-"}, remote=${r}, userAgent=${c}`);const p=await Vt();if(!p)return l(500,{error:"Git server encryption key not available"});const d=Qt(e.params.gitServerId,p),u=d?.webhookSecret;if(!u)return l(403,{error:`GitLab webhook bridge is not configured for git server ${e.params.gitServerId}`});if(!function(e,t){if("string"!=typeof e)return!1;const n=Buffer.from(e),s=Buffer.from(t);return n.length===s.length&&ae(n,s)}(e.headers["x-gitlab-token"],u))return l(401,{error:"Invalid GitLab webhook token"});const m=Ks(e.headers["x-gitlab-event-uuid"])??Ks(e.headers["x-gitlab-delivery"]),h=a;(async function(e,t,n,s,a){if(!a?.connected)throw new Error("Machine WebSocket is not connected");const i={eventId:N(),provider:"gitlab",gitServerId:e,deliveryId:n,eventType:s,payload:t},o=await async function(e){let t;try{return await Promise.race([e,new Promise((e,n)=>{t=setTimeout(()=>n(new Error("Timed out waiting for repository inbox webhook ack")),5e3)})])}finally{t&&clearTimeout(t)}}(a.sendWithAck("repository-inbox-webhook",i));if("success"!==o.status)throw new Error(o.message||"API failed to process repository inbox webhook")})(e.params.gitServerId,e.body,m,h,o?.()).catch(t=>{const s=t instanceof Error?t.message:String(t);ce.warn(`[GITLAB WEBHOOK] inbox side-channel failed: hookId=${n}, gitServer=${e.params.gitServerId}, message=${s}`)});const g=an(e.params.gitServerId,p);if(!g)return l(403,{error:`No PAT configured for git server ${e.params.gitServerId}`});try{const t=Yt(e.params.gitServerId),s=t?.apiUrl;if(!s)return l(400,{error:`GitLab API URL is not configured for git server ${e.params.gitServerId}`});let o;if(i)if(o=d.projectTriggerTokens?.[i],o)ce.info(`[GITLAB WEBHOOK] pipeline trigger token reused: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}`);else{const t=function(e){const t=Ws(e);return t?.path_with_namespace?t.id?{projectId:t.id}:{projectPath:t.path_with_namespace}:null}(e.body);if(!t)return l(400,{error:"GitLab webhook payload is missing project information"});ce.info(`[GITLAB WEBHOOK] ensuring pipeline trigger token: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}, mode=create_or_reuse`);const a=new cn(s,g,{gitServerId:e.params.gitServerId}),r=await a.executeOperation("ensurePipelineTriggerToken",t);if(!r||"object"!=typeof r||"string"!=typeof r.token)return l(502,{error:"Failed to create GitLab pipeline trigger token"});o=r.token,Zt(e.params.gitServerId,{webhookSecret:u,projectTriggerTokens:{...d.projectTriggerTokens??{},[i]:o}},p),ce.info(`[GITLAB WEBHOOK] pipeline trigger token stored: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}`)}return ce.info(`[GITLAB WEBHOOK] triggering pipeline: hookId=${n}, gitServer=${e.params.gitServerId}, eventType=${a}, projectKey=${i??"-"}`),l(200,await Bs({gitServerId:e.params.gitServerId,payload:e.body,pat:g,config:{apiUrl:s,triggerToken:o}}))}catch(t){const s=t,a="number"==typeof s.status&&s.status>=400&&s.status<600?s.status:500,i="string"==typeof s.message?s.message:t instanceof Error?t.message:"Failed to process GitLab webhook";return ce.warn(`[GITLAB WEBHOOK] failed: hookId=${n}, gitServer=${e.params.gitServerId}, statusCode=${a}, message=${i}`),l(a,{error:i})}}),f.post("/schedule",{schema:{body:Ge.object({task:Ge.string(),type:Ge.enum(["once","recurring"]),due:Ge.string().optional(),cron:Ge.string().optional(),timezone:Ge.string().optional(),timeType:Ge.enum(["utc","local"]).optional()}),response:{200:Ge.object({id:Ge.string(),task:Ge.string(),type:Ge.enum(["once","recurring"]),due:Ge.string().optional(),cron:Ge.string().optional(),timezone:Ge.string().optional(),timeType:Ge.enum(["utc","local"]).optional(),createdAt:Ge.string()}),400:Ge.object({error:Ge.string()}),503:Ge.object({error:Ge.string()})}}},async(t,n)=>{const s=e.companionScheduler;if(!s)return n.code(503).send({error:"Companion scheduler not available"});const{task:a,type:i,due:o,cron:r,timezone:c,timeType:l}=t.body;return"once"!==i||o?"recurring"!==i||r?s.addScheduledTask({task:a,type:i,due:o,cron:r,timezone:c,timeType:l}):n.code(400).send({error:'"cron" is required for recurring tasks'}):n.code(400).send({error:'"due" is required for one-time tasks'})}),f.get("/schedule",{schema:{response:{200:Ge.object({tasks:Ge.array(Ge.object({id:Ge.string(),task:Ge.string(),type:Ge.enum(["once","recurring"]),due:Ge.string().optional(),cron:Ge.string().optional(),timezone:Ge.string().optional(),timeType:Ge.enum(["utc","local"]).optional(),createdAt:Ge.string()}))}),503:Ge.object({error:Ge.string()})}}},async(t,n)=>{const s=e.companionScheduler;return s?{tasks:s.listScheduledTasks()}:n.code(503).send({error:"Companion scheduler not available"})}),f.delete("/schedule/:id",{schema:{params:Ge.object({id:Ge.string()}),response:{200:Ge.object({success:Ge.boolean()}),404:Ge.object({error:Ge.string()}),503:Ge.object({error:Ge.string()})}}},async(t,n)=>{const s=e.companionScheduler;return s?s.deleteScheduledTask(t.params.id)?{success:!0}:n.code(404).send({error:`Task ${t.params.id} not found`}):n.code(503).send({error:"Companion scheduler not available"})}),f.post("/list",{schema:{response:{200:Ge.object({children:Ge.array(Ge.object({startedBy:Ge.string(),taskId:Ge.string(),pid:Ge.number()}))})}}},async()=>({children:t().filter(e=>void 0!==e.taskId).map(e=>({startedBy:e.startedBy,taskId:e.taskId,pid:e.pid}))})),f.post("/stop-session",{schema:{body:Ge.object({sessionId:Ge.string()}),response:{200:Ge.object({success:Ge.boolean()})}}},async e=>{const{sessionId:t}=e.body;return ce.debug(`[CONTROL SERVER] Stop session request: ${t}`),{success:n(t)}}),f.post("/stop",{schema:{response:{200:Ge.object({status:Ge.string()})}}},async()=>(ce.debug("[CONTROL SERVER] Stop daemon request received"),setTimeout(()=>{ce.debug("[CONTROL SERVER] Triggering daemon shutdown"),s()},50),{status:"stopping"})),"127.0.0.1"!==u&&ce.warn(`[CONTROL SERVER] Listening on ${u}; ensure daemon control endpoints are protected by network policy`);const w=e=>new Promise((t,n)=>{g.listen({port:e,host:u},(e,s)=>{e?n(e):t(s)})});(async()=>{let e;try{e=await w(30624)}catch(t){const n=t?.code;if("EADDRINUSE"!==n&&"EACCES"!==n)throw ce.info("[CONTROL SERVER] Failed to start:",t),t;ce.info(`[CONTROL SERVER] Port 30624 unavailable (${n??"error"}), falling back to dynamic port`),e=await w(0)}const t=parseInt(e.split(":").pop());ce.info(`[CONTROL SERVER] Started on port ${t}`),d({port:t,host:u,webhookHost:m,stop:async()=>{await g.close(),ce.info("[CONTROL SERVER] Server stopped")}})})().catch(e=>{throw ce.info("[CONTROL SERVER] Failed to start:",e),e})})}function Xs(e,t={}){const n=le(),s=y(n,"dist","index.mjs"),a=["--no-warnings","--no-deprecation",s,...e];if(!r(s)){const e=`Entrypoint ${s} does not exist`;throw ce.debug(`[SPAWN Agentrix CLI] ${e}`),new Error(e)}return Ne(process.execPath,a,t)}const Js=[{version:1,fileName:"001_init.sql"}];function Ys(e){var t;return function(e,t){const n=new et(e),s=new Ze;n.pragma("journal_mode = WAL"),function(e){const t=function(){const e=Ie(tt(import.meta.url)),t=[ke(e,"migrations"),ke(process.cwd(),"dist","migrations"),ke(process.cwd(),"src","worker","history","migrations")];for(const e of t)if(xe(e))return e;throw new Error(`Task history migrations directory not found at ${t[0]}`)}(),n=e.pragma("user_version",{simple:!0}),s=function(e,t){const n=ke(e,t);return ve(n,"utf8")}(t,Js[0].fileName);e.exec(s),n<Js[0].version&&e.pragma(`user_version = ${Js[0].version}`)}(n);const a=n.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=n.prepare("SELECT local_sequence FROM task_message WHERE event_id = ?"),o=n.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=n.prepare("\n UPDATE task_event\n SET sequence = ?\n WHERE event_id = ? AND (sequence IS NULL OR sequence < ?)\n "),c=n.prepare("\n SELECT * FROM task_event\n WHERE sequence > ? AND event_type = 'task-message'\n ORDER BY sequence ASC\n LIMIT ?\n "),l=n.prepare("\n SELECT 1 as has_row\n FROM task_event\n WHERE sequence > ? AND event_type = 'task-message'\n LIMIT 1\n "),p=n.prepare("\n SELECT * FROM task_message\n ORDER BY local_sequence DESC\n LIMIT ?\n "),d=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence ASC\n LIMIT ?\n "),u=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence < ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),m=n.prepare("\n SELECT 1 as has_row\n FROM task_message\n WHERE local_sequence < ?\n LIMIT 1\n "),h=n.prepare("\n SELECT 1 as has_row\n FROM task_message\n WHERE local_sequence > ?\n LIMIT 1\n "),g=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),f=n.prepare("\n SELECT agent_id, session_id, last_sequence\n FROM task_agent_session\n "),v=n.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 "),x=n.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 n=e.eventId??N(),o=(new Date).toISOString(),r=a.run({eventId:n,taskId:t,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,message:JSON.stringify(e.message),createdAt:o}).changes>0,c=i.get(n),l=c?.local_sequence??null;return r&&null!==l&&s.emit("message-saved",{eventId:n}),{eventId:n,localSequence:l,inserted:r}},saveTaskEvent:e=>{const t=e.eventId??N(),n=(new Date).toISOString(),s={...e.eventData,eventId:t};return o.run({eventId:t,taskId:e.taskId,chatId:e.chatId,sequence:e.sequence,eventType:e.eventType,eventData:JSON.stringify(s),createdAt:n}),t},updateTaskEventSequence:(e,t)=>{r.run(t,e,t)},pageTaskEventsAfter:(e,t)=>{const n=c.all(e,t).map(Zs),s=n.at(-1)?.sequence??null;return{data:n,hasMore:null!==s&&Boolean(l.get(s))}},getLatestTaskEvent:e=>{if(0===e.length)return null;const t=e.map(()=>"?").join(","),s=n.prepare(`\n SELECT * FROM task_event\n WHERE event_type IN (${t})\n ORDER BY created_at DESC, rowid DESC\n LIMIT 1\n `).get(...e);return s?Zs(s):null},pageRecentMessages:e=>{const t=p.all(e).map(Qs).reverse(),n=t[0]?.localSequence??null;return{data:t,hasMore:!!n&&Boolean(m.get(n))}},pageMessagesAfter:(e,t)=>{const n=d.all(e,t).map(Qs),s=n.at(-1)?.localSequence??null;return{data:n,hasMore:!!s&&Boolean(h.get(s))}},pageMessagesBefore:(e,t)=>{const n=u.all(e,t).map(Qs).reverse(),s=n[0]?.localSequence??null;return{data:n,hasMore:!!s&&Boolean(m.get(s))}},pageRecentMessagesAfter:(e,t)=>{const n=g.all(e,t).map(Qs).reverse(),s=n[0]?.localSequence??null;return{data:n,hasMore:!!s&&Boolean(m.get(s))}},getAgentSessions:()=>{const e=f.all(),t=new Map;for(const n of e)t.set(n.agent_id,n.session_id);return t},getAgentLastSequences:()=>{const e=f.all(),t=new Map;for(const n of e)t.set(n.agent_id,n.last_sequence);return t},upsertAgentSession:(e,n)=>{v.run(e,t,n,(new Date).toISOString())},updateAgentLastSequence:(e,n)=>{x.run(e,t,n,(new Date).toISOString())},on:(e,t)=>{s.on(e,t)},off:(e,t)=>{s.off(e,t)},close:()=>{s.removeAllListeners(),n.close()}}}((t=e.dataDir,ke(t,"data.bin")),e.taskId)}function Qs(e){const t=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:t,createdAt:e.created_at}}function Zs(e){const t=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:t,createdAt:e.created_at}}const ea={".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"},ta={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","image/svg+xml":".svg","image/x-icon":".ico","application/pdf":".pdf","text/plain":".txt","text/html":".html","text/csv":".csv","application/json":".json","video/mp4":".mp4","audio/mpeg":".mp3"};async function na(e,t,n=!1){try{const s=await fetch(e);if(!s.ok)throw new Error(`Failed to download file: ${s.status} ${s.statusText}`);if(!s.body)throw new Error("Response body is null");const a=function(e){try{const t=new URL(e),n=E(t.pathname);if(n)return n;const s=t.searchParams.get("filename")||t.searchParams.get("name")||t.searchParams.get("file");if(s){const e=E(s);if(e)return e}return""}catch{return""}}(e),i=s.headers.get("content-type"),o=i?.split(";")[0].trim()||function(e){const t=e.toLowerCase();return ea[t]||"application/octet-stream"}(a),r=a||function(e){return ta[e]||""}(o);let c;if(n)try{const t=new URL(e).pathname,n=w(t);c=n&&E(n)?n:`${se()}${r||".dat"}`}catch{c=`${se()}${r||".dat"}`}else c=`${se()}${r||".dat"}`;const l=y(t,c),p=s.body,d=g(l);return await st(p,d),{filePath:l,mimeType:o,filename:c}}catch(t){throw new Error(`Failed to download file from ${e}: ${t instanceof Error?t.message:String(t)}`)}}async function sa(e,t){const{attachmentsDir:n,log:s}=t;if(!Array.isArray(e.message.content))return e;const a=await Promise.all(e.message.content.map(async e=>"image"===e.type&&"url"===e.source?.type&&e.source?.url?async function(e,t,n){try{const s=e.source.url;n?.("info","IMAGE",`Downloading image to file (no-vision mode): ${s}`);const{filePath:a,mimeType:i}=await na(s,t,!0);return n?.("info","IMAGE",`Image saved to: ${a}`),{type:"text",text:`Image file: ${a}\nType: ${i}`}}catch(t){return n?.("error","IMAGE",`Error downloading image to file: ${t}`),e}}(e,n,s):"document"===e.type&&"url"===e.source?.type&&e.source?.url?async function(e,t,n){try{const s=e.source.url;n?.("info","DOCUMENT",`Downloading document from: ${s}`);const{filePath:a,mimeType:i,filename:o}=await na(s,t,!0);return n?.("info","DOCUMENT",`Document downloaded to: ${a}`),{type:"text",text:`Document: ${a}\nTitle: ${e.title||o}\nType: ${i}`}}catch(t){return n?.("error","DOCUMENT",`Error processing document: ${t}`),e}}(e,n,s):e));return{...e,message:{...e.message,content:a}}}class aa{pidToTrackedSession;taskToStartPromise;sandboxPool;constructor(e){this.pidToTrackedSession=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[t,n]of this.pidToTrackedSession.entries())if(n.taskId===e){if(this.isProcessAlive(t))return n;this.pidToTrackedSession.delete(t)}}getCurrentSessions(){return Array.from(this.pidToTrackedSession.values())}getSessionByPid(e){return this.pidToTrackedSession.get(e)}registerTaskWorker(e,t){const n=t.pid;if(!n)return void ce.warn(`[SESSION] Missing PID for task ${e}`);ce.info(`[SESSION] Registered task ${e}, PID: ${n}`);const s=this.pidToTrackedSession.get(n);if(!(s&&s.taskId===e||s)){const t={startedBy:"cli",taskId:e,pid:n};this.pidToTrackedSession.set(n,t)}}async decryptTaskMessage(e){if(!e.dataEncryptionKey)return;const t=await re.getSecretKey();if(!t)return;const n=D(O(e.dataEncryptionKey),t);if(!n)return void ce.warn("[SESSION] Failed to decrypt data encryption key");if(e.dataEncryptionKey=_(n),"task-message"!==e.event)return;const s=e.eventData;if(!s.encryptedMessage)return;const a=H(s.encryptedMessage,n);a?e.eventData={...s,message:a,encryptedMessage:void 0}:ce.warn("[SESSION] Failed to decrypt task message")}async persistCreateTaskStart(e){const t=re.resolveDataDir(e.userId,e.taskId),n=re.resolveAttachmentsDir(e.userId,e.taskId),s=Ys({dataDir:t,taskId:e.taskId});try{const t=e.eventData;if(s.saveTaskEvent({eventType:e.event,eventId:t.eventId,eventData:t,taskId:e.taskId,chatId:e.chatId,sequence:t.sequence??0}),t.message){let e=t.message;G(e)&&(e=await sa(e,{attachmentsDir:n,log:(e,t,n)=>ce["debug"===e?"info":e](`[ATTACH:${t}] ${n}`)})),s.saveMessage({eventId:t.eventId,message:e,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName})}}finally{s.close()}}persistResumeTaskStart(e){const t=Ys({dataDir:re.resolveDataDir(e.userId,e.taskId),taskId:e.taskId}),n=e.eventData.sequence;if(null==n)throw new Error(`Missing resume sequence for task ${e.taskId}`);try{const s=e.eventData;t.saveTaskEvent({eventType:e.event,eventId:s.eventId,eventData:s,taskId:e.taskId,chatId:e.chatId,sequence:n}),s.message&&t.saveMessage({eventId:s.eventId,message:s.message,senderType:s.senderType,senderId:s.senderId,senderName:s.senderName})}finally{t.close()}}trackWorkerProcess(e,t){const n={startedBy:"daemon",pid:t.pid,childProcess:t,taskId:e.taskId};this.pidToTrackedSession.set(t.pid,n),t.on("exit",(n,s)=>{this.pidToTrackedSession.delete(t.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId)}),t.on("error",n=>{this.pidToTrackedSession.delete(t.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId)})}async startWorker(e,t){const n={eventId:N(),status:"success",opCode:e.eventId};await this.decryptTaskMessage(e),re.writeTaskInput(e),"create-task"===t?await this.persistCreateTaskStart(e):this.persistResumeTaskStart(e);const s=this.taskToStartPromise.get(e.taskId);if(s)return ce.info(`[SESSION] Task ${e.taskId} is already starting, skip duplicate ${t}`),s;const a=this.startWorkerInternal(e,t,n).finally(()=>{this.taskToStartPromise.get(e.taskId)===a&&this.taskToStartPromise.delete(e.taskId)});return this.taskToStartPromise.set(e.taskId,a),a}async startWorkerInternal(e,t,n){const s=this.getAliveSessionByTaskId(e.taskId);if(s)return ce.info(`[SESSION] Task ${e.taskId} already has worker PID ${s.pid}, skip duplicate ${t}`),n.message=`Worker already running (PID ${s.pid})`,n;const a=re.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,a))throw new Error("Failed to create sandbox instance");const{projectPath:t}=await import("./logger-BVnpkRi2.mjs").then(function(e){return e.d}),{join:n}=await import("path"),s=["--no-warnings","--no-deprecation",n(t(),"dist","index.mjs"),...i],r=`"${process.execPath}" ${s.map(e=>`"${e}"`).join(" ")}`,c=await this.sandboxPool.wrapWorkerCommand(e.taskId,r);ce.debug(`[SESSION] Sandboxed command for task ${e.taskId}: ${c}`),o=Ne(c,{shell:!0,cwd:a,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}}),ce.info(`[SESSION] Worker started with sandbox, PID: ${o.pid}`)}catch(t){return ce.error(`[SESSION] Failed to setup sandbox for task ${e.taskId}:`,t),n.status="failed",n.message=`Sandbox setup failed: ${t instanceof Error?t.message:String(t)}`,n}else o=Xs(i,{cwd:a,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}}),ce.info(`[SESSION] Worker started without sandbox, PID: ${o.pid}`);return process.env.DEBUG&&(o.stdout?.on("data",e=>{ce.debug(`[Daemon] worker stdout: ${e.toString()}`)}),o.stderr?.on("data",e=>{ce.debug(`[Daemon] worker stderr: ${e.toString()}`)})),o.pid?(ce.info(`[SESSION] Worker started, PID: ${o.pid}`),this.trackWorkerProcess(e,o),n):(n.status="failed",n.message="Failed to start worker - no PID",n)}stopSession(e){for(const[t,n]of this.pidToTrackedSession.entries())if(n.taskId===e){try{(n.childProcess?n.childProcess:{kill:e=>process.kill(t,e)}).kill("SIGTERM"),ce.info(`[SESSION] Task ${e} stopped`);const s=setTimeout(()=>{const n=this.pidToTrackedSession.get(t);if(n&&n.taskId===e&&this.isProcessAlive(t))try{process.kill(t,"SIGKILL"),ce.warn(`[SESSION] Task ${e} did not exit after SIGTERM, sent SIGKILL to PID ${t}`)}catch(n){ce.warn(`[SESSION] Failed to force kill task ${e} (PID ${t}):`,n)}},3e3);s.unref?.()}catch(n){ce.warn(`[SESSION] Failed to stop task ${e}:`,n),this.isProcessAlive(t)||this.pidToTrackedSession.delete(t)}return!0}return ce.warn(`[SESSION] Task ${e} not found`),!1}pruneStaleSessions(){for(const[e,t]of this.pidToTrackedSession.entries())try{process.kill(e,0)}catch(t){this.pidToTrackedSession.delete(e)}}shutdown(){ce.info("[SESSION] Shutting down all sessions");for(const[e,t]of this.pidToTrackedSession.entries())try{"daemon"===t.startedBy&&t.childProcess?t.childProcess.kill("SIGTERM"):process.kill(e,"SIGTERM")}catch(t){ce.warn(`[SESSION] Failed to stop PID ${e}:`,t)}this.pidToTrackedSession.clear()}async startHivePublishWorker(e){const t={eventId:N(),status:"success",opCode:e.eventId};re.writeTaskInput(e);try{const n=Xs(["worker","--type","hive-publish","--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&&(n.stdout?.on("data",e=>{ce.debug(`[HivePublish] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{ce.debug(`[HivePublish] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start hive-publish worker - no PID",t;ce.info(`[SESSION] Hive publish worker started, PID: ${n.pid}`);const s={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(s,n),t}catch(e){return t.status="failed",t.message=`Failed to start hive-publish worker: ${e instanceof Error?e.message:String(e)}`,t}}async startHiveInstallWorker(e){const t={eventId:N(),status:"success",opCode:e.eventId};re.writeTaskInput(e);try{const n=Xs(["worker","--type","hive-install","--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&&(n.stdout?.on("data",e=>{ce.debug(`[HiveInstall] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{ce.debug(`[HiveInstall] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start hive-install worker - no PID",t;ce.info(`[SESSION] Hive install worker started, PID: ${n.pid}`);const s={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(s,n),t}catch(e){return t.status="failed",t.message=`Failed to start hive-install worker: ${e instanceof Error?e.message:String(e)}`,t}}async startDeploymentWorker(e){const t={eventId:N(),status:"success",opCode:e.eventId};re.writeTaskInput(e);try{const n=Xs(["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&&(n.stdout?.on("data",e=>{ce.debug(`[Deployment] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{ce.debug(`[Deployment] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start deployment worker - no PID",t;ce.info(`[SESSION] Deployment worker started, PID: ${n.pid}`);const s={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(s,n),t}catch(e){return t.status="failed",t.message=`Failed to start deployment worker: ${e instanceof Error?e.message:String(e)}`,t}}}class ia{networkManager=null;workerSandboxes=new Map;settings=null;platform;constructor(){this.platform=Le()}async initialize(e){if(this.settings=e,!e.enabled)return ce.info("[SANDBOX] Sandbox disabled via settings"),!1;if(!at(this.platform))return ce.warn("[SANDBOX] Platform not supported, sandbox disabled"),!1;try{const t={allowedDomains:[new URL(re.serverUrl).hostname,...e.network.allowedDomains],deniedDomains:e.network.deniedDomains,allowLocalBinding:!1};return this.networkManager=new it,await this.networkManager.initialize(t),ce.info("[SANDBOX] Sandbox pool initialized successfully"),!0}catch(e){throw ce.error("[SANDBOX] Failed to initialize:",e),e}}async createWorkerSandbox(e,t,n){if(!this.networkManager||!this.settings?.enabled)return null;try{const s=re.resolveUserWorkSpaceDir(t),a=re.getStatePaths().logsDir,i=this.settings.filesystem||{},o=this.settings.env||{},r={...i,allowWrite:[...i.allowWrite||[],s,n,a]};if("linux"===this.platform&&i.allowRead){const e=we.dirname(process.execPath);r.allowRead=[...i.allowRead,e]}const c={filesystem:r,env:o},l=new ot(this.networkManager,c);return this.workerSandboxes.set(e,l),ce.info(`[SANDBOX] Created sandbox for task ${e}`),l}catch(t){return ce.error(`[SANDBOX] Failed to create sandbox for task ${e}:`,t),null}}async wrapWorkerCommand(e,t){const n=this.workerSandboxes.get(e);if(!n)throw new Error(`No sandbox found for task ${e}`);const s=await n.wrapWithSandbox(t);return ce.debug(`[SANDBOX] Wrapped command for task ${e}`),s}disposeWorkerSandbox(e){const t=this.workerSandboxes.get(e);t&&(t.dispose(),this.workerSandboxes.delete(e),ce.debug(`[SANDBOX] Disposed sandbox for task ${e}`))}async shutdown(){ce.info("[SANDBOX] Shutting down sandbox pool");for(const[e,t]of this.workerSandboxes.entries())t.dispose(),ce.debug(`[SANDBOX] Disposed sandbox for task ${e}`);this.workerSandboxes.clear(),this.networkManager&&(await this.networkManager.shutdown(),this.networkManager=null,ce.info("[SANDBOX] Network manager shutdown complete"))}isEnabled(){return!0===this.settings?.enabled}}class oa{constructor(e,t){this.client=e,this.machineId=t;const n=re.agentrixAgentsHomeDir,s=y(n,"companion","claude");this.stateFilePath=y(s,"state.json")}timer=null;initialDelay=null;intervalMs=9e5;enabled=!1;heartbeatTaskId=null;companionState=null;stateFilePath;cronJobs=new Map;start(){this.loadState(),this.companionState?(ce.info(`[COMPANION SCHEDULER] Ready: agent=${this.companionState.agentId}, chatId=${this.companionState.chatId}`),this.restoreScheduledTasks()):ce.warn("[COMPANION SCHEDULER] No state.json found (companion not registered yet), will keep checking"),ce.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);for(const[e,t]of this.cronJobs)t.stop(),ce.debug(`[COMPANION SCHEDULER] Stopped cron job: ${e}`);this.cronJobs.clear(),ce.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),ce.info("[COMPANION SCHEDULER] Cleared heartbeat task ID")}recordInteraction(e){if(!this.companionState?.chatId||e!==this.companionState.chatId)return;const t=(new Date).toISOString();this.saveStateField("lastInteractionTimestamp",t),ce.debug(`[COMPANION SCHEDULER] Recorded interaction at ${t}`)}loadState(){try{if(r(this.stateFilePath)){this.companionState=JSON.parse(c(this.stateFilePath,"utf-8"));const e=this.companionState?.heartbeatIntervalMs??9e5;e!==this.intervalMs&&(ce.info(`[COMPANION SCHEDULER] Interval changed: ${this.intervalMs}ms -> ${e}ms`),this.intervalMs=e),this.enabled=this.companionState?.heartbeatEnabled??!1,this.heartbeatTaskId=this.companionState?.heartbeatTaskId??null,ce.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){ce.warn("[COMPANION SCHEDULER] Failed to load state.json",e)}}saveStateField(e,t){try{let n={};r(this.stateFilePath)&&(n=JSON.parse(c(this.stateFilePath,"utf-8"))),void 0===t?delete n[e]:n[e]=t;const s=b(this.stateFilePath);r(s)||h(s,{recursive:!0}),p(this.stateFilePath,JSON.stringify(n,null,2),"utf-8"),ce.debug(`[COMPANION SCHEDULER] Saved state field: ${e}=${t??"removed"}`)}catch(t){ce.warn(`[COMPANION SCHEDULER] Failed to save state field: ${e}`,t)}}getTodayDateString(){const e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}addScheduledTask(e){const t={id:se(),...e,createdAt:(new Date).toISOString()};this.loadState();const n=this.companionState?.scheduledTasks??[];return n.push(t),this.saveStateField("scheduledTasks",n),this.startCronJob(t),ce.info(`[COMPANION SCHEDULER] Added scheduled task: id=${t.id}, type=${t.type}, task="${t.task}"`),t}listScheduledTasks(){return this.loadState(),this.companionState?.scheduledTasks??[]}deleteScheduledTask(e){this.loadState();const t=this.companionState?.scheduledTasks??[],n=t.findIndex(t=>t.id===e);if(-1===n)return!1;t.splice(n,1),this.saveStateField("scheduledTasks",t);const s=this.cronJobs.get(e);return s&&(s.stop(),this.cronJobs.delete(e)),ce.info(`[COMPANION SCHEDULER] Deleted scheduled task: id=${e}`),!0}startCronJob(e){try{const t={},n="utc"===e.timeType;let s;if(e.due){if(n){const n=new Date(e.due);s=`${n.getUTCMinutes()} ${n.getUTCHours()} ${n.getUTCDate()} ${n.getUTCMonth()+1} *`,t.timezone="Etc/UTC"}else{const n=e.due.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);if(!n)return void ce.warn(`[COMPANION SCHEDULER] Cannot parse due date: ${e.due}, skipping: ${e.id}`);s=`${parseInt(n[5])} ${parseInt(n[4])} ${parseInt(n[3])} ${parseInt(n[2])} *`,e.timezone&&(t.timezone=e.timezone)}"once"===e.type&&(t.maxRuns=1)}else{if(!e.cron)return void ce.warn(`[COMPANION SCHEDULER] Invalid task entry, skipping: ${e.id}`);s=e.cron,n?t.timezone="Etc/UTC":e.timezone&&(t.timezone=e.timezone)}const a=new rt(s,t,()=>{this.onScheduledTaskFired(e)});this.cronJobs.set(e.id,a),ce.debug(`[COMPANION SCHEDULER] Started cron job: id=${e.id}, pattern="${s}"`)}catch(t){ce.warn(`[COMPANION SCHEDULER] Failed to start cron job for task ${e.id}`,t)}}onScheduledTaskFired(e){ce.info(`[COMPANION SCHEDULER] Scheduled task fired: id=${e.id}, task="${e.task}"`),this.loadState();const t=this.companionState;t?.chatId&&(this.client.send("task-message",{eventId:N(),taskId:t.chatId,chatId:t.chatId,from:"machine",message:{type:"companion_reminder",content:`Scheduled task due: ${e.task}`,timestamp:(new Date).toISOString()},senderType:"system",senderId:"system",senderName:"system"}),"once"===e.type&&this.deleteScheduledTask(e.id))}restoreScheduledTasks(){const e=this.companionState?.scheduledTasks??[];if(0===e.length)return;let t=0;for(const n of e)"once"===n.type&&n.due&&new Date(n.due).getTime()<Date.now()?ce.debug(`[COMPANION SCHEDULER] Skipping expired one-time task: ${n.id}`):(this.startCronJob(n),t++);ce.info(`[COMPANION SCHEDULER] Restored ${t}/${e.length} scheduled tasks`)}tick(){if(this.loadState(),!this.companionState)return void ce.debug("[COMPANION SCHEDULER] Still no state.json, skipping heartbeat");if(!this.enabled)return void ce.debug("[COMPANION SCHEDULER] Heartbeat disabled, skipping");const e=this.companionState,t=[];e.lastInteractionTimestamp&&(!e.lastHeartbeatTimestamp||new Date(e.lastInteractionTimestamp).getTime()>new Date(e.lastHeartbeatTimestamp).getTime())&&t.push("new_interaction");const n=this.getTodayDateString();if(e.lastHeartbeatDate!==n&&t.push("first_today"),0===t.length)return void ce.debug("[COMPANION SCHEDULER] No trigger conditions met, skipping heartbeat");ce.info(`[COMPANION SCHEDULER] Heartbeat triggered: ${t.join(", ")}`);const s=new Date;this.saveStateField("lastHeartbeatTimestamp",s.toISOString()),this.saveStateField("lastHeartbeatDate",n);const a=s.toLocaleString();this.heartbeatTaskId?(ce.debug(`[COMPANION SCHEDULER] Sending heartbeat to existing task ${this.heartbeatTaskId}`),this.client.send("task-message",{eventId:N(),taskId:this.heartbeatTaskId,chatId:e.chatId,from:"machine",message:{type:"companion_heartbeat",timestamp:s.toISOString(),triggerTime:a,triggerReasons:t},senderType:"system",senderId:"system",senderName:"system"})):(ce.debug("[COMPANION SCHEDULER] Requesting new heartbeat task"),this.client.send("request-companion-heartbeat",{eventId:N(),machineId:e.machineId,agentId:e.agentId,chatId:e.chatId,userId:e.userId,timestamp:s.toISOString(),triggerTime:a,triggerReasons:t}))}}class ra{constructor(e,t){this.client=e,this.machineId=t;const n=re.agentrixAgentsHomeDir,s=y(n,"companion"),a=y(s,"claude");this.bootstrapPath=y(a,"BOOTSTRAP.md"),this.countPath=y(s,"BOOTSTRAP.count"),this.stateFilePath=y(a,"state.json")}timer=null;intervalMs=18e4;maxAttempts=10;bootstrapPath;countPath;stateFilePath;start(){r(this.bootstrapPath)?this.readCount()>=this.maxAttempts?ce.warn(`[COMPANION BOOTSTRAP] Already reached max attempts (${this.maxAttempts}), not starting watcher`):(ce.info("[COMPANION BOOTSTRAP] BOOTSTRAP.md exists, starting watcher"),this.scheduleNext()):ce.debug("[COMPANION BOOTSTRAP] BOOTSTRAP.md not found, companion already initialized")}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null)}scheduleNext(){this.timer=setTimeout(()=>this.tick(),this.intervalMs)}tick(){if(!r(this.bootstrapPath))return void ce.info("[COMPANION BOOTSTRAP] BOOTSTRAP.md removed, companion init complete");const e=this.readCount();if(e>=this.maxAttempts)return void ce.warn(`[COMPANION BOOTSTRAP] Max attempts (${this.maxAttempts}) reached, giving up`);const t=this.loadState();if(!t)return ce.warn("[COMPANION BOOTSTRAP] No state.json available, will retry next interval"),void this.scheduleNext();this.writeCount(e+1),ce.info(`[COMPANION BOOTSTRAP] Sending init request (attempt ${e+1}/${this.maxAttempts})`),this.client.send("request-companion-init",{eventId:N(),machineId:t.machineId,agentId:t.agentId,chatId:t.chatId,userId:t.userId}),this.scheduleNext()}readCount(){try{if(r(this.countPath)){const e=parseInt(c(this.countPath,"utf-8").trim(),10);return isNaN(e)?0:e}}catch{}return 0}writeCount(e){try{p(this.countPath,String(e),"utf-8")}catch(e){ce.warn("[COMPANION BOOTSTRAP] Failed to write BOOTSTRAP.count:",e)}}loadState(){try{if(r(this.stateFilePath)){const e=JSON.parse(c(this.stateFilePath,"utf-8"));if(e?.agentId&&e?.machineId&&e?.userId&&e?.chatId)return e}}catch{}return null}}async function ca(){Object.assign(ce,de({type:"daemon"}));const{requestShutdown:e,shutdownPromise:t}=function(){const{processType:e,onShutdownRequest:t}={processType:"daemon"},n=`[${e.toUpperCase()}]`;let s;const a=new Promise(e=>{s=(s,a)=>{ce.info(`${n} Requesting shutdown (source: ${s}, errorMessage: ${a})`),t&&t(s,a),setTimeout(()=>process.exit(1),1e3),e({source:s,errorMessage:a})}}),i=e=>{process.on(e,()=>{s("os-signal")})};return i("SIGINT"),i("SIGTERM"),process.on("uncaughtException",e=>{ce.info(`${n} FATAL: Uncaught exception`,e),ce.info(`${n} Stack trace: ${e.stack}`),s("exception",e.message)}),process.on("unhandledRejection",e=>{ce.info(`${n} FATAL: Unhandled promise rejection`,e);const t=e instanceof Error?e:new Error(`Unhandled promise rejection: ${e}`);ce.info(`${n} Stack trace: ${t.stack}`),s("exception",t.message)}),process.on("exit",e=>{ce.info(`${n} Process exiting with code: ${e}`)}),{requestShutdown:s,shutdownPromise:a}}();console.log("[DAEMON RUN] Starting daemon process..."),ce.debug("[DAEMON RUN] Environment",jn()),await At()&&(console.log("Daemon already running..."),process.exit(0));let n=await re.acquireDaemonLock(5,200);for(;!n;)await $t(),n=await re.acquireDaemonLock(5,200),n||(ce.debug("[DAEMON RUN] cannot acquire daemon lock..."),process.exit(1));try{(function(){if(re.disableCaffeinate)return ce.debug("[caffeinate] Caffeinate disabled via AGENTRIX_DISABLE_CAFFEINATE environment variable"),!1;if("darwin"!==process.platform)return ce.debug("[caffeinate] Not on macOS, skipping caffeinate"),!1;if(_n&&!_n.killed)return ce.debug("[caffeinate] Caffeinate already running"),!0;try{return _n=Ne("caffeinate",["-im"],{stdio:"ignore",detached:!1}),_n.on("error",e=>{ce.debug("[caffeinate] Error starting caffeinate:",e),_n=null}),_n.on("exit",(e,t)=>{ce.debug(`[caffeinate] Process exited with code ${e}, signal ${t}`),_n=null}),ce.info(`[caffeinate] Started with PID ${_n.pid}`),function(){if(Rn)return;Rn=!0;const e=()=>{Mn()};process.on("exit",e),process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGUSR1",e),process.on("SIGUSR2",e),process.on("uncaughtException",t=>{ce.debug("[caffeinate] Uncaught exception, cleaning up:",t),e()}),process.on("unhandledRejection",(t,n)=>{ce.debug("[caffeinate] Unhandled rejection, cleaning up:",t),e()})}(),!0}catch(e){return ce.info("[caffeinate] Failed to start caffeinate:",e),!1}})()&&ce.debug("[DAEMON RUN] Sleep prevention enabled");const s=await Rt();ce.debug("[DAEMON RUN] Auth and machine setup complete");const a=new ia;await a.initialize(re.getSandboxSettings());const i=new aa(a);let o,r;const{port:c,host:l,webhookHost:p,stop:d}=await Vs({getChildren:()=>i.getCurrentSessions(),stopSession:e=>i.stopSession(e),requestShutdown:()=>e("agentrix-cli"),registerSession:(e,t)=>i.registerTaskWorker(e,t),getSocketClient:()=>o?.client,credentials:s,get companionScheduler(){return r}});try{await Hn(),ce.debug("[DAEMON RUN] Openers detected")}catch(e){ce.warn("[DAEMON RUN] Failed to detect openers",e)}const u={pid:process.pid,port:c,host:l,webhookHost:p,startTime:(new Date).toLocaleString(),cliVersion:pe.version,logPath:ue({type:"daemon"})};re.writeDaemonState(u),ce.debug("[DAEMON RUN] Daemon state written");const m=new $n({machineId:s.machineId,serverUrl:re.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:W(s.token,s.machineId),keepAliveConfig:{intervalMs:2e4,event:"machine-alive",payloadGenerator:()=>({eventId:N(),machineId:s.machineId,timestamp:Date.now().toString(),controlPort:c})},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...t)=>ce.debug(`[DAEMON SOCKET] ${e}`,...t)},i,{requestShutdown:e});await m.connect(),o=m,ce.info("[DAEMON RUN] Machine client connected to server");const h=new oa(m.client,s.machineId);r=h,h.start(),m.setCompanionInteractionCallback(e=>{h.recordInteraction(e)});const g=new ra(m.client,s.machineId);g.start(),m.client.onEvent("companion-heartbeat-response",e=>{e?.taskId&&h.setHeartbeatTaskId(e.taskId)});const f=async(e,t)=>{h.stop(),g.stop(),await m.disconnect(),await d(),await a.shutdown(),await Ct(),await Mn(),await re.releaseDaemonLock(n),ce.info("[DAEMON RUN] Cleanup completed, exiting process"),process.exit(0)};ce.info("[DAEMON RUN] Daemon started successfully, waiting for shutdown request");const v=await t;await f(v.source,v.errorMessage)}catch(e){(function(e){return e instanceof Error&&e.message.includes("Machine binding revoked")})(e)&&(console.error("Machine binding is no longer valid."),console.error("Run `agentrix logout` and bind this machine again.")),ce.info("[DAEMON RUN][FATAL] Failed somewhere unexpectedly - exiting with code 1",e),process.exit(1)}}const la="\n\n[Tool result truncated to 1024 bytes]";function pa(e,t=1024){if(Buffer.byteLength(e,"utf8")<=t)return e;const n=Buffer.byteLength(la,"utf8");return n>t?ua(la,t):`${ua(e,t-n)}${la}`}function da(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function ua(e,t){let n="",s=0;for(const a of e){const e=Buffer.byteLength(a,"utf8");if(s+e>t)break;n+=a,s+=e}return n}const ma={senderType:"system",senderId:"system",senderName:"system"};class ha{client;context;historyDb;getPermissionMode;outbox=new Map;usageOutbox=new Map;hasConnectedOnce=!1;constructor(e,t){const{taskId:n,userId:s,machineId:a,cwd:i,chatId:o,...r}=e,c=i.endsWith("/")?i:`${i}/`;this.client=new Nt(r),this.context={taskId:n,chatId:o,userId:s,machineId:a,cwd:c,stopTask:t.stopTask,shouldPersistTaskMessage:t.shouldPersistTaskMessage,onTaskMessage:t.onTaskMessage,onTaskInfoUpdate:t.onTaskInfoUpdate,onWorkerStatusRequest:t.onWorkerStatusRequest,onSubTaskResultUpdated:t.onSubTaskResultUpdated,onSubTaskAskUser:t.onSubTaskAskUser,onGitPush:t.onGitPush,dataEncryptionKey:e.dataEncryptionKey,attachmentsDir:t.attachmentsDir,noVision:t.noVision,logger:t.logger},this.historyDb=t.historyDb,this.getPermissionMode=t.getPermissionMode,this.initHandlers()}getPermissionModeSnapshot(){return this.getPermissionMode?.()??null}connect(){return new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("Worker connection timeout after 10 seconds"))},1e4);this.client.onLifecycle("connect",()=>{clearTimeout(n),e()}),this.client.onLifecycle("connect_error",e=>{clearTimeout(n),t(e)}),this.client.connect()})}async disconnect(){this.client.connected&&await this.client.flush(5e3).catch(()=>{}),this.client.disconnect()}sendTaskMessage(e,t,n){const s=N();return this.historyDb.saveMessage({eventId:s,message:t,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}),this.sendTaskEvent(e,t,n),s}sendWorkerInitializing(e){const t={eventId:N(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),cwd:this.context.cwd,...void 0!==e?.deployingAgent&&{deployingAgent:e.deployingAgent},...void 0!==e?.upgradingAgent&&{upgradingAgent:e.upgradingAgent}};this.client.send("worker-initializing",t)}sendWorkerInitialized(){const e={eventId:N(),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 t=this.getPermissionModeSnapshot(),n={eventId:N(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),...void 0!==e&&{duration:e},...null!==t&&{permissionMode:t}};this.client.send("worker-ready",n)}sendWorkRunning(e){const t=this.getPermissionModeSnapshot(),n={eventId:N(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),activeAgents:e,...null!==t&&{permissionMode:t}};this.client.send("worker-running",n)}sendPermissionMode(e){const t={eventId:N(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),permissionMode:e};this.client.send("worker-permission-mode",t)}sendWorkerExit(e){const t={eventId:N(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),reason:e};this.client.send("worker-exit",t)}async sendErrorMessageAndExit(e){this.sendTerminalErrorResult(e),await this.client.flush(2e3),this.sendWorkerExit("error"),await this.disconnect()}sendTerminalErrorResult(e,t){this.sendSystemErrorMessage(e,t),this.sendTaskEvent(ma,function(e){return{type:"result",subtype:"error_during_execution",duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,total_cost_usd:0,usage:{input_tokens:0,output_tokens:0,cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},cache_creation_input_tokens:0,cache_read_input_tokens:0,server_tool_use:{web_fetch_requests:0,web_search_requests:0},service_tier:"standard"},modelUsage:{},permission_denials:[],errors:[e],uuid:crypto.randomUUID(),session_id:""}}(e),{groupId:t?.groupId})}sendSystemErrorMessage(e,t){const n={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(ma,n,{groupId:t?.groupId})}sendAssistantMessage(e,t){const n={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:e}]}};this.sendTaskEvent(ma,n,{groupId:t?.groupId})}sendAskUser(e,t,n){return this.sendTaskMessage(e,{type:"ask_user",questions:t},{groupId:n?.groupId})}sendAskUserResponse(e,t){return this.sendTaskMessage(ma,t,{opCode:e})}sendTaskEvent(e,t,n){const s=function(e,t=1024){const n=e,s=n?.message?.content;if(!Array.isArray(s))return e;let a=!1;const i=s.map(e=>{if("tool_result"!==e?.type||!("content"in e))return e;const n=function(e,t=1024){if("string"==typeof e)return pa(e,t);const n=da(e);return Buffer.byteLength(n,"utf8")<=t?e:Array.isArray(e)?pa(e.map(e=>{return"object"==typeof(t=e)&&null!==t&&"text"in t&&"string"==typeof t.text?e.text:da(e);var t}).join("\n"),t):pa(n,t)}(e.content,t);return n===e.content?e:(a=!0,{...e,content:n})});return a?{...n,message:{...n.message,content:i}}:e}(t),{eventId:a,opCode:i,artifacts:o,navigateToTaskId:r}=n||{},c=a??N(),l={eventId:c,taskId:this.context.taskId,chatId:this.context.chatId,from:"worker",messageType:s.type,message:s,encryptedMessage:void 0,opCode:i,groupId:n?.groupId,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,artifacts:o,navigateToTaskId:r};this.historyDb.saveTaskEvent({eventType:"task-message",eventId:c,eventData:l,taskId:this.context.taskId,chatId:this.context.chatId,sequence:"number"==typeof l.sequence?l.sequence:null});const p=this.buildTaskUsageReport(s,c);if(this.context.dataEncryptionKey){const e=F(s,this.context.dataEncryptionKey);l.message=void 0,l.encryptedMessage=e}return this.outbox.set(c,l),p&&(this.usageOutbox.set(c,p),this.client.send("task-usage-report",p)),this.client.send("task-message",l),c}buildTaskUsageReport(e,t){if("result"!==e.type)return null;const n=e.modelUsage;if(!n||"object"!=typeof n)return null;const s={};for(const[e,t]of Object.entries(n)){if(!e||!t||"object"!=typeof t)continue;const n=t,a={inputTokens:this.normalizeUsageCount(n.inputTokens),outputTokens:this.normalizeUsageCount(n.outputTokens),cacheReadInputTokens:this.normalizeUsageCount(n.cacheReadInputTokens),cacheCreationInputTokens:this.normalizeUsageCount(n.cacheCreationInputTokens),webSearchRequests:this.normalizeUsageCount(n.webSearchRequests)};Object.values(a).some(e=>e>0)&&(s[e]=a)}return 0===Object.keys(s).length?null:{eventId:N(),taskId:this.context.taskId,resultEventId:t,modelUsage:s}}normalizeUsageCount(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.trunc(e)}sendUpdateTaskAgentSessionId(e){const t={eventId:N(),taskId:this.context.taskId,agentSessionId:e,cwd:this.context.cwd};this.client.send("update-task-agent-session-id",t)}sendTaskSlashCommandsUpdate(e,t){const n={eventId:N(),taskId:this.context.taskId,commands:e,version:t,updatedAt:(new Date).toISOString()};this.client.send("task-slash-commands-update",n)}sendChangeTaskTitle(e){const t={eventId:N(),taskId:this.context.taskId,title:e};this.client.send("change-task-title",t),ce.info(`[AGENT] Title changed to: ${e}`)}sendUpdateAgentInfo(e,t){const n={eventId:N(),taskId:this.context.taskId,agentId:e,...t};this.client.send("update-agent-info",n),ce.info(`[AGENT] Agent info updated: ${JSON.stringify(t)}`)}sendResetTaskSession(){const e={eventId:N(),taskId:this.context.taskId};this.client.send("reset-task-session",e),ce.info(`[AGENT] Session reset requested for task ${this.context.taskId}`)}async sendMergeRequest(e,t){const n={eventId:N(),taskId:this.context.taskId,summary:e,description:t};ce.info(`[MERGE] Sending merge-request event for task ${this.context.taskId}`);const s=await this.client.sendWithAck("merge-request",n);if(!s.success)throw new Error(`Failed to create pull request: ${s.error||"Unknown error"}`);return ce.info(`[MERGE] Pull request created: #${s.data.pullRequestNumber}`),{pullRequestNumber:s.data.pullRequestNumber,pullRequestUrl:s.data.pullRequestUrl}}async sendMergePr(){const e={eventId:N(),taskId:this.context.taskId,mergeMethod:"squash"};return ce.info(`[MERGE-PR] Sending merge-pr event for task ${this.context.taskId}`),await this.client.sendWithAck("merge-pr",e)}associateRepository(e,t,n,s){const a={eventId:N(),taskId:this.context.taskId,gitServerHost:e,owner:t,repo:n,remoteUrl:s};ce.info(`[REPO] Sending repository association request: ${e}/${t}/${n}`),this.client.send("associate-repo",a)}async dispatchTaskMessage(e){await this.context.onTaskMessage(e)}sendEventAck(e){this.client.send("event-ack",{eventId:N(),status:"success",opCode:e})}initHandlers(){const e=(t=this.context,n=this.historyDb,s=e=>{this.sendEventAck(e)},{"cancel-task":async e=>{e.taskId===t.taskId&&(ce.info(`[WORKER] Task ${t.taskId} cancelled`),await t.stopTask())},"stop-task":async e=>{e.taskId===t.taskId&&(ce.info(`[WORKER] Task ${t.taskId} stopped: ${e.reason||"no reason"}`),await t.stopTask())},"task-message":async e=>{if(e.taskId!==t.taskId)return;let a=e.message??null;if(!a&&e.encryptedMessage&&t.dataEncryptionKey&&(a=H(e.encryptedMessage,t.dataEncryptionKey)??null),!a)return;const i={senderType:e.senderType,senderId:e.senderId,senderName:e.senderName};if(t.attachmentsDir&&G(a)&&(a=await sa(a,{attachmentsDir:t.attachmentsDir,log:t.logger})),t.shouldPersistTaskMessage&&!await t.shouldPersistTaskMessage(a,i))return void ce.debug(`[WORKER] Dropping incoming task-message before persistence: eventId=${e.eventId}`);if(!n.saveMessage({eventId:e.eventId,message:a,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}).inserted)return ce.debug(`[WORKER] Ignoring duplicate incoming task-message: eventId=${e.eventId}`),void s(e.eventId);const o={...e,message:a,encryptedMessage:void 0,chatId:e.chatId??t.chatId};n.saveTaskEvent({eventType:"task-message",eventId:e.eventId,eventData:o,taskId:t.taskId,chatId:e.chatId??t.chatId,sequence:e.sequence??null}),s(e.eventId),t.onTaskMessage&&await t.onTaskMessage(a,i)},"task-info-update":async e=>{e.taskId===t.taskId&&t.onTaskInfoUpdate&&await t.onTaskInfoUpdate(e)},"worker-status-request":async e=>{e.taskId===t.taskId&&t.onWorkerStatusRequest&&await t.onWorkerStatusRequest(e)},"sub-task-result-updated":async e=>{e.parentTaskId===t.taskId&&t.onSubTaskResultUpdated&&await t.onSubTaskResultUpdated(e)},"sub-task-ask-user":async e=>{e.parentTaskId===t.taskId&&t.onSubTaskAskUser&&await t.onSubTaskAskUser(e)}});var t,n,s;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("sub-task-ask-user",e["sub-task-ask-user"]),this.client.onEvent("event-ack",e=>{const t=e.data?.sequence;void 0!==e.opCode&&(this.outbox.delete(e.opCode),this.usageOutbox.delete(e.opCode)),void 0!==e.opCode&&"number"==typeof t&&this.historyDb.updateTaskEventSequence(e.opCode,t)}),this.client.onLifecycle("connect",()=>{if(this.hasConnectedOnce){if(this.outbox.size>0){ce.info(`[WORKER] Reconnected — flushing ${this.outbox.size} outbox message(s)`);for(const[e,t]of this.outbox.entries()){const n=this.usageOutbox.get(e);n&&this.client.send("task-usage-report",n),this.client.send("task-message",t)}}}else this.hasConnectedOnce=!0})}}class ga{logger;socketClient;taskId;userId;chatId;rootTaskId;parentTaskId;workingDirectory;taskAgents;serverUrl;taskDataKey;agentHomeDir;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.agentHomeDir=e.agentHomeDir,this.taskAgents=e.taskAgents,this.serverUrl=e.serverUrl,this.taskDataKey=e.taskDataKey}async call(e,t,n){const s=N();try{const a=await this.socketClient.sendWithAck("rpc-call",{eventId:s,taskId:this.taskId,method:e,path:t,query:n?.query,body:n?.body});if(!a.success){const n=a.error||{code:"unknown",message:"Unknown error"};throw new Error(`RPC ${e} ${t} failed: ${n.message} (${n.code})`)}return a.data}catch(n){throw new Error(`RPC ${e} ${t} error: ${n.message}`)}}log(e){this.logger.info(e)}getWorkspace(){return this.workingDirectory}getAgentHomeDir(){return this.agentHomeDir}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,t){return this.call("PATCH",`/v1/draft-agent/${e}`,{body:t})}async startSubTask(e){const t={userId:this.userId,chatId:this.chatId,agentId:e.agentId,parentTaskId:this.taskId,customTitle:e.title,cwd:e.cwd,forceUserCwd:e.forceUserCwd};return this.taskDataKey?t.encryptedMessage=F(e.message,this.taskDataKey):t.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:t})).taskId}}async startIndependentTask(e){const t={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?t.encryptedMessage=F(e.message,this.taskDataKey):t.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:t})).taskId}}async startGroupTask(e){const t={userId:this.userId,chatId:e.chatId??this.chatId,parentTaskId:this.taskId,customTitle:e.title,todos:e.todos};return this.taskDataKey?t.encryptedMessage=F(e.message,this.taskDataKey):t.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:t})).taskId}}async createGroupChat(e){return this.call("POST","/v1/agent-group-chats",{body:{agentIds:e}})}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 t=await this.call("GET","/v1/tasks/find-by-agent",{query:{parentTaskId:this.taskId,agentId:e}});return t.taskId?{taskId:t.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 t=await ge.promises.stat(e.path);this.logger.info("[Agent-Context] file stats");const n=t.size,s=e.contentType||Wt.lookup(e.name)||"application/octet-stream",a=(await this.call("POST","/v1/files/upload-urls",{body:{count:1}})).files[0],i=a.url;this.logger.info(`[Agent-Context] FileUploadUrl: ${i}`);const o=await ge.promises.readFile(e.path),r=await fetch(i,{method:"PUT",headers:{"Content-Type":s},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:a.id,name:e.name,size:n,contentType:s,visibility:e.visibility||"private"}}),c="public"===e.visibility?`${this.serverUrl}/v1/files/public/${a.id}`:i.split("?")[0],{fileId:a.id,name:e.name,size:n,contentType:s,url:c}}}function fa(e,t){const n=e.split("\n");return n.length<=t?e:n.slice(0,t).join("\n")+"..."}function va(e,t){let n=e.resultMessage;if(0===n.result.trim().length&&e.encryptedResultMessage&&t){const s=H(e.encryptedResultMessage,t);s&&"result"===s.type&&(n={type:"result",result:"result"in s?s.result:"",is_error:s.is_error})}const s={...e,resultMessage:{...n,result:fa(n.result,3)}};let a=`<sub-task-result-updated>\n${JSON.stringify(s,null,2)}\n</sub-task-result-updated>`;return a+=n.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:a}}}function xa(e,t){let n=e.message;if(!n&&e.encryptedMessage&&t){const s=H(e.encryptedMessage,t);s&&"ask_user"===s.type&&(n=s)}return{type:"user",message:{role:"user",content:`<sub-task-ask-user>\n${JSON.stringify({taskId:e.taskId,agentId:e.agentId,agentName:e.agentName,taskName:e.taskName,questions:n?.questions??[]},null,2)}\n</sub-task-ask-user>\n<system-reminder>A sub-task agent is asking the user questions. You should answer these questions on behalf of the user based on the task context and instructions. Use the reply_to_sub_task tool to send your answers back.</system-reminder>`}}}function ya(){const e=new Set;return{filter(t){const n=t;if(!n.message||!n.message.content||"string"==typeof n.message.content)return t;const s=n.message.content.filter(t=>!("tool_result"===t.type&&e.has(t.tool_use_id)||"user"===n.type&&"tool_result"!==t.type));return 0===s.length?null:(n.message.content=s,n)},clear(){e.clear()}}}function ba(e){const t=Ea(e);return t?{type:"user",message:{role:"user",content:[{type:"text",text:`<msg ${ka({seq:t.seq.toString(),at:t.at,senderType:t.senderType??void 0,senderId:t.senderId??void 0,senderName:t.senderName??void 0})}>${t.text}</msg>\n`},...t.nonTextBlocks]},parent_tool_use_id:null,session_id:""}:null}function wa(e){const t=Ea(e);return t?`<msg ${ka({seq:t.seq.toString(),at:t.at,senderType:t.senderType??void 0,senderId:t.senderId??void 0,senderName:t.senderName??void 0})}>\n${t.text}\n</msg>`:null}function ka(e){return Object.entries(e).filter(([,e])=>void 0!==e&&""!==e).map(([e,t])=>`${e}="${function(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}(t)}"`).join(" ")}function Ia(e){const t=[];for(const n of e){const e=wa(n);e&&t.push(e)}return t.join("\n")}function Sa(e){return`Ask user: ${e.questions.map((e,t)=>{const n=e.options?.map(e=>e.label).filter(Boolean),s=n&&n.length>0?` options: ${n.join(", ")}`:"";return`Q${t+1}[${e.header}] ${e.question}${s}`}).join(" | ")}`}function Ta(e){const t=e.status?` status=${e.status}`:"",n=e.reason?` reason=${e.reason}`:"",s=e.answers?.length?e.answers.join(", "):"no answers",a=e.details?.filter(Boolean).join(" | ");return`Ask user response:${t}${n} answers: ${s}${a?` details: ${a}`:""}`}function Ea(e){const{text:t,nonTextBlocks:n}=(s=e.message,B(s)?{text:Sa(s),nonTextBlocks:[]}:z(s)?{text:Ta(s),nonTextBlocks:[]}:K(s)?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 t=[],n=[];for(const s of e)"text"!==s.type||"string"!=typeof s.text?n.push(s):t.push(s.text);return{text:t.join("\n"),nonTextBlocks:n}}return{text:"",nonTextBlocks:[]}}(e.message.content);case"result":return"success"===e.subtype?{text:e.result,nonTextBlocks:[]}:{text:Array.isArray(e.errors)?e.errors.filter(e=>"string"==typeof e).join("\n").trim():"",nonTextBlocks:[]}}return{text:"",nonTextBlocks:[]}}(s):{text:"",nonTextBlocks:[]});var s;return t?{seq:e.localSequence,at:e.createdAt,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,text:t,nonTextBlocks:n}:null}function Aa({workClient:e}){return Ye("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:Ge.string().describe("New title for the task")},async t=>(e.sendChangeTaskTitle(t.title),{content:[{type:"text",text:`Task title updated to: ${t.title}`}]}))}function Ca({agentContext:e,log:t}){return Ye("emit_to_task","Send a message to a sub-task. Use this to:\n1. Answer a sub-task's ask_user questions: set answers array (one answer per question).\n2. Send follow-up instructions: set instructions only (no answers).",{taskId:Ge.string().describe("Sub-task ID to send the message to"),instructions:Ge.string().optional().describe("Follow-up instructions for the sub-task (used when not answering ask_user)"),answers:Ge.array(Ge.string()).optional().describe("Answers to the sub-task ask_user questions, one per question. When provided, sends as ask_user_response.")},async n=>{try{let t;return t=n.answers&&n.answers.length>0?{type:"ask_user_response",answers:n.answers}:{type:"user",message:{role:"user",content:n.instructions??""}},await e.sendMessage({taskId:n.taskId,message:t,target:"agent"}),{content:[{type:"text",text:`${n.answers?"Sent ask_user response":"Sent follow-up instructions"} to sub-task ${n.taskId}.`}]}}catch(e){return t("error","TASK",`Failed to send message to sub-task ${n.taskId}:`,e),{content:[{type:"text",text:`Failed to send message to sub-task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function $a({historyDb:e}){return Ye("get_task_history","Retrieve earlier task history stored locally for additional context.",{sequence:Ge.number().int().describe("Return messages before this local sequence (exclusive)."),limit:Ge.number().int().min(1).max(50).default(20).describe("Maximum number of messages to return.")},async t=>{const n=t.limit??20,s=e.pageMessagesBefore(t.sequence,n);return 0===s.data.length?{content:[{type:"text",text:"No earlier messages found."}]}:{content:[{type:"text",text:Ia(s.data)}]}})}function _a({agentContext:e}){return Ye("get_task_agents","List the agents available for the current task and return taskAgents info.",{},async()=>{const t=e.getTaskAgents();return t.length?{content:[{type:"text",text:JSON.stringify(t,null,2)}]}:{content:[{type:"text",text:"No task agents available."}]}})}function Pa({agentContext:e,log:t}){return Ye("list_sub_task","List direct sub tasks for the current task with taskId, title, and cwd.",{},async()=>{try{const t=await e.listSubTasks();return t.length?{content:[{type:"text",text:JSON.stringify(t,null,2)}]}:{content:[{type:"text",text:"No sub tasks found."}]}}catch(e){return t("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 Ma({agentContext:e,agentId:t,log:n,setPendingNavigateTaskId:s}){return Ye("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:Ge.string().optional().describe('Target agent ID (e.g., "agent-poster-generator"). If not provided, uses current agent.'),title:Ge.string().min(1).max(200).describe("Task title for the agent to use (required)"),instructions:Ge.string().describe("Detailed instructions for the agent. Be specific about what needs to be done."),briefSummary:Ge.string().describe('One-line summary shown to user immediately (e.g., "Creating login page")'),cwd:Ge.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:Ge.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place)."),independent:Ge.boolean().optional().describe("Create as independent top-level task (no parent). Defaults to false (sub-task mode)."),autoNavigate:Ge.boolean().optional().describe("Auto-switch App UI to this task after creation. Only works with independent=true. Defaults to false.")},async a=>{try{if(a.autoNavigate&&!a.independent)return{content:[{type:"text",text:"Error: autoNavigate can only be used with independent=true"}],isError:!0};const i=a.agentId||t;let o;return a.independent?(o=await e.startIndependentTask({agentId:i,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree,autoNavigate:a.autoNavigate}),a.autoNavigate&&s(o.taskId),n("info","TASK",`Created independent task ${o.taskId} for agent ${i} (autoNavigate: ${a.autoNavigate??!1})`)):(o=await e.startSubTask({agentId:i,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree}),n("info","TASK",`Created sub-task ${o.taskId} for agent ${i}`)),{content:[{type:"text",text:`🚀 Task created: ${o.taskId}\n${a.agentId?`Agent: ${i}\n`:""}${a.independent?"Mode: Independent\n":""}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","Failed to create task:",e),{content:[{type:"text",text:`Failed to create task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Ra({agentContext:e,log:t}){return Ye("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:Ge.string().min(1).max(200).describe("Task title"),instructions:Ge.string().describe("Instructions for the owner agent"),briefSummary:Ge.string().optional().describe("One-line summary shown to user immediately"),agentId:Ge.string().describe("Target agent ID"),cwd:Ge.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:Ge.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place).")},async n=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startSubTask({agentId:n.agentId,message:{type:"user",message:{role:"user",content:n.instructions}},title:n.title,cwd:n.cwd,forceUserCwd:!n.useWorktree})).taskId}\n${n.briefSummary?`Summary: ${n.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return t("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 Oa({agentContext:e,log:t,agentId:n}){return Ye("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:Ge.string().min(1).max(200).describe("Task title"),requirement:Ge.string().describe("Overall requirement"),briefSummary:Ge.string().optional().describe("One-line summary shown to user immediately"),todos:Ge.array(Ge.object({agentId:Ge.string().describe("Agent ID responsible for the todo"),title:Ge.string().min(1).max(200).describe("Todo title"),instructions:Ge.string().describe("Detailed instructions for this todo")})).min(1).describe("Todo list for agents")},async n=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startGroupTask({title:n.title,todos:n.todos,message:{type:"user",message:{role:"user",content:n.requirement}}})).taskId}\n${n.briefSummary?`Summary: ${n.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return t("error","DISPATCH","Dispatch failed:",e),{content:[{type:"text",text:`Dispatch failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Da({askUser:e,log:t}){return Ye("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:Ge.array(Ge.object({question:Ge.string().describe("The complete question to ask the user"),header:Ge.string().max(12).describe("Short label displayed as a chip/tag (max 12 chars)"),multiSelect:Ge.boolean().describe("Set to true to allow multiple option selections"),options:Ge.array(Ge.object({label:Ge.string().describe("Option label (1-5 words)"),description:Ge.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 n=>{try{const t=n.questions.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]})),s=await e(t);return"answered"!==(s.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${s.answers.map(e=>e.startsWith("other:")?`Other: "${e.slice(6)}"`:e).join("\n")}`}]}}catch(e){return t("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 Na({invokeAgent:e}){return Ye("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:Ge.string().describe("Target agent ID"),hint:Ge.string().optional().describe("Optional context/instruction for the agent")},async t=>(e(t.agentId,t.hint),{content:[{type:"text",text:`Invoked ${t.agentId}. The agent will respond in the chat later.`}]}))}function Ua({workClient:e,agentId:t,uploadFile:n,log:s}){return Ye("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:Ge.string().optional().describe("Your display name"),avatarPath:Ge.string().optional().describe("Local path to avatar image file (png/jpg/svg)"),signature:Ge.string().optional().describe("Short status line or tagline shown under your name")},async a=>{let i;if(a.avatarPath)try{i=(await n({name:"avatar.png",path:a.avatarPath,visibility:"public"})).fileId}catch(e){return s("error","TOOL","Avatar upload failed:",e),{content:[{type:"text",text:`Avatar upload failed: ${e}`}],isError:!0}}e.sendUpdateAgentInfo(t,{displayName:a.displayName,avatar:i,signature:a.signature});const o=[];return a.displayName&&o.push(`name → ${a.displayName}`),i&&o.push("avatar → uploaded"),a.signature&&o.push(`signature → ${a.signature}`),{content:[{type:"text",text:`Profile updated: ${o.join(", ")}`}]}})}function ja({assign:e,log:t}){return Ye("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:Ge.string().describe("Target agent ID"),instruction:Ge.string().describe("Task instruction for the agent"),acknowledgment:Ge.string().optional().describe('Agent\'s quick reply shown immediately (e.g., "starting now", "On it")')},async t=>(e(t.agentId,t.instruction,t.acknowledgment),{content:[{type:"text",text:`Assigned work to ${t.agentId}.`}]}))}function qa({agentContext:e,log:t}){return Ye("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:Ge.number().int().min(1).max(50).default(10).optional().describe("Maximum number of tasks to return (default 10)."),status:Ge.enum(["all","active","completed"]).default("all").optional().describe("Filter by task status: all, active, or completed.")},async n=>{try{const t=await e.listTasks({limit:n.limit??10,status:n.status??"all"});return t.length?{content:[{type:"text",text:JSON.stringify(t,null,2)}]}:{content:[{type:"text",text:"No tasks found."}]}}catch(e){return t("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 La({chatHistoryDb:e}){return Ye("read_conversation","Read recent messages from the main conversation between you and the user. Use this to review what was discussed recently.",{limit:Ge.number().int().min(1).max(200).default(50).optional().describe("Number of recent messages to return (default 50)."),before:Ge.number().int().optional().describe("Sequence number — return messages before this sequence for pagination.")},async t=>{if(!e)return{content:[{type:"text",text:"Chat history not available in this mode."}],isError:!0};const n=t.limit??50,s=null!=t.before?e.pageMessagesBefore(t.before,n):e.pageRecentMessages(n);if(0===s.data.length)return{content:[{type:"text",text:"No conversation messages found."}]};let a=Ia(s.data);return s.hasMore&&(a+=`\n\nMore messages available. Use before=${Math.min(...s.data.map(e=>e.localSequence))} to load earlier messages.`),{content:[{type:"text",text:a}]}})}function Ha({agentContext:e,log:t}){return Ye("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:Ge.string().describe('Brief reminder message (one sentence, e.g., "Heartbeat architecture discussion pending for 2 days, consider following up")'),filePath:Ge.string().optional().describe("Path to detailed analysis file in workspace, if any")},async n=>{try{const t=e.getChatId();return await e.sendMessage({taskId:t,message:{type:"companion_reminder",content:n.content,filePath:n.filePath,timestamp:(new Date).toISOString()},target:"agent"}),{content:[{type:"text",text:"Reminder sent to main companion."}]}}catch(e){return t("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 Ga({uploadFile:e,log:n}){return Ye("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., ).",{filePath:Ge.string().describe("Absolute path to the local file to upload"),name:Ge.string().optional().describe("Display name for the file (defaults to filename)")},async s=>{try{const n=t("path"),a=s.name||n.basename(s.filePath);return{content:[{type:"text",text:(await e({name:a,path:s.filePath,visibility:"public"})).url}]}}catch(e){return n("error","TOOL","File upload failed:",e),{content:[{type:"text",text:`File upload failed: ${e}`}],isError:!0}}})}function Wa({agentContext:e,log:t}){return Ye("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:t,draftAgents:n}=await e.listAgents(),s=e=>`- **${e.displayName||e.name}** (${e.id})\n Type: ${e.type}\n`+(e.developerName?` Developer: ${e.developerName}\n`:"")+` ${e.description||"No description"}\n`;let a="# Available Agents\n\n";return t.length>0&&(a+="## Published Agents\n\n",a+=t.map(s).join("\n")),n.length>0&&(a+="\n## Draft Agents\n\n",a+=n.map(s).join("\n")),0===t.length&&0===n.length&&(a+="No agents available."),{content:[{type:"text",text:a}]}}catch(e){return t("error","AGENTS","Failed to list agents:",e),{content:[{type:"text",text:`Failed to list agents: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}async function*Fa(e){yield e}function Ba({visionModel:e,log:t}){return Ye("analyze_image","Analyze a local image file and return a description of its contents.\nUse this tool when you need to understand the content of an image file on the local filesystem.\nThe primary model does not support vision, so this tool delegates to a vision-capable model.",{imagePath:Ge.string().describe("Absolute path to the image file to analyze"),prompt:Ge.string().optional().describe("Optional specific question or instruction about the image (default: describe the image)")},async n=>{if(!e)return{content:[{type:"text",text:"Vision analysis is not available (missing configuration)."}],isError:!0};try{const t=(await ct(n.imagePath)).toString("base64"),s={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp"}[n.imagePath.split(".").pop()?.toLowerCase()??"jpeg"]??"image/jpeg",a=n.prompt||"Describe this image in detail.",i=Je({prompt:Fa({type:"user",message:{role:"user",content:[{type:"image",source:{type:"base64",media_type:s,data:t}},{type:"text",text:a}]},parent_tool_use_id:null,session_id:""}),options:{model:e,permissionMode:"bypassPermissions",maxTurns:1,tools:[]}});let o="";for await(const e of i)if("result"===e.type){o=e.result??"";break}return{content:[{type:"text",text:o||"No description returned."}]}}catch(e){return t("error","VISION","Failed to analyze image:",e),{content:[{type:"text",text:`Failed to analyze image: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function za({log:e}){return Ye("schedule_task",'Create, list, or delete scheduled tasks (reminders and recurring jobs).\nTasks are managed by the daemon scheduler and fire as reminders to the main companion.\n\nUse action "create" to schedule a new task:\n- For one-time tasks: provide "due" (ISO 8601 timestamp)\n- For recurring tasks: provide "cron" (standard 5-field cron expression)\n- Set timeType to "utc" if the time is in UTC, or "local" (default) if in the user\'s timezone\n\nUse action "list" to see all scheduled tasks.\nUse action "delete" with an "id" to remove a task.',{action:Ge.enum(["create","list","delete"]).describe("Operation to perform"),task:Ge.string().optional().describe("Task description (required for create)"),type:Ge.enum(["once","recurring"]).optional().describe("Task type (required for create)"),due:Ge.string().optional().describe("ISO 8601 timestamp for one-time tasks"),cron:Ge.string().optional().describe('Cron expression for recurring tasks (e.g., "0 18 * * *")'),timezone:Ge.string().optional().describe('IANA timezone (e.g., Asia/Shanghai). Required when timeType is "local"'),timeType:Ge.enum(["utc","local"]).optional().describe('How to interpret time — "utc" for absolute UTC, "local" (default) for user timezone'),id:Ge.string().optional().describe("Task ID (required for delete)")},async t=>{try{const e=await re.readDaemonState();if(!e?.port)return{content:[{type:"text",text:"Daemon not running."}],isError:!0};const n=`http://127.0.0.1:${e.port}`;if("list"===t.action){const e=await fetch(`${n}/schedule`),t=await e.json();if(!e.ok)return{content:[{type:"text",text:`Error: ${t.error}`}],isError:!0};const s=t.tasks??[];return 0===s.length?{content:[{type:"text",text:"No scheduled tasks."}]}:{content:[{type:"text",text:s.map(e=>`- [${e.id}] ${"once"===e.type?`once at ${e.due}`:`recurring: ${e.cron}`} — "${e.task}"`).join("\n")}]}}if("create"===t.action){if(!t.task||!t.type)return{content:[{type:"text",text:"Missing required fields: task, type"}],isError:!0};const e=await fetch(`${n}/schedule`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({task:t.task,type:t.type,due:t.due,cron:t.cron,timezone:t.timezone,timeType:t.timeType})}),s=await e.json();if(!e.ok)return{content:[{type:"text",text:`Error: ${s.error}`}],isError:!0};const a="once"===s.type?`due=${s.due}`:`cron=${s.cron}`;return{content:[{type:"text",text:`Scheduled: id=${s.id}, ${a}`}]}}if("delete"===t.action){if(!t.id)return{content:[{type:"text",text:"Missing required field: id"}],isError:!0};const e=await fetch(`${n}/schedule/${t.id}`,{method:"DELETE"}),s=await e.json();return e.ok?{content:[{type:"text",text:`Deleted: ${t.id}`}]}:{content:[{type:"text",text:`Error: ${s.error}`}],isError:!0}}return{content:[{type:"text",text:`Unknown action: ${t.action}`}],isError:!0}}catch(t){return e("error","SCHEDULE","Schedule task failed:",t),{content:[{type:"text",text:`Failed: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}})}const Ka=pt(Ve);function Va(e){const t={baseDir:e,binary:"git",maxConcurrentProcesses:6,trimmed:!1};return"win32"===process.platform&&(t.spawnOptions={windowsHide:!0}),lt(t)}async function Xa(e){try{const t=Va(e);return await t.checkIsRepo()}catch{return!1}}async function Ja(e){const t=Va(e),n=(await t.raw(["worktree","list","--porcelain"])).trim().split("\n").filter(Boolean),s=[];let a=null;for(const e of n)if(e.startsWith("worktree "))a&&s.push(a),a={path:e.replace("worktree ","").trim(),branch:null,commit:"",isMain:0===s.length};else if(a)if(e.startsWith("HEAD "))a.commit=e.replace("HEAD ","").trim();else{if(e.startsWith("branch ")){const t=e.replace("branch ","").trim();a.branch=t.replace("refs/heads/","");continue}e.startsWith("detached")&&(a.branch=null)}return a&&s.push(a),s}async function Ya(e,t,n,s="HEAD"){const a=b(t);if(r(a)||h(a,{recursive:!0}),r(t)&&!ii(t))throw new Error(`Worktree directory already exists at ${t}`);const i=Va(e);await i.raw(["worktree","add","-b",n,t,s])}async function Qa(e,t,n=!1){const s=Va(e),a=["worktree","remove"];n&&a.push("--force"),a.push(t),await s.raw(a)}async function Za(e){const t=Va(e);await t.init()}async function ei(e){const t=Va(e);await t.add("."),await t.commit("Initial commit",{"--allow-empty":null})}async function ti(e,t,n){const s=Va(e);(await s.branchLocal()).all.includes(t)?await s.checkout(t):(n&&await s.checkout(n),await s.checkoutLocalBranch(t))}async function ni(e){const t=Va(e);return!(await t.status()).isClean()}async function si(e){const t=Va(e),n=await t.log({maxCount:1});if(!n.latest)throw new Error("No commits found in repository");return n.latest.hash}async function ai(e){try{const t=Va(e);return null!==(await t.log({maxCount:1})).latest}catch{return!1}}function ii(e){if(!r(e))return!0;const t=m(e);return 0===t.length||1===t.length&&".git"===t[0]}function oi(e){const t=e.match(/^(.*)?\{([^}]*) => ([^}]*)\}(.*)$/);if(!t)return e;const[,n="",,s,a=""]=t;return`${n}${s}${a}`}async function ri(e,t,n){const s=Va(e),a=await s.diffSummary([`${t}..${n}`]);return{totalInsertions:a.insertions,totalDeletions:a.deletions,files:a.files.map(e=>({path:oi(V(e.file)),insertions:"insertions"in e?e.insertions:0,deletions:"deletions"in e?e.deletions:0}))}}async function ci(e,t){try{const{stdout:n}=await Ka("git",t,{cwd:e,maxBuffer:10485760,windowsHide:!0});return n}catch(e){const t=e;if(1===t.code&&"string"==typeof t.stdout)return t.stdout;throw e}}function li(e){return e.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>function(e){const[t,n,s]=e.split("\t");if(!t||!n||!s)return null;const a="-"===t?0:Number.parseInt(t,10),i="-"===n?0:Number.parseInt(n,10);if(Number.isNaN(a)||Number.isNaN(i))return null;const o=s.startsWith("/dev/null => ")?s.slice(13):s;return{path:oi(V(o)),insertions:a,deletions:i}}(e)).filter(e=>null!==e)}function pi(e,t){return ie("sha256").update(`${e}\n${t}`).digest("hex")}async function di(e,t){const n=await ci(e,["diff","--binary","--find-renames",t,"--"]),s=li(await ci(e,["diff","--numstat","--find-renames",t,"--"])),a=await async function(e){const{stdout:t}=await Ka("git",["ls-files","--others","--exclude-standard","-z"],{cwd:e,maxBuffer:10485760,windowsHide:!0});return t.split("\0").filter(Boolean)}(e),i=await Promise.all(a.map(t=>ci(e,["diff","--no-index","--binary","--","/dev/null",t]))),o=li((await Promise.all(a.map(t=>ci(e,["diff","--no-index","--numstat","--","/dev/null",t])))).join("\n")),r=function(e){const t=e.trim();return t?`${t}\n`:""}([n,...i].filter(Boolean).join("\n"));return r?{patch:r,stats:{totalInsertions:(c=[...s,...o]).reduce((e,t)=>e+t.insertions,0),totalDeletions:c.reduce((e,t)=>e+t.deletions,0),files:c},artifactVersion:pi(t,r)}:null;var c}async function ui(e){const t=Va(e);return(await t.revparse(["--abbrev-ref","HEAD"])).trim()}async function mi(e,t,n){const s=Va(e);await s.remote(["set-url",t,n])}function hi(e){try{const t=new URL(e);return t.username="",t.password="",t.toString()}catch{return e}}async function gi(e,t,n){const s=Va(e),a=(await s.getRemotes(!0)).find(e=>e.name===t);a?a.refs.fetch!==n&&await mi(e,t,n):await s.addRemote(t,n)}function fi(e){const t=e.match(/^git@([^:]+):(.+)\/(.+?)(?:\.git)?$/);if(t){const[,n,s,a]=t;return{url:e,host:n.split("-")[0],owner:s,repo:a}}const n=e.match(/^https?:\/\/([^/]+)\/(.+)\/(.+?)(?:\.git)?$/);if(n){const[,t,s,a]=n;return{url:e,host:t,owner:s,repo:a}}return null}const vi="oauth2",xi="AGENTRIX_GIT_USERNAME",yi="AGENTRIX_GIT_PASSWORD";function bi(){const e=y(s(),`git-askpass-${se()}.sh`);return p(e,`#!/bin/sh\ncase "$1" in\n *Username*|*username*) printf '%s\\n' "\${${xi}:-${vi}}" ;;\n *) printf '%s\\n' "\${${yi}:-}" ;;\nesac\n`,{mode:448}),e}function wi(e,t,n=vi){return{...process.env,GIT_ASKPASS:e,GIT_TERMINAL_PROMPT:"0",[xi]:n,[yi]:t}}function ki(e){if(e)return e.replace(/\/+$/g,"")||"/"}function Ii(e){return{gitUrl:e.gitUrl,baseBranch:e.baseBranch,branchName:e.branchName,cwd:ki(e.cwd)||"",userCwd:ki(e.userCwd),forceUserCwd:e.forceUserCwd,useWorktree:e.useWorktree,userId:e.userId,taskId:e.taskId,repositorySourceType:e.repositorySourceType,taskRepositoryId:e.repositoryId,gitServerId:e.gitServerId}}function Si(e,t){return t??`agentrix/${e}`}async function Ti(e){if(!e)return null;const t=await Vt();return t?an(e,t):null}async function Ei(e,t){const n=tn(t);if(!n)return void console.warn("[GIT] No PAT user metadata found, skipping git config");const s=n.username,a=n.email||`${n.username}@gitlab.local`;await async function(e,t,n){await Ka("git",["config","user.name",t],{cwd:e,windowsHide:!0}),await Ka("git",["config","user.email",n],{cwd:e,windowsHide:!0})}(e,s,a),console.log(`[GIT] Set local git config user.name=${s} user.email=${a}`)}async function Ai(e,t,n){const s=await Ti(n);s?await async function(e,t){const n=bi();try{await Ka("git",["-c","credential.helper=","fetch","--prune","origin"],{cwd:t,env:wi(n,e),windowsHide:!0})}finally{f(n)}}(s,e):await async function(e,t){await Ka("git",["-c","credential.helper=","fetch","--prune",e,"+refs/heads/*:refs/remotes/origin/*","+refs/tags/*:refs/tags/*"],{cwd:t,windowsHide:!0})}(t,e)}async function Ci(e,t,n,s={}){const a=await Ti(s.gitServerId);a?await async function(e,t,n,s=!1){const a=bi();try{const i=["-c","credential.helper=","push","origin",n];s&&i.push("--force"),await Ka("git",i,{cwd:t,env:wi(a,e),windowsHide:!0})}finally{f(a)}}(a,e,t,n):s.gitUrl?await async function(e,t,n,s=!1){const a=["-c","credential.helper=","push",e,n];s&&a.push("--force"),await Ka("git",a,{cwd:t,windowsHide:!0})}(s.gitUrl,e,t,n):await async function(e,t,n=!1){const s=Va(e),a=n?["--force"]:[];await s.push("origin",t,a)}(e,t,n)}async function $i(e,t,n){const s=n.trim();if(!s)return;const a=re.resolveDataDir(e,t),i=y(a,"patch.diff");return await dt(a,{recursive:!0}),await ut(i,`${s}\n`),i}async function _i(e,t,n){await re.writeLastSentArtifactVersion(e,t,n)}function Pi(e,t){return`Please generate pull request metadata for the changes made in this task.\n\nInitial commit hash: ${e}\n${t?`\n\nAdditional instructions:\n${t}`:""}\n\nProvide a concise title (conventional commits format), a detailed description, and a user-facing summary message.`}function Mi(e,t,n,s=6e4){return new Promise(a=>{const i=`shell_${ht().replace(/-/g,"")}`;n.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=Ne("/bin/bash",["-c",e],{cwd:t,env:process.env,shell:!1});let r=null,c=!1;s>0&&(r=setTimeout(()=>{c=!0,o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL")},1e3)},s));let l="";o.stdout?.on("data",e=>{l+=e.toString()}),o.stderr?.on("data",e=>{l+=e.toString()}),o.on("close",(e,t)=>{let o,p,d;if(r&&clearTimeout(r),c){o=124,d=!0;const e=`\n[Command timed out after ${s/1e3} seconds]`;p=l?`${l}${e}`:e.trim()}else o=null!==e?e:"SIGTERM"===t?143:1,d=0!==o,p=l||"(no output)";n.onOutput({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:i,content:p,is_error:d}]},parent_tool_use_id:null,session_id:""}),n.onComplete(o),a(o)}),o.on("error",e=>{r&&clearTimeout(r);const t=`[Error] ${e.message||"Command execution failed"}`;n.onOutput({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:i,content:t,is_error:!0}]},parent_tool_use_id:null,session_id:""}),n.onComplete(1),a(1)})})}class Ri{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 t=("string"==typeof e.message.content?e.message.content:"").trim();return t.startsWith("!")&&!t.startsWith("![")?{type:"bash-command",content:t.slice(1).trim(),originalMessage:e}:"![merge-request]"===t?{type:"merge-request",content:t,originalMessage:e}:"![merge-pr]"===t?{type:"merge-pr",content:t,originalMessage:e}:"![new]"===t?{type:"new-session",content:t,originalMessage:e}:"![plan]"===t?{type:"plan-mode",content:t,originalMessage:e}:{type:"normal",content:t,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 t=this.parseMessage(e),n={id:"msg-"+ ++this.messageIdCounter,type:t.type,priority:"normal",content:t.content,originalMessage:e,timestamp:Date.now()};this.messageQueue.push(n),this.log("info","COORDINATOR",`Enqueued message ${n.id} (type: ${n.type}, queue: ${this.messageQueue.length})`),this.tryUpdateWorkerState(),this.tryProcessNext()}async tryProcessNext(){if(!this.isStopped)if(0!==this.messageQueue.length)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.tryUpdateWorkerState(),this.isStopped||this.tryProcessNext()}else this.tryUpdateWorkerState()}async processMessage(e){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;case"plan-mode":await this.processPlanMode(e);break;default:this.log("warn","COORDINATOR",`Unknown message type: ${e.type}`)}}async processNormalMessage(e){this.log("info","COORDINATOR","Processing normal message for SDK");const t=await this.config.handlers.onNormalMessage(e.originalMessage);this.enqueueAgentMessage(t)}async processBashCommand(e){this.log("info","COORDINATOR",`Processing bash command: ${e.content}`),await this.processCommand(async()=>{await this.config.handlers.onBashCommand(e.content,e.originalMessage)},e)}async processMergeRequest(e){this.log("info","COORDINATOR","Processing merge-request command"),await this.processCommand(async()=>{await this.config.handlers.onMergeRequest(e.originalMessage)},e)}async processMergePr(e){this.log("info","COORDINATOR","Processing merge-pr command"),await this.processCommand(async()=>{await this.config.handlers.onMergePr()},e)}async processNewSession(e){this.log("info","COORDINATOR","Processing new-session command"),await this.processCommand(async()=>{await(this.config.handlers.onNewSession?.())},e)}async processPlanMode(e){this.log("info","COORDINATOR","Processing plan-mode command"),await this.processCommand(async()=>{if(!this.config.handlers.onPlanMode)return;const t=await this.config.handlers.onPlanMode(e.originalMessage);t&&this.enqueueAgentMessage(t)},e)}async processCommand(e,t){await this.waitWorkerIdle(),this.setCommandRunning(!0),this.markCommandMessageProcessed(t);try{await e()}finally{this.setCommandRunning(!1)}}markCommandMessageProcessed(e){const t=e.originalMessage.__localSequence;void 0!==t&&this.config.onCommandMessageProcessed?.(t)}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 t=this.workerState;if(this.log("info","COORDINATOR",`Worker state: ${t} → ${e}`),this.workerState=e,"running"===e&&"idle"===t&&(this.runStartTime=Date.now(),this.config.workClient.sendWorkRunning(this.getActiveAgents()),this.lastActiveAgentsSignature=this.getActiveAgentsSignature(),this.clearIdleTimer()),"idle"===e&&"running"===t){let e;this.runStartTime&&(e=Date.now()-this.runStartTime,this.runStartTime=null),this.config.workClient.sendWorkerReady(e),this.lastActiveAgentsSignature=null,this.startIdleTimer(),this.config.onBecameIdle?.()}}updateAgentRunning(e){this.setAgentRunning("default","Agent",e)}setAgentRunning(e,t,n){const s="running"===this.workerState,a=this.lastActiveAgentsSignature;n?this.agentRunningMap.set(e,{agentId:e,agentName:t,startedAt:Date.now()}):this.agentRunningMap.delete(e);const i=this.getActiveAgentsSignature();this.lastActiveAgentsSignature=i,this.tryUpdateWorkerState(),s&&"running"===this.workerState&&i!==a&&this.config.workClient.sendWorkRunning(this.getActiveAgents())}setBackgroundTaskRunning(e,t){e&&(t?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:t})=>({agentId:e,agentName:t}))}getActiveAgentsSignature(){const e=this.getActiveAgents().slice().sort((e,t)=>e.agentId.localeCompare(t.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,t=this.hasExecutionWork(),n=!e&&!t;this.setWorkerState(n?"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,t,n){this.config.logger&&this.config.logger(e,t,n)}}function Oi(e,t){const n={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:t}]}};e.sendTaskMessage(ma,n)}async function Di(e){const{workingDirectory:t,workClient:n,repositoryId:s,gitServerId:a,gitUrl:i,logger:o,allowInteractive:r=!0,askUser:c,commitChanges:l}=e;if(o.info("[MERGE-PR] Executing merge-pr command"),s){try{const e=await ui(t),s=await ni(t),p=await async function(e,t){const n=Va(e);try{return(await n.log([`origin/${t}..HEAD`])).total>0}catch{return!0}}(t,e);if(s||p){if(!r)throw new Error("merge-pr requires user input to resolve git state, which is not supported in oneshot execution mode");const d=await async function(e,t,n,s){let a="";a=e&&t?"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:a,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 n(i)).answers[0];return e.startsWith("other:")?(s.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 s.error("[MERGE-PR] Ask user failed:",e),"Pause"}}(s,p,c,o);if("Pause"===d)return void Oi(n,"Operation paused. Please handle git state and run merge again.");if(("Push"===d||"PushAndMerge"===d)&&(s&&(o.info("[MERGE-PR] Generating commit message with agent"),await l(),o.info("[MERGE-PR] Committed changes with agent-generated message")),o.info(`[MERGE-PR] Pushing branch ${e} to remote`),await Ci(t,e,!1,{gitServerId:a,gitUrl:i}),"Push"===d))return void Oi(n,"✅ All changes pushed to remote. You can now review and run merge again if everything looks good.")}const d=await n.sendMergePr();if(d.success)Oi(n,`✅ PR merged successfully! Branch ${e} has been merged into the target branch.`);else{let e;switch(d.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: ${d.error||"Unknown error"}`;break;default:e=`Failed to merge PR: ${d.error||"Unknown error"}`}n.sendSystemErrorMessage(e)}}catch(e){o.error("[MERGE-PR] Failed:",e);const t=e instanceof Error?e.message:"Unknown error";n.sendSystemErrorMessage(`Failed to push or merge: ${t}`)}o.info("[MERGE-PR] Worker ready after merge-pr execution")}else n.sendSystemErrorMessage("Cannot merge: task has no git repository configured.")}function Ni(e,t){const n=e.updates?.repositoryId;return"string"==typeof n&&0!==n.length&&t.repositoryId!==n&&(t.repositoryId=n,re.writeTaskInput(t),!0)}function Ui(e,t,n,s={}){const a=n.sendAskUser(e),i=s.timeoutMs??18e5,o=s.onTimeout;return new Promise((e,s)=>{const r=setTimeout(()=>{t.delete(a);const i={type:"ask_user_response",answers:[],status:"timeout",reason:"timeout"};n.sendAskUserResponse(a,i),"abort_task"===o?(n.onTimeoutMessage?.("ask_user timed out. Task cancelled."),n.stopTask?.("ask_user_timeout"),s(new Error("Ask user request timed out"))):e(i)},i);t.set(a,t=>{clearTimeout(r),e(function(e){const t=e.status??"answered";return e.status&&e.reason?e:{...e,status:t,reason:e.reason??("timeout"===t?"timeout":"user")}}(t))})})}function ji(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:se(),session_id:e.sessionId}}function qi(e,t){const n=se();return t.set(e,n),n}function Li(e,t){return t.get(e)||e}function Hi(e,t){return"thread.started"===e.type||"turn.started"===e.type||"turn.completed"===e.type||"turn.failed"===e.type?null:"item.started"===e.type?function(e,t){switch(e.type){case"command_execution":return function(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:qi(e.id,t),name:"Bash",input:{command:e.command}}]},parent_tool_use_id:null,session_id:""}}(e,t);case"file_change":return function(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:qi(e.id,t),name:"Edit",input:{changes:e.changes.map(e=>({kind:e.kind,path:e.path}))}}]},parent_tool_use_id:null,session_id:""}}(e,t);case"mcp_tool_call":return function(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:qi(e.id,t),server_name:e.server,name:e.tool,input:e.arguments}]},parent_tool_use_id:null,session_id:""}}(e,t);case"web_search":return function(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:qi(e.id,t),name:"web_search",input:{query:e.query}}]},parent_tool_use_id:null,session_id:""}}(e,t);default:return null}}(e.item,t):"item.completed"===e.type?function(e,t){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:se().toString()}}(e);case"reasoning":default:return null;case"command_execution":return function(e,t){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:Li(e.id,t),content:"failed"===e.status?"Command execution failed":e.aggregated_output||""}]},parent_tool_use_id:null,session_id:""}}(e,t);case"file_change":return function(e,t){const n=t.get(e.id),s=n??qi(e.id,t),a=!n;(e.changes||[]).map(e=>`${e.kind}: ${e.path}`);const i={type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:s,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:s,content:"failed"===e.status?"File changes failed":"File changes completed"}]},parent_tool_use_id:null,session_id:""};return a?[i,o]:o}(e,t);case"mcp_tool_call":return function(e,t){const n=Li(e.id,t),s="failed"===e.status&&e.error;return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:n,is_error:s,content:s?e.error.message:e.result?.content||""}]},parent_tool_use_id:null,session_id:""}}(e,t);case"web_search":return function(e,t){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:Li(e.id,t),content:{type:"web_search_result",results:[]}}]},parent_tool_use_id:null,session_id:""}}(e,t);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,t):null}let Gi,Wi,Fi;function Bi(e){let t=null,n=!1;for(let s=0;s<e.length;s+=1){const a=e[s];if(n)n=!1;else if("\\"!==a||'"'!==t)if('"'!==a&&"'"!==a||null!==t)if(a!==t){if("#"===a&&null===t)return e.slice(0,s)}else t=null;else t=a;else n=!0}return e}function zi(e){const t=e.trim();if(!t)return null;if(t.startsWith('"'))try{return JSON.parse(t)}catch{return null}const n=t.match(/^'([^']*)'$/);return n?n[1]:t.match(/^[A-Za-z0-9._:/@+-]+$/)?t:null}function Ki(e){const t=e?.trim();return t||function(){const e=function(){const e=process.env.CODEX_HOME||process.env.AGENTRIX_CODEX_HOME||y(n.homedir(),".codex");return y(e.replace(/^~(?=\/|$)/,n.homedir()),"config.toml")}();if(Wi===e&&void 0!==Gi)return Gi;if(Wi=e,Gi=null,!r(e))return Gi;let t;try{t=c(e,"utf8")}catch{return Gi}for(const e of t.split(/\r?\n/)){const t=Bi(e).trim();if(!t)continue;if(t.startsWith("["))break;const n=t.match(/^model\s*=\s*(.+)$/);if(!n)continue;const s=zi(n[1])?.trim();return Gi=s||null,Gi}return Gi}()}class Vi{createCodex(e){const t={},n=function(){if(void 0!==Fi)return Fi??void 0;const e=process.env.AGENTRIX_CODEX_PATH?.trim();return e?(Fi=e,e):0===ze("codex",["--version"],{stdio:"ignore"}).status?(Fi="codex",Fi):void(Fi=null)}();return n&&(t.codexPathOverride=n),e.env&&(t.env=fs(e.env)),new gt(Object.keys(t).length>0?t:void 0)}getAgentConfiguration(){return null}getHooks(){}getMcpServers(){}async executeHook(e,t,n){}async run(e,t){const n=t.abortController,s=this.createCodex(t),a=Ki(t.model),i={workingDirectory:t.cwd,model:a??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},o=t.agentSessionId?s.resumeThread(t.agentSessionId,i):s.startThread(i),r=await o.run("string"==typeof e?e:ys(e),{signal:n.signal,outputSchema:t.structuredOutputSchema?.schema||void 0});return bs({sessionId:o.id??t.agentSessionId??"unknown",model:a??"unknown",numTurns:1,usage:r.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0},result:r.finalResponse??"",structuredOutput:ws(r.finalResponse??"",Boolean(t.structuredOutputSchema))})}async*runStreamed(e,t){const n=t.abortController,s=this.createCodex(t),a=Ki(t.model),i={workingDirectory:t.cwd,model:a??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},o=t.agentSessionId?s.resumeThread(t.agentSessionId,i):s.startThread(i),{events:r}=await o.runStreamed("string"==typeof e?e:ys(e),{signal:n.signal,outputSchema:t.structuredOutputSchema?.schema||void 0});let c=t.agentSessionId||"",l="",p={input_tokens:0,cached_input_tokens:0,output_tokens:0};const d=new Map,u={get:e=>d.get(e),set:(e,t)=>{d.set(e,t)}};for await(const e of r){if("thread.started"===e.type&&(c=e.thread_id,yield ji({sessionId:c,cwd:t.cwd,model:a??void 0})),"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&&(l=e.item.text),"item.started"===e.type||"item.completed"===e.type){const t=Hi(e,u);if(!t)continue;const n=Array.isArray(t)?t:[t];for(const e of n)yield e}}const m=bs({sessionId:c,model:a??"unknown",numTurns:1,usage:p,result:l,structuredOutput:ws(l,Boolean(t.structuredOutputSchema))});yield m}loop(e){const t=e.abortController,n=this.createCodex(e),s=Ki(e.model),a={workingDirectory:e.cwd,model:s??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0};let i=e.agentSessionId?n.resumeThread(e.agentSessionId,a):n.startThread(a),o=!1;const r=[];let c=null,l=e.agentSessionId??null,p=0;const d=()=>{if(!o&&(o=!0,c)){const e=c;c=null,e(null)}},u=e=>"string"==typeof e?e:ys(e),m=async function*(){try{for(;!o&&!t.signal.aborted;){const n=r.length>0?r.shift():await new Promise(e=>{c=e});if(!n)break;let a="";const d=new Map,m={get:e=>d.get(e),set:(e,t)=>{d.set(e,t)}},{events:h}=await i.runStreamed(u(n),{signal:t.signal,outputSchema:e.structuredOutputSchema?.schema||void 0});for await(const t of h){if(o)break;if("thread.started"!==t.type){if("turn.completed"===t.type){l&&(yield bs({sessionId:l,model:s??"unknown",numTurns:p+1,usage:t.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0},result:a,structuredOutput:ws(a,Boolean(e.structuredOutputSchema))}));break}if("turn.failed"===t.type)throw new Error(t.error.message);if("error"===t.type)throw new Error(t.message);if("item.started"===t.type||"item.completed"===t.type){"item.completed"===t.type&&"agent_message"===t.item.type&&t.item.text&&(a=t.item.text);const e=Hi(t,m);if(!e)continue;const n=Array.isArray(e)?e:[e];for(const e of n)yield e}}else l=t.thread_id,yield ji({sessionId:l,cwd:e.cwd,model:s??void 0})}p+=1}}finally{d()}}();return t.signal.addEventListener("abort",d,{once:!0}),{push:e=>{if(console.log("CodexRunner.loop.push:",JSON.stringify(e,null,2)),!o){if(c){const t=c;return c=null,void t(e)}r.push(e)}},events:m,stop:d}}}const Xi=["PreToolUse","PostToolUse","SessionStart","SessionEnd","UserPromptSubmit","Stop","SubagentStop","PreCompact","Notification","RepositoryInit"];function Ji(e){const t={};for(const n of Xi){const s=e[n];"function"==typeof s&&(t[n]=s,console.log(`[Hook Loader] ✓ Loaded hook: ${n}`))}const n=Object.keys(t).length;return 0===n?console.warn("[Hook Loader] No valid hooks found in module"):console.log(`[Hook Loader] Successfully loaded ${n} hook(s)`),t}class Yi{static pool=new Map;static async create(e,t,n){const s=this.pool.get(t);if(s)return s;let a;if("claude"===e){const e=await async function(e){const{agentId:t,agentDir:n,logger:s}=e;if(!t||"default"===t)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{Ms(s,"info",`Loading agent: ${t}`);const e=await Pe({agentId:t,framework:"claude",agentDir:n});if(!e.claude)return Ms(s,"warn",`No claude configuration found for agent ${t}`),{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 a=e.claude,i=a.plugins.map(e=>({type:"local",path:e})),o=n||Me().resolveAgentDir(t),r=a.config.sdkMcpTools?.map(e=>y(o,"claude",e)),c={customSystemPrompt:a.systemPrompt,customModel:a.config.model,customFallbackModel:a.config.fallbackModel,customMaxTurns:a.config.maxTurns,customExtraArgs:a.config.extraArgs,customPermissionMode:a.config.settings?.permissionMode,customPlugins:i,systemPromptMode:a.config.systemPrompt?.mode??"append",customPRPromptTemplate:a.prPromptTemplate,prPromptMode:a.config.pullRequestPrompt?.mode??"append",customSdkMcpTools:r};return Ms(s,"info",`Agent ${t} loaded successfully (${i.length} plugins)`),c}catch{return Ms(s,"error",`Failed to load agent: ${t}`),{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:t,agentDir:n?.agentDir,logger:n?.logger});let s,i;n?.context&&t&&"default"!==t&&(s=await async function(e,t,n){if(e&&"default"!==e)try{const s=X(),a=t||s.resolveAgentDir(e),i=y(a,"claude");return await async function(e,t){const n=ke(e,"hooks");if(!xe(n))return{};const s=[ke(n,"dist","index.mjs"),ke(n,"dist","index.js"),ke(n,"index.mjs"),ke(n,"index.js")];let a=null;for(const e of s)if(xe(e)){a=e;break}if(!a)return console.warn(`[Hook Loader] Hooks not built: ${n}`),console.warn("[Hook Loader] To build hooks, run:"),console.warn(`[Hook Loader] cd ${n}`),console.warn("[Hook Loader] npm install && npm run build"),console.warn("[Hook Loader] Or place hooks directly in:"),console.warn(`[Hook Loader] ${ke(n,"index.js")} or ${ke(n,"index.mjs")}`),{};try{console.log(`[Hook Loader] Loading hooks: ${a}`);const e=`${nt(a).href}?t=${Date.now()}`,n=await import(e);if("function"==typeof n.default){if(t)return console.log("[Hook Loader] Using factory pattern with AgentrixContext"),Ji(n.default(t));console.warn("[Hook Loader] Factory function found but no context provided, skipping factory")}return Ji(n)}catch(e){throw console.error(`[Hook Loader] Failed to load hooks from ${a}:`,e),new Error(`Hook loading failed: ${e instanceof Error?e.message:String(e)}`)}}(i,n)}catch(e){return void console.warn("[AgentRunners] Failed to load hooks:",e)}}(t,n.agentDir,n.context)),n?.context&&e.customSdkMcpTools&&e.customSdkMcpTools.length>0&&(i=await async function(e,t,n){const s={};for(const a of e)try{n&&n("info","MCP",`Loading SDK MCP tools from: ${a}`);const e=await import(a),i=e.default||e;if(!i){n&&n("warn","MCP",`No default export found in ${a}`);continue}const o="function"==typeof i?i(t):i,r=o.name;s[r]=o,n&&n("info","MCP",`Loaded MCP server: ${r}`)}catch(e){n&&n("error","MCP",`Failed to load SDK MCP tools from ${a}: ${e instanceof Error?e.message:String(e)}`)}return s}(e.customSdkMcpTools,n.context,n.logger)),a=new Ps(t,e,s,i)}else a=new Vi;return this.pool.set(t,a),a}static release(e){this.pool.delete(e)}static releaseAll(){this.pool.clear()}}class Qi{constructor(e){this.workingDirectory=e}async listFiles(e=3){const t=[];return this.listFilesRecursively(this.workingDirectory,t,"",e,0),t}async readFile(e){try{const t=be.join(this.workingDirectory,e);return ge.existsSync(t)?ge.readFileSync(t,"utf-8"):null}catch{return null}}async fileExists(e){const t=be.join(this.workingDirectory,e);return ge.existsSync(t)}listFilesRecursively(e,t,n,s,a){if(!(a>s))try{const i=ge.readdirSync(e,{withFileTypes:!0});for(const o of i){const i=n?`${n}/${o.name}`:o.name;o.isDirectory()?Y.includes(o.name)||this.listFilesRecursively(be.join(e,o.name),t,i,s,a+1):o.isFile()&&t.push(i)}}catch(e){}}}class Zi{constructor(e){this.params=e}state=null;async setup(){const{options:e,handlers:t}=this.params,{userId:n,taskId:s,cwd:a}=e;if(!a)throw new Error("[WORKSPACE] Missing cwd for workspace setup");const i=re.getWorkspaceState(n,s),o=e.repositorySourceType,r={...e,repositorySourceType:o},{initialCommitHash:c,isGitRepository:l,setupAction:p,useWorktree:d,initPolicyUpdates:u}=await this.ensureWorkspace(r,t,i);await re.writeWorkspaceState(n,s,{initialized:!0,initializedAt:(new Date).toISOString(),cwd:a,repositorySourceType:r.repositorySourceType,useWorktree:d,userCwd:e.userCwd,forceUserCwd:e.forceUserCwd,gitUrl:e.gitUrl,baseBranch:e.baseBranch,taskRepositoryId:e.taskRepositoryId,initialCommitHash:c,initPolicies:{...i?.initPolicies,...u}});const m=await async function(e,t,n,s){return async function(e,t,n,s){if(!await Xa(e))return{currentCommitHash:"",hadUncommittedChanges:!1,hasNewArtifacts:!1,lastSentArtifactVersion:void 0,patchPath:"",diffStats:void 0};const a=await ni(e),i=await si(e),o=s||re.getWorkspaceState(t,n)?.initialCommitHash;if(!o)throw new Error(`Initial commit hash not found for task ${n}`);const r=await di(e,o),c=r?await $i(t,n,r.patch):void 0,l=await re.readLastSentArtifactVersion(t,n),p=!!r&&r.artifactVersion!==l;return{currentCommitHash:i,currentArtifactVersion:r?.artifactVersion,hadUncommittedChanges:a,hasNewArtifacts:p,lastSentArtifactVersion:l??void 0,patchPath:c,diffStats:r?.stats}}(e,t,n,s)}(a,n,s,c);return this.state={cwd:a,initialCommitHash:c,isGitRepository:l,setupAction:p,gitStateResult:m},l&&!e.taskRepositoryId&&await async function(e,t){try{const n=await async function(e){try{const t=Va(e),n=(await t.getRemotes(!0)).find(e=>"origin"===e.name);return n?.refs?.fetch?fi(n.refs.fetch):null}catch(e){return console.error("[GIT] Failed to get remote info:",e),null}}(e);if(!n)return void console.log("[REPO] No origin remote found, skipping repository association");if(!t?.onRepositoryDetected)return;console.log(`[REPO] Detected remote: ${n.host}/${n.owner}/${n.repo}`),t.onRepositoryDetected(n)}catch(e){console.error("[REPO] Failed to send repository association:",e)}}(a,t),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:t,initialCommitHash:n,isGitRepository:s}=this.getState(),{userId:a,taskId:i}=this.params.options;if(!s||!n)return{};const o=await di(t,n);if(!o)return{};try{await $i(a,i,o.patch)}catch(t){e.onPatchError?.(t)}const r=await async function(e){const t=new Qi(e);return J(t)}(t),c=await re.readLastSentArtifactVersion(a,i);return c&&c===o.artifactVersion?{artifactVersion:o.artifactVersion}:{artifactVersion:o.artifactVersion,artifacts:{artifactVersion:o.artifactVersion,stats:o.stats,preview:r}}}async ensureWorkspace(e,t,n){const s=e.repositorySourceType;return"git-server"===s?this.ensureGitServerWorkspace(e,t,n):"directory"===s?this.ensureDirectoryWorkspace(e,t,n):this.ensureTemporaryWorkspace(e,t,n)}async ensureGitServerWorkspace(e,t,n){const{cwd:s,gitUrl:a,taskId:i,baseBranch:o,branchName:c,gitServerId:l}=e;if(!a)throw new Error("[WORKSPACE] gitUrl is required for git-server mode");const p=Boolean(e.taskRepositoryId&&l),d="git-server"===n?.repositorySourceType&&!0===n.useWorktree,u=await Xa(s),m=ii(s);if(p&&(!u||d)){const p=await async function(e,t,n,s,a,i){const o=ki(e)||e,c=hi(n),l=fi(c);if(!l)throw new Error(`Unable to resolve repository owner/name from git URL: ${c}`);const p=re.resolveRepoStoreCheckoutDir(s,l.owner,l.repo),d=re.resolveRepoStoreLockPath(s,l.owner,l.repo),u=await re.acquireFileLock(d);if(!u)throw new Error(`Timed out waiting for repo store lock at ${d}`);try{await async function(e,t,n,s){const a=hi(t);if(!await Xa(e)){if(!ii(e))throw new Error(`Repo store directory ${e} exists but is not a git repository`);await Za(e)}await gi(e,"origin",a),await Ai(e,t,n);const i=await async function(e,t="origin"){const{stdout:n}=await Ka("git",["for-each-ref","--format=%(refname:short)",`refs/remotes/${t}`],{cwd:e,maxBuffer:10485760,windowsHide:!0});return n.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>e.replace(`${t}/`,"")).filter(e=>"HEAD"!==e)}(e),o=function(e,t){if(t&&e.includes(t))return t;if(e.includes("main"))return"main";if(e.includes("master"))return"master";if(e.length>0)return e[0];throw new Error("Cannot create worktree: repository has no remote branches to base the workspace on.")}(i,s);return await async function(e,t,n){await Ka("git",["checkout","-B",t,n],{cwd:e,windowsHide:!0})}(e,o,`origin/${o}`),{baseBranch:o}}(p,n,s,a);const e=Si(t,i),c=await Ja(p),l=c.find(e=>ki(e.path)===o);if(l){if(l.branch&&l.branch!==e)throw new Error(`Worktree at ${o} is already attached to branch ${l.branch}. Remove it before retrying: git worktree remove ${o}`);return s&&await Ei(o,s),{initialCommitHash:await si(o)}}const d=c.find(t=>t.branch===e&&ki(t.path)!==o);if(d)throw new Error(`Branch ${e} is already attached to worktree ${d.path}. Remove it before retrying.`);const u=lt(p),m=(await u.branchLocal()).all.includes(e);if(r(o)&&!ii(o))throw new Error(`Worktree directory already exists at ${o}. This may be from a previous task. To clean up: git worktree remove ${o} OR rm -rf ${o}`);try{m?await u.raw(["worktree","add",o,e]):await Ya(p,o,e,"HEAD")}catch(e){try{await Qa(p,o,!0)}catch{}throw e}return await Ei(o,s),{initialCommitHash:await si(o)}}finally{await re.releaseFileLock(d,u)}}(s,i,a,l,o,c);return u?{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:!0}:{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,p.initialCommitHash,"none"),isGitRepository:!0,setupAction:"worktree",autoCommitPolicy:"enabled",useWorktree:!0}}if(!u){if(!m)throw new Error(`[WORKSPACE] Directory ${s} exists but is not a git repository.`);const e=await async function(e,t,n,s,a,i){const o=Si(n,i),c=hi(t),l=await Xa(e);if(!ii(e)&&!l)throw new Error(`Directory ${e} exists but is not a git repository`);const p=await Ti(a);return ii(e)?(p?(console.log("[GIT] Using GIT_ASKPASS credential injection for clone"),await async function(e,t,n){const s=b(n);r(s)||h(s,{recursive:!0});const a=bi();try{await Ka("git",["-c","credential.helper=","clone",t,n],{env:wi(a,e),windowsHide:!0})}finally{f(a)}}(p,c,e),a&&await Ei(e,a)):await async function(e,t){const n=b(t);r(n)||h(n,{recursive:!0});const s=Va();await s.clone(e,t)}(t,e),await mi(e,"origin",c),await ti(e,o,s),await si(e)):(await gi(e,"origin",c),await Ai(e,t,a),a&&await Ei(e,a),await ti(e,o,s),await si(e))}(s,a,i,o,l,c)||await si(s);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,e,"none"),isGitRepository:!0,setupAction:"clone",autoCommitPolicy:"enabled",useWorktree:!1}}return await mi(s,"origin",hi(a)),{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:n?.useWorktree??!1}}async ensureDirectoryWorkspace(e,t,n){const{cwd:s,taskId:i,userCwd:o}=e;if(await Xa(s))return this.tryResolveDirtyRepo(e,t,n);if(!ii(s))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};{if(!o)return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};const t=o.replace(/^~/,a());if(ii(t))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};if(!await Xa(t))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};await ai(t)||await ei(t),await async function(e,t,n,s){const i=e.replace(/^~/,a()),o=ki(t)||t;if(!await Xa(i))throw new Error(`Directory ${i} is not a git repository. Worktrees can only be created from existing git repositories.`);if(!await ai(i))throw new Error(`Cannot create worktree: repository at ${i} has no commits. Please create an initial commit first: cd ${i} && git add . && git commit -m 'Initial commit'`);const c=Si(n,s),l=(await Ja(i)).find(e=>ki(e.path)===o);if(l){if(l.branch&&l.branch!==c)throw new Error(`Worktree at ${o} is already attached to branch ${l.branch}. Remove it before retrying: git worktree remove ${o}`);return{initialCommitHash:await si(o)}}const p=lt(i),d=(await p.branchLocal()).all.includes(c);if(r(o)&&!ii(o))throw new Error(`Worktree directory already exists at ${o}. This may be from a previous task. To clean up: git worktree remove ${o} OR rm -rf ${o}`);try{d?await p.raw(["worktree","add",o,c]):await Ya(i,o,c,"HEAD")}catch(e){try{await Qa(i,o,!0)}catch{}throw e}return{initialCommitHash:await si(o)}}(t,s,i,e.branchName)}return{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:!0}}async ensureTemporaryWorkspace(e,t,n){const{cwd:s,taskId:a}=e;if(!await Xa(s)){await async function(e,t,n){const s=await async function(e,t,n){await Za(e);const s=function(e,t){return{hook_event_name:"RepositoryInit",workspace_path:e,task_id:t}}(e,t);return n?.onRepositoryInit&&await n.onRepositoryInit(s),await ei(e),await si(e)}(e,t,n);return{initialCommitHash:s}}(s,a,t),await ti(s,Si(a,e.branchName),e.baseBranch);const i=await si(s);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,i,"none"),isGitRepository:!0,setupAction:"init",autoCommitPolicy:"enabled",useWorktree:!1}}return{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:n?.useWorktree??!1}}async tryResolveDirtyRepo(e,t,n){let s=null,a="enabled";const i={};if(await async function(e){return!!await Xa(e)&&await ni(e)}(e.cwd)){const o=this.getPersistedInitPolicy(n,"uncommittedChanges",["Ignore","Commit","Stash"]),r=o?{action:o,remember:!0}:t?.onUncommittedChanges?await t.onUncommittedChanges():{action:"Ignore",remember:!1},c=r.action;if(await async function(e,t){switch(t){case"Ignore":console.log("[GIT] User chose to ignore uncommitted changes");break;case"Stash":console.log("[GIT] Stashing uncommitted changes"),await async function(e){const t=Va(e);await t.stash(["push"])}(e);break;case"Commit":console.log("[GIT] Committing uncommitted changes with agent-generated message");break;case"Abort":throw new Error("Task aborted by user due to uncommitted changes")}}(e.cwd,c),"Abort"===c)throw new Error("Task aborted by user due to uncommitted changes");if("Commit"===c){if(!t?.onCommitUncommittedChanges)throw new Error("Unable to commit uncommitted changes during workspace setup");await t.onCommitUncommittedChanges()}!o&&r.remember&&(i.uncommittedChanges=c),s=c,"Ignore"===c&&(a="disabled_by_ignore")}let o;if(await ai(e.cwd)||await ei(e.cwd),"Ignore"===s){const t=Si(e.taskId,e.branchName);o=await ui(e.cwd)===t?"none":"kept"}else o=await this.tryResolveBranchMismatch(e,t,n,i);const r=await si(e.cwd);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,r,o),isGitRepository:!0,setupAction:"reuse",autoCommitPolicy:a,useWorktree:n?.useWorktree??!1,initPolicyUpdates:i}}getPersistedInitPolicy(e,t,n){const s=e?.initPolicies?.[t];return s&&n.includes(s)?s:null}resolveInitialCommitHash(e,t,n){return e?"kept"===n?t:e:t}async tryResolveBranchMismatch(e,t,n,s){const a=Si(e.taskId,e.branchName),i=await ui(e.cwd);if(i===a)return"none";const o=this.getPersistedInitPolicy(n,"branchMismatch",["Switch","Keep"]),r=o?{action:o,remember:!0}:t?.onBranchMismatch?await t.onBranchMismatch({currentBranch:i,expectedBranch:a,workingDirectory:e.cwd}):{action:"Switch",remember:!1};if("Abort"===r.action)throw new Error("Task aborted by user due to branch mismatch");return!o&&r.remember&&(s.branchMismatch=r.action),"Keep"===r.action?"kept":(await ti(e.cwd,a,e.baseBranch),"switched")}}const eo=Ge.object({title:Ge.string().describe("Concise PR title following conventional commits format (feat/fix/docs/refactor/test/chore: description), maximum 50 characters"),description:Ge.string().describe("Detailed PR description explaining: what changed, why these changes were necessary, any important technical decisions, and impact on existing functionality"),userMessage:Ge.string().describe("Friendly message to display to the user, summarizing the PR creation. Should be concise and informative.")}),to=We(eo,{target:"draft-07"}),no=We(eo);function so(e){if("success"!==e.subtype)throw new Error("PR response failed before structured output was returned");const t=e;return t.structured_output?eo.parse(t.structured_output):function(e){if(!e.trim())throw new Error("PR response was empty");const t=ao(e),n=JSON.parse(t);return eo.parse(n)}(t.result??"")}function ao(e){const t=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);return t?t[1].trim():e.trim()}class io{chain=Promise.resolve();run(e){const t=this.chain.then(e,e);return this.chain=t.then(()=>{},()=>{}),t}}const oo=[{name:"/merge-request",sendAs:"![merge-request]",description:"Create a pull request for current task changes"},{name:"/merge-pr",sendAs:"![merge-pr]",description:"Merge the current pull request"},{name:"/new",sendAs:"![new]",description:"Start a new session for this task"}];function ro(e){const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:""}function co(e=[]){const t=[],n=new Set;for(const e of oo.map(e=>({id:`cli_builtin:${e.name}`,name:e.name,kind:"cli_builtin",sendAs:e.sendAs,description:e.description})))t.push(e),n.add(e.name);const s=Array.from(new Set(e.map(ro).filter(Boolean)));s.sort((e,t)=>e.localeCompare(t));for(const e of s)n.has(e)||t.push({id:`sdk:${e}`,name:e,kind:"sdk",sendAs:e});return t}const lo=Ge.object({message:Ge.string().describe("A git commit message following conventional commits. Return only the commit message text, optionally with a blank line and body.")}),po=We(lo,{target:"draft-07"}),uo=We(lo);async function mo(e){if(!await ni(e.workingDirectory))throw new Error("No uncommitted changes to commit");const t=await si(e.workingDirectory),n=await async function(e){const t=e.runner.runStreamed("Generate a git commit message for the current uncommitted changes.\n\nRequirements:\n- Follow this repository's commit message conventions.\n- Keep the subject line specific and concise.\n- Add a body only if it materially improves clarity.\n- Return only the commit message.",{cwd:e.workingDirectory,model:e.model,abortController:e.abortController,modeConfig:e.modeConfig,structuredOutputSchema:{type:"json_schema",schema:"claude"===e.schemaTarget?po:uo}});let n=null;for await(const s of t){if("result"===s.type){n=s;break}await(e.onStreamMessage?.(s))}if(!n)throw new Error("Commit message generation did not return a result message");return function(e){if("success"!==e.subtype)throw new Error("Commit message generation failed before structured output was returned");const t=e,n=(t.structured_output?lo.parse(t.structured_output):lo.parse(JSON.parse(ao(t.result??"")))).message.trim();if(!n)throw new Error("Commit message generation returned an empty message");return n}(n)}(e),s=await async function(e,t){const n=t.trim();if(!n)throw new Error("Commit message cannot be empty");const[s,...a]=n.split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean);if(!s)throw new Error("Commit subject cannot be empty");const i=Va(e);await i.add(["--all"]);const o=["commit","-m",s];for(const e of a)o.push("-m",e);return await i.raw(o),await si(e)}(e.workingDirectory,n);if(await ni(e.workingDirectory))throw new Error("Commit completed but working tree is still dirty");if(s===t)throw new Error("Commit completed but HEAD did not change");return{commitHash:s,message:n}}function ho(e){if(e)return{type:"json_schema",schema:e}}async function go(e,t){await o.promises.mkdir(t,{recursive:!0});const n=await o.promises.readdir(e,{withFileTypes:!0});for(const s of n){const n=x.join(e,s.name),a=x.join(t,s.name);s.isDirectory()?await go(n,a):await o.promises.copyFile(n,a)}}function fo(e){return"oneshot"===function(e){return e.workerExecutionMode??Q}(e)}class vo{constructor(e,t,n){this.credentials=e,this.options=t,this.workingDirectory=n;const s=this.options.input,{taskId:a,userId:i}=s;this.logger=de({type:"worker",taskId:a}),this.currentAgentSessionId="agentSessionId"in s?s.agentSessionId:void 0;const o=s.taskAgents||[];this.taskAgentsMap=new Map(o.map(e=>[e.id,e]));const r=this.taskAgentsMap.size>1;this.primaryAgentId=r?"planner":s.agentId,this.primaryAgentName=r?"planner":this.taskAgentsMap.get(s.agentId)?.name??"unknown";const c=this.createWorkerClientConfig(i,a,n),l=re.resolveDataDir(i,a);this.historyDb=Ys({dataDir:l,taskId:a}),this.workClient=new ha(c.config,{...c.handlers,getPermissionMode:()=>this.getPermissionModeSnapshot(),historyDb:this.historyDb}),this.coordinator=this.createMessageCoordinator(this.workClient,this.options.idleTimeoutSecond),this.agentContext=new ga({logger:this.logger,socketClient:this.workClient.client,taskId:s.taskId,userId:s.userId,chatId:s.chatId,rootTaskId:s.rootTaskId||s.taskId,parentTaskId:s.parentTaskId||null,workingDirectory:this.workingDirectory,agentHomeDir:re.agentrixAgentsHomeDir,taskAgents:s.taskAgents||[],serverUrl:re.serverUrl,taskDataKey:this.options.dataEncryptionKey}),this.agentrixTools=this.createAgentrixTools();const p={...Ii(this.options.input),cwd:this.workingDirectory};this.workspace=new Zi({options:p,handlers:this.createWorkspaceHandlers(this.workClient)})}abortController=new AbortController;isStopping=!1;askUserAwaiter=new Map;messageFilter=ya();logger;workClient;workspace;coordinator;agentContext;runner;agentQueues=new Map;currentAgentSessionId;currentGroupId=null;historyDb;chatHistoryDb=null;agentrixTools;pendingNavigateTaskId=null;pendingPermissions=new Map;grantedPermissions=new Set;loopPermissionModeSetter=null;configuredPermissionMode="bypassPermissions";desiredPermissionMode=null;activePermissionMode=null;lastBroadcastPermissionMode=null;taskAgentsMap;messageSavedListener=null;messageDebounceHandle=null;messageDebounceMs=1e4;lastProcessedSequence=0;primarySessionReady=!1;pendingPrimaryLastSequence=null;primaryAgentId;primaryAgentName;exitReason="completed";newMessageGroupId(){return`group-${crypto.randomUUID()}`}refreshGroupId(){this.currentGroupId=this.newMessageGroupId()}getConfiguredPermissionMode(){if(this.isOneShotExecution())return"bypassPermissions";const e=this.runner?.getAgentConfiguration()?.customPermissionMode;return e??"bypassPermissions"}isOneShotExecution(){return fo(this.options.input)}initializePermissionModeState(){this.configuredPermissionMode=this.getConfiguredPermissionMode(),this.desiredPermissionMode??=this.configuredPermissionMode}getPermissionModeSnapshot(){return this.desiredPermissionMode??this.configuredPermissionMode??null}broadcastPermissionMode(e){this.lastBroadcastPermissionMode!==e&&(this.lastBroadcastPermissionMode=e,this.workClient.sendPermissionMode(e))}confirmPermissionModeApplied(e){this.desiredPermissionMode=e,this.activePermissionMode=e,this.broadcastPermissionMode(e)}async applyPermissionMode(e){this.loopPermissionModeSetter&&(await this.loopPermissionModeSetter(e),this.confirmPermissionModeApplied(e))}async flushDesiredPermissionMode(){const e=this.getPermissionModeSnapshot();e&&this.loopPermissionModeSetter&&this.activePermissionMode!==e&&await this.applyPermissionMode(e)}async requestPermissionMode(e){this.desiredPermissionMode=e,this.broadcastPermissionMode(e),await this.flushDesiredPermissionMode()}async restoreConfiguredPermissionMode(){await this.requestPermissionMode(this.configuredPermissionMode)}shouldProcessMessage(e){const t=e.message,n=this.getRunnerMode(),s="group_chat"===n||"group_work"===n,a=z(t);return!!Z(t)||!!ee(t)||!(!K(t)&&!a)&&(s?"agent"!==e.senderType&&e.senderId!==this.primaryAgentId:!!a||"system"===e.senderType&&"user"===t.type||"user"===t.type)}shouldDropHeartbeatWhileBusy(){return this.coordinator.isActivelyExecuting()}async processPendingMessages(){const e=this.historyDb.pageMessagesAfter(this.lastProcessedSequence,100),t=this.getRunnerMode(),n="group_chat"===t||"group_work"===t,s=[];for(const t of e.data)if(this.lastProcessedSequence=t.localSequence,this.shouldProcessMessage(t)){if(n&&this.isUnsupportedGroupPlanCommand(t)){this.log("info","PLAN","Ignoring unsupported ![plan] command in group mode");continue}s.push(t)}if(s.length>0){this.deduplicateHeartbeats(s);const e=this.mergeConsecutiveHumanMessages(s);n?await this.processMessagesAsGroup(e):await this.processMessagesIndividually(e)}e.hasMore&&await this.processPendingMessages()}isUnsupportedGroupPlanCommand(e){const t=e.message;return!(!K(t)||"user"!==t.type)&&"![plan]"===ys(t).trim()}deduplicateHeartbeats(e){let t=-1;for(let n=e.length-1;n>=0;n--)Z(e[n].message)&&(-1===t?t=n:(e.splice(n,1),t--))}mergeConsecutiveHumanMessages(e){if(0===e.length)return[];const t=[];let n=0;for(;n<e.length;){const s=e[n];if("human"===s.senderType){const a=[s];for(;n+1<e.length;){const t=e[n+1];if("human"!==t.senderType||t.senderId!==s.senderId)break;a.push(t),n++}1===a.length?t.push(s):t.push(this.createMergedHumanMessage(a))}else t.push(s);n++}return t}createMergedHumanMessage(e){const t=[],n=[];for(const s of e){const e=s.message;if(!K(e)||"user"!==e.type)continue;const a=e.message.content;if("string"==typeof a)t.push(a);else if(Array.isArray(a))for(const e of a)"text"===e.type?t.push(e.text):n.push(e)}const s=t.join(""),a=n.length>0?[{type:"text",text:s},...n]:s,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:a},parent_tool_use_id:null,session_id:i.message?.session_id||""}}}async processMessagesAsGroup(e){const t=[],n=[];for(const s of e){const e=ba(s);if(e){const s=e.message.content;if("string"==typeof s)t.push(s);else if(Array.isArray(s))for(const e of s)"text"===e.type?t.push(e.text):n.push(e)}}if(0===t.length)return;const s=Math.max(...e.map(e=>e.localSequence)),a=t.join(" "),i={type:"user",message:{role:"user",content:n.length>0?[{type:"text",text:a},...n]:a},parent_tool_use_id:null,session_id:""};i.__localSequence=s,await this.coordinator.enqueue(i)}async processMessagesIndividually(e){for(const t of e){const e=this.formatSingleMessage(t);e&&(e.__localSequence=t.localSequence,await this.coordinator.enqueue(e))}}formatSingleMessage(e){const t=e.message;if(Z(t))return{type:"user",message:{role:"user",content:`[heartbeat] You are being awakened by a scheduled heartbeat at ${t.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(ee(t)){const e=t;let n=`[reminder from shadow] ${e.content}`;return e.filePath&&(n+=`\nDetailed analysis: ${e.filePath}`),{type:"user",message:{role:"user",content:n},parent_tool_use_id:null,session_id:""}}return K(t)&&"user"===t.type?t: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(t){if(!(t instanceof Qe)){e="error",this.log("warn","AGENT","Fatal error:",t);const n=t instanceof Error?t.message:String(t);await this.reportFatalError(n)}}finally{await this.exitWorker("error"===e?"error":this.exitReason)}}async autoInstallAgent(e){const t=this.options.input,n=t.agentGitUrl,s=t.agentGitSubDir;if(n)try{this.log("info","AGENT",`Auto-installing agent ${e} from git`),await as({agentId:e,gitUrl:n,subDir:s??void 0})}catch(t){this.log("warn","AGENT",`Auto-install failed for agent ${e}: ${t}`)}else this.log("warn","AGENT",`Auto-install skipped: no agentGitUrl provided for agent ${e}`)}async applyAgentUpgrade(e,t,n){const s=re.agentrixAgentsHomeDir,a=y(s,`${e}.new`),i=y(s,`${e}-bak`);try{this.log("info","AGENT",`Applying upgrade for ${e}`),is(n),d(n,a),await go(t,i),u(t,{recursive:!0,force:!0}),d(a,t),xe(i)&&u(i,{recursive:!0,force:!0}),this.log("info","AGENT",`Upgrade applied for ${e}`)}catch(n){this.log("warn","AGENT",`Upgrade failed for ${e}: ${n}`),!xe(t)&&xe(i)&&d(i,t),xe(a)&&u(a,{recursive:!0,force:!0})}}async initialize(){const e=this.options.input,t=re.resolveAgentDir(e.agentId),n=y(t,"upgrade"),s=Boolean(e.agentGitUrl),a=Boolean(e.agentId&&"default"!==e.agentId&&!e.agentDir&&s&&!xe(t)),i=Boolean(e.agentId&&"default"!==e.agentId&&!e.agentDir&&!a&&xe(n));await this.workClient.connect(),this.workClient.sendWorkerInitializing({deployingAgent:a,upgradingAgent:i}),a&&await this.autoInstallAgent(e.agentId),i&&await this.applyAgentUpgrade(e.agentId,t,n);const o=await Yi.create("claude",e.agentId,{agentDir:e.agentDir,logger:this.log.bind(this),context:this.agentContext});this.runner=o,this.initializePermissionModeState();const r=await this.workspace.setup();await this.registerWithDaemon(this.workingDirectory),this.log("info","WORKSPACE",`Prepared ${this.options.input.repositorySourceType} workspace via ${r.setupAction} at ${this.workingDirectory} (${r.initialCommitHash||"none"})`),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(),this.workClient.sendTaskSlashCommandsUpdate(co())}createWorkspaceHandlers(e){return this.isOneShotExecution()?{onRepositoryDetected:t=>{e.associateRepository(t.host,t.owner,t.repo,t.url)},onRepositoryInit:async e=>{await(this.runner?.executeHook("RepositoryInit",e))},onUncommittedChanges:async()=>{throw new Error("Uncommitted changes require user input, which is not supported in oneshot execution mode")},onCommitUncommittedChanges:this.commitCurrentChangesWithAgent.bind(this),onBranchMismatch:async()=>{throw new Error("Branch mismatch requires user input, which is not supported in oneshot execution mode")}}:{onRepositoryDetected:t=>{e.associateRepository(t.host,t.owner,t.repo,t.url)},onRepositoryInit:async e=>{await(this.runner?.executeHook("RepositoryInit",e))},onUncommittedChanges:this.onUncommittedChanges.bind(this),onCommitUncommittedChanges:this.commitCurrentChangesWithAgent.bind(this),onBranchMismatch:this.onBranchMismatch.bind(this)}}async registerWithDaemon(e){const t=this.options.input.taskId,n=await Tt(t,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});n.error?this.log("warn","DAEMON",`Failed to report session ${t}:`,n.error):this.log("info","DAEMON",`Session ${t} registered`)}setEnvironmentVariables(){this.options.input.environmentVariables&&Object.entries(this.options.input.environmentVariables).forEach(([e,t])=>{null!=t&&(process.env[e]=String(t))}),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,t){const n=1e3*Math.max(0,t??0);return this.coordinator=new Ri({workerType:"claude",workClient:e,onCommandMessageProcessed:e=>{this.markPrimaryMessageProcessed(e)},handlers:{onNormalMessage:async e=>e,onBashCommand:async(e,t)=>{await this.executeBashCommand(e)},onMergeRequest:async e=>{await this.executeMergeRequest()},onMergePr:async()=>{await this.executeMergePr()},onNewSession:async()=>{await this.executeNewSession()},onPlanMode:async()=>this.isOneShotExecution()?(this.workClient.sendSystemErrorMessage("![plan] is not supported in oneshot execution mode",{groupId:this.currentGroupId??void 0}),null):(await this.requestPermissionMode("plan"),null)},logger:(e,t,n)=>{const s=e;this.log(s,t,n)},idleTimeoutMs:n,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}async handleEvent(){const e=this.options.input.event,t=this.options.input.eventData;if("sub-task-result-updated"===e){const e=t,n=va(e,this.options.dataEncryptionKey);this.historyDb.saveMessage({eventId:e.eventId||`sub-task-${Date.now()}`,message:n,senderType:"system",senderId:"system",senderName:"system"})}if("sub-task-ask-user"===e){const e=t,n=xa(e,this.options.dataEncryptionKey);this.historyDb.saveMessage({eventId:e.eventId||`sub-task-ask-${Date.now()}`,message:n,senderType:"system",senderId:"system",senderName:"system"})}this.isOneShotExecution()?(await this.processPendingMessages(),this.coordinator.hasAgentMessages()||this.isStopping||this.stopTask("oneshot_complete")):this.triggerMessageProcessing(),"task-message"===e&&t?.eventId&&this.workClient.sendEventAck(t.eventId)}async executeMergeRequest(){this.log("info","MERGE","Executing merge-request command");const e=this.getRunnerMode(),t="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 ni(this.workingDirectory)&&await this.commitCurrentChangesWithAgent();const e=await si(this.workingDirectory),a=this.workspace.getInitialCommitHash();if(!a){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 ri(this.workingDirectory,a,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 ui(this.workingDirectory);this.log("info","MERGE",`Pushing branch ${i} to remote`),await Ci(this.workingDirectory,i,!1,{gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl}),this.log("info","MERGE","Successfully pushed branch to remote");const o=this.runner?.getAgentConfiguration(),r=Pi(a,(o?.customPRPromptTemplate?(n=o.customPRPromptTemplate,s={initialCommitHash:a,currentCommitHash:"",branchName:""},n.replace(/\{\{initialCommitHash\}\}/g,s.initialCommitHash).replace(/\{\{currentCommitHash\}\}/g,s.currentCommitHash).replace(/\{\{branchName\}\}/g,s.branchName)):void 0)??void 0);this.log("debug","MERGE",`PR prompt: ${r.substring(0,200)}...`);const c=this.runner;let l=null;const p=c.runStreamed(r,{cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),allowAskUser:!this.isOneShotExecution(),structuredOutputSchema:{type:"json_schema",schema:to}});for await(const e of p){if(this.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){l=e;break}const n=t?e:this.messageFilter.filter(e);null!==n&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}if(!l)throw new Error("Merge-request did not return a result message");if("success"!==l.subtype)throw new Error("Merge-request did not return a successful result message");const d=so(l),u=await this.workClient.sendMergeRequest(d.title,d.description),m=`${d.userMessage}\n\n✅ Pull request created successfully!\nNumber: #${u.pullRequestNumber}\nURL: ${u.pullRequestUrl}`,h={input_tokens:l.usage.input_tokens??0,cached_input_tokens:l.usage.cache_read_input_tokens??0,output_tokens:l.usage.output_tokens??0};this.workClient.sendTaskMessage(this.getChatSenderMeta(),bs({sessionId:l.session_id,model:this.options.input.model??"unknown",numTurns:l.num_turns,usage:h,result:m}),{groupId:this.currentGroupId??void 0})}catch(e){const t=e instanceof Error?e.message:String(e);this.log("error","MERGE","Merge-request failed:",e),this.workClient.sendSystemErrorMessage(`❌ Merge-request failed: ${t}\n\nPlease check git status and try again, or create the PR manually.`,{groupId:this.currentGroupId??void 0})}var n,s}async executeBashCommand(e){if(!re.isDirectBashAllowed())return this.log("warn","BASH","Direct bash execution is disabled by global settings"),void this.workClient.sendSystemErrorMessage("Direct bash execution is disabled by global settings.",{groupId:this.currentGroupId??void 0});this.log("info","BASH",`Executing command: ${e}`);const t={senderType:"agent",senderId:"bash",senderName:"bash"},n=await Mi(e,this.workingDirectory,{onOutput:e=>{this.workClient.sendTaskMessage(t,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 Di({workingDirectory:this.workingDirectory,workClient:this.workClient,repositoryId:this.options.input.repositoryId,gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl,logger:this.logger,askUser:e=>this.askUser(e,{onTimeout:"abort_task"}),commitChanges:()=>this.commitCurrentChangesWithAgent()})}async commitCurrentChangesWithAgent(){this.log("info","MERGE","Generating commit message with agent"),await mo({runner:this.runner,workingDirectory:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),schemaTarget:"claude",onStreamMessage:async e=>{const t=this.taskAgentsMap.size>1?e:this.messageFilter.filter(e);null!==t&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}}),this.log("info","MERGE","Committed changes with agent-generated message")}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(){if(this.log("info","AGENT",`Starting Claude agent for task ${this.taskId}`),this.isStopping)return void this.log("info","AGENT",`Skipping Claude run for task ${this.taskId} because worker is stopping`);if(this.isOneShotExecution())return void await this.runClaudeOneShot();const e=this.currentAgentSessionId,t=this.runner,n=this.getRunnerModeConfig(),s="group_chat"===n.mode||"group_work"===n.mode,a=this.createPermissionHandler(),i=this.buildSystemHooks({trackBackgroundTasks:!0,trackPrimaryAgentStop:!0});this.initializePermissionModeState();const o=t.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:e,abortController:this.abortController,initialPermissionMode:this.getPermissionModeSnapshot()??void 0,stderr:e=>{this.log("debug","SDK",e)},modeConfig:n,agentrixTools:this.agentrixTools,allowAskUser:!this.isOneShotExecution(),visionModel:this.options.input.visionModel,canUseTool:a,hooks:i,maxTurns:this.options.input.maxTurns??void 0,structuredOutputSchema:this.getStructuredOutputSchema()});this.loopPermissionModeSetter=o.setPermissionMode??null,this.activePermissionMode=null,this.lastBroadcastPermissionMode=null,this.broadcastPermissionMode(this.getPermissionModeSnapshot()),await this.flushDesiredPermissionMode(),(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(!e){if(this.isStopping)break;continue}this.updateAgentRunning(!0),o.push(e);const t=e.__localSequence;void 0!==t&&(this.markPrimaryMessageProcessed(t),delete e.__localSequence)}}catch(e){this.log("error","AGENT","Message pump failed:",e),this.stopTask("event")}})();for await(const e of o.events)this.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e,s);this.resetPrimaryPermissionState(),this.log("info","AGENT",`Claude agent finished for task ${this.taskId}`)}async runClaudeOneShot(){const e=this.runner,t=this.getRunnerModeConfig(),n="group_chat"===t.mode||"group_work"===t.mode,s=this.createPermissionHandler(),a=this.buildSystemHooks({trackBackgroundTasks:!0,trackPrimaryAgentStop:!0});this.loopPermissionModeSetter=null,this.activePermissionMode=null,this.lastBroadcastPermissionMode=null,this.initializePermissionModeState(),this.broadcastPermissionMode(this.getPermissionModeSnapshot());const i=await this.coordinator.waitForAgentMessage();if(!i)return this.isStopping||this.stopTask("oneshot_complete"),this.resetPrimaryPermissionState(),void this.log("info","AGENT",`Claude oneshot finished for task ${this.taskId} without runnable message`);const o=i.__localSequence;void 0!==o&&(this.markPrimaryMessageProcessed(o),delete i.__localSequence),this.updateAgentRunning(!0);try{const o=e.runStreamed(i,{cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:this.currentAgentSessionId,abortController:this.abortController,initialPermissionMode:this.getPermissionModeSnapshot()??void 0,stderr:e=>{this.log("debug","SDK",e)},modeConfig:t,agentrixTools:this.agentrixTools,allowAskUser:!1,visionModel:this.options.input.visionModel,canUseTool:s,hooks:a,maxTurns:this.options.input.maxTurns??void 0,structuredOutputSchema:this.getStructuredOutputSchema()});for await(const e of o)this.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e,n);this.isStopping||this.stopTask("oneshot_complete")}finally{this.resetPrimaryPermissionState(),this.log("info","AGENT",`Claude oneshot finished for task ${this.taskId}`)}}async handlePrimaryRunnerMessage(e,t){if("system"===e.type&&"init"===e.subtype)return this.workClient.sendUpdateTaskAgentSessionId(e.session_id),this.workClient.sendTaskSlashCommandsUpdate(co(e.slash_commands??[]),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(),void this.updateAgentRunning(!0);if("result"===e.type)return await this.handleSdkResultMessage(e),this.refreshGroupId(),void this.updateAgentRunning(!1);"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})}resetPrimaryPermissionState(){this.loopPermissionModeSetter=null,this.activePermissionMode=null}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,"oneshot_complete"===e&&(this.exitReason="oneshot_complete",this.log("info","AGENT","One-shot execution completed, stopping task")),"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(),"oneshot_complete"!==e&&this.abortController.abort())}async handleAskUserQuestionPermission(e){const t=e,n=Array.isArray(t.questions)?t.questions:[];if(0===n.length)return this.log("warn","PERMISSION","AskUserQuestion missing questions"),{behavior:"deny",message:"AskUserQuestion missing questions"};const s=n.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]}));try{const e=await this.askUser(s),a={};for(let t=0;t<n.length;t+=1){const s=n[t]?.question;if(!s)continue;const i=e.answers?.[t];"string"==typeof i&&(a[s]=i)}return{behavior:"allow",updatedInput:{...t,answers:a}}}catch(e){return this.log("warn","PERMISSION",`AskUserQuestion failed: ${e}`),{behavior:"deny",message:"AskUserQuestion failed"}}}createPermissionHandler(){return async(e,t)=>{if("AskUserQuestion"===e)return this.handleAskUserQuestionPermission(t);if("ExitPlanMode"===e)return this.handleExitPlanModePermission(t);if(this.grantedPermissions.has(e))return this.log("info","PERMISSION",`Tool "${e}" already granted, skipping`),{behavior:"allow",updatedInput:t};const n=this.pendingPermissions.get(e);if(n)return this.log("info","PERMISSION",`Tool "${e}" has pending request, waiting...`),"allow"===await n?{behavior:"allow",updatedInput:t}:{behavior:"deny",message:"Permission denied by user"};let s;this.log("info","PERMISSION",`Requesting permission for "${e}"`);const a=new Promise(e=>{s=e});this.pendingPermissions.set(e,a);try{const n=await this.requestToolPermission(e);return s(n),"allow"===n?(this.grantedPermissions.add(e),{behavior:"allow",updatedInput:t}):{behavior:"deny",message:"Permission denied by user"}}catch(e){return s("deny"),{behavior:"deny",message:"Permission request failed"}}finally{this.pendingPermissions.delete(e)}}}async handleExitPlanModePermission(e){const t=e.planFilePath??e.filePath;let n,s;if(t){const e=this.workspace.getCwd(),a=e.endsWith("/")?e:e+"/";n=t.startsWith(a)?t.slice(a.length):void 0;try{const e=await ye.readFile(t,"utf-8");s=e.length>8e3?e.slice(0,8e3)+"\n\n…(truncated)":e}catch{}}!s&&"string"==typeof e.plan&&e.plan&&(s=e.plan);const a=[{question:"Review the plan and choose how to proceed.",header:"Plan Review",multiSelect:!1,options:[{label:"Approve",description:"Approve the plan and start implementation"},{label:"Revise",description:"Need to revise the plan",additionalInput:{enabled:!0,required:!1,placeholder:"Describe what should change."}},{label:"Cancel",description:"Cancel this plan"}],planFilePath:n,planContent:s}];try{const t=await this.askUser(a,{onTimeout:"abort_task"}),n=t.answers[0],s=t.details?.[0]?.trim();return"Approve"===n?{behavior:"allow",updatedInput:e}:"Revise"===n?{behavior:"deny",message:s?`The user wants to revise the plan. Revision notes: ${s}. Please reconsider and update the plan, then call ExitPlanMode again when ready.`:"The user wants to revise the plan. Please reconsider and update the plan, then call ExitPlanMode again when ready."}:(await this.restoreConfiguredPermissionMode(),{behavior:"deny",message:"User cancelled plan review",interrupt:!0})}catch{return await this.restoreConfiguredPermissionMode(),{behavior:"deny",message:"Plan review failed or was interrupted"}}}async requestToolPermission(e){const t=[{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(t,{onTimeout:"abort_task"})).answers[0]?"allow":"deny"}catch(e){return this.log("warn","PERMISSION",`Permission request failed: ${e}`),"deny"}}async askUser(e,t={}){if(this.isOneShotExecution())throw new Error("ask_user is not supported in oneshot execution mode");const n=this.workClient;return Ui(e,this.askUserAwaiter,{sendAskUser:e=>n.sendAskUser(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0}),sendAskUserResponse:(e,t)=>n.sendAskUserResponse(e,t),onTimeoutMessage:e=>n.sendAssistantMessage(e,{groupId:this.currentGroupId??void 0}),stopTask:e=>this.stopTask(e)},t)}async onUncommittedChanges(){const e=[{question:"Uncommitted changes detected in the working directory. How would you like to proceed?",header:"Git Status",multiSelect:!1,rememberSelection:{enabled:!0,defaultValue:!0},options:[{label:"Ignore",description:"Keep changes on current branch and continue without switching"},{label:"Commit",description:"Create a commit with an agent-generated message, 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 t=await this.askUser(e,{onTimeout:"abort_task"}),n=t.answers[0],s=t.rememberAnswers?.[0]??e[0]?.rememberSelection?.defaultValue??!1;return n.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${n}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort",remember:s}}catch(e){return this.log("warn","GIT",`Failed to get user response for uncommitted changes: ${e}`),{action:"Abort",remember:!1}}}async onBranchMismatch(e){const t=[{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"}],n=[{question:`Branch mismatch detected. Current: ${e.currentBranch}. Expected: ${e.expectedBranch}. How would you like to proceed?`,header:"Git Branch",multiSelect:!1,rememberSelection:{enabled:!0,defaultValue:!0},options:t}];try{const e=await this.askUser(n,{onTimeout:"abort_task"}),t=e.answers[0],s=e.rememberAnswers?.[0]??n[0]?.rememberSelection?.defaultValue??!1;return t.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${t}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[t]||"Abort",remember:s}}catch(e){return this.log("warn","GIT",`Failed to get user response for branch mismatch: ${e}`),{action:"Abort",remember:!1}}}getRunnerMode(){const e=this.taskAgentsMap.size>1,t=this.options.input.taskType,n=!(!process.env.AGENTRIX_COMPANION_HOME&&!process.env.AGENTRIX_COMPANION_WORKSPACE);return"shadow"===t?"companion_shadow":n&&"chat"===t?"companion_chat":e?"chat"===t?"group_chat":"group_work":"chat"===t?"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)}getStructuredOutputSchema(){return ho(this.options.input.outputSchema)}createAgentrixTools(){const e=this.taskAgentsMap.size>1;if("companion_shadow"===this.getRunnerMode()){const e=this.options.input.chatId,t=this.options.input.userId,n=re.resolveDataDir(t,e);this.chatHistoryDb=Ys({dataDir:n,taskId:e})}return{createTask:Ma(t={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,t)=>this.invokeAgent(e,t),assign:(e,t,n)=>this.assignWork(e,t,n),setPendingNavigateTaskId:e=>{this.pendingNavigateTaskId=e},visionModel:this.options.input.visionModel}),createSoloTask:Ra(t),createGroupTask:Oa(t),replyToSubTask:Ca(t),changeTaskTitle:Aa(t),askUser:Da(t),getTaskHistory:$a(t),getTaskAgents:_a(t),listSubTask:Pa(t),invoke:Na(t),assign:ja(t),updateAgentInfo:Ua(t),sendReminder:Ha(t),listTasks:qa(t),readConversation:La(t),uploadFile:Ga(t),listAgents:Wa(t),analyzeImage:Ba(t),scheduleTask:za(t)};var t}resolveTaskAgentName(e){return this.taskAgentsMap.get(e)?.name||""}getChatSenderMeta(){return{senderType:"agent",senderId:this.primaryAgentId,senderName:this.primaryAgentName}}sendAgentErrorMessage(e,t,n,s){const a=t||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${a}: ${n}`}]}};this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:a},i,{groupId:s?.groupId})}async invokeAgent(e,t){const n=this.buildSubAgentHistoryContext(e,t);if(!n)return!1;const s=this.taskAgentsMap.get(e),a=s?.type||"claude";let i=this.agentQueues.get(e);i||(i=new io,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();try{const s=await Yi.create(a,e,{logger:this.log.bind(this),context:this.agentContext}),i=this.getGroupAgents()||[],r={mode:"reply",supportChangeTitle:!1,groupAgents:i},l=this.createPermissionHandler(),p=this.buildSystemHooks({trackBackgroundTasks:!1}),d=ya(),u=s.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:n.sessionId,abortController:this.abortController,modeConfig:r,agentrixTools:this.agentrixTools,allowAskUser:!this.isOneShotExecution(),canUseTool:l,hooks:p,maxTurns:this.options.input.maxTurns??void 0,structuredOutputSchema:this.getStructuredOutputSchema()});let m=n.message;if("codex"===a&&!n.sessionId){const t=[gs(e,i),"=== CONVERSATION STREAM START FROM HERE ===",ys(n.message)].join("\n\n").trim();t&&(m=t)}u.push(m);const h=n.lastSequence;let g=!1;n.sessionId&&(this.historyDb.updateAgentLastSequence(e,h),g=!0);let f=!1;for await(const n of u.events){if("system"===n.type&&"init"===n.subtype){this.historyDb?.upsertAgentSession(e,n.session_id),g||(this.historyDb.updateAgentLastSequence(e,h),g=!0);continue}if("result"===n.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},n,{groupId:t}),f=!0;break}const s=c?n:d.filter(n);s&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},s,{groupId:t})}}catch(t){this.log("error","INVOKE",`Invoke failed for ${e}:`,t)}finally{this.coordinator?.setAgentRunning(e,o,!1)}}),!0}async assignWork(e,t,n){const s=this.taskAgentsMap.get(e),a=s?.type||"claude";let i=this.agentQueues.get(e);i||(i=new io,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 s=this.newMessageGroupId();var i;n&&this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},(i=n,{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 n=await Yi.create(a,e,{logger:this.log.bind(this),context:this.agentContext}),i={mode:"work",supportChangeTitle:!1},r=this.createPermissionHandler(),l=this.buildSystemHooks({trackBackgroundTasks:!1}),p=ya(),d=n.loop({cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:i,agentrixTools:this.agentrixTools,allowAskUser:!this.isOneShotExecution(),canUseTool:r,hooks:l,maxTurns:this.options.input.maxTurns??void 0,structuredOutputSchema:this.getStructuredOutputSchema()});d.push(t);let u=!1;for await(const t of d.events){if("system"===t.type&&"init"===t.subtype)continue;if("result"===t.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},t,{groupId:s}),u=!0;break}const n=c?t:p.filter(t);n&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},n,{groupId:s})}}catch(t){this.log("error","RUN_TASK",`Run task failed for ${e}:`,t);const n=t instanceof Error?t.message:String(t);this.sendAgentErrorMessage(e,o,`I meet some error: ${n}`,{groupId:s})}finally{this.coordinator?.setAgentRunning(e,o,!1)}})}buildSubAgentHistoryContext(e,t){const n=this.historyDb;if(!n)return this.log("warn","HISTORY","Task history DB unavailable; delegate cannot build context."),null;const s=n.getAgentSessions().get(e),a=n.getAgentLastSequences().get(e)??0,i=n.pageRecentMessagesAfter(a,20);if(0===i.data.length&&!t)return null;const o=this.mergeConsecutiveHumanMessages(i.data),r=this.buildHistoryMessages(o,t);return r?{message:r,sessionId:s,lastSequence:i.data.length>0?i.data[i.data.length-1].localSequence:a}:null}buildHistoryMessages(e,t){const n=[];for(const t of e){const e=wa(t);e&&n.push(e)}if(0===n.length&&!t)return null;let s=n.join("\n");return t&&(s=`<hint>\n${t}\n</hint>\n\n${s}`),{type:"user",message:{role:"user",content:s},parent_tool_use_id:null,session_id:""}}buildSystemHooks(e){const t=e?.trackBackgroundTasks??!0,n=e?.trackPrimaryAgentStop??!1,s={};return t&&(s.PostToolUse=async e=>(this.syncPermissionModeFromPostToolUse(e),this.trackBackgroundTaskFromPostToolUse(e),{})),n&&(s.Stop=async()=>(this.updateAgentRunning(!1),{})),s}trackBackgroundTaskFromPostToolUse(e){if(!e||"object"!=typeof e)return void this.log("debug","TASK","PostToolUse hook input is not an object");const t=e,n=t.tool_input;if(!n||!0!==n.run_in_background)return;const s=this.extractBackgroundTaskId(t.tool_response);if(!s)return this.log("debug","TASK",`PostToolUse(${t.tool_name}) run_in_background=true but no task_id found, using anonymous tracking`),void this.coordinator?.setAnonymousBackgroundTaskRunning(!0);this.coordinator?.setBackgroundTaskRunning(s,!0),this.log("info","TASK",`Background task started: ${s} (tool: ${t.tool_name})`)}syncPermissionModeFromPostToolUse(e){if(!e||"object"!=typeof e)return;const t=(n=e.tool_name,s=this.configuredPermissionMode,"EnterPlanMode"===n?"plan":"ExitPlanMode"===n?s:null);var n,s;t&&this.confirmPermissionModeApplied(t)}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 t=new Set,n=new Set,s=e=>{if("string"!=typeof e)return;const n=e.trim();n&&t.add(n)},a=e=>{if(null==e)return;if("string"==typeof e)return void(e=>{const t=/(task[_-]?id|agent[_-]?id|shell[_-]?id)["'\s:=]+([A-Za-z0-9._:-]+)/gi;let n;for(;null!==(n=t.exec(e));)s(n[2])})(e);if("object"!=typeof e)return;if(n.has(e))return;if(n.add(e),Array.isArray(e)){for(const t of e)a(t);return}const t=e;"string"==typeof t.task_id&&s(t.task_id),"string"==typeof t.taskId&&s(t.taskId),"string"==typeof t.agent_id&&s(t.agent_id),"string"==typeof t.agentId&&s(t.agentId),"string"==typeof t.shell_id&&s(t.shell_id),"string"==typeof t.shellId&&s(t.shellId);for(const e of Object.values(t))a(e)};a(e);const i=[...t];return i.length>1&&this.log("warn","TASK",`Multiple background task ids extracted (${i.join(", ")}), using first id ${i[0]}`),i[0]}createWorkerClientConfig(e,t,n){const s=this.options.input.agentId,a=this.taskAgentsMap.get(s)?.name;return{config:{userId:e,taskId:t,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:s,agentName:a,cwd:n,serverUrl:re.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:te(this.credentials.token,this.credentials.machineId,t),dataEncryptionKey:this.options.dataEncryptionKey??null,keepAliveConfig:{intervalMs:2e4,event:"worker-alive",payloadGenerator:()=>{const e=this.coordinator?.getStatus(),n="running"===e?.state?"worker-running":"worker-ready";return{eventId:N(),status:n,taskId:t,machineId:this.credentials.machineId,timestamp:Date.now().toString(),activeAgents:this.coordinator?.getActiveAgents(),permissionMode:this.getPermissionModeSnapshot()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...t)=>this.logger.info(`[SOCKET] ${e}`,...t)},handlers:{attachmentsDir:re.resolveAttachmentsDir(e,t),noVision:!!this.options.input.visionModel,logger:(e,t,n,...s)=>{this.log(e,t,n,...s)},stopTask:async()=>{this.stopTask("event")},shouldPersistTaskMessage:async e=>!Z(e)||!this.shouldDropHeartbeatWhileBusy()||(this.log("debug","WORKER","Dropping heartbeat at WorkerClient receive stage: agent is running"),!1),onTaskMessage:async(e,t)=>{if(z(e)){const[t,n]=this.askUserAwaiter.entries().next().value||[];t&&n&&(this.askUserAwaiter.delete(t),n(e))}},onTaskInfoUpdate:async e=>{Ni(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 t=va(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(t)},onSubTaskAskUser:async e=>{const t=xa(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(t)}}}}async exitWorker(e){this.log("info","WORKER",`Exiting with reason: ${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.sendTerminalErrorResult(e,{groupId:this.currentGroupId??void 0})}log(e,t,n,...s){this.logger&&this.logger[e](`[${t}] ${n}`,...s)}get taskId(){return this.options.input.taskId}async handleSdkResultMessage(e){let t,n;try{const e=await this.workspace.prepareResultArtifacts({onPatchError:e=>{this.log("warn","GIT","Failed to write patch diff for result:",e)}});t=e.artifacts,n=e.artifactVersion}catch(e){this.log("warn","GIT","Failed to prepare git artifacts for result:",e)}const s=this.getRunnerMode(),a="group_chat"===s||"group_work"===s,i=this.pendingNavigateTaskId;if(this.pendingNavigateTaskId=null,a?this.workClient.sendTaskEvent(this.getChatSenderMeta(),e,{...t?{artifacts:t}:{},groupId:this.currentGroupId??void 0,navigateToTaskId:i??void 0}):this.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{...t?{artifacts:t}:{},groupId:this.currentGroupId??void 0,navigateToTaskId:i??void 0}),n)try{await _i(this.options.input.userId,this.taskId,n)}catch(e){this.log("warn","GIT","Failed to mark artifact version as sent:",e)}}}class xo{static async calculateFinalCwd(e){const{repositorySourceType:t,cwd:n,userCwd:s,userId:i,taskId:o,forceUserCwd:r,useWorktree:c}=e,l=e=>ki(e)||e;if(n)return l(n);const p=re.resolveProjectDir(i,o);if("directory"===t&&s){const e=l(s.replace(/^~/,a()));return r||!1===c?e:await this.shouldUseWorktree(e)?l(p):e}return l(p)}static async shouldUseWorktree(e){try{return!ii(e)&&await Xa(e)}catch{return!1}}}var yo=Ut(me);class bo{constructor(e,t){this.credentials=e,this.options=t}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;exitReason="completed";isOneShotExecution(){return fo(this.options.input)}refreshGroupId(){this.currentGroupId=`group-${se()}`}async start(){try{await this.initialize(),await this.handleEvent(),await this.runCodex(),await this.exitWorker(this.exitReason)}catch(e){if(!this.isStopping){this.isStopping=!0,this.askUserAwaiter.clear(),this.coordinator?.stop(),this.log("warn","AGENT","Fatal error:",e);const t=e instanceof Error?e.message:String(e);throw await this.exitWorker("error",t),e}this.log("info","AGENT",`Task ${this.taskId} stopped gracefully`),await this.exitWorker(this.exitReason)}finally{process.exit(0)}}async initialize(){const e=this.options.input.taskId,t=this.options.input.userId;this.logger=this.createLogger({type:"worker",taskId:e}),this.dataEncryptionKey=this.options.dataEncryptionKey??null;const n=Ii(this.options.input),s=await xo.calculateFinalCwd(n),a={...n,cwd:s};this.log("info","INIT",`Phase 1: Working directory: ${s}`);const i=this.createWorkerClientConfig(t,e,s),o=re.resolveDataDir(t,e);this.historyDb=Ys({dataDir:o,taskId:e});const r=new ha(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 l=new Zi({options:a,handlers:this.createWorkspaceHandlers(r,s)}),{initialCommitHash:p,gitStateResult:d,setupAction:u}=await l.setup();this.workspace=l,this.log("info","INIT","Phase 7: Workspace setup complete"),r.sendWorkerInitialized(),r.sendTaskSlashCommandsUpdate(co()),this.log("info","INIT","Phase 8: Initialization finalized"),await this.registerWithDaemon(s),this.log("info","INIT","Phase 9: Registered with daemon"),this.log("info","WORKSPACE",`Prepared ${this.options.input.repositorySourceType} workspace via ${u} at ${s} (${p||"none"})`),this.context={credentials:this.credentials,options:this.options,workClient:r,workingDirectory:s,initialCommitHash:p,logger:this.logger},process.env.AGENTRIX_WORKING_DIR=s,process.env.AGENTRIX_WORKING_USER=t,process.env.AGENTRIX_WORKING_TASK=e,this.options.input.environmentVariables&&Object.entries(this.options.input.environmentVariables).forEach(([e,t])=>{null!=t&&(process.env[e]=String(t))}),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,t){return this.isOneShotExecution()?{onRepositoryDetected:t=>{e.associateRepository(t.host,t.owner,t.repo,t.url)},onUncommittedChanges:async()=>{throw new Error("Uncommitted changes require user input, which is not supported in oneshot execution mode")},onCommitUncommittedChanges:async()=>this.commitCurrentChangesWithAgent(t),onBranchMismatch:async()=>{throw new Error("Branch mismatch requires user input, which is not supported in oneshot execution mode")}}:{onRepositoryDetected:t=>{e.associateRepository(t.host,t.owner,t.repo,t.url)},onUncommittedChanges:this.onUncommittedChanges.bind(this),onCommitUncommittedChanges:async()=>this.commitCurrentChangesWithAgent(t),onBranchMismatch:this.onBranchMismatch.bind(this)}}async registerWithDaemon(e){const t=this.options.input.taskId,n=await Tt(t,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});n.error?this.log("warn","DAEMON",`Failed to report session ${t}:`,n.error):this.log("info","DAEMON",`Session ${t} registered`)}createMessageCoordinator(e,t){return this.coordinator=new Ri({workerType:"codex",workClient:e,handlers:{onNormalMessage:async e=>this.convertSDKMessageToCodexInput(e),onBashCommand:async(e,t)=>{await this.executeBashCommand(e)},onMergeRequest:async e=>{await this.executeMergeRequest()},onMergePr:async()=>{await this.executeMergePr()},onNewSession:async()=>{await this.executeNewSession()}},logger:(e,t,n)=>{const s=e;this.log(s,t,n)},idleTimeoutMs:t,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}async handleEvent(){if("task-message"===this.options.input.event){const{eventId:e,message:t}=this.options.input.eventData;t&&K(t)&&"user"===t.type&&(await this.coordinator.enqueue(t),e&&this.workClient?.sendEventAck(e))}}async executeMergeRequest(){this.refreshGroupId(),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 ni(this.context.workingDirectory)&&await this.commitCurrentChangesWithAgent();const e=await si(this.context.workingDirectory),t=this.context.initialCommitHash,n=await ui(this.context.workingDirectory);if(this.log("info","MERGE",`Pushing branch ${n} to remote`),await Ci(this.context.workingDirectory,n,!1,{gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl}),this.log("info","MERGE","Successfully pushed branch to remote"),!t){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 ri(this.context.workingDirectory,t,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 s=Pi(t);this.log("debug","MERGE",`PR prompt: ${s.substring(0,200)}...`);const a=this.options.input.agentId??"default",i=await Yi.create("codex",a),o={mode:"work",supportChangeTitle:!1},r=i.runStreamed(s,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,abortController:this.abortController,modeConfig:o,structuredOutputSchema:{type:"json_schema",schema:no}});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 t=this.filterMessages(e);null!==t&&this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}if(!c)throw new Error("Merge-request did not return a result message");const l=so(c);await this.createPullRequest(l.title,l.description),this.sendMessage(l.userMessage)}catch(e){const t=e instanceof Error?e.message:String(e);this.log("error","MERGE","Merge-request failed:",e),this.context.workClient.sendSystemErrorMessage(`Merge-request failed: ${t}\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){if(this.refreshGroupId(),!re.isDirectBashAllowed())return this.log("warn","BASH","Direct bash execution is disabled by global settings"),void this.context.workClient.sendSystemErrorMessage("Direct bash execution is disabled by global settings.",{groupId:this.currentGroupId??void 0});this.log("info","BASH",`Executing command: ${e}`);const t=await Mi(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: ${t})`)}async executeMergePr(){this.refreshGroupId(),await Di({workingDirectory:this.context.workingDirectory,workClient:this.context.workClient,repositoryId:this.options.input.repositoryId,gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl,logger:this.context.logger,allowInteractive:!this.isOneShotExecution(),askUser:e=>this.askUser(e,{onTimeout:"abort_task"}),commitChanges:()=>this.commitCurrentChangesWithAgent()})}async commitCurrentChangesWithAgent(e){const t=this.options.input.agentId??"default",n=await Yi.create("codex",t),s=e||this.context?.workingDirectory;if(!s)throw new Error("Working directory is not available for commit generation");this.log("info","MERGE","Generating commit message with agent"),await mo({runner:n,workingDirectory:s,model:this.currentModel||this.options.input.model||void 0,abortController:this.abortController,modeConfig:{mode:"work",supportChangeTitle:!1},schemaTarget:"openai",onStreamMessage:async e=>{const t=this.filterMessages(e);null!==t&&this.getActiveWorkClient().sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}}),this.log("info","MERGE","Committed changes with agent-generated message")}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")}getStructuredOutputSchema(){return ho(this.options.input.outputSchema)}async runCodex(){this.log("info","AGENT",`Starting Codex agent for task ${this.taskId}`),this.currentModel=Ki(this.options.input.model),this.currentModel?this.log("info","AGENT",`Using model: ${this.currentModel}`):this.log("info","AGENT","Using default model from Codex config (model name unavailable)");const e=this.options.input.agentId??"default",t=await Yi.create("codex",e),n={mode:"work",supportChangeTitle:!1};if(this.isStopping)return void this.log("info","AGENT",`Skipping Codex run for task ${this.taskId} because worker is stopping`);if(this.isOneShotExecution())return void await this.runCodexOneShot(t,n);const s=t.loop({cwd:this.context.workingDirectory,model:this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:n,structuredOutputSchema:this.getStructuredOutputSchema()});(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(e)this.refreshGroupId(),this.updateAgentRunning(!0),s.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 s.events)this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e);this.log("info","AGENT",`Codex agent finished for task ${this.taskId}`)}async runCodexOneShot(e,t){const n=await this.coordinator.waitForAgentMessage();if(!n)return this.isStopping||this.stopTask("oneshot_complete"),void this.log("info","AGENT",`Codex oneshot finished for task ${this.taskId} without runnable message`);this.updateAgentRunning(!0);try{this.refreshGroupId();const s=e.runStreamed(n,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:t,structuredOutputSchema:this.getStructuredOutputSchema()});for await(const e of s)this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e);this.isStopping||this.stopTask("oneshot_complete")}finally{this.log("info","AGENT",`Codex oneshot finished for task ${this.taskId}`)}}async handlePrimaryRunnerMessage(e){if("system"===e.type&&"init"===e.subtype)return this.threadId=e.session_id,this.context.workClient.sendUpdateTaskAgentSessionId(e.session_id),this.context.workClient.sendTaskSlashCommandsUpdate(co(e.slash_commands??[]),e.session_id),this.log("info","AGENT",`Thread started: ${e.session_id}`),void this.updateAgentRunning(!0);const t=this.filterMessages(e);null!==t&&("result"===e.type?await this.handleSdkResultMessage(t):this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})),"result"!==e.type?this.updateAgentRunning(!0):this.updateAgentRunning(!1)}filterMessages(e){const t=e,n=t?.message?.content;if(!n||"string"==typeof n)return e;const s=n.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"===t.type&&"tool_result"!==e.type));return 0===s.length?null:(t.message.content=s,t)}sendMessage(e){const t={type:"assistant",message:{id:se().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:se().toString()};this.getActiveWorkClient().sendTaskMessage(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}async askUser(e,t={}){if(this.isOneShotExecution())throw new Error("ask_user is not supported in oneshot execution mode");const n=this.getActiveWorkClient();return Ui(e,this.askUserAwaiter,{sendAskUser:e=>n.sendAskUser(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0}),sendAskUserResponse:(e,t)=>n.sendAskUserResponse(e,t),onTimeoutMessage:e=>this.sendMessage(e),stopTask:e=>this.stopTask(e)},t)}getActiveWorkClient(){const e=this.context?.workClient??this.workClient;if(!e)throw new Error("[WORKER] WorkerClient not available");return e}resolveTaskAgentName(e){const t=this.options.input.taskAgents??[];return t.find(t=>t.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,rememberSelection:{enabled:!0,defaultValue:!0},options:[{label:"Ignore",description:"Keep changes on current branch and continue without switching"},{label:"Commit",description:"Create a commit with an agent-generated message, 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 t=await this.askUser(e,{onTimeout:"abort_task"}),n=t.answers[0],s=t.rememberAnswers?.[0]??e[0]?.rememberSelection?.defaultValue??!1;return n.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${n}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort",remember:s}}catch(e){return this.log("warn","GIT",`Failed to get user response for uncommitted changes: ${e}`),{action:"Abort",remember:!1}}}async onBranchMismatch(e){const t=[{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"}],n=[{question:`Branch mismatch detected. Current: ${e.currentBranch}. Expected: ${e.expectedBranch}. How would you like to proceed?`,header:"Git Branch",multiSelect:!1,rememberSelection:{enabled:!0,defaultValue:!0},options:t}];try{const e=await this.askUser(n,{onTimeout:"abort_task"}),t=e.answers[0],s=e.rememberAnswers?.[0]??n[0]?.rememberSelection?.defaultValue??!1;return t.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${t}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[t]||"Abort",remember:s}}catch(e){return this.log("warn","GIT",`Failed to get user response for branch mismatch: ${e}`),{action:"Abort",remember:!1}}}async createPullRequest(e,t){this.log("info","MERGE",`Creating PR: ${e}`);try{const n=await this.context.workClient.sendMergeRequest(e,t);this.sendMessage(`✅ Pull request created successfully!\nNumber: #${n.pullRequestNumber}\nURL: ${n.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 t=e.message.content;if("string"==typeof t)return t;if(Array.isArray(t)){const e=[],n=re.resolveAttachmentsDir(this.options.input.userId,this.taskId);for(const s of t)if("text"===s.type&&s.text)e.push(s.text);else if("image"===s.type&&s.source&&s.source.url){const t=s.source.url;try{const{filePath:s}=await na(t,n,!1);this.log("info","IMAGE",`Downloaded image from ${t} to ${s}`),e.push(`Image: ${s}`)}catch(e){this.log("error","IMAGE",`Failed to download image from ${t}:`,e)}}else if("document"===s.type&&s.source&&s.source.url){const t=s.source.url;try{const{filePath:a,mimeType:i,filename:o}=await na(t,n,!0);this.log("info","DOCUMENT",`Downloaded document from ${t} to ${a}`);const r=s.title||o;e.push(`Document: ${a}\nTitle: ${r}\nType: ${i}`)}catch(e){this.log("error","DOCUMENT",`Failed to download document from ${t}:`,e)}}const s=e.map(e=>e.trim()).filter(Boolean).join("\n\n").trim();if(s)return s}return""}stopTask(e){this.isStopping||(this.isStopping=!0,"oneshot_complete"===e&&(this.exitReason="oneshot_complete",this.log("info","AGENT","One-shot execution completed, stopping task")),"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(),"oneshot_complete"!==e&&this.abortController.abort())}updateAgentRunning(e){this.coordinator?.updateAgentRunning(e)}createWorkerClientConfig(e,t,n){const s=this.options.input.agentId,a=this.options.input.taskAgents?.find(e=>e.id===s)?.name;return{config:{userId:e,taskId:t,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:s,agentName:a,cwd:n,serverUrl:re.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:te(this.credentials.token,this.credentials.machineId,t),dataEncryptionKey:this.dataEncryptionKey,keepAliveConfig:{intervalMs:2e4,event:"worker-alive",payloadGenerator:()=>{const e=this.coordinator?.getStatus(),n="running"===e?.state?"worker-running":"worker-ready";return{eventId:N(),status:n,taskId:t,machineId:this.credentials.machineId,timestamp:Date.now().toString()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...t)=>(this.context?.logger??this.logger)?.info(`[SOCKET] ${e}`,...t)},handlers:{stopTask:async()=>{this.stopTask("event")},onTaskMessage:async e=>{if(z(e)){const[t,n]=this.askUserAwaiter.entries().next().value||[];return void(t&&n&&(this.askUserAwaiter.delete(t),n(e)))}K(e)&&"user"===e.type&&await this.coordinator.enqueue(e)},onTaskInfoUpdate:async e=>{Ni(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,t){this.coordinator&&this.coordinator.stop(),this.log("info","WORKER",`Exiting with reason: ${e} for task ${this.taskId}`),"error"===e&&t?await this.context.workClient.sendErrorMessageAndExit(t):(this.context.workClient.sendWorkerExit(e),await this.context.workClient.disconnect()),this.historyDb&&this.historyDb.close()}createLogger(e){const{createLogger:t}=yo;return t(e)}log(e,t,n,...s){const a=this.context?.logger??this.logger;a&&a[e](`[${t}] ${n}`,...s)}get taskId(){return this.options.input.taskId}getCurrentModel(){return this.currentModel||"unknown"}async handleSdkResultMessage(e){let t,n;try{const e=await this.workspace.prepareResultArtifacts({onPatchError:e=>{this.log("warn","GIT","Failed to write patch diff for result:",e)}});t=e.artifacts,n=e.artifactVersion}catch(e){this.log("warn","GIT","Failed to prepare git artifacts for result:",e)}if(this.context.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{...t?{artifacts:t}:{},groupId:this.currentGroupId??void 0}),n)try{await _i(this.options.input.userId,this.taskId,n)}catch(e){this.log("warn","GIT","Failed to mark artifact version as sent:",e)}}}function wo(){const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(!e)return;if(e.includes("/")||e.includes("\\")||e.startsWith(".")){const t=x.isAbsolute(e)?e:x.resolve(e);return o.existsSync(t)?t:void 0}const t="win32"===process.platform?"where":"which",n=ze(t,[e],{encoding:"utf-8"});return 0===n.status?n.stdout.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0):void 0}function ko(e){const t=e.map(e=>e.toLowerCase().trim().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean);return[...new Set(t)].slice(0,8)}function Io(e,t=""){const n=o.readdirSync(e,{withFileTypes:!0}),s=[];for(const a of n){const n=t?`${t}/${a.name}`:a.name;"node_modules"!==a.name&&".git"!==a.name&&(a.isDirectory()?s.push(...Io(x.join(e,a.name),n)):s.push(n))}return s}async function So(e,t,n){const s=Io(e).map(e=>` - ${e}`).join("\n");return new Promise((a,i)=>{let o=!1,r=null;const c=e=>{o||(o=!0,clearTimeout(p),a(e))},l=e=>{o||(o=!0,clearTimeout(p),i(e))},p=setTimeout(()=>{c({approved:!1,reasons:["Review timed out after 10 minutes"],tags:[]})},6e5),d=(u=e=>{r=e,c(e)},Ye("hive_publish_review","Submit your security review decision for this Hive publish request. You MUST call this tool exactly once after reviewing all source files.",{approved:Ge.boolean().describe("true if the code passes security review, false if it must be rejected"),reasons:Ge.array(Ge.string()).describe("If rejected: list each specific issue found. If approved: briefly state what was checked."),tags:Ge.array(Ge.string()).describe("3-8 concise marketplace discovery tags describing the agent or skill capability. Use lowercase kebab-case.")},async e=>(u({approved:e.approved,reasons:e.reasons,tags:ko(e.tags)}),{content:[{type:"text",text:"Review decision recorded."}]})));var u;const m=Xe({name:"hive_review",version:"1.0.0",tools:[d]}),h=[`Review the ${n} "${t}" for security issues before publishing to Hive.`,"",`Source directory: ${e}`,"","Files to review:",s,"","Read each file, then call mcp__hive_review__hive_publish_review with your decision."].join("\n"),g=Je({prompt:h,options:{systemPrompt:"You are a security reviewer for the Agentrix Hive marketplace.\nYour job is to review agent/skill source code before it is published to the public repository.\n\nYou MUST check for:\n1. **Hardcoded secrets**: API keys, tokens, passwords, private keys, credentials in any file\n2. **PII exposure**: emails, phone numbers, physical addresses, names of real people\n3. **Data exfiltration**: suspicious network requests, unauthorized file uploads, sending user data to external servers\n4. **Malicious code**: eval/exec of untrusted input, shell injection, code that modifies files outside workspace\n5. **Dependency risks**: suspicious or known-malicious packages, typo-squatting package names\n6. **Permission abuse**: code that requests excessive permissions, reads sensitive system files, or accesses other users' data\n\nProcess:\n1. Read EVERY source file in the directory using the Read tool\n2. Analyze each file for the issues listed above\n3. Assign marketplace discovery tags for the source. Tags should describe what the agent/skill does, its domain, and useful capability filters.\n4. Call mcp__hive_review__hive_publish_review with your decision and tags.\n\nTag rules:\n- Provide 3-8 tags.\n- Use lowercase kebab-case, for example: web-design, code-review, react, testing, documentation.\n- Prefer functional/domain tags over generic labels.\n\nBe strict but fair: reject if ANY security issue is found. Approve if the code is clean.",permissionMode:"bypassPermissions",settingSources:["user","project","local"],maxTurns:30,cwd:e,mcpServers:{hive_review:m},pathToClaudeCodeExecutable:wo(),stderr:e=>{const t=String(e).trim();t&&console.error(`[HiveReview] Claude stderr: ${t}`)}}});(async()=>{try{for await(const e of g)if("result"===e.type&&e.is_error&&!r){const t=e.result;return void l(new Error(`Claude security review failed: ${t||"unknown Claude Code error"}`))}r||l(new Error("Claude security review finished without submitting a review decision"))}catch(e){l(e)}})()})}const To=pt(Ve);function Eo(e,t,n){const s=re.serverUrl.replace(/^http/,"ws");return Te(s,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}async function Ao(e,...t){const{stdout:n}=await To("git",t,{cwd:e});return n.trim()}function Co(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"skill"}const $o=pt(Ve);function _o(e,t,n){const s=re.serverUrl.replace(/^http/,"ws");return Te(s,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}const Po=["claude","codex","deployment","companion","hive-publish","hive-install"],Mo={claude:{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i=re.readTaskInput(n,s),o=i.dataEncryptionKey?O(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:a,input:i,dataEncryptionKey:o};await async function(e,t){const n=Ii(t.input),s=await xo.calculateFinalCwd(n),a=new vo(e,t,s);await a.start()}(e,r)}},codex:{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i=re.readTaskInput(n,s),o=i.dataEncryptionKey?O(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:a,input:i,dataEncryptionKey:o};await async function(e,t){const n=new bo(e,t);await n.start()}(e,r)}},deployment:{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i={input:re.readTaskInput(n,s)};await async function(e,t){const n=t.input,{taskId:s,sourcePath:a,targetAgentId:i,userId:r,name:c,avatar:l,isSystemAgent:p,supportLocal:d}=n;let u=null;try{if(console.log(`[Deployment] Starting deployment worker for task ${s}`),!o.existsSync(a))throw new Error(`Source path not found: ${a}`);const t=x.join(re.agentrixAgentsHomeDir,i);if(o.existsSync(t))throw new Error(`Target agent directory already exists: ${t}`);console.log(`[Deployment] Copying from ${a} to ${t}`),await go(a,t),console.log("[Deployment] Deployment completed successfully"),u=function(e,t,n){const s=re.serverUrl.replace(/^http/,"ws");return Te(s,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}(e,0,s),await new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);u.on("connect",()=>{clearTimeout(n),console.log("[Deployment] Connected to server"),u.emit("deploy-agent-complete",{eventId:N(),taskId:s,targetAgentId:i,success:!0,name:c,avatar:l,isSystemAgent:p,supportLocal:d}),console.log("[Deployment] Sent deploy-agent-complete event"),setTimeout(()=>{e()},1e3)}),u.on("connect_error",e=>{clearTimeout(n),t(e)})})}catch(e){throw console.error("[Deployment] Deployment failed:",e),u&&u.connected&&(u.emit("deploy-agent-complete",{eventId:N(),taskId:s,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)}}(e,i)}},"hive-publish":{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i={input:re.readTaskInput(n,s)};await async function(e,t){const n=t.input,{taskId:s,userId:a,sourceDir:i,gitUrl:r,version:c}=n;let l,p,{repoDir:d,name:u}=n,m=n.displayName,h=n.description,g=n.readme,f=null,v=null;try{if(n.environmentVariables)for(const[e,t]of Object.entries(n.environmentVariables))null!=t&&(process.env[e]=String(t));if(console.log(`[HivePublish] Starting for task ${s}, name=${u}`),function(e,t){if(!o.existsSync(e))throw new Error(`Source directory not found: ${e}`);if(!o.statSync(e).isDirectory())throw new Error(`Source path is not a directory: ${e}`);if("skill"===t&&!o.existsSync(x.join(e,"SKILL.md")))throw new Error(`Skill directory must contain SKILL.md: ${e}`)}(i,n.type),"skill"===n.type){const e=function(e){const t=x.join(e,"SKILL.md"),n=o.readFileSync(t,"utf-8"),s=n.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!s)throw new Error("SKILL.md must start with YAML frontmatter containing name and description");const a=s[1],i=new Map;for(const e of a.split(/\r?\n/)){const t=e.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);t&&i.set(t[1],t[2].replace(/^["']|["']$/g,"").trim())}const r=i.get("name"),c=i.get("description");if(!r)throw new Error("SKILL.md frontmatter must include name");if(!c)throw new Error("SKILL.md frontmatter must include description");return{name:Co(r),displayName:r,description:c,readme:n,repoDirName:Co(r)}}(i);u=e.name,m=e.displayName,h=e.description,g=e.readme,d=x.posix.join(d,e.repoDirName),console.log(`[HivePublish] Parsed skill metadata name=${u}, displayName=${m}`)}v=x.join(re.agentrixHomeDir,"tmp","hive-publish",s),o.mkdirSync(v,{recursive:!0}),console.log("[HivePublish] Cloning hive repo..."),await Ao(v,"clone","--depth","1",r,".");const t=x.join(v,d);if(o.mkdirSync(x.dirname(t),{recursive:!0}),"skill"===n.type&&o.existsSync(t))throw new Error(`Skill already exists in Hive repository: ${d}`);o.existsSync(t)&&o.rmSync(t,{recursive:!0,force:!0}),console.log(`[HivePublish] Copying ${i} → ${d}`),await go(i,t),await Ao(v,"add",".");const a=await async function(e){try{return await To("git",["diff","--cached","--quiet"],{cwd:e}),!1}catch(e){if("number"==typeof e?.code&&1===e.code)return!0;throw e}}(v);if(a){console.log("[HivePublish] Running Claude security review...");const e=await So(i,u,n.type);if(l=e.reasons,p=e.tags,!e.approved)throw new Error(`Security review rejected: ${e.reasons.join("; ")}`);console.log("[HivePublish] Security review passed");const t=`publish: ${d} v${c}`;await Ao(v,"commit","-m",t),console.log("[HivePublish] Pushing to remote..."),await Ao(v,"push")}else console.log("[HivePublish] No git changes to publish; using existing HEAD");const y=await Ao(v,"rev-parse","HEAD");console.log(`[HivePublish] Push succeeded, commit=${y}`),f=Eo(e,0,s),await new Promise((e,t)=>{const n=setTimeout(()=>t(new Error("WebSocket connection timeout")),1e4);f.on("connect",()=>{clearTimeout(n),f.emit("hive-publish-complete",{eventId:N(),taskId:s,success:!0,gitCommitHash:y,hasChanges:a,tags:p,name:u,displayName:m,description:h,readme:g,repoDir:d}),console.log("[HivePublish] Sent hive-publish-complete (success)"),setTimeout(e,1e3)}),f.on("connect_error",e=>{clearTimeout(n),t(e)})})}catch(t){console.error("[HivePublish] Failed:",t);try{f=f??Eo(e,0,s),await new Promise(e=>{const n=setTimeout(e,5e3),a=()=>{f.emit("hive-publish-complete",{eventId:N(),taskId:s,success:!1,error:t instanceof Error?t.message:String(t),reviewReasons:l}),clearTimeout(n),setTimeout(e,1e3)};f.connected?a():(f.on("connect",a),f.on("connect_error",()=>{clearTimeout(n),e()}))})}catch{console.error("[HivePublish] Failed to send error event")}throw t}finally{if(f&&f.disconnect(),v&&o.existsSync(v))try{o.rmSync(v,{recursive:!0,force:!0})}catch{}process.exit(0)}}(e,i)}},"hive-install":{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i={input:re.readTaskInput(n,s)};await async function(e,t){const n=t.input,{taskId:s,userId:a,sourceRepoDir:i,gitUrl:r,name:c,sourceType:l}=n,p=n.installDir??n.draftAgentDir;let d=null,u=null;try{console.log(`[HiveInstall] Starting for task ${s}, name=${c}`),u=x.join(re.agentrixHomeDir,"tmp","hive-install",s),o.mkdirSync(u,{recursive:!0}),console.log("[HiveInstall] Cloning hive repo..."),await async function(e,...t){const{stdout:n}=await $o("git",t,{cwd:e});return n.trim()}(u,"clone","--depth","1",r,".");const t=x.join(u,i);if(!o.existsSync(t))throw new Error(`Source directory not found in hive repo: ${i}`);if("skill"===l&&!o.existsSync(x.join(t,"SKILL.md")))throw new Error(`Skill directory must contain SKILL.md: ${i}`);const n=(m=p).startsWith("~/")?x.join(process.env.HOME||"",m.slice(2)):x.isAbsolute(m)?m:x.join(re.agentrixHomeDir,m);if(o.existsSync(n))throw new Error(`Target install directory already exists: ${n}`);o.mkdirSync(n,{recursive:!0}),console.log(`[HiveInstall] Copying ${i} → ${n}`),await go(t,n);const a=x.join(n,".git");o.existsSync(a)&&(o.rmSync(a,{recursive:!0,force:!0}),console.log("[HiveInstall] Removed .git from installed directory")),console.log("[HiveInstall] Install completed successfully"),d=_o(e,0,s),await new Promise((e,t)=>{const a=setTimeout(()=>t(new Error("WebSocket connection timeout")),1e4);d.on("connect",()=>{clearTimeout(a),d.emit("hive-install-complete",{eventId:N(),taskId:s,success:!0,agentDir:n}),console.log("[HiveInstall] Sent hive-install-complete (success)"),setTimeout(e,1e3)}),d.on("connect_error",e=>{clearTimeout(a),t(e)})})}catch(t){console.error("[HiveInstall] Failed:",t);try{d=d??_o(e,0,s),await new Promise(e=>{const n=setTimeout(e,5e3),a=()=>{d.emit("hive-install-complete",{eventId:N(),taskId:s,success:!1,error:t instanceof Error?t.message:String(t)}),clearTimeout(n),setTimeout(e,1e3)};d.connected?a():(d.on("connect",a),d.on("connect_error",()=>{clearTimeout(n),e()}))})}catch{console.error("[HiveInstall] Failed to send error event")}throw t}finally{if(d&&d.disconnect(),u&&o.existsSync(u))try{o.rmSync(u,{recursive:!0,force:!0})}catch{}process.exit(0)}var m}(e,i)}},companion:{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i=re.readTaskInput(n,s),o=i.dataEncryptionKey?O(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:a,input:i,dataEncryptionKey:o};await async function(e,t){const{agentDir:n,homeDir:s}=await qs();t.input.agentDir=n,process.env.AGENTRIX_COMPANION_HOME=s;const a=Ii(t.input),i=await xo.calculateFinalCwd(a),o=new vo(e,t,i);await o.start()}(e,r)}}};async function Ro(){const e=function(){try{const e=ke(le(),"package.json"),t=JSON.parse(ve(e,"utf-8"));if("string"==typeof t.version&&t.version.trim().length>0)return t.version}catch{}return"0.0.0"}();try{const t=Ue("npm view @agentrix/cli version",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();return{hasUpgrade:function(e,t){const n=e.split(".").map(Number),s=t.split(".").map(Number);for(let e=0;e<Math.max(n.length,s.length);e++){const t=n[e]||0,a=s[e]||0;if(t>a)return 1;if(t<a)return-1}return 0}(t,e)>0,currentVersion:e,latestVersion:t}}catch(t){return{hasUpgrade:!1,currentVersion:e,latestVersion:null}}}function Oo(){return"true"===process.env.AGENTRIX_DISABLE_AUTO_UPGRADE}async function Do(e){try{const{execSync:t}=await import("child_process");return console.log(""),e||(console.log($.blue("🔄 Checking for upgrades...")),e=await Ro()),e.hasUpgrade?(console.log($.blue(`🔄 Upgrading from ${e.currentVersion} to ${e.latestVersion}...`)),t("npm install -g @agentrix/cli@latest",{stdio:"inherit"}),console.log($.green("✓ Upgrade complete")),console.log(""),!0):(console.log($.green("✓ Already on latest version")),console.log(""),!0)}catch(e){return console.log(""),console.log($.yellow("⚠️ Auto-upgrade failed")),console.log($.dim(" You can upgrade manually with: npm install -g @agentrix/cli@latest")),console.log(""),!1}}async function No(e,t){const n=`${re.serverUrl}/v1/agents/${encodeURIComponent(e)}/git-url`,s=await fetch(n,{headers:{Authorization:`Bearer ${t.token}`}});return s.ok?s.json():null}function Uo(e){try{const t=c(y(e,"agent.json"),"utf-8"),n=JSON.parse(t);return"string"==typeof n.version?n.version:null}catch{return null}}function jo(e,t){const n=e=>e.split(".").map(e=>parseInt(e,10)||0),s=n(e),a=n(t);for(let e=0;e<Math.max(s.length,a.length);e++){const t=s[e]??0,n=a[e]??0;if(t>n)return!0;if(t<n)return!1}return!1}async function qo(e){const t=re.agentrixAgentsHomeDir;if(!r(t))return;let n;try{n=m(t).filter(e=>l(y(t,e)).isDirectory())}catch{return}for(const s of n){if("companion"===s||s.startsWith("draftagent-")||s.includes("."))continue;const n=y(t,s),a=y(n,"upgrade");if(r(a))continue;const i=Uo(n);ce.info(`[AGENT UPDATE] Checking ${s} (local version: ${i??"unknown"})`);try{const t=await No(s,e);if(!t||!t.gitUrl){ce.info(`[AGENT UPDATE] No git repo for ${s}, skipping`);continue}const n=`${a}.tmp-${Date.now()}`;try{const e=["git","clone","--depth=1","--branch",t.branch,t.gitUrl,n];Ke(e.join(" "),{stdio:"pipe",timeout:12e4});const o=t.subDir?y(n,t.subDir):n;if(t.subDir&&!r(o))throw new Error(`subDir "${t.subDir}" not found in cloned repo`);const c=Uo(o);if(!c||i&&!jo(c,i)){ce.info(`[AGENT UPDATE] ${s} up to date (local: ${i??"unknown"}, remote: ${c??"unknown"})`),u(n,{recursive:!0,force:!0});continue}ce.info(`[AGENT UPDATE] Update available for ${s}: ${i??"unknown"} → ${c}`),t.subDir?(d(o,a),u(n,{recursive:!0,force:!0})):d(n,a),ce.info(`[AGENT UPDATE] Staged upgrade for ${s}`)}catch(e){throw r(n)&&u(n,{recursive:!0,force:!0}),e}}catch(e){ce.warn(`[AGENT UPDATE] Check failed for ${s}: ${e}`)}}}function Lo(){const e=re.getStatePaths();return we.join(we.dirname(e.daemonStateFile),"upgrade-daemon.state.json")}function Ho(){try{const e=Lo();if(!fe.existsSync(e))return null;const t=fe.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return null}}function Go(e){try{const t=Lo();if(fe.existsSync(t)){if("number"==typeof e){const t=Ho();if(!t||t.pid!==e)return}fe.unlinkSync(t)}}catch{}}function Wo(e){try{return process.kill(e,0),!0}catch{return!1}}function Fo(){const e=Ho();return!(!e||!Wo(e.pid)&&(Go(),1))}function Bo(){const e=Ho();if(e)try{Wo(e.pid)&&process.kill(e.pid,"SIGTERM")}catch{}finally{Go()}}async function zo(){if(Oo())return"no-upgrade";const e=await Ro();if(e.hasUpgrade&&await Do(e))return await $t(),await new Promise(e=>setTimeout(e,1e3)),Xs(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref(),"upgraded";try{const e=await re.readCredentials();e&&await qo(e)}catch{}return"no-upgrade"}var Ko=Object.freeze({__proto__:null,isUpgradeDaemonRunning:Fo,startUpgradeDaemon:async function(){await async function(){!function(e){const t=Lo();fe.writeFileSync(t,JSON.stringify(e,null,2))}({pid:process.pid,startedAt:(new Date).toISOString()}),process.on("SIGTERM",()=>{Go(process.pid),process.exit(0)}),process.on("SIGINT",()=>{Go(process.pid),process.exit(0)});try{"upgraded"===await zo()&&(Xs(["upgrade-daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref(),process.exit(0))}catch(e){}for(;;){await new Promise(e=>setTimeout(e,216e5));try{"upgraded"===await zo()&&(Xs(["upgrade-daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref(),process.exit(0))}catch(e){}}}()},stopUpgradeDaemon:Bo});function Vo(e,t){const n=e.trim();if(!n)throw new Error(`${t} is required`);let s;try{s=new URL(n)}catch{throw new Error(`${t} must be a valid URL`)}if("http:"!==s.protocol&&"https:"!==s.protocol)throw new Error(`${t} must use http or https`);return s.toString().replace(/\/+$/,"")}function Xo(e){return`${Vo(e,"baseUrl")}/api/v4`}async function Jo(e,t){if(!ft.isTTY){if(void 0!==t)return t;throw new Error(`${e} is required in non-interactive mode`)}const n=xt({input:ft,output:vt});try{const s=t?` (${t})`:"";return(await n.question(`${e}${s}: `)).trim()||t||""}finally{n.close()}}async function Yo(){const e=await Vt();if(!e)throw new Error("No Agentrix auth secret found. Run `agentrix start` and complete machine binding first.");return e}function Qo(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function Zo(e){return e.webhookSecret||e.projectTriggerTokens?{webhookSecret:e.webhookSecret,projectTriggerTokens:e.projectTriggerTokens??{}}:null}async function er(e){const t=await Yo(),n=Vo(Qo(e["base-url"])??await Jo("GitLab base URL"),"baseUrl"),s=Qo(e.id)??await Jo("Git server ID",function(e){return new URL(Vo(e,"baseUrl")).hostname.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"gitlab"}(n)),a=Vo(Qo(e["api-url"])??await Jo("GitLab API URL",Xo(n)),"apiUrl"),i=(Qo(e["pat-file"])?function(e){if("-"===e)return c(0,"utf8").trim();if(!r(e))throw new Error(`File not found: ${e}`);return c(e,"utf8").trim()}(Qo(e["pat-file"])):void 0)??await async function(e){return ft.isTTY&&vt.isTTY&&"function"==typeof ft.setRawMode?new Promise((t,n)=>{let s="";const a=()=>{ft.setRawMode(!1),ft.pause(),ft.off("data",i)},i=e=>{const i=e.toString("utf8");return""===i?(a(),vt.write("\n"),void n(new Error("Interrupted"))):"\r"===i||"\n"===i?(a(),vt.write("\n"),void t(s.trim())):void(""!==i&&"\b"!==i?s+=i:s=s.slice(0,-1))};vt.write(`${e}: `),ft.setRawMode(!0),ft.resume(),ft.on("data",i)}):Jo(e)}("GitLab PAT");if(!i)throw new Error("GitLab PAT is required");let o;if(!e["skip-validate"]){const e=await async function(e,t){const{result:n,user:s}=await Ce(e,t);return{valid:n.valid,username:n.username,scopes:n.scopes,meta:n.valid&&s?{username:s.username,email:s.email||"",lastValidatedAt:(new Date).toISOString(),expiresAt:n.expiresAt}:void 0}}(a,i);if(!e.valid)throw new Error(`PAT validation failed for ${a}/user`);o=e.meta}const l=await async function(e){const t=await async function(e){return await St("/git-server/register",e)}({id:e.id,name:e.id,baseUrl:e.baseUrl,apiUrl:e.apiUrl});if(t.error||!t.gitServer)throw new Error(`Backend Git server registration failed: ${t.error||"Daemon did not return a registered Git server"}`);return{id:t.gitServer.id,baseUrl:t.gitServer.baseUrl,apiUrl:t.gitServer.apiUrl}}({id:s,baseUrl:n,apiUrl:a});o&&nn(l.id,o),Xt(l.id,{baseUrl:l.baseUrl,apiUrl:l.apiUrl}),sn(l.id,i,t);const p=en(l.id,t);console.log(JSON.stringify({id:l.id,type:"gitlab",baseUrl:l.baseUrl,apiUrl:l.apiUrl,webhookEndpointPath:Oe(l.id),webhookUrl:Re(l.id,await re.readDaemonState()),backendRegistered:!0,patConfigured:!0,patMeta:tn(l.id),webhookSecret:p},null,2))}function tr(e){console.error($.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}const nr=A(C(process.argv)).scriptName("agentrix").version(pe.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");re.getStatePaths,nr.command("upgrade","Upgrade CLI to the latest version",{},async e=>{console.log($.dim(`Current version: ${pe.version}`));const t=await Et();await Do()||process.exit(1);try{const e=await re.readCredentials();e&&(console.log($.dim("Checking agent updates...")),await qo(e))}catch{}if(t){console.log($.blue("Restarting daemon...")),await $t(),await new Promise(e=>setTimeout(e,1e3)),Xs(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();let e=!1;for(let t=0;t<50;t++)if(await new Promise(e=>setTimeout(e,100)),await Et()){e=!0;break}e?console.log($.green("✓ Daemon restarted successfully")):console.log($.yellow("⚠️ Daemon may still be starting. Run 'agentrix status' to check."))}try{const{version:e}=await import("./logger-BVnpkRi2.mjs").then(function(e){return e._});console.log($.green(`\n✓ Now running version: ${e}`))}catch{console.log($.dim("\nRun 'agentrix --version' to see the new version"))}process.exit(0)}),nr.command("doctor","System diagnostics & troubleshooting",{},async e=>{await qn(),process.exit(0)}),nr.command("logout","Logout from Agentrix",{},async e=>{try{await async function(){if(!await re.readCredentials())return void console.log($.yellow("Not currently authenticated"));console.log($.blue("This will log you out of Agentrix")),console.log($.yellow("⚠️ You will need to re-authenticate to use Agentrix again"));const e=he({input:process.stdin,output:process.stdout}),t=await new Promise(t=>{e.question($.yellow("Are you sure you want to log out? (y/N): "),t)});if(e.close(),"y"===t.toLowerCase()||"yes"===t.toLowerCase())try{try{await $t(),console.log($.gray("Stopped daemon"))}catch{}await re.clearCredentials(),console.log($.gray("Removed credentials")),console.log($.green("✓ Successfully logged out"))}catch(e){throw new Error(`Failed to logout: ${e instanceof Error?e.message:"Unknown error"}`)}else console.log($.blue("Logout cancelled"))}()}catch(e){console.error($.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}process.exit(0)}),nr.command("stop","Stop the daemon",{},async e=>{Bo(),await $t(),process.exit(0)}),nr.command("status","Show daemon and authentication status",{},async e=>{await qn("daemon"),console.log(""),await async function(){const e=await re.readCredentials();if(console.log($.bold("\nAuthentication Status\n")),!e)return void console.log($.red("✗ Not authenticated"));console.log($.green("✓ Authenticated"));const t=e.token.substring(0,30)+"...";console.log($.gray(` Token: ${t}`)),e.machineId?(console.log($.green("✓ Machine registered")),console.log($.gray(` Machine ID: ${e.machineId}`)),console.log($.gray(` Host: ${n.hostname()}`))):console.log($.yellow("⚠️ Machine not registered")),console.log($.gray(`\n Data directory: ${re.agentrixHomeDir}`));try{await Et()?console.log($.green("✓ Daemon running")):console.log($.gray("✗ Daemon not running"))}catch{console.log($.gray("✗ Daemon not running"))}}(),process.exit(0)}),nr.command("ls","List active sessions",{},async e=>{try{const e=await async function(){return(await St("/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)}),nr.command("killall","Clean up all runaway agentrix processes",{},async()=>{const e=await async function(){const e=await async function(){return(await Dn()).filter(e=>e.pid!==process.pid&&("daemon"===e.type||"worker"===e.type||"upgrade-daemon"===e.type)).map(e=>({pid:e.pid,command:e.command}))}(),t=[];let n=0;for(const{pid:s,command:a}of e)try{if(console.log(`Killing runaway process PID ${s}: ${a}`),"win32"===process.platform){const e=qe.sync("taskkill",["/F","/PID",s.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(s,"SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),(await je()).find(e=>e.pid===s)&&(console.log(`Process PID ${s} ignored SIGTERM, using SIGKILL`),process.kill(s,"SIGKILL"));console.log(`Successfully killed runaway process PID ${s}`),n++}catch(e){const n=e.message;t.push({pid:s,error:n}),console.log(`Failed to kill process PID ${s}: ${n}`)}return{killed:n,errors:t}}();console.log(`Cleaned up ${e.killed} runaway processes`),e.errors.length>0&&console.log("Errors:",e.errors),process.exit(0)}),function(e){e.command("git-server","Manage local private GitLab server config",e=>e.command("add","Add a private GitLab server to local daemon config",e=>e.option("id",{type:"string",describe:"Local git server ID"}).option("base-url",{type:"string",describe:"GitLab base URL, for example https://gitlab.example.com"}).option("api-url",{type:"string",describe:"GitLab API URL, defaults to <base-url>/api/v4"}).option("pat-file",{type:"string",nargs:1,describe:"Read GitLab PAT from a file, or - for stdin"}).option("skip-validate",{type:"boolean",default:!1,describe:"Save without calling GitLab /user"}),async e=>{try{await er(e),process.exit(0)}catch(e){tr(e)}}).command("import <file>","Import private GitLab server config from a JSON bundle",e=>e.positional("file",{type:"string",describe:"Import file path, or - for stdin"}),async e=>{try{await async function(e){const t=Qo(e.file);if(!t)throw new Error("Import file is required");const n=await Yo(),s=function(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Import file must be valid JSON")}if(!t||"object"!=typeof t)throw new Error("Import file must contain a JSON object");const n=t;if(1!==n.version)throw new Error("Unsupported git server export version");if(!Array.isArray(n.gitServers))throw new Error("Import file must contain gitServers array");return n}(function(e){if("-"===e)return c(0,"utf8");if(!r(e))throw new Error(`Import file not found: ${e}`);return c(e,"utf8")}(t)),a=[];for(const e of s.gitServers){if(!e||"object"!=typeof e)throw new Error("Each gitServers item must be an object");if(!e.id||"string"!=typeof e.id)throw new Error("Each git server needs an id");if(e.type&&"gitlab"!==e.type)throw new Error(`Unsupported git server type for ${e.id}: ${e.type}`);const t={};if(e.baseUrl&&(t.baseUrl=Vo(e.baseUrl,`${e.id}.baseUrl`)),e.apiUrl?t.apiUrl=Vo(e.apiUrl,`${e.id}.apiUrl`):t.baseUrl&&(t.apiUrl=Xo(t.baseUrl)),!t.baseUrl||!t.apiUrl)throw new Error(`Git server ${e.id} needs baseUrl and apiUrl`);Xt(e.id,t),"string"==typeof e.pat&&e.pat.trim()&&sn(e.id,e.pat.trim(),n),e.patMeta&&nn(e.id,e.patMeta);const s=Zo(e);s?(Zt(e.id,s,n),s.webhookSecret||en(e.id,n)):en(e.id,n),a.push(e.id)}console.log(JSON.stringify({imported:a},null,2))}(e),process.exit(0)}catch(e){tr(e)}}).command("list","List local private GitLab server config",{},async()=>{try{await async function(){const e=await Yo(),t=await re.readDaemonState(),n=Jt().map(n=>function(e,t,n){const s=Yt(e)??{},a=Qt(e,t)??{};return{id:e,type:"gitlab",baseUrl:s.baseUrl,apiUrl:s.apiUrl,webhookEndpointPath:Oe(e),webhookUrl:Re(e,n),patConfigured:(i=e,Kt.hasPat(i)),patMeta:tn(e),webhookSecret:a.webhookSecret,projectTriggerTokens:a.projectTriggerTokens??{}};var i}(n,e,t));console.log(JSON.stringify(n,null,2))}(),process.exit(0)}catch(e){tr(e)}}).command("export [file]","Export private GitLab server config to a JSON bundle",e=>e.positional("file",{type:"string",describe:"Export file path. Use - or omit to write JSON to stdout."}).option("id",{type:"string",array:!0,describe:"Export only the specified git server ID. Can be repeated."}),async e=>{try{await async function(e){const t=await Yo(),n=function(e){if("string"==typeof e&&e.trim())return[e.trim()];if(Array.isArray(e)){const t=e.filter(e=>"string"==typeof e&&e.trim().length>0);return t.length>0?t.map(e=>e.trim()):void 0}}(e.id)??Jt(),s={version:1,exportedAt:(new Date).toISOString(),gitServers:n.map(e=>function(e,t){const n=Yt(e)??{},s=Qt(e,t)??{},a=an(e,t)??void 0;return{id:e,type:"gitlab",baseUrl:n.baseUrl,apiUrl:n.apiUrl,pat:a,patMeta:tn(e),webhookSecret:s.webhookSecret,projectTriggerTokens:s.projectTriggerTokens??{}}}(e,t))},a=`${JSON.stringify(s,null,2)}\n`,i=Qo(e.file);if(!i||"-"===i)return console.error($.yellow("Warning: export output contains PATs and webhook secrets.")),void process.stdout.write(a);p(i,a,{mode:384}),console.log(JSON.stringify({exported:n,file:i},null,2))}(e),process.exit(0)}catch(e){tr(e)}}).demandCommand(1,"Please specify one of: add, import, list, export").strict(),()=>{})}(nr),nr.command("kill <sessionId>","Stop a specific session",e=>e.positional("sessionId",{type:"string",describe:"Session ID to stop"}),async e=>{try{const t=await async function(e){return(await St("/stop-session",{sessionId:e})).success||!1}(e.sessionId);console.log(t?$.green("✓ Session stopped"):$.red("Failed to stop session"))}catch(e){console.log($.red("No daemon running"))}process.exit(0)}),nr.command("daemon",!1,{},async e=>{try{await Rt()}catch(e){console.error($.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}await ca(),process.exit(0)}),nr.command("worker",!1,e=>e.option("type",{type:"string",choices:Po,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 t=e.type,n=Mo[t];if(!n)throw new Error(`Unsupported worker type: ${String(e.type)}`);const s=e["started-by"],a=await Rt(),i=e["user-id"],o=e["task-id"],r=e["idle-timeout"];await n.run({credentials:a,startedBy:s,userId:i,taskId:o,idleTimeoutSecond:r})}catch(e){console.error($.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}}),nr.command("upgrade-daemon",!1,{},async e=>{const{startUpgradeDaemon:t}=await Promise.resolve().then(function(){return Ko});await t(),process.exit(0)}),nr.command("start","Start daemon (if not running) and show status",{},async e=>{try{await Rt()}catch(e){console.error($.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}const t=function(){const e=Un(),t=[],n=e.cli.find(e=>"git"===e.name);n&&!n.installed&&t.push("git");for(const n of e.missingSandbox)t.push(n.name);return{ok:0===t.length,missing:t}}();if(t.ok||(console.log($.bold.red("\n⚠️ Missing Critical Dependencies")),console.log($.yellow(`Cannot start daemon. Missing: ${t.missing.join(", ")}`)),console.log($.blue('\nRun "agentrix doctor" for detailed dependency information and installation instructions.')),process.exit(1)),!await At()){console.log("Starting Agentrix background service..."),Xs(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();let e=!1;for(let t=0;t<50;t++)if(await new Promise(e=>setTimeout(e,100)),await Et()){e=!0;break}e?(await new Promise(e=>setTimeout(e,1200)),await Et()?console.log($.green("✓ Daemon started successfully")):await async function(){const e=await async function(){const e=y(re.getStatePaths().logsDir,"daemon.log");try{return(await mt(e,"utf8")).trim().split("\n").filter(Boolean).slice(-12).join("\n")||null}catch{return null}}();if(console.log($.red("✗ Daemon exited shortly after startup")),!e)return;const t=e.split("\n").reverse().find(e=>e.includes("Machine binding revoked")||e.includes("Run `agentrix logout` and bind again"));t?console.log($.yellow(t)):(console.log($.gray("Recent daemon log:")),console.log(e))}()):console.log($.yellow("⚠️ Daemon may still be starting..."))}if(Oo()){const e=await Ro();e.hasUpgrade&&(n=e).hasUpgrade&&n.latestVersion&&(console.log(""),console.log($.yellow("┌────────────────────────────────────────────────────┐")),console.log($.yellow("│")+" "+$.bold("Upgrade Available")+" "+$.yellow("│")),console.log($.yellow("│")+" "+$.yellow("│")),console.log($.yellow("│")+` Current: ${$.dim(n.currentVersion)} → Latest: ${$.green.bold(n.latestVersion)} `+$.yellow("│")),console.log($.yellow("│")+" "+$.yellow("│")),console.log($.yellow("│")+" Run "+$.cyan.bold("agentrix upgrade")+" to upgrade "+$.yellow("│")),console.log($.yellow("│")+" "+$.yellow("│")),console.log($.yellow("│")+" To enable auto-upgrade, set: "+$.yellow("│")),console.log($.yellow("│")+" "+$.dim("AGENTRIX_DISABLE_AUTO_UPGRADE=false")+" "+$.yellow("│")),console.log($.yellow("└────────────────────────────────────────────────────┘")),console.log(""))}else Fo()||Xs(["upgrade-daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();var n;await qn("daemon"),process.exit(0)}),nr.demandCommand(1,"Please specify a command. Use --help to see available commands.").parse();
|
|
1
|
+
import{createRequire as e}from"node:module";const t=e(import.meta.url);import n,{tmpdir as s,homedir as a}from"node:os";import*as i from"node:fs";import o,{existsSync as r,readFileSync as c,statSync as l,writeFileSync as p,renameSync as d,rmSync as u,readdirSync as m,mkdirSync as g,createWriteStream as h,unlinkSync as f,accessSync as v,constants as x}from"node:fs";import*as y from"node:path";import b,{join as w,dirname as k,basename as I,isAbsolute as S,resolve as T,relative as E,normalize as A,extname as C}from"node:path";import $ from"yargs";import{hideBin as _}from"yargs/helpers";import P from"chalk";import{encodeBase64 as R,createKeyPairWithUit8Array as M,encryptMachineEncryptionKey as O,generateAESKey as D,decodeBase64 as N,decryptWithEphemeralKey as U,createEventId as j,encryptFileContent as q,splitRtcChunkFrame as L,RtcChunkFlags as H,buildRtcChunkFrame as G,decryptSdkMessage as W,isSDKUserMessage as F,machineAuth as B,encryptSdkMessage as z,isAskUserMessage as K,isAskUserResponseMessage as V,isSDKMessage as X,decodeGitPath as Y,getAgentContext as J,detectPreview as Q,IGNORED_DIRECTORIES as Z,DEFAULT_WORKER_EXECUTION_MODE as ee,isCompanionHeartbeatMessage as te,isCompanionReminderMessage as ne,workerAuth as se}from"@agentrix/shared";import{randomBytes as ae,randomUUID as ie,timingSafeEqual as oe,createHash as re}from"node:crypto";import ce from"axios";import{m as le,l as pe,p as de,a as ue,c as me,g as ge,b as he}from"./logger-GnFTqOqO.mjs";import{createInterface as fe}from"node:readline";import*as ve from"fs";import xe,{readFileSync as ye,existsSync as be,promises as we}from"fs";import*as ke from"path";import Ie,{join as Se,dirname as Te}from"path";import Ee from"open";import{io as Ae}from"socket.io-client";import{EventEmitter as Ce}from"node:events";import{GitServerLocalStore as $e,validateGitLabPatToken as _e,deriveLocalGitServerEncryptionKey as Pe,replacePromptPlaceholders as Re,loadAgentConfig as Me,getAgentContext as Oe,buildGitLabWebhookUrl as De,buildGitLabWebhookEndpointPath as Ne}from"@agentrix/shared/node";import{createRequire as Ue}from"node:module";import{spawn as je,execSync as qe}from"child_process";import Le from"ps-list";import He from"cross-spawn";import{getPlatform as Ge}from"@xmz-ai/sandbox-runtime/dist/utils/platform.js";import We from"fastify";import{z as Fe,toJSONSchema as Be}from"zod";import{validatorCompiler as ze,serializerCompiler as Ke}from"fastify-type-provider-zod";import{spawnSync as Ve,execSync as Xe,execFile as Ye,spawn as Je}from"node:child_process";import{createSdkMcpServer as Qe,query as Ze,tool as et,AbortError as tt}from"@anthropic-ai/claude-agent-sdk";import{EventEmitter as nt}from"events";import st from"better-sqlite3";import{fileURLToPath as at,pathToFileURL as it}from"url";import{pipeline as ot}from"node:stream/promises";import{isSupportedPlatform as rt,NetworkManager as ct,SandboxManager as lt}from"@xmz-ai/sandbox-runtime";import{Cron as pt}from"croner";import{readFile as dt}from"fs/promises";import ut from"simple-git";import{promisify as mt}from"node:util";import{mkdir as gt,writeFile as ht,access as ft,readFile as vt}from"node:fs/promises";import{randomUUID as xt}from"crypto";import{Codex as yt}from"@openai/codex-sdk";import{stdin as bt,stdout as wt}from"node:process";import{createInterface as kt}from"node:readline/promises";import"winston";import"os";const It=new Set(["AGENTRIX_CLAUDE_HOME","AGENTRIX_CODEX_HOME","AGENTRIX_CLAUDE_PATH","AGENTRIX_CODEX_PATH"]);function St(e){return e.replace(/^~(?=\/|$)/,n.homedir())}function Tt(e,t,n){const s=t.toLowerCase();"http_proxy"===s?(e.HTTP_PROXY=n,e.http_proxy=n):"https_proxy"===s?(e.HTTPS_PROXY=n,e.https_proxy=n):"no_proxy"===s?(e.NO_PROXY=n,e.no_proxy=n):"all_proxy"===s?(e.ALL_PROXY=n,e.all_proxy=n):"global_agent_http_proxy"===s&&(e.GLOBAL_AGENT_HTTP_PROXY=n,e.global_agent_http_proxy=n)}function Et(e,t,n){const s=n.trim();s&&("AGENTRIX_CLAUDE_HOME"===t?e.CLAUDE_CONFIG_DIR=St(s):"AGENTRIX_CODEX_HOME"===t&&(e.CODEX_HOME=St(s)))}async function At(e){return new Promise(t=>setTimeout(t,e))}function Ct(e,t){return`http://${"::1"===e.host?"[::1]":"127.0.0.1"}:${e.port}${t}`}async function $t(e,t){const n=await le.readDaemonState();if(!n?.port){const e="No daemon running, no state file found";return pe.debug(`[CONTROL CLIENT] ${e}`),{error:e}}try{const s=process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT?parseInt(process.env.AGENTRIX_DAEMON_HTTP_TIMEOUT):1e4,a=Ct(n,e),i=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{}),signal:AbortSignal.timeout(s)});if(!i.ok){const t=await i.json().catch(()=>null),n=("string"==typeof t?.error?t.error:"string"==typeof t?.message?t.message:void 0)||`Request failed: ${e}, HTTP ${i.status}`;return pe.debug(`[CONTROL CLIENT] ${n}`),{error:n}}return await i.json()}catch(t){const s=`Request failed: ${e} at ${Ct(n,e)}, ${t instanceof Error?t.message:"Unknown error"}. Check that the Agentrix daemon is running and that ${n.host??"127.0.0.1"}:${n.port} is reachable.`;return pe.debug(`[CONTROL CLIENT] ${s}`),{error:s}}}async function _t(e,t){return await $t("/session-started",{sessionId:e,metadata:t})}async function Pt(){const e=await le.readDaemonState();if(!e)return!1;try{return process.kill(e.pid,0),!0}catch{return pe.debug("[DAEMON RUN] Daemon PID not running, cleaning up state"),await Mt(),!1}}async function Rt(){if(pe.debug("[DAEMON CONTROL] Checking if daemon is running same version"),!await Pt())return pe.debug("[DAEMON CONTROL] No daemon running, returning false"),!1;const e=await le.readDaemonState();if(!e)return pe.debug("[DAEMON CONTROL] No daemon state found, returning false"),!1;try{const t=Se(de(),"package.json"),n=JSON.parse(ye(t,"utf-8")).version;return pe.debug(`[DAEMON CONTROL] Current CLI version: ${n}, Daemon started with version: ${e.cliVersion}`),n===e.cliVersion}catch(e){return pe.debug("[DAEMON CONTROL] Error checking daemon version",e),!1}}async function Mt(){try{await le.clearDaemonState(),pe.debug("[DAEMON RUN] Daemon state file removed")}catch(e){pe.debug("[DAEMON RUN] Error cleaning up daemon metadata",e)}}async function Ot(){try{const e=await le.readDaemonState();if(!e)return void pe.debug("No daemon state found");pe.debug(`Stopping daemon with PID ${e.pid}`);try{return await async function(){await $t("/stop")}(),void await async function(e){const t=Date.now();for(;Date.now()-t<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){pe.debug("HTTP stop failed, will force kill",e)}process.kill(e.pid,"SIGKILL")}catch(e){pe.debug("Error stopping daemon",e)}}function Dt(e){return`${e}\nRun \`agentrix logout\` and bind this machine again.`}function Nt(e,t){if(ce.isAxiosError(e)){const n=e.response?.data?.message;return"string"==typeof n&&n.length>0?n.includes("Machine binding revoked")?Dt(n):`${t}: ${n}`:"string"==typeof e.message&&e.message.includes("Machine binding revoked")?Dt(e.message):`${t}: ${e.message}`}return e instanceof Error&&e.message.includes("Machine binding revoked")?Dt(e.message):e instanceof Error?`${t}: ${e.message}`:t}function Ut(){return R(new Uint8Array(ae(32)))}async function jt(){const e=await le.readCredentials();if(e){if(await async function(e){try{await ce.get(`${le.serverUrl}/v1/machines/validate`,{headers:{Authorization:`Bearer ${e.token}`},timeout:15e3})}catch(e){throw new Error(Nt(e,"Stored machine credentials are no longer valid"))}}(e),!e.secret){const t={...e,secret:Ut()};return await le.writeCredentials(t),pe.info("[AUTH] Generated missing local auth secret"),t}return pe.info("[AUTH] Using existing credentials"),e}const t=process.env.CLOUD_AUTH_TOKEN;let n,s,a;if(t){const e=le.generateMachineId();n={token:t,secret:Ut(),machineId:e},pe.info(`[AUTH] Cloud mode detected, generated machine ID: ${e}`)}else{const e=await async function(){console.clear();const e=le.generateMachineId(),t=new Uint8Array(ae(32)),n=await M(t);try{console.log(`[AUTH] Sending auth request to: ${le.serverUrl}/v1/auth/machine`),console.log(`[AUTH] Public key: ${R(n.publicKey).substring(0,20)}...`);const t={machineId:e};await ce.post(`${le.serverUrl}/v1/auth/machine`,t),console.log("[AUTH] Auth request sent successfully")}catch(e){return console.log(Nt(e,"Failed to create authentication request, please try again later.")),{credentials:null,userPublicKey:null,keypair:n}}const s=await async function(e,t){console.clear(),console.log("\nWeb Authentication\n");const n=function(e,t){const n={key:R(e,"base64"),machineId:t},s=JSON.stringify(n),a=R((new TextEncoder).encode(s),"base64url");return`${le.webappUrl}/terminal/connect?auth=${a}`}(e.publicKey,t);return console.log("Opening your browser..."),await async function(e){try{return!process.stdout.isTTY||process.env.CI||process.env.HEADLESS?(pe.debug("[browser] Headless environment detected, skipping browser open"),!1):(pe.debug(`[browser] Attempting to open URL: ${e}`),await Ee(e),pe.debug("[browser] Browser opened successfully"),!0)}catch(e){return pe.debug("[browser] Failed to open browser:",e),!1}}(n)?(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(n),console.log(""),await async function(e,t){process.stdout.write("Waiting for authentication");let n=0,s=!1;const a=()=>{s=!0,console.log("\n\nAuthentication cancelled."),process.exit(0)};process.on("SIGINT",a);try{for(;!s;){try{const n=await ce.get(`${le.serverUrl}/v1/auth/machine?machineId=${t}`);if("authorized"===n.data.state){const t=n.data.token,s=n.data.content,a=U(N(s),e.secretKey);return a?{token:t,userPublicKey:JSON.parse((new TextDecoder).decode(a)).publicKey}:(console.log("\n\nFailed to decrypt authentication data. Please try again."),{token:null,userPublicKey:null})}}catch(e){return console.log(`\n\n${Nt(e,"Failed to check authentication status. Please try again.")}`),{token:null,userPublicKey:null}}process.stdout.write("\rWaiting for authentication"+".".repeat(n%3+1)+" "),n++,await At(1e3)}}finally{process.off("SIGINT",a)}return{token:null,userPublicKey:null}}(e,t)}(n,e);return s.token?{credentials:{token:s.token,secret:R(t),machineId:e},userPublicKey:s?.userPublicKey,keypair:n}:{credentials:null,userPublicKey:null,keypair:n}}();if(!e.credentials||!e.userPublicKey)throw new Error("Authentication failed or was cancelled");n=e.credentials,s=e.keypair,a=e.userPublicKey}return await le.writeCredentials(n),await async function(e,t,n,s){try{const a={id:e.machineId,metadata:JSON.stringify(t)};s&&n&&(a.dataEncryptionKey=O(s.publicKey,D(),N(n))),await ce.post(`${le.serverUrl}/v1/machines/sync`,a,{headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},timeout:6e4})}catch(e){throw new Error(Nt(e,"Failed to sync machine data"))}}(n,le.metadata(),a,s),pe.info("[AUTH] Machine setup completed"),n}!function(e=process.env){!function(e=process.env,t){if(!t?.variables)return e;const n=!0===t.enabled;for(const[s,a]of Object.entries(t.variables)){const t=s.trim();if(!t)continue;const i=String(a),o=It.has(t);(n||o)&&(e[t]=i,Tt(e,t,i),Et(e,t,i))}}(e,function(e=process.env){const t=w(function(e=process.env){const t=e.AGENTRIX_HOME_DIR||e.AGENTRIX_DIR;return t?St(t):w(n.homedir(),".agentrix")}(e),"settings.json");if(!r(t))return null;try{const e=c(t,"utf-8"),n=JSON.parse(e);return n?.daemonEnv||null}catch{return null}}(e))}();class qt{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}}function Lt(e){if(!e||"object"!=typeof e)return String(e??"unknown error");const t=e,n=[];return t.message&&n.push(t.message),t.type&&n.push(`type=${t.type}`),void 0!==t.description&&n.push(`description=${JSON.stringify(t.description)}`),void 0!==t.data&&n.push(`data=${JSON.stringify(t.data)}`),void 0!==t.context&&n.push(`context=${JSON.stringify(t.context)}`),n.filter(Boolean).join(" ")||"unknown socket error"}class Ht{socket=null;config;eventHandlers=new Map;eventEmitter=new Ce;KeepAliveManager=null;healthCheckInterval=null;constructor(e){this.config=e,e.keepAliveConfig&&(this.KeepAliveManager=new qt(e.keepAliveConfig))}connect(){if(this.socket)return void this.log("Already connected or connecting");const{serverUrl:e,path:t,auth:n={},options:s={}}=this.config,a={path:t,auth:n,transports:["websocket"],reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:5e3,reconnectionAttempts:1/0,...s};this.socket=Ae(e,a),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,t,n){this.socket&&(t&&this.socket.off(e,t),this.socket.on(e,n))}onEvent(e,t){const n=async n=>(this.log(`received event ${e}, data: ${JSON.stringify(n)}`),t(n)),s=this.eventHandlers.get(e);this.eventHandlers.set(e,n),this.replaceSocketHandler(e,s,n)}onEventWithAck(e,t){const n=async(n,s)=>(this.log(`received event with ack ${e}, data: ${JSON.stringify(n)}`),t(n,s)),s=this.eventHandlers.get(e);this.eventHandlers.set(e,n),this.replaceSocketHandler(e,s,n)}unregisterHandler(e){this.eventHandlers.delete(e),this.socket&&this.socket.off(e)}send(e,t){this.socket?(this.log(`send event ${e}`),void 0!==t?this.socket.emit(e,t):this.socket.emit(e)):this.log("Cannot send - socket not connected")}async sendWithAck(e,t){if(!this.socket)throw new Error("Cannot send - socket not connected");return this.log(`send event ${e}, data: ${JSON.stringify(t)}`),this.socket.emitWithAck(e,t)}sendVolatile(e,t){this.socket&&(void 0!==t?this.socket.volatile.emit(e,t):this.socket.volatile.emit(e))}async flush(e=1e4){if(this.connected)return new Promise(t=>{const n=setTimeout(()=>t(),e);this.socket.emit("ping",()=>{clearTimeout(n),t()})})}updateAuth(e){this.socket&&(this.socket.auth=e),this.config.auth=e}onLifecycle(e,t){this.eventEmitter.on(`lifecycle:${e}`,t)}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,t]of this.eventHandlers.entries())this.socket.off(e,t),this.socket.on(e,t);this.KeepAliveManager?.start(this.socket),this.startHealthCheck()}),this.socket.on("disconnect",e=>{this.log(`Disconnected: ${e||"unknown"}`),this.eventEmitter.emit("lifecycle:disconnect",e),this.KeepAliveManager?.stop(),this.stopHealthCheck()}),this.socket.on("connect_error",e=>{this.log(`Connection error: ${Lt(e)}`),this.eventEmitter.emit("lifecycle:connect_error",e),setTimeout(()=>this.socket?.connect(),5e3)}),this.socket.on("error",e=>{this.log(`Socket error: ${Lt(e)}`),this.eventEmitter.emit("lifecycle:error",e)}))}startHealthCheck(){const e=this.config.healthCheckConfig;if(!1===e?.enabled)return;const t=e?.intervalMs??3e4,n=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())},n);this.socket.once("pong",()=>{clearTimeout(e)}),this.socket.emit("ping")},t)}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}log(e,...t){this.config.logger&&this.config.logger(`[SocketClient] ${e}`,...t)}}function Gt(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}),n}var Wt,Ft,Bt,zt={},Kt={"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/activemessage":{source:"iana"},"application/activity+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-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/applefile":{source:"iana"},"application/applixware":{source:"apache",extensions:["aw"]},"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/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/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/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/cea":{source:"iana"},"application/cea-2018+xml":{source:"iana",compressible:!0},"application/cellml+xml":{source:"iana",compressible:!0},"application/cfw":{source:"iana"},"application/city+json":{source:"iana",compressible:!0},"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-group+json":{source:"iana",compressible:!0},"application/coap-payload":{source:"iana"},"application/commonground":{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/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/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"},"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/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/ecmascript":{source:"iana",compressible:!0,extensions:["es","ecma"]},"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.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/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/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/geoxacml+xml":{source:"iana",compressible:!0},"application/gltf-buffer":{source:"iana"},"application/gml+xml":{source:"iana",compressible:!0,extensions:["gml"]},"application/gpx+xml":{source:"apache",compressible:!0,extensions:["gpx"]},"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/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:"apache",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:"iana",charset:"UTF-8",compressible:!0,extensions:["js","mjs"]},"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/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/jwk+json":{source:"iana",compressible:!0},"application/jwk-set+json":{source:"iana",compressible:!0},"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/load-control+xml":{source:"iana",compressible:!0},"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:["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/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:!1,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/omdoc+xml":{source:"apache",compressible:!0,extensions:["omdoc"]},"application/onenote":{source:"apache",extensions:["onetoc","onetoc2","onetmp","onepkg"]},"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:["asc","sig"]},"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/problem+json":{source:"iana",compressible:!0},"application/problem+xml":{source:"iana",compressible:!0},"application/provenance+xml":{source:"iana",compressible:!0,extensions:["provx"]},"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.nprend":{source:"iana"},"application/prs.plucker":{source:"iana"},"application/prs.rdf-xml-crypt":{source:"iana"},"application/prs.xsf+xml":{source:"iana",compressible:!0},"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:"iana"},"application/reputon+json":{source:"iana",compressible:!0},"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-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-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:"iana"},"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"},"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/ssml+xml":{source:"iana",compressible:!0,extensions:["ssml"]},"application/stix+json":{source:"iana",compressible:!0},"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/tnauthlist":{source:"iana"},"application/token-introspection+jwt":{source:"iana"},"application/toml":{compressible:!0,extensions:["toml"]},"application/trickle-ice-sdpfrag":{source:"iana"},"application/trig":{source:"iana",extensions:["trig"]},"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/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/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.3gpp-prose+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-prose-pc3ch+xml":{source:"iana",compressible:!0},"application/vnd.3gpp-v2x-local-service-information":{source:"iana"},"application/vnd.3gpp.5gnas":{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.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-payload":{source:"iana"},"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-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-affiliation-info+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-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.s1ap":{source:"iana"},"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.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.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:"iana",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:"iana"},"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.thrift.binary":{source:"iana"},"application/vnd.apache.thrift.compact":{source:"iana"},"application/vnd.apache.thrift.json":{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:"iana"},"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.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.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.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.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.datapackage+json":{source:"iana",compressible:!0},"application/vnd.dataresource+json":{source:"iana",compressible:!0},"application/vnd.dbf":{source:"iana",extensions:["dbf"]},"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.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.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:"iana",extensions:["fdf"]},"application/vnd.fdsn.mseed":{source:"iana",extensions:["mseed"]},"application/vnd.fdsn.seed":{source:"iana",extensions:["seed","dataless"]},"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.frogans.fnc":{source:"iana",extensions:["fnc"]},"application/vnd.frogans.ltf":{source:"iana",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.genomatix.tuxedo":{source:"iana",extensions:["txd"]},"application/vnd.gentics.grd+json":{source:"iana",compressible:!0},"application/vnd.geo+json":{source:"iana",compressible:!0},"application/vnd.geocube+xml":{source:"iana",compressible:!0},"application/vnd.geogebra.file":{source:"iana",extensions:["ggb"]},"application/vnd.geogebra.slides":{source:"iana"},"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.google-apps.document":{compressible:!1,extensions:["gdoc"]},"application/vnd.google-apps.presentation":{compressible:!1,extensions:["gslides"]},"application/vnd.google-apps.spreadsheet":{compressible:!1,extensions:["gsheet"]},"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:"iana",compressible:!0},"application/vnd.gov.sk.e-form+zip":{source:"iana",compressible:!1},"application/vnd.gov.sk.xmldatacontainer+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.hl7cda+xml":{source:"iana",charset:"UTF-8",compressible:!0},"application/vnd.hl7v2+xml":{source:"iana",charset:"UTF-8",compressible:!0},"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.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:"iana"},"application/vnd.ibm.electronic-media":{source:"iana"},"application/vnd.ibm.minipay":{source:"iana",extensions:["mpy"]},"application/vnd.ibm.modcap":{source:"iana",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:"iana"},"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.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.kenameaapp":{source:"iana",extensions:["htke"]},"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.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.medcalcdata":{source:"iana",extensions:["mc1"]},"application/vnd.mediastation.cdkey":{source:"iana",extensions:["cdkey"]},"application/vnd.meridian-slingshot":{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.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-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.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.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:"iana",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.oasis.opendocument.chart":{source:"iana",extensions:["odc"]},"application/vnd.oasis.opendocument.chart-template":{source:"iana",extensions:["otc"]},"application/vnd.oasis.opendocument.database":{source:"iana",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-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:"iana",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:"iana",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.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.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.proteus.magazine":{source:"iana",extensions:["mgz"]},"application/vnd.psfs":{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},"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.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.smaf":{source:"iana",extensions:["mmf"]},"application/vnd.smart.notebook":{source:"iana"},"application/vnd.smart.teacher":{source:"iana",extensions:["teacher"]},"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.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.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"]},"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.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"]},"application/vnd.visionary":{source:"iana",extensions:["vis"]},"application/vnd.vividence.scriptfile":{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.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.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.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.youtube.yt":{source:"iana"},"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/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-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-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-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-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/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/yang":{source:"iana",extensions:["yang"]},"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/yin+xml":{source:"iana",compressible:!0,extensions:["yin"]},"application/zip":{source:"iana",compressible:!1,extensions:["zip"]},"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"},"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/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/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/mobile-xmf":{source:"iana",extensions:["mxmf"]},"audio/mp3":{compressible:!1,extensions:["mp3"]},"audio/mp4":{source:"iana",compressible:!1,extensions:["m4a","mp4a"]},"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:"iana"},"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":{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"]},"image/cgm":{source:"iana",extensions:["cgm"]},"image/dicom-rle":{source:"iana",extensions:["drle"]},"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/hsj2":{source:"iana",extensions:["hsj2"]},"image/ief":{source:"iana",extensions:["ief"]},"image/jls":{source:"iana",extensions:["jls"]},"image/jp2":{source:"iana",compressible:!1,extensions:["jp2","jpg2"]},"image/jpeg":{source:"iana",compressible:!1,extensions:["jpeg","jpg","jpe"]},"image/jph":{source:"iana",extensions:["jph"]},"image/jphc":{source:"iana",extensions:["jhc"]},"image/jpm":{source:"iana",compressible:!1,extensions:["jpm"]},"image/jpx":{source:"iana",compressible:!1,extensions:["jpx","jpf"]},"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},"image/png":{source:"iana",compressible:!1,extensions:["png"]},"image/prs.btif":{source:"iana",extensions:["btif"]},"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.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:"apache",extensions:["webp"]},"image/wmf":{source:"iana",extensions:["wmf"]},"image/x-3ds":{source:"apache",extensions:["3ds"]},"image/x-cmu-raster":{source:"apache",extensions:["ras"]},"image/x-cmx":{source:"apache",extensions:["cmx"]},"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-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/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/news":{source:"iana"},"message/partial":{source:"iana",compressible:!1},"message/rfc822":{source:"iana",compressible:!0,extensions:["eml","mime"]},"message/s-http":{source:"iana"},"message/sip":{source:"iana"},"message/sipfrag":{source:"iana"},"message/tracking-status":{source:"iana"},"message/vnd.si.simp":{source:"iana"},"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/mesh":{source:"iana",compressible:!1,extensions:["msh","mesh","silo"]},"model/mtl":{source:"iana",extensions:["mtl"]},"model/obj":{source:"iana",extensions:["obj"]},"model/step":{source:"iana"},"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/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"},"model/vnd.rosette.annotated-data-model":{source:"iana"},"model/vnd.sap.vds":{source:"iana",extensions:["vds"]},"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:"iana"},"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/html":{source:"iana",compressible:!0,extensions:["html","htm","shtml"]},"text/jade":{extensions:["jade"]},"text/javascript":{source:"iana",compressible:!0},"text/jcr-cnd":{source:"iana"},"text/jsx":{compressible:!0,extensions:["jsx"]},"text/less":{compressible:!0,extensions:["less"]},"text/markdown":{source:"iana",compressible:!0,extensions:["markdown","md"]},"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/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.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:"iana"},"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.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/vtt":{source:"iana",charset:"UTF-8",compressible:!0,extensions:["vtt"]},"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/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/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/mj2":{source:"iana",extensions:["mj2","mjp2"]},"video/mp1s":{source:"iana"},"video/mp2p":{source:"iana"},"video/mp2t":{source:"iana",extensions:["ts"]},"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.radgamettools.bink":{source:"iana"},"video/vnd.radgamettools.smacker":{source:"iana"},"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}},Vt=(Bt||(Bt=1,function(e){var t,n,s,a=Ft?Wt:(Ft=1,Wt=Kt),i=Ie.extname,o=/^\s*([^;\s]*)(?:;|\s|$)/,r=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var t=o.exec(e),n=t&&a[t[1].toLowerCase()];return n&&n.charset?n.charset:!(!t||!r.test(t[1]))&&"UTF-8"}e.charset=c,e.charsets={lookup:c},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var n=-1===t.indexOf("/")?e.lookup(t):t;if(!n)return!1;if(-1===n.indexOf("charset")){var s=e.charset(n);s&&(n+="; charset="+s.toLowerCase())}return n},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var n=o.exec(t),s=n&&e.extensions[n[1].toLowerCase()];return!(!s||!s.length)&&s[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var n=i("x."+t).toLowerCase().substr(1);return n&&e.types[n]||!1},e.types=Object.create(null),t=e.extensions,n=e.types,s=["nginx","apache",void 0,"iana"],Object.keys(a).forEach(function(e){var i=a[e],o=i.extensions;if(o&&o.length){t[e]=o;for(var r=0;r<o.length;r++){var c=o[r];if(n[c]){var l=s.indexOf(a[n[c]].source),p=s.indexOf(i.source);if("application/octet-stream"!==n[c]&&(l>p||l===p&&"application/"===n[c].substr(0,12)))continue}n[c]=e}}})}(zt)),zt);function Xt(e,t){e?e.send("workspace-file-response",t):pe.error("[WORKSPACE] Cannot send workspace-file-response: client not available")}function Yt(e,t,n,s){return{eventId:j(),requestId:e,taskId:t,success:!1,error:{code:n,message:s}}}function Jt(e){return async t=>{const{taskId:n,userId:s,relativePath:a,requestId:o,maxFileSizeMB:r,ifModifiedSince:c,dataEncryptionKey:l}=t;pe.debug(`[WORKSPACE] File request: taskId=${n}, userId=${s}, relativePath=${a}, maxFileSizeMB=${r}, ifModifiedSince=${c}, hasEncryptionKey=${!!l}`);try{const t=1024*(r||10)*1024,p=function(e,t,n){return le.resolveWorkspaceFilePath(e,t,n)}(s,n,a);if(!i.existsSync(p))return pe.warn(`[WORKSPACE] File not found: ${p}`),void Xt(e.client,Yt(o,n,"file_not_found","File or directory not found"));const d=await i.promises.stat(p),u=d.mtime.toISOString();if(c&&u===c)return void function(e,t,n,s){pe.debug(`[WORKSPACE] File not modified: ${s}`),Xt(e,{eventId:j(),requestId:t,taskId:n,success:!0,notModified:!0})}(e.client,o,n,p);if(d.isDirectory())return void await async function(e,t,n,s,a,o){const r=await i.promises.readdir(s,{withFileTypes:!0}),c=await Promise.all(r.map(async e=>{const t=y.join(s,e.name),n=await i.promises.stat(t);return{name:e.name,type:e.isDirectory()?"directory":"file",size:n.size,modifiedAt:n.mtime.toISOString(),accessDenied:n.size>o}}));Xt(e,{eventId:j(),requestId:t,taskId:n,success:!0,data:{type:"directory",entries:c,metadata:{size:0,modifiedAt:a.mtime.toISOString()}}})}(e.client,o,n,p,d,t);{const s=Vt.lookup(p)||"application/octet-stream";return d.size>t?void function(e,t,n,s,a,i,o){pe.warn(`[WORKSPACE] File too large (${a.size} bytes > ${o} bytes): ${s}`),Xt(e,{eventId:j(),requestId:t,taskId:n,success:!0,data:{type:"file",metadata:{size:a.size,mimeType:i,modifiedAt:a.mtime.toISOString(),accessDenied:!0}}})}(e.client,o,n,p,d,s,t):void await async function(e,t,n,s,a,o){const r=Vt.lookup(s)||"application/octet-stream",c=(await i.promises.readFile(s)).toString("base64");let l=null;o&&(l=await async function(e){try{const t=await le.getSecretKey();if(!t)return pe.warn("[WORKSPACE] Machine secret key not available"),null;const n=N(e);return U(n,t)||(pe.warn("[WORKSPACE] Failed to decrypt dataEncryptionKey"),null)}catch(e){return pe.warn("[WORKSPACE] Error decrypting dataEncryptionKey:",e),null}}(o));const p={type:"file",metadata:{size:a.size,mimeType:r,modifiedAt:a.mtime.toISOString()}};l?p.encryptedContent=q(c,l):p.content=c,Xt(e,{eventId:j(),requestId:t,taskId:n,success:!0,data:p})}(e.client,o,n,p,d,l)}}catch(t){pe.error(`[WORKSPACE] Failed to handle workspace-file-request: ${t.message}`,t);const s="ENOENT"===t.code?"file_not_found":"EACCES"===t.code?"permission_denied":"unknown_error";Xt(e.client,Yt(o,n,s,t.message))}}}const Qt=new $e({credentialsDir:w(le.agentrixHomeDir,"credentials")});async function Zt(){const e=await le.readCredentials();return e?.secret?Pe(e.secret):null}function en(e){return Qt.loadGitServerConfig(e)}function tn(e,t){return Qt.loadGitLabWebhookBridgeSecrets(e,t)}function nn(e){return Qt.loadPatMeta(e)}function sn(e,t){return Qt.loadPat(e,t)}const an=100,on=[{method:"GET",pattern:/^\/user$/},{method:"GET",pattern:/^\/projects$/},{method:"GET",pattern:/^\/projects\/[^/]+\/repository\/branches$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues$/},{method:"POST",pattern:/^\/projects\/[^/]+\/issues$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues\/\d+$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/issues\/\d+$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues\/\d+\/notes$/},{method:"GET",pattern:/^\/projects\/[^/]+\/issues\/\d+\/discussions$/},{method:"POST",pattern:/^\/projects\/[^/]+\/issues\/\d+\/discussions$/},{method:"POST",pattern:/^\/projects\/[^/]+\/issues\/\d+\/discussions\/[^/]+\/notes$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/changes$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/notes$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions$/},{method:"GET",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/approvals$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions\/[^/]+\/notes$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/approve$/},{method:"POST",pattern:/^\/projects\/[^/]+\/merge_requests$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions\/[^/]+$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/discussions\/[^/]+\/notes\/\d+$/},{method:"PUT",pattern:/^\/projects\/[^/]+\/merge_requests\/\d+\/merge$/}];class rn{apiUrl;pat;requestId;gitServerId;constructor(e,t,n){this.apiUrl=e,this.pat=t,this.requestId=n?.requestId,this.gitServerId=n?.gitServerId}logPrefix(){return`[GITLAB EXECUTOR] reqId=${this.requestId??"-"}, gitServer=${this.gitServerId??"-"}`}summarizeResult(e,t){if(Array.isArray(t))return`items=${t.length}`;if(t&&"object"==typeof t){const n=t;return"resolveGitAuthContext"===e?`authMode=${String(n.authMode??"unknown")}, hasPat=${Boolean(n.hasPat)}`:"id"in n&&"status"in n?`id=${String(n.id??"-")}, status=${String(n.status??"-")}`:"number"in n||"state"in n?`number=${String(n.number??"-")}, state=${String(n.state??"-")}`:`keys=${Object.keys(n).join(",")||"-"}`}return"type="+typeof t}truncateText(e,t=300){return e.length<=t?e:`${e.slice(0,t)}...`}async requestWithResponse(e,t="GET",n){const s=`${this.apiUrl}${e}`,a={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/json"},i=Date.now();pe.debug(`${this.logPrefix()} request start: ${t} ${e}`);try{const o=await fetch(s,{method:t,headers:a,body:n?JSON.stringify(n):void 0}),r=Date.now()-i;if(!o.ok){const n=await o.text().catch(()=>"Unknown error"),s=this.truncateText(n);throw pe.warn(`${this.logPrefix()} request failed: ${t} ${e}, status=${o.status}, elapsedMs=${r}, detail=${s}`),{status:o.status,message:`GitLab API error: ${o.status} ${o.statusText}`,detail:s}}return pe.debug(`${this.logPrefix()} request success: ${t} ${e}, elapsedMs=${r}`),{data:await o.json(),headers:o.headers}}catch(n){if("object"==typeof n&&null!==n&&"status"in n)throw n;const s=n instanceof Error?n.message:"Unknown network error";throw pe.error(`${this.logPrefix()} request exception: ${t} ${e}, message=${s}`),{status:0,message:`GitLab request failed: ${s}`}}}async requestForm(e,t){const n=`${this.apiUrl}${e}`,s={Authorization:`Bearer ${this.pat}`,"Content-Type":"application/x-www-form-urlencoded"},a=Date.now();pe.debug(`${this.logPrefix()} form request start: POST ${e}`);try{const i=await fetch(n,{method:"POST",headers:s,body:t}),o=Date.now()-a;if(!i.ok){const t=await i.text().catch(()=>"Unknown error"),n=this.truncateText(t);throw pe.warn(`${this.logPrefix()} form request failed: POST ${e}, status=${i.status}, elapsedMs=${o}, detail=${n}`),{status:i.status,message:`GitLab API error: ${i.status} ${i.statusText}`,detail:n}}return pe.debug(`${this.logPrefix()} form request success: POST ${e}, elapsedMs=${o}`),await i.json()}catch(t){if("object"==typeof t&&null!==t&&"status"in t)throw t;const n=t instanceof Error?t.message:"Unknown network error";throw pe.error(`${this.logPrefix()} form request exception: POST ${e}, message=${n}`),{status:0,message:`GitLab request failed: ${n}`}}}async request(e,t="GET",n){const{data:s}=await this.requestWithResponse(e,t,n);return s}withQueryParams(e,t){const[n,s=""]=e.split("?"),a=new URLSearchParams(s);for(const[e,n]of Object.entries(t))a.set(e,String(n));const i=a.toString();return i?`${n}?${i}`:n}parseTotalPages(e){const t=e.get("x-total-pages");if(!t)return null;const n=Number.parseInt(t,10);return!Number.isFinite(n)||n<=0?null:n}async fetchRemainingPagesInBatches(e,t){const n=[];for(let s=2;s<=e;s+=4){const a=Math.min(s+4-1,e),i=Array.from({length:a-s+1},(e,t)=>s+t),o=await Promise.all(i.map(e=>t(e)));for(const e of o)n.push(...e)}return n}async requestPaginated(e){const t=this.withQueryParams(e,{per_page:an,page:1}),n=await this.requestWithResponse(t),s=[...n.data],a=this.parseTotalPages(n.headers);if(a&&a>1){const t=await this.fetchRemainingPagesInBatches(a,async t=>{const n=this.withQueryParams(e,{per_page:an,page:t});return this.request(n)});return s.push(...t),s}if(!a&&n.data.length===an){let t=2;for(;;){const n=this.withQueryParams(e,{per_page:an,page:t}),a=await this.request(n);if(0===a.length)break;if(s.push(...a),a.length<an)break;t+=1}}return s}async executeOperation(e,t){pe.info(`${this.logPrefix()} execute operation: op=${e}, payloadKeys=${Object.keys(t||{}).join(",")||"-"}`);try{let n;switch(e){case"listRepos":n=await this.listRepos();break;case"listBranches":n=await this.listBranches(t.owner,t.name);break;case"createMergeRequest":n=await this.createMergeRequest(t);break;case"getMergeRequest":n=await this.getMergeRequest(t.owner,t.name,t.iid);break;case"listMergeRequests":n=await this.listMergeRequests(t.owner,t.name);break;case"triggerPipeline":n=await this.triggerPipeline(t);break;case"ensurePipelineTriggerToken":n=await this.ensurePipelineTriggerToken(t);break;case"requestGitlabApi":n=await this.requestGitlabApi(t);break;case"resolveGitAuthContext":n={authMode:"local_pat",hasPat:!0};break;default:throw{status:400,message:`Unknown operation: ${e}`}}return pe.info(`${this.logPrefix()} operation success: op=${e}, summary=${this.summarizeResult(e,n)}`),n}catch(t){const n=t instanceof Error?t.message:"object"==typeof t&&null!==t&&"message"in t?String(t.message):"Unknown error";throw pe.error(`${this.logPrefix()} operation failed: op=${e}, message=${n}`),t}}async listRepos(){return(await this.requestPaginated("/projects?membership=true&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,t){const n=encodeURIComponent(`${e}/${t}`);return(await this.requestPaginated(`/projects/${n}/repository/branches`)).map(e=>({name:e.name,commit:{sha:e.commit.id,url:""},protected:e.protected}))}async createMergeRequest(e){const t=encodeURIComponent(`${e.owner}/${e.repo}`),n=await this.request(`/projects/${t}/merge_requests`,"POST",{source_branch:e.head,target_branch:e.base,title:e.title,description:e.body||""});return{number:n.iid,title:n.title,body:n.description,state:"opened"===n.state?"open":n.state,url:n.web_url,head:n.source_branch,base:n.target_branch,createdAt:n.created_at,updatedAt:n.updated_at}}async getMergeRequest(e,t,n){const s=encodeURIComponent(`${e}/${t}`),a=await this.request(`/projects/${s}/merge_requests/${n}`);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 listMergeRequests(e,t){const n=encodeURIComponent(`${e}/${t}`);return(await this.request(`/projects/${n}/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}))}parseNonEmptyString(e,t){if("string"!=typeof e||0===e.trim().length)throw{status:400,message:`${t} is required`};return e.trim()}parseOptionalString(e,t){if(null!=e){if("string"!=typeof e||0===e.trim().length)throw{status:400,message:`${t} must be a non-empty string`};return e.trim()}}resolveProjectPath(e){if("number"==typeof e.projectId||"string"==typeof e.projectId){const t=String(e.projectId).trim();if(t.length>0)return encodeURIComponent(t)}const t=this.parseOptionalString(e.projectPath,"projectPath");if(t)return encodeURIComponent(t);const n=this.parseOptionalString(e.owner,"owner"),s=this.parseOptionalString(e.repo??e.name,"repo");if(!n||!s)throw{status:400,message:"projectId, projectPath, or owner + repo is required"};return encodeURIComponent(`${n}/${s}`)}parsePipelineVariables(e){if(null==e)return{};if("object"!=typeof e||Array.isArray(e))throw{status:400,message:"Pipeline variables must be an object"};const t={};for(const[n,s]of Object.entries(e)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw{status:400,message:`Pipeline variable name is invalid: ${n}`};if(null!=s){if("string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s)throw{status:400,message:`Pipeline variable value for "${n}" is invalid`};t[n]=String(s)}}return t}isUsableTriggerToken(e){return"string"==typeof e&&e.length>=20&&!e.includes("*")}async resolvePipelineTriggerToken(e,t){const n=this.parseOptionalString(t.triggerToken,"triggerToken");if(n)return n;if(!0!==t.createTriggerIfMissing)throw{status:400,message:"triggerToken is required unless createTriggerIfMissing is true"};const s=this.parseOptionalString(t.triggerDescription,"triggerDescription")??"Agentrix webhook bridge",a=(await this.requestPaginated(`/projects/${e}/triggers`)).find(e=>e.description===s&&this.isUsableTriggerToken(e.token));if(a?.token)return a.token;const i=new URLSearchParams;i.set("description",s);const o=await this.requestForm(`/projects/${e}/triggers`,i);if(!this.isUsableTriggerToken(o.token))throw{status:502,message:"GitLab did not return a usable pipeline trigger token"};return o.token}async ensurePipelineTriggerToken(e){const t=this.resolveProjectPath(e);return{token:await this.resolvePipelineTriggerToken(t,{...e,createTriggerIfMissing:!0})}}async triggerPipeline(e){const t=this.resolveProjectPath(e),n=this.parseNonEmptyString(e.ref,"ref"),s=this.parsePipelineVariables(e.variables),a=await this.resolvePipelineTriggerToken(t,e),i=new URLSearchParams;i.set("token",a),i.set("ref",n);for(const[e,t]of Object.entries(s))i.set(`variables[${e}]`,t);const o=await this.requestForm(`/projects/${t}/trigger/pipeline`,i);return{id:o.id,iid:o.iid,projectId:o.project_id,ref:o.ref,sha:o.sha,status:o.status,source:o.source,url:o.web_url,createdAt:o.created_at,updatedAt:o.updated_at}}parseProxyMethod(e){const t="string"==typeof e?e.toUpperCase():"GET";if("GET"===t||"POST"===t||"PUT"===t||"PATCH"===t||"DELETE"===t)return t;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 t=new URLSearchParams;for(const[n,s]of Object.entries(e))if(null!=s)if(Array.isArray(s))for(const e of s){if("string"!=typeof e&&"number"!=typeof e&&"boolean"!=typeof e)throw{status:400,message:`Proxy query value for "${n}" is invalid`};t.append(n,String(e))}else{if("string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s)throw{status:400,message:`Proxy query value for "${n}" is invalid`};t.append(n,String(s))}return t.toString()}isProxyAllowed(e,t){return on.some(n=>n.method===e&&n.pattern.test(t))}async requestGitlabApi(e){const t=this.parseProxyMethod(e.method),n=this.parseProxyPath(e.path),s=this.buildProxyQueryString(e.query),a=s.length>0?`${n}?${s}`:n;if(!this.isProxyAllowed(t,n))throw{status:403,message:`Proxy path not allowed: ${t} ${n}`};return"GET"===t?await this.request(a,t):await this.request(a,t,e.body)}}function cn(e){const t=e.replace(/\/+$/,"");return t.endsWith("/v1")?`${t}/models`:`${t}/v1/models`}function ln(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/+$/,"")}`}catch{return e}}function pn(e){return ce.isAxiosError(e)?{message:e.message,status:e.response?.status,code:e.code}:{message:e instanceof Error?e.message:String(e)}}async function dn(e,t){if(!e.apiKey)throw new Error("missing api key");const n="anthropic"===t?{"x-api-key":e.apiKey,"anthropic-version":"2023-06-01"}:{Authorization:`Bearer ${e.apiKey}`},s=await ce.get(cn(e.baseUrl),{headers:n,timeout:1e4});return(s.data?.data||[]).map(e=>e&&"object"==typeof e&&"id"in e?String(e.id):null).filter(e=>Boolean(e))}async function un(e){const t=function(e){try{const t=new URL(e).hostname.toLowerCase();if("api.anthropic.com"===t||t.endsWith(".anthropic.com"))return"anthropic";if("api.openai.com"===t||t.endsWith(".openai.com"))return"openai"}catch{return null}return null}(e.baseUrl),n=t?[t]:["anthropic","openai"];let s;for(const a of n){pe.info(`[MODELS] Requesting models: source=${e.source}, protocol=${a}, url=${ln(cn(e.baseUrl))}, officialProtocol=${t??"none"}`);try{const t=await dn(e,a);return pe.info(`[MODELS] Models request succeeded: source=${e.source}, protocol=${a}, count=${t.length}`),t}catch(t){s=t;const n=pn(t);pe.warn(`[MODELS] Models request failed: source=${e.source}, protocol=${a}, status=${n.status??"-"}, code=${n.code??"-"}, message=${n.message}`)}}throw s instanceof Error?s:new Error("failed to fetch models")}function mn(e,t){const n=t.ANTHROPIC_MODEL||e?.model||process.env.ANTHROPIC_MODEL;if(!n)return;const s=n.toLowerCase();return"opus"===s?t.ANTHROPIC_DEFAULT_OPUS_MODEL||process.env.ANTHROPIC_DEFAULT_OPUS_MODEL||"claude-opus-4-6":"sonnet"===s?t.ANTHROPIC_DEFAULT_SONNET_MODEL||process.env.ANTHROPIC_DEFAULT_SONNET_MODEL||"claude-sonnet-4-6":"haiku"===s?t.ANTHROPIC_DEFAULT_HAIKU_MODEL||process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL||"claude-haiku-4-5":n}async function gn(e){const t=[];if(!e||"claude"===e){const e=function(){const e=function(e){if(!r(e))return null;try{return JSON.parse(c(e,"utf-8"))}catch{return null}}(w(le.claudeConfigDir,"settings.json")),t=e?.env||{},n=t.ANTHROPIC_BASE_URL||process.env.ANTHROPIC_BASE_URL||"https://api.anthropic.com",s=t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||process.env.ANTHROPIC_API_KEY;return s?{baseUrl:n,apiKey:s,source:"claude",defaultModel:mn(e,t)}:null}();e&&t.push(e)}if(!e||"codex"===e){const e=function(){const e=w(le.codexHomeDir,"config.toml");if(!r(e))return process.env.OPENAI_API_KEY?{baseUrl:process.env.OPENAI_BASE_URL||"https://api.openai.com",apiKey:process.env.OPENAI_API_KEY,source:"codex",defaultModel:process.env.OPENAI_MODEL}:null;const t=c(e,"utf-8"),n=t.match(/^model_provider\s*=\s*"([^"]+)"/m)?.[1]||"openai",s=t.match(/^model\s*=\s*"([^"]+)"/m)?.[1],a=t.match(new RegExp(`\\[model_providers\\.${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\]([\\s\\S]*?)(?=\\n\\[|$)`)),i=a?.[1]||"",o=i.match(/^\s*base_url\s*=\s*"([^"]+)"/m)?.[1]||process.env.OPENAI_BASE_URL||"https://api.openai.com",l=i.match(/^\s*env_key\s*=\s*"([^"]+)"/m)?.[1]||("agentrix"===n?"AGENTRIX_API_KEY":"OPENAI_API_KEY");return{baseUrl:o,apiKey:process.env[l],source:"codex",defaultModel:s}}();e&&t.push(e)}pe.info(`[MODELS] Listing available models: agentType=${e??"all"}, endpointCount=${t.length}, endpoints=${t.map(e=>`${e.source}:${ln(e.baseUrl)}:hasKey=${Boolean(e.apiKey)}:defaultModel=${e.defaultModel??"-"}`).join(",")||"-"}`);const n=new Set,s=[],a=t.find(e=>e.defaultModel)?.defaultModel;for(const e of t)try{for(const t of await un(e))n.add(t)}catch(t){const n=pn(t);s.push({source:e.source,baseUrl:ln(e.baseUrl),message:n.message,status:n.status,code:n.code})}const i=Array.from(n).sort();return 0===i.length?pe.warn(`[MODELS] No models available: endpointCount=${t.length}, failures=${JSON.stringify(s)}`):pe.info(`[MODELS] Listed available models: count=${i.length}`),{models:i,defaultModel:a}}function hn(e,t){return{eventId:j(),status:"failed",opCode:e,message:t}}function fn(e){return async(t,n)=>{if(pe.info(`[EVENT HANDLER] create-task: ${t.taskId}, agentType=${t.agentType}, agentId=${t.agentId}`),"shadow"!==t.taskType&&e.onCompanionInteraction?.(t.chatId),"task-message"!==t.event)return pe.error(`[EVENT HANDLER] create-task expects task-message, got ${t.event} for task ${t.taskId}`),void n(hn(t.eventId,`create-task expects task-message, got ${t.event}`));try{const s=await e.workerManager.startWorker(t,"create-task");"success"!==s.status&&pe.error(`[EVENT HANDLER] create-task startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){pe.error(`[EVENT HANDLER] create-task startup threw for task ${t.taskId}:`,e),n(hn(t.eventId,e instanceof Error?e.message:"create-task startup failed"))}}}function vn(e){return async(t,n)=>{pe.debug(`[EVENT HANDLER] resume-task: ${t.taskId}, agentSessionId=${t.agentSessionId}`),"shadow"!==t.taskType&&e.onCompanionInteraction?.(t.chatId);try{const s=await e.workerManager.startWorker(t,"resume-task");"success"!==s.status&&pe.error(`[EVENT HANDLER] resume-task startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){pe.error(`[EVENT HANDLER] resume-task startup threw for task ${t.taskId}:`,e),n(hn(t.eventId,e instanceof Error?e.message:"resume-task startup failed"))}}}function xn(e){return async(t,n)=>{if(pe.info(`[EVENT HANDLER] list-models received: machineId=${t.machineId}, agentType=${t.agentType??"all"}, eventId=${t.eventId}`),t.machineId!==e.machineId)return pe.warn(`[EVENT HANDLER] list-models target mismatch: requested=${t.machineId}, current=${e.machineId}`),void n(hn(t.eventId,"list-models target machine mismatch"));try{const{models:e,defaultModel:s}=await gn(t.agentType);if(0===e.length&&!s)return pe.warn(`[EVENT HANDLER] list-models found no models and no default model: machineId=${t.machineId}, agentType=${t.agentType??"all"}`),void n(hn(t.eventId,"No models available from configured endpoints"));pe.info(`[EVENT HANDLER] list-models success: machineId=${t.machineId}, count=${e.length}, defaultModel=${s??"-"}`),n({eventId:j(),status:"success",opCode:t.eventId,data:{models:e,defaultModel:s}})}catch(e){pe.error(`[EVENT HANDLER] list-models failed: machineId=${t.machineId}, agentType=${t.agentType??"all"}:`,e),n(hn(t.eventId,e instanceof Error?e.message:"Failed to list models"))}}}function yn(e){return async t=>{pe.info("[EVENT HANDLER] shutdown-machine received",t),e.requestShutdown("agentrix-app",t.reason)}}function bn(e){return async(t,n)=>{pe.info(`[EVENT HANDLER] deploy-agent received: taskId=${t.taskId}, draftAgentId=${t.draftAgentId}, targetAgentId=${t.targetAgentId}, sourcePath=${t.sourcePath}`);try{const s=await e.workerManager.startDeploymentWorker(t);"success"!==s.status&&pe.error(`[EVENT HANDLER] deploy-agent startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){pe.error(`[EVENT HANDLER] deploy-agent startup threw for task ${t.taskId}:`,e),n(hn(t.eventId,e instanceof Error?e.message:"deploy-agent startup failed"))}}}function wn(e){return async(t,n)=>{pe.info(`[EVENT HANDLER] hive-publish received: taskId=${t.taskId}, name=${t.name}, repoDir=${t.repoDir}`);try{const s=await e.workerManager.startHivePublishWorker(t);"success"!==s.status&&pe.error(`[EVENT HANDLER] hive-publish startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){pe.error(`[EVENT HANDLER] hive-publish startup threw for task ${t.taskId}:`,e),n(hn(t.eventId,e instanceof Error?e.message:"hive-publish startup failed"))}}}function kn(e){return async(t,n)=>{pe.info(`[EVENT HANDLER] hive-install received: taskId=${t.taskId}, name=${t.name}, hiveListingId=${t.hiveListingId}`);try{const s=await e.workerManager.startHiveInstallWorker(t);"success"!==s.status&&pe.error(`[EVENT HANDLER] hive-install startup failed for task ${t.taskId}: ${s.message||"unknown error"}`),n(s)}catch(e){pe.error(`[EVENT HANDLER] hive-install startup threw for task ${t.taskId}:`,e),n(hn(t.eventId,e instanceof Error?e.message:"hive-install startup failed"))}}}function In(e){return async t=>{pe.info(`[EVENT HANDLER] stop-task: ${t.taskId}, reason=${t.reason||"n/a"}`),e.workerManager.stopSession(t.taskId)||pe.warn(`[EVENT HANDLER] stop-task failed, task not found: ${t.taskId}`)}}function Sn(e){return async t=>{pe.info(`[GITLAB PROXY] request received: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}, ttlMs=${t.ttlMs}, payloadKeys=${function(e){const t=Object.keys(e||{});return t.length>0?t.join(","):"-"}(t.payload)}`);const n=Date.now(),s=n=>{const s={eventId:t.requestId,requestId:t.requestId,machineId:e.machineId,...n};e.client?(e.client.send("daemon-gitlab-response",s),pe.info(`[GITLAB PROXY] response sent: reqId=${t.requestId}, op=${t.operation}, success=${n.success}, executionMs=${n.executionTimeMs}`)):pe.error(`[GITLAB PROXY] response dropped: reqId=${t.requestId}, op=${t.operation}, reason=socket-client-unavailable`)};try{const e=await Zt();if(!e)return pe.warn(`[GITLAB PROXY] git server encryption key unavailable: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),void s({success:!1,errorCode:"PAT_MISSING",errorMessage:"Git server encryption key not available",executionTimeMs:Date.now()-n});const a=sn(t.gitServerId,e);if(!a)return pe.warn(`[GITLAB PROXY] PAT missing: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),void s({success:!1,errorCode:"PAT_MISSING",errorMessage:`No PAT configured for git server ${t.gitServerId}`,executionTimeMs:Date.now()-n});const i=t.payload.apiUrl;if(!i)return pe.warn(`[GITLAB PROXY] apiUrl missing in payload: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}`),void s({success:!1,errorCode:"PAT_MISSING",errorMessage:"GitLab API URL not provided in request",executionTimeMs:Date.now()-n});pe.info(`[GITLAB PROXY] executing: reqId=${t.requestId}, op=${t.operation}, gitServer=${t.gitServerId}, apiHost=${function(e){try{return new URL(e).host}catch{return"invalid-url"}}(i)}`);const o=new rn(i,a,{requestId:t.requestId,gitServerId:t.gitServerId}),r=await o.executeOperation(t.operation,t.payload);pe.info(`[GITLAB PROXY] execution succeeded: reqId=${t.requestId}, op=${t.operation}, summary=${function(e,t){if(Array.isArray(t))return`items=${t.length}`;if(t&&"object"==typeof t){const n=t;return"resolveGitAuthContext"===e?`authMode=${String(n.authMode??"unknown")}, hasPat=${Boolean(n.hasPat)}`:"number"in n||"state"in n?`number=${String(n.number??"-")}, state=${String(n.state??"-")}`:`keys=${Object.keys(n).join(",")||"-"}`}return"type="+typeof t}(t.operation,r)}`),s({success:!0,data:r,executionTimeMs:Date.now()-n})}catch(e){const a=e;let i="GITLAB_CONNECTIVITY_FAILED";401===a.status?i="PAT_INVALID":403===a.status?i="PAT_SCOPE_INSUFFICIENT":404===a.status&&(i="RESOURCE_NOT_FOUND");const o="string"==typeof a.message?a.message:"Unknown error",r="string"==typeof a.detail?function(e,t=300){return e.length<=t?e:`${e.slice(0,t)}...`}(a.detail):void 0,c="number"==typeof a.status?String(a.status):"unknown";pe.error(`[GITLAB PROXY] execution failed: reqId=${t.requestId}, op=${t.operation}, errorCode=${i}, status=${c}, message=${o}${r?`, detail=${r}`:""}`),s({success:!1,errorCode:i,errorMessage:o,executionTimeMs:Date.now()-n})}}}const Tn=parseInt(process.env.MAX_WORKSPACE_FILE_SIZE_MB||"100",10);function En(e,t){if(!e)return;if("string"==typeof t)return void(e.sendMessage?e.sendMessage(t):e.send&&e.send(t));const n=Buffer.from(t);e.sendMessageBinary?e.sendMessageBinary(n):e.send&&e.send(n)}class An{client;machineId;iceServers=[];sessions=new Map;rtcModule;peerConstructor;constructor(e,t){this.client=e,this.machineId=t;const n=Ue(import.meta.url);var s;this.rtcModule=n("node-datachannel"),this.peerConstructor=(s=this.rtcModule).RTCPeerConnection||s.PeerConnection||s.RTCConnection||s.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))):pe.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:j()})}handleIceServersResponse(e){this.iceServers=function(e){const t=[];return e.forEach(e=>{Array.isArray(e.urls)?t.push(...e.urls):t.push(e.urls)}),t}(e.iceServers),pe.info(`[RTC] Loaded ${this.iceServers.length} ICE servers`)}handleRtcRequest(e){if(!this.peerConstructor)return;const t=e.userId;if(!t)return void pe.warn("[RTC] machine-rtc-request missing userId");const n=e.workspaceUserId||t,s=e.taskId;if(this.sessions.has(e.sessionId))return void this.sendMachineRtcResponse(e.sessionId,t,!0);const a=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers}),i={sessionId:e.sessionId,userId:t,workspaceUserId:n,allowedTaskId:s||void 0,peerConnection:a,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]};this.sessions.set(e.sessionId,i),this.registerPeerHandlers(i),this.sendMachineRtcResponse(e.sessionId,t,!0)}sendMachineRtcResponse(e,t,n,s){this.client.send("machine-rtc-response",{eventId:j(),machineId:this.machineId,sessionId:e,accepted:n,reason:s,userId:t,capabilities:{dataChannel:!0}})}handleRtcSignal(e){if(!this.peerConstructor)return;if("app"!==e.from)return;const t=e.userId;if(!t)return void pe.warn("[RTC] rtc-signal missing userId");const n=e.workspaceUserId||t,s=e.taskId;let a=this.sessions.get(e.sessionId);if(!a){const i=new this.peerConstructor(e.sessionId,{iceServers:this.iceServers});a={sessionId:e.sessionId,userId:t,workspaceUserId:n,allowedTaskId:s||void 0,peerConnection:i,lastActivity:Date.now(),remoteDescriptionSet:!1,pendingCandidates:[]},this.sessions.set(e.sessionId,a),this.registerPeerHandlers(a)}try{this.applyRemoteSignal(a,e.signal)}catch(e){pe.warn("[RTC] Failed to apply remote signal",e)}}registerPeerHandlers(e){const{peerConnection:t}=e;t.onStateChange?.(t=>{pe.info(`[RTC] Peer state (${e.sessionId}): ${t}`)}),t.onGatheringStateChange?.(t=>{pe.info(`[RTC] ICE gathering (${e.sessionId}): ${t}`)}),t.onLocalDescription?.((t,n)=>{const s=function(e,t){return e&&"object"==typeof e&&"string"==typeof e.sdp?{sdp:e.sdp,type:e.type||t}:{sdp:String(e||""),type:t}}(t,n);this.client.send("rtc-signal",{eventId:j(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:s,userId:e.userId})}),t.onLocalCandidate?.((t,n,s)=>{const a=function(e,t,n){return"string"==typeof e?{candidate:e,sdpMid:t||"0",sdpMLineIndex:n??0}:e&&"string"==typeof e.candidate?{candidate:e.candidate,sdpMid:e.sdpMid||e.mid||t||"0",sdpMLineIndex:"number"==typeof e.sdpMLineIndex?e.sdpMLineIndex:n??0}:null}(t,n,s);a&&this.client.send("rtc-signal",{eventId:j(),machineId:this.machineId,sessionId:e.sessionId,from:"machine",signal:{candidate:a},userId:e.userId})}),t.onDataChannel?.(t=>{e.dataChannel=t,this.registerDataChannel(e,t)})}registerDataChannel(e,t){t.onOpen?.(()=>{pe.info(`[RTC] Data channel open (${e.sessionId})`),e.lastActivity=Date.now(),En(t,JSON.stringify({v:1,type:"control.ready",channel:"control",requestId:`req-${e.sessionId}`,streamId:0,timestamp:(new Date).toISOString(),payload:{ok:!0}}))}),t.onClosed?.(()=>{pe.warn(`[RTC] Data channel closed (${e.sessionId})`),e.peerConnection.close?.(),this.sessions.delete(e.sessionId)}),t.onError?.(t=>{pe.error(`[RTC] Data channel error (${e.sessionId})`,t)}),t.onMessage?.(t=>{e.lastActivity=Date.now(),this.handleDataChannelMessage(e,t)})}handleDataChannelMessage(e,t){if(Buffer.isBuffer(t)||t instanceof Uint8Array){try{L(new Uint8Array(t))}catch(e){pe.warn("[RTC] Received binary payload without handler")}return}let n=null;if("string"==typeof t?n=t:t&&"string"==typeof t.text&&(n=t.text),!n)return;let s=null;try{s=JSON.parse(n)}catch(e){return void pe.warn("[RTC] Non-JSON message",n)}s&&"string"==typeof s.type&&"file.request"===s.type&&this.handleFileRequest(e,s).catch(e=>{pe.error("[RTC] Failed to handle file request",e)})}async handleFileRequest(e,t){const n=t.payload;if(!n)return;if(n.userId!==e.workspaceUserId)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:"unauthorized",message:"Unauthorized workspace access"}});if(e.allowedTaskId&&n.taskId!==e.allowedTaskId)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:"unauthorized",message:"Unauthorized task access"}});const s=(a=n.userId,o=n.taskId,r=n.relativePath,le.resolveWorkspaceFilePath(a,o,r));var a,o,r;if(!i.existsSync(s))return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:"file_not_found",message:"File or directory not found"}});const c=await i.promises.stat(s);if(!function(e,t){return!t||e.mtime.toISOString()!==t}(c,n.ifModifiedSince))return void this.sendControl(e,{v:1,type:"file.not_modified",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString()});if(c.isDirectory()||"directory"===n.entryType){const n=await i.promises.readdir(s,{withFileTypes:!0}),a={entries:await Promise.all(n.map(async e=>{const t=y.join(s,e.name),n=await i.promises.stat(t);return{name:e.name,type:e.isDirectory()?"directory":"file",size:n.size,modifiedAt:n.mtime.toISOString()}})),modifiedAt:c.mtime.toISOString()};return void this.sendControl(e,{v:1,type:"file.dir",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:a})}const l=1024*(n.maxFileSizeMB??Tn)*1024;if(c.size>l)return void this.sendControl(e,{v:1,type:"file.error",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),error:{code:"file_too_large",message:"File exceeds size limit"}});const p=Vt.lookup(s)||"application/octet-stream",d={size:c.size,mimeType:"string"==typeof p?p:"application/octet-stream",modifiedAt:c.mtime.toISOString()};this.sendControl(e,{v:1,type:"file.meta",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:d}),await this.sendFileChunks(e,t.streamId,s),this.sendControl(e,{v:1,type:"file.end",channel:"file",requestId:t.requestId,streamId:t.streamId,timestamp:(new Date).toISOString(),payload:{size:c.size}})}async sendFileChunks(e,t,n){const s=e.dataChannel;if(!s)return;const a=i.createReadStream(n,{highWaterMark:65536});let o=0;await new Promise((e,n)=>{a.on("data",e=>{const n=H.Binary|(0===o?H.Start:0),a=Buffer.isBuffer(e)?e:Buffer.from(e),i=new Uint8Array(a.buffer,a.byteOffset,a.byteLength),r=G({streamId:t,seq:o,flags:n,payloadLength:i.length},i);En(s,r),o+=1}),a.on("end",()=>{if(o>0){const e=G({streamId:t,seq:o,flags:H.End|H.Binary,payloadLength:0},new Uint8Array);En(s,e)}e()}),a.on("error",e=>n(e))})}sendControl(e,t){const n=e.dataChannel;n&&En(n,JSON.stringify(t))}applyRemoteSignal(e,t){const{peerConnection:n}=e;if(t&&t.sdp&&t.type)return n.setRemoteDescription?.(t.sdp,t.type),e.remoteDescriptionSet=!0,e.pendingCandidates?.forEach(e=>{try{n.addRemoteCandidate?.(e.candidate,e.mid)}catch(e){pe.warn("[RTC] Failed to add queued candidate",e)}}),void(e.pendingCandidates=[]);if(t&&t.candidate){const s=t.candidate,a="string"==typeof s?s:s&&"string"==typeof s.candidate?s.candidate:null,i=t.sdpMid||s?.sdpMid||s?.mid||"0";if(a){if(!e.remoteDescriptionSet)return void e.pendingCandidates?.push({candidate:a,mid:i});n.addRemoteCandidate?.(a,i)}}}}class Cn{client;context;rtcManager;constructor(e,t,n){const{machineId:s,...a}=e;this.client=new Ht(a),this.context={machineId:s,workerManager:t,requestShutdown:n.requestShutdown,client:this.client},this.rtcManager=new An(this.client,s),this.initHandlers(),this.rtcManager.registerHandlers()}connect(){return new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("Machine connection timeout after 30 seconds"))},3e4);this.client.onLifecycle("connect",()=>{clearTimeout(n),e()}),this.client.onLifecycle("connect_error",e=>{clearTimeout(n),t(e)}),this.client.connect()})}async disconnect(){this.client.connected&&await this.client.flush(5e3).catch(()=>{}),this.rtcManager.shutdown(),this.client.disconnect()}setCompanionInteractionCallback(e){this.context.onCompanionInteraction=e}initHandlers(){const e={"create-task":fn(t=this.context),"resume-task":vn(t),"list-models":xn(t),"stop-task":In(t),"deploy-agent":bn(t),"hive-publish":wn(t),"hive-install":kn(t),"shutdown-machine":yn(t),"workspace-file-request":Jt({client:t.client}),"daemon-gitlab-request":Sn(t)};var t;this.client.onEventWithAck("create-task",e["create-task"]),this.client.onEventWithAck("resume-task",e["resume-task"]),this.client.onEventWithAck("list-models",e["list-models"]),this.client.onEvent("stop-task",e["stop-task"]),this.client.onEventWithAck("deploy-agent",e["deploy-agent"]),this.client.onEventWithAck("hive-publish",e["hive-publish"]),this.client.onEventWithAck("hive-install",e["hive-install"]),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 $n=null;let _n=!1;async function Pn(){if(_n)pe.info("[caffeinate] Already stopping, skipping");else if($n&&!$n.killed){_n=!0,pe.info(`[caffeinate] Stopping caffeinate process PID ${$n.pid}`);try{$n.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),$n&&!$n.killed&&$n.kill("SIGKILL"),$n=null,_n=!1}catch(e){pe.info("[caffeinate] Error stopping caffeinate:",e),_n=!1}}}let Rn=!1;function Mn(e){const{pid:t,name:n,cmd:s}=e;if(t===process.pid||t===process.ppid)return null;if(!(n.includes("agentrix")||"node"===n&&(s.includes("agentrix-cli")||s.includes("dist/index.mjs")||s.includes("dist\\index.mjs"))||("MainThread"===n||n.includes("MainThread"))&&(s.includes("agentrix-cli")||s.includes("dist/index.mjs")||s.includes("agentrix.mjs"))||s.includes("agentrix.mjs")||s.includes("agentrix-cli")||s.includes("tsx")&&s.includes("src/index.ts")&&s.includes("agentrix-cli")))return null;let a="unknown";const i=s.toLowerCase();return i.includes(" worker")?a="worker":i.includes(" upgrade-daemon")?a="upgrade-daemon":i.includes(" daemon")?a="daemon":i.includes("doctor")&&(a="doctor"),{pid:t,command:s||n,type:a}}async function On(){try{let e;e="win32"===process.platform?await async function(){try{const e=qe("wmic process where \"name='node.exe'\" get ProcessId,CommandLine /format:csv",{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}),t=[],n=e.split("\n").map(e=>e.trim()).filter(Boolean);for(let e=1;e<n.length;e++){const s=n[e];if(!s)continue;const a=s.indexOf(",");if(-1===a)continue;const i=s.substring(a+1),o=i.lastIndexOf(",");if(-1===o)continue;const r=i.substring(0,o).trim(),c=i.substring(o+1).trim(),l=parseInt(c,10);isNaN(l)||t.push({pid:l,name:"node",cmd:r})}return t}catch(e){return[]}}():(await Le()).map(e=>({pid:e.pid,name:e.name||"",cmd:e.cmd||""}));const t=[];for(const n of e){const e=Mn(n);e&&t.push(e)}return t}catch(e){return[]}}function Dn(e){try{const t="win32"===process.platform?"where":"which";return{available:!0,path:qe(`${t} ${e}`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}}catch{return{available:!1}}}function Nn(){const e=Ge(),t=function(){const e=Dn("git"),t=Dn("claude"),n=Dn("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:t.available,required:!0,description:"Claude Code CLI (required for most features)",installCommand:"npm install -g @anthropic-ai/claude-code",path:t.path},{name:"codex",installed:n.available,required:!1,description:"Codex CLI (optional, for Codex tasks)",installCommand:"npm install -g @codex-ai/codex-cli",path:n.path}]}(),n=function(e){if("macos"===e){const e=Dn("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=Dn("bwrap"),t=Dn("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:t.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:t.path}]}return[]}(e),s=t.filter(e=>e.required&&!e.installed),a=n.filter(e=>e.required&&!e.installed);return{cli:t,sandbox:n,allSatisfied:0===s.length&&0===a.length,missingSandbox:a,missingCli:s}}function Un(){const e=Nn(),t=[],n=e.cli.find(e=>"git"===e.name);n&&!n.installed&&t.push("git");for(const n of e.missingSandbox)t.push(n.name);return{ok:0===t.length,missing:t}}function jn(){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:le.agentrixHomeDir,serverUrl:le.serverUrl,logsDir:le.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 qn(e){if(e||(e="all"),console.log(P.bold.cyan("\n🩺 Agentrix CLI Doctor\n")),"all"===e){console.log(P.bold("📋 Basic Information")),console.log(`Agentrix CLI Version: ${P.green(ue.version)}`),console.log(`Platform: ${P.green(process.platform)} ${process.arch}`),console.log(`Node.js Version: ${P.green(process.version)}`),console.log(""),console.log(P.bold("🔧 Daemon Spawn Diagnostics"));const e=de(),t=w(e,"bin","agentrix.mjs"),n=w(e,"dist","index.mjs");console.log(`Project Root: ${P.blue(e)}`),console.log(`Wrapper Script: ${P.blue(t)}`),console.log(`CLI Entrypoint: ${P.blue(n)}`),console.log(`Wrapper Exists: ${r(t)?P.green("✓ Yes"):P.red("❌ No")}`),console.log(`CLI Exists: ${r(n)?P.green("✓ Yes"):P.red("❌ No")}`),console.log(""),console.log(P.bold("⚙️ Configuration")),console.log(`Agentrix Home: ${P.blue(le.agentrixHomeDir)}`),console.log(`Server URL: ${P.blue(le.serverUrl)}`),console.log(`Logs Dir: ${P.blue(le.getStatePaths().logsDir)}`),console.log(P.bold("\n🌍 Environment Variables"));const s=jn();console.log(`AGENTRIX_HOME_DIR: ${s.AGENTRIX_HOME_DIR?P.green(s.AGENTRIX_HOME_DIR):P.gray("not set")}`),console.log(`AGENTRIX_SERVER_URL: ${s.AGENTRIX_SERVER_URL?P.green(s.AGENTRIX_SERVER_URL):P.gray("not set")}`),console.log(`DANGEROUSLY_LOG_TO_SERVER: ${s.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING?P.yellow("ENABLED"):P.gray("not set")}`),console.log(`DEBUG: ${s.DEBUG?P.green(s.DEBUG):P.gray("not set")}`),console.log(`NODE_ENV: ${s.NODE_ENV?P.green(s.NODE_ENV):P.gray("not set")}`),console.log(P.bold("\n🔐 Authentication"));try{await le.readCredentials()?console.log(P.green("✓ Authenticated (credentials found)")):console.log(P.yellow("⚠️ Not authenticated (no credentials)"))}catch(e){console.log(P.red("❌ Error reading credentials"))}!function(e=!1){const t=Nn(),n=Ge();console.log(P.bold("\n🔧 CLI Dependencies"));for(const n of t.cli)if(n.installed)console.log(P.green(`✓ ${n.name}`),P.gray(`- ${n.description}`)),e&&n.path&&console.log(P.gray(` Location: ${n.path}`));else{const e=n.required?P.red("❌"):P.yellow("⚠️");console.log(`${e} ${n.name}`,P.gray(`- ${n.description}`)),n.installCommand&&console.log(P.blue(` Install: ${n.installCommand}`))}if(t.sandbox.length>0){console.log(P.bold("\n🔒 Sandbox Dependencies")),console.log(P.gray(`Platform: ${n}`));for(const n of t.sandbox)n.installed?(console.log(P.green(`✓ ${n.name}`),P.gray(`- ${n.description}`)),e&&n.path&&console.log(P.gray(` Location: ${n.path}`))):(console.log(P.red(`❌ ${n.name}`),P.gray(`- ${n.description}`)),n.installCommand&&console.log(P.blue(` Install: ${n.installCommand}`)))}else console.log(P.bold("\n🔒 Sandbox Dependencies")),console.log(P.yellow(`⚠️ Platform ${n} not supported - sandbox will be disabled`));if(t.allSatisfied)return console.log(P.bold.green("\n✓ All required dependencies are installed")),!0;{console.log(P.bold.red("\n⚠️ Missing Required Dependencies"));const e=[...t.missingCli,...t.missingSandbox];for(const t of e)console.log(P.red(` • ${t.name}`));console.log(P.yellow("\nPlease install missing dependencies before starting the daemon."))}}(!0)}console.log(P.bold("\n🤖 Daemon Status"));try{const t=await Pt(),n=await le.readDaemonState();if(t&&n?(console.log(P.green("✓ Daemon is running")),console.log(` PID: ${n.pid}`),console.log(` Started: ${new Date(n.startTime).toLocaleString()}`),console.log(` CLI Version: ${n.cliVersion}`),n.port&&console.log(` HTTP Port: ${n.port}`)):n&&!t?console.log(P.yellow("⚠️ Daemon state exists but process not running (stale)")):console.log(P.red("❌ Daemon is not running")),n){console.log(P.bold("\n📄 Daemon State:"));const e=le.getStatePaths();console.log(P.blue(`Location: ${e.daemonStateFile}`)),console.log(P.gray(JSON.stringify(n,null,2)))}const s=await On();if(s.length>0){console.log(P.bold("\n🔍 All Agentrix CLI Processes"));const e=s.reduce((e,t)=>(e[t.type]||(e[t.type]=[]),e[t.type].push(t),e),{});Object.entries(e).forEach(([e,t])=>{console.log(P.blue(`\n${{daemon:"🤖 Daemon","upgrade-daemon":"🔄 Upgrade Daemon",worker:"🔗 Workers",doctor:"🩺 Doctor",unknown:"❓ Unknown"}[e]||e}:`)),t.forEach(({pid:t,command:n})=>{const s=e.startsWith("dev")?P.cyan:e.includes("daemon")?P.blue:P.gray;console.log(` ${s(`PID ${t}`)}: ${P.gray(n)}`)})})}else console.log(P.red("❌ No agentrix processes found"));"all"===e&&s.length>1&&(console.log(P.bold("\n💡 Process Management")),console.log(P.gray("To clean up runaway processes: agentrix killall")))}catch(e){console.log(P.red("❌ Error checking daemon status"))}}let Ln=null;async function Hn(){const e=zn(),t=function(e){try{return JSON.stringify(e)}catch{return""}}(e);if(Ln&&Ln.expiresAt>Date.now()&&Ln.overridesSignature===t)return Ln.openers;const n=Wn(e),s=[];for(const e of n){const t=e.isSupported();t&&s.push({id:e.id,label:e.label,kind:e.kind,method:e.method,urlTemplate:e.urlTemplate,supported:t})}return Ln={expiresAt:Date.now()+6048e5,openers:s,overridesSignature:t},s}function Gn(e){const t=process.platform;if("darwin"===t)return function(e){const t=Fn(e),n=[];if(t){const e=Qn(t);n.push("-e",`set defaultLocation to POSIX file "${e}"`,"-e","set chosenFolder to choose folder default location defaultLocation")}else n.push("-e","set chosenFolder to choose folder");return n.push("-e","POSIX path of chosenFolder"),Bn(Yn("osascript",n,{captureOutput:!0}))}(e);if("win32"===t)return function(e){const t=Xn("powershell")?"powershell":Xn("pwsh")?"pwsh":null;if(!t)throw new Error("PowerShell is required to pick a directory");const n=Fn(e),s=["Add-Type -AssemblyName System.Windows.Forms;","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;",n?`$dialog.SelectedPath = '${Jn(n)}';`:"","$null = $dialog.ShowDialog();","$dialog.SelectedPath;"].filter(Boolean).join(" ");return Bn(Yn(t,"powershell"===t?["-NoProfile","-STA","-Command",s]:["-NoProfile","-Sta","-Command",s],{captureOutput:!0}))}(e);if("linux"===t)return function(e){const t=Fn(e);if(Xn("zenity")){const e=["--file-selection","--directory","--title=Select Folder"];if(t){const n=t.endsWith("/")?t:`${t}/`;e.push(`--filename=${n}`)}return Bn(Yn("zenity",e,{captureOutput:!0}))}if(Xn("kdialog")){const e=["--getexistingdirectory"];return t&&e.push(t),Bn(Yn("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 Wn(e){const t=process.platform,n=["Visual Studio Code","Visual Studio Code - Insiders"],s=["Cursor"],a=["IntelliJ IDEA","IntelliJ IDEA CE","IntelliJ IDEA Ultimate"],i=["WebStorm"],o=["PyCharm","PyCharm CE","PyCharm Professional"],c=[{id:"vscode",label:"VS Code",kind:"editor",method:"scheme",urlTemplate:"vscode://file/{path}?windowId=_blank",scheme:"vscode",macAppNames:n,isSupported:()=>Kn("vscode",t,n)},{id:"cursor",label:"Cursor",kind:"editor",method:"scheme",urlTemplate:"cursor://file/{path}?windowId=_blank",scheme:"cursor",macAppNames:s,isSupported:()=>Kn("cursor",t,s)},{id:"idea",label:"IntelliJ IDEA",kind:"ide",method:"scheme",urlTemplate:"idea://open?file={path}&newWindow=true",scheme:"idea",macAppNames:a,isSupported:()=>Kn("idea",t,a)},{id:"pycharm",label:"PyCharm",kind:"ide",method:"scheme",urlTemplate:"pycharm://open?file={path}&newWindow=true",scheme:"pycharm",macAppNames:o,isSupported:()=>Kn("pycharm",t,o)},{id:"webstorm",label:"WebStorm",kind:"ide",method:"scheme",urlTemplate:"webstorm://open?file={path}&newWindow=true",scheme:"webstorm",macAppNames:i,isSupported:()=>Kn("webstorm",t,i)},{id:"file-manager",label:"darwin"===t?"Finder":"win32"===t?"Explorer":"Files",kind:"file-manager",method:"cli",isSupported:()=>function(e){return"darwin"===e?Xn("open"):"win32"===e||"linux"===e&&(Xn("xdg-open")||Xn("gio"))}(t),open:e=>function(e,t){if("darwin"!==t){if("win32"!==t){if("linux"===t)return Xn("xdg-open")?void Yn("xdg-open",[e]):void Yn("gio",["open",e]);throw new Error("File manager open is not supported on this platform")}Yn("explorer",[e])}else Yn("open",[e])}(e,t)},{id:"open-with",label:"Open With...",kind:"system",method:"cli",isSupported:()=>function(e){return"darwin"===e?Xn("osascript"):"win32"===e?Xn("powershell")||Xn("pwsh"):"linux"===e&&Xn("gio")}(t),open:e=>function(e,t){if("darwin"!==t)if("win32"!==t){if("linux"!==t)throw new Error("Open With is not supported on this platform");Yn("gio",["open","--ask",e])}else Yn(Xn("powershell")?"powershell":"pwsh",["-NoProfile","-Command",`Start-Process -Verb OpenAs -FilePath '${Jn(e)}'`]);else if(null===Yn("osascript",["-e",`set targetPath to POSIX file "${Qn(e)}"`,"-e","set appChoice to choose application","-e","tell appChoice to open targetPath"],{captureOutput:!0}))throw new Error("No application selected")}(e,t)}];return function(e,t,n){const s=n??zn();return e.map(e=>{const n=s[e.id];if(!n)return e;if(!1===n.enabled)return{...e,isSupported:()=>!1};const a={...e,label:n.label??e.label,method:n.method??e.method,urlTemplate:n.urlTemplate??e.urlTemplate};if(n.command){const s=function(e){return e?Array.isArray(e)?e:[e]:[]}(n.appName??e.macAppNames);a.method="cli",a.isSupported=()=>function(e,t,n){return"darwin"===n&&t.length>0?t.some(e=>Vn(e)):b.isAbsolute(e)||e.includes(b.sep)?r(e):Xn(e)}(n.command,s,t),a.open=e=>function(e,t,n){if(!Yn(e,(t&&t.length>0?t:["{path}"]).map(e=>e.split("{path}").join(n))))throw new Error(`Command failed: ${e}`)}(n.command,n.args,e)}return a})}(c,t,e)}function Fn(e){if(!e)return;const t=e.replace(/^~(?=$|[\\/])/,n.homedir());if(r(t)){try{if(!l(t).isDirectory())return}catch{return}return t}}function Bn(e){if(!e)return null;return e.trim()||null}function zn(){try{const e=le.readSettings();if(!e||"object"!=typeof e)return{};const t=e.openersOverrides;return t&&"object"==typeof t?t:{}}catch(e){return pe.warn("[OPENERS] Failed to read opener overrides",e),{}}}function Kn(e,t,s){return"darwin"===t?function(e,t){if(Xn("mdfind")){const t=Yn("mdfind",[`kMDItemCFBundleURLSchemes == '${e}'`],{captureOutput:!0});if(t&&t.trim())return!0}if(Xn("plutil")){const t=[b.join(n.homedir(),"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"),"/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"];for(const n of t){if(!r(n))continue;const t=Yn("plutil",["-extract","LSHandlers","json","-o","-",n],{captureOutput:!0});if(t)try{const n=JSON.parse(t);if(Array.isArray(n)&&n.some(t=>t.LSHandlerURLScheme?.toLowerCase()===e.toLowerCase()))return!0}catch(e){pe.debug("[OPENERS] Failed to parse LaunchServices handlers",e)}}}return!!(t&&t.length>0)&&t.some(e=>Vn(e))}(e,s):"win32"===t?function(e){return Xn("reg")&&(Boolean(Yn("reg",["query",`HKCU\\Software\\Classes\\${e}`]))||Boolean(Yn("reg",["query",`HKCR\\${e}`])))}(e):"linux"===t&&function(e){if(Xn("xdg-settings")){const t=Yn("xdg-settings",["get","default-url-scheme-handler",e],{captureOutput:!0});if(t&&t.trim()&&"null"!==t.trim())return!0}if(Xn("gio")){const t=Yn("gio",["mime",`x-scheme-handler/${e}`],{captureOutput:!0});if(t&&/Default application/.test(t))return!0}return!1}(e)}function Vn(e){return"darwin"===process.platform&&Boolean(Yn("open",["-Ra",e]))}function Xn(e){return"win32"===process.platform?Boolean(Yn("where",[e])):Boolean(Yn("sh",["-c",`command -v ${e}`]))}function Yn(e,t,n){const s=Ve(e,t,{encoding:n?.captureOutput?"utf8":void 0,stdio:n?.captureOutput?"pipe":"ignore",windowsHide:!0});if(0!==s.status){if(n?.captureOutput){const n="string"==typeof s.stderr?s.stderr.trim():"";n&&pe.warn(`[OPENERS] Command failed: ${e} ${t.join(" ")}: ${n}`)}return null}return n?.captureOutput?s.stdout:"ok"}function Jn(e){return e.replace(/'/g,"''")}function Qn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Zn(e,t){if(t){const n=e.startsWith(t)?e.slice(t.length).replace(/^\//,""):I(e);return w(t,"versions",n)}let n=k(e),s=0;for(;s<10;){if(r(w(n,"agent.json"))){const t=e.slice(n.length).replace(/^\//,"");return w(n,"versions",t)}const t=k(n);if(t===n)break;n=t,s++}const a=k(e),i=I(e);return w(a,`.${i}.version`)}function es(e,t){const n=Zn(e,t);if(!r(n))return"0.0.0";try{return c(n,"utf-8").trim()}catch(e){return"0.0.0"}}function ts(e,t,n){try{const s=Zn(e,n),a=k(s);if(!r(a)){const{mkdirSync:e}=o;e(a,{recursive:!0})}p(s,t,"utf-8")}catch(e){}}function ns(e,t){const n=e.split(".").map(Number),s=t.split(".").map(Number);for(let e=0;e<3;e++){const t=n[e]||0,a=s[e]||0;if(t>a)return 1;if(t<a)return-1}return 0}function ss(e,t,n){const s=es(e,n),a=ns(t.metadata.version,s);if(!r(e)){const s=k(e);if(!r(s)){const{mkdirSync:e}=o;e(s,{recursive:!0})}return p(e,t.content,"utf-8"),ts(e,t.metadata.version,n),{updated:!0,reason:"created"}}if(a<=0)return{updated:!1,reason:"up-to-date"};switch(t.metadata.updateStrategy){case"overwrite":return p(e,t.content,"utf-8"),ts(e,t.metadata.version,n),{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"}}}async function as(e){const{agentId:t,gitUrl:n,branch:s,subDir:a}=e,i=w(le.agentrixAgentsHomeDir,t);if(r(i))return{agentDir:i};const o=`${i}.tmp-${Date.now()}`;try{const e=["git","clone","--depth=1"];if(s&&e.push("--branch",s),e.push(n,o),Xe(e.join(" "),{stdio:"pipe"}),a){const e=w(o,a);if(!r(e))throw new Error(`Sub-directory "${a}" not found in cloned repository`);d(e,i),u(o,{recursive:!0,force:!0})}else d(o,i);return is(i),{agentDir:i}}catch(e){throw r(o)&&u(o,{recursive:!0,force:!0}),r(i)&&u(i,{recursive:!0,force:!0}),e}}function is(e){const t=[],n=w(e,"claude","plugins");if(r(n))for(const e of m(n)){const s=w(n,e);l(s).isDirectory()&&r(w(s,"package.json"))&&t.push(s)}const s=w(e,"claude","hooks");r(s)&&r(w(s,"package.json"))&&t.push(s);for(const e of t)Xe("yarn install --frozen-lockfile",{cwd:e,stdio:"pipe"}),Xe("yarn build",{cwd:e,stdio:"pipe"})}function os(e){const t=e.split("\n");for(;t.length>0&&""===t[0].trim();)t.shift();for(;t.length>0&&""===t[t.length-1].trim();)t.pop();const n=t.reduce((e,t)=>{if(""===t.trim())return e;const n=t.match(/^\s*/)[0].length;return Math.min(e,n)},1/0);return t.map(e=>e.slice(n)).join("\n")}const rs=os("\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"),cs=os('\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'),ls=os('\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'),ps=os('\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'),ds=os("\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"),us=os(`\n ${ps}\n\n ${cs}\n\n ${ls}\n`),ms=os('\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 gs(e){const t=["# Available Agents",""];for(const n of e)n.description?t.push(`- **${n.name}** (${n.id}): ${n.description}`):t.push(`- **${n.name}** (${n.id})`);return t.join("\n")}function hs(e,t){const n=t.find(t=>t.id===e);if(!n)return gs(t);const s=t.filter(t=>t.id!==e),a=["# Group Context","",`You are \`${n.name}\`. `,"You are a member of this group chat."];if(n.description&&a.push(`Your role: ${n.description}`),s.length>0){a.push(""),a.push("## Other Agents in This Group"),a.push("");for(const e of s)e.description?a.push(`- **${e.name}**: ${e.description}`):a.push(`- **${e.name}**`)}return a.push(""),a.push(ms),a.join("\n")}function fs(e){const t={};for(const[n,s]of Object.entries(e))"string"==typeof s&&(t[n]=s);return t}function vs(e){if("object"!=typeof e||null===e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text}function xs(e){return{type:"user",message:{role:"user",content:e},parent_tool_use_id:null,session_id:""}}function ys(e){const t=e.message?.content;return"string"==typeof t?t:Array.isArray(t)?t.filter(vs).map(e=>e.text).join("\n").trim():""}function bs(e){const t=e.usage.input_tokens-e.usage.cached_input_tokens,n={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,inference_geo:"",iterations:[],server_tool_use:{web_fetch_requests:0,web_search_requests:0},service_tier:"standard",speed:"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:n,modelUsage:{[e.model]:{inputTokens:t>0?t: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,structured_output:e.structuredOutput}}function ws(e,t){if(!t)return;const n=e?.trim();if(!n)throw new Error("Structured output was requested but the agent returned an empty response");try{return JSON.parse(n)}catch(e){const t=n.length>200?`${n.slice(0,200)}...`:n;throw new Error(`Structured output was requested but the agent returned invalid JSON: ${e instanceof Error?e.message:"unknown error"}; response=${JSON.stringify(t)}`)}}const ks="agentrix",Is="1.0.0";async function*Ss(e){yield e}let Ts;const Es=["Bash","Glob","Grep","ExitPlanMode","Read","Skill","SlashCommand","EnterPlanMode"],As=["Glob","Grep","Read","Skill"],Cs=["Read","Glob","Grep"],$s=["Read","Glob","Grep","TodoWrite"];function _s(e,t,n,s,a,i,o){const c=function(e){const{agentId:t,modeConfig:n,cwd:s,agentConfig:a}=e,{mode:i,groupAgents:o}=n,r=a.customSystemPrompt,c=a.systemPromptMode??"append",l=function(e){const{mode:t,supportChangeTitle:n}=e;switch(t){case"work":return n?rs:void 0;case"companion_shadow":case"companion_chat":case"reply":case"group_chat":return;case"chat":return ds;case"group_work":{const e=[];return n&&e.push(rs),e.join("\n\n")}}}(n);if("group_chat"===i||"group_work"===i){const e=[us];return o&&o.length>0&&e.push(gs(o)),l&&e.push(l),e.join("\n\n")}const p="reply"===i&&o&&o.length>0?hs(t,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?Re(r,s,m):void 0;if("replace"===c&&g){const e=[g];return p&&e.push(p),l&&e.push(l),e.join("\n\n")}const h=[];return p&&h.push(p),l&&h.push(l),g&&h.push(g),{type:"preset",preset:"claude_code",append:h.length>0?h.join("\n\n"):void 0}}({agentId:e,modeConfig:t.modeConfig,cwd:t.cwd,agentConfig:n}),l=function(e){switch(e){case"work":case"companion_shadow":return;case"chat":case"companion_chat":return[...Es];case"reply":return[...As];case"group_chat":return[...Cs];case"group_work":return[...$s]}}(t.modeConfig.mode),p=function(e,t){const n={},s=e=>async(t,n,s)=>await e(t,n,s)??{},a=new Set([...Object.keys(e),...t?Object.keys(t):[]]);for(const i of a){const a=[],o=e[i];o&&a.push(s(o));const r=t?.[i];r&&a.push(s(r)),n[i]=[{hooks:a}]}return n}(t.hooks??{},s),d=function(){if(void 0!==Ts)return Ts??void 0;const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(e){const t=function(e){const t=e.trim();if(t){if(t.includes("/")||t.includes("\\")||t.startsWith(".")){const e=S(t)?t:T(t);return r(e)?e:void 0}return function(e){const t="win32"===process.platform?"where":"which",n=Ve(t,[e],{encoding:"utf-8"});if(0===n.status)return n.stdout.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0)}(t)}}(e);if(t)return Ts=t,t}Ts=null}(),u=i?function(e){const{modeConfig:t,tools:n,allowAskUser:s=!0,visionModel:a,serverName:i=ks,serverVersion:o=Is}=e,{mode:r,supportChangeTitle:c}=t,l=[];switch(r){case"work":c&&l.push(n.changeTaskTitle),s&&l.push(n.askUser),l.push(n.getTaskHistory);break;case"chat":l.push(n.createTask),l.push(n.replyToSubTask),s&&l.push(n.askUser),l.push(n.getTaskHistory),l.push(n.listSubTask);break;case"group_chat":l.push(n.invoke),l.push(n.createSoloTask),l.push(n.createGroupTask),l.push(n.replyToSubTask),l.push(n.getTaskAgents),l.push(n.getTaskHistory);break;case"group_work":l.push(n.invoke),l.push(n.assign),c&&l.push(n.changeTaskTitle),l.push(n.getTaskAgents),l.push(n.getTaskHistory);break;case"reply":l.push(n.getTaskHistory),s&&l.push(n.askUser);break;case"companion_chat":l.push(n.createTask),l.push(n.replyToSubTask),s&&l.push(n.askUser),l.push(n.getTaskHistory),l.push(n.uploadFile),l.push(n.listAgents),l.push(n.scheduleTask);break;case"companion_shadow":l.push(n.getTaskHistory),l.push(n.readConversation),l.push(n.listAgents),l.push(n.scheduleTask)}("companion_chat"===r||"companion_shadow"===r)&&(l.push(n.listTasks),l.push(n.updateAgentInfo),l.push(n.sendReminder)),a&&"companion_shadow"!==r&&"reply"!==r&&l.push(n.analyzeImage);const p=Qe({name:i,version:o,tools:l}),d=l.map(e=>((e,t)=>`mcp__${e}__${t}`)(i,e.name));return{server:p,toolNames:d}}({modeConfig:t.modeConfig,tools:i,allowAskUser:t.allowAskUser,visionModel:t.visionModel}):void 0,m={...u?.server?{agentrix:u.server}:{},...t.mcpServers??{},...a??{}};return{stderr:t.stderr,model:t.model||n.customModel,fallbackModel:n.customFallbackModel,cwd:t.cwd,resume:t.agentSessionId,permissionMode:t.initialPermissionMode??n.customPermissionMode??"bypassPermissions",settingSources:["user","project","local"],systemPrompt:c,tools:l,mcpServers:m,plugins:n.customPlugins,abortController:t.abortController,env:t.env?fs(t.env):void 0,pathToClaudeCodeExecutable:d,maxTurns:n.customMaxTurns??t.maxTurns??o,extraArgs:n.customExtraArgs,canUseTool:t.canUseTool,hooks:p,outputFormat:t.structuredOutputSchema}}class Ps{constructor(e,t,n,s){this.agentId=e,this.agentConfig=t,this.agentHooks=n,this.agentMcpServers=s}getAgentConfiguration(){return this.agentConfig}getHooks(){return this.agentHooks}getMcpServers(){return this.agentMcpServers}async executeHook(e,t,n){await async function(e,t,n,s){if(!e)return;const a=e[t];if(!a)return;const i=s||(e=>console.log(e));try{i(`[${t}] Executing hook...`);const e=new AbortController,s=setTimeout(()=>{e.abort()},6e4);try{await a(n,"",{signal:e.signal}),i(`[${t}] Hook executed successfully`)}finally{clearTimeout(s)}}catch(e){console.warn(`[${t}] Hook failed (non-fatal):`,e)}}(this.agentHooks,e,t,n)}async run(e,t){const n=this.agentConfig,s="string"==typeof e?xs(e):e;let a=null;const i=Ze({prompt:Ss(s),options:_s(this.agentId,t,n,this.agentHooks,this.agentMcpServers,t.agentrixTools)});for await(const e of i)if(console.log("ClaudeRunner.run: received message",JSON.stringify(e)),"result"===e.type){a=e;break}if(!a)throw new Error("ClaudeRunner.run: missing result message");return a}async*runStreamed(e,t){const n=this.agentConfig,s="string"==typeof e?xs(e):e,a=Ze({prompt:Ss(s),options:_s(this.agentId,t,n,this.agentHooks,this.agentMcpServers,t.agentrixTools)});for await(const e of a)if(yield e,"result"===e.type)break}loop(e){const t=e.abortController,n=this.agentConfig,s=_s(this.agentId,e,n,this.agentHooks,this.agentMcpServers,e.agentrixTools);let a=!1;const i=[];let o=null,r=null;const c=()=>{if(!a&&(a=!0,o)){const e=o;o=null,e(null)}},l=async function*(){for(;!a&&!t.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:l(),options:s});r=e;for await(const t of e)yield t}finally{r=null,c()}}();return t.signal.addEventListener("abort",c,{once:!0}),{push:e=>{if(console.log("ClaudeRunner.loop.push:",JSON.stringify(e,null,2)),a)return;const t="string"==typeof e?xs(e):e;if(o){const e=o;return o=null,void e(t)}i.push(t)},events:p,stop:c,setPermissionMode:async e=>{r&&await r.setPermissionMode(e)}}}}function Rs(e,t,n){e&&e(t,"AGENT",n)}function Ms(){return`Companion probe timed out after ${Math.round(45)}s`}function Os(e){return e instanceof Error&&e.message?e.message:String(e)}function Ds(e){return"string"==typeof e.result&&e.result.trim()?e.result:Array.isArray(e.permission_denials)&&e.permission_denials.length>0?String(e.permission_denials[0]):"error_max_turns"===e.subtype?"Companion probe exceeded max turns":"Companion probe failed"}async function Ns(){const e=w(le.agentrixHomeDir,"tmp","companion-probe");g(e,{recursive:!0});const t=new Ps("default",{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}),n=new AbortController;let s=!1;const a=setTimeout(()=>{s=!0,n.abort()},45e3);try{const a=await t.run("hi",{cwd:e,abortController:n,modeConfig:{mode:"chat",supportChangeTitle:!1}});return a.is_error?{success:!1,error:s?Ms():Ds(a)}:{success:!0}}catch(e){return{success:!1,error:s?Ms():Os(e)}}finally{clearTimeout(a)}}function Us(e){return e.split("\\").join("/")}function js(e,t){const n=w(t,"template","versions",`${e}.json`);if(!r(n))return{};try{const e=c(n,"utf-8");return JSON.parse(e)}catch(e){return console.warn(`[Companion] Failed to parse ${n}:`,e),{}}}async function qs(e){const t=le.agentrixAgentsHomeDir,n=w(t,"companion"),s=w(n,"claude");if(!r(w(n,"agent.json"))){const t=await Ns();if(!t.success)throw new Error(`Companion probe failed: ${t.error||"Unknown error"}`);const s=e?.credentials?.token;if(s)try{const e=await async function(e){const t=`${le.serverUrl}/v1/agents/${encodeURIComponent("companion")}/git-url`;try{const n=await fetch(t,{headers:{Authorization:`Bearer ${e}`}});return n.ok?n.json():null}catch(e){return null}}(s);e&&(await as({agentId:"companion",gitUrl:e.gitUrl,branch:e.branch,subDir:e.subDir??"companion"}),console.log("[Companion] Installed from git"))}catch(e){console.warn("[Companion] Git install failed, will retry next boot:",e instanceof Error?e.message:e)}r(w(n,"agent.json"))||(console.log("[Companion] Falling back to public repo..."),await as({agentId:"companion",gitUrl:"https://github.com/xmz-ai/agentrix-agent",branch:"main",subDir:"companion"}))}var a;a=w(s,"memory"),r(a)||g(a,{recursive:!0});const{language:i,templates:o}=function(e,t){const n=function(e){const t=[e,process.env.AGENTRIX_COMPANION_TEMPLATE_LANGUAGE,process.env.LC_ALL,process.env.LC_MESSAGES,process.env.LANG];for(const e of t){if(!e)continue;const t=e.trim().toLowerCase();if(t){if(t.startsWith("zh"))return"zh-Hans";if(t.startsWith("en"))return"en"}}return"en"}(e),s=js("common",t),a=js(n,t),i=[],o={version:"1.0.0",updateStrategy:"create-only"};for(const[e,n]of Object.entries(s)){const s=w(t,e);r(s)&&i.push({relativePath:e,content:c(s,"utf-8"),metadata:n})}const p=function(e){const t={};if(!r(e))return t;const n=s=>{const a=m(s).sort();for(const i of a){const a=w(s,i);if(l(a).isDirectory()){n(a);continue}if("versions.json"===i)continue;const o=Us(E(e,a));t[o]=c(a,"utf-8")}};return n(e),t}(w(t,"template","languages",n));for(const[e,t]of Object.entries(p))i.push({relativePath:e,content:t,metadata:a[e]||o});if(0===i.length)throw new Error(`Companion template files are missing in ${t}`);return{language:n,templates:i}}(e?.preferredLanguage,n),d=[];for(const e of o){const t=ss(w(n,e.relativePath),e,n);if(d.push({path:e.relativePath,updated:t.updated,reason:t.reason}),t.updated){const n="created"===t.reason?"Created":"Updated";console.log(`[Companion] ${n}: ${e.relativePath}`)}}const u=function(e,t){const n=[];for(const s of e){if("notify-user"!==s.metadata.updateStrategy)continue;const e=w(t,s.relativePath);if(!r(e))continue;const a=es(e,t);ns(s.metadata.version,a)>0&&n.push({template:s,targetPath:e,currentVersion:a,newVersion:s.metadata.version})}return n}(o,n);if(u.length>0)try{const e=w(s,"UPGRADES.md"),t=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`}(u);p(e,t,"utf-8");for(const e of u){const t=`${e.targetPath}.upgrade`,n=`# 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`;p(t,n,"utf-8")}console.log(`[Companion] Created UPGRADES.md with ${u.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: ${i}`),{agentDir:n,homeDir:s}}function Ls(e){return!e||"object"!=typeof e||Array.isArray(e)?null:e}function Hs(e){return"string"==typeof e&&e.trim().length>0?e.trim():void 0}function Gs(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Ws(e){const t=Ls(e.project);return t?{id:Gs(t.id),path:Hs(t.path),path_with_namespace:Hs(t.path_with_namespace),default_branch:Hs(t.default_branch),web_url:Hs(t.web_url)}:null}function Fs(e){return Hs(e.event_type)||Hs(e.object_kind)||"unknown"}async function Bs({gitServerId:e,payload:t,config:n,pat:s}){const a=Fs(t),i=function(e,t,n){if("issue"!==Fs(t))return null;const s=Ws(t),a=function(e){const t=Ls(e.object_attributes);return t?{iid:Gs(t.iid),title:Hs(t.title),url:Hs(t.url),action:Hs(t.action),state:Hs(t.state)}:null}(t);if(!s?.path_with_namespace||!a?.iid)return null;const i=n.ref||s.default_branch;if(!i)throw{status:400,message:"Pipeline ref is required; pass ref or ensure GitLab payload includes project.default_branch"};const{owner:o,name:r}=function(e){const t=e.split("/").filter(Boolean);if(t.length<2)return{owner:"",name:e};const n=t[t.length-1];return{owner:t.slice(0,-1).join("/"),name:n}}(s.path_with_namespace),c=function(e,t){switch(e){case"open":case"opened":return"opened";case"reopen":case"reopened":return"reopened";case"close":case"closed":return"closed";case"update":case"updated":case"edit":case"edited":return"edited";default:return"opened"===t?"opened":"closed"===t?"closed":e||"unknown"}}(a.action,a.state),l={AGENTRIX_EVENT_NAME:"issue",AGENTRIX_EVENT_ACTION:c,AGENTRIX_ISSUE_NUMBER:String(a.iid),AGENTRIX_GIT_SERVER_ID:e,AGENTRIX_PROVIDER:"gitlab",AGENTRIX_REPOSITORY_OWNER:o,AGENTRIX_REPOSITORY_NAME:r,AGENTRIX_TRIGGER_SOURCE:"agentrix_daemon_webhook"};a.title&&(l.AGENTRIX_ISSUE_TITLE=a.title);const p=function(e,t){return t.url?t.url:e.web_url&&"number"==typeof t.iid?`${e.web_url}/-/issues/${t.iid}`:void 0}(s,a);p&&(l.AGENTRIX_ISSUE_URL=p);const d={ref:i,variables:l};return s.id?d.projectId=s.id:d.projectPath=s.path_with_namespace,n.triggerToken&&(d.triggerToken=n.triggerToken),void 0!==n.createTriggerIfMissing&&(d.createTriggerIfMissing=n.createTriggerIfMissing),{operationPayload:d,action:c}}(e,t,n);if(!i)return{status:"ignored",eventType:a,reason:"unsupported_event"};if(!n.apiUrl)throw{status:400,message:"GitLab API URL is required"};const o=new rn(n.apiUrl,s,{gitServerId:e});let r;try{r=await o.executeOperation("triggerPipeline",i.operationPayload)}catch(e){const t=function(e){const t=e;return{message:"string"==typeof t?.message?t.message:e instanceof Error?e.message:"Failed to trigger GitLab pipeline",detail:"string"==typeof t?.detail?t.detail:void 0,upstreamStatus:"number"==typeof t?.status?t.status:void 0}}(e);return{status:"failed",eventType:a,action:i.action,reason:"pipeline_trigger_failed",errorMessage:t.message,errorDetail:t.detail,upstreamStatus:t.upstreamStatus}}return{status:"triggered",eventType:a,action:i.action,pipeline:r}}function zs(e,t){const n=[],s=m(e,{withFileTypes:!0});for(const a of s){if(".gitkeep"===a.name)continue;const s=w(e,a.name),i=l(s),o=E(t,s);n.push({name:a.name,path:o,size:i.size,modifiedAt:i.mtimeMs,isDirectory:a.isDirectory()}),a.isDirectory()&&n.push(...zs(s,t))}return n}const Ks=Fe.object({id:Fe.string(),type:Fe.string(),name:Fe.string(),baseUrl:Fe.string(),apiUrl:Fe.string(),oauthServerId:Fe.string().nullable().optional(),ownerId:Fe.string().nullable().optional(),authModeDefault:Fe.string().optional(),executionMode:Fe.string().optional(),syncMode:Fe.string().optional(),networkMode:Fe.string().optional(),githubAppName:Fe.string().nullable().optional(),enabled:Fe.boolean().optional(),createdAt:Fe.string().optional(),updatedAt:Fe.string().optional()}).passthrough();async function Vs(e,t,n){let s;try{return await Promise.race([e,new Promise((e,a)=>{s=setTimeout(()=>a(new Error(n)),t)})])}finally{s&&clearTimeout(s)}}function Xs(e){return Array.isArray(e)?e[0]:e}function Ys(e){return e instanceof Error?e.message:"Unknown error"}async function Js(e,t,n,s,a=15e3){if(!e?.connected)throw new Error("Machine WebSocket is not connected");const i={eventId:j(),method:t,path:n,body:s},o=await Vs(e.sendWithAck("machine-rpc-call",i),a,`Timed out waiting for machine RPC ${t} ${n}`);if(!o.success){const e=o.error?.message||`Machine RPC failed: ${t} ${n}`;throw new Error(e)}return o.data}function Qs(e){const{getChildren:t,stopSession:n,requestShutdown:s,registerSession:a,credentials:i,getSocketClient:o}=e;return new Promise(d=>{const u=le.getDaemonControlHost(),m=le.getDaemonWebhookHost(),h=We({logger:!1});h.removeContentTypeParser("application/json"),h.addContentTypeParser("application/json",{parseAs:"string"},(e,t,n)=>{const s="string"==typeof t?t:t.toString("utf8");if(0!==s.trim().length)try{n(null,JSON.parse(s))}catch(e){const t=e instanceof Error?e:new Error("Invalid JSON body");t.statusCode=400,n(t,void 0)}else n(null,{})}),h.setValidatorCompiler(ze),h.setSerializerCompiler(Ke);const f=h.withTypeProvider(),v=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")};f.post("/session-started",{schema:{body:Fe.object({sessionId:Fe.string(),metadata:Fe.any()}),response:{200:Fe.object({status:Fe.literal("ok")})}}},async e=>{const{sessionId:t,metadata:n}=e.body;return pe.debug(`[CONTROL SERVER] Session started: ${t}`),a(t,n),{status:"ok"}}),f.options("/ping",async(e,t)=>(v(t),t.send())),f.get("/ping",{schema:{response:{200:Fe.object({status:Fe.literal("ok"),machineId:Fe.string(),timestamp:Fe.string(),controlHost:Fe.string(),webhookHost:Fe.string()})}}},async(e,t)=>(v(t),{status:"ok",machineId:i.machineId,timestamp:(new Date).toISOString(),controlHost:u,webhookHost:m})),f.options("/openers",async(e,t)=>(v(t),t.send())),f.get("/openers",{schema:{response:{200:Fe.object({openers:Fe.array(Fe.object({id:Fe.string(),label:Fe.string(),kind:Fe.enum(["system","file-manager","editor","ide"]),method:Fe.enum(["scheme","cli"]),urlTemplate:Fe.string().optional(),supported:Fe.boolean()}))})}}},async(e,t)=>(v(t),{openers:await Hn()})),f.options("/open",async(e,t)=>(v(t),t.send())),f.options("/pick-directory",async(e,t)=>(v(t),t.send())),f.post("/open",{schema:{body:Fe.object({path:Fe.string(),openerId:Fe.string(),userId:Fe.string().optional(),taskId:Fe.string().optional()}),response:{200:Fe.object({success:Fe.boolean(),error:Fe.string().optional()})}}},async(e,t)=>{v(t);const{path:n,openerId:s,userId:a,taskId:i}=e.body;return await async function({openerId:e,targetPath:t,userId:n,taskId:s}){const a=Wn(zn()).find(t=>t.id===e);if(!a)return{success:!1,error:"Unknown openerId"};if("cli"!==a.method||!a.open)return{success:!1,error:"Opener is not executable by CLI"};if(!a.isSupported())return{success:!1,error:"Opener is not supported on this system"};let i;try{i=function(e,t,n){const s=b.resolve(e);if(!b.isAbsolute(s))throw new Error("Path must be absolute");if(!l(s).isDirectory())throw new Error("Path must be a directory");if(t&&n){const e=le.getTaskCwd(t,n);if(e&&!function(e,t){const n=b.relative(t,e);return""===n||!n.startsWith("..")&&!b.isAbsolute(n)}(s,b.resolve(e)))throw new Error("Path is outside the task workspace")}return s}(t,n,s)}catch(e){return{success:!1,error:e instanceof Error?e.message:"Invalid path"}}try{return a.open(i),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Failed to open path";return pe.warn(`[OPENERS] Failed to open path: ${t}`),{success:!1,error:t}}}({openerId:s,targetPath:n,userId:a,taskId:i})}),f.post("/pick-directory",{schema:{body:Fe.object({defaultPath:Fe.string().optional()}),response:{200:Fe.object({path:Fe.string().nullable(),error:Fe.string().optional()})}}},async(e,t)=>{v(t);try{return{path:Gn(e.body.defaultPath)??null}}catch(e){return{path:null,error:e instanceof Error?e.message:"Failed to pick directory"}}}),f.post("/companion/ensure",{schema:{body:Fe.object({preferredLanguage:Fe.enum(["en","zh-Hans"]).nullable().optional()}).optional(),response:{200:Fe.object({agentDir:Fe.string()})}}},async e=>await qs({preferredLanguage:e.body?.preferredLanguage,credentials:i})),f.post("/companion/probe",{schema:{response:{200:Fe.object({success:Fe.boolean(),error:Fe.string().optional()})}}},async()=>await Ns()),f.get("/companion/workspace",{schema:{response:{200:Fe.object({files:Fe.array(Fe.object({name:Fe.string(),path:Fe.string(),size:Fe.number(),modifiedAt:Fe.number(),isDirectory:Fe.boolean()}))})}}},async()=>{const{homeDir:e}=await qs({credentials:i});return r(e)?{files:zs(e,e)}:{files:[]}}),f.get("/companion/file",{schema:{querystring:Fe.object({path:Fe.string()}),response:{200:Fe.object({content:Fe.string()}),404:Fe.object({error:Fe.string()})}}},async(e,t)=>{const{homeDir:n}=await qs({credentials:i}),s=A(w(n,e.query.path));return s.startsWith(n)&&r(s)?{content:c(s,"utf-8")}:t.code(404).send({error:"File not found"})}),f.put("/companion/file",{schema:{body:Fe.object({path:Fe.string(),content:Fe.string()}),response:{200:Fe.object({success:Fe.boolean()}),400:Fe.object({error:Fe.string()})}}},async(e,t)=>{const{homeDir:n}=await qs({credentials:i}),s=A(w(n,e.body.path));return s.startsWith(n)?(g(k(s),{recursive:!0}),p(s,e.body.content,"utf-8"),{success:!0}):t.code(400).send({error:"Invalid path"})}),f.get("/companion/config",{schema:{response:{200:Fe.object({heartbeatIntervalMs:Fe.number(),heartbeatEnabled:Fe.boolean(),lastHeartbeatTimestamp:Fe.string().nullable(),lastHeartbeatDate:Fe.string().nullable(),lastInteractionTimestamp:Fe.string().nullable()})}}},async()=>{const{homeDir:e}=await qs({credentials:i}),t=w(e,"state.json");let n=9e5,s=!1,a=null,o=null,l=null;if(r(t))try{const e=JSON.parse(c(t,"utf-8"));"number"==typeof e.heartbeatIntervalMs&&(n=e.heartbeatIntervalMs),"boolean"==typeof e.heartbeatEnabled&&(s=e.heartbeatEnabled),"string"==typeof e.lastHeartbeatTimestamp&&(a=e.lastHeartbeatTimestamp),"string"==typeof e.lastHeartbeatDate&&(o=e.lastHeartbeatDate),"string"==typeof e.lastInteractionTimestamp&&(l=e.lastInteractionTimestamp)}catch{}return{heartbeatIntervalMs:n,heartbeatEnabled:s,lastHeartbeatTimestamp:a,lastHeartbeatDate:o,lastInteractionTimestamp:l}}),f.put("/companion/config",{schema:{body:Fe.object({heartbeatIntervalMs:Fe.number().optional(),heartbeatEnabled:Fe.boolean().optional()}),response:{200:Fe.object({success:Fe.boolean()})}}},async e=>{const{homeDir:t}=await qs({credentials:i}),n=w(t,"state.json");let s={};if(r(n))try{s=JSON.parse(c(n,"utf-8"))}catch{}const{heartbeatIntervalMs:a,heartbeatEnabled:o}=e.body;return void 0!==a&&(s.heartbeatIntervalMs=a),void 0!==o&&(s.heartbeatEnabled=o),g(k(n),{recursive:!0}),p(n,JSON.stringify(s,null,2),"utf-8"),{success:!0}}),f.post("/agent/install",{schema:{body:Fe.object({agentId:Fe.string(),gitUrl:Fe.string(),branch:Fe.string().optional(),subDir:Fe.string().optional()}),response:{200:Fe.object({agentDir:Fe.string()}),500:Fe.object({error:Fe.string()})}}},async(e,t)=>{try{return await as(e.body)}catch(e){const n=e instanceof Error?e.message:String(e);return t.code(500).send({error:n})}}),f.post("/git-server/register",{schema:{body:Fe.object({name:Fe.string().min(1),baseUrl:Fe.string().url(),apiUrl:Fe.string().url()}),response:{200:Fe.object({gitServer:Fe.object({id:Fe.string(),type:Fe.string(),name:Fe.string(),baseUrl:Fe.string(),apiUrl:Fe.string()}),machineId:Fe.string()}),502:Fe.object({error:Fe.string()})}}},async(e,t)=>{try{const n=await Js(o?.(),"POST","/v1/git-servers/machine-register",{...e.body,machineId:i.machineId});return t.send(n)}catch(n){const s=Ys(n);return pe.warn(`[GIT SERVER] register failed: baseUrl=${e.body.baseUrl}, message=${s}`),t.code(502).send({error:s})}}),f.post("/git-server/complete",{schema:{body:Fe.object({gitServerId:Fe.string().min(1)}),response:{200:Fe.object({success:Fe.boolean(),machineId:Fe.string()}),502:Fe.object({error:Fe.string()})}}},async(e,t)=>{try{const n=await Js(o?.(),"POST",`/v1/git-servers/${encodeURIComponent(e.body.gitServerId)}/machine-complete`,{machineId:i.machineId});return t.send(n)}catch(n){const s=Ys(n);return pe.warn(`[GIT SERVER] complete failed: gitServerId=${e.body.gitServerId}, message=${s}`),t.code(502).send({error:s})}}),f.post("/git-server/list",{schema:{response:{200:Fe.object({gitServers:Fe.array(Ks)}),502:Fe.object({error:Fe.string()})}}},async(e,t)=>{try{const e=await Js(o?.(),"POST","/v1/git-servers/machine-list",{machineId:i.machineId});return t.send({gitServers:Array.isArray(e)?e:[]})}catch(e){const n=Ys(e);return pe.warn(`[GIT SERVER] list failed: message=${n}`),t.code(502).send({error:n})}}),f.post("/git-server/delete",{schema:{body:Fe.object({gitServerId:Fe.string().min(1)}),response:{200:Fe.object({success:Fe.boolean(),machineId:Fe.string()}),502:Fe.object({error:Fe.string()})}}},async(e,t)=>{try{const n=await Js(o?.(),"POST",`/v1/git-servers/${encodeURIComponent(e.body.gitServerId)}/machine-unlink`,{machineId:i.machineId});return t.send({success:!0,machineId:i.machineId,...n&&"object"==typeof n?n:{}})}catch(n){const s=Ys(n);return pe.warn(`[GIT SERVER] delete failed: gitServerId=${e.body.gitServerId}, message=${s}`),t.code(502).send({error:s})}}),f.post("/webhooks/gitlab/:gitServerId",{schema:{params:Fe.object({gitServerId:Fe.string()}),body:Fe.record(Fe.string(),Fe.unknown()),response:{200:Fe.object({status:Fe.enum(["triggered","ignored","failed"]),eventType:Fe.string(),action:Fe.string().optional(),pipeline:Fe.unknown().optional(),reason:Fe.string().optional(),errorMessage:Fe.string().optional(),errorDetail:Fe.string().optional(),upstreamStatus:Fe.number().optional()}),400:Fe.object({error:Fe.string()}),401:Fe.object({error:Fe.string()}),403:Fe.object({error:Fe.string()}),404:Fe.object({error:Fe.string()}),502:Fe.object({error:Fe.string()}),500:Fe.object({error:Fe.string()})}}},async(e,t)=>{const n=ie(),s=Date.now(),a=function(e){const t=e.event_type??e.object_kind;return"string"==typeof t?t:"unknown"}(e.body),i="issue"===a?function(e){const t=Ws(e);return t?.id?String(t.id):t?.path_with_namespace??null}(e.body):null,r=e.ip||"-",c="string"==typeof e.headers["user-agent"]?e.headers["user-agent"]:"-",l=(a,i)=>{const o=Date.now()-s,r=function(e){if(!e||"object"!=typeof e)return"type="+typeof e;const t=e;if("string"==typeof t.error)return`error=${t.error}`;const n=String(t.status??"-"),s=String(t.eventType??"-"),a=String(t.action??"-"),i=String(t.reason??"-"),o=String(t.upstreamStatus??"-"),r=String(t.errorMessage??"-"),c=function(e){if(!e||"object"!=typeof e)return"-";const t=e,n=t.id??t.iid??"-",s=t.status??"-",a=t.ref??"-",i=t.web_url??t.webUrl??"-";return`id=${String(n)}, status=${String(s)}, ref=${String(a)}, webUrl=${String(i)}`}(t.pipeline);return`status=${n}, eventType=${s}, action=${a}, reason=${i}, upstreamStatus=${o}, errorMessage=${r}, pipeline=${c}`}(i);return pe[a>=400?"warn":"info"](`[GITLAB WEBHOOK] response: hookId=${n}, gitServer=${e.params.gitServerId}, statusCode=${a}, elapsedMs=${o}, ${r}`),t.code(a).send(i)};pe.info(`[GITLAB WEBHOOK] request received: hookId=${n}, gitServer=${e.params.gitServerId}, eventType=${a}, projectKey=${i??"-"}, remote=${r}, userAgent=${c}`);const p=await Zt();if(!p)return l(500,{error:"Git server encryption key not available"});const d=tn(e.params.gitServerId,p),u=d?.webhookSecret;if(!u)return l(403,{error:`GitLab webhook bridge is not configured for git server ${e.params.gitServerId}`});if(!function(e,t){if("string"!=typeof e)return!1;const n=Buffer.from(e),s=Buffer.from(t);return n.length===s.length&&oe(n,s)}(e.headers["x-gitlab-token"],u))return l(401,{error:"Invalid GitLab webhook token"});const m=Xs(e.headers["x-gitlab-event-uuid"])??Xs(e.headers["x-gitlab-delivery"]),g=a;(async function(e,t,n,s,a){if(!a?.connected)throw new Error("Machine WebSocket is not connected");const i={eventId:j(),provider:"gitlab",gitServerId:e,deliveryId:n,eventType:s,payload:t},o=await Vs(a.sendWithAck("repository-inbox-webhook",i),5e3,"Timed out waiting for repository inbox webhook ack");if("success"!==o.status)throw new Error(o.message||"API failed to process repository inbox webhook")})(e.params.gitServerId,e.body,m,g,o?.()).catch(t=>{const s=t instanceof Error?t.message:String(t);pe.warn(`[GITLAB WEBHOOK] inbox side-channel failed: hookId=${n}, gitServer=${e.params.gitServerId}, message=${s}`)});const h=sn(e.params.gitServerId,p);if(!h)return l(403,{error:`No PAT configured for git server ${e.params.gitServerId}`});try{const t=en(e.params.gitServerId),s=t?.apiUrl;if(!s)return l(400,{error:`GitLab API URL is not configured for git server ${e.params.gitServerId}`});let o;if(i)if(o=d.projectTriggerTokens?.[i],o)pe.info(`[GITLAB WEBHOOK] pipeline trigger token reused: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}`);else{const t=function(e){const t=Ws(e);return t?.path_with_namespace?t.id?{projectId:t.id}:{projectPath:t.path_with_namespace}:null}(e.body);if(!t)return l(400,{error:"GitLab webhook payload is missing project information"});pe.info(`[GITLAB WEBHOOK] ensuring pipeline trigger token: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}, mode=create_or_reuse`);const a=new rn(s,h,{gitServerId:e.params.gitServerId}),r=await a.executeOperation("ensurePipelineTriggerToken",t);if(!r||"object"!=typeof r||"string"!=typeof r.token)return l(502,{error:"Failed to create GitLab pipeline trigger token"});o=r.token,function(e,t,n){Qt.saveGitLabWebhookBridgeSecrets(e,t,n)}(e.params.gitServerId,{webhookSecret:u,projectTriggerTokens:{...d.projectTriggerTokens??{},[i]:o}},p),pe.info(`[GITLAB WEBHOOK] pipeline trigger token stored: hookId=${n}, gitServer=${e.params.gitServerId}, projectKey=${i}`)}return pe.info(`[GITLAB WEBHOOK] triggering pipeline: hookId=${n}, gitServer=${e.params.gitServerId}, eventType=${a}, projectKey=${i??"-"}`),l(200,await Bs({gitServerId:e.params.gitServerId,payload:e.body,pat:h,config:{apiUrl:s,triggerToken:o}}))}catch(t){const s=t,a="number"==typeof s.status&&s.status>=400&&s.status<600?s.status:500,i="string"==typeof s.message?s.message:t instanceof Error?t.message:"Failed to process GitLab webhook";return pe.warn(`[GITLAB WEBHOOK] failed: hookId=${n}, gitServer=${e.params.gitServerId}, statusCode=${a}, message=${i}`),l(a,{error:i})}}),f.post("/schedule",{schema:{body:Fe.object({task:Fe.string(),type:Fe.enum(["once","recurring"]),due:Fe.string().optional(),cron:Fe.string().optional(),timezone:Fe.string().optional(),timeType:Fe.enum(["utc","local"]).optional()}),response:{200:Fe.object({id:Fe.string(),task:Fe.string(),type:Fe.enum(["once","recurring"]),due:Fe.string().optional(),cron:Fe.string().optional(),timezone:Fe.string().optional(),timeType:Fe.enum(["utc","local"]).optional(),createdAt:Fe.string()}),400:Fe.object({error:Fe.string()}),503:Fe.object({error:Fe.string()})}}},async(t,n)=>{const s=e.companionScheduler;if(!s)return n.code(503).send({error:"Companion scheduler not available"});const{task:a,type:i,due:o,cron:r,timezone:c,timeType:l}=t.body;return"once"!==i||o?"recurring"!==i||r?s.addScheduledTask({task:a,type:i,due:o,cron:r,timezone:c,timeType:l}):n.code(400).send({error:'"cron" is required for recurring tasks'}):n.code(400).send({error:'"due" is required for one-time tasks'})}),f.get("/schedule",{schema:{response:{200:Fe.object({tasks:Fe.array(Fe.object({id:Fe.string(),task:Fe.string(),type:Fe.enum(["once","recurring"]),due:Fe.string().optional(),cron:Fe.string().optional(),timezone:Fe.string().optional(),timeType:Fe.enum(["utc","local"]).optional(),createdAt:Fe.string()}))}),503:Fe.object({error:Fe.string()})}}},async(t,n)=>{const s=e.companionScheduler;return s?{tasks:s.listScheduledTasks()}:n.code(503).send({error:"Companion scheduler not available"})}),f.delete("/schedule/:id",{schema:{params:Fe.object({id:Fe.string()}),response:{200:Fe.object({success:Fe.boolean()}),404:Fe.object({error:Fe.string()}),503:Fe.object({error:Fe.string()})}}},async(t,n)=>{const s=e.companionScheduler;return s?s.deleteScheduledTask(t.params.id)?{success:!0}:n.code(404).send({error:`Task ${t.params.id} not found`}):n.code(503).send({error:"Companion scheduler not available"})}),f.post("/list",{schema:{response:{200:Fe.object({children:Fe.array(Fe.object({startedBy:Fe.string(),taskId:Fe.string(),pid:Fe.number()}))})}}},async()=>({children:t().filter(e=>void 0!==e.taskId).map(e=>({startedBy:e.startedBy,taskId:e.taskId,pid:e.pid}))})),f.post("/stop-session",{schema:{body:Fe.object({sessionId:Fe.string()}),response:{200:Fe.object({success:Fe.boolean()})}}},async e=>{const{sessionId:t}=e.body;return pe.debug(`[CONTROL SERVER] Stop session request: ${t}`),{success:n(t)}}),f.post("/stop",{schema:{response:{200:Fe.object({status:Fe.string()})}}},async()=>(pe.debug("[CONTROL SERVER] Stop daemon request received"),setTimeout(()=>{pe.debug("[CONTROL SERVER] Triggering daemon shutdown"),s()},50),{status:"stopping"})),"127.0.0.1"!==u&&pe.warn(`[CONTROL SERVER] Listening on ${u}; ensure daemon control endpoints are protected by network policy`);const x=e=>new Promise((t,n)=>{h.listen({port:e,host:u},(e,s)=>{e?n(e):t(s)})});(async()=>{let e;try{e=await x(30624)}catch(t){const n=t?.code;if("EADDRINUSE"!==n&&"EACCES"!==n)throw pe.info("[CONTROL SERVER] Failed to start:",t),t;pe.info(`[CONTROL SERVER] Port 30624 unavailable (${n??"error"}), falling back to dynamic port`),e=await x(0)}const t=parseInt(e.split(":").pop());pe.info(`[CONTROL SERVER] Started on port ${t}`),d({port:t,host:u,webhookHost:m,stop:async()=>{await h.close(),pe.info("[CONTROL SERVER] Server stopped")}})})().catch(e=>{throw pe.info("[CONTROL SERVER] Failed to start:",e),e})})}function Zs(e,t={}){const n=de(),s=w(n,"dist","index.mjs"),a=["--no-warnings","--no-deprecation",s,...e];if(!r(s)){const e=`Entrypoint ${s} does not exist`;throw pe.debug(`[SPAWN Agentrix CLI] ${e}`),new Error(e)}return je(process.execPath,a,t)}const ea=[{version:1,fileName:"001_init.sql"}];function ta(e){var t;return function(e,t){const n=new st(e),s=new nt;n.pragma("journal_mode = WAL"),function(e){const t=function(){const e=Te(at(import.meta.url)),t=[Se(e,"migrations"),Se(process.cwd(),"dist","migrations"),Se(process.cwd(),"src","worker","history","migrations")];for(const e of t)if(be(e))return e;throw new Error(`Task history migrations directory not found at ${t[0]}`)}(),n=e.pragma("user_version",{simple:!0}),s=function(e,t){const n=Se(e,t);return ye(n,"utf8")}(t,ea[0].fileName);e.exec(s),n<ea[0].version&&e.pragma(`user_version = ${ea[0].version}`)}(n);const a=n.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=n.prepare("SELECT local_sequence FROM task_message WHERE event_id = ?"),o=n.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=n.prepare("\n UPDATE task_event\n SET sequence = ?\n WHERE event_id = ? AND (sequence IS NULL OR sequence < ?)\n "),c=n.prepare("\n SELECT * FROM task_event\n WHERE sequence > ? AND event_type = 'task-message'\n ORDER BY sequence ASC\n LIMIT ?\n "),l=n.prepare("\n SELECT 1 as has_row\n FROM task_event\n WHERE sequence > ? AND event_type = 'task-message'\n LIMIT 1\n "),p=n.prepare("\n SELECT * FROM task_message\n ORDER BY local_sequence DESC\n LIMIT ?\n "),d=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence ASC\n LIMIT ?\n "),u=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence < ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),m=n.prepare("\n SELECT 1 as has_row\n FROM task_message\n WHERE local_sequence < ?\n LIMIT 1\n "),g=n.prepare("\n SELECT 1 as has_row\n FROM task_message\n WHERE local_sequence > ?\n LIMIT 1\n "),h=n.prepare("\n SELECT * FROM task_message\n WHERE local_sequence > ?\n ORDER BY local_sequence DESC\n LIMIT ?\n "),f=n.prepare("\n SELECT agent_id, session_id, last_sequence\n FROM task_agent_session\n "),v=n.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 "),x=n.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 n=e.eventId??j(),o=(new Date).toISOString(),r=a.run({eventId:n,taskId:t,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,message:JSON.stringify(e.message),createdAt:o}).changes>0,c=i.get(n),l=c?.local_sequence??null;return r&&null!==l&&s.emit("message-saved",{eventId:n}),{eventId:n,localSequence:l,inserted:r}},saveTaskEvent:e=>{const t=e.eventId??j(),n=(new Date).toISOString(),s={...e.eventData,eventId:t};return o.run({eventId:t,taskId:e.taskId,chatId:e.chatId,sequence:e.sequence,eventType:e.eventType,eventData:JSON.stringify(s),createdAt:n}),t},updateTaskEventSequence:(e,t)=>{r.run(t,e,t)},pageTaskEventsAfter:(e,t)=>{const n=c.all(e,t).map(sa),s=n.at(-1)?.sequence??null;return{data:n,hasMore:null!==s&&Boolean(l.get(s))}},getLatestTaskEvent:e=>{if(0===e.length)return null;const t=e.map(()=>"?").join(","),s=n.prepare(`\n SELECT * FROM task_event\n WHERE event_type IN (${t})\n ORDER BY created_at DESC, rowid DESC\n LIMIT 1\n `).get(...e);return s?sa(s):null},pageRecentMessages:e=>{const t=p.all(e).map(na).reverse(),n=t[0]?.localSequence??null;return{data:t,hasMore:!!n&&Boolean(m.get(n))}},pageMessagesAfter:(e,t)=>{const n=d.all(e,t).map(na),s=n.at(-1)?.localSequence??null;return{data:n,hasMore:!!s&&Boolean(g.get(s))}},pageMessagesBefore:(e,t)=>{const n=u.all(e,t).map(na).reverse(),s=n[0]?.localSequence??null;return{data:n,hasMore:!!s&&Boolean(m.get(s))}},pageRecentMessagesAfter:(e,t)=>{const n=h.all(e,t).map(na).reverse(),s=n[0]?.localSequence??null;return{data:n,hasMore:!!s&&Boolean(m.get(s))}},getAgentSessions:()=>{const e=f.all(),t=new Map;for(const n of e)t.set(n.agent_id,n.session_id);return t},getAgentLastSequences:()=>{const e=f.all(),t=new Map;for(const n of e)t.set(n.agent_id,n.last_sequence);return t},upsertAgentSession:(e,n)=>{v.run(e,t,n,(new Date).toISOString())},updateAgentLastSequence:(e,n)=>{x.run(e,t,n,(new Date).toISOString())},on:(e,t)=>{s.on(e,t)},off:(e,t)=>{s.off(e,t)},close:()=>{s.removeAllListeners(),n.close()}}}((t=e.dataDir,Se(t,"data.bin")),e.taskId)}function na(e){const t=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:t,createdAt:e.created_at}}function sa(e){const t=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:t,createdAt:e.created_at}}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"},ia={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","image/svg+xml":".svg","image/x-icon":".ico","application/pdf":".pdf","text/plain":".txt","text/html":".html","text/csv":".csv","application/json":".json","video/mp4":".mp4","audio/mpeg":".mp3"};async function oa(e,t,n=!1){try{const s=await fetch(e);if(!s.ok)throw new Error(`Failed to download file: ${s.status} ${s.statusText}`);if(!s.body)throw new Error("Response body is null");const a=function(e){try{const t=new URL(e),n=C(t.pathname);if(n)return n;const s=t.searchParams.get("filename")||t.searchParams.get("name")||t.searchParams.get("file");if(s){const e=C(s);if(e)return e}return""}catch{return""}}(e),i=s.headers.get("content-type"),o=i?.split(";")[0].trim()||function(e){const t=e.toLowerCase();return aa[t]||"application/octet-stream"}(a),r=a||function(e){return ia[e]||""}(o);let c;if(n)try{const t=new URL(e).pathname,n=I(t);c=n&&C(n)?n:`${ie()}${r||".dat"}`}catch{c=`${ie()}${r||".dat"}`}else c=`${ie()}${r||".dat"}`;const l=w(t,c),p=s.body,d=h(l);return await ot(p,d),{filePath:l,mimeType:o,filename:c}}catch(t){throw new Error(`Failed to download file from ${e}: ${t instanceof Error?t.message:String(t)}`)}}async function ra(e,t){const{attachmentsDir:n,log:s}=t;if(!Array.isArray(e.message.content))return e;const a=await Promise.all(e.message.content.map(async e=>"image"===e.type&&"url"===e.source?.type&&e.source?.url?async function(e,t,n){try{const s=e.source.url;n?.("info","IMAGE",`Downloading image to file (no-vision mode): ${s}`);const{filePath:a,mimeType:i}=await oa(s,t,!0);return n?.("info","IMAGE",`Image saved to: ${a}`),{type:"text",text:`Image file: ${a}\nType: ${i}`}}catch(t){return n?.("error","IMAGE",`Error downloading image to file: ${t}`),e}}(e,n,s):"document"===e.type&&"url"===e.source?.type&&e.source?.url?async function(e,t,n){try{const s=e.source.url;n?.("info","DOCUMENT",`Downloading document from: ${s}`);const{filePath:a,mimeType:i,filename:o}=await oa(s,t,!0);return n?.("info","DOCUMENT",`Document downloaded to: ${a}`),{type:"text",text:`Document: ${a}\nTitle: ${e.title||o}\nType: ${i}`}}catch(t){return n?.("error","DOCUMENT",`Error processing document: ${t}`),e}}(e,n,s):e));return{...e,message:{...e.message,content:a}}}class ca{pidToTrackedSession;taskToStartPromise;sandboxPool;constructor(e){this.pidToTrackedSession=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[t,n]of this.pidToTrackedSession.entries())if(n.taskId===e){if(this.isProcessAlive(t))return n;this.pidToTrackedSession.delete(t)}}getCurrentSessions(){return Array.from(this.pidToTrackedSession.values())}getSessionByPid(e){return this.pidToTrackedSession.get(e)}registerTaskWorker(e,t){const n=t.pid;if(!n)return void pe.warn(`[SESSION] Missing PID for task ${e}`);pe.info(`[SESSION] Registered task ${e}, PID: ${n}`);const s=this.pidToTrackedSession.get(n);if(!(s&&s.taskId===e||s)){const t={startedBy:"cli",taskId:e,pid:n};this.pidToTrackedSession.set(n,t)}}async decryptTaskMessage(e){if(!e.dataEncryptionKey)return;const t=await le.getSecretKey();if(!t)return;const n=U(N(e.dataEncryptionKey),t);if(!n)return void pe.warn("[SESSION] Failed to decrypt data encryption key");if(e.dataEncryptionKey=R(n),"task-message"!==e.event)return;const s=e.eventData;if(!s.encryptedMessage)return;const a=W(s.encryptedMessage,n);a?e.eventData={...s,message:a,encryptedMessage:void 0}:pe.warn("[SESSION] Failed to decrypt task message")}async persistCreateTaskStart(e){const t=le.resolveDataDir(e.userId,e.taskId),n=le.resolveAttachmentsDir(e.userId,e.taskId),s=ta({dataDir:t,taskId:e.taskId});try{const t=e.eventData;if(s.saveTaskEvent({eventType:e.event,eventId:t.eventId,eventData:t,taskId:e.taskId,chatId:e.chatId,sequence:t.sequence??0}),t.message){let e=t.message;F(e)&&(e=await ra(e,{attachmentsDir:n,log:(e,t,n)=>pe["debug"===e?"info":e](`[ATTACH:${t}] ${n}`)})),s.saveMessage({eventId:t.eventId,message:e,senderType:t.senderType,senderId:t.senderId,senderName:t.senderName})}}finally{s.close()}}persistResumeTaskStart(e){const t=ta({dataDir:le.resolveDataDir(e.userId,e.taskId),taskId:e.taskId}),n=e.eventData.sequence;if(null==n)throw new Error(`Missing resume sequence for task ${e.taskId}`);try{const s=e.eventData;t.saveTaskEvent({eventType:e.event,eventId:s.eventId,eventData:s,taskId:e.taskId,chatId:e.chatId,sequence:n}),s.message&&t.saveMessage({eventId:s.eventId,message:s.message,senderType:s.senderType,senderId:s.senderId,senderName:s.senderName})}finally{t.close()}}trackWorkerProcess(e,t){const n={startedBy:"daemon",pid:t.pid,childProcess:t,taskId:e.taskId};this.pidToTrackedSession.set(t.pid,n),t.on("exit",(n,s)=>{this.pidToTrackedSession.delete(t.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId)}),t.on("error",n=>{this.pidToTrackedSession.delete(t.pid),this.sandboxPool&&this.sandboxPool.disposeWorkerSandbox(e.taskId)})}async startWorker(e,t){const n={eventId:j(),status:"success",opCode:e.eventId};await this.decryptTaskMessage(e),le.writeTaskInput(e),"create-task"===t?await this.persistCreateTaskStart(e):this.persistResumeTaskStart(e);const s=this.taskToStartPromise.get(e.taskId);if(s)return pe.info(`[SESSION] Task ${e.taskId} is already starting, skip duplicate ${t}`),s;const a=this.startWorkerInternal(e,t,n).finally(()=>{this.taskToStartPromise.get(e.taskId)===a&&this.taskToStartPromise.delete(e.taskId)});return this.taskToStartPromise.set(e.taskId,a),a}async startWorkerInternal(e,t,n){const s=this.getAliveSessionByTaskId(e.taskId);if(s)return pe.info(`[SESSION] Task ${e.taskId} already has worker PID ${s.pid}, skip duplicate ${t}`),n.message=`Worker already running (PID ${s.pid})`,n;const a=le.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,a))throw new Error("Failed to create sandbox instance");const{projectPath:t}=await import("./logger-GnFTqOqO.mjs").then(function(e){return e.d}),{join:n}=await import("path"),s=["--no-warnings","--no-deprecation",n(t(),"dist","index.mjs"),...i],r=`"${process.execPath}" ${s.map(e=>`"${e}"`).join(" ")}`,c=await this.sandboxPool.wrapWorkerCommand(e.taskId,r);pe.debug(`[SESSION] Sandboxed command for task ${e.taskId}: ${c}`),o=je(c,{shell:!0,cwd:a,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}}),pe.info(`[SESSION] Worker started with sandbox, PID: ${o.pid}`)}catch(t){return pe.error(`[SESSION] Failed to setup sandbox for task ${e.taskId}:`,t),n.status="failed",n.message=`Sandbox setup failed: ${t instanceof Error?t.message:String(t)}`,n}else o=Zs(i,{cwd:a,detached:!0,stdio:["ignore","pipe","pipe"],env:{...process.env}}),pe.info(`[SESSION] Worker started without sandbox, PID: ${o.pid}`);return process.env.DEBUG&&(o.stdout?.on("data",e=>{pe.debug(`[Daemon] worker stdout: ${e.toString()}`)}),o.stderr?.on("data",e=>{pe.debug(`[Daemon] worker stderr: ${e.toString()}`)})),o.pid?(pe.info(`[SESSION] Worker started, PID: ${o.pid}`),this.trackWorkerProcess(e,o),n):(n.status="failed",n.message="Failed to start worker - no PID",n)}stopSession(e){for(const[t,n]of this.pidToTrackedSession.entries())if(n.taskId===e){try{(n.childProcess?n.childProcess:{kill:e=>process.kill(t,e)}).kill("SIGTERM"),pe.info(`[SESSION] Task ${e} stopped`);const s=setTimeout(()=>{const n=this.pidToTrackedSession.get(t);if(n&&n.taskId===e&&this.isProcessAlive(t))try{process.kill(t,"SIGKILL"),pe.warn(`[SESSION] Task ${e} did not exit after SIGTERM, sent SIGKILL to PID ${t}`)}catch(n){pe.warn(`[SESSION] Failed to force kill task ${e} (PID ${t}):`,n)}},3e3);s.unref?.()}catch(n){pe.warn(`[SESSION] Failed to stop task ${e}:`,n),this.isProcessAlive(t)||this.pidToTrackedSession.delete(t)}return!0}return pe.warn(`[SESSION] Task ${e} not found`),!1}pruneStaleSessions(){for(const[e,t]of this.pidToTrackedSession.entries())try{process.kill(e,0)}catch(t){this.pidToTrackedSession.delete(e)}}shutdown(){pe.info("[SESSION] Shutting down all sessions");for(const[e,t]of this.pidToTrackedSession.entries())try{"daemon"===t.startedBy&&t.childProcess?t.childProcess.kill("SIGTERM"):process.kill(e,"SIGTERM")}catch(t){pe.warn(`[SESSION] Failed to stop PID ${e}:`,t)}this.pidToTrackedSession.clear()}async startHivePublishWorker(e){const t={eventId:j(),status:"success",opCode:e.eventId};le.writeTaskInput(e);try{const n=Zs(["worker","--type","hive-publish","--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&&(n.stdout?.on("data",e=>{pe.debug(`[HivePublish] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{pe.debug(`[HivePublish] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start hive-publish worker - no PID",t;pe.info(`[SESSION] Hive publish worker started, PID: ${n.pid}`);const s={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(s,n),t}catch(e){return t.status="failed",t.message=`Failed to start hive-publish worker: ${e instanceof Error?e.message:String(e)}`,t}}async startHiveInstallWorker(e){const t={eventId:j(),status:"success",opCode:e.eventId};le.writeTaskInput(e);try{const n=Zs(["worker","--type","hive-install","--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&&(n.stdout?.on("data",e=>{pe.debug(`[HiveInstall] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{pe.debug(`[HiveInstall] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start hive-install worker - no PID",t;pe.info(`[SESSION] Hive install worker started, PID: ${n.pid}`);const s={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(s,n),t}catch(e){return t.status="failed",t.message=`Failed to start hive-install worker: ${e instanceof Error?e.message:String(e)}`,t}}async startDeploymentWorker(e){const t={eventId:j(),status:"success",opCode:e.eventId};le.writeTaskInput(e);try{const n=Zs(["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&&(n.stdout?.on("data",e=>{pe.debug(`[Deployment] worker stdout: ${e.toString()}`)}),n.stderr?.on("data",e=>{pe.debug(`[Deployment] worker stderr: ${e.toString()}`)})),!n.pid)return t.status="failed",t.message="Failed to start deployment worker - no PID",t;pe.info(`[SESSION] Deployment worker started, PID: ${n.pid}`);const s={taskId:e.taskId,userId:e.userId};return this.trackWorkerProcess(s,n),t}catch(e){return t.status="failed",t.message=`Failed to start deployment worker: ${e instanceof Error?e.message:String(e)}`,t}}}class la{networkManager=null;workerSandboxes=new Map;settings=null;platform;constructor(){this.platform=Ge()}async initialize(e){if(this.settings=e,!e.enabled)return pe.info("[SANDBOX] Sandbox disabled via settings"),!1;if(!rt(this.platform))return pe.warn("[SANDBOX] Platform not supported, sandbox disabled"),!1;try{const t={allowedDomains:[new URL(le.serverUrl).hostname,...e.network.allowedDomains],deniedDomains:e.network.deniedDomains,allowLocalBinding:!1};return this.networkManager=new ct,await this.networkManager.initialize(t),pe.info("[SANDBOX] Sandbox pool initialized successfully"),!0}catch(e){throw pe.error("[SANDBOX] Failed to initialize:",e),e}}async createWorkerSandbox(e,t,n){if(!this.networkManager||!this.settings?.enabled)return null;try{const s=le.resolveUserWorkSpaceDir(t),a=le.getStatePaths().logsDir,i=this.settings.filesystem||{},o=this.settings.env||{},r={...i,allowWrite:[...i.allowWrite||[],s,n,a]};if("linux"===this.platform&&i.allowRead){const e=Ie.dirname(process.execPath);r.allowRead=[...i.allowRead,e]}const c={filesystem:r,env:o},l=new lt(this.networkManager,c);return this.workerSandboxes.set(e,l),pe.info(`[SANDBOX] Created sandbox for task ${e}`),l}catch(t){return pe.error(`[SANDBOX] Failed to create sandbox for task ${e}:`,t),null}}async wrapWorkerCommand(e,t){const n=this.workerSandboxes.get(e);if(!n)throw new Error(`No sandbox found for task ${e}`);const s=await n.wrapWithSandbox(t);return pe.debug(`[SANDBOX] Wrapped command for task ${e}`),s}disposeWorkerSandbox(e){const t=this.workerSandboxes.get(e);t&&(t.dispose(),this.workerSandboxes.delete(e),pe.debug(`[SANDBOX] Disposed sandbox for task ${e}`))}async shutdown(){pe.info("[SANDBOX] Shutting down sandbox pool");for(const[e,t]of this.workerSandboxes.entries())t.dispose(),pe.debug(`[SANDBOX] Disposed sandbox for task ${e}`);this.workerSandboxes.clear(),this.networkManager&&(await this.networkManager.shutdown(),this.networkManager=null,pe.info("[SANDBOX] Network manager shutdown complete"))}isEnabled(){return!0===this.settings?.enabled}}class pa{constructor(e,t){this.client=e,this.machineId=t;const n=le.agentrixAgentsHomeDir,s=w(n,"companion","claude");this.stateFilePath=w(s,"state.json")}timer=null;initialDelay=null;intervalMs=9e5;enabled=!1;heartbeatTaskId=null;companionState=null;stateFilePath;cronJobs=new Map;start(){this.loadState(),this.companionState?(pe.info(`[COMPANION SCHEDULER] Ready: agent=${this.companionState.agentId}, chatId=${this.companionState.chatId}`),this.restoreScheduledTasks()):pe.warn("[COMPANION SCHEDULER] No state.json found (companion not registered yet), will keep checking"),pe.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);for(const[e,t]of this.cronJobs)t.stop(),pe.debug(`[COMPANION SCHEDULER] Stopped cron job: ${e}`);this.cronJobs.clear(),pe.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),pe.info("[COMPANION SCHEDULER] Cleared heartbeat task ID")}recordInteraction(e){if(!this.companionState?.chatId||e!==this.companionState.chatId)return;const t=(new Date).toISOString();this.saveStateField("lastInteractionTimestamp",t),pe.debug(`[COMPANION SCHEDULER] Recorded interaction at ${t}`)}loadState(){try{if(r(this.stateFilePath)){this.companionState=JSON.parse(c(this.stateFilePath,"utf-8"));const e=this.companionState?.heartbeatIntervalMs??9e5;e!==this.intervalMs&&(pe.info(`[COMPANION SCHEDULER] Interval changed: ${this.intervalMs}ms -> ${e}ms`),this.intervalMs=e),this.enabled=this.companionState?.heartbeatEnabled??!1,this.heartbeatTaskId=this.companionState?.heartbeatTaskId??null,pe.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){pe.warn("[COMPANION SCHEDULER] Failed to load state.json",e)}}saveStateField(e,t){try{let n={};r(this.stateFilePath)&&(n=JSON.parse(c(this.stateFilePath,"utf-8"))),void 0===t?delete n[e]:n[e]=t;const s=k(this.stateFilePath);r(s)||g(s,{recursive:!0}),p(this.stateFilePath,JSON.stringify(n,null,2),"utf-8"),pe.debug(`[COMPANION SCHEDULER] Saved state field: ${e}=${t??"removed"}`)}catch(t){pe.warn(`[COMPANION SCHEDULER] Failed to save state field: ${e}`,t)}}getTodayDateString(){const e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}addScheduledTask(e){const t={id:ie(),...e,createdAt:(new Date).toISOString()};this.loadState();const n=this.companionState?.scheduledTasks??[];return n.push(t),this.saveStateField("scheduledTasks",n),this.startCronJob(t),pe.info(`[COMPANION SCHEDULER] Added scheduled task: id=${t.id}, type=${t.type}, task="${t.task}"`),t}listScheduledTasks(){return this.loadState(),this.companionState?.scheduledTasks??[]}deleteScheduledTask(e){this.loadState();const t=this.companionState?.scheduledTasks??[],n=t.findIndex(t=>t.id===e);if(-1===n)return!1;t.splice(n,1),this.saveStateField("scheduledTasks",t);const s=this.cronJobs.get(e);return s&&(s.stop(),this.cronJobs.delete(e)),pe.info(`[COMPANION SCHEDULER] Deleted scheduled task: id=${e}`),!0}startCronJob(e){try{const t={},n="utc"===e.timeType;let s;if(e.due){if(n){const n=new Date(e.due);s=`${n.getUTCMinutes()} ${n.getUTCHours()} ${n.getUTCDate()} ${n.getUTCMonth()+1} *`,t.timezone="Etc/UTC"}else{const n=e.due.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);if(!n)return void pe.warn(`[COMPANION SCHEDULER] Cannot parse due date: ${e.due}, skipping: ${e.id}`);s=`${parseInt(n[5])} ${parseInt(n[4])} ${parseInt(n[3])} ${parseInt(n[2])} *`,e.timezone&&(t.timezone=e.timezone)}"once"===e.type&&(t.maxRuns=1)}else{if(!e.cron)return void pe.warn(`[COMPANION SCHEDULER] Invalid task entry, skipping: ${e.id}`);s=e.cron,n?t.timezone="Etc/UTC":e.timezone&&(t.timezone=e.timezone)}const a=new pt(s,t,()=>{this.onScheduledTaskFired(e)});this.cronJobs.set(e.id,a),pe.debug(`[COMPANION SCHEDULER] Started cron job: id=${e.id}, pattern="${s}"`)}catch(t){pe.warn(`[COMPANION SCHEDULER] Failed to start cron job for task ${e.id}`,t)}}onScheduledTaskFired(e){pe.info(`[COMPANION SCHEDULER] Scheduled task fired: id=${e.id}, task="${e.task}"`),this.loadState();const t=this.companionState;t?.chatId&&(this.client.send("task-message",{eventId:j(),taskId:t.chatId,chatId:t.chatId,from:"machine",message:{type:"companion_reminder",content:`Scheduled task due: ${e.task}`,timestamp:(new Date).toISOString()},senderType:"system",senderId:"system",senderName:"system"}),"once"===e.type&&this.deleteScheduledTask(e.id))}restoreScheduledTasks(){const e=this.companionState?.scheduledTasks??[];if(0===e.length)return;let t=0;for(const n of e)"once"===n.type&&n.due&&new Date(n.due).getTime()<Date.now()?pe.debug(`[COMPANION SCHEDULER] Skipping expired one-time task: ${n.id}`):(this.startCronJob(n),t++);pe.info(`[COMPANION SCHEDULER] Restored ${t}/${e.length} scheduled tasks`)}tick(){if(this.loadState(),!this.companionState)return void pe.debug("[COMPANION SCHEDULER] Still no state.json, skipping heartbeat");if(!this.enabled)return void pe.debug("[COMPANION SCHEDULER] Heartbeat disabled, skipping");const e=this.companionState,t=[];e.lastInteractionTimestamp&&(!e.lastHeartbeatTimestamp||new Date(e.lastInteractionTimestamp).getTime()>new Date(e.lastHeartbeatTimestamp).getTime())&&t.push("new_interaction");const n=this.getTodayDateString();if(e.lastHeartbeatDate!==n&&t.push("first_today"),0===t.length)return void pe.debug("[COMPANION SCHEDULER] No trigger conditions met, skipping heartbeat");pe.info(`[COMPANION SCHEDULER] Heartbeat triggered: ${t.join(", ")}`);const s=new Date;this.saveStateField("lastHeartbeatTimestamp",s.toISOString()),this.saveStateField("lastHeartbeatDate",n);const a=s.toLocaleString();this.heartbeatTaskId?(pe.debug(`[COMPANION SCHEDULER] Sending heartbeat to existing task ${this.heartbeatTaskId}`),this.client.send("task-message",{eventId:j(),taskId:this.heartbeatTaskId,chatId:e.chatId,from:"machine",message:{type:"companion_heartbeat",timestamp:s.toISOString(),triggerTime:a,triggerReasons:t},senderType:"system",senderId:"system",senderName:"system"})):(pe.debug("[COMPANION SCHEDULER] Requesting new heartbeat task"),this.client.send("request-companion-heartbeat",{eventId:j(),machineId:e.machineId,agentId:e.agentId,chatId:e.chatId,userId:e.userId,timestamp:s.toISOString(),triggerTime:a,triggerReasons:t}))}}class da{constructor(e,t){this.client=e,this.machineId=t;const n=le.agentrixAgentsHomeDir,s=w(n,"companion"),a=w(s,"claude");this.bootstrapPath=w(a,"BOOTSTRAP.md"),this.countPath=w(s,"BOOTSTRAP.count"),this.stateFilePath=w(a,"state.json")}timer=null;intervalMs=18e4;maxAttempts=10;bootstrapPath;countPath;stateFilePath;start(){r(this.bootstrapPath)?this.readCount()>=this.maxAttempts?pe.warn(`[COMPANION BOOTSTRAP] Already reached max attempts (${this.maxAttempts}), not starting watcher`):(pe.info("[COMPANION BOOTSTRAP] BOOTSTRAP.md exists, starting watcher"),this.scheduleNext()):pe.debug("[COMPANION BOOTSTRAP] BOOTSTRAP.md not found, companion already initialized")}stop(){this.timer&&(clearTimeout(this.timer),this.timer=null)}scheduleNext(){this.timer=setTimeout(()=>this.tick(),this.intervalMs)}tick(){if(!r(this.bootstrapPath))return void pe.info("[COMPANION BOOTSTRAP] BOOTSTRAP.md removed, companion init complete");const e=this.readCount();if(e>=this.maxAttempts)return void pe.warn(`[COMPANION BOOTSTRAP] Max attempts (${this.maxAttempts}) reached, giving up`);const t=this.loadState();if(!t)return pe.warn("[COMPANION BOOTSTRAP] No state.json available, will retry next interval"),void this.scheduleNext();this.writeCount(e+1),pe.info(`[COMPANION BOOTSTRAP] Sending init request (attempt ${e+1}/${this.maxAttempts})`),this.client.send("request-companion-init",{eventId:j(),machineId:t.machineId,agentId:t.agentId,chatId:t.chatId,userId:t.userId}),this.scheduleNext()}readCount(){try{if(r(this.countPath)){const e=parseInt(c(this.countPath,"utf-8").trim(),10);return isNaN(e)?0:e}}catch{}return 0}writeCount(e){try{p(this.countPath,String(e),"utf-8")}catch(e){pe.warn("[COMPANION BOOTSTRAP] Failed to write BOOTSTRAP.count:",e)}}loadState(){try{if(r(this.stateFilePath)){const e=JSON.parse(c(this.stateFilePath,"utf-8"));if(e?.agentId&&e?.machineId&&e?.userId&&e?.chatId)return e}}catch{}return null}}async function ua(){Object.assign(pe,me({type:"daemon"}));const{requestShutdown:e,shutdownPromise:t}=function(){const{processType:e,onShutdownRequest:t}={processType:"daemon"},n=`[${e.toUpperCase()}]`;let s;const a=new Promise(e=>{s=(s,a)=>{pe.info(`${n} Requesting shutdown (source: ${s}, errorMessage: ${a})`),t&&t(s,a),setTimeout(()=>process.exit(1),1e3),e({source:s,errorMessage:a})}}),i=e=>{process.on(e,()=>{s("os-signal")})};return i("SIGINT"),i("SIGTERM"),process.on("uncaughtException",e=>{pe.info(`${n} FATAL: Uncaught exception`,e),pe.info(`${n} Stack trace: ${e.stack}`),s("exception",e.message)}),process.on("unhandledRejection",e=>{pe.info(`${n} FATAL: Unhandled promise rejection`,e);const t=e instanceof Error?e:new Error(`Unhandled promise rejection: ${e}`);pe.info(`${n} Stack trace: ${t.stack}`),s("exception",t.message)}),process.on("exit",e=>{pe.info(`${n} Process exiting with code: ${e}`)}),{requestShutdown:s,shutdownPromise:a}}();console.log("[DAEMON RUN] Starting daemon process..."),pe.debug("[DAEMON RUN] Environment",jn()),await Rt()&&(console.log("Daemon already running..."),process.exit(0));let n=await le.acquireDaemonLock(5,200);for(;!n;)await Ot(),n=await le.acquireDaemonLock(5,200),n||(pe.debug("[DAEMON RUN] cannot acquire daemon lock..."),process.exit(1));try{(function(){if(le.disableCaffeinate)return pe.debug("[caffeinate] Caffeinate disabled via AGENTRIX_DISABLE_CAFFEINATE environment variable"),!1;if("darwin"!==process.platform)return pe.debug("[caffeinate] Not on macOS, skipping caffeinate"),!1;if($n&&!$n.killed)return pe.debug("[caffeinate] Caffeinate already running"),!0;try{return $n=je("caffeinate",["-im"],{stdio:"ignore",detached:!1}),$n.on("error",e=>{pe.debug("[caffeinate] Error starting caffeinate:",e),$n=null}),$n.on("exit",(e,t)=>{pe.debug(`[caffeinate] Process exited with code ${e}, signal ${t}`),$n=null}),pe.info(`[caffeinate] Started with PID ${$n.pid}`),function(){if(Rn)return;Rn=!0;const e=()=>{Pn()};process.on("exit",e),process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGUSR1",e),process.on("SIGUSR2",e),process.on("uncaughtException",t=>{pe.debug("[caffeinate] Uncaught exception, cleaning up:",t),e()}),process.on("unhandledRejection",(t,n)=>{pe.debug("[caffeinate] Unhandled rejection, cleaning up:",t),e()})}(),!0}catch(e){return pe.info("[caffeinate] Failed to start caffeinate:",e),!1}})()&&pe.debug("[DAEMON RUN] Sleep prevention enabled");const s=await jt();pe.debug("[DAEMON RUN] Auth and machine setup complete");const a=new la;await a.initialize(le.getSandboxSettings());const i=new ca(a);let o,r;const{port:c,host:l,webhookHost:p,stop:d}=await Qs({getChildren:()=>i.getCurrentSessions(),stopSession:e=>i.stopSession(e),requestShutdown:()=>e("agentrix-cli"),registerSession:(e,t)=>i.registerTaskWorker(e,t),getSocketClient:()=>o?.client,credentials:s,get companionScheduler(){return r}});try{await Hn(),pe.debug("[DAEMON RUN] Openers detected")}catch(e){pe.warn("[DAEMON RUN] Failed to detect openers",e)}const u={pid:process.pid,port:c,host:l,webhookHost:p,startTime:(new Date).toLocaleString(),cliVersion:ue.version,logPath:ge({type:"daemon"})};le.writeDaemonState(u),pe.debug("[DAEMON RUN] Daemon state written");const m=new Cn({machineId:s.machineId,serverUrl:le.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:B(s.token,s.machineId),keepAliveConfig:{intervalMs:2e4,event:"machine-alive",payloadGenerator:()=>({eventId:j(),machineId:s.machineId,timestamp:Date.now().toString(),controlPort:c})},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...t)=>pe.debug(`[DAEMON SOCKET] ${e}`,...t)},i,{requestShutdown:e});await m.connect(),o=m,pe.info("[DAEMON RUN] Machine client connected to server");const g=new pa(m.client,s.machineId);r=g,g.start(),m.setCompanionInteractionCallback(e=>{g.recordInteraction(e)});const h=new da(m.client,s.machineId);h.start(),m.client.onEvent("companion-heartbeat-response",e=>{e?.taskId&&g.setHeartbeatTaskId(e.taskId)});const f=async(e,t)=>{g.stop(),h.stop(),await m.disconnect(),await d(),await a.shutdown(),await Mt(),await Pn(),await le.releaseDaemonLock(n),pe.info("[DAEMON RUN] Cleanup completed, exiting process"),process.exit(0)};pe.info("[DAEMON RUN] Daemon started successfully, waiting for shutdown request");const v=await t;await f(v.source,v.errorMessage)}catch(e){(function(e){return e instanceof Error&&e.message.includes("Machine binding revoked")})(e)&&(console.error("Machine binding is no longer valid."),console.error("Run `agentrix logout` and bind this machine again.")),pe.info("[DAEMON RUN][FATAL] Failed somewhere unexpectedly - exiting with code 1",e),process.exit(1)}}const ma="\n\n[Tool result truncated to 1024 bytes]";function ga(e,t=1024){if(Buffer.byteLength(e,"utf8")<=t)return e;const n=Buffer.byteLength(ma,"utf8");return n>t?fa(ma,t):`${fa(e,t-n)}${ma}`}function ha(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function fa(e,t){let n="",s=0;for(const a of e){const e=Buffer.byteLength(a,"utf8");if(s+e>t)break;n+=a,s+=e}return n}const va={senderType:"system",senderId:"system",senderName:"system"};class xa{client;context;historyDb;getPermissionMode;outbox=new Map;usageOutbox=new Map;hasConnectedOnce=!1;constructor(e,t){const{taskId:n,userId:s,machineId:a,cwd:i,chatId:o,...r}=e,c=i.endsWith("/")?i:`${i}/`;this.client=new Ht(r),this.context={taskId:n,chatId:o,userId:s,machineId:a,cwd:c,stopTask:t.stopTask,shouldPersistTaskMessage:t.shouldPersistTaskMessage,onTaskMessage:t.onTaskMessage,onTaskInfoUpdate:t.onTaskInfoUpdate,onWorkerStatusRequest:t.onWorkerStatusRequest,onSubTaskResultUpdated:t.onSubTaskResultUpdated,onSubTaskAskUser:t.onSubTaskAskUser,onGitPush:t.onGitPush,dataEncryptionKey:e.dataEncryptionKey,attachmentsDir:t.attachmentsDir,noVision:t.noVision,logger:t.logger},this.historyDb=t.historyDb,this.getPermissionMode=t.getPermissionMode,this.initHandlers()}getPermissionModeSnapshot(){return this.getPermissionMode?.()??null}connect(){return new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("Worker connection timeout after 10 seconds"))},1e4);this.client.onLifecycle("connect",()=>{clearTimeout(n),e()}),this.client.onLifecycle("connect_error",e=>{clearTimeout(n),t(e)}),this.client.connect()})}async disconnect(){this.client.connected&&await this.client.flush(5e3).catch(()=>{}),this.client.disconnect()}sendTaskMessage(e,t,n){const s=j();return this.historyDb.saveMessage({eventId:s,message:t,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}),this.sendTaskEvent(e,t,n),s}sendWorkerInitializing(e){const t={eventId:j(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),cwd:this.context.cwd,...void 0!==e?.deployingAgent&&{deployingAgent:e.deployingAgent},...void 0!==e?.upgradingAgent&&{upgradingAgent:e.upgradingAgent}};this.client.send("worker-initializing",t)}sendWorkerInitialized(){const e={eventId:j(),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 t=this.getPermissionModeSnapshot(),n={eventId:j(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),...void 0!==e&&{duration:e},...null!==t&&{permissionMode:t}};this.client.send("worker-ready",n)}sendWorkRunning(e){const t=this.getPermissionModeSnapshot(),n={eventId:j(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),activeAgents:e,...null!==t&&{permissionMode:t}};this.client.send("worker-running",n)}sendPermissionMode(e){const t={eventId:j(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),permissionMode:e};this.client.send("worker-permission-mode",t)}sendWorkerExit(e){const t={eventId:j(),taskId:this.context.taskId,machineId:this.context.machineId,timestamp:(new Date).toISOString(),reason:e};this.client.send("worker-exit",t)}async sendErrorMessageAndExit(e){this.sendTerminalErrorResult(e),await this.client.flush(2e3),this.sendWorkerExit("error"),await this.disconnect()}sendTerminalErrorResult(e,t){this.sendSystemErrorMessage(e,t),this.sendTaskEvent(va,function(e){return{type:"result",subtype:"error_during_execution",duration_ms:0,duration_api_ms:0,is_error:!0,num_turns:0,stop_reason:null,total_cost_usd:0,usage:{input_tokens:0,output_tokens:0,cache_creation:{ephemeral_1h_input_tokens:0,ephemeral_5m_input_tokens:0},cache_creation_input_tokens:0,cache_read_input_tokens:0,inference_geo:"",iterations:[],server_tool_use:{web_fetch_requests:0,web_search_requests:0},service_tier:"standard",speed:"standard"},modelUsage:{},permission_denials:[],errors:[e],uuid:crypto.randomUUID(),session_id:""}}(e),{groupId:t?.groupId})}sendSystemErrorMessage(e,t){const n={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(va,n,{groupId:t?.groupId})}sendAssistantMessage(e,t){const n={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:e}]}};this.sendTaskEvent(va,n,{groupId:t?.groupId})}sendAskUser(e,t,n){return this.sendTaskMessage(e,{type:"ask_user",questions:t},{groupId:n?.groupId})}sendAskUserResponse(e,t){return this.sendTaskMessage(va,t,{opCode:e})}sendTaskEvent(e,t,n){const s=function(e,t=1024){const n=e,s=n?.message?.content;if(!Array.isArray(s))return e;let a=!1;const i=s.map(e=>{if("tool_result"!==e?.type||!("content"in e))return e;const n=function(e,t=1024){if("string"==typeof e)return ga(e,t);const n=ha(e);return Buffer.byteLength(n,"utf8")<=t?e:Array.isArray(e)?ga(e.map(e=>{return"object"==typeof(t=e)&&null!==t&&"text"in t&&"string"==typeof t.text?e.text:ha(e);var t}).join("\n"),t):ga(n,t)}(e.content,t);return n===e.content?e:(a=!0,{...e,content:n})});return a?{...n,message:{...n.message,content:i}}:e}(t),{eventId:a,opCode:i,artifacts:o,navigateToTaskId:r}=n||{},c=a??j(),l={eventId:c,taskId:this.context.taskId,chatId:this.context.chatId,from:"worker",messageType:s.type,message:s,encryptedMessage:void 0,opCode:i,groupId:n?.groupId,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,artifacts:o,navigateToTaskId:r};this.historyDb.saveTaskEvent({eventType:"task-message",eventId:c,eventData:l,taskId:this.context.taskId,chatId:this.context.chatId,sequence:"number"==typeof l.sequence?l.sequence:null});const p=this.buildTaskUsageReport(s,c);if(this.context.dataEncryptionKey){const e=z(s,this.context.dataEncryptionKey);l.message=void 0,l.encryptedMessage=e}return this.outbox.set(c,l),p&&(this.usageOutbox.set(c,p),this.client.send("task-usage-report",p)),this.client.send("task-message",l),c}buildTaskUsageReport(e,t){if("result"!==e.type)return null;const n=e.modelUsage;if(!n||"object"!=typeof n)return null;const s={};for(const[e,t]of Object.entries(n)){if(!e||!t||"object"!=typeof t)continue;const n=t,a={inputTokens:this.normalizeUsageCount(n.inputTokens),outputTokens:this.normalizeUsageCount(n.outputTokens),cacheReadInputTokens:this.normalizeUsageCount(n.cacheReadInputTokens),cacheCreationInputTokens:this.normalizeUsageCount(n.cacheCreationInputTokens),webSearchRequests:this.normalizeUsageCount(n.webSearchRequests)};Object.values(a).some(e=>e>0)&&(s[e]=a)}return 0===Object.keys(s).length?null:{eventId:j(),taskId:this.context.taskId,resultEventId:t,modelUsage:s}}normalizeUsageCount(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.trunc(e)}sendUpdateTaskAgentSessionId(e){const t={eventId:j(),taskId:this.context.taskId,agentSessionId:e,cwd:this.context.cwd};this.client.send("update-task-agent-session-id",t)}sendTaskSlashCommandsUpdate(e,t){const n={eventId:j(),taskId:this.context.taskId,commands:e,version:t,updatedAt:(new Date).toISOString()};this.client.send("task-slash-commands-update",n)}sendChangeTaskTitle(e){const t={eventId:j(),taskId:this.context.taskId,title:e};this.client.send("change-task-title",t),pe.info(`[AGENT] Title changed to: ${e}`)}sendUpdateAgentInfo(e,t){const n={eventId:j(),taskId:this.context.taskId,agentId:e,...t};this.client.send("update-agent-info",n),pe.info(`[AGENT] Agent info updated: ${JSON.stringify(t)}`)}sendResetTaskSession(){const e={eventId:j(),taskId:this.context.taskId};this.client.send("reset-task-session",e),pe.info(`[AGENT] Session reset requested for task ${this.context.taskId}`)}async sendMergeRequest(e,t){const n={eventId:j(),taskId:this.context.taskId,summary:e,description:t};pe.info(`[MERGE] Sending merge-request event for task ${this.context.taskId}`);const s=await this.client.sendWithAck("merge-request",n);if(!s.success)throw new Error(`Failed to create pull request: ${s.error||"Unknown error"}`);return pe.info(`[MERGE] Pull request created: #${s.data.pullRequestNumber}`),{pullRequestNumber:s.data.pullRequestNumber,pullRequestUrl:s.data.pullRequestUrl}}async sendMergePr(){const e={eventId:j(),taskId:this.context.taskId,mergeMethod:"squash"};return pe.info(`[MERGE-PR] Sending merge-pr event for task ${this.context.taskId}`),await this.client.sendWithAck("merge-pr",e)}associateRepository(e,t,n,s){const a={eventId:j(),taskId:this.context.taskId,gitServerHost:e,owner:t,repo:n,remoteUrl:s};pe.info(`[REPO] Sending repository association request: ${e}/${t}/${n}`),this.client.send("associate-repo",a)}async dispatchTaskMessage(e){await this.context.onTaskMessage(e)}sendEventAck(e){this.client.send("event-ack",{eventId:j(),status:"success",opCode:e})}initHandlers(){const e=(t=this.context,n=this.historyDb,s=e=>{this.sendEventAck(e)},{"cancel-task":async e=>{e.taskId===t.taskId&&(pe.info(`[WORKER] Task ${t.taskId} cancelled`),await t.stopTask())},"stop-task":async e=>{e.taskId===t.taskId&&(pe.info(`[WORKER] Task ${t.taskId} stopped: ${e.reason||"no reason"}`),await t.stopTask())},"task-message":async e=>{if(e.taskId!==t.taskId)return;let a=e.message??null;if(!a&&e.encryptedMessage&&t.dataEncryptionKey&&(a=W(e.encryptedMessage,t.dataEncryptionKey)??null),!a)return;const i={senderType:e.senderType,senderId:e.senderId,senderName:e.senderName};if(t.attachmentsDir&&F(a)&&(a=await ra(a,{attachmentsDir:t.attachmentsDir,log:t.logger})),t.shouldPersistTaskMessage&&!await t.shouldPersistTaskMessage(a,i))return void pe.debug(`[WORKER] Dropping incoming task-message before persistence: eventId=${e.eventId}`);if(!n.saveMessage({eventId:e.eventId,message:a,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName}).inserted)return pe.debug(`[WORKER] Ignoring duplicate incoming task-message: eventId=${e.eventId}`),void s(e.eventId);const o={...e,message:a,encryptedMessage:void 0,chatId:e.chatId??t.chatId};n.saveTaskEvent({eventType:"task-message",eventId:e.eventId,eventData:o,taskId:t.taskId,chatId:e.chatId??t.chatId,sequence:e.sequence??null}),s(e.eventId),t.onTaskMessage&&await t.onTaskMessage(a,i)},"task-info-update":async e=>{e.taskId===t.taskId&&t.onTaskInfoUpdate&&await t.onTaskInfoUpdate(e)},"worker-status-request":async e=>{e.taskId===t.taskId&&t.onWorkerStatusRequest&&await t.onWorkerStatusRequest(e)},"sub-task-result-updated":async e=>{e.parentTaskId===t.taskId&&t.onSubTaskResultUpdated&&await t.onSubTaskResultUpdated(e)},"sub-task-ask-user":async e=>{e.parentTaskId===t.taskId&&t.onSubTaskAskUser&&await t.onSubTaskAskUser(e)}});var t,n,s;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("sub-task-ask-user",e["sub-task-ask-user"]),this.client.onEvent("event-ack",e=>{const t=e.data?.sequence;void 0!==e.opCode&&(this.outbox.delete(e.opCode),this.usageOutbox.delete(e.opCode)),void 0!==e.opCode&&"number"==typeof t&&this.historyDb.updateTaskEventSequence(e.opCode,t)}),this.client.onLifecycle("connect",()=>{if(this.hasConnectedOnce){if(this.outbox.size>0){pe.info(`[WORKER] Reconnected — flushing ${this.outbox.size} outbox message(s)`);for(const[e,t]of this.outbox.entries()){const n=this.usageOutbox.get(e);n&&this.client.send("task-usage-report",n),this.client.send("task-message",t)}}}else this.hasConnectedOnce=!0})}}class ya{logger;socketClient;taskId;userId;chatId;rootTaskId;parentTaskId;workingDirectory;taskAgents;serverUrl;taskDataKey;agentHomeDir;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.agentHomeDir=e.agentHomeDir,this.taskAgents=e.taskAgents,this.serverUrl=e.serverUrl,this.taskDataKey=e.taskDataKey}async call(e,t,n){const s=j();try{const a=await this.socketClient.sendWithAck("rpc-call",{eventId:s,taskId:this.taskId,method:e,path:t,query:n?.query,body:n?.body});if(!a.success){const n=a.error||{code:"unknown",message:"Unknown error"};throw new Error(`RPC ${e} ${t} failed: ${n.message} (${n.code})`)}return a.data}catch(n){throw new Error(`RPC ${e} ${t} error: ${n.message}`)}}log(e){this.logger.info(e)}getWorkspace(){return this.workingDirectory}getAgentHomeDir(){return this.agentHomeDir}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,t){return this.call("PATCH",`/v1/draft-agent/${e}`,{body:t})}async startSubTask(e){const t={userId:this.userId,chatId:this.chatId,agentId:e.agentId,parentTaskId:this.taskId,customTitle:e.title,cwd:e.cwd,forceUserCwd:e.forceUserCwd};return this.taskDataKey?t.encryptedMessage=z(e.message,this.taskDataKey):t.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:t})).taskId}}async startIndependentTask(e){const t={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?t.encryptedMessage=z(e.message,this.taskDataKey):t.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:t})).taskId}}async startGroupTask(e){const t={userId:this.userId,chatId:e.chatId??this.chatId,parentTaskId:this.taskId,customTitle:e.title,todos:e.todos};return this.taskDataKey?t.encryptedMessage=z(e.message,this.taskDataKey):t.message=e.message,{taskId:(await this.call("POST","/v1/tasks/start",{body:t})).taskId}}async createGroupChat(e){return this.call("POST","/v1/agent-group-chats",{body:{agentIds:e}})}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 t=await this.call("GET","/v1/tasks/find-by-agent",{query:{parentTaskId:this.taskId,agentId:e}});return t.taskId?{taskId:t.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 t=await ve.promises.stat(e.path);this.logger.info("[Agent-Context] file stats");const n=t.size,s=e.contentType||Vt.lookup(e.name)||"application/octet-stream",a=(await this.call("POST","/v1/files/upload-urls",{body:{count:1}})).files[0],i=a.url;this.logger.info(`[Agent-Context] FileUploadUrl: ${i}`);const o=await ve.promises.readFile(e.path),r=await fetch(i,{method:"PUT",headers:{"Content-Type":s},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:a.id,name:e.name,size:n,contentType:s,visibility:e.visibility||"private"}}),c="public"===e.visibility?`${this.serverUrl}/v1/files/public/${a.id}`:i.split("?")[0],{fileId:a.id,name:e.name,size:n,contentType:s,url:c}}}function ba(e,t){const n=e.split("\n");return n.length<=t?e:n.slice(0,t).join("\n")+"..."}function wa(e,t){let n=e.resultMessage;if(0===n.result.trim().length&&e.encryptedResultMessage&&t){const s=W(e.encryptedResultMessage,t);s&&"result"===s.type&&(n={type:"result",result:"result"in s?s.result:"",is_error:s.is_error})}const s={...e,resultMessage:{...n,result:ba(n.result,3)}};let a=`<sub-task-result-updated>\n${JSON.stringify(s,null,2)}\n</sub-task-result-updated>`;return a+=n.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:a}}}function ka(e,t){let n=e.message;if(!n&&e.encryptedMessage&&t){const s=W(e.encryptedMessage,t);s&&"ask_user"===s.type&&(n=s)}return{type:"user",message:{role:"user",content:`<sub-task-ask-user>\n${JSON.stringify({taskId:e.taskId,agentId:e.agentId,agentName:e.agentName,taskName:e.taskName,questions:n?.questions??[]},null,2)}\n</sub-task-ask-user>\n<system-reminder>A sub-task agent is asking the user questions. You should answer these questions on behalf of the user based on the task context and instructions. Use the reply_to_sub_task tool to send your answers back.</system-reminder>`}}}function Ia(){const e=new Set;return{filter(t){const n=t;if(!n.message||!n.message.content||"string"==typeof n.message.content)return t;const s=n.message.content.filter(t=>!("tool_result"===t.type&&e.has(t.tool_use_id)||"user"===n.type&&"tool_result"!==t.type));return 0===s.length?null:(n.message.content=s,n)},clear(){e.clear()}}}function Sa(e){const t=_a(e);return t?{type:"user",message:{role:"user",content:[{type:"text",text:`<msg ${Ea({seq:t.seq.toString(),at:t.at,senderType:t.senderType??void 0,senderId:t.senderId??void 0,senderName:t.senderName??void 0})}>${t.text}</msg>\n`},...t.nonTextBlocks]},parent_tool_use_id:null,session_id:""}:null}function Ta(e){const t=_a(e);return t?`<msg ${Ea({seq:t.seq.toString(),at:t.at,senderType:t.senderType??void 0,senderId:t.senderId??void 0,senderName:t.senderName??void 0})}>\n${t.text}\n</msg>`:null}function Ea(e){return Object.entries(e).filter(([,e])=>void 0!==e&&""!==e).map(([e,t])=>`${e}="${function(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}(t)}"`).join(" ")}function Aa(e){const t=[];for(const n of e){const e=Ta(n);e&&t.push(e)}return t.join("\n")}function Ca(e){return`Ask user: ${e.questions.map((e,t)=>{const n=e.options?.map(e=>e.label).filter(Boolean),s=n&&n.length>0?` options: ${n.join(", ")}`:"";return`Q${t+1}[${e.header}] ${e.question}${s}`}).join(" | ")}`}function $a(e){const t=e.status?` status=${e.status}`:"",n=e.reason?` reason=${e.reason}`:"",s=e.answers?.length?e.answers.join(", "):"no answers",a=e.details?.filter(Boolean).join(" | ");return`Ask user response:${t}${n} answers: ${s}${a?` details: ${a}`:""}`}function _a(e){const{text:t,nonTextBlocks:n}=(s=e.message,K(s)?{text:Ca(s),nonTextBlocks:[]}:V(s)?{text:$a(s),nonTextBlocks:[]}:X(s)?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 t=[],n=[];for(const s of e)"text"!==s.type||"string"!=typeof s.text?n.push(s):t.push(s.text);return{text:t.join("\n"),nonTextBlocks:n}}return{text:"",nonTextBlocks:[]}}(e.message.content);case"result":return"success"===e.subtype?{text:e.result,nonTextBlocks:[]}:{text:Array.isArray(e.errors)?e.errors.filter(e=>"string"==typeof e).join("\n").trim():"",nonTextBlocks:[]}}return{text:"",nonTextBlocks:[]}}(s):{text:"",nonTextBlocks:[]});var s;return t?{seq:e.localSequence,at:e.createdAt,senderType:e.senderType,senderId:e.senderId,senderName:e.senderName,text:t,nonTextBlocks:n}:null}function Pa({workClient:e}){return et("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:Fe.string().describe("New title for the task")},async t=>(e.sendChangeTaskTitle(t.title),{content:[{type:"text",text:`Task title updated to: ${t.title}`}]}))}function Ra({agentContext:e,log:t}){return et("emit_to_task","Send a message to a sub-task. Use this to:\n1. Answer a sub-task's ask_user questions: set answers array (one answer per question).\n2. Send follow-up instructions: set instructions only (no answers).",{taskId:Fe.string().describe("Sub-task ID to send the message to"),instructions:Fe.string().optional().describe("Follow-up instructions for the sub-task (used when not answering ask_user)"),answers:Fe.array(Fe.string()).optional().describe("Answers to the sub-task ask_user questions, one per question. When provided, sends as ask_user_response.")},async n=>{try{let t;return t=n.answers&&n.answers.length>0?{type:"ask_user_response",answers:n.answers}:{type:"user",message:{role:"user",content:n.instructions??""}},await e.sendMessage({taskId:n.taskId,message:t,target:"agent"}),{content:[{type:"text",text:`${n.answers?"Sent ask_user response":"Sent follow-up instructions"} to sub-task ${n.taskId}.`}]}}catch(e){return t("error","TASK",`Failed to send message to sub-task ${n.taskId}:`,e),{content:[{type:"text",text:`Failed to send message to sub-task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Ma({historyDb:e}){return et("get_task_history","Retrieve earlier task history stored locally for additional context.",{sequence:Fe.number().int().describe("Return messages before this local sequence (exclusive)."),limit:Fe.number().int().min(1).max(50).default(20).describe("Maximum number of messages to return.")},async t=>{const n=t.limit??20,s=e.pageMessagesBefore(t.sequence,n);return 0===s.data.length?{content:[{type:"text",text:"No earlier messages found."}]}:{content:[{type:"text",text:Aa(s.data)}]}})}function Oa({agentContext:e}){return et("get_task_agents","List the agents available for the current task and return taskAgents info.",{},async()=>{const t=e.getTaskAgents();return t.length?{content:[{type:"text",text:JSON.stringify(t,null,2)}]}:{content:[{type:"text",text:"No task agents available."}]}})}function Da({agentContext:e,log:t}){return et("list_sub_task","List direct sub tasks for the current task with taskId, title, and cwd.",{},async()=>{try{const t=await e.listSubTasks();return t.length?{content:[{type:"text",text:JSON.stringify(t,null,2)}]}:{content:[{type:"text",text:"No sub tasks found."}]}}catch(e){return t("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 Na({agentContext:e,agentId:t,log:n,setPendingNavigateTaskId:s}){return et("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:Fe.string().optional().describe('Target agent ID (e.g., "agent-poster-generator"). If not provided, uses current agent.'),title:Fe.string().min(1).max(200).describe("Task title for the agent to use (required)"),instructions:Fe.string().describe("Detailed instructions for the agent. Be specific about what needs to be done."),briefSummary:Fe.string().describe('One-line summary shown to user immediately (e.g., "Creating login page")'),cwd:Fe.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:Fe.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place)."),independent:Fe.boolean().optional().describe("Create as independent top-level task (no parent). Defaults to false (sub-task mode)."),autoNavigate:Fe.boolean().optional().describe("Auto-switch App UI to this task after creation. Only works with independent=true. Defaults to false.")},async a=>{try{if(a.autoNavigate&&!a.independent)return{content:[{type:"text",text:"Error: autoNavigate can only be used with independent=true"}],isError:!0};const i=a.agentId||t;let o;return a.independent?(o=await e.startIndependentTask({agentId:i,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree,autoNavigate:a.autoNavigate}),a.autoNavigate&&s(o.taskId),n("info","TASK",`Created independent task ${o.taskId} for agent ${i} (autoNavigate: ${a.autoNavigate??!1})`)):(o=await e.startSubTask({agentId:i,message:{type:"user",message:{role:"user",content:a.instructions}},title:a.title,cwd:a.cwd,forceUserCwd:!a.useWorktree}),n("info","TASK",`Created sub-task ${o.taskId} for agent ${i}`)),{content:[{type:"text",text:`🚀 Task created: ${o.taskId}\n${a.agentId?`Agent: ${i}\n`:""}${a.independent?"Mode: Independent\n":""}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","Failed to create task:",e),{content:[{type:"text",text:`Failed to create task: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Ua({agentContext:e,log:t}){return et("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:Fe.string().min(1).max(200).describe("Task title"),instructions:Fe.string().describe("Instructions for the owner agent"),briefSummary:Fe.string().optional().describe("One-line summary shown to user immediately"),agentId:Fe.string().describe("Target agent ID"),cwd:Fe.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:Fe.boolean().optional().describe("Whether to create a git worktree for isolation. Defaults to false (work in-place).")},async n=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startSubTask({agentId:n.agentId,message:{type:"user",message:{role:"user",content:n.instructions}},title:n.title,cwd:n.cwd,forceUserCwd:!n.useWorktree})).taskId}\n${n.briefSummary?`Summary: ${n.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return t("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 ja({agentContext:e,log:t,agentId:n}){return et("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:Fe.string().min(1).max(200).describe("Task title"),requirement:Fe.string().describe("Overall requirement"),briefSummary:Fe.string().optional().describe("One-line summary shown to user immediately"),todos:Fe.array(Fe.object({agentId:Fe.string().describe("Agent ID responsible for the todo"),title:Fe.string().min(1).max(200).describe("Todo title"),instructions:Fe.string().describe("Detailed instructions for this todo")})).min(1).describe("Todo list for agents")},async n=>{try{return{content:[{type:"text",text:`🚀 Task created: ${(await e.startGroupTask({title:n.title,todos:n.todos,message:{type:"user",message:{role:"user",content:n.requirement}}})).taskId}\n${n.briefSummary?`Summary: ${n.briefSummary}\n`:""}\nYou'll receive a <sub-task-result-updated> notification when the task completes. Continue responding to the user.`}]}}catch(e){return t("error","DISPATCH","Dispatch failed:",e),{content:[{type:"text",text:`Dispatch failed: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function qa({askUser:e,log:t}){return et("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:Fe.array(Fe.object({question:Fe.string().describe("The complete question to ask the user"),header:Fe.string().max(12).describe("Short label displayed as a chip/tag (max 12 chars)"),multiSelect:Fe.boolean().describe("Set to true to allow multiple option selections"),options:Fe.array(Fe.object({label:Fe.string().describe("Option label (1-5 words)"),description:Fe.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 n=>{try{const t=n.questions.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]})),s=await e(t);return"answered"!==(s.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${s.answers.map(e=>e.startsWith("other:")?`Other: "${e.slice(6)}"`:e).join("\n")}`}]}}catch(e){return t("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 La({invokeAgent:e}){return et("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:Fe.string().describe("Target agent ID"),hint:Fe.string().optional().describe("Optional context/instruction for the agent")},async t=>(e(t.agentId,t.hint),{content:[{type:"text",text:`Invoked ${t.agentId}. The agent will respond in the chat later.`}]}))}function Ha({workClient:e,agentId:t,uploadFile:n,log:s}){return et("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:Fe.string().optional().describe("Your display name"),avatarPath:Fe.string().optional().describe("Local path to avatar image file (png/jpg/svg)"),signature:Fe.string().optional().describe("Short status line or tagline shown under your name")},async a=>{let i;if(a.avatarPath)try{i=(await n({name:"avatar.png",path:a.avatarPath,visibility:"public"})).fileId}catch(e){return s("error","TOOL","Avatar upload failed:",e),{content:[{type:"text",text:`Avatar upload failed: ${e}`}],isError:!0}}e.sendUpdateAgentInfo(t,{displayName:a.displayName,avatar:i,signature:a.signature});const o=[];return a.displayName&&o.push(`name → ${a.displayName}`),i&&o.push("avatar → uploaded"),a.signature&&o.push(`signature → ${a.signature}`),{content:[{type:"text",text:`Profile updated: ${o.join(", ")}`}]}})}function Ga({assign:e,log:t}){return et("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:Fe.string().describe("Target agent ID"),instruction:Fe.string().describe("Task instruction for the agent"),acknowledgment:Fe.string().optional().describe('Agent\'s quick reply shown immediately (e.g., "starting now", "On it")')},async t=>(e(t.agentId,t.instruction,t.acknowledgment),{content:[{type:"text",text:`Assigned work to ${t.agentId}.`}]}))}function Wa({agentContext:e,log:t}){return et("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:Fe.number().int().min(1).max(50).default(10).optional().describe("Maximum number of tasks to return (default 10)."),status:Fe.enum(["all","active","completed"]).default("all").optional().describe("Filter by task status: all, active, or completed.")},async n=>{try{const t=await e.listTasks({limit:n.limit??10,status:n.status??"all"});return t.length?{content:[{type:"text",text:JSON.stringify(t,null,2)}]}:{content:[{type:"text",text:"No tasks found."}]}}catch(e){return t("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 Fa({chatHistoryDb:e}){return et("read_conversation","Read recent messages from the main conversation between you and the user. Use this to review what was discussed recently.",{limit:Fe.number().int().min(1).max(200).default(50).optional().describe("Number of recent messages to return (default 50)."),before:Fe.number().int().optional().describe("Sequence number — return messages before this sequence for pagination.")},async t=>{if(!e)return{content:[{type:"text",text:"Chat history not available in this mode."}],isError:!0};const n=t.limit??50,s=null!=t.before?e.pageMessagesBefore(t.before,n):e.pageRecentMessages(n);if(0===s.data.length)return{content:[{type:"text",text:"No conversation messages found."}]};let a=Aa(s.data);return s.hasMore&&(a+=`\n\nMore messages available. Use before=${Math.min(...s.data.map(e=>e.localSequence))} to load earlier messages.`),{content:[{type:"text",text:a}]}})}function Ba({agentContext:e,log:t}){return et("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:Fe.string().describe('Brief reminder message (one sentence, e.g., "Heartbeat architecture discussion pending for 2 days, consider following up")'),filePath:Fe.string().optional().describe("Path to detailed analysis file in workspace, if any")},async n=>{try{const t=e.getChatId();return await e.sendMessage({taskId:t,message:{type:"companion_reminder",content:n.content,filePath:n.filePath,timestamp:(new Date).toISOString()},target:"agent"}),{content:[{type:"text",text:"Reminder sent to main companion."}]}}catch(e){return t("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 za({uploadFile:e,log:n}){return et("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., ).",{filePath:Fe.string().describe("Absolute path to the local file to upload"),name:Fe.string().optional().describe("Display name for the file (defaults to filename)")},async s=>{try{const n=t("path"),a=s.name||n.basename(s.filePath);return{content:[{type:"text",text:(await e({name:a,path:s.filePath,visibility:"public"})).url}]}}catch(e){return n("error","TOOL","File upload failed:",e),{content:[{type:"text",text:`File upload failed: ${e}`}],isError:!0}}})}function Ka({agentContext:e,log:t}){return et("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:t,draftAgents:n}=await e.listAgents(),s=e=>`- **${e.displayName||e.name}** (${e.id})\n Type: ${e.type}\n`+(e.developerName?` Developer: ${e.developerName}\n`:"")+` ${e.description||"No description"}\n`;let a="# Available Agents\n\n";return t.length>0&&(a+="## Published Agents\n\n",a+=t.map(s).join("\n")),n.length>0&&(a+="\n## Draft Agents\n\n",a+=n.map(s).join("\n")),0===t.length&&0===n.length&&(a+="No agents available."),{content:[{type:"text",text:a}]}}catch(e){return t("error","AGENTS","Failed to list agents:",e),{content:[{type:"text",text:`Failed to list agents: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}async function*Va(e){yield e}function Xa({visionModel:e,log:t}){return et("analyze_image","Analyze a local image file and return a description of its contents.\nUse this tool when you need to understand the content of an image file on the local filesystem.\nThe primary model does not support vision, so this tool delegates to a vision-capable model.",{imagePath:Fe.string().describe("Absolute path to the image file to analyze"),prompt:Fe.string().optional().describe("Optional specific question or instruction about the image (default: describe the image)")},async n=>{if(!e)return{content:[{type:"text",text:"Vision analysis is not available (missing configuration)."}],isError:!0};try{const t=(await dt(n.imagePath)).toString("base64"),s={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp"}[n.imagePath.split(".").pop()?.toLowerCase()??"jpeg"]??"image/jpeg",a=n.prompt||"Describe this image in detail.",i=Ze({prompt:Va({type:"user",message:{role:"user",content:[{type:"image",source:{type:"base64",media_type:s,data:t}},{type:"text",text:a}]},parent_tool_use_id:null,session_id:""}),options:{model:e,permissionMode:"bypassPermissions",maxTurns:1,tools:[]}});let o="";for await(const e of i)if("result"===e.type){o=e.result??"";break}return{content:[{type:"text",text:o||"No description returned."}]}}catch(e){return t("error","VISION","Failed to analyze image:",e),{content:[{type:"text",text:`Failed to analyze image: ${e instanceof Error?e.message:"Unknown error"}`}],isError:!0}}})}function Ya({log:e}){return et("schedule_task",'Create, list, or delete scheduled tasks (reminders and recurring jobs).\nTasks are managed by the daemon scheduler and fire as reminders to the main companion.\n\nUse action "create" to schedule a new task:\n- For one-time tasks: provide "due" (ISO 8601 timestamp)\n- For recurring tasks: provide "cron" (standard 5-field cron expression)\n- Set timeType to "utc" if the time is in UTC, or "local" (default) if in the user\'s timezone\n\nUse action "list" to see all scheduled tasks.\nUse action "delete" with an "id" to remove a task.',{action:Fe.enum(["create","list","delete"]).describe("Operation to perform"),task:Fe.string().optional().describe("Task description (required for create)"),type:Fe.enum(["once","recurring"]).optional().describe("Task type (required for create)"),due:Fe.string().optional().describe("ISO 8601 timestamp for one-time tasks"),cron:Fe.string().optional().describe('Cron expression for recurring tasks (e.g., "0 18 * * *")'),timezone:Fe.string().optional().describe('IANA timezone (e.g., Asia/Shanghai). Required when timeType is "local"'),timeType:Fe.enum(["utc","local"]).optional().describe('How to interpret time — "utc" for absolute UTC, "local" (default) for user timezone'),id:Fe.string().optional().describe("Task ID (required for delete)")},async t=>{try{const e=await le.readDaemonState();if(!e?.port)return{content:[{type:"text",text:"Daemon not running."}],isError:!0};const n=`http://127.0.0.1:${e.port}`;if("list"===t.action){const e=await fetch(`${n}/schedule`),t=await e.json();if(!e.ok)return{content:[{type:"text",text:`Error: ${t.error}`}],isError:!0};const s=t.tasks??[];return 0===s.length?{content:[{type:"text",text:"No scheduled tasks."}]}:{content:[{type:"text",text:s.map(e=>`- [${e.id}] ${"once"===e.type?`once at ${e.due}`:`recurring: ${e.cron}`} — "${e.task}"`).join("\n")}]}}if("create"===t.action){if(!t.task||!t.type)return{content:[{type:"text",text:"Missing required fields: task, type"}],isError:!0};const e=await fetch(`${n}/schedule`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({task:t.task,type:t.type,due:t.due,cron:t.cron,timezone:t.timezone,timeType:t.timeType})}),s=await e.json();if(!e.ok)return{content:[{type:"text",text:`Error: ${s.error}`}],isError:!0};const a="once"===s.type?`due=${s.due}`:`cron=${s.cron}`;return{content:[{type:"text",text:`Scheduled: id=${s.id}, ${a}`}]}}if("delete"===t.action){if(!t.id)return{content:[{type:"text",text:"Missing required field: id"}],isError:!0};const e=await fetch(`${n}/schedule/${t.id}`,{method:"DELETE"}),s=await e.json();return e.ok?{content:[{type:"text",text:`Deleted: ${t.id}`}]}:{content:[{type:"text",text:`Error: ${s.error}`}],isError:!0}}return{content:[{type:"text",text:`Unknown action: ${t.action}`}],isError:!0}}catch(t){return e("error","SCHEDULE","Schedule task failed:",t),{content:[{type:"text",text:`Failed: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}})}const Ja=mt(Ye);function Qa(e){const t={baseDir:e,binary:"git",maxConcurrentProcesses:6,trimmed:!1};return"win32"===process.platform&&(t.spawnOptions={windowsHide:!0}),ut(t)}async function Za(e){try{const t=Qa(e);return await t.checkIsRepo()}catch{return!1}}async function ei(e){const t=Qa(e),n=(await t.raw(["worktree","list","--porcelain"])).trim().split("\n").filter(Boolean),s=[];let a=null;for(const e of n)if(e.startsWith("worktree "))a&&s.push(a),a={path:e.replace("worktree ","").trim(),branch:null,commit:"",isMain:0===s.length};else if(a)if(e.startsWith("HEAD "))a.commit=e.replace("HEAD ","").trim();else{if(e.startsWith("branch ")){const t=e.replace("branch ","").trim();a.branch=t.replace("refs/heads/","");continue}e.startsWith("detached")&&(a.branch=null)}return a&&s.push(a),s}async function ti(e,t,n,s="HEAD"){const a=k(t);if(r(a)||g(a,{recursive:!0}),r(t)&&!li(t))throw new Error(`Worktree directory already exists at ${t}`);const i=Qa(e);await i.raw(["worktree","add","-b",n,t,s])}async function ni(e,t,n=!1){const s=Qa(e),a=["worktree","remove"];n&&a.push("--force"),a.push(t),await s.raw(a)}async function si(e){const t=Qa(e);await t.init()}async function ai(e){const t=Qa(e);await t.add("."),await t.commit("Initial commit",{"--allow-empty":null})}async function ii(e,t,n){const s=Qa(e);(await s.branchLocal()).all.includes(t)?await s.checkout(t):(n&&await s.checkout(n),await s.checkoutLocalBranch(t))}async function oi(e){const t=Qa(e);return!(await t.status()).isClean()}async function ri(e){const t=Qa(e),n=await t.log({maxCount:1});if(!n.latest)throw new Error("No commits found in repository");return n.latest.hash}async function ci(e){try{const t=Qa(e);return null!==(await t.log({maxCount:1})).latest}catch{return!1}}function li(e){if(!r(e))return!0;const t=m(e);return 0===t.length||1===t.length&&".git"===t[0]}function pi(e){const t=e.match(/^(.*)?\{([^}]*) => ([^}]*)\}(.*)$/);if(!t)return e;const[,n="",,s,a=""]=t;return`${n}${s}${a}`}async function di(e,t,n){const s=Qa(e),a=await s.diffSummary([`${t}..${n}`]);return{totalInsertions:a.insertions,totalDeletions:a.deletions,files:a.files.map(e=>({path:pi(Y(e.file)),insertions:"insertions"in e?e.insertions:0,deletions:"deletions"in e?e.deletions:0}))}}async function ui(e,t){try{const{stdout:n}=await Ja("git",t,{cwd:e,maxBuffer:10485760,windowsHide:!0});return n}catch(e){const t=e;if(1===t.code&&"string"==typeof t.stdout)return t.stdout;throw e}}function mi(e){return e.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>function(e){const[t,n,s]=e.split("\t");if(!t||!n||!s)return null;const a="-"===t?0:Number.parseInt(t,10),i="-"===n?0:Number.parseInt(n,10);if(Number.isNaN(a)||Number.isNaN(i))return null;const o=s.startsWith("/dev/null => ")?s.slice(13):s;return{path:pi(Y(o)),insertions:a,deletions:i}}(e)).filter(e=>null!==e)}function gi(e,t){return re("sha256").update(`${e}\n${t}`).digest("hex")}async function hi(e,t){const n=await ui(e,["diff","--binary","--find-renames",t,"--"]),s=mi(await ui(e,["diff","--numstat","--find-renames",t,"--"])),a=await async function(e){const{stdout:t}=await Ja("git",["ls-files","--others","--exclude-standard","-z"],{cwd:e,maxBuffer:10485760,windowsHide:!0});return t.split("\0").filter(Boolean)}(e),i=await Promise.all(a.map(t=>ui(e,["diff","--no-index","--binary","--","/dev/null",t]))),o=mi((await Promise.all(a.map(t=>ui(e,["diff","--no-index","--numstat","--","/dev/null",t])))).join("\n")),r=function(e){const t=e.trim();return t?`${t}\n`:""}([n,...i].filter(Boolean).join("\n"));return r?{patch:r,stats:{totalInsertions:(c=[...s,...o]).reduce((e,t)=>e+t.insertions,0),totalDeletions:c.reduce((e,t)=>e+t.deletions,0),files:c},artifactVersion:gi(t,r)}:null;var c}async function fi(e){const t=Qa(e);return(await t.revparse(["--abbrev-ref","HEAD"])).trim()}async function vi(e,t,n){const s=Qa(e);await s.remote(["set-url",t,n])}function xi(e){try{const t=new URL(e);return t.username="",t.password="",t.toString()}catch{return e}}async function yi(e,t,n){const s=Qa(e),a=(await s.getRemotes(!0)).find(e=>e.name===t);a?a.refs.fetch!==n&&await vi(e,t,n):await s.addRemote(t,n)}function bi(e){const t=e.match(/^git@([^:]+):(.+)\/(.+?)(?:\.git)?$/);if(t){const[,n,s,a]=t;return{url:e,host:n.split("-")[0],owner:s,repo:a}}const n=e.match(/^https?:\/\/([^/]+)\/(.+)\/(.+?)(?:\.git)?$/);if(n){const[,t,s,a]=n;return{url:e,host:t,owner:s,repo:a}}return null}const wi="oauth2",ki="AGENTRIX_GIT_USERNAME",Ii="AGENTRIX_GIT_PASSWORD";function Si(){const e=w(s(),`git-askpass-${ie()}.sh`);return p(e,`#!/bin/sh\ncase "$1" in\n *Username*|*username*) printf '%s\\n' "\${${ki}:-${wi}}" ;;\n *) printf '%s\\n' "\${${Ii}:-}" ;;\nesac\n`,{mode:448}),e}function Ti(e,t,n=wi){return{...process.env,GIT_ASKPASS:e,GIT_TERMINAL_PROMPT:"0",[ki]:n,[Ii]:t}}function Ei(e){if(e)return e.replace(/\/+$/g,"")||"/"}function Ai(e){return{gitUrl:e.gitUrl,baseBranch:e.baseBranch,branchName:e.branchName,cwd:Ei(e.cwd)||"",userCwd:Ei(e.userCwd),forceUserCwd:e.forceUserCwd,useWorktree:e.useWorktree,userId:e.userId,taskId:e.taskId,repositorySourceType:e.repositorySourceType,taskRepositoryId:e.repositoryId,gitServerId:e.gitServerId}}function Ci(e,t){return t??`agentrix/${e}`}async function $i(e){if(!e)return null;const t=await Zt();return t?sn(e,t):null}async function _i(e,t){const n=nn(t);if(!n)return void console.warn("[GIT] No PAT user metadata found, skipping git config");const s=n.username,a=n.email||`${n.username}@gitlab.local`;await async function(e,t,n){await Ja("git",["config","user.name",t],{cwd:e,windowsHide:!0}),await Ja("git",["config","user.email",n],{cwd:e,windowsHide:!0})}(e,s,a),console.log(`[GIT] Set local git config user.name=${s} user.email=${a}`)}async function Pi(e,t,n){const s=await $i(n);s?await async function(e,t){const n=Si();try{await Ja("git",["-c","credential.helper=","fetch","--prune","origin"],{cwd:t,env:Ti(n,e),windowsHide:!0})}finally{f(n)}}(s,e):await async function(e,t){await Ja("git",["-c","credential.helper=","fetch","--prune",e,"+refs/heads/*:refs/remotes/origin/*","+refs/tags/*:refs/tags/*"],{cwd:t,windowsHide:!0})}(t,e)}async function Ri(e,t,n,s={}){const a=await $i(s.gitServerId);a?await async function(e,t,n,s=!1){const a=Si();try{const i=["-c","credential.helper=","push","origin",n];s&&i.push("--force"),await Ja("git",i,{cwd:t,env:Ti(a,e),windowsHide:!0})}finally{f(a)}}(a,e,t,n):s.gitUrl?await async function(e,t,n,s=!1){const a=["-c","credential.helper=","push",e,n];s&&a.push("--force"),await Ja("git",a,{cwd:t,windowsHide:!0})}(s.gitUrl,e,t,n):await async function(e,t,n=!1){const s=Qa(e),a=n?["--force"]:[];await s.push("origin",t,a)}(e,t,n)}async function Mi(e,t,n){const s=n.trim();if(!s)return;const a=le.resolveDataDir(e,t),i=w(a,"patch.diff");return await gt(a,{recursive:!0}),await ht(i,`${s}\n`),i}async function Oi(e,t,n){await le.writeLastSentArtifactVersion(e,t,n)}function Di(e,t){return`Please generate pull request metadata for the changes made in this task.\n\nInitial commit hash: ${e}\n${t?`\n\nAdditional instructions:\n${t}`:""}\n\nProvide a concise title (conventional commits format), a detailed description, and a user-facing summary message.`}function Ni(e,t,n,s=6e4){return new Promise(a=>{const i=`shell_${xt().replace(/-/g,"")}`;n.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=je("/bin/bash",["-c",e],{cwd:t,env:process.env,shell:!1});let r=null,c=!1;s>0&&(r=setTimeout(()=>{c=!0,o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL")},1e3)},s));let l="";o.stdout?.on("data",e=>{l+=e.toString()}),o.stderr?.on("data",e=>{l+=e.toString()}),o.on("close",(e,t)=>{let o,p,d;if(r&&clearTimeout(r),c){o=124,d=!0;const e=`\n[Command timed out after ${s/1e3} seconds]`;p=l?`${l}${e}`:e.trim()}else o=null!==e?e:"SIGTERM"===t?143:1,d=0!==o,p=l||"(no output)";n.onOutput({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:i,content:p,is_error:d}]},parent_tool_use_id:null,session_id:""}),n.onComplete(o),a(o)}),o.on("error",e=>{r&&clearTimeout(r);const t=`[Error] ${e.message||"Command execution failed"}`;n.onOutput({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:i,content:t,is_error:!0}]},parent_tool_use_id:null,session_id:""}),n.onComplete(1),a(1)})})}class Ui{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 t=("string"==typeof e.message.content?e.message.content:"").trim();return t.startsWith("!")&&!t.startsWith("![")?{type:"bash-command",content:t.slice(1).trim(),originalMessage:e}:"![merge-request]"===t?{type:"merge-request",content:t,originalMessage:e}:"![merge-pr]"===t?{type:"merge-pr",content:t,originalMessage:e}:"![new]"===t?{type:"new-session",content:t,originalMessage:e}:"![plan]"===t?{type:"plan-mode",content:t,originalMessage:e}:{type:"normal",content:t,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 t=this.parseMessage(e),n={id:"msg-"+ ++this.messageIdCounter,type:t.type,priority:"normal",content:t.content,originalMessage:e,timestamp:Date.now()};this.messageQueue.push(n),this.log("info","COORDINATOR",`Enqueued message ${n.id} (type: ${n.type}, queue: ${this.messageQueue.length})`),this.tryUpdateWorkerState(),this.tryProcessNext()}async tryProcessNext(){if(!this.isStopped)if(0!==this.messageQueue.length)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.tryUpdateWorkerState(),this.isStopped||this.tryProcessNext()}else this.tryUpdateWorkerState()}async processMessage(e){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;case"plan-mode":await this.processPlanMode(e);break;default:this.log("warn","COORDINATOR",`Unknown message type: ${e.type}`)}}async processNormalMessage(e){this.log("info","COORDINATOR","Processing normal message for SDK");const t=await this.config.handlers.onNormalMessage(e.originalMessage);this.enqueueAgentMessage(t)}async processBashCommand(e){this.log("info","COORDINATOR",`Processing bash command: ${e.content}`),await this.processCommand(async()=>{await this.config.handlers.onBashCommand(e.content,e.originalMessage)},e)}async processMergeRequest(e){this.log("info","COORDINATOR","Processing merge-request command"),await this.processCommand(async()=>{await this.config.handlers.onMergeRequest(e.originalMessage)},e)}async processMergePr(e){this.log("info","COORDINATOR","Processing merge-pr command"),await this.processCommand(async()=>{await this.config.handlers.onMergePr()},e)}async processNewSession(e){this.log("info","COORDINATOR","Processing new-session command"),await this.processCommand(async()=>{await(this.config.handlers.onNewSession?.())},e)}async processPlanMode(e){this.log("info","COORDINATOR","Processing plan-mode command"),await this.processCommand(async()=>{if(!this.config.handlers.onPlanMode)return;const t=await this.config.handlers.onPlanMode(e.originalMessage);t&&this.enqueueAgentMessage(t)},e)}async processCommand(e,t){await this.waitWorkerIdle(),this.setCommandRunning(!0),this.markCommandMessageProcessed(t);try{await e()}finally{this.setCommandRunning(!1)}}markCommandMessageProcessed(e){const t=e.originalMessage.__localSequence;void 0!==t&&this.config.onCommandMessageProcessed?.(t)}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 t=this.workerState;if(this.log("info","COORDINATOR",`Worker state: ${t} → ${e}`),this.workerState=e,"running"===e&&"idle"===t&&(this.runStartTime=Date.now(),this.config.workClient.sendWorkRunning(this.getActiveAgents()),this.lastActiveAgentsSignature=this.getActiveAgentsSignature(),this.clearIdleTimer()),"idle"===e&&"running"===t){let e;this.runStartTime&&(e=Date.now()-this.runStartTime,this.runStartTime=null),this.config.workClient.sendWorkerReady(e),this.lastActiveAgentsSignature=null,this.startIdleTimer(),this.config.onBecameIdle?.()}}updateAgentRunning(e){this.setAgentRunning("default","Agent",e)}setAgentRunning(e,t,n){const s="running"===this.workerState,a=this.lastActiveAgentsSignature;n?this.agentRunningMap.set(e,{agentId:e,agentName:t,startedAt:Date.now()}):this.agentRunningMap.delete(e);const i=this.getActiveAgentsSignature();this.lastActiveAgentsSignature=i,this.tryUpdateWorkerState(),s&&"running"===this.workerState&&i!==a&&this.config.workClient.sendWorkRunning(this.getActiveAgents())}setBackgroundTaskRunning(e,t){e&&(t?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:t})=>({agentId:e,agentName:t}))}getActiveAgentsSignature(){const e=this.getActiveAgents().slice().sort((e,t)=>e.agentId.localeCompare(t.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,t=this.hasExecutionWork(),n=!e&&!t;this.setWorkerState(n?"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,t,n){this.config.logger&&this.config.logger(e,t,n)}}function ji(e,t){const n={type:"assistant",session_id:"",uuid:crypto.randomUUID(),parent_tool_use_id:null,message:{role:"assistant",content:[{type:"text",text:t}]}};e.sendTaskMessage(va,n)}async function qi(e){const{workingDirectory:t,workClient:n,repositoryId:s,gitServerId:a,gitUrl:i,logger:o,allowInteractive:r=!0,askUser:c,commitChanges:l}=e;if(o.info("[MERGE-PR] Executing merge-pr command"),s){try{const e=await fi(t),s=await oi(t),p=await async function(e,t){const n=Qa(e);try{return(await n.log([`origin/${t}..HEAD`])).total>0}catch{return!0}}(t,e);if(s||p){if(!r)throw new Error("merge-pr requires user input to resolve git state, which is not supported in oneshot execution mode");const d=await async function(e,t,n,s){let a="";a=e&&t?"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:a,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 n(i)).answers[0];return e.startsWith("other:")?(s.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 s.error("[MERGE-PR] Ask user failed:",e),"Pause"}}(s,p,c,o);if("Pause"===d)return void ji(n,"Operation paused. Please handle git state and run merge again.");if(("Push"===d||"PushAndMerge"===d)&&(s&&(o.info("[MERGE-PR] Generating commit message with agent"),await l(),o.info("[MERGE-PR] Committed changes with agent-generated message")),o.info(`[MERGE-PR] Pushing branch ${e} to remote`),await Ri(t,e,!1,{gitServerId:a,gitUrl:i}),"Push"===d))return void ji(n,"✅ All changes pushed to remote. You can now review and run merge again if everything looks good.")}const d=await n.sendMergePr();if(d.success)ji(n,`✅ PR merged successfully! Branch ${e} has been merged into the target branch.`);else{let e;switch(d.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: ${d.error||"Unknown error"}`;break;default:e=`Failed to merge PR: ${d.error||"Unknown error"}`}n.sendSystemErrorMessage(e)}}catch(e){o.error("[MERGE-PR] Failed:",e);const t=e instanceof Error?e.message:"Unknown error";n.sendSystemErrorMessage(`Failed to push or merge: ${t}`)}o.info("[MERGE-PR] Worker ready after merge-pr execution")}else n.sendSystemErrorMessage("Cannot merge: task has no git repository configured.")}function Li(e,t){const n=e.updates?.repositoryId;return"string"==typeof n&&0!==n.length&&t.repositoryId!==n&&(t.repositoryId=n,le.writeTaskInput(t),!0)}function Hi(e,t,n,s={}){const a=n.sendAskUser(e),i=s.timeoutMs??18e5,o=s.onTimeout;return new Promise((e,s)=>{const r=setTimeout(()=>{t.delete(a);const i={type:"ask_user_response",answers:[],status:"timeout",reason:"timeout"};n.sendAskUserResponse(a,i),"abort_task"===o?(n.onTimeoutMessage?.("ask_user timed out. Task cancelled."),n.stopTask?.("ask_user_timeout"),s(new Error("Ask user request timed out"))):e(i)},i);t.set(a,t=>{clearTimeout(r),e(function(e){const t=e.status??"answered";return e.status&&e.reason?e:{...e,status:t,reason:e.reason??("timeout"===t?"timeout":"user")}}(t))})})}function Gi(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:ie(),session_id:e.sessionId}}function Wi(e,t){const n=ie();return t.set(e,n),n}function Fi(e,t){return t.get(e)||e}function Bi(e,t){return"thread.started"===e.type||"turn.started"===e.type||"turn.completed"===e.type||"turn.failed"===e.type?null:"item.started"===e.type?function(e,t){switch(e.type){case"command_execution":return function(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:Wi(e.id,t),name:"Bash",input:{command:e.command}}]},parent_tool_use_id:null,session_id:""}}(e,t);case"file_change":return function(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:Wi(e.id,t),name:"Edit",input:{changes:e.changes.map(e=>({kind:e.kind,path:e.path}))}}]},parent_tool_use_id:null,session_id:""}}(e,t);case"mcp_tool_call":return function(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:Wi(e.id,t),server_name:e.server,name:e.tool,input:e.arguments}]},parent_tool_use_id:null,session_id:""}}(e,t);case"web_search":return function(e,t){return{type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:Wi(e.id,t),name:"web_search",input:{query:e.query}}]},parent_tool_use_id:null,session_id:""}}(e,t);default:return null}}(e.item,t):"item.completed"===e.type?function(e,t){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:ie().toString()}}(e);case"reasoning":default:return null;case"command_execution":return function(e,t){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:Fi(e.id,t),content:"failed"===e.status?"Command execution failed":e.aggregated_output||""}]},parent_tool_use_id:null,session_id:""}}(e,t);case"file_change":return function(e,t){const n=t.get(e.id),s=n??Wi(e.id,t),a=!n;(e.changes||[]).map(e=>`${e.kind}: ${e.path}`);const i={type:"assistant",message:{role:"assistant",content:[{type:"tool_use",id:s,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:s,content:"failed"===e.status?"File changes failed":"File changes completed"}]},parent_tool_use_id:null,session_id:""};return a?[i,o]:o}(e,t);case"mcp_tool_call":return function(e,t){const n=Fi(e.id,t),s="failed"===e.status&&e.error;return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:n,is_error:s,content:s?e.error.message:e.result?.content||""}]},parent_tool_use_id:null,session_id:""}}(e,t);case"web_search":return function(e,t){return{type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:Fi(e.id,t),content:{type:"web_search_result",results:[]}}]},parent_tool_use_id:null,session_id:""}}(e,t);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,t):null}let zi,Ki,Vi;function Xi(e){let t=null,n=!1;for(let s=0;s<e.length;s+=1){const a=e[s];if(n)n=!1;else if("\\"!==a||'"'!==t)if('"'!==a&&"'"!==a||null!==t)if(a!==t){if("#"===a&&null===t)return e.slice(0,s)}else t=null;else t=a;else n=!0}return e}function Yi(e){const t=e.trim();if(!t)return null;if(t.startsWith('"'))try{return JSON.parse(t)}catch{return null}const n=t.match(/^'([^']*)'$/);return n?n[1]:t.match(/^[A-Za-z0-9._:/@+-]+$/)?t:null}function Ji(e){const t=e?.trim();return t||function(){const e=function(){const e=process.env.CODEX_HOME||process.env.AGENTRIX_CODEX_HOME||w(n.homedir(),".codex");return w(e.replace(/^~(?=\/|$)/,n.homedir()),"config.toml")}();if(Ki===e&&void 0!==zi)return zi;if(Ki=e,zi=null,!r(e))return zi;let t;try{t=c(e,"utf8")}catch{return zi}for(const e of t.split(/\r?\n/)){const t=Xi(e).trim();if(!t)continue;if(t.startsWith("["))break;const n=t.match(/^model\s*=\s*(.+)$/);if(!n)continue;const s=Yi(n[1])?.trim();return zi=s||null,zi}return zi}()}class Qi{createCodex(e){const t={},n=function(){if(void 0!==Vi)return Vi??void 0;const e=process.env.AGENTRIX_CODEX_PATH?.trim();return e?(Vi=e,e):0===Ve("codex",["--version"],{stdio:"ignore"}).status?(Vi="codex",Vi):void(Vi=null)}();return n&&(t.codexPathOverride=n),e.env&&(t.env=fs(e.env)),new yt(Object.keys(t).length>0?t:void 0)}getAgentConfiguration(){return null}getHooks(){}getMcpServers(){}async executeHook(e,t,n){}async run(e,t){const n=t.abortController,s=this.createCodex(t),a=Ji(t.model),i={workingDirectory:t.cwd,model:a??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},o=t.agentSessionId?s.resumeThread(t.agentSessionId,i):s.startThread(i),r=await o.run("string"==typeof e?e:ys(e),{signal:n.signal,outputSchema:t.structuredOutputSchema?.schema||void 0});return bs({sessionId:o.id??t.agentSessionId??"unknown",model:a??"unknown",numTurns:1,usage:r.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0,reasoning_output_tokens:0},result:r.finalResponse??"",structuredOutput:ws(r.finalResponse??"",Boolean(t.structuredOutputSchema))})}async*runStreamed(e,t){const n=t.abortController,s=this.createCodex(t),a=Ji(t.model),i={workingDirectory:t.cwd,model:a??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0},o=t.agentSessionId?s.resumeThread(t.agentSessionId,i):s.startThread(i),{events:r}=await o.runStreamed("string"==typeof e?e:ys(e),{signal:n.signal,outputSchema:t.structuredOutputSchema?.schema||void 0});let c=t.agentSessionId||"",l="",p={input_tokens:0,cached_input_tokens:0,output_tokens:0,reasoning_output_tokens:0};const d=new Map,u={get:e=>d.get(e),set:(e,t)=>{d.set(e,t)}};for await(const e of r){if("thread.started"===e.type&&(c=e.thread_id,yield Gi({sessionId:c,cwd:t.cwd,model:a??void 0})),"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&&(l=e.item.text),"item.started"===e.type||"item.completed"===e.type){const t=Bi(e,u);if(!t)continue;const n=Array.isArray(t)?t:[t];for(const e of n)yield e}}const m=bs({sessionId:c,model:a??"unknown",numTurns:1,usage:p,result:l,structuredOutput:ws(l,Boolean(t.structuredOutputSchema))});yield m}loop(e){const t=e.abortController,n=this.createCodex(e),s=Ji(e.model),a={workingDirectory:e.cwd,model:s??void 0,sandboxMode:"danger-full-access",approvalPolicy:"never",skipGitRepoCheck:!0};let i=e.agentSessionId?n.resumeThread(e.agentSessionId,a):n.startThread(a),o=!1;const r=[];let c=null,l=e.agentSessionId??null,p=0;const d=()=>{if(!o&&(o=!0,c)){const e=c;c=null,e(null)}},u=e=>"string"==typeof e?e:ys(e),m=async function*(){try{for(;!o&&!t.signal.aborted;){const n=r.length>0?r.shift():await new Promise(e=>{c=e});if(!n)break;let a="";const d=new Map,m={get:e=>d.get(e),set:(e,t)=>{d.set(e,t)}},{events:g}=await i.runStreamed(u(n),{signal:t.signal,outputSchema:e.structuredOutputSchema?.schema||void 0});for await(const t of g){if(o)break;if("thread.started"!==t.type){if("turn.completed"===t.type){l&&(yield bs({sessionId:l,model:s??"unknown",numTurns:p+1,usage:t.usage??{input_tokens:0,cached_input_tokens:0,output_tokens:0},result:a,structuredOutput:ws(a,Boolean(e.structuredOutputSchema))}));break}if("turn.failed"===t.type)throw new Error(t.error.message);if("error"===t.type)throw new Error(t.message);if("item.started"===t.type||"item.completed"===t.type){"item.completed"===t.type&&"agent_message"===t.item.type&&t.item.text&&(a=t.item.text);const e=Bi(t,m);if(!e)continue;const n=Array.isArray(e)?e:[e];for(const e of n)yield e}}else l=t.thread_id,yield Gi({sessionId:l,cwd:e.cwd,model:s??void 0})}p+=1}}finally{d()}}();return t.signal.addEventListener("abort",d,{once:!0}),{push:e=>{if(console.log("CodexRunner.loop.push:",JSON.stringify(e,null,2)),!o){if(c){const t=c;return c=null,void t(e)}r.push(e)}},events:m,stop:d}}}const Zi=["PreToolUse","PostToolUse","SessionStart","SessionEnd","UserPromptSubmit","Stop","SubagentStop","PreCompact","Notification","RepositoryInit"];function eo(e){const t={};for(const n of Zi){const s=e[n];"function"==typeof s&&(t[n]=s,console.log(`[Hook Loader] ✓ Loaded hook: ${n}`))}const n=Object.keys(t).length;return 0===n?console.warn("[Hook Loader] No valid hooks found in module"):console.log(`[Hook Loader] Successfully loaded ${n} hook(s)`),t}class to{static pool=new Map;static async create(e,t,n){const s=this.pool.get(t);if(s)return s;let a;if("claude"===e){const e=await async function(e){const{agentId:t,agentDir:n,logger:s}=e;if(!t||"default"===t)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{Rs(s,"info",`Loading agent: ${t}`);const e=await Me({agentId:t,framework:"claude",agentDir:n});if(!e.claude)return Rs(s,"warn",`No claude configuration found for agent ${t}`),{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 a=e.claude,i=a.plugins.map(e=>({type:"local",path:e})),o=n||Oe().resolveAgentDir(t),r=a.config.sdkMcpTools?.map(e=>w(o,"claude",e)),c={customSystemPrompt:a.systemPrompt,customModel:a.config.model,customFallbackModel:a.config.fallbackModel,customMaxTurns:a.config.maxTurns,customExtraArgs:a.config.extraArgs,customPermissionMode:a.config.settings?.permissionMode,customPlugins:i,systemPromptMode:a.config.systemPrompt?.mode??"append",customPRPromptTemplate:a.prPromptTemplate,prPromptMode:a.config.pullRequestPrompt?.mode??"append",customSdkMcpTools:r};return Rs(s,"info",`Agent ${t} loaded successfully (${i.length} plugins)`),c}catch{return Rs(s,"error",`Failed to load agent: ${t}`),{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:t,agentDir:n?.agentDir,logger:n?.logger});let s,i;n?.context&&t&&"default"!==t&&(s=await async function(e,t,n){if(e&&"default"!==e)try{const s=J(),a=t||s.resolveAgentDir(e),i=w(a,"claude");return await async function(e,t){const n=Se(e,"hooks");if(!be(n))return{};const s=[Se(n,"dist","index.mjs"),Se(n,"dist","index.js"),Se(n,"index.mjs"),Se(n,"index.js")];let a=null;for(const e of s)if(be(e)){a=e;break}if(!a)return console.warn(`[Hook Loader] Hooks not built: ${n}`),console.warn("[Hook Loader] To build hooks, run:"),console.warn(`[Hook Loader] cd ${n}`),console.warn("[Hook Loader] npm install && npm run build"),console.warn("[Hook Loader] Or place hooks directly in:"),console.warn(`[Hook Loader] ${Se(n,"index.js")} or ${Se(n,"index.mjs")}`),{};try{console.log(`[Hook Loader] Loading hooks: ${a}`);const e=`${it(a).href}?t=${Date.now()}`,n=await import(e);if("function"==typeof n.default){if(t)return console.log("[Hook Loader] Using factory pattern with AgentrixContext"),eo(n.default(t));console.warn("[Hook Loader] Factory function found but no context provided, skipping factory")}return eo(n)}catch(e){throw console.error(`[Hook Loader] Failed to load hooks from ${a}:`,e),new Error(`Hook loading failed: ${e instanceof Error?e.message:String(e)}`)}}(i,n)}catch(e){return void console.warn("[AgentRunners] Failed to load hooks:",e)}}(t,n.agentDir,n.context)),n?.context&&e.customSdkMcpTools&&e.customSdkMcpTools.length>0&&(i=await async function(e,t,n){const s={};for(const a of e)try{n&&n("info","MCP",`Loading SDK MCP tools from: ${a}`);const e=await import(a),i=e.default||e;if(!i){n&&n("warn","MCP",`No default export found in ${a}`);continue}const o="function"==typeof i?i(t):i,r=o.name;s[r]=o,n&&n("info","MCP",`Loaded MCP server: ${r}`)}catch(e){n&&n("error","MCP",`Failed to load SDK MCP tools from ${a}: ${e instanceof Error?e.message:String(e)}`)}return s}(e.customSdkMcpTools,n.context,n.logger)),a=new Ps(t,e,s,i)}else a=new Qi;return this.pool.set(t,a),a}static release(e){this.pool.delete(e)}static releaseAll(){this.pool.clear()}}class no{constructor(e){this.workingDirectory=e}async listFiles(e=3){const t=[];return this.listFilesRecursively(this.workingDirectory,t,"",e,0),t}async readFile(e){try{const t=ke.join(this.workingDirectory,e);return ve.existsSync(t)?ve.readFileSync(t,"utf-8"):null}catch{return null}}async fileExists(e){const t=ke.join(this.workingDirectory,e);return ve.existsSync(t)}listFilesRecursively(e,t,n,s,a){if(!(a>s))try{const i=ve.readdirSync(e,{withFileTypes:!0});for(const o of i){const i=n?`${n}/${o.name}`:o.name;o.isDirectory()?Z.includes(o.name)||this.listFilesRecursively(ke.join(e,o.name),t,i,s,a+1):o.isFile()&&t.push(i)}}catch(e){}}}class so{constructor(e){this.params=e}state=null;async setup(){const{options:e,handlers:t}=this.params,{userId:n,taskId:s,cwd:a}=e;if(!a)throw new Error("[WORKSPACE] Missing cwd for workspace setup");const i=le.getWorkspaceState(n,s),o=e.repositorySourceType,r={...e,repositorySourceType:o},{initialCommitHash:c,isGitRepository:l,setupAction:p,useWorktree:d,initPolicyUpdates:u}=await this.ensureWorkspace(r,t,i);await le.writeWorkspaceState(n,s,{initialized:!0,initializedAt:(new Date).toISOString(),cwd:a,repositorySourceType:r.repositorySourceType,useWorktree:d,userCwd:e.userCwd,forceUserCwd:e.forceUserCwd,gitUrl:e.gitUrl,baseBranch:e.baseBranch,taskRepositoryId:e.taskRepositoryId,initialCommitHash:c,initPolicies:{...i?.initPolicies,...u}});const m=await async function(e,t,n,s){return async function(e,t,n,s){if(!await Za(e))return{currentCommitHash:"",hadUncommittedChanges:!1,hasNewArtifacts:!1,lastSentArtifactVersion:void 0,patchPath:"",diffStats:void 0};const a=await oi(e),i=await ri(e),o=s||le.getWorkspaceState(t,n)?.initialCommitHash;if(!o)throw new Error(`Initial commit hash not found for task ${n}`);const r=await hi(e,o),c=r?await Mi(t,n,r.patch):void 0,l=await le.readLastSentArtifactVersion(t,n),p=!!r&&r.artifactVersion!==l;return{currentCommitHash:i,currentArtifactVersion:r?.artifactVersion,hadUncommittedChanges:a,hasNewArtifacts:p,lastSentArtifactVersion:l??void 0,patchPath:c,diffStats:r?.stats}}(e,t,n,s)}(a,n,s,c);return this.state={cwd:a,initialCommitHash:c,isGitRepository:l,setupAction:p,gitStateResult:m},l&&!e.taskRepositoryId&&await async function(e,t){try{const n=await async function(e){try{const t=Qa(e),n=(await t.getRemotes(!0)).find(e=>"origin"===e.name);return n?.refs?.fetch?bi(n.refs.fetch):null}catch(e){return console.error("[GIT] Failed to get remote info:",e),null}}(e);if(!n)return void console.log("[REPO] No origin remote found, skipping repository association");if(!t?.onRepositoryDetected)return;console.log(`[REPO] Detected remote: ${n.host}/${n.owner}/${n.repo}`),t.onRepositoryDetected(n)}catch(e){console.error("[REPO] Failed to send repository association:",e)}}(a,t),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:t,initialCommitHash:n,isGitRepository:s}=this.getState(),{userId:a,taskId:i}=this.params.options;if(!s||!n)return{};const o=await hi(t,n);if(!o)return{};try{await Mi(a,i,o.patch)}catch(t){e.onPatchError?.(t)}const r=await async function(e){const t=new no(e);return Q(t)}(t),c=await le.readLastSentArtifactVersion(a,i);return c&&c===o.artifactVersion?{artifactVersion:o.artifactVersion}:{artifactVersion:o.artifactVersion,artifacts:{artifactVersion:o.artifactVersion,stats:o.stats,preview:r}}}async ensureWorkspace(e,t,n){const s=e.repositorySourceType;return"git-server"===s?this.ensureGitServerWorkspace(e,t,n):"directory"===s?this.ensureDirectoryWorkspace(e,t,n):this.ensureTemporaryWorkspace(e,t,n)}async ensureGitServerWorkspace(e,t,n){const{cwd:s,gitUrl:a,taskId:i,baseBranch:o,branchName:c,gitServerId:l}=e;if(!a)throw new Error("[WORKSPACE] gitUrl is required for git-server mode");const p=Boolean(e.taskRepositoryId&&l),d="git-server"===n?.repositorySourceType&&!0===n.useWorktree,u=await Za(s),m=li(s);if(p&&(!u||d)){const p=await async function(e,t,n,s,a,i){const o=Ei(e)||e,c=xi(n),l=bi(c);if(!l)throw new Error(`Unable to resolve repository owner/name from git URL: ${c}`);const p=le.resolveRepoStoreCheckoutDir(s,l.owner,l.repo),d=le.resolveRepoStoreLockPath(s,l.owner,l.repo),u=await le.acquireFileLock(d);if(!u)throw new Error(`Timed out waiting for repo store lock at ${d}`);try{await async function(e,t,n,s){const a=xi(t);if(!await Za(e)){if(!li(e))throw new Error(`Repo store directory ${e} exists but is not a git repository`);await si(e)}await yi(e,"origin",a),await Pi(e,t,n);const i=await async function(e,t="origin"){const{stdout:n}=await Ja("git",["for-each-ref","--format=%(refname:short)",`refs/remotes/${t}`],{cwd:e,maxBuffer:10485760,windowsHide:!0});return n.split("\n").map(e=>e.trim()).filter(Boolean).map(e=>e.replace(`${t}/`,"")).filter(e=>"HEAD"!==e)}(e),o=function(e,t){if(t&&e.includes(t))return t;if(e.includes("main"))return"main";if(e.includes("master"))return"master";if(e.length>0)return e[0];throw new Error("Cannot create worktree: repository has no remote branches to base the workspace on.")}(i,s);return await async function(e,t,n){await Ja("git",["checkout","-B",t,n],{cwd:e,windowsHide:!0})}(e,o,`origin/${o}`),{baseBranch:o}}(p,n,s,a);const e=Ci(t,i),c=await ei(p),l=c.find(e=>Ei(e.path)===o);if(l){if(l.branch&&l.branch!==e)throw new Error(`Worktree at ${o} is already attached to branch ${l.branch}. Remove it before retrying: git worktree remove ${o}`);return s&&await _i(o,s),{initialCommitHash:await ri(o)}}const d=c.find(t=>t.branch===e&&Ei(t.path)!==o);if(d)throw new Error(`Branch ${e} is already attached to worktree ${d.path}. Remove it before retrying.`);const u=ut(p),m=(await u.branchLocal()).all.includes(e);if(r(o)&&!li(o))throw new Error(`Worktree directory already exists at ${o}. This may be from a previous task. To clean up: git worktree remove ${o} OR rm -rf ${o}`);try{m?await u.raw(["worktree","add",o,e]):await ti(p,o,e,"HEAD")}catch(e){try{await ni(p,o,!0)}catch{}throw e}return await _i(o,s),{initialCommitHash:await ri(o)}}finally{await le.releaseFileLock(d,u)}}(s,i,a,l,o,c);return u?{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:!0}:{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,p.initialCommitHash,"none"),isGitRepository:!0,setupAction:"worktree",autoCommitPolicy:"enabled",useWorktree:!0}}if(!u){if(!m)throw new Error(`[WORKSPACE] Directory ${s} exists but is not a git repository.`);const e=await async function(e,t,n,s,a,i){const o=Ci(n,i),c=xi(t),l=await Za(e);if(!li(e)&&!l)throw new Error(`Directory ${e} exists but is not a git repository`);const p=await $i(a);return li(e)?(p?(console.log("[GIT] Using GIT_ASKPASS credential injection for clone"),await async function(e,t,n){const s=k(n);r(s)||g(s,{recursive:!0});const a=Si();try{await Ja("git",["-c","credential.helper=","clone",t,n],{env:Ti(a,e),windowsHide:!0})}finally{f(a)}}(p,c,e),a&&await _i(e,a)):await async function(e,t){const n=k(t);r(n)||g(n,{recursive:!0});const s=Qa();await s.clone(e,t)}(t,e),await vi(e,"origin",c),await ii(e,o,s),await ri(e)):(await yi(e,"origin",c),await Pi(e,t,a),a&&await _i(e,a),await ii(e,o,s),await ri(e))}(s,a,i,o,l,c)||await ri(s);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,e,"none"),isGitRepository:!0,setupAction:"clone",autoCommitPolicy:"enabled",useWorktree:!1}}return await vi(s,"origin",xi(a)),{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:n?.useWorktree??!1}}async ensureDirectoryWorkspace(e,t,n){const{cwd:s,taskId:i,userCwd:o}=e;if(await Za(s))return this.tryResolveDirtyRepo(e,t,n);if(!li(s))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};{if(!o)return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};const t=o.replace(/^~/,a());if(li(t))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};if(!await Za(t))return{initialCommitHash:"",isGitRepository:!1,setupAction:"reuse",autoCommitPolicy:"enabled",useWorktree:!1};await ci(t)||await ai(t),await async function(e,t,n,s){const i=e.replace(/^~/,a()),o=Ei(t)||t;if(!await Za(i))throw new Error(`Directory ${i} is not a git repository. Worktrees can only be created from existing git repositories.`);if(!await ci(i))throw new Error(`Cannot create worktree: repository at ${i} has no commits. Please create an initial commit first: cd ${i} && git add . && git commit -m 'Initial commit'`);const c=Ci(n,s),l=(await ei(i)).find(e=>Ei(e.path)===o);if(l){if(l.branch&&l.branch!==c)throw new Error(`Worktree at ${o} is already attached to branch ${l.branch}. Remove it before retrying: git worktree remove ${o}`);return{initialCommitHash:await ri(o)}}const p=ut(i),d=(await p.branchLocal()).all.includes(c);if(r(o)&&!li(o))throw new Error(`Worktree directory already exists at ${o}. This may be from a previous task. To clean up: git worktree remove ${o} OR rm -rf ${o}`);try{d?await p.raw(["worktree","add",o,c]):await ti(i,o,c,"HEAD")}catch(e){try{await ni(i,o,!0)}catch{}throw e}return{initialCommitHash:await ri(o)}}(t,s,i,e.branchName)}return{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:!0}}async ensureTemporaryWorkspace(e,t,n){const{cwd:s,taskId:a}=e;if(!await Za(s)){await async function(e,t,n){const s=await async function(e,t,n){await si(e);const s=function(e,t){return{hook_event_name:"RepositoryInit",workspace_path:e,task_id:t}}(e,t);return n?.onRepositoryInit&&await n.onRepositoryInit(s),await ai(e),await ri(e)}(e,t,n);return{initialCommitHash:s}}(s,a,t),await ii(s,Ci(a,e.branchName),e.baseBranch);const i=await ri(s);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,i,"none"),isGitRepository:!0,setupAction:"init",autoCommitPolicy:"enabled",useWorktree:!1}}return{...await this.tryResolveDirtyRepo(e,t,n),setupAction:"reuse",useWorktree:n?.useWorktree??!1}}async tryResolveDirtyRepo(e,t,n){let s=null,a="enabled";const i={};if(await async function(e){return!!await Za(e)&&await oi(e)}(e.cwd)){const o=this.getPersistedInitPolicy(n,"uncommittedChanges",["Ignore","Commit","Stash"]),r=o?{action:o,remember:!0}:t?.onUncommittedChanges?await t.onUncommittedChanges():{action:"Ignore",remember:!1},c=r.action;if(await async function(e,t){switch(t){case"Ignore":console.log("[GIT] User chose to ignore uncommitted changes");break;case"Stash":console.log("[GIT] Stashing uncommitted changes"),await async function(e){const t=Qa(e);await t.stash(["push"])}(e);break;case"Commit":console.log("[GIT] Committing uncommitted changes with agent-generated message");break;case"Abort":throw new Error("Task aborted by user due to uncommitted changes")}}(e.cwd,c),"Abort"===c)throw new Error("Task aborted by user due to uncommitted changes");if("Commit"===c){if(!t?.onCommitUncommittedChanges)throw new Error("Unable to commit uncommitted changes during workspace setup");await t.onCommitUncommittedChanges()}!o&&r.remember&&(i.uncommittedChanges=c),s=c,"Ignore"===c&&(a="disabled_by_ignore")}let o;if(await ci(e.cwd)||await ai(e.cwd),"Ignore"===s){const t=Ci(e.taskId,e.branchName);o=await fi(e.cwd)===t?"none":"kept"}else o=await this.tryResolveBranchMismatch(e,t,n,i);const r=await ri(e.cwd);return{initialCommitHash:this.resolveInitialCommitHash(n?.initialCommitHash,r,o),isGitRepository:!0,setupAction:"reuse",autoCommitPolicy:a,useWorktree:n?.useWorktree??!1,initPolicyUpdates:i}}getPersistedInitPolicy(e,t,n){const s=e?.initPolicies?.[t];return s&&n.includes(s)?s:null}resolveInitialCommitHash(e,t,n){return e?"kept"===n?t:e:t}async tryResolveBranchMismatch(e,t,n,s){const a=Ci(e.taskId,e.branchName),i=await fi(e.cwd);if(i===a)return"none";const o=this.getPersistedInitPolicy(n,"branchMismatch",["Switch","Keep"]),r=o?{action:o,remember:!0}:t?.onBranchMismatch?await t.onBranchMismatch({currentBranch:i,expectedBranch:a,workingDirectory:e.cwd}):{action:"Switch",remember:!1};if("Abort"===r.action)throw new Error("Task aborted by user due to branch mismatch");return!o&&r.remember&&(s.branchMismatch=r.action),"Keep"===r.action?"kept":(await ii(e.cwd,a,e.baseBranch),"switched")}}const ao=Fe.object({title:Fe.string().describe("Concise PR title following conventional commits format (feat/fix/docs/refactor/test/chore: description), maximum 50 characters"),description:Fe.string().describe("Detailed PR description explaining: what changed, why these changes were necessary, any important technical decisions, and impact on existing functionality"),userMessage:Fe.string().describe("Friendly message to display to the user, summarizing the PR creation. Should be concise and informative.")}),io=Be(ao,{target:"draft-07"}),oo=Be(ao);function ro(e){if("success"!==e.subtype)throw new Error("PR response failed before structured output was returned");const t=e;return t.structured_output?ao.parse(t.structured_output):function(e){if(!e.trim())throw new Error("PR response was empty");const t=co(e),n=JSON.parse(t);return ao.parse(n)}(t.result??"")}function co(e){const t=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);return t?t[1].trim():e.trim()}class lo{chain=Promise.resolve();run(e){const t=this.chain.then(e,e);return this.chain=t.then(()=>{},()=>{}),t}}const po=[{name:"/merge-request",sendAs:"![merge-request]",description:"Create a pull request for current task changes"},{name:"/merge-pr",sendAs:"![merge-pr]",description:"Merge the current pull request"},{name:"/new",sendAs:"![new]",description:"Start a new session for this task"}];function uo(e){const t=e.trim();return t?t.startsWith("/")?t:`/${t}`:""}function mo(e=[]){const t=[],n=new Set;for(const e of po.map(e=>({id:`cli_builtin:${e.name}`,name:e.name,kind:"cli_builtin",sendAs:e.sendAs,description:e.description})))t.push(e),n.add(e.name);const s=Array.from(new Set(e.map(uo).filter(Boolean)));s.sort((e,t)=>e.localeCompare(t));for(const e of s)n.has(e)||t.push({id:`sdk:${e}`,name:e,kind:"sdk",sendAs:e});return t}const go=Fe.object({message:Fe.string().describe("A git commit message following conventional commits. Return only the commit message text, optionally with a blank line and body.")}),ho=Be(go,{target:"draft-07"}),fo=Be(go);async function vo(e){if(!await oi(e.workingDirectory))throw new Error("No uncommitted changes to commit");const t=await ri(e.workingDirectory),n=await async function(e){const t=e.runner.runStreamed("Generate a git commit message for the current uncommitted changes.\n\nRequirements:\n- Follow this repository's commit message conventions.\n- Keep the subject line specific and concise.\n- Add a body only if it materially improves clarity.\n- Return only the commit message.",{cwd:e.workingDirectory,model:e.model,abortController:e.abortController,modeConfig:e.modeConfig,structuredOutputSchema:{type:"json_schema",schema:"claude"===e.schemaTarget?ho:fo}});let n=null;for await(const s of t){if("result"===s.type){n=s;break}await(e.onStreamMessage?.(s))}if(!n)throw new Error("Commit message generation did not return a result message");return function(e){if("success"!==e.subtype)throw new Error("Commit message generation failed before structured output was returned");const t=e,n=(t.structured_output?go.parse(t.structured_output):go.parse(JSON.parse(co(t.result??"")))).message.trim();if(!n)throw new Error("Commit message generation returned an empty message");return n}(n)}(e),s=await async function(e,t){const n=t.trim();if(!n)throw new Error("Commit message cannot be empty");const[s,...a]=n.split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean);if(!s)throw new Error("Commit subject cannot be empty");const i=Qa(e);await i.add(["--all"]);const o=["commit","-m",s];for(const e of a)o.push("-m",e);return await i.raw(o),await ri(e)}(e.workingDirectory,n);if(await oi(e.workingDirectory))throw new Error("Commit completed but working tree is still dirty");if(s===t)throw new Error("Commit completed but HEAD did not change");return{commitHash:s,message:n}}function xo(e){if(e)return{type:"json_schema",schema:e}}async function yo(e,t){await o.promises.mkdir(t,{recursive:!0});const n=await o.promises.readdir(e,{withFileTypes:!0});for(const s of n){const n=b.join(e,s.name),a=b.join(t,s.name);s.isDirectory()?await yo(n,a):await o.promises.copyFile(n,a)}}function bo(e){return"oneshot"===function(e){return e.workerExecutionMode??ee}(e)}class wo{constructor(e,t,n){this.credentials=e,this.options=t,this.workingDirectory=n;const s=this.options.input,{taskId:a,userId:i}=s;this.logger=me({type:"worker",taskId:a}),this.currentAgentSessionId="agentSessionId"in s?s.agentSessionId:void 0;const o=s.taskAgents||[];this.taskAgentsMap=new Map(o.map(e=>[e.id,e]));const r=this.taskAgentsMap.size>1;this.primaryAgentId=r?"planner":s.agentId,this.primaryAgentName=r?"planner":this.taskAgentsMap.get(s.agentId)?.name??"unknown";const c=this.createWorkerClientConfig(i,a,n),l=le.resolveDataDir(i,a);this.historyDb=ta({dataDir:l,taskId:a}),this.workClient=new xa(c.config,{...c.handlers,getPermissionMode:()=>this.getPermissionModeSnapshot(),historyDb:this.historyDb}),this.coordinator=this.createMessageCoordinator(this.workClient,this.options.idleTimeoutSecond),this.agentContext=new ya({logger:this.logger,socketClient:this.workClient.client,taskId:s.taskId,userId:s.userId,chatId:s.chatId,rootTaskId:s.rootTaskId||s.taskId,parentTaskId:s.parentTaskId||null,workingDirectory:this.workingDirectory,agentHomeDir:le.agentrixAgentsHomeDir,taskAgents:s.taskAgents||[],serverUrl:le.serverUrl,taskDataKey:this.options.dataEncryptionKey}),this.agentrixTools=this.createAgentrixTools();const p={...Ai(this.options.input),cwd:this.workingDirectory};this.workspace=new so({options:p,handlers:this.createWorkspaceHandlers(this.workClient)})}abortController=new AbortController;isStopping=!1;askUserAwaiter=new Map;messageFilter=Ia();logger;workClient;workspace;coordinator;agentContext;runner;agentQueues=new Map;currentAgentSessionId;currentGroupId=null;historyDb;chatHistoryDb=null;agentrixTools;pendingNavigateTaskId=null;pendingPermissions=new Map;grantedPermissions=new Set;loopPermissionModeSetter=null;configuredPermissionMode="bypassPermissions";desiredPermissionMode=null;activePermissionMode=null;lastBroadcastPermissionMode=null;taskAgentsMap;messageSavedListener=null;messageDebounceHandle=null;messageDebounceMs=1e4;lastProcessedSequence=0;primarySessionReady=!1;pendingPrimaryLastSequence=null;primaryAgentId;primaryAgentName;exitReason="completed";newMessageGroupId(){return`group-${crypto.randomUUID()}`}refreshGroupId(){this.currentGroupId=this.newMessageGroupId()}getConfiguredPermissionMode(){if(this.isOneShotExecution())return"bypassPermissions";const e=this.runner?.getAgentConfiguration()?.customPermissionMode;return e??"bypassPermissions"}isOneShotExecution(){return bo(this.options.input)}initializePermissionModeState(){this.configuredPermissionMode=this.getConfiguredPermissionMode(),this.desiredPermissionMode??=this.configuredPermissionMode}getPermissionModeSnapshot(){return this.desiredPermissionMode??this.configuredPermissionMode??null}broadcastPermissionMode(e){this.lastBroadcastPermissionMode!==e&&(this.lastBroadcastPermissionMode=e,this.workClient.sendPermissionMode(e))}confirmPermissionModeApplied(e){this.desiredPermissionMode=e,this.activePermissionMode=e,this.broadcastPermissionMode(e)}async applyPermissionMode(e){this.loopPermissionModeSetter&&(await this.loopPermissionModeSetter(e),this.confirmPermissionModeApplied(e))}async flushDesiredPermissionMode(){const e=this.getPermissionModeSnapshot();e&&this.loopPermissionModeSetter&&this.activePermissionMode!==e&&await this.applyPermissionMode(e)}async requestPermissionMode(e){this.desiredPermissionMode=e,this.broadcastPermissionMode(e),await this.flushDesiredPermissionMode()}async restoreConfiguredPermissionMode(){await this.requestPermissionMode(this.configuredPermissionMode)}shouldProcessMessage(e){const t=e.message,n=this.getRunnerMode(),s="group_chat"===n||"group_work"===n,a=V(t);return!!te(t)||!!ne(t)||!(!X(t)&&!a)&&(s?"agent"!==e.senderType&&e.senderId!==this.primaryAgentId:!!a||"system"===e.senderType&&"user"===t.type||"user"===t.type)}shouldDropHeartbeatWhileBusy(){return this.coordinator.isActivelyExecuting()}async processPendingMessages(){const e=this.historyDb.pageMessagesAfter(this.lastProcessedSequence,100),t=this.getRunnerMode(),n="group_chat"===t||"group_work"===t,s=[];for(const t of e.data)if(this.lastProcessedSequence=t.localSequence,this.shouldProcessMessage(t)){if(n&&this.isUnsupportedGroupPlanCommand(t)){this.log("info","PLAN","Ignoring unsupported ![plan] command in group mode");continue}s.push(t)}if(s.length>0){this.deduplicateHeartbeats(s);const e=this.mergeConsecutiveHumanMessages(s);n?await this.processMessagesAsGroup(e):await this.processMessagesIndividually(e)}e.hasMore&&await this.processPendingMessages()}isUnsupportedGroupPlanCommand(e){const t=e.message;return!(!X(t)||"user"!==t.type)&&"![plan]"===ys(t).trim()}deduplicateHeartbeats(e){let t=-1;for(let n=e.length-1;n>=0;n--)te(e[n].message)&&(-1===t?t=n:(e.splice(n,1),t--))}mergeConsecutiveHumanMessages(e){if(0===e.length)return[];const t=[];let n=0;for(;n<e.length;){const s=e[n];if("human"===s.senderType){const a=[s];for(;n+1<e.length;){const t=e[n+1];if("human"!==t.senderType||t.senderId!==s.senderId)break;a.push(t),n++}1===a.length?t.push(s):t.push(this.createMergedHumanMessage(a))}else t.push(s);n++}return t}createMergedHumanMessage(e){const t=[],n=[];for(const s of e){const e=s.message;if(!X(e)||"user"!==e.type)continue;const a=e.message.content;if("string"==typeof a)t.push(a);else if(Array.isArray(a))for(const e of a)"text"===e.type?t.push(e.text):n.push(e)}const s=t.join(""),a=n.length>0?[{type:"text",text:s},...n]:s,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:a},parent_tool_use_id:null,session_id:i.message?.session_id||""}}}async processMessagesAsGroup(e){const t=[],n=[];for(const s of e){const e=Sa(s);if(e){const s=e.message.content;if("string"==typeof s)t.push(s);else if(Array.isArray(s))for(const e of s)"text"===e.type?t.push(e.text):n.push(e)}}if(0===t.length)return;const s=Math.max(...e.map(e=>e.localSequence)),a=t.join(" "),i={type:"user",message:{role:"user",content:n.length>0?[{type:"text",text:a},...n]:a},parent_tool_use_id:null,session_id:""};i.__localSequence=s,await this.coordinator.enqueue(i)}async processMessagesIndividually(e){for(const t of e){const e=this.formatSingleMessage(t);e&&(e.__localSequence=t.localSequence,await this.coordinator.enqueue(e))}}formatSingleMessage(e){const t=e.message;if(te(t))return{type:"user",message:{role:"user",content:`[heartbeat] You are being awakened by a scheduled heartbeat at ${t.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(ne(t)){const e=t;let n=`[reminder from shadow] ${e.content}`;return e.filePath&&(n+=`\nDetailed analysis: ${e.filePath}`),{type:"user",message:{role:"user",content:n},parent_tool_use_id:null,session_id:""}}return X(t)&&"user"===t.type?t: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(t){if(!(t instanceof tt)){e="error",this.log("warn","AGENT","Fatal error:",t);const n=t instanceof Error?t.message:String(t);await this.reportFatalError(n)}}finally{await this.exitWorker("error"===e?"error":this.exitReason)}}async autoInstallAgent(e){const t=this.options.input,n=t.agentGitUrl,s=t.agentGitSubDir;if(n)try{this.log("info","AGENT",`Auto-installing agent ${e} from git`),await as({agentId:e,gitUrl:n,subDir:s??void 0})}catch(t){this.log("warn","AGENT",`Auto-install failed for agent ${e}: ${t}`)}else this.log("warn","AGENT",`Auto-install skipped: no agentGitUrl provided for agent ${e}`)}async applyAgentUpgrade(e,t,n){const s=le.agentrixAgentsHomeDir,a=w(s,`${e}.new`),i=w(s,`${e}-bak`);try{this.log("info","AGENT",`Applying upgrade for ${e}`),is(n),d(n,a),await yo(t,i),u(t,{recursive:!0,force:!0}),d(a,t),be(i)&&u(i,{recursive:!0,force:!0}),this.log("info","AGENT",`Upgrade applied for ${e}`)}catch(n){this.log("warn","AGENT",`Upgrade failed for ${e}: ${n}`),!be(t)&&be(i)&&d(i,t),be(a)&&u(a,{recursive:!0,force:!0})}}async initialize(){const e=this.options.input,t=le.resolveAgentDir(e.agentId),n=w(t,"upgrade"),s=Boolean(e.agentGitUrl),a=Boolean(e.agentId&&"default"!==e.agentId&&!e.agentDir&&s&&!be(t)),i=Boolean(e.agentId&&"default"!==e.agentId&&!e.agentDir&&!a&&be(n));await this.workClient.connect(),this.workClient.sendWorkerInitializing({deployingAgent:a,upgradingAgent:i}),a&&await this.autoInstallAgent(e.agentId),i&&await this.applyAgentUpgrade(e.agentId,t,n);const o=await to.create("claude",e.agentId,{agentDir:e.agentDir,logger:this.log.bind(this),context:this.agentContext});this.runner=o,this.initializePermissionModeState();const r=await this.workspace.setup();await this.registerWithDaemon(this.workingDirectory),this.log("info","WORKSPACE",`Prepared ${this.options.input.repositorySourceType} workspace via ${r.setupAction} at ${this.workingDirectory} (${r.initialCommitHash||"none"})`),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(),this.workClient.sendTaskSlashCommandsUpdate(mo())}createWorkspaceHandlers(e){return this.isOneShotExecution()?{onRepositoryDetected:t=>{e.associateRepository(t.host,t.owner,t.repo,t.url)},onRepositoryInit:async e=>{await(this.runner?.executeHook("RepositoryInit",e))},onUncommittedChanges:async()=>{throw new Error("Uncommitted changes require user input, which is not supported in oneshot execution mode")},onCommitUncommittedChanges:this.commitCurrentChangesWithAgent.bind(this),onBranchMismatch:async()=>{throw new Error("Branch mismatch requires user input, which is not supported in oneshot execution mode")}}:{onRepositoryDetected:t=>{e.associateRepository(t.host,t.owner,t.repo,t.url)},onRepositoryInit:async e=>{await(this.runner?.executeHook("RepositoryInit",e))},onUncommittedChanges:this.onUncommittedChanges.bind(this),onCommitUncommittedChanges:this.commitCurrentChangesWithAgent.bind(this),onBranchMismatch:this.onBranchMismatch.bind(this)}}async registerWithDaemon(e){const t=this.options.input.taskId,n=await _t(t,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});n.error?this.log("warn","DAEMON",`Failed to report session ${t}:`,n.error):this.log("info","DAEMON",`Session ${t} registered`)}setEnvironmentVariables(){this.options.input.environmentVariables&&Object.entries(this.options.input.environmentVariables).forEach(([e,t])=>{null!=t&&(process.env[e]=String(t))}),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,t){const n=1e3*Math.max(0,t??0);return this.coordinator=new Ui({workerType:"claude",workClient:e,onCommandMessageProcessed:e=>{this.markPrimaryMessageProcessed(e)},handlers:{onNormalMessage:async e=>e,onBashCommand:async(e,t)=>{await this.executeBashCommand(e)},onMergeRequest:async e=>{await this.executeMergeRequest()},onMergePr:async()=>{await this.executeMergePr()},onNewSession:async()=>{await this.executeNewSession()},onPlanMode:async()=>this.isOneShotExecution()?(this.workClient.sendSystemErrorMessage("![plan] is not supported in oneshot execution mode",{groupId:this.currentGroupId??void 0}),null):(await this.requestPermissionMode("plan"),null)},logger:(e,t,n)=>{const s=e;this.log(s,t,n)},idleTimeoutMs:n,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}async handleEvent(){const e=this.options.input.event,t=this.options.input.eventData;if("sub-task-result-updated"===e){const e=t,n=wa(e,this.options.dataEncryptionKey);this.historyDb.saveMessage({eventId:e.eventId||`sub-task-${Date.now()}`,message:n,senderType:"system",senderId:"system",senderName:"system"})}if("sub-task-ask-user"===e){const e=t,n=ka(e,this.options.dataEncryptionKey);this.historyDb.saveMessage({eventId:e.eventId||`sub-task-ask-${Date.now()}`,message:n,senderType:"system",senderId:"system",senderName:"system"})}this.isOneShotExecution()?(await this.processPendingMessages(),this.coordinator.hasAgentMessages()||this.isStopping||this.stopTask("oneshot_complete")):this.triggerMessageProcessing(),"task-message"===e&&t?.eventId&&this.workClient.sendEventAck(t.eventId)}async executeMergeRequest(){this.log("info","MERGE","Executing merge-request command");const e=this.getRunnerMode(),t="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 oi(this.workingDirectory)&&await this.commitCurrentChangesWithAgent();const e=await ri(this.workingDirectory),a=this.workspace.getInitialCommitHash();if(!a){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 di(this.workingDirectory,a,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 fi(this.workingDirectory);this.log("info","MERGE",`Pushing branch ${i} to remote`),await Ri(this.workingDirectory,i,!1,{gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl}),this.log("info","MERGE","Successfully pushed branch to remote");const o=this.runner?.getAgentConfiguration(),r=Di(a,(o?.customPRPromptTemplate?(n=o.customPRPromptTemplate,s={initialCommitHash:a,currentCommitHash:"",branchName:""},n.replace(/\{\{initialCommitHash\}\}/g,s.initialCommitHash).replace(/\{\{currentCommitHash\}\}/g,s.currentCommitHash).replace(/\{\{branchName\}\}/g,s.branchName)):void 0)??void 0);this.log("debug","MERGE",`PR prompt: ${r.substring(0,200)}...`);const c=this.runner;let l=null;const p=c.runStreamed(r,{cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),allowAskUser:!this.isOneShotExecution(),structuredOutputSchema:{type:"json_schema",schema:io}});for await(const e of p){if(this.logger.debug(`sdk message: ${JSON.stringify(e)}`),"result"===e.type){l=e;break}const n=t?e:this.messageFilter.filter(e);null!==n&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),n,{groupId:this.currentGroupId??void 0})}if(!l)throw new Error("Merge-request did not return a result message");if("success"!==l.subtype)throw new Error("Merge-request did not return a successful result message");const d=ro(l),u=await this.workClient.sendMergeRequest(d.title,d.description),m=`${d.userMessage}\n\n✅ Pull request created successfully!\nNumber: #${u.pullRequestNumber}\nURL: ${u.pullRequestUrl}`,g={input_tokens:l.usage.input_tokens??0,cached_input_tokens:l.usage.cache_read_input_tokens??0,output_tokens:l.usage.output_tokens??0,reasoning_output_tokens:0};this.workClient.sendTaskMessage(this.getChatSenderMeta(),bs({sessionId:l.session_id,model:this.options.input.model??"unknown",numTurns:l.num_turns,usage:g,result:m}),{groupId:this.currentGroupId??void 0})}catch(e){const t=e instanceof Error?e.message:String(e);this.log("error","MERGE","Merge-request failed:",e),this.workClient.sendSystemErrorMessage(`❌ Merge-request failed: ${t}\n\nPlease check git status and try again, or create the PR manually.`,{groupId:this.currentGroupId??void 0})}var n,s}async executeBashCommand(e){if(!le.isDirectBashAllowed())return this.log("warn","BASH","Direct bash execution is disabled by global settings"),void this.workClient.sendSystemErrorMessage("Direct bash execution is disabled by global settings.",{groupId:this.currentGroupId??void 0});this.log("info","BASH",`Executing command: ${e}`);const t={senderType:"agent",senderId:"bash",senderName:"bash"},n=await Ni(e,this.workingDirectory,{onOutput:e=>{this.workClient.sendTaskMessage(t,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 qi({workingDirectory:this.workingDirectory,workClient:this.workClient,repositoryId:this.options.input.repositoryId,gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl,logger:this.logger,askUser:e=>this.askUser(e,{onTimeout:"abort_task"}),commitChanges:()=>this.commitCurrentChangesWithAgent()})}async commitCurrentChangesWithAgent(){this.log("info","MERGE","Generating commit message with agent"),await vo({runner:this.runner,workingDirectory:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:this.getRunnerModeConfig(),schemaTarget:"claude",onStreamMessage:async e=>{const t=this.taskAgentsMap.size>1?e:this.messageFilter.filter(e);null!==t&&this.workClient.sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}}),this.log("info","MERGE","Committed changes with agent-generated message")}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(){if(this.log("info","AGENT",`Starting Claude agent for task ${this.taskId}`),this.isStopping)return void this.log("info","AGENT",`Skipping Claude run for task ${this.taskId} because worker is stopping`);if(this.isOneShotExecution())return void await this.runClaudeOneShot();const e=this.currentAgentSessionId,t=this.runner,n=this.getRunnerModeConfig(),s="group_chat"===n.mode||"group_work"===n.mode,a=this.createPermissionHandler(),i=this.buildSystemHooks({trackBackgroundTasks:!0,trackPrimaryAgentStop:!0});this.initializePermissionModeState();const o=t.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:e,abortController:this.abortController,initialPermissionMode:this.getPermissionModeSnapshot()??void 0,stderr:e=>{this.log("debug","SDK",e)},modeConfig:n,agentrixTools:this.agentrixTools,allowAskUser:!this.isOneShotExecution(),visionModel:this.options.input.visionModel,canUseTool:a,hooks:i,maxTurns:this.options.input.maxTurns??void 0,structuredOutputSchema:this.getStructuredOutputSchema()});this.loopPermissionModeSetter=o.setPermissionMode??null,this.activePermissionMode=null,this.lastBroadcastPermissionMode=null,this.broadcastPermissionMode(this.getPermissionModeSnapshot()),await this.flushDesiredPermissionMode(),(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(!e){if(this.isStopping)break;continue}this.updateAgentRunning(!0),o.push(e);const t=e.__localSequence;void 0!==t&&(this.markPrimaryMessageProcessed(t),delete e.__localSequence)}}catch(e){this.log("error","AGENT","Message pump failed:",e),this.stopTask("event")}})();for await(const e of o.events)this.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e,s);this.resetPrimaryPermissionState(),this.log("info","AGENT",`Claude agent finished for task ${this.taskId}`)}async runClaudeOneShot(){const e=this.runner,t=this.getRunnerModeConfig(),n="group_chat"===t.mode||"group_work"===t.mode,s=this.createPermissionHandler(),a=this.buildSystemHooks({trackBackgroundTasks:!0,trackPrimaryAgentStop:!0});this.loopPermissionModeSetter=null,this.activePermissionMode=null,this.lastBroadcastPermissionMode=null,this.initializePermissionModeState(),this.broadcastPermissionMode(this.getPermissionModeSnapshot());const i=await this.coordinator.waitForAgentMessage();if(!i)return this.isStopping||this.stopTask("oneshot_complete"),this.resetPrimaryPermissionState(),void this.log("info","AGENT",`Claude oneshot finished for task ${this.taskId} without runnable message`);const o=i.__localSequence;void 0!==o&&(this.markPrimaryMessageProcessed(o),delete i.__localSequence),this.updateAgentRunning(!0);try{const o=e.runStreamed(i,{cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:this.currentAgentSessionId,abortController:this.abortController,initialPermissionMode:this.getPermissionModeSnapshot()??void 0,stderr:e=>{this.log("debug","SDK",e)},modeConfig:t,agentrixTools:this.agentrixTools,allowAskUser:!1,visionModel:this.options.input.visionModel,canUseTool:s,hooks:a,maxTurns:this.options.input.maxTurns??void 0,structuredOutputSchema:this.getStructuredOutputSchema()});for await(const e of o)this.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e,n);this.isStopping||this.stopTask("oneshot_complete")}finally{this.resetPrimaryPermissionState(),this.log("info","AGENT",`Claude oneshot finished for task ${this.taskId}`)}}async handlePrimaryRunnerMessage(e,t){if("system"===e.type&&"init"===e.subtype)return this.workClient.sendUpdateTaskAgentSessionId(e.session_id),this.workClient.sendTaskSlashCommandsUpdate(mo(e.slash_commands??[]),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(),void this.updateAgentRunning(!0);if("result"===e.type)return await this.handleSdkResultMessage(e),this.refreshGroupId(),void this.updateAgentRunning(!1);"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})}resetPrimaryPermissionState(){this.loopPermissionModeSetter=null,this.activePermissionMode=null}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,"oneshot_complete"===e&&(this.exitReason="oneshot_complete",this.log("info","AGENT","One-shot execution completed, stopping task")),"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(),"oneshot_complete"!==e&&this.abortController.abort())}async handleAskUserQuestionPermission(e){const t=e,n=Array.isArray(t.questions)?t.questions:[];if(0===n.length)return this.log("warn","PERMISSION","AskUserQuestion missing questions"),{behavior:"deny",message:"AskUserQuestion missing questions"};const s=n.map(e=>({...e,options:[...e.options,{label:"Other",description:""}]}));try{const e=await this.askUser(s),a={};for(let t=0;t<n.length;t+=1){const s=n[t]?.question;if(!s)continue;const i=e.answers?.[t];"string"==typeof i&&(a[s]=i)}return{behavior:"allow",updatedInput:{...t,answers:a}}}catch(e){return this.log("warn","PERMISSION",`AskUserQuestion failed: ${e}`),{behavior:"deny",message:"AskUserQuestion failed"}}}createPermissionHandler(){return async(e,t)=>{if("AskUserQuestion"===e)return this.handleAskUserQuestionPermission(t);if("ExitPlanMode"===e)return this.handleExitPlanModePermission(t);if(this.grantedPermissions.has(e))return this.log("info","PERMISSION",`Tool "${e}" already granted, skipping`),{behavior:"allow",updatedInput:t};const n=this.pendingPermissions.get(e);if(n)return this.log("info","PERMISSION",`Tool "${e}" has pending request, waiting...`),"allow"===await n?{behavior:"allow",updatedInput:t}:{behavior:"deny",message:"Permission denied by user"};let s;this.log("info","PERMISSION",`Requesting permission for "${e}"`);const a=new Promise(e=>{s=e});this.pendingPermissions.set(e,a);try{const n=await this.requestToolPermission(e);return s(n),"allow"===n?(this.grantedPermissions.add(e),{behavior:"allow",updatedInput:t}):{behavior:"deny",message:"Permission denied by user"}}catch(e){return s("deny"),{behavior:"deny",message:"Permission request failed"}}finally{this.pendingPermissions.delete(e)}}}async handleExitPlanModePermission(e){const t=e.planFilePath??e.filePath;let n,s;if(t){const e=this.workspace.getCwd(),a=e.endsWith("/")?e:e+"/";n=t.startsWith(a)?t.slice(a.length):void 0;try{const e=await we.readFile(t,"utf-8");s=e.length>8e3?e.slice(0,8e3)+"\n\n…(truncated)":e}catch{}}!s&&"string"==typeof e.plan&&e.plan&&(s=e.plan);const a=[{question:"Review the plan and choose how to proceed.",header:"Plan Review",multiSelect:!1,options:[{label:"Approve",description:"Approve the plan and start implementation"},{label:"Revise",description:"Need to revise the plan",additionalInput:{enabled:!0,required:!1,placeholder:"Describe what should change."}},{label:"Cancel",description:"Cancel this plan"}],planFilePath:n,planContent:s}];try{const t=await this.askUser(a,{onTimeout:"abort_task"}),n=t.answers[0],s=t.details?.[0]?.trim();return"Approve"===n?{behavior:"allow",updatedInput:e}:"Revise"===n?{behavior:"deny",message:s?`The user wants to revise the plan. Revision notes: ${s}. Please reconsider and update the plan, then call ExitPlanMode again when ready.`:"The user wants to revise the plan. Please reconsider and update the plan, then call ExitPlanMode again when ready."}:(await this.restoreConfiguredPermissionMode(),{behavior:"deny",message:"User cancelled plan review",interrupt:!0})}catch{return await this.restoreConfiguredPermissionMode(),{behavior:"deny",message:"Plan review failed or was interrupted"}}}async requestToolPermission(e){const t=[{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(t,{onTimeout:"abort_task"})).answers[0]?"allow":"deny"}catch(e){return this.log("warn","PERMISSION",`Permission request failed: ${e}`),"deny"}}async askUser(e,t={}){if(this.isOneShotExecution())throw new Error("ask_user is not supported in oneshot execution mode");const n=this.workClient;return Hi(e,this.askUserAwaiter,{sendAskUser:e=>n.sendAskUser(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0}),sendAskUserResponse:(e,t)=>n.sendAskUserResponse(e,t),onTimeoutMessage:e=>n.sendAssistantMessage(e,{groupId:this.currentGroupId??void 0}),stopTask:e=>this.stopTask(e)},t)}async onUncommittedChanges(){const e=[{question:"Uncommitted changes detected in the working directory. How would you like to proceed?",header:"Git Status",multiSelect:!1,rememberSelection:{enabled:!0,defaultValue:!0},options:[{label:"Ignore",description:"Keep changes on current branch and continue without switching"},{label:"Commit",description:"Create a commit with an agent-generated message, 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 t=await this.askUser(e,{onTimeout:"abort_task"}),n=t.answers[0],s=t.rememberAnswers?.[0]??e[0]?.rememberSelection?.defaultValue??!1;return n.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${n}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort",remember:s}}catch(e){return this.log("warn","GIT",`Failed to get user response for uncommitted changes: ${e}`),{action:"Abort",remember:!1}}}async onBranchMismatch(e){const t=[{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"}],n=[{question:`Branch mismatch detected. Current: ${e.currentBranch}. Expected: ${e.expectedBranch}. How would you like to proceed?`,header:"Git Branch",multiSelect:!1,rememberSelection:{enabled:!0,defaultValue:!0},options:t}];try{const e=await this.askUser(n,{onTimeout:"abort_task"}),t=e.answers[0],s=e.rememberAnswers?.[0]??n[0]?.rememberSelection?.defaultValue??!1;return t.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${t}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[t]||"Abort",remember:s}}catch(e){return this.log("warn","GIT",`Failed to get user response for branch mismatch: ${e}`),{action:"Abort",remember:!1}}}getRunnerMode(){const e=this.taskAgentsMap.size>1,t=this.options.input.taskType,n=!(!process.env.AGENTRIX_COMPANION_HOME&&!process.env.AGENTRIX_COMPANION_WORKSPACE);return"shadow"===t?"companion_shadow":n&&"chat"===t?"companion_chat":e?"chat"===t?"group_chat":"group_work":"chat"===t?"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)}getStructuredOutputSchema(){return xo(this.options.input.outputSchema)}createAgentrixTools(){const e=this.taskAgentsMap.size>1;if("companion_shadow"===this.getRunnerMode()){const e=this.options.input.chatId,t=this.options.input.userId,n=le.resolveDataDir(t,e);this.chatHistoryDb=ta({dataDir:n,taskId:e})}return{createTask:Na(t={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,t)=>this.invokeAgent(e,t),assign:(e,t,n)=>this.assignWork(e,t,n),setPendingNavigateTaskId:e=>{this.pendingNavigateTaskId=e},visionModel:this.options.input.visionModel}),createSoloTask:Ua(t),createGroupTask:ja(t),replyToSubTask:Ra(t),changeTaskTitle:Pa(t),askUser:qa(t),getTaskHistory:Ma(t),getTaskAgents:Oa(t),listSubTask:Da(t),invoke:La(t),assign:Ga(t),updateAgentInfo:Ha(t),sendReminder:Ba(t),listTasks:Wa(t),readConversation:Fa(t),uploadFile:za(t),listAgents:Ka(t),analyzeImage:Xa(t),scheduleTask:Ya(t)};var t}resolveTaskAgentName(e){return this.taskAgentsMap.get(e)?.name||""}getChatSenderMeta(){return{senderType:"agent",senderId:this.primaryAgentId,senderName:this.primaryAgentName}}sendAgentErrorMessage(e,t,n,s){const a=t||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${a}: ${n}`}]}};this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:a},i,{groupId:s?.groupId})}async invokeAgent(e,t){const n=this.buildSubAgentHistoryContext(e,t);if(!n)return!1;const s=this.taskAgentsMap.get(e),a=s?.type||"claude";let i=this.agentQueues.get(e);i||(i=new lo,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();try{const s=await to.create(a,e,{logger:this.log.bind(this),context:this.agentContext}),i=this.getGroupAgents()||[],r={mode:"reply",supportChangeTitle:!1,groupAgents:i},l=this.createPermissionHandler(),p=this.buildSystemHooks({trackBackgroundTasks:!1}),d=Ia(),u=s.loop({cwd:this.workingDirectory,model:this.options.input.model,agentSessionId:n.sessionId,abortController:this.abortController,modeConfig:r,agentrixTools:this.agentrixTools,allowAskUser:!this.isOneShotExecution(),canUseTool:l,hooks:p,maxTurns:this.options.input.maxTurns??void 0,structuredOutputSchema:this.getStructuredOutputSchema()});let m=n.message;if("codex"===a&&!n.sessionId){const t=[hs(e,i),"=== CONVERSATION STREAM START FROM HERE ===",ys(n.message)].join("\n\n").trim();t&&(m=t)}u.push(m);const g=n.lastSequence;let h=!1;n.sessionId&&(this.historyDb.updateAgentLastSequence(e,g),h=!0);let f=!1;for await(const n of u.events){if("system"===n.type&&"init"===n.subtype){this.historyDb?.upsertAgentSession(e,n.session_id),h||(this.historyDb.updateAgentLastSequence(e,g),h=!0);continue}if("result"===n.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},n,{groupId:t}),f=!0;break}const s=c?n:d.filter(n);s&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},s,{groupId:t})}}catch(t){this.log("error","INVOKE",`Invoke failed for ${e}:`,t)}finally{this.coordinator?.setAgentRunning(e,o,!1)}}),!0}async assignWork(e,t,n){const s=this.taskAgentsMap.get(e),a=s?.type||"claude";let i=this.agentQueues.get(e);i||(i=new lo,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 s=this.newMessageGroupId();var i;n&&this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},(i=n,{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 n=await to.create(a,e,{logger:this.log.bind(this),context:this.agentContext}),i={mode:"work",supportChangeTitle:!1},r=this.createPermissionHandler(),l=this.buildSystemHooks({trackBackgroundTasks:!1}),p=Ia(),d=n.loop({cwd:this.workingDirectory,model:this.options.input.model,abortController:this.abortController,modeConfig:i,agentrixTools:this.agentrixTools,allowAskUser:!this.isOneShotExecution(),canUseTool:r,hooks:l,maxTurns:this.options.input.maxTurns??void 0,structuredOutputSchema:this.getStructuredOutputSchema()});d.push(t);let u=!1;for await(const t of d.events){if("system"===t.type&&"init"===t.subtype)continue;if("result"===t.type){this.workClient.sendTaskMessage({senderType:"agent",senderId:e,senderName:o},t,{groupId:s}),u=!0;break}const n=c?t:p.filter(t);n&&this.workClient.sendTaskEvent({senderType:"agent",senderId:e,senderName:o},n,{groupId:s})}}catch(t){this.log("error","RUN_TASK",`Run task failed for ${e}:`,t);const n=t instanceof Error?t.message:String(t);this.sendAgentErrorMessage(e,o,`I meet some error: ${n}`,{groupId:s})}finally{this.coordinator?.setAgentRunning(e,o,!1)}})}buildSubAgentHistoryContext(e,t){const n=this.historyDb;if(!n)return this.log("warn","HISTORY","Task history DB unavailable; delegate cannot build context."),null;const s=n.getAgentSessions().get(e),a=n.getAgentLastSequences().get(e)??0,i=n.pageRecentMessagesAfter(a,20);if(0===i.data.length&&!t)return null;const o=this.mergeConsecutiveHumanMessages(i.data),r=this.buildHistoryMessages(o,t);return r?{message:r,sessionId:s,lastSequence:i.data.length>0?i.data[i.data.length-1].localSequence:a}:null}buildHistoryMessages(e,t){const n=[];for(const t of e){const e=Ta(t);e&&n.push(e)}if(0===n.length&&!t)return null;let s=n.join("\n");return t&&(s=`<hint>\n${t}\n</hint>\n\n${s}`),{type:"user",message:{role:"user",content:s},parent_tool_use_id:null,session_id:""}}buildSystemHooks(e){const t=e?.trackBackgroundTasks??!0,n=e?.trackPrimaryAgentStop??!1,s={};return t&&(s.PostToolUse=async e=>(this.syncPermissionModeFromPostToolUse(e),this.trackBackgroundTaskFromPostToolUse(e),{})),n&&(s.Stop=async()=>(this.updateAgentRunning(!1),{})),s}trackBackgroundTaskFromPostToolUse(e){if(!e||"object"!=typeof e)return void this.log("debug","TASK","PostToolUse hook input is not an object");const t=e,n=t.tool_input;if(!n||!0!==n.run_in_background)return;const s=this.extractBackgroundTaskId(t.tool_response);if(!s)return this.log("debug","TASK",`PostToolUse(${t.tool_name}) run_in_background=true but no task_id found, using anonymous tracking`),void this.coordinator?.setAnonymousBackgroundTaskRunning(!0);this.coordinator?.setBackgroundTaskRunning(s,!0),this.log("info","TASK",`Background task started: ${s} (tool: ${t.tool_name})`)}syncPermissionModeFromPostToolUse(e){if(!e||"object"!=typeof e)return;const t=(n=e.tool_name,s=this.configuredPermissionMode,"EnterPlanMode"===n?"plan":"ExitPlanMode"===n?s:null);var n,s;t&&this.confirmPermissionModeApplied(t)}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 t=new Set,n=new Set,s=e=>{if("string"!=typeof e)return;const n=e.trim();n&&t.add(n)},a=e=>{if(null==e)return;if("string"==typeof e)return void(e=>{const t=/(task[_-]?id|agent[_-]?id|shell[_-]?id)["'\s:=]+([A-Za-z0-9._:-]+)/gi;let n;for(;null!==(n=t.exec(e));)s(n[2])})(e);if("object"!=typeof e)return;if(n.has(e))return;if(n.add(e),Array.isArray(e)){for(const t of e)a(t);return}const t=e;"string"==typeof t.task_id&&s(t.task_id),"string"==typeof t.taskId&&s(t.taskId),"string"==typeof t.agent_id&&s(t.agent_id),"string"==typeof t.agentId&&s(t.agentId),"string"==typeof t.shell_id&&s(t.shell_id),"string"==typeof t.shellId&&s(t.shellId);for(const e of Object.values(t))a(e)};a(e);const i=[...t];return i.length>1&&this.log("warn","TASK",`Multiple background task ids extracted (${i.join(", ")}), using first id ${i[0]}`),i[0]}createWorkerClientConfig(e,t,n){const s=this.options.input.agentId,a=this.taskAgentsMap.get(s)?.name;return{config:{userId:e,taskId:t,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:s,agentName:a,cwd:n,serverUrl:le.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:se(this.credentials.token,this.credentials.machineId,t),dataEncryptionKey:this.options.dataEncryptionKey??null,keepAliveConfig:{intervalMs:2e4,event:"worker-alive",payloadGenerator:()=>{const e=this.coordinator?.getStatus(),n="running"===e?.state?"worker-running":"worker-ready";return{eventId:j(),status:n,taskId:t,machineId:this.credentials.machineId,timestamp:Date.now().toString(),activeAgents:this.coordinator?.getActiveAgents(),permissionMode:this.getPermissionModeSnapshot()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...t)=>this.logger.info(`[SOCKET] ${e}`,...t)},handlers:{attachmentsDir:le.resolveAttachmentsDir(e,t),noVision:!!this.options.input.visionModel,logger:(e,t,n,...s)=>{this.log(e,t,n,...s)},stopTask:async()=>{this.stopTask("event")},shouldPersistTaskMessage:async e=>!te(e)||!this.shouldDropHeartbeatWhileBusy()||(this.log("debug","WORKER","Dropping heartbeat at WorkerClient receive stage: agent is running"),!1),onTaskMessage:async(e,t)=>{if(V(e)){const[t,n]=this.askUserAwaiter.entries().next().value||[];t&&n&&(this.askUserAwaiter.delete(t),n(e))}},onTaskInfoUpdate:async e=>{Li(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 t=wa(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(t)},onSubTaskAskUser:async e=>{const t=ka(e,this.options.dataEncryptionKey);await this.coordinator.enqueue(t)}}}}async exitWorker(e){this.log("info","WORKER",`Exiting with reason: ${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.sendTerminalErrorResult(e,{groupId:this.currentGroupId??void 0})}log(e,t,n,...s){this.logger&&this.logger[e](`[${t}] ${n}`,...s)}get taskId(){return this.options.input.taskId}async handleSdkResultMessage(e){let t,n;try{const e=await this.workspace.prepareResultArtifacts({onPatchError:e=>{this.log("warn","GIT","Failed to write patch diff for result:",e)}});t=e.artifacts,n=e.artifactVersion}catch(e){this.log("warn","GIT","Failed to prepare git artifacts for result:",e)}const s=this.getRunnerMode(),a="group_chat"===s||"group_work"===s,i=this.pendingNavigateTaskId;if(this.pendingNavigateTaskId=null,a?this.workClient.sendTaskEvent(this.getChatSenderMeta(),e,{...t?{artifacts:t}:{},groupId:this.currentGroupId??void 0,navigateToTaskId:i??void 0}):this.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{...t?{artifacts:t}:{},groupId:this.currentGroupId??void 0,navigateToTaskId:i??void 0}),n)try{await Oi(this.options.input.userId,this.taskId,n)}catch(e){this.log("warn","GIT","Failed to mark artifact version as sent:",e)}}}class ko{static async calculateFinalCwd(e){const{repositorySourceType:t,cwd:n,userCwd:s,userId:i,taskId:o,forceUserCwd:r,useWorktree:c}=e,l=e=>Ei(e)||e;if(n)return l(n);const p=le.resolveProjectDir(i,o);if("directory"===t&&s){const e=l(s.replace(/^~/,a()));return r||!1===c?e:await this.shouldUseWorktree(e)?l(p):e}return l(p)}static async shouldUseWorktree(e){try{return!li(e)&&await Za(e)}catch{return!1}}}var Io=Gt(he);class So{constructor(e,t){this.credentials=e,this.options=t}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;exitReason="completed";isOneShotExecution(){return bo(this.options.input)}refreshGroupId(){this.currentGroupId=`group-${ie()}`}async start(){try{await this.initialize(),await this.handleEvent(),await this.runCodex(),await this.exitWorker(this.exitReason)}catch(e){if(!this.isStopping){this.isStopping=!0,this.askUserAwaiter.clear(),this.coordinator?.stop(),this.log("warn","AGENT","Fatal error:",e);const t=e instanceof Error?e.message:String(e);throw await this.exitWorker("error",t),e}this.log("info","AGENT",`Task ${this.taskId} stopped gracefully`),await this.exitWorker(this.exitReason)}finally{process.exit(0)}}async initialize(){const e=this.options.input.taskId,t=this.options.input.userId;this.logger=this.createLogger({type:"worker",taskId:e}),this.dataEncryptionKey=this.options.dataEncryptionKey??null;const n=Ai(this.options.input),s=await ko.calculateFinalCwd(n),a={...n,cwd:s};this.log("info","INIT",`Phase 1: Working directory: ${s}`);const i=this.createWorkerClientConfig(t,e,s),o=le.resolveDataDir(t,e);this.historyDb=ta({dataDir:o,taskId:e});const r=new xa(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 l=new so({options:a,handlers:this.createWorkspaceHandlers(r,s)}),{initialCommitHash:p,gitStateResult:d,setupAction:u}=await l.setup();this.workspace=l,this.log("info","INIT","Phase 7: Workspace setup complete"),r.sendWorkerInitialized(),r.sendTaskSlashCommandsUpdate(mo()),this.log("info","INIT","Phase 8: Initialization finalized"),await this.registerWithDaemon(s),this.log("info","INIT","Phase 9: Registered with daemon"),this.log("info","WORKSPACE",`Prepared ${this.options.input.repositorySourceType} workspace via ${u} at ${s} (${p||"none"})`),this.context={credentials:this.credentials,options:this.options,workClient:r,workingDirectory:s,initialCommitHash:p,logger:this.logger},process.env.AGENTRIX_WORKING_DIR=s,process.env.AGENTRIX_WORKING_USER=t,process.env.AGENTRIX_WORKING_TASK=e,this.options.input.environmentVariables&&Object.entries(this.options.input.environmentVariables).forEach(([e,t])=>{null!=t&&(process.env[e]=String(t))}),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,t){return this.isOneShotExecution()?{onRepositoryDetected:t=>{e.associateRepository(t.host,t.owner,t.repo,t.url)},onUncommittedChanges:async()=>{throw new Error("Uncommitted changes require user input, which is not supported in oneshot execution mode")},onCommitUncommittedChanges:async()=>this.commitCurrentChangesWithAgent(t),onBranchMismatch:async()=>{throw new Error("Branch mismatch requires user input, which is not supported in oneshot execution mode")}}:{onRepositoryDetected:t=>{e.associateRepository(t.host,t.owner,t.repo,t.url)},onUncommittedChanges:this.onUncommittedChanges.bind(this),onCommitUncommittedChanges:async()=>this.commitCurrentChangesWithAgent(t),onBranchMismatch:this.onBranchMismatch.bind(this)}}async registerWithDaemon(e){const t=this.options.input.taskId,n=await _t(t,{cwd:e,machineId:this.credentials.machineId,pid:process.pid,startedBy:this.options.startedBy||"terminal"});n.error?this.log("warn","DAEMON",`Failed to report session ${t}:`,n.error):this.log("info","DAEMON",`Session ${t} registered`)}createMessageCoordinator(e,t){return this.coordinator=new Ui({workerType:"codex",workClient:e,handlers:{onNormalMessage:async e=>this.convertSDKMessageToCodexInput(e),onBashCommand:async(e,t)=>{await this.executeBashCommand(e)},onMergeRequest:async e=>{await this.executeMergeRequest()},onMergePr:async()=>{await this.executeMergePr()},onNewSession:async()=>{await this.executeNewSession()}},logger:(e,t,n)=>{const s=e;this.log(s,t,n)},idleTimeoutMs:t,onIdleTimeout:()=>this.stopTask("idle")}),this.coordinator}async handleEvent(){if("task-message"===this.options.input.event){const{eventId:e,message:t}=this.options.input.eventData;t&&X(t)&&"user"===t.type&&(await this.coordinator.enqueue(t),e&&this.workClient?.sendEventAck(e))}}async executeMergeRequest(){this.refreshGroupId(),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 oi(this.context.workingDirectory)&&await this.commitCurrentChangesWithAgent();const e=await ri(this.context.workingDirectory),t=this.context.initialCommitHash,n=await fi(this.context.workingDirectory);if(this.log("info","MERGE",`Pushing branch ${n} to remote`),await Ri(this.context.workingDirectory,n,!1,{gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl}),this.log("info","MERGE","Successfully pushed branch to remote"),!t){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 di(this.context.workingDirectory,t,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 s=Di(t);this.log("debug","MERGE",`PR prompt: ${s.substring(0,200)}...`);const a=this.options.input.agentId??"default",i=await to.create("codex",a),o={mode:"work",supportChangeTitle:!1},r=i.runStreamed(s,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,abortController:this.abortController,modeConfig:o,structuredOutputSchema:{type:"json_schema",schema:oo}});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 t=this.filterMessages(e);null!==t&&this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}if(!c)throw new Error("Merge-request did not return a result message");const l=ro(c);await this.createPullRequest(l.title,l.description),this.sendMessage(l.userMessage)}catch(e){const t=e instanceof Error?e.message:String(e);this.log("error","MERGE","Merge-request failed:",e),this.context.workClient.sendSystemErrorMessage(`Merge-request failed: ${t}\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){if(this.refreshGroupId(),!le.isDirectBashAllowed())return this.log("warn","BASH","Direct bash execution is disabled by global settings"),void this.context.workClient.sendSystemErrorMessage("Direct bash execution is disabled by global settings.",{groupId:this.currentGroupId??void 0});this.log("info","BASH",`Executing command: ${e}`);const t=await Ni(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: ${t})`)}async executeMergePr(){this.refreshGroupId(),await qi({workingDirectory:this.context.workingDirectory,workClient:this.context.workClient,repositoryId:this.options.input.repositoryId,gitServerId:this.options.input.gitServerId,gitUrl:this.options.input.gitUrl,logger:this.context.logger,allowInteractive:!this.isOneShotExecution(),askUser:e=>this.askUser(e,{onTimeout:"abort_task"}),commitChanges:()=>this.commitCurrentChangesWithAgent()})}async commitCurrentChangesWithAgent(e){const t=this.options.input.agentId??"default",n=await to.create("codex",t),s=e||this.context?.workingDirectory;if(!s)throw new Error("Working directory is not available for commit generation");this.log("info","MERGE","Generating commit message with agent"),await vo({runner:n,workingDirectory:s,model:this.currentModel||this.options.input.model||void 0,abortController:this.abortController,modeConfig:{mode:"work",supportChangeTitle:!1},schemaTarget:"openai",onStreamMessage:async e=>{const t=this.filterMessages(e);null!==t&&this.getActiveWorkClient().sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}}),this.log("info","MERGE","Committed changes with agent-generated message")}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")}getStructuredOutputSchema(){return xo(this.options.input.outputSchema)}async runCodex(){this.log("info","AGENT",`Starting Codex agent for task ${this.taskId}`),this.currentModel=Ji(this.options.input.model),this.currentModel?this.log("info","AGENT",`Using model: ${this.currentModel}`):this.log("info","AGENT","Using default model from Codex config (model name unavailable)");const e=this.options.input.agentId??"default",t=await to.create("codex",e),n={mode:"work",supportChangeTitle:!1};if(this.isStopping)return void this.log("info","AGENT",`Skipping Codex run for task ${this.taskId} because worker is stopping`);if(this.isOneShotExecution())return void await this.runCodexOneShot(t,n);const s=t.loop({cwd:this.context.workingDirectory,model:this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:n,structuredOutputSchema:this.getStructuredOutputSchema()});(async()=>{try{for(;!this.isStopping;){const e=await this.coordinator.waitForAgentMessage();if(e)this.refreshGroupId(),this.updateAgentRunning(!0),s.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 s.events)this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e);this.log("info","AGENT",`Codex agent finished for task ${this.taskId}`)}async runCodexOneShot(e,t){const n=await this.coordinator.waitForAgentMessage();if(!n)return this.isStopping||this.stopTask("oneshot_complete"),void this.log("info","AGENT",`Codex oneshot finished for task ${this.taskId} without runnable message`);this.updateAgentRunning(!0);try{this.refreshGroupId();const s=e.runStreamed(n,{cwd:this.context.workingDirectory,model:this.currentModel||void 0,agentSessionId:this.threadId??void 0,abortController:this.abortController,modeConfig:t,structuredOutputSchema:this.getStructuredOutputSchema()});for await(const e of s)this.context.logger.debug(`sdk message: ${JSON.stringify(e)}`),await this.handlePrimaryRunnerMessage(e);this.isStopping||this.stopTask("oneshot_complete")}finally{this.log("info","AGENT",`Codex oneshot finished for task ${this.taskId}`)}}async handlePrimaryRunnerMessage(e){if("system"===e.type&&"init"===e.subtype)return this.threadId=e.session_id,this.context.workClient.sendUpdateTaskAgentSessionId(e.session_id),this.context.workClient.sendTaskSlashCommandsUpdate(mo(e.slash_commands??[]),e.session_id),this.log("info","AGENT",`Thread started: ${e.session_id}`),void this.updateAgentRunning(!0);const t=this.filterMessages(e);null!==t&&("result"===e.type?await this.handleSdkResultMessage(t):this.context.workClient.sendTaskEvent(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})),"result"!==e.type?this.updateAgentRunning(!0):this.updateAgentRunning(!1)}filterMessages(e){const t=e,n=t?.message?.content;if(!n||"string"==typeof n)return e;const s=n.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"===t.type&&"tool_result"!==e.type));return 0===s.length?null:(t.message.content=s,t)}sendMessage(e){const t={type:"assistant",message:{id:ie().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:ie().toString()};this.getActiveWorkClient().sendTaskMessage(this.getChatSenderMeta(),t,{groupId:this.currentGroupId??void 0})}async askUser(e,t={}){if(this.isOneShotExecution())throw new Error("ask_user is not supported in oneshot execution mode");const n=this.getActiveWorkClient();return Hi(e,this.askUserAwaiter,{sendAskUser:e=>n.sendAskUser(this.getChatSenderMeta(),e,{groupId:this.currentGroupId??void 0}),sendAskUserResponse:(e,t)=>n.sendAskUserResponse(e,t),onTimeoutMessage:e=>this.sendMessage(e),stopTask:e=>this.stopTask(e)},t)}getActiveWorkClient(){const e=this.context?.workClient??this.workClient;if(!e)throw new Error("[WORKER] WorkerClient not available");return e}resolveTaskAgentName(e){const t=this.options.input.taskAgents??[];return t.find(t=>t.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,rememberSelection:{enabled:!0,defaultValue:!0},options:[{label:"Ignore",description:"Keep changes on current branch and continue without switching"},{label:"Commit",description:"Create a commit with an agent-generated message, 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 t=await this.askUser(e,{onTimeout:"abort_task"}),n=t.answers[0],s=t.rememberAnswers?.[0]??e[0]?.rememberSelection?.defaultValue??!1;return n.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${n}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Ignore:"Ignore",Commit:"Commit",Stash:"Stash",Abort:"Abort"}[n]||"Abort",remember:s}}catch(e){return this.log("warn","GIT",`Failed to get user response for uncommitted changes: ${e}`),{action:"Abort",remember:!1}}}async onBranchMismatch(e){const t=[{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"}],n=[{question:`Branch mismatch detected. Current: ${e.currentBranch}. Expected: ${e.expectedBranch}. How would you like to proceed?`,header:"Git Branch",multiSelect:!1,rememberSelection:{enabled:!0,defaultValue:!0},options:t}];try{const e=await this.askUser(n,{onTimeout:"abort_task"}),t=e.answers[0],s=e.rememberAnswers?.[0]??n[0]?.rememberSelection?.defaultValue??!1;return t.startsWith("other:")?(this.log("info","GIT",`User provided custom input: ${t}, defaulting to Abort`),{action:"Abort",remember:!1}):{action:{Switch:"Switch",Keep:"Keep",Abort:"Abort"}[t]||"Abort",remember:s}}catch(e){return this.log("warn","GIT",`Failed to get user response for branch mismatch: ${e}`),{action:"Abort",remember:!1}}}async createPullRequest(e,t){this.log("info","MERGE",`Creating PR: ${e}`);try{const n=await this.context.workClient.sendMergeRequest(e,t);this.sendMessage(`✅ Pull request created successfully!\nNumber: #${n.pullRequestNumber}\nURL: ${n.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 t=e.message.content;if("string"==typeof t)return t;if(Array.isArray(t)){const e=[],n=le.resolveAttachmentsDir(this.options.input.userId,this.taskId);for(const s of t)if("text"===s.type&&s.text)e.push(s.text);else if("image"===s.type&&s.source&&s.source.url){const t=s.source.url;try{const{filePath:s}=await oa(t,n,!1);this.log("info","IMAGE",`Downloaded image from ${t} to ${s}`),e.push(`Image: ${s}`)}catch(e){this.log("error","IMAGE",`Failed to download image from ${t}:`,e)}}else if("document"===s.type&&s.source&&s.source.url){const t=s.source.url;try{const{filePath:a,mimeType:i,filename:o}=await oa(t,n,!0);this.log("info","DOCUMENT",`Downloaded document from ${t} to ${a}`);const r=s.title||o;e.push(`Document: ${a}\nTitle: ${r}\nType: ${i}`)}catch(e){this.log("error","DOCUMENT",`Failed to download document from ${t}:`,e)}}const s=e.map(e=>e.trim()).filter(Boolean).join("\n\n").trim();if(s)return s}return""}stopTask(e){this.isStopping||(this.isStopping=!0,"oneshot_complete"===e&&(this.exitReason="oneshot_complete",this.log("info","AGENT","One-shot execution completed, stopping task")),"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(),"oneshot_complete"!==e&&this.abortController.abort())}updateAgentRunning(e){this.coordinator?.updateAgentRunning(e)}createWorkerClientConfig(e,t,n){const s=this.options.input.agentId,a=this.options.input.taskAgents?.find(e=>e.id===s)?.name;return{config:{userId:e,taskId:t,chatId:this.options.input.chatId,machineId:this.credentials.machineId,agentId:s,agentName:a,cwd:n,serverUrl:le.serverUrl.replace(/^http/,"ws"),path:"/v1/ws",auth:se(this.credentials.token,this.credentials.machineId,t),dataEncryptionKey:this.dataEncryptionKey,keepAliveConfig:{intervalMs:2e4,event:"worker-alive",payloadGenerator:()=>{const e=this.coordinator?.getStatus(),n="running"===e?.state?"worker-running":"worker-ready";return{eventId:j(),status:n,taskId:t,machineId:this.credentials.machineId,timestamp:Date.now().toString()}}},healthCheckConfig:{enabled:!0,intervalMs:3e4,timeoutMs:5e3},logger:(e,...t)=>(this.context?.logger??this.logger)?.info(`[SOCKET] ${e}`,...t)},handlers:{stopTask:async()=>{this.stopTask("event")},onTaskMessage:async e=>{if(V(e)){const[t,n]=this.askUserAwaiter.entries().next().value||[];return void(t&&n&&(this.askUserAwaiter.delete(t),n(e)))}X(e)&&"user"===e.type&&await this.coordinator.enqueue(e)},onTaskInfoUpdate:async e=>{Li(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,t){this.coordinator&&this.coordinator.stop(),this.log("info","WORKER",`Exiting with reason: ${e} for task ${this.taskId}`),"error"===e&&t?await this.context.workClient.sendErrorMessageAndExit(t):(this.context.workClient.sendWorkerExit(e),await this.context.workClient.disconnect()),this.historyDb&&this.historyDb.close()}createLogger(e){const{createLogger:t}=Io;return t(e)}log(e,t,n,...s){const a=this.context?.logger??this.logger;a&&a[e](`[${t}] ${n}`,...s)}get taskId(){return this.options.input.taskId}getCurrentModel(){return this.currentModel||"unknown"}async handleSdkResultMessage(e){let t,n;try{const e=await this.workspace.prepareResultArtifacts({onPatchError:e=>{this.log("warn","GIT","Failed to write patch diff for result:",e)}});t=e.artifacts,n=e.artifactVersion}catch(e){this.log("warn","GIT","Failed to prepare git artifacts for result:",e)}if(this.context.workClient.sendTaskMessage(this.getChatSenderMeta(),e,{...t?{artifacts:t}:{},groupId:this.currentGroupId??void 0}),n)try{await Oi(this.options.input.userId,this.taskId,n)}catch(e){this.log("warn","GIT","Failed to mark artifact version as sent:",e)}}}function To(){const e=process.env.AGENTRIX_CLAUDE_PATH?.trim();if(!e)return;if(e.includes("/")||e.includes("\\")||e.startsWith(".")){const t=b.isAbsolute(e)?e:b.resolve(e);return o.existsSync(t)?t:void 0}const t="win32"===process.platform?"where":"which",n=Ve(t,[e],{encoding:"utf-8"});return 0===n.status?n.stdout.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0):void 0}function Eo(e){const t=e.map(e=>e.toLowerCase().trim().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean);return[...new Set(t)].slice(0,8)}function Ao(e,t=""){const n=o.readdirSync(e,{withFileTypes:!0}),s=[];for(const a of n){const n=t?`${t}/${a.name}`:a.name;"node_modules"!==a.name&&".git"!==a.name&&(a.isDirectory()?s.push(...Ao(b.join(e,a.name),n)):s.push(n))}return s}async function Co(e,t,n){const s=Ao(e).map(e=>` - ${e}`).join("\n");return new Promise((a,i)=>{let o=!1,r=null;const c=e=>{o||(o=!0,clearTimeout(p),a(e))},l=e=>{o||(o=!0,clearTimeout(p),i(e))},p=setTimeout(()=>{c({approved:!1,reasons:["Review timed out after 10 minutes"],tags:[]})},6e5),d=(u=e=>{r=e,c(e)},et("hive_publish_review","Submit your security review decision for this Hive publish request. You MUST call this tool exactly once after reviewing all source files.",{approved:Fe.boolean().describe("true if the code passes security review, false if it must be rejected"),reasons:Fe.array(Fe.string()).describe("If rejected: list each specific issue found. If approved: briefly state what was checked."),tags:Fe.array(Fe.string()).describe("3-8 concise marketplace discovery tags describing the agent or skill capability. Use lowercase kebab-case.")},async e=>(u({approved:e.approved,reasons:e.reasons,tags:Eo(e.tags)}),{content:[{type:"text",text:"Review decision recorded."}]})));var u;const m=Qe({name:"hive_review",version:"1.0.0",tools:[d]}),g=[`Review the ${n} "${t}" for security issues before publishing to Hive.`,"",`Source directory: ${e}`,"","Files to review:",s,"","Read each file, then call mcp__hive_review__hive_publish_review with your decision."].join("\n"),h=Ze({prompt:g,options:{systemPrompt:"You are a security reviewer for the Agentrix Hive marketplace.\nYour job is to review agent/skill source code before it is published to the public repository.\n\nYou MUST check for:\n1. **Hardcoded secrets**: API keys, tokens, passwords, private keys, credentials in any file\n2. **PII exposure**: emails, phone numbers, physical addresses, names of real people\n3. **Data exfiltration**: suspicious network requests, unauthorized file uploads, sending user data to external servers\n4. **Malicious code**: eval/exec of untrusted input, shell injection, code that modifies files outside workspace\n5. **Dependency risks**: suspicious or known-malicious packages, typo-squatting package names\n6. **Permission abuse**: code that requests excessive permissions, reads sensitive system files, or accesses other users' data\n\nProcess:\n1. Read EVERY source file in the directory using the Read tool\n2. Analyze each file for the issues listed above\n3. Assign marketplace discovery tags for the source. Tags should describe what the agent/skill does, its domain, and useful capability filters.\n4. Call mcp__hive_review__hive_publish_review with your decision and tags.\n\nTag rules:\n- Provide 3-8 tags.\n- Use lowercase kebab-case, for example: web-design, code-review, react, testing, documentation.\n- Prefer functional/domain tags over generic labels.\n\nBe strict but fair: reject if ANY security issue is found. Approve if the code is clean.",permissionMode:"bypassPermissions",settingSources:["user","project","local"],maxTurns:30,cwd:e,mcpServers:{hive_review:m},pathToClaudeCodeExecutable:To(),stderr:e=>{const t=String(e).trim();t&&console.error(`[HiveReview] Claude stderr: ${t}`)}}});(async()=>{try{for await(const e of h)if("result"===e.type&&e.is_error&&!r){const t=e.result;return void l(new Error(`Claude security review failed: ${t||"unknown Claude Code error"}`))}r||l(new Error("Claude security review finished without submitting a review decision"))}catch(e){l(e)}})()})}const $o=mt(Ye);function _o(e,t,n){const s=le.serverUrl.replace(/^http/,"ws");return Ae(s,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}async function Po(e,...t){const{stdout:n}=await $o("git",t,{cwd:e});return n.trim()}function Ro(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"skill"}const Mo=mt(Ye);function Oo(e,t,n){const s=le.serverUrl.replace(/^http/,"ws");return Ae(s,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}const Do=["claude","codex","deployment","companion","hive-publish","hive-install"],No={claude:{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i=le.readTaskInput(n,s),o=i.dataEncryptionKey?N(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:a,input:i,dataEncryptionKey:o};await async function(e,t){const n=Ai(t.input),s=await ko.calculateFinalCwd(n),a=new wo(e,t,s);await a.start()}(e,r)}},codex:{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i=le.readTaskInput(n,s),o=i.dataEncryptionKey?N(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:a,input:i,dataEncryptionKey:o};await async function(e,t){const n=new So(e,t);await n.start()}(e,r)}},deployment:{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i={input:le.readTaskInput(n,s)};await async function(e,t){const n=t.input,{taskId:s,sourcePath:a,targetAgentId:i,userId:r,name:c,avatar:l,isSystemAgent:p,supportLocal:d}=n;let u=null;try{if(console.log(`[Deployment] Starting deployment worker for task ${s}`),!o.existsSync(a))throw new Error(`Source path not found: ${a}`);const t=b.join(le.agentrixAgentsHomeDir,i);if(o.existsSync(t))throw new Error(`Target agent directory already exists: ${t}`);console.log(`[Deployment] Copying from ${a} to ${t}`),await yo(a,t),console.log("[Deployment] Deployment completed successfully"),u=function(e,t,n){const s=le.serverUrl.replace(/^http/,"ws");return Ae(s,{path:"/v1/ws",transports:["websocket"],auth:{token:e.token,clientType:"worker",machineId:e.machineId,taskId:n}})}(e,0,s),await new Promise((e,t)=>{const n=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);u.on("connect",()=>{clearTimeout(n),console.log("[Deployment] Connected to server"),u.emit("deploy-agent-complete",{eventId:j(),taskId:s,targetAgentId:i,success:!0,name:c,avatar:l,isSystemAgent:p,supportLocal:d}),console.log("[Deployment] Sent deploy-agent-complete event"),setTimeout(()=>{e()},1e3)}),u.on("connect_error",e=>{clearTimeout(n),t(e)})})}catch(e){throw console.error("[Deployment] Deployment failed:",e),u&&u.connected&&(u.emit("deploy-agent-complete",{eventId:j(),taskId:s,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)}}(e,i)}},"hive-publish":{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i={input:le.readTaskInput(n,s)};await async function(e,t){const n=t.input,{taskId:s,userId:a,sourceDir:i,gitUrl:r,version:c}=n;let l,p,{repoDir:d,name:u}=n,m=n.displayName,g=n.description,h=n.readme,f=null,v=null;try{if(n.environmentVariables)for(const[e,t]of Object.entries(n.environmentVariables))null!=t&&(process.env[e]=String(t));if(console.log(`[HivePublish] Starting for task ${s}, name=${u}`),function(e,t){if(!o.existsSync(e))throw new Error(`Source directory not found: ${e}`);if(!o.statSync(e).isDirectory())throw new Error(`Source path is not a directory: ${e}`);if("skill"===t&&!o.existsSync(b.join(e,"SKILL.md")))throw new Error(`Skill directory must contain SKILL.md: ${e}`)}(i,n.type),"skill"===n.type){const e=function(e){const t=b.join(e,"SKILL.md"),n=o.readFileSync(t,"utf-8"),s=n.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!s)throw new Error("SKILL.md must start with YAML frontmatter containing name and description");const a=s[1],i=new Map;for(const e of a.split(/\r?\n/)){const t=e.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);t&&i.set(t[1],t[2].replace(/^["']|["']$/g,"").trim())}const r=i.get("name"),c=i.get("description");if(!r)throw new Error("SKILL.md frontmatter must include name");if(!c)throw new Error("SKILL.md frontmatter must include description");return{name:Ro(r),displayName:r,description:c,readme:n,repoDirName:Ro(r)}}(i);u=e.name,m=e.displayName,g=e.description,h=e.readme,d=b.posix.join(d,e.repoDirName),console.log(`[HivePublish] Parsed skill metadata name=${u}, displayName=${m}`)}v=b.join(le.agentrixHomeDir,"tmp","hive-publish",s),o.mkdirSync(v,{recursive:!0}),console.log("[HivePublish] Cloning hive repo..."),await Po(v,"clone","--depth","1",r,".");const t=b.join(v,d);if(o.mkdirSync(b.dirname(t),{recursive:!0}),"skill"===n.type&&o.existsSync(t))throw new Error(`Skill already exists in Hive repository: ${d}`);o.existsSync(t)&&o.rmSync(t,{recursive:!0,force:!0}),console.log(`[HivePublish] Copying ${i} → ${d}`),await yo(i,t),await Po(v,"add",".");const a=await async function(e){try{return await $o("git",["diff","--cached","--quiet"],{cwd:e}),!1}catch(e){if("number"==typeof e?.code&&1===e.code)return!0;throw e}}(v);if(a){console.log("[HivePublish] Running Claude security review...");const e=await Co(i,u,n.type);if(l=e.reasons,p=e.tags,!e.approved)throw new Error(`Security review rejected: ${e.reasons.join("; ")}`);console.log("[HivePublish] Security review passed");const t=`publish: ${d} v${c}`;await Po(v,"commit","-m",t),console.log("[HivePublish] Pushing to remote..."),await Po(v,"push")}else console.log("[HivePublish] No git changes to publish; using existing HEAD");const x=await Po(v,"rev-parse","HEAD");console.log(`[HivePublish] Push succeeded, commit=${x}`),f=_o(e,0,s),await new Promise((e,t)=>{const n=setTimeout(()=>t(new Error("WebSocket connection timeout")),1e4);f.on("connect",()=>{clearTimeout(n),f.emit("hive-publish-complete",{eventId:j(),taskId:s,success:!0,gitCommitHash:x,hasChanges:a,tags:p,name:u,displayName:m,description:g,readme:h,repoDir:d}),console.log("[HivePublish] Sent hive-publish-complete (success)"),setTimeout(e,1e3)}),f.on("connect_error",e=>{clearTimeout(n),t(e)})})}catch(t){console.error("[HivePublish] Failed:",t);try{f=f??_o(e,0,s),await new Promise(e=>{const n=setTimeout(e,5e3),a=()=>{f.emit("hive-publish-complete",{eventId:j(),taskId:s,success:!1,error:t instanceof Error?t.message:String(t),reviewReasons:l}),clearTimeout(n),setTimeout(e,1e3)};f.connected?a():(f.on("connect",a),f.on("connect_error",()=>{clearTimeout(n),e()}))})}catch{console.error("[HivePublish] Failed to send error event")}throw t}finally{if(f&&f.disconnect(),v&&o.existsSync(v))try{o.rmSync(v,{recursive:!0,force:!0})}catch{}process.exit(0)}}(e,i)}},"hive-install":{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i={input:le.readTaskInput(n,s)};await async function(e,t){const n=t.input,{taskId:s,userId:a,sourceRepoDir:i,gitUrl:r,name:c,sourceType:l}=n,p=n.installDir??n.draftAgentDir;let d=null,u=null;try{console.log(`[HiveInstall] Starting for task ${s}, name=${c}`),u=b.join(le.agentrixHomeDir,"tmp","hive-install",s),o.mkdirSync(u,{recursive:!0}),console.log("[HiveInstall] Cloning hive repo..."),await async function(e,...t){const{stdout:n}=await Mo("git",t,{cwd:e});return n.trim()}(u,"clone","--depth","1",r,".");const t=b.join(u,i);if(!o.existsSync(t))throw new Error(`Source directory not found in hive repo: ${i}`);if("skill"===l&&!o.existsSync(b.join(t,"SKILL.md")))throw new Error(`Skill directory must contain SKILL.md: ${i}`);const n=(m=p).startsWith("~/")?b.join(process.env.HOME||"",m.slice(2)):b.isAbsolute(m)?m:b.join(le.agentrixHomeDir,m);if(o.existsSync(n))throw new Error(`Target install directory already exists: ${n}`);o.mkdirSync(n,{recursive:!0}),console.log(`[HiveInstall] Copying ${i} → ${n}`),await yo(t,n);const a=b.join(n,".git");o.existsSync(a)&&(o.rmSync(a,{recursive:!0,force:!0}),console.log("[HiveInstall] Removed .git from installed directory")),console.log("[HiveInstall] Install completed successfully"),d=Oo(e,0,s),await new Promise((e,t)=>{const a=setTimeout(()=>t(new Error("WebSocket connection timeout")),1e4);d.on("connect",()=>{clearTimeout(a),d.emit("hive-install-complete",{eventId:j(),taskId:s,success:!0,agentDir:n}),console.log("[HiveInstall] Sent hive-install-complete (success)"),setTimeout(e,1e3)}),d.on("connect_error",e=>{clearTimeout(a),t(e)})})}catch(t){console.error("[HiveInstall] Failed:",t);try{d=d??Oo(e,0,s),await new Promise(e=>{const n=setTimeout(e,5e3),a=()=>{d.emit("hive-install-complete",{eventId:j(),taskId:s,success:!1,error:t instanceof Error?t.message:String(t)}),clearTimeout(n),setTimeout(e,1e3)};d.connected?a():(d.on("connect",a),d.on("connect_error",()=>{clearTimeout(n),e()}))})}catch{console.error("[HiveInstall] Failed to send error event")}throw t}finally{if(d&&d.disconnect(),u&&o.existsSync(u))try{o.rmSync(u,{recursive:!0,force:!0})}catch{}process.exit(0)}var m}(e,i)}},companion:{async run({credentials:e,startedBy:t,userId:n,taskId:s,idleTimeoutSecond:a}){const i=le.readTaskInput(n,s),o=i.dataEncryptionKey?N(i.dataEncryptionKey):null;if(o&&32!==o.length)throw new Error("Invalid dataEncryptionKey: expected decrypted 32-byte key");const r={startedBy:t,idleTimeoutSecond:a,input:i,dataEncryptionKey:o};await async function(e,t){const{agentDir:n,homeDir:s}=await qs();t.input.agentDir=n,process.env.AGENTRIX_COMPANION_HOME=s;const a=Ai(t.input),i=await ko.calculateFinalCwd(a),o=new wo(e,t,i);await o.start()}(e,r)}}};async function Uo(){const e=function(){try{const e=Se(de(),"package.json"),t=JSON.parse(ye(e,"utf-8"));if("string"==typeof t.version&&t.version.trim().length>0)return t.version}catch{}return"0.0.0"}();try{const t=qe("npm view @agentrix/cli version",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim();return{hasUpgrade:function(e,t){const n=e.split(".").map(Number),s=t.split(".").map(Number);for(let e=0;e<Math.max(n.length,s.length);e++){const t=n[e]||0,a=s[e]||0;if(t>a)return 1;if(t<a)return-1}return 0}(t,e)>0,currentVersion:e,latestVersion:t}}catch(t){return{hasUpgrade:!1,currentVersion:e,latestVersion:null}}}function jo(){return"true"===process.env.AGENTRIX_DISABLE_AUTO_UPGRADE}async function qo(e){try{const{execSync:t}=await import("child_process");return console.log(""),e||(console.log(P.blue("🔄 Checking for upgrades...")),e=await Uo()),e.hasUpgrade?(console.log(P.blue(`🔄 Upgrading from ${e.currentVersion} to ${e.latestVersion}...`)),t("npm install -g @agentrix/cli@latest",{stdio:"inherit"}),console.log(P.green("✓ Upgrade complete")),console.log(""),!0):(console.log(P.green("✓ Already on latest version")),console.log(""),!0)}catch(e){return console.log(""),console.log(P.yellow("⚠️ Auto-upgrade failed")),console.log(P.dim(" You can upgrade manually with: npm install -g @agentrix/cli@latest")),console.log(""),!1}}async function Lo(e,t){const n=`${le.serverUrl}/v1/agents/${encodeURIComponent(e)}/git-url`,s=await fetch(n,{headers:{Authorization:`Bearer ${t.token}`}});return s.ok?s.json():null}function Ho(e){try{const t=c(w(e,"agent.json"),"utf-8"),n=JSON.parse(t);return"string"==typeof n.version?n.version:null}catch{return null}}function Go(e,t){const n=e=>e.split(".").map(e=>parseInt(e,10)||0),s=n(e),a=n(t);for(let e=0;e<Math.max(s.length,a.length);e++){const t=s[e]??0,n=a[e]??0;if(t>n)return!0;if(t<n)return!1}return!1}async function Wo(e){const t=le.agentrixAgentsHomeDir;if(!r(t))return;let n;try{n=m(t).filter(e=>l(w(t,e)).isDirectory())}catch{return}for(const s of n){if("companion"===s||s.startsWith("draftagent-")||s.includes("."))continue;const n=w(t,s),a=w(n,"upgrade");if(r(a))continue;const i=Ho(n);pe.info(`[AGENT UPDATE] Checking ${s} (local version: ${i??"unknown"})`);try{const t=await Lo(s,e);if(!t||!t.gitUrl){pe.info(`[AGENT UPDATE] No git repo for ${s}, skipping`);continue}const n=`${a}.tmp-${Date.now()}`;try{const e=["git","clone","--depth=1","--branch",t.branch,t.gitUrl,n];Xe(e.join(" "),{stdio:"pipe",timeout:12e4});const o=t.subDir?w(n,t.subDir):n;if(t.subDir&&!r(o))throw new Error(`subDir "${t.subDir}" not found in cloned repo`);const c=Ho(o);if(!c||i&&!Go(c,i)){pe.info(`[AGENT UPDATE] ${s} up to date (local: ${i??"unknown"}, remote: ${c??"unknown"})`),u(n,{recursive:!0,force:!0});continue}pe.info(`[AGENT UPDATE] Update available for ${s}: ${i??"unknown"} → ${c}`),t.subDir?(d(o,a),u(n,{recursive:!0,force:!0})):d(n,a),pe.info(`[AGENT UPDATE] Staged upgrade for ${s}`)}catch(e){throw r(n)&&u(n,{recursive:!0,force:!0}),e}}catch(e){pe.warn(`[AGENT UPDATE] Check failed for ${s}: ${e}`)}}}function Fo(){const e=le.getStatePaths();return Ie.join(Ie.dirname(e.daemonStateFile),"upgrade-daemon.state.json")}function Bo(){try{const e=Fo();if(!xe.existsSync(e))return null;const t=xe.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return null}}function zo(e){try{const t=Fo();if(xe.existsSync(t)){if("number"==typeof e){const t=Bo();if(!t||t.pid!==e)return}xe.unlinkSync(t)}}catch{}}function Ko(e){try{return process.kill(e,0),!0}catch{return!1}}function Vo(){const e=Bo();return!(!e||!Ko(e.pid)&&(zo(),1))}function Xo(){const e=Bo();if(e)try{Ko(e.pid)&&process.kill(e.pid,"SIGTERM")}catch{}finally{zo()}}async function Yo(){if(jo())return"no-upgrade";const e=await Uo();if(e.hasUpgrade&&await qo(e))return await Ot(),await new Promise(e=>setTimeout(e,1e3)),Zs(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref(),"upgraded";try{const e=await le.readCredentials();e&&await Wo(e)}catch{}return"no-upgrade"}var Jo=Object.freeze({__proto__:null,isUpgradeDaemonRunning:Vo,startUpgradeDaemon:async function(){await async function(){!function(e){const t=Fo();xe.writeFileSync(t,JSON.stringify(e,null,2))}({pid:process.pid,startedAt:(new Date).toISOString()}),process.on("SIGTERM",()=>{zo(process.pid),process.exit(0)}),process.on("SIGINT",()=>{zo(process.pid),process.exit(0)});try{"upgraded"===await Yo()&&(Zs(["upgrade-daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref(),process.exit(0))}catch(e){}for(;;){await new Promise(e=>setTimeout(e,216e5));try{"upgraded"===await Yo()&&(Zs(["upgrade-daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref(),process.exit(0))}catch(e){}}}()},stopUpgradeDaemon:Xo});function Qo(e,t){const n=e.trim();if(!n)throw new Error(`${t} is required`);let s;try{s=new URL(n)}catch{throw new Error(`${t} must be a valid URL`)}if("http:"!==s.protocol&&"https:"!==s.protocol)throw new Error(`${t} must use http or https`);return s.toString().replace(/\/+$/,"")}async function Zo(e,t){if(!bt.isTTY){if(void 0!==t)return t;throw new Error(`${e} is required in non-interactive mode`)}const n=kt({input:bt,output:wt});try{const s=t?` (${t})`:"";return(await n.question(`${e}${s}: `)).trim()||t||""}finally{n.close()}}async function er(){const e=await Zt();if(!e)throw new Error("No Agentrix auth secret found. Run `agentrix start` and complete machine binding first.");return e}function tr(e){return"string"==typeof e&&e.trim()?e.trim():void 0}async function nr(e){const t=await er(),n=Qo(tr(e["base-url"])??await Zo("GitLab base URL"),"baseUrl"),s=Qo(tr(e["api-url"])??await Zo("GitLab API URL",function(e){return`${Qo(e,"baseUrl")}/api/v4`}(n)),"apiUrl"),a=(tr(e["pat-file"])?function(e){if("-"===e)return c(0,"utf8").trim();if(!r(e))throw new Error(`File not found: ${e}`);return c(e,"utf8").trim()}(tr(e["pat-file"])):void 0)??await async function(e){return bt.isTTY&&wt.isTTY&&"function"==typeof bt.setRawMode?new Promise((t,n)=>{let s="";const a=()=>{bt.setRawMode(!1),bt.pause(),bt.off("data",i)},i=e=>{const i=e.toString("utf8");return""===i?(a(),wt.write("\n"),void n(new Error("Interrupted"))):"\r"===i||"\n"===i?(a(),wt.write("\n"),void t(s.trim())):void(""!==i&&"\b"!==i?s+=i:s=s.slice(0,-1))};wt.write(`${e}: `),bt.setRawMode(!0),bt.resume(),bt.on("data",i)}):Zo(e)}("GitLab PAT");if(!a)throw new Error("GitLab PAT is required");let i;const o=await async function(e,t){const{result:n,user:s}=await _e(e,t);return{valid:n.valid,username:n.username,scopes:n.scopes,meta:n.valid&&s?{username:s.username,email:s.email||"",lastValidatedAt:(new Date).toISOString(),expiresAt:n.expiresAt}:void 0}}(s,a);if(!o.valid)throw new Error(`PAT validation failed for ${s}/user`);i=o.meta;const l=await async function(e){const t=await async function(e){return await $t("/git-server/register",e)}({name:new URL(e.baseUrl).hostname,baseUrl:e.baseUrl,apiUrl:e.apiUrl});if(t.error||!t.gitServer)throw new Error(`Backend Git server registration failed: ${t.error||"Daemon did not return a registered Git server"}`);return{id:t.gitServer.id,baseUrl:t.gitServer.baseUrl,apiUrl:t.gitServer.apiUrl}}({baseUrl:n,apiUrl:s});var p,d;i&&(p=l.id,d=i,Qt.savePatMeta(p,d)),function(e,t){Qt.saveGitServerConfig(e,t)}(l.id,{baseUrl:l.baseUrl,apiUrl:l.apiUrl}),function(e,t,n){Qt.savePat(e,t,n)}(l.id,a,t);const u=function(e,t){return Qt.ensureGitLabWebhookSecret(e,t)}(l.id,t),m=await async function(e){return await $t("/git-server/complete",{gitServerId:e})}(l.id);if(m.error||!m.success)throw new Error(`Backend Git server completion failed: ${m.error||"Daemon did not confirm completion"}`);console.log(JSON.stringify({id:l.id,type:"gitlab",baseUrl:l.baseUrl,apiUrl:l.apiUrl,webhookEndpointPath:Ne(l.id),webhookUrl:De(l.id,await le.readDaemonState()),backendRegistered:!0,patConfigured:!0,patMeta:nn(l.id),webhookSecret:u},null,2))}function sr(e){console.error(P.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}function ar(){return process.env.OPENAPI_BASE_URL||process.env.AGENTRIX_OPENAPI_BASE_URL||le.serverUrl}function ir(e){return(process.env.PATH||"").split(":").filter(Boolean).some(t=>{try{return v(w(t,e),x.X_OK),!0}catch{return!1}})}function or(e,t,n){return new Promise((s,a)=>{const i=Je(e,t,{stdio:"inherit",shell:n?.shell||!1,env:process.env});i.on("error",a),i.on("close",t=>{0===t?s():a(new Error(`${e} exited with code ${t}`))})})}async function rr(e){try{return await ft(e),!0}catch{return!1}}function cr(e){return e.filter(e=>e.required&&!e.installed)}async function lr(e,t){ir(e)?console.log(P.green(`✓ ${e} is installed`)):ir("npm")?(console.log(P.blue(`Installing ${e} with npm...`)),await or("npm",["install","-g",t])):console.log(P.yellow(`npm is not available. Install ${t} manually.`))}async function pr(e,t,n){const s=n?` (${n})`:"";return(await e.question(`${t}${s}: `)).trim()||n||""}async function dr(e,t,n=!0){const s=n?"Y/n":"y/N",a=(await e.question(`${t} (${s}): `)).trim().toLowerCase();return a?"y"===a||"yes"===a:n}async function ur(e,t,n,s){for(console.log(t),n.forEach((e,t)=>{const n=e.value===s?" default":"";console.log(` ${t+1}. ${e.label}${n}`)});;){const t=(await e.question("Select: ")).trim();if(!t)return s;const a=Number.parseInt(t,10);if(!Number.isNaN(a)&&n[a-1])return n[a-1].value;const i=n.find(e=>e.value===t);if(i)return i.value;console.log(P.yellow("Invalid selection"))}}function mr(e){return JSON.stringify(e)}async function gr(e,t){const n=await async function(e){try{return(await ce.get(`${le.serverUrl}/v1/openapi-config`,{headers:{Authorization:`Bearer ${e.token}`},timeout:1e4})).data.baseUrl||ar()}catch(e){const t=e instanceof Error?e.message:"unknown error";return console.log(P.yellow(`Could not fetch Agentrix API URL from server, using fallback: ${t}`)),ar()}}(t),s=kt({input:bt,output:wt});try{await async function(e,t,n){const s=w(le.claudeConfigDir,"settings.json");if(!t&&await rr(s)&&!await dr(e,`Claude config already exists at ${s}. Overwrite`,!1))return void console.log(P.gray("Skipped Claude config"));const a=await ur(e,"Configure Claude provider",[{value:"agentrix",label:"Agentrix API"},{value:"official",label:"Anthropic official API"},{value:"proxy",label:"Custom Anthropic-compatible proxy"},{value:"skip",label:"Skip Claude config"}],"agentrix");if("skip"===a)return void console.log(P.gray("Skipped Claude config"));const i={};if("official"===a)i.ANTHROPIC_API_KEY=await pr(e,"Anthropic API key");else if("agentrix"===a)i.ANTHROPIC_BASE_URL=n,i.ANTHROPIC_AUTH_TOKEN=await pr(e,"Agentrix API key for Claude");else{const t=await pr(e,"Anthropic-compatible base URL");i.ANTHROPIC_BASE_URL=t,i.ANTHROPIC_AUTH_TOKEN=await pr(e,"Anthropic auth token")}const o=await pr(e,"Claude primary model","claude-sonnet-4-6"),r=await pr(e,"Claude fast model","claude-haiku-4-5"),c=await pr(e,"Claude subagent model",o||"claude-sonnet-4-6");i.ANTHROPIC_MODEL=o,i.CLAUDE_CODE_SUBAGENT_MODEL=c,i.ANTHROPIC_SMALL_FAST_MODEL=r,i.ANTHROPIC_DEFAULT_OPUS_MODEL="claude-opus-4-6",i.ANTHROPIC_DEFAULT_SONNET_MODEL="claude-sonnet-4-6",i.ANTHROPIC_DEFAULT_HAIKU_MODEL="claude-haiku-4-5",await gt(le.claudeConfigDir,{recursive:!0}),await ht(s,JSON.stringify({env:i,model:o},null,2),"utf-8"),console.log(P.green(`✓ Wrote Claude config: ${s}`))}(s,e,n),await async function(e,t,n){const s=w(le.codexHomeDir,"config.toml");if(!t&&await rr(s)&&!await dr(e,`Codex config already exists at ${s}. Overwrite`,!1))return void console.log(P.gray("Skipped Codex config"));const a=await ur(e,"Configure Codex provider",[{value:"agentrix",label:"Agentrix API"},{value:"openai",label:"OpenAI official API"},{value:"custom",label:"OpenAI-compatible custom API"},{value:"skip",label:"Skip Codex config"}],"agentrix");if("skip"===a)return void console.log(P.gray("Skipped Codex config"));const i=await pr(e,"Codex model","gpt-5.5"),o=await ur(e,"Codex API wire format",[{value:"responses",label:"Responses API"},{value:"chat",label:"Chat Completions API"}],"agentrix"===a?"responses":"chat"),r={};let c,l;"agentrix"===a?(c=n,l="AGENTRIX_API_KEY",r[l]=await pr(e,"Agentrix API key for Codex")):"openai"===a?(l="OPENAI_API_KEY",r[l]=await pr(e,"OpenAI API key")):(c=await pr(e,"Custom OpenAI-compatible base URL"),l="CUSTOM_API_KEY",r[l]=await pr(e,"Custom API key")),await gt(le.codexHomeDir,{recursive:!0}),await ht(s,function(e){const t=e.provider,n=[`model = ${mr(e.model)}`,`model_provider = ${mr(t)}`,'approval_policy = "never"',"","[sandbox_workspace_write]","writable_roots = []","network_access = true","exclude_tmpdir_env_var = false","","[features]","hide_agent_reasoning = false","show_raw_agent_reasoning = false",'file_opener = "vscode"',"",`[model_providers.${t}]`,`name = ${mr("agentrix"===t?"Agentrix":"openai"===t?"Openai":"Custom")}`,`wire_api = ${mr(e.wireApi)}`];if(e.baseUrl){const s="agentrix"===t?e.baseUrl.replace(/\/+$/,"")+"/v1":e.baseUrl;n.push(`base_url = ${mr(s)}`)}return e.envKey&&n.push(`env_key = ${mr(e.envKey)}`),`${n.join("\n")}\n`}({provider:a,baseUrl:c||void 0,envKey:l,model:i,wireApi:o}),"utf-8"),function(e){const t=le.readOrInitSettings({sandbox:le.getSandboxSettings(),daemonEnv:{enabled:!1,variables:{}},daemonControl:{allowLanAccess:!1},allowDirectBash:!0}),n=t.daemonEnv||{enabled:!1,variables:{}},s={...n.variables||{},...e};le.writeSettings({...t,daemonEnv:{...n,enabled:!0,variables:s}});for(const[t,n]of Object.entries(e))process.env[t]=n}(r),console.log(P.green(`✓ Wrote Codex config: ${s}`)),console.log(P.green(`✓ Wrote Codex env vars to ${le.getStatePaths().settingsFile}`))}(s,e,n)}finally{s.close()}}async function hr(e={}){console.log(P.bold("\nAgentrix CLI initialization\n")),e.skipDeps||await async function(){const e=Nn(),t=[...cr(e.cli.filter(e=>"claude"!==e.name)),...cr(e.sandbox)];"linux"!==process.platform||ir("rg")||t.push({name:"ripgrep",installed:!1,required:!0,description:"Fast code search tool",installCommand:"sudo apt install ripgrep"}),await async function(e){if(0===e.length)return void console.log(P.green("✓ System dependencies are installed"));if("linux"!==process.platform){console.log(P.yellow("Automatic dependency installation is currently only supported on Linux."));for(const t of e)console.log(P.yellow(`- ${t.name}: ${t.installCommand||"install manually"}`));return}const t=[{name:"apt-get",installCommand:e=>["sudo","apt-get","update","&&","sudo","apt-get","install","-y",...e],packageNames:{git:"git",bubblewrap:"bubblewrap",socat:"socat",ripgrep:"ripgrep"}},{name:"dnf",installCommand:e=>["sudo","dnf","install","-y",...e],packageNames:{git:"git",bubblewrap:"bubblewrap",socat:"socat",ripgrep:"ripgrep"}},{name:"yum",installCommand:e=>["sudo","yum","install","-y",...e],packageNames:{git:"git",bubblewrap:"bubblewrap",socat:"socat",ripgrep:"ripgrep"}},{name:"pacman",installCommand:e=>["sudo","pacman","-S","--needed","--noconfirm",...e],packageNames:{git:"git",bubblewrap:"bubblewrap",socat:"socat",ripgrep:"ripgrep"}}].find(e=>ir(e.name))||null;if(!t){console.log(P.yellow("No supported package manager found. Install these dependencies manually:"));for(const t of e)console.log(P.yellow(`- ${t.name}: ${t.installCommand||"install manually"}`));return}const n=e.map(e=>t.packageNames[e.name]).filter(e=>Boolean(e));if(0===n.length)return;console.log(P.blue(`Installing system dependencies with ${t.name}: ${n.join(", ")}`));const s=t.installCommand(n);"apt-get"===t.name?await or(s.join(" "),[],{shell:!0}):await or(s[0],s.slice(1))}(t),await lr("claude","@anthropic-ai/claude-code@latest"),await lr("codex","@openai/codex@latest");const n=Un();if(!n.ok)throw new Error(`Missing critical dependencies after installation: ${n.missing.join(", ")}`)}();const t=await jt();await gr(Boolean(e.force),t),e.skipDaemon||await async function(){if(await Rt())console.log(P.green("✓ Daemon is already running"));else{console.log(P.blue("Starting Agentrix daemon...")),Zs(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();for(let e=0;e<80;e++)if(await new Promise(e=>setTimeout(e,250)),await Pt())return void console.log(P.green("✓ Daemon started successfully"));console.log(P.yellow("Daemon may still be starting. Run `agentrix status` to check."))}}(),console.log(P.green("\n✓ Agentrix CLI initialization complete"))}const fr=$(_(process.argv)).scriptName("agentrix").version(ue.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");le.getStatePaths,fr.command("upgrade","Upgrade CLI to the latest version",{},async e=>{console.log(P.dim(`Current version: ${ue.version}`));const t=await Pt();await qo()||process.exit(1);try{const e=await le.readCredentials();e&&(console.log(P.dim("Checking agent updates...")),await Wo(e))}catch{}if(t){console.log(P.blue("Restarting daemon...")),await Ot(),await new Promise(e=>setTimeout(e,1e3)),Zs(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();let e=!1;for(let t=0;t<50;t++)if(await new Promise(e=>setTimeout(e,100)),await Pt()){e=!0;break}e?console.log(P.green("✓ Daemon restarted successfully")):console.log(P.yellow("⚠️ Daemon may still be starting. Run 'agentrix status' to check."))}try{const{version:e}=await import("./logger-GnFTqOqO.mjs").then(function(e){return e._});console.log(P.green(`\n✓ Now running version: ${e}`))}catch{console.log(P.dim("\nRun 'agentrix --version' to see the new version"))}process.exit(0)}),fr.command("doctor","System diagnostics & troubleshooting",{},async e=>{await qn(),process.exit(0)}),fr.command("logout","Logout from Agentrix",{},async e=>{try{await async function(){if(!await le.readCredentials())return void console.log(P.yellow("Not currently authenticated"));console.log(P.blue("This will log you out of Agentrix")),console.log(P.yellow("⚠️ You will need to re-authenticate to use Agentrix again"));const e=fe({input:process.stdin,output:process.stdout}),t=await new Promise(t=>{e.question(P.yellow("Are you sure you want to log out? (y/N): "),t)});if(e.close(),"y"===t.toLowerCase()||"yes"===t.toLowerCase())try{try{await Ot(),console.log(P.gray("Stopped daemon"))}catch{}await le.clearCredentials(),console.log(P.gray("Removed credentials")),console.log(P.green("✓ Successfully logged out"))}catch(e){throw new Error(`Failed to logout: ${e instanceof Error?e.message:"Unknown error"}`)}else console.log(P.blue("Logout cancelled"))}()}catch(e){console.error(P.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}process.exit(0)}),fr.command("stop","Stop the daemon",{},async e=>{Xo(),await Ot(),process.exit(0)}),fr.command("status","Show daemon and authentication status",{},async e=>{await qn("daemon"),console.log(""),await async function(){const e=await le.readCredentials();if(console.log(P.bold("\nAuthentication Status\n")),!e)return void console.log(P.red("✗ Not authenticated"));console.log(P.green("✓ Authenticated"));const t=e.token.substring(0,30)+"...";console.log(P.gray(` Token: ${t}`)),e.machineId?(console.log(P.green("✓ Machine registered")),console.log(P.gray(` Machine ID: ${e.machineId}`)),console.log(P.gray(` Host: ${n.hostname()}`))):console.log(P.yellow("⚠️ Machine not registered")),console.log(P.gray(`\n Data directory: ${le.agentrixHomeDir}`));try{await Pt()?console.log(P.green("✓ Daemon running")):console.log(P.gray("✗ Daemon not running"))}catch{console.log(P.gray("✗ Daemon not running"))}}(),process.exit(0)}),fr.command("ls","List active sessions",{},async e=>{try{const e=await async function(){return(await $t("/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)}),fr.command("killall","Clean up all runaway agentrix processes",{},async()=>{const e=await async function(){const e=await async function(){return(await On()).filter(e=>e.pid!==process.pid&&("daemon"===e.type||"worker"===e.type||"upgrade-daemon"===e.type)).map(e=>({pid:e.pid,command:e.command}))}(),t=[];let n=0;for(const{pid:s,command:a}of e)try{if(console.log(`Killing runaway process PID ${s}: ${a}`),"win32"===process.platform){const e=He.sync("taskkill",["/F","/PID",s.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(s,"SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),(await Le()).find(e=>e.pid===s)&&(console.log(`Process PID ${s} ignored SIGTERM, using SIGKILL`),process.kill(s,"SIGKILL"));console.log(`Successfully killed runaway process PID ${s}`),n++}catch(e){const n=e.message;t.push({pid:s,error:n}),console.log(`Failed to kill process PID ${s}: ${n}`)}return{killed:n,errors:t}}();console.log(`Cleaned up ${e.killed} runaway processes`),e.errors.length>0&&console.log("Errors:",e.errors),process.exit(0)}),function(e){e.command("git-server","Manage local private GitLab server config",e=>e.command("add","Add a private GitLab server to local daemon config",e=>e.option("base-url",{type:"string",describe:"GitLab base URL, for example https://gitlab.example.com"}).option("api-url",{type:"string",describe:"GitLab API URL, defaults to <base-url>/api/v4"}).option("pat-file",{type:"string",nargs:1,describe:"Read GitLab PAT from a file, or - for stdin"}),async e=>{try{await nr(e),process.exit(0)}catch(e){sr(e)}}).command("list","List local private GitLab server config",{},async()=>{try{await async function(){const e=await er(),t=await le.readDaemonState(),n=await async function(){return await $t("/git-server/list")}();if(n.error)throw new Error(`Backend Git server list failed: ${n.error}`);const s=(n.gitServers??[]).filter(e=>"gitlab"===e.type&&"local_pat"===e.authModeDefault).map(n=>function(e,t,n){const s=en(e.id)??{},a=tn(e.id,t)??{};return{id:e.id,type:"gitlab",baseUrl:e.baseUrl||s.baseUrl,apiUrl:e.apiUrl||s.apiUrl,webhookEndpointPath:Ne(e.id),webhookUrl:De(e.id,n),patConfigured:(i=e.id,Qt.hasPat(i)),patMeta:nn(e.id),webhookSecret:a.webhookSecret,projectTriggerTokens:a.projectTriggerTokens??{}};var i}(n,e,t));console.log(JSON.stringify(s,null,2))}(),process.exit(0)}catch(e){sr(e)}}).demandCommand(1,"Please specify one of: add, list").strict(),()=>{})}(fr),function(e){e.command("init","Initialize CLI dependencies, authentication, and LLM config",e=>e.option("skip-deps",{type:"boolean",default:!1,describe:"Skip dependency installation"}).option("skip-daemon",{type:"boolean",default:!1,describe:"Do not start the daemon after initialization"}).option("force",{type:"boolean",default:!1,describe:"Overwrite existing Claude/Codex config files without prompting"}),async e=>{try{await hr({skipDeps:e.skipDeps,skipDaemon:e.skipDaemon,force:e.force}),process.exit(0)}catch(e){console.error(P.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}})}(fr),fr.command("kill <sessionId>","Stop a specific session",e=>e.positional("sessionId",{type:"string",describe:"Session ID to stop"}),async e=>{try{const t=await async function(e){return(await $t("/stop-session",{sessionId:e})).success||!1}(e.sessionId);console.log(t?P.green("✓ Session stopped"):P.red("Failed to stop session"))}catch(e){console.log(P.red("No daemon running"))}process.exit(0)}),fr.command("daemon",!1,{},async e=>{try{await jt()}catch(e){console.error(P.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}await ua(),process.exit(0)}),fr.command("worker",!1,e=>e.option("type",{type:"string",choices:Do,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 t=e.type,n=No[t];if(!n)throw new Error(`Unsupported worker type: ${String(e.type)}`);const s=e["started-by"],a=await jt(),i=e["user-id"],o=e["task-id"],r=e["idle-timeout"];await n.run({credentials:a,startedBy:s,userId:i,taskId:o,idleTimeoutSecond:r})}catch(e){console.error(P.red("Error:"),e instanceof Error?e.message:"Unknown error"),process.env.DEBUG&&console.error(e),process.exit(1)}}),fr.command("upgrade-daemon",!1,{},async e=>{const{startUpgradeDaemon:t}=await Promise.resolve().then(function(){return Jo});await t(),process.exit(0)}),fr.command("start","Start daemon (if not running) and show status",{},async e=>{try{await jt()}catch(e){console.error(P.red("Error:"),e instanceof Error?e.message:"Authentication failed"),process.env.DEBUG&&console.error(e),process.exit(1)}const t=Un();if(t.ok||(console.log(P.bold.red("\n⚠️ Missing Critical Dependencies")),console.log(P.yellow(`Cannot start daemon. Missing: ${t.missing.join(", ")}`)),console.log(P.blue('\nRun "agentrix doctor" for detailed dependency information and installation instructions.')),process.exit(1)),!await Rt()){console.log("Starting Agentrix background service..."),Zs(["daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();let e=!1;for(let t=0;t<50;t++)if(await new Promise(e=>setTimeout(e,100)),await Pt()){e=!0;break}e?(await new Promise(e=>setTimeout(e,1200)),await Pt()?console.log(P.green("✓ Daemon started successfully")):await async function(){const e=await async function(){const e=w(le.getStatePaths().logsDir,"daemon.log");try{return(await vt(e,"utf8")).trim().split("\n").filter(Boolean).slice(-12).join("\n")||null}catch{return null}}();if(console.log(P.red("✗ Daemon exited shortly after startup")),!e)return;const t=e.split("\n").reverse().find(e=>e.includes("Machine binding revoked")||e.includes("Run `agentrix logout` and bind again"));t?console.log(P.yellow(t)):(console.log(P.gray("Recent daemon log:")),console.log(e))}()):console.log(P.yellow("⚠️ Daemon may still be starting..."))}if(jo()){const e=await Uo();e.hasUpgrade&&(n=e).hasUpgrade&&n.latestVersion&&(console.log(""),console.log(P.yellow("┌────────────────────────────────────────────────────┐")),console.log(P.yellow("│")+" "+P.bold("Upgrade Available")+" "+P.yellow("│")),console.log(P.yellow("│")+" "+P.yellow("│")),console.log(P.yellow("│")+` Current: ${P.dim(n.currentVersion)} → Latest: ${P.green.bold(n.latestVersion)} `+P.yellow("│")),console.log(P.yellow("│")+" "+P.yellow("│")),console.log(P.yellow("│")+" Run "+P.cyan.bold("agentrix upgrade")+" to upgrade "+P.yellow("│")),console.log(P.yellow("│")+" "+P.yellow("│")),console.log(P.yellow("│")+" To enable auto-upgrade, set: "+P.yellow("│")),console.log(P.yellow("│")+" "+P.dim("AGENTRIX_DISABLE_AUTO_UPGRADE=false")+" "+P.yellow("│")),console.log(P.yellow("└────────────────────────────────────────────────────┘")),console.log(""))}else Vo()||Zs(["upgrade-daemon"],{detached:!0,stdio:"ignore",env:process.env}).unref();var n;await qn("daemon"),process.exit(0)}),fr.demandCommand(1,"Please specify a command. Use --help to see available commands.").parse();
|